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
95impl crate::prop::PropEnum for Option<crate::FontWeight> {
99 const NAMES: &'static [&'static str] = &crate::FONT_WEIGHTS;
100
101 fn from_index(index: usize) -> Option<Self> {
102 use crate::FontWeight::*;
103 match index {
104 0 => Some(None),
105 i => [Thin, Light, Normal, Medium, SemiBold, Bold, Black].get(i - 1).map(|w| Some(*w)),
106 }
107 }
108
109 fn index(self) -> usize {
110 self.map_or(0, |w| w as usize + 1)
111 }
112}
113
114pub fn read_set<E: crate::prop::PropEnum>(ui: &Ui, id: ComponentId, prop: &str) -> Vec<E> {
116 let names: Vec<String> = match read(ui, id, prop) {
117 Some(PropValue::Set(names)) => names,
118 Some(PropValue::String(s) | PropValue::Enum(s)) => s.split(',').map(|p| p.trim().to_string()).filter(|p| !p.is_empty()).collect(),
119 _ => Vec::new(),
120 };
121 names.iter().filter_map(|n| E::from_name(n)).collect()
122}
123
124pub fn set_value<E: crate::prop::PropEnum>(values: &[E]) -> PropValue {
126 PropValue::Set(values.iter().map(|v| v.name().to_string()).collect())
127}
128
129fn read_text(ui: &Ui, id: ComponentId, prop: &str) -> String {
130 read(ui, id, prop).and_then(|v| v.to_str().ok().map(str::to_string)).unwrap_or_default()
131}
132
133pub fn read_date(ui: &Ui, id: ComponentId, prop: &str) -> Option<crate::Date> {
135 crate::Date::parse_iso(&read_text(ui, id, prop))
136}
137
138pub fn read_time(ui: &Ui, id: ComponentId, prop: &str) -> Option<crate::Time> {
140 crate::Time::parse_iso(&read_text(ui, id, prop))
141}
142
143pub fn read_datetime(ui: &Ui, id: ComponentId, prop: &str) -> Option<crate::DateTime> {
145 crate::DateTime::parse_iso(&read_text(ui, id, prop))
146}
147
148pub fn date_value(value: Option<crate::Date>) -> PropValue {
150 PropValue::String(value.map(|d| d.to_string()).unwrap_or_default())
151}
152
153pub fn time_value(value: Option<crate::Time>) -> PropValue {
155 PropValue::String(value.map(time_text).unwrap_or_default())
156}
157
158pub fn datetime_value(value: Option<crate::DateTime>) -> PropValue {
160 PropValue::String(value.map(|d| format!("{}T{}", d.date, time_text(d.time))).unwrap_or_default())
161}
162
163fn time_text(t: crate::Time) -> String {
164 if t.second() == 0 { format!("{:02}:{:02}", t.hour(), t.minute()) } else { format!("{:02}:{:02}:{:02}", t.hour(), t.minute(), t.second()) }
165}
166
167fn items(text: &str) -> impl Iterator<Item = &str> {
169 text.split(';').map(str::trim).filter(|s| !s.is_empty())
170}
171
172pub fn read_list(ui: &Ui, id: ComponentId, prop: &str) -> Vec<String> {
176 split_list(&read_text(ui, id, prop))
177}
178
179pub fn split_list(text: &str) -> Vec<String> {
181 if text.is_empty() { Vec::new() } else { text.split(';').map(str::to_string).collect() }
182}
183
184pub fn read_numbers(ui: &Ui, id: ComponentId, prop: &str) -> Vec<f64> {
186 items(&read_text(ui, id, prop)).filter_map(|s| s.parse().ok()).collect()
187}
188
189pub fn read_colors(ui: &Ui, id: ComponentId, prop: &str) -> Vec<crate::Color> {
191 items(&read_text(ui, id, prop)).filter_map(crate::Color::from_hex).collect()
192}
193
194pub fn list_value<S: AsRef<str>>(values: &[S]) -> PropValue {
196 PropValue::String(values.iter().map(|s| s.as_ref()).collect::<Vec<_>>().join(";"))
197}
198
199pub fn numbers_value(values: &[f64]) -> PropValue {
201 PropValue::String(values.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(";"))
202}
203
204pub fn colors_value(values: &[crate::Color]) -> PropValue {
206 PropValue::String(values.iter().map(|c| c.to_hex()).collect::<Vec<_>>().join(";"))
207}
208
209pub fn read_shadow(ui: &Ui, id: ComponentId, prop: &str) -> Option<crate::Shadow> {
211 crate::Shadow::parse(&read_text(ui, id, prop))
212}
213
214pub fn shadow_value(value: Option<crate::Shadow>) -> PropValue {
216 PropValue::String(value.map(|s| s.to_spec()).unwrap_or_default())
217}
218
219pub fn read_easing(ui: &Ui, id: ComponentId, prop: &str) -> crate::Easing {
221 crate::Easing::parse(&read_text(ui, id, prop)).unwrap_or_default()
222}
223
224pub fn easing_value(value: crate::Easing) -> PropValue {
226 PropValue::String(value.to_spec())
227}
228
229pub fn read_points(ui: &Ui, id: ComponentId, prop: &str) -> Vec<crate::PointF> {
231 read_text(ui, id, prop)
232 .split_whitespace()
233 .filter_map(|p| {
234 let (x, y) = p.split_once(',')?;
235 Some(crate::PointF::new(x.trim().parse().ok()?, y.trim().parse().ok()?))
236 })
237 .collect()
238}
239
240pub fn points_value(values: &[crate::PointF]) -> PropValue {
242 PropValue::String(values.iter().map(|p| format!("{},{}", p.x, p.y)).collect::<Vec<_>>().join(" "))
243}
244
245pub fn read_ref(ui: &Ui, id: ComponentId, prop: &str) -> Option<ComponentId> {
247 read(ui, id, prop).and_then(|v| v.to_component().ok().flatten())
248}
249
250pub fn read(ui: &Ui, id: ComponentId, prop: &str) -> Option<PropValue> {
253 match ui.get_prop(id, prop) {
254 Ok(v) => Some(v),
255 Err(e) => {
256 if cfg!(debug_assertions) {
257 crate::stderr_line!("aylis: ler {}.{prop}: {e}", ui.path_of(id));
258 }
259 None
260 }
261 }
262}
263
264pub fn write(ui: &mut Ui, id: ComponentId, prop: &str, value: impl Into<PropValue>) {
266 if let Err(e) = ui.set_prop(id, prop, value) {
267 failed(ui, id, &format!("gravar {prop}"), &e.to_string());
268 }
269}
270
271pub fn call(ui: &mut Ui, id: ComponentId, method: &str, args: &[PropValue]) -> Option<PropValue> {
273 match ui.invoke(id, method, args) {
274 Ok(v) => Some(v),
275 Err(e) => {
276 failed(ui, id, &format!("chamar {method}"), &e.to_string());
277 None
278 }
279 }
280}
281
282pub fn try_call(ui: &mut Ui, id: ComponentId, method: &str, args: &[PropValue]) -> std::result::Result<PropValue, String> {
286 ui.invoke(id, method, args).inspect_err(|e| failed(ui, id, &format!("chamar {method}"), e))
287}
288
289fn failed(ui: &mut Ui, id: ComponentId, what: &str, error: &str) {
290 let message = format!("{what} em {}: {error}", ui.path_of(id));
291 if cfg!(debug_assertions) {
292 crate::stderr_line!("aylis: {message}");
293 }
294 ui.report(&Activity::Error { message: &message });
295}
296
297pub fn text(ui: &Ui, value: Option<PropValue>) -> String {
299 match value {
300 Some(PropValue::Color(c)) => c.to_hex(),
301 Some(PropValue::Component(Some(id))) => ui.path_of(id),
302 Some(PropValue::Bounds(b)) => format!("{}, {}, {}, {}", b.left, b.top, b.right, b.bottom),
304 Some(PropValue::Set(names)) => names.join(","),
305 Some(v) => v.to_str().map(str::to_string).unwrap_or_default(),
306 None => String::new(),
307 }
308}
309
310pub fn resolve(ui: &Ui, root: ComponentId, name: &str, class: &str, problems: &mut Vec<String>) -> ComponentId {
313 match ui.find_in(root, name) {
314 Some(id) => {
315 let actual = ui.class_name(id).unwrap_or_default();
316 if actual != class {
317 problems.push(format!("{name} é {actual} no form e {class} no código"));
318 }
319 id
320 }
321 None => {
322 problems.push(format!("falta o componente {name} ({class})"));
323 root
324 }
325 }
326}
327
328#[cfg(test)]
329mod tests {
330 use super::*;
331
332 #[test]
334 fn the_list_keeps_the_empty_items_and_the_spaces() {
335 let text = match list_value(&["", "A", " B "]) {
336 PropValue::String(s) => s,
337 _ => unreachable!(),
338 };
339 assert_eq!(split_list(&text), ["", "A", " B "]);
340 assert!(split_list("").is_empty());
341 }
342
343 #[test]
345 fn the_font_weight_names_match_the_core_type() {
346 use crate::prop::PropEnum;
347 for (i, name) in crate::FONT_WEIGHTS.iter().enumerate() {
348 let w = <Option<crate::FontWeight>>::from_index(i).unwrap();
349 assert_eq!(w.name(), *name);
350 }
351 assert_eq!(<Option<crate::FontWeight>>::from_name("semibold"), Some(Some(crate::FontWeight::SemiBold)));
352 assert_eq!(<Option<crate::FontWeight>>::from_name("default"), Some(None));
353 }
354}