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