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