1use 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#[inline]
19#[allow(clippy::panic)] fn invariant<T>(value: Option<T>, message: &str) -> T {
21 match value {
22 Some(value) => value,
23 None => panic!("{message}"),
24 }
25}
26
27#[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
60pub trait Action: Any + Send {
134 fn boxed_clone(&self) -> Box<dyn Action>;
136
137 fn partial_eq(&self, action: &dyn Action) -> bool;
139
140 fn name(&self) -> &'static str;
142
143 fn name_for_type() -> &'static str
145 where
146 Self: Sized;
147
148 fn build(value: serde_json::Value) -> Result<Box<dyn Action>>
151 where
152 Self: Sized;
153
154 fn action_json_schema(_: &mut schemars::SchemaGenerator) -> Option<schemars::Schema>
156 where
157 Self: Sized,
158 {
159 None
160 }
161
162 fn deprecated_aliases() -> &'static [&'static str]
165 where
166 Self: Sized,
167 {
168 &[]
169 }
170
171 fn deprecation_message() -> Option<&'static str>
173 where
174 Self: Sized,
175 {
176 None
177 }
178
179 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 pub fn as_any(&self) -> &dyn Any {
200 self as &dyn Any
201 }
202}
203
204#[derive(Debug)]
206pub enum ActionBuildError {
207 NotFound {
209 name: String,
211 },
212 BuildError {
214 name: String,
216 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>, deprecated_aliases: HashMap<&'static str, &'static str>, deprecation_messages: HashMap<&'static str, &'static str>, documentation: HashMap<&'static str, &'static str>, }
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#[doc(hidden)]
279pub struct MacroActionBuilder(pub fn() -> MacroActionData);
280
281#[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 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 #[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 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 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 self.all_names
394 .iter()
395 .map(|name| {
396 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
429pub 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 NoAction
449 ]
450 );
451
452 #[derive(Clone, Debug, PartialEq, Deserialize, JsonSchema, rgpui::Action)]
459 #[action(namespace = rgpui)]
460 pub struct Unbind(pub rgpui::SharedString);
461
462 pub fn is_no_action(action: &dyn rgpui::Action) -> bool {
464 action.as_any().is::<NoAction>()
465 }
466
467 pub fn is_unbind(action: &dyn rgpui::Action) -> bool {
469 action.as_any().is::<Unbind>()
470 }
471}