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