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