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