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