1use crate::activity::Activity;
8use crate::component::ComponentId;
9use crate::error::Result;
10use crate::prop::PropValue;
11use crate::ui::Ui;
12
13pub trait Handle: Copy {
15 fn id(&self) -> ComponentId;
16
17 fn try_get(&self, ui: &Ui, prop: &str) -> Result<PropValue> {
19 ui.get_prop(self.id(), prop)
20 }
21
22 fn try_set(&self, ui: &mut Ui, prop: &str, value: impl Into<PropValue>) -> Result<()> {
24 ui.set_prop(self.id(), prop, value)
25 }
26
27 fn try_invoke(&self, ui: &mut Ui, method: &str, args: &[PropValue]) -> std::result::Result<PropValue, String> {
29 ui.invoke(self.id(), method, args)
30 }
31}
32
33#[derive(Clone, Debug, PartialEq)]
36pub struct ColorRef(PropValue);
37
38impl ColorRef {
39 pub fn token(name: &str) -> Self {
41 Self(PropValue::String(name.trim().to_string()))
42 }
43}
44
45impl From<crate::Color> for ColorRef {
46 fn from(c: crate::Color) -> Self {
47 Self(PropValue::Color(c))
48 }
49}
50
51impl From<ColorRef> for PropValue {
52 fn from(c: ColorRef) -> Self {
53 c.0
54 }
55}
56
57#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
60pub struct Ref(pub Option<ComponentId>);
61
62impl Ref {
63 pub const NONE: Ref = Ref(None);
64}
65
66impl<H: Handle> From<H> for Ref {
67 fn from(h: H) -> Self {
68 Ref(Some(h.id()))
69 }
70}
71
72impl From<ComponentId> for Ref {
73 fn from(id: ComponentId) -> Self {
74 Ref(Some(id))
75 }
76}
77
78impl From<Option<ComponentId>> for Ref {
79 fn from(id: Option<ComponentId>) -> Self {
80 Ref(id)
81 }
82}
83
84impl From<Ref> for PropValue {
85 fn from(r: Ref) -> Self {
86 PropValue::Component(r.0)
87 }
88}
89
90pub fn read_enum<E: crate::prop::PropEnum>(ui: &Ui, id: ComponentId, prop: &str) -> E {
92 read(ui, id, prop).and_then(|v| v.to_enum::<E>().ok()).or_else(|| E::from_index(0)).expect("enum sem valores")
93}
94
95pub fn read_set<E: crate::prop::PropEnum>(ui: &Ui, id: ComponentId, prop: &str) -> Vec<E> {
97 let names: Vec<String> = match read(ui, id, prop) {
98 Some(PropValue::Set(names)) => names,
99 Some(PropValue::String(s) | PropValue::Enum(s)) => s.split(',').map(|p| p.trim().to_string()).filter(|p| !p.is_empty()).collect(),
100 _ => Vec::new(),
101 };
102 names.iter().filter_map(|n| E::from_name(n)).collect()
103}
104
105pub fn set_value<E: crate::prop::PropEnum>(values: &[E]) -> PropValue {
107 PropValue::Set(values.iter().map(|v| v.name().to_string()).collect())
108}
109
110fn read_text(ui: &Ui, id: ComponentId, prop: &str) -> String {
111 read(ui, id, prop).and_then(|v| v.to_str().ok().map(str::to_string)).unwrap_or_default()
112}
113
114pub fn read_date(ui: &Ui, id: ComponentId, prop: &str) -> Option<crate::Date> {
116 crate::Date::parse_iso(&read_text(ui, id, prop))
117}
118
119pub fn read_time(ui: &Ui, id: ComponentId, prop: &str) -> Option<crate::Time> {
121 crate::Time::parse_iso(&read_text(ui, id, prop))
122}
123
124pub fn read_datetime(ui: &Ui, id: ComponentId, prop: &str) -> Option<crate::DateTime> {
126 crate::DateTime::parse_iso(&read_text(ui, id, prop))
127}
128
129pub fn date_value(value: Option<crate::Date>) -> PropValue {
131 PropValue::String(value.map(|d| d.to_string()).unwrap_or_default())
132}
133
134pub fn time_value(value: Option<crate::Time>) -> PropValue {
136 PropValue::String(value.map(time_text).unwrap_or_default())
137}
138
139pub fn datetime_value(value: Option<crate::DateTime>) -> PropValue {
141 PropValue::String(value.map(|d| format!("{}T{}", d.date, time_text(d.time))).unwrap_or_default())
142}
143
144fn time_text(t: crate::Time) -> String {
145 if t.second() == 0 { format!("{:02}:{:02}", t.hour(), t.minute()) } else { format!("{:02}:{:02}:{:02}", t.hour(), t.minute(), t.second()) }
146}
147
148fn items(text: &str) -> impl Iterator<Item = &str> {
150 text.split(';').map(str::trim).filter(|s| !s.is_empty())
151}
152
153pub fn read_list(ui: &Ui, id: ComponentId, prop: &str) -> Vec<String> {
155 items(&read_text(ui, id, prop)).map(str::to_string).collect()
156}
157
158pub fn read_numbers(ui: &Ui, id: ComponentId, prop: &str) -> Vec<f64> {
160 items(&read_text(ui, id, prop)).filter_map(|s| s.parse().ok()).collect()
161}
162
163pub fn read_colors(ui: &Ui, id: ComponentId, prop: &str) -> Vec<crate::Color> {
165 items(&read_text(ui, id, prop)).filter_map(crate::Color::from_hex).collect()
166}
167
168pub fn list_value<S: AsRef<str>>(values: &[S]) -> PropValue {
170 PropValue::String(values.iter().map(|s| s.as_ref()).collect::<Vec<_>>().join(";"))
171}
172
173pub fn numbers_value(values: &[f64]) -> PropValue {
175 PropValue::String(values.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(";"))
176}
177
178pub fn colors_value(values: &[crate::Color]) -> PropValue {
180 PropValue::String(values.iter().map(|c| c.to_hex()).collect::<Vec<_>>().join(";"))
181}
182
183pub fn read_shadow(ui: &Ui, id: ComponentId, prop: &str) -> Option<crate::Shadow> {
185 crate::Shadow::parse(&read_text(ui, id, prop))
186}
187
188pub fn shadow_value(value: Option<crate::Shadow>) -> PropValue {
190 PropValue::String(value.map(|s| s.to_spec()).unwrap_or_default())
191}
192
193pub fn read_easing(ui: &Ui, id: ComponentId, prop: &str) -> crate::Easing {
195 crate::Easing::parse(&read_text(ui, id, prop)).unwrap_or_default()
196}
197
198pub fn easing_value(value: crate::Easing) -> PropValue {
200 PropValue::String(value.to_spec())
201}
202
203pub fn read_points(ui: &Ui, id: ComponentId, prop: &str) -> Vec<crate::PointF> {
205 read_text(ui, id, prop)
206 .split_whitespace()
207 .filter_map(|p| {
208 let (x, y) = p.split_once(',')?;
209 Some(crate::PointF::new(x.trim().parse().ok()?, y.trim().parse().ok()?))
210 })
211 .collect()
212}
213
214pub fn points_value(values: &[crate::PointF]) -> PropValue {
216 PropValue::String(values.iter().map(|p| format!("{},{}", p.x, p.y)).collect::<Vec<_>>().join(" "))
217}
218
219pub fn read_ref(ui: &Ui, id: ComponentId, prop: &str) -> Option<ComponentId> {
221 read(ui, id, prop).and_then(|v| v.to_component().ok().flatten())
222}
223
224pub fn read(ui: &Ui, id: ComponentId, prop: &str) -> Option<PropValue> {
227 match ui.get_prop(id, prop) {
228 Ok(v) => Some(v),
229 Err(e) => {
230 if cfg!(debug_assertions) {
231 crate::stderr_line!("aylis: ler {}.{prop}: {e}", ui.path_of(id));
232 }
233 None
234 }
235 }
236}
237
238pub fn write(ui: &mut Ui, id: ComponentId, prop: &str, value: impl Into<PropValue>) {
240 if let Err(e) = ui.set_prop(id, prop, value) {
241 failed(ui, id, &format!("gravar {prop}"), &e.to_string());
242 }
243}
244
245pub fn call(ui: &mut Ui, id: ComponentId, method: &str, args: &[PropValue]) -> Option<PropValue> {
247 match ui.invoke(id, method, args) {
248 Ok(v) => Some(v),
249 Err(e) => {
250 failed(ui, id, &format!("chamar {method}"), &e.to_string());
251 None
252 }
253 }
254}
255
256pub fn try_call(ui: &mut Ui, id: ComponentId, method: &str, args: &[PropValue]) -> std::result::Result<PropValue, String> {
260 ui.invoke(id, method, args).inspect_err(|e| failed(ui, id, &format!("chamar {method}"), e))
261}
262
263fn failed(ui: &mut Ui, id: ComponentId, what: &str, error: &str) {
264 let message = format!("{what} em {}: {error}", ui.path_of(id));
265 if cfg!(debug_assertions) {
266 crate::stderr_line!("aylis: {message}");
267 }
268 ui.report(&Activity::Error { message: &message });
269}
270
271pub fn text(ui: &Ui, value: Option<PropValue>) -> String {
273 match value {
274 Some(PropValue::Color(c)) => c.to_hex(),
275 Some(PropValue::Component(Some(id))) => ui.path_of(id),
276 Some(PropValue::Bounds(b)) => format!("{}, {}, {}, {}", b.left, b.top, b.right, b.bottom),
278 Some(PropValue::Set(names)) => names.join(","),
279 Some(v) => v.to_str().map(str::to_string).unwrap_or_default(),
280 None => String::new(),
281 }
282}
283
284pub fn resolve(ui: &Ui, root: ComponentId, name: &str, class: &str, problems: &mut Vec<String>) -> ComponentId {
287 match ui.find_in(root, name) {
288 Some(id) => {
289 let actual = ui.class_name(id).unwrap_or_default();
290 if actual != class {
291 problems.push(format!("{name} é {actual} no form e {class} no código"));
292 }
293 id
294 }
295 None => {
296 problems.push(format!("falta o componente {name} ({class})"));
297 root
298 }
299 }
300}