Files
tinyblocks/libraries/tinyblocks-blueprint/src/serialize.c
T
mguinhosandClaude Opus 5.5 80bd330766 Comentários: separadores com no máximo "---"
Trechos com quatro ou mais hífens dentro de comentários viram "---"
(strings não mudam).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 07:24:19 -03:00

650 lines
27 KiB
C

/*
* TinyBlocks - tinyblocks-blueprint / src/serialize.c
* JSON nativo (to/from), exportacao JSON/XML/CSV e I/O de arquivo.
*/
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <stdio.h>
#include "blueprint.h"
/* ============================================================
* Blueprint -> arvore JSON (formato nativo)
* ============================================================ */
#define PUT(o, k, val) do { TinyBlocks_JsonValue* _v = (val); tb_json_object_set((o), (k), _v); tb_json_release(_v); } while (0)
static TinyBlocks_JsonValue* jstr_arr_of(const char names[][32], int n) {
TinyBlocks_JsonValue* a = tb_json_array();
for (int i = 0; i < n; i++) {
TinyBlocks_JsonValue* v = tb_json_string(names[i]);
tb_json_array_push(a, v);
tb_json_release(v);
}
return a;
}
TinyBlocks_JsonValue* tb_blueprint_to_json(const TbBlueprint* bp) {
if (!bp) return NULL;
TinyBlocks_JsonValue* root = tb_json_object();
if (!root) return NULL;
PUT(root, "format", tb_json_string("tinyblocks-project"));
PUT(root, "version", tb_json_number(2)); /* v2: 3 bocas, REL_ARG0 = 4 */
PUT(root, "cur_tab", tb_json_number(bp->cur_tab));
TinyBlocks_JsonValue* tabs = tb_json_array();
PUT(root, "tabs", tabs);
for (int ti = 0; ti < bp->tab_count; ti++) {
const TbBpTab* T = &bp->tabs[ti];
TinyBlocks_JsonValue* jt = tb_json_object();
PUT(jt, "name", tb_json_string(T->name));
PUT(jt, "composite", tb_json_bool(T->composite));
PUT(jt, "comp_id", tb_json_number(T->comp_id));
PUT(jt, "color", tb_json_number(T->color_idx));
PUT(jt, "ws_sx", tb_json_number(T->ws_sx));
PUT(jt, "ws_sy", tb_json_number(T->ws_sy));
TinyBlocks_JsonValue* jb = tb_json_array();
PUT(jt, "blocks", jb);
for (int i = 0; i < TB_BP_MAX_WS; i++) {
const TbBpBlock* b = &T->blocks[i];
if (!b->used) continue;
TinyBlocks_JsonValue* o = tb_json_object();
PUT(o, "i", tb_json_number(i));
PUT(o, "type", tb_json_string(b->type));
PUT(o, "x", tb_json_number(b->x));
PUT(o, "y", tb_json_number(b->y));
PUT(o, "parent", tb_json_number(b->parent));
PUT(o, "prel", tb_json_number(b->prel));
PUT(o, "next", tb_json_number(b->next));
TinyBlocks_JsonValue* sub = tb_json_array();
for (int k = 0; k < 3; k++) { TinyBlocks_JsonValue* e = tb_json_number(b->sub[k]); tb_json_array_push(sub, e); tb_json_release(e); }
PUT(o, "sub", sub);
TinyBlocks_JsonValue* args = tb_json_array();
for (int s = 0; s < TB_BP_MAX_INPUTS; s++) { TinyBlocks_JsonValue* e = tb_json_number(b->args[s]); tb_json_array_push(args, e); tb_json_release(e); }
PUT(o, "args", args);
TinyBlocks_JsonValue* txt = tb_json_array();
for (int s = 0; s < TB_BP_MAX_INPUTS; s++) { TinyBlocks_JsonValue* e = tb_json_string(b->in_text[s]); tb_json_array_push(txt, e); tb_json_release(e); }
PUT(o, "in_text", txt);
PUT(o, "lit", tb_json_string(b->lit));
tb_json_array_push(jb, o);
tb_json_release(o);
}
TinyBlocks_JsonValue* top = tb_json_array();
PUT(jt, "top", top);
for (int i = 0; i < T->top_n; i++) { TinyBlocks_JsonValue* e = tb_json_number(T->top[i]); tb_json_array_push(top, e); tb_json_release(e); }
if (T->group_n > 0) {
TinyBlocks_JsonValue* jg = tb_json_array();
PUT(jt, "groups", jg);
for (int g = 0; g < T->group_n; g++) {
const TbBpGroup* G = &T->groups[g];
TinyBlocks_JsonValue* o = tb_json_object();
PUT(o, "x", tb_json_number(G->x));
PUT(o, "y", tb_json_number(G->y));
PUT(o, "w", tb_json_number(G->w));
PUT(o, "h", tb_json_number(G->h));
PUT(o, "color", tb_json_number(G->color));
PUT(o, "title", tb_json_string(G->title));
tb_json_array_push(jg, o);
tb_json_release(o);
}
}
tb_json_array_push(tabs, jt);
tb_json_release(jt);
}
TinyBlocks_JsonValue* ubs = tb_json_array();
PUT(root, "user_blocks", ubs);
for (int u = 0; u < bp->user_block_n; u++) {
const TbBpUserBlock* d = &bp->user_blocks[u];
TinyBlocks_JsonValue* jo = tb_json_object();
PUT(jo, "name", tb_json_string(d->name));
PUT(jo, "color", tb_json_number(d->color_idx));
PUT(jo, "tab", tb_json_number(d->tab_idx));
PUT(jo, "inputs", jstr_arr_of(d->input_names, d->input_count));
PUT(jo, "outputs", jstr_arr_of(d->output_names, d->output_count));
TinyBlocks_JsonValue* parts = tb_json_array();
for (int i = 0; i < d->part_n; i++) {
TinyBlocks_JsonValue* po = tb_json_object();
PUT(po, "kind", tb_json_number(d->parts[i].kind));
PUT(po, "name", tb_json_string(d->parts[i].name));
tb_json_array_push(parts, po);
tb_json_release(po);
}
PUT(jo, "parts", parts);
tb_json_array_push(ubs, jo);
tb_json_release(jo);
}
TinyBlocks_JsonValue* vars = tb_json_array();
PUT(root, "variables", vars);
for (int i = 0; i < bp->var_n; i++) {
const TbBpVar* v = &bp->vars[i];
TinyBlocks_JsonValue* jo = tb_json_object();
PUT(jo, "name", tb_json_string(v->name));
PUT(jo, "kind", tb_json_number(v->kind));
PUT(jo, "num", tb_json_number(v->num));
PUT(jo, "text", tb_json_string(v->text));
tb_json_array_push(vars, jo);
tb_json_release(jo);
}
return root;
}
/* ============================================================
* Arvore JSON -> Blueprint
* ============================================================ */
static const char* jget_str(const TinyBlocks_JsonValue* o, const char* k, const char* def) {
TinyBlocks_JsonValue* v = tb_json_object_get(o, k);
const char* s = v ? tb_json_as_string(v) : NULL;
tb_json_release(v);
return s ? s : def;
}
static double jget_num(const TinyBlocks_JsonValue* o, const char* k, double def) {
TinyBlocks_JsonValue* v = tb_json_object_get(o, k);
double d = v ? tb_json_as_number(v, def) : def;
tb_json_release(v);
return d;
}
static bool jget_bool(const TinyBlocks_JsonValue* o, const char* k, bool def) {
TinyBlocks_JsonValue* v = tb_json_object_get(o, k);
bool b = v ? tb_json_as_bool(v, def) : def;
tb_json_release(v);
return b;
}
static void jcopy_names(const TinyBlocks_JsonValue* o, const char* k, char names[][32], int max, int* n) {
*n = 0;
TinyBlocks_JsonValue* a = tb_json_object_get(o, k);
for (uint32_t i = 0; a && i < tb_json_array_length(a) && *n < max; i++) {
TinyBlocks_JsonValue* e = tb_json_array_get(a, i);
const char* s = e ? tb_json_as_string(e) : NULL;
snprintf(names[*n], 32, "%.31s", s ? s : "");
(*n)++;
tb_json_release(e);
}
tb_json_release(a);
}
TbBlueprint* tb_blueprint_from_json(const TinyBlocks_JsonValue* root) {
if (!root) return NULL;
TbBlueprint* bp = tb_blueprint_new();
if (!bp) return NULL;
int version = (int)jget_num(root, "version", 1);
TinyBlocks_JsonValue* ubs = tb_json_object_get(root, "user_blocks");
for (uint32_t u = 0; ubs && u < tb_json_array_length(ubs) && bp->user_block_n < TB_BP_MAX_UBLOCKS; u++) {
TinyBlocks_JsonValue* jo = tb_json_array_get(ubs, u);
TbBpUserBlock* d = &bp->user_blocks[bp->user_block_n];
memset(d, 0, sizeof(*d));
snprintf(d->name, sizeof(d->name), "%s", jget_str(jo, "name", ""));
d->color_idx = (int)jget_num(jo, "color", 0);
d->tab_idx = (int)jget_num(jo, "tab", -1);
jcopy_names(jo, "inputs", d->input_names, TB_BP_MAX_USLOTS, &d->input_count);
jcopy_names(jo, "outputs", d->output_names, TB_BP_MAX_USLOTS, &d->output_count);
TinyBlocks_JsonValue* parts = tb_json_object_get(jo, "parts");
d->part_n = 0;
for (uint32_t i = 0; parts && i < tb_json_array_length(parts) && d->part_n < TB_BP_MAX_UPARTS; i++) {
TinyBlocks_JsonValue* po = tb_json_array_get(parts, i);
d->parts[d->part_n].kind = (TbBpParamKind)(int)jget_num(po, "kind", 0);
snprintf(d->parts[d->part_n].name, 32, "%.31s", jget_str(po, "name", ""));
d->part_n++;
tb_json_release(po);
}
tb_json_release(parts);
tb_json_release(jo);
bp->user_block_n++;
}
tb_json_release(ubs);
TinyBlocks_JsonValue* tabs = tb_json_object_get(root, "tabs");
for (uint32_t ti = 0; tabs && ti < tb_json_array_length(tabs) && bp->tab_count < TB_BP_MAX_TABS; ti++) {
TinyBlocks_JsonValue* jt = tb_json_array_get(tabs, ti);
int idx = tb_blueprint_add_tab(bp, jget_str(jt, "name", "Codigo"), jget_bool(jt, "composite", false));
TbBpTab* T = &bp->tabs[idx];
T->comp_id = (int)jget_num(jt, "comp_id", -1);
T->color_idx = (int)jget_num(jt, "color", 0);
T->ws_sx = (float)jget_num(jt, "ws_sx", 0);
T->ws_sy = (float)jget_num(jt, "ws_sy", 0);
TinyBlocks_JsonValue* jb = tb_json_object_get(jt, "blocks");
for (uint32_t bi = 0; jb && bi < tb_json_array_length(jb); bi++) {
TinyBlocks_JsonValue* o = tb_json_array_get(jb, bi);
int i = (int)jget_num(o, "i", -1);
if (i >= 0 && i < TB_BP_MAX_WS) {
TbBpBlock* b = &T->blocks[i];
b->used = true;
snprintf(b->type, sizeof(b->type), "%s", jget_str(o, "type", ""));
b->x = (float)jget_num(o, "x", 0);
b->y = (float)jget_num(o, "y", 0);
b->parent = (int)jget_num(o, "parent", -1);
b->prel = (int)jget_num(o, "prel", TB_BP_REL_NONE);
if (version < 2 && b->prel >= 3) b->prel++; /* v1: campos comecavam em 3 */
b->next = (int)jget_num(o, "next", -1);
TinyBlocks_JsonValue* sub = tb_json_object_get(o, "sub");
for (int k = 0; k < 3; k++) { TinyBlocks_JsonValue* e = tb_json_array_get(sub, (uint32_t)k); b->sub[k] = e ? (int)tb_json_as_number(e, -1) : -1; tb_json_release(e); }
tb_json_release(sub);
TinyBlocks_JsonValue* args = tb_json_object_get(o, "args");
for (int s = 0; s < TB_BP_MAX_INPUTS; s++) { TinyBlocks_JsonValue* e = tb_json_array_get(args, (uint32_t)s); b->args[s] = e ? (int)tb_json_as_number(e, -1) : -1; tb_json_release(e); }
tb_json_release(args);
TinyBlocks_JsonValue* txt = tb_json_object_get(o, "in_text");
for (int s = 0; s < TB_BP_MAX_INPUTS; s++) {
TinyBlocks_JsonValue* e = tb_json_array_get(txt, (uint32_t)s);
if (e) { const char* sv = tb_json_as_string(e); if (sv) snprintf(b->in_text[s], sizeof(b->in_text[s]), "%s", sv); }
tb_json_release(e);
}
tb_json_release(txt);
snprintf(b->lit, sizeof(b->lit), "%s", jget_str(o, "lit", ""));
}
tb_json_release(o);
}
tb_json_release(jb);
TinyBlocks_JsonValue* top = tb_json_object_get(jt, "top");
T->top_n = 0;
for (uint32_t i = 0; top && i < tb_json_array_length(top) && T->top_n < TB_BP_MAX_WS; i++) {
TinyBlocks_JsonValue* e = tb_json_array_get(top, i);
T->top[T->top_n++] = e ? (int)tb_json_as_number(e, 0) : 0;
tb_json_release(e);
}
tb_json_release(top);
TinyBlocks_JsonValue* jg = tb_json_object_get(jt, "groups");
T->group_n = 0;
for (uint32_t i = 0; jg && i < tb_json_array_length(jg) && T->group_n < TB_BP_MAX_GROUPS; i++) {
TinyBlocks_JsonValue* o = tb_json_array_get(jg, i);
TbBpGroup* G = &T->groups[T->group_n++];
G->x = (float)jget_num(o, "x", 0);
G->y = (float)jget_num(o, "y", 0);
G->w = (float)jget_num(o, "w", 300);
G->h = (float)jget_num(o, "h", 200);
G->color = (int)jget_num(o, "color", 0);
snprintf(G->title, sizeof(G->title), "%s", jget_str(o, "title", ""));
tb_json_release(o);
}
tb_json_release(jg);
tb_json_release(jt);
}
tb_json_release(tabs);
TinyBlocks_JsonValue* vars = tb_json_object_get(root, "variables");
for (uint32_t i = 0; vars && i < tb_json_array_length(vars) && bp->var_n < TB_BP_MAX_VARS; i++) {
TinyBlocks_JsonValue* o = tb_json_array_get(vars, i);
TbBpVar* v = &bp->vars[bp->var_n];
memset(v, 0, sizeof(*v));
snprintf(v->name, sizeof(v->name), "%s", jget_str(o, "name", ""));
v->kind = (TbBpValueKind)(int)jget_num(o, "kind", TB_BP_VAL_TEXT);
v->num = jget_num(o, "num", 0);
snprintf(v->text, sizeof(v->text), "%s", jget_str(o, "text", ""));
bp->var_n++;
tb_json_release(o);
}
tb_json_release(vars);
bp->cur_tab = (int)jget_num(root, "cur_tab", 0);
return bp;
}
/* ============================================================
* Buffer de saida + escritores JSON/XML/CSV
* ============================================================ */
typedef struct { char* p; size_t len, cap; } Buf;
static void bput(Buf* b, const char* s, size_t n) {
if (b->len + n + 1 > b->cap) {
size_t nc = b->cap ? b->cap : 128;
while (nc < b->len + n + 1) nc *= 2;
char* p = (char*)realloc(b->p, nc);
if (!p) return;
b->p = p; b->cap = nc;
}
memcpy(b->p + b->len, s, n); b->len += n; b->p[b->len] = 0;
}
static void bs(Buf* b, const char* s) { bput(b, s, strlen(s)); }
static void bc(Buf* b, char c) { bput(b, &c, 1); }
static void bindent(Buf* b, int depth) { for (int i = 0; i < depth; i++) bs(b, " "); }
static void quote(Buf* b, const char* s) {
bc(b, '"');
for (const unsigned char* p = (const unsigned char*)s; *p; p++) {
switch (*p) {
case '"': bs(b, "\\\""); break;
case '\\': bs(b, "\\\\"); break;
case '\n': bs(b, "\\n"); break;
case '\r': bs(b, "\\r"); break;
case '\t': bs(b, "\\t"); break;
default: bc(b, (char)*p);
}
}
bc(b, '"');
}
static void json_rec(Buf* b, const TinyBlocks_JsonValue* j, bool pretty, int depth) {
if (!j) { bs(b, "null"); return; }
char tmp[64];
switch (tb_json_kind(j)) {
case TB_JSON_NULL: bs(b, "null"); break;
case TB_JSON_BOOL: bs(b, tb_json_as_bool(j, false) ? "true" : "false"); break;
case TB_JSON_NUMBER: {
double d = tb_json_as_number(j, 0);
if (d == (double)(long long)d) snprintf(tmp, sizeof(tmp), "%lld", (long long)d);
else snprintf(tmp, sizeof(tmp), "%g", d);
bs(b, tmp);
break;
}
case TB_JSON_STRING: quote(b, tb_json_as_string(j) ? tb_json_as_string(j) : ""); break;
case TB_JSON_ARRAY:
bc(b, '[');
for (uint32_t i = 0; i < tb_json_array_length(j); i++) {
TinyBlocks_JsonValue* e = tb_json_array_get(j, i);
if (i) bc(b, ',');
if (pretty) { bc(b, '\n'); bindent(b, depth + 1); }
json_rec(b, e, pretty, depth + 1);
tb_json_release(e);
}
if (pretty && tb_json_array_length(j)) { bc(b, '\n'); bindent(b, depth); }
bc(b, ']');
break;
case TB_JSON_OBJECT:
bc(b, '{');
for (uint32_t i = 0; i < tb_json_object_length(j); i++) {
const char* k = tb_json_object_key_at(j, i);
TinyBlocks_JsonValue* e = tb_json_object_get(j, k);
if (i) bc(b, ',');
if (pretty) { bc(b, '\n'); bindent(b, depth + 1); }
quote(b, k);
bc(b, ':');
if (pretty) bc(b, ' ');
json_rec(b, e, pretty, depth + 1);
tb_json_release(e);
}
if (pretty && tb_json_object_length(j)) { bc(b, '\n'); bindent(b, depth); }
bc(b, '}');
break;
}
}
static void esc_xml(Buf* b, const char* s) {
for (const char* q = s; *q; q++) {
switch (*q) {
case '<': bs(b, "&lt;"); break;
case '>': bs(b, "&gt;"); break;
case '&': bs(b, "&amp;"); break;
case '"': bs(b, "&quot;"); break;
default: bc(b, *q);
}
}
}
static void xattr(Buf* b, const char* k, const char* v) {
bs(b, " "); bs(b, k); bs(b, "=\""); esc_xml(b, v ? v : ""); bs(b, "\"");
}
static void xattr_num(Buf* b, const char* k, long long v) {
char t[32]; snprintf(t, sizeof(t), "%lld", v); xattr(b, k, t);
}
static void xattr_real(Buf* b, const char* k, double v) {
char t[32];
if (v == (double)(long long)v) snprintf(t, sizeof(t), "%lld", (long long)v);
else snprintf(t, sizeof(t), "%g", v);
xattr(b, k, t);
}
static void xattr_bool(Buf* b, const char* k, bool v) { xattr(b, k, v ? "true" : "false"); }
/* XML completo do projeto (escrito direto do modelo). */
static void blueprint_xml(Buf* b, const TbBlueprint* bp) {
bs(b, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
bs(b, "<tinyblocks");
xattr(b, "format", "tinyblocks-project");
xattr_num(b, "version", 2);
bs(b, ">\n");
bindent(b, 1); bs(b, "<tabs>\n");
for (int ti = 0; ti < bp->tab_count; ti++) {
const TbBpTab* T = &bp->tabs[ti];
bindent(b, 2); bs(b, "<tab");
xattr(b, "name", T->name);
xattr_bool(b, "composite", T->composite);
xattr_num(b, "comp_id", T->comp_id);
xattr_num(b, "color", T->color_idx);
xattr_real(b, "ws_sx", T->ws_sx);
xattr_real(b, "ws_sy", T->ws_sy);
bs(b, ">\n");
bindent(b, 3); bs(b, "<top>");
for (int i = 0; i < T->top_n; i++) { char t[24]; snprintf(t, sizeof(t), "<i>%d</i>", T->top[i]); bs(b, t); }
bs(b, "</top>\n");
bindent(b, 3); bs(b, "<blocks>\n");
for (int i = 0; i < TB_BP_MAX_WS; i++) {
const TbBpBlock* bl = &T->blocks[i];
if (!bl->used) continue;
bindent(b, 4); bs(b, "<block");
xattr_num(b, "i", i);
xattr(b, "type", bl->type);
xattr_real(b, "x", bl->x);
xattr_real(b, "y", bl->y);
xattr_num(b, "parent", bl->parent);
xattr_num(b, "prel", bl->prel);
xattr_num(b, "next", bl->next);
bs(b, ">\n");
bindent(b, 5); bs(b, "<sub>");
for (int k = 0; k < 3; k++) { char t[24]; snprintf(t, sizeof(t), "<i>%d</i>", bl->sub[k]); bs(b, t); }
bs(b, "</sub>\n");
bindent(b, 5); bs(b, "<args>");
for (int s = 0; s < TB_BP_MAX_INPUTS; s++) { char t[24]; snprintf(t, sizeof(t), "<i>%d</i>", bl->args[s]); bs(b, t); }
bs(b, "</args>\n");
bindent(b, 5); bs(b, "<in_text>");
for (int s = 0; s < TB_BP_MAX_INPUTS; s++) { bs(b, "<s>"); esc_xml(b, bl->in_text[s]); bs(b, "</s>"); }
bs(b, "</in_text>\n");
bindent(b, 5); bs(b, "<lit>"); esc_xml(b, bl->lit); bs(b, "</lit>\n");
bindent(b, 4); bs(b, "</block>\n");
}
bindent(b, 3); bs(b, "</blocks>\n");
bindent(b, 2); bs(b, "</tab>\n");
}
bindent(b, 1); bs(b, "</tabs>\n");
bindent(b, 1); bs(b, "<user_blocks>\n");
for (int u = 0; u < bp->user_block_n; u++) {
const TbBpUserBlock* d = &bp->user_blocks[u];
bindent(b, 2); bs(b, "<user_block");
xattr(b, "name", d->name);
xattr_num(b, "color", d->color_idx);
xattr_num(b, "tab", d->tab_idx);
bs(b, ">\n");
bindent(b, 3); bs(b, "<inputs>");
for (int i = 0; i < d->input_count; i++) { bs(b, "<s>"); esc_xml(b, d->input_names[i]); bs(b, "</s>"); }
bs(b, "</inputs>\n");
bindent(b, 3); bs(b, "<outputs>");
for (int i = 0; i < d->output_count; i++) { bs(b, "<s>"); esc_xml(b, d->output_names[i]); bs(b, "</s>"); }
bs(b, "</outputs>\n");
bindent(b, 3); bs(b, "<parts>\n");
for (int i = 0; i < d->part_n; i++) {
bindent(b, 4); bs(b, "<part");
xattr_num(b, "kind", d->parts[i].kind);
xattr(b, "name", d->parts[i].name);
bs(b, "/>\n");
}
bindent(b, 3); bs(b, "</parts>\n");
bindent(b, 2); bs(b, "</user_block>\n");
}
bindent(b, 1); bs(b, "</user_blocks>\n");
bindent(b, 1); bs(b, "<variables>\n");
for (int i = 0; i < bp->var_n; i++) {
const TbBpVar* v = &bp->vars[i];
bindent(b, 2); bs(b, "<var");
xattr(b, "name", v->name);
xattr_num(b, "kind", v->kind);
xattr_real(b, "num", v->num);
xattr(b, "text", v->text);
bs(b, "/>\n");
}
bindent(b, 1); bs(b, "</variables>\n");
bs(b, "</tinyblocks>\n");
}
static bool csv_needs_quote(const char* s) {
for (; *s; s++) if (*s == ',' || *s == '"' || *s == '\n' || *s == '\r') return true;
return false;
}
static void csv_field(Buf* b, const char* s) {
if (!csv_needs_quote(s)) { bs(b, s); return; }
bc(b, '"');
for (; *s; s++) { if (*s == '"') bc(b, '"'); bc(b, *s); }
bc(b, '"');
}
/* data = array de objetos; colunas vem das chaves do primeiro. */
static void csv_rec(Buf* b, const TinyBlocks_JsonValue* data) {
if (tb_json_kind(data) != TB_JSON_ARRAY) return;
TinyBlocks_JsonValue* first = tb_json_array_get(data, 0);
if (!first) { tb_json_release(first); return; }
uint32_t ncol = tb_json_object_length(first);
for (uint32_t j = 0; j < ncol; j++) { if (j) bc(b, ','); csv_field(b, tb_json_object_key_at(first, j)); }
bc(b, '\n');
for (uint32_t i = 0; i < tb_json_array_length(data); i++) {
TinyBlocks_JsonValue* o = tb_json_array_get(data, i);
for (uint32_t j = 0; j < ncol; j++) {
if (j) bc(b, ',');
TinyBlocks_JsonValue* v = tb_json_object_get(o, tb_json_object_key_at(first, j));
char num[32];
const char* s = "";
if (v && tb_json_kind(v) == TB_JSON_STRING) s = tb_json_as_string(v);
else if (v && tb_json_kind(v) == TB_JSON_NUMBER) {
double d = tb_json_as_number(v, 0);
if (d == (double)(long long)d) snprintf(num, sizeof(num), "%lld", (long long)d);
else snprintf(num, sizeof(num), "%g", d);
s = num;
} else if (v && tb_json_kind(v) == TB_JSON_BOOL) {
s = tb_json_as_bool(v, false) ? "true" : "false";
}
csv_field(b, s);
tb_json_release(v);
}
bc(b, '\n');
tb_json_release(o);
}
tb_json_release(first);
}
/* Tabela plana de blocos para o CSV. */
static TinyBlocks_JsonValue* blueprint_csv_tree(const TbBlueprint* bp) {
TinyBlocks_JsonValue* arr = tb_json_array();
for (int ti = 0; ti < bp->tab_count; ti++) {
const TbBpTab* T = &bp->tabs[ti];
for (int i = 0; i < TB_BP_MAX_WS; i++) {
const TbBpBlock* b = &T->blocks[i];
if (!b->used) continue;
TinyBlocks_JsonValue* o = tb_json_object();
PUT(o, "aba", tb_json_string(T->name));
PUT(o, "tipo", tb_json_string(b->type));
PUT(o, "x", tb_json_number(b->x));
PUT(o, "y", tb_json_number(b->y));
PUT(o, "texto", tb_json_string(b->in_text[0]));
tb_json_array_push(arr, o);
tb_json_release(o);
}
}
return arr;
}
/* -- Formatos (TbBpFormat) --- */
static char* buf_take(Buf* b) {
if (!b->p) { b->p = (char*)malloc(1); if (b->p) b->p[0] = 0; }
return b->p;
}
static char* json_write(const TbBlueprint* bp, bool pretty) {
Buf b = {0};
TinyBlocks_JsonValue* root = tb_blueprint_to_json(bp);
json_rec(&b, root, pretty, 0); bc(&b, '\n');
tb_json_release(root);
return buf_take(&b);
}
static TbBlueprint* json_read(const char* text, char* err, size_t errcap) {
TinyBlocks_JsonValue* root = tb_json_parse(text, err, errcap);
if (!root) return NULL;
TinyBlocks_JsonValue* fv = tb_json_object_get(root, "format");
const char* fmt_s = fv ? tb_json_as_string(fv) : NULL;
bool ok = fmt_s && strcmp(fmt_s, "tinyblocks-project") == 0;
tb_json_release(fv);
if (!ok) { if (err && errcap) snprintf(err, errcap, "formato de projeto desconhecido"); tb_json_release(root); return NULL; }
TbBlueprint* bp = tb_blueprint_from_json(root);
tb_json_release(root);
return bp;
}
static char* xml_write(const TbBlueprint* bp, bool pretty) {
(void)pretty;
Buf b = {0};
blueprint_xml(&b, bp);
return buf_take(&b);
}
static char* csv_write(const TbBlueprint* bp, bool pretty) {
(void)pretty;
Buf b = {0};
TinyBlocks_JsonValue* data = blueprint_csv_tree(bp);
csv_rec(&b, data);
tb_json_release(data);
return buf_take(&b);
}
static const TbBpFormat s_formats[] = {
{ TB_BP_FMT_JSON, "json", ".json", json_write, json_read },
{ TB_BP_FMT_XML, "xml", ".xml", xml_write, NULL },
{ TB_BP_FMT_CSV, "csv", ".csv", csv_write, NULL },
};
const TbBpFormat* tb_blueprint_format(int fmt) {
for (size_t i = 0; i < sizeof(s_formats) / sizeof(s_formats[0]); i++)
if (s_formats[i].id == fmt) return &s_formats[i];
return NULL;
}
const TbBpFormat* tb_blueprint_format_for_path(const char* path) {
const char* dot = path ? strrchr(path, '.') : NULL;
for (size_t i = 0; dot && i < sizeof(s_formats) / sizeof(s_formats[0]); i++)
if (strcasecmp(dot, s_formats[i].ext) == 0) return &s_formats[i];
return NULL;
}
char* tb_blueprint_serialize(const TbBlueprint* bp, int fmt, bool pretty) {
const TbBpFormat* f = tb_blueprint_format(fmt);
return (f ? f : &s_formats[0])->write(bp, pretty);
}
TbBlueprint* tb_blueprint_parse(const char* text, int fmt, char* err, size_t errcap) {
const TbBpFormat* f = tb_blueprint_format(fmt);
if (!f || !f->read) {
if (err && errcap) snprintf(err, errcap, "o formato %s so exporta", f ? f->name : "?");
return NULL;
}
return f->read(text, err, errcap);
}
bool tb_blueprint_save_file(const TbBlueprint* bp, const char* path, int fmt, bool pretty) {
char* s = tb_blueprint_serialize(bp, fmt, pretty);
if (!s) return false;
FILE* f = fopen(path, "wb");
if (!f) { free(s); return false; }
size_t n = strlen(s);
size_t w = fwrite(s, 1, n, f);
fclose(f);
free(s);
return w == n;
}
TbBlueprint* tb_blueprint_load_file(const char* path, char* err, size_t errcap) {
FILE* f = fopen(path, "rb");
if (!f) { if (err && errcap) snprintf(err, errcap, "nao abriu %s", path); return NULL; }
fseek(f, 0, SEEK_END); long sz = ftell(f); fseek(f, 0, SEEK_SET);
if (sz < 0 || sz > 256L * 1024 * 1024) { fclose(f); if (err && errcap) snprintf(err, errcap, "arquivo grande demais"); return NULL; }
char* buf = (char*)malloc((size_t)sz + 1);
if (!buf) { fclose(f); return NULL; }
size_t rd = fread(buf, 1, (size_t)sz, f);
buf[rd] = 0; fclose(f);
TbBlueprint* bp = tb_blueprint_parse(buf, TB_BP_FMT_JSON, err, errcap);
free(buf);
return bp;
}