Skip to main content

rgpui/
action.rs

1//! Action 系统 —— 定义和管理 UI 动作的注册、分发与序列化机制。
2
3use crate::collections::{HashMap, TypeIdHashMap};
4use anyhow::{Context as _, Result};
5pub use no_action::{NoAction, Unbind, is_no_action, is_unbind};
6pub use rgpui_macros::Action;
7use serde_json::json;
8use std::{
9    any::{Any, TypeId},
10    fmt::Display,
11};
12
13/// 内部不变量:值为 `None` 说明前提被破坏(all_names 与 by_name 不一致等),
14/// 必须立刻暴露。
15///
16/// 统一走这里而不是散落的 `unwrap`:语义与原先一致(同样 panic),但把「这是不变量
17/// 断言」的意图写进调用点,模块级 `deny` 仍能拦住随手写的 unwrap。
18#[inline]
19#[allow(clippy::panic)] // 不变量断言:前提被破坏必须立刻暴露
20fn invariant<T>(value: Option<T>, message: &str) -> T {
21    match value {
22        Some(value) => value,
23        None => panic!("{message}"),
24    }
25}
26
27/// 定义并注册可用作动作的单元结构体。对于更复杂的数据类型,请派生 `Action`。
28///
29/// 例如:
30///
31/// ```
32/// use rgpui::actions;
33/// actions!(editor, [MoveUp, MoveDown, MoveLeft, MoveRight, Newline]);
34/// ```
35///
36/// 这将创建名为 `editor::MoveUp`、`editor::MoveDown` 等的动作。
37///
38/// 命名空间参数 `editor` 也可以省略,但对于 Zed 动作是必需的。
39#[macro_export]
40macro_rules! actions {
41    ($namespace:path, [ $( $(#[$attr:meta])* $name:ident),* $(,)? ]) => {
42        $(
43            #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, rgpui::Action)]
44            #[action(namespace = $namespace)]
45            $(#[$attr])*
46            #[doc = concat!("`", stringify!($name), "` 动作。")]
47            pub struct $name;
48        )*
49    };
50    ([ $( $(#[$attr:meta])* $name:ident),* $(,)? ]) => {
51        $(
52            #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::default::Default, ::std::fmt::Debug, rgpui::Action)]
53            $(#[$attr])*
54            #[doc = concat!("`", stringify!($name), "` 动作。")]
55            pub struct $name;
56        )*
57    };
58}
59
60/// 动作用于实现键盘驱动的 UI。声明动作后,可以在键映射中将按键绑定到该动作,
61/// 并在元素树中为该动作设置监听器。
62///
63/// 要声明一组简单动作,可以使用 actions! 宏,它为给定命名空间中列出的每个动作名称
64/// 定义一个简单的单元结构体动作。
65///
66/// ```
67/// use rgpui::actions;
68/// actions!(editor, [MoveUp, MoveDown, MoveLeft, MoveRight, Newline]);
69/// ```
70///
71/// 注册同名动作会导致 `App` 创建时 panic。
72///
73/// # 派生宏
74///
75/// 更复杂的数据类型也可以是动作,通过为 `Action` 使用派生宏:
76///
77/// ```
78/// use rgpui::Action;
79/// #[derive(Clone, PartialEq, serde::Deserialize, schemars::JsonSchema, Action)]
80/// #[action(namespace = editor)]
81/// pub struct SelectNext {
82///     pub replace_newest: bool,
83/// }
84/// ```
85///
86/// `Action` 的派生宏要求类型实现 `Clone` 和 `PartialEq`。它还要求
87/// `serde::Deserialize` 和 `schemars::JsonSchema`,除非指定了 `#[action(no_json)]`。
88/// 在 Zed 中,这些 trait 实现用于从 JSON 加载键映射。
89///
90/// `#[action(...)]` 中可以指定多个以逗号分隔的参数:
91///
92/// - `namespace = some_namespace` 设置命名空间。在 Zed 中这是必需的。
93///
94/// - `name = "ActionName"` 覆盖动作名称。不能包含 `::`。
95///
96/// - `no_json` 使 `build` 方法始终报错且 `action_json_schema` 返回 `None`,
97///   并允许动作不实现 `serde::Serialize` 和 `schemars::JsonSchema`。
98///
99/// - `no_register` 跳过注册动作。这在实现 `Action` trait 时不支持按名称调用
100///   或 JSON 反序列化时很有用。
101///
102/// - `deprecated_aliases = ["editor::SomeAction"]` 指定动作的已弃用旧名称。
103///   这些动作名称*不应*对应任何已注册的动作。这些旧名称仍可用于引用调用此动作。
104///   在 Zed 中,键映射 JSON 模式将接受这些旧名称并提供警告。
105///
106/// - `deprecated = "关于此动作弃用原因的消息"` 指定弃用消息。
107///   在 Zed 中,键映射 JSON 模式会将其显示为警告。
108///
109/// # 手动实现
110///
111/// 如果想手动控制 action trait 的行为,可以使用更低级的
112/// `#[register_action]` 宏,它只生成在 `main` 之前注册动作所需的代码。
113///
114/// ```
115/// use rgpui::{SharedString, register_action};
116/// #[derive(Clone, PartialEq, Eq, serde::Deserialize, schemars::JsonSchema)]
117/// pub struct Paste {
118///     pub content: SharedString,
119/// }
120///
121/// impl rgpui::Action for Paste {
122///     # fn boxed_clone(&self) -> Box<dyn rgpui::Action> { unimplemented!()}
123///     # fn partial_eq(&self, other: &dyn rgpui::Action) -> bool { unimplemented!() }
124///     # fn name(&self) -> &'static str { "Paste" }
125///     # fn name_for_type() -> &'static str { "Paste" }
126///     # fn build(value: serde_json::Value) -> anyhow::Result<Box<dyn rgpui::Action>> {
127///     #     unimplemented!()
128///     # }
129/// }
130///
131/// register_action!(Paste);
132/// ```
133pub trait Action: Any + Send {
134    /// 将动作克隆到新的 Box 中
135    fn boxed_clone(&self) -> Box<dyn Action>;
136
137    /// 对此动作与另一个动作进行部分相等性检查
138    fn partial_eq(&self, action: &dyn Action) -> bool;
139
140    /// 获取此动作的名称,用于在 UI 中显示
141    fn name(&self) -> &'static str;
142
143    /// 获取此动作类型的名称(静态)
144    fn name_for_type() -> &'static str
145    where
146        Self: Sized;
147
148    /// 从 JSON 值构建此动作。用于从键映射构造动作。
149    /// 对于没有参数的动作,将传递 `{}` 值。
150    fn build(value: serde_json::Value) -> Result<Box<dyn Action>>
151    where
152        Self: Sized;
153
154    /// 动作输入数据的可选 JSON 模式。
155    fn action_json_schema(_: &mut schemars::SchemaGenerator) -> Option<schemars::Schema>
156    where
157        Self: Sized,
158    {
159        None
160    }
161
162    /// 此动作的替代已弃用名称列表。这些名称仍可用于调用该动作。
163    /// 在 Zed 中,键映射 JSON 模式将接受这些旧名称并提供警告。
164    fn deprecated_aliases() -> &'static [&'static str]
165    where
166        Self: Sized,
167    {
168        &[]
169    }
170
171    /// 返回此动作的弃用消息(如果有)。在 Zed 中,键映射 JSON 模式会将其显示为警告。
172    fn deprecation_message() -> Option<&'static str>
173    where
174        Self: Sized,
175    {
176        None
177    }
178
179    /// 此动作的文档(如果有)。使用动作的派生宏时,
180    /// 这将从动作结构体上的文档注释自动生成。
181    fn documentation() -> Option<&'static str>
182    where
183        Self: Sized,
184    {
185        None
186    }
187}
188
189impl std::fmt::Debug for dyn Action {
190    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
191        f.debug_struct("dyn Action")
192            .field("name", &self.name())
193            .finish()
194    }
195}
196
197impl dyn Action {
198    /// 类型擦除 Action 类型。
199    pub fn as_any(&self) -> &dyn Any {
200        self as &dyn Any
201    }
202}
203
204/// `Keystroke::parse` 的错误类型。使用此类型而非 `anyhow::Error`,以便 Zed 可以使用 markdown 来显示它。
205#[derive(Debug)]
206pub enum ActionBuildError {
207    /// 表示未注册具有此名称的动作。
208    NotFound {
209        /// 未找到的动作名称。
210        name: String,
211    },
212    /// 表示构建动作时发生错误,通常是 JSON 反序列化错误。
213    BuildError {
214        /// 正在尝试构建的动作名称。
215        name: String,
216        /// 构建动作时发生的错误。
217        error: anyhow::Error,
218    },
219}
220
221impl std::error::Error for ActionBuildError {
222    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
223        match self {
224            ActionBuildError::NotFound { .. } => None,
225            ActionBuildError::BuildError { error, .. } => error.source(),
226        }
227    }
228}
229
230impl Display for ActionBuildError {
231    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232        match self {
233            ActionBuildError::NotFound { name } => {
234                write!(f, "Didn't find an action named \"{name}\"")
235            }
236            ActionBuildError::BuildError { name, error } => {
237                write!(f, "Error while building action \"{name}\": {error}")
238            }
239        }
240    }
241}
242
243type ActionBuilder = fn(json: serde_json::Value) -> anyhow::Result<Box<dyn Action>>;
244
245pub(crate) struct ActionRegistry {
246    by_name: HashMap<&'static str, ActionData>,
247    names_by_type_id: TypeIdHashMap<&'static str>,
248    all_names: Vec<&'static str>, // So we can return a static slice.
249    deprecated_aliases: HashMap<&'static str, &'static str>, // deprecated name -> preferred name
250    deprecation_messages: HashMap<&'static str, &'static str>, // action name -> deprecation message
251    documentation: HashMap<&'static str, &'static str>, // action name -> documentation
252}
253
254impl Default for ActionRegistry {
255    fn default() -> Self {
256        let mut this = ActionRegistry {
257            by_name: Default::default(),
258            names_by_type_id: Default::default(),
259            documentation: Default::default(),
260            all_names: Default::default(),
261            deprecated_aliases: Default::default(),
262            deprecation_messages: Default::default(),
263        };
264
265        this.load_actions();
266
267        this
268    }
269}
270
271struct ActionData {
272    pub build: ActionBuilder,
273    pub json_schema: fn(&mut schemars::SchemaGenerator) -> Option<schemars::Schema>,
274}
275
276/// 此类型必须是公共的,以便我们的宏可以在其他 crate 中构建它。
277/// 但这是实现细节,不应直接使用。
278#[doc(hidden)]
279pub struct MacroActionBuilder(pub fn() -> MacroActionData);
280
281/// 此类型必须是公共的,以便我们的宏可以在其他 crate 中构建它。
282/// 但这是实现细节,不应直接使用。
283#[doc(hidden)]
284pub struct MacroActionData {
285    pub name: &'static str,
286    pub type_id: TypeId,
287    pub build: ActionBuilder,
288    pub json_schema: fn(&mut schemars::SchemaGenerator) -> Option<schemars::Schema>,
289    pub deprecated_aliases: &'static [&'static str],
290    pub deprecation_message: Option<&'static str>,
291    pub documentation: Option<&'static str>,
292}
293
294inventory::collect!(MacroActionBuilder);
295
296impl ActionRegistry {
297    /// 将所有已注册的动作加载到注册表中。
298    pub(crate) fn load_actions(&mut self) {
299        for builder in inventory::iter::<MacroActionBuilder> {
300            let action = builder.0();
301            self.insert_action(action);
302        }
303    }
304
305    // 契约违规:动作/别名重复注册(宏生成或 #[action(deprecated_aliases)] 写错)
306    #[allow(clippy::panic)]
307    fn insert_action(&mut self, action: MacroActionData) {
308        let name = action.name;
309        if self.by_name.contains_key(name) {
310            panic!(
311                "Action with name `{name}` already registered \
312                (might be registered in `#[action(deprecated_aliases = [...])]`."
313            );
314        }
315        self.by_name.insert(
316            name,
317            ActionData {
318                build: action.build,
319                json_schema: action.json_schema,
320            },
321        );
322        for &alias in action.deprecated_aliases {
323            if self.by_name.contains_key(alias) {
324                panic!(
325                    "Action with name `{alias}` already registered. \
326                    `{alias}` is specified in `#[action(deprecated_aliases = [...])]` for action `{name}`."
327                );
328            }
329            self.by_name.insert(
330                alias,
331                ActionData {
332                    build: action.build,
333                    json_schema: action.json_schema,
334                },
335            );
336            self.deprecated_aliases.insert(alias, name);
337            self.all_names.push(alias);
338        }
339        self.names_by_type_id.insert(action.type_id, name);
340        self.all_names.push(name);
341        if let Some(deprecation_msg) = action.deprecation_message {
342            self.deprecation_messages.insert(name, deprecation_msg);
343        }
344        if let Some(documentation) = action.documentation {
345            self.documentation.insert(name, documentation);
346        }
347    }
348
349    /// 根据动作名称和可选的 JSON 参数(来源于键映射)构建动作。
350    pub fn build_action_type(&self, type_id: &TypeId) -> Result<Box<dyn Action>> {
351        let name = self
352            .names_by_type_id
353            .get(type_id)
354            .with_context(|| format!("no action type registered for {type_id:?}"))?;
355
356        Ok(self.build_action(name, None)?)
357    }
358
359    pub(crate) fn try_resolve_action(&self, type_id: &TypeId) -> Option<&'static str> {
360        self.names_by_type_id.get(type_id).copied()
361    }
362
363    /// 根据动作名称和可选的 JSON 参数(来源于键映射)构建动作。
364    pub fn build_action(
365        &self,
366        name: &str,
367        params: Option<serde_json::Value>,
368    ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
369        let build_action = self
370            .by_name
371            .get(name)
372            .ok_or_else(|| ActionBuildError::NotFound {
373                name: name.to_owned(),
374            })?
375            .build;
376        (build_action)(params.unwrap_or_else(|| json!({}))).map_err(|e| {
377            ActionBuildError::BuildError {
378                name: name.to_owned(),
379                error: e,
380            }
381        })
382    }
383
384    pub fn all_action_names(&self) -> &[&'static str] {
385        self.all_names.as_slice()
386    }
387
388    pub fn action_schemas(
389        &self,
390        generator: &mut schemars::SchemaGenerator,
391    ) -> Vec<(&'static str, Option<schemars::Schema>)> {
392        // Use the order from all_names so that the resulting schema has sensible order.
393        self.all_names
394            .iter()
395            .map(|name| {
396                // all_names 与 by_name 由同一 insert_action 维护,必有一一对应
397                let action_data = invariant(
398                    self.by_name.get(name),
399                    "动作注册表:all_names 中的动作必已注册",
400                );
401                (*name, (action_data.json_schema)(generator))
402            })
403            .collect::<Vec<_>>()
404    }
405
406    pub fn action_schema_by_name(
407        &self,
408        name: &str,
409        generator: &mut schemars::SchemaGenerator,
410    ) -> Option<Option<schemars::Schema>> {
411        self.by_name
412            .get(name)
413            .map(|action_data| (action_data.json_schema)(generator))
414    }
415
416    pub fn deprecated_aliases(&self) -> &HashMap<&'static str, &'static str> {
417        &self.deprecated_aliases
418    }
419
420    pub fn deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
421        &self.deprecation_messages
422    }
423
424    pub fn documentation(&self) -> &HashMap<&'static str, &'static str> {
425        &self.documentation
426    }
427}
428
429/// 生成所有已注册动作的列表。
430/// 适用于将可用动作列表转换为适合静态分析的格式,
431/// 例如验证键映射或生成文档。
432pub fn generate_list_of_all_registered_actions() -> impl Iterator<Item = MacroActionData> {
433    inventory::iter::<MacroActionBuilder>
434        .into_iter()
435        .map(|builder| builder.0())
436}
437
438mod no_action {
439    use crate as rgpui;
440    use schemars::JsonSchema;
441    use serde::Deserialize;
442
443    actions!(
444        rgpui,
445        [
446            /// 具有特殊处理的动作,如果它是最高优先级匹配项,
447            /// 则会解除关联的键绑定。
448            NoAction
449        ]
450    );
451
452    /// 具有特殊处理的动作,当同一按键序列触发指定动作时,
453    /// 它会解除后续绑定,无论该动作的上下文如何。
454    ///
455    /// 在键映射 JSON 中写作:
456    ///
457    /// `["rgpui::Unbind", "editor::NewLine"]`
458    #[derive(Clone, Debug, PartialEq, Deserialize, JsonSchema, rgpui::Action)]
459    #[action(namespace = rgpui)]
460    pub struct Unbind(pub rgpui::SharedString);
461
462    /// 返回此动作是否表示已移除的键绑定。
463    pub fn is_no_action(action: &dyn rgpui::Action) -> bool {
464        action.as_any().is::<NoAction>()
465    }
466
467    /// 返回此动作是否表示解除绑定标记。
468    pub fn is_unbind(action: &dyn rgpui::Action) -> bool {
469        action.as_any().is::<Unbind>()
470    }
471}