pub mod dock;pub mod item;mod modal_layer;pub mod notifications;pub mod pane;pub mod pane_group;mod persistence;pub mod searchable;pub mod shared_screen;mod status_bar;pub mod tasks;mod toolbar;mod workspace_settings; use anyhow::{anyhow, Context as _, Result};use call::{call_settings::CallSettings, ActiveCall};use client::{ proto::{self, ErrorCode, PeerId}, ChannelId, Client, ErrorExt, ProjectId, Status, TypedEnvelope, UserStore,};use collections::{hash_map, HashMap, HashSet};use derive_more::{Deref, DerefMut};use dock::{Dock, DockPosition, Panel, PanelButtons, PanelHandle};use futures::{ channel::{mpsc, oneshot}, future::try_join_all, Future, FutureExt, StreamExt,};use gpui::{ actions, canvas, impl_actions, point, relative, size, Action, AnyElement, AnyView, AnyWeakView, AppContext, AsyncAppContext, AsyncWindowContext, Bounds, DevicePixels, DragMoveEvent, ElementId, Entity as _, EntityId, EventEmitter, FocusHandle, FocusableView, Global, GlobalElementId, KeyContext, Keystroke, LayoutId, ManagedView, Model, ModelContext, PathPromptOptions, Point, PromptLevel, Render, Size, Subscription, Task, View, WeakView, WindowBounds, WindowHandle, WindowOptions,};use item::{ FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings, ProjectItem,};use itertools::Itertools;use language::{LanguageRegistry, Rope};use lazy_static::lazy_static;pub use modal_layer::*;use node_runtime::NodeRuntime;use notifications::{simple_message_notification::MessageNotification, NotificationHandle};pub use pane::*;pub use pane_group::*;use persistence::{model::SerializedWorkspace, SerializedWindowBounds, DB};pub use persistence::{ model::{ItemId, LocalPaths, SerializedDevServerProject, SerializedWorkspaceLocation}, WorkspaceDb, DB as WORKSPACE_DB,};use postage::stream::Stream;use project::{Project, ProjectEntryId, ProjectPath, Worktree, WorktreeId};use serde::Deserialize;use settings::Settings;use shared_screen::SharedScreen;use sqlez::{ bindable::{Bind, Column, StaticColumnCount}, statement::Statement,};use status_bar::StatusBar;pub use status_bar::StatusItemView;use std::{ any::TypeId, borrow::Cow, cell::RefCell, cmp, collections::hash_map::DefaultHasher, env, hash::{Hash, Hasher}, path::{Path, PathBuf}, rc::Rc, sync::{atomic::AtomicUsize, Arc, Weak}, time::Duration,};use task::SpawnInTerminal;use theme::{ActiveTheme, SystemAppearance, ThemeSettings};pub use toolbar::{Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView};pub use ui;use ui::{ div, h_flex, Context as _, Div, Element, FluentBuilder, InteractiveElement as _, IntoElement, Label, ParentElement as _, Pixels, SharedString, Styled as _, ViewContext, VisualContext as _, WindowContext,};use util::{maybe, ResultExt};use uuid::Uuid;pub use workspace_settings::{ AutosaveSetting, RestoreOnStartupBehaviour, TabBarSettings, WorkspaceSettings,}; use crate::notifications::NotificationId;use crate::persistence::{ model::{DockData, DockStructure, SerializedItem, SerializedPane, SerializedPaneGroup}, SerializedAxis,}; lazy_static! { static ref ZED_WINDOW_SIZE: Option<Size<DevicePixels>> = env::var("ZED_WINDOW_SIZE") .ok() .as_deref() .and_then(parse_pixel_size_env_var); static ref ZED_WINDOW_POSITION: Option<Point<DevicePixels>> = env::var("ZED_WINDOW_POSITION") .ok() .as_deref() .and_then(parse_pixel_position_env_var);} #[derive(Clone, PartialEq)]pub struct RemoveWorktreeFromProject(pub WorktreeId); actions!( workspace, [ Open, OpenInTerminal, NewFile, NewWindow, CloseWindow, AddFolderToProject, Unfollow, SaveAs, SaveWithoutFormat, ReloadActiveItem, ActivatePreviousPane, ActivateNextPane, FollowNextCollaborator, NewTerminal, NewCenterTerminal, NewSearch, Feedback, Welcome, ToggleZoom, ToggleLeftDock, ToggleRightDock, ToggleBottomDock, ToggleCenteredLayout, CloseAllDocks, ]); #[derive(Clone, PartialEq)]pub struct OpenPaths { pub paths: Vec<PathBuf>,} #[derive(Clone, Deserialize, PartialEq)]pub struct ActivatePane(pub usize); #[derive(Clone, Deserialize, PartialEq)]pub struct ActivatePaneInDirection(pub SplitDirection); #[derive(Clone, Deserialize, PartialEq)]pub struct SwapPaneInDirection(pub SplitDirection); #[derive(Clone, Deserialize, PartialEq)]pub struct NewFileInDirection(pub SplitDirection); #[derive(Clone, PartialEq, Debug, Deserialize)]#[serde(rename_all = "camelCase")]pub struct SaveAll { pub save_intent: Option<SaveIntent>,} #[derive(Clone, PartialEq, Debug, Deserialize)]#[serde(rename_all = "camelCase")]pub struct Save { pub save_intent: Option<SaveIntent>,} #[derive(Clone, PartialEq, Debug, Deserialize, Default)]#[serde(rename_all = "camelCase")]pub struct CloseAllItemsAndPanes { pub save_intent: Option<SaveIntent>,} #[derive(Clone, PartialEq, Debug, Deserialize, Default)]#[serde(rename_all = "camelCase")]pub struct CloseInactiveTabsAndPanes { pub save_intent: Option<SaveIntent>,} #[derive(Clone, Deserialize, PartialEq)]pub struct SendKeystrokes(pub String); #[derive(Clone, Deserialize, PartialEq, Default)]pub struct Restart { pub binary_path: Option<PathBuf>,} impl_actions!( workspace, [ ActivatePane, ActivatePaneInDirection, CloseAllItemsAndPanes, CloseInactiveTabsAndPanes, NewFileInDirection, OpenTerminal, Restart, Save, SaveAll, SwapPaneInDirection, SendKeystrokes, ]); pub struct Toast { id: NotificationId, msg: Cow<'static, str>, on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut WindowContext)>)>,} impl Toast { pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self { Toast { id, msg: msg.into(), on_click: None, } } pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self where M: Into<Cow<'static, str>>, F: Fn(&mut WindowContext) + 'static, { self.on_click = Some((message.into(), Arc::new(on_click))); self }} impl PartialEq for Toast { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.msg == other.msg && self.on_click.is_some() == other.on_click.is_some() }} impl Clone for Toast { fn clone(&self) -> Self { Toast { id: self.id.clone(), msg: self.msg.clone(), on_click: self.on_click.clone(), } }} #[derive(Debug, Default, Clone, Deserialize, PartialEq)]pub struct OpenTerminal { pub working_directory: PathBuf,} #[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]pub struct WorkspaceId(i64); impl StaticColumnCount for WorkspaceId {}impl Bind for WorkspaceId { fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> { self.0.bind(statement, start_index) }}impl Column for WorkspaceId { fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> { i64::column(statement, start_index) .map(|(i, next_index)| (Self(i), next_index)) .with_context(|| format!("Failed to read WorkspaceId at index {start_index}")) }}pub fn init_settings(cx: &mut AppContext) { WorkspaceSettings::register(cx); ItemSettings::register(cx); PreviewTabsSettings::register(cx); TabBarSettings::register(cx);} pub fn init(app_state: Arc<AppState>, cx: &mut AppContext) { init_settings(cx); notifications::init(cx); cx.on_action(Workspace::close_global); cx.on_action(restart); cx.on_action({ let app_state = Arc::downgrade(&app_state); move |_: &Open, cx: &mut AppContext| { let paths = cx.prompt_for_paths(PathPromptOptions { files: true, directories: true, multiple: true, }); if let Some(app_state) = app_state.upgrade() { cx.spawn(move |cx| async move { if let Some(paths) = paths.await.log_err().flatten() { cx.update(|cx| { open_paths(&paths, app_state, OpenOptions::default(), cx) .detach_and_log_err(cx) }) .ok(); } }) .detach(); } } });} #[derive(Clone, Default, Deref, DerefMut)]struct ProjectItemOpeners(Vec<ProjectItemOpener>); type ProjectItemOpener = fn( &Model<Project>, &ProjectPath, &mut WindowContext,) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>; type WorkspaceItemBuilder = Box<dyn FnOnce(&mut ViewContext<Pane>) -> Box<dyn ItemHandle>>; impl Global for ProjectItemOpeners {} /// Registers a [ProjectItem] for the app. When opening a file, all the registered/// items will get a chance to open the file, starting from the project item that/// was added last.pub fn register_project_item<I: ProjectItem>(cx: &mut AppContext) { let builders = cx.default_global::<ProjectItemOpeners>(); builders.push(|project, project_path, cx| { let project_item = <I::Item as project::Item>::try_open(&project, project_path, cx)?; let project = project.clone(); Some(cx.spawn(|cx| async move { let project_item = project_item.await?; let project_entry_id: Option<ProjectEntryId> = project_item.read_with(&cx, |item, cx| project::Item::entry_id(item, cx))?; let build_workspace_item = Box::new(|cx: &mut ViewContext<Pane>| { Box::new(cx.new_view(|cx| I::for_project_item(project, project_item, cx))) as Box<dyn ItemHandle> }) as Box<_>; Ok((project_entry_id, build_workspace_item)) })) });} type FollowableItemBuilder = fn( View<Pane>, View<Workspace>, ViewId, &mut Option<proto::view::Variant>, &mut WindowContext,) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>; #[derive(Default, Deref, DerefMut)]struct FollowableItemBuilders( HashMap< TypeId, ( FollowableItemBuilder, fn(&AnyView) -> Box<dyn FollowableItemHandle>, ), >,); impl Global for FollowableItemBuilders {} pub fn register_followable_item<I: FollowableItem>(cx: &mut AppContext) { let builders = cx.default_global::<FollowableItemBuilders>(); builders.insert( TypeId::of::<I>(), ( |pane, workspace, id, state, cx| { I::from_state_proto(pane, workspace, id, state, cx).map(|task| { cx.foreground_executor() .spawn(async move { Ok(Box::new(task.await?) as Box<_>) }) }) }, |this| Box::new(this.clone().downcast::<I>().unwrap()), ), );} #[derive(Default, Deref, DerefMut)]struct ItemDeserializers( HashMap< Arc<str>, fn( Model<Project>, WeakView<Workspace>, WorkspaceId, ItemId, &mut ViewContext<Pane>, ) -> Task<Result<Box<dyn ItemHandle>>>, >,); impl Global for ItemDeserializers {} pub fn register_deserializable_item<I: Item>(cx: &mut AppContext) { if let Some(serialized_item_kind) = I::serialized_item_kind() { let deserializers = cx.default_global::<ItemDeserializers>(); deserializers.insert( Arc::from(serialized_item_kind), |project, workspace, workspace_id, item_id, cx| { let task = I::deserialize(project, workspace, workspace_id, item_id, cx); cx.foreground_executor() .spawn(async { Ok(Box::new(task.await?) as Box<_>) }) }, ); }} pub struct AppState { pub languages: Arc<LanguageRegistry>, pub client: Arc<Client>, pub user_store: Model<UserStore>, pub workspace_store: Model<WorkspaceStore>, pub fs: Arc<dyn fs::Fs>, pub build_window_options: fn(Option<Uuid>, &mut AppContext) -> WindowOptions, pub node_runtime: Arc<dyn NodeRuntime>,} struct GlobalAppState(Weak<AppState>); impl Global for GlobalAppState {} pub struct WorkspaceStore { workspaces: HashSet<WindowHandle<Workspace>>, client: Arc<Client>, _subscriptions: Vec<client::Subscription>,} #[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]struct Follower { project_id: Option<u64>, peer_id: PeerId,} impl AppState { pub fn global(cx: &AppContext) -> Weak<Self> { cx.global::<GlobalAppState>().0.clone() } pub fn try_global(cx: &AppContext) -> Option<Weak<Self>> { cx.try_global::<GlobalAppState>() .map(|state| state.0.clone()) } pub fn set_global(state: Weak<AppState>, cx: &mut AppContext) { cx.set_global(GlobalAppState(state)); } #[cfg(any(test, feature = "test-support"))] pub fn test(cx: &mut AppContext) -> Arc<Self> { use node_runtime::FakeNodeRuntime; use settings::SettingsStore; use ui::Context as _; if !cx.has_global::<SettingsStore>() { let settings_store = SettingsStore::test(cx); cx.set_global(settings_store); } let fs = fs::FakeFs::new(cx.background_executor().clone()); let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone())); let clock = Arc::new(clock::FakeSystemClock::default()); let http_client = http::FakeHttpClient::with_404_response(); let client = Client::new(clock, http_client.clone(), cx); let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx)); let workspace_store = cx.new_model(|cx| WorkspaceStore::new(client.clone(), cx)); theme::init(theme::LoadThemes::JustBase, cx); client::init(&client, cx); crate::init_settings(cx); Arc::new(Self { client, fs, languages, user_store, workspace_store, node_runtime: FakeNodeRuntime::new(), build_window_options: |_, _| Default::default(), }) }} struct DelayedDebouncedEditAction { task: Option<Task<()>>, cancel_channel: Option<oneshot::Sender<()>>,} impl DelayedDebouncedEditAction { fn new() -> DelayedDebouncedEditAction { DelayedDebouncedEditAction { task: None, cancel_channel: None, } } fn fire_new<F>(&mut self, delay: Duration, cx: &mut ViewContext<Workspace>, func: F)Lines 1–500 of 6463. Load more
pub mod dock; pub mod item; mod modal_layer; pub mod notifications; pub mod pane; pub mod pane_group; mod persistence; pub mod searchable; pub mod shared_screen; mod status_bar; pub mod tasks; mod toolbar; mod workspace_settings; use anyhow::{anyhow, Context as _, Result}; use call::{call_settings::CallSettings, ActiveCall}; use client::{ proto::{self, ErrorCode, PeerId}, ChannelId, Client, ErrorExt, ProjectId, Status, TypedEnvelope, UserStore, }; use collections::{hash_map, HashMap, HashSet}; use derive_more::{Deref, DerefMut}; use dock::{Dock, DockPosition, Panel, PanelButtons, PanelHandle}; use futures::{ channel::{mpsc, oneshot}, future::try_join_all, Future, FutureExt, StreamExt, }; use gpui::{ actions, canvas, impl_actions, point, relative, size, Action, AnyElement, AnyView, AnyWeakView, AppContext, AsyncAppContext, AsyncWindowContext, Bounds, DevicePixels, DragMoveEvent, ElementId, Entity as _, EntityId, EventEmitter, FocusHandle, FocusableView, Global, GlobalElementId, KeyContext, Keystroke, LayoutId, ManagedView, Model, ModelContext, PathPromptOptions, Point, PromptLevel, Render, Size, Subscription, Task, View, WeakView, WindowBounds, WindowHandle, WindowOptions, }; use item::{ FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings, ProjectItem, }; use itertools::Itertools; use language::{LanguageRegistry, Rope}; use lazy_static::lazy_static; pub use modal_layer::*; use node_runtime::NodeRuntime; use notifications::{simple_message_notification::MessageNotification, NotificationHandle}; pub use pane::*; pub use pane_group::*; use persistence::{model::SerializedWorkspace, SerializedWindowBounds, DB}; pub use persistence::{ model::{ItemId, LocalPaths, SerializedDevServerProject, SerializedWorkspaceLocation}, WorkspaceDb, DB as WORKSPACE_DB, }; use postage::stream::Stream; use project::{Project, ProjectEntryId, ProjectPath, Worktree, WorktreeId}; use serde::Deserialize; use settings::Settings; use shared_screen::SharedScreen; use sqlez::{ bindable::{Bind, Column, StaticColumnCount}, statement::Statement, }; use status_bar::StatusBar; pub use status_bar::StatusItemView; use std::{ any::TypeId, borrow::Cow, cell::RefCell, cmp, collections::hash_map::DefaultHasher, env, hash::{Hash, Hasher}, path::{Path, PathBuf}, rc::Rc, sync::{atomic::AtomicUsize, Arc, Weak}, time::Duration, }; use task::SpawnInTerminal; use theme::{ActiveTheme, SystemAppearance, ThemeSettings}; pub use toolbar::{Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView}; pub use ui; use ui::{ div, h_flex, Context as _, Div, Element, FluentBuilder, InteractiveElement as _, IntoElement, Label, ParentElement as _, Pixels, SharedString, Styled as _, ViewContext, VisualContext as _, WindowContext, }; use util::{maybe, ResultExt}; use uuid::Uuid; pub use workspace_settings::{ AutosaveSetting, RestoreOnStartupBehaviour, TabBarSettings, WorkspaceSettings, }; use crate::notifications::NotificationId; use crate::persistence::{ model::{DockData, DockStructure, SerializedItem, SerializedPane, SerializedPaneGroup}, SerializedAxis, }; lazy_static! { static ref ZED_WINDOW_SIZE: Option<Size<DevicePixels>> = env::var("ZED_WINDOW_SIZE") .ok() .as_deref() .and_then(parse_pixel_size_env_var); static ref ZED_WINDOW_POSITION: Option<Point<DevicePixels>> = env::var("ZED_WINDOW_POSITION") .ok() .as_deref() .and_then(parse_pixel_position_env_var); } #[derive(Clone, PartialEq)] pub struct RemoveWorktreeFromProject(pub WorktreeId); actions!( workspace, [ Open, OpenInTerminal, NewFile, NewWindow, CloseWindow, AddFolderToProject, Unfollow, SaveAs, SaveWithoutFormat, ReloadActiveItem, ActivatePreviousPane, ActivateNextPane, FollowNextCollaborator, NewTerminal, NewCenterTerminal, NewSearch, Feedback, Welcome, ToggleZoom, ToggleLeftDock, ToggleRightDock, ToggleBottomDock, ToggleCenteredLayout, CloseAllDocks, ] ); #[derive(Clone, PartialEq)] pub struct OpenPaths { pub paths: Vec<PathBuf>, } #[derive(Clone, Deserialize, PartialEq)] pub struct ActivatePane(pub usize); #[derive(Clone, Deserialize, PartialEq)] pub struct ActivatePaneInDirection(pub SplitDirection); #[derive(Clone, Deserialize, PartialEq)] pub struct SwapPaneInDirection(pub SplitDirection); #[derive(Clone, Deserialize, PartialEq)] pub struct NewFileInDirection(pub SplitDirection); #[derive(Clone, PartialEq, Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SaveAll { pub save_intent: Option<SaveIntent>, } #[derive(Clone, PartialEq, Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Save { pub save_intent: Option<SaveIntent>, } #[derive(Clone, PartialEq, Debug, Deserialize, Default)] #[serde(rename_all = "camelCase")] pub struct CloseAllItemsAndPanes { pub save_intent: Option<SaveIntent>, } #[derive(Clone, PartialEq, Debug, Deserialize, Default)] #[serde(rename_all = "camelCase")] pub struct CloseInactiveTabsAndPanes { pub save_intent: Option<SaveIntent>, } #[derive(Clone, Deserialize, PartialEq)] pub struct SendKeystrokes(pub String); #[derive(Clone, Deserialize, PartialEq, Default)] pub struct Restart { pub binary_path: Option<PathBuf>, } impl_actions!( workspace, [ ActivatePane, ActivatePaneInDirection, CloseAllItemsAndPanes, CloseInactiveTabsAndPanes, NewFileInDirection, OpenTerminal, Restart, Save, SaveAll, SwapPaneInDirection, SendKeystrokes, ] ); pub struct Toast { id: NotificationId, msg: Cow<'static, str>, on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut WindowContext)>)>, } impl Toast { pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self { Toast { id, msg: msg.into(), on_click: None, } } pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self where M: Into<Cow<'static, str>>, F: Fn(&mut WindowContext) + 'static, { self.on_click = Some((message.into(), Arc::new(on_click))); self } } impl PartialEq for Toast { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.msg == other.msg && self.on_click.is_some() == other.on_click.is_some() } } impl Clone for Toast { fn clone(&self) -> Self { Toast { id: self.id.clone(), msg: self.msg.clone(), on_click: self.on_click.clone(), } } } #[derive(Debug, Default, Clone, Deserialize, PartialEq)] pub struct OpenTerminal { pub working_directory: PathBuf, } #[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct WorkspaceId(i64); impl StaticColumnCount for WorkspaceId {} impl Bind for WorkspaceId { fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> { self.0.bind(statement, start_index) } } impl Column for WorkspaceId { fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> { i64::column(statement, start_index) .map(|(i, next_index)| (Self(i), next_index)) .with_context(|| format!("Failed to read WorkspaceId at index {start_index}")) } } pub fn init_settings(cx: &mut AppContext) { WorkspaceSettings::register(cx); ItemSettings::register(cx); PreviewTabsSettings::register(cx); TabBarSettings::register(cx); } pub fn init(app_state: Arc<AppState>, cx: &mut AppContext) { init_settings(cx); notifications::init(cx); cx.on_action(Workspace::close_global); cx.on_action(restart); cx.on_action({ let app_state = Arc::downgrade(&app_state); move |_: &Open, cx: &mut AppContext| { let paths = cx.prompt_for_paths(PathPromptOptions { files: true, directories: true, multiple: true, }); if let Some(app_state) = app_state.upgrade() { cx.spawn(move |cx| async move { if let Some(paths) = paths.await.log_err().flatten() { cx.update(|cx| { open_paths(&paths, app_state, OpenOptions::default(), cx) .detach_and_log_err(cx) }) .ok(); } }) .detach(); } } }); } #[derive(Clone, Default, Deref, DerefMut)] struct ProjectItemOpeners(Vec<ProjectItemOpener>); type ProjectItemOpener = fn( &Model<Project>, &ProjectPath, &mut WindowContext, ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>; type WorkspaceItemBuilder = Box<dyn FnOnce(&mut ViewContext<Pane>) -> Box<dyn ItemHandle>>; impl Global for ProjectItemOpeners {} /// Registers a [ProjectItem] for the app. When opening a file, all the registered /// items will get a chance to open the file, starting from the project item that /// was added last. pub fn register_project_item<I: ProjectItem>(cx: &mut AppContext) { let builders = cx.default_global::<ProjectItemOpeners>(); builders.push(|project, project_path, cx| { let project_item = <I::Item as project::Item>::try_open(&project, project_path, cx)?; let project = project.clone(); Some(cx.spawn(|cx| async move { let project_item = project_item.await?; let project_entry_id: Option<ProjectEntryId> = project_item.read_with(&cx, |item, cx| project::Item::entry_id(item, cx))?; let build_workspace_item = Box::new(|cx: &mut ViewContext<Pane>| { Box::new(cx.new_view(|cx| I::for_project_item(project, project_item, cx))) as Box<dyn ItemHandle> }) as Box<_>; Ok((project_entry_id, build_workspace_item)) })) }); } type FollowableItemBuilder = fn( View<Pane>, View<Workspace>, ViewId, &mut Option<proto::view::Variant>, &mut WindowContext, ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>; #[derive(Default, Deref, DerefMut)] struct FollowableItemBuilders( HashMap< TypeId, ( FollowableItemBuilder, fn(&AnyView) -> Box<dyn FollowableItemHandle>, ), >, ); impl Global for FollowableItemBuilders {} pub fn register_followable_item<I: FollowableItem>(cx: &mut AppContext) { let builders = cx.default_global::<FollowableItemBuilders>(); builders.insert( TypeId::of::<I>(), ( |pane, workspace, id, state, cx| { I::from_state_proto(pane, workspace, id, state, cx).map(|task| { cx.foreground_executor() .spawn(async move { Ok(Box::new(task.await?) as Box<_>) }) }) }, |this| Box::new(this.clone().downcast::<I>().unwrap()), ), ); } #[derive(Default, Deref, DerefMut)] struct ItemDeserializers( HashMap< Arc<str>, fn( Model<Project>, WeakView<Workspace>, WorkspaceId, ItemId, &mut ViewContext<Pane>, ) -> Task<Result<Box<dyn ItemHandle>>>, >, ); impl Global for ItemDeserializers {} pub fn register_deserializable_item<I: Item>(cx: &mut AppContext) { if let Some(serialized_item_kind) = I::serialized_item_kind() { let deserializers = cx.default_global::<ItemDeserializers>(); deserializers.insert( Arc::from(serialized_item_kind), |project, workspace, workspace_id, item_id, cx| { let task = I::deserialize(project, workspace, workspace_id, item_id, cx); cx.foreground_executor() .spawn(async { Ok(Box::new(task.await?) as Box<_>) }) }, ); } } pub struct AppState { pub languages: Arc<LanguageRegistry>, pub client: Arc<Client>, pub user_store: Model<UserStore>, pub workspace_store: Model<WorkspaceStore>, pub fs: Arc<dyn fs::Fs>, pub build_window_options: fn(Option<Uuid>, &mut AppContext) -> WindowOptions, pub node_runtime: Arc<dyn NodeRuntime>, } struct GlobalAppState(Weak<AppState>); impl Global for GlobalAppState {} pub struct WorkspaceStore { workspaces: HashSet<WindowHandle<Workspace>>, client: Arc<Client>, _subscriptions: Vec<client::Subscription>, } #[derive(PartialEq, Eq, PartialOrd, Ord, Debug)] struct Follower { project_id: Option<u64>, peer_id: PeerId, } impl AppState { pub fn global(cx: &AppContext) -> Weak<Self> { cx.global::<GlobalAppState>().0.clone() } pub fn try_global(cx: &AppContext) -> Option<Weak<Self>> { cx.try_global::<GlobalAppState>() .map(|state| state.0.clone()) } pub fn set_global(state: Weak<AppState>, cx: &mut AppContext) { cx.set_global(GlobalAppState(state)); } #[cfg(any(test, feature = "test-support"))] pub fn test(cx: &mut AppContext) -> Arc<Self> { use node_runtime::FakeNodeRuntime; use settings::SettingsStore; use ui::Context as _; if !cx.has_global::<SettingsStore>() { let settings_store = SettingsStore::test(cx); cx.set_global(settings_store); } let fs = fs::FakeFs::new(cx.background_executor().clone()); let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone())); let clock = Arc::new(clock::FakeSystemClock::default()); let http_client = http::FakeHttpClient::with_404_response(); let client = Client::new(clock, http_client.clone(), cx); let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx)); let workspace_store = cx.new_model(|cx| WorkspaceStore::new(client.clone(), cx)); theme::init(theme::LoadThemes::JustBase, cx); client::init(&client, cx); crate::init_settings(cx); Arc::new(Self { client, fs, languages, user_store, workspace_store, node_runtime: FakeNodeRuntime::new(), build_window_options: |_, _| Default::default(), }) } } struct DelayedDebouncedEditAction { task: Option<Task<()>>, cancel_channel: Option<oneshot::Sender<()>>, } impl DelayedDebouncedEditAction { fn new() -> DelayedDebouncedEditAction { DelayedDebouncedEditAction { task: None, cancel_channel: None, } } fn fire_new<F>(&mut self, delay: Duration, cx: &mut ViewContext<Workspace>, func: F)