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