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