action.rs

  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        let name = type_name::<A>();
 72        let mut separator_matches = name.rmatch_indices("::");
 73        separator_matches.next().unwrap();
 74        let name_start_ix = separator_matches.next().map_or(0, |(ix, _)| ix + 2);
 75        // todo!() remove the 2 replacement when migration is done
 76        name[name_start_ix..].replace("2::", "::").into()
 77    }
 78
 79    fn build(params: Option<serde_json::Value>) -> Result<Box<dyn Action>>
 80    where
 81        Self: Sized,
 82    {
 83        let action = if let Some(params) = params {
 84            serde_json::from_value(params).context("failed to deserialize action")?
 85        } else {
 86            Self::default()
 87        };
 88        Ok(Box::new(action))
 89    }
 90
 91    fn partial_eq(&self, action: &dyn Action) -> bool {
 92        action
 93            .as_any()
 94            .downcast_ref::<Self>()
 95            .map_or(false, |a| self == a)
 96    }
 97
 98    fn boxed_clone(&self) -> Box<dyn Action> {
 99        Box::new(self.clone())
100    }
101
102    fn as_any(&self) -> &dyn Any {
103        self
104    }
105}
106
107impl dyn Action {
108    pub fn type_id(&self) -> TypeId {
109        self.as_any().type_id()
110    }
111
112    pub fn name(&self) -> SharedString {
113        ACTION_REGISTRY
114            .read()
115            .names_by_type_id
116            .get(&self.type_id())
117            .expect("type is not a registered action")
118            .clone()
119    }
120}
121
122type ActionBuilder = fn(json: Option<serde_json::Value>) -> anyhow::Result<Box<dyn Action>>;
123
124lazy_static! {
125    static ref ACTION_REGISTRY: RwLock<ActionRegistry> = RwLock::default();
126}
127
128#[derive(Default)]
129struct ActionRegistry {
130    builders_by_name: HashMap<SharedString, ActionBuilder>,
131    names_by_type_id: HashMap<TypeId, SharedString>,
132    all_names: Vec<SharedString>, // So we can return a static slice.
133}
134
135/// Register an action type to allow it to be referenced in keymaps.
136pub fn register_action<A: Action>() {
137    let name = A::qualified_name();
138    let mut lock = ACTION_REGISTRY.write();
139    lock.builders_by_name.insert(name.clone(), A::build);
140    lock.names_by_type_id
141        .insert(TypeId::of::<A>(), name.clone());
142    lock.all_names.push(name);
143}
144
145/// Construct an action based on its name and optional JSON parameters sourced from the keymap.
146pub fn build_action_from_type(type_id: &TypeId) -> Result<Box<dyn Action>> {
147    let lock = ACTION_REGISTRY.read();
148    let name = lock
149        .names_by_type_id
150        .get(type_id)
151        .ok_or_else(|| anyhow!("no action type registered for {:?}", type_id))?
152        .clone();
153    drop(lock);
154
155    build_action(&name, None)
156}
157
158/// Construct an action based on its name and optional JSON parameters sourced from the keymap.
159pub fn build_action(name: &str, params: Option<serde_json::Value>) -> Result<Box<dyn Action>> {
160    let lock = ACTION_REGISTRY.read();
161
162    let build_action = lock
163        .builders_by_name
164        .get(name)
165        .ok_or_else(|| anyhow!("no action type registered for {}", name))?;
166    (build_action)(params)
167}
168
169pub fn all_action_names() -> MappedRwLockReadGuard<'static, [SharedString]> {
170    let lock = ACTION_REGISTRY.read();
171    RwLockReadGuard::map(lock, |registry: &ActionRegistry| {
172        registry.all_names.as_slice()
173    })
174}
175
176/// Defines unit structs that can be used as actions.
177/// To use more complex data types as actions, annotate your type with the #[action] macro.
178#[macro_export]
179macro_rules! actions {
180    () => {};
181
182    ( $name:ident ) => {
183        #[gpui::action]
184        pub struct $name;
185    };
186
187    ( $name:ident, $($rest:tt)* ) => {
188        actions!($name);
189        actions!($($rest)*);
190    };
191}