Skip to main content

aylis_data/
binding.rs

1//! As ligações de propriedades a dados ([`aylis_core::Binding`]): mostra o
2//! campo (ou o texto montado, ou a expressão) na propriedade quando o dataset muda e grava de
3//! volta quando o usuário muda uma propriedade ligada só a um campo.
4//!
5//! O ligar fica no núcleo (`Ui::set_binding`, o JSON do form, a IDE em "Ligar a campo…");
6//! aqui, [`install`] (chamado pelo [`register`](crate::register)) liga o `Ui` a este motor.
7//!
8//! O que vai em `path`:
9//! - `nome`: o campo, como o dataset mostra (`display_format`, máscara);
10//! - `Total: {valor:moeda}`: um texto com campos; depois do `:`, `moeda`, um formato de
11//!   número (`#,##0.00`) ou de data (`dd/mm/yyyy`);
12//! - `=quantidade * preco`: uma expressão com os campos do mesmo dataset (a do filtro).
13
14use std::cell::Cell;
15use std::rc::Rc;
16
17use aylis_core::{Binding, ComponentId, PropKind, PropValue, Ui};
18
19use crate::dataset::{DataEvent, DataSource};
20use crate::expr::Expr;
21use crate::handle::{data_set, view};
22use crate::value::Value;
23
24/// Liga o `Ui` ao motor das ligações.
25pub fn install(ui: &mut Ui) {
26    ui.set_binding_sink(Rc::new(write_back), Rc::new(|ui: &mut Ui, id| apply(ui, id)));
27}
28
29/// O dataset por trás do `DataSource` da ligação (se ligado e habilitado).
30fn data_set_of(ui: &Ui, source: Option<ComponentId>) -> Option<ComponentId> {
31    let s = ui.get::<DataSource>(source?)?;
32    if s.enabled { s.data_set } else { None }
33}
34
35/// Mostra os valores de todas as ligações de `id`.
36pub fn apply(ui: &mut Ui, id: ComponentId) {
37    let mut bindings: Vec<Binding> = ui.bindings(id).to_vec();
38    // As listas antes: o `value` de uma lista suspensa escolhe entre os `values`.
39    bindings.sort_by_key(|b| !LIST_PROPS.contains(&b.property.as_str()));
40    for b in bindings {
41        if b.is_field() {
42            metadata(ui, id, &b);
43        }
44        if let Some(value) = compute(ui, id, &b) {
45            if ui.get_prop(id, &b.property).ok().as_ref() != Some(&value) {
46                let _ = ui.set_prop(id, &b.property, value);
47            }
48        }
49    }
50}
51
52/// Os metadados do campo no componente (se ele tiver a propriedade): tamanho, máscara,
53/// leitura e dado pessoal.
54fn metadata(ui: &mut Ui, id: ComponentId, b: &Binding) {
55    // No designer só o valor aparece: os metadados iriam para o JSON do form.
56    if ui.design_mode() {
57        return;
58    }
59    let Some(ds) = data_set_of(ui, b.source) else { return };
60    let v = view(ui, ds);
61    let Ok(field) = v.field(&b.path) else { return };
62    let read_only = field.is_read_only() || ui.get::<crate::ClientDataSet>(ds).is_some_and(|c| c.read_only);
63    let (size, mask, sensitive) = (field.size, field.edit_mask.clone(), field.sensitive);
64    let main = matches!(b.property.as_str(), "text" | "value" | "checked" | "item_index" | "date");
65    if !main {
66        return;
67    }
68    let mut set = |name: &str, value: PropValue| {
69        if ui.prop_info(id, name).is_some() && ui.get_prop(id, name).ok().as_ref() != Some(&value) {
70            let _ = ui.set_prop(id, name, value);
71        }
72    };
73    set("read_only", PropValue::Bool(read_only));
74    if b.property == "text" {
75        if size > 0 {
76            set("max_length", PropValue::Int(size as i64));
77        }
78        if !mask.is_empty() {
79            set("mask", PropValue::String(mask));
80        }
81        if sensitive {
82            set("sensitive", PropValue::Bool(true));
83        }
84    }
85}
86
87/// O dataset avisou: mostra de novo os componentes ligados a ele.
88pub(crate) fn notify(ui: &mut Ui, sources: &[ComponentId], event: &DataEvent) {
89    if *event == DataEvent::UpdateData {
90        return;
91    }
92    let mut bound: Vec<ComponentId> = Vec::new();
93    for &s in sources {
94        for c in ui.bound_to(s) {
95            if !bound.contains(&c) {
96                bound.push(c);
97            }
98        }
99    }
100    for c in bound {
101        // Este componente está gravando de volta (o `edit` do dataset avisa no meio): mostrar
102        // o campo agora apagaria o valor que o usuário acabou de escolher.
103        if WRITING.with(Cell::get) == Some(c) {
104            continue;
105        }
106        // O campo que mudou foi este mesmo componente (o usuário digitando): não sobrescreve.
107        if let DataEvent::RecordChanged(Some(field)) = event {
108            if ui.bindings(c).iter().any(|b| b.is_field() && b.path.eq_ignore_ascii_case(field)) && is_focused(ui, c) {
109                continue;
110            }
111        }
112        apply(ui, c);
113    }
114}
115
116fn is_focused(ui: &Ui, id: ComponentId) -> bool {
117    ui.control(id).is_some_and(|c| c.state().focused)
118}
119
120/// As propriedades que recebem o campo de todos os registros (separados por `;`): as listas
121/// e os rótulos do eixo do `Chart`.
122pub const LIST_PROPS: [&str; 4] = ["items", "values", "labels", "series"];
123
124/// As séries do `Chart` ligadas a campos, um ponto por registro. O caminho é só os campos
125/// (`vendas;custos`: o nome da série é o do campo) ou a lista de séries do `series`
126/// (`ChartSeries`) com o `field` de cada uma no lugar dos `values`
127/// (`[{"name": "Custos", "kind": "line", "color": "#EF4444", "field": "custos"}]`). Sai o
128/// JSON do `series`, com os `values`.
129fn series_of(v: &crate::handle::DataView<'_>, path: &str) -> String {
130    use serde_json::{Map, Value as Json};
131    let values = |field: &str| -> Json {
132        (0..v.record_count())
133            .map(|r| {
134                let x = v.value_at(r, field).ok().and_then(|x| x.as_f64()).unwrap_or(0.0);
135                if x.fract() == 0.0 && x.abs() < 9.0e15 { Json::from(x as i64) } else { Json::from(x) }
136            })
137            .collect()
138    };
139    let path = path.trim();
140    let series: Vec<Json> = if path.starts_with('[') {
141        let Ok(Json::Array(items)) = serde_json::from_str::<Json>(path) else { return "[]".into() };
142        items
143            .into_iter()
144            .filter_map(|item| {
145                let Json::Object(mut o) = item else { return None };
146                let field = o.remove("field")?.as_str()?.trim().to_string();
147                o.insert("values".into(), values(&field));
148                Some(Json::Object(o))
149            })
150            .collect()
151    } else {
152        path.split(';')
153            .map(str::trim)
154            .filter(|f| !f.is_empty())
155            .map(|f| {
156                let mut o = Map::new();
157                o.insert("name".into(), f.into());
158                o.insert("values".into(), values(f));
159                Json::Object(o)
160            })
161            .collect()
162    };
163    Json::Array(series).to_string()
164}
165
166/// O valor da ligação, já no tipo da propriedade.
167pub fn compute(ui: &Ui, id: ComponentId, b: &Binding) -> Option<PropValue> {
168    let ds = data_set_of(ui, b.source)?;
169    let v = view(ui, ds);
170    if !v.is_active() {
171        return None;
172    }
173    let kind = ui.prop_info(id, &b.property)?.kind;
174    if let Some(expr) = b.path.strip_prefix('=') {
175        let expr = Expr::parse(expr).ok()?;
176        let value = expr.eval(&|name| v.value(name).ok()).ok()?;
177        return Some(to_prop(&value, kind, &text_of(&value)));
178    }
179    // As séries de um gráfico: um ponto por registro em cada uma (antes do modelo com `{}`:
180    // o caminho delas pode ser JSON).
181    if b.property == "series" {
182        return Some(PropValue::String(series_of(&v, &b.path)));
183    }
184    if b.path.contains('{') {
185        return Some(PropValue::String(template(ui, ds, &b.path)));
186    }
187    // As listas (`items` e `values` de uma lista suspensa, `labels` de um gráfico): o campo
188    // de todos os registros.
189    if LIST_PROPS.contains(&b.property.as_str()) {
190        let all: Vec<String> = (0..v.record_count()).map(|r| v.text_at(r, &b.path).unwrap_or_default().replace(';', ",")).collect();
191        return Some(PropValue::String(all.join(";")));
192    }
193    if v.is_empty() {
194        return Some(empty(kind));
195    }
196    let value = v.value(&b.path).ok()?;
197    let text = if is_focused(ui, id) { v.edit_text(&b.path).ok()? } else { v.text(&b.path).ok()? };
198    Some(to_prop(&value, kind, &text))
199}
200
201fn text_of(value: &Value) -> String {
202    match value {
203        Value::Null => String::new(),
204        Value::Bool(b) => b.to_string(),
205        Value::Int(i) => i.to_string(),
206        Value::Float(f) => f.to_string(),
207        Value::Decimal(d) => d.to_f64().to_string(),
208        Value::String(s) => s.clone(),
209        other => format!("{other:?}"),
210    }
211}
212
213/// O valor vazio de cada tipo (dataset sem registros).
214fn empty(kind: PropKind) -> PropValue {
215    match kind {
216        PropKind::Bool => PropValue::Bool(false),
217        PropKind::Int => PropValue::Int(0),
218        PropKind::Float | PropKind::Angle | PropKind::Duration => PropValue::Float(0.0),
219        _ => PropValue::String(String::new()),
220    }
221}
222
223fn to_prop(value: &Value, kind: PropKind, text: &str) -> PropValue {
224    match kind {
225        PropKind::Bool => PropValue::Bool(value.as_bool().unwrap_or_else(|| value.as_f64().is_some_and(|n| n != 0.0))),
226        PropKind::Int => PropValue::Int(value.as_i64().or_else(|| value.as_f64().map(|f| f.round() as i64)).unwrap_or(0)),
227        PropKind::Float | PropKind::Angle | PropKind::Duration => PropValue::Float(value.as_f64().unwrap_or(0.0)),
228        PropKind::Enum(_) => PropValue::Enum(text.to_string()),
229        PropKind::Color => aylis_core::Color::from_hex(text.trim()).map_or_else(|| PropValue::String(text.to_string()), PropValue::Color),
230        _ => PropValue::String(text.to_string()),
231    }
232}
233
234fn decimal(value: &Value, scale: u8) -> Option<crate::Decimal> {
235    value.as_decimal().or_else(|| value.as_f64().and_then(|f| crate::Decimal::from_f64(f, scale)))
236}
237
238/// `Total: {valor:moeda}` com os campos do registro atual.
239fn template(ui: &Ui, ds: ComponentId, text: &str) -> String {
240    let v = view(ui, ds);
241    let locale = ui.locale();
242    let mut out = String::new();
243    let mut rest = text;
244    while let Some(open) = rest.find('{') {
245        out.push_str(&rest[..open]);
246        let Some(close) = rest[open..].find('}') else {
247            out.push_str(&rest[open..]);
248            return out;
249        };
250        let inner = &rest[open + 1..open + close];
251        let (name, format) = inner.split_once(':').map_or((inner.trim(), ""), |(n, f)| (n.trim(), f.trim()));
252        let shown = match (format, v.value(name)) {
253            ("", _) => v.text(name).unwrap_or_default(),
254            (_, Ok(value)) if value.is_null() => String::new(),
255            ("moeda" | "currency", Ok(value)) => match decimal(&value, 2) {
256                Some(n) => format!("{} {}", locale.currency_symbol, crate::format::format_number(n, "#,##0.00", &locale)),
257                None => text_of(&value),
258            },
259            (pattern, Ok(value)) if value.as_f64().is_some() => match decimal(&value, 6) {
260                Some(n) => crate::format::format_number(n, pattern, &locale),
261                None => text_of(&value),
262            },
263            (pattern, Ok(Value::Date(d))) => crate::format::format_date_time(Some(d), None, pattern),
264            (pattern, Ok(Value::DateTime(dt))) => crate::format::format_date_time(Some(dt.date), Some(dt.time), pattern),
265            (pattern, Ok(Value::Timestamp(ts))) => {
266                let dt = ts.to_local();
267                crate::format::format_date_time(Some(dt.date), Some(dt.time), pattern)
268            }
269            (_, Ok(value)) => text_of(&value),
270            (_, Err(_)) => format!("{{{inner}?}}"),
271        };
272        out.push_str(&shown);
273        rest = &rest[open + close + 1..];
274    }
275    out.push_str(rest);
276    out
277}
278
279thread_local! {
280    /// O componente que está gravando de volta agora.
281    static WRITING: Cell<Option<ComponentId>> = const { Cell::new(None) };
282}
283
284/// O usuário mudou um componente ligado: grava as propriedades ligadas só a um campo.
285fn write_back(ui: &mut Ui, id: ComponentId) {
286    let outer = WRITING.with(|w| w.replace(Some(id)));
287    write_fields(ui, id);
288    WRITING.with(|w| w.set(outer));
289}
290
291fn write_fields(ui: &mut Ui, id: ComponentId) {
292    let bindings: Vec<Binding> = ui.bindings(id).iter().filter(|b| b.is_field() && !LIST_PROPS.contains(&b.property.as_str())).cloned().collect();
293    for b in bindings {
294        let Some(ds) = data_set_of(ui, b.source) else { continue };
295        let Ok(now) = ui.get_prop(id, &b.property) else { continue };
296        // Só se mudou de verdade (o evento pode vir de um clique que não mexeu no valor).
297        if compute(ui, id, &b).as_ref() == Some(&now) {
298            continue;
299        }
300        let read_only = view(ui, ds).field(&b.path).map_or(true, |f| f.is_read_only());
301        if read_only {
302            apply(ui, id);
303            continue;
304        }
305        let auto_edit = b.source.and_then(|s| ui.get::<DataSource>(s)).is_some_and(|s| s.auto_edit);
306        let mut d = data_set(ui, ds);
307        if !d.state().is_editing() {
308            if !auto_edit || d.edit().is_err() {
309                drop(d);
310                apply(ui, id);
311                continue;
312            }
313        }
314        let result = match &now {
315            PropValue::Bool(v) => d.set_value(&b.path, *v),
316            PropValue::Int(n) => d.set_value(&b.path, *n),
317            PropValue::Float(n) => d.set_value(&b.path, *n),
318            PropValue::Enum(s) => d.set_text(&b.path, s),
319            PropValue::Color(c) => d.set_text(&b.path, &c.to_hex()),
320            PropValue::String(s) => d.set_text(&b.path, s),
321            other => d.set_text(&b.path, &format!("{other:?}")),
322        };
323        // O erro de validação aparece no próprio componente (o `error` do Edit), se ele tiver.
324        let error = match result {
325            Ok(()) => String::new(),
326            Err(e) => e.message,
327        };
328        drop(d);
329        if ui.prop_info(id, "error").is_some() {
330            let _ = ui.set_prop(id, "error", error);
331        }
332    }
333}