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