diff --git a/Makefile b/Makefile index 2d8bd46..7c477f5 100644 --- a/Makefile +++ b/Makefile @@ -34,6 +34,7 @@ VG_DIR := $(LIBDIR)/tinyblocks-vg SVG_DIR := $(LIBDIR)/tinyblocks-svg JPG_DIR := $(LIBDIR)/tinyblocks-jpg SYN_DIR := $(LIBDIR)/tinyblocks-syntax +SB_DIR := $(LIBDIR)/tinyblocks-scratchblocks RE_DIR := $(LIBDIR)/tinyblocks-regex MD_DIR := $(LIBDIR)/tinyblocks-markdown OT_DIR := $(LIBDIR)/tinyblocks-opentype @@ -89,6 +90,7 @@ BP_A := $(BP_DIR)/build/libtinyblocks-blueprint.a API_A := $(API_DIR)/build/libtinyblocks-api.a LIBM_A := $(LIBM_DIR)/build/libtinyblocks-libman.a SYN_A := $(SYN_DIR)/build/libtinyblocks-syntax.a +SB_A := $(SB_DIR)/build/libtinyblocks-scratchblocks.a LIB_LDFLAGS := -L$(ED_DIR)/build -L$(GX_DIR)/build -L$(SD_DIR)/build \ $(foreach l,$(CAT_LIBS),-L$(LIBDIR)/tinyblocks-$(l)/build) -L$(BUILD) @@ -96,12 +98,12 @@ LIB_LDFLAGS := -L$(ED_DIR)/build -L$(GX_DIR)/build -L$(SD_DIR)/build \ editor run-editor run-sdl2 mylib vector customappearance graphics sdl2-backend test-editor \ appdir appimage run-appimage icon \ test-toml test-plugin test-blueprint test-base64 test-curves test-meta test-ppm test-bmp test-png test-image test-vg test-svg test-jpg \ - test-syntax test-os test-input test-stdlib test-regex test-markdown test-opentype \ + test-syntax test-os test-scratchblocks test-input test-stdlib test-regex test-markdown test-opentype \ category-libs category-sos libs \ lib-events lib-control lib-input lib-operators lib-number lib-string lib-variables lib-vector lib-appearance lib-pen lib-fs lib-os \ lib-environ \ lib-editor lib-graphics lib-sdl2 lib-python lib-mcp lib-toml \ - lib-json lib-xml lib-csv lib-blueprint lib-base64 lib-curves lib-ppm lib-bmp lib-png lib-image lib-vg lib-svg lib-jpg lib-syntax lib-regex lib-markdown lib-opentype lib-api lib-libman \ + lib-json lib-xml lib-csv lib-blueprint lib-base64 lib-curves lib-ppm lib-bmp lib-png lib-image lib-vg lib-svg lib-jpg lib-syntax lib-scratchblocks lib-regex lib-markdown lib-opentype lib-api lib-libman \ test-libman test-environ all: static example ## Compila a biblioteca estática e o exemplo hello (padrão) @@ -207,6 +209,9 @@ lib-jpg: lib-syntax: $(MAKE) -C $(SYN_DIR) +lib-scratchblocks: + $(MAKE) -C $(SB_DIR) + lib-regex: $(MAKE) -C $(RE_DIR) @@ -236,7 +241,7 @@ lib-mcp: libs: static lib-events lib-control lib-operators lib-variables \ lib-appearance lib-pen lib-fs lib-os lib-input lib-number lib-string lib-vector lib-environ lib-graphics lib-sdl2 lib-toml \ - lib-json lib-xml lib-csv lib-blueprint lib-base64 lib-curves lib-ppm lib-bmp lib-png lib-image lib-vg lib-svg lib-jpg lib-syntax lib-regex lib-markdown lib-opentype lib-api lib-libman lib-editor + lib-json lib-xml lib-csv lib-blueprint lib-base64 lib-curves lib-ppm lib-bmp lib-png lib-image lib-vg lib-svg lib-jpg lib-syntax lib-scratchblocks lib-regex lib-markdown lib-opentype lib-api lib-libman lib-editor @echo "Libraries OK: category + graphics + sdl2 + toml + json + xml + csv + blueprint + base64 + curves + ppm + bmp + png + image + vg + svg + jpg + syntax + regex + markdown + opentype + api + libman + editor" category-libs: static $(foreach l,$(CAT_LIBS),lib-$(l)) ## Compila as libraries de categoria (.a/.so) @@ -281,7 +286,7 @@ $(BUILD)/editor: examples/editor/main.c static libs -I$(JSON_DIR)/include -I$(XML_DIR)/include -I$(CSV_DIR)/include -I$(BP_DIR)/include \ -I$(API_DIR)/include -I$(LIBM_DIR)/include -I$(SYN_DIR)/include \ $< -o $@ \ - -Wl,--start-group $(ED_A) $(GX_A) $(SD_A) $(TOML_A) $(JSON_A) $(XML_A) $(CSV_A) $(BP_A) $(API_A) $(LIBM_A) $(SYN_A) $(CAT_A) $(LIB_A) -Wl,--end-group \ + -Wl,--start-group $(ED_A) $(GX_A) $(SD_A) $(TOML_A) $(JSON_A) $(XML_A) $(CSV_A) $(BP_A) $(SB_A) $(API_A) $(LIBM_A) $(SYN_A) $(CAT_A) $(LIB_A) -Wl,--end-group \ $(SDL2_LIBS) $(SDL2TTF_LIBS) -ldl -lm -rdynamic \ '-Wl,-rpath,$$ORIGIN' @@ -443,7 +448,7 @@ $(BUILD)/editor_harness: tests/editor_harness.c $(SRCS) \ @mkdir -p $(BUILD) $(CC) $(CFLAGS_DBG) \ -I$(ED_DIR)/include -I$(EDITOR_SRC) -I$(ED_DIR)/internal -I$(EW_DIR)/include -I$(EIMG_DIR)/include -I$(EFILES_DIR)/include -I$(GFX_INC) $(CAT_INCS) -I$(BP_DIR)/include \ - -I$(API_DIR)/include -I$(LIBM_DIR)/include -I$(EN_DIR)/include -I$(TOML_DIR)/include -I$(CV_DIR)/include -I$(B64_DIR)/include -I$(PPM_DIR)/include -I$(SYN_DIR)/include \ + -I$(API_DIR)/include -I$(LIBM_DIR)/include -I$(EN_DIR)/include -I$(TOML_DIR)/include -I$(CV_DIR)/include -I$(B64_DIR)/include -I$(PPM_DIR)/include -I$(SYN_DIR)/include -I$(SB_DIR)/include \ $(SRCS) \ $(EDITOR_SRC)/tb_editor.c $(EDITOR_SRC)/tb_stage_widget.c \ $(EDITOR_SRC)/tb_editor_modules.c \ @@ -452,7 +457,7 @@ $(BUILD)/editor_harness: tests/editor_harness.c $(SRCS) \ $(API_DIR)/src/tb_api.c $(LIBM_DIR)/src/tb_libman.c \ $(TOML_LIB_SRCS) $(TOML_DIR)/src/tb_toml.c \ $(foreach l,$(CAT_LIBS),$(LIBDIR)/tinyblocks-$(l)/src/tb_$(l).c) \ - $(CV_DIR)/src/tb_curves.c $(B64_DIR)/src/tb_base64.c $(PPM_DIR)/src/tb_ppm.c $(SYN_DIR)/src/tb_syntax.c tests/editor_harness.c -o $@ -ldl -lm -rdynamic + $(CV_DIR)/src/tb_curves.c $(B64_DIR)/src/tb_base64.c $(PPM_DIR)/src/tb_ppm.c $(SYN_DIR)/src/tb_syntax.c $(SB_DIR)/src/tb_scratchblocks.c tests/editor_harness.c -o $@ -ldl -lm -rdynamic test-editor: $(BUILD)/editor_harness ## Roda o harness headless do editor (ASan/UBSan) ./$(BUILD)/editor_harness @@ -620,6 +625,15 @@ $(BUILD)/os_fs_test: tests/os_fs_test.c $(FS_DIR)/src/tb_fs.c $(LIBDIR)/tinybloc test-os: $(BUILD)/os_fs_test ## Roda o teste de tinyblocks-os + pastas do tinyblocks-fs (ASan/UBSan) ./$(BUILD)/os_fs_test +$(BUILD)/scratchblocks_test: tests/scratchblocks_test.c $(SB_DIR)/src/tb_scratchblocks.c $(BP_LIB_SRCS) + @mkdir -p $(BUILD) + $(CC) $(CFLAGS_DBG) -I$(SB_DIR)/include -I$(BP_DIR)/include \ + $(SB_DIR)/src/tb_scratchblocks.c $(BP_LIB_SRCS) tests/scratchblocks_test.c \ + -o $@ -Wl,--start-group $(LIB_A) -Wl,--end-group $(EXTRA_TEST_LIBS) + +test-scratchblocks: $(BUILD)/scratchblocks_test static ## Roda o teste da notação scratchblocks (ASan/UBSan) + ./$(BUILD)/scratchblocks_test + $(BUILD)/input_test: tests/input_test.c $(LIBDIR)/tinyblocks-input/src/tb_input.c static @mkdir -p $(BUILD) $(CC) $(CFLAGS_DBG) -I$(LIBDIR)/tinyblocks-input/include -I$(GFX_INC) \ diff --git a/libraries/tinyblocks-editor/Makefile b/libraries/tinyblocks-editor/Makefile index 3951a80..2a0eff6 100644 --- a/libraries/tinyblocks-editor/Makefile +++ b/libraries/tinyblocks-editor/Makefile @@ -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 $@ diff --git a/libraries/tinyblocks-editor/internal/tb_editor_internal.h b/libraries/tinyblocks-editor/internal/tb_editor_internal.h index 525691a..2cbfd77 100644 --- a/libraries/tinyblocks-editor/internal/tb_editor_internal.h +++ b/libraries/tinyblocks-editor/internal/tb_editor_internal.h @@ -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. */ diff --git a/libraries/tinyblocks-editor/libraries/tinyblocks-editor-files/src/tb_editor_files.c b/libraries/tinyblocks-editor/libraries/tinyblocks-editor-files/src/tb_editor_files.c index 6cb22a2..141ddbf 100644 --- a/libraries/tinyblocks-editor/libraries/tinyblocks-editor-files/src/tb_editor_files.c +++ b/libraries/tinyblocks-editor/libraries/tinyblocks-editor-files/src/tb_editor_files.c @@ -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; diff --git a/libraries/tinyblocks-editor/src/tb_editor.c b/libraries/tinyblocks-editor/src/tb_editor.c index fbb0b70..82db05d 100644 --- a/libraries/tinyblocks-editor/src/tb_editor.c +++ b/libraries/tinyblocks-editor/src/tb_editor.c @@ -43,6 +43,8 @@ #include #include #include +#include +#include #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; diff --git a/libraries/tinyblocks-scratchblocks/Makefile b/libraries/tinyblocks-scratchblocks/Makefile new file mode 100644 index 0000000..64db54e --- /dev/null +++ b/libraries/tinyblocks-scratchblocks/Makefile @@ -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) diff --git a/libraries/tinyblocks-scratchblocks/include/tb_scratchblocks.h b/libraries/tinyblocks-scratchblocks/include/tb_scratchblocks.h new file mode 100644 index 0000000..95d3b9c --- /dev/null +++ b/libraries/tinyblocks-scratchblocks/include/tb_scratchblocks.h @@ -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 +#include +#include + +#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 */ diff --git a/libraries/tinyblocks-scratchblocks/library.toml b/libraries/tinyblocks-scratchblocks/library.toml new file mode 100644 index 0000000..f38b35b --- /dev/null +++ b/libraries/tinyblocks-scratchblocks/library.toml @@ -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"] diff --git a/libraries/tinyblocks-scratchblocks/src/tb_scratchblocks.c b/libraries/tinyblocks-scratchblocks/src/tb_scratchblocks.c new file mode 100644 index 0000000..b3c9a21 --- /dev/null +++ b/libraries/tinyblocks-scratchblocks/src/tb_scratchblocks.c @@ -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 +#include +#include +#include +#include + +#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; +} diff --git a/tests/editor_harness.c b/tests/editor_harness.c index fac8a1c..3c313a7 100644 --- a/tests/editor_harness.c +++ b/tests/editor_harness.c @@ -460,7 +460,7 @@ int main(void) { mkdir(fdir, 0755); snprintf(fp, sizeof(fp), "%s/sub", fdir); mkdir(fp, 0755); - snprintf(fp, sizeof(fp), "%s/nota.txt", fdir); + snprintf(fp, sizeof(fp), "%s/nota.md", fdir); FILE* tf = fopen(fp, "wb"); if (tf) { fputs("oi", tf); fclose(tf); } snprintf(fp, sizeof(fp), "%s/proj.json", fdir); @@ -477,7 +477,7 @@ int main(void) { type(fdir); key(TB_KEY_RETURN, 0, 0); CHECK(find("proj.json", R_ANY, 0, &x, &y) && find("sub", R_ANY, 0, &x, &y) - && !find("nota.txt", R_ANY, 0, &x, &y), + && !find("nota.md", R_ANY, 0, &x, &y), "explorador lista pastas + .json e filtra o resto"); if (need("proj.json", R_ANY, 0, &x, &y)) { click(x, y); click(x, y); } frame(0, 0, 0, 0, 0, 0, NULL); @@ -501,7 +501,7 @@ int main(void) { CHECK(!find("Abrir projeto", R_ANY, 0, &x, &y), "Esc fecha o explorador"); remove(fp); - snprintf(fp, sizeof(fp), "%s/nota.txt", fdir); remove(fp); + snprintf(fp, sizeof(fp), "%s/nota.md", fdir); remove(fp); snprintf(fp, sizeof(fp), "%s/sub", fdir); rmdir(fp); rmdir(fdir); } @@ -950,6 +950,43 @@ int main(void) { } } + /* 24. Notação do fórum (scratchblocks): Abrir .txt cria aba; Exportar gera o texto */ + { + const char* src = "/tmp/tb_harness_sb.txt"; + const char* dst = "/tmp/tb_harness_sb_out.txt"; + const char* script = + "when flag clicked\n" + "set [x v] to (0)\n" + "repeat (3)\n" + " change [x v] by (1)\n" + "end\n" + "say (x)\n"; + FILE* f = fopen(src, "wb"); + if (f) { fputs(script, f); fclose(f); } + remove(dst); + frame(0, 0, 0, 0, 0, 0, NULL); + if (need("Abrir", R_FLY, 0, &x, &y)) click(x, y); + for (int i = 0; i < 40; i++) key(TB_KEY_BACKSPACE, 0, 0); + type(src); + key(TB_KEY_RETURN, 0, 0); + frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(any_has("Importado: 1 script"), "Abrir um .txt em scratchblocks cria aba com o script"); + CHECK(any_has("de tb_harness_sb.txt"), "aba nova recebe o nome do arquivo"); + CHECK(find("repita", R_WS, 0, &x, &y) || ws_has("repita"), "blocos importados aparecem (repita)"); + if (need("Exportar", R_FLY, 0, &x, &y)) click(x, y); + if (need("Exportar scratchblocks", R_ANY, 0, &x, &y)) click(x, y); + for (int i = 0; i < 40; i++) key(TB_KEY_BACKSPACE, 0, 0); + type(dst); + key(TB_KEY_RETURN, 0, 0); + frame(0, 0, 0, 0, 0, 0, NULL); + char got[512] = ""; + f = fopen(dst, "rb"); + if (f) { size_t n = fread(got, 1, sizeof(got) - 1, f); got[n] = 0; fclose(f); } + CHECK(!strcmp(got, script), "Exportar scratchblocks gera o mesmo texto"); + if (strcmp(got, script)) printf("---- exportado:\n%s----\n", got); + remove(src); remove(dst); + } + printf("comandos de desenho no último frame: %u\n", ncmd); tinyblocks_deinit(&rt); printf(fails ? "\n%d FALHA(S)\n" : "\nTUDO OK\n", fails); diff --git a/tests/scratchblocks_test.c b/tests/scratchblocks_test.c new file mode 100644 index 0000000..bababdb --- /dev/null +++ b/tests/scratchblocks_test.c @@ -0,0 +1,162 @@ +/* + * scratchblocks_test.c - testa tinyblocks-scratchblocks: notacao de texto do + * forum do Scratch <-> aba de blocos (TbBpTab). + */ +#include +#include +#include +#include +#include + +static int fails = 0; +#define CHECK(c, m) do { if (c) printf("ok %s\n", m); else { printf("FAIL %s\n", m); fails++; } } while (0) + +/* rotulos "do editor" para blocos que so o TinyBlocks tem */ +static const TbSbLabel s_labels[] = { + {"Stage.Circle", "desenhe círculo em x %1 y %2 raio %3"}, + {"FS.IsDir", "%1 é pasta?"}, +}; + +static int shape(const char* type, void* ud) { + (void)ud; + if (!strcmp(type, "FS.IsDir")) return TB_SB_BOOLEAN; + return -1; /* o resto: tabela interna */ +} +static int slot_kind(const char* type, int slot, void* ud) { + (void)ud; (void)slot; + return !strcmp(type, "Stage.Circle") ? TB_SB_SLOT_NUM : TB_SB_SLOT_TEXT; +} +static const char* category(const char* type, void* ud) { + (void)ud; + return !strncmp(type, "Stage.", 6) ? "pen" : "extension"; +} + +static const TbSbContext CX = { s_labels, 2, shape, slot_kind, category, NULL }; + +static TbBpTab* fresh(void) { return calloc(1, sizeof(TbBpTab)); } + +static const char* SCRIPT = + "[scratchblocks]\n" + "when flag clicked\n" + "set [x v] to (0)\n" + "repeat (10)\n" + " change [x v] by (1) // conta\n" + " if <(x) > (5)> then\n" + " say [grande]\n" + " else\n" + " say (join [x = ] (x))\n" + " end\n" + "end\n" + "delete all of [frutas v]\n" + "add [maçã] to [frutas v]\n" + "say (item (1) of [frutas v])\n" + "[/scratchblocks]\n"; + +static const char* EXPECTED = + "when flag clicked\n" + "set [x v] to (0)\n" + "repeat (10)\n" + " change [x v] by (1)\n" + " if <(x) > (5)> then\n" + " say [grande]\n" + " else\n" + " say (join [x = ] (x))\n" + " end\n" + "end\n" + "delete all of [frutas v]\n" + "add [maçã] to [frutas v]\n" + "say (item (1) of [frutas v])\n"; + +static int child(const TbBpTab* t, int bi, int s) { return bi >= 0 ? t->blocks[bi].args[s] : -1; } +static const char* ty(const TbBpTab* t, int bi) { return bi >= 0 ? t->blocks[bi].type : "(nada)"; } + +int main(void) { + char warn[256]; + + /* -- importar ---------------------------------------------------------- */ + TbBpTab* t = fresh(); + int n = tb_scratchblocks_import(SCRIPT, t, &CX, warn, sizeof(warn)); + CHECK(n == 1 && !warn[0], "importa um script (uma pilha, sem avisos)"); + int hat = t->top_n ? t->top[0] : -1; + CHECK(!strcmp(ty(t, hat), "Events.WhenRun"), "chapéu: quando a bandeira for clicada"); + int set = t->blocks[hat].next; + CHECK(!strcmp(ty(t, set), "Variables.Set") && !strcmp(t->blocks[set].in_text[0], "x") && + !strcmp(t->blocks[set].in_text[1], "0"), "set [x v] to (0)"); + int rep = t->blocks[set].next; + CHECK(!strcmp(ty(t, rep), "Control.Repeat") && !strcmp(t->blocks[rep].in_text[0], "10"), "repeat (10)"); + int chg = t->blocks[rep].sub[0]; + CHECK(!strcmp(ty(t, chg), "Variables.Change"), "corpo do repeat começa com change (comentário ignorado)"); + int iff = t->blocks[chg].next; + CHECK(!strcmp(ty(t, iff), "Control.IfElse"), "if ... else ... end vira se/senão"); + int cond = child(t, iff, 0); + CHECK(!strcmp(ty(t, cond), "Operators.Gt") && !strcmp(ty(t, child(t, cond, 0)), "Variables.Get") && + !strcmp(t->blocks[cond].in_text[1], "5"), "condição <(x) > (5)> com variável e número"); + int say2 = t->blocks[iff].sub[1]; + int join = child(t, say2, 0); + CHECK(!strcmp(ty(t, join), "Text.Concat") && !strcmp(t->blocks[join].in_text[0], "x = "), + "senão: say (join [x = ] (x))"); + int after = t->blocks[rep].next; + CHECK(!strcmp(ty(t, after), "List.Clear") && !strcmp(t->blocks[after].in_text[0], "frutas"), + "depois do end: delete all of [frutas v]"); + int add = t->blocks[after].next; + CHECK(!strcmp(ty(t, add), "List.Push") && !strcmp(t->blocks[add].in_text[0], "maçã"), "add [maçã] to [frutas v]"); + int say3 = t->blocks[add].next; + int item = child(t, say3, 0); + CHECK(!strcmp(ty(t, item), "List.Item") && !strcmp(ty(t, child(t, item, 0)), "List.Var") && + !strcmp(t->blocks[child(t, item, 0)].in_text[0], "frutas"), + "item (1) of [frutas v] usa a lista com nome"); + + /* -- exportar ---------------------------------------------------------- */ + char* txt = tb_scratchblocks_export(t, &CX); + CHECK(txt && !strcmp(txt, EXPECTED), "exporta igual ao texto do fórum"); + if (txt && strcmp(txt, EXPECTED)) printf("---- obtido:\n%s----\n", txt); + + /* ida e volta */ + TbBpTab* t2 = fresh(); + tb_scratchblocks_import(txt ? txt : "", t2, &CX, warn, sizeof(warn)); + char* txt2 = tb_scratchblocks_export(t2, &CX); + CHECK(txt2 && txt && !strcmp(txt, txt2), "ida e volta (exportar(importar(texto))) é estável"); + free(txt); free(txt2); free(t2); free(t); + + /* -- blocos só do TinyBlocks: rótulo em português + ::categoria ------- */ + t = fresh(); + n = tb_scratchblocks_import( + "when flag clicked\n" + "desenhe círculo em x (10) y (-20) raio (30) :: pen\n" + "if <[/tmp] é pasta? :: extension> then\n" + " erase all\n" + "end\n" + "\n" + "forever\n" + " set pen size to (4)\n" + "end\n" + "say [isto vira outra pilha]\n", t, &CX, warn, sizeof(warn)); + CHECK(n == 3 && !warn[0], "rótulos em português, chapéu, \"sempre\" e linha em branco separam pilhas"); + if (!(n == 3 && !warn[0])) printf(" n=%d aviso=%s\n", n, warn); + txt = tb_scratchblocks_export(t, &CX); + CHECK(txt && strstr(txt, "desenhe círculo em x (10) y (-20) raio (30) :: pen\n"), + "exporta bloco do TinyBlocks com rótulo em português e ::pen"); + CHECK(txt && strstr(txt, "if <[/tmp] é pasta? :: extension> then\n"), "booleano do TinyBlocks dentro do if"); + if (txt && !strstr(txt, "if <[/tmp] é pasta? :: extension> then\n")) printf("---- obtido:\n%s----\n", txt); + CHECK(txt && strstr(txt, "forever\n set pen size to (4)\nend\n"), "sempre (tampa) com corpo"); + free(txt); free(t); + + /* -- linha desconhecida: avisa e segue -------------------------------- */ + t = fresh(); + n = tb_scratchblocks_import("when flag clicked\nvoe para a lua\nerase all\n", t, &CX, warn, sizeof(warn)); + CHECK(n == 1 && strstr(warn, "linha 2"), "linha desconhecida gera aviso com o número da linha"); + CHECK(!strcmp(ty(t, t->blocks[t->top[0]].next), "Stage.Clear"), "e o resto continua sendo importado"); + free(t); + + /* -- texto com colchetes é escapado ----------------------------------- */ + t = fresh(); + tb_scratchblocks_import("say [a \\] b]\n", t, &CX, warn, sizeof(warn)); + CHECK(!strcmp(t->blocks[t->top[0]].in_text[0], "a ] b"), "\\] dentro de [ ] é texto"); + txt = tb_scratchblocks_export(t, &CX); + CHECK(txt && !strcmp(txt, "say [a \\] b]\n"), "exporta escapando o ]"); + free(txt); free(t); + + if (fails) printf("\n%d FALHA(S)\n", fails); + else printf("\nTUDO OK\n"); + return fails != 0; +}