Skip to main content

gpui/
action.rs

1// Modified for gpui-pre (snapshot of zed@f816e1f): the `actions!` derive paths are crate-relative.
2use anyhow::{Context as _, Result};
3use collections::{HashMap, TypeIdHashMap};
4pub use gpui_macros::Action;
5pub use no_action::{NoAction, Unbind, is_no_action, is_unbind};
6use serde_json::json;
7use std::{
8    any::{Any, TypeId},
9    fmt::Display,
10};
11
12/// Defines and registers unit structs that can be used as actions. For more complex data types, derive `Action`.
13///
14/// For example:
15///
16/// ```
17/// use gpui::actions;
18/// actions!(editor, [MoveUp, MoveDown, MoveLeft, MoveRight, Newline]);
19/// ```
20///
21/// This will create actions with names like `editor::MoveUp`, `editor::MoveDown`, etc.
22///
23/// The namespace argument `editor` can also be omitted, though it is required for Zed actions.
24#[macro_export]
25macro_rules! actions {
26    ($namespace:path, [ $( $(#[$attr:meta])* $name:ident),* $(,)? ]) => {
27        $(
28            #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, $crate::Action)]
29            #[action(namespace = $namespace)]
30            $(#[$attr])*
31            pub struct $name;
32        )*
33    };
34    ([ $( $(#[$attr:meta])* $name:ident),* $(,)? ]) => {
35        $(
36            #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, $crate::Action)]
37            $(#[$attr])*
38            pub struct $name;
39        )*
40    };
41}
42
43/// Actions are used to implement keyboard-driven UI. When you declare an action, you can bind keys
44/// to the action in the keymap and listeners for that action in the element tree.
45///
46/// To declare a list of simple actions, you can use the actions! macro, which defines a simple unit
47/// struct action for each listed action name in the given namespace.
48///
49/// ```
50/// use gpui::actions;
51/// actions!(editor, [MoveUp, MoveDown, MoveLeft, MoveRight, Newline]);
52/// ```
53///
54/// Registering the actions with the same name will result in a panic during  `App` creation.
55///
56/// # Derive Macro
57///
58/// More complex data types can also be actions, by using the derive macro for `Action`:
59///
60/// ```
61/// use gpui::Action;
62/// #[derive(Clone, PartialEq, serde::Deserialize, schemars::JsonSchema, Action)]
63/// #[action(namespace = editor)]
64/// pub struct SelectNext {
65///     pub replace_newest: bool,
66/// }
67/// ```
68///
69/// The derive macro for `Action` requires that the type implement `Clone` and `PartialEq`. It also
70/// requires `serde::Deserialize` and `schemars::JsonSchema` unless `#[action(no_json)]` is
71/// specified. In Zed these trait impls are used to load keymaps from JSON.
72///
73/// Multiple arguments separated by commas may be specified in `#[action(...)]`:
74///
75/// - `namespace = some_namespace` sets the namespace. In Zed this is required.
76///
77/// - `name = "ActionName"` overrides the action's name. This must not contain `::`.
78///
79/// - `no_json` causes the `build` method to always error and `action_json_schema` to return `None`,
80///   and allows actions not implement `serde::Serialize` and `schemars::JsonSchema`.
81///
82/// - `no_register` skips registering the action. This is useful for implementing the `Action` trait
83///   while not supporting invocation by name or JSON deserialization.
84///
85/// - `deprecated_aliases = ["editor::SomeAction"]` specifies deprecated old names for the action.
86///   These action names should *not* correspond to any actions that are registered. These old names
87///   can then still be used to refer to invoke this action. In Zed, the keymap JSON schema will
88///   accept these old names and provide warnings.
89///
90/// - `deprecated = "Message about why this action is deprecation"` specifies a deprecation message.
91///   In Zed, the keymap JSON schema will cause this to be displayed as a warning.
92///
93/// # Manual Implementation
94///
95/// If you want to control the behavior of the action trait manually, you can use the lower-level
96/// `#[register_action]` macro, which only generates the code needed to register your action before
97/// `main`.
98///
99/// ```
100/// use gpui::{SharedString, register_action};
101/// #[derive(Clone, PartialEq, Eq, serde::Deserialize, schemars::JsonSchema)]
102/// pub struct Paste {
103///     pub content: SharedString,
104/// }
105///
106/// impl gpui::Action for Paste {
107///     # fn boxed_clone(&self) -> Box<dyn gpui::Action> { unimplemented!()}
108///     # fn partial_eq(&self, other: &dyn gpui::Action) -> bool { unimplemented!() }
109///     # fn name(&self) -> &'static str { "Paste" }
110///     # fn name_for_type() -> &'static str { "Paste" }
111///     # fn build(value: serde_json::Value) -> anyhow::Result<Box<dyn gpui::Action>> {
112///     #     unimplemented!()
113///     # }
114/// }
115///
116/// register_action!(Paste);
117/// ```
118pub trait Action: Any + Send {
119    /// Clone the action into a new box
120    fn boxed_clone(&self) -> Box<dyn Action>;
121
122    /// Do a partial equality check on this action and the other
123    fn partial_eq(&self, action: &dyn Action) -> bool;
124
125    /// Get the name of this action, for displaying in UI
126    fn name(&self) -> &'static str;
127
128    /// Get the name of this action type (static)
129    fn name_for_type() -> &'static str
130    where
131        Self: Sized;
132
133    /// Build this action from a JSON value. This is used to construct actions from the keymap.
134    /// A value of `{}` will be passed for actions that don't have any parameters.
135    fn build(value: serde_json::Value) -> Result<Box<dyn Action>>
136    where
137        Self: Sized;
138
139    /// Optional JSON schema for the action's input data.
140    fn action_json_schema(_: &mut schemars::SchemaGenerator) -> Option<schemars::Schema>
141    where
142        Self: Sized,
143    {
144        None
145    }
146
147    /// A list of alternate, deprecated names for this action. These names can still be used to
148    /// invoke the action. In Zed, the keymap JSON schema will accept these old names and provide
149    /// warnings.
150    fn deprecated_aliases() -> &'static [&'static str]
151    where
152        Self: Sized,
153    {
154        &[]
155    }
156
157    /// Returns the deprecation message for this action, if any. In Zed, the keymap JSON schema will
158    /// cause this to be displayed as a warning.
159    fn deprecation_message() -> Option<&'static str>
160    where
161        Self: Sized,
162    {
163        None
164    }
165
166    /// The documentation for this action, if any. When using the derive macro for actions
167    /// this will be automatically generated from the doc comments on the action struct.
168    fn documentation() -> Option<&'static str>
169    where
170        Self: Sized,
171    {
172        None
173    }
174}
175
176impl std::fmt::Debug for dyn Action {
177    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178        f.debug_struct("dyn Action")
179            .field("name", &self.name())
180            .finish()
181    }
182}
183
184impl dyn Action {
185    /// Type-erase Action type.
186    pub fn as_any(&self) -> &dyn Any {
187        self as &dyn Any
188    }
189}
190
191/// Error type for `Keystroke::parse`. This is used instead of `anyhow::Error` so that Zed can use
192/// markdown to display it.
193#[derive(Debug)]
194pub enum ActionBuildError {
195    /// Indicates that an action with this name has not been registered.
196    NotFound {
197        /// Name of the action that was not found.
198        name: Box<str>,
199    },
200    /// Indicates that an error occurred while building the action, typically a JSON deserialization
201    /// error.
202    BuildError {
203        /// Name of the action that was attempting to be built.
204        name: Box<str>,
205        /// Error that occurred while building the action.
206        error: anyhow::Error,
207    },
208}
209
210impl std::error::Error for ActionBuildError {
211    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
212        match self {
213            ActionBuildError::NotFound { .. } => None,
214            ActionBuildError::BuildError { error, .. } => error.source(),
215        }
216    }
217}
218
219impl Display for ActionBuildError {
220    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
221        match self {
222            ActionBuildError::NotFound { name } => {
223                write!(f, "Didn't find an action named \"{name}\"")
224            }
225            ActionBuildError::BuildError { name, error } => {
226                write!(f, "Error while building action \"{name}\": {error}")
227            }
228        }
229    }
230}
231
232type ActionBuilder = fn(json: serde_json::Value) -> anyhow::Result<Box<dyn Action>>;
233
234pub(crate) struct ActionRegistry {
235    by_name: HashMap<&'static str, ActionData>,
236    names_by_type_id: TypeIdHashMap<&'static str>,
237    all_names: Vec<&'static str>, // So we can return a static slice.
238    deprecated_aliases: HashMap<&'static str, &'static str>, // deprecated name -> preferred name
239    deprecation_messages: HashMap<&'static str, &'static str>, // action name -> deprecation message
240    documentation: HashMap<&'static str, &'static str>, // action name -> documentation
241}
242
243impl Default for ActionRegistry {
244    fn default() -> Self {
245        let mut this = ActionRegistry {
246            by_name: Default::default(),
247            names_by_type_id: Default::default(),
248            documentation: Default::default(),
249            all_names: Default::default(),
250            deprecated_aliases: Default::default(),
251            deprecation_messages: Default::default(),
252        };
253
254        this.load_actions();
255
256        this
257    }
258}
259
260struct ActionData {
261    pub build: ActionBuilder,
262    pub json_schema: fn(&mut schemars::SchemaGenerator) -> Option<schemars::Schema>,
263}
264
265/// This type must be public so that our macros can build it in other crates.
266/// But this is an implementation detail and should not be used directly.
267#[doc(hidden)]
268pub struct MacroActionBuilder(pub fn() -> MacroActionData);
269
270/// This type must be public so that our macros can build it in other crates.
271/// But this is an implementation detail and should not be used directly.
272#[doc(hidden)]
273pub struct MacroActionData {
274    pub name: &'static str,
275    pub type_id: TypeId,
276    pub build: ActionBuilder,
277    pub json_schema: fn(&mut schemars::SchemaGenerator) -> Option<schemars::Schema>,
278    pub deprecated_aliases: &'static [&'static str],
279    pub deprecation_message: Option<&'static str>,
280    pub documentation: Option<&'static str>,
281}
282
283inventory::collect!(MacroActionBuilder);
284
285impl ActionRegistry {
286    /// Load all registered actions into the registry.
287    pub(crate) fn load_actions(&mut self) {
288        for builder in inventory::iter::<MacroActionBuilder> {
289            let action = builder.0();
290            self.insert_action(action);
291        }
292    }
293
294    fn insert_action(&mut self, action: MacroActionData) {
295        let name = action.name;
296        if self.by_name.contains_key(name) {
297            panic!(
298                "Action with name `{name}` already registered \
299                (might be registered in `#[action(deprecated_aliases = [...])]`."
300            );
301        }
302        self.by_name.insert(
303            name,
304            ActionData {
305                build: action.build,
306                json_schema: action.json_schema,
307            },
308        );
309        for &alias in action.deprecated_aliases {
310            if self.by_name.contains_key(alias) {
311                panic!(
312                    "Action with name `{alias}` already registered. \
313                    `{alias}` is specified in `#[action(deprecated_aliases = [...])]` for action `{name}`."
314                );
315            }
316            self.by_name.insert(
317                alias,
318                ActionData {
319                    build: action.build,
320                    json_schema: action.json_schema,
321                },
322            );
323            self.deprecated_aliases.insert(alias, name);
324            self.all_names.push(alias);
325        }
326        self.names_by_type_id.insert(action.type_id, name);
327        self.all_names.push(name);
328        if let Some(deprecation_msg) = action.deprecation_message {
329            self.deprecation_messages.insert(name, deprecation_msg);
330        }
331        if let Some(documentation) = action.documentation {
332            self.documentation.insert(name, documentation);
333        }
334    }
335
336    /// Construct an action based on its name and optional JSON parameters sourced from the keymap.
337    pub fn build_action_type(&self, type_id: &TypeId) -> Result<Box<dyn Action>> {
338        let name = self
339            .names_by_type_id
340            .get(type_id)
341            .with_context(|| format!("no action type registered for {type_id:?}"))?;
342
343        Ok(self.build_action(name, None)?)
344    }
345
346    #[cfg(feature = "profiler")]
347    pub(crate) fn try_resolve_action(&self, type_id: &TypeId) -> Option<&'static str> {
348        self.names_by_type_id.get(type_id).copied()
349    }
350
351    /// Construct an action based on its name and optional JSON parameters sourced from the keymap.
352    pub fn build_action(
353        &self,
354        name: &str,
355        params: Option<serde_json::Value>,
356    ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
357        let build_action = self
358            .by_name
359            .get(name)
360            .ok_or_else(|| ActionBuildError::NotFound { name: name.into() })?
361            .build;
362        (build_action)(params.unwrap_or_else(|| json!({}))).map_err(|e| {
363            ActionBuildError::BuildError {
364                name: name.into(),
365                error: e,
366            }
367        })
368    }
369
370    pub fn all_action_names(&self) -> &[&'static str] {
371        self.all_names.as_slice()
372    }
373
374    pub fn action_schemas(
375        &self,
376        generator: &mut schemars::SchemaGenerator,
377    ) -> Vec<(&'static str, Option<schemars::Schema>)> {
378        // Use the order from all_names so that the resulting schema has sensible order.
379        self.all_names
380            .iter()
381            .map(|name| {
382                let action_data = self
383                    .by_name
384                    .get(name)
385                    .expect("All actions in all_names should be registered");
386                (*name, (action_data.json_schema)(generator))
387            })
388            .collect::<Vec<_>>()
389    }
390
391    pub fn action_schema_by_name(
392        &self,
393        name: &str,
394        generator: &mut schemars::SchemaGenerator,
395    ) -> Option<Option<schemars::Schema>> {
396        self.by_name
397            .get(name)
398            .map(|action_data| (action_data.json_schema)(generator))
399    }
400
401    pub fn deprecated_aliases(&self) -> &HashMap<&'static str, &'static str> {
402        &self.deprecated_aliases
403    }
404
405    pub fn deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
406        &self.deprecation_messages
407    }
408
409    pub fn documentation(&self) -> &HashMap<&'static str, &'static str> {
410        &self.documentation
411    }
412}
413
414/// Generate a list of all the registered actions.
415/// Useful for transforming the list of available actions into a
416/// format suited for static analysis such as in validating keymaps, or
417/// generating documentation.
418pub fn generate_list_of_all_registered_actions() -> impl Iterator<Item = MacroActionData> {
419    inventory::iter::<MacroActionBuilder>
420        .into_iter()
421        .map(|builder| builder.0())
422}
423
424mod no_action {
425    use crate as gpui;
426    use schemars::JsonSchema;
427    use serde::Deserialize;
428
429    actions!(
430        zed,
431        [
432            /// Action with special handling which unbinds the keybinding this is associated with,
433            /// if it is the highest precedence match.
434            NoAction
435        ]
436    );
437
438    /// Action with special handling which unbinds later bindings for the same keystrokes when they
439    /// dispatch the named action, regardless of that action's context.
440    ///
441    /// In keymap JSON this is written as:
442    ///
443    /// `["zed::Unbind", "editor::NewLine"]`
444    #[derive(Clone, Debug, PartialEq, Deserialize, JsonSchema, gpui::Action)]
445    #[action(namespace = zed)]
446    pub struct Unbind(pub gpui::SharedString);
447
448    /// Returns whether or not this action represents a removed key binding.
449    pub fn is_no_action(action: &dyn gpui::Action) -> bool {
450        action.as_any().is::<NoAction>()
451    }
452
453    /// Returns whether or not this action represents an unbind marker.
454    pub fn is_unbind(action: &dyn gpui::Action) -> bool {
455        action.as_any().is::<Unbind>()
456    }
457}