Notação do fórum do Scratch (scratchblocks): exportar e importar scripts

- Nova library tinyblocks-scratchblocks: converte uma aba (TbBpTab da
  blueprint) para o texto do fórum e de volta. Blocos com equivalente no
  Scratch saem em inglês ("when flag clicked", "repeat (10)", "set [x v]
  to (0)", "if <> then ... else ... end", listas, operadores, sensores);
  os do TinyBlocks usam o rótulo em português com "::categoria". A
  importação aceita as duas formas, comentários "//", "::categoria",
  escapes e as tags [scratchblocks]. Forma, tipo dos campos e categoria
  vêm por callbacks (a library não conhece o editor).
- Editor: "Exportar scratchblocks" no menu Exportar (aba atual -> .txt);
  "Abrir" aceita .txt/.sb e cria uma aba com os scripts.
- test-scratchblocks + cenário de ida e volta no harness.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mguinhosandClaude Opus 5.5 committed 2026-10-22 18:04:22 -03:00
1 parent 649ae14fb3
commit d842890b0b
11 files changed
+1255 -38

No files matched your search

+3 -1
View File
@@ -15,6 +15,7 @@ CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \
-I../tinyblocks-api/include \
-I../tinyblocks-libman/include \
-I../tinyblocks-syntax/include \
-I../tinyblocks-scratchblocks/include \
-Ilibraries/tinyblocks-editor-widgets/include \
-Ilibraries/tinyblocks-editor-image/include \
-Ilibraries/tinyblocks-editor-files/include
@@ -46,7 +47,8 @@ $(BUILD)/tb_editor.o: src/tb_editor.c include/tb_editor.h internal/tb_editor_int
../tinyblocks-environ/include/tb_environ.h \
../tinyblocks-api/include/tb_api.h \
../tinyblocks-libman/include/tb_libman.h \
../tinyblocks-syntax/include/tb_syntax.h
../tinyblocks-syntax/include/tb_syntax.h \
../tinyblocks-scratchblocks/include/tb_scratchblocks.h
@mkdir -p $(BUILD)
$(CC) $(CFLAGS) -fPIC -c $< -o $@
@@ -593,11 +593,12 @@ typedef struct { FlyKind kind; int cat; int bi; float y, h; } FlyItem;
typedef enum { ES_IDLE, ES_PRESS, ES_DRAG, ES_PAN } EdSt;
typedef enum { SN_NONE, SN_NEXT, SN_SUB, SN_ABOVE, SN_ARG } SnapKind;
enum { CM_DUPLICATE, CM_DELETE, CM_EDIT_DEF, CM_CLEANUP, CM_NEW_COMPOSITE,
CM_EXP_JSON, CM_EXP_XML, CM_EXP_CSV };
CM_EXP_JSON, CM_EXP_XML, CM_EXP_CSV, CM_EXP_SB };
/* Modos da barra de caminho do menu (path_input) */
enum { PM_NONE, PM_LIB, PM_LOAD, PM_SAVE, PM_EXP_JSON, PM_EXP_XML, PM_EXP_CSV,
PM_IMGLOAD, PM_IMSAVE, PM_IMADDR, PM_IMADDV, PM_CODELOAD, PM_CODESAVE };
PM_IMGLOAD, PM_IMSAVE, PM_IMADDR, PM_IMADDV, PM_CODELOAD, PM_CODESAVE,
PM_EXP_SB };
/* Explorador de arquivos (library privada tinyblocks-editor-files).
O estado vive aqui para sobreviver ao hot reload do modulo. */
@@ -493,11 +493,12 @@ static void fd_mode_info(FileDlg* F, int mode) {
bool save = false;
switch (mode) {
case PM_LIB: title = "Carregar library"; ok = "Carregar"; filter = ".so"; break;
case PM_LOAD: title = "Abrir projeto"; filter = ".json"; break;
case PM_LOAD: title = "Abrir projeto"; filter = ".json .txt .sb"; break;
case PM_SAVE: title = "Salvar projeto"; ok = "Salvar"; filter = ".json"; save = true; break;
case PM_EXP_JSON: title = "Exportar como JSON"; ok = "Exportar"; filter = ".json"; save = true; break;
case PM_EXP_XML: title = "Exportar como XML"; ok = "Exportar"; filter = ".xml"; save = true; break;
case PM_EXP_CSV: title = "Exportar como CSV"; ok = "Exportar"; filter = ".csv"; save = true; break;
case PM_EXP_SB: title = "Exportar scratchblocks"; ok = "Exportar"; filter = ".txt"; save = true; break;
case PM_IMGLOAD: title = "Abrir imagem"; filter = ".png .jpg .jpeg .bmp .ppm .svg"; break;
case PM_IMSAVE: title = "Salvar imagem"; ok = "Salvar"; filter = ".png .jpg .jpeg .bmp .ppm"; save = true; break;
case PM_IMADDR: title = "Adicionar camada raster"; ok = "Adicionar"; filter = ".png .jpg .jpeg .bmp .ppm .svg"; break;
+171 -25
View File
@@ -43,6 +43,8 @@
#include <tb_libman.h>
#include <tb_environ.h>
#include <tb_syntax.h>
#include <tb_scratchblocks.h>
#include <strings.h>
#include "tb_stage_widget.h"
#include "../include/tb_editor.h"
@@ -2410,6 +2412,34 @@ static TbBlueprint* ed_to_blueprint(Ed* ed) {
return bp;
}
/* Blocos de uma aba da blueprint -> aba do editor (os mesmos indices) */
static void bp_tab_load(Ed* ed, const TbBpTab* B, Tab* T) {
for (int i = 0; i < MAX_WS; i++) {
memset(&T->ws[i], 0, sizeof(T->ws[i]));
T->ws[i].parent = -1; T->ws[i].prel = REL_NONE; T->ws[i].next = -1;
T->ws[i].sub[0] = T->ws[i].sub[1] = -1;
for (int s = 0; s < MAX_INPUTS; s++) T->ws[i].args[s] = -1;
}
for (int i = 0; i < MAX_WS; i++) {
const TbBpBlock* o = &B->blocks[i];
if (!o->used) continue;
EdBlock* b = &T->ws[i];
b->used = true;
snprintf(b->type_name, sizeof(b->type_name), "%s", o->type);
b->type = b->type_name[0] ? tb_type_block_find(ed->rt, b->type_name) : NULL;
b->x = o->x; b->y = o->y;
b->parent = o->parent; b->prel = o->prel; b->next = o->next;
for (int k = 0; k < 2; k++) b->sub[k] = o->sub[k];
for (int s = 0; s < MAX_INPUTS; s++) {
b->args[s] = o->args[s];
snprintf(b->in_text[s], sizeof(b->in_text[s]), "%s", o->in_text[s]);
}
snprintf(b->lit_text, sizeof(b->lit_text), "%s", o->lit);
}
T->top_n = B->top_n < MAX_WS ? B->top_n : MAX_WS;
for (int i = 0; i < T->top_n; i++) T->top[i] = B->top[i];
}
/* Descarta tudo do editor e reconstroi a partir da blueprint. */
static void blueprint_apply(Ed* ed, const TbBlueprint* bp) {
tabwins_close_all(ed); /* abas destacadas voltam antes de recriar as abas */
@@ -2447,37 +2477,14 @@ static void blueprint_apply(Ed* ed, const TbBlueprint* bp) {
for (int ti = 0; ti < bp->tab_count && ed->tab_n < MAX_TABS; ti++) {
const TbBpTab* B = &bp->tabs[ti];
int idx = ed->tab_n++;
Tab* T = &ed->tabs[idx];
Tab* T = &ed->tabs[ed->tab_n++];
memset(T, 0, sizeof(*T));
snprintf(T->name, sizeof(T->name), "%s", B->name);
T->is_composite = B->composite;
T->comp_id = B->comp_id;
T->color_idx = B->color_idx;
T->ws_sx = B->ws_sx; T->ws_sy = B->ws_sy;
for (int i = 0; i < MAX_WS; i++) {
T->ws[i].parent = -1; T->ws[i].prel = REL_NONE; T->ws[i].next = -1;
T->ws[i].sub[0] = T->ws[i].sub[1] = -1;
for (int s = 0; s < MAX_INPUTS; s++) T->ws[i].args[s] = -1;
}
for (int i = 0; i < MAX_WS; i++) {
const TbBpBlock* o = &B->blocks[i];
if (!o->used) continue;
EdBlock* b = &T->ws[i];
b->used = true;
snprintf(b->type_name, sizeof(b->type_name), "%s", o->type);
b->type = b->type_name[0] ? tb_type_block_find(ed->rt, b->type_name) : NULL;
b->x = o->x; b->y = o->y;
b->parent = o->parent; b->prel = o->prel; b->next = o->next;
for (int k = 0; k < 2; k++) b->sub[k] = o->sub[k];
for (int s = 0; s < MAX_INPUTS; s++) {
b->args[s] = o->args[s];
snprintf(b->in_text[s], sizeof(b->in_text[s]), "%s", o->in_text[s]);
}
snprintf(b->lit_text, sizeof(b->lit_text), "%s", o->lit);
}
T->top_n = B->top_n < MAX_WS ? B->top_n : MAX_WS;
for (int i = 0; i < T->top_n; i++) T->top[i] = B->top[i];
bp_tab_load(ed, B, T);
}
for (int u = 0; u < ed->user_block_n; u++) {
@@ -2503,7 +2510,16 @@ static void blueprint_apply(Ed* ed, const TbBlueprint* bp) {
ed->stage_buf[0] = 0;
}
static bool sb_import_file(Ed* ed, const char* path);
static bool has_ext(const char* path, const char* ext) {
size_t n = strlen(path), e = strlen(ext);
return n > e && !strcasecmp(path + n - e, ext);
}
static bool project_load(Ed* ed, const char* path) {
if (has_ext(path, ".txt") || has_ext(path, ".sb") || has_ext(path, ".scratchblocks"))
return sb_import_file(ed, path); /* notacao de texto do forum do Scratch */
char err[160] = "";
TbBlueprint* bp = tb_blueprint_load_file(path, err, sizeof(err));
if (!bp) {
@@ -2539,6 +2555,132 @@ static bool project_export(Ed* ed, const char* path, int fmt) {
return ok;
}
/* ===
* Notacao de texto do forum do Scratch ("scratchblocks"): exportar a aba
* atual / importar como aba nova (library tinyblocks-scratchblocks)
* === */
static void cleanup_ws(Ed* ed);
static int sb_shape(const char* type, void* ud) {
Ed* ed = (Ed*)ud;
TinyBlocks_TypeBlock* t = tb_type_block_find(ed->rt, type);
if (!t) return -1;
if (is_cap(t)) return TB_SB_CAP;
switch (shape_of(t)) {
case SH_HAT: return TB_SB_HAT;
case SH_C1: return TB_SB_C1;
case SH_C2: return TB_SB_C2;
case SH_REPORTER: return TB_SB_REPORTER;
case SH_BOOL: return TB_SB_BOOLEAN;
default: return TB_SB_STACK;
}
}
static int sb_slot_kind(const char* type, int slot, void* ud) {
Ed* ed = (Ed*)ud;
TinyBlocks_TypeBlock* t = tb_type_block_find(ed->rt, type);
if (!t || slot < 0 || slot >= input_count(t)) return TB_SB_SLOT_TEXT;
if (slot_is_bool(t, slot)) return TB_SB_SLOT_BOOL;
TinyBlocks_ValueKind k = t->input_descs[slot].expected_kind;
return (k == TB_VALUE_INTEGER || k == TB_VALUE_REAL) ? TB_SB_SLOT_NUM : TB_SB_SLOT_TEXT;
}
/* categoria do editor -> categoria do scratchblocks (cor no forum) */
static const char* sb_category(const char* type, void* ud) {
Ed* ed = (Ed*)ud;
int k = cat_of(ed, type);
const char* c = k >= 0 ? ed->cats[k].name : "";
static const struct { const char* pt; const char* sb; } map[] = {
{"Eventos", "events"}, {"Controle", "control"}, {"Sensores", "sensing"},
{"Operadores", "operators"}, {"Números", "operators"}, {"Texto", "operators"},
{"Variáveis", "variables"}, {"Listas", "list"}, {"Aparência", "looks"},
{"Caneta", "pen"}, {"Meus Blocos", "custom"},
};
for (size_t i = 0; i < sizeof(map) / sizeof(map[0]); i++)
if (!strcmp(c, map[i].pt)) return map[i].sb;
return "extension";
}
/* Contexto: rotulos em portugues do editor + callbacks */
static TbSbContext sb_context(Ed* ed, TbSbLabel** labels_out) {
size_t n = sizeof(s_specs) / sizeof(s_specs[0]);
TbSbLabel* L = calloc(n, sizeof(TbSbLabel));
int k = 0;
for (size_t i = 0; L && i < n; i++) {
L[k].type = s_specs[i].type;
L[k].label = s_specs[i].label;
k++;
}
*labels_out = L;
TbSbContext cx = { L, L ? k : 0, sb_shape, sb_slot_kind, sb_category, ed };
return cx;
}
static void sb_export_file(Ed* ed, const char* path) {
if (CT.kind != TK_BLOCKS) {
snprintf(ed->hot_status, sizeof(ed->hot_status), "Só abas de blocos viram scratchblocks");
ed->hot_status_ok = false;
return;
}
TbBlueprint* bp = ed_to_blueprint(ed);
TbSbLabel* labels = NULL;
TbSbContext cx = sb_context(ed, &labels);
char* txt = bp ? tb_scratchblocks_export(&bp->tabs[ed->cur_tab], &cx) : NULL;
FILE* f = txt ? fopen(path, "wb") : NULL;
bool ok = f && fputs(txt, f) >= 0;
if (f) fclose(f);
snprintf(ed->hot_status, sizeof(ed->hot_status), ok ? "Exportado (scratchblocks): %.200s"
: "Falha ao exportar: %.200s", path);
ed->hot_status_ok = ok;
free(txt);
free(labels);
tb_blueprint_free(bp);
}
static bool sb_import_file(Ed* ed, const char* path) {
FILE* f = fopen(path, "rb");
char* text = NULL;
if (f) {
fseek(f, 0, SEEK_END);
long n = ftell(f);
fseek(f, 0, SEEK_SET);
text = n >= 0 ? malloc((size_t)n + 1) : NULL;
if (text) { size_t r = fread(text, 1, (size_t)n, f); text[r] = 0; }
fclose(f);
}
TbBpTab* B = text ? calloc(1, sizeof(TbBpTab)) : NULL;
if (!B) {
snprintf(ed->hot_status, sizeof(ed->hot_status), "Não consegui ler %.200s", path);
ed->hot_status_ok = false;
free(text);
return false;
}
TbSbLabel* labels = NULL;
TbSbContext cx = sb_context(ed, &labels);
char warn[200] = "";
int n = tb_scratchblocks_import(text, B, &cx, warn, sizeof(warn));
free(labels);
free(text);
const char* base = strrchr(path, '/');
base = base ? base + 1 : path;
if (n <= 0 || !tab_new_kind(ed, base, false, TK_BLOCKS)) {
if (n <= 0) snprintf(ed->hot_status, sizeof(ed->hot_status), "Nenhum script em %.200s", path);
else snprintf(ed->hot_status, sizeof(ed->hot_status), "Limite de abas atingido");
ed->hot_status_ok = false;
free(B);
return false;
}
bp_tab_load(ed, B, &CT);
free(B);
layout_tab(&CT);
cleanup_ws(ed); /* arruma as pilhas uma embaixo da outra */
palette_rebuild(ed);
if (warn[0]) snprintf(ed->hot_status, sizeof(ed->hot_status), "Importado com avisos: %.180s", warn);
else snprintf(ed->hot_status, sizeof(ed->hot_status), "Importado: %d script(s) de %.160s", n, base);
ed->hot_status_ok = !warn[0];
return true;
}
/* ===
* Diálogo modal "Criar um Bloco" (estilo Scratch)
* === */
@@ -4013,6 +4155,7 @@ static const char* ctx_label(int id) {
case CM_EXP_JSON: return "Exportar JSON";
case CM_EXP_XML: return "Exportar XML";
case CM_EXP_CSV: return "Exportar CSV";
case CM_EXP_SB: return "Exportar scratchblocks";
default: return "";
}
}
@@ -5012,6 +5155,7 @@ static void ctx_exec(Ed* ed, int id) {
case CM_EXP_JSON: start_path(ed, PM_EXP_JSON, "projeto.json"); break;
case CM_EXP_XML: start_path(ed, PM_EXP_XML, "projeto.xml"); break;
case CM_EXP_CSV: start_path(ed, PM_EXP_CSV, "projeto.csv"); break;
case CM_EXP_SB: start_path(ed, PM_EXP_SB, "script.txt"); break;
default: break;
}
}
@@ -5080,6 +5224,7 @@ static void on_lmb_down(Ed* ed, float mx, float my) {
ed->ctx_items[ed->ctx_n++] = CM_EXP_JSON;
ed->ctx_items[ed->ctx_n++] = CM_EXP_XML;
ed->ctx_items[ed->ctx_n++] = CM_EXP_CSV;
ed->ctx_items[ed->ctx_n++] = CM_EXP_SB;
ed->ctx_menu_open = true;
ed->ctx_export = true;
ed->ctx_menu_bi = -1;
@@ -5332,6 +5477,7 @@ TB_ED_API void path_commit(Ed* ed, int mode, const char* p) {
case PM_EXP_JSON: project_export(ed, p, EX_JSON); break;
case PM_EXP_XML: project_export(ed, p, EX_XML); break;
case PM_EXP_CSV: project_export(ed, p, EX_CSV); break;
case PM_EXP_SB: sb_export_file(ed, p); break;
case PM_IMGLOAD: if (CT.kind == TK_IMAGE) img_load_file(ed, p, -1); break;
case PM_IMSAVE: if (CT.kind == TK_IMAGE) img_save_out(ed, p); break;
case PM_IMADDR: if (CT.kind == TK_IMAGE) img_load_file(ed, p, IMG_L_RASTER); break;