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