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