open_gpui/action.rs
1use anyhow::{Context as _, Result};
2pub use no_action::{NoAction, Unbind, is_no_action, is_unbind};
3use open_gpui_collections::{HashMap, TypeIdHashMap};
4pub use open_gpui_macros::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/// use open_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 for application-local actions. Public
23/// actions should use an explicit namespace so keymaps can refer to them unambiguously.
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, open_gpui::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, open_gpui::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 open_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 open_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. These trait impls allow actions to be loaded from JSON keymaps.
72///
73/// Multiple arguments separated by commas may be specified in `#[action(...)]`:
74///
75/// - `namespace = some_namespace` sets the namespace used in serialized action names.
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. JSON schema consumers can accept these
88/// old names and provide warnings.
89///
90/// - `deprecated = "Message about why this action is deprecation"` specifies a deprecation message.
91/// JSON schema consumers can display this 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 open_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 open_gpui::Action for Paste {
107/// # fn boxed_clone(&self) -> Box<dyn open_gpui::Action> { unimplemented!()}
108/// # fn partial_eq(&self, other: &dyn open_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 open_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. JSON schema consumers can accept these old names and provide warnings.
149 fn deprecated_aliases() -> &'static [&'static str]
150 where
151 Self: Sized,
152 {
153 &[]
154 }
155
156 /// Returns the deprecation message for this action, if any. JSON schema consumers can display
157 /// this as a warning.
158 fn deprecation_message() -> Option<&'static str>
159 where
160 Self: Sized,
161 {
162 None
163 }
164
165 /// The documentation for this action, if any. When using the derive macro for actions
166 /// this will be automatically generated from the doc comments on the action struct.
167 fn documentation() -> Option<&'static str>
168 where
169 Self: Sized,
170 {
171 None
172 }
173}
174
175impl std::fmt::Debug for dyn Action {
176 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
177 f.debug_struct("dyn Action")
178 .field("name", &self.name())
179 .finish()
180 }
181}
182
183impl dyn Action {
184 /// Type-erase Action type.
185 pub fn as_any(&self) -> &dyn Any {
186 self as &dyn Any
187 }
188}
189
190/// Error type for constructing actions from JSON. This is used instead of `anyhow::Error` so
191/// callers can display structured, user-friendly diagnostics.
192#[derive(Debug)]
193pub enum ActionBuildError {
194 /// Indicates that an action with this name has not been registered.
195 NotFound {
196 /// Name of the action that was not found.
197 name: String,
198 },
199 /// Indicates that an error occurred while building the action, typically a JSON deserialization
200 /// error.
201 BuildError {
202 /// Name of the action that was attempting to be built.
203 name: String,
204 /// Error that occurred while building the action.
205 error: anyhow::Error,
206 },
207}
208
209impl std::error::Error for ActionBuildError {
210 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
211 match self {
212 ActionBuildError::NotFound { .. } => None,
213 ActionBuildError::BuildError { error, .. } => error.source(),
214 }
215 }
216}
217
218impl Display for ActionBuildError {
219 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220 match self {
221 ActionBuildError::NotFound { name } => {
222 write!(f, "Didn't find an action named \"{name}\"")
223 }
224 ActionBuildError::BuildError { name, error } => {
225 write!(f, "Error while building action \"{name}\": {error}")
226 }
227 }
228 }
229}
230
231type ActionBuilder = fn(json: serde_json::Value) -> anyhow::Result<Box<dyn Action>>;
232
233pub(crate) struct ActionRegistry {
234 by_name: HashMap<&'static str, ActionData>,
235 names_by_type_id: TypeIdHashMap<&'static str>,
236 all_names: Vec<&'static str>, // So we can return a static slice.
237 deprecated_aliases: HashMap<&'static str, &'static str>, // deprecated name -> preferred name
238 deprecation_messages: HashMap<&'static str, &'static str>, // action name -> deprecation message
239 documentation: HashMap<&'static str, &'static str>, // action name -> documentation
240}
241
242impl Default for ActionRegistry {
243 fn default() -> Self {
244 let mut this = ActionRegistry {
245 by_name: Default::default(),
246 names_by_type_id: Default::default(),
247 documentation: Default::default(),
248 all_names: Default::default(),
249 deprecated_aliases: Default::default(),
250 deprecation_messages: Default::default(),
251 };
252
253 this.load_actions();
254
255 this
256 }
257}
258
259struct ActionData {
260 pub build: ActionBuilder,
261 pub json_schema: fn(&mut schemars::SchemaGenerator) -> Option<schemars::Schema>,
262}
263
264/// This type must be public so that our macros can build it in other crates.
265/// But this is an implementation detail and should not be used directly.
266#[doc(hidden)]
267pub struct MacroActionBuilder(pub fn() -> MacroActionData);
268
269/// This type must be public so that our macros can build it in other crates.
270/// But this is an implementation detail and should not be used directly.
271#[doc(hidden)]
272pub struct MacroActionData {
273 pub name: &'static str,
274 pub type_id: TypeId,
275 pub build: ActionBuilder,
276 pub json_schema: fn(&mut schemars::SchemaGenerator) -> Option<schemars::Schema>,
277 pub deprecated_aliases: &'static [&'static str],
278 pub deprecation_message: Option<&'static str>,
279 pub documentation: Option<&'static str>,
280}
281
282inventory::collect!(MacroActionBuilder);
283
284impl ActionRegistry {
285 /// Load all registered actions into the registry.
286 pub(crate) fn load_actions(&mut self) {
287 for builder in inventory::iter::<MacroActionBuilder> {
288 let action = builder.0();
289 self.insert_action(action);
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 if let Some(documentation) = action.documentation {
331 self.documentation.insert(name, documentation);
332 }
333 }
334
335 /// Construct an action based on its name and optional JSON parameters sourced from the keymap.
336 pub fn build_action_type(&self, type_id: &TypeId) -> Result<Box<dyn Action>> {
337 let name = self
338 .names_by_type_id
339 .get(type_id)
340 .with_context(|| format!("no action type registered for {type_id:?}"))?;
341
342 Ok(self.build_action(name, None)?)
343 }
344
345 pub(crate) fn try_resolve_action(&self, type_id: &TypeId) -> Option<&'static str> {
346 self.names_by_type_id.get(type_id).copied()
347 }
348
349 /// Construct an action based on its name and optional JSON parameters sourced from the keymap.
350 pub fn build_action(
351 &self,
352 name: &str,
353 params: Option<serde_json::Value>,
354 ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
355 let build_action = self
356 .by_name
357 .get(name)
358 .ok_or_else(|| ActionBuildError::NotFound {
359 name: name.to_owned(),
360 })?
361 .build;
362 (build_action)(params.unwrap_or_else(|| json!({}))).map_err(|e| {
363 ActionBuildError::BuildError {
364 name: name.to_owned(),
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 schemars::JsonSchema;
426 use serde::Deserialize;
427
428 actions!(
429 open_gpui,
430 [
431 #[action(deprecated_aliases = ["zed::NoAction"])]
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 /// `["open_gpui::Unbind", "editor::NewLine"]`
444 #[derive(Clone, Debug, PartialEq, Deserialize, JsonSchema, open_gpui::Action)]
445 #[action(namespace = open_gpui, deprecated_aliases = ["zed::Unbind"])]
446 pub struct Unbind(pub open_gpui::SharedString);
447
448 /// Returns whether or not this action represents a removed key binding.
449 pub fn is_no_action(action: &dyn open_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 open_gpui::Action) -> bool {
455 action.as_any().is::<Unbind>()
456 }
457}