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