From 4950ad6006bdf4c70a2e5a365ce91d6175651ac2 Mon Sep 17 00:00:00 2001 From: mguinhos Date: Tue, 20 Oct 2026 19:10:43 -0300 Subject: [PATCH] Estado atual do TinyBlocks: editor estilo Scratch + graphics como interface MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Snapshot do projeto antes de implementar o diálogo "Criar um Bloco": - runtime C block-based (src/, include/) - libraries: graphics (interface), sdl2 (backend), editor (estilo Scratch), python, mcp - exemplos (hello, sdl2, editor, vector, json, customappearance, python, mcp) - Makefile com alvo help e build do editor Co-Authored-By: Claude --- .gitignore | 9 + Makefile | 244 ++ examples/customappearance/customappearance.c | 283 ++ examples/editor/main.c | 185 + examples/hello/main.c | 235 ++ examples/json/json.c | 260 ++ examples/mcp/mcp.c | 109 + examples/mylib/mylib.c | 125 + examples/python/python.c | 111 + examples/sdl2/main.c | 162 + examples/vector/vector.c | 210 ++ include/tinyblocks/tb_block.h | 95 + include/tinyblocks/tb_defs.h | 116 + include/tinyblocks/tb_integer_block.h | 26 + include/tinyblocks/tb_json_block.h | 72 + include/tinyblocks/tb_library_block.h | 82 + include/tinyblocks/tb_real_block.h | 26 + include/tinyblocks/tb_renderable_block.h | 116 + include/tinyblocks/tb_text_block.h | 30 + include/tinyblocks/tb_type_block.h | 72 + include/tinyblocks/tb_vector_block.h | 65 + include/tinyblocks/tinyblocks.h | 113 + libraries/tinyblocks-editor/Makefile | 43 + .../tinyblocks-editor/include/tb_editor.h | 37 + libraries/tinyblocks-editor/src/tb_editor.c | 3020 +++++++++++++++++ libraries/tinyblocks-editor/src/tb_stage.c | 259 ++ libraries/tinyblocks-editor/src/tb_stage.h | 19 + .../tinyblocks-graphics/include/tb_graphics.h | 126 + .../tinyblocks-graphics/src/tb_graphics.c | 383 +++ .../include/tinyblocks-mcp/tb_mcp.h | 36 + libraries/tinyblocks-mcp/src/tb_mcp.c | 125 + libraries/tinyblocks-mcp/src/tb_mcp.py | 115 + libraries/tinyblocks-mcp/src/tb_mcp_py.h | 314 ++ .../include/tinyblocks-python/tb_python.h | 52 + libraries/tinyblocks-python/src/tb_python.c | 179 + libraries/tinyblocks-sdl2/Makefile | 30 + libraries/tinyblocks-sdl2/include/tb_sdl2.h | 61 + libraries/tinyblocks-sdl2/src/tb_sdl2.c | 1089 ++++++ src/tb_block.c | 252 ++ src/tb_integer_block.c | 68 + src/tb_json_block.c | 526 +++ src/tb_library_block.c | 190 ++ src/tb_real_block.c | 68 + src/tb_renderable_block.c | 165 + src/tb_text_block.c | 88 + src/tb_type_block.c | 113 + src/tb_value.c | 62 + src/tb_vector_block.c | 190 ++ src/tinyblocks.c | 240 ++ 49 files changed, 10596 insertions(+) create mode 100644 .gitignore create mode 100644 Makefile create mode 100644 examples/customappearance/customappearance.c create mode 100644 examples/editor/main.c create mode 100644 examples/hello/main.c create mode 100644 examples/json/json.c create mode 100644 examples/mcp/mcp.c create mode 100644 examples/mylib/mylib.c create mode 100644 examples/python/python.c create mode 100644 examples/sdl2/main.c create mode 100644 examples/vector/vector.c create mode 100644 include/tinyblocks/tb_block.h create mode 100644 include/tinyblocks/tb_defs.h create mode 100644 include/tinyblocks/tb_integer_block.h create mode 100644 include/tinyblocks/tb_json_block.h create mode 100644 include/tinyblocks/tb_library_block.h create mode 100644 include/tinyblocks/tb_real_block.h create mode 100644 include/tinyblocks/tb_renderable_block.h create mode 100644 include/tinyblocks/tb_text_block.h create mode 100644 include/tinyblocks/tb_type_block.h create mode 100644 include/tinyblocks/tb_vector_block.h create mode 100644 include/tinyblocks/tinyblocks.h create mode 100644 libraries/tinyblocks-editor/Makefile create mode 100644 libraries/tinyblocks-editor/include/tb_editor.h create mode 100644 libraries/tinyblocks-editor/src/tb_editor.c create mode 100644 libraries/tinyblocks-editor/src/tb_stage.c create mode 100644 libraries/tinyblocks-editor/src/tb_stage.h create mode 100644 libraries/tinyblocks-graphics/include/tb_graphics.h create mode 100644 libraries/tinyblocks-graphics/src/tb_graphics.c create mode 100644 libraries/tinyblocks-mcp/include/tinyblocks-mcp/tb_mcp.h create mode 100644 libraries/tinyblocks-mcp/src/tb_mcp.c create mode 100644 libraries/tinyblocks-mcp/src/tb_mcp.py create mode 100644 libraries/tinyblocks-mcp/src/tb_mcp_py.h create mode 100644 libraries/tinyblocks-python/include/tinyblocks-python/tb_python.h create mode 100644 libraries/tinyblocks-python/src/tb_python.c create mode 100644 libraries/tinyblocks-sdl2/Makefile create mode 100644 libraries/tinyblocks-sdl2/include/tb_sdl2.h create mode 100644 libraries/tinyblocks-sdl2/src/tb_sdl2.c create mode 100644 src/tb_block.c create mode 100644 src/tb_integer_block.c create mode 100644 src/tb_json_block.c create mode 100644 src/tb_library_block.c create mode 100644 src/tb_real_block.c create mode 100644 src/tb_renderable_block.c create mode 100644 src/tb_text_block.c create mode 100644 src/tb_type_block.c create mode 100644 src/tb_value.c create mode 100644 src/tb_vector_block.c create mode 100644 src/tinyblocks.c diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d50f560 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +# Artefatos de build +/build/ +build.tar.xz +*.o +*.a +*.so + +# Configuração local do Claude Code +.claude/settings.local.json diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..f0f467d --- /dev/null +++ b/Makefile @@ -0,0 +1,244 @@ +CC := gcc +CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \ + -D_POSIX_C_SOURCE=200809L -Iinclude +CFLAGS_DBG := $(CFLAGS) -g -DDEBUG -fsanitize=address,undefined +CFLAGS_REL := $(CFLAGS) -O2 -DNDEBUG + +BUILD := build +LIB_A := $(BUILD)/libtinyblocks.a +LIB_SO := $(BUILD)/libtinyblocks.so +EXAMPLE := $(BUILD)/hello +GFX_INC := libraries/tinyblocks-graphics/include +GFX_HDR := $(GFX_INC)/tb_graphics.h + +SRCS := src/tinyblocks.c \ + src/tb_value.c \ + src/tb_block.c \ + src/tb_type_block.c \ + src/tb_library_block.c \ + src/tb_text_block.c \ + src/tb_integer_block.c \ + src/tb_real_block.c \ + src/tb_vector_block.c \ + src/tb_renderable_block.c \ + src/tb_json_block.c + +OBJS := $(patsubst src/%.c,$(BUILD)/%.o,$(SRCS)) +OBJS_DBG := $(patsubst src/%.c,$(BUILD)/%-dbg.o,$(SRCS)) + +.PHONY: all help debug release static shared example sdl2 clean run python-lib mcp-lib json \ + editor run-editor run-sdl2 mylib vector customappearance graphics sdl2-backend + +all: static example ## Compila a biblioteca estática e o exemplo hello (padrão) + +help: ## Lista os alvos disponíveis + @echo "TinyBlocks — alvos do make:" + @echo + @awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / { printf " \033[36m%-18s\033[0m %s\n", $$1, $$2 }' $(MAKEFILE_LIST) + @echo + @echo "Exemplo: make run-editor (libraries extras: ./build/editor build/mylib.so)" + +# ── Biblioteca ──────────────────────────────────────────────────────────── +static: $(LIB_A) ## Compila build/libtinyblocks.a +shared: $(LIB_SO) ## Compila build/libtinyblocks.so + +HDRS := $(wildcard include/tinyblocks/*.h) + +$(BUILD)/%.o: src/%.c $(HDRS) + @mkdir -p $(BUILD) + $(CC) $(CFLAGS_REL) -fPIC -c $< -o $@ + +$(BUILD)/%-dbg.o: src/%.c $(HDRS) + @mkdir -p $(BUILD) + $(CC) $(CFLAGS_DBG) -fPIC -c $< -o $@ + +$(LIB_A): $(OBJS) + ar rcs $@ $^ + +$(LIB_SO): $(OBJS) + $(CC) -shared -o $@ $^ + +# ── Exemplo hello ───────────────────────────────────────────────────────── +$(EXAMPLE): examples/hello/main.c $(LIB_A) + $(CC) $(CFLAGS_REL) $< -o $@ -L$(BUILD) -ltinyblocks + +example: $(EXAMPLE) ## Compila o exemplo hello + +run: example ## Compila e roda o exemplo hello + ./$(EXAMPLE) + +# ── Build de debug com ASan/UBSan ──────────────────────────────────────── +$(BUILD)/libtinyblocks-dbg.a: $(OBJS_DBG) + ar rcs $@ $^ + +$(BUILD)/hello-dbg: examples/hello/main.c $(BUILD)/libtinyblocks-dbg.a + $(CC) $(CFLAGS_DBG) $< -o $@ -L$(BUILD) -ltinyblocks-dbg + +debug: $(BUILD)/hello-dbg ## Compila e roda o hello com ASan/UBSan + ./$(BUILD)/hello-dbg + +# ── Library SDL2 ────────────────────────────────────────────────────────── +SDL2_CFLAGS := $(shell sdl2-config --cflags) +SDL2_LIBS := $(shell sdl2-config --libs) + +$(BUILD)/sdl2-example: examples/sdl2/main.c $(LIB_A) $(BUILD)/libtinyblocks-sdl2.a + $(CC) $(CFLAGS_REL) $(SDL2_CFLAGS) $(SDL2TTF_CFLAGS) \ + -Ilibraries/tinyblocks-sdl2/include \ + $< -o $@ \ + -L$(BUILD) -ltinyblocks-sdl2 -ltinyblocks $(SDL2_LIBS) $(SDL2TTF_LIBS) -lm + +sdl2: static $(BUILD)/libtinyblocks-sdl2.a $(BUILD)/sdl2-example ## Compila a library SDL2 e seu exemplo + @echo "Build SDL2 OK: $(BUILD)/sdl2-example" + +$(BUILD)/libtinyblocks-sdl2.a: $(BUILD)/tb_sdl2.o + ar rcs $@ $^ + +$(BUILD)/tb_sdl2.o: libraries/tinyblocks-sdl2/src/tb_sdl2.c $(GFX_HDR) $(HDRS) + @mkdir -p $(BUILD) + $(CC) $(CFLAGS_REL) $(SDL2_CFLAGS) $(SDL2TTF_CFLAGS) \ + -Ilibraries/tinyblocks-sdl2/include -I$(GFX_INC) -Iinclude -fPIC -c $< -o $@ + +# Backend SDL2 como .so, para trocar em tempo de execução (--backend) +$(BUILD)/libtinyblocks-sdl2.so: libraries/tinyblocks-sdl2/src/tb_sdl2.c $(GFX_HDR) $(LIB_A) + $(CC) $(CFLAGS_REL) $(SDL2_CFLAGS) $(SDL2TTF_CFLAGS) \ + -Ilibraries/tinyblocks-sdl2/include -I$(GFX_INC) -Iinclude -fPIC -shared \ + $< -o $@ -L$(BUILD) -ltinyblocks $(SDL2_LIBS) $(SDL2TTF_LIBS) -lm + +sdl2-backend: static $(BUILD)/libtinyblocks-sdl2.so ## Backend SDL2 como .so (./build/editor --backend build/libtinyblocks-sdl2.so) + @echo "Build backend OK: $(BUILD)/libtinyblocks-sdl2.so" + +# ── Library Graphics (interface; backend padrão: SDL2) ─────────────────── +$(BUILD)/tb_graphics.o: libraries/tinyblocks-graphics/src/tb_graphics.c $(GFX_HDR) $(HDRS) + @mkdir -p $(BUILD) + $(CC) $(CFLAGS_REL) -DTB_GRAPHICS_DEFAULT_SDL2 \ + -I$(GFX_INC) -Ilibraries/tinyblocks-sdl2/include -fPIC -c $< -o $@ + +$(BUILD)/libtinyblocks-graphics.a: $(BUILD)/tb_graphics.o + ar rcs $@ $^ + +graphics: static $(BUILD)/libtinyblocks-graphics.a $(BUILD)/libtinyblocks-sdl2.a ## Interface gráfica (com backend SDL2) + @echo "Build graphics OK: $(BUILD)/libtinyblocks-graphics.a" + +run-sdl2: sdl2 ## Compila e roda o exemplo SDL2 + LD_LIBRARY_PATH=$(BUILD) ./$(BUILD)/sdl2-example + +# ── Library Editor ──────────────────────────────────────────────────────── +SDL2TTF_CFLAGS := $(shell pkg-config --cflags SDL2_ttf 2>/dev/null) +SDL2TTF_LIBS := $(shell pkg-config --libs SDL2_ttf 2>/dev/null) + +EDITOR_SRC := libraries/tinyblocks-editor/src +EDITOR_HDRS := $(EDITOR_SRC)/tb_stage.h libraries/tinyblocks-editor/include/tb_editor.h $(GFX_HDR) $(HDRS) + +$(BUILD)/tb_editor.o: $(EDITOR_SRC)/tb_editor.c $(EDITOR_HDRS) + $(CC) $(CFLAGS_REL) -Ilibraries/tinyblocks-editor/include -I$(GFX_INC) -fPIC -c $< -o $@ + +$(BUILD)/tb_stage.o: $(EDITOR_SRC)/tb_stage.c $(EDITOR_HDRS) + $(CC) $(CFLAGS_REL) -I$(GFX_INC) -fPIC -c $< -o $@ + +$(BUILD)/libtinyblocks-editor.a: $(BUILD)/tb_editor.o $(BUILD)/tb_stage.o + ar rcs $@ $^ + +$(BUILD)/editor: examples/editor/main.c $(LIB_A) $(BUILD)/libtinyblocks-editor.a \ + $(BUILD)/libtinyblocks-graphics.a $(BUILD)/libtinyblocks-sdl2.a + $(CC) $(CFLAGS_REL) -Ilibraries/tinyblocks-editor/include -I$(GFX_INC) \ + $< -o $@ \ + -L$(BUILD) -ltinyblocks-editor -ltinyblocks-graphics -ltinyblocks-sdl2 -ltinyblocks \ + $(SDL2_LIBS) $(SDL2TTF_LIBS) -ldl -lm \ + '-Wl,-rpath,$$ORIGIN' + +editor: static graphics $(BUILD)/libtinyblocks-editor.a $(BUILD)/editor ## Compila o editor visual (estilo Scratch) + @echo "Build editor OK: $(BUILD)/editor" + +run-editor: editor ## Compila e abre o editor visual + ./$(BUILD)/editor + +# ── Exemplo de library externa (hot reload) ────────────────────────────── +$(BUILD)/mylib.so: examples/mylib/mylib.c $(LIB_A) + $(CC) $(CFLAGS_REL) -Iinclude -fPIC -shared \ + $< -o $@ -L$(BUILD) -ltinyblocks '-Wl,-rpath,$$ORIGIN' + +mylib: static $(BUILD)/mylib.so ## Library de exemplo (hot reload) → build/mylib.so + @echo "Build mylib OK: $(BUILD)/mylib.so → Carregue no editor com Ctrl+O" + +# ── Library de vetor 2D ─────────────────────────────────────────────────── +$(BUILD)/vector.so: examples/vector/vector.c $(LIB_A) + $(CC) $(CFLAGS_REL) -Iinclude -fPIC -shared \ + $< -o $@ -L$(BUILD) -ltinyblocks '-Wl,-rpath,$$ORIGIN' + +vector: static $(BUILD)/vector.so ## Library de vetor 2D → build/vector.so + @echo "Build vector OK: $(BUILD)/vector.so → Carregue no editor com Ctrl+O" + +# ── Library de JSON ──────────────────────────────────────────────────────── +$(BUILD)/json.so: examples/json/json.c $(LIB_A) + $(CC) $(CFLAGS_REL) -Iinclude -fPIC -shared \ + $< -o $@ -L$(BUILD) -ltinyblocks '-Wl,-rpath,$$ORIGIN' + +json: static $(BUILD)/json.so ## Library de JSON → build/json.so + @echo "Build json OK: $(BUILD)/json.so → Carregue no editor com Ctrl+O" + +# ── Library de aparência personalizada (on_render demo) ─────────────────── +$(BUILD)/customappearance.so: examples/customappearance/customappearance.c $(LIB_A) + $(CC) $(CFLAGS_REL) -Iinclude -fPIC -shared \ + $< -o $@ -L$(BUILD) -ltinyblocks -lm '-Wl,-rpath,$$ORIGIN' + +customappearance: static $(BUILD)/customappearance.so ## Library de demo do on_draw → build/customappearance.so + @echo "Build customappearance OK: $(BUILD)/customappearance.so" + +# ── Library Python (embedding CPython) ─────────────────────────────────── +PYTHON_CFLAGS := $(shell python3-config --cflags --embed 2>/dev/null || python3-config --cflags) +PYTHON_LIBS := $(shell python3-config --ldflags --embed 2>/dev/null || python3-config --ldflags) + +$(BUILD)/tb_python_lib.o: libraries/tinyblocks-python/src/tb_python.c + @mkdir -p $(BUILD) + $(CC) $(CFLAGS_REL) $(PYTHON_CFLAGS) \ + -Ilibraries/tinyblocks-python/include -fPIC -c $< -o $@ + +# Shared lib — garante um único interpretador Python no processo +$(BUILD)/libtinyblocks-python.so: $(BUILD)/tb_python_lib.o + $(CC) -shared -Wl,-soname,libtinyblocks-python.so -o $@ $^ $(PYTHON_LIBS) + +$(BUILD)/python.so: examples/python/python.c $(LIB_A) $(BUILD)/libtinyblocks-python.so + $(CC) $(CFLAGS_REL) $(PYTHON_CFLAGS) \ + -Ilibraries/tinyblocks-python/include -Iinclude -fPIC -shared \ + $< -o $@ -L$(BUILD) -ltinyblocks -ltinyblocks-python \ + '-Wl,-rpath,$$ORIGIN' + +python-lib: static $(BUILD)/libtinyblocks-python.so $(BUILD)/python.so ## Library Python (CPython embutido) → build/python.so + @echo "Build python OK: $(BUILD)/python.so" + +# ── Library MCP (usa tinyblocks-python) ────────────────────────────────── +# Gera header com o código Python embutido (unsigned char tb_mcp_py[]) +libraries/tinyblocks-mcp/src/tb_mcp_py.h: libraries/tinyblocks-mcp/src/tb_mcp.py + xxd -i -n tb_mcp_py $< $@ + +$(BUILD)/tb_mcp_lib.o: libraries/tinyblocks-mcp/src/tb_mcp.c \ + libraries/tinyblocks-mcp/src/tb_mcp_py.h \ + libraries/tinyblocks-python/include/tinyblocks-python/tb_python.h + @mkdir -p $(BUILD) + $(CC) $(CFLAGS_REL) $(PYTHON_CFLAGS) \ + -Ilibraries/tinyblocks-mcp/include \ + -Ilibraries/tinyblocks-python/include \ + -Ilibraries/tinyblocks-mcp/src \ + -fPIC -c $< -o $@ + +$(BUILD)/libtinyblocks-mcp.so: $(BUILD)/tb_mcp_lib.o $(BUILD)/libtinyblocks-python.so + $(CC) -shared -Wl,-soname,libtinyblocks-mcp.so -o $@ $(BUILD)/tb_mcp_lib.o \ + -L$(BUILD) -ltinyblocks-python $(PYTHON_LIBS) \ + '-Wl,-rpath,$$ORIGIN' + +$(BUILD)/mcp.so: examples/mcp/mcp.c $(LIB_A) \ + $(BUILD)/libtinyblocks-mcp.so $(BUILD)/libtinyblocks-python.so + $(CC) $(CFLAGS_REL) \ + -Ilibraries/tinyblocks-mcp/include \ + -Ilibraries/tinyblocks-python/include \ + -Iinclude -fPIC -shared \ + $< -o $@ -L$(BUILD) -ltinyblocks -ltinyblocks-mcp -ltinyblocks-python \ + '-Wl,-rpath,$$ORIGIN' + +mcp-lib: static $(BUILD)/libtinyblocks-python.so $(BUILD)/libtinyblocks-mcp.so $(BUILD)/mcp.so ## Library cliente MCP → build/mcp.so + @echo "Build mcp OK: $(BUILD)/mcp.so" + +# ── Limpeza ─────────────────────────────────────────────────────────────── +clean: ## Remove o diretório build/ + $(RM) -r $(BUILD) + $(MAKE) -C libraries/tinyblocks-sdl2 clean 2>/dev/null || true diff --git a/examples/customappearance/customappearance.c b/examples/customappearance/customappearance.c new file mode 100644 index 0000000..6b363d1 --- /dev/null +++ b/examples/customappearance/customappearance.c @@ -0,0 +1,283 @@ +/* + * customappearance.c — Demonstração de on_draw (aparência personalizada de bloco). + * + * Blocos: + * Viz.ColorSwatch — inputs: r, g, b, a (0..1) → mostra quadrado colorido + * Viz.Gauge — inputs: value (0..1), r, g, b → barra de progresso + * Viz.Star — inputs: r, g, b, a → estrela de 5 pontas (contorno) + * Viz.BarChart — inputs: a, b, c, d (reais) → mini gráfico de barras + * + * make customappearance → build/customappearance.so + */ + +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include + +/* ── Helpers ─────────────────────────────────────────────────────────────── */ +static float gf(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) { + TinyBlocks_Value v = tb_block_get_input(self, rt, idx); + if (v.kind == TB_VALUE_REAL) return (float)v.as.real; + if (v.kind == TB_VALUE_INTEGER) return (float)v.as.integer; + return 0.0f; +} + +static float out_f(TinyBlocks_Block* self, uint32_t idx) { + if (!self || idx >= self->output_count) return 0.0f; + TinyBlocks_Value* v = &self->outputs[idx]; + if (v->kind == TB_VALUE_REAL) return (float)v->as.real; + if (v->kind == TB_VALUE_INTEGER) return (float)v->as.integer; + return 0.0f; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Viz.ColorSwatch + * ══════════════════════════════════════════════════════════════════════════ */ +static void eval_color_swatch(TinyBlocks_Block* self, TinyBlocks* rt) { + for (uint32_t i = 0; i < 4 && i < self->output_count; i++) + tb_block_set_output(self, i, tb_value_real((double)gf(self, rt, i))); + self->dirty = false; +} + +static bool draw_color_swatch(TinyBlocks_Block* self, TinyBlocks* rt, + TinyBlocks_RenderableBlock** dst) { + (void)rt; + TinyBlocks_RenderableBlock* rb = tb_renderable_acquire(); + if (!rb) return false; + + float r = out_f(self, 0), g = out_f(self, 1); + float b = out_f(self, 2), a = out_f(self, 3); + + /* Área de conteúdo: coordenadas locais ao bloco (0,0 = topo-esq) */ + float bw = 168.f, bh = 60.f; + float pad = 6.f; + float w = bw - 2*pad, h = bh - 2*pad; + + /* Xadrez de fundo */ + float cell = 8.f; + for (float cy = 0; cy < h; cy += cell) { + for (float cx = 0; cx < w; cx += cell) { + float dark = ((int)(cx/cell)+(int)(cy/cell)) % 2 == 0 ? 0.6f : 0.9f; + float cw2 = (cx+cell > w) ? w-cx : cell; + float ch2 = (cy+cell > h) ? h-cy : cell; + tb_draw_fill_rect(rb, pad+cx, pad+cy, cw2, ch2, dark, dark, dark, 1.f); + } + } + + /* Swatch com alpha real */ + tb_draw_fill_rect(rb, pad, pad, w, h, r, g, b, a); + + /* Borda */ + tb_draw_stroke_rect(rb, pad, pad, w, h, 1.f, 0.9f, 0.9f, 0.9f, 0.6f); + + *dst = rb; + return true; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Viz.Gauge + * ══════════════════════════════════════════════════════════════════════════ */ +static void eval_gauge(TinyBlocks_Block* self, TinyBlocks* rt) { + for (uint32_t i = 0; i < 4 && i < self->output_count; i++) + tb_block_set_output(self, i, tb_value_real((double)gf(self, rt, i))); + self->dirty = false; +} + +static bool draw_gauge(TinyBlocks_Block* self, TinyBlocks* rt, + TinyBlocks_RenderableBlock** dst) { + (void)rt; + TinyBlocks_RenderableBlock* rb = tb_renderable_acquire(); + if (!rb) return false; + + float value = out_f(self, 0); + float r = out_f(self, 1), g = out_f(self, 2), b = out_f(self, 3); + if (value < 0.f) value = 0.f; + if (value > 1.f) value = 1.f; + + float bw = 168.f, bh = 60.f; + float pad = 8.f; + float barh = 14.f; + float bary = (bh - barh) * 0.5f; + float barw = bw - 2*pad; + + /* Fundo escuro */ + tb_draw_fill_rect(rb, pad, bary, barw, barh, 0.15f, 0.15f, 0.2f, 1.f); + + /* Preenchimento proporcional */ + if (value > 0.001f) + tb_draw_fill_rect(rb, pad, bary, barw * value, barh, r, g, b, 1.f); + + /* Borda */ + tb_draw_stroke_rect(rb, pad, bary, barw, barh, 1.f, 0.6f, 0.6f, 0.7f, 0.8f); + + *dst = rb; + return true; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Viz.Star + * ══════════════════════════════════════════════════════════════════════════ */ +static void eval_star(TinyBlocks_Block* self, TinyBlocks* rt) { + for (uint32_t i = 0; i < 4 && i < self->output_count; i++) + tb_block_set_output(self, i, tb_value_real((double)gf(self, rt, i))); + self->dirty = false; +} + +static bool draw_star(TinyBlocks_Block* self, TinyBlocks* rt, + TinyBlocks_RenderableBlock** dst) { + (void)rt; + TinyBlocks_RenderableBlock* rb = tb_renderable_acquire(); + if (!rb) return false; + + float r = out_f(self, 0), g = out_f(self, 1); + float b = out_f(self, 2), a = out_f(self, 3); + + float bw = 168.f, bh = 60.f; + float cx = bw * 0.5f, cy = bh * 0.5f; + float ro = (bw < bh ? bw : bh) * 0.42f; + float ri = ro * 0.42f; + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + + /* Desenha 5 linhas da estrela (conecta pontos alternados) */ + float px[10], py[10]; + for (int i = 0; i < 10; i++) { + float angle = (float)i * (float)M_PI / 5.f - (float)M_PI / 2.f; + float rad = (i % 2 == 0) ? ro : ri; + px[i] = cx + rad * cosf(angle); + py[i] = cy + rad * sinf(angle); + } + /* Contorno */ + for (int i = 0; i < 10; i++) { + int j = (i + 1) % 10; + tb_draw_stroke_line(rb, px[i], py[i], px[j], py[j], 1.5f, r, g, b, a); + } + /* Diagonais internas (estrela de 5 pontas típica) */ + for (int i = 0; i < 5; i++) { + int j = (i + 2) % 10 * 2 % 10; + tb_draw_stroke_line(rb, px[i*2], py[i*2], px[j], py[j], 1.f, r*0.6f, g*0.6f, b*0.6f, a); + } + + *dst = rb; + return true; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Viz.BarChart + * ══════════════════════════════════════════════════════════════════════════ */ +static void eval_barchart(TinyBlocks_Block* self, TinyBlocks* rt) { + for (uint32_t i = 0; i < 4 && i < self->output_count; i++) + tb_block_set_output(self, i, tb_value_real((double)gf(self, rt, i))); + self->dirty = false; +} + +static bool draw_barchart(TinyBlocks_Block* self, TinyBlocks* rt, + TinyBlocks_RenderableBlock** dst) { + (void)rt; + TinyBlocks_RenderableBlock* rb = tb_renderable_acquire(); + if (!rb) return false; + + float vals[4]; + for (int i = 0; i < 4; i++) vals[i] = out_f(self, i); + + float maxv = 0.001f; + for (int i = 0; i < 4; i++) if (vals[i] > maxv) maxv = vals[i]; + + static const float colors[4][3] = { + {0.36f, 0.70f, 1.00f}, + {0.40f, 0.86f, 0.56f}, + {1.00f, 0.75f, 0.30f}, + {0.86f, 0.40f, 0.50f}, + }; + + float bw = 168.f, bh = 60.f; + float pad = 6.f; + float gap = 4.f; + float tw = bw - 2*pad; + float th = bh - 2*pad - 4.f; + float barw = (tw - gap*3.f) / 4.f; + + /* Linha de base */ + tb_draw_fill_rect(rb, pad, pad+th, tw, 1.f, 0.3f, 0.3f, 0.35f, 1.f); + + for (int i = 0; i < 4; i++) { + float norm = vals[i] / maxv; + float bh2 = norm * th; + float bx = pad + i * (barw + gap); + float by = pad + th - bh2; + if (bh2 < 1.f) bh2 = 1.f; + tb_draw_fill_rect(rb, bx, by, barw, bh2, + colors[i][0], colors[i][1], colors[i][2], 0.9f); + } + + *dst = rb; + return true; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Descritores de slots + * ══════════════════════════════════════════════════════════════════════════ */ +static const TinyBlocks_SlotDesc rgba_in[] = { + {"r", TB_VALUE_REAL}, {"g", TB_VALUE_REAL}, + {"b", TB_VALUE_REAL}, {"a", TB_VALUE_REAL} +}; +static const TinyBlocks_SlotDesc rgba_out[] = { + {"r", TB_VALUE_REAL}, {"g", TB_VALUE_REAL}, + {"b", TB_VALUE_REAL}, {"a", TB_VALUE_REAL} +}; +static const TinyBlocks_SlotDesc gauge_in[] = { + {"value", TB_VALUE_REAL}, + {"r", TB_VALUE_REAL}, {"g", TB_VALUE_REAL}, {"b", TB_VALUE_REAL} +}; +static const TinyBlocks_SlotDesc gauge_out[] = { + {"value", TB_VALUE_REAL}, + {"r", TB_VALUE_REAL}, {"g", TB_VALUE_REAL}, {"b", TB_VALUE_REAL} +}; +static const TinyBlocks_SlotDesc chart_in[] = { + {"a", TB_VALUE_REAL}, {"b", TB_VALUE_REAL}, + {"c", TB_VALUE_REAL}, {"d", TB_VALUE_REAL} +}; +static const TinyBlocks_SlotDesc chart_out[] = { + {"a", TB_VALUE_REAL}, {"b", TB_VALUE_REAL}, + {"c", TB_VALUE_REAL}, {"d", TB_VALUE_REAL} +}; + +/* ══════════════════════════════════════════════════════════════════════════ + * Registro + * ══════════════════════════════════════════════════════════════════════════ */ +static bool ca_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + TinyBlocks_TypeBlock* t; + +#define REG_VIZ(name, ins, ni, outs, no, eval_fn, draw_fn) \ + t = tb_type_block_create(rt, name, ins, ni, outs, no, eval_fn); \ + if (t) { t->on_draw = draw_fn; tb_library_add(lib, &t->base); } + + REG_VIZ("Viz.ColorSwatch", rgba_in, 4, rgba_out, 4, + eval_color_swatch, draw_color_swatch); + + REG_VIZ("Viz.Gauge", gauge_in, 4, gauge_out, 4, + eval_gauge, draw_gauge); + + REG_VIZ("Viz.Star", rgba_in, 4, rgba_out, 4, + eval_star, draw_star); + + REG_VIZ("Viz.BarChart", chart_in, 4, chart_out, 4, + eval_barchart, draw_barchart); + +#undef REG_VIZ + return true; +} + +static void ca_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + (void)rt; (void)lib; +} + +TINYBLOCKS_DEFINE_LIBRARY(customappearance, + "customappearance", + "1.0.0", + ca_init, + ca_deinit) diff --git a/examples/editor/main.c b/examples/editor/main.c new file mode 100644 index 0000000..ba07a3d --- /dev/null +++ b/examples/editor/main.c @@ -0,0 +1,185 @@ +/* + * TinyBlocks — exemplo editor + * + * Abre o editor visual com os blocos Math.* e IO.Print pré-registrados. + * A janela vem da interface tinyblocks-graphics; o backend padrão é SDL2 e + * pode ser trocado por outro .so: + * + * ./editor [--backend libbackend.so] [library.so ...] + */ +#include +#include +#include +#include +#include +#include + +/* ── TypeBlocks de demonstração ─────────────────────────────────────────── */ +static void eval_math_add(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value a = tb_block_get_input(self, rt, 0); + TinyBlocks_Value b = tb_block_get_input(self, rt, 1); + int64_t va = a.kind==TB_VALUE_INTEGER ? a.as.integer : 0; + int64_t vb = b.kind==TB_VALUE_INTEGER ? b.as.integer : 0; + tb_block_set_output(self, 0, tb_value_integer(va + vb)); +} +static void eval_math_sub(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value a = tb_block_get_input(self, rt, 0); + TinyBlocks_Value b = tb_block_get_input(self, rt, 1); + int64_t va = a.kind==TB_VALUE_INTEGER ? a.as.integer : 0; + int64_t vb = b.kind==TB_VALUE_INTEGER ? b.as.integer : 0; + tb_block_set_output(self, 0, tb_value_integer(va - vb)); +} +static void eval_math_mul(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value a = tb_block_get_input(self, rt, 0); + TinyBlocks_Value b = tb_block_get_input(self, rt, 1); + int64_t va = a.kind==TB_VALUE_INTEGER ? a.as.integer : 0; + int64_t vb = b.kind==TB_VALUE_INTEGER ? b.as.integer : 0; + tb_block_set_output(self, 0, tb_value_integer(va * vb)); +} +static void eval_math_div(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value a = tb_block_get_input(self, rt, 0); + TinyBlocks_Value b = tb_block_get_input(self, rt, 1); + int64_t va = a.kind==TB_VALUE_INTEGER ? a.as.integer : 0; + int64_t vb = b.kind==TB_VALUE_INTEGER ? b.as.integer : 1; + tb_block_set_output(self, 0, tb_value_integer(vb ? va/vb : 0)); +} +static void eval_math_mod(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value a = tb_block_get_input(self, rt, 0); + TinyBlocks_Value b = tb_block_get_input(self, rt, 1); + int64_t va = a.kind==TB_VALUE_INTEGER ? a.as.integer : 0; + int64_t vb = b.kind==TB_VALUE_INTEGER ? b.as.integer : 1; + tb_block_set_output(self, 0, tb_value_integer(vb ? va%vb : 0)); +} +static void eval_math_abs(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value a = tb_block_get_input(self, rt, 0); + int64_t v = a.kind==TB_VALUE_INTEGER ? a.as.integer : 0; + tb_block_set_output(self, 0, tb_value_integer(v<0 ? -v : v)); +} +static void eval_math_max(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value a = tb_block_get_input(self, rt, 0); + TinyBlocks_Value b = tb_block_get_input(self, rt, 1); + int64_t va = a.kind==TB_VALUE_INTEGER ? a.as.integer : 0; + int64_t vb = b.kind==TB_VALUE_INTEGER ? b.as.integer : 0; + tb_block_set_output(self, 0, tb_value_integer(va>vb ? va : vb)); +} +static void eval_math_min(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value a = tb_block_get_input(self, rt, 0); + TinyBlocks_Value b = tb_block_get_input(self, rt, 1); + int64_t va = a.kind==TB_VALUE_INTEGER ? a.as.integer : 0; + int64_t vb = b.kind==TB_VALUE_INTEGER ? b.as.integer : 0; + tb_block_set_output(self, 0, tb_value_integer(vaname); + tb_graphics_run(rt); /* loop até a janela principal fechar */ + + tinyblocks_deinit(&rt); + return 0; +} diff --git a/examples/hello/main.c b/examples/hello/main.c new file mode 100644 index 0000000..f79dcd0 --- /dev/null +++ b/examples/hello/main.c @@ -0,0 +1,235 @@ +/* + * TinyBlocks — exemplo hello + * + * Demonstra: + * 1. Inicializar o runtime + * 2. Criar TypeBlocks (Math.Add, Math.Mul, IO.Print) + * 3. Criar blocos literais (IntegerBlock, TextBlock) + * 4. Conectar blocos e avaliar + * 5. Usar LibraryBlock como namespace + */ +#include +#include + +/* ── TypeBlock: Math.Add ─────────────────────────────────────────────────── */ +/* inputs: a(int), b(int) + * outputs: result(int) */ +static void eval_math_add(TinyBlocks_Block* self, TinyBlocks* rt) +{ + TinyBlocks_Value va = tb_block_get_input(self, rt, 0); + TinyBlocks_Value vb = tb_block_get_input(self, rt, 1); + int64_t a = va.kind == TB_VALUE_INTEGER ? va.as.integer : 0; + int64_t b = vb.kind == TB_VALUE_INTEGER ? vb.as.integer : 0; + tb_block_set_output(self, 0, tb_value_integer(a + b)); +} + +/* ── TypeBlock: Math.Mul ─────────────────────────────────────────────────── */ +static void eval_math_mul(TinyBlocks_Block* self, TinyBlocks* rt) +{ + TinyBlocks_Value va = tb_block_get_input(self, rt, 0); + TinyBlocks_Value vb = tb_block_get_input(self, rt, 1); + int64_t a = va.kind == TB_VALUE_INTEGER ? va.as.integer : 0; + int64_t b = vb.kind == TB_VALUE_INTEGER ? vb.as.integer : 0; + tb_block_set_output(self, 0, tb_value_integer(a * b)); +} + +/* ── TypeBlock: IO.Print ─────────────────────────────────────────────────── */ +/* inputs: label(text), value(int) + * outputs: (nenhum) */ +static void eval_io_print(TinyBlocks_Block* self, TinyBlocks* rt) +{ + TinyBlocks_Value vlabel = tb_block_get_input(self, rt, 0); + TinyBlocks_Value vvalue = tb_block_get_input(self, rt, 1); + + const char* label = vlabel.kind == TB_VALUE_TEXT ? vlabel.as.text : "(sem rótulo)"; + + char valstr[64] = "?"; + if (vvalue.kind == TB_VALUE_INTEGER) + snprintf(valstr, sizeof(valstr), "%lld", (long long)vvalue.as.integer); + else if (vvalue.kind == TB_VALUE_REAL) + snprintf(valstr, sizeof(valstr), "%g", vvalue.as.real); + else if (vvalue.kind == TB_VALUE_TEXT) + snprintf(valstr, sizeof(valstr), "%s", vvalue.as.text); + + printf("[IO.Print] %s = %s\n", label, valstr); +} + +/* ── TypeBlock: Math.Factorial (demonstra userdata por instância) ─────────── */ +/* inputs: n(int) + * outputs: result(int) */ +typedef struct { int64_t memo; } FactorialData; + +static void eval_math_factorial(TinyBlocks_Block* self, TinyBlocks* rt) +{ + TinyBlocks_Value vn = tb_block_get_input(self, rt, 0); + int64_t n = vn.kind == TB_VALUE_INTEGER ? vn.as.integer : 0; + int64_t result = 1; + for (int64_t i = 2; i <= n; ++i) result *= i; + + FactorialData* d = (FactorialData*)self->userdata; + if (d) d->memo = result; /* guarda no userdata por instância */ + + tb_block_set_output(self, 0, tb_value_integer(result)); +} + +/* ═══════════════════════════════════════════════════════════════════════════ + * main + * ═══════════════════════════════════════════════════════════════════════════ */ +int main(void) +{ + printf("=== TinyBlocks — exemplo hello ===\n\n"); + + /* 1. Inicializar runtime */ + TinyBlocks* rt = NULL; + if (!tinyblocks_init(&rt, NULL)) { + fprintf(stderr, "Falha ao inicializar TinyBlocks\n"); + return 1; + } + printf("[runtime] inicializado id_counter=%llu\n\n", + (unsigned long long)rt->next_id); + + /* 2. Criar library "Math" */ + TinyBlocks_LibraryBlock* lib_math = tb_library_block_create(rt, "Math"); + TinyBlocks_LibraryBlock* lib_io = tb_library_block_create(rt, "IO"); + + /* 3. Definir slots e TypeBlocks */ + static const TinyBlocks_SlotDesc two_int_ins[] = { + { "a", TB_VALUE_INTEGER }, { "b", TB_VALUE_INTEGER } }; + static const TinyBlocks_SlotDesc int_out[] = { + { "result", TB_VALUE_INTEGER } }; + static const TinyBlocks_SlotDesc one_int_in[] = { + { "n", TB_VALUE_INTEGER } }; + static const TinyBlocks_SlotDesc print_ins[] = { + { "label", TB_VALUE_TEXT }, { "value", TB_VALUE_NONE } }; + + TinyBlocks_TypeBlock* t_add = tb_type_block_create(rt, "Math.Add", + two_int_ins, 2, int_out, 1, eval_math_add); + TinyBlocks_TypeBlock* t_mul = tb_type_block_create(rt, "Math.Mul", + two_int_ins, 2, int_out, 1, eval_math_mul); + TinyBlocks_TypeBlock* t_fact = tb_type_block_create(rt, "Math.Factorial", + one_int_in, 1, int_out, 1, eval_math_factorial); + TinyBlocks_TypeBlock* t_print = tb_type_block_create(rt, "IO.Print", + print_ins, 2, NULL, 0, eval_io_print); + + /* Factorial usa userdata por instância */ + tb_type_block_set_instance_hooks(t_fact, sizeof(FactorialData), NULL, NULL); + + /* Adiciona às libraries */ + tb_library_add(lib_math, &t_add->base); + tb_library_add(lib_math, &t_mul->base); + tb_library_add(lib_math, &t_fact->base); + tb_library_add(lib_io, &t_print->base); + + printf("[types] Math.Add, Math.Mul, Math.Factorial, IO.Print registrados\n"); + printf("[libs] Math=%u blocos, IO=%u bloco(s)\n\n", + lib_math->block_count, lib_io->block_count); + + /* ── Exemplo 1: 3 + 4 ───────────────────────────────────────────────── */ + printf("--- Exemplo 1: 3 + 4 ---\n"); + { + TinyBlocks_IntegerBlock* lit3 = tb_integer_block_create(rt, 3); + TinyBlocks_IntegerBlock* lit4 = tb_integer_block_create(rt, 4); + TinyBlocks_TextBlock* label = tb_text_block_create(rt, "3 + 4"); + TinyBlocks_Block* add = tb_block_create(rt, t_add); + TinyBlocks_Block* print = tb_block_create(rt, t_print); + + /* Conecta: add.in[0] ← lit3.out[0] + add.in[1] ← lit4.out[0] */ + tb_block_connect(add, 0, &lit3->base, 0); + tb_block_connect(add, 1, &lit4->base, 0); + + /* print.in[0] ← label.out[0] + print.in[1] ← add.out[0] */ + tb_block_connect(print, 0, &label->base, 0); + tb_block_connect(print, 1, add, 0); + + /* Avalia a cadeia inteira (lazy: avalia dependências primeiro) */ + tb_block_eval(print, rt); + } + + /* ── Exemplo 2: (2 + 3) * 5 ────────────────────────────────────────── */ + printf("\n--- Exemplo 2: (2 + 3) * 5 ---\n"); + { + TinyBlocks_IntegerBlock* lit2 = tb_integer_block_create(rt, 2); + TinyBlocks_IntegerBlock* lit3 = tb_integer_block_create(rt, 3); + TinyBlocks_IntegerBlock* lit5 = tb_integer_block_create(rt, 5); + TinyBlocks_TextBlock* label = tb_text_block_create(rt, "(2+3)*5"); + TinyBlocks_Block* add = tb_block_create(rt, t_add); + TinyBlocks_Block* mul = tb_block_create(rt, t_mul); + TinyBlocks_Block* print = tb_block_create(rt, t_print); + + tb_block_connect(add, 0, &lit2->base, 0); + tb_block_connect(add, 1, &lit3->base, 0); + tb_block_connect(mul, 0, add, 0); + tb_block_connect(mul, 1, &lit5->base, 0); + tb_block_connect(print, 0, &label->base, 0); + tb_block_connect(print, 1, mul, 0); + + tb_block_eval(print, rt); + } + + /* ── Exemplo 3: 7! (fatorial com userdata por instância) ────────────── */ + printf("\n--- Exemplo 3: 7! ---\n"); + { + TinyBlocks_IntegerBlock* lit7 = tb_integer_block_create(rt, 7); + TinyBlocks_TextBlock* label = tb_text_block_create(rt, "7!"); + TinyBlocks_Block* fact = tb_block_create(rt, t_fact); + TinyBlocks_Block* print = tb_block_create(rt, t_print); + + tb_block_connect(fact, 0, &lit7->base, 0); + tb_block_connect(print, 0, &label->base, 0); + tb_block_connect(print, 1, fact, 0); + + tb_block_eval(print, rt); + + /* Lê o valor memoizado do userdata */ + FactorialData* d = (FactorialData*)fact->userdata; + printf(" userdata.memo = %lld\n", (long long)d->memo); + } + + /* ── Exemplo 4: busca de tipo por nome ──────────────────────────────── */ + printf("\n--- Exemplo 4: busca de tipo por nome ---\n"); + { + TinyBlocks_TypeBlock* found = tb_type_block_find(rt, "Math.Add"); + printf("tb_type_block_find(\"Math.Add\") = %s\n", + found ? found->type_name : "NULL"); + + /* Busca dentro da library */ + TinyBlocks_Block* b = tb_library_find(lib_math, "Math.Mul"); + printf("tb_library_find(lib_math, \"Math.Mul\") kind=%d name=%s\n", + b ? (int)b->kind : -1, + b && b->kind == TB_KIND_TYPE + ? ((TinyBlocks_TypeBlock*)b)->type_name : "?"); + } + + /* ── Exemplo 5: to_string ────────────────────────────────────────────── */ + printf("\n--- Exemplo 5: representação textual ---\n"); + { + TinyBlocks_IntegerBlock* ib = tb_integer_block_create(rt, 42); + TinyBlocks_RealBlock* rb = tb_real_block_create(rt, 3.14); + TinyBlocks_TextBlock* tb2 = tb_text_block_create(rt, "olá"); + + char buf[256]; + tb_block_eval(&ib->base, rt); + tb_block_eval(&rb->base, rt); + tb_block_eval(&tb2->base, rt); + + tb_block_to_string(&ib->base, rt, buf, sizeof(buf)); + printf("IntegerBlock: %s\n", buf); + tb_block_to_string(&rb->base, rt, buf, sizeof(buf)); + printf("RealBlock: %s\n", buf); + tb_block_to_string(&tb2->base, rt, buf, sizeof(buf)); + printf("TextBlock: %s\n", buf); + } + + /* ── Resumo do runtime ───────────────────────────────────────────────── */ + printf("\n--- Estado do runtime ---\n"); + printf("blocks vivos: %u\n", rt->block_count); + printf("types: %u\n", rt->type_count); + printf("libraries: %u\n", rt->library_count); + + /* 4. Desinicializar (libera tudo) */ + tinyblocks_deinit(&rt); + printf("\n[runtime] deinicializado. rt = %p\n", (void*)rt); + return 0; +} diff --git a/examples/json/json.c b/examples/json/json.c new file mode 100644 index 0000000..e0dbd56 --- /dev/null +++ b/examples/json/json.c @@ -0,0 +1,260 @@ +/* + * json.c — Library de JSON para o TinyBlocks Editor. + * + * Blocos incluídos: + * Json.Parse — texto -> json (null em caso de erro de sintaxe) + * Json.Stringify — json -> texto + * Json.Null — constrói json null + * Json.Bool — inteiro (0/1) -> json bool + * Json.Number — real -> json number + * Json.String — texto -> json string + * Json.Array — constrói array vazio + * Json.Object — constrói objeto vazio + * Json.Push — (array, valor) -> novo array com valor anexado + * Json.Set — (objeto, chave, valor) -> novo objeto com campo definido + * Json.Get — (objeto, chave) -> valor do campo, ou Json.Null + * Json.Index — (array, índice) -> valor na posição, ou Json.Null + * Json.Length — (json) -> nº de elementos (array/objeto) ou 0 + * Json.TypeOf — (json) -> "null"|"bool"|"number"|"string"|"array"|"object" + * Json.ToNumber — (json, default) -> número (ou default se não for number/bool) + * Json.ToText — (json) -> string contida, ou "" se não for string + * Json.ToBool — (json, default) -> 0/1 (ou default se não for bool/number) + * + * Json.Push/Json.Set não mutam o valor recebido: clonam e devolvem uma nova + * árvore, mantendo o fluxo de dados imutável como o resto do TinyBlocks. + * + * Para compilar: + * make json + * + * Para carregar no editor: + * Ctrl+O → build/json.so ou arraste build/json.so para a janela + */ + +#define _POSIX_C_SOURCE 200809L +#include +#include + +#include + +/* ── Helpers de leitura de inputs ────────────────────────────────────────── */ +static const char* gt(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) { + TinyBlocks_Value v = tb_block_get_input(self, rt, idx); + return v.kind == TB_VALUE_TEXT ? v.as.text : ""; +} + +static double gn(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) { + TinyBlocks_Value v = tb_block_get_input(self, rt, idx); + if (v.kind == TB_VALUE_REAL) return v.as.real; + if (v.kind == TB_VALUE_INTEGER) return (double)v.as.integer; + return 0.0; +} + +static int64_t gi(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) { + TinyBlocks_Value v = tb_block_get_input(self, rt, idx); + if (v.kind == TB_VALUE_INTEGER) return v.as.integer; + if (v.kind == TB_VALUE_REAL) return (int64_t)v.as.real; + return 0; +} + +static TinyBlocks_JsonValue* gj(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) { + TinyBlocks_Value v = tb_block_get_input(self, rt, idx); + return tb_value_as_json(v); +} + +/* Macro: produz output json/texto/integer/real e libera self->dirty */ +#define EMIT_JSON(self, j) do { \ + tb_block_set_output((self), 0, tb_value_json(j)); \ + tb_json_release(j); \ + (self)->dirty = false; \ +} while (0) + +/* ══════════════════════════════════════════════════════════════════════════ + * Implementações dos blocos + * ══════════════════════════════════════════════════════════════════════════ */ + +static void eval_parse(TinyBlocks_Block* self, TinyBlocks* rt) { + char err[128] = {0}; + TinyBlocks_JsonValue* j = tb_json_parse(gt(self, rt, 0), err, sizeof(err)); + if (!j) j = tb_json_null(); + EMIT_JSON(self, j); +} + +static void eval_stringify(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* j = gj(self, rt, 0); + char* s = tb_json_stringify(j); + tb_block_set_output(self, 0, tb_value_text(s ? s : "null")); + free(s); + self->dirty = false; +} + +static void eval_null(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + EMIT_JSON(self, tb_json_null()); +} + +static void eval_bool(TinyBlocks_Block* self, TinyBlocks* rt) { + EMIT_JSON(self, tb_json_bool(gi(self, rt, 0) != 0)); +} + +static void eval_number(TinyBlocks_Block* self, TinyBlocks* rt) { + EMIT_JSON(self, tb_json_number(gn(self, rt, 0))); +} + +static void eval_string(TinyBlocks_Block* self, TinyBlocks* rt) { + EMIT_JSON(self, tb_json_string(gt(self, rt, 0))); +} + +static void eval_array(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + EMIT_JSON(self, tb_json_array()); +} + +static void eval_object(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + EMIT_JSON(self, tb_json_object()); +} + +static void eval_push(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* arr = tb_json_clone(gj(self, rt, 0)); + if (!arr || tb_json_kind(arr) != TB_JSON_ARRAY) { + tb_json_release(arr); + arr = tb_json_array(); + } + TinyBlocks_JsonValue* item = gj(self, rt, 1); + tb_json_array_push(arr, item ? item : tb_json_null()); + EMIT_JSON(self, arr); +} + +static void eval_set(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* obj = tb_json_clone(gj(self, rt, 0)); + if (!obj || tb_json_kind(obj) != TB_JSON_OBJECT) { + tb_json_release(obj); + obj = tb_json_object(); + } + TinyBlocks_JsonValue* val = gj(self, rt, 2); + tb_json_object_set(obj, gt(self, rt, 1), val ? val : tb_json_null()); + EMIT_JSON(self, obj); +} + +static void eval_get(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* obj = gj(self, rt, 0); + TinyBlocks_JsonValue* val = tb_json_object_get(obj, gt(self, rt, 1)); + if (!val) val = tb_json_null(); + EMIT_JSON(self, val); +} + +static void eval_index(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* arr = gj(self, rt, 0); + int64_t idx = gi(self, rt, 1); + TinyBlocks_JsonValue* val = (idx >= 0) ? tb_json_array_get(arr, (uint32_t)idx) : NULL; + if (!val) val = tb_json_null(); + EMIT_JSON(self, val); +} + +static void eval_length(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* j = gj(self, rt, 0); + uint32_t n = 0; + switch (tb_json_kind(j)) { + case TB_JSON_ARRAY: n = tb_json_array_length(j); break; + case TB_JSON_OBJECT: n = tb_json_object_length(j); break; + case TB_JSON_STRING: n = (uint32_t)strlen(tb_json_as_string(j)); break; + default: break; + } + tb_block_set_output(self, 0, tb_value_integer(n)); + self->dirty = false; +} + +static void eval_typeof(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* j = gj(self, rt, 0); + tb_block_set_output(self, 0, tb_value_text(tb_json_kind_name(j))); + self->dirty = false; +} + +static void eval_to_number(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* j = gj(self, rt, 0); + double def = gn(self, rt, 1); + tb_block_set_output(self, 0, tb_value_real(tb_json_as_number(j, def))); + self->dirty = false; +} + +static void eval_to_text(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* j = gj(self, rt, 0); + const char* s = tb_json_as_string(j); + tb_block_set_output(self, 0, tb_value_text(s ? s : "")); + self->dirty = false; +} + +static void eval_to_bool(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* j = gj(self, rt, 0); + bool def = gi(self, rt, 1) != 0; + tb_block_set_output(self, 0, tb_value_integer(tb_json_as_bool(j, def) ? 1 : 0)); + self->dirty = false; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Descritores de slots + * ══════════════════════════════════════════════════════════════════════════ */ +static const TinyBlocks_SlotDesc out_json[] = {{"json", TB_VALUE_JSON}}; +static const TinyBlocks_SlotDesc out_text[] = {{"text", TB_VALUE_TEXT}}; +static const TinyBlocks_SlotDesc out_integer[] = {{"n", TB_VALUE_INTEGER}}; +static const TinyBlocks_SlotDesc out_real[] = {{"n", TB_VALUE_REAL}}; + +static const TinyBlocks_SlotDesc in_text[] = {{"text", TB_VALUE_TEXT}}; +static const TinyBlocks_SlotDesc in_json[] = {{"json", TB_VALUE_JSON}}; +static const TinyBlocks_SlotDesc in_integer[] = {{"n", TB_VALUE_INTEGER}}; +static const TinyBlocks_SlotDesc in_real[] = {{"n", TB_VALUE_REAL}}; +static const TinyBlocks_SlotDesc in_json_json[] = {{"a", TB_VALUE_JSON}, + {"b", TB_VALUE_JSON}}; +static const TinyBlocks_SlotDesc in_json_text_json[] = {{"obj", TB_VALUE_JSON}, + {"key", TB_VALUE_TEXT}, + {"val", TB_VALUE_JSON}}; +static const TinyBlocks_SlotDesc in_json_text[] = {{"obj", TB_VALUE_JSON}, + {"key", TB_VALUE_TEXT}}; +static const TinyBlocks_SlotDesc in_json_int[] = {{"arr", TB_VALUE_JSON}, + {"idx", TB_VALUE_INTEGER}}; +static const TinyBlocks_SlotDesc in_json_real[] = {{"json", TB_VALUE_JSON}, + {"def", TB_VALUE_REAL}}; +static const TinyBlocks_SlotDesc in_json_int_def[] = {{"json", TB_VALUE_JSON}, + {"def", TB_VALUE_INTEGER}}; + +/* ══════════════════════════════════════════════════════════════════════════ + * Registro da library + * ══════════════════════════════════════════════════════════════════════════ */ +static bool json_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + TinyBlocks_TypeBlock* t; + +#define REG(name, ins, ni, outs, no, fn) \ + t = tb_type_block_create(rt, name, ins, ni, outs, no, fn); \ + if (t) tb_library_add(lib, &t->base) + + REG("Json.Parse", in_text, 1, out_json, 1, eval_parse); + REG("Json.Stringify", in_json, 1, out_text, 1, eval_stringify); + REG("Json.Null", NULL, 0, out_json, 1, eval_null); + REG("Json.Bool", in_integer, 1, out_json, 1, eval_bool); + REG("Json.Number", in_real, 1, out_json, 1, eval_number); + REG("Json.String", in_text, 1, out_json, 1, eval_string); + REG("Json.Array", NULL, 0, out_json, 1, eval_array); + REG("Json.Object", NULL, 0, out_json, 1, eval_object); + REG("Json.Push", in_json_json, 2, out_json, 1, eval_push); + REG("Json.Set", in_json_text_json, 3, out_json, 1, eval_set); + REG("Json.Get", in_json_text, 2, out_json, 1, eval_get); + REG("Json.Index", in_json_int, 2, out_json, 1, eval_index); + REG("Json.Length", in_json, 1, out_integer, 1, eval_length); + REG("Json.TypeOf", in_json, 1, out_text, 1, eval_typeof); + REG("Json.ToNumber", in_json_real, 2, out_real, 1, eval_to_number); + REG("Json.ToText", in_json, 1, out_text, 1, eval_to_text); + REG("Json.ToBool", in_json_int_def, 2, out_integer, 1, eval_to_bool); + +#undef REG + return true; +} + +static void json_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + (void)rt; (void)lib; +} + +TINYBLOCKS_DEFINE_LIBRARY(json, + "tinyblocks-json", + "1.0.0", + json_init, + json_deinit) diff --git a/examples/mcp/mcp.c b/examples/mcp/mcp.c new file mode 100644 index 0000000..c7338dc --- /dev/null +++ b/examples/mcp/mcp.c @@ -0,0 +1,109 @@ +/* + * mcp.c — Plugin TinyBlocks com blocos MCP (Model Context Protocol). + * + * Blocos: + * MCP.Server — literal: armazena a URL do servidor MCP + * HTTP: "http://localhost:3000/mcp" + * stdio: "stdio://npx @modelcontextprotocol/server-filesystem /tmp" + * + * MCP.Ping — input: url (text) → output: status (text) + * Verifica se o servidor responde. + * + * MCP.ListTools — input: url (text) → output: tools (text) + * Lista ferramentas disponíveis no servidor. + * + * MCP.Call — inputs: url, tool, args (text) → output: result (text) + * Chama uma ferramenta com argumentos JSON. + * + * Compilar: + * make mcp-lib + * + * Carregar no editor: + * ./build/editor build/mcp.so ou Ctrl+O → build/mcp.so + * + * Exemplo de uso no editor: + * [Literal.Text "stdio://npx @modelcontextprotocol/server-filesystem /tmp"] + * → [MCP.ListTools] → [IO.Print "tools"] + */ + +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include + +/* ── Helper: lê texto de slot ────────────────────────────────────────────── */ +static const char* gs(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) { + TinyBlocks_Value v = tb_block_get_input(self, rt, idx); + return (v.kind == TB_VALUE_TEXT && v.as.text) ? v.as.text : ""; +} + +/* ── MCP.Ping ────────────────────────────────────────────────────────────── */ +static void eval_mcp_ping(TinyBlocks_Block* self, TinyBlocks* rt) { + const char* url = gs(self, rt, 0); + char* result = tb_mcp_ping(url); + tb_block_set_output(self, 0, tb_value_text(result ? result : "erro")); + free(result); + self->dirty = false; +} + +/* ── MCP.ListTools ───────────────────────────────────────────────────────── */ +static void eval_mcp_list_tools(TinyBlocks_Block* self, TinyBlocks* rt) { + const char* url = gs(self, rt, 0); + char* result = tb_mcp_list_tools(url); + tb_block_set_output(self, 0, tb_value_text(result ? result : "erro")); + free(result); + self->dirty = false; +} + +/* ── MCP.Call ────────────────────────────────────────────────────────────── */ +static void eval_mcp_call(TinyBlocks_Block* self, TinyBlocks* rt) { + const char* url = gs(self, rt, 0); + const char* tool = gs(self, rt, 1); + const char* args = gs(self, rt, 2); + char* result = tb_mcp_call_tool(url, tool, args); + tb_block_set_output(self, 0, tb_value_text(result ? result : "erro")); + free(result); + self->dirty = false; +} + +/* ── Slots ───────────────────────────────────────────────────────────────── */ +static const TinyBlocks_SlotDesc url_in[] = {{"url", TB_VALUE_TEXT}}; +static const TinyBlocks_SlotDesc call_in[] = {{"url", TB_VALUE_TEXT}, + {"tool", TB_VALUE_TEXT}, + {"args", TB_VALUE_TEXT}}; +static const TinyBlocks_SlotDesc status_out[] = {{"status", TB_VALUE_TEXT}}; +static const TinyBlocks_SlotDesc tools_out[] = {{"tools", TB_VALUE_TEXT}}; +static const TinyBlocks_SlotDesc result_out[] = {{"result", TB_VALUE_TEXT}}; + +/* ── Registro ────────────────────────────────────────────────────────────── */ +static bool mcp_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + if (!tb_mcp_init()) return false; + + TinyBlocks_TypeBlock* t; + + t = tb_type_block_create(rt, "MCP.Ping", + url_in, 1, status_out, 1, eval_mcp_ping); + if (t) tb_library_add(lib, &t->base); + + t = tb_type_block_create(rt, "MCP.ListTools", + url_in, 1, tools_out, 1, eval_mcp_list_tools); + if (t) tb_library_add(lib, &t->base); + + t = tb_type_block_create(rt, "MCP.Call", + call_in, 3, result_out, 1, eval_mcp_call); + if (t) tb_library_add(lib, &t->base); + + return true; +} + +static void mcp_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + (void)rt; (void)lib; + tb_mcp_deinit(); +} + +TINYBLOCKS_DEFINE_LIBRARY(mcp, + "tinyblocks-mcp", + "1.0.0", + mcp_init, + mcp_deinit) diff --git a/examples/mylib/mylib.c b/examples/mylib/mylib.c new file mode 100644 index 0000000..c99cecd --- /dev/null +++ b/examples/mylib/mylib.c @@ -0,0 +1,125 @@ +/* + * mylib.c — Library de exemplo para testar hot reload no TinyBlocks Editor. + * + * Blocos incluídos: + * Extra.Square — n² de um inteiro + * Extra.Cube — n³ de um inteiro + * Extra.Clamp — limita valor entre min e max + * Extra.Fibonacci — n-ésimo número de Fibonacci + * Extra.IsEven — 1 se par, 0 se ímpar + * Extra.IntToText — converte inteiro em texto + * Extra.Pow — base elevado a exp (inteiros) + * + * Para compilar: + * make mylib + * + * Para carregar no editor: + * Ctrl+O → build/mylib.so ou arraste build/mylib.so para a janela + */ + +#define _POSIX_C_SOURCE 200809L +#include +#include +#include + +#include + +/* ── Slots reutilizáveis ─────────────────────────────────────────────────── */ +static const TinyBlocks_SlotDesc in_n[] = {{"n", TB_VALUE_INTEGER}}; +static const TinyBlocks_SlotDesc in_ab[] = {{"a", TB_VALUE_INTEGER}, + {"b", TB_VALUE_INTEGER}}; +static const TinyBlocks_SlotDesc in_clamp[]= {{"val", TB_VALUE_INTEGER}, + {"min", TB_VALUE_INTEGER}, + {"max", TB_VALUE_INTEGER}}; +static const TinyBlocks_SlotDesc out_int[] = {{"out", TB_VALUE_INTEGER}}; +static const TinyBlocks_SlotDesc out_txt[] = {{"out", TB_VALUE_TEXT}}; + +/* ── Implementações ──────────────────────────────────────────────────────── */ +static void eval_square(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + int64_t n = v.kind==TB_VALUE_INTEGER ? v.as.integer : 0; + tb_block_set_output(self, 0, tb_value_integer(n * n)); +} + +static void eval_cube(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + int64_t n = v.kind==TB_VALUE_INTEGER ? v.as.integer : 0; + tb_block_set_output(self, 0, tb_value_integer(n * n * n)); +} + +static void eval_pow(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value a = tb_block_get_input(self, rt, 0); + TinyBlocks_Value b = tb_block_get_input(self, rt, 1); + int64_t base = a.kind==TB_VALUE_INTEGER ? a.as.integer : 0; + int64_t exp = b.kind==TB_VALUE_INTEGER ? b.as.integer : 0; + if (exp < 0) { tb_block_set_output(self, 0, tb_value_integer(0)); return; } + int64_t result = 1; + for (int64_t i = 0; i < exp; i++) result *= base; + tb_block_set_output(self, 0, tb_value_integer(result)); +} + +static void eval_clamp(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value val = tb_block_get_input(self, rt, 0); + TinyBlocks_Value mn = tb_block_get_input(self, rt, 1); + TinyBlocks_Value mx = tb_block_get_input(self, rt, 2); + int64_t v = val.kind==TB_VALUE_INTEGER ? val.as.integer : 0; + int64_t lo = mn.kind ==TB_VALUE_INTEGER ? mn.as.integer : 0; + int64_t hi = mx.kind ==TB_VALUE_INTEGER ? mx.as.integer : 100; + if (v < lo) v = lo; + if (v > hi) v = hi; + tb_block_set_output(self, 0, tb_value_integer(v)); +} + +static void eval_fibonacci(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + int64_t n = v.kind==TB_VALUE_INTEGER ? v.as.integer : 0; + if (n <= 0) { tb_block_set_output(self, 0, tb_value_integer(0)); return; } + if (n == 1) { tb_block_set_output(self, 0, tb_value_integer(1)); return; } + int64_t a=0, b=1; + for (int64_t i=2; i<=n && i<94; i++) { int64_t c=a+b; a=b; b=c; } + tb_block_set_output(self, 0, tb_value_integer(b)); +} + +static void eval_iseven(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + int64_t n = v.kind==TB_VALUE_INTEGER ? v.as.integer : 0; + tb_block_set_output(self, 0, tb_value_integer((n % 2 == 0) ? 1 : 0)); +} + +static void eval_int_to_text(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + int64_t n = v.kind==TB_VALUE_INTEGER ? v.as.integer : 0; + char buf[32]; + snprintf(buf, sizeof(buf), "%lld", (long long)n); + tb_block_set_output(self, 0, tb_value_text(buf)); +} + +/* ── Registro da library ─────────────────────────────────────────────────── */ +static bool mylib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + TinyBlocks_TypeBlock* t; + +#define REG(name, ins, ni, outs, no, fn) \ + t = tb_type_block_create(rt, name, ins, ni, outs, no, fn); \ + if (t) tb_library_add(lib, &t->base) + + REG("Extra.Square", in_n, 1, out_int, 1, eval_square); + REG("Extra.Cube", in_n, 1, out_int, 1, eval_cube); + REG("Extra.Pow", in_ab, 2, out_int, 1, eval_pow); + REG("Extra.Clamp", in_clamp, 3, out_int, 1, eval_clamp); + REG("Extra.Fibonacci", in_n, 1, out_int, 1, eval_fibonacci); + REG("Extra.IsEven", in_n, 1, out_int, 1, eval_iseven); + REG("Extra.IntToText", in_n, 1, out_txt, 1, eval_int_to_text); + +#undef REG + return true; +} + +static void mylib_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + (void)rt; (void)lib; +} + +TINYBLOCKS_DEFINE_LIBRARY(mylib, + "mylib", + "1.0.0", + mylib_init, + mylib_deinit) diff --git a/examples/python/python.c b/examples/python/python.c new file mode 100644 index 0000000..6cd94ed --- /dev/null +++ b/examples/python/python.c @@ -0,0 +1,111 @@ +/* + * python.c — Plugin TinyBlocks com blocos Python.*. + * + * Blocos: + * Python.Eval — avalia expressão Python com variáveis x0..x3 + * Python.Run — executa script Python com variáveis x0..x3, captura stdout + * + * Compilar: + * make python-lib + * + * Carregar no editor: + * ./build/editor build/python.so ou Ctrl+O → build/python.so + * + * Exemplos de expressões: + * x0 ** 2 + x1 ** 2 + * __import__('math').sqrt(x0) + * [x*x for x in range(int(x0))] + */ + +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include + +/* ── Helper: lê float de slot numérico ──────────────────────────────────── */ +static double gd(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) { + TinyBlocks_Value v = tb_block_get_input(self, rt, idx); + if (v.kind == TB_VALUE_REAL) return v.as.real; + if (v.kind == TB_VALUE_INTEGER) return (double)v.as.integer; + return 0.0; +} + +static const char* gs(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) { + TinyBlocks_Value v = tb_block_get_input(self, rt, idx); + return (v.kind == TB_VALUE_TEXT && v.as.text) ? v.as.text : ""; +} + +/* ── Python.Eval ─────────────────────────────────────────────────────────── */ +/* + * Inputs: expr (text), x0..x3 (real) + * Output: result (text) + */ +static void eval_python_eval(TinyBlocks_Block* self, TinyBlocks* rt) { + const char* expr = gs(self, rt, 0); + double vals[4] = { gd(self,rt,1), gd(self,rt,2), gd(self,rt,3), gd(self,rt,4) }; + static const char* names[] = {"x0","x1","x2","x3"}; + + char* result = tb_python_eval(expr, names, vals, 4); + tb_block_set_output(self, 0, tb_value_text(result ? result : "")); + free(result); + self->dirty = false; +} + +/* ── Python.Run ──────────────────────────────────────────────────────────── */ +/* + * Inputs: code (text), x0..x3 (real) + * Output: stdout (text) + */ +static void eval_python_run(TinyBlocks_Block* self, TinyBlocks* rt) { + const char* code = gs(self, rt, 0); + double vals[4] = { gd(self,rt,1), gd(self,rt,2), gd(self,rt,3), gd(self,rt,4) }; + static const char* names[] = {"x0","x1","x2","x3"}; + + char* out = tb_python_run_with_vars(code, names, vals, 4); + tb_block_set_output(self, 0, tb_value_text(out ? out : "")); + free(out); + self->dirty = false; +} + +/* ── Slots ───────────────────────────────────────────────────────────────── */ +static const TinyBlocks_SlotDesc eval_in[] = { + {"expr", TB_VALUE_TEXT}, + {"x0", TB_VALUE_REAL}, {"x1", TB_VALUE_REAL}, + {"x2", TB_VALUE_REAL}, {"x3", TB_VALUE_REAL}, +}; +static const TinyBlocks_SlotDesc run_in[] = { + {"code", TB_VALUE_TEXT}, + {"x0", TB_VALUE_REAL}, {"x1", TB_VALUE_REAL}, + {"x2", TB_VALUE_REAL}, {"x3", TB_VALUE_REAL}, +}; +static const TinyBlocks_SlotDesc text_out[] = {{"result", TB_VALUE_TEXT}}; +static const TinyBlocks_SlotDesc stdout_out[]= {{"stdout", TB_VALUE_TEXT}}; + +/* ── Registro ────────────────────────────────────────────────────────────── */ +static bool py_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + if (!tb_python_init()) return false; + + TinyBlocks_TypeBlock* t; + + t = tb_type_block_create(rt, "Python.Eval", + eval_in, 5, text_out, 1, eval_python_eval); + if (t) tb_library_add(lib, &t->base); + + t = tb_type_block_create(rt, "Python.Run", + run_in, 5, stdout_out, 1, eval_python_run); + if (t) tb_library_add(lib, &t->base); + + return true; +} + +static void py_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + (void)rt; (void)lib; + tb_python_deinit(); +} + +TINYBLOCKS_DEFINE_LIBRARY(python, + "tinyblocks-python", + "1.0.0", + py_init, + py_deinit) diff --git a/examples/sdl2/main.c b/examples/sdl2/main.c new file mode 100644 index 0000000..08e5cdc --- /dev/null +++ b/examples/sdl2/main.c @@ -0,0 +1,162 @@ +/* + * TinyBlocks — exemplo SDL2 + * + * Demonstra o uso da library tinyblocks-sdl2 registrada estaticamente. + * Abre uma janela 640x480, desenha um retângulo pulsante e fecha ao pressionar + * Escape ou fechar a janela. Toda a lógica gráfica é expressa como blocos. + */ +#include +#include +#include + +int main(void) +{ + /* ── Runtime ──────────────────────────────────────────────────────────── */ + TinyBlocks* rt = NULL; + if (!tinyblocks_init(&rt, NULL)) { fprintf(stderr, "init falhou\n"); return 1; } + + /* ── Registra a library SDL2 estaticamente ────────────────────────────── */ + TinyBlocks_LibraryBlock* sdl2 = tb_library_register(rt, tb_sdl2_get_library()); + if (!sdl2) { + fprintf(stderr, "Falha ao registrar SDL2: %s\n", tinyblocks_last_error(rt)); + tinyblocks_deinit(&rt); + return 1; + } + printf("Library '%s' carregada com %u blocos\n", + sdl2->base.name, sdl2->block_count); + + /* ── Busca os TypeBlocks que vamos usar ───────────────────────────────── */ + TinyBlocks_TypeBlock* T_Init = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.Init"); + TinyBlocks_TypeBlock* T_Quit = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.Quit"); + TinyBlocks_TypeBlock* T_Window = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.Window"); + TinyBlocks_TypeBlock* T_Renderer = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.Renderer"); + TinyBlocks_TypeBlock* T_SetColor = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.SetDrawColor"); + TinyBlocks_TypeBlock* T_Clear = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.Clear"); + TinyBlocks_TypeBlock* T_FillRect = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.FillRect"); + TinyBlocks_TypeBlock* T_Present = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.Present"); + TinyBlocks_TypeBlock* T_PollEvent = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.PollEvent"); + TinyBlocks_TypeBlock* T_DestroyWin = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.DestroyWindow"); + TinyBlocks_TypeBlock* T_DestroyRend = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.DestroyRenderer"); + TinyBlocks_TypeBlock* T_Delay = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.Delay"); + + /* ── SDL2.Init ────────────────────────────────────────────────────────── */ + TinyBlocks_Block* b_init = tb_block_create(rt, T_Init); + tb_block_eval(b_init, rt); + + /* ── SDL2.Window ─────────────────────────────────────────────────────── */ + TinyBlocks_TextBlock* lit_title = tb_text_block_create(rt, "TinyBlocks SDL2"); + TinyBlocks_IntegerBlock* lit_cx = tb_integer_block_create(rt, -1); /* centered */ + TinyBlocks_IntegerBlock* lit_cy = tb_integer_block_create(rt, -1); + TinyBlocks_IntegerBlock* lit_w = tb_integer_block_create(rt, 640); + TinyBlocks_IntegerBlock* lit_h = tb_integer_block_create(rt, 480); + + TinyBlocks_Block* b_window = tb_block_create(rt, T_Window); + tb_block_connect(b_window, 0, &lit_title->base, 0); + tb_block_connect(b_window, 1, &lit_cx->base, 0); + tb_block_connect(b_window, 2, &lit_cy->base, 0); + tb_block_connect(b_window, 3, &lit_w->base, 0); + tb_block_connect(b_window, 4, &lit_h->base, 0); + tb_block_eval(b_window, rt); + + /* ── SDL2.Renderer ───────────────────────────────────────────────────── */ + TinyBlocks_Block* b_renderer = tb_block_create(rt, T_Renderer); + tb_block_connect(b_renderer, 0, b_window, 0); + tb_block_eval(b_renderer, rt); + + /* ── Blocos reutilizáveis por frame ──────────────────────────────────── */ + TinyBlocks_Block* b_poll = tb_block_create(rt, T_PollEvent); + TinyBlocks_Block* b_bg_color = tb_block_create(rt, T_SetColor); + TinyBlocks_Block* b_clear = tb_block_create(rt, T_Clear); + TinyBlocks_Block* b_rect_color= tb_block_create(rt, T_SetColor); + TinyBlocks_Block* b_rect = tb_block_create(rt, T_FillRect); + TinyBlocks_Block* b_present = tb_block_create(rt, T_Present); + TinyBlocks_Block* b_delay = tb_block_create(rt, T_Delay); + + /* Cor de fundo: preto */ + TinyBlocks_IntegerBlock* lit_0 = tb_integer_block_create(rt, 0); + TinyBlocks_IntegerBlock* lit_255 = tb_integer_block_create(rt, 255); + tb_block_connect(b_bg_color, 0, b_renderer, 0); + tb_block_connect(b_bg_color, 1, &lit_0->base, 0); + tb_block_connect(b_bg_color, 2, &lit_0->base, 0); + tb_block_connect(b_bg_color, 3, &lit_0->base, 0); + tb_block_connect(b_bg_color, 4, &lit_255->base, 0); + + tb_block_connect(b_clear, 0, b_renderer, 0); + + /* Cor do retângulo: vermelho */ + TinyBlocks_IntegerBlock* lit_r = tb_integer_block_create(rt, 220); + TinyBlocks_IntegerBlock* lit_g = tb_integer_block_create(rt, 50); + TinyBlocks_IntegerBlock* lit_b2= tb_integer_block_create(rt, 50); + tb_block_connect(b_rect_color, 0, b_renderer, 0); + tb_block_connect(b_rect_color, 1, &lit_r->base, 0); + tb_block_connect(b_rect_color, 2, &lit_g->base, 0); + tb_block_connect(b_rect_color, 3, &lit_b2->base, 0); + tb_block_connect(b_rect_color, 4, &lit_255->base, 0); + + /* Retângulo dinâmico — usaremos IntegerBlocks mutáveis para posição */ + TinyBlocks_IntegerBlock* lit_rx = tb_integer_block_create(rt, 100); + TinyBlocks_IntegerBlock* lit_ry = tb_integer_block_create(rt, 100); + TinyBlocks_IntegerBlock* lit_rw = tb_integer_block_create(rt, 200); + TinyBlocks_IntegerBlock* lit_rh = tb_integer_block_create(rt, 120); + tb_block_connect(b_rect, 0, b_renderer, 0); + tb_block_connect(b_rect, 1, &lit_rx->base, 0); + tb_block_connect(b_rect, 2, &lit_ry->base, 0); + tb_block_connect(b_rect, 3, &lit_rw->base, 0); + tb_block_connect(b_rect, 4, &lit_rh->base, 0); + + tb_block_connect(b_present, 0, b_renderer, 0); + + TinyBlocks_IntegerBlock* lit_delay = tb_integer_block_create(rt, 16); /* ~60fps */ + tb_block_connect(b_delay, 0, &lit_delay->base, 0); + + /* ── Loop principal ──────────────────────────────────────────────────── */ + printf("Janela aberta. Pressione Escape ou feche a janela para sair.\n"); + + int running = 1; + int frame = 0; + + while (running) { + /* Eventos */ + b_poll->dirty = true; + tb_block_eval(b_poll, rt); + + TinyBlocks_Value vquit = b_poll->outputs[1]; + TinyBlocks_Value vtype = b_poll->outputs[0]; + if (vquit.as.integer) running = 0; + if (vtype.as.integer == 768 /* SDL_KEYDOWN */) { + /* sacancode 41 = Escape */ + if (b_poll->outputs[2].as.integer == 41) running = 0; + } + + /* Animação simples: retângulo oscila horizontalmente */ + frame++; + int offset = (int)(80.0 * (0.5 + 0.5 * ((frame % 120) < 60 + ? (frame % 60) / 60.0 + : 1.0 - (frame % 60) / 60.0))); + tb_integer_block_set(lit_rx, 80 + offset); + + /* Renderização — cada bloco é avaliado na ordem correta */ + b_bg_color->dirty = true; tb_block_eval(b_bg_color, rt); + b_clear->dirty = true; tb_block_eval(b_clear, rt); + b_rect_color->dirty = true; tb_block_eval(b_rect_color, rt); + b_rect->dirty = true; tb_block_eval(b_rect, rt); + b_present->dirty = true; tb_block_eval(b_present, rt); + b_delay->dirty = true; tb_block_eval(b_delay, rt); + } + + /* ── Limpeza SDL2 via blocos ──────────────────────────────────────────── */ + TinyBlocks_Block* b_drend = tb_block_create(rt, T_DestroyRend); + TinyBlocks_Block* b_dwin = tb_block_create(rt, T_DestroyWin); + TinyBlocks_Block* b_quit = tb_block_create(rt, T_Quit); + + tb_block_connect(b_drend, 0, b_renderer, 0); + tb_block_connect(b_dwin, 0, b_window, 0); + + tb_block_eval(b_drend, rt); + tb_block_eval(b_dwin, rt); + tb_block_eval(b_quit, rt); + + tinyblocks_deinit(&rt); + printf("Encerrado.\n"); + return 0; +} diff --git a/examples/vector/vector.c b/examples/vector/vector.c new file mode 100644 index 0000000..35d951d --- /dev/null +++ b/examples/vector/vector.c @@ -0,0 +1,210 @@ +/* + * vector.c — Library de vetor 2D para o TinyBlocks Editor. + * + * Blocos incluídos: + * Vector.BeginPath — inicia um novo path (sem inputs) + * Vector.MoveTo — move caneta para (x, y) + * Vector.LineTo — linha até (x, y) + * Vector.ClosePath — fecha sub-path atual + * Vector.Stroke — aplica traçado com cor/espessura RGBA + * Vector.Fill — aplica preenchimento RGBA ao path + * Vector.Rect — retângulo preenchido (usa Fill por cima) + * Vector.Circle — círculo preenchido + * Vector.Render — recebe vector e desenha no corpo do bloco (on_draw) + * + * Todos os blocos encadeiam: cada um recebe o vetor do anterior e devolve + * um novo com o comando acrescentado. Combine-os com Vector.Render no final. + * + * Para compilar: + * make vector + * + * Para carregar no editor: + * Ctrl+O → build/vector.so ou arraste build/vector.so para a janela + */ + +#define _POSIX_C_SOURCE 200809L +#include +#include + +#include +#include + +/* ── Helper: lê float de qualquer slot numérico ──────────────────────────── */ +static float gf(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) { + TinyBlocks_Value v = tb_block_get_input(self, rt, idx); + if (v.kind == TB_VALUE_REAL) return (float)v.as.real; + if (v.kind == TB_VALUE_INTEGER) return (float)v.as.integer; + return 0.0f; +} + +/* Helper: obtém VectorData do slot 0 e clona (ou cria novo se não conectado) */ +static TinyBlocks_VectorData* clone_vec(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + TinyBlocks_VectorData* src = tb_value_as_vector(v); + return src ? tb_vector_data_clone(src) : tb_vector_data_create(); +} + +/* Macro: produz output vector e libera a ref local */ +#define EMIT_VEC(self, v) do { \ + tb_block_set_output((self), 0, tb_value_vector(v)); \ + tb_vector_data_release(v); \ + (self)->dirty = false; \ +} while(0) + +/* ══════════════════════════════════════════════════════════════════════════ + * Implementações dos blocos + * ══════════════════════════════════════════════════════════════════════════ */ + +static void eval_begin_path(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + TinyBlocks_VectorData* v = tb_vector_data_create(); + if (!v) return; + tb_vector_begin_path(v); + EMIT_VEC(self, v); +} + +static void eval_move_to(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_VectorData* v = clone_vec(self, rt); + if (!v) return; + tb_vector_move_to(v, gf(self, rt, 1), gf(self, rt, 2)); + EMIT_VEC(self, v); +} + +static void eval_line_to(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_VectorData* v = clone_vec(self, rt); + if (!v) return; + tb_vector_line_to(v, gf(self, rt, 1), gf(self, rt, 2)); + EMIT_VEC(self, v); +} + +static void eval_close_path(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_VectorData* v = clone_vec(self, rt); + if (!v) return; + tb_vector_close_path(v); + EMIT_VEC(self, v); +} + +static void eval_stroke(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_VectorData* v = clone_vec(self, rt); + if (!v) return; + tb_vector_stroke(v, gf(self,rt,1), gf(self,rt,2), + gf(self,rt,3), gf(self,rt,4), gf(self,rt,5)); + EMIT_VEC(self, v); +} + +static void eval_fill(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_VectorData* v = clone_vec(self, rt); + if (!v) return; + tb_vector_fill(v, gf(self,rt,1), gf(self,rt,2), + gf(self,rt,3), gf(self,rt,4)); + EMIT_VEC(self, v); +} + +static void eval_rect(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_VectorData* v = clone_vec(self, rt); + if (!v) return; + tb_vector_rect(v, gf(self,rt,1), gf(self,rt,2), + gf(self,rt,3), gf(self,rt,4)); + EMIT_VEC(self, v); +} + +static void eval_circle(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_VectorData* v = clone_vec(self, rt); + if (!v) return; + tb_vector_circle(v, gf(self,rt,1), gf(self,rt,2), gf(self,rt,3)); + EMIT_VEC(self, v); +} + +/* Vector.Render — passa o vetor adiante e tem on_render para preview */ +static void eval_render(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + /* Clona para manter o vector vivo no output (get_input é não-owning) */ + if (v.kind == TB_VALUE_VECTOR && v.as.vector) { + tb_vector_data_retain(v.as.vector); + tb_block_set_output(self, 0, v); /* set_output toma ownership */ + } + self->dirty = false; +} + +static bool on_draw_vector(TinyBlocks_Block* self, TinyBlocks* rt, + TinyBlocks_RenderableBlock** dst) { + (void)rt; + if (!self) return false; + TinyBlocks_RenderableBlock* rb = tb_renderable_acquire(); + if (!rb) return false; + TinyBlocks_VectorData* vd = tb_value_as_vector(self->outputs[0]); + if (vd) tb_draw_ctx_play(rb, vd); + *dst = rb; + return true; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Descritores de slots + * ══════════════════════════════════════════════════════════════════════════ */ +static const TinyBlocks_SlotDesc out_vec[] = {{"vec", TB_VALUE_VECTOR}}; +static const TinyBlocks_SlotDesc in_vec[] = {{"vec", TB_VALUE_VECTOR}}; +static const TinyBlocks_SlotDesc in_vec_xy[] = {{"vec", TB_VALUE_VECTOR}, + {"x", TB_VALUE_REAL}, + {"y", TB_VALUE_REAL}}; +static const TinyBlocks_SlotDesc in_vec_rgba[] = {{"vec", TB_VALUE_VECTOR}, + {"r", TB_VALUE_REAL}, + {"g", TB_VALUE_REAL}, + {"b", TB_VALUE_REAL}, + {"a", TB_VALUE_REAL}}; +static const TinyBlocks_SlotDesc in_vec_rgbaw[] = {{"vec", TB_VALUE_VECTOR}, + {"r", TB_VALUE_REAL}, + {"g", TB_VALUE_REAL}, + {"b", TB_VALUE_REAL}, + {"a", TB_VALUE_REAL}, + {"w", TB_VALUE_REAL}}; +static const TinyBlocks_SlotDesc in_vec_xywh[] = {{"vec", TB_VALUE_VECTOR}, + {"x", TB_VALUE_REAL}, + {"y", TB_VALUE_REAL}, + {"w", TB_VALUE_REAL}, + {"h", TB_VALUE_REAL}}; +static const TinyBlocks_SlotDesc in_vec_cyr[] = {{"vec", TB_VALUE_VECTOR}, + {"cx", TB_VALUE_REAL}, + {"cy", TB_VALUE_REAL}, + {"r", TB_VALUE_REAL}}; + +/* ══════════════════════════════════════════════════════════════════════════ + * Registro da library + * ══════════════════════════════════════════════════════════════════════════ */ +static bool vector_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + TinyBlocks_TypeBlock* t; + +#define REG(name, ins, ni, fn) \ + t = tb_type_block_create(rt, name, ins, ni, out_vec, 1, fn); \ + if (t) tb_library_add(lib, &t->base) + + REG("Vector.BeginPath", NULL, 0, eval_begin_path); + REG("Vector.MoveTo", in_vec_xy, 3, eval_move_to); + REG("Vector.LineTo", in_vec_xy, 3, eval_line_to); + REG("Vector.ClosePath", in_vec, 1, eval_close_path); + REG("Vector.Stroke", in_vec_rgbaw, 6, eval_stroke); + REG("Vector.Fill", in_vec_rgba, 5, eval_fill); + REG("Vector.Rect", in_vec_xywh, 5, eval_rect); + REG("Vector.Circle", in_vec_cyr, 4, eval_circle); + +#undef REG + + /* Vector.Render tem on_draw — preview gráfico no corpo do bloco */ + t = tb_type_block_create(rt, "Vector.Render", + in_vec, 1, out_vec, 1, eval_render); + if (t) { + t->on_draw = on_draw_vector; + tb_library_add(lib, &t->base); + } + + return true; +} + +static void vector_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + (void)rt; (void)lib; +} + +TINYBLOCKS_DEFINE_LIBRARY(vector, + "tinyblocks-vector", + "1.0.0", + vector_init, + vector_deinit) diff --git a/include/tinyblocks/tb_block.h b/include/tinyblocks/tb_block.h new file mode 100644 index 0000000..b8e718e --- /dev/null +++ b/include/tinyblocks/tb_block.h @@ -0,0 +1,95 @@ +/* + * TinyBlocks — tb_block.h + * Estrutura base de todo bloco e operações polimórficas via vtable. + * + * Todos os tipos concretos (TypeBlock, LibraryBlock, TextBlock…) começam com + * um campo `TinyBlocks_Block base` — herança em C via primeiro membro. + */ +#ifndef TINYBLOCKS_BLOCK_H +#define TINYBLOCKS_BLOCK_H + +#include "tb_defs.h" + +/* ── Vtable de bloco ─────────────────────────────────────────────────────── */ +typedef struct TinyBlocks_BlockVTable { + /* Avalia o bloco: lê inputs, processa, escreve outputs */ + void (*eval) (TinyBlocks_Block* self, TinyBlocks* rt); + /* Libera recursos internos (NÃO libera o ponteiro do bloco em si) */ + void (*destroy) (TinyBlocks_Block* self, TinyBlocks* rt); + /* Representação textual; escreve em buf[0..buf_size-1], retorna len */ + size_t (*to_string)(TinyBlocks_Block* self, TinyBlocks* rt, + char* buf, size_t buf_size); + /* Clona recursivamente o bloco (o runtime registra o clone) */ + TinyBlocks_Block* (*clone) (const TinyBlocks_Block* self, TinyBlocks* rt); +} TinyBlocks_BlockVTable; + +/* ── Estrutura base de todo bloco ────────────────────────────────────────── */ +struct TinyBlocks_Block { + TinyBlocks_BlockKind kind; + const TinyBlocks_BlockVTable* vtable; + + uint64_t id; /* ID único gerado pelo runtime */ + char* name; /* rótulo opcional (heap-owned) */ + + TinyBlocks_TypeBlock* type; /* tipo/classe deste bloco; NULL * + * para blocos primitivos built-in */ + + /* Slots de entrada: connections[i] descreve de onde vem o input i */ + TinyBlocks_Connection* inputs; + uint32_t input_count; + + /* Slots de saída: valores computados pelo último eval */ + TinyBlocks_Value* outputs; + uint32_t output_count; + + TinyBlocks_Block* parent; /* bloco pai (se aninhado) */ + void* userdata; /* dados extra por instância */ + bool dirty; /* marcado quando inputs mudam */ + bool in_eval; /* guard anti-ciclo */ +}; + +/* ── Ciclo de vida ───────────────────────────────────────────────────────── */ + +/* Cria um bloco a partir de um TypeBlock; registra no runtime */ +TB_API TinyBlocks_Block* tb_block_create (TinyBlocks* rt, TinyBlocks_TypeBlock* type); +/* Destrói e libera; remove do registro do runtime */ +TB_API void tb_block_destroy(TinyBlocks_Block* block, TinyBlocks* rt); +/* Avalia o bloco (e seus inputs recursivamente se dirty) */ +TB_API void tb_block_eval (TinyBlocks_Block* block, TinyBlocks* rt); +/* Clona o bloco e o registra no runtime */ +TB_API TinyBlocks_Block* tb_block_clone (const TinyBlocks_Block* block, TinyBlocks* rt); +/* Representação textual */ +TB_API size_t tb_block_to_string(TinyBlocks_Block* block, TinyBlocks* rt, + char* buf, size_t buf_size); + +/* ── Conexões ────────────────────────────────────────────────────────────── */ +TB_API bool tb_block_connect (TinyBlocks_Block* target, uint32_t input_idx, + TinyBlocks_Block* source, uint32_t output_idx); +TB_API void tb_block_disconnect(TinyBlocks_Block* target, uint32_t input_idx); +TB_API bool tb_block_set_default(TinyBlocks_Block* target, uint32_t input_idx, + TinyBlocks_Value default_value); + +/* ── Acesso a valores (para uso dentro de eval_fn) ───────────────────────── */ +/* Retorna o valor do input[idx]; resolve a conexão se necessário */ +TB_API TinyBlocks_Value tb_block_get_input (TinyBlocks_Block* self, TinyBlocks* rt, + uint32_t input_idx); +/* Escreve no output[idx] */ +TB_API void tb_block_set_output(TinyBlocks_Block* self, + uint32_t output_idx, TinyBlocks_Value v); + +/* ── Downcasting seguro ──────────────────────────────────────────────────── */ +TB_API TinyBlocks_TypeBlock* tb_block_as_type (TinyBlocks_Block* b); +TB_API TinyBlocks_LibraryBlock* tb_block_as_library(TinyBlocks_Block* b); +TB_API TinyBlocks_TextBlock* tb_block_as_text (TinyBlocks_Block* b); +TB_API TinyBlocks_IntegerBlock* tb_block_as_integer(TinyBlocks_Block* b); +TB_API TinyBlocks_RealBlock* tb_block_as_real (TinyBlocks_Block* b); + +/* ── Helpers internos (usados por implementações de built-ins) ───────────── */ +TB_API TinyBlocks_Block* tb_block_alloc_base(TinyBlocks* rt, + TinyBlocks_BlockKind kind, + size_t struct_size, + uint32_t input_count, + uint32_t output_count, + const TinyBlocks_BlockVTable* vtable); + +#endif /* TINYBLOCKS_BLOCK_H */ diff --git a/include/tinyblocks/tb_defs.h b/include/tinyblocks/tb_defs.h new file mode 100644 index 0000000..4b70085 --- /dev/null +++ b/include/tinyblocks/tb_defs.h @@ -0,0 +1,116 @@ +/* + * TinyBlocks — tb_defs.h + * Forward declarations, enums e tipos primitivos compartilhados por todo o runtime. + */ +#ifndef TINYBLOCKS_DEFS_H +#define TINYBLOCKS_DEFS_H + +#include +#include +#include + +/* ── Visibilidade de API ─────────────────────────────────────────────────── */ +#ifdef _WIN32 +# define TB_API __declspec(dllexport) +#else +# define TB_API __attribute__((visibility("default"))) +#endif + +/* ── Forward declarations ────────────────────────────────────────────────── */ +typedef struct TinyBlocks TinyBlocks; +typedef struct TinyBlocks_Block TinyBlocks_Block; +typedef struct TinyBlocks_TypeBlock TinyBlocks_TypeBlock; +typedef struct TinyBlocks_LibraryBlock TinyBlocks_LibraryBlock; +typedef struct TinyBlocks_TextBlock TinyBlocks_TextBlock; +typedef struct TinyBlocks_IntegerBlock TinyBlocks_IntegerBlock; +typedef struct TinyBlocks_RealBlock TinyBlocks_RealBlock; +typedef struct TinyBlocks_VectorBlock TinyBlocks_VectorBlock; +typedef struct TinyBlocks_VectorData TinyBlocks_VectorData; +typedef struct TinyBlocks_RenderableBlock TinyBlocks_RenderableBlock; +typedef struct TinyBlocks_JsonValue TinyBlocks_JsonValue; + +/* ── Kinds de bloco ──────────────────────────────────────────────────────── */ +typedef enum TinyBlocks_BlockKind { + TB_KIND_BLOCK = 0, /* bloco genérico / definido pelo usuário */ + TB_KIND_TYPE = 1, /* TinyBlocks_TypeBlock */ + TB_KIND_LIBRARY = 2, /* TinyBlocks_LibraryBlock */ + TB_KIND_TEXT = 3, /* TinyBlocks_TextBlock */ + TB_KIND_INTEGER = 4, /* TinyBlocks_IntegerBlock */ + TB_KIND_REAL = 5, /* TinyBlocks_RealBlock */ + TB_KIND_VECTOR = 6, /* TinyBlocks_VectorBlock */ +} TinyBlocks_BlockKind; + +/* ── Kinds de valor (para slots) ─────────────────────────────────────────── */ +typedef enum TinyBlocks_ValueKind { + TB_VALUE_NONE = 0, + TB_VALUE_INTEGER = 1, + TB_VALUE_REAL = 2, + TB_VALUE_TEXT = 3, + TB_VALUE_BLOCK = 4, /* referência a qualquer bloco (handle opaco) */ + TB_VALUE_VECTOR = 5, /* dados de vetor 2D (ref-counted) */ + TB_VALUE_JSON = 6, /* valor JSON (ref-counted) */ +} TinyBlocks_ValueKind; + +/* ── Valor com tag (flui entre slots) ────────────────────────────────────── */ +typedef struct TinyBlocks_Value { + TinyBlocks_ValueKind kind; + union { + int64_t integer; + double real; + char* text; /* heap-owned (tb_value_free) */ + TinyBlocks_Block* block; /* ponteiro não-owning */ + TinyBlocks_VectorData* vector; /* ref-counted (retain/release) */ + TinyBlocks_JsonValue* json; /* ref-counted (retain/release) */ + } as; +} TinyBlocks_Value; + +/* ══════════════════════════════════════════════════════════════════════════ + * Dados de vetor 2D (fluxo de comandos de desenho, ref-counted) + * ══════════════════════════════════════════════════════════════════════════ */ +typedef enum TinyBlocks_VCmdKind { + TB_VCMD_BEGIN_PATH = 0, /* nenhum arg */ + TB_VCMD_MOVE_TO, /* args[0]=x, args[1]=y */ + TB_VCMD_LINE_TO, /* args[0]=x, args[1]=y */ + TB_VCMD_CLOSE_PATH, /* nenhum arg */ + TB_VCMD_STROKE, /* args[0..3]=r,g,b,a args[4]=width */ + TB_VCMD_FILL, /* args[0..3]=r,g,b,a */ + TB_VCMD_RECT, /* args[0..3]=x,y,w,h */ + TB_VCMD_CIRCLE, /* args[0..2]=cx,cy,raio */ +} TinyBlocks_VCmdKind; + +typedef struct { TinyBlocks_VCmdKind kind; float args[5]; } TinyBlocks_VCmd; + +struct TinyBlocks_VectorData { + TinyBlocks_VCmd* cmds; + uint32_t count, capacity; + int32_t ref; +}; + + +/* ── Descritor de slot (em TypeBlock — descreve a forma dos inputs/outputs) ─ */ +typedef struct TinyBlocks_SlotDesc { + const char* name; + TinyBlocks_ValueKind expected_kind; /* TB_VALUE_NONE = aceita qualquer tipo */ +} TinyBlocks_SlotDesc; + +/* ── Conexão de entrada (de qual bloco/slot este input lê) ───────────────── */ +typedef struct TinyBlocks_Connection { + TinyBlocks_Block* source; /* bloco de origem (NULL se não conectado) */ + uint32_t output_idx; /* qual output slot da origem */ + TinyBlocks_Value default_value; /* valor quando não há conexão */ +} TinyBlocks_Connection; + +/* ── Alocador customizável ───────────────────────────────────────────────── */ +typedef void* (*TinyBlocks_AllocFn)(size_t size, void* userdata); +typedef void (*TinyBlocks_FreeFn) (void* ptr, void* userdata); + +/* ── Helpers para TinyBlocks_Value ──────────────────────────────────────── */ +TB_API TinyBlocks_Value tb_value_none(void); +TB_API TinyBlocks_Value tb_value_integer(int64_t v); +TB_API TinyBlocks_Value tb_value_real(double v); +TB_API TinyBlocks_Value tb_value_text(const char* v); /* copia a string */ +TB_API TinyBlocks_Value tb_value_block(TinyBlocks_Block* v); +TB_API TinyBlocks_Value tb_value_clone(TinyBlocks_Value v); /* deep copy */ +TB_API void tb_value_free(TinyBlocks_Value* v); /* libera text */ + +#endif /* TINYBLOCKS_DEFS_H */ diff --git a/include/tinyblocks/tb_integer_block.h b/include/tinyblocks/tb_integer_block.h new file mode 100644 index 0000000..ac85f69 --- /dev/null +++ b/include/tinyblocks/tb_integer_block.h @@ -0,0 +1,26 @@ +/* + * TinyBlocks — tb_integer_block.h + * TinyBlocks_IntegerBlock: bloco primitivo que contém um inteiro de 64 bits. + * + * IntegerBlocks são literais: têm 0 inputs e 1 output (TB_VALUE_INTEGER). + */ +#ifndef TINYBLOCKS_INTEGER_BLOCK_H +#define TINYBLOCKS_INTEGER_BLOCK_H + +#include "tb_block.h" + +struct TinyBlocks_IntegerBlock { + TinyBlocks_Block base; /* DEVE ser o primeiro campo */ + int64_t value; +}; + +/* ── Ciclo de vida ───────────────────────────────────────────────────────── */ +TB_API TinyBlocks_IntegerBlock* tb_integer_block_create (TinyBlocks* rt, int64_t value); +TB_API void tb_integer_block_destroy(TinyBlocks_IntegerBlock* ib, + TinyBlocks* rt); + +/* ── Acesso ao valor ─────────────────────────────────────────────────────── */ +TB_API int64_t tb_integer_block_get(const TinyBlocks_IntegerBlock* ib); +TB_API void tb_integer_block_set(TinyBlocks_IntegerBlock* ib, int64_t value); + +#endif /* TINYBLOCKS_INTEGER_BLOCK_H */ diff --git a/include/tinyblocks/tb_json_block.h b/include/tinyblocks/tb_json_block.h new file mode 100644 index 0000000..cf7a8f2 --- /dev/null +++ b/include/tinyblocks/tb_json_block.h @@ -0,0 +1,72 @@ +/* + * TinyBlocks — tb_json_block.h + * TinyBlocks_JsonValue: árvore JSON imutável e ref-counted que flui como valor + * entre blocos (TB_VALUE_JSON). + * + * Fluxo típico de uso: + * TinyBlocks_JsonValue* root = tb_json_parse(text, NULL, 0); + * TinyBlocks_JsonValue* name = tb_json_object_get(root, "name"); // ref nova + * const char* s = tb_json_as_string(name); + * tb_json_release(name); + * tb_json_release(root); + * + * Mutações (array_push/object_set) são feitas em árvores recém-criadas (não + * compartilhadas); para "modificar" um valor já em uso, clone primeiro com + * tb_json_clone. + */ +#ifndef TINYBLOCKS_JSON_BLOCK_H +#define TINYBLOCKS_JSON_BLOCK_H + +#include "tb_block.h" + +typedef enum TinyBlocks_JsonKind { + TB_JSON_NULL = 0, + TB_JSON_BOOL = 1, + TB_JSON_NUMBER = 2, + TB_JSON_STRING = 3, + TB_JSON_ARRAY = 4, + TB_JSON_OBJECT = 5, +} TinyBlocks_JsonKind; + +/* ── Ciclo de vida ───────────────────────────────────────────────────────── */ +TB_API TinyBlocks_JsonValue* tb_json_null (void); +TB_API TinyBlocks_JsonValue* tb_json_bool (bool b); +TB_API TinyBlocks_JsonValue* tb_json_number(double d); +TB_API TinyBlocks_JsonValue* tb_json_string(const char* s); /* copia a string */ +TB_API TinyBlocks_JsonValue* tb_json_array (void); /* array vazio */ +TB_API TinyBlocks_JsonValue* tb_json_object(void); /* objeto vazio */ + +TB_API void tb_json_retain (TinyBlocks_JsonValue* j); +TB_API void tb_json_release(TinyBlocks_JsonValue* j); +TB_API TinyBlocks_JsonValue* tb_json_clone (const TinyBlocks_JsonValue* j); /* deep copy */ + +/* ── Inspeção ────────────────────────────────────────────────────────────── */ +TB_API TinyBlocks_JsonKind tb_json_kind (const TinyBlocks_JsonValue* j); +TB_API const char* tb_json_kind_name(const TinyBlocks_JsonValue* j); + +TB_API bool tb_json_as_bool (const TinyBlocks_JsonValue* j, bool def); +TB_API double tb_json_as_number(const TinyBlocks_JsonValue* j, double def); +TB_API const char* tb_json_as_string(const TinyBlocks_JsonValue* j); /* NULL se não for string */ + +/* ── Arrays (mutação in-place; use em árvores não compartilhadas) ───────── */ +TB_API bool tb_json_array_push (TinyBlocks_JsonValue* arr, TinyBlocks_JsonValue* item); +TB_API uint32_t tb_json_array_length(const TinyBlocks_JsonValue* arr); +TB_API TinyBlocks_JsonValue* tb_json_array_get(const TinyBlocks_JsonValue* arr, uint32_t idx); /* ref nova, ou NULL */ + +/* ── Objetos (mutação in-place; use em árvores não compartilhadas) ──────── */ +TB_API bool tb_json_object_set (TinyBlocks_JsonValue* obj, const char* key, TinyBlocks_JsonValue* val); +TB_API uint32_t tb_json_object_length (const TinyBlocks_JsonValue* obj); +TB_API const char* tb_json_object_key_at (const TinyBlocks_JsonValue* obj, uint32_t idx); +TB_API TinyBlocks_JsonValue* tb_json_object_get(const TinyBlocks_JsonValue* obj, const char* key); /* ref nova, ou NULL */ + +/* ── Parsing / serialização ──────────────────────────────────────────────── */ +/* Retorna NULL em erro de sintaxe; se errbuf não for NULL, escreve a mensagem. */ +TB_API TinyBlocks_JsonValue* tb_json_parse(const char* text, char* errbuf, size_t errbuf_size); +/* Serializa para texto; retorna buffer heap-alocado (free() do chamador). */ +TB_API char* tb_json_stringify(const TinyBlocks_JsonValue* j); + +/* ── Helpers para TinyBlocks_Value ──────────────────────────────────────── */ +TB_API TinyBlocks_Value tb_value_json (TinyBlocks_JsonValue* j); /* retém ref */ +TB_API TinyBlocks_JsonValue* tb_value_as_json(TinyBlocks_Value v); + +#endif /* TINYBLOCKS_JSON_BLOCK_H */ diff --git a/include/tinyblocks/tb_library_block.h b/include/tinyblocks/tb_library_block.h new file mode 100644 index 0000000..2e648b0 --- /dev/null +++ b/include/tinyblocks/tb_library_block.h @@ -0,0 +1,82 @@ +/* + * TinyBlocks — tb_library_block.h + * TinyBlocks_LibraryBlock: contêiner que agrupa um conjunto de blocos. + * + * Libraries são o mecanismo de modularidade da linguagem. Uma library contém + * TypeBlocks (tipos/operações) e pode ser carregada dinamicamente via dlopen. + * + * Estrutura de uma library em C: + * 1. Exporte `const TinyBlocks_LibraryDescriptor* tinyblocks_get_library(void)` + * 2. Implemente `init` para criar TypeBlocks e adicioná-los com tb_library_add + * 3. Implemente `deinit` para limpeza + */ +#ifndef TINYBLOCKS_LIBRARY_BLOCK_H +#define TINYBLOCKS_LIBRARY_BLOCK_H + +#include "tb_block.h" + +struct TinyBlocks_LibraryBlock { + TinyBlocks_Block base; /* DEVE ser o primeiro campo */ + + TinyBlocks_Block** blocks; /* blocos contidos (TypeBlocks, etc.) */ + uint32_t block_count; + uint32_t block_capacity; + + /* Hooks chamados pelo runtime ao carregar/descarregar (podem ser NULL) */ + bool (*on_load )(TinyBlocks_LibraryBlock* self, TinyBlocks* rt); + void (*on_unload)(TinyBlocks_LibraryBlock* self, TinyBlocks* rt); + + void* lib_userdata; /* dados privados da library */ +}; + +/* ── Descritor exportado por cada library .so/.dll ───────────────────────── */ +typedef struct TinyBlocks_LibraryDescriptor { + const char* name; + const char* version; + bool (*init )(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib); + void (*deinit)(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib); +} TinyBlocks_LibraryDescriptor; + +/* Símbolo que cada library deve exportar */ +#define TINYBLOCKS_LIBRARY_SYMBOL "tinyblocks_get_library" + +/* Macro de conveniência para implementações de library */ +#define TINYBLOCKS_DEFINE_LIBRARY(sym, name_, version_, init_, deinit_) \ + static const TinyBlocks_LibraryDescriptor _tb_lib_desc_##sym = { \ + .name = (name_), \ + .version = (version_), \ + .init = (init_), \ + .deinit = (deinit_), \ + }; \ + TB_API __attribute__((weak)) \ + const TinyBlocks_LibraryDescriptor* tinyblocks_get_library(void) { \ + return &_tb_lib_desc_##sym; \ + } + +/* ── Operações em LibraryBlock ───────────────────────────────────────────── */ +TB_API TinyBlocks_LibraryBlock* tb_library_block_create(TinyBlocks* rt, + const char* name); +TB_API void tb_library_block_destroy(TinyBlocks_LibraryBlock* lib, TinyBlocks* rt); + +/* Adiciona um bloco à library (a library não toma ownership do bloco) */ +TB_API bool tb_library_add(TinyBlocks_LibraryBlock* lib, TinyBlocks_Block* block); + +/* Remove um bloco da library pelo índice */ +TB_API bool tb_library_remove_at(TinyBlocks_LibraryBlock* lib, uint32_t index); + +/* Busca um bloco pelo nome dentro da library */ +TB_API TinyBlocks_Block* tb_library_find(TinyBlocks_LibraryBlock* lib, + const char* name); + +/* ── Carregamento dinâmico de libraries ──────────────────────────────────── */ +/* Carrega uma library a partir de um .so/.dll; retorna NULL em erro */ +TB_API TinyBlocks_LibraryBlock* tb_library_load(TinyBlocks* rt, const char* path); + +/* Descarrega uma library previamente carregada com tb_library_load */ +TB_API void tb_library_unload(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib); + +/* Registra um LibraryDescriptor estático (para libraries embutidas) */ +TB_API TinyBlocks_LibraryBlock* tb_library_register( + TinyBlocks* rt, const TinyBlocks_LibraryDescriptor* desc); + +#endif /* TINYBLOCKS_LIBRARY_BLOCK_H */ diff --git a/include/tinyblocks/tb_real_block.h b/include/tinyblocks/tb_real_block.h new file mode 100644 index 0000000..e0de29c --- /dev/null +++ b/include/tinyblocks/tb_real_block.h @@ -0,0 +1,26 @@ +/* + * TinyBlocks — tb_real_block.h + * TinyBlocks_RealBlock: bloco primitivo que contém um número real (double). + * + * RealBlocks são literais: têm 0 inputs e 1 output (TB_VALUE_REAL). + */ +#ifndef TINYBLOCKS_REAL_BLOCK_H +#define TINYBLOCKS_REAL_BLOCK_H + +#include "tb_block.h" + +struct TinyBlocks_RealBlock { + TinyBlocks_Block base; /* DEVE ser o primeiro campo */ + double value; +}; + +/* ── Ciclo de vida ───────────────────────────────────────────────────────── */ +TB_API TinyBlocks_RealBlock* tb_real_block_create (TinyBlocks* rt, double value); +TB_API void tb_real_block_destroy(TinyBlocks_RealBlock* rb, + TinyBlocks* rt); + +/* ── Acesso ao valor ─────────────────────────────────────────────────────── */ +TB_API double tb_real_block_get(const TinyBlocks_RealBlock* rb); +TB_API void tb_real_block_set(TinyBlocks_RealBlock* rb, double value); + +#endif /* TINYBLOCKS_REAL_BLOCK_H */ diff --git a/include/tinyblocks/tb_renderable_block.h b/include/tinyblocks/tb_renderable_block.h new file mode 100644 index 0000000..d152243 --- /dev/null +++ b/include/tinyblocks/tb_renderable_block.h @@ -0,0 +1,116 @@ +/* + * TinyBlocks — tb_renderable_block.h + * + * TinyBlocks_RenderableBlock: lista de comandos de desenho produzida por on_draw. + * O backend (ex: SDL2.App) interpreta os comandos para renderizar na tela. + * + * Uso típico: + * bool my_on_draw(TinyBlocks_Block* self, TinyBlocks* rt, + * TinyBlocks_RenderableBlock** dst) { + * TinyBlocks_RenderableBlock* rb = tb_renderable_acquire(); + * if (!rb) return false; + * tb_draw_clear(rb, 0.1f, 0.1f, 0.18f, 1.f); + * tb_draw_fill_rect(rb, 10, 10, 200, 100, 0.5f, 0.3f, 0.9f, 1.f); + * tb_draw_text(rb, 20, 50, "Olá", 13.f, 1,1,1,1); + * *dst = rb; + * return true; + * } + * // Após renderizar: tb_renderable_release_all(); + */ +#ifndef TINYBLOCKS_RENDERABLE_BLOCK_H +#define TINYBLOCKS_RENDERABLE_BLOCK_H + +#include "tb_defs.h" + +/* ── Tipos de comando ──────────────────────────────────────────────────────── */ +typedef enum { + TB_DRAW_CLEAR, /* limpa toda a área com uma cor */ + TB_DRAW_FILL_RECT, /* retângulo preenchido */ + TB_DRAW_FILL_RRECT, /* retângulo com cantos arredondados (param=radius) */ + TB_DRAW_FILL_CIRCLE, /* círculo preenchido (x=cx, y=cy, param=radius) */ + TB_DRAW_STROKE_LINE, /* linha (x,y → w,h como x2,y2; param=espessura) */ + TB_DRAW_STROKE_RECT, /* contorno de retângulo (param=espessura) */ + TB_DRAW_STROKE_CIRCLE, /* contorno de círculo (x=cx,y=cy,param=r,w=espessura)*/ + TB_DRAW_SET_CLIP, /* define rect de clip (coordenadas tela) */ + TB_DRAW_CLEAR_CLIP, /* remove clip */ + TB_DRAW_TEXT, /* texto (x,y=baseline-left; font_size em px) */ +} TinyBlocks_DrawCmdKind; + +typedef struct { + TinyBlocks_DrawCmdKind kind; + float x, y, w, h; /* geometria (significado varia por kind) */ + float r, g, b, a; /* cor RGBA [0..1] */ + float param; /* radius (rrect/circle), espessura (linha/stroke) */ + float font_size; /* tamanho da fonte em pixels (TB_DRAW_TEXT) */ + char text[128]; /* conteúdo do texto (TB_DRAW_TEXT) */ +} TinyBlocks_DrawCmd; + +/* ── RenderableBlock ───────────────────────────────────────────────────────── */ +#define TB_DRAW_CMD_CAP 8192 + +struct TinyBlocks_RenderableBlock { + TinyBlocks_DrawCmd cmds[TB_DRAW_CMD_CAP]; + uint32_t count; +}; + +/* ── Pool de renderables (reset por frame, sem malloc durante o loop) ──────── */ + +/* Adquire um renderable limpo do pool. Retorna NULL se esgotado. */ +TB_API TinyBlocks_RenderableBlock* tb_renderable_acquire(void); + +/* Libera um renderable individual de volta ao pool (uso após merge). */ +TB_API void tb_renderable_release(TinyBlocks_RenderableBlock* rb); + +/* Libera todos os renderables de volta ao pool (chamar uma vez por frame, + depois que o backend terminar de renderizar). */ +TB_API void tb_renderable_release_all(void); + +/* ── Helpers para acrescentar comandos ────────────────────────────────────── */ + +TB_API void tb_draw_clear (TinyBlocks_RenderableBlock* rb, + float r, float g, float b, float a); + +TB_API void tb_draw_fill_rect (TinyBlocks_RenderableBlock* rb, + float x, float y, float w, float h, + float r, float g, float b, float a); + +TB_API void tb_draw_fill_rrect (TinyBlocks_RenderableBlock* rb, + float x, float y, float w, float h, float radius, + float r, float g, float b, float a); + +TB_API void tb_draw_fill_circle(TinyBlocks_RenderableBlock* rb, + float cx, float cy, float radius, + float r, float g, float b, float a); + +TB_API void tb_draw_stroke_line(TinyBlocks_RenderableBlock* rb, + float x1, float y1, float x2, float y2, float w, + float r, float g, float b, float a); + +TB_API void tb_draw_stroke_rect (TinyBlocks_RenderableBlock* rb, + float x, float y, float w, float h, float stroke_w, + float r, float g, float b, float a); + +TB_API void tb_draw_stroke_circle(TinyBlocks_RenderableBlock* rb, + float cx, float cy, float radius, float stroke_w, + float r, float g, float b, float a); + +TB_API void tb_draw_set_clip (TinyBlocks_RenderableBlock* rb, + float x, float y, float w, float h); + +TB_API void tb_draw_clear_clip (TinyBlocks_RenderableBlock* rb); + +TB_API void tb_draw_text (TinyBlocks_RenderableBlock* rb, + float x, float y, const char* text, float font_size, + float r, float g, float b, float a); + +/* Mescla src em dst deslocando todas as coordenadas por (dx, dy). + Usado pelo editor para incorporar sub-renderables de blocos com on_draw. */ +TB_API void tb_draw_merge_offset(TinyBlocks_RenderableBlock* dst, + const TinyBlocks_RenderableBlock* src, + float dx, float dy); + +/* Estimativa de largura de texto (independente de fonte real). + Precisa ser substituída por medição real pelo backend quando disponível. */ +TB_API float tb_measure_text(const char* text, float font_size); + +#endif /* TINYBLOCKS_RENDERABLE_BLOCK_H */ diff --git a/include/tinyblocks/tb_text_block.h b/include/tinyblocks/tb_text_block.h new file mode 100644 index 0000000..cb73114 --- /dev/null +++ b/include/tinyblocks/tb_text_block.h @@ -0,0 +1,30 @@ +/* + * TinyBlocks — tb_text_block.h + * TinyBlocks_TextBlock: bloco primitivo que contém um valor textual. + * + * TextBlocks são literais: têm 0 inputs e 1 output (TB_VALUE_TEXT). + * A string interna é heap-owned e gerenciada pelo bloco. + */ +#ifndef TINYBLOCKS_TEXT_BLOCK_H +#define TINYBLOCKS_TEXT_BLOCK_H + +#include "tb_block.h" + +struct TinyBlocks_TextBlock { + TinyBlocks_Block base; /* DEVE ser o primeiro campo */ + char* value; /* string heap-owned */ +}; + +/* ── Ciclo de vida ───────────────────────────────────────────────────────── */ +TB_API TinyBlocks_TextBlock* tb_text_block_create (TinyBlocks* rt, const char* value); +TB_API void tb_text_block_destroy(TinyBlocks_TextBlock* tb, + TinyBlocks* rt); + +/* ── Acesso ao valor ─────────────────────────────────────────────────────── */ +TB_API const char* tb_text_block_get(const TinyBlocks_TextBlock* tb); +TB_API void tb_text_block_set(TinyBlocks_TextBlock* tb, const char* value); + +/* Concatena value ao final da string atual */ +TB_API void tb_text_block_append(TinyBlocks_TextBlock* tb, const char* suffix); + +#endif /* TINYBLOCKS_TEXT_BLOCK_H */ diff --git a/include/tinyblocks/tb_type_block.h b/include/tinyblocks/tb_type_block.h new file mode 100644 index 0000000..241f53e --- /dev/null +++ b/include/tinyblocks/tb_type_block.h @@ -0,0 +1,72 @@ +/* + * TinyBlocks — tb_type_block.h + * TinyBlocks_TypeBlock: representa a "classe" de um bloco. + * + * Um TypeBlock define: + * • O nome do tipo + * • Os descritores de slots (inputs e outputs) + * • A função de avaliação para instâncias + * • Hooks de init/deinit por instância + * • Tamanho extra de userdata para instâncias + * + * TypeBlocks são eles mesmos blocos (base.kind == TB_KIND_TYPE). + */ +#ifndef TINYBLOCKS_TYPE_BLOCK_H +#define TINYBLOCKS_TYPE_BLOCK_H + +#include "tb_block.h" + +struct TinyBlocks_TypeBlock { + TinyBlocks_Block base; /* DEVE ser o primeiro campo */ + + char* type_name; /* nome do tipo, e.g. "SDL2.Window" */ + + /* Descritores de slots */ + TinyBlocks_SlotDesc* input_descs; + uint32_t input_desc_count; + TinyBlocks_SlotDesc* output_descs; + uint32_t output_desc_count; + + /* Função de avaliação chamada para todas as instâncias deste tipo */ + void (*eval_fn)(TinyBlocks_Block* self, TinyBlocks* rt); + + /* Tamanho do bloco de userdata alocado em cada instância (pode ser 0) */ + size_t instance_userdata_size; + + /* Hooks de ciclo de vida por instância (podem ser NULL) */ + bool (*instance_init )(TinyBlocks_Block* self, TinyBlocks* rt); + void (*instance_deinit)(TinyBlocks_Block* self, TinyBlocks* rt); + + /* Renderização personalizada (opcional, NULL = aparência padrão do editor). + * Produz comandos de desenho em *dst (adquirido do pool ou passado pelo caller). + * Para blocos widget: coordenadas relativas à área de conteúdo (0,0=top-left). + * Para blocos de cena (ex: Editor.Scene): coordenadas absolutas de tela. */ + bool (*on_draw)(TinyBlocks_Block* self, TinyBlocks* rt, + TinyBlocks_RenderableBlock** dst); +}; + +/* ── Criação de TypeBlock ────────────────────────────────────────────────── */ + +/* Cria e registra um TypeBlock no runtime */ +TB_API TinyBlocks_TypeBlock* tb_type_block_create( + TinyBlocks* rt, + const char* type_name, + const TinyBlocks_SlotDesc* input_descs, uint32_t input_count, + const TinyBlocks_SlotDesc* output_descs, uint32_t output_count, + void (*eval_fn)(TinyBlocks_Block* self, TinyBlocks* rt) +); + +TB_API void tb_type_block_destroy(TinyBlocks_TypeBlock* tb, TinyBlocks* rt); + +/* Configura hooks de ciclo de vida e tamanho de userdata de instância */ +TB_API void tb_type_block_set_instance_hooks( + TinyBlocks_TypeBlock* tb, + size_t instance_userdata_size, + bool (*init )(TinyBlocks_Block* self, TinyBlocks* rt), + void (*deinit)(TinyBlocks_Block* self, TinyBlocks* rt) +); + +/* Localiza um TypeBlock por nome no runtime */ +TB_API TinyBlocks_TypeBlock* tb_type_block_find(TinyBlocks* rt, const char* type_name); + +#endif /* TINYBLOCKS_TYPE_BLOCK_H */ diff --git a/include/tinyblocks/tb_vector_block.h b/include/tinyblocks/tb_vector_block.h new file mode 100644 index 0000000..e58643c --- /dev/null +++ b/include/tinyblocks/tb_vector_block.h @@ -0,0 +1,65 @@ +/* + * TinyBlocks — tb_vector_block.h + * TinyBlocks_VectorBlock: bloco que armazena dados de vetor 2D. + * TinyBlocks_VectorData: comandos de desenho ref-counted que fluem como valores. + * + * Fluxo típico de uso: + * v = tb_vector_data_create(); + * tb_vector_begin_path(v); + * tb_vector_move_to(v, 0, 0); + * tb_vector_line_to(v, 100, 50); + * tb_vector_stroke(v, 1,0,0,1, 2.0f); + * TinyBlocks_Value val = tb_value_vector(v); // retém ref + * tb_vector_data_release(v); // libera ref local + * tb_block_set_output(self, 0, val); // set_output toma ownership + * + * Reprodução em RenderableBlock: + * tb_draw_ctx_play(rb, val.as.vector); + */ +#ifndef TINYBLOCKS_VECTOR_BLOCK_H +#define TINYBLOCKS_VECTOR_BLOCK_H + +#include "tb_block.h" +#include "tb_renderable_block.h" + +/* ── TinyBlocks_VectorBlock — bloco que contém VectorData ───────────────── */ +struct TinyBlocks_VectorBlock { + TinyBlocks_Block base; /* DEVE ser o primeiro campo */ + TinyBlocks_VectorData* data; +}; + +/* ── Ciclo de vida de VectorData ────────────────────────────────────────── */ +TB_API TinyBlocks_VectorData* tb_vector_data_create (void); +TB_API void tb_vector_data_retain (TinyBlocks_VectorData* v); +TB_API void tb_vector_data_release(TinyBlocks_VectorData* v); +TB_API TinyBlocks_VectorData* tb_vector_data_clone (const TinyBlocks_VectorData* v); +TB_API bool tb_vector_data_push (TinyBlocks_VectorData* v, + TinyBlocks_VCmd cmd); + +/* ── Construtores de comandos ────────────────────────────────────────────── */ +TB_API bool tb_vector_begin_path(TinyBlocks_VectorData* v); +TB_API bool tb_vector_move_to (TinyBlocks_VectorData* v, float x, float y); +TB_API bool tb_vector_line_to (TinyBlocks_VectorData* v, float x, float y); +TB_API bool tb_vector_close_path(TinyBlocks_VectorData* v); +TB_API bool tb_vector_stroke (TinyBlocks_VectorData* v, + float r, float g, float b, float a, float width); +TB_API bool tb_vector_fill (TinyBlocks_VectorData* v, + float r, float g, float b, float a); +TB_API bool tb_vector_rect (TinyBlocks_VectorData* v, + float x, float y, float w, float h); +TB_API bool tb_vector_circle (TinyBlocks_VectorData* v, + float cx, float cy, float radius); + +/* ── Helpers para TinyBlocks_Value ──────────────────────────────────────── */ +TB_API TinyBlocks_Value tb_value_vector (TinyBlocks_VectorData* v); +TB_API TinyBlocks_VectorData* tb_value_as_vector(TinyBlocks_Value v); + +/* ── VectorBlock (bloco no grafo) ────────────────────────────────────────── */ +TB_API TinyBlocks_VectorBlock* tb_vector_block_create (TinyBlocks* rt); +TB_API void tb_vector_block_set_data (TinyBlocks_VectorBlock* b, + TinyBlocks_VectorData* v); + +/* ── Reprodução de VectorData via RenderableBlock ───────────────────────── */ +TB_API void tb_draw_ctx_play(TinyBlocks_RenderableBlock* rb, TinyBlocks_VectorData* v); + +#endif /* TINYBLOCKS_VECTOR_BLOCK_H */ diff --git a/include/tinyblocks/tinyblocks.h b/include/tinyblocks/tinyblocks.h new file mode 100644 index 0000000..6bb7ef8 --- /dev/null +++ b/include/tinyblocks/tinyblocks.h @@ -0,0 +1,113 @@ +/* + * TinyBlocks — tinyblocks.h + * Cabeçalho principal do runtime. Inclua apenas este arquivo. + * + * O struct TinyBlocks é o runtime da linguagem. Ele é completamente separado + * de qualquer interface gráfica — GUIs são implementadas como LibraryBlocks. + * + * Fluxo de uso mínimo: + * + * TinyBlocks* rt = NULL; + * tinyblocks_init(&rt, NULL); // inicializa com alocador padrão + * + * // carrega uma library (estática ou dinâmica) + * tb_library_register(rt, my_library_descriptor()); + * + * // cria blocos, conecta-os, avalia + * TinyBlocks_TypeBlock* t = tb_type_block_find(rt, "Math.Add"); + * TinyBlocks_Block* b = tb_block_create(rt, t); + * tb_block_connect(b, 0, lit_a, 0); + * tb_block_connect(b, 1, lit_b, 0); + * tb_block_eval(b, rt); + * TinyBlocks_Value result = b->outputs[0]; + * + * tinyblocks_deinit(&rt); + */ +#ifndef TINYBLOCKS_H +#define TINYBLOCKS_H + +#include "tb_defs.h" +#include "tb_block.h" +#include "tb_type_block.h" +#include "tb_library_block.h" +#include "tb_text_block.h" +#include "tb_integer_block.h" +#include "tb_real_block.h" +#include "tb_vector_block.h" +#include "tb_json_block.h" + +/* ── Runtime ─────────────────────────────────────────────────────────────── */ +struct TinyBlocks { + /* Alocador (padrão: malloc/free) */ + TinyBlocks_AllocFn alloc; + TinyBlocks_FreeFn free; + void* alloc_userdata; + + /* Registro global de blocos vivos */ + TinyBlocks_Block** blocks; + uint32_t block_count; + uint32_t block_capacity; + + /* Registro de tipos */ + TinyBlocks_TypeBlock** types; + uint32_t type_count; + uint32_t type_capacity; + + /* Registro de libraries */ + TinyBlocks_LibraryBlock** libraries; + uint32_t library_count; + uint32_t library_capacity; + + /* Handles de bibliotecas carregadas dinamicamente (dlopen) */ + void** dl_handles; + uint32_t dl_handle_count; + uint32_t dl_handle_capacity; + + /* Gerador de IDs únicos */ + uint64_t next_id; + + /* Último erro em texto legível */ + char error[512]; +}; + +/* ── Opções de inicialização ─────────────────────────────────────────────── */ +typedef struct TinyBlocks_InitOptions { + TinyBlocks_AllocFn alloc; /* NULL = malloc padrão */ + TinyBlocks_FreeFn free_fn; /* NULL = free padrão */ + void* alloc_userdata; + uint32_t initial_block_cap; /* 0 = 64 */ + uint32_t initial_type_cap; /* 0 = 32 */ + uint32_t initial_library_cap; /* 0 = 16 */ +} TinyBlocks_InitOptions; + +/* ── Ciclo de vida do runtime ────────────────────────────────────────────── */ +TB_API bool tinyblocks_init (TinyBlocks** out_rt, const TinyBlocks_InitOptions* opts); +TB_API void tinyblocks_deinit(TinyBlocks** rt); + +/* ── Registro interno (usado pelas implementações de bloco) ─────────────── */ +TB_API bool tb_rt_register_block (TinyBlocks* rt, TinyBlocks_Block* block); +TB_API void tb_rt_unregister_block(TinyBlocks* rt, TinyBlocks_Block* block); +TB_API bool tb_rt_register_type (TinyBlocks* rt, TinyBlocks_TypeBlock* type); +TB_API void tb_rt_unregister_type (TinyBlocks* rt, TinyBlocks_TypeBlock* type); +TB_API bool tb_rt_register_library(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib); +TB_API void tb_rt_unregister_library(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib); + +/* ── Alocação com o alocador do runtime ─────────────────────────────────── */ +TB_API void* tb_alloc(TinyBlocks* rt, size_t size); +TB_API void tb_free (TinyBlocks* rt, void* ptr); +TB_API char* tb_strdup(TinyBlocks* rt, const char* str); + +/* ── Diagnósticos ────────────────────────────────────────────────────────── */ +TB_API const char* tinyblocks_last_error(TinyBlocks* rt); +TB_API void tinyblocks_set_error (TinyBlocks* rt, const char* fmt, ...); +TB_API void tinyblocks_clear_error(TinyBlocks* rt); + +/* ── Busca no registro ───────────────────────────────────────────────────── */ +TB_API TinyBlocks_Block* tb_rt_find_block (TinyBlocks* rt, uint64_t id); +TB_API TinyBlocks_TypeBlock* tb_rt_find_type (TinyBlocks* rt, const char* name); +TB_API TinyBlocks_LibraryBlock* tb_rt_find_library(TinyBlocks* rt, const char* name); + +/* ── Geração de ID ───────────────────────────────────────────────────────── */ +TB_API uint64_t tb_rt_next_id(TinyBlocks* rt); + +#endif /* TINYBLOCKS_H */ diff --git a/libraries/tinyblocks-editor/Makefile b/libraries/tinyblocks-editor/Makefile new file mode 100644 index 0000000..24e37a9 --- /dev/null +++ b/libraries/tinyblocks-editor/Makefile @@ -0,0 +1,43 @@ +CC := gcc +BUILD := ../../build + +SDL2_CFLAGS := $(shell sdl2-config --cflags) +SDL2_LIBS := $(shell sdl2-config --libs) +SDL2TTF_CFLAGS:= $(shell pkg-config --cflags SDL2_ttf 2>/dev/null) +SDL2TTF_LIBS := $(shell pkg-config --libs SDL2_ttf 2>/dev/null) + +ifeq ($(SDL2TTF_LIBS),) +$(error SDL2_ttf não encontrado. Instale: sudo apt install libsdl2-ttf-dev) +endif + +CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \ + -D_POSIX_C_SOURCE=200809L \ + -I../../include \ + -Iinclude \ + $(SDL2_CFLAGS) $(SDL2TTF_CFLAGS) + +LDFLAGS := $(SDL2_LIBS) $(SDL2TTF_LIBS) -lm + +OBJ := $(BUILD)/tb_editor.o +LIB_A := $(BUILD)/libtinyblocks-editor.a +LIB_SO := $(BUILD)/libtinyblocks-editor.so + +.PHONY: all static shared clean + +all: static shared + +static: $(LIB_A) +shared: $(LIB_SO) + +$(OBJ): src/tb_editor.c include/tb_editor.h + @mkdir -p $(BUILD) + $(CC) $(CFLAGS) -fPIC -c $< -o $@ + +$(LIB_A): $(OBJ) + ar rcs $@ $^ + +$(LIB_SO): $(OBJ) + $(CC) -shared -o $@ $^ $(LDFLAGS) + +clean: + $(RM) $(OBJ) $(LIB_A) $(LIB_SO) diff --git a/libraries/tinyblocks-editor/include/tb_editor.h b/libraries/tinyblocks-editor/include/tb_editor.h new file mode 100644 index 0000000..fe3531c --- /dev/null +++ b/libraries/tinyblocks-editor/include/tb_editor.h @@ -0,0 +1,37 @@ +/* + * TinyBlocks — tb_editor.h + * Editor visual block-based (estilo Scratch) implementado como LibraryBlock. + * + * O editor é o próprio bloco "Editor.Scene": não abre janela nem processa + * eventos SDL2 diretamente. Em vez disso: + * - implementa on_draw, produzindo um TinyBlocks_RenderableBlock + * - lê o estado de input/mouse/teclado a partir de um bloco SDL2.Events + * conectado ao seu input "events" + * - deve ser conectado ao input "scene" de um bloco SDL2.App, que é quem + * de fato cria a janela, roda o loop e interpreta o RenderableBlock. + * + * Uso: + * tb_library_register(rt, tb_editor_get_library()); + * tb_library_register(rt, tb_sdl2_get_library()); + * + * TinyBlocks_Block* events = tb_block_create(rt, tb_type_block_find(rt,"SDL2.Events")); + * TinyBlocks_Block* scene = tb_block_create(rt, tb_type_block_find(rt,"Editor.Scene")); + * tb_block_set_default(scene, 0, tb_value_block(events)); + * + * TinyBlocks_Block* app = tb_block_create(rt, tb_type_block_find(rt,"SDL2.App")); + * tb_block_set_default(app, 3, tb_value_block(scene)); + * tb_block_set_default(app, 4, tb_value_block(events)); + * tb_block_eval(app, rt); // roda o loop principal — bloqueia até fechar + */ +#ifndef TINYBLOCKS_EDITOR_H +#define TINYBLOCKS_EDITOR_H + +#include + +TB_API const TinyBlocks_LibraryDescriptor* tb_editor_get_library(void); +TB_API const TinyBlocks_LibraryDescriptor* tinyblocks_get_library(void); + +/* Enfileira um .so para ser carregado automaticamente ao abrir o editor */ +TB_API void tb_editor_preload(const char* path); + +#endif /* TINYBLOCKS_EDITOR_H */ diff --git a/libraries/tinyblocks-editor/src/tb_editor.c b/libraries/tinyblocks-editor/src/tb_editor.c new file mode 100644 index 0000000..ee2119d --- /dev/null +++ b/libraries/tinyblocks-editor/src/tb_editor.c @@ -0,0 +1,3020 @@ +/* + * TinyBlocks — tb_editor.c + * Editor visual no estilo Scratch, implementado como TypeBlock "Editor.Scene". + * + * Não abre janela nem conhece backend: implementa on_draw (produzindo um + * TinyBlocks_RenderableBlock) e lê a entrada de um bloco Graphics.Input + * conectado ao seu input "events". É a cena de um Graphics.Window da + * interface tinyblocks-graphics, que escolhe o backend (SDL2 ou outro). + * + * O Palco (Editor.Stage, tb_stage.c) é um componente à parte: fica embutido + * no painel direito ou, ao ser destacado, vira a cena de outro Graphics.Window. + * + * Modelo de programação (igual ao Scratch): + * - blocos de comando se empilham formando scripts (executados de cima para baixo); + * - repórteres (blocos com saída) encaixam nos campos de entrada de outros blocos; + * - blocos de controle (repita / se / se-senão / repita até) têm "bocas" + * que abrigam outra pilha; + * - "quando ⚑ for clicado" inicia um script quando a bandeira verde é clicada. + * + * Execução: cada comando vira uma árvore de blocos do runtime (cada repórter + * encaixado = uma conexão de input) avaliada com tb_block_eval. A sequência + * e os blocos de controle são interpretados pelo próprio editor. + */ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include "tb_stage.h" +#include "../include/tb_editor.h" + + +/* ══════════════════════════════════════════════════════════════════════════ + * Fila de preload (tb_editor_preload antes do bloco entrar em uso) + * ══════════════════════════════════════════════════════════════════════════ */ +#define MAX_PRELOAD 16 +static char s_preload[MAX_PRELOAD][512]; +static int s_preload_n = 0; + +TB_API void tb_editor_preload(const char* path) { + if (!path || s_preload_n >= MAX_PRELOAD) return; + strncpy(s_preload[s_preload_n++], path, 511); +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Layout da janela + * + * ┌──────────────────── barra de menu (azul) ──────────────────────────────┐ + * ├─ abas ───────────────────────────────────────────┬─ ⚑ ● ──────────────┤ + * │cat│ flyout (blocos) │ área de scripts │ palco / saída │ + * └───┴─────────────────┴─────────────────────────────┴─────────────────────┘ + * ══════════════════════════════════════════════════════════════════════════ */ +#define WIN_W_DEFAULT 1280 +#define WIN_H_DEFAULT 720 +#define MENU_H 44 +#define TAB_H 36 +#define CAT_W 68 +#define FLY_W 250 +#define FLY_PAD 12 +#define FLY_BTN_W 150 +#define PALETTE_W (CAT_W + FLY_W) +#define STAGE_W 360 +#define STAGE_BAR_H 44 +#define PAL_Y (MENU_H + TAB_H) +#define WS_X PALETTE_W +#define WS_Y (MENU_H + TAB_H) +#define WIN_W (ed->win_w) +#define WIN_H (ed->win_h) +#define WS_W (ed->win_w - PALETTE_W - STAGE_W) +#define WS_H (ed->win_h - WS_Y) +#define TAB_W 150 +#define PLUS_W 28 +#define LIB_BTN_X 150 +#define LIB_BTN_W 170 + +/* ── Geometria dos blocos ────────────────────────────────────────────────── */ +#define FS 12 /* texto dos blocos */ +#define FS_UI 13 /* texto da interface */ +#define FS_SM 11 +#define BLK_GAP 5 /* espaço entre partes do rótulo */ +#define BLK_PAD 10 +#define ROW_MIN_STACK 36 +#define ROW_MIN_REP 24 +#define SLOT_MIN_H 20 +#define SLOT_MIN_W 28 +#define SLOT_LINE_H 15 +#define HAT_CAP 18 /* altura do "chapéu" acima da linha do rótulo */ +#define HAT_CAP_W 96 +#define ARM_W 16 /* braço esquerdo dos blocos C */ +#define BOT_H 22 /* braço inferior dos blocos C */ +#define MID_H 26 /* braço "senão" */ +#define MOUTH_MIN 22 +#define NOTCH_X 12 /* encaixe (macho) sob os comandos */ +#define NOTCH_W 18 +#define NOTCH_D 4 +#define PREVIEW_H 64 /* área de on_draw */ +#define PREVIEW_W 168 +#define SNAP_R 28.f + +#define MAX_WS 256 +#define MAX_INPUTS 16 +#define MAX_PARTS 40 +#define MAX_TABS 8 +#define MAX_FLY 192 +#define MAX_CATS 24 +#define MAX_VARS 64 +#define MAX_CALL_DEPTH 32 +#define MAX_STEPS 500000L +#define MAX_RUN_BLOCKS 200000 +#define STAGE_BUF 16384 +#define LIT_TEXT_CAP 512 +#define MAX_HOT_LIBS 16 +#define MAX_HOT_TYPES 64 +#define MAX_USER_BLOCKS 16 +#define MAX_UBLK_SLOTS 8 + +/* ══════════════════════════════════════════════════════════════════════════ + * Cores (paleta do Scratch 3) — componentes 0..1 + * ══════════════════════════════════════════════════════════════════════════ */ +typedef struct { float r,g,b,a; } Col; +#define C(r,g,b) {(r)/255.0f,(g)/255.0f,(b)/255.0f,1.0f} +#define COLA(r,g,b,a)((Col){(r)/255.0f,(g)/255.0f,(b)/255.0f,(a)/255.0f}) +static inline Col col_mul(Col c, float k) { return (Col){c.r*k,c.g*k,c.b*k,c.a}; } + +static const Col COL_MENU = C( 76,151,255); /* #4C97FF */ +static const Col COL_MENU_DARK = C( 61,121,204); +static const Col COL_UI_BG = C(229,240,255); /* #E5F0FF */ +static const Col COL_PANEL = C(255,255,255); +static const Col COL_FLY = C(249,249,249); +static const Col COL_WS_BG = C(249,249,249); +static const Col COL_GRID = C(221,221,221); +static const Col COL_BORDER = C(217,217,217); +static const Col COL_TEXT = C( 87, 94,117); /* #575E75 */ +static const Col COL_TEXT_DIM = C(150,155,175); +static const Col COL_TAB_OFF = C(217,227,242); +static const Col COL_HOVER = C(214,228,248); +static const Col COL_FLAG = C( 76,191, 86); /* #4CBF56 */ +static const Col COL_FLAG_DARK = C( 69,153, 61); +static const Col COL_STOP = C(236, 89, 89); /* #EC5959 */ +static const Col COL_STOP_DARK = C(184, 60, 60); +static const Col COL_WHITE = C(255,255,255); +static const Col COL_MISSING = C(170,170,170); +static const Col COL_EXT = C( 15,189,140); /* extensões */ +static const Col COL_EXT_DARK = C( 11,142,105); +static const Col COL_VAR = C(255,140, 26); +static const Col COL_MON_BG = C(230,240,255); +static const Col COL_MON_BORDER = C(195,204,217); +static const Col COL_ERR_MENU = C(255,215,215); +static const Col COL_ERR_TEXT = C(204, 60, 60); + +/* ── Categorias ──────────────────────────────────────────────────────────── */ +typedef enum { + CAT_EVENTS, CAT_CONTROL, CAT_OPERATORS, CAT_VARIABLES, CAT_LOOKS, CAT_PEN, CAT_MYBLOCKS, + CAT_BUILTIN_N +} CatId; + +static const struct { const char* name; Col col, dark; } s_builtin_cats[CAT_BUILTIN_N] = { + {"Eventos", C(255,191, 0), C(204,153, 0)}, + {"Controle", C(255,171, 25), C(207,139, 23)}, + {"Operadores", C( 89,192, 89), C( 56,148, 56)}, + {"Variáveis", C(255,140, 26), C(219,110, 0)}, + {"Aparência", C(153,102,255), C(119, 77,203)}, + {"Caneta", C( 15,189,140), C( 11,142,105)}, + {"Meus Blocos", C(255,102,128), C(255, 51, 85)}, +}; + +#define USER_COLOR_COUNT 8 +static const Col s_user_colors[USER_COLOR_COUNT] = { + C(255,102,128), C( 76,151,255), C(153,102,255), C(207, 99,207), + C(255,191, 0), C(255,171, 25), C( 89,192, 89), C( 15,189,140), +}; + +/* ── Rótulos dos blocos (%N = campo de entrada N) ───────────────────────── */ +typedef struct { + const char* type; + const char* label; + const char* defs; /* valores iniciais dos campos, separados por '|' */ +} BlockSpec; + +static const BlockSpec s_specs[] = { + {"Events.WhenRun", "quando ⚑ for clicado", NULL}, + {"Control.Repeat", "repita %1 vezes", "10"}, + {"Control.RepeatUntil", "repita até que %1", NULL}, + {"Control.If", "se %1 então", NULL}, + {"Control.IfElse", "se %1 então", NULL}, + {"Operators.Lt", "%1 < %2", "|50"}, + {"Operators.Eq", "%1 = %2", "|50"}, + {"Operators.Gt", "%1 > %2", "|50"}, + {"Operators.And", "%1 e %2", NULL}, + {"Operators.Or", "%1 ou %2", NULL}, + {"Operators.Not", "não %1", NULL}, + {"Operators.Random", "número aleatório entre %1 e %2", "1|10"}, + {"Math.Add", "%1 + %2", NULL}, + {"Math.Sub", "%1 - %2", NULL}, + {"Math.Mul", "%1 * %2", NULL}, + {"Math.Div", "%1 / %2", NULL}, + {"Math.Mod", "resto de %1 por %2", NULL}, + {"Math.Abs", "valor absoluto de %1", NULL}, + {"Math.Max", "maior entre %1 e %2", NULL}, + {"Math.Min", "menor entre %1 e %2", NULL}, + {"Text.Concat", "junte %1 com %2", "maçã|banana"}, + {"Text.Length", "tamanho de %1", "maçã"}, + {"Literal.Text", "texto %1", NULL}, + {"Variables.Set", "mude %1 para %2", "x|0"}, + {"Variables.Change", "adicione %2 a %1", "x|1"}, + {"Variables.Get", "%1", "x"}, + {"IO.Print", "escreva %1 %2", "Olá!|"}, + {"IO.PrintInt", "escreva o número %1", NULL}, + {"Port.In", "parâmetro %1", "x"}, + {"Port.Out", "devolva %1 = %2", "resultado|"}, + {"Stage.Clear", "apague tudo", NULL}, + {"Stage.Background", "mude o fundo para r %1 g %2 b %3", "255|255|255"}, + {"Stage.PenColor", "mude a cor da caneta para r %1 g %2 b %3", "76|151|255"}, + {"Stage.PenSize", "mude o tamanho da caneta para %1", "4"}, + {"Stage.Line", "desenhe linha de x %1 y %2 até x %3 y %4", "-100|0|100|0"}, + {"Stage.Rect", "desenhe retângulo em x %1 y %2 largura %3 altura %4", "0|0|120|80"}, + {"Stage.Circle", "desenhe círculo em x %1 y %2 raio %3", "0|0|50"}, + {"Stage.Text", "escreva %1 no palco em x %2 y %3", "Olá!|-40|0"}, +}; + +/* ══════════════════════════════════════════════════════════════════════════ + * Estruturas de dados + * ══════════════════════════════════════════════════════════════════════════ */ +typedef enum { SH_STACK, SH_HAT, SH_C1, SH_C2, SH_REPORTER, SH_BOOL } Shape; + +/* Relação de um bloco com o pai */ +#define REL_NONE (-1) +#define REL_NEXT 0 +#define REL_SUB0 1 /* REL_SUB0 + k: boca k de um bloco C */ +#define REL_ARG0 3 /* REL_ARG0 + i: campo de entrada i */ + +typedef struct { + int16_t arg; /* -1 = texto; senão índice do campo */ + int16_t len; + const char* txt; + float x, w; +} Part; + +typedef struct { + bool used; + bool dragging; + TinyBlocks_TypeBlock* type; + char type_name[64]; + float x, y; /* posição (só para o topo de uma pilha) */ + int parent, prel; + int next; + int sub[2]; + int args[MAX_INPUTS]; + char in_text[MAX_INPUTS][64]; + char lit_text[LIT_TEXT_CAP]; + + /* layout — recalculado a cada frame */ + float ax, ay, w, h; + float row_y, row_h, prev_y; + float sub_y[2], sub_h[2]; + float slot_x[MAX_INPUTS], slot_y[MAX_INPUTS], slot_w[MAX_INPUTS], slot_h[MAX_INPUTS]; + int part_n; + Part parts[MAX_PARTS]; + + TinyBlocks_Block* live_rt; /* última instância no runtime (não-owning) */ +} EdBlock; + +typedef struct { + EdBlock ws[MAX_WS]; + int top[MAX_WS]; /* pilhas de topo, em ordem de desenho */ + int top_n; + float ws_sx, ws_sy; + char name[48]; + bool is_composite; + int comp_id; + int color_idx; +} Tab; + +typedef struct { + char name[48]; + int input_count, output_count; + char input_names[MAX_UBLK_SLOTS][32]; + char output_names[MAX_UBLK_SLOTS][32]; + Tab* snap; /* cópia da aba no momento do "Salvar" */ + TinyBlocks_TypeBlock* reg_type; + int tab_idx; + int color_idx; +} UserBlockDef; + +typedef struct { + UserBlockDef* def; + TinyBlocks_Value in[MAX_UBLK_SLOTS]; + TinyBlocks_Value out[MAX_UBLK_SLOTS]; +} CallFrame; + +typedef struct { + char path[512]; + void* dl; + time_t mtime; + TinyBlocks_LibraryBlock* lib; +} HotLib; + +typedef struct { char name[32]; char prefix[32]; Col col, dark; float fly_y; } Cat; + +typedef enum { FI_HEADER, FI_BUTTON, FI_BLOCK } FlyKind; +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 }; + +typedef struct { + TinyBlocks* rt; + + Cat cats[MAX_CATS]; + int cat_n; + Tab fly; /* blocos-modelo do flyout */ + FlyItem fly_items[MAX_FLY]; + int fly_n; + float fly_scroll, fly_total_h; + + Tab tabs[MAX_TABS]; + int tab_n; + int cur_tab; + + UserBlockDef user_blocks[MAX_USER_BLOCKS]; + int user_block_n; + + char comp_name_buf[48]; + int comp_name_len; + bool comp_name_active; + + bool ctx_menu_open; + int ctx_menu_bi; + int ctx_menu_x, ctx_menu_y; + int ctx_menu_hover; + int ctx_items[8]; + int ctx_n; + + EdSt state; + int press_bi; + float press_mx, press_my; + int drag_bi; + float drag_ox, drag_oy; + SnapKind snap_kind; + int snap_bi, snap_idx; + float pan_mx, pan_my, pan_sx, pan_sy; + + bool editing; + int edit_bi, edit_in; + + int bubble_bi; + char bubble_text[128]; + + char stage_buf[STAGE_BUF]; + + /* Execução */ + char var_name[MAX_VARS][32]; + TinyBlocks_Value var_val[MAX_VARS]; + int var_n; + CallFrame frames[MAX_CALL_DEPTH]; + int frame_n; + long steps; + bool abort; + char abort_msg[160]; + TinyBlocks_Block** run_blocks; /* instâncias criadas na última execução */ + int run_n, run_cap; + Tab* live_tab; + FILE* cap_file; + int cap_saved; + + float mouse_x, mouse_y; + bool flag_hover, stop_hover, lib_hover, detach_hover; + + /* Palco: embutido no painel ou numa janela própria (Graphics.Window) */ + TinyBlocks_Block* stage; + TinyBlocks_Block* stage_win; + TinyBlocks_Block* stage_in; + + bool clip_on; + float clip[4]; + + HotLib hot_libs[MAX_HOT_LIBS]; + int hot_lib_n; + int hot_check_frame; + char hot_status[256]; + bool hot_status_ok; + + bool path_input_active; + char path_input_buf[512]; + int path_input_len; + + int win_w, win_h; +} Ed; + +#define CT (ed->tabs[ed->cur_tab]) + +/* Ponteiro global para o editor ativo — os eval_fn dos blocos do editor + * (variáveis, compostos, portas) só recebem (self, rt). */ +static Ed* g_active_ed = NULL; + +static void palette_rebuild(Ed* ed); + +/* ══════════════════════════════════════════════════════════════════════════ + * Helpers de desenho — emitem TinyBlocks_DrawCmd em um RenderableBlock + * ══════════════════════════════════════════════════════════════════════════ */ +static inline void rb_fill_rect(TinyBlocks_RenderableBlock* rb, float x,float y,float w,float h, Col c) +{ tb_draw_fill_rect(rb,x,y,w,h,c.r,c.g,c.b,c.a); } + +static inline void rb_fill_rrect(TinyBlocks_RenderableBlock* rb, float x,float y,float w,float h,float rad, Col c) +{ tb_draw_fill_rrect(rb,x,y,w,h,rad<0?0:rad,c.r,c.g,c.b,c.a); } + +static inline void rb_fill_circle(TinyBlocks_RenderableBlock* rb, float cx,float cy,float rad, Col c) +{ tb_draw_fill_circle(rb,cx,cy,rad,c.r,c.g,c.b,c.a); } + +static inline void rb_stroke_rect(TinyBlocks_RenderableBlock* rb, float x,float y,float w,float h,float t, Col c) +{ tb_draw_stroke_rect(rb,x,y,w,h,t,c.r,c.g,c.b,c.a); } + +static inline void rb_line(TinyBlocks_RenderableBlock* rb, float x0,float y0,float x1,float y1,float w, Col c) +{ tb_draw_stroke_line(rb,x0,y0,x1,y1,w,c.r,c.g,c.b,c.a); } + +static inline bool in_rect(float mx, float my, float x, float y, float w, float h) +{ return mx>=x && mx=y && myclip_on = true; + ed->clip[0]=x; ed->clip[1]=y; ed->clip[2]=w; ed->clip[3]=h; + tb_draw_set_clip(rb, x, y, w, h); +} +static void clip_clear(Ed* ed, TinyBlocks_RenderableBlock* rb) { + ed->clip_on = false; + tb_draw_clear_clip(rb); +} +static void clip_restore(Ed* ed, TinyBlocks_RenderableBlock* rb) { + if (ed->clip_on) tb_draw_set_clip(rb, ed->clip[0], ed->clip[1], ed->clip[2], ed->clip[3]); + else tb_draw_clear_clip(rb); +} + +/* Hexágono (repórter booleano) desenhado em faixas de 1px */ +static void draw_hex(TinyBlocks_RenderableBlock* rb, float x, float y, float w, float h, Col c) { + float half = h*0.5f; + int rows = (int)(h + 0.5f); + for (int r = 0; r < rows; r++) { + float in = fabsf(r + 0.5f - half); + if (in > w*0.5f) in = w*0.5f; + rb_fill_rect(rb, x+in, y+r, w-2*in, 1.f, c); + } +} + +/* Encaixe trapezoidal sob um comando; y = borda inferior do bloco */ +static void draw_bump(TinyBlocks_RenderableBlock* rb, float x, float y, Col c, Col d) { + float bx = x + NOTCH_X; + for (int r = 0; r <= NOTCH_D; r++) + rb_fill_rect(rb, bx+r-1, y-1+r, NOTCH_W-2*r+2, 1.f, d); + for (int r = 0; r < NOTCH_D; r++) + rb_fill_rect(rb, bx+r, y-1+r, NOTCH_W-2*r, 1.f, c); +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Valores + * ══════════════════════════════════════════════════════════════════════════ */ +static void value_to_str(const TinyBlocks_Value* v, char* buf, size_t cap) { + switch (v->kind) { + case TB_VALUE_INTEGER: snprintf(buf, cap, "%lld", (long long)v->as.integer); break; + case TB_VALUE_REAL: snprintf(buf, cap, "%g", v->as.real); break; + case TB_VALUE_TEXT: snprintf(buf, cap, "%s", v->as.text ? v->as.text : ""); break; + case TB_VALUE_BLOCK: snprintf(buf, cap, "[bloco]"); break; + case TB_VALUE_VECTOR: snprintf(buf, cap, "[vetor]"); break; + case TB_VALUE_JSON: snprintf(buf, cap, "[json]"); break; + default: buf[0] = 0; break; + } +} + +static bool value_num(const TinyBlocks_Value* v, double* d) { + if (v->kind == TB_VALUE_INTEGER) { *d = (double)v->as.integer; return true; } + if (v->kind == TB_VALUE_REAL) { *d = v->as.real; return true; } + if (v->kind == TB_VALUE_TEXT && v->as.text && v->as.text[0]) { + char* e; *d = strtod(v->as.text, &e); + return *e == 0; + } + return false; +} + +static long long value_to_ll(const TinyBlocks_Value* v) { + double d; + if (v->kind == TB_VALUE_INTEGER) return v->as.integer; + return value_num(v, &d) ? llround(d) : 0; +} + +static bool value_truthy(const TinyBlocks_Value* v) { + switch (v->kind) { + case TB_VALUE_INTEGER: return v->as.integer != 0; + case TB_VALUE_REAL: return v->as.real != 0.0; + case TB_VALUE_TEXT: { + const char* t = v->as.text ? v->as.text : ""; + if (!t[0] || strcmp(t, "0") == 0) return false; + const char* f = "false"; + for (; *t && *f; t++, f++) if (tolower((unsigned char)*t) != *f) return true; + return *t || *f; + } + case TB_VALUE_BLOCK: return v->as.block != NULL; + default: return false; + } +} + +/* Converte o texto de um campo no valor esperado pelo slot. + * Slots sem tipo (NONE) adivinham: inteiro, real ou texto. */ +static TinyBlocks_Value value_from_text(const char* raw, TinyBlocks_ValueKind k) { + char* e; + switch (k) { + case TB_VALUE_INTEGER: { + long long v = strtoll(raw, &e, 10); + if (*e == '.' || *e == 'e' || *e == 'E') v = llround(strtod(raw, NULL)); + return tb_value_integer(v); + } + case TB_VALUE_REAL: return tb_value_real(strtod(raw, NULL)); + case TB_VALUE_TEXT: return tb_value_text(raw); + case TB_VALUE_NONE: { + long long iv = strtoll(raw, &e, 10); + if (*e == 0) return tb_value_integer(iv); + double dv = strtod(raw, &e); + if (*e == 0) return tb_value_real(dv); + return tb_value_text(raw); + } + default: return tb_value_none(); + } +} + +static int str_icmp(const char* a, const char* b) { + for (;; a++, b++) { + int ca = tolower((unsigned char)*a), cb = tolower((unsigned char)*b); + if (ca != cb || !ca) return (ca > cb) - (ca < cb); + } +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Tipos de bloco: forma, categoria, rótulo + * ══════════════════════════════════════════════════════════════════════════ */ +static const char* display_name(const char* full) { + if (!full) return "?"; + const char* p = strrchr(full,'.'); + return p ? p+1 : full; +} + +static const BlockSpec* spec_of(const char* tn) { + if (!tn) return NULL; + for (size_t i = 0; i < sizeof(s_specs)/sizeof(s_specs[0]); i++) + if (strcmp(s_specs[i].type, tn) == 0) return &s_specs[i]; + return NULL; +} + +static int input_count(const TinyBlocks_TypeBlock* t) { + if (!t) return 0; + return t->input_desc_count < MAX_INPUTS ? (int)t->input_desc_count : MAX_INPUTS; +} + +static Shape shape_of(const TinyBlocks_TypeBlock* t) { + if (!t || !t->type_name) return SH_STACK; + const char* n = t->type_name; + if (strncmp(n, "Events.", 7) == 0) return SH_HAT; + if (strcmp(n, "Control.If") == 0 || strcmp(n, "Control.Repeat") == 0 || + strcmp(n, "Control.RepeatUntil") == 0) return SH_C1; + if (strcmp(n, "Control.IfElse") == 0) return SH_C2; + if (strcmp(n, "Operators.Lt") == 0 || strcmp(n, "Operators.Eq") == 0 || + strcmp(n, "Operators.Gt") == 0 || strcmp(n, "Operators.And") == 0 || + strcmp(n, "Operators.Or") == 0 || strcmp(n, "Operators.Not") == 0) + return SH_BOOL; + return t->output_desc_count > 0 ? SH_REPORTER : SH_STACK; +} + +static bool shape_is_value(Shape s) { return s == SH_REPORTER || s == SH_BOOL; } + +static bool slot_is_bool(const TinyBlocks_TypeBlock* t, int i) { + if (!t || !t->type_name) return false; + const char* n = t->type_name; + if (i == 0 && (strcmp(n,"Control.If") == 0 || strcmp(n,"Control.IfElse") == 0 || + strcmp(n,"Control.RepeatUntil") == 0)) return true; + return strcmp(n,"Operators.And") == 0 || strcmp(n,"Operators.Or") == 0 || + strcmp(n,"Operators.Not") == 0; +} + +static bool is_lit_text(const TinyBlocks_TypeBlock* t) { + return t && t->type_name && strcmp(t->type_name, "Literal.Text") == 0; +} + +static int builtin_cat_of(const char* n) { + if (!n) return -1; + if (strncmp(n,"Events.",7) == 0) return CAT_EVENTS; + if (strncmp(n,"Control.",8) == 0) return CAT_CONTROL; + if (strncmp(n,"Operators.",10) == 0 || strncmp(n,"Math.",5) == 0 || + strncmp(n,"Text.",5) == 0 || strncmp(n,"Literal.",8) == 0) + return CAT_OPERATORS; + if (strncmp(n,"Variables.",10) == 0) return CAT_VARIABLES; + if (strncmp(n,"IO.",3) == 0) return CAT_LOOKS; + if (strncmp(n,"Stage.",6) == 0) return CAT_PEN; + if (strncmp(n,"User.",5) == 0 || strncmp(n,"Port.",5) == 0) + return CAT_MYBLOCKS; + return -1; +} + +static void type_prefix(const char* n, char* out, size_t cap) { + const char* dot = strchr(n, '.'); + size_t len = dot ? (size_t)(dot - n) : strlen(n); + if (len >= cap) len = cap - 1; + memcpy(out, n, len); out[len] = 0; +} + +static int cat_of(Ed* ed, const char* n) { + int c = builtin_cat_of(n); + if (c >= 0 || !n) return c; + char pre[32]; type_prefix(n, pre, sizeof(pre)); + for (int i = CAT_BUILTIN_N; i < ed->cat_n; i++) + if (strcmp(ed->cats[i].prefix, pre) == 0) return i; + return -1; +} + +static UserBlockDef* user_def_find(Ed* ed, const char* name) { + for (int i = 0; i < ed->user_block_n; i++) + if (strcmp(ed->user_blocks[i].name, name) == 0) return &ed->user_blocks[i]; + return NULL; +} + +static void block_cols(Ed* ed, const EdBlock* b, Col* c, Col* d) { + const TinyBlocks_TypeBlock* t = b->type; + if (!t || !t->type_name) { *c = COL_MISSING; *d = col_mul(COL_MISSING, 0.75f); return; } + if (strncmp(t->type_name, "User.", 5) == 0) { + UserBlockDef* def = user_def_find(ed, t->type_name + 5); + *c = s_user_colors[def ? def->color_idx : 0]; + *d = col_mul(*c, 0.8f); + return; + } + int k = cat_of(ed, t->type_name); + if (k < 0) { *c = COL_EXT; *d = COL_EXT_DARK; return; } + *c = ed->cats[k].col; *d = ed->cats[k].dark; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Pool de blocos de uma aba (índices estáveis, sem compactação) + * ══════════════════════════════════════════════════════════════════════════ */ +static void blk_defaults(EdBlock* b) { + const TinyBlocks_TypeBlock* t = b->type; + int n = input_count(t); + for (int i = 0; i < n; i++) { + TinyBlocks_ValueKind k = t->input_descs[i].expected_kind; + if ((k == TB_VALUE_INTEGER || k == TB_VALUE_REAL) && !slot_is_bool(t, i)) + strcpy(b->in_text[i], "0"); + } + const BlockSpec* sp = t ? spec_of(t->type_name) : NULL; + const char* p = sp ? sp->defs : NULL; + for (int i = 0; i < n && p; i++) { + const char* e = strchr(p, '|'); + size_t len = e ? (size_t)(e - p) : strlen(p); + if (len > 63) len = 63; + memcpy(b->in_text[i], p, len); b->in_text[i][len] = 0; + p = e ? e + 1 : NULL; + } +} + +static int blk_alloc(Tab* T) { + for (int i = 0; i < MAX_WS; i++) { + if (T->ws[i].used) continue; + EdBlock* b = &T->ws[i]; + memset(b, 0, sizeof(*b)); + b->used = true; + b->parent = -1; b->prel = REL_NONE; b->next = -1; + b->sub[0] = b->sub[1] = -1; + for (int s = 0; s < MAX_INPUTS; s++) b->args[s] = -1; + return i; + } + return -1; +} + +static int blk_new(Tab* T, TinyBlocks_TypeBlock* type) { + int i = blk_alloc(T); + if (i < 0) return -1; + EdBlock* b = &T->ws[i]; + b->type = type; + if (type && type->type_name) strncpy(b->type_name, type->type_name, 63); + blk_defaults(b); + return i; +} + +static void top_remove(Tab* T, int bi) { + for (int i = 0; i < T->top_n; i++) { + if (T->top[i] != bi) continue; + memmove(&T->top[i], &T->top[i+1], (size_t)(T->top_n - i - 1) * sizeof(int)); + T->top_n--; + return; + } +} + +/* Adiciona (ou traz para a frente) uma pilha de topo */ +static void top_add(Tab* T, int bi) { + top_remove(T, bi); + if (T->top_n < MAX_WS) T->top[T->top_n++] = bi; +} + +/* Liga child ao pai na relação rel (child = -1 desliga) */ +static void blk_link(Tab* T, int parent, int rel, int child) { + EdBlock* p = &T->ws[parent]; + if (rel == REL_NEXT) p->next = child; + else if (rel < REL_ARG0) p->sub[rel - REL_SUB0] = child; + else p->args[rel - REL_ARG0] = child; + if (child >= 0) { T->ws[child].parent = parent; T->ws[child].prel = rel; } +} + +static int linked(Tab* T, int parent, int rel) { + EdBlock* p = &T->ws[parent]; + if (rel == REL_NEXT) return p->next; + if (rel < REL_ARG0) return p->sub[rel - REL_SUB0]; + return p->args[rel - REL_ARG0]; +} + +/* Solta bi do pai; vira topo de pilha (levando os blocos abaixo dele) */ +static void detach(Tab* T, int bi) { + EdBlock* b = &T->ws[bi]; + if (b->parent < 0) return; + blk_link(T, b->parent, b->prel, -1); + b->parent = -1; b->prel = REL_NONE; + top_add(T, bi); +} + +static int chain_last(Tab* T, int bi) { + while (T->ws[bi].next >= 0) bi = T->ws[bi].next; + return bi; +} + +static int stack_root(Tab* T, int bi) { + while (T->ws[bi].parent >= 0) bi = T->ws[bi].parent; + return bi; +} + +static float chain_h(Tab* T, int head) { + float h = 0; + for (int c = head; c >= 0; c = T->ws[c].next) h += T->ws[c].h; + return h; +} + +/* Insere a pilha bi (de topo) em parent/rel; o que estava lá vai para baixo dela */ +static void attach_insert(Tab* T, int parent, int rel, int bi) { + top_remove(T, bi); + int old = linked(T, parent, rel); + int last = chain_last(T, bi); + blk_link(T, parent, rel, bi); + if (old >= 0) blk_link(T, last, REL_NEXT, old); +} + +/* Encaixa a pilha bi acima da pilha de topo target */ +static void attach_above(Tab* T, int target, int bi) { + float dh = chain_h(T, bi); + top_remove(T, target); + blk_link(T, chain_last(T, bi), REL_NEXT, target); + T->ws[bi].x = T->ws[target].x; + T->ws[bi].y = T->ws[target].y - dh; +} + +/* Encaixa o repórter bi no campo s; um repórter que já estava lá é expulso */ +static void attach_arg(Tab* T, int parent, int s, int bi) { + top_remove(T, bi); + int old = T->ws[parent].args[s]; + if (old >= 0) { + detach(T, old); + T->ws[old].x = T->ws[old].ax + 20; + T->ws[old].y = T->ws[old].ay + 24; + } + blk_link(T, parent, REL_ARG0 + s, bi); +} + +static void mark_drag(Tab* T, int bi, bool v) { + for (; bi >= 0; bi = T->ws[bi].next) { + EdBlock* b = &T->ws[bi]; + b->dragging = v; + for (int s = 0; s < MAX_INPUTS; s++) if (b->args[s] >= 0) mark_drag(T, b->args[s], v); + for (int k = 0; k < 2; k++) if (b->sub[k] >= 0) mark_drag(T, b->sub[k], v); + } +} + +/* Cópia profunda (repórteres, bocas e — se with_next — os blocos abaixo) */ +static int copy_tree(Tab* S, int si, Tab* D, bool with_next) { + int first = -1, prev = -1; + for (int c = si; c >= 0; c = with_next ? S->ws[c].next : -1) { + int ni = blk_alloc(D); + if (ni < 0) break; + EdBlock* n = &D->ws[ni]; + const EdBlock* o = &S->ws[c]; + *n = *o; + n->parent = -1; n->prel = REL_NONE; n->next = -1; + n->sub[0] = n->sub[1] = -1; + n->live_rt = NULL; n->dragging = false; + for (int s = 0; s < MAX_INPUTS; s++) n->args[s] = -1; + for (int s = 0; s < MAX_INPUTS; s++) { + if (o->args[s] < 0) continue; + int k = copy_tree(S, o->args[s], D, false); + if (k >= 0) blk_link(D, ni, REL_ARG0 + s, k); + } + for (int k = 0; k < 2; k++) { + if (o->sub[k] < 0) continue; + int h = copy_tree(S, o->sub[k], D, true); + if (h >= 0) blk_link(D, ni, REL_SUB0 + k, h); + } + if (prev >= 0) blk_link(D, prev, REL_NEXT, ni); else first = ni; + prev = ni; + } + return first; +} + +/* Libera bi, tudo o que está encaixado nele e os blocos abaixo */ +static void free_tree(Ed* ed, Tab* T, int bi) { + while (bi >= 0) { + EdBlock* b = &T->ws[bi]; + int nx = b->next; + for (int s = 0; s < MAX_INPUTS; s++) if (b->args[s] >= 0) free_tree(ed, T, b->args[s]); + for (int k = 0; k < 2; k++) if (b->sub[k] >= 0) free_tree(ed, T, b->sub[k]); + top_remove(T, bi); + if (T == &CT) { + if (ed->editing && ed->edit_bi == bi) ed->editing = false; + if (ed->bubble_bi == bi) ed->bubble_bi = -1; + } + b->used = false; + b->live_rt = NULL; + bi = nx; + } +} + +/* Apaga só bi (com o que está encaixado nele); os blocos abaixo sobem */ +static void delete_heal(Ed* ed, Tab* T, int bi) { + EdBlock* b = &T->ws[bi]; + int nx = b->next, par = b->parent, rel = b->prel; + if (nx >= 0) { b->next = -1; T->ws[nx].parent = -1; T->ws[nx].prel = REL_NONE; } + if (par >= 0) blk_link(T, par, rel, -1); + b->parent = -1; + if (nx >= 0) { + if (par >= 0) blk_link(T, par, rel, nx); + else { T->ws[nx].x = b->x; T->ws[nx].y = b->y; top_add(T, nx); } + } + free_tree(ed, T, bi); +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Layout: mede (tamanhos) e posiciona (coordenadas do workspace) + * ══════════════════════════════════════════════════════════════════════════ */ +static const char* slot_src(const EdBlock* b, int s) { + return (is_lit_text(b->type) && s == 0) ? b->lit_text : b->in_text[s]; +} + +static int text_lines(const char* s) { + int n = 1; + for (; *s; s++) if (*s == '\n') n++; + return n; +} + +/* Copia a linha idx de s em out (truncada para exibição) */ +static bool text_line(const char* s, int idx, char* out, size_t cap) { + for (int i = 0; i < idx; i++) { + s = strchr(s, '\n'); + if (!s) return false; + s++; + } + size_t n = strcspn(s, "\n"); + size_t lim = cap - 4 < 48 ? cap - 4 : 48; + bool cut = n > lim; + if (cut) { n = lim; while (n > 0 && ((unsigned char)s[n] & 0xC0) == 0x80) n--; } + memcpy(out, s, n); out[n] = 0; + if (cut) strcat(out, "…"); + return true; +} + +static void slot_size(const EdBlock* b, int s, float* w, float* h) { + if (slot_is_bool(b->type, s)) { *w = 40; *h = SLOT_MIN_H; return; } + const char* src = slot_src(b, s); + int lines = text_lines(src); + float mw = 0; char line[64]; + for (int l = 0; l < lines; l++) { + text_line(src, l, line, sizeof(line)); + float lw = tw(line, FS); + if (lw > mw) mw = lw; + } + *w = fmaxf(SLOT_MIN_W, mw + 16); + *h = fmaxf(SLOT_MIN_H, lines*SLOT_LINE_H + 6); +} + +static const char* part_str(const Part* p, char* buf, size_t cap) { + size_t n = (size_t)p->len < cap - 1 ? (size_t)p->len : cap - 1; + memcpy(buf, p->txt, n); buf[n] = 0; + return buf; +} + +static void add_part(EdBlock* b, int arg, const char* s, int len) { + if (b->part_n >= MAX_PARTS) return; + if (arg < 0) { + while (len > 0 && *s == ' ') { s++; len--; } + while (len > 0 && s[len-1] == ' ') len--; + if (len <= 0) return; + } + Part* p = &b->parts[b->part_n++]; + p->arg = (int16_t)arg; p->txt = s; p->len = (int16_t)len; + p->x = p->w = 0; +} + +static void build_parts(EdBlock* b) { + b->part_n = 0; + const TinyBlocks_TypeBlock* t = b->type; + if (!t) { add_part(b, -1, b->type_name, (int)strlen(b->type_name)); return; } + int n = input_count(t); + bool used[MAX_INPUTS] = {0}; + const BlockSpec* sp = spec_of(t->type_name); + if (sp) { + const char* p = sp->label; const char* seg = p; + while (*p) { + if (p[0] == '%' && p[1] >= '1' && p[1] <= '9') { + add_part(b, -1, seg, (int)(p - seg)); + int a = p[1] - '1'; + if (a < n) { add_part(b, a, NULL, 0); used[a] = true; } + p += 2; seg = p; + } else p++; + } + add_part(b, -1, seg, (int)(p - seg)); + } else { + const char* nm = strncmp(t->type_name, "User.", 5) == 0 ? t->type_name + 5 + : display_name(t->type_name); + add_part(b, -1, nm, (int)strlen(nm)); + } + /* Campos que o rótulo não cita: "nome [campo]" ao final */ + for (int i = 0; i < n; i++) { + if (used[i]) continue; + const char* sn = t->input_descs[i].name; + if (sn) add_part(b, -1, sn, (int)strlen(sn)); + add_part(b, i, NULL, 0); + } +} + +static void measure(Tab* T, int bi); + +static float measure_chain(Tab* T, int head) { + float h = 0; + for (int c = head; c >= 0; c = T->ws[c].next) { measure(T, c); h += T->ws[c].h; } + return h; +} + +static void measure(Tab* T, int bi) { + EdBlock* b = &T->ws[bi]; + Shape sh = shape_of(b->type); + bool val = shape_is_value(sh); + build_parts(b); + + float pad = sh == SH_BOOL ? 12.f : BLK_PAD; + float row_h = val ? ROW_MIN_REP : ROW_MIN_STACK; + float x = pad; + char buf[96]; + for (int i = 0; i < b->part_n; i++) { + Part* p = &b->parts[i]; + p->x = x; + if (p->arg < 0) { + p->w = tw(part_str(p, buf, sizeof(buf)), FS); + } else { + int s = p->arg; float aw, ah; + if (b->args[s] >= 0) { + measure(T, b->args[s]); + aw = T->ws[b->args[s]].w; ah = T->ws[b->args[s]].h; + } else slot_size(b, s, &aw, &ah); + b->slot_x[s] = x; b->slot_w[s] = aw; b->slot_h[s] = ah; + p->w = aw; + if (ah + 8 > row_h) row_h = ah + 8; + } + x += p->w + BLK_GAP; + } + float w = b->part_n ? x - BLK_GAP + pad : 2*pad; + b->row_y = sh == SH_HAT ? HAT_CAP : 0.f; + b->row_h = row_h; + for (int i = 0; i < b->part_n; i++) { + int s = b->parts[i].arg; + if (s >= 0) b->slot_y[s] = b->row_y + (row_h - b->slot_h[s]) * 0.5f; + } + + float h = b->row_y + row_h; + switch (sh) { + case SH_HAT: if (w < HAT_CAP_W + 16) w = HAT_CAP_W + 16; break; + case SH_STACK: if (w < 64) w = 64; break; + case SH_C1: case SH_C2: { + int mouths = sh == SH_C2 ? 2 : 1; + float y = row_h; + for (int k = 0; k < mouths; k++) { + float ch = b->sub[k] >= 0 ? measure_chain(T, b->sub[k]) : 0.f; + b->sub_y[k] = y; + b->sub_h[k] = ch > MOUTH_MIN ? ch : MOUTH_MIN; + y += b->sub_h[k]; + if (k == 0 && mouths == 2) y += MID_H; + } + h = y + BOT_H; + if (w < 150) w = 150; + break; + } + default: if (w < row_h) w = row_h; break; + } + b->prev_y = 0; + if (b->type && b->type->on_draw) { + b->prev_y = h; h += PREVIEW_H; + if (w < PREVIEW_W) w = PREVIEW_W; + } + b->w = w; b->h = h; +} + +static void place_chain(Tab* T, int head, float x, float y); + +static void place(Tab* T, int bi, float x, float y) { + EdBlock* b = &T->ws[bi]; + b->ax = x; b->ay = y; + for (int s = 0; s < MAX_INPUTS; s++) + if (b->args[s] >= 0) place(T, b->args[s], x + b->slot_x[s], y + b->slot_y[s]); + for (int k = 0; k < 2; k++) + if (b->sub[k] >= 0) place_chain(T, b->sub[k], x + ARM_W, y + b->sub_y[k]); +} + +static void place_chain(Tab* T, int head, float x, float y) { + for (int c = head; c >= 0; c = T->ws[c].next) { place(T, c, x, y); y += T->ws[c].h; } +} + +static void layout_tab(Tab* T) { + for (int i = 0; i < T->top_n; i++) { + int h = T->top[i]; + measure_chain(T, h); + place_chain(T, h, T->ws[h].x, T->ws[h].y); + } +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Hit testing (coordenadas do workspace) + * ══════════════════════════════════════════════════════════════════════════ */ +static bool body_contains(const EdBlock* b, float x, float y) { + if (!in_rect(x, y, b->ax, b->ay, b->w, b->h)) return false; + float lx = x - b->ax, ly = y - b->ay; + Shape sh = shape_of(b->type); + if (sh == SH_C1 || sh == SH_C2) { + if (lx < ARM_W || ly < b->row_h || ly >= b->h - BOT_H) return true; + return sh == SH_C2 && ly >= b->sub_y[0] + b->sub_h[0] && ly < b->sub_y[1]; + } + if (sh == SH_HAT && ly < HAT_CAP && lx > HAT_CAP_W) return false; + return true; +} + +static int hit_chain(Tab* T, int head, float x, float y); + +/* Bloco mais interno sob (x,y) dentro de bi */ +static int hit_one(Tab* T, int bi, float x, float y) { + EdBlock* b = &T->ws[bi]; + for (int s = 0; s < MAX_INPUTS; s++) { + if (b->args[s] < 0) continue; + int r = hit_one(T, b->args[s], x, y); + if (r >= 0) return r; + } + for (int k = 0; k < 2; k++) { + if (b->sub[k] < 0) continue; + int r = hit_chain(T, b->sub[k], x, y); + if (r >= 0) return r; + } + return body_contains(b, x, y) ? bi : -1; +} + +static int hit_chain(Tab* T, int head, float x, float y) { + for (int c = head; c >= 0; c = T->ws[c].next) { + int r = hit_one(T, c, x, y); + if (r >= 0) return r; + } + return -1; +} + +static int hit_ws(Tab* T, float x, float y) { + for (int i = T->top_n - 1; i >= 0; i--) { + int r = hit_chain(T, T->top[i], x, y); + if (r >= 0) return r; + } + return -1; +} + +/* Campo vazio de bi sob (x,y) */ +static int hit_slot(Tab* T, int bi, float x, float y) { + EdBlock* b = &T->ws[bi]; + for (int s = 0; s < input_count(b->type); s++) { + if (b->args[s] >= 0) continue; + if (in_rect(x, y, b->ax + b->slot_x[s], b->ay + b->slot_y[s], b->slot_w[s], b->slot_h[s])) + return s; + } + return -1; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Renderização de blocos + * ══════════════════════════════════════════════════════════════════════════ */ +static void draw_slot(TinyBlocks_RenderableBlock* rb, const EdBlock* b, int s, + float x, float y, Col dark, bool editing) { + float sx = x + b->slot_x[s], sy = y + b->slot_y[s]; + float sw = b->slot_w[s], sh = b->slot_h[s]; + if (slot_is_bool(b->type, s)) { draw_hex(rb, sx, sy, sw, sh, col_mul(dark, 0.9f)); return; } + + const char* src = slot_src(b, s); + int lines = text_lines(src); + float rad = lines > 1 ? 4.f : sh*0.5f; + rb_fill_rrect(rb, sx, sy, sw, sh, rad, editing ? COL_MENU : COLA(0,0,0,40)); + rb_fill_rrect(rb, sx+1, sy+1, sw-2, sh-2, rad-1, COL_WHITE); + + char line[64]; + float ly = sy + (sh - lines*SLOT_LINE_H)*0.5f + SLOT_LINE_H*0.5f; + float end_x = sx + sw*0.5f; + for (int l = 0; l < lines; l++) { + text_line(src, l, line, sizeof(line)); + float lw = tw(line, FS); + float lx = lines > 1 ? sx + 7 : sx + (sw - lw)*0.5f; + rb_text_c(rb, lx, ly, line, COL_TEXT, FS); + end_x = lx + lw; + ly += SLOT_LINE_H; + } + if (editing) rb_fill_rect(rb, end_x + 1, ly - SLOT_LINE_H - 7, 1.5f, 14, COL_TEXT); +} + +static void render_chain(Ed* ed, TinyBlocks_RenderableBlock* rb, Tab* T, int head, float ox, float oy); + +static void render_block(Ed* ed, TinyBlocks_RenderableBlock* rb, Tab* T, int bi, float ox, float oy) { + EdBlock* b = &T->ws[bi]; + Shape sh = shape_of(b->type); + Col c, d; block_cols(ed, b, &c, &d); + float x = b->ax + ox, y = b->ay + oy, w = b->w, h = b->h; + + /* ── Corpo: contorno escuro + preenchimento ─────────────────────── */ + switch (sh) { + case SH_HAT: + rb_fill_rrect(rb, x, y, HAT_CAP_W, HAT_CAP*2 + 4, HAT_CAP, d); + rb_fill_rrect(rb, x, y + HAT_CAP, w, h - HAT_CAP, 4, d); + rb_fill_rrect(rb, x+1, y+1, HAT_CAP_W-2, HAT_CAP*2 + 2, HAT_CAP-1, c); + rb_fill_rrect(rb, x+1, y + HAT_CAP + 1, w-2, h - HAT_CAP - 2, 3, c); + break; + case SH_C1: case SH_C2: { + float r[4][4] = { + { x, y, w, b->row_h }, /* braço superior */ + { x, y, ARM_W, h }, /* braço esquerdo */ + { x, y + h - BOT_H, w, BOT_H }, /* braço inferior */ + { x, y + b->sub_y[0] + b->sub_h[0], w, MID_H }, /* "senão" */ + }; + int n = sh == SH_C2 ? 4 : 3; + for (int i = 0; i < n; i++) rb_fill_rrect(rb, r[i][0], r[i][1], r[i][2], r[i][3], 4, d); + for (int i = 0; i < n; i++) rb_fill_rrect(rb, r[i][0]+1, r[i][1]+1, r[i][2]-2, r[i][3]-2, 3, c); + break; + } + case SH_REPORTER: { + float rad = b->prev_y > 0 ? 8.f : h*0.5f; + rb_fill_rrect(rb, x, y, w, h, rad, d); + rb_fill_rrect(rb, x+1, y+1, w-2, h-2, rad-1, c); + break; + } + case SH_BOOL: + draw_hex(rb, x, y, w, h, d); + draw_hex(rb, x+1, y+1, w-2, h-2, c); + break; + default: + rb_fill_rrect(rb, x, y, w, h, 4, d); + rb_fill_rrect(rb, x+1, y+1, w-2, h-2, 3, c); + break; + } + + /* ── Rótulo e campos vazios ─────────────────────────────────────── */ + float cy = y + b->row_y + b->row_h*0.5f; + char buf[96]; + bool can_edit = ed->editing && T == &CT && ed->edit_bi == bi; + for (int i = 0; i < b->part_n; i++) { + const Part* p = &b->parts[i]; + if (p->arg < 0) + rb_text_c(rb, x + p->x, cy, part_str(p, buf, sizeof(buf)), COL_WHITE, FS); + else if (b->args[p->arg] < 0) + draw_slot(rb, b, p->arg, x, y, d, can_edit && ed->edit_in == p->arg); + } + if (sh == SH_C2) + rb_text_c(rb, x + BLK_PAD, y + b->sub_y[0] + b->sub_h[0] + MID_H*0.5f, "senão", COL_WHITE, FS); + + /* ── Bocas (pilhas internas) ────────────────────────────────────── */ + int mouths = sh == SH_C1 ? 1 : sh == SH_C2 ? 2 : 0; + for (int k = 0; k < mouths; k++) { + if (b->sub[k] >= 0) render_chain(ed, rb, T, b->sub[k], ox, oy); + draw_bump(rb, x + ARM_W, y + b->sub_y[k], c, d); + } + + /* ── Repórteres encaixados ──────────────────────────────────────── */ + for (int s = 0; s < MAX_INPUTS; s++) + if (b->args[s] >= 0) render_block(ed, rb, T, b->args[s], ox, oy); + + /* ── Área de on_draw ────────────────────────────────────────────── */ + if (b->prev_y > 0) { + float py = y + b->prev_y; + rb_fill_rrect(rb, x+4, py, w-8, PREVIEW_H-4, 4, col_mul(c, 0.85f)); + if (b->live_rt) { + TinyBlocks_RenderableBlock* sub = NULL; + tb_draw_set_clip(rb, x+4, py, w-8, PREVIEW_H-4); + if (b->type->on_draw(b->live_rt, ed->rt, &sub) && sub) { + tb_draw_merge_offset(rb, sub, x, py); + tb_renderable_release(sub); + } + clip_restore(ed, rb); + } + } + + /* Encaixe inferior por último: fica sobre o topo do bloco seguinte */ + if (!shape_is_value(sh)) draw_bump(rb, x, y + h, c, d); +} + +/* Desenha de baixo para cima, para cada encaixe cobrir o bloco seguinte */ +static void render_chain(Ed* ed, TinyBlocks_RenderableBlock* rb, Tab* T, int head, float ox, float oy) { + int ids[MAX_WS], n = 0; + for (int c = head; c >= 0 && n < MAX_WS; c = T->ws[c].next) ids[n++] = c; + for (int i = n - 1; i >= 0; i--) render_block(ed, rb, T, ids[i], ox, oy); +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Execução + * ══════════════════════════════════════════════════════════════════════════ */ +static void stage_append(Ed* ed, const char* s) { + size_t cur = strlen(ed->stage_buf), add = strlen(s); + if (add >= STAGE_BUF/2) { s += add - STAGE_BUF/2; add = strlen(s); } + if (cur + add >= STAGE_BUF - 1) { + size_t drop = cur + add - (STAGE_BUF - 1); + const char* nl = strchr(ed->stage_buf + drop, '\n'); + drop = nl ? (size_t)(nl - ed->stage_buf) + 1 : cur; + memmove(ed->stage_buf, ed->stage_buf + drop, cur - drop + 1); + } + strcat(ed->stage_buf, s); +} + +static void run_abort(Ed* ed, const char* msg) { + if (ed->abort) return; + ed->abort = true; + snprintf(ed->abort_msg, sizeof(ed->abort_msg), "%s", msg); +} + +static int var_find(Ed* ed, const char* n, bool create) { + if (!n || !n[0]) return -1; + for (int i = 0; i < ed->var_n; i++) + if (strcmp(ed->var_name[i], n) == 0) return i; + if (!create || ed->var_n >= MAX_VARS) return -1; + int i = ed->var_n++; + strncpy(ed->var_name[i], n, 31); ed->var_name[i][31] = 0; + ed->var_val[i] = tb_value_integer(0); + return i; +} + +static void clear_live(Tab* T) { + for (int i = 0; i < MAX_WS; i++) T->ws[i].live_rt = NULL; +} + +/* Destrói as instâncias do runtime da execução anterior */ +static void run_reset(Ed* ed) { + for (int i = ed->run_n - 1; i >= 0; i--) tb_block_destroy(ed->run_blocks[i], ed->rt); + ed->run_n = 0; + for (int t = 0; t < ed->tab_n; t++) clear_live(&ed->tabs[t]); + /* Referências a blocos (não-owning) agora estariam penduradas */ + for (int v = 0; v < ed->var_n; v++) + if (ed->var_val[v].kind == TB_VALUE_BLOCK) ed->var_val[v] = tb_value_integer(0); +} + +static void run_track(Ed* ed, TinyBlocks_Block* b) { + if (ed->run_n >= ed->run_cap) { + int nc = ed->run_cap ? ed->run_cap*2 : 256; + TinyBlocks_Block** p = realloc(ed->run_blocks, (size_t)nc * sizeof(*p)); + if (!p) return; + ed->run_blocks = p; ed->run_cap = nc; + } + ed->run_blocks[ed->run_n++] = b; +} + +static TinyBlocks_TypeBlock* blk_type(Ed* ed, EdBlock* b) { + if (!b->type && b->type_name[0]) b->type = tb_type_block_find(ed->rt, b->type_name); + return b->type; +} + +/* Converte o bloco bi (e seus repórteres) em uma árvore de blocos do runtime */ +static TinyBlocks_Block* build_rt(Ed* ed, Tab* T, int bi) { + EdBlock* b = &T->ws[bi]; + TinyBlocks_TypeBlock* t = blk_type(ed, b); + if (!t) return NULL; + if (ed->run_n >= MAX_RUN_BLOCKS) { run_abort(ed, "limite de blocos em execução atingido"); return NULL; } + TinyBlocks_Block* r = tb_block_create(ed->rt, t); + if (!r) return NULL; + run_track(ed, r); + if (T == ed->live_tab) b->live_rt = r; + + bool lit = is_lit_text(t); + for (int s = 0; s < input_count(t); s++) { + if (b->args[s] >= 0) { + TinyBlocks_Block* c = build_rt(ed, T, b->args[s]); + if (c && c->output_count > 0) tb_block_connect(r, (uint32_t)s, c, 0); + continue; + } + const char* raw = slot_src(b, s); + if (!raw[0]) continue; + TinyBlocks_ValueKind k = lit ? TB_VALUE_TEXT : t->input_descs[s].expected_kind; + TinyBlocks_Value v = value_from_text(raw, k); + tb_block_set_default(r, (uint32_t)s, v); + tb_value_free(&v); + } + return r; +} + +/* Avalia um repórter; devolve uma cópia (owned) do primeiro output */ +static TinyBlocks_Value eval_reporter(Ed* ed, Tab* T, int bi) { + TinyBlocks_Block* r = build_rt(ed, T, bi); + if (!r) return tb_value_none(); + tb_block_eval(r, ed->rt); + return r->output_count > 0 ? tb_value_clone(r->outputs[0]) : tb_value_none(); +} + +static TinyBlocks_Value eval_arg(Ed* ed, Tab* T, int bi, int s) { + EdBlock* b = &T->ws[bi]; + if (b->args[s] >= 0) return eval_reporter(ed, T, b->args[s]); + const char* raw = slot_src(b, s); + if (!raw[0] || !b->type) return tb_value_none(); + return value_from_text(raw, b->type->input_descs[s].expected_kind); +} + +static bool step(Ed* ed) { + if (++ed->steps > MAX_STEPS) run_abort(ed, "limite de passos atingido (laço infinito?)"); + return !ed->abort; +} + +static void run_chain(Ed* ed, Tab* T, int head) { + for (int bi = head; bi >= 0 && step(ed); bi = T->ws[bi].next) { + EdBlock* b = &T->ws[bi]; + TinyBlocks_TypeBlock* t = blk_type(ed, b); + if (!t) continue; + const char* tn = t->type_name; + Shape sh = shape_of(t); + if (sh == SH_HAT || shape_is_value(sh)) continue; + + if (strcmp(tn, "Control.Repeat") == 0) { + TinyBlocks_Value v = eval_arg(ed, T, bi, 0); + long long n = value_to_ll(&v); + tb_value_free(&v); + for (long long k = 0; k < n && step(ed); k++) run_chain(ed, T, b->sub[0]); + } else if (strcmp(tn, "Control.RepeatUntil") == 0) { + for (;;) { + TinyBlocks_Value v = eval_arg(ed, T, bi, 0); + bool done = value_truthy(&v); + tb_value_free(&v); + if (done || !step(ed)) break; + run_chain(ed, T, b->sub[0]); + } + } else if (strcmp(tn, "Control.If") == 0 || strcmp(tn, "Control.IfElse") == 0) { + TinyBlocks_Value v = eval_arg(ed, T, bi, 0); + bool cond = value_truthy(&v); + tb_value_free(&v); + if (cond) run_chain(ed, T, b->sub[0]); + else if (sh == SH_C2) run_chain(ed, T, b->sub[1]); + } else { + TinyBlocks_Block* r = build_rt(ed, T, bi); + if (r) tb_block_eval(r, ed->rt); + } + } +} + +/* Início/fim de uma execução: zera o runtime e captura o stdout no palco */ +static void run_begin(Ed* ed, bool clear) { + run_reset(ed); + ed->steps = 0; ed->abort = false; ed->abort_msg[0] = 0; ed->frame_n = 0; + ed->live_tab = &CT; + if (clear) ed->stage_buf[0] = 0; + fflush(stdout); + ed->cap_file = tmpfile(); + ed->cap_saved = -1; + if (ed->cap_file) { + ed->cap_saved = dup(STDOUT_FILENO); + if (ed->cap_saved >= 0) dup2(fileno(ed->cap_file), STDOUT_FILENO); + else { fclose(ed->cap_file); ed->cap_file = NULL; } + } +} + +static void run_end(Ed* ed) { + if (ed->cap_file) { + fflush(stdout); + dup2(ed->cap_saved, STDOUT_FILENO); + close(ed->cap_saved); + rewind(ed->cap_file); + char buf[STAGE_BUF]; + size_t n = fread(buf, 1, sizeof(buf) - 1, ed->cap_file); + buf[n] = 0; + fclose(ed->cap_file); + ed->cap_file = NULL; + stage_append(ed, buf); + } + const char* err = tinyblocks_last_error(ed->rt); + if (err && err[0]) { + char warn[512]; + snprintf(warn, sizeof(warn), "[AVISO] %s\n", err); + stage_append(ed, warn); + tinyblocks_clear_error(ed->rt); + } + if (ed->abort_msg[0]) { + char msg[200]; + snprintf(msg, sizeof(msg), "[ERRO] %s\n", ed->abort_msg); + stage_append(ed, msg); + } + ed->live_tab = NULL; + palette_rebuild(ed); /* variáveis novas aparecem no flyout */ +} + +/* Bandeira verde: roda os scripts "quando ⚑ for clicado", de cima para baixo */ +static void run_flag(Ed* ed) { + run_begin(ed, true); + int heads[MAX_WS], n = 0; + for (int i = 0; i < CT.top_n; i++) heads[n++] = CT.top[i]; + for (int i = 1; i < n; i++) + for (int j = i; j > 0 && CT.ws[heads[j]].y < CT.ws[heads[j-1]].y; j--) { + int tmp = heads[j]; heads[j] = heads[j-1]; heads[j-1] = tmp; + } + int started = 0; + for (int i = 0; i < n && !ed->abort; i++) { + EdBlock* b = &CT.ws[heads[i]]; + if (blk_type(ed, b) && strcmp(b->type->type_name, "Events.WhenRun") == 0) { + run_chain(ed, &CT, heads[i]); + started++; + } + } + run_end(ed); + if (!started) stage_append(ed, "Nenhum script começa com \"quando ⚑ for clicado\".\n"); +} + +/* Clique num bloco: roda a pilha inteira, ou mostra o valor de um repórter */ +static void run_click(Ed* ed, int bi) { + int root = stack_root(&CT, bi); + Shape sh = shape_of(blk_type(ed, &CT.ws[root])); + run_begin(ed, false); + if (shape_is_value(sh)) { + TinyBlocks_Value v = eval_reporter(ed, &CT, root); + value_to_str(&v, ed->bubble_text, sizeof(ed->bubble_text)); + if (!ed->bubble_text[0]) strcpy(ed->bubble_text, "(vazio)"); + ed->bubble_bi = root; + tb_value_free(&v); + } else { + run_chain(ed, &CT, root); + } + run_end(ed); +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Blocos do editor: eventos, controle, operadores, variáveis, literais, portas + * ══════════════════════════════════════════════════════════════════════════ */ +static void eval_noop(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + self->dirty = false; +} + +static int cmp_inputs(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value a = tb_block_get_input(self, rt, 0); + TinyBlocks_Value b = tb_block_get_input(self, rt, 1); + double x, y; + if (value_num(&a, &x) && value_num(&b, &y)) return (x > y) - (x < y); + char sa[256], sb[256]; + value_to_str(&a, sa, sizeof(sa)); + value_to_str(&b, sb, sizeof(sb)); + return str_icmp(sa, sb); +} + +static void eval_op_lt(TinyBlocks_Block* self, TinyBlocks* rt) +{ tb_block_set_output(self, 0, tb_value_integer(cmp_inputs(self, rt) < 0)); self->dirty = false; } +static void eval_op_eq(TinyBlocks_Block* self, TinyBlocks* rt) +{ tb_block_set_output(self, 0, tb_value_integer(cmp_inputs(self, rt) == 0)); self->dirty = false; } +static void eval_op_gt(TinyBlocks_Block* self, TinyBlocks* rt) +{ tb_block_set_output(self, 0, tb_value_integer(cmp_inputs(self, rt) > 0)); self->dirty = false; } + +static void eval_op_and(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value a = tb_block_get_input(self, rt, 0); + TinyBlocks_Value b = tb_block_get_input(self, rt, 1); + tb_block_set_output(self, 0, tb_value_integer(value_truthy(&a) && value_truthy(&b))); + self->dirty = false; +} +static void eval_op_or(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value a = tb_block_get_input(self, rt, 0); + TinyBlocks_Value b = tb_block_get_input(self, rt, 1); + tb_block_set_output(self, 0, tb_value_integer(value_truthy(&a) || value_truthy(&b))); + self->dirty = false; +} +static void eval_op_not(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value a = tb_block_get_input(self, rt, 0); + tb_block_set_output(self, 0, tb_value_integer(!value_truthy(&a))); + self->dirty = false; +} + +static void eval_op_random(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value a = tb_block_get_input(self, rt, 0); + TinyBlocks_Value b = tb_block_get_input(self, rt, 1); + double lo = 0, hi = 0; + value_num(&a, &lo); value_num(&b, &hi); + if (lo > hi) { double t = lo; lo = hi; hi = t; } + if (lo == floor(lo) && hi == floor(hi)) { + long long span = (long long)(hi - lo) + 1; + tb_block_set_output(self, 0, tb_value_integer((long long)lo + (span > 0 ? rand() % span : 0))); + } else { + tb_block_set_output(self, 0, tb_value_real(lo + (hi - lo) * rand() / (double)RAND_MAX)); + } + self->dirty = false; +} + +static void input_name(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i, char* out, size_t cap) { + TinyBlocks_Value v = tb_block_get_input(self, rt, i); + value_to_str(&v, out, cap); +} + +static void eval_var_get(TinyBlocks_Block* self, TinyBlocks* rt) { + char name[64]; input_name(self, rt, 0, name, sizeof(name)); + int i = g_active_ed ? var_find(g_active_ed, name, false) : -1; + tb_block_set_output(self, 0, i >= 0 ? tb_value_clone(g_active_ed->var_val[i]) + : tb_value_integer(0)); + self->dirty = false; +} + +static void eval_var_set(TinyBlocks_Block* self, TinyBlocks* rt) { + char name[64]; input_name(self, rt, 0, name, sizeof(name)); + int i = g_active_ed ? var_find(g_active_ed, name, true) : -1; + if (i >= 0) { + TinyBlocks_Value v = tb_block_get_input(self, rt, 1); + tb_value_free(&g_active_ed->var_val[i]); + g_active_ed->var_val[i] = tb_value_clone(v); + } + self->dirty = false; +} + +static void eval_var_change(TinyBlocks_Block* self, TinyBlocks* rt) { + char name[64]; input_name(self, rt, 0, name, sizeof(name)); + int i = g_active_ed ? var_find(g_active_ed, name, true) : -1; + if (i >= 0) { + TinyBlocks_Value by = tb_block_get_input(self, rt, 1); + TinyBlocks_Value* cur = &g_active_ed->var_val[i]; + double a = 0, d = 0; + value_num(cur, &a); value_num(&by, &d); + TinyBlocks_Value nv = (a == floor(a) && d == floor(d)) + ? tb_value_integer(llround(a + d)) : tb_value_real(a + d); + tb_value_free(cur); + *cur = nv; + } + self->dirty = false; +} + +static void eval_literal_int(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + tb_block_set_output(self, 0, tb_value_clone(v)); +} +static void eval_literal_real(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + tb_block_set_output(self, 0, tb_value_clone(v)); +} +static void eval_literal_text(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + const char* s = (v.kind==TB_VALUE_TEXT && v.as.text) ? v.as.text : ""; + tb_block_set_output(self, 0, tb_value_text(s)); +} + +/* ── Blocos compostos ("Meus Blocos") ──────────────────────────────────── + * A definição é uma aba com scripts; "parâmetro [x]" lê os inputs da chamada + * e "devolva [y] = (v)" escreve os outputs. */ +static CallFrame* cur_frame(void) { + Ed* ed = g_active_ed; + return (ed && ed->frame_n > 0) ? &ed->frames[ed->frame_n - 1] : NULL; +} + +static void eval_port_in(TinyBlocks_Block* self, TinyBlocks* rt) { + CallFrame* f = cur_frame(); + TinyBlocks_Value out = tb_value_none(); + if (f) { + char label[64]; input_name(self, rt, 0, label, sizeof(label)); + for (int i = 0; i < f->def->input_count; i++) + if (strcmp(f->def->input_names[i], label) == 0) { out = tb_value_clone(f->in[i]); break; } + } + tb_block_set_output(self, 0, out); + self->dirty = false; +} + +static void eval_port_out(TinyBlocks_Block* self, TinyBlocks* rt) { + CallFrame* f = cur_frame(); + if (f) { + char label[64]; input_name(self, rt, 0, label, sizeof(label)); + for (int i = 0; i < f->def->output_count; i++) { + if (strcmp(f->def->output_names[i], label) != 0) continue; + tb_value_free(&f->out[i]); + f->out[i] = tb_value_clone(tb_block_get_input(self, rt, 1)); + break; + } + } + self->dirty = false; +} + +static void eval_composite(TinyBlocks_Block* self, TinyBlocks* rt) { + Ed* ed = g_active_ed; + self->dirty = false; + const char* tn = self->type ? self->type->type_name : ""; + if (!ed || strncmp(tn, "User.", 5) != 0) return; + UserBlockDef* def = user_def_find(ed, tn + 5); + if (!def || !def->snap) return; + if (ed->frame_n >= MAX_CALL_DEPTH) { run_abort(ed, "recursão profunda demais em bloco composto"); return; } + + CallFrame* f = &ed->frames[ed->frame_n++]; + memset(f, 0, sizeof(*f)); + f->def = def; + for (int i = 0; i < def->input_count; i++) + f->in[i] = tb_value_clone(tb_block_get_input(self, rt, (uint32_t)i)); + + /* Roda os scripts da definição de cima para baixo */ + Tab* S = def->snap; + int heads[MAX_WS], n = 0; + for (int i = 0; i < S->top_n; i++) heads[n++] = S->top[i]; + for (int i = 1; i < n; i++) + for (int j = i; j > 0 && S->ws[heads[j]].y < S->ws[heads[j-1]].y; j--) { + int tmp = heads[j]; heads[j] = heads[j-1]; heads[j-1] = tmp; + } + for (int i = 0; i < n && !ed->abort; i++) + if (!shape_is_value(shape_of(blk_type(ed, &S->ws[heads[i]])))) + run_chain(ed, S, heads[i]); + + for (int i = 0; i < def->output_count; i++) { + tb_block_set_output(self, (uint32_t)i, f->out[i]); /* transfere ownership */ + f->out[i] = tb_value_none(); + } + for (int i = 0; i < def->input_count; i++) tb_value_free(&f->in[i]); + ed->frame_n--; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Tipos: invalidação/re-resolução (hot reload e redefinição de compostos) + * ══════════════════════════════════════════════════════════════════════════ */ +static void invalidate_tab(Tab* T) { + for (int i = 0; i < MAX_WS; i++) { T->ws[i].type = NULL; T->ws[i].live_rt = NULL; } +} + +static void invalidate_types(Ed* ed) { + run_reset(ed); + for (int t = 0; t < ed->tab_n; t++) invalidate_tab(&ed->tabs[t]); + for (int u = 0; u < ed->user_block_n; u++) + if (ed->user_blocks[u].snap) invalidate_tab(ed->user_blocks[u].snap); + invalidate_tab(&ed->fly); +} + +static void retype_tab(Ed* ed, Tab* T) { + for (int i = 0; i < MAX_WS; i++) { + EdBlock* b = &T->ws[i]; + if (!b->used) continue; + b->type = b->type_name[0] ? tb_type_block_find(ed->rt, b->type_name) : NULL; + if (!b->type) continue; + /* O tipo pode ter perdido campos: repórteres órfãos ficam soltos */ + for (int s = input_count(b->type); s < MAX_INPUTS; s++) { + int c = b->args[s]; + if (c < 0) continue; + detach(T, c); + T->ws[c].x = b->ax + b->w + 16; + T->ws[c].y = b->ay; + } + } +} + +static void retype_all(Ed* ed) { + for (int t = 0; t < ed->tab_n; t++) retype_tab(ed, &ed->tabs[t]); + for (int u = 0; u < ed->user_block_n; u++) + if (ed->user_blocks[u].snap) retype_tab(ed, ed->user_blocks[u].snap); + palette_rebuild(ed); +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Paleta: categorias + flyout + * ══════════════════════════════════════════════════════════════════════════ */ +static bool type_hidden(Ed* ed, const TinyBlocks_TypeBlock* t) { + const char* n = t->type_name; + if (!n || n[0] == '_' || strstr(n, "._")) return true; + if (strncmp(n, "Editor.", 7) == 0 || strncmp(n, "Graphics.", 9) == 0) return true; + if (strcmp(n, "Literal.Integer") == 0 || strcmp(n, "Literal.Real") == 0) return true; + if (strncmp(n, "Port.", 5) == 0) return !CT.is_composite; + return false; +} + +static void cats_rebuild(Ed* ed) { + ed->cat_n = 0; + for (int i = 0; i < CAT_BUILTIN_N; i++) { + Cat* c = &ed->cats[ed->cat_n++]; + memset(c, 0, sizeof(*c)); + strncpy(c->name, s_builtin_cats[i].name, sizeof(c->name) - 1); + c->col = s_builtin_cats[i].col; c->dark = s_builtin_cats[i].dark; + } + /* Uma categoria por prefixo de library (Python., MCP., Viz.…) */ + for (uint32_t i = 0; i < ed->rt->type_count && ed->cat_n < MAX_CATS; i++) { + TinyBlocks_TypeBlock* t = ed->rt->types[i]; + if (type_hidden(ed, t) || builtin_cat_of(t->type_name) >= 0) continue; + if (cat_of(ed, t->type_name) >= 0) continue; + Cat* c = &ed->cats[ed->cat_n++]; + memset(c, 0, sizeof(*c)); + type_prefix(t->type_name, c->prefix, sizeof(c->prefix)); + strncpy(c->name, c->prefix, sizeof(c->name) - 1); + c->col = COL_EXT; c->dark = COL_EXT_DARK; + } +} + +static void fly_add_block(Ed* ed, int cat, TinyBlocks_TypeBlock* t, const char* first, float* y) { + if (ed->fly_n >= MAX_FLY) return; + int bi = blk_new(&ed->fly, t); + if (bi < 0) return; + if (first) strncpy(ed->fly.ws[bi].in_text[0], first, 63); + measure(&ed->fly, bi); + place(&ed->fly, bi, FLY_PAD, *y); + float h = ed->fly.ws[bi].h; + ed->fly_items[ed->fly_n++] = (FlyItem){FI_BLOCK, cat, bi, *y, h + NOTCH_D}; + *y += h + 14; +} + +static void palette_rebuild(Ed* ed) { + cats_rebuild(ed); + memset(&ed->fly, 0, sizeof(ed->fly)); + ed->fly_n = 0; + float y = 8; + TinyBlocks_TypeBlock* var_get = tb_type_block_find(ed->rt, "Variables.Get"); + for (int c = 0; c < ed->cat_n && ed->fly_n < MAX_FLY; c++) { + ed->cats[c].fly_y = y; + ed->fly_items[ed->fly_n++] = (FlyItem){FI_HEADER, c, -1, y, 34}; + y += 34; + if (c == CAT_MYBLOCKS && ed->fly_n < MAX_FLY) { + ed->fly_items[ed->fly_n++] = (FlyItem){FI_BUTTON, c, -1, y, 42}; + y += 42; + } + for (uint32_t i = 0; i < ed->rt->type_count; i++) { + TinyBlocks_TypeBlock* t = ed->rt->types[i]; + if (type_hidden(ed, t) || cat_of(ed, t->type_name) != c) continue; + fly_add_block(ed, c, t, NULL, &y); + } + if (c == CAT_VARIABLES && var_get) + for (int v = 0; v < ed->var_n; v++) fly_add_block(ed, c, var_get, ed->var_name[v], &y); + y += 10; + } + ed->fly_total_h = y; +} + +static float cat_item_h(Ed* ed) { + float h = ed->cat_n ? (WIN_H - PAL_Y) / (float)ed->cat_n : 58.f; + return h > 58.f ? 58.f : h; +} + +static int current_cat(Ed* ed) { + int cur = 0; + for (int c = 0; c < ed->cat_n; c++) + if (ed->cats[c].fly_y <= ed->fly_scroll + 16) cur = c; + return cur; +} + +static float fly_max_scroll(Ed* ed) { + float m = ed->fly_total_h - 60; + return m > 0 ? m : 0; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Abas e blocos compostos + * ══════════════════════════════════════════════════════════════════════════ */ +static void tab_select(Ed* ed, int i) { + if (i < 0 || i >= ed->tab_n) return; + ed->cur_tab = i; + ed->editing = false; + ed->comp_name_active = false; + ed->bubble_bi = -1; + if (CT.is_composite) { + const char* nm = CT.comp_id >= 0 ? ed->user_blocks[CT.comp_id].name : ""; + strncpy(ed->comp_name_buf, nm, sizeof(ed->comp_name_buf) - 1); + ed->comp_name_buf[sizeof(ed->comp_name_buf) - 1] = 0; + ed->comp_name_len = (int)strlen(ed->comp_name_buf); + } + palette_rebuild(ed); +} + +static bool tab_new(Ed* ed, const char* name, bool is_composite) { + if (ed->tab_n >= MAX_TABS) { + snprintf(ed->hot_status, sizeof(ed->hot_status), "Limite de %d abas atingido", MAX_TABS); + ed->hot_status_ok = false; + return false; + } + int idx = ed->tab_n++; + Tab* T = &ed->tabs[idx]; + memset(T, 0, sizeof(*T)); + if (name && name[0]) strncpy(T->name, name, sizeof(T->name) - 1); + else snprintf(T->name, sizeof(T->name), "Código %d", idx + 1); + T->comp_id = -1; + T->is_composite = is_composite; + tab_select(ed, idx); + return true; +} + +static void tab_close(Ed* ed, int ti) { + if (ed->tab_n <= 1 || ti < 0 || ti >= ed->tab_n) return; + run_reset(ed); + for (int i = ti; i < ed->tab_n - 1; i++) ed->tabs[i] = ed->tabs[i+1]; + ed->tab_n--; + for (int u = 0; u < ed->user_block_n; u++) { + int* t = &ed->user_blocks[u].tab_idx; + if (*t == ti) *t = -1; else if (*t > ti) (*t)--; + } + tab_select(ed, ed->cur_tab >= ed->tab_n ? ed->tab_n - 1 + : ed->cur_tab > ti ? ed->cur_tab - 1 : ed->cur_tab); +} + +static void new_composite_tab(Ed* ed) { + if (!tab_new(ed, "Novo bloco", true)) return; + ed->comp_name_buf[0] = 0; + ed->comp_name_len = 0; + ed->comp_name_active = true; + snprintf(ed->hot_status, sizeof(ed->hot_status), + "Monte o bloco com \"parâmetro\" e \"devolva\" (Meus Blocos) e clique em Salvar"); + ed->hot_status_ok = true; +} + +static void open_def(Ed* ed, const char* uname) { + UserBlockDef* def = user_def_find(ed, uname); + if (!def) return; + if (def->tab_idx >= 0 && def->tab_idx < ed->tab_n) { tab_select(ed, def->tab_idx); return; } + /* A aba foi fechada: recria a partir da cópia salva */ + if (!def->snap || !tab_new(ed, def->name, true)) return; + Tab* T = &CT; + *T = *def->snap; + clear_live(T); + snprintf(T->name, sizeof(T->name), "%s", def->name); + T->is_composite = true; + T->comp_id = (int)(def - ed->user_blocks); + T->color_idx = def->color_idx; + def->tab_idx = ed->cur_tab; + tab_select(ed, ed->cur_tab); +} + +static void collect_labels(Tab* T, const char* type_name, char names[][32], int* count, const char* fallback) { + *count = 0; + for (int i = 0; i < MAX_WS && *count < MAX_UBLK_SLOTS; i++) { + EdBlock* b = &T->ws[i]; + if (!b->used || strcmp(b->type_name, type_name) != 0) continue; + char lbl[32]; + if (b->in_text[0][0]) snprintf(lbl, sizeof(lbl), "%s", b->in_text[0]); + else snprintf(lbl, sizeof(lbl), fallback, *count); + bool dup = false; + for (int k = 0; k < *count; k++) if (strcmp(names[k], lbl) == 0) dup = true; + if (!dup) strcpy(names[(*count)++], lbl); + } +} + +static void save_composite_from_tab(Ed* ed) { + if (!ed->comp_name_buf[0]) { + snprintf(ed->hot_status, sizeof(ed->hot_status), "Digite um nome para o bloco antes de salvar."); + ed->hot_status_ok = false; + ed->comp_name_active = true; + return; + } + UserBlockDef* def = user_def_find(ed, ed->comp_name_buf); + if (!def) { + if (ed->user_block_n >= MAX_USER_BLOCKS) { + snprintf(ed->hot_status, sizeof(ed->hot_status), "Limite de blocos compostos atingido."); + ed->hot_status_ok = false; + return; + } + def = &ed->user_blocks[ed->user_block_n++]; + memset(def, 0, sizeof(*def)); + snprintf(def->name, sizeof(def->name), "%s", ed->comp_name_buf); + } + int def_idx = (int)(def - ed->user_blocks); + snprintf(CT.name, sizeof(CT.name), "%s", def->name); + CT.comp_id = def_idx; + def->tab_idx = ed->cur_tab; + def->color_idx = CT.color_idx; + + collect_labels(&CT, "Port.In", def->input_names, &def->input_count, "in%d"); + collect_labels(&CT, "Port.Out", def->output_names, &def->output_count, "out%d"); + + /* Instâncias e referências ao tipo antigo precisam sumir antes de destruí-lo */ + invalidate_types(ed); + if (def->reg_type) { tb_block_destroy(&def->reg_type->base, ed->rt); def->reg_type = NULL; } + + if (!def->snap) def->snap = (Tab*)malloc(sizeof(Tab)); + if (def->snap) *def->snap = CT; + + TinyBlocks_SlotDesc in_s[MAX_UBLK_SLOTS], out_s[MAX_UBLK_SLOTS]; + for (int i = 0; i < def->input_count; i++) in_s[i] = (TinyBlocks_SlotDesc){def->input_names[i], TB_VALUE_NONE}; + for (int i = 0; i < def->output_count; i++) out_s[i] = (TinyBlocks_SlotDesc){def->output_names[i], TB_VALUE_NONE}; + char type_name[64]; + snprintf(type_name, sizeof(type_name), "User.%s", def->name); + def->reg_type = tb_type_block_create(ed->rt, type_name, + def->input_count ? in_s : NULL, (uint32_t)def->input_count, + def->output_count ? out_s : NULL, (uint32_t)def->output_count, + eval_composite); + + retype_all(ed); + snprintf(ed->hot_status, sizeof(ed->hot_status), "Bloco \"%s\" salvo em Meus Blocos", def->name); + ed->hot_status_ok = true; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Hot reload de libraries .so + * ══════════════════════════════════════════════════════════════════════════ */ +static time_t file_mtime(const char* path) { + struct stat st; + return (stat(path, &st) == 0) ? st.st_mtime : 0; +} + +typedef const TinyBlocks_LibraryDescriptor* (*GetLibFn)(void); + +static bool hotlib_load(Ed* ed, const char* path) { + if (ed->hot_lib_n >= MAX_HOT_LIBS) { + snprintf(ed->hot_status, sizeof(ed->hot_status), + "Hot reload: limite de %d libs atingido", MAX_HOT_LIBS); + ed->hot_status_ok = false; + return false; + } + void* dl = dlopen(path, RTLD_NOW | RTLD_LOCAL); + if (!dl) { + snprintf(ed->hot_status, sizeof(ed->hot_status), "dlopen: %s", dlerror()); + ed->hot_status_ok = false; + return false; + } + GetLibFn get_lib = (GetLibFn)(uintptr_t)dlsym(dl, TINYBLOCKS_LIBRARY_SYMBOL); + if (!get_lib) { + const char* base = strrchr(path, '/'); + base = base ? base+1 : path; + if (strncmp(base, "libtinyblocks-", 14) == 0) + snprintf(ed->hot_status, sizeof(ed->hot_status), + "'%s' é dependência — carregue a library (ex: python.so, mcp.so)", base); + else + snprintf(ed->hot_status, sizeof(ed->hot_status), + "'%s' não exporta tinyblocks_get_library — não é uma library válida", base); + ed->hot_status_ok = false; + dlclose(dl); + return false; + } + TinyBlocks_LibraryBlock* lib = tb_library_register(ed->rt, get_lib()); + if (!lib) { + snprintf(ed->hot_status, sizeof(ed->hot_status), "tb_library_register falhou para %s", path); + ed->hot_status_ok = false; + dlclose(dl); + return false; + } + HotLib* h = &ed->hot_libs[ed->hot_lib_n++]; + strncpy(h->path, path, sizeof(h->path)-1); + h->dl = dl; + h->mtime = file_mtime(path); + h->lib = lib; + retype_all(ed); /* blocos que estavam sem tipo podem ganhar um agora */ + snprintf(ed->hot_status, sizeof(ed->hot_status), "Carregado: %s", path); + ed->hot_status_ok = true; + return true; +} + +static void hotlib_reload(Ed* ed, int idx) { + HotLib* h = &ed->hot_libs[idx]; + /* Nenhuma instância ou ponteiro de tipo pode sobreviver ao unload */ + invalidate_types(ed); + tb_library_unload(ed->rt, h->lib); + h->lib = NULL; + dlclose(h->dl); + h->dl = NULL; + h->mtime = file_mtime(h->path); + + void* dl = dlopen(h->path, RTLD_NOW | RTLD_LOCAL); + GetLibFn get_lib = dl ? (GetLibFn)(uintptr_t)dlsym(dl, TINYBLOCKS_LIBRARY_SYMBOL) : NULL; + TinyBlocks_LibraryBlock* lib = get_lib ? tb_library_register(ed->rt, get_lib()) : NULL; + if (!lib) { + snprintf(ed->hot_status, sizeof(ed->hot_status), "Hot reload falhou: %s", + dl ? h->path : dlerror()); + ed->hot_status_ok = false; + if (dl) dlclose(dl); + retype_all(ed); + return; + } + h->dl = dl; + h->lib = lib; + retype_all(ed); + snprintf(ed->hot_status, sizeof(ed->hot_status), "Recarregado: %s", h->path); + ed->hot_status_ok = true; +} + +static void hotlib_check(Ed* ed) { + for (int i = 0; i < ed->hot_lib_n; i++) { + HotLib* h = &ed->hot_libs[i]; + if (!h->dl || !h->path[0]) continue; + time_t mt = file_mtime(h->path); + if (mt && mt != h->mtime) hotlib_reload(ed, i); + } +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Renderização da interface + * ══════════════════════════════════════════════════════════════════════════ */ +static void render_menu(Ed* ed, TinyBlocks_RenderableBlock* rb) { + rb_fill_rect(rb, 0, 0, WIN_W, MENU_H, COL_MENU); + rb_text_c(rb, 18, MENU_H*0.5f, "TinyBlocks", COL_WHITE, 20); + + if (ed->lib_hover || ed->path_input_active) + rb_fill_rect(rb, LIB_BTN_X, 0, LIB_BTN_W, MENU_H, COL_MENU_DARK); + rb_text_c(rb, LIB_BTN_X + 14, MENU_H*0.5f, "Carregar library…", COL_WHITE, FS_UI); + + if (ed->path_input_active) { + float bx = LIB_BTN_X + LIB_BTN_W + 10, bw = WIN_W - bx - 16; + rb_fill_rrect(rb, bx, 7, bw, MENU_H-14, 6, COL_WHITE); + const char* t = ed->path_input_buf[0] ? ed->path_input_buf : "caminho do .so (Enter carrega, Esc cancela)"; + rb_text_c(rb, bx + 10, MENU_H*0.5f, t, ed->path_input_buf[0] ? COL_TEXT : COL_TEXT_DIM, FS_UI); + float cw = tw(ed->path_input_buf, FS_UI); + rb_fill_rect(rb, bx + 11 + cw, MENU_H*0.5f - 8, 1.5f, 16, COL_TEXT); + } else if (ed->hot_status[0]) { + float w = tw(ed->hot_status, FS_SM); + rb_text_c(rb, WIN_W - 16 - w, MENU_H*0.5f, ed->hot_status, + ed->hot_status_ok ? COL_WHITE : COL_ERR_MENU, FS_SM); + } +} + +static void render_tab_bar(Ed* ed, TinyBlocks_RenderableBlock* rb) { + float y0 = MENU_H, wbar = WIN_W - STAGE_W; + rb_fill_rect(rb, 0, y0, wbar, TAB_H, COL_UI_BG); + for (int i = 0; i < ed->tab_n; i++) { + float tx = 8 + i*TAB_W; + if (tx + TAB_W > wbar - PLUS_W) break; + bool cur = i == ed->cur_tab; + Col bg = cur ? COL_PANEL : COL_TAB_OFF; + rb_fill_rrect(rb, tx, y0+6, TAB_W-4, TAB_H-6, 8, bg); + rb_fill_rect(rb, tx, y0+TAB_H-8, TAB_W-4, 8, bg); + float cy = y0 + 6 + (TAB_H-6)*0.5f, lx = tx + 12; + if (ed->tabs[i].is_composite) { + rb_fill_circle(rb, tx+14, cy, 5, s_user_colors[ed->tabs[i].color_idx]); + lx = tx + 24; + } + rb_text_c(rb, lx, cy, ed->tabs[i].name, cur ? COL_MENU : COL_TEXT, FS_UI); + if (ed->tab_n > 1) rb_text_c(rb, tx+TAB_W-22, cy, "×", COL_TEXT_DIM, FS_UI); + } + float px = 8 + ed->tab_n*TAB_W; + if (px + PLUS_W <= wbar && ed->tab_n < MAX_TABS) + rb_text_c(rb, px+8, y0 + 6 + (TAB_H-6)*0.5f, "+", COL_TEXT, 18); +} + +static void render_categories(Ed* ed, TinyBlocks_RenderableBlock* rb) { + rb_fill_rect(rb, 0, PAL_Y, CAT_W, WIN_H-PAL_Y, COL_PANEL); + rb_line(rb, CAT_W-1, PAL_Y, CAT_W-1, WIN_H, 1.f, COL_BORDER); + float ih = cat_item_h(ed); + int cur = current_cat(ed); + for (int c = 0; c < ed->cat_n; c++) { + float iy = PAL_Y + c*ih; + if (c == cur) rb_fill_rect(rb, 0, iy, CAT_W-1, ih, COL_UI_BG); + float cy = iy + ih*0.36f; + rb_fill_circle(rb, CAT_W*0.5f, cy, 10, ed->cats[c].dark); + rb_fill_circle(rb, CAT_W*0.5f, cy, 9, ed->cats[c].col); + float w = tw(ed->cats[c].name, 10); + rb_text_c(rb, CAT_W*0.5f - w*0.5f, iy + ih*0.76f, ed->cats[c].name, COL_TEXT, 10); + } +} + +static void render_flyout(Ed* ed, TinyBlocks_RenderableBlock* rb) { + rb_fill_rect(rb, CAT_W, PAL_Y, FLY_W, WIN_H-PAL_Y, COL_FLY); + rb_line(rb, PALETTE_W-1, PAL_Y, PALETTE_W-1, WIN_H, 1.f, COL_BORDER); + clip_set(ed, rb, CAT_W, PAL_Y, FLY_W-1, WIN_H-PAL_Y); + float oy = PAL_Y - ed->fly_scroll; + for (int i = 0; i < ed->fly_n; i++) { + FlyItem* it = &ed->fly_items[i]; + float iy = it->y + oy; + if (iy + it->h < PAL_Y || iy > WIN_H) continue; + switch (it->kind) { + case FI_HEADER: + rb_text_c(rb, CAT_W + FLY_PAD, iy + it->h*0.55f, ed->cats[it->cat].name, COL_TEXT, 14); + break; + case FI_BUTTON: + rb_fill_rrect(rb, CAT_W + FLY_PAD, iy+4, FLY_BTN_W, 30, 6, COL_BORDER); + rb_fill_rrect(rb, CAT_W + FLY_PAD + 1, iy+5, FLY_BTN_W-2, 28, 5, COL_PANEL); + rb_text_c(rb, CAT_W + FLY_PAD + (FLY_BTN_W - tw("Criar um Bloco", FS_UI))*0.5f, + iy + 19, "Criar um Bloco", COL_TEXT, FS_UI); + break; + case FI_BLOCK: + render_block(ed, rb, &ed->fly, it->bi, CAT_W, oy); + break; + } + } + clip_clear(ed, rb); +} + +static void render_snap(Ed* ed, TinyBlocks_RenderableBlock* rb, float ox, float oy) { + if (ed->state != ES_DRAG || ed->snap_kind == SN_NONE) return; + Tab* T = &CT; + EdBlock* d = &T->ws[ed->drag_bi]; + EdBlock* t = &T->ws[ed->snap_bi]; + if (ed->snap_kind == SN_ARG) { + int s = ed->snap_idx; + float sx = t->ax + ox + t->slot_x[s], sy = t->ay + oy + t->slot_y[s]; + rb_stroke_rect(rb, sx-3, sy-3, t->slot_w[s]+6, t->slot_h[s]+6, 1.f, COLA(0,0,0,70)); + rb_stroke_rect(rb, sx-2, sy-2, t->slot_w[s]+4, t->slot_h[s]+4, 2.f, COL_WHITE); + return; + } + float gh = chain_h(T, ed->drag_bi), gx = t->ax, gy; + if (ed->snap_kind == SN_NEXT) gy = t->ay + t->h; + else if (ed->snap_kind == SN_SUB) { gx = t->ax + ARM_W; gy = t->ay + t->sub_y[ed->snap_idx]; } + else gy = t->ay - gh; + rb_fill_rrect(rb, gx + ox, gy + oy, d->w, gh, 4, COLA(0,0,0,45)); +} + +static void render_workspace(Ed* ed, TinyBlocks_RenderableBlock* rb) { + float ox = WS_X - CT.ws_sx, oy = WS_Y - CT.ws_sy; + rb_fill_rect(rb, WS_X, WS_Y, WS_W, WS_H, COL_WS_BG); + clip_set(ed, rb, WS_X, WS_Y, WS_W, WS_H); + + const float g = 40.f; + float offx = fmodf(CT.ws_sx, g); if (offx < 0) offx += g; + float offy = fmodf(CT.ws_sy, g); if (offy < 0) offy += g; + for (float gx = WS_X - offx; gx < WS_X + WS_W; gx += g) + for (float gy = WS_Y - offy; gy < WS_Y + WS_H; gy += g) + rb_fill_rect(rb, gx, gy, 2, 2, COL_GRID); + + if (CT.top_n == 0) { + const char* hint = CT.is_composite + ? "Arraste \"parâmetro\" e \"devolva\" de Meus Blocos para montar o bloco" + : "Arraste blocos da paleta para cá"; + rb_text_c(rb, WS_X + (WS_W - tw(hint, FS_UI))*0.5f, WS_Y + WS_H*0.45f, hint, COL_TEXT_DIM, FS_UI); + } + + for (int i = 0; i < CT.top_n; i++) { + if (ed->state == ES_DRAG && CT.top[i] == ed->drag_bi) continue; + render_chain(ed, rb, &CT, CT.top[i], ox, oy); + } + render_snap(ed, rb, ox, oy); + + if (ed->bubble_bi >= 0 && CT.ws[ed->bubble_bi].used) { + EdBlock* b = &CT.ws[ed->bubble_bi]; + float w = tw(ed->bubble_text, FS) + 20; + float bx = b->ax + ox + 8, by = b->ay + oy - 32; + rb_fill_rrect(rb, bx, by, w, 26, 8, COL_BORDER); + rb_fill_rrect(rb, bx+1, by+1, w-2, 24, 7, COL_WHITE); + rb_fill_rect(rb, bx + 12, by + 25, 8, 4, COL_WHITE); + rb_text_c(rb, bx + 10, by + 13, ed->bubble_text, COL_TEXT, FS); + } + clip_clear(ed, rb); +} + +/* ── Painel de bloco composto (canto superior direito do workspace) ───── */ +#define CP_W 440 +#define CP_H 40 +static void comp_panel_pos(Ed* ed, float* px, float* py) { + *px = WS_X + WS_W - CP_W - 10; + *py = WS_Y + 10; +} + +static void render_comp_panel(Ed* ed, TinyBlocks_RenderableBlock* rb) { + if (!CT.is_composite) return; + float px, py; comp_panel_pos(ed, &px, &py); + rb_fill_rrect(rb, px, py, CP_W, CP_H, 8, COL_BORDER); + rb_fill_rrect(rb, px+1, py+1, CP_W-2, CP_H-2, 7, COL_PANEL); + rb_text_c(rb, px+10, py+CP_H*0.5f, "Nome:", COL_TEXT, FS_UI); + + rb_fill_rrect(rb, px+56, py+6, 140, 28, 5, ed->comp_name_active ? COL_MENU : COL_BORDER); + rb_fill_rrect(rb, px+57, py+7, 138, 26, 4, COL_WHITE); + bool empty = !ed->comp_name_buf[0]; + rb_text_c(rb, px+64, py+CP_H*0.5f, empty ? "nome do bloco" : ed->comp_name_buf, + empty ? COL_TEXT_DIM : COL_TEXT, FS_UI); + if (ed->comp_name_active) + rb_fill_rect(rb, px+65 + tw(ed->comp_name_buf, FS_UI), py+12, 1.5f, 16, COL_TEXT); + + for (int ci = 0; ci < USER_COLOR_COUNT; ci++) { + float sx = px + 206 + ci*20; + if (CT.color_idx == ci) rb_fill_rrect(rb, sx-2, py+10, 20, 20, 5, COL_TEXT); + rb_fill_rrect(rb, sx, py+12, 16, 16, 4, s_user_colors[ci]); + } + float bx = px + 206 + USER_COLOR_COUNT*20 + 4; + rb_fill_rrect(rb, bx, py+6, 64, 28, 6, s_user_colors[CT.color_idx]); + rb_text_c(rb, bx + (64 - tw("Salvar", FS_UI))*0.5f, py+CP_H*0.5f, "Salvar", COL_WHITE, FS_UI); +} + +/* Altura da área do palco no painel (4:3 embutido; faixa curta se destacado) */ +static float stage_panel_h(Ed* ed) { + if (!ed->stage) return 0.f; + return ed->stage_win ? 40.f : (STAGE_W - 16) * 0.75f; +} + +static void render_stage(Ed* ed, TinyBlocks_RenderableBlock* rb) { + float sx = WIN_W - STAGE_W, sy = MENU_H; + rb_fill_rect(rb, sx, sy, STAGE_W, WIN_H - sy, COL_UI_BG); + + /* Bandeira verde */ + float fx = sx + 10, fy = sy + 6; + if (ed->flag_hover) rb_fill_rrect(rb, fx, fy, 40, 32, 6, COL_HOVER); + rb_fill_rect(rb, fx+13, fy+6, 2, 21, COL_FLAG_DARK); + rb_fill_rrect(rb, fx+15, fy+6, 15, 11, 2, COL_FLAG); + /* Parar */ + float tx = sx + 56; + if (ed->stop_hover) rb_fill_rrect(rb, tx, fy, 40, 32, 6, COL_HOVER); + draw_hex(rb, tx+10, fy+6, 20, 20, COL_STOP_DARK); + rb_fill_circle(rb, tx+20, fy+16, 9, COL_STOP); + rb_text_c(rb, sx + 110, sy + STAGE_BAR_H*0.5f, "Palco", COL_TEXT_DIM, FS_UI); + /* Destacar / recolher o palco */ + if (ed->stage) { + float dx = sx + STAGE_W - 50; + if (ed->detach_hover) rb_fill_rrect(rb, dx, fy, 40, 32, 6, COL_HOVER); + if (ed->stage_win) { + rb_stroke_rect(rb, dx+9, fy+7, 22, 18, 1.5f, COL_TEXT); + rb_fill_rect(rb, dx+12, fy+15, 10, 7, COL_TEXT); + } else { + rb_stroke_rect(rb, dx+9, fy+11, 15, 13, 1.5f, COL_TEXT); + rb_stroke_rect(rb, dx+16, fy+6, 15, 13, 1.5f, COL_TEXT); + } + } + + float bx = sx + 8, by = sy + STAGE_BAR_H, bw = STAGE_W - 16; + float ph = stage_panel_h(ed); + if (ph > 0) { + rb_fill_rrect(rb, bx, by, bw, ph, 8, COL_BORDER); + if (ed->stage_win) { + rb_fill_rrect(rb, bx+1, by+1, bw-2, ph-2, 7, COL_PANEL); + const char* msg = "Palco aberto em outra janela"; + rb_text_c(rb, bx + (bw - tw(msg, FS_UI))*0.5f, by + ph*0.5f, msg, COL_TEXT_DIM, FS_UI); + } else { + TinyBlocks_RenderableBlock* sub = NULL; + tb_stage_set_view(ed->stage, bw-2, ph-2); + clip_set(ed, rb, bx+1, by+1, bw-2, ph-2); + if (ed->stage->type->on_draw(ed->stage, ed->rt, &sub) && sub) { + tb_draw_merge_offset(rb, sub, bx+1, by+1); + tb_renderable_release(sub); + } + clip_clear(ed, rb); + } + by += ph + 8; + } + + float bh = WIN_H - by - 8; + rb_fill_rrect(rb, bx, by, bw, bh, 8, COL_BORDER); + rb_fill_rrect(rb, bx+1, by+1, bw-2, bh-2, 7, COL_PANEL); + clip_set(ed, rb, bx+2, by+2, bw-4, bh-4); + + /* Monitores de variáveis */ + float y = by + 10; + for (int v = 0; v < ed->var_n && y < by + bh*0.5f; v++) { + char val[64]; value_to_str(&ed->var_val[v], val, sizeof(val)); + float nw = tw(ed->var_name[v], FS), vw = fmaxf(30, tw(val, FS) + 14); + float mw = nw + vw + 26; + rb_fill_rrect(rb, bx+10, y, mw, 26, 5, COL_MON_BORDER); + rb_fill_rrect(rb, bx+11, y+1, mw-2, 24, 4, COL_MON_BG); + rb_text_c(rb, bx+18, y+13, ed->var_name[v], COL_TEXT, FS); + rb_fill_rrect(rb, bx+18+nw+6, y+4, vw, 18, 4, COL_VAR); + rb_text_c(rb, bx+18+nw+6 + (vw - tw(val, FS))*0.5f, y+13, val, COL_WHITE, FS); + y += 32; + } + + /* Console: mostra as últimas linhas que cabem */ + const float lh = FS_SM + 5; + int total = text_lines(ed->stage_buf); + int fit = (int)((by + bh - 8 - y) / lh); + int skip = total > fit ? total - fit : 0; + const char* p = ed->stage_buf; + for (int l = 0; *p; l++) { + size_t n = strcspn(p, "\n"); + if (l >= skip) { + char line[128]; + size_t m = n < sizeof(line) - 1 ? n : sizeof(line) - 1; + memcpy(line, p, m); line[m] = 0; + bool err = strncmp(line, "[ERRO]", 6) == 0 || strncmp(line, "[AVISO]", 7) == 0; + rb_text_c(rb, bx + 12, y + lh*0.5f, line, err ? COL_ERR_TEXT : COL_TEXT, FS_SM); + y += lh; + } + p += n; + if (*p == '\n') p++; + } + clip_clear(ed, rb); +} + +#define CTX_ITEM_H 30 +#define CTX_W 190 +static const char* ctx_label(int id) { + switch (id) { + case CM_DUPLICATE: return "Duplicar"; + case CM_DELETE: return "Apagar bloco"; + case CM_EDIT_DEF: return "Editar definição"; + case CM_CLEANUP: return "Organizar blocos"; + case CM_NEW_COMPOSITE: return "Criar um bloco"; + default: return ""; + } +} + +static void ctx_pos(Ed* ed, float* x, float* y) { + float mh = ed->ctx_n*CTX_ITEM_H + 8; + *x = ed->ctx_menu_x; *y = ed->ctx_menu_y; + if (*x + CTX_W > WIN_W) *x = WIN_W - CTX_W; + if (*y + mh > WIN_H) *y = WIN_H - mh; +} + +static int ctx_hit(Ed* ed, float mx, float my) { + float x, y; ctx_pos(ed, &x, &y); + if (!in_rect(mx, my, x, y+4, CTX_W, ed->ctx_n*CTX_ITEM_H)) return -1; + return (int)((my - y - 4) / CTX_ITEM_H); +} + +static void render_ctx_menu(Ed* ed, TinyBlocks_RenderableBlock* rb) { + if (!ed->ctx_menu_open) return; + float x, y; ctx_pos(ed, &x, &y); + float mh = ed->ctx_n*CTX_ITEM_H + 8; + rb_fill_rrect(rb, x+2, y+3, CTX_W, mh, 6, COLA(0,0,0,40)); + rb_fill_rrect(rb, x, y, CTX_W, mh, 6, COL_BORDER); + rb_fill_rrect(rb, x+1, y+1, CTX_W-2, mh-2, 5, COL_PANEL); + for (int i = 0; i < ed->ctx_n; i++) { + float iy = y + 4 + i*CTX_ITEM_H; + if (ed->ctx_menu_hover == i) rb_fill_rect(rb, x+1, iy, CTX_W-2, CTX_ITEM_H, COL_UI_BG); + rb_text_c(rb, x+14, iy + CTX_ITEM_H*0.5f, ctx_label(ed->ctx_items[i]), COL_TEXT, FS_UI); + } +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Arrastar e encaixar + * ══════════════════════════════════════════════════════════════════════════ */ +static void start_drag(Ed* ed) { + Tab* T = &CT; + int bi = ed->press_bi; + EdBlock* b = &T->ws[bi]; + float sx = b->ax + WS_X - T->ws_sx, sy = b->ay + WS_Y - T->ws_sy; + float ax = b->ax, ay = b->ay; + detach(T, bi); + top_add(T, bi); + b->x = ax; b->y = ay; + ed->drag_bi = bi; + ed->drag_ox = ed->press_mx - sx; + ed->drag_oy = ed->press_my - sy; + mark_drag(T, bi, true); + ed->state = ES_DRAG; + ed->snap_kind = SN_NONE; + ed->bubble_bi = -1; +} + +static void consider(Ed* ed, float* best, SnapKind k, int bi, int idx, float x0, float y0, float x1, float y1) { + float d = hypotf(x1 - x0, y1 - y0); + if (d >= *best) return; + *best = d; + ed->snap_kind = k; ed->snap_bi = bi; ed->snap_idx = idx; +} + +static void compute_snap(Ed* ed) { + Tab* T = &CT; + EdBlock* d = &T->ws[ed->drag_bi]; + Shape ds = shape_of(d->type); + float best = SNAP_R; + ed->snap_kind = SN_NONE; + + if (shape_is_value(ds)) { + /* Repórter: o lado esquerdo procura um campo de entrada */ + float px = d->x, py = d->y + d->h*0.5f; + for (int i = 0; i < MAX_WS; i++) { + EdBlock* B = &T->ws[i]; + if (!B->used || B->dragging || !B->type) continue; + for (int s = 0; s < input_count(B->type); s++) { + if (ds == SH_REPORTER && slot_is_bool(B->type, s)) continue; + consider(ed, &best, SN_ARG, i, s, px, py, + B->ax + B->slot_x[s], B->ay + B->slot_y[s] + B->slot_h[s]*0.5f); + } + } + return; + } + + float dh = chain_h(T, ed->drag_bi); + for (int i = 0; i < MAX_WS; i++) { + EdBlock* B = &T->ws[i]; + if (!B->used || B->dragging) continue; + Shape bs = shape_of(B->type); + if (shape_is_value(bs)) continue; + if (ds != SH_HAT) { + consider(ed, &best, SN_NEXT, i, 0, d->x, d->y, B->ax, B->ay + B->h); + int mouths = bs == SH_C1 ? 1 : bs == SH_C2 ? 2 : 0; + for (int k = 0; k < mouths; k++) + consider(ed, &best, SN_SUB, i, k, d->x, d->y, B->ax + ARM_W, B->ay + B->sub_y[k]); + } + if (B->parent < 0 && bs != SH_HAT) + consider(ed, &best, SN_ABOVE, i, 0, d->x, d->y + dh, B->ax, B->ay); + } +} + +static void apply_snap(Ed* ed) { + Tab* T = &CT; + int bi = ed->drag_bi, t = ed->snap_bi; + switch (ed->snap_kind) { + case SN_NEXT: attach_insert(T, t, REL_NEXT, bi); break; + case SN_SUB: attach_insert(T, t, REL_SUB0 + ed->snap_idx, bi); break; + case SN_ABOVE: attach_above(T, t, bi); break; + case SN_ARG: attach_arg(T, t, ed->snap_idx, bi); break; + default: break; + } +} + +static void cleanup_ws(Ed* ed) { + Tab* T = &CT; + layout_tab(T); + float y = 24 + T->ws_sy; + for (int i = 0; i < T->top_n; i++) { + EdBlock* b = &T->ws[T->top[i]]; + b->x = 24 + T->ws_sx; + b->y = y; + y += chain_h(T, T->top[i]) + 28; + } +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Edição de texto + * ══════════════════════════════════════════════════════════════════════════ */ +static void utf8_pop(char* s) { + size_t n = strlen(s); + while (n > 0) { + n--; + if (((unsigned char)s[n] & 0xC0) != 0x80) break; + } + s[n] = 0; +} + +static void append_text(char* dst, size_t cap, const char* add) { + size_t n = strlen(dst), a = strlen(add); + if (n + a < cap) memcpy(dst + n, add, a + 1); +} + +static char* edit_target(Ed* ed, size_t* cap) { + EdBlock* b = &CT.ws[ed->edit_bi]; + if (is_lit_text(b->type) && ed->edit_in == 0) { *cap = LIT_TEXT_CAP; return b->lit_text; } + *cap = sizeof(b->in_text[0]); + return b->in_text[ed->edit_in]; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Input + * ══════════════════════════════════════════════════════════════════════════ */ +static TinyBlocks_Block* editor_events_block(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + return v.kind == TB_VALUE_BLOCK ? v.as.block : NULL; +} +static int64_t ev_int(TinyBlocks_Block* evb, int idx) { + if (!evb || idx<0 || (uint32_t)idx>=evb->output_count) return 0; + TinyBlocks_Value* v=&evb->outputs[idx]; + return v->kind==TB_VALUE_INTEGER ? v->as.integer : 0; +} +static double ev_real(TinyBlocks_Block* evb, int idx) { + if (!evb || idx<0 || (uint32_t)idx>=evb->output_count) return 0.0; + TinyBlocks_Value* v=&evb->outputs[idx]; + return v->kind==TB_VALUE_REAL ? v->as.real : 0.0; +} +static const char* ev_text(TinyBlocks_Block* evb, int idx) { + if (!evb || idx<0 || (uint32_t)idx>=evb->output_count) return ""; + TinyBlocks_Value* v=&evb->outputs[idx]; + return (v->kind==TB_VALUE_TEXT && v->as.text) ? v->as.text : ""; +} + +static bool hit_flag(Ed* ed, float mx, float my) { return in_rect(mx, my, WIN_W-STAGE_W+10, MENU_H+6, 40, 32); } +static bool hit_stop(Ed* ed, float mx, float my) { return in_rect(mx, my, WIN_W-STAGE_W+56, MENU_H+6, 40, 32); } +static bool hit_detach(Ed* ed, float mx, float my) { + return ed->stage && in_rect(mx, my, WIN_W-50, MENU_H+6, 40, 32); +} +static bool hit_lib_btn(float mx, float my) { return in_rect(mx, my, LIB_BTN_X, 0, LIB_BTN_W, MENU_H); } + +static int hit_fly(Ed* ed, float mx, float my) { + float fx = mx - CAT_W, fy = my - PAL_Y + ed->fly_scroll; + for (int i = 0; i < ed->fly_n; i++) { + FlyItem* it = &ed->fly_items[i]; + if (it->kind == FI_BUTTON && in_rect(fx, fy, FLY_PAD, it->y+4, FLY_BTN_W, 30)) return i; + if (it->kind == FI_BLOCK && hit_one(&ed->fly, it->bi, fx, fy) >= 0) return i; + } + return -1; +} + +static void spawn_from_fly(Ed* ed, int item, float mx, float my) { + Tab* F = &ed->fly; + int src = ed->fly_items[item].bi; + int ni = copy_tree(F, src, &CT, false); + if (ni < 0) { + snprintf(ed->hot_status, sizeof(ed->hot_status), "Limite de %d blocos por aba atingido", MAX_WS); + ed->hot_status_ok = false; + return; + } + top_add(&CT, ni); + float sx = F->ws[src].ax + CAT_W, sy = F->ws[src].ay + PAL_Y - ed->fly_scroll; + CT.ws[ni].x = sx - WS_X + CT.ws_sx; + CT.ws[ni].y = sy - WS_Y + CT.ws_sy; + ed->drag_bi = ni; + ed->drag_ox = mx - sx; ed->drag_oy = my - sy; + mark_drag(&CT, ni, true); + ed->state = ES_DRAG; + ed->snap_kind = SN_NONE; + layout_tab(&CT); +} + +/* Recolhe o palco para o painel (fecha a janela própria, se houver) */ +static void stage_attach(Ed* ed) { + if (ed->stage) tb_block_set_default(ed->stage, 0, tb_value_none()); + if (ed->stage_win) { tb_block_destroy(ed->stage_win, ed->rt); ed->stage_win = NULL; } + if (ed->stage_in) { tb_block_destroy(ed->stage_in, ed->rt); ed->stage_in = NULL; } +} + +/* Destaca o palco: ele vira a cena de um Graphics.Window próprio */ +static void stage_detach(Ed* ed) { + TinyBlocks_TypeBlock* t_win = tb_type_block_find(ed->rt, "Graphics.Window"); + TinyBlocks_TypeBlock* t_in = tb_type_block_find(ed->rt, "Graphics.Input"); + if (!ed->stage || ed->stage_win || !t_win || !t_in) return; + ed->stage_in = tb_block_create(ed->rt, t_in); + ed->stage_win = tb_block_create(ed->rt, t_win); + if (ed->stage_in && ed->stage_win) { + TinyBlocks_Value title = tb_value_text("Palco — TinyBlocks"); + tb_block_set_default(ed->stage_win, 0, title); /* set_default clona */ + tb_value_free(&title); + tb_block_set_default(ed->stage_win, 1, tb_value_integer(480)); + tb_block_set_default(ed->stage_win, 2, tb_value_integer(360)); + tb_block_set_default(ed->stage_win, 3, tb_value_block(ed->stage)); + tb_block_set_default(ed->stage_win, 4, tb_value_block(ed->stage_in)); + tb_block_set_default(ed->stage_win, 5, tb_value_integer(0)); /* fechar não encerra o editor */ + tb_block_set_default(ed->stage, 0, tb_value_block(ed->stage_in)); + tb_block_eval(ed->stage_win, ed->rt); + } + if (!tb_graphics_window_is_open(ed->stage_win)) { + stage_attach(ed); + snprintf(ed->hot_status, sizeof(ed->hot_status), "Não foi possível abrir a janela do palco"); + ed->hot_status_ok = false; + } +} + +static void ctx_exec(Ed* ed, int id) { + Tab* T = &CT; + int bi = ed->ctx_menu_bi; + switch (id) { + case CM_DUPLICATE: { + int ni = copy_tree(T, bi, T, true); + if (ni >= 0) { top_add(T, ni); T->ws[ni].x = T->ws[bi].ax + 24; T->ws[ni].y = T->ws[bi].ay + 24; } + break; + } + case CM_DELETE: delete_heal(ed, T, bi); break; + case CM_EDIT_DEF: if (T->ws[bi].type) open_def(ed, T->ws[bi].type->type_name + 5); break; + case CM_CLEANUP: cleanup_ws(ed); break; + case CM_NEW_COMPOSITE: new_composite_tab(ed); break; + default: break; + } +} + +static void on_lmb_down(Ed* ed, float mx, float my) { + if (ed->ctx_menu_open) { + int it = ctx_hit(ed, mx, my); + ed->ctx_menu_open = false; + if (it >= 0 && it < ed->ctx_n) ctx_exec(ed, ed->ctx_items[it]); + return; + } + ed->editing = false; + ed->bubble_bi = -1; + bool was_naming = ed->comp_name_active; + ed->comp_name_active = false; + + /* Barra de menu */ + if (my < MENU_H) { + if (hit_lib_btn(mx, my)) { + ed->path_input_active = true; + ed->path_input_buf[0] = 0; ed->path_input_len = 0; + } else if (mx < LIB_BTN_X + LIB_BTN_W) { + ed->path_input_active = false; + } + return; + } + ed->path_input_active = false; + + /* Palco */ + if (mx >= WIN_W - STAGE_W) { + if (hit_flag(ed, mx, my)) run_flag(ed); + else if (hit_stop(ed, mx, my)) { run_reset(ed); ed->stage_buf[0] = 0; } + else if (hit_detach(ed, mx, my)) { if (ed->stage_win) stage_attach(ed); else stage_detach(ed); } + return; + } + + /* Abas */ + if (my < MENU_H + TAB_H) { + for (int i = 0; i < ed->tab_n; i++) { + float tx = 8 + i*TAB_W; + if (!in_rect(mx, my, tx, MENU_H, TAB_W-4, TAB_H)) continue; + if (ed->tab_n > 1 && mx >= tx + TAB_W - 28) tab_close(ed, i); + else tab_select(ed, i); + return; + } + float px = 8 + ed->tab_n*TAB_W; + if (in_rect(mx, my, px, MENU_H, PLUS_W, TAB_H)) tab_new(ed, NULL, false); + return; + } + + /* Painel do bloco composto */ + if (CT.is_composite) { + float px, py; comp_panel_pos(ed, &px, &py); + if (in_rect(mx, my, px, py, CP_W, CP_H)) { + if (in_rect(mx, my, px+56, py+6, 140, 28)) { ed->comp_name_active = true; return; } + for (int ci = 0; ci < USER_COLOR_COUNT; ci++) + if (in_rect(mx, my, px+206+ci*20, py+10, 18, 20)) { CT.color_idx = ci; return; } + if (in_rect(mx, my, px+206+USER_COLOR_COUNT*20+4, py+6, 64, 28)) save_composite_from_tab(ed); + ed->comp_name_active = was_naming; + return; + } + } + + /* Categorias */ + if (mx < CAT_W) { + int c = (int)((my - PAL_Y) / cat_item_h(ed)); + if (c >= 0 && c < ed->cat_n) { + ed->fly_scroll = ed->cats[c].fly_y - 4; + if (ed->fly_scroll > fly_max_scroll(ed)) ed->fly_scroll = fly_max_scroll(ed); + if (ed->fly_scroll < 0) ed->fly_scroll = 0; + } + return; + } + + /* Flyout */ + if (mx < PALETTE_W) { + int it = hit_fly(ed, mx, my); + if (it < 0) return; + if (ed->fly_items[it].kind == FI_BUTTON) new_composite_tab(ed); + else spawn_from_fly(ed, it, mx, my); + return; + } + + /* Workspace */ + float wx = mx - WS_X + CT.ws_sx, wy = my - WS_Y + CT.ws_sy; + int bi = hit_ws(&CT, wx, wy); + if (bi < 0) { + ed->state = ES_PAN; + ed->pan_mx = mx; ed->pan_my = my; + ed->pan_sx = CT.ws_sx; ed->pan_sy = CT.ws_sy; + return; + } + int s = hit_slot(&CT, bi, wx, wy); + if (s >= 0 && !slot_is_bool(CT.ws[bi].type, s)) { + ed->editing = true; ed->edit_bi = bi; ed->edit_in = s; + return; + } + top_add(&CT, stack_root(&CT, bi)); + ed->state = ES_PRESS; + ed->press_bi = bi; + ed->press_mx = mx; ed->press_my = my; +} + +static void on_lmb_up(Ed* ed, float mx, float my) { + (void)my; + if (ed->state == ES_DRAG && ed->drag_bi >= 0) { + mark_drag(&CT, ed->drag_bi, false); + if (mx < PALETTE_W) free_tree(ed, &CT, ed->drag_bi); /* solto na paleta = apagar */ + else apply_snap(ed); + } else if (ed->state == ES_PRESS) { + ed->state = ES_IDLE; + run_click(ed, ed->press_bi); + } + ed->state = ES_IDLE; + ed->drag_bi = -1; + ed->snap_kind = SN_NONE; +} + +static void on_rmb_down(Ed* ed, float mx, float my) { + if (ed->ctx_menu_open) { ed->ctx_menu_open = false; return; } + if (ed->state != ES_IDLE) return; + if (my < WS_Y || mx < WS_X || mx >= WIN_W - STAGE_W) return; + int bi = hit_ws(&CT, mx - WS_X + CT.ws_sx, my - WS_Y + CT.ws_sy); + ed->ctx_n = 0; + if (bi >= 0) { + ed->ctx_items[ed->ctx_n++] = CM_DUPLICATE; + ed->ctx_items[ed->ctx_n++] = CM_DELETE; + const TinyBlocks_TypeBlock* t = CT.ws[bi].type; + if (t && strncmp(t->type_name, "User.", 5) == 0) ed->ctx_items[ed->ctx_n++] = CM_EDIT_DEF; + } else { + ed->ctx_items[ed->ctx_n++] = CM_CLEANUP; + ed->ctx_items[ed->ctx_n++] = CM_NEW_COMPOSITE; + } + ed->ctx_menu_open = true; + ed->ctx_menu_bi = bi; + ed->ctx_menu_x = (int)mx; ed->ctx_menu_y = (int)my; + ed->ctx_menu_hover = -1; +} + +static void on_key(Ed* ed, int sc, bool ctrl) { + bool enter = sc == TB_KEY_RETURN; + if (ed->ctx_menu_open) { if (sc == TB_KEY_ESCAPE) ed->ctx_menu_open = false; return; } + + if (ed->path_input_active) { + if (sc == TB_KEY_ESCAPE) ed->path_input_active = false; + else if (enter) { + if (ed->path_input_buf[0]) hotlib_load(ed, ed->path_input_buf); + ed->path_input_active = false; + } else if (sc == TB_KEY_BACKSPACE) { + utf8_pop(ed->path_input_buf); + ed->path_input_len = (int)strlen(ed->path_input_buf); + } + return; + } + if (ed->comp_name_active) { + if (sc == TB_KEY_ESCAPE) ed->comp_name_active = false; + else if (enter) { ed->comp_name_active = false; save_composite_from_tab(ed); } + else if (sc == TB_KEY_BACKSPACE) { + utf8_pop(ed->comp_name_buf); + ed->comp_name_len = (int)strlen(ed->comp_name_buf); + } + return; + } + if (ed->editing) { + size_t cap; char* t = edit_target(ed, &cap); + bool multi = is_lit_text(CT.ws[ed->edit_bi].type); + if (sc == TB_KEY_ESCAPE || (enter && !multi)) ed->editing = false; + else if (enter) append_text(t, cap, "\n"); + else if (sc == TB_KEY_BACKSPACE) utf8_pop(t); + return; + } + if (ctrl && sc == (TB_KEY_A + ('o' - 'a'))) { + ed->path_input_active = true; + ed->path_input_buf[0] = 0; ed->path_input_len = 0; + return; + } + if (sc == TB_KEY_DELETE && ed->state == ES_IDLE) { + float mx = ed->mouse_x, my = ed->mouse_y; + if (mx >= WS_X && mx < WIN_W - STAGE_W && my >= WS_Y) { + int bi = hit_ws(&CT, mx - WS_X + CT.ws_sx, my - WS_Y + CT.ws_sy); + if (bi >= 0) delete_heal(ed, &CT, bi); + } + return; + } + if (sc == TB_KEY_F5) run_flag(ed); +} + +static void on_text(Ed* ed, const char* typed) { + if (ed->path_input_active) { + append_text(ed->path_input_buf, sizeof(ed->path_input_buf), typed); + ed->path_input_len = (int)strlen(ed->path_input_buf); + } else if (ed->comp_name_active) { + append_text(ed->comp_name_buf, sizeof(ed->comp_name_buf), typed); + ed->comp_name_len = (int)strlen(ed->comp_name_buf); + } else if (ed->editing) { + size_t cap; char* t = edit_target(ed, &cap); + append_text(t, cap, typed); + } +} + +/* ══════════════════════════════════════════════════════════════════════════ + * editor_eval — lê um snapshot de Graphics.Input por frame e atualiza o estado + * ══════════════════════════════════════════════════════════════════════════ */ +static void editor_eval(TinyBlocks_Block* self, TinyBlocks* rt) { + Ed* ed = *(Ed**)self->userdata; + self->dirty = false; + if (!ed) return; + g_active_ed = ed; + + TinyBlocks_Block* evb = editor_events_block(self, rt); + if (!evb) return; + + int ww = (int)ev_int(evb, GFX_IN_WIN_W); + int wh = (int)ev_int(evb, GFX_IN_WIN_H); + if (ww > 0) ed->win_w = ww; + if (wh > 0) ed->win_h = wh; + + float mx = (float)ev_real(evb, GFX_IN_MOUSE_X); + float my = (float)ev_real(evb, GFX_IN_MOUSE_Y); + ed->mouse_x = mx; ed->mouse_y = my; + layout_tab(&CT); + + /* ── Hover ──────────────────────────────────────────────────────── */ + ed->flag_hover = hit_flag(ed, mx, my); + ed->stop_hover = hit_stop(ed, mx, my); + ed->lib_hover = hit_lib_btn(mx, my); + ed->detach_hover = hit_detach(ed, mx, my); + + /* Janela do palco fechada pelo usuário: o palco volta para o painel */ + if (ed->stage_win && !tb_graphics_window_is_open(ed->stage_win)) stage_attach(ed); + ed->ctx_menu_hover = ed->ctx_menu_open ? ctx_hit(ed, mx, my) : -1; + + /* ── Movimento ──────────────────────────────────────────────────── */ + if (ed->state == ES_PRESS && fabsf(mx - ed->press_mx) + fabsf(my - ed->press_my) > 4.f) + start_drag(ed); + if (ed->state == ES_DRAG && ed->drag_bi >= 0) { + EdBlock* b = &CT.ws[ed->drag_bi]; + b->x = mx - ed->drag_ox - WS_X + CT.ws_sx; + b->y = my - ed->drag_oy - WS_Y + CT.ws_sy; + layout_tab(&CT); + compute_snap(ed); + } + if (ed->state == ES_PAN) { + CT.ws_sx = ed->pan_sx - (mx - ed->pan_mx); + CT.ws_sy = ed->pan_sy - (my - ed->pan_my); + } + + /* ── Scroll ─────────────────────────────────────────────────────── */ + double sdx = ev_real(evb, GFX_IN_SCROLL_DX); + double sdy = ev_real(evb, GFX_IN_SCROLL_DY); + if (sdx != 0.0 || sdy != 0.0) { + if (mx >= WS_X && mx < WIN_W - STAGE_W && my >= WS_Y) { + CT.ws_sx -= (float)sdx * 40.f; + CT.ws_sy -= (float)sdy * 40.f; + } else if (mx < PALETTE_W && my >= PAL_Y) { + ed->fly_scroll -= (float)sdy * 48.f; + if (ed->fly_scroll > fly_max_scroll(ed)) ed->fly_scroll = fly_max_scroll(ed); + if (ed->fly_scroll < 0) ed->fly_scroll = 0; + } + } + + /* ── Drop de arquivo ────────────────────────────────────────────── */ + const char* dropped = ev_text(evb, GFX_IN_DROP_FILE); + if (dropped[0]) { + size_t len = strlen(dropped); + if (len > 3 && strcmp(dropped + len - 3, ".so") == 0) hotlib_load(ed, dropped); + } + + if (ev_int(evb, GFX_IN_MOUSE_L_DOWN)) on_lmb_down(ed, mx, my); + if (ev_int(evb, GFX_IN_MOUSE_R_DOWN)) on_rmb_down(ed, mx, my); + if (ev_int(evb, GFX_IN_MOUSE_L_UP)) on_lmb_up(ed, mx, my); + + int sc = (int)ev_int(evb, GFX_IN_KEY); + if (sc != 0) on_key(ed, sc, (ev_int(evb, GFX_IN_KEY_MOD) & TB_MOD_CTRL) != 0); + + const char* typed = ev_text(evb, GFX_IN_TEXT); + if (typed[0]) on_text(ed, typed); + + /* Verifica mtime das libs vigiadas a cada ~60 frames (~1s) */ + if (++ed->hot_check_frame >= 60) { + ed->hot_check_frame = 0; + hotlib_check(ed); + } +} + +/* ══════════════════════════════════════════════════════════════════════════ + * editor_on_draw — compõe o frame inteiro em um RenderableBlock + * ══════════════════════════════════════════════════════════════════════════ */ +static bool editor_on_draw(TinyBlocks_Block* self, TinyBlocks* rt, + TinyBlocks_RenderableBlock** dst) { + (void)rt; + Ed* ed = *(Ed**)self->userdata; + if (!ed) return false; + TinyBlocks_RenderableBlock* rb = tb_renderable_acquire(); + if (!rb) return false; + + layout_tab(&CT); + tb_draw_clear(rb, COL_UI_BG.r, COL_UI_BG.g, COL_UI_BG.b, 1.f); + + render_workspace(ed, rb); + render_comp_panel(ed, rb); + render_flyout(ed, rb); + render_categories(ed, rb); + render_stage(ed, rb); + render_tab_bar(ed, rb); + render_menu(ed, rb); + + /* A pilha arrastada fica por cima de tudo (pode passar sobre a paleta) */ + if (ed->state == ES_DRAG && ed->drag_bi >= 0) + render_chain(ed, rb, &CT, ed->drag_bi, WS_X - CT.ws_sx, WS_Y - CT.ws_sy); + + render_ctx_menu(ed, rb); + + *dst = rb; + return true; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Ciclo de vida da instância + * ══════════════════════════════════════════════════════════════════════════ */ +static int seed_blk(Ed* ed, const char* tn, const char* a0, const char* a1) { + TinyBlocks_TypeBlock* t = tb_type_block_find(ed->rt, tn); + int bi = t ? blk_new(&CT, t) : -1; + if (bi < 0) return -1; + if (a0) strncpy(CT.ws[bi].in_text[0], a0, 63); + if (a1) strncpy(CT.ws[bi].in_text[1], a1, 63); + return bi; +} + +/* Script de exemplo no primeiro workspace */ +static void seed_example(Ed* ed) { + int hat = seed_blk(ed, "Events.WhenRun", NULL, NULL); + int set = seed_blk(ed, "Variables.Set", "x", "0"); + int rep = seed_blk(ed, "Control.Repeat", "5", NULL); + int chg = seed_blk(ed, "Variables.Change", "x", "1"); + int prt = seed_blk(ed, "IO.Print", "x vale", ""); + int get = seed_blk(ed, "Variables.Get", "x", NULL); + int all[] = { hat, set, rep, chg, prt, get }; + for (int i = 0; i < 6; i++) { + if (all[i] >= 0) continue; + for (int k = 0; k < 6; k++) if (all[k] >= 0) free_tree(ed, &CT, all[k]); + return; + } + Tab* T = &CT; + T->ws[hat].x = 40; T->ws[hat].y = 40; + top_add(T, hat); + blk_link(T, hat, REL_NEXT, set); + blk_link(T, set, REL_NEXT, rep); + blk_link(T, rep, REL_SUB0, chg); + blk_link(T, chg, REL_NEXT, prt); + blk_link(T, prt, REL_ARG0 + 1, get); +} + +static bool editor_instance_init(TinyBlocks_Block* self, TinyBlocks* rt) { + Ed* ed = (Ed*)calloc(1, sizeof(Ed)); + if (!ed) return false; + ed->rt = rt; + ed->win_w = WIN_W_DEFAULT; + ed->win_h = WIN_H_DEFAULT; + + ed->drag_bi = -1; + ed->press_bi = -1; + ed->edit_bi = -1; + ed->bubble_bi = -1; + ed->ctx_menu_bi = -1; + + ed->tab_n = 1; + ed->cur_tab = 0; + strcpy(ed->tabs[0].name, "Código"); + ed->tabs[0].comp_id = -1; + strcpy(ed->stage_buf, + "Clique na bandeira verde (ou F5) para executar.\n" + "Clique num bloco para executá-lo sozinho.\n"); + strcpy(ed->hot_status, "Ctrl+O ou arraste um .so para carregar uma library"); + ed->hot_status_ok = true; + + *(Ed**)self->userdata = ed; + g_active_ed = ed; + + TinyBlocks_TypeBlock* t_stage = tb_type_block_find(rt, "Editor.Stage"); + if (t_stage) ed->stage = tb_block_create(rt, t_stage); + + palette_rebuild(ed); + for (int i = 0; i < s_preload_n; i++) hotlib_load(ed, s_preload[i]); + s_preload_n = 0; + seed_example(ed); + return true; +} + +static void editor_instance_deinit(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + Ed* ed = *(Ed**)self->userdata; + if (!ed) return; + /* As instâncias em run_blocks (e o palco e sua janela) são TB_KIND_BLOCK + * registradas no runtime: a fase 1 do tinyblocks_deinit já as destrói — + * aqui só soltamos o que é do editor. */ + free(ed->run_blocks); + for (int v = 0; v < ed->var_n; v++) tb_value_free(&ed->var_val[v]); + for (int u = 0; u < ed->user_block_n; u++) free(ed->user_blocks[u].snap); + if (g_active_ed == ed) g_active_ed = NULL; + free(ed); + *(Ed**)self->userdata = NULL; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Registra a library + * ══════════════════════════════════════════════════════════════════════════ */ +static void reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name, + const TinyBlocks_SlotDesc* in, uint32_t ni, + const TinyBlocks_SlotDesc* out, uint32_t no, + void (*fn)(TinyBlocks_Block*, TinyBlocks*)) { + TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, out, no, fn); + if (t) tb_library_add(lib, &t->base); +} + +static bool editor_lib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + srand((unsigned)time(NULL)); + + static const TinyBlocks_SlotDesc lit_int_in[] = {{"value", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc lit_int_out[] = {{"out", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc lit_real_in[] = {{"value", TB_VALUE_REAL}}; + static const TinyBlocks_SlotDesc lit_real_out[]= {{"out", TB_VALUE_REAL}}; + static const TinyBlocks_SlotDesc lit_txt_in[] = {{"value", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc lit_txt_out[] = {{"out", TB_VALUE_TEXT}}; + reg(rt, lib, "Literal.Integer", lit_int_in, 1, lit_int_out, 1, eval_literal_int); + reg(rt, lib, "Literal.Real", lit_real_in, 1, lit_real_out, 1, eval_literal_real); + reg(rt, lib, "Literal.Text", lit_txt_in, 1, lit_txt_out, 1, eval_literal_text); + + /* Eventos e controle (a sequência é interpretada pelo editor) */ + static const TinyBlocks_SlotDesc times_in[] = {{"vezes", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc cond_in[] = {{"condição", TB_VALUE_INTEGER}}; + reg(rt, lib, "Events.WhenRun", NULL, 0, NULL, 0, eval_noop); + reg(rt, lib, "Control.Repeat", times_in, 1, NULL, 0, eval_noop); + reg(rt, lib, "Control.RepeatUntil", cond_in, 1, NULL, 0, eval_noop); + reg(rt, lib, "Control.If", cond_in, 1, NULL, 0, eval_noop); + reg(rt, lib, "Control.IfElse", cond_in, 1, NULL, 0, eval_noop); + + /* Operadores */ + static const TinyBlocks_SlotDesc any2[] = {{"a", TB_VALUE_NONE}, {"b", TB_VALUE_NONE}}; + static const TinyBlocks_SlotDesc bool2[] = {{"a", TB_VALUE_INTEGER}, {"b", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc bool_out[] = {{"resultado", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc rnd_in[] = {{"de", TB_VALUE_NONE}, {"até", TB_VALUE_NONE}}; + static const TinyBlocks_SlotDesc any_out[] = {{"valor", TB_VALUE_NONE}}; + reg(rt, lib, "Operators.Lt", any2, 2, bool_out, 1, eval_op_lt); + reg(rt, lib, "Operators.Eq", any2, 2, bool_out, 1, eval_op_eq); + reg(rt, lib, "Operators.Gt", any2, 2, bool_out, 1, eval_op_gt); + reg(rt, lib, "Operators.And", bool2, 2, bool_out, 1, eval_op_and); + reg(rt, lib, "Operators.Or", bool2, 2, bool_out, 1, eval_op_or); + reg(rt, lib, "Operators.Not", bool2, 1, bool_out, 1, eval_op_not); + reg(rt, lib, "Operators.Random", rnd_in, 2, any_out, 1, eval_op_random); + + /* Variáveis */ + static const TinyBlocks_SlotDesc var_in[] = {{"variável", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc var_set[] = {{"variável", TB_VALUE_TEXT}, {"valor", TB_VALUE_NONE}}; + reg(rt, lib, "Variables.Set", var_set, 2, NULL, 0, eval_var_set); + reg(rt, lib, "Variables.Change", var_set, 2, NULL, 0, eval_var_change); + reg(rt, lib, "Variables.Get", var_in, 1, any_out, 1, eval_var_get); + + /* Portas de blocos compostos */ + static const TinyBlocks_SlotDesc port_label[] = {{"nome", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc port_out_in[] = {{"nome", TB_VALUE_TEXT}, {"valor", TB_VALUE_NONE}}; + reg(rt, lib, "Port.In", port_label, 1, any_out, 1, eval_port_in); + reg(rt, lib, "Port.Out", port_out_in, 2, NULL, 0, eval_port_out); + + /* Palco e blocos de desenho (caneta) */ + if (!tb_stage_register(rt, lib)) return false; + + /* Editor.Scene — produz um RenderableBlock via on_draw; não abre janela */ + static const TinyBlocks_SlotDesc scene_in[] = { {"events", TB_VALUE_BLOCK} }; + TinyBlocks_TypeBlock* t = tb_type_block_create(rt, "Editor.Scene", + scene_in, 1, NULL, 0, editor_eval); + if (!t) return false; + tb_type_block_set_instance_hooks(t, sizeof(Ed*), editor_instance_init, editor_instance_deinit); + t->on_draw = editor_on_draw; + tb_library_add(lib, &t->base); + return true; +} + +static void editor_lib_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + (void)rt; (void)lib; +} + +TINYBLOCKS_DEFINE_LIBRARY(editor, + "tinyblocks-editor", + "2.0.0", + editor_lib_init, + editor_lib_deinit) + +const TinyBlocks_LibraryDescriptor* tb_editor_get_library(void) { + return &_tb_lib_desc_editor; +} diff --git a/libraries/tinyblocks-editor/src/tb_stage.c b/libraries/tinyblocks-editor/src/tb_stage.c new file mode 100644 index 0000000..cd9117b --- /dev/null +++ b/libraries/tinyblocks-editor/src/tb_stage.c @@ -0,0 +1,259 @@ +/* + * TinyBlocks — tb_stage.c + * O Palco do editor: uma tela lógica de 480x360 (origem no centro, y para + * cima, como no Scratch) onde os blocos Stage.* desenham. É um componente de + * UI: o editor o embute no painel direito (chamando seu on_draw) ou o entrega + * como cena de um Graphics.Window próprio ("destacar palco"). + * + * Os desenhos ficam numa lista retida e são re-emitidos a cada on_draw, + * escalados para o tamanho da área (letterbox mantendo 4:3). + */ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include + +#include +#include "tb_stage.h" + +#define STAGE_W 480.f +#define STAGE_H 360.f +#define STAGE_MAX_CMDS 4000 +#define STAGE_TEXT_FS 14.f + +typedef enum { SC_RECT, SC_CIRCLE, SC_LINE, SC_TEXT } StageCmdKind; + +typedef struct { + StageCmdKind kind; + float a, b, c, d; /* geometria em coordenadas do palco */ + float size; /* espessura da caneta */ + float col[3]; + char text[96]; +} StageCmd; + +typedef struct { + StageCmd* cmds; + int n, cap; + float bg[3]; + float pen[3]; + float pen_size; + float view_w, view_h; + bool full_warned; +} Stage; + +static TinyBlocks_Block* s_current = NULL; + +static Stage* stage_of(TinyBlocks_Block* b) { return b ? *(Stage**)b->userdata : NULL; } + +TinyBlocks_Block* tb_stage_current(void) { return s_current; } + +void tb_stage_set_view(TinyBlocks_Block* stage, float w, float h) { + Stage* s = stage_of(stage); + if (s && w > 0 && h > 0) { s->view_w = w; s->view_h = h; } +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Editor.Stage + * ══════════════════════════════════════════════════════════════════════════ */ +static bool stage_instance_init(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + Stage* s = (Stage*)calloc(1, sizeof(Stage)); + if (!s) return false; + s->bg[0] = s->bg[1] = s->bg[2] = 1.f; + s->pen[0] = 76/255.f; s->pen[1] = 151/255.f; s->pen[2] = 1.f; + s->pen_size = 2.f; + s->view_w = STAGE_W; s->view_h = STAGE_H; + *(Stage**)self->userdata = s; + s_current = self; + return true; +} + +static void stage_instance_deinit(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + Stage* s = stage_of(self); + if (s) { free(s->cmds); free(s); } + *(Stage**)self->userdata = NULL; + if (s_current == self) s_current = NULL; +} + +/* input 0 (opcional): Graphics.Input da janela que mostra o palco — dá o tamanho da vista */ +static void eval_stage(TinyBlocks_Block* self, TinyBlocks* rt) { + self->dirty = false; + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + TinyBlocks_Block* in = v.kind == TB_VALUE_BLOCK ? v.as.block : NULL; + if (!in || in->output_count < GFX_IN_COUNT) return; + TinyBlocks_Value w = in->outputs[GFX_IN_WIN_W], h = in->outputs[GFX_IN_WIN_H]; + if (w.kind == TB_VALUE_INTEGER && h.kind == TB_VALUE_INTEGER) + tb_stage_set_view(self, (float)w.as.integer, (float)h.as.integer); +} + +static bool stage_on_draw(TinyBlocks_Block* self, TinyBlocks* rt, TinyBlocks_RenderableBlock** dst) { + (void)rt; + Stage* s = stage_of(self); + if (!s) return false; + TinyBlocks_RenderableBlock* rb = tb_renderable_acquire(); + if (!rb) return false; + + float sc = s->view_w / STAGE_W < s->view_h / STAGE_H ? s->view_w / STAGE_W : s->view_h / STAGE_H; + float ox = (s->view_w - STAGE_W*sc) * 0.5f, oy = (s->view_h - STAGE_H*sc) * 0.5f; +#define SX(x) (ox + ((x) + STAGE_W*0.5f) * sc) +#define SY(y) (oy + (STAGE_H*0.5f - (y)) * sc) + + if (ox > 0.5f || oy > 0.5f) tb_draw_fill_rect(rb, 0, 0, s->view_w, s->view_h, 0.12f, 0.12f, 0.14f, 1.f); + tb_draw_fill_rect(rb, ox, oy, STAGE_W*sc, STAGE_H*sc, s->bg[0], s->bg[1], s->bg[2], 1.f); + tb_draw_set_clip(rb, ox, oy, STAGE_W*sc, STAGE_H*sc); + + for (int i = 0; i < s->n && rb->count < TB_DRAW_CMD_CAP - 2; i++) { + const StageCmd* c = &s->cmds[i]; + float r = c->col[0], g = c->col[1], b = c->col[2]; + switch (c->kind) { + case SC_RECT: + tb_draw_fill_rect(rb, SX(c->a - c->c*0.5f), SY(c->b + c->d*0.5f), c->c*sc, c->d*sc, r, g, b, 1.f); + break; + case SC_CIRCLE: + tb_draw_fill_circle(rb, SX(c->a), SY(c->b), c->c*sc, r, g, b, 1.f); + break; + case SC_LINE: + tb_draw_stroke_line(rb, SX(c->a), SY(c->b), SX(c->c), SY(c->d), c->size*sc, r, g, b, 1.f); + break; + case SC_TEXT: { + float fs = STAGE_TEXT_FS * sc; + tb_draw_text(rb, SX(c->a), SY(c->b) + fs*0.36f, c->text, fs, r, g, b, 1.f); + break; + } + } + } + tb_draw_clear_clip(rb); +#undef SX +#undef SY + *dst = rb; + return true; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Blocos Stage.* — desenham no palco atual + * ══════════════════════════════════════════════════════════════════════════ */ +static float num(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { + TinyBlocks_Value v = tb_block_get_input(self, rt, i); + if (v.kind == TB_VALUE_REAL) return (float)v.as.real; + if (v.kind == TB_VALUE_INTEGER) return (float)v.as.integer; + if (v.kind == TB_VALUE_TEXT && v.as.text) return (float)strtod(v.as.text, NULL); + return 0.f; +} + +static float chan(float v) { return v < 0 ? 0.f : v > 255 ? 1.f : v / 255.f; } + +static StageCmd* push(TinyBlocks* rt, StageCmdKind kind) { + Stage* s = stage_of(s_current); + if (!s) { tinyblocks_set_error(rt, "nenhum palco (Editor.Stage) criado"); return NULL; } + if (s->n >= STAGE_MAX_CMDS) { + if (!s->full_warned) tinyblocks_set_error(rt, "palco cheio (%d desenhos) — use \"apague tudo\"", STAGE_MAX_CMDS); + s->full_warned = true; + return NULL; + } + if (s->n >= s->cap) { + int nc = s->cap ? s->cap * 2 : 64; + StageCmd* p = (StageCmd*)realloc(s->cmds, (size_t)nc * sizeof(StageCmd)); + if (!p) return NULL; + s->cmds = p; s->cap = nc; + } + StageCmd* c = &s->cmds[s->n++]; + memset(c, 0, sizeof(*c)); + c->kind = kind; + memcpy(c->col, s->pen, sizeof(c->col)); + c->size = s->pen_size; + return c; +} + +static void eval_clear(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + Stage* s = stage_of(s_current); + if (s) { s->n = 0; s->full_warned = false; } + self->dirty = false; +} + +static void eval_background(TinyBlocks_Block* self, TinyBlocks* rt) { + Stage* s = stage_of(s_current); + if (s) { s->bg[0] = chan(num(self, rt, 0)); s->bg[1] = chan(num(self, rt, 1)); s->bg[2] = chan(num(self, rt, 2)); } + self->dirty = false; +} + +static void eval_pen_color(TinyBlocks_Block* self, TinyBlocks* rt) { + Stage* s = stage_of(s_current); + if (s) { s->pen[0] = chan(num(self, rt, 0)); s->pen[1] = chan(num(self, rt, 1)); s->pen[2] = chan(num(self, rt, 2)); } + self->dirty = false; +} + +static void eval_pen_size(TinyBlocks_Block* self, TinyBlocks* rt) { + Stage* s = stage_of(s_current); + float v = num(self, rt, 0); + if (s) s->pen_size = v < 1.f ? 1.f : v; + self->dirty = false; +} + +static void eval_line(TinyBlocks_Block* self, TinyBlocks* rt) { + StageCmd* c = push(rt, SC_LINE); + if (c) { c->a = num(self, rt, 0); c->b = num(self, rt, 1); c->c = num(self, rt, 2); c->d = num(self, rt, 3); } + self->dirty = false; +} + +static void eval_rect(TinyBlocks_Block* self, TinyBlocks* rt) { + StageCmd* c = push(rt, SC_RECT); + if (c) { c->a = num(self, rt, 0); c->b = num(self, rt, 1); c->c = num(self, rt, 2); c->d = num(self, rt, 3); } + self->dirty = false; +} + +static void eval_circle(TinyBlocks_Block* self, TinyBlocks* rt) { + StageCmd* c = push(rt, SC_CIRCLE); + if (c) { c->a = num(self, rt, 0); c->b = num(self, rt, 1); c->c = num(self, rt, 2); } + self->dirty = false; +} + +static void eval_text(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + char buf[96] = ""; + if (v.kind == TB_VALUE_TEXT && v.as.text) snprintf(buf, sizeof(buf), "%s", v.as.text); + else if (v.kind == TB_VALUE_INTEGER) snprintf(buf, sizeof(buf), "%lld", (long long)v.as.integer); + else if (v.kind == TB_VALUE_REAL) snprintf(buf, sizeof(buf), "%g", v.as.real); + StageCmd* c = push(rt, SC_TEXT); + if (c) { memcpy(c->text, buf, sizeof(c->text)); c->a = num(self, rt, 1); c->b = num(self, rt, 2); } + self->dirty = false; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Registro + * ══════════════════════════════════════════════════════════════════════════ */ +static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name, + const TinyBlocks_SlotDesc* in, uint32_t ni, + void (*fn)(TinyBlocks_Block*, TinyBlocks*)) { + TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, NULL, 0, fn); + if (!t) return false; + tb_library_add(lib, &t->base); + return true; +} + +bool tb_stage_register(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + static const TinyBlocks_SlotDesc stage_in[] = {{"entrada", TB_VALUE_BLOCK}}; + TinyBlocks_TypeBlock* t = tb_type_block_create(rt, "Editor.Stage", stage_in, 1, NULL, 0, eval_stage); + if (!t) return false; + tb_type_block_set_instance_hooks(t, sizeof(Stage*), stage_instance_init, stage_instance_deinit); + t->on_draw = stage_on_draw; + tb_library_add(lib, &t->base); + + static const TinyBlocks_SlotDesc rgb[] = {{"r", TB_VALUE_REAL}, {"g", TB_VALUE_REAL}, {"b", TB_VALUE_REAL}}; + static const TinyBlocks_SlotDesc size[] = {{"tamanho", TB_VALUE_REAL}}; + static const TinyBlocks_SlotDesc line[] = {{"x1", TB_VALUE_REAL}, {"y1", TB_VALUE_REAL}, + {"x2", TB_VALUE_REAL}, {"y2", TB_VALUE_REAL}}; + static const TinyBlocks_SlotDesc rect[] = {{"x", TB_VALUE_REAL}, {"y", TB_VALUE_REAL}, + {"largura", TB_VALUE_REAL}, {"altura", TB_VALUE_REAL}}; + static const TinyBlocks_SlotDesc circ[] = {{"x", TB_VALUE_REAL}, {"y", TB_VALUE_REAL}, {"raio", TB_VALUE_REAL}}; + static const TinyBlocks_SlotDesc text[] = {{"texto", TB_VALUE_TEXT}, {"x", TB_VALUE_REAL}, {"y", TB_VALUE_REAL}}; + return reg(rt, lib, "Stage.Clear", NULL, 0, eval_clear) + && reg(rt, lib, "Stage.Background", rgb, 3, eval_background) + && reg(rt, lib, "Stage.PenColor", rgb, 3, eval_pen_color) + && reg(rt, lib, "Stage.PenSize", size, 1, eval_pen_size) + && reg(rt, lib, "Stage.Line", line, 4, eval_line) + && reg(rt, lib, "Stage.Rect", rect, 4, eval_rect) + && reg(rt, lib, "Stage.Circle", circ, 3, eval_circle) + && reg(rt, lib, "Stage.Text", text, 3, eval_text); +} diff --git a/libraries/tinyblocks-editor/src/tb_stage.h b/libraries/tinyblocks-editor/src/tb_stage.h new file mode 100644 index 0000000..c9785a8 --- /dev/null +++ b/libraries/tinyblocks-editor/src/tb_stage.h @@ -0,0 +1,19 @@ +/* + * TinyBlocks — tb_stage.h + * Palco do editor (Editor.Stage) e blocos de desenho Stage.*. + */ +#ifndef TINYBLOCKS_EDITOR_STAGE_H +#define TINYBLOCKS_EDITOR_STAGE_H + +#include + +/* Registra Editor.Stage e os blocos Stage.* na library do editor */ +bool tb_stage_register(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib); + +/* Tamanho da área onde o palco será desenhado (on_draw usa 0..w × 0..h) */ +void tb_stage_set_view(TinyBlocks_Block* stage, float w, float h); + +/* Palco onde os blocos Stage.* desenham (o último criado) */ +TinyBlocks_Block* tb_stage_current(void); + +#endif /* TINYBLOCKS_EDITOR_STAGE_H */ diff --git a/libraries/tinyblocks-graphics/include/tb_graphics.h b/libraries/tinyblocks-graphics/include/tb_graphics.h new file mode 100644 index 0000000..5951399 --- /dev/null +++ b/libraries/tinyblocks-graphics/include/tb_graphics.h @@ -0,0 +1,126 @@ +/* + * TinyBlocks — tb_graphics.h + * Interface gráfica do TinyBlocks: janelas, entrada, desenho e texto. + * + * Tudo o que é gráfico passa por aqui antes de chegar a um backend concreto. + * O backend (ex: tinyblocks-sdl2) implementa TinyBlocks_GraphicsBackend e + * pode ser trocado livremente: + * - estaticamente: tb_graphics_set_backend(tb_sdl2_graphics_backend()); + * - dinamicamente: tb_graphics_load_backend("build/libtinyblocks-sdl2.so"); + * (o .so exporta TINYBLOCKS_GRAPHICS_BACKEND_SYMBOL) + * Sem escolha explícita usa o backend padrão de compilação (SDL2) ou, na + * falta dele, o backend nulo (headless — útil para testes). + * + * TypeBlocks registrados por tb_graphics_get_library(): + * Graphics.Input — estado de entrada de uma janela no frame (outputs GFX_IN_*) + * Graphics.Window — uma janela do SO que mostra uma cena (qualquer bloco com on_draw) + * in: título, largura, altura, cena(block), entrada(block), principal(int) + * Graphics.Run — roda o loop até a janela principal fechar + * + * Esta library não conhece nenhum consumidor (editor, palco…): só define o + * contrato e despacha para o backend. Cenas são quaisquer blocos com on_draw. + * + * Uso típico (host): + * tb_library_register(rt, tb_graphics_get_library()); + * TinyBlocks_Block* in = tb_block_create(rt, tb_type_block_find(rt, "Graphics.Input")); + * TinyBlocks_Block* win = tb_block_create(rt, tb_type_block_find(rt, "Graphics.Window")); + * tb_block_set_default(win, 3, tb_value_block(cena)); + * tb_block_set_default(win, 4, tb_value_block(in)); + * tb_block_eval(win, rt); // abre a janela + * tb_graphics_run(rt); // loop até a janela principal fechar + */ +#ifndef TINYBLOCKS_GRAPHICS_H +#define TINYBLOCKS_GRAPHICS_H + +#include +#include + +/* ── Teclas (neutras; o backend traduz as suas) ──────────────────────────── */ +enum { + TB_KEY_NONE = 0, + TB_KEY_ESCAPE, TB_KEY_RETURN, TB_KEY_BACKSPACE, TB_KEY_DELETE, TB_KEY_TAB, + TB_KEY_SPACE, TB_KEY_LEFT, TB_KEY_RIGHT, TB_KEY_UP, TB_KEY_DOWN, + TB_KEY_HOME, TB_KEY_END, + TB_KEY_F1, TB_KEY_F2, TB_KEY_F3, TB_KEY_F4, TB_KEY_F5, TB_KEY_F6, + TB_KEY_F7, TB_KEY_F8, TB_KEY_F9, TB_KEY_F10, TB_KEY_F11, TB_KEY_F12, + TB_KEY_A = 64, /* TB_KEY_A + n = letra 'a'+n */ + TB_KEY_0 = TB_KEY_A + 26, /* TB_KEY_0 + n = dígito n */ + TB_KEY_OTHER = 127 +}; + +/* ── Modificadores (bitmask) ─────────────────────────────────────────────── */ +#define TB_MOD_SHIFT 0x1 +#define TB_MOD_CTRL 0x2 +#define TB_MOD_ALT 0x4 + +/* ── Índices de output do bloco Graphics.Input ───────────────────────────── */ +#define GFX_IN_MOUSE_X 0 /* real: posição X do mouse na janela */ +#define GFX_IN_MOUSE_Y 1 /* real: posição Y do mouse na janela */ +#define GFX_IN_MOUSE_L_HELD 2 /* int: botão esquerdo pressionado (estado) */ +#define GFX_IN_MOUSE_R_HELD 3 /* int: botão direito pressionado (estado) */ +#define GFX_IN_MOUSE_L_DOWN 4 /* int: 1 se pressionado neste frame */ +#define GFX_IN_MOUSE_L_UP 5 /* int: 1 se solto neste frame */ +#define GFX_IN_MOUSE_R_DOWN 6 /* int: 1 se pressionado neste frame */ +#define GFX_IN_MOUSE_R_UP 7 /* int: 1 se solto neste frame */ +#define GFX_IN_SCROLL_DX 8 /* real: scroll horizontal deste frame */ +#define GFX_IN_SCROLL_DY 9 /* real: scroll vertical deste frame */ +#define GFX_IN_KEY 10 /* int: TB_KEY_* pressionada neste frame */ +#define GFX_IN_KEY_MOD 11 /* int: TB_MOD_* no momento da tecla */ +#define GFX_IN_KEY_REPEAT 12 /* int: 1 se é repetição de tecla segurada */ +#define GFX_IN_TEXT 13 /* text: texto digitado neste frame */ +#define GFX_IN_CLOSE 14 /* int: 1 se o usuário pediu para fechar */ +#define GFX_IN_WIN_W 15 /* int: largura atual da janela */ +#define GFX_IN_WIN_H 16 /* int: altura atual da janela */ +#define GFX_IN_DROP_FILE 17 /* text: caminho de arquivo solto na janela */ +#define GFX_IN_MOD_STATE 18 /* int: TB_MOD_* segurados agora */ +#define GFX_IN_COUNT 19 + +/* Estado de entrada de uma janela em um frame (preenchido pelo backend) */ +typedef struct TinyBlocks_GfxInput { + float mouse_x, mouse_y; + int l_held, r_held; + int l_down, l_up, r_down, r_up; + float scroll_dx, scroll_dy; + int key, key_mod, key_repeat; + char text[64]; + int close; + int win_w, win_h; + char drop_file[512]; + int mod_state; +} TinyBlocks_GfxInput; + +/* ── Contrato de um backend gráfico ──────────────────────────────────────── */ +typedef struct TinyBlocks_GraphicsBackend { + const char* name; + bool (*init)(void); /* idempotente */ + void (*shutdown)(void); + void* (*window_open)(const char* title, int w, int h); /* handle opaco ou NULL */ + void (*window_close)(void* win); + void (*poll)(void); /* coleta eventos do SO */ + void (*window_input)(void* win, TinyBlocks_GfxInput* out); + void (*window_present)(void* win, const TinyBlocks_RenderableBlock* rb); + float (*measure_text)(const char* text, float font_size); /* NULL = estimativa */ + void (*frame_wait)(void); /* NULL = ~16 ms */ +} TinyBlocks_GraphicsBackend; + +/* Símbolo exportado por um backend carregado como .so */ +#define TINYBLOCKS_GRAPHICS_BACKEND_SYMBOL "tinyblocks_get_graphics_backend" +typedef const TinyBlocks_GraphicsBackend* (*TinyBlocks_GetGraphicsBackendFn)(void); + +/* ── API ─────────────────────────────────────────────────────────────────── */ +TB_API const TinyBlocks_LibraryDescriptor* tb_graphics_get_library(void); + +/* Escolhe o backend (antes de abrir a primeira janela) */ +TB_API bool tb_graphics_set_backend(const TinyBlocks_GraphicsBackend* backend); +TB_API bool tb_graphics_load_backend(const char* so_path); +TB_API const TinyBlocks_GraphicsBackend* tb_graphics_backend(void); +TB_API const TinyBlocks_GraphicsBackend* tb_graphics_null_backend(void); + +/* Largura de um texto na fonte do backend */ +TB_API float tb_graphics_measure_text(const char* text, float font_size); + +/* Loop principal: roda todas as janelas abertas até a principal fechar */ +TB_API void tb_graphics_run(TinyBlocks* rt); +TB_API bool tb_graphics_window_is_open(TinyBlocks_Block* window); + +#endif /* TINYBLOCKS_GRAPHICS_H */ diff --git a/libraries/tinyblocks-graphics/src/tb_graphics.c b/libraries/tinyblocks-graphics/src/tb_graphics.c new file mode 100644 index 0000000..0984857 --- /dev/null +++ b/libraries/tinyblocks-graphics/src/tb_graphics.c @@ -0,0 +1,383 @@ +/* + * TinyBlocks — tb_graphics.c + * Interface gráfica: escolha de backend, janelas, entrada e loop principal. + */ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include +#include + +#include "../include/tb_graphics.h" + +#ifdef TB_GRAPHICS_DEFAULT_SDL2 +#include +#endif + +/* ══════════════════════════════════════════════════════════════════════════ + * Backend nulo (headless): janelas sem tela, entrada vazia, texto estimado + * ══════════════════════════════════════════════════════════════════════════ */ +typedef struct { int w, h; } NullWin; + +static bool null_init(void) { return true; } +static void null_shutdown(void) { } +static void* null_open(const char* title, int w, int h) { + (void)title; + NullWin* n = (NullWin*)calloc(1, sizeof(*n)); + if (n) { n->w = w; n->h = h; } + return n; +} +static void null_close(void* win) { free(win); } +static void null_poll(void) { } +static void null_input(void* win, TinyBlocks_GfxInput* out) { + memset(out, 0, sizeof(*out)); + const NullWin* n = (const NullWin*)win; + if (n) { out->win_w = n->w; out->win_h = n->h; } +} +static void null_present(void* win, const TinyBlocks_RenderableBlock* rb) { (void)win; (void)rb; } + +static const TinyBlocks_GraphicsBackend s_null_backend = { + .name = "null", + .init = null_init, + .shutdown = null_shutdown, + .window_open = null_open, + .window_close = null_close, + .poll = null_poll, + .window_input = null_input, + .window_present = null_present, + .measure_text = NULL, + .frame_wait = NULL, +}; + +const TinyBlocks_GraphicsBackend* tb_graphics_null_backend(void) { return &s_null_backend; } + +/* ══════════════════════════════════════════════════════════════════════════ + * Escolha do backend + * ══════════════════════════════════════════════════════════════════════════ */ +static const TinyBlocks_GraphicsBackend* s_backend = NULL; +static bool s_backend_ready = false; +static void* s_backend_dl = NULL; + +#define MAX_WINDOWS 16 +typedef struct { TinyBlocks_Block* block; uint64_t id; } WinEntry; +static WinEntry s_wins[MAX_WINDOWS]; +static int s_win_n = 0; +static uint64_t s_next_id = 1; + +const TinyBlocks_GraphicsBackend* tb_graphics_backend(void) { + if (!s_backend) { +#ifdef TB_GRAPHICS_DEFAULT_SDL2 + s_backend = (const TinyBlocks_GraphicsBackend*)tb_sdl2_graphics_backend(); +#endif + if (!s_backend) s_backend = &s_null_backend; + } + return s_backend; +} + +/* Backend inicializado; se o init falhar, cai para o nulo */ +static const TinyBlocks_GraphicsBackend* backend_ready(void) { + const TinyBlocks_GraphicsBackend* b = tb_graphics_backend(); + if (s_backend_ready) return b; + if (b->init && !b->init()) { + fprintf(stderr, "tinyblocks-graphics: backend '%s' falhou ao iniciar; usando 'null'\n", b->name); + s_backend = b = &s_null_backend; + } + s_backend_ready = true; + return b; +} + +bool tb_graphics_set_backend(const TinyBlocks_GraphicsBackend* backend) { + if (!backend || !backend->window_open || !backend->window_present) return false; + if (backend == s_backend) return true; + if (s_win_n > 0) { + fprintf(stderr, "tinyblocks-graphics: feche as janelas antes de trocar o backend\n"); + return false; + } + if (s_backend_ready && s_backend->shutdown) s_backend->shutdown(); + s_backend_ready = false; + s_backend = backend; + return true; +} + +bool tb_graphics_load_backend(const char* so_path) { + void* dl = dlopen(so_path, RTLD_NOW | RTLD_LOCAL); + if (!dl) { + fprintf(stderr, "tinyblocks-graphics: dlopen: %s\n", dlerror()); + return false; + } + TinyBlocks_GetGraphicsBackendFn get = + (TinyBlocks_GetGraphicsBackendFn)(uintptr_t)dlsym(dl, TINYBLOCKS_GRAPHICS_BACKEND_SYMBOL); + const TinyBlocks_GraphicsBackend* b = get ? get() : NULL; + if (!b || !tb_graphics_set_backend(b)) { + fprintf(stderr, "tinyblocks-graphics: '%s' não exporta um backend válido (%s)\n", + so_path, TINYBLOCKS_GRAPHICS_BACKEND_SYMBOL); + dlclose(dl); + return false; + } + if (s_backend_dl) dlclose(s_backend_dl); + s_backend_dl = dl; + return true; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Medição de texto + * ══════════════════════════════════════════════════════════════════════════ */ + +/* Larguras de avanço da DejaVu Sans, em em, para ASCII 32..126 — estimativa + * usada quando o backend não sabe medir (ex: backend nulo). */ +static const float s_adv[95] = { + .318f,.401f,.460f,.838f,.636f,.950f,.780f,.275f,.390f,.390f,.500f,.838f,.318f,.361f,.318f,.337f, + .636f,.636f,.636f,.636f,.636f,.636f,.636f,.636f,.636f,.636f,.337f,.337f,.838f,.838f,.838f,.531f, + 1.0f, .684f,.686f,.698f,.770f,.632f,.575f,.775f,.752f,.295f,.295f,.656f,.557f,.863f,.748f,.787f, + .603f,.787f,.695f,.635f,.611f,.732f,.684f,.989f,.685f,.611f,.685f,.390f,.337f,.390f,.838f,.500f, + .500f,.613f,.635f,.550f,.635f,.615f,.352f,.635f,.634f,.278f,.278f,.579f,.278f,.974f,.634f,.612f, + .635f,.635f,.411f,.521f,.392f,.634f,.592f,.818f,.592f,.592f,.525f,.636f,.337f,.636f,.838f +}; + +static float estimate_text(const char* s, float fs) { + float w = 0.f; + for (const unsigned char* p = (const unsigned char*)s; *p; p++) { + if (*p >= 32 && *p < 127) w += s_adv[*p - 32]; + else if ((*p & 0xC0) == 0xC0) w += (*p >= 0xE0) ? 0.9f : 0.62f; /* início de UTF-8 */ + } + return w * fs; +} + +float tb_graphics_measure_text(const char* text, float font_size) { + if (!text || !text[0]) return 0.f; + const TinyBlocks_GraphicsBackend* b = backend_ready(); + return b->measure_text ? b->measure_text(text, font_size) : estimate_text(text, font_size); +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Graphics.Input — estado de entrada de uma janela no frame + * ══════════════════════════════════════════════════════════════════════════ */ +static const TinyBlocks_SlotDesc s_input_outs[GFX_IN_COUNT] = { + {"mouse_x", TB_VALUE_REAL}, {"mouse_y", TB_VALUE_REAL}, + {"l_held", TB_VALUE_INTEGER}, {"r_held", TB_VALUE_INTEGER}, + {"l_down", TB_VALUE_INTEGER}, {"l_up", TB_VALUE_INTEGER}, + {"r_down", TB_VALUE_INTEGER}, {"r_up", TB_VALUE_INTEGER}, + {"scroll_dx", TB_VALUE_REAL}, {"scroll_dy", TB_VALUE_REAL}, + {"key", TB_VALUE_INTEGER}, {"key_mod", TB_VALUE_INTEGER}, + {"key_repeat", TB_VALUE_INTEGER}, {"text", TB_VALUE_TEXT}, + {"close", TB_VALUE_INTEGER}, {"win_w", TB_VALUE_INTEGER}, + {"win_h", TB_VALUE_INTEGER}, {"drop_file", TB_VALUE_TEXT}, + {"mod_state", TB_VALUE_INTEGER}, +}; + +static void eval_input(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + /* Os outputs são preenchidos pelo loop; aqui só garante valores neutros */ + for (uint32_t i = 0; i < self->output_count && i < GFX_IN_COUNT; i++) { + if (self->outputs[i].kind != TB_VALUE_NONE) continue; + switch (s_input_outs[i].expected_kind) { + case TB_VALUE_REAL: self->outputs[i] = tb_value_real(0.0); break; + case TB_VALUE_TEXT: self->outputs[i] = tb_value_text(""); break; + default: self->outputs[i] = tb_value_integer(0); break; + } + } + self->dirty = false; +} + +static void input_push(TinyBlocks_Block* b, const TinyBlocks_GfxInput* in) { + if (!b || b->output_count < GFX_IN_COUNT) return; +#define SET(idx, v) tb_block_set_output(b, idx, v) + SET(GFX_IN_MOUSE_X, tb_value_real(in->mouse_x)); + SET(GFX_IN_MOUSE_Y, tb_value_real(in->mouse_y)); + SET(GFX_IN_MOUSE_L_HELD, tb_value_integer(in->l_held)); + SET(GFX_IN_MOUSE_R_HELD, tb_value_integer(in->r_held)); + SET(GFX_IN_MOUSE_L_DOWN, tb_value_integer(in->l_down)); + SET(GFX_IN_MOUSE_L_UP, tb_value_integer(in->l_up)); + SET(GFX_IN_MOUSE_R_DOWN, tb_value_integer(in->r_down)); + SET(GFX_IN_MOUSE_R_UP, tb_value_integer(in->r_up)); + SET(GFX_IN_SCROLL_DX, tb_value_real(in->scroll_dx)); + SET(GFX_IN_SCROLL_DY, tb_value_real(in->scroll_dy)); + SET(GFX_IN_KEY, tb_value_integer(in->key)); + SET(GFX_IN_KEY_MOD, tb_value_integer(in->key_mod)); + SET(GFX_IN_KEY_REPEAT, tb_value_integer(in->key_repeat)); + SET(GFX_IN_TEXT, tb_value_text(in->text)); + SET(GFX_IN_CLOSE, tb_value_integer(in->close)); + SET(GFX_IN_WIN_W, tb_value_integer(in->win_w)); + SET(GFX_IN_WIN_H, tb_value_integer(in->win_h)); + SET(GFX_IN_DROP_FILE, tb_value_text(in->drop_file)); + SET(GFX_IN_MOD_STATE, tb_value_integer(in->mod_state)); +#undef SET + b->dirty = false; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Graphics.Window — uma janela do SO mostrando uma cena + * inputs: 0 título, 1 largura, 2 altura, 3 cena(block), 4 entrada(block), + * 5 principal(int: fechar esta janela encerra o loop; padrão 1) + * output: 0 aberta(int) + * ══════════════════════════════════════════════════════════════════════════ */ +typedef struct { void* handle; uint64_t id; bool open; } WinState; + +static int win_find(uint64_t id) { + for (int i = 0; i < s_win_n; i++) if (s_wins[i].id == id) return i; + return -1; +} + +static void win_close(TinyBlocks_Block* self) { + WinState* ws = (WinState*)self->userdata; + if (!ws->open) return; + int i = win_find(ws->id); + if (i >= 0) { s_wins[i] = s_wins[s_win_n - 1]; s_win_n--; } + if (ws->handle && s_backend_ready) s_backend->window_close(ws->handle); + ws->handle = NULL; + ws->open = false; + tb_block_set_output(self, 0, tb_value_integer(0)); +} + +static bool win_instance_init(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + memset(self->userdata, 0, sizeof(WinState)); + return true; +} + +static void win_instance_deinit(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + win_close(self); +} + +static void eval_window(TinyBlocks_Block* self, TinyBlocks* rt) { + WinState* ws = (WinState*)self->userdata; + self->dirty = false; + if (ws->open) return; + if (s_win_n >= MAX_WINDOWS) { + tinyblocks_set_error(rt, "Graphics.Window: limite de %d janelas", MAX_WINDOWS); + return; + } + TinyBlocks_Value vt = tb_block_get_input(self, rt, 0); + TinyBlocks_Value vw = tb_block_get_input(self, rt, 1); + TinyBlocks_Value vh = tb_block_get_input(self, rt, 2); + const char* title = (vt.kind == TB_VALUE_TEXT && vt.as.text) ? vt.as.text : "TinyBlocks"; + int w = vw.kind == TB_VALUE_INTEGER && vw.as.integer > 0 ? (int)vw.as.integer : 640; + int h = vh.kind == TB_VALUE_INTEGER && vh.as.integer > 0 ? (int)vh.as.integer : 480; + + const TinyBlocks_GraphicsBackend* b = backend_ready(); + void* handle = b->window_open(title, w, h); + if (!handle) { + tinyblocks_set_error(rt, "Graphics.Window: o backend '%s' não abriu a janela", b->name); + return; + } + ws->handle = handle; + ws->id = s_next_id++; + ws->open = true; + s_wins[s_win_n++] = (WinEntry){ self, ws->id }; + tb_block_set_output(self, 0, tb_value_integer(1)); +} + +bool tb_graphics_window_is_open(TinyBlocks_Block* window) { + if (!window || !window->type || !window->type->type_name || + strcmp(window->type->type_name, "Graphics.Window") != 0) return false; + return ((WinState*)window->userdata)->open; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Loop principal + * ══════════════════════════════════════════════════════════════════════════ */ +static void default_wait(void) { + struct timespec ts = { 0, 16 * 1000000L }; + nanosleep(&ts, NULL); +} + +void tb_graphics_run(TinyBlocks* rt) { + const TinyBlocks_GraphicsBackend* b = backend_ready(); + bool running = s_win_n > 0; + while (running) { + if (b->poll) b->poll(); + + /* As cenas podem abrir/fechar janelas: itera sobre uma cópia dos ids */ + uint64_t ids[MAX_WINDOWS]; + int n = s_win_n; + for (int i = 0; i < n; i++) ids[i] = s_wins[i].id; + + for (int k = 0; k < n; k++) { + int i = win_find(ids[k]); + if (i < 0) continue; + TinyBlocks_Block* wb = s_wins[i].block; + WinState* ws = (WinState*)wb->userdata; + + TinyBlocks_GfxInput in; + b->window_input(ws->handle, &in); + TinyBlocks_Value vin = tb_block_get_input(wb, rt, 4); + if (vin.kind == TB_VALUE_BLOCK) input_push(vin.as.block, &in); + + if (in.close) { + TinyBlocks_Value vp = tb_block_get_input(wb, rt, 5); + if (vp.kind != TB_VALUE_INTEGER || vp.as.integer) running = false; + win_close(wb); + continue; + } + + TinyBlocks_RenderableBlock* rb = NULL; + TinyBlocks_Value vs = tb_block_get_input(wb, rt, 3); + TinyBlocks_Block* scene = vs.kind == TB_VALUE_BLOCK ? vs.as.block : NULL; + if (scene) { + scene->dirty = true; + tb_block_eval(scene, rt); + if (win_find(ids[k]) < 0) continue; /* a cena fechou esta janela */ + if (scene->type && scene->type->on_draw) scene->type->on_draw(scene, rt, &rb); + } + b->window_present(ws->handle, rb); + if (rb) tb_renderable_release(rb); + } + tb_renderable_release_all(); + + if (s_win_n == 0) running = false; + if (running) { if (b->frame_wait) b->frame_wait(); else default_wait(); } + } + + while (s_win_n > 0) win_close(s_wins[s_win_n - 1].block); + if (b->shutdown) b->shutdown(); + s_backend_ready = false; +} + +static void eval_run(TinyBlocks_Block* self, TinyBlocks* rt) { + self->dirty = false; + tb_graphics_run(rt); +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Registro da library + * ══════════════════════════════════════════════════════════════════════════ */ +static bool graphics_lib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + TinyBlocks_TypeBlock* t; + + t = tb_type_block_create(rt, "Graphics.Input", NULL, 0, s_input_outs, GFX_IN_COUNT, eval_input); + if (!t) return false; + tb_library_add(lib, &t->base); + + static const TinyBlocks_SlotDesc win_in[] = { + {"título", TB_VALUE_TEXT}, {"largura", TB_VALUE_INTEGER}, {"altura", TB_VALUE_INTEGER}, + {"cena", TB_VALUE_BLOCK}, {"entrada", TB_VALUE_BLOCK}, {"principal", TB_VALUE_INTEGER}, + }; + static const TinyBlocks_SlotDesc win_out[] = {{"aberta", TB_VALUE_INTEGER}}; + t = tb_type_block_create(rt, "Graphics.Window", win_in, 6, win_out, 1, eval_window); + if (!t) return false; + tb_type_block_set_instance_hooks(t, sizeof(WinState), win_instance_init, win_instance_deinit); + tb_library_add(lib, &t->base); + + t = tb_type_block_create(rt, "Graphics.Run", NULL, 0, NULL, 0, eval_run); + if (!t) return false; + tb_library_add(lib, &t->base); + return true; +} + +static void graphics_lib_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + (void)rt; (void)lib; + if (s_backend_ready && s_backend->shutdown) s_backend->shutdown(); + s_backend_ready = false; +} + +TINYBLOCKS_DEFINE_LIBRARY(graphics, + "tinyblocks-graphics", + "1.0.0", + graphics_lib_init, + graphics_lib_deinit) + +const TinyBlocks_LibraryDescriptor* tb_graphics_get_library(void) { + return &_tb_lib_desc_graphics; +} diff --git a/libraries/tinyblocks-mcp/include/tinyblocks-mcp/tb_mcp.h b/libraries/tinyblocks-mcp/include/tinyblocks-mcp/tb_mcp.h new file mode 100644 index 0000000..e14d5c6 --- /dev/null +++ b/libraries/tinyblocks-mcp/include/tinyblocks-mcp/tb_mcp.h @@ -0,0 +1,36 @@ +#ifndef TINYBLOCKS_MCP_H +#define TINYBLOCKS_MCP_H + +#include + +#ifdef _WIN32 +# define TB_MCP_API __declspec(dllexport) +#else +# define TB_MCP_API __attribute__((visibility("default"))) +#endif + +/* + * tb_mcp — cliente MCP (Model Context Protocol) sobre transporte HTTP + * e stdio, implementado em Python via tinyblocks-python. + * + * Transport HTTP (streamable): url = "http://host:port/mcp" + * Transport stdio: url = "stdio://npx @modelcontextprotocol/server-filesystem /tmp" + * + * Todas as funções retornam string heap-alocada (caller frees) ou NULL em erro. + */ + +TB_MCP_API bool tb_mcp_init(void); +TB_MCP_API void tb_mcp_deinit(void); + +/* Lista ferramentas disponíveis → JSON array de objetos {name, description} */ +TB_MCP_API char* tb_mcp_list_tools(const char* url); + +/* Chama uma ferramenta com argumentos JSON → resultado JSON */ +TB_MCP_API char* tb_mcp_call_tool(const char* url, + const char* tool_name, + const char* args_json); + +/* Ping: verifica se o servidor responde → "ok" ou mensagem de erro */ +TB_MCP_API char* tb_mcp_ping(const char* url); + +#endif /* TINYBLOCKS_MCP_H */ diff --git a/libraries/tinyblocks-mcp/src/tb_mcp.c b/libraries/tinyblocks-mcp/src/tb_mcp.c new file mode 100644 index 0000000..247b68c --- /dev/null +++ b/libraries/tinyblocks-mcp/src/tb_mcp.c @@ -0,0 +1,125 @@ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include + +#include "tinyblocks-mcp/tb_mcp.h" +#include "tinyblocks-python/tb_python.h" + +/* Código Python gerado por: xxd -i tb_mcp.py > tb_mcp_py.h */ +#include "tb_mcp_py.h" + +/* ── Singleton ───────────────────────────────────────────────────────────── */ +static bool s_module_loaded = false; + +static bool ensure_module(void) { + if (s_module_loaded) return true; + /* + * Executa o módulo Python em __main__ para que as funções persistam + * entre chamadas. tb_mcp_py é unsigned char[] gerado pelo xxd -i. + */ + char* err = tb_python_exec_main((const char*)tb_mcp_py); + bool ok = (err != NULL && strlen(err) == 0); + if (!ok && err) fprintf(stderr, "[tinyblocks-mcp] erro ao carregar modulo Python:\n%s\n", err); + free(err); + s_module_loaded = ok; + return ok; +} + +TB_MCP_API bool tb_mcp_init(void) { + if (!tb_python_init()) return false; + return ensure_module(); +} + +TB_MCP_API void tb_mcp_deinit(void) { + s_module_loaded = false; + tb_python_deinit(); +} + +/* ── Helper: escapa string para literal Python ───────────────────────────── */ +static char* py_str(const char* s) { + size_t n = strlen(s); + char* out = malloc(n * 4 + 3); + if (!out) return NULL; + char* p = out; + *p++ = '"'; + for (size_t i = 0; i < n; i++) { + unsigned char c = (unsigned char)s[i]; + if (c == '"') { *p++ = '\\'; *p++ = '"'; } + else if (c == '\\') { *p++ = '\\'; *p++ = '\\'; } + else if (c == '\n') { *p++ = '\\'; *p++ = 'n'; } + else if (c == '\r') { *p++ = '\\'; *p++ = 'r'; } + else if (c < 0x20) { + p += sprintf(p, "\\x%02x", c); + } else { + *p++ = (char)c; + } + } + *p++ = '"'; + *p = '\0'; + return out; +} + +/* ── Helper genérico: monta e executa chamada Python fn(arg...) ─────────── */ +static char* py_call(const char* fn, const char* const* args, int n) { + if (!ensure_module()) return strdup("erro: modulo MCP nao carregado"); + + /* Constrói "print(fn(arg0, arg1, ...))" */ + size_t total = strlen(fn) + 16; + char** esc = malloc(n * sizeof(char*)); + if (!esc) return strdup("erro: memoria"); + for (int i = 0; i < n; i++) { + esc[i] = py_str(args[i]); + if (!esc[i]) { + for (int j = 0; j < i; j++) free(esc[j]); + free(esc); + return strdup("erro: memoria"); + } + total += strlen(esc[i]) + 2; + } + + char* code = malloc(total + 16); + if (!code) { + for (int i = 0; i < n; i++) free(esc[i]); + free(esc); + return strdup("erro: memoria"); + } + + char* p = code; + p += sprintf(p, "print(%s(", fn); + for (int i = 0; i < n; i++) { + if (i > 0) { *p++ = ','; *p++ = ' '; } + p += sprintf(p, "%s", esc[i]); + } + sprintf(p, "))"); + + for (int i = 0; i < n; i++) free(esc[i]); + free(esc); + + char* out = tb_python_exec_main(code); + free(code); + + /* Remove trailing newline */ + if (out) { + size_t len = strlen(out); + while (len > 0 && (out[len-1] == '\n' || out[len-1] == '\r')) + out[--len] = '\0'; + } + return out ? out : strdup(""); +} + +/* ── API pública ─────────────────────────────────────────────────────────── */ +TB_MCP_API char* tb_mcp_ping(const char* url) { + const char* args[] = {url}; + return py_call("mcp_ping", args, 1); +} + +TB_MCP_API char* tb_mcp_list_tools(const char* url) { + const char* args[] = {url}; + return py_call("mcp_list_tools", args, 1); +} + +TB_MCP_API char* tb_mcp_call_tool(const char* url, const char* tool_name, const char* args_json) { + const char* args[] = {url, tool_name, args_json ? args_json : "{}"}; + return py_call("mcp_call_tool", args, 3); +} diff --git a/libraries/tinyblocks-mcp/src/tb_mcp.py b/libraries/tinyblocks-mcp/src/tb_mcp.py new file mode 100644 index 0000000..195c5ea --- /dev/null +++ b/libraries/tinyblocks-mcp/src/tb_mcp.py @@ -0,0 +1,115 @@ +import json + +def _http_jsonrpc(url, method, params): + import urllib.request, urllib.error + payload = json.dumps({ + "jsonrpc": "2.0", + "id": 1, + "method": method, + "params": params + }).encode() + req = urllib.request.Request( + url, + data=payload, + headers={ + "Content-Type": "application/json", + "Accept": "application/json", + } + ) + try: + with urllib.request.urlopen(req, timeout=15) as r: + body = r.read().decode() + except urllib.error.HTTPError as e: + return {"error": {"code": e.code, "message": e.reason}} + except Exception as e: + return {"error": {"code": -1, "message": str(e)}} + try: + return json.loads(body) + except Exception as e: + return {"error": {"code": -2, "message": "invalid JSON: " + str(e)}} + +def _stdio_jsonrpc(cmd, method, params): + import subprocess + args = cmd.split() + try: + proc = subprocess.Popen( + args, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL + ) + except FileNotFoundError as e: + return {"error": {"code": -1, "message": str(e)}} + + def send(obj): + line = (json.dumps(obj) + "\n").encode() + proc.stdin.write(line) + proc.stdin.flush() + + def recv(): + line = proc.stdout.readline() + if not line: + return {} + return json.loads(line.decode().strip()) + + try: + send({"jsonrpc":"2.0","id":1,"method":"initialize","params":{ + "protocolVersion":"2024-11-05", + "capabilities":{}, + "clientInfo":{"name":"tinyblocks-mcp","version":"1.0"} + }}) + recv() + send({"jsonrpc":"2.0","method":"notifications/initialized","params":{}}) + send({"jsonrpc":"2.0","id":2,"method":method,"params":params}) + resp = recv() + return resp + except Exception as e: + return {"error":{"code":-1,"message":str(e)}} + finally: + proc.terminate() + proc.wait(timeout=3) + +def _dispatch(url, method, params): + if url.startswith("stdio://"): + return _stdio_jsonrpc(url[len("stdio://"):], method, params) + else: + return _http_jsonrpc(url, method, params) + +def mcp_ping(url): + resp = _dispatch(url, "ping", {}) + if "error" in resp: + return "erro: " + resp["error"].get("message", str(resp["error"])) + return "ok" + +def mcp_list_tools(url): + resp = _dispatch(url, "tools/list", {}) + if "error" in resp: + return "erro: " + resp["error"].get("message", str(resp["error"])) + result = resp.get("result", resp) + tools = result.get("tools", []) + out = [] + for t in tools: + name = t.get("name","?") + desc = t.get("description","") + out.append(name + ": " + desc) + return "\n".join(out) if out else "(nenhuma ferramenta)" + +def mcp_call_tool(url, tool_name, args_json): + try: + args = json.loads(args_json) if args_json and args_json.strip() else {} + except Exception as e: + return "erro: args JSON invalido: " + str(e) + resp = _dispatch(url, "tools/call", {"name": tool_name, "arguments": args}) + if "error" in resp: + return "erro: " + resp["error"].get("message", str(resp["error"])) + result = resp.get("result", resp) + content = result.get("content", result) + if isinstance(content, list): + parts = [] + for item in content: + if isinstance(item, dict): + parts.append(item.get("text", json.dumps(item))) + else: + parts.append(str(item)) + return "\n".join(parts) + return json.dumps(content, ensure_ascii=False, indent=2) diff --git a/libraries/tinyblocks-mcp/src/tb_mcp_py.h b/libraries/tinyblocks-mcp/src/tb_mcp_py.h new file mode 100644 index 0000000..8cf74f7 --- /dev/null +++ b/libraries/tinyblocks-mcp/src/tb_mcp_py.h @@ -0,0 +1,314 @@ +unsigned char tb_mcp_py[] = { + 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x20, 0x6a, 0x73, 0x6f, 0x6e, 0x0a, + 0x0a, 0x64, 0x65, 0x66, 0x20, 0x5f, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x6a, + 0x73, 0x6f, 0x6e, 0x72, 0x70, 0x63, 0x28, 0x75, 0x72, 0x6c, 0x2c, 0x20, + 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x2c, 0x20, 0x70, 0x61, 0x72, 0x61, + 0x6d, 0x73, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x6d, 0x70, + 0x6f, 0x72, 0x74, 0x20, 0x75, 0x72, 0x6c, 0x6c, 0x69, 0x62, 0x2e, 0x72, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2c, 0x20, 0x75, 0x72, 0x6c, 0x6c, + 0x69, 0x62, 0x2e, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x20, 0x3d, 0x20, 0x6a, + 0x73, 0x6f, 0x6e, 0x2e, 0x64, 0x75, 0x6d, 0x70, 0x73, 0x28, 0x7b, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6a, 0x73, 0x6f, + 0x6e, 0x72, 0x70, 0x63, 0x22, 0x3a, 0x20, 0x22, 0x32, 0x2e, 0x30, 0x22, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x69, + 0x64, 0x22, 0x3a, 0x20, 0x31, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x22, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x22, 0x3a, + 0x20, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x2c, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, + 0x22, 0x3a, 0x20, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x7d, 0x29, 0x2e, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x65, 0x28, + 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x71, 0x20, 0x3d, 0x20, + 0x75, 0x72, 0x6c, 0x6c, 0x69, 0x62, 0x2e, 0x72, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x28, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x75, 0x72, 0x6c, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x61, 0x74, + 0x61, 0x3d, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x2c, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x68, 0x65, 0x61, 0x64, 0x65, + 0x72, 0x73, 0x3d, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, + 0x74, 0x2d, 0x54, 0x79, 0x70, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x61, 0x70, + 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x6a, 0x73, + 0x6f, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, + 0x22, 0x3a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x70, + 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x6a, 0x73, + 0x6f, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x29, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x74, 0x72, 0x79, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x75, 0x72, 0x6c, 0x6c, 0x69, + 0x62, 0x2e, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x75, 0x72, + 0x6c, 0x6f, 0x70, 0x65, 0x6e, 0x28, 0x72, 0x65, 0x71, 0x2c, 0x20, 0x74, + 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x3d, 0x31, 0x35, 0x29, 0x20, 0x61, + 0x73, 0x20, 0x72, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x62, 0x6f, 0x64, 0x79, 0x20, 0x3d, 0x20, + 0x72, 0x2e, 0x72, 0x65, 0x61, 0x64, 0x28, 0x29, 0x2e, 0x64, 0x65, 0x63, + 0x6f, 0x64, 0x65, 0x28, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x65, 0x78, + 0x63, 0x65, 0x70, 0x74, 0x20, 0x75, 0x72, 0x6c, 0x6c, 0x69, 0x62, 0x2e, + 0x65, 0x72, 0x72, 0x6f, 0x72, 0x2e, 0x48, 0x54, 0x54, 0x50, 0x45, 0x72, + 0x72, 0x6f, 0x72, 0x20, 0x61, 0x73, 0x20, 0x65, 0x3a, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, + 0x20, 0x7b, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x3a, 0x20, 0x7b, + 0x22, 0x63, 0x6f, 0x64, 0x65, 0x22, 0x3a, 0x20, 0x65, 0x2e, 0x63, 0x6f, + 0x64, 0x65, 0x2c, 0x20, 0x22, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, + 0x22, 0x3a, 0x20, 0x65, 0x2e, 0x72, 0x65, 0x61, 0x73, 0x6f, 0x6e, 0x7d, + 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x65, 0x78, 0x63, 0x65, 0x70, 0x74, + 0x20, 0x45, 0x78, 0x63, 0x65, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x61, + 0x73, 0x20, 0x65, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x7b, 0x22, 0x65, 0x72, + 0x72, 0x6f, 0x72, 0x22, 0x3a, 0x20, 0x7b, 0x22, 0x63, 0x6f, 0x64, 0x65, + 0x22, 0x3a, 0x20, 0x2d, 0x31, 0x2c, 0x20, 0x22, 0x6d, 0x65, 0x73, 0x73, + 0x61, 0x67, 0x65, 0x22, 0x3a, 0x20, 0x73, 0x74, 0x72, 0x28, 0x65, 0x29, + 0x7d, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x74, 0x72, 0x79, 0x3a, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, + 0x72, 0x6e, 0x20, 0x6a, 0x73, 0x6f, 0x6e, 0x2e, 0x6c, 0x6f, 0x61, 0x64, + 0x73, 0x28, 0x62, 0x6f, 0x64, 0x79, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x65, 0x78, 0x63, 0x65, 0x70, 0x74, 0x20, 0x45, 0x78, 0x63, 0x65, 0x70, + 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x61, 0x73, 0x20, 0x65, 0x3a, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, + 0x6e, 0x20, 0x7b, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x3a, 0x20, + 0x7b, 0x22, 0x63, 0x6f, 0x64, 0x65, 0x22, 0x3a, 0x20, 0x2d, 0x32, 0x2c, + 0x20, 0x22, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x3a, 0x20, + 0x22, 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x20, 0x4a, 0x53, 0x4f, + 0x4e, 0x3a, 0x20, 0x22, 0x20, 0x2b, 0x20, 0x73, 0x74, 0x72, 0x28, 0x65, + 0x29, 0x7d, 0x7d, 0x0a, 0x0a, 0x64, 0x65, 0x66, 0x20, 0x5f, 0x73, 0x74, + 0x64, 0x69, 0x6f, 0x5f, 0x6a, 0x73, 0x6f, 0x6e, 0x72, 0x70, 0x63, 0x28, + 0x63, 0x6d, 0x64, 0x2c, 0x20, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x2c, + 0x20, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x29, 0x3a, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x20, 0x73, 0x75, 0x62, + 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x61, 0x72, 0x67, 0x73, 0x20, 0x3d, 0x20, 0x63, 0x6d, 0x64, 0x2e, 0x73, + 0x70, 0x6c, 0x69, 0x74, 0x28, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x74, + 0x72, 0x79, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x70, 0x72, 0x6f, 0x63, 0x20, 0x3d, 0x20, 0x73, 0x75, 0x62, 0x70, 0x72, + 0x6f, 0x63, 0x65, 0x73, 0x73, 0x2e, 0x50, 0x6f, 0x70, 0x65, 0x6e, 0x28, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x61, 0x72, 0x67, 0x73, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x74, 0x64, 0x69, 0x6e, + 0x3d, 0x73, 0x75, 0x62, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x2e, + 0x50, 0x49, 0x50, 0x45, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x74, 0x64, 0x6f, 0x75, 0x74, + 0x3d, 0x73, 0x75, 0x62, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x2e, + 0x50, 0x49, 0x50, 0x45, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x74, 0x64, 0x65, 0x72, 0x72, + 0x3d, 0x73, 0x75, 0x62, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x2e, + 0x44, 0x45, 0x56, 0x4e, 0x55, 0x4c, 0x4c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x65, 0x78, + 0x63, 0x65, 0x70, 0x74, 0x20, 0x46, 0x69, 0x6c, 0x65, 0x4e, 0x6f, 0x74, + 0x46, 0x6f, 0x75, 0x6e, 0x64, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x20, 0x61, + 0x73, 0x20, 0x65, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x7b, 0x22, 0x65, 0x72, + 0x72, 0x6f, 0x72, 0x22, 0x3a, 0x20, 0x7b, 0x22, 0x63, 0x6f, 0x64, 0x65, + 0x22, 0x3a, 0x20, 0x2d, 0x31, 0x2c, 0x20, 0x22, 0x6d, 0x65, 0x73, 0x73, + 0x61, 0x67, 0x65, 0x22, 0x3a, 0x20, 0x73, 0x74, 0x72, 0x28, 0x65, 0x29, + 0x7d, 0x7d, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x66, 0x20, + 0x73, 0x65, 0x6e, 0x64, 0x28, 0x6f, 0x62, 0x6a, 0x29, 0x3a, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x69, 0x6e, 0x65, 0x20, + 0x3d, 0x20, 0x28, 0x6a, 0x73, 0x6f, 0x6e, 0x2e, 0x64, 0x75, 0x6d, 0x70, + 0x73, 0x28, 0x6f, 0x62, 0x6a, 0x29, 0x20, 0x2b, 0x20, 0x22, 0x5c, 0x6e, + 0x22, 0x29, 0x2e, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x65, 0x28, 0x29, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x70, 0x72, 0x6f, 0x63, + 0x2e, 0x73, 0x74, 0x64, 0x69, 0x6e, 0x2e, 0x77, 0x72, 0x69, 0x74, 0x65, + 0x28, 0x6c, 0x69, 0x6e, 0x65, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x70, 0x72, 0x6f, 0x63, 0x2e, 0x73, 0x74, 0x64, 0x69, + 0x6e, 0x2e, 0x66, 0x6c, 0x75, 0x73, 0x68, 0x28, 0x29, 0x0a, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x64, 0x65, 0x66, 0x20, 0x72, 0x65, 0x63, 0x76, 0x28, + 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, + 0x69, 0x6e, 0x65, 0x20, 0x3d, 0x20, 0x70, 0x72, 0x6f, 0x63, 0x2e, 0x73, + 0x74, 0x64, 0x6f, 0x75, 0x74, 0x2e, 0x72, 0x65, 0x61, 0x64, 0x6c, 0x69, + 0x6e, 0x65, 0x28, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x69, 0x66, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x6c, 0x69, 0x6e, 0x65, + 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x7b, 0x7d, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, + 0x72, 0x6e, 0x20, 0x6a, 0x73, 0x6f, 0x6e, 0x2e, 0x6c, 0x6f, 0x61, 0x64, + 0x73, 0x28, 0x6c, 0x69, 0x6e, 0x65, 0x2e, 0x64, 0x65, 0x63, 0x6f, 0x64, + 0x65, 0x28, 0x29, 0x2e, 0x73, 0x74, 0x72, 0x69, 0x70, 0x28, 0x29, 0x29, + 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x74, 0x72, 0x79, 0x3a, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x65, 0x6e, 0x64, 0x28, + 0x7b, 0x22, 0x6a, 0x73, 0x6f, 0x6e, 0x72, 0x70, 0x63, 0x22, 0x3a, 0x22, + 0x32, 0x2e, 0x30, 0x22, 0x2c, 0x22, 0x69, 0x64, 0x22, 0x3a, 0x31, 0x2c, + 0x22, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x22, 0x3a, 0x22, 0x69, 0x6e, + 0x69, 0x74, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x22, 0x2c, 0x22, 0x70, + 0x61, 0x72, 0x61, 0x6d, 0x73, 0x22, 0x3a, 0x7b, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, + 0x6e, 0x22, 0x3a, 0x22, 0x32, 0x30, 0x32, 0x34, 0x2d, 0x31, 0x31, 0x2d, + 0x30, 0x35, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x61, 0x70, 0x61, 0x62, 0x69, + 0x6c, 0x69, 0x74, 0x69, 0x65, 0x73, 0x22, 0x3a, 0x7b, 0x7d, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x22, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x22, + 0x3a, 0x7b, 0x22, 0x6e, 0x61, 0x6d, 0x65, 0x22, 0x3a, 0x22, 0x74, 0x69, + 0x6e, 0x79, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x2d, 0x6d, 0x63, 0x70, + 0x22, 0x2c, 0x22, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0x3a, + 0x22, 0x31, 0x2e, 0x30, 0x22, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x7d, 0x7d, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x72, 0x65, 0x63, 0x76, 0x28, 0x29, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x65, 0x6e, 0x64, 0x28, 0x7b, + 0x22, 0x6a, 0x73, 0x6f, 0x6e, 0x72, 0x70, 0x63, 0x22, 0x3a, 0x22, 0x32, + 0x2e, 0x30, 0x22, 0x2c, 0x22, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x22, + 0x3a, 0x22, 0x6e, 0x6f, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x73, 0x2f, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x69, + 0x7a, 0x65, 0x64, 0x22, 0x2c, 0x22, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, + 0x22, 0x3a, 0x7b, 0x7d, 0x7d, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x73, 0x65, 0x6e, 0x64, 0x28, 0x7b, 0x22, 0x6a, 0x73, + 0x6f, 0x6e, 0x72, 0x70, 0x63, 0x22, 0x3a, 0x22, 0x32, 0x2e, 0x30, 0x22, + 0x2c, 0x22, 0x69, 0x64, 0x22, 0x3a, 0x32, 0x2c, 0x22, 0x6d, 0x65, 0x74, + 0x68, 0x6f, 0x64, 0x22, 0x3a, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x2c, + 0x22, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x22, 0x3a, 0x70, 0x61, 0x72, + 0x61, 0x6d, 0x73, 0x7d, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x72, 0x65, 0x73, 0x70, 0x20, 0x3d, 0x20, 0x72, 0x65, 0x63, + 0x76, 0x28, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x72, 0x65, 0x73, 0x70, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x65, 0x78, 0x63, 0x65, 0x70, 0x74, 0x20, 0x45, + 0x78, 0x63, 0x65, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x61, 0x73, 0x20, + 0x65, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, + 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x7b, 0x22, 0x65, 0x72, 0x72, 0x6f, + 0x72, 0x22, 0x3a, 0x7b, 0x22, 0x63, 0x6f, 0x64, 0x65, 0x22, 0x3a, 0x2d, + 0x31, 0x2c, 0x22, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x3a, + 0x73, 0x74, 0x72, 0x28, 0x65, 0x29, 0x7d, 0x7d, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x66, 0x69, 0x6e, 0x61, 0x6c, 0x6c, 0x79, 0x3a, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x70, 0x72, 0x6f, 0x63, 0x2e, 0x74, + 0x65, 0x72, 0x6d, 0x69, 0x6e, 0x61, 0x74, 0x65, 0x28, 0x29, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x70, 0x72, 0x6f, 0x63, 0x2e, + 0x77, 0x61, 0x69, 0x74, 0x28, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, + 0x3d, 0x33, 0x29, 0x0a, 0x0a, 0x64, 0x65, 0x66, 0x20, 0x5f, 0x64, 0x69, + 0x73, 0x70, 0x61, 0x74, 0x63, 0x68, 0x28, 0x75, 0x72, 0x6c, 0x2c, 0x20, + 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x2c, 0x20, 0x70, 0x61, 0x72, 0x61, + 0x6d, 0x73, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, + 0x75, 0x72, 0x6c, 0x2e, 0x73, 0x74, 0x61, 0x72, 0x74, 0x73, 0x77, 0x69, + 0x74, 0x68, 0x28, 0x22, 0x73, 0x74, 0x64, 0x69, 0x6f, 0x3a, 0x2f, 0x2f, + 0x22, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x5f, 0x73, 0x74, 0x64, 0x69, + 0x6f, 0x5f, 0x6a, 0x73, 0x6f, 0x6e, 0x72, 0x70, 0x63, 0x28, 0x75, 0x72, + 0x6c, 0x5b, 0x6c, 0x65, 0x6e, 0x28, 0x22, 0x73, 0x74, 0x64, 0x69, 0x6f, + 0x3a, 0x2f, 0x2f, 0x22, 0x29, 0x3a, 0x5d, 0x2c, 0x20, 0x6d, 0x65, 0x74, + 0x68, 0x6f, 0x64, 0x2c, 0x20, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x29, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x65, 0x6c, 0x73, 0x65, 0x3a, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, + 0x6e, 0x20, 0x5f, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x6a, 0x73, 0x6f, 0x6e, + 0x72, 0x70, 0x63, 0x28, 0x75, 0x72, 0x6c, 0x2c, 0x20, 0x6d, 0x65, 0x74, + 0x68, 0x6f, 0x64, 0x2c, 0x20, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x29, + 0x0a, 0x0a, 0x64, 0x65, 0x66, 0x20, 0x6d, 0x63, 0x70, 0x5f, 0x70, 0x69, + 0x6e, 0x67, 0x28, 0x75, 0x72, 0x6c, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x72, 0x65, 0x73, 0x70, 0x20, 0x3d, 0x20, 0x5f, 0x64, 0x69, 0x73, + 0x70, 0x61, 0x74, 0x63, 0x68, 0x28, 0x75, 0x72, 0x6c, 0x2c, 0x20, 0x22, + 0x70, 0x69, 0x6e, 0x67, 0x22, 0x2c, 0x20, 0x7b, 0x7d, 0x29, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72, + 0x22, 0x20, 0x69, 0x6e, 0x20, 0x72, 0x65, 0x73, 0x70, 0x3a, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, + 0x6e, 0x20, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x3a, 0x20, 0x22, 0x20, 0x2b, + 0x20, 0x72, 0x65, 0x73, 0x70, 0x5b, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72, + 0x22, 0x5d, 0x2e, 0x67, 0x65, 0x74, 0x28, 0x22, 0x6d, 0x65, 0x73, 0x73, + 0x61, 0x67, 0x65, 0x22, 0x2c, 0x20, 0x73, 0x74, 0x72, 0x28, 0x72, 0x65, + 0x73, 0x70, 0x5b, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x5d, 0x29, + 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, + 0x20, 0x22, 0x6f, 0x6b, 0x22, 0x0a, 0x0a, 0x64, 0x65, 0x66, 0x20, 0x6d, + 0x63, 0x70, 0x5f, 0x6c, 0x69, 0x73, 0x74, 0x5f, 0x74, 0x6f, 0x6f, 0x6c, + 0x73, 0x28, 0x75, 0x72, 0x6c, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x72, 0x65, 0x73, 0x70, 0x20, 0x3d, 0x20, 0x5f, 0x64, 0x69, 0x73, 0x70, + 0x61, 0x74, 0x63, 0x68, 0x28, 0x75, 0x72, 0x6c, 0x2c, 0x20, 0x22, 0x74, + 0x6f, 0x6f, 0x6c, 0x73, 0x2f, 0x6c, 0x69, 0x73, 0x74, 0x22, 0x2c, 0x20, + 0x7b, 0x7d, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x22, + 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x20, 0x69, 0x6e, 0x20, 0x72, 0x65, + 0x73, 0x70, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x22, 0x65, 0x72, 0x72, 0x6f, + 0x3a, 0x20, 0x22, 0x20, 0x2b, 0x20, 0x72, 0x65, 0x73, 0x70, 0x5b, 0x22, + 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x5d, 0x2e, 0x67, 0x65, 0x74, 0x28, + 0x22, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x2c, 0x20, 0x73, + 0x74, 0x72, 0x28, 0x72, 0x65, 0x73, 0x70, 0x5b, 0x22, 0x65, 0x72, 0x72, + 0x6f, 0x72, 0x22, 0x5d, 0x29, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72, + 0x65, 0x73, 0x75, 0x6c, 0x74, 0x20, 0x3d, 0x20, 0x72, 0x65, 0x73, 0x70, + 0x2e, 0x67, 0x65, 0x74, 0x28, 0x22, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, + 0x22, 0x2c, 0x20, 0x72, 0x65, 0x73, 0x70, 0x29, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x74, 0x6f, 0x6f, 0x6c, 0x73, 0x20, 0x3d, 0x20, 0x72, 0x65, 0x73, + 0x75, 0x6c, 0x74, 0x2e, 0x67, 0x65, 0x74, 0x28, 0x22, 0x74, 0x6f, 0x6f, + 0x6c, 0x73, 0x22, 0x2c, 0x20, 0x5b, 0x5d, 0x29, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x6f, 0x75, 0x74, 0x20, 0x3d, 0x20, 0x5b, 0x5d, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x74, 0x20, 0x69, 0x6e, 0x20, 0x74, + 0x6f, 0x6f, 0x6c, 0x73, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x3d, 0x20, 0x74, 0x2e, 0x67, + 0x65, 0x74, 0x28, 0x22, 0x6e, 0x61, 0x6d, 0x65, 0x22, 0x2c, 0x22, 0x3f, + 0x22, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, + 0x65, 0x73, 0x63, 0x20, 0x3d, 0x20, 0x74, 0x2e, 0x67, 0x65, 0x74, 0x28, + 0x22, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, + 0x22, 0x2c, 0x22, 0x22, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x6f, 0x75, 0x74, 0x2e, 0x61, 0x70, 0x70, 0x65, 0x6e, 0x64, + 0x28, 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x2b, 0x20, 0x22, 0x3a, 0x20, 0x22, + 0x20, 0x2b, 0x20, 0x64, 0x65, 0x73, 0x63, 0x29, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x22, 0x5c, 0x6e, 0x22, + 0x2e, 0x6a, 0x6f, 0x69, 0x6e, 0x28, 0x6f, 0x75, 0x74, 0x29, 0x20, 0x69, + 0x66, 0x20, 0x6f, 0x75, 0x74, 0x20, 0x65, 0x6c, 0x73, 0x65, 0x20, 0x22, + 0x28, 0x6e, 0x65, 0x6e, 0x68, 0x75, 0x6d, 0x61, 0x20, 0x66, 0x65, 0x72, + 0x72, 0x61, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x29, 0x22, 0x0a, 0x0a, 0x64, + 0x65, 0x66, 0x20, 0x6d, 0x63, 0x70, 0x5f, 0x63, 0x61, 0x6c, 0x6c, 0x5f, + 0x74, 0x6f, 0x6f, 0x6c, 0x28, 0x75, 0x72, 0x6c, 0x2c, 0x20, 0x74, 0x6f, + 0x6f, 0x6c, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x2c, 0x20, 0x61, 0x72, 0x67, + 0x73, 0x5f, 0x6a, 0x73, 0x6f, 0x6e, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x74, 0x72, 0x79, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x61, 0x72, 0x67, 0x73, 0x20, 0x3d, 0x20, 0x6a, 0x73, 0x6f, + 0x6e, 0x2e, 0x6c, 0x6f, 0x61, 0x64, 0x73, 0x28, 0x61, 0x72, 0x67, 0x73, + 0x5f, 0x6a, 0x73, 0x6f, 0x6e, 0x29, 0x20, 0x69, 0x66, 0x20, 0x61, 0x72, + 0x67, 0x73, 0x5f, 0x6a, 0x73, 0x6f, 0x6e, 0x20, 0x61, 0x6e, 0x64, 0x20, + 0x61, 0x72, 0x67, 0x73, 0x5f, 0x6a, 0x73, 0x6f, 0x6e, 0x2e, 0x73, 0x74, + 0x72, 0x69, 0x70, 0x28, 0x29, 0x20, 0x65, 0x6c, 0x73, 0x65, 0x20, 0x7b, + 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x65, 0x78, 0x63, 0x65, 0x70, 0x74, + 0x20, 0x45, 0x78, 0x63, 0x65, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x61, + 0x73, 0x20, 0x65, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x22, 0x65, 0x72, 0x72, + 0x6f, 0x3a, 0x20, 0x61, 0x72, 0x67, 0x73, 0x20, 0x4a, 0x53, 0x4f, 0x4e, + 0x20, 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x6f, 0x3a, 0x20, 0x22, + 0x20, 0x2b, 0x20, 0x73, 0x74, 0x72, 0x28, 0x65, 0x29, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x72, 0x65, 0x73, 0x70, 0x20, 0x3d, 0x20, 0x5f, 0x64, 0x69, + 0x73, 0x70, 0x61, 0x74, 0x63, 0x68, 0x28, 0x75, 0x72, 0x6c, 0x2c, 0x20, + 0x22, 0x74, 0x6f, 0x6f, 0x6c, 0x73, 0x2f, 0x63, 0x61, 0x6c, 0x6c, 0x22, + 0x2c, 0x20, 0x7b, 0x22, 0x6e, 0x61, 0x6d, 0x65, 0x22, 0x3a, 0x20, 0x74, + 0x6f, 0x6f, 0x6c, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x2c, 0x20, 0x22, 0x61, + 0x72, 0x67, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x22, 0x3a, 0x20, 0x61, + 0x72, 0x67, 0x73, 0x7d, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, + 0x20, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x20, 0x69, 0x6e, 0x20, + 0x72, 0x65, 0x73, 0x70, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x22, 0x65, 0x72, + 0x72, 0x6f, 0x3a, 0x20, 0x22, 0x20, 0x2b, 0x20, 0x72, 0x65, 0x73, 0x70, + 0x5b, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x5d, 0x2e, 0x67, 0x65, + 0x74, 0x28, 0x22, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x2c, + 0x20, 0x73, 0x74, 0x72, 0x28, 0x72, 0x65, 0x73, 0x70, 0x5b, 0x22, 0x65, + 0x72, 0x72, 0x6f, 0x72, 0x22, 0x5d, 0x29, 0x29, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x20, 0x3d, 0x20, 0x72, 0x65, + 0x73, 0x70, 0x2e, 0x67, 0x65, 0x74, 0x28, 0x22, 0x72, 0x65, 0x73, 0x75, + 0x6c, 0x74, 0x22, 0x2c, 0x20, 0x72, 0x65, 0x73, 0x70, 0x29, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x20, 0x3d, + 0x20, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x2e, 0x67, 0x65, 0x74, 0x28, + 0x22, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x22, 0x2c, 0x20, 0x72, + 0x65, 0x73, 0x75, 0x6c, 0x74, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, + 0x66, 0x20, 0x69, 0x73, 0x69, 0x6e, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, + 0x28, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2c, 0x20, 0x6c, 0x69, + 0x73, 0x74, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x70, 0x61, 0x72, 0x74, 0x73, 0x20, 0x3d, 0x20, 0x5b, 0x5d, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6f, 0x72, 0x20, + 0x69, 0x74, 0x65, 0x6d, 0x20, 0x69, 0x6e, 0x20, 0x63, 0x6f, 0x6e, 0x74, + 0x65, 0x6e, 0x74, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x69, 0x73, 0x69, 0x6e, + 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x28, 0x69, 0x74, 0x65, 0x6d, 0x2c, + 0x20, 0x64, 0x69, 0x63, 0x74, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x70, 0x61, 0x72, 0x74, 0x73, 0x2e, 0x61, 0x70, 0x70, 0x65, 0x6e, 0x64, + 0x28, 0x69, 0x74, 0x65, 0x6d, 0x2e, 0x67, 0x65, 0x74, 0x28, 0x22, 0x74, + 0x65, 0x78, 0x74, 0x22, 0x2c, 0x20, 0x6a, 0x73, 0x6f, 0x6e, 0x2e, 0x64, + 0x75, 0x6d, 0x70, 0x73, 0x28, 0x69, 0x74, 0x65, 0x6d, 0x29, 0x29, 0x29, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x65, 0x6c, 0x73, 0x65, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x70, + 0x61, 0x72, 0x74, 0x73, 0x2e, 0x61, 0x70, 0x70, 0x65, 0x6e, 0x64, 0x28, + 0x73, 0x74, 0x72, 0x28, 0x69, 0x74, 0x65, 0x6d, 0x29, 0x29, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, + 0x6e, 0x20, 0x22, 0x5c, 0x6e, 0x22, 0x2e, 0x6a, 0x6f, 0x69, 0x6e, 0x28, + 0x70, 0x61, 0x72, 0x74, 0x73, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72, + 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x6a, 0x73, 0x6f, 0x6e, 0x2e, 0x64, + 0x75, 0x6d, 0x70, 0x73, 0x28, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, + 0x2c, 0x20, 0x65, 0x6e, 0x73, 0x75, 0x72, 0x65, 0x5f, 0x61, 0x73, 0x63, + 0x69, 0x69, 0x3d, 0x46, 0x61, 0x6c, 0x73, 0x65, 0x2c, 0x20, 0x69, 0x6e, + 0x64, 0x65, 0x6e, 0x74, 0x3d, 0x32, 0x29, 0x0a +}; +unsigned int tb_mcp_py_len = 3728; diff --git a/libraries/tinyblocks-python/include/tinyblocks-python/tb_python.h b/libraries/tinyblocks-python/include/tinyblocks-python/tb_python.h new file mode 100644 index 0000000..636a745 --- /dev/null +++ b/libraries/tinyblocks-python/include/tinyblocks-python/tb_python.h @@ -0,0 +1,52 @@ +#ifndef TINYBLOCKS_PYTHON_H +#define TINYBLOCKS_PYTHON_H + +#include + +#ifdef _WIN32 +# define TB_PYTHON_API __declspec(dllexport) +#else +# define TB_PYTHON_API __attribute__((visibility("default"))) +#endif + +/* + * tb_python — wrapper fino sobre o interpretador CPython embutido. + * + * O interpretador é compartilhado em todo o processo (singleton ref-counted). + * Compile a lib como .so compartilhada para que python.so e mcp.so usem o + * mesmo intérprete: libtinyblocks-python.so. + */ + +TB_PYTHON_API bool tb_python_init(void); +TB_PYTHON_API void tb_python_deinit(void); + +/* + * Avalia uma expressão Python. + * names/vals: variáveis disponíveis no namespace (n itens). + * Retorna string heap-alocada com o resultado (caller frees) ou NULL em erro. + */ +TB_PYTHON_API char* tb_python_eval(const char* expr, + const char* const* names, + const double* vals, int n); + +/* + * Executa código Python arbitrário. + * Captura stdout+stderr e os retorna como string heap-alocada (caller frees). + */ +TB_PYTHON_API char* tb_python_run(const char* code); + +/* + * Executa código passando variáveis como locais (nome=valor float). + * Equivalente a tb_python_run mas com namespace preenchido. + */ +TB_PYTHON_API char* tb_python_run_with_vars(const char* code, + const char* const* names, + const double* vals, int n); + +/* + * Executa código no namespace __main__ (definições persistem entre chamadas). + * Retorna stdout+stderr capturado (caller frees). + */ +TB_PYTHON_API char* tb_python_exec_main(const char* code); + +#endif /* TINYBLOCKS_PYTHON_H */ diff --git a/libraries/tinyblocks-python/src/tb_python.c b/libraries/tinyblocks-python/src/tb_python.c new file mode 100644 index 0000000..3d5cb6e --- /dev/null +++ b/libraries/tinyblocks-python/src/tb_python.c @@ -0,0 +1,179 @@ +#define PY_SSIZE_T_CLEAN +#include + +#include +#include +#include + +#include "tinyblocks-python/tb_python.h" + +/* ── Singleton ref-counted ───────────────────────────────────────────────── */ +static int s_refs = 0; + +TB_PYTHON_API bool tb_python_init(void) { + if (s_refs++ > 0) return true; + if (Py_IsInitialized()) return true; + Py_Initialize(); + /* Garante que stdout/stderr padrão existam (modo embutido pode omití-los) */ + PyRun_SimpleString( + "import sys, io\n" + "if not hasattr(sys,'_tb_orig_stdout'):\n" + " sys._tb_orig_stdout = sys.stdout\n" + " sys._tb_orig_stderr = sys.stderr\n" + ); + return Py_IsInitialized(); +} + +TB_PYTHON_API void tb_python_deinit(void) { + if (s_refs <= 0) return; + if (--s_refs == 0 && Py_IsInitialized()) + Py_FinalizeEx(); +} + +/* ── Helper: captura stdout+stderr de uma execução ──────────────────────── */ +static char* capture_run(const char* code, PyObject* local_dict) { + /* StringIO para capturar output */ + PyObject* io = PyImport_ImportModule("io"); + PyObject* buf = PyObject_CallMethod(io, "StringIO", NULL); + PyObject* sys = PyImport_ImportModule("sys"); + PyObject_SetAttrString(sys, "stdout", buf); + PyObject_SetAttrString(sys, "stderr", buf); + + PyObject* globals = PyDict_New(); + PyObject* builtins = PyEval_GetBuiltins(); + PyDict_SetItemString(globals, "__builtins__", builtins); + + PyObject* result = PyRun_String(code, Py_file_input, globals, + local_dict ? local_dict : globals); + if (!result) { + PyErr_Print(); /* vai para buf via stderr */ + PyErr_Clear(); + } + Py_XDECREF(result); + Py_DECREF(globals); + + /* Restaura stdout/stderr */ + PyObject* orig_out = PyObject_GetAttrString(sys, "_tb_orig_stdout"); + PyObject* orig_err = PyObject_GetAttrString(sys, "_tb_orig_stderr"); + if (orig_out) PyObject_SetAttrString(sys, "stdout", orig_out); + if (orig_err) PyObject_SetAttrString(sys, "stderr", orig_err); + Py_XDECREF(orig_out); + Py_XDECREF(orig_err); + + PyObject* val = PyObject_CallMethod(buf, "getvalue", NULL); + const char* s = val ? PyUnicode_AsUTF8(val) : NULL; + char* out = strdup(s ? s : ""); + + Py_XDECREF(val); + Py_DECREF(buf); + Py_DECREF(io); + Py_DECREF(sys); + + return out; +} + +/* ── API pública ─────────────────────────────────────────────────────────── */ +TB_PYTHON_API char* tb_python_run(const char* code) { + if (!code || !Py_IsInitialized()) return strdup(""); + return capture_run(code, NULL); +} + +/* + * Executa código no namespace __main__ (definições persistem entre chamadas). + * Ideal para carregar módulos/funções que serão chamados depois. + */ +TB_PYTHON_API char* tb_python_exec_main(const char* code) { + if (!code || !Py_IsInitialized()) return strdup(""); + + PyObject* main_mod = PyImport_AddModule("__main__"); /* borrowed */ + PyObject* main_dict = PyModule_GetDict(main_mod); /* borrowed */ + + /* Redireciona stdout/stderr */ + PyObject* io = PyImport_ImportModule("io"); + PyObject* buf = PyObject_CallMethod(io, "StringIO", NULL); + PyObject* sys = PyImport_ImportModule("sys"); + PyObject_SetAttrString(sys, "stdout", buf); + PyObject_SetAttrString(sys, "stderr", buf); + + /* Executa com main_dict como globals E locals — definições persistem */ + PyObject* result = PyRun_String(code, Py_file_input, main_dict, main_dict); + if (!result) { PyErr_Print(); PyErr_Clear(); } + Py_XDECREF(result); + + /* Restaura stdout/stderr */ + PyObject* orig_out = PyObject_GetAttrString(sys, "_tb_orig_stdout"); + PyObject* orig_err = PyObject_GetAttrString(sys, "_tb_orig_stderr"); + if (orig_out) PyObject_SetAttrString(sys, "stdout", orig_out); + if (orig_err) PyObject_SetAttrString(sys, "stderr", orig_err); + Py_XDECREF(orig_out); + Py_XDECREF(orig_err); + + PyObject* val = PyObject_CallMethod(buf, "getvalue", NULL); + const char* s = val ? PyUnicode_AsUTF8(val) : NULL; + char* out = strdup(s ? s : ""); + + Py_XDECREF(val); + Py_DECREF(buf); + Py_DECREF(io); + Py_DECREF(sys); + + return out; +} + +TB_PYTHON_API char* tb_python_run_with_vars(const char* code, + const char* const* names, + const double* vals, int n) { + if (!code || !Py_IsInitialized()) return strdup(""); + + PyObject* locals = PyDict_New(); + for (int i = 0; i < n; i++) { + if (!names[i]) continue; + PyObject* v = PyFloat_FromDouble(vals[i]); + PyDict_SetItemString(locals, names[i], v); + Py_DECREF(v); + } + + char* out = capture_run(code, locals); + Py_DECREF(locals); + return out; +} + +TB_PYTHON_API char* tb_python_eval(const char* expr, + const char* const* names, const double* vals, int n) { + if (!expr || !Py_IsInitialized()) return strdup(""); + + PyObject* globals = PyDict_New(); + PyObject* builtins = PyEval_GetBuiltins(); + PyDict_SetItemString(globals, "__builtins__", builtins); + + for (int i = 0; i < n; i++) { + if (!names[i]) continue; + PyObject* v = PyFloat_FromDouble(vals[i]); + PyDict_SetItemString(globals, names[i], v); + Py_DECREF(v); + } + + PyObject* result = PyRun_String(expr, Py_eval_input, globals, globals); + char* out = NULL; + + if (result) { + PyObject* str = PyObject_Str(result); + const char* s = str ? PyUnicode_AsUTF8(str) : NULL; + out = strdup(s ? s : "None"); + Py_XDECREF(str); + Py_DECREF(result); + } else { + PyObject* exc = PyErr_GetRaisedException(); + PyObject* str = exc ? PyObject_Str(exc) : NULL; + const char* s = str ? PyUnicode_AsUTF8(str) : NULL; + char buf[256]; + snprintf(buf, sizeof(buf), "", s ? s : "?"); + out = strdup(buf); + Py_XDECREF(str); + Py_XDECREF(exc); + PyErr_Clear(); + } + + Py_DECREF(globals); + return out; +} diff --git a/libraries/tinyblocks-sdl2/Makefile b/libraries/tinyblocks-sdl2/Makefile new file mode 100644 index 0000000..c4afc09 --- /dev/null +++ b/libraries/tinyblocks-sdl2/Makefile @@ -0,0 +1,30 @@ +CC := gcc +CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \ + -I../../include \ + $(shell sdl2-config --cflags) +LDFLAGS := $(shell sdl2-config --libs) + +BUILD := ../../build +LIB_SO := $(BUILD)/libtinyblocks-sdl2.so +LIB_A := $(BUILD)/libtinyblocks-sdl2.a +OBJ := $(BUILD)/tb_sdl2.o + +.PHONY: all clean shared static + +all: shared static + +shared: $(LIB_SO) +static: $(LIB_A) + +$(OBJ): src/tb_sdl2.c include/tb_sdl2.h + @mkdir -p $(BUILD) + $(CC) $(CFLAGS) -fPIC -c src/tb_sdl2.c -o $@ + +$(LIB_SO): $(OBJ) + $(CC) -shared -o $@ $^ $(LDFLAGS) + +$(LIB_A): $(OBJ) + ar rcs $@ $^ + +clean: + $(RM) $(OBJ) $(LIB_SO) $(LIB_A) diff --git a/libraries/tinyblocks-sdl2/include/tb_sdl2.h b/libraries/tinyblocks-sdl2/include/tb_sdl2.h new file mode 100644 index 0000000..aac44c1 --- /dev/null +++ b/libraries/tinyblocks-sdl2/include/tb_sdl2.h @@ -0,0 +1,61 @@ +/* + * TinyBlocks — tb_sdl2.h + * + * TypeBlocks disponíveis após registrar esta library: + * + * SDL2.Events — expõe o estado de eventos do frame corrente (sem inputs; + * outputs pré-preenchidos pelo SDL2.App antes de cada on_draw) + * + * SDL2.App — cria janela, roda o loop principal, chama on_draw na scene. + * in: title(text), w(int), h(int), scene(block), events(block) + * + * Blocos primitivos (uso manual): + * SDL2.Init / SDL2.Quit + * SDL2.Window / SDL2.DestroyWindow + * SDL2.Renderer / SDL2.DestroyRenderer + * SDL2.SetDrawColor / SDL2.Clear / SDL2.FillRect / SDL2.DrawRect + * SDL2.Present / SDL2.Delay / SDL2.PollEvent + */ +#ifndef TINYBLOCKS_SDL2_H +#define TINYBLOCKS_SDL2_H + +#include + +TB_API const TinyBlocks_LibraryDescriptor* tb_sdl2_get_library(void); +TB_API const TinyBlocks_LibraryDescriptor* tinyblocks_get_library(void); + +/* Implementação do contrato de backend da interface tinyblocks-graphics + * (struct definida em tb_graphics.h; declarada aqui só por nome para que + * quem usa os blocos SDL2.* não precise do header da interface). */ +struct TinyBlocks_GraphicsBackend; +TB_API const struct TinyBlocks_GraphicsBackend* tb_sdl2_graphics_backend(void); + +/* ── Índices de output do bloco SDL2.Events ──────────────────────────────── */ +#define SDL2_EV_MOUSE_X 0 /* real: posição X do mouse */ +#define SDL2_EV_MOUSE_Y 1 /* real: posição Y do mouse */ +#define SDL2_EV_MOUSE_L_HELD 2 /* int: botão esquerdo pressionado (estado) */ +#define SDL2_EV_MOUSE_R_HELD 3 /* int: botão direito pressionado (estado) */ +#define SDL2_EV_MOUSE_L_DOWN 4 /* int: 1 se pressionado neste frame */ +#define SDL2_EV_MOUSE_L_UP 5 /* int: 1 se solto neste frame */ +#define SDL2_EV_MOUSE_R_DOWN 6 /* int: 1 se pressionado neste frame */ +#define SDL2_EV_MOUSE_R_UP 7 /* int: 1 se solto neste frame */ +#define SDL2_EV_SCROLL_DY 8 /* real: scroll vertical deste frame */ +#define SDL2_EV_KEY_SCANCODE 9 /* int: SDL_Scancode da tecla pressionada */ +#define SDL2_EV_KEY_MOD 10 /* int: SDL_Keymod (KMOD_CTRL etc.) */ +#define SDL2_EV_KEY_REPEAT 11 /* int: 1 se é repeat de key held */ +#define SDL2_EV_TEXT_INPUT 12 /* text: texto digitado neste frame */ +#define SDL2_EV_QUIT 13 /* int: 1 se janela foi fechada */ +#define SDL2_EV_WIN_W 14 /* int: largura atual da janela */ +#define SDL2_EV_WIN_H 15 /* int: altura atual da janela */ +#define SDL2_EV_DROP_FILE 16 /* text: caminho de arquivo arrastado */ +#define SDL2_EV_SCROLL_DX 17 /* real: scroll horizontal deste frame */ +#define SDL2_EV_MOD_STATE 18 /* int: SDL_GetModState() deste frame */ +#define SDL2_EV_COUNT 19 /* total de outputs */ + +/* ── Constantes de tipo de evento (SDL2.PollEvent legado) ───────────────── */ +#define TB_SDL2_EVENT_NONE 0 +#define TB_SDL2_EVENT_QUIT 256 +#define TB_SDL2_EVENT_KEYDOWN 768 +#define TB_SDL2_EVENT_KEYUP 769 + +#endif /* TINYBLOCKS_SDL2_H */ diff --git a/libraries/tinyblocks-sdl2/src/tb_sdl2.c b/libraries/tinyblocks-sdl2/src/tb_sdl2.c new file mode 100644 index 0000000..4cd2933 --- /dev/null +++ b/libraries/tinyblocks-sdl2/src/tb_sdl2.c @@ -0,0 +1,1089 @@ +/* + * TinyBlocks — tb_sdl2.c + * Backend SDL2 para TinyBlocks. + * + * Blocos principais: + * SDL2.Events — snapshot de eventos do frame, pré-preenchido pelo SDL2.App + * SDL2.App — janela + renderer + loop principal + executor de renderables + * + * Blocos primitivos legados: Init, Quit, Window, Renderer, etc. + * + * Também implementa o contrato TinyBlocks_GraphicsBackend da interface + * tinyblocks-graphics (várias janelas, entrada por janela, desenho com AA e + * medição de texto com a fonte real) — ver tb_sdl2_graphics_backend(). + */ + +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include "../include/tb_sdl2.h" + +/* ═══════════════════════════════════════════════════════════════════════════ + * Handles opacos de Window/Renderer (blocos wrapper) + * ═══════════════════════════════════════════════════════════════════════════ */ +static TinyBlocks_TypeBlock* s_type_window_handle = NULL; +static TinyBlocks_TypeBlock* s_type_renderer_handle = NULL; + +static TinyBlocks_Block* make_handle_block(TinyBlocks* rt, + TinyBlocks_TypeBlock* type, void* ptr) { + TinyBlocks_Block* b = tb_block_create(rt, type); + if (b) b->userdata = ptr; + return b; +} + +static void eval_handle_noop(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)self; (void)rt; +} + +/* ═══════════════════════════════════════════════════════════════════════════ + * Fonte TTF — cache por tamanho + * ═══════════════════════════════════════════════════════════════════════════ */ +#define FONT_CACHE_CAP 8 +#define FONT_SEARCH_COUNT 6 + +typedef struct { int size; TTF_Font* font; } FontEntry; + +static FontEntry s_font_cache[FONT_CACHE_CAP]; +static int s_font_cache_n = 0; + +static const char* s_font_paths[FONT_SEARCH_COUNT] = { + "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", + "/usr/share/fonts/TTF/DejaVuSans.ttf", + "/usr/share/fonts/dejavu/DejaVuSans.ttf", + "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", + "/usr/share/fonts/truetype/ubuntu/Ubuntu-R.ttf", + "/System/Library/Fonts/Helvetica.ttc", +}; + +static TTF_Font* get_font(int size) { + for (int i = 0; i < s_font_cache_n; i++) + if (s_font_cache[i].size == size) return s_font_cache[i].font; + + TTF_Font* f = NULL; + for (int i = 0; i < FONT_SEARCH_COUNT && !f; i++) + f = TTF_OpenFont(s_font_paths[i], size); + + if (f && s_font_cache_n < FONT_CACHE_CAP) { + s_font_cache[s_font_cache_n].size = size; + s_font_cache[s_font_cache_n].font = f; + s_font_cache_n++; + } + return f; +} + +static void fonts_close_all(void) { + for (int i = 0; i < s_font_cache_n; i++) { + TTF_CloseFont(s_font_cache[i].font); + s_font_cache[i].font = NULL; + } + s_font_cache_n = 0; +} + +/* ═══════════════════════════════════════════════════════════════════════════ + * Executor de TinyBlocks_RenderableBlock via SDL2 + * ═══════════════════════════════════════════════════════════════════════════ */ + +/* ── Rasterização com antialias ───────────────────────────────────────────── + * As formas preenchidas são varridas linha a linha com AA_SUB sub-linhas por + * pixel e cobertura horizontal exata. Cada pixel é pintado uma única vez, com + * alpha proporcional à cobertura: bordas suavizadas e sem overdraw (cores + * translúcidas ficam uniformes, inclusive nos cantos arredondados). */ +#define AA_SUB 4 + +typedef struct { Uint8 r, g, b, a; } Rgba; + +static Rgba rgba_of(const TinyBlocks_DrawCmd* cmd) { + return (Rgba){ (Uint8)(cmd->r*255.f + 0.5f), (Uint8)(cmd->g*255.f + 0.5f), + (Uint8)(cmd->b*255.f + 0.5f), (Uint8)(cmd->a*255.f + 0.5f) }; +} + +/* Preenche [x0,x1) x [y0,y1) com a cor c atenuada pela cobertura cov */ +static void aa_rect(SDL_Renderer* ren, Rgba c, int x0, int y0, int x1, int y1, float cov) { + if (x1 <= x0 || y1 <= y0 || cov <= 0.f) return; + Uint8 a = (Uint8)(c.a * (cov > 1.f ? 1.f : cov) + 0.5f); + if (!a) return; + SDL_SetRenderDrawColor(ren, c.r, c.g, c.b, a); + SDL_Rect rc = { x0, y0, x1 - x0, y1 - y0 }; + SDL_RenderFillRect(ren, &rc); +} + +/* Fração do pixel px coberta pelos intervalos [l,r] das sub-linhas */ +static float aa_cover(const float* l, const float* r, const bool* ok, int px) { + float s = 0.f; + for (int i = 0; i < AA_SUB; i++) { + if (!ok[i]) continue; + float a = l[i] > (float)px ? l[i] : (float)px; + float b = r[i] < (float)(px + 1) ? r[i] : (float)(px + 1); + if (b > a) s += b - a; + } + return s / AA_SUB; +} + +/* Uma linha de pixels de uma forma convexa: interior sólido + bordas parciais */ +static void aa_row(SDL_Renderer* ren, Rgba c, int py, const float* l, const float* r, const bool* ok) { + float L = 0.f, R = 0.f; + int sl = 0, sr = 0; + bool any = false, all = true; + for (int i = 0; i < AA_SUB; i++) { + if (!ok[i]) { all = false; continue; } + int cl = (int)ceilf(l[i]), fr = (int)floorf(r[i]); + if (!any) { L = l[i]; R = r[i]; sl = cl; sr = fr; any = true; continue; } + if (l[i] < L) L = l[i]; + if (r[i] > R) R = r[i]; + if (cl > sl) sl = cl; + if (fr < sr) sr = fr; + } + if (!any) return; + int x0 = (int)floorf(L), x1 = (int)ceilf(R); + if (!all || sl >= sr) sl = sr = x1; /* sem interior totalmente coberto */ + for (int px = x0; px < sl; px++) aa_rect(ren, c, px, py, px + 1, py + 1, aa_cover(l, r, ok, px)); + aa_rect(ren, c, sl, py, sr, py + 1, 1.f); + for (int px = sr; px < x1; px++) aa_rect(ren, c, px, py, px + 1, py + 1, aa_cover(l, r, ok, px)); +} + +/* Extensão horizontal de um retângulo arredondado na altura yc */ +static bool rrect_span(float x, float y, float w, float h, float rad, float yc, float* l, float* r) { + if (yc < y || yc > y + h) return false; + float d = 0.f; + if (yc < y + rad) d = y + rad - yc; + else if (yc > y + h - rad) d = yc - (y + h - rad); + float dx = d > 0.f ? rad - sqrtf(fmaxf(rad*rad - d*d, 0.f)) : 0.f; + *l = x + dx; *r = x + w - dx; + return *r > *l; +} + +static void aa_fill_rrect(SDL_Renderer* ren, Rgba c, float x, float y, float w, float h, float rad) { + if (w <= 0.f || h <= 0.f || !c.a) return; + if (rad < 0.f) rad = 0.f; + if (rad > w*0.5f) rad = w*0.5f; + if (rad > h*0.5f) rad = h*0.5f; + + /* Trecho reto do meio: um retângulo sólido + duas colunas de borda */ + int by0 = (int)ceilf(y + rad), by1 = (int)floorf(y + h - rad); + if (by1 > by0) { + int xl = (int)ceilf(x), xr = (int)floorf(x + w); + if (xr > xl) { + aa_rect(ren, c, xl, by0, xr, by1, 1.f); + aa_rect(ren, c, xl - 1, by0, xl, by1, (float)xl - x); + aa_rect(ren, c, xr, by0, xr + 1, by1, x + w - (float)xr); + } else { + aa_rect(ren, c, (int)floorf(x), by0, (int)floorf(x) + 1, by1, w); + } + } else { + by0 = by1 = 0; + } + + /* Cantos e bordas superior/inferior: varredura */ + float l[AA_SUB], r[AA_SUB]; bool ok[AA_SUB]; + for (int py = (int)floorf(y); py < (int)ceilf(y + h); py++) { + if (py >= by0 && py < by1) continue; + for (int i = 0; i < AA_SUB; i++) + ok[i] = rrect_span(x, y, w, h, rad, py + (i + 0.5f)/AA_SUB, &l[i], &r[i]); + aa_row(ren, c, py, l, r, ok); + } +} + +/* Extensão horizontal de um polígono convexo na altura yc */ +static bool poly_span(const float* px, const float* py, int n, float yc, float* l, float* r) { + bool hit = false; + float lo = 0.f, hi = 0.f; + for (int i = 0; i < n; i++) { + int j = (i + 1) % n; + float y0 = py[i], y1 = py[j]; + if (yc < fminf(y0, y1) || yc > fmaxf(y0, y1)) continue; + float xa, xb; + if (y1 == y0) { xa = fminf(px[i], px[j]); xb = fmaxf(px[i], px[j]); } + else { xa = xb = px[i] + (yc - y0)/(y1 - y0)*(px[j] - px[i]); } + if (!hit) { lo = xa; hi = xb; hit = true; } + else { lo = fminf(lo, xa); hi = fmaxf(hi, xb); } + } + *l = lo; *r = hi; + return hit && hi > lo; +} + +static void aa_fill_poly(SDL_Renderer* ren, Rgba c, const float* px, const float* py, int n) { + float y0 = py[0], y1 = py[0]; + for (int i = 1; i < n; i++) { y0 = fminf(y0, py[i]); y1 = fmaxf(y1, py[i]); } + float l[AA_SUB], r[AA_SUB]; bool ok[AA_SUB]; + for (int y = (int)floorf(y0); y < (int)ceilf(y1); y++) { + for (int i = 0; i < AA_SUB; i++) + ok[i] = poly_span(px, py, n, y + (i + 0.5f)/AA_SUB, &l[i], &r[i]); + aa_row(ren, c, y, l, r, ok); + } +} + +/* Linha com espessura: retângulo orientado, com meia espessura de "capa" + * nas pontas. As coordenadas são de pixel (o centro do pixel é +0.5). */ +static void aa_line(SDL_Renderer* ren, Rgba c, float x0, float y0, float x1, float y1, float thick) { + if (thick < 1.f) thick = 1.f; + x0 += 0.5f; y0 += 0.5f; x1 += 0.5f; y1 += 0.5f; + float dx = x1 - x0, dy = y1 - y0, len = sqrtf(dx*dx + dy*dy); + if (len < 1e-4f) { dx = 1.f; dy = 0.f; } else { dx /= len; dy /= len; } + float hx = dx*0.5f, hy = dy*0.5f; /* capa de meio pixel */ + float nx = -dy*thick*0.5f, ny = dx*thick*0.5f; /* normal */ + float qx[4] = { x0 - hx + nx, x1 + hx + nx, x1 + hx - nx, x0 - hx - nx }; + float qy[4] = { y0 - hy + ny, y1 + hy + ny, y1 + hy - ny, y0 - hy - ny }; + aa_fill_poly(ren, c, qx, qy, 4); +} + +/* Anel: círculo de raio rad menos o de raio rad - thick (por pixel) */ +static void aa_stroke_circle(SDL_Renderer* ren, Rgba c, float cx, float cy, float rad, float thick) { + if (rad <= 0.f || !c.a) return; + if (thick < 1.f) thick = 1.f; + float ri = rad - thick > 0.f ? rad - thick : 0.f; + float lo[AA_SUB], ro[AA_SUB], li[AA_SUB], rri[AA_SUB]; + bool oko[AA_SUB], oki[AA_SUB]; + for (int py = (int)floorf(cy - rad); py < (int)ceilf(cy + rad); py++) { + for (int i = 0; i < AA_SUB; i++) { + float yc = py + (i + 0.5f)/AA_SUB; + oko[i] = rrect_span(cx - rad, cy - rad, 2*rad, 2*rad, rad, yc, &lo[i], &ro[i]); + oki[i] = ri > 0.f && rrect_span(cx - ri, cy - ri, 2*ri, 2*ri, ri, yc, &li[i], &rri[i]); + } + for (int px = (int)floorf(cx - rad); px < (int)ceilf(cx + rad); px++) + aa_rect(ren, c, px, py, px + 1, py + 1, + aa_cover(lo, ro, oko, px) - aa_cover(li, rri, oki, px)); + } +} + +static void set_color(SDL_Renderer* ren, float r, float g, float b, float a) { + SDL_SetRenderDrawColor(ren, + (Uint8)(r*255.f), (Uint8)(g*255.f), + (Uint8)(b*255.f), (Uint8)(a*255.f)); +} + +static void sdl2_execute(SDL_Renderer* ren, + const TinyBlocks_RenderableBlock* rb) { + if (!ren || !rb) return; + SDL_SetRenderDrawBlendMode(ren, SDL_BLENDMODE_BLEND); + + for (uint32_t i = 0; i < rb->count; i++) { + const TinyBlocks_DrawCmd* cmd = &rb->cmds[i]; + switch (cmd->kind) { + + case TB_DRAW_CLEAR: + set_color(ren, cmd->r, cmd->g, cmd->b, cmd->a); + SDL_RenderClear(ren); + break; + + case TB_DRAW_FILL_RECT: + aa_fill_rrect(ren, rgba_of(cmd), cmd->x, cmd->y, cmd->w, cmd->h, 0.f); + break; + + case TB_DRAW_FILL_RRECT: + aa_fill_rrect(ren, rgba_of(cmd), cmd->x, cmd->y, cmd->w, cmd->h, cmd->param); + break; + + case TB_DRAW_FILL_CIRCLE: + aa_fill_rrect(ren, rgba_of(cmd), cmd->x - cmd->param, cmd->y - cmd->param, + 2*cmd->param, 2*cmd->param, cmd->param); + break; + + case TB_DRAW_STROKE_LINE: + aa_line(ren, rgba_of(cmd), cmd->x, cmd->y, cmd->w, cmd->h, cmd->param); + break; + + case TB_DRAW_STROKE_RECT: { + /* Quatro faixas sem sobreposição, espessura para dentro */ + Rgba c = rgba_of(cmd); + float t = cmd->param < 1.f ? 1.f : cmd->param; + float x = cmd->x, y = cmd->y, w = cmd->w, h = cmd->h; + if (2*t >= w || 2*t >= h) { aa_fill_rrect(ren, c, x, y, w, h, 0.f); break; } + aa_fill_rrect(ren, c, x, y, w, t, 0.f); + aa_fill_rrect(ren, c, x, y + h - t, w, t, 0.f); + aa_fill_rrect(ren, c, x, y + t, t, h - 2*t, 0.f); + aa_fill_rrect(ren, c, x + w - t, y + t, t, h - 2*t, 0.f); + break; + } + + case TB_DRAW_STROKE_CIRCLE: + aa_stroke_circle(ren, rgba_of(cmd), cmd->x, cmd->y, cmd->param, cmd->w); + break; + + case TB_DRAW_SET_CLIP: + { + SDL_Rect clip = {(int)cmd->x, (int)cmd->y, + (int)cmd->w, (int)cmd->h}; + SDL_RenderSetClipRect(ren, &clip); + } + break; + + case TB_DRAW_CLEAR_CLIP: + SDL_RenderSetClipRect(ren, NULL); + break; + + case TB_DRAW_TEXT: + if (cmd->text[0]) { + TTF_Font* font = get_font((int)cmd->font_size); + if (font) { + SDL_Color col = { + (Uint8)(cmd->r*255.f), (Uint8)(cmd->g*255.f), + (Uint8)(cmd->b*255.f), (Uint8)(cmd->a*255.f) + }; + SDL_Surface* surf = TTF_RenderUTF8_Blended(font, cmd->text, col); + if (surf) { + SDL_Texture* tex = SDL_CreateTextureFromSurface(ren, surf); + if (tex) { + /* cmd->x,cmd->y é baseline-left; converte para o + topo do retângulo usando o ascent real da fonte. */ + SDL_Rect dst = {(int)cmd->x, + (int)cmd->y - TTF_FontAscent(font), + surf->w, surf->h}; + SDL_RenderCopy(ren, tex, NULL, &dst); + SDL_DestroyTexture(tex); + } + SDL_FreeSurface(surf); + } + } + } + break; + } + } +} + +/* ═══════════════════════════════════════════════════════════════════════════ + * Backend da interface tinyblocks-graphics + * ═══════════════════════════════════════════════════════════════════════════ */ +typedef struct SdlWin { + SDL_Window* win; + SDL_Renderer* ren; + Uint32 id; + TinyBlocks_GfxInput in; + struct SdlWin* next; +} SdlWin; + +static SdlWin* s_wins = NULL; +static bool s_be_inited = false; + +static int map_key(SDL_Scancode sc) { + if (sc >= SDL_SCANCODE_A && sc <= SDL_SCANCODE_Z) return TB_KEY_A + (sc - SDL_SCANCODE_A); + if (sc >= SDL_SCANCODE_1 && sc <= SDL_SCANCODE_9) return TB_KEY_0 + 1 + (sc - SDL_SCANCODE_1); + if (sc >= SDL_SCANCODE_F1 && sc <= SDL_SCANCODE_F12) return TB_KEY_F1 + (sc - SDL_SCANCODE_F1); + switch (sc) { + case SDL_SCANCODE_0: return TB_KEY_0; + case SDL_SCANCODE_ESCAPE: return TB_KEY_ESCAPE; + case SDL_SCANCODE_RETURN: + case SDL_SCANCODE_KP_ENTER: return TB_KEY_RETURN; + case SDL_SCANCODE_BACKSPACE: return TB_KEY_BACKSPACE; + case SDL_SCANCODE_DELETE: + case SDL_SCANCODE_KP_PERIOD: return TB_KEY_DELETE; + case SDL_SCANCODE_TAB: return TB_KEY_TAB; + case SDL_SCANCODE_SPACE: return TB_KEY_SPACE; + case SDL_SCANCODE_LEFT: return TB_KEY_LEFT; + case SDL_SCANCODE_RIGHT: return TB_KEY_RIGHT; + case SDL_SCANCODE_UP: return TB_KEY_UP; + case SDL_SCANCODE_DOWN: return TB_KEY_DOWN; + case SDL_SCANCODE_HOME: return TB_KEY_HOME; + case SDL_SCANCODE_END: return TB_KEY_END; + default: return TB_KEY_OTHER; + } +} + +static int map_mod(Uint16 m) { + return ((m & KMOD_SHIFT) ? TB_MOD_SHIFT : 0) | + ((m & KMOD_CTRL) ? TB_MOD_CTRL : 0) | + ((m & KMOD_ALT) ? TB_MOD_ALT : 0); +} + +static SdlWin* win_by_id(Uint32 id) { + for (SdlWin* w = s_wins; w; w = w->next) if (w->id == id) return w; + return NULL; +} + +static bool be_init(void) { + if (s_be_inited) return true; + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0) { + fprintf(stderr, "tinyblocks-sdl2: SDL_Init: %s\n", SDL_GetError()); + return false; + } + if (TTF_Init() != 0) { + fprintf(stderr, "tinyblocks-sdl2: TTF_Init: %s\n", TTF_GetError()); + SDL_Quit(); + return false; + } + SDL_EventState(SDL_DROPFILE, SDL_ENABLE); + SDL_StartTextInput(); + s_be_inited = true; + return true; +} + +static void be_window_close(void* handle) { + SdlWin* w = (SdlWin*)handle; + for (SdlWin** pp = &s_wins; *pp; pp = &(*pp)->next) + if (*pp == w) { *pp = w->next; break; } + if (w->ren) SDL_DestroyRenderer(w->ren); + if (w->win) SDL_DestroyWindow(w->win); + free(w); +} + +static void be_shutdown(void) { + if (!s_be_inited) return; + while (s_wins) be_window_close(s_wins); + fonts_close_all(); + TTF_Quit(); + SDL_Quit(); + s_be_inited = false; +} + +static void* be_window_open(const char* title, int w, int h) { + if (!be_init()) return NULL; + SdlWin* sw = (SdlWin*)calloc(1, sizeof(SdlWin)); + if (!sw) return NULL; + sw->win = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, + w, h, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); + if (!sw->win) { + fprintf(stderr, "tinyblocks-sdl2: janela: %s\n", SDL_GetError()); + free(sw); + return NULL; + } + /* Sem vsync: com várias janelas cada present esperaria um retraço */ + sw->ren = SDL_CreateRenderer(sw->win, -1, SDL_RENDERER_ACCELERATED); + if (!sw->ren) sw->ren = SDL_CreateRenderer(sw->win, -1, SDL_RENDERER_SOFTWARE); + if (!sw->ren) { + fprintf(stderr, "tinyblocks-sdl2: renderer: %s\n", SDL_GetError()); + SDL_DestroyWindow(sw->win); + free(sw); + return NULL; + } + SDL_SetRenderDrawBlendMode(sw->ren, SDL_BLENDMODE_BLEND); + sw->id = SDL_GetWindowID(sw->win); + sw->in.win_w = w; sw->in.win_h = h; + sw->next = s_wins; + s_wins = sw; + return sw; +} + +/* Coleta os eventos do SO e distribui para a janela de cada evento */ +static void be_poll(void) { + for (SdlWin* w = s_wins; w; w = w->next) { + TinyBlocks_GfxInput* in = &w->in; + in->l_down = in->l_up = in->r_down = in->r_up = 0; + in->scroll_dx = in->scroll_dy = 0.f; + in->key = in->key_mod = in->key_repeat = 0; + in->text[0] = 0; + in->drop_file[0] = 0; + in->close = 0; + } + + SDL_Event ev; + while (SDL_PollEvent(&ev)) { + SdlWin* w = NULL; + switch (ev.type) { + case SDL_WINDOWEVENT: + if ((w = win_by_id(ev.window.windowID)) && ev.window.event == SDL_WINDOWEVENT_CLOSE) + w->in.close = 1; + break; + case SDL_MOUSEMOTION: + if ((w = win_by_id(ev.motion.windowID))) { + w->in.mouse_x = (float)ev.motion.x; + w->in.mouse_y = (float)ev.motion.y; + } + break; + case SDL_MOUSEBUTTONDOWN: + case SDL_MOUSEBUTTONUP: + if ((w = win_by_id(ev.button.windowID))) { + bool down = ev.type == SDL_MOUSEBUTTONDOWN; + w->in.mouse_x = (float)ev.button.x; + w->in.mouse_y = (float)ev.button.y; + if (ev.button.button == SDL_BUTTON_LEFT) { if (down) w->in.l_down = 1; else w->in.l_up = 1; } + if (ev.button.button == SDL_BUTTON_RIGHT) { if (down) w->in.r_down = 1; else w->in.r_up = 1; } + } + break; + case SDL_MOUSEWHEEL: + if ((w = win_by_id(ev.wheel.windowID))) { + w->in.scroll_dx += (float)ev.wheel.x; + w->in.scroll_dy += (float)ev.wheel.y; + } + break; + case SDL_KEYDOWN: + if ((w = win_by_id(ev.key.windowID))) { + w->in.key = map_key(ev.key.keysym.scancode); + w->in.key_mod = map_mod(ev.key.keysym.mod); + w->in.key_repeat = ev.key.repeat ? 1 : 0; + } + break; + case SDL_TEXTINPUT: + if ((w = win_by_id(ev.text.windowID))) { + size_t cur = strlen(w->in.text), add = strlen(ev.text.text); + if (cur + add < sizeof(w->in.text)) memcpy(w->in.text + cur, ev.text.text, add + 1); + } + break; + case SDL_DROPFILE: + if ((w = win_by_id(ev.drop.windowID)) && ev.drop.file) + snprintf(w->in.drop_file, sizeof(w->in.drop_file), "%s", ev.drop.file); + SDL_free(ev.drop.file); + break; + default: + break; + } + } + + /* Estado contínuo: botões segurados só valem na janela com o foco do mouse */ + SDL_Window* focus = SDL_GetMouseFocus(); + int mx, my; + Uint32 btns = SDL_GetMouseState(&mx, &my); + int mods = map_mod((Uint16)SDL_GetModState()); + for (SdlWin* w = s_wins; w; w = w->next) { + bool f = w->win == focus; + if (f) { w->in.mouse_x = (float)mx; w->in.mouse_y = (float)my; } + w->in.l_held = f && (btns & SDL_BUTTON_LMASK) ? 1 : 0; + w->in.r_held = f && (btns & SDL_BUTTON_RMASK) ? 1 : 0; + w->in.mod_state = mods; + SDL_GetWindowSize(w->win, &w->in.win_w, &w->in.win_h); + } +} + +static void be_window_input(void* handle, TinyBlocks_GfxInput* out) { + *out = ((SdlWin*)handle)->in; +} + +static void be_window_present(void* handle, const TinyBlocks_RenderableBlock* rb) { + SdlWin* w = (SdlWin*)handle; + SDL_SetRenderDrawColor(w->ren, 0, 0, 0, 255); + SDL_RenderClear(w->ren); + if (rb) sdl2_execute(w->ren, rb); + SDL_RenderPresent(w->ren); +} + +static float be_measure_text(const char* text, float font_size) { + if (!be_init()) return 0.f; + TTF_Font* font = get_font((int)(font_size + 0.5f)); + int w = 0, h = 0; + if (!font || TTF_SizeUTF8(font, text, &w, &h) != 0) return 0.f; + return (float)w; +} + +static void be_frame_wait(void) { SDL_Delay(14); } + +static const TinyBlocks_GraphicsBackend s_sdl2_backend = { + .name = "sdl2", + .init = be_init, + .shutdown = be_shutdown, + .window_open = be_window_open, + .window_close = be_window_close, + .poll = be_poll, + .window_input = be_window_input, + .window_present = be_window_present, + .measure_text = be_measure_text, + .frame_wait = be_frame_wait, +}; + +const TinyBlocks_GraphicsBackend* tb_sdl2_graphics_backend(void) { + return &s_sdl2_backend; +} + +/* Ponto de entrada quando esta library é carregada como backend (.so) */ +TB_API __attribute__((weak)) +const TinyBlocks_GraphicsBackend* tinyblocks_get_graphics_backend(void) { + return &s_sdl2_backend; +} + +/* ═══════════════════════════════════════════════════════════════════════════ + * SDL2.Events — snapshot de eventos do frame + * ═══════════════════════════════════════════════════════════════════════════ */ +static void eval_sdl2_events(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + /* Outputs são pré-preenchidos pelo SDL2.App antes de cada frame. + Se não há SDL2.App, inicializa com zeros/strings vazias. */ + for (uint32_t i = 0; i < self->output_count; i++) { + if (self->outputs[i].kind == TB_VALUE_NONE) { + if (i == SDL2_EV_MOUSE_X || i == SDL2_EV_MOUSE_Y || + i == SDL2_EV_SCROLL_DY || i == SDL2_EV_SCROLL_DX) + self->outputs[i] = tb_value_real(0.0); + else if (i == SDL2_EV_TEXT_INPUT || i == SDL2_EV_DROP_FILE) + self->outputs[i] = tb_value_text(""); + else + self->outputs[i] = tb_value_integer(0); + } + } + self->dirty = false; +} + +/* Preenche os outputs do bloco SDL2.Events com o estado de um frame */ +typedef struct { + float mouse_x, mouse_y; + int l_held, r_held; + int l_down, l_up, r_down, r_up; + float scroll_dy, scroll_dx; + int key_scancode, key_mod, key_repeat; + char text_input[64]; + int quit; + int win_w, win_h; + char drop_file[512]; + int mod_state; +} FrameEvents; + +static void events_push(TinyBlocks_Block* ev, const FrameEvents* fe) { + if (!ev || ev->output_count < SDL2_EV_COUNT) return; + +#define SET_R(idx, val) do { tb_value_free(&ev->outputs[idx]); \ + ev->outputs[idx] = tb_value_real((double)(val)); } while(0) +#define SET_I(idx, val) do { tb_value_free(&ev->outputs[idx]); \ + ev->outputs[idx] = tb_value_integer((int64_t)(val)); } while(0) +#define SET_T(idx, val) do { tb_value_free(&ev->outputs[idx]); \ + ev->outputs[idx] = tb_value_text(val); } while(0) + + SET_R(SDL2_EV_MOUSE_X, fe->mouse_x); + SET_R(SDL2_EV_MOUSE_Y, fe->mouse_y); + SET_I(SDL2_EV_MOUSE_L_HELD, fe->l_held); + SET_I(SDL2_EV_MOUSE_R_HELD, fe->r_held); + SET_I(SDL2_EV_MOUSE_L_DOWN, fe->l_down); + SET_I(SDL2_EV_MOUSE_L_UP, fe->l_up); + SET_I(SDL2_EV_MOUSE_R_DOWN, fe->r_down); + SET_I(SDL2_EV_MOUSE_R_UP, fe->r_up); + SET_R(SDL2_EV_SCROLL_DY, fe->scroll_dy); + SET_I(SDL2_EV_KEY_SCANCODE, fe->key_scancode); + SET_I(SDL2_EV_KEY_MOD, fe->key_mod); + SET_I(SDL2_EV_KEY_REPEAT, fe->key_repeat); + SET_T(SDL2_EV_TEXT_INPUT, fe->text_input); + SET_I(SDL2_EV_QUIT, fe->quit); + SET_I(SDL2_EV_WIN_W, fe->win_w); + SET_I(SDL2_EV_WIN_H, fe->win_h); + SET_T(SDL2_EV_DROP_FILE, fe->drop_file); + SET_R(SDL2_EV_SCROLL_DX, fe->scroll_dx); + SET_I(SDL2_EV_MOD_STATE, fe->mod_state); + +#undef SET_R +#undef SET_I +#undef SET_T + + ev->dirty = false; +} + +/* ═══════════════════════════════════════════════════════════════════════════ + * SDL2.App — janela + loop principal + * ═══════════════════════════════════════════════════════════════════════════ */ +typedef struct { + SDL_Window* win; + SDL_Renderer* ren; +} AppState; + +static bool app_init(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + AppState* s = (AppState*)self->userdata; + s->win = NULL; s->ren = NULL; + return true; +} + +static void app_deinit(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + AppState* s = (AppState*)self->userdata; + if (s->ren) { SDL_DestroyRenderer(s->ren); s->ren = NULL; } + if (s->win) { SDL_DestroyWindow(s->win); s->win = NULL; } +} + +static void eval_sdl2_app(TinyBlocks_Block* self, TinyBlocks* rt) { + AppState* s = (AppState*)self->userdata; + + /* inputs: 0=title, 1=w, 2=h, 3=scene(block), 4=events(block) */ + TinyBlocks_Value vtitle = tb_block_get_input(self, rt, 0); + TinyBlocks_Value vw = tb_block_get_input(self, rt, 1); + TinyBlocks_Value vh = tb_block_get_input(self, rt, 2); + TinyBlocks_Value vscene = tb_block_get_input(self, rt, 3); + TinyBlocks_Value vevents = tb_block_get_input(self, rt, 4); + + const char* title = (vtitle.kind == TB_VALUE_TEXT && vtitle.as.text) + ? vtitle.as.text : "TinyBlocks"; + int win_w = (int)(vw.kind == TB_VALUE_INTEGER ? vw.as.integer : 1280); + int win_h = (int)(vh.kind == TB_VALUE_INTEGER ? vh.as.integer : 720); + + TinyBlocks_Block* scene = (vscene.kind == TB_VALUE_BLOCK) ? vscene.as.block : NULL; + TinyBlocks_Block* ev_blk = (vevents.kind == TB_VALUE_BLOCK) ? vevents.as.block : NULL; + + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0) { + fprintf(stderr, "SDL2.App SDL_Init: %s\n", SDL_GetError()); + return; + } + if (TTF_Init() != 0) { + fprintf(stderr, "SDL2.App TTF_Init: %s\n", TTF_GetError()); + SDL_Quit(); return; + } + + s->win = SDL_CreateWindow(title, + SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, + win_w, win_h, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); + if (!s->win) { + fprintf(stderr, "SDL2.App window: %s\n", SDL_GetError()); + TTF_Quit(); SDL_Quit(); return; + } + + s->ren = SDL_CreateRenderer(s->win, -1, + SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); + if (!s->ren) + s->ren = SDL_CreateRenderer(s->win, -1, SDL_RENDERER_SOFTWARE); + if (!s->ren) { + fprintf(stderr, "SDL2.App renderer: %s\n", SDL_GetError()); + SDL_DestroyWindow(s->win); s->win = NULL; + TTF_Quit(); SDL_Quit(); return; + } + + SDL_SetRenderDrawBlendMode(s->ren, SDL_BLENDMODE_BLEND); + SDL_EventState(SDL_DROPFILE, SDL_ENABLE); + SDL_StartTextInput(); + + FrameEvents fe; + bool quit = false; + + while (!quit) { + memset(&fe, 0, sizeof(fe)); + + /* Coleta todos os eventos do frame */ + SDL_Event ev; + while (SDL_PollEvent(&ev)) { + switch (ev.type) { + case SDL_QUIT: + fe.quit = 1; quit = true; + break; + case SDL_MOUSEBUTTONDOWN: + if (ev.button.button == SDL_BUTTON_LEFT) fe.l_down = 1; + if (ev.button.button == SDL_BUTTON_RIGHT) fe.r_down = 1; + break; + case SDL_MOUSEBUTTONUP: + if (ev.button.button == SDL_BUTTON_LEFT) fe.l_up = 1; + if (ev.button.button == SDL_BUTTON_RIGHT) fe.r_up = 1; + break; + case SDL_MOUSEWHEEL: + fe.scroll_dy += (float)ev.wheel.y; + fe.scroll_dx += (float)ev.wheel.x; + break; + case SDL_KEYDOWN: + fe.key_scancode = (int)ev.key.keysym.scancode; + fe.key_mod = (int)ev.key.keysym.mod; + fe.key_repeat = ev.key.repeat ? 1 : 0; + break; + case SDL_TEXTINPUT: { + size_t cur = strlen(fe.text_input); + size_t add = strlen(ev.text.text); + if (cur + add < sizeof(fe.text_input) - 1) + strcat(fe.text_input, ev.text.text); + break; + } + case SDL_DROPFILE: + if (ev.drop.file) { + strncpy(fe.drop_file, ev.drop.file, + sizeof(fe.drop_file) - 1); + SDL_free(ev.drop.file); + } + break; + default: break; + } + } + + /* Estado contínuo do mouse */ + { + int mx, my; + Uint32 btns = SDL_GetMouseState(&mx, &my); + fe.mouse_x = (float)mx; + fe.mouse_y = (float)my; + fe.l_held = (btns & SDL_BUTTON_LMASK) ? 1 : 0; + fe.r_held = (btns & SDL_BUTTON_RMASK) ? 1 : 0; + } + + /* Tamanho atual da janela e estado dos modificadores */ + SDL_GetWindowSize(s->win, &fe.win_w, &fe.win_h); + fe.mod_state = (int)SDL_GetModState(); + + /* Preenche o bloco SDL2.Events */ + if (ev_blk) events_push(ev_blk, &fe); + + /* Avalia a cena e obtém renderable */ + TinyBlocks_RenderableBlock* rb = NULL; + if (scene) { + scene->dirty = true; + tb_block_eval(scene, rt); + if (scene->type && scene->type->on_draw) + scene->type->on_draw(scene, rt, &rb); + } + + /* Renderiza */ + SDL_SetRenderDrawColor(s->ren, 30, 30, 46, 255); + SDL_RenderClear(s->ren); + if (rb) sdl2_execute(s->ren, rb); + SDL_RenderPresent(s->ren); + + /* Libera os renderables adquiridos neste frame */ + tb_renderable_release_all(); + + SDL_Delay(14); + } + + fonts_close_all(); + TTF_Quit(); + SDL_DestroyRenderer(s->ren); s->ren = NULL; + SDL_DestroyWindow(s->win); s->win = NULL; + SDL_Quit(); + + self->dirty = false; +} + +/* ═══════════════════════════════════════════════════════════════════════════ + * Blocos primitivos legados + * ═══════════════════════════════════════════════════════════════════════════ */ +static void eval_sdl2_init(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)self; + if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_EVENTS) != 0) + tinyblocks_set_error(rt, "SDL2.Init: %s", SDL_GetError()); +} +static void eval_sdl2_quit(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)self; (void)rt; SDL_Quit(); +} +static void eval_sdl2_window(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value vtitle = tb_block_get_input(self, rt, 0); + TinyBlocks_Value vx = tb_block_get_input(self, rt, 1); + TinyBlocks_Value vy = tb_block_get_input(self, rt, 2); + TinyBlocks_Value vw = tb_block_get_input(self, rt, 3); + TinyBlocks_Value vh = tb_block_get_input(self, rt, 4); + const char* title = vtitle.kind==TB_VALUE_TEXT ? vtitle.as.text : "TinyBlocks"; + int x = (int)(vx.kind==TB_VALUE_INTEGER ? vx.as.integer : SDL_WINDOWPOS_CENTERED); + int y = (int)(vy.kind==TB_VALUE_INTEGER ? vy.as.integer : SDL_WINDOWPOS_CENTERED); + int w = (int)(vw.kind==TB_VALUE_INTEGER ? vw.as.integer : 800); + int h = (int)(vh.kind==TB_VALUE_INTEGER ? vh.as.integer : 600); + SDL_Window* win = SDL_CreateWindow(title, x, y, w, h, SDL_WINDOW_SHOWN); + if (!win) { tinyblocks_set_error(rt,"SDL2.Window: %s",SDL_GetError()); return; } + tb_block_set_output(self, 0, tb_value_block(make_handle_block(rt, s_type_window_handle, win))); +} +static void eval_sdl2_destroy_window(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + if (v.kind==TB_VALUE_BLOCK && v.as.block) { + SDL_DestroyWindow((SDL_Window*)v.as.block->userdata); + v.as.block->userdata = NULL; + } +} +static void eval_sdl2_renderer(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + if (v.kind!=TB_VALUE_BLOCK || !v.as.block) return; + SDL_Window* win = (SDL_Window*)v.as.block->userdata; + SDL_Renderer* ren = SDL_CreateRenderer(win, -1, + SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC); + if (!ren) ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_SOFTWARE); + if (!ren) { tinyblocks_set_error(rt,"SDL2.Renderer: %s",SDL_GetError()); return; } + tb_block_set_output(self, 0, tb_value_block(make_handle_block(rt, s_type_renderer_handle, ren))); +} +static void eval_sdl2_destroy_renderer(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + if (v.kind==TB_VALUE_BLOCK && v.as.block) { + SDL_DestroyRenderer((SDL_Renderer*)v.as.block->userdata); + v.as.block->userdata = NULL; + } +} +static SDL_Renderer* get_ren(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) { + TinyBlocks_Value v = tb_block_get_input(self, rt, idx); + return (v.kind==TB_VALUE_BLOCK && v.as.block) ? (SDL_Renderer*)v.as.block->userdata : NULL; +} +static void eval_sdl2_set_draw_color(TinyBlocks_Block* self, TinyBlocks* rt) { + SDL_Renderer* ren = get_ren(self, rt, 0); if (!ren) return; + TinyBlocks_Value vr=tb_block_get_input(self,rt,1), vg=tb_block_get_input(self,rt,2); + TinyBlocks_Value vb=tb_block_get_input(self,rt,3), va=tb_block_get_input(self,rt,4); + SDL_SetRenderDrawColor(ren, + (Uint8)(vr.kind==TB_VALUE_INTEGER?vr.as.integer:0), + (Uint8)(vg.kind==TB_VALUE_INTEGER?vg.as.integer:0), + (Uint8)(vb.kind==TB_VALUE_INTEGER?vb.as.integer:0), + (Uint8)(va.kind==TB_VALUE_INTEGER?va.as.integer:255)); +} +static void eval_sdl2_clear(TinyBlocks_Block* self, TinyBlocks* rt) { + SDL_Renderer* ren = get_ren(self, rt, 0); if (ren) SDL_RenderClear(ren); +} +static void eval_sdl2_fill_rect(TinyBlocks_Block* self, TinyBlocks* rt) { + SDL_Renderer* ren = get_ren(self, rt, 0); if (!ren) return; + TinyBlocks_Value vx=tb_block_get_input(self,rt,1), vy=tb_block_get_input(self,rt,2); + TinyBlocks_Value vw=tb_block_get_input(self,rt,3), vh=tb_block_get_input(self,rt,4); + SDL_Rect rc={ + (int)(vx.kind==TB_VALUE_INTEGER?vx.as.integer:0), + (int)(vy.kind==TB_VALUE_INTEGER?vy.as.integer:0), + (int)(vw.kind==TB_VALUE_INTEGER?vw.as.integer:100), + (int)(vh.kind==TB_VALUE_INTEGER?vh.as.integer:100)}; + SDL_RenderFillRect(ren, &rc); +} +static void eval_sdl2_draw_rect(TinyBlocks_Block* self, TinyBlocks* rt) { + SDL_Renderer* ren = get_ren(self, rt, 0); if (!ren) return; + TinyBlocks_Value vx=tb_block_get_input(self,rt,1), vy=tb_block_get_input(self,rt,2); + TinyBlocks_Value vw=tb_block_get_input(self,rt,3), vh=tb_block_get_input(self,rt,4); + SDL_Rect rc={ + (int)(vx.kind==TB_VALUE_INTEGER?vx.as.integer:0), + (int)(vy.kind==TB_VALUE_INTEGER?vy.as.integer:0), + (int)(vw.kind==TB_VALUE_INTEGER?vw.as.integer:100), + (int)(vh.kind==TB_VALUE_INTEGER?vh.as.integer:100)}; + SDL_RenderDrawRect(ren, &rc); +} +static void eval_sdl2_present(TinyBlocks_Block* self, TinyBlocks* rt) { + SDL_Renderer* ren = get_ren(self, rt, 0); if (ren) SDL_RenderPresent(ren); +} +static void eval_sdl2_delay(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + SDL_Delay((Uint32)(v.kind==TB_VALUE_INTEGER && v.as.integer>0 ? v.as.integer : 0)); +} +static void eval_sdl2_poll_event(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + SDL_Event ev; + if (SDL_PollEvent(&ev)) { + tb_block_set_output(self, 0, tb_value_integer((int64_t)ev.type)); + tb_block_set_output(self, 1, tb_value_integer(ev.type==SDL_QUIT?1:0)); + int64_t sc = (ev.type==SDL_KEYDOWN||ev.type==SDL_KEYUP) + ? (int64_t)ev.key.keysym.scancode : 0; + tb_block_set_output(self, 2, tb_value_integer(sc)); + } else { + tb_block_set_output(self, 0, tb_value_integer(TB_SDL2_EVENT_NONE)); + tb_block_set_output(self, 1, tb_value_integer(0)); + tb_block_set_output(self, 2, tb_value_integer(0)); + } +} + +/* ═══════════════════════════════════════════════════════════════════════════ + * Registro da library + * ═══════════════════════════════════════════════════════════════════════════ */ +static bool sdl2_lib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + s_type_window_handle = tb_type_block_create(rt, "SDL2._WindowHandle", + NULL,0,NULL,0, eval_handle_noop); + s_type_renderer_handle = tb_type_block_create(rt, "SDL2._RendererHandle", + NULL,0,NULL,0, eval_handle_noop); + if (!s_type_window_handle || !s_type_renderer_handle) return false; + +#define IN(n,k) { .name=(n), .expected_kind=(k) } +#define BLOCK_IN(n) IN(n, TB_VALUE_BLOCK) +#define INT_IN(n) IN(n, TB_VALUE_INTEGER) +#define TEXT_IN(n) IN(n, TB_VALUE_TEXT) +#define OUT(n,k) { .name=(n), .expected_kind=(k) } + + /* SDL2.Events */ + { + static const TinyBlocks_SlotDesc outs[SDL2_EV_COUNT] = { + OUT("mouse_x", TB_VALUE_REAL), + OUT("mouse_y", TB_VALUE_REAL), + OUT("mouse_l_held", TB_VALUE_INTEGER), + OUT("mouse_r_held", TB_VALUE_INTEGER), + OUT("mouse_l_down", TB_VALUE_INTEGER), + OUT("mouse_l_up", TB_VALUE_INTEGER), + OUT("mouse_r_down", TB_VALUE_INTEGER), + OUT("mouse_r_up", TB_VALUE_INTEGER), + OUT("scroll_dy", TB_VALUE_REAL), + OUT("key_scancode", TB_VALUE_INTEGER), + OUT("key_mod", TB_VALUE_INTEGER), + OUT("key_repeat", TB_VALUE_INTEGER), + OUT("text_input", TB_VALUE_TEXT), + OUT("quit", TB_VALUE_INTEGER), + OUT("win_w", TB_VALUE_INTEGER), + OUT("win_h", TB_VALUE_INTEGER), + OUT("drop_file", TB_VALUE_TEXT), + OUT("scroll_dx", TB_VALUE_REAL), + OUT("mod_state", TB_VALUE_INTEGER), + }; + TinyBlocks_TypeBlock* t = tb_type_block_create(rt, "SDL2.Events", + NULL, 0, outs, SDL2_EV_COUNT, eval_sdl2_events); + if (!t) return false; + tb_library_add(lib, &t->base); + } + + /* SDL2.App */ + { + static const TinyBlocks_SlotDesc ins[] = { + TEXT_IN("title"), + INT_IN("w"), + INT_IN("h"), + IN("scene", TB_VALUE_BLOCK), + IN("events", TB_VALUE_BLOCK), + }; + TinyBlocks_TypeBlock* t = tb_type_block_create(rt, "SDL2.App", + ins, 5, NULL, 0, eval_sdl2_app); + if (!t) return false; + tb_type_block_set_instance_hooks(t, sizeof(AppState), app_init, app_deinit); + tb_library_add(lib, &t->base); + } + + /* Blocos primitivos legados */ + { + TinyBlocks_TypeBlock* t = tb_type_block_create(rt,"SDL2.Init",NULL,0,NULL,0,eval_sdl2_init); + if (t) tb_library_add(lib, &t->base); + } + { + TinyBlocks_TypeBlock* t = tb_type_block_create(rt,"SDL2.Quit",NULL,0,NULL,0,eval_sdl2_quit); + if (t) tb_library_add(lib, &t->base); + } + { + static const TinyBlocks_SlotDesc ins[]={TEXT_IN("title"),INT_IN("x"),INT_IN("y"),INT_IN("w"),INT_IN("h")}; + static const TinyBlocks_SlotDesc outs[]={OUT("window",TB_VALUE_BLOCK)}; + TinyBlocks_TypeBlock* t=tb_type_block_create(rt,"SDL2.Window",ins,5,outs,1,eval_sdl2_window); + if (t) tb_library_add(lib, &t->base); + } + { + static const TinyBlocks_SlotDesc ins[]={BLOCK_IN("window")}; + TinyBlocks_TypeBlock* t=tb_type_block_create(rt,"SDL2.DestroyWindow",ins,1,NULL,0,eval_sdl2_destroy_window); + if (t) tb_library_add(lib, &t->base); + } + { + static const TinyBlocks_SlotDesc ins[]={BLOCK_IN("window")}; + static const TinyBlocks_SlotDesc outs[]={OUT("renderer",TB_VALUE_BLOCK)}; + TinyBlocks_TypeBlock* t=tb_type_block_create(rt,"SDL2.Renderer",ins,1,outs,1,eval_sdl2_renderer); + if (t) tb_library_add(lib, &t->base); + } + { + static const TinyBlocks_SlotDesc ins[]={BLOCK_IN("renderer")}; + TinyBlocks_TypeBlock* t=tb_type_block_create(rt,"SDL2.DestroyRenderer",ins,1,NULL,0,eval_sdl2_destroy_renderer); + if (t) tb_library_add(lib, &t->base); + } + { + static const TinyBlocks_SlotDesc ins[]={BLOCK_IN("renderer"),INT_IN("r"),INT_IN("g"),INT_IN("b"),INT_IN("a")}; + TinyBlocks_TypeBlock* t=tb_type_block_create(rt,"SDL2.SetDrawColor",ins,5,NULL,0,eval_sdl2_set_draw_color); + if (t) tb_library_add(lib, &t->base); + } + { + static const TinyBlocks_SlotDesc ins[]={BLOCK_IN("renderer")}; + TinyBlocks_TypeBlock* t=tb_type_block_create(rt,"SDL2.Clear",ins,1,NULL,0,eval_sdl2_clear); + if (t) tb_library_add(lib, &t->base); + } + { + static const TinyBlocks_SlotDesc ins[]={BLOCK_IN("renderer"),INT_IN("x"),INT_IN("y"),INT_IN("w"),INT_IN("h")}; + TinyBlocks_TypeBlock* t=tb_type_block_create(rt,"SDL2.FillRect",ins,5,NULL,0,eval_sdl2_fill_rect); + if (t) tb_library_add(lib, &t->base); + } + { + static const TinyBlocks_SlotDesc ins[]={BLOCK_IN("renderer"),INT_IN("x"),INT_IN("y"),INT_IN("w"),INT_IN("h")}; + TinyBlocks_TypeBlock* t=tb_type_block_create(rt,"SDL2.DrawRect",ins,5,NULL,0,eval_sdl2_draw_rect); + if (t) tb_library_add(lib, &t->base); + } + { + static const TinyBlocks_SlotDesc ins[]={BLOCK_IN("renderer")}; + TinyBlocks_TypeBlock* t=tb_type_block_create(rt,"SDL2.Present",ins,1,NULL,0,eval_sdl2_present); + if (t) tb_library_add(lib, &t->base); + } + { + static const TinyBlocks_SlotDesc ins[]={INT_IN("ms")}; + TinyBlocks_TypeBlock* t=tb_type_block_create(rt,"SDL2.Delay",ins,1,NULL,0,eval_sdl2_delay); + if (t) tb_library_add(lib, &t->base); + } + { + static const TinyBlocks_SlotDesc outs[]={ + OUT("type",TB_VALUE_INTEGER),OUT("quit",TB_VALUE_INTEGER), + OUT("key_scancode",TB_VALUE_INTEGER)}; + TinyBlocks_TypeBlock* t=tb_type_block_create(rt,"SDL2.PollEvent",NULL,0,outs,3,eval_sdl2_poll_event); + if (t) tb_library_add(lib, &t->base); + } + +#undef IN +#undef BLOCK_IN +#undef INT_IN +#undef TEXT_IN +#undef OUT + + return true; +} + +static void sdl2_lib_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + (void)rt; (void)lib; + s_type_window_handle = NULL; + s_type_renderer_handle = NULL; +} + +TINYBLOCKS_DEFINE_LIBRARY(sdl2, "tinyblocks-sdl2", "2.0.0", + sdl2_lib_init, sdl2_lib_deinit) + +const TinyBlocks_LibraryDescriptor* tb_sdl2_get_library(void) { + return &_tb_lib_desc_sdl2; +} diff --git a/src/tb_block.c b/src/tb_block.c new file mode 100644 index 0000000..17370c1 --- /dev/null +++ b/src/tb_block.c @@ -0,0 +1,252 @@ +#include +#include +#include "tinyblocks/tinyblocks.h" + +/* ── Alocação da estrutura base ──────────────────────────────────────────── */ +TinyBlocks_Block* tb_block_alloc_base(TinyBlocks* rt, + TinyBlocks_BlockKind kind, + size_t struct_size, + uint32_t input_count, + uint32_t output_count, + const TinyBlocks_BlockVTable* vtable) +{ + TinyBlocks_Block* b = tb_alloc(rt, struct_size); + if (!b) return NULL; + + b->kind = kind; + b->vtable = vtable; + b->id = tb_rt_next_id(rt); + b->input_count = input_count; + b->output_count = output_count; + b->dirty = true; + + if (input_count > 0) { + b->inputs = tb_alloc(rt, input_count * sizeof(TinyBlocks_Connection)); + if (!b->inputs) { tb_free(rt, b); return NULL; } + } + if (output_count > 0) { + b->outputs = tb_alloc(rt, output_count * sizeof(TinyBlocks_Value)); + if (!b->outputs) { tb_free(rt, b->inputs); tb_free(rt, b); return NULL; } + } + + tb_rt_register_block(rt, b); + return b; +} + +/* ── Vtable padrão para blocos definidos por TypeBlock ───────────────────── */ +static void default_eval(TinyBlocks_Block* self, TinyBlocks* rt) +{ + if (self->type && self->type->eval_fn) + self->type->eval_fn(self, rt); + self->dirty = false; +} + +static void default_destroy(TinyBlocks_Block* self, TinyBlocks* rt) +{ + if (self->type && self->type->instance_deinit) + self->type->instance_deinit(self, rt); + tb_free(rt, self->userdata); +} + +static size_t default_to_string(TinyBlocks_Block* self, TinyBlocks* rt, + char* buf, size_t buf_size) +{ + (void)rt; + const char* tname = self->type ? self->type->type_name : "Block"; + const char* bname = self->name ? self->name : ""; + return (size_t)snprintf(buf, buf_size, + "[%s#%llu%s%s]", + tname, (unsigned long long)self->id, + bname[0] ? " " : "", bname); +} + +static TinyBlocks_Block* default_clone(const TinyBlocks_Block* self, TinyBlocks* rt) +{ + TinyBlocks_Block* c = tb_block_create(rt, self->type); + if (!c) return NULL; + if (self->name) c->name = tb_strdup(rt, self->name); + /* copia conexões */ + memcpy(c->inputs, self->inputs, self->input_count * sizeof(TinyBlocks_Connection)); + /* copia outputs */ + for (uint32_t i = 0; i < self->output_count; ++i) + c->outputs[i] = tb_value_clone(self->outputs[i]); + return c; +} + +static const TinyBlocks_BlockVTable s_default_vtable = { + .eval = default_eval, + .destroy = default_destroy, + .to_string = default_to_string, + .clone = default_clone, +}; + +/* ── Criação via TypeBlock ───────────────────────────────────────────────── */ +TinyBlocks_Block* tb_block_create(TinyBlocks* rt, TinyBlocks_TypeBlock* type) +{ + if (!type) { + tinyblocks_set_error(rt, "tb_block_create: type is NULL"); + return NULL; + } + + TinyBlocks_Block* b = tb_block_alloc_base(rt, + TB_KIND_BLOCK, + sizeof(TinyBlocks_Block), + type->input_desc_count, + type->output_desc_count, + &s_default_vtable); + if (!b) return NULL; + + b->type = type; + + /* Inicializa userdata por instância */ + if (type->instance_userdata_size > 0) { + b->userdata = tb_alloc(rt, type->instance_userdata_size); + if (!b->userdata) { + tb_block_destroy(b, rt); + return NULL; + } + } + + if (type->instance_init && !type->instance_init(b, rt)) { + tb_block_destroy(b, rt); + return NULL; + } + + return b; +} + +/* ── Destruição ──────────────────────────────────────────────────────────── */ +void tb_block_destroy(TinyBlocks_Block* block, TinyBlocks* rt) +{ + if (!block) return; + tb_rt_unregister_block(rt, block); + + if (block->vtable && block->vtable->destroy) + block->vtable->destroy(block, rt); + + tb_free(rt, block->name); + + /* Libera valores de default dos inputs */ + for (uint32_t i = 0; i < block->input_count; ++i) + tb_value_free(&block->inputs[i].default_value); + tb_free(rt, block->inputs); + + for (uint32_t i = 0; i < block->output_count; ++i) + tb_value_free(&block->outputs[i]); + tb_free(rt, block->outputs); + + tb_free(rt, block); +} + +/* ── Avaliação ───────────────────────────────────────────────────────────── */ +void tb_block_eval(TinyBlocks_Block* block, TinyBlocks* rt) +{ + if (!block || !block->vtable || !block->vtable->eval) return; + + /* Detecta ciclo: bloco já está sendo avaliado nesta chamada recursiva */ + if (block->in_eval) { + tinyblocks_set_error(rt, "ciclo detectado em '%s' — conexão ignorada", + block->type ? block->type->type_name : "?"); + return; + } + block->in_eval = true; + + /* Avalia fontes conectadas primeiro (lazy) */ + for (uint32_t i = 0; i < block->input_count; ++i) { + TinyBlocks_Connection* conn = &block->inputs[i]; + if (conn->source && conn->source->dirty) + tb_block_eval(conn->source, rt); + } + + block->vtable->eval(block, rt); + block->in_eval = false; +} + +/* ── Clone ───────────────────────────────────────────────────────────────── */ +TinyBlocks_Block* tb_block_clone(const TinyBlocks_Block* block, TinyBlocks* rt) +{ + if (!block || !block->vtable || !block->vtable->clone) return NULL; + return block->vtable->clone(block, rt); +} + +/* ── Representação textual ───────────────────────────────────────────────── */ +size_t tb_block_to_string(TinyBlocks_Block* block, TinyBlocks* rt, + char* buf, size_t buf_size) +{ + if (!block || !buf || buf_size == 0) return 0; + if (block->vtable && block->vtable->to_string) + return block->vtable->to_string(block, rt, buf, buf_size); + return (size_t)snprintf(buf, buf_size, "[Block#%llu]", + (unsigned long long)block->id); +} + +/* ── Conexões ────────────────────────────────────────────────────────────── */ +bool tb_block_connect(TinyBlocks_Block* target, uint32_t input_idx, + TinyBlocks_Block* source, uint32_t output_idx) +{ + if (!target || input_idx >= target->input_count) return false; + if (!source || output_idx >= source->output_count) return false; + + TinyBlocks_Connection* conn = &target->inputs[input_idx]; + conn->source = source; + conn->output_idx = output_idx; + target->dirty = true; + return true; +} + +void tb_block_disconnect(TinyBlocks_Block* target, uint32_t input_idx) +{ + if (!target || input_idx >= target->input_count) return; + target->inputs[input_idx].source = NULL; + target->dirty = true; +} + +bool tb_block_set_default(TinyBlocks_Block* target, uint32_t input_idx, + TinyBlocks_Value default_value) +{ + if (!target || input_idx >= target->input_count) return false; + tb_value_free(&target->inputs[input_idx].default_value); + target->inputs[input_idx].default_value = tb_value_clone(default_value); + return true; +} + +/* ── Acesso a valores em eval_fn ─────────────────────────────────────────── */ +TinyBlocks_Value tb_block_get_input(TinyBlocks_Block* self, TinyBlocks* rt, + uint32_t input_idx) +{ + if (!self || input_idx >= self->input_count) return tb_value_none(); + + TinyBlocks_Connection* conn = &self->inputs[input_idx]; + if (conn->source) { + if (conn->source->dirty) tb_block_eval(conn->source, rt); + if (conn->output_idx < conn->source->output_count) + return conn->source->outputs[conn->output_idx]; + } + return conn->default_value; +} + +/* Toma ownership de v — o caller NÃO deve liberar v depois desta chamada. + Se precisar manter v, passe tb_value_clone(v) em vez de v. */ +void tb_block_set_output(TinyBlocks_Block* self, uint32_t output_idx, + TinyBlocks_Value v) +{ + if (!self || output_idx >= self->output_count) return; + tb_value_free(&self->outputs[output_idx]); + self->outputs[output_idx] = v; +} + +/* ── Downcasting seguro ──────────────────────────────────────────────────── */ +TinyBlocks_TypeBlock* tb_block_as_type (TinyBlocks_Block* b) +{ return b && b->kind == TB_KIND_TYPE ? (TinyBlocks_TypeBlock*)b : NULL; } + +TinyBlocks_LibraryBlock* tb_block_as_library(TinyBlocks_Block* b) +{ return b && b->kind == TB_KIND_LIBRARY ? (TinyBlocks_LibraryBlock*)b : NULL; } + +TinyBlocks_TextBlock* tb_block_as_text (TinyBlocks_Block* b) +{ return b && b->kind == TB_KIND_TEXT ? (TinyBlocks_TextBlock*)b : NULL; } + +TinyBlocks_IntegerBlock* tb_block_as_integer(TinyBlocks_Block* b) +{ return b && b->kind == TB_KIND_INTEGER ? (TinyBlocks_IntegerBlock*)b : NULL; } + +TinyBlocks_RealBlock* tb_block_as_real (TinyBlocks_Block* b) +{ return b && b->kind == TB_KIND_REAL ? (TinyBlocks_RealBlock*)b : NULL; } diff --git a/src/tb_integer_block.c b/src/tb_integer_block.c new file mode 100644 index 0000000..df746fa --- /dev/null +++ b/src/tb_integer_block.c @@ -0,0 +1,68 @@ +#include +#include "tinyblocks/tinyblocks.h" + +/* ── Vtable ──────────────────────────────────────────────────────────────── */ +static void integer_eval(TinyBlocks_Block* self, TinyBlocks* rt) +{ + (void)rt; + TinyBlocks_IntegerBlock* ib = (TinyBlocks_IntegerBlock*)self; + tb_block_set_output(self, 0, tb_value_integer(ib->value)); + self->dirty = false; +} + +static void integer_destroy(TinyBlocks_Block* self, TinyBlocks* rt) +{ + (void)self; (void)rt; /* nada a liberar além do base */ +} + +static size_t integer_to_string(TinyBlocks_Block* self, TinyBlocks* rt, + char* buf, size_t sz) +{ + (void)rt; + TinyBlocks_IntegerBlock* ib = (TinyBlocks_IntegerBlock*)self; + return (size_t)snprintf(buf, sz, "%lld", (long long)ib->value); +} + +static TinyBlocks_Block* integer_clone(const TinyBlocks_Block* self, TinyBlocks* rt) +{ + const TinyBlocks_IntegerBlock* ib = (const TinyBlocks_IntegerBlock*)self; + TinyBlocks_IntegerBlock* clone = tb_integer_block_create(rt, ib->value); + if (clone && self->name) clone->base.name = tb_strdup(rt, self->name); + return (TinyBlocks_Block*)clone; +} + +static const TinyBlocks_BlockVTable s_integer_vtable = { + .eval = integer_eval, + .destroy = integer_destroy, + .to_string = integer_to_string, + .clone = integer_clone, +}; + +/* ── Ciclo de vida ───────────────────────────────────────────────────────── */ +TinyBlocks_IntegerBlock* tb_integer_block_create(TinyBlocks* rt, int64_t value) +{ + TinyBlocks_IntegerBlock* ib = (TinyBlocks_IntegerBlock*)tb_block_alloc_base( + rt, TB_KIND_INTEGER, sizeof(TinyBlocks_IntegerBlock), + 0, 1, &s_integer_vtable); + if (!ib) return NULL; + ib->value = value; + return ib; +} + +void tb_integer_block_destroy(TinyBlocks_IntegerBlock* ib, TinyBlocks* rt) +{ + tb_block_destroy(&ib->base, rt); +} + +/* ── Acesso ──────────────────────────────────────────────────────────────── */ +int64_t tb_integer_block_get(const TinyBlocks_IntegerBlock* ib) +{ + return ib ? ib->value : 0; +} + +void tb_integer_block_set(TinyBlocks_IntegerBlock* ib, int64_t value) +{ + if (!ib) return; + ib->value = value; + ib->base.dirty = true; +} diff --git a/src/tb_json_block.c b/src/tb_json_block.c new file mode 100644 index 0000000..6d18da3 --- /dev/null +++ b/src/tb_json_block.c @@ -0,0 +1,526 @@ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include +#include + +#include "tinyblocks/tinyblocks.h" + +struct TinyBlocks_JsonValue { + TinyBlocks_JsonKind kind; + int32_t ref; + union { + bool boolean; + double number; + char* string; + struct { + TinyBlocks_JsonValue** items; + uint32_t count, capacity; + } array; + struct { + char** keys; + TinyBlocks_JsonValue** values; + uint32_t count, capacity; + } object; + } as; +}; + +/* ══════════════════════════════════════════════════════════════════════════ + * Construtores / ciclo de vida + * ══════════════════════════════════════════════════════════════════════════ */ +static TinyBlocks_JsonValue* json_alloc(TinyBlocks_JsonKind kind) { + TinyBlocks_JsonValue* j = calloc(1, sizeof(TinyBlocks_JsonValue)); + if (!j) return NULL; + j->kind = kind; + j->ref = 1; + return j; +} + +TinyBlocks_JsonValue* tb_json_null(void) { return json_alloc(TB_JSON_NULL); } + +TinyBlocks_JsonValue* tb_json_bool(bool b) { + TinyBlocks_JsonValue* j = json_alloc(TB_JSON_BOOL); + if (j) j->as.boolean = b; + return j; +} + +TinyBlocks_JsonValue* tb_json_number(double d) { + TinyBlocks_JsonValue* j = json_alloc(TB_JSON_NUMBER); + if (j) j->as.number = d; + return j; +} + +TinyBlocks_JsonValue* tb_json_string(const char* s) { + TinyBlocks_JsonValue* j = json_alloc(TB_JSON_STRING); + if (!j) return NULL; + j->as.string = strdup(s ? s : ""); + return j; +} + +TinyBlocks_JsonValue* tb_json_array(void) { return json_alloc(TB_JSON_ARRAY); } +TinyBlocks_JsonValue* tb_json_object(void) { return json_alloc(TB_JSON_OBJECT); } + +static void json_destroy(TinyBlocks_JsonValue* j) { + switch (j->kind) { + case TB_JSON_STRING: + free(j->as.string); + break; + case TB_JSON_ARRAY: + for (uint32_t i = 0; i < j->as.array.count; i++) + tb_json_release(j->as.array.items[i]); + free(j->as.array.items); + break; + case TB_JSON_OBJECT: + for (uint32_t i = 0; i < j->as.object.count; i++) { + free(j->as.object.keys[i]); + tb_json_release(j->as.object.values[i]); + } + free(j->as.object.keys); + free(j->as.object.values); + break; + default: + break; + } + free(j); +} + +void tb_json_retain(TinyBlocks_JsonValue* j) { + if (j) j->ref++; +} + +void tb_json_release(TinyBlocks_JsonValue* j) { + if (!j) return; + if (--j->ref <= 0) json_destroy(j); +} + +TinyBlocks_JsonValue* tb_json_clone(const TinyBlocks_JsonValue* j) { + if (!j) return NULL; + switch (j->kind) { + case TB_JSON_NULL: return tb_json_null(); + case TB_JSON_BOOL: return tb_json_bool(j->as.boolean); + case TB_JSON_NUMBER: return tb_json_number(j->as.number); + case TB_JSON_STRING: return tb_json_string(j->as.string); + case TB_JSON_ARRAY: { + TinyBlocks_JsonValue* out = tb_json_array(); + if (!out) return NULL; + for (uint32_t i = 0; i < j->as.array.count; i++) { + TinyBlocks_JsonValue* item = tb_json_clone(j->as.array.items[i]); + tb_json_array_push(out, item); + tb_json_release(item); + } + return out; + } + case TB_JSON_OBJECT: { + TinyBlocks_JsonValue* out = tb_json_object(); + if (!out) return NULL; + for (uint32_t i = 0; i < j->as.object.count; i++) { + TinyBlocks_JsonValue* val = tb_json_clone(j->as.object.values[i]); + tb_json_object_set(out, j->as.object.keys[i], val); + tb_json_release(val); + } + return out; + } + } + return tb_json_null(); +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Inspeção + * ══════════════════════════════════════════════════════════════════════════ */ +TinyBlocks_JsonKind tb_json_kind(const TinyBlocks_JsonValue* j) { + return j ? j->kind : TB_JSON_NULL; +} + +const char* tb_json_kind_name(const TinyBlocks_JsonValue* j) { + switch (tb_json_kind(j)) { + case TB_JSON_NULL: return "null"; + case TB_JSON_BOOL: return "bool"; + case TB_JSON_NUMBER: return "number"; + case TB_JSON_STRING: return "string"; + case TB_JSON_ARRAY: return "array"; + case TB_JSON_OBJECT: return "object"; + } + return "null"; +} + +bool tb_json_as_bool(const TinyBlocks_JsonValue* j, bool def) { + if (!j) return def; + if (j->kind == TB_JSON_BOOL) return j->as.boolean; + if (j->kind == TB_JSON_NUMBER) return j->as.number != 0.0; + return def; +} + +double tb_json_as_number(const TinyBlocks_JsonValue* j, double def) { + if (!j) return def; + if (j->kind == TB_JSON_NUMBER) return j->as.number; + if (j->kind == TB_JSON_BOOL) return j->as.boolean ? 1.0 : 0.0; + return def; +} + +const char* tb_json_as_string(const TinyBlocks_JsonValue* j) { + if (!j || j->kind != TB_JSON_STRING) return NULL; + return j->as.string; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Arrays + * ══════════════════════════════════════════════════════════════════════════ */ +bool tb_json_array_push(TinyBlocks_JsonValue* arr, TinyBlocks_JsonValue* item) { + if (!arr || arr->kind != TB_JSON_ARRAY || !item) return false; + if (arr->as.array.count == arr->as.array.capacity) { + uint32_t cap = arr->as.array.capacity ? arr->as.array.capacity * 2 : 8; + TinyBlocks_JsonValue** items = realloc(arr->as.array.items, cap * sizeof(*items)); + if (!items) return false; + arr->as.array.items = items; + arr->as.array.capacity = cap; + } + tb_json_retain(item); + arr->as.array.items[arr->as.array.count++] = item; + return true; +} + +uint32_t tb_json_array_length(const TinyBlocks_JsonValue* arr) { + return (arr && arr->kind == TB_JSON_ARRAY) ? arr->as.array.count : 0; +} + +TinyBlocks_JsonValue* tb_json_array_get(const TinyBlocks_JsonValue* arr, uint32_t idx) { + if (!arr || arr->kind != TB_JSON_ARRAY || idx >= arr->as.array.count) return NULL; + TinyBlocks_JsonValue* v = arr->as.array.items[idx]; + tb_json_retain(v); + return v; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Objetos + * ══════════════════════════════════════════════════════════════════════════ */ +bool tb_json_object_set(TinyBlocks_JsonValue* obj, const char* key, TinyBlocks_JsonValue* val) { + if (!obj || obj->kind != TB_JSON_OBJECT || !key || !val) return false; + for (uint32_t i = 0; i < obj->as.object.count; i++) { + if (strcmp(obj->as.object.keys[i], key) == 0) { + tb_json_release(obj->as.object.values[i]); + tb_json_retain(val); + obj->as.object.values[i] = val; + return true; + } + } + if (obj->as.object.count == obj->as.object.capacity) { + uint32_t cap = obj->as.object.capacity ? obj->as.object.capacity * 2 : 8; + char** keys = realloc(obj->as.object.keys, cap * sizeof(*keys)); + TinyBlocks_JsonValue** values = realloc(obj->as.object.values, cap * sizeof(*values)); + if (!keys || !values) { free(keys); free(values); return false; } + obj->as.object.keys = keys; + obj->as.object.values = values; + obj->as.object.capacity = cap; + } + obj->as.object.keys[obj->as.object.count] = strdup(key); + tb_json_retain(val); + obj->as.object.values[obj->as.object.count] = val; + obj->as.object.count++; + return true; +} + +uint32_t tb_json_object_length(const TinyBlocks_JsonValue* obj) { + return (obj && obj->kind == TB_JSON_OBJECT) ? obj->as.object.count : 0; +} + +const char* tb_json_object_key_at(const TinyBlocks_JsonValue* obj, uint32_t idx) { + if (!obj || obj->kind != TB_JSON_OBJECT || idx >= obj->as.object.count) return NULL; + return obj->as.object.keys[idx]; +} + +TinyBlocks_JsonValue* tb_json_object_get(const TinyBlocks_JsonValue* obj, const char* key) { + if (!obj || obj->kind != TB_JSON_OBJECT || !key) return NULL; + for (uint32_t i = 0; i < obj->as.object.count; i++) { + if (strcmp(obj->as.object.keys[i], key) == 0) { + tb_json_retain(obj->as.object.values[i]); + return obj->as.object.values[i]; + } + } + return NULL; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Parser (recursive-descent, RFC 8259 simplificado) + * ══════════════════════════════════════════════════════════════════════════ */ +typedef struct { const char* p; const char* end; char* err; size_t errcap; } JsonParser; + +static void parser_fail(JsonParser* ps, const char* msg) { + if (ps->err && ps->errcap) snprintf(ps->err, ps->errcap, "%s", msg); +} + +static void skip_ws(JsonParser* ps) { + while (ps->p < ps->end && isspace((unsigned char)*ps->p)) ps->p++; +} + +static TinyBlocks_JsonValue* parse_value(JsonParser* ps); + +static bool parse_literal(JsonParser* ps, const char* lit) { + size_t n = strlen(lit); + if ((size_t)(ps->end - ps->p) < n) return false; + if (memcmp(ps->p, lit, n) != 0) return false; + ps->p += n; + return true; +} + +static char* parse_string_raw(JsonParser* ps) { + if (ps->p >= ps->end || *ps->p != '"') { parser_fail(ps, "esperado '\"'"); return NULL; } + ps->p++; + size_t cap = 32, len = 0; + char* buf = malloc(cap); + if (!buf) return NULL; + while (ps->p < ps->end && *ps->p != '"') { + unsigned char c = (unsigned char)*ps->p++; + char out = (char)c; + if (c == '\\') { + if (ps->p >= ps->end) { free(buf); parser_fail(ps, "string truncada"); return NULL; } + char esc = *ps->p++; + switch (esc) { + case '"': out = '"'; break; + case '\\': out = '\\'; break; + case '/': out = '/'; break; + case 'b': out = '\b'; break; + case 'f': out = '\f'; break; + case 'n': out = '\n'; break; + case 'r': out = '\r'; break; + case 't': out = '\t'; break; + case 'u': { + if (ps->end - ps->p < 4) { free(buf); parser_fail(ps, "\\u incompleto"); return NULL; } + unsigned cp = 0; + for (int i = 0; i < 4; i++) { + char h = ps->p[i]; + cp <<= 4; + if (h >= '0' && h <= '9') cp |= (unsigned)(h - '0'); + else if (h >= 'a' && h <= 'f') cp |= (unsigned)(h - 'a' + 10); + else if (h >= 'A' && h <= 'F') cp |= (unsigned)(h - 'A' + 10); + else { free(buf); parser_fail(ps, "\\u inválido"); return NULL; } + } + ps->p += 4; + /* codifica em UTF-8 (apenas BMP, sem pares substitutos) */ + if (len + 4 >= cap) { cap *= 2; buf = realloc(buf, cap); if (!buf) return NULL; } + if (cp < 0x80) { + buf[len++] = (char)cp; + } else if (cp < 0x800) { + buf[len++] = (char)(0xC0 | (cp >> 6)); + buf[len++] = (char)(0x80 | (cp & 0x3F)); + } else { + buf[len++] = (char)(0xE0 | (cp >> 12)); + buf[len++] = (char)(0x80 | ((cp >> 6) & 0x3F)); + buf[len++] = (char)(0x80 | (cp & 0x3F)); + } + continue; + } + default: + free(buf); parser_fail(ps, "escape inválido"); return NULL; + } + } + if (len + 1 >= cap) { cap *= 2; buf = realloc(buf, cap); if (!buf) return NULL; } + buf[len++] = out; + } + if (ps->p >= ps->end) { free(buf); parser_fail(ps, "string não terminada"); return NULL; } + ps->p++; /* fecha '"' */ + buf[len] = '\0'; + return buf; +} + +static TinyBlocks_JsonValue* parse_number(JsonParser* ps) { + const char* start = ps->p; + if (ps->p < ps->end && *ps->p == '-') ps->p++; + while (ps->p < ps->end && isdigit((unsigned char)*ps->p)) ps->p++; + if (ps->p < ps->end && *ps->p == '.') { + ps->p++; + while (ps->p < ps->end && isdigit((unsigned char)*ps->p)) ps->p++; + } + if (ps->p < ps->end && (*ps->p == 'e' || *ps->p == 'E')) { + ps->p++; + if (ps->p < ps->end && (*ps->p == '+' || *ps->p == '-')) ps->p++; + while (ps->p < ps->end && isdigit((unsigned char)*ps->p)) ps->p++; + } + if (ps->p == start) { parser_fail(ps, "número inválido"); return NULL; } + char tmp[64]; + size_t n = (size_t)(ps->p - start); + if (n >= sizeof(tmp)) n = sizeof(tmp) - 1; + memcpy(tmp, start, n); + tmp[n] = '\0'; + return tb_json_number(strtod(tmp, NULL)); +} + +static TinyBlocks_JsonValue* parse_array(JsonParser* ps) { + ps->p++; /* '[' */ + TinyBlocks_JsonValue* arr = tb_json_array(); + skip_ws(ps); + if (ps->p < ps->end && *ps->p == ']') { ps->p++; return arr; } + for (;;) { + skip_ws(ps); + TinyBlocks_JsonValue* item = parse_value(ps); + if (!item) { tb_json_release(arr); return NULL; } + tb_json_array_push(arr, item); + tb_json_release(item); + skip_ws(ps); + if (ps->p < ps->end && *ps->p == ',') { ps->p++; continue; } + if (ps->p < ps->end && *ps->p == ']') { ps->p++; break; } + tb_json_release(arr); parser_fail(ps, "esperado ',' ou ']'"); return NULL; + } + return arr; +} + +static TinyBlocks_JsonValue* parse_object(JsonParser* ps) { + ps->p++; /* '{' */ + TinyBlocks_JsonValue* obj = tb_json_object(); + skip_ws(ps); + if (ps->p < ps->end && *ps->p == '}') { ps->p++; return obj; } + for (;;) { + skip_ws(ps); + char* key = parse_string_raw(ps); + if (!key) { tb_json_release(obj); return NULL; } + skip_ws(ps); + if (ps->p >= ps->end || *ps->p != ':') { free(key); tb_json_release(obj); parser_fail(ps, "esperado ':'"); return NULL; } + ps->p++; + skip_ws(ps); + TinyBlocks_JsonValue* val = parse_value(ps); + if (!val) { free(key); tb_json_release(obj); return NULL; } + tb_json_object_set(obj, key, val); + free(key); + tb_json_release(val); + skip_ws(ps); + if (ps->p < ps->end && *ps->p == ',') { ps->p++; continue; } + if (ps->p < ps->end && *ps->p == '}') { ps->p++; break; } + tb_json_release(obj); parser_fail(ps, "esperado ',' ou '}'"); return NULL; + } + return obj; +} + +static TinyBlocks_JsonValue* parse_value(JsonParser* ps) { + skip_ws(ps); + if (ps->p >= ps->end) { parser_fail(ps, "fim inesperado"); return NULL; } + char c = *ps->p; + if (c == '{') return parse_object(ps); + if (c == '[') return parse_array(ps); + if (c == '"') { + char* s = parse_string_raw(ps); + if (!s) return NULL; + TinyBlocks_JsonValue* j = tb_json_string(s); + free(s); + return j; + } + if (c == '-' || isdigit((unsigned char)c)) return parse_number(ps); + if (parse_literal(ps, "true")) return tb_json_bool(true); + if (parse_literal(ps, "false")) return tb_json_bool(false); + if (parse_literal(ps, "null")) return tb_json_null(); + parser_fail(ps, "token inesperado"); + return NULL; +} + +TinyBlocks_JsonValue* tb_json_parse(const char* text, char* errbuf, size_t errbuf_size) { + if (!text) { if (errbuf && errbuf_size) snprintf(errbuf, errbuf_size, "texto nulo"); return NULL; } + JsonParser ps = { .p = text, .end = text + strlen(text), .err = errbuf, .errcap = errbuf_size }; + TinyBlocks_JsonValue* v = parse_value(&ps); + if (!v) return NULL; + skip_ws(&ps); + if (ps.p != ps.end) { + tb_json_release(v); + if (errbuf && errbuf_size) snprintf(errbuf, errbuf_size, "lixo após valor JSON"); + return NULL; + } + return v; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Stringify + * ══════════════════════════════════════════════════════════════════════════ */ +typedef struct { char* buf; size_t len, cap; } StrBuf; + +static void sb_ensure(StrBuf* sb, size_t extra) { + if (sb->len + extra + 1 <= sb->cap) return; + size_t cap = sb->cap ? sb->cap * 2 : 64; + while (cap < sb->len + extra + 1) cap *= 2; + sb->buf = realloc(sb->buf, cap); + sb->cap = cap; +} + +static void sb_append(StrBuf* sb, const char* s) { + size_t n = strlen(s); + sb_ensure(sb, n); + memcpy(sb->buf + sb->len, s, n); + sb->len += n; + sb->buf[sb->len] = '\0'; +} + +static void sb_append_quoted(StrBuf* sb, const char* s) { + sb_append(sb, "\""); + for (const unsigned char* p = (const unsigned char*)s; *p; p++) { + char tmp[8]; + switch (*p) { + case '"': sb_append(sb, "\\\""); break; + case '\\': sb_append(sb, "\\\\"); break; + case '\n': sb_append(sb, "\\n"); break; + case '\r': sb_append(sb, "\\r"); break; + case '\t': sb_append(sb, "\\t"); break; + default: + if (*p < 0x20) { snprintf(tmp, sizeof(tmp), "\\u%04x", *p); sb_append(sb, tmp); } + else { tmp[0] = (char)*p; tmp[1] = '\0'; sb_append(sb, tmp); } + } + } + sb_append(sb, "\""); +} + +static void stringify_rec(StrBuf* sb, const TinyBlocks_JsonValue* j) { + if (!j) { sb_append(sb, "null"); return; } + char tmp[64]; + switch (j->kind) { + case TB_JSON_NULL: + sb_append(sb, "null"); + break; + case TB_JSON_BOOL: + sb_append(sb, j->as.boolean ? "true" : "false"); + break; + case TB_JSON_NUMBER: + if (isfinite(j->as.number) && j->as.number == (double)(int64_t)j->as.number) + snprintf(tmp, sizeof(tmp), "%lld", (long long)j->as.number); + else + snprintf(tmp, sizeof(tmp), "%g", j->as.number); + sb_append(sb, tmp); + break; + case TB_JSON_STRING: + sb_append_quoted(sb, j->as.string); + break; + case TB_JSON_ARRAY: + sb_append(sb, "["); + for (uint32_t i = 0; i < j->as.array.count; i++) { + if (i) sb_append(sb, ","); + stringify_rec(sb, j->as.array.items[i]); + } + sb_append(sb, "]"); + break; + case TB_JSON_OBJECT: + sb_append(sb, "{"); + for (uint32_t i = 0; i < j->as.object.count; i++) { + if (i) sb_append(sb, ","); + sb_append_quoted(sb, j->as.object.keys[i]); + sb_append(sb, ":"); + stringify_rec(sb, j->as.object.values[i]); + } + sb_append(sb, "}"); + break; + } +} + +char* tb_json_stringify(const TinyBlocks_JsonValue* j) { + StrBuf sb = {0}; + stringify_rec(&sb, j); + if (!sb.buf) sb.buf = strdup("null"); + return sb.buf; +} + +/* ══════════════════════════════════════════════════════════════════════════ + * Helpers para TinyBlocks_Value + * ══════════════════════════════════════════════════════════════════════════ */ +TinyBlocks_Value tb_value_json(TinyBlocks_JsonValue* j) { + TinyBlocks_Value v = { .kind = TB_VALUE_JSON, .as.json = j }; + if (j) tb_json_retain(j); + return v; +} + +TinyBlocks_JsonValue* tb_value_as_json(TinyBlocks_Value v) { + return v.kind == TB_VALUE_JSON ? v.as.json : NULL; +} diff --git a/src/tb_library_block.c b/src/tb_library_block.c new file mode 100644 index 0000000..24115f9 --- /dev/null +++ b/src/tb_library_block.c @@ -0,0 +1,190 @@ +#include +#include +#include +#include "tinyblocks/tinyblocks.h" + +#ifdef __linux__ +# include +#endif + +/* ── Vtable de LibraryBlock ──────────────────────────────────────────────── */ +static void lib_eval(TinyBlocks_Block* self, TinyBlocks* rt) +{ + /* Libraries não avaliam diretamente; servem como namespaces */ + (void)self; (void)rt; + self->dirty = false; +} + +static void lib_destroy(TinyBlocks_Block* self, TinyBlocks* rt) +{ + TinyBlocks_LibraryBlock* lib = (TinyBlocks_LibraryBlock*)self; + tb_rt_unregister_library(rt, lib); + /* Destrói blocos contidos */ + for (uint32_t i = 0; i < lib->block_count; ++i) + tb_block_destroy(lib->blocks[i], rt); + tb_free(rt, lib->blocks); +} + +static size_t lib_to_string(TinyBlocks_Block* self, TinyBlocks* rt, + char* buf, size_t sz) +{ + (void)rt; + return (size_t)snprintf(buf, sz, "[Library:%s (%u blocks)]", + self->name ? self->name : "?", + ((TinyBlocks_LibraryBlock*)self)->block_count); +} + +static TinyBlocks_Block* lib_clone(const TinyBlocks_Block* self, TinyBlocks* rt) +{ + /* Clonar uma library cria uma nova library vazia com o mesmo nome */ + return (TinyBlocks_Block*)tb_library_block_create(rt, self->name); +} + +static const TinyBlocks_BlockVTable s_lib_vtable = { + .eval = lib_eval, + .destroy = lib_destroy, + .to_string = lib_to_string, + .clone = lib_clone, +}; + +/* ── Criação ─────────────────────────────────────────────────────────────── */ +TinyBlocks_LibraryBlock* tb_library_block_create(TinyBlocks* rt, const char* name) +{ + TinyBlocks_LibraryBlock* lib = (TinyBlocks_LibraryBlock*)tb_block_alloc_base( + rt, TB_KIND_LIBRARY, sizeof(TinyBlocks_LibraryBlock), + 0, 0, &s_lib_vtable); + if (!lib) return NULL; + + lib->base.name = tb_strdup(rt, name); + lib->block_capacity = 16; + lib->blocks = tb_alloc(rt, lib->block_capacity * sizeof(TinyBlocks_Block*)); + if (!lib->blocks) { + tb_block_destroy(&lib->base, rt); + return NULL; + } + + tb_rt_register_library(rt, lib); + return lib; +} + +void tb_library_block_destroy(TinyBlocks_LibraryBlock* lib, TinyBlocks* rt) +{ + tb_block_destroy(&lib->base, rt); +} + +/* ── Gerenciamento de blocos contidos ────────────────────────────────────── */ +bool tb_library_add(TinyBlocks_LibraryBlock* lib, TinyBlocks_Block* block) +{ + if (!lib || !block) return false; + if (lib->block_count >= lib->block_capacity) { + uint32_t new_cap = lib->block_capacity * 2; + /* A library pertence a um runtime — mas não temos rt aqui. + Solução: guardar rt no lib_userdata NÃO é a API pública. + Usamos realloc direto pois este array não usa o alocador customizado + (trade-off documentado: arrays de library usam realloc). */ + TinyBlocks_Block** arr = realloc(lib->blocks, + new_cap * sizeof(TinyBlocks_Block*)); + if (!arr) return false; + lib->blocks = arr; + lib->block_capacity = new_cap; + } + lib->blocks[lib->block_count++] = block; + block->parent = &lib->base; + return true; +} + +bool tb_library_remove_at(TinyBlocks_LibraryBlock* lib, uint32_t index) +{ + if (!lib || index >= lib->block_count) return false; + lib->blocks[index]->parent = NULL; + lib->blocks[index] = lib->blocks[--lib->block_count]; + return true; +} + +TinyBlocks_Block* tb_library_find(TinyBlocks_LibraryBlock* lib, const char* name) +{ + if (!lib || !name) return NULL; + for (uint32_t i = 0; i < lib->block_count; ++i) { + TinyBlocks_Block* b = lib->blocks[i]; + /* Compara pelo nome do bloco ou pelo type_name se for TypeBlock */ + if (b->name && strcmp(b->name, name) == 0) return b; + if (b->kind == TB_KIND_TYPE) { + TinyBlocks_TypeBlock* tb = (TinyBlocks_TypeBlock*)b; + if (tb->type_name && strcmp(tb->type_name, name) == 0) return b; + } + } + return NULL; +} + +/* ── Carregamento dinâmico ───────────────────────────────────────────────── */ +TinyBlocks_LibraryBlock* tb_library_load(TinyBlocks* rt, const char* path) +{ +#ifdef __linux__ + void* handle = dlopen(path, RTLD_NOW | RTLD_LOCAL); + if (!handle) { + tinyblocks_set_error(rt, "tb_library_load: dlopen failed: %s", dlerror()); + return NULL; + } + + typedef const TinyBlocks_LibraryDescriptor* (*GetLibFn)(void); + GetLibFn get_lib = (GetLibFn)(uintptr_t)dlsym(handle, TINYBLOCKS_LIBRARY_SYMBOL); + if (!get_lib) { + tinyblocks_set_error(rt, "tb_library_load: symbol '%s' not found in %s", + TINYBLOCKS_LIBRARY_SYMBOL, path); + dlclose(handle); + return NULL; + } + + const TinyBlocks_LibraryDescriptor* desc = get_lib(); + TinyBlocks_LibraryBlock* lib = tb_library_register(rt, desc); + if (!lib) { dlclose(handle); return NULL; } + + /* Guarda handle para dlclose no deinit */ + if (rt->dl_handle_count >= rt->dl_handle_capacity) { + uint32_t nc = rt->dl_handle_capacity * 2; + void** arr = realloc(rt->dl_handles, nc * sizeof(void*)); + if (!arr) { tb_library_unload(rt, lib); dlclose(handle); return NULL; } + rt->dl_handles = arr; + rt->dl_handle_capacity = nc; + } + rt->dl_handles[rt->dl_handle_count++] = handle; + return lib; +#else + (void)path; + tinyblocks_set_error(rt, "tb_library_load: not supported on this platform"); + return NULL; +#endif +} + +void tb_library_unload(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) +{ + if (!lib) return; + if (lib->on_unload) lib->on_unload(lib, rt); + tb_library_block_destroy(lib, rt); +} + +TinyBlocks_LibraryBlock* tb_library_register(TinyBlocks* rt, + const TinyBlocks_LibraryDescriptor* desc) +{ + if (!desc) { + tinyblocks_set_error(rt, "tb_library_register: descriptor is NULL"); + return NULL; + } + + TinyBlocks_LibraryBlock* lib = tb_library_block_create(rt, desc->name); + if (!lib) return NULL; + + if (desc->init && !desc->init(rt, lib)) { + tinyblocks_set_error(rt, "tb_library_register: init failed for '%s'", + desc->name ? desc->name : "?"); + tb_library_block_destroy(lib, rt); + return NULL; + } + + if (lib->on_load && !lib->on_load(lib, rt)) { + tb_library_block_destroy(lib, rt); + return NULL; + } + + return lib; +} diff --git a/src/tb_real_block.c b/src/tb_real_block.c new file mode 100644 index 0000000..c5b8ac6 --- /dev/null +++ b/src/tb_real_block.c @@ -0,0 +1,68 @@ +#include +#include "tinyblocks/tinyblocks.h" + +/* ── Vtable ──────────────────────────────────────────────────────────────── */ +static void real_eval(TinyBlocks_Block* self, TinyBlocks* rt) +{ + (void)rt; + TinyBlocks_RealBlock* rb = (TinyBlocks_RealBlock*)self; + tb_block_set_output(self, 0, tb_value_real(rb->value)); + self->dirty = false; +} + +static void real_destroy(TinyBlocks_Block* self, TinyBlocks* rt) +{ + (void)self; (void)rt; +} + +static size_t real_to_string(TinyBlocks_Block* self, TinyBlocks* rt, + char* buf, size_t sz) +{ + (void)rt; + TinyBlocks_RealBlock* rb = (TinyBlocks_RealBlock*)self; + return (size_t)snprintf(buf, sz, "%g", rb->value); +} + +static TinyBlocks_Block* real_clone(const TinyBlocks_Block* self, TinyBlocks* rt) +{ + const TinyBlocks_RealBlock* rb = (const TinyBlocks_RealBlock*)self; + TinyBlocks_RealBlock* clone = tb_real_block_create(rt, rb->value); + if (clone && self->name) clone->base.name = tb_strdup(rt, self->name); + return (TinyBlocks_Block*)clone; +} + +static const TinyBlocks_BlockVTable s_real_vtable = { + .eval = real_eval, + .destroy = real_destroy, + .to_string = real_to_string, + .clone = real_clone, +}; + +/* ── Ciclo de vida ───────────────────────────────────────────────────────── */ +TinyBlocks_RealBlock* tb_real_block_create(TinyBlocks* rt, double value) +{ + TinyBlocks_RealBlock* rb = (TinyBlocks_RealBlock*)tb_block_alloc_base( + rt, TB_KIND_REAL, sizeof(TinyBlocks_RealBlock), + 0, 1, &s_real_vtable); + if (!rb) return NULL; + rb->value = value; + return rb; +} + +void tb_real_block_destroy(TinyBlocks_RealBlock* rb, TinyBlocks* rt) +{ + tb_block_destroy(&rb->base, rt); +} + +/* ── Acesso ──────────────────────────────────────────────────────────────── */ +double tb_real_block_get(const TinyBlocks_RealBlock* rb) +{ + return rb ? rb->value : 0.0; +} + +void tb_real_block_set(TinyBlocks_RealBlock* rb, double value) +{ + if (!rb) return; + rb->value = value; + rb->base.dirty = true; +} diff --git a/src/tb_renderable_block.c b/src/tb_renderable_block.c new file mode 100644 index 0000000..4cf44a5 --- /dev/null +++ b/src/tb_renderable_block.c @@ -0,0 +1,165 @@ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include "tinyblocks/tb_renderable_block.h" + +/* ── Pool estático — 4 frames em paralelo é suficiente para qualquer backend ─ */ +#define POOL_CAP 4 + +static TinyBlocks_RenderableBlock s_pool[POOL_CAP]; +static bool s_used[POOL_CAP]; + +TinyBlocks_RenderableBlock* tb_renderable_acquire(void) { + for (int i = 0; i < POOL_CAP; i++) { + if (!s_used[i]) { + s_used[i] = true; + s_pool[i].count = 0; + return &s_pool[i]; + } + } + return NULL; +} + +void tb_renderable_release(TinyBlocks_RenderableBlock* rb) { + for (int i = 0; i < POOL_CAP; i++) { + if (&s_pool[i] == rb) { s_used[i] = false; return; } + } +} + +void tb_renderable_release_all(void) { + for (int i = 0; i < POOL_CAP; i++) + s_used[i] = false; +} + +/* ── Append interno ─────────────────────────────────────────────────────────── */ +static TinyBlocks_DrawCmd* append(TinyBlocks_RenderableBlock* rb) { + if (!rb || rb->count >= TB_DRAW_CMD_CAP) return NULL; + TinyBlocks_DrawCmd* c = &rb->cmds[rb->count++]; + memset(c, 0, sizeof(*c)); + return c; +} + +/* ── Helpers públicos ────────────────────────────────────────────────────────── */ +void tb_draw_clear(TinyBlocks_RenderableBlock* rb, + float r, float g, float b, float a) { + TinyBlocks_DrawCmd* c = append(rb); if (!c) return; + c->kind = TB_DRAW_CLEAR; + c->r=r; c->g=g; c->b=b; c->a=a; +} + +void tb_draw_fill_rect(TinyBlocks_RenderableBlock* rb, + float x, float y, float w, float h, + float r, float g, float b, float a) { + TinyBlocks_DrawCmd* c = append(rb); if (!c) return; + c->kind = TB_DRAW_FILL_RECT; + c->x=x; c->y=y; c->w=w; c->h=h; + c->r=r; c->g=g; c->b=b; c->a=a; +} + +void tb_draw_fill_rrect(TinyBlocks_RenderableBlock* rb, + float x, float y, float w, float h, float radius, + float r, float g, float b, float a) { + TinyBlocks_DrawCmd* c = append(rb); if (!c) return; + c->kind = TB_DRAW_FILL_RRECT; + c->x=x; c->y=y; c->w=w; c->h=h; c->param=radius; + c->r=r; c->g=g; c->b=b; c->a=a; +} + +void tb_draw_fill_circle(TinyBlocks_RenderableBlock* rb, + float cx, float cy, float radius, + float r, float g, float b, float a) { + TinyBlocks_DrawCmd* c = append(rb); if (!c) return; + c->kind = TB_DRAW_FILL_CIRCLE; + c->x=cx; c->y=cy; c->param=radius; + c->r=r; c->g=g; c->b=b; c->a=a; +} + +void tb_draw_stroke_line(TinyBlocks_RenderableBlock* rb, + float x1, float y1, float x2, float y2, float stroke_w, + float r, float g, float b, float a) { + TinyBlocks_DrawCmd* c = append(rb); if (!c) return; + c->kind = TB_DRAW_STROKE_LINE; + c->x=x1; c->y=y1; c->w=x2; c->h=y2; c->param=stroke_w; + c->r=r; c->g=g; c->b=b; c->a=a; +} + +void tb_draw_stroke_circle(TinyBlocks_RenderableBlock* rb, + float cx, float cy, float radius, float stroke_w, + float r, float g, float b, float a) { + TinyBlocks_DrawCmd* c = append(rb); if (!c) return; + c->kind = TB_DRAW_STROKE_CIRCLE; + c->x=cx; c->y=cy; c->param=radius; c->w=stroke_w; + c->r=r; c->g=g; c->b=b; c->a=a; +} + +void tb_draw_stroke_rect(TinyBlocks_RenderableBlock* rb, + float x, float y, float w, float h, float stroke_w, + float r, float g, float b, float a) { + TinyBlocks_DrawCmd* c = append(rb); if (!c) return; + c->kind = TB_DRAW_STROKE_RECT; + c->x=x; c->y=y; c->w=w; c->h=h; c->param=stroke_w; + c->r=r; c->g=g; c->b=b; c->a=a; +} + +void tb_draw_set_clip(TinyBlocks_RenderableBlock* rb, + float x, float y, float w, float h) { + TinyBlocks_DrawCmd* c = append(rb); if (!c) return; + c->kind = TB_DRAW_SET_CLIP; + c->x=x; c->y=y; c->w=w; c->h=h; +} + +void tb_draw_clear_clip(TinyBlocks_RenderableBlock* rb) { + TinyBlocks_DrawCmd* c = append(rb); if (!c) return; + c->kind = TB_DRAW_CLEAR_CLIP; +} + +void tb_draw_text(TinyBlocks_RenderableBlock* rb, + float x, float y, const char* text, float font_size, + float r, float g, float b, float a) { + if (!text || !text[0]) return; + TinyBlocks_DrawCmd* c = append(rb); if (!c) return; + c->kind = TB_DRAW_TEXT; + c->x=x; c->y=y; + c->font_size = font_size; + c->r=r; c->g=g; c->b=b; c->a=a; + strncpy(c->text, text, sizeof(c->text) - 1); +} + +void tb_draw_merge_offset(TinyBlocks_RenderableBlock* dst, + const TinyBlocks_RenderableBlock* src, + float dx, float dy) { + if (!dst || !src) return; + for (uint32_t i = 0; i < src->count && dst->count < TB_DRAW_CMD_CAP; i++) { + TinyBlocks_DrawCmd cmd = src->cmds[i]; + switch (cmd.kind) { + case TB_DRAW_FILL_RECT: + case TB_DRAW_FILL_RRECT: + case TB_DRAW_STROKE_RECT: + case TB_DRAW_SET_CLIP: + case TB_DRAW_TEXT: + cmd.x += dx; cmd.y += dy; + break; + case TB_DRAW_FILL_CIRCLE: + case TB_DRAW_STROKE_CIRCLE: + cmd.x += dx; cmd.y += dy; + break; + case TB_DRAW_STROKE_LINE: + cmd.x += dx; cmd.y += dy; + cmd.w += dx; cmd.h += dy; + break; + case TB_DRAW_CLEAR: + case TB_DRAW_CLEAR_CLIP: + break; + } + dst->cmds[dst->count++] = cmd; + } +} + +float tb_measure_text(const char* text, float font_size) { + if (!text) return 0.f; + size_t len = 0; + for (const char* p = text; *p; p++) { + if ((*p & 0xC0) != 0x80) len++; /* conta codepoints UTF-8 */ + } + return (float)len * font_size * 0.55f; +} diff --git a/src/tb_text_block.c b/src/tb_text_block.c new file mode 100644 index 0000000..7382da5 --- /dev/null +++ b/src/tb_text_block.c @@ -0,0 +1,88 @@ +#include +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include "tinyblocks/tinyblocks.h" + +/* ── Vtable ──────────────────────────────────────────────────────────────── */ +static void text_eval(TinyBlocks_Block* self, TinyBlocks* rt) +{ + (void)rt; + TinyBlocks_TextBlock* tb = (TinyBlocks_TextBlock*)self; + tb_block_set_output(self, 0, tb_value_text(tb->value)); + self->dirty = false; +} + +static void text_destroy(TinyBlocks_Block* self, TinyBlocks* rt) +{ + TinyBlocks_TextBlock* tb = (TinyBlocks_TextBlock*)self; + tb_free(rt, tb->value); +} + +static size_t text_to_string(TinyBlocks_Block* self, TinyBlocks* rt, + char* buf, size_t sz) +{ + (void)rt; + TinyBlocks_TextBlock* tb = (TinyBlocks_TextBlock*)self; + return (size_t)snprintf(buf, sz, "\"%s\"", tb->value ? tb->value : ""); +} + +static TinyBlocks_Block* text_clone(const TinyBlocks_Block* self, TinyBlocks* rt) +{ + const TinyBlocks_TextBlock* tb = (const TinyBlocks_TextBlock*)self; + TinyBlocks_TextBlock* clone = tb_text_block_create(rt, tb->value); + if (clone && self->name) clone->base.name = tb_strdup(rt, self->name); + return (TinyBlocks_Block*)clone; +} + +static const TinyBlocks_BlockVTable s_text_vtable = { + .eval = text_eval, + .destroy = text_destroy, + .to_string = text_to_string, + .clone = text_clone, +}; + +/* ── Ciclo de vida ───────────────────────────────────────────────────────── */ +TinyBlocks_TextBlock* tb_text_block_create(TinyBlocks* rt, const char* value) +{ + TinyBlocks_TextBlock* tb = (TinyBlocks_TextBlock*)tb_block_alloc_base( + rt, TB_KIND_TEXT, sizeof(TinyBlocks_TextBlock), + 0, 1, &s_text_vtable); + if (!tb) return NULL; + tb->value = tb_strdup(rt, value ? value : ""); + return tb; +} + +void tb_text_block_destroy(TinyBlocks_TextBlock* tb, TinyBlocks* rt) +{ + tb_block_destroy(&tb->base, rt); +} + +/* ── Acesso ──────────────────────────────────────────────────────────────── */ +const char* tb_text_block_get(const TinyBlocks_TextBlock* tb) +{ + return tb ? tb->value : NULL; +} + +void tb_text_block_set(TinyBlocks_TextBlock* tb, const char* value) +{ + if (!tb) return; + /* Usa realloc para evitar precisar de rt aqui */ + char* copy = value ? strdup(value) : strdup(""); + free(tb->value); + tb->value = copy; + tb->base.dirty = true; +} + +void tb_text_block_append(TinyBlocks_TextBlock* tb, const char* suffix) +{ + if (!tb || !suffix) return; + size_t old_len = tb->value ? strlen(tb->value) : 0; + size_t suf_len = strlen(suffix); + char* buf = realloc(tb->value, old_len + suf_len + 1); + if (!buf) return; + memcpy(buf + old_len, suffix, suf_len + 1); + tb->value = buf; + tb->base.dirty = true; +} diff --git a/src/tb_type_block.c b/src/tb_type_block.c new file mode 100644 index 0000000..e0407ec --- /dev/null +++ b/src/tb_type_block.c @@ -0,0 +1,113 @@ +#include +#include +#include "tinyblocks/tinyblocks.h" + +/* ── Vtable de TypeBlock ─────────────────────────────────────────────────── */ +static void type_eval(TinyBlocks_Block* self, TinyBlocks* rt) +{ + /* Um TypeBlock em si não avalia; serve como fábrica/descritor */ + (void)self; (void)rt; + self->dirty = false; +} + +static void type_destroy(TinyBlocks_Block* self, TinyBlocks* rt) +{ + TinyBlocks_TypeBlock* tb = (TinyBlocks_TypeBlock*)self; + tb_rt_unregister_type(rt, tb); + tb_free(rt, tb->type_name); + for (uint32_t i = 0; i < tb->input_desc_count; ++i) + tb_free(rt, (void*)tb->input_descs[i].name); + tb_free(rt, tb->input_descs); + for (uint32_t i = 0; i < tb->output_desc_count; ++i) + tb_free(rt, (void*)tb->output_descs[i].name); + tb_free(rt, tb->output_descs); +} + +static size_t type_to_string(TinyBlocks_Block* self, TinyBlocks* rt, + char* buf, size_t sz) +{ + (void)rt; + TinyBlocks_TypeBlock* tb = (TinyBlocks_TypeBlock*)self; + return (size_t)snprintf(buf, sz, "[Type:%s]", + tb->type_name ? tb->type_name : "?"); +} + +static TinyBlocks_Block* type_clone(const TinyBlocks_Block* self, TinyBlocks* rt) +{ + const TinyBlocks_TypeBlock* src = (const TinyBlocks_TypeBlock*)self; + return (TinyBlocks_Block*)tb_type_block_create(rt, src->type_name, + src->input_descs, src->input_desc_count, + src->output_descs, src->output_desc_count, + src->eval_fn); +} + +static const TinyBlocks_BlockVTable s_type_vtable = { + .eval = type_eval, + .destroy = type_destroy, + .to_string = type_to_string, + .clone = type_clone, +}; + +/* ── Criação ─────────────────────────────────────────────────────────────── */ +TinyBlocks_TypeBlock* tb_type_block_create( + TinyBlocks* rt, + const char* type_name, + const TinyBlocks_SlotDesc* input_descs, uint32_t input_count, + const TinyBlocks_SlotDesc* output_descs, uint32_t output_count, + void (*eval_fn)(TinyBlocks_Block* self, TinyBlocks* rt)) +{ + TinyBlocks_TypeBlock* tb = (TinyBlocks_TypeBlock*)tb_block_alloc_base( + rt, TB_KIND_TYPE, sizeof(TinyBlocks_TypeBlock), + 0, 0, &s_type_vtable); + if (!tb) return NULL; + + tb->type_name = tb_strdup(rt, type_name); + tb->eval_fn = eval_fn; + tb->input_desc_count = input_count; + tb->output_desc_count = output_count; + + if (input_count > 0) { + tb->input_descs = tb_alloc(rt, input_count * sizeof(TinyBlocks_SlotDesc)); + if (!tb->input_descs) goto fail; + memcpy(tb->input_descs, input_descs, input_count * sizeof(TinyBlocks_SlotDesc)); + /* Duplica os nomes dos slots */ + for (uint32_t i = 0; i < input_count; ++i) + tb->input_descs[i].name = tb_strdup(rt, input_descs[i].name); + } + if (output_count > 0) { + tb->output_descs = tb_alloc(rt, output_count * sizeof(TinyBlocks_SlotDesc)); + if (!tb->output_descs) goto fail; + memcpy(tb->output_descs, output_descs, output_count * sizeof(TinyBlocks_SlotDesc)); + for (uint32_t i = 0; i < output_count; ++i) + tb->output_descs[i].name = tb_strdup(rt, output_descs[i].name); + } + + tb_rt_register_type(rt, tb); + return tb; + +fail: + tb_block_destroy(&tb->base, rt); + return NULL; +} + +void tb_type_block_destroy(TinyBlocks_TypeBlock* tb, TinyBlocks* rt) +{ + tb_block_destroy(&tb->base, rt); +} + +void tb_type_block_set_instance_hooks( + TinyBlocks_TypeBlock* tb, + size_t instance_userdata_size, + bool (*init )(TinyBlocks_Block* self, TinyBlocks* rt), + void (*deinit)(TinyBlocks_Block* self, TinyBlocks* rt)) +{ + if (!tb) return; + tb->instance_userdata_size = instance_userdata_size; + tb->instance_init = init; + tb->instance_deinit = deinit; +} + +TinyBlocks_TypeBlock* tb_type_block_find(TinyBlocks* rt, const char* type_name) +{ + return tb_rt_find_type(rt, type_name); +} diff --git a/src/tb_value.c b/src/tb_value.c new file mode 100644 index 0000000..52a74da --- /dev/null +++ b/src/tb_value.c @@ -0,0 +1,62 @@ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include "tinyblocks/tinyblocks.h" + +TinyBlocks_Value tb_value_none(void) +{ + TinyBlocks_Value v = { .kind = TB_VALUE_NONE }; + return v; +} + +TinyBlocks_Value tb_value_integer(int64_t n) +{ + TinyBlocks_Value v = { .kind = TB_VALUE_INTEGER, .as.integer = n }; + return v; +} + +TinyBlocks_Value tb_value_real(double d) +{ + TinyBlocks_Value v = { .kind = TB_VALUE_REAL, .as.real = d }; + return v; +} + +TinyBlocks_Value tb_value_text(const char* str) +{ + TinyBlocks_Value v = { .kind = TB_VALUE_TEXT }; + v.as.text = str ? strdup(str) : NULL; + return v; +} + +TinyBlocks_Value tb_value_block(TinyBlocks_Block* block) +{ + TinyBlocks_Value v = { .kind = TB_VALUE_BLOCK, .as.block = block }; + return v; +} + +TinyBlocks_Value tb_value_clone(TinyBlocks_Value v) +{ + if (v.kind == TB_VALUE_TEXT && v.as.text) + return tb_value_text(v.as.text); + if (v.kind == TB_VALUE_VECTOR && v.as.vector) + tb_vector_data_retain(v.as.vector); + if (v.kind == TB_VALUE_JSON && v.as.json) + tb_json_retain(v.as.json); + return v; +} + +void tb_value_free(TinyBlocks_Value* v) +{ + if (!v) return; + if (v->kind == TB_VALUE_TEXT) { + free(v->as.text); + v->as.text = NULL; + } else if (v->kind == TB_VALUE_VECTOR) { + tb_vector_data_release(v->as.vector); + v->as.vector = NULL; + } else if (v->kind == TB_VALUE_JSON) { + tb_json_release(v->as.json); + v->as.json = NULL; + } + v->kind = TB_VALUE_NONE; +} diff --git a/src/tb_vector_block.c b/src/tb_vector_block.c new file mode 100644 index 0000000..cc66f0d --- /dev/null +++ b/src/tb_vector_block.c @@ -0,0 +1,190 @@ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include "tinyblocks/tinyblocks.h" + +/* ══════════════════════════════════════════════════════════════════════════ + * TinyBlocks_VectorData — buffer de comandos ref-counted + * ══════════════════════════════════════════════════════════════════════════ */ +TinyBlocks_VectorData* tb_vector_data_create(void) { + TinyBlocks_VectorData* v = malloc(sizeof(TinyBlocks_VectorData)); + if (!v) return NULL; + v->capacity = 16; + v->count = 0; + v->ref = 1; + v->cmds = malloc(v->capacity * sizeof(TinyBlocks_VCmd)); + if (!v->cmds) { free(v); return NULL; } + return v; +} + +void tb_vector_data_retain(TinyBlocks_VectorData* v) { + if (v) v->ref++; +} + +void tb_vector_data_release(TinyBlocks_VectorData* v) { + if (!v) return; + if (--v->ref <= 0) { free(v->cmds); free(v); } +} + +TinyBlocks_VectorData* tb_vector_data_clone(const TinyBlocks_VectorData* src) { + if (!src) return NULL; + TinyBlocks_VectorData* v = tb_vector_data_create(); + if (!v) return NULL; + for (uint32_t i = 0; i < src->count; i++) + tb_vector_data_push(v, src->cmds[i]); + return v; +} + +bool tb_vector_data_push(TinyBlocks_VectorData* v, TinyBlocks_VCmd cmd) { + if (!v) return false; + if (v->count >= v->capacity) { + uint32_t nc = v->capacity * 2; + TinyBlocks_VCmd* a = realloc(v->cmds, nc * sizeof(TinyBlocks_VCmd)); + if (!a) return false; + v->cmds = a; v->capacity = nc; + } + v->cmds[v->count++] = cmd; + return true; +} + +/* ── Construtores de conveniência ────────────────────────────────────────── */ +#define PUSH0(v,k) tb_vector_data_push(v, (TinyBlocks_VCmd){(k), {0}}) +#define PUSH2(v,k,a,b) tb_vector_data_push(v, (TinyBlocks_VCmd){(k), {(a),(b)}}) +#define PUSH4(v,k,a,b,c,d) tb_vector_data_push(v,(TinyBlocks_VCmd){(k),{(a),(b),(c),(d)}}) +#define PUSH5(v,k,a,b,c,d,e) tb_vector_data_push(v,(TinyBlocks_VCmd){(k),{(a),(b),(c),(d),(e)}}) + +bool tb_vector_begin_path(TinyBlocks_VectorData* v) { return PUSH0(v, TB_VCMD_BEGIN_PATH); } +bool tb_vector_move_to (TinyBlocks_VectorData* v, float x, float y) { return PUSH2(v, TB_VCMD_MOVE_TO, x,y); } +bool tb_vector_line_to (TinyBlocks_VectorData* v, float x, float y) { return PUSH2(v, TB_VCMD_LINE_TO, x,y); } +bool tb_vector_close_path(TinyBlocks_VectorData* v) { return PUSH0(v, TB_VCMD_CLOSE_PATH); } + +bool tb_vector_stroke(TinyBlocks_VectorData* v, float r, float g, float b, float a, float w) { + return PUSH5(v, TB_VCMD_STROKE, r, g, b, a, w); +} +bool tb_vector_fill(TinyBlocks_VectorData* v, float r, float g, float b, float a) { + return PUSH4(v, TB_VCMD_FILL, r, g, b, a); +} +bool tb_vector_rect(TinyBlocks_VectorData* v, float x, float y, float w, float h) { + return PUSH4(v, TB_VCMD_RECT, x, y, w, h); +} +bool tb_vector_circle(TinyBlocks_VectorData* v, float cx, float cy, float radius) { + return PUSH5(v, TB_VCMD_CIRCLE, cx, cy, radius, 0, 0); +} + +#undef PUSH0 +#undef PUSH2 +#undef PUSH4 +#undef PUSH5 + +/* ── Value helpers ───────────────────────────────────────────────────────── */ +TinyBlocks_Value tb_value_vector(TinyBlocks_VectorData* v) { + TinyBlocks_Value val; + val.kind = TB_VALUE_VECTOR; + val.as.vector = v; + if (v) v->ref++; /* tb_value retém a referência */ + return val; +} + +TinyBlocks_VectorData* tb_value_as_vector(TinyBlocks_Value v) { + return v.kind == TB_VALUE_VECTOR ? v.as.vector : NULL; +} + +/* ── RenderableBlock play ────────────────────────────────────────────────── */ +void tb_draw_ctx_play(TinyBlocks_RenderableBlock* rb, TinyBlocks_VectorData* v) { + if (!rb || !v) return; + float px = 0.f, py = 0.f; /* ponto atual do path */ + float sx = 0.f, sy = 0.f; /* início do path (close_path) */ + float fr = 1.f, fg = 1.f, fb = 1.f, fa = 1.f; /* cor de fill/stroke atual */ + for (uint32_t i = 0; i < v->count; i++) { + TinyBlocks_VCmd* c = &v->cmds[i]; + switch (c->kind) { + case TB_VCMD_BEGIN_PATH: + break; + case TB_VCMD_MOVE_TO: + px = sx = c->args[0]; py = sy = c->args[1]; break; + case TB_VCMD_LINE_TO: + tb_draw_stroke_line(rb, px, py, c->args[0], c->args[1], 1.f, fr, fg, fb, fa); + px = c->args[0]; py = c->args[1]; + break; + case TB_VCMD_CLOSE_PATH: + tb_draw_stroke_line(rb, px, py, sx, sy, 1.f, fr, fg, fb, fa); + px = sx; py = sy; + break; + case TB_VCMD_STROKE: + fr = c->args[0]; fg = c->args[1]; fb = c->args[2]; fa = c->args[3]; + break; + case TB_VCMD_FILL: + fr = c->args[0]; fg = c->args[1]; fb = c->args[2]; fa = c->args[3]; + break; + case TB_VCMD_RECT: + tb_draw_fill_rect(rb, c->args[0], c->args[1], c->args[2], c->args[3], + fr, fg, fb, fa); + break; + case TB_VCMD_CIRCLE: + tb_draw_fill_circle(rb, c->args[0], c->args[1], c->args[2], fr, fg, fb, fa); + break; + } + } +} + +/* ══════════════════════════════════════════════════════════════════════════ + * TinyBlocks_VectorBlock — block kind TB_KIND_VECTOR + * ══════════════════════════════════════════════════════════════════════════ */ +static void vec_eval(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + TinyBlocks_VectorBlock* vb = (TinyBlocks_VectorBlock*)self; + /* Coloca o VectorData no output[0] como valor (com retain) */ + if (self->output_count > 0) + tb_block_set_output(self, 0, tb_value_vector(vb->data)); + self->dirty = false; +} + +static void vec_destroy(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + TinyBlocks_VectorBlock* vb = (TinyBlocks_VectorBlock*)self; + tb_vector_data_release(vb->data); + vb->data = NULL; +} + +static size_t vec_to_string(TinyBlocks_Block* self, TinyBlocks* rt, + char* buf, size_t sz) { + (void)rt; + TinyBlocks_VectorBlock* vb = (TinyBlocks_VectorBlock*)self; + return (size_t)snprintf(buf, sz, "[Vector %u cmds]", + vb->data ? vb->data->count : 0u); +} + +static TinyBlocks_Block* vec_clone(const TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_VectorBlock* src = (TinyBlocks_VectorBlock*)self; + TinyBlocks_VectorBlock* dst = tb_vector_block_create(rt); + if (!dst) return NULL; + if (src->data) { + dst->data = tb_vector_data_clone(src->data); + } + return &dst->base; +} + +static const TinyBlocks_BlockVTable s_vec_vtable = { + .eval = vec_eval, + .destroy = vec_destroy, + .to_string = vec_to_string, + .clone = vec_clone, +}; + +TinyBlocks_VectorBlock* tb_vector_block_create(TinyBlocks* rt) { + TinyBlocks_VectorBlock* b = (TinyBlocks_VectorBlock*)tb_block_alloc_base( + rt, TB_KIND_VECTOR, sizeof(TinyBlocks_VectorBlock), + 0, 1, &s_vec_vtable); + if (!b) return NULL; + b->data = tb_vector_data_create(); + return b; +} + +void tb_vector_block_set_data(TinyBlocks_VectorBlock* b, TinyBlocks_VectorData* v) { + if (!b) return; + tb_vector_data_release(b->data); + b->data = v; + if (v) v->ref++; + b->base.dirty = true; +} diff --git a/src/tinyblocks.c b/src/tinyblocks.c new file mode 100644 index 0000000..e437f38 --- /dev/null +++ b/src/tinyblocks.c @@ -0,0 +1,240 @@ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include +#include "tinyblocks/tinyblocks.h" + +/* ── Alocador padrão ─────────────────────────────────────────────────────── */ +static void* default_alloc(size_t size, void* ud) { (void)ud; return malloc(size); } +static void default_free (void* ptr, void* ud) { (void)ud; free(ptr); } + +/* ── Inicialização ───────────────────────────────────────────────────────── */ +bool tinyblocks_init(TinyBlocks** out_rt, const TinyBlocks_InitOptions* opts) +{ + if (!out_rt) return false; + + TinyBlocks_AllocFn alloc_fn = opts && opts->alloc ? opts->alloc : default_alloc; + TinyBlocks_FreeFn free_fn = opts && opts->free_fn ? opts->free_fn : default_free; + void* alloc_ud = opts ? opts->alloc_userdata : NULL; + + TinyBlocks* rt = alloc_fn(sizeof(TinyBlocks), alloc_ud); + if (!rt) return false; + memset(rt, 0, sizeof(TinyBlocks)); + + rt->alloc = alloc_fn; + rt->free = free_fn; + rt->alloc_userdata = alloc_ud; + rt->next_id = 1; + + uint32_t bcap = (opts && opts->initial_block_cap) ? opts->initial_block_cap : 64; + uint32_t tcap = (opts && opts->initial_type_cap) ? opts->initial_type_cap : 32; + uint32_t lcap = (opts && opts->initial_library_cap) ? opts->initial_library_cap : 16; + + rt->blocks = alloc_fn(bcap * sizeof(TinyBlocks_Block*), alloc_ud); + rt->types = alloc_fn(tcap * sizeof(TinyBlocks_TypeBlock*), alloc_ud); + rt->libraries = alloc_fn(lcap * sizeof(TinyBlocks_LibraryBlock*), alloc_ud); + rt->dl_handles= alloc_fn(lcap * sizeof(void*), alloc_ud); + + if (!rt->blocks || !rt->types || !rt->libraries || !rt->dl_handles) { + if (rt->blocks) free_fn(rt->blocks, alloc_ud); + if (rt->types) free_fn(rt->types, alloc_ud); + if (rt->libraries) free_fn(rt->libraries, alloc_ud); + if (rt->dl_handles)free_fn(rt->dl_handles,alloc_ud); + free_fn(rt, alloc_ud); + return false; + } + + rt->block_capacity = bcap; + rt->type_capacity = tcap; + rt->library_capacity = lcap; + rt->dl_handle_capacity = lcap; + + *out_rt = rt; + return true; +} + +/* ── Desinicialização ────────────────────────────────────────────────────── */ +void tinyblocks_deinit(TinyBlocks** rt_ptr) +{ + if (!rt_ptr || !*rt_ptr) return; + TinyBlocks* rt = *rt_ptr; + + /* Fase 1: destruir instâncias (KB_KIND_BLOCK) primeiro. + Elas referenciam TypeBlocks via ->type; devem ser liberadas antes + das libraries que contêm esses TypeBlocks. */ + { + uint32_t i = rt->block_count; + while (i > 0) { + TinyBlocks_Block* b = rt->blocks[i - 1]; + if (b->kind == TB_KIND_BLOCK) { + tb_block_destroy(b, rt); /* remove de rt->blocks e libera */ + i = rt->block_count; /* reinicia: o array mudou de tamanho */ + } else { + --i; + } + } + } + + /* Fase 2: descarregar libraries (invoca on_unload e destrói TypeBlocks). */ + while (rt->library_count > 0) { + TinyBlocks_LibraryBlock* lib = rt->libraries[rt->library_count - 1]; + if (lib->on_unload) lib->on_unload(lib, rt); + tb_library_block_destroy(lib, rt); + } + + /* Fase 3: TypeBlocks e primitivos órfãos (não pertencentes a nenhuma library). */ + while (rt->block_count > 0) { + TinyBlocks_Block* b = rt->blocks[rt->block_count - 1]; + tb_block_destroy(b, rt); + } + +#ifdef __linux__ + /* Fecha dl handles (apenas no Linux por enquanto) */ + for (uint32_t i = 0; i < rt->dl_handle_count; ++i) { + extern int dlclose(void*); + dlclose(rt->dl_handles[i]); + } +#endif + + TinyBlocks_FreeFn free_fn = rt->free; + void* alloc_ud = rt->alloc_userdata; + + free_fn(rt->blocks, alloc_ud); + free_fn(rt->types, alloc_ud); + free_fn(rt->libraries, alloc_ud); + free_fn(rt->dl_handles, alloc_ud); + free_fn(rt, alloc_ud); + + *rt_ptr = NULL; +} + +/* ── Alocação ────────────────────────────────────────────────────────────── */ +void* tb_alloc(TinyBlocks* rt, size_t size) +{ + void* p = rt->alloc(size, rt->alloc_userdata); + if (p) memset(p, 0, size); + return p; +} + +void tb_free(TinyBlocks* rt, void* ptr) +{ + if (ptr) rt->free(ptr, rt->alloc_userdata); +} + +char* tb_strdup(TinyBlocks* rt, const char* str) +{ + if (!str) return NULL; + size_t n = strlen(str) + 1; + char* p = rt->alloc(n, rt->alloc_userdata); + if (p) memcpy(p, str, n); + return p; +} + +/* ── Geração de ID ───────────────────────────────────────────────────────── */ +uint64_t tb_rt_next_id(TinyBlocks* rt) { return rt->next_id++; } + +/* ── Registro de blocos ──────────────────────────────────────────────────── */ +static bool grow_array(TinyBlocks* rt, void*** arr, uint32_t* cap, uint32_t count) +{ + if (count < *cap) return true; + uint32_t new_cap = (*cap) * 2; + void** new_arr = rt->alloc(new_cap * sizeof(void*), rt->alloc_userdata); + if (!new_arr) return false; + memcpy(new_arr, *arr, count * sizeof(void*)); + rt->free(*arr, rt->alloc_userdata); + *arr = new_arr; + *cap = new_cap; + return true; +} + +bool tb_rt_register_block(TinyBlocks* rt, TinyBlocks_Block* block) +{ + if (!grow_array(rt, (void***)&rt->blocks, &rt->block_capacity, rt->block_count)) + return false; + rt->blocks[rt->block_count++] = block; + return true; +} + +void tb_rt_unregister_block(TinyBlocks* rt, TinyBlocks_Block* block) +{ + for (uint32_t i = 0; i < rt->block_count; ++i) { + if (rt->blocks[i] == block) { + rt->blocks[i] = rt->blocks[--rt->block_count]; + return; + } + } +} + +bool tb_rt_register_type(TinyBlocks* rt, TinyBlocks_TypeBlock* type) +{ + if (!grow_array(rt, (void***)&rt->types, &rt->type_capacity, rt->type_count)) + return false; + rt->types[rt->type_count++] = type; + return true; +} + +void tb_rt_unregister_type(TinyBlocks* rt, TinyBlocks_TypeBlock* type) +{ + for (uint32_t i = 0; i < rt->type_count; ++i) { + if (rt->types[i] == type) { + rt->types[i] = rt->types[--rt->type_count]; + return; + } + } +} + +bool tb_rt_register_library(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) +{ + if (!grow_array(rt, (void***)&rt->libraries, &rt->library_capacity, rt->library_count)) + return false; + rt->libraries[rt->library_count++] = lib; + return true; +} + +void tb_rt_unregister_library(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) +{ + for (uint32_t i = 0; i < rt->library_count; ++i) { + if (rt->libraries[i] == lib) { + rt->libraries[i] = rt->libraries[--rt->library_count]; + return; + } + } +} + +/* ── Busca ───────────────────────────────────────────────────────────────── */ +TinyBlocks_Block* tb_rt_find_block(TinyBlocks* rt, uint64_t id) +{ + for (uint32_t i = 0; i < rt->block_count; ++i) + if (rt->blocks[i]->id == id) return rt->blocks[i]; + return NULL; +} + +TinyBlocks_TypeBlock* tb_rt_find_type(TinyBlocks* rt, const char* name) +{ + for (uint32_t i = 0; i < rt->type_count; ++i) + if (rt->types[i]->type_name && strcmp(rt->types[i]->type_name, name) == 0) + return rt->types[i]; + return NULL; +} + +TinyBlocks_LibraryBlock* tb_rt_find_library(TinyBlocks* rt, const char* name) +{ + for (uint32_t i = 0; i < rt->library_count; ++i) + if (rt->libraries[i]->base.name && + strcmp(rt->libraries[i]->base.name, name) == 0) + return rt->libraries[i]; + return NULL; +} + +/* ── Erros ───────────────────────────────────────────────────────────────── */ +const char* tinyblocks_last_error(TinyBlocks* rt) { return rt->error; } +void tinyblocks_clear_error(TinyBlocks* rt) { rt->error[0] = '\0'; } + +void tinyblocks_set_error(TinyBlocks* rt, const char* fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + vsnprintf(rt->error, sizeof(rt->error), fmt, ap); + va_end(ap); +}