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