1use crate::SharedString;
2use anyhow::{anyhow, Context, Result};
3use collections::HashMap;
4use lazy_static::lazy_static;
5use parking_lot::{MappedRwLockReadGuard, RwLock, RwLockReadGuard};
6use serde::Deserialize;
7use std::any::{type_name, Any, TypeId};
8
9/// Actions are used to implement keyboard-driven UI.
10/// When you declare an action, you can bind keys to the action in the keymap and
11/// listeners for that action in the element tree.
12///
13/// To declare a list of simple actions, you can use the actions! macro, which defines a simple unit struct
14/// action for each listed action name.
15/// ```rust
16/// actions!(MoveUp, MoveDown, MoveLeft, MoveRight, Newline);
17/// ```
18/// More complex data types can also be actions. If you annotate your type with the `#[action]` proc macro,
19/// it will automatically
20/// ```
21/// #[action]
22/// pub struct SelectNext {
23/// pub replace_newest: bool,
24/// }
25///
26/// Any type A that satisfies the following bounds is automatically an action:
27///
28/// ```
29/// A: for<'a> Deserialize<'a> + PartialEq + Clone + Default + std::fmt::Debug + 'static,
30/// ```
31///
32/// The `#[action]` annotation will derive these implementations for your struct automatically. If you
33/// want to control them manually, you can use the lower-level `#[register_action]` macro, which only
34/// generates the code needed to register your action before `main`. Then you'll need to implement all
35/// the traits manually.
36///
37/// ```
38/// #[gpui::register_action]
39/// #[derive(gpui::serde::Deserialize, std::cmp::PartialEq, std::clone::Clone, std::fmt::Debug)]
40/// pub struct Paste {
41/// pub content: SharedString,
42/// }
43///
44/// impl std::default::Default for Paste {
45/// fn default() -> Self {
46/// Self {
47/// content: SharedString::from("🍝"),
48/// }
49/// }
50/// }
51/// ```
52pub trait Action: std::fmt::Debug + 'static {
53 fn qualified_name() -> SharedString
54 where
55 Self: Sized;
56 fn build(value: Option<serde_json::Value>) -> Result<Box<dyn Action>>
57 where
58 Self: Sized;
59
60 fn partial_eq(&self, action: &dyn Action) -> bool;
61 fn boxed_clone(&self) -> Box<dyn Action>;
62 fn as_any(&self) -> &dyn Any;
63}
64
65// Types become actions by satisfying a list of trait bounds.
66impl<A> Action for A
67where
68 A: for<'a> Deserialize<'a> + PartialEq + Clone + Default + std::fmt::Debug + 'static,
69{
70 fn qualified_name() -> SharedString {
71 // todo!() remove the 2 replacement when migration is done
72 type_name::<A>().replace("2::", "::").into()
73 }
74
75 fn build(params: Option<serde_json::Value>) -> Result<Box<dyn Action>>
76 where
77 Self: Sized,
78 {
79 let action = if let Some(params) = params {
80 serde_json::from_value(params).context("failed to deserialize action")?
81 } else {
82 Self::default()
83 };
84 Ok(Box::new(action))
85 }
86
87 fn partial_eq(&self, action: &dyn Action) -> bool {
88 action
89 .as_any()
90 .downcast_ref::<Self>()
91 .map_or(false, |a| self == a)
92 }
93
94 fn boxed_clone(&self) -> Box<dyn Action> {
95 Box::new(self.clone())
96 }
97
98 fn as_any(&self) -> &dyn Any {
99 self
100 }
101}
102
103impl dyn Action {
104 pub fn type_id(&self) -> TypeId {
105 self.as_any().type_id()
106 }
107
108 pub fn name(&self) -> SharedString {
109 ACTION_REGISTRY
110 .read()
111 .names_by_type_id
112 .get(&self.type_id())
113 .expect("type is not a registered action")
114 .clone()
115 }
116}
117
118type ActionBuilder = fn(json: Option<serde_json::Value>) -> anyhow::Result<Box<dyn Action>>;
119
120lazy_static! {
121 static ref ACTION_REGISTRY: RwLock<ActionRegistry> = RwLock::default();
122}
123
124#[derive(Default)]
125struct ActionRegistry {
126 builders_by_name: HashMap<SharedString, ActionBuilder>,
127 names_by_type_id: HashMap<TypeId, SharedString>,
128 all_names: Vec<SharedString>, // So we can return a static slice.
129}
130
131/// Register an action type to allow it to be referenced in keymaps.
132pub fn register_action<A: Action>() {
133 let name = A::qualified_name();
134 let mut lock = ACTION_REGISTRY.write();
135 lock.builders_by_name.insert(name.clone(), A::build);
136 lock.names_by_type_id
137 .insert(TypeId::of::<A>(), name.clone());
138 lock.all_names.push(name);
139}
140
141/// Construct an action based on its name and optional JSON parameters sourced from the keymap.
142pub fn build_action_from_type(type_id: &TypeId) -> Result<Box<dyn Action>> {
143 let lock = ACTION_REGISTRY.read();
144 let name = lock
145 .names_by_type_id
146 .get(type_id)
147 .ok_or_else(|| anyhow!("no action type registered for {:?}", type_id))?
148 .clone();
149 drop(lock);
150
151 build_action(&name, None)
152}
153
154/// Construct an action based on its name and optional JSON parameters sourced from the keymap.
155pub fn build_action(name: &str, params: Option<serde_json::Value>) -> Result<Box<dyn Action>> {
156 let lock = ACTION_REGISTRY.read();
157
158 let build_action = lock
159 .builders_by_name
160 .get(name)
161 .ok_or_else(|| anyhow!("no action type registered for {}", name))?;
162 (build_action)(params)
163}
164
165pub fn all_action_names() -> MappedRwLockReadGuard<'static, [SharedString]> {
166 let lock = ACTION_REGISTRY.read();
167 RwLockReadGuard::map(lock, |registry: &ActionRegistry| {
168 registry.all_names.as_slice()
169 })
170}
171
172/// Defines unit structs that can be used as actions.
173/// To use more complex data types as actions, annotate your type with the #[action] macro.
174#[macro_export]
175macro_rules! actions {
176 () => {};
177
178 ( $name:ident ) => {
179 #[gpui::action]
180 pub struct $name;
181 };
182
183 ( $name:ident, $($rest:tt)* ) => {
184 actions!($name);
185 actions!($($rest)*);
186 };
187}