diff --git a/Makefile b/Makefile index 1c5dabf..e6550c2 100644 --- a/Makefile +++ b/Makefile @@ -32,13 +32,13 @@ OBJS_DBG := $(patsubst src/%.c,$(BUILD)/%-dbg.o,$(SRCS)) 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 "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 ──────────────────────────────────────────────────────────── +# -- Biblioteca --- static: $(LIB_A) ## Compila build/libtinyblocks.a shared: $(LIB_SO) ## Compila build/libtinyblocks.so @@ -58,7 +58,7 @@ $(LIB_A): $(OBJS) $(LIB_SO): $(OBJS) $(CC) -shared -o $@ $^ -# ── Exemplo hello ───────────────────────────────────────────────────────── +# -- Exemplo hello --- $(EXAMPLE): examples/hello/main.c $(LIB_A) $(CC) $(CFLAGS_REL) $< -o $@ -L$(BUILD) -ltinyblocks @@ -67,7 +67,7 @@ example: $(EXAMPLE) ## Compila o exemplo hello run: example ## Compila e roda o exemplo hello ./$(EXAMPLE) -# ── Build de debug com ASan/UBSan ──────────────────────────────────────── +# -- Build de debug com ASan/UBSan --- $(BUILD)/libtinyblocks-dbg.a: $(OBJS_DBG) ar rcs $@ $^ @@ -77,7 +77,7 @@ $(BUILD)/hello-dbg: examples/hello/main.c $(BUILD)/libtinyblocks-dbg.a debug: $(BUILD)/hello-dbg ## Compila e roda o hello com ASan/UBSan ./$(BUILD)/hello-dbg -# ── Library SDL2 ────────────────────────────────────────────────────────── +# -- Library SDL2 --- SDL2_CFLAGS := $(shell sdl2-config --cflags) SDL2_LIBS := $(shell sdl2-config --libs) @@ -107,7 +107,7 @@ $(BUILD)/libtinyblocks-sdl2.so: libraries/tinyblocks-sdl2/src/tb_sdl2.c $(GFX_HD 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) ─────────────────── +# -- 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 \ @@ -122,7 +122,33 @@ graphics: static $(BUILD)/libtinyblocks-graphics.a $(BUILD)/libtinyblocks-sdl2.a run-sdl2: sdl2 ## Compila e roda o exemplo SDL2 LD_LIBRARY_PATH=$(BUILD) ./$(BUILD)/sdl2-example -# ── Library Editor ──────────────────────────────────────────────────────── +# -- Libraries de categoria (uma por seção da paleta) -- +CAT_LIBS := events control operators variables appearance pen +CAT_A := $(patsubst %,$(BUILD)/libtinyblocks-%.a,$(CAT_LIBS)) +CAT_SO := $(patsubst %,$(BUILD)/tinyblocks-%.so,$(CAT_LIBS)) +CAT_LDFLAGS := $(patsubst %,-ltinyblocks-%,$(CAT_LIBS)) + +define CAT_LIB_RULE +$(BUILD)/tb_$(1).o: libraries/tinyblocks-$(1)/src/tb_$(1).c libraries/tinyblocks-$(1)/include/tb_$(1).h $(HDRS) + @mkdir -p $(BUILD) + $(CC) $(CFLAGS_REL) -Ilibraries/tinyblocks-$(1)/include -Ilibraries/tinyblocks-editor/src -fPIC -c $$< -o $$@ + +$(BUILD)/libtinyblocks-$(1).a: $(BUILD)/tb_$(1).o + ar rcs $$@ $$^ + +$(BUILD)/tinyblocks-$(1).so: libraries/tinyblocks-$(1)/src/tb_$(1).c libraries/tinyblocks-$(1)/include/tb_$(1).h $(LIB_A) + $(CC) $(CFLAGS_REL) -Ilibraries/tinyblocks-$(1)/include -Ilibraries/tinyblocks-editor/src -fPIC -shared $$< -o $$@ -L$(BUILD) -ltinyblocks '-Wl,-rpath,$$$$ORIGIN' +endef + +$(foreach l,$(CAT_LIBS),$(eval $(call CAT_LIB_RULE,$(l)))) + +category-libs: static $(CAT_A) ## Compila as libraries de categoria (.a) + @echo "Build category libs OK: $(CAT_A)" + +category-sos: static $(CAT_SO) ## Compila as libraries de categoria (.so, hot reload) + @echo "Build category .so OK: $(CAT_SO)" + +# -- Library Editor --- SDL2TTF_CFLAGS := $(shell pkg-config --cflags SDL2_ttf 2>/dev/null) SDL2TTF_LIBS := $(shell pkg-config --libs SDL2_ttf 2>/dev/null) @@ -130,7 +156,8 @@ 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 $@ + $(CC) $(CFLAGS_REL) -Ilibraries/tinyblocks-editor/include -I$(GFX_INC) \ + $(patsubst %,-Ilibraries/tinyblocks-%/include,$(CAT_LIBS)) -fPIC -c $< -o $@ $(BUILD)/tb_stage.o: $(EDITOR_SRC)/tb_stage.c $(EDITOR_HDRS) $(CC) $(CFLAGS_REL) -I$(GFX_INC) -fPIC -c $< -o $@ @@ -139,52 +166,55 @@ $(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) \ + $(BUILD)/libtinyblocks-graphics.a $(BUILD)/libtinyblocks-sdl2.a $(CAT_A) + $(CC) $(CFLAGS_REL) \ + -Ilibraries/tinyblocks-editor/include -I$(GFX_INC) \ + $(patsubst %,-Ilibraries/tinyblocks-%/include,$(CAT_LIBS)) \ $< -o $@ \ - -L$(BUILD) -ltinyblocks-editor -ltinyblocks-graphics -ltinyblocks-sdl2 -ltinyblocks \ + -L$(BUILD) -Wl,--start-group -ltinyblocks-editor -ltinyblocks-graphics \ + -ltinyblocks-sdl2 $(CAT_LDFLAGS) -ltinyblocks -Wl,--end-group \ $(SDL2_LIBS) $(SDL2TTF_LIBS) -ldl -lm \ '-Wl,-rpath,$$ORIGIN' -editor: static graphics $(BUILD)/libtinyblocks-editor.a $(BUILD)/editor ## Compila o editor visual (estilo Scratch) +editor: static graphics $(BUILD)/libtinyblocks-editor.a $(CAT_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) ────────────────────────────── +# -- 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" +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 ─────────────────────────────────────────────────── +# -- 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" +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 ──────────────────────────────────────────────────────── +# -- 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" +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) ─────────────────── +# -- 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 +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) ─────────────────────────────────── +# -- 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) @@ -193,7 +223,7 @@ $(BUILD)/tb_python_lib.o: libraries/tinyblocks-python/src/tb_python.c $(CC) $(CFLAGS_REL) $(PYTHON_CFLAGS) \ -Ilibraries/tinyblocks-python/include -fPIC -c $< -o $@ -# Shared lib — garante um único interpretador Python no processo +# 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) @@ -203,10 +233,10 @@ $(BUILD)/python.so: examples/python/python.c $(LIB_A) $(BUILD)/libtinyblocks-pyt $< -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 +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) ────────────────────────────────── +# -- 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 $< $@ @@ -235,11 +265,11 @@ $(BUILD)/mcp.so: examples/mcp/mcp.c $(LIB_A) \ $< -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 +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 ─────────────────────────────────────────────────────────────── -# ── Testes (harness headless com ASan/UBSan) ──────────────────────────── +# -- Limpeza --- +# -- Testes (harness headless com ASan/UBSan) --- $(BUILD)/editor_harness: tests/editor_harness.c $(SRCS) \ $(EDITOR_SRC)/tb_editor.c $(EDITOR_SRC)/tb_stage.c \ libraries/tinyblocks-graphics/src/tb_graphics.c @@ -247,9 +277,11 @@ $(BUILD)/editor_harness: tests/editor_harness.c $(SRCS) \ $(CC) $(CFLAGS_DBG) \ -Ilibraries/tinyblocks-editor/include -Ilibraries/tinyblocks-editor/src \ -I$(GFX_INC) \ + $(patsubst %,-Ilibraries/tinyblocks-%/include,$(CAT_LIBS)) \ $(SRCS) \ $(EDITOR_SRC)/tb_editor.c $(EDITOR_SRC)/tb_stage.c \ libraries/tinyblocks-graphics/src/tb_graphics.c \ + $(foreach l,$(CAT_LIBS),libraries/tinyblocks-$(l)/src/tb_$(l).c) \ tests/editor_harness.c -o $@ -ldl -lm test-editor: $(BUILD)/editor_harness ## Roda o harness headless do editor (ASan/UBSan) diff --git a/examples/editor/main.c b/examples/editor/main.c index ba07a3d..a582ab5 100644 --- a/examples/editor/main.c +++ b/examples/editor/main.c @@ -1,11 +1,16 @@ /* - * TinyBlocks — exemplo editor + * TinyBlocks - exemplo editor + * + * Abre o editor visual com as libraries de categoria registradas: + * Eventos, Controle, Operadores, Variáveis, Aparência, Caneta, Meus Blocos. * - * 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 ...] + * + * O editor não conhece essas libraries: elas apenas registram seus blocos e + * declaram uma categoria, e o editor monta a paleta a partir disso. */ #include #include @@ -13,97 +18,12 @@ #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(va +#include +#include +#include +#include +#include int main(int argc, char** argv) { TinyBlocks* rt = NULL; @@ -118,42 +38,19 @@ int main(int argc, char** argv) { } } - /* Slots reutilizáveis */ - static const TinyBlocks_SlotDesc two_int[] = { - {"a", TB_VALUE_INTEGER}, {"b", TB_VALUE_INTEGER} }; - static const TinyBlocks_SlotDesc one_int[] = { - {"n", TB_VALUE_INTEGER} }; - static const TinyBlocks_SlotDesc int_out[] = { {"result", TB_VALUE_INTEGER} }; - static const TinyBlocks_SlotDesc print_in[] = { - {"label", TB_VALUE_TEXT}, {"value", TB_VALUE_NONE} }; - static const TinyBlocks_SlotDesc two_text[] = { - {"a", TB_VALUE_TEXT}, {"b", TB_VALUE_TEXT} }; - static const TinyBlocks_SlotDesc text_out[] = { {"result", TB_VALUE_TEXT} }; - static const TinyBlocks_SlotDesc text_in[] = { {"text", TB_VALUE_TEXT} }; + /* Libraries de categoria, na ordem em que aparecem na paleta */ + tb_library_register(rt, tb_events_get_library()); + tb_library_register(rt, tb_control_get_library()); + tb_library_register(rt, tb_operators_get_library()); + tb_library_register(rt, tb_variables_get_library()); + tb_library_register(rt, tb_appearance_get_library()); + tb_library_register(rt, tb_pen_get_library()); - /* Math */ - tb_type_block_create(rt,"Math.Add", two_int,2, int_out,1, eval_math_add); - tb_type_block_create(rt,"Math.Sub", two_int,2, int_out,1, eval_math_sub); - tb_type_block_create(rt,"Math.Mul", two_int,2, int_out,1, eval_math_mul); - tb_type_block_create(rt,"Math.Div", two_int,2, int_out,1, eval_math_div); - tb_type_block_create(rt,"Math.Mod", two_int,2, int_out,1, eval_math_mod); - tb_type_block_create(rt,"Math.Abs", one_int,1, int_out,1, eval_math_abs); - tb_type_block_create(rt,"Math.Max", two_int,2, int_out,1, eval_math_max); - tb_type_block_create(rt,"Math.Min", two_int,2, int_out,1, eval_math_min); - - /* IO */ - tb_type_block_create(rt,"IO.Print", print_in,2, NULL,0, eval_io_print); - tb_type_block_create(rt,"IO.PrintInt", one_int,1, NULL,0, eval_io_print_int); - - /* Text */ - tb_type_block_create(rt,"Text.Concat", two_text,2, text_out,1, eval_text_concat); - tb_type_block_create(rt,"Text.Length", text_in, 1, int_out, 1, eval_text_len); - - /* Interface gráfica primeiro: o editor mede texto e cria o palco ao nascer */ + /* Interface gráfica: o editor mede texto e cria o palco ao nascer */ tb_library_register(rt, tb_graphics_get_library()); tb_library_register(rt, tb_editor_get_library()); - /* Graphics.Input → Editor.Scene → Graphics.Window */ + /* Graphics.Input - Editor.Scene - Graphics.Window */ TinyBlocks_TypeBlock* t_input = tb_type_block_find(rt, "Graphics.Input"); TinyBlocks_TypeBlock* t_scene = tb_type_block_find(rt, "Editor.Scene"); TinyBlocks_TypeBlock* t_win = tb_type_block_find(rt, "Graphics.Window"); diff --git a/include/tinyblocks/tb_library_block.h b/include/tinyblocks/tb_library_block.h index 2e648b0..dcb5a0b 100644 --- a/include/tinyblocks/tb_library_block.h +++ b/include/tinyblocks/tb_library_block.h @@ -1,5 +1,5 @@ /* - * TinyBlocks — tb_library_block.h + * 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 @@ -15,6 +15,13 @@ #include "tb_block.h" +/* == Metadados opcionais de categoria (usados por UIs, ex.: o editor) === */ +typedef struct TinyBlocks_Category { + const char* name; /* nome exibido, ex.: "Controle" */ + float color[4]; /* r,g,b,a (0..1) */ + float dark[4]; /* variante escura para contorno/sombra */ +} TinyBlocks_Category; + struct TinyBlocks_LibraryBlock { TinyBlocks_Block base; /* DEVE ser o primeiro campo */ @@ -27,9 +34,13 @@ struct TinyBlocks_LibraryBlock { void (*on_unload)(TinyBlocks_LibraryBlock* self, TinyBlocks* rt); void* lib_userdata; /* dados privados da library */ + + /* Categoria opcional: quando definida, todos os TypeBlocks desta library + * pertencem a ela (a UI, como o editor, agrupa a paleta por categoria). */ + const TinyBlocks_Category* category; }; -/* ── Descritor exportado por cada library .so/.dll ───────────────────────── */ +/* == Descritor exportado por cada library .so/.dll === */ typedef struct TinyBlocks_LibraryDescriptor { const char* name; const char* version; @@ -53,11 +64,15 @@ typedef struct TinyBlocks_LibraryDescriptor { return &_tb_lib_desc_##sym; \ } -/* ── Operações em LibraryBlock ───────────────────────────────────────────── */ +/* == 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); +/* Define a categoria de uma library (todos os seus TypeBlocks vão para ela) */ +TB_API void tb_library_set_category(TinyBlocks_LibraryBlock* lib, + const TinyBlocks_Category* category); + /* Adiciona um bloco à library (a library não toma ownership do bloco) */ TB_API bool tb_library_add(TinyBlocks_LibraryBlock* lib, TinyBlocks_Block* block); @@ -68,7 +83,7 @@ TB_API bool tb_library_remove_at(TinyBlocks_LibraryBlock* lib, uint32_t index); TB_API TinyBlocks_Block* tb_library_find(TinyBlocks_LibraryBlock* lib, const char* name); -/* ── Carregamento dinâmico de libraries ──────────────────────────────────── */ +/* == 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); diff --git a/libraries/tinyblocks-appearance/include/tb_appearance.h b/libraries/tinyblocks-appearance/include/tb_appearance.h new file mode 100644 index 0000000..07101eb --- /dev/null +++ b/libraries/tinyblocks-appearance/include/tb_appearance.h @@ -0,0 +1,12 @@ +/* + * TinyBlocks - tb_appearance.h + * Library da categoria "Aparência": saída/escrita (IO.Print, IO.PrintInt). + */ +#ifndef TINYBLOCKS_APPEARANCE_H +#define TINYBLOCKS_APPEARANCE_H + +#include + +TB_API const TinyBlocks_LibraryDescriptor* tb_appearance_get_library(void); + +#endif /* TINYBLOCKS_APPEARANCE_H */ diff --git a/libraries/tinyblocks-appearance/src/tb_appearance.c b/libraries/tinyblocks-appearance/src/tb_appearance.c new file mode 100644 index 0000000..0f8af59 --- /dev/null +++ b/libraries/tinyblocks-appearance/src/tb_appearance.c @@ -0,0 +1,62 @@ +/* + * TinyBlocks - tb_appearance.c + * Categoria "Aparência": blocos que produzem saída visível (console do editor). + */ +#include +#include +#include "tb_appearance.h" + +static void eval_print(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value label = tb_block_get_input(self, rt, 0); + TinyBlocks_Value value = tb_block_get_input(self, rt, 1); + const char* lbl = label.kind == TB_VALUE_TEXT ? label.as.text : "resultado"; + if (value.kind == TB_VALUE_INTEGER) + printf("%s = %lld\n", lbl, (long long)value.as.integer); + else if (value.kind == TB_VALUE_REAL) + printf("%s = %g\n", lbl, value.as.real); + else if (value.kind == TB_VALUE_TEXT) + printf("%s = %s\n", lbl, value.as.text ? value.as.text : ""); + else + printf("%s\n", lbl); + self->dirty = false; +} + +static void eval_print_int(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; + printf("%lld\n", (long long)n); + self->dirty = false; +} + +static bool appearance_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + static const TinyBlocks_Category cat = { + "Aparência", + {153/255.f, 102/255.f, 255/255.f, 1.f}, + {119/255.f, 77/255.f, 203/255.f, 1.f}, + }; + tb_library_set_category(lib, &cat); + + static const TinyBlocks_SlotDesc print_in[] = {{"label", TB_VALUE_TEXT}, {"value", TB_VALUE_NONE}}; + static const TinyBlocks_SlotDesc one_int[] = {{"n", TB_VALUE_INTEGER}}; + + TinyBlocks_TypeBlock* t; + t = tb_type_block_create(rt, "IO.Print", print_in, 2, NULL, 0, eval_print); + if (!t || !tb_library_add(lib, &t->base)) return false; + t = tb_type_block_create(rt, "IO.PrintInt", one_int, 1, NULL, 0, eval_print_int); + if (!t || !tb_library_add(lib, &t->base)) return false; + return true; +} + +static void appearance_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + (void)rt; (void)lib; +} + +TINYBLOCKS_DEFINE_LIBRARY(appearance, + "tinyblocks-appearance", + "1.0.0", + appearance_init, + appearance_deinit) + +const TinyBlocks_LibraryDescriptor* tb_appearance_get_library(void) { + return &_tb_lib_desc_appearance; +} diff --git a/libraries/tinyblocks-control/include/tb_control.h b/libraries/tinyblocks-control/include/tb_control.h new file mode 100644 index 0000000..65ba4b6 --- /dev/null +++ b/libraries/tinyblocks-control/include/tb_control.h @@ -0,0 +1,12 @@ +/* + * TinyBlocks - tb_control.h + * Library da categoria "Controle" (repita, se, se-senão, repita até que). + */ +#ifndef TINYBLOCKS_CONTROL_H +#define TINYBLOCKS_CONTROL_H + +#include + +TB_API const TinyBlocks_LibraryDescriptor* tb_control_get_library(void); + +#endif /* TINYBLOCKS_CONTROL_H */ diff --git a/libraries/tinyblocks-control/src/tb_control.c b/libraries/tinyblocks-control/src/tb_control.c new file mode 100644 index 0000000..58d4eef --- /dev/null +++ b/libraries/tinyblocks-control/src/tb_control.c @@ -0,0 +1,49 @@ +/* + * TinyBlocks - tb_control.c + * Categoria "Controle": repita / repita até que / se / se-senão. + * A semântica (bocas e sequência) é interpretada pelo editor; aqui só + * registramos os tipos e a categoria. + */ +#include +#include "tb_control.h" + +static void eval_noop(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + self->dirty = false; +} + +static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name, + const TinyBlocks_SlotDesc* in, uint32_t ni) { + TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, NULL, 0, eval_noop); + return t && tb_library_add(lib, &t->base); +} + +static bool control_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + static const TinyBlocks_Category cat = { + "Controle", + {255/255.f, 171/255.f, 25/255.f, 1.f}, + {207/255.f, 139/255.f, 23/255.f, 1.f}, + }; + tb_library_set_category(lib, &cat); + + static const TinyBlocks_SlotDesc times_in[] = {{"vezes", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc cond_in[] = {{"condição", TB_VALUE_INTEGER}}; + return reg(rt, lib, "Control.Repeat", times_in, 1) + && reg(rt, lib, "Control.RepeatUntil", cond_in, 1) + && reg(rt, lib, "Control.If", cond_in, 1) + && reg(rt, lib, "Control.IfElse", cond_in, 1); +} + +static void control_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + (void)rt; (void)lib; +} + +TINYBLOCKS_DEFINE_LIBRARY(control, + "tinyblocks-control", + "1.0.0", + control_init, + control_deinit) + +const TinyBlocks_LibraryDescriptor* tb_control_get_library(void) { + return &_tb_lib_desc_control; +} diff --git a/libraries/tinyblocks-editor/src/tb_editor.c b/libraries/tinyblocks-editor/src/tb_editor.c index a0b6377..6337134 100644 --- a/libraries/tinyblocks-editor/src/tb_editor.c +++ b/libraries/tinyblocks-editor/src/tb_editor.c @@ -1,5 +1,5 @@ /* - * TinyBlocks — tb_editor.c + * 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 @@ -15,10 +15,10 @@ * - 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. + * - "quando a bandeira 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 + * 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 @@ -35,13 +35,14 @@ #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; @@ -51,14 +52,14 @@ TB_API void tb_editor_preload(const char* path) { 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 │ - * └───┴─────────────────┴─────────────────────────────┴─────────────────────┘ - * ══════════════════════════════════════════════════════════════════════════ */ + * ==== barra de menu (azul) ==== + * == abas ===== [flag] [run] ==== + * =cat= flyout (blocos) - área de scripts - palco / saída = + * ================= + * === */ #define WIN_W_DEFAULT 1280 #define WIN_H_DEFAULT 720 #define MENU_H 44 @@ -82,7 +83,7 @@ TB_API void tb_editor_preload(const char* path) { #define LIB_BTN_X 150 #define LIB_BTN_W 170 -/* ── Geometria dos blocos ────────────────────────────────────────────────── */ +/* == Geometria dos blocos === */ #define FS 12 /* texto dos blocos */ #define FS_UI 13 /* texto da interface */ #define FS_SM 11 @@ -112,7 +113,6 @@ TB_API void tb_editor_preload(const char* path) { #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 @@ -124,9 +124,9 @@ TB_API void tb_editor_preload(const char* path) { #define MAX_UBLK_SLOTS 8 #define MAX_UBLK_PARTS 16 -/* ══════════════════════════════════════════════════════════════════════════ - * Cores (paleta do Scratch 3) — componentes 0..1 - * ══════════════════════════════════════════════════════════════════════════ */ +/* === + * 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}) @@ -158,21 +158,9 @@ 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)}, -}; +/* == Categorias (vêm das libraries; "Meus Blocos" é do editor) === */ +static const Col COL_MYBLOCKS_COL = C(255,102,128); +static const Col COL_MYBLOCKS_DARK = C(255, 51, 85); #define USER_COLOR_COUNT 8 static const Col s_user_colors[USER_COLOR_COUNT] = { @@ -180,7 +168,7 @@ static const Col s_user_colors[USER_COLOR_COUNT] = { 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) ───────────────────────── */ +/* == Rótulos dos blocos (%N - campo de entrada N) === */ typedef struct { const char* type; const char* label; @@ -188,7 +176,7 @@ typedef struct { } BlockSpec; static const BlockSpec s_specs[] = { - {"Events.WhenRun", "quando ⚑ for clicado", NULL}, + {"Events.WhenRun", "quando a bandeira for clicado", NULL}, {"Control.Repeat", "repita %1 vezes", "10"}, {"Control.RepeatUntil", "repita até que %1", NULL}, {"Control.If", "se %1 então", NULL}, @@ -228,9 +216,9 @@ static const BlockSpec s_specs[] = { {"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 */ @@ -259,7 +247,7 @@ typedef struct { char in_text[MAX_INPUTS][64]; char lit_text[LIT_TEXT_CAP]; - /* layout — recalculado a cada frame */ + /* layout - recalculado a cada frame */ float ax, ay, w, h; float row_y, row_h, prev_y; float sub_y[2], sub_h[2]; @@ -310,7 +298,8 @@ typedef struct { TinyBlocks_LibraryBlock* lib; } HotLib; -typedef struct { char name[32]; char prefix[32]; Col col, dark; float fly_y; } Cat; +typedef struct { char name[32]; char prefix[32]; Col col, dark; float fly_y; + const TinyBlocks_LibraryBlock* lib; } Cat; typedef enum { FI_HEADER, FI_BUTTON, FI_BLOCK } FlyKind; typedef struct { FlyKind kind; int cat; int bi; float y, h; } FlyItem; @@ -324,6 +313,7 @@ typedef struct { Cat cats[MAX_CATS]; int cat_n; + int myblocks_cat; /* índice da categoria "Meus Blocos" */ Tab fly; /* blocos-modelo do flyout */ FlyItem fly_items[MAX_FLY]; int fly_n; @@ -377,9 +367,6 @@ typedef struct { 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; @@ -417,7 +404,7 @@ typedef struct { #define CT (ed->tabs[ed->cur_tab]) -/* Ponteiro global para o editor ativo — os eval_fn dos blocos do editor +/* 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; @@ -430,9 +417,9 @@ static bool dlg_click(Ed* ed, float mx, float my); static void dlg_key(Ed* ed, int sc); static void dlg_text(Ed* ed, const char* typed); -/* ══════════════════════════════════════════════════════════════════════════ - * Helpers de desenho — emitem TinyBlocks_DrawCmd em um RenderableBlock - * ══════════════════════════════════════════════════════════════════════════ */ +/* === + * 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); } @@ -487,7 +474,7 @@ static void draw_hex(TinyBlocks_RenderableBlock* rb, float x, float y, float w, } } -/* Encaixe trapezoidal sob um comando; y = borda inferior do bloco */ +/* 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++) @@ -496,9 +483,9 @@ static void draw_bump(TinyBlocks_RenderableBlock* rb, float x, float y, Col c, C 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; @@ -566,16 +553,9 @@ static TinyBlocks_Value value_from_text(const char* raw, TinyBlocks_ValueKind k) } } -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,'.'); @@ -642,21 +622,6 @@ 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); @@ -664,15 +629,29 @@ static void type_prefix(const char* n, char* out, size_t cap) { 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; +/* Categoria de um TypeBlock: pela library que o contém, ou por prefixo. */ +static int cat_of_type(Ed* ed, const TinyBlocks_TypeBlock* t) { + if (!t || !t->type_name) return -1; + const char* n = t->type_name; + if (strncmp(n, "User.", 5) == 0 || strncmp(n, "Port.", 5) == 0) + return ed->myblocks_cat; + if (t->base.parent && t->base.parent->kind == TB_KIND_LIBRARY) { + const TinyBlocks_LibraryBlock* lib = + (const TinyBlocks_LibraryBlock*)t->base.parent; + for (int i = 0; i < ed->cat_n; i++) + if (ed->cats[i].lib == lib) return i; + } 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; + for (int i = 0; i < ed->cat_n; i++) + if (ed->cats[i].prefix[0] && strcmp(ed->cats[i].prefix, pre) == 0) return i; return -1; } +static int cat_of(Ed* ed, const char* n) { + if (!n) return -1; + return cat_of_type(ed, tb_type_block_find(ed->rt, n)); +} + 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]; @@ -693,9 +672,9 @@ static void block_cols(Ed* ed, const EdBlock* b, Col* c, Col* d) { *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); @@ -769,7 +748,7 @@ static void top_add(Tab* T, int bi) { if (T->top_n < MAX_WS) T->top[T->top_n++] = bi; } -/* Liga child ao pai na relação rel (child = -1 desliga) */ +/* 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; @@ -849,7 +828,7 @@ static void mark_drag(Tab* T, int bi, bool v) { } } -/* Cópia profunda (repórteres, bocas e — se with_next — os blocos abaixo) */ +/* 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) { @@ -910,9 +889,9 @@ static void delete_heal(Ed* ed, Tab* T, int bi) { 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]; } @@ -935,7 +914,7 @@ static bool text_line(const char* s, int idx, char* out, size_t cap) { 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, "…"); + if (cut) strcat(out, "="); return true; } @@ -1114,9 +1093,9 @@ static void layout_tab(Tab* T) { } } -/* ══════════════════════════════════════════════════════════════════════════ +/* === * 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; @@ -1174,9 +1153,9 @@ static int hit_slot(Tab* T, int bi, float x, float y) { 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]; @@ -1211,7 +1190,7 @@ static void render_block(Ed* ed, TinyBlocks_RenderableBlock* rb, Tab* T, int bi, 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 ─────────────────────── */ + /* == 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); @@ -1247,7 +1226,7 @@ static void render_block(Ed* ed, TinyBlocks_RenderableBlock* rb, Tab* T, int bi, break; } - /* ── Rótulo e campos vazios ─────────────────────────────────────── */ + /* == 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; @@ -1261,18 +1240,18 @@ static void render_block(Ed* ed, TinyBlocks_RenderableBlock* rb, Tab* T, int bi, 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) ────────────────────────────────────── */ + /* == 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 ──────────────────────────────────────── */ + /* == 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 ────────────────────────────────────────────── */ + /* == Á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)); @@ -1298,9 +1277,9 @@ static void render_chain(Ed* ed, TinyBlocks_RenderableBlock* rb, Tab* T, int hea 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); } @@ -1319,18 +1298,7 @@ static void run_abort(Ed* ed, const char* msg) { 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) { +static void clear_live(Tab* T) { for (int i = 0; i < MAX_WS; i++) T->ws[i].live_rt = NULL; } @@ -1340,8 +1308,7 @@ static void run_reset(Ed* ed) { 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); + tb_variables_reset_blocks(); } static void run_track(Ed* ed, TinyBlocks_Block* b) { @@ -1488,7 +1455,7 @@ static void run_end(Ed* ed) { palette_rebuild(ed); /* variáveis novas aparecem no flyout */ } -/* Bandeira verde: roda os scripts "quando ⚑ for clicado", de cima para baixo */ +/* Bandeira verde: roda os scripts "quando a bandeira for clicado", de cima para baixo */ static void run_flag(Ed* ed) { run_begin(ed, true); int heads[MAX_WS], n = 0; @@ -1506,7 +1473,7 @@ static void run_flag(Ed* ed) { } } run_end(ed); - if (!started) stage_append(ed, "Nenhum script começa com \"quando ⚑ for clicado\".\n"); + if (!started) stage_append(ed, "Nenhum script começa com \"quando a bandeira for clicado\".\n"); } /* Clique num bloco: roda a pilha inteira, ou mostra o valor de um repórter */ @@ -1526,122 +1493,17 @@ static void run_click(Ed* ed, int bi) { 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; -} - +/* === + * Portas de blocos compostos ("Meus Blocos") + * === */ 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") ──────────────────────────────────── +/* == 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. */ + * 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; @@ -1708,9 +1570,9 @@ static void eval_composite(TinyBlocks_Block* self, TinyBlocks* rt) { 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; } } @@ -1747,9 +1609,9 @@ static void retype_all(Ed* ed) { 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; @@ -1761,21 +1623,37 @@ static bool type_hidden(Ed* ed, const TinyBlocks_TypeBlock* t) { static void cats_rebuild(Ed* ed) { ed->cat_n = 0; - for (int i = 0; i < CAT_BUILTIN_N; i++) { + /* 1) Categoria declarada por cada library, na ordem de registro */ + for (uint32_t i = 0; i < ed->rt->library_count && ed->cat_n < MAX_CATS; i++) { + TinyBlocks_LibraryBlock* lib = ed->rt->libraries[i]; + if (!lib->category || !lib->category->name) continue; 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; + snprintf(c->name, sizeof(c->name), "%s", lib->category->name); + c->col = (Col){lib->category->color[0], lib->category->color[1], + lib->category->color[2], lib->category->color[3]}; + c->dark = (Col){lib->category->dark[0], lib->category->dark[1], + lib->category->dark[2], lib->category->dark[3]}; + c->lib = lib; } - /* Uma categoria por prefixo de library (Python., MCP., Viz.…) */ + /* 2) "Meus Blocos" pertence ao editor */ + ed->myblocks_cat = -1; + if (ed->cat_n < MAX_CATS) { + Cat* c = &ed->cats[ed->cat_n++]; + memset(c, 0, sizeof(*c)); + snprintf(c->name, sizeof(c->name), "Meus Blocos"); + c->col = COL_MYBLOCKS_COL; c->dark = COL_MYBLOCKS_DARK; + ed->myblocks_cat = ed->cat_n - 1; + } + /* 3) Uma categoria por prefixo para libraries/tipos sem categoria */ 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; + if (type_hidden(ed, t) || cat_of_type(ed, t) >= 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->name[sizeof(c->name) - 1] = 0; c->col = COL_EXT; c->dark = COL_EXT_DARK; } } @@ -1798,21 +1676,23 @@ static void palette_rebuild(Ed* ed) { ed->fly_n = 0; float y = 8; TinyBlocks_TypeBlock* var_get = tb_type_block_find(ed->rt, "Variables.Get"); + int var_cat = cat_of(ed, "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) { + if (c == ed->myblocks_cat && 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; + if (type_hidden(ed, t) || cat_of_type(ed, t) != 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); + if (var_get && c == var_cat) + for (int v = 0; v < tb_variables_count(); v++) + fly_add_block(ed, c, var_get, tb_variables_name(v), &y); y += 10; } ed->fly_total_h = y; @@ -1835,9 +1715,9 @@ static float fly_max_scroll(Ed* ed) { 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; @@ -1909,7 +1789,7 @@ static void collect_labels(Tab* T, const char* type_name, char names[][32], int* 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]); + if (b->in_text[0][0]) snprintf(lbl, sizeof(lbl), "%.31s", 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; @@ -2014,9 +1894,9 @@ static void save_composite_from_tab(Ed* ed) { ed->hot_status_ok = true; } -/* ══════════════════════════════════════════════════════════════════════════ +/* === * Diálogo modal "Criar um Bloco" (estilo Scratch) - * ══════════════════════════════════════════════════════════════════════════ */ + * === */ #define DLG_W 580 #define DLG_H 380 #define DLG_HEAD_H 50 @@ -2046,7 +1926,7 @@ static void dlg_geom(Ed* ed, float* bx, float* by, float* bw, float* bh) { *by = dy + DLG_HEAD_H + 46.f; } -/* Dimensões de um card "Adicionar…" */ +/* Dimensões de um card "Adicionar=" */ static void dlg_card_rect(float* w, float* h) { *w = (DLG_W - 56.f - 32.f) / 3.f; *h = 88.f; @@ -2198,7 +2078,7 @@ static void dlg_render(Ed* ed, TinyBlocks_RenderableBlock* rb) { const char* title = ed->comp_dialog_def >= 0 ? "Editar Bloco" : "Criar um Bloco"; rb_text_c(rb, dx + (DLG_W - tw(title, 18)) * 0.5f, dy + DLG_HEAD_H * 0.5f, title, COL_WHITE, 18); rb_fill_circle(rb, dx + DLG_W - 26, dy + DLG_HEAD_H * 0.5f, 12, COLA(255, 255, 255, 60)); - rb_text_c(rb, dx + DLG_W - 30, dy + DLG_HEAD_H * 0.5f, "×", COL_WHITE, 18); + rb_text_c(rb, dx + DLG_W - 30, dy + DLG_HEAD_H * 0.5f, "=", COL_WHITE, 18); /* Protótipo do bloco */ float bx, by, bw, bh; @@ -2247,11 +2127,11 @@ static void dlg_render(Ed* ed, TinyBlocks_RenderableBlock* rb) { } } - /* Controles ‹ 🗑 › da parte selecionada */ + /* Controles - apagar - da parte selecionada */ if (ed->comp_dialog_sel >= 0) { float ctr = bx + bw * 0.5f, cty = by - 26; - rb_text_c(rb, ctr - 44, cty, "‹", COL_TEXT, 22); - rb_text_c(rb, ctr + 40, cty, "›", COL_TEXT, 22); + rb_text_c(rb, ctr - 44, cty, "=", COL_TEXT, 22); + rb_text_c(rb, ctr + 40, cty, "=", COL_TEXT, 22); rb_fill_rect(rb, ctr - 7, cty - 8, 14, 3, COL_TEXT); rb_fill_rect(rb, ctr - 4, cty - 12, 8, 4, COL_TEXT); rb_fill_rect(rb, ctr - 6, cty - 4, 12, 12, COL_TEXT); @@ -2274,7 +2154,7 @@ static void dlg_render(Ed* ed, TinyBlocks_RenderableBlock* rb) { float iy = cy0 + 16.f; if (i == 0) { rb_fill_rrect(rb, cx + cw * 0.5f - 22, iy, 44, 22, 11, accent); - rb_text_c(rb, cx + cw * 0.5f - 14, iy + 11, "· · ·", COL_WHITE, FS); + rb_text_c(rb, cx + cw * 0.5f - 14, iy + 11, "= = =", COL_WHITE, FS); } else if (i == 1) { draw_hex(rb, cx + cw * 0.5f - 20, iy, 40, 22, accent); } else { @@ -2363,9 +2243,9 @@ static void dlg_text(Ed* ed, const char* typed) { append_text(t, cap, typed); } -/* ══════════════════════════════════════════════════════════════════════════ +/* === * 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; @@ -2392,10 +2272,10 @@ static bool hotlib_load(Ed* ed, const char* 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); + "'%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); + "'%s' não exporta tinyblocks_get_library = não é uma library válida", base); ed->hot_status_ok = false; dlclose(dl); return false; @@ -2432,7 +2312,7 @@ static void hotlib_reload(Ed* ed, int idx) { 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", + snprintf(ed->hot_status, sizeof(ed->hot_status), "Hot reload falhou: %.230s", dl ? h->path : dlerror()); ed->hot_status_ok = false; if (dl) dlclose(dl); @@ -2442,7 +2322,7 @@ static void hotlib_reload(Ed* ed, int idx) { h->dl = dl; h->lib = lib; retype_all(ed); - snprintf(ed->hot_status, sizeof(ed->hot_status), "Recarregado: %s", h->path); + snprintf(ed->hot_status, sizeof(ed->hot_status), "Recarregado: %.240s", h->path); ed->hot_status_ok = true; } @@ -2455,16 +2335,16 @@ static void hotlib_check(Ed* ed) { } } -/* ══════════════════════════════════════════════════════════════════════════ +/* === * 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); + 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; @@ -2496,7 +2376,7 @@ static void render_tab_bar(Ed* ed, TinyBlocks_RenderableBlock* rb) { 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); + 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) @@ -2602,7 +2482,7 @@ static void render_workspace(Ed* ed, TinyBlocks_RenderableBlock* rb) { clip_clear(ed, rb); } -/* ── Barra do bloco composto (canto superior direito do workspace) ───── */ +/* == Barra do bloco composto (canto superior direito do workspace) === */ #define CP_W 440 #define CP_H 44 static void comp_panel_pos(Ed* ed, float* px, float* py) { @@ -2693,13 +2573,16 @@ static void render_stage(Ed* ed, TinyBlocks_RenderableBlock* rb) { /* 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); + for (int v = 0; v < tb_variables_count() && y < by + bh*0.5f; v++) { + const char* vname = tb_variables_name(v); + const TinyBlocks_Value* vv = tb_variables_value(v); + char val[64]; + if (vv) value_to_str(vv, val, sizeof(val)); else val[0] = 0; + float nw = tw(vname, 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_text_c(rb, bx+18, y+13, vname, 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; @@ -2767,9 +2650,9 @@ static void render_ctx_menu(Ed* ed, TinyBlocks_RenderableBlock* rb) { } } -/* ══════════════════════════════════════════════════════════════════════════ +/* === * Arrastar e encaixar - * ══════════════════════════════════════════════════════════════════════════ */ + * === */ static void start_drag(Ed* ed) { Tab* T = &CT; int bi = ed->press_bi; @@ -2858,9 +2741,9 @@ static void cleanup_ws(Ed* ed) { } } -/* ══════════════════════════════════════════════════════════════════════════ +/* === * Edição de texto - * ══════════════════════════════════════════════════════════════════════════ */ + * === */ static void utf8_pop(char* s) { size_t n = strlen(s); while (n > 0) { @@ -2882,9 +2765,9 @@ static char* edit_target(Ed* ed, size_t* cap) { 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; @@ -2958,7 +2841,7 @@ static void stage_detach(Ed* ed) { 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"); + 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)); @@ -3182,9 +3065,9 @@ static void on_text(Ed* ed, const char* typed) { } } -/* ══════════════════════════════════════════════════════════════════════════ - * editor_eval — lê um snapshot de Graphics.Input por frame e atualiza o estado - * ══════════════════════════════════════════════════════════════════════════ */ +/* === + * 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; @@ -3204,7 +3087,7 @@ static void editor_eval(TinyBlocks_Block* self, TinyBlocks* rt) { ed->mouse_x = mx; ed->mouse_y = my; layout_tab(&CT); - /* ── Hover ──────────────────────────────────────────────────────── */ + /* == 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); @@ -3214,7 +3097,7 @@ static void editor_eval(TinyBlocks_Block* self, TinyBlocks* rt) { 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 ──────────────────────────────────────────────────── */ + /* == 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) { @@ -3229,7 +3112,7 @@ static void editor_eval(TinyBlocks_Block* self, TinyBlocks* rt) { CT.ws_sy = ed->pan_sy - (my - ed->pan_my); } - /* ── Scroll ─────────────────────────────────────────────────────── */ + /* == 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) { @@ -3243,7 +3126,7 @@ static void editor_eval(TinyBlocks_Block* self, TinyBlocks* rt) { } } - /* ── Drop de arquivo ────────────────────────────────────────────── */ + /* == Drop de arquivo === */ const char* dropped = ev_text(evb, GFX_IN_DROP_FILE); if (dropped[0]) { size_t len = strlen(dropped); @@ -3267,9 +3150,9 @@ static void editor_eval(TinyBlocks_Block* self, TinyBlocks* rt) { } } -/* ══════════════════════════════════════════════════════════════════════════ - * editor_on_draw — compõe o frame inteiro em um RenderableBlock - * ══════════════════════════════════════════════════════════════════════════ */ +/* === + * 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; @@ -3300,9 +3183,9 @@ static bool editor_on_draw(TinyBlocks_Block* self, TinyBlocks* rt, 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; @@ -3377,19 +3260,18 @@ static void editor_instance_deinit(TinyBlocks_Block* self, TinyBlocks* 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 — + * 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, @@ -3399,58 +3281,17 @@ static void reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name, } 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}}; + static const TinyBlocks_SlotDesc any_out[] = {{"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) */ + /* Palco (Editor.Stage); os blocos Stage.* ficam na library Caneta */ if (!tb_stage_register(rt, lib)) return false; - /* Editor.Scene — produz um RenderableBlock via on_draw; não abre janela */ + /* 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); diff --git a/libraries/tinyblocks-editor/src/tb_stage.c b/libraries/tinyblocks-editor/src/tb_stage.c index cd9117b..5877c13 100644 --- a/libraries/tinyblocks-editor/src/tb_stage.c +++ b/libraries/tinyblocks-editor/src/tb_stage.c @@ -1,5 +1,5 @@ /* - * TinyBlocks — tb_stage.c + * 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 @@ -42,6 +42,7 @@ typedef struct { } Stage; static TinyBlocks_Block* s_current = NULL; +static TinyBlocks* s_rt = NULL; /* para mensagens de erro */ static Stage* stage_of(TinyBlocks_Block* b) { return b ? *(Stage**)b->userdata : NULL; } @@ -52,9 +53,9 @@ void tb_stage_set_view(TinyBlocks_Block* stage, float w, float h) { 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)); @@ -76,7 +77,7 @@ static void stage_instance_deinit(TinyBlocks_Block* self, TinyBlocks* rt) { if (s_current == self) s_current = NULL; } -/* input 0 (opcional): Graphics.Input da janela que mostra o palco — dá o tamanho da vista */ +/* 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); @@ -130,24 +131,16 @@ static bool stage_on_draw(TinyBlocks_Block* self, TinyBlocks* rt, TinyBlocks_Ren 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; -} - +/* === + * API de desenho - usada pela library tinyblocks-pen (categoria "Caneta") + * === */ 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); + if (!s->full_warned) tinyblocks_set_error(rt, "palco cheio (%d desenhos) = use \"apague tudo\"", STAGE_MAX_CMDS); s->full_warned = true; return NULL; } @@ -165,95 +158,58 @@ static StageCmd* push(TinyBlocks* rt, StageCmdKind kind) { return c; } -static void eval_clear(TinyBlocks_Block* self, TinyBlocks* rt) { - (void)rt; +void tb_stage_clear(void) { 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) { +void tb_stage_set_background(float r, float g, float b) { 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; + if (s) { s->bg[0] = chan(r); s->bg[1] = chan(g); s->bg[2] = chan(b); } } -static void eval_pen_color(TinyBlocks_Block* self, TinyBlocks* rt) { +void tb_stage_set_pen(float r, float g, float b) { 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; + if (s) { s->pen[0] = chan(r); s->pen[1] = chan(g); s->pen[2] = chan(b); } } -static void eval_pen_size(TinyBlocks_Block* self, TinyBlocks* rt) { +void tb_stage_set_pen_size(float size) { 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; + if (s) s->pen_size = size < 1.f ? 1.f : size; } -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; +void tb_stage_line(float x1, float y1, float x2, float y2) { + StageCmd* c = push(s_rt, SC_LINE); + if (c) { c->a = x1; c->b = y1; c->c = x2; c->d = y2; } } -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; +void tb_stage_rect(float x, float y, float w, float h) { + StageCmd* c = push(s_rt, SC_RECT); + if (c) { c->a = x; c->b = y; c->c = w; c->d = h; } } -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; +void tb_stage_circle(float x, float y, float radius) { + StageCmd* c = push(s_rt, SC_CIRCLE); + if (c) { c->a = x; c->b = y; c->c = radius; } } -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; +void tb_stage_text(const char* text, float x, float y) { + StageCmd* c = push(s_rt, SC_TEXT); + if (c) { + snprintf(c->text, sizeof(c->text), "%s", text ? text : ""); + c->a = x; c->b = y; + } } +/* === + * Registro do widget Editor.Stage + * === */ bool tb_stage_register(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + s_rt = rt; 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); + return tb_library_add(lib, &t->base); } diff --git a/libraries/tinyblocks-editor/src/tb_stage.h b/libraries/tinyblocks-editor/src/tb_stage.h index c9785a8..5886392 100644 --- a/libraries/tinyblocks-editor/src/tb_stage.h +++ b/libraries/tinyblocks-editor/src/tb_stage.h @@ -1,19 +1,29 @@ /* - * TinyBlocks — tb_stage.h - * Palco do editor (Editor.Stage) e blocos de desenho Stage.*. + * TinyBlocks - tb_stage.h + * Palco do editor (Editor.Stage) e API de desenho usada pela library Caneta. */ #ifndef TINYBLOCKS_EDITOR_STAGE_H #define TINYBLOCKS_EDITOR_STAGE_H #include -/* Registra Editor.Stage e os blocos Stage.* na library do editor */ +/* Registra apenas o widget Editor.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) */ +/* 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) */ +/* Palco onde o desenho acontece (o último Editor.Stage criado) */ TinyBlocks_Block* tb_stage_current(void); +/* == API de desenho (usada pela library tinyblocks-pen) === */ +void tb_stage_clear(void); +void tb_stage_set_background(float r, float g, float b); /* canais 0..255 */ +void tb_stage_set_pen(float r, float g, float b); /* canais 0..255 */ +void tb_stage_set_pen_size(float size); +void tb_stage_line(float x1, float y1, float x2, float y2); +void tb_stage_rect(float x, float y, float w, float h); +void tb_stage_circle(float x, float y, float radius); +void tb_stage_text(const char* text, float x, float y); + #endif /* TINYBLOCKS_EDITOR_STAGE_H */ diff --git a/libraries/tinyblocks-events/include/tb_events.h b/libraries/tinyblocks-events/include/tb_events.h new file mode 100644 index 0000000..17e1d18 --- /dev/null +++ b/libraries/tinyblocks-events/include/tb_events.h @@ -0,0 +1,12 @@ +/* + * TinyBlocks - tb_events.h + * Library da categoria "Eventos" (blocos que iniciam scripts). + */ +#ifndef TINYBLOCKS_EVENTS_H +#define TINYBLOCKS_EVENTS_H + +#include + +TB_API const TinyBlocks_LibraryDescriptor* tb_events_get_library(void); + +#endif /* TINYBLOCKS_EVENTS_H */ diff --git a/libraries/tinyblocks-events/src/tb_events.c b/libraries/tinyblocks-events/src/tb_events.c new file mode 100644 index 0000000..53453ef --- /dev/null +++ b/libraries/tinyblocks-events/src/tb_events.c @@ -0,0 +1,40 @@ +/* + * TinyBlocks - tb_events.c + * Categoria "Eventos": blocos que iniciam scripts. A execução é conduzida + * pelo editor (run_chain); aqui só registramos os tipos e a categoria. + */ +#include +#include "tb_events.h" + +static void eval_noop(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + self->dirty = false; +} + +static bool events_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + static const TinyBlocks_Category cat = { + "Eventos", + {255/255.f, 191/255.f, 0/255.f, 1.f}, + {204/255.f, 153/255.f, 0/255.f, 1.f}, + }; + tb_library_set_category(lib, &cat); + + TinyBlocks_TypeBlock* t = tb_type_block_create(rt, "Events.WhenRun", + NULL, 0, NULL, 0, eval_noop); + if (!t) return false; + return tb_library_add(lib, &t->base); +} + +static void events_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + (void)rt; (void)lib; +} + +TINYBLOCKS_DEFINE_LIBRARY(events, + "tinyblocks-events", + "1.0.0", + events_init, + events_deinit) + +const TinyBlocks_LibraryDescriptor* tb_events_get_library(void) { + return &_tb_lib_desc_events; +} diff --git a/libraries/tinyblocks-operators/include/tb_operators.h b/libraries/tinyblocks-operators/include/tb_operators.h new file mode 100644 index 0000000..c5aa884 --- /dev/null +++ b/libraries/tinyblocks-operators/include/tb_operators.h @@ -0,0 +1,13 @@ +/* + * TinyBlocks - tb_operators.h + * Library da categoria "Operadores": lógica, comparação, matemática, texto + * e literais. + */ +#ifndef TINYBLOCKS_OPERATORS_H +#define TINYBLOCKS_OPERATORS_H + +#include + +TB_API const TinyBlocks_LibraryDescriptor* tb_operators_get_library(void); + +#endif /* TINYBLOCKS_OPERATORS_H */ diff --git a/libraries/tinyblocks-operators/src/tb_operators.c b/libraries/tinyblocks-operators/src/tb_operators.c new file mode 100644 index 0000000..b58451c --- /dev/null +++ b/libraries/tinyblocks-operators/src/tb_operators.c @@ -0,0 +1,237 @@ +/* + * TinyBlocks - tb_operators.c + * Categoria "Operadores": comparações, lógica booleana, número aleatório, + * aritmética, texto e literais. + */ +#include +#include +#include +#include +#include +#include +#include "tb_operators.h" + +/* == Conversões === */ +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 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 ((*t | 32) != *f) return true; + return *t || *f; + } + default: return false; + } +} + +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; + default: buf[0] = 0; break; + } +} + +static int str_icmp(const char* a, const char* b) { + for (;; a++, b++) { + int ca = (*a | 32), cb = (*b | 32); + if (ca != cb || !ca) return (ca > cb) - (ca < cb); + } +} + +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); +} + +/* == Lógica e comparação === */ +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; +} + +/* == Aritmética (inteiros) === */ +static int64_t ai(TinyBlocks_Block* s, TinyBlocks* rt, uint32_t i) { + TinyBlocks_Value v = tb_block_get_input(s, rt, i); + return v.kind == TB_VALUE_INTEGER ? v.as.integer : 0; +} +static void eval_add(TinyBlocks_Block* s, TinyBlocks* rt) +{ tb_block_set_output(s, 0, tb_value_integer(ai(s,rt,0) + ai(s,rt,1))); } +static void eval_sub(TinyBlocks_Block* s, TinyBlocks* rt) +{ tb_block_set_output(s, 0, tb_value_integer(ai(s,rt,0) - ai(s,rt,1))); } +static void eval_mul(TinyBlocks_Block* s, TinyBlocks* rt) +{ tb_block_set_output(s, 0, tb_value_integer(ai(s,rt,0) * ai(s,rt,1))); } +static void eval_div(TinyBlocks_Block* s, TinyBlocks* rt) +{ int64_t b = ai(s,rt,1); tb_block_set_output(s, 0, tb_value_integer(b ? ai(s,rt,0)/b : 0)); } +static void eval_mod(TinyBlocks_Block* s, TinyBlocks* rt) +{ int64_t b = ai(s,rt,1); tb_block_set_output(s, 0, tb_value_integer(b ? ai(s,rt,0)%b : 0)); } +static void eval_abs(TinyBlocks_Block* s, TinyBlocks* rt) +{ int64_t a = ai(s,rt,0); tb_block_set_output(s, 0, tb_value_integer(a < 0 ? -a : a)); } +static void eval_max(TinyBlocks_Block* s, TinyBlocks* rt) +{ int64_t a = ai(s,rt,0), b = ai(s,rt,1); tb_block_set_output(s, 0, tb_value_integer(a > b ? a : b)); } +static void eval_min(TinyBlocks_Block* s, TinyBlocks* rt) +{ int64_t a = ai(s,rt,0), b = ai(s,rt,1); tb_block_set_output(s, 0, tb_value_integer(a < b ? a : b)); } + +/* == Texto === */ +static void eval_concat(TinyBlocks_Block* s, TinyBlocks* rt) { + TinyBlocks_Value a = tb_block_get_input(s, rt, 0); + TinyBlocks_Value b = tb_block_get_input(s, rt, 1); + const char* sa = a.kind == TB_VALUE_TEXT ? a.as.text : ""; + const char* sb = b.kind == TB_VALUE_TEXT ? b.as.text : ""; + if (!sa) sa = ""; + if (!sb) sb = ""; + size_t n = strlen(sa) + strlen(sb) + 1; + char* buf = (char*)malloc(n); + if (!buf) return; + memcpy(buf, sa, strlen(sa)); + memcpy(buf + strlen(sa), sb, strlen(sb) + 1); + TinyBlocks_Value v; v.kind = TB_VALUE_TEXT; v.as.text = buf; + tb_block_set_output(s, 0, v); /* set_output toma ownership */ +} +static void eval_len(TinyBlocks_Block* s, TinyBlocks* rt) { + TinyBlocks_Value a = tb_block_get_input(s, rt, 0); + int64_t n = (a.kind == TB_VALUE_TEXT && a.as.text) ? (int64_t)strlen(a.as.text) : 0; + tb_block_set_output(s, 0, tb_value_integer(n)); +} + +/* == Literais === */ +static void eval_lit_int(TinyBlocks_Block* s, TinyBlocks* rt) +{ tb_block_set_output(s, 0, tb_value_clone(tb_block_get_input(s, rt, 0))); } +static void eval_lit_real(TinyBlocks_Block* s, TinyBlocks* rt) +{ tb_block_set_output(s, 0, tb_value_clone(tb_block_get_input(s, rt, 0))); } +static void eval_lit_text(TinyBlocks_Block* s, TinyBlocks* rt) { + TinyBlocks_Value v = tb_block_get_input(s, rt, 0); + const char* t = (v.kind == TB_VALUE_TEXT && v.as.text) ? v.as.text : ""; + tb_block_set_output(s, 0, tb_value_text(t)); +} + +/* == Registro === */ +static bool 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); + return t && tb_library_add(lib, &t->base); +} + +static bool operators_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + srand((unsigned)time(NULL)); + static const TinyBlocks_Category cat = { + "Operadores", + { 89/255.f, 192/255.f, 89/255.f, 1.f}, + { 56/255.f, 148/255.f, 56/255.f, 1.f}, + }; + tb_library_set_category(lib, &cat); + + 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 bool1[] = {{"a", 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}}; + + static const TinyBlocks_SlotDesc two_int[] = {{"a", TB_VALUE_INTEGER}, {"b", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc one_int[] = {{"n", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc int_out[] = {{"result", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc two_text[] = {{"a", TB_VALUE_TEXT}, {"b", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc text_out[] = {{"result", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc text_in[] = {{"text", TB_VALUE_TEXT}}; + + 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}}; + + return 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", bool1, 1, bool_out, 1, eval_op_not) + && reg(rt, lib, "Operators.Random", rnd_in, 2, any_out, 1, eval_op_random) + && reg(rt, lib, "Math.Add", two_int, 2, int_out, 1, eval_add) + && reg(rt, lib, "Math.Sub", two_int, 2, int_out, 1, eval_sub) + && reg(rt, lib, "Math.Mul", two_int, 2, int_out, 1, eval_mul) + && reg(rt, lib, "Math.Div", two_int, 2, int_out, 1, eval_div) + && reg(rt, lib, "Math.Mod", two_int, 2, int_out, 1, eval_mod) + && reg(rt, lib, "Math.Abs", one_int, 1, int_out, 1, eval_abs) + && reg(rt, lib, "Math.Max", two_int, 2, int_out, 1, eval_max) + && reg(rt, lib, "Math.Min", two_int, 2, int_out, 1, eval_min) + && reg(rt, lib, "Text.Concat", two_text, 2, text_out, 1, eval_concat) + && reg(rt, lib, "Text.Length", text_in, 1, int_out, 1, eval_len) + && reg(rt, lib, "Literal.Integer", lit_int_in, 1, lit_int_out, 1, eval_lit_int) + && reg(rt, lib, "Literal.Real", lit_real_in, 1, lit_real_out, 1, eval_lit_real) + && reg(rt, lib, "Literal.Text", lit_txt_in, 1, lit_txt_out, 1, eval_lit_text); +} + +static void operators_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + (void)rt; (void)lib; +} + +TINYBLOCKS_DEFINE_LIBRARY(operators, + "tinyblocks-operators", + "1.0.0", + operators_init, + operators_deinit) + +const TinyBlocks_LibraryDescriptor* tb_operators_get_library(void) { + return &_tb_lib_desc_operators; +} diff --git a/libraries/tinyblocks-pen/include/tb_pen.h b/libraries/tinyblocks-pen/include/tb_pen.h new file mode 100644 index 0000000..636c7ac --- /dev/null +++ b/libraries/tinyblocks-pen/include/tb_pen.h @@ -0,0 +1,12 @@ +/* + * TinyBlocks - tb_pen.h + * Library da categoria "Caneta": desenha no palco (Editor.Stage). + */ +#ifndef TINYBLOCKS_PEN_H +#define TINYBLOCKS_PEN_H + +#include + +TB_API const TinyBlocks_LibraryDescriptor* tb_pen_get_library(void); + +#endif /* TINYBLOCKS_PEN_H */ diff --git a/libraries/tinyblocks-pen/src/tb_pen.c b/libraries/tinyblocks-pen/src/tb_pen.c new file mode 100644 index 0000000..28f436d --- /dev/null +++ b/libraries/tinyblocks-pen/src/tb_pen.c @@ -0,0 +1,104 @@ +/* + * TinyBlocks - tb_pen.c + * Categoria "Caneta": apague / mude fundo / cor / espessura / desenhe linhas, + * retângulos, círculos e texto. Delega o desenho à API do palco do editor. + */ +#include +#include +#include +#include +#include "tb_stage.h" +#include "tb_pen.h" + +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 void eval_clear(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; tb_stage_clear(); self->dirty = false; +} +static void eval_background(TinyBlocks_Block* self, TinyBlocks* rt) { + tb_stage_set_background(num(self, rt, 0), num(self, rt, 1), num(self, rt, 2)); + self->dirty = false; +} +static void eval_pen_color(TinyBlocks_Block* self, TinyBlocks* rt) { + tb_stage_set_pen(num(self, rt, 0), num(self, rt, 1), num(self, rt, 2)); + self->dirty = false; +} +static void eval_pen_size(TinyBlocks_Block* self, TinyBlocks* rt) { + tb_stage_set_pen_size(num(self, rt, 0)); + self->dirty = false; +} +static void eval_line(TinyBlocks_Block* self, TinyBlocks* rt) { + tb_stage_line(num(self, rt, 0), num(self, rt, 1), num(self, rt, 2), num(self, rt, 3)); + self->dirty = false; +} +static void eval_rect(TinyBlocks_Block* self, TinyBlocks* rt) { + tb_stage_rect(num(self, rt, 0), num(self, rt, 1), num(self, rt, 2), num(self, rt, 3)); + self->dirty = false; +} +static void eval_circle(TinyBlocks_Block* self, TinyBlocks* rt) { + tb_stage_circle(num(self, rt, 0), num(self, rt, 1), 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); + tb_stage_text(buf, num(self, rt, 1), num(self, rt, 2)); + self->dirty = false; +} + +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); + return t && tb_library_add(lib, &t->base); +} + +static bool pen_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + static const TinyBlocks_Category cat = { + "Caneta", + { 15/255.f, 189/255.f, 140/255.f, 1.f}, + { 11/255.f, 142/255.f, 105/255.f, 1.f}, + }; + tb_library_set_category(lib, &cat); + + 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); +} + +static void pen_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + (void)rt; (void)lib; +} + +TINYBLOCKS_DEFINE_LIBRARY(pen, + "tinyblocks-pen", + "1.0.0", + pen_init, + pen_deinit) + +const TinyBlocks_LibraryDescriptor* tb_pen_get_library(void) { + return &_tb_lib_desc_pen; +} diff --git a/libraries/tinyblocks-variables/include/tb_variables.h b/libraries/tinyblocks-variables/include/tb_variables.h new file mode 100644 index 0000000..c8b117c --- /dev/null +++ b/libraries/tinyblocks-variables/include/tb_variables.h @@ -0,0 +1,21 @@ +/* + * TinyBlocks - tb_variables.h + * Library da categoria "Variáveis". Ela é dona do armazenamento (nome=valor); + * UIs, como o editor, consultam a lista para desenhar monitores. + */ +#ifndef TINYBLOCKS_VARIABLES_H +#define TINYBLOCKS_VARIABLES_H + +#include + +TB_API const TinyBlocks_LibraryDescriptor* tb_variables_get_library(void); + +/* Enumeração do armazenamento (para monitores etc.) */ +TB_API int tb_variables_count(void); +TB_API const char* tb_variables_name(int i); +TB_API const TinyBlocks_Value* tb_variables_value(int i); /* emprestado */ + +/* Zera variáveis que guardam blocos (chamado antes de uma nova execução) */ +TB_API void tb_variables_reset_blocks(void); + +#endif /* TINYBLOCKS_VARIABLES_H */ diff --git a/libraries/tinyblocks-variables/src/tb_variables.c b/libraries/tinyblocks-variables/src/tb_variables.c new file mode 100644 index 0000000..db175cd --- /dev/null +++ b/libraries/tinyblocks-variables/src/tb_variables.c @@ -0,0 +1,139 @@ +/* + * TinyBlocks - tb_variables.c + * Categoria "Variáveis": mude / adicione / valor de . + * A library é dona do armazenamento de variáveis e o expõe para monitores. + */ +#include +#include +#include +#include +#include +#include "tb_variables.h" + +#define MAX_VARS 64 + +typedef struct { char name[32]; TinyBlocks_Value val; } Var; + +static Var s_vars[MAX_VARS]; +static int s_n = 0; + +static int var_find(const char* n, bool create) { + for (int i = 0; i < s_n; i++) + if (strcmp(s_vars[i].name, n) == 0) return i; + if (!create || s_n >= MAX_VARS) return -1; + int i = s_n++; + strncpy(s_vars[i].name, n, 31); s_vars[i].name[31] = 0; + s_vars[i].val = tb_value_integer(0); + return i; +} + +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 reduzido */ + switch (v.kind) { + case TB_VALUE_INTEGER: snprintf(out, cap, "%lld", (long long)v.as.integer); break; + case TB_VALUE_REAL: snprintf(out, cap, "%g", v.as.real); break; + case TB_VALUE_TEXT: snprintf(out, cap, "%s", v.as.text ? v.as.text : ""); break; + default: out[0] = 0; break; + } +} + +static void eval_var_get(TinyBlocks_Block* self, TinyBlocks* rt) { + char name[64]; input_name(self, rt, 0, name, sizeof(name)); + int i = var_find(name, false); + tb_block_set_output(self, 0, i >= 0 ? tb_value_clone(s_vars[i].val) + : 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 = var_find(name, true); + if (i >= 0) { + TinyBlocks_Value v = tb_block_get_input(self, rt, 1); + tb_value_free(&s_vars[i].val); + s_vars[i].val = 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 = var_find(name, true); + if (i >= 0) { + TinyBlocks_Value by = tb_block_get_input(self, rt, 1); + TinyBlocks_Value* cur = &s_vars[i].val; + double a = 0, d = 0; + if (cur->kind == TB_VALUE_INTEGER) a = (double)cur->as.integer; + else if (cur->kind == TB_VALUE_REAL) a = cur->as.real; + else if (cur->kind == TB_VALUE_TEXT && cur->as.text) a = strtod(cur->as.text, NULL); + if (by.kind == TB_VALUE_INTEGER) d = (double)by.as.integer; + else if (by.kind == TB_VALUE_REAL) d = by.as.real; + else if (by.kind == TB_VALUE_TEXT && by.as.text) d = strtod(by.as.text, NULL); + TinyBlocks_Value nv = (a == floor(a) && d == floor(d)) + ? tb_value_integer((long long)llround(a + d)) + : tb_value_real(a + d); + tb_value_free(cur); + *cur = nv; + } + self->dirty = false; +} + +/* == API de enumeração === */ +int tb_variables_count(void) { return s_n; } + +const char* tb_variables_name(int i) { + return (i >= 0 && i < s_n) ? s_vars[i].name : ""; +} + +const TinyBlocks_Value* tb_variables_value(int i) { + return (i >= 0 && i < s_n) ? &s_vars[i].val : NULL; +} + +void tb_variables_reset_blocks(void) { + for (int v = 0; v < s_n; v++) + if (s_vars[v].val.kind == TB_VALUE_BLOCK) { + tb_value_free(&s_vars[v].val); + s_vars[v].val = tb_value_integer(0); + } +} + +/* == Registro === */ +static bool variables_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + static const TinyBlocks_Category cat = { + "Variáveis", + {255/255.f, 140/255.f, 26/255.f, 1.f}, + {219/255.f, 110/255.f, 0/255.f, 1.f}, + }; + tb_library_set_category(lib, &cat); + + 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}}; + static const TinyBlocks_SlotDesc any_out[] = {{"valor", TB_VALUE_NONE}}; + + TinyBlocks_TypeBlock* t; + t = tb_type_block_create(rt, "Variables.Set", var_set, 2, NULL, 0, eval_var_set); + if (!t || !tb_library_add(lib, &t->base)) return false; + t = tb_type_block_create(rt, "Variables.Change", var_set, 2, NULL, 0, eval_var_change); + if (!t || !tb_library_add(lib, &t->base)) return false; + t = tb_type_block_create(rt, "Variables.Get", var_in, 1, any_out, 1, eval_var_get); + if (!t || !tb_library_add(lib, &t->base)) return false; + return true; +} + +static void variables_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + (void)rt; (void)lib; + for (int i = 0; i < s_n; i++) tb_value_free(&s_vars[i].val); + s_n = 0; +} + +TINYBLOCKS_DEFINE_LIBRARY(variables, + "tinyblocks-variables", + "1.0.0", + variables_init, + variables_deinit) + +const TinyBlocks_LibraryDescriptor* tb_variables_get_library(void) { + return &_tb_lib_desc_variables; +} diff --git a/src/tb_library_block.c b/src/tb_library_block.c index 24115f9..2ea7107 100644 --- a/src/tb_library_block.c +++ b/src/tb_library_block.c @@ -7,7 +7,7 @@ # include #endif -/* ── Vtable de LibraryBlock ──────────────────────────────────────────────── */ +/* == Vtable de LibraryBlock === */ static void lib_eval(TinyBlocks_Block* self, TinyBlocks* rt) { /* Libraries não avaliam diretamente; servem como namespaces */ @@ -47,7 +47,7 @@ static const TinyBlocks_BlockVTable s_lib_vtable = { .clone = lib_clone, }; -/* ── Criação ─────────────────────────────────────────────────────────────── */ +/* == Criação === */ TinyBlocks_LibraryBlock* tb_library_block_create(TinyBlocks* rt, const char* name) { TinyBlocks_LibraryBlock* lib = (TinyBlocks_LibraryBlock*)tb_block_alloc_base( @@ -57,6 +57,7 @@ TinyBlocks_LibraryBlock* tb_library_block_create(TinyBlocks* rt, const char* nam lib->base.name = tb_strdup(rt, name); lib->block_capacity = 16; + lib->category = NULL; lib->blocks = tb_alloc(rt, lib->block_capacity * sizeof(TinyBlocks_Block*)); if (!lib->blocks) { tb_block_destroy(&lib->base, rt); @@ -72,13 +73,13 @@ void tb_library_block_destroy(TinyBlocks_LibraryBlock* lib, TinyBlocks* rt) tb_block_destroy(&lib->base, rt); } -/* ── Gerenciamento de blocos contidos ────────────────────────────────────── */ +/* == 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. + /* 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). */ @@ -93,6 +94,13 @@ bool tb_library_add(TinyBlocks_LibraryBlock* lib, TinyBlocks_Block* block) return true; } +/* == Categoria === */ +void tb_library_set_category(TinyBlocks_LibraryBlock* lib, + const TinyBlocks_Category* category) +{ + if (lib) lib->category = category; +} + bool tb_library_remove_at(TinyBlocks_LibraryBlock* lib, uint32_t index) { if (!lib || index >= lib->block_count) return false; @@ -116,7 +124,7 @@ TinyBlocks_Block* tb_library_find(TinyBlocks_LibraryBlock* lib, const char* name return NULL; } -/* ── Carregamento dinâmico ───────────────────────────────────────────────── */ +/* == Carregamento dinâmico === */ TinyBlocks_LibraryBlock* tb_library_load(TinyBlocks* rt, const char* path) { #ifdef __linux__ diff --git a/tests/editor_harness.c b/tests/editor_harness.c index 8821d32..e200a51 100644 --- a/tests/editor_harness.c +++ b/tests/editor_harness.c @@ -8,6 +8,12 @@ #include #include #include +#include +#include +#include +#include +#include +#include static TinyBlocks* rt; static TinyBlocks_Block *ev, *scene; @@ -15,19 +21,6 @@ static TinyBlocks_DrawCmd cmds[TB_DRAW_CMD_CAP]; static uint32_t ncmd; static int fails = 0; -static void eval_print(TinyBlocks_Block* self, TinyBlocks* rt) { - TinyBlocks_Value l = tb_block_get_input(self, rt, 0), v = tb_block_get_input(self, rt, 1); - const char* lbl = l.kind==TB_VALUE_TEXT ? l.as.text : "resultado"; - if (v.kind==TB_VALUE_INTEGER) printf("%s = %lld\n", lbl, (long long)v.as.integer); - else if (v.kind==TB_VALUE_REAL) printf("%s = %g\n", lbl, v.as.real); - else if (v.kind==TB_VALUE_TEXT) printf("%s = %s\n", lbl, v.as.text); - else printf("%s\n", lbl); -} -static void eval_add(TinyBlocks_Block* self, TinyBlocks* rt) { - TinyBlocks_Value a = tb_block_get_input(self, rt, 0), b = tb_block_get_input(self, rt, 1); - long long x = a.kind==TB_VALUE_INTEGER ? a.as.integer : 0, y = b.kind==TB_VALUE_INTEGER ? b.as.integer : 0; - tb_block_set_output(self, 0, tb_value_integer(x + y)); -} static void eval_ev(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; self->dirty = false; } static void draw(void) { @@ -122,12 +115,13 @@ static bool need(const char* s, int region, int nth, float* x, float* y) { int main(void) { tinyblocks_init(&rt, NULL); - static const TinyBlocks_SlotDesc print_in[] = {{"label", TB_VALUE_TEXT}, {"value", TB_VALUE_NONE}}; - static const TinyBlocks_SlotDesc two_int[] = {{"a", TB_VALUE_INTEGER}, {"b", TB_VALUE_INTEGER}}; - static const TinyBlocks_SlotDesc int_out[] = {{"result", TB_VALUE_INTEGER}}; - tb_type_block_create(rt, "Math.Add", two_int, 2, int_out, 1, eval_add); - tb_type_block_create(rt, "IO.Print", print_in, 2, NULL, 0, eval_print); tb_graphics_set_backend(tb_graphics_null_backend()); + tb_library_register(rt, tb_events_get_library()); + tb_library_register(rt, tb_control_get_library()); + tb_library_register(rt, tb_operators_get_library()); + tb_library_register(rt, tb_variables_get_library()); + tb_library_register(rt, tb_appearance_get_library()); + tb_library_register(rt, tb_pen_get_library()); tb_library_register(rt, tb_graphics_get_library()); tb_library_register(rt, tb_editor_get_library()); (void)eval_ev; @@ -154,8 +148,8 @@ int main(void) { /* 3. Encaixar o "escreva Olá!" logo abaixo do chapéu */ float hx, hy; - if (need("quando ⚑ for clicado", R_WS, 0, &hx, &hy) && need("escreva", R_WS, 1, &x, &y)) { - /* hat: rótulo em (bx+10, by+18+18); fundo em by+54 → alvo: topo do bloco em by+54 */ + if (need("quando a bandeira for clicado", R_WS, 0, &hx, &hy) && need("escreva", R_WS, 1, &x, &y)) { + /* hat: rótulo em (bx+10, by+18+18); fundo em by+54 - alvo: topo do bloco em by+54 */ float bx = hx - 3 - 10, by = hy - 18 - 18; float gx = x - 3 - 10, gy = y - 18; /* canto do bloco arrastado */ drag(x, y, x + (bx - gx), y + (by + 54 - gy) + 6); @@ -169,7 +163,7 @@ int main(void) { } CHECK(oy1 > 0 && oy2 > oy1, "ordem de execução: Olá! antes de x vale"); - /* 4. Repórter "+": solto, editar campos, clicar → balão */ + /* 4. Repórter "+": solto, editar campos, clicar - balão */ if (need("Operadores", R_CAT, 0, &x, &y)) click(x, y); if (need("+", R_FLY, 0, &x, &y)) drag(x, y, 640, 470); if (need("+", R_WS, 0, &x, &y)) {