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