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