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 (como o `.dfm` na VCL).
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 (como o `Loaded` do Delphi): 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 (como o
228    /// `GlobalFixupReferences` do Delphi).
229    pub(crate) fn fixup(&mut self) -> Result<()> {
230        for (id, property, target, path) in std::mem::take(&mut self.deferred) {
231            if let Err(e) = self.ui.set_prop(id, &property, target.as_str()) {
232                self.soft(Error::Property { path, property, message: strip_property(e) })?;
233            }
234        }
235        for (id, property, source, field) in std::mem::take(&mut self.bindings) {
236            let source = self.ui.resolve_reference(id, &source);
237            self.ui.set_binding(id, &property, source, &field);
238        }
239        for (form, list) in std::mem::take(&mut self.views) {
240            let views = load_views(self.ui, form, &list);
241            self.ui.set_views(form, views);
242        }
243        Ok(())
244    }
245}
246
247/// As vistas do JSON, com os valores no tipo de cada propriedade:
248/// `[{ "name", "max_width", "min_width", "min_height", "max_height", "orientation",
249/// "platforms": [...], "font_scale", "spacing_scale", "changes": { "componente": { "prop": valor,
250/// "parent": "pnlRodape", "index": 0 } } }]` (só `name` é obrigatório). O que não existe mais
251/// (componente, propriedade) fica de fora.
252fn load_views(ui: &Ui, form: ComponentId, list: &Value) -> Vec<aylis_core::FormView> {
253    use aylis_core::views::{INDEX, PARENT};
254    let mut views = Vec::new();
255    for v in list.as_array().into_iter().flatten() {
256        let Some(name) = v.get("name").and_then(Value::as_str) else { continue };
257        let number = |key: &str, default: f64| v.get(key).and_then(Value::as_f64).unwrap_or(default) as f32;
258        let mut view = aylis_core::FormView::new(name, number("max_width", 0.0));
259        view.min_width = number("min_width", 0.0);
260        view.min_height = number("min_height", 0.0);
261        view.max_height = number("max_height", 0.0);
262        view.font_scale = number("font_scale", 1.0);
263        view.spacing_scale = number("spacing_scale", 1.0);
264        if let Some(o) = v.get("orientation").and_then(Value::as_str) {
265            view.orientation = <aylis_core::ViewOrientation as aylis_core::PropEnum>::from_name(o).unwrap_or_default();
266        }
267        view.platforms = v.get("platforms").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();
268        for (component, props) in v.get("changes").and_then(Value::as_object).into_iter().flatten() {
269            let Some(id) = (if component.is_empty() { Some(form) } else { ui.find_in(form, component) }) else { continue };
270            for (property, value) in props.as_object().into_iter().flatten() {
271                let value = match property.as_str() {
272                    PARENT => value.as_str().map(|s| PropValue::String(s.to_string())),
273                    INDEX => value.as_i64().map(PropValue::Int),
274                    _ => crate::prop_from_json(ui, id, property, value).ok(),
275                };
276                if let Some(value) = value {
277                    view.changes.push(aylis_core::ViewChange { component: component.clone(), property: property.clone(), value });
278                }
279            }
280        }
281        views.push(view);
282    }
283    views
284}
285
286/// As vistas do form para o JSON (as condições e escalas só quando não são as de sempre).
287fn save_views(views: &[aylis_core::FormView]) -> Value {
288    let list: Vec<Value> = views
289        .iter()
290        .map(|v| {
291            let mut changes = Map::new();
292            for c in &v.changes {
293                let entry = changes.entry(c.component.clone()).or_insert_with(|| Value::Object(Map::new()));
294                if let Value::Object(props) = entry {
295                    props.insert(c.property.clone(), from_prop(&c.value));
296                }
297            }
298            let mut map = Map::new();
299            map.insert("name".into(), Value::from(v.name.clone()));
300            map.insert("max_width".into(), crate::value::number(v.max_width as f64));
301            for (key, value, default) in [
302                ("min_width", v.min_width, 0.0),
303                ("min_height", v.min_height, 0.0),
304                ("max_height", v.max_height, 0.0),
305                ("font_scale", v.font_scale, 1.0),
306                ("spacing_scale", v.spacing_scale, 1.0),
307            ] {
308                if value != default {
309                    map.insert(key.into(), crate::value::number(value as f64));
310                }
311            }
312            if v.orientation != aylis_core::ViewOrientation::Any {
313                map.insert("orientation".into(), Value::from(aylis_core::PropEnum::name(v.orientation)));
314            }
315            if !v.platforms.is_empty() {
316                map.insert("platforms".into(), Value::from(v.platforms.clone()));
317            }
318            map.insert("changes".into(), Value::Object(changes));
319            Value::Object(map)
320        })
321        .collect();
322    Value::Array(list)
323}
324
325fn structure(path: &str) -> impl Fn(String) -> Error + '_ {
326    move |message| Error::Structure { path: path.to_string(), message }
327}
328
329/// A mensagem do core já cita a propriedade; aqui ela vai no campo próprio.
330fn strip_property(e: aylis_core::Error) -> String {
331    match e {
332        aylis_core::Error::TypeMismatch { expected, got, .. } => format!("esperado {expected}, recebido {got}"),
333        aylis_core::Error::InvalidValue { message, .. } => message,
334        other => other.to_string(),
335    }
336}
337
338// ---------------------------------------------------------------------------
339
340/// Salva o componente e seus descendentes como documento JSON (formatado).
341///
342/// Só são gravadas as propriedades que diferem do padrão da classe. Eventos ligados
343/// por closure não têm nome e ficam de fora; os ligados por nome são gravados.
344pub fn save(ui: &Ui, root: ComponentId) -> Result<String> {
345    let value = save_value(ui, root)?;
346    Ok(crate::format::to_form_text(&value))
347}
348
349/// Como [`save`], devolvendo o valor JSON.
350pub fn save_value(ui: &Ui, root: ComponentId) -> Result<Value> {
351    let mut doc = Map::new();
352    doc.insert("aylis".into(), Value::from(FORMAT_VERSION));
353    doc.insert("root".into(), save_node(ui, root, &mut Vec::new())?);
354    Ok(Value::Object(doc))
355}
356
357fn save_node(ui: &Ui, id: ComponentId, path: &mut Vec<String>) -> Result<Value> {
358    let component = ui.component(id).ok_or_else(|| structure(&path.join(" > "))("componente inexistente".into()))?;
359    let class = component.class_name();
360    let name = ui.name(id).unwrap_or_default();
361    path.push(if name.is_empty() { class.to_string() } else { name.to_string() });
362    let here = path.join(" > ");
363
364    // Uma instância nova da classe dá os valores padrão.
365    let create = ui
366        .registry()
367        .get(class)
368        .ok_or_else(|| structure(&here)(format!("a classe {class} não está registrada; registre-a para poder salvar")))?
369        .create;
370    let defaults = create();
371
372    let mut map = Map::new();
373    map.insert("class".into(), Value::String(class.to_string()));
374    if !name.is_empty() {
375        map.insert("name".into(), Value::String(name.to_string()));
376    }
377    for info in ui.prop_infos(id) {
378        if info.read_only || info.runtime {
379            continue;
380        }
381        // O valor de uma propriedade ligada vem dos dados (o designer mostra o registro atual).
382        if ui.binding(id, info.name).is_some() {
383            continue;
384        }
385        // Com uma vista por largura ativa, grava o valor do form base (o da vista fica nela).
386        let value = match ui.view_base(id, info.name) {
387            Some(base) => base.clone(),
388            None => ui.get_declared_prop(id, info.name).map_err(|source| Error::Component { path: here.clone(), source })?,
389        };
390        let json = match (&value, info.kind) {
391            (PropValue::Event(None), _) => continue,
392            (PropValue::Component(target), PropKind::Component) => {
393                match target.and_then(|t| ui.reference_name(id, t)) {
394                    Some(target_name) => Value::String(target_name),
395                    None => continue,
396                }
397            }
398            (PropValue::Event(Some(_)), _) => from_prop(&value),
399            _ => {
400                if read_prop(defaults.as_ref(), info.name).as_ref() == Some(&value) {
401                    continue;
402                }
403                from_prop(&value)
404            }
405        };
406        map.insert(info.name.to_string(), json);
407    }
408
409    if !ui.bindings(id).is_empty() {
410        let mut list = Map::new();
411        for b in ui.bindings(id) {
412            let mut item = Map::new();
413            if let Some(name) = b.source.and_then(|s| ui.reference_name(id, s)) {
414                item.insert("source".into(), Value::String(name));
415            }
416            item.insert("field".into(), Value::String(b.path.clone()));
417            list.insert(b.property.clone(), Value::Object(item));
418        }
419        map.insert("bindings".into(), Value::Object(list));
420    }
421    if !ui.views(id).is_empty() {
422        map.insert("views".into(), save_views(ui.views(id)));
423    }
424
425    // O conteúdo de um Frame é o form dele (fica no arquivo do form, não aqui).
426    // Com uma vista ativa que mudou componentes de contêiner, os filhos do base.
427    let own: Vec<ComponentId> = if class == "Frame" { Vec::new() } else { ui.base_children(id) };
428    let children: Vec<Value> = own.iter().map(|&c| save_node(ui, c, path)).collect::<Result<_>>()?;
429    if !children.is_empty() {
430        map.insert("children".into(), Value::Array(children));
431    }
432    path.pop();
433    Ok(Value::Object(map))
434}