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