use std::sync::Arc;
use bevy_ecs::resource::Resource;
use bevy_platform::collections::HashMap;
use bevy_reflect::TypeRegistration;
use parking_lot::RwLock;
use crate::{
AnyTypeRegistration, AnyTypeRegistrationV, ScriptBundleRegistration,
ScriptComponentRegistration, ScriptResourceRegistration, ScriptTypeRegistration,
WorldExtensions, error::InteropError, function::from::V,
};
use bevy_mod_scripting_world::WorldGuard;
#[derive(Clone)]
pub enum CatalogueRegistration {
Type(ScriptTypeRegistration),
Component(ScriptComponentRegistration),
Resource(ScriptResourceRegistration),
Bundle(ScriptBundleRegistration),
}
impl CatalogueRegistration {
fn from_any(any: AnyTypeRegistration) -> Self {
match any.into_left() {
Ok(r) => Self::Type(r),
Err(other) => match other.into_left() {
Ok(c) => Self::Component(c),
Err(other) => match other.into_left() {
Ok(r) => Self::Resource(r),
Err(b) => Self::Bundle(b),
},
},
}
}
pub fn to_script(&self) -> AnyTypeRegistrationV {
use crate::function::from::Union;
match self.clone() {
Self::Type(r) => Union::new_left(V(r)),
Self::Component(c) => Union::new_right(Union::new_left(V(c))),
Self::Resource(r) => Union::new_right(Union::new_right(Union::new_left(V(r)))),
Self::Bundle(b) => Union::new_right(Union::new_right(Union::new_right(V(b)))),
}
}
}
#[derive(Clone)]
pub struct CatalogueEntry {
pub short_name: Arc<str>,
pub namespace: Arc<str>,
pub registration: CatalogueRegistration,
}
#[derive(Clone, Default)]
pub struct ScriptTypeCatalogue {
entries: Vec<CatalogueEntry>,
by_short_name: HashMap<Arc<str>, usize>,
by_namespace: HashMap<Arc<str>, Vec<usize>>,
}
impl ScriptTypeCatalogue {
pub fn iter(&self) -> impl Iterator<Item = &CatalogueEntry> {
self.entries.iter()
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn get_by_short_name(&self, name: &str) -> Option<&CatalogueEntry> {
self.by_short_name.get(name).map(|i| &self.entries[*i])
}
pub fn namespaces(&self) -> impl Iterator<Item = &str> {
self.by_namespace.keys().map(|n| n.as_ref())
}
pub fn iter_namespace<'a>(
&'a self,
namespace: &str,
) -> impl Iterator<Item = &'a CatalogueEntry> + 'a {
self.by_namespace
.get(namespace)
.into_iter()
.flatten()
.map(|i| &self.entries[*i])
}
pub fn namespace_view(&self, namespace: &str) -> Option<HashMap<String, AnyTypeRegistrationV>> {
let indices = self.by_namespace.get(namespace)?;
let mut view = HashMap::with_capacity(indices.len());
for entry in indices.iter().map(|i| &self.entries[*i]) {
view.entry(entry.short_name.to_string())
.or_insert_with(|| entry.registration.to_script());
}
Some(view)
}
pub fn similar_namespaces(&self, requested: &str) -> Vec<String> {
self.similar_namespaces_with(requested, &[])
}
pub fn similar_namespaces_with(&self, requested: &str, extra: &[String]) -> Vec<String> {
let all = self
.namespaces()
.chain(extra.iter().map(String::as_str))
.collect::<std::collections::BTreeSet<_>>();
let mut scored = all
.into_iter()
.filter(|n| !n.is_empty())
.filter_map(|n| {
let distance = edit_distance(requested, n);
let related =
!requested.is_empty() && (n.contains(requested) || requested.contains(n));
(distance <= 3.max(requested.len() / 3) || related).then_some((distance, n))
})
.collect::<Vec<_>>();
scored.sort();
scored
.into_iter()
.take(3)
.map(|(_, n)| n.to_owned())
.collect()
}
pub fn insert(&mut self, entry: CatalogueEntry) -> bool {
let index = self.entries.len();
self.by_namespace
.entry(entry.namespace.clone())
.or_default()
.push(index);
let fresh = match self.by_short_name.entry(entry.short_name.clone()) {
bevy_platform::collections::hash_map::Entry::Vacant(v) => {
v.insert(index);
true
}
bevy_platform::collections::hash_map::Entry::Occupied(_) => false,
};
self.entries.push(entry);
fresh
}
pub fn build(
guard: WorldGuard,
filter: fn(&TypeRegistration) -> bool,
) -> Result<Self, InteropError> {
let type_registry = guard.type_registry();
let type_registry = type_registry.read();
let mut catalogue = Self::default();
for registration in type_registry.iter().filter(|r| filter(r)) {
let short_name: Arc<str> = registration
.type_info()
.type_path_table()
.short_path()
.into();
let registration = ScriptTypeRegistration::new(Arc::new(registration.clone()));
let namespace: Arc<str> = registration.namespace().into();
let registration = guard.clone().get_type_registration(registration)?;
catalogue.insert(CatalogueEntry {
short_name,
namespace,
registration: CatalogueRegistration::from_any(registration),
});
}
drop(type_registry);
let script_registry = guard.component_registry();
let script_registry = script_registry.read();
for info in script_registry.iter_components() {
catalogue.insert(CatalogueEntry {
short_name: info.name.as_str().into(),
namespace: info.namespace.as_str().into(),
registration: CatalogueRegistration::Component(info.registration.clone()),
});
}
Ok(catalogue)
}
}
struct Cached {
stamp: (usize, usize, u64),
catalogue: Arc<ScriptTypeCatalogue>,
}
#[derive(Resource, Clone)]
pub struct AppScriptTypeCatalogue {
filter: fn(&TypeRegistration) -> bool,
cached: Arc<RwLock<Option<Cached>>>,
}
impl Default for AppScriptTypeCatalogue {
fn default() -> Self {
Self::new(|_| true)
}
}
impl AppScriptTypeCatalogue {
pub fn new(filter: fn(&TypeRegistration) -> bool) -> Self {
Self {
filter,
cached: Default::default(),
}
}
fn stamp(guard: &WorldGuard) -> Result<(usize, usize, u64), InteropError> {
let types = guard.type_registry().read().iter().count();
let components = guard.as_unsafe_world_cell()?.components().len();
let script_generation = guard.component_registry().read().generation();
Ok((types, components, script_generation))
}
pub fn get(&self, guard: WorldGuard) -> Result<Arc<ScriptTypeCatalogue>, InteropError> {
let stamp = Self::stamp(&guard)?;
if let Some(cached) = self.cached.read().as_ref()
&& cached.stamp == stamp
{
return Ok(cached.catalogue.clone());
}
let catalogue = Arc::new(ScriptTypeCatalogue::build(guard, self.filter)?);
*self.cached.write() = Some(Cached {
stamp,
catalogue: catalogue.clone(),
});
Ok(catalogue)
}
}
fn edit_distance(a: &str, b: &str) -> usize {
let b: Vec<char> = b.chars().collect();
let mut previous: Vec<usize> = (0..=b.len()).collect();
for (i, ca) in a.chars().enumerate() {
let mut current = vec![i + 1];
for (j, cb) in b.iter().enumerate() {
let substitution = previous[j] + usize::from(ca != *cb);
current.push(substitution.min(previous[j + 1] + 1).min(current[j] + 1));
}
previous = current;
}
previous[b.len()]
}