orbtk_theming/config/
theme_config.rsuse std::collections::HashMap;
use ron::{de::from_str, Value};
use serde_derive::{Deserialize, Serialize};
use crate::{config::StyleConfig, Selector};
pub static BASE_STYLE: &str = "base";
pub static RESOURCE_KEY: &str = "$";
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
#[serde(rename = "Theme")]
pub struct ThemeConfig {
#[serde(default)]
pub styles: HashMap<String, StyleConfig>,
#[serde(default)]
pub resources: HashMap<String, Value>,
}
impl<'a> ThemeConfig {
pub fn extend(mut self, other: ThemeConfig) -> Self {
let mut other = other;
for style in other.styles.drain() {
self.styles.insert(style.0, style.1);
}
for resource in other.resources.drain() {
self.resources.insert(resource.0, resource.1);
}
self
}
pub fn property(&'a self, property: &str, selector: &Selector) -> Option<Value> {
if let Some(style) = &selector.style {
if let Some(style) = self.styles.get(style) {
return self.get_property(property, style, selector);
}
}
if let Some(base_style) = self.styles.get(BASE_STYLE) {
return self.get_property(property, base_style, selector);
}
None
}
fn get_property(
&'a self,
property: &str,
style: &'a StyleConfig,
selector: &Selector,
) -> Option<Value> {
if let Some(state) = &selector.state {
if let Some(properties) = style.states.get(state) {
return self.get_property_value(property, properties);
}
if style.base.is_empty() {
return None;
}
if let Some(base_style) = self.styles.get(&style.base) {
if let Some(properties) = base_style.states.get(state) {
return self.get_property_value(property, properties);
}
}
}
let value = self.get_property_value(property, &style.properties);
if value.is_some() {
return value;
}
if style.base.is_empty() {
return None;
}
if let Some(base_style) = self.styles.get(&style.base) {
return self.get_property(property, base_style, selector);
}
None
}
fn get_property_value(
&self,
property: &str,
properties: &'a HashMap<String, Value>,
) -> Option<Value> {
let property = properties.get(property)?;
if let Ok(key) = property.clone().into_rust::<String>() {
if key.starts_with(RESOURCE_KEY) {
return Some(self.resources.get(&key.replace(RESOURCE_KEY, ""))?.clone());
}
}
Some(property.clone())
}
}
impl From<&str> for ThemeConfig {
fn from(s: &str) -> Self {
from_str(s).unwrap()
}
}