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