1pub mod dock;
2pub mod history_manager;
3pub mod invalid_item_view;
4pub mod item;
5mod modal_layer;
6mod multi_workspace;
7pub mod notifications;
8pub mod pane;
9pub mod pane_group;
10mod path_list;
11mod persistence;
12pub mod searchable;
13mod security_modal;
14pub mod shared_screen;
15pub use shared_screen::SharedScreen;
16mod status_bar;
17pub mod tasks;
18mod theme_preview;
19mod toast_layer;
20mod toolbar;
21pub mod welcome;
22mod workspace_settings;
23
24pub use crate::notifications::NotificationFrame;
25pub use dock::Panel;
26pub use multi_workspace::{
27 DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace, NewWorkspaceInWindow,
28 NextWorkspaceInWindow, PreviousWorkspaceInWindow, Sidebar, SidebarEvent, SidebarHandle,
29 ToggleWorkspaceSidebar,
30};
31pub use path_list::PathList;
32pub use toast_layer::{ToastAction, ToastLayer, ToastView};
33
34use anyhow::{Context as _, Result, anyhow};
35use client::{
36 ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
37 proto::{self, ErrorCode, PanelId, PeerId},
38};
39use collections::{HashMap, HashSet, hash_map};
40use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
41use fs::Fs;
42use futures::{
43 Future, FutureExt, StreamExt,
44 channel::{
45 mpsc::{self, UnboundedReceiver, UnboundedSender},
46 oneshot,
47 },
48 future::{Shared, try_join_all},
49};
50use gpui::{
51 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
52 CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
53 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
54 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
55 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
56 WindowOptions, actions, canvas, point, relative, size, transparent_black,
57};
58pub use history_manager::*;
59pub use item::{
60 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
61 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
62};
63use itertools::Itertools;
64use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
65pub use modal_layer::*;
66use node_runtime::NodeRuntime;
67use notifications::{
68 DetachAndPromptErr, Notifications, dismiss_app_notification,
69 simple_message_notification::MessageNotification,
70};
71pub use pane::*;
72pub use pane_group::{
73 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
74 SplitDirection,
75};
76use persistence::{DB, SerializedWindowBounds, model::SerializedWorkspace};
77pub use persistence::{
78 DB as WORKSPACE_DB, WorkspaceDb, delete_unloaded_items,
79 model::{ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation, SessionWorkspace},
80 read_serialized_multi_workspaces,
81};
82use postage::stream::Stream;
83use project::{
84 DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
85 WorktreeSettings,
86 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
87 project_settings::ProjectSettings,
88 toolchain_store::ToolchainStoreEvent,
89 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
90};
91use remote::{
92 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
93 remote_client::ConnectionIdentifier,
94};
95use schemars::JsonSchema;
96use serde::Deserialize;
97use session::AppSession;
98use settings::{
99 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
100};
101
102use sqlez::{
103 bindable::{Bind, Column, StaticColumnCount},
104 statement::Statement,
105};
106use status_bar::StatusBar;
107pub use status_bar::StatusItemView;
108use std::{
109 any::TypeId,
110 borrow::Cow,
111 cell::RefCell,
112 cmp,
113 collections::VecDeque,
114 env,
115 hash::Hash,
116 path::{Path, PathBuf},
117 process::ExitStatus,
118 rc::Rc,
119 sync::{
120 Arc, LazyLock, Weak,
121 atomic::{AtomicBool, AtomicUsize},
122 },
123 time::Duration,
124};
125use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
126use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
127pub use toolbar::{
128 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
129};
130pub use ui;
131use ui::{Window, prelude::*};
132use util::{
133 ResultExt, TryFutureExt,
134 paths::{PathStyle, SanitizedPath},
135 rel_path::RelPath,
136 serde::default_true,
137};
138use uuid::Uuid;
139pub use workspace_settings::{
140 AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
141 WorkspaceSettings,
142};
143use zed_actions::{Spawn, feedback::FileBugReport};
144
145use crate::{item::ItemBufferKind, notifications::NotificationId};
146use crate::{
147 persistence::{
148 SerializedAxis,
149 model::{DockData, DockStructure, SerializedItem, SerializedPane, SerializedPaneGroup},
150 },
151 security_modal::SecurityModal,
152};
153
154pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
155
156static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
157 env::var("ZED_WINDOW_SIZE")
158 .ok()
159 .as_deref()
160 .and_then(parse_pixel_size_env_var)
161});
162
163static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
164 env::var("ZED_WINDOW_POSITION")
165 .ok()
166 .as_deref()
167 .and_then(parse_pixel_position_env_var)
168});
169
170pub trait TerminalProvider {
171 fn spawn(
172 &self,
173 task: SpawnInTerminal,
174 window: &mut Window,
175 cx: &mut App,
176 ) -> Task<Option<Result<ExitStatus>>>;
177}
178
179pub trait DebuggerProvider {
180 // `active_buffer` is used to resolve build task's name against language-specific tasks.
181 fn start_session(
182 &self,
183 definition: DebugScenario,
184 task_context: SharedTaskContext,
185 active_buffer: Option<Entity<Buffer>>,
186 worktree_id: Option<WorktreeId>,
187 window: &mut Window,
188 cx: &mut App,
189 );
190
191 fn spawn_task_or_modal(
192 &self,
193 workspace: &mut Workspace,
194 action: &Spawn,
195 window: &mut Window,
196 cx: &mut Context<Workspace>,
197 );
198
199 fn task_scheduled(&self, cx: &mut App);
200 fn debug_scenario_scheduled(&self, cx: &mut App);
201 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
202
203 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
204}
205
206actions!(
207 workspace,
208 [
209 /// Activates the next pane in the workspace.
210 ActivateNextPane,
211 /// Activates the previous pane in the workspace.
212 ActivatePreviousPane,
213 /// Activates the last pane in the workspace.
214 ActivateLastPane,
215 /// Switches to the next window.
216 ActivateNextWindow,
217 /// Switches to the previous window.
218 ActivatePreviousWindow,
219 /// Adds a folder to the current project.
220 AddFolderToProject,
221 /// Clears all notifications.
222 ClearAllNotifications,
223 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
224 ClearNavigationHistory,
225 /// Closes the active dock.
226 CloseActiveDock,
227 /// Closes all docks.
228 CloseAllDocks,
229 /// Toggles all docks.
230 ToggleAllDocks,
231 /// Closes the current window.
232 CloseWindow,
233 /// Closes the current project.
234 CloseProject,
235 /// Opens the feedback dialog.
236 Feedback,
237 /// Follows the next collaborator in the session.
238 FollowNextCollaborator,
239 /// Moves the focused panel to the next position.
240 MoveFocusedPanelToNextPosition,
241 /// Creates a new file.
242 NewFile,
243 /// Creates a new file in a vertical split.
244 NewFileSplitVertical,
245 /// Creates a new file in a horizontal split.
246 NewFileSplitHorizontal,
247 /// Opens a new search.
248 NewSearch,
249 /// Opens a new window.
250 NewWindow,
251 /// Opens a file or directory.
252 Open,
253 /// Opens multiple files.
254 OpenFiles,
255 /// Opens the current location in terminal.
256 OpenInTerminal,
257 /// Opens the component preview.
258 OpenComponentPreview,
259 /// Reloads the active item.
260 ReloadActiveItem,
261 /// Resets the active dock to its default size.
262 ResetActiveDockSize,
263 /// Resets all open docks to their default sizes.
264 ResetOpenDocksSize,
265 /// Reloads the application
266 Reload,
267 /// Saves the current file with a new name.
268 SaveAs,
269 /// Saves without formatting.
270 SaveWithoutFormat,
271 /// Shuts down all debug adapters.
272 ShutdownDebugAdapters,
273 /// Suppresses the current notification.
274 SuppressNotification,
275 /// Toggles the bottom dock.
276 ToggleBottomDock,
277 /// Toggles centered layout mode.
278 ToggleCenteredLayout,
279 /// Toggles edit prediction feature globally for all files.
280 ToggleEditPrediction,
281 /// Toggles the left dock.
282 ToggleLeftDock,
283 /// Toggles the right dock.
284 ToggleRightDock,
285 /// Toggles zoom on the active pane.
286 ToggleZoom,
287 /// Toggles read-only mode for the active item (if supported by that item).
288 ToggleReadOnlyFile,
289 /// Zooms in on the active pane.
290 ZoomIn,
291 /// Zooms out of the active pane.
292 ZoomOut,
293 /// If any worktrees are in restricted mode, shows a modal with possible actions.
294 /// If the modal is shown already, closes it without trusting any worktree.
295 ToggleWorktreeSecurity,
296 /// Clears all trusted worktrees, placing them in restricted mode on next open.
297 /// Requires restart to take effect on already opened projects.
298 ClearTrustedWorktrees,
299 /// Stops following a collaborator.
300 Unfollow,
301 /// Restores the banner.
302 RestoreBanner,
303 /// Toggles expansion of the selected item.
304 ToggleExpandItem,
305 ]
306);
307
308/// Activates a specific pane by its index.
309#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
310#[action(namespace = workspace)]
311pub struct ActivatePane(pub usize);
312
313/// Moves an item to a specific pane by index.
314#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
315#[action(namespace = workspace)]
316#[serde(deny_unknown_fields)]
317pub struct MoveItemToPane {
318 #[serde(default = "default_1")]
319 pub destination: usize,
320 #[serde(default = "default_true")]
321 pub focus: bool,
322 #[serde(default)]
323 pub clone: bool,
324}
325
326fn default_1() -> usize {
327 1
328}
329
330/// Moves an item to a pane in the specified direction.
331#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
332#[action(namespace = workspace)]
333#[serde(deny_unknown_fields)]
334pub struct MoveItemToPaneInDirection {
335 #[serde(default = "default_right")]
336 pub direction: SplitDirection,
337 #[serde(default = "default_true")]
338 pub focus: bool,
339 #[serde(default)]
340 pub clone: bool,
341}
342
343/// Creates a new file in a split of the desired direction.
344#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
345#[action(namespace = workspace)]
346#[serde(deny_unknown_fields)]
347pub struct NewFileSplit(pub SplitDirection);
348
349fn default_right() -> SplitDirection {
350 SplitDirection::Right
351}
352
353/// Saves all open files in the workspace.
354#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
355#[action(namespace = workspace)]
356#[serde(deny_unknown_fields)]
357pub struct SaveAll {
358 #[serde(default)]
359 pub save_intent: Option<SaveIntent>,
360}
361
362/// Saves the current file with the specified options.
363#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
364#[action(namespace = workspace)]
365#[serde(deny_unknown_fields)]
366pub struct Save {
367 #[serde(default)]
368 pub save_intent: Option<SaveIntent>,
369}
370
371/// Closes all items and panes in the workspace.
372#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
373#[action(namespace = workspace)]
374#[serde(deny_unknown_fields)]
375pub struct CloseAllItemsAndPanes {
376 #[serde(default)]
377 pub save_intent: Option<SaveIntent>,
378}
379
380/// Closes all inactive tabs and panes in the workspace.
381#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
382#[action(namespace = workspace)]
383#[serde(deny_unknown_fields)]
384pub struct CloseInactiveTabsAndPanes {
385 #[serde(default)]
386 pub save_intent: Option<SaveIntent>,
387}
388
389/// Closes the active item across all panes.
390#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
391#[action(namespace = workspace)]
392#[serde(deny_unknown_fields)]
393pub struct CloseItemInAllPanes {
394 #[serde(default)]
395 pub save_intent: Option<SaveIntent>,
396 #[serde(default)]
397 pub close_pinned: bool,
398}
399
400/// Sends a sequence of keystrokes to the active element.
401#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
402#[action(namespace = workspace)]
403pub struct SendKeystrokes(pub String);
404
405actions!(
406 project_symbols,
407 [
408 /// Toggles the project symbols search.
409 #[action(name = "Toggle")]
410 ToggleProjectSymbols
411 ]
412);
413
414/// Toggles the file finder interface.
415#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
416#[action(namespace = file_finder, name = "Toggle")]
417#[serde(deny_unknown_fields)]
418pub struct ToggleFileFinder {
419 #[serde(default)]
420 pub separate_history: bool,
421}
422
423/// Opens a new terminal in the center.
424#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
425#[action(namespace = workspace)]
426#[serde(deny_unknown_fields)]
427pub struct NewCenterTerminal {
428 /// If true, creates a local terminal even in remote projects.
429 #[serde(default)]
430 pub local: bool,
431}
432
433/// Opens a new terminal.
434#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
435#[action(namespace = workspace)]
436#[serde(deny_unknown_fields)]
437pub struct NewTerminal {
438 /// If true, creates a local terminal even in remote projects.
439 #[serde(default)]
440 pub local: bool,
441}
442
443/// Increases size of a currently focused dock by a given amount of pixels.
444#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
445#[action(namespace = workspace)]
446#[serde(deny_unknown_fields)]
447pub struct IncreaseActiveDockSize {
448 /// For 0px parameter, uses UI font size value.
449 #[serde(default)]
450 pub px: u32,
451}
452
453/// Decreases size of a currently focused dock by a given amount of pixels.
454#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
455#[action(namespace = workspace)]
456#[serde(deny_unknown_fields)]
457pub struct DecreaseActiveDockSize {
458 /// For 0px parameter, uses UI font size value.
459 #[serde(default)]
460 pub px: u32,
461}
462
463/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
464#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
465#[action(namespace = workspace)]
466#[serde(deny_unknown_fields)]
467pub struct IncreaseOpenDocksSize {
468 /// For 0px parameter, uses UI font size value.
469 #[serde(default)]
470 pub px: u32,
471}
472
473/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
474#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
475#[action(namespace = workspace)]
476#[serde(deny_unknown_fields)]
477pub struct DecreaseOpenDocksSize {
478 /// For 0px parameter, uses UI font size value.
479 #[serde(default)]
480 pub px: u32,
481}
482
483actions!(
484 workspace,
485 [
486 /// Activates the pane to the left.
487 ActivatePaneLeft,
488 /// Activates the pane to the right.
489 ActivatePaneRight,
490 /// Activates the pane above.
491 ActivatePaneUp,
492 /// Activates the pane below.
493 ActivatePaneDown,
494 /// Swaps the current pane with the one to the left.
495 SwapPaneLeft,
496 /// Swaps the current pane with the one to the right.
497 SwapPaneRight,
498 /// Swaps the current pane with the one above.
499 SwapPaneUp,
500 /// Swaps the current pane with the one below.
501 SwapPaneDown,
502 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
503 SwapPaneAdjacent,
504 /// Move the current pane to be at the far left.
505 MovePaneLeft,
506 /// Move the current pane to be at the far right.
507 MovePaneRight,
508 /// Move the current pane to be at the very top.
509 MovePaneUp,
510 /// Move the current pane to be at the very bottom.
511 MovePaneDown,
512 ]
513);
514
515#[derive(PartialEq, Eq, Debug)]
516pub enum CloseIntent {
517 /// Quit the program entirely.
518 Quit,
519 /// Close a window.
520 CloseWindow,
521 /// Replace the workspace in an existing window.
522 ReplaceWindow,
523}
524
525#[derive(Clone)]
526pub struct Toast {
527 id: NotificationId,
528 msg: Cow<'static, str>,
529 autohide: bool,
530 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
531}
532
533impl Toast {
534 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
535 Toast {
536 id,
537 msg: msg.into(),
538 on_click: None,
539 autohide: false,
540 }
541 }
542
543 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
544 where
545 M: Into<Cow<'static, str>>,
546 F: Fn(&mut Window, &mut App) + 'static,
547 {
548 self.on_click = Some((message.into(), Arc::new(on_click)));
549 self
550 }
551
552 pub fn autohide(mut self) -> Self {
553 self.autohide = true;
554 self
555 }
556}
557
558impl PartialEq for Toast {
559 fn eq(&self, other: &Self) -> bool {
560 self.id == other.id
561 && self.msg == other.msg
562 && self.on_click.is_some() == other.on_click.is_some()
563 }
564}
565
566/// Opens a new terminal with the specified working directory.
567#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
568#[action(namespace = workspace)]
569#[serde(deny_unknown_fields)]
570pub struct OpenTerminal {
571 pub working_directory: PathBuf,
572 /// If true, creates a local terminal even in remote projects.
573 #[serde(default)]
574 pub local: bool,
575}
576
577#[derive(
578 Clone,
579 Copy,
580 Debug,
581 Default,
582 Hash,
583 PartialEq,
584 Eq,
585 PartialOrd,
586 Ord,
587 serde::Serialize,
588 serde::Deserialize,
589)]
590pub struct WorkspaceId(i64);
591
592impl WorkspaceId {
593 pub fn from_i64(value: i64) -> Self {
594 Self(value)
595 }
596}
597
598impl StaticColumnCount for WorkspaceId {}
599impl Bind for WorkspaceId {
600 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
601 self.0.bind(statement, start_index)
602 }
603}
604impl Column for WorkspaceId {
605 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
606 i64::column(statement, start_index)
607 .map(|(i, next_index)| (Self(i), next_index))
608 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
609 }
610}
611impl From<WorkspaceId> for i64 {
612 fn from(val: WorkspaceId) -> Self {
613 val.0
614 }
615}
616
617fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
618 if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
619 workspace_window
620 .update(cx, |multi_workspace, window, cx| {
621 let workspace = multi_workspace.workspace().clone();
622 workspace.update(cx, |workspace, cx| {
623 prompt_for_open_path_and_open(workspace, app_state, options, window, cx);
624 });
625 })
626 .ok();
627 } else {
628 let task = Workspace::new_local(Vec::new(), app_state.clone(), None, None, None, cx);
629 cx.spawn(async move |cx| {
630 let (window, _) = task.await?;
631 window.update(cx, |multi_workspace, window, cx| {
632 window.activate_window();
633 let workspace = multi_workspace.workspace().clone();
634 workspace.update(cx, |workspace, cx| {
635 prompt_for_open_path_and_open(workspace, app_state, options, window, cx);
636 });
637 })?;
638 anyhow::Ok(())
639 })
640 .detach_and_log_err(cx);
641 }
642}
643
644pub fn prompt_for_open_path_and_open(
645 workspace: &mut Workspace,
646 app_state: Arc<AppState>,
647 options: PathPromptOptions,
648 window: &mut Window,
649 cx: &mut Context<Workspace>,
650) {
651 let paths = workspace.prompt_for_open_path(
652 options,
653 DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
654 window,
655 cx,
656 );
657 cx.spawn_in(window, async move |this, cx| {
658 let Some(paths) = paths.await.log_err().flatten() else {
659 return;
660 };
661 if let Some(task) = this
662 .update_in(cx, |this, window, cx| {
663 this.open_workspace_for_paths(false, paths, window, cx)
664 })
665 .log_err()
666 {
667 task.await.log_err();
668 }
669 })
670 .detach();
671}
672
673pub fn init(app_state: Arc<AppState>, cx: &mut App) {
674 component::init();
675 theme_preview::init(cx);
676 toast_layer::init(cx);
677 history_manager::init(app_state.fs.clone(), cx);
678
679 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
680 .on_action(|_: &Reload, cx| reload(cx))
681 .on_action({
682 let app_state = Arc::downgrade(&app_state);
683 move |_: &Open, cx: &mut App| {
684 if let Some(app_state) = app_state.upgrade() {
685 prompt_and_open_paths(
686 app_state,
687 PathPromptOptions {
688 files: true,
689 directories: true,
690 multiple: true,
691 prompt: None,
692 },
693 cx,
694 );
695 }
696 }
697 })
698 .on_action({
699 let app_state = Arc::downgrade(&app_state);
700 move |_: &OpenFiles, cx: &mut App| {
701 let directories = cx.can_select_mixed_files_and_dirs();
702 if let Some(app_state) = app_state.upgrade() {
703 prompt_and_open_paths(
704 app_state,
705 PathPromptOptions {
706 files: true,
707 directories,
708 multiple: true,
709 prompt: None,
710 },
711 cx,
712 );
713 }
714 }
715 });
716}
717
718type BuildProjectItemFn =
719 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
720
721type BuildProjectItemForPathFn =
722 fn(
723 &Entity<Project>,
724 &ProjectPath,
725 &mut Window,
726 &mut App,
727 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
728
729#[derive(Clone, Default)]
730struct ProjectItemRegistry {
731 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
732 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
733}
734
735impl ProjectItemRegistry {
736 fn register<T: ProjectItem>(&mut self) {
737 self.build_project_item_fns_by_type.insert(
738 TypeId::of::<T::Item>(),
739 |item, project, pane, window, cx| {
740 let item = item.downcast().unwrap();
741 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
742 as Box<dyn ItemHandle>
743 },
744 );
745 self.build_project_item_for_path_fns
746 .push(|project, project_path, window, cx| {
747 let project_path = project_path.clone();
748 let is_file = project
749 .read(cx)
750 .entry_for_path(&project_path, cx)
751 .is_some_and(|entry| entry.is_file());
752 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
753 let is_local = project.read(cx).is_local();
754 let project_item =
755 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
756 let project = project.clone();
757 Some(window.spawn(cx, async move |cx| {
758 match project_item.await.with_context(|| {
759 format!(
760 "opening project path {:?}",
761 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
762 )
763 }) {
764 Ok(project_item) => {
765 let project_item = project_item;
766 let project_entry_id: Option<ProjectEntryId> =
767 project_item.read_with(cx, project::ProjectItem::entry_id);
768 let build_workspace_item = Box::new(
769 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
770 Box::new(cx.new(|cx| {
771 T::for_project_item(
772 project,
773 Some(pane),
774 project_item,
775 window,
776 cx,
777 )
778 })) as Box<dyn ItemHandle>
779 },
780 ) as Box<_>;
781 Ok((project_entry_id, build_workspace_item))
782 }
783 Err(e) => {
784 log::warn!("Failed to open a project item: {e:#}");
785 if e.error_code() == ErrorCode::Internal {
786 if let Some(abs_path) =
787 entry_abs_path.as_deref().filter(|_| is_file)
788 {
789 if let Some(broken_project_item_view) =
790 cx.update(|window, cx| {
791 T::for_broken_project_item(
792 abs_path, is_local, &e, window, cx,
793 )
794 })?
795 {
796 let build_workspace_item = Box::new(
797 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
798 cx.new(|_| broken_project_item_view).boxed_clone()
799 },
800 )
801 as Box<_>;
802 return Ok((None, build_workspace_item));
803 }
804 }
805 }
806 Err(e)
807 }
808 }
809 }))
810 });
811 }
812
813 fn open_path(
814 &self,
815 project: &Entity<Project>,
816 path: &ProjectPath,
817 window: &mut Window,
818 cx: &mut App,
819 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
820 let Some(open_project_item) = self
821 .build_project_item_for_path_fns
822 .iter()
823 .rev()
824 .find_map(|open_project_item| open_project_item(project, path, window, cx))
825 else {
826 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
827 };
828 open_project_item
829 }
830
831 fn build_item<T: project::ProjectItem>(
832 &self,
833 item: Entity<T>,
834 project: Entity<Project>,
835 pane: Option<&Pane>,
836 window: &mut Window,
837 cx: &mut App,
838 ) -> Option<Box<dyn ItemHandle>> {
839 let build = self
840 .build_project_item_fns_by_type
841 .get(&TypeId::of::<T>())?;
842 Some(build(item.into_any(), project, pane, window, cx))
843 }
844}
845
846type WorkspaceItemBuilder =
847 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
848
849impl Global for ProjectItemRegistry {}
850
851/// Registers a [ProjectItem] for the app. When opening a file, all the registered
852/// items will get a chance to open the file, starting from the project item that
853/// was added last.
854pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
855 cx.default_global::<ProjectItemRegistry>().register::<I>();
856}
857
858#[derive(Default)]
859pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
860
861struct FollowableViewDescriptor {
862 from_state_proto: fn(
863 Entity<Workspace>,
864 ViewId,
865 &mut Option<proto::view::Variant>,
866 &mut Window,
867 &mut App,
868 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
869 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
870}
871
872impl Global for FollowableViewRegistry {}
873
874impl FollowableViewRegistry {
875 pub fn register<I: FollowableItem>(cx: &mut App) {
876 cx.default_global::<Self>().0.insert(
877 TypeId::of::<I>(),
878 FollowableViewDescriptor {
879 from_state_proto: |workspace, id, state, window, cx| {
880 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
881 cx.foreground_executor()
882 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
883 })
884 },
885 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
886 },
887 );
888 }
889
890 pub fn from_state_proto(
891 workspace: Entity<Workspace>,
892 view_id: ViewId,
893 mut state: Option<proto::view::Variant>,
894 window: &mut Window,
895 cx: &mut App,
896 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
897 cx.update_default_global(|this: &mut Self, cx| {
898 this.0.values().find_map(|descriptor| {
899 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
900 })
901 })
902 }
903
904 pub fn to_followable_view(
905 view: impl Into<AnyView>,
906 cx: &App,
907 ) -> Option<Box<dyn FollowableItemHandle>> {
908 let this = cx.try_global::<Self>()?;
909 let view = view.into();
910 let descriptor = this.0.get(&view.entity_type())?;
911 Some((descriptor.to_followable_view)(&view))
912 }
913}
914
915#[derive(Copy, Clone)]
916struct SerializableItemDescriptor {
917 deserialize: fn(
918 Entity<Project>,
919 WeakEntity<Workspace>,
920 WorkspaceId,
921 ItemId,
922 &mut Window,
923 &mut Context<Pane>,
924 ) -> Task<Result<Box<dyn ItemHandle>>>,
925 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
926 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
927}
928
929#[derive(Default)]
930struct SerializableItemRegistry {
931 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
932 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
933}
934
935impl Global for SerializableItemRegistry {}
936
937impl SerializableItemRegistry {
938 fn deserialize(
939 item_kind: &str,
940 project: Entity<Project>,
941 workspace: WeakEntity<Workspace>,
942 workspace_id: WorkspaceId,
943 item_item: ItemId,
944 window: &mut Window,
945 cx: &mut Context<Pane>,
946 ) -> Task<Result<Box<dyn ItemHandle>>> {
947 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
948 return Task::ready(Err(anyhow!(
949 "cannot deserialize {}, descriptor not found",
950 item_kind
951 )));
952 };
953
954 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
955 }
956
957 fn cleanup(
958 item_kind: &str,
959 workspace_id: WorkspaceId,
960 loaded_items: Vec<ItemId>,
961 window: &mut Window,
962 cx: &mut App,
963 ) -> Task<Result<()>> {
964 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
965 return Task::ready(Err(anyhow!(
966 "cannot cleanup {}, descriptor not found",
967 item_kind
968 )));
969 };
970
971 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
972 }
973
974 fn view_to_serializable_item_handle(
975 view: AnyView,
976 cx: &App,
977 ) -> Option<Box<dyn SerializableItemHandle>> {
978 let this = cx.try_global::<Self>()?;
979 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
980 Some((descriptor.view_to_serializable_item)(view))
981 }
982
983 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
984 let this = cx.try_global::<Self>()?;
985 this.descriptors_by_kind.get(item_kind).copied()
986 }
987}
988
989pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
990 let serialized_item_kind = I::serialized_item_kind();
991
992 let registry = cx.default_global::<SerializableItemRegistry>();
993 let descriptor = SerializableItemDescriptor {
994 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
995 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
996 cx.foreground_executor()
997 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
998 },
999 cleanup: |workspace_id, loaded_items, window, cx| {
1000 I::cleanup(workspace_id, loaded_items, window, cx)
1001 },
1002 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
1003 };
1004 registry
1005 .descriptors_by_kind
1006 .insert(Arc::from(serialized_item_kind), descriptor);
1007 registry
1008 .descriptors_by_type
1009 .insert(TypeId::of::<I>(), descriptor);
1010}
1011
1012pub struct AppState {
1013 pub languages: Arc<LanguageRegistry>,
1014 pub client: Arc<Client>,
1015 pub user_store: Entity<UserStore>,
1016 pub workspace_store: Entity<WorkspaceStore>,
1017 pub fs: Arc<dyn fs::Fs>,
1018 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
1019 pub node_runtime: NodeRuntime,
1020 pub session: Entity<AppSession>,
1021}
1022
1023struct GlobalAppState(Weak<AppState>);
1024
1025impl Global for GlobalAppState {}
1026
1027pub struct WorkspaceStore {
1028 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1029 client: Arc<Client>,
1030 _subscriptions: Vec<client::Subscription>,
1031}
1032
1033#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1034pub enum CollaboratorId {
1035 PeerId(PeerId),
1036 Agent,
1037}
1038
1039impl From<PeerId> for CollaboratorId {
1040 fn from(peer_id: PeerId) -> Self {
1041 CollaboratorId::PeerId(peer_id)
1042 }
1043}
1044
1045impl From<&PeerId> for CollaboratorId {
1046 fn from(peer_id: &PeerId) -> Self {
1047 CollaboratorId::PeerId(*peer_id)
1048 }
1049}
1050
1051#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1052struct Follower {
1053 project_id: Option<u64>,
1054 peer_id: PeerId,
1055}
1056
1057impl AppState {
1058 #[track_caller]
1059 pub fn global(cx: &App) -> Weak<Self> {
1060 cx.global::<GlobalAppState>().0.clone()
1061 }
1062 pub fn try_global(cx: &App) -> Option<Weak<Self>> {
1063 cx.try_global::<GlobalAppState>()
1064 .map(|state| state.0.clone())
1065 }
1066 pub fn set_global(state: Weak<AppState>, cx: &mut App) {
1067 cx.set_global(GlobalAppState(state));
1068 }
1069
1070 #[cfg(any(test, feature = "test-support"))]
1071 pub fn test(cx: &mut App) -> Arc<Self> {
1072 use fs::Fs;
1073 use node_runtime::NodeRuntime;
1074 use session::Session;
1075 use settings::SettingsStore;
1076
1077 if !cx.has_global::<SettingsStore>() {
1078 let settings_store = SettingsStore::test(cx);
1079 cx.set_global(settings_store);
1080 }
1081
1082 let fs = fs::FakeFs::new(cx.background_executor().clone());
1083 <dyn Fs>::set_global(fs.clone(), cx);
1084 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1085 let clock = Arc::new(clock::FakeSystemClock::new());
1086 let http_client = http_client::FakeHttpClient::with_404_response();
1087 let client = Client::new(clock, http_client, cx);
1088 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1089 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1090 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1091
1092 theme::init(theme::LoadThemes::JustBase, cx);
1093 client::init(&client, cx);
1094
1095 Arc::new(Self {
1096 client,
1097 fs,
1098 languages,
1099 user_store,
1100 workspace_store,
1101 node_runtime: NodeRuntime::unavailable(),
1102 build_window_options: |_, _| Default::default(),
1103 session,
1104 })
1105 }
1106}
1107
1108struct DelayedDebouncedEditAction {
1109 task: Option<Task<()>>,
1110 cancel_channel: Option<oneshot::Sender<()>>,
1111}
1112
1113impl DelayedDebouncedEditAction {
1114 fn new() -> DelayedDebouncedEditAction {
1115 DelayedDebouncedEditAction {
1116 task: None,
1117 cancel_channel: None,
1118 }
1119 }
1120
1121 fn fire_new<F>(
1122 &mut self,
1123 delay: Duration,
1124 window: &mut Window,
1125 cx: &mut Context<Workspace>,
1126 func: F,
1127 ) where
1128 F: 'static
1129 + Send
1130 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1131 {
1132 if let Some(channel) = self.cancel_channel.take() {
1133 _ = channel.send(());
1134 }
1135
1136 let (sender, mut receiver) = oneshot::channel::<()>();
1137 self.cancel_channel = Some(sender);
1138
1139 let previous_task = self.task.take();
1140 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1141 let mut timer = cx.background_executor().timer(delay).fuse();
1142 if let Some(previous_task) = previous_task {
1143 previous_task.await;
1144 }
1145
1146 futures::select_biased! {
1147 _ = receiver => return,
1148 _ = timer => {}
1149 }
1150
1151 if let Some(result) = workspace
1152 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1153 .log_err()
1154 {
1155 result.await.log_err();
1156 }
1157 }));
1158 }
1159}
1160
1161pub enum Event {
1162 PaneAdded(Entity<Pane>),
1163 PaneRemoved,
1164 ItemAdded {
1165 item: Box<dyn ItemHandle>,
1166 },
1167 ActiveItemChanged,
1168 ItemRemoved {
1169 item_id: EntityId,
1170 },
1171 UserSavedItem {
1172 pane: WeakEntity<Pane>,
1173 item: Box<dyn WeakItemHandle>,
1174 save_intent: SaveIntent,
1175 },
1176 ContactRequestedJoin(u64),
1177 WorkspaceCreated(WeakEntity<Workspace>),
1178 OpenBundledFile {
1179 text: Cow<'static, str>,
1180 title: &'static str,
1181 language: &'static str,
1182 },
1183 ZoomChanged,
1184 ModalOpened,
1185}
1186
1187#[derive(Debug, Clone)]
1188pub enum OpenVisible {
1189 All,
1190 None,
1191 OnlyFiles,
1192 OnlyDirectories,
1193}
1194
1195enum WorkspaceLocation {
1196 // Valid local paths or SSH project to serialize
1197 Location(SerializedWorkspaceLocation, PathList),
1198 // No valid location found hence clear session id
1199 DetachFromSession,
1200 // No valid location found to serialize
1201 None,
1202}
1203
1204type PromptForNewPath = Box<
1205 dyn Fn(
1206 &mut Workspace,
1207 DirectoryLister,
1208 Option<String>,
1209 &mut Window,
1210 &mut Context<Workspace>,
1211 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1212>;
1213
1214type PromptForOpenPath = Box<
1215 dyn Fn(
1216 &mut Workspace,
1217 DirectoryLister,
1218 &mut Window,
1219 &mut Context<Workspace>,
1220 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1221>;
1222
1223#[derive(Default)]
1224struct DispatchingKeystrokes {
1225 dispatched: HashSet<Vec<Keystroke>>,
1226 queue: VecDeque<Keystroke>,
1227 task: Option<Shared<Task<()>>>,
1228}
1229
1230/// Collects everything project-related for a certain window opened.
1231/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1232///
1233/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1234/// The `Workspace` owns everybody's state and serves as a default, "global context",
1235/// that can be used to register a global action to be triggered from any place in the window.
1236pub struct Workspace {
1237 weak_self: WeakEntity<Self>,
1238 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1239 zoomed: Option<AnyWeakView>,
1240 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1241 zoomed_position: Option<DockPosition>,
1242 center: PaneGroup,
1243 left_dock: Entity<Dock>,
1244 bottom_dock: Entity<Dock>,
1245 right_dock: Entity<Dock>,
1246 panes: Vec<Entity<Pane>>,
1247 active_worktree_override: Option<WorktreeId>,
1248 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1249 active_pane: Entity<Pane>,
1250 last_active_center_pane: Option<WeakEntity<Pane>>,
1251 last_active_view_id: Option<proto::ViewId>,
1252 status_bar: Entity<StatusBar>,
1253 modal_layer: Entity<ModalLayer>,
1254 toast_layer: Entity<ToastLayer>,
1255 titlebar_item: Option<AnyView>,
1256 notifications: Notifications,
1257 suppressed_notifications: HashSet<NotificationId>,
1258 project: Entity<Project>,
1259 follower_states: HashMap<CollaboratorId, FollowerState>,
1260 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1261 window_edited: bool,
1262 last_window_title: Option<String>,
1263 dirty_items: HashMap<EntityId, Subscription>,
1264 active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
1265 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1266 database_id: Option<WorkspaceId>,
1267 app_state: Arc<AppState>,
1268 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1269 _subscriptions: Vec<Subscription>,
1270 _apply_leader_updates: Task<Result<()>>,
1271 _observe_current_user: Task<Result<()>>,
1272 _schedule_serialize_workspace: Option<Task<()>>,
1273 _serialize_workspace_task: Option<Task<()>>,
1274 _schedule_serialize_ssh_paths: Option<Task<()>>,
1275 pane_history_timestamp: Arc<AtomicUsize>,
1276 bounds: Bounds<Pixels>,
1277 pub centered_layout: bool,
1278 bounds_save_task_queued: Option<Task<()>>,
1279 on_prompt_for_new_path: Option<PromptForNewPath>,
1280 on_prompt_for_open_path: Option<PromptForOpenPath>,
1281 terminal_provider: Option<Box<dyn TerminalProvider>>,
1282 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1283 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1284 _items_serializer: Task<Result<()>>,
1285 session_id: Option<String>,
1286 scheduled_tasks: Vec<Task<()>>,
1287 last_open_dock_positions: Vec<DockPosition>,
1288 removing: bool,
1289}
1290
1291impl EventEmitter<Event> for Workspace {}
1292
1293#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1294pub struct ViewId {
1295 pub creator: CollaboratorId,
1296 pub id: u64,
1297}
1298
1299pub struct FollowerState {
1300 center_pane: Entity<Pane>,
1301 dock_pane: Option<Entity<Pane>>,
1302 active_view_id: Option<ViewId>,
1303 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1304}
1305
1306struct FollowerView {
1307 view: Box<dyn FollowableItemHandle>,
1308 location: Option<proto::PanelId>,
1309}
1310
1311impl Workspace {
1312 pub fn new(
1313 workspace_id: Option<WorkspaceId>,
1314 project: Entity<Project>,
1315 app_state: Arc<AppState>,
1316 window: &mut Window,
1317 cx: &mut Context<Self>,
1318 ) -> Self {
1319 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1320 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1321 if let TrustedWorktreesEvent::Trusted(..) = e {
1322 // Do not persist auto trusted worktrees
1323 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1324 worktrees_store.update(cx, |worktrees_store, cx| {
1325 worktrees_store.schedule_serialization(
1326 cx,
1327 |new_trusted_worktrees, cx| {
1328 let timeout =
1329 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1330 cx.background_spawn(async move {
1331 timeout.await;
1332 persistence::DB
1333 .save_trusted_worktrees(new_trusted_worktrees)
1334 .await
1335 .log_err();
1336 })
1337 },
1338 )
1339 });
1340 }
1341 }
1342 })
1343 .detach();
1344
1345 cx.observe_global::<SettingsStore>(|_, cx| {
1346 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1347 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1348 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1349 trusted_worktrees.auto_trust_all(cx);
1350 })
1351 }
1352 }
1353 })
1354 .detach();
1355 }
1356
1357 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1358 match event {
1359 project::Event::RemoteIdChanged(_) => {
1360 this.update_window_title(window, cx);
1361 }
1362
1363 project::Event::CollaboratorLeft(peer_id) => {
1364 this.collaborator_left(*peer_id, window, cx);
1365 }
1366
1367 &project::Event::WorktreeRemoved(id) | &project::Event::WorktreeAdded(id) => {
1368 this.update_window_title(window, cx);
1369 if this
1370 .project()
1371 .read(cx)
1372 .worktree_for_id(id, cx)
1373 .is_some_and(|wt| wt.read(cx).is_visible())
1374 {
1375 this.serialize_workspace(window, cx);
1376 this.update_history(cx);
1377 }
1378 }
1379 project::Event::WorktreeUpdatedEntries(..) => {
1380 this.update_window_title(window, cx);
1381 this.serialize_workspace(window, cx);
1382 }
1383
1384 project::Event::DisconnectedFromHost => {
1385 this.update_window_edited(window, cx);
1386 let leaders_to_unfollow =
1387 this.follower_states.keys().copied().collect::<Vec<_>>();
1388 for leader_id in leaders_to_unfollow {
1389 this.unfollow(leader_id, window, cx);
1390 }
1391 }
1392
1393 project::Event::DisconnectedFromRemote {
1394 server_not_running: _,
1395 } => {
1396 this.update_window_edited(window, cx);
1397 }
1398
1399 project::Event::Closed => {
1400 window.remove_window();
1401 }
1402
1403 project::Event::DeletedEntry(_, entry_id) => {
1404 for pane in this.panes.iter() {
1405 pane.update(cx, |pane, cx| {
1406 pane.handle_deleted_project_item(*entry_id, window, cx)
1407 });
1408 }
1409 }
1410
1411 project::Event::Toast {
1412 notification_id,
1413 message,
1414 link,
1415 } => this.show_notification(
1416 NotificationId::named(notification_id.clone()),
1417 cx,
1418 |cx| {
1419 let mut notification = MessageNotification::new(message.clone(), cx);
1420 if let Some(link) = link {
1421 notification = notification
1422 .more_info_message(link.label)
1423 .more_info_url(link.url);
1424 }
1425
1426 cx.new(|_| notification)
1427 },
1428 ),
1429
1430 project::Event::HideToast { notification_id } => {
1431 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1432 }
1433
1434 project::Event::LanguageServerPrompt(request) => {
1435 struct LanguageServerPrompt;
1436
1437 this.show_notification(
1438 NotificationId::composite::<LanguageServerPrompt>(request.id),
1439 cx,
1440 |cx| {
1441 cx.new(|cx| {
1442 notifications::LanguageServerPrompt::new(request.clone(), cx)
1443 })
1444 },
1445 );
1446 }
1447
1448 project::Event::AgentLocationChanged => {
1449 this.handle_agent_location_changed(window, cx)
1450 }
1451
1452 _ => {}
1453 }
1454 cx.notify()
1455 })
1456 .detach();
1457
1458 cx.subscribe_in(
1459 &project.read(cx).breakpoint_store(),
1460 window,
1461 |workspace, _, event, window, cx| match event {
1462 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1463 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1464 workspace.serialize_workspace(window, cx);
1465 }
1466 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1467 },
1468 )
1469 .detach();
1470 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1471 cx.subscribe_in(
1472 &toolchain_store,
1473 window,
1474 |workspace, _, event, window, cx| match event {
1475 ToolchainStoreEvent::CustomToolchainsModified => {
1476 workspace.serialize_workspace(window, cx);
1477 }
1478 _ => {}
1479 },
1480 )
1481 .detach();
1482 }
1483
1484 cx.on_focus_lost(window, |this, window, cx| {
1485 let focus_handle = this.focus_handle(cx);
1486 window.focus(&focus_handle, cx);
1487 })
1488 .detach();
1489
1490 let weak_handle = cx.entity().downgrade();
1491 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1492
1493 let center_pane = cx.new(|cx| {
1494 let mut center_pane = Pane::new(
1495 weak_handle.clone(),
1496 project.clone(),
1497 pane_history_timestamp.clone(),
1498 None,
1499 NewFile.boxed_clone(),
1500 true,
1501 window,
1502 cx,
1503 );
1504 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1505 center_pane.set_should_display_welcome_page(true);
1506 center_pane
1507 });
1508 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1509 .detach();
1510
1511 window.focus(¢er_pane.focus_handle(cx), cx);
1512
1513 cx.emit(Event::PaneAdded(center_pane.clone()));
1514
1515 let any_window_handle = window.window_handle();
1516 app_state.workspace_store.update(cx, |store, _| {
1517 store
1518 .workspaces
1519 .insert((any_window_handle, weak_handle.clone()));
1520 });
1521
1522 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1523 let mut connection_status = app_state.client.status();
1524 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1525 current_user.next().await;
1526 connection_status.next().await;
1527 let mut stream =
1528 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1529
1530 while stream.recv().await.is_some() {
1531 this.update(cx, |_, cx| cx.notify())?;
1532 }
1533 anyhow::Ok(())
1534 });
1535
1536 // All leader updates are enqueued and then processed in a single task, so
1537 // that each asynchronous operation can be run in order.
1538 let (leader_updates_tx, mut leader_updates_rx) =
1539 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1540 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1541 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1542 Self::process_leader_update(&this, leader_id, update, cx)
1543 .await
1544 .log_err();
1545 }
1546
1547 Ok(())
1548 });
1549
1550 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1551 let modal_layer = cx.new(|_| ModalLayer::new());
1552 let toast_layer = cx.new(|_| ToastLayer::new());
1553 cx.subscribe(
1554 &modal_layer,
1555 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1556 cx.emit(Event::ModalOpened);
1557 },
1558 )
1559 .detach();
1560
1561 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1562 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1563 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1564 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1565 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1566 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1567 let status_bar = cx.new(|cx| {
1568 let mut status_bar = StatusBar::new(¢er_pane.clone(), window, cx);
1569 status_bar.add_left_item(left_dock_buttons, window, cx);
1570 status_bar.add_right_item(right_dock_buttons, window, cx);
1571 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1572 status_bar
1573 });
1574
1575 let session_id = app_state.session.read(cx).id().to_owned();
1576
1577 let mut active_call = None;
1578 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1579 let subscriptions =
1580 vec![
1581 call.0
1582 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1583 ];
1584 active_call = Some((call, subscriptions));
1585 }
1586
1587 let (serializable_items_tx, serializable_items_rx) =
1588 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1589 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1590 Self::serialize_items(&this, serializable_items_rx, cx).await
1591 });
1592
1593 let subscriptions = vec![
1594 cx.observe_window_activation(window, Self::on_window_activation_changed),
1595 cx.observe_window_bounds(window, move |this, window, cx| {
1596 if this.bounds_save_task_queued.is_some() {
1597 return;
1598 }
1599 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1600 cx.background_executor()
1601 .timer(Duration::from_millis(100))
1602 .await;
1603 this.update_in(cx, |this, window, cx| {
1604 if let Some(display) = window.display(cx)
1605 && let Ok(display_uuid) = display.uuid()
1606 {
1607 let window_bounds = window.inner_window_bounds();
1608 let has_paths = !this.root_paths(cx).is_empty();
1609 if !has_paths {
1610 cx.background_executor()
1611 .spawn(persistence::write_default_window_bounds(
1612 window_bounds,
1613 display_uuid,
1614 ))
1615 .detach_and_log_err(cx);
1616 }
1617 if let Some(database_id) = workspace_id {
1618 cx.background_executor()
1619 .spawn(DB.set_window_open_status(
1620 database_id,
1621 SerializedWindowBounds(window_bounds),
1622 display_uuid,
1623 ))
1624 .detach_and_log_err(cx);
1625 } else {
1626 cx.background_executor()
1627 .spawn(persistence::write_default_window_bounds(
1628 window_bounds,
1629 display_uuid,
1630 ))
1631 .detach_and_log_err(cx);
1632 }
1633 }
1634 this.bounds_save_task_queued.take();
1635 })
1636 .ok();
1637 }));
1638 cx.notify();
1639 }),
1640 cx.observe_window_appearance(window, |_, window, cx| {
1641 let window_appearance = window.appearance();
1642
1643 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1644
1645 GlobalTheme::reload_theme(cx);
1646 GlobalTheme::reload_icon_theme(cx);
1647 }),
1648 cx.on_release({
1649 let weak_handle = weak_handle.clone();
1650 move |this, cx| {
1651 this.app_state.workspace_store.update(cx, move |store, _| {
1652 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1653 })
1654 }
1655 }),
1656 ];
1657
1658 cx.defer_in(window, move |this, window, cx| {
1659 this.update_window_title(window, cx);
1660 this.show_initial_notifications(cx);
1661 });
1662
1663 let mut center = PaneGroup::new(center_pane.clone());
1664 center.set_is_center(true);
1665 center.mark_positions(cx);
1666
1667 Workspace {
1668 weak_self: weak_handle.clone(),
1669 zoomed: None,
1670 zoomed_position: None,
1671 previous_dock_drag_coordinates: None,
1672 center,
1673 panes: vec![center_pane.clone()],
1674 panes_by_item: Default::default(),
1675 active_pane: center_pane.clone(),
1676 last_active_center_pane: Some(center_pane.downgrade()),
1677 last_active_view_id: None,
1678 status_bar,
1679 modal_layer,
1680 toast_layer,
1681 titlebar_item: None,
1682 active_worktree_override: None,
1683 notifications: Notifications::default(),
1684 suppressed_notifications: HashSet::default(),
1685 left_dock,
1686 bottom_dock,
1687 right_dock,
1688 project: project.clone(),
1689 follower_states: Default::default(),
1690 last_leaders_by_pane: Default::default(),
1691 dispatching_keystrokes: Default::default(),
1692 window_edited: false,
1693 last_window_title: None,
1694 dirty_items: Default::default(),
1695 active_call,
1696 database_id: workspace_id,
1697 app_state,
1698 _observe_current_user,
1699 _apply_leader_updates,
1700 _schedule_serialize_workspace: None,
1701 _serialize_workspace_task: None,
1702 _schedule_serialize_ssh_paths: None,
1703 leader_updates_tx,
1704 _subscriptions: subscriptions,
1705 pane_history_timestamp,
1706 workspace_actions: Default::default(),
1707 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1708 bounds: Default::default(),
1709 centered_layout: false,
1710 bounds_save_task_queued: None,
1711 on_prompt_for_new_path: None,
1712 on_prompt_for_open_path: None,
1713 terminal_provider: None,
1714 debugger_provider: None,
1715 serializable_items_tx,
1716 _items_serializer,
1717 session_id: Some(session_id),
1718
1719 scheduled_tasks: Vec::new(),
1720 last_open_dock_positions: Vec::new(),
1721 removing: false,
1722 }
1723 }
1724
1725 pub fn new_local(
1726 abs_paths: Vec<PathBuf>,
1727 app_state: Arc<AppState>,
1728 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1729 env: Option<HashMap<String, String>>,
1730 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1731 cx: &mut App,
1732 ) -> Task<
1733 anyhow::Result<(
1734 WindowHandle<MultiWorkspace>,
1735 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
1736 )>,
1737 > {
1738 let project_handle = Project::local(
1739 app_state.client.clone(),
1740 app_state.node_runtime.clone(),
1741 app_state.user_store.clone(),
1742 app_state.languages.clone(),
1743 app_state.fs.clone(),
1744 env,
1745 Default::default(),
1746 cx,
1747 );
1748
1749 cx.spawn(async move |cx| {
1750 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1751 for path in abs_paths.into_iter() {
1752 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1753 paths_to_open.push(canonical)
1754 } else {
1755 paths_to_open.push(path)
1756 }
1757 }
1758
1759 let serialized_workspace =
1760 persistence::DB.workspace_for_roots(paths_to_open.as_slice());
1761
1762 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1763 paths_to_open = paths.ordered_paths().cloned().collect();
1764 if !paths.is_lexicographically_ordered() {
1765 project_handle.update(cx, |project, cx| {
1766 project.set_worktrees_reordered(true, cx);
1767 });
1768 }
1769 }
1770
1771 // Get project paths for all of the abs_paths
1772 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1773 Vec::with_capacity(paths_to_open.len());
1774
1775 for path in paths_to_open.into_iter() {
1776 if let Some((_, project_entry)) = cx
1777 .update(|cx| {
1778 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1779 })
1780 .await
1781 .log_err()
1782 {
1783 project_paths.push((path, Some(project_entry)));
1784 } else {
1785 project_paths.push((path, None));
1786 }
1787 }
1788
1789 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1790 serialized_workspace.id
1791 } else {
1792 DB.next_id().await.unwrap_or_else(|_| Default::default())
1793 };
1794
1795 let toolchains = DB.toolchains(workspace_id).await?;
1796
1797 for (toolchain, worktree_path, path) in toolchains {
1798 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1799 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1800 this.find_worktree(&worktree_path, cx)
1801 .and_then(|(worktree, rel_path)| {
1802 if rel_path.is_empty() {
1803 Some(worktree.read(cx).id())
1804 } else {
1805 None
1806 }
1807 })
1808 }) else {
1809 // We did not find a worktree with a given path, but that's whatever.
1810 continue;
1811 };
1812 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1813 continue;
1814 }
1815
1816 project_handle
1817 .update(cx, |this, cx| {
1818 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1819 })
1820 .await;
1821 }
1822 if let Some(workspace) = serialized_workspace.as_ref() {
1823 project_handle.update(cx, |this, cx| {
1824 for (scope, toolchains) in &workspace.user_toolchains {
1825 for toolchain in toolchains {
1826 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1827 }
1828 }
1829 });
1830 }
1831
1832 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1833 if let Some(window) = requesting_window {
1834 let centered_layout = serialized_workspace
1835 .as_ref()
1836 .map(|w| w.centered_layout)
1837 .unwrap_or(false);
1838
1839 let workspace = window.update(cx, |multi_workspace, window, cx| {
1840 let workspace = cx.new(|cx| {
1841 let mut workspace = Workspace::new(
1842 Some(workspace_id),
1843 project_handle.clone(),
1844 app_state.clone(),
1845 window,
1846 cx,
1847 );
1848
1849 workspace.centered_layout = centered_layout;
1850
1851 // Call init callback to add items before window renders
1852 if let Some(init) = init {
1853 init(&mut workspace, window, cx);
1854 }
1855
1856 workspace
1857 });
1858 multi_workspace.activate(workspace.clone(), cx);
1859 workspace
1860 })?;
1861 (window, workspace)
1862 } else {
1863 let window_bounds_override = window_bounds_env_override();
1864
1865 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1866 (Some(WindowBounds::Windowed(bounds)), None)
1867 } else if let Some(workspace) = serialized_workspace.as_ref()
1868 && let Some(display) = workspace.display
1869 && let Some(bounds) = workspace.window_bounds.as_ref()
1870 {
1871 // Reopening an existing workspace - restore its saved bounds
1872 (Some(bounds.0), Some(display))
1873 } else if let Some((display, bounds)) =
1874 persistence::read_default_window_bounds()
1875 {
1876 // New or empty workspace - use the last known window bounds
1877 (Some(bounds), Some(display))
1878 } else {
1879 // New window - let GPUI's default_bounds() handle cascading
1880 (None, None)
1881 };
1882
1883 // Use the serialized workspace to construct the new window
1884 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1885 options.window_bounds = window_bounds;
1886 let centered_layout = serialized_workspace
1887 .as_ref()
1888 .map(|w| w.centered_layout)
1889 .unwrap_or(false);
1890 let window = cx.open_window(options, {
1891 let app_state = app_state.clone();
1892 let project_handle = project_handle.clone();
1893 move |window, cx| {
1894 let workspace = cx.new(|cx| {
1895 let mut workspace = Workspace::new(
1896 Some(workspace_id),
1897 project_handle,
1898 app_state,
1899 window,
1900 cx,
1901 );
1902 workspace.centered_layout = centered_layout;
1903
1904 // Call init callback to add items before window renders
1905 if let Some(init) = init {
1906 init(&mut workspace, window, cx);
1907 }
1908
1909 workspace
1910 });
1911 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1912 }
1913 })?;
1914 let workspace =
1915 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
1916 multi_workspace.workspace().clone()
1917 })?;
1918 (window, workspace)
1919 };
1920
1921 notify_if_database_failed(window, cx);
1922 // Check if this is an empty workspace (no paths to open)
1923 // An empty workspace is one where project_paths is empty
1924 let is_empty_workspace = project_paths.is_empty();
1925 // Check if serialized workspace has paths before it's moved
1926 let serialized_workspace_has_paths = serialized_workspace
1927 .as_ref()
1928 .map(|ws| !ws.paths.is_empty())
1929 .unwrap_or(false);
1930
1931 let opened_items = window
1932 .update(cx, |_, window, cx| {
1933 workspace.update(cx, |_workspace: &mut Workspace, cx| {
1934 open_items(serialized_workspace, project_paths, window, cx)
1935 })
1936 })?
1937 .await
1938 .unwrap_or_default();
1939
1940 // Restore default dock state for empty workspaces
1941 // Only restore if:
1942 // 1. This is an empty workspace (no paths), AND
1943 // 2. The serialized workspace either doesn't exist or has no paths
1944 if is_empty_workspace && !serialized_workspace_has_paths {
1945 if let Some(default_docks) = persistence::read_default_dock_state() {
1946 window
1947 .update(cx, |_, window, cx| {
1948 workspace.update(cx, |workspace, cx| {
1949 for (dock, serialized_dock) in [
1950 (&workspace.right_dock, &default_docks.right),
1951 (&workspace.left_dock, &default_docks.left),
1952 (&workspace.bottom_dock, &default_docks.bottom),
1953 ] {
1954 dock.update(cx, |dock, cx| {
1955 dock.serialized_dock = Some(serialized_dock.clone());
1956 dock.restore_state(window, cx);
1957 });
1958 }
1959 cx.notify();
1960 });
1961 })
1962 .log_err();
1963 }
1964 }
1965
1966 window
1967 .update(cx, |_, _window, cx| {
1968 workspace.update(cx, |this: &mut Workspace, cx| {
1969 this.update_history(cx);
1970 });
1971 })
1972 .log_err();
1973 Ok((window, opened_items))
1974 })
1975 }
1976
1977 pub fn weak_handle(&self) -> WeakEntity<Self> {
1978 self.weak_self.clone()
1979 }
1980
1981 pub fn left_dock(&self) -> &Entity<Dock> {
1982 &self.left_dock
1983 }
1984
1985 pub fn bottom_dock(&self) -> &Entity<Dock> {
1986 &self.bottom_dock
1987 }
1988
1989 pub fn set_bottom_dock_layout(
1990 &mut self,
1991 layout: BottomDockLayout,
1992 window: &mut Window,
1993 cx: &mut Context<Self>,
1994 ) {
1995 let fs = self.project().read(cx).fs();
1996 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
1997 content.workspace.bottom_dock_layout = Some(layout);
1998 });
1999
2000 cx.notify();
2001 self.serialize_workspace(window, cx);
2002 }
2003
2004 pub fn right_dock(&self) -> &Entity<Dock> {
2005 &self.right_dock
2006 }
2007
2008 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2009 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2010 }
2011
2012 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2013 match position {
2014 DockPosition::Left => &self.left_dock,
2015 DockPosition::Bottom => &self.bottom_dock,
2016 DockPosition::Right => &self.right_dock,
2017 }
2018 }
2019
2020 pub fn is_edited(&self) -> bool {
2021 self.window_edited
2022 }
2023
2024 pub fn add_panel<T: Panel>(
2025 &mut self,
2026 panel: Entity<T>,
2027 window: &mut Window,
2028 cx: &mut Context<Self>,
2029 ) {
2030 let focus_handle = panel.panel_focus_handle(cx);
2031 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2032 .detach();
2033
2034 let dock_position = panel.position(window, cx);
2035 let dock = self.dock_at_position(dock_position);
2036
2037 dock.update(cx, |dock, cx| {
2038 dock.add_panel(panel, self.weak_self.clone(), window, cx)
2039 });
2040 }
2041
2042 pub fn remove_panel<T: Panel>(
2043 &mut self,
2044 panel: &Entity<T>,
2045 window: &mut Window,
2046 cx: &mut Context<Self>,
2047 ) {
2048 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2049 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2050 }
2051 }
2052
2053 pub fn status_bar(&self) -> &Entity<StatusBar> {
2054 &self.status_bar
2055 }
2056
2057 pub fn set_workspace_sidebar_open(&self, open: bool, cx: &mut App) {
2058 self.status_bar.update(cx, |status_bar, cx| {
2059 status_bar.set_workspace_sidebar_open(open, cx);
2060 });
2061 }
2062
2063 pub fn status_bar_visible(&self, cx: &App) -> bool {
2064 StatusBarSettings::get_global(cx).show
2065 }
2066
2067 pub fn app_state(&self) -> &Arc<AppState> {
2068 &self.app_state
2069 }
2070
2071 pub fn user_store(&self) -> &Entity<UserStore> {
2072 &self.app_state.user_store
2073 }
2074
2075 pub fn project(&self) -> &Entity<Project> {
2076 &self.project
2077 }
2078
2079 pub fn path_style(&self, cx: &App) -> PathStyle {
2080 self.project.read(cx).path_style(cx)
2081 }
2082
2083 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2084 let mut history: HashMap<EntityId, usize> = HashMap::default();
2085
2086 for pane_handle in &self.panes {
2087 let pane = pane_handle.read(cx);
2088
2089 for entry in pane.activation_history() {
2090 history.insert(
2091 entry.entity_id,
2092 history
2093 .get(&entry.entity_id)
2094 .cloned()
2095 .unwrap_or(0)
2096 .max(entry.timestamp),
2097 );
2098 }
2099 }
2100
2101 history
2102 }
2103
2104 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2105 let mut recent_item: Option<Entity<T>> = None;
2106 let mut recent_timestamp = 0;
2107 for pane_handle in &self.panes {
2108 let pane = pane_handle.read(cx);
2109 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2110 pane.items().map(|item| (item.item_id(), item)).collect();
2111 for entry in pane.activation_history() {
2112 if entry.timestamp > recent_timestamp
2113 && let Some(&item) = item_map.get(&entry.entity_id)
2114 && let Some(typed_item) = item.act_as::<T>(cx)
2115 {
2116 recent_timestamp = entry.timestamp;
2117 recent_item = Some(typed_item);
2118 }
2119 }
2120 }
2121 recent_item
2122 }
2123
2124 pub fn recent_navigation_history_iter(
2125 &self,
2126 cx: &App,
2127 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2128 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2129 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2130
2131 for pane in &self.panes {
2132 let pane = pane.read(cx);
2133
2134 pane.nav_history()
2135 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2136 if let Some(fs_path) = &fs_path {
2137 abs_paths_opened
2138 .entry(fs_path.clone())
2139 .or_default()
2140 .insert(project_path.clone());
2141 }
2142 let timestamp = entry.timestamp;
2143 match history.entry(project_path) {
2144 hash_map::Entry::Occupied(mut entry) => {
2145 let (_, old_timestamp) = entry.get();
2146 if ×tamp > old_timestamp {
2147 entry.insert((fs_path, timestamp));
2148 }
2149 }
2150 hash_map::Entry::Vacant(entry) => {
2151 entry.insert((fs_path, timestamp));
2152 }
2153 }
2154 });
2155
2156 if let Some(item) = pane.active_item()
2157 && let Some(project_path) = item.project_path(cx)
2158 {
2159 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2160
2161 if let Some(fs_path) = &fs_path {
2162 abs_paths_opened
2163 .entry(fs_path.clone())
2164 .or_default()
2165 .insert(project_path.clone());
2166 }
2167
2168 history.insert(project_path, (fs_path, std::usize::MAX));
2169 }
2170 }
2171
2172 history
2173 .into_iter()
2174 .sorted_by_key(|(_, (_, order))| *order)
2175 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2176 .rev()
2177 .filter(move |(history_path, abs_path)| {
2178 let latest_project_path_opened = abs_path
2179 .as_ref()
2180 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2181 .and_then(|project_paths| {
2182 project_paths
2183 .iter()
2184 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2185 });
2186
2187 latest_project_path_opened.is_none_or(|path| path == history_path)
2188 })
2189 }
2190
2191 pub fn recent_navigation_history(
2192 &self,
2193 limit: Option<usize>,
2194 cx: &App,
2195 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2196 self.recent_navigation_history_iter(cx)
2197 .take(limit.unwrap_or(usize::MAX))
2198 .collect()
2199 }
2200
2201 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2202 for pane in &self.panes {
2203 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2204 }
2205 }
2206
2207 fn navigate_history(
2208 &mut self,
2209 pane: WeakEntity<Pane>,
2210 mode: NavigationMode,
2211 window: &mut Window,
2212 cx: &mut Context<Workspace>,
2213 ) -> Task<Result<()>> {
2214 self.navigate_history_impl(
2215 pane,
2216 mode,
2217 window,
2218 &mut |history, cx| history.pop(mode, cx),
2219 cx,
2220 )
2221 }
2222
2223 fn navigate_tag_history(
2224 &mut self,
2225 pane: WeakEntity<Pane>,
2226 mode: TagNavigationMode,
2227 window: &mut Window,
2228 cx: &mut Context<Workspace>,
2229 ) -> Task<Result<()>> {
2230 self.navigate_history_impl(
2231 pane,
2232 NavigationMode::Normal,
2233 window,
2234 &mut |history, _cx| history.pop_tag(mode),
2235 cx,
2236 )
2237 }
2238
2239 fn navigate_history_impl(
2240 &mut self,
2241 pane: WeakEntity<Pane>,
2242 mode: NavigationMode,
2243 window: &mut Window,
2244 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2245 cx: &mut Context<Workspace>,
2246 ) -> Task<Result<()>> {
2247 let to_load = if let Some(pane) = pane.upgrade() {
2248 pane.update(cx, |pane, cx| {
2249 window.focus(&pane.focus_handle(cx), cx);
2250 loop {
2251 // Retrieve the weak item handle from the history.
2252 let entry = cb(pane.nav_history_mut(), cx)?;
2253
2254 // If the item is still present in this pane, then activate it.
2255 if let Some(index) = entry
2256 .item
2257 .upgrade()
2258 .and_then(|v| pane.index_for_item(v.as_ref()))
2259 {
2260 let prev_active_item_index = pane.active_item_index();
2261 pane.nav_history_mut().set_mode(mode);
2262 pane.activate_item(index, true, true, window, cx);
2263 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2264
2265 let mut navigated = prev_active_item_index != pane.active_item_index();
2266 if let Some(data) = entry.data {
2267 navigated |= pane.active_item()?.navigate(data, window, cx);
2268 }
2269
2270 if navigated {
2271 break None;
2272 }
2273 } else {
2274 // If the item is no longer present in this pane, then retrieve its
2275 // path info in order to reopen it.
2276 break pane
2277 .nav_history()
2278 .path_for_item(entry.item.id())
2279 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2280 }
2281 }
2282 })
2283 } else {
2284 None
2285 };
2286
2287 if let Some((project_path, abs_path, entry)) = to_load {
2288 // If the item was no longer present, then load it again from its previous path, first try the local path
2289 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2290
2291 cx.spawn_in(window, async move |workspace, cx| {
2292 let open_by_project_path = open_by_project_path.await;
2293 let mut navigated = false;
2294 match open_by_project_path
2295 .with_context(|| format!("Navigating to {project_path:?}"))
2296 {
2297 Ok((project_entry_id, build_item)) => {
2298 let prev_active_item_id = pane.update(cx, |pane, _| {
2299 pane.nav_history_mut().set_mode(mode);
2300 pane.active_item().map(|p| p.item_id())
2301 })?;
2302
2303 pane.update_in(cx, |pane, window, cx| {
2304 let item = pane.open_item(
2305 project_entry_id,
2306 project_path,
2307 true,
2308 entry.is_preview,
2309 true,
2310 None,
2311 window, cx,
2312 build_item,
2313 );
2314 navigated |= Some(item.item_id()) != prev_active_item_id;
2315 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2316 if let Some(data) = entry.data {
2317 navigated |= item.navigate(data, window, cx);
2318 }
2319 })?;
2320 }
2321 Err(open_by_project_path_e) => {
2322 // Fall back to opening by abs path, in case an external file was opened and closed,
2323 // and its worktree is now dropped
2324 if let Some(abs_path) = abs_path {
2325 let prev_active_item_id = pane.update(cx, |pane, _| {
2326 pane.nav_history_mut().set_mode(mode);
2327 pane.active_item().map(|p| p.item_id())
2328 })?;
2329 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2330 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2331 })?;
2332 match open_by_abs_path
2333 .await
2334 .with_context(|| format!("Navigating to {abs_path:?}"))
2335 {
2336 Ok(item) => {
2337 pane.update_in(cx, |pane, window, cx| {
2338 navigated |= Some(item.item_id()) != prev_active_item_id;
2339 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2340 if let Some(data) = entry.data {
2341 navigated |= item.navigate(data, window, cx);
2342 }
2343 })?;
2344 }
2345 Err(open_by_abs_path_e) => {
2346 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2347 }
2348 }
2349 }
2350 }
2351 }
2352
2353 if !navigated {
2354 workspace
2355 .update_in(cx, |workspace, window, cx| {
2356 Self::navigate_history(workspace, pane, mode, window, cx)
2357 })?
2358 .await?;
2359 }
2360
2361 Ok(())
2362 })
2363 } else {
2364 Task::ready(Ok(()))
2365 }
2366 }
2367
2368 pub fn go_back(
2369 &mut self,
2370 pane: WeakEntity<Pane>,
2371 window: &mut Window,
2372 cx: &mut Context<Workspace>,
2373 ) -> Task<Result<()>> {
2374 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2375 }
2376
2377 pub fn go_forward(
2378 &mut self,
2379 pane: WeakEntity<Pane>,
2380 window: &mut Window,
2381 cx: &mut Context<Workspace>,
2382 ) -> Task<Result<()>> {
2383 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2384 }
2385
2386 pub fn reopen_closed_item(
2387 &mut self,
2388 window: &mut Window,
2389 cx: &mut Context<Workspace>,
2390 ) -> Task<Result<()>> {
2391 self.navigate_history(
2392 self.active_pane().downgrade(),
2393 NavigationMode::ReopeningClosedItem,
2394 window,
2395 cx,
2396 )
2397 }
2398
2399 pub fn client(&self) -> &Arc<Client> {
2400 &self.app_state.client
2401 }
2402
2403 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2404 self.titlebar_item = Some(item);
2405 cx.notify();
2406 }
2407
2408 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2409 self.on_prompt_for_new_path = Some(prompt)
2410 }
2411
2412 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2413 self.on_prompt_for_open_path = Some(prompt)
2414 }
2415
2416 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2417 self.terminal_provider = Some(Box::new(provider));
2418 }
2419
2420 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2421 self.debugger_provider = Some(Arc::new(provider));
2422 }
2423
2424 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2425 self.debugger_provider.clone()
2426 }
2427
2428 pub fn prompt_for_open_path(
2429 &mut self,
2430 path_prompt_options: PathPromptOptions,
2431 lister: DirectoryLister,
2432 window: &mut Window,
2433 cx: &mut Context<Self>,
2434 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2435 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2436 let prompt = self.on_prompt_for_open_path.take().unwrap();
2437 let rx = prompt(self, lister, window, cx);
2438 self.on_prompt_for_open_path = Some(prompt);
2439 rx
2440 } else {
2441 let (tx, rx) = oneshot::channel();
2442 let abs_path = cx.prompt_for_paths(path_prompt_options);
2443
2444 cx.spawn_in(window, async move |workspace, cx| {
2445 let Ok(result) = abs_path.await else {
2446 return Ok(());
2447 };
2448
2449 match result {
2450 Ok(result) => {
2451 tx.send(result).ok();
2452 }
2453 Err(err) => {
2454 let rx = workspace.update_in(cx, |workspace, window, cx| {
2455 workspace.show_portal_error(err.to_string(), cx);
2456 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2457 let rx = prompt(workspace, lister, window, cx);
2458 workspace.on_prompt_for_open_path = Some(prompt);
2459 rx
2460 })?;
2461 if let Ok(path) = rx.await {
2462 tx.send(path).ok();
2463 }
2464 }
2465 };
2466 anyhow::Ok(())
2467 })
2468 .detach();
2469
2470 rx
2471 }
2472 }
2473
2474 pub fn prompt_for_new_path(
2475 &mut self,
2476 lister: DirectoryLister,
2477 suggested_name: Option<String>,
2478 window: &mut Window,
2479 cx: &mut Context<Self>,
2480 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2481 if self.project.read(cx).is_via_collab()
2482 || self.project.read(cx).is_via_remote_server()
2483 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2484 {
2485 let prompt = self.on_prompt_for_new_path.take().unwrap();
2486 let rx = prompt(self, lister, suggested_name, window, cx);
2487 self.on_prompt_for_new_path = Some(prompt);
2488 return rx;
2489 }
2490
2491 let (tx, rx) = oneshot::channel();
2492 cx.spawn_in(window, async move |workspace, cx| {
2493 let abs_path = workspace.update(cx, |workspace, cx| {
2494 let relative_to = workspace
2495 .most_recent_active_path(cx)
2496 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2497 .or_else(|| {
2498 let project = workspace.project.read(cx);
2499 project.visible_worktrees(cx).find_map(|worktree| {
2500 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2501 })
2502 })
2503 .or_else(std::env::home_dir)
2504 .unwrap_or_else(|| PathBuf::from(""));
2505 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2506 })?;
2507 let abs_path = match abs_path.await? {
2508 Ok(path) => path,
2509 Err(err) => {
2510 let rx = workspace.update_in(cx, |workspace, window, cx| {
2511 workspace.show_portal_error(err.to_string(), cx);
2512
2513 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2514 let rx = prompt(workspace, lister, suggested_name, window, cx);
2515 workspace.on_prompt_for_new_path = Some(prompt);
2516 rx
2517 })?;
2518 if let Ok(path) = rx.await {
2519 tx.send(path).ok();
2520 }
2521 return anyhow::Ok(());
2522 }
2523 };
2524
2525 tx.send(abs_path.map(|path| vec![path])).ok();
2526 anyhow::Ok(())
2527 })
2528 .detach();
2529
2530 rx
2531 }
2532
2533 pub fn titlebar_item(&self) -> Option<AnyView> {
2534 self.titlebar_item.clone()
2535 }
2536
2537 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2538 /// When set, git-related operations should use this worktree instead of deriving
2539 /// the active worktree from the focused file.
2540 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2541 self.active_worktree_override
2542 }
2543
2544 pub fn set_active_worktree_override(
2545 &mut self,
2546 worktree_id: Option<WorktreeId>,
2547 cx: &mut Context<Self>,
2548 ) {
2549 self.active_worktree_override = worktree_id;
2550 cx.notify();
2551 }
2552
2553 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2554 self.active_worktree_override = None;
2555 cx.notify();
2556 }
2557
2558 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2559 ///
2560 /// If the given workspace has a local project, then it will be passed
2561 /// to the callback. Otherwise, a new empty window will be created.
2562 pub fn with_local_workspace<T, F>(
2563 &mut self,
2564 window: &mut Window,
2565 cx: &mut Context<Self>,
2566 callback: F,
2567 ) -> Task<Result<T>>
2568 where
2569 T: 'static,
2570 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2571 {
2572 if self.project.read(cx).is_local() {
2573 Task::ready(Ok(callback(self, window, cx)))
2574 } else {
2575 let env = self.project.read(cx).cli_environment(cx);
2576 let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, None, cx);
2577 cx.spawn_in(window, async move |_vh, cx| {
2578 let (multi_workspace_window, _) = task.await?;
2579 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2580 let workspace = multi_workspace.workspace().clone();
2581 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2582 })
2583 })
2584 }
2585 }
2586
2587 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2588 ///
2589 /// If the given workspace has a local project, then it will be passed
2590 /// to the callback. Otherwise, a new empty window will be created.
2591 pub fn with_local_or_wsl_workspace<T, F>(
2592 &mut self,
2593 window: &mut Window,
2594 cx: &mut Context<Self>,
2595 callback: F,
2596 ) -> Task<Result<T>>
2597 where
2598 T: 'static,
2599 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2600 {
2601 let project = self.project.read(cx);
2602 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
2603 Task::ready(Ok(callback(self, window, cx)))
2604 } else {
2605 let env = self.project.read(cx).cli_environment(cx);
2606 let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, None, cx);
2607 cx.spawn_in(window, async move |_vh, cx| {
2608 let (multi_workspace_window, _) = task.await?;
2609 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2610 let workspace = multi_workspace.workspace().clone();
2611 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2612 })
2613 })
2614 }
2615 }
2616
2617 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2618 self.project.read(cx).worktrees(cx)
2619 }
2620
2621 pub fn visible_worktrees<'a>(
2622 &self,
2623 cx: &'a App,
2624 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2625 self.project.read(cx).visible_worktrees(cx)
2626 }
2627
2628 #[cfg(any(test, feature = "test-support"))]
2629 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
2630 let futures = self
2631 .worktrees(cx)
2632 .filter_map(|worktree| worktree.read(cx).as_local())
2633 .map(|worktree| worktree.scan_complete())
2634 .collect::<Vec<_>>();
2635 async move {
2636 for future in futures {
2637 future.await;
2638 }
2639 }
2640 }
2641
2642 pub fn close_global(cx: &mut App) {
2643 cx.defer(|cx| {
2644 cx.windows().iter().find(|window| {
2645 window
2646 .update(cx, |_, window, _| {
2647 if window.is_window_active() {
2648 //This can only get called when the window's project connection has been lost
2649 //so we don't need to prompt the user for anything and instead just close the window
2650 window.remove_window();
2651 true
2652 } else {
2653 false
2654 }
2655 })
2656 .unwrap_or(false)
2657 });
2658 });
2659 }
2660
2661 pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
2662 let prepare = self.prepare_to_close(CloseIntent::CloseWindow, window, cx);
2663 cx.spawn_in(window, async move |_, cx| {
2664 if prepare.await? {
2665 cx.update(|window, _cx| window.remove_window())?;
2666 }
2667 anyhow::Ok(())
2668 })
2669 .detach_and_log_err(cx)
2670 }
2671
2672 pub fn move_focused_panel_to_next_position(
2673 &mut self,
2674 _: &MoveFocusedPanelToNextPosition,
2675 window: &mut Window,
2676 cx: &mut Context<Self>,
2677 ) {
2678 let docks = self.all_docks();
2679 let active_dock = docks
2680 .into_iter()
2681 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
2682
2683 if let Some(dock) = active_dock {
2684 dock.update(cx, |dock, cx| {
2685 let active_panel = dock
2686 .active_panel()
2687 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
2688
2689 if let Some(panel) = active_panel {
2690 panel.move_to_next_position(window, cx);
2691 }
2692 })
2693 }
2694 }
2695
2696 pub fn prepare_to_close(
2697 &mut self,
2698 close_intent: CloseIntent,
2699 window: &mut Window,
2700 cx: &mut Context<Self>,
2701 ) -> Task<Result<bool>> {
2702 let active_call = self.active_global_call();
2703
2704 cx.spawn_in(window, async move |this, cx| {
2705 this.update(cx, |this, _| {
2706 if close_intent == CloseIntent::CloseWindow {
2707 this.removing = true;
2708 }
2709 })?;
2710
2711 let workspace_count = cx.update(|_window, cx| {
2712 cx.windows()
2713 .iter()
2714 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
2715 .count()
2716 })?;
2717
2718 #[cfg(target_os = "macos")]
2719 let save_last_workspace = false;
2720
2721 // On Linux and Windows, closing the last window should restore the last workspace.
2722 #[cfg(not(target_os = "macos"))]
2723 let save_last_workspace = {
2724 let remaining_workspaces = cx.update(|_window, cx| {
2725 cx.windows()
2726 .iter()
2727 .filter_map(|window| window.downcast::<MultiWorkspace>())
2728 .filter_map(|multi_workspace| {
2729 multi_workspace
2730 .update(cx, |multi_workspace, _, cx| {
2731 multi_workspace.workspace().read(cx).removing
2732 })
2733 .ok()
2734 })
2735 .filter(|removing| !removing)
2736 .count()
2737 })?;
2738
2739 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
2740 };
2741
2742 if let Some(active_call) = active_call
2743 && workspace_count == 1
2744 && cx
2745 .update(|_window, cx| active_call.0.is_in_room(cx))
2746 .unwrap_or(false)
2747 {
2748 if close_intent == CloseIntent::CloseWindow {
2749 let answer = cx.update(|window, cx| {
2750 window.prompt(
2751 PromptLevel::Warning,
2752 "Do you want to leave the current call?",
2753 None,
2754 &["Close window and hang up", "Cancel"],
2755 cx,
2756 )
2757 })?;
2758
2759 if answer.await.log_err() == Some(1) {
2760 return anyhow::Ok(false);
2761 } else {
2762 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
2763 task.await.log_err();
2764 }
2765 }
2766 }
2767 if close_intent == CloseIntent::ReplaceWindow {
2768 _ = cx.update(|_window, cx| {
2769 let multi_workspace = cx
2770 .windows()
2771 .iter()
2772 .filter_map(|window| window.downcast::<MultiWorkspace>())
2773 .next()
2774 .unwrap();
2775 let project = multi_workspace
2776 .read(cx)?
2777 .workspace()
2778 .read(cx)
2779 .project
2780 .clone();
2781 if project.read(cx).is_shared() {
2782 active_call.0.unshare_project(project, cx)?;
2783 }
2784 Ok::<_, anyhow::Error>(())
2785 });
2786 }
2787 }
2788
2789 let save_result = this
2790 .update_in(cx, |this, window, cx| {
2791 this.save_all_internal(SaveIntent::Close, window, cx)
2792 })?
2793 .await;
2794
2795 // If we're not quitting, but closing, we remove the workspace from
2796 // the current session.
2797 if close_intent != CloseIntent::Quit
2798 && !save_last_workspace
2799 && save_result.as_ref().is_ok_and(|&res| res)
2800 {
2801 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
2802 .await;
2803 }
2804
2805 save_result
2806 })
2807 }
2808
2809 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
2810 self.save_all_internal(
2811 action.save_intent.unwrap_or(SaveIntent::SaveAll),
2812 window,
2813 cx,
2814 )
2815 .detach_and_log_err(cx);
2816 }
2817
2818 fn send_keystrokes(
2819 &mut self,
2820 action: &SendKeystrokes,
2821 window: &mut Window,
2822 cx: &mut Context<Self>,
2823 ) {
2824 let keystrokes: Vec<Keystroke> = action
2825 .0
2826 .split(' ')
2827 .flat_map(|k| Keystroke::parse(k).log_err())
2828 .map(|k| {
2829 cx.keyboard_mapper()
2830 .map_key_equivalent(k, false)
2831 .inner()
2832 .clone()
2833 })
2834 .collect();
2835 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
2836 }
2837
2838 pub fn send_keystrokes_impl(
2839 &mut self,
2840 keystrokes: Vec<Keystroke>,
2841 window: &mut Window,
2842 cx: &mut Context<Self>,
2843 ) -> Shared<Task<()>> {
2844 let mut state = self.dispatching_keystrokes.borrow_mut();
2845 if !state.dispatched.insert(keystrokes.clone()) {
2846 cx.propagate();
2847 return state.task.clone().unwrap();
2848 }
2849
2850 state.queue.extend(keystrokes);
2851
2852 let keystrokes = self.dispatching_keystrokes.clone();
2853 if state.task.is_none() {
2854 state.task = Some(
2855 window
2856 .spawn(cx, async move |cx| {
2857 // limit to 100 keystrokes to avoid infinite recursion.
2858 for _ in 0..100 {
2859 let mut state = keystrokes.borrow_mut();
2860 let Some(keystroke) = state.queue.pop_front() else {
2861 state.dispatched.clear();
2862 state.task.take();
2863 return;
2864 };
2865 drop(state);
2866 cx.update(|window, cx| {
2867 let focused = window.focused(cx);
2868 window.dispatch_keystroke(keystroke.clone(), cx);
2869 if window.focused(cx) != focused {
2870 // dispatch_keystroke may cause the focus to change.
2871 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
2872 // And we need that to happen before the next keystroke to keep vim mode happy...
2873 // (Note that the tests always do this implicitly, so you must manually test with something like:
2874 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
2875 // )
2876 window.draw(cx).clear();
2877 }
2878 })
2879 .ok();
2880 }
2881
2882 *keystrokes.borrow_mut() = Default::default();
2883 log::error!("over 100 keystrokes passed to send_keystrokes");
2884 })
2885 .shared(),
2886 );
2887 }
2888 state.task.clone().unwrap()
2889 }
2890
2891 fn save_all_internal(
2892 &mut self,
2893 mut save_intent: SaveIntent,
2894 window: &mut Window,
2895 cx: &mut Context<Self>,
2896 ) -> Task<Result<bool>> {
2897 if self.project.read(cx).is_disconnected(cx) {
2898 return Task::ready(Ok(true));
2899 }
2900 let dirty_items = self
2901 .panes
2902 .iter()
2903 .flat_map(|pane| {
2904 pane.read(cx).items().filter_map(|item| {
2905 if item.is_dirty(cx) {
2906 item.tab_content_text(0, cx);
2907 Some((pane.downgrade(), item.boxed_clone()))
2908 } else {
2909 None
2910 }
2911 })
2912 })
2913 .collect::<Vec<_>>();
2914
2915 let project = self.project.clone();
2916 cx.spawn_in(window, async move |workspace, cx| {
2917 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
2918 let (serialize_tasks, remaining_dirty_items) =
2919 workspace.update_in(cx, |workspace, window, cx| {
2920 let mut remaining_dirty_items = Vec::new();
2921 let mut serialize_tasks = Vec::new();
2922 for (pane, item) in dirty_items {
2923 if let Some(task) = item
2924 .to_serializable_item_handle(cx)
2925 .and_then(|handle| handle.serialize(workspace, true, window, cx))
2926 {
2927 serialize_tasks.push(task);
2928 } else {
2929 remaining_dirty_items.push((pane, item));
2930 }
2931 }
2932 (serialize_tasks, remaining_dirty_items)
2933 })?;
2934
2935 futures::future::try_join_all(serialize_tasks).await?;
2936
2937 if remaining_dirty_items.len() > 1 {
2938 let answer = workspace.update_in(cx, |_, window, cx| {
2939 let detail = Pane::file_names_for_prompt(
2940 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
2941 cx,
2942 );
2943 window.prompt(
2944 PromptLevel::Warning,
2945 "Do you want to save all changes in the following files?",
2946 Some(&detail),
2947 &["Save all", "Discard all", "Cancel"],
2948 cx,
2949 )
2950 })?;
2951 match answer.await.log_err() {
2952 Some(0) => save_intent = SaveIntent::SaveAll,
2953 Some(1) => save_intent = SaveIntent::Skip,
2954 Some(2) => return Ok(false),
2955 _ => {}
2956 }
2957 }
2958
2959 remaining_dirty_items
2960 } else {
2961 dirty_items
2962 };
2963
2964 for (pane, item) in dirty_items {
2965 let (singleton, project_entry_ids) = cx.update(|_, cx| {
2966 (
2967 item.buffer_kind(cx) == ItemBufferKind::Singleton,
2968 item.project_entry_ids(cx),
2969 )
2970 })?;
2971 if (singleton || !project_entry_ids.is_empty())
2972 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
2973 {
2974 return Ok(false);
2975 }
2976 }
2977 Ok(true)
2978 })
2979 }
2980
2981 pub fn open_workspace_for_paths(
2982 &mut self,
2983 replace_current_window: bool,
2984 paths: Vec<PathBuf>,
2985 window: &mut Window,
2986 cx: &mut Context<Self>,
2987 ) -> Task<Result<()>> {
2988 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
2989 let is_remote = self.project.read(cx).is_via_collab();
2990 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
2991 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
2992
2993 let window_to_replace = if replace_current_window {
2994 window_handle
2995 } else if is_remote || has_worktree || has_dirty_items {
2996 None
2997 } else {
2998 window_handle
2999 };
3000 let app_state = self.app_state.clone();
3001
3002 cx.spawn(async move |_, cx| {
3003 cx.update(|cx| {
3004 open_paths(
3005 &paths,
3006 app_state,
3007 OpenOptions {
3008 replace_window: window_to_replace,
3009 ..Default::default()
3010 },
3011 cx,
3012 )
3013 })
3014 .await?;
3015 Ok(())
3016 })
3017 }
3018
3019 #[allow(clippy::type_complexity)]
3020 pub fn open_paths(
3021 &mut self,
3022 mut abs_paths: Vec<PathBuf>,
3023 options: OpenOptions,
3024 pane: Option<WeakEntity<Pane>>,
3025 window: &mut Window,
3026 cx: &mut Context<Self>,
3027 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3028 let fs = self.app_state.fs.clone();
3029
3030 let caller_ordered_abs_paths = abs_paths.clone();
3031
3032 // Sort the paths to ensure we add worktrees for parents before their children.
3033 abs_paths.sort_unstable();
3034 cx.spawn_in(window, async move |this, cx| {
3035 let mut tasks = Vec::with_capacity(abs_paths.len());
3036
3037 for abs_path in &abs_paths {
3038 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3039 OpenVisible::All => Some(true),
3040 OpenVisible::None => Some(false),
3041 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3042 Some(Some(metadata)) => Some(!metadata.is_dir),
3043 Some(None) => Some(true),
3044 None => None,
3045 },
3046 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3047 Some(Some(metadata)) => Some(metadata.is_dir),
3048 Some(None) => Some(false),
3049 None => None,
3050 },
3051 };
3052 let project_path = match visible {
3053 Some(visible) => match this
3054 .update(cx, |this, cx| {
3055 Workspace::project_path_for_path(
3056 this.project.clone(),
3057 abs_path,
3058 visible,
3059 cx,
3060 )
3061 })
3062 .log_err()
3063 {
3064 Some(project_path) => project_path.await.log_err(),
3065 None => None,
3066 },
3067 None => None,
3068 };
3069
3070 let this = this.clone();
3071 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3072 let fs = fs.clone();
3073 let pane = pane.clone();
3074 let task = cx.spawn(async move |cx| {
3075 let (_worktree, project_path) = project_path?;
3076 if fs.is_dir(&abs_path).await {
3077 // Opening a directory should not race to update the active entry.
3078 // We'll select/reveal a deterministic final entry after all paths finish opening.
3079 None
3080 } else {
3081 Some(
3082 this.update_in(cx, |this, window, cx| {
3083 this.open_path(
3084 project_path,
3085 pane,
3086 options.focus.unwrap_or(true),
3087 window,
3088 cx,
3089 )
3090 })
3091 .ok()?
3092 .await,
3093 )
3094 }
3095 });
3096 tasks.push(task);
3097 }
3098
3099 let results = futures::future::join_all(tasks).await;
3100
3101 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3102 let mut winner: Option<(PathBuf, bool)> = None;
3103 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3104 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3105 if !metadata.is_dir {
3106 winner = Some((abs_path, false));
3107 break;
3108 }
3109 if winner.is_none() {
3110 winner = Some((abs_path, true));
3111 }
3112 } else if winner.is_none() {
3113 winner = Some((abs_path, false));
3114 }
3115 }
3116
3117 // Compute the winner entry id on the foreground thread and emit once, after all
3118 // paths finish opening. This avoids races between concurrently-opening paths
3119 // (directories in particular) and makes the resulting project panel selection
3120 // deterministic.
3121 if let Some((winner_abs_path, winner_is_dir)) = winner {
3122 'emit_winner: {
3123 let winner_abs_path: Arc<Path> =
3124 SanitizedPath::new(&winner_abs_path).as_path().into();
3125
3126 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3127 OpenVisible::All => true,
3128 OpenVisible::None => false,
3129 OpenVisible::OnlyFiles => !winner_is_dir,
3130 OpenVisible::OnlyDirectories => winner_is_dir,
3131 };
3132
3133 let Some(worktree_task) = this
3134 .update(cx, |workspace, cx| {
3135 workspace.project.update(cx, |project, cx| {
3136 project.find_or_create_worktree(
3137 winner_abs_path.as_ref(),
3138 visible,
3139 cx,
3140 )
3141 })
3142 })
3143 .ok()
3144 else {
3145 break 'emit_winner;
3146 };
3147
3148 let Ok((worktree, _)) = worktree_task.await else {
3149 break 'emit_winner;
3150 };
3151
3152 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3153 let worktree = worktree.read(cx);
3154 let worktree_abs_path = worktree.abs_path();
3155 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3156 worktree.root_entry()
3157 } else {
3158 winner_abs_path
3159 .strip_prefix(worktree_abs_path.as_ref())
3160 .ok()
3161 .and_then(|relative_path| {
3162 let relative_path =
3163 RelPath::new(relative_path, PathStyle::local())
3164 .log_err()?;
3165 worktree.entry_for_path(&relative_path)
3166 })
3167 }?;
3168 Some(entry.id)
3169 }) else {
3170 break 'emit_winner;
3171 };
3172
3173 this.update(cx, |workspace, cx| {
3174 workspace.project.update(cx, |_, cx| {
3175 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3176 });
3177 })
3178 .ok();
3179 }
3180 }
3181
3182 results
3183 })
3184 }
3185
3186 pub fn open_resolved_path(
3187 &mut self,
3188 path: ResolvedPath,
3189 window: &mut Window,
3190 cx: &mut Context<Self>,
3191 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3192 match path {
3193 ResolvedPath::ProjectPath { project_path, .. } => {
3194 self.open_path(project_path, None, true, window, cx)
3195 }
3196 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3197 PathBuf::from(path),
3198 OpenOptions {
3199 visible: Some(OpenVisible::None),
3200 ..Default::default()
3201 },
3202 window,
3203 cx,
3204 ),
3205 }
3206 }
3207
3208 pub fn absolute_path_of_worktree(
3209 &self,
3210 worktree_id: WorktreeId,
3211 cx: &mut Context<Self>,
3212 ) -> Option<PathBuf> {
3213 self.project
3214 .read(cx)
3215 .worktree_for_id(worktree_id, cx)
3216 // TODO: use `abs_path` or `root_dir`
3217 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3218 }
3219
3220 fn add_folder_to_project(
3221 &mut self,
3222 _: &AddFolderToProject,
3223 window: &mut Window,
3224 cx: &mut Context<Self>,
3225 ) {
3226 let project = self.project.read(cx);
3227 if project.is_via_collab() {
3228 self.show_error(
3229 &anyhow!("You cannot add folders to someone else's project"),
3230 cx,
3231 );
3232 return;
3233 }
3234 let paths = self.prompt_for_open_path(
3235 PathPromptOptions {
3236 files: false,
3237 directories: true,
3238 multiple: true,
3239 prompt: None,
3240 },
3241 DirectoryLister::Project(self.project.clone()),
3242 window,
3243 cx,
3244 );
3245 cx.spawn_in(window, async move |this, cx| {
3246 if let Some(paths) = paths.await.log_err().flatten() {
3247 let results = this
3248 .update_in(cx, |this, window, cx| {
3249 this.open_paths(
3250 paths,
3251 OpenOptions {
3252 visible: Some(OpenVisible::All),
3253 ..Default::default()
3254 },
3255 None,
3256 window,
3257 cx,
3258 )
3259 })?
3260 .await;
3261 for result in results.into_iter().flatten() {
3262 result.log_err();
3263 }
3264 }
3265 anyhow::Ok(())
3266 })
3267 .detach_and_log_err(cx);
3268 }
3269
3270 pub fn project_path_for_path(
3271 project: Entity<Project>,
3272 abs_path: &Path,
3273 visible: bool,
3274 cx: &mut App,
3275 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3276 let entry = project.update(cx, |project, cx| {
3277 project.find_or_create_worktree(abs_path, visible, cx)
3278 });
3279 cx.spawn(async move |cx| {
3280 let (worktree, path) = entry.await?;
3281 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3282 Ok((worktree, ProjectPath { worktree_id, path }))
3283 })
3284 }
3285
3286 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3287 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3288 }
3289
3290 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3291 self.items_of_type(cx).max_by_key(|item| item.item_id())
3292 }
3293
3294 pub fn items_of_type<'a, T: Item>(
3295 &'a self,
3296 cx: &'a App,
3297 ) -> impl 'a + Iterator<Item = Entity<T>> {
3298 self.panes
3299 .iter()
3300 .flat_map(|pane| pane.read(cx).items_of_type())
3301 }
3302
3303 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3304 self.active_pane().read(cx).active_item()
3305 }
3306
3307 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3308 let item = self.active_item(cx)?;
3309 item.to_any_view().downcast::<I>().ok()
3310 }
3311
3312 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3313 self.active_item(cx).and_then(|item| item.project_path(cx))
3314 }
3315
3316 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3317 self.recent_navigation_history_iter(cx)
3318 .filter_map(|(path, abs_path)| {
3319 let worktree = self
3320 .project
3321 .read(cx)
3322 .worktree_for_id(path.worktree_id, cx)?;
3323 if worktree.read(cx).is_visible() {
3324 abs_path
3325 } else {
3326 None
3327 }
3328 })
3329 .next()
3330 }
3331
3332 pub fn save_active_item(
3333 &mut self,
3334 save_intent: SaveIntent,
3335 window: &mut Window,
3336 cx: &mut App,
3337 ) -> Task<Result<()>> {
3338 let project = self.project.clone();
3339 let pane = self.active_pane();
3340 let item = pane.read(cx).active_item();
3341 let pane = pane.downgrade();
3342
3343 window.spawn(cx, async move |cx| {
3344 if let Some(item) = item {
3345 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3346 .await
3347 .map(|_| ())
3348 } else {
3349 Ok(())
3350 }
3351 })
3352 }
3353
3354 pub fn close_inactive_items_and_panes(
3355 &mut self,
3356 action: &CloseInactiveTabsAndPanes,
3357 window: &mut Window,
3358 cx: &mut Context<Self>,
3359 ) {
3360 if let Some(task) = self.close_all_internal(
3361 true,
3362 action.save_intent.unwrap_or(SaveIntent::Close),
3363 window,
3364 cx,
3365 ) {
3366 task.detach_and_log_err(cx)
3367 }
3368 }
3369
3370 pub fn close_all_items_and_panes(
3371 &mut self,
3372 action: &CloseAllItemsAndPanes,
3373 window: &mut Window,
3374 cx: &mut Context<Self>,
3375 ) {
3376 if let Some(task) = self.close_all_internal(
3377 false,
3378 action.save_intent.unwrap_or(SaveIntent::Close),
3379 window,
3380 cx,
3381 ) {
3382 task.detach_and_log_err(cx)
3383 }
3384 }
3385
3386 /// Closes the active item across all panes.
3387 pub fn close_item_in_all_panes(
3388 &mut self,
3389 action: &CloseItemInAllPanes,
3390 window: &mut Window,
3391 cx: &mut Context<Self>,
3392 ) {
3393 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3394 return;
3395 };
3396
3397 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3398 let close_pinned = action.close_pinned;
3399
3400 if let Some(project_path) = active_item.project_path(cx) {
3401 self.close_items_with_project_path(
3402 &project_path,
3403 save_intent,
3404 close_pinned,
3405 window,
3406 cx,
3407 );
3408 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3409 let item_id = active_item.item_id();
3410 self.active_pane().update(cx, |pane, cx| {
3411 pane.close_item_by_id(item_id, save_intent, window, cx)
3412 .detach_and_log_err(cx);
3413 });
3414 }
3415 }
3416
3417 /// Closes all items with the given project path across all panes.
3418 pub fn close_items_with_project_path(
3419 &mut self,
3420 project_path: &ProjectPath,
3421 save_intent: SaveIntent,
3422 close_pinned: bool,
3423 window: &mut Window,
3424 cx: &mut Context<Self>,
3425 ) {
3426 let panes = self.panes().to_vec();
3427 for pane in panes {
3428 pane.update(cx, |pane, cx| {
3429 pane.close_items_for_project_path(
3430 project_path,
3431 save_intent,
3432 close_pinned,
3433 window,
3434 cx,
3435 )
3436 .detach_and_log_err(cx);
3437 });
3438 }
3439 }
3440
3441 fn close_all_internal(
3442 &mut self,
3443 retain_active_pane: bool,
3444 save_intent: SaveIntent,
3445 window: &mut Window,
3446 cx: &mut Context<Self>,
3447 ) -> Option<Task<Result<()>>> {
3448 let current_pane = self.active_pane();
3449
3450 let mut tasks = Vec::new();
3451
3452 if retain_active_pane {
3453 let current_pane_close = current_pane.update(cx, |pane, cx| {
3454 pane.close_other_items(
3455 &CloseOtherItems {
3456 save_intent: None,
3457 close_pinned: false,
3458 },
3459 None,
3460 window,
3461 cx,
3462 )
3463 });
3464
3465 tasks.push(current_pane_close);
3466 }
3467
3468 for pane in self.panes() {
3469 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3470 continue;
3471 }
3472
3473 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3474 pane.close_all_items(
3475 &CloseAllItems {
3476 save_intent: Some(save_intent),
3477 close_pinned: false,
3478 },
3479 window,
3480 cx,
3481 )
3482 });
3483
3484 tasks.push(close_pane_items)
3485 }
3486
3487 if tasks.is_empty() {
3488 None
3489 } else {
3490 Some(cx.spawn_in(window, async move |_, _| {
3491 for task in tasks {
3492 task.await?
3493 }
3494 Ok(())
3495 }))
3496 }
3497 }
3498
3499 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3500 self.dock_at_position(position).read(cx).is_open()
3501 }
3502
3503 pub fn toggle_dock(
3504 &mut self,
3505 dock_side: DockPosition,
3506 window: &mut Window,
3507 cx: &mut Context<Self>,
3508 ) {
3509 let mut focus_center = false;
3510 let mut reveal_dock = false;
3511
3512 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3513 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3514
3515 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3516 telemetry::event!(
3517 "Panel Button Clicked",
3518 name = panel.persistent_name(),
3519 toggle_state = !was_visible
3520 );
3521 }
3522 if was_visible {
3523 self.save_open_dock_positions(cx);
3524 }
3525
3526 let dock = self.dock_at_position(dock_side);
3527 dock.update(cx, |dock, cx| {
3528 dock.set_open(!was_visible, window, cx);
3529
3530 if dock.active_panel().is_none() {
3531 let Some(panel_ix) = dock
3532 .first_enabled_panel_idx(cx)
3533 .log_with_level(log::Level::Info)
3534 else {
3535 return;
3536 };
3537 dock.activate_panel(panel_ix, window, cx);
3538 }
3539
3540 if let Some(active_panel) = dock.active_panel() {
3541 if was_visible {
3542 if active_panel
3543 .panel_focus_handle(cx)
3544 .contains_focused(window, cx)
3545 {
3546 focus_center = true;
3547 }
3548 } else {
3549 let focus_handle = &active_panel.panel_focus_handle(cx);
3550 window.focus(focus_handle, cx);
3551 reveal_dock = true;
3552 }
3553 }
3554 });
3555
3556 if reveal_dock {
3557 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3558 }
3559
3560 if focus_center {
3561 self.active_pane
3562 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3563 }
3564
3565 cx.notify();
3566 self.serialize_workspace(window, cx);
3567 }
3568
3569 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3570 self.all_docks().into_iter().find(|&dock| {
3571 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3572 })
3573 }
3574
3575 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3576 if let Some(dock) = self.active_dock(window, cx).cloned() {
3577 self.save_open_dock_positions(cx);
3578 dock.update(cx, |dock, cx| {
3579 dock.set_open(false, window, cx);
3580 });
3581 return true;
3582 }
3583 false
3584 }
3585
3586 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3587 self.save_open_dock_positions(cx);
3588 for dock in self.all_docks() {
3589 dock.update(cx, |dock, cx| {
3590 dock.set_open(false, window, cx);
3591 });
3592 }
3593
3594 cx.focus_self(window);
3595 cx.notify();
3596 self.serialize_workspace(window, cx);
3597 }
3598
3599 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
3600 self.all_docks()
3601 .into_iter()
3602 .filter_map(|dock| {
3603 let dock_ref = dock.read(cx);
3604 if dock_ref.is_open() {
3605 Some(dock_ref.position())
3606 } else {
3607 None
3608 }
3609 })
3610 .collect()
3611 }
3612
3613 /// Saves the positions of currently open docks.
3614 ///
3615 /// Updates `last_open_dock_positions` with positions of all currently open
3616 /// docks, to later be restored by the 'Toggle All Docks' action.
3617 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
3618 let open_dock_positions = self.get_open_dock_positions(cx);
3619 if !open_dock_positions.is_empty() {
3620 self.last_open_dock_positions = open_dock_positions;
3621 }
3622 }
3623
3624 /// Toggles all docks between open and closed states.
3625 ///
3626 /// If any docks are open, closes all and remembers their positions. If all
3627 /// docks are closed, restores the last remembered dock configuration.
3628 fn toggle_all_docks(
3629 &mut self,
3630 _: &ToggleAllDocks,
3631 window: &mut Window,
3632 cx: &mut Context<Self>,
3633 ) {
3634 let open_dock_positions = self.get_open_dock_positions(cx);
3635
3636 if !open_dock_positions.is_empty() {
3637 self.close_all_docks(window, cx);
3638 } else if !self.last_open_dock_positions.is_empty() {
3639 self.restore_last_open_docks(window, cx);
3640 }
3641 }
3642
3643 /// Reopens docks from the most recently remembered configuration.
3644 ///
3645 /// Opens all docks whose positions are stored in `last_open_dock_positions`
3646 /// and clears the stored positions.
3647 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3648 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
3649
3650 for position in positions_to_open {
3651 let dock = self.dock_at_position(position);
3652 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
3653 }
3654
3655 cx.focus_self(window);
3656 cx.notify();
3657 self.serialize_workspace(window, cx);
3658 }
3659
3660 /// Transfer focus to the panel of the given type.
3661 pub fn focus_panel<T: Panel>(
3662 &mut self,
3663 window: &mut Window,
3664 cx: &mut Context<Self>,
3665 ) -> Option<Entity<T>> {
3666 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
3667 panel.to_any().downcast().ok()
3668 }
3669
3670 /// Focus the panel of the given type if it isn't already focused. If it is
3671 /// already focused, then transfer focus back to the workspace center.
3672 /// When the `close_panel_on_toggle` setting is enabled, also closes the
3673 /// panel when transferring focus back to the center.
3674 pub fn toggle_panel_focus<T: Panel>(
3675 &mut self,
3676 window: &mut Window,
3677 cx: &mut Context<Self>,
3678 ) -> bool {
3679 let mut did_focus_panel = false;
3680 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
3681 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
3682 did_focus_panel
3683 });
3684
3685 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
3686 self.close_panel::<T>(window, cx);
3687 }
3688
3689 telemetry::event!(
3690 "Panel Button Clicked",
3691 name = T::persistent_name(),
3692 toggle_state = did_focus_panel
3693 );
3694
3695 did_focus_panel
3696 }
3697
3698 pub fn activate_panel_for_proto_id(
3699 &mut self,
3700 panel_id: PanelId,
3701 window: &mut Window,
3702 cx: &mut Context<Self>,
3703 ) -> Option<Arc<dyn PanelHandle>> {
3704 let mut panel = None;
3705 for dock in self.all_docks() {
3706 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
3707 panel = dock.update(cx, |dock, cx| {
3708 dock.activate_panel(panel_index, window, cx);
3709 dock.set_open(true, window, cx);
3710 dock.active_panel().cloned()
3711 });
3712 break;
3713 }
3714 }
3715
3716 if panel.is_some() {
3717 cx.notify();
3718 self.serialize_workspace(window, cx);
3719 }
3720
3721 panel
3722 }
3723
3724 /// Focus or unfocus the given panel type, depending on the given callback.
3725 fn focus_or_unfocus_panel<T: Panel>(
3726 &mut self,
3727 window: &mut Window,
3728 cx: &mut Context<Self>,
3729 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
3730 ) -> Option<Arc<dyn PanelHandle>> {
3731 let mut result_panel = None;
3732 let mut serialize = false;
3733 for dock in self.all_docks() {
3734 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3735 let mut focus_center = false;
3736 let panel = dock.update(cx, |dock, cx| {
3737 dock.activate_panel(panel_index, window, cx);
3738
3739 let panel = dock.active_panel().cloned();
3740 if let Some(panel) = panel.as_ref() {
3741 if should_focus(&**panel, window, cx) {
3742 dock.set_open(true, window, cx);
3743 panel.panel_focus_handle(cx).focus(window, cx);
3744 } else {
3745 focus_center = true;
3746 }
3747 }
3748 panel
3749 });
3750
3751 if focus_center {
3752 self.active_pane
3753 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3754 }
3755
3756 result_panel = panel;
3757 serialize = true;
3758 break;
3759 }
3760 }
3761
3762 if serialize {
3763 self.serialize_workspace(window, cx);
3764 }
3765
3766 cx.notify();
3767 result_panel
3768 }
3769
3770 /// Open the panel of the given type
3771 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3772 for dock in self.all_docks() {
3773 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3774 dock.update(cx, |dock, cx| {
3775 dock.activate_panel(panel_index, window, cx);
3776 dock.set_open(true, window, cx);
3777 });
3778 }
3779 }
3780 }
3781
3782 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
3783 for dock in self.all_docks().iter() {
3784 dock.update(cx, |dock, cx| {
3785 if dock.panel::<T>().is_some() {
3786 dock.set_open(false, window, cx)
3787 }
3788 })
3789 }
3790 }
3791
3792 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
3793 self.all_docks()
3794 .iter()
3795 .find_map(|dock| dock.read(cx).panel::<T>())
3796 }
3797
3798 fn dismiss_zoomed_items_to_reveal(
3799 &mut self,
3800 dock_to_reveal: Option<DockPosition>,
3801 window: &mut Window,
3802 cx: &mut Context<Self>,
3803 ) {
3804 // If a center pane is zoomed, unzoom it.
3805 for pane in &self.panes {
3806 if pane != &self.active_pane || dock_to_reveal.is_some() {
3807 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
3808 }
3809 }
3810
3811 // If another dock is zoomed, hide it.
3812 let mut focus_center = false;
3813 for dock in self.all_docks() {
3814 dock.update(cx, |dock, cx| {
3815 if Some(dock.position()) != dock_to_reveal
3816 && let Some(panel) = dock.active_panel()
3817 && panel.is_zoomed(window, cx)
3818 {
3819 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
3820 dock.set_open(false, window, cx);
3821 }
3822 });
3823 }
3824
3825 if focus_center {
3826 self.active_pane
3827 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3828 }
3829
3830 if self.zoomed_position != dock_to_reveal {
3831 self.zoomed = None;
3832 self.zoomed_position = None;
3833 cx.emit(Event::ZoomChanged);
3834 }
3835
3836 cx.notify();
3837 }
3838
3839 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
3840 let pane = cx.new(|cx| {
3841 let mut pane = Pane::new(
3842 self.weak_handle(),
3843 self.project.clone(),
3844 self.pane_history_timestamp.clone(),
3845 None,
3846 NewFile.boxed_clone(),
3847 true,
3848 window,
3849 cx,
3850 );
3851 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
3852 pane
3853 });
3854 cx.subscribe_in(&pane, window, Self::handle_pane_event)
3855 .detach();
3856 self.panes.push(pane.clone());
3857
3858 window.focus(&pane.focus_handle(cx), cx);
3859
3860 cx.emit(Event::PaneAdded(pane.clone()));
3861 pane
3862 }
3863
3864 pub fn add_item_to_center(
3865 &mut self,
3866 item: Box<dyn ItemHandle>,
3867 window: &mut Window,
3868 cx: &mut Context<Self>,
3869 ) -> bool {
3870 if let Some(center_pane) = self.last_active_center_pane.clone() {
3871 if let Some(center_pane) = center_pane.upgrade() {
3872 center_pane.update(cx, |pane, cx| {
3873 pane.add_item(item, true, true, None, window, cx)
3874 });
3875 true
3876 } else {
3877 false
3878 }
3879 } else {
3880 false
3881 }
3882 }
3883
3884 pub fn add_item_to_active_pane(
3885 &mut self,
3886 item: Box<dyn ItemHandle>,
3887 destination_index: Option<usize>,
3888 focus_item: bool,
3889 window: &mut Window,
3890 cx: &mut App,
3891 ) {
3892 self.add_item(
3893 self.active_pane.clone(),
3894 item,
3895 destination_index,
3896 false,
3897 focus_item,
3898 window,
3899 cx,
3900 )
3901 }
3902
3903 pub fn add_item(
3904 &mut self,
3905 pane: Entity<Pane>,
3906 item: Box<dyn ItemHandle>,
3907 destination_index: Option<usize>,
3908 activate_pane: bool,
3909 focus_item: bool,
3910 window: &mut Window,
3911 cx: &mut App,
3912 ) {
3913 pane.update(cx, |pane, cx| {
3914 pane.add_item(
3915 item,
3916 activate_pane,
3917 focus_item,
3918 destination_index,
3919 window,
3920 cx,
3921 )
3922 });
3923 }
3924
3925 pub fn split_item(
3926 &mut self,
3927 split_direction: SplitDirection,
3928 item: Box<dyn ItemHandle>,
3929 window: &mut Window,
3930 cx: &mut Context<Self>,
3931 ) {
3932 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
3933 self.add_item(new_pane, item, None, true, true, window, cx);
3934 }
3935
3936 pub fn open_abs_path(
3937 &mut self,
3938 abs_path: PathBuf,
3939 options: OpenOptions,
3940 window: &mut Window,
3941 cx: &mut Context<Self>,
3942 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3943 cx.spawn_in(window, async move |workspace, cx| {
3944 let open_paths_task_result = workspace
3945 .update_in(cx, |workspace, window, cx| {
3946 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
3947 })
3948 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
3949 .await;
3950 anyhow::ensure!(
3951 open_paths_task_result.len() == 1,
3952 "open abs path {abs_path:?} task returned incorrect number of results"
3953 );
3954 match open_paths_task_result
3955 .into_iter()
3956 .next()
3957 .expect("ensured single task result")
3958 {
3959 Some(open_result) => {
3960 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
3961 }
3962 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
3963 }
3964 })
3965 }
3966
3967 pub fn split_abs_path(
3968 &mut self,
3969 abs_path: PathBuf,
3970 visible: bool,
3971 window: &mut Window,
3972 cx: &mut Context<Self>,
3973 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3974 let project_path_task =
3975 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
3976 cx.spawn_in(window, async move |this, cx| {
3977 let (_, path) = project_path_task.await?;
3978 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
3979 .await
3980 })
3981 }
3982
3983 pub fn open_path(
3984 &mut self,
3985 path: impl Into<ProjectPath>,
3986 pane: Option<WeakEntity<Pane>>,
3987 focus_item: bool,
3988 window: &mut Window,
3989 cx: &mut App,
3990 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3991 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
3992 }
3993
3994 pub fn open_path_preview(
3995 &mut self,
3996 path: impl Into<ProjectPath>,
3997 pane: Option<WeakEntity<Pane>>,
3998 focus_item: bool,
3999 allow_preview: bool,
4000 activate: bool,
4001 window: &mut Window,
4002 cx: &mut App,
4003 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4004 let pane = pane.unwrap_or_else(|| {
4005 self.last_active_center_pane.clone().unwrap_or_else(|| {
4006 self.panes
4007 .first()
4008 .expect("There must be an active pane")
4009 .downgrade()
4010 })
4011 });
4012
4013 let project_path = path.into();
4014 let task = self.load_path(project_path.clone(), window, cx);
4015 window.spawn(cx, async move |cx| {
4016 let (project_entry_id, build_item) = task.await?;
4017
4018 pane.update_in(cx, |pane, window, cx| {
4019 pane.open_item(
4020 project_entry_id,
4021 project_path,
4022 focus_item,
4023 allow_preview,
4024 activate,
4025 None,
4026 window,
4027 cx,
4028 build_item,
4029 )
4030 })
4031 })
4032 }
4033
4034 pub fn split_path(
4035 &mut self,
4036 path: impl Into<ProjectPath>,
4037 window: &mut Window,
4038 cx: &mut Context<Self>,
4039 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4040 self.split_path_preview(path, false, None, window, cx)
4041 }
4042
4043 pub fn split_path_preview(
4044 &mut self,
4045 path: impl Into<ProjectPath>,
4046 allow_preview: bool,
4047 split_direction: Option<SplitDirection>,
4048 window: &mut Window,
4049 cx: &mut Context<Self>,
4050 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4051 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4052 self.panes
4053 .first()
4054 .expect("There must be an active pane")
4055 .downgrade()
4056 });
4057
4058 if let Member::Pane(center_pane) = &self.center.root
4059 && center_pane.read(cx).items_len() == 0
4060 {
4061 return self.open_path(path, Some(pane), true, window, cx);
4062 }
4063
4064 let project_path = path.into();
4065 let task = self.load_path(project_path.clone(), window, cx);
4066 cx.spawn_in(window, async move |this, cx| {
4067 let (project_entry_id, build_item) = task.await?;
4068 this.update_in(cx, move |this, window, cx| -> Option<_> {
4069 let pane = pane.upgrade()?;
4070 let new_pane = this.split_pane(
4071 pane,
4072 split_direction.unwrap_or(SplitDirection::Right),
4073 window,
4074 cx,
4075 );
4076 new_pane.update(cx, |new_pane, cx| {
4077 Some(new_pane.open_item(
4078 project_entry_id,
4079 project_path,
4080 true,
4081 allow_preview,
4082 true,
4083 None,
4084 window,
4085 cx,
4086 build_item,
4087 ))
4088 })
4089 })
4090 .map(|option| option.context("pane was dropped"))?
4091 })
4092 }
4093
4094 fn load_path(
4095 &mut self,
4096 path: ProjectPath,
4097 window: &mut Window,
4098 cx: &mut App,
4099 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4100 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4101 registry.open_path(self.project(), &path, window, cx)
4102 }
4103
4104 pub fn find_project_item<T>(
4105 &self,
4106 pane: &Entity<Pane>,
4107 project_item: &Entity<T::Item>,
4108 cx: &App,
4109 ) -> Option<Entity<T>>
4110 where
4111 T: ProjectItem,
4112 {
4113 use project::ProjectItem as _;
4114 let project_item = project_item.read(cx);
4115 let entry_id = project_item.entry_id(cx);
4116 let project_path = project_item.project_path(cx);
4117
4118 let mut item = None;
4119 if let Some(entry_id) = entry_id {
4120 item = pane.read(cx).item_for_entry(entry_id, cx);
4121 }
4122 if item.is_none()
4123 && let Some(project_path) = project_path
4124 {
4125 item = pane.read(cx).item_for_path(project_path, cx);
4126 }
4127
4128 item.and_then(|item| item.downcast::<T>())
4129 }
4130
4131 pub fn is_project_item_open<T>(
4132 &self,
4133 pane: &Entity<Pane>,
4134 project_item: &Entity<T::Item>,
4135 cx: &App,
4136 ) -> bool
4137 where
4138 T: ProjectItem,
4139 {
4140 self.find_project_item::<T>(pane, project_item, cx)
4141 .is_some()
4142 }
4143
4144 pub fn open_project_item<T>(
4145 &mut self,
4146 pane: Entity<Pane>,
4147 project_item: Entity<T::Item>,
4148 activate_pane: bool,
4149 focus_item: bool,
4150 keep_old_preview: bool,
4151 allow_new_preview: bool,
4152 window: &mut Window,
4153 cx: &mut Context<Self>,
4154 ) -> Entity<T>
4155 where
4156 T: ProjectItem,
4157 {
4158 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4159
4160 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4161 if !keep_old_preview
4162 && let Some(old_id) = old_item_id
4163 && old_id != item.item_id()
4164 {
4165 // switching to a different item, so unpreview old active item
4166 pane.update(cx, |pane, _| {
4167 pane.unpreview_item_if_preview(old_id);
4168 });
4169 }
4170
4171 self.activate_item(&item, activate_pane, focus_item, window, cx);
4172 if !allow_new_preview {
4173 pane.update(cx, |pane, _| {
4174 pane.unpreview_item_if_preview(item.item_id());
4175 });
4176 }
4177 return item;
4178 }
4179
4180 let item = pane.update(cx, |pane, cx| {
4181 cx.new(|cx| {
4182 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4183 })
4184 });
4185 let mut destination_index = None;
4186 pane.update(cx, |pane, cx| {
4187 if !keep_old_preview && let Some(old_id) = old_item_id {
4188 pane.unpreview_item_if_preview(old_id);
4189 }
4190 if allow_new_preview {
4191 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4192 }
4193 });
4194
4195 self.add_item(
4196 pane,
4197 Box::new(item.clone()),
4198 destination_index,
4199 activate_pane,
4200 focus_item,
4201 window,
4202 cx,
4203 );
4204 item
4205 }
4206
4207 pub fn open_shared_screen(
4208 &mut self,
4209 peer_id: PeerId,
4210 window: &mut Window,
4211 cx: &mut Context<Self>,
4212 ) {
4213 if let Some(shared_screen) =
4214 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4215 {
4216 self.active_pane.update(cx, |pane, cx| {
4217 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4218 });
4219 }
4220 }
4221
4222 pub fn activate_item(
4223 &mut self,
4224 item: &dyn ItemHandle,
4225 activate_pane: bool,
4226 focus_item: bool,
4227 window: &mut Window,
4228 cx: &mut App,
4229 ) -> bool {
4230 let result = self.panes.iter().find_map(|pane| {
4231 pane.read(cx)
4232 .index_for_item(item)
4233 .map(|ix| (pane.clone(), ix))
4234 });
4235 if let Some((pane, ix)) = result {
4236 pane.update(cx, |pane, cx| {
4237 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4238 });
4239 true
4240 } else {
4241 false
4242 }
4243 }
4244
4245 fn activate_pane_at_index(
4246 &mut self,
4247 action: &ActivatePane,
4248 window: &mut Window,
4249 cx: &mut Context<Self>,
4250 ) {
4251 let panes = self.center.panes();
4252 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4253 window.focus(&pane.focus_handle(cx), cx);
4254 } else {
4255 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4256 .detach();
4257 }
4258 }
4259
4260 fn move_item_to_pane_at_index(
4261 &mut self,
4262 action: &MoveItemToPane,
4263 window: &mut Window,
4264 cx: &mut Context<Self>,
4265 ) {
4266 let panes = self.center.panes();
4267 let destination = match panes.get(action.destination) {
4268 Some(&destination) => destination.clone(),
4269 None => {
4270 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4271 return;
4272 }
4273 let direction = SplitDirection::Right;
4274 let split_off_pane = self
4275 .find_pane_in_direction(direction, cx)
4276 .unwrap_or_else(|| self.active_pane.clone());
4277 let new_pane = self.add_pane(window, cx);
4278 if self
4279 .center
4280 .split(&split_off_pane, &new_pane, direction, cx)
4281 .log_err()
4282 .is_none()
4283 {
4284 return;
4285 };
4286 new_pane
4287 }
4288 };
4289
4290 if action.clone {
4291 if self
4292 .active_pane
4293 .read(cx)
4294 .active_item()
4295 .is_some_and(|item| item.can_split(cx))
4296 {
4297 clone_active_item(
4298 self.database_id(),
4299 &self.active_pane,
4300 &destination,
4301 action.focus,
4302 window,
4303 cx,
4304 );
4305 return;
4306 }
4307 }
4308 move_active_item(
4309 &self.active_pane,
4310 &destination,
4311 action.focus,
4312 true,
4313 window,
4314 cx,
4315 )
4316 }
4317
4318 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4319 let panes = self.center.panes();
4320 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4321 let next_ix = (ix + 1) % panes.len();
4322 let next_pane = panes[next_ix].clone();
4323 window.focus(&next_pane.focus_handle(cx), cx);
4324 }
4325 }
4326
4327 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4328 let panes = self.center.panes();
4329 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4330 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4331 let prev_pane = panes[prev_ix].clone();
4332 window.focus(&prev_pane.focus_handle(cx), cx);
4333 }
4334 }
4335
4336 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4337 let last_pane = self.center.last_pane();
4338 window.focus(&last_pane.focus_handle(cx), cx);
4339 }
4340
4341 pub fn activate_pane_in_direction(
4342 &mut self,
4343 direction: SplitDirection,
4344 window: &mut Window,
4345 cx: &mut App,
4346 ) {
4347 use ActivateInDirectionTarget as Target;
4348 enum Origin {
4349 LeftDock,
4350 RightDock,
4351 BottomDock,
4352 Center,
4353 }
4354
4355 let origin: Origin = [
4356 (&self.left_dock, Origin::LeftDock),
4357 (&self.right_dock, Origin::RightDock),
4358 (&self.bottom_dock, Origin::BottomDock),
4359 ]
4360 .into_iter()
4361 .find_map(|(dock, origin)| {
4362 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4363 Some(origin)
4364 } else {
4365 None
4366 }
4367 })
4368 .unwrap_or(Origin::Center);
4369
4370 let get_last_active_pane = || {
4371 let pane = self
4372 .last_active_center_pane
4373 .clone()
4374 .unwrap_or_else(|| {
4375 self.panes
4376 .first()
4377 .expect("There must be an active pane")
4378 .downgrade()
4379 })
4380 .upgrade()?;
4381 (pane.read(cx).items_len() != 0).then_some(pane)
4382 };
4383
4384 let try_dock =
4385 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4386
4387 let target = match (origin, direction) {
4388 // We're in the center, so we first try to go to a different pane,
4389 // otherwise try to go to a dock.
4390 (Origin::Center, direction) => {
4391 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4392 Some(Target::Pane(pane))
4393 } else {
4394 match direction {
4395 SplitDirection::Up => None,
4396 SplitDirection::Down => try_dock(&self.bottom_dock),
4397 SplitDirection::Left => try_dock(&self.left_dock),
4398 SplitDirection::Right => try_dock(&self.right_dock),
4399 }
4400 }
4401 }
4402
4403 (Origin::LeftDock, SplitDirection::Right) => {
4404 if let Some(last_active_pane) = get_last_active_pane() {
4405 Some(Target::Pane(last_active_pane))
4406 } else {
4407 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4408 }
4409 }
4410
4411 (Origin::LeftDock, SplitDirection::Down)
4412 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4413
4414 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4415 (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
4416 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4417
4418 (Origin::RightDock, SplitDirection::Left) => {
4419 if let Some(last_active_pane) = get_last_active_pane() {
4420 Some(Target::Pane(last_active_pane))
4421 } else {
4422 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
4423 }
4424 }
4425
4426 _ => None,
4427 };
4428
4429 match target {
4430 Some(ActivateInDirectionTarget::Pane(pane)) => {
4431 let pane = pane.read(cx);
4432 if let Some(item) = pane.active_item() {
4433 item.item_focus_handle(cx).focus(window, cx);
4434 } else {
4435 log::error!(
4436 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4437 );
4438 }
4439 }
4440 Some(ActivateInDirectionTarget::Dock(dock)) => {
4441 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4442 window.defer(cx, move |window, cx| {
4443 let dock = dock.read(cx);
4444 if let Some(panel) = dock.active_panel() {
4445 panel.panel_focus_handle(cx).focus(window, cx);
4446 } else {
4447 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4448 }
4449 })
4450 }
4451 None => {}
4452 }
4453 }
4454
4455 pub fn move_item_to_pane_in_direction(
4456 &mut self,
4457 action: &MoveItemToPaneInDirection,
4458 window: &mut Window,
4459 cx: &mut Context<Self>,
4460 ) {
4461 let destination = match self.find_pane_in_direction(action.direction, cx) {
4462 Some(destination) => destination,
4463 None => {
4464 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4465 return;
4466 }
4467 let new_pane = self.add_pane(window, cx);
4468 if self
4469 .center
4470 .split(&self.active_pane, &new_pane, action.direction, cx)
4471 .log_err()
4472 .is_none()
4473 {
4474 return;
4475 };
4476 new_pane
4477 }
4478 };
4479
4480 if action.clone {
4481 if self
4482 .active_pane
4483 .read(cx)
4484 .active_item()
4485 .is_some_and(|item| item.can_split(cx))
4486 {
4487 clone_active_item(
4488 self.database_id(),
4489 &self.active_pane,
4490 &destination,
4491 action.focus,
4492 window,
4493 cx,
4494 );
4495 return;
4496 }
4497 }
4498 move_active_item(
4499 &self.active_pane,
4500 &destination,
4501 action.focus,
4502 true,
4503 window,
4504 cx,
4505 );
4506 }
4507
4508 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4509 self.center.bounding_box_for_pane(pane)
4510 }
4511
4512 pub fn find_pane_in_direction(
4513 &mut self,
4514 direction: SplitDirection,
4515 cx: &App,
4516 ) -> Option<Entity<Pane>> {
4517 self.center
4518 .find_pane_in_direction(&self.active_pane, direction, cx)
4519 .cloned()
4520 }
4521
4522 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4523 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4524 self.center.swap(&self.active_pane, &to, cx);
4525 cx.notify();
4526 }
4527 }
4528
4529 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4530 if self
4531 .center
4532 .move_to_border(&self.active_pane, direction, cx)
4533 .unwrap()
4534 {
4535 cx.notify();
4536 }
4537 }
4538
4539 pub fn resize_pane(
4540 &mut self,
4541 axis: gpui::Axis,
4542 amount: Pixels,
4543 window: &mut Window,
4544 cx: &mut Context<Self>,
4545 ) {
4546 let docks = self.all_docks();
4547 let active_dock = docks
4548 .into_iter()
4549 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4550
4551 if let Some(dock) = active_dock {
4552 let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
4553 return;
4554 };
4555 match dock.read(cx).position() {
4556 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4557 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4558 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4559 }
4560 } else {
4561 self.center
4562 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
4563 }
4564 cx.notify();
4565 }
4566
4567 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
4568 self.center.reset_pane_sizes(cx);
4569 cx.notify();
4570 }
4571
4572 fn handle_pane_focused(
4573 &mut self,
4574 pane: Entity<Pane>,
4575 window: &mut Window,
4576 cx: &mut Context<Self>,
4577 ) {
4578 // This is explicitly hoisted out of the following check for pane identity as
4579 // terminal panel panes are not registered as a center panes.
4580 self.status_bar.update(cx, |status_bar, cx| {
4581 status_bar.set_active_pane(&pane, window, cx);
4582 });
4583 if self.active_pane != pane {
4584 self.set_active_pane(&pane, window, cx);
4585 }
4586
4587 if self.last_active_center_pane.is_none() {
4588 self.last_active_center_pane = Some(pane.downgrade());
4589 }
4590
4591 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
4592 // This prevents the dock from closing when focus events fire during window activation.
4593 // We also preserve any dock whose active panel itself has focus — this covers
4594 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
4595 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
4596 let dock_read = dock.read(cx);
4597 if let Some(panel) = dock_read.active_panel() {
4598 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
4599 || panel.panel_focus_handle(cx).contains_focused(window, cx)
4600 {
4601 return Some(dock_read.position());
4602 }
4603 }
4604 None
4605 });
4606
4607 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
4608 if pane.read(cx).is_zoomed() {
4609 self.zoomed = Some(pane.downgrade().into());
4610 } else {
4611 self.zoomed = None;
4612 }
4613 self.zoomed_position = None;
4614 cx.emit(Event::ZoomChanged);
4615 self.update_active_view_for_followers(window, cx);
4616 pane.update(cx, |pane, _| {
4617 pane.track_alternate_file_items();
4618 });
4619
4620 cx.notify();
4621 }
4622
4623 fn set_active_pane(
4624 &mut self,
4625 pane: &Entity<Pane>,
4626 window: &mut Window,
4627 cx: &mut Context<Self>,
4628 ) {
4629 self.active_pane = pane.clone();
4630 self.active_item_path_changed(true, window, cx);
4631 self.last_active_center_pane = Some(pane.downgrade());
4632 }
4633
4634 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4635 self.update_active_view_for_followers(window, cx);
4636 }
4637
4638 fn handle_pane_event(
4639 &mut self,
4640 pane: &Entity<Pane>,
4641 event: &pane::Event,
4642 window: &mut Window,
4643 cx: &mut Context<Self>,
4644 ) {
4645 let mut serialize_workspace = true;
4646 match event {
4647 pane::Event::AddItem { item } => {
4648 item.added_to_pane(self, pane.clone(), window, cx);
4649 cx.emit(Event::ItemAdded {
4650 item: item.boxed_clone(),
4651 });
4652 }
4653 pane::Event::Split { direction, mode } => {
4654 match mode {
4655 SplitMode::ClonePane => {
4656 self.split_and_clone(pane.clone(), *direction, window, cx)
4657 .detach();
4658 }
4659 SplitMode::EmptyPane => {
4660 self.split_pane(pane.clone(), *direction, window, cx);
4661 }
4662 SplitMode::MovePane => {
4663 self.split_and_move(pane.clone(), *direction, window, cx);
4664 }
4665 };
4666 }
4667 pane::Event::JoinIntoNext => {
4668 self.join_pane_into_next(pane.clone(), window, cx);
4669 }
4670 pane::Event::JoinAll => {
4671 self.join_all_panes(window, cx);
4672 }
4673 pane::Event::Remove { focus_on_pane } => {
4674 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
4675 }
4676 pane::Event::ActivateItem {
4677 local,
4678 focus_changed,
4679 } => {
4680 window.invalidate_character_coordinates();
4681
4682 pane.update(cx, |pane, _| {
4683 pane.track_alternate_file_items();
4684 });
4685 if *local {
4686 self.unfollow_in_pane(pane, window, cx);
4687 }
4688 serialize_workspace = *focus_changed || pane != self.active_pane();
4689 if pane == self.active_pane() {
4690 self.active_item_path_changed(*focus_changed, window, cx);
4691 self.update_active_view_for_followers(window, cx);
4692 } else if *local {
4693 self.set_active_pane(pane, window, cx);
4694 }
4695 }
4696 pane::Event::UserSavedItem { item, save_intent } => {
4697 cx.emit(Event::UserSavedItem {
4698 pane: pane.downgrade(),
4699 item: item.boxed_clone(),
4700 save_intent: *save_intent,
4701 });
4702 serialize_workspace = false;
4703 }
4704 pane::Event::ChangeItemTitle => {
4705 if *pane == self.active_pane {
4706 self.active_item_path_changed(false, window, cx);
4707 }
4708 serialize_workspace = false;
4709 }
4710 pane::Event::RemovedItem { item } => {
4711 cx.emit(Event::ActiveItemChanged);
4712 self.update_window_edited(window, cx);
4713 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
4714 && entry.get().entity_id() == pane.entity_id()
4715 {
4716 entry.remove();
4717 }
4718 cx.emit(Event::ItemRemoved {
4719 item_id: item.item_id(),
4720 });
4721 }
4722 pane::Event::Focus => {
4723 window.invalidate_character_coordinates();
4724 self.handle_pane_focused(pane.clone(), window, cx);
4725 }
4726 pane::Event::ZoomIn => {
4727 if *pane == self.active_pane {
4728 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
4729 if pane.read(cx).has_focus(window, cx) {
4730 self.zoomed = Some(pane.downgrade().into());
4731 self.zoomed_position = None;
4732 cx.emit(Event::ZoomChanged);
4733 }
4734 cx.notify();
4735 }
4736 }
4737 pane::Event::ZoomOut => {
4738 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4739 if self.zoomed_position.is_none() {
4740 self.zoomed = None;
4741 cx.emit(Event::ZoomChanged);
4742 }
4743 cx.notify();
4744 }
4745 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
4746 }
4747
4748 if serialize_workspace {
4749 self.serialize_workspace(window, cx);
4750 }
4751 }
4752
4753 pub fn unfollow_in_pane(
4754 &mut self,
4755 pane: &Entity<Pane>,
4756 window: &mut Window,
4757 cx: &mut Context<Workspace>,
4758 ) -> Option<CollaboratorId> {
4759 let leader_id = self.leader_for_pane(pane)?;
4760 self.unfollow(leader_id, window, cx);
4761 Some(leader_id)
4762 }
4763
4764 pub fn split_pane(
4765 &mut self,
4766 pane_to_split: Entity<Pane>,
4767 split_direction: SplitDirection,
4768 window: &mut Window,
4769 cx: &mut Context<Self>,
4770 ) -> Entity<Pane> {
4771 let new_pane = self.add_pane(window, cx);
4772 self.center
4773 .split(&pane_to_split, &new_pane, split_direction, cx)
4774 .unwrap();
4775 cx.notify();
4776 new_pane
4777 }
4778
4779 pub fn split_and_move(
4780 &mut self,
4781 pane: Entity<Pane>,
4782 direction: SplitDirection,
4783 window: &mut Window,
4784 cx: &mut Context<Self>,
4785 ) {
4786 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
4787 return;
4788 };
4789 let new_pane = self.add_pane(window, cx);
4790 new_pane.update(cx, |pane, cx| {
4791 pane.add_item(item, true, true, None, window, cx)
4792 });
4793 self.center.split(&pane, &new_pane, direction, cx).unwrap();
4794 cx.notify();
4795 }
4796
4797 pub fn split_and_clone(
4798 &mut self,
4799 pane: Entity<Pane>,
4800 direction: SplitDirection,
4801 window: &mut Window,
4802 cx: &mut Context<Self>,
4803 ) -> Task<Option<Entity<Pane>>> {
4804 let Some(item) = pane.read(cx).active_item() else {
4805 return Task::ready(None);
4806 };
4807 if !item.can_split(cx) {
4808 return Task::ready(None);
4809 }
4810 let task = item.clone_on_split(self.database_id(), window, cx);
4811 cx.spawn_in(window, async move |this, cx| {
4812 if let Some(clone) = task.await {
4813 this.update_in(cx, |this, window, cx| {
4814 let new_pane = this.add_pane(window, cx);
4815 let nav_history = pane.read(cx).fork_nav_history();
4816 new_pane.update(cx, |pane, cx| {
4817 pane.set_nav_history(nav_history, cx);
4818 pane.add_item(clone, true, true, None, window, cx)
4819 });
4820 this.center.split(&pane, &new_pane, direction, cx).unwrap();
4821 cx.notify();
4822 new_pane
4823 })
4824 .ok()
4825 } else {
4826 None
4827 }
4828 })
4829 }
4830
4831 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4832 let active_item = self.active_pane.read(cx).active_item();
4833 for pane in &self.panes {
4834 join_pane_into_active(&self.active_pane, pane, window, cx);
4835 }
4836 if let Some(active_item) = active_item {
4837 self.activate_item(active_item.as_ref(), true, true, window, cx);
4838 }
4839 cx.notify();
4840 }
4841
4842 pub fn join_pane_into_next(
4843 &mut self,
4844 pane: Entity<Pane>,
4845 window: &mut Window,
4846 cx: &mut Context<Self>,
4847 ) {
4848 let next_pane = self
4849 .find_pane_in_direction(SplitDirection::Right, cx)
4850 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
4851 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
4852 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
4853 let Some(next_pane) = next_pane else {
4854 return;
4855 };
4856 move_all_items(&pane, &next_pane, window, cx);
4857 cx.notify();
4858 }
4859
4860 fn remove_pane(
4861 &mut self,
4862 pane: Entity<Pane>,
4863 focus_on: Option<Entity<Pane>>,
4864 window: &mut Window,
4865 cx: &mut Context<Self>,
4866 ) {
4867 if self.center.remove(&pane, cx).unwrap() {
4868 self.force_remove_pane(&pane, &focus_on, window, cx);
4869 self.unfollow_in_pane(&pane, window, cx);
4870 self.last_leaders_by_pane.remove(&pane.downgrade());
4871 for removed_item in pane.read(cx).items() {
4872 self.panes_by_item.remove(&removed_item.item_id());
4873 }
4874
4875 cx.notify();
4876 } else {
4877 self.active_item_path_changed(true, window, cx);
4878 }
4879 cx.emit(Event::PaneRemoved);
4880 }
4881
4882 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
4883 &mut self.panes
4884 }
4885
4886 pub fn panes(&self) -> &[Entity<Pane>] {
4887 &self.panes
4888 }
4889
4890 pub fn active_pane(&self) -> &Entity<Pane> {
4891 &self.active_pane
4892 }
4893
4894 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
4895 for dock in self.all_docks() {
4896 if dock.focus_handle(cx).contains_focused(window, cx)
4897 && let Some(pane) = dock
4898 .read(cx)
4899 .active_panel()
4900 .and_then(|panel| panel.pane(cx))
4901 {
4902 return pane;
4903 }
4904 }
4905 self.active_pane().clone()
4906 }
4907
4908 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4909 self.find_pane_in_direction(SplitDirection::Right, cx)
4910 .unwrap_or_else(|| {
4911 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
4912 })
4913 }
4914
4915 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
4916 self.pane_for_item_id(handle.item_id())
4917 }
4918
4919 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
4920 let weak_pane = self.panes_by_item.get(&item_id)?;
4921 weak_pane.upgrade()
4922 }
4923
4924 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
4925 self.panes
4926 .iter()
4927 .find(|pane| pane.entity_id() == entity_id)
4928 .cloned()
4929 }
4930
4931 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
4932 self.follower_states.retain(|leader_id, state| {
4933 if *leader_id == CollaboratorId::PeerId(peer_id) {
4934 for item in state.items_by_leader_view_id.values() {
4935 item.view.set_leader_id(None, window, cx);
4936 }
4937 false
4938 } else {
4939 true
4940 }
4941 });
4942 cx.notify();
4943 }
4944
4945 pub fn start_following(
4946 &mut self,
4947 leader_id: impl Into<CollaboratorId>,
4948 window: &mut Window,
4949 cx: &mut Context<Self>,
4950 ) -> Option<Task<Result<()>>> {
4951 let leader_id = leader_id.into();
4952 let pane = self.active_pane().clone();
4953
4954 self.last_leaders_by_pane
4955 .insert(pane.downgrade(), leader_id);
4956 self.unfollow(leader_id, window, cx);
4957 self.unfollow_in_pane(&pane, window, cx);
4958 self.follower_states.insert(
4959 leader_id,
4960 FollowerState {
4961 center_pane: pane.clone(),
4962 dock_pane: None,
4963 active_view_id: None,
4964 items_by_leader_view_id: Default::default(),
4965 },
4966 );
4967 cx.notify();
4968
4969 match leader_id {
4970 CollaboratorId::PeerId(leader_peer_id) => {
4971 let room_id = self.active_call()?.room_id(cx)?;
4972 let project_id = self.project.read(cx).remote_id();
4973 let request = self.app_state.client.request(proto::Follow {
4974 room_id,
4975 project_id,
4976 leader_id: Some(leader_peer_id),
4977 });
4978
4979 Some(cx.spawn_in(window, async move |this, cx| {
4980 let response = request.await?;
4981 this.update(cx, |this, _| {
4982 let state = this
4983 .follower_states
4984 .get_mut(&leader_id)
4985 .context("following interrupted")?;
4986 state.active_view_id = response
4987 .active_view
4988 .as_ref()
4989 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
4990 anyhow::Ok(())
4991 })??;
4992 if let Some(view) = response.active_view {
4993 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
4994 }
4995 this.update_in(cx, |this, window, cx| {
4996 this.leader_updated(leader_id, window, cx)
4997 })?;
4998 Ok(())
4999 }))
5000 }
5001 CollaboratorId::Agent => {
5002 self.leader_updated(leader_id, window, cx)?;
5003 Some(Task::ready(Ok(())))
5004 }
5005 }
5006 }
5007
5008 pub fn follow_next_collaborator(
5009 &mut self,
5010 _: &FollowNextCollaborator,
5011 window: &mut Window,
5012 cx: &mut Context<Self>,
5013 ) {
5014 let collaborators = self.project.read(cx).collaborators();
5015 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5016 let mut collaborators = collaborators.keys().copied();
5017 for peer_id in collaborators.by_ref() {
5018 if CollaboratorId::PeerId(peer_id) == leader_id {
5019 break;
5020 }
5021 }
5022 collaborators.next().map(CollaboratorId::PeerId)
5023 } else if let Some(last_leader_id) =
5024 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5025 {
5026 match last_leader_id {
5027 CollaboratorId::PeerId(peer_id) => {
5028 if collaborators.contains_key(peer_id) {
5029 Some(*last_leader_id)
5030 } else {
5031 None
5032 }
5033 }
5034 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5035 }
5036 } else {
5037 None
5038 };
5039
5040 let pane = self.active_pane.clone();
5041 let Some(leader_id) = next_leader_id.or_else(|| {
5042 Some(CollaboratorId::PeerId(
5043 collaborators.keys().copied().next()?,
5044 ))
5045 }) else {
5046 return;
5047 };
5048 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5049 return;
5050 }
5051 if let Some(task) = self.start_following(leader_id, window, cx) {
5052 task.detach_and_log_err(cx)
5053 }
5054 }
5055
5056 pub fn follow(
5057 &mut self,
5058 leader_id: impl Into<CollaboratorId>,
5059 window: &mut Window,
5060 cx: &mut Context<Self>,
5061 ) {
5062 let leader_id = leader_id.into();
5063
5064 if let CollaboratorId::PeerId(peer_id) = leader_id {
5065 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5066 return;
5067 };
5068 let Some(remote_participant) =
5069 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5070 else {
5071 return;
5072 };
5073
5074 let project = self.project.read(cx);
5075
5076 let other_project_id = match remote_participant.location {
5077 ParticipantLocation::External => None,
5078 ParticipantLocation::UnsharedProject => None,
5079 ParticipantLocation::SharedProject { project_id } => {
5080 if Some(project_id) == project.remote_id() {
5081 None
5082 } else {
5083 Some(project_id)
5084 }
5085 }
5086 };
5087
5088 // if they are active in another project, follow there.
5089 if let Some(project_id) = other_project_id {
5090 let app_state = self.app_state.clone();
5091 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5092 .detach_and_log_err(cx);
5093 }
5094 }
5095
5096 // if you're already following, find the right pane and focus it.
5097 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5098 window.focus(&follower_state.pane().focus_handle(cx), cx);
5099
5100 return;
5101 }
5102
5103 // Otherwise, follow.
5104 if let Some(task) = self.start_following(leader_id, window, cx) {
5105 task.detach_and_log_err(cx)
5106 }
5107 }
5108
5109 pub fn unfollow(
5110 &mut self,
5111 leader_id: impl Into<CollaboratorId>,
5112 window: &mut Window,
5113 cx: &mut Context<Self>,
5114 ) -> Option<()> {
5115 cx.notify();
5116
5117 let leader_id = leader_id.into();
5118 let state = self.follower_states.remove(&leader_id)?;
5119 for (_, item) in state.items_by_leader_view_id {
5120 item.view.set_leader_id(None, window, cx);
5121 }
5122
5123 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5124 let project_id = self.project.read(cx).remote_id();
5125 let room_id = self.active_call()?.room_id(cx)?;
5126 self.app_state
5127 .client
5128 .send(proto::Unfollow {
5129 room_id,
5130 project_id,
5131 leader_id: Some(leader_peer_id),
5132 })
5133 .log_err();
5134 }
5135
5136 Some(())
5137 }
5138
5139 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5140 self.follower_states.contains_key(&id.into())
5141 }
5142
5143 fn active_item_path_changed(
5144 &mut self,
5145 focus_changed: bool,
5146 window: &mut Window,
5147 cx: &mut Context<Self>,
5148 ) {
5149 cx.emit(Event::ActiveItemChanged);
5150 let active_entry = self.active_project_path(cx);
5151 self.project.update(cx, |project, cx| {
5152 project.set_active_path(active_entry.clone(), cx)
5153 });
5154
5155 if focus_changed && let Some(project_path) = &active_entry {
5156 let git_store_entity = self.project.read(cx).git_store().clone();
5157 git_store_entity.update(cx, |git_store, cx| {
5158 git_store.set_active_repo_for_path(project_path, cx);
5159 });
5160 }
5161
5162 self.update_window_title(window, cx);
5163 }
5164
5165 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5166 let project = self.project().read(cx);
5167 let mut title = String::new();
5168
5169 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5170 let name = {
5171 let settings_location = SettingsLocation {
5172 worktree_id: worktree.read(cx).id(),
5173 path: RelPath::empty(),
5174 };
5175
5176 let settings = WorktreeSettings::get(Some(settings_location), cx);
5177 match &settings.project_name {
5178 Some(name) => name.as_str(),
5179 None => worktree.read(cx).root_name_str(),
5180 }
5181 };
5182 if i > 0 {
5183 title.push_str(", ");
5184 }
5185 title.push_str(name);
5186 }
5187
5188 if title.is_empty() {
5189 title = "empty project".to_string();
5190 }
5191
5192 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5193 let filename = path.path.file_name().or_else(|| {
5194 Some(
5195 project
5196 .worktree_for_id(path.worktree_id, cx)?
5197 .read(cx)
5198 .root_name_str(),
5199 )
5200 });
5201
5202 if let Some(filename) = filename {
5203 title.push_str(" — ");
5204 title.push_str(filename.as_ref());
5205 }
5206 }
5207
5208 if project.is_via_collab() {
5209 title.push_str(" ↙");
5210 } else if project.is_shared() {
5211 title.push_str(" ↗");
5212 }
5213
5214 if let Some(last_title) = self.last_window_title.as_ref()
5215 && &title == last_title
5216 {
5217 return;
5218 }
5219 window.set_window_title(&title);
5220 SystemWindowTabController::update_tab_title(
5221 cx,
5222 window.window_handle().window_id(),
5223 SharedString::from(&title),
5224 );
5225 self.last_window_title = Some(title);
5226 }
5227
5228 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5229 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5230 if is_edited != self.window_edited {
5231 self.window_edited = is_edited;
5232 window.set_window_edited(self.window_edited)
5233 }
5234 }
5235
5236 fn update_item_dirty_state(
5237 &mut self,
5238 item: &dyn ItemHandle,
5239 window: &mut Window,
5240 cx: &mut App,
5241 ) {
5242 let is_dirty = item.is_dirty(cx);
5243 let item_id = item.item_id();
5244 let was_dirty = self.dirty_items.contains_key(&item_id);
5245 if is_dirty == was_dirty {
5246 return;
5247 }
5248 if was_dirty {
5249 self.dirty_items.remove(&item_id);
5250 self.update_window_edited(window, cx);
5251 return;
5252 }
5253
5254 let workspace = self.weak_handle();
5255 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5256 return;
5257 };
5258 let on_release_callback = Box::new(move |cx: &mut App| {
5259 window_handle
5260 .update(cx, |_, window, cx| {
5261 workspace
5262 .update(cx, |workspace, cx| {
5263 workspace.dirty_items.remove(&item_id);
5264 workspace.update_window_edited(window, cx)
5265 })
5266 .ok();
5267 })
5268 .ok();
5269 });
5270
5271 let s = item.on_release(cx, on_release_callback);
5272 self.dirty_items.insert(item_id, s);
5273 self.update_window_edited(window, cx);
5274 }
5275
5276 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5277 if self.notifications.is_empty() {
5278 None
5279 } else {
5280 Some(
5281 div()
5282 .absolute()
5283 .right_3()
5284 .bottom_3()
5285 .w_112()
5286 .h_full()
5287 .flex()
5288 .flex_col()
5289 .justify_end()
5290 .gap_2()
5291 .children(
5292 self.notifications
5293 .iter()
5294 .map(|(_, notification)| notification.clone().into_any()),
5295 ),
5296 )
5297 }
5298 }
5299
5300 // RPC handlers
5301
5302 fn active_view_for_follower(
5303 &self,
5304 follower_project_id: Option<u64>,
5305 window: &mut Window,
5306 cx: &mut Context<Self>,
5307 ) -> Option<proto::View> {
5308 let (item, panel_id) = self.active_item_for_followers(window, cx);
5309 let item = item?;
5310 let leader_id = self
5311 .pane_for(&*item)
5312 .and_then(|pane| self.leader_for_pane(&pane));
5313 let leader_peer_id = match leader_id {
5314 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5315 Some(CollaboratorId::Agent) | None => None,
5316 };
5317
5318 let item_handle = item.to_followable_item_handle(cx)?;
5319 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5320 let variant = item_handle.to_state_proto(window, cx)?;
5321
5322 if item_handle.is_project_item(window, cx)
5323 && (follower_project_id.is_none()
5324 || follower_project_id != self.project.read(cx).remote_id())
5325 {
5326 return None;
5327 }
5328
5329 Some(proto::View {
5330 id: id.to_proto(),
5331 leader_id: leader_peer_id,
5332 variant: Some(variant),
5333 panel_id: panel_id.map(|id| id as i32),
5334 })
5335 }
5336
5337 fn handle_follow(
5338 &mut self,
5339 follower_project_id: Option<u64>,
5340 window: &mut Window,
5341 cx: &mut Context<Self>,
5342 ) -> proto::FollowResponse {
5343 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5344
5345 cx.notify();
5346 proto::FollowResponse {
5347 views: active_view.iter().cloned().collect(),
5348 active_view,
5349 }
5350 }
5351
5352 fn handle_update_followers(
5353 &mut self,
5354 leader_id: PeerId,
5355 message: proto::UpdateFollowers,
5356 _window: &mut Window,
5357 _cx: &mut Context<Self>,
5358 ) {
5359 self.leader_updates_tx
5360 .unbounded_send((leader_id, message))
5361 .ok();
5362 }
5363
5364 async fn process_leader_update(
5365 this: &WeakEntity<Self>,
5366 leader_id: PeerId,
5367 update: proto::UpdateFollowers,
5368 cx: &mut AsyncWindowContext,
5369 ) -> Result<()> {
5370 match update.variant.context("invalid update")? {
5371 proto::update_followers::Variant::CreateView(view) => {
5372 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5373 let should_add_view = this.update(cx, |this, _| {
5374 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5375 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5376 } else {
5377 anyhow::Ok(false)
5378 }
5379 })??;
5380
5381 if should_add_view {
5382 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5383 }
5384 }
5385 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5386 let should_add_view = this.update(cx, |this, _| {
5387 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5388 state.active_view_id = update_active_view
5389 .view
5390 .as_ref()
5391 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5392
5393 if state.active_view_id.is_some_and(|view_id| {
5394 !state.items_by_leader_view_id.contains_key(&view_id)
5395 }) {
5396 anyhow::Ok(true)
5397 } else {
5398 anyhow::Ok(false)
5399 }
5400 } else {
5401 anyhow::Ok(false)
5402 }
5403 })??;
5404
5405 if should_add_view && let Some(view) = update_active_view.view {
5406 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5407 }
5408 }
5409 proto::update_followers::Variant::UpdateView(update_view) => {
5410 let variant = update_view.variant.context("missing update view variant")?;
5411 let id = update_view.id.context("missing update view id")?;
5412 let mut tasks = Vec::new();
5413 this.update_in(cx, |this, window, cx| {
5414 let project = this.project.clone();
5415 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5416 let view_id = ViewId::from_proto(id.clone())?;
5417 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5418 tasks.push(item.view.apply_update_proto(
5419 &project,
5420 variant.clone(),
5421 window,
5422 cx,
5423 ));
5424 }
5425 }
5426 anyhow::Ok(())
5427 })??;
5428 try_join_all(tasks).await.log_err();
5429 }
5430 }
5431 this.update_in(cx, |this, window, cx| {
5432 this.leader_updated(leader_id, window, cx)
5433 })?;
5434 Ok(())
5435 }
5436
5437 async fn add_view_from_leader(
5438 this: WeakEntity<Self>,
5439 leader_id: PeerId,
5440 view: &proto::View,
5441 cx: &mut AsyncWindowContext,
5442 ) -> Result<()> {
5443 let this = this.upgrade().context("workspace dropped")?;
5444
5445 let Some(id) = view.id.clone() else {
5446 anyhow::bail!("no id for view");
5447 };
5448 let id = ViewId::from_proto(id)?;
5449 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5450
5451 let pane = this.update(cx, |this, _cx| {
5452 let state = this
5453 .follower_states
5454 .get(&leader_id.into())
5455 .context("stopped following")?;
5456 anyhow::Ok(state.pane().clone())
5457 })?;
5458 let existing_item = pane.update_in(cx, |pane, window, cx| {
5459 let client = this.read(cx).client().clone();
5460 pane.items().find_map(|item| {
5461 let item = item.to_followable_item_handle(cx)?;
5462 if item.remote_id(&client, window, cx) == Some(id) {
5463 Some(item)
5464 } else {
5465 None
5466 }
5467 })
5468 })?;
5469 let item = if let Some(existing_item) = existing_item {
5470 existing_item
5471 } else {
5472 let variant = view.variant.clone();
5473 anyhow::ensure!(variant.is_some(), "missing view variant");
5474
5475 let task = cx.update(|window, cx| {
5476 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5477 })?;
5478
5479 let Some(task) = task else {
5480 anyhow::bail!(
5481 "failed to construct view from leader (maybe from a different version of zed?)"
5482 );
5483 };
5484
5485 let mut new_item = task.await?;
5486 pane.update_in(cx, |pane, window, cx| {
5487 let mut item_to_remove = None;
5488 for (ix, item) in pane.items().enumerate() {
5489 if let Some(item) = item.to_followable_item_handle(cx) {
5490 match new_item.dedup(item.as_ref(), window, cx) {
5491 Some(item::Dedup::KeepExisting) => {
5492 new_item =
5493 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5494 break;
5495 }
5496 Some(item::Dedup::ReplaceExisting) => {
5497 item_to_remove = Some((ix, item.item_id()));
5498 break;
5499 }
5500 None => {}
5501 }
5502 }
5503 }
5504
5505 if let Some((ix, id)) = item_to_remove {
5506 pane.remove_item(id, false, false, window, cx);
5507 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5508 }
5509 })?;
5510
5511 new_item
5512 };
5513
5514 this.update_in(cx, |this, window, cx| {
5515 let state = this.follower_states.get_mut(&leader_id.into())?;
5516 item.set_leader_id(Some(leader_id.into()), window, cx);
5517 state.items_by_leader_view_id.insert(
5518 id,
5519 FollowerView {
5520 view: item,
5521 location: panel_id,
5522 },
5523 );
5524
5525 Some(())
5526 })
5527 .context("no follower state")?;
5528
5529 Ok(())
5530 }
5531
5532 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5533 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5534 return;
5535 };
5536
5537 if let Some(agent_location) = self.project.read(cx).agent_location() {
5538 let buffer_entity_id = agent_location.buffer.entity_id();
5539 let view_id = ViewId {
5540 creator: CollaboratorId::Agent,
5541 id: buffer_entity_id.as_u64(),
5542 };
5543 follower_state.active_view_id = Some(view_id);
5544
5545 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5546 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5547 hash_map::Entry::Vacant(entry) => {
5548 let existing_view =
5549 follower_state
5550 .center_pane
5551 .read(cx)
5552 .items()
5553 .find_map(|item| {
5554 let item = item.to_followable_item_handle(cx)?;
5555 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5556 && item.project_item_model_ids(cx).as_slice()
5557 == [buffer_entity_id]
5558 {
5559 Some(item)
5560 } else {
5561 None
5562 }
5563 });
5564 let view = existing_view.or_else(|| {
5565 agent_location.buffer.upgrade().and_then(|buffer| {
5566 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
5567 registry.build_item(buffer, self.project.clone(), None, window, cx)
5568 })?
5569 .to_followable_item_handle(cx)
5570 })
5571 });
5572
5573 view.map(|view| {
5574 entry.insert(FollowerView {
5575 view,
5576 location: None,
5577 })
5578 })
5579 }
5580 };
5581
5582 if let Some(item) = item {
5583 item.view
5584 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
5585 item.view
5586 .update_agent_location(agent_location.position, window, cx);
5587 }
5588 } else {
5589 follower_state.active_view_id = None;
5590 }
5591
5592 self.leader_updated(CollaboratorId::Agent, window, cx);
5593 }
5594
5595 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
5596 let mut is_project_item = true;
5597 let mut update = proto::UpdateActiveView::default();
5598 if window.is_window_active() {
5599 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
5600
5601 if let Some(item) = active_item
5602 && item.item_focus_handle(cx).contains_focused(window, cx)
5603 {
5604 let leader_id = self
5605 .pane_for(&*item)
5606 .and_then(|pane| self.leader_for_pane(&pane));
5607 let leader_peer_id = match leader_id {
5608 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5609 Some(CollaboratorId::Agent) | None => None,
5610 };
5611
5612 if let Some(item) = item.to_followable_item_handle(cx) {
5613 let id = item
5614 .remote_id(&self.app_state.client, window, cx)
5615 .map(|id| id.to_proto());
5616
5617 if let Some(id) = id
5618 && let Some(variant) = item.to_state_proto(window, cx)
5619 {
5620 let view = Some(proto::View {
5621 id,
5622 leader_id: leader_peer_id,
5623 variant: Some(variant),
5624 panel_id: panel_id.map(|id| id as i32),
5625 });
5626
5627 is_project_item = item.is_project_item(window, cx);
5628 update = proto::UpdateActiveView { view };
5629 };
5630 }
5631 }
5632 }
5633
5634 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
5635 if active_view_id != self.last_active_view_id.as_ref() {
5636 self.last_active_view_id = active_view_id.cloned();
5637 self.update_followers(
5638 is_project_item,
5639 proto::update_followers::Variant::UpdateActiveView(update),
5640 window,
5641 cx,
5642 );
5643 }
5644 }
5645
5646 fn active_item_for_followers(
5647 &self,
5648 window: &mut Window,
5649 cx: &mut App,
5650 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
5651 let mut active_item = None;
5652 let mut panel_id = None;
5653 for dock in self.all_docks() {
5654 if dock.focus_handle(cx).contains_focused(window, cx)
5655 && let Some(panel) = dock.read(cx).active_panel()
5656 && let Some(pane) = panel.pane(cx)
5657 && let Some(item) = pane.read(cx).active_item()
5658 {
5659 active_item = Some(item);
5660 panel_id = panel.remote_id();
5661 break;
5662 }
5663 }
5664
5665 if active_item.is_none() {
5666 active_item = self.active_pane().read(cx).active_item();
5667 }
5668 (active_item, panel_id)
5669 }
5670
5671 fn update_followers(
5672 &self,
5673 project_only: bool,
5674 update: proto::update_followers::Variant,
5675 _: &mut Window,
5676 cx: &mut App,
5677 ) -> Option<()> {
5678 // If this update only applies to for followers in the current project,
5679 // then skip it unless this project is shared. If it applies to all
5680 // followers, regardless of project, then set `project_id` to none,
5681 // indicating that it goes to all followers.
5682 let project_id = if project_only {
5683 Some(self.project.read(cx).remote_id()?)
5684 } else {
5685 None
5686 };
5687 self.app_state().workspace_store.update(cx, |store, cx| {
5688 store.update_followers(project_id, update, cx)
5689 })
5690 }
5691
5692 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
5693 self.follower_states.iter().find_map(|(leader_id, state)| {
5694 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
5695 Some(*leader_id)
5696 } else {
5697 None
5698 }
5699 })
5700 }
5701
5702 fn leader_updated(
5703 &mut self,
5704 leader_id: impl Into<CollaboratorId>,
5705 window: &mut Window,
5706 cx: &mut Context<Self>,
5707 ) -> Option<Box<dyn ItemHandle>> {
5708 cx.notify();
5709
5710 let leader_id = leader_id.into();
5711 let (panel_id, item) = match leader_id {
5712 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
5713 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
5714 };
5715
5716 let state = self.follower_states.get(&leader_id)?;
5717 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
5718 let pane;
5719 if let Some(panel_id) = panel_id {
5720 pane = self
5721 .activate_panel_for_proto_id(panel_id, window, cx)?
5722 .pane(cx)?;
5723 let state = self.follower_states.get_mut(&leader_id)?;
5724 state.dock_pane = Some(pane.clone());
5725 } else {
5726 pane = state.center_pane.clone();
5727 let state = self.follower_states.get_mut(&leader_id)?;
5728 if let Some(dock_pane) = state.dock_pane.take() {
5729 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
5730 }
5731 }
5732
5733 pane.update(cx, |pane, cx| {
5734 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
5735 if let Some(index) = pane.index_for_item(item.as_ref()) {
5736 pane.activate_item(index, false, false, window, cx);
5737 } else {
5738 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
5739 }
5740
5741 if focus_active_item {
5742 pane.focus_active_item(window, cx)
5743 }
5744 });
5745
5746 Some(item)
5747 }
5748
5749 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
5750 let state = self.follower_states.get(&CollaboratorId::Agent)?;
5751 let active_view_id = state.active_view_id?;
5752 Some(
5753 state
5754 .items_by_leader_view_id
5755 .get(&active_view_id)?
5756 .view
5757 .boxed_clone(),
5758 )
5759 }
5760
5761 fn active_item_for_peer(
5762 &self,
5763 peer_id: PeerId,
5764 window: &mut Window,
5765 cx: &mut Context<Self>,
5766 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
5767 let call = self.active_call()?;
5768 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
5769 let leader_in_this_app;
5770 let leader_in_this_project;
5771 match participant.location {
5772 ParticipantLocation::SharedProject { project_id } => {
5773 leader_in_this_app = true;
5774 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
5775 }
5776 ParticipantLocation::UnsharedProject => {
5777 leader_in_this_app = true;
5778 leader_in_this_project = false;
5779 }
5780 ParticipantLocation::External => {
5781 leader_in_this_app = false;
5782 leader_in_this_project = false;
5783 }
5784 };
5785 let state = self.follower_states.get(&peer_id.into())?;
5786 let mut item_to_activate = None;
5787 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
5788 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
5789 && (leader_in_this_project || !item.view.is_project_item(window, cx))
5790 {
5791 item_to_activate = Some((item.location, item.view.boxed_clone()));
5792 }
5793 } else if let Some(shared_screen) =
5794 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
5795 {
5796 item_to_activate = Some((None, Box::new(shared_screen)));
5797 }
5798 item_to_activate
5799 }
5800
5801 fn shared_screen_for_peer(
5802 &self,
5803 peer_id: PeerId,
5804 pane: &Entity<Pane>,
5805 window: &mut Window,
5806 cx: &mut App,
5807 ) -> Option<Entity<SharedScreen>> {
5808 self.active_call()?
5809 .create_shared_screen(peer_id, pane, window, cx)
5810 }
5811
5812 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5813 if window.is_window_active() {
5814 self.update_active_view_for_followers(window, cx);
5815
5816 if let Some(database_id) = self.database_id {
5817 cx.background_spawn(persistence::DB.update_timestamp(database_id))
5818 .detach();
5819 }
5820 } else {
5821 for pane in &self.panes {
5822 pane.update(cx, |pane, cx| {
5823 if let Some(item) = pane.active_item() {
5824 item.workspace_deactivated(window, cx);
5825 }
5826 for item in pane.items() {
5827 if matches!(
5828 item.workspace_settings(cx).autosave,
5829 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
5830 ) {
5831 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
5832 .detach_and_log_err(cx);
5833 }
5834 }
5835 });
5836 }
5837 }
5838 }
5839
5840 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
5841 self.active_call.as_ref().map(|(call, _)| &*call.0)
5842 }
5843
5844 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
5845 self.active_call.as_ref().map(|(call, _)| call.clone())
5846 }
5847
5848 fn on_active_call_event(
5849 &mut self,
5850 event: &ActiveCallEvent,
5851 window: &mut Window,
5852 cx: &mut Context<Self>,
5853 ) {
5854 match event {
5855 ActiveCallEvent::ParticipantLocationChanged { participant_id }
5856 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
5857 self.leader_updated(participant_id, window, cx);
5858 }
5859 }
5860 }
5861
5862 pub fn database_id(&self) -> Option<WorkspaceId> {
5863 self.database_id
5864 }
5865
5866 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
5867 self.database_id = Some(id);
5868 }
5869
5870 pub fn session_id(&self) -> Option<String> {
5871 self.session_id.clone()
5872 }
5873
5874 /// Bypass the 200ms serialization throttle and write workspace state to
5875 /// the DB immediately. Returns a task the caller can await to ensure the
5876 /// write completes. Used by the quit handler so the most recent state
5877 /// isn't lost to a pending throttle timer when the process exits.
5878 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
5879 self._schedule_serialize_workspace.take();
5880 self._serialize_workspace_task.take();
5881 self.serialize_workspace_internal(window, cx)
5882 }
5883
5884 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
5885 let project = self.project().read(cx);
5886 project
5887 .visible_worktrees(cx)
5888 .map(|worktree| worktree.read(cx).abs_path())
5889 .collect::<Vec<_>>()
5890 }
5891
5892 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
5893 match member {
5894 Member::Axis(PaneAxis { members, .. }) => {
5895 for child in members.iter() {
5896 self.remove_panes(child.clone(), window, cx)
5897 }
5898 }
5899 Member::Pane(pane) => {
5900 self.force_remove_pane(&pane, &None, window, cx);
5901 }
5902 }
5903 }
5904
5905 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
5906 self.session_id.take();
5907 self.serialize_workspace_internal(window, cx)
5908 }
5909
5910 fn force_remove_pane(
5911 &mut self,
5912 pane: &Entity<Pane>,
5913 focus_on: &Option<Entity<Pane>>,
5914 window: &mut Window,
5915 cx: &mut Context<Workspace>,
5916 ) {
5917 self.panes.retain(|p| p != pane);
5918 if let Some(focus_on) = focus_on {
5919 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
5920 } else if self.active_pane() == pane {
5921 self.panes
5922 .last()
5923 .unwrap()
5924 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
5925 }
5926 if self.last_active_center_pane == Some(pane.downgrade()) {
5927 self.last_active_center_pane = None;
5928 }
5929 cx.notify();
5930 }
5931
5932 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5933 if self._schedule_serialize_workspace.is_none() {
5934 self._schedule_serialize_workspace =
5935 Some(cx.spawn_in(window, async move |this, cx| {
5936 cx.background_executor()
5937 .timer(SERIALIZATION_THROTTLE_TIME)
5938 .await;
5939 this.update_in(cx, |this, window, cx| {
5940 this._serialize_workspace_task =
5941 Some(this.serialize_workspace_internal(window, cx));
5942 this._schedule_serialize_workspace.take();
5943 })
5944 .log_err();
5945 }));
5946 }
5947 }
5948
5949 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
5950 let Some(database_id) = self.database_id() else {
5951 return Task::ready(());
5952 };
5953
5954 fn serialize_pane_handle(
5955 pane_handle: &Entity<Pane>,
5956 window: &mut Window,
5957 cx: &mut App,
5958 ) -> SerializedPane {
5959 let (items, active, pinned_count) = {
5960 let pane = pane_handle.read(cx);
5961 let active_item_id = pane.active_item().map(|item| item.item_id());
5962 (
5963 pane.items()
5964 .filter_map(|handle| {
5965 let handle = handle.to_serializable_item_handle(cx)?;
5966
5967 Some(SerializedItem {
5968 kind: Arc::from(handle.serialized_item_kind()),
5969 item_id: handle.item_id().as_u64(),
5970 active: Some(handle.item_id()) == active_item_id,
5971 preview: pane.is_active_preview_item(handle.item_id()),
5972 })
5973 })
5974 .collect::<Vec<_>>(),
5975 pane.has_focus(window, cx),
5976 pane.pinned_count(),
5977 )
5978 };
5979
5980 SerializedPane::new(items, active, pinned_count)
5981 }
5982
5983 fn build_serialized_pane_group(
5984 pane_group: &Member,
5985 window: &mut Window,
5986 cx: &mut App,
5987 ) -> SerializedPaneGroup {
5988 match pane_group {
5989 Member::Axis(PaneAxis {
5990 axis,
5991 members,
5992 flexes,
5993 bounding_boxes: _,
5994 }) => SerializedPaneGroup::Group {
5995 axis: SerializedAxis(*axis),
5996 children: members
5997 .iter()
5998 .map(|member| build_serialized_pane_group(member, window, cx))
5999 .collect::<Vec<_>>(),
6000 flexes: Some(flexes.lock().clone()),
6001 },
6002 Member::Pane(pane_handle) => {
6003 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6004 }
6005 }
6006 }
6007
6008 fn build_serialized_docks(
6009 this: &Workspace,
6010 window: &mut Window,
6011 cx: &mut App,
6012 ) -> DockStructure {
6013 let left_dock = this.left_dock.read(cx);
6014 let left_visible = left_dock.is_open();
6015 let left_active_panel = left_dock
6016 .active_panel()
6017 .map(|panel| panel.persistent_name().to_string());
6018 let left_dock_zoom = left_dock
6019 .active_panel()
6020 .map(|panel| panel.is_zoomed(window, cx))
6021 .unwrap_or(false);
6022
6023 let right_dock = this.right_dock.read(cx);
6024 let right_visible = right_dock.is_open();
6025 let right_active_panel = right_dock
6026 .active_panel()
6027 .map(|panel| panel.persistent_name().to_string());
6028 let right_dock_zoom = right_dock
6029 .active_panel()
6030 .map(|panel| panel.is_zoomed(window, cx))
6031 .unwrap_or(false);
6032
6033 let bottom_dock = this.bottom_dock.read(cx);
6034 let bottom_visible = bottom_dock.is_open();
6035 let bottom_active_panel = bottom_dock
6036 .active_panel()
6037 .map(|panel| panel.persistent_name().to_string());
6038 let bottom_dock_zoom = bottom_dock
6039 .active_panel()
6040 .map(|panel| panel.is_zoomed(window, cx))
6041 .unwrap_or(false);
6042
6043 DockStructure {
6044 left: DockData {
6045 visible: left_visible,
6046 active_panel: left_active_panel,
6047 zoom: left_dock_zoom,
6048 },
6049 right: DockData {
6050 visible: right_visible,
6051 active_panel: right_active_panel,
6052 zoom: right_dock_zoom,
6053 },
6054 bottom: DockData {
6055 visible: bottom_visible,
6056 active_panel: bottom_active_panel,
6057 zoom: bottom_dock_zoom,
6058 },
6059 }
6060 }
6061
6062 match self.workspace_location(cx) {
6063 WorkspaceLocation::Location(location, paths) => {
6064 let breakpoints = self.project.update(cx, |project, cx| {
6065 project
6066 .breakpoint_store()
6067 .read(cx)
6068 .all_source_breakpoints(cx)
6069 });
6070 let user_toolchains = self
6071 .project
6072 .read(cx)
6073 .user_toolchains(cx)
6074 .unwrap_or_default();
6075
6076 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6077 let docks = build_serialized_docks(self, window, cx);
6078 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6079
6080 let serialized_workspace = SerializedWorkspace {
6081 id: database_id,
6082 location,
6083 paths,
6084 center_group,
6085 window_bounds,
6086 display: Default::default(),
6087 docks,
6088 centered_layout: self.centered_layout,
6089 session_id: self.session_id.clone(),
6090 breakpoints,
6091 window_id: Some(window.window_handle().window_id().as_u64()),
6092 user_toolchains,
6093 };
6094
6095 window.spawn(cx, async move |_| {
6096 persistence::DB.save_workspace(serialized_workspace).await;
6097 })
6098 }
6099 WorkspaceLocation::DetachFromSession => {
6100 let window_bounds = SerializedWindowBounds(window.window_bounds());
6101 let display = window.display(cx).and_then(|d| d.uuid().ok());
6102 // Save dock state for empty local workspaces
6103 let docks = build_serialized_docks(self, window, cx);
6104 window.spawn(cx, async move |_| {
6105 persistence::DB
6106 .set_window_open_status(
6107 database_id,
6108 window_bounds,
6109 display.unwrap_or_default(),
6110 )
6111 .await
6112 .log_err();
6113 persistence::DB
6114 .set_session_id(database_id, None)
6115 .await
6116 .log_err();
6117 persistence::write_default_dock_state(docks).await.log_err();
6118 })
6119 }
6120 WorkspaceLocation::None => {
6121 // Save dock state for empty non-local workspaces
6122 let docks = build_serialized_docks(self, window, cx);
6123 window.spawn(cx, async move |_| {
6124 persistence::write_default_dock_state(docks).await.log_err();
6125 })
6126 }
6127 }
6128 }
6129
6130 fn has_any_items_open(&self, cx: &App) -> bool {
6131 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6132 }
6133
6134 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6135 let paths = PathList::new(&self.root_paths(cx));
6136 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6137 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6138 } else if self.project.read(cx).is_local() {
6139 if !paths.is_empty() || self.has_any_items_open(cx) {
6140 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6141 } else {
6142 WorkspaceLocation::DetachFromSession
6143 }
6144 } else {
6145 WorkspaceLocation::None
6146 }
6147 }
6148
6149 fn update_history(&self, cx: &mut App) {
6150 let Some(id) = self.database_id() else {
6151 return;
6152 };
6153 if !self.project.read(cx).is_local() {
6154 return;
6155 }
6156 if let Some(manager) = HistoryManager::global(cx) {
6157 let paths = PathList::new(&self.root_paths(cx));
6158 manager.update(cx, |this, cx| {
6159 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6160 });
6161 }
6162 }
6163
6164 async fn serialize_items(
6165 this: &WeakEntity<Self>,
6166 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6167 cx: &mut AsyncWindowContext,
6168 ) -> Result<()> {
6169 const CHUNK_SIZE: usize = 200;
6170
6171 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6172
6173 while let Some(items_received) = serializable_items.next().await {
6174 let unique_items =
6175 items_received
6176 .into_iter()
6177 .fold(HashMap::default(), |mut acc, item| {
6178 acc.entry(item.item_id()).or_insert(item);
6179 acc
6180 });
6181
6182 // We use into_iter() here so that the references to the items are moved into
6183 // the tasks and not kept alive while we're sleeping.
6184 for (_, item) in unique_items.into_iter() {
6185 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6186 item.serialize(workspace, false, window, cx)
6187 }) {
6188 cx.background_spawn(async move { task.await.log_err() })
6189 .detach();
6190 }
6191 }
6192
6193 cx.background_executor()
6194 .timer(SERIALIZATION_THROTTLE_TIME)
6195 .await;
6196 }
6197
6198 Ok(())
6199 }
6200
6201 pub(crate) fn enqueue_item_serialization(
6202 &mut self,
6203 item: Box<dyn SerializableItemHandle>,
6204 ) -> Result<()> {
6205 self.serializable_items_tx
6206 .unbounded_send(item)
6207 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6208 }
6209
6210 pub(crate) fn load_workspace(
6211 serialized_workspace: SerializedWorkspace,
6212 paths_to_open: Vec<Option<ProjectPath>>,
6213 window: &mut Window,
6214 cx: &mut Context<Workspace>,
6215 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6216 cx.spawn_in(window, async move |workspace, cx| {
6217 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6218
6219 let mut center_group = None;
6220 let mut center_items = None;
6221
6222 // Traverse the splits tree and add to things
6223 if let Some((group, active_pane, items)) = serialized_workspace
6224 .center_group
6225 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6226 .await
6227 {
6228 center_items = Some(items);
6229 center_group = Some((group, active_pane))
6230 }
6231
6232 let mut items_by_project_path = HashMap::default();
6233 let mut item_ids_by_kind = HashMap::default();
6234 let mut all_deserialized_items = Vec::default();
6235 cx.update(|_, cx| {
6236 for item in center_items.unwrap_or_default().into_iter().flatten() {
6237 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6238 item_ids_by_kind
6239 .entry(serializable_item_handle.serialized_item_kind())
6240 .or_insert(Vec::new())
6241 .push(item.item_id().as_u64() as ItemId);
6242 }
6243
6244 if let Some(project_path) = item.project_path(cx) {
6245 items_by_project_path.insert(project_path, item.clone());
6246 }
6247 all_deserialized_items.push(item);
6248 }
6249 })?;
6250
6251 let opened_items = paths_to_open
6252 .into_iter()
6253 .map(|path_to_open| {
6254 path_to_open
6255 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6256 })
6257 .collect::<Vec<_>>();
6258
6259 // Remove old panes from workspace panes list
6260 workspace.update_in(cx, |workspace, window, cx| {
6261 if let Some((center_group, active_pane)) = center_group {
6262 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6263
6264 // Swap workspace center group
6265 workspace.center = PaneGroup::with_root(center_group);
6266 workspace.center.set_is_center(true);
6267 workspace.center.mark_positions(cx);
6268
6269 if let Some(active_pane) = active_pane {
6270 workspace.set_active_pane(&active_pane, window, cx);
6271 cx.focus_self(window);
6272 } else {
6273 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6274 }
6275 }
6276
6277 let docks = serialized_workspace.docks;
6278
6279 for (dock, serialized_dock) in [
6280 (&mut workspace.right_dock, docks.right),
6281 (&mut workspace.left_dock, docks.left),
6282 (&mut workspace.bottom_dock, docks.bottom),
6283 ]
6284 .iter_mut()
6285 {
6286 dock.update(cx, |dock, cx| {
6287 dock.serialized_dock = Some(serialized_dock.clone());
6288 dock.restore_state(window, cx);
6289 });
6290 }
6291
6292 cx.notify();
6293 })?;
6294
6295 let _ = project
6296 .update(cx, |project, cx| {
6297 project
6298 .breakpoint_store()
6299 .update(cx, |breakpoint_store, cx| {
6300 breakpoint_store
6301 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6302 })
6303 })
6304 .await;
6305
6306 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6307 // after loading the items, we might have different items and in order to avoid
6308 // the database filling up, we delete items that haven't been loaded now.
6309 //
6310 // The items that have been loaded, have been saved after they've been added to the workspace.
6311 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6312 item_ids_by_kind
6313 .into_iter()
6314 .map(|(item_kind, loaded_items)| {
6315 SerializableItemRegistry::cleanup(
6316 item_kind,
6317 serialized_workspace.id,
6318 loaded_items,
6319 window,
6320 cx,
6321 )
6322 .log_err()
6323 })
6324 .collect::<Vec<_>>()
6325 })?;
6326
6327 futures::future::join_all(clean_up_tasks).await;
6328
6329 workspace
6330 .update_in(cx, |workspace, window, cx| {
6331 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6332 workspace.serialize_workspace_internal(window, cx).detach();
6333
6334 // Ensure that we mark the window as edited if we did load dirty items
6335 workspace.update_window_edited(window, cx);
6336 })
6337 .ok();
6338
6339 Ok(opened_items)
6340 })
6341 }
6342
6343 fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6344 self.add_workspace_actions_listeners(div, window, cx)
6345 .on_action(cx.listener(
6346 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6347 for action in &action_sequence.0 {
6348 window.dispatch_action(action.boxed_clone(), cx);
6349 }
6350 },
6351 ))
6352 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6353 .on_action(cx.listener(Self::close_all_items_and_panes))
6354 .on_action(cx.listener(Self::close_item_in_all_panes))
6355 .on_action(cx.listener(Self::save_all))
6356 .on_action(cx.listener(Self::send_keystrokes))
6357 .on_action(cx.listener(Self::add_folder_to_project))
6358 .on_action(cx.listener(Self::follow_next_collaborator))
6359 .on_action(cx.listener(Self::close_window))
6360 .on_action(cx.listener(Self::activate_pane_at_index))
6361 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6362 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6363 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6364 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6365 let pane = workspace.active_pane().clone();
6366 workspace.unfollow_in_pane(&pane, window, cx);
6367 }))
6368 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6369 workspace
6370 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6371 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6372 }))
6373 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6374 workspace
6375 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6376 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6377 }))
6378 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6379 workspace
6380 .save_active_item(SaveIntent::SaveAs, window, cx)
6381 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6382 }))
6383 .on_action(
6384 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6385 workspace.activate_previous_pane(window, cx)
6386 }),
6387 )
6388 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6389 workspace.activate_next_pane(window, cx)
6390 }))
6391 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6392 workspace.activate_last_pane(window, cx)
6393 }))
6394 .on_action(
6395 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6396 workspace.activate_next_window(cx)
6397 }),
6398 )
6399 .on_action(
6400 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6401 workspace.activate_previous_window(cx)
6402 }),
6403 )
6404 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6405 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6406 }))
6407 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6408 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6409 }))
6410 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6411 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6412 }))
6413 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6414 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6415 }))
6416 .on_action(cx.listener(
6417 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6418 workspace.move_item_to_pane_in_direction(action, window, cx)
6419 },
6420 ))
6421 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6422 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6423 }))
6424 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6425 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6426 }))
6427 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6428 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6429 }))
6430 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6431 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6432 }))
6433 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6434 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6435 SplitDirection::Down,
6436 SplitDirection::Up,
6437 SplitDirection::Right,
6438 SplitDirection::Left,
6439 ];
6440 for dir in DIRECTION_PRIORITY {
6441 if workspace.find_pane_in_direction(dir, cx).is_some() {
6442 workspace.swap_pane_in_direction(dir, cx);
6443 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6444 break;
6445 }
6446 }
6447 }))
6448 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6449 workspace.move_pane_to_border(SplitDirection::Left, cx)
6450 }))
6451 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6452 workspace.move_pane_to_border(SplitDirection::Right, cx)
6453 }))
6454 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6455 workspace.move_pane_to_border(SplitDirection::Up, cx)
6456 }))
6457 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6458 workspace.move_pane_to_border(SplitDirection::Down, cx)
6459 }))
6460 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6461 this.toggle_dock(DockPosition::Left, window, cx);
6462 }))
6463 .on_action(cx.listener(
6464 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6465 workspace.toggle_dock(DockPosition::Right, window, cx);
6466 },
6467 ))
6468 .on_action(cx.listener(
6469 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6470 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6471 },
6472 ))
6473 .on_action(cx.listener(
6474 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6475 if !workspace.close_active_dock(window, cx) {
6476 cx.propagate();
6477 }
6478 },
6479 ))
6480 .on_action(
6481 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6482 workspace.close_all_docks(window, cx);
6483 }),
6484 )
6485 .on_action(cx.listener(Self::toggle_all_docks))
6486 .on_action(cx.listener(
6487 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6488 workspace.clear_all_notifications(cx);
6489 },
6490 ))
6491 .on_action(cx.listener(
6492 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6493 workspace.clear_navigation_history(window, cx);
6494 },
6495 ))
6496 .on_action(cx.listener(
6497 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6498 if let Some((notification_id, _)) = workspace.notifications.pop() {
6499 workspace.suppress_notification(¬ification_id, cx);
6500 }
6501 },
6502 ))
6503 .on_action(cx.listener(
6504 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
6505 workspace.show_worktree_trust_security_modal(true, window, cx);
6506 },
6507 ))
6508 .on_action(
6509 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
6510 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
6511 trusted_worktrees.update(cx, |trusted_worktrees, _| {
6512 trusted_worktrees.clear_trusted_paths()
6513 });
6514 let clear_task = persistence::DB.clear_trusted_worktrees();
6515 cx.spawn(async move |_, cx| {
6516 if clear_task.await.log_err().is_some() {
6517 cx.update(|cx| reload(cx));
6518 }
6519 })
6520 .detach();
6521 }
6522 }),
6523 )
6524 .on_action(cx.listener(
6525 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
6526 workspace.reopen_closed_item(window, cx).detach();
6527 },
6528 ))
6529 .on_action(cx.listener(
6530 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
6531 for dock in workspace.all_docks() {
6532 if dock.focus_handle(cx).contains_focused(window, cx) {
6533 let Some(panel) = dock.read(cx).active_panel() else {
6534 return;
6535 };
6536
6537 // Set to `None`, then the size will fall back to the default.
6538 panel.clone().set_size(None, window, cx);
6539
6540 return;
6541 }
6542 }
6543 },
6544 ))
6545 .on_action(cx.listener(
6546 |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
6547 for dock in workspace.all_docks() {
6548 if let Some(panel) = dock.read(cx).visible_panel() {
6549 // Set to `None`, then the size will fall back to the default.
6550 panel.clone().set_size(None, window, cx);
6551 }
6552 }
6553 },
6554 ))
6555 .on_action(cx.listener(
6556 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
6557 adjust_active_dock_size_by_px(
6558 px_with_ui_font_fallback(act.px, cx),
6559 workspace,
6560 window,
6561 cx,
6562 );
6563 },
6564 ))
6565 .on_action(cx.listener(
6566 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
6567 adjust_active_dock_size_by_px(
6568 px_with_ui_font_fallback(act.px, cx) * -1.,
6569 workspace,
6570 window,
6571 cx,
6572 );
6573 },
6574 ))
6575 .on_action(cx.listener(
6576 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
6577 adjust_open_docks_size_by_px(
6578 px_with_ui_font_fallback(act.px, cx),
6579 workspace,
6580 window,
6581 cx,
6582 );
6583 },
6584 ))
6585 .on_action(cx.listener(
6586 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
6587 adjust_open_docks_size_by_px(
6588 px_with_ui_font_fallback(act.px, cx) * -1.,
6589 workspace,
6590 window,
6591 cx,
6592 );
6593 },
6594 ))
6595 .on_action(cx.listener(Workspace::toggle_centered_layout))
6596 .on_action(cx.listener(
6597 |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
6598 if let Some(active_dock) = workspace.active_dock(window, cx) {
6599 let dock = active_dock.read(cx);
6600 if let Some(active_panel) = dock.active_panel() {
6601 if active_panel.pane(cx).is_none() {
6602 let mut recent_pane: Option<Entity<Pane>> = None;
6603 let mut recent_timestamp = 0;
6604 for pane_handle in workspace.panes() {
6605 let pane = pane_handle.read(cx);
6606 for entry in pane.activation_history() {
6607 if entry.timestamp > recent_timestamp {
6608 recent_timestamp = entry.timestamp;
6609 recent_pane = Some(pane_handle.clone());
6610 }
6611 }
6612 }
6613
6614 if let Some(pane) = recent_pane {
6615 pane.update(cx, |pane, cx| {
6616 let current_index = pane.active_item_index();
6617 let items_len = pane.items_len();
6618 if items_len > 0 {
6619 let next_index = if current_index + 1 < items_len {
6620 current_index + 1
6621 } else {
6622 0
6623 };
6624 pane.activate_item(
6625 next_index, false, false, window, cx,
6626 );
6627 }
6628 });
6629 return;
6630 }
6631 }
6632 }
6633 }
6634 cx.propagate();
6635 },
6636 ))
6637 .on_action(cx.listener(
6638 |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
6639 if let Some(active_dock) = workspace.active_dock(window, cx) {
6640 let dock = active_dock.read(cx);
6641 if let Some(active_panel) = dock.active_panel() {
6642 if active_panel.pane(cx).is_none() {
6643 let mut recent_pane: Option<Entity<Pane>> = None;
6644 let mut recent_timestamp = 0;
6645 for pane_handle in workspace.panes() {
6646 let pane = pane_handle.read(cx);
6647 for entry in pane.activation_history() {
6648 if entry.timestamp > recent_timestamp {
6649 recent_timestamp = entry.timestamp;
6650 recent_pane = Some(pane_handle.clone());
6651 }
6652 }
6653 }
6654
6655 if let Some(pane) = recent_pane {
6656 pane.update(cx, |pane, cx| {
6657 let current_index = pane.active_item_index();
6658 let items_len = pane.items_len();
6659 if items_len > 0 {
6660 let prev_index = if current_index > 0 {
6661 current_index - 1
6662 } else {
6663 items_len.saturating_sub(1)
6664 };
6665 pane.activate_item(
6666 prev_index, false, false, window, cx,
6667 );
6668 }
6669 });
6670 return;
6671 }
6672 }
6673 }
6674 }
6675 cx.propagate();
6676 },
6677 ))
6678 .on_action(cx.listener(
6679 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
6680 if let Some(active_dock) = workspace.active_dock(window, cx) {
6681 let dock = active_dock.read(cx);
6682 if let Some(active_panel) = dock.active_panel() {
6683 if active_panel.pane(cx).is_none() {
6684 let active_pane = workspace.active_pane().clone();
6685 active_pane.update(cx, |pane, cx| {
6686 pane.close_active_item(action, window, cx)
6687 .detach_and_log_err(cx);
6688 });
6689 return;
6690 }
6691 }
6692 }
6693 cx.propagate();
6694 },
6695 ))
6696 .on_action(
6697 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
6698 let pane = workspace.active_pane().clone();
6699 if let Some(item) = pane.read(cx).active_item() {
6700 item.toggle_read_only(window, cx);
6701 }
6702 }),
6703 )
6704 .on_action(cx.listener(Workspace::cancel))
6705 }
6706
6707 #[cfg(any(test, feature = "test-support"))]
6708 pub fn set_random_database_id(&mut self) {
6709 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
6710 }
6711
6712 #[cfg(any(test, feature = "test-support"))]
6713 pub(crate) fn test_new(
6714 project: Entity<Project>,
6715 window: &mut Window,
6716 cx: &mut Context<Self>,
6717 ) -> Self {
6718 use node_runtime::NodeRuntime;
6719 use session::Session;
6720
6721 let client = project.read(cx).client();
6722 let user_store = project.read(cx).user_store();
6723 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
6724 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
6725 window.activate_window();
6726 let app_state = Arc::new(AppState {
6727 languages: project.read(cx).languages().clone(),
6728 workspace_store,
6729 client,
6730 user_store,
6731 fs: project.read(cx).fs().clone(),
6732 build_window_options: |_, _| Default::default(),
6733 node_runtime: NodeRuntime::unavailable(),
6734 session,
6735 });
6736 let workspace = Self::new(Default::default(), project, app_state, window, cx);
6737 workspace
6738 .active_pane
6739 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6740 workspace
6741 }
6742
6743 pub fn register_action<A: Action>(
6744 &mut self,
6745 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
6746 ) -> &mut Self {
6747 let callback = Arc::new(callback);
6748
6749 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
6750 let callback = callback.clone();
6751 div.on_action(cx.listener(move |workspace, event, window, cx| {
6752 (callback)(workspace, event, window, cx)
6753 }))
6754 }));
6755 self
6756 }
6757 pub fn register_action_renderer(
6758 &mut self,
6759 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
6760 ) -> &mut Self {
6761 self.workspace_actions.push(Box::new(callback));
6762 self
6763 }
6764
6765 fn add_workspace_actions_listeners(
6766 &self,
6767 mut div: Div,
6768 window: &mut Window,
6769 cx: &mut Context<Self>,
6770 ) -> Div {
6771 for action in self.workspace_actions.iter() {
6772 div = (action)(div, self, window, cx)
6773 }
6774 div
6775 }
6776
6777 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
6778 self.modal_layer.read(cx).has_active_modal()
6779 }
6780
6781 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
6782 self.modal_layer.read(cx).active_modal()
6783 }
6784
6785 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
6786 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
6787 /// If no modal is active, the new modal will be shown.
6788 ///
6789 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
6790 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
6791 /// will not be shown.
6792 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
6793 where
6794 B: FnOnce(&mut Window, &mut Context<V>) -> V,
6795 {
6796 self.modal_layer.update(cx, |modal_layer, cx| {
6797 modal_layer.toggle_modal(window, cx, build)
6798 })
6799 }
6800
6801 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
6802 self.modal_layer
6803 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
6804 }
6805
6806 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
6807 self.toast_layer
6808 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
6809 }
6810
6811 pub fn toggle_centered_layout(
6812 &mut self,
6813 _: &ToggleCenteredLayout,
6814 _: &mut Window,
6815 cx: &mut Context<Self>,
6816 ) {
6817 self.centered_layout = !self.centered_layout;
6818 if let Some(database_id) = self.database_id() {
6819 cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
6820 .detach_and_log_err(cx);
6821 }
6822 cx.notify();
6823 }
6824
6825 fn adjust_padding(padding: Option<f32>) -> f32 {
6826 padding
6827 .unwrap_or(CenteredPaddingSettings::default().0)
6828 .clamp(
6829 CenteredPaddingSettings::MIN_PADDING,
6830 CenteredPaddingSettings::MAX_PADDING,
6831 )
6832 }
6833
6834 fn render_dock(
6835 &self,
6836 position: DockPosition,
6837 dock: &Entity<Dock>,
6838 window: &mut Window,
6839 cx: &mut App,
6840 ) -> Option<Div> {
6841 if self.zoomed_position == Some(position) {
6842 return None;
6843 }
6844
6845 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
6846 let pane = panel.pane(cx)?;
6847 let follower_states = &self.follower_states;
6848 leader_border_for_pane(follower_states, &pane, window, cx)
6849 });
6850
6851 Some(
6852 div()
6853 .flex()
6854 .flex_none()
6855 .overflow_hidden()
6856 .child(dock.clone())
6857 .children(leader_border),
6858 )
6859 }
6860
6861 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
6862 window
6863 .root::<MultiWorkspace>()
6864 .flatten()
6865 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
6866 }
6867
6868 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
6869 self.zoomed.as_ref()
6870 }
6871
6872 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
6873 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
6874 return;
6875 };
6876 let windows = cx.windows();
6877 let next_window =
6878 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
6879 || {
6880 windows
6881 .iter()
6882 .cycle()
6883 .skip_while(|window| window.window_id() != current_window_id)
6884 .nth(1)
6885 },
6886 );
6887
6888 if let Some(window) = next_window {
6889 window
6890 .update(cx, |_, window, _| window.activate_window())
6891 .ok();
6892 }
6893 }
6894
6895 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
6896 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
6897 return;
6898 };
6899 let windows = cx.windows();
6900 let prev_window =
6901 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
6902 || {
6903 windows
6904 .iter()
6905 .rev()
6906 .cycle()
6907 .skip_while(|window| window.window_id() != current_window_id)
6908 .nth(1)
6909 },
6910 );
6911
6912 if let Some(window) = prev_window {
6913 window
6914 .update(cx, |_, window, _| window.activate_window())
6915 .ok();
6916 }
6917 }
6918
6919 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
6920 if cx.stop_active_drag(window) {
6921 } else if let Some((notification_id, _)) = self.notifications.pop() {
6922 dismiss_app_notification(¬ification_id, cx);
6923 } else {
6924 cx.propagate();
6925 }
6926 }
6927
6928 fn adjust_dock_size_by_px(
6929 &mut self,
6930 panel_size: Pixels,
6931 dock_pos: DockPosition,
6932 px: Pixels,
6933 window: &mut Window,
6934 cx: &mut Context<Self>,
6935 ) {
6936 match dock_pos {
6937 DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
6938 DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
6939 DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
6940 }
6941 }
6942
6943 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6944 let size = new_size.min(self.bounds.right() - RESIZE_HANDLE_SIZE);
6945
6946 self.left_dock.update(cx, |left_dock, cx| {
6947 if WorkspaceSettings::get_global(cx)
6948 .resize_all_panels_in_dock
6949 .contains(&DockPosition::Left)
6950 {
6951 left_dock.resize_all_panels(Some(size), window, cx);
6952 } else {
6953 left_dock.resize_active_panel(Some(size), window, cx);
6954 }
6955 });
6956 }
6957
6958 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6959 let mut size = new_size.max(self.bounds.left() - RESIZE_HANDLE_SIZE);
6960 self.left_dock.read_with(cx, |left_dock, cx| {
6961 let left_dock_size = left_dock
6962 .active_panel_size(window, cx)
6963 .unwrap_or(Pixels::ZERO);
6964 if left_dock_size + size > self.bounds.right() {
6965 size = self.bounds.right() - left_dock_size
6966 }
6967 });
6968 self.right_dock.update(cx, |right_dock, cx| {
6969 if WorkspaceSettings::get_global(cx)
6970 .resize_all_panels_in_dock
6971 .contains(&DockPosition::Right)
6972 {
6973 right_dock.resize_all_panels(Some(size), window, cx);
6974 } else {
6975 right_dock.resize_active_panel(Some(size), window, cx);
6976 }
6977 });
6978 }
6979
6980 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6981 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
6982 self.bottom_dock.update(cx, |bottom_dock, cx| {
6983 if WorkspaceSettings::get_global(cx)
6984 .resize_all_panels_in_dock
6985 .contains(&DockPosition::Bottom)
6986 {
6987 bottom_dock.resize_all_panels(Some(size), window, cx);
6988 } else {
6989 bottom_dock.resize_active_panel(Some(size), window, cx);
6990 }
6991 });
6992 }
6993
6994 fn toggle_edit_predictions_all_files(
6995 &mut self,
6996 _: &ToggleEditPrediction,
6997 _window: &mut Window,
6998 cx: &mut Context<Self>,
6999 ) {
7000 let fs = self.project().read(cx).fs().clone();
7001 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7002 update_settings_file(fs, cx, move |file, _| {
7003 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7004 });
7005 }
7006
7007 pub fn show_worktree_trust_security_modal(
7008 &mut self,
7009 toggle: bool,
7010 window: &mut Window,
7011 cx: &mut Context<Self>,
7012 ) {
7013 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7014 if toggle {
7015 security_modal.update(cx, |security_modal, cx| {
7016 security_modal.dismiss(cx);
7017 })
7018 } else {
7019 security_modal.update(cx, |security_modal, cx| {
7020 security_modal.refresh_restricted_paths(cx);
7021 });
7022 }
7023 } else {
7024 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7025 .map(|trusted_worktrees| {
7026 trusted_worktrees
7027 .read(cx)
7028 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7029 })
7030 .unwrap_or(false);
7031 if has_restricted_worktrees {
7032 let project = self.project().read(cx);
7033 let remote_host = project
7034 .remote_connection_options(cx)
7035 .map(RemoteHostLocation::from);
7036 let worktree_store = project.worktree_store().downgrade();
7037 self.toggle_modal(window, cx, |_, cx| {
7038 SecurityModal::new(worktree_store, remote_host, cx)
7039 });
7040 }
7041 }
7042 }
7043}
7044
7045pub trait AnyActiveCall {
7046 fn entity(&self) -> AnyEntity;
7047 fn is_in_room(&self, _: &App) -> bool;
7048 fn room_id(&self, _: &App) -> Option<u64>;
7049 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7050 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7051 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7052 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7053 fn is_sharing_project(&self, _: &App) -> bool;
7054 fn has_remote_participants(&self, _: &App) -> bool;
7055 fn local_participant_is_guest(&self, _: &App) -> bool;
7056 fn client(&self, _: &App) -> Arc<Client>;
7057 fn share_on_join(&self, _: &App) -> bool;
7058 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7059 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7060 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7061 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7062 fn join_project(
7063 &self,
7064 _: u64,
7065 _: Arc<LanguageRegistry>,
7066 _: Arc<dyn Fs>,
7067 _: &mut App,
7068 ) -> Task<Result<Entity<Project>>>;
7069 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7070 fn subscribe(
7071 &self,
7072 _: &mut Window,
7073 _: &mut Context<Workspace>,
7074 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7075 ) -> Subscription;
7076 fn create_shared_screen(
7077 &self,
7078 _: PeerId,
7079 _: &Entity<Pane>,
7080 _: &mut Window,
7081 _: &mut App,
7082 ) -> Option<Entity<SharedScreen>>;
7083}
7084
7085#[derive(Clone)]
7086pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7087impl Global for GlobalAnyActiveCall {}
7088
7089impl GlobalAnyActiveCall {
7090 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7091 cx.try_global()
7092 }
7093
7094 pub(crate) fn global(cx: &App) -> &Self {
7095 cx.global()
7096 }
7097}
7098/// Workspace-local view of a remote participant's location.
7099#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7100pub enum ParticipantLocation {
7101 SharedProject { project_id: u64 },
7102 UnsharedProject,
7103 External,
7104}
7105
7106impl ParticipantLocation {
7107 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7108 match location
7109 .and_then(|l| l.variant)
7110 .context("participant location was not provided")?
7111 {
7112 proto::participant_location::Variant::SharedProject(project) => {
7113 Ok(Self::SharedProject {
7114 project_id: project.id,
7115 })
7116 }
7117 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7118 proto::participant_location::Variant::External(_) => Ok(Self::External),
7119 }
7120 }
7121}
7122/// Workspace-local view of a remote collaborator's state.
7123/// This is the subset of `call::RemoteParticipant` that workspace needs.
7124#[derive(Clone)]
7125pub struct RemoteCollaborator {
7126 pub user: Arc<User>,
7127 pub peer_id: PeerId,
7128 pub location: ParticipantLocation,
7129 pub participant_index: ParticipantIndex,
7130}
7131
7132pub enum ActiveCallEvent {
7133 ParticipantLocationChanged { participant_id: PeerId },
7134 RemoteVideoTracksChanged { participant_id: PeerId },
7135}
7136
7137fn leader_border_for_pane(
7138 follower_states: &HashMap<CollaboratorId, FollowerState>,
7139 pane: &Entity<Pane>,
7140 _: &Window,
7141 cx: &App,
7142) -> Option<Div> {
7143 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7144 if state.pane() == pane {
7145 Some((*leader_id, state))
7146 } else {
7147 None
7148 }
7149 })?;
7150
7151 let mut leader_color = match leader_id {
7152 CollaboratorId::PeerId(leader_peer_id) => {
7153 let leader = GlobalAnyActiveCall::try_global(cx)?
7154 .0
7155 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7156
7157 cx.theme()
7158 .players()
7159 .color_for_participant(leader.participant_index.0)
7160 .cursor
7161 }
7162 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7163 };
7164 leader_color.fade_out(0.3);
7165 Some(
7166 div()
7167 .absolute()
7168 .size_full()
7169 .left_0()
7170 .top_0()
7171 .border_2()
7172 .border_color(leader_color),
7173 )
7174}
7175
7176fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7177 ZED_WINDOW_POSITION
7178 .zip(*ZED_WINDOW_SIZE)
7179 .map(|(position, size)| Bounds {
7180 origin: position,
7181 size,
7182 })
7183}
7184
7185fn open_items(
7186 serialized_workspace: Option<SerializedWorkspace>,
7187 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7188 window: &mut Window,
7189 cx: &mut Context<Workspace>,
7190) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7191 let restored_items = serialized_workspace.map(|serialized_workspace| {
7192 Workspace::load_workspace(
7193 serialized_workspace,
7194 project_paths_to_open
7195 .iter()
7196 .map(|(_, project_path)| project_path)
7197 .cloned()
7198 .collect(),
7199 window,
7200 cx,
7201 )
7202 });
7203
7204 cx.spawn_in(window, async move |workspace, cx| {
7205 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7206
7207 if let Some(restored_items) = restored_items {
7208 let restored_items = restored_items.await?;
7209
7210 let restored_project_paths = restored_items
7211 .iter()
7212 .filter_map(|item| {
7213 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7214 .ok()
7215 .flatten()
7216 })
7217 .collect::<HashSet<_>>();
7218
7219 for restored_item in restored_items {
7220 opened_items.push(restored_item.map(Ok));
7221 }
7222
7223 project_paths_to_open
7224 .iter_mut()
7225 .for_each(|(_, project_path)| {
7226 if let Some(project_path_to_open) = project_path
7227 && restored_project_paths.contains(project_path_to_open)
7228 {
7229 *project_path = None;
7230 }
7231 });
7232 } else {
7233 for _ in 0..project_paths_to_open.len() {
7234 opened_items.push(None);
7235 }
7236 }
7237 assert!(opened_items.len() == project_paths_to_open.len());
7238
7239 let tasks =
7240 project_paths_to_open
7241 .into_iter()
7242 .enumerate()
7243 .map(|(ix, (abs_path, project_path))| {
7244 let workspace = workspace.clone();
7245 cx.spawn(async move |cx| {
7246 let file_project_path = project_path?;
7247 let abs_path_task = workspace.update(cx, |workspace, cx| {
7248 workspace.project().update(cx, |project, cx| {
7249 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7250 })
7251 });
7252
7253 // We only want to open file paths here. If one of the items
7254 // here is a directory, it was already opened further above
7255 // with a `find_or_create_worktree`.
7256 if let Ok(task) = abs_path_task
7257 && task.await.is_none_or(|p| p.is_file())
7258 {
7259 return Some((
7260 ix,
7261 workspace
7262 .update_in(cx, |workspace, window, cx| {
7263 workspace.open_path(
7264 file_project_path,
7265 None,
7266 true,
7267 window,
7268 cx,
7269 )
7270 })
7271 .log_err()?
7272 .await,
7273 ));
7274 }
7275 None
7276 })
7277 });
7278
7279 let tasks = tasks.collect::<Vec<_>>();
7280
7281 let tasks = futures::future::join_all(tasks);
7282 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7283 opened_items[ix] = Some(path_open_result);
7284 }
7285
7286 Ok(opened_items)
7287 })
7288}
7289
7290enum ActivateInDirectionTarget {
7291 Pane(Entity<Pane>),
7292 Dock(Entity<Dock>),
7293}
7294
7295fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7296 window
7297 .update(cx, |multi_workspace, _, cx| {
7298 let workspace = multi_workspace.workspace().clone();
7299 workspace.update(cx, |workspace, cx| {
7300 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7301 struct DatabaseFailedNotification;
7302
7303 workspace.show_notification(
7304 NotificationId::unique::<DatabaseFailedNotification>(),
7305 cx,
7306 |cx| {
7307 cx.new(|cx| {
7308 MessageNotification::new("Failed to load the database file.", cx)
7309 .primary_message("File an Issue")
7310 .primary_icon(IconName::Plus)
7311 .primary_on_click(|window, cx| {
7312 window.dispatch_action(Box::new(FileBugReport), cx)
7313 })
7314 })
7315 },
7316 );
7317 }
7318 });
7319 })
7320 .log_err();
7321}
7322
7323fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7324 if val == 0 {
7325 ThemeSettings::get_global(cx).ui_font_size(cx)
7326 } else {
7327 px(val as f32)
7328 }
7329}
7330
7331fn adjust_active_dock_size_by_px(
7332 px: Pixels,
7333 workspace: &mut Workspace,
7334 window: &mut Window,
7335 cx: &mut Context<Workspace>,
7336) {
7337 let Some(active_dock) = workspace
7338 .all_docks()
7339 .into_iter()
7340 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7341 else {
7342 return;
7343 };
7344 let dock = active_dock.read(cx);
7345 let Some(panel_size) = dock.active_panel_size(window, cx) else {
7346 return;
7347 };
7348 let dock_pos = dock.position();
7349 workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
7350}
7351
7352fn adjust_open_docks_size_by_px(
7353 px: Pixels,
7354 workspace: &mut Workspace,
7355 window: &mut Window,
7356 cx: &mut Context<Workspace>,
7357) {
7358 let docks = workspace
7359 .all_docks()
7360 .into_iter()
7361 .filter_map(|dock| {
7362 if dock.read(cx).is_open() {
7363 let dock = dock.read(cx);
7364 let panel_size = dock.active_panel_size(window, cx)?;
7365 let dock_pos = dock.position();
7366 Some((panel_size, dock_pos, px))
7367 } else {
7368 None
7369 }
7370 })
7371 .collect::<Vec<_>>();
7372
7373 docks
7374 .into_iter()
7375 .for_each(|(panel_size, dock_pos, offset)| {
7376 workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
7377 });
7378}
7379
7380impl Focusable for Workspace {
7381 fn focus_handle(&self, cx: &App) -> FocusHandle {
7382 self.active_pane.focus_handle(cx)
7383 }
7384}
7385
7386#[derive(Clone)]
7387struct DraggedDock(DockPosition);
7388
7389impl Render for DraggedDock {
7390 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7391 gpui::Empty
7392 }
7393}
7394
7395impl Render for Workspace {
7396 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7397 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
7398 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
7399 log::info!("Rendered first frame");
7400 }
7401 let mut context = KeyContext::new_with_defaults();
7402 context.add("Workspace");
7403 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
7404 if let Some(status) = self
7405 .debugger_provider
7406 .as_ref()
7407 .and_then(|provider| provider.active_thread_state(cx))
7408 {
7409 match status {
7410 ThreadStatus::Running | ThreadStatus::Stepping => {
7411 context.add("debugger_running");
7412 }
7413 ThreadStatus::Stopped => context.add("debugger_stopped"),
7414 ThreadStatus::Exited | ThreadStatus::Ended => {}
7415 }
7416 }
7417
7418 if self.left_dock.read(cx).is_open() {
7419 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
7420 context.set("left_dock", active_panel.panel_key());
7421 }
7422 }
7423
7424 if self.right_dock.read(cx).is_open() {
7425 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
7426 context.set("right_dock", active_panel.panel_key());
7427 }
7428 }
7429
7430 if self.bottom_dock.read(cx).is_open() {
7431 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
7432 context.set("bottom_dock", active_panel.panel_key());
7433 }
7434 }
7435
7436 let centered_layout = self.centered_layout
7437 && self.center.panes().len() == 1
7438 && self.active_item(cx).is_some();
7439 let render_padding = |size| {
7440 (size > 0.0).then(|| {
7441 div()
7442 .h_full()
7443 .w(relative(size))
7444 .bg(cx.theme().colors().editor_background)
7445 .border_color(cx.theme().colors().pane_group_border)
7446 })
7447 };
7448 let paddings = if centered_layout {
7449 let settings = WorkspaceSettings::get_global(cx).centered_layout;
7450 (
7451 render_padding(Self::adjust_padding(
7452 settings.left_padding.map(|padding| padding.0),
7453 )),
7454 render_padding(Self::adjust_padding(
7455 settings.right_padding.map(|padding| padding.0),
7456 )),
7457 )
7458 } else {
7459 (None, None)
7460 };
7461 let ui_font = theme::setup_ui_font(window, cx);
7462
7463 let theme = cx.theme().clone();
7464 let colors = theme.colors();
7465 let notification_entities = self
7466 .notifications
7467 .iter()
7468 .map(|(_, notification)| notification.entity_id())
7469 .collect::<Vec<_>>();
7470 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
7471
7472 self.actions(div(), window, cx)
7473 .key_context(context)
7474 .relative()
7475 .size_full()
7476 .flex()
7477 .flex_col()
7478 .font(ui_font)
7479 .gap_0()
7480 .justify_start()
7481 .items_start()
7482 .text_color(colors.text)
7483 .overflow_hidden()
7484 .children(self.titlebar_item.clone())
7485 .on_modifiers_changed(move |_, _, cx| {
7486 for &id in ¬ification_entities {
7487 cx.notify(id);
7488 }
7489 })
7490 .child(
7491 div()
7492 .size_full()
7493 .relative()
7494 .flex_1()
7495 .flex()
7496 .flex_col()
7497 .child(
7498 div()
7499 .id("workspace")
7500 .bg(colors.background)
7501 .relative()
7502 .flex_1()
7503 .w_full()
7504 .flex()
7505 .flex_col()
7506 .overflow_hidden()
7507 .border_t_1()
7508 .border_b_1()
7509 .border_color(colors.border)
7510 .child({
7511 let this = cx.entity();
7512 canvas(
7513 move |bounds, window, cx| {
7514 this.update(cx, |this, cx| {
7515 let bounds_changed = this.bounds != bounds;
7516 this.bounds = bounds;
7517
7518 if bounds_changed {
7519 this.left_dock.update(cx, |dock, cx| {
7520 dock.clamp_panel_size(
7521 bounds.size.width,
7522 window,
7523 cx,
7524 )
7525 });
7526
7527 this.right_dock.update(cx, |dock, cx| {
7528 dock.clamp_panel_size(
7529 bounds.size.width,
7530 window,
7531 cx,
7532 )
7533 });
7534
7535 this.bottom_dock.update(cx, |dock, cx| {
7536 dock.clamp_panel_size(
7537 bounds.size.height,
7538 window,
7539 cx,
7540 )
7541 });
7542 }
7543 })
7544 },
7545 |_, _, _, _| {},
7546 )
7547 .absolute()
7548 .size_full()
7549 })
7550 .when(self.zoomed.is_none(), |this| {
7551 this.on_drag_move(cx.listener(
7552 move |workspace,
7553 e: &DragMoveEvent<DraggedDock>,
7554 window,
7555 cx| {
7556 if workspace.previous_dock_drag_coordinates
7557 != Some(e.event.position)
7558 {
7559 workspace.previous_dock_drag_coordinates =
7560 Some(e.event.position);
7561 match e.drag(cx).0 {
7562 DockPosition::Left => {
7563 workspace.resize_left_dock(
7564 e.event.position.x
7565 - workspace.bounds.left(),
7566 window,
7567 cx,
7568 );
7569 }
7570 DockPosition::Right => {
7571 workspace.resize_right_dock(
7572 workspace.bounds.right()
7573 - e.event.position.x,
7574 window,
7575 cx,
7576 );
7577 }
7578 DockPosition::Bottom => {
7579 workspace.resize_bottom_dock(
7580 workspace.bounds.bottom()
7581 - e.event.position.y,
7582 window,
7583 cx,
7584 );
7585 }
7586 };
7587 workspace.serialize_workspace(window, cx);
7588 }
7589 },
7590 ))
7591
7592 })
7593 .child({
7594 match bottom_dock_layout {
7595 BottomDockLayout::Full => div()
7596 .flex()
7597 .flex_col()
7598 .h_full()
7599 .child(
7600 div()
7601 .flex()
7602 .flex_row()
7603 .flex_1()
7604 .overflow_hidden()
7605 .children(self.render_dock(
7606 DockPosition::Left,
7607 &self.left_dock,
7608 window,
7609 cx,
7610 ))
7611
7612 .child(
7613 div()
7614 .flex()
7615 .flex_col()
7616 .flex_1()
7617 .overflow_hidden()
7618 .child(
7619 h_flex()
7620 .flex_1()
7621 .when_some(
7622 paddings.0,
7623 |this, p| {
7624 this.child(
7625 p.border_r_1(),
7626 )
7627 },
7628 )
7629 .child(self.center.render(
7630 self.zoomed.as_ref(),
7631 &PaneRenderContext {
7632 follower_states:
7633 &self.follower_states,
7634 active_call: self.active_call(),
7635 active_pane: &self.active_pane,
7636 app_state: &self.app_state,
7637 project: &self.project,
7638 workspace: &self.weak_self,
7639 },
7640 window,
7641 cx,
7642 ))
7643 .when_some(
7644 paddings.1,
7645 |this, p| {
7646 this.child(
7647 p.border_l_1(),
7648 )
7649 },
7650 ),
7651 ),
7652 )
7653
7654 .children(self.render_dock(
7655 DockPosition::Right,
7656 &self.right_dock,
7657 window,
7658 cx,
7659 )),
7660 )
7661 .child(div().w_full().children(self.render_dock(
7662 DockPosition::Bottom,
7663 &self.bottom_dock,
7664 window,
7665 cx
7666 ))),
7667
7668 BottomDockLayout::LeftAligned => div()
7669 .flex()
7670 .flex_row()
7671 .h_full()
7672 .child(
7673 div()
7674 .flex()
7675 .flex_col()
7676 .flex_1()
7677 .h_full()
7678 .child(
7679 div()
7680 .flex()
7681 .flex_row()
7682 .flex_1()
7683 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
7684
7685 .child(
7686 div()
7687 .flex()
7688 .flex_col()
7689 .flex_1()
7690 .overflow_hidden()
7691 .child(
7692 h_flex()
7693 .flex_1()
7694 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7695 .child(self.center.render(
7696 self.zoomed.as_ref(),
7697 &PaneRenderContext {
7698 follower_states:
7699 &self.follower_states,
7700 active_call: self.active_call(),
7701 active_pane: &self.active_pane,
7702 app_state: &self.app_state,
7703 project: &self.project,
7704 workspace: &self.weak_self,
7705 },
7706 window,
7707 cx,
7708 ))
7709 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7710 )
7711 )
7712
7713 )
7714 .child(
7715 div()
7716 .w_full()
7717 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7718 ),
7719 )
7720 .children(self.render_dock(
7721 DockPosition::Right,
7722 &self.right_dock,
7723 window,
7724 cx,
7725 )),
7726
7727 BottomDockLayout::RightAligned => div()
7728 .flex()
7729 .flex_row()
7730 .h_full()
7731 .children(self.render_dock(
7732 DockPosition::Left,
7733 &self.left_dock,
7734 window,
7735 cx,
7736 ))
7737
7738 .child(
7739 div()
7740 .flex()
7741 .flex_col()
7742 .flex_1()
7743 .h_full()
7744 .child(
7745 div()
7746 .flex()
7747 .flex_row()
7748 .flex_1()
7749 .child(
7750 div()
7751 .flex()
7752 .flex_col()
7753 .flex_1()
7754 .overflow_hidden()
7755 .child(
7756 h_flex()
7757 .flex_1()
7758 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7759 .child(self.center.render(
7760 self.zoomed.as_ref(),
7761 &PaneRenderContext {
7762 follower_states:
7763 &self.follower_states,
7764 active_call: self.active_call(),
7765 active_pane: &self.active_pane,
7766 app_state: &self.app_state,
7767 project: &self.project,
7768 workspace: &self.weak_self,
7769 },
7770 window,
7771 cx,
7772 ))
7773 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7774 )
7775 )
7776
7777 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
7778 )
7779 .child(
7780 div()
7781 .w_full()
7782 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7783 ),
7784 ),
7785
7786 BottomDockLayout::Contained => div()
7787 .flex()
7788 .flex_row()
7789 .h_full()
7790 .children(self.render_dock(
7791 DockPosition::Left,
7792 &self.left_dock,
7793 window,
7794 cx,
7795 ))
7796
7797 .child(
7798 div()
7799 .flex()
7800 .flex_col()
7801 .flex_1()
7802 .overflow_hidden()
7803 .child(
7804 h_flex()
7805 .flex_1()
7806 .when_some(paddings.0, |this, p| {
7807 this.child(p.border_r_1())
7808 })
7809 .child(self.center.render(
7810 self.zoomed.as_ref(),
7811 &PaneRenderContext {
7812 follower_states:
7813 &self.follower_states,
7814 active_call: self.active_call(),
7815 active_pane: &self.active_pane,
7816 app_state: &self.app_state,
7817 project: &self.project,
7818 workspace: &self.weak_self,
7819 },
7820 window,
7821 cx,
7822 ))
7823 .when_some(paddings.1, |this, p| {
7824 this.child(p.border_l_1())
7825 }),
7826 )
7827 .children(self.render_dock(
7828 DockPosition::Bottom,
7829 &self.bottom_dock,
7830 window,
7831 cx,
7832 )),
7833 )
7834
7835 .children(self.render_dock(
7836 DockPosition::Right,
7837 &self.right_dock,
7838 window,
7839 cx,
7840 )),
7841 }
7842 })
7843 .children(self.zoomed.as_ref().and_then(|view| {
7844 let zoomed_view = view.upgrade()?;
7845 let div = div()
7846 .occlude()
7847 .absolute()
7848 .overflow_hidden()
7849 .border_color(colors.border)
7850 .bg(colors.background)
7851 .child(zoomed_view)
7852 .inset_0()
7853 .shadow_lg();
7854
7855 if !WorkspaceSettings::get_global(cx).zoomed_padding {
7856 return Some(div);
7857 }
7858
7859 Some(match self.zoomed_position {
7860 Some(DockPosition::Left) => div.right_2().border_r_1(),
7861 Some(DockPosition::Right) => div.left_2().border_l_1(),
7862 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
7863 None => {
7864 div.top_2().bottom_2().left_2().right_2().border_1()
7865 }
7866 })
7867 }))
7868 .children(self.render_notifications(window, cx)),
7869 )
7870 .when(self.status_bar_visible(cx), |parent| {
7871 parent.child(self.status_bar.clone())
7872 })
7873 .child(self.modal_layer.clone())
7874 .child(self.toast_layer.clone()),
7875 )
7876 }
7877}
7878
7879impl WorkspaceStore {
7880 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
7881 Self {
7882 workspaces: Default::default(),
7883 _subscriptions: vec![
7884 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
7885 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
7886 ],
7887 client,
7888 }
7889 }
7890
7891 pub fn update_followers(
7892 &self,
7893 project_id: Option<u64>,
7894 update: proto::update_followers::Variant,
7895 cx: &App,
7896 ) -> Option<()> {
7897 let active_call = GlobalAnyActiveCall::try_global(cx)?;
7898 let room_id = active_call.0.room_id(cx)?;
7899 self.client
7900 .send(proto::UpdateFollowers {
7901 room_id,
7902 project_id,
7903 variant: Some(update),
7904 })
7905 .log_err()
7906 }
7907
7908 pub async fn handle_follow(
7909 this: Entity<Self>,
7910 envelope: TypedEnvelope<proto::Follow>,
7911 mut cx: AsyncApp,
7912 ) -> Result<proto::FollowResponse> {
7913 this.update(&mut cx, |this, cx| {
7914 let follower = Follower {
7915 project_id: envelope.payload.project_id,
7916 peer_id: envelope.original_sender_id()?,
7917 };
7918
7919 let mut response = proto::FollowResponse::default();
7920
7921 this.workspaces.retain(|(window_handle, weak_workspace)| {
7922 let Some(workspace) = weak_workspace.upgrade() else {
7923 return false;
7924 };
7925 window_handle
7926 .update(cx, |_, window, cx| {
7927 workspace.update(cx, |workspace, cx| {
7928 let handler_response =
7929 workspace.handle_follow(follower.project_id, window, cx);
7930 if let Some(active_view) = handler_response.active_view
7931 && workspace.project.read(cx).remote_id() == follower.project_id
7932 {
7933 response.active_view = Some(active_view)
7934 }
7935 });
7936 })
7937 .is_ok()
7938 });
7939
7940 Ok(response)
7941 })
7942 }
7943
7944 async fn handle_update_followers(
7945 this: Entity<Self>,
7946 envelope: TypedEnvelope<proto::UpdateFollowers>,
7947 mut cx: AsyncApp,
7948 ) -> Result<()> {
7949 let leader_id = envelope.original_sender_id()?;
7950 let update = envelope.payload;
7951
7952 this.update(&mut cx, |this, cx| {
7953 this.workspaces.retain(|(window_handle, weak_workspace)| {
7954 let Some(workspace) = weak_workspace.upgrade() else {
7955 return false;
7956 };
7957 window_handle
7958 .update(cx, |_, window, cx| {
7959 workspace.update(cx, |workspace, cx| {
7960 let project_id = workspace.project.read(cx).remote_id();
7961 if update.project_id != project_id && update.project_id.is_some() {
7962 return;
7963 }
7964 workspace.handle_update_followers(
7965 leader_id,
7966 update.clone(),
7967 window,
7968 cx,
7969 );
7970 });
7971 })
7972 .is_ok()
7973 });
7974 Ok(())
7975 })
7976 }
7977
7978 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
7979 self.workspaces.iter().map(|(_, weak)| weak)
7980 }
7981
7982 pub fn workspaces_with_windows(
7983 &self,
7984 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
7985 self.workspaces.iter().map(|(window, weak)| (*window, weak))
7986 }
7987}
7988
7989impl ViewId {
7990 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
7991 Ok(Self {
7992 creator: message
7993 .creator
7994 .map(CollaboratorId::PeerId)
7995 .context("creator is missing")?,
7996 id: message.id,
7997 })
7998 }
7999
8000 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8001 if let CollaboratorId::PeerId(peer_id) = self.creator {
8002 Some(proto::ViewId {
8003 creator: Some(peer_id),
8004 id: self.id,
8005 })
8006 } else {
8007 None
8008 }
8009 }
8010}
8011
8012impl FollowerState {
8013 fn pane(&self) -> &Entity<Pane> {
8014 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8015 }
8016}
8017
8018pub trait WorkspaceHandle {
8019 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8020}
8021
8022impl WorkspaceHandle for Entity<Workspace> {
8023 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8024 self.read(cx)
8025 .worktrees(cx)
8026 .flat_map(|worktree| {
8027 let worktree_id = worktree.read(cx).id();
8028 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8029 worktree_id,
8030 path: f.path.clone(),
8031 })
8032 })
8033 .collect::<Vec<_>>()
8034 }
8035}
8036
8037pub async fn last_opened_workspace_location(
8038 fs: &dyn fs::Fs,
8039) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8040 DB.last_workspace(fs)
8041 .await
8042 .log_err()
8043 .flatten()
8044 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8045}
8046
8047pub async fn last_session_workspace_locations(
8048 last_session_id: &str,
8049 last_session_window_stack: Option<Vec<WindowId>>,
8050 fs: &dyn fs::Fs,
8051) -> Option<Vec<SessionWorkspace>> {
8052 DB.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8053 .await
8054 .log_err()
8055}
8056
8057pub struct MultiWorkspaceRestoreResult {
8058 pub window_handle: WindowHandle<MultiWorkspace>,
8059 pub errors: Vec<anyhow::Error>,
8060}
8061
8062pub async fn restore_multiworkspace(
8063 multi_workspace: SerializedMultiWorkspace,
8064 app_state: Arc<AppState>,
8065 cx: &mut AsyncApp,
8066) -> anyhow::Result<MultiWorkspaceRestoreResult> {
8067 let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
8068 let mut group_iter = workspaces.into_iter();
8069 let first = group_iter
8070 .next()
8071 .context("window group must not be empty")?;
8072
8073 let window_handle = if first.paths.is_empty() {
8074 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
8075 .await?
8076 } else {
8077 let (window, _items) = cx
8078 .update(|cx| {
8079 Workspace::new_local(
8080 first.paths.paths().to_vec(),
8081 app_state.clone(),
8082 None,
8083 None,
8084 None,
8085 cx,
8086 )
8087 })
8088 .await?;
8089 window
8090 };
8091
8092 let mut errors = Vec::new();
8093
8094 for session_workspace in group_iter {
8095 let error = if session_workspace.paths.is_empty() {
8096 cx.update(|cx| {
8097 open_workspace_by_id(
8098 session_workspace.workspace_id,
8099 app_state.clone(),
8100 Some(window_handle),
8101 cx,
8102 )
8103 })
8104 .await
8105 .err()
8106 } else {
8107 cx.update(|cx| {
8108 Workspace::new_local(
8109 session_workspace.paths.paths().to_vec(),
8110 app_state.clone(),
8111 Some(window_handle),
8112 None,
8113 None,
8114 cx,
8115 )
8116 })
8117 .await
8118 .err()
8119 };
8120
8121 if let Some(error) = error {
8122 errors.push(error);
8123 }
8124 }
8125
8126 if let Some(target_id) = state.active_workspace_id {
8127 window_handle
8128 .update(cx, |multi_workspace, window, cx| {
8129 let target_index = multi_workspace
8130 .workspaces()
8131 .iter()
8132 .position(|ws| ws.read(cx).database_id() == Some(target_id));
8133 if let Some(index) = target_index {
8134 multi_workspace.activate_index(index, window, cx);
8135 } else if !multi_workspace.workspaces().is_empty() {
8136 multi_workspace.activate_index(0, window, cx);
8137 }
8138 })
8139 .ok();
8140 } else {
8141 window_handle
8142 .update(cx, |multi_workspace, window, cx| {
8143 if !multi_workspace.workspaces().is_empty() {
8144 multi_workspace.activate_index(0, window, cx);
8145 }
8146 })
8147 .ok();
8148 }
8149
8150 if state.sidebar_open {
8151 window_handle
8152 .update(cx, |multi_workspace, _, cx| {
8153 multi_workspace.open_sidebar(cx);
8154 })
8155 .ok();
8156 }
8157
8158 window_handle
8159 .update(cx, |_, window, _cx| {
8160 window.activate_window();
8161 })
8162 .ok();
8163
8164 Ok(MultiWorkspaceRestoreResult {
8165 window_handle,
8166 errors,
8167 })
8168}
8169
8170actions!(
8171 collab,
8172 [
8173 /// Opens the channel notes for the current call.
8174 ///
8175 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8176 /// channel in the collab panel.
8177 ///
8178 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8179 /// can be copied via "Copy link to section" in the context menu of the channel notes
8180 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8181 OpenChannelNotes,
8182 /// Mutes your microphone.
8183 Mute,
8184 /// Deafens yourself (mute both microphone and speakers).
8185 Deafen,
8186 /// Leaves the current call.
8187 LeaveCall,
8188 /// Shares the current project with collaborators.
8189 ShareProject,
8190 /// Shares your screen with collaborators.
8191 ScreenShare,
8192 /// Copies the current room name and session id for debugging purposes.
8193 CopyRoomId,
8194 ]
8195);
8196actions!(
8197 zed,
8198 [
8199 /// Opens the Zed log file.
8200 OpenLog,
8201 /// Reveals the Zed log file in the system file manager.
8202 RevealLogInFileManager
8203 ]
8204);
8205
8206async fn join_channel_internal(
8207 channel_id: ChannelId,
8208 app_state: &Arc<AppState>,
8209 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8210 requesting_workspace: Option<WeakEntity<Workspace>>,
8211 active_call: &dyn AnyActiveCall,
8212 cx: &mut AsyncApp,
8213) -> Result<bool> {
8214 let (should_prompt, already_in_channel) = cx.update(|cx| {
8215 if !active_call.is_in_room(cx) {
8216 return (false, false);
8217 }
8218
8219 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8220 let should_prompt = active_call.is_sharing_project(cx)
8221 && active_call.has_remote_participants(cx)
8222 && !already_in_channel;
8223 (should_prompt, already_in_channel)
8224 });
8225
8226 if already_in_channel {
8227 let task = cx.update(|cx| {
8228 if let Some((project, host)) = active_call.most_active_project(cx) {
8229 Some(join_in_room_project(project, host, app_state.clone(), cx))
8230 } else {
8231 None
8232 }
8233 });
8234 if let Some(task) = task {
8235 task.await?;
8236 }
8237 return anyhow::Ok(true);
8238 }
8239
8240 if should_prompt {
8241 if let Some(multi_workspace) = requesting_window {
8242 let answer = multi_workspace
8243 .update(cx, |_, window, cx| {
8244 window.prompt(
8245 PromptLevel::Warning,
8246 "Do you want to switch channels?",
8247 Some("Leaving this call will unshare your current project."),
8248 &["Yes, Join Channel", "Cancel"],
8249 cx,
8250 )
8251 })?
8252 .await;
8253
8254 if answer == Ok(1) {
8255 return Ok(false);
8256 }
8257 } else {
8258 return Ok(false);
8259 }
8260 }
8261
8262 let client = cx.update(|cx| active_call.client(cx));
8263
8264 let mut client_status = client.status();
8265
8266 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8267 'outer: loop {
8268 let Some(status) = client_status.recv().await else {
8269 anyhow::bail!("error connecting");
8270 };
8271
8272 match status {
8273 Status::Connecting
8274 | Status::Authenticating
8275 | Status::Authenticated
8276 | Status::Reconnecting
8277 | Status::Reauthenticating
8278 | Status::Reauthenticated => continue,
8279 Status::Connected { .. } => break 'outer,
8280 Status::SignedOut | Status::AuthenticationError => {
8281 return Err(ErrorCode::SignedOut.into());
8282 }
8283 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8284 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8285 return Err(ErrorCode::Disconnected.into());
8286 }
8287 }
8288 }
8289
8290 let joined = cx
8291 .update(|cx| active_call.join_channel(channel_id, cx))
8292 .await?;
8293
8294 if !joined {
8295 return anyhow::Ok(true);
8296 }
8297
8298 cx.update(|cx| active_call.room_update_completed(cx)).await;
8299
8300 let task = cx.update(|cx| {
8301 if let Some((project, host)) = active_call.most_active_project(cx) {
8302 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8303 }
8304
8305 // If you are the first to join a channel, see if you should share your project.
8306 if !active_call.has_remote_participants(cx)
8307 && !active_call.local_participant_is_guest(cx)
8308 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8309 {
8310 let project = workspace.update(cx, |workspace, cx| {
8311 let project = workspace.project.read(cx);
8312
8313 if !active_call.share_on_join(cx) {
8314 return None;
8315 }
8316
8317 if (project.is_local() || project.is_via_remote_server())
8318 && project.visible_worktrees(cx).any(|tree| {
8319 tree.read(cx)
8320 .root_entry()
8321 .is_some_and(|entry| entry.is_dir())
8322 })
8323 {
8324 Some(workspace.project.clone())
8325 } else {
8326 None
8327 }
8328 });
8329 if let Some(project) = project {
8330 let share_task = active_call.share_project(project, cx);
8331 return Some(cx.spawn(async move |_cx| -> Result<()> {
8332 share_task.await?;
8333 Ok(())
8334 }));
8335 }
8336 }
8337
8338 None
8339 });
8340 if let Some(task) = task {
8341 task.await?;
8342 return anyhow::Ok(true);
8343 }
8344 anyhow::Ok(false)
8345}
8346
8347pub fn join_channel(
8348 channel_id: ChannelId,
8349 app_state: Arc<AppState>,
8350 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8351 requesting_workspace: Option<WeakEntity<Workspace>>,
8352 cx: &mut App,
8353) -> Task<Result<()>> {
8354 let active_call = GlobalAnyActiveCall::global(cx).clone();
8355 cx.spawn(async move |cx| {
8356 let result = join_channel_internal(
8357 channel_id,
8358 &app_state,
8359 requesting_window,
8360 requesting_workspace,
8361 &*active_call.0,
8362 cx,
8363 )
8364 .await;
8365
8366 // join channel succeeded, and opened a window
8367 if matches!(result, Ok(true)) {
8368 return anyhow::Ok(());
8369 }
8370
8371 // find an existing workspace to focus and show call controls
8372 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8373 if active_window.is_none() {
8374 // no open workspaces, make one to show the error in (blergh)
8375 let (window_handle, _) = cx
8376 .update(|cx| {
8377 Workspace::new_local(
8378 vec![],
8379 app_state.clone(),
8380 requesting_window,
8381 None,
8382 None,
8383 cx,
8384 )
8385 })
8386 .await?;
8387
8388 window_handle
8389 .update(cx, |_, window, _cx| {
8390 window.activate_window();
8391 })
8392 .ok();
8393
8394 if result.is_ok() {
8395 cx.update(|cx| {
8396 cx.dispatch_action(&OpenChannelNotes);
8397 });
8398 }
8399
8400 active_window = Some(window_handle);
8401 }
8402
8403 if let Err(err) = result {
8404 log::error!("failed to join channel: {}", err);
8405 if let Some(active_window) = active_window {
8406 active_window
8407 .update(cx, |_, window, cx| {
8408 let detail: SharedString = match err.error_code() {
8409 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8410 ErrorCode::UpgradeRequired => concat!(
8411 "Your are running an unsupported version of Zed. ",
8412 "Please update to continue."
8413 )
8414 .into(),
8415 ErrorCode::NoSuchChannel => concat!(
8416 "No matching channel was found. ",
8417 "Please check the link and try again."
8418 )
8419 .into(),
8420 ErrorCode::Forbidden => concat!(
8421 "This channel is private, and you do not have access. ",
8422 "Please ask someone to add you and try again."
8423 )
8424 .into(),
8425 ErrorCode::Disconnected => {
8426 "Please check your internet connection and try again.".into()
8427 }
8428 _ => format!("{}\n\nPlease try again.", err).into(),
8429 };
8430 window.prompt(
8431 PromptLevel::Critical,
8432 "Failed to join channel",
8433 Some(&detail),
8434 &["Ok"],
8435 cx,
8436 )
8437 })?
8438 .await
8439 .ok();
8440 }
8441 }
8442
8443 // return ok, we showed the error to the user.
8444 anyhow::Ok(())
8445 })
8446}
8447
8448pub async fn get_any_active_multi_workspace(
8449 app_state: Arc<AppState>,
8450 mut cx: AsyncApp,
8451) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8452 // find an existing workspace to focus and show call controls
8453 let active_window = activate_any_workspace_window(&mut cx);
8454 if active_window.is_none() {
8455 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, cx))
8456 .await?;
8457 }
8458 activate_any_workspace_window(&mut cx).context("could not open zed")
8459}
8460
8461fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
8462 cx.update(|cx| {
8463 if let Some(workspace_window) = cx
8464 .active_window()
8465 .and_then(|window| window.downcast::<MultiWorkspace>())
8466 {
8467 return Some(workspace_window);
8468 }
8469
8470 for window in cx.windows() {
8471 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
8472 workspace_window
8473 .update(cx, |_, window, _| window.activate_window())
8474 .ok();
8475 return Some(workspace_window);
8476 }
8477 }
8478 None
8479 })
8480}
8481
8482pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
8483 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
8484}
8485
8486pub fn workspace_windows_for_location(
8487 serialized_location: &SerializedWorkspaceLocation,
8488 cx: &App,
8489) -> Vec<WindowHandle<MultiWorkspace>> {
8490 cx.windows()
8491 .into_iter()
8492 .filter_map(|window| window.downcast::<MultiWorkspace>())
8493 .filter(|multi_workspace| {
8494 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
8495 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
8496 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
8497 }
8498 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
8499 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
8500 a.distro_name == b.distro_name
8501 }
8502 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
8503 a.container_id == b.container_id
8504 }
8505 #[cfg(any(test, feature = "test-support"))]
8506 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
8507 a.id == b.id
8508 }
8509 _ => false,
8510 };
8511
8512 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
8513 multi_workspace.workspaces().iter().any(|workspace| {
8514 match workspace.read(cx).workspace_location(cx) {
8515 WorkspaceLocation::Location(location, _) => {
8516 match (&location, serialized_location) {
8517 (
8518 SerializedWorkspaceLocation::Local,
8519 SerializedWorkspaceLocation::Local,
8520 ) => true,
8521 (
8522 SerializedWorkspaceLocation::Remote(a),
8523 SerializedWorkspaceLocation::Remote(b),
8524 ) => same_host(a, b),
8525 _ => false,
8526 }
8527 }
8528 _ => false,
8529 }
8530 })
8531 })
8532 })
8533 .collect()
8534}
8535
8536pub async fn find_existing_workspace(
8537 abs_paths: &[PathBuf],
8538 open_options: &OpenOptions,
8539 location: &SerializedWorkspaceLocation,
8540 cx: &mut AsyncApp,
8541) -> (
8542 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
8543 OpenVisible,
8544) {
8545 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
8546 let mut open_visible = OpenVisible::All;
8547 let mut best_match = None;
8548
8549 if open_options.open_new_workspace != Some(true) {
8550 cx.update(|cx| {
8551 for window in workspace_windows_for_location(location, cx) {
8552 if let Ok(multi_workspace) = window.read(cx) {
8553 for workspace in multi_workspace.workspaces() {
8554 let project = workspace.read(cx).project.read(cx);
8555 let m = project.visibility_for_paths(
8556 abs_paths,
8557 open_options.open_new_workspace == None,
8558 cx,
8559 );
8560 if m > best_match {
8561 existing = Some((window, workspace.clone()));
8562 best_match = m;
8563 } else if best_match.is_none()
8564 && open_options.open_new_workspace == Some(false)
8565 {
8566 existing = Some((window, workspace.clone()))
8567 }
8568 }
8569 }
8570 }
8571 });
8572
8573 let all_paths_are_files = existing
8574 .as_ref()
8575 .and_then(|(_, target_workspace)| {
8576 cx.update(|cx| {
8577 let workspace = target_workspace.read(cx);
8578 let project = workspace.project.read(cx);
8579 let path_style = workspace.path_style(cx);
8580 Some(!abs_paths.iter().any(|path| {
8581 let path = util::paths::SanitizedPath::new(path);
8582 project.worktrees(cx).any(|worktree| {
8583 let worktree = worktree.read(cx);
8584 let abs_path = worktree.abs_path();
8585 path_style
8586 .strip_prefix(path.as_ref(), abs_path.as_ref())
8587 .and_then(|rel| worktree.entry_for_path(&rel))
8588 .is_some_and(|e| e.is_dir())
8589 })
8590 }))
8591 })
8592 })
8593 .unwrap_or(false);
8594
8595 if open_options.open_new_workspace.is_none()
8596 && existing.is_some()
8597 && open_options.wait
8598 && all_paths_are_files
8599 {
8600 cx.update(|cx| {
8601 let windows = workspace_windows_for_location(location, cx);
8602 let window = cx
8603 .active_window()
8604 .and_then(|window| window.downcast::<MultiWorkspace>())
8605 .filter(|window| windows.contains(window))
8606 .or_else(|| windows.into_iter().next());
8607 if let Some(window) = window {
8608 if let Ok(multi_workspace) = window.read(cx) {
8609 let active_workspace = multi_workspace.workspace().clone();
8610 existing = Some((window, active_workspace));
8611 open_visible = OpenVisible::None;
8612 }
8613 }
8614 });
8615 }
8616 }
8617 (existing, open_visible)
8618}
8619
8620#[derive(Default, Clone)]
8621pub struct OpenOptions {
8622 pub visible: Option<OpenVisible>,
8623 pub focus: Option<bool>,
8624 pub open_new_workspace: Option<bool>,
8625 pub wait: bool,
8626 pub replace_window: Option<WindowHandle<MultiWorkspace>>,
8627 pub env: Option<HashMap<String, String>>,
8628}
8629
8630/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
8631pub fn open_workspace_by_id(
8632 workspace_id: WorkspaceId,
8633 app_state: Arc<AppState>,
8634 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8635 cx: &mut App,
8636) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
8637 let project_handle = Project::local(
8638 app_state.client.clone(),
8639 app_state.node_runtime.clone(),
8640 app_state.user_store.clone(),
8641 app_state.languages.clone(),
8642 app_state.fs.clone(),
8643 None,
8644 project::LocalProjectFlags {
8645 init_worktree_trust: true,
8646 ..project::LocalProjectFlags::default()
8647 },
8648 cx,
8649 );
8650
8651 cx.spawn(async move |cx| {
8652 let serialized_workspace = persistence::DB
8653 .workspace_for_id(workspace_id)
8654 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
8655
8656 let centered_layout = serialized_workspace.centered_layout;
8657
8658 let (window, workspace) = if let Some(window) = requesting_window {
8659 let workspace = window.update(cx, |multi_workspace, window, cx| {
8660 let workspace = cx.new(|cx| {
8661 let mut workspace = Workspace::new(
8662 Some(workspace_id),
8663 project_handle.clone(),
8664 app_state.clone(),
8665 window,
8666 cx,
8667 );
8668 workspace.centered_layout = centered_layout;
8669 workspace
8670 });
8671 multi_workspace.add_workspace(workspace.clone(), cx);
8672 workspace
8673 })?;
8674 (window, workspace)
8675 } else {
8676 let window_bounds_override = window_bounds_env_override();
8677
8678 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
8679 (Some(WindowBounds::Windowed(bounds)), None)
8680 } else if let Some(display) = serialized_workspace.display
8681 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
8682 {
8683 (Some(bounds.0), Some(display))
8684 } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
8685 (Some(bounds), Some(display))
8686 } else {
8687 (None, None)
8688 };
8689
8690 let options = cx.update(|cx| {
8691 let mut options = (app_state.build_window_options)(display, cx);
8692 options.window_bounds = window_bounds;
8693 options
8694 });
8695
8696 let window = cx.open_window(options, {
8697 let app_state = app_state.clone();
8698 let project_handle = project_handle.clone();
8699 move |window, cx| {
8700 let workspace = cx.new(|cx| {
8701 let mut workspace = Workspace::new(
8702 Some(workspace_id),
8703 project_handle,
8704 app_state,
8705 window,
8706 cx,
8707 );
8708 workspace.centered_layout = centered_layout;
8709 workspace
8710 });
8711 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
8712 }
8713 })?;
8714
8715 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
8716 multi_workspace.workspace().clone()
8717 })?;
8718
8719 (window, workspace)
8720 };
8721
8722 notify_if_database_failed(window, cx);
8723
8724 // Restore items from the serialized workspace
8725 window
8726 .update(cx, |_, window, cx| {
8727 workspace.update(cx, |_workspace, cx| {
8728 open_items(Some(serialized_workspace), vec![], window, cx)
8729 })
8730 })?
8731 .await?;
8732
8733 window.update(cx, |_, window, cx| {
8734 workspace.update(cx, |workspace, cx| {
8735 workspace.serialize_workspace(window, cx);
8736 });
8737 })?;
8738
8739 Ok(window)
8740 })
8741}
8742
8743#[allow(clippy::type_complexity)]
8744pub fn open_paths(
8745 abs_paths: &[PathBuf],
8746 app_state: Arc<AppState>,
8747 open_options: OpenOptions,
8748 cx: &mut App,
8749) -> Task<
8750 anyhow::Result<(
8751 WindowHandle<MultiWorkspace>,
8752 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
8753 )>,
8754> {
8755 let abs_paths = abs_paths.to_vec();
8756 #[cfg(target_os = "windows")]
8757 let wsl_path = abs_paths
8758 .iter()
8759 .find_map(|p| util::paths::WslPath::from_path(p));
8760
8761 cx.spawn(async move |cx| {
8762 let (mut existing, mut open_visible) = find_existing_workspace(
8763 &abs_paths,
8764 &open_options,
8765 &SerializedWorkspaceLocation::Local,
8766 cx,
8767 )
8768 .await;
8769
8770 // Fallback: if no workspace contains the paths and all paths are files,
8771 // prefer an existing local workspace window (active window first).
8772 if open_options.open_new_workspace.is_none() && existing.is_none() {
8773 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
8774 let all_metadatas = futures::future::join_all(all_paths)
8775 .await
8776 .into_iter()
8777 .filter_map(|result| result.ok().flatten())
8778 .collect::<Vec<_>>();
8779
8780 if all_metadatas.iter().all(|file| !file.is_dir) {
8781 cx.update(|cx| {
8782 let windows = workspace_windows_for_location(
8783 &SerializedWorkspaceLocation::Local,
8784 cx,
8785 );
8786 let window = cx
8787 .active_window()
8788 .and_then(|window| window.downcast::<MultiWorkspace>())
8789 .filter(|window| windows.contains(window))
8790 .or_else(|| windows.into_iter().next());
8791 if let Some(window) = window {
8792 if let Ok(multi_workspace) = window.read(cx) {
8793 let active_workspace = multi_workspace.workspace().clone();
8794 existing = Some((window, active_workspace));
8795 open_visible = OpenVisible::None;
8796 }
8797 }
8798 });
8799 }
8800 }
8801
8802 let result = if let Some((existing, target_workspace)) = existing {
8803 let open_task = existing
8804 .update(cx, |multi_workspace, window, cx| {
8805 window.activate_window();
8806 multi_workspace.activate(target_workspace.clone(), cx);
8807 target_workspace.update(cx, |workspace, cx| {
8808 workspace.open_paths(
8809 abs_paths,
8810 OpenOptions {
8811 visible: Some(open_visible),
8812 ..Default::default()
8813 },
8814 None,
8815 window,
8816 cx,
8817 )
8818 })
8819 })?
8820 .await;
8821
8822 _ = existing.update(cx, |multi_workspace, _, cx| {
8823 let workspace = multi_workspace.workspace().clone();
8824 workspace.update(cx, |workspace, cx| {
8825 for item in open_task.iter().flatten() {
8826 if let Err(e) = item {
8827 workspace.show_error(&e, cx);
8828 }
8829 }
8830 });
8831 });
8832
8833 Ok((existing, open_task))
8834 } else {
8835 let result = cx
8836 .update(move |cx| {
8837 Workspace::new_local(
8838 abs_paths,
8839 app_state.clone(),
8840 open_options.replace_window,
8841 open_options.env,
8842 None,
8843 cx,
8844 )
8845 })
8846 .await;
8847
8848 if let Ok((ref window_handle, _)) = result {
8849 window_handle
8850 .update(cx, |_, window, _cx| {
8851 window.activate_window();
8852 })
8853 .log_err();
8854 }
8855
8856 result
8857 };
8858
8859 #[cfg(target_os = "windows")]
8860 if let Some(util::paths::WslPath{distro, path}) = wsl_path
8861 && let Ok((multi_workspace_window, _)) = &result
8862 {
8863 multi_workspace_window
8864 .update(cx, move |multi_workspace, _window, cx| {
8865 struct OpenInWsl;
8866 let workspace = multi_workspace.workspace().clone();
8867 workspace.update(cx, |workspace, cx| {
8868 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
8869 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
8870 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
8871 cx.new(move |cx| {
8872 MessageNotification::new(msg, cx)
8873 .primary_message("Open in WSL")
8874 .primary_icon(IconName::FolderOpen)
8875 .primary_on_click(move |window, cx| {
8876 window.dispatch_action(Box::new(remote::OpenWslPath {
8877 distro: remote::WslConnectionOptions {
8878 distro_name: distro.clone(),
8879 user: None,
8880 },
8881 paths: vec![path.clone().into()],
8882 }), cx)
8883 })
8884 })
8885 });
8886 });
8887 })
8888 .unwrap();
8889 };
8890 result
8891 })
8892}
8893
8894pub fn open_new(
8895 open_options: OpenOptions,
8896 app_state: Arc<AppState>,
8897 cx: &mut App,
8898 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
8899) -> Task<anyhow::Result<()>> {
8900 let task = Workspace::new_local(
8901 Vec::new(),
8902 app_state,
8903 open_options.replace_window,
8904 open_options.env,
8905 Some(Box::new(init)),
8906 cx,
8907 );
8908 cx.spawn(async move |cx| {
8909 let (window, _opened_paths) = task.await?;
8910 window
8911 .update(cx, |_, window, _cx| {
8912 window.activate_window();
8913 })
8914 .ok();
8915 Ok(())
8916 })
8917}
8918
8919pub fn create_and_open_local_file(
8920 path: &'static Path,
8921 window: &mut Window,
8922 cx: &mut Context<Workspace>,
8923 default_content: impl 'static + Send + FnOnce() -> Rope,
8924) -> Task<Result<Box<dyn ItemHandle>>> {
8925 cx.spawn_in(window, async move |workspace, cx| {
8926 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
8927 if !fs.is_file(path).await {
8928 fs.create_file(path, Default::default()).await?;
8929 fs.save(path, &default_content(), Default::default())
8930 .await?;
8931 }
8932
8933 workspace
8934 .update_in(cx, |workspace, window, cx| {
8935 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
8936 let path = workspace
8937 .project
8938 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
8939 cx.spawn_in(window, async move |workspace, cx| {
8940 let path = path.await?;
8941 let mut items = workspace
8942 .update_in(cx, |workspace, window, cx| {
8943 workspace.open_paths(
8944 vec![path.to_path_buf()],
8945 OpenOptions {
8946 visible: Some(OpenVisible::None),
8947 ..Default::default()
8948 },
8949 None,
8950 window,
8951 cx,
8952 )
8953 })?
8954 .await;
8955 let item = items.pop().flatten();
8956 item.with_context(|| format!("path {path:?} is not a file"))?
8957 })
8958 })
8959 })?
8960 .await?
8961 .await
8962 })
8963}
8964
8965pub fn open_remote_project_with_new_connection(
8966 window: WindowHandle<MultiWorkspace>,
8967 remote_connection: Arc<dyn RemoteConnection>,
8968 cancel_rx: oneshot::Receiver<()>,
8969 delegate: Arc<dyn RemoteClientDelegate>,
8970 app_state: Arc<AppState>,
8971 paths: Vec<PathBuf>,
8972 cx: &mut App,
8973) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
8974 cx.spawn(async move |cx| {
8975 let (workspace_id, serialized_workspace) =
8976 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
8977 .await?;
8978
8979 let session = match cx
8980 .update(|cx| {
8981 remote::RemoteClient::new(
8982 ConnectionIdentifier::Workspace(workspace_id.0),
8983 remote_connection,
8984 cancel_rx,
8985 delegate,
8986 cx,
8987 )
8988 })
8989 .await?
8990 {
8991 Some(result) => result,
8992 None => return Ok(Vec::new()),
8993 };
8994
8995 let project = cx.update(|cx| {
8996 project::Project::remote(
8997 session,
8998 app_state.client.clone(),
8999 app_state.node_runtime.clone(),
9000 app_state.user_store.clone(),
9001 app_state.languages.clone(),
9002 app_state.fs.clone(),
9003 true,
9004 cx,
9005 )
9006 });
9007
9008 open_remote_project_inner(
9009 project,
9010 paths,
9011 workspace_id,
9012 serialized_workspace,
9013 app_state,
9014 window,
9015 cx,
9016 )
9017 .await
9018 })
9019}
9020
9021pub fn open_remote_project_with_existing_connection(
9022 connection_options: RemoteConnectionOptions,
9023 project: Entity<Project>,
9024 paths: Vec<PathBuf>,
9025 app_state: Arc<AppState>,
9026 window: WindowHandle<MultiWorkspace>,
9027 cx: &mut AsyncApp,
9028) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9029 cx.spawn(async move |cx| {
9030 let (workspace_id, serialized_workspace) =
9031 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9032
9033 open_remote_project_inner(
9034 project,
9035 paths,
9036 workspace_id,
9037 serialized_workspace,
9038 app_state,
9039 window,
9040 cx,
9041 )
9042 .await
9043 })
9044}
9045
9046async fn open_remote_project_inner(
9047 project: Entity<Project>,
9048 paths: Vec<PathBuf>,
9049 workspace_id: WorkspaceId,
9050 serialized_workspace: Option<SerializedWorkspace>,
9051 app_state: Arc<AppState>,
9052 window: WindowHandle<MultiWorkspace>,
9053 cx: &mut AsyncApp,
9054) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9055 let toolchains = DB.toolchains(workspace_id).await?;
9056 for (toolchain, worktree_path, path) in toolchains {
9057 project
9058 .update(cx, |this, cx| {
9059 let Some(worktree_id) =
9060 this.find_worktree(&worktree_path, cx)
9061 .and_then(|(worktree, rel_path)| {
9062 if rel_path.is_empty() {
9063 Some(worktree.read(cx).id())
9064 } else {
9065 None
9066 }
9067 })
9068 else {
9069 return Task::ready(None);
9070 };
9071
9072 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9073 })
9074 .await;
9075 }
9076 let mut project_paths_to_open = vec![];
9077 let mut project_path_errors = vec![];
9078
9079 for path in paths {
9080 let result = cx
9081 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9082 .await;
9083 match result {
9084 Ok((_, project_path)) => {
9085 project_paths_to_open.push((path.clone(), Some(project_path)));
9086 }
9087 Err(error) => {
9088 project_path_errors.push(error);
9089 }
9090 };
9091 }
9092
9093 if project_paths_to_open.is_empty() {
9094 return Err(project_path_errors.pop().context("no paths given")?);
9095 }
9096
9097 let workspace = window.update(cx, |multi_workspace, window, cx| {
9098 telemetry::event!("SSH Project Opened");
9099
9100 let new_workspace = cx.new(|cx| {
9101 let mut workspace =
9102 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9103 workspace.update_history(cx);
9104
9105 if let Some(ref serialized) = serialized_workspace {
9106 workspace.centered_layout = serialized.centered_layout;
9107 }
9108
9109 workspace
9110 });
9111
9112 multi_workspace.activate(new_workspace.clone(), cx);
9113 new_workspace
9114 })?;
9115
9116 let items = window
9117 .update(cx, |_, window, cx| {
9118 window.activate_window();
9119 workspace.update(cx, |_workspace, cx| {
9120 open_items(serialized_workspace, project_paths_to_open, window, cx)
9121 })
9122 })?
9123 .await?;
9124
9125 workspace.update(cx, |workspace, cx| {
9126 for error in project_path_errors {
9127 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9128 if let Some(path) = error.error_tag("path") {
9129 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9130 }
9131 } else {
9132 workspace.show_error(&error, cx)
9133 }
9134 }
9135 });
9136
9137 Ok(items.into_iter().map(|item| item?.ok()).collect())
9138}
9139
9140fn deserialize_remote_project(
9141 connection_options: RemoteConnectionOptions,
9142 paths: Vec<PathBuf>,
9143 cx: &AsyncApp,
9144) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9145 cx.background_spawn(async move {
9146 let remote_connection_id = persistence::DB
9147 .get_or_create_remote_connection(connection_options)
9148 .await?;
9149
9150 let serialized_workspace =
9151 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
9152
9153 let workspace_id = if let Some(workspace_id) =
9154 serialized_workspace.as_ref().map(|workspace| workspace.id)
9155 {
9156 workspace_id
9157 } else {
9158 persistence::DB.next_id().await?
9159 };
9160
9161 Ok((workspace_id, serialized_workspace))
9162 })
9163}
9164
9165pub fn join_in_room_project(
9166 project_id: u64,
9167 follow_user_id: u64,
9168 app_state: Arc<AppState>,
9169 cx: &mut App,
9170) -> Task<Result<()>> {
9171 let windows = cx.windows();
9172 cx.spawn(async move |cx| {
9173 let existing_window_and_workspace: Option<(
9174 WindowHandle<MultiWorkspace>,
9175 Entity<Workspace>,
9176 )> = windows.into_iter().find_map(|window_handle| {
9177 window_handle
9178 .downcast::<MultiWorkspace>()
9179 .and_then(|window_handle| {
9180 window_handle
9181 .update(cx, |multi_workspace, _window, cx| {
9182 for workspace in multi_workspace.workspaces() {
9183 if workspace.read(cx).project().read(cx).remote_id()
9184 == Some(project_id)
9185 {
9186 return Some((window_handle, workspace.clone()));
9187 }
9188 }
9189 None
9190 })
9191 .unwrap_or(None)
9192 })
9193 });
9194
9195 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9196 existing_window_and_workspace
9197 {
9198 existing_window
9199 .update(cx, |multi_workspace, _, cx| {
9200 multi_workspace.activate(target_workspace, cx);
9201 })
9202 .ok();
9203 existing_window
9204 } else {
9205 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9206 let project = cx
9207 .update(|cx| {
9208 active_call.0.join_project(
9209 project_id,
9210 app_state.languages.clone(),
9211 app_state.fs.clone(),
9212 cx,
9213 )
9214 })
9215 .await?;
9216
9217 let window_bounds_override = window_bounds_env_override();
9218 cx.update(|cx| {
9219 let mut options = (app_state.build_window_options)(None, cx);
9220 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9221 cx.open_window(options, |window, cx| {
9222 let workspace = cx.new(|cx| {
9223 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9224 });
9225 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9226 })
9227 })?
9228 };
9229
9230 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9231 cx.activate(true);
9232 window.activate_window();
9233
9234 // We set the active workspace above, so this is the correct workspace.
9235 let workspace = multi_workspace.workspace().clone();
9236 workspace.update(cx, |workspace, cx| {
9237 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9238 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9239 .or_else(|| {
9240 // If we couldn't follow the given user, follow the host instead.
9241 let collaborator = workspace
9242 .project()
9243 .read(cx)
9244 .collaborators()
9245 .values()
9246 .find(|collaborator| collaborator.is_host)?;
9247 Some(collaborator.peer_id)
9248 });
9249
9250 if let Some(follow_peer_id) = follow_peer_id {
9251 workspace.follow(follow_peer_id, window, cx);
9252 }
9253 });
9254 })?;
9255
9256 anyhow::Ok(())
9257 })
9258}
9259
9260pub fn reload(cx: &mut App) {
9261 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9262 let mut workspace_windows = cx
9263 .windows()
9264 .into_iter()
9265 .filter_map(|window| window.downcast::<MultiWorkspace>())
9266 .collect::<Vec<_>>();
9267
9268 // If multiple windows have unsaved changes, and need a save prompt,
9269 // prompt in the active window before switching to a different window.
9270 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9271
9272 let mut prompt = None;
9273 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9274 prompt = window
9275 .update(cx, |_, window, cx| {
9276 window.prompt(
9277 PromptLevel::Info,
9278 "Are you sure you want to restart?",
9279 None,
9280 &["Restart", "Cancel"],
9281 cx,
9282 )
9283 })
9284 .ok();
9285 }
9286
9287 cx.spawn(async move |cx| {
9288 if let Some(prompt) = prompt {
9289 let answer = prompt.await?;
9290 if answer != 0 {
9291 return anyhow::Ok(());
9292 }
9293 }
9294
9295 // If the user cancels any save prompt, then keep the app open.
9296 for window in workspace_windows {
9297 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9298 let workspace = multi_workspace.workspace().clone();
9299 workspace.update(cx, |workspace, cx| {
9300 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9301 })
9302 }) && !should_close.await?
9303 {
9304 return anyhow::Ok(());
9305 }
9306 }
9307 cx.update(|cx| cx.restart());
9308 anyhow::Ok(())
9309 })
9310 .detach_and_log_err(cx);
9311}
9312
9313fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9314 let mut parts = value.split(',');
9315 let x: usize = parts.next()?.parse().ok()?;
9316 let y: usize = parts.next()?.parse().ok()?;
9317 Some(point(px(x as f32), px(y as f32)))
9318}
9319
9320fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9321 let mut parts = value.split(',');
9322 let width: usize = parts.next()?.parse().ok()?;
9323 let height: usize = parts.next()?.parse().ok()?;
9324 Some(size(px(width as f32), px(height as f32)))
9325}
9326
9327/// Add client-side decorations (rounded corners, shadows, resize handling) when
9328/// appropriate.
9329///
9330/// The `border_radius_tiling` parameter allows overriding which corners get
9331/// rounded, independently of the actual window tiling state. This is used
9332/// specifically for the workspace switcher sidebar: when the sidebar is open,
9333/// we want square corners on the left (so the sidebar appears flush with the
9334/// window edge) but we still need the shadow padding for proper visual
9335/// appearance. Unlike actual window tiling, this only affects border radius -
9336/// not padding or shadows.
9337pub fn client_side_decorations(
9338 element: impl IntoElement,
9339 window: &mut Window,
9340 cx: &mut App,
9341 border_radius_tiling: Tiling,
9342) -> Stateful<Div> {
9343 const BORDER_SIZE: Pixels = px(1.0);
9344 let decorations = window.window_decorations();
9345 let tiling = match decorations {
9346 Decorations::Server => Tiling::default(),
9347 Decorations::Client { tiling } => tiling,
9348 };
9349
9350 match decorations {
9351 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9352 Decorations::Server => window.set_client_inset(px(0.0)),
9353 }
9354
9355 struct GlobalResizeEdge(ResizeEdge);
9356 impl Global for GlobalResizeEdge {}
9357
9358 div()
9359 .id("window-backdrop")
9360 .bg(transparent_black())
9361 .map(|div| match decorations {
9362 Decorations::Server => div,
9363 Decorations::Client { .. } => div
9364 .when(
9365 !(tiling.top
9366 || tiling.right
9367 || border_radius_tiling.top
9368 || border_radius_tiling.right),
9369 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9370 )
9371 .when(
9372 !(tiling.top
9373 || tiling.left
9374 || border_radius_tiling.top
9375 || border_radius_tiling.left),
9376 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9377 )
9378 .when(
9379 !(tiling.bottom
9380 || tiling.right
9381 || border_radius_tiling.bottom
9382 || border_radius_tiling.right),
9383 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9384 )
9385 .when(
9386 !(tiling.bottom
9387 || tiling.left
9388 || border_radius_tiling.bottom
9389 || border_radius_tiling.left),
9390 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9391 )
9392 .when(!tiling.top, |div| {
9393 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9394 })
9395 .when(!tiling.bottom, |div| {
9396 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9397 })
9398 .when(!tiling.left, |div| {
9399 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9400 })
9401 .when(!tiling.right, |div| {
9402 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9403 })
9404 .on_mouse_move(move |e, window, cx| {
9405 let size = window.window_bounds().get_bounds().size;
9406 let pos = e.position;
9407
9408 let new_edge =
9409 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
9410
9411 let edge = cx.try_global::<GlobalResizeEdge>();
9412 if new_edge != edge.map(|edge| edge.0) {
9413 window
9414 .window_handle()
9415 .update(cx, |workspace, _, cx| {
9416 cx.notify(workspace.entity_id());
9417 })
9418 .ok();
9419 }
9420 })
9421 .on_mouse_down(MouseButton::Left, move |e, window, _| {
9422 let size = window.window_bounds().get_bounds().size;
9423 let pos = e.position;
9424
9425 let edge = match resize_edge(
9426 pos,
9427 theme::CLIENT_SIDE_DECORATION_SHADOW,
9428 size,
9429 tiling,
9430 ) {
9431 Some(value) => value,
9432 None => return,
9433 };
9434
9435 window.start_window_resize(edge);
9436 }),
9437 })
9438 .size_full()
9439 .child(
9440 div()
9441 .cursor(CursorStyle::Arrow)
9442 .map(|div| match decorations {
9443 Decorations::Server => div,
9444 Decorations::Client { .. } => div
9445 .border_color(cx.theme().colors().border)
9446 .when(
9447 !(tiling.top
9448 || tiling.right
9449 || border_radius_tiling.top
9450 || border_radius_tiling.right),
9451 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9452 )
9453 .when(
9454 !(tiling.top
9455 || tiling.left
9456 || border_radius_tiling.top
9457 || border_radius_tiling.left),
9458 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9459 )
9460 .when(
9461 !(tiling.bottom
9462 || tiling.right
9463 || border_radius_tiling.bottom
9464 || border_radius_tiling.right),
9465 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9466 )
9467 .when(
9468 !(tiling.bottom
9469 || tiling.left
9470 || border_radius_tiling.bottom
9471 || border_radius_tiling.left),
9472 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9473 )
9474 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
9475 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
9476 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
9477 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
9478 .when(!tiling.is_tiled(), |div| {
9479 div.shadow(vec![gpui::BoxShadow {
9480 color: Hsla {
9481 h: 0.,
9482 s: 0.,
9483 l: 0.,
9484 a: 0.4,
9485 },
9486 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
9487 spread_radius: px(0.),
9488 offset: point(px(0.0), px(0.0)),
9489 }])
9490 }),
9491 })
9492 .on_mouse_move(|_e, _, cx| {
9493 cx.stop_propagation();
9494 })
9495 .size_full()
9496 .child(element),
9497 )
9498 .map(|div| match decorations {
9499 Decorations::Server => div,
9500 Decorations::Client { tiling, .. } => div.child(
9501 canvas(
9502 |_bounds, window, _| {
9503 window.insert_hitbox(
9504 Bounds::new(
9505 point(px(0.0), px(0.0)),
9506 window.window_bounds().get_bounds().size,
9507 ),
9508 HitboxBehavior::Normal,
9509 )
9510 },
9511 move |_bounds, hitbox, window, cx| {
9512 let mouse = window.mouse_position();
9513 let size = window.window_bounds().get_bounds().size;
9514 let Some(edge) =
9515 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
9516 else {
9517 return;
9518 };
9519 cx.set_global(GlobalResizeEdge(edge));
9520 window.set_cursor_style(
9521 match edge {
9522 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
9523 ResizeEdge::Left | ResizeEdge::Right => {
9524 CursorStyle::ResizeLeftRight
9525 }
9526 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
9527 CursorStyle::ResizeUpLeftDownRight
9528 }
9529 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
9530 CursorStyle::ResizeUpRightDownLeft
9531 }
9532 },
9533 &hitbox,
9534 );
9535 },
9536 )
9537 .size_full()
9538 .absolute(),
9539 ),
9540 })
9541}
9542
9543fn resize_edge(
9544 pos: Point<Pixels>,
9545 shadow_size: Pixels,
9546 window_size: Size<Pixels>,
9547 tiling: Tiling,
9548) -> Option<ResizeEdge> {
9549 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
9550 if bounds.contains(&pos) {
9551 return None;
9552 }
9553
9554 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
9555 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
9556 if !tiling.top && top_left_bounds.contains(&pos) {
9557 return Some(ResizeEdge::TopLeft);
9558 }
9559
9560 let top_right_bounds = Bounds::new(
9561 Point::new(window_size.width - corner_size.width, px(0.)),
9562 corner_size,
9563 );
9564 if !tiling.top && top_right_bounds.contains(&pos) {
9565 return Some(ResizeEdge::TopRight);
9566 }
9567
9568 let bottom_left_bounds = Bounds::new(
9569 Point::new(px(0.), window_size.height - corner_size.height),
9570 corner_size,
9571 );
9572 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
9573 return Some(ResizeEdge::BottomLeft);
9574 }
9575
9576 let bottom_right_bounds = Bounds::new(
9577 Point::new(
9578 window_size.width - corner_size.width,
9579 window_size.height - corner_size.height,
9580 ),
9581 corner_size,
9582 );
9583 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
9584 return Some(ResizeEdge::BottomRight);
9585 }
9586
9587 if !tiling.top && pos.y < shadow_size {
9588 Some(ResizeEdge::Top)
9589 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
9590 Some(ResizeEdge::Bottom)
9591 } else if !tiling.left && pos.x < shadow_size {
9592 Some(ResizeEdge::Left)
9593 } else if !tiling.right && pos.x > window_size.width - shadow_size {
9594 Some(ResizeEdge::Right)
9595 } else {
9596 None
9597 }
9598}
9599
9600fn join_pane_into_active(
9601 active_pane: &Entity<Pane>,
9602 pane: &Entity<Pane>,
9603 window: &mut Window,
9604 cx: &mut App,
9605) {
9606 if pane == active_pane {
9607 } else if pane.read(cx).items_len() == 0 {
9608 pane.update(cx, |_, cx| {
9609 cx.emit(pane::Event::Remove {
9610 focus_on_pane: None,
9611 });
9612 })
9613 } else {
9614 move_all_items(pane, active_pane, window, cx);
9615 }
9616}
9617
9618fn move_all_items(
9619 from_pane: &Entity<Pane>,
9620 to_pane: &Entity<Pane>,
9621 window: &mut Window,
9622 cx: &mut App,
9623) {
9624 let destination_is_different = from_pane != to_pane;
9625 let mut moved_items = 0;
9626 for (item_ix, item_handle) in from_pane
9627 .read(cx)
9628 .items()
9629 .enumerate()
9630 .map(|(ix, item)| (ix, item.clone()))
9631 .collect::<Vec<_>>()
9632 {
9633 let ix = item_ix - moved_items;
9634 if destination_is_different {
9635 // Close item from previous pane
9636 from_pane.update(cx, |source, cx| {
9637 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
9638 });
9639 moved_items += 1;
9640 }
9641
9642 // This automatically removes duplicate items in the pane
9643 to_pane.update(cx, |destination, cx| {
9644 destination.add_item(item_handle, true, true, None, window, cx);
9645 window.focus(&destination.focus_handle(cx), cx)
9646 });
9647 }
9648}
9649
9650pub fn move_item(
9651 source: &Entity<Pane>,
9652 destination: &Entity<Pane>,
9653 item_id_to_move: EntityId,
9654 destination_index: usize,
9655 activate: bool,
9656 window: &mut Window,
9657 cx: &mut App,
9658) {
9659 let Some((item_ix, item_handle)) = source
9660 .read(cx)
9661 .items()
9662 .enumerate()
9663 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
9664 .map(|(ix, item)| (ix, item.clone()))
9665 else {
9666 // Tab was closed during drag
9667 return;
9668 };
9669
9670 if source != destination {
9671 // Close item from previous pane
9672 source.update(cx, |source, cx| {
9673 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
9674 });
9675 }
9676
9677 // This automatically removes duplicate items in the pane
9678 destination.update(cx, |destination, cx| {
9679 destination.add_item_inner(
9680 item_handle,
9681 activate,
9682 activate,
9683 activate,
9684 Some(destination_index),
9685 window,
9686 cx,
9687 );
9688 if activate {
9689 window.focus(&destination.focus_handle(cx), cx)
9690 }
9691 });
9692}
9693
9694pub fn move_active_item(
9695 source: &Entity<Pane>,
9696 destination: &Entity<Pane>,
9697 focus_destination: bool,
9698 close_if_empty: bool,
9699 window: &mut Window,
9700 cx: &mut App,
9701) {
9702 if source == destination {
9703 return;
9704 }
9705 let Some(active_item) = source.read(cx).active_item() else {
9706 return;
9707 };
9708 source.update(cx, |source_pane, cx| {
9709 let item_id = active_item.item_id();
9710 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
9711 destination.update(cx, |target_pane, cx| {
9712 target_pane.add_item(
9713 active_item,
9714 focus_destination,
9715 focus_destination,
9716 Some(target_pane.items_len()),
9717 window,
9718 cx,
9719 );
9720 });
9721 });
9722}
9723
9724pub fn clone_active_item(
9725 workspace_id: Option<WorkspaceId>,
9726 source: &Entity<Pane>,
9727 destination: &Entity<Pane>,
9728 focus_destination: bool,
9729 window: &mut Window,
9730 cx: &mut App,
9731) {
9732 if source == destination {
9733 return;
9734 }
9735 let Some(active_item) = source.read(cx).active_item() else {
9736 return;
9737 };
9738 if !active_item.can_split(cx) {
9739 return;
9740 }
9741 let destination = destination.downgrade();
9742 let task = active_item.clone_on_split(workspace_id, window, cx);
9743 window
9744 .spawn(cx, async move |cx| {
9745 let Some(clone) = task.await else {
9746 return;
9747 };
9748 destination
9749 .update_in(cx, |target_pane, window, cx| {
9750 target_pane.add_item(
9751 clone,
9752 focus_destination,
9753 focus_destination,
9754 Some(target_pane.items_len()),
9755 window,
9756 cx,
9757 );
9758 })
9759 .log_err();
9760 })
9761 .detach();
9762}
9763
9764#[derive(Debug)]
9765pub struct WorkspacePosition {
9766 pub window_bounds: Option<WindowBounds>,
9767 pub display: Option<Uuid>,
9768 pub centered_layout: bool,
9769}
9770
9771pub fn remote_workspace_position_from_db(
9772 connection_options: RemoteConnectionOptions,
9773 paths_to_open: &[PathBuf],
9774 cx: &App,
9775) -> Task<Result<WorkspacePosition>> {
9776 let paths = paths_to_open.to_vec();
9777
9778 cx.background_spawn(async move {
9779 let remote_connection_id = persistence::DB
9780 .get_or_create_remote_connection(connection_options)
9781 .await
9782 .context("fetching serialized ssh project")?;
9783 let serialized_workspace =
9784 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
9785
9786 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
9787 (Some(WindowBounds::Windowed(bounds)), None)
9788 } else {
9789 let restorable_bounds = serialized_workspace
9790 .as_ref()
9791 .and_then(|workspace| {
9792 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
9793 })
9794 .or_else(|| persistence::read_default_window_bounds());
9795
9796 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
9797 (Some(serialized_bounds), Some(serialized_display))
9798 } else {
9799 (None, None)
9800 }
9801 };
9802
9803 let centered_layout = serialized_workspace
9804 .as_ref()
9805 .map(|w| w.centered_layout)
9806 .unwrap_or(false);
9807
9808 Ok(WorkspacePosition {
9809 window_bounds,
9810 display,
9811 centered_layout,
9812 })
9813 })
9814}
9815
9816pub fn with_active_or_new_workspace(
9817 cx: &mut App,
9818 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
9819) {
9820 match cx
9821 .active_window()
9822 .and_then(|w| w.downcast::<MultiWorkspace>())
9823 {
9824 Some(multi_workspace) => {
9825 cx.defer(move |cx| {
9826 multi_workspace
9827 .update(cx, |multi_workspace, window, cx| {
9828 let workspace = multi_workspace.workspace().clone();
9829 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
9830 })
9831 .log_err();
9832 });
9833 }
9834 None => {
9835 let app_state = AppState::global(cx);
9836 if let Some(app_state) = app_state.upgrade() {
9837 open_new(
9838 OpenOptions::default(),
9839 app_state,
9840 cx,
9841 move |workspace, window, cx| f(workspace, window, cx),
9842 )
9843 .detach_and_log_err(cx);
9844 }
9845 }
9846 }
9847}
9848
9849#[cfg(test)]
9850mod tests {
9851 use std::{cell::RefCell, rc::Rc};
9852
9853 use super::*;
9854 use crate::{
9855 dock::{PanelEvent, test::TestPanel},
9856 item::{
9857 ItemBufferKind, ItemEvent,
9858 test::{TestItem, TestProjectItem},
9859 },
9860 };
9861 use fs::FakeFs;
9862 use gpui::{
9863 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
9864 UpdateGlobal, VisualTestContext, px,
9865 };
9866 use project::{Project, ProjectEntryId};
9867 use serde_json::json;
9868 use settings::SettingsStore;
9869 use util::rel_path::rel_path;
9870
9871 #[gpui::test]
9872 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
9873 init_test(cx);
9874
9875 let fs = FakeFs::new(cx.executor());
9876 let project = Project::test(fs, [], cx).await;
9877 let (workspace, cx) =
9878 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9879
9880 // Adding an item with no ambiguity renders the tab without detail.
9881 let item1 = cx.new(|cx| {
9882 let mut item = TestItem::new(cx);
9883 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
9884 item
9885 });
9886 workspace.update_in(cx, |workspace, window, cx| {
9887 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
9888 });
9889 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
9890
9891 // Adding an item that creates ambiguity increases the level of detail on
9892 // both tabs.
9893 let item2 = cx.new_window_entity(|_window, cx| {
9894 let mut item = TestItem::new(cx);
9895 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
9896 item
9897 });
9898 workspace.update_in(cx, |workspace, window, cx| {
9899 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
9900 });
9901 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
9902 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
9903
9904 // Adding an item that creates ambiguity increases the level of detail only
9905 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
9906 // we stop at the highest detail available.
9907 let item3 = cx.new(|cx| {
9908 let mut item = TestItem::new(cx);
9909 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
9910 item
9911 });
9912 workspace.update_in(cx, |workspace, window, cx| {
9913 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
9914 });
9915 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
9916 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
9917 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
9918 }
9919
9920 #[gpui::test]
9921 async fn test_tracking_active_path(cx: &mut TestAppContext) {
9922 init_test(cx);
9923
9924 let fs = FakeFs::new(cx.executor());
9925 fs.insert_tree(
9926 "/root1",
9927 json!({
9928 "one.txt": "",
9929 "two.txt": "",
9930 }),
9931 )
9932 .await;
9933 fs.insert_tree(
9934 "/root2",
9935 json!({
9936 "three.txt": "",
9937 }),
9938 )
9939 .await;
9940
9941 let project = Project::test(fs, ["root1".as_ref()], cx).await;
9942 let (workspace, cx) =
9943 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9944 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9945 let worktree_id = project.update(cx, |project, cx| {
9946 project.worktrees(cx).next().unwrap().read(cx).id()
9947 });
9948
9949 let item1 = cx.new(|cx| {
9950 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
9951 });
9952 let item2 = cx.new(|cx| {
9953 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
9954 });
9955
9956 // Add an item to an empty pane
9957 workspace.update_in(cx, |workspace, window, cx| {
9958 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
9959 });
9960 project.update(cx, |project, cx| {
9961 assert_eq!(
9962 project.active_entry(),
9963 project
9964 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
9965 .map(|e| e.id)
9966 );
9967 });
9968 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
9969
9970 // Add a second item to a non-empty pane
9971 workspace.update_in(cx, |workspace, window, cx| {
9972 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
9973 });
9974 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
9975 project.update(cx, |project, cx| {
9976 assert_eq!(
9977 project.active_entry(),
9978 project
9979 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
9980 .map(|e| e.id)
9981 );
9982 });
9983
9984 // Close the active item
9985 pane.update_in(cx, |pane, window, cx| {
9986 pane.close_active_item(&Default::default(), window, cx)
9987 })
9988 .await
9989 .unwrap();
9990 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
9991 project.update(cx, |project, cx| {
9992 assert_eq!(
9993 project.active_entry(),
9994 project
9995 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
9996 .map(|e| e.id)
9997 );
9998 });
9999
10000 // Add a project folder
10001 project
10002 .update(cx, |project, cx| {
10003 project.find_or_create_worktree("root2", true, cx)
10004 })
10005 .await
10006 .unwrap();
10007 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10008
10009 // Remove a project folder
10010 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10011 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10012 }
10013
10014 #[gpui::test]
10015 async fn test_close_window(cx: &mut TestAppContext) {
10016 init_test(cx);
10017
10018 let fs = FakeFs::new(cx.executor());
10019 fs.insert_tree("/root", json!({ "one": "" })).await;
10020
10021 let project = Project::test(fs, ["root".as_ref()], cx).await;
10022 let (workspace, cx) =
10023 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10024
10025 // When there are no dirty items, there's nothing to do.
10026 let item1 = cx.new(TestItem::new);
10027 workspace.update_in(cx, |w, window, cx| {
10028 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10029 });
10030 let task = workspace.update_in(cx, |w, window, cx| {
10031 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10032 });
10033 assert!(task.await.unwrap());
10034
10035 // When there are dirty untitled items, prompt to save each one. If the user
10036 // cancels any prompt, then abort.
10037 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10038 let item3 = cx.new(|cx| {
10039 TestItem::new(cx)
10040 .with_dirty(true)
10041 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10042 });
10043 workspace.update_in(cx, |w, window, cx| {
10044 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10045 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10046 });
10047 let task = workspace.update_in(cx, |w, window, cx| {
10048 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10049 });
10050 cx.executor().run_until_parked();
10051 cx.simulate_prompt_answer("Cancel"); // cancel save all
10052 cx.executor().run_until_parked();
10053 assert!(!cx.has_pending_prompt());
10054 assert!(!task.await.unwrap());
10055 }
10056
10057 #[gpui::test]
10058 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10059 init_test(cx);
10060
10061 // Register TestItem as a serializable item
10062 cx.update(|cx| {
10063 register_serializable_item::<TestItem>(cx);
10064 });
10065
10066 let fs = FakeFs::new(cx.executor());
10067 fs.insert_tree("/root", json!({ "one": "" })).await;
10068
10069 let project = Project::test(fs, ["root".as_ref()], cx).await;
10070 let (workspace, cx) =
10071 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10072
10073 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10074 let item1 = cx.new(|cx| {
10075 TestItem::new(cx)
10076 .with_dirty(true)
10077 .with_serialize(|| Some(Task::ready(Ok(()))))
10078 });
10079 let item2 = cx.new(|cx| {
10080 TestItem::new(cx)
10081 .with_dirty(true)
10082 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10083 .with_serialize(|| Some(Task::ready(Ok(()))))
10084 });
10085 workspace.update_in(cx, |w, window, cx| {
10086 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10087 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10088 });
10089 let task = workspace.update_in(cx, |w, window, cx| {
10090 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10091 });
10092 assert!(task.await.unwrap());
10093 }
10094
10095 #[gpui::test]
10096 async fn test_close_pane_items(cx: &mut TestAppContext) {
10097 init_test(cx);
10098
10099 let fs = FakeFs::new(cx.executor());
10100
10101 let project = Project::test(fs, None, cx).await;
10102 let (workspace, cx) =
10103 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10104
10105 let item1 = cx.new(|cx| {
10106 TestItem::new(cx)
10107 .with_dirty(true)
10108 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10109 });
10110 let item2 = cx.new(|cx| {
10111 TestItem::new(cx)
10112 .with_dirty(true)
10113 .with_conflict(true)
10114 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10115 });
10116 let item3 = cx.new(|cx| {
10117 TestItem::new(cx)
10118 .with_dirty(true)
10119 .with_conflict(true)
10120 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10121 });
10122 let item4 = cx.new(|cx| {
10123 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10124 let project_item = TestProjectItem::new_untitled(cx);
10125 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10126 project_item
10127 }])
10128 });
10129 let pane = workspace.update_in(cx, |workspace, window, cx| {
10130 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10131 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10132 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10133 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10134 workspace.active_pane().clone()
10135 });
10136
10137 let close_items = pane.update_in(cx, |pane, window, cx| {
10138 pane.activate_item(1, true, true, window, cx);
10139 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10140 let item1_id = item1.item_id();
10141 let item3_id = item3.item_id();
10142 let item4_id = item4.item_id();
10143 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10144 [item1_id, item3_id, item4_id].contains(&id)
10145 })
10146 });
10147 cx.executor().run_until_parked();
10148
10149 assert!(cx.has_pending_prompt());
10150 cx.simulate_prompt_answer("Save all");
10151
10152 cx.executor().run_until_parked();
10153
10154 // Item 1 is saved. There's a prompt to save item 3.
10155 pane.update(cx, |pane, cx| {
10156 assert_eq!(item1.read(cx).save_count, 1);
10157 assert_eq!(item1.read(cx).save_as_count, 0);
10158 assert_eq!(item1.read(cx).reload_count, 0);
10159 assert_eq!(pane.items_len(), 3);
10160 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10161 });
10162 assert!(cx.has_pending_prompt());
10163
10164 // Cancel saving item 3.
10165 cx.simulate_prompt_answer("Discard");
10166 cx.executor().run_until_parked();
10167
10168 // Item 3 is reloaded. There's a prompt to save item 4.
10169 pane.update(cx, |pane, cx| {
10170 assert_eq!(item3.read(cx).save_count, 0);
10171 assert_eq!(item3.read(cx).save_as_count, 0);
10172 assert_eq!(item3.read(cx).reload_count, 1);
10173 assert_eq!(pane.items_len(), 2);
10174 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10175 });
10176
10177 // There's a prompt for a path for item 4.
10178 cx.simulate_new_path_selection(|_| Some(Default::default()));
10179 close_items.await.unwrap();
10180
10181 // The requested items are closed.
10182 pane.update(cx, |pane, cx| {
10183 assert_eq!(item4.read(cx).save_count, 0);
10184 assert_eq!(item4.read(cx).save_as_count, 1);
10185 assert_eq!(item4.read(cx).reload_count, 0);
10186 assert_eq!(pane.items_len(), 1);
10187 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10188 });
10189 }
10190
10191 #[gpui::test]
10192 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10193 init_test(cx);
10194
10195 let fs = FakeFs::new(cx.executor());
10196 let project = Project::test(fs, [], cx).await;
10197 let (workspace, cx) =
10198 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10199
10200 // Create several workspace items with single project entries, and two
10201 // workspace items with multiple project entries.
10202 let single_entry_items = (0..=4)
10203 .map(|project_entry_id| {
10204 cx.new(|cx| {
10205 TestItem::new(cx)
10206 .with_dirty(true)
10207 .with_project_items(&[dirty_project_item(
10208 project_entry_id,
10209 &format!("{project_entry_id}.txt"),
10210 cx,
10211 )])
10212 })
10213 })
10214 .collect::<Vec<_>>();
10215 let item_2_3 = cx.new(|cx| {
10216 TestItem::new(cx)
10217 .with_dirty(true)
10218 .with_buffer_kind(ItemBufferKind::Multibuffer)
10219 .with_project_items(&[
10220 single_entry_items[2].read(cx).project_items[0].clone(),
10221 single_entry_items[3].read(cx).project_items[0].clone(),
10222 ])
10223 });
10224 let item_3_4 = cx.new(|cx| {
10225 TestItem::new(cx)
10226 .with_dirty(true)
10227 .with_buffer_kind(ItemBufferKind::Multibuffer)
10228 .with_project_items(&[
10229 single_entry_items[3].read(cx).project_items[0].clone(),
10230 single_entry_items[4].read(cx).project_items[0].clone(),
10231 ])
10232 });
10233
10234 // Create two panes that contain the following project entries:
10235 // left pane:
10236 // multi-entry items: (2, 3)
10237 // single-entry items: 0, 2, 3, 4
10238 // right pane:
10239 // single-entry items: 4, 1
10240 // multi-entry items: (3, 4)
10241 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10242 let left_pane = workspace.active_pane().clone();
10243 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10244 workspace.add_item_to_active_pane(
10245 single_entry_items[0].boxed_clone(),
10246 None,
10247 true,
10248 window,
10249 cx,
10250 );
10251 workspace.add_item_to_active_pane(
10252 single_entry_items[2].boxed_clone(),
10253 None,
10254 true,
10255 window,
10256 cx,
10257 );
10258 workspace.add_item_to_active_pane(
10259 single_entry_items[3].boxed_clone(),
10260 None,
10261 true,
10262 window,
10263 cx,
10264 );
10265 workspace.add_item_to_active_pane(
10266 single_entry_items[4].boxed_clone(),
10267 None,
10268 true,
10269 window,
10270 cx,
10271 );
10272
10273 let right_pane =
10274 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10275
10276 let boxed_clone = single_entry_items[1].boxed_clone();
10277 let right_pane = window.spawn(cx, async move |cx| {
10278 right_pane.await.inspect(|right_pane| {
10279 right_pane
10280 .update_in(cx, |pane, window, cx| {
10281 pane.add_item(boxed_clone, true, true, None, window, cx);
10282 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10283 })
10284 .unwrap();
10285 })
10286 });
10287
10288 (left_pane, right_pane)
10289 });
10290 let right_pane = right_pane.await.unwrap();
10291 cx.focus(&right_pane);
10292
10293 let close = right_pane.update_in(cx, |pane, window, cx| {
10294 pane.close_all_items(&CloseAllItems::default(), window, cx)
10295 .unwrap()
10296 });
10297 cx.executor().run_until_parked();
10298
10299 let msg = cx.pending_prompt().unwrap().0;
10300 assert!(msg.contains("1.txt"));
10301 assert!(!msg.contains("2.txt"));
10302 assert!(!msg.contains("3.txt"));
10303 assert!(!msg.contains("4.txt"));
10304
10305 // With best-effort close, cancelling item 1 keeps it open but items 4
10306 // and (3,4) still close since their entries exist in left pane.
10307 cx.simulate_prompt_answer("Cancel");
10308 close.await;
10309
10310 right_pane.read_with(cx, |pane, _| {
10311 assert_eq!(pane.items_len(), 1);
10312 });
10313
10314 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10315 left_pane
10316 .update_in(cx, |left_pane, window, cx| {
10317 left_pane.close_item_by_id(
10318 single_entry_items[3].entity_id(),
10319 SaveIntent::Skip,
10320 window,
10321 cx,
10322 )
10323 })
10324 .await
10325 .unwrap();
10326
10327 let close = left_pane.update_in(cx, |pane, window, cx| {
10328 pane.close_all_items(&CloseAllItems::default(), window, cx)
10329 .unwrap()
10330 });
10331 cx.executor().run_until_parked();
10332
10333 let details = cx.pending_prompt().unwrap().1;
10334 assert!(details.contains("0.txt"));
10335 assert!(details.contains("3.txt"));
10336 assert!(details.contains("4.txt"));
10337 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10338 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10339 // assert!(!details.contains("2.txt"));
10340
10341 cx.simulate_prompt_answer("Save all");
10342 cx.executor().run_until_parked();
10343 close.await;
10344
10345 left_pane.read_with(cx, |pane, _| {
10346 assert_eq!(pane.items_len(), 0);
10347 });
10348 }
10349
10350 #[gpui::test]
10351 async fn test_autosave(cx: &mut gpui::TestAppContext) {
10352 init_test(cx);
10353
10354 let fs = FakeFs::new(cx.executor());
10355 let project = Project::test(fs, [], cx).await;
10356 let (workspace, cx) =
10357 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10358 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10359
10360 let item = cx.new(|cx| {
10361 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10362 });
10363 let item_id = item.entity_id();
10364 workspace.update_in(cx, |workspace, window, cx| {
10365 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10366 });
10367
10368 // Autosave on window change.
10369 item.update(cx, |item, cx| {
10370 SettingsStore::update_global(cx, |settings, cx| {
10371 settings.update_user_settings(cx, |settings| {
10372 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10373 })
10374 });
10375 item.is_dirty = true;
10376 });
10377
10378 // Deactivating the window saves the file.
10379 cx.deactivate_window();
10380 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10381
10382 // Re-activating the window doesn't save the file.
10383 cx.update(|window, _| window.activate_window());
10384 cx.executor().run_until_parked();
10385 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10386
10387 // Autosave on focus change.
10388 item.update_in(cx, |item, window, cx| {
10389 cx.focus_self(window);
10390 SettingsStore::update_global(cx, |settings, cx| {
10391 settings.update_user_settings(cx, |settings| {
10392 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10393 })
10394 });
10395 item.is_dirty = true;
10396 });
10397 // Blurring the item saves the file.
10398 item.update_in(cx, |_, window, _| window.blur());
10399 cx.executor().run_until_parked();
10400 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10401
10402 // Deactivating the window still saves the file.
10403 item.update_in(cx, |item, window, cx| {
10404 cx.focus_self(window);
10405 item.is_dirty = true;
10406 });
10407 cx.deactivate_window();
10408 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10409
10410 // Autosave after delay.
10411 item.update(cx, |item, cx| {
10412 SettingsStore::update_global(cx, |settings, cx| {
10413 settings.update_user_settings(cx, |settings| {
10414 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10415 milliseconds: 500.into(),
10416 });
10417 })
10418 });
10419 item.is_dirty = true;
10420 cx.emit(ItemEvent::Edit);
10421 });
10422
10423 // Delay hasn't fully expired, so the file is still dirty and unsaved.
10424 cx.executor().advance_clock(Duration::from_millis(250));
10425 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10426
10427 // After delay expires, the file is saved.
10428 cx.executor().advance_clock(Duration::from_millis(250));
10429 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10430
10431 // Autosave after delay, should save earlier than delay if tab is closed
10432 item.update(cx, |item, cx| {
10433 item.is_dirty = true;
10434 cx.emit(ItemEvent::Edit);
10435 });
10436 cx.executor().advance_clock(Duration::from_millis(250));
10437 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10438
10439 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10440 pane.update_in(cx, |pane, window, cx| {
10441 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10442 })
10443 .await
10444 .unwrap();
10445 assert!(!cx.has_pending_prompt());
10446 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10447
10448 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10449 workspace.update_in(cx, |workspace, window, cx| {
10450 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10451 });
10452 item.update_in(cx, |item, _window, cx| {
10453 item.is_dirty = true;
10454 for project_item in &mut item.project_items {
10455 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10456 }
10457 });
10458 cx.run_until_parked();
10459 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10460
10461 // Autosave on focus change, ensuring closing the tab counts as such.
10462 item.update(cx, |item, cx| {
10463 SettingsStore::update_global(cx, |settings, cx| {
10464 settings.update_user_settings(cx, |settings| {
10465 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10466 })
10467 });
10468 item.is_dirty = true;
10469 for project_item in &mut item.project_items {
10470 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10471 }
10472 });
10473
10474 pane.update_in(cx, |pane, window, cx| {
10475 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10476 })
10477 .await
10478 .unwrap();
10479 assert!(!cx.has_pending_prompt());
10480 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10481
10482 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10483 workspace.update_in(cx, |workspace, window, cx| {
10484 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10485 });
10486 item.update_in(cx, |item, window, cx| {
10487 item.project_items[0].update(cx, |item, _| {
10488 item.entry_id = None;
10489 });
10490 item.is_dirty = true;
10491 window.blur();
10492 });
10493 cx.run_until_parked();
10494 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10495
10496 // Ensure autosave is prevented for deleted files also when closing the buffer.
10497 let _close_items = pane.update_in(cx, |pane, window, cx| {
10498 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10499 });
10500 cx.run_until_parked();
10501 assert!(cx.has_pending_prompt());
10502 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10503 }
10504
10505 #[gpui::test]
10506 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10507 init_test(cx);
10508
10509 let fs = FakeFs::new(cx.executor());
10510
10511 let project = Project::test(fs, [], cx).await;
10512 let (workspace, cx) =
10513 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10514
10515 let item = cx.new(|cx| {
10516 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10517 });
10518 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10519 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10520 let toolbar_notify_count = Rc::new(RefCell::new(0));
10521
10522 workspace.update_in(cx, |workspace, window, cx| {
10523 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10524 let toolbar_notification_count = toolbar_notify_count.clone();
10525 cx.observe_in(&toolbar, window, move |_, _, _, _| {
10526 *toolbar_notification_count.borrow_mut() += 1
10527 })
10528 .detach();
10529 });
10530
10531 pane.read_with(cx, |pane, _| {
10532 assert!(!pane.can_navigate_backward());
10533 assert!(!pane.can_navigate_forward());
10534 });
10535
10536 item.update_in(cx, |item, _, cx| {
10537 item.set_state("one".to_string(), cx);
10538 });
10539
10540 // Toolbar must be notified to re-render the navigation buttons
10541 assert_eq!(*toolbar_notify_count.borrow(), 1);
10542
10543 pane.read_with(cx, |pane, _| {
10544 assert!(pane.can_navigate_backward());
10545 assert!(!pane.can_navigate_forward());
10546 });
10547
10548 workspace
10549 .update_in(cx, |workspace, window, cx| {
10550 workspace.go_back(pane.downgrade(), window, cx)
10551 })
10552 .await
10553 .unwrap();
10554
10555 assert_eq!(*toolbar_notify_count.borrow(), 2);
10556 pane.read_with(cx, |pane, _| {
10557 assert!(!pane.can_navigate_backward());
10558 assert!(pane.can_navigate_forward());
10559 });
10560 }
10561
10562 #[gpui::test]
10563 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
10564 init_test(cx);
10565 let fs = FakeFs::new(cx.executor());
10566 let project = Project::test(fs, [], cx).await;
10567 let (workspace, cx) =
10568 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10569
10570 workspace.update_in(cx, |workspace, window, cx| {
10571 let first_item = cx.new(|cx| {
10572 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10573 });
10574 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
10575 workspace.split_pane(
10576 workspace.active_pane().clone(),
10577 SplitDirection::Right,
10578 window,
10579 cx,
10580 );
10581 workspace.split_pane(
10582 workspace.active_pane().clone(),
10583 SplitDirection::Right,
10584 window,
10585 cx,
10586 );
10587 });
10588
10589 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
10590 let panes = workspace.center.panes();
10591 assert!(panes.len() >= 2);
10592 (
10593 panes.first().expect("at least one pane").entity_id(),
10594 panes.last().expect("at least one pane").entity_id(),
10595 )
10596 });
10597
10598 workspace.update_in(cx, |workspace, window, cx| {
10599 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
10600 });
10601 workspace.update(cx, |workspace, _| {
10602 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
10603 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
10604 });
10605
10606 cx.dispatch_action(ActivateLastPane);
10607
10608 workspace.update(cx, |workspace, _| {
10609 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
10610 });
10611 }
10612
10613 #[gpui::test]
10614 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
10615 init_test(cx);
10616 let fs = FakeFs::new(cx.executor());
10617
10618 let project = Project::test(fs, [], cx).await;
10619 let (workspace, cx) =
10620 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10621
10622 let panel = workspace.update_in(cx, |workspace, window, cx| {
10623 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10624 workspace.add_panel(panel.clone(), window, cx);
10625
10626 workspace
10627 .right_dock()
10628 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10629
10630 panel
10631 });
10632
10633 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10634 pane.update_in(cx, |pane, window, cx| {
10635 let item = cx.new(TestItem::new);
10636 pane.add_item(Box::new(item), true, true, None, window, cx);
10637 });
10638
10639 // Transfer focus from center to panel
10640 workspace.update_in(cx, |workspace, window, cx| {
10641 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10642 });
10643
10644 workspace.update_in(cx, |workspace, window, cx| {
10645 assert!(workspace.right_dock().read(cx).is_open());
10646 assert!(!panel.is_zoomed(window, cx));
10647 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10648 });
10649
10650 // Transfer focus from panel to center
10651 workspace.update_in(cx, |workspace, window, cx| {
10652 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10653 });
10654
10655 workspace.update_in(cx, |workspace, window, cx| {
10656 assert!(workspace.right_dock().read(cx).is_open());
10657 assert!(!panel.is_zoomed(window, cx));
10658 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10659 });
10660
10661 // Close the dock
10662 workspace.update_in(cx, |workspace, window, cx| {
10663 workspace.toggle_dock(DockPosition::Right, window, cx);
10664 });
10665
10666 workspace.update_in(cx, |workspace, window, cx| {
10667 assert!(!workspace.right_dock().read(cx).is_open());
10668 assert!(!panel.is_zoomed(window, cx));
10669 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10670 });
10671
10672 // Open the dock
10673 workspace.update_in(cx, |workspace, window, cx| {
10674 workspace.toggle_dock(DockPosition::Right, window, cx);
10675 });
10676
10677 workspace.update_in(cx, |workspace, window, cx| {
10678 assert!(workspace.right_dock().read(cx).is_open());
10679 assert!(!panel.is_zoomed(window, cx));
10680 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10681 });
10682
10683 // Focus and zoom panel
10684 panel.update_in(cx, |panel, window, cx| {
10685 cx.focus_self(window);
10686 panel.set_zoomed(true, window, cx)
10687 });
10688
10689 workspace.update_in(cx, |workspace, window, cx| {
10690 assert!(workspace.right_dock().read(cx).is_open());
10691 assert!(panel.is_zoomed(window, cx));
10692 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10693 });
10694
10695 // Transfer focus to the center closes the dock
10696 workspace.update_in(cx, |workspace, window, cx| {
10697 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10698 });
10699
10700 workspace.update_in(cx, |workspace, window, cx| {
10701 assert!(!workspace.right_dock().read(cx).is_open());
10702 assert!(panel.is_zoomed(window, cx));
10703 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10704 });
10705
10706 // Transferring focus back to the panel keeps it zoomed
10707 workspace.update_in(cx, |workspace, window, cx| {
10708 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10709 });
10710
10711 workspace.update_in(cx, |workspace, window, cx| {
10712 assert!(workspace.right_dock().read(cx).is_open());
10713 assert!(panel.is_zoomed(window, cx));
10714 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10715 });
10716
10717 // Close the dock while it is zoomed
10718 workspace.update_in(cx, |workspace, window, cx| {
10719 workspace.toggle_dock(DockPosition::Right, window, cx)
10720 });
10721
10722 workspace.update_in(cx, |workspace, window, cx| {
10723 assert!(!workspace.right_dock().read(cx).is_open());
10724 assert!(panel.is_zoomed(window, cx));
10725 assert!(workspace.zoomed.is_none());
10726 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10727 });
10728
10729 // Opening the dock, when it's zoomed, retains focus
10730 workspace.update_in(cx, |workspace, window, cx| {
10731 workspace.toggle_dock(DockPosition::Right, window, cx)
10732 });
10733
10734 workspace.update_in(cx, |workspace, window, cx| {
10735 assert!(workspace.right_dock().read(cx).is_open());
10736 assert!(panel.is_zoomed(window, cx));
10737 assert!(workspace.zoomed.is_some());
10738 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10739 });
10740
10741 // Unzoom and close the panel, zoom the active pane.
10742 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
10743 workspace.update_in(cx, |workspace, window, cx| {
10744 workspace.toggle_dock(DockPosition::Right, window, cx)
10745 });
10746 pane.update_in(cx, |pane, window, cx| {
10747 pane.toggle_zoom(&Default::default(), window, cx)
10748 });
10749
10750 // Opening a dock unzooms the pane.
10751 workspace.update_in(cx, |workspace, window, cx| {
10752 workspace.toggle_dock(DockPosition::Right, window, cx)
10753 });
10754 workspace.update_in(cx, |workspace, window, cx| {
10755 let pane = pane.read(cx);
10756 assert!(!pane.is_zoomed());
10757 assert!(!pane.focus_handle(cx).is_focused(window));
10758 assert!(workspace.right_dock().read(cx).is_open());
10759 assert!(workspace.zoomed.is_none());
10760 });
10761 }
10762
10763 #[gpui::test]
10764 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
10765 init_test(cx);
10766 let fs = FakeFs::new(cx.executor());
10767
10768 let project = Project::test(fs, [], cx).await;
10769 let (workspace, cx) =
10770 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10771
10772 let panel = workspace.update_in(cx, |workspace, window, cx| {
10773 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10774 workspace.add_panel(panel.clone(), window, cx);
10775 panel
10776 });
10777
10778 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10779 pane.update_in(cx, |pane, window, cx| {
10780 let item = cx.new(TestItem::new);
10781 pane.add_item(Box::new(item), true, true, None, window, cx);
10782 });
10783
10784 // Enable close_panel_on_toggle
10785 cx.update_global(|store: &mut SettingsStore, cx| {
10786 store.update_user_settings(cx, |settings| {
10787 settings.workspace.close_panel_on_toggle = Some(true);
10788 });
10789 });
10790
10791 // Panel starts closed. Toggling should open and focus it.
10792 workspace.update_in(cx, |workspace, window, cx| {
10793 assert!(!workspace.right_dock().read(cx).is_open());
10794 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10795 });
10796
10797 workspace.update_in(cx, |workspace, window, cx| {
10798 assert!(
10799 workspace.right_dock().read(cx).is_open(),
10800 "Dock should be open after toggling from center"
10801 );
10802 assert!(
10803 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10804 "Panel should be focused after toggling from center"
10805 );
10806 });
10807
10808 // Panel is open and focused. Toggling should close the panel and
10809 // return focus to the center.
10810 workspace.update_in(cx, |workspace, window, cx| {
10811 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10812 });
10813
10814 workspace.update_in(cx, |workspace, window, cx| {
10815 assert!(
10816 !workspace.right_dock().read(cx).is_open(),
10817 "Dock should be closed after toggling from focused panel"
10818 );
10819 assert!(
10820 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10821 "Panel should not be focused after toggling from focused panel"
10822 );
10823 });
10824
10825 // Open the dock and focus something else so the panel is open but not
10826 // focused. Toggling should focus the panel (not close it).
10827 workspace.update_in(cx, |workspace, window, cx| {
10828 workspace
10829 .right_dock()
10830 .update(cx, |dock, cx| dock.set_open(true, window, cx));
10831 window.focus(&pane.read(cx).focus_handle(cx), cx);
10832 });
10833
10834 workspace.update_in(cx, |workspace, window, cx| {
10835 assert!(workspace.right_dock().read(cx).is_open());
10836 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10837 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10838 });
10839
10840 workspace.update_in(cx, |workspace, window, cx| {
10841 assert!(
10842 workspace.right_dock().read(cx).is_open(),
10843 "Dock should remain open when toggling focuses an open-but-unfocused panel"
10844 );
10845 assert!(
10846 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10847 "Panel should be focused after toggling an open-but-unfocused panel"
10848 );
10849 });
10850
10851 // Now disable the setting and verify the original behavior: toggling
10852 // from a focused panel moves focus to center but leaves the dock open.
10853 cx.update_global(|store: &mut SettingsStore, cx| {
10854 store.update_user_settings(cx, |settings| {
10855 settings.workspace.close_panel_on_toggle = Some(false);
10856 });
10857 });
10858
10859 workspace.update_in(cx, |workspace, window, cx| {
10860 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10861 });
10862
10863 workspace.update_in(cx, |workspace, window, cx| {
10864 assert!(
10865 workspace.right_dock().read(cx).is_open(),
10866 "Dock should remain open when setting is disabled"
10867 );
10868 assert!(
10869 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10870 "Panel should not be focused after toggling with setting disabled"
10871 );
10872 });
10873 }
10874
10875 #[gpui::test]
10876 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
10877 init_test(cx);
10878 let fs = FakeFs::new(cx.executor());
10879
10880 let project = Project::test(fs, [], cx).await;
10881 let (workspace, cx) =
10882 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10883
10884 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
10885 workspace.active_pane().clone()
10886 });
10887
10888 // Add an item to the pane so it can be zoomed
10889 workspace.update_in(cx, |workspace, window, cx| {
10890 let item = cx.new(TestItem::new);
10891 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
10892 });
10893
10894 // Initially not zoomed
10895 workspace.update_in(cx, |workspace, _window, cx| {
10896 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
10897 assert!(
10898 workspace.zoomed.is_none(),
10899 "Workspace should track no zoomed pane"
10900 );
10901 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
10902 });
10903
10904 // Zoom In
10905 pane.update_in(cx, |pane, window, cx| {
10906 pane.zoom_in(&crate::ZoomIn, window, cx);
10907 });
10908
10909 workspace.update_in(cx, |workspace, window, cx| {
10910 assert!(
10911 pane.read(cx).is_zoomed(),
10912 "Pane should be zoomed after ZoomIn"
10913 );
10914 assert!(
10915 workspace.zoomed.is_some(),
10916 "Workspace should track the zoomed pane"
10917 );
10918 assert!(
10919 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
10920 "ZoomIn should focus the pane"
10921 );
10922 });
10923
10924 // Zoom In again is a no-op
10925 pane.update_in(cx, |pane, window, cx| {
10926 pane.zoom_in(&crate::ZoomIn, window, cx);
10927 });
10928
10929 workspace.update_in(cx, |workspace, window, cx| {
10930 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
10931 assert!(
10932 workspace.zoomed.is_some(),
10933 "Workspace still tracks zoomed pane"
10934 );
10935 assert!(
10936 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
10937 "Pane remains focused after repeated ZoomIn"
10938 );
10939 });
10940
10941 // Zoom Out
10942 pane.update_in(cx, |pane, window, cx| {
10943 pane.zoom_out(&crate::ZoomOut, window, cx);
10944 });
10945
10946 workspace.update_in(cx, |workspace, _window, cx| {
10947 assert!(
10948 !pane.read(cx).is_zoomed(),
10949 "Pane should unzoom after ZoomOut"
10950 );
10951 assert!(
10952 workspace.zoomed.is_none(),
10953 "Workspace clears zoom tracking after ZoomOut"
10954 );
10955 });
10956
10957 // Zoom Out again is a no-op
10958 pane.update_in(cx, |pane, window, cx| {
10959 pane.zoom_out(&crate::ZoomOut, window, cx);
10960 });
10961
10962 workspace.update_in(cx, |workspace, _window, cx| {
10963 assert!(
10964 !pane.read(cx).is_zoomed(),
10965 "Second ZoomOut keeps pane unzoomed"
10966 );
10967 assert!(
10968 workspace.zoomed.is_none(),
10969 "Workspace remains without zoomed pane"
10970 );
10971 });
10972 }
10973
10974 #[gpui::test]
10975 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
10976 init_test(cx);
10977 let fs = FakeFs::new(cx.executor());
10978
10979 let project = Project::test(fs, [], cx).await;
10980 let (workspace, cx) =
10981 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10982 workspace.update_in(cx, |workspace, window, cx| {
10983 // Open two docks
10984 let left_dock = workspace.dock_at_position(DockPosition::Left);
10985 let right_dock = workspace.dock_at_position(DockPosition::Right);
10986
10987 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10988 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10989
10990 assert!(left_dock.read(cx).is_open());
10991 assert!(right_dock.read(cx).is_open());
10992 });
10993
10994 workspace.update_in(cx, |workspace, window, cx| {
10995 // Toggle all docks - should close both
10996 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10997
10998 let left_dock = workspace.dock_at_position(DockPosition::Left);
10999 let right_dock = workspace.dock_at_position(DockPosition::Right);
11000 assert!(!left_dock.read(cx).is_open());
11001 assert!(!right_dock.read(cx).is_open());
11002 });
11003
11004 workspace.update_in(cx, |workspace, window, cx| {
11005 // Toggle again - should reopen both
11006 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11007
11008 let left_dock = workspace.dock_at_position(DockPosition::Left);
11009 let right_dock = workspace.dock_at_position(DockPosition::Right);
11010 assert!(left_dock.read(cx).is_open());
11011 assert!(right_dock.read(cx).is_open());
11012 });
11013 }
11014
11015 #[gpui::test]
11016 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11017 init_test(cx);
11018 let fs = FakeFs::new(cx.executor());
11019
11020 let project = Project::test(fs, [], cx).await;
11021 let (workspace, cx) =
11022 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11023 workspace.update_in(cx, |workspace, window, cx| {
11024 // Open two docks
11025 let left_dock = workspace.dock_at_position(DockPosition::Left);
11026 let right_dock = workspace.dock_at_position(DockPosition::Right);
11027
11028 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11029 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11030
11031 assert!(left_dock.read(cx).is_open());
11032 assert!(right_dock.read(cx).is_open());
11033 });
11034
11035 workspace.update_in(cx, |workspace, window, cx| {
11036 // Close them manually
11037 workspace.toggle_dock(DockPosition::Left, window, cx);
11038 workspace.toggle_dock(DockPosition::Right, window, cx);
11039
11040 let left_dock = workspace.dock_at_position(DockPosition::Left);
11041 let right_dock = workspace.dock_at_position(DockPosition::Right);
11042 assert!(!left_dock.read(cx).is_open());
11043 assert!(!right_dock.read(cx).is_open());
11044 });
11045
11046 workspace.update_in(cx, |workspace, window, cx| {
11047 // Toggle all docks - only last closed (right dock) should reopen
11048 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11049
11050 let left_dock = workspace.dock_at_position(DockPosition::Left);
11051 let right_dock = workspace.dock_at_position(DockPosition::Right);
11052 assert!(!left_dock.read(cx).is_open());
11053 assert!(right_dock.read(cx).is_open());
11054 });
11055 }
11056
11057 #[gpui::test]
11058 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11059 init_test(cx);
11060 let fs = FakeFs::new(cx.executor());
11061 let project = Project::test(fs, [], cx).await;
11062 let (workspace, cx) =
11063 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11064
11065 // Open two docks (left and right) with one panel each
11066 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11067 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11068 workspace.add_panel(left_panel.clone(), window, cx);
11069
11070 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11071 workspace.add_panel(right_panel.clone(), window, cx);
11072
11073 workspace.toggle_dock(DockPosition::Left, window, cx);
11074 workspace.toggle_dock(DockPosition::Right, window, cx);
11075
11076 // Verify initial state
11077 assert!(
11078 workspace.left_dock().read(cx).is_open(),
11079 "Left dock should be open"
11080 );
11081 assert_eq!(
11082 workspace
11083 .left_dock()
11084 .read(cx)
11085 .visible_panel()
11086 .unwrap()
11087 .panel_id(),
11088 left_panel.panel_id(),
11089 "Left panel should be visible in left dock"
11090 );
11091 assert!(
11092 workspace.right_dock().read(cx).is_open(),
11093 "Right dock should be open"
11094 );
11095 assert_eq!(
11096 workspace
11097 .right_dock()
11098 .read(cx)
11099 .visible_panel()
11100 .unwrap()
11101 .panel_id(),
11102 right_panel.panel_id(),
11103 "Right panel should be visible in right dock"
11104 );
11105 assert!(
11106 !workspace.bottom_dock().read(cx).is_open(),
11107 "Bottom dock should be closed"
11108 );
11109
11110 (left_panel, right_panel)
11111 });
11112
11113 // Focus the left panel and move it to the next position (bottom dock)
11114 workspace.update_in(cx, |workspace, window, cx| {
11115 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11116 assert!(
11117 left_panel.read(cx).focus_handle(cx).is_focused(window),
11118 "Left panel should be focused"
11119 );
11120 });
11121
11122 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11123
11124 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11125 workspace.update(cx, |workspace, cx| {
11126 assert!(
11127 !workspace.left_dock().read(cx).is_open(),
11128 "Left dock should be closed"
11129 );
11130 assert!(
11131 workspace.bottom_dock().read(cx).is_open(),
11132 "Bottom dock should now be open"
11133 );
11134 assert_eq!(
11135 left_panel.read(cx).position,
11136 DockPosition::Bottom,
11137 "Left panel should now be in the bottom dock"
11138 );
11139 assert_eq!(
11140 workspace
11141 .bottom_dock()
11142 .read(cx)
11143 .visible_panel()
11144 .unwrap()
11145 .panel_id(),
11146 left_panel.panel_id(),
11147 "Left panel should be the visible panel in the bottom dock"
11148 );
11149 });
11150
11151 // Toggle all docks off
11152 workspace.update_in(cx, |workspace, window, cx| {
11153 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11154 assert!(
11155 !workspace.left_dock().read(cx).is_open(),
11156 "Left dock should be closed"
11157 );
11158 assert!(
11159 !workspace.right_dock().read(cx).is_open(),
11160 "Right dock should be closed"
11161 );
11162 assert!(
11163 !workspace.bottom_dock().read(cx).is_open(),
11164 "Bottom dock should be closed"
11165 );
11166 });
11167
11168 // Toggle all docks back on and verify positions are restored
11169 workspace.update_in(cx, |workspace, window, cx| {
11170 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11171 assert!(
11172 !workspace.left_dock().read(cx).is_open(),
11173 "Left dock should remain closed"
11174 );
11175 assert!(
11176 workspace.right_dock().read(cx).is_open(),
11177 "Right dock should remain open"
11178 );
11179 assert!(
11180 workspace.bottom_dock().read(cx).is_open(),
11181 "Bottom dock should remain open"
11182 );
11183 assert_eq!(
11184 left_panel.read(cx).position,
11185 DockPosition::Bottom,
11186 "Left panel should remain in the bottom dock"
11187 );
11188 assert_eq!(
11189 right_panel.read(cx).position,
11190 DockPosition::Right,
11191 "Right panel should remain in the right dock"
11192 );
11193 assert_eq!(
11194 workspace
11195 .bottom_dock()
11196 .read(cx)
11197 .visible_panel()
11198 .unwrap()
11199 .panel_id(),
11200 left_panel.panel_id(),
11201 "Left panel should be the visible panel in the right dock"
11202 );
11203 });
11204 }
11205
11206 #[gpui::test]
11207 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11208 init_test(cx);
11209
11210 let fs = FakeFs::new(cx.executor());
11211
11212 let project = Project::test(fs, None, cx).await;
11213 let (workspace, cx) =
11214 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11215
11216 // Let's arrange the panes like this:
11217 //
11218 // +-----------------------+
11219 // | top |
11220 // +------+--------+-------+
11221 // | left | center | right |
11222 // +------+--------+-------+
11223 // | bottom |
11224 // +-----------------------+
11225
11226 let top_item = cx.new(|cx| {
11227 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11228 });
11229 let bottom_item = cx.new(|cx| {
11230 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11231 });
11232 let left_item = cx.new(|cx| {
11233 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11234 });
11235 let right_item = cx.new(|cx| {
11236 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11237 });
11238 let center_item = cx.new(|cx| {
11239 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11240 });
11241
11242 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11243 let top_pane_id = workspace.active_pane().entity_id();
11244 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11245 workspace.split_pane(
11246 workspace.active_pane().clone(),
11247 SplitDirection::Down,
11248 window,
11249 cx,
11250 );
11251 top_pane_id
11252 });
11253 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11254 let bottom_pane_id = workspace.active_pane().entity_id();
11255 workspace.add_item_to_active_pane(
11256 Box::new(bottom_item.clone()),
11257 None,
11258 false,
11259 window,
11260 cx,
11261 );
11262 workspace.split_pane(
11263 workspace.active_pane().clone(),
11264 SplitDirection::Up,
11265 window,
11266 cx,
11267 );
11268 bottom_pane_id
11269 });
11270 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11271 let left_pane_id = workspace.active_pane().entity_id();
11272 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11273 workspace.split_pane(
11274 workspace.active_pane().clone(),
11275 SplitDirection::Right,
11276 window,
11277 cx,
11278 );
11279 left_pane_id
11280 });
11281 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11282 let right_pane_id = workspace.active_pane().entity_id();
11283 workspace.add_item_to_active_pane(
11284 Box::new(right_item.clone()),
11285 None,
11286 false,
11287 window,
11288 cx,
11289 );
11290 workspace.split_pane(
11291 workspace.active_pane().clone(),
11292 SplitDirection::Left,
11293 window,
11294 cx,
11295 );
11296 right_pane_id
11297 });
11298 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11299 let center_pane_id = workspace.active_pane().entity_id();
11300 workspace.add_item_to_active_pane(
11301 Box::new(center_item.clone()),
11302 None,
11303 false,
11304 window,
11305 cx,
11306 );
11307 center_pane_id
11308 });
11309 cx.executor().run_until_parked();
11310
11311 workspace.update_in(cx, |workspace, window, cx| {
11312 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11313
11314 // Join into next from center pane into right
11315 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11316 });
11317
11318 workspace.update_in(cx, |workspace, window, cx| {
11319 let active_pane = workspace.active_pane();
11320 assert_eq!(right_pane_id, active_pane.entity_id());
11321 assert_eq!(2, active_pane.read(cx).items_len());
11322 let item_ids_in_pane =
11323 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11324 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11325 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11326
11327 // Join into next from right pane into bottom
11328 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11329 });
11330
11331 workspace.update_in(cx, |workspace, window, cx| {
11332 let active_pane = workspace.active_pane();
11333 assert_eq!(bottom_pane_id, active_pane.entity_id());
11334 assert_eq!(3, active_pane.read(cx).items_len());
11335 let item_ids_in_pane =
11336 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11337 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11338 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11339 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11340
11341 // Join into next from bottom pane into left
11342 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11343 });
11344
11345 workspace.update_in(cx, |workspace, window, cx| {
11346 let active_pane = workspace.active_pane();
11347 assert_eq!(left_pane_id, active_pane.entity_id());
11348 assert_eq!(4, active_pane.read(cx).items_len());
11349 let item_ids_in_pane =
11350 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11351 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11352 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11353 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11354 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11355
11356 // Join into next from left pane into top
11357 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11358 });
11359
11360 workspace.update_in(cx, |workspace, window, cx| {
11361 let active_pane = workspace.active_pane();
11362 assert_eq!(top_pane_id, active_pane.entity_id());
11363 assert_eq!(5, active_pane.read(cx).items_len());
11364 let item_ids_in_pane =
11365 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11366 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11367 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11368 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11369 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11370 assert!(item_ids_in_pane.contains(&top_item.item_id()));
11371
11372 // Single pane left: no-op
11373 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11374 });
11375
11376 workspace.update(cx, |workspace, _cx| {
11377 let active_pane = workspace.active_pane();
11378 assert_eq!(top_pane_id, active_pane.entity_id());
11379 });
11380 }
11381
11382 fn add_an_item_to_active_pane(
11383 cx: &mut VisualTestContext,
11384 workspace: &Entity<Workspace>,
11385 item_id: u64,
11386 ) -> Entity<TestItem> {
11387 let item = cx.new(|cx| {
11388 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11389 item_id,
11390 "item{item_id}.txt",
11391 cx,
11392 )])
11393 });
11394 workspace.update_in(cx, |workspace, window, cx| {
11395 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11396 });
11397 item
11398 }
11399
11400 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11401 workspace.update_in(cx, |workspace, window, cx| {
11402 workspace.split_pane(
11403 workspace.active_pane().clone(),
11404 SplitDirection::Right,
11405 window,
11406 cx,
11407 )
11408 })
11409 }
11410
11411 #[gpui::test]
11412 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11413 init_test(cx);
11414 let fs = FakeFs::new(cx.executor());
11415 let project = Project::test(fs, None, cx).await;
11416 let (workspace, cx) =
11417 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11418
11419 add_an_item_to_active_pane(cx, &workspace, 1);
11420 split_pane(cx, &workspace);
11421 add_an_item_to_active_pane(cx, &workspace, 2);
11422 split_pane(cx, &workspace); // empty pane
11423 split_pane(cx, &workspace);
11424 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11425
11426 cx.executor().run_until_parked();
11427
11428 workspace.update(cx, |workspace, cx| {
11429 let num_panes = workspace.panes().len();
11430 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11431 let active_item = workspace
11432 .active_pane()
11433 .read(cx)
11434 .active_item()
11435 .expect("item is in focus");
11436
11437 assert_eq!(num_panes, 4);
11438 assert_eq!(num_items_in_current_pane, 1);
11439 assert_eq!(active_item.item_id(), last_item.item_id());
11440 });
11441
11442 workspace.update_in(cx, |workspace, window, cx| {
11443 workspace.join_all_panes(window, cx);
11444 });
11445
11446 workspace.update(cx, |workspace, cx| {
11447 let num_panes = workspace.panes().len();
11448 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11449 let active_item = workspace
11450 .active_pane()
11451 .read(cx)
11452 .active_item()
11453 .expect("item is in focus");
11454
11455 assert_eq!(num_panes, 1);
11456 assert_eq!(num_items_in_current_pane, 3);
11457 assert_eq!(active_item.item_id(), last_item.item_id());
11458 });
11459 }
11460 struct TestModal(FocusHandle);
11461
11462 impl TestModal {
11463 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11464 Self(cx.focus_handle())
11465 }
11466 }
11467
11468 impl EventEmitter<DismissEvent> for TestModal {}
11469
11470 impl Focusable for TestModal {
11471 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11472 self.0.clone()
11473 }
11474 }
11475
11476 impl ModalView for TestModal {}
11477
11478 impl Render for TestModal {
11479 fn render(
11480 &mut self,
11481 _window: &mut Window,
11482 _cx: &mut Context<TestModal>,
11483 ) -> impl IntoElement {
11484 div().track_focus(&self.0)
11485 }
11486 }
11487
11488 #[gpui::test]
11489 async fn test_panels(cx: &mut gpui::TestAppContext) {
11490 init_test(cx);
11491 let fs = FakeFs::new(cx.executor());
11492
11493 let project = Project::test(fs, [], cx).await;
11494 let (workspace, cx) =
11495 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11496
11497 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11498 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11499 workspace.add_panel(panel_1.clone(), window, cx);
11500 workspace.toggle_dock(DockPosition::Left, window, cx);
11501 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11502 workspace.add_panel(panel_2.clone(), window, cx);
11503 workspace.toggle_dock(DockPosition::Right, window, cx);
11504
11505 let left_dock = workspace.left_dock();
11506 assert_eq!(
11507 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11508 panel_1.panel_id()
11509 );
11510 assert_eq!(
11511 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11512 panel_1.size(window, cx)
11513 );
11514
11515 left_dock.update(cx, |left_dock, cx| {
11516 left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11517 });
11518 assert_eq!(
11519 workspace
11520 .right_dock()
11521 .read(cx)
11522 .visible_panel()
11523 .unwrap()
11524 .panel_id(),
11525 panel_2.panel_id(),
11526 );
11527
11528 (panel_1, panel_2)
11529 });
11530
11531 // Move panel_1 to the right
11532 panel_1.update_in(cx, |panel_1, window, cx| {
11533 panel_1.set_position(DockPosition::Right, window, cx)
11534 });
11535
11536 workspace.update_in(cx, |workspace, window, cx| {
11537 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11538 // Since it was the only panel on the left, the left dock should now be closed.
11539 assert!(!workspace.left_dock().read(cx).is_open());
11540 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11541 let right_dock = workspace.right_dock();
11542 assert_eq!(
11543 right_dock.read(cx).visible_panel().unwrap().panel_id(),
11544 panel_1.panel_id()
11545 );
11546 assert_eq!(
11547 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11548 px(1337.)
11549 );
11550
11551 // Now we move panel_2 to the left
11552 panel_2.set_position(DockPosition::Left, window, cx);
11553 });
11554
11555 workspace.update(cx, |workspace, cx| {
11556 // Since panel_2 was not visible on the right, we don't open the left dock.
11557 assert!(!workspace.left_dock().read(cx).is_open());
11558 // And the right dock is unaffected in its displaying of panel_1
11559 assert!(workspace.right_dock().read(cx).is_open());
11560 assert_eq!(
11561 workspace
11562 .right_dock()
11563 .read(cx)
11564 .visible_panel()
11565 .unwrap()
11566 .panel_id(),
11567 panel_1.panel_id(),
11568 );
11569 });
11570
11571 // Move panel_1 back to the left
11572 panel_1.update_in(cx, |panel_1, window, cx| {
11573 panel_1.set_position(DockPosition::Left, window, cx)
11574 });
11575
11576 workspace.update_in(cx, |workspace, window, cx| {
11577 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
11578 let left_dock = workspace.left_dock();
11579 assert!(left_dock.read(cx).is_open());
11580 assert_eq!(
11581 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11582 panel_1.panel_id()
11583 );
11584 assert_eq!(
11585 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11586 px(1337.)
11587 );
11588 // And the right dock should be closed as it no longer has any panels.
11589 assert!(!workspace.right_dock().read(cx).is_open());
11590
11591 // Now we move panel_1 to the bottom
11592 panel_1.set_position(DockPosition::Bottom, window, cx);
11593 });
11594
11595 workspace.update_in(cx, |workspace, window, cx| {
11596 // Since panel_1 was visible on the left, we close the left dock.
11597 assert!(!workspace.left_dock().read(cx).is_open());
11598 // The bottom dock is sized based on the panel's default size,
11599 // since the panel orientation changed from vertical to horizontal.
11600 let bottom_dock = workspace.bottom_dock();
11601 assert_eq!(
11602 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
11603 panel_1.size(window, cx),
11604 );
11605 // Close bottom dock and move panel_1 back to the left.
11606 bottom_dock.update(cx, |bottom_dock, cx| {
11607 bottom_dock.set_open(false, window, cx)
11608 });
11609 panel_1.set_position(DockPosition::Left, window, cx);
11610 });
11611
11612 // Emit activated event on panel 1
11613 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
11614
11615 // Now the left dock is open and panel_1 is active and focused.
11616 workspace.update_in(cx, |workspace, window, cx| {
11617 let left_dock = workspace.left_dock();
11618 assert!(left_dock.read(cx).is_open());
11619 assert_eq!(
11620 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11621 panel_1.panel_id(),
11622 );
11623 assert!(panel_1.focus_handle(cx).is_focused(window));
11624 });
11625
11626 // Emit closed event on panel 2, which is not active
11627 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11628
11629 // Wo don't close the left dock, because panel_2 wasn't the active panel
11630 workspace.update(cx, |workspace, cx| {
11631 let left_dock = workspace.left_dock();
11632 assert!(left_dock.read(cx).is_open());
11633 assert_eq!(
11634 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11635 panel_1.panel_id(),
11636 );
11637 });
11638
11639 // Emitting a ZoomIn event shows the panel as zoomed.
11640 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
11641 workspace.read_with(cx, |workspace, _| {
11642 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11643 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
11644 });
11645
11646 // Move panel to another dock while it is zoomed
11647 panel_1.update_in(cx, |panel, window, cx| {
11648 panel.set_position(DockPosition::Right, window, cx)
11649 });
11650 workspace.read_with(cx, |workspace, _| {
11651 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11652
11653 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11654 });
11655
11656 // This is a helper for getting a:
11657 // - valid focus on an element,
11658 // - that isn't a part of the panes and panels system of the Workspace,
11659 // - and doesn't trigger the 'on_focus_lost' API.
11660 let focus_other_view = {
11661 let workspace = workspace.clone();
11662 move |cx: &mut VisualTestContext| {
11663 workspace.update_in(cx, |workspace, window, cx| {
11664 if workspace.active_modal::<TestModal>(cx).is_some() {
11665 workspace.toggle_modal(window, cx, TestModal::new);
11666 workspace.toggle_modal(window, cx, TestModal::new);
11667 } else {
11668 workspace.toggle_modal(window, cx, TestModal::new);
11669 }
11670 })
11671 }
11672 };
11673
11674 // If focus is transferred to another view that's not a panel or another pane, we still show
11675 // the panel as zoomed.
11676 focus_other_view(cx);
11677 workspace.read_with(cx, |workspace, _| {
11678 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11679 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11680 });
11681
11682 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
11683 workspace.update_in(cx, |_workspace, window, cx| {
11684 cx.focus_self(window);
11685 });
11686 workspace.read_with(cx, |workspace, _| {
11687 assert_eq!(workspace.zoomed, None);
11688 assert_eq!(workspace.zoomed_position, None);
11689 });
11690
11691 // If focus is transferred again to another view that's not a panel or a pane, we won't
11692 // show the panel as zoomed because it wasn't zoomed before.
11693 focus_other_view(cx);
11694 workspace.read_with(cx, |workspace, _| {
11695 assert_eq!(workspace.zoomed, None);
11696 assert_eq!(workspace.zoomed_position, None);
11697 });
11698
11699 // When the panel is activated, it is zoomed again.
11700 cx.dispatch_action(ToggleRightDock);
11701 workspace.read_with(cx, |workspace, _| {
11702 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11703 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11704 });
11705
11706 // Emitting a ZoomOut event unzooms the panel.
11707 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
11708 workspace.read_with(cx, |workspace, _| {
11709 assert_eq!(workspace.zoomed, None);
11710 assert_eq!(workspace.zoomed_position, None);
11711 });
11712
11713 // Emit closed event on panel 1, which is active
11714 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11715
11716 // Now the left dock is closed, because panel_1 was the active panel
11717 workspace.update(cx, |workspace, cx| {
11718 let right_dock = workspace.right_dock();
11719 assert!(!right_dock.read(cx).is_open());
11720 });
11721 }
11722
11723 #[gpui::test]
11724 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
11725 init_test(cx);
11726
11727 let fs = FakeFs::new(cx.background_executor.clone());
11728 let project = Project::test(fs, [], cx).await;
11729 let (workspace, cx) =
11730 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11731 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11732
11733 let dirty_regular_buffer = cx.new(|cx| {
11734 TestItem::new(cx)
11735 .with_dirty(true)
11736 .with_label("1.txt")
11737 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11738 });
11739 let dirty_regular_buffer_2 = cx.new(|cx| {
11740 TestItem::new(cx)
11741 .with_dirty(true)
11742 .with_label("2.txt")
11743 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11744 });
11745 let dirty_multi_buffer_with_both = cx.new(|cx| {
11746 TestItem::new(cx)
11747 .with_dirty(true)
11748 .with_buffer_kind(ItemBufferKind::Multibuffer)
11749 .with_label("Fake Project Search")
11750 .with_project_items(&[
11751 dirty_regular_buffer.read(cx).project_items[0].clone(),
11752 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11753 ])
11754 });
11755 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
11756 workspace.update_in(cx, |workspace, window, cx| {
11757 workspace.add_item(
11758 pane.clone(),
11759 Box::new(dirty_regular_buffer.clone()),
11760 None,
11761 false,
11762 false,
11763 window,
11764 cx,
11765 );
11766 workspace.add_item(
11767 pane.clone(),
11768 Box::new(dirty_regular_buffer_2.clone()),
11769 None,
11770 false,
11771 false,
11772 window,
11773 cx,
11774 );
11775 workspace.add_item(
11776 pane.clone(),
11777 Box::new(dirty_multi_buffer_with_both.clone()),
11778 None,
11779 false,
11780 false,
11781 window,
11782 cx,
11783 );
11784 });
11785
11786 pane.update_in(cx, |pane, window, cx| {
11787 pane.activate_item(2, true, true, window, cx);
11788 assert_eq!(
11789 pane.active_item().unwrap().item_id(),
11790 multi_buffer_with_both_files_id,
11791 "Should select the multi buffer in the pane"
11792 );
11793 });
11794 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11795 pane.close_other_items(
11796 &CloseOtherItems {
11797 save_intent: Some(SaveIntent::Save),
11798 close_pinned: true,
11799 },
11800 None,
11801 window,
11802 cx,
11803 )
11804 });
11805 cx.background_executor.run_until_parked();
11806 assert!(!cx.has_pending_prompt());
11807 close_all_but_multi_buffer_task
11808 .await
11809 .expect("Closing all buffers but the multi buffer failed");
11810 pane.update(cx, |pane, cx| {
11811 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
11812 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
11813 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
11814 assert_eq!(pane.items_len(), 1);
11815 assert_eq!(
11816 pane.active_item().unwrap().item_id(),
11817 multi_buffer_with_both_files_id,
11818 "Should have only the multi buffer left in the pane"
11819 );
11820 assert!(
11821 dirty_multi_buffer_with_both.read(cx).is_dirty,
11822 "The multi buffer containing the unsaved buffer should still be dirty"
11823 );
11824 });
11825
11826 dirty_regular_buffer.update(cx, |buffer, cx| {
11827 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
11828 });
11829
11830 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11831 pane.close_active_item(
11832 &CloseActiveItem {
11833 save_intent: Some(SaveIntent::Close),
11834 close_pinned: false,
11835 },
11836 window,
11837 cx,
11838 )
11839 });
11840 cx.background_executor.run_until_parked();
11841 assert!(
11842 cx.has_pending_prompt(),
11843 "Dirty multi buffer should prompt a save dialog"
11844 );
11845 cx.simulate_prompt_answer("Save");
11846 cx.background_executor.run_until_parked();
11847 close_multi_buffer_task
11848 .await
11849 .expect("Closing the multi buffer failed");
11850 pane.update(cx, |pane, cx| {
11851 assert_eq!(
11852 dirty_multi_buffer_with_both.read(cx).save_count,
11853 1,
11854 "Multi buffer item should get be saved"
11855 );
11856 // Test impl does not save inner items, so we do not assert them
11857 assert_eq!(
11858 pane.items_len(),
11859 0,
11860 "No more items should be left in the pane"
11861 );
11862 assert!(pane.active_item().is_none());
11863 });
11864 }
11865
11866 #[gpui::test]
11867 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
11868 cx: &mut TestAppContext,
11869 ) {
11870 init_test(cx);
11871
11872 let fs = FakeFs::new(cx.background_executor.clone());
11873 let project = Project::test(fs, [], cx).await;
11874 let (workspace, cx) =
11875 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11876 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11877
11878 let dirty_regular_buffer = cx.new(|cx| {
11879 TestItem::new(cx)
11880 .with_dirty(true)
11881 .with_label("1.txt")
11882 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11883 });
11884 let dirty_regular_buffer_2 = cx.new(|cx| {
11885 TestItem::new(cx)
11886 .with_dirty(true)
11887 .with_label("2.txt")
11888 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11889 });
11890 let clear_regular_buffer = cx.new(|cx| {
11891 TestItem::new(cx)
11892 .with_label("3.txt")
11893 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
11894 });
11895
11896 let dirty_multi_buffer_with_both = cx.new(|cx| {
11897 TestItem::new(cx)
11898 .with_dirty(true)
11899 .with_buffer_kind(ItemBufferKind::Multibuffer)
11900 .with_label("Fake Project Search")
11901 .with_project_items(&[
11902 dirty_regular_buffer.read(cx).project_items[0].clone(),
11903 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11904 clear_regular_buffer.read(cx).project_items[0].clone(),
11905 ])
11906 });
11907 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
11908 workspace.update_in(cx, |workspace, window, cx| {
11909 workspace.add_item(
11910 pane.clone(),
11911 Box::new(dirty_regular_buffer.clone()),
11912 None,
11913 false,
11914 false,
11915 window,
11916 cx,
11917 );
11918 workspace.add_item(
11919 pane.clone(),
11920 Box::new(dirty_multi_buffer_with_both.clone()),
11921 None,
11922 false,
11923 false,
11924 window,
11925 cx,
11926 );
11927 });
11928
11929 pane.update_in(cx, |pane, window, cx| {
11930 pane.activate_item(1, true, true, window, cx);
11931 assert_eq!(
11932 pane.active_item().unwrap().item_id(),
11933 multi_buffer_with_both_files_id,
11934 "Should select the multi buffer in the pane"
11935 );
11936 });
11937 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11938 pane.close_active_item(
11939 &CloseActiveItem {
11940 save_intent: None,
11941 close_pinned: false,
11942 },
11943 window,
11944 cx,
11945 )
11946 });
11947 cx.background_executor.run_until_parked();
11948 assert!(
11949 cx.has_pending_prompt(),
11950 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
11951 );
11952 }
11953
11954 /// Tests that when `close_on_file_delete` is enabled, files are automatically
11955 /// closed when they are deleted from disk.
11956 #[gpui::test]
11957 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
11958 init_test(cx);
11959
11960 // Enable the close_on_disk_deletion setting
11961 cx.update_global(|store: &mut SettingsStore, cx| {
11962 store.update_user_settings(cx, |settings| {
11963 settings.workspace.close_on_file_delete = Some(true);
11964 });
11965 });
11966
11967 let fs = FakeFs::new(cx.background_executor.clone());
11968 let project = Project::test(fs, [], cx).await;
11969 let (workspace, cx) =
11970 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11971 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11972
11973 // Create a test item that simulates a file
11974 let item = cx.new(|cx| {
11975 TestItem::new(cx)
11976 .with_label("test.txt")
11977 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11978 });
11979
11980 // Add item to workspace
11981 workspace.update_in(cx, |workspace, window, cx| {
11982 workspace.add_item(
11983 pane.clone(),
11984 Box::new(item.clone()),
11985 None,
11986 false,
11987 false,
11988 window,
11989 cx,
11990 );
11991 });
11992
11993 // Verify the item is in the pane
11994 pane.read_with(cx, |pane, _| {
11995 assert_eq!(pane.items().count(), 1);
11996 });
11997
11998 // Simulate file deletion by setting the item's deleted state
11999 item.update(cx, |item, _| {
12000 item.set_has_deleted_file(true);
12001 });
12002
12003 // Emit UpdateTab event to trigger the close behavior
12004 cx.run_until_parked();
12005 item.update(cx, |_, cx| {
12006 cx.emit(ItemEvent::UpdateTab);
12007 });
12008
12009 // Allow the close operation to complete
12010 cx.run_until_parked();
12011
12012 // Verify the item was automatically closed
12013 pane.read_with(cx, |pane, _| {
12014 assert_eq!(
12015 pane.items().count(),
12016 0,
12017 "Item should be automatically closed when file is deleted"
12018 );
12019 });
12020 }
12021
12022 /// Tests that when `close_on_file_delete` is disabled (default), files remain
12023 /// open with a strikethrough when they are deleted from disk.
12024 #[gpui::test]
12025 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
12026 init_test(cx);
12027
12028 // Ensure close_on_disk_deletion is disabled (default)
12029 cx.update_global(|store: &mut SettingsStore, cx| {
12030 store.update_user_settings(cx, |settings| {
12031 settings.workspace.close_on_file_delete = Some(false);
12032 });
12033 });
12034
12035 let fs = FakeFs::new(cx.background_executor.clone());
12036 let project = Project::test(fs, [], cx).await;
12037 let (workspace, cx) =
12038 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12039 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12040
12041 // Create a test item that simulates a file
12042 let item = cx.new(|cx| {
12043 TestItem::new(cx)
12044 .with_label("test.txt")
12045 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12046 });
12047
12048 // Add item to workspace
12049 workspace.update_in(cx, |workspace, window, cx| {
12050 workspace.add_item(
12051 pane.clone(),
12052 Box::new(item.clone()),
12053 None,
12054 false,
12055 false,
12056 window,
12057 cx,
12058 );
12059 });
12060
12061 // Verify the item is in the pane
12062 pane.read_with(cx, |pane, _| {
12063 assert_eq!(pane.items().count(), 1);
12064 });
12065
12066 // Simulate file deletion
12067 item.update(cx, |item, _| {
12068 item.set_has_deleted_file(true);
12069 });
12070
12071 // Emit UpdateTab event
12072 cx.run_until_parked();
12073 item.update(cx, |_, cx| {
12074 cx.emit(ItemEvent::UpdateTab);
12075 });
12076
12077 // Allow any potential close operation to complete
12078 cx.run_until_parked();
12079
12080 // Verify the item remains open (with strikethrough)
12081 pane.read_with(cx, |pane, _| {
12082 assert_eq!(
12083 pane.items().count(),
12084 1,
12085 "Item should remain open when close_on_disk_deletion is disabled"
12086 );
12087 });
12088
12089 // Verify the item shows as deleted
12090 item.read_with(cx, |item, _| {
12091 assert!(
12092 item.has_deleted_file,
12093 "Item should be marked as having deleted file"
12094 );
12095 });
12096 }
12097
12098 /// Tests that dirty files are not automatically closed when deleted from disk,
12099 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
12100 /// unsaved changes without being prompted.
12101 #[gpui::test]
12102 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
12103 init_test(cx);
12104
12105 // Enable the close_on_file_delete setting
12106 cx.update_global(|store: &mut SettingsStore, cx| {
12107 store.update_user_settings(cx, |settings| {
12108 settings.workspace.close_on_file_delete = Some(true);
12109 });
12110 });
12111
12112 let fs = FakeFs::new(cx.background_executor.clone());
12113 let project = Project::test(fs, [], cx).await;
12114 let (workspace, cx) =
12115 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12116 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12117
12118 // Create a dirty test item
12119 let item = cx.new(|cx| {
12120 TestItem::new(cx)
12121 .with_dirty(true)
12122 .with_label("test.txt")
12123 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12124 });
12125
12126 // Add item to workspace
12127 workspace.update_in(cx, |workspace, window, cx| {
12128 workspace.add_item(
12129 pane.clone(),
12130 Box::new(item.clone()),
12131 None,
12132 false,
12133 false,
12134 window,
12135 cx,
12136 );
12137 });
12138
12139 // Simulate file deletion
12140 item.update(cx, |item, _| {
12141 item.set_has_deleted_file(true);
12142 });
12143
12144 // Emit UpdateTab event to trigger the close behavior
12145 cx.run_until_parked();
12146 item.update(cx, |_, cx| {
12147 cx.emit(ItemEvent::UpdateTab);
12148 });
12149
12150 // Allow any potential close operation to complete
12151 cx.run_until_parked();
12152
12153 // Verify the item remains open (dirty files are not auto-closed)
12154 pane.read_with(cx, |pane, _| {
12155 assert_eq!(
12156 pane.items().count(),
12157 1,
12158 "Dirty items should not be automatically closed even when file is deleted"
12159 );
12160 });
12161
12162 // Verify the item is marked as deleted and still dirty
12163 item.read_with(cx, |item, _| {
12164 assert!(
12165 item.has_deleted_file,
12166 "Item should be marked as having deleted file"
12167 );
12168 assert!(item.is_dirty, "Item should still be dirty");
12169 });
12170 }
12171
12172 /// Tests that navigation history is cleaned up when files are auto-closed
12173 /// due to deletion from disk.
12174 #[gpui::test]
12175 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12176 init_test(cx);
12177
12178 // Enable the close_on_file_delete setting
12179 cx.update_global(|store: &mut SettingsStore, cx| {
12180 store.update_user_settings(cx, |settings| {
12181 settings.workspace.close_on_file_delete = Some(true);
12182 });
12183 });
12184
12185 let fs = FakeFs::new(cx.background_executor.clone());
12186 let project = Project::test(fs, [], cx).await;
12187 let (workspace, cx) =
12188 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12189 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12190
12191 // Create test items
12192 let item1 = cx.new(|cx| {
12193 TestItem::new(cx)
12194 .with_label("test1.txt")
12195 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12196 });
12197 let item1_id = item1.item_id();
12198
12199 let item2 = cx.new(|cx| {
12200 TestItem::new(cx)
12201 .with_label("test2.txt")
12202 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12203 });
12204
12205 // Add items to workspace
12206 workspace.update_in(cx, |workspace, window, cx| {
12207 workspace.add_item(
12208 pane.clone(),
12209 Box::new(item1.clone()),
12210 None,
12211 false,
12212 false,
12213 window,
12214 cx,
12215 );
12216 workspace.add_item(
12217 pane.clone(),
12218 Box::new(item2.clone()),
12219 None,
12220 false,
12221 false,
12222 window,
12223 cx,
12224 );
12225 });
12226
12227 // Activate item1 to ensure it gets navigation entries
12228 pane.update_in(cx, |pane, window, cx| {
12229 pane.activate_item(0, true, true, window, cx);
12230 });
12231
12232 // Switch to item2 and back to create navigation history
12233 pane.update_in(cx, |pane, window, cx| {
12234 pane.activate_item(1, true, true, window, cx);
12235 });
12236 cx.run_until_parked();
12237
12238 pane.update_in(cx, |pane, window, cx| {
12239 pane.activate_item(0, true, true, window, cx);
12240 });
12241 cx.run_until_parked();
12242
12243 // Simulate file deletion for item1
12244 item1.update(cx, |item, _| {
12245 item.set_has_deleted_file(true);
12246 });
12247
12248 // Emit UpdateTab event to trigger the close behavior
12249 item1.update(cx, |_, cx| {
12250 cx.emit(ItemEvent::UpdateTab);
12251 });
12252 cx.run_until_parked();
12253
12254 // Verify item1 was closed
12255 pane.read_with(cx, |pane, _| {
12256 assert_eq!(
12257 pane.items().count(),
12258 1,
12259 "Should have 1 item remaining after auto-close"
12260 );
12261 });
12262
12263 // Check navigation history after close
12264 let has_item = pane.read_with(cx, |pane, cx| {
12265 let mut has_item = false;
12266 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12267 if entry.item.id() == item1_id {
12268 has_item = true;
12269 }
12270 });
12271 has_item
12272 });
12273
12274 assert!(
12275 !has_item,
12276 "Navigation history should not contain closed item entries"
12277 );
12278 }
12279
12280 #[gpui::test]
12281 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12282 cx: &mut TestAppContext,
12283 ) {
12284 init_test(cx);
12285
12286 let fs = FakeFs::new(cx.background_executor.clone());
12287 let project = Project::test(fs, [], cx).await;
12288 let (workspace, cx) =
12289 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12290 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12291
12292 let dirty_regular_buffer = cx.new(|cx| {
12293 TestItem::new(cx)
12294 .with_dirty(true)
12295 .with_label("1.txt")
12296 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12297 });
12298 let dirty_regular_buffer_2 = cx.new(|cx| {
12299 TestItem::new(cx)
12300 .with_dirty(true)
12301 .with_label("2.txt")
12302 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12303 });
12304 let clear_regular_buffer = cx.new(|cx| {
12305 TestItem::new(cx)
12306 .with_label("3.txt")
12307 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12308 });
12309
12310 let dirty_multi_buffer = cx.new(|cx| {
12311 TestItem::new(cx)
12312 .with_dirty(true)
12313 .with_buffer_kind(ItemBufferKind::Multibuffer)
12314 .with_label("Fake Project Search")
12315 .with_project_items(&[
12316 dirty_regular_buffer.read(cx).project_items[0].clone(),
12317 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12318 clear_regular_buffer.read(cx).project_items[0].clone(),
12319 ])
12320 });
12321 workspace.update_in(cx, |workspace, window, cx| {
12322 workspace.add_item(
12323 pane.clone(),
12324 Box::new(dirty_regular_buffer.clone()),
12325 None,
12326 false,
12327 false,
12328 window,
12329 cx,
12330 );
12331 workspace.add_item(
12332 pane.clone(),
12333 Box::new(dirty_regular_buffer_2.clone()),
12334 None,
12335 false,
12336 false,
12337 window,
12338 cx,
12339 );
12340 workspace.add_item(
12341 pane.clone(),
12342 Box::new(dirty_multi_buffer.clone()),
12343 None,
12344 false,
12345 false,
12346 window,
12347 cx,
12348 );
12349 });
12350
12351 pane.update_in(cx, |pane, window, cx| {
12352 pane.activate_item(2, true, true, window, cx);
12353 assert_eq!(
12354 pane.active_item().unwrap().item_id(),
12355 dirty_multi_buffer.item_id(),
12356 "Should select the multi buffer in the pane"
12357 );
12358 });
12359 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12360 pane.close_active_item(
12361 &CloseActiveItem {
12362 save_intent: None,
12363 close_pinned: false,
12364 },
12365 window,
12366 cx,
12367 )
12368 });
12369 cx.background_executor.run_until_parked();
12370 assert!(
12371 !cx.has_pending_prompt(),
12372 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12373 );
12374 close_multi_buffer_task
12375 .await
12376 .expect("Closing multi buffer failed");
12377 pane.update(cx, |pane, cx| {
12378 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12379 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12380 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12381 assert_eq!(
12382 pane.items()
12383 .map(|item| item.item_id())
12384 .sorted()
12385 .collect::<Vec<_>>(),
12386 vec![
12387 dirty_regular_buffer.item_id(),
12388 dirty_regular_buffer_2.item_id(),
12389 ],
12390 "Should have no multi buffer left in the pane"
12391 );
12392 assert!(dirty_regular_buffer.read(cx).is_dirty);
12393 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12394 });
12395 }
12396
12397 #[gpui::test]
12398 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12399 init_test(cx);
12400 let fs = FakeFs::new(cx.executor());
12401 let project = Project::test(fs, [], cx).await;
12402 let (workspace, cx) =
12403 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12404
12405 // Add a new panel to the right dock, opening the dock and setting the
12406 // focus to the new panel.
12407 let panel = workspace.update_in(cx, |workspace, window, cx| {
12408 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12409 workspace.add_panel(panel.clone(), window, cx);
12410
12411 workspace
12412 .right_dock()
12413 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12414
12415 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12416
12417 panel
12418 });
12419
12420 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12421 // panel to the next valid position which, in this case, is the left
12422 // dock.
12423 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12424 workspace.update(cx, |workspace, cx| {
12425 assert!(workspace.left_dock().read(cx).is_open());
12426 assert_eq!(panel.read(cx).position, DockPosition::Left);
12427 });
12428
12429 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12430 // panel to the next valid position which, in this case, is the bottom
12431 // dock.
12432 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12433 workspace.update(cx, |workspace, cx| {
12434 assert!(workspace.bottom_dock().read(cx).is_open());
12435 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12436 });
12437
12438 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12439 // around moving the panel to its initial position, the right dock.
12440 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12441 workspace.update(cx, |workspace, cx| {
12442 assert!(workspace.right_dock().read(cx).is_open());
12443 assert_eq!(panel.read(cx).position, DockPosition::Right);
12444 });
12445
12446 // Remove focus from the panel, ensuring that, if the panel is not
12447 // focused, the `MoveFocusedPanelToNextPosition` action does not update
12448 // the panel's position, so the panel is still in the right dock.
12449 workspace.update_in(cx, |workspace, window, cx| {
12450 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12451 });
12452
12453 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12454 workspace.update(cx, |workspace, cx| {
12455 assert!(workspace.right_dock().read(cx).is_open());
12456 assert_eq!(panel.read(cx).position, DockPosition::Right);
12457 });
12458 }
12459
12460 #[gpui::test]
12461 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12462 init_test(cx);
12463
12464 let fs = FakeFs::new(cx.executor());
12465 let project = Project::test(fs, [], cx).await;
12466 let (workspace, cx) =
12467 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12468
12469 let item_1 = cx.new(|cx| {
12470 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12471 });
12472 workspace.update_in(cx, |workspace, window, cx| {
12473 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12474 workspace.move_item_to_pane_in_direction(
12475 &MoveItemToPaneInDirection {
12476 direction: SplitDirection::Right,
12477 focus: true,
12478 clone: false,
12479 },
12480 window,
12481 cx,
12482 );
12483 workspace.move_item_to_pane_at_index(
12484 &MoveItemToPane {
12485 destination: 3,
12486 focus: true,
12487 clone: false,
12488 },
12489 window,
12490 cx,
12491 );
12492
12493 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12494 assert_eq!(
12495 pane_items_paths(&workspace.active_pane, cx),
12496 vec!["first.txt".to_string()],
12497 "Single item was not moved anywhere"
12498 );
12499 });
12500
12501 let item_2 = cx.new(|cx| {
12502 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12503 });
12504 workspace.update_in(cx, |workspace, window, cx| {
12505 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12506 assert_eq!(
12507 pane_items_paths(&workspace.panes[0], cx),
12508 vec!["first.txt".to_string(), "second.txt".to_string()],
12509 );
12510 workspace.move_item_to_pane_in_direction(
12511 &MoveItemToPaneInDirection {
12512 direction: SplitDirection::Right,
12513 focus: true,
12514 clone: false,
12515 },
12516 window,
12517 cx,
12518 );
12519
12520 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12521 assert_eq!(
12522 pane_items_paths(&workspace.panes[0], cx),
12523 vec!["first.txt".to_string()],
12524 "After moving, one item should be left in the original pane"
12525 );
12526 assert_eq!(
12527 pane_items_paths(&workspace.panes[1], cx),
12528 vec!["second.txt".to_string()],
12529 "New item should have been moved to the new pane"
12530 );
12531 });
12532
12533 let item_3 = cx.new(|cx| {
12534 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12535 });
12536 workspace.update_in(cx, |workspace, window, cx| {
12537 let original_pane = workspace.panes[0].clone();
12538 workspace.set_active_pane(&original_pane, window, cx);
12539 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12540 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12541 assert_eq!(
12542 pane_items_paths(&workspace.active_pane, cx),
12543 vec!["first.txt".to_string(), "third.txt".to_string()],
12544 "New pane should be ready to move one item out"
12545 );
12546
12547 workspace.move_item_to_pane_at_index(
12548 &MoveItemToPane {
12549 destination: 3,
12550 focus: true,
12551 clone: false,
12552 },
12553 window,
12554 cx,
12555 );
12556 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12557 assert_eq!(
12558 pane_items_paths(&workspace.active_pane, cx),
12559 vec!["first.txt".to_string()],
12560 "After moving, one item should be left in the original pane"
12561 );
12562 assert_eq!(
12563 pane_items_paths(&workspace.panes[1], cx),
12564 vec!["second.txt".to_string()],
12565 "Previously created pane should be unchanged"
12566 );
12567 assert_eq!(
12568 pane_items_paths(&workspace.panes[2], cx),
12569 vec!["third.txt".to_string()],
12570 "New item should have been moved to the new pane"
12571 );
12572 });
12573 }
12574
12575 #[gpui::test]
12576 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
12577 init_test(cx);
12578
12579 let fs = FakeFs::new(cx.executor());
12580 let project = Project::test(fs, [], cx).await;
12581 let (workspace, cx) =
12582 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12583
12584 let item_1 = cx.new(|cx| {
12585 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12586 });
12587 workspace.update_in(cx, |workspace, window, cx| {
12588 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12589 workspace.move_item_to_pane_in_direction(
12590 &MoveItemToPaneInDirection {
12591 direction: SplitDirection::Right,
12592 focus: true,
12593 clone: true,
12594 },
12595 window,
12596 cx,
12597 );
12598 });
12599 cx.run_until_parked();
12600 workspace.update_in(cx, |workspace, window, cx| {
12601 workspace.move_item_to_pane_at_index(
12602 &MoveItemToPane {
12603 destination: 3,
12604 focus: true,
12605 clone: true,
12606 },
12607 window,
12608 cx,
12609 );
12610 });
12611 cx.run_until_parked();
12612
12613 workspace.update(cx, |workspace, cx| {
12614 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
12615 for pane in workspace.panes() {
12616 assert_eq!(
12617 pane_items_paths(pane, cx),
12618 vec!["first.txt".to_string()],
12619 "Single item exists in all panes"
12620 );
12621 }
12622 });
12623
12624 // verify that the active pane has been updated after waiting for the
12625 // pane focus event to fire and resolve
12626 workspace.read_with(cx, |workspace, _app| {
12627 assert_eq!(
12628 workspace.active_pane(),
12629 &workspace.panes[2],
12630 "The third pane should be the active one: {:?}",
12631 workspace.panes
12632 );
12633 })
12634 }
12635
12636 #[gpui::test]
12637 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
12638 init_test(cx);
12639
12640 let fs = FakeFs::new(cx.executor());
12641 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
12642
12643 let project = Project::test(fs, ["root".as_ref()], cx).await;
12644 let (workspace, cx) =
12645 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12646
12647 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12648 // Add item to pane A with project path
12649 let item_a = cx.new(|cx| {
12650 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12651 });
12652 workspace.update_in(cx, |workspace, window, cx| {
12653 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
12654 });
12655
12656 // Split to create pane B
12657 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
12658 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
12659 });
12660
12661 // Add item with SAME project path to pane B, and pin it
12662 let item_b = cx.new(|cx| {
12663 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12664 });
12665 pane_b.update_in(cx, |pane, window, cx| {
12666 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
12667 pane.set_pinned_count(1);
12668 });
12669
12670 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
12671 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
12672
12673 // close_pinned: false should only close the unpinned copy
12674 workspace.update_in(cx, |workspace, window, cx| {
12675 workspace.close_item_in_all_panes(
12676 &CloseItemInAllPanes {
12677 save_intent: Some(SaveIntent::Close),
12678 close_pinned: false,
12679 },
12680 window,
12681 cx,
12682 )
12683 });
12684 cx.executor().run_until_parked();
12685
12686 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
12687 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
12688 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
12689 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
12690
12691 // Split again, seeing as closing the previous item also closed its
12692 // pane, so only pane remains, which does not allow us to properly test
12693 // that both items close when `close_pinned: true`.
12694 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
12695 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
12696 });
12697
12698 // Add an item with the same project path to pane C so that
12699 // close_item_in_all_panes can determine what to close across all panes
12700 // (it reads the active item from the active pane, and split_pane
12701 // creates an empty pane).
12702 let item_c = cx.new(|cx| {
12703 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12704 });
12705 pane_c.update_in(cx, |pane, window, cx| {
12706 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
12707 });
12708
12709 // close_pinned: true should close the pinned copy too
12710 workspace.update_in(cx, |workspace, window, cx| {
12711 let panes_count = workspace.panes().len();
12712 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
12713
12714 workspace.close_item_in_all_panes(
12715 &CloseItemInAllPanes {
12716 save_intent: Some(SaveIntent::Close),
12717 close_pinned: true,
12718 },
12719 window,
12720 cx,
12721 )
12722 });
12723 cx.executor().run_until_parked();
12724
12725 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
12726 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
12727 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
12728 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
12729 }
12730
12731 mod register_project_item_tests {
12732
12733 use super::*;
12734
12735 // View
12736 struct TestPngItemView {
12737 focus_handle: FocusHandle,
12738 }
12739 // Model
12740 struct TestPngItem {}
12741
12742 impl project::ProjectItem for TestPngItem {
12743 fn try_open(
12744 _project: &Entity<Project>,
12745 path: &ProjectPath,
12746 cx: &mut App,
12747 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
12748 if path.path.extension().unwrap() == "png" {
12749 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
12750 } else {
12751 None
12752 }
12753 }
12754
12755 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
12756 None
12757 }
12758
12759 fn project_path(&self, _: &App) -> Option<ProjectPath> {
12760 None
12761 }
12762
12763 fn is_dirty(&self) -> bool {
12764 false
12765 }
12766 }
12767
12768 impl Item for TestPngItemView {
12769 type Event = ();
12770 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12771 "".into()
12772 }
12773 }
12774 impl EventEmitter<()> for TestPngItemView {}
12775 impl Focusable for TestPngItemView {
12776 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12777 self.focus_handle.clone()
12778 }
12779 }
12780
12781 impl Render for TestPngItemView {
12782 fn render(
12783 &mut self,
12784 _window: &mut Window,
12785 _cx: &mut Context<Self>,
12786 ) -> impl IntoElement {
12787 Empty
12788 }
12789 }
12790
12791 impl ProjectItem for TestPngItemView {
12792 type Item = TestPngItem;
12793
12794 fn for_project_item(
12795 _project: Entity<Project>,
12796 _pane: Option<&Pane>,
12797 _item: Entity<Self::Item>,
12798 _: &mut Window,
12799 cx: &mut Context<Self>,
12800 ) -> Self
12801 where
12802 Self: Sized,
12803 {
12804 Self {
12805 focus_handle: cx.focus_handle(),
12806 }
12807 }
12808 }
12809
12810 // View
12811 struct TestIpynbItemView {
12812 focus_handle: FocusHandle,
12813 }
12814 // Model
12815 struct TestIpynbItem {}
12816
12817 impl project::ProjectItem for TestIpynbItem {
12818 fn try_open(
12819 _project: &Entity<Project>,
12820 path: &ProjectPath,
12821 cx: &mut App,
12822 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
12823 if path.path.extension().unwrap() == "ipynb" {
12824 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
12825 } else {
12826 None
12827 }
12828 }
12829
12830 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
12831 None
12832 }
12833
12834 fn project_path(&self, _: &App) -> Option<ProjectPath> {
12835 None
12836 }
12837
12838 fn is_dirty(&self) -> bool {
12839 false
12840 }
12841 }
12842
12843 impl Item for TestIpynbItemView {
12844 type Event = ();
12845 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12846 "".into()
12847 }
12848 }
12849 impl EventEmitter<()> for TestIpynbItemView {}
12850 impl Focusable for TestIpynbItemView {
12851 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12852 self.focus_handle.clone()
12853 }
12854 }
12855
12856 impl Render for TestIpynbItemView {
12857 fn render(
12858 &mut self,
12859 _window: &mut Window,
12860 _cx: &mut Context<Self>,
12861 ) -> impl IntoElement {
12862 Empty
12863 }
12864 }
12865
12866 impl ProjectItem for TestIpynbItemView {
12867 type Item = TestIpynbItem;
12868
12869 fn for_project_item(
12870 _project: Entity<Project>,
12871 _pane: Option<&Pane>,
12872 _item: Entity<Self::Item>,
12873 _: &mut Window,
12874 cx: &mut Context<Self>,
12875 ) -> Self
12876 where
12877 Self: Sized,
12878 {
12879 Self {
12880 focus_handle: cx.focus_handle(),
12881 }
12882 }
12883 }
12884
12885 struct TestAlternatePngItemView {
12886 focus_handle: FocusHandle,
12887 }
12888
12889 impl Item for TestAlternatePngItemView {
12890 type Event = ();
12891 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12892 "".into()
12893 }
12894 }
12895
12896 impl EventEmitter<()> for TestAlternatePngItemView {}
12897 impl Focusable for TestAlternatePngItemView {
12898 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12899 self.focus_handle.clone()
12900 }
12901 }
12902
12903 impl Render for TestAlternatePngItemView {
12904 fn render(
12905 &mut self,
12906 _window: &mut Window,
12907 _cx: &mut Context<Self>,
12908 ) -> impl IntoElement {
12909 Empty
12910 }
12911 }
12912
12913 impl ProjectItem for TestAlternatePngItemView {
12914 type Item = TestPngItem;
12915
12916 fn for_project_item(
12917 _project: Entity<Project>,
12918 _pane: Option<&Pane>,
12919 _item: Entity<Self::Item>,
12920 _: &mut Window,
12921 cx: &mut Context<Self>,
12922 ) -> Self
12923 where
12924 Self: Sized,
12925 {
12926 Self {
12927 focus_handle: cx.focus_handle(),
12928 }
12929 }
12930 }
12931
12932 #[gpui::test]
12933 async fn test_register_project_item(cx: &mut TestAppContext) {
12934 init_test(cx);
12935
12936 cx.update(|cx| {
12937 register_project_item::<TestPngItemView>(cx);
12938 register_project_item::<TestIpynbItemView>(cx);
12939 });
12940
12941 let fs = FakeFs::new(cx.executor());
12942 fs.insert_tree(
12943 "/root1",
12944 json!({
12945 "one.png": "BINARYDATAHERE",
12946 "two.ipynb": "{ totally a notebook }",
12947 "three.txt": "editing text, sure why not?"
12948 }),
12949 )
12950 .await;
12951
12952 let project = Project::test(fs, ["root1".as_ref()], cx).await;
12953 let (workspace, cx) =
12954 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12955
12956 let worktree_id = project.update(cx, |project, cx| {
12957 project.worktrees(cx).next().unwrap().read(cx).id()
12958 });
12959
12960 let handle = workspace
12961 .update_in(cx, |workspace, window, cx| {
12962 let project_path = (worktree_id, rel_path("one.png"));
12963 workspace.open_path(project_path, None, true, window, cx)
12964 })
12965 .await
12966 .unwrap();
12967
12968 // Now we can check if the handle we got back errored or not
12969 assert_eq!(
12970 handle.to_any_view().entity_type(),
12971 TypeId::of::<TestPngItemView>()
12972 );
12973
12974 let handle = workspace
12975 .update_in(cx, |workspace, window, cx| {
12976 let project_path = (worktree_id, rel_path("two.ipynb"));
12977 workspace.open_path(project_path, None, true, window, cx)
12978 })
12979 .await
12980 .unwrap();
12981
12982 assert_eq!(
12983 handle.to_any_view().entity_type(),
12984 TypeId::of::<TestIpynbItemView>()
12985 );
12986
12987 let handle = workspace
12988 .update_in(cx, |workspace, window, cx| {
12989 let project_path = (worktree_id, rel_path("three.txt"));
12990 workspace.open_path(project_path, None, true, window, cx)
12991 })
12992 .await;
12993 assert!(handle.is_err());
12994 }
12995
12996 #[gpui::test]
12997 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
12998 init_test(cx);
12999
13000 cx.update(|cx| {
13001 register_project_item::<TestPngItemView>(cx);
13002 register_project_item::<TestAlternatePngItemView>(cx);
13003 });
13004
13005 let fs = FakeFs::new(cx.executor());
13006 fs.insert_tree(
13007 "/root1",
13008 json!({
13009 "one.png": "BINARYDATAHERE",
13010 "two.ipynb": "{ totally a notebook }",
13011 "three.txt": "editing text, sure why not?"
13012 }),
13013 )
13014 .await;
13015 let project = Project::test(fs, ["root1".as_ref()], cx).await;
13016 let (workspace, cx) =
13017 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13018 let worktree_id = project.update(cx, |project, cx| {
13019 project.worktrees(cx).next().unwrap().read(cx).id()
13020 });
13021
13022 let handle = workspace
13023 .update_in(cx, |workspace, window, cx| {
13024 let project_path = (worktree_id, rel_path("one.png"));
13025 workspace.open_path(project_path, None, true, window, cx)
13026 })
13027 .await
13028 .unwrap();
13029
13030 // This _must_ be the second item registered
13031 assert_eq!(
13032 handle.to_any_view().entity_type(),
13033 TypeId::of::<TestAlternatePngItemView>()
13034 );
13035
13036 let handle = workspace
13037 .update_in(cx, |workspace, window, cx| {
13038 let project_path = (worktree_id, rel_path("three.txt"));
13039 workspace.open_path(project_path, None, true, window, cx)
13040 })
13041 .await;
13042 assert!(handle.is_err());
13043 }
13044 }
13045
13046 #[gpui::test]
13047 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
13048 init_test(cx);
13049
13050 let fs = FakeFs::new(cx.executor());
13051 let project = Project::test(fs, [], cx).await;
13052 let (workspace, _cx) =
13053 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13054
13055 // Test with status bar shown (default)
13056 workspace.read_with(cx, |workspace, cx| {
13057 let visible = workspace.status_bar_visible(cx);
13058 assert!(visible, "Status bar should be visible by default");
13059 });
13060
13061 // Test with status bar hidden
13062 cx.update_global(|store: &mut SettingsStore, cx| {
13063 store.update_user_settings(cx, |settings| {
13064 settings.status_bar.get_or_insert_default().show = Some(false);
13065 });
13066 });
13067
13068 workspace.read_with(cx, |workspace, cx| {
13069 let visible = workspace.status_bar_visible(cx);
13070 assert!(!visible, "Status bar should be hidden when show is false");
13071 });
13072
13073 // Test with status bar shown explicitly
13074 cx.update_global(|store: &mut SettingsStore, cx| {
13075 store.update_user_settings(cx, |settings| {
13076 settings.status_bar.get_or_insert_default().show = Some(true);
13077 });
13078 });
13079
13080 workspace.read_with(cx, |workspace, cx| {
13081 let visible = workspace.status_bar_visible(cx);
13082 assert!(visible, "Status bar should be visible when show is true");
13083 });
13084 }
13085
13086 #[gpui::test]
13087 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
13088 init_test(cx);
13089
13090 let fs = FakeFs::new(cx.executor());
13091 let project = Project::test(fs, [], cx).await;
13092 let (workspace, cx) =
13093 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13094 let panel = workspace.update_in(cx, |workspace, window, cx| {
13095 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13096 workspace.add_panel(panel.clone(), window, cx);
13097
13098 workspace
13099 .right_dock()
13100 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13101
13102 panel
13103 });
13104
13105 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13106 let item_a = cx.new(TestItem::new);
13107 let item_b = cx.new(TestItem::new);
13108 let item_a_id = item_a.entity_id();
13109 let item_b_id = item_b.entity_id();
13110
13111 pane.update_in(cx, |pane, window, cx| {
13112 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
13113 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13114 });
13115
13116 pane.read_with(cx, |pane, _| {
13117 assert_eq!(pane.items_len(), 2);
13118 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
13119 });
13120
13121 workspace.update_in(cx, |workspace, window, cx| {
13122 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13123 });
13124
13125 workspace.update_in(cx, |_, window, cx| {
13126 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13127 });
13128
13129 // Assert that the `pane::CloseActiveItem` action is handled at the
13130 // workspace level when one of the dock panels is focused and, in that
13131 // case, the center pane's active item is closed but the focus is not
13132 // moved.
13133 cx.dispatch_action(pane::CloseActiveItem::default());
13134 cx.run_until_parked();
13135
13136 pane.read_with(cx, |pane, _| {
13137 assert_eq!(pane.items_len(), 1);
13138 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
13139 });
13140
13141 workspace.update_in(cx, |workspace, window, cx| {
13142 assert!(workspace.right_dock().read(cx).is_open());
13143 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13144 });
13145 }
13146
13147 #[gpui::test]
13148 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
13149 init_test(cx);
13150 let fs = FakeFs::new(cx.executor());
13151
13152 let project_a = Project::test(fs.clone(), [], cx).await;
13153 let project_b = Project::test(fs, [], cx).await;
13154
13155 let multi_workspace_handle =
13156 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
13157
13158 let workspace_a = multi_workspace_handle
13159 .read_with(cx, |mw, _| mw.workspace().clone())
13160 .unwrap();
13161
13162 let _workspace_b = multi_workspace_handle
13163 .update(cx, |mw, window, cx| {
13164 mw.test_add_workspace(project_b, window, cx)
13165 })
13166 .unwrap();
13167
13168 // Switch to workspace A
13169 multi_workspace_handle
13170 .update(cx, |mw, window, cx| {
13171 mw.activate_index(0, window, cx);
13172 })
13173 .unwrap();
13174
13175 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13176
13177 // Add a panel to workspace A's right dock and open the dock
13178 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13179 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13180 workspace.add_panel(panel.clone(), window, cx);
13181 workspace
13182 .right_dock()
13183 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13184 panel
13185 });
13186
13187 // Focus the panel through the workspace (matching existing test pattern)
13188 workspace_a.update_in(cx, |workspace, window, cx| {
13189 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13190 });
13191
13192 // Zoom the panel
13193 panel.update_in(cx, |panel, window, cx| {
13194 panel.set_zoomed(true, window, cx);
13195 });
13196
13197 // Verify the panel is zoomed and the dock is open
13198 workspace_a.update_in(cx, |workspace, window, cx| {
13199 assert!(
13200 workspace.right_dock().read(cx).is_open(),
13201 "dock should be open before switch"
13202 );
13203 assert!(
13204 panel.is_zoomed(window, cx),
13205 "panel should be zoomed before switch"
13206 );
13207 assert!(
13208 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13209 "panel should be focused before switch"
13210 );
13211 });
13212
13213 // Switch to workspace B
13214 multi_workspace_handle
13215 .update(cx, |mw, window, cx| {
13216 mw.activate_index(1, window, cx);
13217 })
13218 .unwrap();
13219 cx.run_until_parked();
13220
13221 // Switch back to workspace A
13222 multi_workspace_handle
13223 .update(cx, |mw, window, cx| {
13224 mw.activate_index(0, window, cx);
13225 })
13226 .unwrap();
13227 cx.run_until_parked();
13228
13229 // Verify the panel is still zoomed and the dock is still open
13230 workspace_a.update_in(cx, |workspace, window, cx| {
13231 assert!(
13232 workspace.right_dock().read(cx).is_open(),
13233 "dock should still be open after switching back"
13234 );
13235 assert!(
13236 panel.is_zoomed(window, cx),
13237 "panel should still be zoomed after switching back"
13238 );
13239 });
13240 }
13241
13242 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13243 pane.read(cx)
13244 .items()
13245 .flat_map(|item| {
13246 item.project_paths(cx)
13247 .into_iter()
13248 .map(|path| path.path.display(PathStyle::local()).into_owned())
13249 })
13250 .collect()
13251 }
13252
13253 pub fn init_test(cx: &mut TestAppContext) {
13254 cx.update(|cx| {
13255 let settings_store = SettingsStore::test(cx);
13256 cx.set_global(settings_store);
13257 theme::init(theme::LoadThemes::JustBase, cx);
13258 });
13259 }
13260
13261 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13262 let item = TestProjectItem::new(id, path, cx);
13263 item.update(cx, |item, _| {
13264 item.is_dirty = true;
13265 });
13266 item
13267 }
13268
13269 #[gpui::test]
13270 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13271 cx: &mut gpui::TestAppContext,
13272 ) {
13273 init_test(cx);
13274 let fs = FakeFs::new(cx.executor());
13275
13276 let project = Project::test(fs, [], cx).await;
13277 let (workspace, cx) =
13278 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13279
13280 let panel = workspace.update_in(cx, |workspace, window, cx| {
13281 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13282 workspace.add_panel(panel.clone(), window, cx);
13283 workspace
13284 .right_dock()
13285 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13286 panel
13287 });
13288
13289 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13290 pane.update_in(cx, |pane, window, cx| {
13291 let item = cx.new(TestItem::new);
13292 pane.add_item(Box::new(item), true, true, None, window, cx);
13293 });
13294
13295 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13296 // mirrors the real-world flow and avoids side effects from directly
13297 // focusing the panel while the center pane is active.
13298 workspace.update_in(cx, |workspace, window, cx| {
13299 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13300 });
13301
13302 panel.update_in(cx, |panel, window, cx| {
13303 panel.set_zoomed(true, window, cx);
13304 });
13305
13306 workspace.update_in(cx, |workspace, window, cx| {
13307 assert!(workspace.right_dock().read(cx).is_open());
13308 assert!(panel.is_zoomed(window, cx));
13309 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13310 });
13311
13312 // Simulate a spurious pane::Event::Focus on the center pane while the
13313 // panel still has focus. This mirrors what happens during macOS window
13314 // activation: the center pane fires a focus event even though actual
13315 // focus remains on the dock panel.
13316 pane.update_in(cx, |_, _, cx| {
13317 cx.emit(pane::Event::Focus);
13318 });
13319
13320 // The dock must remain open because the panel had focus at the time the
13321 // event was processed. Before the fix, dock_to_preserve was None for
13322 // panels that don't implement pane(), causing the dock to close.
13323 workspace.update_in(cx, |workspace, window, cx| {
13324 assert!(
13325 workspace.right_dock().read(cx).is_open(),
13326 "Dock should stay open when its zoomed panel (without pane()) still has focus"
13327 );
13328 assert!(panel.is_zoomed(window, cx));
13329 });
13330 }
13331}