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 utility_pane;
21pub mod welcome;
22mod workspace_settings;
23
24pub use crate::notifications::NotificationFrame;
25pub use dock::Panel;
26pub use multi_workspace::{
27 DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace, NewWorkspaceInWindow,
28 NextWorkspaceInWindow, PreviousWorkspaceInWindow, Sidebar, SidebarEvent, SidebarHandle,
29 ToggleWorkspaceSidebar,
30};
31pub use path_list::PathList;
32pub use toast_layer::{ToastAction, ToastLayer, ToastView};
33
34use anyhow::{Context as _, Result, anyhow};
35use call::{ActiveCall, call_settings::CallSettings};
36use client::{
37 ChannelId, Client, ErrorExt, Status, TypedEnvelope, UserStore,
38 proto::{self, ErrorCode, PanelId, PeerId},
39};
40use collections::{HashMap, HashSet, hash_map};
41use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
42use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt};
43use futures::{
44 Future, FutureExt, StreamExt,
45 channel::{
46 mpsc::{self, UnboundedReceiver, UnboundedSender},
47 oneshot,
48 },
49 future::{Shared, try_join_all},
50};
51use gpui::{
52 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
53 CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
54 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
55 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
56 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
57 WindowOptions, actions, canvas, point, relative, size, transparent_black,
58};
59pub use history_manager::*;
60pub use item::{
61 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
62 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
63};
64use itertools::Itertools;
65use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
66pub use modal_layer::*;
67use node_runtime::NodeRuntime;
68use notifications::{
69 DetachAndPromptErr, Notifications, dismiss_app_notification,
70 simple_message_notification::MessageNotification,
71};
72pub use pane::*;
73pub use pane_group::{
74 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
75 SplitDirection,
76};
77use persistence::{DB, SerializedWindowBounds, model::SerializedWorkspace};
78pub use persistence::{
79 DB as WORKSPACE_DB, WorkspaceDb, delete_unloaded_items,
80 model::{ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation, SessionWorkspace},
81 read_serialized_multi_workspaces,
82};
83use postage::stream::Stream;
84use project::{
85 DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
86 WorktreeSettings,
87 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
88 project_settings::ProjectSettings,
89 toolchain_store::ToolchainStoreEvent,
90 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
91};
92use remote::{
93 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
94 remote_client::ConnectionIdentifier,
95};
96use schemars::JsonSchema;
97use serde::Deserialize;
98use session::AppSession;
99use settings::{
100 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
101};
102use shared_screen::SharedScreen;
103use sqlez::{
104 bindable::{Bind, Column, StaticColumnCount},
105 statement::Statement,
106};
107use status_bar::StatusBar;
108pub use status_bar::StatusItemView;
109use std::{
110 any::TypeId,
111 borrow::Cow,
112 cell::RefCell,
113 cmp,
114 collections::VecDeque,
115 env,
116 hash::Hash,
117 path::{Path, PathBuf},
118 process::ExitStatus,
119 rc::Rc,
120 sync::{
121 Arc, LazyLock, Weak,
122 atomic::{AtomicBool, AtomicUsize},
123 },
124 time::Duration,
125};
126use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
127use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
128pub use toolbar::{
129 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
130};
131pub use ui;
132use ui::{Window, prelude::*};
133use util::{
134 ResultExt, TryFutureExt,
135 paths::{PathStyle, SanitizedPath},
136 rel_path::RelPath,
137 serde::default_true,
138};
139use uuid::Uuid;
140pub use workspace_settings::{
141 AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
142 WorkspaceSettings,
143};
144use zed_actions::{Spawn, feedback::FileBugReport};
145
146use crate::{
147 item::ItemBufferKind,
148 notifications::NotificationId,
149 utility_pane::{UTILITY_PANE_MIN_WIDTH, utility_slot_for_dock_position},
150};
151use crate::{
152 persistence::{
153 SerializedAxis,
154 model::{DockData, DockStructure, SerializedItem, SerializedPane, SerializedPaneGroup},
155 },
156 security_modal::SecurityModal,
157 utility_pane::{DraggedUtilityPane, UtilityPaneFrame, UtilityPaneSlot, UtilityPaneState},
158};
159
160pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
161
162static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
163 env::var("ZED_WINDOW_SIZE")
164 .ok()
165 .as_deref()
166 .and_then(parse_pixel_size_env_var)
167});
168
169static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
170 env::var("ZED_WINDOW_POSITION")
171 .ok()
172 .as_deref()
173 .and_then(parse_pixel_position_env_var)
174});
175
176pub trait TerminalProvider {
177 fn spawn(
178 &self,
179 task: SpawnInTerminal,
180 window: &mut Window,
181 cx: &mut App,
182 ) -> Task<Option<Result<ExitStatus>>>;
183}
184
185pub trait DebuggerProvider {
186 // `active_buffer` is used to resolve build task's name against language-specific tasks.
187 fn start_session(
188 &self,
189 definition: DebugScenario,
190 task_context: SharedTaskContext,
191 active_buffer: Option<Entity<Buffer>>,
192 worktree_id: Option<WorktreeId>,
193 window: &mut Window,
194 cx: &mut App,
195 );
196
197 fn spawn_task_or_modal(
198 &self,
199 workspace: &mut Workspace,
200 action: &Spawn,
201 window: &mut Window,
202 cx: &mut Context<Workspace>,
203 );
204
205 fn task_scheduled(&self, cx: &mut App);
206 fn debug_scenario_scheduled(&self, cx: &mut App);
207 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
208
209 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
210}
211
212actions!(
213 workspace,
214 [
215 /// Activates the next pane in the workspace.
216 ActivateNextPane,
217 /// Activates the previous pane in the workspace.
218 ActivatePreviousPane,
219 /// Switches to the next window.
220 ActivateNextWindow,
221 /// Switches to the previous window.
222 ActivatePreviousWindow,
223 /// Adds a folder to the current project.
224 AddFolderToProject,
225 /// Clears all notifications.
226 ClearAllNotifications,
227 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
228 ClearNavigationHistory,
229 /// Closes the active dock.
230 CloseActiveDock,
231 /// Closes all docks.
232 CloseAllDocks,
233 /// Toggles all docks.
234 ToggleAllDocks,
235 /// Closes the current window.
236 CloseWindow,
237 /// Closes the current project.
238 CloseProject,
239 /// Opens the feedback dialog.
240 Feedback,
241 /// Follows the next collaborator in the session.
242 FollowNextCollaborator,
243 /// Moves the focused panel to the next position.
244 MoveFocusedPanelToNextPosition,
245 /// Creates a new file.
246 NewFile,
247 /// Creates a new file in a vertical split.
248 NewFileSplitVertical,
249 /// Creates a new file in a horizontal split.
250 NewFileSplitHorizontal,
251 /// Opens a new search.
252 NewSearch,
253 /// Opens a new window.
254 NewWindow,
255 /// Opens a file or directory.
256 Open,
257 /// Opens multiple files.
258 OpenFiles,
259 /// Opens the current location in terminal.
260 OpenInTerminal,
261 /// Opens the component preview.
262 OpenComponentPreview,
263 /// Reloads the active item.
264 ReloadActiveItem,
265 /// Resets the active dock to its default size.
266 ResetActiveDockSize,
267 /// Resets all open docks to their default sizes.
268 ResetOpenDocksSize,
269 /// Reloads the application
270 Reload,
271 /// Saves the current file with a new name.
272 SaveAs,
273 /// Saves without formatting.
274 SaveWithoutFormat,
275 /// Shuts down all debug adapters.
276 ShutdownDebugAdapters,
277 /// Suppresses the current notification.
278 SuppressNotification,
279 /// Toggles the bottom dock.
280 ToggleBottomDock,
281 /// Toggles centered layout mode.
282 ToggleCenteredLayout,
283 /// Toggles edit prediction feature globally for all files.
284 ToggleEditPrediction,
285 /// Toggles the left dock.
286 ToggleLeftDock,
287 /// Toggles the right dock.
288 ToggleRightDock,
289 /// Toggles zoom on the active pane.
290 ToggleZoom,
291 /// Toggles read-only mode for the active item (if supported by that item).
292 ToggleReadOnlyFile,
293 /// Zooms in on the active pane.
294 ZoomIn,
295 /// Zooms out of the active pane.
296 ZoomOut,
297 /// If any worktrees are in restricted mode, shows a modal with possible actions.
298 /// If the modal is shown already, closes it without trusting any worktree.
299 ToggleWorktreeSecurity,
300 /// Clears all trusted worktrees, placing them in restricted mode on next open.
301 /// Requires restart to take effect on already opened projects.
302 ClearTrustedWorktrees,
303 /// Stops following a collaborator.
304 Unfollow,
305 /// Restores the banner.
306 RestoreBanner,
307 /// Toggles expansion of the selected item.
308 ToggleExpandItem,
309 ]
310);
311
312/// Activates a specific pane by its index.
313#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
314#[action(namespace = workspace)]
315pub struct ActivatePane(pub usize);
316
317/// Moves an item to a specific pane by index.
318#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
319#[action(namespace = workspace)]
320#[serde(deny_unknown_fields)]
321pub struct MoveItemToPane {
322 #[serde(default = "default_1")]
323 pub destination: usize,
324 #[serde(default = "default_true")]
325 pub focus: bool,
326 #[serde(default)]
327 pub clone: bool,
328}
329
330fn default_1() -> usize {
331 1
332}
333
334/// Moves an item to a pane in the specified direction.
335#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
336#[action(namespace = workspace)]
337#[serde(deny_unknown_fields)]
338pub struct MoveItemToPaneInDirection {
339 #[serde(default = "default_right")]
340 pub direction: SplitDirection,
341 #[serde(default = "default_true")]
342 pub focus: bool,
343 #[serde(default)]
344 pub clone: bool,
345}
346
347/// Creates a new file in a split of the desired direction.
348#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
349#[action(namespace = workspace)]
350#[serde(deny_unknown_fields)]
351pub struct NewFileSplit(pub SplitDirection);
352
353fn default_right() -> SplitDirection {
354 SplitDirection::Right
355}
356
357/// Saves all open files in the workspace.
358#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
359#[action(namespace = workspace)]
360#[serde(deny_unknown_fields)]
361pub struct SaveAll {
362 #[serde(default)]
363 pub save_intent: Option<SaveIntent>,
364}
365
366/// Saves the current file with the specified options.
367#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
368#[action(namespace = workspace)]
369#[serde(deny_unknown_fields)]
370pub struct Save {
371 #[serde(default)]
372 pub save_intent: Option<SaveIntent>,
373}
374
375/// Closes all items and panes in the workspace.
376#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
377#[action(namespace = workspace)]
378#[serde(deny_unknown_fields)]
379pub struct CloseAllItemsAndPanes {
380 #[serde(default)]
381 pub save_intent: Option<SaveIntent>,
382}
383
384/// Closes all inactive tabs and panes in the workspace.
385#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
386#[action(namespace = workspace)]
387#[serde(deny_unknown_fields)]
388pub struct CloseInactiveTabsAndPanes {
389 #[serde(default)]
390 pub save_intent: Option<SaveIntent>,
391}
392
393/// Closes the active item across all panes.
394#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
395#[action(namespace = workspace)]
396#[serde(deny_unknown_fields)]
397pub struct CloseItemInAllPanes {
398 #[serde(default)]
399 pub save_intent: Option<SaveIntent>,
400 #[serde(default)]
401 pub close_pinned: bool,
402}
403
404/// Sends a sequence of keystrokes to the active element.
405#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
406#[action(namespace = workspace)]
407pub struct SendKeystrokes(pub String);
408
409actions!(
410 project_symbols,
411 [
412 /// Toggles the project symbols search.
413 #[action(name = "Toggle")]
414 ToggleProjectSymbols
415 ]
416);
417
418/// Toggles the file finder interface.
419#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
420#[action(namespace = file_finder, name = "Toggle")]
421#[serde(deny_unknown_fields)]
422pub struct ToggleFileFinder {
423 #[serde(default)]
424 pub separate_history: bool,
425}
426
427/// Opens a new terminal in the center.
428#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
429#[action(namespace = workspace)]
430#[serde(deny_unknown_fields)]
431pub struct NewCenterTerminal {
432 /// If true, creates a local terminal even in remote projects.
433 #[serde(default)]
434 pub local: bool,
435}
436
437/// Opens a new terminal.
438#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
439#[action(namespace = workspace)]
440#[serde(deny_unknown_fields)]
441pub struct NewTerminal {
442 /// If true, creates a local terminal even in remote projects.
443 #[serde(default)]
444 pub local: bool,
445}
446
447/// Increases size of a currently focused dock by a given amount of pixels.
448#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
449#[action(namespace = workspace)]
450#[serde(deny_unknown_fields)]
451pub struct IncreaseActiveDockSize {
452 /// For 0px parameter, uses UI font size value.
453 #[serde(default)]
454 pub px: u32,
455}
456
457/// Decreases size of a currently focused dock by a given amount of pixels.
458#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
459#[action(namespace = workspace)]
460#[serde(deny_unknown_fields)]
461pub struct DecreaseActiveDockSize {
462 /// For 0px parameter, uses UI font size value.
463 #[serde(default)]
464 pub px: u32,
465}
466
467/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
468#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
469#[action(namespace = workspace)]
470#[serde(deny_unknown_fields)]
471pub struct IncreaseOpenDocksSize {
472 /// For 0px parameter, uses UI font size value.
473 #[serde(default)]
474 pub px: u32,
475}
476
477/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
478#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
479#[action(namespace = workspace)]
480#[serde(deny_unknown_fields)]
481pub struct DecreaseOpenDocksSize {
482 /// For 0px parameter, uses UI font size value.
483 #[serde(default)]
484 pub px: u32,
485}
486
487actions!(
488 workspace,
489 [
490 /// Activates the pane to the left.
491 ActivatePaneLeft,
492 /// Activates the pane to the right.
493 ActivatePaneRight,
494 /// Activates the pane above.
495 ActivatePaneUp,
496 /// Activates the pane below.
497 ActivatePaneDown,
498 /// Swaps the current pane with the one to the left.
499 SwapPaneLeft,
500 /// Swaps the current pane with the one to the right.
501 SwapPaneRight,
502 /// Swaps the current pane with the one above.
503 SwapPaneUp,
504 /// Swaps the current pane with the one below.
505 SwapPaneDown,
506 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
507 SwapPaneAdjacent,
508 /// Move the current pane to be at the far left.
509 MovePaneLeft,
510 /// Move the current pane to be at the far right.
511 MovePaneRight,
512 /// Move the current pane to be at the very top.
513 MovePaneUp,
514 /// Move the current pane to be at the very bottom.
515 MovePaneDown,
516 ]
517);
518
519#[derive(PartialEq, Eq, Debug)]
520pub enum CloseIntent {
521 /// Quit the program entirely.
522 Quit,
523 /// Close a window.
524 CloseWindow,
525 /// Replace the workspace in an existing window.
526 ReplaceWindow,
527}
528
529#[derive(Clone)]
530pub struct Toast {
531 id: NotificationId,
532 msg: Cow<'static, str>,
533 autohide: bool,
534 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
535}
536
537impl Toast {
538 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
539 Toast {
540 id,
541 msg: msg.into(),
542 on_click: None,
543 autohide: false,
544 }
545 }
546
547 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
548 where
549 M: Into<Cow<'static, str>>,
550 F: Fn(&mut Window, &mut App) + 'static,
551 {
552 self.on_click = Some((message.into(), Arc::new(on_click)));
553 self
554 }
555
556 pub fn autohide(mut self) -> Self {
557 self.autohide = true;
558 self
559 }
560}
561
562impl PartialEq for Toast {
563 fn eq(&self, other: &Self) -> bool {
564 self.id == other.id
565 && self.msg == other.msg
566 && self.on_click.is_some() == other.on_click.is_some()
567 }
568}
569
570/// Opens a new terminal with the specified working directory.
571#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
572#[action(namespace = workspace)]
573#[serde(deny_unknown_fields)]
574pub struct OpenTerminal {
575 pub working_directory: PathBuf,
576 /// If true, creates a local terminal even in remote projects.
577 #[serde(default)]
578 pub local: bool,
579}
580
581#[derive(
582 Clone,
583 Copy,
584 Debug,
585 Default,
586 Hash,
587 PartialEq,
588 Eq,
589 PartialOrd,
590 Ord,
591 serde::Serialize,
592 serde::Deserialize,
593)]
594pub struct WorkspaceId(i64);
595
596impl WorkspaceId {
597 pub fn from_i64(value: i64) -> Self {
598 Self(value)
599 }
600}
601
602impl StaticColumnCount for WorkspaceId {}
603impl Bind for WorkspaceId {
604 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
605 self.0.bind(statement, start_index)
606 }
607}
608impl Column for WorkspaceId {
609 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
610 i64::column(statement, start_index)
611 .map(|(i, next_index)| (Self(i), next_index))
612 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
613 }
614}
615impl From<WorkspaceId> for i64 {
616 fn from(val: WorkspaceId) -> Self {
617 val.0
618 }
619}
620
621fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
622 let paths = cx.prompt_for_paths(options);
623 cx.spawn(
624 async move |cx| match paths.await.anyhow().and_then(|res| res) {
625 Ok(Some(paths)) => {
626 cx.update(|cx| {
627 open_paths(&paths, app_state, OpenOptions::default(), cx).detach_and_log_err(cx)
628 });
629 }
630 Ok(None) => {}
631 Err(err) => {
632 util::log_err(&err);
633 cx.update(|cx| {
634 if let Some(workspace_window) = cx
635 .active_window()
636 .and_then(|window| window.downcast::<MultiWorkspace>())
637 {
638 workspace_window
639 .update(cx, |multi_workspace, _, cx| {
640 let workspace = multi_workspace.workspace().clone();
641 workspace.update(cx, |workspace, cx| {
642 workspace.show_portal_error(err.to_string(), cx);
643 });
644 })
645 .ok();
646 }
647 });
648 }
649 },
650 )
651 .detach();
652}
653
654pub fn init(app_state: Arc<AppState>, cx: &mut App) {
655 component::init();
656 theme_preview::init(cx);
657 toast_layer::init(cx);
658 history_manager::init(app_state.fs.clone(), cx);
659
660 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
661 .on_action(|_: &Reload, cx| reload(cx))
662 .on_action({
663 let app_state = Arc::downgrade(&app_state);
664 move |_: &Open, cx: &mut App| {
665 if let Some(app_state) = app_state.upgrade() {
666 prompt_and_open_paths(
667 app_state,
668 PathPromptOptions {
669 files: true,
670 directories: true,
671 multiple: true,
672 prompt: None,
673 },
674 cx,
675 );
676 }
677 }
678 })
679 .on_action({
680 let app_state = Arc::downgrade(&app_state);
681 move |_: &OpenFiles, cx: &mut App| {
682 let directories = cx.can_select_mixed_files_and_dirs();
683 if let Some(app_state) = app_state.upgrade() {
684 prompt_and_open_paths(
685 app_state,
686 PathPromptOptions {
687 files: true,
688 directories,
689 multiple: true,
690 prompt: None,
691 },
692 cx,
693 );
694 }
695 }
696 });
697}
698
699type BuildProjectItemFn =
700 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
701
702type BuildProjectItemForPathFn =
703 fn(
704 &Entity<Project>,
705 &ProjectPath,
706 &mut Window,
707 &mut App,
708 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
709
710#[derive(Clone, Default)]
711struct ProjectItemRegistry {
712 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
713 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
714}
715
716impl ProjectItemRegistry {
717 fn register<T: ProjectItem>(&mut self) {
718 self.build_project_item_fns_by_type.insert(
719 TypeId::of::<T::Item>(),
720 |item, project, pane, window, cx| {
721 let item = item.downcast().unwrap();
722 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
723 as Box<dyn ItemHandle>
724 },
725 );
726 self.build_project_item_for_path_fns
727 .push(|project, project_path, window, cx| {
728 let project_path = project_path.clone();
729 let is_file = project
730 .read(cx)
731 .entry_for_path(&project_path, cx)
732 .is_some_and(|entry| entry.is_file());
733 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
734 let is_local = project.read(cx).is_local();
735 let project_item =
736 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
737 let project = project.clone();
738 Some(window.spawn(cx, async move |cx| {
739 match project_item.await.with_context(|| {
740 format!(
741 "opening project path {:?}",
742 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
743 )
744 }) {
745 Ok(project_item) => {
746 let project_item = project_item;
747 let project_entry_id: Option<ProjectEntryId> =
748 project_item.read_with(cx, project::ProjectItem::entry_id);
749 let build_workspace_item = Box::new(
750 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
751 Box::new(cx.new(|cx| {
752 T::for_project_item(
753 project,
754 Some(pane),
755 project_item,
756 window,
757 cx,
758 )
759 })) as Box<dyn ItemHandle>
760 },
761 ) as Box<_>;
762 Ok((project_entry_id, build_workspace_item))
763 }
764 Err(e) => {
765 log::warn!("Failed to open a project item: {e:#}");
766 if e.error_code() == ErrorCode::Internal {
767 if let Some(abs_path) =
768 entry_abs_path.as_deref().filter(|_| is_file)
769 {
770 if let Some(broken_project_item_view) =
771 cx.update(|window, cx| {
772 T::for_broken_project_item(
773 abs_path, is_local, &e, window, cx,
774 )
775 })?
776 {
777 let build_workspace_item = Box::new(
778 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
779 cx.new(|_| broken_project_item_view).boxed_clone()
780 },
781 )
782 as Box<_>;
783 return Ok((None, build_workspace_item));
784 }
785 }
786 }
787 Err(e)
788 }
789 }
790 }))
791 });
792 }
793
794 fn open_path(
795 &self,
796 project: &Entity<Project>,
797 path: &ProjectPath,
798 window: &mut Window,
799 cx: &mut App,
800 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
801 let Some(open_project_item) = self
802 .build_project_item_for_path_fns
803 .iter()
804 .rev()
805 .find_map(|open_project_item| open_project_item(project, path, window, cx))
806 else {
807 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
808 };
809 open_project_item
810 }
811
812 fn build_item<T: project::ProjectItem>(
813 &self,
814 item: Entity<T>,
815 project: Entity<Project>,
816 pane: Option<&Pane>,
817 window: &mut Window,
818 cx: &mut App,
819 ) -> Option<Box<dyn ItemHandle>> {
820 let build = self
821 .build_project_item_fns_by_type
822 .get(&TypeId::of::<T>())?;
823 Some(build(item.into_any(), project, pane, window, cx))
824 }
825}
826
827type WorkspaceItemBuilder =
828 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
829
830impl Global for ProjectItemRegistry {}
831
832/// Registers a [ProjectItem] for the app. When opening a file, all the registered
833/// items will get a chance to open the file, starting from the project item that
834/// was added last.
835pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
836 cx.default_global::<ProjectItemRegistry>().register::<I>();
837}
838
839#[derive(Default)]
840pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
841
842struct FollowableViewDescriptor {
843 from_state_proto: fn(
844 Entity<Workspace>,
845 ViewId,
846 &mut Option<proto::view::Variant>,
847 &mut Window,
848 &mut App,
849 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
850 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
851}
852
853impl Global for FollowableViewRegistry {}
854
855impl FollowableViewRegistry {
856 pub fn register<I: FollowableItem>(cx: &mut App) {
857 cx.default_global::<Self>().0.insert(
858 TypeId::of::<I>(),
859 FollowableViewDescriptor {
860 from_state_proto: |workspace, id, state, window, cx| {
861 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
862 cx.foreground_executor()
863 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
864 })
865 },
866 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
867 },
868 );
869 }
870
871 pub fn from_state_proto(
872 workspace: Entity<Workspace>,
873 view_id: ViewId,
874 mut state: Option<proto::view::Variant>,
875 window: &mut Window,
876 cx: &mut App,
877 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
878 cx.update_default_global(|this: &mut Self, cx| {
879 this.0.values().find_map(|descriptor| {
880 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
881 })
882 })
883 }
884
885 pub fn to_followable_view(
886 view: impl Into<AnyView>,
887 cx: &App,
888 ) -> Option<Box<dyn FollowableItemHandle>> {
889 let this = cx.try_global::<Self>()?;
890 let view = view.into();
891 let descriptor = this.0.get(&view.entity_type())?;
892 Some((descriptor.to_followable_view)(&view))
893 }
894}
895
896#[derive(Copy, Clone)]
897struct SerializableItemDescriptor {
898 deserialize: fn(
899 Entity<Project>,
900 WeakEntity<Workspace>,
901 WorkspaceId,
902 ItemId,
903 &mut Window,
904 &mut Context<Pane>,
905 ) -> Task<Result<Box<dyn ItemHandle>>>,
906 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
907 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
908}
909
910#[derive(Default)]
911struct SerializableItemRegistry {
912 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
913 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
914}
915
916impl Global for SerializableItemRegistry {}
917
918impl SerializableItemRegistry {
919 fn deserialize(
920 item_kind: &str,
921 project: Entity<Project>,
922 workspace: WeakEntity<Workspace>,
923 workspace_id: WorkspaceId,
924 item_item: ItemId,
925 window: &mut Window,
926 cx: &mut Context<Pane>,
927 ) -> Task<Result<Box<dyn ItemHandle>>> {
928 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
929 return Task::ready(Err(anyhow!(
930 "cannot deserialize {}, descriptor not found",
931 item_kind
932 )));
933 };
934
935 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
936 }
937
938 fn cleanup(
939 item_kind: &str,
940 workspace_id: WorkspaceId,
941 loaded_items: Vec<ItemId>,
942 window: &mut Window,
943 cx: &mut App,
944 ) -> Task<Result<()>> {
945 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
946 return Task::ready(Err(anyhow!(
947 "cannot cleanup {}, descriptor not found",
948 item_kind
949 )));
950 };
951
952 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
953 }
954
955 fn view_to_serializable_item_handle(
956 view: AnyView,
957 cx: &App,
958 ) -> Option<Box<dyn SerializableItemHandle>> {
959 let this = cx.try_global::<Self>()?;
960 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
961 Some((descriptor.view_to_serializable_item)(view))
962 }
963
964 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
965 let this = cx.try_global::<Self>()?;
966 this.descriptors_by_kind.get(item_kind).copied()
967 }
968}
969
970pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
971 let serialized_item_kind = I::serialized_item_kind();
972
973 let registry = cx.default_global::<SerializableItemRegistry>();
974 let descriptor = SerializableItemDescriptor {
975 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
976 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
977 cx.foreground_executor()
978 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
979 },
980 cleanup: |workspace_id, loaded_items, window, cx| {
981 I::cleanup(workspace_id, loaded_items, window, cx)
982 },
983 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
984 };
985 registry
986 .descriptors_by_kind
987 .insert(Arc::from(serialized_item_kind), descriptor);
988 registry
989 .descriptors_by_type
990 .insert(TypeId::of::<I>(), descriptor);
991}
992
993pub struct AppState {
994 pub languages: Arc<LanguageRegistry>,
995 pub client: Arc<Client>,
996 pub user_store: Entity<UserStore>,
997 pub workspace_store: Entity<WorkspaceStore>,
998 pub fs: Arc<dyn fs::Fs>,
999 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
1000 pub node_runtime: NodeRuntime,
1001 pub session: Entity<AppSession>,
1002}
1003
1004struct GlobalAppState(Weak<AppState>);
1005
1006impl Global for GlobalAppState {}
1007
1008pub struct WorkspaceStore {
1009 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1010 client: Arc<Client>,
1011 _subscriptions: Vec<client::Subscription>,
1012}
1013
1014#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1015pub enum CollaboratorId {
1016 PeerId(PeerId),
1017 Agent,
1018}
1019
1020impl From<PeerId> for CollaboratorId {
1021 fn from(peer_id: PeerId) -> Self {
1022 CollaboratorId::PeerId(peer_id)
1023 }
1024}
1025
1026impl From<&PeerId> for CollaboratorId {
1027 fn from(peer_id: &PeerId) -> Self {
1028 CollaboratorId::PeerId(*peer_id)
1029 }
1030}
1031
1032#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1033struct Follower {
1034 project_id: Option<u64>,
1035 peer_id: PeerId,
1036}
1037
1038impl AppState {
1039 #[track_caller]
1040 pub fn global(cx: &App) -> Weak<Self> {
1041 cx.global::<GlobalAppState>().0.clone()
1042 }
1043 pub fn try_global(cx: &App) -> Option<Weak<Self>> {
1044 cx.try_global::<GlobalAppState>()
1045 .map(|state| state.0.clone())
1046 }
1047 pub fn set_global(state: Weak<AppState>, cx: &mut App) {
1048 cx.set_global(GlobalAppState(state));
1049 }
1050
1051 #[cfg(any(test, feature = "test-support"))]
1052 pub fn test(cx: &mut App) -> Arc<Self> {
1053 use fs::Fs;
1054 use node_runtime::NodeRuntime;
1055 use session::Session;
1056 use settings::SettingsStore;
1057
1058 if !cx.has_global::<SettingsStore>() {
1059 let settings_store = SettingsStore::test(cx);
1060 cx.set_global(settings_store);
1061 }
1062
1063 let fs = fs::FakeFs::new(cx.background_executor().clone());
1064 <dyn Fs>::set_global(fs.clone(), cx);
1065 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1066 let clock = Arc::new(clock::FakeSystemClock::new());
1067 let http_client = http_client::FakeHttpClient::with_404_response();
1068 let client = Client::new(clock, http_client, cx);
1069 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1070 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1071 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1072
1073 theme::init(theme::LoadThemes::JustBase, cx);
1074 client::init(&client, cx);
1075
1076 Arc::new(Self {
1077 client,
1078 fs,
1079 languages,
1080 user_store,
1081 workspace_store,
1082 node_runtime: NodeRuntime::unavailable(),
1083 build_window_options: |_, _| Default::default(),
1084 session,
1085 })
1086 }
1087}
1088
1089struct DelayedDebouncedEditAction {
1090 task: Option<Task<()>>,
1091 cancel_channel: Option<oneshot::Sender<()>>,
1092}
1093
1094impl DelayedDebouncedEditAction {
1095 fn new() -> DelayedDebouncedEditAction {
1096 DelayedDebouncedEditAction {
1097 task: None,
1098 cancel_channel: None,
1099 }
1100 }
1101
1102 fn fire_new<F>(
1103 &mut self,
1104 delay: Duration,
1105 window: &mut Window,
1106 cx: &mut Context<Workspace>,
1107 func: F,
1108 ) where
1109 F: 'static
1110 + Send
1111 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1112 {
1113 if let Some(channel) = self.cancel_channel.take() {
1114 _ = channel.send(());
1115 }
1116
1117 let (sender, mut receiver) = oneshot::channel::<()>();
1118 self.cancel_channel = Some(sender);
1119
1120 let previous_task = self.task.take();
1121 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1122 let mut timer = cx.background_executor().timer(delay).fuse();
1123 if let Some(previous_task) = previous_task {
1124 previous_task.await;
1125 }
1126
1127 futures::select_biased! {
1128 _ = receiver => return,
1129 _ = timer => {}
1130 }
1131
1132 if let Some(result) = workspace
1133 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1134 .log_err()
1135 {
1136 result.await.log_err();
1137 }
1138 }));
1139 }
1140}
1141
1142pub enum Event {
1143 PaneAdded(Entity<Pane>),
1144 PaneRemoved,
1145 ItemAdded {
1146 item: Box<dyn ItemHandle>,
1147 },
1148 ActiveItemChanged,
1149 ItemRemoved {
1150 item_id: EntityId,
1151 },
1152 UserSavedItem {
1153 pane: WeakEntity<Pane>,
1154 item: Box<dyn WeakItemHandle>,
1155 save_intent: SaveIntent,
1156 },
1157 ContactRequestedJoin(u64),
1158 WorkspaceCreated(WeakEntity<Workspace>),
1159 OpenBundledFile {
1160 text: Cow<'static, str>,
1161 title: &'static str,
1162 language: &'static str,
1163 },
1164 ZoomChanged,
1165 ModalOpened,
1166}
1167
1168#[derive(Debug)]
1169pub enum OpenVisible {
1170 All,
1171 None,
1172 OnlyFiles,
1173 OnlyDirectories,
1174}
1175
1176enum WorkspaceLocation {
1177 // Valid local paths or SSH project to serialize
1178 Location(SerializedWorkspaceLocation, PathList),
1179 // No valid location found hence clear session id
1180 DetachFromSession,
1181 // No valid location found to serialize
1182 None,
1183}
1184
1185type PromptForNewPath = Box<
1186 dyn Fn(
1187 &mut Workspace,
1188 DirectoryLister,
1189 Option<String>,
1190 &mut Window,
1191 &mut Context<Workspace>,
1192 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1193>;
1194
1195type PromptForOpenPath = Box<
1196 dyn Fn(
1197 &mut Workspace,
1198 DirectoryLister,
1199 &mut Window,
1200 &mut Context<Workspace>,
1201 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1202>;
1203
1204#[derive(Default)]
1205struct DispatchingKeystrokes {
1206 dispatched: HashSet<Vec<Keystroke>>,
1207 queue: VecDeque<Keystroke>,
1208 task: Option<Shared<Task<()>>>,
1209}
1210
1211/// Collects everything project-related for a certain window opened.
1212/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1213///
1214/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1215/// The `Workspace` owns everybody's state and serves as a default, "global context",
1216/// that can be used to register a global action to be triggered from any place in the window.
1217pub struct Workspace {
1218 weak_self: WeakEntity<Self>,
1219 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1220 zoomed: Option<AnyWeakView>,
1221 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1222 zoomed_position: Option<DockPosition>,
1223 center: PaneGroup,
1224 left_dock: Entity<Dock>,
1225 bottom_dock: Entity<Dock>,
1226 right_dock: Entity<Dock>,
1227 panes: Vec<Entity<Pane>>,
1228 active_worktree_override: Option<WorktreeId>,
1229 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1230 active_pane: Entity<Pane>,
1231 last_active_center_pane: Option<WeakEntity<Pane>>,
1232 last_active_view_id: Option<proto::ViewId>,
1233 status_bar: Entity<StatusBar>,
1234 modal_layer: Entity<ModalLayer>,
1235 toast_layer: Entity<ToastLayer>,
1236 titlebar_item: Option<AnyView>,
1237 notifications: Notifications,
1238 suppressed_notifications: HashSet<NotificationId>,
1239 project: Entity<Project>,
1240 follower_states: HashMap<CollaboratorId, FollowerState>,
1241 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1242 window_edited: bool,
1243 last_window_title: Option<String>,
1244 dirty_items: HashMap<EntityId, Subscription>,
1245 active_call: Option<(Entity<ActiveCall>, Vec<Subscription>)>,
1246 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1247 database_id: Option<WorkspaceId>,
1248 app_state: Arc<AppState>,
1249 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1250 _subscriptions: Vec<Subscription>,
1251 _apply_leader_updates: Task<Result<()>>,
1252 _observe_current_user: Task<Result<()>>,
1253 _schedule_serialize_workspace: Option<Task<()>>,
1254 _schedule_serialize_ssh_paths: Option<Task<()>>,
1255 pane_history_timestamp: Arc<AtomicUsize>,
1256 bounds: Bounds<Pixels>,
1257 pub centered_layout: bool,
1258 bounds_save_task_queued: Option<Task<()>>,
1259 on_prompt_for_new_path: Option<PromptForNewPath>,
1260 on_prompt_for_open_path: Option<PromptForOpenPath>,
1261 terminal_provider: Option<Box<dyn TerminalProvider>>,
1262 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1263 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1264 _items_serializer: Task<Result<()>>,
1265 session_id: Option<String>,
1266 scheduled_tasks: Vec<Task<()>>,
1267 last_open_dock_positions: Vec<DockPosition>,
1268 removing: bool,
1269 utility_panes: UtilityPaneState,
1270}
1271
1272impl EventEmitter<Event> for Workspace {}
1273
1274#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1275pub struct ViewId {
1276 pub creator: CollaboratorId,
1277 pub id: u64,
1278}
1279
1280pub struct FollowerState {
1281 center_pane: Entity<Pane>,
1282 dock_pane: Option<Entity<Pane>>,
1283 active_view_id: Option<ViewId>,
1284 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1285}
1286
1287struct FollowerView {
1288 view: Box<dyn FollowableItemHandle>,
1289 location: Option<proto::PanelId>,
1290}
1291
1292impl Workspace {
1293 pub fn new(
1294 workspace_id: Option<WorkspaceId>,
1295 project: Entity<Project>,
1296 app_state: Arc<AppState>,
1297 window: &mut Window,
1298 cx: &mut Context<Self>,
1299 ) -> Self {
1300 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1301 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1302 if let TrustedWorktreesEvent::Trusted(..) = e {
1303 // Do not persist auto trusted worktrees
1304 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1305 worktrees_store.update(cx, |worktrees_store, cx| {
1306 worktrees_store.schedule_serialization(
1307 cx,
1308 |new_trusted_worktrees, cx| {
1309 let timeout =
1310 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1311 cx.background_spawn(async move {
1312 timeout.await;
1313 persistence::DB
1314 .save_trusted_worktrees(new_trusted_worktrees)
1315 .await
1316 .log_err();
1317 })
1318 },
1319 )
1320 });
1321 }
1322 }
1323 })
1324 .detach();
1325
1326 cx.observe_global::<SettingsStore>(|_, cx| {
1327 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1328 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1329 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1330 trusted_worktrees.auto_trust_all(cx);
1331 })
1332 }
1333 }
1334 })
1335 .detach();
1336 }
1337
1338 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1339 match event {
1340 project::Event::RemoteIdChanged(_) => {
1341 this.update_window_title(window, cx);
1342 }
1343
1344 project::Event::CollaboratorLeft(peer_id) => {
1345 this.collaborator_left(*peer_id, window, cx);
1346 }
1347
1348 &project::Event::WorktreeRemoved(id) | &project::Event::WorktreeAdded(id) => {
1349 this.update_window_title(window, cx);
1350 if this
1351 .project()
1352 .read(cx)
1353 .worktree_for_id(id, cx)
1354 .is_some_and(|wt| wt.read(cx).is_visible())
1355 {
1356 this.serialize_workspace(window, cx);
1357 this.update_history(cx);
1358 }
1359 }
1360 project::Event::WorktreeUpdatedEntries(..) => {
1361 this.update_window_title(window, cx);
1362 this.serialize_workspace(window, cx);
1363 }
1364
1365 project::Event::DisconnectedFromHost => {
1366 this.update_window_edited(window, cx);
1367 let leaders_to_unfollow =
1368 this.follower_states.keys().copied().collect::<Vec<_>>();
1369 for leader_id in leaders_to_unfollow {
1370 this.unfollow(leader_id, window, cx);
1371 }
1372 }
1373
1374 project::Event::DisconnectedFromRemote {
1375 server_not_running: _,
1376 } => {
1377 this.update_window_edited(window, cx);
1378 }
1379
1380 project::Event::Closed => {
1381 window.remove_window();
1382 }
1383
1384 project::Event::DeletedEntry(_, entry_id) => {
1385 for pane in this.panes.iter() {
1386 pane.update(cx, |pane, cx| {
1387 pane.handle_deleted_project_item(*entry_id, window, cx)
1388 });
1389 }
1390 }
1391
1392 project::Event::Toast {
1393 notification_id,
1394 message,
1395 link,
1396 } => this.show_notification(
1397 NotificationId::named(notification_id.clone()),
1398 cx,
1399 |cx| {
1400 let mut notification = MessageNotification::new(message.clone(), cx);
1401 if let Some(link) = link {
1402 notification = notification
1403 .more_info_message(link.label)
1404 .more_info_url(link.url);
1405 }
1406
1407 cx.new(|_| notification)
1408 },
1409 ),
1410
1411 project::Event::HideToast { notification_id } => {
1412 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1413 }
1414
1415 project::Event::LanguageServerPrompt(request) => {
1416 struct LanguageServerPrompt;
1417
1418 this.show_notification(
1419 NotificationId::composite::<LanguageServerPrompt>(request.id),
1420 cx,
1421 |cx| {
1422 cx.new(|cx| {
1423 notifications::LanguageServerPrompt::new(request.clone(), cx)
1424 })
1425 },
1426 );
1427 }
1428
1429 project::Event::AgentLocationChanged => {
1430 this.handle_agent_location_changed(window, cx)
1431 }
1432
1433 _ => {}
1434 }
1435 cx.notify()
1436 })
1437 .detach();
1438
1439 cx.subscribe_in(
1440 &project.read(cx).breakpoint_store(),
1441 window,
1442 |workspace, _, event, window, cx| match event {
1443 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1444 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1445 workspace.serialize_workspace(window, cx);
1446 }
1447 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1448 },
1449 )
1450 .detach();
1451 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1452 cx.subscribe_in(
1453 &toolchain_store,
1454 window,
1455 |workspace, _, event, window, cx| match event {
1456 ToolchainStoreEvent::CustomToolchainsModified => {
1457 workspace.serialize_workspace(window, cx);
1458 }
1459 _ => {}
1460 },
1461 )
1462 .detach();
1463 }
1464
1465 cx.on_focus_lost(window, |this, window, cx| {
1466 let focus_handle = this.focus_handle(cx);
1467 window.focus(&focus_handle, cx);
1468 })
1469 .detach();
1470
1471 let weak_handle = cx.entity().downgrade();
1472 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1473
1474 let center_pane = cx.new(|cx| {
1475 let mut center_pane = Pane::new(
1476 weak_handle.clone(),
1477 project.clone(),
1478 pane_history_timestamp.clone(),
1479 None,
1480 NewFile.boxed_clone(),
1481 true,
1482 window,
1483 cx,
1484 );
1485 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1486 center_pane.set_should_display_welcome_page(true);
1487 center_pane
1488 });
1489 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1490 .detach();
1491
1492 window.focus(¢er_pane.focus_handle(cx), cx);
1493
1494 cx.emit(Event::PaneAdded(center_pane.clone()));
1495
1496 let any_window_handle = window.window_handle();
1497 app_state.workspace_store.update(cx, |store, _| {
1498 store
1499 .workspaces
1500 .insert((any_window_handle, weak_handle.clone()));
1501 });
1502
1503 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1504 let mut connection_status = app_state.client.status();
1505 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1506 current_user.next().await;
1507 connection_status.next().await;
1508 let mut stream =
1509 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1510
1511 while stream.recv().await.is_some() {
1512 this.update(cx, |_, cx| cx.notify())?;
1513 }
1514 anyhow::Ok(())
1515 });
1516
1517 // All leader updates are enqueued and then processed in a single task, so
1518 // that each asynchronous operation can be run in order.
1519 let (leader_updates_tx, mut leader_updates_rx) =
1520 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1521 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1522 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1523 Self::process_leader_update(&this, leader_id, update, cx)
1524 .await
1525 .log_err();
1526 }
1527
1528 Ok(())
1529 });
1530
1531 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1532 let modal_layer = cx.new(|_| ModalLayer::new());
1533 let toast_layer = cx.new(|_| ToastLayer::new());
1534 cx.subscribe(
1535 &modal_layer,
1536 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1537 cx.emit(Event::ModalOpened);
1538 },
1539 )
1540 .detach();
1541
1542 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1543 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1544 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1545 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1546 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1547 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1548 let status_bar = cx.new(|cx| {
1549 let mut status_bar = StatusBar::new(¢er_pane.clone(), window, cx);
1550 status_bar.add_left_item(left_dock_buttons, window, cx);
1551 status_bar.add_right_item(right_dock_buttons, window, cx);
1552 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1553 status_bar
1554 });
1555
1556 let session_id = app_state.session.read(cx).id().to_owned();
1557
1558 let mut active_call = None;
1559 if let Some(call) = ActiveCall::try_global(cx) {
1560 let subscriptions = vec![cx.subscribe_in(&call, window, Self::on_active_call_event)];
1561 active_call = Some((call, subscriptions));
1562 }
1563
1564 let (serializable_items_tx, serializable_items_rx) =
1565 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1566 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1567 Self::serialize_items(&this, serializable_items_rx, cx).await
1568 });
1569
1570 let subscriptions = vec![
1571 cx.observe_window_activation(window, Self::on_window_activation_changed),
1572 cx.observe_window_bounds(window, move |this, window, cx| {
1573 if this.bounds_save_task_queued.is_some() {
1574 return;
1575 }
1576 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1577 cx.background_executor()
1578 .timer(Duration::from_millis(100))
1579 .await;
1580 this.update_in(cx, |this, window, cx| {
1581 if let Some(display) = window.display(cx)
1582 && let Ok(display_uuid) = display.uuid()
1583 {
1584 let window_bounds = window.inner_window_bounds();
1585 let has_paths = !this.root_paths(cx).is_empty();
1586 if !has_paths {
1587 cx.background_executor()
1588 .spawn(persistence::write_default_window_bounds(
1589 window_bounds,
1590 display_uuid,
1591 ))
1592 .detach_and_log_err(cx);
1593 }
1594 if let Some(database_id) = workspace_id {
1595 cx.background_executor()
1596 .spawn(DB.set_window_open_status(
1597 database_id,
1598 SerializedWindowBounds(window_bounds),
1599 display_uuid,
1600 ))
1601 .detach_and_log_err(cx);
1602 } else {
1603 cx.background_executor()
1604 .spawn(persistence::write_default_window_bounds(
1605 window_bounds,
1606 display_uuid,
1607 ))
1608 .detach_and_log_err(cx);
1609 }
1610 }
1611 this.bounds_save_task_queued.take();
1612 })
1613 .ok();
1614 }));
1615 cx.notify();
1616 }),
1617 cx.observe_window_appearance(window, |_, window, cx| {
1618 let window_appearance = window.appearance();
1619
1620 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1621
1622 GlobalTheme::reload_theme(cx);
1623 GlobalTheme::reload_icon_theme(cx);
1624 }),
1625 cx.on_release({
1626 let weak_handle = weak_handle.clone();
1627 move |this, cx| {
1628 this.app_state.workspace_store.update(cx, move |store, _| {
1629 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1630 })
1631 }
1632 }),
1633 ];
1634
1635 cx.defer_in(window, move |this, window, cx| {
1636 this.update_window_title(window, cx);
1637 this.show_initial_notifications(cx);
1638 });
1639
1640 let mut center = PaneGroup::new(center_pane.clone());
1641 center.set_is_center(true);
1642 center.mark_positions(cx);
1643
1644 Workspace {
1645 weak_self: weak_handle.clone(),
1646 zoomed: None,
1647 zoomed_position: None,
1648 previous_dock_drag_coordinates: None,
1649 center,
1650 panes: vec![center_pane.clone()],
1651 panes_by_item: Default::default(),
1652 active_pane: center_pane.clone(),
1653 last_active_center_pane: Some(center_pane.downgrade()),
1654 last_active_view_id: None,
1655 status_bar,
1656 modal_layer,
1657 toast_layer,
1658 titlebar_item: None,
1659 active_worktree_override: None,
1660 notifications: Notifications::default(),
1661 suppressed_notifications: HashSet::default(),
1662 left_dock,
1663 bottom_dock,
1664 right_dock,
1665 project: project.clone(),
1666 follower_states: Default::default(),
1667 last_leaders_by_pane: Default::default(),
1668 dispatching_keystrokes: Default::default(),
1669 window_edited: false,
1670 last_window_title: None,
1671 dirty_items: Default::default(),
1672 active_call,
1673 database_id: workspace_id,
1674 app_state,
1675 _observe_current_user,
1676 _apply_leader_updates,
1677 _schedule_serialize_workspace: None,
1678 _schedule_serialize_ssh_paths: None,
1679 leader_updates_tx,
1680 _subscriptions: subscriptions,
1681 pane_history_timestamp,
1682 workspace_actions: Default::default(),
1683 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1684 bounds: Default::default(),
1685 centered_layout: false,
1686 bounds_save_task_queued: None,
1687 on_prompt_for_new_path: None,
1688 on_prompt_for_open_path: None,
1689 terminal_provider: None,
1690 debugger_provider: None,
1691 serializable_items_tx,
1692 _items_serializer,
1693 session_id: Some(session_id),
1694
1695 scheduled_tasks: Vec::new(),
1696 last_open_dock_positions: Vec::new(),
1697 removing: false,
1698 utility_panes: UtilityPaneState::default(),
1699 }
1700 }
1701
1702 pub fn new_local(
1703 abs_paths: Vec<PathBuf>,
1704 app_state: Arc<AppState>,
1705 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1706 env: Option<HashMap<String, String>>,
1707 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1708 cx: &mut App,
1709 ) -> Task<
1710 anyhow::Result<(
1711 WindowHandle<MultiWorkspace>,
1712 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
1713 )>,
1714 > {
1715 let project_handle = Project::local(
1716 app_state.client.clone(),
1717 app_state.node_runtime.clone(),
1718 app_state.user_store.clone(),
1719 app_state.languages.clone(),
1720 app_state.fs.clone(),
1721 env,
1722 Default::default(),
1723 cx,
1724 );
1725
1726 cx.spawn(async move |cx| {
1727 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1728 for path in abs_paths.into_iter() {
1729 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1730 paths_to_open.push(canonical)
1731 } else {
1732 paths_to_open.push(path)
1733 }
1734 }
1735
1736 let serialized_workspace =
1737 persistence::DB.workspace_for_roots(paths_to_open.as_slice());
1738
1739 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1740 paths_to_open = paths.ordered_paths().cloned().collect();
1741 if !paths.is_lexicographically_ordered() {
1742 project_handle.update(cx, |project, cx| {
1743 project.set_worktrees_reordered(true, cx);
1744 });
1745 }
1746 }
1747
1748 // Get project paths for all of the abs_paths
1749 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1750 Vec::with_capacity(paths_to_open.len());
1751
1752 for path in paths_to_open.into_iter() {
1753 if let Some((_, project_entry)) = cx
1754 .update(|cx| {
1755 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1756 })
1757 .await
1758 .log_err()
1759 {
1760 project_paths.push((path, Some(project_entry)));
1761 } else {
1762 project_paths.push((path, None));
1763 }
1764 }
1765
1766 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1767 serialized_workspace.id
1768 } else {
1769 DB.next_id().await.unwrap_or_else(|_| Default::default())
1770 };
1771
1772 let toolchains = DB.toolchains(workspace_id).await?;
1773
1774 for (toolchain, worktree_path, path) in toolchains {
1775 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1776 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1777 this.find_worktree(&worktree_path, cx)
1778 .and_then(|(worktree, rel_path)| {
1779 if rel_path.is_empty() {
1780 Some(worktree.read(cx).id())
1781 } else {
1782 None
1783 }
1784 })
1785 }) else {
1786 // We did not find a worktree with a given path, but that's whatever.
1787 continue;
1788 };
1789 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1790 continue;
1791 }
1792
1793 project_handle
1794 .update(cx, |this, cx| {
1795 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1796 })
1797 .await;
1798 }
1799 if let Some(workspace) = serialized_workspace.as_ref() {
1800 project_handle.update(cx, |this, cx| {
1801 for (scope, toolchains) in &workspace.user_toolchains {
1802 for toolchain in toolchains {
1803 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1804 }
1805 }
1806 });
1807 }
1808
1809 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1810 if let Some(window) = requesting_window {
1811 let centered_layout = serialized_workspace
1812 .as_ref()
1813 .map(|w| w.centered_layout)
1814 .unwrap_or(false);
1815
1816 let workspace = window.update(cx, |multi_workspace, window, cx| {
1817 let workspace = cx.new(|cx| {
1818 let mut workspace = Workspace::new(
1819 Some(workspace_id),
1820 project_handle.clone(),
1821 app_state.clone(),
1822 window,
1823 cx,
1824 );
1825
1826 workspace.centered_layout = centered_layout;
1827
1828 // Call init callback to add items before window renders
1829 if let Some(init) = init {
1830 init(&mut workspace, window, cx);
1831 }
1832
1833 workspace
1834 });
1835 multi_workspace.activate(workspace.clone(), cx);
1836 workspace
1837 })?;
1838 (window, workspace)
1839 } else {
1840 let window_bounds_override = window_bounds_env_override();
1841
1842 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1843 (Some(WindowBounds::Windowed(bounds)), None)
1844 } else if let Some(workspace) = serialized_workspace.as_ref()
1845 && let Some(display) = workspace.display
1846 && let Some(bounds) = workspace.window_bounds.as_ref()
1847 {
1848 // Reopening an existing workspace - restore its saved bounds
1849 (Some(bounds.0), Some(display))
1850 } else if let Some((display, bounds)) =
1851 persistence::read_default_window_bounds()
1852 {
1853 // New or empty workspace - use the last known window bounds
1854 (Some(bounds), Some(display))
1855 } else {
1856 // New window - let GPUI's default_bounds() handle cascading
1857 (None, None)
1858 };
1859
1860 // Use the serialized workspace to construct the new window
1861 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1862 options.window_bounds = window_bounds;
1863 let centered_layout = serialized_workspace
1864 .as_ref()
1865 .map(|w| w.centered_layout)
1866 .unwrap_or(false);
1867 let window = cx.open_window(options, {
1868 let app_state = app_state.clone();
1869 let project_handle = project_handle.clone();
1870 move |window, cx| {
1871 let workspace = cx.new(|cx| {
1872 let mut workspace = Workspace::new(
1873 Some(workspace_id),
1874 project_handle,
1875 app_state,
1876 window,
1877 cx,
1878 );
1879 workspace.centered_layout = centered_layout;
1880
1881 // Call init callback to add items before window renders
1882 if let Some(init) = init {
1883 init(&mut workspace, window, cx);
1884 }
1885
1886 workspace
1887 });
1888 cx.new(|cx| MultiWorkspace::new(workspace, cx))
1889 }
1890 })?;
1891 let workspace =
1892 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
1893 multi_workspace.workspace().clone()
1894 })?;
1895 (window, workspace)
1896 };
1897
1898 notify_if_database_failed(window, cx);
1899 // Check if this is an empty workspace (no paths to open)
1900 // An empty workspace is one where project_paths is empty
1901 let is_empty_workspace = project_paths.is_empty();
1902 // Check if serialized workspace has paths before it's moved
1903 let serialized_workspace_has_paths = serialized_workspace
1904 .as_ref()
1905 .map(|ws| !ws.paths.is_empty())
1906 .unwrap_or(false);
1907
1908 let opened_items = window
1909 .update(cx, |_, window, cx| {
1910 workspace.update(cx, |_workspace: &mut Workspace, cx| {
1911 open_items(serialized_workspace, project_paths, window, cx)
1912 })
1913 })?
1914 .await
1915 .unwrap_or_default();
1916
1917 // Restore default dock state for empty workspaces
1918 // Only restore if:
1919 // 1. This is an empty workspace (no paths), AND
1920 // 2. The serialized workspace either doesn't exist or has no paths
1921 if is_empty_workspace && !serialized_workspace_has_paths {
1922 if let Some(default_docks) = persistence::read_default_dock_state() {
1923 window
1924 .update(cx, |_, window, cx| {
1925 workspace.update(cx, |workspace, cx| {
1926 for (dock, serialized_dock) in [
1927 (&workspace.right_dock, &default_docks.right),
1928 (&workspace.left_dock, &default_docks.left),
1929 (&workspace.bottom_dock, &default_docks.bottom),
1930 ] {
1931 dock.update(cx, |dock, cx| {
1932 dock.serialized_dock = Some(serialized_dock.clone());
1933 dock.restore_state(window, cx);
1934 });
1935 }
1936 cx.notify();
1937 });
1938 })
1939 .log_err();
1940 }
1941 }
1942
1943 window
1944 .update(cx, |_, _window, cx| {
1945 workspace.update(cx, |this: &mut Workspace, cx| {
1946 this.update_history(cx);
1947 });
1948 })
1949 .log_err();
1950 Ok((window, opened_items))
1951 })
1952 }
1953
1954 pub fn weak_handle(&self) -> WeakEntity<Self> {
1955 self.weak_self.clone()
1956 }
1957
1958 pub fn left_dock(&self) -> &Entity<Dock> {
1959 &self.left_dock
1960 }
1961
1962 pub fn bottom_dock(&self) -> &Entity<Dock> {
1963 &self.bottom_dock
1964 }
1965
1966 pub fn set_bottom_dock_layout(
1967 &mut self,
1968 layout: BottomDockLayout,
1969 window: &mut Window,
1970 cx: &mut Context<Self>,
1971 ) {
1972 let fs = self.project().read(cx).fs();
1973 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
1974 content.workspace.bottom_dock_layout = Some(layout);
1975 });
1976
1977 cx.notify();
1978 self.serialize_workspace(window, cx);
1979 }
1980
1981 pub fn right_dock(&self) -> &Entity<Dock> {
1982 &self.right_dock
1983 }
1984
1985 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
1986 [&self.left_dock, &self.bottom_dock, &self.right_dock]
1987 }
1988
1989 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
1990 match position {
1991 DockPosition::Left => &self.left_dock,
1992 DockPosition::Bottom => &self.bottom_dock,
1993 DockPosition::Right => &self.right_dock,
1994 }
1995 }
1996
1997 pub fn is_edited(&self) -> bool {
1998 self.window_edited
1999 }
2000
2001 pub fn add_panel<T: Panel>(
2002 &mut self,
2003 panel: Entity<T>,
2004 window: &mut Window,
2005 cx: &mut Context<Self>,
2006 ) {
2007 let focus_handle = panel.panel_focus_handle(cx);
2008 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2009 .detach();
2010
2011 let dock_position = panel.position(window, cx);
2012 let dock = self.dock_at_position(dock_position);
2013
2014 dock.update(cx, |dock, cx| {
2015 dock.add_panel(panel, self.weak_self.clone(), window, cx)
2016 });
2017 }
2018
2019 pub fn remove_panel<T: Panel>(
2020 &mut self,
2021 panel: &Entity<T>,
2022 window: &mut Window,
2023 cx: &mut Context<Self>,
2024 ) {
2025 let mut found_in_dock = None;
2026 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2027 let found = dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2028
2029 if found {
2030 found_in_dock = Some(dock.clone());
2031 }
2032 }
2033 if let Some(found_in_dock) = found_in_dock {
2034 let position = found_in_dock.read(cx).position();
2035 let slot = utility_slot_for_dock_position(position);
2036 self.clear_utility_pane_if_provider(slot, Entity::entity_id(panel), cx);
2037 }
2038 }
2039
2040 pub fn status_bar(&self) -> &Entity<StatusBar> {
2041 &self.status_bar
2042 }
2043
2044 pub fn set_workspace_sidebar_open(&self, open: bool, cx: &mut App) {
2045 self.status_bar.update(cx, |status_bar, cx| {
2046 status_bar.set_workspace_sidebar_open(open, cx);
2047 });
2048 }
2049
2050 pub fn status_bar_visible(&self, cx: &App) -> bool {
2051 StatusBarSettings::get_global(cx).show
2052 }
2053
2054 pub fn app_state(&self) -> &Arc<AppState> {
2055 &self.app_state
2056 }
2057
2058 pub fn user_store(&self) -> &Entity<UserStore> {
2059 &self.app_state.user_store
2060 }
2061
2062 pub fn project(&self) -> &Entity<Project> {
2063 &self.project
2064 }
2065
2066 pub fn path_style(&self, cx: &App) -> PathStyle {
2067 self.project.read(cx).path_style(cx)
2068 }
2069
2070 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2071 let mut history: HashMap<EntityId, usize> = HashMap::default();
2072
2073 for pane_handle in &self.panes {
2074 let pane = pane_handle.read(cx);
2075
2076 for entry in pane.activation_history() {
2077 history.insert(
2078 entry.entity_id,
2079 history
2080 .get(&entry.entity_id)
2081 .cloned()
2082 .unwrap_or(0)
2083 .max(entry.timestamp),
2084 );
2085 }
2086 }
2087
2088 history
2089 }
2090
2091 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2092 let mut recent_item: Option<Entity<T>> = None;
2093 let mut recent_timestamp = 0;
2094 for pane_handle in &self.panes {
2095 let pane = pane_handle.read(cx);
2096 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2097 pane.items().map(|item| (item.item_id(), item)).collect();
2098 for entry in pane.activation_history() {
2099 if entry.timestamp > recent_timestamp
2100 && let Some(&item) = item_map.get(&entry.entity_id)
2101 && let Some(typed_item) = item.act_as::<T>(cx)
2102 {
2103 recent_timestamp = entry.timestamp;
2104 recent_item = Some(typed_item);
2105 }
2106 }
2107 }
2108 recent_item
2109 }
2110
2111 pub fn recent_navigation_history_iter(
2112 &self,
2113 cx: &App,
2114 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2115 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2116 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2117
2118 for pane in &self.panes {
2119 let pane = pane.read(cx);
2120
2121 pane.nav_history()
2122 .for_each_entry(cx, |entry, (project_path, fs_path)| {
2123 if let Some(fs_path) = &fs_path {
2124 abs_paths_opened
2125 .entry(fs_path.clone())
2126 .or_default()
2127 .insert(project_path.clone());
2128 }
2129 let timestamp = entry.timestamp;
2130 match history.entry(project_path) {
2131 hash_map::Entry::Occupied(mut entry) => {
2132 let (_, old_timestamp) = entry.get();
2133 if ×tamp > old_timestamp {
2134 entry.insert((fs_path, timestamp));
2135 }
2136 }
2137 hash_map::Entry::Vacant(entry) => {
2138 entry.insert((fs_path, timestamp));
2139 }
2140 }
2141 });
2142
2143 if let Some(item) = pane.active_item()
2144 && let Some(project_path) = item.project_path(cx)
2145 {
2146 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2147
2148 if let Some(fs_path) = &fs_path {
2149 abs_paths_opened
2150 .entry(fs_path.clone())
2151 .or_default()
2152 .insert(project_path.clone());
2153 }
2154
2155 history.insert(project_path, (fs_path, std::usize::MAX));
2156 }
2157 }
2158
2159 history
2160 .into_iter()
2161 .sorted_by_key(|(_, (_, order))| *order)
2162 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2163 .rev()
2164 .filter(move |(history_path, abs_path)| {
2165 let latest_project_path_opened = abs_path
2166 .as_ref()
2167 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2168 .and_then(|project_paths| {
2169 project_paths
2170 .iter()
2171 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2172 });
2173
2174 latest_project_path_opened.is_none_or(|path| path == history_path)
2175 })
2176 }
2177
2178 pub fn recent_navigation_history(
2179 &self,
2180 limit: Option<usize>,
2181 cx: &App,
2182 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2183 self.recent_navigation_history_iter(cx)
2184 .take(limit.unwrap_or(usize::MAX))
2185 .collect()
2186 }
2187
2188 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2189 for pane in &self.panes {
2190 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2191 }
2192 }
2193
2194 fn navigate_history(
2195 &mut self,
2196 pane: WeakEntity<Pane>,
2197 mode: NavigationMode,
2198 window: &mut Window,
2199 cx: &mut Context<Workspace>,
2200 ) -> Task<Result<()>> {
2201 self.navigate_history_impl(pane, mode, window, |history, cx| history.pop(mode, cx), cx)
2202 }
2203
2204 fn navigate_tag_history(
2205 &mut self,
2206 pane: WeakEntity<Pane>,
2207 mode: TagNavigationMode,
2208 window: &mut Window,
2209 cx: &mut Context<Workspace>,
2210 ) -> Task<Result<()>> {
2211 self.navigate_history_impl(
2212 pane,
2213 NavigationMode::Normal,
2214 window,
2215 |history, _cx| history.pop_tag(mode),
2216 cx,
2217 )
2218 }
2219
2220 fn navigate_history_impl(
2221 &mut self,
2222 pane: WeakEntity<Pane>,
2223 mode: NavigationMode,
2224 window: &mut Window,
2225 mut cb: impl FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2226 cx: &mut Context<Workspace>,
2227 ) -> Task<Result<()>> {
2228 let to_load = if let Some(pane) = pane.upgrade() {
2229 pane.update(cx, |pane, cx| {
2230 window.focus(&pane.focus_handle(cx), cx);
2231 loop {
2232 // Retrieve the weak item handle from the history.
2233 let entry = cb(pane.nav_history_mut(), cx)?;
2234
2235 // If the item is still present in this pane, then activate it.
2236 if let Some(index) = entry
2237 .item
2238 .upgrade()
2239 .and_then(|v| pane.index_for_item(v.as_ref()))
2240 {
2241 let prev_active_item_index = pane.active_item_index();
2242 pane.nav_history_mut().set_mode(mode);
2243 pane.activate_item(index, true, true, window, cx);
2244 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2245
2246 let mut navigated = prev_active_item_index != pane.active_item_index();
2247 if let Some(data) = entry.data {
2248 navigated |= pane.active_item()?.navigate(data, window, cx);
2249 }
2250
2251 if navigated {
2252 break None;
2253 }
2254 } else {
2255 // If the item is no longer present in this pane, then retrieve its
2256 // path info in order to reopen it.
2257 break pane
2258 .nav_history()
2259 .path_for_item(entry.item.id())
2260 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2261 }
2262 }
2263 })
2264 } else {
2265 None
2266 };
2267
2268 if let Some((project_path, abs_path, entry)) = to_load {
2269 // If the item was no longer present, then load it again from its previous path, first try the local path
2270 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2271
2272 cx.spawn_in(window, async move |workspace, cx| {
2273 let open_by_project_path = open_by_project_path.await;
2274 let mut navigated = false;
2275 match open_by_project_path
2276 .with_context(|| format!("Navigating to {project_path:?}"))
2277 {
2278 Ok((project_entry_id, build_item)) => {
2279 let prev_active_item_id = pane.update(cx, |pane, _| {
2280 pane.nav_history_mut().set_mode(mode);
2281 pane.active_item().map(|p| p.item_id())
2282 })?;
2283
2284 pane.update_in(cx, |pane, window, cx| {
2285 let item = pane.open_item(
2286 project_entry_id,
2287 project_path,
2288 true,
2289 entry.is_preview,
2290 true,
2291 None,
2292 window, cx,
2293 build_item,
2294 );
2295 navigated |= Some(item.item_id()) != prev_active_item_id;
2296 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2297 if let Some(data) = entry.data {
2298 navigated |= item.navigate(data, window, cx);
2299 }
2300 })?;
2301 }
2302 Err(open_by_project_path_e) => {
2303 // Fall back to opening by abs path, in case an external file was opened and closed,
2304 // and its worktree is now dropped
2305 if let Some(abs_path) = abs_path {
2306 let prev_active_item_id = pane.update(cx, |pane, _| {
2307 pane.nav_history_mut().set_mode(mode);
2308 pane.active_item().map(|p| p.item_id())
2309 })?;
2310 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2311 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2312 })?;
2313 match open_by_abs_path
2314 .await
2315 .with_context(|| format!("Navigating to {abs_path:?}"))
2316 {
2317 Ok(item) => {
2318 pane.update_in(cx, |pane, window, cx| {
2319 navigated |= Some(item.item_id()) != prev_active_item_id;
2320 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2321 if let Some(data) = entry.data {
2322 navigated |= item.navigate(data, window, cx);
2323 }
2324 })?;
2325 }
2326 Err(open_by_abs_path_e) => {
2327 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2328 }
2329 }
2330 }
2331 }
2332 }
2333
2334 if !navigated {
2335 workspace
2336 .update_in(cx, |workspace, window, cx| {
2337 Self::navigate_history(workspace, pane, mode, window, cx)
2338 })?
2339 .await?;
2340 }
2341
2342 Ok(())
2343 })
2344 } else {
2345 Task::ready(Ok(()))
2346 }
2347 }
2348
2349 pub fn go_back(
2350 &mut self,
2351 pane: WeakEntity<Pane>,
2352 window: &mut Window,
2353 cx: &mut Context<Workspace>,
2354 ) -> Task<Result<()>> {
2355 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2356 }
2357
2358 pub fn go_forward(
2359 &mut self,
2360 pane: WeakEntity<Pane>,
2361 window: &mut Window,
2362 cx: &mut Context<Workspace>,
2363 ) -> Task<Result<()>> {
2364 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2365 }
2366
2367 pub fn reopen_closed_item(
2368 &mut self,
2369 window: &mut Window,
2370 cx: &mut Context<Workspace>,
2371 ) -> Task<Result<()>> {
2372 self.navigate_history(
2373 self.active_pane().downgrade(),
2374 NavigationMode::ReopeningClosedItem,
2375 window,
2376 cx,
2377 )
2378 }
2379
2380 pub fn client(&self) -> &Arc<Client> {
2381 &self.app_state.client
2382 }
2383
2384 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2385 self.titlebar_item = Some(item);
2386 cx.notify();
2387 }
2388
2389 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2390 self.on_prompt_for_new_path = Some(prompt)
2391 }
2392
2393 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2394 self.on_prompt_for_open_path = Some(prompt)
2395 }
2396
2397 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2398 self.terminal_provider = Some(Box::new(provider));
2399 }
2400
2401 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2402 self.debugger_provider = Some(Arc::new(provider));
2403 }
2404
2405 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2406 self.debugger_provider.clone()
2407 }
2408
2409 pub fn prompt_for_open_path(
2410 &mut self,
2411 path_prompt_options: PathPromptOptions,
2412 lister: DirectoryLister,
2413 window: &mut Window,
2414 cx: &mut Context<Self>,
2415 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2416 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2417 let prompt = self.on_prompt_for_open_path.take().unwrap();
2418 let rx = prompt(self, lister, window, cx);
2419 self.on_prompt_for_open_path = Some(prompt);
2420 rx
2421 } else {
2422 let (tx, rx) = oneshot::channel();
2423 let abs_path = cx.prompt_for_paths(path_prompt_options);
2424
2425 cx.spawn_in(window, async move |workspace, cx| {
2426 let Ok(result) = abs_path.await else {
2427 return Ok(());
2428 };
2429
2430 match result {
2431 Ok(result) => {
2432 tx.send(result).ok();
2433 }
2434 Err(err) => {
2435 let rx = workspace.update_in(cx, |workspace, window, cx| {
2436 workspace.show_portal_error(err.to_string(), cx);
2437 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2438 let rx = prompt(workspace, lister, window, cx);
2439 workspace.on_prompt_for_open_path = Some(prompt);
2440 rx
2441 })?;
2442 if let Ok(path) = rx.await {
2443 tx.send(path).ok();
2444 }
2445 }
2446 };
2447 anyhow::Ok(())
2448 })
2449 .detach();
2450
2451 rx
2452 }
2453 }
2454
2455 pub fn prompt_for_new_path(
2456 &mut self,
2457 lister: DirectoryLister,
2458 suggested_name: Option<String>,
2459 window: &mut Window,
2460 cx: &mut Context<Self>,
2461 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2462 if self.project.read(cx).is_via_collab()
2463 || self.project.read(cx).is_via_remote_server()
2464 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2465 {
2466 let prompt = self.on_prompt_for_new_path.take().unwrap();
2467 let rx = prompt(self, lister, suggested_name, window, cx);
2468 self.on_prompt_for_new_path = Some(prompt);
2469 return rx;
2470 }
2471
2472 let (tx, rx) = oneshot::channel();
2473 cx.spawn_in(window, async move |workspace, cx| {
2474 let abs_path = workspace.update(cx, |workspace, cx| {
2475 let relative_to = workspace
2476 .most_recent_active_path(cx)
2477 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2478 .or_else(|| {
2479 let project = workspace.project.read(cx);
2480 project.visible_worktrees(cx).find_map(|worktree| {
2481 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2482 })
2483 })
2484 .or_else(std::env::home_dir)
2485 .unwrap_or_else(|| PathBuf::from(""));
2486 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2487 })?;
2488 let abs_path = match abs_path.await? {
2489 Ok(path) => path,
2490 Err(err) => {
2491 let rx = workspace.update_in(cx, |workspace, window, cx| {
2492 workspace.show_portal_error(err.to_string(), cx);
2493
2494 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2495 let rx = prompt(workspace, lister, suggested_name, window, cx);
2496 workspace.on_prompt_for_new_path = Some(prompt);
2497 rx
2498 })?;
2499 if let Ok(path) = rx.await {
2500 tx.send(path).ok();
2501 }
2502 return anyhow::Ok(());
2503 }
2504 };
2505
2506 tx.send(abs_path.map(|path| vec![path])).ok();
2507 anyhow::Ok(())
2508 })
2509 .detach();
2510
2511 rx
2512 }
2513
2514 pub fn titlebar_item(&self) -> Option<AnyView> {
2515 self.titlebar_item.clone()
2516 }
2517
2518 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2519 /// When set, git-related operations should use this worktree instead of deriving
2520 /// the active worktree from the focused file.
2521 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2522 self.active_worktree_override
2523 }
2524
2525 pub fn set_active_worktree_override(
2526 &mut self,
2527 worktree_id: Option<WorktreeId>,
2528 cx: &mut Context<Self>,
2529 ) {
2530 self.active_worktree_override = worktree_id;
2531 cx.notify();
2532 }
2533
2534 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2535 self.active_worktree_override = None;
2536 cx.notify();
2537 }
2538
2539 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2540 ///
2541 /// If the given workspace has a local project, then it will be passed
2542 /// to the callback. Otherwise, a new empty window will be created.
2543 pub fn with_local_workspace<T, F>(
2544 &mut self,
2545 window: &mut Window,
2546 cx: &mut Context<Self>,
2547 callback: F,
2548 ) -> Task<Result<T>>
2549 where
2550 T: 'static,
2551 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2552 {
2553 if self.project.read(cx).is_local() {
2554 Task::ready(Ok(callback(self, window, cx)))
2555 } else {
2556 let env = self.project.read(cx).cli_environment(cx);
2557 let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, None, cx);
2558 cx.spawn_in(window, async move |_vh, cx| {
2559 let (multi_workspace_window, _) = task.await?;
2560 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2561 let workspace = multi_workspace.workspace().clone();
2562 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2563 })
2564 })
2565 }
2566 }
2567
2568 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2569 ///
2570 /// If the given workspace has a local project, then it will be passed
2571 /// to the callback. Otherwise, a new empty window will be created.
2572 pub fn with_local_or_wsl_workspace<T, F>(
2573 &mut self,
2574 window: &mut Window,
2575 cx: &mut Context<Self>,
2576 callback: F,
2577 ) -> Task<Result<T>>
2578 where
2579 T: 'static,
2580 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2581 {
2582 let project = self.project.read(cx);
2583 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
2584 Task::ready(Ok(callback(self, window, cx)))
2585 } else {
2586 let env = self.project.read(cx).cli_environment(cx);
2587 let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, None, cx);
2588 cx.spawn_in(window, async move |_vh, cx| {
2589 let (multi_workspace_window, _) = task.await?;
2590 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2591 let workspace = multi_workspace.workspace().clone();
2592 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2593 })
2594 })
2595 }
2596 }
2597
2598 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2599 self.project.read(cx).worktrees(cx)
2600 }
2601
2602 pub fn visible_worktrees<'a>(
2603 &self,
2604 cx: &'a App,
2605 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2606 self.project.read(cx).visible_worktrees(cx)
2607 }
2608
2609 #[cfg(any(test, feature = "test-support"))]
2610 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
2611 let futures = self
2612 .worktrees(cx)
2613 .filter_map(|worktree| worktree.read(cx).as_local())
2614 .map(|worktree| worktree.scan_complete())
2615 .collect::<Vec<_>>();
2616 async move {
2617 for future in futures {
2618 future.await;
2619 }
2620 }
2621 }
2622
2623 pub fn close_global(cx: &mut App) {
2624 cx.defer(|cx| {
2625 cx.windows().iter().find(|window| {
2626 window
2627 .update(cx, |_, window, _| {
2628 if window.is_window_active() {
2629 //This can only get called when the window's project connection has been lost
2630 //so we don't need to prompt the user for anything and instead just close the window
2631 window.remove_window();
2632 true
2633 } else {
2634 false
2635 }
2636 })
2637 .unwrap_or(false)
2638 });
2639 });
2640 }
2641
2642 pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
2643 let prepare = self.prepare_to_close(CloseIntent::CloseWindow, window, cx);
2644 cx.spawn_in(window, async move |_, cx| {
2645 if prepare.await? {
2646 cx.update(|window, _cx| window.remove_window())?;
2647 }
2648 anyhow::Ok(())
2649 })
2650 .detach_and_log_err(cx)
2651 }
2652
2653 pub fn move_focused_panel_to_next_position(
2654 &mut self,
2655 _: &MoveFocusedPanelToNextPosition,
2656 window: &mut Window,
2657 cx: &mut Context<Self>,
2658 ) {
2659 let docks = self.all_docks();
2660 let active_dock = docks
2661 .into_iter()
2662 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
2663
2664 if let Some(dock) = active_dock {
2665 dock.update(cx, |dock, cx| {
2666 let active_panel = dock
2667 .active_panel()
2668 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
2669
2670 if let Some(panel) = active_panel {
2671 panel.move_to_next_position(window, cx);
2672 }
2673 })
2674 }
2675 }
2676
2677 pub fn prepare_to_close(
2678 &mut self,
2679 close_intent: CloseIntent,
2680 window: &mut Window,
2681 cx: &mut Context<Self>,
2682 ) -> Task<Result<bool>> {
2683 let active_call = self.active_call().cloned();
2684
2685 cx.spawn_in(window, async move |this, cx| {
2686 this.update(cx, |this, _| {
2687 if close_intent == CloseIntent::CloseWindow {
2688 this.removing = true;
2689 }
2690 })?;
2691
2692 let workspace_count = cx.update(|_window, cx| {
2693 cx.windows()
2694 .iter()
2695 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
2696 .count()
2697 })?;
2698
2699 #[cfg(target_os = "macos")]
2700 let save_last_workspace = false;
2701
2702 // On Linux and Windows, closing the last window should restore the last workspace.
2703 #[cfg(not(target_os = "macos"))]
2704 let save_last_workspace = {
2705 let remaining_workspaces = cx.update(|_window, cx| {
2706 cx.windows()
2707 .iter()
2708 .filter_map(|window| window.downcast::<MultiWorkspace>())
2709 .filter_map(|multi_workspace| {
2710 multi_workspace
2711 .update(cx, |multi_workspace, _, cx| {
2712 multi_workspace.workspace().read(cx).removing
2713 })
2714 .ok()
2715 })
2716 .filter(|removing| !removing)
2717 .count()
2718 })?;
2719
2720 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
2721 };
2722
2723 if let Some(active_call) = active_call
2724 && workspace_count == 1
2725 && active_call.read_with(cx, |call, _| call.room().is_some())
2726 {
2727 if close_intent == CloseIntent::CloseWindow {
2728 let answer = cx.update(|window, cx| {
2729 window.prompt(
2730 PromptLevel::Warning,
2731 "Do you want to leave the current call?",
2732 None,
2733 &["Close window and hang up", "Cancel"],
2734 cx,
2735 )
2736 })?;
2737
2738 if answer.await.log_err() == Some(1) {
2739 return anyhow::Ok(false);
2740 } else {
2741 active_call
2742 .update(cx, |call, cx| call.hang_up(cx))
2743 .await
2744 .log_err();
2745 }
2746 }
2747 if close_intent == CloseIntent::ReplaceWindow {
2748 _ = active_call.update(cx, |this, cx| {
2749 let multi_workspace = cx
2750 .windows()
2751 .iter()
2752 .filter_map(|window| window.downcast::<MultiWorkspace>())
2753 .next()
2754 .unwrap();
2755 let project = multi_workspace
2756 .read(cx)?
2757 .workspace()
2758 .read(cx)
2759 .project
2760 .clone();
2761 if project.read(cx).is_shared() {
2762 this.unshare_project(project, cx)?;
2763 }
2764 Ok::<_, anyhow::Error>(())
2765 })?;
2766 }
2767 }
2768
2769 let save_result = this
2770 .update_in(cx, |this, window, cx| {
2771 this.save_all_internal(SaveIntent::Close, window, cx)
2772 })?
2773 .await;
2774
2775 // If we're not quitting, but closing, we remove the workspace from
2776 // the current session.
2777 if close_intent != CloseIntent::Quit
2778 && !save_last_workspace
2779 && save_result.as_ref().is_ok_and(|&res| res)
2780 {
2781 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
2782 .await;
2783 }
2784
2785 save_result
2786 })
2787 }
2788
2789 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
2790 self.save_all_internal(
2791 action.save_intent.unwrap_or(SaveIntent::SaveAll),
2792 window,
2793 cx,
2794 )
2795 .detach_and_log_err(cx);
2796 }
2797
2798 fn send_keystrokes(
2799 &mut self,
2800 action: &SendKeystrokes,
2801 window: &mut Window,
2802 cx: &mut Context<Self>,
2803 ) {
2804 let keystrokes: Vec<Keystroke> = action
2805 .0
2806 .split(' ')
2807 .flat_map(|k| Keystroke::parse(k).log_err())
2808 .map(|k| {
2809 cx.keyboard_mapper()
2810 .map_key_equivalent(k, false)
2811 .inner()
2812 .clone()
2813 })
2814 .collect();
2815 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
2816 }
2817
2818 pub fn send_keystrokes_impl(
2819 &mut self,
2820 keystrokes: Vec<Keystroke>,
2821 window: &mut Window,
2822 cx: &mut Context<Self>,
2823 ) -> Shared<Task<()>> {
2824 let mut state = self.dispatching_keystrokes.borrow_mut();
2825 if !state.dispatched.insert(keystrokes.clone()) {
2826 cx.propagate();
2827 return state.task.clone().unwrap();
2828 }
2829
2830 state.queue.extend(keystrokes);
2831
2832 let keystrokes = self.dispatching_keystrokes.clone();
2833 if state.task.is_none() {
2834 state.task = Some(
2835 window
2836 .spawn(cx, async move |cx| {
2837 // limit to 100 keystrokes to avoid infinite recursion.
2838 for _ in 0..100 {
2839 let mut state = keystrokes.borrow_mut();
2840 let Some(keystroke) = state.queue.pop_front() else {
2841 state.dispatched.clear();
2842 state.task.take();
2843 return;
2844 };
2845 drop(state);
2846 cx.update(|window, cx| {
2847 let focused = window.focused(cx);
2848 window.dispatch_keystroke(keystroke.clone(), cx);
2849 if window.focused(cx) != focused {
2850 // dispatch_keystroke may cause the focus to change.
2851 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
2852 // And we need that to happen before the next keystroke to keep vim mode happy...
2853 // (Note that the tests always do this implicitly, so you must manually test with something like:
2854 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
2855 // )
2856 window.draw(cx).clear();
2857 }
2858 })
2859 .ok();
2860 }
2861
2862 *keystrokes.borrow_mut() = Default::default();
2863 log::error!("over 100 keystrokes passed to send_keystrokes");
2864 })
2865 .shared(),
2866 );
2867 }
2868 state.task.clone().unwrap()
2869 }
2870
2871 fn save_all_internal(
2872 &mut self,
2873 mut save_intent: SaveIntent,
2874 window: &mut Window,
2875 cx: &mut Context<Self>,
2876 ) -> Task<Result<bool>> {
2877 if self.project.read(cx).is_disconnected(cx) {
2878 return Task::ready(Ok(true));
2879 }
2880 let dirty_items = self
2881 .panes
2882 .iter()
2883 .flat_map(|pane| {
2884 pane.read(cx).items().filter_map(|item| {
2885 if item.is_dirty(cx) {
2886 item.tab_content_text(0, cx);
2887 Some((pane.downgrade(), item.boxed_clone()))
2888 } else {
2889 None
2890 }
2891 })
2892 })
2893 .collect::<Vec<_>>();
2894
2895 let project = self.project.clone();
2896 cx.spawn_in(window, async move |workspace, cx| {
2897 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
2898 let (serialize_tasks, remaining_dirty_items) =
2899 workspace.update_in(cx, |workspace, window, cx| {
2900 let mut remaining_dirty_items = Vec::new();
2901 let mut serialize_tasks = Vec::new();
2902 for (pane, item) in dirty_items {
2903 if let Some(task) = item
2904 .to_serializable_item_handle(cx)
2905 .and_then(|handle| handle.serialize(workspace, true, window, cx))
2906 {
2907 serialize_tasks.push(task);
2908 } else {
2909 remaining_dirty_items.push((pane, item));
2910 }
2911 }
2912 (serialize_tasks, remaining_dirty_items)
2913 })?;
2914
2915 futures::future::try_join_all(serialize_tasks).await?;
2916
2917 if remaining_dirty_items.len() > 1 {
2918 let answer = workspace.update_in(cx, |_, window, cx| {
2919 let detail = Pane::file_names_for_prompt(
2920 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
2921 cx,
2922 );
2923 window.prompt(
2924 PromptLevel::Warning,
2925 "Do you want to save all changes in the following files?",
2926 Some(&detail),
2927 &["Save all", "Discard all", "Cancel"],
2928 cx,
2929 )
2930 })?;
2931 match answer.await.log_err() {
2932 Some(0) => save_intent = SaveIntent::SaveAll,
2933 Some(1) => save_intent = SaveIntent::Skip,
2934 Some(2) => return Ok(false),
2935 _ => {}
2936 }
2937 }
2938
2939 remaining_dirty_items
2940 } else {
2941 dirty_items
2942 };
2943
2944 for (pane, item) in dirty_items {
2945 let (singleton, project_entry_ids) = cx.update(|_, cx| {
2946 (
2947 item.buffer_kind(cx) == ItemBufferKind::Singleton,
2948 item.project_entry_ids(cx),
2949 )
2950 })?;
2951 if (singleton || !project_entry_ids.is_empty())
2952 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
2953 {
2954 return Ok(false);
2955 }
2956 }
2957 Ok(true)
2958 })
2959 }
2960
2961 pub fn open_workspace_for_paths(
2962 &mut self,
2963 replace_current_window: bool,
2964 paths: Vec<PathBuf>,
2965 window: &mut Window,
2966 cx: &mut Context<Self>,
2967 ) -> Task<Result<()>> {
2968 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
2969 let is_remote = self.project.read(cx).is_via_collab();
2970 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
2971 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
2972
2973 let window_to_replace = if replace_current_window {
2974 window_handle
2975 } else if is_remote || has_worktree || has_dirty_items {
2976 None
2977 } else {
2978 window_handle
2979 };
2980 let app_state = self.app_state.clone();
2981
2982 cx.spawn(async move |_, cx| {
2983 cx.update(|cx| {
2984 open_paths(
2985 &paths,
2986 app_state,
2987 OpenOptions {
2988 replace_window: window_to_replace,
2989 ..Default::default()
2990 },
2991 cx,
2992 )
2993 })
2994 .await?;
2995 Ok(())
2996 })
2997 }
2998
2999 #[allow(clippy::type_complexity)]
3000 pub fn open_paths(
3001 &mut self,
3002 mut abs_paths: Vec<PathBuf>,
3003 options: OpenOptions,
3004 pane: Option<WeakEntity<Pane>>,
3005 window: &mut Window,
3006 cx: &mut Context<Self>,
3007 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3008 let fs = self.app_state.fs.clone();
3009
3010 let caller_ordered_abs_paths = abs_paths.clone();
3011
3012 // Sort the paths to ensure we add worktrees for parents before their children.
3013 abs_paths.sort_unstable();
3014 cx.spawn_in(window, async move |this, cx| {
3015 let mut tasks = Vec::with_capacity(abs_paths.len());
3016
3017 for abs_path in &abs_paths {
3018 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3019 OpenVisible::All => Some(true),
3020 OpenVisible::None => Some(false),
3021 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3022 Some(Some(metadata)) => Some(!metadata.is_dir),
3023 Some(None) => Some(true),
3024 None => None,
3025 },
3026 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3027 Some(Some(metadata)) => Some(metadata.is_dir),
3028 Some(None) => Some(false),
3029 None => None,
3030 },
3031 };
3032 let project_path = match visible {
3033 Some(visible) => match this
3034 .update(cx, |this, cx| {
3035 Workspace::project_path_for_path(
3036 this.project.clone(),
3037 abs_path,
3038 visible,
3039 cx,
3040 )
3041 })
3042 .log_err()
3043 {
3044 Some(project_path) => project_path.await.log_err(),
3045 None => None,
3046 },
3047 None => None,
3048 };
3049
3050 let this = this.clone();
3051 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3052 let fs = fs.clone();
3053 let pane = pane.clone();
3054 let task = cx.spawn(async move |cx| {
3055 let (_worktree, project_path) = project_path?;
3056 if fs.is_dir(&abs_path).await {
3057 // Opening a directory should not race to update the active entry.
3058 // We'll select/reveal a deterministic final entry after all paths finish opening.
3059 None
3060 } else {
3061 Some(
3062 this.update_in(cx, |this, window, cx| {
3063 this.open_path(
3064 project_path,
3065 pane,
3066 options.focus.unwrap_or(true),
3067 window,
3068 cx,
3069 )
3070 })
3071 .ok()?
3072 .await,
3073 )
3074 }
3075 });
3076 tasks.push(task);
3077 }
3078
3079 let results = futures::future::join_all(tasks).await;
3080
3081 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3082 let mut winner: Option<(PathBuf, bool)> = None;
3083 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3084 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3085 if !metadata.is_dir {
3086 winner = Some((abs_path, false));
3087 break;
3088 }
3089 if winner.is_none() {
3090 winner = Some((abs_path, true));
3091 }
3092 } else if winner.is_none() {
3093 winner = Some((abs_path, false));
3094 }
3095 }
3096
3097 // Compute the winner entry id on the foreground thread and emit once, after all
3098 // paths finish opening. This avoids races between concurrently-opening paths
3099 // (directories in particular) and makes the resulting project panel selection
3100 // deterministic.
3101 if let Some((winner_abs_path, winner_is_dir)) = winner {
3102 'emit_winner: {
3103 let winner_abs_path: Arc<Path> =
3104 SanitizedPath::new(&winner_abs_path).as_path().into();
3105
3106 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3107 OpenVisible::All => true,
3108 OpenVisible::None => false,
3109 OpenVisible::OnlyFiles => !winner_is_dir,
3110 OpenVisible::OnlyDirectories => winner_is_dir,
3111 };
3112
3113 let Some(worktree_task) = this
3114 .update(cx, |workspace, cx| {
3115 workspace.project.update(cx, |project, cx| {
3116 project.find_or_create_worktree(
3117 winner_abs_path.as_ref(),
3118 visible,
3119 cx,
3120 )
3121 })
3122 })
3123 .ok()
3124 else {
3125 break 'emit_winner;
3126 };
3127
3128 let Ok((worktree, _)) = worktree_task.await else {
3129 break 'emit_winner;
3130 };
3131
3132 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3133 let worktree = worktree.read(cx);
3134 let worktree_abs_path = worktree.abs_path();
3135 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3136 worktree.root_entry()
3137 } else {
3138 winner_abs_path
3139 .strip_prefix(worktree_abs_path.as_ref())
3140 .ok()
3141 .and_then(|relative_path| {
3142 let relative_path =
3143 RelPath::new(relative_path, PathStyle::local())
3144 .log_err()?;
3145 worktree.entry_for_path(&relative_path)
3146 })
3147 }?;
3148 Some(entry.id)
3149 }) else {
3150 break 'emit_winner;
3151 };
3152
3153 this.update(cx, |workspace, cx| {
3154 workspace.project.update(cx, |_, cx| {
3155 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3156 });
3157 })
3158 .ok();
3159 }
3160 }
3161
3162 results
3163 })
3164 }
3165
3166 pub fn open_resolved_path(
3167 &mut self,
3168 path: ResolvedPath,
3169 window: &mut Window,
3170 cx: &mut Context<Self>,
3171 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3172 match path {
3173 ResolvedPath::ProjectPath { project_path, .. } => {
3174 self.open_path(project_path, None, true, window, cx)
3175 }
3176 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3177 PathBuf::from(path),
3178 OpenOptions {
3179 visible: Some(OpenVisible::None),
3180 ..Default::default()
3181 },
3182 window,
3183 cx,
3184 ),
3185 }
3186 }
3187
3188 pub fn absolute_path_of_worktree(
3189 &self,
3190 worktree_id: WorktreeId,
3191 cx: &mut Context<Self>,
3192 ) -> Option<PathBuf> {
3193 self.project
3194 .read(cx)
3195 .worktree_for_id(worktree_id, cx)
3196 // TODO: use `abs_path` or `root_dir`
3197 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3198 }
3199
3200 fn add_folder_to_project(
3201 &mut self,
3202 _: &AddFolderToProject,
3203 window: &mut Window,
3204 cx: &mut Context<Self>,
3205 ) {
3206 let project = self.project.read(cx);
3207 if project.is_via_collab() {
3208 self.show_error(
3209 &anyhow!("You cannot add folders to someone else's project"),
3210 cx,
3211 );
3212 return;
3213 }
3214 let paths = self.prompt_for_open_path(
3215 PathPromptOptions {
3216 files: false,
3217 directories: true,
3218 multiple: true,
3219 prompt: None,
3220 },
3221 DirectoryLister::Project(self.project.clone()),
3222 window,
3223 cx,
3224 );
3225 cx.spawn_in(window, async move |this, cx| {
3226 if let Some(paths) = paths.await.log_err().flatten() {
3227 let results = this
3228 .update_in(cx, |this, window, cx| {
3229 this.open_paths(
3230 paths,
3231 OpenOptions {
3232 visible: Some(OpenVisible::All),
3233 ..Default::default()
3234 },
3235 None,
3236 window,
3237 cx,
3238 )
3239 })?
3240 .await;
3241 for result in results.into_iter().flatten() {
3242 result.log_err();
3243 }
3244 }
3245 anyhow::Ok(())
3246 })
3247 .detach_and_log_err(cx);
3248 }
3249
3250 pub fn project_path_for_path(
3251 project: Entity<Project>,
3252 abs_path: &Path,
3253 visible: bool,
3254 cx: &mut App,
3255 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3256 let entry = project.update(cx, |project, cx| {
3257 project.find_or_create_worktree(abs_path, visible, cx)
3258 });
3259 cx.spawn(async move |cx| {
3260 let (worktree, path) = entry.await?;
3261 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3262 Ok((worktree, ProjectPath { worktree_id, path }))
3263 })
3264 }
3265
3266 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3267 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3268 }
3269
3270 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3271 self.items_of_type(cx).max_by_key(|item| item.item_id())
3272 }
3273
3274 pub fn items_of_type<'a, T: Item>(
3275 &'a self,
3276 cx: &'a App,
3277 ) -> impl 'a + Iterator<Item = Entity<T>> {
3278 self.panes
3279 .iter()
3280 .flat_map(|pane| pane.read(cx).items_of_type())
3281 }
3282
3283 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3284 self.active_pane().read(cx).active_item()
3285 }
3286
3287 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3288 let item = self.active_item(cx)?;
3289 item.to_any_view().downcast::<I>().ok()
3290 }
3291
3292 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3293 self.active_item(cx).and_then(|item| item.project_path(cx))
3294 }
3295
3296 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3297 self.recent_navigation_history_iter(cx)
3298 .filter_map(|(path, abs_path)| {
3299 let worktree = self
3300 .project
3301 .read(cx)
3302 .worktree_for_id(path.worktree_id, cx)?;
3303 if worktree.read(cx).is_visible() {
3304 abs_path
3305 } else {
3306 None
3307 }
3308 })
3309 .next()
3310 }
3311
3312 pub fn save_active_item(
3313 &mut self,
3314 save_intent: SaveIntent,
3315 window: &mut Window,
3316 cx: &mut App,
3317 ) -> Task<Result<()>> {
3318 let project = self.project.clone();
3319 let pane = self.active_pane();
3320 let item = pane.read(cx).active_item();
3321 let pane = pane.downgrade();
3322
3323 window.spawn(cx, async move |cx| {
3324 if let Some(item) = item {
3325 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3326 .await
3327 .map(|_| ())
3328 } else {
3329 Ok(())
3330 }
3331 })
3332 }
3333
3334 pub fn close_inactive_items_and_panes(
3335 &mut self,
3336 action: &CloseInactiveTabsAndPanes,
3337 window: &mut Window,
3338 cx: &mut Context<Self>,
3339 ) {
3340 if let Some(task) = self.close_all_internal(
3341 true,
3342 action.save_intent.unwrap_or(SaveIntent::Close),
3343 window,
3344 cx,
3345 ) {
3346 task.detach_and_log_err(cx)
3347 }
3348 }
3349
3350 pub fn close_all_items_and_panes(
3351 &mut self,
3352 action: &CloseAllItemsAndPanes,
3353 window: &mut Window,
3354 cx: &mut Context<Self>,
3355 ) {
3356 if let Some(task) = self.close_all_internal(
3357 false,
3358 action.save_intent.unwrap_or(SaveIntent::Close),
3359 window,
3360 cx,
3361 ) {
3362 task.detach_and_log_err(cx)
3363 }
3364 }
3365
3366 /// Closes the active item across all panes.
3367 pub fn close_item_in_all_panes(
3368 &mut self,
3369 action: &CloseItemInAllPanes,
3370 window: &mut Window,
3371 cx: &mut Context<Self>,
3372 ) {
3373 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3374 return;
3375 };
3376
3377 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3378 let close_pinned = action.close_pinned;
3379
3380 if let Some(project_path) = active_item.project_path(cx) {
3381 self.close_items_with_project_path(
3382 &project_path,
3383 save_intent,
3384 close_pinned,
3385 window,
3386 cx,
3387 );
3388 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3389 let item_id = active_item.item_id();
3390 self.active_pane().update(cx, |pane, cx| {
3391 pane.close_item_by_id(item_id, save_intent, window, cx)
3392 .detach_and_log_err(cx);
3393 });
3394 }
3395 }
3396
3397 /// Closes all items with the given project path across all panes.
3398 pub fn close_items_with_project_path(
3399 &mut self,
3400 project_path: &ProjectPath,
3401 save_intent: SaveIntent,
3402 close_pinned: bool,
3403 window: &mut Window,
3404 cx: &mut Context<Self>,
3405 ) {
3406 let panes = self.panes().to_vec();
3407 for pane in panes {
3408 pane.update(cx, |pane, cx| {
3409 pane.close_items_for_project_path(
3410 project_path,
3411 save_intent,
3412 close_pinned,
3413 window,
3414 cx,
3415 )
3416 .detach_and_log_err(cx);
3417 });
3418 }
3419 }
3420
3421 fn close_all_internal(
3422 &mut self,
3423 retain_active_pane: bool,
3424 save_intent: SaveIntent,
3425 window: &mut Window,
3426 cx: &mut Context<Self>,
3427 ) -> Option<Task<Result<()>>> {
3428 let current_pane = self.active_pane();
3429
3430 let mut tasks = Vec::new();
3431
3432 if retain_active_pane {
3433 let current_pane_close = current_pane.update(cx, |pane, cx| {
3434 pane.close_other_items(
3435 &CloseOtherItems {
3436 save_intent: None,
3437 close_pinned: false,
3438 },
3439 None,
3440 window,
3441 cx,
3442 )
3443 });
3444
3445 tasks.push(current_pane_close);
3446 }
3447
3448 for pane in self.panes() {
3449 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3450 continue;
3451 }
3452
3453 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3454 pane.close_all_items(
3455 &CloseAllItems {
3456 save_intent: Some(save_intent),
3457 close_pinned: false,
3458 },
3459 window,
3460 cx,
3461 )
3462 });
3463
3464 tasks.push(close_pane_items)
3465 }
3466
3467 if tasks.is_empty() {
3468 None
3469 } else {
3470 Some(cx.spawn_in(window, async move |_, _| {
3471 for task in tasks {
3472 task.await?
3473 }
3474 Ok(())
3475 }))
3476 }
3477 }
3478
3479 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3480 self.dock_at_position(position).read(cx).is_open()
3481 }
3482
3483 pub fn toggle_dock(
3484 &mut self,
3485 dock_side: DockPosition,
3486 window: &mut Window,
3487 cx: &mut Context<Self>,
3488 ) {
3489 let mut focus_center = false;
3490 let mut reveal_dock = false;
3491
3492 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3493 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3494
3495 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3496 telemetry::event!(
3497 "Panel Button Clicked",
3498 name = panel.persistent_name(),
3499 toggle_state = !was_visible
3500 );
3501 }
3502 if was_visible {
3503 self.save_open_dock_positions(cx);
3504 }
3505
3506 let dock = self.dock_at_position(dock_side);
3507 dock.update(cx, |dock, cx| {
3508 dock.set_open(!was_visible, window, cx);
3509
3510 if dock.active_panel().is_none() {
3511 let Some(panel_ix) = dock
3512 .first_enabled_panel_idx(cx)
3513 .log_with_level(log::Level::Info)
3514 else {
3515 return;
3516 };
3517 dock.activate_panel(panel_ix, window, cx);
3518 }
3519
3520 if let Some(active_panel) = dock.active_panel() {
3521 if was_visible {
3522 if active_panel
3523 .panel_focus_handle(cx)
3524 .contains_focused(window, cx)
3525 {
3526 focus_center = true;
3527 }
3528 } else {
3529 let focus_handle = &active_panel.panel_focus_handle(cx);
3530 window.focus(focus_handle, cx);
3531 reveal_dock = true;
3532 }
3533 }
3534 });
3535
3536 if reveal_dock {
3537 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3538 }
3539
3540 if focus_center {
3541 self.active_pane
3542 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3543 }
3544
3545 cx.notify();
3546 self.serialize_workspace(window, cx);
3547 }
3548
3549 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3550 self.all_docks().into_iter().find(|&dock| {
3551 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3552 })
3553 }
3554
3555 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3556 if let Some(dock) = self.active_dock(window, cx).cloned() {
3557 self.save_open_dock_positions(cx);
3558 dock.update(cx, |dock, cx| {
3559 dock.set_open(false, window, cx);
3560 });
3561 return true;
3562 }
3563 false
3564 }
3565
3566 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3567 self.save_open_dock_positions(cx);
3568 for dock in self.all_docks() {
3569 dock.update(cx, |dock, cx| {
3570 dock.set_open(false, window, cx);
3571 });
3572 }
3573
3574 cx.focus_self(window);
3575 cx.notify();
3576 self.serialize_workspace(window, cx);
3577 }
3578
3579 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
3580 self.all_docks()
3581 .into_iter()
3582 .filter_map(|dock| {
3583 let dock_ref = dock.read(cx);
3584 if dock_ref.is_open() {
3585 Some(dock_ref.position())
3586 } else {
3587 None
3588 }
3589 })
3590 .collect()
3591 }
3592
3593 /// Saves the positions of currently open docks.
3594 ///
3595 /// Updates `last_open_dock_positions` with positions of all currently open
3596 /// docks, to later be restored by the 'Toggle All Docks' action.
3597 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
3598 let open_dock_positions = self.get_open_dock_positions(cx);
3599 if !open_dock_positions.is_empty() {
3600 self.last_open_dock_positions = open_dock_positions;
3601 }
3602 }
3603
3604 /// Toggles all docks between open and closed states.
3605 ///
3606 /// If any docks are open, closes all and remembers their positions. If all
3607 /// docks are closed, restores the last remembered dock configuration.
3608 fn toggle_all_docks(
3609 &mut self,
3610 _: &ToggleAllDocks,
3611 window: &mut Window,
3612 cx: &mut Context<Self>,
3613 ) {
3614 let open_dock_positions = self.get_open_dock_positions(cx);
3615
3616 if !open_dock_positions.is_empty() {
3617 self.close_all_docks(window, cx);
3618 } else if !self.last_open_dock_positions.is_empty() {
3619 self.restore_last_open_docks(window, cx);
3620 }
3621 }
3622
3623 /// Reopens docks from the most recently remembered configuration.
3624 ///
3625 /// Opens all docks whose positions are stored in `last_open_dock_positions`
3626 /// and clears the stored positions.
3627 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3628 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
3629
3630 for position in positions_to_open {
3631 let dock = self.dock_at_position(position);
3632 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
3633 }
3634
3635 cx.focus_self(window);
3636 cx.notify();
3637 self.serialize_workspace(window, cx);
3638 }
3639
3640 /// Transfer focus to the panel of the given type.
3641 pub fn focus_panel<T: Panel>(
3642 &mut self,
3643 window: &mut Window,
3644 cx: &mut Context<Self>,
3645 ) -> Option<Entity<T>> {
3646 let panel = self.focus_or_unfocus_panel::<T>(window, cx, |_, _, _| true)?;
3647 panel.to_any().downcast().ok()
3648 }
3649
3650 /// Focus the panel of the given type if it isn't already focused. If it is
3651 /// already focused, then transfer focus back to the workspace center.
3652 pub fn toggle_panel_focus<T: Panel>(
3653 &mut self,
3654 window: &mut Window,
3655 cx: &mut Context<Self>,
3656 ) -> bool {
3657 let mut did_focus_panel = false;
3658 self.focus_or_unfocus_panel::<T>(window, cx, |panel, window, cx| {
3659 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
3660 did_focus_panel
3661 });
3662
3663 telemetry::event!(
3664 "Panel Button Clicked",
3665 name = T::persistent_name(),
3666 toggle_state = did_focus_panel
3667 );
3668
3669 did_focus_panel
3670 }
3671
3672 pub fn activate_panel_for_proto_id(
3673 &mut self,
3674 panel_id: PanelId,
3675 window: &mut Window,
3676 cx: &mut Context<Self>,
3677 ) -> Option<Arc<dyn PanelHandle>> {
3678 let mut panel = None;
3679 for dock in self.all_docks() {
3680 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
3681 panel = dock.update(cx, |dock, cx| {
3682 dock.activate_panel(panel_index, window, cx);
3683 dock.set_open(true, window, cx);
3684 dock.active_panel().cloned()
3685 });
3686 break;
3687 }
3688 }
3689
3690 if panel.is_some() {
3691 cx.notify();
3692 self.serialize_workspace(window, cx);
3693 }
3694
3695 panel
3696 }
3697
3698 /// Focus or unfocus the given panel type, depending on the given callback.
3699 fn focus_or_unfocus_panel<T: Panel>(
3700 &mut self,
3701 window: &mut Window,
3702 cx: &mut Context<Self>,
3703 mut should_focus: impl FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
3704 ) -> Option<Arc<dyn PanelHandle>> {
3705 let mut result_panel = None;
3706 let mut serialize = false;
3707 for dock in self.all_docks() {
3708 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3709 let mut focus_center = false;
3710 let panel = dock.update(cx, |dock, cx| {
3711 dock.activate_panel(panel_index, window, cx);
3712
3713 let panel = dock.active_panel().cloned();
3714 if let Some(panel) = panel.as_ref() {
3715 if should_focus(&**panel, window, cx) {
3716 dock.set_open(true, window, cx);
3717 panel.panel_focus_handle(cx).focus(window, cx);
3718 } else {
3719 focus_center = true;
3720 }
3721 }
3722 panel
3723 });
3724
3725 if focus_center {
3726 self.active_pane
3727 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3728 }
3729
3730 result_panel = panel;
3731 serialize = true;
3732 break;
3733 }
3734 }
3735
3736 if serialize {
3737 self.serialize_workspace(window, cx);
3738 }
3739
3740 cx.notify();
3741 result_panel
3742 }
3743
3744 /// Open the panel of the given type
3745 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3746 for dock in self.all_docks() {
3747 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3748 dock.update(cx, |dock, cx| {
3749 dock.activate_panel(panel_index, window, cx);
3750 dock.set_open(true, window, cx);
3751 });
3752 }
3753 }
3754 }
3755
3756 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
3757 for dock in self.all_docks().iter() {
3758 dock.update(cx, |dock, cx| {
3759 if dock.panel::<T>().is_some() {
3760 dock.set_open(false, window, cx)
3761 }
3762 })
3763 }
3764 }
3765
3766 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
3767 self.all_docks()
3768 .iter()
3769 .find_map(|dock| dock.read(cx).panel::<T>())
3770 }
3771
3772 fn dismiss_zoomed_items_to_reveal(
3773 &mut self,
3774 dock_to_reveal: Option<DockPosition>,
3775 window: &mut Window,
3776 cx: &mut Context<Self>,
3777 ) {
3778 // If a center pane is zoomed, unzoom it.
3779 for pane in &self.panes {
3780 if pane != &self.active_pane || dock_to_reveal.is_some() {
3781 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
3782 }
3783 }
3784
3785 // If another dock is zoomed, hide it.
3786 let mut focus_center = false;
3787 for dock in self.all_docks() {
3788 dock.update(cx, |dock, cx| {
3789 if Some(dock.position()) != dock_to_reveal
3790 && let Some(panel) = dock.active_panel()
3791 && panel.is_zoomed(window, cx)
3792 {
3793 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
3794 dock.set_open(false, window, cx);
3795 }
3796 });
3797 }
3798
3799 if focus_center {
3800 self.active_pane
3801 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3802 }
3803
3804 if self.zoomed_position != dock_to_reveal {
3805 self.zoomed = None;
3806 self.zoomed_position = None;
3807 cx.emit(Event::ZoomChanged);
3808 }
3809
3810 cx.notify();
3811 }
3812
3813 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
3814 let pane = cx.new(|cx| {
3815 let mut pane = Pane::new(
3816 self.weak_handle(),
3817 self.project.clone(),
3818 self.pane_history_timestamp.clone(),
3819 None,
3820 NewFile.boxed_clone(),
3821 true,
3822 window,
3823 cx,
3824 );
3825 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
3826 pane
3827 });
3828 cx.subscribe_in(&pane, window, Self::handle_pane_event)
3829 .detach();
3830 self.panes.push(pane.clone());
3831
3832 window.focus(&pane.focus_handle(cx), cx);
3833
3834 cx.emit(Event::PaneAdded(pane.clone()));
3835 pane
3836 }
3837
3838 pub fn add_item_to_center(
3839 &mut self,
3840 item: Box<dyn ItemHandle>,
3841 window: &mut Window,
3842 cx: &mut Context<Self>,
3843 ) -> bool {
3844 if let Some(center_pane) = self.last_active_center_pane.clone() {
3845 if let Some(center_pane) = center_pane.upgrade() {
3846 center_pane.update(cx, |pane, cx| {
3847 pane.add_item(item, true, true, None, window, cx)
3848 });
3849 true
3850 } else {
3851 false
3852 }
3853 } else {
3854 false
3855 }
3856 }
3857
3858 pub fn add_item_to_active_pane(
3859 &mut self,
3860 item: Box<dyn ItemHandle>,
3861 destination_index: Option<usize>,
3862 focus_item: bool,
3863 window: &mut Window,
3864 cx: &mut App,
3865 ) {
3866 self.add_item(
3867 self.active_pane.clone(),
3868 item,
3869 destination_index,
3870 false,
3871 focus_item,
3872 window,
3873 cx,
3874 )
3875 }
3876
3877 pub fn add_item(
3878 &mut self,
3879 pane: Entity<Pane>,
3880 item: Box<dyn ItemHandle>,
3881 destination_index: Option<usize>,
3882 activate_pane: bool,
3883 focus_item: bool,
3884 window: &mut Window,
3885 cx: &mut App,
3886 ) {
3887 pane.update(cx, |pane, cx| {
3888 pane.add_item(
3889 item,
3890 activate_pane,
3891 focus_item,
3892 destination_index,
3893 window,
3894 cx,
3895 )
3896 });
3897 }
3898
3899 pub fn split_item(
3900 &mut self,
3901 split_direction: SplitDirection,
3902 item: Box<dyn ItemHandle>,
3903 window: &mut Window,
3904 cx: &mut Context<Self>,
3905 ) {
3906 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
3907 self.add_item(new_pane, item, None, true, true, window, cx);
3908 }
3909
3910 pub fn open_abs_path(
3911 &mut self,
3912 abs_path: PathBuf,
3913 options: OpenOptions,
3914 window: &mut Window,
3915 cx: &mut Context<Self>,
3916 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3917 cx.spawn_in(window, async move |workspace, cx| {
3918 let open_paths_task_result = workspace
3919 .update_in(cx, |workspace, window, cx| {
3920 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
3921 })
3922 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
3923 .await;
3924 anyhow::ensure!(
3925 open_paths_task_result.len() == 1,
3926 "open abs path {abs_path:?} task returned incorrect number of results"
3927 );
3928 match open_paths_task_result
3929 .into_iter()
3930 .next()
3931 .expect("ensured single task result")
3932 {
3933 Some(open_result) => {
3934 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
3935 }
3936 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
3937 }
3938 })
3939 }
3940
3941 pub fn split_abs_path(
3942 &mut self,
3943 abs_path: PathBuf,
3944 visible: bool,
3945 window: &mut Window,
3946 cx: &mut Context<Self>,
3947 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3948 let project_path_task =
3949 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
3950 cx.spawn_in(window, async move |this, cx| {
3951 let (_, path) = project_path_task.await?;
3952 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
3953 .await
3954 })
3955 }
3956
3957 pub fn open_path(
3958 &mut self,
3959 path: impl Into<ProjectPath>,
3960 pane: Option<WeakEntity<Pane>>,
3961 focus_item: bool,
3962 window: &mut Window,
3963 cx: &mut App,
3964 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3965 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
3966 }
3967
3968 pub fn open_path_preview(
3969 &mut self,
3970 path: impl Into<ProjectPath>,
3971 pane: Option<WeakEntity<Pane>>,
3972 focus_item: bool,
3973 allow_preview: bool,
3974 activate: bool,
3975 window: &mut Window,
3976 cx: &mut App,
3977 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3978 let pane = pane.unwrap_or_else(|| {
3979 self.last_active_center_pane.clone().unwrap_or_else(|| {
3980 self.panes
3981 .first()
3982 .expect("There must be an active pane")
3983 .downgrade()
3984 })
3985 });
3986
3987 let project_path = path.into();
3988 let task = self.load_path(project_path.clone(), window, cx);
3989 window.spawn(cx, async move |cx| {
3990 let (project_entry_id, build_item) = task.await?;
3991
3992 pane.update_in(cx, |pane, window, cx| {
3993 pane.open_item(
3994 project_entry_id,
3995 project_path,
3996 focus_item,
3997 allow_preview,
3998 activate,
3999 None,
4000 window,
4001 cx,
4002 build_item,
4003 )
4004 })
4005 })
4006 }
4007
4008 pub fn split_path(
4009 &mut self,
4010 path: impl Into<ProjectPath>,
4011 window: &mut Window,
4012 cx: &mut Context<Self>,
4013 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4014 self.split_path_preview(path, false, None, window, cx)
4015 }
4016
4017 pub fn split_path_preview(
4018 &mut self,
4019 path: impl Into<ProjectPath>,
4020 allow_preview: bool,
4021 split_direction: Option<SplitDirection>,
4022 window: &mut Window,
4023 cx: &mut Context<Self>,
4024 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4025 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4026 self.panes
4027 .first()
4028 .expect("There must be an active pane")
4029 .downgrade()
4030 });
4031
4032 if let Member::Pane(center_pane) = &self.center.root
4033 && center_pane.read(cx).items_len() == 0
4034 {
4035 return self.open_path(path, Some(pane), true, window, cx);
4036 }
4037
4038 let project_path = path.into();
4039 let task = self.load_path(project_path.clone(), window, cx);
4040 cx.spawn_in(window, async move |this, cx| {
4041 let (project_entry_id, build_item) = task.await?;
4042 this.update_in(cx, move |this, window, cx| -> Option<_> {
4043 let pane = pane.upgrade()?;
4044 let new_pane = this.split_pane(
4045 pane,
4046 split_direction.unwrap_or(SplitDirection::Right),
4047 window,
4048 cx,
4049 );
4050 new_pane.update(cx, |new_pane, cx| {
4051 Some(new_pane.open_item(
4052 project_entry_id,
4053 project_path,
4054 true,
4055 allow_preview,
4056 true,
4057 None,
4058 window,
4059 cx,
4060 build_item,
4061 ))
4062 })
4063 })
4064 .map(|option| option.context("pane was dropped"))?
4065 })
4066 }
4067
4068 fn load_path(
4069 &mut self,
4070 path: ProjectPath,
4071 window: &mut Window,
4072 cx: &mut App,
4073 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4074 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4075 registry.open_path(self.project(), &path, window, cx)
4076 }
4077
4078 pub fn find_project_item<T>(
4079 &self,
4080 pane: &Entity<Pane>,
4081 project_item: &Entity<T::Item>,
4082 cx: &App,
4083 ) -> Option<Entity<T>>
4084 where
4085 T: ProjectItem,
4086 {
4087 use project::ProjectItem as _;
4088 let project_item = project_item.read(cx);
4089 let entry_id = project_item.entry_id(cx);
4090 let project_path = project_item.project_path(cx);
4091
4092 let mut item = None;
4093 if let Some(entry_id) = entry_id {
4094 item = pane.read(cx).item_for_entry(entry_id, cx);
4095 }
4096 if item.is_none()
4097 && let Some(project_path) = project_path
4098 {
4099 item = pane.read(cx).item_for_path(project_path, cx);
4100 }
4101
4102 item.and_then(|item| item.downcast::<T>())
4103 }
4104
4105 pub fn is_project_item_open<T>(
4106 &self,
4107 pane: &Entity<Pane>,
4108 project_item: &Entity<T::Item>,
4109 cx: &App,
4110 ) -> bool
4111 where
4112 T: ProjectItem,
4113 {
4114 self.find_project_item::<T>(pane, project_item, cx)
4115 .is_some()
4116 }
4117
4118 pub fn open_project_item<T>(
4119 &mut self,
4120 pane: Entity<Pane>,
4121 project_item: Entity<T::Item>,
4122 activate_pane: bool,
4123 focus_item: bool,
4124 keep_old_preview: bool,
4125 allow_new_preview: bool,
4126 window: &mut Window,
4127 cx: &mut Context<Self>,
4128 ) -> Entity<T>
4129 where
4130 T: ProjectItem,
4131 {
4132 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4133
4134 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4135 if !keep_old_preview
4136 && let Some(old_id) = old_item_id
4137 && old_id != item.item_id()
4138 {
4139 // switching to a different item, so unpreview old active item
4140 pane.update(cx, |pane, _| {
4141 pane.unpreview_item_if_preview(old_id);
4142 });
4143 }
4144
4145 self.activate_item(&item, activate_pane, focus_item, window, cx);
4146 if !allow_new_preview {
4147 pane.update(cx, |pane, _| {
4148 pane.unpreview_item_if_preview(item.item_id());
4149 });
4150 }
4151 return item;
4152 }
4153
4154 let item = pane.update(cx, |pane, cx| {
4155 cx.new(|cx| {
4156 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4157 })
4158 });
4159 let mut destination_index = None;
4160 pane.update(cx, |pane, cx| {
4161 if !keep_old_preview && let Some(old_id) = old_item_id {
4162 pane.unpreview_item_if_preview(old_id);
4163 }
4164 if allow_new_preview {
4165 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4166 }
4167 });
4168
4169 self.add_item(
4170 pane,
4171 Box::new(item.clone()),
4172 destination_index,
4173 activate_pane,
4174 focus_item,
4175 window,
4176 cx,
4177 );
4178 item
4179 }
4180
4181 pub fn open_shared_screen(
4182 &mut self,
4183 peer_id: PeerId,
4184 window: &mut Window,
4185 cx: &mut Context<Self>,
4186 ) {
4187 if let Some(shared_screen) =
4188 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4189 {
4190 self.active_pane.update(cx, |pane, cx| {
4191 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4192 });
4193 }
4194 }
4195
4196 pub fn activate_item(
4197 &mut self,
4198 item: &dyn ItemHandle,
4199 activate_pane: bool,
4200 focus_item: bool,
4201 window: &mut Window,
4202 cx: &mut App,
4203 ) -> bool {
4204 let result = self.panes.iter().find_map(|pane| {
4205 pane.read(cx)
4206 .index_for_item(item)
4207 .map(|ix| (pane.clone(), ix))
4208 });
4209 if let Some((pane, ix)) = result {
4210 pane.update(cx, |pane, cx| {
4211 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4212 });
4213 true
4214 } else {
4215 false
4216 }
4217 }
4218
4219 fn activate_pane_at_index(
4220 &mut self,
4221 action: &ActivatePane,
4222 window: &mut Window,
4223 cx: &mut Context<Self>,
4224 ) {
4225 let panes = self.center.panes();
4226 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4227 window.focus(&pane.focus_handle(cx), cx);
4228 } else {
4229 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4230 .detach();
4231 }
4232 }
4233
4234 fn move_item_to_pane_at_index(
4235 &mut self,
4236 action: &MoveItemToPane,
4237 window: &mut Window,
4238 cx: &mut Context<Self>,
4239 ) {
4240 let panes = self.center.panes();
4241 let destination = match panes.get(action.destination) {
4242 Some(&destination) => destination.clone(),
4243 None => {
4244 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4245 return;
4246 }
4247 let direction = SplitDirection::Right;
4248 let split_off_pane = self
4249 .find_pane_in_direction(direction, cx)
4250 .unwrap_or_else(|| self.active_pane.clone());
4251 let new_pane = self.add_pane(window, cx);
4252 if self
4253 .center
4254 .split(&split_off_pane, &new_pane, direction, cx)
4255 .log_err()
4256 .is_none()
4257 {
4258 return;
4259 };
4260 new_pane
4261 }
4262 };
4263
4264 if action.clone {
4265 if self
4266 .active_pane
4267 .read(cx)
4268 .active_item()
4269 .is_some_and(|item| item.can_split(cx))
4270 {
4271 clone_active_item(
4272 self.database_id(),
4273 &self.active_pane,
4274 &destination,
4275 action.focus,
4276 window,
4277 cx,
4278 );
4279 return;
4280 }
4281 }
4282 move_active_item(
4283 &self.active_pane,
4284 &destination,
4285 action.focus,
4286 true,
4287 window,
4288 cx,
4289 )
4290 }
4291
4292 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4293 let panes = self.center.panes();
4294 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4295 let next_ix = (ix + 1) % panes.len();
4296 let next_pane = panes[next_ix].clone();
4297 window.focus(&next_pane.focus_handle(cx), cx);
4298 }
4299 }
4300
4301 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4302 let panes = self.center.panes();
4303 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4304 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4305 let prev_pane = panes[prev_ix].clone();
4306 window.focus(&prev_pane.focus_handle(cx), cx);
4307 }
4308 }
4309
4310 pub fn activate_pane_in_direction(
4311 &mut self,
4312 direction: SplitDirection,
4313 window: &mut Window,
4314 cx: &mut App,
4315 ) {
4316 use ActivateInDirectionTarget as Target;
4317 enum Origin {
4318 LeftDock,
4319 RightDock,
4320 BottomDock,
4321 Center,
4322 }
4323
4324 let origin: Origin = [
4325 (&self.left_dock, Origin::LeftDock),
4326 (&self.right_dock, Origin::RightDock),
4327 (&self.bottom_dock, Origin::BottomDock),
4328 ]
4329 .into_iter()
4330 .find_map(|(dock, origin)| {
4331 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4332 Some(origin)
4333 } else {
4334 None
4335 }
4336 })
4337 .unwrap_or(Origin::Center);
4338
4339 let get_last_active_pane = || {
4340 let pane = self
4341 .last_active_center_pane
4342 .clone()
4343 .unwrap_or_else(|| {
4344 self.panes
4345 .first()
4346 .expect("There must be an active pane")
4347 .downgrade()
4348 })
4349 .upgrade()?;
4350 (pane.read(cx).items_len() != 0).then_some(pane)
4351 };
4352
4353 let try_dock =
4354 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4355
4356 let target = match (origin, direction) {
4357 // We're in the center, so we first try to go to a different pane,
4358 // otherwise try to go to a dock.
4359 (Origin::Center, direction) => {
4360 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4361 Some(Target::Pane(pane))
4362 } else {
4363 match direction {
4364 SplitDirection::Up => None,
4365 SplitDirection::Down => try_dock(&self.bottom_dock),
4366 SplitDirection::Left => try_dock(&self.left_dock),
4367 SplitDirection::Right => try_dock(&self.right_dock),
4368 }
4369 }
4370 }
4371
4372 (Origin::LeftDock, SplitDirection::Right) => {
4373 if let Some(last_active_pane) = get_last_active_pane() {
4374 Some(Target::Pane(last_active_pane))
4375 } else {
4376 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4377 }
4378 }
4379
4380 (Origin::LeftDock, SplitDirection::Down)
4381 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4382
4383 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4384 (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
4385 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4386
4387 (Origin::RightDock, SplitDirection::Left) => {
4388 if let Some(last_active_pane) = get_last_active_pane() {
4389 Some(Target::Pane(last_active_pane))
4390 } else {
4391 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
4392 }
4393 }
4394
4395 _ => None,
4396 };
4397
4398 match target {
4399 Some(ActivateInDirectionTarget::Pane(pane)) => {
4400 let pane = pane.read(cx);
4401 if let Some(item) = pane.active_item() {
4402 item.item_focus_handle(cx).focus(window, cx);
4403 } else {
4404 log::error!(
4405 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4406 );
4407 }
4408 }
4409 Some(ActivateInDirectionTarget::Dock(dock)) => {
4410 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4411 window.defer(cx, move |window, cx| {
4412 let dock = dock.read(cx);
4413 if let Some(panel) = dock.active_panel() {
4414 panel.panel_focus_handle(cx).focus(window, cx);
4415 } else {
4416 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4417 }
4418 })
4419 }
4420 None => {}
4421 }
4422 }
4423
4424 pub fn move_item_to_pane_in_direction(
4425 &mut self,
4426 action: &MoveItemToPaneInDirection,
4427 window: &mut Window,
4428 cx: &mut Context<Self>,
4429 ) {
4430 let destination = match self.find_pane_in_direction(action.direction, cx) {
4431 Some(destination) => destination,
4432 None => {
4433 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4434 return;
4435 }
4436 let new_pane = self.add_pane(window, cx);
4437 if self
4438 .center
4439 .split(&self.active_pane, &new_pane, action.direction, cx)
4440 .log_err()
4441 .is_none()
4442 {
4443 return;
4444 };
4445 new_pane
4446 }
4447 };
4448
4449 if action.clone {
4450 if self
4451 .active_pane
4452 .read(cx)
4453 .active_item()
4454 .is_some_and(|item| item.can_split(cx))
4455 {
4456 clone_active_item(
4457 self.database_id(),
4458 &self.active_pane,
4459 &destination,
4460 action.focus,
4461 window,
4462 cx,
4463 );
4464 return;
4465 }
4466 }
4467 move_active_item(
4468 &self.active_pane,
4469 &destination,
4470 action.focus,
4471 true,
4472 window,
4473 cx,
4474 );
4475 }
4476
4477 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4478 self.center.bounding_box_for_pane(pane)
4479 }
4480
4481 pub fn find_pane_in_direction(
4482 &mut self,
4483 direction: SplitDirection,
4484 cx: &App,
4485 ) -> Option<Entity<Pane>> {
4486 self.center
4487 .find_pane_in_direction(&self.active_pane, direction, cx)
4488 .cloned()
4489 }
4490
4491 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4492 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4493 self.center.swap(&self.active_pane, &to, cx);
4494 cx.notify();
4495 }
4496 }
4497
4498 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4499 if self
4500 .center
4501 .move_to_border(&self.active_pane, direction, cx)
4502 .unwrap()
4503 {
4504 cx.notify();
4505 }
4506 }
4507
4508 pub fn resize_pane(
4509 &mut self,
4510 axis: gpui::Axis,
4511 amount: Pixels,
4512 window: &mut Window,
4513 cx: &mut Context<Self>,
4514 ) {
4515 let docks = self.all_docks();
4516 let active_dock = docks
4517 .into_iter()
4518 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4519
4520 if let Some(dock) = active_dock {
4521 let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
4522 return;
4523 };
4524 match dock.read(cx).position() {
4525 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4526 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4527 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4528 }
4529 } else {
4530 self.center
4531 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
4532 }
4533 cx.notify();
4534 }
4535
4536 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
4537 self.center.reset_pane_sizes(cx);
4538 cx.notify();
4539 }
4540
4541 fn handle_pane_focused(
4542 &mut self,
4543 pane: Entity<Pane>,
4544 window: &mut Window,
4545 cx: &mut Context<Self>,
4546 ) {
4547 // This is explicitly hoisted out of the following check for pane identity as
4548 // terminal panel panes are not registered as a center panes.
4549 self.status_bar.update(cx, |status_bar, cx| {
4550 status_bar.set_active_pane(&pane, window, cx);
4551 });
4552 if self.active_pane != pane {
4553 self.set_active_pane(&pane, window, cx);
4554 }
4555
4556 if self.last_active_center_pane.is_none() {
4557 self.last_active_center_pane = Some(pane.downgrade());
4558 }
4559
4560 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
4561 // This prevents the dock from closing when focus events fire during window activation.
4562 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
4563 let dock_read = dock.read(cx);
4564 if let Some(panel) = dock_read.active_panel()
4565 && let Some(dock_pane) = panel.pane(cx)
4566 && dock_pane == pane
4567 {
4568 Some(dock_read.position())
4569 } else {
4570 None
4571 }
4572 });
4573
4574 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
4575 if pane.read(cx).is_zoomed() {
4576 self.zoomed = Some(pane.downgrade().into());
4577 } else {
4578 self.zoomed = None;
4579 }
4580 self.zoomed_position = None;
4581 cx.emit(Event::ZoomChanged);
4582 self.update_active_view_for_followers(window, cx);
4583 pane.update(cx, |pane, _| {
4584 pane.track_alternate_file_items();
4585 });
4586
4587 cx.notify();
4588 }
4589
4590 fn set_active_pane(
4591 &mut self,
4592 pane: &Entity<Pane>,
4593 window: &mut Window,
4594 cx: &mut Context<Self>,
4595 ) {
4596 self.active_pane = pane.clone();
4597 self.active_item_path_changed(true, window, cx);
4598 self.last_active_center_pane = Some(pane.downgrade());
4599 }
4600
4601 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4602 self.update_active_view_for_followers(window, cx);
4603 }
4604
4605 fn handle_pane_event(
4606 &mut self,
4607 pane: &Entity<Pane>,
4608 event: &pane::Event,
4609 window: &mut Window,
4610 cx: &mut Context<Self>,
4611 ) {
4612 let mut serialize_workspace = true;
4613 match event {
4614 pane::Event::AddItem { item } => {
4615 item.added_to_pane(self, pane.clone(), window, cx);
4616 cx.emit(Event::ItemAdded {
4617 item: item.boxed_clone(),
4618 });
4619 }
4620 pane::Event::Split { direction, mode } => {
4621 match mode {
4622 SplitMode::ClonePane => {
4623 self.split_and_clone(pane.clone(), *direction, window, cx)
4624 .detach();
4625 }
4626 SplitMode::EmptyPane => {
4627 self.split_pane(pane.clone(), *direction, window, cx);
4628 }
4629 SplitMode::MovePane => {
4630 self.split_and_move(pane.clone(), *direction, window, cx);
4631 }
4632 };
4633 }
4634 pane::Event::JoinIntoNext => {
4635 self.join_pane_into_next(pane.clone(), window, cx);
4636 }
4637 pane::Event::JoinAll => {
4638 self.join_all_panes(window, cx);
4639 }
4640 pane::Event::Remove { focus_on_pane } => {
4641 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
4642 }
4643 pane::Event::ActivateItem {
4644 local,
4645 focus_changed,
4646 } => {
4647 window.invalidate_character_coordinates();
4648
4649 pane.update(cx, |pane, _| {
4650 pane.track_alternate_file_items();
4651 });
4652 if *local {
4653 self.unfollow_in_pane(pane, window, cx);
4654 }
4655 serialize_workspace = *focus_changed || pane != self.active_pane();
4656 if pane == self.active_pane() {
4657 self.active_item_path_changed(*focus_changed, window, cx);
4658 self.update_active_view_for_followers(window, cx);
4659 } else if *local {
4660 self.set_active_pane(pane, window, cx);
4661 }
4662 }
4663 pane::Event::UserSavedItem { item, save_intent } => {
4664 cx.emit(Event::UserSavedItem {
4665 pane: pane.downgrade(),
4666 item: item.boxed_clone(),
4667 save_intent: *save_intent,
4668 });
4669 serialize_workspace = false;
4670 }
4671 pane::Event::ChangeItemTitle => {
4672 if *pane == self.active_pane {
4673 self.active_item_path_changed(false, window, cx);
4674 }
4675 serialize_workspace = false;
4676 }
4677 pane::Event::RemovedItem { item } => {
4678 cx.emit(Event::ActiveItemChanged);
4679 self.update_window_edited(window, cx);
4680 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
4681 && entry.get().entity_id() == pane.entity_id()
4682 {
4683 entry.remove();
4684 }
4685 cx.emit(Event::ItemRemoved {
4686 item_id: item.item_id(),
4687 });
4688 }
4689 pane::Event::Focus => {
4690 window.invalidate_character_coordinates();
4691 self.handle_pane_focused(pane.clone(), window, cx);
4692 }
4693 pane::Event::ZoomIn => {
4694 if *pane == self.active_pane {
4695 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
4696 if pane.read(cx).has_focus(window, cx) {
4697 self.zoomed = Some(pane.downgrade().into());
4698 self.zoomed_position = None;
4699 cx.emit(Event::ZoomChanged);
4700 }
4701 cx.notify();
4702 }
4703 }
4704 pane::Event::ZoomOut => {
4705 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4706 if self.zoomed_position.is_none() {
4707 self.zoomed = None;
4708 cx.emit(Event::ZoomChanged);
4709 }
4710 cx.notify();
4711 }
4712 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
4713 }
4714
4715 if serialize_workspace {
4716 self.serialize_workspace(window, cx);
4717 }
4718 }
4719
4720 pub fn unfollow_in_pane(
4721 &mut self,
4722 pane: &Entity<Pane>,
4723 window: &mut Window,
4724 cx: &mut Context<Workspace>,
4725 ) -> Option<CollaboratorId> {
4726 let leader_id = self.leader_for_pane(pane)?;
4727 self.unfollow(leader_id, window, cx);
4728 Some(leader_id)
4729 }
4730
4731 pub fn split_pane(
4732 &mut self,
4733 pane_to_split: Entity<Pane>,
4734 split_direction: SplitDirection,
4735 window: &mut Window,
4736 cx: &mut Context<Self>,
4737 ) -> Entity<Pane> {
4738 let new_pane = self.add_pane(window, cx);
4739 self.center
4740 .split(&pane_to_split, &new_pane, split_direction, cx)
4741 .unwrap();
4742 cx.notify();
4743 new_pane
4744 }
4745
4746 pub fn split_and_move(
4747 &mut self,
4748 pane: Entity<Pane>,
4749 direction: SplitDirection,
4750 window: &mut Window,
4751 cx: &mut Context<Self>,
4752 ) {
4753 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
4754 return;
4755 };
4756 let new_pane = self.add_pane(window, cx);
4757 new_pane.update(cx, |pane, cx| {
4758 pane.add_item(item, true, true, None, window, cx)
4759 });
4760 self.center.split(&pane, &new_pane, direction, cx).unwrap();
4761 cx.notify();
4762 }
4763
4764 pub fn split_and_clone(
4765 &mut self,
4766 pane: Entity<Pane>,
4767 direction: SplitDirection,
4768 window: &mut Window,
4769 cx: &mut Context<Self>,
4770 ) -> Task<Option<Entity<Pane>>> {
4771 let Some(item) = pane.read(cx).active_item() else {
4772 return Task::ready(None);
4773 };
4774 if !item.can_split(cx) {
4775 return Task::ready(None);
4776 }
4777 let task = item.clone_on_split(self.database_id(), window, cx);
4778 cx.spawn_in(window, async move |this, cx| {
4779 if let Some(clone) = task.await {
4780 this.update_in(cx, |this, window, cx| {
4781 let new_pane = this.add_pane(window, cx);
4782 let nav_history = pane.read(cx).fork_nav_history();
4783 new_pane.update(cx, |pane, cx| {
4784 pane.set_nav_history(nav_history, cx);
4785 pane.add_item(clone, true, true, None, window, cx)
4786 });
4787 this.center.split(&pane, &new_pane, direction, cx).unwrap();
4788 cx.notify();
4789 new_pane
4790 })
4791 .ok()
4792 } else {
4793 None
4794 }
4795 })
4796 }
4797
4798 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4799 let active_item = self.active_pane.read(cx).active_item();
4800 for pane in &self.panes {
4801 join_pane_into_active(&self.active_pane, pane, window, cx);
4802 }
4803 if let Some(active_item) = active_item {
4804 self.activate_item(active_item.as_ref(), true, true, window, cx);
4805 }
4806 cx.notify();
4807 }
4808
4809 pub fn join_pane_into_next(
4810 &mut self,
4811 pane: Entity<Pane>,
4812 window: &mut Window,
4813 cx: &mut Context<Self>,
4814 ) {
4815 let next_pane = self
4816 .find_pane_in_direction(SplitDirection::Right, cx)
4817 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
4818 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
4819 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
4820 let Some(next_pane) = next_pane else {
4821 return;
4822 };
4823 move_all_items(&pane, &next_pane, window, cx);
4824 cx.notify();
4825 }
4826
4827 fn remove_pane(
4828 &mut self,
4829 pane: Entity<Pane>,
4830 focus_on: Option<Entity<Pane>>,
4831 window: &mut Window,
4832 cx: &mut Context<Self>,
4833 ) {
4834 if self.center.remove(&pane, cx).unwrap() {
4835 self.force_remove_pane(&pane, &focus_on, window, cx);
4836 self.unfollow_in_pane(&pane, window, cx);
4837 self.last_leaders_by_pane.remove(&pane.downgrade());
4838 for removed_item in pane.read(cx).items() {
4839 self.panes_by_item.remove(&removed_item.item_id());
4840 }
4841
4842 cx.notify();
4843 } else {
4844 self.active_item_path_changed(true, window, cx);
4845 }
4846 cx.emit(Event::PaneRemoved);
4847 }
4848
4849 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
4850 &mut self.panes
4851 }
4852
4853 pub fn panes(&self) -> &[Entity<Pane>] {
4854 &self.panes
4855 }
4856
4857 pub fn active_pane(&self) -> &Entity<Pane> {
4858 &self.active_pane
4859 }
4860
4861 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
4862 for dock in self.all_docks() {
4863 if dock.focus_handle(cx).contains_focused(window, cx)
4864 && let Some(pane) = dock
4865 .read(cx)
4866 .active_panel()
4867 .and_then(|panel| panel.pane(cx))
4868 {
4869 return pane;
4870 }
4871 }
4872 self.active_pane().clone()
4873 }
4874
4875 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4876 self.find_pane_in_direction(SplitDirection::Right, cx)
4877 .unwrap_or_else(|| {
4878 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
4879 })
4880 }
4881
4882 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
4883 let weak_pane = self.panes_by_item.get(&handle.item_id())?;
4884 weak_pane.upgrade()
4885 }
4886
4887 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
4888 self.follower_states.retain(|leader_id, state| {
4889 if *leader_id == CollaboratorId::PeerId(peer_id) {
4890 for item in state.items_by_leader_view_id.values() {
4891 item.view.set_leader_id(None, window, cx);
4892 }
4893 false
4894 } else {
4895 true
4896 }
4897 });
4898 cx.notify();
4899 }
4900
4901 pub fn start_following(
4902 &mut self,
4903 leader_id: impl Into<CollaboratorId>,
4904 window: &mut Window,
4905 cx: &mut Context<Self>,
4906 ) -> Option<Task<Result<()>>> {
4907 let leader_id = leader_id.into();
4908 let pane = self.active_pane().clone();
4909
4910 self.last_leaders_by_pane
4911 .insert(pane.downgrade(), leader_id);
4912 self.unfollow(leader_id, window, cx);
4913 self.unfollow_in_pane(&pane, window, cx);
4914 self.follower_states.insert(
4915 leader_id,
4916 FollowerState {
4917 center_pane: pane.clone(),
4918 dock_pane: None,
4919 active_view_id: None,
4920 items_by_leader_view_id: Default::default(),
4921 },
4922 );
4923 cx.notify();
4924
4925 match leader_id {
4926 CollaboratorId::PeerId(leader_peer_id) => {
4927 let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
4928 let project_id = self.project.read(cx).remote_id();
4929 let request = self.app_state.client.request(proto::Follow {
4930 room_id,
4931 project_id,
4932 leader_id: Some(leader_peer_id),
4933 });
4934
4935 Some(cx.spawn_in(window, async move |this, cx| {
4936 let response = request.await?;
4937 this.update(cx, |this, _| {
4938 let state = this
4939 .follower_states
4940 .get_mut(&leader_id)
4941 .context("following interrupted")?;
4942 state.active_view_id = response
4943 .active_view
4944 .as_ref()
4945 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
4946 anyhow::Ok(())
4947 })??;
4948 if let Some(view) = response.active_view {
4949 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
4950 }
4951 this.update_in(cx, |this, window, cx| {
4952 this.leader_updated(leader_id, window, cx)
4953 })?;
4954 Ok(())
4955 }))
4956 }
4957 CollaboratorId::Agent => {
4958 self.leader_updated(leader_id, window, cx)?;
4959 Some(Task::ready(Ok(())))
4960 }
4961 }
4962 }
4963
4964 pub fn follow_next_collaborator(
4965 &mut self,
4966 _: &FollowNextCollaborator,
4967 window: &mut Window,
4968 cx: &mut Context<Self>,
4969 ) {
4970 let collaborators = self.project.read(cx).collaborators();
4971 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
4972 let mut collaborators = collaborators.keys().copied();
4973 for peer_id in collaborators.by_ref() {
4974 if CollaboratorId::PeerId(peer_id) == leader_id {
4975 break;
4976 }
4977 }
4978 collaborators.next().map(CollaboratorId::PeerId)
4979 } else if let Some(last_leader_id) =
4980 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
4981 {
4982 match last_leader_id {
4983 CollaboratorId::PeerId(peer_id) => {
4984 if collaborators.contains_key(peer_id) {
4985 Some(*last_leader_id)
4986 } else {
4987 None
4988 }
4989 }
4990 CollaboratorId::Agent => Some(CollaboratorId::Agent),
4991 }
4992 } else {
4993 None
4994 };
4995
4996 let pane = self.active_pane.clone();
4997 let Some(leader_id) = next_leader_id.or_else(|| {
4998 Some(CollaboratorId::PeerId(
4999 collaborators.keys().copied().next()?,
5000 ))
5001 }) else {
5002 return;
5003 };
5004 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5005 return;
5006 }
5007 if let Some(task) = self.start_following(leader_id, window, cx) {
5008 task.detach_and_log_err(cx)
5009 }
5010 }
5011
5012 pub fn follow(
5013 &mut self,
5014 leader_id: impl Into<CollaboratorId>,
5015 window: &mut Window,
5016 cx: &mut Context<Self>,
5017 ) {
5018 let leader_id = leader_id.into();
5019
5020 if let CollaboratorId::PeerId(peer_id) = leader_id {
5021 let Some(room) = ActiveCall::global(cx).read(cx).room() else {
5022 return;
5023 };
5024 let room = room.read(cx);
5025 let Some(remote_participant) = room.remote_participant_for_peer_id(peer_id) else {
5026 return;
5027 };
5028
5029 let project = self.project.read(cx);
5030
5031 let other_project_id = match remote_participant.location {
5032 call::ParticipantLocation::External => None,
5033 call::ParticipantLocation::UnsharedProject => None,
5034 call::ParticipantLocation::SharedProject { project_id } => {
5035 if Some(project_id) == project.remote_id() {
5036 None
5037 } else {
5038 Some(project_id)
5039 }
5040 }
5041 };
5042
5043 // if they are active in another project, follow there.
5044 if let Some(project_id) = other_project_id {
5045 let app_state = self.app_state.clone();
5046 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5047 .detach_and_log_err(cx);
5048 }
5049 }
5050
5051 // if you're already following, find the right pane and focus it.
5052 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5053 window.focus(&follower_state.pane().focus_handle(cx), cx);
5054
5055 return;
5056 }
5057
5058 // Otherwise, follow.
5059 if let Some(task) = self.start_following(leader_id, window, cx) {
5060 task.detach_and_log_err(cx)
5061 }
5062 }
5063
5064 pub fn unfollow(
5065 &mut self,
5066 leader_id: impl Into<CollaboratorId>,
5067 window: &mut Window,
5068 cx: &mut Context<Self>,
5069 ) -> Option<()> {
5070 cx.notify();
5071
5072 let leader_id = leader_id.into();
5073 let state = self.follower_states.remove(&leader_id)?;
5074 for (_, item) in state.items_by_leader_view_id {
5075 item.view.set_leader_id(None, window, cx);
5076 }
5077
5078 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5079 let project_id = self.project.read(cx).remote_id();
5080 let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
5081 self.app_state
5082 .client
5083 .send(proto::Unfollow {
5084 room_id,
5085 project_id,
5086 leader_id: Some(leader_peer_id),
5087 })
5088 .log_err();
5089 }
5090
5091 Some(())
5092 }
5093
5094 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5095 self.follower_states.contains_key(&id.into())
5096 }
5097
5098 fn active_item_path_changed(
5099 &mut self,
5100 focus_changed: bool,
5101 window: &mut Window,
5102 cx: &mut Context<Self>,
5103 ) {
5104 cx.emit(Event::ActiveItemChanged);
5105 let active_entry = self.active_project_path(cx);
5106 self.project.update(cx, |project, cx| {
5107 project.set_active_path(active_entry.clone(), cx)
5108 });
5109
5110 if focus_changed && let Some(project_path) = &active_entry {
5111 let git_store_entity = self.project.read(cx).git_store().clone();
5112 git_store_entity.update(cx, |git_store, cx| {
5113 git_store.set_active_repo_for_path(project_path, cx);
5114 });
5115 }
5116
5117 self.update_window_title(window, cx);
5118 }
5119
5120 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5121 let project = self.project().read(cx);
5122 let mut title = String::new();
5123
5124 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5125 let name = {
5126 let settings_location = SettingsLocation {
5127 worktree_id: worktree.read(cx).id(),
5128 path: RelPath::empty(),
5129 };
5130
5131 let settings = WorktreeSettings::get(Some(settings_location), cx);
5132 match &settings.project_name {
5133 Some(name) => name.as_str(),
5134 None => worktree.read(cx).root_name_str(),
5135 }
5136 };
5137 if i > 0 {
5138 title.push_str(", ");
5139 }
5140 title.push_str(name);
5141 }
5142
5143 if title.is_empty() {
5144 title = "empty project".to_string();
5145 }
5146
5147 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5148 let filename = path.path.file_name().or_else(|| {
5149 Some(
5150 project
5151 .worktree_for_id(path.worktree_id, cx)?
5152 .read(cx)
5153 .root_name_str(),
5154 )
5155 });
5156
5157 if let Some(filename) = filename {
5158 title.push_str(" — ");
5159 title.push_str(filename.as_ref());
5160 }
5161 }
5162
5163 if project.is_via_collab() {
5164 title.push_str(" ↙");
5165 } else if project.is_shared() {
5166 title.push_str(" ↗");
5167 }
5168
5169 if let Some(last_title) = self.last_window_title.as_ref()
5170 && &title == last_title
5171 {
5172 return;
5173 }
5174 window.set_window_title(&title);
5175 SystemWindowTabController::update_tab_title(
5176 cx,
5177 window.window_handle().window_id(),
5178 SharedString::from(&title),
5179 );
5180 self.last_window_title = Some(title);
5181 }
5182
5183 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5184 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5185 if is_edited != self.window_edited {
5186 self.window_edited = is_edited;
5187 window.set_window_edited(self.window_edited)
5188 }
5189 }
5190
5191 fn update_item_dirty_state(
5192 &mut self,
5193 item: &dyn ItemHandle,
5194 window: &mut Window,
5195 cx: &mut App,
5196 ) {
5197 let is_dirty = item.is_dirty(cx);
5198 let item_id = item.item_id();
5199 let was_dirty = self.dirty_items.contains_key(&item_id);
5200 if is_dirty == was_dirty {
5201 return;
5202 }
5203 if was_dirty {
5204 self.dirty_items.remove(&item_id);
5205 self.update_window_edited(window, cx);
5206 return;
5207 }
5208
5209 let workspace = self.weak_handle();
5210 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5211 return;
5212 };
5213 let on_release_callback = Box::new(move |cx: &mut App| {
5214 window_handle
5215 .update(cx, |_, window, cx| {
5216 workspace
5217 .update(cx, |workspace, cx| {
5218 workspace.dirty_items.remove(&item_id);
5219 workspace.update_window_edited(window, cx)
5220 })
5221 .ok();
5222 })
5223 .ok();
5224 });
5225
5226 let s = item.on_release(cx, on_release_callback);
5227 self.dirty_items.insert(item_id, s);
5228 self.update_window_edited(window, cx);
5229 }
5230
5231 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5232 if self.notifications.is_empty() {
5233 None
5234 } else {
5235 Some(
5236 div()
5237 .absolute()
5238 .right_3()
5239 .bottom_3()
5240 .w_112()
5241 .h_full()
5242 .flex()
5243 .flex_col()
5244 .justify_end()
5245 .gap_2()
5246 .children(
5247 self.notifications
5248 .iter()
5249 .map(|(_, notification)| notification.clone().into_any()),
5250 ),
5251 )
5252 }
5253 }
5254
5255 // RPC handlers
5256
5257 fn active_view_for_follower(
5258 &self,
5259 follower_project_id: Option<u64>,
5260 window: &mut Window,
5261 cx: &mut Context<Self>,
5262 ) -> Option<proto::View> {
5263 let (item, panel_id) = self.active_item_for_followers(window, cx);
5264 let item = item?;
5265 let leader_id = self
5266 .pane_for(&*item)
5267 .and_then(|pane| self.leader_for_pane(&pane));
5268 let leader_peer_id = match leader_id {
5269 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5270 Some(CollaboratorId::Agent) | None => None,
5271 };
5272
5273 let item_handle = item.to_followable_item_handle(cx)?;
5274 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5275 let variant = item_handle.to_state_proto(window, cx)?;
5276
5277 if item_handle.is_project_item(window, cx)
5278 && (follower_project_id.is_none()
5279 || follower_project_id != self.project.read(cx).remote_id())
5280 {
5281 return None;
5282 }
5283
5284 Some(proto::View {
5285 id: id.to_proto(),
5286 leader_id: leader_peer_id,
5287 variant: Some(variant),
5288 panel_id: panel_id.map(|id| id as i32),
5289 })
5290 }
5291
5292 fn handle_follow(
5293 &mut self,
5294 follower_project_id: Option<u64>,
5295 window: &mut Window,
5296 cx: &mut Context<Self>,
5297 ) -> proto::FollowResponse {
5298 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5299
5300 cx.notify();
5301 proto::FollowResponse {
5302 views: active_view.iter().cloned().collect(),
5303 active_view,
5304 }
5305 }
5306
5307 fn handle_update_followers(
5308 &mut self,
5309 leader_id: PeerId,
5310 message: proto::UpdateFollowers,
5311 _window: &mut Window,
5312 _cx: &mut Context<Self>,
5313 ) {
5314 self.leader_updates_tx
5315 .unbounded_send((leader_id, message))
5316 .ok();
5317 }
5318
5319 async fn process_leader_update(
5320 this: &WeakEntity<Self>,
5321 leader_id: PeerId,
5322 update: proto::UpdateFollowers,
5323 cx: &mut AsyncWindowContext,
5324 ) -> Result<()> {
5325 match update.variant.context("invalid update")? {
5326 proto::update_followers::Variant::CreateView(view) => {
5327 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5328 let should_add_view = this.update(cx, |this, _| {
5329 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5330 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5331 } else {
5332 anyhow::Ok(false)
5333 }
5334 })??;
5335
5336 if should_add_view {
5337 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5338 }
5339 }
5340 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5341 let should_add_view = this.update(cx, |this, _| {
5342 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5343 state.active_view_id = update_active_view
5344 .view
5345 .as_ref()
5346 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5347
5348 if state.active_view_id.is_some_and(|view_id| {
5349 !state.items_by_leader_view_id.contains_key(&view_id)
5350 }) {
5351 anyhow::Ok(true)
5352 } else {
5353 anyhow::Ok(false)
5354 }
5355 } else {
5356 anyhow::Ok(false)
5357 }
5358 })??;
5359
5360 if should_add_view && let Some(view) = update_active_view.view {
5361 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5362 }
5363 }
5364 proto::update_followers::Variant::UpdateView(update_view) => {
5365 let variant = update_view.variant.context("missing update view variant")?;
5366 let id = update_view.id.context("missing update view id")?;
5367 let mut tasks = Vec::new();
5368 this.update_in(cx, |this, window, cx| {
5369 let project = this.project.clone();
5370 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5371 let view_id = ViewId::from_proto(id.clone())?;
5372 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5373 tasks.push(item.view.apply_update_proto(
5374 &project,
5375 variant.clone(),
5376 window,
5377 cx,
5378 ));
5379 }
5380 }
5381 anyhow::Ok(())
5382 })??;
5383 try_join_all(tasks).await.log_err();
5384 }
5385 }
5386 this.update_in(cx, |this, window, cx| {
5387 this.leader_updated(leader_id, window, cx)
5388 })?;
5389 Ok(())
5390 }
5391
5392 async fn add_view_from_leader(
5393 this: WeakEntity<Self>,
5394 leader_id: PeerId,
5395 view: &proto::View,
5396 cx: &mut AsyncWindowContext,
5397 ) -> Result<()> {
5398 let this = this.upgrade().context("workspace dropped")?;
5399
5400 let Some(id) = view.id.clone() else {
5401 anyhow::bail!("no id for view");
5402 };
5403 let id = ViewId::from_proto(id)?;
5404 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5405
5406 let pane = this.update(cx, |this, _cx| {
5407 let state = this
5408 .follower_states
5409 .get(&leader_id.into())
5410 .context("stopped following")?;
5411 anyhow::Ok(state.pane().clone())
5412 })?;
5413 let existing_item = pane.update_in(cx, |pane, window, cx| {
5414 let client = this.read(cx).client().clone();
5415 pane.items().find_map(|item| {
5416 let item = item.to_followable_item_handle(cx)?;
5417 if item.remote_id(&client, window, cx) == Some(id) {
5418 Some(item)
5419 } else {
5420 None
5421 }
5422 })
5423 })?;
5424 let item = if let Some(existing_item) = existing_item {
5425 existing_item
5426 } else {
5427 let variant = view.variant.clone();
5428 anyhow::ensure!(variant.is_some(), "missing view variant");
5429
5430 let task = cx.update(|window, cx| {
5431 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5432 })?;
5433
5434 let Some(task) = task else {
5435 anyhow::bail!(
5436 "failed to construct view from leader (maybe from a different version of zed?)"
5437 );
5438 };
5439
5440 let mut new_item = task.await?;
5441 pane.update_in(cx, |pane, window, cx| {
5442 let mut item_to_remove = None;
5443 for (ix, item) in pane.items().enumerate() {
5444 if let Some(item) = item.to_followable_item_handle(cx) {
5445 match new_item.dedup(item.as_ref(), window, cx) {
5446 Some(item::Dedup::KeepExisting) => {
5447 new_item =
5448 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5449 break;
5450 }
5451 Some(item::Dedup::ReplaceExisting) => {
5452 item_to_remove = Some((ix, item.item_id()));
5453 break;
5454 }
5455 None => {}
5456 }
5457 }
5458 }
5459
5460 if let Some((ix, id)) = item_to_remove {
5461 pane.remove_item(id, false, false, window, cx);
5462 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5463 }
5464 })?;
5465
5466 new_item
5467 };
5468
5469 this.update_in(cx, |this, window, cx| {
5470 let state = this.follower_states.get_mut(&leader_id.into())?;
5471 item.set_leader_id(Some(leader_id.into()), window, cx);
5472 state.items_by_leader_view_id.insert(
5473 id,
5474 FollowerView {
5475 view: item,
5476 location: panel_id,
5477 },
5478 );
5479
5480 Some(())
5481 })
5482 .context("no follower state")?;
5483
5484 Ok(())
5485 }
5486
5487 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5488 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5489 return;
5490 };
5491
5492 if let Some(agent_location) = self.project.read(cx).agent_location() {
5493 let buffer_entity_id = agent_location.buffer.entity_id();
5494 let view_id = ViewId {
5495 creator: CollaboratorId::Agent,
5496 id: buffer_entity_id.as_u64(),
5497 };
5498 follower_state.active_view_id = Some(view_id);
5499
5500 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5501 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5502 hash_map::Entry::Vacant(entry) => {
5503 let existing_view =
5504 follower_state
5505 .center_pane
5506 .read(cx)
5507 .items()
5508 .find_map(|item| {
5509 let item = item.to_followable_item_handle(cx)?;
5510 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5511 && item.project_item_model_ids(cx).as_slice()
5512 == [buffer_entity_id]
5513 {
5514 Some(item)
5515 } else {
5516 None
5517 }
5518 });
5519 let view = existing_view.or_else(|| {
5520 agent_location.buffer.upgrade().and_then(|buffer| {
5521 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
5522 registry.build_item(buffer, self.project.clone(), None, window, cx)
5523 })?
5524 .to_followable_item_handle(cx)
5525 })
5526 });
5527
5528 view.map(|view| {
5529 entry.insert(FollowerView {
5530 view,
5531 location: None,
5532 })
5533 })
5534 }
5535 };
5536
5537 if let Some(item) = item {
5538 item.view
5539 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
5540 item.view
5541 .update_agent_location(agent_location.position, window, cx);
5542 }
5543 } else {
5544 follower_state.active_view_id = None;
5545 }
5546
5547 self.leader_updated(CollaboratorId::Agent, window, cx);
5548 }
5549
5550 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
5551 let mut is_project_item = true;
5552 let mut update = proto::UpdateActiveView::default();
5553 if window.is_window_active() {
5554 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
5555
5556 if let Some(item) = active_item
5557 && item.item_focus_handle(cx).contains_focused(window, cx)
5558 {
5559 let leader_id = self
5560 .pane_for(&*item)
5561 .and_then(|pane| self.leader_for_pane(&pane));
5562 let leader_peer_id = match leader_id {
5563 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5564 Some(CollaboratorId::Agent) | None => None,
5565 };
5566
5567 if let Some(item) = item.to_followable_item_handle(cx) {
5568 let id = item
5569 .remote_id(&self.app_state.client, window, cx)
5570 .map(|id| id.to_proto());
5571
5572 if let Some(id) = id
5573 && let Some(variant) = item.to_state_proto(window, cx)
5574 {
5575 let view = Some(proto::View {
5576 id,
5577 leader_id: leader_peer_id,
5578 variant: Some(variant),
5579 panel_id: panel_id.map(|id| id as i32),
5580 });
5581
5582 is_project_item = item.is_project_item(window, cx);
5583 update = proto::UpdateActiveView { view };
5584 };
5585 }
5586 }
5587 }
5588
5589 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
5590 if active_view_id != self.last_active_view_id.as_ref() {
5591 self.last_active_view_id = active_view_id.cloned();
5592 self.update_followers(
5593 is_project_item,
5594 proto::update_followers::Variant::UpdateActiveView(update),
5595 window,
5596 cx,
5597 );
5598 }
5599 }
5600
5601 fn active_item_for_followers(
5602 &self,
5603 window: &mut Window,
5604 cx: &mut App,
5605 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
5606 let mut active_item = None;
5607 let mut panel_id = None;
5608 for dock in self.all_docks() {
5609 if dock.focus_handle(cx).contains_focused(window, cx)
5610 && let Some(panel) = dock.read(cx).active_panel()
5611 && let Some(pane) = panel.pane(cx)
5612 && let Some(item) = pane.read(cx).active_item()
5613 {
5614 active_item = Some(item);
5615 panel_id = panel.remote_id();
5616 break;
5617 }
5618 }
5619
5620 if active_item.is_none() {
5621 active_item = self.active_pane().read(cx).active_item();
5622 }
5623 (active_item, panel_id)
5624 }
5625
5626 fn update_followers(
5627 &self,
5628 project_only: bool,
5629 update: proto::update_followers::Variant,
5630 _: &mut Window,
5631 cx: &mut App,
5632 ) -> Option<()> {
5633 // If this update only applies to for followers in the current project,
5634 // then skip it unless this project is shared. If it applies to all
5635 // followers, regardless of project, then set `project_id` to none,
5636 // indicating that it goes to all followers.
5637 let project_id = if project_only {
5638 Some(self.project.read(cx).remote_id()?)
5639 } else {
5640 None
5641 };
5642 self.app_state().workspace_store.update(cx, |store, cx| {
5643 store.update_followers(project_id, update, cx)
5644 })
5645 }
5646
5647 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
5648 self.follower_states.iter().find_map(|(leader_id, state)| {
5649 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
5650 Some(*leader_id)
5651 } else {
5652 None
5653 }
5654 })
5655 }
5656
5657 fn leader_updated(
5658 &mut self,
5659 leader_id: impl Into<CollaboratorId>,
5660 window: &mut Window,
5661 cx: &mut Context<Self>,
5662 ) -> Option<Box<dyn ItemHandle>> {
5663 cx.notify();
5664
5665 let leader_id = leader_id.into();
5666 let (panel_id, item) = match leader_id {
5667 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
5668 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
5669 };
5670
5671 let state = self.follower_states.get(&leader_id)?;
5672 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
5673 let pane;
5674 if let Some(panel_id) = panel_id {
5675 pane = self
5676 .activate_panel_for_proto_id(panel_id, window, cx)?
5677 .pane(cx)?;
5678 let state = self.follower_states.get_mut(&leader_id)?;
5679 state.dock_pane = Some(pane.clone());
5680 } else {
5681 pane = state.center_pane.clone();
5682 let state = self.follower_states.get_mut(&leader_id)?;
5683 if let Some(dock_pane) = state.dock_pane.take() {
5684 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
5685 }
5686 }
5687
5688 pane.update(cx, |pane, cx| {
5689 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
5690 if let Some(index) = pane.index_for_item(item.as_ref()) {
5691 pane.activate_item(index, false, false, window, cx);
5692 } else {
5693 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
5694 }
5695
5696 if focus_active_item {
5697 pane.focus_active_item(window, cx)
5698 }
5699 });
5700
5701 Some(item)
5702 }
5703
5704 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
5705 let state = self.follower_states.get(&CollaboratorId::Agent)?;
5706 let active_view_id = state.active_view_id?;
5707 Some(
5708 state
5709 .items_by_leader_view_id
5710 .get(&active_view_id)?
5711 .view
5712 .boxed_clone(),
5713 )
5714 }
5715
5716 fn active_item_for_peer(
5717 &self,
5718 peer_id: PeerId,
5719 window: &mut Window,
5720 cx: &mut Context<Self>,
5721 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
5722 let call = self.active_call()?;
5723 let room = call.read(cx).room()?.read(cx);
5724 let participant = room.remote_participant_for_peer_id(peer_id)?;
5725 let leader_in_this_app;
5726 let leader_in_this_project;
5727 match participant.location {
5728 call::ParticipantLocation::SharedProject { project_id } => {
5729 leader_in_this_app = true;
5730 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
5731 }
5732 call::ParticipantLocation::UnsharedProject => {
5733 leader_in_this_app = true;
5734 leader_in_this_project = false;
5735 }
5736 call::ParticipantLocation::External => {
5737 leader_in_this_app = false;
5738 leader_in_this_project = false;
5739 }
5740 };
5741 let state = self.follower_states.get(&peer_id.into())?;
5742 let mut item_to_activate = None;
5743 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
5744 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
5745 && (leader_in_this_project || !item.view.is_project_item(window, cx))
5746 {
5747 item_to_activate = Some((item.location, item.view.boxed_clone()));
5748 }
5749 } else if let Some(shared_screen) =
5750 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
5751 {
5752 item_to_activate = Some((None, Box::new(shared_screen)));
5753 }
5754 item_to_activate
5755 }
5756
5757 fn shared_screen_for_peer(
5758 &self,
5759 peer_id: PeerId,
5760 pane: &Entity<Pane>,
5761 window: &mut Window,
5762 cx: &mut App,
5763 ) -> Option<Entity<SharedScreen>> {
5764 let call = self.active_call()?;
5765 let room = call.read(cx).room()?.clone();
5766 let participant = room.read(cx).remote_participant_for_peer_id(peer_id)?;
5767 let track = participant.video_tracks.values().next()?.clone();
5768 let user = participant.user.clone();
5769
5770 for item in pane.read(cx).items_of_type::<SharedScreen>() {
5771 if item.read(cx).peer_id == peer_id {
5772 return Some(item);
5773 }
5774 }
5775
5776 Some(cx.new(|cx| SharedScreen::new(track, peer_id, user.clone(), room.clone(), window, cx)))
5777 }
5778
5779 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5780 if window.is_window_active() {
5781 self.update_active_view_for_followers(window, cx);
5782
5783 if let Some(database_id) = self.database_id {
5784 cx.background_spawn(persistence::DB.update_timestamp(database_id))
5785 .detach();
5786 }
5787 } else {
5788 for pane in &self.panes {
5789 pane.update(cx, |pane, cx| {
5790 if let Some(item) = pane.active_item() {
5791 item.workspace_deactivated(window, cx);
5792 }
5793 for item in pane.items() {
5794 if matches!(
5795 item.workspace_settings(cx).autosave,
5796 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
5797 ) {
5798 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
5799 .detach_and_log_err(cx);
5800 }
5801 }
5802 });
5803 }
5804 }
5805 }
5806
5807 pub fn active_call(&self) -> Option<&Entity<ActiveCall>> {
5808 self.active_call.as_ref().map(|(call, _)| call)
5809 }
5810
5811 fn on_active_call_event(
5812 &mut self,
5813 _: &Entity<ActiveCall>,
5814 event: &call::room::Event,
5815 window: &mut Window,
5816 cx: &mut Context<Self>,
5817 ) {
5818 match event {
5819 call::room::Event::ParticipantLocationChanged { participant_id }
5820 | call::room::Event::RemoteVideoTracksChanged { participant_id } => {
5821 self.leader_updated(participant_id, window, cx);
5822 }
5823 _ => {}
5824 }
5825 }
5826
5827 pub fn database_id(&self) -> Option<WorkspaceId> {
5828 self.database_id
5829 }
5830
5831 pub fn session_id(&self) -> Option<String> {
5832 self.session_id.clone()
5833 }
5834
5835 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
5836 let project = self.project().read(cx);
5837 project
5838 .visible_worktrees(cx)
5839 .map(|worktree| worktree.read(cx).abs_path())
5840 .collect::<Vec<_>>()
5841 }
5842
5843 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
5844 match member {
5845 Member::Axis(PaneAxis { members, .. }) => {
5846 for child in members.iter() {
5847 self.remove_panes(child.clone(), window, cx)
5848 }
5849 }
5850 Member::Pane(pane) => {
5851 self.force_remove_pane(&pane, &None, window, cx);
5852 }
5853 }
5854 }
5855
5856 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
5857 self.session_id.take();
5858 self.serialize_workspace_internal(window, cx)
5859 }
5860
5861 fn force_remove_pane(
5862 &mut self,
5863 pane: &Entity<Pane>,
5864 focus_on: &Option<Entity<Pane>>,
5865 window: &mut Window,
5866 cx: &mut Context<Workspace>,
5867 ) {
5868 self.panes.retain(|p| p != pane);
5869 if let Some(focus_on) = focus_on {
5870 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
5871 } else if self.active_pane() == pane {
5872 self.panes
5873 .last()
5874 .unwrap()
5875 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
5876 }
5877 if self.last_active_center_pane == Some(pane.downgrade()) {
5878 self.last_active_center_pane = None;
5879 }
5880 cx.notify();
5881 }
5882
5883 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5884 if self._schedule_serialize_workspace.is_none() {
5885 self._schedule_serialize_workspace =
5886 Some(cx.spawn_in(window, async move |this, cx| {
5887 cx.background_executor()
5888 .timer(SERIALIZATION_THROTTLE_TIME)
5889 .await;
5890 this.update_in(cx, |this, window, cx| {
5891 this.serialize_workspace_internal(window, cx).detach();
5892 this._schedule_serialize_workspace.take();
5893 })
5894 .log_err();
5895 }));
5896 }
5897 }
5898
5899 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
5900 let Some(database_id) = self.database_id() else {
5901 return Task::ready(());
5902 };
5903
5904 fn serialize_pane_handle(
5905 pane_handle: &Entity<Pane>,
5906 window: &mut Window,
5907 cx: &mut App,
5908 ) -> SerializedPane {
5909 let (items, active, pinned_count) = {
5910 let pane = pane_handle.read(cx);
5911 let active_item_id = pane.active_item().map(|item| item.item_id());
5912 (
5913 pane.items()
5914 .filter_map(|handle| {
5915 let handle = handle.to_serializable_item_handle(cx)?;
5916
5917 Some(SerializedItem {
5918 kind: Arc::from(handle.serialized_item_kind()),
5919 item_id: handle.item_id().as_u64(),
5920 active: Some(handle.item_id()) == active_item_id,
5921 preview: pane.is_active_preview_item(handle.item_id()),
5922 })
5923 })
5924 .collect::<Vec<_>>(),
5925 pane.has_focus(window, cx),
5926 pane.pinned_count(),
5927 )
5928 };
5929
5930 SerializedPane::new(items, active, pinned_count)
5931 }
5932
5933 fn build_serialized_pane_group(
5934 pane_group: &Member,
5935 window: &mut Window,
5936 cx: &mut App,
5937 ) -> SerializedPaneGroup {
5938 match pane_group {
5939 Member::Axis(PaneAxis {
5940 axis,
5941 members,
5942 flexes,
5943 bounding_boxes: _,
5944 }) => SerializedPaneGroup::Group {
5945 axis: SerializedAxis(*axis),
5946 children: members
5947 .iter()
5948 .map(|member| build_serialized_pane_group(member, window, cx))
5949 .collect::<Vec<_>>(),
5950 flexes: Some(flexes.lock().clone()),
5951 },
5952 Member::Pane(pane_handle) => {
5953 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
5954 }
5955 }
5956 }
5957
5958 fn build_serialized_docks(
5959 this: &Workspace,
5960 window: &mut Window,
5961 cx: &mut App,
5962 ) -> DockStructure {
5963 let left_dock = this.left_dock.read(cx);
5964 let left_visible = left_dock.is_open();
5965 let left_active_panel = left_dock
5966 .active_panel()
5967 .map(|panel| panel.persistent_name().to_string());
5968 let left_dock_zoom = left_dock
5969 .active_panel()
5970 .map(|panel| panel.is_zoomed(window, cx))
5971 .unwrap_or(false);
5972
5973 let right_dock = this.right_dock.read(cx);
5974 let right_visible = right_dock.is_open();
5975 let right_active_panel = right_dock
5976 .active_panel()
5977 .map(|panel| panel.persistent_name().to_string());
5978 let right_dock_zoom = right_dock
5979 .active_panel()
5980 .map(|panel| panel.is_zoomed(window, cx))
5981 .unwrap_or(false);
5982
5983 let bottom_dock = this.bottom_dock.read(cx);
5984 let bottom_visible = bottom_dock.is_open();
5985 let bottom_active_panel = bottom_dock
5986 .active_panel()
5987 .map(|panel| panel.persistent_name().to_string());
5988 let bottom_dock_zoom = bottom_dock
5989 .active_panel()
5990 .map(|panel| panel.is_zoomed(window, cx))
5991 .unwrap_or(false);
5992
5993 DockStructure {
5994 left: DockData {
5995 visible: left_visible,
5996 active_panel: left_active_panel,
5997 zoom: left_dock_zoom,
5998 },
5999 right: DockData {
6000 visible: right_visible,
6001 active_panel: right_active_panel,
6002 zoom: right_dock_zoom,
6003 },
6004 bottom: DockData {
6005 visible: bottom_visible,
6006 active_panel: bottom_active_panel,
6007 zoom: bottom_dock_zoom,
6008 },
6009 }
6010 }
6011
6012 match self.serialize_workspace_location(cx) {
6013 WorkspaceLocation::Location(location, paths) => {
6014 let breakpoints = self.project.update(cx, |project, cx| {
6015 project
6016 .breakpoint_store()
6017 .read(cx)
6018 .all_source_breakpoints(cx)
6019 });
6020 let user_toolchains = self
6021 .project
6022 .read(cx)
6023 .user_toolchains(cx)
6024 .unwrap_or_default();
6025
6026 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6027 let docks = build_serialized_docks(self, window, cx);
6028 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6029
6030 let serialized_workspace = SerializedWorkspace {
6031 id: database_id,
6032 location,
6033 paths,
6034 center_group,
6035 window_bounds,
6036 display: Default::default(),
6037 docks,
6038 centered_layout: self.centered_layout,
6039 session_id: self.session_id.clone(),
6040 breakpoints,
6041 window_id: Some(window.window_handle().window_id().as_u64()),
6042 user_toolchains,
6043 };
6044
6045 window.spawn(cx, async move |_| {
6046 persistence::DB.save_workspace(serialized_workspace).await;
6047 })
6048 }
6049 WorkspaceLocation::DetachFromSession => {
6050 let window_bounds = SerializedWindowBounds(window.window_bounds());
6051 let display = window.display(cx).and_then(|d| d.uuid().ok());
6052 // Save dock state for empty local workspaces
6053 let docks = build_serialized_docks(self, window, cx);
6054 window.spawn(cx, async move |_| {
6055 persistence::DB
6056 .set_window_open_status(
6057 database_id,
6058 window_bounds,
6059 display.unwrap_or_default(),
6060 )
6061 .await
6062 .log_err();
6063 persistence::DB
6064 .set_session_id(database_id, None)
6065 .await
6066 .log_err();
6067 persistence::write_default_dock_state(docks).await.log_err();
6068 })
6069 }
6070 WorkspaceLocation::None => {
6071 // Save dock state for empty non-local workspaces
6072 let docks = build_serialized_docks(self, window, cx);
6073 window.spawn(cx, async move |_| {
6074 persistence::write_default_dock_state(docks).await.log_err();
6075 })
6076 }
6077 }
6078 }
6079
6080 fn has_any_items_open(&self, cx: &App) -> bool {
6081 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6082 }
6083
6084 fn serialize_workspace_location(&self, cx: &App) -> WorkspaceLocation {
6085 let paths = PathList::new(&self.root_paths(cx));
6086 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6087 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6088 } else if self.project.read(cx).is_local() {
6089 if !paths.is_empty() || self.has_any_items_open(cx) {
6090 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6091 } else {
6092 WorkspaceLocation::DetachFromSession
6093 }
6094 } else {
6095 WorkspaceLocation::None
6096 }
6097 }
6098
6099 fn update_history(&self, cx: &mut App) {
6100 let Some(id) = self.database_id() else {
6101 return;
6102 };
6103 if !self.project.read(cx).is_local() {
6104 return;
6105 }
6106 if let Some(manager) = HistoryManager::global(cx) {
6107 let paths = PathList::new(&self.root_paths(cx));
6108 manager.update(cx, |this, cx| {
6109 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6110 });
6111 }
6112 }
6113
6114 async fn serialize_items(
6115 this: &WeakEntity<Self>,
6116 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6117 cx: &mut AsyncWindowContext,
6118 ) -> Result<()> {
6119 const CHUNK_SIZE: usize = 200;
6120
6121 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6122
6123 while let Some(items_received) = serializable_items.next().await {
6124 let unique_items =
6125 items_received
6126 .into_iter()
6127 .fold(HashMap::default(), |mut acc, item| {
6128 acc.entry(item.item_id()).or_insert(item);
6129 acc
6130 });
6131
6132 // We use into_iter() here so that the references to the items are moved into
6133 // the tasks and not kept alive while we're sleeping.
6134 for (_, item) in unique_items.into_iter() {
6135 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6136 item.serialize(workspace, false, window, cx)
6137 }) {
6138 cx.background_spawn(async move { task.await.log_err() })
6139 .detach();
6140 }
6141 }
6142
6143 cx.background_executor()
6144 .timer(SERIALIZATION_THROTTLE_TIME)
6145 .await;
6146 }
6147
6148 Ok(())
6149 }
6150
6151 pub(crate) fn enqueue_item_serialization(
6152 &mut self,
6153 item: Box<dyn SerializableItemHandle>,
6154 ) -> Result<()> {
6155 self.serializable_items_tx
6156 .unbounded_send(item)
6157 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6158 }
6159
6160 pub(crate) fn load_workspace(
6161 serialized_workspace: SerializedWorkspace,
6162 paths_to_open: Vec<Option<ProjectPath>>,
6163 window: &mut Window,
6164 cx: &mut Context<Workspace>,
6165 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6166 cx.spawn_in(window, async move |workspace, cx| {
6167 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6168
6169 let mut center_group = None;
6170 let mut center_items = None;
6171
6172 // Traverse the splits tree and add to things
6173 if let Some((group, active_pane, items)) = serialized_workspace
6174 .center_group
6175 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6176 .await
6177 {
6178 center_items = Some(items);
6179 center_group = Some((group, active_pane))
6180 }
6181
6182 let mut items_by_project_path = HashMap::default();
6183 let mut item_ids_by_kind = HashMap::default();
6184 let mut all_deserialized_items = Vec::default();
6185 cx.update(|_, cx| {
6186 for item in center_items.unwrap_or_default().into_iter().flatten() {
6187 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6188 item_ids_by_kind
6189 .entry(serializable_item_handle.serialized_item_kind())
6190 .or_insert(Vec::new())
6191 .push(item.item_id().as_u64() as ItemId);
6192 }
6193
6194 if let Some(project_path) = item.project_path(cx) {
6195 items_by_project_path.insert(project_path, item.clone());
6196 }
6197 all_deserialized_items.push(item);
6198 }
6199 })?;
6200
6201 let opened_items = paths_to_open
6202 .into_iter()
6203 .map(|path_to_open| {
6204 path_to_open
6205 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6206 })
6207 .collect::<Vec<_>>();
6208
6209 // Remove old panes from workspace panes list
6210 workspace.update_in(cx, |workspace, window, cx| {
6211 if let Some((center_group, active_pane)) = center_group {
6212 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6213
6214 // Swap workspace center group
6215 workspace.center = PaneGroup::with_root(center_group);
6216 workspace.center.set_is_center(true);
6217 workspace.center.mark_positions(cx);
6218
6219 if let Some(active_pane) = active_pane {
6220 workspace.set_active_pane(&active_pane, window, cx);
6221 cx.focus_self(window);
6222 } else {
6223 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6224 }
6225 }
6226
6227 let docks = serialized_workspace.docks;
6228
6229 for (dock, serialized_dock) in [
6230 (&mut workspace.right_dock, docks.right),
6231 (&mut workspace.left_dock, docks.left),
6232 (&mut workspace.bottom_dock, docks.bottom),
6233 ]
6234 .iter_mut()
6235 {
6236 dock.update(cx, |dock, cx| {
6237 dock.serialized_dock = Some(serialized_dock.clone());
6238 dock.restore_state(window, cx);
6239 });
6240 }
6241
6242 cx.notify();
6243 })?;
6244
6245 let _ = project
6246 .update(cx, |project, cx| {
6247 project
6248 .breakpoint_store()
6249 .update(cx, |breakpoint_store, cx| {
6250 breakpoint_store
6251 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6252 })
6253 })
6254 .await;
6255
6256 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6257 // after loading the items, we might have different items and in order to avoid
6258 // the database filling up, we delete items that haven't been loaded now.
6259 //
6260 // The items that have been loaded, have been saved after they've been added to the workspace.
6261 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6262 item_ids_by_kind
6263 .into_iter()
6264 .map(|(item_kind, loaded_items)| {
6265 SerializableItemRegistry::cleanup(
6266 item_kind,
6267 serialized_workspace.id,
6268 loaded_items,
6269 window,
6270 cx,
6271 )
6272 .log_err()
6273 })
6274 .collect::<Vec<_>>()
6275 })?;
6276
6277 futures::future::join_all(clean_up_tasks).await;
6278
6279 workspace
6280 .update_in(cx, |workspace, window, cx| {
6281 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6282 workspace.serialize_workspace_internal(window, cx).detach();
6283
6284 // Ensure that we mark the window as edited if we did load dirty items
6285 workspace.update_window_edited(window, cx);
6286 })
6287 .ok();
6288
6289 Ok(opened_items)
6290 })
6291 }
6292
6293 fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6294 self.add_workspace_actions_listeners(div, window, cx)
6295 .on_action(cx.listener(
6296 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6297 for action in &action_sequence.0 {
6298 window.dispatch_action(action.boxed_clone(), cx);
6299 }
6300 },
6301 ))
6302 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6303 .on_action(cx.listener(Self::close_all_items_and_panes))
6304 .on_action(cx.listener(Self::close_item_in_all_panes))
6305 .on_action(cx.listener(Self::save_all))
6306 .on_action(cx.listener(Self::send_keystrokes))
6307 .on_action(cx.listener(Self::add_folder_to_project))
6308 .on_action(cx.listener(Self::follow_next_collaborator))
6309 .on_action(cx.listener(Self::close_window))
6310 .on_action(cx.listener(Self::activate_pane_at_index))
6311 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6312 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6313 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6314 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6315 let pane = workspace.active_pane().clone();
6316 workspace.unfollow_in_pane(&pane, window, cx);
6317 }))
6318 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6319 workspace
6320 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6321 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6322 }))
6323 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6324 workspace
6325 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6326 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6327 }))
6328 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6329 workspace
6330 .save_active_item(SaveIntent::SaveAs, window, cx)
6331 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6332 }))
6333 .on_action(
6334 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6335 workspace.activate_previous_pane(window, cx)
6336 }),
6337 )
6338 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6339 workspace.activate_next_pane(window, cx)
6340 }))
6341 .on_action(
6342 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6343 workspace.activate_next_window(cx)
6344 }),
6345 )
6346 .on_action(
6347 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6348 workspace.activate_previous_window(cx)
6349 }),
6350 )
6351 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6352 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6353 }))
6354 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6355 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6356 }))
6357 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6358 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6359 }))
6360 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6361 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6362 }))
6363 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6364 workspace.activate_next_pane(window, cx)
6365 }))
6366 .on_action(cx.listener(
6367 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6368 workspace.move_item_to_pane_in_direction(action, window, cx)
6369 },
6370 ))
6371 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6372 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6373 }))
6374 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6375 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6376 }))
6377 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6378 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6379 }))
6380 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6381 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6382 }))
6383 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6384 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6385 SplitDirection::Down,
6386 SplitDirection::Up,
6387 SplitDirection::Right,
6388 SplitDirection::Left,
6389 ];
6390 for dir in DIRECTION_PRIORITY {
6391 if workspace.find_pane_in_direction(dir, cx).is_some() {
6392 workspace.swap_pane_in_direction(dir, cx);
6393 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6394 break;
6395 }
6396 }
6397 }))
6398 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6399 workspace.move_pane_to_border(SplitDirection::Left, cx)
6400 }))
6401 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6402 workspace.move_pane_to_border(SplitDirection::Right, cx)
6403 }))
6404 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6405 workspace.move_pane_to_border(SplitDirection::Up, cx)
6406 }))
6407 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6408 workspace.move_pane_to_border(SplitDirection::Down, cx)
6409 }))
6410 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6411 this.toggle_dock(DockPosition::Left, window, cx);
6412 }))
6413 .on_action(cx.listener(
6414 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6415 workspace.toggle_dock(DockPosition::Right, window, cx);
6416 },
6417 ))
6418 .on_action(cx.listener(
6419 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6420 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6421 },
6422 ))
6423 .on_action(cx.listener(
6424 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6425 if !workspace.close_active_dock(window, cx) {
6426 cx.propagate();
6427 }
6428 },
6429 ))
6430 .on_action(
6431 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6432 workspace.close_all_docks(window, cx);
6433 }),
6434 )
6435 .on_action(cx.listener(Self::toggle_all_docks))
6436 .on_action(cx.listener(
6437 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6438 workspace.clear_all_notifications(cx);
6439 },
6440 ))
6441 .on_action(cx.listener(
6442 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6443 workspace.clear_navigation_history(window, cx);
6444 },
6445 ))
6446 .on_action(cx.listener(
6447 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6448 if let Some((notification_id, _)) = workspace.notifications.pop() {
6449 workspace.suppress_notification(¬ification_id, cx);
6450 }
6451 },
6452 ))
6453 .on_action(cx.listener(
6454 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
6455 workspace.show_worktree_trust_security_modal(true, window, cx);
6456 },
6457 ))
6458 .on_action(
6459 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
6460 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
6461 trusted_worktrees.update(cx, |trusted_worktrees, _| {
6462 trusted_worktrees.clear_trusted_paths()
6463 });
6464 let clear_task = persistence::DB.clear_trusted_worktrees();
6465 cx.spawn(async move |_, cx| {
6466 if clear_task.await.log_err().is_some() {
6467 cx.update(|cx| reload(cx));
6468 }
6469 })
6470 .detach();
6471 }
6472 }),
6473 )
6474 .on_action(cx.listener(
6475 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
6476 workspace.reopen_closed_item(window, cx).detach();
6477 },
6478 ))
6479 .on_action(cx.listener(
6480 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
6481 for dock in workspace.all_docks() {
6482 if dock.focus_handle(cx).contains_focused(window, cx) {
6483 let Some(panel) = dock.read(cx).active_panel() else {
6484 return;
6485 };
6486
6487 // Set to `None`, then the size will fall back to the default.
6488 panel.clone().set_size(None, window, cx);
6489
6490 return;
6491 }
6492 }
6493 },
6494 ))
6495 .on_action(cx.listener(
6496 |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
6497 for dock in workspace.all_docks() {
6498 if let Some(panel) = dock.read(cx).visible_panel() {
6499 // Set to `None`, then the size will fall back to the default.
6500 panel.clone().set_size(None, window, cx);
6501 }
6502 }
6503 },
6504 ))
6505 .on_action(cx.listener(
6506 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
6507 adjust_active_dock_size_by_px(
6508 px_with_ui_font_fallback(act.px, cx),
6509 workspace,
6510 window,
6511 cx,
6512 );
6513 },
6514 ))
6515 .on_action(cx.listener(
6516 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
6517 adjust_active_dock_size_by_px(
6518 px_with_ui_font_fallback(act.px, cx) * -1.,
6519 workspace,
6520 window,
6521 cx,
6522 );
6523 },
6524 ))
6525 .on_action(cx.listener(
6526 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
6527 adjust_open_docks_size_by_px(
6528 px_with_ui_font_fallback(act.px, cx),
6529 workspace,
6530 window,
6531 cx,
6532 );
6533 },
6534 ))
6535 .on_action(cx.listener(
6536 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
6537 adjust_open_docks_size_by_px(
6538 px_with_ui_font_fallback(act.px, cx) * -1.,
6539 workspace,
6540 window,
6541 cx,
6542 );
6543 },
6544 ))
6545 .on_action(cx.listener(Workspace::toggle_centered_layout))
6546 .on_action(cx.listener(
6547 |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
6548 if let Some(active_dock) = workspace.active_dock(window, cx) {
6549 let dock = active_dock.read(cx);
6550 if let Some(active_panel) = dock.active_panel() {
6551 if active_panel.pane(cx).is_none() {
6552 let mut recent_pane: Option<Entity<Pane>> = None;
6553 let mut recent_timestamp = 0;
6554 for pane_handle in workspace.panes() {
6555 let pane = pane_handle.read(cx);
6556 for entry in pane.activation_history() {
6557 if entry.timestamp > recent_timestamp {
6558 recent_timestamp = entry.timestamp;
6559 recent_pane = Some(pane_handle.clone());
6560 }
6561 }
6562 }
6563
6564 if let Some(pane) = recent_pane {
6565 pane.update(cx, |pane, cx| {
6566 let current_index = pane.active_item_index();
6567 let items_len = pane.items_len();
6568 if items_len > 0 {
6569 let next_index = if current_index + 1 < items_len {
6570 current_index + 1
6571 } else {
6572 0
6573 };
6574 pane.activate_item(
6575 next_index, false, false, window, cx,
6576 );
6577 }
6578 });
6579 return;
6580 }
6581 }
6582 }
6583 }
6584 cx.propagate();
6585 },
6586 ))
6587 .on_action(cx.listener(
6588 |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
6589 if let Some(active_dock) = workspace.active_dock(window, cx) {
6590 let dock = active_dock.read(cx);
6591 if let Some(active_panel) = dock.active_panel() {
6592 if active_panel.pane(cx).is_none() {
6593 let mut recent_pane: Option<Entity<Pane>> = None;
6594 let mut recent_timestamp = 0;
6595 for pane_handle in workspace.panes() {
6596 let pane = pane_handle.read(cx);
6597 for entry in pane.activation_history() {
6598 if entry.timestamp > recent_timestamp {
6599 recent_timestamp = entry.timestamp;
6600 recent_pane = Some(pane_handle.clone());
6601 }
6602 }
6603 }
6604
6605 if let Some(pane) = recent_pane {
6606 pane.update(cx, |pane, cx| {
6607 let current_index = pane.active_item_index();
6608 let items_len = pane.items_len();
6609 if items_len > 0 {
6610 let prev_index = if current_index > 0 {
6611 current_index - 1
6612 } else {
6613 items_len.saturating_sub(1)
6614 };
6615 pane.activate_item(
6616 prev_index, false, false, window, cx,
6617 );
6618 }
6619 });
6620 return;
6621 }
6622 }
6623 }
6624 }
6625 cx.propagate();
6626 },
6627 ))
6628 .on_action(cx.listener(
6629 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
6630 if let Some(active_dock) = workspace.active_dock(window, cx) {
6631 let dock = active_dock.read(cx);
6632 if let Some(active_panel) = dock.active_panel() {
6633 if active_panel.pane(cx).is_none() {
6634 let active_pane = workspace.active_pane().clone();
6635 active_pane.update(cx, |pane, cx| {
6636 pane.close_active_item(action, window, cx)
6637 .detach_and_log_err(cx);
6638 });
6639 return;
6640 }
6641 }
6642 }
6643 cx.propagate();
6644 },
6645 ))
6646 .on_action(
6647 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
6648 let pane = workspace.active_pane().clone();
6649 if let Some(item) = pane.read(cx).active_item() {
6650 item.toggle_read_only(window, cx);
6651 }
6652 }),
6653 )
6654 .on_action(cx.listener(Workspace::cancel))
6655 }
6656
6657 #[cfg(any(test, feature = "test-support"))]
6658 pub fn set_random_database_id(&mut self) {
6659 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
6660 }
6661
6662 #[cfg(any(test, feature = "test-support"))]
6663 pub(crate) fn test_new(
6664 project: Entity<Project>,
6665 window: &mut Window,
6666 cx: &mut Context<Self>,
6667 ) -> Self {
6668 use node_runtime::NodeRuntime;
6669 use session::Session;
6670
6671 let client = project.read(cx).client();
6672 let user_store = project.read(cx).user_store();
6673 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
6674 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
6675 window.activate_window();
6676 let app_state = Arc::new(AppState {
6677 languages: project.read(cx).languages().clone(),
6678 workspace_store,
6679 client,
6680 user_store,
6681 fs: project.read(cx).fs().clone(),
6682 build_window_options: |_, _| Default::default(),
6683 node_runtime: NodeRuntime::unavailable(),
6684 session,
6685 });
6686 let workspace = Self::new(Default::default(), project, app_state, window, cx);
6687 workspace
6688 .active_pane
6689 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6690 workspace
6691 }
6692
6693 pub fn register_action<A: Action>(
6694 &mut self,
6695 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
6696 ) -> &mut Self {
6697 let callback = Arc::new(callback);
6698
6699 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
6700 let callback = callback.clone();
6701 div.on_action(cx.listener(move |workspace, event, window, cx| {
6702 (callback)(workspace, event, window, cx)
6703 }))
6704 }));
6705 self
6706 }
6707 pub fn register_action_renderer(
6708 &mut self,
6709 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
6710 ) -> &mut Self {
6711 self.workspace_actions.push(Box::new(callback));
6712 self
6713 }
6714
6715 fn add_workspace_actions_listeners(
6716 &self,
6717 mut div: Div,
6718 window: &mut Window,
6719 cx: &mut Context<Self>,
6720 ) -> Div {
6721 for action in self.workspace_actions.iter() {
6722 div = (action)(div, self, window, cx)
6723 }
6724 div
6725 }
6726
6727 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
6728 self.modal_layer.read(cx).has_active_modal()
6729 }
6730
6731 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
6732 self.modal_layer.read(cx).active_modal()
6733 }
6734
6735 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
6736 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
6737 /// If no modal is active, the new modal will be shown.
6738 ///
6739 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
6740 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
6741 /// will not be shown.
6742 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
6743 where
6744 B: FnOnce(&mut Window, &mut Context<V>) -> V,
6745 {
6746 self.modal_layer.update(cx, |modal_layer, cx| {
6747 modal_layer.toggle_modal(window, cx, build)
6748 })
6749 }
6750
6751 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
6752 self.modal_layer
6753 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
6754 }
6755
6756 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
6757 self.toast_layer
6758 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
6759 }
6760
6761 pub fn toggle_centered_layout(
6762 &mut self,
6763 _: &ToggleCenteredLayout,
6764 _: &mut Window,
6765 cx: &mut Context<Self>,
6766 ) {
6767 self.centered_layout = !self.centered_layout;
6768 if let Some(database_id) = self.database_id() {
6769 cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
6770 .detach_and_log_err(cx);
6771 }
6772 cx.notify();
6773 }
6774
6775 fn adjust_padding(padding: Option<f32>) -> f32 {
6776 padding
6777 .unwrap_or(CenteredPaddingSettings::default().0)
6778 .clamp(
6779 CenteredPaddingSettings::MIN_PADDING,
6780 CenteredPaddingSettings::MAX_PADDING,
6781 )
6782 }
6783
6784 fn render_dock(
6785 &self,
6786 position: DockPosition,
6787 dock: &Entity<Dock>,
6788 window: &mut Window,
6789 cx: &mut App,
6790 ) -> Option<Div> {
6791 if self.zoomed_position == Some(position) {
6792 return None;
6793 }
6794
6795 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
6796 let pane = panel.pane(cx)?;
6797 let follower_states = &self.follower_states;
6798 leader_border_for_pane(follower_states, &pane, window, cx)
6799 });
6800
6801 Some(
6802 div()
6803 .flex()
6804 .flex_none()
6805 .overflow_hidden()
6806 .child(dock.clone())
6807 .children(leader_border),
6808 )
6809 }
6810
6811 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
6812 window
6813 .root::<MultiWorkspace>()
6814 .flatten()
6815 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
6816 }
6817
6818 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
6819 self.zoomed.as_ref()
6820 }
6821
6822 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
6823 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
6824 return;
6825 };
6826 let windows = cx.windows();
6827 let next_window =
6828 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
6829 || {
6830 windows
6831 .iter()
6832 .cycle()
6833 .skip_while(|window| window.window_id() != current_window_id)
6834 .nth(1)
6835 },
6836 );
6837
6838 if let Some(window) = next_window {
6839 window
6840 .update(cx, |_, window, _| window.activate_window())
6841 .ok();
6842 }
6843 }
6844
6845 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
6846 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
6847 return;
6848 };
6849 let windows = cx.windows();
6850 let prev_window =
6851 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
6852 || {
6853 windows
6854 .iter()
6855 .rev()
6856 .cycle()
6857 .skip_while(|window| window.window_id() != current_window_id)
6858 .nth(1)
6859 },
6860 );
6861
6862 if let Some(window) = prev_window {
6863 window
6864 .update(cx, |_, window, _| window.activate_window())
6865 .ok();
6866 }
6867 }
6868
6869 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
6870 if cx.stop_active_drag(window) {
6871 } else if let Some((notification_id, _)) = self.notifications.pop() {
6872 dismiss_app_notification(¬ification_id, cx);
6873 } else {
6874 cx.propagate();
6875 }
6876 }
6877
6878 fn adjust_dock_size_by_px(
6879 &mut self,
6880 panel_size: Pixels,
6881 dock_pos: DockPosition,
6882 px: Pixels,
6883 window: &mut Window,
6884 cx: &mut Context<Self>,
6885 ) {
6886 match dock_pos {
6887 DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
6888 DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
6889 DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
6890 }
6891 }
6892
6893 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6894 let size = new_size.min(self.bounds.right() - RESIZE_HANDLE_SIZE);
6895
6896 self.left_dock.update(cx, |left_dock, cx| {
6897 if WorkspaceSettings::get_global(cx)
6898 .resize_all_panels_in_dock
6899 .contains(&DockPosition::Left)
6900 {
6901 left_dock.resize_all_panels(Some(size), window, cx);
6902 } else {
6903 left_dock.resize_active_panel(Some(size), window, cx);
6904 }
6905 });
6906 self.clamp_utility_pane_widths(window, cx);
6907 }
6908
6909 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6910 let mut size = new_size.max(self.bounds.left() - RESIZE_HANDLE_SIZE);
6911 self.left_dock.read_with(cx, |left_dock, cx| {
6912 let left_dock_size = left_dock
6913 .active_panel_size(window, cx)
6914 .unwrap_or(Pixels::ZERO);
6915 if left_dock_size + size > self.bounds.right() {
6916 size = self.bounds.right() - left_dock_size
6917 }
6918 });
6919 self.right_dock.update(cx, |right_dock, cx| {
6920 if WorkspaceSettings::get_global(cx)
6921 .resize_all_panels_in_dock
6922 .contains(&DockPosition::Right)
6923 {
6924 right_dock.resize_all_panels(Some(size), window, cx);
6925 } else {
6926 right_dock.resize_active_panel(Some(size), window, cx);
6927 }
6928 });
6929 self.clamp_utility_pane_widths(window, cx);
6930 }
6931
6932 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6933 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
6934 self.bottom_dock.update(cx, |bottom_dock, cx| {
6935 if WorkspaceSettings::get_global(cx)
6936 .resize_all_panels_in_dock
6937 .contains(&DockPosition::Bottom)
6938 {
6939 bottom_dock.resize_all_panels(Some(size), window, cx);
6940 } else {
6941 bottom_dock.resize_active_panel(Some(size), window, cx);
6942 }
6943 });
6944 self.clamp_utility_pane_widths(window, cx);
6945 }
6946
6947 fn max_utility_pane_width(&self, window: &Window, cx: &App) -> Pixels {
6948 let left_dock_width = self
6949 .left_dock
6950 .read(cx)
6951 .active_panel_size(window, cx)
6952 .unwrap_or(px(0.0));
6953 let right_dock_width = self
6954 .right_dock
6955 .read(cx)
6956 .active_panel_size(window, cx)
6957 .unwrap_or(px(0.0));
6958 let center_pane_width = self.bounds.size.width - left_dock_width - right_dock_width;
6959 center_pane_width - px(10.0)
6960 }
6961
6962 fn clamp_utility_pane_widths(&mut self, window: &mut Window, cx: &mut App) {
6963 let max_width = self.max_utility_pane_width(window, cx);
6964
6965 // Clamp left slot utility pane if it exists
6966 if let Some(handle) = self.utility_pane(UtilityPaneSlot::Left) {
6967 let current_width = handle.width(cx);
6968 if current_width > max_width {
6969 handle.set_width(Some(max_width.max(UTILITY_PANE_MIN_WIDTH)), cx);
6970 }
6971 }
6972
6973 // Clamp right slot utility pane if it exists
6974 if let Some(handle) = self.utility_pane(UtilityPaneSlot::Right) {
6975 let current_width = handle.width(cx);
6976 if current_width > max_width {
6977 handle.set_width(Some(max_width.max(UTILITY_PANE_MIN_WIDTH)), cx);
6978 }
6979 }
6980 }
6981
6982 fn toggle_edit_predictions_all_files(
6983 &mut self,
6984 _: &ToggleEditPrediction,
6985 _window: &mut Window,
6986 cx: &mut Context<Self>,
6987 ) {
6988 let fs = self.project().read(cx).fs().clone();
6989 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
6990 update_settings_file(fs, cx, move |file, _| {
6991 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
6992 });
6993 }
6994
6995 pub fn show_worktree_trust_security_modal(
6996 &mut self,
6997 toggle: bool,
6998 window: &mut Window,
6999 cx: &mut Context<Self>,
7000 ) {
7001 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7002 if toggle {
7003 security_modal.update(cx, |security_modal, cx| {
7004 security_modal.dismiss(cx);
7005 })
7006 } else {
7007 security_modal.update(cx, |security_modal, cx| {
7008 security_modal.refresh_restricted_paths(cx);
7009 });
7010 }
7011 } else {
7012 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7013 .map(|trusted_worktrees| {
7014 trusted_worktrees
7015 .read(cx)
7016 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7017 })
7018 .unwrap_or(false);
7019 if has_restricted_worktrees {
7020 let project = self.project().read(cx);
7021 let remote_host = project
7022 .remote_connection_options(cx)
7023 .map(RemoteHostLocation::from);
7024 let worktree_store = project.worktree_store().downgrade();
7025 self.toggle_modal(window, cx, |_, cx| {
7026 SecurityModal::new(worktree_store, remote_host, cx)
7027 });
7028 }
7029 }
7030 }
7031}
7032
7033fn leader_border_for_pane(
7034 follower_states: &HashMap<CollaboratorId, FollowerState>,
7035 pane: &Entity<Pane>,
7036 _: &Window,
7037 cx: &App,
7038) -> Option<Div> {
7039 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7040 if state.pane() == pane {
7041 Some((*leader_id, state))
7042 } else {
7043 None
7044 }
7045 })?;
7046
7047 let mut leader_color = match leader_id {
7048 CollaboratorId::PeerId(leader_peer_id) => {
7049 let room = ActiveCall::try_global(cx)?.read(cx).room()?.read(cx);
7050 let leader = room.remote_participant_for_peer_id(leader_peer_id)?;
7051
7052 cx.theme()
7053 .players()
7054 .color_for_participant(leader.participant_index.0)
7055 .cursor
7056 }
7057 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7058 };
7059 leader_color.fade_out(0.3);
7060 Some(
7061 div()
7062 .absolute()
7063 .size_full()
7064 .left_0()
7065 .top_0()
7066 .border_2()
7067 .border_color(leader_color),
7068 )
7069}
7070
7071fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7072 ZED_WINDOW_POSITION
7073 .zip(*ZED_WINDOW_SIZE)
7074 .map(|(position, size)| Bounds {
7075 origin: position,
7076 size,
7077 })
7078}
7079
7080fn open_items(
7081 serialized_workspace: Option<SerializedWorkspace>,
7082 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7083 window: &mut Window,
7084 cx: &mut Context<Workspace>,
7085) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7086 let restored_items = serialized_workspace.map(|serialized_workspace| {
7087 Workspace::load_workspace(
7088 serialized_workspace,
7089 project_paths_to_open
7090 .iter()
7091 .map(|(_, project_path)| project_path)
7092 .cloned()
7093 .collect(),
7094 window,
7095 cx,
7096 )
7097 });
7098
7099 cx.spawn_in(window, async move |workspace, cx| {
7100 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7101
7102 if let Some(restored_items) = restored_items {
7103 let restored_items = restored_items.await?;
7104
7105 let restored_project_paths = restored_items
7106 .iter()
7107 .filter_map(|item| {
7108 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7109 .ok()
7110 .flatten()
7111 })
7112 .collect::<HashSet<_>>();
7113
7114 for restored_item in restored_items {
7115 opened_items.push(restored_item.map(Ok));
7116 }
7117
7118 project_paths_to_open
7119 .iter_mut()
7120 .for_each(|(_, project_path)| {
7121 if let Some(project_path_to_open) = project_path
7122 && restored_project_paths.contains(project_path_to_open)
7123 {
7124 *project_path = None;
7125 }
7126 });
7127 } else {
7128 for _ in 0..project_paths_to_open.len() {
7129 opened_items.push(None);
7130 }
7131 }
7132 assert!(opened_items.len() == project_paths_to_open.len());
7133
7134 let tasks =
7135 project_paths_to_open
7136 .into_iter()
7137 .enumerate()
7138 .map(|(ix, (abs_path, project_path))| {
7139 let workspace = workspace.clone();
7140 cx.spawn(async move |cx| {
7141 let file_project_path = project_path?;
7142 let abs_path_task = workspace.update(cx, |workspace, cx| {
7143 workspace.project().update(cx, |project, cx| {
7144 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7145 })
7146 });
7147
7148 // We only want to open file paths here. If one of the items
7149 // here is a directory, it was already opened further above
7150 // with a `find_or_create_worktree`.
7151 if let Ok(task) = abs_path_task
7152 && task.await.is_none_or(|p| p.is_file())
7153 {
7154 return Some((
7155 ix,
7156 workspace
7157 .update_in(cx, |workspace, window, cx| {
7158 workspace.open_path(
7159 file_project_path,
7160 None,
7161 true,
7162 window,
7163 cx,
7164 )
7165 })
7166 .log_err()?
7167 .await,
7168 ));
7169 }
7170 None
7171 })
7172 });
7173
7174 let tasks = tasks.collect::<Vec<_>>();
7175
7176 let tasks = futures::future::join_all(tasks);
7177 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7178 opened_items[ix] = Some(path_open_result);
7179 }
7180
7181 Ok(opened_items)
7182 })
7183}
7184
7185enum ActivateInDirectionTarget {
7186 Pane(Entity<Pane>),
7187 Dock(Entity<Dock>),
7188}
7189
7190fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7191 window
7192 .update(cx, |multi_workspace, _, cx| {
7193 let workspace = multi_workspace.workspace().clone();
7194 workspace.update(cx, |workspace, cx| {
7195 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7196 struct DatabaseFailedNotification;
7197
7198 workspace.show_notification(
7199 NotificationId::unique::<DatabaseFailedNotification>(),
7200 cx,
7201 |cx| {
7202 cx.new(|cx| {
7203 MessageNotification::new("Failed to load the database file.", cx)
7204 .primary_message("File an Issue")
7205 .primary_icon(IconName::Plus)
7206 .primary_on_click(|window, cx| {
7207 window.dispatch_action(Box::new(FileBugReport), cx)
7208 })
7209 })
7210 },
7211 );
7212 }
7213 });
7214 })
7215 .log_err();
7216}
7217
7218fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7219 if val == 0 {
7220 ThemeSettings::get_global(cx).ui_font_size(cx)
7221 } else {
7222 px(val as f32)
7223 }
7224}
7225
7226fn adjust_active_dock_size_by_px(
7227 px: Pixels,
7228 workspace: &mut Workspace,
7229 window: &mut Window,
7230 cx: &mut Context<Workspace>,
7231) {
7232 let Some(active_dock) = workspace
7233 .all_docks()
7234 .into_iter()
7235 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7236 else {
7237 return;
7238 };
7239 let dock = active_dock.read(cx);
7240 let Some(panel_size) = dock.active_panel_size(window, cx) else {
7241 return;
7242 };
7243 let dock_pos = dock.position();
7244 workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
7245}
7246
7247fn adjust_open_docks_size_by_px(
7248 px: Pixels,
7249 workspace: &mut Workspace,
7250 window: &mut Window,
7251 cx: &mut Context<Workspace>,
7252) {
7253 let docks = workspace
7254 .all_docks()
7255 .into_iter()
7256 .filter_map(|dock| {
7257 if dock.read(cx).is_open() {
7258 let dock = dock.read(cx);
7259 let panel_size = dock.active_panel_size(window, cx)?;
7260 let dock_pos = dock.position();
7261 Some((panel_size, dock_pos, px))
7262 } else {
7263 None
7264 }
7265 })
7266 .collect::<Vec<_>>();
7267
7268 docks
7269 .into_iter()
7270 .for_each(|(panel_size, dock_pos, offset)| {
7271 workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
7272 });
7273}
7274
7275impl Focusable for Workspace {
7276 fn focus_handle(&self, cx: &App) -> FocusHandle {
7277 self.active_pane.focus_handle(cx)
7278 }
7279}
7280
7281#[derive(Clone)]
7282struct DraggedDock(DockPosition);
7283
7284impl Render for DraggedDock {
7285 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7286 gpui::Empty
7287 }
7288}
7289
7290impl Render for Workspace {
7291 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7292 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
7293 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
7294 log::info!("Rendered first frame");
7295 }
7296 let mut context = KeyContext::new_with_defaults();
7297 context.add("Workspace");
7298 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
7299 if let Some(status) = self
7300 .debugger_provider
7301 .as_ref()
7302 .and_then(|provider| provider.active_thread_state(cx))
7303 {
7304 match status {
7305 ThreadStatus::Running | ThreadStatus::Stepping => {
7306 context.add("debugger_running");
7307 }
7308 ThreadStatus::Stopped => context.add("debugger_stopped"),
7309 ThreadStatus::Exited | ThreadStatus::Ended => {}
7310 }
7311 }
7312
7313 if self.left_dock.read(cx).is_open() {
7314 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
7315 context.set("left_dock", active_panel.panel_key());
7316 }
7317 }
7318
7319 if self.right_dock.read(cx).is_open() {
7320 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
7321 context.set("right_dock", active_panel.panel_key());
7322 }
7323 }
7324
7325 if self.bottom_dock.read(cx).is_open() {
7326 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
7327 context.set("bottom_dock", active_panel.panel_key());
7328 }
7329 }
7330
7331 let centered_layout = self.centered_layout
7332 && self.center.panes().len() == 1
7333 && self.active_item(cx).is_some();
7334 let render_padding = |size| {
7335 (size > 0.0).then(|| {
7336 div()
7337 .h_full()
7338 .w(relative(size))
7339 .bg(cx.theme().colors().editor_background)
7340 .border_color(cx.theme().colors().pane_group_border)
7341 })
7342 };
7343 let paddings = if centered_layout {
7344 let settings = WorkspaceSettings::get_global(cx).centered_layout;
7345 (
7346 render_padding(Self::adjust_padding(
7347 settings.left_padding.map(|padding| padding.0),
7348 )),
7349 render_padding(Self::adjust_padding(
7350 settings.right_padding.map(|padding| padding.0),
7351 )),
7352 )
7353 } else {
7354 (None, None)
7355 };
7356 let ui_font = theme::setup_ui_font(window, cx);
7357
7358 let theme = cx.theme().clone();
7359 let colors = theme.colors();
7360 let notification_entities = self
7361 .notifications
7362 .iter()
7363 .map(|(_, notification)| notification.entity_id())
7364 .collect::<Vec<_>>();
7365 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
7366
7367 self.actions(div(), window, cx)
7368 .key_context(context)
7369 .relative()
7370 .size_full()
7371 .flex()
7372 .flex_col()
7373 .font(ui_font)
7374 .gap_0()
7375 .justify_start()
7376 .items_start()
7377 .text_color(colors.text)
7378 .overflow_hidden()
7379 .children(self.titlebar_item.clone())
7380 .on_modifiers_changed(move |_, _, cx| {
7381 for &id in ¬ification_entities {
7382 cx.notify(id);
7383 }
7384 })
7385 .child(
7386 div()
7387 .size_full()
7388 .relative()
7389 .flex_1()
7390 .flex()
7391 .flex_col()
7392 .child(
7393 div()
7394 .id("workspace")
7395 .bg(colors.background)
7396 .relative()
7397 .flex_1()
7398 .w_full()
7399 .flex()
7400 .flex_col()
7401 .overflow_hidden()
7402 .border_t_1()
7403 .border_b_1()
7404 .border_color(colors.border)
7405 .child({
7406 let this = cx.entity();
7407 canvas(
7408 move |bounds, window, cx| {
7409 this.update(cx, |this, cx| {
7410 let bounds_changed = this.bounds != bounds;
7411 this.bounds = bounds;
7412
7413 if bounds_changed {
7414 this.left_dock.update(cx, |dock, cx| {
7415 dock.clamp_panel_size(
7416 bounds.size.width,
7417 window,
7418 cx,
7419 )
7420 });
7421
7422 this.right_dock.update(cx, |dock, cx| {
7423 dock.clamp_panel_size(
7424 bounds.size.width,
7425 window,
7426 cx,
7427 )
7428 });
7429
7430 this.bottom_dock.update(cx, |dock, cx| {
7431 dock.clamp_panel_size(
7432 bounds.size.height,
7433 window,
7434 cx,
7435 )
7436 });
7437 }
7438 })
7439 },
7440 |_, _, _, _| {},
7441 )
7442 .absolute()
7443 .size_full()
7444 })
7445 .when(self.zoomed.is_none(), |this| {
7446 this.on_drag_move(cx.listener(
7447 move |workspace,
7448 e: &DragMoveEvent<DraggedDock>,
7449 window,
7450 cx| {
7451 if workspace.previous_dock_drag_coordinates
7452 != Some(e.event.position)
7453 {
7454 workspace.previous_dock_drag_coordinates =
7455 Some(e.event.position);
7456 match e.drag(cx).0 {
7457 DockPosition::Left => {
7458 workspace.resize_left_dock(
7459 e.event.position.x
7460 - workspace.bounds.left(),
7461 window,
7462 cx,
7463 );
7464 }
7465 DockPosition::Right => {
7466 workspace.resize_right_dock(
7467 workspace.bounds.right()
7468 - e.event.position.x,
7469 window,
7470 cx,
7471 );
7472 }
7473 DockPosition::Bottom => {
7474 workspace.resize_bottom_dock(
7475 workspace.bounds.bottom()
7476 - e.event.position.y,
7477 window,
7478 cx,
7479 );
7480 }
7481 };
7482 workspace.serialize_workspace(window, cx);
7483 }
7484 },
7485 ))
7486 .on_drag_move(cx.listener(
7487 move |workspace,
7488 e: &DragMoveEvent<DraggedUtilityPane>,
7489 window,
7490 cx| {
7491 let slot = e.drag(cx).0;
7492 match slot {
7493 UtilityPaneSlot::Left => {
7494 let left_dock_width = workspace.left_dock.read(cx)
7495 .active_panel_size(window, cx)
7496 .unwrap_or(gpui::px(0.0));
7497 let new_width = e.event.position.x
7498 - workspace.bounds.left()
7499 - left_dock_width;
7500 workspace.resize_utility_pane(slot, new_width, window, cx);
7501 }
7502 UtilityPaneSlot::Right => {
7503 let right_dock_width = workspace.right_dock.read(cx)
7504 .active_panel_size(window, cx)
7505 .unwrap_or(gpui::px(0.0));
7506 let new_width = workspace.bounds.right()
7507 - e.event.position.x
7508 - right_dock_width;
7509 workspace.resize_utility_pane(slot, new_width, window, cx);
7510 }
7511 }
7512 },
7513 ))
7514 })
7515 .child({
7516 match bottom_dock_layout {
7517 BottomDockLayout::Full => div()
7518 .flex()
7519 .flex_col()
7520 .h_full()
7521 .child(
7522 div()
7523 .flex()
7524 .flex_row()
7525 .flex_1()
7526 .overflow_hidden()
7527 .children(self.render_dock(
7528 DockPosition::Left,
7529 &self.left_dock,
7530 window,
7531 cx,
7532 ))
7533 .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
7534 this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
7535 this.when(pane.expanded(cx), |this| {
7536 this.child(
7537 UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
7538 )
7539 })
7540 })
7541 })
7542 .child(
7543 div()
7544 .flex()
7545 .flex_col()
7546 .flex_1()
7547 .overflow_hidden()
7548 .child(
7549 h_flex()
7550 .flex_1()
7551 .when_some(
7552 paddings.0,
7553 |this, p| {
7554 this.child(
7555 p.border_r_1(),
7556 )
7557 },
7558 )
7559 .child(self.center.render(
7560 self.zoomed.as_ref(),
7561 &PaneRenderContext {
7562 follower_states:
7563 &self.follower_states,
7564 active_call: self.active_call(),
7565 active_pane: &self.active_pane,
7566 app_state: &self.app_state,
7567 project: &self.project,
7568 workspace: &self.weak_self,
7569 },
7570 window,
7571 cx,
7572 ))
7573 .when_some(
7574 paddings.1,
7575 |this, p| {
7576 this.child(
7577 p.border_l_1(),
7578 )
7579 },
7580 ),
7581 ),
7582 )
7583 .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
7584 this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
7585 this.when(pane.expanded(cx), |this| {
7586 this.child(
7587 UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
7588 )
7589 })
7590 })
7591 })
7592 .children(self.render_dock(
7593 DockPosition::Right,
7594 &self.right_dock,
7595 window,
7596 cx,
7597 )),
7598 )
7599 .child(div().w_full().children(self.render_dock(
7600 DockPosition::Bottom,
7601 &self.bottom_dock,
7602 window,
7603 cx
7604 ))),
7605
7606 BottomDockLayout::LeftAligned => div()
7607 .flex()
7608 .flex_row()
7609 .h_full()
7610 .child(
7611 div()
7612 .flex()
7613 .flex_col()
7614 .flex_1()
7615 .h_full()
7616 .child(
7617 div()
7618 .flex()
7619 .flex_row()
7620 .flex_1()
7621 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
7622 .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
7623 this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
7624 this.when(pane.expanded(cx), |this| {
7625 this.child(
7626 UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
7627 )
7628 })
7629 })
7630 })
7631 .child(
7632 div()
7633 .flex()
7634 .flex_col()
7635 .flex_1()
7636 .overflow_hidden()
7637 .child(
7638 h_flex()
7639 .flex_1()
7640 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7641 .child(self.center.render(
7642 self.zoomed.as_ref(),
7643 &PaneRenderContext {
7644 follower_states:
7645 &self.follower_states,
7646 active_call: self.active_call(),
7647 active_pane: &self.active_pane,
7648 app_state: &self.app_state,
7649 project: &self.project,
7650 workspace: &self.weak_self,
7651 },
7652 window,
7653 cx,
7654 ))
7655 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7656 )
7657 )
7658 .when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
7659 this.when(pane.expanded(cx), |this| {
7660 this.child(
7661 UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
7662 )
7663 })
7664 })
7665 )
7666 .child(
7667 div()
7668 .w_full()
7669 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7670 ),
7671 )
7672 .children(self.render_dock(
7673 DockPosition::Right,
7674 &self.right_dock,
7675 window,
7676 cx,
7677 )),
7678
7679 BottomDockLayout::RightAligned => div()
7680 .flex()
7681 .flex_row()
7682 .h_full()
7683 .children(self.render_dock(
7684 DockPosition::Left,
7685 &self.left_dock,
7686 window,
7687 cx,
7688 ))
7689 .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
7690 this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
7691 this.when(pane.expanded(cx), |this| {
7692 this.child(
7693 UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
7694 )
7695 })
7696 })
7697 })
7698 .child(
7699 div()
7700 .flex()
7701 .flex_col()
7702 .flex_1()
7703 .h_full()
7704 .child(
7705 div()
7706 .flex()
7707 .flex_row()
7708 .flex_1()
7709 .child(
7710 div()
7711 .flex()
7712 .flex_col()
7713 .flex_1()
7714 .overflow_hidden()
7715 .child(
7716 h_flex()
7717 .flex_1()
7718 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7719 .child(self.center.render(
7720 self.zoomed.as_ref(),
7721 &PaneRenderContext {
7722 follower_states:
7723 &self.follower_states,
7724 active_call: self.active_call(),
7725 active_pane: &self.active_pane,
7726 app_state: &self.app_state,
7727 project: &self.project,
7728 workspace: &self.weak_self,
7729 },
7730 window,
7731 cx,
7732 ))
7733 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7734 )
7735 )
7736 .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
7737 this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
7738 this.when(pane.expanded(cx), |this| {
7739 this.child(
7740 UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
7741 )
7742 })
7743 })
7744 })
7745 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
7746 )
7747 .child(
7748 div()
7749 .w_full()
7750 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7751 ),
7752 ),
7753
7754 BottomDockLayout::Contained => div()
7755 .flex()
7756 .flex_row()
7757 .h_full()
7758 .children(self.render_dock(
7759 DockPosition::Left,
7760 &self.left_dock,
7761 window,
7762 cx,
7763 ))
7764 .when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
7765 this.when(pane.expanded(cx), |this| {
7766 this.child(
7767 UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
7768 )
7769 })
7770 })
7771 .child(
7772 div()
7773 .flex()
7774 .flex_col()
7775 .flex_1()
7776 .overflow_hidden()
7777 .child(
7778 h_flex()
7779 .flex_1()
7780 .when_some(paddings.0, |this, p| {
7781 this.child(p.border_r_1())
7782 })
7783 .child(self.center.render(
7784 self.zoomed.as_ref(),
7785 &PaneRenderContext {
7786 follower_states:
7787 &self.follower_states,
7788 active_call: self.active_call(),
7789 active_pane: &self.active_pane,
7790 app_state: &self.app_state,
7791 project: &self.project,
7792 workspace: &self.weak_self,
7793 },
7794 window,
7795 cx,
7796 ))
7797 .when_some(paddings.1, |this, p| {
7798 this.child(p.border_l_1())
7799 }),
7800 )
7801 .children(self.render_dock(
7802 DockPosition::Bottom,
7803 &self.bottom_dock,
7804 window,
7805 cx,
7806 )),
7807 )
7808 .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
7809 this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
7810 this.when(pane.expanded(cx), |this| {
7811 this.child(
7812 UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
7813 )
7814 })
7815 })
7816 })
7817 .children(self.render_dock(
7818 DockPosition::Right,
7819 &self.right_dock,
7820 window,
7821 cx,
7822 )),
7823 }
7824 })
7825 .children(self.zoomed.as_ref().and_then(|view| {
7826 let zoomed_view = view.upgrade()?;
7827 let div = div()
7828 .occlude()
7829 .absolute()
7830 .overflow_hidden()
7831 .border_color(colors.border)
7832 .bg(colors.background)
7833 .child(zoomed_view)
7834 .inset_0()
7835 .shadow_lg();
7836
7837 if !WorkspaceSettings::get_global(cx).zoomed_padding {
7838 return Some(div);
7839 }
7840
7841 Some(match self.zoomed_position {
7842 Some(DockPosition::Left) => div.right_2().border_r_1(),
7843 Some(DockPosition::Right) => div.left_2().border_l_1(),
7844 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
7845 None => {
7846 div.top_2().bottom_2().left_2().right_2().border_1()
7847 }
7848 })
7849 }))
7850 .children(self.render_notifications(window, cx)),
7851 )
7852 .when(self.status_bar_visible(cx), |parent| {
7853 parent.child(self.status_bar.clone())
7854 })
7855 .child(self.modal_layer.clone())
7856 .child(self.toast_layer.clone()),
7857 )
7858 }
7859}
7860
7861impl WorkspaceStore {
7862 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
7863 Self {
7864 workspaces: Default::default(),
7865 _subscriptions: vec![
7866 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
7867 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
7868 ],
7869 client,
7870 }
7871 }
7872
7873 pub fn update_followers(
7874 &self,
7875 project_id: Option<u64>,
7876 update: proto::update_followers::Variant,
7877 cx: &App,
7878 ) -> Option<()> {
7879 let active_call = ActiveCall::try_global(cx)?;
7880 let room_id = active_call.read(cx).room()?.read(cx).id();
7881 self.client
7882 .send(proto::UpdateFollowers {
7883 room_id,
7884 project_id,
7885 variant: Some(update),
7886 })
7887 .log_err()
7888 }
7889
7890 pub async fn handle_follow(
7891 this: Entity<Self>,
7892 envelope: TypedEnvelope<proto::Follow>,
7893 mut cx: AsyncApp,
7894 ) -> Result<proto::FollowResponse> {
7895 this.update(&mut cx, |this, cx| {
7896 let follower = Follower {
7897 project_id: envelope.payload.project_id,
7898 peer_id: envelope.original_sender_id()?,
7899 };
7900
7901 let mut response = proto::FollowResponse::default();
7902
7903 this.workspaces.retain(|(window_handle, weak_workspace)| {
7904 let Some(workspace) = weak_workspace.upgrade() else {
7905 return false;
7906 };
7907 window_handle
7908 .update(cx, |_, window, cx| {
7909 workspace.update(cx, |workspace, cx| {
7910 let handler_response =
7911 workspace.handle_follow(follower.project_id, window, cx);
7912 if let Some(active_view) = handler_response.active_view
7913 && workspace.project.read(cx).remote_id() == follower.project_id
7914 {
7915 response.active_view = Some(active_view)
7916 }
7917 });
7918 })
7919 .is_ok()
7920 });
7921
7922 Ok(response)
7923 })
7924 }
7925
7926 async fn handle_update_followers(
7927 this: Entity<Self>,
7928 envelope: TypedEnvelope<proto::UpdateFollowers>,
7929 mut cx: AsyncApp,
7930 ) -> Result<()> {
7931 let leader_id = envelope.original_sender_id()?;
7932 let update = envelope.payload;
7933
7934 this.update(&mut cx, |this, cx| {
7935 this.workspaces.retain(|(window_handle, weak_workspace)| {
7936 let Some(workspace) = weak_workspace.upgrade() else {
7937 return false;
7938 };
7939 window_handle
7940 .update(cx, |_, window, cx| {
7941 workspace.update(cx, |workspace, cx| {
7942 let project_id = workspace.project.read(cx).remote_id();
7943 if update.project_id != project_id && update.project_id.is_some() {
7944 return;
7945 }
7946 workspace.handle_update_followers(
7947 leader_id,
7948 update.clone(),
7949 window,
7950 cx,
7951 );
7952 });
7953 })
7954 .is_ok()
7955 });
7956 Ok(())
7957 })
7958 }
7959
7960 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
7961 self.workspaces.iter().map(|(_, weak)| weak)
7962 }
7963
7964 pub fn workspaces_with_windows(
7965 &self,
7966 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
7967 self.workspaces.iter().map(|(window, weak)| (*window, weak))
7968 }
7969}
7970
7971impl ViewId {
7972 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
7973 Ok(Self {
7974 creator: message
7975 .creator
7976 .map(CollaboratorId::PeerId)
7977 .context("creator is missing")?,
7978 id: message.id,
7979 })
7980 }
7981
7982 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
7983 if let CollaboratorId::PeerId(peer_id) = self.creator {
7984 Some(proto::ViewId {
7985 creator: Some(peer_id),
7986 id: self.id,
7987 })
7988 } else {
7989 None
7990 }
7991 }
7992}
7993
7994impl FollowerState {
7995 fn pane(&self) -> &Entity<Pane> {
7996 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
7997 }
7998}
7999
8000pub trait WorkspaceHandle {
8001 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8002}
8003
8004impl WorkspaceHandle for Entity<Workspace> {
8005 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8006 self.read(cx)
8007 .worktrees(cx)
8008 .flat_map(|worktree| {
8009 let worktree_id = worktree.read(cx).id();
8010 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8011 worktree_id,
8012 path: f.path.clone(),
8013 })
8014 })
8015 .collect::<Vec<_>>()
8016 }
8017}
8018
8019pub async fn last_opened_workspace_location(
8020 fs: &dyn fs::Fs,
8021) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8022 DB.last_workspace(fs).await.log_err().flatten()
8023}
8024
8025pub async fn last_session_workspace_locations(
8026 last_session_id: &str,
8027 last_session_window_stack: Option<Vec<WindowId>>,
8028 fs: &dyn fs::Fs,
8029) -> Option<Vec<SessionWorkspace>> {
8030 DB.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8031 .await
8032 .log_err()
8033}
8034
8035pub async fn restore_multiworkspace(
8036 multi_workspace: SerializedMultiWorkspace,
8037 app_state: Arc<AppState>,
8038 cx: &mut AsyncApp,
8039) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8040 let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
8041 let mut group_iter = workspaces.into_iter();
8042 let first = group_iter
8043 .next()
8044 .context("window group must not be empty")?;
8045
8046 let window_handle = if first.paths.is_empty() {
8047 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
8048 .await?
8049 } else {
8050 let (window, _items) = cx
8051 .update(|cx| {
8052 Workspace::new_local(
8053 first.paths.paths().to_vec(),
8054 app_state.clone(),
8055 None,
8056 None,
8057 None,
8058 cx,
8059 )
8060 })
8061 .await?;
8062 window
8063 };
8064
8065 for session_workspace in group_iter {
8066 if session_workspace.paths.is_empty() {
8067 cx.update(|cx| {
8068 open_workspace_by_id(
8069 session_workspace.workspace_id,
8070 app_state.clone(),
8071 Some(window_handle),
8072 cx,
8073 )
8074 })
8075 .await?;
8076 } else {
8077 cx.update(|cx| {
8078 Workspace::new_local(
8079 session_workspace.paths.paths().to_vec(),
8080 app_state.clone(),
8081 Some(window_handle),
8082 None,
8083 None,
8084 cx,
8085 )
8086 })
8087 .await?;
8088 }
8089 }
8090
8091 if let Some(target_id) = state.active_workspace_id {
8092 window_handle
8093 .update(cx, |multi_workspace, window, cx| {
8094 let target_index = multi_workspace
8095 .workspaces()
8096 .iter()
8097 .position(|ws| ws.read(cx).database_id() == Some(target_id));
8098 if let Some(index) = target_index {
8099 multi_workspace.activate_index(index, window, cx);
8100 } else if !multi_workspace.workspaces().is_empty() {
8101 multi_workspace.activate_index(0, window, cx);
8102 }
8103 })
8104 .ok();
8105 } else {
8106 window_handle
8107 .update(cx, |multi_workspace, window, cx| {
8108 if !multi_workspace.workspaces().is_empty() {
8109 multi_workspace.activate_index(0, window, cx);
8110 }
8111 })
8112 .ok();
8113 }
8114
8115 if state.sidebar_open {
8116 window_handle
8117 .update(cx, |multi_workspace, window, cx| {
8118 multi_workspace.open_sidebar(window, cx);
8119 })
8120 .ok();
8121 }
8122
8123 window_handle
8124 .update(cx, |_, window, _cx| {
8125 window.activate_window();
8126 })
8127 .ok();
8128
8129 Ok(window_handle)
8130}
8131
8132actions!(
8133 collab,
8134 [
8135 /// Opens the channel notes for the current call.
8136 ///
8137 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8138 /// channel in the collab panel.
8139 ///
8140 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8141 /// can be copied via "Copy link to section" in the context menu of the channel notes
8142 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8143 OpenChannelNotes,
8144 /// Mutes your microphone.
8145 Mute,
8146 /// Deafens yourself (mute both microphone and speakers).
8147 Deafen,
8148 /// Leaves the current call.
8149 LeaveCall,
8150 /// Shares the current project with collaborators.
8151 ShareProject,
8152 /// Shares your screen with collaborators.
8153 ScreenShare,
8154 /// Copies the current room name and session id for debugging purposes.
8155 CopyRoomId,
8156 ]
8157);
8158actions!(
8159 zed,
8160 [
8161 /// Opens the Zed log file.
8162 OpenLog,
8163 /// Reveals the Zed log file in the system file manager.
8164 RevealLogInFileManager
8165 ]
8166);
8167
8168async fn join_channel_internal(
8169 channel_id: ChannelId,
8170 app_state: &Arc<AppState>,
8171 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8172 requesting_workspace: Option<WeakEntity<Workspace>>,
8173 active_call: &Entity<ActiveCall>,
8174 cx: &mut AsyncApp,
8175) -> Result<bool> {
8176 let (should_prompt, open_room) = active_call.update(cx, |active_call, cx| {
8177 let Some(room) = active_call.room().map(|room| room.read(cx)) else {
8178 return (false, None);
8179 };
8180
8181 let already_in_channel = room.channel_id() == Some(channel_id);
8182 let should_prompt = room.is_sharing_project()
8183 && !room.remote_participants().is_empty()
8184 && !already_in_channel;
8185 let open_room = if already_in_channel {
8186 active_call.room().cloned()
8187 } else {
8188 None
8189 };
8190 (should_prompt, open_room)
8191 });
8192
8193 if let Some(room) = open_room {
8194 let task = room.update(cx, |room, cx| {
8195 if let Some((project, host)) = room.most_active_project(cx) {
8196 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8197 }
8198
8199 None
8200 });
8201 if let Some(task) = task {
8202 task.await?;
8203 }
8204 return anyhow::Ok(true);
8205 }
8206
8207 if should_prompt {
8208 if let Some(multi_workspace) = requesting_window {
8209 let answer = multi_workspace
8210 .update(cx, |_, window, cx| {
8211 window.prompt(
8212 PromptLevel::Warning,
8213 "Do you want to switch channels?",
8214 Some("Leaving this call will unshare your current project."),
8215 &["Yes, Join Channel", "Cancel"],
8216 cx,
8217 )
8218 })?
8219 .await;
8220
8221 if answer == Ok(1) {
8222 return Ok(false);
8223 }
8224 } else {
8225 return Ok(false); // unreachable!() hopefully
8226 }
8227 }
8228
8229 let client = cx.update(|cx| active_call.read(cx).client());
8230
8231 let mut client_status = client.status();
8232
8233 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8234 'outer: loop {
8235 let Some(status) = client_status.recv().await else {
8236 anyhow::bail!("error connecting");
8237 };
8238
8239 match status {
8240 Status::Connecting
8241 | Status::Authenticating
8242 | Status::Authenticated
8243 | Status::Reconnecting
8244 | Status::Reauthenticating
8245 | Status::Reauthenticated => continue,
8246 Status::Connected { .. } => break 'outer,
8247 Status::SignedOut | Status::AuthenticationError => {
8248 return Err(ErrorCode::SignedOut.into());
8249 }
8250 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8251 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8252 return Err(ErrorCode::Disconnected.into());
8253 }
8254 }
8255 }
8256
8257 let room = active_call
8258 .update(cx, |active_call, cx| {
8259 active_call.join_channel(channel_id, cx)
8260 })
8261 .await?;
8262
8263 let Some(room) = room else {
8264 return anyhow::Ok(true);
8265 };
8266
8267 room.update(cx, |room, _| room.room_update_completed())
8268 .await;
8269
8270 let task = room.update(cx, |room, cx| {
8271 if let Some((project, host)) = room.most_active_project(cx) {
8272 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8273 }
8274
8275 // If you are the first to join a channel, see if you should share your project.
8276 if room.remote_participants().is_empty()
8277 && !room.local_participant_is_guest()
8278 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8279 {
8280 let project = workspace.update(cx, |workspace, cx| {
8281 let project = workspace.project.read(cx);
8282
8283 if !CallSettings::get_global(cx).share_on_join {
8284 return None;
8285 }
8286
8287 if (project.is_local() || project.is_via_remote_server())
8288 && project.visible_worktrees(cx).any(|tree| {
8289 tree.read(cx)
8290 .root_entry()
8291 .is_some_and(|entry| entry.is_dir())
8292 })
8293 {
8294 Some(workspace.project.clone())
8295 } else {
8296 None
8297 }
8298 });
8299 if let Some(project) = project {
8300 return Some(cx.spawn(async move |room, cx| {
8301 room.update(cx, |room, cx| room.share_project(project, cx))?
8302 .await?;
8303 Ok(())
8304 }));
8305 }
8306 }
8307
8308 None
8309 });
8310 if let Some(task) = task {
8311 task.await?;
8312 return anyhow::Ok(true);
8313 }
8314 anyhow::Ok(false)
8315}
8316
8317pub fn join_channel(
8318 channel_id: ChannelId,
8319 app_state: Arc<AppState>,
8320 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8321 requesting_workspace: Option<WeakEntity<Workspace>>,
8322 cx: &mut App,
8323) -> Task<Result<()>> {
8324 let active_call = ActiveCall::global(cx);
8325 cx.spawn(async move |cx| {
8326 let result = join_channel_internal(
8327 channel_id,
8328 &app_state,
8329 requesting_window,
8330 requesting_workspace,
8331 &active_call,
8332 cx,
8333 )
8334 .await;
8335
8336 // join channel succeeded, and opened a window
8337 if matches!(result, Ok(true)) {
8338 return anyhow::Ok(());
8339 }
8340
8341 // find an existing workspace to focus and show call controls
8342 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8343 if active_window.is_none() {
8344 // no open workspaces, make one to show the error in (blergh)
8345 let (window_handle, _) = cx
8346 .update(|cx| {
8347 Workspace::new_local(
8348 vec![],
8349 app_state.clone(),
8350 requesting_window,
8351 None,
8352 None,
8353 cx,
8354 )
8355 })
8356 .await?;
8357
8358 window_handle
8359 .update(cx, |_, window, _cx| {
8360 window.activate_window();
8361 })
8362 .ok();
8363
8364 if result.is_ok() {
8365 cx.update(|cx| {
8366 cx.dispatch_action(&OpenChannelNotes);
8367 });
8368 }
8369
8370 active_window = Some(window_handle);
8371 }
8372
8373 if let Err(err) = result {
8374 log::error!("failed to join channel: {}", err);
8375 if let Some(active_window) = active_window {
8376 active_window
8377 .update(cx, |_, window, cx| {
8378 let detail: SharedString = match err.error_code() {
8379 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8380 ErrorCode::UpgradeRequired => concat!(
8381 "Your are running an unsupported version of Zed. ",
8382 "Please update to continue."
8383 )
8384 .into(),
8385 ErrorCode::NoSuchChannel => concat!(
8386 "No matching channel was found. ",
8387 "Please check the link and try again."
8388 )
8389 .into(),
8390 ErrorCode::Forbidden => concat!(
8391 "This channel is private, and you do not have access. ",
8392 "Please ask someone to add you and try again."
8393 )
8394 .into(),
8395 ErrorCode::Disconnected => {
8396 "Please check your internet connection and try again.".into()
8397 }
8398 _ => format!("{}\n\nPlease try again.", err).into(),
8399 };
8400 window.prompt(
8401 PromptLevel::Critical,
8402 "Failed to join channel",
8403 Some(&detail),
8404 &["Ok"],
8405 cx,
8406 )
8407 })?
8408 .await
8409 .ok();
8410 }
8411 }
8412
8413 // return ok, we showed the error to the user.
8414 anyhow::Ok(())
8415 })
8416}
8417
8418pub async fn get_any_active_multi_workspace(
8419 app_state: Arc<AppState>,
8420 mut cx: AsyncApp,
8421) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8422 // find an existing workspace to focus and show call controls
8423 let active_window = activate_any_workspace_window(&mut cx);
8424 if active_window.is_none() {
8425 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, cx))
8426 .await?;
8427 }
8428 activate_any_workspace_window(&mut cx).context("could not open zed")
8429}
8430
8431fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
8432 cx.update(|cx| {
8433 if let Some(workspace_window) = cx
8434 .active_window()
8435 .and_then(|window| window.downcast::<MultiWorkspace>())
8436 {
8437 return Some(workspace_window);
8438 }
8439
8440 for window in cx.windows() {
8441 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
8442 workspace_window
8443 .update(cx, |_, window, _| window.activate_window())
8444 .ok();
8445 return Some(workspace_window);
8446 }
8447 }
8448 None
8449 })
8450}
8451
8452pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
8453 cx.windows()
8454 .into_iter()
8455 .filter_map(|window| window.downcast::<MultiWorkspace>())
8456 .filter(|multi_workspace| {
8457 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
8458 multi_workspace
8459 .workspaces()
8460 .iter()
8461 .any(|workspace| workspace.read(cx).project.read(cx).is_local())
8462 })
8463 })
8464 .collect()
8465}
8466
8467#[derive(Default)]
8468pub struct OpenOptions {
8469 pub visible: Option<OpenVisible>,
8470 pub focus: Option<bool>,
8471 pub open_new_workspace: Option<bool>,
8472 pub prefer_focused_window: bool,
8473 pub replace_window: Option<WindowHandle<MultiWorkspace>>,
8474 pub env: Option<HashMap<String, String>>,
8475}
8476
8477/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
8478pub fn open_workspace_by_id(
8479 workspace_id: WorkspaceId,
8480 app_state: Arc<AppState>,
8481 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8482 cx: &mut App,
8483) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
8484 let project_handle = Project::local(
8485 app_state.client.clone(),
8486 app_state.node_runtime.clone(),
8487 app_state.user_store.clone(),
8488 app_state.languages.clone(),
8489 app_state.fs.clone(),
8490 None,
8491 project::LocalProjectFlags {
8492 init_worktree_trust: true,
8493 ..project::LocalProjectFlags::default()
8494 },
8495 cx,
8496 );
8497
8498 cx.spawn(async move |cx| {
8499 let serialized_workspace = persistence::DB
8500 .workspace_for_id(workspace_id)
8501 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
8502
8503 let centered_layout = serialized_workspace.centered_layout;
8504
8505 let (window, workspace) = if let Some(window) = requesting_window {
8506 let workspace = window.update(cx, |multi_workspace, window, cx| {
8507 let workspace = cx.new(|cx| {
8508 let mut workspace = Workspace::new(
8509 Some(workspace_id),
8510 project_handle.clone(),
8511 app_state.clone(),
8512 window,
8513 cx,
8514 );
8515 workspace.centered_layout = centered_layout;
8516 workspace
8517 });
8518 multi_workspace.add_workspace(workspace.clone(), cx);
8519 workspace
8520 })?;
8521 (window, workspace)
8522 } else {
8523 let window_bounds_override = window_bounds_env_override();
8524
8525 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
8526 (Some(WindowBounds::Windowed(bounds)), None)
8527 } else if let Some(display) = serialized_workspace.display
8528 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
8529 {
8530 (Some(bounds.0), Some(display))
8531 } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
8532 (Some(bounds), Some(display))
8533 } else {
8534 (None, None)
8535 };
8536
8537 let options = cx.update(|cx| {
8538 let mut options = (app_state.build_window_options)(display, cx);
8539 options.window_bounds = window_bounds;
8540 options
8541 });
8542
8543 let window = cx.open_window(options, {
8544 let app_state = app_state.clone();
8545 let project_handle = project_handle.clone();
8546 move |window, cx| {
8547 let workspace = cx.new(|cx| {
8548 let mut workspace = Workspace::new(
8549 Some(workspace_id),
8550 project_handle,
8551 app_state,
8552 window,
8553 cx,
8554 );
8555 workspace.centered_layout = centered_layout;
8556 workspace
8557 });
8558 cx.new(|cx| MultiWorkspace::new(workspace, cx))
8559 }
8560 })?;
8561
8562 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
8563 multi_workspace.workspace().clone()
8564 })?;
8565
8566 (window, workspace)
8567 };
8568
8569 notify_if_database_failed(window, cx);
8570
8571 // Restore items from the serialized workspace
8572 window
8573 .update(cx, |_, window, cx| {
8574 workspace.update(cx, |_workspace, cx| {
8575 open_items(Some(serialized_workspace), vec![], window, cx)
8576 })
8577 })?
8578 .await?;
8579
8580 window.update(cx, |_, window, cx| {
8581 workspace.update(cx, |workspace, cx| {
8582 workspace.serialize_workspace(window, cx);
8583 });
8584 })?;
8585
8586 Ok(window)
8587 })
8588}
8589
8590#[allow(clippy::type_complexity)]
8591pub fn open_paths(
8592 abs_paths: &[PathBuf],
8593 app_state: Arc<AppState>,
8594 open_options: OpenOptions,
8595 cx: &mut App,
8596) -> Task<
8597 anyhow::Result<(
8598 WindowHandle<MultiWorkspace>,
8599 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
8600 )>,
8601> {
8602 let abs_paths = abs_paths.to_vec();
8603 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
8604 let mut best_match = None;
8605 let mut open_visible = OpenVisible::All;
8606 #[cfg(target_os = "windows")]
8607 let wsl_path = abs_paths
8608 .iter()
8609 .find_map(|p| util::paths::WslPath::from_path(p));
8610
8611 cx.spawn(async move |cx| {
8612 if open_options.open_new_workspace != Some(true) {
8613 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
8614 let all_metadatas = futures::future::join_all(all_paths)
8615 .await
8616 .into_iter()
8617 .filter_map(|result| result.ok().flatten())
8618 .collect::<Vec<_>>();
8619
8620 cx.update(|cx| {
8621 for window in local_workspace_windows(cx) {
8622 if let Ok(multi_workspace) = window.read(cx) {
8623 for workspace in multi_workspace.workspaces() {
8624 let m = workspace.read(cx).project.read(cx).visibility_for_paths(
8625 &abs_paths,
8626 &all_metadatas,
8627 open_options.open_new_workspace == None,
8628 cx,
8629 );
8630 if m > best_match {
8631 existing = Some((window, workspace.clone()));
8632 best_match = m;
8633 } else if best_match.is_none()
8634 && open_options.open_new_workspace == Some(false)
8635 {
8636 existing = Some((window, workspace.clone()))
8637 }
8638 }
8639 }
8640 }
8641 });
8642
8643 if (open_options.open_new_workspace.is_none()
8644 || (open_options.open_new_workspace == Some(false)
8645 && open_options.prefer_focused_window))
8646 && (existing.is_none() || open_options.prefer_focused_window)
8647 && all_metadatas.iter().all(|file| !file.is_dir)
8648 {
8649 cx.update(|cx| {
8650 if let Some(window) = cx
8651 .active_window()
8652 .and_then(|window| window.downcast::<MultiWorkspace>())
8653 && let Ok(multi_workspace) = window.read(cx)
8654 {
8655 let active_workspace = multi_workspace.workspace().clone();
8656 let project = active_workspace.read(cx).project().read(cx);
8657 if project.is_local() && !project.is_via_collab() {
8658 existing = Some((window, active_workspace));
8659 open_visible = OpenVisible::None;
8660 return;
8661 }
8662 }
8663 'outer: for window in local_workspace_windows(cx) {
8664 if let Ok(multi_workspace) = window.read(cx) {
8665 for workspace in multi_workspace.workspaces() {
8666 let project = workspace.read(cx).project().read(cx);
8667 if project.is_via_collab() {
8668 continue;
8669 }
8670 existing = Some((window, workspace.clone()));
8671 open_visible = OpenVisible::None;
8672 break 'outer;
8673 }
8674 }
8675 }
8676 });
8677 }
8678 }
8679
8680 let result = if let Some((existing, target_workspace)) = existing {
8681 let open_task = existing
8682 .update(cx, |multi_workspace, window, cx| {
8683 window.activate_window();
8684 multi_workspace.activate(target_workspace.clone(), cx);
8685 target_workspace.update(cx, |workspace, cx| {
8686 workspace.open_paths(
8687 abs_paths,
8688 OpenOptions {
8689 visible: Some(open_visible),
8690 ..Default::default()
8691 },
8692 None,
8693 window,
8694 cx,
8695 )
8696 })
8697 })?
8698 .await;
8699
8700 _ = existing.update(cx, |multi_workspace, _, cx| {
8701 let workspace = multi_workspace.workspace().clone();
8702 workspace.update(cx, |workspace, cx| {
8703 for item in open_task.iter().flatten() {
8704 if let Err(e) = item {
8705 workspace.show_error(&e, cx);
8706 }
8707 }
8708 });
8709 });
8710
8711 Ok((existing, open_task))
8712 } else {
8713 let result = cx
8714 .update(move |cx| {
8715 Workspace::new_local(
8716 abs_paths,
8717 app_state.clone(),
8718 open_options.replace_window,
8719 open_options.env,
8720 None,
8721 cx,
8722 )
8723 })
8724 .await;
8725
8726 if let Ok((ref window_handle, _)) = result {
8727 window_handle
8728 .update(cx, |_, window, _cx| {
8729 window.activate_window();
8730 })
8731 .log_err();
8732 }
8733
8734 result
8735 };
8736
8737 #[cfg(target_os = "windows")]
8738 if let Some(util::paths::WslPath{distro, path}) = wsl_path
8739 && let Ok((multi_workspace_window, _)) = &result
8740 {
8741 multi_workspace_window
8742 .update(cx, move |multi_workspace, _window, cx| {
8743 struct OpenInWsl;
8744 let workspace = multi_workspace.workspace().clone();
8745 workspace.update(cx, |workspace, cx| {
8746 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
8747 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
8748 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
8749 cx.new(move |cx| {
8750 MessageNotification::new(msg, cx)
8751 .primary_message("Open in WSL")
8752 .primary_icon(IconName::FolderOpen)
8753 .primary_on_click(move |window, cx| {
8754 window.dispatch_action(Box::new(remote::OpenWslPath {
8755 distro: remote::WslConnectionOptions {
8756 distro_name: distro.clone(),
8757 user: None,
8758 },
8759 paths: vec![path.clone().into()],
8760 }), cx)
8761 })
8762 })
8763 });
8764 });
8765 })
8766 .unwrap();
8767 };
8768 result
8769 })
8770}
8771
8772pub fn open_new(
8773 open_options: OpenOptions,
8774 app_state: Arc<AppState>,
8775 cx: &mut App,
8776 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
8777) -> Task<anyhow::Result<()>> {
8778 let task = Workspace::new_local(
8779 Vec::new(),
8780 app_state,
8781 open_options.replace_window,
8782 open_options.env,
8783 Some(Box::new(init)),
8784 cx,
8785 );
8786 cx.spawn(async move |cx| {
8787 let (window, _opened_paths) = task.await?;
8788 window
8789 .update(cx, |_, window, _cx| {
8790 window.activate_window();
8791 })
8792 .ok();
8793 Ok(())
8794 })
8795}
8796
8797pub fn create_and_open_local_file(
8798 path: &'static Path,
8799 window: &mut Window,
8800 cx: &mut Context<Workspace>,
8801 default_content: impl 'static + Send + FnOnce() -> Rope,
8802) -> Task<Result<Box<dyn ItemHandle>>> {
8803 cx.spawn_in(window, async move |workspace, cx| {
8804 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
8805 if !fs.is_file(path).await {
8806 fs.create_file(path, Default::default()).await?;
8807 fs.save(path, &default_content(), Default::default())
8808 .await?;
8809 }
8810
8811 workspace
8812 .update_in(cx, |workspace, window, cx| {
8813 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
8814 let path = workspace
8815 .project
8816 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
8817 cx.spawn_in(window, async move |workspace, cx| {
8818 let path = path.await?;
8819 let mut items = workspace
8820 .update_in(cx, |workspace, window, cx| {
8821 workspace.open_paths(
8822 vec![path.to_path_buf()],
8823 OpenOptions {
8824 visible: Some(OpenVisible::None),
8825 ..Default::default()
8826 },
8827 None,
8828 window,
8829 cx,
8830 )
8831 })?
8832 .await;
8833 let item = items.pop().flatten();
8834 item.with_context(|| format!("path {path:?} is not a file"))?
8835 })
8836 })
8837 })?
8838 .await?
8839 .await
8840 })
8841}
8842
8843pub fn open_remote_project_with_new_connection(
8844 window: WindowHandle<MultiWorkspace>,
8845 remote_connection: Arc<dyn RemoteConnection>,
8846 cancel_rx: oneshot::Receiver<()>,
8847 delegate: Arc<dyn RemoteClientDelegate>,
8848 app_state: Arc<AppState>,
8849 paths: Vec<PathBuf>,
8850 cx: &mut App,
8851) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
8852 cx.spawn(async move |cx| {
8853 let (workspace_id, serialized_workspace) =
8854 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
8855 .await?;
8856
8857 let session = match cx
8858 .update(|cx| {
8859 remote::RemoteClient::new(
8860 ConnectionIdentifier::Workspace(workspace_id.0),
8861 remote_connection,
8862 cancel_rx,
8863 delegate,
8864 cx,
8865 )
8866 })
8867 .await?
8868 {
8869 Some(result) => result,
8870 None => return Ok(Vec::new()),
8871 };
8872
8873 let project = cx.update(|cx| {
8874 project::Project::remote(
8875 session,
8876 app_state.client.clone(),
8877 app_state.node_runtime.clone(),
8878 app_state.user_store.clone(),
8879 app_state.languages.clone(),
8880 app_state.fs.clone(),
8881 true,
8882 cx,
8883 )
8884 });
8885
8886 open_remote_project_inner(
8887 project,
8888 paths,
8889 workspace_id,
8890 serialized_workspace,
8891 app_state,
8892 window,
8893 cx,
8894 )
8895 .await
8896 })
8897}
8898
8899pub fn open_remote_project_with_existing_connection(
8900 connection_options: RemoteConnectionOptions,
8901 project: Entity<Project>,
8902 paths: Vec<PathBuf>,
8903 app_state: Arc<AppState>,
8904 window: WindowHandle<MultiWorkspace>,
8905 cx: &mut AsyncApp,
8906) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
8907 cx.spawn(async move |cx| {
8908 let (workspace_id, serialized_workspace) =
8909 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
8910
8911 open_remote_project_inner(
8912 project,
8913 paths,
8914 workspace_id,
8915 serialized_workspace,
8916 app_state,
8917 window,
8918 cx,
8919 )
8920 .await
8921 })
8922}
8923
8924async fn open_remote_project_inner(
8925 project: Entity<Project>,
8926 paths: Vec<PathBuf>,
8927 workspace_id: WorkspaceId,
8928 serialized_workspace: Option<SerializedWorkspace>,
8929 app_state: Arc<AppState>,
8930 window: WindowHandle<MultiWorkspace>,
8931 cx: &mut AsyncApp,
8932) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
8933 let toolchains = DB.toolchains(workspace_id).await?;
8934 for (toolchain, worktree_path, path) in toolchains {
8935 project
8936 .update(cx, |this, cx| {
8937 let Some(worktree_id) =
8938 this.find_worktree(&worktree_path, cx)
8939 .and_then(|(worktree, rel_path)| {
8940 if rel_path.is_empty() {
8941 Some(worktree.read(cx).id())
8942 } else {
8943 None
8944 }
8945 })
8946 else {
8947 return Task::ready(None);
8948 };
8949
8950 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
8951 })
8952 .await;
8953 }
8954 let mut project_paths_to_open = vec![];
8955 let mut project_path_errors = vec![];
8956
8957 for path in paths {
8958 let result = cx
8959 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
8960 .await;
8961 match result {
8962 Ok((_, project_path)) => {
8963 project_paths_to_open.push((path.clone(), Some(project_path)));
8964 }
8965 Err(error) => {
8966 project_path_errors.push(error);
8967 }
8968 };
8969 }
8970
8971 if project_paths_to_open.is_empty() {
8972 return Err(project_path_errors.pop().context("no paths given")?);
8973 }
8974
8975 let workspace = window.update(cx, |multi_workspace, window, cx| {
8976 telemetry::event!("SSH Project Opened");
8977
8978 let new_workspace = cx.new(|cx| {
8979 let mut workspace =
8980 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
8981 workspace.update_history(cx);
8982
8983 if let Some(ref serialized) = serialized_workspace {
8984 workspace.centered_layout = serialized.centered_layout;
8985 }
8986
8987 workspace
8988 });
8989
8990 multi_workspace.activate(new_workspace.clone(), cx);
8991 new_workspace
8992 })?;
8993
8994 let items = window
8995 .update(cx, |_, window, cx| {
8996 window.activate_window();
8997 workspace.update(cx, |_workspace, cx| {
8998 open_items(serialized_workspace, project_paths_to_open, window, cx)
8999 })
9000 })?
9001 .await?;
9002
9003 workspace.update(cx, |workspace, cx| {
9004 for error in project_path_errors {
9005 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9006 if let Some(path) = error.error_tag("path") {
9007 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9008 }
9009 } else {
9010 workspace.show_error(&error, cx)
9011 }
9012 }
9013 });
9014
9015 Ok(items.into_iter().map(|item| item?.ok()).collect())
9016}
9017
9018fn deserialize_remote_project(
9019 connection_options: RemoteConnectionOptions,
9020 paths: Vec<PathBuf>,
9021 cx: &AsyncApp,
9022) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9023 cx.background_spawn(async move {
9024 let remote_connection_id = persistence::DB
9025 .get_or_create_remote_connection(connection_options)
9026 .await?;
9027
9028 let serialized_workspace =
9029 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
9030
9031 let workspace_id = if let Some(workspace_id) =
9032 serialized_workspace.as_ref().map(|workspace| workspace.id)
9033 {
9034 workspace_id
9035 } else {
9036 persistence::DB.next_id().await?
9037 };
9038
9039 Ok((workspace_id, serialized_workspace))
9040 })
9041}
9042
9043pub fn join_in_room_project(
9044 project_id: u64,
9045 follow_user_id: u64,
9046 app_state: Arc<AppState>,
9047 cx: &mut App,
9048) -> Task<Result<()>> {
9049 let windows = cx.windows();
9050 cx.spawn(async move |cx| {
9051 let existing_window_and_workspace: Option<(
9052 WindowHandle<MultiWorkspace>,
9053 Entity<Workspace>,
9054 )> = windows.into_iter().find_map(|window_handle| {
9055 window_handle
9056 .downcast::<MultiWorkspace>()
9057 .and_then(|window_handle| {
9058 window_handle
9059 .update(cx, |multi_workspace, _window, cx| {
9060 for workspace in multi_workspace.workspaces() {
9061 if workspace.read(cx).project().read(cx).remote_id()
9062 == Some(project_id)
9063 {
9064 return Some((window_handle, workspace.clone()));
9065 }
9066 }
9067 None
9068 })
9069 .unwrap_or(None)
9070 })
9071 });
9072
9073 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9074 existing_window_and_workspace
9075 {
9076 existing_window
9077 .update(cx, |multi_workspace, _, cx| {
9078 multi_workspace.activate(target_workspace, cx);
9079 })
9080 .ok();
9081 existing_window
9082 } else {
9083 let active_call = cx.update(|cx| ActiveCall::global(cx));
9084 let room = active_call
9085 .read_with(cx, |call, _| call.room().cloned())
9086 .context("not in a call")?;
9087 let project = room
9088 .update(cx, |room, cx| {
9089 room.join_project(
9090 project_id,
9091 app_state.languages.clone(),
9092 app_state.fs.clone(),
9093 cx,
9094 )
9095 })
9096 .await?;
9097
9098 let window_bounds_override = window_bounds_env_override();
9099 cx.update(|cx| {
9100 let mut options = (app_state.build_window_options)(None, cx);
9101 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9102 cx.open_window(options, |window, cx| {
9103 let workspace = cx.new(|cx| {
9104 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9105 });
9106 cx.new(|cx| MultiWorkspace::new(workspace, cx))
9107 })
9108 })?
9109 };
9110
9111 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9112 cx.activate(true);
9113 window.activate_window();
9114
9115 // We set the active workspace above, so this is the correct workspace.
9116 let workspace = multi_workspace.workspace().clone();
9117 workspace.update(cx, |workspace, cx| {
9118 if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
9119 let follow_peer_id = room
9120 .read(cx)
9121 .remote_participants()
9122 .iter()
9123 .find(|(_, participant)| participant.user.id == follow_user_id)
9124 .map(|(_, p)| p.peer_id)
9125 .or_else(|| {
9126 // If we couldn't follow the given user, follow the host instead.
9127 let collaborator = workspace
9128 .project()
9129 .read(cx)
9130 .collaborators()
9131 .values()
9132 .find(|collaborator| collaborator.is_host)?;
9133 Some(collaborator.peer_id)
9134 });
9135
9136 if let Some(follow_peer_id) = follow_peer_id {
9137 workspace.follow(follow_peer_id, window, cx);
9138 }
9139 }
9140 });
9141 })?;
9142
9143 anyhow::Ok(())
9144 })
9145}
9146
9147pub fn reload(cx: &mut App) {
9148 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9149 let mut workspace_windows = cx
9150 .windows()
9151 .into_iter()
9152 .filter_map(|window| window.downcast::<MultiWorkspace>())
9153 .collect::<Vec<_>>();
9154
9155 // If multiple windows have unsaved changes, and need a save prompt,
9156 // prompt in the active window before switching to a different window.
9157 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9158
9159 let mut prompt = None;
9160 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9161 prompt = window
9162 .update(cx, |_, window, cx| {
9163 window.prompt(
9164 PromptLevel::Info,
9165 "Are you sure you want to restart?",
9166 None,
9167 &["Restart", "Cancel"],
9168 cx,
9169 )
9170 })
9171 .ok();
9172 }
9173
9174 cx.spawn(async move |cx| {
9175 if let Some(prompt) = prompt {
9176 let answer = prompt.await?;
9177 if answer != 0 {
9178 return anyhow::Ok(());
9179 }
9180 }
9181
9182 // If the user cancels any save prompt, then keep the app open.
9183 for window in workspace_windows {
9184 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9185 let workspace = multi_workspace.workspace().clone();
9186 workspace.update(cx, |workspace, cx| {
9187 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9188 })
9189 }) && !should_close.await?
9190 {
9191 return anyhow::Ok(());
9192 }
9193 }
9194 cx.update(|cx| cx.restart());
9195 anyhow::Ok(())
9196 })
9197 .detach_and_log_err(cx);
9198}
9199
9200fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9201 let mut parts = value.split(',');
9202 let x: usize = parts.next()?.parse().ok()?;
9203 let y: usize = parts.next()?.parse().ok()?;
9204 Some(point(px(x as f32), px(y as f32)))
9205}
9206
9207fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9208 let mut parts = value.split(',');
9209 let width: usize = parts.next()?.parse().ok()?;
9210 let height: usize = parts.next()?.parse().ok()?;
9211 Some(size(px(width as f32), px(height as f32)))
9212}
9213
9214/// Add client-side decorations (rounded corners, shadows, resize handling) when
9215/// appropriate.
9216///
9217/// The `border_radius_tiling` parameter allows overriding which corners get
9218/// rounded, independently of the actual window tiling state. This is used
9219/// specifically for the workspace switcher sidebar: when the sidebar is open,
9220/// we want square corners on the left (so the sidebar appears flush with the
9221/// window edge) but we still need the shadow padding for proper visual
9222/// appearance. Unlike actual window tiling, this only affects border radius -
9223/// not padding or shadows.
9224pub fn client_side_decorations(
9225 element: impl IntoElement,
9226 window: &mut Window,
9227 cx: &mut App,
9228 border_radius_tiling: Tiling,
9229) -> Stateful<Div> {
9230 const BORDER_SIZE: Pixels = px(1.0);
9231 let decorations = window.window_decorations();
9232 let tiling = match decorations {
9233 Decorations::Server => Tiling::default(),
9234 Decorations::Client { tiling } => tiling,
9235 };
9236
9237 match decorations {
9238 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9239 Decorations::Server => window.set_client_inset(px(0.0)),
9240 }
9241
9242 struct GlobalResizeEdge(ResizeEdge);
9243 impl Global for GlobalResizeEdge {}
9244
9245 div()
9246 .id("window-backdrop")
9247 .bg(transparent_black())
9248 .map(|div| match decorations {
9249 Decorations::Server => div,
9250 Decorations::Client { .. } => div
9251 .when(
9252 !(tiling.top
9253 || tiling.right
9254 || border_radius_tiling.top
9255 || border_radius_tiling.right),
9256 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9257 )
9258 .when(
9259 !(tiling.top
9260 || tiling.left
9261 || border_radius_tiling.top
9262 || border_radius_tiling.left),
9263 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9264 )
9265 .when(
9266 !(tiling.bottom
9267 || tiling.right
9268 || border_radius_tiling.bottom
9269 || border_radius_tiling.right),
9270 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9271 )
9272 .when(
9273 !(tiling.bottom
9274 || tiling.left
9275 || border_radius_tiling.bottom
9276 || border_radius_tiling.left),
9277 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9278 )
9279 .when(!tiling.top, |div| {
9280 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9281 })
9282 .when(!tiling.bottom, |div| {
9283 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9284 })
9285 .when(!tiling.left, |div| {
9286 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9287 })
9288 .when(!tiling.right, |div| {
9289 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9290 })
9291 .on_mouse_move(move |e, window, cx| {
9292 let size = window.window_bounds().get_bounds().size;
9293 let pos = e.position;
9294
9295 let new_edge =
9296 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
9297
9298 let edge = cx.try_global::<GlobalResizeEdge>();
9299 if new_edge != edge.map(|edge| edge.0) {
9300 window
9301 .window_handle()
9302 .update(cx, |workspace, _, cx| {
9303 cx.notify(workspace.entity_id());
9304 })
9305 .ok();
9306 }
9307 })
9308 .on_mouse_down(MouseButton::Left, move |e, window, _| {
9309 let size = window.window_bounds().get_bounds().size;
9310 let pos = e.position;
9311
9312 let edge = match resize_edge(
9313 pos,
9314 theme::CLIENT_SIDE_DECORATION_SHADOW,
9315 size,
9316 tiling,
9317 ) {
9318 Some(value) => value,
9319 None => return,
9320 };
9321
9322 window.start_window_resize(edge);
9323 }),
9324 })
9325 .size_full()
9326 .child(
9327 div()
9328 .cursor(CursorStyle::Arrow)
9329 .map(|div| match decorations {
9330 Decorations::Server => div,
9331 Decorations::Client { .. } => div
9332 .border_color(cx.theme().colors().border)
9333 .when(
9334 !(tiling.top
9335 || tiling.right
9336 || border_radius_tiling.top
9337 || border_radius_tiling.right),
9338 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9339 )
9340 .when(
9341 !(tiling.top
9342 || tiling.left
9343 || border_radius_tiling.top
9344 || border_radius_tiling.left),
9345 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9346 )
9347 .when(
9348 !(tiling.bottom
9349 || tiling.right
9350 || border_radius_tiling.bottom
9351 || border_radius_tiling.right),
9352 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9353 )
9354 .when(
9355 !(tiling.bottom
9356 || tiling.left
9357 || border_radius_tiling.bottom
9358 || border_radius_tiling.left),
9359 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9360 )
9361 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
9362 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
9363 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
9364 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
9365 .when(!tiling.is_tiled(), |div| {
9366 div.shadow(vec![gpui::BoxShadow {
9367 color: Hsla {
9368 h: 0.,
9369 s: 0.,
9370 l: 0.,
9371 a: 0.4,
9372 },
9373 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
9374 spread_radius: px(0.),
9375 offset: point(px(0.0), px(0.0)),
9376 }])
9377 }),
9378 })
9379 .on_mouse_move(|_e, _, cx| {
9380 cx.stop_propagation();
9381 })
9382 .size_full()
9383 .child(element),
9384 )
9385 .map(|div| match decorations {
9386 Decorations::Server => div,
9387 Decorations::Client { tiling, .. } => div.child(
9388 canvas(
9389 |_bounds, window, _| {
9390 window.insert_hitbox(
9391 Bounds::new(
9392 point(px(0.0), px(0.0)),
9393 window.window_bounds().get_bounds().size,
9394 ),
9395 HitboxBehavior::Normal,
9396 )
9397 },
9398 move |_bounds, hitbox, window, cx| {
9399 let mouse = window.mouse_position();
9400 let size = window.window_bounds().get_bounds().size;
9401 let Some(edge) =
9402 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
9403 else {
9404 return;
9405 };
9406 cx.set_global(GlobalResizeEdge(edge));
9407 window.set_cursor_style(
9408 match edge {
9409 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
9410 ResizeEdge::Left | ResizeEdge::Right => {
9411 CursorStyle::ResizeLeftRight
9412 }
9413 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
9414 CursorStyle::ResizeUpLeftDownRight
9415 }
9416 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
9417 CursorStyle::ResizeUpRightDownLeft
9418 }
9419 },
9420 &hitbox,
9421 );
9422 },
9423 )
9424 .size_full()
9425 .absolute(),
9426 ),
9427 })
9428}
9429
9430fn resize_edge(
9431 pos: Point<Pixels>,
9432 shadow_size: Pixels,
9433 window_size: Size<Pixels>,
9434 tiling: Tiling,
9435) -> Option<ResizeEdge> {
9436 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
9437 if bounds.contains(&pos) {
9438 return None;
9439 }
9440
9441 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
9442 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
9443 if !tiling.top && top_left_bounds.contains(&pos) {
9444 return Some(ResizeEdge::TopLeft);
9445 }
9446
9447 let top_right_bounds = Bounds::new(
9448 Point::new(window_size.width - corner_size.width, px(0.)),
9449 corner_size,
9450 );
9451 if !tiling.top && top_right_bounds.contains(&pos) {
9452 return Some(ResizeEdge::TopRight);
9453 }
9454
9455 let bottom_left_bounds = Bounds::new(
9456 Point::new(px(0.), window_size.height - corner_size.height),
9457 corner_size,
9458 );
9459 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
9460 return Some(ResizeEdge::BottomLeft);
9461 }
9462
9463 let bottom_right_bounds = Bounds::new(
9464 Point::new(
9465 window_size.width - corner_size.width,
9466 window_size.height - corner_size.height,
9467 ),
9468 corner_size,
9469 );
9470 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
9471 return Some(ResizeEdge::BottomRight);
9472 }
9473
9474 if !tiling.top && pos.y < shadow_size {
9475 Some(ResizeEdge::Top)
9476 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
9477 Some(ResizeEdge::Bottom)
9478 } else if !tiling.left && pos.x < shadow_size {
9479 Some(ResizeEdge::Left)
9480 } else if !tiling.right && pos.x > window_size.width - shadow_size {
9481 Some(ResizeEdge::Right)
9482 } else {
9483 None
9484 }
9485}
9486
9487fn join_pane_into_active(
9488 active_pane: &Entity<Pane>,
9489 pane: &Entity<Pane>,
9490 window: &mut Window,
9491 cx: &mut App,
9492) {
9493 if pane == active_pane {
9494 } else if pane.read(cx).items_len() == 0 {
9495 pane.update(cx, |_, cx| {
9496 cx.emit(pane::Event::Remove {
9497 focus_on_pane: None,
9498 });
9499 })
9500 } else {
9501 move_all_items(pane, active_pane, window, cx);
9502 }
9503}
9504
9505fn move_all_items(
9506 from_pane: &Entity<Pane>,
9507 to_pane: &Entity<Pane>,
9508 window: &mut Window,
9509 cx: &mut App,
9510) {
9511 let destination_is_different = from_pane != to_pane;
9512 let mut moved_items = 0;
9513 for (item_ix, item_handle) in from_pane
9514 .read(cx)
9515 .items()
9516 .enumerate()
9517 .map(|(ix, item)| (ix, item.clone()))
9518 .collect::<Vec<_>>()
9519 {
9520 let ix = item_ix - moved_items;
9521 if destination_is_different {
9522 // Close item from previous pane
9523 from_pane.update(cx, |source, cx| {
9524 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
9525 });
9526 moved_items += 1;
9527 }
9528
9529 // This automatically removes duplicate items in the pane
9530 to_pane.update(cx, |destination, cx| {
9531 destination.add_item(item_handle, true, true, None, window, cx);
9532 window.focus(&destination.focus_handle(cx), cx)
9533 });
9534 }
9535}
9536
9537pub fn move_item(
9538 source: &Entity<Pane>,
9539 destination: &Entity<Pane>,
9540 item_id_to_move: EntityId,
9541 destination_index: usize,
9542 activate: bool,
9543 window: &mut Window,
9544 cx: &mut App,
9545) {
9546 let Some((item_ix, item_handle)) = source
9547 .read(cx)
9548 .items()
9549 .enumerate()
9550 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
9551 .map(|(ix, item)| (ix, item.clone()))
9552 else {
9553 // Tab was closed during drag
9554 return;
9555 };
9556
9557 if source != destination {
9558 // Close item from previous pane
9559 source.update(cx, |source, cx| {
9560 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
9561 });
9562 }
9563
9564 // This automatically removes duplicate items in the pane
9565 destination.update(cx, |destination, cx| {
9566 destination.add_item_inner(
9567 item_handle,
9568 activate,
9569 activate,
9570 activate,
9571 Some(destination_index),
9572 window,
9573 cx,
9574 );
9575 if activate {
9576 window.focus(&destination.focus_handle(cx), cx)
9577 }
9578 });
9579}
9580
9581pub fn move_active_item(
9582 source: &Entity<Pane>,
9583 destination: &Entity<Pane>,
9584 focus_destination: bool,
9585 close_if_empty: bool,
9586 window: &mut Window,
9587 cx: &mut App,
9588) {
9589 if source == destination {
9590 return;
9591 }
9592 let Some(active_item) = source.read(cx).active_item() else {
9593 return;
9594 };
9595 source.update(cx, |source_pane, cx| {
9596 let item_id = active_item.item_id();
9597 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
9598 destination.update(cx, |target_pane, cx| {
9599 target_pane.add_item(
9600 active_item,
9601 focus_destination,
9602 focus_destination,
9603 Some(target_pane.items_len()),
9604 window,
9605 cx,
9606 );
9607 });
9608 });
9609}
9610
9611pub fn clone_active_item(
9612 workspace_id: Option<WorkspaceId>,
9613 source: &Entity<Pane>,
9614 destination: &Entity<Pane>,
9615 focus_destination: bool,
9616 window: &mut Window,
9617 cx: &mut App,
9618) {
9619 if source == destination {
9620 return;
9621 }
9622 let Some(active_item) = source.read(cx).active_item() else {
9623 return;
9624 };
9625 if !active_item.can_split(cx) {
9626 return;
9627 }
9628 let destination = destination.downgrade();
9629 let task = active_item.clone_on_split(workspace_id, window, cx);
9630 window
9631 .spawn(cx, async move |cx| {
9632 let Some(clone) = task.await else {
9633 return;
9634 };
9635 destination
9636 .update_in(cx, |target_pane, window, cx| {
9637 target_pane.add_item(
9638 clone,
9639 focus_destination,
9640 focus_destination,
9641 Some(target_pane.items_len()),
9642 window,
9643 cx,
9644 );
9645 })
9646 .log_err();
9647 })
9648 .detach();
9649}
9650
9651#[derive(Debug)]
9652pub struct WorkspacePosition {
9653 pub window_bounds: Option<WindowBounds>,
9654 pub display: Option<Uuid>,
9655 pub centered_layout: bool,
9656}
9657
9658pub fn remote_workspace_position_from_db(
9659 connection_options: RemoteConnectionOptions,
9660 paths_to_open: &[PathBuf],
9661 cx: &App,
9662) -> Task<Result<WorkspacePosition>> {
9663 let paths = paths_to_open.to_vec();
9664
9665 cx.background_spawn(async move {
9666 let remote_connection_id = persistence::DB
9667 .get_or_create_remote_connection(connection_options)
9668 .await
9669 .context("fetching serialized ssh project")?;
9670 let serialized_workspace =
9671 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
9672
9673 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
9674 (Some(WindowBounds::Windowed(bounds)), None)
9675 } else {
9676 let restorable_bounds = serialized_workspace
9677 .as_ref()
9678 .and_then(|workspace| {
9679 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
9680 })
9681 .or_else(|| persistence::read_default_window_bounds());
9682
9683 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
9684 (Some(serialized_bounds), Some(serialized_display))
9685 } else {
9686 (None, None)
9687 }
9688 };
9689
9690 let centered_layout = serialized_workspace
9691 .as_ref()
9692 .map(|w| w.centered_layout)
9693 .unwrap_or(false);
9694
9695 Ok(WorkspacePosition {
9696 window_bounds,
9697 display,
9698 centered_layout,
9699 })
9700 })
9701}
9702
9703pub fn with_active_or_new_workspace(
9704 cx: &mut App,
9705 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
9706) {
9707 match cx
9708 .active_window()
9709 .and_then(|w| w.downcast::<MultiWorkspace>())
9710 {
9711 Some(multi_workspace) => {
9712 cx.defer(move |cx| {
9713 multi_workspace
9714 .update(cx, |multi_workspace, window, cx| {
9715 let workspace = multi_workspace.workspace().clone();
9716 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
9717 })
9718 .log_err();
9719 });
9720 }
9721 None => {
9722 let app_state = AppState::global(cx);
9723 if let Some(app_state) = app_state.upgrade() {
9724 open_new(
9725 OpenOptions::default(),
9726 app_state,
9727 cx,
9728 move |workspace, window, cx| f(workspace, window, cx),
9729 )
9730 .detach_and_log_err(cx);
9731 }
9732 }
9733 }
9734}
9735
9736#[cfg(test)]
9737mod tests {
9738 use std::{cell::RefCell, rc::Rc};
9739
9740 use super::*;
9741 use crate::{
9742 dock::{PanelEvent, test::TestPanel},
9743 item::{
9744 ItemBufferKind, ItemEvent,
9745 test::{TestItem, TestProjectItem},
9746 },
9747 };
9748 use fs::FakeFs;
9749 use gpui::{
9750 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
9751 UpdateGlobal, VisualTestContext, px,
9752 };
9753 use project::{Project, ProjectEntryId};
9754 use serde_json::json;
9755 use settings::SettingsStore;
9756 use util::rel_path::rel_path;
9757
9758 #[gpui::test]
9759 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
9760 init_test(cx);
9761
9762 let fs = FakeFs::new(cx.executor());
9763 let project = Project::test(fs, [], cx).await;
9764 let (workspace, cx) =
9765 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9766
9767 // Adding an item with no ambiguity renders the tab without detail.
9768 let item1 = cx.new(|cx| {
9769 let mut item = TestItem::new(cx);
9770 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
9771 item
9772 });
9773 workspace.update_in(cx, |workspace, window, cx| {
9774 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
9775 });
9776 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
9777
9778 // Adding an item that creates ambiguity increases the level of detail on
9779 // both tabs.
9780 let item2 = cx.new_window_entity(|_window, cx| {
9781 let mut item = TestItem::new(cx);
9782 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
9783 item
9784 });
9785 workspace.update_in(cx, |workspace, window, cx| {
9786 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
9787 });
9788 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
9789 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
9790
9791 // Adding an item that creates ambiguity increases the level of detail only
9792 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
9793 // we stop at the highest detail available.
9794 let item3 = cx.new(|cx| {
9795 let mut item = TestItem::new(cx);
9796 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
9797 item
9798 });
9799 workspace.update_in(cx, |workspace, window, cx| {
9800 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
9801 });
9802 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
9803 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
9804 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
9805 }
9806
9807 #[gpui::test]
9808 async fn test_tracking_active_path(cx: &mut TestAppContext) {
9809 init_test(cx);
9810
9811 let fs = FakeFs::new(cx.executor());
9812 fs.insert_tree(
9813 "/root1",
9814 json!({
9815 "one.txt": "",
9816 "two.txt": "",
9817 }),
9818 )
9819 .await;
9820 fs.insert_tree(
9821 "/root2",
9822 json!({
9823 "three.txt": "",
9824 }),
9825 )
9826 .await;
9827
9828 let project = Project::test(fs, ["root1".as_ref()], cx).await;
9829 let (workspace, cx) =
9830 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9831 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9832 let worktree_id = project.update(cx, |project, cx| {
9833 project.worktrees(cx).next().unwrap().read(cx).id()
9834 });
9835
9836 let item1 = cx.new(|cx| {
9837 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
9838 });
9839 let item2 = cx.new(|cx| {
9840 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
9841 });
9842
9843 // Add an item to an empty pane
9844 workspace.update_in(cx, |workspace, window, cx| {
9845 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
9846 });
9847 project.update(cx, |project, cx| {
9848 assert_eq!(
9849 project.active_entry(),
9850 project
9851 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
9852 .map(|e| e.id)
9853 );
9854 });
9855 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
9856
9857 // Add a second item to a non-empty pane
9858 workspace.update_in(cx, |workspace, window, cx| {
9859 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
9860 });
9861 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
9862 project.update(cx, |project, cx| {
9863 assert_eq!(
9864 project.active_entry(),
9865 project
9866 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
9867 .map(|e| e.id)
9868 );
9869 });
9870
9871 // Close the active item
9872 pane.update_in(cx, |pane, window, cx| {
9873 pane.close_active_item(&Default::default(), window, cx)
9874 })
9875 .await
9876 .unwrap();
9877 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
9878 project.update(cx, |project, cx| {
9879 assert_eq!(
9880 project.active_entry(),
9881 project
9882 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
9883 .map(|e| e.id)
9884 );
9885 });
9886
9887 // Add a project folder
9888 project
9889 .update(cx, |project, cx| {
9890 project.find_or_create_worktree("root2", true, cx)
9891 })
9892 .await
9893 .unwrap();
9894 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
9895
9896 // Remove a project folder
9897 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
9898 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
9899 }
9900
9901 #[gpui::test]
9902 async fn test_close_window(cx: &mut TestAppContext) {
9903 init_test(cx);
9904
9905 let fs = FakeFs::new(cx.executor());
9906 fs.insert_tree("/root", json!({ "one": "" })).await;
9907
9908 let project = Project::test(fs, ["root".as_ref()], cx).await;
9909 let (workspace, cx) =
9910 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9911
9912 // When there are no dirty items, there's nothing to do.
9913 let item1 = cx.new(TestItem::new);
9914 workspace.update_in(cx, |w, window, cx| {
9915 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
9916 });
9917 let task = workspace.update_in(cx, |w, window, cx| {
9918 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
9919 });
9920 assert!(task.await.unwrap());
9921
9922 // When there are dirty untitled items, prompt to save each one. If the user
9923 // cancels any prompt, then abort.
9924 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
9925 let item3 = cx.new(|cx| {
9926 TestItem::new(cx)
9927 .with_dirty(true)
9928 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
9929 });
9930 workspace.update_in(cx, |w, window, cx| {
9931 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
9932 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
9933 });
9934 let task = workspace.update_in(cx, |w, window, cx| {
9935 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
9936 });
9937 cx.executor().run_until_parked();
9938 cx.simulate_prompt_answer("Cancel"); // cancel save all
9939 cx.executor().run_until_parked();
9940 assert!(!cx.has_pending_prompt());
9941 assert!(!task.await.unwrap());
9942 }
9943
9944 #[gpui::test]
9945 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
9946 init_test(cx);
9947
9948 // Register TestItem as a serializable item
9949 cx.update(|cx| {
9950 register_serializable_item::<TestItem>(cx);
9951 });
9952
9953 let fs = FakeFs::new(cx.executor());
9954 fs.insert_tree("/root", json!({ "one": "" })).await;
9955
9956 let project = Project::test(fs, ["root".as_ref()], cx).await;
9957 let (workspace, cx) =
9958 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9959
9960 // When there are dirty untitled items, but they can serialize, then there is no prompt.
9961 let item1 = cx.new(|cx| {
9962 TestItem::new(cx)
9963 .with_dirty(true)
9964 .with_serialize(|| Some(Task::ready(Ok(()))))
9965 });
9966 let item2 = cx.new(|cx| {
9967 TestItem::new(cx)
9968 .with_dirty(true)
9969 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
9970 .with_serialize(|| Some(Task::ready(Ok(()))))
9971 });
9972 workspace.update_in(cx, |w, window, cx| {
9973 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
9974 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
9975 });
9976 let task = workspace.update_in(cx, |w, window, cx| {
9977 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
9978 });
9979 assert!(task.await.unwrap());
9980 }
9981
9982 #[gpui::test]
9983 async fn test_close_pane_items(cx: &mut TestAppContext) {
9984 init_test(cx);
9985
9986 let fs = FakeFs::new(cx.executor());
9987
9988 let project = Project::test(fs, None, cx).await;
9989 let (workspace, cx) =
9990 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9991
9992 let item1 = cx.new(|cx| {
9993 TestItem::new(cx)
9994 .with_dirty(true)
9995 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
9996 });
9997 let item2 = cx.new(|cx| {
9998 TestItem::new(cx)
9999 .with_dirty(true)
10000 .with_conflict(true)
10001 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10002 });
10003 let item3 = cx.new(|cx| {
10004 TestItem::new(cx)
10005 .with_dirty(true)
10006 .with_conflict(true)
10007 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10008 });
10009 let item4 = cx.new(|cx| {
10010 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10011 let project_item = TestProjectItem::new_untitled(cx);
10012 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10013 project_item
10014 }])
10015 });
10016 let pane = workspace.update_in(cx, |workspace, window, cx| {
10017 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10018 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10019 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10020 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10021 workspace.active_pane().clone()
10022 });
10023
10024 let close_items = pane.update_in(cx, |pane, window, cx| {
10025 pane.activate_item(1, true, true, window, cx);
10026 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10027 let item1_id = item1.item_id();
10028 let item3_id = item3.item_id();
10029 let item4_id = item4.item_id();
10030 pane.close_items(window, cx, SaveIntent::Close, move |id| {
10031 [item1_id, item3_id, item4_id].contains(&id)
10032 })
10033 });
10034 cx.executor().run_until_parked();
10035
10036 assert!(cx.has_pending_prompt());
10037 cx.simulate_prompt_answer("Save all");
10038
10039 cx.executor().run_until_parked();
10040
10041 // Item 1 is saved. There's a prompt to save item 3.
10042 pane.update(cx, |pane, cx| {
10043 assert_eq!(item1.read(cx).save_count, 1);
10044 assert_eq!(item1.read(cx).save_as_count, 0);
10045 assert_eq!(item1.read(cx).reload_count, 0);
10046 assert_eq!(pane.items_len(), 3);
10047 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10048 });
10049 assert!(cx.has_pending_prompt());
10050
10051 // Cancel saving item 3.
10052 cx.simulate_prompt_answer("Discard");
10053 cx.executor().run_until_parked();
10054
10055 // Item 3 is reloaded. There's a prompt to save item 4.
10056 pane.update(cx, |pane, cx| {
10057 assert_eq!(item3.read(cx).save_count, 0);
10058 assert_eq!(item3.read(cx).save_as_count, 0);
10059 assert_eq!(item3.read(cx).reload_count, 1);
10060 assert_eq!(pane.items_len(), 2);
10061 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10062 });
10063
10064 // There's a prompt for a path for item 4.
10065 cx.simulate_new_path_selection(|_| Some(Default::default()));
10066 close_items.await.unwrap();
10067
10068 // The requested items are closed.
10069 pane.update(cx, |pane, cx| {
10070 assert_eq!(item4.read(cx).save_count, 0);
10071 assert_eq!(item4.read(cx).save_as_count, 1);
10072 assert_eq!(item4.read(cx).reload_count, 0);
10073 assert_eq!(pane.items_len(), 1);
10074 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10075 });
10076 }
10077
10078 #[gpui::test]
10079 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10080 init_test(cx);
10081
10082 let fs = FakeFs::new(cx.executor());
10083 let project = Project::test(fs, [], cx).await;
10084 let (workspace, cx) =
10085 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10086
10087 // Create several workspace items with single project entries, and two
10088 // workspace items with multiple project entries.
10089 let single_entry_items = (0..=4)
10090 .map(|project_entry_id| {
10091 cx.new(|cx| {
10092 TestItem::new(cx)
10093 .with_dirty(true)
10094 .with_project_items(&[dirty_project_item(
10095 project_entry_id,
10096 &format!("{project_entry_id}.txt"),
10097 cx,
10098 )])
10099 })
10100 })
10101 .collect::<Vec<_>>();
10102 let item_2_3 = cx.new(|cx| {
10103 TestItem::new(cx)
10104 .with_dirty(true)
10105 .with_buffer_kind(ItemBufferKind::Multibuffer)
10106 .with_project_items(&[
10107 single_entry_items[2].read(cx).project_items[0].clone(),
10108 single_entry_items[3].read(cx).project_items[0].clone(),
10109 ])
10110 });
10111 let item_3_4 = cx.new(|cx| {
10112 TestItem::new(cx)
10113 .with_dirty(true)
10114 .with_buffer_kind(ItemBufferKind::Multibuffer)
10115 .with_project_items(&[
10116 single_entry_items[3].read(cx).project_items[0].clone(),
10117 single_entry_items[4].read(cx).project_items[0].clone(),
10118 ])
10119 });
10120
10121 // Create two panes that contain the following project entries:
10122 // left pane:
10123 // multi-entry items: (2, 3)
10124 // single-entry items: 0, 2, 3, 4
10125 // right pane:
10126 // single-entry items: 4, 1
10127 // multi-entry items: (3, 4)
10128 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10129 let left_pane = workspace.active_pane().clone();
10130 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10131 workspace.add_item_to_active_pane(
10132 single_entry_items[0].boxed_clone(),
10133 None,
10134 true,
10135 window,
10136 cx,
10137 );
10138 workspace.add_item_to_active_pane(
10139 single_entry_items[2].boxed_clone(),
10140 None,
10141 true,
10142 window,
10143 cx,
10144 );
10145 workspace.add_item_to_active_pane(
10146 single_entry_items[3].boxed_clone(),
10147 None,
10148 true,
10149 window,
10150 cx,
10151 );
10152 workspace.add_item_to_active_pane(
10153 single_entry_items[4].boxed_clone(),
10154 None,
10155 true,
10156 window,
10157 cx,
10158 );
10159
10160 let right_pane =
10161 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10162
10163 let boxed_clone = single_entry_items[1].boxed_clone();
10164 let right_pane = window.spawn(cx, async move |cx| {
10165 right_pane.await.inspect(|right_pane| {
10166 right_pane
10167 .update_in(cx, |pane, window, cx| {
10168 pane.add_item(boxed_clone, true, true, None, window, cx);
10169 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10170 })
10171 .unwrap();
10172 })
10173 });
10174
10175 (left_pane, right_pane)
10176 });
10177 let right_pane = right_pane.await.unwrap();
10178 cx.focus(&right_pane);
10179
10180 let close = right_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 msg = cx.pending_prompt().unwrap().0;
10187 assert!(msg.contains("1.txt"));
10188 assert!(!msg.contains("2.txt"));
10189 assert!(!msg.contains("3.txt"));
10190 assert!(!msg.contains("4.txt"));
10191
10192 // With best-effort close, cancelling item 1 keeps it open but items 4
10193 // and (3,4) still close since their entries exist in left pane.
10194 cx.simulate_prompt_answer("Cancel");
10195 close.await;
10196
10197 right_pane.read_with(cx, |pane, _| {
10198 assert_eq!(pane.items_len(), 1);
10199 });
10200
10201 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10202 left_pane
10203 .update_in(cx, |left_pane, window, cx| {
10204 left_pane.close_item_by_id(
10205 single_entry_items[3].entity_id(),
10206 SaveIntent::Skip,
10207 window,
10208 cx,
10209 )
10210 })
10211 .await
10212 .unwrap();
10213
10214 let close = left_pane.update_in(cx, |pane, window, cx| {
10215 pane.close_all_items(&CloseAllItems::default(), window, cx)
10216 .unwrap()
10217 });
10218 cx.executor().run_until_parked();
10219
10220 let details = cx.pending_prompt().unwrap().1;
10221 assert!(details.contains("0.txt"));
10222 assert!(details.contains("3.txt"));
10223 assert!(details.contains("4.txt"));
10224 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10225 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10226 // assert!(!details.contains("2.txt"));
10227
10228 cx.simulate_prompt_answer("Save all");
10229 cx.executor().run_until_parked();
10230 close.await;
10231
10232 left_pane.read_with(cx, |pane, _| {
10233 assert_eq!(pane.items_len(), 0);
10234 });
10235 }
10236
10237 #[gpui::test]
10238 async fn test_autosave(cx: &mut gpui::TestAppContext) {
10239 init_test(cx);
10240
10241 let fs = FakeFs::new(cx.executor());
10242 let project = Project::test(fs, [], cx).await;
10243 let (workspace, cx) =
10244 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10245 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10246
10247 let item = cx.new(|cx| {
10248 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10249 });
10250 let item_id = item.entity_id();
10251 workspace.update_in(cx, |workspace, window, cx| {
10252 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10253 });
10254
10255 // Autosave on window change.
10256 item.update(cx, |item, cx| {
10257 SettingsStore::update_global(cx, |settings, cx| {
10258 settings.update_user_settings(cx, |settings| {
10259 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10260 })
10261 });
10262 item.is_dirty = true;
10263 });
10264
10265 // Deactivating the window saves the file.
10266 cx.deactivate_window();
10267 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10268
10269 // Re-activating the window doesn't save the file.
10270 cx.update(|window, _| window.activate_window());
10271 cx.executor().run_until_parked();
10272 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10273
10274 // Autosave on focus change.
10275 item.update_in(cx, |item, window, cx| {
10276 cx.focus_self(window);
10277 SettingsStore::update_global(cx, |settings, cx| {
10278 settings.update_user_settings(cx, |settings| {
10279 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10280 })
10281 });
10282 item.is_dirty = true;
10283 });
10284 // Blurring the item saves the file.
10285 item.update_in(cx, |_, window, _| window.blur());
10286 cx.executor().run_until_parked();
10287 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10288
10289 // Deactivating the window still saves the file.
10290 item.update_in(cx, |item, window, cx| {
10291 cx.focus_self(window);
10292 item.is_dirty = true;
10293 });
10294 cx.deactivate_window();
10295 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10296
10297 // Autosave after delay.
10298 item.update(cx, |item, cx| {
10299 SettingsStore::update_global(cx, |settings, cx| {
10300 settings.update_user_settings(cx, |settings| {
10301 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10302 milliseconds: 500.into(),
10303 });
10304 })
10305 });
10306 item.is_dirty = true;
10307 cx.emit(ItemEvent::Edit);
10308 });
10309
10310 // Delay hasn't fully expired, so the file is still dirty and unsaved.
10311 cx.executor().advance_clock(Duration::from_millis(250));
10312 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10313
10314 // After delay expires, the file is saved.
10315 cx.executor().advance_clock(Duration::from_millis(250));
10316 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10317
10318 // Autosave after delay, should save earlier than delay if tab is closed
10319 item.update(cx, |item, cx| {
10320 item.is_dirty = true;
10321 cx.emit(ItemEvent::Edit);
10322 });
10323 cx.executor().advance_clock(Duration::from_millis(250));
10324 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10325
10326 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
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, 5));
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.is_dirty = true;
10341 for project_item in &mut item.project_items {
10342 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10343 }
10344 });
10345 cx.run_until_parked();
10346 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10347
10348 // Autosave on focus change, ensuring closing the tab counts as such.
10349 item.update(cx, |item, cx| {
10350 SettingsStore::update_global(cx, |settings, cx| {
10351 settings.update_user_settings(cx, |settings| {
10352 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10353 })
10354 });
10355 item.is_dirty = true;
10356 for project_item in &mut item.project_items {
10357 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10358 }
10359 });
10360
10361 pane.update_in(cx, |pane, window, cx| {
10362 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
10363 })
10364 .await
10365 .unwrap();
10366 assert!(!cx.has_pending_prompt());
10367 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10368
10369 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10370 workspace.update_in(cx, |workspace, window, cx| {
10371 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10372 });
10373 item.update_in(cx, |item, window, cx| {
10374 item.project_items[0].update(cx, |item, _| {
10375 item.entry_id = None;
10376 });
10377 item.is_dirty = true;
10378 window.blur();
10379 });
10380 cx.run_until_parked();
10381 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10382
10383 // Ensure autosave is prevented for deleted files also when closing the buffer.
10384 let _close_items = pane.update_in(cx, |pane, window, cx| {
10385 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
10386 });
10387 cx.run_until_parked();
10388 assert!(cx.has_pending_prompt());
10389 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10390 }
10391
10392 #[gpui::test]
10393 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10394 init_test(cx);
10395
10396 let fs = FakeFs::new(cx.executor());
10397
10398 let project = Project::test(fs, [], cx).await;
10399 let (workspace, cx) =
10400 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10401
10402 let item = cx.new(|cx| {
10403 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10404 });
10405 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10406 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10407 let toolbar_notify_count = Rc::new(RefCell::new(0));
10408
10409 workspace.update_in(cx, |workspace, window, cx| {
10410 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10411 let toolbar_notification_count = toolbar_notify_count.clone();
10412 cx.observe_in(&toolbar, window, move |_, _, _, _| {
10413 *toolbar_notification_count.borrow_mut() += 1
10414 })
10415 .detach();
10416 });
10417
10418 pane.read_with(cx, |pane, _| {
10419 assert!(!pane.can_navigate_backward());
10420 assert!(!pane.can_navigate_forward());
10421 });
10422
10423 item.update_in(cx, |item, _, cx| {
10424 item.set_state("one".to_string(), cx);
10425 });
10426
10427 // Toolbar must be notified to re-render the navigation buttons
10428 assert_eq!(*toolbar_notify_count.borrow(), 1);
10429
10430 pane.read_with(cx, |pane, _| {
10431 assert!(pane.can_navigate_backward());
10432 assert!(!pane.can_navigate_forward());
10433 });
10434
10435 workspace
10436 .update_in(cx, |workspace, window, cx| {
10437 workspace.go_back(pane.downgrade(), window, cx)
10438 })
10439 .await
10440 .unwrap();
10441
10442 assert_eq!(*toolbar_notify_count.borrow(), 2);
10443 pane.read_with(cx, |pane, _| {
10444 assert!(!pane.can_navigate_backward());
10445 assert!(pane.can_navigate_forward());
10446 });
10447 }
10448
10449 #[gpui::test]
10450 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
10451 init_test(cx);
10452 let fs = FakeFs::new(cx.executor());
10453
10454 let project = Project::test(fs, [], cx).await;
10455 let (workspace, cx) =
10456 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10457
10458 let panel = workspace.update_in(cx, |workspace, window, cx| {
10459 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10460 workspace.add_panel(panel.clone(), window, cx);
10461
10462 workspace
10463 .right_dock()
10464 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10465
10466 panel
10467 });
10468
10469 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10470 pane.update_in(cx, |pane, window, cx| {
10471 let item = cx.new(TestItem::new);
10472 pane.add_item(Box::new(item), true, true, None, window, cx);
10473 });
10474
10475 // Transfer focus from center to panel
10476 workspace.update_in(cx, |workspace, window, cx| {
10477 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10478 });
10479
10480 workspace.update_in(cx, |workspace, window, cx| {
10481 assert!(workspace.right_dock().read(cx).is_open());
10482 assert!(!panel.is_zoomed(window, cx));
10483 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10484 });
10485
10486 // Transfer focus from panel to center
10487 workspace.update_in(cx, |workspace, window, cx| {
10488 workspace.toggle_panel_focus::<TestPanel>(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 // Close the dock
10498 workspace.update_in(cx, |workspace, window, cx| {
10499 workspace.toggle_dock(DockPosition::Right, 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 // Open the dock
10509 workspace.update_in(cx, |workspace, window, cx| {
10510 workspace.toggle_dock(DockPosition::Right, 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 // Focus and zoom panel
10520 panel.update_in(cx, |panel, window, cx| {
10521 cx.focus_self(window);
10522 panel.set_zoomed(true, window, cx)
10523 });
10524
10525 workspace.update_in(cx, |workspace, window, cx| {
10526 assert!(workspace.right_dock().read(cx).is_open());
10527 assert!(panel.is_zoomed(window, cx));
10528 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10529 });
10530
10531 // Transfer focus to the center closes the dock
10532 workspace.update_in(cx, |workspace, window, cx| {
10533 workspace.toggle_panel_focus::<TestPanel>(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!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10540 });
10541
10542 // Transferring focus back to the panel keeps it zoomed
10543 workspace.update_in(cx, |workspace, window, cx| {
10544 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10545 });
10546
10547 workspace.update_in(cx, |workspace, window, cx| {
10548 assert!(workspace.right_dock().read(cx).is_open());
10549 assert!(panel.is_zoomed(window, cx));
10550 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10551 });
10552
10553 // Close the dock while it is zoomed
10554 workspace.update_in(cx, |workspace, window, cx| {
10555 workspace.toggle_dock(DockPosition::Right, window, cx)
10556 });
10557
10558 workspace.update_in(cx, |workspace, window, cx| {
10559 assert!(!workspace.right_dock().read(cx).is_open());
10560 assert!(panel.is_zoomed(window, cx));
10561 assert!(workspace.zoomed.is_none());
10562 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10563 });
10564
10565 // Opening the dock, when it's zoomed, retains focus
10566 workspace.update_in(cx, |workspace, window, cx| {
10567 workspace.toggle_dock(DockPosition::Right, window, cx)
10568 });
10569
10570 workspace.update_in(cx, |workspace, window, cx| {
10571 assert!(workspace.right_dock().read(cx).is_open());
10572 assert!(panel.is_zoomed(window, cx));
10573 assert!(workspace.zoomed.is_some());
10574 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10575 });
10576
10577 // Unzoom and close the panel, zoom the active pane.
10578 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
10579 workspace.update_in(cx, |workspace, window, cx| {
10580 workspace.toggle_dock(DockPosition::Right, window, cx)
10581 });
10582 pane.update_in(cx, |pane, window, cx| {
10583 pane.toggle_zoom(&Default::default(), window, cx)
10584 });
10585
10586 // Opening a dock unzooms the pane.
10587 workspace.update_in(cx, |workspace, window, cx| {
10588 workspace.toggle_dock(DockPosition::Right, window, cx)
10589 });
10590 workspace.update_in(cx, |workspace, window, cx| {
10591 let pane = pane.read(cx);
10592 assert!(!pane.is_zoomed());
10593 assert!(!pane.focus_handle(cx).is_focused(window));
10594 assert!(workspace.right_dock().read(cx).is_open());
10595 assert!(workspace.zoomed.is_none());
10596 });
10597 }
10598
10599 #[gpui::test]
10600 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
10601 init_test(cx);
10602 let fs = FakeFs::new(cx.executor());
10603
10604 let project = Project::test(fs, [], cx).await;
10605 let (workspace, cx) =
10606 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10607
10608 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
10609 workspace.active_pane().clone()
10610 });
10611
10612 // Add an item to the pane so it can be zoomed
10613 workspace.update_in(cx, |workspace, window, cx| {
10614 let item = cx.new(TestItem::new);
10615 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
10616 });
10617
10618 // Initially not zoomed
10619 workspace.update_in(cx, |workspace, _window, cx| {
10620 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
10621 assert!(
10622 workspace.zoomed.is_none(),
10623 "Workspace should track no zoomed pane"
10624 );
10625 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
10626 });
10627
10628 // Zoom In
10629 pane.update_in(cx, |pane, window, cx| {
10630 pane.zoom_in(&crate::ZoomIn, window, cx);
10631 });
10632
10633 workspace.update_in(cx, |workspace, window, cx| {
10634 assert!(
10635 pane.read(cx).is_zoomed(),
10636 "Pane should be zoomed after ZoomIn"
10637 );
10638 assert!(
10639 workspace.zoomed.is_some(),
10640 "Workspace should track the zoomed pane"
10641 );
10642 assert!(
10643 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
10644 "ZoomIn should focus the pane"
10645 );
10646 });
10647
10648 // Zoom In again is a no-op
10649 pane.update_in(cx, |pane, window, cx| {
10650 pane.zoom_in(&crate::ZoomIn, window, cx);
10651 });
10652
10653 workspace.update_in(cx, |workspace, window, cx| {
10654 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
10655 assert!(
10656 workspace.zoomed.is_some(),
10657 "Workspace still tracks zoomed pane"
10658 );
10659 assert!(
10660 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
10661 "Pane remains focused after repeated ZoomIn"
10662 );
10663 });
10664
10665 // Zoom Out
10666 pane.update_in(cx, |pane, window, cx| {
10667 pane.zoom_out(&crate::ZoomOut, window, cx);
10668 });
10669
10670 workspace.update_in(cx, |workspace, _window, cx| {
10671 assert!(
10672 !pane.read(cx).is_zoomed(),
10673 "Pane should unzoom after ZoomOut"
10674 );
10675 assert!(
10676 workspace.zoomed.is_none(),
10677 "Workspace clears zoom tracking after ZoomOut"
10678 );
10679 });
10680
10681 // Zoom Out again is a no-op
10682 pane.update_in(cx, |pane, window, cx| {
10683 pane.zoom_out(&crate::ZoomOut, window, cx);
10684 });
10685
10686 workspace.update_in(cx, |workspace, _window, cx| {
10687 assert!(
10688 !pane.read(cx).is_zoomed(),
10689 "Second ZoomOut keeps pane unzoomed"
10690 );
10691 assert!(
10692 workspace.zoomed.is_none(),
10693 "Workspace remains without zoomed pane"
10694 );
10695 });
10696 }
10697
10698 #[gpui::test]
10699 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
10700 init_test(cx);
10701 let fs = FakeFs::new(cx.executor());
10702
10703 let project = Project::test(fs, [], cx).await;
10704 let (workspace, cx) =
10705 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10706 workspace.update_in(cx, |workspace, window, cx| {
10707 // Open two docks
10708 let left_dock = workspace.dock_at_position(DockPosition::Left);
10709 let right_dock = workspace.dock_at_position(DockPosition::Right);
10710
10711 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10712 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10713
10714 assert!(left_dock.read(cx).is_open());
10715 assert!(right_dock.read(cx).is_open());
10716 });
10717
10718 workspace.update_in(cx, |workspace, window, cx| {
10719 // Toggle all docks - should close both
10720 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10721
10722 let left_dock = workspace.dock_at_position(DockPosition::Left);
10723 let right_dock = workspace.dock_at_position(DockPosition::Right);
10724 assert!(!left_dock.read(cx).is_open());
10725 assert!(!right_dock.read(cx).is_open());
10726 });
10727
10728 workspace.update_in(cx, |workspace, window, cx| {
10729 // Toggle again - should reopen both
10730 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10731
10732 let left_dock = workspace.dock_at_position(DockPosition::Left);
10733 let right_dock = workspace.dock_at_position(DockPosition::Right);
10734 assert!(left_dock.read(cx).is_open());
10735 assert!(right_dock.read(cx).is_open());
10736 });
10737 }
10738
10739 #[gpui::test]
10740 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
10741 init_test(cx);
10742 let fs = FakeFs::new(cx.executor());
10743
10744 let project = Project::test(fs, [], cx).await;
10745 let (workspace, cx) =
10746 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10747 workspace.update_in(cx, |workspace, window, cx| {
10748 // Open two docks
10749 let left_dock = workspace.dock_at_position(DockPosition::Left);
10750 let right_dock = workspace.dock_at_position(DockPosition::Right);
10751
10752 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10753 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10754
10755 assert!(left_dock.read(cx).is_open());
10756 assert!(right_dock.read(cx).is_open());
10757 });
10758
10759 workspace.update_in(cx, |workspace, window, cx| {
10760 // Close them manually
10761 workspace.toggle_dock(DockPosition::Left, window, cx);
10762 workspace.toggle_dock(DockPosition::Right, window, cx);
10763
10764 let left_dock = workspace.dock_at_position(DockPosition::Left);
10765 let right_dock = workspace.dock_at_position(DockPosition::Right);
10766 assert!(!left_dock.read(cx).is_open());
10767 assert!(!right_dock.read(cx).is_open());
10768 });
10769
10770 workspace.update_in(cx, |workspace, window, cx| {
10771 // Toggle all docks - only last closed (right dock) should reopen
10772 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10773
10774 let left_dock = workspace.dock_at_position(DockPosition::Left);
10775 let right_dock = workspace.dock_at_position(DockPosition::Right);
10776 assert!(!left_dock.read(cx).is_open());
10777 assert!(right_dock.read(cx).is_open());
10778 });
10779 }
10780
10781 #[gpui::test]
10782 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
10783 init_test(cx);
10784 let fs = FakeFs::new(cx.executor());
10785 let project = Project::test(fs, [], cx).await;
10786 let (workspace, cx) =
10787 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10788
10789 // Open two docks (left and right) with one panel each
10790 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
10791 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
10792 workspace.add_panel(left_panel.clone(), window, cx);
10793
10794 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
10795 workspace.add_panel(right_panel.clone(), window, cx);
10796
10797 workspace.toggle_dock(DockPosition::Left, window, cx);
10798 workspace.toggle_dock(DockPosition::Right, window, cx);
10799
10800 // Verify initial state
10801 assert!(
10802 workspace.left_dock().read(cx).is_open(),
10803 "Left dock should be open"
10804 );
10805 assert_eq!(
10806 workspace
10807 .left_dock()
10808 .read(cx)
10809 .visible_panel()
10810 .unwrap()
10811 .panel_id(),
10812 left_panel.panel_id(),
10813 "Left panel should be visible in left dock"
10814 );
10815 assert!(
10816 workspace.right_dock().read(cx).is_open(),
10817 "Right dock should be open"
10818 );
10819 assert_eq!(
10820 workspace
10821 .right_dock()
10822 .read(cx)
10823 .visible_panel()
10824 .unwrap()
10825 .panel_id(),
10826 right_panel.panel_id(),
10827 "Right panel should be visible in right dock"
10828 );
10829 assert!(
10830 !workspace.bottom_dock().read(cx).is_open(),
10831 "Bottom dock should be closed"
10832 );
10833
10834 (left_panel, right_panel)
10835 });
10836
10837 // Focus the left panel and move it to the next position (bottom dock)
10838 workspace.update_in(cx, |workspace, window, cx| {
10839 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
10840 assert!(
10841 left_panel.read(cx).focus_handle(cx).is_focused(window),
10842 "Left panel should be focused"
10843 );
10844 });
10845
10846 cx.dispatch_action(MoveFocusedPanelToNextPosition);
10847
10848 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
10849 workspace.update(cx, |workspace, cx| {
10850 assert!(
10851 !workspace.left_dock().read(cx).is_open(),
10852 "Left dock should be closed"
10853 );
10854 assert!(
10855 workspace.bottom_dock().read(cx).is_open(),
10856 "Bottom dock should now be open"
10857 );
10858 assert_eq!(
10859 left_panel.read(cx).position,
10860 DockPosition::Bottom,
10861 "Left panel should now be in the bottom dock"
10862 );
10863 assert_eq!(
10864 workspace
10865 .bottom_dock()
10866 .read(cx)
10867 .visible_panel()
10868 .unwrap()
10869 .panel_id(),
10870 left_panel.panel_id(),
10871 "Left panel should be the visible panel in the bottom dock"
10872 );
10873 });
10874
10875 // Toggle all docks off
10876 workspace.update_in(cx, |workspace, window, cx| {
10877 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10878 assert!(
10879 !workspace.left_dock().read(cx).is_open(),
10880 "Left dock should be closed"
10881 );
10882 assert!(
10883 !workspace.right_dock().read(cx).is_open(),
10884 "Right dock should be closed"
10885 );
10886 assert!(
10887 !workspace.bottom_dock().read(cx).is_open(),
10888 "Bottom dock should be closed"
10889 );
10890 });
10891
10892 // Toggle all docks back on and verify positions are restored
10893 workspace.update_in(cx, |workspace, window, cx| {
10894 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10895 assert!(
10896 !workspace.left_dock().read(cx).is_open(),
10897 "Left dock should remain closed"
10898 );
10899 assert!(
10900 workspace.right_dock().read(cx).is_open(),
10901 "Right dock should remain open"
10902 );
10903 assert!(
10904 workspace.bottom_dock().read(cx).is_open(),
10905 "Bottom dock should remain open"
10906 );
10907 assert_eq!(
10908 left_panel.read(cx).position,
10909 DockPosition::Bottom,
10910 "Left panel should remain in the bottom dock"
10911 );
10912 assert_eq!(
10913 right_panel.read(cx).position,
10914 DockPosition::Right,
10915 "Right panel should remain in the right dock"
10916 );
10917 assert_eq!(
10918 workspace
10919 .bottom_dock()
10920 .read(cx)
10921 .visible_panel()
10922 .unwrap()
10923 .panel_id(),
10924 left_panel.panel_id(),
10925 "Left panel should be the visible panel in the right dock"
10926 );
10927 });
10928 }
10929
10930 #[gpui::test]
10931 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
10932 init_test(cx);
10933
10934 let fs = FakeFs::new(cx.executor());
10935
10936 let project = Project::test(fs, None, cx).await;
10937 let (workspace, cx) =
10938 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10939
10940 // Let's arrange the panes like this:
10941 //
10942 // +-----------------------+
10943 // | top |
10944 // +------+--------+-------+
10945 // | left | center | right |
10946 // +------+--------+-------+
10947 // | bottom |
10948 // +-----------------------+
10949
10950 let top_item = cx.new(|cx| {
10951 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
10952 });
10953 let bottom_item = cx.new(|cx| {
10954 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
10955 });
10956 let left_item = cx.new(|cx| {
10957 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
10958 });
10959 let right_item = cx.new(|cx| {
10960 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
10961 });
10962 let center_item = cx.new(|cx| {
10963 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
10964 });
10965
10966 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10967 let top_pane_id = workspace.active_pane().entity_id();
10968 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
10969 workspace.split_pane(
10970 workspace.active_pane().clone(),
10971 SplitDirection::Down,
10972 window,
10973 cx,
10974 );
10975 top_pane_id
10976 });
10977 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10978 let bottom_pane_id = workspace.active_pane().entity_id();
10979 workspace.add_item_to_active_pane(
10980 Box::new(bottom_item.clone()),
10981 None,
10982 false,
10983 window,
10984 cx,
10985 );
10986 workspace.split_pane(
10987 workspace.active_pane().clone(),
10988 SplitDirection::Up,
10989 window,
10990 cx,
10991 );
10992 bottom_pane_id
10993 });
10994 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10995 let left_pane_id = workspace.active_pane().entity_id();
10996 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
10997 workspace.split_pane(
10998 workspace.active_pane().clone(),
10999 SplitDirection::Right,
11000 window,
11001 cx,
11002 );
11003 left_pane_id
11004 });
11005 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11006 let right_pane_id = workspace.active_pane().entity_id();
11007 workspace.add_item_to_active_pane(
11008 Box::new(right_item.clone()),
11009 None,
11010 false,
11011 window,
11012 cx,
11013 );
11014 workspace.split_pane(
11015 workspace.active_pane().clone(),
11016 SplitDirection::Left,
11017 window,
11018 cx,
11019 );
11020 right_pane_id
11021 });
11022 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11023 let center_pane_id = workspace.active_pane().entity_id();
11024 workspace.add_item_to_active_pane(
11025 Box::new(center_item.clone()),
11026 None,
11027 false,
11028 window,
11029 cx,
11030 );
11031 center_pane_id
11032 });
11033 cx.executor().run_until_parked();
11034
11035 workspace.update_in(cx, |workspace, window, cx| {
11036 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11037
11038 // Join into next from center pane into right
11039 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11040 });
11041
11042 workspace.update_in(cx, |workspace, window, cx| {
11043 let active_pane = workspace.active_pane();
11044 assert_eq!(right_pane_id, active_pane.entity_id());
11045 assert_eq!(2, active_pane.read(cx).items_len());
11046 let item_ids_in_pane =
11047 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11048 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11049 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11050
11051 // Join into next from right pane into bottom
11052 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11053 });
11054
11055 workspace.update_in(cx, |workspace, window, cx| {
11056 let active_pane = workspace.active_pane();
11057 assert_eq!(bottom_pane_id, active_pane.entity_id());
11058 assert_eq!(3, active_pane.read(cx).items_len());
11059 let item_ids_in_pane =
11060 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11061 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11062 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11063 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11064
11065 // Join into next from bottom pane into left
11066 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11067 });
11068
11069 workspace.update_in(cx, |workspace, window, cx| {
11070 let active_pane = workspace.active_pane();
11071 assert_eq!(left_pane_id, active_pane.entity_id());
11072 assert_eq!(4, active_pane.read(cx).items_len());
11073 let item_ids_in_pane =
11074 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11075 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11076 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11077 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11078 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11079
11080 // Join into next from left pane into top
11081 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11082 });
11083
11084 workspace.update_in(cx, |workspace, window, cx| {
11085 let active_pane = workspace.active_pane();
11086 assert_eq!(top_pane_id, active_pane.entity_id());
11087 assert_eq!(5, active_pane.read(cx).items_len());
11088 let item_ids_in_pane =
11089 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11090 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11091 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11092 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11093 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11094 assert!(item_ids_in_pane.contains(&top_item.item_id()));
11095
11096 // Single pane left: no-op
11097 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11098 });
11099
11100 workspace.update(cx, |workspace, _cx| {
11101 let active_pane = workspace.active_pane();
11102 assert_eq!(top_pane_id, active_pane.entity_id());
11103 });
11104 }
11105
11106 fn add_an_item_to_active_pane(
11107 cx: &mut VisualTestContext,
11108 workspace: &Entity<Workspace>,
11109 item_id: u64,
11110 ) -> Entity<TestItem> {
11111 let item = cx.new(|cx| {
11112 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11113 item_id,
11114 "item{item_id}.txt",
11115 cx,
11116 )])
11117 });
11118 workspace.update_in(cx, |workspace, window, cx| {
11119 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11120 });
11121 item
11122 }
11123
11124 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11125 workspace.update_in(cx, |workspace, window, cx| {
11126 workspace.split_pane(
11127 workspace.active_pane().clone(),
11128 SplitDirection::Right,
11129 window,
11130 cx,
11131 )
11132 })
11133 }
11134
11135 #[gpui::test]
11136 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11137 init_test(cx);
11138 let fs = FakeFs::new(cx.executor());
11139 let project = Project::test(fs, None, cx).await;
11140 let (workspace, cx) =
11141 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11142
11143 add_an_item_to_active_pane(cx, &workspace, 1);
11144 split_pane(cx, &workspace);
11145 add_an_item_to_active_pane(cx, &workspace, 2);
11146 split_pane(cx, &workspace); // empty pane
11147 split_pane(cx, &workspace);
11148 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11149
11150 cx.executor().run_until_parked();
11151
11152 workspace.update(cx, |workspace, cx| {
11153 let num_panes = workspace.panes().len();
11154 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11155 let active_item = workspace
11156 .active_pane()
11157 .read(cx)
11158 .active_item()
11159 .expect("item is in focus");
11160
11161 assert_eq!(num_panes, 4);
11162 assert_eq!(num_items_in_current_pane, 1);
11163 assert_eq!(active_item.item_id(), last_item.item_id());
11164 });
11165
11166 workspace.update_in(cx, |workspace, window, cx| {
11167 workspace.join_all_panes(window, cx);
11168 });
11169
11170 workspace.update(cx, |workspace, cx| {
11171 let num_panes = workspace.panes().len();
11172 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11173 let active_item = workspace
11174 .active_pane()
11175 .read(cx)
11176 .active_item()
11177 .expect("item is in focus");
11178
11179 assert_eq!(num_panes, 1);
11180 assert_eq!(num_items_in_current_pane, 3);
11181 assert_eq!(active_item.item_id(), last_item.item_id());
11182 });
11183 }
11184 struct TestModal(FocusHandle);
11185
11186 impl TestModal {
11187 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11188 Self(cx.focus_handle())
11189 }
11190 }
11191
11192 impl EventEmitter<DismissEvent> for TestModal {}
11193
11194 impl Focusable for TestModal {
11195 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11196 self.0.clone()
11197 }
11198 }
11199
11200 impl ModalView for TestModal {}
11201
11202 impl Render for TestModal {
11203 fn render(
11204 &mut self,
11205 _window: &mut Window,
11206 _cx: &mut Context<TestModal>,
11207 ) -> impl IntoElement {
11208 div().track_focus(&self.0)
11209 }
11210 }
11211
11212 #[gpui::test]
11213 async fn test_panels(cx: &mut gpui::TestAppContext) {
11214 init_test(cx);
11215 let fs = FakeFs::new(cx.executor());
11216
11217 let project = Project::test(fs, [], cx).await;
11218 let (workspace, cx) =
11219 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11220
11221 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11222 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11223 workspace.add_panel(panel_1.clone(), window, cx);
11224 workspace.toggle_dock(DockPosition::Left, window, cx);
11225 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11226 workspace.add_panel(panel_2.clone(), window, cx);
11227 workspace.toggle_dock(DockPosition::Right, window, cx);
11228
11229 let left_dock = workspace.left_dock();
11230 assert_eq!(
11231 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11232 panel_1.panel_id()
11233 );
11234 assert_eq!(
11235 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11236 panel_1.size(window, cx)
11237 );
11238
11239 left_dock.update(cx, |left_dock, cx| {
11240 left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11241 });
11242 assert_eq!(
11243 workspace
11244 .right_dock()
11245 .read(cx)
11246 .visible_panel()
11247 .unwrap()
11248 .panel_id(),
11249 panel_2.panel_id(),
11250 );
11251
11252 (panel_1, panel_2)
11253 });
11254
11255 // Move panel_1 to the right
11256 panel_1.update_in(cx, |panel_1, window, cx| {
11257 panel_1.set_position(DockPosition::Right, window, cx)
11258 });
11259
11260 workspace.update_in(cx, |workspace, window, cx| {
11261 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11262 // Since it was the only panel on the left, the left dock should now be closed.
11263 assert!(!workspace.left_dock().read(cx).is_open());
11264 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11265 let right_dock = workspace.right_dock();
11266 assert_eq!(
11267 right_dock.read(cx).visible_panel().unwrap().panel_id(),
11268 panel_1.panel_id()
11269 );
11270 assert_eq!(
11271 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11272 px(1337.)
11273 );
11274
11275 // Now we move panel_2 to the left
11276 panel_2.set_position(DockPosition::Left, window, cx);
11277 });
11278
11279 workspace.update(cx, |workspace, cx| {
11280 // Since panel_2 was not visible on the right, we don't open the left dock.
11281 assert!(!workspace.left_dock().read(cx).is_open());
11282 // And the right dock is unaffected in its displaying of panel_1
11283 assert!(workspace.right_dock().read(cx).is_open());
11284 assert_eq!(
11285 workspace
11286 .right_dock()
11287 .read(cx)
11288 .visible_panel()
11289 .unwrap()
11290 .panel_id(),
11291 panel_1.panel_id(),
11292 );
11293 });
11294
11295 // Move panel_1 back to the left
11296 panel_1.update_in(cx, |panel_1, window, cx| {
11297 panel_1.set_position(DockPosition::Left, window, cx)
11298 });
11299
11300 workspace.update_in(cx, |workspace, window, cx| {
11301 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
11302 let left_dock = workspace.left_dock();
11303 assert!(left_dock.read(cx).is_open());
11304 assert_eq!(
11305 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11306 panel_1.panel_id()
11307 );
11308 assert_eq!(
11309 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11310 px(1337.)
11311 );
11312 // And the right dock should be closed as it no longer has any panels.
11313 assert!(!workspace.right_dock().read(cx).is_open());
11314
11315 // Now we move panel_1 to the bottom
11316 panel_1.set_position(DockPosition::Bottom, window, cx);
11317 });
11318
11319 workspace.update_in(cx, |workspace, window, cx| {
11320 // Since panel_1 was visible on the left, we close the left dock.
11321 assert!(!workspace.left_dock().read(cx).is_open());
11322 // The bottom dock is sized based on the panel's default size,
11323 // since the panel orientation changed from vertical to horizontal.
11324 let bottom_dock = workspace.bottom_dock();
11325 assert_eq!(
11326 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
11327 panel_1.size(window, cx),
11328 );
11329 // Close bottom dock and move panel_1 back to the left.
11330 bottom_dock.update(cx, |bottom_dock, cx| {
11331 bottom_dock.set_open(false, window, cx)
11332 });
11333 panel_1.set_position(DockPosition::Left, window, cx);
11334 });
11335
11336 // Emit activated event on panel 1
11337 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
11338
11339 // Now the left dock is open and panel_1 is active and focused.
11340 workspace.update_in(cx, |workspace, window, cx| {
11341 let left_dock = workspace.left_dock();
11342 assert!(left_dock.read(cx).is_open());
11343 assert_eq!(
11344 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11345 panel_1.panel_id(),
11346 );
11347 assert!(panel_1.focus_handle(cx).is_focused(window));
11348 });
11349
11350 // Emit closed event on panel 2, which is not active
11351 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11352
11353 // Wo don't close the left dock, because panel_2 wasn't the active panel
11354 workspace.update(cx, |workspace, cx| {
11355 let left_dock = workspace.left_dock();
11356 assert!(left_dock.read(cx).is_open());
11357 assert_eq!(
11358 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11359 panel_1.panel_id(),
11360 );
11361 });
11362
11363 // Emitting a ZoomIn event shows the panel as zoomed.
11364 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
11365 workspace.read_with(cx, |workspace, _| {
11366 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11367 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
11368 });
11369
11370 // Move panel to another dock while it is zoomed
11371 panel_1.update_in(cx, |panel, window, cx| {
11372 panel.set_position(DockPosition::Right, window, cx)
11373 });
11374 workspace.read_with(cx, |workspace, _| {
11375 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11376
11377 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11378 });
11379
11380 // This is a helper for getting a:
11381 // - valid focus on an element,
11382 // - that isn't a part of the panes and panels system of the Workspace,
11383 // - and doesn't trigger the 'on_focus_lost' API.
11384 let focus_other_view = {
11385 let workspace = workspace.clone();
11386 move |cx: &mut VisualTestContext| {
11387 workspace.update_in(cx, |workspace, window, cx| {
11388 if workspace.active_modal::<TestModal>(cx).is_some() {
11389 workspace.toggle_modal(window, cx, TestModal::new);
11390 workspace.toggle_modal(window, cx, TestModal::new);
11391 } else {
11392 workspace.toggle_modal(window, cx, TestModal::new);
11393 }
11394 })
11395 }
11396 };
11397
11398 // If focus is transferred to another view that's not a panel or another pane, we still show
11399 // the panel as zoomed.
11400 focus_other_view(cx);
11401 workspace.read_with(cx, |workspace, _| {
11402 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11403 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11404 });
11405
11406 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
11407 workspace.update_in(cx, |_workspace, window, cx| {
11408 cx.focus_self(window);
11409 });
11410 workspace.read_with(cx, |workspace, _| {
11411 assert_eq!(workspace.zoomed, None);
11412 assert_eq!(workspace.zoomed_position, None);
11413 });
11414
11415 // If focus is transferred again to another view that's not a panel or a pane, we won't
11416 // show the panel as zoomed because it wasn't zoomed before.
11417 focus_other_view(cx);
11418 workspace.read_with(cx, |workspace, _| {
11419 assert_eq!(workspace.zoomed, None);
11420 assert_eq!(workspace.zoomed_position, None);
11421 });
11422
11423 // When the panel is activated, it is zoomed again.
11424 cx.dispatch_action(ToggleRightDock);
11425 workspace.read_with(cx, |workspace, _| {
11426 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11427 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11428 });
11429
11430 // Emitting a ZoomOut event unzooms the panel.
11431 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
11432 workspace.read_with(cx, |workspace, _| {
11433 assert_eq!(workspace.zoomed, None);
11434 assert_eq!(workspace.zoomed_position, None);
11435 });
11436
11437 // Emit closed event on panel 1, which is active
11438 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11439
11440 // Now the left dock is closed, because panel_1 was the active panel
11441 workspace.update(cx, |workspace, cx| {
11442 let right_dock = workspace.right_dock();
11443 assert!(!right_dock.read(cx).is_open());
11444 });
11445 }
11446
11447 #[gpui::test]
11448 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
11449 init_test(cx);
11450
11451 let fs = FakeFs::new(cx.background_executor.clone());
11452 let project = Project::test(fs, [], cx).await;
11453 let (workspace, cx) =
11454 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11455 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11456
11457 let dirty_regular_buffer = cx.new(|cx| {
11458 TestItem::new(cx)
11459 .with_dirty(true)
11460 .with_label("1.txt")
11461 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11462 });
11463 let dirty_regular_buffer_2 = cx.new(|cx| {
11464 TestItem::new(cx)
11465 .with_dirty(true)
11466 .with_label("2.txt")
11467 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11468 });
11469 let dirty_multi_buffer_with_both = cx.new(|cx| {
11470 TestItem::new(cx)
11471 .with_dirty(true)
11472 .with_buffer_kind(ItemBufferKind::Multibuffer)
11473 .with_label("Fake Project Search")
11474 .with_project_items(&[
11475 dirty_regular_buffer.read(cx).project_items[0].clone(),
11476 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11477 ])
11478 });
11479 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
11480 workspace.update_in(cx, |workspace, window, cx| {
11481 workspace.add_item(
11482 pane.clone(),
11483 Box::new(dirty_regular_buffer.clone()),
11484 None,
11485 false,
11486 false,
11487 window,
11488 cx,
11489 );
11490 workspace.add_item(
11491 pane.clone(),
11492 Box::new(dirty_regular_buffer_2.clone()),
11493 None,
11494 false,
11495 false,
11496 window,
11497 cx,
11498 );
11499 workspace.add_item(
11500 pane.clone(),
11501 Box::new(dirty_multi_buffer_with_both.clone()),
11502 None,
11503 false,
11504 false,
11505 window,
11506 cx,
11507 );
11508 });
11509
11510 pane.update_in(cx, |pane, window, cx| {
11511 pane.activate_item(2, true, true, window, cx);
11512 assert_eq!(
11513 pane.active_item().unwrap().item_id(),
11514 multi_buffer_with_both_files_id,
11515 "Should select the multi buffer in the pane"
11516 );
11517 });
11518 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11519 pane.close_other_items(
11520 &CloseOtherItems {
11521 save_intent: Some(SaveIntent::Save),
11522 close_pinned: true,
11523 },
11524 None,
11525 window,
11526 cx,
11527 )
11528 });
11529 cx.background_executor.run_until_parked();
11530 assert!(!cx.has_pending_prompt());
11531 close_all_but_multi_buffer_task
11532 .await
11533 .expect("Closing all buffers but the multi buffer failed");
11534 pane.update(cx, |pane, cx| {
11535 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
11536 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
11537 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
11538 assert_eq!(pane.items_len(), 1);
11539 assert_eq!(
11540 pane.active_item().unwrap().item_id(),
11541 multi_buffer_with_both_files_id,
11542 "Should have only the multi buffer left in the pane"
11543 );
11544 assert!(
11545 dirty_multi_buffer_with_both.read(cx).is_dirty,
11546 "The multi buffer containing the unsaved buffer should still be dirty"
11547 );
11548 });
11549
11550 dirty_regular_buffer.update(cx, |buffer, cx| {
11551 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
11552 });
11553
11554 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11555 pane.close_active_item(
11556 &CloseActiveItem {
11557 save_intent: Some(SaveIntent::Close),
11558 close_pinned: false,
11559 },
11560 window,
11561 cx,
11562 )
11563 });
11564 cx.background_executor.run_until_parked();
11565 assert!(
11566 cx.has_pending_prompt(),
11567 "Dirty multi buffer should prompt a save dialog"
11568 );
11569 cx.simulate_prompt_answer("Save");
11570 cx.background_executor.run_until_parked();
11571 close_multi_buffer_task
11572 .await
11573 .expect("Closing the multi buffer failed");
11574 pane.update(cx, |pane, cx| {
11575 assert_eq!(
11576 dirty_multi_buffer_with_both.read(cx).save_count,
11577 1,
11578 "Multi buffer item should get be saved"
11579 );
11580 // Test impl does not save inner items, so we do not assert them
11581 assert_eq!(
11582 pane.items_len(),
11583 0,
11584 "No more items should be left in the pane"
11585 );
11586 assert!(pane.active_item().is_none());
11587 });
11588 }
11589
11590 #[gpui::test]
11591 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
11592 cx: &mut TestAppContext,
11593 ) {
11594 init_test(cx);
11595
11596 let fs = FakeFs::new(cx.background_executor.clone());
11597 let project = Project::test(fs, [], cx).await;
11598 let (workspace, cx) =
11599 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11600 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11601
11602 let dirty_regular_buffer = cx.new(|cx| {
11603 TestItem::new(cx)
11604 .with_dirty(true)
11605 .with_label("1.txt")
11606 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11607 });
11608 let dirty_regular_buffer_2 = cx.new(|cx| {
11609 TestItem::new(cx)
11610 .with_dirty(true)
11611 .with_label("2.txt")
11612 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11613 });
11614 let clear_regular_buffer = cx.new(|cx| {
11615 TestItem::new(cx)
11616 .with_label("3.txt")
11617 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
11618 });
11619
11620 let dirty_multi_buffer_with_both = cx.new(|cx| {
11621 TestItem::new(cx)
11622 .with_dirty(true)
11623 .with_buffer_kind(ItemBufferKind::Multibuffer)
11624 .with_label("Fake Project Search")
11625 .with_project_items(&[
11626 dirty_regular_buffer.read(cx).project_items[0].clone(),
11627 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11628 clear_regular_buffer.read(cx).project_items[0].clone(),
11629 ])
11630 });
11631 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
11632 workspace.update_in(cx, |workspace, window, cx| {
11633 workspace.add_item(
11634 pane.clone(),
11635 Box::new(dirty_regular_buffer.clone()),
11636 None,
11637 false,
11638 false,
11639 window,
11640 cx,
11641 );
11642 workspace.add_item(
11643 pane.clone(),
11644 Box::new(dirty_multi_buffer_with_both.clone()),
11645 None,
11646 false,
11647 false,
11648 window,
11649 cx,
11650 );
11651 });
11652
11653 pane.update_in(cx, |pane, window, cx| {
11654 pane.activate_item(1, true, true, window, cx);
11655 assert_eq!(
11656 pane.active_item().unwrap().item_id(),
11657 multi_buffer_with_both_files_id,
11658 "Should select the multi buffer in the pane"
11659 );
11660 });
11661 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11662 pane.close_active_item(
11663 &CloseActiveItem {
11664 save_intent: None,
11665 close_pinned: false,
11666 },
11667 window,
11668 cx,
11669 )
11670 });
11671 cx.background_executor.run_until_parked();
11672 assert!(
11673 cx.has_pending_prompt(),
11674 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
11675 );
11676 }
11677
11678 /// Tests that when `close_on_file_delete` is enabled, files are automatically
11679 /// closed when they are deleted from disk.
11680 #[gpui::test]
11681 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
11682 init_test(cx);
11683
11684 // Enable the close_on_disk_deletion setting
11685 cx.update_global(|store: &mut SettingsStore, cx| {
11686 store.update_user_settings(cx, |settings| {
11687 settings.workspace.close_on_file_delete = Some(true);
11688 });
11689 });
11690
11691 let fs = FakeFs::new(cx.background_executor.clone());
11692 let project = Project::test(fs, [], cx).await;
11693 let (workspace, cx) =
11694 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11695 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11696
11697 // Create a test item that simulates a file
11698 let item = cx.new(|cx| {
11699 TestItem::new(cx)
11700 .with_label("test.txt")
11701 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11702 });
11703
11704 // Add item to workspace
11705 workspace.update_in(cx, |workspace, window, cx| {
11706 workspace.add_item(
11707 pane.clone(),
11708 Box::new(item.clone()),
11709 None,
11710 false,
11711 false,
11712 window,
11713 cx,
11714 );
11715 });
11716
11717 // Verify the item is in the pane
11718 pane.read_with(cx, |pane, _| {
11719 assert_eq!(pane.items().count(), 1);
11720 });
11721
11722 // Simulate file deletion by setting the item's deleted state
11723 item.update(cx, |item, _| {
11724 item.set_has_deleted_file(true);
11725 });
11726
11727 // Emit UpdateTab event to trigger the close behavior
11728 cx.run_until_parked();
11729 item.update(cx, |_, cx| {
11730 cx.emit(ItemEvent::UpdateTab);
11731 });
11732
11733 // Allow the close operation to complete
11734 cx.run_until_parked();
11735
11736 // Verify the item was automatically closed
11737 pane.read_with(cx, |pane, _| {
11738 assert_eq!(
11739 pane.items().count(),
11740 0,
11741 "Item should be automatically closed when file is deleted"
11742 );
11743 });
11744 }
11745
11746 /// Tests that when `close_on_file_delete` is disabled (default), files remain
11747 /// open with a strikethrough when they are deleted from disk.
11748 #[gpui::test]
11749 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
11750 init_test(cx);
11751
11752 // Ensure close_on_disk_deletion is disabled (default)
11753 cx.update_global(|store: &mut SettingsStore, cx| {
11754 store.update_user_settings(cx, |settings| {
11755 settings.workspace.close_on_file_delete = Some(false);
11756 });
11757 });
11758
11759 let fs = FakeFs::new(cx.background_executor.clone());
11760 let project = Project::test(fs, [], cx).await;
11761 let (workspace, cx) =
11762 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11763 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11764
11765 // Create a test item that simulates a file
11766 let item = cx.new(|cx| {
11767 TestItem::new(cx)
11768 .with_label("test.txt")
11769 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11770 });
11771
11772 // Add item to workspace
11773 workspace.update_in(cx, |workspace, window, cx| {
11774 workspace.add_item(
11775 pane.clone(),
11776 Box::new(item.clone()),
11777 None,
11778 false,
11779 false,
11780 window,
11781 cx,
11782 );
11783 });
11784
11785 // Verify the item is in the pane
11786 pane.read_with(cx, |pane, _| {
11787 assert_eq!(pane.items().count(), 1);
11788 });
11789
11790 // Simulate file deletion
11791 item.update(cx, |item, _| {
11792 item.set_has_deleted_file(true);
11793 });
11794
11795 // Emit UpdateTab event
11796 cx.run_until_parked();
11797 item.update(cx, |_, cx| {
11798 cx.emit(ItemEvent::UpdateTab);
11799 });
11800
11801 // Allow any potential close operation to complete
11802 cx.run_until_parked();
11803
11804 // Verify the item remains open (with strikethrough)
11805 pane.read_with(cx, |pane, _| {
11806 assert_eq!(
11807 pane.items().count(),
11808 1,
11809 "Item should remain open when close_on_disk_deletion is disabled"
11810 );
11811 });
11812
11813 // Verify the item shows as deleted
11814 item.read_with(cx, |item, _| {
11815 assert!(
11816 item.has_deleted_file,
11817 "Item should be marked as having deleted file"
11818 );
11819 });
11820 }
11821
11822 /// Tests that dirty files are not automatically closed when deleted from disk,
11823 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
11824 /// unsaved changes without being prompted.
11825 #[gpui::test]
11826 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
11827 init_test(cx);
11828
11829 // Enable the close_on_file_delete setting
11830 cx.update_global(|store: &mut SettingsStore, cx| {
11831 store.update_user_settings(cx, |settings| {
11832 settings.workspace.close_on_file_delete = Some(true);
11833 });
11834 });
11835
11836 let fs = FakeFs::new(cx.background_executor.clone());
11837 let project = Project::test(fs, [], cx).await;
11838 let (workspace, cx) =
11839 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11840 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11841
11842 // Create a dirty test item
11843 let item = cx.new(|cx| {
11844 TestItem::new(cx)
11845 .with_dirty(true)
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 // Simulate file deletion
11864 item.update(cx, |item, _| {
11865 item.set_has_deleted_file(true);
11866 });
11867
11868 // Emit UpdateTab event to trigger the close behavior
11869 cx.run_until_parked();
11870 item.update(cx, |_, cx| {
11871 cx.emit(ItemEvent::UpdateTab);
11872 });
11873
11874 // Allow any potential close operation to complete
11875 cx.run_until_parked();
11876
11877 // Verify the item remains open (dirty files are not auto-closed)
11878 pane.read_with(cx, |pane, _| {
11879 assert_eq!(
11880 pane.items().count(),
11881 1,
11882 "Dirty items should not be automatically closed even when file is deleted"
11883 );
11884 });
11885
11886 // Verify the item is marked as deleted and still dirty
11887 item.read_with(cx, |item, _| {
11888 assert!(
11889 item.has_deleted_file,
11890 "Item should be marked as having deleted file"
11891 );
11892 assert!(item.is_dirty, "Item should still be dirty");
11893 });
11894 }
11895
11896 /// Tests that navigation history is cleaned up when files are auto-closed
11897 /// due to deletion from disk.
11898 #[gpui::test]
11899 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
11900 init_test(cx);
11901
11902 // Enable the close_on_file_delete setting
11903 cx.update_global(|store: &mut SettingsStore, cx| {
11904 store.update_user_settings(cx, |settings| {
11905 settings.workspace.close_on_file_delete = Some(true);
11906 });
11907 });
11908
11909 let fs = FakeFs::new(cx.background_executor.clone());
11910 let project = Project::test(fs, [], cx).await;
11911 let (workspace, cx) =
11912 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11913 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11914
11915 // Create test items
11916 let item1 = cx.new(|cx| {
11917 TestItem::new(cx)
11918 .with_label("test1.txt")
11919 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
11920 });
11921 let item1_id = item1.item_id();
11922
11923 let item2 = cx.new(|cx| {
11924 TestItem::new(cx)
11925 .with_label("test2.txt")
11926 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
11927 });
11928
11929 // Add items to workspace
11930 workspace.update_in(cx, |workspace, window, cx| {
11931 workspace.add_item(
11932 pane.clone(),
11933 Box::new(item1.clone()),
11934 None,
11935 false,
11936 false,
11937 window,
11938 cx,
11939 );
11940 workspace.add_item(
11941 pane.clone(),
11942 Box::new(item2.clone()),
11943 None,
11944 false,
11945 false,
11946 window,
11947 cx,
11948 );
11949 });
11950
11951 // Activate item1 to ensure it gets navigation entries
11952 pane.update_in(cx, |pane, window, cx| {
11953 pane.activate_item(0, true, true, window, cx);
11954 });
11955
11956 // Switch to item2 and back to create navigation history
11957 pane.update_in(cx, |pane, window, cx| {
11958 pane.activate_item(1, true, true, window, cx);
11959 });
11960 cx.run_until_parked();
11961
11962 pane.update_in(cx, |pane, window, cx| {
11963 pane.activate_item(0, true, true, window, cx);
11964 });
11965 cx.run_until_parked();
11966
11967 // Simulate file deletion for item1
11968 item1.update(cx, |item, _| {
11969 item.set_has_deleted_file(true);
11970 });
11971
11972 // Emit UpdateTab event to trigger the close behavior
11973 item1.update(cx, |_, cx| {
11974 cx.emit(ItemEvent::UpdateTab);
11975 });
11976 cx.run_until_parked();
11977
11978 // Verify item1 was closed
11979 pane.read_with(cx, |pane, _| {
11980 assert_eq!(
11981 pane.items().count(),
11982 1,
11983 "Should have 1 item remaining after auto-close"
11984 );
11985 });
11986
11987 // Check navigation history after close
11988 let has_item = pane.read_with(cx, |pane, cx| {
11989 let mut has_item = false;
11990 pane.nav_history().for_each_entry(cx, |entry, _| {
11991 if entry.item.id() == item1_id {
11992 has_item = true;
11993 }
11994 });
11995 has_item
11996 });
11997
11998 assert!(
11999 !has_item,
12000 "Navigation history should not contain closed item entries"
12001 );
12002 }
12003
12004 #[gpui::test]
12005 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12006 cx: &mut TestAppContext,
12007 ) {
12008 init_test(cx);
12009
12010 let fs = FakeFs::new(cx.background_executor.clone());
12011 let project = Project::test(fs, [], cx).await;
12012 let (workspace, cx) =
12013 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12014 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12015
12016 let dirty_regular_buffer = cx.new(|cx| {
12017 TestItem::new(cx)
12018 .with_dirty(true)
12019 .with_label("1.txt")
12020 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12021 });
12022 let dirty_regular_buffer_2 = cx.new(|cx| {
12023 TestItem::new(cx)
12024 .with_dirty(true)
12025 .with_label("2.txt")
12026 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12027 });
12028 let clear_regular_buffer = cx.new(|cx| {
12029 TestItem::new(cx)
12030 .with_label("3.txt")
12031 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12032 });
12033
12034 let dirty_multi_buffer = cx.new(|cx| {
12035 TestItem::new(cx)
12036 .with_dirty(true)
12037 .with_buffer_kind(ItemBufferKind::Multibuffer)
12038 .with_label("Fake Project Search")
12039 .with_project_items(&[
12040 dirty_regular_buffer.read(cx).project_items[0].clone(),
12041 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12042 clear_regular_buffer.read(cx).project_items[0].clone(),
12043 ])
12044 });
12045 workspace.update_in(cx, |workspace, window, cx| {
12046 workspace.add_item(
12047 pane.clone(),
12048 Box::new(dirty_regular_buffer.clone()),
12049 None,
12050 false,
12051 false,
12052 window,
12053 cx,
12054 );
12055 workspace.add_item(
12056 pane.clone(),
12057 Box::new(dirty_regular_buffer_2.clone()),
12058 None,
12059 false,
12060 false,
12061 window,
12062 cx,
12063 );
12064 workspace.add_item(
12065 pane.clone(),
12066 Box::new(dirty_multi_buffer.clone()),
12067 None,
12068 false,
12069 false,
12070 window,
12071 cx,
12072 );
12073 });
12074
12075 pane.update_in(cx, |pane, window, cx| {
12076 pane.activate_item(2, true, true, window, cx);
12077 assert_eq!(
12078 pane.active_item().unwrap().item_id(),
12079 dirty_multi_buffer.item_id(),
12080 "Should select the multi buffer in the pane"
12081 );
12082 });
12083 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12084 pane.close_active_item(
12085 &CloseActiveItem {
12086 save_intent: None,
12087 close_pinned: false,
12088 },
12089 window,
12090 cx,
12091 )
12092 });
12093 cx.background_executor.run_until_parked();
12094 assert!(
12095 !cx.has_pending_prompt(),
12096 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12097 );
12098 close_multi_buffer_task
12099 .await
12100 .expect("Closing multi buffer failed");
12101 pane.update(cx, |pane, cx| {
12102 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12103 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12104 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12105 assert_eq!(
12106 pane.items()
12107 .map(|item| item.item_id())
12108 .sorted()
12109 .collect::<Vec<_>>(),
12110 vec![
12111 dirty_regular_buffer.item_id(),
12112 dirty_regular_buffer_2.item_id(),
12113 ],
12114 "Should have no multi buffer left in the pane"
12115 );
12116 assert!(dirty_regular_buffer.read(cx).is_dirty);
12117 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12118 });
12119 }
12120
12121 #[gpui::test]
12122 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12123 init_test(cx);
12124 let fs = FakeFs::new(cx.executor());
12125 let project = Project::test(fs, [], cx).await;
12126 let (workspace, cx) =
12127 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12128
12129 // Add a new panel to the right dock, opening the dock and setting the
12130 // focus to the new panel.
12131 let panel = workspace.update_in(cx, |workspace, window, cx| {
12132 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12133 workspace.add_panel(panel.clone(), window, cx);
12134
12135 workspace
12136 .right_dock()
12137 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12138
12139 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12140
12141 panel
12142 });
12143
12144 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12145 // panel to the next valid position which, in this case, is the left
12146 // dock.
12147 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12148 workspace.update(cx, |workspace, cx| {
12149 assert!(workspace.left_dock().read(cx).is_open());
12150 assert_eq!(panel.read(cx).position, DockPosition::Left);
12151 });
12152
12153 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12154 // panel to the next valid position which, in this case, is the bottom
12155 // dock.
12156 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12157 workspace.update(cx, |workspace, cx| {
12158 assert!(workspace.bottom_dock().read(cx).is_open());
12159 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12160 });
12161
12162 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12163 // around moving the panel to its initial position, the right dock.
12164 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12165 workspace.update(cx, |workspace, cx| {
12166 assert!(workspace.right_dock().read(cx).is_open());
12167 assert_eq!(panel.read(cx).position, DockPosition::Right);
12168 });
12169
12170 // Remove focus from the panel, ensuring that, if the panel is not
12171 // focused, the `MoveFocusedPanelToNextPosition` action does not update
12172 // the panel's position, so the panel is still in the right dock.
12173 workspace.update_in(cx, |workspace, window, cx| {
12174 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12175 });
12176
12177 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12178 workspace.update(cx, |workspace, cx| {
12179 assert!(workspace.right_dock().read(cx).is_open());
12180 assert_eq!(panel.read(cx).position, DockPosition::Right);
12181 });
12182 }
12183
12184 #[gpui::test]
12185 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12186 init_test(cx);
12187
12188 let fs = FakeFs::new(cx.executor());
12189 let project = Project::test(fs, [], cx).await;
12190 let (workspace, cx) =
12191 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12192
12193 let item_1 = cx.new(|cx| {
12194 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12195 });
12196 workspace.update_in(cx, |workspace, window, cx| {
12197 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12198 workspace.move_item_to_pane_in_direction(
12199 &MoveItemToPaneInDirection {
12200 direction: SplitDirection::Right,
12201 focus: true,
12202 clone: false,
12203 },
12204 window,
12205 cx,
12206 );
12207 workspace.move_item_to_pane_at_index(
12208 &MoveItemToPane {
12209 destination: 3,
12210 focus: true,
12211 clone: false,
12212 },
12213 window,
12214 cx,
12215 );
12216
12217 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12218 assert_eq!(
12219 pane_items_paths(&workspace.active_pane, cx),
12220 vec!["first.txt".to_string()],
12221 "Single item was not moved anywhere"
12222 );
12223 });
12224
12225 let item_2 = cx.new(|cx| {
12226 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12227 });
12228 workspace.update_in(cx, |workspace, window, cx| {
12229 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12230 assert_eq!(
12231 pane_items_paths(&workspace.panes[0], cx),
12232 vec!["first.txt".to_string(), "second.txt".to_string()],
12233 );
12234 workspace.move_item_to_pane_in_direction(
12235 &MoveItemToPaneInDirection {
12236 direction: SplitDirection::Right,
12237 focus: true,
12238 clone: false,
12239 },
12240 window,
12241 cx,
12242 );
12243
12244 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12245 assert_eq!(
12246 pane_items_paths(&workspace.panes[0], cx),
12247 vec!["first.txt".to_string()],
12248 "After moving, one item should be left in the original pane"
12249 );
12250 assert_eq!(
12251 pane_items_paths(&workspace.panes[1], cx),
12252 vec!["second.txt".to_string()],
12253 "New item should have been moved to the new pane"
12254 );
12255 });
12256
12257 let item_3 = cx.new(|cx| {
12258 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12259 });
12260 workspace.update_in(cx, |workspace, window, cx| {
12261 let original_pane = workspace.panes[0].clone();
12262 workspace.set_active_pane(&original_pane, window, cx);
12263 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12264 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12265 assert_eq!(
12266 pane_items_paths(&workspace.active_pane, cx),
12267 vec!["first.txt".to_string(), "third.txt".to_string()],
12268 "New pane should be ready to move one item out"
12269 );
12270
12271 workspace.move_item_to_pane_at_index(
12272 &MoveItemToPane {
12273 destination: 3,
12274 focus: true,
12275 clone: false,
12276 },
12277 window,
12278 cx,
12279 );
12280 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12281 assert_eq!(
12282 pane_items_paths(&workspace.active_pane, cx),
12283 vec!["first.txt".to_string()],
12284 "After moving, one item should be left in the original pane"
12285 );
12286 assert_eq!(
12287 pane_items_paths(&workspace.panes[1], cx),
12288 vec!["second.txt".to_string()],
12289 "Previously created pane should be unchanged"
12290 );
12291 assert_eq!(
12292 pane_items_paths(&workspace.panes[2], cx),
12293 vec!["third.txt".to_string()],
12294 "New item should have been moved to the new pane"
12295 );
12296 });
12297 }
12298
12299 #[gpui::test]
12300 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
12301 init_test(cx);
12302
12303 let fs = FakeFs::new(cx.executor());
12304 let project = Project::test(fs, [], cx).await;
12305 let (workspace, cx) =
12306 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12307
12308 let item_1 = cx.new(|cx| {
12309 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12310 });
12311 workspace.update_in(cx, |workspace, window, cx| {
12312 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12313 workspace.move_item_to_pane_in_direction(
12314 &MoveItemToPaneInDirection {
12315 direction: SplitDirection::Right,
12316 focus: true,
12317 clone: true,
12318 },
12319 window,
12320 cx,
12321 );
12322 });
12323 cx.run_until_parked();
12324 workspace.update_in(cx, |workspace, window, cx| {
12325 workspace.move_item_to_pane_at_index(
12326 &MoveItemToPane {
12327 destination: 3,
12328 focus: true,
12329 clone: true,
12330 },
12331 window,
12332 cx,
12333 );
12334 });
12335 cx.run_until_parked();
12336
12337 workspace.update(cx, |workspace, cx| {
12338 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
12339 for pane in workspace.panes() {
12340 assert_eq!(
12341 pane_items_paths(pane, cx),
12342 vec!["first.txt".to_string()],
12343 "Single item exists in all panes"
12344 );
12345 }
12346 });
12347
12348 // verify that the active pane has been updated after waiting for the
12349 // pane focus event to fire and resolve
12350 workspace.read_with(cx, |workspace, _app| {
12351 assert_eq!(
12352 workspace.active_pane(),
12353 &workspace.panes[2],
12354 "The third pane should be the active one: {:?}",
12355 workspace.panes
12356 );
12357 })
12358 }
12359
12360 #[gpui::test]
12361 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
12362 init_test(cx);
12363
12364 let fs = FakeFs::new(cx.executor());
12365 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
12366
12367 let project = Project::test(fs, ["root".as_ref()], cx).await;
12368 let (workspace, cx) =
12369 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12370
12371 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12372 // Add item to pane A with project path
12373 let item_a = cx.new(|cx| {
12374 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12375 });
12376 workspace.update_in(cx, |workspace, window, cx| {
12377 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
12378 });
12379
12380 // Split to create pane B
12381 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
12382 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
12383 });
12384
12385 // Add item with SAME project path to pane B, and pin it
12386 let item_b = cx.new(|cx| {
12387 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12388 });
12389 pane_b.update_in(cx, |pane, window, cx| {
12390 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
12391 pane.set_pinned_count(1);
12392 });
12393
12394 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
12395 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
12396
12397 // close_pinned: false should only close the unpinned copy
12398 workspace.update_in(cx, |workspace, window, cx| {
12399 workspace.close_item_in_all_panes(
12400 &CloseItemInAllPanes {
12401 save_intent: Some(SaveIntent::Close),
12402 close_pinned: false,
12403 },
12404 window,
12405 cx,
12406 )
12407 });
12408 cx.executor().run_until_parked();
12409
12410 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
12411 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
12412 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
12413 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
12414
12415 // Split again, seeing as closing the previous item also closed its
12416 // pane, so only pane remains, which does not allow us to properly test
12417 // that both items close when `close_pinned: true`.
12418 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
12419 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
12420 });
12421
12422 // Add an item with the same project path to pane C so that
12423 // close_item_in_all_panes can determine what to close across all panes
12424 // (it reads the active item from the active pane, and split_pane
12425 // creates an empty pane).
12426 let item_c = cx.new(|cx| {
12427 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12428 });
12429 pane_c.update_in(cx, |pane, window, cx| {
12430 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
12431 });
12432
12433 // close_pinned: true should close the pinned copy too
12434 workspace.update_in(cx, |workspace, window, cx| {
12435 let panes_count = workspace.panes().len();
12436 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
12437
12438 workspace.close_item_in_all_panes(
12439 &CloseItemInAllPanes {
12440 save_intent: Some(SaveIntent::Close),
12441 close_pinned: true,
12442 },
12443 window,
12444 cx,
12445 )
12446 });
12447 cx.executor().run_until_parked();
12448
12449 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
12450 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
12451 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
12452 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
12453 }
12454
12455 mod register_project_item_tests {
12456
12457 use super::*;
12458
12459 // View
12460 struct TestPngItemView {
12461 focus_handle: FocusHandle,
12462 }
12463 // Model
12464 struct TestPngItem {}
12465
12466 impl project::ProjectItem for TestPngItem {
12467 fn try_open(
12468 _project: &Entity<Project>,
12469 path: &ProjectPath,
12470 cx: &mut App,
12471 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
12472 if path.path.extension().unwrap() == "png" {
12473 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
12474 } else {
12475 None
12476 }
12477 }
12478
12479 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
12480 None
12481 }
12482
12483 fn project_path(&self, _: &App) -> Option<ProjectPath> {
12484 None
12485 }
12486
12487 fn is_dirty(&self) -> bool {
12488 false
12489 }
12490 }
12491
12492 impl Item for TestPngItemView {
12493 type Event = ();
12494 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12495 "".into()
12496 }
12497 }
12498 impl EventEmitter<()> for TestPngItemView {}
12499 impl Focusable for TestPngItemView {
12500 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12501 self.focus_handle.clone()
12502 }
12503 }
12504
12505 impl Render for TestPngItemView {
12506 fn render(
12507 &mut self,
12508 _window: &mut Window,
12509 _cx: &mut Context<Self>,
12510 ) -> impl IntoElement {
12511 Empty
12512 }
12513 }
12514
12515 impl ProjectItem for TestPngItemView {
12516 type Item = TestPngItem;
12517
12518 fn for_project_item(
12519 _project: Entity<Project>,
12520 _pane: Option<&Pane>,
12521 _item: Entity<Self::Item>,
12522 _: &mut Window,
12523 cx: &mut Context<Self>,
12524 ) -> Self
12525 where
12526 Self: Sized,
12527 {
12528 Self {
12529 focus_handle: cx.focus_handle(),
12530 }
12531 }
12532 }
12533
12534 // View
12535 struct TestIpynbItemView {
12536 focus_handle: FocusHandle,
12537 }
12538 // Model
12539 struct TestIpynbItem {}
12540
12541 impl project::ProjectItem for TestIpynbItem {
12542 fn try_open(
12543 _project: &Entity<Project>,
12544 path: &ProjectPath,
12545 cx: &mut App,
12546 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
12547 if path.path.extension().unwrap() == "ipynb" {
12548 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
12549 } else {
12550 None
12551 }
12552 }
12553
12554 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
12555 None
12556 }
12557
12558 fn project_path(&self, _: &App) -> Option<ProjectPath> {
12559 None
12560 }
12561
12562 fn is_dirty(&self) -> bool {
12563 false
12564 }
12565 }
12566
12567 impl Item for TestIpynbItemView {
12568 type Event = ();
12569 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12570 "".into()
12571 }
12572 }
12573 impl EventEmitter<()> for TestIpynbItemView {}
12574 impl Focusable for TestIpynbItemView {
12575 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12576 self.focus_handle.clone()
12577 }
12578 }
12579
12580 impl Render for TestIpynbItemView {
12581 fn render(
12582 &mut self,
12583 _window: &mut Window,
12584 _cx: &mut Context<Self>,
12585 ) -> impl IntoElement {
12586 Empty
12587 }
12588 }
12589
12590 impl ProjectItem for TestIpynbItemView {
12591 type Item = TestIpynbItem;
12592
12593 fn for_project_item(
12594 _project: Entity<Project>,
12595 _pane: Option<&Pane>,
12596 _item: Entity<Self::Item>,
12597 _: &mut Window,
12598 cx: &mut Context<Self>,
12599 ) -> Self
12600 where
12601 Self: Sized,
12602 {
12603 Self {
12604 focus_handle: cx.focus_handle(),
12605 }
12606 }
12607 }
12608
12609 struct TestAlternatePngItemView {
12610 focus_handle: FocusHandle,
12611 }
12612
12613 impl Item for TestAlternatePngItemView {
12614 type Event = ();
12615 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12616 "".into()
12617 }
12618 }
12619
12620 impl EventEmitter<()> for TestAlternatePngItemView {}
12621 impl Focusable for TestAlternatePngItemView {
12622 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12623 self.focus_handle.clone()
12624 }
12625 }
12626
12627 impl Render for TestAlternatePngItemView {
12628 fn render(
12629 &mut self,
12630 _window: &mut Window,
12631 _cx: &mut Context<Self>,
12632 ) -> impl IntoElement {
12633 Empty
12634 }
12635 }
12636
12637 impl ProjectItem for TestAlternatePngItemView {
12638 type Item = TestPngItem;
12639
12640 fn for_project_item(
12641 _project: Entity<Project>,
12642 _pane: Option<&Pane>,
12643 _item: Entity<Self::Item>,
12644 _: &mut Window,
12645 cx: &mut Context<Self>,
12646 ) -> Self
12647 where
12648 Self: Sized,
12649 {
12650 Self {
12651 focus_handle: cx.focus_handle(),
12652 }
12653 }
12654 }
12655
12656 #[gpui::test]
12657 async fn test_register_project_item(cx: &mut TestAppContext) {
12658 init_test(cx);
12659
12660 cx.update(|cx| {
12661 register_project_item::<TestPngItemView>(cx);
12662 register_project_item::<TestIpynbItemView>(cx);
12663 });
12664
12665 let fs = FakeFs::new(cx.executor());
12666 fs.insert_tree(
12667 "/root1",
12668 json!({
12669 "one.png": "BINARYDATAHERE",
12670 "two.ipynb": "{ totally a notebook }",
12671 "three.txt": "editing text, sure why not?"
12672 }),
12673 )
12674 .await;
12675
12676 let project = Project::test(fs, ["root1".as_ref()], cx).await;
12677 let (workspace, cx) =
12678 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12679
12680 let worktree_id = project.update(cx, |project, cx| {
12681 project.worktrees(cx).next().unwrap().read(cx).id()
12682 });
12683
12684 let handle = workspace
12685 .update_in(cx, |workspace, window, cx| {
12686 let project_path = (worktree_id, rel_path("one.png"));
12687 workspace.open_path(project_path, None, true, window, cx)
12688 })
12689 .await
12690 .unwrap();
12691
12692 // Now we can check if the handle we got back errored or not
12693 assert_eq!(
12694 handle.to_any_view().entity_type(),
12695 TypeId::of::<TestPngItemView>()
12696 );
12697
12698 let handle = workspace
12699 .update_in(cx, |workspace, window, cx| {
12700 let project_path = (worktree_id, rel_path("two.ipynb"));
12701 workspace.open_path(project_path, None, true, window, cx)
12702 })
12703 .await
12704 .unwrap();
12705
12706 assert_eq!(
12707 handle.to_any_view().entity_type(),
12708 TypeId::of::<TestIpynbItemView>()
12709 );
12710
12711 let handle = workspace
12712 .update_in(cx, |workspace, window, cx| {
12713 let project_path = (worktree_id, rel_path("three.txt"));
12714 workspace.open_path(project_path, None, true, window, cx)
12715 })
12716 .await;
12717 assert!(handle.is_err());
12718 }
12719
12720 #[gpui::test]
12721 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
12722 init_test(cx);
12723
12724 cx.update(|cx| {
12725 register_project_item::<TestPngItemView>(cx);
12726 register_project_item::<TestAlternatePngItemView>(cx);
12727 });
12728
12729 let fs = FakeFs::new(cx.executor());
12730 fs.insert_tree(
12731 "/root1",
12732 json!({
12733 "one.png": "BINARYDATAHERE",
12734 "two.ipynb": "{ totally a notebook }",
12735 "three.txt": "editing text, sure why not?"
12736 }),
12737 )
12738 .await;
12739 let project = Project::test(fs, ["root1".as_ref()], cx).await;
12740 let (workspace, cx) =
12741 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12742 let worktree_id = project.update(cx, |project, cx| {
12743 project.worktrees(cx).next().unwrap().read(cx).id()
12744 });
12745
12746 let handle = workspace
12747 .update_in(cx, |workspace, window, cx| {
12748 let project_path = (worktree_id, rel_path("one.png"));
12749 workspace.open_path(project_path, None, true, window, cx)
12750 })
12751 .await
12752 .unwrap();
12753
12754 // This _must_ be the second item registered
12755 assert_eq!(
12756 handle.to_any_view().entity_type(),
12757 TypeId::of::<TestAlternatePngItemView>()
12758 );
12759
12760 let handle = workspace
12761 .update_in(cx, |workspace, window, cx| {
12762 let project_path = (worktree_id, rel_path("three.txt"));
12763 workspace.open_path(project_path, None, true, window, cx)
12764 })
12765 .await;
12766 assert!(handle.is_err());
12767 }
12768 }
12769
12770 #[gpui::test]
12771 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
12772 init_test(cx);
12773
12774 let fs = FakeFs::new(cx.executor());
12775 let project = Project::test(fs, [], cx).await;
12776 let (workspace, _cx) =
12777 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12778
12779 // Test with status bar shown (default)
12780 workspace.read_with(cx, |workspace, cx| {
12781 let visible = workspace.status_bar_visible(cx);
12782 assert!(visible, "Status bar should be visible by default");
12783 });
12784
12785 // Test with status bar hidden
12786 cx.update_global(|store: &mut SettingsStore, cx| {
12787 store.update_user_settings(cx, |settings| {
12788 settings.status_bar.get_or_insert_default().show = Some(false);
12789 });
12790 });
12791
12792 workspace.read_with(cx, |workspace, cx| {
12793 let visible = workspace.status_bar_visible(cx);
12794 assert!(!visible, "Status bar should be hidden when show is false");
12795 });
12796
12797 // Test with status bar shown explicitly
12798 cx.update_global(|store: &mut SettingsStore, cx| {
12799 store.update_user_settings(cx, |settings| {
12800 settings.status_bar.get_or_insert_default().show = Some(true);
12801 });
12802 });
12803
12804 workspace.read_with(cx, |workspace, cx| {
12805 let visible = workspace.status_bar_visible(cx);
12806 assert!(visible, "Status bar should be visible when show is true");
12807 });
12808 }
12809
12810 #[gpui::test]
12811 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
12812 init_test(cx);
12813
12814 let fs = FakeFs::new(cx.executor());
12815 let project = Project::test(fs, [], cx).await;
12816 let (workspace, cx) =
12817 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12818 let panel = workspace.update_in(cx, |workspace, window, cx| {
12819 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12820 workspace.add_panel(panel.clone(), window, cx);
12821
12822 workspace
12823 .right_dock()
12824 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12825
12826 panel
12827 });
12828
12829 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12830 let item_a = cx.new(TestItem::new);
12831 let item_b = cx.new(TestItem::new);
12832 let item_a_id = item_a.entity_id();
12833 let item_b_id = item_b.entity_id();
12834
12835 pane.update_in(cx, |pane, window, cx| {
12836 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
12837 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
12838 });
12839
12840 pane.read_with(cx, |pane, _| {
12841 assert_eq!(pane.items_len(), 2);
12842 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
12843 });
12844
12845 workspace.update_in(cx, |workspace, window, cx| {
12846 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12847 });
12848
12849 workspace.update_in(cx, |_, window, cx| {
12850 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12851 });
12852
12853 // Assert that the `pane::CloseActiveItem` action is handled at the
12854 // workspace level when one of the dock panels is focused and, in that
12855 // case, the center pane's active item is closed but the focus is not
12856 // moved.
12857 cx.dispatch_action(pane::CloseActiveItem::default());
12858 cx.run_until_parked();
12859
12860 pane.read_with(cx, |pane, _| {
12861 assert_eq!(pane.items_len(), 1);
12862 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
12863 });
12864
12865 workspace.update_in(cx, |workspace, window, cx| {
12866 assert!(workspace.right_dock().read(cx).is_open());
12867 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12868 });
12869 }
12870
12871 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
12872 pane.read(cx)
12873 .items()
12874 .flat_map(|item| {
12875 item.project_paths(cx)
12876 .into_iter()
12877 .map(|path| path.path.display(PathStyle::local()).into_owned())
12878 })
12879 .collect()
12880 }
12881
12882 pub fn init_test(cx: &mut TestAppContext) {
12883 cx.update(|cx| {
12884 let settings_store = SettingsStore::test(cx);
12885 cx.set_global(settings_store);
12886 theme::init(theme::LoadThemes::JustBase, cx);
12887 });
12888 }
12889
12890 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
12891 let item = TestProjectItem::new(id, path, cx);
12892 item.update(cx, |item, _| {
12893 item.is_dirty = true;
12894 });
12895 item
12896 }
12897}