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)
}
}
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
}
}
}