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` como texto é a propriedade da lista (`DataRepeater`, `VirtualList`:
158            // "lblNome=nome"); como objeto, as ligações de propriedade a campo (abaixo). Pulada
159            // sempre, a da lista sumia ao carregar o form (relatório do RTSPlayer, 10/11).
160            if RESERVED.contains(&key.as_str()) && !(key == "bindings" && value.is_string()) {
161                continue;
162            }
163            if let Err(e) = self.property(id, class, key, value, path) {
164                self.soft(e)?;
165            }
166        }
167
168        // "bindings": { "text": { "source": "dsClientes", "field": "nome" } }
169        if let Some(Value::Object(list)) = obj.get("bindings") {
170            for (property, b) in list {
171                let source = b.get("source").and_then(Value::as_str).unwrap_or("").to_string();
172                let field = b.get("field").and_then(Value::as_str).unwrap_or("").to_string();
173                self.bindings.push((id, property.clone(), source, field));
174            }
175        }
176        // "views": [ { "name": "phone", "max_width": 599, "changes": { "btn": { "visible": false } } } ]
177        if let Some(views) = obj.get("views").filter(|v| v.is_array()) {
178            self.views.push((id, views.clone()));
179        }
180
181        // O Frame mostra o form de `form`: filhos dele no JSON tomavam o lugar desse form, e
182        // excluir o Frame os jogava no form de fora (relatório do InsightDB, 11/11).
183        if class == "Frame" && obj.get("children").and_then(Value::as_array).is_some_and(|c| !c.is_empty()) {
184            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()))?;
185            path.pop();
186            return Ok(id);
187        }
188        match obj.get("children") {
189            None | Some(Value::Null) => {}
190            Some(Value::Array(children)) => {
191                for child in children {
192                    self.node(child, Some(id), path)?;
193                }
194            }
195            Some(other) => {
196                return Err(structure(&here(path))(format!("\"children\" deve ser uma lista, recebido {}", describe(other))));
197            }
198        }
199        path.pop();
200        Ok(id)
201    }
202
203    /// Uma propriedade do componente `id` (da classe `class`) pelo JSON.
204    fn property(&mut self, id: ComponentId, class: &str, key: &str, value: &Value, path: &[String]) -> Result<()> {
205        let fail = |message: String| Error::Property { path: path.join(" > "), property: key.to_string(), message };
206        // "margins.left": 4
207        if key.contains('.') {
208            let v = value.as_f64().ok_or_else(|| fail(format!("esperado número, recebido {}", describe(value))))?;
209            return self.ui.set_prop(id, key, v).map_err(|e| fail(e.to_string()));
210        }
211        let info = self.ui.prop_info(id, key).ok_or_else(|| fail(format!("a classe {class} não tem esta propriedade")))?;
212        let prop = to_prop(value, info.kind, self.ui.theme()).map_err(fail)?;
213        if info.kind == PropKind::Component {
214            if let PropValue::String(target) = prop {
215                self.deferred.push((id, key.to_string(), target, path.join(" > ")));
216            }
217            return Ok(());
218        }
219        // Textos da tela: traduzidos para o idioma atual (o original fica lembrado).
220        if let (PropValue::String(text), true) = (&prop, aylis_core::i18n::TRANSLATABLE.contains(&key)) {
221            let text = text.clone();
222            return self.ui.set_translated(id, key, &text).map_err(|e| fail(strip_property(e)));
223        }
224        self.ui.set_prop(id, key, prop).map_err(|e| fail(strip_property(e)))
225    }
226
227    /// Resolve as referências por nome depois que tudo existe.
228    pub(crate) fn fixup(&mut self) -> Result<()> {
229        for (id, property, target, path) in std::mem::take(&mut self.deferred) {
230            if let Err(e) = self.ui.set_prop(id, &property, target.as_str()) {
231                self.soft(Error::Property { path, property, message: strip_property(e) })?;
232            }
233        }
234        for (id, property, source, field) in std::mem::take(&mut self.bindings) {
235            let source = self.ui.resolve_reference(id, &source);
236            self.ui.set_binding(id, &property, source, &field);
237        }
238        for (form, list) in std::mem::take(&mut self.views) {
239            let views = load_views(self.ui, form, &list);
240            self.ui.set_views(form, views);
241        }
242        Ok(())
243    }
244}
245
246/// As vistas do JSON, com os valores no tipo de cada propriedade:
247/// `[{ "name", "max_width", "min_width", "min_height", "max_height", "orientation",
248/// "platforms": [...], "font_scale", "spacing_scale", "changes": { "componente": { "prop": valor,
249/// "parent": "pnlRodape", "index": 0 } } }]` (só `name` é obrigatório). O que não existe mais
250/// (componente, propriedade) fica de fora.
251fn load_views(ui: &Ui, form: ComponentId, list: &Value) -> Vec<aylis_core::FormView> {
252    use aylis_core::views::{INDEX, PARENT};
253    let mut views = Vec::new();
254    for v in list.as_array().into_iter().flatten() {
255        let Some(name) = v.get("name").and_then(Value::as_str) else { continue };
256        let number = |key: &str, default: f64| v.get(key).and_then(Value::as_f64).unwrap_or(default) as f32;
257        let mut view = aylis_core::FormView::new(name, number("max_width", 0.0));
258        view.min_width = number("min_width", 0.0);
259        view.min_height = number("min_height", 0.0);
260        view.max_height = number("max_height", 0.0);
261        view.font_scale = number("font_scale", 1.0);
262        view.spacing_scale = number("spacing_scale", 1.0);
263        if let Some(o) = v.get("orientation").and_then(Value::as_str) {
264            view.orientation = <aylis_core::ViewOrientation as aylis_core::PropEnum>::from_name(o).unwrap_or_default();
265        }
266        view.platforms = v.get("platforms").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();
267        for (component, props) in v.get("changes").and_then(Value::as_object).into_iter().flatten() {
268            let Some(id) = (if component.is_empty() { Some(form) } else { ui.find_in(form, component) }) else { continue };
269            for (property, value) in props.as_object().into_iter().flatten() {
270                let value = match property.as_str() {
271                    PARENT => value.as_str().map(|s| PropValue::String(s.to_string())),
272                    INDEX => value.as_i64().map(PropValue::Int),
273                    _ => crate::prop_from_json(ui, id, property, value).ok(),
274                };
275                if let Some(value) = value {
276                    view.changes.push(aylis_core::ViewChange { component: component.clone(), property: property.clone(), value });
277                }
278            }
279        }
280        views.push(view);
281    }
282    views
283}
284
285/// As vistas do form para o JSON (as condições e escalas só quando não são as de sempre).
286fn save_views(views: &[aylis_core::FormView]) -> Value {
287    let list: Vec<Value> = views
288        .iter()
289        .map(|v| {
290            let mut changes = Map::new();
291            for c in &v.changes {
292                let entry = changes.entry(c.component.clone()).or_insert_with(|| Value::Object(Map::new()));
293                if let Value::Object(props) = entry {
294                    props.insert(c.property.clone(), from_prop(&c.value));
295                }
296            }
297            let mut map = Map::new();
298            map.insert("name".into(), Value::from(v.name.clone()));
299            map.insert("max_width".into(), crate::value::number(v.max_width as f64));
300            for (key, value, default) in [
301                ("min_width", v.min_width, 0.0),
302                ("min_height", v.min_height, 0.0),
303                ("max_height", v.max_height, 0.0),
304                ("font_scale", v.font_scale, 1.0),
305                ("spacing_scale", v.spacing_scale, 1.0),
306            ] {
307                if value != default {
308                    map.insert(key.into(), crate::value::number(value as f64));
309                }
310            }
311            if v.orientation != aylis_core::ViewOrientation::Any {
312                map.insert("orientation".into(), Value::from(aylis_core::PropEnum::name(v.orientation)));
313            }
314            if !v.platforms.is_empty() {
315                map.insert("platforms".into(), Value::from(v.platforms.clone()));
316            }
317            map.insert("changes".into(), Value::Object(changes));
318            Value::Object(map)
319        })
320        .collect();
321    Value::Array(list)
322}
323
324fn structure(path: &str) -> impl Fn(String) -> Error + '_ {
325    move |message| Error::Structure { path: path.to_string(), message }
326}
327
328/// A mensagem do core já cita a propriedade; aqui ela vai no campo próprio.
329fn strip_property(e: aylis_core::Error) -> String {
330    match e {
331        aylis_core::Error::TypeMismatch { expected, got, .. } => format!("esperado {expected}, recebido {got}"),
332        aylis_core::Error::InvalidValue { message, .. } => message,
333        other => other.to_string(),
334    }
335}
336
337// ---------------------------------------------------------------------------
338
339/// Salva o componente e seus descendentes como documento JSON (formatado).
340///
341/// Só são gravadas as propriedades que diferem do padrão da classe. Eventos ligados
342/// por closure não têm nome e ficam de fora; os ligados por nome são gravados.
343pub fn save(ui: &Ui, root: ComponentId) -> Result<String> {
344    let value = save_value(ui, root)?;
345    Ok(crate::format::to_form_text(&value))
346}
347
348/// Como [`save`], devolvendo o valor JSON.
349pub fn save_value(ui: &Ui, root: ComponentId) -> Result<Value> {
350    let mut doc = Map::new();
351    doc.insert("aylis".into(), Value::from(FORMAT_VERSION));
352    doc.insert("root".into(), save_node(ui, root, &mut Vec::new())?);
353    Ok(Value::Object(doc))
354}
355
356fn save_node(ui: &Ui, id: ComponentId, path: &mut Vec<String>) -> Result<Value> {
357    let component = ui.component(id).ok_or_else(|| structure(&path.join(" > "))("componente inexistente".into()))?;
358    let class = component.class_name();
359    let name = ui.name(id).unwrap_or_default();
360    path.push(if name.is_empty() { class.to_string() } else { name.to_string() });
361    let here = path.join(" > ");
362
363    // Uma instância nova da classe dá os valores padrão.
364    let create = ui
365        .registry()
366        .get(class)
367        .ok_or_else(|| structure(&here)(format!("a classe {class} não está registrada; registre-a para poder salvar")))?
368        .create;
369    let defaults = create();
370
371    let mut map = Map::new();
372    map.insert("class".into(), Value::String(class.to_string()));
373    if !name.is_empty() {
374        map.insert("name".into(), Value::String(name.to_string()));
375    }
376    for info in ui.prop_infos(id) {
377        if info.read_only || info.runtime {
378            continue;
379        }
380        // O valor de uma propriedade ligada vem dos dados (o designer mostra o registro atual).
381        if ui.binding(id, info.name).is_some() {
382            continue;
383        }
384        // Com uma vista por largura ativa, grava o valor do form base (o da vista fica nela).
385        let value = match ui.view_base(id, info.name) {
386            Some(base) => base.clone(),
387            None => ui.get_declared_prop(id, info.name).map_err(|source| Error::Component { path: here.clone(), source })?,
388        };
389        let json = match (&value, info.kind) {
390            (PropValue::Event(None), _) => continue,
391            (PropValue::Component(target), PropKind::Component) => {
392                match target.and_then(|t| ui.reference_name(id, t)) {
393                    Some(target_name) => Value::String(target_name),
394                    None => continue,
395                }
396            }
397            (PropValue::Event(Some(_)), _) => from_prop(&value),
398            _ => {
399                if read_prop(defaults.as_ref(), info.name).as_ref() == Some(&value) {
400                    continue;
401                }
402                from_prop(&value)
403            }
404        };
405        map.insert(info.name.to_string(), json);
406    }
407
408    if !ui.bindings(id).is_empty() {
409        let mut list = Map::new();
410        for b in ui.bindings(id) {
411            let mut item = Map::new();
412            if let Some(name) = b.source.and_then(|s| ui.reference_name(id, s)) {
413                item.insert("source".into(), Value::String(name));
414            }
415            item.insert("field".into(), Value::String(b.path.clone()));
416            list.insert(b.property.clone(), Value::Object(item));
417        }
418        map.insert("bindings".into(), Value::Object(list));
419    }
420    if !ui.views(id).is_empty() {
421        map.insert("views".into(), save_views(ui.views(id)));
422    }
423
424    // O conteúdo de um Frame é o form dele (fica no arquivo do form, não aqui).
425    // Com uma vista ativa que mudou componentes de contêiner, os filhos do base.
426    let own: Vec<ComponentId> = if class == "Frame" { Vec::new() } else { ui.base_children(id) };
427    let children: Vec<Value> = own.iter().map(|&c| save_node(ui, c, path)).collect::<Result<_>>()?;
428    if !children.is_empty() {
429        map.insert("children".into(), Value::Array(children));
430    }
431    path.pop();
432    Ok(Value::Object(map))
433}