Skip to main content

gpui/
action.rs

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