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:
1 parent
649ae14fb3
commit
d842890b0b
11 files changed
+1255
-38
No files matched your search
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# Makefile da library scratchblocks (notacao de texto do forum do Scratch)
|
||||
# Constroi build/libtinyblocks-scratchblocks.a e build/libtinyblocks-scratchblocks.so
|
||||
CC := gcc
|
||||
BUILD := build
|
||||
|
||||
CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \
|
||||
-I../../include -Iinclude -I../tinyblocks-blueprint/include
|
||||
|
||||
OBJ := $(BUILD)/tb_scratchblocks.o
|
||||
LIB_A := $(BUILD)/libtinyblocks-scratchblocks.a
|
||||
LIB_SO := $(BUILD)/libtinyblocks-scratchblocks.so
|
||||
|
||||
.PHONY: all static shared clean
|
||||
all: static shared
|
||||
static: $(LIB_A)
|
||||
shared: $(LIB_SO)
|
||||
|
||||
$(OBJ): src/tb_scratchblocks.c include/tb_scratchblocks.h ../tinyblocks-blueprint/include/blueprint.h
|
||||
@mkdir -p $(BUILD)
|
||||
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||
|
||||
$(LIB_A): $(OBJ)
|
||||
ar rcs $@ $^
|
||||
|
||||
$(LIB_SO): $(OBJ)
|
||||
$(CC) -shared -o $@ $^
|
||||
|
||||
clean:
|
||||
$(RM) -r $(BUILD)
|
||||
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
* TinyBlocks - tb_scratchblocks.h
|
||||
* Library tinyblocks-scratchblocks: converte uma aba de blocos (o modelo da
|
||||
* tinyblocks-blueprint) para a notacao de texto do forum do Scratch
|
||||
* ("scratchblocks") e de volta.
|
||||
*
|
||||
* when flag clicked
|
||||
* set [x v] to (0)
|
||||
* repeat (10)
|
||||
* change [x v] by (1)
|
||||
* end
|
||||
*
|
||||
* Blocos com equivalente no Scratch saem em ingles (renderizam no forum
|
||||
* como no Scratch). Os demais usam os rotulos passados pelo chamador (ex.:
|
||||
* os do editor, em portugues) com "::categoria". A importacao aceita as
|
||||
* duas formas. Nao conhece o editor: forma do bloco, tipo de cada campo e
|
||||
* categoria chegam por callbacks.
|
||||
*/
|
||||
#ifndef TINYBLOCKS_SCRATCHBLOCKS_H
|
||||
#define TINYBLOCKS_SCRATCHBLOCKS_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <blueprint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Forma do bloco */
|
||||
enum {
|
||||
TB_SB_STACK = 0, /* comando */
|
||||
TB_SB_HAT, /* chapeu (inicio de script) */
|
||||
TB_SB_C1, /* C com uma boca (repita, se) */
|
||||
TB_SB_C2, /* C com duas bocas (se/senao) */
|
||||
TB_SB_CAP, /* C sem encaixe embaixo (sempre) */
|
||||
TB_SB_REPORTER, /* ( ) */
|
||||
TB_SB_BOOLEAN /* < > */
|
||||
};
|
||||
|
||||
/* Tipo de um campo de entrada (escolhe ( ), [ ] ou < >) */
|
||||
enum { TB_SB_SLOT_TEXT = 0, TB_SB_SLOT_NUM, TB_SB_SLOT_BOOL };
|
||||
|
||||
/* Rotulo extra: "%1".."%9" sao os campos (ex.: "mude %1 para %2") */
|
||||
typedef struct {
|
||||
const char* type;
|
||||
const char* label;
|
||||
} TbSbLabel;
|
||||
|
||||
typedef struct {
|
||||
const TbSbLabel* labels; /* rotulos extras (podem ser NULL) */
|
||||
int label_n;
|
||||
/* forma do tipo (TB_SB_*); -1 = desconhecido. NULL = so a tabela interna */
|
||||
int (*shape)(const char* type, void* ud);
|
||||
/* TB_SB_SLOT_* do campo `slot` (0-based) do tipo */
|
||||
int (*slot_kind)(const char* type, int slot, void* ud);
|
||||
/* categoria do scratchblocks para "::" (motion, looks, events, control,
|
||||
sensing, operators, variables, list, pen, custom, extension...) */
|
||||
const char* (*category)(const char* type, void* ud);
|
||||
void* ud;
|
||||
} TbSbContext;
|
||||
|
||||
/* Texto da aba (todas as pilhas, de cima para baixo). malloc; NULL em erro. */
|
||||
char* tb_scratchblocks_export(const TbBpTab* tab, const TbSbContext* cx);
|
||||
|
||||
/* Le o texto para dentro de `out` (que deve vir zerado). Devolve o numero de
|
||||
pilhas criadas (ou -1). Linhas que nao reconhece sao puladas; a primeira
|
||||
delas fica descrita em `warn` (se nao for NULL). */
|
||||
int tb_scratchblocks_import(const char* text, TbBpTab* out, const TbSbContext* cx,
|
||||
char* warn, size_t warn_cap);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* TINYBLOCKS_SCRATCHBLOCKS_H */
|
||||
@@ -0,0 +1,15 @@
|
||||
# Metadados da library scratchblocks. Lido pela UI/build sem recompilar o .so.
|
||||
[library]
|
||||
name = "tinyblocks-scratchblocks"
|
||||
version = "1.0.0"
|
||||
category = "Editor"
|
||||
description = "Converte scripts para a notacao de texto do forum do Scratch (scratchblocks) e de volta"
|
||||
color = [76, 151, 255, 255]
|
||||
dark = [61, 121, 204, 255]
|
||||
|
||||
[build]
|
||||
sources = ["src/tb_scratchblocks.c"]
|
||||
includes = ["include"]
|
||||
shared = "build/libtinyblocks-scratchblocks.so"
|
||||
static = "build/libtinyblocks-scratchblocks.a"
|
||||
depends = ["tinyblocks-blueprint"]
|
||||
@@ -0,0 +1,734 @@
|
||||
/*
|
||||
* TinyBlocks - tb_scratchblocks.c
|
||||
* Notacao de texto do forum do Scratch ("scratchblocks") <-> aba de blocos
|
||||
* (TbBpTab da tinyblocks-blueprint). Ver tb_scratchblocks.h.
|
||||
*
|
||||
* Um modelo descreve um tipo de bloco no texto de dentro dele:
|
||||
* "set [%1 v] to (%2)" -> %N e o campo N (1-based), com o tipo de
|
||||
* parenteses que sai na exportacao
|
||||
* "item (%2) of [%L1 v]" -> %LN: o campo N recebe uma lista com nome
|
||||
* (repórter List.Var), escrita como menu
|
||||
* "[abs v] of (%1)" -> campo fixo: so casa com esse texto
|
||||
* Exportar troca os %N pelos valores; importar reduz a linha a palavras e
|
||||
* campos e procura o modelo que casa posicao a posicao.
|
||||
*/
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
|
||||
#include "tb_scratchblocks.h"
|
||||
|
||||
/* -- Modelos internos (ingles do Scratch 3) ------------------------------- */
|
||||
/* forma: h chapeu, s comando, c C, C se/senao, e sempre, r repórter, b booleano */
|
||||
typedef struct { const char* type; const char* text; char shape; bool import_only; } Tpl;
|
||||
|
||||
static const Tpl s_builtin[] = {
|
||||
{"Events.WhenRun", "when flag clicked", 'h', false},
|
||||
{"Events.WhenRun", "when green flag clicked", 'h', true},
|
||||
{"Control.Repeat", "repeat (%1)", 'c', false},
|
||||
{"Control.RepeatUntil", "repeat until <%1>", 'c', false},
|
||||
{"Control.Forever", "forever", 'e', false},
|
||||
{"Control.If", "if <%1> then", 'c', false},
|
||||
{"Control.IfElse", "if <%1> then", 'C', false},
|
||||
{"Variables.Set", "set [%1 v] to (%2)", 's', false},
|
||||
{"Variables.Change", "change [%1 v] by (%2)", 's', false},
|
||||
{"IO.Print", "say [%1]", 's', false},
|
||||
{"Stage.Clear", "erase all", 's', false},
|
||||
{"Stage.PenSize", "set pen size to (%1)", 's', false},
|
||||
{"Input.ResetTimer", "reset timer", 's', false},
|
||||
{"List.Push", "add [%1] to [%2 v]", 's', false},
|
||||
{"List.DeleteAt", "delete (%1) of [%2 v]", 's', false},
|
||||
{"List.Clear", "delete all of [%1 v]", 's', false},
|
||||
{"List.InsertAt", "insert [%1] at (%2) of [%3 v]", 's', false},
|
||||
{"List.SetAt", "replace item (%1) of [%2 v] with [%3]", 's', false},
|
||||
{"Operators.Lt", "(%1) < (%2)", 'b', false},
|
||||
{"Operators.Eq", "(%1) = (%2)", 'b', false},
|
||||
{"Operators.Gt", "(%1) > (%2)", 'b', false},
|
||||
{"Operators.And", "<%1> and <%2>", 'b', false},
|
||||
{"Operators.Or", "<%1> or <%2>", 'b', false},
|
||||
{"Operators.Not", "not <%1>", 'b', false},
|
||||
{"List.Contains", "[%L1 v] contains [%2]?", 'b', false},
|
||||
{"String.Contains", "[%1] contains [%2]?", 'b', false},
|
||||
{"Input.MouseDown", "mouse down?", 'b', false},
|
||||
{"Input.KeyPressed", "key [%1 v] pressed?", 'b', false},
|
||||
{"Operators.Random", "pick random (%1) to (%2)", 'r', false},
|
||||
{"Math.Add", "(%1) + (%2)", 'r', false},
|
||||
{"Math.Sub", "(%1) - (%2)", 'r', false},
|
||||
{"Math.Mul", "(%1) * (%2)", 'r', false},
|
||||
{"Number.Div", "(%1) / (%2)", 'r', false},
|
||||
{"Math.Div", "(%1) / (%2)", 'r', false},
|
||||
{"Math.Mod", "(%1) mod (%2)", 'r', false},
|
||||
{"Number.Round", "round (%1)", 'r', false},
|
||||
{"Math.Abs", "[abs v] of (%1)", 'r', false},
|
||||
{"Number.Floor", "[floor v] of (%1)", 'r', false},
|
||||
{"Number.Ceil", "[ceiling v] of (%1)", 'r', false},
|
||||
{"Number.Sqrt", "[sqrt v] of (%1)", 'r', false},
|
||||
{"Number.Sin", "[sin v] of (%1)", 'r', false},
|
||||
{"Number.Cos", "[cos v] of (%1)", 'r', false},
|
||||
{"Number.Tan", "[tan v] of (%1)", 'r', false},
|
||||
{"Number.Asin", "[asin v] of (%1)", 'r', false},
|
||||
{"Number.Acos", "[acos v] of (%1)", 'r', false},
|
||||
{"Number.Atan", "[atan v] of (%1)", 'r', false},
|
||||
{"Number.Ln", "[ln v] of (%1)", 'r', false},
|
||||
{"Number.Log10", "[log v] of (%1)", 'r', false},
|
||||
{"Number.Exp", "[e ^ v] of (%1)", 'r', false},
|
||||
{"Text.Concat", "join [%1] [%2]", 'r', false},
|
||||
{"List.Length", "length of [%L1 v]", 'r', false},
|
||||
{"Text.Length", "length of [%1]", 'r', false},
|
||||
{"String.Letter", "letter (%2) of [%1]", 'r', false},
|
||||
{"List.Item", "item (%2) of [%L1 v]", 'r', false},
|
||||
{"List.IndexOf", "item # of [%2] in [%L1 v]", 'r', false},
|
||||
{"List.Var", "[%1 v] :: list", 'r', false},
|
||||
{"Input.MouseX", "mouse x", 'r', false},
|
||||
{"Input.MouseY", "mouse y", 'r', false},
|
||||
{"Input.Timer", "timer", 'r', false},
|
||||
};
|
||||
#define BUILTIN_N ((int)(sizeof(s_builtin) / sizeof(s_builtin[0])))
|
||||
|
||||
/* -- Texto dinamico -------------------------------------------------------- */
|
||||
typedef struct { char* p; size_t n, cap; } Sb;
|
||||
|
||||
static void sb_add(Sb* b, const char* s, size_t n) {
|
||||
if (!b->p && b->cap == (size_t)-1) return;
|
||||
if (b->n + n + 1 > b->cap) {
|
||||
size_t nc = b->cap ? b->cap * 2 : 256;
|
||||
while (nc < b->n + n + 1) nc *= 2;
|
||||
char* np = realloc(b->p, nc);
|
||||
if (!np) { free(b->p); b->p = NULL; b->cap = (size_t)-1; return; }
|
||||
b->p = np; b->cap = nc;
|
||||
}
|
||||
memcpy(b->p + b->n, s, n);
|
||||
b->n += n;
|
||||
b->p[b->n] = 0;
|
||||
}
|
||||
static void sb_str(Sb* b, const char* s) { sb_add(b, s, strlen(s)); }
|
||||
|
||||
/* texto de campo: escapa os caracteres da notacao */
|
||||
static void sb_esc(Sb* b, const char* s) {
|
||||
for (; *s; s++) {
|
||||
if (strchr("[]()<>\\", *s)) sb_add(b, "\\", 1);
|
||||
sb_add(b, s, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/* -- Tokens ---------------------------------------------------------------- */
|
||||
enum { T_WORD, T_ROUND, T_SQUARE, T_ANGLE }; /* palavra, ( ), [ ], < > */
|
||||
#define TOK_MAX 40
|
||||
#define TOK_TEXT 256
|
||||
typedef struct { int kind; bool dropdown; char text[TOK_TEXT]; } Tok;
|
||||
|
||||
/* fim do grupo que abre em s[i] (indice do fechamento) ou -1 */
|
||||
static int group_end(const char* s, int i) {
|
||||
char open = s[i];
|
||||
if (open == '[') {
|
||||
for (int k = i + 1; s[k]; k++) {
|
||||
if (s[k] == '\\' && s[k + 1]) { k++; continue; }
|
||||
if (s[k] == ']') return k;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
int depth = 0;
|
||||
for (int k = i; s[k]; k++) {
|
||||
char c = s[k];
|
||||
if (c == '\\' && s[k + 1]) { k++; continue; }
|
||||
if (c == '[') { int e = group_end(s, k); if (e < 0) return -1; k = e; continue; }
|
||||
if (open == '(') {
|
||||
if (c == '(') depth++;
|
||||
else if (c == ')') { if (--depth == 0) return k; }
|
||||
} else { /* '<' booleano */
|
||||
/* "<" e ">" com espaco dos dois lados sao os operadores menor/maior */
|
||||
bool spaced = k > 0 && s[k - 1] == ' ' && s[k + 1] == ' ';
|
||||
if (c == '(') { int e = group_end(s, k); if (e < 0) return -1; k = e; continue; }
|
||||
if (c == '<' && !spaced && s[k + 1] != ' ') depth++;
|
||||
else if (c == '>' && !spaced) { if (--depth == 0) return k; }
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
static void copy_inner(char* out, const char* s, int a, int b, bool unescape, bool trim) {
|
||||
int n = 0;
|
||||
for (int k = a; k < b && n < TOK_TEXT - 1; k++) {
|
||||
if (unescape && s[k] == '\\' && k + 1 < b) k++;
|
||||
out[n++] = s[k];
|
||||
}
|
||||
out[n] = 0;
|
||||
if (!trim) return;
|
||||
/* tira espacos das pontas */
|
||||
char* p = out;
|
||||
while (*p == ' ') p++;
|
||||
if (p != out) memmove(out, p, strlen(p) + 1);
|
||||
n = (int)strlen(out);
|
||||
while (n > 0 && out[n - 1] == ' ') out[--n] = 0;
|
||||
}
|
||||
|
||||
/* Divide o texto de um bloco em palavras e campos; -1 em erro de sintaxe */
|
||||
static int tokenize(const char* s, Tok* t, int max) {
|
||||
int n = 0, i = 0;
|
||||
while (s[i] && n < max) {
|
||||
if (s[i] == ' ' || s[i] == '\t') { i++; continue; }
|
||||
char c = s[i];
|
||||
bool is_group = c == '(' || c == '[' || (c == '<' && s[i + 1] && s[i + 1] != ' ');
|
||||
if (is_group) {
|
||||
int e = group_end(s, i);
|
||||
if (e < 0) return -1;
|
||||
Tok* k = &t[n++];
|
||||
k->kind = c == '(' ? T_ROUND : c == '[' ? T_SQUARE : T_ANGLE;
|
||||
copy_inner(k->text, s, i + 1, e, c == '[', c != '[');
|
||||
k->dropdown = false;
|
||||
size_t L = strlen(k->text);
|
||||
if (c == '[' && L >= 2 && k->text[L - 1] == 'v' && k->text[L - 2] == ' ') {
|
||||
k->dropdown = true; /* menu: nome aparado */
|
||||
k->text[L - 2] = 0;
|
||||
copy_inner(k->text, k->text, 0, (int)strlen(k->text), false, true);
|
||||
} else if (c == '[' && L == 1 && k->text[0] == 'v') {
|
||||
k->dropdown = true; k->text[0] = 0;
|
||||
}
|
||||
i = e + 1;
|
||||
continue;
|
||||
}
|
||||
int a = i;
|
||||
while (s[i] && s[i] != ' ' && s[i] != '\t' && s[i] != '(' && s[i] != '[' &&
|
||||
!(s[i] == '<' && i > a)) i++;
|
||||
Tok* k = &t[n++];
|
||||
k->kind = T_WORD;
|
||||
k->dropdown = false;
|
||||
int len = i - a < TOK_TEXT - 1 ? i - a : TOK_TEXT - 1;
|
||||
memcpy(k->text, s + a, (size_t)len);
|
||||
k->text[len] = 0;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/* Indice logo depois do grupo ( ) [ ] < > que abre em s[k], ou k+1 se nao for grupo */
|
||||
static int skip_group(const char* s, int k) {
|
||||
char c = s[k];
|
||||
if (c == '(' || c == '[' || (c == '<' && s[k + 1] && s[k + 1] != ' ')) {
|
||||
int e = group_end(s, k);
|
||||
return e < 0 ? (int)strlen(s) : e + 1;
|
||||
}
|
||||
return k + 1;
|
||||
}
|
||||
|
||||
/* Tira " :: categoria" (fora dos campos) */
|
||||
static void strip_category(char* s) {
|
||||
for (int k = 0; s[k]; ) {
|
||||
if (s[k] == '\\' && s[k + 1]) { k += 2; continue; }
|
||||
if (s[k] == '(' || s[k] == '[' || s[k] == '<') { k = skip_group(s, k); continue; }
|
||||
if (s[k] == ':' && s[k + 1] == ':') {
|
||||
s[k] = 0;
|
||||
int n = (int)strlen(s);
|
||||
while (n > 0 && s[n - 1] == ' ') s[--n] = 0;
|
||||
return;
|
||||
}
|
||||
k++;
|
||||
}
|
||||
}
|
||||
|
||||
/* -- Modelos (internos + rotulos do chamador) ------------------------------ */
|
||||
typedef struct {
|
||||
const char* type;
|
||||
char shape;
|
||||
bool builtin, import_only;
|
||||
int n;
|
||||
Tok tok[TOK_MAX];
|
||||
int slot[TOK_MAX]; /* campo (0-based) do token; -1 = fixo/palavra */
|
||||
bool listslot[TOK_MAX]; /* %LN */
|
||||
char cat[24]; /* "list" de "... :: list" (modelos internos) */
|
||||
} Model;
|
||||
|
||||
static int shape_char(int sh) {
|
||||
switch (sh) {
|
||||
case TB_SB_HAT: return 'h';
|
||||
case TB_SB_C1: return 'c';
|
||||
case TB_SB_C2: return 'C';
|
||||
case TB_SB_CAP: return 'e';
|
||||
case TB_SB_REPORTER: return 'r';
|
||||
case TB_SB_BOOLEAN: return 'b';
|
||||
default: return 's';
|
||||
}
|
||||
}
|
||||
|
||||
/* "%N" ou "%LN" -> campo (0-based); -1 se nao for */
|
||||
static int slot_ref(const char* s, bool* list) {
|
||||
*list = false;
|
||||
if (s[0] != '%') return -1;
|
||||
const char* p = s + 1;
|
||||
if (*p == 'L') { *list = true; p++; }
|
||||
if (!isdigit((unsigned char)*p)) return -1;
|
||||
int v = atoi(p);
|
||||
while (isdigit((unsigned char)*p)) p++;
|
||||
return *p ? -1 : v - 1;
|
||||
}
|
||||
|
||||
static bool model_build(Model* m, const char* type, const char* text, char shape) {
|
||||
memset(m, 0, sizeof(*m));
|
||||
m->type = type;
|
||||
m->shape = shape;
|
||||
char buf[512];
|
||||
snprintf(buf, sizeof(buf), "%s", text);
|
||||
const char* cc = strstr(text, "::");
|
||||
if (cc) {
|
||||
cc += 2;
|
||||
while (*cc == ' ') cc++;
|
||||
snprintf(m->cat, sizeof(m->cat), "%s", cc);
|
||||
}
|
||||
strip_category(buf);
|
||||
m->n = tokenize(buf, m->tok, TOK_MAX);
|
||||
if (m->n <= 0) return false;
|
||||
for (int i = 0; i < m->n; i++) {
|
||||
bool list;
|
||||
m->slot[i] = slot_ref(m->tok[i].text, &list);
|
||||
m->listslot[i] = list;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
typedef struct {
|
||||
Model* m;
|
||||
int n;
|
||||
const TbSbContext* cx;
|
||||
} Models;
|
||||
|
||||
static int cx_shape(const TbSbContext* cx, const char* type) {
|
||||
return cx && cx->shape ? cx->shape(type, cx->ud) : -1;
|
||||
}
|
||||
|
||||
static Models models_load(const TbSbContext* cx) {
|
||||
Models M = { NULL, 0, cx };
|
||||
int extra = cx && cx->labels ? cx->label_n : 0;
|
||||
M.m = calloc((size_t)(BUILTIN_N + extra), sizeof(Model));
|
||||
if (!M.m) return M;
|
||||
for (int i = 0; i < BUILTIN_N; i++) {
|
||||
Model* m = &M.m[M.n];
|
||||
if (!model_build(m, s_builtin[i].type, s_builtin[i].text, s_builtin[i].shape)) continue;
|
||||
m->builtin = true;
|
||||
m->import_only = s_builtin[i].import_only;
|
||||
M.n++;
|
||||
}
|
||||
for (int i = 0; i < extra; i++) {
|
||||
const TbSbLabel* L = &cx->labels[i];
|
||||
if (!L->type || !L->label) continue;
|
||||
int sh = cx_shape(cx, L->type);
|
||||
Model* m = &M.m[M.n];
|
||||
if (!model_build(m, L->type, L->label, (char)shape_char(sh < 0 ? TB_SB_STACK : sh))) continue;
|
||||
/* "%1" sozinho (ex.: valor de variavel) casaria com qualquer coisa */
|
||||
if (m->n == 1 && m->slot[0] >= 0) continue;
|
||||
M.n++;
|
||||
}
|
||||
return M;
|
||||
}
|
||||
|
||||
static bool word_eq(const char* a, const char* b) {
|
||||
return strcasecmp(a, b) == 0;
|
||||
}
|
||||
|
||||
/* O modelo casa com os tokens? */
|
||||
static bool model_match(const Model* m, const Tok* t, int n) {
|
||||
if (m->n != n) return false;
|
||||
for (int i = 0; i < n; i++) {
|
||||
const Tok* mt = &m->tok[i];
|
||||
if (m->slot[i] >= 0) {
|
||||
if (t[i].kind == T_WORD) return false;
|
||||
if (m->listslot[i] && !(t[i].kind == T_SQUARE && t[i].dropdown)) return false;
|
||||
continue;
|
||||
}
|
||||
if (mt->kind != t[i].kind) {
|
||||
/* campo fixo "[abs v]" aceita tambem "(abs)" */
|
||||
if (mt->kind == T_WORD || t[i].kind == T_WORD) return false;
|
||||
}
|
||||
if (!word_eq(mt->text, t[i].text)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool shape_is_stmt(char s) { return s == 's' || s == 'h' || s == 'c' || s == 'C' || s == 'e'; }
|
||||
|
||||
/* -- Exportar -------------------------------------------------------------- */
|
||||
static bool is_literal(const char* type) { return strncmp(type, "Literal.", 8) == 0; }
|
||||
|
||||
static int block_shape(const Models* M, const char* type) {
|
||||
int sh = cx_shape(M->cx, type);
|
||||
if (sh >= 0) return sh;
|
||||
if (!strcmp(type, "Variables.Get") || is_literal(type)) return TB_SB_REPORTER;
|
||||
for (int i = 0; i < M->n; i++) {
|
||||
if (strcmp(M->m[i].type, type) != 0) continue;
|
||||
switch (M->m[i].shape) {
|
||||
case 'h': return TB_SB_HAT;
|
||||
case 'c': return TB_SB_C1;
|
||||
case 'C': return TB_SB_C2;
|
||||
case 'e': return TB_SB_CAP;
|
||||
case 'r': return TB_SB_REPORTER;
|
||||
case 'b': return TB_SB_BOOLEAN;
|
||||
default: return TB_SB_STACK;
|
||||
}
|
||||
}
|
||||
return TB_SB_STACK;
|
||||
}
|
||||
|
||||
static bool slot_used(const TbBpTab* tab, int bi, int s) {
|
||||
const TbBpBlock* b = &tab->blocks[bi];
|
||||
return b->args[s] >= 0 || b->in_text[s][0];
|
||||
}
|
||||
|
||||
/* O modelo serve para exportar este bloco? (cobre os campos preenchidos e
|
||||
os %LN recebem um repórter List.Var) */
|
||||
static bool model_fits(const Model* m, const TbBpTab* tab, int bi) {
|
||||
if (m->import_only) return false;
|
||||
const TbBpBlock* b = &tab->blocks[bi];
|
||||
bool covered[TB_BP_MAX_INPUTS] = {0};
|
||||
for (int i = 0; i < m->n; i++) {
|
||||
int s = m->slot[i];
|
||||
if (s < 0 || s >= TB_BP_MAX_INPUTS) continue;
|
||||
covered[s] = true;
|
||||
if (m->listslot[i]) {
|
||||
int c = b->args[s];
|
||||
if (c < 0 || strcmp(tab->blocks[c].type, "List.Var") != 0 || tab->blocks[c].args[0] >= 0) return false;
|
||||
}
|
||||
}
|
||||
for (int s = 0; s < TB_BP_MAX_INPUTS; s++)
|
||||
if (!covered[s] && slot_used(tab, bi, s)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
static void render_block(const Models* M, const TbBpTab* tab, int bi, Sb* out, bool outer);
|
||||
|
||||
/* Valor de um campo, no parentese pedido pelo modelo ('(' '[' '<') */
|
||||
static void render_slot(const Models* M, const TbBpTab* tab, int bi, int s, int kind, bool dropdown, Sb* out) {
|
||||
const TbBpBlock* b = &tab->blocks[bi];
|
||||
int c = s < TB_BP_MAX_INPUTS ? b->args[s] : -1;
|
||||
if (c >= 0 && is_literal(tab->blocks[c].type)) {
|
||||
const TbBpBlock* L = &tab->blocks[c];
|
||||
const char* v = strcmp(L->type, "Literal.Text") == 0 && L->lit[0] ? L->lit : L->in_text[0];
|
||||
sb_str(out, kind == T_ROUND ? "(" : "["); sb_esc(out, v); sb_str(out, kind == T_ROUND ? ")" : "]");
|
||||
return;
|
||||
}
|
||||
if (c >= 0) { render_block(M, tab, c, out, true); return; }
|
||||
const char* v = s < TB_BP_MAX_INPUTS ? b->in_text[s] : "";
|
||||
if (kind == T_ANGLE) { sb_str(out, "<>"); return; }
|
||||
sb_str(out, kind == T_ROUND ? "(" : "[");
|
||||
sb_esc(out, v);
|
||||
if (dropdown) sb_str(out, " v");
|
||||
sb_str(out, kind == T_ROUND ? ")" : "]");
|
||||
}
|
||||
|
||||
static void render_tokens(const Models* M, const Model* m, const TbBpTab* tab, int bi, Sb* out) {
|
||||
for (int i = 0; i < m->n; i++) {
|
||||
if (i) sb_str(out, " ");
|
||||
const Tok* t = &m->tok[i];
|
||||
int s = m->slot[i];
|
||||
if (s >= 0 && m->listslot[i]) { /* nome da lista, como menu */
|
||||
int c = tab->blocks[bi].args[s];
|
||||
sb_str(out, "[");
|
||||
sb_esc(out, c >= 0 ? tab->blocks[c].in_text[0] : "");
|
||||
sb_str(out, " v]");
|
||||
continue;
|
||||
}
|
||||
if (s >= 0) {
|
||||
int kind = t->kind;
|
||||
if (kind == T_WORD) { /* "%1" solto (rotulo do chamador) */
|
||||
int sk = M->cx && M->cx->slot_kind ? M->cx->slot_kind(m->type, s, M->cx->ud) : TB_SB_SLOT_TEXT;
|
||||
kind = sk == TB_SB_SLOT_BOOL ? T_ANGLE : sk == TB_SB_SLOT_NUM ? T_ROUND : T_SQUARE;
|
||||
}
|
||||
render_slot(M, tab, bi, s, kind, t->dropdown, out);
|
||||
continue;
|
||||
}
|
||||
switch (t->kind) {
|
||||
case T_ROUND: sb_str(out, "("); sb_esc(out, t->text); sb_str(out, ")"); break;
|
||||
case T_SQUARE: sb_str(out, "["); sb_esc(out, t->text); sb_str(out, t->dropdown ? " v]" : "]"); break;
|
||||
case T_ANGLE: sb_str(out, "<"); sb_str(out, t->text); sb_str(out, ">"); break;
|
||||
default: sb_str(out, t->text); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Texto de um bloco; outer = com os parenteses de repórter/booleano */
|
||||
static void render_block(const Models* M, const TbBpTab* tab, int bi, Sb* out, bool outer) {
|
||||
const TbBpBlock* b = &tab->blocks[bi];
|
||||
int sh = block_shape(M, b->type);
|
||||
bool rep = sh == TB_SB_REPORTER, boo = sh == TB_SB_BOOLEAN;
|
||||
if (outer && rep) sb_str(out, "(");
|
||||
if (outer && boo) sb_str(out, "<");
|
||||
if (strcmp(b->type, "Variables.Get") == 0) { /* (x): valor da variavel */
|
||||
sb_esc(out, b->in_text[0]);
|
||||
} else if (is_literal(b->type)) {
|
||||
sb_esc(out, strcmp(b->type, "Literal.Text") == 0 && b->lit[0] ? b->lit : b->in_text[0]);
|
||||
} else {
|
||||
const Model* use = NULL;
|
||||
for (int i = 0; i < M->n && !use; i++)
|
||||
if (M->m[i].builtin && !strcmp(M->m[i].type, b->type) && model_fits(&M->m[i], tab, bi)) use = &M->m[i];
|
||||
for (int i = 0; i < M->n && !use; i++)
|
||||
if (!M->m[i].builtin && !strcmp(M->m[i].type, b->type)) use = &M->m[i];
|
||||
if (use) {
|
||||
render_tokens(M, use, tab, bi, out);
|
||||
if (use->builtin && use->cat[0]) { sb_str(out, " :: "); sb_str(out, use->cat); }
|
||||
if (!use->builtin) { /* bloco so do TinyBlocks */
|
||||
const char* cat = M->cx && M->cx->category ? M->cx->category(b->type, M->cx->ud) : NULL;
|
||||
sb_str(out, " :: ");
|
||||
sb_str(out, cat && cat[0] ? cat : "extension");
|
||||
}
|
||||
} else {
|
||||
/* sem modelo: o nome do tipo e os campos */
|
||||
sb_str(out, b->type);
|
||||
for (int s = 0; s < TB_BP_MAX_INPUTS; s++) {
|
||||
if (!slot_used(tab, bi, s)) continue;
|
||||
sb_str(out, " ");
|
||||
render_slot(M, tab, bi, s, T_SQUARE, false, out);
|
||||
}
|
||||
sb_str(out, " :: extension");
|
||||
}
|
||||
}
|
||||
if (outer && rep) sb_str(out, ")");
|
||||
if (outer && boo) sb_str(out, ">");
|
||||
}
|
||||
|
||||
static void indent(Sb* out, int depth) {
|
||||
for (int i = 0; i < depth; i++) sb_str(out, " ");
|
||||
}
|
||||
|
||||
static void render_chain(const Models* M, const TbBpTab* tab, int bi, int depth, Sb* out) {
|
||||
for (int c = bi; c >= 0 && c < TB_BP_MAX_WS && tab->blocks[c].used; c = tab->blocks[c].next) {
|
||||
const TbBpBlock* b = &tab->blocks[c];
|
||||
int sh = block_shape(M, b->type);
|
||||
indent(out, depth);
|
||||
render_block(M, tab, c, out, true);
|
||||
sb_str(out, "\n");
|
||||
if (sh == TB_SB_C1 || sh == TB_SB_C2 || sh == TB_SB_CAP) {
|
||||
render_chain(M, tab, b->sub[0], depth + 1, out);
|
||||
if (sh == TB_SB_C2) {
|
||||
indent(out, depth); sb_str(out, "else\n");
|
||||
render_chain(M, tab, b->sub[1], depth + 1, out);
|
||||
}
|
||||
indent(out, depth); sb_str(out, "end\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
char* tb_scratchblocks_export(const TbBpTab* tab, const TbSbContext* cx) {
|
||||
if (!tab) return NULL;
|
||||
Models M = models_load(cx);
|
||||
if (!M.m) return NULL;
|
||||
/* pilhas de cima para baixo */
|
||||
int order[TB_BP_MAX_WS], n = 0;
|
||||
for (int i = 0; i < tab->top_n; i++) {
|
||||
int bi = tab->top[i];
|
||||
if (bi < 0 || bi >= TB_BP_MAX_WS || !tab->blocks[bi].used) continue;
|
||||
int k = n++;
|
||||
while (k > 0 && tab->blocks[order[k - 1]].y > tab->blocks[bi].y) { order[k] = order[k - 1]; k--; }
|
||||
order[k] = bi;
|
||||
}
|
||||
Sb out = {0};
|
||||
sb_str(&out, "");
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (i) sb_str(&out, "\n");
|
||||
render_chain(&M, tab, order[i], 0, &out);
|
||||
}
|
||||
free(M.m);
|
||||
return out.p;
|
||||
}
|
||||
|
||||
/* -- Importar -------------------------------------------------------------- */
|
||||
typedef struct {
|
||||
const Models* M;
|
||||
TbBpTab* tab;
|
||||
char* warn;
|
||||
size_t warn_cap;
|
||||
int line;
|
||||
} Imp;
|
||||
|
||||
static void imp_warn(Imp* I, const char* what, const char* text) {
|
||||
if (!I->warn || I->warn[0]) return;
|
||||
snprintf(I->warn, I->warn_cap, "linha %d: %s: %.120s", I->line, what, text);
|
||||
}
|
||||
|
||||
static bool is_number(const char* s) {
|
||||
if (!*s) return true;
|
||||
char* e;
|
||||
strtod(s, &e);
|
||||
while (*e == ' ') e++;
|
||||
return *e == 0;
|
||||
}
|
||||
|
||||
static int new_block(Imp* I, const char* type) {
|
||||
int bi = tb_blueprint_alloc_block(I->tab);
|
||||
if (bi < 0) { imp_warn(I, "limite de blocos", type); return -1; }
|
||||
snprintf(I->tab->blocks[bi].type, sizeof(I->tab->blocks[bi].type), "%s", type);
|
||||
return bi;
|
||||
}
|
||||
|
||||
static int parse_inner(Imp* I, const char* text, char cls);
|
||||
|
||||
/* Preenche o campo s do bloco bi com o token t */
|
||||
static void fill_slot(Imp* I, int bi, int s, const Tok* t, bool listslot) {
|
||||
if (s < 0 || s >= TB_BP_MAX_INPUTS) return;
|
||||
TbBpBlock* b = &I->tab->blocks[bi];
|
||||
if (listslot) { /* [nome v] -> lista com nome */
|
||||
int c = new_block(I, "List.Var");
|
||||
if (c < 0) return;
|
||||
snprintf(I->tab->blocks[c].in_text[0], 64, "%.63s", t->text);
|
||||
tb_blueprint_link(I->tab, bi, TB_BP_REL_ARG0 + s, c);
|
||||
return;
|
||||
}
|
||||
if (t->kind == T_SQUARE || (t->kind == T_ROUND && is_number(t->text))) {
|
||||
snprintf(b->in_text[s], sizeof(b->in_text[s]), "%.63s", t->text);
|
||||
return;
|
||||
}
|
||||
if (!t->text[0]) return; /* <> vazio */
|
||||
int c = parse_inner(I, t->text, t->kind == T_ANGLE ? 'b' : 'r');
|
||||
if (c >= 0) tb_blueprint_link(I->tab, bi, TB_BP_REL_ARG0 + s, c);
|
||||
}
|
||||
|
||||
/* Cria o bloco do modelo m a partir dos tokens */
|
||||
static int build_from(Imp* I, const Model* m, const Tok* t, int n) {
|
||||
int bi = new_block(I, m->type);
|
||||
if (bi < 0) return -1;
|
||||
for (int i = 0; i < n; i++)
|
||||
if (m->slot[i] >= 0) fill_slot(I, bi, m->slot[i], &t[i], m->listslot[i]);
|
||||
return bi;
|
||||
}
|
||||
|
||||
/* Procura o modelo para tokens de uma classe: 's' comando, 'r', 'b' */
|
||||
static const Model* find_model(const Models* M, const Tok* t, int n, char cls) {
|
||||
for (int pass = 0; pass < 2; pass++)
|
||||
for (int i = 0; i < M->n; i++) {
|
||||
const Model* m = &M->m[i];
|
||||
bool ok = cls == 's' ? shape_is_stmt(m->shape)
|
||||
: pass == 0 ? m->shape == cls : (m->shape == 'r' || m->shape == 'b');
|
||||
if (ok && model_match(m, t, n)) return m;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* Conteudo de um ( ) ou < > -> repórter */
|
||||
static int parse_inner(Imp* I, const char* text, char cls) {
|
||||
char buf[TOK_TEXT];
|
||||
snprintf(buf, sizeof(buf), "%s", text);
|
||||
strip_category(buf);
|
||||
Tok t[TOK_MAX];
|
||||
int n = tokenize(buf, t, TOK_MAX);
|
||||
if (n < 0) { imp_warn(I, "parenteses nao fecham", text); return -1; }
|
||||
const Model* m = find_model(I->M, t, n, cls);
|
||||
if (m) return build_from(I, m, t, n);
|
||||
bool words = n > 0;
|
||||
for (int i = 0; i < n; i++) if (t[i].kind != T_WORD) words = false;
|
||||
if (words && cls == 'r') { /* (x): variavel */
|
||||
int bi = new_block(I, "Variables.Get");
|
||||
if (bi >= 0) snprintf(I->tab->blocks[bi].in_text[0], 64, "%.63s", buf);
|
||||
return bi;
|
||||
}
|
||||
imp_warn(I, "repórter desconhecido", text);
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Tira comentario "// ..." (fora de colchetes) e espacos das pontas */
|
||||
static void clean_line(char* s) {
|
||||
for (int k = 0; s[k]; ) {
|
||||
if (s[k] == '\\' && s[k + 1]) { k += 2; continue; }
|
||||
if (s[k] == '(' || s[k] == '[' || s[k] == '<') { k = skip_group(s, k); continue; }
|
||||
if (s[k] == '/' && s[k + 1] == '/') { s[k] = 0; break; }
|
||||
k++;
|
||||
}
|
||||
char* p = s;
|
||||
while (*p == ' ' || *p == '\t') p++;
|
||||
if (p != s) memmove(s, p, strlen(p) + 1);
|
||||
int n = (int)strlen(s);
|
||||
while (n > 0 && (s[n - 1] == ' ' || s[n - 1] == '\t' || s[n - 1] == '\r')) s[--n] = 0;
|
||||
}
|
||||
|
||||
typedef struct { int cblock, sub, last; } Level;
|
||||
#define LEVEL_MAX 32
|
||||
|
||||
int tb_scratchblocks_import(const char* text, TbBpTab* out, const TbSbContext* cx,
|
||||
char* warn, size_t warn_cap) {
|
||||
if (!text || !out) return -1;
|
||||
if (warn && warn_cap) warn[0] = 0;
|
||||
Models M = models_load(cx);
|
||||
if (!M.m) return -1;
|
||||
Imp I = { &M, out, warn, warn_cap, 0 };
|
||||
Level lv[LEVEL_MAX];
|
||||
int depth = 0, stacks = 0;
|
||||
lv[0].cblock = -1; lv[0].sub = 0; lv[0].last = -1;
|
||||
float y = 40;
|
||||
|
||||
const char* p = text;
|
||||
while (*p) {
|
||||
const char* e = strchr(p, '\n');
|
||||
size_t len = e ? (size_t)(e - p) : strlen(p);
|
||||
char line[1024];
|
||||
if (len >= sizeof(line)) len = sizeof(line) - 1;
|
||||
memcpy(line, p, len);
|
||||
line[len] = 0;
|
||||
p = e ? e + 1 : p + len;
|
||||
I.line++;
|
||||
clean_line(line);
|
||||
if (!strncasecmp(line, "[scratchblocks]", 15) || !strncasecmp(line, "[/scratchblocks]", 16)) continue;
|
||||
if (!line[0]) { /* linha em branco: fim do script */
|
||||
if (depth == 0) lv[0].last = -1;
|
||||
continue;
|
||||
}
|
||||
if (!strcasecmp(line, "end")) { if (depth > 0) depth--; continue; }
|
||||
if (!strcasecmp(line, "else")) {
|
||||
if (depth > 0) {
|
||||
TbBpBlock* c = &out->blocks[lv[depth].cblock];
|
||||
if (!strcmp(c->type, "Control.If")) snprintf(c->type, sizeof(c->type), "Control.IfElse");
|
||||
lv[depth].sub = 1;
|
||||
lv[depth].last = -1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
char body[1024];
|
||||
snprintf(body, sizeof(body), "%s", line);
|
||||
/* repórter/booleano solto numa linha */
|
||||
char outer = 0;
|
||||
size_t bl = strlen(body);
|
||||
if (bl >= 2 && ((body[0] == '(' && group_end(body, 0) == (int)bl - 1) ||
|
||||
(body[0] == '<' && group_end(body, 0) == (int)bl - 1))) {
|
||||
outer = body[0] == '(' ? 'r' : 'b';
|
||||
body[bl - 1] = 0;
|
||||
memmove(body, body + 1, bl);
|
||||
}
|
||||
int bi;
|
||||
const Model* m = NULL;
|
||||
if (outer) {
|
||||
bi = parse_inner(&I, body, outer);
|
||||
} else {
|
||||
strip_category(body);
|
||||
Tok t[TOK_MAX];
|
||||
int n = tokenize(body, t, TOK_MAX);
|
||||
if (n < 0) { imp_warn(&I, "parenteses nao fecham", line); continue; }
|
||||
m = find_model(&M, t, n, 's');
|
||||
if (!m) { imp_warn(&I, "bloco desconhecido", line); continue; }
|
||||
bi = build_from(&I, m, t, n);
|
||||
}
|
||||
if (bi < 0) continue;
|
||||
|
||||
int sh = block_shape(&M, out->blocks[bi].type);
|
||||
int prev = lv[depth].last;
|
||||
bool after_cap = prev >= 0 && block_shape(&M, out->blocks[prev].type) == TB_SB_CAP;
|
||||
if (outer || sh == TB_SB_HAT || after_cap || (depth == 0 && lv[0].last < 0)) {
|
||||
/* comeca uma pilha nova */
|
||||
depth = 0;
|
||||
out->blocks[bi].x = 40;
|
||||
out->blocks[bi].y = y;
|
||||
y += 120;
|
||||
tb_blueprint_top_add(out, bi);
|
||||
stacks++;
|
||||
lv[0].last = outer ? -1 : bi;
|
||||
} else {
|
||||
Level* L = &lv[depth];
|
||||
if (L->last >= 0) tb_blueprint_link(out, L->last, TB_BP_REL_NEXT, bi);
|
||||
else if (depth > 0) tb_blueprint_link(out, L->cblock, TB_BP_REL_SUB0 + L->sub, bi);
|
||||
L->last = bi;
|
||||
}
|
||||
if (!outer && (sh == TB_SB_C1 || sh == TB_SB_C2 || sh == TB_SB_CAP) && depth + 1 < LEVEL_MAX) {
|
||||
depth++;
|
||||
lv[depth].cblock = bi; lv[depth].sub = 0; lv[depth].last = -1;
|
||||
}
|
||||
}
|
||||
free(M.m);
|
||||
return stacks;
|
||||
}
|
||||
Reference in new issue
Block a user