action.rs

  1use crate::SharedString;
  2use anyhow::{anyhow, Context, Result};
  3use collections::HashMap;
  4pub use no_action::NoAction;
  5use serde_json::json;
  6use std::any::{Any, TypeId};
  7
  8/// Actions are used to implement keyboard-driven UI.
  9/// When you declare an action, you can bind keys to the action in the keymap and
 10/// listeners for that action in the element tree.
 11///
 12/// To declare a list of simple actions, you can use the actions! macro, which defines a simple unit struct
 13/// action for each listed action name in the given namespace.
 14/// ```rust
 15/// actions!(editor, [MoveUp, MoveDown, MoveLeft, MoveRight, Newline]);
 16/// ```
 17/// More complex data types can also be actions, providing they implement Clone, PartialEq,
 18/// and serde_derive::Deserialize.
 19/// Use `impl_actions!` to automatically implement the action in the given namespace.
 20/// ```
 21/// #[derive(Clone, PartialEq, serde_derive::Deserialize)]
 22/// pub struct SelectNext {
 23///     pub replace_newest: bool,
 24/// }
 25/// impl_actions!(editor, [SelectNext]);
 26/// ```
 27///
 28/// If you want to control the behavior of the action trait manually, you can use the lower-level `#[register_action]`
 29/// macro, which only generates the code needed to register your action before `main`.
 30///
 31/// ```
 32/// #[derive(gpui::private::serde::Deserialize, std::cmp::PartialEq, std::clone::Clone)]
 33/// pub struct Paste {
 34///     pub content: SharedString,
 35/// }
 36///
 37/// impl gpui::Action for Paste {
 38///      ///...
 39/// }
 40/// register_action!(Paste);
 41/// ```
 42pub trait Action: 'static {
 43    fn boxed_clone(&self) -> Box<dyn Action>;
 44    fn as_any(&self) -> &dyn Any;
 45    fn partial_eq(&self, action: &dyn Action) -> bool;
 46    fn name(&self) -> &str;
 47
 48    fn debug_name() -> &'static str
 49    where
 50        Self: Sized;
 51    fn build(value: serde_json::Value) -> Result<Box<dyn Action>>
 52    where
 53        Self: Sized;
 54}
 55
 56impl std::fmt::Debug for dyn Action {
 57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 58        f.debug_struct("dyn Action")
 59            .field("name", &self.name())
 60            .finish()
 61    }
 62}
 63
 64impl dyn Action {
 65    pub fn type_id(&self) -> TypeId {
 66        self.as_any().type_id()
 67    }
 68}
 69
 70type ActionBuilder = fn(json: serde_json::Value) -> anyhow::Result<Box<dyn Action>>;
 71
 72pub(crate) struct ActionRegistry {
 73    builders_by_name: HashMap<SharedString, ActionBuilder>,
 74    names_by_type_id: HashMap<TypeId, SharedString>,
 75    all_names: Vec<SharedString>, // So we can return a static slice.
 76}
 77
 78impl Default for ActionRegistry {
 79    fn default() -> Self {
 80        let mut this = ActionRegistry {
 81            builders_by_name: Default::default(),
 82            names_by_type_id: Default::default(),
 83            all_names: Default::default(),
 84        };
 85
 86        this.load_actions();
 87
 88        this
 89    }
 90}
 91
 92/// This type must be public so that our macros can build it in other crates.
 93/// But this is an implementation detail and should not be used directly.
 94#[doc(hidden)]
 95pub type MacroActionBuilder = fn() -> ActionData;
 96
 97/// This type must be public so that our macros can build it in other crates.
 98/// But this is an implementation detail and should not be used directly.
 99#[doc(hidden)]
