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