action.rs

  1use crate::SharedString;
  2use anyhow::{anyhow, Context, Result};
  3use collections::HashMap;
  4pub use no_action::{is_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 + Send {
 43    /// Clone the action into a new box
 44    fn boxed_clone(&self) -> Box<dyn Action>;
 45
 46    /// Cast the action to the any type
 47    fn as_any(&self) -> &dyn Any;
 48
 49    /// Do a partial equality check on this action and the other
 50    fn partial_eq(&self, action: &dyn Action) -> bool;
 51
 52    /// Get the name of this action, for displaying in UI
 53    fn name(&self) -> &str;
 54
 55    /// Get the name of this action for debugging
 56    fn debug_name() -> &'static str
 57    where
 58        Self: Sized;
 59
 60    /// Build this action from a JSON value. This is used to construct actions from the keymap.
 61    /// A value of `{}` will be passed for actions that don't have any parameters.
 62    fn build(value: serde_json::Value) -> Result<Box<dyn Action>>
 63    where
 64        Self: Sized;
 65}
 66
 67impl std::fmt::Debug for dyn Action {
 68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 69        f.debug_struct("dyn Action")
 70            .field("name", &self.name())
 71            .finish()
 72    }
 73}
 74
 75impl dyn Action {
 76    /// Get the type id of this action
 77    pub fn type_id(&self) -> TypeId {
 78        self.as_any().type_id()
 79    }
 80}
 81
 82type ActionBuilder = fn(json: serde_json::Value) -> anyhow::Result<Box<dyn Action>>;
 83
 84pub(crate) struct ActionRegistry {
 85    builders_by_name: HashMap<SharedString, ActionBuilder>,
 86    names_by_type_id: HashMap<TypeId, SharedString>,
 87    all_names: Vec<SharedString>, // So we can return a static slice.
 88}
 89
 90impl Default for ActionRegistry {
 91    fn default() -> Self {
 92        let mut this = ActionRegistry {
 93            builders_by_name: Default::default(),
 94            names_by_type_id: Default::default(),
 95            all_names: Default::default(),
 96        };
 97
 98        this.load_actions();
 99
100        this
101    }
102}
103
104/// This type must be public so that our macros can build it in other crates.
105/// But this is an implementation detail and should not be used directly.
106#[doc(hidden)]
107pub type MacroActionBuilder = fn() -> ActionData;
108
109/// This type must be public so that our macros can build it in other crates.
110/// But this is an implementation detail and should not be used directly.
111#[doc(hidden)]
112pub struct ActionData {
113    pub name: &'static str,
114    pub type_id: TypeId,
115    pub build: ActionBuilder,
116}
117
118/// This constant must be public to be accessible from other crates.
119/// But its existence is an implementation detail and should not be used directly.
120#[doc(hidden)]
121#[linkme::distributed_slice]
122pub static __GPUI_ACTIONS: [MacroActionBuilder];
123
124impl ActionRegistry {
125    /// Load all registered actions into the registry.
126    pub(crate) fn load_actions(&mut self) {
127        for builder in __GPUI_ACTIONS {
128            let action = builder();
129            self.insert_action(action);
130        }
131    }
132
133    #[cfg(test)]
134    pub(crate) fn load_action<A: Action>(&mut self) {
135        self.insert_action(ActionData {
136            name: A::debug_name(),
137            type_id: TypeId::of::<A>(),
138            build: A::build,
139        });
140    }
141
142    fn insert_action(&mut self, action: ActionData) {
143        let name: SharedString = action.name.into();
144        self.builders_by_name.insert(name.clone(), action.build);
145        self.names_by_type_id.insert(action.type_id, name.clone());
146        self.all_names.push(name);
147    }
148
149    /// Construct an action based on its name and optional JSON parameters sourced from the keymap.
150    pub fn build_action_type(&self, type_id: &TypeId) -> Result<Box<dyn Action>> {
151        let name = self
152            .names_by_type_id
153            .get(type_id)
154            .ok_or_else(|| anyhow!("no action type registered for {:?}", type_id))?
155            .clone();
156
157        self.build_action(&name, None)
158    }
159
160    /// Construct an action based on its name and optional JSON parameters sourced from the keymap.
161    pub fn build_action(
162        &self,
163        name: &str,
164        params: Option<serde_json::Value>,
165    ) -> Result<Box<dyn Action>> {
166        let build_action = self
167            .builders_by_name
168            .get(name)
169            .ok_or_else(|| anyhow!("no action type registered for {}", name))?;
170        (build_action)(params.unwrap_or_else(|| json!({})))
171            .with_context(|| format!("Attempting to build action {}", name))
172    }
173
174    pub fn all_action_names(&self) -> &[SharedString] {
175        self.all_names.as_slice()
176    }
177}
178
179/// Defines unit structs that can be used as actions.
180/// To use more complex data types as actions, use `impl_actions!`
181#[macro_export]
182macro_rules! actions {
183    ($namespace:path, [ $($name:ident),* $(,)? ]) => {
184        $(
185            #[doc = "The `"]
186            #[doc = stringify!($name)]
187            #[doc = "` action, see [`gpui::actions!`]"]
188            #[derive(::std::clone::Clone,::std::cmp::PartialEq, ::std::default::Default)]
189            pub struct $name;
190
191            gpui::__impl_action!($namespace, $name, $name,
192                fn build(_: gpui::private::serde_json::Value) -> gpui::Result<::std::boxed::Box<dyn gpui::Action>> {
193                    Ok(Box::new(Self))
194                }
195            );
196
197            gpui::register_action!($name);
198        )*
199    };
200}
201
202/// Defines a unit struct that can be used as an actions, with a name
203/// that differs from it's type name.
204///
205/// To use more complex data types as actions, and rename them use
206/// `impl_action_as!`
207#[macro_export]
208macro_rules! action_as {
209    ($namespace:path, $name:ident as $visual_name:tt) => {
210        #[doc = "The `"]
211        #[doc = stringify!($name)]
212        #[doc = "` action, see [`gpui::actions!`]"]
213        #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default)]
214        pub struct $name;
215
216        gpui::__impl_action!(
217            $namespace,
218            $name,
219            $visual_name,
220            fn build(
221                _: gpui::private::serde_json::Value,
222            ) -> gpui::Result<::std::boxed::Box<dyn gpui::Action>> {
223                Ok(Box::new(Self))
224            }
225        );
226
227        gpui::register_action!($name);
228    };
229}
230
231/// Implements the Action trait for any struct that implements Clone, Default, PartialEq, and serde_deserialize::Deserialize
232#[macro_export]
233macro_rules! impl_actions {
234    ($namespace:path, [ $($name:ident),* $(,)? ]) => {
235        $(
236            gpui::__impl_action!($namespace, $name, $name,
237                fn build(value: gpui::private::serde_json::Value) -> gpui::Result<::std::boxed::Box<dyn gpui::Action>> {
238                    Ok(std::boxed::Box::new(gpui::private::serde_json::from_value::<Self>(value)?))
239                }
240            );
241
242            gpui::register_action!($name);
243        )*
244    };
245}
246
247/// Implements the Action trait for a struct that implements Clone, Default, PartialEq, and serde_deserialize::Deserialize
248/// Allows you to rename the action visually, without changing the struct's name
249#[macro_export]
250macro_rules! impl_action_as {
251    ($namespace:path, $name:ident as $visual_name:tt ) => {
252        gpui::__impl_action!(
253            $namespace,
254            $name,
255            $visual_name,
256            fn build(
257                value: gpui::private::serde_json::Value,
258            ) -> gpui::Result<::std::boxed::Box<dyn gpui::Action>> {
259                Ok(std::boxed::Box::new(
260                    gpui::private::serde_json::from_value::<Self>(value)?,
261                ))
262            }
263        );
264
265        gpui::register_action!($name);
266    };
267}
268
269#[doc(hidden)]
270#[macro_export]
271macro_rules! __impl_action {
272    ($namespace:path, $name:ident, $visual_name:tt, $build:item) => {
273        impl gpui::Action for $name {
274            fn name(&self) -> &'static str
275            {
276                concat!(
277                    stringify!($namespace),
278                    "::",
279                    stringify!($visual_name),
280                )
281            }
282
283            fn debug_name() -> &'static str
284            where
285                Self: ::std::marker::Sized
286            {
287                concat!(
288                    stringify!($namespace),
289                    "::",
290                    stringify!($visual_name),
291                )
292            }
293
294            $build
295
296            fn partial_eq(&self, action: &dyn gpui::Action) -> bool {
297                action
298                    .as_any()
299                    .downcast_ref::<Self>()
300                    .map_or(false, |a| self == a)
301            }
302
303            fn boxed_clone(&self) ->  std::boxed::Box<dyn gpui::Action> {
304                ::std::boxed::Box::new(self.clone())
305            }
306
307            fn as_any(&self) -> &dyn ::std::any::Any {
308                self
309            }
310        }
311    };
312}
313
314mod no_action {
315    use crate as gpui;
316    use std::any::Any as _;
317
318    actions!(zed, [NoAction]);
319
320    /// Returns whether or not this action represents a removed key binding.
321    pub fn is_no_action(action: &dyn gpui::Action) -> bool {
322        action.as_any().type_id() == (NoAction {}).type_id()
323    }
324}