1pub mod dock;
2pub mod history_manager;
3pub mod invalid_item_view;
4pub mod item;
5mod modal_layer;
6mod multi_workspace;
7pub mod notifications;
8pub mod pane;
9pub mod pane_group;
10mod path_list;
11mod persistence;
12pub mod searchable;
13mod security_modal;
14pub mod shared_screen;
15mod status_bar;
16pub mod tasks;
17mod theme_preview;
18mod toast_layer;
19mod toolbar;
20pub mod welcome;
21mod workspace_settings;
22
23pub use crate::notifications::NotificationFrame;
24pub use dock::Panel;
25pub use multi_workspace::{
26 DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace, NewWorkspaceInWindow,
27 NextWorkspaceInWindow, PreviousWorkspaceInWindow, Sidebar, SidebarEvent, SidebarHandle,
28 ToggleWorkspaceSidebar,
29};
30pub use path_list::PathList;
31pub use toast_layer::{ToastAction, ToastLayer, ToastView};
32
33use anyhow::{Context as _, Result, anyhow};
34use call::{ActiveCall, call_settings::CallSettings};
35use client::{
36 ChannelId, Client, ErrorExt, Status, TypedEnvelope, UserStore,
37 proto::{self, ErrorCode, PanelId, PeerId},
38};
39use collections::{HashMap, HashSet, hash_map};
40use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
41use futures::{
42 Future, FutureExt, StreamExt,
43 channel::{
44 mpsc::{self, UnboundedReceiver, UnboundedSender},
45 oneshot,
46 },
47 future::{Shared, try_join_all},
48};
49use gpui::{
50 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
51 CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
52 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
53 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
54 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
55 WindowOptions, actions, canvas, point, relative, size, transparent_black,
56};
57pub use history_manager::*;
58pub use item::{
59 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
60 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
61};
62use itertools::Itertools;
63use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
64pub use modal_layer::*;
65use node_runtime::NodeRuntime;
66use notifications::{
67 DetachAndPromptErr, Notifications, dismiss_app_notification,
68 simple_message_notification::MessageNotification,
69};
70pub use pane::*;
71pub use pane_group::{
72 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
73 SplitDirection,
74};
75use persistence::{DB, SerializedWindowBounds, model::SerializedWorkspace};
76pub use persistence::{
77 DB as WORKSPACE_DB, WorkspaceDb, delete_unloaded_items,
78 model::{ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation, SessionWorkspace},
79 read_serialized_multi_workspaces,
80};
81use postage::stream::Stream;
82use project::{
83 DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
84 WorktreeSettings,
85 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
86 project_settings::ProjectSettings,
87 toolchain_store::ToolchainStoreEvent,
88 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
89};
90use remote::{
91 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
92 remote_client::ConnectionIdentifier,
93};
94use schemars::JsonSchema;
95use serde::Deserialize;
96use session::AppSession;
97use settings::{
98 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
99};
100use shared_screen::SharedScreen;
101use sqlez::{
102 bindable::{Bind, Column, StaticColumnCount},
103 statement::Statement,
104};
105use status_bar::StatusBar;
106pub use status_bar::StatusItemView;
107use std::{
108 any::TypeId,
109 borrow::Cow,
110 cell::RefCell,
111 cmp,
112 collections::VecDeque,
113 env,
114 hash::Hash,
115 path::{Path, PathBuf},
116 process::ExitStatus,
117 rc::Rc,
118 sync::{
119 Arc, LazyLock, Weak,
120 atomic::{AtomicBool, AtomicUsize},
121 },
122 time::Duration,
123};
124use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
125use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
126pub use toolbar::{
127 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
128};
129pub use ui;
130use ui::{Window, prelude::*};
131use util::{
132 ResultExt, TryFutureExt,
133 paths::{PathStyle, SanitizedPath},
134 rel_path::RelPath,
135 serde::default_true,
136};
137use uuid::Uuid;
138pub use workspace_settings::{
139 AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
140 WorkspaceSettings,
141};
142use zed_actions::{Spawn, feedback::FileBugReport};
143
144use crate::{item::ItemBufferKind, notifications::NotificationId};
145use crate::{
146 persistence::{
147 SerializedAxis,
148 model::{DockData, DockStructure, SerializedItem, SerializedPane, SerializedPaneGroup},
149 },
150 security_modal::SecurityModal,
151};
152
153pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
154
155static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
156 env::var("ZED_WINDOW_SIZE")
157 .ok()
158 .as_deref()
159 .and_then(parse_pixel_size_env_var)
160});
161
162static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
163 env::var("ZED_WINDOW_POSITION")
164 .ok()
165 .as_deref()
166 .and_then(parse_pixel_position_env_var)
167});
168
169pub trait TerminalProvider {
170 fn spawn(
171 &self,
172 task: SpawnInTerminal,
173 window: &mut Window,
174 cx: &mut App,
175 ) -> Task<Option<Result<ExitStatus>>>;
176}
177
178pub trait DebuggerProvider {
179 // `active_buffer` is used to resolve build task's name against language-specific tasks.
180 fn start_session(
181 &self,
182 definition: DebugScenario,
183 task_context: SharedTaskContext,
184 active_buffer: Option<Entity<Buffer>>,
185 worktree_id: Option<WorktreeId>,
186 window: &mut Window,
187 cx: &mut App,
188 );
189
190 fn spawn_task_or_modal(
191 &self,
192 workspace: &mut Workspace,
193 action: &Spawn,
194 window: &mut Window,
195 cx: &mut Context<Workspace>,
196 );
197
198 fn task_scheduled(&self, cx: &mut App);
199 fn debug_scenario_scheduled(&self, cx: &mut App);
200 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
201
202 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
203}
204
205actions!(
206 workspace,
207 [
208 /// Activates the next pane in the workspace.
209 ActivateNextPane,
210 /// Activates the previous pane in the workspace.
211 ActivatePreviousPane,
212 /// Switches to the next window.
213 ActivateNextWindow,
214 /// Switches to the previous window.
215 ActivatePreviousWindow,
216 /// Adds a folder to the current project.
217 AddFolderToProject,
218 /// Clears all notifications.
219 ClearAllNotifications,
220 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
221 ClearNavigationHistory,
222 /// Closes the active dock.
223 CloseActiveDock,
224 /// Closes all docks.
225 CloseAllDocks,
226 /// Toggles all docks.
227 ToggleAllDocks,
228 /// Closes the current window.
229 CloseWindow,
230 /// Closes the current project.
231 CloseProject,
232 /// Opens the feedback dialog.
233 Feedback,
234 /// Follows the next collaborator in the session.
235 FollowNextCollaborator,
236 /// Moves the focused panel to the next position.
237 MoveFocusedPanelToNextPosition,
238 /// Creates a new file.
239 NewFile,
240 /// Creates a new file in a vertical split.
241 NewFileSplitVertical,
242 /// Creates a new file in a horizontal split.
243 NewFileSplitHorizontal,
244 /// Opens a new search.
245 NewSearch,
246 /// Opens a new window.
247 NewWindow,
248 /// Opens a file or directory.
249 Open,
250 /// Opens multiple files.
251 OpenFiles,
252 /// Opens the current location in terminal.
253 OpenInTerminal,
254 /// Opens the component preview.
255 OpenComponentPreview,
256 /// Reloads the active item.
257 ReloadActiveItem,
258 /// Resets the active dock to its default size.
259 ResetActiveDockSize,
260 /// Resets all open docks to their default sizes.
261 ResetOpenDocksSize,
262 /// Reloads the application
263 Reload,
264 /// Saves the current file with a new name.
265 SaveAs,
266 /// Saves without formatting.
267 SaveWithoutFormat,
268 /// Shuts down all debug adapters.
269 ShutdownDebugAdapters,
270 /// Suppresses the current notification.
271 SuppressNotification,
272 /// Toggles the bottom dock.
273 ToggleBottomDock,
274 /// Toggles centered layout mode.
275 ToggleCenteredLayout,
276 /// Toggles edit prediction feature globally for all files.
277 ToggleEditPrediction,
278 /// Toggles the left dock.
279 ToggleLeftDock,
280 /// Toggles the right dock.
281 ToggleRightDock,
282 /// Toggles zoom on the active pane.
283 ToggleZoom,
284 /// Toggles read-only mode for the active item (if supported by that item).
285 ToggleReadOnlyFile,
286 /// Zooms in on the active pane.
287 ZoomIn,
288 /// Zooms out of the active pane.
289 ZoomOut,
290 /// If any worktrees are in restricted mode, shows a modal with possible actions.
291 /// If the modal is shown already, closes it without trusting any worktree.
292 ToggleWorktreeSecurity,
293 /// Clears all trusted worktrees, placing them in restricted mode on next open.
294 /// Requires restart to take effect on already opened projects.
295 ClearTrustedWorktrees,
296 /// Stops following a collaborator.
297 Unfollow,
298 /// Restores the banner.
299 RestoreBanner,
300 /// Toggles expansion of the selected item.
301 ToggleExpandItem,
302 ]
303);
304
305/// Activates a specific pane by its index.
306#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
307#[action(namespace = workspace)]
308pub struct ActivatePane(pub usize);
309
310/// Moves an item to a specific pane by index.
311#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
312#[action(namespace = workspace)]
313#[serde(deny_unknown_fields)]
314pub struct MoveItemToPane {
315 #[serde(default = "default_1")]
316 pub destination: usize,
317 #[serde(default = "default_true")]
318 pub focus: bool,
319 #[serde(default)]
320 pub clone: bool,
321}
322
323fn default_1() -> usize {
324 1
325}
326
327/// Moves an item to a pane in the specified direction.
328#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
329#[action(namespace = workspace)]
330#[serde(deny_unknown_fields)]
331pub struct MoveItemToPaneInDirection {
332 #[serde(default = "default_right")]
333 pub direction: SplitDirection,
334 #[serde(default = "default_true")]
335 pub focus: bool,
336 #[serde(default)]
337 pub clone: bool,
338}
339
340/// Creates a new file in a split of the desired direction.
341#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
342#[action(namespace = workspace)]
343#[serde(deny_unknown_fields)]
344pub struct NewFileSplit(pub SplitDirection);
345
346fn default_right() -> SplitDirection {
347 SplitDirection::Right
348}
349
350/// Saves all open files in the workspace.
351#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
352#[action(namespace = workspace)]
353#[serde(deny_unknown_fields)]
354pub struct SaveAll {
355 #[serde(default)]
356 pub save_intent: Option<SaveIntent>,
357}
358
359/// Saves the current file with the specified options.
360#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
361#[action(namespace = workspace)]
362#[serde(deny_unknown_fields)]
363pub struct Save {
364 #[serde(default)]
365 pub save_intent: Option<SaveIntent>,
366}
367
368/// Closes all items and panes in the workspace.
369#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
370#[action(namespace = workspace)]
371#[serde(deny_unknown_fields)]
372pub struct CloseAllItemsAndPanes {
373 #[serde(default)]
374 pub save_intent: Option<SaveIntent>,
375}
376
377/// Closes all inactive tabs and panes in the workspace.
378#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
379#[action(namespace = workspace)]
380#[serde(deny_unknown_fields)]
381pub struct CloseInactiveTabsAndPanes {
382 #[serde(default)]
383 pub save_intent: Option<SaveIntent>,
384}
385
386/// Closes the active item across all panes.
387#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
388#[action(namespace = workspace)]
389#[serde(deny_unknown_fields)]
390pub struct CloseItemInAllPanes {
391 #[serde(default)]
392 pub save_intent: Option<SaveIntent>,
393 #[serde(default)]
394 pub close_pinned: bool,
395}
396
397/// Sends a sequence of keystrokes to the active element.
398#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
399#[action(namespace = workspace)]
400pub struct SendKeystrokes(pub String);
401
402actions!(
403 project_symbols,
404 [
405 /// Toggles the project symbols search.
406 #[action(name = "Toggle")]
407 ToggleProjectSymbols
408 ]
409);
410
411/// Toggles the file finder interface.
412#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
413#[action(namespace = file_finder, name = "Toggle")]
414#[serde(deny_unknown_fields)]
415pub struct ToggleFileFinder {
416 #[serde(default)]
417 pub separate_history: bool,
418}
419
420/// Opens a new terminal in the center.
421#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
422#[action(namespace = workspace)]
423#[serde(deny_unknown_fields)]
424pub struct NewCenterTerminal {
425 /// If true, creates a local terminal even in remote projects.
426 #[serde(default)]
427 pub local: bool,
428}
429
430/// Opens a new terminal.
431#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
432#[action(namespace = workspace)]
433#[serde(deny_unknown_fields)]
434pub struct NewTerminal {
435 /// If true, creates a local terminal even in remote projects.
436 #[serde(default)]
437 pub local: bool,
438}
439
440/// Increases size of a currently focused dock by a given amount of pixels.
441#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
442#[action(namespace = workspace)]
443#[serde(deny_unknown_fields)]
444pub struct IncreaseActiveDockSize {
445 /// For 0px parameter, uses UI font size value.
446 #[serde(default)]
447 pub px: u32,
448}
449
450/// Decreases size of a currently focused dock by a given amount of pixels.
451#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
452#[action(namespace = workspace)]
453#[serde(deny_unknown_fields)]
454pub struct DecreaseActiveDockSize {
455 /// For 0px parameter, uses UI font size value.
456 #[serde(default)]
457 pub px: u32,
458}
459
460/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
461#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
462#[action(namespace = workspace)]
463#[serde(deny_unknown_fields)]
464pub struct IncreaseOpenDocksSize {
465 /// For 0px parameter, uses UI font size value.
466 #[serde(default)]
467 pub px: u32,
468}
469
470/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
471#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
472#[action(namespace = workspace)]
473#[serde(deny_unknown_fields)]
474pub struct DecreaseOpenDocksSize {
475 /// For 0px parameter, uses UI font size value.
476 #[serde(default)]
477 pub px: u32,
478}
479
480actions!(
481 workspace,
482 [
483 /// Activates the pane to the left.
484 ActivatePaneLeft,
485 /// Activates the pane to the right.
486 ActivatePaneRight,
487 /// Activates the pane above.
488 ActivatePaneUp,
489 /// Activates the pane below.
490 ActivatePaneDown,
491 /// Swaps the current pane with the one to the left.
492 SwapPaneLeft,
493 /// Swaps the current pane with the one to the right.
494 SwapPaneRight,
495 /// Swaps the current pane with the one above.
496 SwapPaneUp,
497 /// Swaps the current pane with the one below.
498 SwapPaneDown,
499 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
500 SwapPaneAdjacent,
501 /// Move the current pane to be at the far left.
502 MovePaneLeft,
503 /// Move the current pane to be at the far right.
504 MovePaneRight,
505 /// Move the current pane to be at the very top.
506 MovePaneUp,
507 /// Move the current pane to be at the very bottom.
508 MovePaneDown,
509 ]
510);
511
512#[derive(PartialEq, Eq, Debug)]
513pub enum CloseIntent {
514 /// Quit the program entirely.
515 Quit,
516 /// Close a window.
517 CloseWindow,
518 /// Replace the workspace in an existing window.
519 ReplaceWindow,
520}
521
522#[derive(Clone)]
523pub struct Toast {
524 id: NotificationId,
525 msg: Cow<'static, str>,
526 autohide: bool,
527 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
528}
529
530impl Toast {
531 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
532 Toast {
533 id,
534 msg: msg.into(),
535 on_click: None,
536 autohide: false,
537 }
538 }
539
540 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
541 where
542 M: Into<Cow<'static, str>>,
543 F: Fn(&mut Window, &mut App) + 'static,
544 {
545 self.on_click = Some((message.into(), Arc::new(on_click)));
546 self
547 }
548
549 pub fn autohide(mut self) -> Self {
550 self.autohide = true;
551 self
552 }
553}
554
555impl PartialEq for Toast {
556 fn eq(&self, other: &Self) -> bool {
557 self.id == other.id
558 && self.msg == other.msg
559 && self.on_click.is_some() == other.on_click.is_some()
560 }
561}
562
563/// Opens a new terminal with the specified working directory.
564#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
565#[action(namespace = workspace)]
566#[serde(deny_unknown_fields)]
567pub struct OpenTerminal {
568 pub working_directory: PathBuf,
569 /// If true, creates a local terminal even in remote projects.
570 #[serde(default)]
571 pub local: bool,
572}
573
574#[derive(
575 Clone,
576 Copy,
577 Debug,
578 Default,
579 Hash,
580 PartialEq,
581 Eq,
582 PartialOrd,
583 Ord,
584 serde::Serialize,
585 serde::Deserialize,
586)]
587pub struct WorkspaceId(i64);
588
589impl WorkspaceId {
590 pub fn from_i64(value: i64) -> Self {
591 Self(value)
592 }
593}
594
595impl StaticColumnCount for WorkspaceId {}
596impl Bind for WorkspaceId {
597 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
598 self.0.bind(statement, start_index)
599 }
600}
601impl Column for WorkspaceId {
602 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
603 i64::column(statement, start_index)
604 .map(|(i, next_index)| (Self(i), next_index))
605 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
606 }
607}
608impl From<WorkspaceId> for i64 {
609 fn from(val: WorkspaceId) -> Self {
610 val.0
611 }
612}
613
614fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
615 let paths = cx.prompt_for_paths(options);
616 cx.spawn(
617 async move |cx| match paths.await.anyhow().and_then(|res| res) {
618 Ok(Some(paths)) => {
619 cx.update(|cx| {
620 open_paths(&paths, app_state, OpenOptions::default(), cx).detach_and_log_err(cx)
621 });
622 }
623 Ok(None) => {}
624 Err(err) => {
625 util::log_err(&err);
626 cx.update(|cx| {
627 if let Some(workspace_window) = cx
628 .active_window()
629 .and_then(|window| window.downcast::<MultiWorkspace>())
630 {
631 workspace_window
632 .update(cx, |multi_workspace, _, cx| {
633 let workspace = multi_workspace.workspace().clone();
634 workspace.update(cx, |workspace, cx| {
635 workspace.show_portal_error(err.to_string(), cx);
636 });
637 })
638 .ok();
639 }
640 });
641 }
642 },
643 )
644 .detach();
645}
646
647pub fn init(app_state: Arc<AppState>, cx: &mut App) {
648 component::init();
649 theme_preview::init(cx);
650 toast_layer::init(cx);
651 history_manager::init(app_state.fs.clone(), cx);
652
653 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
654 .on_action(|_: &Reload, cx| reload(cx))
655 .on_action({
656 let app_state = Arc::downgrade(&app_state);
657 move |_: &Open, cx: &mut App| {
658 if let Some(app_state) = app_state.upgrade() {
659 prompt_and_open_paths(
660 app_state,
661 PathPromptOptions {
662 files: true,
663 directories: true,
664 multiple: true,
665 prompt: None,
666 },
667 cx,
668 );
669 }
670 }
671 })
672 .on_action({
673 let app_state = Arc::downgrade(&app_state);
674 move |_: &OpenFiles, cx: &mut App| {
675 let directories = cx.can_select_mixed_files_and_dirs();
676 if let Some(app_state) = app_state.upgrade() {
677 prompt_and_open_paths(
678 app_state,
679 PathPromptOptions {
680 files: true,
681 directories,
682 multiple: true,
683 prompt: None,
684 },
685 cx,
686 );
687 }
688 }
689 });
690}
691
692type BuildProjectItemFn =
693 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
694
695type BuildProjectItemForPathFn =
696 fn(
697 &Entity<Project>,
698 &ProjectPath,
699 &mut Window,
700 &mut App,
701 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
702
703#[derive(Clone, Default)]
704struct ProjectItemRegistry {
705 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
706 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
707}
708
709impl ProjectItemRegistry {
710 fn register<T: ProjectItem>(&mut self) {
711 self.build_project_item_fns_by_type.insert(
712 TypeId::of::<T::Item>(),
713 |item, project, pane, window, cx| {
714 let item = item.downcast().unwrap();
715 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
716 as Box<dyn ItemHandle>
717 },
718 );
719 self.build_project_item_for_path_fns
720 .push(|project, project_path, window, cx| {
721 let project_path = project_path.clone();
722 let is_file = project
723 .read(cx)
724 .entry_for_path(&project_path, cx)
725 .is_some_and(|entry| entry.is_file());
726 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
727 let is_local = project.read(cx).is_local();
728 let project_item =
729 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
730 let project = project.clone();
731 Some(window.spawn(cx, async move |cx| {
732 match project_item.await.with_context(|| {
733 format!(
734 "opening project path {:?}",
735 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
736 )
737 }) {
738 Ok(project_item) => {
739 let project_item = project_item;
740 let project_entry_id: Option<ProjectEntryId> =
741 project_item.read_with(cx, project::ProjectItem::entry_id);
742 let build_workspace_item = Box::new(
743 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
744 Box::new(cx.new(|cx| {
745 T::for_project_item(
746 project,
747 Some(pane),
748 project_item,
749 window,
750 cx,
751 )
752 })) as Box<dyn ItemHandle>
753 },
754 ) as Box<_>;
755 Ok((project_entry_id, build_workspace_item))
756 }
757 Err(e) => {
758 log::warn!("Failed to open a project item: {e:#}");
759 if e.error_code() == ErrorCode::Internal {
760 if let Some(abs_path) =
761 entry_abs_path.as_deref().filter(|_| is_file)
762 {
763 if let Some(broken_project_item_view) =
764 cx.update(|window, cx| {
765 T::for_broken_project_item(
766 abs_path, is_local, &e, window, cx,
767 )
768 })?
769 {
770 let build_workspace_item = Box::new(
771 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
772 cx.new(|_| broken_project_item_view).boxed_clone()
773 },
774 )
775 as Box<_>;
776 return Ok((None, build_workspace_item));
777 }
778 }
779 }
780 Err(e)
781 }
782 }
783 }))
784 });
785 }
786
787 fn open_path(
788 &self,
789 project: &Entity<Project>,
790 path: &ProjectPath,
791 window: &mut Window,
792 cx: &mut App,
793 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
794 let Some(open_project_item) = self
795 .build_project_item_for_path_fns
796 .iter()
797 .rev()
798 .find_map(|open_project_item| open_project_item(project, path, window, cx))
799 else {
800 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
801 };
802 open_project_item
803 }
804
805 fn build_item<T: project::ProjectItem>(
806 &self,
807 item: Entity<T>,
808 project: Entity<Project>,
809 pane: Option<&Pane>,
810 window: &mut Window,
811 cx: &mut App,
812 ) -> Option<Box<dyn ItemHandle>> {
813 let build = self
814 .build_project_item_fns_by_type
815 .get(&TypeId::of::<T>())?;
816 Some(build(item.into_any(), project, pane, window, cx))
817 }
818}
819
820type WorkspaceItemBuilder =
821 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
822
823impl Global for ProjectItemRegistry {}
824
825/// Registers a [ProjectItem] for the app. When opening a file, all the registered
826/// items will get a chance to open the file, starting from the project item that
827/// was added last.
828pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
829 cx.default_global::<ProjectItemRegistry>().register::<I>();
830}
831
832#[derive(Default)]
833pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
834
835struct FollowableViewDescriptor {
836 from_state_proto: fn(
837 Entity<Workspace>,
838 ViewId,
839 &mut Option<proto::view::Variant>,
840 &mut Window,
841 &mut App,
842 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
843 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
844}
845
846impl Global for FollowableViewRegistry {}
847
848impl FollowableViewRegistry {
849 pub fn register<I: FollowableItem>(cx: &mut App) {
850 cx.default_global::<Self>().0.insert(
851 TypeId::of::<I>(),
852 FollowableViewDescriptor {
853 from_state_proto: |workspace, id, state, window, cx| {
854 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
855 cx.foreground_executor()
856 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
857 })
858 },
859 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
860 },
861 );
862 }
863
864 pub fn from_state_proto(
865 workspace: Entity<Workspace>,
866 view_id: ViewId,
867 mut state: Option<proto::view::Variant>,
868 window: &mut Window,
869 cx: &mut App,
870 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
871 cx.update_default_global(|this: &mut Self, cx| {
872 this.0.values().find_map(|descriptor| {
873 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
874 })
875 })
876 }
877
878 pub fn to_followable_view(
879 view: impl Into<AnyView>,
880 cx: &App,
881 ) -> Option<Box<dyn FollowableItemHandle>> {
882 let this = cx.try_global::<Self>()?;
883 let view = view.into();
884 let descriptor = this.0.get(&view.entity_type())?;
885 Some((descriptor.to_followable_view)(&view))
886 }
887}
888
889#[derive(Copy, Clone)]
890struct SerializableItemDescriptor {
891 deserialize: fn(
892 Entity<Project>,
893 WeakEntity<Workspace>,
894 WorkspaceId,
895 ItemId,
896 &mut Window,
897 &mut Context<Pane>,
898 ) -> Task<Result<Box<dyn ItemHandle>>>,
899 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
900 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
901}
902
903#[derive(Default)]
904struct SerializableItemRegistry {
905 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
906 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
907}
908
909impl Global for SerializableItemRegistry {}
910
911impl SerializableItemRegistry {
912 fn deserialize(
913 item_kind: &str,
914 project: Entity<Project>,
915 workspace: WeakEntity<Workspace>,
916 workspace_id: WorkspaceId,
917 item_item: ItemId,
918 window: &mut Window,
919 cx: &mut Context<Pane>,
920 ) -> Task<Result<Box<dyn ItemHandle>>> {
921 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
922 return Task::ready(Err(anyhow!(
923 "cannot deserialize {}, descriptor not found",
924 item_kind
925 )));
926 };
927
928 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
929 }
930
931 fn cleanup(
932 item_kind: &str,
933 workspace_id: WorkspaceId,
934 loaded_items: Vec<ItemId>,
935 window: &mut Window,
936 cx: &mut App,
937 ) -> Task<Result<()>> {
938 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
939 return Task::ready(Err(anyhow!(
940 "cannot cleanup {}, descriptor not found",
941 item_kind
942 )));
943 };
944
945 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
946 }
947
948 fn view_to_serializable_item_handle(
949 view: AnyView,
950 cx: &App,
951 ) -> Option<Box<dyn SerializableItemHandle>> {
952 let this = cx.try_global::<Self>()?;
953 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
954 Some((descriptor.view_to_serializable_item)(view))
955 }
956
957 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
958 let this = cx.try_global::<Self>()?;
959 this.descriptors_by_kind.get(item_kind).copied()
960 }
961}
962
963pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
964 let serialized_item_kind = I::serialized_item_kind();
965
966 let registry = cx.default_global::<SerializableItemRegistry>();
967 let descriptor = SerializableItemDescriptor {
968 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
969 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
970 cx.foreground_executor()
971 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
972 },
973 cleanup: |workspace_id, loaded_items, window, cx| {
974 I::cleanup(workspace_id, loaded_items, window, cx)
975 },
976 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
977 };
978 registry
979 .descriptors_by_kind
980 .insert(Arc::from(serialized_item_kind), descriptor);
981 registry
982 .descriptors_by_type
983 .insert(TypeId::of::<I>(), descriptor);
984}
985
986pub struct AppState {
987 pub languages: Arc<LanguageRegistry>,
988 pub client: Arc<Client>,
989 pub user_store: Entity<UserStore>,
990 pub workspace_store: Entity<WorkspaceStore>,
991 pub fs: Arc<dyn fs::Fs>,
992 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
993 pub node_runtime: NodeRuntime,
994 pub session: Entity<AppSession>,
995}
996
997struct GlobalAppState(Weak<AppState>);
998
999impl Global for GlobalAppState {}
1000
1001pub struct WorkspaceStore {
1002 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1003 client: Arc<Client>,
1004 _subscriptions: Vec<client::Subscription>,
1005}
1006
1007#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1008pub enum CollaboratorId {
1009 PeerId(PeerId),
1010 Agent,
1011}
1012
1013impl From<PeerId> for CollaboratorId {
1014 fn from(peer_id: PeerId) -> Self {
1015 CollaboratorId::PeerId(peer_id)
1016 }
1017}
1018
1019impl From<&PeerId> for CollaboratorId {
1020 fn from(peer_id: &PeerId) -> Self {
1021 CollaboratorId::PeerId(*peer_id)
1022 }
1023}
1024
1025#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1026struct Follower {
1027 project_id: Option<u64>,
1028 peer_id: PeerId,
1029}
1030
1031impl AppState {
1032 #[track_caller]
1033 pub fn global(cx: &App) -> Weak<Self> {
1034 cx.global::<GlobalAppState>().0.clone()
1035 }
1036 pub fn try_global(cx: &App) -> Option<Weak<Self>> {
1037 cx.try_global::<GlobalAppState>()
1038 .map(|state| state.0.clone())
1039 }
1040 pub fn set_global(state: Weak<AppState>, cx: &mut App) {
1041 cx.set_global(GlobalAppState(state));
1042 }
1043
1044 #[cfg(any(test, feature = "test-support"))]
1045 pub fn test(cx: &mut App) -> Arc<Self> {
1046 use fs::Fs;
1047 use node_runtime::NodeRuntime;
1048 use session::Session;
1049 use settings::SettingsStore;
1050
1051 if !cx.has_global::<SettingsStore>() {
1052 let settings_store = SettingsStore::test(cx);
1053 cx.set_global(settings_store);
1054 }
1055
1056 let fs = fs::FakeFs::new(cx.background_executor().clone());
1057 <dyn Fs>::set_global(fs.clone(), cx);
1058 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1059 let clock = Arc::new(clock::FakeSystemClock::new());
1060 let http_client = http_client::FakeHttpClient::with_404_response();
1061 let client = Client::new(clock, http_client, cx);
1062 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1063 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1064 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1065
1066 theme::init(theme::LoadThemes::JustBase, cx);
1067 client::init(&client, cx);
1068
1069 Arc::new(Self {
1070 client,
1071 fs,
1072 languages,
1073 user_store,
1074 workspace_store,
1075 node_runtime: NodeRuntime::unavailable(),
1076 build_window_options: |_, _| Default::default(),
1077 session,
1078 })
1079 }
1080}
1081
1082struct DelayedDebouncedEditAction {
1083 task: Option<Task<()>>,
1084 cancel_channel: Option<oneshot::Sender<()>>,
1085}
1086
1087impl DelayedDebouncedEditAction {
1088 fn new() -> DelayedDebouncedEditAction {
1089 DelayedDebouncedEditAction {
1090 task: None,
1091 cancel_channel: None,
1092 }
1093 }
1094
1095 fn fire_new<F>(
1096 &mut self,
1097 delay: Duration,
1098 window: &mut Window,
1099 cx: &mut Context<Workspace>,
1100 func: F,
1101 ) where
1102 F: 'static
1103 + Send
1104 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1105 {
1106 if let Some(channel) = self.cancel_channel.take() {
1107 _ = channel.send(());
1108 }
1109
1110 let (sender, mut receiver) = oneshot::channel::<()>();
1111 self.cancel_channel = Some(sender);
1112
1113 let previous_task = self.task.take();
1114 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1115 let mut timer = cx.background_executor().timer(delay).fuse();
1116 if let Some(previous_task) = previous_task {
1117 previous_task.await;
1118 }
1119
1120 futures::select_biased! {
1121 _ = receiver => return,
1122 _ = timer => {}
1123 }
1124
1125 if let Some(result) = workspace
1126 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1127 .log_err()
1128 {
1129 result.await.log_err();
1130 }
1131 }));
1132 }
1133}
1134
1135pub enum Event {
1136 PaneAdded(Entity<Pane>),
1137 PaneRemoved,
1138 ItemAdded {
1139 item: Box<dyn ItemHandle>,
1140 },
1141 ActiveItemChanged,
1142 ItemRemoved {
1143 item_id: EntityId,
1144 },
1145 UserSavedItem {
1146 pane: WeakEntity<Pane>,
1147 item: Box<dyn WeakItemHandle>,
1148 save_intent: SaveIntent,
1149 },
1150 ContactRequestedJoin(u64),
1151 WorkspaceCreated(WeakEntity<Workspace>),
1152 OpenBundledFile {
1153 text: Cow<'static, str>,
1154 title: &'static str,
1155 language: &'static str,
1156 },
1157 ZoomChanged,
1158 ModalOpened,
1159}
1160
1161#[derive(Debug, Clone)]
1162pub enum OpenVisible {
1163 All,
1164 None,
1165 OnlyFiles,
1166 OnlyDirectories,
1167}
1168
1169enum WorkspaceLocation {
1170 // Valid local paths or SSH project to serialize
1171 Location(SerializedWorkspaceLocation, PathList),
1172 // No valid location found hence clear session id
1173 DetachFromSession,
1174 // No valid location found to serialize
1175 None,
1176}
1177
1178type PromptForNewPath = Box<
1179 dyn Fn(
1180 &mut Workspace,
1181 DirectoryLister,
1182 Option<String>,
1183 &mut Window,
1184 &mut Context<Workspace>,
1185 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1186>;
1187
1188type PromptForOpenPath = Box<
1189 dyn Fn(
1190 &mut Workspace,
1191 DirectoryLister,
1192 &mut Window,
1193 &mut Context<Workspace>,
1194 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1195>;
1196
1197#[derive(Default)]
1198struct DispatchingKeystrokes {
1199 dispatched: HashSet<Vec<Keystroke>>,
1200 queue: VecDeque<Keystroke>,
1201 task: Option<Shared<Task<()>>>,
1202}
1203
1204/// Collects everything project-related for a certain window opened.
1205/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1206///
1207/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1208/// The `Workspace` owns everybody's state and serves as a default, "global context",
1209/// that can be used to register a global action to be triggered from any place in the window.
1210pub struct Workspace {
1211 weak_self: WeakEntity<Self>,
1212 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1213 zoomed: Option<AnyWeakView>,
1214 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1215 zoomed_position: Option<DockPosition>,
1216 center: PaneGroup,
1217 left_dock: Entity<Dock>,
1218 bottom_dock: Entity<Dock>,
1219 right_dock: Entity<Dock>,
1220 panes: Vec<Entity<Pane>>,
1221 active_worktree_override: Option<WorktreeId>,
1222 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1223 active_pane: Entity<Pane>,
1224 last_active_center_pane: Option<WeakEntity<Pane>>,
1225 last_active_view_id: Option<proto::ViewId>,
1226 status_bar: Entity<StatusBar>,
1227 modal_layer: Entity<ModalLayer>,
1228 toast_layer: Entity<ToastLayer>,
1229 titlebar_item: Option<AnyView>,
1230 notifications: Notifications,
1231 suppressed_notifications: HashSet<NotificationId>,
1232 project: Entity<Project>,
1233 follower_states: HashMap<CollaboratorId, FollowerState>,
1234 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1235 window_edited: bool,
1236 last_window_title: Option<String>,
1237 dirty_items: HashMap<EntityId, Subscription>,
1238 active_call: Option<(Entity<ActiveCall>, Vec<Subscription>)>,
1239 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1240 database_id: Option<WorkspaceId>,
1241 app_state: Arc<AppState>,
1242 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1243 _subscriptions: Vec<Subscription>,
1244 _apply_leader_updates: Task<Result<()>>,
1245 _observe_current_user: Task<Result<()>>,
1246 _schedule_serialize_workspace: Option<Task<()>>,
1247 _schedule_serialize_ssh_paths: Option<Task<()>>,
1248 pane_history_timestamp: Arc<AtomicUsize>,
1249 bounds: Bounds<Pixels>,
1250 pub centered_layout: bool,
1251 bounds_save_task_queued: Option<Task<()>>,
1252 on_prompt_for_new_path: Option<PromptForNewPath>,
1253 on_prompt_for_open_path: Option<PromptForOpenPath>,
1254 terminal_provider: Option<Box<dyn TerminalProvider>>,
1255 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1256 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1257 _items_serializer: Task<Result<()>>,
1258 session_id: Option<String>,
1259 scheduled_tasks: Vec<Task<()>>,
1260 last_open_dock_positions: Vec<DockPosition>,
1261 removing: bool,
1262}
1263
1264impl EventEmitter<Event> for Workspace {}
1265
1266#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1267pub struct ViewId {
1268 pub creator: CollaboratorId,
1269 pub id: u64,
1270}
1271
1272pub struct FollowerState {
1273 center_pane: Entity<Pane>,
1274 dock_pane: Option<Entity<Pane>>,
1275 active_view_id: Option<ViewId>,
1276 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1277}
1278
1279struct FollowerView {
1280 view: Box<dyn FollowableItemHandle>,
1281 location: Option<proto::PanelId>,
1282}
1283
1284impl Workspace {
1285 pub fn new(
1286 workspace_id: Option<WorkspaceId>,
1287 project: Entity<Project>,
1288 app_state: Arc<AppState>,
1289 window: &mut Window,
1290 cx: &mut Context<Self>,
1291 ) -> Self {
1292 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1293 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1294 if let TrustedWorktreesEvent::Trusted(..) = e {
1295 // Do not persist auto trusted worktrees
1296 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1297 worktrees_store.update(cx, |worktrees_store, cx| {
1298 worktrees_store.schedule_serialization(
1299 cx,
1300 |new_trusted_worktrees, cx| {
1301 let timeout =
1302 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1303 cx.background_spawn(async move {
1304 timeout.await;
1305 persistence::DB
1306 .save_trusted_worktrees(new_trusted_worktrees)
1307 .await
1308 .log_err();
1309 })
1310 },
1311 )
1312 });
1313 }
1314 }
1315 })
1316 .detach();
1317
1318 cx.observe_global::<SettingsStore>(|_, cx| {
1319 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1320 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1321 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1322 trusted_worktrees.auto_trust_all(cx);
1323 })
1324 }
1325 }
1326 })
1327 .detach();
1328 }
1329
1330 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1331 match event {
1332 project::Event::RemoteIdChanged(_) => {
1333 this.update_window_title(window, cx);
1334 }
1335
1336 project::Event::CollaboratorLeft(peer_id) => {
1337 this.collaborator_left(*peer_id, window, cx);
1338 }
1339
1340 &project::Event::WorktreeRemoved(id) | &project::Event::WorktreeAdded(id) => {
1341 this.update_window_title(window, cx);
1342 if this
1343 .project()
1344 .read(cx)
1345 .worktree_for_id(id, cx)
1346 .is_some_and(|wt| wt.read(cx).is_visible())
1347 {
1348 this.serialize_workspace(window, cx);
1349 this.update_history(cx);
1350 }
1351 }
1352 project::Event::WorktreeUpdatedEntries(..) => {
1353 this.update_window_title(window, cx);
1354 this.serialize_workspace(window, cx);
1355 }
1356
1357 project::Event::DisconnectedFromHost => {
1358 this.update_window_edited(window, cx);
1359 let leaders_to_unfollow =
1360 this.follower_states.keys().copied().collect::<Vec<_>>();
1361 for leader_id in leaders_to_unfollow {
1362 this.unfollow(leader_id, window, cx);
1363 }
1364 }
1365
1366 project::Event::DisconnectedFromRemote {
1367 server_not_running: _,
1368 } => {
1369 this.update_window_edited(window, cx);
1370 }
1371
1372 project::Event::Closed => {
1373 window.remove_window();
1374 }
1375
1376 project::Event::DeletedEntry(_, entry_id) => {
1377 for pane in this.panes.iter() {
1378 pane.update(cx, |pane, cx| {
1379 pane.handle_deleted_project_item(*entry_id, window, cx)
1380 });
1381 }
1382 }
1383
1384 project::Event::Toast {
1385 notification_id,
1386 message,
1387 link,
1388 } => this.show_notification(
1389 NotificationId::named(notification_id.clone()),
1390 cx,
1391 |cx| {
1392 let mut notification = MessageNotification::new(message.clone(), cx);
1393 if let Some(link) = link {
1394 notification = notification
1395 .more_info_message(link.label)
1396 .more_info_url(link.url);
1397 }
1398
1399 cx.new(|_| notification)
1400 },
1401 ),
1402
1403 project::Event::HideToast { notification_id } => {
1404 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1405 }
1406
1407 project::Event::LanguageServerPrompt(request) => {
1408 struct LanguageServerPrompt;
1409
1410 this.show_notification(
1411 NotificationId::composite::<LanguageServerPrompt>(request.id),
1412 cx,
1413 |cx| {
1414 cx.new(|cx| {
1415 notifications::LanguageServerPrompt::new(request.clone(), cx)
1416 })
1417 },
1418 );
1419 }
1420
1421 project::Event::AgentLocationChanged => {
1422 this.handle_agent_location_changed(window, cx)
1423 }
1424
1425 _ => {}
1426 }
1427 cx.notify()
1428 })
1429 .detach();
1430
1431 cx.subscribe_in(
1432 &project.read(cx).breakpoint_store(),
1433 window,
1434 |workspace, _, event, window, cx| match event {
1435 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1436 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1437 workspace.serialize_workspace(window, cx);
1438 }
1439 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1440 },
1441 )
1442 .detach();
1443 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1444 cx.subscribe_in(
1445 &toolchain_store,
1446 window,
1447 |workspace, _, event, window, cx| match event {
1448 ToolchainStoreEvent::CustomToolchainsModified => {
1449 workspace.serialize_workspace(window, cx);
1450 }
1451 _ => {}
1452 },
1453 )
1454 .detach();
1455 }
1456
1457 cx.on_focus_lost(window, |this, window, cx| {
1458 let focus_handle = this.focus_handle(cx);
1459 window.focus(&focus_handle, cx);
1460 })
1461 .detach();
1462
1463 let weak_handle = cx.entity().downgrade();
1464 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1465
1466 let center_pane = cx.new(|cx| {
1467 let mut center_pane = Pane::new(
1468 weak_handle.clone(),
1469 project.clone(),
1470 pane_history_timestamp.clone(),
1471 None,
1472 NewFile.boxed_clone(),
1473 true,
1474 window,
1475 cx,
1476 );
1477 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1478 center_pane.set_should_display_welcome_page(true);
1479 center_pane
1480 });
1481 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1482 .detach();
1483
1484 window.focus(¢er_pane.focus_handle(cx), cx);
1485
1486 cx.emit(Event::PaneAdded(center_pane.clone()));
1487
1488 let any_window_handle = window.window_handle();
1489 app_state.workspace_store.update(cx, |store, _| {
1490 store
1491 .workspaces
1492 .insert((any_window_handle, weak_handle.clone()));
1493 });
1494
1495 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1496 let mut connection_status = app_state.client.status();
1497 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1498 current_user.next().await;
1499 connection_status.next().await;
1500 let mut stream =
1501 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1502
1503 while stream.recv().await.is_some() {
1504 this.update(cx, |_, cx| cx.notify())?;
1505 }
1506 anyhow::Ok(())
1507 });
1508
1509 // All leader updates are enqueued and then processed in a single task, so
1510 // that each asynchronous operation can be run in order.
1511 let (leader_updates_tx, mut leader_updates_rx) =
1512 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1513 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1514 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1515 Self::process_leader_update(&this, leader_id, update, cx)
1516 .await
1517 .log_err();
1518 }
1519
1520 Ok(())
1521 });
1522
1523 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1524 let modal_layer = cx.new(|_| ModalLayer::new());
1525 let toast_layer = cx.new(|_| ToastLayer::new());
1526 cx.subscribe(
1527 &modal_layer,
1528 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1529 cx.emit(Event::ModalOpened);
1530 },
1531 )
1532 .detach();
1533
1534 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1535 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1536 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1537 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1538 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1539 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1540 let status_bar = cx.new(|cx| {
1541 let mut status_bar = StatusBar::new(¢er_pane.clone(), window, cx);
1542 status_bar.add_left_item(left_dock_buttons, window, cx);
1543 status_bar.add_right_item(right_dock_buttons, window, cx);
1544 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1545 status_bar
1546 });
1547
1548 let session_id = app_state.session.read(cx).id().to_owned();
1549
1550 let mut active_call = None;
1551 if let Some(call) = ActiveCall::try_global(cx) {
1552 let subscriptions = vec![cx.subscribe_in(&call, window, Self::on_active_call_event)];
1553 active_call = Some((call, subscriptions));
1554 }
1555
1556 let (serializable_items_tx, serializable_items_rx) =
1557 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1558 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1559 Self::serialize_items(&this, serializable_items_rx, cx).await
1560 });
1561
1562 let subscriptions = vec![
1563 cx.observe_window_activation(window, Self::on_window_activation_changed),
1564 cx.observe_window_bounds(window, move |this, window, cx| {
1565 if this.bounds_save_task_queued.is_some() {
1566 return;
1567 }
1568 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1569 cx.background_executor()
1570 .timer(Duration::from_millis(100))
1571 .await;
1572 this.update_in(cx, |this, window, cx| {
1573 if let Some(display) = window.display(cx)
1574 && let Ok(display_uuid) = display.uuid()
1575 {
1576 let window_bounds = window.inner_window_bounds();
1577 let has_paths = !this.root_paths(cx).is_empty();
1578 if !has_paths {
1579 cx.background_executor()
1580 .spawn(persistence::write_default_window_bounds(
1581 window_bounds,
1582 display_uuid,
1583 ))
1584 .detach_and_log_err(cx);
1585 }
1586 if let Some(database_id) = workspace_id {
1587 cx.background_executor()
1588 .spawn(DB.set_window_open_status(
1589 database_id,
1590 SerializedWindowBounds(window_bounds),
1591 display_uuid,
1592 ))
1593 .detach_and_log_err(cx);
1594 } else {
1595 cx.background_executor()
1596 .spawn(persistence::write_default_window_bounds(
1597 window_bounds,
1598 display_uuid,
1599 ))
1600 .detach_and_log_err(cx);
1601 }
1602 }
1603 this.bounds_save_task_queued.take();
1604 })
1605 .ok();
1606 }));
1607 cx.notify();
1608 }),
1609 cx.observe_window_appearance(window, |_, window, cx| {
1610 let window_appearance = window.appearance();
1611
1612 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1613
1614 GlobalTheme::reload_theme(cx);
1615 GlobalTheme::reload_icon_theme(cx);
1616 }),
1617 cx.on_release({
1618 let weak_handle = weak_handle.clone();
1619 move |this, cx| {
1620 this.app_state.workspace_store.update(cx, move |store, _| {
1621 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1622 })
1623 }
1624 }),
1625 ];
1626
1627 cx.defer_in(window, move |this, window, cx| {
1628 this.update_window_title(window, cx);
1629 this.show_initial_notifications(cx);
1630 });
1631
1632 let mut center = PaneGroup::new(center_pane.clone());
1633 center.set_is_center(true);
1634 center.mark_positions(cx);
1635
1636 Workspace {
1637 weak_self: weak_handle.clone(),
1638 zoomed: None,
1639 zoomed_position: None,
1640 previous_dock_drag_coordinates: None,
1641 center,
1642 panes: vec![center_pane.clone()],
1643 panes_by_item: Default::default(),
1644 active_pane: center_pane.clone(),
1645 last_active_center_pane: Some(center_pane.downgrade()),
1646 last_active_view_id: None,
1647 status_bar,
1648 modal_layer,
1649 toast_layer,
1650 titlebar_item: None,
1651 active_worktree_override: None,
1652 notifications: Notifications::default(),
1653 suppressed_notifications: HashSet::default(),
1654 left_dock,
1655 bottom_dock,
1656 right_dock,
1657 project: project.clone(),
1658 follower_states: Default::default(),
1659 last_leaders_by_pane: Default::default(),
1660 dispatching_keystrokes: Default::default(),
1661 window_edited: false,
1662 last_window_title: None,
1663 dirty_items: Default::default(),
1664 active_call,
1665 database_id: workspace_id,
1666 app_state,
1667 _observe_current_user,
1668 _apply_leader_updates,
1669 _schedule_serialize_workspace: None,
1670 _schedule_serialize_ssh_paths: None,
1671 leader_updates_tx,
1672 _subscriptions: subscriptions,
1673 pane_history_timestamp,
1674 workspace_actions: Default::default(),
1675 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1676 bounds: Default::default(),
1677 centered_layout: false,
1678 bounds_save_task_queued: None,
1679 on_prompt_for_new_path: None,
1680 on_prompt_for_open_path: None,
1681 terminal_provider: None,
1682 debugger_provider: None,
1683 serializable_items_tx,
1684 _items_serializer,
1685 session_id: Some(session_id),
1686
1687 scheduled_tasks: Vec::new(),
1688 last_open_dock_positions: Vec::new(),
1689 removing: false,
1690 }
1691 }
1692
1693 pub fn new_local(
1694 abs_paths: Vec<PathBuf>,
1695 app_state: Arc<AppState>,
1696 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1697 env: Option<HashMap<String, String>>,
1698 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1699 cx: &mut App,
1700 ) -> Task<
1701 anyhow::Result<(
1702 WindowHandle<MultiWorkspace>,
1703 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
1704 )>,
1705 > {
1706 let project_handle = Project::local(
1707 app_state.client.clone(),
1708 app_state.node_runtime.clone(),
1709 app_state.user_store.clone(),
1710 app_state.languages.clone(),
1711 app_state.fs.clone(),
1712 env,
1713 Default::default(),
1714 cx,
1715 );
1716
1717 cx.spawn(async move |cx| {
1718 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1719 for path in abs_paths.into_iter() {
1720 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1721 paths_to_open.push(canonical)
1722 } else {
1723 paths_to_open.push(path)
1724 }
1725 }
1726
1727 let serialized_workspace =
1728 persistence::DB.workspace_for_roots(paths_to_open.as_slice());
1729
1730 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1731 paths_to_open = paths.ordered_paths().cloned().collect();
1732 if !paths.is_lexicographically_ordered() {
1733 project_handle.update(cx, |project, cx| {
1734 project.set_worktrees_reordered(true, cx);
1735 });
1736 }
1737 }
1738
1739 // Get project paths for all of the abs_paths
1740 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1741 Vec::with_capacity(paths_to_open.len());
1742
1743 for path in paths_to_open.into_iter() {
1744 if let Some((_, project_entry)) = cx
1745 .update(|cx| {
1746 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1747 })
1748 .await
1749 .log_err()
1750 {
1751 project_paths.push((path, Some(project_entry)));
1752 } else {
1753 project_paths.push((path, None));
1754 }
1755 }
1756
1757 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1758 serialized_workspace.id
1759 } else {
1760 DB.next_id().await.unwrap_or_else(|_| Default::default())
1761 };
1762
1763 let toolchains = DB.toolchains(workspace_id).await?;
1764
1765 for (toolchain, worktree_path, path) in toolchains {
1766 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1767 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1768 this.find_worktree(&worktree_path, cx)
1769 .and_then(|(worktree, rel_path)| {
1770 if rel_path.is_empty() {
1771 Some(worktree.read(cx).id())
1772 } else {
1773 None
1774 }
1775 })
1776 }) else {
1777 // We did not find a worktree with a given path, but that's whatever.
1778 continue;
1779 };
1780 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1781 continue;
1782 }
1783
1784 project_handle
1785 .update(cx, |this, cx| {
1786 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1787 })
1788 .await;
1789 }
1790 if let Some(workspace) = serialized_workspace.as_ref() {
1791 project_handle.update(cx, |this, cx| {
1792 for (scope, toolchains) in &workspace.user_toolchains {
1793 for toolchain in toolchains {
1794 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1795 }
1796 }
1797 });
1798 }
1799
1800 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1801 if let Some(window) = requesting_window {
1802 let centered_layout = serialized_workspace
1803 .as_ref()
1804 .map(|w| w.centered_layout)
1805 .unwrap_or(false);
1806
1807 let workspace = window.update(cx, |multi_workspace, window, cx| {
1808 let workspace = cx.new(|cx| {
1809 let mut workspace = Workspace::new(
1810 Some(workspace_id),
1811 project_handle.clone(),
1812 app_state.clone(),
1813 window,
1814 cx,
1815 );
1816
1817 workspace.centered_layout = centered_layout;
1818
1819 // Call init callback to add items before window renders
1820 if let Some(init) = init {
1821 init(&mut workspace, window, cx);
1822 }
1823
1824 workspace
1825 });
1826 multi_workspace.activate(workspace.clone(), cx);
1827 workspace
1828 })?;
1829 (window, workspace)
1830 } else {
1831 let window_bounds_override = window_bounds_env_override();
1832
1833 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1834 (Some(WindowBounds::Windowed(bounds)), None)
1835 } else if let Some(workspace) = serialized_workspace.as_ref()
1836 && let Some(display) = workspace.display
1837 && let Some(bounds) = workspace.window_bounds.as_ref()
1838 {
1839 // Reopening an existing workspace - restore its saved bounds
1840 (Some(bounds.0), Some(display))
1841 } else if let Some((display, bounds)) =
1842 persistence::read_default_window_bounds()
1843 {
1844 // New or empty workspace - use the last known window bounds
1845 (Some(bounds), Some(display))
1846 } else {
1847 // New window - let GPUI's default_bounds() handle cascading
1848 (None, None)
1849 };
1850
1851 // Use the serialized workspace to construct the new window
1852 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1853 options.window_bounds = window_bounds;
1854 let centered_layout = serialized_workspace
1855 .as_ref()
1856 .map(|w| w.centered_layout)
1857 .unwrap_or(false);
1858 let window = cx.open_window(options, {
1859 let app_state = app_state.clone();
1860 let project_handle = project_handle.clone();
1861 move |window, cx| {
1862 let workspace = cx.new(|cx| {
1863 let mut workspace = Workspace::new(
1864 Some(workspace_id),
1865 project_handle,
1866 app_state,
1867 window,
1868 cx,
1869 );
1870 workspace.centered_layout = centered_layout;
1871
1872 // Call init callback to add items before window renders
1873 if let Some(init) = init {
1874 init(&mut workspace, window, cx);
1875 }
1876
1877 workspace
1878 });
1879 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1880 }
1881 })?;
1882 let workspace =
1883 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
1884 multi_workspace.workspace().clone()
1885 })?;
1886 (window, workspace)
1887 };
1888
1889 notify_if_database_failed(window, cx);
1890 // Check if this is an empty workspace (no paths to open)
1891 // An empty workspace is one where project_paths is empty
1892 let is_empty_workspace = project_paths.is_empty();
1893 // Check if serialized workspace has paths before it's moved
1894 let serialized_workspace_has_paths = serialized_workspace
1895 .as_ref()
1896 .map(|ws| !ws.paths.is_empty())
1897 .unwrap_or(false);
1898
1899 let opened_items = window
1900 .update(cx, |_, window, cx| {
1901 workspace.update(cx, |_workspace: &mut Workspace, cx| {
1902 open_items(serialized_workspace, project_paths, window, cx)
1903 })
1904 })?
1905 .await
1906 .unwrap_or_default();
1907
1908 // Restore default dock state for empty workspaces
1909 // Only restore if:
1910 // 1. This is an empty workspace (no paths), AND
1911 // 2. The serialized workspace either doesn't exist or has no paths
1912 if is_empty_workspace && !serialized_workspace_has_paths {
1913 if let Some(default_docks) = persistence::read_default_dock_state() {
1914 window
1915 .update(cx, |_, window, cx| {
1916 workspace.update(cx, |workspace, cx| {
1917 for (dock, serialized_dock) in [
1918 (&workspace.right_dock, &default_docks.right),
1919 (&workspace.left_dock, &default_docks.left),
1920 (&workspace.bottom_dock, &default_docks.bottom),
1921 ] {
1922 dock.update(cx, |dock, cx| {
1923 dock.serialized_dock = Some(serialized_dock.clone());
1924 dock.restore_state(window, cx);
1925 });
1926 }
1927 cx.notify();
1928 });
1929 })
1930 .log_err();
1931 }
1932 }
1933
1934 window
1935 .update(cx, |_, _window, cx| {
1936 workspace.update(cx, |this: &mut Workspace, cx| {
1937 this.update_history(cx);
1938 });
1939 })
1940 .log_err();
1941 Ok((window, opened_items))
1942 })
1943 }
1944
1945 pub fn weak_handle(&self) -> WeakEntity<Self> {
1946 self.weak_self.clone()
1947 }
1948
1949 pub fn left_dock(&self) -> &Entity<Dock> {
1950 &self.left_dock
1951 }
1952
1953 pub fn bottom_dock(&self) -> &Entity<Dock> {
1954 &self.bottom_dock
1955 }
1956
1957 pub fn set_bottom_dock_layout(
1958 &mut self,
1959 layout: BottomDockLayout,
1960 window: &mut Window,
1961 cx: &mut Context<Self>,
1962 ) {
1963 let fs = self.project().read(cx).fs();
1964 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
1965 content.workspace.bottom_dock_layout = Some(layout);
1966 });
1967
1968 cx.notify();
1969 self.serialize_workspace(window, cx);
1970 }
1971
1972 pub fn right_dock(&self) -> &Entity<Dock> {
1973 &self.right_dock
1974 }
1975
1976 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
1977 [&self.left_dock, &self.bottom_dock, &self.right_dock]
1978 }
1979
1980 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
1981 match position {
1982 DockPosition::Left => &self.left_dock,
1983 DockPosition::Bottom => &self.bottom_dock,
1984 DockPosition::Right => &self.right_dock,
1985 }
1986 }
1987
1988 pub fn is_edited(&self) -> bool {
1989 self.window_edited
1990 }
1991
1992 pub fn add_panel<T: Panel>(
1993 &mut self,
1994 panel: Entity<T>,
1995 window: &mut Window,
1996 cx: &mut Context<Self>,
1997 ) {
1998 let focus_handle = panel.panel_focus_handle(cx);
1999 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2000 .detach();
2001
2002 let dock_position = panel.position(window, cx);
2003 let dock = self.dock_at_position(dock_position);
2004
2005 dock.update(cx, |dock, cx| {
2006 dock.add_panel(panel, self.weak_self.clone(), window, cx)
2007 });
2008 }
2009
2010 pub fn remove_panel<T: Panel>(
2011 &mut self,
2012 panel: &Entity<T>,
2013 window: &mut Window,
2014 cx: &mut Context<Self>,
2015 ) {
2016 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2017 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2018 }
2019 }
2020
2021 pub fn status_bar(&self) -> &Entity<StatusBar> {
2022 &self.status_bar
2023 }
2024
2025 pub fn set_workspace_sidebar_open(&self, open: bool, cx: &mut App) {
2026 self.status_bar.update(cx, |status_bar, cx| {
2027 status_bar.set_workspace_sidebar_open(open, cx);
2028 });
2029 }
2030
2031 pub fn status_bar_visible(&self, cx: &App) -> bool {
2032 StatusBarSettings::get_global(cx).show
2033 }
2034
2035 pub fn app_state(&self) -> &Arc<AppState> {
2036 &self.app_state
2037 }
2038
2039 pub fn user_store(&self) -> &Entity<UserStore> {
2040 &self.app_state.user_store
2041 }
2042
2043 pub fn project(&self) -> &Entity<Project> {
2044 &self.project
2045 }
2046
2047 pub fn path_style(&self, cx: &App) -> PathStyle {
2048 self.project.read(cx).path_style(cx)
2049 }
2050
2051 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2052 let mut history: HashMap<EntityId, usize> = HashMap::default();
2053
2054 for pane_handle in &self.panes {
2055 let pane = pane_handle.read(cx);
2056
2057 for entry in pane.activation_history() {
2058 history.insert(
2059 entry.entity_id,
2060 history
2061 .get(&entry.entity_id)
2062 .cloned()
2063 .unwrap_or(0)
2064 .max(entry.timestamp),
2065 );
2066 }
2067 }
2068
2069 history
2070 }
2071
2072 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2073 let mut recent_item: Option<Entity<T>> = None;
2074 let mut recent_timestamp = 0;
2075 for pane_handle in &self.panes {
2076 let pane = pane_handle.read(cx);
2077 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2078 pane.items().map(|item| (item.item_id(), item)).collect();
2079 for entry in pane.activation_history() {
2080 if entry.timestamp > recent_timestamp
2081 && let Some(&item) = item_map.get(&entry.entity_id)
2082 && let Some(typed_item) = item.act_as::<T>(cx)
2083 {
2084 recent_timestamp = entry.timestamp;
2085 recent_item = Some(typed_item);
2086 }
2087 }
2088 }
2089 recent_item
2090 }
2091
2092 pub fn recent_navigation_history_iter(
2093 &self,
2094 cx: &App,
2095 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2096 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2097 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2098
2099 for pane in &self.panes {
2100 let pane = pane.read(cx);
2101
2102 pane.nav_history()
2103 .for_each_entry(cx, |entry, (project_path, fs_path)| {
2104 if let Some(fs_path) = &fs_path {
2105 abs_paths_opened
2106 .entry(fs_path.clone())
2107 .or_default()
2108 .insert(project_path.clone());
2109 }
2110 let timestamp = entry.timestamp;
2111 match history.entry(project_path) {
2112 hash_map::Entry::Occupied(mut entry) => {
2113 let (_, old_timestamp) = entry.get();
2114 if ×tamp > old_timestamp {
2115 entry.insert((fs_path, timestamp));
2116 }
2117 }
2118 hash_map::Entry::Vacant(entry) => {
2119 entry.insert((fs_path, timestamp));
2120 }
2121 }
2122 });
2123
2124 if let Some(item) = pane.active_item()
2125 && let Some(project_path) = item.project_path(cx)
2126 {
2127 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2128
2129 if let Some(fs_path) = &fs_path {
2130 abs_paths_opened
2131 .entry(fs_path.clone())
2132 .or_default()
2133 .insert(project_path.clone());
2134 }
2135
2136 history.insert(project_path, (fs_path, std::usize::MAX));
2137 }
2138 }
2139
2140 history
2141 .into_iter()
2142 .sorted_by_key(|(_, (_, order))| *order)
2143 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2144 .rev()
2145 .filter(move |(history_path, abs_path)| {
2146 let latest_project_path_opened = abs_path
2147 .as_ref()
2148 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2149 .and_then(|project_paths| {
2150 project_paths
2151 .iter()
2152 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2153 });
2154
2155 latest_project_path_opened.is_none_or(|path| path == history_path)
2156 })
2157 }
2158
2159 pub fn recent_navigation_history(
2160 &self,
2161 limit: Option<usize>,
2162 cx: &App,
2163 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2164 self.recent_navigation_history_iter(cx)
2165 .take(limit.unwrap_or(usize::MAX))
2166 .collect()
2167 }
2168
2169 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2170 for pane in &self.panes {
2171 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2172 }
2173 }
2174
2175 fn navigate_history(
2176 &mut self,
2177 pane: WeakEntity<Pane>,
2178 mode: NavigationMode,
2179 window: &mut Window,
2180 cx: &mut Context<Workspace>,
2181 ) -> Task<Result<()>> {
2182 self.navigate_history_impl(pane, mode, window, |history, cx| history.pop(mode, cx), cx)
2183 }
2184
2185 fn navigate_tag_history(
2186 &mut self,
2187 pane: WeakEntity<Pane>,
2188 mode: TagNavigationMode,
2189 window: &mut Window,
2190 cx: &mut Context<Workspace>,
2191 ) -> Task<Result<()>> {
2192 self.navigate_history_impl(
2193 pane,
2194 NavigationMode::Normal,
2195 window,
2196 |history, _cx| history.pop_tag(mode),
2197 cx,
2198 )
2199 }
2200
2201 fn navigate_history_impl(
2202 &mut self,
2203 pane: WeakEntity<Pane>,
2204 mode: NavigationMode,
2205 window: &mut Window,
2206 mut cb: impl FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2207 cx: &mut Context<Workspace>,
2208 ) -> Task<Result<()>> {
2209 let to_load = if let Some(pane) = pane.upgrade() {
2210 pane.update(cx, |pane, cx| {
2211 window.focus(&pane.focus_handle(cx), cx);
2212 loop {
2213 // Retrieve the weak item handle from the history.
2214 let entry = cb(pane.nav_history_mut(), cx)?;
2215
2216 // If the item is still present in this pane, then activate it.
2217 if let Some(index) = entry
2218 .item
2219 .upgrade()
2220 .and_then(|v| pane.index_for_item(v.as_ref()))
2221 {
2222 let prev_active_item_index = pane.active_item_index();
2223 pane.nav_history_mut().set_mode(mode);
2224 pane.activate_item(index, true, true, window, cx);
2225 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2226
2227 let mut navigated = prev_active_item_index != pane.active_item_index();
2228 if let Some(data) = entry.data {
2229 navigated |= pane.active_item()?.navigate(data, window, cx);
2230 }
2231
2232 if navigated {
2233 break None;
2234 }
2235 } else {
2236 // If the item is no longer present in this pane, then retrieve its
2237 // path info in order to reopen it.
2238 break pane
2239 .nav_history()
2240 .path_for_item(entry.item.id())
2241 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2242 }
2243 }
2244 })
2245 } else {
2246 None
2247 };
2248
2249 if let Some((project_path, abs_path, entry)) = to_load {
2250 // If the item was no longer present, then load it again from its previous path, first try the local path
2251 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2252
2253 cx.spawn_in(window, async move |workspace, cx| {
2254 let open_by_project_path = open_by_project_path.await;
2255 let mut navigated = false;
2256 match open_by_project_path
2257 .with_context(|| format!("Navigating to {project_path:?}"))
2258 {
2259 Ok((project_entry_id, build_item)) => {
2260 let prev_active_item_id = pane.update(cx, |pane, _| {
2261 pane.nav_history_mut().set_mode(mode);
2262 pane.active_item().map(|p| p.item_id())
2263 })?;
2264
2265 pane.update_in(cx, |pane, window, cx| {
2266 let item = pane.open_item(
2267 project_entry_id,
2268 project_path,
2269 true,
2270 entry.is_preview,
2271 true,
2272 None,
2273 window, cx,
2274 build_item,
2275 );
2276 navigated |= Some(item.item_id()) != prev_active_item_id;
2277 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2278 if let Some(data) = entry.data {
2279 navigated |= item.navigate(data, window, cx);
2280 }
2281 })?;
2282 }
2283 Err(open_by_project_path_e) => {
2284 // Fall back to opening by abs path, in case an external file was opened and closed,
2285 // and its worktree is now dropped
2286 if let Some(abs_path) = abs_path {
2287 let prev_active_item_id = pane.update(cx, |pane, _| {
2288 pane.nav_history_mut().set_mode(mode);
2289 pane.active_item().map(|p| p.item_id())
2290 })?;
2291 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2292 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2293 })?;
2294 match open_by_abs_path
2295 .await
2296 .with_context(|| format!("Navigating to {abs_path:?}"))
2297 {
2298 Ok(item) => {
2299 pane.update_in(cx, |pane, window, cx| {
2300 navigated |= Some(item.item_id()) != prev_active_item_id;
2301 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2302 if let Some(data) = entry.data {
2303 navigated |= item.navigate(data, window, cx);
2304 }
2305 })?;
2306 }
2307 Err(open_by_abs_path_e) => {
2308 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2309 }
2310 }
2311 }
2312 }
2313 }
2314
2315 if !navigated {
2316 workspace
2317 .update_in(cx, |workspace, window, cx| {
2318 Self::navigate_history(workspace, pane, mode, window, cx)
2319 })?
2320 .await?;
2321 }
2322
2323 Ok(())
2324 })
2325 } else {
2326 Task::ready(Ok(()))
2327 }
2328 }
2329
2330 pub fn go_back(
2331 &mut self,
2332 pane: WeakEntity<Pane>,
2333 window: &mut Window,
2334 cx: &mut Context<Workspace>,
2335 ) -> Task<Result<()>> {
2336 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2337 }
2338
2339 pub fn go_forward(
2340 &mut self,
2341 pane: WeakEntity<Pane>,
2342 window: &mut Window,
2343 cx: &mut Context<Workspace>,
2344 ) -> Task<Result<()>> {
2345 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2346 }
2347
2348 pub fn reopen_closed_item(
2349 &mut self,
2350 window: &mut Window,
2351 cx: &mut Context<Workspace>,
2352 ) -> Task<Result<()>> {
2353 self.navigate_history(
2354 self.active_pane().downgrade(),
2355 NavigationMode::ReopeningClosedItem,
2356 window,
2357 cx,
2358 )
2359 }
2360
2361 pub fn client(&self) -> &Arc<Client> {
2362 &self.app_state.client
2363 }
2364
2365 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2366 self.titlebar_item = Some(item);
2367 cx.notify();
2368 }
2369
2370 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2371 self.on_prompt_for_new_path = Some(prompt)
2372 }
2373
2374 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2375 self.on_prompt_for_open_path = Some(prompt)
2376 }
2377
2378 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2379 self.terminal_provider = Some(Box::new(provider));
2380 }
2381
2382 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2383 self.debugger_provider = Some(Arc::new(provider));
2384 }
2385
2386 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2387 self.debugger_provider.clone()
2388 }
2389
2390 pub fn prompt_for_open_path(
2391 &mut self,
2392 path_prompt_options: PathPromptOptions,
2393 lister: DirectoryLister,
2394 window: &mut Window,
2395 cx: &mut Context<Self>,
2396 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2397 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2398 let prompt = self.on_prompt_for_open_path.take().unwrap();
2399 let rx = prompt(self, lister, window, cx);
2400 self.on_prompt_for_open_path = Some(prompt);
2401 rx
2402 } else {
2403 let (tx, rx) = oneshot::channel();
2404 let abs_path = cx.prompt_for_paths(path_prompt_options);
2405
2406 cx.spawn_in(window, async move |workspace, cx| {
2407 let Ok(result) = abs_path.await else {
2408 return Ok(());
2409 };
2410
2411 match result {
2412 Ok(result) => {
2413 tx.send(result).ok();
2414 }
2415 Err(err) => {
2416 let rx = workspace.update_in(cx, |workspace, window, cx| {
2417 workspace.show_portal_error(err.to_string(), cx);
2418 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2419 let rx = prompt(workspace, lister, window, cx);
2420 workspace.on_prompt_for_open_path = Some(prompt);
2421 rx
2422 })?;
2423 if let Ok(path) = rx.await {
2424 tx.send(path).ok();
2425 }
2426 }
2427 };
2428 anyhow::Ok(())
2429 })
2430 .detach();
2431
2432 rx
2433 }
2434 }
2435
2436 pub fn prompt_for_new_path(
2437 &mut self,
2438 lister: DirectoryLister,
2439 suggested_name: Option<String>,
2440 window: &mut Window,
2441 cx: &mut Context<Self>,
2442 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2443 if self.project.read(cx).is_via_collab()
2444 || self.project.read(cx).is_via_remote_server()
2445 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2446 {
2447 let prompt = self.on_prompt_for_new_path.take().unwrap();
2448 let rx = prompt(self, lister, suggested_name, window, cx);
2449 self.on_prompt_for_new_path = Some(prompt);
2450 return rx;
2451 }
2452
2453 let (tx, rx) = oneshot::channel();
2454 cx.spawn_in(window, async move |workspace, cx| {
2455 let abs_path = workspace.update(cx, |workspace, cx| {
2456 let relative_to = workspace
2457 .most_recent_active_path(cx)
2458 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2459 .or_else(|| {
2460 let project = workspace.project.read(cx);
2461 project.visible_worktrees(cx).find_map(|worktree| {
2462 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2463 })
2464 })
2465 .or_else(std::env::home_dir)
2466 .unwrap_or_else(|| PathBuf::from(""));
2467 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2468 })?;
2469 let abs_path = match abs_path.await? {
2470 Ok(path) => path,
2471 Err(err) => {
2472 let rx = workspace.update_in(cx, |workspace, window, cx| {
2473 workspace.show_portal_error(err.to_string(), cx);
2474
2475 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2476 let rx = prompt(workspace, lister, suggested_name, window, cx);
2477 workspace.on_prompt_for_new_path = Some(prompt);
2478 rx
2479 })?;
2480 if let Ok(path) = rx.await {
2481 tx.send(path).ok();
2482 }
2483 return anyhow::Ok(());
2484 }
2485 };
2486
2487 tx.send(abs_path.map(|path| vec![path])).ok();
2488 anyhow::Ok(())
2489 })
2490 .detach();
2491
2492 rx
2493 }
2494
2495 pub fn titlebar_item(&self) -> Option<AnyView> {
2496 self.titlebar_item.clone()
2497 }
2498
2499 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2500 /// When set, git-related operations should use this worktree instead of deriving
2501 /// the active worktree from the focused file.
2502 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2503 self.active_worktree_override
2504 }
2505
2506 pub fn set_active_worktree_override(
2507 &mut self,
2508 worktree_id: Option<WorktreeId>,
2509 cx: &mut Context<Self>,
2510 ) {
2511 self.active_worktree_override = worktree_id;
2512 cx.notify();
2513 }
2514
2515 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2516 self.active_worktree_override = None;
2517 cx.notify();
2518 }
2519
2520 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2521 ///
2522 /// If the given workspace has a local project, then it will be passed
2523 /// to the callback. Otherwise, a new empty window will be created.
2524 pub fn with_local_workspace<T, F>(
2525 &mut self,
2526 window: &mut Window,
2527 cx: &mut Context<Self>,
2528 callback: F,
2529 ) -> Task<Result<T>>
2530 where
2531 T: 'static,
2532 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2533 {
2534 if self.project.read(cx).is_local() {
2535 Task::ready(Ok(callback(self, window, cx)))
2536 } else {
2537 let env = self.project.read(cx).cli_environment(cx);
2538 let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, None, cx);
2539 cx.spawn_in(window, async move |_vh, cx| {
2540 let (multi_workspace_window, _) = task.await?;
2541 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2542 let workspace = multi_workspace.workspace().clone();
2543 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2544 })
2545 })
2546 }
2547 }
2548
2549 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2550 ///
2551 /// If the given workspace has a local project, then it will be passed
2552 /// to the callback. Otherwise, a new empty window will be created.
2553 pub fn with_local_or_wsl_workspace<T, F>(
2554 &mut self,
2555 window: &mut Window,
2556 cx: &mut Context<Self>,
2557 callback: F,
2558 ) -> Task<Result<T>>
2559 where
2560 T: 'static,
2561 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2562 {
2563 let project = self.project.read(cx);
2564 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
2565 Task::ready(Ok(callback(self, window, cx)))
2566 } else {
2567 let env = self.project.read(cx).cli_environment(cx);
2568 let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, None, cx);
2569 cx.spawn_in(window, async move |_vh, cx| {
2570 let (multi_workspace_window, _) = task.await?;
2571 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2572 let workspace = multi_workspace.workspace().clone();
2573 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2574 })
2575 })
2576 }
2577 }
2578
2579 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2580 self.project.read(cx).worktrees(cx)
2581 }
2582
2583 pub fn visible_worktrees<'a>(
2584 &self,
2585 cx: &'a App,
2586 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2587 self.project.read(cx).visible_worktrees(cx)
2588 }
2589
2590 #[cfg(any(test, feature = "test-support"))]
2591 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
2592 let futures = self
2593 .worktrees(cx)
2594 .filter_map(|worktree| worktree.read(cx).as_local())
2595 .map(|worktree| worktree.scan_complete())
2596 .collect::<Vec<_>>();
2597 async move {
2598 for future in futures {
2599 future.await;
2600 }
2601 }
2602 }
2603
2604 pub fn close_global(cx: &mut App) {
2605 cx.defer(|cx| {
2606 cx.windows().iter().find(|window| {
2607 window
2608 .update(cx, |_, window, _| {
2609 if window.is_window_active() {
2610 //This can only get called when the window's project connection has been lost
2611 //so we don't need to prompt the user for anything and instead just close the window
2612 window.remove_window();
2613 true
2614 } else {
2615 false
2616 }
2617 })
2618 .unwrap_or(false)
2619 });
2620 });
2621 }
2622
2623 pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
2624 let prepare = self.prepare_to_close(CloseIntent::CloseWindow, window, cx);
2625 cx.spawn_in(window, async move |_, cx| {
2626 if prepare.await? {
2627 cx.update(|window, _cx| window.remove_window())?;
2628 }
2629 anyhow::Ok(())
2630 })
2631 .detach_and_log_err(cx)
2632 }
2633
2634 pub fn move_focused_panel_to_next_position(
2635 &mut self,
2636 _: &MoveFocusedPanelToNextPosition,
2637 window: &mut Window,
2638 cx: &mut Context<Self>,
2639 ) {
2640 let docks = self.all_docks();
2641 let active_dock = docks
2642 .into_iter()
2643 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
2644
2645 if let Some(dock) = active_dock {
2646 dock.update(cx, |dock, cx| {
2647 let active_panel = dock
2648 .active_panel()
2649 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
2650
2651 if let Some(panel) = active_panel {
2652 panel.move_to_next_position(window, cx);
2653 }
2654 })
2655 }
2656 }
2657
2658 pub fn prepare_to_close(
2659 &mut self,
2660 close_intent: CloseIntent,
2661 window: &mut Window,
2662 cx: &mut Context<Self>,
2663 ) -> Task<Result<bool>> {
2664 let active_call = self.active_call().cloned();
2665
2666 cx.spawn_in(window, async move |this, cx| {
2667 this.update(cx, |this, _| {
2668 if close_intent == CloseIntent::CloseWindow {
2669 this.removing = true;
2670 }
2671 })?;
2672
2673 let workspace_count = cx.update(|_window, cx| {
2674 cx.windows()
2675 .iter()
2676 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
2677 .count()
2678 })?;
2679
2680 #[cfg(target_os = "macos")]
2681 let save_last_workspace = false;
2682
2683 // On Linux and Windows, closing the last window should restore the last workspace.
2684 #[cfg(not(target_os = "macos"))]
2685 let save_last_workspace = {
2686 let remaining_workspaces = cx.update(|_window, cx| {
2687 cx.windows()
2688 .iter()
2689 .filter_map(|window| window.downcast::<MultiWorkspace>())
2690 .filter_map(|multi_workspace| {
2691 multi_workspace
2692 .update(cx, |multi_workspace, _, cx| {
2693 multi_workspace.workspace().read(cx).removing
2694 })
2695 .ok()
2696 })
2697 .filter(|removing| !removing)
2698 .count()
2699 })?;
2700
2701 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
2702 };
2703
2704 if let Some(active_call) = active_call
2705 && workspace_count == 1
2706 && active_call.read_with(cx, |call, _| call.room().is_some())
2707 {
2708 if close_intent == CloseIntent::CloseWindow {
2709 let answer = cx.update(|window, cx| {
2710 window.prompt(
2711 PromptLevel::Warning,
2712 "Do you want to leave the current call?",
2713 None,
2714 &["Close window and hang up", "Cancel"],
2715 cx,
2716 )
2717 })?;
2718
2719 if answer.await.log_err() == Some(1) {
2720 return anyhow::Ok(false);
2721 } else {
2722 active_call
2723 .update(cx, |call, cx| call.hang_up(cx))
2724 .await
2725 .log_err();
2726 }
2727 }
2728 if close_intent == CloseIntent::ReplaceWindow {
2729 _ = active_call.update(cx, |this, cx| {
2730 let multi_workspace = cx
2731 .windows()
2732 .iter()
2733 .filter_map(|window| window.downcast::<MultiWorkspace>())
2734 .next()
2735 .unwrap();
2736 let project = multi_workspace
2737 .read(cx)?
2738 .workspace()
2739 .read(cx)
2740 .project
2741 .clone();
2742 if project.read(cx).is_shared() {
2743 this.unshare_project(project, cx)?;
2744 }
2745 Ok::<_, anyhow::Error>(())
2746 })?;
2747 }
2748 }
2749
2750 let save_result = this
2751 .update_in(cx, |this, window, cx| {
2752 this.save_all_internal(SaveIntent::Close, window, cx)
2753 })?
2754 .await;
2755
2756 // If we're not quitting, but closing, we remove the workspace from
2757 // the current session.
2758 if close_intent != CloseIntent::Quit
2759 && !save_last_workspace
2760 && save_result.as_ref().is_ok_and(|&res| res)
2761 {
2762 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
2763 .await;
2764 }
2765
2766 save_result
2767 })
2768 }
2769
2770 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
2771 self.save_all_internal(
2772 action.save_intent.unwrap_or(SaveIntent::SaveAll),
2773 window,
2774 cx,
2775 )
2776 .detach_and_log_err(cx);
2777 }
2778
2779 fn send_keystrokes(
2780 &mut self,
2781 action: &SendKeystrokes,
2782 window: &mut Window,
2783 cx: &mut Context<Self>,
2784 ) {
2785 let keystrokes: Vec<Keystroke> = action
2786 .0
2787 .split(' ')
2788 .flat_map(|k| Keystroke::parse(k).log_err())
2789 .map(|k| {
2790 cx.keyboard_mapper()
2791 .map_key_equivalent(k, false)
2792 .inner()
2793 .clone()
2794 })
2795 .collect();
2796 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
2797 }
2798
2799 pub fn send_keystrokes_impl(
2800 &mut self,
2801 keystrokes: Vec<Keystroke>,
2802 window: &mut Window,
2803 cx: &mut Context<Self>,
2804 ) -> Shared<Task<()>> {
2805 let mut state = self.dispatching_keystrokes.borrow_mut();
2806 if !state.dispatched.insert(keystrokes.clone()) {
2807 cx.propagate();
2808 return state.task.clone().unwrap();
2809 }
2810
2811 state.queue.extend(keystrokes);
2812
2813 let keystrokes = self.dispatching_keystrokes.clone();
2814 if state.task.is_none() {
2815 state.task = Some(
2816 window
2817 .spawn(cx, async move |cx| {
2818 // limit to 100 keystrokes to avoid infinite recursion.
2819 for _ in 0..100 {
2820 let mut state = keystrokes.borrow_mut();
2821 let Some(keystroke) = state.queue.pop_front() else {
2822 state.dispatched.clear();
2823 state.task.take();
2824 return;
2825 };
2826 drop(state);
2827 cx.update(|window, cx| {
2828 let focused = window.focused(cx);
2829 window.dispatch_keystroke(keystroke.clone(), cx);
2830 if window.focused(cx) != focused {
2831 // dispatch_keystroke may cause the focus to change.
2832 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
2833 // And we need that to happen before the next keystroke to keep vim mode happy...
2834 // (Note that the tests always do this implicitly, so you must manually test with something like:
2835 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
2836 // )
2837 window.draw(cx).clear();
2838 }
2839 })
2840 .ok();
2841 }
2842
2843 *keystrokes.borrow_mut() = Default::default();
2844 log::error!("over 100 keystrokes passed to send_keystrokes");
2845 })
2846 .shared(),
2847 );
2848 }
2849 state.task.clone().unwrap()
2850 }
2851
2852 fn save_all_internal(
2853 &mut self,
2854 mut save_intent: SaveIntent,
2855 window: &mut Window,
2856 cx: &mut Context<Self>,
2857 ) -> Task<Result<bool>> {
2858 if self.project.read(cx).is_disconnected(cx) {
2859 return Task::ready(Ok(true));
2860 }
2861 let dirty_items = self
2862 .panes
2863 .iter()
2864 .flat_map(|pane| {
2865 pane.read(cx).items().filter_map(|item| {
2866 if item.is_dirty(cx) {
2867 item.tab_content_text(0, cx);
2868 Some((pane.downgrade(), item.boxed_clone()))
2869 } else {
2870 None
2871 }
2872 })
2873 })
2874 .collect::<Vec<_>>();
2875
2876 let project = self.project.clone();
2877 cx.spawn_in(window, async move |workspace, cx| {
2878 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
2879 let (serialize_tasks, remaining_dirty_items) =
2880 workspace.update_in(cx, |workspace, window, cx| {
2881 let mut remaining_dirty_items = Vec::new();
2882 let mut serialize_tasks = Vec::new();
2883 for (pane, item) in dirty_items {
2884 if let Some(task) = item
2885 .to_serializable_item_handle(cx)
2886 .and_then(|handle| handle.serialize(workspace, true, window, cx))
2887 {
2888 serialize_tasks.push(task);
2889 } else {
2890 remaining_dirty_items.push((pane, item));
2891 }
2892 }
2893 (serialize_tasks, remaining_dirty_items)
2894 })?;
2895
2896 futures::future::try_join_all(serialize_tasks).await?;
2897
2898 if remaining_dirty_items.len() > 1 {
2899 let answer = workspace.update_in(cx, |_, window, cx| {
2900 let detail = Pane::file_names_for_prompt(
2901 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
2902 cx,
2903 );
2904 window.prompt(
2905 PromptLevel::Warning,
2906 "Do you want to save all changes in the following files?",
2907 Some(&detail),
2908 &["Save all", "Discard all", "Cancel"],
2909 cx,
2910 )
2911 })?;
2912 match answer.await.log_err() {
2913 Some(0) => save_intent = SaveIntent::SaveAll,
2914 Some(1) => save_intent = SaveIntent::Skip,
2915 Some(2) => return Ok(false),
2916 _ => {}
2917 }
2918 }
2919
2920 remaining_dirty_items
2921 } else {
2922 dirty_items
2923 };
2924
2925 for (pane, item) in dirty_items {
2926 let (singleton, project_entry_ids) = cx.update(|_, cx| {
2927 (
2928 item.buffer_kind(cx) == ItemBufferKind::Singleton,
2929 item.project_entry_ids(cx),
2930 )
2931 })?;
2932 if (singleton || !project_entry_ids.is_empty())
2933 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
2934 {
2935 return Ok(false);
2936 }
2937 }
2938 Ok(true)
2939 })
2940 }
2941
2942 pub fn open_workspace_for_paths(
2943 &mut self,
2944 replace_current_window: bool,
2945 paths: Vec<PathBuf>,
2946 window: &mut Window,
2947 cx: &mut Context<Self>,
2948 ) -> Task<Result<()>> {
2949 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
2950 let is_remote = self.project.read(cx).is_via_collab();
2951 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
2952 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
2953
2954 let window_to_replace = if replace_current_window {
2955 window_handle
2956 } else if is_remote || has_worktree || has_dirty_items {
2957 None
2958 } else {
2959 window_handle
2960 };
2961 let app_state = self.app_state.clone();
2962
2963 cx.spawn(async move |_, cx| {
2964 cx.update(|cx| {
2965 open_paths(
2966 &paths,
2967 app_state,
2968 OpenOptions {
2969 replace_window: window_to_replace,
2970 ..Default::default()
2971 },
2972 cx,
2973 )
2974 })
2975 .await?;
2976 Ok(())
2977 })
2978 }
2979
2980 #[allow(clippy::type_complexity)]
2981 pub fn open_paths(
2982 &mut self,
2983 mut abs_paths: Vec<PathBuf>,
2984 options: OpenOptions,
2985 pane: Option<WeakEntity<Pane>>,
2986 window: &mut Window,
2987 cx: &mut Context<Self>,
2988 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
2989 let fs = self.app_state.fs.clone();
2990
2991 let caller_ordered_abs_paths = abs_paths.clone();
2992
2993 // Sort the paths to ensure we add worktrees for parents before their children.
2994 abs_paths.sort_unstable();
2995 cx.spawn_in(window, async move |this, cx| {
2996 let mut tasks = Vec::with_capacity(abs_paths.len());
2997
2998 for abs_path in &abs_paths {
2999 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3000 OpenVisible::All => Some(true),
3001 OpenVisible::None => Some(false),
3002 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3003 Some(Some(metadata)) => Some(!metadata.is_dir),
3004 Some(None) => Some(true),
3005 None => None,
3006 },
3007 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3008 Some(Some(metadata)) => Some(metadata.is_dir),
3009 Some(None) => Some(false),
3010 None => None,
3011 },
3012 };
3013 let project_path = match visible {
3014 Some(visible) => match this
3015 .update(cx, |this, cx| {
3016 Workspace::project_path_for_path(
3017 this.project.clone(),
3018 abs_path,
3019 visible,
3020 cx,
3021 )
3022 })
3023 .log_err()
3024 {
3025 Some(project_path) => project_path.await.log_err(),
3026 None => None,
3027 },
3028 None => None,
3029 };
3030
3031 let this = this.clone();
3032 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3033 let fs = fs.clone();
3034 let pane = pane.clone();
3035 let task = cx.spawn(async move |cx| {
3036 let (_worktree, project_path) = project_path?;
3037 if fs.is_dir(&abs_path).await {
3038 // Opening a directory should not race to update the active entry.
3039 // We'll select/reveal a deterministic final entry after all paths finish opening.
3040 None
3041 } else {
3042 Some(
3043 this.update_in(cx, |this, window, cx| {
3044 this.open_path(
3045 project_path,
3046 pane,
3047 options.focus.unwrap_or(true),
3048 window,
3049 cx,
3050 )
3051 })
3052 .ok()?
3053 .await,
3054 )
3055 }
3056 });
3057 tasks.push(task);
3058 }
3059
3060 let results = futures::future::join_all(tasks).await;
3061
3062 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3063 let mut winner: Option<(PathBuf, bool)> = None;
3064 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3065 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3066 if !metadata.is_dir {
3067 winner = Some((abs_path, false));
3068 break;
3069 }
3070 if winner.is_none() {
3071 winner = Some((abs_path, true));
3072 }
3073 } else if winner.is_none() {
3074 winner = Some((abs_path, false));
3075 }
3076 }
3077
3078 // Compute the winner entry id on the foreground thread and emit once, after all
3079 // paths finish opening. This avoids races between concurrently-opening paths
3080 // (directories in particular) and makes the resulting project panel selection
3081 // deterministic.
3082 if let Some((winner_abs_path, winner_is_dir)) = winner {
3083 'emit_winner: {
3084 let winner_abs_path: Arc<Path> =
3085 SanitizedPath::new(&winner_abs_path).as_path().into();
3086
3087 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3088 OpenVisible::All => true,
3089 OpenVisible::None => false,
3090 OpenVisible::OnlyFiles => !winner_is_dir,
3091 OpenVisible::OnlyDirectories => winner_is_dir,
3092 };
3093
3094 let Some(worktree_task) = this
3095 .update(cx, |workspace, cx| {
3096 workspace.project.update(cx, |project, cx| {
3097 project.find_or_create_worktree(
3098 winner_abs_path.as_ref(),
3099 visible,
3100 cx,
3101 )
3102 })
3103 })
3104 .ok()
3105 else {
3106 break 'emit_winner;
3107 };
3108
3109 let Ok((worktree, _)) = worktree_task.await else {
3110 break 'emit_winner;
3111 };
3112
3113 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3114 let worktree = worktree.read(cx);
3115 let worktree_abs_path = worktree.abs_path();
3116 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3117 worktree.root_entry()
3118 } else {
3119 winner_abs_path
3120 .strip_prefix(worktree_abs_path.as_ref())
3121 .ok()
3122 .and_then(|relative_path| {
3123 let relative_path =
3124 RelPath::new(relative_path, PathStyle::local())
3125 .log_err()?;
3126 worktree.entry_for_path(&relative_path)
3127 })
3128 }?;
3129 Some(entry.id)
3130 }) else {
3131 break 'emit_winner;
3132 };
3133
3134 this.update(cx, |workspace, cx| {
3135 workspace.project.update(cx, |_, cx| {
3136 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3137 });
3138 })
3139 .ok();
3140 }
3141 }
3142
3143 results
3144 })
3145 }
3146
3147 pub fn open_resolved_path(
3148 &mut self,
3149 path: ResolvedPath,
3150 window: &mut Window,
3151 cx: &mut Context<Self>,
3152 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3153 match path {
3154 ResolvedPath::ProjectPath { project_path, .. } => {
3155 self.open_path(project_path, None, true, window, cx)
3156 }
3157 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3158 PathBuf::from(path),
3159 OpenOptions {
3160 visible: Some(OpenVisible::None),
3161 ..Default::default()
3162 },
3163 window,
3164 cx,
3165 ),
3166 }
3167 }
3168
3169 pub fn absolute_path_of_worktree(
3170 &self,
3171 worktree_id: WorktreeId,
3172 cx: &mut Context<Self>,
3173 ) -> Option<PathBuf> {
3174 self.project
3175 .read(cx)
3176 .worktree_for_id(worktree_id, cx)
3177 // TODO: use `abs_path` or `root_dir`
3178 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3179 }
3180
3181 fn add_folder_to_project(
3182 &mut self,
3183 _: &AddFolderToProject,
3184 window: &mut Window,
3185 cx: &mut Context<Self>,
3186 ) {
3187 let project = self.project.read(cx);
3188 if project.is_via_collab() {
3189 self.show_error(
3190 &anyhow!("You cannot add folders to someone else's project"),
3191 cx,
3192 );
3193 return;
3194 }
3195 let paths = self.prompt_for_open_path(
3196 PathPromptOptions {
3197 files: false,
3198 directories: true,
3199 multiple: true,
3200 prompt: None,
3201 },
3202 DirectoryLister::Project(self.project.clone()),
3203 window,
3204 cx,
3205 );
3206 cx.spawn_in(window, async move |this, cx| {
3207 if let Some(paths) = paths.await.log_err().flatten() {
3208 let results = this
3209 .update_in(cx, |this, window, cx| {
3210 this.open_paths(
3211 paths,
3212 OpenOptions {
3213 visible: Some(OpenVisible::All),
3214 ..Default::default()
3215 },
3216 None,
3217 window,
3218 cx,
3219 )
3220 })?
3221 .await;
3222 for result in results.into_iter().flatten() {
3223 result.log_err();
3224 }
3225 }
3226 anyhow::Ok(())
3227 })
3228 .detach_and_log_err(cx);
3229 }
3230
3231 pub fn project_path_for_path(
3232 project: Entity<Project>,
3233 abs_path: &Path,
3234 visible: bool,
3235 cx: &mut App,
3236 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3237 let entry = project.update(cx, |project, cx| {
3238 project.find_or_create_worktree(abs_path, visible, cx)
3239 });
3240 cx.spawn(async move |cx| {
3241 let (worktree, path) = entry.await?;
3242 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3243 Ok((worktree, ProjectPath { worktree_id, path }))
3244 })
3245 }
3246
3247 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3248 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3249 }
3250
3251 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3252 self.items_of_type(cx).max_by_key(|item| item.item_id())
3253 }
3254
3255 pub fn items_of_type<'a, T: Item>(
3256 &'a self,
3257 cx: &'a App,
3258 ) -> impl 'a + Iterator<Item = Entity<T>> {
3259 self.panes
3260 .iter()
3261 .flat_map(|pane| pane.read(cx).items_of_type())
3262 }
3263
3264 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3265 self.active_pane().read(cx).active_item()
3266 }
3267
3268 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3269 let item = self.active_item(cx)?;
3270 item.to_any_view().downcast::<I>().ok()
3271 }
3272
3273 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3274 self.active_item(cx).and_then(|item| item.project_path(cx))
3275 }
3276
3277 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3278 self.recent_navigation_history_iter(cx)
3279 .filter_map(|(path, abs_path)| {
3280 let worktree = self
3281 .project
3282 .read(cx)
3283 .worktree_for_id(path.worktree_id, cx)?;
3284 if worktree.read(cx).is_visible() {
3285 abs_path
3286 } else {
3287 None
3288 }
3289 })
3290 .next()
3291 }
3292
3293 pub fn save_active_item(
3294 &mut self,
3295 save_intent: SaveIntent,
3296 window: &mut Window,
3297 cx: &mut App,
3298 ) -> Task<Result<()>> {
3299 let project = self.project.clone();
3300 let pane = self.active_pane();
3301 let item = pane.read(cx).active_item();
3302 let pane = pane.downgrade();
3303
3304 window.spawn(cx, async move |cx| {
3305 if let Some(item) = item {
3306 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3307 .await
3308 .map(|_| ())
3309 } else {
3310 Ok(())
3311 }
3312 })
3313 }
3314
3315 pub fn close_inactive_items_and_panes(
3316 &mut self,
3317 action: &CloseInactiveTabsAndPanes,
3318 window: &mut Window,
3319 cx: &mut Context<Self>,
3320 ) {
3321 if let Some(task) = self.close_all_internal(
3322 true,
3323 action.save_intent.unwrap_or(SaveIntent::Close),
3324 window,
3325 cx,
3326 ) {
3327 task.detach_and_log_err(cx)
3328 }
3329 }
3330
3331 pub fn close_all_items_and_panes(
3332 &mut self,
3333 action: &CloseAllItemsAndPanes,
3334 window: &mut Window,
3335 cx: &mut Context<Self>,
3336 ) {
3337 if let Some(task) = self.close_all_internal(
3338 false,
3339 action.save_intent.unwrap_or(SaveIntent::Close),
3340 window,
3341 cx,
3342 ) {
3343 task.detach_and_log_err(cx)
3344 }
3345 }
3346
3347 /// Closes the active item across all panes.
3348 pub fn close_item_in_all_panes(
3349 &mut self,
3350 action: &CloseItemInAllPanes,
3351 window: &mut Window,
3352 cx: &mut Context<Self>,
3353 ) {
3354 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3355 return;
3356 };
3357
3358 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3359 let close_pinned = action.close_pinned;
3360
3361 if let Some(project_path) = active_item.project_path(cx) {
3362 self.close_items_with_project_path(
3363 &project_path,
3364 save_intent,
3365 close_pinned,
3366 window,
3367 cx,
3368 );
3369 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3370 let item_id = active_item.item_id();
3371 self.active_pane().update(cx, |pane, cx| {
3372 pane.close_item_by_id(item_id, save_intent, window, cx)
3373 .detach_and_log_err(cx);
3374 });
3375 }
3376 }
3377
3378 /// Closes all items with the given project path across all panes.
3379 pub fn close_items_with_project_path(
3380 &mut self,
3381 project_path: &ProjectPath,
3382 save_intent: SaveIntent,
3383 close_pinned: bool,
3384 window: &mut Window,
3385 cx: &mut Context<Self>,
3386 ) {
3387 let panes = self.panes().to_vec();
3388 for pane in panes {
3389 pane.update(cx, |pane, cx| {
3390 pane.close_items_for_project_path(
3391 project_path,
3392 save_intent,
3393 close_pinned,
3394 window,
3395 cx,
3396 )
3397 .detach_and_log_err(cx);
3398 });
3399 }
3400 }
3401
3402 fn close_all_internal(
3403 &mut self,
3404 retain_active_pane: bool,
3405 save_intent: SaveIntent,
3406 window: &mut Window,
3407 cx: &mut Context<Self>,
3408 ) -> Option<Task<Result<()>>> {
3409 let current_pane = self.active_pane();
3410
3411 let mut tasks = Vec::new();
3412
3413 if retain_active_pane {
3414 let current_pane_close = current_pane.update(cx, |pane, cx| {
3415 pane.close_other_items(
3416 &CloseOtherItems {
3417 save_intent: None,
3418 close_pinned: false,
3419 },
3420 None,
3421 window,
3422 cx,
3423 )
3424 });
3425
3426 tasks.push(current_pane_close);
3427 }
3428
3429 for pane in self.panes() {
3430 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3431 continue;
3432 }
3433
3434 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3435 pane.close_all_items(
3436 &CloseAllItems {
3437 save_intent: Some(save_intent),
3438 close_pinned: false,
3439 },
3440 window,
3441 cx,
3442 )
3443 });
3444
3445 tasks.push(close_pane_items)
3446 }
3447
3448 if tasks.is_empty() {
3449 None
3450 } else {
3451 Some(cx.spawn_in(window, async move |_, _| {
3452 for task in tasks {
3453 task.await?
3454 }
3455 Ok(())
3456 }))
3457 }
3458 }
3459
3460 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3461 self.dock_at_position(position).read(cx).is_open()
3462 }
3463
3464 pub fn toggle_dock(
3465 &mut self,
3466 dock_side: DockPosition,
3467 window: &mut Window,
3468 cx: &mut Context<Self>,
3469 ) {
3470 let mut focus_center = false;
3471 let mut reveal_dock = false;
3472
3473 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3474 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3475
3476 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3477 telemetry::event!(
3478 "Panel Button Clicked",
3479 name = panel.persistent_name(),
3480 toggle_state = !was_visible
3481 );
3482 }
3483 if was_visible {
3484 self.save_open_dock_positions(cx);
3485 }
3486
3487 let dock = self.dock_at_position(dock_side);
3488 dock.update(cx, |dock, cx| {
3489 dock.set_open(!was_visible, window, cx);
3490
3491 if dock.active_panel().is_none() {
3492 let Some(panel_ix) = dock
3493 .first_enabled_panel_idx(cx)
3494 .log_with_level(log::Level::Info)
3495 else {
3496 return;
3497 };
3498 dock.activate_panel(panel_ix, window, cx);
3499 }
3500
3501 if let Some(active_panel) = dock.active_panel() {
3502 if was_visible {
3503 if active_panel
3504 .panel_focus_handle(cx)
3505 .contains_focused(window, cx)
3506 {
3507 focus_center = true;
3508 }
3509 } else {
3510 let focus_handle = &active_panel.panel_focus_handle(cx);
3511 window.focus(focus_handle, cx);
3512 reveal_dock = true;
3513 }
3514 }
3515 });
3516
3517 if reveal_dock {
3518 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3519 }
3520
3521 if focus_center {
3522 self.active_pane
3523 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3524 }
3525
3526 cx.notify();
3527 self.serialize_workspace(window, cx);
3528 }
3529
3530 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3531 self.all_docks().into_iter().find(|&dock| {
3532 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3533 })
3534 }
3535
3536 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3537 if let Some(dock) = self.active_dock(window, cx).cloned() {
3538 self.save_open_dock_positions(cx);
3539 dock.update(cx, |dock, cx| {
3540 dock.set_open(false, window, cx);
3541 });
3542 return true;
3543 }
3544 false
3545 }
3546
3547 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3548 self.save_open_dock_positions(cx);
3549 for dock in self.all_docks() {
3550 dock.update(cx, |dock, cx| {
3551 dock.set_open(false, window, cx);
3552 });
3553 }
3554
3555 cx.focus_self(window);
3556 cx.notify();
3557 self.serialize_workspace(window, cx);
3558 }
3559
3560 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
3561 self.all_docks()
3562 .into_iter()
3563 .filter_map(|dock| {
3564 let dock_ref = dock.read(cx);
3565 if dock_ref.is_open() {
3566 Some(dock_ref.position())
3567 } else {
3568 None
3569 }
3570 })
3571 .collect()
3572 }
3573
3574 /// Saves the positions of currently open docks.
3575 ///
3576 /// Updates `last_open_dock_positions` with positions of all currently open
3577 /// docks, to later be restored by the 'Toggle All Docks' action.
3578 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
3579 let open_dock_positions = self.get_open_dock_positions(cx);
3580 if !open_dock_positions.is_empty() {
3581 self.last_open_dock_positions = open_dock_positions;
3582 }
3583 }
3584
3585 /// Toggles all docks between open and closed states.
3586 ///
3587 /// If any docks are open, closes all and remembers their positions. If all
3588 /// docks are closed, restores the last remembered dock configuration.
3589 fn toggle_all_docks(
3590 &mut self,
3591 _: &ToggleAllDocks,
3592 window: &mut Window,
3593 cx: &mut Context<Self>,
3594 ) {
3595 let open_dock_positions = self.get_open_dock_positions(cx);
3596
3597 if !open_dock_positions.is_empty() {
3598 self.close_all_docks(window, cx);
3599 } else if !self.last_open_dock_positions.is_empty() {
3600 self.restore_last_open_docks(window, cx);
3601 }
3602 }
3603
3604 /// Reopens docks from the most recently remembered configuration.
3605 ///
3606 /// Opens all docks whose positions are stored in `last_open_dock_positions`
3607 /// and clears the stored positions.
3608 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3609 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
3610
3611 for position in positions_to_open {
3612 let dock = self.dock_at_position(position);
3613 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
3614 }
3615
3616 cx.focus_self(window);
3617 cx.notify();
3618 self.serialize_workspace(window, cx);
3619 }
3620
3621 /// Transfer focus to the panel of the given type.
3622 pub fn focus_panel<T: Panel>(
3623 &mut self,
3624 window: &mut Window,
3625 cx: &mut Context<Self>,
3626 ) -> Option<Entity<T>> {
3627 let panel = self.focus_or_unfocus_panel::<T>(window, cx, |_, _, _| true)?;
3628 panel.to_any().downcast().ok()
3629 }
3630
3631 /// Focus the panel of the given type if it isn't already focused. If it is
3632 /// already focused, then transfer focus back to the workspace center.
3633 pub fn toggle_panel_focus<T: Panel>(
3634 &mut self,
3635 window: &mut Window,
3636 cx: &mut Context<Self>,
3637 ) -> bool {
3638 let mut did_focus_panel = false;
3639 self.focus_or_unfocus_panel::<T>(window, cx, |panel, window, cx| {
3640 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
3641 did_focus_panel
3642 });
3643
3644 telemetry::event!(
3645 "Panel Button Clicked",
3646 name = T::persistent_name(),
3647 toggle_state = did_focus_panel
3648 );
3649
3650 did_focus_panel
3651 }
3652
3653 pub fn activate_panel_for_proto_id(
3654 &mut self,
3655 panel_id: PanelId,
3656 window: &mut Window,
3657 cx: &mut Context<Self>,
3658 ) -> Option<Arc<dyn PanelHandle>> {
3659 let mut panel = None;
3660 for dock in self.all_docks() {
3661 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
3662 panel = dock.update(cx, |dock, cx| {
3663 dock.activate_panel(panel_index, window, cx);
3664 dock.set_open(true, window, cx);
3665 dock.active_panel().cloned()
3666 });
3667 break;
3668 }
3669 }
3670
3671 if panel.is_some() {
3672 cx.notify();
3673 self.serialize_workspace(window, cx);
3674 }
3675
3676 panel
3677 }
3678
3679 /// Focus or unfocus the given panel type, depending on the given callback.
3680 fn focus_or_unfocus_panel<T: Panel>(
3681 &mut self,
3682 window: &mut Window,
3683 cx: &mut Context<Self>,
3684 mut should_focus: impl FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
3685 ) -> Option<Arc<dyn PanelHandle>> {
3686 let mut result_panel = None;
3687 let mut serialize = false;
3688 for dock in self.all_docks() {
3689 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3690 let mut focus_center = false;
3691 let panel = dock.update(cx, |dock, cx| {
3692 dock.activate_panel(panel_index, window, cx);
3693
3694 let panel = dock.active_panel().cloned();
3695 if let Some(panel) = panel.as_ref() {
3696 if should_focus(&**panel, window, cx) {
3697 dock.set_open(true, window, cx);
3698 panel.panel_focus_handle(cx).focus(window, cx);
3699 } else {
3700 focus_center = true;
3701 }
3702 }
3703 panel
3704 });
3705
3706 if focus_center {
3707 self.active_pane
3708 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3709 }
3710
3711 result_panel = panel;
3712 serialize = true;
3713 break;
3714 }
3715 }
3716
3717 if serialize {
3718 self.serialize_workspace(window, cx);
3719 }
3720
3721 cx.notify();
3722 result_panel
3723 }
3724
3725 /// Open the panel of the given type
3726 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3727 for dock in self.all_docks() {
3728 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3729 dock.update(cx, |dock, cx| {
3730 dock.activate_panel(panel_index, window, cx);
3731 dock.set_open(true, window, cx);
3732 });
3733 }
3734 }
3735 }
3736
3737 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
3738 for dock in self.all_docks().iter() {
3739 dock.update(cx, |dock, cx| {
3740 if dock.panel::<T>().is_some() {
3741 dock.set_open(false, window, cx)
3742 }
3743 })
3744 }
3745 }
3746
3747 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
3748 self.all_docks()
3749 .iter()
3750 .find_map(|dock| dock.read(cx).panel::<T>())
3751 }
3752
3753 fn dismiss_zoomed_items_to_reveal(
3754 &mut self,
3755 dock_to_reveal: Option<DockPosition>,
3756 window: &mut Window,
3757 cx: &mut Context<Self>,
3758 ) {
3759 // If a center pane is zoomed, unzoom it.
3760 for pane in &self.panes {
3761 if pane != &self.active_pane || dock_to_reveal.is_some() {
3762 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
3763 }
3764 }
3765
3766 // If another dock is zoomed, hide it.
3767 let mut focus_center = false;
3768 for dock in self.all_docks() {
3769 dock.update(cx, |dock, cx| {
3770 if Some(dock.position()) != dock_to_reveal
3771 && let Some(panel) = dock.active_panel()
3772 && panel.is_zoomed(window, cx)
3773 {
3774 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
3775 dock.set_open(false, window, cx);
3776 }
3777 });
3778 }
3779
3780 if focus_center {
3781 self.active_pane
3782 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3783 }
3784
3785 if self.zoomed_position != dock_to_reveal {
3786 self.zoomed = None;
3787 self.zoomed_position = None;
3788 cx.emit(Event::ZoomChanged);
3789 }
3790
3791 cx.notify();
3792 }
3793
3794 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
3795 let pane = cx.new(|cx| {
3796 let mut pane = Pane::new(
3797 self.weak_handle(),
3798 self.project.clone(),
3799 self.pane_history_timestamp.clone(),
3800 None,
3801 NewFile.boxed_clone(),
3802 true,
3803 window,
3804 cx,
3805 );
3806 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
3807 pane
3808 });
3809 cx.subscribe_in(&pane, window, Self::handle_pane_event)
3810 .detach();
3811 self.panes.push(pane.clone());
3812
3813 window.focus(&pane.focus_handle(cx), cx);
3814
3815 cx.emit(Event::PaneAdded(pane.clone()));
3816 pane
3817 }
3818
3819 pub fn add_item_to_center(
3820 &mut self,
3821 item: Box<dyn ItemHandle>,
3822 window: &mut Window,
3823 cx: &mut Context<Self>,
3824 ) -> bool {
3825 if let Some(center_pane) = self.last_active_center_pane.clone() {
3826 if let Some(center_pane) = center_pane.upgrade() {
3827 center_pane.update(cx, |pane, cx| {
3828 pane.add_item(item, true, true, None, window, cx)
3829 });
3830 true
3831 } else {
3832 false
3833 }
3834 } else {
3835 false
3836 }
3837 }
3838
3839 pub fn add_item_to_active_pane(
3840 &mut self,
3841 item: Box<dyn ItemHandle>,
3842 destination_index: Option<usize>,
3843 focus_item: bool,
3844 window: &mut Window,
3845 cx: &mut App,
3846 ) {
3847 self.add_item(
3848 self.active_pane.clone(),
3849 item,
3850 destination_index,
3851 false,
3852 focus_item,
3853 window,
3854 cx,
3855 )
3856 }
3857
3858 pub fn add_item(
3859 &mut self,
3860 pane: Entity<Pane>,
3861 item: Box<dyn ItemHandle>,
3862 destination_index: Option<usize>,
3863 activate_pane: bool,
3864 focus_item: bool,
3865 window: &mut Window,
3866 cx: &mut App,
3867 ) {
3868 pane.update(cx, |pane, cx| {
3869 pane.add_item(
3870 item,
3871 activate_pane,
3872 focus_item,
3873 destination_index,
3874 window,
3875 cx,
3876 )
3877 });
3878 }
3879
3880 pub fn split_item(
3881 &mut self,
3882 split_direction: SplitDirection,
3883 item: Box<dyn ItemHandle>,
3884 window: &mut Window,
3885 cx: &mut Context<Self>,
3886 ) {
3887 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
3888 self.add_item(new_pane, item, None, true, true, window, cx);
3889 }
3890
3891 pub fn open_abs_path(
3892 &mut self,
3893 abs_path: PathBuf,
3894 options: OpenOptions,
3895 window: &mut Window,
3896 cx: &mut Context<Self>,
3897 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3898 cx.spawn_in(window, async move |workspace, cx| {
3899 let open_paths_task_result = workspace
3900 .update_in(cx, |workspace, window, cx| {
3901 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
3902 })
3903 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
3904 .await;
3905 anyhow::ensure!(
3906 open_paths_task_result.len() == 1,
3907 "open abs path {abs_path:?} task returned incorrect number of results"
3908 );
3909 match open_paths_task_result
3910 .into_iter()
3911 .next()
3912 .expect("ensured single task result")
3913 {
3914 Some(open_result) => {
3915 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
3916 }
3917 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
3918 }
3919 })
3920 }
3921
3922 pub fn split_abs_path(
3923 &mut self,
3924 abs_path: PathBuf,
3925 visible: bool,
3926 window: &mut Window,
3927 cx: &mut Context<Self>,
3928 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3929 let project_path_task =
3930 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
3931 cx.spawn_in(window, async move |this, cx| {
3932 let (_, path) = project_path_task.await?;
3933 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
3934 .await
3935 })
3936 }
3937
3938 pub fn open_path(
3939 &mut self,
3940 path: impl Into<ProjectPath>,
3941 pane: Option<WeakEntity<Pane>>,
3942 focus_item: bool,
3943 window: &mut Window,
3944 cx: &mut App,
3945 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3946 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
3947 }
3948
3949 pub fn open_path_preview(
3950 &mut self,
3951 path: impl Into<ProjectPath>,
3952 pane: Option<WeakEntity<Pane>>,
3953 focus_item: bool,
3954 allow_preview: bool,
3955 activate: bool,
3956 window: &mut Window,
3957 cx: &mut App,
3958 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3959 let pane = pane.unwrap_or_else(|| {
3960 self.last_active_center_pane.clone().unwrap_or_else(|| {
3961 self.panes
3962 .first()
3963 .expect("There must be an active pane")
3964 .downgrade()
3965 })
3966 });
3967
3968 let project_path = path.into();
3969 let task = self.load_path(project_path.clone(), window, cx);
3970 window.spawn(cx, async move |cx| {
3971 let (project_entry_id, build_item) = task.await?;
3972
3973 pane.update_in(cx, |pane, window, cx| {
3974 pane.open_item(
3975 project_entry_id,
3976 project_path,
3977 focus_item,
3978 allow_preview,
3979 activate,
3980 None,
3981 window,
3982 cx,
3983 build_item,
3984 )
3985 })
3986 })
3987 }
3988
3989 pub fn split_path(
3990 &mut self,
3991 path: impl Into<ProjectPath>,
3992 window: &mut Window,
3993 cx: &mut Context<Self>,
3994 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3995 self.split_path_preview(path, false, None, window, cx)
3996 }
3997
3998 pub fn split_path_preview(
3999 &mut self,
4000 path: impl Into<ProjectPath>,
4001 allow_preview: bool,
4002 split_direction: Option<SplitDirection>,
4003 window: &mut Window,
4004 cx: &mut Context<Self>,
4005 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4006 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4007 self.panes
4008 .first()
4009 .expect("There must be an active pane")
4010 .downgrade()
4011 });
4012
4013 if let Member::Pane(center_pane) = &self.center.root
4014 && center_pane.read(cx).items_len() == 0
4015 {
4016 return self.open_path(path, Some(pane), true, window, cx);
4017 }
4018
4019 let project_path = path.into();
4020 let task = self.load_path(project_path.clone(), window, cx);
4021 cx.spawn_in(window, async move |this, cx| {
4022 let (project_entry_id, build_item) = task.await?;
4023 this.update_in(cx, move |this, window, cx| -> Option<_> {
4024 let pane = pane.upgrade()?;
4025 let new_pane = this.split_pane(
4026 pane,
4027 split_direction.unwrap_or(SplitDirection::Right),
4028 window,
4029 cx,
4030 );
4031 new_pane.update(cx, |new_pane, cx| {
4032 Some(new_pane.open_item(
4033 project_entry_id,
4034 project_path,
4035 true,
4036 allow_preview,
4037 true,
4038 None,
4039 window,
4040 cx,
4041 build_item,
4042 ))
4043 })
4044 })
4045 .map(|option| option.context("pane was dropped"))?
4046 })
4047 }
4048
4049 fn load_path(
4050 &mut self,
4051 path: ProjectPath,
4052 window: &mut Window,
4053 cx: &mut App,
4054 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4055 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4056 registry.open_path(self.project(), &path, window, cx)
4057 }
4058
4059 pub fn find_project_item<T>(
4060 &self,
4061 pane: &Entity<Pane>,
4062 project_item: &Entity<T::Item>,
4063 cx: &App,
4064 ) -> Option<Entity<T>>
4065 where
4066 T: ProjectItem,
4067 {
4068 use project::ProjectItem as _;
4069 let project_item = project_item.read(cx);
4070 let entry_id = project_item.entry_id(cx);
4071 let project_path = project_item.project_path(cx);
4072
4073 let mut item = None;
4074 if let Some(entry_id) = entry_id {
4075 item = pane.read(cx).item_for_entry(entry_id, cx);
4076 }
4077 if item.is_none()
4078 && let Some(project_path) = project_path
4079 {
4080 item = pane.read(cx).item_for_path(project_path, cx);
4081 }
4082
4083 item.and_then(|item| item.downcast::<T>())
4084 }
4085
4086 pub fn is_project_item_open<T>(
4087 &self,
4088 pane: &Entity<Pane>,
4089 project_item: &Entity<T::Item>,
4090 cx: &App,
4091 ) -> bool
4092 where
4093 T: ProjectItem,
4094 {
4095 self.find_project_item::<T>(pane, project_item, cx)
4096 .is_some()
4097 }
4098
4099 pub fn open_project_item<T>(
4100 &mut self,
4101 pane: Entity<Pane>,
4102 project_item: Entity<T::Item>,
4103 activate_pane: bool,
4104 focus_item: bool,
4105 keep_old_preview: bool,
4106 allow_new_preview: bool,
4107 window: &mut Window,
4108 cx: &mut Context<Self>,
4109 ) -> Entity<T>
4110 where
4111 T: ProjectItem,
4112 {
4113 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4114
4115 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4116 if !keep_old_preview
4117 && let Some(old_id) = old_item_id
4118 && old_id != item.item_id()
4119 {
4120 // switching to a different item, so unpreview old active item
4121 pane.update(cx, |pane, _| {
4122 pane.unpreview_item_if_preview(old_id);
4123 });
4124 }
4125
4126 self.activate_item(&item, activate_pane, focus_item, window, cx);
4127 if !allow_new_preview {
4128 pane.update(cx, |pane, _| {
4129 pane.unpreview_item_if_preview(item.item_id());
4130 });
4131 }
4132 return item;
4133 }
4134
4135 let item = pane.update(cx, |pane, cx| {
4136 cx.new(|cx| {
4137 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4138 })
4139 });
4140 let mut destination_index = None;
4141 pane.update(cx, |pane, cx| {
4142 if !keep_old_preview && let Some(old_id) = old_item_id {
4143 pane.unpreview_item_if_preview(old_id);
4144 }
4145 if allow_new_preview {
4146 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4147 }
4148 });
4149
4150 self.add_item(
4151 pane,
4152 Box::new(item.clone()),
4153 destination_index,
4154 activate_pane,
4155 focus_item,
4156 window,
4157 cx,
4158 );
4159 item
4160 }
4161
4162 pub fn open_shared_screen(
4163 &mut self,
4164 peer_id: PeerId,
4165 window: &mut Window,
4166 cx: &mut Context<Self>,
4167 ) {
4168 if let Some(shared_screen) =
4169 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4170 {
4171 self.active_pane.update(cx, |pane, cx| {
4172 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4173 });
4174 }
4175 }
4176
4177 pub fn activate_item(
4178 &mut self,
4179 item: &dyn ItemHandle,
4180 activate_pane: bool,
4181 focus_item: bool,
4182 window: &mut Window,
4183 cx: &mut App,
4184 ) -> bool {
4185 let result = self.panes.iter().find_map(|pane| {
4186 pane.read(cx)
4187 .index_for_item(item)
4188 .map(|ix| (pane.clone(), ix))
4189 });
4190 if let Some((pane, ix)) = result {
4191 pane.update(cx, |pane, cx| {
4192 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4193 });
4194 true
4195 } else {
4196 false
4197 }
4198 }
4199
4200 fn activate_pane_at_index(
4201 &mut self,
4202 action: &ActivatePane,
4203 window: &mut Window,
4204 cx: &mut Context<Self>,
4205 ) {
4206 let panes = self.center.panes();
4207 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4208 window.focus(&pane.focus_handle(cx), cx);
4209 } else {
4210 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4211 .detach();
4212 }
4213 }
4214
4215 fn move_item_to_pane_at_index(
4216 &mut self,
4217 action: &MoveItemToPane,
4218 window: &mut Window,
4219 cx: &mut Context<Self>,
4220 ) {
4221 let panes = self.center.panes();
4222 let destination = match panes.get(action.destination) {
4223 Some(&destination) => destination.clone(),
4224 None => {
4225 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4226 return;
4227 }
4228 let direction = SplitDirection::Right;
4229 let split_off_pane = self
4230 .find_pane_in_direction(direction, cx)
4231 .unwrap_or_else(|| self.active_pane.clone());
4232 let new_pane = self.add_pane(window, cx);
4233 if self
4234 .center
4235 .split(&split_off_pane, &new_pane, direction, cx)
4236 .log_err()
4237 .is_none()
4238 {
4239 return;
4240 };
4241 new_pane
4242 }
4243 };
4244
4245 if action.clone {
4246 if self
4247 .active_pane
4248 .read(cx)
4249 .active_item()
4250 .is_some_and(|item| item.can_split(cx))
4251 {
4252 clone_active_item(
4253 self.database_id(),
4254 &self.active_pane,
4255 &destination,
4256 action.focus,
4257 window,
4258 cx,
4259 );
4260 return;
4261 }
4262 }
4263 move_active_item(
4264 &self.active_pane,
4265 &destination,
4266 action.focus,
4267 true,
4268 window,
4269 cx,
4270 )
4271 }
4272
4273 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4274 let panes = self.center.panes();
4275 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4276 let next_ix = (ix + 1) % panes.len();
4277 let next_pane = panes[next_ix].clone();
4278 window.focus(&next_pane.focus_handle(cx), cx);
4279 }
4280 }
4281
4282 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4283 let panes = self.center.panes();
4284 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4285 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4286 let prev_pane = panes[prev_ix].clone();
4287 window.focus(&prev_pane.focus_handle(cx), cx);
4288 }
4289 }
4290
4291 pub fn activate_pane_in_direction(
4292 &mut self,
4293 direction: SplitDirection,
4294 window: &mut Window,
4295 cx: &mut App,
4296 ) {
4297 use ActivateInDirectionTarget as Target;
4298 enum Origin {
4299 LeftDock,
4300 RightDock,
4301 BottomDock,
4302 Center,
4303 }
4304
4305 let origin: Origin = [
4306 (&self.left_dock, Origin::LeftDock),
4307 (&self.right_dock, Origin::RightDock),
4308 (&self.bottom_dock, Origin::BottomDock),
4309 ]
4310 .into_iter()
4311 .find_map(|(dock, origin)| {
4312 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4313 Some(origin)
4314 } else {
4315 None
4316 }
4317 })
4318 .unwrap_or(Origin::Center);
4319
4320 let get_last_active_pane = || {
4321 let pane = self
4322 .last_active_center_pane
4323 .clone()
4324 .unwrap_or_else(|| {
4325 self.panes
4326 .first()
4327 .expect("There must be an active pane")
4328 .downgrade()
4329 })
4330 .upgrade()?;
4331 (pane.read(cx).items_len() != 0).then_some(pane)
4332 };
4333
4334 let try_dock =
4335 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4336
4337 let target = match (origin, direction) {
4338 // We're in the center, so we first try to go to a different pane,
4339 // otherwise try to go to a dock.
4340 (Origin::Center, direction) => {
4341 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4342 Some(Target::Pane(pane))
4343 } else {
4344 match direction {
4345 SplitDirection::Up => None,
4346 SplitDirection::Down => try_dock(&self.bottom_dock),
4347 SplitDirection::Left => try_dock(&self.left_dock),
4348 SplitDirection::Right => try_dock(&self.right_dock),
4349 }
4350 }
4351 }
4352
4353 (Origin::LeftDock, SplitDirection::Right) => {
4354 if let Some(last_active_pane) = get_last_active_pane() {
4355 Some(Target::Pane(last_active_pane))
4356 } else {
4357 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4358 }
4359 }
4360
4361 (Origin::LeftDock, SplitDirection::Down)
4362 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4363
4364 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4365 (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
4366 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4367
4368 (Origin::RightDock, SplitDirection::Left) => {
4369 if let Some(last_active_pane) = get_last_active_pane() {
4370 Some(Target::Pane(last_active_pane))
4371 } else {
4372 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
4373 }
4374 }
4375
4376 _ => None,
4377 };
4378
4379 match target {
4380 Some(ActivateInDirectionTarget::Pane(pane)) => {
4381 let pane = pane.read(cx);
4382 if let Some(item) = pane.active_item() {
4383 item.item_focus_handle(cx).focus(window, cx);
4384 } else {
4385 log::error!(
4386 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4387 );
4388 }
4389 }
4390 Some(ActivateInDirectionTarget::Dock(dock)) => {
4391 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4392 window.defer(cx, move |window, cx| {
4393 let dock = dock.read(cx);
4394 if let Some(panel) = dock.active_panel() {
4395 panel.panel_focus_handle(cx).focus(window, cx);
4396 } else {
4397 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4398 }
4399 })
4400 }
4401 None => {}
4402 }
4403 }
4404
4405 pub fn move_item_to_pane_in_direction(
4406 &mut self,
4407 action: &MoveItemToPaneInDirection,
4408 window: &mut Window,
4409 cx: &mut Context<Self>,
4410 ) {
4411 let destination = match self.find_pane_in_direction(action.direction, cx) {
4412 Some(destination) => destination,
4413 None => {
4414 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4415 return;
4416 }
4417 let new_pane = self.add_pane(window, cx);
4418 if self
4419 .center
4420 .split(&self.active_pane, &new_pane, action.direction, cx)
4421 .log_err()
4422 .is_none()
4423 {
4424 return;
4425 };
4426 new_pane
4427 }
4428 };
4429
4430 if action.clone {
4431 if self
4432 .active_pane
4433 .read(cx)
4434 .active_item()
4435 .is_some_and(|item| item.can_split(cx))
4436 {
4437 clone_active_item(
4438 self.database_id(),
4439 &self.active_pane,
4440 &destination,
4441 action.focus,
4442 window,
4443 cx,
4444 );
4445 return;
4446 }
4447 }
4448 move_active_item(
4449 &self.active_pane,
4450 &destination,
4451 action.focus,
4452 true,
4453 window,
4454 cx,
4455 );
4456 }
4457
4458 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4459 self.center.bounding_box_for_pane(pane)
4460 }
4461
4462 pub fn find_pane_in_direction(
4463 &mut self,
4464 direction: SplitDirection,
4465 cx: &App,
4466 ) -> Option<Entity<Pane>> {
4467 self.center
4468 .find_pane_in_direction(&self.active_pane, direction, cx)
4469 .cloned()
4470 }
4471
4472 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4473 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4474 self.center.swap(&self.active_pane, &to, cx);
4475 cx.notify();
4476 }
4477 }
4478
4479 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4480 if self
4481 .center
4482 .move_to_border(&self.active_pane, direction, cx)
4483 .unwrap()
4484 {
4485 cx.notify();
4486 }
4487 }
4488
4489 pub fn resize_pane(
4490 &mut self,
4491 axis: gpui::Axis,
4492 amount: Pixels,
4493 window: &mut Window,
4494 cx: &mut Context<Self>,
4495 ) {
4496 let docks = self.all_docks();
4497 let active_dock = docks
4498 .into_iter()
4499 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4500
4501 if let Some(dock) = active_dock {
4502 let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
4503 return;
4504 };
4505 match dock.read(cx).position() {
4506 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4507 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4508 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4509 }
4510 } else {
4511 self.center
4512 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
4513 }
4514 cx.notify();
4515 }
4516
4517 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
4518 self.center.reset_pane_sizes(cx);
4519 cx.notify();
4520 }
4521
4522 fn handle_pane_focused(
4523 &mut self,
4524 pane: Entity<Pane>,
4525 window: &mut Window,
4526 cx: &mut Context<Self>,
4527 ) {
4528 // This is explicitly hoisted out of the following check for pane identity as
4529 // terminal panel panes are not registered as a center panes.
4530 self.status_bar.update(cx, |status_bar, cx| {
4531 status_bar.set_active_pane(&pane, window, cx);
4532 });
4533 if self.active_pane != pane {
4534 self.set_active_pane(&pane, window, cx);
4535 }
4536
4537 if self.last_active_center_pane.is_none() {
4538 self.last_active_center_pane = Some(pane.downgrade());
4539 }
4540
4541 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
4542 // This prevents the dock from closing when focus events fire during window activation.
4543 // We also preserve any dock whose active panel itself has focus — this covers
4544 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
4545 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
4546 let dock_read = dock.read(cx);
4547 if let Some(panel) = dock_read.active_panel() {
4548 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
4549 || panel.panel_focus_handle(cx).contains_focused(window, cx)
4550 {
4551 return Some(dock_read.position());
4552 }
4553 }
4554 None
4555 });
4556
4557 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
4558 if pane.read(cx).is_zoomed() {
4559 self.zoomed = Some(pane.downgrade().into());
4560 } else {
4561 self.zoomed = None;
4562 }
4563 self.zoomed_position = None;
4564 cx.emit(Event::ZoomChanged);
4565 self.update_active_view_for_followers(window, cx);
4566 pane.update(cx, |pane, _| {
4567 pane.track_alternate_file_items();
4568 });
4569
4570 cx.notify();
4571 }
4572
4573 fn set_active_pane(
4574 &mut self,
4575 pane: &Entity<Pane>,
4576 window: &mut Window,
4577 cx: &mut Context<Self>,
4578 ) {
4579 self.active_pane = pane.clone();
4580 self.active_item_path_changed(true, window, cx);
4581 self.last_active_center_pane = Some(pane.downgrade());
4582 }
4583
4584 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4585 self.update_active_view_for_followers(window, cx);
4586 }
4587
4588 fn handle_pane_event(
4589 &mut self,
4590 pane: &Entity<Pane>,
4591 event: &pane::Event,
4592 window: &mut Window,
4593 cx: &mut Context<Self>,
4594 ) {
4595 let mut serialize_workspace = true;
4596 match event {
4597 pane::Event::AddItem { item } => {
4598 item.added_to_pane(self, pane.clone(), window, cx);
4599 cx.emit(Event::ItemAdded {
4600 item: item.boxed_clone(),
4601 });
4602 }
4603 pane::Event::Split { direction, mode } => {
4604 match mode {
4605 SplitMode::ClonePane => {
4606 self.split_and_clone(pane.clone(), *direction, window, cx)
4607 .detach();
4608 }
4609 SplitMode::EmptyPane => {
4610 self.split_pane(pane.clone(), *direction, window, cx);
4611 }
4612 SplitMode::MovePane => {
4613 self.split_and_move(pane.clone(), *direction, window, cx);
4614 }
4615 };
4616 }
4617 pane::Event::JoinIntoNext => {
4618 self.join_pane_into_next(pane.clone(), window, cx);
4619 }
4620 pane::Event::JoinAll => {
4621 self.join_all_panes(window, cx);
4622 }
4623 pane::Event::Remove { focus_on_pane } => {
4624 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
4625 }
4626 pane::Event::ActivateItem {
4627 local,
4628 focus_changed,
4629 } => {
4630 window.invalidate_character_coordinates();
4631
4632 pane.update(cx, |pane, _| {
4633 pane.track_alternate_file_items();
4634 });
4635 if *local {
4636 self.unfollow_in_pane(pane, window, cx);
4637 }
4638 serialize_workspace = *focus_changed || pane != self.active_pane();
4639 if pane == self.active_pane() {
4640 self.active_item_path_changed(*focus_changed, window, cx);
4641 self.update_active_view_for_followers(window, cx);
4642 } else if *local {
4643 self.set_active_pane(pane, window, cx);
4644 }
4645 }
4646 pane::Event::UserSavedItem { item, save_intent } => {
4647 cx.emit(Event::UserSavedItem {
4648 pane: pane.downgrade(),
4649 item: item.boxed_clone(),
4650 save_intent: *save_intent,
4651 });
4652 serialize_workspace = false;
4653 }
4654 pane::Event::ChangeItemTitle => {
4655 if *pane == self.active_pane {
4656 self.active_item_path_changed(false, window, cx);
4657 }
4658 serialize_workspace = false;
4659 }
4660 pane::Event::RemovedItem { item } => {
4661 cx.emit(Event::ActiveItemChanged);
4662 self.update_window_edited(window, cx);
4663 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
4664 && entry.get().entity_id() == pane.entity_id()
4665 {
4666 entry.remove();
4667 }
4668 cx.emit(Event::ItemRemoved {
4669 item_id: item.item_id(),
4670 });
4671 }
4672 pane::Event::Focus => {
4673 window.invalidate_character_coordinates();
4674 self.handle_pane_focused(pane.clone(), window, cx);
4675 }
4676 pane::Event::ZoomIn => {
4677 if *pane == self.active_pane {
4678 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
4679 if pane.read(cx).has_focus(window, cx) {
4680 self.zoomed = Some(pane.downgrade().into());
4681 self.zoomed_position = None;
4682 cx.emit(Event::ZoomChanged);
4683 }
4684 cx.notify();
4685 }
4686 }
4687 pane::Event::ZoomOut => {
4688 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4689 if self.zoomed_position.is_none() {
4690 self.zoomed = None;
4691 cx.emit(Event::ZoomChanged);
4692 }
4693 cx.notify();
4694 }
4695 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
4696 }
4697
4698 if serialize_workspace {
4699 self.serialize_workspace(window, cx);
4700 }
4701 }
4702
4703 pub fn unfollow_in_pane(
4704 &mut self,
4705 pane: &Entity<Pane>,
4706 window: &mut Window,
4707 cx: &mut Context<Workspace>,
4708 ) -> Option<CollaboratorId> {
4709 let leader_id = self.leader_for_pane(pane)?;
4710 self.unfollow(leader_id, window, cx);
4711 Some(leader_id)
4712 }
4713
4714 pub fn split_pane(
4715 &mut self,
4716 pane_to_split: Entity<Pane>,
4717 split_direction: SplitDirection,
4718 window: &mut Window,
4719 cx: &mut Context<Self>,
4720 ) -> Entity<Pane> {
4721 let new_pane = self.add_pane(window, cx);
4722 self.center
4723 .split(&pane_to_split, &new_pane, split_direction, cx)
4724 .unwrap();
4725 cx.notify();
4726 new_pane
4727 }
4728
4729 pub fn split_and_move(
4730 &mut self,
4731 pane: Entity<Pane>,
4732 direction: SplitDirection,
4733 window: &mut Window,
4734 cx: &mut Context<Self>,
4735 ) {
4736 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
4737 return;
4738 };
4739 let new_pane = self.add_pane(window, cx);
4740 new_pane.update(cx, |pane, cx| {
4741 pane.add_item(item, true, true, None, window, cx)
4742 });
4743 self.center.split(&pane, &new_pane, direction, cx).unwrap();
4744 cx.notify();
4745 }
4746
4747 pub fn split_and_clone(
4748 &mut self,
4749 pane: Entity<Pane>,
4750 direction: SplitDirection,
4751 window: &mut Window,
4752 cx: &mut Context<Self>,
4753 ) -> Task<Option<Entity<Pane>>> {
4754 let Some(item) = pane.read(cx).active_item() else {
4755 return Task::ready(None);
4756 };
4757 if !item.can_split(cx) {
4758 return Task::ready(None);
4759 }
4760 let task = item.clone_on_split(self.database_id(), window, cx);
4761 cx.spawn_in(window, async move |this, cx| {
4762 if let Some(clone) = task.await {
4763 this.update_in(cx, |this, window, cx| {
4764 let new_pane = this.add_pane(window, cx);
4765 let nav_history = pane.read(cx).fork_nav_history();
4766 new_pane.update(cx, |pane, cx| {
4767 pane.set_nav_history(nav_history, cx);
4768 pane.add_item(clone, true, true, None, window, cx)
4769 });
4770 this.center.split(&pane, &new_pane, direction, cx).unwrap();
4771 cx.notify();
4772 new_pane
4773 })
4774 .ok()
4775 } else {
4776 None
4777 }
4778 })
4779 }
4780
4781 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4782 let active_item = self.active_pane.read(cx).active_item();
4783 for pane in &self.panes {
4784 join_pane_into_active(&self.active_pane, pane, window, cx);
4785 }
4786 if let Some(active_item) = active_item {
4787 self.activate_item(active_item.as_ref(), true, true, window, cx);
4788 }
4789 cx.notify();
4790 }
4791
4792 pub fn join_pane_into_next(
4793 &mut self,
4794 pane: Entity<Pane>,
4795 window: &mut Window,
4796 cx: &mut Context<Self>,
4797 ) {
4798 let next_pane = self
4799 .find_pane_in_direction(SplitDirection::Right, cx)
4800 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
4801 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
4802 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
4803 let Some(next_pane) = next_pane else {
4804 return;
4805 };
4806 move_all_items(&pane, &next_pane, window, cx);
4807 cx.notify();
4808 }
4809
4810 fn remove_pane(
4811 &mut self,
4812 pane: Entity<Pane>,
4813 focus_on: Option<Entity<Pane>>,
4814 window: &mut Window,
4815 cx: &mut Context<Self>,
4816 ) {
4817 if self.center.remove(&pane, cx).unwrap() {
4818 self.force_remove_pane(&pane, &focus_on, window, cx);
4819 self.unfollow_in_pane(&pane, window, cx);
4820 self.last_leaders_by_pane.remove(&pane.downgrade());
4821 for removed_item in pane.read(cx).items() {
4822 self.panes_by_item.remove(&removed_item.item_id());
4823 }
4824
4825 cx.notify();
4826 } else {
4827 self.active_item_path_changed(true, window, cx);
4828 }
4829 cx.emit(Event::PaneRemoved);
4830 }
4831
4832 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
4833 &mut self.panes
4834 }
4835
4836 pub fn panes(&self) -> &[Entity<Pane>] {
4837 &self.panes
4838 }
4839
4840 pub fn active_pane(&self) -> &Entity<Pane> {
4841 &self.active_pane
4842 }
4843
4844 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
4845 for dock in self.all_docks() {
4846 if dock.focus_handle(cx).contains_focused(window, cx)
4847 && let Some(pane) = dock
4848 .read(cx)
4849 .active_panel()
4850 .and_then(|panel| panel.pane(cx))
4851 {
4852 return pane;
4853 }
4854 }
4855 self.active_pane().clone()
4856 }
4857
4858 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4859 self.find_pane_in_direction(SplitDirection::Right, cx)
4860 .unwrap_or_else(|| {
4861 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
4862 })
4863 }
4864
4865 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
4866 let weak_pane = self.panes_by_item.get(&handle.item_id())?;
4867 weak_pane.upgrade()
4868 }
4869
4870 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
4871 self.follower_states.retain(|leader_id, state| {
4872 if *leader_id == CollaboratorId::PeerId(peer_id) {
4873 for item in state.items_by_leader_view_id.values() {
4874 item.view.set_leader_id(None, window, cx);
4875 }
4876 false
4877 } else {
4878 true
4879 }
4880 });
4881 cx.notify();
4882 }
4883
4884 pub fn start_following(
4885 &mut self,
4886 leader_id: impl Into<CollaboratorId>,
4887 window: &mut Window,
4888 cx: &mut Context<Self>,
4889 ) -> Option<Task<Result<()>>> {
4890 let leader_id = leader_id.into();
4891 let pane = self.active_pane().clone();
4892
4893 self.last_leaders_by_pane
4894 .insert(pane.downgrade(), leader_id);
4895 self.unfollow(leader_id, window, cx);
4896 self.unfollow_in_pane(&pane, window, cx);
4897 self.follower_states.insert(
4898 leader_id,
4899 FollowerState {
4900 center_pane: pane.clone(),
4901 dock_pane: None,
4902 active_view_id: None,
4903 items_by_leader_view_id: Default::default(),
4904 },
4905 );
4906 cx.notify();
4907
4908 match leader_id {
4909 CollaboratorId::PeerId(leader_peer_id) => {
4910 let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
4911 let project_id = self.project.read(cx).remote_id();
4912 let request = self.app_state.client.request(proto::Follow {
4913 room_id,
4914 project_id,
4915 leader_id: Some(leader_peer_id),
4916 });
4917
4918 Some(cx.spawn_in(window, async move |this, cx| {
4919 let response = request.await?;
4920 this.update(cx, |this, _| {
4921 let state = this
4922 .follower_states
4923 .get_mut(&leader_id)
4924 .context("following interrupted")?;
4925 state.active_view_id = response
4926 .active_view
4927 .as_ref()
4928 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
4929 anyhow::Ok(())
4930 })??;
4931 if let Some(view) = response.active_view {
4932 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
4933 }
4934 this.update_in(cx, |this, window, cx| {
4935 this.leader_updated(leader_id, window, cx)
4936 })?;
4937 Ok(())
4938 }))
4939 }
4940 CollaboratorId::Agent => {
4941 self.leader_updated(leader_id, window, cx)?;
4942 Some(Task::ready(Ok(())))
4943 }
4944 }
4945 }
4946
4947 pub fn follow_next_collaborator(
4948 &mut self,
4949 _: &FollowNextCollaborator,
4950 window: &mut Window,
4951 cx: &mut Context<Self>,
4952 ) {
4953 let collaborators = self.project.read(cx).collaborators();
4954 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
4955 let mut collaborators = collaborators.keys().copied();
4956 for peer_id in collaborators.by_ref() {
4957 if CollaboratorId::PeerId(peer_id) == leader_id {
4958 break;
4959 }
4960 }
4961 collaborators.next().map(CollaboratorId::PeerId)
4962 } else if let Some(last_leader_id) =
4963 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
4964 {
4965 match last_leader_id {
4966 CollaboratorId::PeerId(peer_id) => {
4967 if collaborators.contains_key(peer_id) {
4968 Some(*last_leader_id)
4969 } else {
4970 None
4971 }
4972 }
4973 CollaboratorId::Agent => Some(CollaboratorId::Agent),
4974 }
4975 } else {
4976 None
4977 };
4978
4979 let pane = self.active_pane.clone();
4980 let Some(leader_id) = next_leader_id.or_else(|| {
4981 Some(CollaboratorId::PeerId(
4982 collaborators.keys().copied().next()?,
4983 ))
4984 }) else {
4985 return;
4986 };
4987 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
4988 return;
4989 }
4990 if let Some(task) = self.start_following(leader_id, window, cx) {
4991 task.detach_and_log_err(cx)
4992 }
4993 }
4994
4995 pub fn follow(
4996 &mut self,
4997 leader_id: impl Into<CollaboratorId>,
4998 window: &mut Window,
4999 cx: &mut Context<Self>,
5000 ) {
5001 let leader_id = leader_id.into();
5002
5003 if let CollaboratorId::PeerId(peer_id) = leader_id {
5004 let Some(room) = ActiveCall::global(cx).read(cx).room() else {
5005 return;
5006 };
5007 let room = room.read(cx);
5008 let Some(remote_participant) = room.remote_participant_for_peer_id(peer_id) else {
5009 return;
5010 };
5011
5012 let project = self.project.read(cx);
5013
5014 let other_project_id = match remote_participant.location {
5015 call::ParticipantLocation::External => None,
5016 call::ParticipantLocation::UnsharedProject => None,
5017 call::ParticipantLocation::SharedProject { project_id } => {
5018 if Some(project_id) == project.remote_id() {
5019 None
5020 } else {
5021 Some(project_id)
5022 }
5023 }
5024 };
5025
5026 // if they are active in another project, follow there.
5027 if let Some(project_id) = other_project_id {
5028 let app_state = self.app_state.clone();
5029 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5030 .detach_and_log_err(cx);
5031 }
5032 }
5033
5034 // if you're already following, find the right pane and focus it.
5035 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5036 window.focus(&follower_state.pane().focus_handle(cx), cx);
5037
5038 return;
5039 }
5040
5041 // Otherwise, follow.
5042 if let Some(task) = self.start_following(leader_id, window, cx) {
5043 task.detach_and_log_err(cx)
5044 }
5045 }
5046
5047 pub fn unfollow(
5048 &mut self,
5049 leader_id: impl Into<CollaboratorId>,
5050 window: &mut Window,
5051 cx: &mut Context<Self>,
5052 ) -> Option<()> {
5053 cx.notify();
5054
5055 let leader_id = leader_id.into();
5056 let state = self.follower_states.remove(&leader_id)?;
5057 for (_, item) in state.items_by_leader_view_id {
5058 item.view.set_leader_id(None, window, cx);
5059 }
5060
5061 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5062 let project_id = self.project.read(cx).remote_id();
5063 let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
5064 self.app_state
5065 .client
5066 .send(proto::Unfollow {
5067 room_id,
5068 project_id,
5069 leader_id: Some(leader_peer_id),
5070 })
5071 .log_err();
5072 }
5073
5074 Some(())
5075 }
5076
5077 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5078 self.follower_states.contains_key(&id.into())
5079 }
5080
5081 fn active_item_path_changed(
5082 &mut self,
5083 focus_changed: bool,
5084 window: &mut Window,
5085 cx: &mut Context<Self>,
5086 ) {
5087 cx.emit(Event::ActiveItemChanged);
5088 let active_entry = self.active_project_path(cx);
5089 self.project.update(cx, |project, cx| {
5090 project.set_active_path(active_entry.clone(), cx)
5091 });
5092
5093 if focus_changed && let Some(project_path) = &active_entry {
5094 let git_store_entity = self.project.read(cx).git_store().clone();
5095 git_store_entity.update(cx, |git_store, cx| {
5096 git_store.set_active_repo_for_path(project_path, cx);
5097 });
5098 }
5099
5100 self.update_window_title(window, cx);
5101 }
5102
5103 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5104 let project = self.project().read(cx);
5105 let mut title = String::new();
5106
5107 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5108 let name = {
5109 let settings_location = SettingsLocation {
5110 worktree_id: worktree.read(cx).id(),
5111 path: RelPath::empty(),
5112 };
5113
5114 let settings = WorktreeSettings::get(Some(settings_location), cx);
5115 match &settings.project_name {
5116 Some(name) => name.as_str(),
5117 None => worktree.read(cx).root_name_str(),
5118 }
5119 };
5120 if i > 0 {
5121 title.push_str(", ");
5122 }
5123 title.push_str(name);
5124 }
5125
5126 if title.is_empty() {
5127 title = "empty project".to_string();
5128 }
5129
5130 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5131 let filename = path.path.file_name().or_else(|| {
5132 Some(
5133 project
5134 .worktree_for_id(path.worktree_id, cx)?
5135 .read(cx)
5136 .root_name_str(),
5137 )
5138 });
5139
5140 if let Some(filename) = filename {
5141 title.push_str(" — ");
5142 title.push_str(filename.as_ref());
5143 }
5144 }
5145
5146 if project.is_via_collab() {
5147 title.push_str(" ↙");
5148 } else if project.is_shared() {
5149 title.push_str(" ↗");
5150 }
5151
5152 if let Some(last_title) = self.last_window_title.as_ref()
5153 && &title == last_title
5154 {
5155 return;
5156 }
5157 window.set_window_title(&title);
5158 SystemWindowTabController::update_tab_title(
5159 cx,
5160 window.window_handle().window_id(),
5161 SharedString::from(&title),
5162 );
5163 self.last_window_title = Some(title);
5164 }
5165
5166 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5167 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5168 if is_edited != self.window_edited {
5169 self.window_edited = is_edited;
5170 window.set_window_edited(self.window_edited)
5171 }
5172 }
5173
5174 fn update_item_dirty_state(
5175 &mut self,
5176 item: &dyn ItemHandle,
5177 window: &mut Window,
5178 cx: &mut App,
5179 ) {
5180 let is_dirty = item.is_dirty(cx);
5181 let item_id = item.item_id();
5182 let was_dirty = self.dirty_items.contains_key(&item_id);
5183 if is_dirty == was_dirty {
5184 return;
5185 }
5186 if was_dirty {
5187 self.dirty_items.remove(&item_id);
5188 self.update_window_edited(window, cx);
5189 return;
5190 }
5191
5192 let workspace = self.weak_handle();
5193 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5194 return;
5195 };
5196 let on_release_callback = Box::new(move |cx: &mut App| {
5197 window_handle
5198 .update(cx, |_, window, cx| {
5199 workspace
5200 .update(cx, |workspace, cx| {
5201 workspace.dirty_items.remove(&item_id);
5202 workspace.update_window_edited(window, cx)
5203 })
5204 .ok();
5205 })
5206 .ok();
5207 });
5208
5209 let s = item.on_release(cx, on_release_callback);
5210 self.dirty_items.insert(item_id, s);
5211 self.update_window_edited(window, cx);
5212 }
5213
5214 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5215 if self.notifications.is_empty() {
5216 None
5217 } else {
5218 Some(
5219 div()
5220 .absolute()
5221 .right_3()
5222 .bottom_3()
5223 .w_112()
5224 .h_full()
5225 .flex()
5226 .flex_col()
5227 .justify_end()
5228 .gap_2()
5229 .children(
5230 self.notifications
5231 .iter()
5232 .map(|(_, notification)| notification.clone().into_any()),
5233 ),
5234 )
5235 }
5236 }
5237
5238 // RPC handlers
5239
5240 fn active_view_for_follower(
5241 &self,
5242 follower_project_id: Option<u64>,
5243 window: &mut Window,
5244 cx: &mut Context<Self>,
5245 ) -> Option<proto::View> {
5246 let (item, panel_id) = self.active_item_for_followers(window, cx);
5247 let item = item?;
5248 let leader_id = self
5249 .pane_for(&*item)
5250 .and_then(|pane| self.leader_for_pane(&pane));
5251 let leader_peer_id = match leader_id {
5252 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5253 Some(CollaboratorId::Agent) | None => None,
5254 };
5255
5256 let item_handle = item.to_followable_item_handle(cx)?;
5257 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5258 let variant = item_handle.to_state_proto(window, cx)?;
5259
5260 if item_handle.is_project_item(window, cx)
5261 && (follower_project_id.is_none()
5262 || follower_project_id != self.project.read(cx).remote_id())
5263 {
5264 return None;
5265 }
5266
5267 Some(proto::View {
5268 id: id.to_proto(),
5269 leader_id: leader_peer_id,
5270 variant: Some(variant),
5271 panel_id: panel_id.map(|id| id as i32),
5272 })
5273 }
5274
5275 fn handle_follow(
5276 &mut self,
5277 follower_project_id: Option<u64>,
5278 window: &mut Window,
5279 cx: &mut Context<Self>,
5280 ) -> proto::FollowResponse {
5281 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5282
5283 cx.notify();
5284 proto::FollowResponse {
5285 views: active_view.iter().cloned().collect(),
5286 active_view,
5287 }
5288 }
5289
5290 fn handle_update_followers(
5291 &mut self,
5292 leader_id: PeerId,
5293 message: proto::UpdateFollowers,
5294 _window: &mut Window,
5295 _cx: &mut Context<Self>,
5296 ) {
5297 self.leader_updates_tx
5298 .unbounded_send((leader_id, message))
5299 .ok();
5300 }
5301
5302 async fn process_leader_update(
5303 this: &WeakEntity<Self>,
5304 leader_id: PeerId,
5305 update: proto::UpdateFollowers,
5306 cx: &mut AsyncWindowContext,
5307 ) -> Result<()> {
5308 match update.variant.context("invalid update")? {
5309 proto::update_followers::Variant::CreateView(view) => {
5310 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5311 let should_add_view = this.update(cx, |this, _| {
5312 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5313 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5314 } else {
5315 anyhow::Ok(false)
5316 }
5317 })??;
5318
5319 if should_add_view {
5320 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5321 }
5322 }
5323 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5324 let should_add_view = this.update(cx, |this, _| {
5325 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5326 state.active_view_id = update_active_view
5327 .view
5328 .as_ref()
5329 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5330
5331 if state.active_view_id.is_some_and(|view_id| {
5332 !state.items_by_leader_view_id.contains_key(&view_id)
5333 }) {
5334 anyhow::Ok(true)
5335 } else {
5336 anyhow::Ok(false)
5337 }
5338 } else {
5339 anyhow::Ok(false)
5340 }
5341 })??;
5342
5343 if should_add_view && let Some(view) = update_active_view.view {
5344 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5345 }
5346 }
5347 proto::update_followers::Variant::UpdateView(update_view) => {
5348 let variant = update_view.variant.context("missing update view variant")?;
5349 let id = update_view.id.context("missing update view id")?;
5350 let mut tasks = Vec::new();
5351 this.update_in(cx, |this, window, cx| {
5352 let project = this.project.clone();
5353 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5354 let view_id = ViewId::from_proto(id.clone())?;
5355 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5356 tasks.push(item.view.apply_update_proto(
5357 &project,
5358 variant.clone(),
5359 window,
5360 cx,
5361 ));
5362 }
5363 }
5364 anyhow::Ok(())
5365 })??;
5366 try_join_all(tasks).await.log_err();
5367 }
5368 }
5369 this.update_in(cx, |this, window, cx| {
5370 this.leader_updated(leader_id, window, cx)
5371 })?;
5372 Ok(())
5373 }
5374
5375 async fn add_view_from_leader(
5376 this: WeakEntity<Self>,
5377 leader_id: PeerId,
5378 view: &proto::View,
5379 cx: &mut AsyncWindowContext,
5380 ) -> Result<()> {
5381 let this = this.upgrade().context("workspace dropped")?;
5382
5383 let Some(id) = view.id.clone() else {
5384 anyhow::bail!("no id for view");
5385 };
5386 let id = ViewId::from_proto(id)?;
5387 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5388
5389 let pane = this.update(cx, |this, _cx| {
5390 let state = this
5391 .follower_states
5392 .get(&leader_id.into())
5393 .context("stopped following")?;
5394 anyhow::Ok(state.pane().clone())
5395 })?;
5396 let existing_item = pane.update_in(cx, |pane, window, cx| {
5397 let client = this.read(cx).client().clone();
5398 pane.items().find_map(|item| {
5399 let item = item.to_followable_item_handle(cx)?;
5400 if item.remote_id(&client, window, cx) == Some(id) {
5401 Some(item)
5402 } else {
5403 None
5404 }
5405 })
5406 })?;
5407 let item = if let Some(existing_item) = existing_item {
5408 existing_item
5409 } else {
5410 let variant = view.variant.clone();
5411 anyhow::ensure!(variant.is_some(), "missing view variant");
5412
5413 let task = cx.update(|window, cx| {
5414 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5415 })?;
5416
5417 let Some(task) = task else {
5418 anyhow::bail!(
5419 "failed to construct view from leader (maybe from a different version of zed?)"
5420 );
5421 };
5422
5423 let mut new_item = task.await?;
5424 pane.update_in(cx, |pane, window, cx| {
5425 let mut item_to_remove = None;
5426 for (ix, item) in pane.items().enumerate() {
5427 if let Some(item) = item.to_followable_item_handle(cx) {
5428 match new_item.dedup(item.as_ref(), window, cx) {
5429 Some(item::Dedup::KeepExisting) => {
5430 new_item =
5431 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5432 break;
5433 }
5434 Some(item::Dedup::ReplaceExisting) => {
5435 item_to_remove = Some((ix, item.item_id()));
5436 break;
5437 }
5438 None => {}
5439 }
5440 }
5441 }
5442
5443 if let Some((ix, id)) = item_to_remove {
5444 pane.remove_item(id, false, false, window, cx);
5445 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5446 }
5447 })?;
5448
5449 new_item
5450 };
5451
5452 this.update_in(cx, |this, window, cx| {
5453 let state = this.follower_states.get_mut(&leader_id.into())?;
5454 item.set_leader_id(Some(leader_id.into()), window, cx);
5455 state.items_by_leader_view_id.insert(
5456 id,
5457 FollowerView {
5458 view: item,
5459 location: panel_id,
5460 },
5461 );
5462
5463 Some(())
5464 })
5465 .context("no follower state")?;
5466
5467 Ok(())
5468 }
5469
5470 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5471 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5472 return;
5473 };
5474
5475 if let Some(agent_location) = self.project.read(cx).agent_location() {
5476 let buffer_entity_id = agent_location.buffer.entity_id();
5477 let view_id = ViewId {
5478 creator: CollaboratorId::Agent,
5479 id: buffer_entity_id.as_u64(),
5480 };
5481 follower_state.active_view_id = Some(view_id);
5482
5483 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5484 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5485 hash_map::Entry::Vacant(entry) => {
5486 let existing_view =
5487 follower_state
5488 .center_pane
5489 .read(cx)
5490 .items()
5491 .find_map(|item| {
5492 let item = item.to_followable_item_handle(cx)?;
5493 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5494 && item.project_item_model_ids(cx).as_slice()
5495 == [buffer_entity_id]
5496 {
5497 Some(item)
5498 } else {
5499 None
5500 }
5501 });
5502 let view = existing_view.or_else(|| {
5503 agent_location.buffer.upgrade().and_then(|buffer| {
5504 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
5505 registry.build_item(buffer, self.project.clone(), None, window, cx)
5506 })?
5507 .to_followable_item_handle(cx)
5508 })
5509 });
5510
5511 view.map(|view| {
5512 entry.insert(FollowerView {
5513 view,
5514 location: None,
5515 })
5516 })
5517 }
5518 };
5519
5520 if let Some(item) = item {
5521 item.view
5522 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
5523 item.view
5524 .update_agent_location(agent_location.position, window, cx);
5525 }
5526 } else {
5527 follower_state.active_view_id = None;
5528 }
5529
5530 self.leader_updated(CollaboratorId::Agent, window, cx);
5531 }
5532
5533 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
5534 let mut is_project_item = true;
5535 let mut update = proto::UpdateActiveView::default();
5536 if window.is_window_active() {
5537 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
5538
5539 if let Some(item) = active_item
5540 && item.item_focus_handle(cx).contains_focused(window, cx)
5541 {
5542 let leader_id = self
5543 .pane_for(&*item)
5544 .and_then(|pane| self.leader_for_pane(&pane));
5545 let leader_peer_id = match leader_id {
5546 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5547 Some(CollaboratorId::Agent) | None => None,
5548 };
5549
5550 if let Some(item) = item.to_followable_item_handle(cx) {
5551 let id = item
5552 .remote_id(&self.app_state.client, window, cx)
5553 .map(|id| id.to_proto());
5554
5555 if let Some(id) = id
5556 && let Some(variant) = item.to_state_proto(window, cx)
5557 {
5558 let view = Some(proto::View {
5559 id,
5560 leader_id: leader_peer_id,
5561 variant: Some(variant),
5562 panel_id: panel_id.map(|id| id as i32),
5563 });
5564
5565 is_project_item = item.is_project_item(window, cx);
5566 update = proto::UpdateActiveView { view };
5567 };
5568 }
5569 }
5570 }
5571
5572 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
5573 if active_view_id != self.last_active_view_id.as_ref() {
5574 self.last_active_view_id = active_view_id.cloned();
5575 self.update_followers(
5576 is_project_item,
5577 proto::update_followers::Variant::UpdateActiveView(update),
5578 window,
5579 cx,
5580 );
5581 }
5582 }
5583
5584 fn active_item_for_followers(
5585 &self,
5586 window: &mut Window,
5587 cx: &mut App,
5588 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
5589 let mut active_item = None;
5590 let mut panel_id = None;
5591 for dock in self.all_docks() {
5592 if dock.focus_handle(cx).contains_focused(window, cx)
5593 && let Some(panel) = dock.read(cx).active_panel()
5594 && let Some(pane) = panel.pane(cx)
5595 && let Some(item) = pane.read(cx).active_item()
5596 {
5597 active_item = Some(item);
5598 panel_id = panel.remote_id();
5599 break;
5600 }
5601 }
5602
5603 if active_item.is_none() {
5604 active_item = self.active_pane().read(cx).active_item();
5605 }
5606 (active_item, panel_id)
5607 }
5608
5609 fn update_followers(
5610 &self,
5611 project_only: bool,
5612 update: proto::update_followers::Variant,
5613 _: &mut Window,
5614 cx: &mut App,
5615 ) -> Option<()> {
5616 // If this update only applies to for followers in the current project,
5617 // then skip it unless this project is shared. If it applies to all
5618 // followers, regardless of project, then set `project_id` to none,
5619 // indicating that it goes to all followers.
5620 let project_id = if project_only {
5621 Some(self.project.read(cx).remote_id()?)
5622 } else {
5623 None
5624 };
5625 self.app_state().workspace_store.update(cx, |store, cx| {
5626 store.update_followers(project_id, update, cx)
5627 })
5628 }
5629
5630 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
5631 self.follower_states.iter().find_map(|(leader_id, state)| {
5632 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
5633 Some(*leader_id)
5634 } else {
5635 None
5636 }
5637 })
5638 }
5639
5640 fn leader_updated(
5641 &mut self,
5642 leader_id: impl Into<CollaboratorId>,
5643 window: &mut Window,
5644 cx: &mut Context<Self>,
5645 ) -> Option<Box<dyn ItemHandle>> {
5646 cx.notify();
5647
5648 let leader_id = leader_id.into();
5649 let (panel_id, item) = match leader_id {
5650 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
5651 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
5652 };
5653
5654 let state = self.follower_states.get(&leader_id)?;
5655 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
5656 let pane;
5657 if let Some(panel_id) = panel_id {
5658 pane = self
5659 .activate_panel_for_proto_id(panel_id, window, cx)?
5660 .pane(cx)?;
5661 let state = self.follower_states.get_mut(&leader_id)?;
5662 state.dock_pane = Some(pane.clone());
5663 } else {
5664 pane = state.center_pane.clone();
5665 let state = self.follower_states.get_mut(&leader_id)?;
5666 if let Some(dock_pane) = state.dock_pane.take() {
5667 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
5668 }
5669 }
5670
5671 pane.update(cx, |pane, cx| {
5672 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
5673 if let Some(index) = pane.index_for_item(item.as_ref()) {
5674 pane.activate_item(index, false, false, window, cx);
5675 } else {
5676 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
5677 }
5678
5679 if focus_active_item {
5680 pane.focus_active_item(window, cx)
5681 }
5682 });
5683
5684 Some(item)
5685 }
5686
5687 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
5688 let state = self.follower_states.get(&CollaboratorId::Agent)?;
5689 let active_view_id = state.active_view_id?;
5690 Some(
5691 state
5692 .items_by_leader_view_id
5693 .get(&active_view_id)?
5694 .view
5695 .boxed_clone(),
5696 )
5697 }
5698
5699 fn active_item_for_peer(
5700 &self,
5701 peer_id: PeerId,
5702 window: &mut Window,
5703 cx: &mut Context<Self>,
5704 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
5705 let call = self.active_call()?;
5706 let room = call.read(cx).room()?.read(cx);
5707 let participant = room.remote_participant_for_peer_id(peer_id)?;
5708 let leader_in_this_app;
5709 let leader_in_this_project;
5710 match participant.location {
5711 call::ParticipantLocation::SharedProject { project_id } => {
5712 leader_in_this_app = true;
5713 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
5714 }
5715 call::ParticipantLocation::UnsharedProject => {
5716 leader_in_this_app = true;
5717 leader_in_this_project = false;
5718 }
5719 call::ParticipantLocation::External => {
5720 leader_in_this_app = false;
5721 leader_in_this_project = false;
5722 }
5723 };
5724 let state = self.follower_states.get(&peer_id.into())?;
5725 let mut item_to_activate = None;
5726 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
5727 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
5728 && (leader_in_this_project || !item.view.is_project_item(window, cx))
5729 {
5730 item_to_activate = Some((item.location, item.view.boxed_clone()));
5731 }
5732 } else if let Some(shared_screen) =
5733 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
5734 {
5735 item_to_activate = Some((None, Box::new(shared_screen)));
5736 }
5737 item_to_activate
5738 }
5739
5740 fn shared_screen_for_peer(
5741 &self,
5742 peer_id: PeerId,
5743 pane: &Entity<Pane>,
5744 window: &mut Window,
5745 cx: &mut App,
5746 ) -> Option<Entity<SharedScreen>> {
5747 let call = self.active_call()?;
5748 let room = call.read(cx).room()?.clone();
5749 let participant = room.read(cx).remote_participant_for_peer_id(peer_id)?;
5750 let track = participant.video_tracks.values().next()?.clone();
5751 let user = participant.user.clone();
5752
5753 for item in pane.read(cx).items_of_type::<SharedScreen>() {
5754 if item.read(cx).peer_id == peer_id {
5755 return Some(item);
5756 }
5757 }
5758
5759 Some(cx.new(|cx| SharedScreen::new(track, peer_id, user.clone(), room.clone(), window, cx)))
5760 }
5761
5762 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5763 if window.is_window_active() {
5764 self.update_active_view_for_followers(window, cx);
5765
5766 if let Some(database_id) = self.database_id {
5767 cx.background_spawn(persistence::DB.update_timestamp(database_id))
5768 .detach();
5769 }
5770 } else {
5771 for pane in &self.panes {
5772 pane.update(cx, |pane, cx| {
5773 if let Some(item) = pane.active_item() {
5774 item.workspace_deactivated(window, cx);
5775 }
5776 for item in pane.items() {
5777 if matches!(
5778 item.workspace_settings(cx).autosave,
5779 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
5780 ) {
5781 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
5782 .detach_and_log_err(cx);
5783 }
5784 }
5785 });
5786 }
5787 }
5788 }
5789
5790 pub fn active_call(&self) -> Option<&Entity<ActiveCall>> {
5791 self.active_call.as_ref().map(|(call, _)| call)
5792 }
5793
5794 fn on_active_call_event(
5795 &mut self,
5796 _: &Entity<ActiveCall>,
5797 event: &call::room::Event,
5798 window: &mut Window,
5799 cx: &mut Context<Self>,
5800 ) {
5801 match event {
5802 call::room::Event::ParticipantLocationChanged { participant_id }
5803 | call::room::Event::RemoteVideoTracksChanged { participant_id } => {
5804 self.leader_updated(participant_id, window, cx);
5805 }
5806 _ => {}
5807 }
5808 }
5809
5810 pub fn database_id(&self) -> Option<WorkspaceId> {
5811 self.database_id
5812 }
5813
5814 pub fn session_id(&self) -> Option<String> {
5815 self.session_id.clone()
5816 }
5817
5818 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
5819 let project = self.project().read(cx);
5820 project
5821 .visible_worktrees(cx)
5822 .map(|worktree| worktree.read(cx).abs_path())
5823 .collect::<Vec<_>>()
5824 }
5825
5826 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
5827 match member {
5828 Member::Axis(PaneAxis { members, .. }) => {
5829 for child in members.iter() {
5830 self.remove_panes(child.clone(), window, cx)
5831 }
5832 }
5833 Member::Pane(pane) => {
5834 self.force_remove_pane(&pane, &None, window, cx);
5835 }
5836 }
5837 }
5838
5839 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
5840 self.session_id.take();
5841 self.serialize_workspace_internal(window, cx)
5842 }
5843
5844 fn force_remove_pane(
5845 &mut self,
5846 pane: &Entity<Pane>,
5847 focus_on: &Option<Entity<Pane>>,
5848 window: &mut Window,
5849 cx: &mut Context<Workspace>,
5850 ) {
5851 self.panes.retain(|p| p != pane);
5852 if let Some(focus_on) = focus_on {
5853 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
5854 } else if self.active_pane() == pane {
5855 self.panes
5856 .last()
5857 .unwrap()
5858 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
5859 }
5860 if self.last_active_center_pane == Some(pane.downgrade()) {
5861 self.last_active_center_pane = None;
5862 }
5863 cx.notify();
5864 }
5865
5866 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5867 if self._schedule_serialize_workspace.is_none() {
5868 self._schedule_serialize_workspace =
5869 Some(cx.spawn_in(window, async move |this, cx| {
5870 cx.background_executor()
5871 .timer(SERIALIZATION_THROTTLE_TIME)
5872 .await;
5873 this.update_in(cx, |this, window, cx| {
5874 this.serialize_workspace_internal(window, cx).detach();
5875 this._schedule_serialize_workspace.take();
5876 })
5877 .log_err();
5878 }));
5879 }
5880 }
5881
5882 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
5883 let Some(database_id) = self.database_id() else {
5884 return Task::ready(());
5885 };
5886
5887 fn serialize_pane_handle(
5888 pane_handle: &Entity<Pane>,
5889 window: &mut Window,
5890 cx: &mut App,
5891 ) -> SerializedPane {
5892 let (items, active, pinned_count) = {
5893 let pane = pane_handle.read(cx);
5894 let active_item_id = pane.active_item().map(|item| item.item_id());
5895 (
5896 pane.items()
5897 .filter_map(|handle| {
5898 let handle = handle.to_serializable_item_handle(cx)?;
5899
5900 Some(SerializedItem {
5901 kind: Arc::from(handle.serialized_item_kind()),
5902 item_id: handle.item_id().as_u64(),
5903 active: Some(handle.item_id()) == active_item_id,
5904 preview: pane.is_active_preview_item(handle.item_id()),
5905 })
5906 })
5907 .collect::<Vec<_>>(),
5908 pane.has_focus(window, cx),
5909 pane.pinned_count(),
5910 )
5911 };
5912
5913 SerializedPane::new(items, active, pinned_count)
5914 }
5915
5916 fn build_serialized_pane_group(
5917 pane_group: &Member,
5918 window: &mut Window,
5919 cx: &mut App,
5920 ) -> SerializedPaneGroup {
5921 match pane_group {
5922 Member::Axis(PaneAxis {
5923 axis,
5924 members,
5925 flexes,
5926 bounding_boxes: _,
5927 }) => SerializedPaneGroup::Group {
5928 axis: SerializedAxis(*axis),
5929 children: members
5930 .iter()
5931 .map(|member| build_serialized_pane_group(member, window, cx))
5932 .collect::<Vec<_>>(),
5933 flexes: Some(flexes.lock().clone()),
5934 },
5935 Member::Pane(pane_handle) => {
5936 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
5937 }
5938 }
5939 }
5940
5941 fn build_serialized_docks(
5942 this: &Workspace,
5943 window: &mut Window,
5944 cx: &mut App,
5945 ) -> DockStructure {
5946 let left_dock = this.left_dock.read(cx);
5947 let left_visible = left_dock.is_open();
5948 let left_active_panel = left_dock
5949 .active_panel()
5950 .map(|panel| panel.persistent_name().to_string());
5951 let left_dock_zoom = left_dock
5952 .active_panel()
5953 .map(|panel| panel.is_zoomed(window, cx))
5954 .unwrap_or(false);
5955
5956 let right_dock = this.right_dock.read(cx);
5957 let right_visible = right_dock.is_open();
5958 let right_active_panel = right_dock
5959 .active_panel()
5960 .map(|panel| panel.persistent_name().to_string());
5961 let right_dock_zoom = right_dock
5962 .active_panel()
5963 .map(|panel| panel.is_zoomed(window, cx))
5964 .unwrap_or(false);
5965
5966 let bottom_dock = this.bottom_dock.read(cx);
5967 let bottom_visible = bottom_dock.is_open();
5968 let bottom_active_panel = bottom_dock
5969 .active_panel()
5970 .map(|panel| panel.persistent_name().to_string());
5971 let bottom_dock_zoom = bottom_dock
5972 .active_panel()
5973 .map(|panel| panel.is_zoomed(window, cx))
5974 .unwrap_or(false);
5975
5976 DockStructure {
5977 left: DockData {
5978 visible: left_visible,
5979 active_panel: left_active_panel,
5980 zoom: left_dock_zoom,
5981 },
5982 right: DockData {
5983 visible: right_visible,
5984 active_panel: right_active_panel,
5985 zoom: right_dock_zoom,
5986 },
5987 bottom: DockData {
5988 visible: bottom_visible,
5989 active_panel: bottom_active_panel,
5990 zoom: bottom_dock_zoom,
5991 },
5992 }
5993 }
5994
5995 match self.workspace_location(cx) {
5996 WorkspaceLocation::Location(location, paths) => {
5997 let breakpoints = self.project.update(cx, |project, cx| {
5998 project
5999 .breakpoint_store()
6000 .read(cx)
6001 .all_source_breakpoints(cx)
6002 });
6003 let user_toolchains = self
6004 .project
6005 .read(cx)
6006 .user_toolchains(cx)
6007 .unwrap_or_default();
6008
6009 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6010 let docks = build_serialized_docks(self, window, cx);
6011 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6012
6013 let serialized_workspace = SerializedWorkspace {
6014 id: database_id,
6015 location,
6016 paths,
6017 center_group,
6018 window_bounds,
6019 display: Default::default(),
6020 docks,
6021 centered_layout: self.centered_layout,
6022 session_id: self.session_id.clone(),
6023 breakpoints,
6024 window_id: Some(window.window_handle().window_id().as_u64()),
6025 user_toolchains,
6026 };
6027
6028 window.spawn(cx, async move |_| {
6029 persistence::DB.save_workspace(serialized_workspace).await;
6030 })
6031 }
6032 WorkspaceLocation::DetachFromSession => {
6033 let window_bounds = SerializedWindowBounds(window.window_bounds());
6034 let display = window.display(cx).and_then(|d| d.uuid().ok());
6035 // Save dock state for empty local workspaces
6036 let docks = build_serialized_docks(self, window, cx);
6037 window.spawn(cx, async move |_| {
6038 persistence::DB
6039 .set_window_open_status(
6040 database_id,
6041 window_bounds,
6042 display.unwrap_or_default(),
6043 )
6044 .await
6045 .log_err();
6046 persistence::DB
6047 .set_session_id(database_id, None)
6048 .await
6049 .log_err();
6050 persistence::write_default_dock_state(docks).await.log_err();
6051 })
6052 }
6053 WorkspaceLocation::None => {
6054 // Save dock state for empty non-local workspaces
6055 let docks = build_serialized_docks(self, window, cx);
6056 window.spawn(cx, async move |_| {
6057 persistence::write_default_dock_state(docks).await.log_err();
6058 })
6059 }
6060 }
6061 }
6062
6063 fn has_any_items_open(&self, cx: &App) -> bool {
6064 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6065 }
6066
6067 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6068 let paths = PathList::new(&self.root_paths(cx));
6069 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6070 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6071 } else if self.project.read(cx).is_local() {
6072 if !paths.is_empty() || self.has_any_items_open(cx) {
6073 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6074 } else {
6075 WorkspaceLocation::DetachFromSession
6076 }
6077 } else {
6078 WorkspaceLocation::None
6079 }
6080 }
6081
6082 fn update_history(&self, cx: &mut App) {
6083 let Some(id) = self.database_id() else {
6084 return;
6085 };
6086 if !self.project.read(cx).is_local() {
6087 return;
6088 }
6089 if let Some(manager) = HistoryManager::global(cx) {
6090 let paths = PathList::new(&self.root_paths(cx));
6091 manager.update(cx, |this, cx| {
6092 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6093 });
6094 }
6095 }
6096
6097 async fn serialize_items(
6098 this: &WeakEntity<Self>,
6099 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6100 cx: &mut AsyncWindowContext,
6101 ) -> Result<()> {
6102 const CHUNK_SIZE: usize = 200;
6103
6104 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6105
6106 while let Some(items_received) = serializable_items.next().await {
6107 let unique_items =
6108 items_received
6109 .into_iter()
6110 .fold(HashMap::default(), |mut acc, item| {
6111 acc.entry(item.item_id()).or_insert(item);
6112 acc
6113 });
6114
6115 // We use into_iter() here so that the references to the items are moved into
6116 // the tasks and not kept alive while we're sleeping.
6117 for (_, item) in unique_items.into_iter() {
6118 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6119 item.serialize(workspace, false, window, cx)
6120 }) {
6121 cx.background_spawn(async move { task.await.log_err() })
6122 .detach();
6123 }
6124 }
6125
6126 cx.background_executor()
6127 .timer(SERIALIZATION_THROTTLE_TIME)
6128 .await;
6129 }
6130
6131 Ok(())
6132 }
6133
6134 pub(crate) fn enqueue_item_serialization(
6135 &mut self,
6136 item: Box<dyn SerializableItemHandle>,
6137 ) -> Result<()> {
6138 self.serializable_items_tx
6139 .unbounded_send(item)
6140 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6141 }
6142
6143 pub(crate) fn load_workspace(
6144 serialized_workspace: SerializedWorkspace,
6145 paths_to_open: Vec<Option<ProjectPath>>,
6146 window: &mut Window,
6147 cx: &mut Context<Workspace>,
6148 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6149 cx.spawn_in(window, async move |workspace, cx| {
6150 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6151
6152 let mut center_group = None;
6153 let mut center_items = None;
6154
6155 // Traverse the splits tree and add to things
6156 if let Some((group, active_pane, items)) = serialized_workspace
6157 .center_group
6158 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6159 .await
6160 {
6161 center_items = Some(items);
6162 center_group = Some((group, active_pane))
6163 }
6164
6165 let mut items_by_project_path = HashMap::default();
6166 let mut item_ids_by_kind = HashMap::default();
6167 let mut all_deserialized_items = Vec::default();
6168 cx.update(|_, cx| {
6169 for item in center_items.unwrap_or_default().into_iter().flatten() {
6170 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6171 item_ids_by_kind
6172 .entry(serializable_item_handle.serialized_item_kind())
6173 .or_insert(Vec::new())
6174 .push(item.item_id().as_u64() as ItemId);
6175 }
6176
6177 if let Some(project_path) = item.project_path(cx) {
6178 items_by_project_path.insert(project_path, item.clone());
6179 }
6180 all_deserialized_items.push(item);
6181 }
6182 })?;
6183
6184 let opened_items = paths_to_open
6185 .into_iter()
6186 .map(|path_to_open| {
6187 path_to_open
6188 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6189 })
6190 .collect::<Vec<_>>();
6191
6192 // Remove old panes from workspace panes list
6193 workspace.update_in(cx, |workspace, window, cx| {
6194 if let Some((center_group, active_pane)) = center_group {
6195 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6196
6197 // Swap workspace center group
6198 workspace.center = PaneGroup::with_root(center_group);
6199 workspace.center.set_is_center(true);
6200 workspace.center.mark_positions(cx);
6201
6202 if let Some(active_pane) = active_pane {
6203 workspace.set_active_pane(&active_pane, window, cx);
6204 cx.focus_self(window);
6205 } else {
6206 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6207 }
6208 }
6209
6210 let docks = serialized_workspace.docks;
6211
6212 for (dock, serialized_dock) in [
6213 (&mut workspace.right_dock, docks.right),
6214 (&mut workspace.left_dock, docks.left),
6215 (&mut workspace.bottom_dock, docks.bottom),
6216 ]
6217 .iter_mut()
6218 {
6219 dock.update(cx, |dock, cx| {
6220 dock.serialized_dock = Some(serialized_dock.clone());
6221 dock.restore_state(window, cx);
6222 });
6223 }
6224
6225 cx.notify();
6226 })?;
6227
6228 let _ = project
6229 .update(cx, |project, cx| {
6230 project
6231 .breakpoint_store()
6232 .update(cx, |breakpoint_store, cx| {
6233 breakpoint_store
6234 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6235 })
6236 })
6237 .await;
6238
6239 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6240 // after loading the items, we might have different items and in order to avoid
6241 // the database filling up, we delete items that haven't been loaded now.
6242 //
6243 // The items that have been loaded, have been saved after they've been added to the workspace.
6244 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6245 item_ids_by_kind
6246 .into_iter()
6247 .map(|(item_kind, loaded_items)| {
6248 SerializableItemRegistry::cleanup(
6249 item_kind,
6250 serialized_workspace.id,
6251 loaded_items,
6252 window,
6253 cx,
6254 )
6255 .log_err()
6256 })
6257 .collect::<Vec<_>>()
6258 })?;
6259
6260 futures::future::join_all(clean_up_tasks).await;
6261
6262 workspace
6263 .update_in(cx, |workspace, window, cx| {
6264 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6265 workspace.serialize_workspace_internal(window, cx).detach();
6266
6267 // Ensure that we mark the window as edited if we did load dirty items
6268 workspace.update_window_edited(window, cx);
6269 })
6270 .ok();
6271
6272 Ok(opened_items)
6273 })
6274 }
6275
6276 fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6277 self.add_workspace_actions_listeners(div, window, cx)
6278 .on_action(cx.listener(
6279 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6280 for action in &action_sequence.0 {
6281 window.dispatch_action(action.boxed_clone(), cx);
6282 }
6283 },
6284 ))
6285 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6286 .on_action(cx.listener(Self::close_all_items_and_panes))
6287 .on_action(cx.listener(Self::close_item_in_all_panes))
6288 .on_action(cx.listener(Self::save_all))
6289 .on_action(cx.listener(Self::send_keystrokes))
6290 .on_action(cx.listener(Self::add_folder_to_project))
6291 .on_action(cx.listener(Self::follow_next_collaborator))
6292 .on_action(cx.listener(Self::close_window))
6293 .on_action(cx.listener(Self::activate_pane_at_index))
6294 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6295 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6296 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6297 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6298 let pane = workspace.active_pane().clone();
6299 workspace.unfollow_in_pane(&pane, window, cx);
6300 }))
6301 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6302 workspace
6303 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6304 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6305 }))
6306 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6307 workspace
6308 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6309 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6310 }))
6311 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6312 workspace
6313 .save_active_item(SaveIntent::SaveAs, window, cx)
6314 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6315 }))
6316 .on_action(
6317 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6318 workspace.activate_previous_pane(window, cx)
6319 }),
6320 )
6321 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6322 workspace.activate_next_pane(window, cx)
6323 }))
6324 .on_action(
6325 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6326 workspace.activate_next_window(cx)
6327 }),
6328 )
6329 .on_action(
6330 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6331 workspace.activate_previous_window(cx)
6332 }),
6333 )
6334 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6335 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6336 }))
6337 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6338 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6339 }))
6340 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6341 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6342 }))
6343 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6344 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6345 }))
6346 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6347 workspace.activate_next_pane(window, cx)
6348 }))
6349 .on_action(cx.listener(
6350 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6351 workspace.move_item_to_pane_in_direction(action, window, cx)
6352 },
6353 ))
6354 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6355 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6356 }))
6357 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6358 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6359 }))
6360 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6361 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6362 }))
6363 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6364 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6365 }))
6366 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6367 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6368 SplitDirection::Down,
6369 SplitDirection::Up,
6370 SplitDirection::Right,
6371 SplitDirection::Left,
6372 ];
6373 for dir in DIRECTION_PRIORITY {
6374 if workspace.find_pane_in_direction(dir, cx).is_some() {
6375 workspace.swap_pane_in_direction(dir, cx);
6376 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6377 break;
6378 }
6379 }
6380 }))
6381 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6382 workspace.move_pane_to_border(SplitDirection::Left, cx)
6383 }))
6384 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6385 workspace.move_pane_to_border(SplitDirection::Right, cx)
6386 }))
6387 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6388 workspace.move_pane_to_border(SplitDirection::Up, cx)
6389 }))
6390 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6391 workspace.move_pane_to_border(SplitDirection::Down, cx)
6392 }))
6393 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6394 this.toggle_dock(DockPosition::Left, window, cx);
6395 }))
6396 .on_action(cx.listener(
6397 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6398 workspace.toggle_dock(DockPosition::Right, window, cx);
6399 },
6400 ))
6401 .on_action(cx.listener(
6402 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6403 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6404 },
6405 ))
6406 .on_action(cx.listener(
6407 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6408 if !workspace.close_active_dock(window, cx) {
6409 cx.propagate();
6410 }
6411 },
6412 ))
6413 .on_action(
6414 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6415 workspace.close_all_docks(window, cx);
6416 }),
6417 )
6418 .on_action(cx.listener(Self::toggle_all_docks))
6419 .on_action(cx.listener(
6420 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6421 workspace.clear_all_notifications(cx);
6422 },
6423 ))
6424 .on_action(cx.listener(
6425 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6426 workspace.clear_navigation_history(window, cx);
6427 },
6428 ))
6429 .on_action(cx.listener(
6430 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6431 if let Some((notification_id, _)) = workspace.notifications.pop() {
6432 workspace.suppress_notification(¬ification_id, cx);
6433 }
6434 },
6435 ))
6436 .on_action(cx.listener(
6437 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
6438 workspace.show_worktree_trust_security_modal(true, window, cx);
6439 },
6440 ))
6441 .on_action(
6442 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
6443 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
6444 trusted_worktrees.update(cx, |trusted_worktrees, _| {
6445 trusted_worktrees.clear_trusted_paths()
6446 });
6447 let clear_task = persistence::DB.clear_trusted_worktrees();
6448 cx.spawn(async move |_, cx| {
6449 if clear_task.await.log_err().is_some() {
6450 cx.update(|cx| reload(cx));
6451 }
6452 })
6453 .detach();
6454 }
6455 }),
6456 )
6457 .on_action(cx.listener(
6458 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
6459 workspace.reopen_closed_item(window, cx).detach();
6460 },
6461 ))
6462 .on_action(cx.listener(
6463 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
6464 for dock in workspace.all_docks() {
6465 if dock.focus_handle(cx).contains_focused(window, cx) {
6466 let Some(panel) = dock.read(cx).active_panel() else {
6467 return;
6468 };
6469
6470 // Set to `None`, then the size will fall back to the default.
6471 panel.clone().set_size(None, window, cx);
6472
6473 return;
6474 }
6475 }
6476 },
6477 ))
6478 .on_action(cx.listener(
6479 |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
6480 for dock in workspace.all_docks() {
6481 if let Some(panel) = dock.read(cx).visible_panel() {
6482 // Set to `None`, then the size will fall back to the default.
6483 panel.clone().set_size(None, window, cx);
6484 }
6485 }
6486 },
6487 ))
6488 .on_action(cx.listener(
6489 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
6490 adjust_active_dock_size_by_px(
6491 px_with_ui_font_fallback(act.px, cx),
6492 workspace,
6493 window,
6494 cx,
6495 );
6496 },
6497 ))
6498 .on_action(cx.listener(
6499 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
6500 adjust_active_dock_size_by_px(
6501 px_with_ui_font_fallback(act.px, cx) * -1.,
6502 workspace,
6503 window,
6504 cx,
6505 );
6506 },
6507 ))
6508 .on_action(cx.listener(
6509 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
6510 adjust_open_docks_size_by_px(
6511 px_with_ui_font_fallback(act.px, cx),
6512 workspace,
6513 window,
6514 cx,
6515 );
6516 },
6517 ))
6518 .on_action(cx.listener(
6519 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
6520 adjust_open_docks_size_by_px(
6521 px_with_ui_font_fallback(act.px, cx) * -1.,
6522 workspace,
6523 window,
6524 cx,
6525 );
6526 },
6527 ))
6528 .on_action(cx.listener(Workspace::toggle_centered_layout))
6529 .on_action(cx.listener(
6530 |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
6531 if let Some(active_dock) = workspace.active_dock(window, cx) {
6532 let dock = active_dock.read(cx);
6533 if let Some(active_panel) = dock.active_panel() {
6534 if active_panel.pane(cx).is_none() {
6535 let mut recent_pane: Option<Entity<Pane>> = None;
6536 let mut recent_timestamp = 0;
6537 for pane_handle in workspace.panes() {
6538 let pane = pane_handle.read(cx);
6539 for entry in pane.activation_history() {
6540 if entry.timestamp > recent_timestamp {
6541 recent_timestamp = entry.timestamp;
6542 recent_pane = Some(pane_handle.clone());
6543 }
6544 }
6545 }
6546
6547 if let Some(pane) = recent_pane {
6548 pane.update(cx, |pane, cx| {
6549 let current_index = pane.active_item_index();
6550 let items_len = pane.items_len();
6551 if items_len > 0 {
6552 let next_index = if current_index + 1 < items_len {
6553 current_index + 1
6554 } else {
6555 0
6556 };
6557 pane.activate_item(
6558 next_index, false, false, window, cx,
6559 );
6560 }
6561 });
6562 return;
6563 }
6564 }
6565 }
6566 }
6567 cx.propagate();
6568 },
6569 ))
6570 .on_action(cx.listener(
6571 |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
6572 if let Some(active_dock) = workspace.active_dock(window, cx) {
6573 let dock = active_dock.read(cx);
6574 if let Some(active_panel) = dock.active_panel() {
6575 if active_panel.pane(cx).is_none() {
6576 let mut recent_pane: Option<Entity<Pane>> = None;
6577 let mut recent_timestamp = 0;
6578 for pane_handle in workspace.panes() {
6579 let pane = pane_handle.read(cx);
6580 for entry in pane.activation_history() {
6581 if entry.timestamp > recent_timestamp {
6582 recent_timestamp = entry.timestamp;
6583 recent_pane = Some(pane_handle.clone());
6584 }
6585 }
6586 }
6587
6588 if let Some(pane) = recent_pane {
6589 pane.update(cx, |pane, cx| {
6590 let current_index = pane.active_item_index();
6591 let items_len = pane.items_len();
6592 if items_len > 0 {
6593 let prev_index = if current_index > 0 {
6594 current_index - 1
6595 } else {
6596 items_len.saturating_sub(1)
6597 };
6598 pane.activate_item(
6599 prev_index, false, false, window, cx,
6600 );
6601 }
6602 });
6603 return;
6604 }
6605 }
6606 }
6607 }
6608 cx.propagate();
6609 },
6610 ))
6611 .on_action(cx.listener(
6612 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
6613 if let Some(active_dock) = workspace.active_dock(window, cx) {
6614 let dock = active_dock.read(cx);
6615 if let Some(active_panel) = dock.active_panel() {
6616 if active_panel.pane(cx).is_none() {
6617 let active_pane = workspace.active_pane().clone();
6618 active_pane.update(cx, |pane, cx| {
6619 pane.close_active_item(action, window, cx)
6620 .detach_and_log_err(cx);
6621 });
6622 return;
6623 }
6624 }
6625 }
6626 cx.propagate();
6627 },
6628 ))
6629 .on_action(
6630 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
6631 let pane = workspace.active_pane().clone();
6632 if let Some(item) = pane.read(cx).active_item() {
6633 item.toggle_read_only(window, cx);
6634 }
6635 }),
6636 )
6637 .on_action(cx.listener(Workspace::cancel))
6638 }
6639
6640 #[cfg(any(test, feature = "test-support"))]
6641 pub fn set_random_database_id(&mut self) {
6642 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
6643 }
6644
6645 #[cfg(any(test, feature = "test-support"))]
6646 pub(crate) fn test_new(
6647 project: Entity<Project>,
6648 window: &mut Window,
6649 cx: &mut Context<Self>,
6650 ) -> Self {
6651 use node_runtime::NodeRuntime;
6652 use session::Session;
6653
6654 let client = project.read(cx).client();
6655 let user_store = project.read(cx).user_store();
6656 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
6657 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
6658 window.activate_window();
6659 let app_state = Arc::new(AppState {
6660 languages: project.read(cx).languages().clone(),
6661 workspace_store,
6662 client,
6663 user_store,
6664 fs: project.read(cx).fs().clone(),
6665 build_window_options: |_, _| Default::default(),
6666 node_runtime: NodeRuntime::unavailable(),
6667 session,
6668 });
6669 let workspace = Self::new(Default::default(), project, app_state, window, cx);
6670 workspace
6671 .active_pane
6672 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6673 workspace
6674 }
6675
6676 pub fn register_action<A: Action>(
6677 &mut self,
6678 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
6679 ) -> &mut Self {
6680 let callback = Arc::new(callback);
6681
6682 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
6683 let callback = callback.clone();
6684 div.on_action(cx.listener(move |workspace, event, window, cx| {
6685 (callback)(workspace, event, window, cx)
6686 }))
6687 }));
6688 self
6689 }
6690 pub fn register_action_renderer(
6691 &mut self,
6692 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
6693 ) -> &mut Self {
6694 self.workspace_actions.push(Box::new(callback));
6695 self
6696 }
6697
6698 fn add_workspace_actions_listeners(
6699 &self,
6700 mut div: Div,
6701 window: &mut Window,
6702 cx: &mut Context<Self>,
6703 ) -> Div {
6704 for action in self.workspace_actions.iter() {
6705 div = (action)(div, self, window, cx)
6706 }
6707 div
6708 }
6709
6710 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
6711 self.modal_layer.read(cx).has_active_modal()
6712 }
6713
6714 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
6715 self.modal_layer.read(cx).active_modal()
6716 }
6717
6718 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
6719 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
6720 /// If no modal is active, the new modal will be shown.
6721 ///
6722 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
6723 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
6724 /// will not be shown.
6725 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
6726 where
6727 B: FnOnce(&mut Window, &mut Context<V>) -> V,
6728 {
6729 self.modal_layer.update(cx, |modal_layer, cx| {
6730 modal_layer.toggle_modal(window, cx, build)
6731 })
6732 }
6733
6734 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
6735 self.modal_layer
6736 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
6737 }
6738
6739 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
6740 self.toast_layer
6741 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
6742 }
6743
6744 pub fn toggle_centered_layout(
6745 &mut self,
6746 _: &ToggleCenteredLayout,
6747 _: &mut Window,
6748 cx: &mut Context<Self>,
6749 ) {
6750 self.centered_layout = !self.centered_layout;
6751 if let Some(database_id) = self.database_id() {
6752 cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
6753 .detach_and_log_err(cx);
6754 }
6755 cx.notify();
6756 }
6757
6758 fn adjust_padding(padding: Option<f32>) -> f32 {
6759 padding
6760 .unwrap_or(CenteredPaddingSettings::default().0)
6761 .clamp(
6762 CenteredPaddingSettings::MIN_PADDING,
6763 CenteredPaddingSettings::MAX_PADDING,
6764 )
6765 }
6766
6767 fn render_dock(
6768 &self,
6769 position: DockPosition,
6770 dock: &Entity<Dock>,
6771 window: &mut Window,
6772 cx: &mut App,
6773 ) -> Option<Div> {
6774 if self.zoomed_position == Some(position) {
6775 return None;
6776 }
6777
6778 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
6779 let pane = panel.pane(cx)?;
6780 let follower_states = &self.follower_states;
6781 leader_border_for_pane(follower_states, &pane, window, cx)
6782 });
6783
6784 Some(
6785 div()
6786 .flex()
6787 .flex_none()
6788 .overflow_hidden()
6789 .child(dock.clone())
6790 .children(leader_border),
6791 )
6792 }
6793
6794 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
6795 window
6796 .root::<MultiWorkspace>()
6797 .flatten()
6798 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
6799 }
6800
6801 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
6802 self.zoomed.as_ref()
6803 }
6804
6805 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
6806 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
6807 return;
6808 };
6809 let windows = cx.windows();
6810 let next_window =
6811 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
6812 || {
6813 windows
6814 .iter()
6815 .cycle()
6816 .skip_while(|window| window.window_id() != current_window_id)
6817 .nth(1)
6818 },
6819 );
6820
6821 if let Some(window) = next_window {
6822 window
6823 .update(cx, |_, window, _| window.activate_window())
6824 .ok();
6825 }
6826 }
6827
6828 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
6829 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
6830 return;
6831 };
6832 let windows = cx.windows();
6833 let prev_window =
6834 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
6835 || {
6836 windows
6837 .iter()
6838 .rev()
6839 .cycle()
6840 .skip_while(|window| window.window_id() != current_window_id)
6841 .nth(1)
6842 },
6843 );
6844
6845 if let Some(window) = prev_window {
6846 window
6847 .update(cx, |_, window, _| window.activate_window())
6848 .ok();
6849 }
6850 }
6851
6852 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
6853 if cx.stop_active_drag(window) {
6854 } else if let Some((notification_id, _)) = self.notifications.pop() {
6855 dismiss_app_notification(¬ification_id, cx);
6856 } else {
6857 cx.propagate();
6858 }
6859 }
6860
6861 fn adjust_dock_size_by_px(
6862 &mut self,
6863 panel_size: Pixels,
6864 dock_pos: DockPosition,
6865 px: Pixels,
6866 window: &mut Window,
6867 cx: &mut Context<Self>,
6868 ) {
6869 match dock_pos {
6870 DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
6871 DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
6872 DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
6873 }
6874 }
6875
6876 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6877 let size = new_size.min(self.bounds.right() - RESIZE_HANDLE_SIZE);
6878
6879 self.left_dock.update(cx, |left_dock, cx| {
6880 if WorkspaceSettings::get_global(cx)
6881 .resize_all_panels_in_dock
6882 .contains(&DockPosition::Left)
6883 {
6884 left_dock.resize_all_panels(Some(size), window, cx);
6885 } else {
6886 left_dock.resize_active_panel(Some(size), window, cx);
6887 }
6888 });
6889 }
6890
6891 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6892 let mut size = new_size.max(self.bounds.left() - RESIZE_HANDLE_SIZE);
6893 self.left_dock.read_with(cx, |left_dock, cx| {
6894 let left_dock_size = left_dock
6895 .active_panel_size(window, cx)
6896 .unwrap_or(Pixels::ZERO);
6897 if left_dock_size + size > self.bounds.right() {
6898 size = self.bounds.right() - left_dock_size
6899 }
6900 });
6901 self.right_dock.update(cx, |right_dock, cx| {
6902 if WorkspaceSettings::get_global(cx)
6903 .resize_all_panels_in_dock
6904 .contains(&DockPosition::Right)
6905 {
6906 right_dock.resize_all_panels(Some(size), window, cx);
6907 } else {
6908 right_dock.resize_active_panel(Some(size), window, cx);
6909 }
6910 });
6911 }
6912
6913 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6914 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
6915 self.bottom_dock.update(cx, |bottom_dock, cx| {
6916 if WorkspaceSettings::get_global(cx)
6917 .resize_all_panels_in_dock
6918 .contains(&DockPosition::Bottom)
6919 {
6920 bottom_dock.resize_all_panels(Some(size), window, cx);
6921 } else {
6922 bottom_dock.resize_active_panel(Some(size), window, cx);
6923 }
6924 });
6925 }
6926
6927 fn toggle_edit_predictions_all_files(
6928 &mut self,
6929 _: &ToggleEditPrediction,
6930 _window: &mut Window,
6931 cx: &mut Context<Self>,
6932 ) {
6933 let fs = self.project().read(cx).fs().clone();
6934 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
6935 update_settings_file(fs, cx, move |file, _| {
6936 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
6937 });
6938 }
6939
6940 pub fn show_worktree_trust_security_modal(
6941 &mut self,
6942 toggle: bool,
6943 window: &mut Window,
6944 cx: &mut Context<Self>,
6945 ) {
6946 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
6947 if toggle {
6948 security_modal.update(cx, |security_modal, cx| {
6949 security_modal.dismiss(cx);
6950 })
6951 } else {
6952 security_modal.update(cx, |security_modal, cx| {
6953 security_modal.refresh_restricted_paths(cx);
6954 });
6955 }
6956 } else {
6957 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
6958 .map(|trusted_worktrees| {
6959 trusted_worktrees
6960 .read(cx)
6961 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
6962 })
6963 .unwrap_or(false);
6964 if has_restricted_worktrees {
6965 let project = self.project().read(cx);
6966 let remote_host = project
6967 .remote_connection_options(cx)
6968 .map(RemoteHostLocation::from);
6969 let worktree_store = project.worktree_store().downgrade();
6970 self.toggle_modal(window, cx, |_, cx| {
6971 SecurityModal::new(worktree_store, remote_host, cx)
6972 });
6973 }
6974 }
6975 }
6976}
6977
6978fn leader_border_for_pane(
6979 follower_states: &HashMap<CollaboratorId, FollowerState>,
6980 pane: &Entity<Pane>,
6981 _: &Window,
6982 cx: &App,
6983) -> Option<Div> {
6984 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
6985 if state.pane() == pane {
6986 Some((*leader_id, state))
6987 } else {
6988 None
6989 }
6990 })?;
6991
6992 let mut leader_color = match leader_id {
6993 CollaboratorId::PeerId(leader_peer_id) => {
6994 let room = ActiveCall::try_global(cx)?.read(cx).room()?.read(cx);
6995 let leader = room.remote_participant_for_peer_id(leader_peer_id)?;
6996
6997 cx.theme()
6998 .players()
6999 .color_for_participant(leader.participant_index.0)
7000 .cursor
7001 }
7002 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7003 };
7004 leader_color.fade_out(0.3);
7005 Some(
7006 div()
7007 .absolute()
7008 .size_full()
7009 .left_0()
7010 .top_0()
7011 .border_2()
7012 .border_color(leader_color),
7013 )
7014}
7015
7016fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7017 ZED_WINDOW_POSITION
7018 .zip(*ZED_WINDOW_SIZE)
7019 .map(|(position, size)| Bounds {
7020 origin: position,
7021 size,
7022 })
7023}
7024
7025fn open_items(
7026 serialized_workspace: Option<SerializedWorkspace>,
7027 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7028 window: &mut Window,
7029 cx: &mut Context<Workspace>,
7030) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7031 let restored_items = serialized_workspace.map(|serialized_workspace| {
7032 Workspace::load_workspace(
7033 serialized_workspace,
7034 project_paths_to_open
7035 .iter()
7036 .map(|(_, project_path)| project_path)
7037 .cloned()
7038 .collect(),
7039 window,
7040 cx,
7041 )
7042 });
7043
7044 cx.spawn_in(window, async move |workspace, cx| {
7045 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7046
7047 if let Some(restored_items) = restored_items {
7048 let restored_items = restored_items.await?;
7049
7050 let restored_project_paths = restored_items
7051 .iter()
7052 .filter_map(|item| {
7053 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7054 .ok()
7055 .flatten()
7056 })
7057 .collect::<HashSet<_>>();
7058
7059 for restored_item in restored_items {
7060 opened_items.push(restored_item.map(Ok));
7061 }
7062
7063 project_paths_to_open
7064 .iter_mut()
7065 .for_each(|(_, project_path)| {
7066 if let Some(project_path_to_open) = project_path
7067 && restored_project_paths.contains(project_path_to_open)
7068 {
7069 *project_path = None;
7070 }
7071 });
7072 } else {
7073 for _ in 0..project_paths_to_open.len() {
7074 opened_items.push(None);
7075 }
7076 }
7077 assert!(opened_items.len() == project_paths_to_open.len());
7078
7079 let tasks =
7080 project_paths_to_open
7081 .into_iter()
7082 .enumerate()
7083 .map(|(ix, (abs_path, project_path))| {
7084 let workspace = workspace.clone();
7085 cx.spawn(async move |cx| {
7086 let file_project_path = project_path?;
7087 let abs_path_task = workspace.update(cx, |workspace, cx| {
7088 workspace.project().update(cx, |project, cx| {
7089 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7090 })
7091 });
7092
7093 // We only want to open file paths here. If one of the items
7094 // here is a directory, it was already opened further above
7095 // with a `find_or_create_worktree`.
7096 if let Ok(task) = abs_path_task
7097 && task.await.is_none_or(|p| p.is_file())
7098 {
7099 return Some((
7100 ix,
7101 workspace
7102 .update_in(cx, |workspace, window, cx| {
7103 workspace.open_path(
7104 file_project_path,
7105 None,
7106 true,
7107 window,
7108 cx,
7109 )
7110 })
7111 .log_err()?
7112 .await,
7113 ));
7114 }
7115 None
7116 })
7117 });
7118
7119 let tasks = tasks.collect::<Vec<_>>();
7120
7121 let tasks = futures::future::join_all(tasks);
7122 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7123 opened_items[ix] = Some(path_open_result);
7124 }
7125
7126 Ok(opened_items)
7127 })
7128}
7129
7130enum ActivateInDirectionTarget {
7131 Pane(Entity<Pane>),
7132 Dock(Entity<Dock>),
7133}
7134
7135fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7136 window
7137 .update(cx, |multi_workspace, _, cx| {
7138 let workspace = multi_workspace.workspace().clone();
7139 workspace.update(cx, |workspace, cx| {
7140 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7141 struct DatabaseFailedNotification;
7142
7143 workspace.show_notification(
7144 NotificationId::unique::<DatabaseFailedNotification>(),
7145 cx,
7146 |cx| {
7147 cx.new(|cx| {
7148 MessageNotification::new("Failed to load the database file.", cx)
7149 .primary_message("File an Issue")
7150 .primary_icon(IconName::Plus)
7151 .primary_on_click(|window, cx| {
7152 window.dispatch_action(Box::new(FileBugReport), cx)
7153 })
7154 })
7155 },
7156 );
7157 }
7158 });
7159 })
7160 .log_err();
7161}
7162
7163fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7164 if val == 0 {
7165 ThemeSettings::get_global(cx).ui_font_size(cx)
7166 } else {
7167 px(val as f32)
7168 }
7169}
7170
7171fn adjust_active_dock_size_by_px(
7172 px: Pixels,
7173 workspace: &mut Workspace,
7174 window: &mut Window,
7175 cx: &mut Context<Workspace>,
7176) {
7177 let Some(active_dock) = workspace
7178 .all_docks()
7179 .into_iter()
7180 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7181 else {
7182 return;
7183 };
7184 let dock = active_dock.read(cx);
7185 let Some(panel_size) = dock.active_panel_size(window, cx) else {
7186 return;
7187 };
7188 let dock_pos = dock.position();
7189 workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
7190}
7191
7192fn adjust_open_docks_size_by_px(
7193 px: Pixels,
7194 workspace: &mut Workspace,
7195 window: &mut Window,
7196 cx: &mut Context<Workspace>,
7197) {
7198 let docks = workspace
7199 .all_docks()
7200 .into_iter()
7201 .filter_map(|dock| {
7202 if dock.read(cx).is_open() {
7203 let dock = dock.read(cx);
7204 let panel_size = dock.active_panel_size(window, cx)?;
7205 let dock_pos = dock.position();
7206 Some((panel_size, dock_pos, px))
7207 } else {
7208 None
7209 }
7210 })
7211 .collect::<Vec<_>>();
7212
7213 docks
7214 .into_iter()
7215 .for_each(|(panel_size, dock_pos, offset)| {
7216 workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
7217 });
7218}
7219
7220impl Focusable for Workspace {
7221 fn focus_handle(&self, cx: &App) -> FocusHandle {
7222 self.active_pane.focus_handle(cx)
7223 }
7224}
7225
7226#[derive(Clone)]
7227struct DraggedDock(DockPosition);
7228
7229impl Render for DraggedDock {
7230 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7231 gpui::Empty
7232 }
7233}
7234
7235impl Render for Workspace {
7236 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7237 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
7238 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
7239 log::info!("Rendered first frame");
7240 }
7241 let mut context = KeyContext::new_with_defaults();
7242 context.add("Workspace");
7243 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
7244 if let Some(status) = self
7245 .debugger_provider
7246 .as_ref()
7247 .and_then(|provider| provider.active_thread_state(cx))
7248 {
7249 match status {
7250 ThreadStatus::Running | ThreadStatus::Stepping => {
7251 context.add("debugger_running");
7252 }
7253 ThreadStatus::Stopped => context.add("debugger_stopped"),
7254 ThreadStatus::Exited | ThreadStatus::Ended => {}
7255 }
7256 }
7257
7258 if self.left_dock.read(cx).is_open() {
7259 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
7260 context.set("left_dock", active_panel.panel_key());
7261 }
7262 }
7263
7264 if self.right_dock.read(cx).is_open() {
7265 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
7266 context.set("right_dock", active_panel.panel_key());
7267 }
7268 }
7269
7270 if self.bottom_dock.read(cx).is_open() {
7271 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
7272 context.set("bottom_dock", active_panel.panel_key());
7273 }
7274 }
7275
7276 let centered_layout = self.centered_layout
7277 && self.center.panes().len() == 1
7278 && self.active_item(cx).is_some();
7279 let render_padding = |size| {
7280 (size > 0.0).then(|| {
7281 div()
7282 .h_full()
7283 .w(relative(size))
7284 .bg(cx.theme().colors().editor_background)
7285 .border_color(cx.theme().colors().pane_group_border)
7286 })
7287 };
7288 let paddings = if centered_layout {
7289 let settings = WorkspaceSettings::get_global(cx).centered_layout;
7290 (
7291 render_padding(Self::adjust_padding(
7292 settings.left_padding.map(|padding| padding.0),
7293 )),
7294 render_padding(Self::adjust_padding(
7295 settings.right_padding.map(|padding| padding.0),
7296 )),
7297 )
7298 } else {
7299 (None, None)
7300 };
7301 let ui_font = theme::setup_ui_font(window, cx);
7302
7303 let theme = cx.theme().clone();
7304 let colors = theme.colors();
7305 let notification_entities = self
7306 .notifications
7307 .iter()
7308 .map(|(_, notification)| notification.entity_id())
7309 .collect::<Vec<_>>();
7310 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
7311
7312 self.actions(div(), window, cx)
7313 .key_context(context)
7314 .relative()
7315 .size_full()
7316 .flex()
7317 .flex_col()
7318 .font(ui_font)
7319 .gap_0()
7320 .justify_start()
7321 .items_start()
7322 .text_color(colors.text)
7323 .overflow_hidden()
7324 .children(self.titlebar_item.clone())
7325 .on_modifiers_changed(move |_, _, cx| {
7326 for &id in ¬ification_entities {
7327 cx.notify(id);
7328 }
7329 })
7330 .child(
7331 div()
7332 .size_full()
7333 .relative()
7334 .flex_1()
7335 .flex()
7336 .flex_col()
7337 .child(
7338 div()
7339 .id("workspace")
7340 .bg(colors.background)
7341 .relative()
7342 .flex_1()
7343 .w_full()
7344 .flex()
7345 .flex_col()
7346 .overflow_hidden()
7347 .border_t_1()
7348 .border_b_1()
7349 .border_color(colors.border)
7350 .child({
7351 let this = cx.entity();
7352 canvas(
7353 move |bounds, window, cx| {
7354 this.update(cx, |this, cx| {
7355 let bounds_changed = this.bounds != bounds;
7356 this.bounds = bounds;
7357
7358 if bounds_changed {
7359 this.left_dock.update(cx, |dock, cx| {
7360 dock.clamp_panel_size(
7361 bounds.size.width,
7362 window,
7363 cx,
7364 )
7365 });
7366
7367 this.right_dock.update(cx, |dock, cx| {
7368 dock.clamp_panel_size(
7369 bounds.size.width,
7370 window,
7371 cx,
7372 )
7373 });
7374
7375 this.bottom_dock.update(cx, |dock, cx| {
7376 dock.clamp_panel_size(
7377 bounds.size.height,
7378 window,
7379 cx,
7380 )
7381 });
7382 }
7383 })
7384 },
7385 |_, _, _, _| {},
7386 )
7387 .absolute()
7388 .size_full()
7389 })
7390 .when(self.zoomed.is_none(), |this| {
7391 this.on_drag_move(cx.listener(
7392 move |workspace,
7393 e: &DragMoveEvent<DraggedDock>,
7394 window,
7395 cx| {
7396 if workspace.previous_dock_drag_coordinates
7397 != Some(e.event.position)
7398 {
7399 workspace.previous_dock_drag_coordinates =
7400 Some(e.event.position);
7401 match e.drag(cx).0 {
7402 DockPosition::Left => {
7403 workspace.resize_left_dock(
7404 e.event.position.x
7405 - workspace.bounds.left(),
7406 window,
7407 cx,
7408 );
7409 }
7410 DockPosition::Right => {
7411 workspace.resize_right_dock(
7412 workspace.bounds.right()
7413 - e.event.position.x,
7414 window,
7415 cx,
7416 );
7417 }
7418 DockPosition::Bottom => {
7419 workspace.resize_bottom_dock(
7420 workspace.bounds.bottom()
7421 - e.event.position.y,
7422 window,
7423 cx,
7424 );
7425 }
7426 };
7427 workspace.serialize_workspace(window, cx);
7428 }
7429 },
7430 ))
7431
7432 })
7433 .child({
7434 match bottom_dock_layout {
7435 BottomDockLayout::Full => div()
7436 .flex()
7437 .flex_col()
7438 .h_full()
7439 .child(
7440 div()
7441 .flex()
7442 .flex_row()
7443 .flex_1()
7444 .overflow_hidden()
7445 .children(self.render_dock(
7446 DockPosition::Left,
7447 &self.left_dock,
7448 window,
7449 cx,
7450 ))
7451
7452 .child(
7453 div()
7454 .flex()
7455 .flex_col()
7456 .flex_1()
7457 .overflow_hidden()
7458 .child(
7459 h_flex()
7460 .flex_1()
7461 .when_some(
7462 paddings.0,
7463 |this, p| {
7464 this.child(
7465 p.border_r_1(),
7466 )
7467 },
7468 )
7469 .child(self.center.render(
7470 self.zoomed.as_ref(),
7471 &PaneRenderContext {
7472 follower_states:
7473 &self.follower_states,
7474 active_call: self.active_call(),
7475 active_pane: &self.active_pane,
7476 app_state: &self.app_state,
7477 project: &self.project,
7478 workspace: &self.weak_self,
7479 },
7480 window,
7481 cx,
7482 ))
7483 .when_some(
7484 paddings.1,
7485 |this, p| {
7486 this.child(
7487 p.border_l_1(),
7488 )
7489 },
7490 ),
7491 ),
7492 )
7493
7494 .children(self.render_dock(
7495 DockPosition::Right,
7496 &self.right_dock,
7497 window,
7498 cx,
7499 )),
7500 )
7501 .child(div().w_full().children(self.render_dock(
7502 DockPosition::Bottom,
7503 &self.bottom_dock,
7504 window,
7505 cx
7506 ))),
7507
7508 BottomDockLayout::LeftAligned => div()
7509 .flex()
7510 .flex_row()
7511 .h_full()
7512 .child(
7513 div()
7514 .flex()
7515 .flex_col()
7516 .flex_1()
7517 .h_full()
7518 .child(
7519 div()
7520 .flex()
7521 .flex_row()
7522 .flex_1()
7523 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
7524
7525 .child(
7526 div()
7527 .flex()
7528 .flex_col()
7529 .flex_1()
7530 .overflow_hidden()
7531 .child(
7532 h_flex()
7533 .flex_1()
7534 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7535 .child(self.center.render(
7536 self.zoomed.as_ref(),
7537 &PaneRenderContext {
7538 follower_states:
7539 &self.follower_states,
7540 active_call: self.active_call(),
7541 active_pane: &self.active_pane,
7542 app_state: &self.app_state,
7543 project: &self.project,
7544 workspace: &self.weak_self,
7545 },
7546 window,
7547 cx,
7548 ))
7549 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7550 )
7551 )
7552
7553 )
7554 .child(
7555 div()
7556 .w_full()
7557 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7558 ),
7559 )
7560 .children(self.render_dock(
7561 DockPosition::Right,
7562 &self.right_dock,
7563 window,
7564 cx,
7565 )),
7566
7567 BottomDockLayout::RightAligned => div()
7568 .flex()
7569 .flex_row()
7570 .h_full()
7571 .children(self.render_dock(
7572 DockPosition::Left,
7573 &self.left_dock,
7574 window,
7575 cx,
7576 ))
7577
7578 .child(
7579 div()
7580 .flex()
7581 .flex_col()
7582 .flex_1()
7583 .h_full()
7584 .child(
7585 div()
7586 .flex()
7587 .flex_row()
7588 .flex_1()
7589 .child(
7590 div()
7591 .flex()
7592 .flex_col()
7593 .flex_1()
7594 .overflow_hidden()
7595 .child(
7596 h_flex()
7597 .flex_1()
7598 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7599 .child(self.center.render(
7600 self.zoomed.as_ref(),
7601 &PaneRenderContext {
7602 follower_states:
7603 &self.follower_states,
7604 active_call: self.active_call(),
7605 active_pane: &self.active_pane,
7606 app_state: &self.app_state,
7607 project: &self.project,
7608 workspace: &self.weak_self,
7609 },
7610 window,
7611 cx,
7612 ))
7613 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7614 )
7615 )
7616
7617 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
7618 )
7619 .child(
7620 div()
7621 .w_full()
7622 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7623 ),
7624 ),
7625
7626 BottomDockLayout::Contained => div()
7627 .flex()
7628 .flex_row()
7629 .h_full()
7630 .children(self.render_dock(
7631 DockPosition::Left,
7632 &self.left_dock,
7633 window,
7634 cx,
7635 ))
7636
7637 .child(
7638 div()
7639 .flex()
7640 .flex_col()
7641 .flex_1()
7642 .overflow_hidden()
7643 .child(
7644 h_flex()
7645 .flex_1()
7646 .when_some(paddings.0, |this, p| {
7647 this.child(p.border_r_1())
7648 })
7649 .child(self.center.render(
7650 self.zoomed.as_ref(),
7651 &PaneRenderContext {
7652 follower_states:
7653 &self.follower_states,
7654 active_call: self.active_call(),
7655 active_pane: &self.active_pane,
7656 app_state: &self.app_state,
7657 project: &self.project,
7658 workspace: &self.weak_self,
7659 },
7660 window,
7661 cx,
7662 ))
7663 .when_some(paddings.1, |this, p| {
7664 this.child(p.border_l_1())
7665 }),
7666 )
7667 .children(self.render_dock(
7668 DockPosition::Bottom,
7669 &self.bottom_dock,
7670 window,
7671 cx,
7672 )),
7673 )
7674
7675 .children(self.render_dock(
7676 DockPosition::Right,
7677 &self.right_dock,
7678 window,
7679 cx,
7680 )),
7681 }
7682 })
7683 .children(self.zoomed.as_ref().and_then(|view| {
7684 let zoomed_view = view.upgrade()?;
7685 let div = div()
7686 .occlude()
7687 .absolute()
7688 .overflow_hidden()
7689 .border_color(colors.border)
7690 .bg(colors.background)
7691 .child(zoomed_view)
7692 .inset_0()
7693 .shadow_lg();
7694
7695 if !WorkspaceSettings::get_global(cx).zoomed_padding {
7696 return Some(div);
7697 }
7698
7699 Some(match self.zoomed_position {
7700 Some(DockPosition::Left) => div.right_2().border_r_1(),
7701 Some(DockPosition::Right) => div.left_2().border_l_1(),
7702 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
7703 None => {
7704 div.top_2().bottom_2().left_2().right_2().border_1()
7705 }
7706 })
7707 }))
7708 .children(self.render_notifications(window, cx)),
7709 )
7710 .when(self.status_bar_visible(cx), |parent| {
7711 parent.child(self.status_bar.clone())
7712 })
7713 .child(self.modal_layer.clone())
7714 .child(self.toast_layer.clone()),
7715 )
7716 }
7717}
7718
7719impl WorkspaceStore {
7720 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
7721 Self {
7722 workspaces: Default::default(),
7723 _subscriptions: vec![
7724 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
7725 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
7726 ],
7727 client,
7728 }
7729 }
7730
7731 pub fn update_followers(
7732 &self,
7733 project_id: Option<u64>,
7734 update: proto::update_followers::Variant,
7735 cx: &App,
7736 ) -> Option<()> {
7737 let active_call = ActiveCall::try_global(cx)?;
7738 let room_id = active_call.read(cx).room()?.read(cx).id();
7739 self.client
7740 .send(proto::UpdateFollowers {
7741 room_id,
7742 project_id,
7743 variant: Some(update),
7744 })
7745 .log_err()
7746 }
7747
7748 pub async fn handle_follow(
7749 this: Entity<Self>,
7750 envelope: TypedEnvelope<proto::Follow>,
7751 mut cx: AsyncApp,
7752 ) -> Result<proto::FollowResponse> {
7753 this.update(&mut cx, |this, cx| {
7754 let follower = Follower {
7755 project_id: envelope.payload.project_id,
7756 peer_id: envelope.original_sender_id()?,
7757 };
7758
7759 let mut response = proto::FollowResponse::default();
7760
7761 this.workspaces.retain(|(window_handle, weak_workspace)| {
7762 let Some(workspace) = weak_workspace.upgrade() else {
7763 return false;
7764 };
7765 window_handle
7766 .update(cx, |_, window, cx| {
7767 workspace.update(cx, |workspace, cx| {
7768 let handler_response =
7769 workspace.handle_follow(follower.project_id, window, cx);
7770 if let Some(active_view) = handler_response.active_view
7771 && workspace.project.read(cx).remote_id() == follower.project_id
7772 {
7773 response.active_view = Some(active_view)
7774 }
7775 });
7776 })
7777 .is_ok()
7778 });
7779
7780 Ok(response)
7781 })
7782 }
7783
7784 async fn handle_update_followers(
7785 this: Entity<Self>,
7786 envelope: TypedEnvelope<proto::UpdateFollowers>,
7787 mut cx: AsyncApp,
7788 ) -> Result<()> {
7789 let leader_id = envelope.original_sender_id()?;
7790 let update = envelope.payload;
7791
7792 this.update(&mut cx, |this, cx| {
7793 this.workspaces.retain(|(window_handle, weak_workspace)| {
7794 let Some(workspace) = weak_workspace.upgrade() else {
7795 return false;
7796 };
7797 window_handle
7798 .update(cx, |_, window, cx| {
7799 workspace.update(cx, |workspace, cx| {
7800 let project_id = workspace.project.read(cx).remote_id();
7801 if update.project_id != project_id && update.project_id.is_some() {
7802 return;
7803 }
7804 workspace.handle_update_followers(
7805 leader_id,
7806 update.clone(),
7807 window,
7808 cx,
7809 );
7810 });
7811 })
7812 .is_ok()
7813 });
7814 Ok(())
7815 })
7816 }
7817
7818 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
7819 self.workspaces.iter().map(|(_, weak)| weak)
7820 }
7821
7822 pub fn workspaces_with_windows(
7823 &self,
7824 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
7825 self.workspaces.iter().map(|(window, weak)| (*window, weak))
7826 }
7827}
7828
7829impl ViewId {
7830 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
7831 Ok(Self {
7832 creator: message
7833 .creator
7834 .map(CollaboratorId::PeerId)
7835 .context("creator is missing")?,
7836 id: message.id,
7837 })
7838 }
7839
7840 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
7841 if let CollaboratorId::PeerId(peer_id) = self.creator {
7842 Some(proto::ViewId {
7843 creator: Some(peer_id),
7844 id: self.id,
7845 })
7846 } else {
7847 None
7848 }
7849 }
7850}
7851
7852impl FollowerState {
7853 fn pane(&self) -> &Entity<Pane> {
7854 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
7855 }
7856}
7857
7858pub trait WorkspaceHandle {
7859 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
7860}
7861
7862impl WorkspaceHandle for Entity<Workspace> {
7863 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
7864 self.read(cx)
7865 .worktrees(cx)
7866 .flat_map(|worktree| {
7867 let worktree_id = worktree.read(cx).id();
7868 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
7869 worktree_id,
7870 path: f.path.clone(),
7871 })
7872 })
7873 .collect::<Vec<_>>()
7874 }
7875}
7876
7877pub async fn last_opened_workspace_location(
7878 fs: &dyn fs::Fs,
7879) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
7880 DB.last_workspace(fs).await.log_err().flatten()
7881}
7882
7883pub async fn last_session_workspace_locations(
7884 last_session_id: &str,
7885 last_session_window_stack: Option<Vec<WindowId>>,
7886 fs: &dyn fs::Fs,
7887) -> Option<Vec<SessionWorkspace>> {
7888 DB.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
7889 .await
7890 .log_err()
7891}
7892
7893pub async fn restore_multiworkspace(
7894 multi_workspace: SerializedMultiWorkspace,
7895 app_state: Arc<AppState>,
7896 cx: &mut AsyncApp,
7897) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
7898 let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
7899 let mut group_iter = workspaces.into_iter();
7900 let first = group_iter
7901 .next()
7902 .context("window group must not be empty")?;
7903
7904 let window_handle = if first.paths.is_empty() {
7905 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
7906 .await?
7907 } else {
7908 let (window, _items) = cx
7909 .update(|cx| {
7910 Workspace::new_local(
7911 first.paths.paths().to_vec(),
7912 app_state.clone(),
7913 None,
7914 None,
7915 None,
7916 cx,
7917 )
7918 })
7919 .await?;
7920 window
7921 };
7922
7923 for session_workspace in group_iter {
7924 if session_workspace.paths.is_empty() {
7925 cx.update(|cx| {
7926 open_workspace_by_id(
7927 session_workspace.workspace_id,
7928 app_state.clone(),
7929 Some(window_handle),
7930 cx,
7931 )
7932 })
7933 .await?;
7934 } else {
7935 cx.update(|cx| {
7936 Workspace::new_local(
7937 session_workspace.paths.paths().to_vec(),
7938 app_state.clone(),
7939 Some(window_handle),
7940 None,
7941 None,
7942 cx,
7943 )
7944 })
7945 .await?;
7946 }
7947 }
7948
7949 if let Some(target_id) = state.active_workspace_id {
7950 window_handle
7951 .update(cx, |multi_workspace, window, cx| {
7952 let target_index = multi_workspace
7953 .workspaces()
7954 .iter()
7955 .position(|ws| ws.read(cx).database_id() == Some(target_id));
7956 if let Some(index) = target_index {
7957 multi_workspace.activate_index(index, window, cx);
7958 } else if !multi_workspace.workspaces().is_empty() {
7959 multi_workspace.activate_index(0, window, cx);
7960 }
7961 })
7962 .ok();
7963 } else {
7964 window_handle
7965 .update(cx, |multi_workspace, window, cx| {
7966 if !multi_workspace.workspaces().is_empty() {
7967 multi_workspace.activate_index(0, window, cx);
7968 }
7969 })
7970 .ok();
7971 }
7972
7973 if state.sidebar_open {
7974 window_handle
7975 .update(cx, |multi_workspace, _, cx| {
7976 multi_workspace.open_sidebar(cx);
7977 })
7978 .ok();
7979 }
7980
7981 window_handle
7982 .update(cx, |_, window, _cx| {
7983 window.activate_window();
7984 })
7985 .ok();
7986
7987 Ok(window_handle)
7988}
7989
7990actions!(
7991 collab,
7992 [
7993 /// Opens the channel notes for the current call.
7994 ///
7995 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
7996 /// channel in the collab panel.
7997 ///
7998 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
7999 /// can be copied via "Copy link to section" in the context menu of the channel notes
8000 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8001 OpenChannelNotes,
8002 /// Mutes your microphone.
8003 Mute,
8004 /// Deafens yourself (mute both microphone and speakers).
8005 Deafen,
8006 /// Leaves the current call.
8007 LeaveCall,
8008 /// Shares the current project with collaborators.
8009 ShareProject,
8010 /// Shares your screen with collaborators.
8011 ScreenShare,
8012 /// Copies the current room name and session id for debugging purposes.
8013 CopyRoomId,
8014 ]
8015);
8016actions!(
8017 zed,
8018 [
8019 /// Opens the Zed log file.
8020 OpenLog,
8021 /// Reveals the Zed log file in the system file manager.
8022 RevealLogInFileManager
8023 ]
8024);
8025
8026async fn join_channel_internal(
8027 channel_id: ChannelId,
8028 app_state: &Arc<AppState>,
8029 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8030 requesting_workspace: Option<WeakEntity<Workspace>>,
8031 active_call: &Entity<ActiveCall>,
8032 cx: &mut AsyncApp,
8033) -> Result<bool> {
8034 let (should_prompt, open_room) = active_call.update(cx, |active_call, cx| {
8035 let Some(room) = active_call.room().map(|room| room.read(cx)) else {
8036 return (false, None);
8037 };
8038
8039 let already_in_channel = room.channel_id() == Some(channel_id);
8040 let should_prompt = room.is_sharing_project()
8041 && !room.remote_participants().is_empty()
8042 && !already_in_channel;
8043 let open_room = if already_in_channel {
8044 active_call.room().cloned()
8045 } else {
8046 None
8047 };
8048 (should_prompt, open_room)
8049 });
8050
8051 if let Some(room) = open_room {
8052 let task = room.update(cx, |room, cx| {
8053 if let Some((project, host)) = room.most_active_project(cx) {
8054 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8055 }
8056
8057 None
8058 });
8059 if let Some(task) = task {
8060 task.await?;
8061 }
8062 return anyhow::Ok(true);
8063 }
8064
8065 if should_prompt {
8066 if let Some(multi_workspace) = requesting_window {
8067 let answer = multi_workspace
8068 .update(cx, |_, window, cx| {
8069 window.prompt(
8070 PromptLevel::Warning,
8071 "Do you want to switch channels?",
8072 Some("Leaving this call will unshare your current project."),
8073 &["Yes, Join Channel", "Cancel"],
8074 cx,
8075 )
8076 })?
8077 .await;
8078
8079 if answer == Ok(1) {
8080 return Ok(false);
8081 }
8082 } else {
8083 return Ok(false); // unreachable!() hopefully
8084 }
8085 }
8086
8087 let client = cx.update(|cx| active_call.read(cx).client());
8088
8089 let mut client_status = client.status();
8090
8091 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8092 'outer: loop {
8093 let Some(status) = client_status.recv().await else {
8094 anyhow::bail!("error connecting");
8095 };
8096
8097 match status {
8098 Status::Connecting
8099 | Status::Authenticating
8100 | Status::Authenticated
8101 | Status::Reconnecting
8102 | Status::Reauthenticating
8103 | Status::Reauthenticated => continue,
8104 Status::Connected { .. } => break 'outer,
8105 Status::SignedOut | Status::AuthenticationError => {
8106 return Err(ErrorCode::SignedOut.into());
8107 }
8108 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8109 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8110 return Err(ErrorCode::Disconnected.into());
8111 }
8112 }
8113 }
8114
8115 let room = active_call
8116 .update(cx, |active_call, cx| {
8117 active_call.join_channel(channel_id, cx)
8118 })
8119 .await?;
8120
8121 let Some(room) = room else {
8122 return anyhow::Ok(true);
8123 };
8124
8125 room.update(cx, |room, _| room.room_update_completed())
8126 .await;
8127
8128 let task = room.update(cx, |room, cx| {
8129 if let Some((project, host)) = room.most_active_project(cx) {
8130 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8131 }
8132
8133 // If you are the first to join a channel, see if you should share your project.
8134 if room.remote_participants().is_empty()
8135 && !room.local_participant_is_guest()
8136 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8137 {
8138 let project = workspace.update(cx, |workspace, cx| {
8139 let project = workspace.project.read(cx);
8140
8141 if !CallSettings::get_global(cx).share_on_join {
8142 return None;
8143 }
8144
8145 if (project.is_local() || project.is_via_remote_server())
8146 && project.visible_worktrees(cx).any(|tree| {
8147 tree.read(cx)
8148 .root_entry()
8149 .is_some_and(|entry| entry.is_dir())
8150 })
8151 {
8152 Some(workspace.project.clone())
8153 } else {
8154 None
8155 }
8156 });
8157 if let Some(project) = project {
8158 return Some(cx.spawn(async move |room, cx| {
8159 room.update(cx, |room, cx| room.share_project(project, cx))?
8160 .await?;
8161 Ok(())
8162 }));
8163 }
8164 }
8165
8166 None
8167 });
8168 if let Some(task) = task {
8169 task.await?;
8170 return anyhow::Ok(true);
8171 }
8172 anyhow::Ok(false)
8173}
8174
8175pub fn join_channel(
8176 channel_id: ChannelId,
8177 app_state: Arc<AppState>,
8178 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8179 requesting_workspace: Option<WeakEntity<Workspace>>,
8180 cx: &mut App,
8181) -> Task<Result<()>> {
8182 let active_call = ActiveCall::global(cx);
8183 cx.spawn(async move |cx| {
8184 let result = join_channel_internal(
8185 channel_id,
8186 &app_state,
8187 requesting_window,
8188 requesting_workspace,
8189 &active_call,
8190 cx,
8191 )
8192 .await;
8193
8194 // join channel succeeded, and opened a window
8195 if matches!(result, Ok(true)) {
8196 return anyhow::Ok(());
8197 }
8198
8199 // find an existing workspace to focus and show call controls
8200 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8201 if active_window.is_none() {
8202 // no open workspaces, make one to show the error in (blergh)
8203 let (window_handle, _) = cx
8204 .update(|cx| {
8205 Workspace::new_local(
8206 vec![],
8207 app_state.clone(),
8208 requesting_window,
8209 None,
8210 None,
8211 cx,
8212 )
8213 })
8214 .await?;
8215
8216 window_handle
8217 .update(cx, |_, window, _cx| {
8218 window.activate_window();
8219 })
8220 .ok();
8221
8222 if result.is_ok() {
8223 cx.update(|cx| {
8224 cx.dispatch_action(&OpenChannelNotes);
8225 });
8226 }
8227
8228 active_window = Some(window_handle);
8229 }
8230
8231 if let Err(err) = result {
8232 log::error!("failed to join channel: {}", err);
8233 if let Some(active_window) = active_window {
8234 active_window
8235 .update(cx, |_, window, cx| {
8236 let detail: SharedString = match err.error_code() {
8237 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8238 ErrorCode::UpgradeRequired => concat!(
8239 "Your are running an unsupported version of Zed. ",
8240 "Please update to continue."
8241 )
8242 .into(),
8243 ErrorCode::NoSuchChannel => concat!(
8244 "No matching channel was found. ",
8245 "Please check the link and try again."
8246 )
8247 .into(),
8248 ErrorCode::Forbidden => concat!(
8249 "This channel is private, and you do not have access. ",
8250 "Please ask someone to add you and try again."
8251 )
8252 .into(),
8253 ErrorCode::Disconnected => {
8254 "Please check your internet connection and try again.".into()
8255 }
8256 _ => format!("{}\n\nPlease try again.", err).into(),
8257 };
8258 window.prompt(
8259 PromptLevel::Critical,
8260 "Failed to join channel",
8261 Some(&detail),
8262 &["Ok"],
8263 cx,
8264 )
8265 })?
8266 .await
8267 .ok();
8268 }
8269 }
8270
8271 // return ok, we showed the error to the user.
8272 anyhow::Ok(())
8273 })
8274}
8275
8276pub async fn get_any_active_multi_workspace(
8277 app_state: Arc<AppState>,
8278 mut cx: AsyncApp,
8279) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8280 // find an existing workspace to focus and show call controls
8281 let active_window = activate_any_workspace_window(&mut cx);
8282 if active_window.is_none() {
8283 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, cx))
8284 .await?;
8285 }
8286 activate_any_workspace_window(&mut cx).context("could not open zed")
8287}
8288
8289fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
8290 cx.update(|cx| {
8291 if let Some(workspace_window) = cx
8292 .active_window()
8293 .and_then(|window| window.downcast::<MultiWorkspace>())
8294 {
8295 return Some(workspace_window);
8296 }
8297
8298 for window in cx.windows() {
8299 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
8300 workspace_window
8301 .update(cx, |_, window, _| window.activate_window())
8302 .ok();
8303 return Some(workspace_window);
8304 }
8305 }
8306 None
8307 })
8308}
8309
8310pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
8311 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
8312}
8313
8314pub fn workspace_windows_for_location(
8315 serialized_location: &SerializedWorkspaceLocation,
8316 cx: &App,
8317) -> Vec<WindowHandle<MultiWorkspace>> {
8318 cx.windows()
8319 .into_iter()
8320 .filter_map(|window| window.downcast::<MultiWorkspace>())
8321 .filter(|multi_workspace| {
8322 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
8323 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
8324 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
8325 }
8326 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
8327 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
8328 a.distro_name == b.distro_name
8329 }
8330 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
8331 a.container_id == b.container_id
8332 }
8333 #[cfg(any(test, feature = "test-support"))]
8334 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
8335 a.id == b.id
8336 }
8337 _ => false,
8338 };
8339
8340 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
8341 multi_workspace.workspaces().iter().any(|workspace| {
8342 match workspace.read(cx).workspace_location(cx) {
8343 WorkspaceLocation::Location(location, _) => {
8344 match (&location, serialized_location) {
8345 (
8346 SerializedWorkspaceLocation::Local,
8347 SerializedWorkspaceLocation::Local,
8348 ) => true,
8349 (
8350 SerializedWorkspaceLocation::Remote(a),
8351 SerializedWorkspaceLocation::Remote(b),
8352 ) => same_host(a, b),
8353 _ => false,
8354 }
8355 }
8356 _ => false,
8357 }
8358 })
8359 })
8360 })
8361 .collect()
8362}
8363
8364pub async fn find_existing_workspace(
8365 abs_paths: &[PathBuf],
8366 open_options: &OpenOptions,
8367 location: &SerializedWorkspaceLocation,
8368 cx: &mut AsyncApp,
8369) -> (
8370 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
8371 OpenVisible,
8372) {
8373 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
8374 let mut open_visible = OpenVisible::All;
8375 let mut best_match = None;
8376
8377 if open_options.open_new_workspace != Some(true) {
8378 cx.update(|cx| {
8379 for window in workspace_windows_for_location(location, cx) {
8380 if let Ok(multi_workspace) = window.read(cx) {
8381 for workspace in multi_workspace.workspaces() {
8382 let project = workspace.read(cx).project.read(cx);
8383 let m = project.visibility_for_paths(
8384 abs_paths,
8385 open_options.open_new_workspace == None,
8386 cx,
8387 );
8388 if m > best_match {
8389 existing = Some((window, workspace.clone()));
8390 best_match = m;
8391 } else if best_match.is_none()
8392 && open_options.open_new_workspace == Some(false)
8393 {
8394 existing = Some((window, workspace.clone()))
8395 }
8396 }
8397 }
8398 }
8399 });
8400
8401 let all_paths_are_files = existing
8402 .as_ref()
8403 .and_then(|(_, target_workspace)| {
8404 cx.update(|cx| {
8405 let workspace = target_workspace.read(cx);
8406 let project = workspace.project.read(cx);
8407 let path_style = workspace.path_style(cx);
8408 Some(!abs_paths.iter().any(|path| {
8409 let path = util::paths::SanitizedPath::new(path);
8410 project.worktrees(cx).any(|worktree| {
8411 let worktree = worktree.read(cx);
8412 let abs_path = worktree.abs_path();
8413 path_style
8414 .strip_prefix(path.as_ref(), abs_path.as_ref())
8415 .and_then(|rel| worktree.entry_for_path(&rel))
8416 .is_some_and(|e| e.is_dir())
8417 })
8418 }))
8419 })
8420 })
8421 .unwrap_or(false);
8422
8423 if open_options.open_new_workspace.is_none()
8424 && existing.is_some()
8425 && open_options.wait
8426 && all_paths_are_files
8427 {
8428 cx.update(|cx| {
8429 let windows = workspace_windows_for_location(location, cx);
8430 let window = cx
8431 .active_window()
8432 .and_then(|window| window.downcast::<MultiWorkspace>())
8433 .filter(|window| windows.contains(window))
8434 .or_else(|| windows.into_iter().next());
8435 if let Some(window) = window {
8436 if let Ok(multi_workspace) = window.read(cx) {
8437 let active_workspace = multi_workspace.workspace().clone();
8438 existing = Some((window, active_workspace));
8439 open_visible = OpenVisible::None;
8440 }
8441 }
8442 });
8443 }
8444 }
8445 (existing, open_visible)
8446}
8447
8448#[derive(Default, Clone)]
8449pub struct OpenOptions {
8450 pub visible: Option<OpenVisible>,
8451 pub focus: Option<bool>,
8452 pub open_new_workspace: Option<bool>,
8453 pub wait: bool,
8454 pub replace_window: Option<WindowHandle<MultiWorkspace>>,
8455 pub env: Option<HashMap<String, String>>,
8456}
8457
8458/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
8459pub fn open_workspace_by_id(
8460 workspace_id: WorkspaceId,
8461 app_state: Arc<AppState>,
8462 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8463 cx: &mut App,
8464) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
8465 let project_handle = Project::local(
8466 app_state.client.clone(),
8467 app_state.node_runtime.clone(),
8468 app_state.user_store.clone(),
8469 app_state.languages.clone(),
8470 app_state.fs.clone(),
8471 None,
8472 project::LocalProjectFlags {
8473 init_worktree_trust: true,
8474 ..project::LocalProjectFlags::default()
8475 },
8476 cx,
8477 );
8478
8479 cx.spawn(async move |cx| {
8480 let serialized_workspace = persistence::DB
8481 .workspace_for_id(workspace_id)
8482 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
8483
8484 let centered_layout = serialized_workspace.centered_layout;
8485
8486 let (window, workspace) = if let Some(window) = requesting_window {
8487 let workspace = window.update(cx, |multi_workspace, window, cx| {
8488 let workspace = cx.new(|cx| {
8489 let mut workspace = Workspace::new(
8490 Some(workspace_id),
8491 project_handle.clone(),
8492 app_state.clone(),
8493 window,
8494 cx,
8495 );
8496 workspace.centered_layout = centered_layout;
8497 workspace
8498 });
8499 multi_workspace.add_workspace(workspace.clone(), cx);
8500 workspace
8501 })?;
8502 (window, workspace)
8503 } else {
8504 let window_bounds_override = window_bounds_env_override();
8505
8506 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
8507 (Some(WindowBounds::Windowed(bounds)), None)
8508 } else if let Some(display) = serialized_workspace.display
8509 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
8510 {
8511 (Some(bounds.0), Some(display))
8512 } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
8513 (Some(bounds), Some(display))
8514 } else {
8515 (None, None)
8516 };
8517
8518 let options = cx.update(|cx| {
8519 let mut options = (app_state.build_window_options)(display, cx);
8520 options.window_bounds = window_bounds;
8521 options
8522 });
8523
8524 let window = cx.open_window(options, {
8525 let app_state = app_state.clone();
8526 let project_handle = project_handle.clone();
8527 move |window, cx| {
8528 let workspace = cx.new(|cx| {
8529 let mut workspace = Workspace::new(
8530 Some(workspace_id),
8531 project_handle,
8532 app_state,
8533 window,
8534 cx,
8535 );
8536 workspace.centered_layout = centered_layout;
8537 workspace
8538 });
8539 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
8540 }
8541 })?;
8542
8543 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
8544 multi_workspace.workspace().clone()
8545 })?;
8546
8547 (window, workspace)
8548 };
8549
8550 notify_if_database_failed(window, cx);
8551
8552 // Restore items from the serialized workspace
8553 window
8554 .update(cx, |_, window, cx| {
8555 workspace.update(cx, |_workspace, cx| {
8556 open_items(Some(serialized_workspace), vec![], window, cx)
8557 })
8558 })?
8559 .await?;
8560
8561 window.update(cx, |_, window, cx| {
8562 workspace.update(cx, |workspace, cx| {
8563 workspace.serialize_workspace(window, cx);
8564 });
8565 })?;
8566
8567 Ok(window)
8568 })
8569}
8570
8571#[allow(clippy::type_complexity)]
8572pub fn open_paths(
8573 abs_paths: &[PathBuf],
8574 app_state: Arc<AppState>,
8575 open_options: OpenOptions,
8576 cx: &mut App,
8577) -> Task<
8578 anyhow::Result<(
8579 WindowHandle<MultiWorkspace>,
8580 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
8581 )>,
8582> {
8583 let abs_paths = abs_paths.to_vec();
8584 #[cfg(target_os = "windows")]
8585 let wsl_path = abs_paths
8586 .iter()
8587 .find_map(|p| util::paths::WslPath::from_path(p));
8588
8589 cx.spawn(async move |cx| {
8590 let (mut existing, mut open_visible) = find_existing_workspace(
8591 &abs_paths,
8592 &open_options,
8593 &SerializedWorkspaceLocation::Local,
8594 cx,
8595 )
8596 .await;
8597
8598 // Fallback: if no workspace contains the paths and all paths are files,
8599 // prefer an existing local workspace window (active window first).
8600 if open_options.open_new_workspace.is_none() && existing.is_none() {
8601 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
8602 let all_metadatas = futures::future::join_all(all_paths)
8603 .await
8604 .into_iter()
8605 .filter_map(|result| result.ok().flatten())
8606 .collect::<Vec<_>>();
8607
8608 if all_metadatas.iter().all(|file| !file.is_dir) {
8609 cx.update(|cx| {
8610 let windows = workspace_windows_for_location(
8611 &SerializedWorkspaceLocation::Local,
8612 cx,
8613 );
8614 let window = cx
8615 .active_window()
8616 .and_then(|window| window.downcast::<MultiWorkspace>())
8617 .filter(|window| windows.contains(window))
8618 .or_else(|| windows.into_iter().next());
8619 if let Some(window) = window {
8620 if let Ok(multi_workspace) = window.read(cx) {
8621 let active_workspace = multi_workspace.workspace().clone();
8622 existing = Some((window, active_workspace));
8623 open_visible = OpenVisible::None;
8624 }
8625 }
8626 });
8627 }
8628 }
8629
8630 let result = if let Some((existing, target_workspace)) = existing {
8631 let open_task = existing
8632 .update(cx, |multi_workspace, window, cx| {
8633 window.activate_window();
8634 multi_workspace.activate(target_workspace.clone(), cx);
8635 target_workspace.update(cx, |workspace, cx| {
8636 workspace.open_paths(
8637 abs_paths,
8638 OpenOptions {
8639 visible: Some(open_visible),
8640 ..Default::default()
8641 },
8642 None,
8643 window,
8644 cx,
8645 )
8646 })
8647 })?
8648 .await;
8649
8650 _ = existing.update(cx, |multi_workspace, _, cx| {
8651 let workspace = multi_workspace.workspace().clone();
8652 workspace.update(cx, |workspace, cx| {
8653 for item in open_task.iter().flatten() {
8654 if let Err(e) = item {
8655 workspace.show_error(&e, cx);
8656 }
8657 }
8658 });
8659 });
8660
8661 Ok((existing, open_task))
8662 } else {
8663 let result = cx
8664 .update(move |cx| {
8665 Workspace::new_local(
8666 abs_paths,
8667 app_state.clone(),
8668 open_options.replace_window,
8669 open_options.env,
8670 None,
8671 cx,
8672 )
8673 })
8674 .await;
8675
8676 if let Ok((ref window_handle, _)) = result {
8677 window_handle
8678 .update(cx, |_, window, _cx| {
8679 window.activate_window();
8680 })
8681 .log_err();
8682 }
8683
8684 result
8685 };
8686
8687 #[cfg(target_os = "windows")]
8688 if let Some(util::paths::WslPath{distro, path}) = wsl_path
8689 && let Ok((multi_workspace_window, _)) = &result
8690 {
8691 multi_workspace_window
8692 .update(cx, move |multi_workspace, _window, cx| {
8693 struct OpenInWsl;
8694 let workspace = multi_workspace.workspace().clone();
8695 workspace.update(cx, |workspace, cx| {
8696 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
8697 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
8698 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
8699 cx.new(move |cx| {
8700 MessageNotification::new(msg, cx)
8701 .primary_message("Open in WSL")
8702 .primary_icon(IconName::FolderOpen)
8703 .primary_on_click(move |window, cx| {
8704 window.dispatch_action(Box::new(remote::OpenWslPath {
8705 distro: remote::WslConnectionOptions {
8706 distro_name: distro.clone(),
8707 user: None,
8708 },
8709 paths: vec![path.clone().into()],
8710 }), cx)
8711 })
8712 })
8713 });
8714 });
8715 })
8716 .unwrap();
8717 };
8718 result
8719 })
8720}
8721
8722pub fn open_new(
8723 open_options: OpenOptions,
8724 app_state: Arc<AppState>,
8725 cx: &mut App,
8726 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
8727) -> Task<anyhow::Result<()>> {
8728 let task = Workspace::new_local(
8729 Vec::new(),
8730 app_state,
8731 open_options.replace_window,
8732 open_options.env,
8733 Some(Box::new(init)),
8734 cx,
8735 );
8736 cx.spawn(async move |cx| {
8737 let (window, _opened_paths) = task.await?;
8738 window
8739 .update(cx, |_, window, _cx| {
8740 window.activate_window();
8741 })
8742 .ok();
8743 Ok(())
8744 })
8745}
8746
8747pub fn create_and_open_local_file(
8748 path: &'static Path,
8749 window: &mut Window,
8750 cx: &mut Context<Workspace>,
8751 default_content: impl 'static + Send + FnOnce() -> Rope,
8752) -> Task<Result<Box<dyn ItemHandle>>> {
8753 cx.spawn_in(window, async move |workspace, cx| {
8754 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
8755 if !fs.is_file(path).await {
8756 fs.create_file(path, Default::default()).await?;
8757 fs.save(path, &default_content(), Default::default())
8758 .await?;
8759 }
8760
8761 workspace
8762 .update_in(cx, |workspace, window, cx| {
8763 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
8764 let path = workspace
8765 .project
8766 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
8767 cx.spawn_in(window, async move |workspace, cx| {
8768 let path = path.await?;
8769 let mut items = workspace
8770 .update_in(cx, |workspace, window, cx| {
8771 workspace.open_paths(
8772 vec![path.to_path_buf()],
8773 OpenOptions {
8774 visible: Some(OpenVisible::None),
8775 ..Default::default()
8776 },
8777 None,
8778 window,
8779 cx,
8780 )
8781 })?
8782 .await;
8783 let item = items.pop().flatten();
8784 item.with_context(|| format!("path {path:?} is not a file"))?
8785 })
8786 })
8787 })?
8788 .await?
8789 .await
8790 })
8791}
8792
8793pub fn open_remote_project_with_new_connection(
8794 window: WindowHandle<MultiWorkspace>,
8795 remote_connection: Arc<dyn RemoteConnection>,
8796 cancel_rx: oneshot::Receiver<()>,
8797 delegate: Arc<dyn RemoteClientDelegate>,
8798 app_state: Arc<AppState>,
8799 paths: Vec<PathBuf>,
8800 cx: &mut App,
8801) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
8802 cx.spawn(async move |cx| {
8803 let (workspace_id, serialized_workspace) =
8804 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
8805 .await?;
8806
8807 let session = match cx
8808 .update(|cx| {
8809 remote::RemoteClient::new(
8810 ConnectionIdentifier::Workspace(workspace_id.0),
8811 remote_connection,
8812 cancel_rx,
8813 delegate,
8814 cx,
8815 )
8816 })
8817 .await?
8818 {
8819 Some(result) => result,
8820 None => return Ok(Vec::new()),
8821 };
8822
8823 let project = cx.update(|cx| {
8824 project::Project::remote(
8825 session,
8826 app_state.client.clone(),
8827 app_state.node_runtime.clone(),
8828 app_state.user_store.clone(),
8829 app_state.languages.clone(),
8830 app_state.fs.clone(),
8831 true,
8832 cx,
8833 )
8834 });
8835
8836 open_remote_project_inner(
8837 project,
8838 paths,
8839 workspace_id,
8840 serialized_workspace,
8841 app_state,
8842 window,
8843 cx,
8844 )
8845 .await
8846 })
8847}
8848
8849pub fn open_remote_project_with_existing_connection(
8850 connection_options: RemoteConnectionOptions,
8851 project: Entity<Project>,
8852 paths: Vec<PathBuf>,
8853 app_state: Arc<AppState>,
8854 window: WindowHandle<MultiWorkspace>,
8855 cx: &mut AsyncApp,
8856) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
8857 cx.spawn(async move |cx| {
8858 let (workspace_id, serialized_workspace) =
8859 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
8860
8861 open_remote_project_inner(
8862 project,
8863 paths,
8864 workspace_id,
8865 serialized_workspace,
8866 app_state,
8867 window,
8868 cx,
8869 )
8870 .await
8871 })
8872}
8873
8874async fn open_remote_project_inner(
8875 project: Entity<Project>,
8876 paths: Vec<PathBuf>,
8877 workspace_id: WorkspaceId,
8878 serialized_workspace: Option<SerializedWorkspace>,
8879 app_state: Arc<AppState>,
8880 window: WindowHandle<MultiWorkspace>,
8881 cx: &mut AsyncApp,
8882) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
8883 let toolchains = DB.toolchains(workspace_id).await?;
8884 for (toolchain, worktree_path, path) in toolchains {
8885 project
8886 .update(cx, |this, cx| {
8887 let Some(worktree_id) =
8888 this.find_worktree(&worktree_path, cx)
8889 .and_then(|(worktree, rel_path)| {
8890 if rel_path.is_empty() {
8891 Some(worktree.read(cx).id())
8892 } else {
8893 None
8894 }
8895 })
8896 else {
8897 return Task::ready(None);
8898 };
8899
8900 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
8901 })
8902 .await;
8903 }
8904 let mut project_paths_to_open = vec![];
8905 let mut project_path_errors = vec![];
8906
8907 for path in paths {
8908 let result = cx
8909 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
8910 .await;
8911 match result {
8912 Ok((_, project_path)) => {
8913 project_paths_to_open.push((path.clone(), Some(project_path)));
8914 }
8915 Err(error) => {
8916 project_path_errors.push(error);
8917 }
8918 };
8919 }
8920
8921 if project_paths_to_open.is_empty() {
8922 return Err(project_path_errors.pop().context("no paths given")?);
8923 }
8924
8925 let workspace = window.update(cx, |multi_workspace, window, cx| {
8926 telemetry::event!("SSH Project Opened");
8927
8928 let new_workspace = cx.new(|cx| {
8929 let mut workspace =
8930 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
8931 workspace.update_history(cx);
8932
8933 if let Some(ref serialized) = serialized_workspace {
8934 workspace.centered_layout = serialized.centered_layout;
8935 }
8936
8937 workspace
8938 });
8939
8940 multi_workspace.activate(new_workspace.clone(), cx);
8941 new_workspace
8942 })?;
8943
8944 let items = window
8945 .update(cx, |_, window, cx| {
8946 window.activate_window();
8947 workspace.update(cx, |_workspace, cx| {
8948 open_items(serialized_workspace, project_paths_to_open, window, cx)
8949 })
8950 })?
8951 .await?;
8952
8953 workspace.update(cx, |workspace, cx| {
8954 for error in project_path_errors {
8955 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
8956 if let Some(path) = error.error_tag("path") {
8957 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
8958 }
8959 } else {
8960 workspace.show_error(&error, cx)
8961 }
8962 }
8963 });
8964
8965 Ok(items.into_iter().map(|item| item?.ok()).collect())
8966}
8967
8968fn deserialize_remote_project(
8969 connection_options: RemoteConnectionOptions,
8970 paths: Vec<PathBuf>,
8971 cx: &AsyncApp,
8972) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
8973 cx.background_spawn(async move {
8974 let remote_connection_id = persistence::DB
8975 .get_or_create_remote_connection(connection_options)
8976 .await?;
8977
8978 let serialized_workspace =
8979 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
8980
8981 let workspace_id = if let Some(workspace_id) =
8982 serialized_workspace.as_ref().map(|workspace| workspace.id)
8983 {
8984 workspace_id
8985 } else {
8986 persistence::DB.next_id().await?
8987 };
8988
8989 Ok((workspace_id, serialized_workspace))
8990 })
8991}
8992
8993pub fn join_in_room_project(
8994 project_id: u64,
8995 follow_user_id: u64,
8996 app_state: Arc<AppState>,
8997 cx: &mut App,
8998) -> Task<Result<()>> {
8999 let windows = cx.windows();
9000 cx.spawn(async move |cx| {
9001 let existing_window_and_workspace: Option<(
9002 WindowHandle<MultiWorkspace>,
9003 Entity<Workspace>,
9004 )> = windows.into_iter().find_map(|window_handle| {
9005 window_handle
9006 .downcast::<MultiWorkspace>()
9007 .and_then(|window_handle| {
9008 window_handle
9009 .update(cx, |multi_workspace, _window, cx| {
9010 for workspace in multi_workspace.workspaces() {
9011 if workspace.read(cx).project().read(cx).remote_id()
9012 == Some(project_id)
9013 {
9014 return Some((window_handle, workspace.clone()));
9015 }
9016 }
9017 None
9018 })
9019 .unwrap_or(None)
9020 })
9021 });
9022
9023 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9024 existing_window_and_workspace
9025 {
9026 existing_window
9027 .update(cx, |multi_workspace, _, cx| {
9028 multi_workspace.activate(target_workspace, cx);
9029 })
9030 .ok();
9031 existing_window
9032 } else {
9033 let active_call = cx.update(|cx| ActiveCall::global(cx));
9034 let room = active_call
9035 .read_with(cx, |call, _| call.room().cloned())
9036 .context("not in a call")?;
9037 let project = room
9038 .update(cx, |room, cx| {
9039 room.join_project(
9040 project_id,
9041 app_state.languages.clone(),
9042 app_state.fs.clone(),
9043 cx,
9044 )
9045 })
9046 .await?;
9047
9048 let window_bounds_override = window_bounds_env_override();
9049 cx.update(|cx| {
9050 let mut options = (app_state.build_window_options)(None, cx);
9051 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9052 cx.open_window(options, |window, cx| {
9053 let workspace = cx.new(|cx| {
9054 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9055 });
9056 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9057 })
9058 })?
9059 };
9060
9061 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9062 cx.activate(true);
9063 window.activate_window();
9064
9065 // We set the active workspace above, so this is the correct workspace.
9066 let workspace = multi_workspace.workspace().clone();
9067 workspace.update(cx, |workspace, cx| {
9068 if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
9069 let follow_peer_id = room
9070 .read(cx)
9071 .remote_participants()
9072 .iter()
9073 .find(|(_, participant)| participant.user.id == follow_user_id)
9074 .map(|(_, p)| p.peer_id)
9075 .or_else(|| {
9076 // If we couldn't follow the given user, follow the host instead.
9077 let collaborator = workspace
9078 .project()
9079 .read(cx)
9080 .collaborators()
9081 .values()
9082 .find(|collaborator| collaborator.is_host)?;
9083 Some(collaborator.peer_id)
9084 });
9085
9086 if let Some(follow_peer_id) = follow_peer_id {
9087 workspace.follow(follow_peer_id, window, cx);
9088 }
9089 }
9090 });
9091 })?;
9092
9093 anyhow::Ok(())
9094 })
9095}
9096
9097pub fn reload(cx: &mut App) {
9098 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9099 let mut workspace_windows = cx
9100 .windows()
9101 .into_iter()
9102 .filter_map(|window| window.downcast::<MultiWorkspace>())
9103 .collect::<Vec<_>>();
9104
9105 // If multiple windows have unsaved changes, and need a save prompt,
9106 // prompt in the active window before switching to a different window.
9107 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9108
9109 let mut prompt = None;
9110 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9111 prompt = window
9112 .update(cx, |_, window, cx| {
9113 window.prompt(
9114 PromptLevel::Info,
9115 "Are you sure you want to restart?",
9116 None,
9117 &["Restart", "Cancel"],
9118 cx,
9119 )
9120 })
9121 .ok();
9122 }
9123
9124 cx.spawn(async move |cx| {
9125 if let Some(prompt) = prompt {
9126 let answer = prompt.await?;
9127 if answer != 0 {
9128 return anyhow::Ok(());
9129 }
9130 }
9131
9132 // If the user cancels any save prompt, then keep the app open.
9133 for window in workspace_windows {
9134 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9135 let workspace = multi_workspace.workspace().clone();
9136 workspace.update(cx, |workspace, cx| {
9137 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9138 })
9139 }) && !should_close.await?
9140 {
9141 return anyhow::Ok(());
9142 }
9143 }
9144 cx.update(|cx| cx.restart());
9145 anyhow::Ok(())
9146 })
9147 .detach_and_log_err(cx);
9148}
9149
9150fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9151 let mut parts = value.split(',');
9152 let x: usize = parts.next()?.parse().ok()?;
9153 let y: usize = parts.next()?.parse().ok()?;
9154 Some(point(px(x as f32), px(y as f32)))
9155}
9156
9157fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9158 let mut parts = value.split(',');
9159 let width: usize = parts.next()?.parse().ok()?;
9160 let height: usize = parts.next()?.parse().ok()?;
9161 Some(size(px(width as f32), px(height as f32)))
9162}
9163
9164/// Add client-side decorations (rounded corners, shadows, resize handling) when
9165/// appropriate.
9166///
9167/// The `border_radius_tiling` parameter allows overriding which corners get
9168/// rounded, independently of the actual window tiling state. This is used
9169/// specifically for the workspace switcher sidebar: when the sidebar is open,
9170/// we want square corners on the left (so the sidebar appears flush with the
9171/// window edge) but we still need the shadow padding for proper visual
9172/// appearance. Unlike actual window tiling, this only affects border radius -
9173/// not padding or shadows.
9174pub fn client_side_decorations(
9175 element: impl IntoElement,
9176 window: &mut Window,
9177 cx: &mut App,
9178 border_radius_tiling: Tiling,
9179) -> Stateful<Div> {
9180 const BORDER_SIZE: Pixels = px(1.0);
9181 let decorations = window.window_decorations();
9182 let tiling = match decorations {
9183 Decorations::Server => Tiling::default(),
9184 Decorations::Client { tiling } => tiling,
9185 };
9186
9187 match decorations {
9188 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9189 Decorations::Server => window.set_client_inset(px(0.0)),
9190 }
9191
9192 struct GlobalResizeEdge(ResizeEdge);
9193 impl Global for GlobalResizeEdge {}
9194
9195 div()
9196 .id("window-backdrop")
9197 .bg(transparent_black())
9198 .map(|div| match decorations {
9199 Decorations::Server => div,
9200 Decorations::Client { .. } => div
9201 .when(
9202 !(tiling.top
9203 || tiling.right
9204 || border_radius_tiling.top
9205 || border_radius_tiling.right),
9206 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9207 )
9208 .when(
9209 !(tiling.top
9210 || tiling.left
9211 || border_radius_tiling.top
9212 || border_radius_tiling.left),
9213 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9214 )
9215 .when(
9216 !(tiling.bottom
9217 || tiling.right
9218 || border_radius_tiling.bottom
9219 || border_radius_tiling.right),
9220 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9221 )
9222 .when(
9223 !(tiling.bottom
9224 || tiling.left
9225 || border_radius_tiling.bottom
9226 || border_radius_tiling.left),
9227 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9228 )
9229 .when(!tiling.top, |div| {
9230 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9231 })
9232 .when(!tiling.bottom, |div| {
9233 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9234 })
9235 .when(!tiling.left, |div| {
9236 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9237 })
9238 .when(!tiling.right, |div| {
9239 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9240 })
9241 .on_mouse_move(move |e, window, cx| {
9242 let size = window.window_bounds().get_bounds().size;
9243 let pos = e.position;
9244
9245 let new_edge =
9246 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
9247
9248 let edge = cx.try_global::<GlobalResizeEdge>();
9249 if new_edge != edge.map(|edge| edge.0) {
9250 window
9251 .window_handle()
9252 .update(cx, |workspace, _, cx| {
9253 cx.notify(workspace.entity_id());
9254 })
9255 .ok();
9256 }
9257 })
9258 .on_mouse_down(MouseButton::Left, move |e, window, _| {
9259 let size = window.window_bounds().get_bounds().size;
9260 let pos = e.position;
9261
9262 let edge = match resize_edge(
9263 pos,
9264 theme::CLIENT_SIDE_DECORATION_SHADOW,
9265 size,
9266 tiling,
9267 ) {
9268 Some(value) => value,
9269 None => return,
9270 };
9271
9272 window.start_window_resize(edge);
9273 }),
9274 })
9275 .size_full()
9276 .child(
9277 div()
9278 .cursor(CursorStyle::Arrow)
9279 .map(|div| match decorations {
9280 Decorations::Server => div,
9281 Decorations::Client { .. } => div
9282 .border_color(cx.theme().colors().border)
9283 .when(
9284 !(tiling.top
9285 || tiling.right
9286 || border_radius_tiling.top
9287 || border_radius_tiling.right),
9288 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9289 )
9290 .when(
9291 !(tiling.top
9292 || tiling.left
9293 || border_radius_tiling.top
9294 || border_radius_tiling.left),
9295 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9296 )
9297 .when(
9298 !(tiling.bottom
9299 || tiling.right
9300 || border_radius_tiling.bottom
9301 || border_radius_tiling.right),
9302 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9303 )
9304 .when(
9305 !(tiling.bottom
9306 || tiling.left
9307 || border_radius_tiling.bottom
9308 || border_radius_tiling.left),
9309 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9310 )
9311 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
9312 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
9313 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
9314 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
9315 .when(!tiling.is_tiled(), |div| {
9316 div.shadow(vec![gpui::BoxShadow {
9317 color: Hsla {
9318 h: 0.,
9319 s: 0.,
9320 l: 0.,
9321 a: 0.4,
9322 },
9323 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
9324 spread_radius: px(0.),
9325 offset: point(px(0.0), px(0.0)),
9326 }])
9327 }),
9328 })
9329 .on_mouse_move(|_e, _, cx| {
9330 cx.stop_propagation();
9331 })
9332 .size_full()
9333 .child(element),
9334 )
9335 .map(|div| match decorations {
9336 Decorations::Server => div,
9337 Decorations::Client { tiling, .. } => div.child(
9338 canvas(
9339 |_bounds, window, _| {
9340 window.insert_hitbox(
9341 Bounds::new(
9342 point(px(0.0), px(0.0)),
9343 window.window_bounds().get_bounds().size,
9344 ),
9345 HitboxBehavior::Normal,
9346 )
9347 },
9348 move |_bounds, hitbox, window, cx| {
9349 let mouse = window.mouse_position();
9350 let size = window.window_bounds().get_bounds().size;
9351 let Some(edge) =
9352 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
9353 else {
9354 return;
9355 };
9356 cx.set_global(GlobalResizeEdge(edge));
9357 window.set_cursor_style(
9358 match edge {
9359 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
9360 ResizeEdge::Left | ResizeEdge::Right => {
9361 CursorStyle::ResizeLeftRight
9362 }
9363 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
9364 CursorStyle::ResizeUpLeftDownRight
9365 }
9366 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
9367 CursorStyle::ResizeUpRightDownLeft
9368 }
9369 },
9370 &hitbox,
9371 );
9372 },
9373 )
9374 .size_full()
9375 .absolute(),
9376 ),
9377 })
9378}
9379
9380fn resize_edge(
9381 pos: Point<Pixels>,
9382 shadow_size: Pixels,
9383 window_size: Size<Pixels>,
9384 tiling: Tiling,
9385) -> Option<ResizeEdge> {
9386 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
9387 if bounds.contains(&pos) {
9388 return None;
9389 }
9390
9391 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
9392 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
9393 if !tiling.top && top_left_bounds.contains(&pos) {
9394 return Some(ResizeEdge::TopLeft);
9395 }
9396
9397 let top_right_bounds = Bounds::new(
9398 Point::new(window_size.width - corner_size.width, px(0.)),
9399 corner_size,
9400 );
9401 if !tiling.top && top_right_bounds.contains(&pos) {
9402 return Some(ResizeEdge::TopRight);
9403 }
9404
9405 let bottom_left_bounds = Bounds::new(
9406 Point::new(px(0.), window_size.height - corner_size.height),
9407 corner_size,
9408 );
9409 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
9410 return Some(ResizeEdge::BottomLeft);
9411 }
9412
9413 let bottom_right_bounds = Bounds::new(
9414 Point::new(
9415 window_size.width - corner_size.width,
9416 window_size.height - corner_size.height,
9417 ),
9418 corner_size,
9419 );
9420 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
9421 return Some(ResizeEdge::BottomRight);
9422 }
9423
9424 if !tiling.top && pos.y < shadow_size {
9425 Some(ResizeEdge::Top)
9426 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
9427 Some(ResizeEdge::Bottom)
9428 } else if !tiling.left && pos.x < shadow_size {
9429 Some(ResizeEdge::Left)
9430 } else if !tiling.right && pos.x > window_size.width - shadow_size {
9431 Some(ResizeEdge::Right)
9432 } else {
9433 None
9434 }
9435}
9436
9437fn join_pane_into_active(
9438 active_pane: &Entity<Pane>,
9439 pane: &Entity<Pane>,
9440 window: &mut Window,
9441 cx: &mut App,
9442) {
9443 if pane == active_pane {
9444 } else if pane.read(cx).items_len() == 0 {
9445 pane.update(cx, |_, cx| {
9446 cx.emit(pane::Event::Remove {
9447 focus_on_pane: None,
9448 });
9449 })
9450 } else {
9451 move_all_items(pane, active_pane, window, cx);
9452 }
9453}
9454
9455fn move_all_items(
9456 from_pane: &Entity<Pane>,
9457 to_pane: &Entity<Pane>,
9458 window: &mut Window,
9459 cx: &mut App,
9460) {
9461 let destination_is_different = from_pane != to_pane;
9462 let mut moved_items = 0;
9463 for (item_ix, item_handle) in from_pane
9464 .read(cx)
9465 .items()
9466 .enumerate()
9467 .map(|(ix, item)| (ix, item.clone()))
9468 .collect::<Vec<_>>()
9469 {
9470 let ix = item_ix - moved_items;
9471 if destination_is_different {
9472 // Close item from previous pane
9473 from_pane.update(cx, |source, cx| {
9474 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
9475 });
9476 moved_items += 1;
9477 }
9478
9479 // This automatically removes duplicate items in the pane
9480 to_pane.update(cx, |destination, cx| {
9481 destination.add_item(item_handle, true, true, None, window, cx);
9482 window.focus(&destination.focus_handle(cx), cx)
9483 });
9484 }
9485}
9486
9487pub fn move_item(
9488 source: &Entity<Pane>,
9489 destination: &Entity<Pane>,
9490 item_id_to_move: EntityId,
9491 destination_index: usize,
9492 activate: bool,
9493 window: &mut Window,
9494 cx: &mut App,
9495) {
9496 let Some((item_ix, item_handle)) = source
9497 .read(cx)
9498 .items()
9499 .enumerate()
9500 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
9501 .map(|(ix, item)| (ix, item.clone()))
9502 else {
9503 // Tab was closed during drag
9504 return;
9505 };
9506
9507 if source != destination {
9508 // Close item from previous pane
9509 source.update(cx, |source, cx| {
9510 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
9511 });
9512 }
9513
9514 // This automatically removes duplicate items in the pane
9515 destination.update(cx, |destination, cx| {
9516 destination.add_item_inner(
9517 item_handle,
9518 activate,
9519 activate,
9520 activate,
9521 Some(destination_index),
9522 window,
9523 cx,
9524 );
9525 if activate {
9526 window.focus(&destination.focus_handle(cx), cx)
9527 }
9528 });
9529}
9530
9531pub fn move_active_item(
9532 source: &Entity<Pane>,
9533 destination: &Entity<Pane>,
9534 focus_destination: bool,
9535 close_if_empty: bool,
9536 window: &mut Window,
9537 cx: &mut App,
9538) {
9539 if source == destination {
9540 return;
9541 }
9542 let Some(active_item) = source.read(cx).active_item() else {
9543 return;
9544 };
9545 source.update(cx, |source_pane, cx| {
9546 let item_id = active_item.item_id();
9547 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
9548 destination.update(cx, |target_pane, cx| {
9549 target_pane.add_item(
9550 active_item,
9551 focus_destination,
9552 focus_destination,
9553 Some(target_pane.items_len()),
9554 window,
9555 cx,
9556 );
9557 });
9558 });
9559}
9560
9561pub fn clone_active_item(
9562 workspace_id: Option<WorkspaceId>,
9563 source: &Entity<Pane>,
9564 destination: &Entity<Pane>,
9565 focus_destination: bool,
9566 window: &mut Window,
9567 cx: &mut App,
9568) {
9569 if source == destination {
9570 return;
9571 }
9572 let Some(active_item) = source.read(cx).active_item() else {
9573 return;
9574 };
9575 if !active_item.can_split(cx) {
9576 return;
9577 }
9578 let destination = destination.downgrade();
9579 let task = active_item.clone_on_split(workspace_id, window, cx);
9580 window
9581 .spawn(cx, async move |cx| {
9582 let Some(clone) = task.await else {
9583 return;
9584 };
9585 destination
9586 .update_in(cx, |target_pane, window, cx| {
9587 target_pane.add_item(
9588 clone,
9589 focus_destination,
9590 focus_destination,
9591 Some(target_pane.items_len()),
9592 window,
9593 cx,
9594 );
9595 })
9596 .log_err();
9597 })
9598 .detach();
9599}
9600
9601#[derive(Debug)]
9602pub struct WorkspacePosition {
9603 pub window_bounds: Option<WindowBounds>,
9604 pub display: Option<Uuid>,
9605 pub centered_layout: bool,
9606}
9607
9608pub fn remote_workspace_position_from_db(
9609 connection_options: RemoteConnectionOptions,
9610 paths_to_open: &[PathBuf],
9611 cx: &App,
9612) -> Task<Result<WorkspacePosition>> {
9613 let paths = paths_to_open.to_vec();
9614
9615 cx.background_spawn(async move {
9616 let remote_connection_id = persistence::DB
9617 .get_or_create_remote_connection(connection_options)
9618 .await
9619 .context("fetching serialized ssh project")?;
9620 let serialized_workspace =
9621 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
9622
9623 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
9624 (Some(WindowBounds::Windowed(bounds)), None)
9625 } else {
9626 let restorable_bounds = serialized_workspace
9627 .as_ref()
9628 .and_then(|workspace| {
9629 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
9630 })
9631 .or_else(|| persistence::read_default_window_bounds());
9632
9633 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
9634 (Some(serialized_bounds), Some(serialized_display))
9635 } else {
9636 (None, None)
9637 }
9638 };
9639
9640 let centered_layout = serialized_workspace
9641 .as_ref()
9642 .map(|w| w.centered_layout)
9643 .unwrap_or(false);
9644
9645 Ok(WorkspacePosition {
9646 window_bounds,
9647 display,
9648 centered_layout,
9649 })
9650 })
9651}
9652
9653pub fn with_active_or_new_workspace(
9654 cx: &mut App,
9655 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
9656) {
9657 match cx
9658 .active_window()
9659 .and_then(|w| w.downcast::<MultiWorkspace>())
9660 {
9661 Some(multi_workspace) => {
9662 cx.defer(move |cx| {
9663 multi_workspace
9664 .update(cx, |multi_workspace, window, cx| {
9665 let workspace = multi_workspace.workspace().clone();
9666 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
9667 })
9668 .log_err();
9669 });
9670 }
9671 None => {
9672 let app_state = AppState::global(cx);
9673 if let Some(app_state) = app_state.upgrade() {
9674 open_new(
9675 OpenOptions::default(),
9676 app_state,
9677 cx,
9678 move |workspace, window, cx| f(workspace, window, cx),
9679 )
9680 .detach_and_log_err(cx);
9681 }
9682 }
9683 }
9684}
9685
9686#[cfg(test)]
9687mod tests {
9688 use std::{cell::RefCell, rc::Rc};
9689
9690 use super::*;
9691 use crate::{
9692 dock::{PanelEvent, test::TestPanel},
9693 item::{
9694 ItemBufferKind, ItemEvent,
9695 test::{TestItem, TestProjectItem},
9696 },
9697 };
9698 use fs::FakeFs;
9699 use gpui::{
9700 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
9701 UpdateGlobal, VisualTestContext, px,
9702 };
9703 use project::{Project, ProjectEntryId};
9704 use serde_json::json;
9705 use settings::SettingsStore;
9706 use util::rel_path::rel_path;
9707
9708 #[gpui::test]
9709 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
9710 init_test(cx);
9711
9712 let fs = FakeFs::new(cx.executor());
9713 let project = Project::test(fs, [], cx).await;
9714 let (workspace, cx) =
9715 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9716
9717 // Adding an item with no ambiguity renders the tab without detail.
9718 let item1 = cx.new(|cx| {
9719 let mut item = TestItem::new(cx);
9720 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
9721 item
9722 });
9723 workspace.update_in(cx, |workspace, window, cx| {
9724 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
9725 });
9726 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
9727
9728 // Adding an item that creates ambiguity increases the level of detail on
9729 // both tabs.
9730 let item2 = cx.new_window_entity(|_window, cx| {
9731 let mut item = TestItem::new(cx);
9732 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
9733 item
9734 });
9735 workspace.update_in(cx, |workspace, window, cx| {
9736 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
9737 });
9738 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
9739 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
9740
9741 // Adding an item that creates ambiguity increases the level of detail only
9742 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
9743 // we stop at the highest detail available.
9744 let item3 = cx.new(|cx| {
9745 let mut item = TestItem::new(cx);
9746 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
9747 item
9748 });
9749 workspace.update_in(cx, |workspace, window, cx| {
9750 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
9751 });
9752 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
9753 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
9754 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
9755 }
9756
9757 #[gpui::test]
9758 async fn test_tracking_active_path(cx: &mut TestAppContext) {
9759 init_test(cx);
9760
9761 let fs = FakeFs::new(cx.executor());
9762 fs.insert_tree(
9763 "/root1",
9764 json!({
9765 "one.txt": "",
9766 "two.txt": "",
9767 }),
9768 )
9769 .await;
9770 fs.insert_tree(
9771 "/root2",
9772 json!({
9773 "three.txt": "",
9774 }),
9775 )
9776 .await;
9777
9778 let project = Project::test(fs, ["root1".as_ref()], cx).await;
9779 let (workspace, cx) =
9780 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9781 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9782 let worktree_id = project.update(cx, |project, cx| {
9783 project.worktrees(cx).next().unwrap().read(cx).id()
9784 });
9785
9786 let item1 = cx.new(|cx| {
9787 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
9788 });
9789 let item2 = cx.new(|cx| {
9790 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
9791 });
9792
9793 // Add an item to an empty pane
9794 workspace.update_in(cx, |workspace, window, cx| {
9795 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
9796 });
9797 project.update(cx, |project, cx| {
9798 assert_eq!(
9799 project.active_entry(),
9800 project
9801 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
9802 .map(|e| e.id)
9803 );
9804 });
9805 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
9806
9807 // Add a second item to a non-empty pane
9808 workspace.update_in(cx, |workspace, window, cx| {
9809 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
9810 });
9811 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
9812 project.update(cx, |project, cx| {
9813 assert_eq!(
9814 project.active_entry(),
9815 project
9816 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
9817 .map(|e| e.id)
9818 );
9819 });
9820
9821 // Close the active item
9822 pane.update_in(cx, |pane, window, cx| {
9823 pane.close_active_item(&Default::default(), window, cx)
9824 })
9825 .await
9826 .unwrap();
9827 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
9828 project.update(cx, |project, cx| {
9829 assert_eq!(
9830 project.active_entry(),
9831 project
9832 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
9833 .map(|e| e.id)
9834 );
9835 });
9836
9837 // Add a project folder
9838 project
9839 .update(cx, |project, cx| {
9840 project.find_or_create_worktree("root2", true, cx)
9841 })
9842 .await
9843 .unwrap();
9844 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
9845
9846 // Remove a project folder
9847 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
9848 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
9849 }
9850
9851 #[gpui::test]
9852 async fn test_close_window(cx: &mut TestAppContext) {
9853 init_test(cx);
9854
9855 let fs = FakeFs::new(cx.executor());
9856 fs.insert_tree("/root", json!({ "one": "" })).await;
9857
9858 let project = Project::test(fs, ["root".as_ref()], cx).await;
9859 let (workspace, cx) =
9860 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9861
9862 // When there are no dirty items, there's nothing to do.
9863 let item1 = cx.new(TestItem::new);
9864 workspace.update_in(cx, |w, window, cx| {
9865 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
9866 });
9867 let task = workspace.update_in(cx, |w, window, cx| {
9868 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
9869 });
9870 assert!(task.await.unwrap());
9871
9872 // When there are dirty untitled items, prompt to save each one. If the user
9873 // cancels any prompt, then abort.
9874 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
9875 let item3 = cx.new(|cx| {
9876 TestItem::new(cx)
9877 .with_dirty(true)
9878 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
9879 });
9880 workspace.update_in(cx, |w, window, cx| {
9881 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
9882 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
9883 });
9884 let task = workspace.update_in(cx, |w, window, cx| {
9885 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
9886 });
9887 cx.executor().run_until_parked();
9888 cx.simulate_prompt_answer("Cancel"); // cancel save all
9889 cx.executor().run_until_parked();
9890 assert!(!cx.has_pending_prompt());
9891 assert!(!task.await.unwrap());
9892 }
9893
9894 #[gpui::test]
9895 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
9896 init_test(cx);
9897
9898 // Register TestItem as a serializable item
9899 cx.update(|cx| {
9900 register_serializable_item::<TestItem>(cx);
9901 });
9902
9903 let fs = FakeFs::new(cx.executor());
9904 fs.insert_tree("/root", json!({ "one": "" })).await;
9905
9906 let project = Project::test(fs, ["root".as_ref()], cx).await;
9907 let (workspace, cx) =
9908 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9909
9910 // When there are dirty untitled items, but they can serialize, then there is no prompt.
9911 let item1 = cx.new(|cx| {
9912 TestItem::new(cx)
9913 .with_dirty(true)
9914 .with_serialize(|| Some(Task::ready(Ok(()))))
9915 });
9916 let item2 = cx.new(|cx| {
9917 TestItem::new(cx)
9918 .with_dirty(true)
9919 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
9920 .with_serialize(|| Some(Task::ready(Ok(()))))
9921 });
9922 workspace.update_in(cx, |w, window, cx| {
9923 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
9924 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
9925 });
9926 let task = workspace.update_in(cx, |w, window, cx| {
9927 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
9928 });
9929 assert!(task.await.unwrap());
9930 }
9931
9932 #[gpui::test]
9933 async fn test_close_pane_items(cx: &mut TestAppContext) {
9934 init_test(cx);
9935
9936 let fs = FakeFs::new(cx.executor());
9937
9938 let project = Project::test(fs, None, cx).await;
9939 let (workspace, cx) =
9940 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9941
9942 let item1 = cx.new(|cx| {
9943 TestItem::new(cx)
9944 .with_dirty(true)
9945 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
9946 });
9947 let item2 = cx.new(|cx| {
9948 TestItem::new(cx)
9949 .with_dirty(true)
9950 .with_conflict(true)
9951 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
9952 });
9953 let item3 = cx.new(|cx| {
9954 TestItem::new(cx)
9955 .with_dirty(true)
9956 .with_conflict(true)
9957 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
9958 });
9959 let item4 = cx.new(|cx| {
9960 TestItem::new(cx).with_dirty(true).with_project_items(&[{
9961 let project_item = TestProjectItem::new_untitled(cx);
9962 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
9963 project_item
9964 }])
9965 });
9966 let pane = workspace.update_in(cx, |workspace, window, cx| {
9967 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
9968 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
9969 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
9970 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
9971 workspace.active_pane().clone()
9972 });
9973
9974 let close_items = pane.update_in(cx, |pane, window, cx| {
9975 pane.activate_item(1, true, true, window, cx);
9976 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
9977 let item1_id = item1.item_id();
9978 let item3_id = item3.item_id();
9979 let item4_id = item4.item_id();
9980 pane.close_items(window, cx, SaveIntent::Close, move |id| {
9981 [item1_id, item3_id, item4_id].contains(&id)
9982 })
9983 });
9984 cx.executor().run_until_parked();
9985
9986 assert!(cx.has_pending_prompt());
9987 cx.simulate_prompt_answer("Save all");
9988
9989 cx.executor().run_until_parked();
9990
9991 // Item 1 is saved. There's a prompt to save item 3.
9992 pane.update(cx, |pane, cx| {
9993 assert_eq!(item1.read(cx).save_count, 1);
9994 assert_eq!(item1.read(cx).save_as_count, 0);
9995 assert_eq!(item1.read(cx).reload_count, 0);
9996 assert_eq!(pane.items_len(), 3);
9997 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
9998 });
9999 assert!(cx.has_pending_prompt());
10000
10001 // Cancel saving item 3.
10002 cx.simulate_prompt_answer("Discard");
10003 cx.executor().run_until_parked();
10004
10005 // Item 3 is reloaded. There's a prompt to save item 4.
10006 pane.update(cx, |pane, cx| {
10007 assert_eq!(item3.read(cx).save_count, 0);
10008 assert_eq!(item3.read(cx).save_as_count, 0);
10009 assert_eq!(item3.read(cx).reload_count, 1);
10010 assert_eq!(pane.items_len(), 2);
10011 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10012 });
10013
10014 // There's a prompt for a path for item 4.
10015 cx.simulate_new_path_selection(|_| Some(Default::default()));
10016 close_items.await.unwrap();
10017
10018 // The requested items are closed.
10019 pane.update(cx, |pane, cx| {
10020 assert_eq!(item4.read(cx).save_count, 0);
10021 assert_eq!(item4.read(cx).save_as_count, 1);
10022 assert_eq!(item4.read(cx).reload_count, 0);
10023 assert_eq!(pane.items_len(), 1);
10024 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10025 });
10026 }
10027
10028 #[gpui::test]
10029 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10030 init_test(cx);
10031
10032 let fs = FakeFs::new(cx.executor());
10033 let project = Project::test(fs, [], cx).await;
10034 let (workspace, cx) =
10035 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10036
10037 // Create several workspace items with single project entries, and two
10038 // workspace items with multiple project entries.
10039 let single_entry_items = (0..=4)
10040 .map(|project_entry_id| {
10041 cx.new(|cx| {
10042 TestItem::new(cx)
10043 .with_dirty(true)
10044 .with_project_items(&[dirty_project_item(
10045 project_entry_id,
10046 &format!("{project_entry_id}.txt"),
10047 cx,
10048 )])
10049 })
10050 })
10051 .collect::<Vec<_>>();
10052 let item_2_3 = cx.new(|cx| {
10053 TestItem::new(cx)
10054 .with_dirty(true)
10055 .with_buffer_kind(ItemBufferKind::Multibuffer)
10056 .with_project_items(&[
10057 single_entry_items[2].read(cx).project_items[0].clone(),
10058 single_entry_items[3].read(cx).project_items[0].clone(),
10059 ])
10060 });
10061 let item_3_4 = cx.new(|cx| {
10062 TestItem::new(cx)
10063 .with_dirty(true)
10064 .with_buffer_kind(ItemBufferKind::Multibuffer)
10065 .with_project_items(&[
10066 single_entry_items[3].read(cx).project_items[0].clone(),
10067 single_entry_items[4].read(cx).project_items[0].clone(),
10068 ])
10069 });
10070
10071 // Create two panes that contain the following project entries:
10072 // left pane:
10073 // multi-entry items: (2, 3)
10074 // single-entry items: 0, 2, 3, 4
10075 // right pane:
10076 // single-entry items: 4, 1
10077 // multi-entry items: (3, 4)
10078 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10079 let left_pane = workspace.active_pane().clone();
10080 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10081 workspace.add_item_to_active_pane(
10082 single_entry_items[0].boxed_clone(),
10083 None,
10084 true,
10085 window,
10086 cx,
10087 );
10088 workspace.add_item_to_active_pane(
10089 single_entry_items[2].boxed_clone(),
10090 None,
10091 true,
10092 window,
10093 cx,
10094 );
10095 workspace.add_item_to_active_pane(
10096 single_entry_items[3].boxed_clone(),
10097 None,
10098 true,
10099 window,
10100 cx,
10101 );
10102 workspace.add_item_to_active_pane(
10103 single_entry_items[4].boxed_clone(),
10104 None,
10105 true,
10106 window,
10107 cx,
10108 );
10109
10110 let right_pane =
10111 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10112
10113 let boxed_clone = single_entry_items[1].boxed_clone();
10114 let right_pane = window.spawn(cx, async move |cx| {
10115 right_pane.await.inspect(|right_pane| {
10116 right_pane
10117 .update_in(cx, |pane, window, cx| {
10118 pane.add_item(boxed_clone, true, true, None, window, cx);
10119 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10120 })
10121 .unwrap();
10122 })
10123 });
10124
10125 (left_pane, right_pane)
10126 });
10127 let right_pane = right_pane.await.unwrap();
10128 cx.focus(&right_pane);
10129
10130 let close = right_pane.update_in(cx, |pane, window, cx| {
10131 pane.close_all_items(&CloseAllItems::default(), window, cx)
10132 .unwrap()
10133 });
10134 cx.executor().run_until_parked();
10135
10136 let msg = cx.pending_prompt().unwrap().0;
10137 assert!(msg.contains("1.txt"));
10138 assert!(!msg.contains("2.txt"));
10139 assert!(!msg.contains("3.txt"));
10140 assert!(!msg.contains("4.txt"));
10141
10142 // With best-effort close, cancelling item 1 keeps it open but items 4
10143 // and (3,4) still close since their entries exist in left pane.
10144 cx.simulate_prompt_answer("Cancel");
10145 close.await;
10146
10147 right_pane.read_with(cx, |pane, _| {
10148 assert_eq!(pane.items_len(), 1);
10149 });
10150
10151 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10152 left_pane
10153 .update_in(cx, |left_pane, window, cx| {
10154 left_pane.close_item_by_id(
10155 single_entry_items[3].entity_id(),
10156 SaveIntent::Skip,
10157 window,
10158 cx,
10159 )
10160 })
10161 .await
10162 .unwrap();
10163
10164 let close = left_pane.update_in(cx, |pane, window, cx| {
10165 pane.close_all_items(&CloseAllItems::default(), window, cx)
10166 .unwrap()
10167 });
10168 cx.executor().run_until_parked();
10169
10170 let details = cx.pending_prompt().unwrap().1;
10171 assert!(details.contains("0.txt"));
10172 assert!(details.contains("3.txt"));
10173 assert!(details.contains("4.txt"));
10174 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10175 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10176 // assert!(!details.contains("2.txt"));
10177
10178 cx.simulate_prompt_answer("Save all");
10179 cx.executor().run_until_parked();
10180 close.await;
10181
10182 left_pane.read_with(cx, |pane, _| {
10183 assert_eq!(pane.items_len(), 0);
10184 });
10185 }
10186
10187 #[gpui::test]
10188 async fn test_autosave(cx: &mut gpui::TestAppContext) {
10189 init_test(cx);
10190
10191 let fs = FakeFs::new(cx.executor());
10192 let project = Project::test(fs, [], cx).await;
10193 let (workspace, cx) =
10194 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10195 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10196
10197 let item = cx.new(|cx| {
10198 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10199 });
10200 let item_id = item.entity_id();
10201 workspace.update_in(cx, |workspace, window, cx| {
10202 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10203 });
10204
10205 // Autosave on window change.
10206 item.update(cx, |item, cx| {
10207 SettingsStore::update_global(cx, |settings, cx| {
10208 settings.update_user_settings(cx, |settings| {
10209 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10210 })
10211 });
10212 item.is_dirty = true;
10213 });
10214
10215 // Deactivating the window saves the file.
10216 cx.deactivate_window();
10217 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10218
10219 // Re-activating the window doesn't save the file.
10220 cx.update(|window, _| window.activate_window());
10221 cx.executor().run_until_parked();
10222 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10223
10224 // Autosave on focus change.
10225 item.update_in(cx, |item, window, cx| {
10226 cx.focus_self(window);
10227 SettingsStore::update_global(cx, |settings, cx| {
10228 settings.update_user_settings(cx, |settings| {
10229 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10230 })
10231 });
10232 item.is_dirty = true;
10233 });
10234 // Blurring the item saves the file.
10235 item.update_in(cx, |_, window, _| window.blur());
10236 cx.executor().run_until_parked();
10237 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10238
10239 // Deactivating the window still saves the file.
10240 item.update_in(cx, |item, window, cx| {
10241 cx.focus_self(window);
10242 item.is_dirty = true;
10243 });
10244 cx.deactivate_window();
10245 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10246
10247 // Autosave after delay.
10248 item.update(cx, |item, cx| {
10249 SettingsStore::update_global(cx, |settings, cx| {
10250 settings.update_user_settings(cx, |settings| {
10251 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10252 milliseconds: 500.into(),
10253 });
10254 })
10255 });
10256 item.is_dirty = true;
10257 cx.emit(ItemEvent::Edit);
10258 });
10259
10260 // Delay hasn't fully expired, so the file is still dirty and unsaved.
10261 cx.executor().advance_clock(Duration::from_millis(250));
10262 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10263
10264 // After delay expires, the file is saved.
10265 cx.executor().advance_clock(Duration::from_millis(250));
10266 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10267
10268 // Autosave after delay, should save earlier than delay if tab is closed
10269 item.update(cx, |item, cx| {
10270 item.is_dirty = true;
10271 cx.emit(ItemEvent::Edit);
10272 });
10273 cx.executor().advance_clock(Duration::from_millis(250));
10274 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10275
10276 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10277 pane.update_in(cx, |pane, window, cx| {
10278 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
10279 })
10280 .await
10281 .unwrap();
10282 assert!(!cx.has_pending_prompt());
10283 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10284
10285 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10286 workspace.update_in(cx, |workspace, window, cx| {
10287 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10288 });
10289 item.update_in(cx, |item, _window, cx| {
10290 item.is_dirty = true;
10291 for project_item in &mut item.project_items {
10292 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10293 }
10294 });
10295 cx.run_until_parked();
10296 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10297
10298 // Autosave on focus change, ensuring closing the tab counts as such.
10299 item.update(cx, |item, cx| {
10300 SettingsStore::update_global(cx, |settings, cx| {
10301 settings.update_user_settings(cx, |settings| {
10302 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10303 })
10304 });
10305 item.is_dirty = true;
10306 for project_item in &mut item.project_items {
10307 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10308 }
10309 });
10310
10311 pane.update_in(cx, |pane, window, cx| {
10312 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
10313 })
10314 .await
10315 .unwrap();
10316 assert!(!cx.has_pending_prompt());
10317 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10318
10319 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10320 workspace.update_in(cx, |workspace, window, cx| {
10321 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10322 });
10323 item.update_in(cx, |item, window, cx| {
10324 item.project_items[0].update(cx, |item, _| {
10325 item.entry_id = None;
10326 });
10327 item.is_dirty = true;
10328 window.blur();
10329 });
10330 cx.run_until_parked();
10331 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10332
10333 // Ensure autosave is prevented for deleted files also when closing the buffer.
10334 let _close_items = pane.update_in(cx, |pane, window, cx| {
10335 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
10336 });
10337 cx.run_until_parked();
10338 assert!(cx.has_pending_prompt());
10339 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10340 }
10341
10342 #[gpui::test]
10343 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10344 init_test(cx);
10345
10346 let fs = FakeFs::new(cx.executor());
10347
10348 let project = Project::test(fs, [], cx).await;
10349 let (workspace, cx) =
10350 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10351
10352 let item = cx.new(|cx| {
10353 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10354 });
10355 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10356 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10357 let toolbar_notify_count = Rc::new(RefCell::new(0));
10358
10359 workspace.update_in(cx, |workspace, window, cx| {
10360 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10361 let toolbar_notification_count = toolbar_notify_count.clone();
10362 cx.observe_in(&toolbar, window, move |_, _, _, _| {
10363 *toolbar_notification_count.borrow_mut() += 1
10364 })
10365 .detach();
10366 });
10367
10368 pane.read_with(cx, |pane, _| {
10369 assert!(!pane.can_navigate_backward());
10370 assert!(!pane.can_navigate_forward());
10371 });
10372
10373 item.update_in(cx, |item, _, cx| {
10374 item.set_state("one".to_string(), cx);
10375 });
10376
10377 // Toolbar must be notified to re-render the navigation buttons
10378 assert_eq!(*toolbar_notify_count.borrow(), 1);
10379
10380 pane.read_with(cx, |pane, _| {
10381 assert!(pane.can_navigate_backward());
10382 assert!(!pane.can_navigate_forward());
10383 });
10384
10385 workspace
10386 .update_in(cx, |workspace, window, cx| {
10387 workspace.go_back(pane.downgrade(), window, cx)
10388 })
10389 .await
10390 .unwrap();
10391
10392 assert_eq!(*toolbar_notify_count.borrow(), 2);
10393 pane.read_with(cx, |pane, _| {
10394 assert!(!pane.can_navigate_backward());
10395 assert!(pane.can_navigate_forward());
10396 });
10397 }
10398
10399 #[gpui::test]
10400 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
10401 init_test(cx);
10402 let fs = FakeFs::new(cx.executor());
10403
10404 let project = Project::test(fs, [], cx).await;
10405 let (workspace, cx) =
10406 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10407
10408 let panel = workspace.update_in(cx, |workspace, window, cx| {
10409 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10410 workspace.add_panel(panel.clone(), window, cx);
10411
10412 workspace
10413 .right_dock()
10414 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10415
10416 panel
10417 });
10418
10419 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10420 pane.update_in(cx, |pane, window, cx| {
10421 let item = cx.new(TestItem::new);
10422 pane.add_item(Box::new(item), true, true, None, window, cx);
10423 });
10424
10425 // Transfer focus from center to panel
10426 workspace.update_in(cx, |workspace, window, cx| {
10427 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10428 });
10429
10430 workspace.update_in(cx, |workspace, window, cx| {
10431 assert!(workspace.right_dock().read(cx).is_open());
10432 assert!(!panel.is_zoomed(window, cx));
10433 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10434 });
10435
10436 // Transfer focus from panel to center
10437 workspace.update_in(cx, |workspace, window, cx| {
10438 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10439 });
10440
10441 workspace.update_in(cx, |workspace, window, cx| {
10442 assert!(workspace.right_dock().read(cx).is_open());
10443 assert!(!panel.is_zoomed(window, cx));
10444 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10445 });
10446
10447 // Close the dock
10448 workspace.update_in(cx, |workspace, window, cx| {
10449 workspace.toggle_dock(DockPosition::Right, window, cx);
10450 });
10451
10452 workspace.update_in(cx, |workspace, window, cx| {
10453 assert!(!workspace.right_dock().read(cx).is_open());
10454 assert!(!panel.is_zoomed(window, cx));
10455 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10456 });
10457
10458 // Open the dock
10459 workspace.update_in(cx, |workspace, window, cx| {
10460 workspace.toggle_dock(DockPosition::Right, window, cx);
10461 });
10462
10463 workspace.update_in(cx, |workspace, window, cx| {
10464 assert!(workspace.right_dock().read(cx).is_open());
10465 assert!(!panel.is_zoomed(window, cx));
10466 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10467 });
10468
10469 // Focus and zoom panel
10470 panel.update_in(cx, |panel, window, cx| {
10471 cx.focus_self(window);
10472 panel.set_zoomed(true, window, cx)
10473 });
10474
10475 workspace.update_in(cx, |workspace, window, cx| {
10476 assert!(workspace.right_dock().read(cx).is_open());
10477 assert!(panel.is_zoomed(window, cx));
10478 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10479 });
10480
10481 // Transfer focus to the center closes the dock
10482 workspace.update_in(cx, |workspace, window, cx| {
10483 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10484 });
10485
10486 workspace.update_in(cx, |workspace, window, cx| {
10487 assert!(!workspace.right_dock().read(cx).is_open());
10488 assert!(panel.is_zoomed(window, cx));
10489 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10490 });
10491
10492 // Transferring focus back to the panel keeps it zoomed
10493 workspace.update_in(cx, |workspace, window, cx| {
10494 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10495 });
10496
10497 workspace.update_in(cx, |workspace, window, cx| {
10498 assert!(workspace.right_dock().read(cx).is_open());
10499 assert!(panel.is_zoomed(window, cx));
10500 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10501 });
10502
10503 // Close the dock while it is zoomed
10504 workspace.update_in(cx, |workspace, window, cx| {
10505 workspace.toggle_dock(DockPosition::Right, window, cx)
10506 });
10507
10508 workspace.update_in(cx, |workspace, window, cx| {
10509 assert!(!workspace.right_dock().read(cx).is_open());
10510 assert!(panel.is_zoomed(window, cx));
10511 assert!(workspace.zoomed.is_none());
10512 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10513 });
10514
10515 // Opening the dock, when it's zoomed, retains focus
10516 workspace.update_in(cx, |workspace, window, cx| {
10517 workspace.toggle_dock(DockPosition::Right, window, cx)
10518 });
10519
10520 workspace.update_in(cx, |workspace, window, cx| {
10521 assert!(workspace.right_dock().read(cx).is_open());
10522 assert!(panel.is_zoomed(window, cx));
10523 assert!(workspace.zoomed.is_some());
10524 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10525 });
10526
10527 // Unzoom and close the panel, zoom the active pane.
10528 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
10529 workspace.update_in(cx, |workspace, window, cx| {
10530 workspace.toggle_dock(DockPosition::Right, window, cx)
10531 });
10532 pane.update_in(cx, |pane, window, cx| {
10533 pane.toggle_zoom(&Default::default(), window, cx)
10534 });
10535
10536 // Opening a dock unzooms the pane.
10537 workspace.update_in(cx, |workspace, window, cx| {
10538 workspace.toggle_dock(DockPosition::Right, window, cx)
10539 });
10540 workspace.update_in(cx, |workspace, window, cx| {
10541 let pane = pane.read(cx);
10542 assert!(!pane.is_zoomed());
10543 assert!(!pane.focus_handle(cx).is_focused(window));
10544 assert!(workspace.right_dock().read(cx).is_open());
10545 assert!(workspace.zoomed.is_none());
10546 });
10547 }
10548
10549 #[gpui::test]
10550 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
10551 init_test(cx);
10552 let fs = FakeFs::new(cx.executor());
10553
10554 let project = Project::test(fs, [], cx).await;
10555 let (workspace, cx) =
10556 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10557
10558 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
10559 workspace.active_pane().clone()
10560 });
10561
10562 // Add an item to the pane so it can be zoomed
10563 workspace.update_in(cx, |workspace, window, cx| {
10564 let item = cx.new(TestItem::new);
10565 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
10566 });
10567
10568 // Initially not zoomed
10569 workspace.update_in(cx, |workspace, _window, cx| {
10570 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
10571 assert!(
10572 workspace.zoomed.is_none(),
10573 "Workspace should track no zoomed pane"
10574 );
10575 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
10576 });
10577
10578 // Zoom In
10579 pane.update_in(cx, |pane, window, cx| {
10580 pane.zoom_in(&crate::ZoomIn, window, cx);
10581 });
10582
10583 workspace.update_in(cx, |workspace, window, cx| {
10584 assert!(
10585 pane.read(cx).is_zoomed(),
10586 "Pane should be zoomed after ZoomIn"
10587 );
10588 assert!(
10589 workspace.zoomed.is_some(),
10590 "Workspace should track the zoomed pane"
10591 );
10592 assert!(
10593 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
10594 "ZoomIn should focus the pane"
10595 );
10596 });
10597
10598 // Zoom In again is a no-op
10599 pane.update_in(cx, |pane, window, cx| {
10600 pane.zoom_in(&crate::ZoomIn, window, cx);
10601 });
10602
10603 workspace.update_in(cx, |workspace, window, cx| {
10604 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
10605 assert!(
10606 workspace.zoomed.is_some(),
10607 "Workspace still tracks zoomed pane"
10608 );
10609 assert!(
10610 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
10611 "Pane remains focused after repeated ZoomIn"
10612 );
10613 });
10614
10615 // Zoom Out
10616 pane.update_in(cx, |pane, window, cx| {
10617 pane.zoom_out(&crate::ZoomOut, window, cx);
10618 });
10619
10620 workspace.update_in(cx, |workspace, _window, cx| {
10621 assert!(
10622 !pane.read(cx).is_zoomed(),
10623 "Pane should unzoom after ZoomOut"
10624 );
10625 assert!(
10626 workspace.zoomed.is_none(),
10627 "Workspace clears zoom tracking after ZoomOut"
10628 );
10629 });
10630
10631 // Zoom Out again is a no-op
10632 pane.update_in(cx, |pane, window, cx| {
10633 pane.zoom_out(&crate::ZoomOut, window, cx);
10634 });
10635
10636 workspace.update_in(cx, |workspace, _window, cx| {
10637 assert!(
10638 !pane.read(cx).is_zoomed(),
10639 "Second ZoomOut keeps pane unzoomed"
10640 );
10641 assert!(
10642 workspace.zoomed.is_none(),
10643 "Workspace remains without zoomed pane"
10644 );
10645 });
10646 }
10647
10648 #[gpui::test]
10649 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
10650 init_test(cx);
10651 let fs = FakeFs::new(cx.executor());
10652
10653 let project = Project::test(fs, [], cx).await;
10654 let (workspace, cx) =
10655 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10656 workspace.update_in(cx, |workspace, window, cx| {
10657 // Open two docks
10658 let left_dock = workspace.dock_at_position(DockPosition::Left);
10659 let right_dock = workspace.dock_at_position(DockPosition::Right);
10660
10661 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10662 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10663
10664 assert!(left_dock.read(cx).is_open());
10665 assert!(right_dock.read(cx).is_open());
10666 });
10667
10668 workspace.update_in(cx, |workspace, window, cx| {
10669 // Toggle all docks - should close both
10670 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10671
10672 let left_dock = workspace.dock_at_position(DockPosition::Left);
10673 let right_dock = workspace.dock_at_position(DockPosition::Right);
10674 assert!(!left_dock.read(cx).is_open());
10675 assert!(!right_dock.read(cx).is_open());
10676 });
10677
10678 workspace.update_in(cx, |workspace, window, cx| {
10679 // Toggle again - should reopen both
10680 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10681
10682 let left_dock = workspace.dock_at_position(DockPosition::Left);
10683 let right_dock = workspace.dock_at_position(DockPosition::Right);
10684 assert!(left_dock.read(cx).is_open());
10685 assert!(right_dock.read(cx).is_open());
10686 });
10687 }
10688
10689 #[gpui::test]
10690 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
10691 init_test(cx);
10692 let fs = FakeFs::new(cx.executor());
10693
10694 let project = Project::test(fs, [], cx).await;
10695 let (workspace, cx) =
10696 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10697 workspace.update_in(cx, |workspace, window, cx| {
10698 // Open two docks
10699 let left_dock = workspace.dock_at_position(DockPosition::Left);
10700 let right_dock = workspace.dock_at_position(DockPosition::Right);
10701
10702 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10703 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10704
10705 assert!(left_dock.read(cx).is_open());
10706 assert!(right_dock.read(cx).is_open());
10707 });
10708
10709 workspace.update_in(cx, |workspace, window, cx| {
10710 // Close them manually
10711 workspace.toggle_dock(DockPosition::Left, window, cx);
10712 workspace.toggle_dock(DockPosition::Right, window, cx);
10713
10714 let left_dock = workspace.dock_at_position(DockPosition::Left);
10715 let right_dock = workspace.dock_at_position(DockPosition::Right);
10716 assert!(!left_dock.read(cx).is_open());
10717 assert!(!right_dock.read(cx).is_open());
10718 });
10719
10720 workspace.update_in(cx, |workspace, window, cx| {
10721 // Toggle all docks - only last closed (right dock) should reopen
10722 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10723
10724 let left_dock = workspace.dock_at_position(DockPosition::Left);
10725 let right_dock = workspace.dock_at_position(DockPosition::Right);
10726 assert!(!left_dock.read(cx).is_open());
10727 assert!(right_dock.read(cx).is_open());
10728 });
10729 }
10730
10731 #[gpui::test]
10732 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
10733 init_test(cx);
10734 let fs = FakeFs::new(cx.executor());
10735 let project = Project::test(fs, [], cx).await;
10736 let (workspace, cx) =
10737 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10738
10739 // Open two docks (left and right) with one panel each
10740 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
10741 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
10742 workspace.add_panel(left_panel.clone(), window, cx);
10743
10744 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
10745 workspace.add_panel(right_panel.clone(), window, cx);
10746
10747 workspace.toggle_dock(DockPosition::Left, window, cx);
10748 workspace.toggle_dock(DockPosition::Right, window, cx);
10749
10750 // Verify initial state
10751 assert!(
10752 workspace.left_dock().read(cx).is_open(),
10753 "Left dock should be open"
10754 );
10755 assert_eq!(
10756 workspace
10757 .left_dock()
10758 .read(cx)
10759 .visible_panel()
10760 .unwrap()
10761 .panel_id(),
10762 left_panel.panel_id(),
10763 "Left panel should be visible in left dock"
10764 );
10765 assert!(
10766 workspace.right_dock().read(cx).is_open(),
10767 "Right dock should be open"
10768 );
10769 assert_eq!(
10770 workspace
10771 .right_dock()
10772 .read(cx)
10773 .visible_panel()
10774 .unwrap()
10775 .panel_id(),
10776 right_panel.panel_id(),
10777 "Right panel should be visible in right dock"
10778 );
10779 assert!(
10780 !workspace.bottom_dock().read(cx).is_open(),
10781 "Bottom dock should be closed"
10782 );
10783
10784 (left_panel, right_panel)
10785 });
10786
10787 // Focus the left panel and move it to the next position (bottom dock)
10788 workspace.update_in(cx, |workspace, window, cx| {
10789 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
10790 assert!(
10791 left_panel.read(cx).focus_handle(cx).is_focused(window),
10792 "Left panel should be focused"
10793 );
10794 });
10795
10796 cx.dispatch_action(MoveFocusedPanelToNextPosition);
10797
10798 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
10799 workspace.update(cx, |workspace, cx| {
10800 assert!(
10801 !workspace.left_dock().read(cx).is_open(),
10802 "Left dock should be closed"
10803 );
10804 assert!(
10805 workspace.bottom_dock().read(cx).is_open(),
10806 "Bottom dock should now be open"
10807 );
10808 assert_eq!(
10809 left_panel.read(cx).position,
10810 DockPosition::Bottom,
10811 "Left panel should now be in the bottom dock"
10812 );
10813 assert_eq!(
10814 workspace
10815 .bottom_dock()
10816 .read(cx)
10817 .visible_panel()
10818 .unwrap()
10819 .panel_id(),
10820 left_panel.panel_id(),
10821 "Left panel should be the visible panel in the bottom dock"
10822 );
10823 });
10824
10825 // Toggle all docks off
10826 workspace.update_in(cx, |workspace, window, cx| {
10827 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10828 assert!(
10829 !workspace.left_dock().read(cx).is_open(),
10830 "Left dock should be closed"
10831 );
10832 assert!(
10833 !workspace.right_dock().read(cx).is_open(),
10834 "Right dock should be closed"
10835 );
10836 assert!(
10837 !workspace.bottom_dock().read(cx).is_open(),
10838 "Bottom dock should be closed"
10839 );
10840 });
10841
10842 // Toggle all docks back on and verify positions are restored
10843 workspace.update_in(cx, |workspace, window, cx| {
10844 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10845 assert!(
10846 !workspace.left_dock().read(cx).is_open(),
10847 "Left dock should remain closed"
10848 );
10849 assert!(
10850 workspace.right_dock().read(cx).is_open(),
10851 "Right dock should remain open"
10852 );
10853 assert!(
10854 workspace.bottom_dock().read(cx).is_open(),
10855 "Bottom dock should remain open"
10856 );
10857 assert_eq!(
10858 left_panel.read(cx).position,
10859 DockPosition::Bottom,
10860 "Left panel should remain in the bottom dock"
10861 );
10862 assert_eq!(
10863 right_panel.read(cx).position,
10864 DockPosition::Right,
10865 "Right panel should remain in the right dock"
10866 );
10867 assert_eq!(
10868 workspace
10869 .bottom_dock()
10870 .read(cx)
10871 .visible_panel()
10872 .unwrap()
10873 .panel_id(),
10874 left_panel.panel_id(),
10875 "Left panel should be the visible panel in the right dock"
10876 );
10877 });
10878 }
10879
10880 #[gpui::test]
10881 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
10882 init_test(cx);
10883
10884 let fs = FakeFs::new(cx.executor());
10885
10886 let project = Project::test(fs, None, cx).await;
10887 let (workspace, cx) =
10888 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10889
10890 // Let's arrange the panes like this:
10891 //
10892 // +-----------------------+
10893 // | top |
10894 // +------+--------+-------+
10895 // | left | center | right |
10896 // +------+--------+-------+
10897 // | bottom |
10898 // +-----------------------+
10899
10900 let top_item = cx.new(|cx| {
10901 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
10902 });
10903 let bottom_item = cx.new(|cx| {
10904 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
10905 });
10906 let left_item = cx.new(|cx| {
10907 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
10908 });
10909 let right_item = cx.new(|cx| {
10910 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
10911 });
10912 let center_item = cx.new(|cx| {
10913 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
10914 });
10915
10916 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10917 let top_pane_id = workspace.active_pane().entity_id();
10918 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
10919 workspace.split_pane(
10920 workspace.active_pane().clone(),
10921 SplitDirection::Down,
10922 window,
10923 cx,
10924 );
10925 top_pane_id
10926 });
10927 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10928 let bottom_pane_id = workspace.active_pane().entity_id();
10929 workspace.add_item_to_active_pane(
10930 Box::new(bottom_item.clone()),
10931 None,
10932 false,
10933 window,
10934 cx,
10935 );
10936 workspace.split_pane(
10937 workspace.active_pane().clone(),
10938 SplitDirection::Up,
10939 window,
10940 cx,
10941 );
10942 bottom_pane_id
10943 });
10944 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10945 let left_pane_id = workspace.active_pane().entity_id();
10946 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
10947 workspace.split_pane(
10948 workspace.active_pane().clone(),
10949 SplitDirection::Right,
10950 window,
10951 cx,
10952 );
10953 left_pane_id
10954 });
10955 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10956 let right_pane_id = workspace.active_pane().entity_id();
10957 workspace.add_item_to_active_pane(
10958 Box::new(right_item.clone()),
10959 None,
10960 false,
10961 window,
10962 cx,
10963 );
10964 workspace.split_pane(
10965 workspace.active_pane().clone(),
10966 SplitDirection::Left,
10967 window,
10968 cx,
10969 );
10970 right_pane_id
10971 });
10972 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10973 let center_pane_id = workspace.active_pane().entity_id();
10974 workspace.add_item_to_active_pane(
10975 Box::new(center_item.clone()),
10976 None,
10977 false,
10978 window,
10979 cx,
10980 );
10981 center_pane_id
10982 });
10983 cx.executor().run_until_parked();
10984
10985 workspace.update_in(cx, |workspace, window, cx| {
10986 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
10987
10988 // Join into next from center pane into right
10989 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10990 });
10991
10992 workspace.update_in(cx, |workspace, window, cx| {
10993 let active_pane = workspace.active_pane();
10994 assert_eq!(right_pane_id, active_pane.entity_id());
10995 assert_eq!(2, active_pane.read(cx).items_len());
10996 let item_ids_in_pane =
10997 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10998 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
10999 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11000
11001 // Join into next from right pane into bottom
11002 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11003 });
11004
11005 workspace.update_in(cx, |workspace, window, cx| {
11006 let active_pane = workspace.active_pane();
11007 assert_eq!(bottom_pane_id, active_pane.entity_id());
11008 assert_eq!(3, active_pane.read(cx).items_len());
11009 let item_ids_in_pane =
11010 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11011 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11012 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11013 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11014
11015 // Join into next from bottom pane into left
11016 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11017 });
11018
11019 workspace.update_in(cx, |workspace, window, cx| {
11020 let active_pane = workspace.active_pane();
11021 assert_eq!(left_pane_id, active_pane.entity_id());
11022 assert_eq!(4, active_pane.read(cx).items_len());
11023 let item_ids_in_pane =
11024 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11025 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11026 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11027 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11028 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11029
11030 // Join into next from left pane into top
11031 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11032 });
11033
11034 workspace.update_in(cx, |workspace, window, cx| {
11035 let active_pane = workspace.active_pane();
11036 assert_eq!(top_pane_id, active_pane.entity_id());
11037 assert_eq!(5, active_pane.read(cx).items_len());
11038 let item_ids_in_pane =
11039 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11040 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11041 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11042 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11043 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11044 assert!(item_ids_in_pane.contains(&top_item.item_id()));
11045
11046 // Single pane left: no-op
11047 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11048 });
11049
11050 workspace.update(cx, |workspace, _cx| {
11051 let active_pane = workspace.active_pane();
11052 assert_eq!(top_pane_id, active_pane.entity_id());
11053 });
11054 }
11055
11056 fn add_an_item_to_active_pane(
11057 cx: &mut VisualTestContext,
11058 workspace: &Entity<Workspace>,
11059 item_id: u64,
11060 ) -> Entity<TestItem> {
11061 let item = cx.new(|cx| {
11062 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11063 item_id,
11064 "item{item_id}.txt",
11065 cx,
11066 )])
11067 });
11068 workspace.update_in(cx, |workspace, window, cx| {
11069 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11070 });
11071 item
11072 }
11073
11074 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11075 workspace.update_in(cx, |workspace, window, cx| {
11076 workspace.split_pane(
11077 workspace.active_pane().clone(),
11078 SplitDirection::Right,
11079 window,
11080 cx,
11081 )
11082 })
11083 }
11084
11085 #[gpui::test]
11086 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11087 init_test(cx);
11088 let fs = FakeFs::new(cx.executor());
11089 let project = Project::test(fs, None, cx).await;
11090 let (workspace, cx) =
11091 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11092
11093 add_an_item_to_active_pane(cx, &workspace, 1);
11094 split_pane(cx, &workspace);
11095 add_an_item_to_active_pane(cx, &workspace, 2);
11096 split_pane(cx, &workspace); // empty pane
11097 split_pane(cx, &workspace);
11098 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11099
11100 cx.executor().run_until_parked();
11101
11102 workspace.update(cx, |workspace, cx| {
11103 let num_panes = workspace.panes().len();
11104 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11105 let active_item = workspace
11106 .active_pane()
11107 .read(cx)
11108 .active_item()
11109 .expect("item is in focus");
11110
11111 assert_eq!(num_panes, 4);
11112 assert_eq!(num_items_in_current_pane, 1);
11113 assert_eq!(active_item.item_id(), last_item.item_id());
11114 });
11115
11116 workspace.update_in(cx, |workspace, window, cx| {
11117 workspace.join_all_panes(window, cx);
11118 });
11119
11120 workspace.update(cx, |workspace, cx| {
11121 let num_panes = workspace.panes().len();
11122 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11123 let active_item = workspace
11124 .active_pane()
11125 .read(cx)
11126 .active_item()
11127 .expect("item is in focus");
11128
11129 assert_eq!(num_panes, 1);
11130 assert_eq!(num_items_in_current_pane, 3);
11131 assert_eq!(active_item.item_id(), last_item.item_id());
11132 });
11133 }
11134 struct TestModal(FocusHandle);
11135
11136 impl TestModal {
11137 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11138 Self(cx.focus_handle())
11139 }
11140 }
11141
11142 impl EventEmitter<DismissEvent> for TestModal {}
11143
11144 impl Focusable for TestModal {
11145 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11146 self.0.clone()
11147 }
11148 }
11149
11150 impl ModalView for TestModal {}
11151
11152 impl Render for TestModal {
11153 fn render(
11154 &mut self,
11155 _window: &mut Window,
11156 _cx: &mut Context<TestModal>,
11157 ) -> impl IntoElement {
11158 div().track_focus(&self.0)
11159 }
11160 }
11161
11162 #[gpui::test]
11163 async fn test_panels(cx: &mut gpui::TestAppContext) {
11164 init_test(cx);
11165 let fs = FakeFs::new(cx.executor());
11166
11167 let project = Project::test(fs, [], cx).await;
11168 let (workspace, cx) =
11169 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11170
11171 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11172 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11173 workspace.add_panel(panel_1.clone(), window, cx);
11174 workspace.toggle_dock(DockPosition::Left, window, cx);
11175 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11176 workspace.add_panel(panel_2.clone(), window, cx);
11177 workspace.toggle_dock(DockPosition::Right, window, cx);
11178
11179 let left_dock = workspace.left_dock();
11180 assert_eq!(
11181 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11182 panel_1.panel_id()
11183 );
11184 assert_eq!(
11185 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11186 panel_1.size(window, cx)
11187 );
11188
11189 left_dock.update(cx, |left_dock, cx| {
11190 left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11191 });
11192 assert_eq!(
11193 workspace
11194 .right_dock()
11195 .read(cx)
11196 .visible_panel()
11197 .unwrap()
11198 .panel_id(),
11199 panel_2.panel_id(),
11200 );
11201
11202 (panel_1, panel_2)
11203 });
11204
11205 // Move panel_1 to the right
11206 panel_1.update_in(cx, |panel_1, window, cx| {
11207 panel_1.set_position(DockPosition::Right, window, cx)
11208 });
11209
11210 workspace.update_in(cx, |workspace, window, cx| {
11211 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11212 // Since it was the only panel on the left, the left dock should now be closed.
11213 assert!(!workspace.left_dock().read(cx).is_open());
11214 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11215 let right_dock = workspace.right_dock();
11216 assert_eq!(
11217 right_dock.read(cx).visible_panel().unwrap().panel_id(),
11218 panel_1.panel_id()
11219 );
11220 assert_eq!(
11221 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11222 px(1337.)
11223 );
11224
11225 // Now we move panel_2 to the left
11226 panel_2.set_position(DockPosition::Left, window, cx);
11227 });
11228
11229 workspace.update(cx, |workspace, cx| {
11230 // Since panel_2 was not visible on the right, we don't open the left dock.
11231 assert!(!workspace.left_dock().read(cx).is_open());
11232 // And the right dock is unaffected in its displaying of panel_1
11233 assert!(workspace.right_dock().read(cx).is_open());
11234 assert_eq!(
11235 workspace
11236 .right_dock()
11237 .read(cx)
11238 .visible_panel()
11239 .unwrap()
11240 .panel_id(),
11241 panel_1.panel_id(),
11242 );
11243 });
11244
11245 // Move panel_1 back to the left
11246 panel_1.update_in(cx, |panel_1, window, cx| {
11247 panel_1.set_position(DockPosition::Left, window, cx)
11248 });
11249
11250 workspace.update_in(cx, |workspace, window, cx| {
11251 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
11252 let left_dock = workspace.left_dock();
11253 assert!(left_dock.read(cx).is_open());
11254 assert_eq!(
11255 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11256 panel_1.panel_id()
11257 );
11258 assert_eq!(
11259 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11260 px(1337.)
11261 );
11262 // And the right dock should be closed as it no longer has any panels.
11263 assert!(!workspace.right_dock().read(cx).is_open());
11264
11265 // Now we move panel_1 to the bottom
11266 panel_1.set_position(DockPosition::Bottom, window, cx);
11267 });
11268
11269 workspace.update_in(cx, |workspace, window, cx| {
11270 // Since panel_1 was visible on the left, we close the left dock.
11271 assert!(!workspace.left_dock().read(cx).is_open());
11272 // The bottom dock is sized based on the panel's default size,
11273 // since the panel orientation changed from vertical to horizontal.
11274 let bottom_dock = workspace.bottom_dock();
11275 assert_eq!(
11276 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
11277 panel_1.size(window, cx),
11278 );
11279 // Close bottom dock and move panel_1 back to the left.
11280 bottom_dock.update(cx, |bottom_dock, cx| {
11281 bottom_dock.set_open(false, window, cx)
11282 });
11283 panel_1.set_position(DockPosition::Left, window, cx);
11284 });
11285
11286 // Emit activated event on panel 1
11287 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
11288
11289 // Now the left dock is open and panel_1 is active and focused.
11290 workspace.update_in(cx, |workspace, window, cx| {
11291 let left_dock = workspace.left_dock();
11292 assert!(left_dock.read(cx).is_open());
11293 assert_eq!(
11294 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11295 panel_1.panel_id(),
11296 );
11297 assert!(panel_1.focus_handle(cx).is_focused(window));
11298 });
11299
11300 // Emit closed event on panel 2, which is not active
11301 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11302
11303 // Wo don't close the left dock, because panel_2 wasn't the active panel
11304 workspace.update(cx, |workspace, cx| {
11305 let left_dock = workspace.left_dock();
11306 assert!(left_dock.read(cx).is_open());
11307 assert_eq!(
11308 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11309 panel_1.panel_id(),
11310 );
11311 });
11312
11313 // Emitting a ZoomIn event shows the panel as zoomed.
11314 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
11315 workspace.read_with(cx, |workspace, _| {
11316 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11317 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
11318 });
11319
11320 // Move panel to another dock while it is zoomed
11321 panel_1.update_in(cx, |panel, window, cx| {
11322 panel.set_position(DockPosition::Right, window, cx)
11323 });
11324 workspace.read_with(cx, |workspace, _| {
11325 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11326
11327 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11328 });
11329
11330 // This is a helper for getting a:
11331 // - valid focus on an element,
11332 // - that isn't a part of the panes and panels system of the Workspace,
11333 // - and doesn't trigger the 'on_focus_lost' API.
11334 let focus_other_view = {
11335 let workspace = workspace.clone();
11336 move |cx: &mut VisualTestContext| {
11337 workspace.update_in(cx, |workspace, window, cx| {
11338 if workspace.active_modal::<TestModal>(cx).is_some() {
11339 workspace.toggle_modal(window, cx, TestModal::new);
11340 workspace.toggle_modal(window, cx, TestModal::new);
11341 } else {
11342 workspace.toggle_modal(window, cx, TestModal::new);
11343 }
11344 })
11345 }
11346 };
11347
11348 // If focus is transferred to another view that's not a panel or another pane, we still show
11349 // the panel as zoomed.
11350 focus_other_view(cx);
11351 workspace.read_with(cx, |workspace, _| {
11352 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11353 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11354 });
11355
11356 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
11357 workspace.update_in(cx, |_workspace, window, cx| {
11358 cx.focus_self(window);
11359 });
11360 workspace.read_with(cx, |workspace, _| {
11361 assert_eq!(workspace.zoomed, None);
11362 assert_eq!(workspace.zoomed_position, None);
11363 });
11364
11365 // If focus is transferred again to another view that's not a panel or a pane, we won't
11366 // show the panel as zoomed because it wasn't zoomed before.
11367 focus_other_view(cx);
11368 workspace.read_with(cx, |workspace, _| {
11369 assert_eq!(workspace.zoomed, None);
11370 assert_eq!(workspace.zoomed_position, None);
11371 });
11372
11373 // When the panel is activated, it is zoomed again.
11374 cx.dispatch_action(ToggleRightDock);
11375 workspace.read_with(cx, |workspace, _| {
11376 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11377 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11378 });
11379
11380 // Emitting a ZoomOut event unzooms the panel.
11381 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
11382 workspace.read_with(cx, |workspace, _| {
11383 assert_eq!(workspace.zoomed, None);
11384 assert_eq!(workspace.zoomed_position, None);
11385 });
11386
11387 // Emit closed event on panel 1, which is active
11388 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11389
11390 // Now the left dock is closed, because panel_1 was the active panel
11391 workspace.update(cx, |workspace, cx| {
11392 let right_dock = workspace.right_dock();
11393 assert!(!right_dock.read(cx).is_open());
11394 });
11395 }
11396
11397 #[gpui::test]
11398 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
11399 init_test(cx);
11400
11401 let fs = FakeFs::new(cx.background_executor.clone());
11402 let project = Project::test(fs, [], cx).await;
11403 let (workspace, cx) =
11404 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11405 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11406
11407 let dirty_regular_buffer = cx.new(|cx| {
11408 TestItem::new(cx)
11409 .with_dirty(true)
11410 .with_label("1.txt")
11411 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11412 });
11413 let dirty_regular_buffer_2 = cx.new(|cx| {
11414 TestItem::new(cx)
11415 .with_dirty(true)
11416 .with_label("2.txt")
11417 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11418 });
11419 let dirty_multi_buffer_with_both = cx.new(|cx| {
11420 TestItem::new(cx)
11421 .with_dirty(true)
11422 .with_buffer_kind(ItemBufferKind::Multibuffer)
11423 .with_label("Fake Project Search")
11424 .with_project_items(&[
11425 dirty_regular_buffer.read(cx).project_items[0].clone(),
11426 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11427 ])
11428 });
11429 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
11430 workspace.update_in(cx, |workspace, window, cx| {
11431 workspace.add_item(
11432 pane.clone(),
11433 Box::new(dirty_regular_buffer.clone()),
11434 None,
11435 false,
11436 false,
11437 window,
11438 cx,
11439 );
11440 workspace.add_item(
11441 pane.clone(),
11442 Box::new(dirty_regular_buffer_2.clone()),
11443 None,
11444 false,
11445 false,
11446 window,
11447 cx,
11448 );
11449 workspace.add_item(
11450 pane.clone(),
11451 Box::new(dirty_multi_buffer_with_both.clone()),
11452 None,
11453 false,
11454 false,
11455 window,
11456 cx,
11457 );
11458 });
11459
11460 pane.update_in(cx, |pane, window, cx| {
11461 pane.activate_item(2, true, true, window, cx);
11462 assert_eq!(
11463 pane.active_item().unwrap().item_id(),
11464 multi_buffer_with_both_files_id,
11465 "Should select the multi buffer in the pane"
11466 );
11467 });
11468 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11469 pane.close_other_items(
11470 &CloseOtherItems {
11471 save_intent: Some(SaveIntent::Save),
11472 close_pinned: true,
11473 },
11474 None,
11475 window,
11476 cx,
11477 )
11478 });
11479 cx.background_executor.run_until_parked();
11480 assert!(!cx.has_pending_prompt());
11481 close_all_but_multi_buffer_task
11482 .await
11483 .expect("Closing all buffers but the multi buffer failed");
11484 pane.update(cx, |pane, cx| {
11485 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
11486 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
11487 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
11488 assert_eq!(pane.items_len(), 1);
11489 assert_eq!(
11490 pane.active_item().unwrap().item_id(),
11491 multi_buffer_with_both_files_id,
11492 "Should have only the multi buffer left in the pane"
11493 );
11494 assert!(
11495 dirty_multi_buffer_with_both.read(cx).is_dirty,
11496 "The multi buffer containing the unsaved buffer should still be dirty"
11497 );
11498 });
11499
11500 dirty_regular_buffer.update(cx, |buffer, cx| {
11501 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
11502 });
11503
11504 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11505 pane.close_active_item(
11506 &CloseActiveItem {
11507 save_intent: Some(SaveIntent::Close),
11508 close_pinned: false,
11509 },
11510 window,
11511 cx,
11512 )
11513 });
11514 cx.background_executor.run_until_parked();
11515 assert!(
11516 cx.has_pending_prompt(),
11517 "Dirty multi buffer should prompt a save dialog"
11518 );
11519 cx.simulate_prompt_answer("Save");
11520 cx.background_executor.run_until_parked();
11521 close_multi_buffer_task
11522 .await
11523 .expect("Closing the multi buffer failed");
11524 pane.update(cx, |pane, cx| {
11525 assert_eq!(
11526 dirty_multi_buffer_with_both.read(cx).save_count,
11527 1,
11528 "Multi buffer item should get be saved"
11529 );
11530 // Test impl does not save inner items, so we do not assert them
11531 assert_eq!(
11532 pane.items_len(),
11533 0,
11534 "No more items should be left in the pane"
11535 );
11536 assert!(pane.active_item().is_none());
11537 });
11538 }
11539
11540 #[gpui::test]
11541 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
11542 cx: &mut TestAppContext,
11543 ) {
11544 init_test(cx);
11545
11546 let fs = FakeFs::new(cx.background_executor.clone());
11547 let project = Project::test(fs, [], cx).await;
11548 let (workspace, cx) =
11549 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11550 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11551
11552 let dirty_regular_buffer = cx.new(|cx| {
11553 TestItem::new(cx)
11554 .with_dirty(true)
11555 .with_label("1.txt")
11556 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11557 });
11558 let dirty_regular_buffer_2 = cx.new(|cx| {
11559 TestItem::new(cx)
11560 .with_dirty(true)
11561 .with_label("2.txt")
11562 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11563 });
11564 let clear_regular_buffer = cx.new(|cx| {
11565 TestItem::new(cx)
11566 .with_label("3.txt")
11567 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
11568 });
11569
11570 let dirty_multi_buffer_with_both = cx.new(|cx| {
11571 TestItem::new(cx)
11572 .with_dirty(true)
11573 .with_buffer_kind(ItemBufferKind::Multibuffer)
11574 .with_label("Fake Project Search")
11575 .with_project_items(&[
11576 dirty_regular_buffer.read(cx).project_items[0].clone(),
11577 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11578 clear_regular_buffer.read(cx).project_items[0].clone(),
11579 ])
11580 });
11581 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
11582 workspace.update_in(cx, |workspace, window, cx| {
11583 workspace.add_item(
11584 pane.clone(),
11585 Box::new(dirty_regular_buffer.clone()),
11586 None,
11587 false,
11588 false,
11589 window,
11590 cx,
11591 );
11592 workspace.add_item(
11593 pane.clone(),
11594 Box::new(dirty_multi_buffer_with_both.clone()),
11595 None,
11596 false,
11597 false,
11598 window,
11599 cx,
11600 );
11601 });
11602
11603 pane.update_in(cx, |pane, window, cx| {
11604 pane.activate_item(1, true, true, window, cx);
11605 assert_eq!(
11606 pane.active_item().unwrap().item_id(),
11607 multi_buffer_with_both_files_id,
11608 "Should select the multi buffer in the pane"
11609 );
11610 });
11611 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11612 pane.close_active_item(
11613 &CloseActiveItem {
11614 save_intent: None,
11615 close_pinned: false,
11616 },
11617 window,
11618 cx,
11619 )
11620 });
11621 cx.background_executor.run_until_parked();
11622 assert!(
11623 cx.has_pending_prompt(),
11624 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
11625 );
11626 }
11627
11628 /// Tests that when `close_on_file_delete` is enabled, files are automatically
11629 /// closed when they are deleted from disk.
11630 #[gpui::test]
11631 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
11632 init_test(cx);
11633
11634 // Enable the close_on_disk_deletion setting
11635 cx.update_global(|store: &mut SettingsStore, cx| {
11636 store.update_user_settings(cx, |settings| {
11637 settings.workspace.close_on_file_delete = Some(true);
11638 });
11639 });
11640
11641 let fs = FakeFs::new(cx.background_executor.clone());
11642 let project = Project::test(fs, [], cx).await;
11643 let (workspace, cx) =
11644 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11645 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11646
11647 // Create a test item that simulates a file
11648 let item = cx.new(|cx| {
11649 TestItem::new(cx)
11650 .with_label("test.txt")
11651 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11652 });
11653
11654 // Add item to workspace
11655 workspace.update_in(cx, |workspace, window, cx| {
11656 workspace.add_item(
11657 pane.clone(),
11658 Box::new(item.clone()),
11659 None,
11660 false,
11661 false,
11662 window,
11663 cx,
11664 );
11665 });
11666
11667 // Verify the item is in the pane
11668 pane.read_with(cx, |pane, _| {
11669 assert_eq!(pane.items().count(), 1);
11670 });
11671
11672 // Simulate file deletion by setting the item's deleted state
11673 item.update(cx, |item, _| {
11674 item.set_has_deleted_file(true);
11675 });
11676
11677 // Emit UpdateTab event to trigger the close behavior
11678 cx.run_until_parked();
11679 item.update(cx, |_, cx| {
11680 cx.emit(ItemEvent::UpdateTab);
11681 });
11682
11683 // Allow the close operation to complete
11684 cx.run_until_parked();
11685
11686 // Verify the item was automatically closed
11687 pane.read_with(cx, |pane, _| {
11688 assert_eq!(
11689 pane.items().count(),
11690 0,
11691 "Item should be automatically closed when file is deleted"
11692 );
11693 });
11694 }
11695
11696 /// Tests that when `close_on_file_delete` is disabled (default), files remain
11697 /// open with a strikethrough when they are deleted from disk.
11698 #[gpui::test]
11699 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
11700 init_test(cx);
11701
11702 // Ensure close_on_disk_deletion is disabled (default)
11703 cx.update_global(|store: &mut SettingsStore, cx| {
11704 store.update_user_settings(cx, |settings| {
11705 settings.workspace.close_on_file_delete = Some(false);
11706 });
11707 });
11708
11709 let fs = FakeFs::new(cx.background_executor.clone());
11710 let project = Project::test(fs, [], cx).await;
11711 let (workspace, cx) =
11712 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11713 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11714
11715 // Create a test item that simulates a file
11716 let item = cx.new(|cx| {
11717 TestItem::new(cx)
11718 .with_label("test.txt")
11719 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11720 });
11721
11722 // Add item to workspace
11723 workspace.update_in(cx, |workspace, window, cx| {
11724 workspace.add_item(
11725 pane.clone(),
11726 Box::new(item.clone()),
11727 None,
11728 false,
11729 false,
11730 window,
11731 cx,
11732 );
11733 });
11734
11735 // Verify the item is in the pane
11736 pane.read_with(cx, |pane, _| {
11737 assert_eq!(pane.items().count(), 1);
11738 });
11739
11740 // Simulate file deletion
11741 item.update(cx, |item, _| {
11742 item.set_has_deleted_file(true);
11743 });
11744
11745 // Emit UpdateTab event
11746 cx.run_until_parked();
11747 item.update(cx, |_, cx| {
11748 cx.emit(ItemEvent::UpdateTab);
11749 });
11750
11751 // Allow any potential close operation to complete
11752 cx.run_until_parked();
11753
11754 // Verify the item remains open (with strikethrough)
11755 pane.read_with(cx, |pane, _| {
11756 assert_eq!(
11757 pane.items().count(),
11758 1,
11759 "Item should remain open when close_on_disk_deletion is disabled"
11760 );
11761 });
11762
11763 // Verify the item shows as deleted
11764 item.read_with(cx, |item, _| {
11765 assert!(
11766 item.has_deleted_file,
11767 "Item should be marked as having deleted file"
11768 );
11769 });
11770 }
11771
11772 /// Tests that dirty files are not automatically closed when deleted from disk,
11773 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
11774 /// unsaved changes without being prompted.
11775 #[gpui::test]
11776 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
11777 init_test(cx);
11778
11779 // Enable the close_on_file_delete setting
11780 cx.update_global(|store: &mut SettingsStore, cx| {
11781 store.update_user_settings(cx, |settings| {
11782 settings.workspace.close_on_file_delete = Some(true);
11783 });
11784 });
11785
11786 let fs = FakeFs::new(cx.background_executor.clone());
11787 let project = Project::test(fs, [], cx).await;
11788 let (workspace, cx) =
11789 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11790 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11791
11792 // Create a dirty test item
11793 let item = cx.new(|cx| {
11794 TestItem::new(cx)
11795 .with_dirty(true)
11796 .with_label("test.txt")
11797 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11798 });
11799
11800 // Add item to workspace
11801 workspace.update_in(cx, |workspace, window, cx| {
11802 workspace.add_item(
11803 pane.clone(),
11804 Box::new(item.clone()),
11805 None,
11806 false,
11807 false,
11808 window,
11809 cx,
11810 );
11811 });
11812
11813 // Simulate file deletion
11814 item.update(cx, |item, _| {
11815 item.set_has_deleted_file(true);
11816 });
11817
11818 // Emit UpdateTab event to trigger the close behavior
11819 cx.run_until_parked();
11820 item.update(cx, |_, cx| {
11821 cx.emit(ItemEvent::UpdateTab);
11822 });
11823
11824 // Allow any potential close operation to complete
11825 cx.run_until_parked();
11826
11827 // Verify the item remains open (dirty files are not auto-closed)
11828 pane.read_with(cx, |pane, _| {
11829 assert_eq!(
11830 pane.items().count(),
11831 1,
11832 "Dirty items should not be automatically closed even when file is deleted"
11833 );
11834 });
11835
11836 // Verify the item is marked as deleted and still dirty
11837 item.read_with(cx, |item, _| {
11838 assert!(
11839 item.has_deleted_file,
11840 "Item should be marked as having deleted file"
11841 );
11842 assert!(item.is_dirty, "Item should still be dirty");
11843 });
11844 }
11845
11846 /// Tests that navigation history is cleaned up when files are auto-closed
11847 /// due to deletion from disk.
11848 #[gpui::test]
11849 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
11850 init_test(cx);
11851
11852 // Enable the close_on_file_delete setting
11853 cx.update_global(|store: &mut SettingsStore, cx| {
11854 store.update_user_settings(cx, |settings| {
11855 settings.workspace.close_on_file_delete = Some(true);
11856 });
11857 });
11858
11859 let fs = FakeFs::new(cx.background_executor.clone());
11860 let project = Project::test(fs, [], cx).await;
11861 let (workspace, cx) =
11862 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11863 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11864
11865 // Create test items
11866 let item1 = cx.new(|cx| {
11867 TestItem::new(cx)
11868 .with_label("test1.txt")
11869 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
11870 });
11871 let item1_id = item1.item_id();
11872
11873 let item2 = cx.new(|cx| {
11874 TestItem::new(cx)
11875 .with_label("test2.txt")
11876 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
11877 });
11878
11879 // Add items to workspace
11880 workspace.update_in(cx, |workspace, window, cx| {
11881 workspace.add_item(
11882 pane.clone(),
11883 Box::new(item1.clone()),
11884 None,
11885 false,
11886 false,
11887 window,
11888 cx,
11889 );
11890 workspace.add_item(
11891 pane.clone(),
11892 Box::new(item2.clone()),
11893 None,
11894 false,
11895 false,
11896 window,
11897 cx,
11898 );
11899 });
11900
11901 // Activate item1 to ensure it gets navigation entries
11902 pane.update_in(cx, |pane, window, cx| {
11903 pane.activate_item(0, true, true, window, cx);
11904 });
11905
11906 // Switch to item2 and back to create navigation history
11907 pane.update_in(cx, |pane, window, cx| {
11908 pane.activate_item(1, true, true, window, cx);
11909 });
11910 cx.run_until_parked();
11911
11912 pane.update_in(cx, |pane, window, cx| {
11913 pane.activate_item(0, true, true, window, cx);
11914 });
11915 cx.run_until_parked();
11916
11917 // Simulate file deletion for item1
11918 item1.update(cx, |item, _| {
11919 item.set_has_deleted_file(true);
11920 });
11921
11922 // Emit UpdateTab event to trigger the close behavior
11923 item1.update(cx, |_, cx| {
11924 cx.emit(ItemEvent::UpdateTab);
11925 });
11926 cx.run_until_parked();
11927
11928 // Verify item1 was closed
11929 pane.read_with(cx, |pane, _| {
11930 assert_eq!(
11931 pane.items().count(),
11932 1,
11933 "Should have 1 item remaining after auto-close"
11934 );
11935 });
11936
11937 // Check navigation history after close
11938 let has_item = pane.read_with(cx, |pane, cx| {
11939 let mut has_item = false;
11940 pane.nav_history().for_each_entry(cx, |entry, _| {
11941 if entry.item.id() == item1_id {
11942 has_item = true;
11943 }
11944 });
11945 has_item
11946 });
11947
11948 assert!(
11949 !has_item,
11950 "Navigation history should not contain closed item entries"
11951 );
11952 }
11953
11954 #[gpui::test]
11955 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
11956 cx: &mut TestAppContext,
11957 ) {
11958 init_test(cx);
11959
11960 let fs = FakeFs::new(cx.background_executor.clone());
11961 let project = Project::test(fs, [], cx).await;
11962 let (workspace, cx) =
11963 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11964 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11965
11966 let dirty_regular_buffer = cx.new(|cx| {
11967 TestItem::new(cx)
11968 .with_dirty(true)
11969 .with_label("1.txt")
11970 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11971 });
11972 let dirty_regular_buffer_2 = cx.new(|cx| {
11973 TestItem::new(cx)
11974 .with_dirty(true)
11975 .with_label("2.txt")
11976 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11977 });
11978 let clear_regular_buffer = cx.new(|cx| {
11979 TestItem::new(cx)
11980 .with_label("3.txt")
11981 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
11982 });
11983
11984 let dirty_multi_buffer = cx.new(|cx| {
11985 TestItem::new(cx)
11986 .with_dirty(true)
11987 .with_buffer_kind(ItemBufferKind::Multibuffer)
11988 .with_label("Fake Project Search")
11989 .with_project_items(&[
11990 dirty_regular_buffer.read(cx).project_items[0].clone(),
11991 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11992 clear_regular_buffer.read(cx).project_items[0].clone(),
11993 ])
11994 });
11995 workspace.update_in(cx, |workspace, window, cx| {
11996 workspace.add_item(
11997 pane.clone(),
11998 Box::new(dirty_regular_buffer.clone()),
11999 None,
12000 false,
12001 false,
12002 window,
12003 cx,
12004 );
12005 workspace.add_item(
12006 pane.clone(),
12007 Box::new(dirty_regular_buffer_2.clone()),
12008 None,
12009 false,
12010 false,
12011 window,
12012 cx,
12013 );
12014 workspace.add_item(
12015 pane.clone(),
12016 Box::new(dirty_multi_buffer.clone()),
12017 None,
12018 false,
12019 false,
12020 window,
12021 cx,
12022 );
12023 });
12024
12025 pane.update_in(cx, |pane, window, cx| {
12026 pane.activate_item(2, true, true, window, cx);
12027 assert_eq!(
12028 pane.active_item().unwrap().item_id(),
12029 dirty_multi_buffer.item_id(),
12030 "Should select the multi buffer in the pane"
12031 );
12032 });
12033 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12034 pane.close_active_item(
12035 &CloseActiveItem {
12036 save_intent: None,
12037 close_pinned: false,
12038 },
12039 window,
12040 cx,
12041 )
12042 });
12043 cx.background_executor.run_until_parked();
12044 assert!(
12045 !cx.has_pending_prompt(),
12046 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12047 );
12048 close_multi_buffer_task
12049 .await
12050 .expect("Closing multi buffer failed");
12051 pane.update(cx, |pane, cx| {
12052 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12053 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12054 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12055 assert_eq!(
12056 pane.items()
12057 .map(|item| item.item_id())
12058 .sorted()
12059 .collect::<Vec<_>>(),
12060 vec![
12061 dirty_regular_buffer.item_id(),
12062 dirty_regular_buffer_2.item_id(),
12063 ],
12064 "Should have no multi buffer left in the pane"
12065 );
12066 assert!(dirty_regular_buffer.read(cx).is_dirty);
12067 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12068 });
12069 }
12070
12071 #[gpui::test]
12072 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12073 init_test(cx);
12074 let fs = FakeFs::new(cx.executor());
12075 let project = Project::test(fs, [], cx).await;
12076 let (workspace, cx) =
12077 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12078
12079 // Add a new panel to the right dock, opening the dock and setting the
12080 // focus to the new panel.
12081 let panel = workspace.update_in(cx, |workspace, window, cx| {
12082 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12083 workspace.add_panel(panel.clone(), window, cx);
12084
12085 workspace
12086 .right_dock()
12087 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12088
12089 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12090
12091 panel
12092 });
12093
12094 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12095 // panel to the next valid position which, in this case, is the left
12096 // dock.
12097 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12098 workspace.update(cx, |workspace, cx| {
12099 assert!(workspace.left_dock().read(cx).is_open());
12100 assert_eq!(panel.read(cx).position, DockPosition::Left);
12101 });
12102
12103 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12104 // panel to the next valid position which, in this case, is the bottom
12105 // dock.
12106 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12107 workspace.update(cx, |workspace, cx| {
12108 assert!(workspace.bottom_dock().read(cx).is_open());
12109 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12110 });
12111
12112 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12113 // around moving the panel to its initial position, the right dock.
12114 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12115 workspace.update(cx, |workspace, cx| {
12116 assert!(workspace.right_dock().read(cx).is_open());
12117 assert_eq!(panel.read(cx).position, DockPosition::Right);
12118 });
12119
12120 // Remove focus from the panel, ensuring that, if the panel is not
12121 // focused, the `MoveFocusedPanelToNextPosition` action does not update
12122 // the panel's position, so the panel is still in the right dock.
12123 workspace.update_in(cx, |workspace, window, cx| {
12124 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12125 });
12126
12127 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12128 workspace.update(cx, |workspace, cx| {
12129 assert!(workspace.right_dock().read(cx).is_open());
12130 assert_eq!(panel.read(cx).position, DockPosition::Right);
12131 });
12132 }
12133
12134 #[gpui::test]
12135 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12136 init_test(cx);
12137
12138 let fs = FakeFs::new(cx.executor());
12139 let project = Project::test(fs, [], cx).await;
12140 let (workspace, cx) =
12141 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12142
12143 let item_1 = cx.new(|cx| {
12144 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12145 });
12146 workspace.update_in(cx, |workspace, window, cx| {
12147 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12148 workspace.move_item_to_pane_in_direction(
12149 &MoveItemToPaneInDirection {
12150 direction: SplitDirection::Right,
12151 focus: true,
12152 clone: false,
12153 },
12154 window,
12155 cx,
12156 );
12157 workspace.move_item_to_pane_at_index(
12158 &MoveItemToPane {
12159 destination: 3,
12160 focus: true,
12161 clone: false,
12162 },
12163 window,
12164 cx,
12165 );
12166
12167 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12168 assert_eq!(
12169 pane_items_paths(&workspace.active_pane, cx),
12170 vec!["first.txt".to_string()],
12171 "Single item was not moved anywhere"
12172 );
12173 });
12174
12175 let item_2 = cx.new(|cx| {
12176 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12177 });
12178 workspace.update_in(cx, |workspace, window, cx| {
12179 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12180 assert_eq!(
12181 pane_items_paths(&workspace.panes[0], cx),
12182 vec!["first.txt".to_string(), "second.txt".to_string()],
12183 );
12184 workspace.move_item_to_pane_in_direction(
12185 &MoveItemToPaneInDirection {
12186 direction: SplitDirection::Right,
12187 focus: true,
12188 clone: false,
12189 },
12190 window,
12191 cx,
12192 );
12193
12194 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12195 assert_eq!(
12196 pane_items_paths(&workspace.panes[0], cx),
12197 vec!["first.txt".to_string()],
12198 "After moving, one item should be left in the original pane"
12199 );
12200 assert_eq!(
12201 pane_items_paths(&workspace.panes[1], cx),
12202 vec!["second.txt".to_string()],
12203 "New item should have been moved to the new pane"
12204 );
12205 });
12206
12207 let item_3 = cx.new(|cx| {
12208 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12209 });
12210 workspace.update_in(cx, |workspace, window, cx| {
12211 let original_pane = workspace.panes[0].clone();
12212 workspace.set_active_pane(&original_pane, window, cx);
12213 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12214 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12215 assert_eq!(
12216 pane_items_paths(&workspace.active_pane, cx),
12217 vec!["first.txt".to_string(), "third.txt".to_string()],
12218 "New pane should be ready to move one item out"
12219 );
12220
12221 workspace.move_item_to_pane_at_index(
12222 &MoveItemToPane {
12223 destination: 3,
12224 focus: true,
12225 clone: false,
12226 },
12227 window,
12228 cx,
12229 );
12230 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12231 assert_eq!(
12232 pane_items_paths(&workspace.active_pane, cx),
12233 vec!["first.txt".to_string()],
12234 "After moving, one item should be left in the original pane"
12235 );
12236 assert_eq!(
12237 pane_items_paths(&workspace.panes[1], cx),
12238 vec!["second.txt".to_string()],
12239 "Previously created pane should be unchanged"
12240 );
12241 assert_eq!(
12242 pane_items_paths(&workspace.panes[2], cx),
12243 vec!["third.txt".to_string()],
12244 "New item should have been moved to the new pane"
12245 );
12246 });
12247 }
12248
12249 #[gpui::test]
12250 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
12251 init_test(cx);
12252
12253 let fs = FakeFs::new(cx.executor());
12254 let project = Project::test(fs, [], cx).await;
12255 let (workspace, cx) =
12256 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12257
12258 let item_1 = cx.new(|cx| {
12259 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12260 });
12261 workspace.update_in(cx, |workspace, window, cx| {
12262 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12263 workspace.move_item_to_pane_in_direction(
12264 &MoveItemToPaneInDirection {
12265 direction: SplitDirection::Right,
12266 focus: true,
12267 clone: true,
12268 },
12269 window,
12270 cx,
12271 );
12272 });
12273 cx.run_until_parked();
12274 workspace.update_in(cx, |workspace, window, cx| {
12275 workspace.move_item_to_pane_at_index(
12276 &MoveItemToPane {
12277 destination: 3,
12278 focus: true,
12279 clone: true,
12280 },
12281 window,
12282 cx,
12283 );
12284 });
12285 cx.run_until_parked();
12286
12287 workspace.update(cx, |workspace, cx| {
12288 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
12289 for pane in workspace.panes() {
12290 assert_eq!(
12291 pane_items_paths(pane, cx),
12292 vec!["first.txt".to_string()],
12293 "Single item exists in all panes"
12294 );
12295 }
12296 });
12297
12298 // verify that the active pane has been updated after waiting for the
12299 // pane focus event to fire and resolve
12300 workspace.read_with(cx, |workspace, _app| {
12301 assert_eq!(
12302 workspace.active_pane(),
12303 &workspace.panes[2],
12304 "The third pane should be the active one: {:?}",
12305 workspace.panes
12306 );
12307 })
12308 }
12309
12310 #[gpui::test]
12311 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
12312 init_test(cx);
12313
12314 let fs = FakeFs::new(cx.executor());
12315 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
12316
12317 let project = Project::test(fs, ["root".as_ref()], cx).await;
12318 let (workspace, cx) =
12319 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12320
12321 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12322 // Add item to pane A with project path
12323 let item_a = cx.new(|cx| {
12324 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12325 });
12326 workspace.update_in(cx, |workspace, window, cx| {
12327 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
12328 });
12329
12330 // Split to create pane B
12331 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
12332 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
12333 });
12334
12335 // Add item with SAME project path to pane B, and pin it
12336 let item_b = cx.new(|cx| {
12337 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12338 });
12339 pane_b.update_in(cx, |pane, window, cx| {
12340 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
12341 pane.set_pinned_count(1);
12342 });
12343
12344 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
12345 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
12346
12347 // close_pinned: false should only close the unpinned copy
12348 workspace.update_in(cx, |workspace, window, cx| {
12349 workspace.close_item_in_all_panes(
12350 &CloseItemInAllPanes {
12351 save_intent: Some(SaveIntent::Close),
12352 close_pinned: false,
12353 },
12354 window,
12355 cx,
12356 )
12357 });
12358 cx.executor().run_until_parked();
12359
12360 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
12361 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
12362 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
12363 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
12364
12365 // Split again, seeing as closing the previous item also closed its
12366 // pane, so only pane remains, which does not allow us to properly test
12367 // that both items close when `close_pinned: true`.
12368 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
12369 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
12370 });
12371
12372 // Add an item with the same project path to pane C so that
12373 // close_item_in_all_panes can determine what to close across all panes
12374 // (it reads the active item from the active pane, and split_pane
12375 // creates an empty pane).
12376 let item_c = cx.new(|cx| {
12377 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12378 });
12379 pane_c.update_in(cx, |pane, window, cx| {
12380 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
12381 });
12382
12383 // close_pinned: true should close the pinned copy too
12384 workspace.update_in(cx, |workspace, window, cx| {
12385 let panes_count = workspace.panes().len();
12386 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
12387
12388 workspace.close_item_in_all_panes(
12389 &CloseItemInAllPanes {
12390 save_intent: Some(SaveIntent::Close),
12391 close_pinned: true,
12392 },
12393 window,
12394 cx,
12395 )
12396 });
12397 cx.executor().run_until_parked();
12398
12399 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
12400 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
12401 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
12402 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
12403 }
12404
12405 mod register_project_item_tests {
12406
12407 use super::*;
12408
12409 // View
12410 struct TestPngItemView {
12411 focus_handle: FocusHandle,
12412 }
12413 // Model
12414 struct TestPngItem {}
12415
12416 impl project::ProjectItem for TestPngItem {
12417 fn try_open(
12418 _project: &Entity<Project>,
12419 path: &ProjectPath,
12420 cx: &mut App,
12421 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
12422 if path.path.extension().unwrap() == "png" {
12423 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
12424 } else {
12425 None
12426 }
12427 }
12428
12429 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
12430 None
12431 }
12432
12433 fn project_path(&self, _: &App) -> Option<ProjectPath> {
12434 None
12435 }
12436
12437 fn is_dirty(&self) -> bool {
12438 false
12439 }
12440 }
12441
12442 impl Item for TestPngItemView {
12443 type Event = ();
12444 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12445 "".into()
12446 }
12447 }
12448 impl EventEmitter<()> for TestPngItemView {}
12449 impl Focusable for TestPngItemView {
12450 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12451 self.focus_handle.clone()
12452 }
12453 }
12454
12455 impl Render for TestPngItemView {
12456 fn render(
12457 &mut self,
12458 _window: &mut Window,
12459 _cx: &mut Context<Self>,
12460 ) -> impl IntoElement {
12461 Empty
12462 }
12463 }
12464
12465 impl ProjectItem for TestPngItemView {
12466 type Item = TestPngItem;
12467
12468 fn for_project_item(
12469 _project: Entity<Project>,
12470 _pane: Option<&Pane>,
12471 _item: Entity<Self::Item>,
12472 _: &mut Window,
12473 cx: &mut Context<Self>,
12474 ) -> Self
12475 where
12476 Self: Sized,
12477 {
12478 Self {
12479 focus_handle: cx.focus_handle(),
12480 }
12481 }
12482 }
12483
12484 // View
12485 struct TestIpynbItemView {
12486 focus_handle: FocusHandle,
12487 }
12488 // Model
12489 struct TestIpynbItem {}
12490
12491 impl project::ProjectItem for TestIpynbItem {
12492 fn try_open(
12493 _project: &Entity<Project>,
12494 path: &ProjectPath,
12495 cx: &mut App,
12496 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
12497 if path.path.extension().unwrap() == "ipynb" {
12498 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
12499 } else {
12500 None
12501 }
12502 }
12503
12504 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
12505 None
12506 }
12507
12508 fn project_path(&self, _: &App) -> Option<ProjectPath> {
12509 None
12510 }
12511
12512 fn is_dirty(&self) -> bool {
12513 false
12514 }
12515 }
12516
12517 impl Item for TestIpynbItemView {
12518 type Event = ();
12519 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12520 "".into()
12521 }
12522 }
12523 impl EventEmitter<()> for TestIpynbItemView {}
12524 impl Focusable for TestIpynbItemView {
12525 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12526 self.focus_handle.clone()
12527 }
12528 }
12529
12530 impl Render for TestIpynbItemView {
12531 fn render(
12532 &mut self,
12533 _window: &mut Window,
12534 _cx: &mut Context<Self>,
12535 ) -> impl IntoElement {
12536 Empty
12537 }
12538 }
12539
12540 impl ProjectItem for TestIpynbItemView {
12541 type Item = TestIpynbItem;
12542
12543 fn for_project_item(
12544 _project: Entity<Project>,
12545 _pane: Option<&Pane>,
12546 _item: Entity<Self::Item>,
12547 _: &mut Window,
12548 cx: &mut Context<Self>,
12549 ) -> Self
12550 where
12551 Self: Sized,
12552 {
12553 Self {
12554 focus_handle: cx.focus_handle(),
12555 }
12556 }
12557 }
12558
12559 struct TestAlternatePngItemView {
12560 focus_handle: FocusHandle,
12561 }
12562
12563 impl Item for TestAlternatePngItemView {
12564 type Event = ();
12565 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12566 "".into()
12567 }
12568 }
12569
12570 impl EventEmitter<()> for TestAlternatePngItemView {}
12571 impl Focusable for TestAlternatePngItemView {
12572 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12573 self.focus_handle.clone()
12574 }
12575 }
12576
12577 impl Render for TestAlternatePngItemView {
12578 fn render(
12579 &mut self,
12580 _window: &mut Window,
12581 _cx: &mut Context<Self>,
12582 ) -> impl IntoElement {
12583 Empty
12584 }
12585 }
12586
12587 impl ProjectItem for TestAlternatePngItemView {
12588 type Item = TestPngItem;
12589
12590 fn for_project_item(
12591 _project: Entity<Project>,
12592 _pane: Option<&Pane>,
12593 _item: Entity<Self::Item>,
12594 _: &mut Window,
12595 cx: &mut Context<Self>,
12596 ) -> Self
12597 where
12598 Self: Sized,
12599 {
12600 Self {
12601 focus_handle: cx.focus_handle(),
12602 }
12603 }
12604 }
12605
12606 #[gpui::test]
12607 async fn test_register_project_item(cx: &mut TestAppContext) {
12608 init_test(cx);
12609
12610 cx.update(|cx| {
12611 register_project_item::<TestPngItemView>(cx);
12612 register_project_item::<TestIpynbItemView>(cx);
12613 });
12614
12615 let fs = FakeFs::new(cx.executor());
12616 fs.insert_tree(
12617 "/root1",
12618 json!({
12619 "one.png": "BINARYDATAHERE",
12620 "two.ipynb": "{ totally a notebook }",
12621 "three.txt": "editing text, sure why not?"
12622 }),
12623 )
12624 .await;
12625
12626 let project = Project::test(fs, ["root1".as_ref()], cx).await;
12627 let (workspace, cx) =
12628 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12629
12630 let worktree_id = project.update(cx, |project, cx| {
12631 project.worktrees(cx).next().unwrap().read(cx).id()
12632 });
12633
12634 let handle = workspace
12635 .update_in(cx, |workspace, window, cx| {
12636 let project_path = (worktree_id, rel_path("one.png"));
12637 workspace.open_path(project_path, None, true, window, cx)
12638 })
12639 .await
12640 .unwrap();
12641
12642 // Now we can check if the handle we got back errored or not
12643 assert_eq!(
12644 handle.to_any_view().entity_type(),
12645 TypeId::of::<TestPngItemView>()
12646 );
12647
12648 let handle = workspace
12649 .update_in(cx, |workspace, window, cx| {
12650 let project_path = (worktree_id, rel_path("two.ipynb"));
12651 workspace.open_path(project_path, None, true, window, cx)
12652 })
12653 .await
12654 .unwrap();
12655
12656 assert_eq!(
12657 handle.to_any_view().entity_type(),
12658 TypeId::of::<TestIpynbItemView>()
12659 );
12660
12661 let handle = workspace
12662 .update_in(cx, |workspace, window, cx| {
12663 let project_path = (worktree_id, rel_path("three.txt"));
12664 workspace.open_path(project_path, None, true, window, cx)
12665 })
12666 .await;
12667 assert!(handle.is_err());
12668 }
12669
12670 #[gpui::test]
12671 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
12672 init_test(cx);
12673
12674 cx.update(|cx| {
12675 register_project_item::<TestPngItemView>(cx);
12676 register_project_item::<TestAlternatePngItemView>(cx);
12677 });
12678
12679 let fs = FakeFs::new(cx.executor());
12680 fs.insert_tree(
12681 "/root1",
12682 json!({
12683 "one.png": "BINARYDATAHERE",
12684 "two.ipynb": "{ totally a notebook }",
12685 "three.txt": "editing text, sure why not?"
12686 }),
12687 )
12688 .await;
12689 let project = Project::test(fs, ["root1".as_ref()], cx).await;
12690 let (workspace, cx) =
12691 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12692 let worktree_id = project.update(cx, |project, cx| {
12693 project.worktrees(cx).next().unwrap().read(cx).id()
12694 });
12695
12696 let handle = workspace
12697 .update_in(cx, |workspace, window, cx| {
12698 let project_path = (worktree_id, rel_path("one.png"));
12699 workspace.open_path(project_path, None, true, window, cx)
12700 })
12701 .await
12702 .unwrap();
12703
12704 // This _must_ be the second item registered
12705 assert_eq!(
12706 handle.to_any_view().entity_type(),
12707 TypeId::of::<TestAlternatePngItemView>()
12708 );
12709
12710 let handle = workspace
12711 .update_in(cx, |workspace, window, cx| {
12712 let project_path = (worktree_id, rel_path("three.txt"));
12713 workspace.open_path(project_path, None, true, window, cx)
12714 })
12715 .await;
12716 assert!(handle.is_err());
12717 }
12718 }
12719
12720 #[gpui::test]
12721 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
12722 init_test(cx);
12723
12724 let fs = FakeFs::new(cx.executor());
12725 let project = Project::test(fs, [], cx).await;
12726 let (workspace, _cx) =
12727 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12728
12729 // Test with status bar shown (default)
12730 workspace.read_with(cx, |workspace, cx| {
12731 let visible = workspace.status_bar_visible(cx);
12732 assert!(visible, "Status bar should be visible by default");
12733 });
12734
12735 // Test with status bar hidden
12736 cx.update_global(|store: &mut SettingsStore, cx| {
12737 store.update_user_settings(cx, |settings| {
12738 settings.status_bar.get_or_insert_default().show = Some(false);
12739 });
12740 });
12741
12742 workspace.read_with(cx, |workspace, cx| {
12743 let visible = workspace.status_bar_visible(cx);
12744 assert!(!visible, "Status bar should be hidden when show is false");
12745 });
12746
12747 // Test with status bar shown explicitly
12748 cx.update_global(|store: &mut SettingsStore, cx| {
12749 store.update_user_settings(cx, |settings| {
12750 settings.status_bar.get_or_insert_default().show = Some(true);
12751 });
12752 });
12753
12754 workspace.read_with(cx, |workspace, cx| {
12755 let visible = workspace.status_bar_visible(cx);
12756 assert!(visible, "Status bar should be visible when show is true");
12757 });
12758 }
12759
12760 #[gpui::test]
12761 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
12762 init_test(cx);
12763
12764 let fs = FakeFs::new(cx.executor());
12765 let project = Project::test(fs, [], cx).await;
12766 let (workspace, cx) =
12767 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12768 let panel = workspace.update_in(cx, |workspace, window, cx| {
12769 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12770 workspace.add_panel(panel.clone(), window, cx);
12771
12772 workspace
12773 .right_dock()
12774 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12775
12776 panel
12777 });
12778
12779 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12780 let item_a = cx.new(TestItem::new);
12781 let item_b = cx.new(TestItem::new);
12782 let item_a_id = item_a.entity_id();
12783 let item_b_id = item_b.entity_id();
12784
12785 pane.update_in(cx, |pane, window, cx| {
12786 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
12787 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
12788 });
12789
12790 pane.read_with(cx, |pane, _| {
12791 assert_eq!(pane.items_len(), 2);
12792 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
12793 });
12794
12795 workspace.update_in(cx, |workspace, window, cx| {
12796 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12797 });
12798
12799 workspace.update_in(cx, |_, window, cx| {
12800 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12801 });
12802
12803 // Assert that the `pane::CloseActiveItem` action is handled at the
12804 // workspace level when one of the dock panels is focused and, in that
12805 // case, the center pane's active item is closed but the focus is not
12806 // moved.
12807 cx.dispatch_action(pane::CloseActiveItem::default());
12808 cx.run_until_parked();
12809
12810 pane.read_with(cx, |pane, _| {
12811 assert_eq!(pane.items_len(), 1);
12812 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
12813 });
12814
12815 workspace.update_in(cx, |workspace, window, cx| {
12816 assert!(workspace.right_dock().read(cx).is_open());
12817 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12818 });
12819 }
12820
12821 #[gpui::test]
12822 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
12823 init_test(cx);
12824 let fs = FakeFs::new(cx.executor());
12825
12826 let project_a = Project::test(fs.clone(), [], cx).await;
12827 let project_b = Project::test(fs, [], cx).await;
12828
12829 let multi_workspace_handle =
12830 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
12831
12832 let workspace_a = multi_workspace_handle
12833 .read_with(cx, |mw, _| mw.workspace().clone())
12834 .unwrap();
12835
12836 let _workspace_b = multi_workspace_handle
12837 .update(cx, |mw, window, cx| {
12838 mw.test_add_workspace(project_b, window, cx)
12839 })
12840 .unwrap();
12841
12842 // Switch to workspace A
12843 multi_workspace_handle
12844 .update(cx, |mw, window, cx| {
12845 mw.activate_index(0, window, cx);
12846 })
12847 .unwrap();
12848
12849 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
12850
12851 // Add a panel to workspace A's right dock and open the dock
12852 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
12853 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12854 workspace.add_panel(panel.clone(), window, cx);
12855 workspace
12856 .right_dock()
12857 .update(cx, |dock, cx| dock.set_open(true, window, cx));
12858 panel
12859 });
12860
12861 // Focus the panel through the workspace (matching existing test pattern)
12862 workspace_a.update_in(cx, |workspace, window, cx| {
12863 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12864 });
12865
12866 // Zoom the panel
12867 panel.update_in(cx, |panel, window, cx| {
12868 panel.set_zoomed(true, window, cx);
12869 });
12870
12871 // Verify the panel is zoomed and the dock is open
12872 workspace_a.update_in(cx, |workspace, window, cx| {
12873 assert!(
12874 workspace.right_dock().read(cx).is_open(),
12875 "dock should be open before switch"
12876 );
12877 assert!(
12878 panel.is_zoomed(window, cx),
12879 "panel should be zoomed before switch"
12880 );
12881 assert!(
12882 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12883 "panel should be focused before switch"
12884 );
12885 });
12886
12887 // Switch to workspace B
12888 multi_workspace_handle
12889 .update(cx, |mw, window, cx| {
12890 mw.activate_index(1, window, cx);
12891 })
12892 .unwrap();
12893 cx.run_until_parked();
12894
12895 // Switch back to workspace A
12896 multi_workspace_handle
12897 .update(cx, |mw, window, cx| {
12898 mw.activate_index(0, window, cx);
12899 })
12900 .unwrap();
12901 cx.run_until_parked();
12902
12903 // Verify the panel is still zoomed and the dock is still open
12904 workspace_a.update_in(cx, |workspace, window, cx| {
12905 assert!(
12906 workspace.right_dock().read(cx).is_open(),
12907 "dock should still be open after switching back"
12908 );
12909 assert!(
12910 panel.is_zoomed(window, cx),
12911 "panel should still be zoomed after switching back"
12912 );
12913 });
12914 }
12915
12916 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
12917 pane.read(cx)
12918 .items()
12919 .flat_map(|item| {
12920 item.project_paths(cx)
12921 .into_iter()
12922 .map(|path| path.path.display(PathStyle::local()).into_owned())
12923 })
12924 .collect()
12925 }
12926
12927 pub fn init_test(cx: &mut TestAppContext) {
12928 cx.update(|cx| {
12929 let settings_store = SettingsStore::test(cx);
12930 cx.set_global(settings_store);
12931 theme::init(theme::LoadThemes::JustBase, cx);
12932 });
12933 }
12934
12935 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
12936 let item = TestProjectItem::new(id, path, cx);
12937 item.update(cx, |item, _| {
12938 item.is_dirty = true;
12939 });
12940 item
12941 }
12942
12943 #[gpui::test]
12944 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
12945 cx: &mut gpui::TestAppContext,
12946 ) {
12947 init_test(cx);
12948 let fs = FakeFs::new(cx.executor());
12949
12950 let project = Project::test(fs, [], cx).await;
12951 let (workspace, cx) =
12952 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12953
12954 let panel = workspace.update_in(cx, |workspace, window, cx| {
12955 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12956 workspace.add_panel(panel.clone(), window, cx);
12957 workspace
12958 .right_dock()
12959 .update(cx, |dock, cx| dock.set_open(true, window, cx));
12960 panel
12961 });
12962
12963 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12964 pane.update_in(cx, |pane, window, cx| {
12965 let item = cx.new(TestItem::new);
12966 pane.add_item(Box::new(item), true, true, None, window, cx);
12967 });
12968
12969 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
12970 // mirrors the real-world flow and avoids side effects from directly
12971 // focusing the panel while the center pane is active.
12972 workspace.update_in(cx, |workspace, window, cx| {
12973 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12974 });
12975
12976 panel.update_in(cx, |panel, window, cx| {
12977 panel.set_zoomed(true, window, cx);
12978 });
12979
12980 workspace.update_in(cx, |workspace, window, cx| {
12981 assert!(workspace.right_dock().read(cx).is_open());
12982 assert!(panel.is_zoomed(window, cx));
12983 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12984 });
12985
12986 // Simulate a spurious pane::Event::Focus on the center pane while the
12987 // panel still has focus. This mirrors what happens during macOS window
12988 // activation: the center pane fires a focus event even though actual
12989 // focus remains on the dock panel.
12990 pane.update_in(cx, |_, _, cx| {
12991 cx.emit(pane::Event::Focus);
12992 });
12993
12994 // The dock must remain open because the panel had focus at the time the
12995 // event was processed. Before the fix, dock_to_preserve was None for
12996 // panels that don't implement pane(), causing the dock to close.
12997 workspace.update_in(cx, |workspace, window, cx| {
12998 assert!(
12999 workspace.right_dock().read(cx).is_open(),
13000 "Dock should stay open when its zoomed panel (without pane()) still has focus"
13001 );
13002 assert!(panel.is_zoomed(window, cx));
13003 });
13004 }
13005}