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