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: `Vendas=vendas|Custos[line;#EF4444]=custos` (o nome
125/// e as opções da série antes do `=`, o campo depois) ou só os campos (`vendas;custos`), um
126/// ponto por registro: `Vendas=10,20,30|Custos=5,8,9`, o formato do `series`.
127fn series_of(v: &crate::handle::DataView<'_>, path: &str) -> String {
128    let parts: Vec<&str> = if path.contains('=') { path.split('|').collect() } else { path.split(';').collect() };
129    parts
130        .iter()
131        .map(|p| p.trim())
132        .filter(|p| !p.is_empty())
133        .map(|p| {
134            let (head, field) = p.rsplit_once('=').map_or((p, p), |(h, f)| (h.trim(), f.trim()));
135            let values: Vec<String> = (0..v.record_count()).map(|r| v.value_at(r, field).ok().and_then(|x| x.as_f64()).unwrap_or(0.0).to_string()).collect();
136            format!("{head}={}", values.join(","))
137        })
138        .collect::<Vec<_>>()
139        .join("|")
140}
141
142/// O valor da ligação, já no tipo da propriedade.
143pub fn compute(ui: &Ui, id: ComponentId, b: &Binding) -> Option<PropValue> {
144    let ds = data_set_of(ui, b.source)?;
145    let v = view(ui, ds);
146    if !v.is_active() {
147        return None;
148    }
149    let kind = ui.prop_info(id, &b.property)?.kind;
150    if let Some(expr) = b.path.strip_prefix('=') {
151        let expr = Expr::parse(expr).ok()?;
152        let value = expr.eval(&|name| v.value(name).ok()).ok()?;
153        return Some(to_prop(&value, kind, &text_of(&value)));
154    }
155    if b.path.contains('{') {
156        return Some(PropValue::String(template(ui, ds, &b.path)));
157    }
158    // As séries de um gráfico: um ponto por registro em cada uma.
159    if b.property == "series" {
160        return Some(PropValue::String(series_of(&v, &b.path)));
161    }
162    // As listas (`items` e `values` de uma lista suspensa, `labels` de um gráfico): o campo
163    // de todos os registros.
164    if LIST_PROPS.contains(&b.property.as_str()) {
165        let all: Vec<String> = (0..v.record_count()).map(|r| v.text_at(r, &b.path).unwrap_or_default().replace(';', ",")).collect();
166        return Some(PropValue::String(all.join(";")));
167    }
168    if v.is_empty() {
169        return Some(empty(kind));
170    }
171    let value = v.value(&b.path).ok()?;
172    let text = if is_focused(ui, id) { v.edit_text(&b.path).ok()? } else { v.text(&b.path).ok()? };
173    Some(to_prop(&value, kind, &text))
174}
175
176fn text_of(value: &Value) -> String {
177    match value {
178        Value::Null => String::new(),
179        Value::Bool(b) => b.to_string(),
180        Value::Int(i) => i.to_string(),
181        Value::Float(f) => f.to_string(),
182        Value::Decimal(d) => d.to_f64().to_string(),
183        Value::String(s) => s.clone(),
184        other => format!("{other:?}"),
185    }
186}
187
188/// O valor vazio de cada tipo (dataset sem registros).
189fn empty(kind: PropKind) -> PropValue {
190    match kind {
191        PropKind::Bool => PropValue::Bool(false),
192        PropKind::Int => PropValue::Int(0),
193        PropKind::Float | PropKind::Angle | PropKind::Duration => PropValue::Float(0.0),
194        _ => PropValue::String(String::new()),
195    }
196}
197
198fn to_prop(value: &Value, kind: PropKind, text: &str) -> PropValue {
199    match kind {
200        PropKind::Bool => PropValue::Bool(value.as_bool().unwrap_or_else(|| value.as_f64().is_some_and(|n| n != 0.0))),
201        PropKind::Int => PropValue::Int(value.as_i64().or_else(|| value.as_f64().map(|f| f.round() as i64)).unwrap_or(0)),
202        PropKind::Float | PropKind::Angle | PropKind::Duration => PropValue::Float(value.as_f64().unwrap_or(0.0)),
203        PropKind::Enum(_) => PropValue::Enum(text.to_string()),
204        PropKind::Color => aylis_core::Color::from_hex(text.trim()).map_or_else(|| PropValue::String(text.to_string()), PropValue::Color),
205        _ => PropValue::String(text.to_string()),
206    }
207}
208
209fn decimal(value: &Value, scale: u8) -> Option<crate::Decimal> {
210    value.as_decimal().or_else(|| value.as_f64().and_then(|f| crate::Decimal::from_f64(f, scale)))
211}
212
213/// `Total: {valor:moeda}` com os campos do registro atual.
214fn template(ui: &Ui, ds: ComponentId, text: &str) -> String {
215    let v = view(ui, ds);
216    let locale = ui.locale();
217    let mut out = String::new();
218    let mut rest = text;
219    while let Some(open) = rest.find('{') {
220        out.push_str(&rest[..open]);
221        let Some(close) = rest[open..].find('}') else {
222            out.push_str(&rest[open..]);
223            return out;
224        };
225        let inner = &rest[open + 1..open + close];
226        let (name, format) = inner.split_once(':').map_or((inner.trim(), ""), |(n, f)| (n.trim(), f.trim()));
227        let shown = match (format, v.value(name)) {
228            ("", _) => v.text(name).unwrap_or_default(),
229            (_, Ok(value)) if value.is_null() => String::new(),
230            ("moeda" | "currency", Ok(value)) => match decimal(&value, 2) {
231                Some(n) => format!("{} {}", locale.currency_symbol, crate::format::format_number(n, "#,##0.00", &locale)),
232                None => text_of(&value),
233            },
234            (pattern, Ok(value)) if value.as_f64().is_some() => match decimal(&value, 6) {
235                Some(n) => crate::format::format_number(n, pattern, &locale),
236                None => text_of(&value),
237            },
238            (pattern, Ok(Value::Date(d))) => crate::format::format_date_time(Some(d), None, pattern),
239            (pattern, Ok(Value::DateTime(dt))) => crate::format::format_date_time(Some(dt.date), Some(dt.time), pattern),
240            (pattern, Ok(Value::Timestamp(ts))) => {
241                let dt = ts.to_local();
242                crate::format::format_date_time(Some(dt.date), Some(dt.time), pattern)
243            }
244            (_, Ok(value)) => text_of(&value),
245            (_, Err(_)) => format!("{{{inner}?}}"),
246        };
247        out.push_str(&shown);
248        rest = &rest[open + close + 1..];
249    }
250    out.push_str(rest);
251    out
252}
253
254thread_local! {
255    /// O componente que está gravando de volta agora.
256    static WRITING: Cell<Option<ComponentId>> = const { Cell::new(None) };
257}
258
259/// O usuário mudou um componente ligado: grava as propriedades ligadas só a um campo.
260fn write_back(ui: &mut Ui, id: ComponentId) {
261    let outer = WRITING.with(|w| w.replace(Some(id)));
262    write_fields(ui, id);
263    WRITING.with(|w| w.set(outer));
264}
265
266fn write_fields(ui: &mut Ui, id: ComponentId) {
267    let bindings: Vec<Binding> = ui.bindings(id).iter().filter(|b| b.is_field() && !LIST_PROPS.contains(&b.property.as_str())).cloned().collect();
268    for b in bindings {
269        let Some(ds) = data_set_of(ui, b.source) else { continue };
270        let Ok(now) = ui.get_prop(id, &b.property) else { continue };
271        // Só se mudou de verdade (o evento pode vir de um clique que não mexeu no valor).
272        if compute(ui, id, &b).as_ref() == Some(&now) {
273            continue;
274        }
275        let read_only = view(ui, ds).field(&b.path).map_or(true, |f| f.is_read_only());
276        if read_only {
277            apply(ui, id);
278            continue;
279        }
280        let auto_edit = b.source.and_then(|s| ui.get::<DataSource>(s)).is_some_and(|s| s.auto_edit);
281        let mut d = data_set(ui, ds);
282        if !d.state().is_editing() {
283            if !auto_edit || d.edit().is_err() {
284                drop(d);
285                apply(ui, id);
286                continue;
287            }
288        }
289        let result = match &now {
290            PropValue::Bool(v) => d.set_value(&b.path, *v),
291            PropValue::Int(n) => d.set_value(&b.path, *n),
292            PropValue::Float(n) => d.set_value(&b.path, *n),
293            PropValue::Enum(s) => d.set_text(&b.path, s),
294            PropValue::Color(c) => d.set_text(&b.path, &c.to_hex()),
295            PropValue::String(s) => d.set_text(&b.path, s),
296            other => d.set_text(&b.path, &format!("{other:?}")),
297        };
298        // O erro de validação aparece no próprio componente (o `error` do Edit), se ele tiver.
299        let error = match result {
300            Ok(()) => String::new(),
301            Err(e) => e.message,
302        };
303        drop(d);
304        if ui.prop_info(id, "error").is_some() {
305            let _ = ui.set_prop(id, "error", error);
306        }
307    }
308}