100pub struct ActionData {
101    pub name: &'static str,
102    pub type_id: TypeId,
103    pub build: ActionBuilder,
104}
105
106/// This constant must be public to be accessible from other crates.
107/// But it's existence is an implementation detail and should not be used directly.
108#[doc(hidden)]
109#[linkme::distributed_slice]
110pub static __GPUI_ACTIONS: [MacroActionBuilder];
111
112impl ActionRegistry {
113    /// Load all registered actions into the registry.
114    pub(crate) fn load_actions(&mut self) {
115        for builder in __GPUI_ACTIONS {
116            let action = builder();
117            //todo(remove)
118            let name: SharedString = action.name.into();
119            self.builders_by_name.insert(name.clone(), action.build);
120            self.names_by_type_id.insert(action.type_id, name.clone());
121            self.all_names.push(name);
122        }
123    }
124
125    /// Construct an action based on its name and optional JSON parameters sourced from the keymap.
126    pub fn build_action_type(&self, type_id: &TypeId) -> Result<Box<dyn Action>> {
127        let name = self
128            .names_by_type_id
129            .get(type_id)
130            .ok_or_else(|| anyhow!("no action type registered for {:?}", type_id))?
131            .clone();
132
133        self.build_action(&name, None)
134    }
135
136    /// Construct an action based on its name and optional JSON parameters sourced from the keymap.
137    pub fn build_action(
138        &self,
139        name: &str,
140        params: Option<serde_json::Value>,
141    ) -> Result<Box<dyn Action>> {
142        let build_action = self
143            .builders_by_name
144            .get(name)
145            .ok_or_else(|| anyhow!("no action type registered for {}", name))?;
146        (build_action)(params.unwrap_or_else(|| json!({})))
147            .with_context(|| format!("Attempting to build action {}", name))
148    }
149
150    pub fn all_action_names(&self) -> &[SharedString] {
151        self.all_names.as_slice()
152    }
153}
154
155/// Defines unit structs that can be used as actions.
156/// To use more complex data types as actions, use `impl_actions!`
157#[macro_export]
158macro_rules! actions {
159    ($namespace:path, [ $($name:ident),* $(,)? ]) => {
160        $(
161            #[derive(::std::cmp::PartialEq, ::std::clone::Clone, ::std::default::Default, gpui::private::serde_derive::Deserialize)]
162            #[serde(crate = "gpui::private::serde")]
163            pub struct $name;
164
165            gpui::__impl_action!($namespace, $name,
166                fn build(_: gpui::private::serde_json::Value) -> gpui::Result<::std::boxed::Box<dyn gpui::Action>> {
167                    Ok(Box::new(Self))
168                }
169            );
170
171            gpui::register_action!($name);
172        )*
173    };
174}
175
176/// Implements the Action trait for any struct that implements Clone, Default, PartialEq, and serde_deserialize::Deserialize
177#[macro_export]
178macro_rules! impl_actions {
179    ($namespace:path, [ $($name:ident),* $(,)? ]) => {
180        $(
181            gpui::__impl_action!($namespace, $name,
182                fn build(value: gpui::private::serde_json::Value) -> gpui::Result<::std::boxed::Box<dyn gpui::Action>> {
183                    Ok(std::boxed::Box::new(gpui::private::serde_json::from_value::<Self>(value)?))
184                }
185            );
186
187            gpui::register_action!($name);
188        )*
189    };
190}
191
192#[doc(hidden)]
193#[macro_export]
194macro_rules! __impl_action {
195    ($namespace:path, $name:ident, $build:item) => {
196        impl gpui::Action for $name {
197            fn name(&self) -> &'static str
198            {
199                concat!(
200                    stringify!($namespace),
201                    "::",
202                    stringify!($name),
203                )
204            }
205
206            // todo!() why is this needed in addition to name?
207            fn debug_name() -> &'static str
208            where
209                Self: ::std::marker::Sized
210            {
211                concat!(
212                    stringify!($namespace),
213                    "::",
214                    stringify!($name),
215                )
216            }
217
218            $build
219
220            fn partial_eq(&self, action: &dyn gpui::Action) -> bool {
221                action
222                    .as_any()
223                    .downcast_ref::<Self>()
224                    .map_or(false, |a| self == a)
225            }
226
227            fn boxed_clone(&self) ->  std::boxed::Box<dyn gpui::Action> {
228                ::std::boxed::Box::new(self.clone())
229            }
230
231            fn as_any(&self) -> &dyn ::std::any::Any {
232                self
233            }
234        }
235    };
236}
237
238mod no_action {
239    use crate as gpui;
240
241    actions!(zed, [NoAction]);
242}