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    /// Optional JSON schema for the action's input data.
 67    fn action_json_schema(
 68        _: &mut schemars::gen::SchemaGenerator,
 69    ) -> Option<schemars::schema::Schema>
 70    where
 71        Self: Sized,
 72    {
 73        None
 74    }
 75
 76    /// A list of alternate, deprecated names for this action.
 77    fn deprecated_aliases() -> &'static [&'static str]
 78    where
 79        Self: Sized,
 80    {
 81        &[]
 82    }
 83}
 84
 85impl std::fmt::Debug for dyn Action {
 86    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 87        f.debug_struct("dyn Action")
 88            .field("name", &self.name())
 89            .finish()
 90    }
 91}
 92
 93impl dyn Action {
 94    /// Get the type id of this action
 95    pub fn type_id(&self) -> TypeId {
 96        self.as_any().type_id()
 97    }
 98}
 99
100type ActionBuilder = fn(json: serde_json::Value) -> anyhow::Result<Box<dyn Action>>;
101
102pub(crate) struct ActionRegistry {
103    by_name: HashMap<SharedString, ActionData>,
104    names_by_type_id: HashMap<TypeId, SharedString>,
105    all_names: Vec<SharedString>, // So we can return a static slice.
106    deprecations: HashMap<SharedString, SharedString>,
107}
108
109impl Default for ActionRegistry {
110    fn default() -> Self {
111        let mut this = ActionRegistry {
112            by_name: Default::default(),
113            names_by_type_id: Default::default(),
114            all_names: Default::default(),
115            deprecations: Default::default(),
116        };
117
118        this.load_actions();
119
120        this
121    }
122}
123
124struct ActionData {
125    pub build: ActionBuilder,
126    pub json_schema: fn(&mut schemars::gen::SchemaGenerator) -> Option<schemars::schema::Schema>,
127}
128
129/// This type must be public so that our macros can build it in other crates.
130/// But this is an implementation detail and should not be used directly.
131#[doc(hidden)]
132pub type MacroActionBuilder = fn() -> MacroActionData;
133
134/// This type must be public so that our macros can build it in other crates.
135/// But this is an implementation detail and should not be used directly.
136#[doc(hidden)]
137pub struct MacroActionData {
138    pub name: &'static str,
139    pub aliases: &'static [&'static str],
140    pub type_id: TypeId,
141    pub build: ActionBuilder,
142    pub json_schema: fn(&mut schemars::gen::SchemaGenerator) -> Option<schemars::schema::Schema>,
143}
144
145/// This constant must be public to be accessible from other crates.
146/// But its existence is an implementation detail and should not be used directly.
147#[doc(hidden)]
148#[linkme::distributed_slice]
149pub static __GPUI_ACTIONS: [MacroActionBuilder];
150
151impl ActionRegistry {
152    /// Load all registered actions into the registry.
153    pub(crate) fn load_actions(&mut self) {
154        for builder in __GPUI_ACTIONS {
155            let action = builder();
156            self.insert_action(action);
157        }
158    }
159
160    #[cfg(test)]
161    pub(crate) fn load_action<A: Action>(&mut self) {
162        self.insert_action(MacroActionData {
163            name: A::debug_name(),
164            aliases: A::deprecated_aliases(),
165            type_id: TypeId::of::<A>(),
166            build: A::build,
167            json_schema: A::action_json_schema,
168        });
169    }
170
171    fn insert_action(&mut self, action: MacroActionData) {
172        let name: SharedString = action.name.into();
173        self.by_name.insert(
174            name.clone(),
175            ActionData {
176                build: action.build,
177                json_schema: action.json_schema,
178            },
179        );
180        for &alias in action.aliases {
181            let alias: SharedString = alias.into();
182            self.by_name.insert(
183                alias.clone(),
184                ActionData {
185                    build: action.build,
186                    json_schema: action.json_schema,
187                },
188            );
189            self.deprecations.insert(alias.clone(), name.clone());
190            self.all_names.push(alias);
191        }
192        self.names_by_type_id.insert(action.type_id, name.clone());
193        self.all_names.push(name);
194    }
195
196    /// Construct an action based on its name and optional JSON parameters sourced from the keymap.
197    pub fn build_action_type(&self, type_id: &TypeId) -> Result<Box<dyn Action>> {
198        let name = self
199            .names_by_type_id
200            .get(type_id)
201            .ok_or_else(|| anyhow!("no action type registered for {:?}", type_id))?
202            .clone();
203
204        self.build_action(&name, None)
205    }
206
207    /// Construct an action based on its name and optional JSON parameters sourced from the keymap.
208    pub fn build_action(
209        &self,
210        name: &str,
211        params: Option<serde_json::Value>,
212    ) -> Result<Box<dyn Action>> {
213        let build_action = self
214            .by_name
215            .get(name)
216            .ok_or_else(|| anyhow!("No action type registered for {}", name))?
217            .build;
218        (build_action)(params.unwrap_or_else(|| json!({})))
219            .with_context(|| format!("Attempting to build action {}", name))
220    }
221
222    pub fn all_action_names(&self) -> &[SharedString] {
223        self.all_names.as_slice()
224    }
225
226    pub fn action_schemas(
227        &self,
228        generator: &mut schemars::gen::SchemaGenerator,
229    ) -> Vec<(SharedString, Option<schemars::schema::Schema>)> {
230        // Use the order from all_names so that the resulting schema has sensible order.
231        self.all_names
232            .iter()
233            .map(|name| {
234                let action_data = self
235                    .by_name
236                    .get(name)
237                    .expect("All actions in all_names should be registered");
238                (name.clone(), (action_data.json_schema)(generator))
239            })
240            .collect::<Vec<_>>()
241    }
242
243    pub fn action_deprecations(&self) -> &HashMap<SharedString, SharedString> {
244        &self.deprecations
245    }
246}
247
248/// Defines and registers unit structs that can be used as actions.
249///
250/// To use more complex data types as actions, use `impl_actions!`
251#[macro_export]
252macro_rules! actions {
253    ($namespace:path, [ $($name:ident),* $(,)? ]) => {
254        $(
255            // Unfortunately rust-analyzer doesn't display the name due to
256            // https://github.com/rust-lang/rust-analyzer/issues/8092
257            #[doc = stringify!($name)]
258            #[doc = "action generated by `gpui::actions!`"]
259            #[derive(::std::clone::Clone,::std::cmp::PartialEq, ::std::default::Default)]
260            pub struct $name;
261
262            gpui::__impl_action!($namespace, $name, $name,
263                fn build(_: gpui::private::serde_json::Value) -> gpui::Result<::std::boxed::Box<dyn gpui::Action>> {
264                    Ok(Box::new(Self))
265                },
266                fn action_json_schema(
267                    _: &mut gpui::private::schemars::gen::SchemaGenerator,
268                ) -> Option<gpui::private::schemars::schema::Schema> {
269                    None
270                }
271            );
272
273            gpui::register_action!($name);
274        )*
275    };
276}
277
278/// Defines and registers a unit struct that can be used as an actions, with a name that differs
279/// from it's type name.
280///
281/// To use more complex data types as actions, and rename them use `impl_action_as!`
282#[macro_export]
283macro_rules! action_as {
284    ($namespace:path, $name:ident as $visual_name:ident) => {
285        // Unfortunately rust-analyzer doesn't display the name due to
286        // https://github.com/rust-lang/rust-analyzer/issues/8092
287        #[doc = stringify!($name)]
288        #[doc = "action generated by `gpui::action_as!`"]
289        #[derive(
290            ::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug, ::std::cmp::PartialEq,
291        )]
292        pub struct $name;
293
294        gpui::__impl_action!(
295            $namespace,
296            $name,
297            $visual_name,
298            fn build(
299                _: gpui::private::serde_json::Value,
300            ) -> gpui::Result<::std::boxed::Box<dyn gpui::Action>> {
301                Ok(Box::new(Self))
302            },
303            fn action_json_schema(
304                generator: &mut gpui::private::schemars::gen::SchemaGenerator,
305            ) -> Option<gpui::private::schemars::schema::Schema> {
306                None
307            }
308        );
309
310        gpui::register_action!($name);
311    };
312}
313
314/// Defines and registers a unit struct that can be used as an action, with some deprecated aliases.
315#[macro_export]
316macro_rules! action_with_deprecated_aliases {
317    ($namespace:path, $name:ident, [$($alias:literal),* $(,)?]) => {
318        // Unfortunately rust-analyzer doesn't display the name due to
319        // https://github.com/rust-lang/rust-analyzer/issues/8092
320        #[doc = stringify!($name)]
321        #[doc = "action, generated by `gpui::action_with_deprecated_aliases!`"]
322        #[derive(
323            ::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug, ::std::cmp::PartialEq,
324        )]
325        pub struct $name;
326
327        gpui::__impl_action!(
328            $namespace,
329            $name,
330            $name,
331            fn build(
332                _: gpui::private::serde_json::Value,
333            ) -> gpui::Result<::std::boxed::Box<dyn gpui::Action>> {
334                Ok(Box::new(Self))
335            },
336            fn action_json_schema(
337                generator: &mut gpui::private::schemars::gen::SchemaGenerator,
338            ) -> Option<gpui::private::schemars::schema::Schema> {
339                None
340
341            },
342            fn deprecated_aliases() -> &'static [&'static str] {
343                &[
344                    $($alias),*
345                ]
346            }
347        );
348
349        gpui::register_action!($name);
350    };
351}
352
353/// Registers the action and implements the Action trait for any struct that implements Clone,
354/// Default, PartialEq, serde_deserialize::Deserialize, and schemars::JsonSchema.
355///
356/// Fields and variants that don't make sense for user configuration should be annotated with
357/// #[serde(skip)].
358#[macro_export]
359macro_rules! impl_actions {
360    ($namespace:path, [ $($name:ident),* $(,)? ]) => {
361        $(
362            gpui::__impl_action!($namespace, $name, $name,
363                fn build(value: gpui::private::serde_json::Value) -> gpui::Result<::std::boxed::Box<dyn gpui::Action>> {
364                    Ok(std::boxed::Box::new(gpui::private::serde_json::from_value::<Self>(value)?))
365                },
366                fn action_json_schema(
367                    generator: &mut gpui::private::schemars::gen::SchemaGenerator,
368                ) -> Option<gpui::private::schemars::schema::Schema> {
369                    Some(<Self as gpui::private::schemars::JsonSchema>::json_schema(
370                        generator,
371                    ))
372                }
373            );
374
375            gpui::register_action!($name);
376        )*
377    };
378}
379
380/// Implements the Action trait for internal action structs that implement Clone, Default,
381/// PartialEq. The purpose of this is to conveniently define values that can be passed in `dyn
382/// Action`.
383///
384/// These actions are internal and so are not registered and do not support deserialization.
385#[macro_export]
386macro_rules! impl_internal_actions {
387    ($namespace:path, [ $($name:ident),* $(,)? ]) => {
388        $(
389            gpui::__impl_action!($namespace, $name, $name,
390                fn build(value: gpui::private::serde_json::Value) -> gpui::Result<::std::boxed::Box<dyn gpui::Action>> {
391                    gpui::Result::Err(gpui::private::anyhow::anyhow!(
392                        concat!(
393                            stringify!($namespace),
394                            "::",
395                            stringify!($visual_name),
396                            " is an internal action, so cannot be built from JSON."
397                        )))
398                },
399                fn action_json_schema(
400                    generator: &mut gpui::private::schemars::gen::SchemaGenerator,
401                ) -> Option<gpui::private::schemars::schema::Schema> {
402                    None
403                }
404            );
405        )*
406    };
407}
408
409/// Implements the Action trait for a struct that implements Clone, Default, PartialEq, and
410/// serde_deserialize::Deserialize. Allows you to rename the action visually, without changing the
411/// struct's name.
412///
413/// Fields and variants that don't make sense for user configuration should be annotated with
414/// #[serde(skip)].
415#[macro_export]
416macro_rules! impl_action_as {
417    ($namespace:path, $name:ident as $visual_name:tt ) => {
418        gpui::__impl_action!(
419            $namespace,
420            $name,
421            $visual_name,
422            fn build(
423                value: gpui::private::serde_json::Value,
424            ) -> gpui::Result<::std::boxed::Box<dyn gpui::Action>> {
425                Ok(std::boxed::Box::new(
426                    gpui::private::serde_json::from_value::<Self>(value)?,
427                ))
428            },
429            fn action_json_schema(
430                generator: &mut gpui::private::schemars::gen::SchemaGenerator,
431            ) -> Option<gpui::private::schemars::schema::Schema> {
432                Some(<Self as gpui::private::schemars::JsonSchema>::json_schema(
433                    generator,
434                ))
435            }
436        );
437
438        gpui::register_action!($name);
439    };
440}
441
442#[doc(hidden)]
443#[macro_export]
444macro_rules! __impl_action {
445    ($namespace:path, $name:ident, $visual_name:tt, $($items:item),*) => {
446        impl gpui::Action for $name {
447            fn name(&self) -> &'static str
448            {
449                concat!(
450                    stringify!($namespace),
451                    "::",
452                    stringify!($visual_name),
453                )
454            }
455
456            fn debug_name() -> &'static str
457            where
458                Self: ::std::marker::Sized
459            {
460                concat!(
461                    stringify!($namespace),
462                    "::",
463                    stringify!($visual_name),
464                )
465            }
466
467            fn partial_eq(&self, action: &dyn gpui::Action) -> bool {
468                action
469                    .as_any()
470                    .downcast_ref::<Self>()
471                    .map_or(false, |a| self == a)
472            }
473
474            fn boxed_clone(&self) ->  std::boxed::Box<dyn gpui::Action> {
475                ::std::boxed::Box::new(self.clone())
476            }
477
478            fn as_any(&self) -> &dyn ::std::any::Any {
479                self
480            }
481
482            $($items)*
483        }
484    };
485}
486
487mod no_action {
488    use crate as gpui;
489    use std::any::Any as _;
490
491    actions!(zed, [NoAction]);
492
493    /// Returns whether or not this action represents a removed key binding.
494    pub fn is_no_action(action: &dyn gpui::Action) -> bool {
495        action.as_any().type_id() == (NoAction {}).type_id()
496    }
497}