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(true, 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(*focus_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(false, 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(true, 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(
4723 &mut self,
4724 focus_changed: bool,
4725 window: &mut Window,
4726 cx: &mut Context<Self>,
4727 ) {
4728 cx.emit(Event::ActiveItemChanged);
4729 let active_entry = self.active_project_path(cx);
4730 self.project.update(cx, |project, cx| {
4731 project.set_active_path(active_entry.clone(), cx)
4732 });
4733
4734 if focus_changed && let Some(project_path) = &active_entry {
4735 let git_store_entity = self.project.read(cx).git_store().clone();
4736 git_store_entity.update(cx, |git_store, cx| {
4737 git_store.set_active_repo_for_path(project_path, cx);
4738 });
4739 }
4740
4741 self.update_window_title(window, cx);
4742 }
4743
4744 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
4745 let project = self.project().read(cx);
4746 let mut title = String::new();
4747
4748 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
4749 let name = {
4750 let settings_location = SettingsLocation {
4751 worktree_id: worktree.read(cx).id(),
4752 path: RelPath::empty(),
4753 };
4754
4755 let settings = WorktreeSettings::get(Some(settings_location), cx);
4756 match &settings.project_name {
4757 Some(name) => name.as_str(),
4758 None => worktree.read(cx).root_name_str(),
4759 }
4760 };
4761 if i > 0 {
4762 title.push_str(", ");
4763 }
4764 title.push_str(name);
4765 }
4766
4767 if title.is_empty() {
4768 title = "empty project".to_string();
4769 }
4770
4771 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
4772 let filename = path.path.file_name().or_else(|| {
4773 Some(
4774 project
4775 .worktree_for_id(path.worktree_id, cx)?
4776 .read(cx)
4777 .root_name_str(),
4778 )
4779 });
4780
4781 if let Some(filename) = filename {
4782 title.push_str(" — ");
4783 title.push_str(filename.as_ref());
4784 }
4785 }
4786
4787 if project.is_via_collab() {
4788 title.push_str(" ↙");
4789 } else if project.is_shared() {
4790 title.push_str(" ↗");
4791 }
4792
4793 if let Some(last_title) = self.last_window_title.as_ref()
4794 && &title == last_title
4795 {
4796 return;
4797 }
4798 window.set_window_title(&title);
4799 SystemWindowTabController::update_tab_title(
4800 cx,
4801 window.window_handle().window_id(),
4802 SharedString::from(&title),
4803 );
4804 self.last_window_title = Some(title);
4805 }
4806
4807 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
4808 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
4809 if is_edited != self.window_edited {
4810 self.window_edited = is_edited;
4811 window.set_window_edited(self.window_edited)
4812 }
4813 }
4814
4815 fn update_item_dirty_state(
4816 &mut self,
4817 item: &dyn ItemHandle,
4818 window: &mut Window,
4819 cx: &mut App,
4820 ) {
4821 let is_dirty = item.is_dirty(cx);
4822 let item_id = item.item_id();
4823 let was_dirty = self.dirty_items.contains_key(&item_id);
4824 if is_dirty == was_dirty {
4825 return;
4826 }
4827 if was_dirty {
4828 self.dirty_items.remove(&item_id);
4829 self.update_window_edited(window, cx);
4830 return;
4831 }
4832 if let Some(window_handle) = window.window_handle().downcast::<Self>() {
4833 let s = item.on_release(
4834 cx,
4835 Box::new(move |cx| {
4836 window_handle
4837 .update(cx, |this, window, cx| {
4838 this.dirty_items.remove(&item_id);
4839 this.update_window_edited(window, cx)
4840 })
4841 .ok();
4842 }),
4843 );
4844 self.dirty_items.insert(item_id, s);
4845 self.update_window_edited(window, cx);
4846 }
4847 }
4848
4849 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
4850 if self.notifications.is_empty() {
4851 None
4852 } else {
4853 Some(
4854 div()
4855 .absolute()
4856 .right_3()
4857 .bottom_3()
4858 .w_112()
4859 .h_full()
4860 .flex()
4861 .flex_col()
4862 .justify_end()
4863 .gap_2()
4864 .children(
4865 self.notifications
4866 .iter()
4867 .map(|(_, notification)| notification.clone().into_any()),
4868 ),
4869 )
4870 }
4871 }
4872
4873 // RPC handlers
4874
4875 fn active_view_for_follower(
4876 &self,
4877 follower_project_id: Option<u64>,
4878 window: &mut Window,
4879 cx: &mut Context<Self>,
4880 ) -> Option<proto::View> {
4881 let (item, panel_id) = self.active_item_for_followers(window, cx);
4882 let item = item?;
4883 let leader_id = self
4884 .pane_for(&*item)
4885 .and_then(|pane| self.leader_for_pane(&pane));
4886 let leader_peer_id = match leader_id {
4887 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
4888 Some(CollaboratorId::Agent) | None => None,
4889 };
4890
4891 let item_handle = item.to_followable_item_handle(cx)?;
4892 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
4893 let variant = item_handle.to_state_proto(window, cx)?;
4894
4895 if item_handle.is_project_item(window, cx)
4896 && (follower_project_id.is_none()
4897 || follower_project_id != self.project.read(cx).remote_id())
4898 {
4899 return None;
4900 }
4901
4902 Some(proto::View {
4903 id: id.to_proto(),
4904 leader_id: leader_peer_id,
4905 variant: Some(variant),
4906 panel_id: panel_id.map(|id| id as i32),
4907 })
4908 }
4909
4910 fn handle_follow(
4911 &mut self,
4912 follower_project_id: Option<u64>,
4913 window: &mut Window,
4914 cx: &mut Context<Self>,
4915 ) -> proto::FollowResponse {
4916 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
4917
4918 cx.notify();
4919 proto::FollowResponse {
4920 // TODO: Remove after version 0.145.x stabilizes.
4921 active_view_id: active_view.as_ref().and_then(|view| view.id.clone()),
4922 views: active_view.iter().cloned().collect(),
4923 active_view,
4924 }
4925 }
4926
4927 fn handle_update_followers(
4928 &mut self,
4929 leader_id: PeerId,
4930 message: proto::UpdateFollowers,
4931 _window: &mut Window,
4932 _cx: &mut Context<Self>,
4933 ) {
4934 self.leader_updates_tx
4935 .unbounded_send((leader_id, message))
4936 .ok();
4937 }
4938
4939 async fn process_leader_update(
4940 this: &WeakEntity<Self>,
4941 leader_id: PeerId,
4942 update: proto::UpdateFollowers,
4943 cx: &mut AsyncWindowContext,
4944 ) -> Result<()> {
4945 match update.variant.context("invalid update")? {
4946 proto::update_followers::Variant::CreateView(view) => {
4947 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
4948 let should_add_view = this.update(cx, |this, _| {
4949 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
4950 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
4951 } else {
4952 anyhow::Ok(false)
4953 }
4954 })??;
4955
4956 if should_add_view {
4957 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
4958 }
4959 }
4960 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
4961 let should_add_view = this.update(cx, |this, _| {
4962 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
4963 state.active_view_id = update_active_view
4964 .view
4965 .as_ref()
4966 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
4967
4968 if state.active_view_id.is_some_and(|view_id| {
4969 !state.items_by_leader_view_id.contains_key(&view_id)
4970 }) {
4971 anyhow::Ok(true)
4972 } else {
4973 anyhow::Ok(false)
4974 }
4975 } else {
4976 anyhow::Ok(false)
4977 }
4978 })??;
4979
4980 if should_add_view && let Some(view) = update_active_view.view {
4981 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
4982 }
4983 }
4984 proto::update_followers::Variant::UpdateView(update_view) => {
4985 let variant = update_view.variant.context("missing update view variant")?;
4986 let id = update_view.id.context("missing update view id")?;
4987 let mut tasks = Vec::new();
4988 this.update_in(cx, |this, window, cx| {
4989 let project = this.project.clone();
4990 if let Some(state) = this.follower_states.get(&leader_id.into()) {
4991 let view_id = ViewId::from_proto(id.clone())?;
4992 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
4993 tasks.push(item.view.apply_update_proto(
4994 &project,
4995 variant.clone(),
4996 window,
4997 cx,
4998 ));
4999 }
5000 }
5001 anyhow::Ok(())
5002 })??;
5003 try_join_all(tasks).await.log_err();
5004 }
5005 }
5006 this.update_in(cx, |this, window, cx| {
5007 this.leader_updated(leader_id, window, cx)
5008 })?;
5009 Ok(())
5010 }
5011
5012 async fn add_view_from_leader(
5013 this: WeakEntity<Self>,
5014 leader_id: PeerId,
5015 view: &proto::View,
5016 cx: &mut AsyncWindowContext,
5017 ) -> Result<()> {
5018 let this = this.upgrade().context("workspace dropped")?;
5019
5020 let Some(id) = view.id.clone() else {
5021 anyhow::bail!("no id for view");
5022 };
5023 let id = ViewId::from_proto(id)?;
5024 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5025
5026 let pane = this.update(cx, |this, _cx| {
5027 let state = this
5028 .follower_states
5029 .get(&leader_id.into())
5030 .context("stopped following")?;
5031 anyhow::Ok(state.pane().clone())
5032 })??;
5033 let existing_item = pane.update_in(cx, |pane, window, cx| {
5034 let client = this.read(cx).client().clone();
5035 pane.items().find_map(|item| {
5036 let item = item.to_followable_item_handle(cx)?;
5037 if item.remote_id(&client, window, cx) == Some(id) {
5038 Some(item)
5039 } else {
5040 None
5041 }
5042 })
5043 })?;
5044 let item = if let Some(existing_item) = existing_item {
5045 existing_item
5046 } else {
5047 let variant = view.variant.clone();
5048 anyhow::ensure!(variant.is_some(), "missing view variant");
5049
5050 let task = cx.update(|window, cx| {
5051 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5052 })?;
5053
5054 let Some(task) = task else {
5055 anyhow::bail!(
5056 "failed to construct view from leader (maybe from a different version of zed?)"
5057 );
5058 };
5059
5060 let mut new_item = task.await?;
5061 pane.update_in(cx, |pane, window, cx| {
5062 let mut item_to_remove = None;
5063 for (ix, item) in pane.items().enumerate() {
5064 if let Some(item) = item.to_followable_item_handle(cx) {
5065 match new_item.dedup(item.as_ref(), window, cx) {
5066 Some(item::Dedup::KeepExisting) => {
5067 new_item =
5068 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5069 break;
5070 }
5071 Some(item::Dedup::ReplaceExisting) => {
5072 item_to_remove = Some((ix, item.item_id()));
5073 break;
5074 }
5075 None => {}
5076 }
5077 }
5078 }
5079
5080 if let Some((ix, id)) = item_to_remove {
5081 pane.remove_item(id, false, false, window, cx);
5082 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5083 }
5084 })?;
5085
5086 new_item
5087 };
5088
5089 this.update_in(cx, |this, window, cx| {
5090 let state = this.follower_states.get_mut(&leader_id.into())?;
5091 item.set_leader_id(Some(leader_id.into()), window, cx);
5092 state.items_by_leader_view_id.insert(
5093 id,
5094 FollowerView {
5095 view: item,
5096 location: panel_id,
5097 },
5098 );
5099
5100 Some(())
5101 })?;
5102
5103 Ok(())
5104 }
5105
5106 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5107 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5108 return;
5109 };
5110
5111 if let Some(agent_location) = self.project.read(cx).agent_location() {
5112 let buffer_entity_id = agent_location.buffer.entity_id();
5113 let view_id = ViewId {
5114 creator: CollaboratorId::Agent,
5115 id: buffer_entity_id.as_u64(),
5116 };
5117 follower_state.active_view_id = Some(view_id);
5118
5119 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5120 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5121 hash_map::Entry::Vacant(entry) => {
5122 let existing_view =
5123 follower_state
5124 .center_pane
5125 .read(cx)
5126 .items()
5127 .find_map(|item| {
5128 let item = item.to_followable_item_handle(cx)?;
5129 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5130 && item.project_item_model_ids(cx).as_slice()
5131 == [buffer_entity_id]
5132 {
5133 Some(item)
5134 } else {
5135 None
5136 }
5137 });
5138 let view = existing_view.or_else(|| {
5139 agent_location.buffer.upgrade().and_then(|buffer| {
5140 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
5141 registry.build_item(buffer, self.project.clone(), None, window, cx)
5142 })?
5143 .to_followable_item_handle(cx)
5144 })
5145 });
5146
5147 view.map(|view| {
5148 entry.insert(FollowerView {
5149 view,
5150 location: None,
5151 })
5152 })
5153 }
5154 };
5155
5156 if let Some(item) = item {
5157 item.view
5158 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
5159 item.view
5160 .update_agent_location(agent_location.position, window, cx);
5161 }
5162 } else {
5163 follower_state.active_view_id = None;
5164 }
5165
5166 self.leader_updated(CollaboratorId::Agent, window, cx);
5167 }
5168
5169 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
5170 let mut is_project_item = true;
5171 let mut update = proto::UpdateActiveView::default();
5172 if window.is_window_active() {
5173 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
5174
5175 if let Some(item) = active_item
5176 && item.item_focus_handle(cx).contains_focused(window, cx)
5177 {
5178 let leader_id = self
5179 .pane_for(&*item)
5180 .and_then(|pane| self.leader_for_pane(&pane));
5181 let leader_peer_id = match leader_id {
5182 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5183 Some(CollaboratorId::Agent) | None => None,
5184 };
5185
5186 if let Some(item) = item.to_followable_item_handle(cx) {
5187 let id = item
5188 .remote_id(&self.app_state.client, window, cx)
5189 .map(|id| id.to_proto());
5190
5191 if let Some(id) = id
5192 && let Some(variant) = item.to_state_proto(window, cx)
5193 {
5194 let view = Some(proto::View {
5195 id: id.clone(),
5196 leader_id: leader_peer_id,
5197 variant: Some(variant),
5198 panel_id: panel_id.map(|id| id as i32),
5199 });
5200
5201 is_project_item = item.is_project_item(window, cx);
5202 update = proto::UpdateActiveView {
5203 view,
5204 // TODO: Remove after version 0.145.x stabilizes.
5205 id,
5206 leader_id: leader_peer_id,
5207 };
5208 };
5209 }
5210 }
5211 }
5212
5213 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
5214 if active_view_id != self.last_active_view_id.as_ref() {
5215 self.last_active_view_id = active_view_id.cloned();
5216 self.update_followers(
5217 is_project_item,
5218 proto::update_followers::Variant::UpdateActiveView(update),
5219 window,
5220 cx,
5221 );
5222 }
5223 }
5224
5225 fn active_item_for_followers(
5226 &self,
5227 window: &mut Window,
5228 cx: &mut App,
5229 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
5230 let mut active_item = None;
5231 let mut panel_id = None;
5232 for dock in self.all_docks() {
5233 if dock.focus_handle(cx).contains_focused(window, cx)
5234 && let Some(panel) = dock.read(cx).active_panel()
5235 && let Some(pane) = panel.pane(cx)
5236 && let Some(item) = pane.read(cx).active_item()
5237 {
5238 active_item = Some(item);
5239 panel_id = panel.remote_id();
5240 break;
5241 }
5242 }
5243
5244 if active_item.is_none() {
5245 active_item = self.active_pane().read(cx).active_item();
5246 }
5247 (active_item, panel_id)
5248 }
5249
5250 fn update_followers(
5251 &self,
5252 project_only: bool,
5253 update: proto::update_followers::Variant,
5254 _: &mut Window,
5255 cx: &mut App,
5256 ) -> Option<()> {
5257 // If this update only applies to for followers in the current project,
5258 // then skip it unless this project is shared. If it applies to all
5259 // followers, regardless of project, then set `project_id` to none,
5260 // indicating that it goes to all followers.
5261 let project_id = if project_only {
5262 Some(self.project.read(cx).remote_id()?)
5263 } else {
5264 None
5265 };
5266 self.app_state().workspace_store.update(cx, |store, cx| {
5267 store.update_followers(project_id, update, cx)
5268 })
5269 }
5270
5271 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
5272 self.follower_states.iter().find_map(|(leader_id, state)| {
5273 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
5274 Some(*leader_id)
5275 } else {
5276 None
5277 }
5278 })
5279 }
5280
5281 fn leader_updated(
5282 &mut self,
5283 leader_id: impl Into<CollaboratorId>,
5284 window: &mut Window,
5285 cx: &mut Context<Self>,
5286 ) -> Option<Box<dyn ItemHandle>> {
5287 cx.notify();
5288
5289 let leader_id = leader_id.into();
5290 let (panel_id, item) = match leader_id {
5291 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
5292 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
5293 };
5294
5295 let state = self.follower_states.get(&leader_id)?;
5296 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
5297 let pane;
5298 if let Some(panel_id) = panel_id {
5299 pane = self
5300 .activate_panel_for_proto_id(panel_id, window, cx)?
5301 .pane(cx)?;
5302 let state = self.follower_states.get_mut(&leader_id)?;
5303 state.dock_pane = Some(pane.clone());
5304 } else {
5305 pane = state.center_pane.clone();
5306 let state = self.follower_states.get_mut(&leader_id)?;
5307 if let Some(dock_pane) = state.dock_pane.take() {
5308 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
5309 }
5310 }
5311
5312 pane.update(cx, |pane, cx| {
5313 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
5314 if let Some(index) = pane.index_for_item(item.as_ref()) {
5315 pane.activate_item(index, false, false, window, cx);
5316 } else {
5317 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
5318 }
5319
5320 if focus_active_item {
5321 pane.focus_active_item(window, cx)
5322 }
5323 });
5324
5325 Some(item)
5326 }
5327
5328 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
5329 let state = self.follower_states.get(&CollaboratorId::Agent)?;
5330 let active_view_id = state.active_view_id?;
5331 Some(
5332 state
5333 .items_by_leader_view_id
5334 .get(&active_view_id)?
5335 .view
5336 .boxed_clone(),
5337 )
5338 }
5339
5340 fn active_item_for_peer(
5341 &self,
5342 peer_id: PeerId,
5343 window: &mut Window,
5344 cx: &mut Context<Self>,
5345 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
5346 let call = self.active_call()?;
5347 let room = call.read(cx).room()?.read(cx);
5348 let participant = room.remote_participant_for_peer_id(peer_id)?;
5349 let leader_in_this_app;
5350 let leader_in_this_project;
5351 match participant.location {
5352 call::ParticipantLocation::SharedProject { project_id } => {
5353 leader_in_this_app = true;
5354 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
5355 }
5356 call::ParticipantLocation::UnsharedProject => {
5357 leader_in_this_app = true;
5358 leader_in_this_project = false;
5359 }
5360 call::ParticipantLocation::External => {
5361 leader_in_this_app = false;
5362 leader_in_this_project = false;
5363 }
5364 };
5365 let state = self.follower_states.get(&peer_id.into())?;
5366 let mut item_to_activate = None;
5367 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
5368 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
5369 && (leader_in_this_project || !item.view.is_project_item(window, cx))
5370 {
5371 item_to_activate = Some((item.location, item.view.boxed_clone()));
5372 }
5373 } else if let Some(shared_screen) =
5374 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
5375 {
5376 item_to_activate = Some((None, Box::new(shared_screen)));
5377 }
5378 item_to_activate
5379 }
5380
5381 fn shared_screen_for_peer(
5382 &self,
5383 peer_id: PeerId,
5384 pane: &Entity<Pane>,
5385 window: &mut Window,
5386 cx: &mut App,
5387 ) -> Option<Entity<SharedScreen>> {
5388 let call = self.active_call()?;
5389 let room = call.read(cx).room()?.clone();
5390 let participant = room.read(cx).remote_participant_for_peer_id(peer_id)?;
5391 let track = participant.video_tracks.values().next()?.clone();
5392 let user = participant.user.clone();
5393
5394 for item in pane.read(cx).items_of_type::<SharedScreen>() {
5395 if item.read(cx).peer_id == peer_id {
5396 return Some(item);
5397 }
5398 }
5399
5400 Some(cx.new(|cx| SharedScreen::new(track, peer_id, user.clone(), room.clone(), window, cx)))
5401 }
5402
5403 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5404 if window.is_window_active() {
5405 self.update_active_view_for_followers(window, cx);
5406
5407 if let Some(database_id) = self.database_id {
5408 cx.background_spawn(persistence::DB.update_timestamp(database_id))
5409 .detach();
5410 }
5411 } else {
5412 for pane in &self.panes {
5413 pane.update(cx, |pane, cx| {
5414 if let Some(item) = pane.active_item() {
5415 item.workspace_deactivated(window, cx);
5416 }
5417 for item in pane.items() {
5418 if matches!(
5419 item.workspace_settings(cx).autosave,
5420 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
5421 ) {
5422 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
5423 .detach_and_log_err(cx);
5424 }
5425 }
5426 });
5427 }
5428 }
5429 }
5430
5431 pub fn active_call(&self) -> Option<&Entity<ActiveCall>> {
5432 self.active_call.as_ref().map(|(call, _)| call)
5433 }
5434
5435 fn on_active_call_event(
5436 &mut self,
5437 _: &Entity<ActiveCall>,
5438 event: &call::room::Event,
5439 window: &mut Window,
5440 cx: &mut Context<Self>,
5441 ) {
5442 match event {
5443 call::room::Event::ParticipantLocationChanged { participant_id }
5444 | call::room::Event::RemoteVideoTracksChanged { participant_id } => {
5445 self.leader_updated(participant_id, window, cx);
5446 }
5447 _ => {}
5448 }
5449 }
5450
5451 pub fn database_id(&self) -> Option<WorkspaceId> {
5452 self.database_id
5453 }
5454
5455 pub fn session_id(&self) -> Option<String> {
5456 self.session_id.clone()
5457 }
5458
5459 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
5460 let project = self.project().read(cx);
5461 project
5462 .visible_worktrees(cx)
5463 .map(|worktree| worktree.read(cx).abs_path())
5464 .collect::<Vec<_>>()
5465 }
5466
5467 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
5468 match member {
5469 Member::Axis(PaneAxis { members, .. }) => {
5470 for child in members.iter() {
5471 self.remove_panes(child.clone(), window, cx)
5472 }
5473 }
5474 Member::Pane(pane) => {
5475 self.force_remove_pane(&pane, &None, window, cx);
5476 }
5477 }
5478 }
5479
5480 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
5481 self.session_id.take();
5482 self.serialize_workspace_internal(window, cx)
5483 }
5484
5485 fn force_remove_pane(
5486 &mut self,
5487 pane: &Entity<Pane>,
5488 focus_on: &Option<Entity<Pane>>,
5489 window: &mut Window,
5490 cx: &mut Context<Workspace>,
5491 ) {
5492 self.panes.retain(|p| p != pane);
5493 if let Some(focus_on) = focus_on {
5494 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
5495 } else if self.active_pane() == pane {
5496 self.panes
5497 .last()
5498 .unwrap()
5499 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
5500 }
5501 if self.last_active_center_pane == Some(pane.downgrade()) {
5502 self.last_active_center_pane = None;
5503 }
5504 cx.notify();
5505 }
5506
5507 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5508 if self._schedule_serialize_workspace.is_none() {
5509 self._schedule_serialize_workspace =
5510 Some(cx.spawn_in(window, async move |this, cx| {
5511 cx.background_executor()
5512 .timer(SERIALIZATION_THROTTLE_TIME)
5513 .await;
5514 this.update_in(cx, |this, window, cx| {
5515 this.serialize_workspace_internal(window, cx).detach();
5516 this._schedule_serialize_workspace.take();
5517 })
5518 .log_err();
5519 }));
5520 }
5521 }
5522
5523 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
5524 let Some(database_id) = self.database_id() else {
5525 return Task::ready(());
5526 };
5527
5528 fn serialize_pane_handle(
5529 pane_handle: &Entity<Pane>,
5530 window: &mut Window,
5531 cx: &mut App,
5532 ) -> SerializedPane {
5533 let (items, active, pinned_count) = {
5534 let pane = pane_handle.read(cx);
5535 let active_item_id = pane.active_item().map(|item| item.item_id());
5536 (
5537 pane.items()
5538 .filter_map(|handle| {
5539 let handle = handle.to_serializable_item_handle(cx)?;
5540
5541 Some(SerializedItem {
5542 kind: Arc::from(handle.serialized_item_kind()),
5543 item_id: handle.item_id().as_u64(),
5544 active: Some(handle.item_id()) == active_item_id,
5545 preview: pane.is_active_preview_item(handle.item_id()),
5546 })
5547 })
5548 .collect::<Vec<_>>(),
5549 pane.has_focus(window, cx),
5550 pane.pinned_count(),
5551 )
5552 };
5553
5554 SerializedPane::new(items, active, pinned_count)
5555 }
5556
5557 fn build_serialized_pane_group(
5558 pane_group: &Member,
5559 window: &mut Window,
5560 cx: &mut App,
5561 ) -> SerializedPaneGroup {
5562 match pane_group {
5563 Member::Axis(PaneAxis {
5564 axis,
5565 members,
5566 flexes,
5567 bounding_boxes: _,
5568 }) => SerializedPaneGroup::Group {
5569 axis: SerializedAxis(*axis),
5570 children: members
5571 .iter()
5572 .map(|member| build_serialized_pane_group(member, window, cx))
5573 .collect::<Vec<_>>(),
5574 flexes: Some(flexes.lock().clone()),
5575 },
5576 Member::Pane(pane_handle) => {
5577 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
5578 }
5579 }
5580 }
5581
5582 fn build_serialized_docks(
5583 this: &Workspace,
5584 window: &mut Window,
5585 cx: &mut App,
5586 ) -> DockStructure {
5587 let left_dock = this.left_dock.read(cx);
5588 let left_visible = left_dock.is_open();
5589 let left_active_panel = left_dock
5590 .active_panel()
5591 .map(|panel| panel.persistent_name().to_string());
5592 let left_dock_zoom = left_dock
5593 .active_panel()
5594 .map(|panel| panel.is_zoomed(window, cx))
5595 .unwrap_or(false);
5596
5597 let right_dock = this.right_dock.read(cx);
5598 let right_visible = right_dock.is_open();
5599 let right_active_panel = right_dock
5600 .active_panel()
5601 .map(|panel| panel.persistent_name().to_string());
5602 let right_dock_zoom = right_dock
5603 .active_panel()
5604 .map(|panel| panel.is_zoomed(window, cx))
5605 .unwrap_or(false);
5606
5607 let bottom_dock = this.bottom_dock.read(cx);
5608 let bottom_visible = bottom_dock.is_open();
5609 let bottom_active_panel = bottom_dock
5610 .active_panel()
5611 .map(|panel| panel.persistent_name().to_string());
5612 let bottom_dock_zoom = bottom_dock
5613 .active_panel()
5614 .map(|panel| panel.is_zoomed(window, cx))
5615 .unwrap_or(false);
5616
5617 DockStructure {
5618 left: DockData {
5619 visible: left_visible,
5620 active_panel: left_active_panel,
5621 zoom: left_dock_zoom,
5622 },
5623 right: DockData {
5624 visible: right_visible,
5625 active_panel: right_active_panel,
5626 zoom: right_dock_zoom,
5627 },
5628 bottom: DockData {
5629 visible: bottom_visible,
5630 active_panel: bottom_active_panel,
5631 zoom: bottom_dock_zoom,
5632 },
5633 }
5634 }
5635
5636 match self.serialize_workspace_location(cx) {
5637 WorkspaceLocation::Location(location, paths) => {
5638 let breakpoints = self.project.update(cx, |project, cx| {
5639 project
5640 .breakpoint_store()
5641 .read(cx)
5642 .all_source_breakpoints(cx)
5643 });
5644 let user_toolchains = self
5645 .project
5646 .read(cx)
5647 .user_toolchains(cx)
5648 .unwrap_or_default();
5649
5650 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
5651 let docks = build_serialized_docks(self, window, cx);
5652 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
5653
5654 let serialized_workspace = SerializedWorkspace {
5655 id: database_id,
5656 location,
5657 paths,
5658 center_group,
5659 window_bounds,
5660 display: Default::default(),
5661 docks,
5662 centered_layout: self.centered_layout,
5663 session_id: self.session_id.clone(),
5664 breakpoints,
5665 window_id: Some(window.window_handle().window_id().as_u64()),
5666 user_toolchains,
5667 };
5668
5669 window.spawn(cx, async move |_| {
5670 persistence::DB.save_workspace(serialized_workspace).await;
5671 })
5672 }
5673 WorkspaceLocation::DetachFromSession => {
5674 let window_bounds = SerializedWindowBounds(window.window_bounds());
5675 let display = window.display(cx).and_then(|d| d.uuid().ok());
5676 window.spawn(cx, async move |_| {
5677 persistence::DB
5678 .set_window_open_status(
5679 database_id,
5680 window_bounds,
5681 display.unwrap_or_default(),
5682 )
5683 .await
5684 .log_err();
5685 persistence::DB
5686 .set_session_id(database_id, None)
5687 .await
5688 .log_err();
5689 })
5690 }
5691 WorkspaceLocation::None => Task::ready(()),
5692 }
5693 }
5694
5695 fn serialize_workspace_location(&self, cx: &App) -> WorkspaceLocation {
5696 let paths = PathList::new(&self.root_paths(cx));
5697 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
5698 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
5699 } else if self.project.read(cx).is_local() {
5700 if !paths.is_empty() {
5701 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
5702 } else {
5703 WorkspaceLocation::DetachFromSession
5704 }
5705 } else {
5706 WorkspaceLocation::None
5707 }
5708 }
5709
5710 fn update_history(&self, cx: &mut App) {
5711 let Some(id) = self.database_id() else {
5712 return;
5713 };
5714 if !self.project.read(cx).is_local() {
5715 return;
5716 }
5717 if let Some(manager) = HistoryManager::global(cx) {
5718 let paths = PathList::new(&self.root_paths(cx));
5719 manager.update(cx, |this, cx| {
5720 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
5721 });
5722 }
5723 }
5724
5725 async fn serialize_items(
5726 this: &WeakEntity<Self>,
5727 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
5728 cx: &mut AsyncWindowContext,
5729 ) -> Result<()> {
5730 const CHUNK_SIZE: usize = 200;
5731
5732 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
5733
5734 while let Some(items_received) = serializable_items.next().await {
5735 let unique_items =
5736 items_received
5737 .into_iter()
5738 .fold(HashMap::default(), |mut acc, item| {
5739 acc.entry(item.item_id()).or_insert(item);
5740 acc
5741 });
5742
5743 // We use into_iter() here so that the references to the items are moved into
5744 // the tasks and not kept alive while we're sleeping.
5745 for (_, item) in unique_items.into_iter() {
5746 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
5747 item.serialize(workspace, false, window, cx)
5748 }) {
5749 cx.background_spawn(async move { task.await.log_err() })
5750 .detach();
5751 }
5752 }
5753
5754 cx.background_executor()
5755 .timer(SERIALIZATION_THROTTLE_TIME)
5756 .await;
5757 }
5758
5759 Ok(())
5760 }
5761
5762 pub(crate) fn enqueue_item_serialization(
5763 &mut self,
5764 item: Box<dyn SerializableItemHandle>,
5765 ) -> Result<()> {
5766 self.serializable_items_tx
5767 .unbounded_send(item)
5768 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
5769 }
5770
5771 pub(crate) fn load_workspace(
5772 serialized_workspace: SerializedWorkspace,
5773 paths_to_open: Vec<Option<ProjectPath>>,
5774 window: &mut Window,
5775 cx: &mut Context<Workspace>,
5776 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
5777 cx.spawn_in(window, async move |workspace, cx| {
5778 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
5779
5780 let mut center_group = None;
5781 let mut center_items = None;
5782
5783 // Traverse the splits tree and add to things
5784 if let Some((group, active_pane, items)) = serialized_workspace
5785 .center_group
5786 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
5787 .await
5788 {
5789 center_items = Some(items);
5790 center_group = Some((group, active_pane))
5791 }
5792
5793 let mut items_by_project_path = HashMap::default();
5794 let mut item_ids_by_kind = HashMap::default();
5795 let mut all_deserialized_items = Vec::default();
5796 cx.update(|_, cx| {
5797 for item in center_items.unwrap_or_default().into_iter().flatten() {
5798 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
5799 item_ids_by_kind
5800 .entry(serializable_item_handle.serialized_item_kind())
5801 .or_insert(Vec::new())
5802 .push(item.item_id().as_u64() as ItemId);
5803 }
5804
5805 if let Some(project_path) = item.project_path(cx) {
5806 items_by_project_path.insert(project_path, item.clone());
5807 }
5808 all_deserialized_items.push(item);
5809 }
5810 })?;
5811
5812 let opened_items = paths_to_open
5813 .into_iter()
5814 .map(|path_to_open| {
5815 path_to_open
5816 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
5817 })
5818 .collect::<Vec<_>>();
5819
5820 // Remove old panes from workspace panes list
5821 workspace.update_in(cx, |workspace, window, cx| {
5822 if let Some((center_group, active_pane)) = center_group {
5823 workspace.remove_panes(workspace.center.root.clone(), window, cx);
5824
5825 // Swap workspace center group
5826 workspace.center = PaneGroup::with_root(center_group);
5827 workspace.center.set_is_center(true);
5828 workspace.center.mark_positions(cx);
5829
5830 if let Some(active_pane) = active_pane {
5831 workspace.set_active_pane(&active_pane, window, cx);
5832 cx.focus_self(window);
5833 } else {
5834 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
5835 }
5836 }
5837
5838 let docks = serialized_workspace.docks;
5839
5840 for (dock, serialized_dock) in [
5841 (&mut workspace.right_dock, docks.right),
5842 (&mut workspace.left_dock, docks.left),
5843 (&mut workspace.bottom_dock, docks.bottom),
5844 ]
5845 .iter_mut()
5846 {
5847 dock.update(cx, |dock, cx| {
5848 dock.serialized_dock = Some(serialized_dock.clone());
5849 dock.restore_state(window, cx);
5850 });
5851 }
5852
5853 cx.notify();
5854 })?;
5855
5856 let _ = project
5857 .update(cx, |project, cx| {
5858 project
5859 .breakpoint_store()
5860 .update(cx, |breakpoint_store, cx| {
5861 breakpoint_store
5862 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
5863 })
5864 })?
5865 .await;
5866
5867 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
5868 // after loading the items, we might have different items and in order to avoid
5869 // the database filling up, we delete items that haven't been loaded now.
5870 //
5871 // The items that have been loaded, have been saved after they've been added to the workspace.
5872 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
5873 item_ids_by_kind
5874 .into_iter()
5875 .map(|(item_kind, loaded_items)| {
5876 SerializableItemRegistry::cleanup(
5877 item_kind,
5878 serialized_workspace.id,
5879 loaded_items,
5880 window,
5881 cx,
5882 )
5883 .log_err()
5884 })
5885 .collect::<Vec<_>>()
5886 })?;
5887
5888 futures::future::join_all(clean_up_tasks).await;
5889
5890 workspace
5891 .update_in(cx, |workspace, window, cx| {
5892 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
5893 workspace.serialize_workspace_internal(window, cx).detach();
5894
5895 // Ensure that we mark the window as edited if we did load dirty items
5896 workspace.update_window_edited(window, cx);
5897 })
5898 .ok();
5899
5900 Ok(opened_items)
5901 })
5902 }
5903
5904 fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
5905 self.add_workspace_actions_listeners(div, window, cx)
5906 .on_action(cx.listener(
5907 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
5908 for action in &action_sequence.0 {
5909 window.dispatch_action(action.boxed_clone(), cx);
5910 }
5911 },
5912 ))
5913 .on_action(cx.listener(Self::close_inactive_items_and_panes))
5914 .on_action(cx.listener(Self::close_all_items_and_panes))
5915 .on_action(cx.listener(Self::save_all))
5916 .on_action(cx.listener(Self::send_keystrokes))
5917 .on_action(cx.listener(Self::add_folder_to_project))
5918 .on_action(cx.listener(Self::follow_next_collaborator))
5919 .on_action(cx.listener(Self::close_window))
5920 .on_action(cx.listener(Self::activate_pane_at_index))
5921 .on_action(cx.listener(Self::move_item_to_pane_at_index))
5922 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
5923 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
5924 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
5925 let pane = workspace.active_pane().clone();
5926 workspace.unfollow_in_pane(&pane, window, cx);
5927 }))
5928 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
5929 workspace
5930 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
5931 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
5932 }))
5933 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
5934 workspace
5935 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
5936 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
5937 }))
5938 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
5939 workspace
5940 .save_active_item(SaveIntent::SaveAs, window, cx)
5941 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
5942 }))
5943 .on_action(
5944 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
5945 workspace.activate_previous_pane(window, cx)
5946 }),
5947 )
5948 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
5949 workspace.activate_next_pane(window, cx)
5950 }))
5951 .on_action(
5952 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
5953 workspace.activate_next_window(cx)
5954 }),
5955 )
5956 .on_action(
5957 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
5958 workspace.activate_previous_window(cx)
5959 }),
5960 )
5961 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
5962 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
5963 }))
5964 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
5965 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
5966 }))
5967 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
5968 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
5969 }))
5970 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
5971 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
5972 }))
5973 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
5974 workspace.activate_next_pane(window, cx)
5975 }))
5976 .on_action(cx.listener(
5977 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
5978 workspace.move_item_to_pane_in_direction(action, window, cx)
5979 },
5980 ))
5981 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
5982 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
5983 }))
5984 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
5985 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
5986 }))
5987 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
5988 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
5989 }))
5990 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
5991 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
5992 }))
5993 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
5994 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
5995 SplitDirection::Down,
5996 SplitDirection::Up,
5997 SplitDirection::Right,
5998 SplitDirection::Left,
5999 ];
6000 for dir in DIRECTION_PRIORITY {
6001 if workspace.find_pane_in_direction(dir, cx).is_some() {
6002 workspace.swap_pane_in_direction(dir, cx);
6003 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6004 break;
6005 }
6006 }
6007 }))
6008 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6009 workspace.move_pane_to_border(SplitDirection::Left, cx)
6010 }))
6011 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6012 workspace.move_pane_to_border(SplitDirection::Right, cx)
6013 }))
6014 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6015 workspace.move_pane_to_border(SplitDirection::Up, cx)
6016 }))
6017 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6018 workspace.move_pane_to_border(SplitDirection::Down, cx)
6019 }))
6020 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6021 this.toggle_dock(DockPosition::Left, window, cx);
6022 }))
6023 .on_action(cx.listener(
6024 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6025 workspace.toggle_dock(DockPosition::Right, window, cx);
6026 },
6027 ))
6028 .on_action(cx.listener(
6029 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6030 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6031 },
6032 ))
6033 .on_action(cx.listener(
6034 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6035 if !workspace.close_active_dock(window, cx) {
6036 cx.propagate();
6037 }
6038 },
6039 ))
6040 .on_action(
6041 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6042 workspace.close_all_docks(window, cx);
6043 }),
6044 )
6045 .on_action(cx.listener(Self::toggle_all_docks))
6046 .on_action(cx.listener(
6047 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6048 workspace.clear_all_notifications(cx);
6049 },
6050 ))
6051 .on_action(cx.listener(
6052 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6053 workspace.clear_navigation_history(window, cx);
6054 },
6055 ))
6056 .on_action(cx.listener(
6057 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6058 if let Some((notification_id, _)) = workspace.notifications.pop() {
6059 workspace.suppress_notification(¬ification_id, cx);
6060 }
6061 },
6062 ))
6063 .on_action(cx.listener(
6064 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
6065 workspace.show_worktree_trust_security_modal(true, window, cx);
6066 },
6067 ))
6068 .on_action(
6069 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
6070 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
6071 trusted_worktrees.update(cx, |trusted_worktrees, _| {
6072 trusted_worktrees.clear_trusted_paths()
6073 });
6074 let clear_task = persistence::DB.clear_trusted_worktrees();
6075 cx.spawn(async move |_, cx| {
6076 if clear_task.await.log_err().is_some() {
6077 cx.update(|cx| reload(cx)).ok();
6078 }
6079 })
6080 .detach();
6081 }
6082 }),
6083 )
6084 .on_action(cx.listener(
6085 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
6086 workspace.reopen_closed_item(window, cx).detach();
6087 },
6088 ))
6089 .on_action(cx.listener(
6090 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
6091 for dock in workspace.all_docks() {
6092 if dock.focus_handle(cx).contains_focused(window, cx) {
6093 let Some(panel) = dock.read(cx).active_panel() else {
6094 return;
6095 };
6096
6097 // Set to `None`, then the size will fall back to the default.
6098 panel.clone().set_size(None, window, cx);
6099
6100 return;
6101 }
6102 }
6103 },
6104 ))
6105 .on_action(cx.listener(
6106 |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
6107 for dock in workspace.all_docks() {
6108 if let Some(panel) = dock.read(cx).visible_panel() {
6109 // Set to `None`, then the size will fall back to the default.
6110 panel.clone().set_size(None, window, cx);
6111 }
6112 }
6113 },
6114 ))
6115 .on_action(cx.listener(
6116 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
6117 adjust_active_dock_size_by_px(
6118 px_with_ui_font_fallback(act.px, cx),
6119 workspace,
6120 window,
6121 cx,
6122 );
6123 },
6124 ))
6125 .on_action(cx.listener(
6126 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
6127 adjust_active_dock_size_by_px(
6128 px_with_ui_font_fallback(act.px, cx) * -1.,
6129 workspace,
6130 window,
6131 cx,
6132 );
6133 },
6134 ))
6135 .on_action(cx.listener(
6136 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
6137 adjust_open_docks_size_by_px(
6138 px_with_ui_font_fallback(act.px, cx),
6139 workspace,
6140 window,
6141 cx,
6142 );
6143 },
6144 ))
6145 .on_action(cx.listener(
6146 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
6147 adjust_open_docks_size_by_px(
6148 px_with_ui_font_fallback(act.px, cx) * -1.,
6149 workspace,
6150 window,
6151 cx,
6152 );
6153 },
6154 ))
6155 .on_action(cx.listener(Workspace::toggle_centered_layout))
6156 .on_action(cx.listener(
6157 |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
6158 if let Some(active_dock) = workspace.active_dock(window, cx) {
6159 let dock = active_dock.read(cx);
6160 if let Some(active_panel) = dock.active_panel() {
6161 if active_panel.pane(cx).is_none() {
6162 let mut recent_pane: Option<Entity<Pane>> = None;
6163 let mut recent_timestamp = 0;
6164 for pane_handle in workspace.panes() {
6165 let pane = pane_handle.read(cx);
6166 for entry in pane.activation_history() {
6167 if entry.timestamp > recent_timestamp {
6168 recent_timestamp = entry.timestamp;
6169 recent_pane = Some(pane_handle.clone());
6170 }
6171 }
6172 }
6173
6174 if let Some(pane) = recent_pane {
6175 pane.update(cx, |pane, cx| {
6176 let current_index = pane.active_item_index();
6177 let items_len = pane.items_len();
6178 if items_len > 0 {
6179 let next_index = if current_index + 1 < items_len {
6180 current_index + 1
6181 } else {
6182 0
6183 };
6184 pane.activate_item(
6185 next_index, false, false, window, cx,
6186 );
6187 }
6188 });
6189 return;
6190 }
6191 }
6192 }
6193 }
6194 cx.propagate();
6195 },
6196 ))
6197 .on_action(cx.listener(
6198 |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
6199 if let Some(active_dock) = workspace.active_dock(window, cx) {
6200 let dock = active_dock.read(cx);
6201 if let Some(active_panel) = dock.active_panel() {
6202 if active_panel.pane(cx).is_none() {
6203 let mut recent_pane: Option<Entity<Pane>> = None;
6204 let mut recent_timestamp = 0;
6205 for pane_handle in workspace.panes() {
6206 let pane = pane_handle.read(cx);
6207 for entry in pane.activation_history() {
6208 if entry.timestamp > recent_timestamp {
6209 recent_timestamp = entry.timestamp;
6210 recent_pane = Some(pane_handle.clone());
6211 }
6212 }
6213 }
6214
6215 if let Some(pane) = recent_pane {
6216 pane.update(cx, |pane, cx| {
6217 let current_index = pane.active_item_index();
6218 let items_len = pane.items_len();
6219 if items_len > 0 {
6220 let prev_index = if current_index > 0 {
6221 current_index - 1
6222 } else {
6223 items_len.saturating_sub(1)
6224 };
6225 pane.activate_item(
6226 prev_index, false, false, window, cx,
6227 );
6228 }
6229 });
6230 return;
6231 }
6232 }
6233 }
6234 }
6235 cx.propagate();
6236 },
6237 ))
6238 .on_action(cx.listener(Workspace::cancel))
6239 }
6240
6241 #[cfg(any(test, feature = "test-support"))]
6242 pub fn set_random_database_id(&mut self) {
6243 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
6244 }
6245
6246 #[cfg(any(test, feature = "test-support"))]
6247 pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
6248 use node_runtime::NodeRuntime;
6249 use session::Session;
6250
6251 let client = project.read(cx).client();
6252 let user_store = project.read(cx).user_store();
6253 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
6254 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
6255 window.activate_window();
6256 let app_state = Arc::new(AppState {
6257 languages: project.read(cx).languages().clone(),
6258 workspace_store,
6259 client,
6260 user_store,
6261 fs: project.read(cx).fs().clone(),
6262 build_window_options: |_, _| Default::default(),
6263 node_runtime: NodeRuntime::unavailable(),
6264 session,
6265 });
6266 let workspace = Self::new(Default::default(), project, app_state, window, cx);
6267 workspace
6268 .active_pane
6269 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6270 workspace
6271 }
6272
6273 pub fn register_action<A: Action>(
6274 &mut self,
6275 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
6276 ) -> &mut Self {
6277 let callback = Arc::new(callback);
6278
6279 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
6280 let callback = callback.clone();
6281 div.on_action(cx.listener(move |workspace, event, window, cx| {
6282 (callback)(workspace, event, window, cx)
6283 }))
6284 }));
6285 self
6286 }
6287 pub fn register_action_renderer(
6288 &mut self,
6289 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
6290 ) -> &mut Self {
6291 self.workspace_actions.push(Box::new(callback));
6292 self
6293 }
6294
6295 fn add_workspace_actions_listeners(
6296 &self,
6297 mut div: Div,
6298 window: &mut Window,
6299 cx: &mut Context<Self>,
6300 ) -> Div {
6301 for action in self.workspace_actions.iter() {
6302 div = (action)(div, self, window, cx)
6303 }
6304 div
6305 }
6306
6307 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
6308 self.modal_layer.read(cx).has_active_modal()
6309 }
6310
6311 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
6312 self.modal_layer.read(cx).active_modal()
6313 }
6314
6315 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
6316 where
6317 B: FnOnce(&mut Window, &mut Context<V>) -> V,
6318 {
6319 self.modal_layer.update(cx, |modal_layer, cx| {
6320 modal_layer.toggle_modal(window, cx, build)
6321 })
6322 }
6323
6324 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
6325 self.modal_layer
6326 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
6327 }
6328
6329 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
6330 self.toast_layer
6331 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
6332 }
6333
6334 pub fn toggle_centered_layout(
6335 &mut self,
6336 _: &ToggleCenteredLayout,
6337 _: &mut Window,
6338 cx: &mut Context<Self>,
6339 ) {
6340 self.centered_layout = !self.centered_layout;
6341 if let Some(database_id) = self.database_id() {
6342 cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
6343 .detach_and_log_err(cx);
6344 }
6345 cx.notify();
6346 }
6347
6348 fn adjust_padding(padding: Option<f32>) -> f32 {
6349 padding
6350 .unwrap_or(CenteredPaddingSettings::default().0)
6351 .clamp(
6352 CenteredPaddingSettings::MIN_PADDING,
6353 CenteredPaddingSettings::MAX_PADDING,
6354 )
6355 }
6356
6357 fn render_dock(
6358 &self,
6359 position: DockPosition,
6360 dock: &Entity<Dock>,
6361 window: &mut Window,
6362 cx: &mut App,
6363 ) -> Option<Div> {
6364 if self.zoomed_position == Some(position) {
6365 return None;
6366 }
6367
6368 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
6369 let pane = panel.pane(cx)?;
6370 let follower_states = &self.follower_states;
6371 leader_border_for_pane(follower_states, &pane, window, cx)
6372 });
6373
6374 Some(
6375 div()
6376 .flex()
6377 .flex_none()
6378 .overflow_hidden()
6379 .child(dock.clone())
6380 .children(leader_border),
6381 )
6382 }
6383
6384 pub fn for_window(window: &mut Window, _: &mut App) -> Option<Entity<Workspace>> {
6385 window.root().flatten()
6386 }
6387
6388 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
6389 self.zoomed.as_ref()
6390 }
6391
6392 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
6393 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
6394 return;
6395 };
6396 let windows = cx.windows();
6397 let next_window =
6398 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
6399 || {
6400 windows
6401 .iter()
6402 .cycle()
6403 .skip_while(|window| window.window_id() != current_window_id)
6404 .nth(1)
6405 },
6406 );
6407
6408 if let Some(window) = next_window {
6409 window
6410 .update(cx, |_, window, _| window.activate_window())
6411 .ok();
6412 }
6413 }
6414
6415 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
6416 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
6417 return;
6418 };
6419 let windows = cx.windows();
6420 let prev_window =
6421 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
6422 || {
6423 windows
6424 .iter()
6425 .rev()
6426 .cycle()
6427 .skip_while(|window| window.window_id() != current_window_id)
6428 .nth(1)
6429 },
6430 );
6431
6432 if let Some(window) = prev_window {
6433 window
6434 .update(cx, |_, window, _| window.activate_window())
6435 .ok();
6436 }
6437 }
6438
6439 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
6440 if cx.stop_active_drag(window) {
6441 } else if let Some((notification_id, _)) = self.notifications.pop() {
6442 dismiss_app_notification(¬ification_id, cx);
6443 } else {
6444 cx.propagate();
6445 }
6446 }
6447
6448 fn adjust_dock_size_by_px(
6449 &mut self,
6450 panel_size: Pixels,
6451 dock_pos: DockPosition,
6452 px: Pixels,
6453 window: &mut Window,
6454 cx: &mut Context<Self>,
6455 ) {
6456 match dock_pos {
6457 DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
6458 DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
6459 DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
6460 }
6461 }
6462
6463 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6464 let size = new_size.min(self.bounds.right() - RESIZE_HANDLE_SIZE);
6465
6466 self.left_dock.update(cx, |left_dock, cx| {
6467 if WorkspaceSettings::get_global(cx)
6468 .resize_all_panels_in_dock
6469 .contains(&DockPosition::Left)
6470 {
6471 left_dock.resize_all_panels(Some(size), window, cx);
6472 } else {
6473 left_dock.resize_active_panel(Some(size), window, cx);
6474 }
6475 });
6476 self.clamp_utility_pane_widths(window, cx);
6477 }
6478
6479 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6480 let mut size = new_size.max(self.bounds.left() - RESIZE_HANDLE_SIZE);
6481 self.left_dock.read_with(cx, |left_dock, cx| {
6482 let left_dock_size = left_dock
6483 .active_panel_size(window, cx)
6484 .unwrap_or(Pixels::ZERO);
6485 if left_dock_size + size > self.bounds.right() {
6486 size = self.bounds.right() - left_dock_size
6487 }
6488 });
6489 self.right_dock.update(cx, |right_dock, cx| {
6490 if WorkspaceSettings::get_global(cx)
6491 .resize_all_panels_in_dock
6492 .contains(&DockPosition::Right)
6493 {
6494 right_dock.resize_all_panels(Some(size), window, cx);
6495 } else {
6496 right_dock.resize_active_panel(Some(size), window, cx);
6497 }
6498 });
6499 self.clamp_utility_pane_widths(window, cx);
6500 }
6501
6502 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6503 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
6504 self.bottom_dock.update(cx, |bottom_dock, cx| {
6505 if WorkspaceSettings::get_global(cx)
6506 .resize_all_panels_in_dock
6507 .contains(&DockPosition::Bottom)
6508 {
6509 bottom_dock.resize_all_panels(Some(size), window, cx);
6510 } else {
6511 bottom_dock.resize_active_panel(Some(size), window, cx);
6512 }
6513 });
6514 self.clamp_utility_pane_widths(window, cx);
6515 }
6516
6517 fn max_utility_pane_width(&self, window: &Window, cx: &App) -> Pixels {
6518 let left_dock_width = self
6519 .left_dock
6520 .read(cx)
6521 .active_panel_size(window, cx)
6522 .unwrap_or(px(0.0));
6523 let right_dock_width = self
6524 .right_dock
6525 .read(cx)
6526 .active_panel_size(window, cx)
6527 .unwrap_or(px(0.0));
6528 let center_pane_width = self.bounds.size.width - left_dock_width - right_dock_width;
6529 center_pane_width - px(10.0)
6530 }
6531
6532 fn clamp_utility_pane_widths(&mut self, window: &mut Window, cx: &mut App) {
6533 let max_width = self.max_utility_pane_width(window, cx);
6534
6535 // Clamp left slot utility pane if it exists
6536 if let Some(handle) = self.utility_pane(UtilityPaneSlot::Left) {
6537 let current_width = handle.width(cx);
6538 if current_width > max_width {
6539 handle.set_width(Some(max_width.max(UTILITY_PANE_MIN_WIDTH)), cx);
6540 }
6541 }
6542
6543 // Clamp right slot utility pane if it exists
6544 if let Some(handle) = self.utility_pane(UtilityPaneSlot::Right) {
6545 let current_width = handle.width(cx);
6546 if current_width > max_width {
6547 handle.set_width(Some(max_width.max(UTILITY_PANE_MIN_WIDTH)), cx);
6548 }
6549 }
6550 }
6551
6552 fn toggle_edit_predictions_all_files(
6553 &mut self,
6554 _: &ToggleEditPrediction,
6555 _window: &mut Window,
6556 cx: &mut Context<Self>,
6557 ) {
6558 let fs = self.project().read(cx).fs().clone();
6559 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
6560 update_settings_file(fs, cx, move |file, _| {
6561 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
6562 });
6563 }
6564
6565 pub fn show_worktree_trust_security_modal(
6566 &mut self,
6567 toggle: bool,
6568 window: &mut Window,
6569 cx: &mut Context<Self>,
6570 ) {
6571 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
6572 if toggle {
6573 security_modal.update(cx, |security_modal, cx| {
6574 security_modal.dismiss(cx);
6575 })
6576 } else {
6577 security_modal.update(cx, |security_modal, cx| {
6578 security_modal.refresh_restricted_paths(cx);
6579 });
6580 }
6581 } else {
6582 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
6583 .map(|trusted_worktrees| {
6584 trusted_worktrees
6585 .read(cx)
6586 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
6587 })
6588 .unwrap_or(false);
6589 if has_restricted_worktrees {
6590 let project = self.project().read(cx);
6591 let remote_host = project.remote_connection_options(cx);
6592 let worktree_store = project.worktree_store().downgrade();
6593 self.toggle_modal(window, cx, |_, cx| {
6594 SecurityModal::new(worktree_store, remote_host, cx)
6595 });
6596 }
6597 }
6598 }
6599
6600 fn update_worktree_data(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) {
6601 self.update_window_title(window, cx);
6602 self.serialize_workspace(window, cx);
6603 // This event could be triggered by `AddFolderToProject` or `RemoveFromProject`.
6604 self.update_history(cx);
6605 }
6606}
6607
6608fn leader_border_for_pane(
6609 follower_states: &HashMap<CollaboratorId, FollowerState>,
6610 pane: &Entity<Pane>,
6611 _: &Window,
6612 cx: &App,
6613) -> Option<Div> {
6614 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
6615 if state.pane() == pane {
6616 Some((*leader_id, state))
6617 } else {
6618 None
6619 }
6620 })?;
6621
6622 let mut leader_color = match leader_id {
6623 CollaboratorId::PeerId(leader_peer_id) => {
6624 let room = ActiveCall::try_global(cx)?.read(cx).room()?.read(cx);
6625 let leader = room.remote_participant_for_peer_id(leader_peer_id)?;
6626
6627 cx.theme()
6628 .players()
6629 .color_for_participant(leader.participant_index.0)
6630 .cursor
6631 }
6632 CollaboratorId::Agent => cx.theme().players().agent().cursor,
6633 };
6634 leader_color.fade_out(0.3);
6635 Some(
6636 div()
6637 .absolute()
6638 .size_full()
6639 .left_0()
6640 .top_0()
6641 .border_2()
6642 .border_color(leader_color),
6643 )
6644}
6645
6646fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
6647 ZED_WINDOW_POSITION
6648 .zip(*ZED_WINDOW_SIZE)
6649 .map(|(position, size)| Bounds {
6650 origin: position,
6651 size,
6652 })
6653}
6654
6655fn open_items(
6656 serialized_workspace: Option<SerializedWorkspace>,
6657 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
6658 window: &mut Window,
6659 cx: &mut Context<Workspace>,
6660) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
6661 let restored_items = serialized_workspace.map(|serialized_workspace| {
6662 Workspace::load_workspace(
6663 serialized_workspace,
6664 project_paths_to_open
6665 .iter()
6666 .map(|(_, project_path)| project_path)
6667 .cloned()
6668 .collect(),
6669 window,
6670 cx,
6671 )
6672 });
6673
6674 cx.spawn_in(window, async move |workspace, cx| {
6675 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
6676
6677 if let Some(restored_items) = restored_items {
6678 let restored_items = restored_items.await?;
6679
6680 let restored_project_paths = restored_items
6681 .iter()
6682 .filter_map(|item| {
6683 cx.update(|_, cx| item.as_ref()?.project_path(cx))
6684 .ok()
6685 .flatten()
6686 })
6687 .collect::<HashSet<_>>();
6688
6689 for restored_item in restored_items {
6690 opened_items.push(restored_item.map(Ok));
6691 }
6692
6693 project_paths_to_open
6694 .iter_mut()
6695 .for_each(|(_, project_path)| {
6696 if let Some(project_path_to_open) = project_path
6697 && restored_project_paths.contains(project_path_to_open)
6698 {
6699 *project_path = None;
6700 }
6701 });
6702 } else {
6703 for _ in 0..project_paths_to_open.len() {
6704 opened_items.push(None);
6705 }
6706 }
6707 assert!(opened_items.len() == project_paths_to_open.len());
6708
6709 let tasks =
6710 project_paths_to_open
6711 .into_iter()
6712 .enumerate()
6713 .map(|(ix, (abs_path, project_path))| {
6714 let workspace = workspace.clone();
6715 cx.spawn(async move |cx| {
6716 let file_project_path = project_path?;
6717 let abs_path_task = workspace.update(cx, |workspace, cx| {
6718 workspace.project().update(cx, |project, cx| {
6719 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
6720 })
6721 });
6722
6723 // We only want to open file paths here. If one of the items
6724 // here is a directory, it was already opened further above
6725 // with a `find_or_create_worktree`.
6726 if let Ok(task) = abs_path_task
6727 && task.await.is_none_or(|p| p.is_file())
6728 {
6729 return Some((
6730 ix,
6731 workspace
6732 .update_in(cx, |workspace, window, cx| {
6733 workspace.open_path(
6734 file_project_path,
6735 None,
6736 true,
6737 window,
6738 cx,
6739 )
6740 })
6741 .log_err()?
6742 .await,
6743 ));
6744 }
6745 None
6746 })
6747 });
6748
6749 let tasks = tasks.collect::<Vec<_>>();
6750
6751 let tasks = futures::future::join_all(tasks);
6752 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
6753 opened_items[ix] = Some(path_open_result);
6754 }
6755
6756 Ok(opened_items)
6757 })
6758}
6759
6760enum ActivateInDirectionTarget {
6761 Pane(Entity<Pane>),
6762 Dock(Entity<Dock>),
6763}
6764
6765fn notify_if_database_failed(workspace: WindowHandle<Workspace>, cx: &mut AsyncApp) {
6766 workspace
6767 .update(cx, |workspace, _, cx| {
6768 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
6769 struct DatabaseFailedNotification;
6770
6771 workspace.show_notification(
6772 NotificationId::unique::<DatabaseFailedNotification>(),
6773 cx,
6774 |cx| {
6775 cx.new(|cx| {
6776 MessageNotification::new("Failed to load the database file.", cx)
6777 .primary_message("File an Issue")
6778 .primary_icon(IconName::Plus)
6779 .primary_on_click(|window, cx| {
6780 window.dispatch_action(Box::new(FileBugReport), cx)
6781 })
6782 })
6783 },
6784 );
6785 }
6786 })
6787 .log_err();
6788}
6789
6790fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
6791 if val == 0 {
6792 ThemeSettings::get_global(cx).ui_font_size(cx)
6793 } else {
6794 px(val as f32)
6795 }
6796}
6797
6798fn adjust_active_dock_size_by_px(
6799 px: Pixels,
6800 workspace: &mut Workspace,
6801 window: &mut Window,
6802 cx: &mut Context<Workspace>,
6803) {
6804 let Some(active_dock) = workspace
6805 .all_docks()
6806 .into_iter()
6807 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
6808 else {
6809 return;
6810 };
6811 let dock = active_dock.read(cx);
6812 let Some(panel_size) = dock.active_panel_size(window, cx) else {
6813 return;
6814 };
6815 let dock_pos = dock.position();
6816 workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
6817}
6818
6819fn adjust_open_docks_size_by_px(
6820 px: Pixels,
6821 workspace: &mut Workspace,
6822 window: &mut Window,
6823 cx: &mut Context<Workspace>,
6824) {
6825 let docks = workspace
6826 .all_docks()
6827 .into_iter()
6828 .filter_map(|dock| {
6829 if dock.read(cx).is_open() {
6830 let dock = dock.read(cx);
6831 let panel_size = dock.active_panel_size(window, cx)?;
6832 let dock_pos = dock.position();
6833 Some((panel_size, dock_pos, px))
6834 } else {
6835 None
6836 }
6837 })
6838 .collect::<Vec<_>>();
6839
6840 docks
6841 .into_iter()
6842 .for_each(|(panel_size, dock_pos, offset)| {
6843 workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
6844 });
6845}
6846
6847impl Focusable for Workspace {
6848 fn focus_handle(&self, cx: &App) -> FocusHandle {
6849 self.active_pane.focus_handle(cx)
6850 }
6851}
6852
6853#[derive(Clone)]
6854struct DraggedDock(DockPosition);
6855
6856impl Render for DraggedDock {
6857 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
6858 gpui::Empty
6859 }
6860}
6861
6862impl Render for Workspace {
6863 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
6864 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
6865 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
6866 log::info!("Rendered first frame");
6867 }
6868 let mut context = KeyContext::new_with_defaults();
6869 context.add("Workspace");
6870 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6871 if let Some(status) = self
6872 .debugger_provider
6873 .as_ref()
6874 .and_then(|provider| provider.active_thread_state(cx))
6875 {
6876 match status {
6877 ThreadStatus::Running | ThreadStatus::Stepping => {
6878 context.add("debugger_running");
6879 }
6880 ThreadStatus::Stopped => context.add("debugger_stopped"),
6881 ThreadStatus::Exited | ThreadStatus::Ended => {}
6882 }
6883 }
6884
6885 if self.left_dock.read(cx).is_open() {
6886 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6887 context.set("left_dock", active_panel.panel_key());
6888 }
6889 }
6890
6891 if self.right_dock.read(cx).is_open() {
6892 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6893 context.set("right_dock", active_panel.panel_key());
6894 }
6895 }
6896
6897 if self.bottom_dock.read(cx).is_open() {
6898 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6899 context.set("bottom_dock", active_panel.panel_key());
6900 }
6901 }
6902
6903 let centered_layout = self.centered_layout
6904 && self.center.panes().len() == 1
6905 && self.active_item(cx).is_some();
6906 let render_padding = |size| {
6907 (size > 0.0).then(|| {
6908 div()
6909 .h_full()
6910 .w(relative(size))
6911 .bg(cx.theme().colors().editor_background)
6912 .border_color(cx.theme().colors().pane_group_border)
6913 })
6914 };
6915 let paddings = if centered_layout {
6916 let settings = WorkspaceSettings::get_global(cx).centered_layout;
6917 (
6918 render_padding(Self::adjust_padding(
6919 settings.left_padding.map(|padding| padding.0),
6920 )),
6921 render_padding(Self::adjust_padding(
6922 settings.right_padding.map(|padding| padding.0),
6923 )),
6924 )
6925 } else {
6926 (None, None)
6927 };
6928 let ui_font = theme::setup_ui_font(window, cx);
6929
6930 let theme = cx.theme().clone();
6931 let colors = theme.colors();
6932 let notification_entities = self
6933 .notifications
6934 .iter()
6935 .map(|(_, notification)| notification.entity_id())
6936 .collect::<Vec<_>>();
6937 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
6938
6939 client_side_decorations(
6940 self.actions(div(), window, cx)
6941 .key_context(context)
6942 .relative()
6943 .size_full()
6944 .flex()
6945 .flex_col()
6946 .font(ui_font)
6947 .gap_0()
6948 .justify_start()
6949 .items_start()
6950 .text_color(colors.text)
6951 .overflow_hidden()
6952 .children(self.titlebar_item.clone())
6953 .on_modifiers_changed(move |_, _, cx| {
6954 for &id in ¬ification_entities {
6955 cx.notify(id);
6956 }
6957 })
6958 .child(
6959 div()
6960 .size_full()
6961 .relative()
6962 .flex_1()
6963 .flex()
6964 .flex_col()
6965 .child(
6966 div()
6967 .id("workspace")
6968 .bg(colors.background)
6969 .relative()
6970 .flex_1()
6971 .w_full()
6972 .flex()
6973 .flex_col()
6974 .overflow_hidden()
6975 .border_t_1()
6976 .border_b_1()
6977 .border_color(colors.border)
6978 .child({
6979 let this = cx.entity();
6980 canvas(
6981 move |bounds, window, cx| {
6982 this.update(cx, |this, cx| {
6983 let bounds_changed = this.bounds != bounds;
6984 this.bounds = bounds;
6985
6986 if bounds_changed {
6987 this.left_dock.update(cx, |dock, cx| {
6988 dock.clamp_panel_size(
6989 bounds.size.width,
6990 window,
6991 cx,
6992 )
6993 });
6994
6995 this.right_dock.update(cx, |dock, cx| {
6996 dock.clamp_panel_size(
6997 bounds.size.width,
6998 window,
6999 cx,
7000 )
7001 });
7002
7003 this.bottom_dock.update(cx, |dock, cx| {
7004 dock.clamp_panel_size(
7005 bounds.size.height,
7006 window,
7007 cx,
7008 )
7009 });
7010 }
7011 })
7012 },
7013 |_, _, _, _| {},
7014 )
7015 .absolute()
7016 .size_full()
7017 })
7018 .when(self.zoomed.is_none(), |this| {
7019 this.on_drag_move(cx.listener(
7020 move |workspace,
7021 e: &DragMoveEvent<DraggedDock>,
7022 window,
7023 cx| {
7024 if workspace.previous_dock_drag_coordinates
7025 != Some(e.event.position)
7026 {
7027 workspace.previous_dock_drag_coordinates =
7028 Some(e.event.position);
7029 match e.drag(cx).0 {
7030 DockPosition::Left => {
7031 workspace.resize_left_dock(
7032 e.event.position.x
7033 - workspace.bounds.left(),
7034 window,
7035 cx,
7036 );
7037 }
7038 DockPosition::Right => {
7039 workspace.resize_right_dock(
7040 workspace.bounds.right()
7041 - e.event.position.x,
7042 window,
7043 cx,
7044 );
7045 }
7046 DockPosition::Bottom => {
7047 workspace.resize_bottom_dock(
7048 workspace.bounds.bottom()
7049 - e.event.position.y,
7050 window,
7051 cx,
7052 );
7053 }
7054 };
7055 workspace.serialize_workspace(window, cx);
7056 }
7057 },
7058 ))
7059 .on_drag_move(cx.listener(
7060 move |workspace,
7061 e: &DragMoveEvent<DraggedUtilityPane>,
7062 window,
7063 cx| {
7064 let slot = e.drag(cx).0;
7065 match slot {
7066 UtilityPaneSlot::Left => {
7067 let left_dock_width = workspace.left_dock.read(cx)
7068 .active_panel_size(window, cx)
7069 .unwrap_or(gpui::px(0.0));
7070 let new_width = e.event.position.x
7071 - workspace.bounds.left()
7072 - left_dock_width;
7073 workspace.resize_utility_pane(slot, new_width, window, cx);
7074 }
7075 UtilityPaneSlot::Right => {
7076 let right_dock_width = workspace.right_dock.read(cx)
7077 .active_panel_size(window, cx)
7078 .unwrap_or(gpui::px(0.0));
7079 let new_width = workspace.bounds.right()
7080 - e.event.position.x
7081 - right_dock_width;
7082 workspace.resize_utility_pane(slot, new_width, window, cx);
7083 }
7084 }
7085 },
7086 ))
7087 })
7088 .child({
7089 match bottom_dock_layout {
7090 BottomDockLayout::Full => div()
7091 .flex()
7092 .flex_col()
7093 .h_full()
7094 .child(
7095 div()
7096 .flex()
7097 .flex_row()
7098 .flex_1()
7099 .overflow_hidden()
7100 .children(self.render_dock(
7101 DockPosition::Left,
7102 &self.left_dock,
7103 window,
7104 cx,
7105 ))
7106 .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
7107 this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
7108 this.when(pane.expanded(cx), |this| {
7109 this.child(
7110 UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
7111 )
7112 })
7113 })
7114 })
7115 .child(
7116 div()
7117 .flex()
7118 .flex_col()
7119 .flex_1()
7120 .overflow_hidden()
7121 .child(
7122 h_flex()
7123 .flex_1()
7124 .when_some(
7125 paddings.0,
7126 |this, p| {
7127 this.child(
7128 p.border_r_1(),
7129 )
7130 },
7131 )
7132 .child(self.center.render(
7133 self.zoomed.as_ref(),
7134 &PaneRenderContext {
7135 follower_states:
7136 &self.follower_states,
7137 active_call: self.active_call(),
7138 active_pane: &self.active_pane,
7139 app_state: &self.app_state,
7140 project: &self.project,
7141 workspace: &self.weak_self,
7142 },
7143 window,
7144 cx,
7145 ))
7146 .when_some(
7147 paddings.1,
7148 |this, p| {
7149 this.child(
7150 p.border_l_1(),
7151 )
7152 },
7153 ),
7154 ),
7155 )
7156 .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
7157 this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
7158 this.when(pane.expanded(cx), |this| {
7159 this.child(
7160 UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
7161 )
7162 })
7163 })
7164 })
7165 .children(self.render_dock(
7166 DockPosition::Right,
7167 &self.right_dock,
7168 window,
7169 cx,
7170 )),
7171 )
7172 .child(div().w_full().children(self.render_dock(
7173 DockPosition::Bottom,
7174 &self.bottom_dock,
7175 window,
7176 cx
7177 ))),
7178
7179 BottomDockLayout::LeftAligned => div()
7180 .flex()
7181 .flex_row()
7182 .h_full()
7183 .child(
7184 div()
7185 .flex()
7186 .flex_col()
7187 .flex_1()
7188 .h_full()
7189 .child(
7190 div()
7191 .flex()
7192 .flex_row()
7193 .flex_1()
7194 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
7195 .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
7196 this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
7197 this.when(pane.expanded(cx), |this| {
7198 this.child(
7199 UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
7200 )
7201 })
7202 })
7203 })
7204 .child(
7205 div()
7206 .flex()
7207 .flex_col()
7208 .flex_1()
7209 .overflow_hidden()
7210 .child(
7211 h_flex()
7212 .flex_1()
7213 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7214 .child(self.center.render(
7215 self.zoomed.as_ref(),
7216 &PaneRenderContext {
7217 follower_states:
7218 &self.follower_states,
7219 active_call: self.active_call(),
7220 active_pane: &self.active_pane,
7221 app_state: &self.app_state,
7222 project: &self.project,
7223 workspace: &self.weak_self,
7224 },
7225 window,
7226 cx,
7227 ))
7228 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7229 )
7230 )
7231 .when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
7232 this.when(pane.expanded(cx), |this| {
7233 this.child(
7234 UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
7235 )
7236 })
7237 })
7238 )
7239 .child(
7240 div()
7241 .w_full()
7242 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7243 ),
7244 )
7245 .children(self.render_dock(
7246 DockPosition::Right,
7247 &self.right_dock,
7248 window,
7249 cx,
7250 )),
7251
7252 BottomDockLayout::RightAligned => div()
7253 .flex()
7254 .flex_row()
7255 .h_full()
7256 .children(self.render_dock(
7257 DockPosition::Left,
7258 &self.left_dock,
7259 window,
7260 cx,
7261 ))
7262 .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
7263 this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
7264 this.when(pane.expanded(cx), |this| {
7265 this.child(
7266 UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
7267 )
7268 })
7269 })
7270 })
7271 .child(
7272 div()
7273 .flex()
7274 .flex_col()
7275 .flex_1()
7276 .h_full()
7277 .child(
7278 div()
7279 .flex()
7280 .flex_row()
7281 .flex_1()
7282 .child(
7283 div()
7284 .flex()
7285 .flex_col()
7286 .flex_1()
7287 .overflow_hidden()
7288 .child(
7289 h_flex()
7290 .flex_1()
7291 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7292 .child(self.center.render(
7293 self.zoomed.as_ref(),
7294 &PaneRenderContext {
7295 follower_states:
7296 &self.follower_states,
7297 active_call: self.active_call(),
7298 active_pane: &self.active_pane,
7299 app_state: &self.app_state,
7300 project: &self.project,
7301 workspace: &self.weak_self,
7302 },
7303 window,
7304 cx,
7305 ))
7306 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7307 )
7308 )
7309 .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
7310 this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
7311 this.when(pane.expanded(cx), |this| {
7312 this.child(
7313 UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
7314 )
7315 })
7316 })
7317 })
7318 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
7319 )
7320 .child(
7321 div()
7322 .w_full()
7323 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7324 ),
7325 ),
7326
7327 BottomDockLayout::Contained => div()
7328 .flex()
7329 .flex_row()
7330 .h_full()
7331 .children(self.render_dock(
7332 DockPosition::Left,
7333 &self.left_dock,
7334 window,
7335 cx,
7336 ))
7337 .when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
7338 this.when(pane.expanded(cx), |this| {
7339 this.child(
7340 UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
7341 )
7342 })
7343 })
7344 .child(
7345 div()
7346 .flex()
7347 .flex_col()
7348 .flex_1()
7349 .overflow_hidden()
7350 .child(
7351 h_flex()
7352 .flex_1()
7353 .when_some(paddings.0, |this, p| {
7354 this.child(p.border_r_1())
7355 })
7356 .child(self.center.render(
7357 self.zoomed.as_ref(),
7358 &PaneRenderContext {
7359 follower_states:
7360 &self.follower_states,
7361 active_call: self.active_call(),
7362 active_pane: &self.active_pane,
7363 app_state: &self.app_state,
7364 project: &self.project,
7365 workspace: &self.weak_self,
7366 },
7367 window,
7368 cx,
7369 ))
7370 .when_some(paddings.1, |this, p| {
7371 this.child(p.border_l_1())
7372 }),
7373 )
7374 .children(self.render_dock(
7375 DockPosition::Bottom,
7376 &self.bottom_dock,
7377 window,
7378 cx,
7379 )),
7380 )
7381 .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
7382 this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
7383 this.when(pane.expanded(cx), |this| {
7384 this.child(
7385 UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
7386 )
7387 })
7388 })
7389 })
7390 .children(self.render_dock(
7391 DockPosition::Right,
7392 &self.right_dock,
7393 window,
7394 cx,
7395 )),
7396 }
7397 })
7398 .children(self.zoomed.as_ref().and_then(|view| {
7399 let zoomed_view = view.upgrade()?;
7400 let div = div()
7401 .occlude()
7402 .absolute()
7403 .overflow_hidden()
7404 .border_color(colors.border)
7405 .bg(colors.background)
7406 .child(zoomed_view)
7407 .inset_0()
7408 .shadow_lg();
7409
7410 if !WorkspaceSettings::get_global(cx).zoomed_padding {
7411 return Some(div);
7412 }
7413
7414 Some(match self.zoomed_position {
7415 Some(DockPosition::Left) => div.right_2().border_r_1(),
7416 Some(DockPosition::Right) => div.left_2().border_l_1(),
7417 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
7418 None => {
7419 div.top_2().bottom_2().left_2().right_2().border_1()
7420 }
7421 })
7422 }))
7423 .children(self.render_notifications(window, cx)),
7424 )
7425 .when(self.status_bar_visible(cx), |parent| {
7426 parent.child(self.status_bar.clone())
7427 })
7428 .child(self.modal_layer.clone())
7429 .child(self.toast_layer.clone()),
7430 ),
7431 window,
7432 cx,
7433 )
7434 }
7435}
7436
7437impl WorkspaceStore {
7438 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
7439 Self {
7440 workspaces: Default::default(),
7441 _subscriptions: vec![
7442 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
7443 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
7444 ],
7445 client,
7446 }
7447 }
7448
7449 pub fn update_followers(
7450 &self,
7451 project_id: Option<u64>,
7452 update: proto::update_followers::Variant,
7453 cx: &App,
7454 ) -> Option<()> {
7455 let active_call = ActiveCall::try_global(cx)?;
7456 let room_id = active_call.read(cx).room()?.read(cx).id();
7457 self.client
7458 .send(proto::UpdateFollowers {
7459 room_id,
7460 project_id,
7461 variant: Some(update),
7462 })
7463 .log_err()
7464 }
7465
7466 pub async fn handle_follow(
7467 this: Entity<Self>,
7468 envelope: TypedEnvelope<proto::Follow>,
7469 mut cx: AsyncApp,
7470 ) -> Result<proto::FollowResponse> {
7471 this.update(&mut cx, |this, cx| {
7472 let follower = Follower {
7473 project_id: envelope.payload.project_id,
7474 peer_id: envelope.original_sender_id()?,
7475 };
7476
7477 let mut response = proto::FollowResponse::default();
7478 this.workspaces.retain(|workspace| {
7479 workspace
7480 .update(cx, |workspace, window, cx| {
7481 let handler_response =
7482 workspace.handle_follow(follower.project_id, window, cx);
7483 if let Some(active_view) = handler_response.active_view
7484 && workspace.project.read(cx).remote_id() == follower.project_id
7485 {
7486 response.active_view = Some(active_view)
7487 }
7488 })
7489 .is_ok()
7490 });
7491
7492 Ok(response)
7493 })?
7494 }
7495
7496 async fn handle_update_followers(
7497 this: Entity<Self>,
7498 envelope: TypedEnvelope<proto::UpdateFollowers>,
7499 mut cx: AsyncApp,
7500 ) -> Result<()> {
7501 let leader_id = envelope.original_sender_id()?;
7502 let update = envelope.payload;
7503
7504 this.update(&mut cx, |this, cx| {
7505 this.workspaces.retain(|workspace| {
7506 workspace
7507 .update(cx, |workspace, window, cx| {
7508 let project_id = workspace.project.read(cx).remote_id();
7509 if update.project_id != project_id && update.project_id.is_some() {
7510 return;
7511 }
7512 workspace.handle_update_followers(leader_id, update.clone(), window, cx);
7513 })
7514 .is_ok()
7515 });
7516 Ok(())
7517 })?
7518 }
7519
7520 pub fn workspaces(&self) -> &HashSet<WindowHandle<Workspace>> {
7521 &self.workspaces
7522 }
7523}
7524
7525impl ViewId {
7526 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
7527 Ok(Self {
7528 creator: message
7529 .creator
7530 .map(CollaboratorId::PeerId)
7531 .context("creator is missing")?,
7532 id: message.id,
7533 })
7534 }
7535
7536 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
7537 if let CollaboratorId::PeerId(peer_id) = self.creator {
7538 Some(proto::ViewId {
7539 creator: Some(peer_id),
7540 id: self.id,
7541 })
7542 } else {
7543 None
7544 }
7545 }
7546}
7547
7548impl FollowerState {
7549 fn pane(&self) -> &Entity<Pane> {
7550 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
7551 }
7552}
7553
7554pub trait WorkspaceHandle {
7555 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
7556}
7557
7558impl WorkspaceHandle for Entity<Workspace> {
7559 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
7560 self.read(cx)
7561 .worktrees(cx)
7562 .flat_map(|worktree| {
7563 let worktree_id = worktree.read(cx).id();
7564 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
7565 worktree_id,
7566 path: f.path.clone(),
7567 })
7568 })
7569 .collect::<Vec<_>>()
7570 }
7571}
7572
7573pub async fn last_opened_workspace_location() -> Option<(SerializedWorkspaceLocation, PathList)> {
7574 DB.last_workspace().await.log_err().flatten()
7575}
7576
7577pub fn last_session_workspace_locations(
7578 last_session_id: &str,
7579 last_session_window_stack: Option<Vec<WindowId>>,
7580) -> Option<Vec<(SerializedWorkspaceLocation, PathList)>> {
7581 DB.last_session_workspace_locations(last_session_id, last_session_window_stack)
7582 .log_err()
7583}
7584
7585actions!(
7586 collab,
7587 [
7588 /// Opens the channel notes for the current call.
7589 ///
7590 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
7591 /// channel in the collab panel.
7592 ///
7593 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
7594 /// can be copied via "Copy link to section" in the context menu of the channel notes
7595 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
7596 OpenChannelNotes,
7597 /// Mutes your microphone.
7598 Mute,
7599 /// Deafens yourself (mute both microphone and speakers).
7600 Deafen,
7601 /// Leaves the current call.
7602 LeaveCall,
7603 /// Shares the current project with collaborators.
7604 ShareProject,
7605 /// Shares your screen with collaborators.
7606 ScreenShare,
7607 /// Copies the current room name and session id for debugging purposes.
7608 CopyRoomId,
7609 ]
7610);
7611actions!(
7612 zed,
7613 [
7614 /// Opens the Zed log file.
7615 OpenLog,
7616 /// Reveals the Zed log file in the system file manager.
7617 RevealLogInFileManager
7618 ]
7619);
7620
7621async fn join_channel_internal(
7622 channel_id: ChannelId,
7623 app_state: &Arc<AppState>,
7624 requesting_window: Option<WindowHandle<Workspace>>,
7625 active_call: &Entity<ActiveCall>,
7626 cx: &mut AsyncApp,
7627) -> Result<bool> {
7628 let (should_prompt, open_room) = active_call.update(cx, |active_call, cx| {
7629 let Some(room) = active_call.room().map(|room| room.read(cx)) else {
7630 return (false, None);
7631 };
7632
7633 let already_in_channel = room.channel_id() == Some(channel_id);
7634 let should_prompt = room.is_sharing_project()
7635 && !room.remote_participants().is_empty()
7636 && !already_in_channel;
7637 let open_room = if already_in_channel {
7638 active_call.room().cloned()
7639 } else {
7640 None
7641 };
7642 (should_prompt, open_room)
7643 })?;
7644
7645 if let Some(room) = open_room {
7646 let task = room.update(cx, |room, cx| {
7647 if let Some((project, host)) = room.most_active_project(cx) {
7648 return Some(join_in_room_project(project, host, app_state.clone(), cx));
7649 }
7650
7651 None
7652 })?;
7653 if let Some(task) = task {
7654 task.await?;
7655 }
7656 return anyhow::Ok(true);
7657 }
7658
7659 if should_prompt {
7660 if let Some(workspace) = requesting_window {
7661 let answer = workspace
7662 .update(cx, |_, window, cx| {
7663 window.prompt(
7664 PromptLevel::Warning,
7665 "Do you want to switch channels?",
7666 Some("Leaving this call will unshare your current project."),
7667 &["Yes, Join Channel", "Cancel"],
7668 cx,
7669 )
7670 })?
7671 .await;
7672
7673 if answer == Ok(1) {
7674 return Ok(false);
7675 }
7676 } else {
7677 return Ok(false); // unreachable!() hopefully
7678 }
7679 }
7680
7681 let client = cx.update(|cx| active_call.read(cx).client())?;
7682
7683 let mut client_status = client.status();
7684
7685 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
7686 'outer: loop {
7687 let Some(status) = client_status.recv().await else {
7688 anyhow::bail!("error connecting");
7689 };
7690
7691 match status {
7692 Status::Connecting
7693 | Status::Authenticating
7694 | Status::Authenticated
7695 | Status::Reconnecting
7696 | Status::Reauthenticating
7697 | Status::Reauthenticated => continue,
7698 Status::Connected { .. } => break 'outer,
7699 Status::SignedOut | Status::AuthenticationError => {
7700 return Err(ErrorCode::SignedOut.into());
7701 }
7702 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
7703 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
7704 return Err(ErrorCode::Disconnected.into());
7705 }
7706 }
7707 }
7708
7709 let room = active_call
7710 .update(cx, |active_call, cx| {
7711 active_call.join_channel(channel_id, cx)
7712 })?
7713 .await?;
7714
7715 let Some(room) = room else {
7716 return anyhow::Ok(true);
7717 };
7718
7719 room.update(cx, |room, _| room.room_update_completed())?
7720 .await;
7721
7722 let task = room.update(cx, |room, cx| {
7723 if let Some((project, host)) = room.most_active_project(cx) {
7724 return Some(join_in_room_project(project, host, app_state.clone(), cx));
7725 }
7726
7727 // If you are the first to join a channel, see if you should share your project.
7728 if room.remote_participants().is_empty()
7729 && !room.local_participant_is_guest()
7730 && let Some(workspace) = requesting_window
7731 {
7732 let project = workspace.update(cx, |workspace, _, cx| {
7733 let project = workspace.project.read(cx);
7734
7735 if !CallSettings::get_global(cx).share_on_join {
7736 return None;
7737 }
7738
7739 if (project.is_local() || project.is_via_remote_server())
7740 && project.visible_worktrees(cx).any(|tree| {
7741 tree.read(cx)
7742 .root_entry()
7743 .is_some_and(|entry| entry.is_dir())
7744 })
7745 {
7746 Some(workspace.project.clone())
7747 } else {
7748 None
7749 }
7750 });
7751 if let Ok(Some(project)) = project {
7752 return Some(cx.spawn(async move |room, cx| {
7753 room.update(cx, |room, cx| room.share_project(project, cx))?
7754 .await?;
7755 Ok(())
7756 }));
7757 }
7758 }
7759
7760 None
7761 })?;
7762 if let Some(task) = task {
7763 task.await?;
7764 return anyhow::Ok(true);
7765 }
7766 anyhow::Ok(false)
7767}
7768
7769pub fn join_channel(
7770 channel_id: ChannelId,
7771 app_state: Arc<AppState>,
7772 requesting_window: Option<WindowHandle<Workspace>>,
7773 cx: &mut App,
7774) -> Task<Result<()>> {
7775 let active_call = ActiveCall::global(cx);
7776 cx.spawn(async move |cx| {
7777 let result =
7778 join_channel_internal(channel_id, &app_state, requesting_window, &active_call, cx)
7779 .await;
7780
7781 // join channel succeeded, and opened a window
7782 if matches!(result, Ok(true)) {
7783 return anyhow::Ok(());
7784 }
7785
7786 // find an existing workspace to focus and show call controls
7787 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
7788 if active_window.is_none() {
7789 // no open workspaces, make one to show the error in (blergh)
7790 let (window_handle, _) = cx
7791 .update(|cx| {
7792 Workspace::new_local(
7793 vec![],
7794 app_state.clone(),
7795 requesting_window,
7796 None,
7797 None,
7798 cx,
7799 )
7800 })?
7801 .await?;
7802
7803 if result.is_ok() {
7804 cx.update(|cx| {
7805 cx.dispatch_action(&OpenChannelNotes);
7806 })
7807 .log_err();
7808 }
7809
7810 active_window = Some(window_handle);
7811 }
7812
7813 if let Err(err) = result {
7814 log::error!("failed to join channel: {}", err);
7815 if let Some(active_window) = active_window {
7816 active_window
7817 .update(cx, |_, window, cx| {
7818 let detail: SharedString = match err.error_code() {
7819 ErrorCode::SignedOut => "Please sign in to continue.".into(),
7820 ErrorCode::UpgradeRequired => concat!(
7821 "Your are running an unsupported version of Zed. ",
7822 "Please update to continue."
7823 )
7824 .into(),
7825 ErrorCode::NoSuchChannel => concat!(
7826 "No matching channel was found. ",
7827 "Please check the link and try again."
7828 )
7829 .into(),
7830 ErrorCode::Forbidden => concat!(
7831 "This channel is private, and you do not have access. ",
7832 "Please ask someone to add you and try again."
7833 )
7834 .into(),
7835 ErrorCode::Disconnected => {
7836 "Please check your internet connection and try again.".into()
7837 }
7838 _ => format!("{}\n\nPlease try again.", err).into(),
7839 };
7840 window.prompt(
7841 PromptLevel::Critical,
7842 "Failed to join channel",
7843 Some(&detail),
7844 &["Ok"],
7845 cx,
7846 )
7847 })?
7848 .await
7849 .ok();
7850 }
7851 }
7852
7853 // return ok, we showed the error to the user.
7854 anyhow::Ok(())
7855 })
7856}
7857
7858pub async fn get_any_active_workspace(
7859 app_state: Arc<AppState>,
7860 mut cx: AsyncApp,
7861) -> anyhow::Result<WindowHandle<Workspace>> {
7862 // find an existing workspace to focus and show call controls
7863 let active_window = activate_any_workspace_window(&mut cx);
7864 if active_window.is_none() {
7865 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, cx))?
7866 .await?;
7867 }
7868 activate_any_workspace_window(&mut cx).context("could not open zed")
7869}
7870
7871fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<Workspace>> {
7872 cx.update(|cx| {
7873 if let Some(workspace_window) = cx
7874 .active_window()
7875 .and_then(|window| window.downcast::<Workspace>())
7876 {
7877 return Some(workspace_window);
7878 }
7879
7880 for window in cx.windows() {
7881 if let Some(workspace_window) = window.downcast::<Workspace>() {
7882 workspace_window
7883 .update(cx, |_, window, _| window.activate_window())
7884 .ok();
7885 return Some(workspace_window);
7886 }
7887 }
7888 None
7889 })
7890 .ok()
7891 .flatten()
7892}
7893
7894pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<Workspace>> {
7895 cx.windows()
7896 .into_iter()
7897 .filter_map(|window| window.downcast::<Workspace>())
7898 .filter(|workspace| {
7899 workspace
7900 .read(cx)
7901 .is_ok_and(|workspace| workspace.project.read(cx).is_local())
7902 })
7903 .collect()
7904}
7905
7906#[derive(Default)]
7907pub struct OpenOptions {
7908 pub visible: Option<OpenVisible>,
7909 pub focus: Option<bool>,
7910 pub open_new_workspace: Option<bool>,
7911 pub prefer_focused_window: bool,
7912 pub replace_window: Option<WindowHandle<Workspace>>,
7913 pub env: Option<HashMap<String, String>>,
7914}
7915
7916#[allow(clippy::type_complexity)]
7917pub fn open_paths(
7918 abs_paths: &[PathBuf],
7919 app_state: Arc<AppState>,
7920 open_options: OpenOptions,
7921 cx: &mut App,
7922) -> Task<
7923 anyhow::Result<(
7924 WindowHandle<Workspace>,
7925 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
7926 )>,
7927> {
7928 let abs_paths = abs_paths.to_vec();
7929 let mut existing = None;
7930 let mut best_match = None;
7931 let mut open_visible = OpenVisible::All;
7932 #[cfg(target_os = "windows")]
7933 let wsl_path = abs_paths
7934 .iter()
7935 .find_map(|p| util::paths::WslPath::from_path(p));
7936
7937 cx.spawn(async move |cx| {
7938 if open_options.open_new_workspace != Some(true) {
7939 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
7940 let all_metadatas = futures::future::join_all(all_paths)
7941 .await
7942 .into_iter()
7943 .filter_map(|result| result.ok().flatten())
7944 .collect::<Vec<_>>();
7945
7946 cx.update(|cx| {
7947 for window in local_workspace_windows(cx) {
7948 if let Ok(workspace) = window.read(cx) {
7949 let m = workspace.project.read(cx).visibility_for_paths(
7950 &abs_paths,
7951 &all_metadatas,
7952 open_options.open_new_workspace == None,
7953 cx,
7954 );
7955 if m > best_match {
7956 existing = Some(window);
7957 best_match = m;
7958 } else if best_match.is_none()
7959 && open_options.open_new_workspace == Some(false)
7960 {
7961 existing = Some(window)
7962 }
7963 }
7964 }
7965 })?;
7966
7967 if open_options.open_new_workspace.is_none()
7968 && (existing.is_none() || open_options.prefer_focused_window)
7969 && all_metadatas.iter().all(|file| !file.is_dir)
7970 {
7971 cx.update(|cx| {
7972 if let Some(window) = cx
7973 .active_window()
7974 .and_then(|window| window.downcast::<Workspace>())
7975 && let Ok(workspace) = window.read(cx)
7976 {
7977 let project = workspace.project().read(cx);
7978 if project.is_local() && !project.is_via_collab() {
7979 existing = Some(window);
7980 open_visible = OpenVisible::None;
7981 return;
7982 }
7983 }
7984 for window in local_workspace_windows(cx) {
7985 if let Ok(workspace) = window.read(cx) {
7986 let project = workspace.project().read(cx);
7987 if project.is_via_collab() {
7988 continue;
7989 }
7990 existing = Some(window);
7991 open_visible = OpenVisible::None;
7992 break;
7993 }
7994 }
7995 })?;
7996 }
7997 }
7998
7999 let result = if let Some(existing) = existing {
8000 let open_task = existing
8001 .update(cx, |workspace, window, cx| {
8002 window.activate_window();
8003 workspace.open_paths(
8004 abs_paths,
8005 OpenOptions {
8006 visible: Some(open_visible),
8007 ..Default::default()
8008 },
8009 None,
8010 window,
8011 cx,
8012 )
8013 })?
8014 .await;
8015
8016 _ = existing.update(cx, |workspace, _, cx| {
8017 for item in open_task.iter().flatten() {
8018 if let Err(e) = item {
8019 workspace.show_error(&e, cx);
8020 }
8021 }
8022 });
8023
8024 Ok((existing, open_task))
8025 } else {
8026 cx.update(move |cx| {
8027 Workspace::new_local(
8028 abs_paths,
8029 app_state.clone(),
8030 open_options.replace_window,
8031 open_options.env,
8032 None,
8033 cx,
8034 )
8035 })?
8036 .await
8037 };
8038
8039 #[cfg(target_os = "windows")]
8040 if let Some(util::paths::WslPath{distro, path}) = wsl_path
8041 && let Ok((workspace, _)) = &result
8042 {
8043 workspace
8044 .update(cx, move |workspace, _window, cx| {
8045 struct OpenInWsl;
8046 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
8047 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
8048 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
8049 cx.new(move |cx| {
8050 MessageNotification::new(msg, cx)
8051 .primary_message("Open in WSL")
8052 .primary_icon(IconName::FolderOpen)
8053 .primary_on_click(move |window, cx| {
8054 window.dispatch_action(Box::new(remote::OpenWslPath {
8055 distro: remote::WslConnectionOptions {
8056 distro_name: distro.clone(),
8057 user: None,
8058 },
8059 paths: vec![path.clone().into()],
8060 }), cx)
8061 })
8062 })
8063 });
8064 })
8065 .unwrap();
8066 };
8067 result
8068 })
8069}
8070
8071pub fn open_new(
8072 open_options: OpenOptions,
8073 app_state: Arc<AppState>,
8074 cx: &mut App,
8075 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
8076) -> Task<anyhow::Result<()>> {
8077 let task = Workspace::new_local(
8078 Vec::new(),
8079 app_state,
8080 None,
8081 open_options.env,
8082 Some(Box::new(init)),
8083 cx,
8084 );
8085 cx.spawn(async move |_cx| {
8086 let (_workspace, _opened_paths) = task.await?;
8087 // Init callback is called synchronously during workspace creation
8088 Ok(())
8089 })
8090}
8091
8092pub fn create_and_open_local_file(
8093 path: &'static Path,
8094 window: &mut Window,
8095 cx: &mut Context<Workspace>,
8096 default_content: impl 'static + Send + FnOnce() -> Rope,
8097) -> Task<Result<Box<dyn ItemHandle>>> {
8098 cx.spawn_in(window, async move |workspace, cx| {
8099 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
8100 if !fs.is_file(path).await {
8101 fs.create_file(path, Default::default()).await?;
8102 fs.save(path, &default_content(), Default::default())
8103 .await?;
8104 }
8105
8106 let mut items = workspace
8107 .update_in(cx, |workspace, window, cx| {
8108 workspace.with_local_workspace(window, cx, |workspace, window, cx| {
8109 workspace.open_paths(
8110 vec![path.to_path_buf()],
8111 OpenOptions {
8112 visible: Some(OpenVisible::None),
8113 ..Default::default()
8114 },
8115 None,
8116 window,
8117 cx,
8118 )
8119 })
8120 })?
8121 .await?
8122 .await;
8123
8124 let item = items.pop().flatten();
8125 item.with_context(|| format!("path {path:?} is not a file"))?
8126 })
8127}
8128
8129pub fn open_remote_project_with_new_connection(
8130 window: WindowHandle<Workspace>,
8131 remote_connection: Arc<dyn RemoteConnection>,
8132 cancel_rx: oneshot::Receiver<()>,
8133 delegate: Arc<dyn RemoteClientDelegate>,
8134 app_state: Arc<AppState>,
8135 paths: Vec<PathBuf>,
8136 cx: &mut App,
8137) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
8138 cx.spawn(async move |cx| {
8139 let (workspace_id, serialized_workspace) =
8140 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
8141 .await?;
8142
8143 let session = match cx
8144 .update(|cx| {
8145 remote::RemoteClient::new(
8146 ConnectionIdentifier::Workspace(workspace_id.0),
8147 remote_connection,
8148 cancel_rx,
8149 delegate,
8150 cx,
8151 )
8152 })?
8153 .await?
8154 {
8155 Some(result) => result,
8156 None => return Ok(Vec::new()),
8157 };
8158
8159 let project = cx.update(|cx| {
8160 project::Project::remote(
8161 session,
8162 app_state.client.clone(),
8163 app_state.node_runtime.clone(),
8164 app_state.user_store.clone(),
8165 app_state.languages.clone(),
8166 app_state.fs.clone(),
8167 true,
8168 cx,
8169 )
8170 })?;
8171
8172 open_remote_project_inner(
8173 project,
8174 paths,
8175 workspace_id,
8176 serialized_workspace,
8177 app_state,
8178 window,
8179 cx,
8180 )
8181 .await
8182 })
8183}
8184
8185pub fn open_remote_project_with_existing_connection(
8186 connection_options: RemoteConnectionOptions,
8187 project: Entity<Project>,
8188 paths: Vec<PathBuf>,
8189 app_state: Arc<AppState>,
8190 window: WindowHandle<Workspace>,
8191 cx: &mut AsyncApp,
8192) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
8193 cx.spawn(async move |cx| {
8194 let (workspace_id, serialized_workspace) =
8195 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
8196
8197 open_remote_project_inner(
8198 project,
8199 paths,
8200 workspace_id,
8201 serialized_workspace,
8202 app_state,
8203 window,
8204 cx,
8205 )
8206 .await
8207 })
8208}
8209
8210async fn open_remote_project_inner(
8211 project: Entity<Project>,
8212 paths: Vec<PathBuf>,
8213 workspace_id: WorkspaceId,
8214 serialized_workspace: Option<SerializedWorkspace>,
8215 app_state: Arc<AppState>,
8216 window: WindowHandle<Workspace>,
8217 cx: &mut AsyncApp,
8218) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
8219 let toolchains = DB.toolchains(workspace_id).await?;
8220 for (toolchain, worktree_id, path) in toolchains {
8221 project
8222 .update(cx, |this, cx| {
8223 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
8224 })?
8225 .await;
8226 }
8227 let mut project_paths_to_open = vec![];
8228 let mut project_path_errors = vec![];
8229
8230 for path in paths {
8231 let result = cx
8232 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))?
8233 .await;
8234 match result {
8235 Ok((_, project_path)) => {
8236 project_paths_to_open.push((path.clone(), Some(project_path)));
8237 }
8238 Err(error) => {
8239 project_path_errors.push(error);
8240 }
8241 };
8242 }
8243
8244 if project_paths_to_open.is_empty() {
8245 return Err(project_path_errors.pop().context("no paths given")?);
8246 }
8247
8248 if let Some(detach_session_task) = window
8249 .update(cx, |_workspace, window, cx| {
8250 cx.spawn_in(window, async move |this, cx| {
8251 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))
8252 })
8253 })
8254 .ok()
8255 {
8256 detach_session_task.await.ok();
8257 }
8258
8259 cx.update_window(window.into(), |_, window, cx| {
8260 window.replace_root(cx, |window, cx| {
8261 telemetry::event!("SSH Project Opened");
8262
8263 let mut workspace =
8264 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
8265 workspace.update_history(cx);
8266
8267 if let Some(ref serialized) = serialized_workspace {
8268 workspace.centered_layout = serialized.centered_layout;
8269 }
8270
8271 workspace
8272 });
8273 })?;
8274
8275 let items = window
8276 .update(cx, |_, window, cx| {
8277 window.activate_window();
8278 open_items(serialized_workspace, project_paths_to_open, window, cx)
8279 })?
8280 .await?;
8281
8282 window.update(cx, |workspace, _, cx| {
8283 for error in project_path_errors {
8284 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
8285 if let Some(path) = error.error_tag("path") {
8286 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
8287 }
8288 } else {
8289 workspace.show_error(&error, cx)
8290 }
8291 }
8292 })?;
8293
8294 Ok(items.into_iter().map(|item| item?.ok()).collect())
8295}
8296
8297fn deserialize_remote_project(
8298 connection_options: RemoteConnectionOptions,
8299 paths: Vec<PathBuf>,
8300 cx: &AsyncApp,
8301) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
8302 cx.background_spawn(async move {
8303 let remote_connection_id = persistence::DB
8304 .get_or_create_remote_connection(connection_options)
8305 .await?;
8306
8307 let serialized_workspace =
8308 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
8309
8310 let workspace_id = if let Some(workspace_id) =
8311 serialized_workspace.as_ref().map(|workspace| workspace.id)
8312 {
8313 workspace_id
8314 } else {
8315 persistence::DB.next_id().await?
8316 };
8317
8318 Ok((workspace_id, serialized_workspace))
8319 })
8320}
8321
8322pub fn join_in_room_project(
8323 project_id: u64,
8324 follow_user_id: u64,
8325 app_state: Arc<AppState>,
8326 cx: &mut App,
8327) -> Task<Result<()>> {
8328 let windows = cx.windows();
8329 cx.spawn(async move |cx| {
8330 let existing_workspace = windows.into_iter().find_map(|window_handle| {
8331 window_handle
8332 .downcast::<Workspace>()
8333 .and_then(|window_handle| {
8334 window_handle
8335 .update(cx, |workspace, _window, cx| {
8336 if workspace.project().read(cx).remote_id() == Some(project_id) {
8337 Some(window_handle)
8338 } else {
8339 None
8340 }
8341 })
8342 .unwrap_or(None)
8343 })
8344 });
8345
8346 let workspace = if let Some(existing_workspace) = existing_workspace {
8347 existing_workspace
8348 } else {
8349 let active_call = cx.update(|cx| ActiveCall::global(cx))?;
8350 let room = active_call
8351 .read_with(cx, |call, _| call.room().cloned())?
8352 .context("not in a call")?;
8353 let project = room
8354 .update(cx, |room, cx| {
8355 room.join_project(
8356 project_id,
8357 app_state.languages.clone(),
8358 app_state.fs.clone(),
8359 cx,
8360 )
8361 })?
8362 .await?;
8363
8364 let window_bounds_override = window_bounds_env_override();
8365 cx.update(|cx| {
8366 let mut options = (app_state.build_window_options)(None, cx);
8367 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
8368 cx.open_window(options, |window, cx| {
8369 cx.new(|cx| {
8370 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
8371 })
8372 })
8373 })??
8374 };
8375
8376 workspace.update(cx, |workspace, window, cx| {
8377 cx.activate(true);
8378 window.activate_window();
8379
8380 if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
8381 let follow_peer_id = room
8382 .read(cx)
8383 .remote_participants()
8384 .iter()
8385 .find(|(_, participant)| participant.user.id == follow_user_id)
8386 .map(|(_, p)| p.peer_id)
8387 .or_else(|| {
8388 // If we couldn't follow the given user, follow the host instead.
8389 let collaborator = workspace
8390 .project()
8391 .read(cx)
8392 .collaborators()
8393 .values()
8394 .find(|collaborator| collaborator.is_host)?;
8395 Some(collaborator.peer_id)
8396 });
8397
8398 if let Some(follow_peer_id) = follow_peer_id {
8399 workspace.follow(follow_peer_id, window, cx);
8400 }
8401 }
8402 })?;
8403
8404 anyhow::Ok(())
8405 })
8406}
8407
8408pub fn reload(cx: &mut App) {
8409 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
8410 let mut workspace_windows = cx
8411 .windows()
8412 .into_iter()
8413 .filter_map(|window| window.downcast::<Workspace>())
8414 .collect::<Vec<_>>();
8415
8416 // If multiple windows have unsaved changes, and need a save prompt,
8417 // prompt in the active window before switching to a different window.
8418 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
8419
8420 let mut prompt = None;
8421 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
8422 prompt = window
8423 .update(cx, |_, window, cx| {
8424 window.prompt(
8425 PromptLevel::Info,
8426 "Are you sure you want to restart?",
8427 None,
8428 &["Restart", "Cancel"],
8429 cx,
8430 )
8431 })
8432 .ok();
8433 }
8434
8435 cx.spawn(async move |cx| {
8436 if let Some(prompt) = prompt {
8437 let answer = prompt.await?;
8438 if answer != 0 {
8439 return Ok(());
8440 }
8441 }
8442
8443 // If the user cancels any save prompt, then keep the app open.
8444 for window in workspace_windows {
8445 if let Ok(should_close) = window.update(cx, |workspace, window, cx| {
8446 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
8447 }) && !should_close.await?
8448 {
8449 return Ok(());
8450 }
8451 }
8452 cx.update(|cx| cx.restart())
8453 })
8454 .detach_and_log_err(cx);
8455}
8456
8457fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
8458 let mut parts = value.split(',');
8459 let x: usize = parts.next()?.parse().ok()?;
8460 let y: usize = parts.next()?.parse().ok()?;
8461 Some(point(px(x as f32), px(y as f32)))
8462}
8463
8464fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
8465 let mut parts = value.split(',');
8466 let width: usize = parts.next()?.parse().ok()?;
8467 let height: usize = parts.next()?.parse().ok()?;
8468 Some(size(px(width as f32), px(height as f32)))
8469}
8470
8471/// Add client-side decorations (rounded corners, shadows, resize handling) when appropriate.
8472pub fn client_side_decorations(
8473 element: impl IntoElement,
8474 window: &mut Window,
8475 cx: &mut App,
8476) -> Stateful<Div> {
8477 const BORDER_SIZE: Pixels = px(1.0);
8478 let decorations = window.window_decorations();
8479
8480 match decorations {
8481 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
8482 Decorations::Server => window.set_client_inset(px(0.0)),
8483 }
8484
8485 struct GlobalResizeEdge(ResizeEdge);
8486 impl Global for GlobalResizeEdge {}
8487
8488 div()
8489 .id("window-backdrop")
8490 .bg(transparent_black())
8491 .map(|div| match decorations {
8492 Decorations::Server => div,
8493 Decorations::Client { tiling, .. } => div
8494 .when(!(tiling.top || tiling.right), |div| {
8495 div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8496 })
8497 .when(!(tiling.top || tiling.left), |div| {
8498 div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8499 })
8500 .when(!(tiling.bottom || tiling.right), |div| {
8501 div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8502 })
8503 .when(!(tiling.bottom || tiling.left), |div| {
8504 div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8505 })
8506 .when(!tiling.top, |div| {
8507 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
8508 })
8509 .when(!tiling.bottom, |div| {
8510 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
8511 })
8512 .when(!tiling.left, |div| {
8513 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
8514 })
8515 .when(!tiling.right, |div| {
8516 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
8517 })
8518 .on_mouse_move(move |e, window, cx| {
8519 let size = window.window_bounds().get_bounds().size;
8520 let pos = e.position;
8521
8522 let new_edge =
8523 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
8524
8525 let edge = cx.try_global::<GlobalResizeEdge>();
8526 if new_edge != edge.map(|edge| edge.0) {
8527 window
8528 .window_handle()
8529 .update(cx, |workspace, _, cx| {
8530 cx.notify(workspace.entity_id());
8531 })
8532 .ok();
8533 }
8534 })
8535 .on_mouse_down(MouseButton::Left, move |e, window, _| {
8536 let size = window.window_bounds().get_bounds().size;
8537 let pos = e.position;
8538
8539 let edge = match resize_edge(
8540 pos,
8541 theme::CLIENT_SIDE_DECORATION_SHADOW,
8542 size,
8543 tiling,
8544 ) {
8545 Some(value) => value,
8546 None => return,
8547 };
8548
8549 window.start_window_resize(edge);
8550 }),
8551 })
8552 .size_full()
8553 .child(
8554 div()
8555 .cursor(CursorStyle::Arrow)
8556 .map(|div| match decorations {
8557 Decorations::Server => div,
8558 Decorations::Client { tiling } => div
8559 .border_color(cx.theme().colors().border)
8560 .when(!(tiling.top || tiling.right), |div| {
8561 div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8562 })
8563 .when(!(tiling.top || tiling.left), |div| {
8564 div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8565 })
8566 .when(!(tiling.bottom || tiling.right), |div| {
8567 div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8568 })
8569 .when(!(tiling.bottom || tiling.left), |div| {
8570 div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
8571 })
8572 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
8573 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
8574 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
8575 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
8576 .when(!tiling.is_tiled(), |div| {
8577 div.shadow(vec![gpui::BoxShadow {
8578 color: Hsla {
8579 h: 0.,
8580 s: 0.,
8581 l: 0.,
8582 a: 0.4,
8583 },
8584 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
8585 spread_radius: px(0.),
8586 offset: point(px(0.0), px(0.0)),
8587 }])
8588 }),
8589 })
8590 .on_mouse_move(|_e, _, cx| {
8591 cx.stop_propagation();
8592 })
8593 .size_full()
8594 .child(element),
8595 )
8596 .map(|div| match decorations {
8597 Decorations::Server => div,
8598 Decorations::Client { tiling, .. } => div.child(
8599 canvas(
8600 |_bounds, window, _| {
8601 window.insert_hitbox(
8602 Bounds::new(
8603 point(px(0.0), px(0.0)),
8604 window.window_bounds().get_bounds().size,
8605 ),
8606 HitboxBehavior::Normal,
8607 )
8608 },
8609 move |_bounds, hitbox, window, cx| {
8610 let mouse = window.mouse_position();
8611 let size = window.window_bounds().get_bounds().size;
8612 let Some(edge) =
8613 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
8614 else {
8615 return;
8616 };
8617 cx.set_global(GlobalResizeEdge(edge));
8618 window.set_cursor_style(
8619 match edge {
8620 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
8621 ResizeEdge::Left | ResizeEdge::Right => {
8622 CursorStyle::ResizeLeftRight
8623 }
8624 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
8625 CursorStyle::ResizeUpLeftDownRight
8626 }
8627 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
8628 CursorStyle::ResizeUpRightDownLeft
8629 }
8630 },
8631 &hitbox,
8632 );
8633 },
8634 )
8635 .size_full()
8636 .absolute(),
8637 ),
8638 })
8639}
8640
8641fn resize_edge(
8642 pos: Point<Pixels>,
8643 shadow_size: Pixels,
8644 window_size: Size<Pixels>,
8645 tiling: Tiling,
8646) -> Option<ResizeEdge> {
8647 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
8648 if bounds.contains(&pos) {
8649 return None;
8650 }
8651
8652 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
8653 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
8654 if !tiling.top && top_left_bounds.contains(&pos) {
8655 return Some(ResizeEdge::TopLeft);
8656 }
8657
8658 let top_right_bounds = Bounds::new(
8659 Point::new(window_size.width - corner_size.width, px(0.)),
8660 corner_size,
8661 );
8662 if !tiling.top && top_right_bounds.contains(&pos) {
8663 return Some(ResizeEdge::TopRight);
8664 }
8665
8666 let bottom_left_bounds = Bounds::new(
8667 Point::new(px(0.), window_size.height - corner_size.height),
8668 corner_size,
8669 );
8670 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
8671 return Some(ResizeEdge::BottomLeft);
8672 }
8673
8674 let bottom_right_bounds = Bounds::new(
8675 Point::new(
8676 window_size.width - corner_size.width,
8677 window_size.height - corner_size.height,
8678 ),
8679 corner_size,
8680 );
8681 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
8682 return Some(ResizeEdge::BottomRight);
8683 }
8684
8685 if !tiling.top && pos.y < shadow_size {
8686 Some(ResizeEdge::Top)
8687 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
8688 Some(ResizeEdge::Bottom)
8689 } else if !tiling.left && pos.x < shadow_size {
8690 Some(ResizeEdge::Left)
8691 } else if !tiling.right && pos.x > window_size.width - shadow_size {
8692 Some(ResizeEdge::Right)
8693 } else {
8694 None
8695 }
8696}
8697
8698fn join_pane_into_active(
8699 active_pane: &Entity<Pane>,
8700 pane: &Entity<Pane>,
8701 window: &mut Window,
8702 cx: &mut App,
8703) {
8704 if pane == active_pane {
8705 } else if pane.read(cx).items_len() == 0 {
8706 pane.update(cx, |_, cx| {
8707 cx.emit(pane::Event::Remove {
8708 focus_on_pane: None,
8709 });
8710 })
8711 } else {
8712 move_all_items(pane, active_pane, window, cx);
8713 }
8714}
8715
8716fn move_all_items(
8717 from_pane: &Entity<Pane>,
8718 to_pane: &Entity<Pane>,
8719 window: &mut Window,
8720 cx: &mut App,
8721) {
8722 let destination_is_different = from_pane != to_pane;
8723 let mut moved_items = 0;
8724 for (item_ix, item_handle) in from_pane
8725 .read(cx)
8726 .items()
8727 .enumerate()
8728 .map(|(ix, item)| (ix, item.clone()))
8729 .collect::<Vec<_>>()
8730 {
8731 let ix = item_ix - moved_items;
8732 if destination_is_different {
8733 // Close item from previous pane
8734 from_pane.update(cx, |source, cx| {
8735 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
8736 });
8737 moved_items += 1;
8738 }
8739
8740 // This automatically removes duplicate items in the pane
8741 to_pane.update(cx, |destination, cx| {
8742 destination.add_item(item_handle, true, true, None, window, cx);
8743 window.focus(&destination.focus_handle(cx), cx)
8744 });
8745 }
8746}
8747
8748pub fn move_item(
8749 source: &Entity<Pane>,
8750 destination: &Entity<Pane>,
8751 item_id_to_move: EntityId,
8752 destination_index: usize,
8753 activate: bool,
8754 window: &mut Window,
8755 cx: &mut App,
8756) {
8757 let Some((item_ix, item_handle)) = source
8758 .read(cx)
8759 .items()
8760 .enumerate()
8761 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
8762 .map(|(ix, item)| (ix, item.clone()))
8763 else {
8764 // Tab was closed during drag
8765 return;
8766 };
8767
8768 if source != destination {
8769 // Close item from previous pane
8770 source.update(cx, |source, cx| {
8771 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
8772 });
8773 }
8774
8775 // This automatically removes duplicate items in the pane
8776 destination.update(cx, |destination, cx| {
8777 destination.add_item_inner(
8778 item_handle,
8779 activate,
8780 activate,
8781 activate,
8782 Some(destination_index),
8783 window,
8784 cx,
8785 );
8786 if activate {
8787 window.focus(&destination.focus_handle(cx), cx)
8788 }
8789 });
8790}
8791
8792pub fn move_active_item(
8793 source: &Entity<Pane>,
8794 destination: &Entity<Pane>,
8795 focus_destination: bool,
8796 close_if_empty: bool,
8797 window: &mut Window,
8798 cx: &mut App,
8799) {
8800 if source == destination {
8801 return;
8802 }
8803 let Some(active_item) = source.read(cx).active_item() else {
8804 return;
8805 };
8806 source.update(cx, |source_pane, cx| {
8807 let item_id = active_item.item_id();
8808 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
8809 destination.update(cx, |target_pane, cx| {
8810 target_pane.add_item(
8811 active_item,
8812 focus_destination,
8813 focus_destination,
8814 Some(target_pane.items_len()),
8815 window,
8816 cx,
8817 );
8818 });
8819 });
8820}
8821
8822pub fn clone_active_item(
8823 workspace_id: Option<WorkspaceId>,
8824 source: &Entity<Pane>,
8825 destination: &Entity<Pane>,
8826 focus_destination: bool,
8827 window: &mut Window,
8828 cx: &mut App,
8829) {
8830 if source == destination {
8831 return;
8832 }
8833 let Some(active_item) = source.read(cx).active_item() else {
8834 return;
8835 };
8836 if !active_item.can_split(cx) {
8837 return;
8838 }
8839 let destination = destination.downgrade();
8840 let task = active_item.clone_on_split(workspace_id, window, cx);
8841 window
8842 .spawn(cx, async move |cx| {
8843 let Some(clone) = task.await else {
8844 return;
8845 };
8846 destination
8847 .update_in(cx, |target_pane, window, cx| {
8848 target_pane.add_item(
8849 clone,
8850 focus_destination,
8851 focus_destination,
8852 Some(target_pane.items_len()),
8853 window,
8854 cx,
8855 );
8856 })
8857 .log_err();
8858 })
8859 .detach();
8860}
8861
8862#[derive(Debug)]
8863pub struct WorkspacePosition {
8864 pub window_bounds: Option<WindowBounds>,
8865 pub display: Option<Uuid>,
8866 pub centered_layout: bool,
8867}
8868
8869pub fn remote_workspace_position_from_db(
8870 connection_options: RemoteConnectionOptions,
8871 paths_to_open: &[PathBuf],
8872 cx: &App,
8873) -> Task<Result<WorkspacePosition>> {
8874 let paths = paths_to_open.to_vec();
8875
8876 cx.background_spawn(async move {
8877 let remote_connection_id = persistence::DB
8878 .get_or_create_remote_connection(connection_options)
8879 .await
8880 .context("fetching serialized ssh project")?;
8881 let serialized_workspace =
8882 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
8883
8884 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
8885 (Some(WindowBounds::Windowed(bounds)), None)
8886 } else {
8887 let restorable_bounds = serialized_workspace
8888 .as_ref()
8889 .and_then(|workspace| {
8890 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
8891 })
8892 .or_else(|| persistence::read_default_window_bounds());
8893
8894 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
8895 (Some(serialized_bounds), Some(serialized_display))
8896 } else {
8897 (None, None)
8898 }
8899 };
8900
8901 let centered_layout = serialized_workspace
8902 .as_ref()
8903 .map(|w| w.centered_layout)
8904 .unwrap_or(false);
8905
8906 Ok(WorkspacePosition {
8907 window_bounds,
8908 display,
8909 centered_layout,
8910 })
8911 })
8912}
8913
8914pub fn with_active_or_new_workspace(
8915 cx: &mut App,
8916 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
8917) {
8918 match cx.active_window().and_then(|w| w.downcast::<Workspace>()) {
8919 Some(workspace) => {
8920 cx.defer(move |cx| {
8921 workspace
8922 .update(cx, |workspace, window, cx| f(workspace, window, cx))
8923 .log_err();
8924 });
8925 }
8926 None => {
8927 let app_state = AppState::global(cx);
8928 if let Some(app_state) = app_state.upgrade() {
8929 open_new(
8930 OpenOptions::default(),
8931 app_state,
8932 cx,
8933 move |workspace, window, cx| f(workspace, window, cx),
8934 )
8935 .detach_and_log_err(cx);
8936 }
8937 }
8938 }
8939}
8940
8941#[cfg(test)]
8942mod tests {
8943 use std::{cell::RefCell, rc::Rc};
8944
8945 use super::*;
8946 use crate::{
8947 dock::{PanelEvent, test::TestPanel},
8948 item::{
8949 ItemBufferKind, ItemEvent,
8950 test::{TestItem, TestProjectItem},
8951 },
8952 };
8953 use fs::FakeFs;
8954 use gpui::{
8955 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
8956 UpdateGlobal, VisualTestContext, px,
8957 };
8958 use project::{Project, ProjectEntryId};
8959 use serde_json::json;
8960 use settings::SettingsStore;
8961 use util::rel_path::rel_path;
8962
8963 #[gpui::test]
8964 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
8965 init_test(cx);
8966
8967 let fs = FakeFs::new(cx.executor());
8968 let project = Project::test(fs, [], cx).await;
8969 let (workspace, cx) =
8970 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8971
8972 // Adding an item with no ambiguity renders the tab without detail.
8973 let item1 = cx.new(|cx| {
8974 let mut item = TestItem::new(cx);
8975 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
8976 item
8977 });
8978 workspace.update_in(cx, |workspace, window, cx| {
8979 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
8980 });
8981 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
8982
8983 // Adding an item that creates ambiguity increases the level of detail on
8984 // both tabs.
8985 let item2 = cx.new_window_entity(|_window, cx| {
8986 let mut item = TestItem::new(cx);
8987 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
8988 item
8989 });
8990 workspace.update_in(cx, |workspace, window, cx| {
8991 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
8992 });
8993 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
8994 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
8995
8996 // Adding an item that creates ambiguity increases the level of detail only
8997 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
8998 // we stop at the highest detail available.
8999 let item3 = cx.new(|cx| {
9000 let mut item = TestItem::new(cx);
9001 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
9002 item
9003 });
9004 workspace.update_in(cx, |workspace, window, cx| {
9005 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
9006 });
9007 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
9008 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
9009 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
9010 }
9011
9012 #[gpui::test]
9013 async fn test_tracking_active_path(cx: &mut TestAppContext) {
9014 init_test(cx);
9015
9016 let fs = FakeFs::new(cx.executor());
9017 fs.insert_tree(
9018 "/root1",
9019 json!({
9020 "one.txt": "",
9021 "two.txt": "",
9022 }),
9023 )
9024 .await;
9025 fs.insert_tree(
9026 "/root2",
9027 json!({
9028 "three.txt": "",
9029 }),
9030 )
9031 .await;
9032
9033 let project = Project::test(fs, ["root1".as_ref()], cx).await;
9034 let (workspace, cx) =
9035 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9036 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9037 let worktree_id = project.update(cx, |project, cx| {
9038 project.worktrees(cx).next().unwrap().read(cx).id()
9039 });
9040
9041 let item1 = cx.new(|cx| {
9042 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
9043 });
9044 let item2 = cx.new(|cx| {
9045 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
9046 });
9047
9048 // Add an item to an empty pane
9049 workspace.update_in(cx, |workspace, window, cx| {
9050 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
9051 });
9052 project.update(cx, |project, cx| {
9053 assert_eq!(
9054 project.active_entry(),
9055 project
9056 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
9057 .map(|e| e.id)
9058 );
9059 });
9060 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
9061
9062 // Add a second item to a non-empty pane
9063 workspace.update_in(cx, |workspace, window, cx| {
9064 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
9065 });
9066 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
9067 project.update(cx, |project, cx| {
9068 assert_eq!(
9069 project.active_entry(),
9070 project
9071 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
9072 .map(|e| e.id)
9073 );
9074 });
9075
9076 // Close the active item
9077 pane.update_in(cx, |pane, window, cx| {
9078 pane.close_active_item(&Default::default(), window, cx)
9079 })
9080 .await
9081 .unwrap();
9082 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
9083 project.update(cx, |project, cx| {
9084 assert_eq!(
9085 project.active_entry(),
9086 project
9087 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
9088 .map(|e| e.id)
9089 );
9090 });
9091
9092 // Add a project folder
9093 project
9094 .update(cx, |project, cx| {
9095 project.find_or_create_worktree("root2", true, cx)
9096 })
9097 .await
9098 .unwrap();
9099 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
9100
9101 // Remove a project folder
9102 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
9103 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
9104 }
9105
9106 #[gpui::test]
9107 async fn test_close_window(cx: &mut TestAppContext) {
9108 init_test(cx);
9109
9110 let fs = FakeFs::new(cx.executor());
9111 fs.insert_tree("/root", json!({ "one": "" })).await;
9112
9113 let project = Project::test(fs, ["root".as_ref()], cx).await;
9114 let (workspace, cx) =
9115 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9116
9117 // When there are no dirty items, there's nothing to do.
9118 let item1 = cx.new(TestItem::new);
9119 workspace.update_in(cx, |w, window, cx| {
9120 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
9121 });
9122 let task = workspace.update_in(cx, |w, window, cx| {
9123 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
9124 });
9125 assert!(task.await.unwrap());
9126
9127 // When there are dirty untitled items, prompt to save each one. If the user
9128 // cancels any prompt, then abort.
9129 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
9130 let item3 = cx.new(|cx| {
9131 TestItem::new(cx)
9132 .with_dirty(true)
9133 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
9134 });
9135 workspace.update_in(cx, |w, window, cx| {
9136 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
9137 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
9138 });
9139 let task = workspace.update_in(cx, |w, window, cx| {
9140 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
9141 });
9142 cx.executor().run_until_parked();
9143 cx.simulate_prompt_answer("Cancel"); // cancel save all
9144 cx.executor().run_until_parked();
9145 assert!(!cx.has_pending_prompt());
9146 assert!(!task.await.unwrap());
9147 }
9148
9149 #[gpui::test]
9150 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
9151 init_test(cx);
9152
9153 // Register TestItem as a serializable item
9154 cx.update(|cx| {
9155 register_serializable_item::<TestItem>(cx);
9156 });
9157
9158 let fs = FakeFs::new(cx.executor());
9159 fs.insert_tree("/root", json!({ "one": "" })).await;
9160
9161 let project = Project::test(fs, ["root".as_ref()], cx).await;
9162 let (workspace, cx) =
9163 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9164
9165 // When there are dirty untitled items, but they can serialize, then there is no prompt.
9166 let item1 = cx.new(|cx| {
9167 TestItem::new(cx)
9168 .with_dirty(true)
9169 .with_serialize(|| Some(Task::ready(Ok(()))))
9170 });
9171 let item2 = cx.new(|cx| {
9172 TestItem::new(cx)
9173 .with_dirty(true)
9174 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
9175 .with_serialize(|| Some(Task::ready(Ok(()))))
9176 });
9177 workspace.update_in(cx, |w, window, cx| {
9178 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
9179 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
9180 });
9181 let task = workspace.update_in(cx, |w, window, cx| {
9182 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
9183 });
9184 assert!(task.await.unwrap());
9185 }
9186
9187 #[gpui::test]
9188 async fn test_close_pane_items(cx: &mut TestAppContext) {
9189 init_test(cx);
9190
9191 let fs = FakeFs::new(cx.executor());
9192
9193 let project = Project::test(fs, None, cx).await;
9194 let (workspace, cx) =
9195 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9196
9197 let item1 = cx.new(|cx| {
9198 TestItem::new(cx)
9199 .with_dirty(true)
9200 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
9201 });
9202 let item2 = cx.new(|cx| {
9203 TestItem::new(cx)
9204 .with_dirty(true)
9205 .with_conflict(true)
9206 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
9207 });
9208 let item3 = cx.new(|cx| {
9209 TestItem::new(cx)
9210 .with_dirty(true)
9211 .with_conflict(true)
9212 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
9213 });
9214 let item4 = cx.new(|cx| {
9215 TestItem::new(cx).with_dirty(true).with_project_items(&[{
9216 let project_item = TestProjectItem::new_untitled(cx);
9217 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
9218 project_item
9219 }])
9220 });
9221 let pane = workspace.update_in(cx, |workspace, window, cx| {
9222 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
9223 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
9224 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
9225 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
9226 workspace.active_pane().clone()
9227 });
9228
9229 let close_items = pane.update_in(cx, |pane, window, cx| {
9230 pane.activate_item(1, true, true, window, cx);
9231 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
9232 let item1_id = item1.item_id();
9233 let item3_id = item3.item_id();
9234 let item4_id = item4.item_id();
9235 pane.close_items(window, cx, SaveIntent::Close, move |id| {
9236 [item1_id, item3_id, item4_id].contains(&id)
9237 })
9238 });
9239 cx.executor().run_until_parked();
9240
9241 assert!(cx.has_pending_prompt());
9242 cx.simulate_prompt_answer("Save all");
9243
9244 cx.executor().run_until_parked();
9245
9246 // Item 1 is saved. There's a prompt to save item 3.
9247 pane.update(cx, |pane, cx| {
9248 assert_eq!(item1.read(cx).save_count, 1);
9249 assert_eq!(item1.read(cx).save_as_count, 0);
9250 assert_eq!(item1.read(cx).reload_count, 0);
9251 assert_eq!(pane.items_len(), 3);
9252 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
9253 });
9254 assert!(cx.has_pending_prompt());
9255
9256 // Cancel saving item 3.
9257 cx.simulate_prompt_answer("Discard");
9258 cx.executor().run_until_parked();
9259
9260 // Item 3 is reloaded. There's a prompt to save item 4.
9261 pane.update(cx, |pane, cx| {
9262 assert_eq!(item3.read(cx).save_count, 0);
9263 assert_eq!(item3.read(cx).save_as_count, 0);
9264 assert_eq!(item3.read(cx).reload_count, 1);
9265 assert_eq!(pane.items_len(), 2);
9266 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
9267 });
9268
9269 // There's a prompt for a path for item 4.
9270 cx.simulate_new_path_selection(|_| Some(Default::default()));
9271 close_items.await.unwrap();
9272
9273 // The requested items are closed.
9274 pane.update(cx, |pane, cx| {
9275 assert_eq!(item4.read(cx).save_count, 0);
9276 assert_eq!(item4.read(cx).save_as_count, 1);
9277 assert_eq!(item4.read(cx).reload_count, 0);
9278 assert_eq!(pane.items_len(), 1);
9279 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
9280 });
9281 }
9282
9283 #[gpui::test]
9284 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
9285 init_test(cx);
9286
9287 let fs = FakeFs::new(cx.executor());
9288 let project = Project::test(fs, [], cx).await;
9289 let (workspace, cx) =
9290 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9291
9292 // Create several workspace items with single project entries, and two
9293 // workspace items with multiple project entries.
9294 let single_entry_items = (0..=4)
9295 .map(|project_entry_id| {
9296 cx.new(|cx| {
9297 TestItem::new(cx)
9298 .with_dirty(true)
9299 .with_project_items(&[dirty_project_item(
9300 project_entry_id,
9301 &format!("{project_entry_id}.txt"),
9302 cx,
9303 )])
9304 })
9305 })
9306 .collect::<Vec<_>>();
9307 let item_2_3 = cx.new(|cx| {
9308 TestItem::new(cx)
9309 .with_dirty(true)
9310 .with_buffer_kind(ItemBufferKind::Multibuffer)
9311 .with_project_items(&[
9312 single_entry_items[2].read(cx).project_items[0].clone(),
9313 single_entry_items[3].read(cx).project_items[0].clone(),
9314 ])
9315 });
9316 let item_3_4 = cx.new(|cx| {
9317 TestItem::new(cx)
9318 .with_dirty(true)
9319 .with_buffer_kind(ItemBufferKind::Multibuffer)
9320 .with_project_items(&[
9321 single_entry_items[3].read(cx).project_items[0].clone(),
9322 single_entry_items[4].read(cx).project_items[0].clone(),
9323 ])
9324 });
9325
9326 // Create two panes that contain the following project entries:
9327 // left pane:
9328 // multi-entry items: (2, 3)
9329 // single-entry items: 0, 2, 3, 4
9330 // right pane:
9331 // single-entry items: 4, 1
9332 // multi-entry items: (3, 4)
9333 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
9334 let left_pane = workspace.active_pane().clone();
9335 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
9336 workspace.add_item_to_active_pane(
9337 single_entry_items[0].boxed_clone(),
9338 None,
9339 true,
9340 window,
9341 cx,
9342 );
9343 workspace.add_item_to_active_pane(
9344 single_entry_items[2].boxed_clone(),
9345 None,
9346 true,
9347 window,
9348 cx,
9349 );
9350 workspace.add_item_to_active_pane(
9351 single_entry_items[3].boxed_clone(),
9352 None,
9353 true,
9354 window,
9355 cx,
9356 );
9357 workspace.add_item_to_active_pane(
9358 single_entry_items[4].boxed_clone(),
9359 None,
9360 true,
9361 window,
9362 cx,
9363 );
9364
9365 let right_pane =
9366 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
9367
9368 let boxed_clone = single_entry_items[1].boxed_clone();
9369 let right_pane = window.spawn(cx, async move |cx| {
9370 right_pane.await.inspect(|right_pane| {
9371 right_pane
9372 .update_in(cx, |pane, window, cx| {
9373 pane.add_item(boxed_clone, true, true, None, window, cx);
9374 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
9375 })
9376 .unwrap();
9377 })
9378 });
9379
9380 (left_pane, right_pane)
9381 });
9382 let right_pane = right_pane.await.unwrap();
9383 cx.focus(&right_pane);
9384
9385 let mut close = right_pane.update_in(cx, |pane, window, cx| {
9386 pane.close_all_items(&CloseAllItems::default(), window, cx)
9387 .unwrap()
9388 });
9389 cx.executor().run_until_parked();
9390
9391 let msg = cx.pending_prompt().unwrap().0;
9392 assert!(msg.contains("1.txt"));
9393 assert!(!msg.contains("2.txt"));
9394 assert!(!msg.contains("3.txt"));
9395 assert!(!msg.contains("4.txt"));
9396
9397 cx.simulate_prompt_answer("Cancel");
9398 close.await;
9399
9400 left_pane
9401 .update_in(cx, |left_pane, window, cx| {
9402 left_pane.close_item_by_id(
9403 single_entry_items[3].entity_id(),
9404 SaveIntent::Skip,
9405 window,
9406 cx,
9407 )
9408 })
9409 .await
9410 .unwrap();
9411
9412 close = right_pane.update_in(cx, |pane, window, cx| {
9413 pane.close_all_items(&CloseAllItems::default(), window, cx)
9414 .unwrap()
9415 });
9416 cx.executor().run_until_parked();
9417
9418 let details = cx.pending_prompt().unwrap().1;
9419 assert!(details.contains("1.txt"));
9420 assert!(!details.contains("2.txt"));
9421 assert!(details.contains("3.txt"));
9422 // ideally this assertion could be made, but today we can only
9423 // save whole items not project items, so the orphaned item 3 causes
9424 // 4 to be saved too.
9425 // assert!(!details.contains("4.txt"));
9426
9427 cx.simulate_prompt_answer("Save all");
9428
9429 cx.executor().run_until_parked();
9430 close.await;
9431 right_pane.read_with(cx, |pane, _| {
9432 assert_eq!(pane.items_len(), 0);
9433 });
9434 }
9435
9436 #[gpui::test]
9437 async fn test_autosave(cx: &mut gpui::TestAppContext) {
9438 init_test(cx);
9439
9440 let fs = FakeFs::new(cx.executor());
9441 let project = Project::test(fs, [], cx).await;
9442 let (workspace, cx) =
9443 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9444 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9445
9446 let item = cx.new(|cx| {
9447 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
9448 });
9449 let item_id = item.entity_id();
9450 workspace.update_in(cx, |workspace, window, cx| {
9451 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
9452 });
9453
9454 // Autosave on window change.
9455 item.update(cx, |item, cx| {
9456 SettingsStore::update_global(cx, |settings, cx| {
9457 settings.update_user_settings(cx, |settings| {
9458 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
9459 })
9460 });
9461 item.is_dirty = true;
9462 });
9463
9464 // Deactivating the window saves the file.
9465 cx.deactivate_window();
9466 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
9467
9468 // Re-activating the window doesn't save the file.
9469 cx.update(|window, _| window.activate_window());
9470 cx.executor().run_until_parked();
9471 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
9472
9473 // Autosave on focus change.
9474 item.update_in(cx, |item, window, cx| {
9475 cx.focus_self(window);
9476 SettingsStore::update_global(cx, |settings, cx| {
9477 settings.update_user_settings(cx, |settings| {
9478 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
9479 })
9480 });
9481 item.is_dirty = true;
9482 });
9483 // Blurring the item saves the file.
9484 item.update_in(cx, |_, window, _| window.blur());
9485 cx.executor().run_until_parked();
9486 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
9487
9488 // Deactivating the window still saves the file.
9489 item.update_in(cx, |item, window, cx| {
9490 cx.focus_self(window);
9491 item.is_dirty = true;
9492 });
9493 cx.deactivate_window();
9494 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
9495
9496 // Autosave after delay.
9497 item.update(cx, |item, cx| {
9498 SettingsStore::update_global(cx, |settings, cx| {
9499 settings.update_user_settings(cx, |settings| {
9500 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
9501 milliseconds: 500.into(),
9502 });
9503 })
9504 });
9505 item.is_dirty = true;
9506 cx.emit(ItemEvent::Edit);
9507 });
9508
9509 // Delay hasn't fully expired, so the file is still dirty and unsaved.
9510 cx.executor().advance_clock(Duration::from_millis(250));
9511 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
9512
9513 // After delay expires, the file is saved.
9514 cx.executor().advance_clock(Duration::from_millis(250));
9515 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
9516
9517 // Autosave after delay, should save earlier than delay if tab is closed
9518 item.update(cx, |item, cx| {
9519 item.is_dirty = true;
9520 cx.emit(ItemEvent::Edit);
9521 });
9522 cx.executor().advance_clock(Duration::from_millis(250));
9523 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
9524
9525 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
9526 pane.update_in(cx, |pane, window, cx| {
9527 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
9528 })
9529 .await
9530 .unwrap();
9531 assert!(!cx.has_pending_prompt());
9532 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
9533
9534 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
9535 workspace.update_in(cx, |workspace, window, cx| {
9536 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
9537 });
9538 item.update_in(cx, |item, _window, cx| {
9539 item.is_dirty = true;
9540 for project_item in &mut item.project_items {
9541 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
9542 }
9543 });
9544 cx.run_until_parked();
9545 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
9546
9547 // Autosave on focus change, ensuring closing the tab counts as such.
9548 item.update(cx, |item, cx| {
9549 SettingsStore::update_global(cx, |settings, cx| {
9550 settings.update_user_settings(cx, |settings| {
9551 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
9552 })
9553 });
9554 item.is_dirty = true;
9555 for project_item in &mut item.project_items {
9556 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
9557 }
9558 });
9559
9560 pane.update_in(cx, |pane, window, cx| {
9561 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
9562 })
9563 .await
9564 .unwrap();
9565 assert!(!cx.has_pending_prompt());
9566 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
9567
9568 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
9569 workspace.update_in(cx, |workspace, window, cx| {
9570 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
9571 });
9572 item.update_in(cx, |item, window, cx| {
9573 item.project_items[0].update(cx, |item, _| {
9574 item.entry_id = None;
9575 });
9576 item.is_dirty = true;
9577 window.blur();
9578 });
9579 cx.run_until_parked();
9580 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
9581
9582 // Ensure autosave is prevented for deleted files also when closing the buffer.
9583 let _close_items = pane.update_in(cx, |pane, window, cx| {
9584 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
9585 });
9586 cx.run_until_parked();
9587 assert!(cx.has_pending_prompt());
9588 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
9589 }
9590
9591 #[gpui::test]
9592 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
9593 init_test(cx);
9594
9595 let fs = FakeFs::new(cx.executor());
9596
9597 let project = Project::test(fs, [], cx).await;
9598 let (workspace, cx) =
9599 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9600
9601 let item = cx.new(|cx| {
9602 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
9603 });
9604 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9605 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
9606 let toolbar_notify_count = Rc::new(RefCell::new(0));
9607
9608 workspace.update_in(cx, |workspace, window, cx| {
9609 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
9610 let toolbar_notification_count = toolbar_notify_count.clone();
9611 cx.observe_in(&toolbar, window, move |_, _, _, _| {
9612 *toolbar_notification_count.borrow_mut() += 1
9613 })
9614 .detach();
9615 });
9616
9617 pane.read_with(cx, |pane, _| {
9618 assert!(!pane.can_navigate_backward());
9619 assert!(!pane.can_navigate_forward());
9620 });
9621
9622 item.update_in(cx, |item, _, cx| {
9623 item.set_state("one".to_string(), cx);
9624 });
9625
9626 // Toolbar must be notified to re-render the navigation buttons
9627 assert_eq!(*toolbar_notify_count.borrow(), 1);
9628
9629 pane.read_with(cx, |pane, _| {
9630 assert!(pane.can_navigate_backward());
9631 assert!(!pane.can_navigate_forward());
9632 });
9633
9634 workspace
9635 .update_in(cx, |workspace, window, cx| {
9636 workspace.go_back(pane.downgrade(), window, cx)
9637 })
9638 .await
9639 .unwrap();
9640
9641 assert_eq!(*toolbar_notify_count.borrow(), 2);
9642 pane.read_with(cx, |pane, _| {
9643 assert!(!pane.can_navigate_backward());
9644 assert!(pane.can_navigate_forward());
9645 });
9646 }
9647
9648 #[gpui::test]
9649 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
9650 init_test(cx);
9651 let fs = FakeFs::new(cx.executor());
9652
9653 let project = Project::test(fs, [], cx).await;
9654 let (workspace, cx) =
9655 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9656
9657 let panel = workspace.update_in(cx, |workspace, window, cx| {
9658 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
9659 workspace.add_panel(panel.clone(), window, cx);
9660
9661 workspace
9662 .right_dock()
9663 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
9664
9665 panel
9666 });
9667
9668 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9669 pane.update_in(cx, |pane, window, cx| {
9670 let item = cx.new(TestItem::new);
9671 pane.add_item(Box::new(item), true, true, None, window, cx);
9672 });
9673
9674 // Transfer focus from center to panel
9675 workspace.update_in(cx, |workspace, window, cx| {
9676 workspace.toggle_panel_focus::<TestPanel>(window, cx);
9677 });
9678
9679 workspace.update_in(cx, |workspace, window, cx| {
9680 assert!(workspace.right_dock().read(cx).is_open());
9681 assert!(!panel.is_zoomed(window, cx));
9682 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9683 });
9684
9685 // Transfer focus from panel to center
9686 workspace.update_in(cx, |workspace, window, cx| {
9687 workspace.toggle_panel_focus::<TestPanel>(window, cx);
9688 });
9689
9690 workspace.update_in(cx, |workspace, window, cx| {
9691 assert!(workspace.right_dock().read(cx).is_open());
9692 assert!(!panel.is_zoomed(window, cx));
9693 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9694 });
9695
9696 // Close the dock
9697 workspace.update_in(cx, |workspace, window, cx| {
9698 workspace.toggle_dock(DockPosition::Right, window, cx);
9699 });
9700
9701 workspace.update_in(cx, |workspace, window, cx| {
9702 assert!(!workspace.right_dock().read(cx).is_open());
9703 assert!(!panel.is_zoomed(window, cx));
9704 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9705 });
9706
9707 // Open the dock
9708 workspace.update_in(cx, |workspace, window, cx| {
9709 workspace.toggle_dock(DockPosition::Right, window, cx);
9710 });
9711
9712 workspace.update_in(cx, |workspace, window, cx| {
9713 assert!(workspace.right_dock().read(cx).is_open());
9714 assert!(!panel.is_zoomed(window, cx));
9715 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9716 });
9717
9718 // Focus and zoom panel
9719 panel.update_in(cx, |panel, window, cx| {
9720 cx.focus_self(window);
9721 panel.set_zoomed(true, window, cx)
9722 });
9723
9724 workspace.update_in(cx, |workspace, window, cx| {
9725 assert!(workspace.right_dock().read(cx).is_open());
9726 assert!(panel.is_zoomed(window, cx));
9727 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9728 });
9729
9730 // Transfer focus to the center closes the dock
9731 workspace.update_in(cx, |workspace, window, cx| {
9732 workspace.toggle_panel_focus::<TestPanel>(window, cx);
9733 });
9734
9735 workspace.update_in(cx, |workspace, window, cx| {
9736 assert!(!workspace.right_dock().read(cx).is_open());
9737 assert!(panel.is_zoomed(window, cx));
9738 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9739 });
9740
9741 // Transferring focus back to the panel keeps it zoomed
9742 workspace.update_in(cx, |workspace, window, cx| {
9743 workspace.toggle_panel_focus::<TestPanel>(window, cx);
9744 });
9745
9746 workspace.update_in(cx, |workspace, window, cx| {
9747 assert!(workspace.right_dock().read(cx).is_open());
9748 assert!(panel.is_zoomed(window, cx));
9749 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9750 });
9751
9752 // Close the dock while it is zoomed
9753 workspace.update_in(cx, |workspace, window, cx| {
9754 workspace.toggle_dock(DockPosition::Right, window, cx)
9755 });
9756
9757 workspace.update_in(cx, |workspace, window, cx| {
9758 assert!(!workspace.right_dock().read(cx).is_open());
9759 assert!(panel.is_zoomed(window, cx));
9760 assert!(workspace.zoomed.is_none());
9761 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9762 });
9763
9764 // Opening the dock, when it's zoomed, retains focus
9765 workspace.update_in(cx, |workspace, window, cx| {
9766 workspace.toggle_dock(DockPosition::Right, window, cx)
9767 });
9768
9769 workspace.update_in(cx, |workspace, window, cx| {
9770 assert!(workspace.right_dock().read(cx).is_open());
9771 assert!(panel.is_zoomed(window, cx));
9772 assert!(workspace.zoomed.is_some());
9773 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
9774 });
9775
9776 // Unzoom and close the panel, zoom the active pane.
9777 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
9778 workspace.update_in(cx, |workspace, window, cx| {
9779 workspace.toggle_dock(DockPosition::Right, window, cx)
9780 });
9781 pane.update_in(cx, |pane, window, cx| {
9782 pane.toggle_zoom(&Default::default(), window, cx)
9783 });
9784
9785 // Opening a dock unzooms the pane.
9786 workspace.update_in(cx, |workspace, window, cx| {
9787 workspace.toggle_dock(DockPosition::Right, window, cx)
9788 });
9789 workspace.update_in(cx, |workspace, window, cx| {
9790 let pane = pane.read(cx);
9791 assert!(!pane.is_zoomed());
9792 assert!(!pane.focus_handle(cx).is_focused(window));
9793 assert!(workspace.right_dock().read(cx).is_open());
9794 assert!(workspace.zoomed.is_none());
9795 });
9796 }
9797
9798 #[gpui::test]
9799 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
9800 init_test(cx);
9801 let fs = FakeFs::new(cx.executor());
9802
9803 let project = Project::test(fs, [], cx).await;
9804 let (workspace, cx) =
9805 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9806
9807 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
9808 workspace.active_pane().clone()
9809 });
9810
9811 // Add an item to the pane so it can be zoomed
9812 workspace.update_in(cx, |workspace, window, cx| {
9813 let item = cx.new(TestItem::new);
9814 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
9815 });
9816
9817 // Initially not zoomed
9818 workspace.update_in(cx, |workspace, _window, cx| {
9819 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
9820 assert!(
9821 workspace.zoomed.is_none(),
9822 "Workspace should track no zoomed pane"
9823 );
9824 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
9825 });
9826
9827 // Zoom In
9828 pane.update_in(cx, |pane, window, cx| {
9829 pane.zoom_in(&crate::ZoomIn, window, cx);
9830 });
9831
9832 workspace.update_in(cx, |workspace, window, cx| {
9833 assert!(
9834 pane.read(cx).is_zoomed(),
9835 "Pane should be zoomed after ZoomIn"
9836 );
9837 assert!(
9838 workspace.zoomed.is_some(),
9839 "Workspace should track the zoomed pane"
9840 );
9841 assert!(
9842 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
9843 "ZoomIn should focus the pane"
9844 );
9845 });
9846
9847 // Zoom In again is a no-op
9848 pane.update_in(cx, |pane, window, cx| {
9849 pane.zoom_in(&crate::ZoomIn, window, cx);
9850 });
9851
9852 workspace.update_in(cx, |workspace, window, cx| {
9853 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
9854 assert!(
9855 workspace.zoomed.is_some(),
9856 "Workspace still tracks zoomed pane"
9857 );
9858 assert!(
9859 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
9860 "Pane remains focused after repeated ZoomIn"
9861 );
9862 });
9863
9864 // Zoom Out
9865 pane.update_in(cx, |pane, window, cx| {
9866 pane.zoom_out(&crate::ZoomOut, window, cx);
9867 });
9868
9869 workspace.update_in(cx, |workspace, _window, cx| {
9870 assert!(
9871 !pane.read(cx).is_zoomed(),
9872 "Pane should unzoom after ZoomOut"
9873 );
9874 assert!(
9875 workspace.zoomed.is_none(),
9876 "Workspace clears zoom tracking after ZoomOut"
9877 );
9878 });
9879
9880 // Zoom Out again is a no-op
9881 pane.update_in(cx, |pane, window, cx| {
9882 pane.zoom_out(&crate::ZoomOut, window, cx);
9883 });
9884
9885 workspace.update_in(cx, |workspace, _window, cx| {
9886 assert!(
9887 !pane.read(cx).is_zoomed(),
9888 "Second ZoomOut keeps pane unzoomed"
9889 );
9890 assert!(
9891 workspace.zoomed.is_none(),
9892 "Workspace remains without zoomed pane"
9893 );
9894 });
9895 }
9896
9897 #[gpui::test]
9898 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
9899 init_test(cx);
9900 let fs = FakeFs::new(cx.executor());
9901
9902 let project = Project::test(fs, [], cx).await;
9903 let (workspace, cx) =
9904 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9905 workspace.update_in(cx, |workspace, window, cx| {
9906 // Open two docks
9907 let left_dock = workspace.dock_at_position(DockPosition::Left);
9908 let right_dock = workspace.dock_at_position(DockPosition::Right);
9909
9910 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
9911 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
9912
9913 assert!(left_dock.read(cx).is_open());
9914 assert!(right_dock.read(cx).is_open());
9915 });
9916
9917 workspace.update_in(cx, |workspace, window, cx| {
9918 // Toggle all docks - should close both
9919 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
9920
9921 let left_dock = workspace.dock_at_position(DockPosition::Left);
9922 let right_dock = workspace.dock_at_position(DockPosition::Right);
9923 assert!(!left_dock.read(cx).is_open());
9924 assert!(!right_dock.read(cx).is_open());
9925 });
9926
9927 workspace.update_in(cx, |workspace, window, cx| {
9928 // Toggle again - should reopen both
9929 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
9930
9931 let left_dock = workspace.dock_at_position(DockPosition::Left);
9932 let right_dock = workspace.dock_at_position(DockPosition::Right);
9933 assert!(left_dock.read(cx).is_open());
9934 assert!(right_dock.read(cx).is_open());
9935 });
9936 }
9937
9938 #[gpui::test]
9939 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
9940 init_test(cx);
9941 let fs = FakeFs::new(cx.executor());
9942
9943 let project = Project::test(fs, [], cx).await;
9944 let (workspace, cx) =
9945 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9946 workspace.update_in(cx, |workspace, window, cx| {
9947 // Open two docks
9948 let left_dock = workspace.dock_at_position(DockPosition::Left);
9949 let right_dock = workspace.dock_at_position(DockPosition::Right);
9950
9951 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
9952 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
9953
9954 assert!(left_dock.read(cx).is_open());
9955 assert!(right_dock.read(cx).is_open());
9956 });
9957
9958 workspace.update_in(cx, |workspace, window, cx| {
9959 // Close them manually
9960 workspace.toggle_dock(DockPosition::Left, window, cx);
9961 workspace.toggle_dock(DockPosition::Right, window, cx);
9962
9963 let left_dock = workspace.dock_at_position(DockPosition::Left);
9964 let right_dock = workspace.dock_at_position(DockPosition::Right);
9965 assert!(!left_dock.read(cx).is_open());
9966 assert!(!right_dock.read(cx).is_open());
9967 });
9968
9969 workspace.update_in(cx, |workspace, window, cx| {
9970 // Toggle all docks - only last closed (right dock) should reopen
9971 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
9972
9973 let left_dock = workspace.dock_at_position(DockPosition::Left);
9974 let right_dock = workspace.dock_at_position(DockPosition::Right);
9975 assert!(!left_dock.read(cx).is_open());
9976 assert!(right_dock.read(cx).is_open());
9977 });
9978 }
9979
9980 #[gpui::test]
9981 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
9982 init_test(cx);
9983 let fs = FakeFs::new(cx.executor());
9984 let project = Project::test(fs, [], cx).await;
9985 let (workspace, cx) =
9986 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9987
9988 // Open two docks (left and right) with one panel each
9989 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
9990 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
9991 workspace.add_panel(left_panel.clone(), window, cx);
9992
9993 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
9994 workspace.add_panel(right_panel.clone(), window, cx);
9995
9996 workspace.toggle_dock(DockPosition::Left, window, cx);
9997 workspace.toggle_dock(DockPosition::Right, window, cx);
9998
9999 // Verify initial state
10000 assert!(
10001 workspace.left_dock().read(cx).is_open(),
10002 "Left dock should be open"
10003 );
10004 assert_eq!(
10005 workspace
10006 .left_dock()
10007 .read(cx)
10008 .visible_panel()
10009 .unwrap()
10010 .panel_id(),
10011 left_panel.panel_id(),
10012 "Left panel should be visible in left dock"
10013 );
10014 assert!(
10015 workspace.right_dock().read(cx).is_open(),
10016 "Right dock should be open"
10017 );
10018 assert_eq!(
10019 workspace
10020 .right_dock()
10021 .read(cx)
10022 .visible_panel()
10023 .unwrap()
10024 .panel_id(),
10025 right_panel.panel_id(),
10026 "Right panel should be visible in right dock"
10027 );
10028 assert!(
10029 !workspace.bottom_dock().read(cx).is_open(),
10030 "Bottom dock should be closed"
10031 );
10032
10033 (left_panel, right_panel)
10034 });
10035
10036 // Focus the left panel and move it to the next position (bottom dock)
10037 workspace.update_in(cx, |workspace, window, cx| {
10038 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
10039 assert!(
10040 left_panel.read(cx).focus_handle(cx).is_focused(window),
10041 "Left panel should be focused"
10042 );
10043 });
10044
10045 cx.dispatch_action(MoveFocusedPanelToNextPosition);
10046
10047 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
10048 workspace.update(cx, |workspace, cx| {
10049 assert!(
10050 !workspace.left_dock().read(cx).is_open(),
10051 "Left dock should be closed"
10052 );
10053 assert!(
10054 workspace.bottom_dock().read(cx).is_open(),
10055 "Bottom dock should now be open"
10056 );
10057 assert_eq!(
10058 left_panel.read(cx).position,
10059 DockPosition::Bottom,
10060 "Left panel should now be in the bottom dock"
10061 );
10062 assert_eq!(
10063 workspace
10064 .bottom_dock()
10065 .read(cx)
10066 .visible_panel()
10067 .unwrap()
10068 .panel_id(),
10069 left_panel.panel_id(),
10070 "Left panel should be the visible panel in the bottom dock"
10071 );
10072 });
10073
10074 // Toggle all docks off
10075 workspace.update_in(cx, |workspace, window, cx| {
10076 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10077 assert!(
10078 !workspace.left_dock().read(cx).is_open(),
10079 "Left dock should be closed"
10080 );
10081 assert!(
10082 !workspace.right_dock().read(cx).is_open(),
10083 "Right dock should be closed"
10084 );
10085 assert!(
10086 !workspace.bottom_dock().read(cx).is_open(),
10087 "Bottom dock should be closed"
10088 );
10089 });
10090
10091 // Toggle all docks back on and verify positions are restored
10092 workspace.update_in(cx, |workspace, window, cx| {
10093 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10094 assert!(
10095 !workspace.left_dock().read(cx).is_open(),
10096 "Left dock should remain closed"
10097 );
10098 assert!(
10099 workspace.right_dock().read(cx).is_open(),
10100 "Right dock should remain open"
10101 );
10102 assert!(
10103 workspace.bottom_dock().read(cx).is_open(),
10104 "Bottom dock should remain open"
10105 );
10106 assert_eq!(
10107 left_panel.read(cx).position,
10108 DockPosition::Bottom,
10109 "Left panel should remain in the bottom dock"
10110 );
10111 assert_eq!(
10112 right_panel.read(cx).position,
10113 DockPosition::Right,
10114 "Right panel should remain in the right dock"
10115 );
10116 assert_eq!(
10117 workspace
10118 .bottom_dock()
10119 .read(cx)
10120 .visible_panel()
10121 .unwrap()
10122 .panel_id(),
10123 left_panel.panel_id(),
10124 "Left panel should be the visible panel in the right dock"
10125 );
10126 });
10127 }
10128
10129 #[gpui::test]
10130 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
10131 init_test(cx);
10132
10133 let fs = FakeFs::new(cx.executor());
10134
10135 let project = Project::test(fs, None, cx).await;
10136 let (workspace, cx) =
10137 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10138
10139 // Let's arrange the panes like this:
10140 //
10141 // +-----------------------+
10142 // | top |
10143 // +------+--------+-------+
10144 // | left | center | right |
10145 // +------+--------+-------+
10146 // | bottom |
10147 // +-----------------------+
10148
10149 let top_item = cx.new(|cx| {
10150 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
10151 });
10152 let bottom_item = cx.new(|cx| {
10153 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
10154 });
10155 let left_item = cx.new(|cx| {
10156 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
10157 });
10158 let right_item = cx.new(|cx| {
10159 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
10160 });
10161 let center_item = cx.new(|cx| {
10162 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
10163 });
10164
10165 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10166 let top_pane_id = workspace.active_pane().entity_id();
10167 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
10168 workspace.split_pane(
10169 workspace.active_pane().clone(),
10170 SplitDirection::Down,
10171 window,
10172 cx,
10173 );
10174 top_pane_id
10175 });
10176 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10177 let bottom_pane_id = workspace.active_pane().entity_id();
10178 workspace.add_item_to_active_pane(
10179 Box::new(bottom_item.clone()),
10180 None,
10181 false,
10182 window,
10183 cx,
10184 );
10185 workspace.split_pane(
10186 workspace.active_pane().clone(),
10187 SplitDirection::Up,
10188 window,
10189 cx,
10190 );
10191 bottom_pane_id
10192 });
10193 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10194 let left_pane_id = workspace.active_pane().entity_id();
10195 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
10196 workspace.split_pane(
10197 workspace.active_pane().clone(),
10198 SplitDirection::Right,
10199 window,
10200 cx,
10201 );
10202 left_pane_id
10203 });
10204 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10205 let right_pane_id = workspace.active_pane().entity_id();
10206 workspace.add_item_to_active_pane(
10207 Box::new(right_item.clone()),
10208 None,
10209 false,
10210 window,
10211 cx,
10212 );
10213 workspace.split_pane(
10214 workspace.active_pane().clone(),
10215 SplitDirection::Left,
10216 window,
10217 cx,
10218 );
10219 right_pane_id
10220 });
10221 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10222 let center_pane_id = workspace.active_pane().entity_id();
10223 workspace.add_item_to_active_pane(
10224 Box::new(center_item.clone()),
10225 None,
10226 false,
10227 window,
10228 cx,
10229 );
10230 center_pane_id
10231 });
10232 cx.executor().run_until_parked();
10233
10234 workspace.update_in(cx, |workspace, window, cx| {
10235 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
10236
10237 // Join into next from center pane into right
10238 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10239 });
10240
10241 workspace.update_in(cx, |workspace, window, cx| {
10242 let active_pane = workspace.active_pane();
10243 assert_eq!(right_pane_id, active_pane.entity_id());
10244 assert_eq!(2, active_pane.read(cx).items_len());
10245 let item_ids_in_pane =
10246 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10247 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
10248 assert!(item_ids_in_pane.contains(&right_item.item_id()));
10249
10250 // Join into next from right pane into bottom
10251 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10252 });
10253
10254 workspace.update_in(cx, |workspace, window, cx| {
10255 let active_pane = workspace.active_pane();
10256 assert_eq!(bottom_pane_id, active_pane.entity_id());
10257 assert_eq!(3, active_pane.read(cx).items_len());
10258 let item_ids_in_pane =
10259 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10260 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
10261 assert!(item_ids_in_pane.contains(&right_item.item_id()));
10262 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
10263
10264 // Join into next from bottom pane into left
10265 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10266 });
10267
10268 workspace.update_in(cx, |workspace, window, cx| {
10269 let active_pane = workspace.active_pane();
10270 assert_eq!(left_pane_id, active_pane.entity_id());
10271 assert_eq!(4, active_pane.read(cx).items_len());
10272 let item_ids_in_pane =
10273 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10274 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
10275 assert!(item_ids_in_pane.contains(&right_item.item_id()));
10276 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
10277 assert!(item_ids_in_pane.contains(&left_item.item_id()));
10278
10279 // Join into next from left pane into top
10280 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10281 });
10282
10283 workspace.update_in(cx, |workspace, window, cx| {
10284 let active_pane = workspace.active_pane();
10285 assert_eq!(top_pane_id, active_pane.entity_id());
10286 assert_eq!(5, active_pane.read(cx).items_len());
10287 let item_ids_in_pane =
10288 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10289 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
10290 assert!(item_ids_in_pane.contains(&right_item.item_id()));
10291 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
10292 assert!(item_ids_in_pane.contains(&left_item.item_id()));
10293 assert!(item_ids_in_pane.contains(&top_item.item_id()));
10294
10295 // Single pane left: no-op
10296 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
10297 });
10298
10299 workspace.update(cx, |workspace, _cx| {
10300 let active_pane = workspace.active_pane();
10301 assert_eq!(top_pane_id, active_pane.entity_id());
10302 });
10303 }
10304
10305 fn add_an_item_to_active_pane(
10306 cx: &mut VisualTestContext,
10307 workspace: &Entity<Workspace>,
10308 item_id: u64,
10309 ) -> Entity<TestItem> {
10310 let item = cx.new(|cx| {
10311 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
10312 item_id,
10313 "item{item_id}.txt",
10314 cx,
10315 )])
10316 });
10317 workspace.update_in(cx, |workspace, window, cx| {
10318 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
10319 });
10320 item
10321 }
10322
10323 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
10324 workspace.update_in(cx, |workspace, window, cx| {
10325 workspace.split_pane(
10326 workspace.active_pane().clone(),
10327 SplitDirection::Right,
10328 window,
10329 cx,
10330 )
10331 })
10332 }
10333
10334 #[gpui::test]
10335 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
10336 init_test(cx);
10337 let fs = FakeFs::new(cx.executor());
10338 let project = Project::test(fs, None, cx).await;
10339 let (workspace, cx) =
10340 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10341
10342 add_an_item_to_active_pane(cx, &workspace, 1);
10343 split_pane(cx, &workspace);
10344 add_an_item_to_active_pane(cx, &workspace, 2);
10345 split_pane(cx, &workspace); // empty pane
10346 split_pane(cx, &workspace);
10347 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
10348
10349 cx.executor().run_until_parked();
10350
10351 workspace.update(cx, |workspace, cx| {
10352 let num_panes = workspace.panes().len();
10353 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
10354 let active_item = workspace
10355 .active_pane()
10356 .read(cx)
10357 .active_item()
10358 .expect("item is in focus");
10359
10360 assert_eq!(num_panes, 4);
10361 assert_eq!(num_items_in_current_pane, 1);
10362 assert_eq!(active_item.item_id(), last_item.item_id());
10363 });
10364
10365 workspace.update_in(cx, |workspace, window, cx| {
10366 workspace.join_all_panes(window, cx);
10367 });
10368
10369 workspace.update(cx, |workspace, cx| {
10370 let num_panes = workspace.panes().len();
10371 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
10372 let active_item = workspace
10373 .active_pane()
10374 .read(cx)
10375 .active_item()
10376 .expect("item is in focus");
10377
10378 assert_eq!(num_panes, 1);
10379 assert_eq!(num_items_in_current_pane, 3);
10380 assert_eq!(active_item.item_id(), last_item.item_id());
10381 });
10382 }
10383 struct TestModal(FocusHandle);
10384
10385 impl TestModal {
10386 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
10387 Self(cx.focus_handle())
10388 }
10389 }
10390
10391 impl EventEmitter<DismissEvent> for TestModal {}
10392
10393 impl Focusable for TestModal {
10394 fn focus_handle(&self, _cx: &App) -> FocusHandle {
10395 self.0.clone()
10396 }
10397 }
10398
10399 impl ModalView for TestModal {}
10400
10401 impl Render for TestModal {
10402 fn render(
10403 &mut self,
10404 _window: &mut Window,
10405 _cx: &mut Context<TestModal>,
10406 ) -> impl IntoElement {
10407 div().track_focus(&self.0)
10408 }
10409 }
10410
10411 #[gpui::test]
10412 async fn test_panels(cx: &mut gpui::TestAppContext) {
10413 init_test(cx);
10414 let fs = FakeFs::new(cx.executor());
10415
10416 let project = Project::test(fs, [], cx).await;
10417 let (workspace, cx) =
10418 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10419
10420 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
10421 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
10422 workspace.add_panel(panel_1.clone(), window, cx);
10423 workspace.toggle_dock(DockPosition::Left, window, cx);
10424 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
10425 workspace.add_panel(panel_2.clone(), window, cx);
10426 workspace.toggle_dock(DockPosition::Right, window, cx);
10427
10428 let left_dock = workspace.left_dock();
10429 assert_eq!(
10430 left_dock.read(cx).visible_panel().unwrap().panel_id(),
10431 panel_1.panel_id()
10432 );
10433 assert_eq!(
10434 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
10435 panel_1.size(window, cx)
10436 );
10437
10438 left_dock.update(cx, |left_dock, cx| {
10439 left_dock.resize_active_panel(Some(px(1337.)), window, cx)
10440 });
10441 assert_eq!(
10442 workspace
10443 .right_dock()
10444 .read(cx)
10445 .visible_panel()
10446 .unwrap()
10447 .panel_id(),
10448 panel_2.panel_id(),
10449 );
10450
10451 (panel_1, panel_2)
10452 });
10453
10454 // Move panel_1 to the right
10455 panel_1.update_in(cx, |panel_1, window, cx| {
10456 panel_1.set_position(DockPosition::Right, window, cx)
10457 });
10458
10459 workspace.update_in(cx, |workspace, window, cx| {
10460 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
10461 // Since it was the only panel on the left, the left dock should now be closed.
10462 assert!(!workspace.left_dock().read(cx).is_open());
10463 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
10464 let right_dock = workspace.right_dock();
10465 assert_eq!(
10466 right_dock.read(cx).visible_panel().unwrap().panel_id(),
10467 panel_1.panel_id()
10468 );
10469 assert_eq!(
10470 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
10471 px(1337.)
10472 );
10473
10474 // Now we move panel_2 to the left
10475 panel_2.set_position(DockPosition::Left, window, cx);
10476 });
10477
10478 workspace.update(cx, |workspace, cx| {
10479 // Since panel_2 was not visible on the right, we don't open the left dock.
10480 assert!(!workspace.left_dock().read(cx).is_open());
10481 // And the right dock is unaffected in its displaying of panel_1
10482 assert!(workspace.right_dock().read(cx).is_open());
10483 assert_eq!(
10484 workspace
10485 .right_dock()
10486 .read(cx)
10487 .visible_panel()
10488 .unwrap()
10489 .panel_id(),
10490 panel_1.panel_id(),
10491 );
10492 });
10493
10494 // Move panel_1 back to the left
10495 panel_1.update_in(cx, |panel_1, window, cx| {
10496 panel_1.set_position(DockPosition::Left, window, cx)
10497 });
10498
10499 workspace.update_in(cx, |workspace, window, cx| {
10500 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
10501 let left_dock = workspace.left_dock();
10502 assert!(left_dock.read(cx).is_open());
10503 assert_eq!(
10504 left_dock.read(cx).visible_panel().unwrap().panel_id(),
10505 panel_1.panel_id()
10506 );
10507 assert_eq!(
10508 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
10509 px(1337.)
10510 );
10511 // And the right dock should be closed as it no longer has any panels.
10512 assert!(!workspace.right_dock().read(cx).is_open());
10513
10514 // Now we move panel_1 to the bottom
10515 panel_1.set_position(DockPosition::Bottom, window, cx);
10516 });
10517
10518 workspace.update_in(cx, |workspace, window, cx| {
10519 // Since panel_1 was visible on the left, we close the left dock.
10520 assert!(!workspace.left_dock().read(cx).is_open());
10521 // The bottom dock is sized based on the panel's default size,
10522 // since the panel orientation changed from vertical to horizontal.
10523 let bottom_dock = workspace.bottom_dock();
10524 assert_eq!(
10525 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
10526 panel_1.size(window, cx),
10527 );
10528 // Close bottom dock and move panel_1 back to the left.
10529 bottom_dock.update(cx, |bottom_dock, cx| {
10530 bottom_dock.set_open(false, window, cx)
10531 });
10532 panel_1.set_position(DockPosition::Left, window, cx);
10533 });
10534
10535 // Emit activated event on panel 1
10536 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
10537
10538 // Now the left dock is open and panel_1 is active and focused.
10539 workspace.update_in(cx, |workspace, window, cx| {
10540 let left_dock = workspace.left_dock();
10541 assert!(left_dock.read(cx).is_open());
10542 assert_eq!(
10543 left_dock.read(cx).visible_panel().unwrap().panel_id(),
10544 panel_1.panel_id(),
10545 );
10546 assert!(panel_1.focus_handle(cx).is_focused(window));
10547 });
10548
10549 // Emit closed event on panel 2, which is not active
10550 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
10551
10552 // Wo don't close the left dock, because panel_2 wasn't the active panel
10553 workspace.update(cx, |workspace, cx| {
10554 let left_dock = workspace.left_dock();
10555 assert!(left_dock.read(cx).is_open());
10556 assert_eq!(
10557 left_dock.read(cx).visible_panel().unwrap().panel_id(),
10558 panel_1.panel_id(),
10559 );
10560 });
10561
10562 // Emitting a ZoomIn event shows the panel as zoomed.
10563 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
10564 workspace.read_with(cx, |workspace, _| {
10565 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10566 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
10567 });
10568
10569 // Move panel to another dock while it is zoomed
10570 panel_1.update_in(cx, |panel, window, cx| {
10571 panel.set_position(DockPosition::Right, window, cx)
10572 });
10573 workspace.read_with(cx, |workspace, _| {
10574 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10575
10576 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10577 });
10578
10579 // This is a helper for getting a:
10580 // - valid focus on an element,
10581 // - that isn't a part of the panes and panels system of the Workspace,
10582 // - and doesn't trigger the 'on_focus_lost' API.
10583 let focus_other_view = {
10584 let workspace = workspace.clone();
10585 move |cx: &mut VisualTestContext| {
10586 workspace.update_in(cx, |workspace, window, cx| {
10587 if workspace.active_modal::<TestModal>(cx).is_some() {
10588 workspace.toggle_modal(window, cx, TestModal::new);
10589 workspace.toggle_modal(window, cx, TestModal::new);
10590 } else {
10591 workspace.toggle_modal(window, cx, TestModal::new);
10592 }
10593 })
10594 }
10595 };
10596
10597 // If focus is transferred to another view that's not a panel or another pane, we still show
10598 // the panel as zoomed.
10599 focus_other_view(cx);
10600 workspace.read_with(cx, |workspace, _| {
10601 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10602 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10603 });
10604
10605 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
10606 workspace.update_in(cx, |_workspace, window, cx| {
10607 cx.focus_self(window);
10608 });
10609 workspace.read_with(cx, |workspace, _| {
10610 assert_eq!(workspace.zoomed, None);
10611 assert_eq!(workspace.zoomed_position, None);
10612 });
10613
10614 // If focus is transferred again to another view that's not a panel or a pane, we won't
10615 // show the panel as zoomed because it wasn't zoomed before.
10616 focus_other_view(cx);
10617 workspace.read_with(cx, |workspace, _| {
10618 assert_eq!(workspace.zoomed, None);
10619 assert_eq!(workspace.zoomed_position, None);
10620 });
10621
10622 // When the panel is activated, it is zoomed again.
10623 cx.dispatch_action(ToggleRightDock);
10624 workspace.read_with(cx, |workspace, _| {
10625 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10626 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10627 });
10628
10629 // Emitting a ZoomOut event unzooms the panel.
10630 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
10631 workspace.read_with(cx, |workspace, _| {
10632 assert_eq!(workspace.zoomed, None);
10633 assert_eq!(workspace.zoomed_position, None);
10634 });
10635
10636 // Emit closed event on panel 1, which is active
10637 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
10638
10639 // Now the left dock is closed, because panel_1 was the active panel
10640 workspace.update(cx, |workspace, cx| {
10641 let right_dock = workspace.right_dock();
10642 assert!(!right_dock.read(cx).is_open());
10643 });
10644 }
10645
10646 #[gpui::test]
10647 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
10648 init_test(cx);
10649
10650 let fs = FakeFs::new(cx.background_executor.clone());
10651 let project = Project::test(fs, [], cx).await;
10652 let (workspace, cx) =
10653 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10654 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10655
10656 let dirty_regular_buffer = cx.new(|cx| {
10657 TestItem::new(cx)
10658 .with_dirty(true)
10659 .with_label("1.txt")
10660 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10661 });
10662 let dirty_regular_buffer_2 = cx.new(|cx| {
10663 TestItem::new(cx)
10664 .with_dirty(true)
10665 .with_label("2.txt")
10666 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10667 });
10668 let dirty_multi_buffer_with_both = cx.new(|cx| {
10669 TestItem::new(cx)
10670 .with_dirty(true)
10671 .with_buffer_kind(ItemBufferKind::Multibuffer)
10672 .with_label("Fake Project Search")
10673 .with_project_items(&[
10674 dirty_regular_buffer.read(cx).project_items[0].clone(),
10675 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10676 ])
10677 });
10678 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
10679 workspace.update_in(cx, |workspace, window, cx| {
10680 workspace.add_item(
10681 pane.clone(),
10682 Box::new(dirty_regular_buffer.clone()),
10683 None,
10684 false,
10685 false,
10686 window,
10687 cx,
10688 );
10689 workspace.add_item(
10690 pane.clone(),
10691 Box::new(dirty_regular_buffer_2.clone()),
10692 None,
10693 false,
10694 false,
10695 window,
10696 cx,
10697 );
10698 workspace.add_item(
10699 pane.clone(),
10700 Box::new(dirty_multi_buffer_with_both.clone()),
10701 None,
10702 false,
10703 false,
10704 window,
10705 cx,
10706 );
10707 });
10708
10709 pane.update_in(cx, |pane, window, cx| {
10710 pane.activate_item(2, true, true, window, cx);
10711 assert_eq!(
10712 pane.active_item().unwrap().item_id(),
10713 multi_buffer_with_both_files_id,
10714 "Should select the multi buffer in the pane"
10715 );
10716 });
10717 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10718 pane.close_other_items(
10719 &CloseOtherItems {
10720 save_intent: Some(SaveIntent::Save),
10721 close_pinned: true,
10722 },
10723 None,
10724 window,
10725 cx,
10726 )
10727 });
10728 cx.background_executor.run_until_parked();
10729 assert!(!cx.has_pending_prompt());
10730 close_all_but_multi_buffer_task
10731 .await
10732 .expect("Closing all buffers but the multi buffer failed");
10733 pane.update(cx, |pane, cx| {
10734 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
10735 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
10736 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
10737 assert_eq!(pane.items_len(), 1);
10738 assert_eq!(
10739 pane.active_item().unwrap().item_id(),
10740 multi_buffer_with_both_files_id,
10741 "Should have only the multi buffer left in the pane"
10742 );
10743 assert!(
10744 dirty_multi_buffer_with_both.read(cx).is_dirty,
10745 "The multi buffer containing the unsaved buffer should still be dirty"
10746 );
10747 });
10748
10749 dirty_regular_buffer.update(cx, |buffer, cx| {
10750 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
10751 });
10752
10753 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10754 pane.close_active_item(
10755 &CloseActiveItem {
10756 save_intent: Some(SaveIntent::Close),
10757 close_pinned: false,
10758 },
10759 window,
10760 cx,
10761 )
10762 });
10763 cx.background_executor.run_until_parked();
10764 assert!(
10765 cx.has_pending_prompt(),
10766 "Dirty multi buffer should prompt a save dialog"
10767 );
10768 cx.simulate_prompt_answer("Save");
10769 cx.background_executor.run_until_parked();
10770 close_multi_buffer_task
10771 .await
10772 .expect("Closing the multi buffer failed");
10773 pane.update(cx, |pane, cx| {
10774 assert_eq!(
10775 dirty_multi_buffer_with_both.read(cx).save_count,
10776 1,
10777 "Multi buffer item should get be saved"
10778 );
10779 // Test impl does not save inner items, so we do not assert them
10780 assert_eq!(
10781 pane.items_len(),
10782 0,
10783 "No more items should be left in the pane"
10784 );
10785 assert!(pane.active_item().is_none());
10786 });
10787 }
10788
10789 #[gpui::test]
10790 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
10791 cx: &mut TestAppContext,
10792 ) {
10793 init_test(cx);
10794
10795 let fs = FakeFs::new(cx.background_executor.clone());
10796 let project = Project::test(fs, [], cx).await;
10797 let (workspace, cx) =
10798 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10799 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10800
10801 let dirty_regular_buffer = cx.new(|cx| {
10802 TestItem::new(cx)
10803 .with_dirty(true)
10804 .with_label("1.txt")
10805 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10806 });
10807 let dirty_regular_buffer_2 = cx.new(|cx| {
10808 TestItem::new(cx)
10809 .with_dirty(true)
10810 .with_label("2.txt")
10811 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10812 });
10813 let clear_regular_buffer = cx.new(|cx| {
10814 TestItem::new(cx)
10815 .with_label("3.txt")
10816 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
10817 });
10818
10819 let dirty_multi_buffer_with_both = cx.new(|cx| {
10820 TestItem::new(cx)
10821 .with_dirty(true)
10822 .with_buffer_kind(ItemBufferKind::Multibuffer)
10823 .with_label("Fake Project Search")
10824 .with_project_items(&[
10825 dirty_regular_buffer.read(cx).project_items[0].clone(),
10826 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10827 clear_regular_buffer.read(cx).project_items[0].clone(),
10828 ])
10829 });
10830 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
10831 workspace.update_in(cx, |workspace, window, cx| {
10832 workspace.add_item(
10833 pane.clone(),
10834 Box::new(dirty_regular_buffer.clone()),
10835 None,
10836 false,
10837 false,
10838 window,
10839 cx,
10840 );
10841 workspace.add_item(
10842 pane.clone(),
10843 Box::new(dirty_multi_buffer_with_both.clone()),
10844 None,
10845 false,
10846 false,
10847 window,
10848 cx,
10849 );
10850 });
10851
10852 pane.update_in(cx, |pane, window, cx| {
10853 pane.activate_item(1, true, true, window, cx);
10854 assert_eq!(
10855 pane.active_item().unwrap().item_id(),
10856 multi_buffer_with_both_files_id,
10857 "Should select the multi buffer in the pane"
10858 );
10859 });
10860 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10861 pane.close_active_item(
10862 &CloseActiveItem {
10863 save_intent: None,
10864 close_pinned: false,
10865 },
10866 window,
10867 cx,
10868 )
10869 });
10870 cx.background_executor.run_until_parked();
10871 assert!(
10872 cx.has_pending_prompt(),
10873 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
10874 );
10875 }
10876
10877 /// Tests that when `close_on_file_delete` is enabled, files are automatically
10878 /// closed when they are deleted from disk.
10879 #[gpui::test]
10880 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
10881 init_test(cx);
10882
10883 // Enable the close_on_disk_deletion setting
10884 cx.update_global(|store: &mut SettingsStore, cx| {
10885 store.update_user_settings(cx, |settings| {
10886 settings.workspace.close_on_file_delete = Some(true);
10887 });
10888 });
10889
10890 let fs = FakeFs::new(cx.background_executor.clone());
10891 let project = Project::test(fs, [], cx).await;
10892 let (workspace, cx) =
10893 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10894 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10895
10896 // Create a test item that simulates a file
10897 let item = cx.new(|cx| {
10898 TestItem::new(cx)
10899 .with_label("test.txt")
10900 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10901 });
10902
10903 // Add item to workspace
10904 workspace.update_in(cx, |workspace, window, cx| {
10905 workspace.add_item(
10906 pane.clone(),
10907 Box::new(item.clone()),
10908 None,
10909 false,
10910 false,
10911 window,
10912 cx,
10913 );
10914 });
10915
10916 // Verify the item is in the pane
10917 pane.read_with(cx, |pane, _| {
10918 assert_eq!(pane.items().count(), 1);
10919 });
10920
10921 // Simulate file deletion by setting the item's deleted state
10922 item.update(cx, |item, _| {
10923 item.set_has_deleted_file(true);
10924 });
10925
10926 // Emit UpdateTab event to trigger the close behavior
10927 cx.run_until_parked();
10928 item.update(cx, |_, cx| {
10929 cx.emit(ItemEvent::UpdateTab);
10930 });
10931
10932 // Allow the close operation to complete
10933 cx.run_until_parked();
10934
10935 // Verify the item was automatically closed
10936 pane.read_with(cx, |pane, _| {
10937 assert_eq!(
10938 pane.items().count(),
10939 0,
10940 "Item should be automatically closed when file is deleted"
10941 );
10942 });
10943 }
10944
10945 /// Tests that when `close_on_file_delete` is disabled (default), files remain
10946 /// open with a strikethrough when they are deleted from disk.
10947 #[gpui::test]
10948 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
10949 init_test(cx);
10950
10951 // Ensure close_on_disk_deletion is disabled (default)
10952 cx.update_global(|store: &mut SettingsStore, cx| {
10953 store.update_user_settings(cx, |settings| {
10954 settings.workspace.close_on_file_delete = Some(false);
10955 });
10956 });
10957
10958 let fs = FakeFs::new(cx.background_executor.clone());
10959 let project = Project::test(fs, [], cx).await;
10960 let (workspace, cx) =
10961 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10962 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10963
10964 // Create a test item that simulates a file
10965 let item = cx.new(|cx| {
10966 TestItem::new(cx)
10967 .with_label("test.txt")
10968 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10969 });
10970
10971 // Add item to workspace
10972 workspace.update_in(cx, |workspace, window, cx| {
10973 workspace.add_item(
10974 pane.clone(),
10975 Box::new(item.clone()),
10976 None,
10977 false,
10978 false,
10979 window,
10980 cx,
10981 );
10982 });
10983
10984 // Verify the item is in the pane
10985 pane.read_with(cx, |pane, _| {
10986 assert_eq!(pane.items().count(), 1);
10987 });
10988
10989 // Simulate file deletion
10990 item.update(cx, |item, _| {
10991 item.set_has_deleted_file(true);
10992 });
10993
10994 // Emit UpdateTab event
10995 cx.run_until_parked();
10996 item.update(cx, |_, cx| {
10997 cx.emit(ItemEvent::UpdateTab);
10998 });
10999
11000 // Allow any potential close operation to complete
11001 cx.run_until_parked();
11002
11003 // Verify the item remains open (with strikethrough)
11004 pane.read_with(cx, |pane, _| {
11005 assert_eq!(
11006 pane.items().count(),
11007 1,
11008 "Item should remain open when close_on_disk_deletion is disabled"
11009 );
11010 });
11011
11012 // Verify the item shows as deleted
11013 item.read_with(cx, |item, _| {
11014 assert!(
11015 item.has_deleted_file,
11016 "Item should be marked as having deleted file"
11017 );
11018 });
11019 }
11020
11021 /// Tests that dirty files are not automatically closed when deleted from disk,
11022 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
11023 /// unsaved changes without being prompted.
11024 #[gpui::test]
11025 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
11026 init_test(cx);
11027
11028 // Enable the close_on_file_delete setting
11029 cx.update_global(|store: &mut SettingsStore, cx| {
11030 store.update_user_settings(cx, |settings| {
11031 settings.workspace.close_on_file_delete = Some(true);
11032 });
11033 });
11034
11035 let fs = FakeFs::new(cx.background_executor.clone());
11036 let project = Project::test(fs, [], cx).await;
11037 let (workspace, cx) =
11038 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11039 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11040
11041 // Create a dirty test item
11042 let item = cx.new(|cx| {
11043 TestItem::new(cx)
11044 .with_dirty(true)
11045 .with_label("test.txt")
11046 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11047 });
11048
11049 // Add item to workspace
11050 workspace.update_in(cx, |workspace, window, cx| {
11051 workspace.add_item(
11052 pane.clone(),
11053 Box::new(item.clone()),
11054 None,
11055 false,
11056 false,
11057 window,
11058 cx,
11059 );
11060 });
11061
11062 // Simulate file deletion
11063 item.update(cx, |item, _| {
11064 item.set_has_deleted_file(true);
11065 });
11066
11067 // Emit UpdateTab event to trigger the close behavior
11068 cx.run_until_parked();
11069 item.update(cx, |_, cx| {
11070 cx.emit(ItemEvent::UpdateTab);
11071 });
11072
11073 // Allow any potential close operation to complete
11074 cx.run_until_parked();
11075
11076 // Verify the item remains open (dirty files are not auto-closed)
11077 pane.read_with(cx, |pane, _| {
11078 assert_eq!(
11079 pane.items().count(),
11080 1,
11081 "Dirty items should not be automatically closed even when file is deleted"
11082 );
11083 });
11084
11085 // Verify the item is marked as deleted and still dirty
11086 item.read_with(cx, |item, _| {
11087 assert!(
11088 item.has_deleted_file,
11089 "Item should be marked as having deleted file"
11090 );
11091 assert!(item.is_dirty, "Item should still be dirty");
11092 });
11093 }
11094
11095 /// Tests that navigation history is cleaned up when files are auto-closed
11096 /// due to deletion from disk.
11097 #[gpui::test]
11098 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
11099 init_test(cx);
11100
11101 // Enable the close_on_file_delete setting
11102 cx.update_global(|store: &mut SettingsStore, cx| {
11103 store.update_user_settings(cx, |settings| {
11104 settings.workspace.close_on_file_delete = Some(true);
11105 });
11106 });
11107
11108 let fs = FakeFs::new(cx.background_executor.clone());
11109 let project = Project::test(fs, [], cx).await;
11110 let (workspace, cx) =
11111 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11112 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11113
11114 // Create test items
11115 let item1 = cx.new(|cx| {
11116 TestItem::new(cx)
11117 .with_label("test1.txt")
11118 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
11119 });
11120 let item1_id = item1.item_id();
11121
11122 let item2 = cx.new(|cx| {
11123 TestItem::new(cx)
11124 .with_label("test2.txt")
11125 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
11126 });
11127
11128 // Add items to workspace
11129 workspace.update_in(cx, |workspace, window, cx| {
11130 workspace.add_item(
11131 pane.clone(),
11132 Box::new(item1.clone()),
11133 None,
11134 false,
11135 false,
11136 window,
11137 cx,
11138 );
11139 workspace.add_item(
11140 pane.clone(),
11141 Box::new(item2.clone()),
11142 None,
11143 false,
11144 false,
11145 window,
11146 cx,
11147 );
11148 });
11149
11150 // Activate item1 to ensure it gets navigation entries
11151 pane.update_in(cx, |pane, window, cx| {
11152 pane.activate_item(0, true, true, window, cx);
11153 });
11154
11155 // Switch to item2 and back to create navigation history
11156 pane.update_in(cx, |pane, window, cx| {
11157 pane.activate_item(1, true, true, window, cx);
11158 });
11159 cx.run_until_parked();
11160
11161 pane.update_in(cx, |pane, window, cx| {
11162 pane.activate_item(0, true, true, window, cx);
11163 });
11164 cx.run_until_parked();
11165
11166 // Simulate file deletion for item1
11167 item1.update(cx, |item, _| {
11168 item.set_has_deleted_file(true);
11169 });
11170
11171 // Emit UpdateTab event to trigger the close behavior
11172 item1.update(cx, |_, cx| {
11173 cx.emit(ItemEvent::UpdateTab);
11174 });
11175 cx.run_until_parked();
11176
11177 // Verify item1 was closed
11178 pane.read_with(cx, |pane, _| {
11179 assert_eq!(
11180 pane.items().count(),
11181 1,
11182 "Should have 1 item remaining after auto-close"
11183 );
11184 });
11185
11186 // Check navigation history after close
11187 let has_item = pane.read_with(cx, |pane, cx| {
11188 let mut has_item = false;
11189 pane.nav_history().for_each_entry(cx, |entry, _| {
11190 if entry.item.id() == item1_id {
11191 has_item = true;
11192 }
11193 });
11194 has_item
11195 });
11196
11197 assert!(
11198 !has_item,
11199 "Navigation history should not contain closed item entries"
11200 );
11201 }
11202
11203 #[gpui::test]
11204 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
11205 cx: &mut TestAppContext,
11206 ) {
11207 init_test(cx);
11208
11209 let fs = FakeFs::new(cx.background_executor.clone());
11210 let project = Project::test(fs, [], cx).await;
11211 let (workspace, cx) =
11212 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11213 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11214
11215 let dirty_regular_buffer = cx.new(|cx| {
11216 TestItem::new(cx)
11217 .with_dirty(true)
11218 .with_label("1.txt")
11219 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11220 });
11221 let dirty_regular_buffer_2 = cx.new(|cx| {
11222 TestItem::new(cx)
11223 .with_dirty(true)
11224 .with_label("2.txt")
11225 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11226 });
11227 let clear_regular_buffer = cx.new(|cx| {
11228 TestItem::new(cx)
11229 .with_label("3.txt")
11230 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
11231 });
11232
11233 let dirty_multi_buffer = cx.new(|cx| {
11234 TestItem::new(cx)
11235 .with_dirty(true)
11236 .with_buffer_kind(ItemBufferKind::Multibuffer)
11237 .with_label("Fake Project Search")
11238 .with_project_items(&[
11239 dirty_regular_buffer.read(cx).project_items[0].clone(),
11240 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11241 clear_regular_buffer.read(cx).project_items[0].clone(),
11242 ])
11243 });
11244 workspace.update_in(cx, |workspace, window, cx| {
11245 workspace.add_item(
11246 pane.clone(),
11247 Box::new(dirty_regular_buffer.clone()),
11248 None,
11249 false,
11250 false,
11251 window,
11252 cx,
11253 );
11254 workspace.add_item(
11255 pane.clone(),
11256 Box::new(dirty_regular_buffer_2.clone()),
11257 None,
11258 false,
11259 false,
11260 window,
11261 cx,
11262 );
11263 workspace.add_item(
11264 pane.clone(),
11265 Box::new(dirty_multi_buffer.clone()),
11266 None,
11267 false,
11268 false,
11269 window,
11270 cx,
11271 );
11272 });
11273
11274 pane.update_in(cx, |pane, window, cx| {
11275 pane.activate_item(2, true, true, window, cx);
11276 assert_eq!(
11277 pane.active_item().unwrap().item_id(),
11278 dirty_multi_buffer.item_id(),
11279 "Should select the multi buffer in the pane"
11280 );
11281 });
11282 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11283 pane.close_active_item(
11284 &CloseActiveItem {
11285 save_intent: None,
11286 close_pinned: false,
11287 },
11288 window,
11289 cx,
11290 )
11291 });
11292 cx.background_executor.run_until_parked();
11293 assert!(
11294 !cx.has_pending_prompt(),
11295 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
11296 );
11297 close_multi_buffer_task
11298 .await
11299 .expect("Closing multi buffer failed");
11300 pane.update(cx, |pane, cx| {
11301 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
11302 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
11303 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
11304 assert_eq!(
11305 pane.items()
11306 .map(|item| item.item_id())
11307 .sorted()
11308 .collect::<Vec<_>>(),
11309 vec![
11310 dirty_regular_buffer.item_id(),
11311 dirty_regular_buffer_2.item_id(),
11312 ],
11313 "Should have no multi buffer left in the pane"
11314 );
11315 assert!(dirty_regular_buffer.read(cx).is_dirty);
11316 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
11317 });
11318 }
11319
11320 #[gpui::test]
11321 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
11322 init_test(cx);
11323 let fs = FakeFs::new(cx.executor());
11324 let project = Project::test(fs, [], cx).await;
11325 let (workspace, cx) =
11326 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11327
11328 // Add a new panel to the right dock, opening the dock and setting the
11329 // focus to the new panel.
11330 let panel = workspace.update_in(cx, |workspace, window, cx| {
11331 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11332 workspace.add_panel(panel.clone(), window, cx);
11333
11334 workspace
11335 .right_dock()
11336 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11337
11338 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11339
11340 panel
11341 });
11342
11343 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
11344 // panel to the next valid position which, in this case, is the left
11345 // dock.
11346 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11347 workspace.update(cx, |workspace, cx| {
11348 assert!(workspace.left_dock().read(cx).is_open());
11349 assert_eq!(panel.read(cx).position, DockPosition::Left);
11350 });
11351
11352 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
11353 // panel to the next valid position which, in this case, is the bottom
11354 // dock.
11355 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11356 workspace.update(cx, |workspace, cx| {
11357 assert!(workspace.bottom_dock().read(cx).is_open());
11358 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
11359 });
11360
11361 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
11362 // around moving the panel to its initial position, the right dock.
11363 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11364 workspace.update(cx, |workspace, cx| {
11365 assert!(workspace.right_dock().read(cx).is_open());
11366 assert_eq!(panel.read(cx).position, DockPosition::Right);
11367 });
11368
11369 // Remove focus from the panel, ensuring that, if the panel is not
11370 // focused, the `MoveFocusedPanelToNextPosition` action does not update
11371 // the panel's position, so the panel is still in the right dock.
11372 workspace.update_in(cx, |workspace, window, cx| {
11373 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11374 });
11375
11376 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11377 workspace.update(cx, |workspace, cx| {
11378 assert!(workspace.right_dock().read(cx).is_open());
11379 assert_eq!(panel.read(cx).position, DockPosition::Right);
11380 });
11381 }
11382
11383 #[gpui::test]
11384 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
11385 init_test(cx);
11386
11387 let fs = FakeFs::new(cx.executor());
11388 let project = Project::test(fs, [], cx).await;
11389 let (workspace, cx) =
11390 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11391
11392 let item_1 = cx.new(|cx| {
11393 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
11394 });
11395 workspace.update_in(cx, |workspace, window, cx| {
11396 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
11397 workspace.move_item_to_pane_in_direction(
11398 &MoveItemToPaneInDirection {
11399 direction: SplitDirection::Right,
11400 focus: true,
11401 clone: false,
11402 },
11403 window,
11404 cx,
11405 );
11406 workspace.move_item_to_pane_at_index(
11407 &MoveItemToPane {
11408 destination: 3,
11409 focus: true,
11410 clone: false,
11411 },
11412 window,
11413 cx,
11414 );
11415
11416 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
11417 assert_eq!(
11418 pane_items_paths(&workspace.active_pane, cx),
11419 vec!["first.txt".to_string()],
11420 "Single item was not moved anywhere"
11421 );
11422 });
11423
11424 let item_2 = cx.new(|cx| {
11425 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
11426 });
11427 workspace.update_in(cx, |workspace, window, cx| {
11428 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
11429 assert_eq!(
11430 pane_items_paths(&workspace.panes[0], cx),
11431 vec!["first.txt".to_string(), "second.txt".to_string()],
11432 );
11433 workspace.move_item_to_pane_in_direction(
11434 &MoveItemToPaneInDirection {
11435 direction: SplitDirection::Right,
11436 focus: true,
11437 clone: false,
11438 },
11439 window,
11440 cx,
11441 );
11442
11443 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
11444 assert_eq!(
11445 pane_items_paths(&workspace.panes[0], cx),
11446 vec!["first.txt".to_string()],
11447 "After moving, one item should be left in the original pane"
11448 );
11449 assert_eq!(
11450 pane_items_paths(&workspace.panes[1], cx),
11451 vec!["second.txt".to_string()],
11452 "New item should have been moved to the new pane"
11453 );
11454 });
11455
11456 let item_3 = cx.new(|cx| {
11457 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
11458 });
11459 workspace.update_in(cx, |workspace, window, cx| {
11460 let original_pane = workspace.panes[0].clone();
11461 workspace.set_active_pane(&original_pane, window, cx);
11462 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
11463 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
11464 assert_eq!(
11465 pane_items_paths(&workspace.active_pane, cx),
11466 vec!["first.txt".to_string(), "third.txt".to_string()],
11467 "New pane should be ready to move one item out"
11468 );
11469
11470 workspace.move_item_to_pane_at_index(
11471 &MoveItemToPane {
11472 destination: 3,
11473 focus: true,
11474 clone: false,
11475 },
11476 window,
11477 cx,
11478 );
11479 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
11480 assert_eq!(
11481 pane_items_paths(&workspace.active_pane, cx),
11482 vec!["first.txt".to_string()],
11483 "After moving, one item should be left in the original pane"
11484 );
11485 assert_eq!(
11486 pane_items_paths(&workspace.panes[1], cx),
11487 vec!["second.txt".to_string()],
11488 "Previously created pane should be unchanged"
11489 );
11490 assert_eq!(
11491 pane_items_paths(&workspace.panes[2], cx),
11492 vec!["third.txt".to_string()],
11493 "New item should have been moved to the new pane"
11494 );
11495 });
11496 }
11497
11498 #[gpui::test]
11499 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
11500 init_test(cx);
11501
11502 let fs = FakeFs::new(cx.executor());
11503 let project = Project::test(fs, [], cx).await;
11504 let (workspace, cx) =
11505 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11506
11507 let item_1 = cx.new(|cx| {
11508 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
11509 });
11510 workspace.update_in(cx, |workspace, window, cx| {
11511 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
11512 workspace.move_item_to_pane_in_direction(
11513 &MoveItemToPaneInDirection {
11514 direction: SplitDirection::Right,
11515 focus: true,
11516 clone: true,
11517 },
11518 window,
11519 cx,
11520 );
11521 workspace.move_item_to_pane_at_index(
11522 &MoveItemToPane {
11523 destination: 3,
11524 focus: true,
11525 clone: true,
11526 },
11527 window,
11528 cx,
11529 );
11530 });
11531 cx.run_until_parked();
11532
11533 workspace.update(cx, |workspace, cx| {
11534 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
11535 for pane in workspace.panes() {
11536 assert_eq!(
11537 pane_items_paths(pane, cx),
11538 vec!["first.txt".to_string()],
11539 "Single item exists in all panes"
11540 );
11541 }
11542 });
11543
11544 // verify that the active pane has been updated after waiting for the
11545 // pane focus event to fire and resolve
11546 workspace.read_with(cx, |workspace, _app| {
11547 assert_eq!(
11548 workspace.active_pane(),
11549 &workspace.panes[2],
11550 "The third pane should be the active one: {:?}",
11551 workspace.panes
11552 );
11553 })
11554 }
11555
11556 mod register_project_item_tests {
11557
11558 use super::*;
11559
11560 // View
11561 struct TestPngItemView {
11562 focus_handle: FocusHandle,
11563 }
11564 // Model
11565 struct TestPngItem {}
11566
11567 impl project::ProjectItem for TestPngItem {
11568 fn try_open(
11569 _project: &Entity<Project>,
11570 path: &ProjectPath,
11571 cx: &mut App,
11572 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
11573 if path.path.extension().unwrap() == "png" {
11574 Some(cx.spawn(async move |cx| cx.new(|_| TestPngItem {})))
11575 } else {
11576 None
11577 }
11578 }
11579
11580 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
11581 None
11582 }
11583
11584 fn project_path(&self, _: &App) -> Option<ProjectPath> {
11585 None
11586 }
11587
11588 fn is_dirty(&self) -> bool {
11589 false
11590 }
11591 }
11592
11593 impl Item for TestPngItemView {
11594 type Event = ();
11595 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11596 "".into()
11597 }
11598 }
11599 impl EventEmitter<()> for TestPngItemView {}
11600 impl Focusable for TestPngItemView {
11601 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11602 self.focus_handle.clone()
11603 }
11604 }
11605
11606 impl Render for TestPngItemView {
11607 fn render(
11608 &mut self,
11609 _window: &mut Window,
11610 _cx: &mut Context<Self>,
11611 ) -> impl IntoElement {
11612 Empty
11613 }
11614 }
11615
11616 impl ProjectItem for TestPngItemView {
11617 type Item = TestPngItem;
11618
11619 fn for_project_item(
11620 _project: Entity<Project>,
11621 _pane: Option<&Pane>,
11622 _item: Entity<Self::Item>,
11623 _: &mut Window,
11624 cx: &mut Context<Self>,
11625 ) -> Self
11626 where
11627 Self: Sized,
11628 {
11629 Self {
11630 focus_handle: cx.focus_handle(),
11631 }
11632 }
11633 }
11634
11635 // View
11636 struct TestIpynbItemView {
11637 focus_handle: FocusHandle,
11638 }
11639 // Model
11640 struct TestIpynbItem {}
11641
11642 impl project::ProjectItem for TestIpynbItem {
11643 fn try_open(
11644 _project: &Entity<Project>,
11645 path: &ProjectPath,
11646 cx: &mut App,
11647 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
11648 if path.path.extension().unwrap() == "ipynb" {
11649 Some(cx.spawn(async move |cx| cx.new(|_| TestIpynbItem {})))
11650 } else {
11651 None
11652 }
11653 }
11654
11655 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
11656 None
11657 }
11658
11659 fn project_path(&self, _: &App) -> Option<ProjectPath> {
11660 None
11661 }
11662
11663 fn is_dirty(&self) -> bool {
11664 false
11665 }
11666 }
11667
11668 impl Item for TestIpynbItemView {
11669 type Event = ();
11670 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11671 "".into()
11672 }
11673 }
11674 impl EventEmitter<()> for TestIpynbItemView {}
11675 impl Focusable for TestIpynbItemView {
11676 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11677 self.focus_handle.clone()
11678 }
11679 }
11680
11681 impl Render for TestIpynbItemView {
11682 fn render(
11683 &mut self,
11684 _window: &mut Window,
11685 _cx: &mut Context<Self>,
11686 ) -> impl IntoElement {
11687 Empty
11688 }
11689 }
11690
11691 impl ProjectItem for TestIpynbItemView {
11692 type Item = TestIpynbItem;
11693
11694 fn for_project_item(
11695 _project: Entity<Project>,
11696 _pane: Option<&Pane>,
11697 _item: Entity<Self::Item>,
11698 _: &mut Window,
11699 cx: &mut Context<Self>,
11700 ) -> Self
11701 where
11702 Self: Sized,
11703 {
11704 Self {
11705 focus_handle: cx.focus_handle(),
11706 }
11707 }
11708 }
11709
11710 struct TestAlternatePngItemView {
11711 focus_handle: FocusHandle,
11712 }
11713
11714 impl Item for TestAlternatePngItemView {
11715 type Event = ();
11716 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11717 "".into()
11718 }
11719 }
11720
11721 impl EventEmitter<()> for TestAlternatePngItemView {}
11722 impl Focusable for TestAlternatePngItemView {
11723 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11724 self.focus_handle.clone()
11725 }
11726 }
11727
11728 impl Render for TestAlternatePngItemView {
11729 fn render(
11730 &mut self,
11731 _window: &mut Window,
11732 _cx: &mut Context<Self>,
11733 ) -> impl IntoElement {
11734 Empty
11735 }
11736 }
11737
11738 impl ProjectItem for TestAlternatePngItemView {
11739 type Item = TestPngItem;
11740
11741 fn for_project_item(
11742 _project: Entity<Project>,
11743 _pane: Option<&Pane>,
11744 _item: Entity<Self::Item>,
11745 _: &mut Window,
11746 cx: &mut Context<Self>,
11747 ) -> Self
11748 where
11749 Self: Sized,
11750 {
11751 Self {
11752 focus_handle: cx.focus_handle(),
11753 }
11754 }
11755 }
11756
11757 #[gpui::test]
11758 async fn test_register_project_item(cx: &mut TestAppContext) {
11759 init_test(cx);
11760
11761 cx.update(|cx| {
11762 register_project_item::<TestPngItemView>(cx);
11763 register_project_item::<TestIpynbItemView>(cx);
11764 });
11765
11766 let fs = FakeFs::new(cx.executor());
11767 fs.insert_tree(
11768 "/root1",
11769 json!({
11770 "one.png": "BINARYDATAHERE",
11771 "two.ipynb": "{ totally a notebook }",
11772 "three.txt": "editing text, sure why not?"
11773 }),
11774 )
11775 .await;
11776
11777 let project = Project::test(fs, ["root1".as_ref()], cx).await;
11778 let (workspace, cx) =
11779 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11780
11781 let worktree_id = project.update(cx, |project, cx| {
11782 project.worktrees(cx).next().unwrap().read(cx).id()
11783 });
11784
11785 let handle = workspace
11786 .update_in(cx, |workspace, window, cx| {
11787 let project_path = (worktree_id, rel_path("one.png"));
11788 workspace.open_path(project_path, None, true, window, cx)
11789 })
11790 .await
11791 .unwrap();
11792
11793 // Now we can check if the handle we got back errored or not
11794 assert_eq!(
11795 handle.to_any_view().entity_type(),
11796 TypeId::of::<TestPngItemView>()
11797 );
11798
11799 let handle = workspace
11800 .update_in(cx, |workspace, window, cx| {
11801 let project_path = (worktree_id, rel_path("two.ipynb"));
11802 workspace.open_path(project_path, None, true, window, cx)
11803 })
11804 .await
11805 .unwrap();
11806
11807 assert_eq!(
11808 handle.to_any_view().entity_type(),
11809 TypeId::of::<TestIpynbItemView>()
11810 );
11811
11812 let handle = workspace
11813 .update_in(cx, |workspace, window, cx| {
11814 let project_path = (worktree_id, rel_path("three.txt"));
11815 workspace.open_path(project_path, None, true, window, cx)
11816 })
11817 .await;
11818 assert!(handle.is_err());
11819 }
11820
11821 #[gpui::test]
11822 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
11823 init_test(cx);
11824
11825 cx.update(|cx| {
11826 register_project_item::<TestPngItemView>(cx);
11827 register_project_item::<TestAlternatePngItemView>(cx);
11828 });
11829
11830 let fs = FakeFs::new(cx.executor());
11831 fs.insert_tree(
11832 "/root1",
11833 json!({
11834 "one.png": "BINARYDATAHERE",
11835 "two.ipynb": "{ totally a notebook }",
11836 "three.txt": "editing text, sure why not?"
11837 }),
11838 )
11839 .await;
11840 let project = Project::test(fs, ["root1".as_ref()], cx).await;
11841 let (workspace, cx) =
11842 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11843 let worktree_id = project.update(cx, |project, cx| {
11844 project.worktrees(cx).next().unwrap().read(cx).id()
11845 });
11846
11847 let handle = workspace
11848 .update_in(cx, |workspace, window, cx| {
11849 let project_path = (worktree_id, rel_path("one.png"));
11850 workspace.open_path(project_path, None, true, window, cx)
11851 })
11852 .await
11853 .unwrap();
11854
11855 // This _must_ be the second item registered
11856 assert_eq!(
11857 handle.to_any_view().entity_type(),
11858 TypeId::of::<TestAlternatePngItemView>()
11859 );
11860
11861 let handle = workspace
11862 .update_in(cx, |workspace, window, cx| {
11863 let project_path = (worktree_id, rel_path("three.txt"));
11864 workspace.open_path(project_path, None, true, window, cx)
11865 })
11866 .await;
11867 assert!(handle.is_err());
11868 }
11869 }
11870
11871 #[gpui::test]
11872 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
11873 init_test(cx);
11874
11875 let fs = FakeFs::new(cx.executor());
11876 let project = Project::test(fs, [], cx).await;
11877 let (workspace, _cx) =
11878 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11879
11880 // Test with status bar shown (default)
11881 workspace.read_with(cx, |workspace, cx| {
11882 let visible = workspace.status_bar_visible(cx);
11883 assert!(visible, "Status bar should be visible by default");
11884 });
11885
11886 // Test with status bar hidden
11887 cx.update_global(|store: &mut SettingsStore, cx| {
11888 store.update_user_settings(cx, |settings| {
11889 settings.status_bar.get_or_insert_default().show = Some(false);
11890 });
11891 });
11892
11893 workspace.read_with(cx, |workspace, cx| {
11894 let visible = workspace.status_bar_visible(cx);
11895 assert!(!visible, "Status bar should be hidden when show is false");
11896 });
11897
11898 // Test with status bar shown explicitly
11899 cx.update_global(|store: &mut SettingsStore, cx| {
11900 store.update_user_settings(cx, |settings| {
11901 settings.status_bar.get_or_insert_default().show = Some(true);
11902 });
11903 });
11904
11905 workspace.read_with(cx, |workspace, cx| {
11906 let visible = workspace.status_bar_visible(cx);
11907 assert!(visible, "Status bar should be visible when show is true");
11908 });
11909 }
11910
11911 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
11912 pane.read(cx)
11913 .items()
11914 .flat_map(|item| {
11915 item.project_paths(cx)
11916 .into_iter()
11917 .map(|path| path.path.display(PathStyle::local()).into_owned())
11918 })
11919 .collect()
11920 }
11921
11922 pub fn init_test(cx: &mut TestAppContext) {
11923 cx.update(|cx| {
11924 let settings_store = SettingsStore::test(cx);
11925 cx.set_global(settings_store);
11926 theme::init(theme::LoadThemes::JustBase, cx);
11927 });
11928 }
11929
11930 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
11931 let item = TestProjectItem::new(id, path, cx);
11932 item.update(cx, |item, _| {
11933 item.is_dirty = true;
11934 });
11935 item
11936 }
11937}