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