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