diff --git a/Makefile b/Makefile index 73f268b..1428f78 100644 --- a/Makefile +++ b/Makefile @@ -23,6 +23,8 @@ JSON_DIR := $(LIBDIR)/tinyblocks-json XML_DIR := $(LIBDIR)/tinyblocks-xml CSV_DIR := $(LIBDIR)/tinyblocks-csv BP_DIR := $(LIBDIR)/tinyblocks-blueprint +API_DIR := $(LIBDIR)/tinyblocks-api +LIBM_DIR := $(LIBDIR)/tinyblocks-libman ED_DIR := $(LIBDIR)/tinyblocks-editor GX_DIR := $(LIBDIR)/tinyblocks-graphics SD_DIR := $(LIBDIR)/tinyblocks-sdl2 @@ -67,6 +69,8 @@ JSON_A := $(JSON_DIR)/build/libtinyblocks-json.a XML_A := $(XML_DIR)/build/libtinyblocks-xml.a CSV_A := $(CSV_DIR)/build/libtinyblocks-csv.a BP_A := $(BP_DIR)/build/libtinyblocks-blueprint.a +API_A := $(API_DIR)/build/libtinyblocks-api.a +LIBM_A := $(LIBM_DIR)/build/libtinyblocks-libman.a LIB_LDFLAGS := -L$(ED_DIR)/build -L$(GX_DIR)/build -L$(SD_DIR)/build \ $(foreach l,$(CAT_LIBS),-L$(LIBDIR)/tinyblocks-$(l)/build) -L$(BUILD) @@ -76,7 +80,8 @@ LIB_LDFLAGS := -L$(ED_DIR)/build -L$(GX_DIR)/build -L$(SD_DIR)/build \ category-libs category-sos libs \ lib-events lib-control lib-operators lib-variables lib-appearance lib-pen lib-fs \ lib-editor lib-graphics lib-sdl2 lib-python lib-mcp lib-toml \ - lib-json lib-xml lib-csv lib-blueprint + lib-json lib-xml lib-csv lib-blueprint lib-api lib-libman \ + test-libman all: static example ## Compila a biblioteca estática e o exemplo hello (padrão) @@ -151,6 +156,12 @@ lib-csv: lib-blueprint: $(MAKE) -C $(BP_DIR) +lib-api: + $(MAKE) -C $(API_DIR) + +lib-libman: lib-api lib-toml + $(MAKE) -C $(LIBM_DIR) + lib-graphics: $(MAKE) -C $(GX_DIR) @@ -165,8 +176,8 @@ lib-mcp: libs: static lib-events lib-control lib-operators lib-variables \ lib-appearance lib-pen lib-fs lib-graphics lib-sdl2 lib-toml \ - lib-json lib-xml lib-csv lib-blueprint lib-editor - @echo "Libraries OK: category + graphics + sdl2 + toml + json + xml + csv + blueprint + editor" + lib-json lib-xml lib-csv lib-blueprint lib-api lib-libman lib-editor + @echo "Libraries OK: category + graphics + sdl2 + toml + json + xml + csv + blueprint + api + libman + editor" category-libs: static $(foreach l,$(CAT_LIBS),lib-$(l)) ## Compila as libraries de categoria (.a/.so) @echo "Build category libs OK" @@ -203,8 +214,9 @@ $(BUILD)/editor: examples/editor/main.c static libs -I$(ED_DIR)/include -I$(GFX_INC) $(CAT_INCS) \ -I$(FS_DIR)/include -I$(TOML_DIR)/include \ -I$(JSON_DIR)/include -I$(XML_DIR)/include -I$(CSV_DIR)/include -I$(BP_DIR)/include \ + -I$(API_DIR)/include -I$(LIBM_DIR)/include \ $< -o $@ \ - -Wl,--start-group $(ED_A) $(GX_A) $(SD_A) $(TOML_A) $(JSON_A) $(XML_A) $(CSV_A) $(BP_A) $(CAT_A) $(LIB_A) -Wl,--end-group \ + -Wl,--start-group $(ED_A) $(GX_A) $(SD_A) $(TOML_A) $(JSON_A) $(XML_A) $(CSV_A) $(BP_A) $(API_A) $(LIBM_A) $(CAT_A) $(LIB_A) -Wl,--end-group \ $(SDL2_LIBS) $(SDL2TTF_LIBS) -ldl -lm -rdynamic \ '-Wl,-rpath,$$ORIGIN' @@ -271,16 +283,19 @@ mcp-lib: static lib-mcp $(BUILD)/mcp.so ## Library cliente MCP -> build/mcp.so # ── Testes (harness headless com ASan/UBSan) ───────────────────────────── $(BUILD)/editor_harness: tests/editor_harness.c $(SRCS) \ $(EDITOR_SRC)/tb_editor.c $(EDITOR_SRC)/tb_stage_widget.c \ - $(GX_DIR)/src/tb_graphics.c + $(GX_DIR)/src/tb_graphics.c lib-blueprint @mkdir -p $(BUILD) $(CC) $(CFLAGS_DBG) \ -I$(ED_DIR)/include -I$(EDITOR_SRC) -I$(GFX_INC) $(CAT_INCS) -I$(BP_DIR)/include \ + -I$(API_DIR)/include -I$(LIBM_DIR)/include -I$(TOML_DIR)/include \ $(SRCS) \ $(EDITOR_SRC)/tb_editor.c $(EDITOR_SRC)/tb_stage_widget.c \ $(GX_DIR)/src/tb_graphics.c \ $(BP_DIR)/src/blueprint.c $(BP_DIR)/src/serialize.c \ + $(API_DIR)/src/tb_api.c $(LIBM_DIR)/src/tb_libman.c \ + $(TOML_LIB_SRCS) $(TOML_DIR)/src/tb_toml.c \ $(foreach l,$(CAT_LIBS),$(LIBDIR)/tinyblocks-$(l)/src/tb_$(l).c) \ - tests/editor_harness.c -o $@ -ldl -lm + tests/editor_harness.c -o $@ -ldl -lm -rdynamic test-editor: $(BUILD)/editor_harness ## Roda o harness headless do editor (ASan/UBSan) ./$(BUILD)/editor_harness @@ -306,6 +321,23 @@ $(BUILD)/blueprint_test: tests/blueprint_test.c $(BP_LIB_SRCS) static test-blueprint: $(BUILD)/blueprint_test ## Roda o teste da blueprint (ASan/UBSan) ./$(BUILD)/blueprint_test +# -- Teste do gestor de libraries (libman + api) --- +$(BUILD)/libman_test: tests/libman_test.c \ + $(API_DIR)/src/tb_api.c $(LIBM_DIR)/src/tb_libman.c \ + $(TOML_LIB_SRCS) $(TOML_DIR)/src/tb_toml.c \ + $(foreach l,$(CAT_LIBS),$(LIBDIR)/tinyblocks-$(l)/src/tb_$(l).c) static + @mkdir -p $(BUILD) + $(CC) $(CFLAGS_DBG) -I$(API_DIR)/include -I$(LIBM_DIR)/include -I$(TOML_DIR)/include \ + $(CAT_INCS) \ + $(API_DIR)/src/tb_api.c $(LIBM_DIR)/src/tb_libman.c \ + $(TOML_LIB_SRCS) $(TOML_DIR)/src/tb_toml.c \ + $(foreach l,$(CAT_LIBS),$(LIBDIR)/tinyblocks-$(l)/src/tb_$(l).c) \ + tests/libman_test.c -o $@ \ + -Wl,--start-group $(LIB_A) -Wl,--end-group -ldl -lm + +test-libman: $(BUILD)/libman_test ## Roda o teste do libman/api (ASan/UBSan) + ./$(BUILD)/libman_test + # -- Teste de plugin .so standalone --- FS_SO := $(FS_DIR)/build/libtinyblocks-fs.so @@ -322,6 +354,7 @@ clean: ## Remove os diretórios build/ (raiz e libraries) $(RM) -r $(BUILD) @for d in $(EV_DIR) $(CT_DIR) $(OP_DIR) $(VR_DIR) $(AP_DIR) $(PN_DIR) $(FS_DIR) \ $(TOML_DIR) $(JSON_DIR) $(XML_DIR) $(CSV_DIR) $(BP_DIR) \ + $(API_DIR) $(LIBM_DIR) \ $(ED_DIR) $(GX_DIR) $(SD_DIR) $(PY_DIR) $(MC_DIR); do \ $(MAKE) -C $$d clean >/dev/null 2>&1 || true; \ done diff --git a/include/tinyblocks/tb_library_block.h b/include/tinyblocks/tb_library_block.h index dcb5a0b..b586f2b 100644 --- a/include/tinyblocks/tb_library_block.h +++ b/include/tinyblocks/tb_library_block.h @@ -83,6 +83,11 @@ 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); +/* -- Acesso publico aos metadados (nao exponha o struct) --- */ +TB_API const char* tb_library_name (const TinyBlocks_LibraryBlock* lib); +TB_API const TinyBlocks_Category* tb_library_category (const TinyBlocks_LibraryBlock* lib); +TB_API uint32_t tb_library_block_count(const TinyBlocks_LibraryBlock* lib); + /* == 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/include/tinyblocks/tinyblocks.h b/include/tinyblocks/tinyblocks.h index 1fdfd4d..8ec6c9d 100644 --- a/include/tinyblocks/tinyblocks.h +++ b/include/tinyblocks/tinyblocks.h @@ -107,6 +107,12 @@ TB_API TinyBlocks_Block* tb_rt_find_block (TinyBlocks* rt, uint64_t id); TB_API TinyBlocks_TypeBlock* tb_rt_find_type (TinyBlocks* rt, const char* name); TB_API TinyBlocks_LibraryBlock* tb_rt_find_library(TinyBlocks* rt, const char* name); +/* -- Enumeracao publica dos registros (sem expor os campos do struct) --- */ +TB_API uint32_t tb_rt_type_count (const TinyBlocks* rt); +TB_API TinyBlocks_TypeBlock* tb_rt_type_at (const TinyBlocks* rt, uint32_t i); +TB_API uint32_t tb_rt_library_count(const TinyBlocks* rt); +TB_API TinyBlocks_LibraryBlock* tb_rt_library_at (const TinyBlocks* rt, uint32_t i); + /* -- Geração de ID --- */ TB_API uint64_t tb_rt_next_id(TinyBlocks* rt); diff --git a/libraries/tinyblocks-api/Makefile b/libraries/tinyblocks-api/Makefile new file mode 100644 index 0000000..8a952ec --- /dev/null +++ b/libraries/tinyblocks-api/Makefile @@ -0,0 +1,29 @@ +# Makefile da library api (gestor publico de modulos/libraries) +# Constroi build/libtinyblocks-api.a e build/libtinyblocks-api.so +CC := gcc +BUILD := build + +CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \ + -D_POSIX_C_SOURCE=200809L -I../../include -Iinclude + +OBJ := $(BUILD)/tb_api.o +LIB_A := $(BUILD)/libtinyblocks-api.a +LIB_SO := $(BUILD)/libtinyblocks-api.so + +.PHONY: all static shared clean +all: static shared +static: $(LIB_A) +shared: $(LIB_SO) + +$(OBJ): src/tb_api.c include/tb_api.h + @mkdir -p $(BUILD) + $(CC) $(CFLAGS) -fPIC -c $< -o $@ + +$(LIB_A): $(OBJ) + ar rcs $@ $^ + +$(LIB_SO): $(OBJ) + $(CC) -shared -o $@ $^ -ldl + +clean: + $(RM) -r $(BUILD) diff --git a/libraries/tinyblocks-api/include/tb_api.h b/libraries/tinyblocks-api/include/tb_api.h new file mode 100644 index 0000000..233c59b --- /dev/null +++ b/libraries/tinyblocks-api/include/tb_api.h @@ -0,0 +1,74 @@ +/* + * TinyBlocks - tb_api.h + * Library tinyblocks-api: gestor publico de modulos/libraries e "cola" entre + * plugins (.so), libraries registradas e o registro de tipos do runtime. + * + * Responsabilidades: + * - carregar/descarregar/recarregar plugins .so (dlopen + tb_library_register) + * - adotar libraries embutidas (registradas estaticamente no runtime) + * - hot reload por mtime + * - introspeccao: enumerar modulos e tipos de bloco disponiveis + * + * NAO desenha UI: quem desenha e o editor. + */ +#ifndef TINYBLOCKS_API_H +#define TINYBLOCKS_API_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define TB_API_MAX_MODULES 64 +#define TB_API_PATH_LEN 512 + +/* Um modulo/library conhecido pelo processo (embutido ou .so dinamico). */ +typedef struct TbApiModule { + char name[64]; /* nome da library (desc->name) */ + char version[32]; + char path[TB_API_PATH_LEN]; /* .so de origem; "" se embutido */ + void* handle; /* dlopen; NULL se embutido */ + TinyBlocks_LibraryBlock* lib; + const TinyBlocks_Category* category; /* pode ser NULL */ + unsigned block_count; + time_t mtime; /* mtime do .so (hot reload) */ +} TbApiModule; + +/* -- Ciclo de vida --- */ +TB_API bool tb_api_init(TinyBlocks* rt); +TB_API void tb_api_shutdown(void); +TB_API TinyBlocks* tb_api_runtime(void); +TB_API const char* tb_api_last_error(void); + +/* -- Registro de modulos --- */ +/* Adota as libraries ja registradas no runtime (embutidas). Retorna o total. */ +TB_API int tb_api_adopt_all(void); +TB_API int tb_api_module_count(void); +TB_API const TbApiModule* tb_api_module(int i); +TB_API const TbApiModule* tb_api_module_find(const char* name); + +/* -- Carregamento dinamico --- */ +/* Carrega um .so; retorna o indice (>=0) ou -1 (erro em tb_api_last_error). */ +TB_API int tb_api_load(const char* path); +TB_API bool tb_api_unload(int idx); +TB_API bool tb_api_reload(int idx); +TB_API bool tb_api_is_loaded(const char* name); + +/* Hot reload: true se algum .so mudou no disco desde o ultimo load. */ +TB_API bool tb_api_any_changed(void); +/* Recarrega os .so que mudaram; retorna quantos. */ +TB_API int tb_api_poll_reload(void); + +/* -- Introspeccao de tipos de bloco (API publica) --- */ +TB_API int tb_api_type_count(void); +TB_API const TinyBlocks_TypeBlock* tb_api_type(int i); +TB_API const TinyBlocks_TypeBlock* tb_api_type_find(const char* name); + +#ifdef __cplusplus +} +#endif + +#endif /* TINYBLOCKS_API_H */ diff --git a/libraries/tinyblocks-api/library.toml b/libraries/tinyblocks-api/library.toml new file mode 100644 index 0000000..8bd46b3 --- /dev/null +++ b/libraries/tinyblocks-api/library.toml @@ -0,0 +1,15 @@ +# Metadados da library api (gestor publico de modulos/libraries). +[library] +name = "tinyblocks-api" +version = "1.0.0" +category = "API" +description = "Gestor publico de modulos, plugins e tipos de bloco" +color = [96, 125, 139, 255] +dark = [69, 90, 100, 255] + +[build] +sources = ["src/tb_api.c"] +includes = ["include"] +shared = "build/libtinyblocks-api.so" +static = "build/libtinyblocks-api.a" +depends = [] diff --git a/libraries/tinyblocks-api/src/tb_api.c b/libraries/tinyblocks-api/src/tb_api.c new file mode 100644 index 0000000..99e3745 --- /dev/null +++ b/libraries/tinyblocks-api/src/tb_api.c @@ -0,0 +1,197 @@ +/* + * TinyBlocks - tb_api.c + * Implementacao do gestor publico de modulos/libraries (tinyblocks-api). + */ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include + +#ifdef __linux__ +# include +#endif + +#include +#include "tb_api.h" + +typedef const TinyBlocks_LibraryDescriptor* (*GetLibFn)(void); + +static TinyBlocks* s_rt = NULL; +static TbApiModule s_mods[TB_API_MAX_MODULES]; +static int s_n = 0; +static char s_err[256]; + +/* -- Helpers --- */ +static time_t file_mtime(const char* p) { + struct stat st; + return (stat(p, &st) == 0) ? st.st_mtime : 0; +} + +static void set_err(const char* fmt, const char* a) { + snprintf(s_err, sizeof(s_err), fmt, a ? a : ""); +} + +static int find_by_lib(const TinyBlocks_LibraryBlock* lib) { + for (int i = 0; i < s_n; i++) if (s_mods[i].lib == lib) return i; + return -1; +} + +static int find_by_name(const char* name) { + if (!name) return -1; + for (int i = 0; i < s_n; i++) if (strcmp(s_mods[i].name, name) == 0) return i; + return -1; +} + +/* -- Ciclo de vida --- */ +bool tb_api_init(TinyBlocks* rt) { + s_rt = rt; + s_n = 0; + s_err[0] = 0; + return rt != NULL; +} + +void tb_api_shutdown(void) { + /* O runtime e o dono dos blocos; aqui so esquecemos os modulos. */ + s_n = 0; + s_rt = NULL; +} + +TinyBlocks* tb_api_runtime(void) { return s_rt; } +const char* tb_api_last_error(void) { return s_err; } + +/* -- Registro de modulos --- */ +int tb_api_adopt_all(void) { + if (!s_rt) return 0; + for (uint32_t i = 0; i < tb_rt_library_count(s_rt); i++) { + TinyBlocks_LibraryBlock* lib = tb_rt_library_at(s_rt, i); + if (!lib || find_by_lib(lib) >= 0) continue; + if (s_n >= TB_API_MAX_MODULES) break; + TbApiModule* m = &s_mods[s_n]; + memset(m, 0, sizeof(*m)); + const char* nm = tb_library_name(lib); + snprintf(m->name, sizeof(m->name), "%s", nm ? nm : "?"); + m->lib = lib; + m->category = tb_library_category(lib); + m->block_count = tb_library_block_count(lib); + s_n++; + } + return s_n; +} + +int tb_api_module_count(void) { return s_n; } + +const TbApiModule* tb_api_module(int i) { + return (i >= 0 && i < s_n) ? &s_mods[i] : NULL; +} + +const TbApiModule* tb_api_module_find(const char* name) { + int i = find_by_name(name); + return i >= 0 ? &s_mods[i] : NULL; +} + +bool tb_api_is_loaded(const char* name) { return find_by_name(name) >= 0; } + +/* -- Carregamento dinamico --- */ +int tb_api_load(const char* path) { + if (!s_rt) { set_err("%s", "tb_api: runtime nao inicializado"); return -1; } + if (!path || !path[0]) { set_err("%s", "tb_api: caminho vazio"); return -1; } + if (s_n >= TB_API_MAX_MODULES) { set_err("%s", "tb_api: limite de modulos atingido"); return -1; } + +#ifdef __linux__ + void* dl = dlopen(path, RTLD_NOW | RTLD_LOCAL); + if (!dl) { set_err("dlopen: %s", dlerror()); return -1; } + + GetLibFn get_lib = (GetLibFn)(uintptr_t)dlsym(dl, TINYBLOCKS_LIBRARY_SYMBOL); + if (!get_lib) { + const char* base = strrchr(path, '/'); + base = base ? base + 1 : path; + if (strncmp(base, "libtinyblocks-", 14) == 0) + set_err("'%s' e dependencia = carregue a library (ex: python.so)", base); + else + set_err("'%s' nao exporta tinyblocks_get_library", base); + dlclose(dl); + return -1; + } + + const TinyBlocks_LibraryDescriptor* desc = get_lib(); + TinyBlocks_LibraryBlock* lib = tb_library_register(s_rt, desc); + if (!lib) { set_err("tb_library_register falhou para %s", path); dlclose(dl); return -1; } + + TbApiModule* m = &s_mods[s_n]; + memset(m, 0, sizeof(*m)); + snprintf(m->name, sizeof(m->name), "%s", desc->name ? desc->name : "?"); + snprintf(m->version, sizeof(m->version), "%s", desc->version ? desc->version : ""); + snprintf(m->path, sizeof(m->path), "%s", path); + m->handle = dl; + m->lib = lib; + m->category = tb_library_category(lib); + m->block_count = tb_library_block_count(lib); + m->mtime = file_mtime(path); + s_err[0] = 0; + return s_n++; +#else + (void)path; + set_err("%s", "tb_api: dlopen nao suportado nesta plataforma"); + return -1; +#endif +} + +bool tb_api_unload(int idx) { + if (idx < 0 || idx >= s_n) return false; + TbApiModule* m = &s_mods[idx]; + if (m->lib) tb_library_unload(s_rt, m->lib); +#ifdef __linux__ + if (m->handle) dlclose(m->handle); +#endif + for (int i = idx; i < s_n - 1; i++) s_mods[i] = s_mods[i + 1]; + s_n--; + return true; +} + +bool tb_api_reload(int idx) { + if (idx < 0 || idx >= s_n) return false; + if (!s_mods[idx].path[0]) return false; /* embutida nao recarrega */ + char path[TB_API_PATH_LEN]; + snprintf(path, sizeof(path), "%s", s_mods[idx].path); + tb_api_unload(idx); + return tb_api_load(path) >= 0; +} + +bool tb_api_any_changed(void) { + for (int i = 0; i < s_n; i++) { + TbApiModule* m = &s_mods[i]; + if (!m->path[0]) continue; + time_t mt = file_mtime(m->path); + if (mt && mt != m->mtime) return true; + } + return false; +} + +int tb_api_poll_reload(void) { + int n = 0; + for (int i = 0; i < s_n; i++) { + TbApiModule* m = &s_mods[i]; + if (!m->path[0]) continue; + time_t mt = file_mtime(m->path); + if (!mt || mt == m->mtime) continue; + char path[TB_API_PATH_LEN]; + snprintf(path, sizeof(path), "%s", m->path); + tb_api_unload(i); + if (tb_api_load(path) >= 0) n++; + i = -1; /* a lista mudou; reinicia a varredura */ + } + return n; +} + +/* -- Introspeccao de tipos --- */ +int tb_api_type_count(void) { return (int)tb_rt_type_count(s_rt); } + +const TinyBlocks_TypeBlock* tb_api_type(int i) { + if (i < 0) return NULL; + return tb_rt_type_at(s_rt, (uint32_t)i); +} + +const TinyBlocks_TypeBlock* tb_api_type_find(const char* name) { + return s_rt ? tb_rt_find_type(s_rt, name) : NULL; +} diff --git a/libraries/tinyblocks-editor/Makefile b/libraries/tinyblocks-editor/Makefile index b4c27bf..de99017 100644 --- a/libraries/tinyblocks-editor/Makefile +++ b/libraries/tinyblocks-editor/Makefile @@ -10,7 +10,9 @@ CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \ -I../../include -Iinclude -Isrc \ -I../tinyblocks-graphics/include \ -I../tinyblocks-variables/include \ - -I../tinyblocks-blueprint/include + -I../tinyblocks-blueprint/include \ + -I../tinyblocks-api/include \ + -I../tinyblocks-libman/include OBJ := $(BUILD)/tb_editor.o $(BUILD)/tb_stage_widget.o LIB_A := $(BUILD)/libtinyblocks-editor.a @@ -24,7 +26,9 @@ shared: $(LIB_SO) $(BUILD)/tb_editor.o: src/tb_editor.c include/tb_editor.h src/tb_stage_widget.h \ ../tinyblocks-graphics/include/tb_graphics.h \ ../tinyblocks-variables/include/tb_variables.h \ - ../tinyblocks-blueprint/include/tb_blueprint.h + ../tinyblocks-blueprint/include/tb_blueprint.h \ + ../tinyblocks-api/include/tb_api.h \ + ../tinyblocks-libman/include/tb_libman.h @mkdir -p $(BUILD) $(CC) $(CFLAGS) -fPIC -c $< -o $@ diff --git a/libraries/tinyblocks-editor/src/tb_editor.c b/libraries/tinyblocks-editor/src/tb_editor.c index 1526f13..558ec48 100644 --- a/libraries/tinyblocks-editor/src/tb_editor.c +++ b/libraries/tinyblocks-editor/src/tb_editor.c @@ -39,6 +39,8 @@ #include #include #include +#include +#include #include "tb_stage_widget.h" #include "../include/tb_editor.h" @@ -91,8 +93,10 @@ TB_API void tb_editor_preload(const char* path) { #define SAVE_BTN_W 70 #define EXP_BTN_X 296 #define EXP_BTN_W 84 -#define LIB_BTN_X 392 -#define LIB_BTN_W 168 +#define LIBM_BTN_X 388 +#define LIBM_BTN_W 104 +#define LIB_BTN_X 500 +#define LIB_BTN_W 200 /* == Geometria dos blocos === */ #define FS 12 /* texto dos blocos */ @@ -129,7 +133,6 @@ TB_API void tb_editor_preload(const char* path) { #define MAX_RUN_BLOCKS 200000 #define STAGE_BUF 16384 #define LIT_TEXT_CAP 512 -#define MAX_HOT_LIBS 16 #define MAX_HOT_TYPES 64 #define MAX_USER_BLOCKS 16 #define MAX_UBLK_SLOTS 8 @@ -302,13 +305,6 @@ typedef struct { TinyBlocks_Value out[MAX_UBLK_SLOTS]; } CallFrame; -typedef struct { - char path[512]; - void* dl; - time_t mtime; - TinyBlocks_LibraryBlock* lib; -} HotLib; - typedef struct { char name[32]; char prefix[32]; Col col, dark; float fly_y; const TinyBlocks_LibraryBlock* lib; } Cat; @@ -408,8 +404,6 @@ typedef struct { bool clip_on; float clip[4]; - HotLib hot_libs[MAX_HOT_LIBS]; - int hot_lib_n; int hot_check_frame; char hot_status[256]; bool hot_status_ok; @@ -419,6 +413,17 @@ typedef struct { int path_input_len; int path_mode; /* PM_* - o que fazer no Enter */ + /* Gestor de libraries (tinyblocks-libman); a UI e desenhada aqui */ + bool libman_open; + char libman_query[128]; + int libman_query_len; + bool libman_search_focus; + int libman_filter; /* -1 = Tudo; senao indice em libman_cats */ + char libman_cats[MAX_CATS][48]; + int libman_cat_n; + int libman_scroll; + int libman_hover; + int win_w, win_h; } Ed; @@ -437,6 +442,14 @@ 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); +/* Gestor de libraries (tinyblocks-libman) - UI desenhada pelo editor */ +static void libman_show(Ed* ed); +static void libman_click(Ed* ed, float mx, float my); +static void libman_key(Ed* ed, int sc); +static void libman_text(Ed* ed, const char* typed); +static void libman_scroll_by(Ed* ed, float dy); +static void libman_render(Ed* ed, TinyBlocks_RenderableBlock* rb); + /* === * Helpers de desenho - emitem TinyBlocks_DrawCmd em um RenderableBlock * === */ @@ -1644,16 +1657,15 @@ static bool type_hidden(Ed* ed, const TinyBlocks_TypeBlock* t) { static void cats_rebuild(Ed* ed) { ed->cat_n = 0; /* 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; + for (uint32_t i = 0; i < tb_rt_library_count(ed->rt) && ed->cat_n < MAX_CATS; i++) { + TinyBlocks_LibraryBlock* lib = tb_rt_library_at(ed->rt, i); + const TinyBlocks_Category* cat = tb_library_category(lib); + if (!cat || !cat->name) continue; Cat* c = &ed->cats[ed->cat_n++]; memset(c, 0, sizeof(*c)); - 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]}; + snprintf(c->name, sizeof(c->name), "%s", cat->name); + c->col = (Col){cat->color[0], cat->color[1], cat->color[2], cat->color[3]}; + c->dark = (Col){cat->dark[0], cat->dark[1], cat->dark[2], cat->dark[3]}; c->lib = lib; } /* 2) "Meus Blocos" pertence ao editor */ @@ -1666,8 +1678,8 @@ static void cats_rebuild(Ed* ed) { 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]; + for (uint32_t i = 0; i < tb_rt_type_count(ed->rt) && ed->cat_n < MAX_CATS; i++) { + TinyBlocks_TypeBlock* t = tb_rt_type_at(ed->rt, i); if (type_hidden(ed, t) || cat_of_type(ed, t) >= 0) continue; Cat* c = &ed->cats[ed->cat_n++]; memset(c, 0, sizeof(*c)); @@ -1705,8 +1717,8 @@ static void palette_rebuild(Ed* ed) { 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]; + for (uint32_t i = 0; i < tb_rt_type_count(ed->rt); i++) { + TinyBlocks_TypeBlock* t = tb_rt_type_at(ed->rt, i); if (type_hidden(ed, t) || cat_of_type(ed, t) != c) continue; fly_add_block(ed, c, t, NULL, &y); } @@ -2462,93 +2474,29 @@ static void dlg_text(Ed* ed, const char* 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; -} - -typedef const TinyBlocks_LibraryDescriptor* (*GetLibFn)(void); - static bool hotlib_load(Ed* ed, const char* path) { - if (ed->hot_lib_n >= MAX_HOT_LIBS) { - snprintf(ed->hot_status, sizeof(ed->hot_status), - "Hot reload: limite de %d libs atingido", MAX_HOT_LIBS); + int idx = tb_api_load(path); + if (idx < 0) { + snprintf(ed->hot_status, sizeof(ed->hot_status), "%s", tb_api_last_error()); ed->hot_status_ok = false; return false; } - void* dl = dlopen(path, RTLD_NOW | RTLD_LOCAL); - if (!dl) { - snprintf(ed->hot_status, sizeof(ed->hot_status), "dlopen: %s", dlerror()); - ed->hot_status_ok = false; - return false; - } - GetLibFn get_lib = (GetLibFn)(uintptr_t)dlsym(dl, TINYBLOCKS_LIBRARY_SYMBOL); - if (!get_lib) { - const char* base = strrchr(path, '/'); - base = base ? base+1 : path; - if (strncmp(base, "libtinyblocks-", 14) == 0) - snprintf(ed->hot_status, sizeof(ed->hot_status), - "'%s' é dependência = carregue a library (ex: python.so, mcp.so)", base); - else - snprintf(ed->hot_status, sizeof(ed->hot_status), - "'%s' não exporta tinyblocks_get_library = não é uma library válida", base); - ed->hot_status_ok = false; - dlclose(dl); - return false; - } - TinyBlocks_LibraryBlock* lib = tb_library_register(ed->rt, get_lib()); - if (!lib) { - snprintf(ed->hot_status, sizeof(ed->hot_status), "tb_library_register falhou para %s", path); - ed->hot_status_ok = false; - dlclose(dl); - return false; - } - HotLib* h = &ed->hot_libs[ed->hot_lib_n++]; - strncpy(h->path, path, sizeof(h->path)-1); - h->dl = dl; - h->mtime = file_mtime(path); - h->lib = lib; retype_all(ed); /* blocos que estavam sem tipo podem ganhar um agora */ snprintf(ed->hot_status, sizeof(ed->hot_status), "Carregado: %s", path); ed->hot_status_ok = true; return true; } -static void hotlib_reload(Ed* ed, int idx) { - HotLib* h = &ed->hot_libs[idx]; - /* Nenhuma instância ou ponteiro de tipo pode sobreviver ao unload */ - invalidate_types(ed); - tb_library_unload(ed->rt, h->lib); - h->lib = NULL; - dlclose(h->dl); - h->dl = NULL; - h->mtime = file_mtime(h->path); - - void* dl = dlopen(h->path, RTLD_NOW | RTLD_LOCAL); - GetLibFn get_lib = dl ? (GetLibFn)(uintptr_t)dlsym(dl, TINYBLOCKS_LIBRARY_SYMBOL) : NULL; - TinyBlocks_LibraryBlock* lib = get_lib ? tb_library_register(ed->rt, get_lib()) : NULL; - if (!lib) { - snprintf(ed->hot_status, sizeof(ed->hot_status), "Hot reload falhou: %.230s", - dl ? h->path : dlerror()); - ed->hot_status_ok = false; - if (dl) dlclose(dl); - retype_all(ed); - return; - } - h->dl = dl; - h->lib = lib; - retype_all(ed); - snprintf(ed->hot_status, sizeof(ed->hot_status), "Recarregado: %.240s", h->path); - ed->hot_status_ok = true; -} - +/* Hot reload: recarrega os .so cujo mtime mudou (delegado a tinyblocks-api). */ static void hotlib_check(Ed* ed) { - for (int i = 0; i < ed->hot_lib_n; i++) { - HotLib* h = &ed->hot_libs[i]; - if (!h->dl || !h->path[0]) continue; - time_t mt = file_mtime(h->path); - if (mt && mt != h->mtime) hotlib_reload(ed, i); - } + if (++ed->hot_check_frame < 60) return; + ed->hot_check_frame = 0; + if (!tb_api_any_changed()) return; + invalidate_types(ed); /* nenhum ponteiro de tipo pode sobreviver ao unload */ + tb_api_poll_reload(); + retype_all(ed); + snprintf(ed->hot_status, sizeof(ed->hot_status), "Hot reload: libraries recarregadas"); + ed->hot_status_ok = true; } /* === @@ -2557,6 +2505,7 @@ static void hotlib_check(Ed* ed) { static bool hit_open_btn(float mx, float my); static bool hit_save_btn(float mx, float my); static bool hit_export_btn(float mx, float my); +static bool hit_libman_btn(float mx, float my); static void menu_button(TinyBlocks_RenderableBlock* rb, float x, float w, const char* label, bool active) { rb_fill_rrect(rb, x, 7, w, MENU_H - 14, 6, active ? COL_MENU_DARK : COLA(255, 255, 255, 34)); @@ -2572,6 +2521,7 @@ static void render_menu(Ed* ed, TinyBlocks_RenderableBlock* rb) { menu_button(rb, OPEN_BTN_X, OPEN_BTN_W, "Abrir", (active && ed->path_mode == PM_LOAD) || hit_open_btn(mx, my)); menu_button(rb, SAVE_BTN_X, SAVE_BTN_W, "Salvar", (active && ed->path_mode == PM_SAVE) || hit_save_btn(mx, my)); menu_button(rb, EXP_BTN_X, EXP_BTN_W, "Exportar", (ed->ctx_menu_open && ed->ctx_export) || hit_export_btn(mx, my)); + menu_button(rb, LIBM_BTN_X, LIBM_BTN_W, "Bibliotecas", ed->libman_open || hit_libman_btn(mx, my)); if (ed->lib_hover || (active && ed->path_mode == PM_LIB)) rb_fill_rect(rb, LIB_BTN_X, 0, LIB_BTN_W, MENU_H, COL_MENU_DARK); @@ -2891,6 +2841,225 @@ static void render_ctx_menu(Ed* ed, TinyBlocks_RenderableBlock* rb) { } } +/* === + * Gestor de libraries (tinyblocks-libman) - UI do editor + * === */ +#define LM_HEAD_H 64 +#define LM_MARGIN 40 +#define LM_CARD_H 190 +#define LM_CARD_GAP 24 +#define LM_CHIP_H 34 +#define LM_CHIP_GAP 10 +#define LM_SEARCH_W 340 +#define LM_CARD_W ((WIN_W - 2*LM_MARGIN - LM_CARD_GAP) / 2) +#define LM_MAX_CHIPS (MAX_CATS + 1) + +static void libman_close(Ed* ed) { + ed->libman_open = false; + ed->libman_search_focus = false; +} + +static void libman_show(Ed* ed) { + ed->libman_open = true; + ed->libman_query[0] = 0; + ed->libman_query_len = 0; + ed->libman_search_focus = true; + ed->libman_filter = -1; + ed->libman_scroll = 0; + ed->libman_hover = -1; + ed->libman_cat_n = tb_libman_categories(ed->libman_cats, MAX_CATS); + ed->path_input_active = false; + ed->ctx_menu_open = false; +} + +static const char* libman_filter_name(Ed* ed) { + return (ed->libman_filter >= 0 && ed->libman_filter < ed->libman_cat_n) + ? ed->libman_cats[ed->libman_filter] : "Tudo"; +} + +static int libman_chip_labels(Ed* ed, const char** out) { + out[0] = "Tudo"; + int n = 1; + for (int i = 0; i < ed->libman_cat_n && n < LM_MAX_CHIPS; i++) out[n++] = ed->libman_cats[i]; + return n; +} + +/* Posiciona as chips (layout que quebra linha). Retorna a altura total + * (relativa ao topo, a partir de LM_HEAD_H). */ +static float libman_chip_layout(Ed* ed, float rects[][4]) { + const char* labels[LM_MAX_CHIPS]; + int n = libman_chip_labels(ed, labels); + float x0 = LM_MARGIN + LM_SEARCH_W + 24; + float x = x0, y = LM_HEAD_H + 14, rowmax = y; + for (int i = 0; i < n; i++) { + float w = tw(labels[i], FS_UI) + 28; + if (x + w > WIN_W - LM_MARGIN) { x = x0; y += LM_CHIP_H + LM_CHIP_GAP; } + if (rects) { rects[i][0] = x; rects[i][1] = y; rects[i][2] = w; rects[i][3] = LM_CHIP_H; } + x += w + LM_CHIP_GAP; + rowmax = y; + } + return rowmax + LM_CHIP_H + 14 - LM_HEAD_H; +} + +static float libman_grid_y(Ed* ed) { + return LM_HEAD_H + libman_chip_layout(ed, NULL) + 8; +} + +static void libman_render(Ed* ed, TinyBlocks_RenderableBlock* rb) { + if (!ed->libman_open) return; + int hits[TBLM_MAX_ENTRIES]; + int nh = tb_libman_search(ed->libman_query, libman_filter_name(ed), hits, TBLM_MAX_ENTRIES); + float gridY = libman_grid_y(ed); + + /* Fundo */ + rb_fill_rect(rb, 0, 0, WIN_W, WIN_H, COL_UI_BG); + + /* Cabeçalho */ + rb_fill_rect(rb, 0, 0, WIN_W, LM_HEAD_H, COL_MENU); + float bx = LM_MARGIN, by = LM_HEAD_H*0.5f; + rb_fill_circle(rb, bx, by, 16, COLA(255,255,255,40)); + rb_line(rb, bx+4, by-7, bx-5, by, 2.f, COL_WHITE); + rb_line(rb, bx-5, by, bx+4, by+7, 2.f, COL_WHITE); + rb_text_c(rb, bx + 28, by, "Voltar", COL_WHITE, FS_UI); + { const char* t = "Escolha uma Extensão"; + rb_text_c(rb, (WIN_W - tw(t, 20))*0.5f, by, t, COL_WHITE, 20); } + + /* Barra de filtros */ + float fh = libman_chip_layout(ed, NULL); + rb_fill_rect(rb, 0, LM_HEAD_H, WIN_W, fh, COL_PANEL); + float sx = LM_MARGIN, sy = LM_HEAD_H + 14; + rb_fill_rrect(rb, sx, sy, LM_SEARCH_W, 44, 22, COL_UI_BG); + if (ed->libman_search_focus) rb_stroke_rect(rb, sx-1, sy-1, LM_SEARCH_W+2, 46, 2.f, COL_MENU); + { + const char* t = ed->libman_query[0] ? ed->libman_query : "Buscar"; + rb_text_c(rb, sx + 16, sy + 22, t, + ed->libman_query[0] ? COL_TEXT : COL_TEXT_DIM, FS_UI); + if (ed->libman_search_focus) { + float cw = tw(ed->libman_query, FS_UI); + rb_fill_rect(rb, sx + 16 + cw, sy + 12, 1.5f, 20, COL_TEXT); + } + } + { + const char* labels[LM_MAX_CHIPS]; + int n = libman_chip_labels(ed, labels); + float rects[LM_MAX_CHIPS][4]; + libman_chip_layout(ed, rects); + for (int i = 0; i < n; i++) { + bool sel = (i == 0) ? (ed->libman_filter < 0) : (ed->libman_filter == i-1); + rb_fill_rrect(rb, rects[i][0], rects[i][1], rects[i][2], rects[i][3], 17, + sel ? COL_MENU : COL_UI_BG); + rb_text_c(rb, rects[i][0] + 14, rects[i][1] + LM_CHIP_H*0.5f, labels[i], + sel ? COL_WHITE : COL_TEXT, FS_UI); + } + } + + /* Grade de cartoes (com recorte e rolagem) */ + rb_fill_rect(rb, 0, gridY, WIN_W, WIN_H - gridY, COL_UI_BG); + clip_set(ed, rb, 0, gridY, WIN_W, WIN_H - gridY); + for (int k = 0; k < nh; k++) { + int col = k % 2, row = k / 2; + float x = LM_MARGIN + col*(LM_CARD_W + LM_CARD_GAP); + float y = gridY + 8 + row*(LM_CARD_H + LM_CARD_GAP) - ed->libman_scroll; + if (y + LM_CARD_H < gridY) continue; + if (y > WIN_H) break; + const TbLibmanEntry* e = tb_libman_entry(hits[k]); + if (!e) continue; + Col c = { e->color[0]/255.f, e->color[1]/255.f, e->color[2]/255.f, 1.f }; + rb_fill_rrect(rb, x, y, LM_CARD_W, LM_CARD_H, 8, COL_PANEL); + rb_fill_rrect(rb, x, y, LM_CARD_W, 56, 8, c); + rb_fill_rect(rb, x, y + 40, LM_CARD_W, 16, c); + rb_text_c(rb, x + 16, y + 28, e->category, COL_WHITE, FS_UI); + rb_text_c(rb, x + 16, y + 84, e->name, COL_TEXT, 18); + rb_text_c(rb, x + 16, y + 114, e->description, COL_TEXT_DIM, FS_UI); + rb_text_c(rb, x + 16, y + LM_CARD_H - 22, e->shared, COL_TEXT_DIM, FS_SM); + if (tb_libman_loaded(hits[k])) { + rb_fill_circle(rb, x + LM_CARD_W - 24, y + 28, 8, COL_FLAG); + rb_text_c(rb, x + LM_CARD_W - 110, y + LM_CARD_H - 22, "carregada", COL_FLAG, FS_SM); + } + if (ed->libman_hover == k) rb_stroke_rect(rb, x-1, y-1, LM_CARD_W+2, LM_CARD_H+2, 2.f, COL_MENU); + } + clip_clear(ed, rb); + + if (nh == 0) + rb_text_c(rb, LM_MARGIN, gridY + 40, "Nenhuma library encontrada.", COL_TEXT_DIM, FS_UI); +} + +static void libman_click(Ed* ed, float mx, float my) { + if (my < LM_HEAD_H) { + if (mx < 170) libman_close(ed); + return; + } + float gridY = libman_grid_y(ed); + if (my < gridY) { + if (in_rect(mx, my, LM_MARGIN, LM_HEAD_H + 14, LM_SEARCH_W, 44)) { + ed->libman_search_focus = true; + return; + } + const char* labels[LM_MAX_CHIPS]; + int n = libman_chip_labels(ed, labels); + float rects[LM_MAX_CHIPS][4]; + libman_chip_layout(ed, rects); + for (int i = 0; i < n; i++) + if (in_rect(mx, my, rects[i][0], rects[i][1], rects[i][2], rects[i][3])) { + ed->libman_filter = i - 1; + ed->libman_scroll = 0; + ed->libman_search_focus = false; + return; + } + ed->libman_search_focus = false; + return; + } + ed->libman_search_focus = false; + if (mx < LM_MARGIN || mx >= WIN_W - LM_MARGIN) return; + int hits[TBLM_MAX_ENTRIES]; + int nh = tb_libman_search(ed->libman_query, libman_filter_name(ed), hits, TBLM_MAX_ENTRIES); + for (int k = 0; k < nh; k++) { + int col = k % 2, row = k / 2; + float x = LM_MARGIN + col*(LM_CARD_W + LM_CARD_GAP); + float y = gridY + 8 + row*(LM_CARD_H + LM_CARD_GAP) - ed->libman_scroll; + if (y + LM_CARD_H < gridY || y > WIN_H) continue; + if (in_rect(mx, my, x, y, LM_CARD_W, LM_CARD_H)) { + const TbLibmanEntry* e = tb_libman_entry(hits[k]); + if (e && e->shared[0]) hotlib_load(ed, e->shared); + else { snprintf(ed->hot_status, sizeof(ed->hot_status), + "%s: caminho do .so indisponivel", e ? e->name : "?"); + ed->hot_status_ok = false; } + libman_close(ed); + return; + } + } +} + +static void libman_key(Ed* ed, int sc) { + if (sc == TB_KEY_ESCAPE) { libman_close(ed); return; } + if (sc == TB_KEY_BACKSPACE && ed->libman_search_focus) { + if (ed->libman_query[0]) { + utf8_pop(ed->libman_query); + ed->libman_query_len = (int)strlen(ed->libman_query); + } + } +} + +static void libman_text(Ed* ed, const char* typed) { + if (!ed->libman_search_focus) return; + append_text(ed->libman_query, sizeof(ed->libman_query), typed); + ed->libman_query_len = (int)strlen(ed->libman_query); +} + +static void libman_scroll_by(Ed* ed, float dy) { + ed->libman_scroll -= (int)(dy * 48.f); + int hits[TBLM_MAX_ENTRIES]; + int nh = tb_libman_search(ed->libman_query, libman_filter_name(ed), hits, TBLM_MAX_ENTRIES); + int rows = (nh + 1) / 2; + float gridY = libman_grid_y(ed); + int content = rows * (LM_CARD_H + LM_CARD_GAP) + 16; + int visible = (int)(WIN_H - gridY); + int maxs = content - visible; + if (maxs < 0) maxs = 0; + if (ed->libman_scroll > maxs) ed->libman_scroll = maxs; + if (ed->libman_scroll < 0) ed->libman_scroll = 0; +} + /* === * Arrastar e encaixar * === */ @@ -3038,6 +3207,7 @@ static bool hit_lib_btn(float mx, float my) { return in_rect(mx, my, LIB_BT static bool hit_open_btn(float mx, float my) { return in_rect(mx, my, OPEN_BTN_X, 0, OPEN_BTN_W, MENU_H); } static bool hit_save_btn(float mx, float my) { return in_rect(mx, my, SAVE_BTN_X, 0, SAVE_BTN_W, MENU_H); } static bool hit_export_btn(float mx, float my) { return in_rect(mx, my, EXP_BTN_X, 0, EXP_BTN_W, MENU_H); } +static bool hit_libman_btn(float mx, float my) { return in_rect(mx, my, LIBM_BTN_X, 0, LIBM_BTN_W, MENU_H); } static void start_path(Ed* ed, int mode, const char* def) { ed->path_input_active = true; @@ -3131,6 +3301,7 @@ static void ctx_exec(Ed* ed, int id) { } static void on_lmb_down(Ed* ed, float mx, float my) { + if (ed->libman_open) { libman_click(ed, mx, my); return; } if (ed->comp_dialog_open) { dlg_click(ed, mx, my); return; } if (ed->ctx_menu_open) { int it = ctx_hit(ed, mx, my); @@ -3147,6 +3318,7 @@ static void on_lmb_down(Ed* ed, float mx, float my) { if (hit_lib_btn(mx, my)) start_path(ed, PM_LIB, ""); else if (hit_open_btn(mx, my)) start_path(ed, PM_LOAD, "projeto.json"); else if (hit_save_btn(mx, my)) start_path(ed, PM_SAVE, "projeto.json"); + else if (hit_libman_btn(mx, my)) libman_show(ed); else if (hit_export_btn(mx, my)) { ed->ctx_n = 0; ed->ctx_items[ed->ctx_n++] = CM_EXP_JSON; @@ -3281,6 +3453,7 @@ static void on_rmb_down(Ed* ed, float mx, float my) { static void on_key(Ed* ed, int sc, bool ctrl) { bool enter = sc == TB_KEY_RETURN; + if (ed->libman_open) { libman_key(ed, sc); return; } if (ed->comp_dialog_open) { dlg_key(ed, sc); return; } if (ed->ctx_menu_open) { if (sc == TB_KEY_ESCAPE) ed->ctx_menu_open = false; return; } @@ -3314,6 +3487,10 @@ static void on_key(Ed* ed, int sc, bool ctrl) { else if (sc == TB_KEY_BACKSPACE) utf8_pop(t); return; } + if (ctrl && sc == (TB_KEY_A + ('l' - 'a'))) { + libman_show(ed); + return; + } if (ctrl && sc == (TB_KEY_A + ('o' - 'a'))) { start_path(ed, PM_LIB, ""); return; @@ -3330,6 +3507,7 @@ static void on_key(Ed* ed, int sc, bool ctrl) { } static void on_text(Ed* ed, const char* typed) { + if (ed->libman_open) { libman_text(ed, typed); return; } if (ed->comp_dialog_open) { dlg_text(ed, typed); return; } if (ed->path_input_active) { append_text(ed->path_input_buf, sizeof(ed->path_input_buf), typed); @@ -3391,7 +3569,9 @@ static void editor_eval(TinyBlocks_Block* self, TinyBlocks* rt) { double sdx = ev_real(evb, GFX_IN_SCROLL_DX); double sdy = ev_real(evb, GFX_IN_SCROLL_DY); if (sdx != 0.0 || sdy != 0.0) { - if (mx >= WS_X && mx < WIN_W - STAGE_W && my >= WS_Y) { + if (ed->libman_open) { + libman_scroll_by(ed, (float)sdy); + } else if (mx >= WS_X && mx < WIN_W - STAGE_W && my >= WS_Y) { CT.ws_sx -= (float)sdx * 40.f; CT.ws_sy -= (float)sdy * 40.f; } else if (mx < PALETTE_W && my >= PAL_Y) { @@ -3454,6 +3634,7 @@ static bool editor_on_draw(TinyBlocks_Block* self, TinyBlocks* rt, render_ctx_menu(ed, rb); dlg_render(ed, rb); + libman_render(ed, rb); /* tela cheia: por cima de tudo */ *dst = rb; return true; @@ -3526,6 +3707,8 @@ static bool editor_instance_init(TinyBlocks_Block* self, TinyBlocks* rt) { if (t_stage) ed->stage = tb_block_create(rt, t_stage); palette_rebuild(ed); + tb_libman_init(rt); /* liga tinyblocks-api e adota as libs embutidas */ + tb_libman_scan_defaults(); /* procura library.toml em libraries/ e ~/.tinyblocks */ for (int i = 0; i < s_preload_n; i++) hotlib_load(ed, s_preload[i]); s_preload_n = 0; seed_example(ed); @@ -3541,6 +3724,7 @@ static void editor_instance_deinit(TinyBlocks_Block* self, TinyBlocks* rt) { * aqui só soltamos o que é do editor. */ free(ed->run_blocks); for (int u = 0; u < ed->user_block_n; u++) free(ed->user_blocks[u].snap); + tb_libman_shutdown(); if (g_active_ed == ed) g_active_ed = NULL; free(ed); *(Ed**)self->userdata = NULL; diff --git a/libraries/tinyblocks-libman/Makefile b/libraries/tinyblocks-libman/Makefile new file mode 100644 index 0000000..522bf38 --- /dev/null +++ b/libraries/tinyblocks-libman/Makefile @@ -0,0 +1,31 @@ +# Makefile da library libman (gestor/buscador de libraries) +# Constroi build/libtinyblocks-libman.a e build/libtinyblocks-libman.so +CC := gcc +BUILD := build + +CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \ + -D_POSIX_C_SOURCE=200809L -I../../include -Iinclude \ + -I../tinyblocks-toml/include -I../tinyblocks-api/include + +OBJ := $(BUILD)/tb_libman.o +LIB_A := $(BUILD)/libtinyblocks-libman.a +LIB_SO := $(BUILD)/libtinyblocks-libman.so + +.PHONY: all static shared clean +all: static shared +static: $(LIB_A) +shared: $(LIB_SO) + +$(OBJ): src/tb_libman.c include/tb_libman.h \ + ../tinyblocks-toml/include/tb_toml.h ../tinyblocks-api/include/tb_api.h + @mkdir -p $(BUILD) + $(CC) $(CFLAGS) -fPIC -c $< -o $@ + +$(LIB_A): $(OBJ) + ar rcs $@ $^ + +$(LIB_SO): $(OBJ) + $(CC) -shared -o $@ $^ + +clean: + $(RM) -r $(BUILD) diff --git a/libraries/tinyblocks-libman/include/tb_libman.h b/libraries/tinyblocks-libman/include/tb_libman.h new file mode 100644 index 0000000..4eaca00 --- /dev/null +++ b/libraries/tinyblocks-libman/include/tb_libman.h @@ -0,0 +1,73 @@ +/* + * TinyBlocks - tb_libman.h + * Library tinyblocks-libman: gestor/buscador de libraries. + * + * Varre diretorios em busca de arquivos "library.toml", le os metadados + * (usando tinyblocks-toml) e resolve os caminhos dos .so/.a. Sabe tambem + * se uma library ja esta carregada, consultando tinyblocks-api. + * + * NAO desenha UI: o editor e quem desenha a tela de escolha de extensao. + */ +#ifndef TINYBLOCKS_LIBMAN_H +#define TINYBLOCKS_LIBMAN_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define TBLM_MAX_ENTRIES 128 +#define TBLM_NAME_LEN 64 +#define TBLM_DESC_LEN 200 +#define TBLM_PATH_LEN 512 + +typedef struct TbLibmanEntry { + char name[TBLM_NAME_LEN]; + char version[24]; + char category[48]; + char description[TBLM_DESC_LEN]; + unsigned char color[4]; + unsigned char dark[4]; + char toml[TBLM_PATH_LEN]; /* caminho do library.toml */ + char dir[TBLM_PATH_LEN]; /* diretorio da library */ + char shared[TBLM_PATH_LEN]; /* caminho do .so (pode nao existir) */ + char staticlib[TBLM_PATH_LEN]; /* caminho do .a */ + char depends[160]; +} TbLibmanEntry; + +/* -- Ciclo de vida --- */ +TB_API bool tb_libman_init(TinyBlocks* rt); /* liga ao tinyblocks-api */ +TB_API void tb_libman_shutdown(void); +TB_API const char* tb_libman_last_error(void); + +/* -- Varredura --- */ +TB_API void tb_libman_clear(void); +/* Varre 'root' recursivamente (ate max_depth niveis) procurando library.toml. */ +TB_API int tb_libman_scan(const char* root, int max_depth); +/* Varre os diretorios padrao: "libraries", "./libraries" e + * "$HOME/.tinyblocks/libraries". */ +TB_API int tb_libman_scan_defaults(void); + +TB_API int tb_libman_count(void); +TB_API const TbLibmanEntry* tb_libman_entry(int i); + +/* -- Estado / instalacao (via tinyblocks-api) --- */ +TB_API bool tb_libman_loaded(int i); +TB_API int tb_libman_install(int i); /* tb_api_load(entry->shared) */ + +/* -- Filtros --- */ +/* Preenche out[] com os indices cujo nome/categoria/descricao contem 'query' + * (case-insensitive) e cuja categoria casa com 'category' (NULL ou "" = todas). + * Retorna quantos indices foram escritos (ate 'max'). */ +TB_API int tb_libman_search(const char* query, const char* category, + int* out, int max); +/* Categorias distintas encontradas (sem repeticao). Retorna n. */ +TB_API int tb_libman_categories(char out[][48], int max); + +#ifdef __cplusplus +} +#endif + +#endif /* TINYBLOCKS_LIBMAN_H */ diff --git a/libraries/tinyblocks-libman/library.toml b/libraries/tinyblocks-libman/library.toml new file mode 100644 index 0000000..9c32a85 --- /dev/null +++ b/libraries/tinyblocks-libman/library.toml @@ -0,0 +1,15 @@ +# Metadados da library libman (gestor/buscador de libraries). +[library] +name = "tinyblocks-libman" +version = "1.0.0" +category = "Bibliotecas" +description = "Procura e carrega libraries por library.toml" +color = [255, 87, 34, 255] +dark = [216, 67, 21, 255] + +[build] +sources = ["src/tb_libman.c"] +includes = ["include"] +shared = "build/libtinyblocks-libman.so" +static = "build/libtinyblocks-libman.a" +depends = ["tinyblocks-toml", "tinyblocks-api"] diff --git a/libraries/tinyblocks-libman/src/tb_libman.c b/libraries/tinyblocks-libman/src/tb_libman.c new file mode 100644 index 0000000..0a706f5 --- /dev/null +++ b/libraries/tinyblocks-libman/src/tb_libman.c @@ -0,0 +1,188 @@ +/* + * TinyBlocks - tb_libman.c + * Gestor/buscador de libraries: varre library.toml, le metadados com + * tinyblocks-toml e consulta o estado de carga em tinyblocks-api. + */ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include +#include +#include + +#include +#include "tb_libman.h" +#include "tb_api.h" +#include "tb_toml.h" /* interface publica do parser TOML */ + +static TbLibmanEntry s_e[TBLM_MAX_ENTRIES]; +static int s_n = 0; +static char s_err[400]; +static TinyBlocks* s_rt = NULL; + +static void copy_str(char* dst, size_t cap, const char* s) { + snprintf(dst, cap, "%s", s ? s : ""); +} + +static void resolve(char* dst, size_t cap, const char* dir, const char* rel) { + if (!rel || !rel[0]) { dst[0] = 0; return; } + if (rel[0] == '/') snprintf(dst, cap, "%s", rel); + else snprintf(dst, cap, "%s/%s", dir, rel); +} + +static bool already(const char* tomlpath) { + for (int i = 0; i < s_n; i++) + if (strcmp(s_e[i].toml, tomlpath) == 0) return true; + return false; +} + +static void entry_from_toml(const char* tomlpath, const char* dir) { + TbTomlDoc* doc = tb_toml_open(tomlpath); + if (!doc) { + snprintf(s_err, sizeof(s_err), "toml: falha ao abrir %s", tomlpath); + return; + } + TbLibmanEntry* e = &s_e[s_n]; + memset(e, 0, sizeof(*e)); + + copy_str(e->name, sizeof(e->name), tb_toml_str(doc, "library.name", "")); + if (!e->name[0]) { tb_toml_close(doc); return; } /* sem nome: ignora */ + + copy_str(e->version, sizeof(e->version), tb_toml_str(doc, "library.version", "")); + copy_str(e->category, sizeof(e->category), tb_toml_str(doc, "library.category", "")); + copy_str(e->description, sizeof(e->description), + tb_toml_str(doc, "library.description", "")); + copy_str(e->depends, sizeof(e->depends), tb_toml_str(doc, "build.depends", "")); + + int col[4]; + tb_toml_int_array(doc, "library.color", col, 4, 255); + for (int i = 0; i < 4; i++) e->color[i] = (unsigned char)col[i]; + tb_toml_int_array(doc, "library.dark", col, 4, 255); + for (int i = 0; i < 4; i++) e->dark[i] = (unsigned char)col[i]; + + copy_str(e->toml, sizeof(e->toml), tomlpath); + copy_str(e->dir, sizeof(e->dir), dir); + resolve(e->shared, sizeof(e->shared), dir, tb_toml_str(doc, "build.shared", "")); + resolve(e->staticlib, sizeof(e->staticlib), dir, tb_toml_str(doc, "build.static", "")); + + tb_toml_close(doc); + s_n++; +} + +static int scan_dir(const char* root, int depth) { + DIR* d = opendir(root); + if (!d) return 0; + int added = 0; + struct dirent* de; + while ((de = readdir(d))) { + if (de->d_name[0] == '.') continue; + if (strcmp(de->d_name, "build") == 0) continue; + char path[TBLM_PATH_LEN]; + snprintf(path, sizeof(path), "%s/%s", root, de->d_name); + struct stat st; + if (stat(path, &st) != 0) continue; + if (S_ISDIR(st.st_mode)) { + if (depth > 0) added += scan_dir(path, depth - 1); + } else if (strcmp(de->d_name, "library.toml") == 0) { + if (s_n < TBLM_MAX_ENTRIES && !already(path)) { + int before = s_n; + entry_from_toml(path, root); + if (s_n > before) added++; + } + } + } + closedir(d); + return added; +} + +bool tb_libman_init(TinyBlocks* rt) { + s_rt = rt; + s_n = 0; + s_err[0] = 0; + if (!tb_api_init(rt)) return false; + tb_api_adopt_all(); /* conta as libraries embutidas ja registradas */ + return true; +} + +void tb_libman_shutdown(void) { + s_n = 0; + tb_api_shutdown(); +} + +const char* tb_libman_last_error(void) { return s_err; } + +void tb_libman_clear(void) { s_n = 0; } +int tb_libman_count(void) { return s_n; } + +const TbLibmanEntry* tb_libman_entry(int i) { + return (i >= 0 && i < s_n) ? &s_e[i] : NULL; +} + +int tb_libman_scan(const char* root, int max_depth) { + if (!root || !root[0]) return 0; + return scan_dir(root, max_depth); +} + +int tb_libman_scan_defaults(void) { + int n = 0; + n += tb_libman_scan("libraries", 3); + const char* home = getenv("HOME"); + if (home && home[0]) { + char buf[TBLM_PATH_LEN]; + snprintf(buf, sizeof(buf), "%s/.tinyblocks/libraries", home); + n += tb_libman_scan(buf, 3); + } + return n; +} + +bool tb_libman_loaded(int i) { + if (i < 0 || i >= s_n) return false; + return tb_api_is_loaded(s_e[i].name); +} + +int tb_libman_install(int i) { + if (i < 0 || i >= s_n) return -1; + int r = tb_api_load(s_e[i].shared); + snprintf(s_err, sizeof(s_err), "%s", r < 0 ? tb_api_last_error() : ""); + return r; +} + +static bool contains_ci(const char* hay, const char* needle) { + if (!needle || !needle[0]) return true; + if (!hay) return false; + for (; *hay; hay++) { + const char* h = hay; + const char* n = needle; + while (*h && *n && tolower((unsigned char)*h) == tolower((unsigned char)*n)) { h++; n++; } + if (!*n) return true; + } + return false; +} + +int tb_libman_search(const char* query, const char* category, + int* out, int max) { + int n = 0; + bool allcat = !category || !category[0] || strcmp(category, "Tudo") == 0; + for (int i = 0; i < s_n && n < max; i++) { + const TbLibmanEntry* e = &s_e[i]; + if (!allcat && strcmp(e->category, category) != 0) continue; + if (!contains_ci(e->name, query) && + !contains_ci(e->category, query) && + !contains_ci(e->description, query)) continue; + out[n++] = i; + } + return n; +} + +int tb_libman_categories(char out[][48], int max) { + int n = 0; + for (int i = 0; i < s_n && n < max; i++) { + const char* c = s_e[i].category; + if (!c[0]) continue; + bool dup = false; + for (int j = 0; j < n; j++) if (strcmp(out[j], c) == 0) { dup = true; break; } + if (!dup) snprintf(out[n++], 48, "%s", c); + } + return n; +} diff --git a/libraries/tinyblocks-toml/include/ast.h b/libraries/tinyblocks-toml/include/ast.h index 2dacc94..83a9c28 100644 --- a/libraries/tinyblocks-toml/include/ast.h +++ b/libraries/tinyblocks-toml/include/ast.h @@ -45,7 +45,7 @@ struct TomlValue { } as; }; -typedef struct { +typedef struct TomlDoc { TomlValue* root; /* tabela raiz */ } TomlDoc; diff --git a/libraries/tinyblocks-toml/include/tb_toml.h b/libraries/tinyblocks-toml/include/tb_toml.h index 2063ed5..a28b1c7 100644 --- a/libraries/tinyblocks-toml/include/tb_toml.h +++ b/libraries/tinyblocks-toml/include/tb_toml.h @@ -7,19 +7,33 @@ #define TINYBLOCKS_TOML_H #include -#include "lexeme.h" -#include "ast.h" #ifdef __cplusplus extern "C" { #endif +/* Documento TOML opaco: consumidores NAO acessam os campos internos. + * (a definicao concreta fica em ast.h, interno a tinyblocks-toml) */ +typedef struct TomlDoc TbTomlDoc; + TB_API const TinyBlocks_LibraryDescriptor* tb_toml_get_library(void); /* Le um valor escalar de um arquivo .toml (ex.: "library.category"). * Retorna o valor em 'out' ou o default. Util para metadados de library. */ TB_API const char* tb_toml_file_get(const char* path, const char* dotted, const char* def); +/* -- Documento via interface publica (encapsula ast.h) --- */ +TB_API TbTomlDoc* tb_toml_open(const char* path); /* NULL em erro */ +TB_API void tb_toml_close(TbTomlDoc* doc); +/* Le um escalar em 'dotted' (ex.: "library.name"). Retorna def se ausente. */ +TB_API const char* tb_toml_str(const TbTomlDoc* doc, const char* dotted, const char* def); +/* Le um inteiro. */ +TB_API long long tb_toml_int(const TbTomlDoc* doc, const char* dotted, long long def); +/* Le um array de inteiros; preenche 'max' itens (ausentes = def) e retorna + * quantos itens o array tinha (limitado a max). */ +TB_API int tb_toml_int_array(const TbTomlDoc* doc, const char* dotted, + int* out, int max, int def); + #ifdef __cplusplus } #endif diff --git a/libraries/tinyblocks-toml/src/tb_toml.c b/libraries/tinyblocks-toml/src/tb_toml.c index 33e55ea..f61920e 100644 --- a/libraries/tinyblocks-toml/src/tb_toml.c +++ b/libraries/tinyblocks-toml/src/tb_toml.c @@ -8,6 +8,8 @@ #include #include "tb_toml.h" +#include "ast.h" /* interno a tinyblocks-toml */ +#include "lexeme.h" #define CAT_COLOR 0.62f, 0.44f, 0.86f, 1.f #define CAT_DARK 0.49f, 0.33f, 0.70f, 1.f @@ -76,3 +78,44 @@ const char* tb_toml_file_get(const char* path, const char* dotted, const char* d toml_free(doc); return buf; } + +/* -- Documento via interface publica (opaca) --- */ +TbTomlDoc* tb_toml_open(const char* path) { + TomlLexError err; + return (TbTomlDoc*)toml_parse_file(path, &err); +} + +void tb_toml_close(TbTomlDoc* doc) { + toml_free((TomlDoc*)doc); +} + +const char* tb_toml_str(const TbTomlDoc* doc, const char* dotted, const char* def) { + static char buf[256]; + if (!doc) return def; + const TomlValue* v = toml_path_get(((const TomlDoc*)doc)->root, dotted); + if (!v) return def; + value_to_text(v, buf, sizeof(buf)); + return buf; +} + +long long tb_toml_int(const TbTomlDoc* doc, const char* dotted, long long def) { + if (!doc) return def; + const TomlValue* v = toml_path_get(((const TomlDoc*)doc)->root, dotted); + return v ? toml_as_int(v, def) : def; +} + +int tb_toml_int_array(const TbTomlDoc* doc, const char* dotted, + int* out, int max, int def) { + for (int i = 0; i < max; i++) out[i] = def; + if (!doc) return 0; + const TomlValue* v = toml_path_get(((const TomlDoc*)doc)->root, dotted); + if (!v || v->kind != TOML_ARRAY) return 0; + size_t cnt = toml_array_count(v); + int n = 0; + for (int i = 0; i < max && (size_t)i < cnt; i++) { + const TomlValue* it = toml_array_get(v, (size_t)i); + if (it) out[i] = (int)toml_as_int(it, def); + n++; + } + return n; +} diff --git a/src/tb_library_block.c b/src/tb_library_block.c index 2ea7107..41200cd 100644 --- a/src/tb_library_block.c +++ b/src/tb_library_block.c @@ -124,6 +124,19 @@ TinyBlocks_Block* tb_library_find(TinyBlocks_LibraryBlock* lib, const char* name return NULL; } +/* == Acesso publico aos metadados === */ +const char* tb_library_name(const TinyBlocks_LibraryBlock* lib) { + return lib ? lib->base.name : NULL; +} + +const TinyBlocks_Category* tb_library_category(const TinyBlocks_LibraryBlock* lib) { + return lib ? lib->category : NULL; +} + +uint32_t tb_library_block_count(const TinyBlocks_LibraryBlock* lib) { + return lib ? lib->block_count : 0; +} + /* == Carregamento dinâmico === */ TinyBlocks_LibraryBlock* tb_library_load(TinyBlocks* rt, const char* path) { diff --git a/src/tinyblocks.c b/src/tinyblocks.c index 0646e7a..49e25f9 100644 --- a/src/tinyblocks.c +++ b/src/tinyblocks.c @@ -227,6 +227,16 @@ TinyBlocks_LibraryBlock* tb_rt_find_library(TinyBlocks* rt, const char* name) return NULL; } +/* -- Enumeracao publica (esconde o layout de TinyBlocks) --- */ +uint32_t tb_rt_type_count(const TinyBlocks* rt) { return rt ? rt->type_count : 0; } +TinyBlocks_TypeBlock* tb_rt_type_at(const TinyBlocks* rt, uint32_t i) { + return (rt && i < rt->type_count) ? rt->types[i] : NULL; +} +uint32_t tb_rt_library_count(const TinyBlocks* rt) { return rt ? rt->library_count : 0; } +TinyBlocks_LibraryBlock* tb_rt_library_at(const TinyBlocks* rt, uint32_t i) { + return (rt && i < rt->library_count) ? rt->libraries[i] : NULL; +} + /* -- Erros --- */ const char* tinyblocks_last_error(TinyBlocks* rt) { return rt->error; } void tinyblocks_clear_error(TinyBlocks* rt) { rt->error[0] = '\0'; } diff --git a/tests/editor_harness.c b/tests/editor_harness.c index 8c871ec..30f2008 100644 --- a/tests/editor_harness.c +++ b/tests/editor_harness.c @@ -363,6 +363,20 @@ int main(void) { { float a, b; for (int k = 0; find("apague tudo", R_WS, k, &a, &b); k++) clear_after++; } CHECK(clear_after == clear_before + 1, "arrastar bloco da Caneta para o chapeu"); + /* 16. Gestor de libraries (tinyblocks-libman), UI desenhada pelo editor */ + CHECK(!find("Blueprint", R_CAT, 0, &x, &y), "categoria Blueprint ainda nao existe"); + if (need("Bibliotecas", R_WS, 0, &x, &y)) click(x, y); + frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(find("Escolha uma Extensão", R_ANY, 0, &x, &y), "abre a tela do libman"); + CHECK(find("Buscar", R_ANY, 0, &x, &y), "libman mostra o campo de busca"); + type("blueprint"); + frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(find("tinyblocks-blueprint", R_ANY, 0, &x, &y), "busca filtra por nome"); + if (need("tinyblocks-blueprint", R_ANY, 0, &x, &y)) click(x, y); + frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(!find("Escolha uma Extensão", R_ANY, 0, &x, &y), "libman fecha apos carregar"); + CHECK(find("Blueprint", R_CAT, 0, &x, &y), "library carregada aparece na paleta"); + printf("comandos de desenho no último frame: %u\n", ncmd); tinyblocks_deinit(&rt); printf(fails ? "\n%d FALHA(S)\n" : "\nTUDO OK\n", fails); diff --git a/tests/libman_test.c b/tests/libman_test.c new file mode 100644 index 0000000..d6fb1fb --- /dev/null +++ b/tests/libman_test.c @@ -0,0 +1,83 @@ +/* + * libman_test.c - testa tinyblocks-libman + tinyblocks-api: + * varredura de library.toml, leitura de metadados, busca, categorias, + * estado de carga e introspeccao de tipos. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int fails = 0; +#define CHECK(c, m) do { if (c) printf("ok %s\n", m); else { printf("FAIL %s\n", m); fails++; } } while (0) + +int main(void) { + TinyBlocks* rt; + tinyblocks_init(&rt, NULL); + 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_fs_get_library()); + tb_library_register(rt, tb_toml_get_library()); + + CHECK(tb_libman_init(rt), "libman init (liga a api)"); + + int n = tb_libman_scan_defaults(); + printf(" libraries encontradas: %d (%d novas)\n", tb_libman_count(), n); + CHECK(tb_libman_count() >= 12, "varredura encontra as libraries do repo"); + + int ev = -1, tm = -1, bp = -1; + for (int i = 0; i < tb_libman_count(); i++) { + const TbLibmanEntry* e = tb_libman_entry(i); + if (strcmp(e->name, "tinyblocks-events") == 0) ev = i; + if (strcmp(e->name, "tinyblocks-toml") == 0) tm = i; + if (strcmp(e->name, "tinyblocks-blueprint") == 0) bp = i; + } + CHECK(ev >= 0, "encontra tinyblocks-events"); + CHECK(tm >= 0, "encontra tinyblocks-toml"); + CHECK(bp >= 0, "encontra tinyblocks-blueprint"); + + if (ev >= 0) { + const TbLibmanEntry* e = tb_libman_entry(ev); + CHECK(strcmp(e->category, "Eventos") == 0, "categoria lida do .toml"); + CHECK(strstr(e->shared, ".so") != NULL, "caminho do .so resolvido"); + CHECK(e->color[0] == 255 && e->color[1] == 191 && e->color[2] == 0, + "cor lida do array .toml"); + CHECK(tb_libman_loaded(ev), "events embutida consta como carregada"); + } + if (bp >= 0) + CHECK(!tb_libman_loaded(bp), "blueprint (nao registrada) consta como nao carregada"); + + int hits[TBLM_MAX_ENTRIES]; + int h = tb_libman_search("toml", "", hits, TBLM_MAX_ENTRIES); + CHECK(h >= 1, "busca por 'toml' retorna resultado"); + h = tb_libman_search("", "Eventos", hits, TBLM_MAX_ENTRIES); + CHECK(h == 1, "filtro por categoria Eventos retorna 1"); + + char cats[32][48]; + int cn = tb_libman_categories(cats, 32); + int has_ev = 0; + for (int i = 0; i < cn; i++) if (strcmp(cats[i], "Eventos") == 0) has_ev = 1; + CHECK(cn >= 5 && has_ev, "categorias distintas incluem Eventos"); + + /* tinyblocks-api: introspeccao de tipos */ + CHECK(tb_api_type_find("Events.WhenRun") != NULL, "api encontra Events.WhenRun"); + CHECK(tb_api_type_count() > 10, "api enumera os tipos registrados"); + + tb_libman_shutdown(); + tinyblocks_deinit(&rt); + printf(fails ? "\n%d FALHA(S)\n" : "\nTUDO OK\n", fails); + return fails != 0; +}