Skip to main content

aylis_json/
layout.rs

1//! Carregar e salvar a árvore de componentes.
2
3use aylis_core::{ComponentId, PropKind, PropValue, Ui, read_prop};
4use serde_json::{Map, Value};
5
6use crate::value::{describe, from_prop, object, to_prop};
7use crate::{Error, FORMAT_VERSION, Result};
8
9/// `uses`: os DataModules que o form usa (o aplicativo cria antes; ver
10/// `aylis_project::ProjectForms`).
11pub(crate) const RESERVED: [&str; 6] = ["class", "name", "children", "uses", "bindings", "views"];
12
13/// As propriedades que limitam outras (o `value` cabe entre elas): carregadas primeiro.
14const LIMITS: [&str; 6] = ["min", "max", "minimum", "maximum", "min_value", "max_value"];
15
16/// Carrega um documento (`{"aylis": 1, "root": {...}}`) e devolve o componente raiz.
17///
18/// Com `parent`, a raiz vira filha dele (para carregar um pedaço de tela dentro de outra);
19/// sem, vira um form. Se der erro, nada do documento fica no `Ui`.
20pub fn load(ui: &mut Ui, json: &str, parent: Option<ComponentId>) -> Result<ComponentId> {
21    let value: Value = serde_json::from_str(json.trim_start_matches('\u{feff}'))?;
22    load_value(ui, &value, parent)
23}
24
25/// Como [`load`], a partir de um valor já lido (por exemplo vindo do protocolo).
26///
27/// Carregar não dispara o `on_change` dos valores.
28pub fn load_value(ui: &mut Ui, document: &Value, parent: Option<ComponentId>) -> Result<ComponentId> {
29    ui.without_change_events(|ui| load_document(ui, document, parent))
30}
31
32fn load_document(ui: &mut Ui, document: &Value, parent: Option<ComponentId>) -> Result<ComponentId> {
33    let doc = object(document, "o documento").map_err(structure(""))?;
34    if let Some(version) = doc.get("aylis") {
35        let version = version.as_u64().ok_or_else(|| structure("")("\"aylis\" deve ser o número da versão".into()))?;
36        // Só o próprio formato: outro (mais novo ou mais antigo) passa pelo aylis-migrate.
37        if version != FORMAT_VERSION {
38            return Err(Error::Version(version));
39        }
40    }
41    for key in doc.keys() {
42        if !matches!(key.as_str(), "aylis" | "root" | "$schema") {
43            return Err(structure("")(format!("chave desconhecida no documento: '{key}' (use \"aylis\" e \"root\")")));
44        }
45    }
46    let root = doc.get("root").ok_or_else(|| structure("")("falta \"root\"".into()))?;
47
48    let mut loader = Loader { ui, created: None, deferred: Vec::new(), bindings: Vec::new(), views: Vec::new(), errors: None };
49    let result = loader.node(root, parent, &mut Vec::new()).and_then(|id| loader.fixup().map(|_| id));
50    if result.is_err() {
51        if let Some(created) = loader.created {
52            loader.ui.free(created);
53        }
54    }
55    result
56}
57
58pub(crate) struct Loader<'a> {
59    pub(crate) ui: &'a mut Ui,
60    /// Primeiro componente criado (para desfazer em caso de erro).
61    pub(crate) created: Option<ComponentId>,
62    /// Referências a outros componentes, resolvidas no fim: (componente, propriedade, nome, caminho).
63    pub(crate) deferred: Vec<(ComponentId, String, String, String)>,
64    /// As ligações a dados, resolvidas no fim: (componente, propriedade, DataSource, campo).
65    pub(crate) bindings: Vec<(ComponentId, String, String, String)>,
66    /// As vistas por largura de um form (veja `aylis_core::views`), resolvidas no fim.
67    pub(crate) views: Vec<(ComponentId, Value)>,
68    /// Com `Some`, os erros de propriedade e de classe são juntados aqui e o carregamento
69    /// segue ([`validate`]): todos de uma vez, em vez de um por tentativa.
70    pub(crate) errors: Option<Vec<Error>>,
71}
72
73/// Confere um layout inteiro e devolve **todos** os erros (vazio: carrega). Monta numa raiz
74/// de passagem no `ui` e a libera no fim. Um layout de 24 KB com cinco erros ia e voltava
75/// cinco vezes, um erro por vez (relatório do RTSPlayer, 10/11).
76pub fn validate(ui: &mut Ui, json: &str) -> Vec<Error> {
77    let doc: Value = match serde_json::from_str(json.trim_start_matches('\u{feff}')) {
78        Ok(v) => v,
79        Err(e) => return vec![Error::Structure { path: String::new(), message: format!("JSON inválido: {e}") }],
80    };
81    let Some(root) = doc.get("root") else { return vec![structure("")("falta \"root\"".into())] };
82    let mut loader = Loader { ui, created: None, deferred: Vec::new(), bindings: Vec::new(), views: Vec::new(), errors: Some(Vec::new()) };
83    let result = loader.node(root, None, &mut Vec::new()).and_then(|_| loader.fixup());
84    let mut errors = loader.errors.take().unwrap_or_default();
85    if let Err(e) = result {
86        errors.push(e);
87    }
88    if let Some(created) = loader.created {
89        loader.ui.free(created);
90    }
91    errors
92}
93
94impl Loader<'_> {
95    /// Um erro que não impede o resto: no [`validate`], anotado (e segue); senão, devolvido.
96    fn soft(&mut self, error: Error) -> Result<()> {
97        match self.errors.as_mut() {
98            Some(list) => {
99                list.push(error);
100                Ok(())
101            }
102            None => Err(error),
103        }
104    }
105
106    pub(crate) fn node(&mut self, value: &Value, parent: Option<ComponentId>, path: &mut Vec<String>) -> Result<ComponentId> {
107        // O caminho (`frmX > pnl > btn`) só é montado quando há um erro: cada componente de um
108        // frame repetido (`FraX::create_in`) passava por dois `join` (G21 do Tabernáculo).
109        let obj = object(value, "cada componente").map_err(|e| structure(&path.join(" > "))(e))?;
110        let class = obj
111            .get("class")
112            .and_then(Value::as_str)
113            .ok_or_else(|| structure(&path.join(" > "))("falta \"class\" (o nome da classe do componente)".into()))?;
114        let name = match obj.get("name") {
115            None | Some(Value::Null) => None,
116            Some(Value::String(s)) => Some(s.as_str()),
117            Some(other) => return Err(structure(&path.join(" > "))(format!("\"name\" deve ser texto, recebido {}", describe(other)))),
118        };
119        path.push(name.unwrap_or(class).to_string());
120        let here = |path: &[String]| path.join(" > ");
121
122        let id = match self.ui.create(class, parent) {
123            Ok(id) => id,
124            // Classe que não existe: no `validate`, anota e pula o componente (e os filhos).
125            Err(source) => {
126                let error = Error::Component { path: here(path), source };
127                match parent {
128                    Some(p) if self.errors.is_some() => {
129                        self.soft(error)?;
130                        path.pop();
131                        return Ok(p);
132                    }
133                    _ => return Err(error),
134                }
135            }
136        };
137        if self.created.is_none() && parent.is_some() && class == "Form" {
138            // Um form carregado dentro de outro tem os próprios nomes (pode repetir os do
139            // form de fora). Um pedaço de tela que não é form entra nos nomes do de fora.
140            self.ui.set_name_scope(id, true);
141        }
142        self.created.get_or_insert(id);
143        if let Some(name) = name {
144            if let Err(source) = self.ui.set_name(id, name) {
145                self.soft(Error::Component { path: here(path), source })?;
146            }
147        }
148
149        // Os limites antes do resto: o `value` de um NumberBox ou de
150        // uma TrackBar, gravado antes do `max` na ordem da classe, não é cortado pelo máximo
151        // padrão ao abrir (o 10.000.000 virava 1000).
152        // O `translate` também vem antes: desligado, os textos não são traduzidos ao carregar.
153        // (Duas passadas pelo objeto, sem a lista ordenada de cada componente.)
154        let first = |key: &str| LIMITS.contains(&key) || key == "translate";
155        let entries = obj.iter().filter(|(key, _)| first(key)).chain(obj.iter().filter(|(key, _)| !first(key)));
156        for (key, value) in entries {
157            // `bindings`: as ligações de propriedade a campo (abaixo). A da lista (`VirtualList`,
158            // `DataRepeater`) chama `item_bindings` e não colide com ela.
159            if RESERVED.contains(&key.as_str()) {
160                continue;
161            }
162            if let Err(e) = self.property(id, class, key, value, path) {
163                self.soft(e)?;
164            }
165        }
166
167        // "bindings": { "text": { "source": "dsClientes", "field": "nome" } }
168        if let Some(Value::Object(list)) = obj.get("bindings") {
169            for (property, b) in list {
170                let source = b.get("source").and_then(Value::as_str).unwrap_or("").to_string();
171                let field = b.get("field").and_then(Value::as_str).unwrap_or("").to_string();
172                self.bindings.push((id, property.clone(), source, field));
173            }
174        }
175        // "views": [ { "name": "phone", "max_width": 599, "changes": { "btn": { "visible": false } } } ]
176        if let Some(views) = obj.get("views").filter(|v| v.is_array()) {
177            self.views.push((id, views.clone()));
178        }
179
180        // O Frame mostra o form de `form`: filhos dele no JSON tomavam o lugar desse form, e
181        // excluir o Frame os jogava no form de fora (relatório do InsightDB, 11/11).
182        if class == "Frame" && obj.get("children").and_then(Value::as_array).is_some_and(|c| !c.is_empty()) {
183            self.soft(structure(&here(path))("o Frame mostra o form da propriedade `form` e não tem filhos: ponha os componentes no form dele".into()))?;
184            path.pop();
185            return Ok(id);
186        }
187        match obj.get("children") {
188            None | Some(Value::Null) => {}
189            Some(Value::Array(children)) => {
190                for child in children {
191                    self.node(child, Some(id), path)?;
192                }
193            }
194            Some(other) => {
195                return Err(structure(&here(path))(format!("\"children\" deve ser uma lista, recebido {}", describe(other))));
196            }
197        }
198        path.pop();
199        Ok(id)
200    }
201
202    /// Uma propriedade do componente `id` (da classe `class`) pelo JSON.
203    fn property(&mut self, id: ComponentId, class: &str, key: &str, value: &Value, path: &[String]) -> Result<()> {
204        let fail = |message: String| Error::Property { path: path.join(" > "), property: key.to_string(), message };
205        // "margins.left": 4
206        if key.contains('.') {
207            let v = value.as_f64().ok_or_else(|| fail(format!("esperado número, recebido {}", describe(value))))?;
208            return self.ui.set_prop(id, key, v).map_err(|e| fail(e.to_string()));
209        }
210        let info = self.ui.prop_info(id, key).ok_or_else(|| fail(format!("a classe {class} não tem esta propriedade")))?;
211        let prop = to_prop(value, info.kind, self.ui.theme()).map_err(fail)?;
212        if info.kind == PropKind::Component {
213            if let PropValue::String(target) = prop {
214                self.deferred.push((id, key.to_string(), target, path.join(" > ")));
215            }
216            return Ok(());
217        }
218        // Textos da tela: traduzidos para o idioma atual (o original fica lembrado).
219        if let (PropValue::String(text), true) = (&prop, aylis_core::i18n::TRANSLATABLE.contains(&key)) {
220            let text = text.clone();
221            return self.ui.set_translated(id, key, &text).map_err(|e| fail(strip_property(e)));
222        }
223        self.ui.set_prop(id, key, prop).map_err(|e| fail(strip_property(e)))
224    }
225
226    /// Resolve as referências por nome depois que tudo existe.
227    pub(crate) fn fixup(&mut self) -> Result<()> {
228        for (id, property, target, path) in std::mem::take(&mut self.deferred) {
229            if let Err(e) = self.ui.set_prop(id, &property, target.as_str()) {
230                self.soft(Error::Property { path, property, message: strip_property(e) })?;
231            }
232        }
233        for (id, property, source, field) in std::mem::take(&mut self.bindings) {
234            let source = self.ui.resolve_reference(id, &source);
235            self.ui.set_binding(id, &property, source, &field);
236        }
237        for (form, list) in std::mem::take(&mut self.views) {
238            let views = load_views(self.ui, form, &list);
239            self.ui.set_views(form, views);
240        }
241        Ok(())
242    }
243}
244
245/// As vistas do JSON, com os valores no tipo de cada propriedade:
246/// `[{ "name", "max_width", "min_width", "min_height", "max_height", "orientation",
247/// "platforms": [...], "font_scale", "spacing_scale", "changes": { "componente": { "prop": valor,
248/// "parent": "pnlRodape", "index": 0 } } }]` (só `name` é obrigatório). O que não existe mais
249/// (componente, propriedade) fica de fora.
250fn load_views(ui: &Ui, form: ComponentId, list: &Value) -> Vec<aylis_core::FormView> {
251    use aylis_core::views::{INDEX, PARENT};
252    let mut views = Vec::new();
253    for v in list.as_array().into_iter().flatten() {
254        let Some(name) = v.get("name").and_then(Value::as_str) else { continue };
255        let number = |key: &str, default: f64| v.get(key).and_then(Value::as_f64).unwrap_or(default) as f32;
256        let mut view = aylis_core::FormView::new(name, number("max_width", 0.0));
257        view.min_width = number("min_width", 0.0);
258        view.min_height = number("min_height", 0.0);
259        view.max_height = number("max_height", 0.0);
260        view.font_scale = number("font_scale", 1.0);
261        view.spacing_scale = number("spacing_scale", 1.0);
262        if let Some(o) = v.get("orientation").and_then(Value::as_str) {
263            view.orientation = <aylis_core::ViewOrientation as aylis_core::PropEnum>::from_name(o).unwrap_or_default();
264        }
265        view.platforms = v.get("platforms").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();
266        for (component, props) in v.get("changes").and_then(Value::as_object).into_iter().flatten() {
267            let Some(id) = (if component.is_empty() { Some(form) } else { ui.find_in(form, component) }) else { continue };
268            for (property, value) in props.as_object().into_iter().flatten() {
269                let value = match property.as_str() {
270                    PARENT => value.as_str().map(|s| PropValue::String(s.to_string())),
271                    INDEX => value.as_i64().map(PropValue::Int),
272                    _ => crate::prop_from_json(ui, id, property, value).ok(),
273                };
274                if let Some(value) = value {
275                    view.changes.push(aylis_core::ViewChange { component: component.clone(), property: property.clone(), value });
276                }
277            }
278        }
279        views.push(view);
280    }
281    views
282}
283
284/// As vistas do form para o JSON (as condições e escalas só quando não são as de sempre).
285fn save_views(views: &[aylis_core::FormView]) -> Value {
286    let list: Vec<Value> = views
287        .iter()
288        .map(|v| {
289            let mut changes = Map::new();
290            for c in &v.changes {
291                let entry = changes.entry(c.component.clone()).or_insert_with(|| Value::Object(Map::new()));
292                if let Value::Object(props) = entry {
293                    props.insert(c.property.clone(), from_prop(&c.value));
294                }
295            }
296            let mut map = Map::new();
297            map.insert("name".into(), Value::from(v.name.clone()));
298            map.insert("max_width".into(), crate::value::number(v.max_width as f64));
299            for (key, value, default) in [
300                ("min_width", v.min_width, 0.0),
301                ("min_height", v.min_height, 0.0),
302                ("max_height", v.max_height, 0.0),
303                ("font_scale", v.font_scale, 1.0),
304                ("spacing_scale", v.spacing_scale, 1.0),
305            ] {
306                if value != default {
307                    map.insert(key.into(), crate::value::number(value as f64));
308                }
309            }
310            if v.orientation != aylis_core::ViewOrientation::Any {
311                map.insert("orientation".into(), Value::from(aylis_core::PropEnum::name(v.orientation)));
312            }
313            if !v.platforms.is_empty() {
314                map.insert("platforms".into(), Value::from(v.platforms.clone()));
315            }
316            map.insert("changes".into(), Value::Object(changes));
317            Value::Object(map)
318        })
319        .collect();
320    Value::Array(list)
321}
322
323fn structure(path: &str) -> impl Fn(String) -> Error + '_ {
324    move |message| Error::Structure { path: path.to_string(), message }
325}
326
327/// A mensagem do core já cita a propriedade; aqui ela vai no campo próprio.
328fn strip_property(e: aylis_core::Error) -> String {
329    match e {
330        aylis_core::Error::TypeMismatch { expected, got, .. } => format!("esperado {expected}, recebido {got}"),
331        aylis_core::Error::InvalidValue { message, .. } => message,
332        other => other.to_string(),
333    }
334}
335
336// ---------------------------------------------------------------------------
337
338/// Salva o componente e seus descendentes como documento JSON (formatado).
339///
340/// Só são gravadas as propriedades que diferem do padrão da classe. Eventos ligados
341/// por closure não têm nome e ficam de fora; os ligados por nome são gravados.
342pub fn save(ui: &Ui, root: ComponentId) -> Result<String> {
343    let value = save_value(ui, root)?;
344    Ok(crate::format::to_form_text(&value))
345}
346
347/// Como [`save`], devolvendo o valor JSON.
348pub fn save_value(ui: &Ui, root: ComponentId) -> Result<Value> {
349    let mut doc = Map::new();
350    doc.insert("aylis".into(), Value::from(FORMAT_VERSION));
351    doc.insert("root".into(), save_node(ui, root, &mut Vec::new())?);
352    Ok(Value::Object(doc))
353}
354
355fn save_node(ui: &Ui, id: ComponentId, path: &mut Vec<String>) -> Result<Value> {
356    let component = ui.component(id).ok_or_else(|| structure(&path.join(" > "))("componente inexistente".into()))?;
357    let class = component.class_name();
358    let name = ui.name(id).unwrap_or_default();
359    path.push(if name.is_empty() { class.to_string() } else { name.to_string() });
360    let here = path.join(" > ");
361
362    // Uma instância nova da classe dá os valores padrão.
363    let create = ui
364        .registry()
365        .get(class)
366        .ok_or_else(|| structure(&here)(format!("a classe {class} não está registrada; registre-a para poder salvar")))?
367        .create;
368    let defaults = create();
369
370    let mut map = Map::new();
371    map.insert("class".into(), Value::String(class.to_string()));
372    if !name.is_empty() {
373        map.insert("name".into(), Value::String(name.to_string()));
374    }
375    for info in ui.prop_infos(id) {
376        if info.read_only || info.runtime {
377            continue;
378        }
379        // O valor de uma propriedade ligada vem dos dados (o designer mostra o registro atual).
380        if ui.binding(id, info.name).is_some() {
381            continue;
382        }
383        // Com uma vista por largura ativa, grava o valor do form base (o da vista fica nela).
384        let value = match ui.view_base(id, info.name) {
385            Some(base) => base.clone(),
386            None => ui.get_declared_prop(id, info.name).map_err(|source| Error::Component { path: here.clone(), source })?,
387        };
388        let json = match (&value, info.kind) {
389            (PropValue::Event(None), _) => continue,
390            (PropValue::Component(target), PropKind::Component) => {
391                match target.and_then(|t| ui.reference_name(id, t)) {
392                    Some(target_name) => Value::String(target_name),
393                    None => continue,
394                }
395            }
396            (PropValue::Event(Some(_)), _) => from_prop(&value),
397            _ => {
398                if read_prop(defaults.as_ref(), info.name).as_ref() == Some(&value) {
399                    continue;
400                }
401                match (&value, info.kind) {
402                    // O registro e a lista de registros vão como JSON de verdade (bom para merge).
403                    (PropValue::String(text), PropKind::Record(_) | PropKind::RecordList(_)) => {
404                        match serde_json::from_str::<Value>(text) {
405                            Ok(v @ (Value::Array(_) | Value::Object(_))) => v,
406                            _ => from_prop(&value),
407                        }
408                    }
409                    _ => from_prop(&value),
410                }
411            }
412        };
413        map.insert(info.name.to_string(), json);
414    }
415
416    if !ui.bindings(id).is_empty() {
417        let mut list = Map::new();
418        for b in ui.bindings(id) {
419            let mut item = Map::new();
420            if let Some(name) = b.source.and_then(|s| ui.reference_name(id, s)) {
421                item.insert("source".into(), Value::String(name));
422            }
423            item.insert("field".into(), Value::String(b.path.clone()));
424            list.insert(b.property.clone(), Value::Object(item));
425        }
426        map.insert("bindings".into(), Value::Object(list));
427    }
428    if !ui.views(id).is_empty() {
429        map.insert("views".into(), save_views(ui.views(id)));
430    }
431
432    // O conteúdo de um Frame é o form dele (fica no arquivo do form, não aqui).
433    // Com uma vista ativa que mudou componentes de contêiner, os filhos do base.
434    let own: Vec<ComponentId> = if class == "Frame" { Vec::new() } else { ui.base_children(id) };
435    let children: Vec<Value> = own.iter().map(|&c| save_node(ui, c, path)).collect::<Result<_>>()?;
436    if !children.is_empty() {
437        map.insert("children".into(), Value::Array(children));
438    }
439    path.pop();
440    Ok(Value::Object(map))
441}