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