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