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