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)]
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, 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.serialize_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 serialize_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, window, cx| {
7976 multi_workspace.open_sidebar(window, 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 cx.windows()
8312 .into_iter()
8313 .filter_map(|window| window.downcast::<MultiWorkspace>())
8314 .filter(|multi_workspace| {
8315 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
8316 multi_workspace
8317 .workspaces()
8318 .iter()
8319 .any(|workspace| workspace.read(cx).project.read(cx).is_local())
8320 })
8321 })
8322 .collect()
8323}
8324
8325#[derive(Default)]
8326pub struct OpenOptions {
8327 pub visible: Option<OpenVisible>,
8328 pub focus: Option<bool>,
8329 pub open_new_workspace: Option<bool>,
8330 pub prefer_focused_window: bool,
8331 pub replace_window: Option<WindowHandle<MultiWorkspace>>,
8332 pub env: Option<HashMap<String, String>>,
8333}
8334
8335/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
8336pub fn open_workspace_by_id(
8337 workspace_id: WorkspaceId,
8338 app_state: Arc<AppState>,
8339 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8340 cx: &mut App,
8341) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
8342 let project_handle = Project::local(
8343 app_state.client.clone(),
8344 app_state.node_runtime.clone(),
8345 app_state.user_store.clone(),
8346 app_state.languages.clone(),
8347 app_state.fs.clone(),
8348 None,
8349 project::LocalProjectFlags {
8350 init_worktree_trust: true,
8351 ..project::LocalProjectFlags::default()
8352 },
8353 cx,
8354 );
8355
8356 cx.spawn(async move |cx| {
8357 let serialized_workspace = persistence::DB
8358 .workspace_for_id(workspace_id)
8359 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
8360
8361 let centered_layout = serialized_workspace.centered_layout;
8362
8363 let (window, workspace) = if let Some(window) = requesting_window {
8364 let workspace = window.update(cx, |multi_workspace, window, cx| {
8365 let workspace = cx.new(|cx| {
8366 let mut workspace = Workspace::new(
8367 Some(workspace_id),
8368 project_handle.clone(),
8369 app_state.clone(),
8370 window,
8371 cx,
8372 );
8373 workspace.centered_layout = centered_layout;
8374 workspace
8375 });
8376 multi_workspace.add_workspace(workspace.clone(), cx);
8377 workspace
8378 })?;
8379 (window, workspace)
8380 } else {
8381 let window_bounds_override = window_bounds_env_override();
8382
8383 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
8384 (Some(WindowBounds::Windowed(bounds)), None)
8385 } else if let Some(display) = serialized_workspace.display
8386 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
8387 {
8388 (Some(bounds.0), Some(display))
8389 } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
8390 (Some(bounds), Some(display))
8391 } else {
8392 (None, None)
8393 };
8394
8395 let options = cx.update(|cx| {
8396 let mut options = (app_state.build_window_options)(display, cx);
8397 options.window_bounds = window_bounds;
8398 options
8399 });
8400
8401 let window = cx.open_window(options, {
8402 let app_state = app_state.clone();
8403 let project_handle = project_handle.clone();
8404 move |window, cx| {
8405 let workspace = cx.new(|cx| {
8406 let mut workspace = Workspace::new(
8407 Some(workspace_id),
8408 project_handle,
8409 app_state,
8410 window,
8411 cx,
8412 );
8413 workspace.centered_layout = centered_layout;
8414 workspace
8415 });
8416 cx.new(|cx| MultiWorkspace::new(workspace, cx))
8417 }
8418 })?;
8419
8420 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
8421 multi_workspace.workspace().clone()
8422 })?;
8423
8424 (window, workspace)
8425 };
8426
8427 notify_if_database_failed(window, cx);
8428
8429 // Restore items from the serialized workspace
8430 window
8431 .update(cx, |_, window, cx| {
8432 workspace.update(cx, |_workspace, cx| {
8433 open_items(Some(serialized_workspace), vec![], window, cx)
8434 })
8435 })?
8436 .await?;
8437
8438 window.update(cx, |_, window, cx| {
8439 workspace.update(cx, |workspace, cx| {
8440 workspace.serialize_workspace(window, cx);
8441 });
8442 })?;
8443
8444 Ok(window)
8445 })
8446}
8447
8448#[allow(clippy::type_complexity)]
8449pub fn open_paths(
8450 abs_paths: &[PathBuf],
8451 app_state: Arc<AppState>,
8452 open_options: OpenOptions,
8453 cx: &mut App,
8454) -> Task<
8455 anyhow::Result<(
8456 WindowHandle<MultiWorkspace>,
8457 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
8458 )>,
8459> {
8460 let abs_paths = abs_paths.to_vec();
8461 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
8462 let mut best_match = None;
8463 let mut open_visible = OpenVisible::All;
8464 #[cfg(target_os = "windows")]
8465 let wsl_path = abs_paths
8466 .iter()
8467 .find_map(|p| util::paths::WslPath::from_path(p));
8468
8469 cx.spawn(async move |cx| {
8470 if open_options.open_new_workspace != Some(true) {
8471 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
8472 let all_metadatas = futures::future::join_all(all_paths)
8473 .await
8474 .into_iter()
8475 .filter_map(|result| result.ok().flatten())
8476 .collect::<Vec<_>>();
8477
8478 cx.update(|cx| {
8479 for window in local_workspace_windows(cx) {
8480 if let Ok(multi_workspace) = window.read(cx) {
8481 for workspace in multi_workspace.workspaces() {
8482 let m = workspace.read(cx).project.read(cx).visibility_for_paths(
8483 &abs_paths,
8484 &all_metadatas,
8485 open_options.open_new_workspace == None,
8486 cx,
8487 );
8488 if m > best_match {
8489 existing = Some((window, workspace.clone()));
8490 best_match = m;
8491 } else if best_match.is_none()
8492 && open_options.open_new_workspace == Some(false)
8493 {
8494 existing = Some((window, workspace.clone()))
8495 }
8496 }
8497 }
8498 }
8499 });
8500
8501 if (open_options.open_new_workspace.is_none()
8502 || (open_options.open_new_workspace == Some(false)
8503 && open_options.prefer_focused_window))
8504 && (existing.is_none() || open_options.prefer_focused_window)
8505 && all_metadatas.iter().all(|file| !file.is_dir)
8506 {
8507 cx.update(|cx| {
8508 if let Some(window) = cx
8509 .active_window()
8510 .and_then(|window| window.downcast::<MultiWorkspace>())
8511 && let Ok(multi_workspace) = window.read(cx)
8512 {
8513 let active_workspace = multi_workspace.workspace().clone();
8514 let project = active_workspace.read(cx).project().read(cx);
8515 if project.is_local() && !project.is_via_collab() {
8516 existing = Some((window, active_workspace));
8517 open_visible = OpenVisible::None;
8518 return;
8519 }
8520 }
8521 'outer: for window in local_workspace_windows(cx) {
8522 if let Ok(multi_workspace) = window.read(cx) {
8523 for workspace in multi_workspace.workspaces() {
8524 let project = workspace.read(cx).project().read(cx);
8525 if project.is_via_collab() {
8526 continue;
8527 }
8528 existing = Some((window, workspace.clone()));
8529 open_visible = OpenVisible::None;
8530 break 'outer;
8531 }
8532 }
8533 }
8534 });
8535 }
8536 }
8537
8538 let result = if let Some((existing, target_workspace)) = existing {
8539 let open_task = existing
8540 .update(cx, |multi_workspace, window, cx| {
8541 window.activate_window();
8542 multi_workspace.activate(target_workspace.clone(), cx);
8543 target_workspace.update(cx, |workspace, cx| {
8544 workspace.open_paths(
8545 abs_paths,
8546 OpenOptions {
8547 visible: Some(open_visible),
8548 ..Default::default()
8549 },
8550 None,
8551 window,
8552 cx,
8553 )
8554 })
8555 })?
8556 .await;
8557
8558 _ = existing.update(cx, |multi_workspace, _, cx| {
8559 let workspace = multi_workspace.workspace().clone();
8560 workspace.update(cx, |workspace, cx| {
8561 for item in open_task.iter().flatten() {
8562 if let Err(e) = item {
8563 workspace.show_error(&e, cx);
8564 }
8565 }
8566 });
8567 });
8568
8569 Ok((existing, open_task))
8570 } else {
8571 let result = cx
8572 .update(move |cx| {
8573 Workspace::new_local(
8574 abs_paths,
8575 app_state.clone(),
8576 open_options.replace_window,
8577 open_options.env,
8578 None,
8579 cx,
8580 )
8581 })
8582 .await;
8583
8584 if let Ok((ref window_handle, _)) = result {
8585 window_handle
8586 .update(cx, |_, window, _cx| {
8587 window.activate_window();
8588 })
8589 .log_err();
8590 }
8591
8592 result
8593 };
8594
8595 #[cfg(target_os = "windows")]
8596 if let Some(util::paths::WslPath{distro, path}) = wsl_path
8597 && let Ok((multi_workspace_window, _)) = &result
8598 {
8599 multi_workspace_window
8600 .update(cx, move |multi_workspace, _window, cx| {
8601 struct OpenInWsl;
8602 let workspace = multi_workspace.workspace().clone();
8603 workspace.update(cx, |workspace, cx| {
8604 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
8605 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
8606 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
8607 cx.new(move |cx| {
8608 MessageNotification::new(msg, cx)
8609 .primary_message("Open in WSL")
8610 .primary_icon(IconName::FolderOpen)
8611 .primary_on_click(move |window, cx| {
8612 window.dispatch_action(Box::new(remote::OpenWslPath {
8613 distro: remote::WslConnectionOptions {
8614 distro_name: distro.clone(),
8615 user: None,
8616 },
8617 paths: vec![path.clone().into()],
8618 }), cx)
8619 })
8620 })
8621 });
8622 });
8623 })
8624 .unwrap();
8625 };
8626 result
8627 })
8628}
8629
8630pub fn open_new(
8631 open_options: OpenOptions,
8632 app_state: Arc<AppState>,
8633 cx: &mut App,
8634 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
8635) -> Task<anyhow::Result<()>> {
8636 let task = Workspace::new_local(
8637 Vec::new(),
8638 app_state,
8639 open_options.replace_window,
8640 open_options.env,
8641 Some(Box::new(init)),
8642 cx,
8643 );
8644 cx.spawn(async move |cx| {
8645 let (window, _opened_paths) = task.await?;
8646 window
8647 .update(cx, |_, window, _cx| {
8648 window.activate_window();
8649 })
8650 .ok();
8651 Ok(())
8652 })
8653}
8654
8655pub fn create_and_open_local_file(
8656 path: &'static Path,
8657 window: &mut Window,
8658 cx: &mut Context<Workspace>,
8659 default_content: impl 'static + Send + FnOnce() -> Rope,
8660) -> Task<Result<Box<dyn ItemHandle>>> {
8661 cx.spawn_in(window, async move |workspace, cx| {
8662 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
8663 if !fs.is_file(path).await {
8664 fs.create_file(path, Default::default()).await?;
8665 fs.save(path, &default_content(), Default::default())
8666 .await?;
8667 }
8668
8669 workspace
8670 .update_in(cx, |workspace, window, cx| {
8671 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
8672 let path = workspace
8673 .project
8674 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
8675 cx.spawn_in(window, async move |workspace, cx| {
8676 let path = path.await?;
8677 let mut items = workspace
8678 .update_in(cx, |workspace, window, cx| {
8679 workspace.open_paths(
8680 vec![path.to_path_buf()],
8681 OpenOptions {
8682 visible: Some(OpenVisible::None),
8683 ..Default::default()
8684 },
8685 None,
8686 window,
8687 cx,
8688 )
8689 })?
8690 .await;
8691 let item = items.pop().flatten();
8692 item.with_context(|| format!("path {path:?} is not a file"))?
8693 })
8694 })
8695 })?
8696 .await?
8697 .await
8698 })
8699}
8700
8701pub fn open_remote_project_with_new_connection(
8702 window: WindowHandle<MultiWorkspace>,
8703 remote_connection: Arc<dyn RemoteConnection>,
8704 cancel_rx: oneshot::Receiver<()>,
8705 delegate: Arc<dyn RemoteClientDelegate>,
8706 app_state: Arc<AppState>,
8707 paths: Vec<PathBuf>,
8708 cx: &mut App,
8709) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
8710 cx.spawn(async move |cx| {
8711 let (workspace_id, serialized_workspace) =
8712 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
8713 .await?;
8714
8715 let session = match cx
8716 .update(|cx| {
8717 remote::RemoteClient::new(
8718 ConnectionIdentifier::Workspace(workspace_id.0),
8719 remote_connection,
8720 cancel_rx,
8721 delegate,
8722 cx,
8723 )
8724 })
8725 .await?
8726 {
8727 Some(result) => result,
8728 None => return Ok(Vec::new()),
8729 };
8730
8731 let project = cx.update(|cx| {
8732 project::Project::remote(
8733 session,
8734 app_state.client.clone(),
8735 app_state.node_runtime.clone(),
8736 app_state.user_store.clone(),
8737 app_state.languages.clone(),
8738 app_state.fs.clone(),
8739 true,
8740 cx,
8741 )
8742 });
8743
8744 open_remote_project_inner(
8745 project,
8746 paths,
8747 workspace_id,
8748 serialized_workspace,
8749 app_state,
8750 window,
8751 cx,
8752 )
8753 .await
8754 })
8755}
8756
8757pub fn open_remote_project_with_existing_connection(
8758 connection_options: RemoteConnectionOptions,
8759 project: Entity<Project>,
8760 paths: Vec<PathBuf>,
8761 app_state: Arc<AppState>,
8762 window: WindowHandle<MultiWorkspace>,
8763 cx: &mut AsyncApp,
8764) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
8765 cx.spawn(async move |cx| {
8766 let (workspace_id, serialized_workspace) =
8767 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
8768
8769 open_remote_project_inner(
8770 project,
8771 paths,
8772 workspace_id,
8773 serialized_workspace,
8774 app_state,
8775 window,
8776 cx,
8777 )
8778 .await
8779 })
8780}
8781
8782async fn open_remote_project_inner(
8783 project: Entity<Project>,
8784 paths: Vec<PathBuf>,
8785 workspace_id: WorkspaceId,
8786 serialized_workspace: Option<SerializedWorkspace>,
8787 app_state: Arc<AppState>,
8788 window: WindowHandle<MultiWorkspace>,
8789 cx: &mut AsyncApp,
8790) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
8791 let toolchains = DB.toolchains(workspace_id).await?;
8792 for (toolchain, worktree_path, path) in toolchains {
8793 project
8794 .update(cx, |this, cx| {
8795 let Some(worktree_id) =
8796 this.find_worktree(&worktree_path, cx)
8797 .and_then(|(worktree, rel_path)| {
8798 if rel_path.is_empty() {
8799 Some(worktree.read(cx).id())
8800 } else {
8801 None
8802 }
8803 })
8804 else {
8805 return Task::ready(None);
8806 };
8807
8808 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
8809 })
8810 .await;
8811 }
8812 let mut project_paths_to_open = vec![];
8813 let mut project_path_errors = vec![];
8814
8815 for path in paths {
8816 let result = cx
8817 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
8818 .await;
8819 match result {
8820 Ok((_, project_path)) => {
8821 project_paths_to_open.push((path.clone(), Some(project_path)));
8822 }
8823 Err(error) => {
8824 project_path_errors.push(error);
8825 }
8826 };
8827 }
8828
8829 if project_paths_to_open.is_empty() {
8830 return Err(project_path_errors.pop().context("no paths given")?);
8831 }
8832
8833 let workspace = window.update(cx, |multi_workspace, window, cx| {
8834 telemetry::event!("SSH Project Opened");
8835
8836 let new_workspace = cx.new(|cx| {
8837 let mut workspace =
8838 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
8839 workspace.update_history(cx);
8840
8841 if let Some(ref serialized) = serialized_workspace {
8842 workspace.centered_layout = serialized.centered_layout;
8843 }
8844
8845 workspace
8846 });
8847
8848 multi_workspace.activate(new_workspace.clone(), cx);
8849 new_workspace
8850 })?;
8851
8852 let items = window
8853 .update(cx, |_, window, cx| {
8854 window.activate_window();
8855 workspace.update(cx, |_workspace, cx| {
8856 open_items(serialized_workspace, project_paths_to_open, window, cx)
8857 })
8858 })?
8859 .await?;
8860
8861 workspace.update(cx, |workspace, cx| {
8862 for error in project_path_errors {
8863 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
8864 if let Some(path) = error.error_tag("path") {
8865 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
8866 }
8867 } else {
8868 workspace.show_error(&error, cx)
8869 }
8870 }
8871 });
8872
8873 Ok(items.into_iter().map(|item| item?.ok()).collect())
8874}
8875
8876fn deserialize_remote_project(
8877 connection_options: RemoteConnectionOptions,
8878 paths: Vec<PathBuf>,
8879 cx: &AsyncApp,
8880) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
8881 cx.background_spawn(async move {
8882 let remote_connection_id = persistence::DB
8883 .get_or_create_remote_connection(connection_options)
8884 .await?;
8885
8886 let serialized_workspace =
8887 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
8888
8889 let workspace_id = if let Some(workspace_id) =
8890 serialized_workspace.as_ref().map(|workspace| workspace.id)
8891 {
8892 workspace_id
8893 } else {
8894 persistence::DB.next_id().await?
8895 };
8896
8897 Ok((workspace_id, serialized_workspace))
8898 })
8899}
8900
8901pub fn join_in_room_project(
8902 project_id: u64,
8903 follow_user_id: u64,
8904 app_state: Arc<AppState>,
8905 cx: &mut App,
8906) -> Task<Result<()>> {
8907 let windows = cx.windows();
8908 cx.spawn(async move |cx| {
8909 let existing_window_and_workspace: Option<(
8910 WindowHandle<MultiWorkspace>,
8911 Entity<Workspace>,
8912 )> = windows.into_iter().find_map(|window_handle| {
8913 window_handle
8914 .downcast::<MultiWorkspace>()
8915 .and_then(|window_handle| {
8916 window_handle
8917 .update(cx, |multi_workspace, _window, cx| {
8918 for workspace in multi_workspace.workspaces() {
8919 if workspace.read(cx).project().read(cx).remote_id()
8920 == Some(project_id)
8921 {
8922 return Some((window_handle, workspace.clone()));
8923 }
8924 }
8925 None
8926 })
8927 .unwrap_or(None)
8928 })
8929 });
8930
8931 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
8932 existing_window_and_workspace
8933 {
8934 existing_window
8935 .update(cx, |multi_workspace, _, cx| {
8936 multi_workspace.activate(target_workspace, cx);
8937 })
8938 .ok();
8939 existing_window
8940 } else {
8941 let active_call = cx.update(|cx| ActiveCall::global(cx));
8942 let room = active_call
8943 .read_with(cx, |call, _| call.room().cloned())
8944 .context("not in a call")?;
8945 let project = room
8946 .update(cx, |room, cx| {
8947 room.join_project(
8948 project_id,
8949 app_state.languages.clone(),
8950 app_state.fs.clone(),
8951 cx,
8952 )
8953 })
8954 .await?;
8955
8956 let window_bounds_override = window_bounds_env_override();
8957 cx.update(|cx| {
8958 let mut options = (app_state.build_window_options)(None, cx);
8959 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
8960 cx.open_window(options, |window, cx| {
8961 let workspace = cx.new(|cx| {
8962 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
8963 });
8964 cx.new(|cx| MultiWorkspace::new(workspace, cx))
8965 })
8966 })?
8967 };
8968
8969 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
8970 cx.activate(true);
8971 window.activate_window();
8972
8973 // We set the active workspace above, so this is the correct workspace.
8974 let workspace = multi_workspace.workspace().clone();
8975 workspace.update(cx, |workspace, cx| {
8976 if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
8977 let follow_peer_id = room
8978 .read(cx)
8979 .remote_participants()
8980 .iter()
8981 .find(|(_, participant)| participant.user.id == follow_user_id)
8982 .map(|(_, p)| p.peer_id)
8983 .or_else(|| {
8984 // If we couldn't follow the given user, follow the host instead.
8985 let collaborator = workspace
8986 .project()
8987 .read(cx)
8988 .collaborators()
8989 .values()
8990 .find(|collaborator| collaborator.is_host)?;
8991 Some(collaborator.peer_id)
8992 });
8993
8994 if let Some(follow_peer_id) = follow_peer_id {
8995 workspace.follow(follow_peer_id, window, cx);
8996 }
8997 }
8998 });
8999 })?;
9000
9001 anyhow::Ok(())
9002 })
9003}
9004
9005pub fn reload(cx: &mut App) {
9006 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9007 let mut workspace_windows = cx
9008 .windows()
9009 .into_iter()
9010 .filter_map(|window| window.downcast::<MultiWorkspace>())
9011 .collect::<Vec<_>>();
9012
9013 // If multiple windows have unsaved changes, and need a save prompt,
9014 // prompt in the active window before switching to a different window.
9015 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9016
9017 let mut prompt = None;
9018 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9019 prompt = window
9020 .update(cx, |_, window, cx| {
9021 window.prompt(
9022 PromptLevel::Info,
9023 "Are you sure you want to restart?",
9024 None,
9025 &["Restart", "Cancel"],
9026 cx,
9027 )
9028 })
9029 .ok();
9030 }
9031
9032 cx.spawn(async move |cx| {
9033 if let Some(prompt) = prompt {
9034 let answer = prompt.await?;
9035 if answer != 0 {
9036 return anyhow::Ok(());
9037 }
9038 }
9039
9040 // If the user cancels any save prompt, then keep the app open.
9041 for window in workspace_windows {
9042 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9043 let workspace = multi_workspace.workspace().clone();
9044 workspace.update(cx, |workspace, cx| {
9045 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9046 })
9047 }) && !should_close.await?
9048 {
9049 return anyhow::Ok(());
9050 }
9051 }
9052 cx.update(|cx| cx.restart());
9053 anyhow::Ok(())
9054 })
9055 .detach_and_log_err(cx);
9056}
9057
9058fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9059 let mut parts = value.split(',');
9060 let x: usize = parts.next()?.parse().ok()?;
9061 let y: usize = parts.next()?.parse().ok()?;
9062 Some(point(px(x as f32), px(y as f32)))
9063}
9064
9065fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9066 let mut parts = value.split(',');
9067 let width: usize = parts.next()?.parse().ok()?;
9068 let height: usize = parts.next()?.parse().ok()?;
9069 Some(size(px(width as f32), px(height as f32)))
9070}
9071
9072/// Add client-side decorations (rounded corners, shadows, resize handling) when
9073/// appropriate.
9074///
9075/// The `border_radius_tiling` parameter allows overriding which corners get
9076/// rounded, independently of the actual window tiling state. This is used
9077/// specifically for the workspace switcher sidebar: when the sidebar is open,
9078/// we want square corners on the left (so the sidebar appears flush with the
9079/// window edge) but we still need the shadow padding for proper visual
9080/// appearance. Unlike actual window tiling, this only affects border radius -
9081/// not padding or shadows.
9082pub fn client_side_decorations(
9083 element: impl IntoElement,
9084 window: &mut Window,
9085 cx: &mut App,
9086 border_radius_tiling: Tiling,
9087) -> Stateful<Div> {
9088 const BORDER_SIZE: Pixels = px(1.0);
9089 let decorations = window.window_decorations();
9090 let tiling = match decorations {
9091 Decorations::Server => Tiling::default(),
9092 Decorations::Client { tiling } => tiling,
9093 };
9094
9095 match decorations {
9096 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9097 Decorations::Server => window.set_client_inset(px(0.0)),
9098 }
9099
9100 struct GlobalResizeEdge(ResizeEdge);
9101 impl Global for GlobalResizeEdge {}
9102
9103 div()
9104 .id("window-backdrop")
9105 .bg(transparent_black())
9106 .map(|div| match decorations {
9107 Decorations::Server => div,
9108 Decorations::Client { .. } => div
9109 .when(
9110 !(tiling.top
9111 || tiling.right
9112 || border_radius_tiling.top
9113 || border_radius_tiling.right),
9114 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9115 )
9116 .when(
9117 !(tiling.top
9118 || tiling.left
9119 || border_radius_tiling.top
9120 || border_radius_tiling.left),
9121 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9122 )
9123 .when(
9124 !(tiling.bottom
9125 || tiling.right
9126 || border_radius_tiling.bottom
9127 || border_radius_tiling.right),
9128 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9129 )
9130 .when(
9131 !(tiling.bottom
9132 || tiling.left
9133 || border_radius_tiling.bottom
9134 || border_radius_tiling.left),
9135 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9136 )
9137 .when(!tiling.top, |div| {
9138 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9139 })
9140 .when(!tiling.bottom, |div| {
9141 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9142 })
9143 .when(!tiling.left, |div| {
9144 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9145 })
9146 .when(!tiling.right, |div| {
9147 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9148 })
9149 .on_mouse_move(move |e, window, cx| {
9150 let size = window.window_bounds().get_bounds().size;
9151 let pos = e.position;
9152
9153 let new_edge =
9154 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
9155
9156 let edge = cx.try_global::<GlobalResizeEdge>();
9157 if new_edge != edge.map(|edge| edge.0) {
9158 window
9159 .window_handle()
9160 .update(cx, |workspace, _, cx| {
9161 cx.notify(workspace.entity_id());
9162 })
9163 .ok();
9164 }
9165 })
9166 .on_mouse_down(MouseButton::Left, move |e, window, _| {
9167 let size = window.window_bounds().get_bounds().size;
9168 let pos = e.position;
9169
9170 let edge = match resize_edge(
9171 pos,
9172 theme::CLIENT_SIDE_DECORATION_SHADOW,
9173 size,
9174 tiling,
9175 ) {
9176 Some(value) => value,
9177 None => return,
9178 };
9179
9180 window.start_window_resize(edge);
9181 }),
9182 })
9183 .size_full()
9184 .child(
9185 div()
9186 .cursor(CursorStyle::Arrow)
9187 .map(|div| match decorations {
9188 Decorations::Server => div,
9189 Decorations::Client { .. } => div
9190 .border_color(cx.theme().colors().border)
9191 .when(
9192 !(tiling.top
9193 || tiling.right
9194 || border_radius_tiling.top
9195 || border_radius_tiling.right),
9196 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9197 )
9198 .when(
9199 !(tiling.top
9200 || tiling.left
9201 || border_radius_tiling.top
9202 || border_radius_tiling.left),
9203 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9204 )
9205 .when(
9206 !(tiling.bottom
9207 || tiling.right
9208 || border_radius_tiling.bottom
9209 || border_radius_tiling.right),
9210 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9211 )
9212 .when(
9213 !(tiling.bottom
9214 || tiling.left
9215 || border_radius_tiling.bottom
9216 || border_radius_tiling.left),
9217 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9218 )
9219 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
9220 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
9221 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
9222 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
9223 .when(!tiling.is_tiled(), |div| {
9224 div.shadow(vec![gpui::BoxShadow {
9225 color: Hsla {
9226 h: 0.,
9227 s: 0.,
9228 l: 0.,
9229 a: 0.4,
9230 },
9231 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
9232 spread_radius: px(0.),
9233 offset: point(px(0.0), px(0.0)),
9234 }])
9235 }),
9236 })
9237 .on_mouse_move(|_e, _, cx| {
9238 cx.stop_propagation();
9239 })
9240 .size_full()
9241 .child(element),
9242 )
9243 .map(|div| match decorations {
9244 Decorations::Server => div,
9245 Decorations::Client { tiling, .. } => div.child(
9246 canvas(
9247 |_bounds, window, _| {
9248 window.insert_hitbox(
9249 Bounds::new(
9250 point(px(0.0), px(0.0)),
9251 window.window_bounds().get_bounds().size,
9252 ),
9253 HitboxBehavior::Normal,
9254 )
9255 },
9256 move |_bounds, hitbox, window, cx| {
9257 let mouse = window.mouse_position();
9258 let size = window.window_bounds().get_bounds().size;
9259 let Some(edge) =
9260 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
9261 else {
9262 return;
9263 };
9264 cx.set_global(GlobalResizeEdge(edge));
9265 window.set_cursor_style(
9266 match edge {
9267 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
9268 ResizeEdge::Left | ResizeEdge::Right => {
9269 CursorStyle::ResizeLeftRight
9270 }
9271 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
9272 CursorStyle::ResizeUpLeftDownRight
9273 }
9274 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
9275 CursorStyle::ResizeUpRightDownLeft
9276 }
9277 },
9278 &hitbox,
9279 );
9280 },
9281 )
9282 .size_full()
9283 .absolute(),
9284 ),
9285 })
9286}
9287
9288fn resize_edge(
9289 pos: Point<Pixels>,
9290 shadow_size: Pixels,
9291 window_size: Size<Pixels>,
9292 tiling: Tiling,
9293) -> Option<ResizeEdge> {
9294 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
9295 if bounds.contains(&pos) {
9296 return None;
9297 }
9298
9299 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
9300 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
9301 if !tiling.top && top_left_bounds.contains(&pos) {
9302 return Some(ResizeEdge::TopLeft);
9303 }
9304
9305 let top_right_bounds = Bounds::new(
9306 Point::new(window_size.width - corner_size.width, px(0.)),
9307 corner_size,
9308 );
9309 if !tiling.top && top_right_bounds.contains(&pos) {
9310 return Some(ResizeEdge::TopRight);
9311 }
9312
9313 let bottom_left_bounds = Bounds::new(
9314 Point::new(px(0.), window_size.height - corner_size.height),
9315 corner_size,
9316 );
9317 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
9318 return Some(ResizeEdge::BottomLeft);
9319 }
9320
9321 let bottom_right_bounds = Bounds::new(
9322 Point::new(
9323 window_size.width - corner_size.width,
9324 window_size.height - corner_size.height,
9325 ),
9326 corner_size,
9327 );
9328 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
9329 return Some(ResizeEdge::BottomRight);
9330 }
9331
9332 if !tiling.top && pos.y < shadow_size {
9333 Some(ResizeEdge::Top)
9334 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
9335 Some(ResizeEdge::Bottom)
9336 } else if !tiling.left && pos.x < shadow_size {
9337 Some(ResizeEdge::Left)
9338 } else if !tiling.right && pos.x > window_size.width - shadow_size {
9339 Some(ResizeEdge::Right)
9340 } else {
9341 None
9342 }
9343}
9344
9345fn join_pane_into_active(
9346 active_pane: &Entity<Pane>,
9347 pane: &Entity<Pane>,
9348 window: &mut Window,
9349 cx: &mut App,
9350) {
9351 if pane == active_pane {
9352 } else if pane.read(cx).items_len() == 0 {
9353 pane.update(cx, |_, cx| {
9354 cx.emit(pane::Event::Remove {
9355 focus_on_pane: None,
9356 });
9357 })
9358 } else {
9359 move_all_items(pane, active_pane, window, cx);
9360 }
9361}
9362
9363fn move_all_items(
9364 from_pane: &Entity<Pane>,
9365 to_pane: &Entity<Pane>,
9366 window: &mut Window,
9367 cx: &mut App,
9368) {
9369 let destination_is_different = from_pane != to_pane;
9370 let mut moved_items = 0;
9371 for (item_ix, item_handle) in from_pane
9372 .read(cx)
9373 .items()
9374 .enumerate()
9375 .map(|(ix, item)| (ix, item.clone()))
9376 .collect::<Vec<_>>()
9377 {
9378 let ix = item_ix - moved_items;
9379 if destination_is_different {
9380 // Close item from previous pane
9381 from_pane.update(cx, |source, cx| {
9382 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
9383 });
9384 moved_items += 1;
9385 }
9386
9387 // This automatically removes duplicate items in the pane
9388 to_pane.update(cx, |destination, cx| {
9389 destination.add_item(item_handle, true, true, None, window, cx);
9390 window.focus(&destination.focus_handle(cx), cx)
9391 });
9392 }
9393}
9394
9395pub fn move_item(
9396 source: &Entity<Pane>,
9397 destination: &Entity<Pane>,
9398 item_id_to_move: EntityId,
9399 destination_index: usize,
9400 activate: bool,
9401 window: &mut Window,
9402 cx: &mut App,
9403) {
9404 let Some((item_ix, item_handle)) = source
9405 .read(cx)
9406 .items()
9407 .enumerate()
9408 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
9409 .map(|(ix, item)| (ix, item.clone()))
9410 else {
9411 // Tab was closed during drag
9412 return;
9413 };
9414
9415 if source != destination {
9416 // Close item from previous pane
9417 source.update(cx, |source, cx| {
9418 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
9419 });
9420 }
9421
9422 // This automatically removes duplicate items in the pane
9423 destination.update(cx, |destination, cx| {
9424 destination.add_item_inner(
9425 item_handle,
9426 activate,
9427 activate,
9428 activate,
9429 Some(destination_index),
9430 window,
9431 cx,
9432 );
9433 if activate {
9434 window.focus(&destination.focus_handle(cx), cx)
9435 }
9436 });
9437}
9438
9439pub fn move_active_item(
9440 source: &Entity<Pane>,
9441 destination: &Entity<Pane>,
9442 focus_destination: bool,
9443 close_if_empty: bool,
9444 window: &mut Window,
9445 cx: &mut App,
9446) {
9447 if source == destination {
9448 return;
9449 }
9450 let Some(active_item) = source.read(cx).active_item() else {
9451 return;
9452 };
9453 source.update(cx, |source_pane, cx| {
9454 let item_id = active_item.item_id();
9455 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
9456 destination.update(cx, |target_pane, cx| {
9457 target_pane.add_item(
9458 active_item,
9459 focus_destination,
9460 focus_destination,
9461 Some(target_pane.items_len()),
9462 window,
9463 cx,
9464 );
9465 });
9466 });
9467}
9468
9469pub fn clone_active_item(
9470 workspace_id: Option<WorkspaceId>,
9471 source: &Entity<Pane>,
9472 destination: &Entity<Pane>,
9473 focus_destination: bool,
9474 window: &mut Window,
9475 cx: &mut App,
9476) {
9477 if source == destination {
9478 return;
9479 }
9480 let Some(active_item) = source.read(cx).active_item() else {
9481 return;
9482 };
9483 if !active_item.can_split(cx) {
9484 return;
9485 }
9486 let destination = destination.downgrade();
9487 let task = active_item.clone_on_split(workspace_id, window, cx);
9488 window
9489 .spawn(cx, async move |cx| {
9490 let Some(clone) = task.await else {
9491 return;
9492 };
9493 destination
9494 .update_in(cx, |target_pane, window, cx| {
9495 target_pane.add_item(
9496 clone,
9497 focus_destination,
9498 focus_destination,
9499 Some(target_pane.items_len()),
9500 window,
9501 cx,
9502 );
9503 })
9504 .log_err();
9505 })
9506 .detach();
9507}
9508
9509#[derive(Debug)]
9510pub struct WorkspacePosition {
9511 pub window_bounds: Option<WindowBounds>,
9512 pub display: Option<Uuid>,
9513 pub centered_layout: bool,
9514}
9515
9516pub fn remote_workspace_position_from_db(
9517 connection_options: RemoteConnectionOptions,
9518 paths_to_open: &[PathBuf],
9519 cx: &App,
9520) -> Task<Result<WorkspacePosition>> {
9521 let paths = paths_to_open.to_vec();
9522
9523 cx.background_spawn(async move {
9524 let remote_connection_id = persistence::DB
9525 .get_or_create_remote_connection(connection_options)
9526 .await
9527 .context("fetching serialized ssh project")?;
9528 let serialized_workspace =
9529 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
9530
9531 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
9532 (Some(WindowBounds::Windowed(bounds)), None)
9533 } else {
9534 let restorable_bounds = serialized_workspace
9535 .as_ref()
9536 .and_then(|workspace| {
9537 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
9538 })
9539 .or_else(|| persistence::read_default_window_bounds());
9540
9541 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
9542 (Some(serialized_bounds), Some(serialized_display))
9543 } else {
9544 (None, None)
9545 }
9546 };
9547
9548 let centered_layout = serialized_workspace
9549 .as_ref()
9550 .map(|w| w.centered_layout)
9551 .unwrap_or(false);
9552
9553 Ok(WorkspacePosition {
9554 window_bounds,
9555 display,
9556 centered_layout,
9557 })
9558 })
9559}
9560
9561pub fn with_active_or_new_workspace(
9562 cx: &mut App,
9563 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
9564) {
9565 match cx
9566 .active_window()
9567 .and_then(|w| w.downcast::<MultiWorkspace>())
9568 {
9569 Some(multi_workspace) => {
9570 cx.defer(move |cx| {
9571 multi_workspace
9572 .update(cx, |multi_workspace, window, cx| {
9573 let workspace = multi_workspace.workspace().clone();
9574 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
9575 })
9576 .log_err();
9577 });
9578 }
9579 None => {
9580 let app_state = AppState::global(cx);
9581 if let Some(app_state) = app_state.upgrade() {
9582 open_new(
9583 OpenOptions::default(),
9584 app_state,
9585 cx,
9586 move |workspace, window, cx| f(workspace, window, cx),
9587 )
9588 .detach_and_log_err(cx);
9589 }
9590 }
9591 }
9592}
9593
9594#[cfg(test)]
9595mod tests {
9596 use std::{cell::RefCell, rc::Rc};
9597
9598 use super::*;
9599 use crate::{
9600 dock::{PanelEvent, test::TestPanel},
9601 item::{
9602 ItemBufferKind, ItemEvent,
9603 test::{TestItem, TestProjectItem},
9604 },
9605 };
9606 use fs::FakeFs;
9607 use gpui::{
9608 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
9609 UpdateGlobal, VisualTestContext, px,
9610 };
9611 use project::{Project, ProjectEntryId};
9612 use serde_json::json;
9613 use settings::SettingsStore;
9614 use util::rel_path::rel_path;
9615
9616 #[gpui::test]
9617 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
9618 init_test(cx);
9619
9620 let fs = FakeFs::new(cx.executor());
9621 let project = Project::test(fs, [], cx).await;
9622 let (workspace, cx) =
9623 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9624
9625 // Adding an item with no ambiguity renders the tab without detail.
9626 let item1 = cx.new(|cx| {
9627 let mut item = TestItem::new(cx);
9628 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
9629 item
9630 });
9631 workspace.update_in(cx, |workspace, window, cx| {
9632 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
9633 });
9634 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
9635
9636 // Adding an item that creates ambiguity increases the level of detail on
9637 // both tabs.
9638 let item2 = cx.new_window_entity(|_window, cx| {
9639 let mut item = TestItem::new(cx);
9640 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
9641 item
9642 });
9643 workspace.update_in(cx, |workspace, window, cx| {
9644 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
9645 });
9646 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
9647 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
9648
9649 // Adding an item that creates ambiguity increases the level of detail only
9650 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
9651 // we stop at the highest detail available.
9652 let item3 = cx.new(|cx| {
9653 let mut item = TestItem::new(cx);
9654 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
9655 item
9656 });
9657 workspace.update_in(cx, |workspace, window, cx| {
9658 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
9659 });
9660 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
9661 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
9662 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
9663 }
9664
9665 #[gpui::test]
9666 async fn test_tracking_active_path(cx: &mut TestAppContext) {
9667 init_test(cx);
9668
9669 let fs = FakeFs::new(cx.executor());
9670 fs.insert_tree(
9671 "/root1",
9672 json!({
9673 "one.txt": "",
9674 "two.txt": "",
9675 }),
9676 )
9677 .await;
9678 fs.insert_tree(
9679 "/root2",
9680 json!({
9681 "three.txt": "",
9682 }),
9683 )
9684 .await;
9685
9686 let project = Project::test(fs, ["root1".as_ref()], cx).await;
9687 let (workspace, cx) =
9688 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9689 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9690 let worktree_id = project.update(cx, |project, cx| {
9691 project.worktrees(cx).next().unwrap().read(cx).id()
9692 });
9693
9694 let item1 = cx.new(|cx| {
9695 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
9696 });
9697 let item2 = cx.new(|cx| {
9698 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
9699 });
9700
9701 // Add an item to an empty pane
9702 workspace.update_in(cx, |workspace, window, cx| {
9703 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
9704 });
9705 project.update(cx, |project, cx| {
9706 assert_eq!(
9707 project.active_entry(),
9708 project
9709 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
9710 .map(|e| e.id)
9711 );
9712 });
9713 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
9714
9715 // Add a second item to a non-empty pane
9716 workspace.update_in(cx, |workspace, window, cx| {
9717 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
9718 });
9719 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
9720 project.update(cx, |project, cx| {
9721 assert_eq!(
9722 project.active_entry(),
9723 project
9724 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
9725 .map(|e| e.id)
9726 );
9727 });
9728
9729 // Close the active item
9730 pane.update_in(cx, |pane, window, cx| {
9731 pane.close_active_item(&Default::default(), window, cx)
9732 })
9733 .await
9734 .unwrap();
9735 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
9736 project.update(cx, |project, cx| {
9737 assert_eq!(
9738 project.active_entry(),
9739 project
9740 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
9741 .map(|e| e.id)
9742 );
9743 });
9744
9745 // Add a project folder
9746 project
9747 .update(cx, |project, cx| {
9748 project.find_or_create_worktree("root2", true, cx)
9749 })
9750 .await
9751 .unwrap();
9752 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
9753
9754 // Remove a project folder
9755 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
9756 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
9757 }
9758
9759 #[gpui::test]
9760 async fn test_close_window(cx: &mut TestAppContext) {
9761 init_test(cx);
9762
9763 let fs = FakeFs::new(cx.executor());
9764 fs.insert_tree("/root", json!({ "one": "" })).await;
9765
9766 let project = Project::test(fs, ["root".as_ref()], cx).await;
9767 let (workspace, cx) =
9768 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9769
9770 // When there are no dirty items, there's nothing to do.
9771 let item1 = cx.new(TestItem::new);
9772 workspace.update_in(cx, |w, window, cx| {
9773 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
9774 });
9775 let task = workspace.update_in(cx, |w, window, cx| {
9776 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
9777 });
9778 assert!(task.await.unwrap());
9779
9780 // When there are dirty untitled items, prompt to save each one. If the user
9781 // cancels any prompt, then abort.
9782 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
9783 let item3 = cx.new(|cx| {
9784 TestItem::new(cx)
9785 .with_dirty(true)
9786 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
9787 });
9788 workspace.update_in(cx, |w, window, cx| {
9789 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
9790 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
9791 });
9792 let task = workspace.update_in(cx, |w, window, cx| {
9793 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
9794 });
9795 cx.executor().run_until_parked();
9796 cx.simulate_prompt_answer("Cancel"); // cancel save all
9797 cx.executor().run_until_parked();
9798 assert!(!cx.has_pending_prompt());
9799 assert!(!task.await.unwrap());
9800 }
9801
9802 #[gpui::test]
9803 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
9804 init_test(cx);
9805
9806 // Register TestItem as a serializable item
9807 cx.update(|cx| {
9808 register_serializable_item::<TestItem>(cx);
9809 });
9810
9811 let fs = FakeFs::new(cx.executor());
9812 fs.insert_tree("/root", json!({ "one": "" })).await;
9813
9814 let project = Project::test(fs, ["root".as_ref()], cx).await;
9815 let (workspace, cx) =
9816 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9817
9818 // When there are dirty untitled items, but they can serialize, then there is no prompt.
9819 let item1 = cx.new(|cx| {
9820 TestItem::new(cx)
9821 .with_dirty(true)
9822 .with_serialize(|| Some(Task::ready(Ok(()))))
9823 });
9824 let item2 = cx.new(|cx| {
9825 TestItem::new(cx)
9826 .with_dirty(true)
9827 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
9828 .with_serialize(|| Some(Task::ready(Ok(()))))
9829 });
9830 workspace.update_in(cx, |w, window, cx| {
9831 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
9832 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
9833 });
9834 let task = workspace.update_in(cx, |w, window, cx| {
9835 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
9836 });
9837 assert!(task.await.unwrap());
9838 }
9839
9840 #[gpui::test]
9841 async fn test_close_pane_items(cx: &mut TestAppContext) {
9842 init_test(cx);
9843
9844 let fs = FakeFs::new(cx.executor());
9845
9846 let project = Project::test(fs, None, cx).await;
9847 let (workspace, cx) =
9848 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9849
9850 let item1 = cx.new(|cx| {
9851 TestItem::new(cx)
9852 .with_dirty(true)
9853 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
9854 });
9855 let item2 = cx.new(|cx| {
9856 TestItem::new(cx)
9857 .with_dirty(true)
9858 .with_conflict(true)
9859 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
9860 });
9861 let item3 = cx.new(|cx| {
9862 TestItem::new(cx)
9863 .with_dirty(true)
9864 .with_conflict(true)
9865 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
9866 });
9867 let item4 = cx.new(|cx| {
9868 TestItem::new(cx).with_dirty(true).with_project_items(&[{
9869 let project_item = TestProjectItem::new_untitled(cx);
9870 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
9871 project_item
9872 }])
9873 });
9874 let pane = workspace.update_in(cx, |workspace, window, cx| {
9875 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
9876 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
9877 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
9878 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
9879 workspace.active_pane().clone()
9880 });
9881
9882 let close_items = pane.update_in(cx, |pane, window, cx| {
9883 pane.activate_item(1, true, true, window, cx);
9884 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
9885 let item1_id = item1.item_id();
9886 let item3_id = item3.item_id();
9887 let item4_id = item4.item_id();
9888 pane.close_items(window, cx, SaveIntent::Close, move |id| {
9889 [item1_id, item3_id, item4_id].contains(&id)
9890 })
9891 });
9892 cx.executor().run_until_parked();
9893
9894 assert!(cx.has_pending_prompt());
9895 cx.simulate_prompt_answer("Save all");
9896
9897 cx.executor().run_until_parked();
9898
9899 // Item 1 is saved. There's a prompt to save item 3.
9900 pane.update(cx, |pane, cx| {
9901 assert_eq!(item1.read(cx).save_count, 1);
9902 assert_eq!(item1.read(cx).save_as_count, 0);
9903 assert_eq!(item1.read(cx).reload_count, 0);
9904 assert_eq!(pane.items_len(), 3);
9905 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
9906 });
9907 assert!(cx.has_pending_prompt());
9908
9909 // Cancel saving item 3.
9910 cx.simulate_prompt_answer("Discard");
9911 cx.executor().run_until_parked();
9912
9913 // Item 3 is reloaded. There's a prompt to save item 4.
9914 pane.update(cx, |pane, cx| {
9915 assert_eq!(item3.read(cx).save_count, 0);
9916 assert_eq!(item3.read(cx).save_as_count, 0);
9917 assert_eq!(item3.read(cx).reload_count, 1);
9918 assert_eq!(pane.items_len(), 2);
9919 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
9920 });
9921
9922 // There's a prompt for a path for item 4.
9923 cx.simulate_new_path_selection(|_| Some(Default::default()));
9924 close_items.await.unwrap();
9925
9926 // The requested items are closed.
9927 pane.update(cx, |pane, cx| {
9928 assert_eq!(item4.read(cx).save_count, 0);
9929 assert_eq!(item4.read(cx).save_as_count, 1);
9930 assert_eq!(item4.read(cx).reload_count, 0);
9931 assert_eq!(pane.items_len(), 1);
9932 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
9933 });
9934 }
9935
9936 #[gpui::test]
9937 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
9938 init_test(cx);
9939
9940 let fs = FakeFs::new(cx.executor());
9941 let project = Project::test(fs, [], cx).await;
9942 let (workspace, cx) =
9943 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9944
9945 // Create several workspace items with single project entries, and two
9946 // workspace items with multiple project entries.
9947 let single_entry_items = (0..=4)
9948 .map(|project_entry_id| {
9949 cx.new(|cx| {
9950 TestItem::new(cx)
9951 .with_dirty(true)
9952 .with_project_items(&[dirty_project_item(
9953 project_entry_id,
9954 &format!("{project_entry_id}.txt"),
9955 cx,
9956 )])
9957 })
9958 })
9959 .collect::<Vec<_>>();
9960 let item_2_3 = cx.new(|cx| {
9961 TestItem::new(cx)
9962 .with_dirty(true)
9963 .with_buffer_kind(ItemBufferKind::Multibuffer)
9964 .with_project_items(&[
9965 single_entry_items[2].read(cx).project_items[0].clone(),
9966 single_entry_items[3].read(cx).project_items[0].clone(),
9967 ])
9968 });
9969 let item_3_4 = cx.new(|cx| {
9970 TestItem::new(cx)
9971 .with_dirty(true)
9972 .with_buffer_kind(ItemBufferKind::Multibuffer)
9973 .with_project_items(&[
9974 single_entry_items[3].read(cx).project_items[0].clone(),
9975 single_entry_items[4].read(cx).project_items[0].clone(),
9976 ])
9977 });
9978
9979 // Create two panes that contain the following project entries:
9980 // left pane:
9981 // multi-entry items: (2, 3)
9982 // single-entry items: 0, 2, 3, 4
9983 // right pane:
9984 // single-entry items: 4, 1
9985 // multi-entry items: (3, 4)
9986 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
9987 let left_pane = workspace.active_pane().clone();
9988 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
9989 workspace.add_item_to_active_pane(
9990 single_entry_items[0].boxed_clone(),
9991 None,
9992 true,
9993 window,
9994 cx,
9995 );
9996 workspace.add_item_to_active_pane(
9997 single_entry_items[2].boxed_clone(),
9998 None,
9999 true,
10000 window,
10001 cx,
10002 );
10003 workspace.add_item_to_active_pane(
10004 single_entry_items[3].boxed_clone(),
10005 None,
10006 true,
10007 window,
10008 cx,
10009 );
10010 workspace.add_item_to_active_pane(
10011 single_entry_items[4].boxed_clone(),
10012 None,
10013 true,
10014 window,
10015 cx,
10016 );
10017
10018 let right_pane =
10019 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10020
10021 let boxed_clone = single_entry_items[1].boxed_clone();
10022 let right_pane = window.spawn(cx, async move |cx| {
10023 right_pane.await.inspect(|right_pane| {
10024 right_pane
10025 .update_in(cx, |pane, window, cx| {
10026 pane.add_item(boxed_clone, true, true, None, window, cx);
10027 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10028 })
10029 .unwrap();
10030 })
10031 });
10032
10033 (left_pane, right_pane)
10034 });
10035 let right_pane = right_pane.await.unwrap();
10036 cx.focus(&right_pane);
10037
10038 let close = right_pane.update_in(cx, |pane, window, cx| {
10039 pane.close_all_items(&CloseAllItems::default(), window, cx)
10040 .unwrap()
10041 });
10042 cx.executor().run_until_parked();
10043
10044 let msg = cx.pending_prompt().unwrap().0;
10045 assert!(msg.contains("1.txt"));
10046 assert!(!msg.contains("2.txt"));
10047 assert!(!msg.contains("3.txt"));
10048 assert!(!msg.contains("4.txt"));
10049
10050 // With best-effort close, cancelling item 1 keeps it open but items 4
10051 // and (3,4) still close since their entries exist in left pane.
10052 cx.simulate_prompt_answer("Cancel");
10053 close.await;
10054
10055 right_pane.read_with(cx, |pane, _| {
10056 assert_eq!(pane.items_len(), 1);
10057 });
10058
10059 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10060 left_pane
10061 .update_in(cx, |left_pane, window, cx| {
10062 left_pane.close_item_by_id(
10063 single_entry_items[3].entity_id(),
10064 SaveIntent::Skip,
10065 window,
10066 cx,
10067 )
10068 })
10069 .await
10070 .unwrap();
10071
10072 let close = left_pane.update_in(cx, |pane, window, cx| {
10073 pane.close_all_items(&CloseAllItems::default(), window, cx)
10074 .unwrap()
10075 });
10076 cx.executor().run_until_parked();
10077
10078 let details = cx.pending_prompt().unwrap().1;
10079 assert!(details.contains("0.txt"));
10080 assert!(details.contains("3.txt"));
10081 assert!(details.contains("4.txt"));
10082 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10083 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10084 // assert!(!details.contains("2.txt"));
10085
10086 cx.simulate_prompt_answer("Save all");
10087 cx.executor().run_until_parked();
10088 close.await;
10089
10090 left_pane.read_with(cx, |pane, _| {
10091 assert_eq!(pane.items_len(), 0);
10092 });
10093 }
10094
10095 #[gpui::test]
10096 async fn test_autosave(cx: &mut gpui::TestAppContext) {
10097 init_test(cx);
10098
10099 let fs = FakeFs::new(cx.executor());
10100 let project = Project::test(fs, [], cx).await;
10101 let (workspace, cx) =
10102 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10103 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10104
10105 let item = cx.new(|cx| {
10106 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10107 });
10108 let item_id = item.entity_id();
10109 workspace.update_in(cx, |workspace, window, cx| {
10110 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10111 });
10112
10113 // Autosave on window change.
10114 item.update(cx, |item, cx| {
10115 SettingsStore::update_global(cx, |settings, cx| {
10116 settings.update_user_settings(cx, |settings| {
10117 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10118 })
10119 });
10120 item.is_dirty = true;
10121 });
10122
10123 // Deactivating the window saves the file.
10124 cx.deactivate_window();
10125 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10126
10127 // Re-activating the window doesn't save the file.
10128 cx.update(|window, _| window.activate_window());
10129 cx.executor().run_until_parked();
10130 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10131
10132 // Autosave on focus change.
10133 item.update_in(cx, |item, window, cx| {
10134 cx.focus_self(window);
10135 SettingsStore::update_global(cx, |settings, cx| {
10136 settings.update_user_settings(cx, |settings| {
10137 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10138 })
10139 });
10140 item.is_dirty = true;
10141 });
10142 // Blurring the item saves the file.
10143 item.update_in(cx, |_, window, _| window.blur());
10144 cx.executor().run_until_parked();
10145 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10146
10147 // Deactivating the window still saves the file.
10148 item.update_in(cx, |item, window, cx| {
10149 cx.focus_self(window);
10150 item.is_dirty = true;
10151 });
10152 cx.deactivate_window();
10153 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10154
10155 // Autosave after delay.
10156 item.update(cx, |item, cx| {
10157 SettingsStore::update_global(cx, |settings, cx| {
10158 settings.update_user_settings(cx, |settings| {
10159 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10160 milliseconds: 500.into(),
10161 });
10162 })
10163 });
10164 item.is_dirty = true;
10165 cx.emit(ItemEvent::Edit);
10166 });
10167
10168 // Delay hasn't fully expired, so the file is still dirty and unsaved.
10169 cx.executor().advance_clock(Duration::from_millis(250));
10170 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10171
10172 // After delay expires, the file is saved.
10173 cx.executor().advance_clock(Duration::from_millis(250));
10174 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10175
10176 // Autosave after delay, should save earlier than delay if tab is closed
10177 item.update(cx, |item, cx| {
10178 item.is_dirty = true;
10179 cx.emit(ItemEvent::Edit);
10180 });
10181 cx.executor().advance_clock(Duration::from_millis(250));
10182 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10183
10184 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10185 pane.update_in(cx, |pane, window, cx| {
10186 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
10187 })
10188 .await
10189 .unwrap();
10190 assert!(!cx.has_pending_prompt());
10191 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10192
10193 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10194 workspace.update_in(cx, |workspace, window, cx| {
10195 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10196 });
10197 item.update_in(cx, |item, _window, cx| {
10198 item.is_dirty = true;
10199 for project_item in &mut item.project_items {
10200 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10201 }
10202 });
10203 cx.run_until_parked();
10204 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10205
10206 // Autosave on focus change, ensuring closing the tab counts as such.
10207 item.update(cx, |item, cx| {
10208 SettingsStore::update_global(cx, |settings, cx| {
10209 settings.update_user_settings(cx, |settings| {
10210 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10211 })
10212 });
10213 item.is_dirty = true;
10214 for project_item in &mut item.project_items {
10215 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10216 }
10217 });
10218
10219 pane.update_in(cx, |pane, window, cx| {
10220 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
10221 })
10222 .await
10223 .unwrap();
10224 assert!(!cx.has_pending_prompt());
10225 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10226
10227 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10228 workspace.update_in(cx, |workspace, window, cx| {
10229 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10230 });
10231 item.update_in(cx, |item, window, cx| {
10232 item.project_items[0].update(cx, |item, _| {
10233 item.entry_id = None;
10234 });
10235 item.is_dirty = true;
10236 window.blur();
10237 });
10238 cx.run_until_parked();
10239 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10240
10241 // Ensure autosave is prevented for deleted files also when closing the buffer.
10242 let _close_items = pane.update_in(cx, |pane, window, cx| {
10243 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
10244 });
10245 cx.run_until_parked();
10246 assert!(cx.has_pending_prompt());
10247 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10248 }
10249
10250 #[gpui::test]
10251 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10252 init_test(cx);
10253
10254 let fs = FakeFs::new(cx.executor());
10255
10256 let project = Project::test(fs, [], cx).await;
10257 let (workspace, cx) =
10258 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10259
10260 let item = cx.new(|cx| {
10261 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10262 });
10263 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10264 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10265 let toolbar_notify_count = Rc::new(RefCell::new(0));
10266
10267 workspace.update_in(cx, |workspace, window, cx| {
10268 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10269 let toolbar_notification_count = toolbar_notify_count.clone();
10270 cx.observe_in(&toolbar, window, move |_, _, _, _| {
10271 *toolbar_notification_count.borrow_mut() += 1
10272 })
10273 .detach();
10274 });
10275
10276 pane.read_with(cx, |pane, _| {
10277 assert!(!pane.can_navigate_backward());
10278 assert!(!pane.can_navigate_forward());
10279 });
10280
10281 item.update_in(cx, |item, _, cx| {
10282 item.set_state("one".to_string(), cx);
10283 });
10284
10285 // Toolbar must be notified to re-render the navigation buttons
10286 assert_eq!(*toolbar_notify_count.borrow(), 1);
10287
10288 pane.read_with(cx, |pane, _| {
10289 assert!(pane.can_navigate_backward());
10290 assert!(!pane.can_navigate_forward());
10291 });
10292
10293 workspace
10294 .update_in(cx, |workspace, window, cx| {
10295 workspace.go_back(pane.downgrade(), window, cx)
10296 })
10297 .await
10298 .unwrap();
10299
10300 assert_eq!(*toolbar_notify_count.borrow(), 2);
10301 pane.read_with(cx, |pane, _| {
10302 assert!(!pane.can_navigate_backward());
10303 assert!(pane.can_navigate_forward());
10304 });
10305 }
10306
10307 #[gpui::test]
10308 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
10309 init_test(cx);
10310 let fs = FakeFs::new(cx.executor());
10311
10312 let project = Project::test(fs, [], cx).await;
10313 let (workspace, cx) =
10314 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10315
10316 let panel = workspace.update_in(cx, |workspace, window, cx| {
10317 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10318 workspace.add_panel(panel.clone(), window, cx);
10319
10320 workspace
10321 .right_dock()
10322 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10323
10324 panel
10325 });
10326
10327 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10328 pane.update_in(cx, |pane, window, cx| {
10329 let item = cx.new(TestItem::new);
10330 pane.add_item(Box::new(item), true, true, None, window, cx);
10331 });
10332
10333 // Transfer focus from center to panel
10334 workspace.update_in(cx, |workspace, window, cx| {
10335 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10336 });
10337
10338 workspace.update_in(cx, |workspace, window, cx| {
10339 assert!(workspace.right_dock().read(cx).is_open());
10340 assert!(!panel.is_zoomed(window, cx));
10341 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10342 });
10343
10344 // Transfer focus from panel to center
10345 workspace.update_in(cx, |workspace, window, cx| {
10346 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10347 });
10348
10349 workspace.update_in(cx, |workspace, window, cx| {
10350 assert!(workspace.right_dock().read(cx).is_open());
10351 assert!(!panel.is_zoomed(window, cx));
10352 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10353 });
10354
10355 // Close the dock
10356 workspace.update_in(cx, |workspace, window, cx| {
10357 workspace.toggle_dock(DockPosition::Right, window, cx);
10358 });
10359
10360 workspace.update_in(cx, |workspace, window, cx| {
10361 assert!(!workspace.right_dock().read(cx).is_open());
10362 assert!(!panel.is_zoomed(window, cx));
10363 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10364 });
10365
10366 // Open the dock
10367 workspace.update_in(cx, |workspace, window, cx| {
10368 workspace.toggle_dock(DockPosition::Right, window, cx);
10369 });
10370
10371 workspace.update_in(cx, |workspace, window, cx| {
10372 assert!(workspace.right_dock().read(cx).is_open());
10373 assert!(!panel.is_zoomed(window, cx));
10374 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10375 });
10376
10377 // Focus and zoom panel
10378 panel.update_in(cx, |panel, window, cx| {
10379 cx.focus_self(window);
10380 panel.set_zoomed(true, window, cx)
10381 });
10382
10383 workspace.update_in(cx, |workspace, window, cx| {
10384 assert!(workspace.right_dock().read(cx).is_open());
10385 assert!(panel.is_zoomed(window, cx));
10386 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10387 });
10388
10389 // Transfer focus to the center closes the dock
10390 workspace.update_in(cx, |workspace, window, cx| {
10391 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10392 });
10393
10394 workspace.update_in(cx, |workspace, window, cx| {
10395 assert!(!workspace.right_dock().read(cx).is_open());
10396 assert!(panel.is_zoomed(window, cx));
10397 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10398 });
10399
10400 // Transferring focus back to the panel keeps it zoomed
10401 workspace.update_in(cx, |workspace, window, cx| {
10402 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10403 });
10404
10405 workspace.update_in(cx, |workspace, window, cx| {
10406 assert!(workspace.right_dock().read(cx).is_open());
10407 assert!(panel.is_zoomed(window, cx));
10408 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10409 });
10410
10411 // Close the dock while it is zoomed
10412 workspace.update_in(cx, |workspace, window, cx| {
10413 workspace.toggle_dock(DockPosition::Right, window, cx)
10414 });
10415
10416 workspace.update_in(cx, |workspace, window, cx| {
10417 assert!(!workspace.right_dock().read(cx).is_open());
10418 assert!(panel.is_zoomed(window, cx));
10419 assert!(workspace.zoomed.is_none());
10420 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10421 });
10422
10423 // Opening the dock, when it's zoomed, retains focus
10424 workspace.update_in(cx, |workspace, window, cx| {
10425 workspace.toggle_dock(DockPosition::Right, window, cx)
10426 });
10427
10428 workspace.update_in(cx, |workspace, window, cx| {
10429 assert!(workspace.right_dock().read(cx).is_open());
10430 assert!(panel.is_zoomed(window, cx));
10431 assert!(workspace.zoomed.is_some());
10432 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10433 });
10434
10435 // Unzoom and close the panel, zoom the active pane.
10436 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
10437 workspace.update_in(cx, |workspace, window, cx| {
10438 workspace.toggle_dock(DockPosition::Right, window, cx)
10439 });
10440 pane.update_in(cx, |pane, window, cx| {
10441 pane.toggle_zoom(&Default::default(), window, cx)
10442 });
10443
10444 // Opening a dock unzooms the pane.
10445 workspace.update_in(cx, |workspace, window, cx| {
10446 workspace.toggle_dock(DockPosition::Right, window, cx)
10447 });
10448 workspace.update_in(cx, |workspace, window, cx| {
10449 let pane = pane.read(cx);
10450 assert!(!pane.is_zoomed());
10451 assert!(!pane.focus_handle(cx).is_focused(window));
10452 assert!(workspace.right_dock().read(cx).is_open());
10453 assert!(workspace.zoomed.is_none());
10454 });
10455 }
10456
10457 #[gpui::test]
10458 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
10459 init_test(cx);
10460 let fs = FakeFs::new(cx.executor());
10461
10462 let project = Project::test(fs, [], cx).await;
10463 let (workspace, cx) =
10464 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10465
10466 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
10467 workspace.active_pane().clone()
10468 });
10469
10470 // Add an item to the pane so it can be zoomed
10471 workspace.update_in(cx, |workspace, window, cx| {
10472 let item = cx.new(TestItem::new);
10473 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
10474 });
10475
10476 // Initially not zoomed
10477 workspace.update_in(cx, |workspace, _window, cx| {
10478 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
10479 assert!(
10480 workspace.zoomed.is_none(),
10481 "Workspace should track no zoomed pane"
10482 );
10483 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
10484 });
10485
10486 // Zoom In
10487 pane.update_in(cx, |pane, window, cx| {
10488 pane.zoom_in(&crate::ZoomIn, window, cx);
10489 });
10490
10491 workspace.update_in(cx, |workspace, window, cx| {
10492 assert!(
10493 pane.read(cx).is_zoomed(),
10494 "Pane should be zoomed after ZoomIn"
10495 );
10496 assert!(
10497 workspace.zoomed.is_some(),
10498 "Workspace should track the zoomed pane"
10499 );
10500 assert!(
10501 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
10502 "ZoomIn should focus the pane"
10503 );
10504 });
10505
10506 // Zoom In again is a no-op
10507 pane.update_in(cx, |pane, window, cx| {
10508 pane.zoom_in(&crate::ZoomIn, window, cx);
10509 });
10510
10511 workspace.update_in(cx, |workspace, window, cx| {
10512 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
10513 assert!(
10514 workspace.zoomed.is_some(),
10515 "Workspace still tracks zoomed pane"
10516 );
10517 assert!(
10518 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
10519 "Pane remains focused after repeated ZoomIn"
10520 );
10521 });
10522
10523 // Zoom Out
10524 pane.update_in(cx, |pane, window, cx| {
10525 pane.zoom_out(&crate::ZoomOut, window, cx);
10526 });
10527
10528 workspace.update_in(cx, |workspace, _window, cx| {
10529 assert!(
10530 !pane.read(cx).is_zoomed(),
10531 "Pane should unzoom after ZoomOut"
10532 );
10533 assert!(
10534 workspace.zoomed.is_none(),
10535 "Workspace clears zoom tracking after ZoomOut"
10536 );
10537 });
10538
10539 // Zoom Out again is a no-op
10540 pane.update_in(cx, |pane, window, cx| {
10541 pane.zoom_out(&crate::ZoomOut, window, cx);
10542 });
10543
10544 workspace.update_in(cx, |workspace, _window, cx| {
10545 assert!(
10546 !pane.read(cx).is_zoomed(),
10547 "Second ZoomOut keeps pane unzoomed"
10548 );
10549 assert!(
10550 workspace.zoomed.is_none(),
10551 "Workspace remains without zoomed pane"
10552 );
10553 });
10554 }
10555
10556 #[gpui::test]
10557 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
10558 init_test(cx);
10559 let fs = FakeFs::new(cx.executor());
10560
10561 let project = Project::test(fs, [], cx).await;
10562 let (workspace, cx) =
10563 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10564 workspace.update_in(cx, |workspace, window, cx| {
10565 // Open two docks
10566 let left_dock = workspace.dock_at_position(DockPosition::Left);
10567 let right_dock = workspace.dock_at_position(DockPosition::Right);
10568
10569 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10570 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10571
10572 assert!(left_dock.read(cx).is_open());
10573 assert!(right_dock.read(cx).is_open());
10574 });
10575
10576 workspace.update_in(cx, |workspace, window, cx| {
10577 // Toggle all docks - should close both
10578 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10579
10580 let left_dock = workspace.dock_at_position(DockPosition::Left);
10581 let right_dock = workspace.dock_at_position(DockPosition::Right);
10582 assert!(!left_dock.read(cx).is_open());
10583 assert!(!right_dock.read(cx).is_open());
10584 });
10585
10586 workspace.update_in(cx, |workspace, window, cx| {
10587 // Toggle again - should reopen both
10588 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10589
10590 let left_dock = workspace.dock_at_position(DockPosition::Left);
10591 let right_dock = workspace.dock_at_position(DockPosition::Right);
10592 assert!(left_dock.read(cx).is_open());
10593 assert!(right_dock.read(cx).is_open());
10594 });
10595 }
10596
10597 #[gpui::test]
10598 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
10599 init_test(cx);
10600 let fs = FakeFs::new(cx.executor());
10601
10602 let project = Project::test(fs, [], cx).await;
10603 let (workspace, cx) =
10604 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10605 workspace.update_in(cx, |workspace, window, cx| {
10606 // Open two docks
10607 let left_dock = workspace.dock_at_position(DockPosition::Left);
10608 let right_dock = workspace.dock_at_position(DockPosition::Right);
10609
10610 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10611 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10612
10613 assert!(left_dock.read(cx).is_open());
10614 assert!(right_dock.read(cx).is_open());
10615 });
10616
10617 workspace.update_in(cx, |workspace, window, cx| {
10618 // Close them manually
10619 workspace.toggle_dock(DockPosition::Left, window, cx);
10620 workspace.toggle_dock(DockPosition::Right, window, cx);
10621
10622 let left_dock = workspace.dock_at_position(DockPosition::Left);
10623 let right_dock = workspace.dock_at_position(DockPosition::Right);
10624 assert!(!left_dock.read(cx).is_open());
10625 assert!(!right_dock.read(cx).is_open());
10626 });
10627
10628 workspace.update_in(cx, |workspace, window, cx| {
10629 // Toggle all docks - only last closed (right dock) should reopen
10630 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10631
10632 let left_dock = workspace.dock_at_position(DockPosition::Left);
10633 let right_dock = workspace.dock_at_position(DockPosition::Right);
10634 assert!(!left_dock.read(cx).is_open());
10635 assert!(right_dock.read(cx).is_open());
10636 });
10637 }
10638
10639 #[gpui::test]
10640 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
10641 init_test(cx);
10642 let fs = FakeFs::new(cx.executor());
10643 let project = Project::test(fs, [], cx).await;
10644 let (workspace, cx) =
10645 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10646
10647 // Open two docks (left and right) with one panel each
10648 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
10649 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
10650 workspace.add_panel(left_panel.clone(), window, cx);
10651
10652 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
10653 workspace.add_panel(right_panel.clone(), window, cx);
10654
10655 workspace.toggle_dock(DockPosition::Left, window, cx);
10656 workspace.toggle_dock(DockPosition::Right, window, cx);
10657
10658 // Verify initial state
10659 assert!(
10660 workspace.left_dock().read(cx).is_open(),
10661 "Left dock should be open"
10662 );
10663 assert_eq!(
10664 workspace
10665 .left_dock()
10666 .read(cx)
10667 .visible_panel()
10668 .unwrap()
10669 .panel_id(),
10670 left_panel.panel_id(),
10671 "Left panel should be visible in left dock"
10672 );
10673 assert!(
10674 workspace.right_dock().read(cx).is_open(),
10675 "Right dock should be open"
10676 );
10677 assert_eq!(
10678 workspace
10679 .right_dock()
10680 .read(cx)
10681 .visible_panel()
10682 .unwrap()
10683 .panel_id(),
10684 right_panel.panel_id(),
10685 "Right panel should be visible in right dock"
10686 );
10687 assert!(
10688 !workspace.bottom_dock().read(cx).is_open(),
10689 "Bottom dock should be closed"
10690 );
10691
10692 (left_panel, right_panel)
10693 });
10694
10695 // Focus the left panel and move it to the next position (bottom dock)
10696 workspace.update_in(cx, |workspace, window, cx| {
10697 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
10698 assert!(
10699 left_panel.read(cx).focus_handle(cx).is_focused(window),
10700 "Left panel should be focused"
10701 );
10702 });
10703
10704 cx.dispatch_action(MoveFocusedPanelToNextPosition);
10705
10706 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
10707 workspace.update(cx, |workspace, cx| {
10708 assert!(
10709 !workspace.left_dock().read(cx).is_open(),
10710 "Left dock should be closed"
10711 );
10712 assert!(
10713 workspace.bottom_dock().read(cx).is_open(),
10714 "Bottom dock should now be open"
10715 );
10716 assert_eq!(
10717 left_panel.read(cx).position,
10718 DockPosition::Bottom,
10719 "Left panel should now be in the bottom dock"
10720 );
10721 assert_eq!(
10722 workspace
10723 .bottom_dock()
10724 .read(cx)
10725 .visible_panel()
10726 .unwrap()
10727 .panel_id(),
10728 left_panel.panel_id(),
10729 "Left panel should be the visible panel in the bottom dock"
10730 );
10731 });
10732
10733 // Toggle all docks off
10734 workspace.update_in(cx, |workspace, window, cx| {
10735 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10736 assert!(
10737 !workspace.left_dock().read(cx).is_open(),
10738 "Left dock should be closed"
10739 );
10740 assert!(
10741 !workspace.right_dock().read(cx).is_open(),
10742 "Right dock should be closed"
10743 );
10744 assert!(
10745 !workspace.bottom_dock().read(cx).is_open(),
10746 "Bottom dock should be closed"
10747 );
10748 });
10749
10750 // Toggle all docks back on and verify positions are restored
10751 workspace.update_in(cx, |workspace, window, cx| {
10752 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10753 assert!(
10754 !workspace.left_dock().read(cx).is_open(),
10755 "Left dock should remain closed"
10756 );
10757 assert!(
10758 workspace.right_dock().read(cx).is_open(),
10759 "Right dock should remain open"
10760 );
10761 assert!(
10762 workspace.bottom_dock().read(cx).is_open(),
10763 "Bottom dock should remain open"
10764 );
10765 assert_eq!(
10766 left_panel.read(cx).position,
10767 DockPosition::Bottom,
10768 "Left panel should remain in the bottom dock"
10769 );
10770 assert_eq!(
10771 right_panel.read(cx).position,
10772 DockPosition::Right,
10773 "Right panel should remain in the right dock"
10774 );
10775 assert_eq!(
10776 workspace
10777 .bottom_dock()
10778 .read(cx)
10779 .visible_panel()
10780 .unwrap()
10781 .panel_id(),
10782 left_panel.panel_id(),
10783 "Left panel should be the visible panel in the right dock"
10784 );
10785 });
10786 }
10787
10788 #[gpui::test]
10789 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
10790 init_test(cx);
10791
10792 let fs = FakeFs::new(cx.executor());
10793
10794 let project = Project::test(fs, None, cx).await;
10795 let (workspace, cx) =
10796 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10797
10798 // Let's arrange the panes like this:
10799 //
10800 // +-----------------------+
10801 // | top |
10802 // +------+--------+-------+
10803 // | left | center | right |
10804 // +------+--------+-------+
10805 // | bottom |
10806 // +-----------------------+
10807
10808 let top_item = cx.new(|cx| {
10809 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
10810 });
10811 let bottom_item = cx.new(|cx| {
10812 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
10813 });
10814 let left_item = cx.new(|cx| {
10815 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
10816 });
10817 let right_item = cx.new(|cx| {
10818 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
10819 });
10820 let center_item = cx.new(|cx| {
10821 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
10822 });
10823
10824 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10825 let top_pane_id = workspace.active_pane().entity_id();
10826 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
10827 workspace.split_pane(
10828 workspace.active_pane().clone(),
10829 SplitDirection::Down,
10830 window,
10831 cx,
10832 );
10833 top_pane_id
10834 });
10835 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10836 let bottom_pane_id = workspace.active_pane().entity_id();
10837 workspace.add_item_to_active_pane(
10838 Box::new(bottom_item.clone()),
10839 None,
10840 false,
10841 window,
10842 cx,
10843 );
10844 workspace.split_pane(
10845 workspace.active_pane().clone(),
10846 SplitDirection::Up,
10847 window,
10848 cx,
10849 );
10850 bottom_pane_id
10851 });
10852 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10853 let left_pane_id = workspace.active_pane().entity_id();
10854 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
10855 workspace.split_pane(
10856 workspace.active_pane().clone(),
10857 SplitDirection::Right,
10858 window,
10859 cx,
10860 );
10861 left_pane_id
10862 });
10863 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10864 let right_pane_id = workspace.active_pane().entity_id();
10865 workspace.add_item_to_active_pane(
10866 Box::new(right_item.clone()),
10867 None,
10868 false,
10869 window,
10870 cx,
10871 );
10872 workspace.split_pane(
10873 workspace.active_pane().clone(),
10874 SplitDirection::Left,
10875 window,
10876 cx,
10877 );
10878 right_pane_id
10879 });
10880 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10881 let center_pane_id = workspace.active_pane().entity_id();
10882 workspace.add_item_to_active_pane(
10883 Box::new(center_item.clone()),
10884 None,
10885 false,
10886 window,
10887 cx,
10888 );
10889 center_pane_id
10890 });
10891 cx.executor().run_until_parked();
10892
10893 workspace.update_in(cx, |workspace, window, cx| {
10894 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
10895
10896 // Join into next from center pane into right
10897 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10898 });
10899
10900 workspace.update_in(cx, |workspace, window, cx| {
10901 let active_pane = workspace.active_pane();
10902 assert_eq!(right_pane_id, active_pane.entity_id());
10903 assert_eq!(2, active_pane.read(cx).items_len());
10904 let item_ids_in_pane =
10905 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10906 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
10907 assert!(item_ids_in_pane.contains(&right_item.item_id()));
10908
10909 // Join into next from right pane into bottom
10910 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10911 });
10912
10913 workspace.update_in(cx, |workspace, window, cx| {
10914 let active_pane = workspace.active_pane();
10915 assert_eq!(bottom_pane_id, active_pane.entity_id());
10916 assert_eq!(3, active_pane.read(cx).items_len());
10917 let item_ids_in_pane =
10918 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10919 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
10920 assert!(item_ids_in_pane.contains(&right_item.item_id()));
10921 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
10922
10923 // Join into next from bottom pane into left
10924 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10925 });
10926
10927 workspace.update_in(cx, |workspace, window, cx| {
10928 let active_pane = workspace.active_pane();
10929 assert_eq!(left_pane_id, active_pane.entity_id());
10930 assert_eq!(4, active_pane.read(cx).items_len());
10931 let item_ids_in_pane =
10932 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10933 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
10934 assert!(item_ids_in_pane.contains(&right_item.item_id()));
10935 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
10936 assert!(item_ids_in_pane.contains(&left_item.item_id()));
10937
10938 // Join into next from left pane into top
10939 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10940 });
10941
10942 workspace.update_in(cx, |workspace, window, cx| {
10943 let active_pane = workspace.active_pane();
10944 assert_eq!(top_pane_id, active_pane.entity_id());
10945 assert_eq!(5, active_pane.read(cx).items_len());
10946 let item_ids_in_pane =
10947 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10948 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
10949 assert!(item_ids_in_pane.contains(&right_item.item_id()));
10950 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
10951 assert!(item_ids_in_pane.contains(&left_item.item_id()));
10952 assert!(item_ids_in_pane.contains(&top_item.item_id()));
10953
10954 // Single pane left: no-op
10955 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
10956 });
10957
10958 workspace.update(cx, |workspace, _cx| {
10959 let active_pane = workspace.active_pane();
10960 assert_eq!(top_pane_id, active_pane.entity_id());
10961 });
10962 }
10963
10964 fn add_an_item_to_active_pane(
10965 cx: &mut VisualTestContext,
10966 workspace: &Entity<Workspace>,
10967 item_id: u64,
10968 ) -> Entity<TestItem> {
10969 let item = cx.new(|cx| {
10970 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
10971 item_id,
10972 "item{item_id}.txt",
10973 cx,
10974 )])
10975 });
10976 workspace.update_in(cx, |workspace, window, cx| {
10977 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
10978 });
10979 item
10980 }
10981
10982 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
10983 workspace.update_in(cx, |workspace, window, cx| {
10984 workspace.split_pane(
10985 workspace.active_pane().clone(),
10986 SplitDirection::Right,
10987 window,
10988 cx,
10989 )
10990 })
10991 }
10992
10993 #[gpui::test]
10994 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
10995 init_test(cx);
10996 let fs = FakeFs::new(cx.executor());
10997 let project = Project::test(fs, None, cx).await;
10998 let (workspace, cx) =
10999 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11000
11001 add_an_item_to_active_pane(cx, &workspace, 1);
11002 split_pane(cx, &workspace);
11003 add_an_item_to_active_pane(cx, &workspace, 2);
11004 split_pane(cx, &workspace); // empty pane
11005 split_pane(cx, &workspace);
11006 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11007
11008 cx.executor().run_until_parked();
11009
11010 workspace.update(cx, |workspace, cx| {
11011 let num_panes = workspace.panes().len();
11012 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11013 let active_item = workspace
11014 .active_pane()
11015 .read(cx)
11016 .active_item()
11017 .expect("item is in focus");
11018
11019 assert_eq!(num_panes, 4);
11020 assert_eq!(num_items_in_current_pane, 1);
11021 assert_eq!(active_item.item_id(), last_item.item_id());
11022 });
11023
11024 workspace.update_in(cx, |workspace, window, cx| {
11025 workspace.join_all_panes(window, cx);
11026 });
11027
11028 workspace.update(cx, |workspace, cx| {
11029 let num_panes = workspace.panes().len();
11030 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11031 let active_item = workspace
11032 .active_pane()
11033 .read(cx)
11034 .active_item()
11035 .expect("item is in focus");
11036
11037 assert_eq!(num_panes, 1);
11038 assert_eq!(num_items_in_current_pane, 3);
11039 assert_eq!(active_item.item_id(), last_item.item_id());
11040 });
11041 }
11042 struct TestModal(FocusHandle);
11043
11044 impl TestModal {
11045 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11046 Self(cx.focus_handle())
11047 }
11048 }
11049
11050 impl EventEmitter<DismissEvent> for TestModal {}
11051
11052 impl Focusable for TestModal {
11053 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11054 self.0.clone()
11055 }
11056 }
11057
11058 impl ModalView for TestModal {}
11059
11060 impl Render for TestModal {
11061 fn render(
11062 &mut self,
11063 _window: &mut Window,
11064 _cx: &mut Context<TestModal>,
11065 ) -> impl IntoElement {
11066 div().track_focus(&self.0)
11067 }
11068 }
11069
11070 #[gpui::test]
11071 async fn test_panels(cx: &mut gpui::TestAppContext) {
11072 init_test(cx);
11073 let fs = FakeFs::new(cx.executor());
11074
11075 let project = Project::test(fs, [], cx).await;
11076 let (workspace, cx) =
11077 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11078
11079 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11080 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11081 workspace.add_panel(panel_1.clone(), window, cx);
11082 workspace.toggle_dock(DockPosition::Left, window, cx);
11083 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11084 workspace.add_panel(panel_2.clone(), window, cx);
11085 workspace.toggle_dock(DockPosition::Right, window, cx);
11086
11087 let left_dock = workspace.left_dock();
11088 assert_eq!(
11089 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11090 panel_1.panel_id()
11091 );
11092 assert_eq!(
11093 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11094 panel_1.size(window, cx)
11095 );
11096
11097 left_dock.update(cx, |left_dock, cx| {
11098 left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11099 });
11100 assert_eq!(
11101 workspace
11102 .right_dock()
11103 .read(cx)
11104 .visible_panel()
11105 .unwrap()
11106 .panel_id(),
11107 panel_2.panel_id(),
11108 );
11109
11110 (panel_1, panel_2)
11111 });
11112
11113 // Move panel_1 to the right
11114 panel_1.update_in(cx, |panel_1, window, cx| {
11115 panel_1.set_position(DockPosition::Right, window, cx)
11116 });
11117
11118 workspace.update_in(cx, |workspace, window, cx| {
11119 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11120 // Since it was the only panel on the left, the left dock should now be closed.
11121 assert!(!workspace.left_dock().read(cx).is_open());
11122 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11123 let right_dock = workspace.right_dock();
11124 assert_eq!(
11125 right_dock.read(cx).visible_panel().unwrap().panel_id(),
11126 panel_1.panel_id()
11127 );
11128 assert_eq!(
11129 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11130 px(1337.)
11131 );
11132
11133 // Now we move panel_2 to the left
11134 panel_2.set_position(DockPosition::Left, window, cx);
11135 });
11136
11137 workspace.update(cx, |workspace, cx| {
11138 // Since panel_2 was not visible on the right, we don't open the left dock.
11139 assert!(!workspace.left_dock().read(cx).is_open());
11140 // And the right dock is unaffected in its displaying of panel_1
11141 assert!(workspace.right_dock().read(cx).is_open());
11142 assert_eq!(
11143 workspace
11144 .right_dock()
11145 .read(cx)
11146 .visible_panel()
11147 .unwrap()
11148 .panel_id(),
11149 panel_1.panel_id(),
11150 );
11151 });
11152
11153 // Move panel_1 back to the left
11154 panel_1.update_in(cx, |panel_1, window, cx| {
11155 panel_1.set_position(DockPosition::Left, window, cx)
11156 });
11157
11158 workspace.update_in(cx, |workspace, window, cx| {
11159 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
11160 let left_dock = workspace.left_dock();
11161 assert!(left_dock.read(cx).is_open());
11162 assert_eq!(
11163 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11164 panel_1.panel_id()
11165 );
11166 assert_eq!(
11167 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11168 px(1337.)
11169 );
11170 // And the right dock should be closed as it no longer has any panels.
11171 assert!(!workspace.right_dock().read(cx).is_open());
11172
11173 // Now we move panel_1 to the bottom
11174 panel_1.set_position(DockPosition::Bottom, window, cx);
11175 });
11176
11177 workspace.update_in(cx, |workspace, window, cx| {
11178 // Since panel_1 was visible on the left, we close the left dock.
11179 assert!(!workspace.left_dock().read(cx).is_open());
11180 // The bottom dock is sized based on the panel's default size,
11181 // since the panel orientation changed from vertical to horizontal.
11182 let bottom_dock = workspace.bottom_dock();
11183 assert_eq!(
11184 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
11185 panel_1.size(window, cx),
11186 );
11187 // Close bottom dock and move panel_1 back to the left.
11188 bottom_dock.update(cx, |bottom_dock, cx| {
11189 bottom_dock.set_open(false, window, cx)
11190 });
11191 panel_1.set_position(DockPosition::Left, window, cx);
11192 });
11193
11194 // Emit activated event on panel 1
11195 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
11196
11197 // Now the left dock is open and panel_1 is active and focused.
11198 workspace.update_in(cx, |workspace, window, cx| {
11199 let left_dock = workspace.left_dock();
11200 assert!(left_dock.read(cx).is_open());
11201 assert_eq!(
11202 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11203 panel_1.panel_id(),
11204 );
11205 assert!(panel_1.focus_handle(cx).is_focused(window));
11206 });
11207
11208 // Emit closed event on panel 2, which is not active
11209 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11210
11211 // Wo don't close the left dock, because panel_2 wasn't the active panel
11212 workspace.update(cx, |workspace, cx| {
11213 let left_dock = workspace.left_dock();
11214 assert!(left_dock.read(cx).is_open());
11215 assert_eq!(
11216 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11217 panel_1.panel_id(),
11218 );
11219 });
11220
11221 // Emitting a ZoomIn event shows the panel as zoomed.
11222 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
11223 workspace.read_with(cx, |workspace, _| {
11224 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11225 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
11226 });
11227
11228 // Move panel to another dock while it is zoomed
11229 panel_1.update_in(cx, |panel, window, cx| {
11230 panel.set_position(DockPosition::Right, window, cx)
11231 });
11232 workspace.read_with(cx, |workspace, _| {
11233 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11234
11235 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11236 });
11237
11238 // This is a helper for getting a:
11239 // - valid focus on an element,
11240 // - that isn't a part of the panes and panels system of the Workspace,
11241 // - and doesn't trigger the 'on_focus_lost' API.
11242 let focus_other_view = {
11243 let workspace = workspace.clone();
11244 move |cx: &mut VisualTestContext| {
11245 workspace.update_in(cx, |workspace, window, cx| {
11246 if workspace.active_modal::<TestModal>(cx).is_some() {
11247 workspace.toggle_modal(window, cx, TestModal::new);
11248 workspace.toggle_modal(window, cx, TestModal::new);
11249 } else {
11250 workspace.toggle_modal(window, cx, TestModal::new);
11251 }
11252 })
11253 }
11254 };
11255
11256 // If focus is transferred to another view that's not a panel or another pane, we still show
11257 // the panel as zoomed.
11258 focus_other_view(cx);
11259 workspace.read_with(cx, |workspace, _| {
11260 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11261 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11262 });
11263
11264 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
11265 workspace.update_in(cx, |_workspace, window, cx| {
11266 cx.focus_self(window);
11267 });
11268 workspace.read_with(cx, |workspace, _| {
11269 assert_eq!(workspace.zoomed, None);
11270 assert_eq!(workspace.zoomed_position, None);
11271 });
11272
11273 // If focus is transferred again to another view that's not a panel or a pane, we won't
11274 // show the panel as zoomed because it wasn't zoomed before.
11275 focus_other_view(cx);
11276 workspace.read_with(cx, |workspace, _| {
11277 assert_eq!(workspace.zoomed, None);
11278 assert_eq!(workspace.zoomed_position, None);
11279 });
11280
11281 // When the panel is activated, it is zoomed again.
11282 cx.dispatch_action(ToggleRightDock);
11283 workspace.read_with(cx, |workspace, _| {
11284 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11285 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11286 });
11287
11288 // Emitting a ZoomOut event unzooms the panel.
11289 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
11290 workspace.read_with(cx, |workspace, _| {
11291 assert_eq!(workspace.zoomed, None);
11292 assert_eq!(workspace.zoomed_position, None);
11293 });
11294
11295 // Emit closed event on panel 1, which is active
11296 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11297
11298 // Now the left dock is closed, because panel_1 was the active panel
11299 workspace.update(cx, |workspace, cx| {
11300 let right_dock = workspace.right_dock();
11301 assert!(!right_dock.read(cx).is_open());
11302 });
11303 }
11304
11305 #[gpui::test]
11306 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
11307 init_test(cx);
11308
11309 let fs = FakeFs::new(cx.background_executor.clone());
11310 let project = Project::test(fs, [], cx).await;
11311 let (workspace, cx) =
11312 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11313 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11314
11315 let dirty_regular_buffer = cx.new(|cx| {
11316 TestItem::new(cx)
11317 .with_dirty(true)
11318 .with_label("1.txt")
11319 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11320 });
11321 let dirty_regular_buffer_2 = cx.new(|cx| {
11322 TestItem::new(cx)
11323 .with_dirty(true)
11324 .with_label("2.txt")
11325 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11326 });
11327 let dirty_multi_buffer_with_both = cx.new(|cx| {
11328 TestItem::new(cx)
11329 .with_dirty(true)
11330 .with_buffer_kind(ItemBufferKind::Multibuffer)
11331 .with_label("Fake Project Search")
11332 .with_project_items(&[
11333 dirty_regular_buffer.read(cx).project_items[0].clone(),
11334 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11335 ])
11336 });
11337 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
11338 workspace.update_in(cx, |workspace, window, cx| {
11339 workspace.add_item(
11340 pane.clone(),
11341 Box::new(dirty_regular_buffer.clone()),
11342 None,
11343 false,
11344 false,
11345 window,
11346 cx,
11347 );
11348 workspace.add_item(
11349 pane.clone(),
11350 Box::new(dirty_regular_buffer_2.clone()),
11351 None,
11352 false,
11353 false,
11354 window,
11355 cx,
11356 );
11357 workspace.add_item(
11358 pane.clone(),
11359 Box::new(dirty_multi_buffer_with_both.clone()),
11360 None,
11361 false,
11362 false,
11363 window,
11364 cx,
11365 );
11366 });
11367
11368 pane.update_in(cx, |pane, window, cx| {
11369 pane.activate_item(2, true, true, window, cx);
11370 assert_eq!(
11371 pane.active_item().unwrap().item_id(),
11372 multi_buffer_with_both_files_id,
11373 "Should select the multi buffer in the pane"
11374 );
11375 });
11376 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11377 pane.close_other_items(
11378 &CloseOtherItems {
11379 save_intent: Some(SaveIntent::Save),
11380 close_pinned: true,
11381 },
11382 None,
11383 window,
11384 cx,
11385 )
11386 });
11387 cx.background_executor.run_until_parked();
11388 assert!(!cx.has_pending_prompt());
11389 close_all_but_multi_buffer_task
11390 .await
11391 .expect("Closing all buffers but the multi buffer failed");
11392 pane.update(cx, |pane, cx| {
11393 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
11394 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
11395 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
11396 assert_eq!(pane.items_len(), 1);
11397 assert_eq!(
11398 pane.active_item().unwrap().item_id(),
11399 multi_buffer_with_both_files_id,
11400 "Should have only the multi buffer left in the pane"
11401 );
11402 assert!(
11403 dirty_multi_buffer_with_both.read(cx).is_dirty,
11404 "The multi buffer containing the unsaved buffer should still be dirty"
11405 );
11406 });
11407
11408 dirty_regular_buffer.update(cx, |buffer, cx| {
11409 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
11410 });
11411
11412 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11413 pane.close_active_item(
11414 &CloseActiveItem {
11415 save_intent: Some(SaveIntent::Close),
11416 close_pinned: false,
11417 },
11418 window,
11419 cx,
11420 )
11421 });
11422 cx.background_executor.run_until_parked();
11423 assert!(
11424 cx.has_pending_prompt(),
11425 "Dirty multi buffer should prompt a save dialog"
11426 );
11427 cx.simulate_prompt_answer("Save");
11428 cx.background_executor.run_until_parked();
11429 close_multi_buffer_task
11430 .await
11431 .expect("Closing the multi buffer failed");
11432 pane.update(cx, |pane, cx| {
11433 assert_eq!(
11434 dirty_multi_buffer_with_both.read(cx).save_count,
11435 1,
11436 "Multi buffer item should get be saved"
11437 );
11438 // Test impl does not save inner items, so we do not assert them
11439 assert_eq!(
11440 pane.items_len(),
11441 0,
11442 "No more items should be left in the pane"
11443 );
11444 assert!(pane.active_item().is_none());
11445 });
11446 }
11447
11448 #[gpui::test]
11449 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
11450 cx: &mut TestAppContext,
11451 ) {
11452 init_test(cx);
11453
11454 let fs = FakeFs::new(cx.background_executor.clone());
11455 let project = Project::test(fs, [], cx).await;
11456 let (workspace, cx) =
11457 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11458 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11459
11460 let dirty_regular_buffer = cx.new(|cx| {
11461 TestItem::new(cx)
11462 .with_dirty(true)
11463 .with_label("1.txt")
11464 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11465 });
11466 let dirty_regular_buffer_2 = cx.new(|cx| {
11467 TestItem::new(cx)
11468 .with_dirty(true)
11469 .with_label("2.txt")
11470 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11471 });
11472 let clear_regular_buffer = cx.new(|cx| {
11473 TestItem::new(cx)
11474 .with_label("3.txt")
11475 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
11476 });
11477
11478 let dirty_multi_buffer_with_both = cx.new(|cx| {
11479 TestItem::new(cx)
11480 .with_dirty(true)
11481 .with_buffer_kind(ItemBufferKind::Multibuffer)
11482 .with_label("Fake Project Search")
11483 .with_project_items(&[
11484 dirty_regular_buffer.read(cx).project_items[0].clone(),
11485 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11486 clear_regular_buffer.read(cx).project_items[0].clone(),
11487 ])
11488 });
11489 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
11490 workspace.update_in(cx, |workspace, window, cx| {
11491 workspace.add_item(
11492 pane.clone(),
11493 Box::new(dirty_regular_buffer.clone()),
11494 None,
11495 false,
11496 false,
11497 window,
11498 cx,
11499 );
11500 workspace.add_item(
11501 pane.clone(),
11502 Box::new(dirty_multi_buffer_with_both.clone()),
11503 None,
11504 false,
11505 false,
11506 window,
11507 cx,
11508 );
11509 });
11510
11511 pane.update_in(cx, |pane, window, cx| {
11512 pane.activate_item(1, true, true, window, cx);
11513 assert_eq!(
11514 pane.active_item().unwrap().item_id(),
11515 multi_buffer_with_both_files_id,
11516 "Should select the multi buffer in the pane"
11517 );
11518 });
11519 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11520 pane.close_active_item(
11521 &CloseActiveItem {
11522 save_intent: None,
11523 close_pinned: false,
11524 },
11525 window,
11526 cx,
11527 )
11528 });
11529 cx.background_executor.run_until_parked();
11530 assert!(
11531 cx.has_pending_prompt(),
11532 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
11533 );
11534 }
11535
11536 /// Tests that when `close_on_file_delete` is enabled, files are automatically
11537 /// closed when they are deleted from disk.
11538 #[gpui::test]
11539 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
11540 init_test(cx);
11541
11542 // Enable the close_on_disk_deletion setting
11543 cx.update_global(|store: &mut SettingsStore, cx| {
11544 store.update_user_settings(cx, |settings| {
11545 settings.workspace.close_on_file_delete = Some(true);
11546 });
11547 });
11548
11549 let fs = FakeFs::new(cx.background_executor.clone());
11550 let project = Project::test(fs, [], cx).await;
11551 let (workspace, cx) =
11552 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11553 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11554
11555 // Create a test item that simulates a file
11556 let item = cx.new(|cx| {
11557 TestItem::new(cx)
11558 .with_label("test.txt")
11559 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11560 });
11561
11562 // Add item to workspace
11563 workspace.update_in(cx, |workspace, window, cx| {
11564 workspace.add_item(
11565 pane.clone(),
11566 Box::new(item.clone()),
11567 None,
11568 false,
11569 false,
11570 window,
11571 cx,
11572 );
11573 });
11574
11575 // Verify the item is in the pane
11576 pane.read_with(cx, |pane, _| {
11577 assert_eq!(pane.items().count(), 1);
11578 });
11579
11580 // Simulate file deletion by setting the item's deleted state
11581 item.update(cx, |item, _| {
11582 item.set_has_deleted_file(true);
11583 });
11584
11585 // Emit UpdateTab event to trigger the close behavior
11586 cx.run_until_parked();
11587 item.update(cx, |_, cx| {
11588 cx.emit(ItemEvent::UpdateTab);
11589 });
11590
11591 // Allow the close operation to complete
11592 cx.run_until_parked();
11593
11594 // Verify the item was automatically closed
11595 pane.read_with(cx, |pane, _| {
11596 assert_eq!(
11597 pane.items().count(),
11598 0,
11599 "Item should be automatically closed when file is deleted"
11600 );
11601 });
11602 }
11603
11604 /// Tests that when `close_on_file_delete` is disabled (default), files remain
11605 /// open with a strikethrough when they are deleted from disk.
11606 #[gpui::test]
11607 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
11608 init_test(cx);
11609
11610 // Ensure close_on_disk_deletion is disabled (default)
11611 cx.update_global(|store: &mut SettingsStore, cx| {
11612 store.update_user_settings(cx, |settings| {
11613 settings.workspace.close_on_file_delete = Some(false);
11614 });
11615 });
11616
11617 let fs = FakeFs::new(cx.background_executor.clone());
11618 let project = Project::test(fs, [], cx).await;
11619 let (workspace, cx) =
11620 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11621 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11622
11623 // Create a test item that simulates a file
11624 let item = cx.new(|cx| {
11625 TestItem::new(cx)
11626 .with_label("test.txt")
11627 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11628 });
11629
11630 // Add item to workspace
11631 workspace.update_in(cx, |workspace, window, cx| {
11632 workspace.add_item(
11633 pane.clone(),
11634 Box::new(item.clone()),
11635 None,
11636 false,
11637 false,
11638 window,
11639 cx,
11640 );
11641 });
11642
11643 // Verify the item is in the pane
11644 pane.read_with(cx, |pane, _| {
11645 assert_eq!(pane.items().count(), 1);
11646 });
11647
11648 // Simulate file deletion
11649 item.update(cx, |item, _| {
11650 item.set_has_deleted_file(true);
11651 });
11652
11653 // Emit UpdateTab event
11654 cx.run_until_parked();
11655 item.update(cx, |_, cx| {
11656 cx.emit(ItemEvent::UpdateTab);
11657 });
11658
11659 // Allow any potential close operation to complete
11660 cx.run_until_parked();
11661
11662 // Verify the item remains open (with strikethrough)
11663 pane.read_with(cx, |pane, _| {
11664 assert_eq!(
11665 pane.items().count(),
11666 1,
11667 "Item should remain open when close_on_disk_deletion is disabled"
11668 );
11669 });
11670
11671 // Verify the item shows as deleted
11672 item.read_with(cx, |item, _| {
11673 assert!(
11674 item.has_deleted_file,
11675 "Item should be marked as having deleted file"
11676 );
11677 });
11678 }
11679
11680 /// Tests that dirty files are not automatically closed when deleted from disk,
11681 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
11682 /// unsaved changes without being prompted.
11683 #[gpui::test]
11684 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
11685 init_test(cx);
11686
11687 // Enable the close_on_file_delete setting
11688 cx.update_global(|store: &mut SettingsStore, cx| {
11689 store.update_user_settings(cx, |settings| {
11690 settings.workspace.close_on_file_delete = Some(true);
11691 });
11692 });
11693
11694 let fs = FakeFs::new(cx.background_executor.clone());
11695 let project = Project::test(fs, [], cx).await;
11696 let (workspace, cx) =
11697 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11698 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11699
11700 // Create a dirty test item
11701 let item = cx.new(|cx| {
11702 TestItem::new(cx)
11703 .with_dirty(true)
11704 .with_label("test.txt")
11705 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11706 });
11707
11708 // Add item to workspace
11709 workspace.update_in(cx, |workspace, window, cx| {
11710 workspace.add_item(
11711 pane.clone(),
11712 Box::new(item.clone()),
11713 None,
11714 false,
11715 false,
11716 window,
11717 cx,
11718 );
11719 });
11720
11721 // Simulate file deletion
11722 item.update(cx, |item, _| {
11723 item.set_has_deleted_file(true);
11724 });
11725
11726 // Emit UpdateTab event to trigger the close behavior
11727 cx.run_until_parked();
11728 item.update(cx, |_, cx| {
11729 cx.emit(ItemEvent::UpdateTab);
11730 });
11731
11732 // Allow any potential close operation to complete
11733 cx.run_until_parked();
11734
11735 // Verify the item remains open (dirty files are not auto-closed)
11736 pane.read_with(cx, |pane, _| {
11737 assert_eq!(
11738 pane.items().count(),
11739 1,
11740 "Dirty items should not be automatically closed even when file is deleted"
11741 );
11742 });
11743
11744 // Verify the item is marked as deleted and still dirty
11745 item.read_with(cx, |item, _| {
11746 assert!(
11747 item.has_deleted_file,
11748 "Item should be marked as having deleted file"
11749 );
11750 assert!(item.is_dirty, "Item should still be dirty");
11751 });
11752 }
11753
11754 /// Tests that navigation history is cleaned up when files are auto-closed
11755 /// due to deletion from disk.
11756 #[gpui::test]
11757 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
11758 init_test(cx);
11759
11760 // Enable the close_on_file_delete setting
11761 cx.update_global(|store: &mut SettingsStore, cx| {
11762 store.update_user_settings(cx, |settings| {
11763 settings.workspace.close_on_file_delete = Some(true);
11764 });
11765 });
11766
11767 let fs = FakeFs::new(cx.background_executor.clone());
11768 let project = Project::test(fs, [], cx).await;
11769 let (workspace, cx) =
11770 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11771 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11772
11773 // Create test items
11774 let item1 = cx.new(|cx| {
11775 TestItem::new(cx)
11776 .with_label("test1.txt")
11777 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
11778 });
11779 let item1_id = item1.item_id();
11780
11781 let item2 = cx.new(|cx| {
11782 TestItem::new(cx)
11783 .with_label("test2.txt")
11784 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
11785 });
11786
11787 // Add items to workspace
11788 workspace.update_in(cx, |workspace, window, cx| {
11789 workspace.add_item(
11790 pane.clone(),
11791 Box::new(item1.clone()),
11792 None,
11793 false,
11794 false,
11795 window,
11796 cx,
11797 );
11798 workspace.add_item(
11799 pane.clone(),
11800 Box::new(item2.clone()),
11801 None,
11802 false,
11803 false,
11804 window,
11805 cx,
11806 );
11807 });
11808
11809 // Activate item1 to ensure it gets navigation entries
11810 pane.update_in(cx, |pane, window, cx| {
11811 pane.activate_item(0, true, true, window, cx);
11812 });
11813
11814 // Switch to item2 and back to create navigation history
11815 pane.update_in(cx, |pane, window, cx| {
11816 pane.activate_item(1, true, true, window, cx);
11817 });
11818 cx.run_until_parked();
11819
11820 pane.update_in(cx, |pane, window, cx| {
11821 pane.activate_item(0, true, true, window, cx);
11822 });
11823 cx.run_until_parked();
11824
11825 // Simulate file deletion for item1
11826 item1.update(cx, |item, _| {
11827 item.set_has_deleted_file(true);
11828 });
11829
11830 // Emit UpdateTab event to trigger the close behavior
11831 item1.update(cx, |_, cx| {
11832 cx.emit(ItemEvent::UpdateTab);
11833 });
11834 cx.run_until_parked();
11835
11836 // Verify item1 was closed
11837 pane.read_with(cx, |pane, _| {
11838 assert_eq!(
11839 pane.items().count(),
11840 1,
11841 "Should have 1 item remaining after auto-close"
11842 );
11843 });
11844
11845 // Check navigation history after close
11846 let has_item = pane.read_with(cx, |pane, cx| {
11847 let mut has_item = false;
11848 pane.nav_history().for_each_entry(cx, |entry, _| {
11849 if entry.item.id() == item1_id {
11850 has_item = true;
11851 }
11852 });
11853 has_item
11854 });
11855
11856 assert!(
11857 !has_item,
11858 "Navigation history should not contain closed item entries"
11859 );
11860 }
11861
11862 #[gpui::test]
11863 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
11864 cx: &mut TestAppContext,
11865 ) {
11866 init_test(cx);
11867
11868 let fs = FakeFs::new(cx.background_executor.clone());
11869 let project = Project::test(fs, [], cx).await;
11870 let (workspace, cx) =
11871 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11872 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11873
11874 let dirty_regular_buffer = cx.new(|cx| {
11875 TestItem::new(cx)
11876 .with_dirty(true)
11877 .with_label("1.txt")
11878 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11879 });
11880 let dirty_regular_buffer_2 = cx.new(|cx| {
11881 TestItem::new(cx)
11882 .with_dirty(true)
11883 .with_label("2.txt")
11884 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11885 });
11886 let clear_regular_buffer = cx.new(|cx| {
11887 TestItem::new(cx)
11888 .with_label("3.txt")
11889 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
11890 });
11891
11892 let dirty_multi_buffer = cx.new(|cx| {
11893 TestItem::new(cx)
11894 .with_dirty(true)
11895 .with_buffer_kind(ItemBufferKind::Multibuffer)
11896 .with_label("Fake Project Search")
11897 .with_project_items(&[
11898 dirty_regular_buffer.read(cx).project_items[0].clone(),
11899 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11900 clear_regular_buffer.read(cx).project_items[0].clone(),
11901 ])
11902 });
11903 workspace.update_in(cx, |workspace, window, cx| {
11904 workspace.add_item(
11905 pane.clone(),
11906 Box::new(dirty_regular_buffer.clone()),
11907 None,
11908 false,
11909 false,
11910 window,
11911 cx,
11912 );
11913 workspace.add_item(
11914 pane.clone(),
11915 Box::new(dirty_regular_buffer_2.clone()),
11916 None,
11917 false,
11918 false,
11919 window,
11920 cx,
11921 );
11922 workspace.add_item(
11923 pane.clone(),
11924 Box::new(dirty_multi_buffer.clone()),
11925 None,
11926 false,
11927 false,
11928 window,
11929 cx,
11930 );
11931 });
11932
11933 pane.update_in(cx, |pane, window, cx| {
11934 pane.activate_item(2, true, true, window, cx);
11935 assert_eq!(
11936 pane.active_item().unwrap().item_id(),
11937 dirty_multi_buffer.item_id(),
11938 "Should select the multi buffer in the pane"
11939 );
11940 });
11941 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11942 pane.close_active_item(
11943 &CloseActiveItem {
11944 save_intent: None,
11945 close_pinned: false,
11946 },
11947 window,
11948 cx,
11949 )
11950 });
11951 cx.background_executor.run_until_parked();
11952 assert!(
11953 !cx.has_pending_prompt(),
11954 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
11955 );
11956 close_multi_buffer_task
11957 .await
11958 .expect("Closing multi buffer failed");
11959 pane.update(cx, |pane, cx| {
11960 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
11961 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
11962 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
11963 assert_eq!(
11964 pane.items()
11965 .map(|item| item.item_id())
11966 .sorted()
11967 .collect::<Vec<_>>(),
11968 vec![
11969 dirty_regular_buffer.item_id(),
11970 dirty_regular_buffer_2.item_id(),
11971 ],
11972 "Should have no multi buffer left in the pane"
11973 );
11974 assert!(dirty_regular_buffer.read(cx).is_dirty);
11975 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
11976 });
11977 }
11978
11979 #[gpui::test]
11980 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
11981 init_test(cx);
11982 let fs = FakeFs::new(cx.executor());
11983 let project = Project::test(fs, [], cx).await;
11984 let (workspace, cx) =
11985 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11986
11987 // Add a new panel to the right dock, opening the dock and setting the
11988 // focus to the new panel.
11989 let panel = workspace.update_in(cx, |workspace, window, cx| {
11990 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11991 workspace.add_panel(panel.clone(), window, cx);
11992
11993 workspace
11994 .right_dock()
11995 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11996
11997 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11998
11999 panel
12000 });
12001
12002 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12003 // panel to the next valid position which, in this case, is the left
12004 // dock.
12005 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12006 workspace.update(cx, |workspace, cx| {
12007 assert!(workspace.left_dock().read(cx).is_open());
12008 assert_eq!(panel.read(cx).position, DockPosition::Left);
12009 });
12010
12011 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12012 // panel to the next valid position which, in this case, is the bottom
12013 // dock.
12014 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12015 workspace.update(cx, |workspace, cx| {
12016 assert!(workspace.bottom_dock().read(cx).is_open());
12017 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12018 });
12019
12020 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12021 // around moving the panel to its initial position, the right dock.
12022 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12023 workspace.update(cx, |workspace, cx| {
12024 assert!(workspace.right_dock().read(cx).is_open());
12025 assert_eq!(panel.read(cx).position, DockPosition::Right);
12026 });
12027
12028 // Remove focus from the panel, ensuring that, if the panel is not
12029 // focused, the `MoveFocusedPanelToNextPosition` action does not update
12030 // the panel's position, so the panel is still in the right dock.
12031 workspace.update_in(cx, |workspace, window, cx| {
12032 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12033 });
12034
12035 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12036 workspace.update(cx, |workspace, cx| {
12037 assert!(workspace.right_dock().read(cx).is_open());
12038 assert_eq!(panel.read(cx).position, DockPosition::Right);
12039 });
12040 }
12041
12042 #[gpui::test]
12043 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12044 init_test(cx);
12045
12046 let fs = FakeFs::new(cx.executor());
12047 let project = Project::test(fs, [], cx).await;
12048 let (workspace, cx) =
12049 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12050
12051 let item_1 = cx.new(|cx| {
12052 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12053 });
12054 workspace.update_in(cx, |workspace, window, cx| {
12055 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12056 workspace.move_item_to_pane_in_direction(
12057 &MoveItemToPaneInDirection {
12058 direction: SplitDirection::Right,
12059 focus: true,
12060 clone: false,
12061 },
12062 window,
12063 cx,
12064 );
12065 workspace.move_item_to_pane_at_index(
12066 &MoveItemToPane {
12067 destination: 3,
12068 focus: true,
12069 clone: false,
12070 },
12071 window,
12072 cx,
12073 );
12074
12075 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12076 assert_eq!(
12077 pane_items_paths(&workspace.active_pane, cx),
12078 vec!["first.txt".to_string()],
12079 "Single item was not moved anywhere"
12080 );
12081 });
12082
12083 let item_2 = cx.new(|cx| {
12084 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12085 });
12086 workspace.update_in(cx, |workspace, window, cx| {
12087 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12088 assert_eq!(
12089 pane_items_paths(&workspace.panes[0], cx),
12090 vec!["first.txt".to_string(), "second.txt".to_string()],
12091 );
12092 workspace.move_item_to_pane_in_direction(
12093 &MoveItemToPaneInDirection {
12094 direction: SplitDirection::Right,
12095 focus: true,
12096 clone: false,
12097 },
12098 window,
12099 cx,
12100 );
12101
12102 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12103 assert_eq!(
12104 pane_items_paths(&workspace.panes[0], cx),
12105 vec!["first.txt".to_string()],
12106 "After moving, one item should be left in the original pane"
12107 );
12108 assert_eq!(
12109 pane_items_paths(&workspace.panes[1], cx),
12110 vec!["second.txt".to_string()],
12111 "New item should have been moved to the new pane"
12112 );
12113 });
12114
12115 let item_3 = cx.new(|cx| {
12116 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12117 });
12118 workspace.update_in(cx, |workspace, window, cx| {
12119 let original_pane = workspace.panes[0].clone();
12120 workspace.set_active_pane(&original_pane, window, cx);
12121 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12122 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12123 assert_eq!(
12124 pane_items_paths(&workspace.active_pane, cx),
12125 vec!["first.txt".to_string(), "third.txt".to_string()],
12126 "New pane should be ready to move one item out"
12127 );
12128
12129 workspace.move_item_to_pane_at_index(
12130 &MoveItemToPane {
12131 destination: 3,
12132 focus: true,
12133 clone: false,
12134 },
12135 window,
12136 cx,
12137 );
12138 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12139 assert_eq!(
12140 pane_items_paths(&workspace.active_pane, cx),
12141 vec!["first.txt".to_string()],
12142 "After moving, one item should be left in the original pane"
12143 );
12144 assert_eq!(
12145 pane_items_paths(&workspace.panes[1], cx),
12146 vec!["second.txt".to_string()],
12147 "Previously created pane should be unchanged"
12148 );
12149 assert_eq!(
12150 pane_items_paths(&workspace.panes[2], cx),
12151 vec!["third.txt".to_string()],
12152 "New item should have been moved to the new pane"
12153 );
12154 });
12155 }
12156
12157 #[gpui::test]
12158 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
12159 init_test(cx);
12160
12161 let fs = FakeFs::new(cx.executor());
12162 let project = Project::test(fs, [], cx).await;
12163 let (workspace, cx) =
12164 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12165
12166 let item_1 = cx.new(|cx| {
12167 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12168 });
12169 workspace.update_in(cx, |workspace, window, cx| {
12170 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12171 workspace.move_item_to_pane_in_direction(
12172 &MoveItemToPaneInDirection {
12173 direction: SplitDirection::Right,
12174 focus: true,
12175 clone: true,
12176 },
12177 window,
12178 cx,
12179 );
12180 });
12181 cx.run_until_parked();
12182 workspace.update_in(cx, |workspace, window, cx| {
12183 workspace.move_item_to_pane_at_index(
12184 &MoveItemToPane {
12185 destination: 3,
12186 focus: true,
12187 clone: true,
12188 },
12189 window,
12190 cx,
12191 );
12192 });
12193 cx.run_until_parked();
12194
12195 workspace.update(cx, |workspace, cx| {
12196 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
12197 for pane in workspace.panes() {
12198 assert_eq!(
12199 pane_items_paths(pane, cx),
12200 vec!["first.txt".to_string()],
12201 "Single item exists in all panes"
12202 );
12203 }
12204 });
12205
12206 // verify that the active pane has been updated after waiting for the
12207 // pane focus event to fire and resolve
12208 workspace.read_with(cx, |workspace, _app| {
12209 assert_eq!(
12210 workspace.active_pane(),
12211 &workspace.panes[2],
12212 "The third pane should be the active one: {:?}",
12213 workspace.panes
12214 );
12215 })
12216 }
12217
12218 #[gpui::test]
12219 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
12220 init_test(cx);
12221
12222 let fs = FakeFs::new(cx.executor());
12223 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
12224
12225 let project = Project::test(fs, ["root".as_ref()], cx).await;
12226 let (workspace, cx) =
12227 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12228
12229 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12230 // Add item to pane A with project path
12231 let item_a = cx.new(|cx| {
12232 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12233 });
12234 workspace.update_in(cx, |workspace, window, cx| {
12235 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
12236 });
12237
12238 // Split to create pane B
12239 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
12240 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
12241 });
12242
12243 // Add item with SAME project path to pane B, and pin it
12244 let item_b = cx.new(|cx| {
12245 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12246 });
12247 pane_b.update_in(cx, |pane, window, cx| {
12248 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
12249 pane.set_pinned_count(1);
12250 });
12251
12252 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
12253 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
12254
12255 // close_pinned: false should only close the unpinned copy
12256 workspace.update_in(cx, |workspace, window, cx| {
12257 workspace.close_item_in_all_panes(
12258 &CloseItemInAllPanes {
12259 save_intent: Some(SaveIntent::Close),
12260 close_pinned: false,
12261 },
12262 window,
12263 cx,
12264 )
12265 });
12266 cx.executor().run_until_parked();
12267
12268 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
12269 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
12270 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
12271 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
12272
12273 // Split again, seeing as closing the previous item also closed its
12274 // pane, so only pane remains, which does not allow us to properly test
12275 // that both items close when `close_pinned: true`.
12276 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
12277 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
12278 });
12279
12280 // Add an item with the same project path to pane C so that
12281 // close_item_in_all_panes can determine what to close across all panes
12282 // (it reads the active item from the active pane, and split_pane
12283 // creates an empty pane).
12284 let item_c = cx.new(|cx| {
12285 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12286 });
12287 pane_c.update_in(cx, |pane, window, cx| {
12288 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
12289 });
12290
12291 // close_pinned: true should close the pinned copy too
12292 workspace.update_in(cx, |workspace, window, cx| {
12293 let panes_count = workspace.panes().len();
12294 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
12295
12296 workspace.close_item_in_all_panes(
12297 &CloseItemInAllPanes {
12298 save_intent: Some(SaveIntent::Close),
12299 close_pinned: true,
12300 },
12301 window,
12302 cx,
12303 )
12304 });
12305 cx.executor().run_until_parked();
12306
12307 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
12308 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
12309 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
12310 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
12311 }
12312
12313 mod register_project_item_tests {
12314
12315 use super::*;
12316
12317 // View
12318 struct TestPngItemView {
12319 focus_handle: FocusHandle,
12320 }
12321 // Model
12322 struct TestPngItem {}
12323
12324 impl project::ProjectItem for TestPngItem {
12325 fn try_open(
12326 _project: &Entity<Project>,
12327 path: &ProjectPath,
12328 cx: &mut App,
12329 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
12330 if path.path.extension().unwrap() == "png" {
12331 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
12332 } else {
12333 None
12334 }
12335 }
12336
12337 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
12338 None
12339 }
12340
12341 fn project_path(&self, _: &App) -> Option<ProjectPath> {
12342 None
12343 }
12344
12345 fn is_dirty(&self) -> bool {
12346 false
12347 }
12348 }
12349
12350 impl Item for TestPngItemView {
12351 type Event = ();
12352 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12353 "".into()
12354 }
12355 }
12356 impl EventEmitter<()> for TestPngItemView {}
12357 impl Focusable for TestPngItemView {
12358 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12359 self.focus_handle.clone()
12360 }
12361 }
12362
12363 impl Render for TestPngItemView {
12364 fn render(
12365 &mut self,
12366 _window: &mut Window,
12367 _cx: &mut Context<Self>,
12368 ) -> impl IntoElement {
12369 Empty
12370 }
12371 }
12372
12373 impl ProjectItem for TestPngItemView {
12374 type Item = TestPngItem;
12375
12376 fn for_project_item(
12377 _project: Entity<Project>,
12378 _pane: Option<&Pane>,
12379 _item: Entity<Self::Item>,
12380 _: &mut Window,
12381 cx: &mut Context<Self>,
12382 ) -> Self
12383 where
12384 Self: Sized,
12385 {
12386 Self {
12387 focus_handle: cx.focus_handle(),
12388 }
12389 }
12390 }
12391
12392 // View
12393 struct TestIpynbItemView {
12394 focus_handle: FocusHandle,
12395 }
12396 // Model
12397 struct TestIpynbItem {}
12398
12399 impl project::ProjectItem for TestIpynbItem {
12400 fn try_open(
12401 _project: &Entity<Project>,
12402 path: &ProjectPath,
12403 cx: &mut App,
12404 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
12405 if path.path.extension().unwrap() == "ipynb" {
12406 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
12407 } else {
12408 None
12409 }
12410 }
12411
12412 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
12413 None
12414 }
12415
12416 fn project_path(&self, _: &App) -> Option<ProjectPath> {
12417 None
12418 }
12419
12420 fn is_dirty(&self) -> bool {
12421 false
12422 }
12423 }
12424
12425 impl Item for TestIpynbItemView {
12426 type Event = ();
12427 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12428 "".into()
12429 }
12430 }
12431 impl EventEmitter<()> for TestIpynbItemView {}
12432 impl Focusable for TestIpynbItemView {
12433 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12434 self.focus_handle.clone()
12435 }
12436 }
12437
12438 impl Render for TestIpynbItemView {
12439 fn render(
12440 &mut self,
12441 _window: &mut Window,
12442 _cx: &mut Context<Self>,
12443 ) -> impl IntoElement {
12444 Empty
12445 }
12446 }
12447
12448 impl ProjectItem for TestIpynbItemView {
12449 type Item = TestIpynbItem;
12450
12451 fn for_project_item(
12452 _project: Entity<Project>,
12453 _pane: Option<&Pane>,
12454 _item: Entity<Self::Item>,
12455 _: &mut Window,
12456 cx: &mut Context<Self>,
12457 ) -> Self
12458 where
12459 Self: Sized,
12460 {
12461 Self {
12462 focus_handle: cx.focus_handle(),
12463 }
12464 }
12465 }
12466
12467 struct TestAlternatePngItemView {
12468 focus_handle: FocusHandle,
12469 }
12470
12471 impl Item for TestAlternatePngItemView {
12472 type Event = ();
12473 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12474 "".into()
12475 }
12476 }
12477
12478 impl EventEmitter<()> for TestAlternatePngItemView {}
12479 impl Focusable for TestAlternatePngItemView {
12480 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12481 self.focus_handle.clone()
12482 }
12483 }
12484
12485 impl Render for TestAlternatePngItemView {
12486 fn render(
12487 &mut self,
12488 _window: &mut Window,
12489 _cx: &mut Context<Self>,
12490 ) -> impl IntoElement {
12491 Empty
12492 }
12493 }
12494
12495 impl ProjectItem for TestAlternatePngItemView {
12496 type Item = TestPngItem;
12497
12498 fn for_project_item(
12499 _project: Entity<Project>,
12500 _pane: Option<&Pane>,
12501 _item: Entity<Self::Item>,
12502 _: &mut Window,
12503 cx: &mut Context<Self>,
12504 ) -> Self
12505 where
12506 Self: Sized,
12507 {
12508 Self {
12509 focus_handle: cx.focus_handle(),
12510 }
12511 }
12512 }
12513
12514 #[gpui::test]
12515 async fn test_register_project_item(cx: &mut TestAppContext) {
12516 init_test(cx);
12517
12518 cx.update(|cx| {
12519 register_project_item::<TestPngItemView>(cx);
12520 register_project_item::<TestIpynbItemView>(cx);
12521 });
12522
12523 let fs = FakeFs::new(cx.executor());
12524 fs.insert_tree(
12525 "/root1",
12526 json!({
12527 "one.png": "BINARYDATAHERE",
12528 "two.ipynb": "{ totally a notebook }",
12529 "three.txt": "editing text, sure why not?"
12530 }),
12531 )
12532 .await;
12533
12534 let project = Project::test(fs, ["root1".as_ref()], cx).await;
12535 let (workspace, cx) =
12536 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12537
12538 let worktree_id = project.update(cx, |project, cx| {
12539 project.worktrees(cx).next().unwrap().read(cx).id()
12540 });
12541
12542 let handle = workspace
12543 .update_in(cx, |workspace, window, cx| {
12544 let project_path = (worktree_id, rel_path("one.png"));
12545 workspace.open_path(project_path, None, true, window, cx)
12546 })
12547 .await
12548 .unwrap();
12549
12550 // Now we can check if the handle we got back errored or not
12551 assert_eq!(
12552 handle.to_any_view().entity_type(),
12553 TypeId::of::<TestPngItemView>()
12554 );
12555
12556 let handle = workspace
12557 .update_in(cx, |workspace, window, cx| {
12558 let project_path = (worktree_id, rel_path("two.ipynb"));
12559 workspace.open_path(project_path, None, true, window, cx)
12560 })
12561 .await
12562 .unwrap();
12563
12564 assert_eq!(
12565 handle.to_any_view().entity_type(),
12566 TypeId::of::<TestIpynbItemView>()
12567 );
12568
12569 let handle = workspace
12570 .update_in(cx, |workspace, window, cx| {
12571 let project_path = (worktree_id, rel_path("three.txt"));
12572 workspace.open_path(project_path, None, true, window, cx)
12573 })
12574 .await;
12575 assert!(handle.is_err());
12576 }
12577
12578 #[gpui::test]
12579 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
12580 init_test(cx);
12581
12582 cx.update(|cx| {
12583 register_project_item::<TestPngItemView>(cx);
12584 register_project_item::<TestAlternatePngItemView>(cx);
12585 });
12586
12587 let fs = FakeFs::new(cx.executor());
12588 fs.insert_tree(
12589 "/root1",
12590 json!({
12591 "one.png": "BINARYDATAHERE",
12592 "two.ipynb": "{ totally a notebook }",
12593 "three.txt": "editing text, sure why not?"
12594 }),
12595 )
12596 .await;
12597 let project = Project::test(fs, ["root1".as_ref()], cx).await;
12598 let (workspace, cx) =
12599 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12600 let worktree_id = project.update(cx, |project, cx| {
12601 project.worktrees(cx).next().unwrap().read(cx).id()
12602 });
12603
12604 let handle = workspace
12605 .update_in(cx, |workspace, window, cx| {
12606 let project_path = (worktree_id, rel_path("one.png"));
12607 workspace.open_path(project_path, None, true, window, cx)
12608 })
12609 .await
12610 .unwrap();
12611
12612 // This _must_ be the second item registered
12613 assert_eq!(
12614 handle.to_any_view().entity_type(),
12615 TypeId::of::<TestAlternatePngItemView>()
12616 );
12617
12618 let handle = workspace
12619 .update_in(cx, |workspace, window, cx| {
12620 let project_path = (worktree_id, rel_path("three.txt"));
12621 workspace.open_path(project_path, None, true, window, cx)
12622 })
12623 .await;
12624 assert!(handle.is_err());
12625 }
12626 }
12627
12628 #[gpui::test]
12629 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
12630 init_test(cx);
12631
12632 let fs = FakeFs::new(cx.executor());
12633 let project = Project::test(fs, [], cx).await;
12634 let (workspace, _cx) =
12635 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12636
12637 // Test with status bar shown (default)
12638 workspace.read_with(cx, |workspace, cx| {
12639 let visible = workspace.status_bar_visible(cx);
12640 assert!(visible, "Status bar should be visible by default");
12641 });
12642
12643 // Test with status bar hidden
12644 cx.update_global(|store: &mut SettingsStore, cx| {
12645 store.update_user_settings(cx, |settings| {
12646 settings.status_bar.get_or_insert_default().show = Some(false);
12647 });
12648 });
12649
12650 workspace.read_with(cx, |workspace, cx| {
12651 let visible = workspace.status_bar_visible(cx);
12652 assert!(!visible, "Status bar should be hidden when show is false");
12653 });
12654
12655 // Test with status bar shown explicitly
12656 cx.update_global(|store: &mut SettingsStore, cx| {
12657 store.update_user_settings(cx, |settings| {
12658 settings.status_bar.get_or_insert_default().show = Some(true);
12659 });
12660 });
12661
12662 workspace.read_with(cx, |workspace, cx| {
12663 let visible = workspace.status_bar_visible(cx);
12664 assert!(visible, "Status bar should be visible when show is true");
12665 });
12666 }
12667
12668 #[gpui::test]
12669 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
12670 init_test(cx);
12671
12672 let fs = FakeFs::new(cx.executor());
12673 let project = Project::test(fs, [], cx).await;
12674 let (workspace, cx) =
12675 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12676 let panel = workspace.update_in(cx, |workspace, window, cx| {
12677 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12678 workspace.add_panel(panel.clone(), window, cx);
12679
12680 workspace
12681 .right_dock()
12682 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12683
12684 panel
12685 });
12686
12687 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12688 let item_a = cx.new(TestItem::new);
12689 let item_b = cx.new(TestItem::new);
12690 let item_a_id = item_a.entity_id();
12691 let item_b_id = item_b.entity_id();
12692
12693 pane.update_in(cx, |pane, window, cx| {
12694 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
12695 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
12696 });
12697
12698 pane.read_with(cx, |pane, _| {
12699 assert_eq!(pane.items_len(), 2);
12700 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
12701 });
12702
12703 workspace.update_in(cx, |workspace, window, cx| {
12704 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12705 });
12706
12707 workspace.update_in(cx, |_, window, cx| {
12708 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12709 });
12710
12711 // Assert that the `pane::CloseActiveItem` action is handled at the
12712 // workspace level when one of the dock panels is focused and, in that
12713 // case, the center pane's active item is closed but the focus is not
12714 // moved.
12715 cx.dispatch_action(pane::CloseActiveItem::default());
12716 cx.run_until_parked();
12717
12718 pane.read_with(cx, |pane, _| {
12719 assert_eq!(pane.items_len(), 1);
12720 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
12721 });
12722
12723 workspace.update_in(cx, |workspace, window, cx| {
12724 assert!(workspace.right_dock().read(cx).is_open());
12725 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12726 });
12727 }
12728
12729 #[gpui::test]
12730 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
12731 init_test(cx);
12732 let fs = FakeFs::new(cx.executor());
12733
12734 let project_a = Project::test(fs.clone(), [], cx).await;
12735 let project_b = Project::test(fs, [], cx).await;
12736
12737 let multi_workspace_handle =
12738 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
12739
12740 let workspace_a = multi_workspace_handle
12741 .read_with(cx, |mw, _| mw.workspace().clone())
12742 .unwrap();
12743
12744 let _workspace_b = multi_workspace_handle
12745 .update(cx, |mw, window, cx| {
12746 mw.test_add_workspace(project_b, window, cx)
12747 })
12748 .unwrap();
12749
12750 // Switch to workspace A
12751 multi_workspace_handle
12752 .update(cx, |mw, window, cx| {
12753 mw.activate_index(0, window, cx);
12754 })
12755 .unwrap();
12756
12757 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
12758
12759 // Add a panel to workspace A's right dock and open the dock
12760 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
12761 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12762 workspace.add_panel(panel.clone(), window, cx);
12763 workspace
12764 .right_dock()
12765 .update(cx, |dock, cx| dock.set_open(true, window, cx));
12766 panel
12767 });
12768
12769 // Focus the panel through the workspace (matching existing test pattern)
12770 workspace_a.update_in(cx, |workspace, window, cx| {
12771 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12772 });
12773
12774 // Zoom the panel
12775 panel.update_in(cx, |panel, window, cx| {
12776 panel.set_zoomed(true, window, cx);
12777 });
12778
12779 // Verify the panel is zoomed and the dock is open
12780 workspace_a.update_in(cx, |workspace, window, cx| {
12781 assert!(
12782 workspace.right_dock().read(cx).is_open(),
12783 "dock should be open before switch"
12784 );
12785 assert!(
12786 panel.is_zoomed(window, cx),
12787 "panel should be zoomed before switch"
12788 );
12789 assert!(
12790 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12791 "panel should be focused before switch"
12792 );
12793 });
12794
12795 // Switch to workspace B
12796 multi_workspace_handle
12797 .update(cx, |mw, window, cx| {
12798 mw.activate_index(1, window, cx);
12799 })
12800 .unwrap();
12801 cx.run_until_parked();
12802
12803 // Switch back to workspace A
12804 multi_workspace_handle
12805 .update(cx, |mw, window, cx| {
12806 mw.activate_index(0, window, cx);
12807 })
12808 .unwrap();
12809 cx.run_until_parked();
12810
12811 // Verify the panel is still zoomed and the dock is still open
12812 workspace_a.update_in(cx, |workspace, window, cx| {
12813 assert!(
12814 workspace.right_dock().read(cx).is_open(),
12815 "dock should still be open after switching back"
12816 );
12817 assert!(
12818 panel.is_zoomed(window, cx),
12819 "panel should still be zoomed after switching back"
12820 );
12821 });
12822 }
12823
12824 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
12825 pane.read(cx)
12826 .items()
12827 .flat_map(|item| {
12828 item.project_paths(cx)
12829 .into_iter()
12830 .map(|path| path.path.display(PathStyle::local()).into_owned())
12831 })
12832 .collect()
12833 }
12834
12835 pub fn init_test(cx: &mut TestAppContext) {
12836 cx.update(|cx| {
12837 let settings_store = SettingsStore::test(cx);
12838 cx.set_global(settings_store);
12839 theme::init(theme::LoadThemes::JustBase, cx);
12840 });
12841 }
12842
12843 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
12844 let item = TestProjectItem::new(id, path, cx);
12845 item.update(cx, |item, _| {
12846 item.is_dirty = true;
12847 });
12848 item
12849 }
12850
12851 #[gpui::test]
12852 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
12853 cx: &mut gpui::TestAppContext,
12854 ) {
12855 init_test(cx);
12856 let fs = FakeFs::new(cx.executor());
12857
12858 let project = Project::test(fs, [], cx).await;
12859 let (workspace, cx) =
12860 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12861
12862 let panel = workspace.update_in(cx, |workspace, window, cx| {
12863 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12864 workspace.add_panel(panel.clone(), window, cx);
12865 workspace
12866 .right_dock()
12867 .update(cx, |dock, cx| dock.set_open(true, window, cx));
12868 panel
12869 });
12870
12871 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12872 pane.update_in(cx, |pane, window, cx| {
12873 let item = cx.new(TestItem::new);
12874 pane.add_item(Box::new(item), true, true, None, window, cx);
12875 });
12876
12877 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
12878 // mirrors the real-world flow and avoids side effects from directly
12879 // focusing the panel while the center pane is active.
12880 workspace.update_in(cx, |workspace, window, cx| {
12881 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12882 });
12883
12884 panel.update_in(cx, |panel, window, cx| {
12885 panel.set_zoomed(true, window, cx);
12886 });
12887
12888 workspace.update_in(cx, |workspace, window, cx| {
12889 assert!(workspace.right_dock().read(cx).is_open());
12890 assert!(panel.is_zoomed(window, cx));
12891 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12892 });
12893
12894 // Simulate a spurious pane::Event::Focus on the center pane while the
12895 // panel still has focus. This mirrors what happens during macOS window
12896 // activation: the center pane fires a focus event even though actual
12897 // focus remains on the dock panel.
12898 pane.update_in(cx, |_, _, cx| {
12899 cx.emit(pane::Event::Focus);
12900 });
12901
12902 // The dock must remain open because the panel had focus at the time the
12903 // event was processed. Before the fix, dock_to_preserve was None for
12904 // panels that don't implement pane(), causing the dock to close.
12905 workspace.update_in(cx, |workspace, window, cx| {
12906 assert!(
12907 workspace.right_dock().read(cx).is_open(),
12908 "Dock should stay open when its zoomed panel (without pane()) still has focus"
12909 );
12910 assert!(panel.is_zoomed(window, cx));
12911 });
12912 }
12913}