use crate::activity::Activity;
use crate::component::ComponentId;
use crate::error::Result;
use crate::prop::PropValue;
use crate::ui::Ui;
pub trait Handle: Copy {
fn id(&self) -> ComponentId;
fn try_get(&self, ui: &Ui, prop: &str) -> Result<PropValue> {
ui.get_prop(self.id(), prop)
}
fn try_set(&self, ui: &mut Ui, prop: &str, value: impl Into<PropValue>) -> Result<()> {
ui.set_prop(self.id(), prop, value)
}
fn try_invoke(&self, ui: &mut Ui, method: &str, args: &[PropValue]) -> std::result::Result<PropValue, String> {
ui.invoke(self.id(), method, args)
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct ColorRef(PropValue);
impl ColorRef {
pub fn token(name: &str) -> Self {
Self(PropValue::String(name.trim().to_string()))
}
}
impl From<crate::Color> for ColorRef {
fn from(c: crate::Color) -> Self {
Self(PropValue::Color(c))
}
}
impl From<ColorRef> for PropValue {
fn from(c: ColorRef) -> Self {
c.0
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Ref(pub Option<ComponentId>);
impl Ref {
pub const NONE: Ref = Ref(None);
}
impl<H: Handle> From<H> for Ref {
fn from(h: H) -> Self {
Ref(Some(h.id()))
}
}
impl From<ComponentId> for Ref {
fn from(id: ComponentId) -> Self {
Ref(Some(id))
}
}
impl From<Option<ComponentId>> for Ref {
fn from(id: Option<ComponentId>) -> Self {
Ref(id)
}
}
impl From<Ref> for PropValue {
fn from(r: Ref) -> Self {
PropValue::Component(r.0)
}
}
pub fn read_enum<E: crate::prop::PropEnum>(ui: &Ui, id: ComponentId, prop: &str) -> E {
read(ui, id, prop).and_then(|v| v.to_enum::<E>().ok()).or_else(|| E::from_index(0)).expect("enum sem valores")
}
pub fn read_set<E: crate::prop::PropEnum>(ui: &Ui, id: ComponentId, prop: &str) -> Vec<E> {
let names: Vec<String> = match read(ui, id, prop) {
Some(PropValue::Set(names)) => names,
Some(PropValue::String(s) | PropValue::Enum(s)) => s.split(',').map(|p| p.trim().to_string()).filter(|p| !p.is_empty()).collect(),
_ => Vec::new(),
};
names.iter().filter_map(|n| E::from_name(n)).collect()
}
pub fn set_value<E: crate::prop::PropEnum>(values: &[E]) -> PropValue {
PropValue::Set(values.iter().map(|v| v.name().to_string()).collect())
}
fn read_text(ui: &Ui, id: ComponentId, prop: &str) -> String {
read(ui, id, prop).and_then(|v| v.to_str().ok().map(str::to_string)).unwrap_or_default()
}
pub fn read_date(ui: &Ui, id: ComponentId, prop: &str) -> Option<crate::Date> {
crate::Date::parse_iso(&read_text(ui, id, prop))
}
pub fn read_time(ui: &Ui, id: ComponentId, prop: &str) -> Option<crate::Time> {
crate::Time::parse_iso(&read_text(ui, id, prop))
}
pub fn read_datetime(ui: &Ui, id: ComponentId, prop: &str) -> Option<crate::DateTime> {
crate::DateTime::parse_iso(&read_text(ui, id, prop))
}
pub fn date_value(value: Option<crate::Date>) -> PropValue {
PropValue::String(value.map(|d| d.to_string()).unwrap_or_default())
}
pub fn time_value(value: Option<crate::Time>) -> PropValue {
PropValue::String(value.map(time_text).unwrap_or_default())
}
pub fn datetime_value(value: Option<crate::DateTime>) -> PropValue {
PropValue::String(value.map(|d| format!("{}T{}", d.date, time_text(d.time))).unwrap_or_default())
}
fn time_text(t: crate::Time) -> String {
if t.second() == 0 { format!("{:02}:{:02}", t.hour(), t.minute()) } else { format!("{:02}:{:02}:{:02}", t.hour(), t.minute(), t.second()) }
}
fn items(text: &str) -> impl Iterator<Item = &str> {
text.split(';').map(str::trim).filter(|s| !s.is_empty())
}
pub fn read_list(ui: &Ui, id: ComponentId, prop: &str) -> Vec<String> {
items(&read_text(ui, id, prop)).map(str::to_string).collect()
}
pub fn read_numbers(ui: &Ui, id: ComponentId, prop: &str) -> Vec<f64> {
items(&read_text(ui, id, prop)).filter_map(|s| s.parse().ok()).collect()
}
pub fn read_colors(ui: &Ui, id: ComponentId, prop: &str) -> Vec<crate::Color> {
items(&read_text(ui, id, prop)).filter_map(crate::Color::from_hex).collect()
}
pub fn list_value<S: AsRef<str>>(values: &[S]) -> PropValue {
PropValue::String(values.iter().map(|s| s.as_ref()).collect::<Vec<_>>().join(";"))
}
pub fn numbers_value(values: &[f64]) -> PropValue {
PropValue::String(values.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(";"))
}
pub fn colors_value(values: &[crate::Color]) -> PropValue {
PropValue::String(values.iter().map(|c| c.to_hex()).collect::<Vec<_>>().join(";"))
}
pub fn read_shadow(ui: &Ui, id: ComponentId, prop: &str) -> Option<crate::Shadow> {
crate::Shadow::parse(&read_text(ui, id, prop))
}
pub fn shadow_value(value: Option<crate::Shadow>) -> PropValue {
PropValue::String(value.map(|s| s.to_spec()).unwrap_or_default())
}
pub fn read_easing(ui: &Ui, id: ComponentId, prop: &str) -> crate::Easing {
crate::Easing::parse(&read_text(ui, id, prop)).unwrap_or_default()
}
pub fn easing_value(value: crate::Easing) -> PropValue {
PropValue::String(value.to_spec())
}
pub fn read_points(ui: &Ui, id: ComponentId, prop: &str) -> Vec<crate::PointF> {
read_text(ui, id, prop)
.split_whitespace()
.filter_map(|p| {
let (x, y) = p.split_once(',')?;
Some(crate::PointF::new(x.trim().parse().ok()?, y.trim().parse().ok()?))
})
.collect()
}
pub fn points_value(values: &[crate::PointF]) -> PropValue {
PropValue::String(values.iter().map(|p| format!("{},{}", p.x, p.y)).collect::<Vec<_>>().join(" "))
}
pub fn read_ref(ui: &Ui, id: ComponentId, prop: &str) -> Option<ComponentId> {
read(ui, id, prop).and_then(|v| v.to_component().ok().flatten())
}
pub fn read(ui: &Ui, id: ComponentId, prop: &str) -> Option<PropValue> {
match ui.get_prop(id, prop) {
Ok(v) => Some(v),
Err(e) => {
if cfg!(debug_assertions) {
crate::stderr_line!("aylis: ler {}.{prop}: {e}", ui.path_of(id));
}
None
}
}
}
pub fn write(ui: &mut Ui, id: ComponentId, prop: &str, value: impl Into<PropValue>) {
if let Err(e) = ui.set_prop(id, prop, value) {
failed(ui, id, &format!("gravar {prop}"), &e.to_string());
}
}
pub fn call(ui: &mut Ui, id: ComponentId, method: &str, args: &[PropValue]) -> Option<PropValue> {
match ui.invoke(id, method, args) {
Ok(v) => Some(v),
Err(e) => {
failed(ui, id, &format!("chamar {method}"), &e.to_string());
None
}
}
}
pub fn try_call(ui: &mut Ui, id: ComponentId, method: &str, args: &[PropValue]) -> std::result::Result<PropValue, String> {
ui.invoke(id, method, args).inspect_err(|e| failed(ui, id, &format!("chamar {method}"), e))
}
fn failed(ui: &mut Ui, id: ComponentId, what: &str, error: &str) {
let message = format!("{what} em {}: {error}", ui.path_of(id));
if cfg!(debug_assertions) {
crate::stderr_line!("aylis: {message}");
}
ui.report(&Activity::Error { message: &message });
}
pub fn text(ui: &Ui, value: Option<PropValue>) -> String {
match value {
Some(PropValue::Color(c)) => c.to_hex(),
Some(PropValue::Component(Some(id))) => ui.path_of(id),
Some(PropValue::Bounds(b)) => format!("{}, {}, {}, {}", b.left, b.top, b.right, b.bottom),
Some(PropValue::Set(names)) => names.join(","),
Some(v) => v.to_str().map(str::to_string).unwrap_or_default(),
None => String::new(),
}
}
pub fn resolve(ui: &Ui, root: ComponentId, name: &str, class: &str, problems: &mut Vec<String>) -> ComponentId {
match ui.find_in(root, name) {
Some(id) => {
let actual = ui.class_name(id).unwrap_or_default();
if actual != class {
problems.push(format!("{name} é {actual} no form e {class} no código"));
}
id
}
None => {
problems.push(format!("falta o componente {name} ({class})"));
root
}
}
}