diff --git a/Makefile b/Makefile index 83df956..25a62ac 100644 --- a/Makefile +++ b/Makefile @@ -87,6 +87,7 @@ 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 +SYN_A := $(SYN_DIR)/build/libtinyblocks-syntax.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) @@ -265,6 +266,10 @@ graphics: static lib-sdl2 lib-graphics ## Interface gráfica (com backend SDL2) # -- Library Editor --- EDITOR_SRC := $(ED_DIR)/src +EW_DIR := $(ED_DIR)/libraries/tinyblocks-editor-widgets +EIMG_DIR := $(ED_DIR)/libraries/tinyblocks-editor-image +EW_A := $(EW_DIR)/build/libtinyblocks-editor-widgets.a +EIMG_A := $(EIMG_DIR)/build/libtinyblocks-editor-image.a EDITOR_HDRS := $(EDITOR_SRC)/tb_stage_widget.h $(ED_DIR)/include/tb_editor.h $(GFX_HDR) $(HDRS) $(BUILD)/editor: examples/editor/main.c static libs @@ -272,9 +277,9 @@ $(BUILD)/editor: examples/editor/main.c static libs -I$(ED_DIR)/include -I$(GFX_INC) $(CAT_INCS) \ -I$(FS_DIR)/include -I$(EN_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 \ + -I$(API_DIR)/include -I$(LIBM_DIR)/include -I$(SYN_DIR)/include \ $< -o $@ \ - -Wl,--start-group $(ED_A) $(GX_A) $(SD_A) $(TOML_A) $(JSON_A) $(XML_A) $(CSV_A) $(BP_A) $(API_A) $(LIBM_A) $(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) $(SYN_A) $(CAT_A) $(LIB_A) -Wl,--end-group \ $(SDL2_LIBS) $(SDL2TTF_LIBS) -ldl -lm -rdynamic \ '-Wl,-rpath,$$ORIGIN' @@ -330,6 +335,10 @@ appdir: editor ## Monta o AppDir (build/TinyBlocks.AppDir) para o AppImage for ex in $(APPIMAGE_EXCLUDE); do case "$$name" in $$ex*) skip=1;; esac; done; \ [ $$skip -eq 0 ] && cp -L "$$path" $(APPDIR)/usr/lib/ 2>/dev/null || true; \ done + @echo "Empacotando as libraries privadas do editor (bundle, hot reload)..." + @mkdir -p $(APPDIR)/usr/lib/tinyblocks-editor + @cp $(EW_DIR)/build/libtinyblocks-editor-widgets.so $(APPDIR)/usr/lib/tinyblocks-editor/ 2>/dev/null || true + @cp $(EIMG_DIR)/build/libtinyblocks-editor-image.so $(APPDIR)/usr/lib/tinyblocks-editor/ 2>/dev/null || true @echo "Empacotando libraries de extensao (.so + library.toml)..." @mkdir -p $(APPDIR)/usr/share/tinyblocks/libraries @for l in $(APPIMAGE_LIBS); do \ @@ -417,22 +426,29 @@ $(BUILD)/mcp.so: examples/mcp/mcp.c static lib-mcp mcp-lib: static lib-mcp $(BUILD)/mcp.so ## Library cliente MCP -> build/mcp.so @echo "Build mcp OK: $(BUILD)/mcp.so" +ed-modules: ## Reconstroi so as libraries privadas do editor (hot reload) + $(MAKE) -C $(ED_DIR) + # ── 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 lib-blueprint + $(EDITOR_SRC)/tb_editor_modules.c \ + $(EW_DIR)/include/tb_editor_widgets.h \ + $(EIMG_DIR)/include/tb_editor_image.h \ + $(GX_DIR)/src/tb_graphics.c lib-blueprint ed-modules @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$(EN_DIR)/include -I$(TOML_DIR)/include -I$(CV_DIR)/include -I$(B64_DIR)/include -I$(PPM_DIR)/include \ + -I$(ED_DIR)/include -I$(EDITOR_SRC) -I$(ED_DIR)/internal -I$(EW_DIR)/include -I$(EIMG_DIR)/include -I$(GFX_INC) $(CAT_INCS) -I$(BP_DIR)/include \ + -I$(API_DIR)/include -I$(LIBM_DIR)/include -I$(EN_DIR)/include -I$(TOML_DIR)/include -I$(CV_DIR)/include -I$(B64_DIR)/include -I$(PPM_DIR)/include -I$(SYN_DIR)/include \ $(SRCS) \ $(EDITOR_SRC)/tb_editor.c $(EDITOR_SRC)/tb_stage_widget.c \ + $(EDITOR_SRC)/tb_editor_modules.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) \ - $(CV_DIR)/src/tb_curves.c $(B64_DIR)/src/tb_base64.c $(PPM_DIR)/src/tb_ppm.c tests/editor_harness.c -o $@ -ldl -lm -rdynamic + $(CV_DIR)/src/tb_curves.c $(B64_DIR)/src/tb_base64.c $(PPM_DIR)/src/tb_ppm.c $(SYN_DIR)/src/tb_syntax.c tests/editor_harness.c -o $@ -ldl -lm -rdynamic test-editor: $(BUILD)/editor_harness ## Roda o harness headless do editor (ASan/UBSan) ./$(BUILD)/editor_harness diff --git a/libraries/tinyblocks-api/include/tb_api.h b/libraries/tinyblocks-api/include/tb_api.h index 233c59b..111ff28 100644 --- a/libraries/tinyblocks-api/include/tb_api.h +++ b/libraries/tinyblocks-api/include/tb_api.h @@ -57,6 +57,28 @@ 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); +/* -- Modulos de codigo (bundle de um app, ex: libraries privadas do editor) + * Nao registram libraries/blocos: sao so codigo (.so) carregado por dlopen. + * Usados para HOT RELOAD: recompile a parte que mudou e o app recarrega. --- */ +#define TB_API_MAX_CODE 32 +TB_API int tb_api_code_load(const char* name, const char* path); /* idx ou -1 */ +TB_API bool tb_api_code_unload(const char* name); +TB_API void tb_api_code_unload_all(void); +TB_API int tb_api_code_count(void); +TB_API const char* tb_api_code_name(int i); +TB_API const char* tb_api_code_path(int i); +TB_API void* tb_api_code_handle(const char* name); +TB_API void* tb_api_code_symbol(const char* name, const char* symbol); +/* Recarrega TODOS os modulos de codigo na ordem de carga (unload inverso, + * load direto) - resolve dependencias entre eles. Retorna quantos voltaram. */ +TB_API int tb_api_code_reload_all(void); +/* true se algum modulo de codigo mudou no disco (usa watcher/mtime). */ +TB_API bool tb_api_code_changed(void); + +/* -- Watcher de arquivos (inotify quando disponivel, senao mtime) --- */ +TB_API bool tb_api_watch(const char* path); +TB_API int tb_api_poll_watch(void); /* eventos pendentes (0 = nada) */ + /* 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. */ diff --git a/libraries/tinyblocks-api/src/tb_api.c b/libraries/tinyblocks-api/src/tb_api.c index 99e3745..3cae7e3 100644 --- a/libraries/tinyblocks-api/src/tb_api.c +++ b/libraries/tinyblocks-api/src/tb_api.c @@ -7,9 +7,11 @@ #include #include #include +#include #ifdef __linux__ # include +# include #endif #include @@ -28,6 +30,230 @@ static time_t file_mtime(const char* p) { return (stat(p, &st) == 0) ? st.st_mtime : 0; } +static void set_err(const char* fmt, const char* a); +static void path_dirname(const char* p, char* out, size_t cap); + +static const char* path_basename(const char* p) { + const char* s = strrchr(p, '/'); + return s ? s + 1 : p; +} + +/* -- Modulos de codigo (bundle) e watcher de arquivos ------------------- */ + +typedef struct { + char name[64]; + char path[TB_API_PATH_LEN]; + void* handle; + time_t mtime; + bool dirty; +} TbApiCode; + +static TbApiCode s_code[TB_API_MAX_CODE]; +static int s_cn = 0; + +static int code_find(const char* name) { + if (!name) return -1; + for (int i = 0; i < s_cn; i++) if (strcmp(s_code[i].name, name) == 0) return i; + return -1; +} + +#ifdef __linux__ +# define TB_API_WATCH_MAX 64 +typedef struct { + int wd; + int idx; /* indice em s_code (-1 = so diretorio) */ + char base[128]; /* nome do arquivo vigiado */ + char dir[TB_API_PATH_LEN]; +} TbWatch; +static TbWatch s_watch[TB_API_WATCH_MAX]; +static int s_wn = 0; +static int s_inot = -1; + +/* Vigia o DIRETORIO do arquivo: cobre tanto escrita no lugar quanto + "make" (escreve num temp e renomeia por cima). */ +static int watch_add(const char* path) { + if (s_inot < 0) return -1; + char dir[TB_API_PATH_LEN]; + path_dirname(path, dir, sizeof(dir)); + if (s_wn > 0 && strcmp(s_watch[s_wn - 1].dir, dir) == 0) { + /* mesmo diretorio: reaproveita o wd */ + snprintf(s_watch[s_wn - 1].base, sizeof(s_watch[s_wn-1].base), "%s", path_basename(path)); + return s_watch[s_wn - 1].wd; + } + if (s_wn >= TB_API_WATCH_MAX) return -1; + int wd = inotify_add_watch(s_inot, dir, + IN_CLOSE_WRITE | IN_MOVED_TO | IN_CREATE | IN_ATTRIB); + if (wd < 0) return -1; + TbWatch* w = &s_watch[s_wn++]; + w->wd = wd; + w->idx = -1; + snprintf(w->dir, sizeof(w->dir), "%s", dir); + snprintf(w->base, sizeof(w->base), "%s", path_basename(path)); + return wd; +} +#endif + +bool tb_api_watch(const char* path) { + if (!path || !path[0]) return false; +#ifdef __linux__ + if (s_inot < 0) { + s_inot = inotify_init1(IN_NONBLOCK); + if (s_inot < 0) return false; + } + return watch_add(path) >= 0; +#else + (void)path; + return false; +#endif +} + +int tb_api_poll_watch(void) { +#ifdef __linux__ + if (s_inot < 0 || s_wn <= 0) return 0; + char buf[4096] __attribute__((aligned(8))); + ssize_t n; + int changed = 0; + while ((n = read(s_inot, buf, sizeof(buf))) > 0) { + for (char* p = buf; p < buf + n; ) { + struct inotify_event* ev = (struct inotify_event*)p; + p += sizeof(*ev) + ev->len; + if (!ev->len) continue; + for (int i = 0; i < s_cn; i++) { + if (strcmp(ev->name, path_basename(s_code[i].path)) != 0) continue; + char d[TB_API_PATH_LEN]; + path_dirname(s_code[i].path, d, sizeof(d)); + for (int k = 0; k < s_wn; k++) + if (s_watch[k].wd == ev->wd && strcmp(s_watch[k].dir, d) == 0) { + s_code[i].dirty = true; + changed++; + } + } + } + } + return changed; +#else + return 0; +#endif +} + +static void path_dirname(const char* p, char* out, size_t cap) { + snprintf(out, cap, "%s", p); + char* sl = strrchr(out, '/'); + if (sl) *sl = 0; else snprintf(out, cap, "."); +} + +static bool code_changed_mtime(void) { + bool any = false; + for (int i = 0; i < s_cn; i++) { + time_t mt = file_mtime(s_code[i].path); + if (mt && mt != s_code[i].mtime) { s_code[i].dirty = true; any = true; } + } + return any; +} + +int tb_api_code_load(const char* name, const char* path) { + if (!name || !name[0] || !path || !path[0]) { + set_err("%s", "tb_api: nome/caminho invalido"); + return -1; + } + int ex = code_find(name); + if (ex >= 0 && s_code[ex].handle && strcmp(s_code[ex].path, path) == 0) + return ex; + if (ex >= 0) tb_api_code_unload(name); + if (s_cn >= TB_API_MAX_CODE) { set_err("%s", "tb_api: limite de modulos de codigo"); return -1; } +#ifdef __linux__ + void* dl = dlopen(path, RTLD_NOW | RTLD_GLOBAL); + if (!dl) { set_err("dlopen: %s", dlerror()); return -1; } + TbApiCode* c = &s_code[s_cn]; + memset(c, 0, sizeof(*c)); + snprintf(c->name, sizeof(c->name), "%s", name); + snprintf(c->path, sizeof(c->path), "%s", path); + c->handle = dl; + c->mtime = file_mtime(path); + c->dirty = false; + /* watcher: registro por arquivo, apontando para o modulo */ + if (tb_api_watch(path)) { + for (int k = s_wn - 1; k >= 0; k--) { + if (strcmp(s_watch[k].base, path_basename(path)) == 0) { s_watch[k].idx = s_cn; break; } + } + } + s_err[0] = 0; + return s_cn++; +#else + (void)name; (void)path; + set_err("%s", "tb_api: dlopen nao suportado nesta plataforma"); + return -1; +#endif +} + +bool tb_api_code_unload(const char* name) { + int i = code_find(name); + if (i < 0) return false; +#ifdef __linux__ + if (s_code[i].handle) dlclose(s_code[i].handle); +#endif + for (int k = i; k < s_cn - 1; k++) s_code[k] = s_code[k + 1]; + s_cn--; + return true; +} + +void tb_api_code_unload_all(void) { + for (int i = s_cn - 1; i >= 0; i--) { +#ifdef __linux__ + if (s_code[i].handle) dlclose(s_code[i].handle); +#endif + s_code[i].handle = NULL; + } + s_cn = 0; +} + +int tb_api_code_count(void) { return s_cn; } +const char* tb_api_code_name(int i) { return (i >= 0 && i < s_cn) ? s_code[i].name : NULL; } +const char* tb_api_code_path(int i) { return (i >= 0 && i < s_cn) ? s_code[i].path : NULL; } + +void* tb_api_code_handle(const char* name) { + int i = code_find(name); + return i >= 0 ? s_code[i].handle : NULL; +} + +void* tb_api_code_symbol(const char* name, const char* symbol) { + void* h = tb_api_code_handle(name); +#ifdef __linux__ + if (!h || !symbol) return NULL; + return dlsym(h, symbol); +#else + (void)h; (void)symbol; + return NULL; +#endif +} + +int tb_api_code_reload_all(void) { + char names[TB_API_MAX_CODE][64]; + char paths[TB_API_MAX_CODE][TB_API_PATH_LEN]; + int n = s_cn; + for (int i = 0; i < n; i++) { + snprintf(names[i], sizeof(names[i]), "%s", s_code[i].name); + snprintf(paths[i], sizeof(paths[i]), "%s", s_code[i].path); + } + tb_api_code_unload_all(); /* ordem inversa de dependencia */ + int ok = 0; + for (int i = 0; i < n; i++) + if (tb_api_code_load(names[i], paths[i]) >= 0) ok++; + return ok; +} + +bool tb_api_code_changed(void) { + bool any = false; +#ifdef __linux__ + if (tb_api_poll_watch() > 0) any = true; +#endif + if (code_changed_mtime()) any = true; + if (!any) { + for (int i = 0; i < s_cn; i++) if (s_code[i].dirty) { any = true; break; } + } + return any; +} + static void set_err(const char* fmt, const char* a) { snprintf(s_err, sizeof(s_err), fmt, a ? a : ""); } @@ -53,6 +279,11 @@ bool tb_api_init(TinyBlocks* rt) { void tb_api_shutdown(void) { /* O runtime e o dono dos blocos; aqui so esquecemos os modulos. */ + tb_api_code_unload_all(); +#ifdef __linux__ + if (s_inot >= 0) { close(s_inot); s_inot = -1; } + s_wn = 0; +#endif s_n = 0; s_rt = NULL; } @@ -170,6 +401,9 @@ bool tb_api_any_changed(void) { int tb_api_poll_reload(void) { int n = 0; +#ifdef __linux__ + tb_api_poll_watch(); +#endif for (int i = 0; i < s_n; i++) { TbApiModule* m = &s_mods[i]; if (!m->path[0]) continue; diff --git a/libraries/tinyblocks-editor/Makefile b/libraries/tinyblocks-editor/Makefile index c637c9d..8c42573 100644 --- a/libraries/tinyblocks-editor/Makefile +++ b/libraries/tinyblocks-editor/Makefile @@ -13,9 +13,17 @@ CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \ -I../tinyblocks-blueprint/include \ -I../tinyblocks-environ/include \ -I../tinyblocks-api/include \ - -I../tinyblocks-libman/include + -I../tinyblocks-libman/include \ + -I../tinyblocks-syntax/include \ + -Ilibraries/tinyblocks-editor-widgets/include \ + -Ilibraries/tinyblocks-editor-image/include -OBJ := $(BUILD)/tb_editor.o $(BUILD)/tb_stage_widget.o +WIDGETS_DIR := libraries/tinyblocks-editor-widgets +WIDGETS_A := $(WIDGETS_DIR)/build/libtinyblocks-editor-widgets.a +IMG_DIR := libraries/tinyblocks-editor-image +IMG_A := $(IMG_DIR)/build/libtinyblocks-editor-image.a + +OBJ := $(BUILD)/tb_editor.o $(BUILD)/tb_stage_widget.o $(BUILD)/tb_editor_modules.o LIB_A := $(BUILD)/libtinyblocks-editor.a LIB_SO := $(BUILD)/libtinyblocks-editor.so @@ -24,13 +32,17 @@ all: static shared static: $(LIB_A) shared: $(LIB_SO) -$(BUILD)/tb_editor.o: src/tb_editor.c include/tb_editor.h src/tb_stage_widget.h \ +$(BUILD)/tb_editor.o: src/tb_editor.c include/tb_editor.h internal/tb_editor_internal.h \ + src/tb_stage_widget.h \ + $(WIDGETS_DIR)/include/tb_editor_widgets.h \ + $(IMG_DIR)/include/tb_editor_image.h \ ../tinyblocks-graphics/include/tb_graphics.h \ ../tinyblocks-variables/include/tb_variables.h \ ../tinyblocks-blueprint/include/tb_blueprint.h \ ../tinyblocks-environ/include/tb_environ.h \ ../tinyblocks-api/include/tb_api.h \ - ../tinyblocks-libman/include/tb_libman.h + ../tinyblocks-libman/include/tb_libman.h \ + ../tinyblocks-syntax/include/tb_syntax.h @mkdir -p $(BUILD) $(CC) $(CFLAGS) -fPIC -c $< -o $@ @@ -39,8 +51,23 @@ $(BUILD)/tb_stage_widget.o: src/tb_stage_widget.c src/tb_stage_widget.h \ @mkdir -p $(BUILD) $(CC) $(CFLAGS) -fPIC -c $< -o $@ -$(LIB_A): $(OBJ) - ar rcs $@ $^ +$(BUILD)/tb_editor_modules.o: src/tb_editor_modules.c internal/tb_editor_modules.h \ + internal/tb_editor_internal.h + @mkdir -p $(BUILD) + $(CC) $(CFLAGS) -fPIC -c $< -o $@ + +# Sempre delega para o make das libraries privadas (elas sabem o que mudou): +# assim o editor nunca fica com um modulo velho. +.PHONY: FORCE +FORCE: + +$(WIDGETS_A): FORCE + $(MAKE) -C $(WIDGETS_DIR) +$(IMG_A): FORCE + $(MAKE) -C $(IMG_DIR) + +$(LIB_A): $(OBJ) $(WIDGETS_A) $(IMG_A) + ar rcs $@ $(OBJ) $(LIB_SO): $(OBJ) $(CC) -shared -o $@ $^ -ldl diff --git a/libraries/tinyblocks-editor/internal/tb_editor_internal.h b/libraries/tinyblocks-editor/internal/tb_editor_internal.h new file mode 100644 index 0000000..e860398 --- /dev/null +++ b/libraries/tinyblocks-editor/internal/tb_editor_internal.h @@ -0,0 +1,704 @@ +/* + * TinyBlocks - tb_editor_internal.h + * Tipos, constantes de layout, tema e prototipos compartilhados entre o + * editor (tb_editor.c) e as libraries privadas do editor + * (libraries/tinyblocks-editor-*). Estas libraries sao um bundle privado: + * vem juntas com o editor e podem compartilhar este cabecalho. + */ +#ifndef TB_EDITOR_INTERNAL_H +#define TB_EDITOR_INTERNAL_H + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "../internal/tb_editor_modules.h" + +#ifndef TB_EW_UNUSED +#define TB_EW_UNUSED __attribute__((unused)) +#endif + +/* === + * Layout da janela + * + * ==== 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 +#define TAB_H 36 +#define CAT_W 68 +#define FLY_W 250 +#define FLY_PAD 12 +#define FLY_BTN_W 150 +#define PALETTE_W (CAT_W + FLY_W) +#define STAGE_W 360 +#define STAGE_BAR_H 44 +#define PAL_Y (MENU_H + TAB_H) +#define WS_X PALETTE_W +#define WS_Y (MENU_H + TAB_H) +#define WIN_W (ed->win_w) +#define WIN_H (ed->win_h) +#define WS_W (ed->win_w - PALETTE_W - STAGE_W) +#define WS_H (ed->win_h - WS_Y) +#define TAB_W 150 +#define PLUS_W 28 + +/* Menu do botao "+" (nova aba) */ +#define PLUS_MENU_W 208 +#define PLUS_MENU_ITEM_H 36 + +/* Editor de codigo (aba de codigo) */ +#define CODE_FS 13 +#define CODE_GUTTER_W 46 +#define CODE_LINE_H 18 +#define CODE_PAD_Y 6 +#define CODE_PAD_X 8 + +/* Tipos de aba */ +enum { TK_BLOCKS, TK_CODE, TK_IMAGE }; + +/* Aba de imagem: editor de pintura com camadas (visual estilo Scratch) */ +/* Medidas da aba de imagem ficam no modulo (tinyblocks-editor-image); + aqui so o que o estado (Tab) precisa. */ +#define IMG_UNDO_MAX 6 +#define IMG_MAX_LAYERS 8 + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +enum { IMG_L_RASTER = 0, IMG_L_VECTOR }; + +/* Camada do documento de imagem (rasterizada; SVG entra como vetor) */ +typedef struct { + TinyBlocks_Image* img; + TinyBlocks_Image* thumb; /* miniatura do painel "Camadas" */ + unsigned thumb_rev;/* revisao em que a miniatura foi feita */ + char name[48]; + char src[192]; + int kind; + int visible; +} ImgLayer; + +/* Selecao da ferramenta "selecionar" (mover/redimensionar pixels) */ +typedef struct { + int on; /* ha selecao ativa */ + TinyBlocks_Image* buf; /* pixels retirados da camada (flutuantes) */ + int ox, oy, ow, oh; /* regiao original (ancora do arrasto / tamanho) */ + int x, y, w, h; /* retangulo atual */ + int mode; /* 0 = nada, 1 = mover, 2 = redimensionar, 3 = novo */ + int hnd; /* indice da alca (0..8) */ + int px, py; /* ultimo ponto em coords da imagem */ +} ImgSel; + +enum { IT_SEL = 0, IT_BRUSH, IT_LINE, IT_RECT, IT_ELLIPSE, + IT_FILL, IT_ERASER, IT_PICK, IT_N }; + +/* Botoes de projeto no menu (geometria) */ +#define OPEN_BTN_X 150 +#define OPEN_BTN_W 64 +#define SAVE_BTN_X 218 +#define SAVE_BTN_W 70 +#define EXP_BTN_X 296 +#define EXP_BTN_W 84 +#define LIBM_BTN_X 388 +#define LIBM_BTN_W 104 +#define LIB_BTN_X 500 +#define LIB_BTN_W 200 + +/* Botao "Config" (settings) ancorado a direita do menu */ +#define CFG_BTN_W 78 +#define CFG_BTN_X (WIN_W - CFG_BTN_W - 10) + +/* Botao de buscar/adicionar library no fim da coluna de categorias */ +#define LIBMAN_BTN_H 56 + +/* == Geometria dos blocos === */ +#define FS 12 /* texto dos blocos */ +#define FS_UI 13 /* texto da interface */ +#define FS_SM 11 +#define BLK_GAP 5 /* espaço entre partes do rótulo */ +#define BLK_PAD 10 +#define ROW_MIN_STACK 36 +#define ROW_MIN_REP 24 +#define SLOT_MIN_H 20 +#define SLOT_MIN_W 28 +#define SLOT_LINE_H 15 +#define HAT_CAP 18 /* altura do "chapéu" acima da linha do rótulo */ +#define HAT_CAP_W 96 +#define ARM_W 16 /* braço esquerdo dos blocos C */ +#define BOT_H 22 /* braço inferior dos blocos C */ +#define MID_H 26 /* braço "senão" */ +#define MOUTH_MIN 22 +#define NOTCH_X 12 /* encaixe (macho) sob os comandos */ +#define NOTCH_W 18 +#define NOTCH_D 4 +#define PREVIEW_H 64 /* área de on_draw */ +#define PREVIEW_W 168 +#define SNAP_R 28.f + +#define MAX_WS 256 +#define MAX_INPUTS 16 +#define MAX_PARTS 40 +#define MAX_TABS 8 +#define MAX_FLY 192 +#define MAX_CATS 24 +#define MAX_CALL_DEPTH 32 +#define MAX_STEPS 500000L +#define MAX_RUN_BLOCKS 200000 +#define STAGE_BUF 16384 +#define LIT_TEXT_CAP 512 +#define MAX_HOT_TYPES 64 +#define MAX_USER_BLOCKS 16 +#define MAX_UBLK_SLOTS 8 +#define MAX_UBLK_PARTS 16 + +/* === + * Cores (paleta do Scratch 3) - componentes 0..1 + * === */ +/* Copia de string com limite (helper compartilhado, sem estado) */ +static inline void scopy(char* dst, size_t cap, const char* src) { + if (!dst || !cap) return; + if (!src) { dst[0] = 0; return; } + size_t n = strlen(src); + if (n >= cap) n = cap - 1; + memcpy(dst, src, n); + dst[n] = 0; +} + +/* Cores e primitivas de desenho vem da library privada + tinyblocks-editor-widgets (ver tb_editor_widgets.h). Aqui so mantemos os + nomes curtos usados no codigo do editor. */ +typedef TbEwColor Col; +#define C(r,g,b) TB_EW_RGB(r,g,b) +#define COLA(r,g,b,a) TB_EW_RGBA(r,g,b,a) +#define col_mul tb_ed_w.col_mul +/* O desenho do editor passa pela library privada widgets. Chamamos pela + tabela (tb_ed_w) para poder recarregar o .so em execucao (hot reload). */ +#define rb_fill_rect tb_ed_w.fill_rect +#define rb_fill_rrect tb_ed_w.fill_rrect +#define rb_fill_circle tb_ed_w.fill_circle +#define rb_stroke_rect tb_ed_w.stroke_rect +#define rb_stroke_circle tb_ed_w.stroke_circle +#define rb_line tb_ed_w.line +#define rb_text_c tb_ed_w.text_c +#define tw tb_ed_w.text_width +#define in_rect tb_ed_w.in_rect + +static const Col COL_MENU TB_EW_UNUSED = C( 76,151,255); /* #4C97FF */ +static const Col COL_MENU_DARK TB_EW_UNUSED = C( 61,121,204); +static const Col COL_UI_BG TB_EW_UNUSED = C(229,240,255); /* #E5F0FF */ +static const Col COL_PANEL TB_EW_UNUSED = C(255,255,255); +static const Col COL_FLY TB_EW_UNUSED = C(249,249,249); +static const Col COL_WS_BG TB_EW_UNUSED = C(249,249,249); +static const Col COL_GRID TB_EW_UNUSED = C(221,221,221); +static const Col COL_BORDER TB_EW_UNUSED = C(217,217,217); +static const Col COL_TEXT TB_EW_UNUSED = C( 87, 94,117); /* #575E75 */ +static const Col COL_TEXT_DIM TB_EW_UNUSED = C(150,155,175); +static const Col COL_TAB_OFF TB_EW_UNUSED = C(217,227,242); +static const Col COL_HOVER TB_EW_UNUSED = C(214,228,248); +static const Col COL_FLAG TB_EW_UNUSED = C( 76,191, 86); /* #4CBF56 */ +static const Col COL_FLAG_DARK TB_EW_UNUSED = C( 69,153, 61); +static const Col COL_STOP TB_EW_UNUSED = C(236, 89, 89); /* #EC5959 */ +static const Col COL_STOP_DARK TB_EW_UNUSED = C(184, 60, 60); +static const Col COL_WHITE TB_EW_UNUSED = C(255,255,255); +static const Col COL_MISSING TB_EW_UNUSED = C(170,170,170); +static const Col COL_EXT TB_EW_UNUSED = C( 15,189,140); /* extensões */ +static const Col COL_EXT_DARK TB_EW_UNUSED = C( 11,142,105); +static const Col COL_LIBBTN TB_EW_UNUSED = C(255, 76, 76); /* botao de extensoes */ +static const Col COL_LIBBTN_DARK TB_EW_UNUSED = C(211, 47, 47); +static const Col COL_VAR TB_EW_UNUSED = C(255,140, 26); + +/* Tema escuro do editor de codigo */ +static const Col COL_CODE_BG TB_EW_UNUSED = C( 40, 44, 52); +static const Col COL_CODE_GUTTER TB_EW_UNUSED = C( 33, 37, 43); +static const Col COL_CODE_CURLINE TB_EW_UNUSED = C( 51, 57, 67); +static const Col COL_CODE_FOCUS TB_EW_UNUSED = C( 62, 74, 53); +static const Col COL_CODE_BAR TB_EW_UNUSED = C( 33, 37, 43); +static const Col COL_CODE_TEXT TB_EW_UNUSED = C(212, 212, 212); +static const Col COL_TIP_BG TB_EW_UNUSED = C( 37, 37, 38); +static const Col COL_TIP_BORDER TB_EW_UNUSED = C( 69, 69, 69); +static const Col COL_TIP_LINK TB_EW_UNUSED = C( 74,158,255); +static const Col COL_MON_BG TB_EW_UNUSED = C(230,240,255); +static const Col COL_MON_BORDER TB_EW_UNUSED = C(195,204,217); +static const Col COL_ERR_MENU TB_EW_UNUSED = C(255,215,215); +static const Col COL_ERR_TEXT TB_EW_UNUSED = C(204, 60, 60); + +/* == Categorias (vêm das libraries; "Meus Blocos" é do editor) === */ +static const Col COL_MYBLOCKS_COL TB_EW_UNUSED = C(255,102,128); +static const Col COL_MYBLOCKS_DARK TB_EW_UNUSED = C(255, 51, 85); + +#define USER_COLOR_COUNT 8 +static const Col s_user_colors[USER_COLOR_COUNT] TB_EW_UNUSED = { + C(255,102,128), C( 76,151,255), C(153,102,255), C(207, 99,207), + C(255,191, 0), C(255,171, 25), C( 89,192, 89), C( 15,189,140), +}; + +/* == Rótulos dos blocos (%N - campo de entrada N) === */ +typedef struct { + const char* type; + const char* label; + const char* defs; /* valores iniciais dos campos, separados por '|' */ +} BlockSpec; + +static const BlockSpec s_specs[] = { + {"Events.WhenRun", "quando 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}, + {"Control.IfElse", "se %1 então", NULL}, + {"Operators.Lt", "%1 < %2", "|50"}, + {"Operators.Eq", "%1 = %2", "|50"}, + {"Operators.Gt", "%1 > %2", "|50"}, + {"Operators.And", "%1 e %2", NULL}, + {"Operators.Or", "%1 ou %2", NULL}, + {"Operators.Not", "não %1", NULL}, + {"Operators.Random", "número aleatório entre %1 e %2", "1|10"}, + {"Math.Add", "%1 + %2", NULL}, + {"Math.Sub", "%1 - %2", NULL}, + {"Math.Mul", "%1 * %2", NULL}, + {"Math.Div", "%1 / %2", NULL}, + {"Math.Mod", "resto de %1 por %2", NULL}, + {"Math.Abs", "valor absoluto de %1", NULL}, + {"Math.Max", "maior entre %1 e %2", NULL}, + {"Math.Min", "menor entre %1 e %2", NULL}, + {"Text.Concat", "junte %1 com %2", "maçã|banana"}, + {"Text.Length", "tamanho de %1", "maçã"}, + {"Literal.Text", "texto %1", NULL}, + {"Variables.Set", "mude %1 para %2", "x|0"}, + {"Variables.Change", "adicione %2 a %1", "x|1"}, + {"Variables.Get", "%1", "x"}, + {"IO.Print", "escreva %1 %2", "Olá!|"}, + {"IO.PrintInt", "escreva o número %1", NULL}, + {"Port.In", "parâmetro %1", "x"}, + {"Port.Out", "devolva %1 = %2", "resultado|"}, + {"Stage.Clear", "apague tudo", NULL}, + {"Stage.Background", "mude o fundo para r %1 g %2 b %3", "255|255|255"}, + {"Stage.PenColor", "mude a cor da caneta para r %1 g %2 b %3", "76|151|255"}, + {"Stage.PenSize", "mude o tamanho da caneta para %1", "4"}, + {"Stage.Line", "desenhe linha de x %1 y %2 até x %3 y %4", "-100|0|100|0"}, + {"Stage.Rect", "desenhe retângulo em x %1 y %2 largura %3 altura %4", "0|0|120|80"}, + {"Stage.Circle", "desenhe círculo em x %1 y %2 raio %3", "0|0|50"}, + {"Stage.Text", "escreva %1 no palco em x %2 y %3", "Olá!|-40|0"}, + /* Curvas (lista de pontos [x,y]) */ + {"Curves.Line", "reta de x %1 y %2 até x %3 y %4 com %5 passos", "0|0|100|0|20"}, + {"Curves.Bezier", "bezier de x %1 y %2 controles (%3,%4) (%5,%6) até x %7 y %8 com %9 passos", "0|0|0|80|100|80|100|0|20"}, + {"Curves.Quadratic", "curva quadrática de x %1 y %2 controle (%3,%4) até x %5 y %6 com %7 passos", "0|0|50|80|100|0|20"}, + {"Curves.Arc", "arco em (%1,%2) raio %3 de %4 a %5 graus com %6 passos", "0|0|50|0|180|24"}, + {"Curves.Circle", "círculo em (%1,%2) raio %3 com %4 passos", "0|0|50|36"}, + {"Curves.Count", "quantos pontos em %1", NULL}, + {"Curves.PointX", "x do ponto %2 de %1", "|0"}, + {"Curves.PointY", "y do ponto %2 de %1", "|0"}, + /* Base64 */ + {"Base64.Encode", "codifique em base64 %1", NULL}, + {"Base64.Decode", "decodifique base64 %1", NULL}, + /* Imagens PPM (tipo imagem do core) */ + {"PPM.Load", "carregue a imagem %1", "imagem.ppm"}, + {"PPM.Save", "grave a imagem %1 em %2", "|saida.ppm"}, + {"PPM.New", "nova imagem(%1 x %2) cor r %3 g %4 b %5", "32|32|255|0|0"}, + {"PPM.Width", "largura de %1", NULL}, + {"PPM.Height", "altura de %1", NULL}, + {"PPM.SetPixel", "pinte %1 em (%2,%3) de r %4 g %5 b %6", "|0|0|0|0|0"}, + {"PPM.GetPixel", "cor de %1 em (%2,%3)", "|0|0"}, + {"BMP.Load", "carregue o BMP %1", "imagem.bmp"}, + {"BMP.Save", "grave o BMP %1 em %2", "|saida.bmp"}, + {"PNG.Load", "carregue o PNG %1", "imagem.png"}, + {"PNG.Save", "grave o PNG %1 em %2", "|saida.png"}, + /* Imagem (ops genericas) */ + {"Image.New", "nova imagem(%1 x %2) cor r %3 g %4 b %5", "32|32|255|0|0"}, + {"Image.Width", "largura da imagem %1", NULL}, + {"Image.Height", "altura da imagem %1", NULL}, + {"Image.GetPixel", "cor da imagem %1 em (%2,%3)", "|0|0"}, + {"Image.SetPixel", "pinte a imagem %1 em (%2,%3) com r %4 g %5 b %6", "|0|0|0|0|0"}, + {"Image.Fill", "preencha a imagem %1 com r %2 g %3 b %4", "|255|255|255"}, + {"Image.Clone", "copie a imagem %1", NULL}, + {"Image.Crop", "recorte da imagem %1 em (%2,%3) tamanho %4 x %5", "|0|0|16|16"}, + {"Image.Scale", "escale a imagem %1 para %2 x %3", "|64|64"}, + {"Image.Load", "carregue a imagem %1", "imagem.png"}, + {"Image.Save", "grave a imagem %1 em %2", "|saida.png"}, + /* Vetor (vg) */ + {"VG.New", "novo desenho vetorial", NULL}, + {"VG.Line", "linha do vetor %1 de (%2,%3) a (%4,%5) cor r %6 g %7 b %8 esp %9", "|0|0|50|50|0|0|0|2"}, + {"VG.Rect", "retangulo no vetor %1 em (%2,%3) %4 x %5 cor r %6 g %7 b %8", "|0|0|40|40|255|0|0"}, + {"VG.Circle", "circulo no vetor %1 em (%2,%3) raio %4 cor r %5 g %6 b %7", "|20|20|15|0|0|255"}, + {"VG.Polygon", "poligono no vetor %1 pontos %2 fechar %3 cor r %4 g %5 b %6", "||1|0|255|0"}, + {"VG.Render", "rasterize o vetor %1 em %2 x %3 escala %4", "|64|64|1"}, + /* SVG */ + {"SVG.Parse", "interprete o SVG %1", NULL}, + {"SVG.Render", "desenhe o SVG %1 em %2 x %3", "|64|64"}, + {"SVG.Load", "carregue o SVG %1", "desenho.svg"}, +}; + +/* === + * Estruturas de dados + * === */ +typedef enum { SH_STACK, SH_HAT, SH_C1, SH_C2, SH_REPORTER, SH_BOOL } Shape; + +/* Relação de um bloco com o pai */ +#define REL_NONE (-1) +#define REL_NEXT 0 +#define REL_SUB0 1 /* REL_SUB0 + k: boca k de um bloco C */ +#define REL_ARG0 3 /* REL_ARG0 + i: campo de entrada i */ + +typedef struct { + int16_t arg; /* -1 = texto; senão índice do campo */ + int16_t len; + const char* txt; + float x, w; +} Part; + +typedef struct { + bool used; + bool dragging; + TinyBlocks_TypeBlock* type; + char type_name[64]; + float x, y; /* posição (só para o topo de uma pilha) */ + int parent, prel; + int next; + int sub[2]; + int args[MAX_INPUTS]; + char in_text[MAX_INPUTS][64]; + char lit_text[LIT_TEXT_CAP]; + + /* layout - recalculado a cada frame */ + float ax, ay, w, h; + float row_y, row_h, prev_y; + float sub_y[2], sub_h[2]; + float slot_x[MAX_INPUTS], slot_y[MAX_INPUTS], slot_w[MAX_INPUTS], slot_h[MAX_INPUTS]; + int part_n; + Part parts[MAX_PARTS]; + + TinyBlocks_Block* live_rt; /* última instância no runtime (não-owning) */ +} EdBlock; + +/* Um trecho colorido do editor de codigo (vindo do tinyblocks-syntax). */ +typedef struct { int line; char* text; char color[12]; } CodeTok; + +typedef struct Tab { + EdBlock ws[MAX_WS]; + int top[MAX_WS]; /* pilhas de topo, em ordem de desenho */ + int top_n; + float ws_sx, ws_sy; + char name[48]; + bool is_composite; + int comp_id; + int color_idx; + + int kind; /* TK_BLOCKS, TK_CODE, TK_IMAGE */ + + /* -- aba de codigo -- */ + char* code_text; + int code_len, code_cap; + int code_caret; /* posicao do cursor (offset em bytes) */ + int code_scroll; /* primeira linha visivel (0-based) */ + int code_focus; /* linha destacada (1-based), -1 = nenhuma */ + char code_path[256]; + char code_lang[16]; + char* code_hl; /* XML do realce (cache) */ + CodeTok* code_toks; + int code_tok_n; + bool code_hl_dirty; + + /* -- aba de imagem: documento com camadas -- */ + ImgLayer img_layers[IMG_MAX_LAYERS]; + int img_layer_n; + int img_layer_cur; + int img_w, img_h; /* tamanho do documento em pixels */ + char img_path[256]; /* arquivo do documento (salvar) */ + int img_tool; /* IT_* */ + int img_rgb[3]; /* cor atual (0..255) */ + int img_swatch; /* paleta selecionada; -1 = cor propria */ + float img_hue, img_sat, img_val; /* HSV da cor atual (roda de cor) */ + int img_cdrag; /* arrasto na roda: 0=nada 1=matiz 2=SV */ + float img_zoom; /* escala de exibicao (1.0 = 1:1) */ + int img_drag; /* traco em andamento */ + int img_drag_x, img_drag_y; + TinyBlocks_Image* img_undo[IMG_UNDO_MAX]; + int img_undo_layer[IMG_UNDO_MAX]; + int img_undo_n; + TinyBlocks_Image* img_prev; /* miniatura (cache) */ + unsigned img_prev_rev; + unsigned img_rev; /* muda a cada alteracao do documento */ + ImgSel img_sel; +} Tab; + +typedef enum { PARAM_NUM, PARAM_BOOL, PARAM_LABEL } ParamKind; +typedef struct { ParamKind kind; char name[32]; } UserParam; + +typedef struct { + char name[48]; + int input_count, output_count; + char input_names[MAX_UBLK_SLOTS][32]; + char output_names[MAX_UBLK_SLOTS][32]; + UserParam parts[MAX_UBLK_PARTS]; /* protótipo: entradas, booleanas e rótulos */ + int part_n; + Tab* snap; /* cópia da aba no momento do "Salvar" */ + TinyBlocks_TypeBlock* reg_type; + int tab_idx; + int color_idx; +} UserBlockDef; + +typedef struct { + UserBlockDef* def; + TinyBlocks_Value in[MAX_UBLK_SLOTS]; + TinyBlocks_Value out[MAX_UBLK_SLOTS]; +} CallFrame; + +typedef struct { char 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; + +typedef enum { ES_IDLE, ES_PRESS, ES_DRAG, ES_PAN } EdSt; +typedef enum { SN_NONE, SN_NEXT, SN_SUB, SN_ABOVE, SN_ARG } SnapKind; +enum { CM_DUPLICATE, CM_DELETE, CM_EDIT_DEF, CM_CLEANUP, CM_NEW_COMPOSITE, + CM_EXP_JSON, CM_EXP_XML, CM_EXP_CSV }; + +/* Modos da barra de caminho do menu (path_input) */ +enum { PM_NONE, PM_LIB, PM_LOAD, PM_SAVE, PM_EXP_JSON, PM_EXP_XML, PM_EXP_CSV, + PM_IMGLOAD, PM_IMSAVE, PM_IMADDR, PM_IMADDV, PM_CODELOAD, PM_CODESAVE }; + +/* Formatos de exportacao */ +enum { EX_JSON, EX_XML, EX_CSV }; + +typedef struct Ed { + TinyBlocks* rt; + + 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; + float fly_scroll, fly_total_h; + + Tab tabs[MAX_TABS]; + int tab_n; + int cur_tab; + + UserBlockDef user_blocks[MAX_USER_BLOCKS]; + int user_block_n; + + char comp_name_buf[48]; + int comp_name_len; + + /* Diálogo modal "Criar um Bloco" (estilo Scratch) */ + bool comp_dialog_open; + int comp_dialog_def; /* -1 = novo; senão índice em user_blocks */ + bool comp_dialog_editing; /* true = edição de nome/rótulo em andamento */ + int comp_dialog_edit_part; /* índice da parte em edição, -1 = nome do bloco */ + char comp_dialog_name[48]; + UserParam comp_dialog_parts[MAX_UBLK_PARTS]; + int comp_dialog_part_n; + int comp_dialog_sel; /* parte selecionada (-1 = nenhuma) */ + int comp_dialog_color; + float comp_dialog_geom[MAX_UBLK_PARTS][2]; /* x,w desenhados (para hit test) */ + float comp_dialog_name_x, comp_dialog_name_w; + + bool ctx_menu_open; + bool ctx_export; /* menu de contexto aberto e o de exportacao */ + int ctx_menu_bi; + int ctx_menu_x, ctx_menu_y; + int ctx_menu_hover; + int ctx_items[8]; + int ctx_n; + + EdSt state; + int press_bi; + float press_mx, press_my; + int drag_bi; + float drag_ox, drag_oy; + SnapKind snap_kind; + int snap_bi, snap_idx; + float pan_mx, pan_my, pan_sx, pan_sy; + + bool editing; + int edit_bi, edit_in; + + int bubble_bi; + char bubble_text[128]; + TinyBlocks_JsonValue* bubble_json; /* lista de pontos (retida) ou NULL */ + TinyBlocks_Image* bubble_img; /* imagem (retida) ou NULL */ + int last_click_bi; + unsigned last_click_ms; + + char stage_buf[STAGE_BUF]; + + /* Execução */ + CallFrame frames[MAX_CALL_DEPTH]; + int frame_n; + long steps; + bool abort; + char abort_msg[160]; + TinyBlocks_Block** run_blocks; /* instâncias criadas na última execução */ + int run_n, run_cap; + Tab* live_tab; + FILE* cap_file; + int cap_saved; + + float mouse_x, mouse_y; + bool flag_hover, stop_hover, lib_hover, detach_hover; + + /* Palco: embutido no painel ou numa janela própria (Graphics.Window) */ + TinyBlocks_Block* stage; + TinyBlocks_Block* stage_win; + TinyBlocks_Block* stage_in; + + bool clip_on; + float clip[4]; + + TbEdModules mods; /* libraries privadas (bundle) por dlopen */ + int hot_check_frame; /* contador para checar hot reload */ + char hot_status[256]; + bool hot_status_ok; + + bool path_input_active; + char path_input_buf[512]; + 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; + + /* Configuracoes (settings) - store da tinyblocks-environ */ + bool settings_open; + int settings_sel; /* linha selecionada (-1 = nenhuma) */ + bool settings_path_focus; /* campo de caminho do CSV em foco */ + bool settings_use_env; /* caminho vindo de TINYBLOCKS_SETTINGS */ + bool settings_value_edit; /* editando o valor da linha sel. */ + bool settings_new_key; /* digitando o nome de uma nova chave */ + char settings_path[256]; + char settings_edit[256]; /* buffer do valor em edicao */ + char settings_key[64]; /* buffer da nova chave */ + int settings_scroll; + int settings_hover; + + /* Menu do botao "+" (nova aba) */ + bool plus_menu_open; + int plus_menu_hover; + float plus_menu_x, plus_menu_y; + + /* Tooltip de metadados do bloco (Alt + hover) */ + bool tip_open; + int tip_bi; + float tip_x, tip_y, tip_w, tip_h; + float tip_prev_y, tip_prev_h; /* area clicavel (previa do codigo) */ + char tip_title[256]; /* assinatura da funcao */ + char tip_loc[320]; /* arquivo:linha */ + char tip_doc[256]; + char tip_file[256]; /* arquivo resolvivel */ + int tip_line; + char tip_preview[768]; + + float img_mx, img_my; /* ultimo ponto do traco (aba de imagem) */ + + int win_w, win_h; +} Ed; + +#define CT (ed->tabs[ed->cur_tab]) + +/* Ponteiro global para o editor ativo - os eval_fn dos blocos do editor + * (variáveis, compostos, portas) só recebem (self, rt). */ +static Ed* g_active_ed TB_EW_UNUSED = NULL; + +void bubble_clear(Ed* ed); + +void palette_rebuild(Ed* ed); +void utf8_pop(char* s); +void append_text(char* dst, size_t cap, const char* add); +void dlg_open(Ed* ed, int def_idx); +void dlg_render(Ed* ed, TinyBlocks_RenderableBlock* rb); +bool dlg_click(Ed* ed, float mx, float my); +void dlg_key(Ed* ed, int sc); +void dlg_text(Ed* ed, const char* typed); + +/* Gestor de libraries (tinyblocks-libman) - UI desenhada pelo editor */ +void libman_show(Ed* ed); +void libman_click(Ed* ed, float mx, float my); +void libman_key(Ed* ed, int sc); +void libman_text(Ed* ed, const char* typed); +void libman_scroll_by(Ed* ed, float dy); +void libman_render(Ed* ed, TinyBlocks_RenderableBlock* rb); +bool hit_libman_foot(Ed* ed, float mx, float my); + +/* Abas de codigo/imagem + tooltip de metadados */ +bool tab_new_kind(Ed* ed, const char* name, bool is_composite, int kind); +void tab_doc_free(Tab* T); +void code_rehighlight(Tab* T); +void open_code_at(Ed* ed, const char* file, int line); +void render_code_tab(Ed* ed, TinyBlocks_RenderableBlock* rb); +void render_tooltip(Ed* ed, TinyBlocks_RenderableBlock* rb); +void render_plus_menu(Ed* ed, TinyBlocks_RenderableBlock* rb); +bool code_click(Ed* ed, float mx, float my); +bool code_key(Ed* ed, int sc, bool ctrl); +bool code_text(Ed* ed, const char* typed); +/* Recorte (clip) do desenho - vive no editor, usado tambem pela aba de imagem. + TB_ED_API: precisa ser visivel para os modulos carregados por dlopen. */ +TB_ED_API void clip_set(Ed* ed, TinyBlocks_RenderableBlock* rb, float x, float y, float w, float h); +TB_ED_API void clip_clear(Ed* ed, TinyBlocks_RenderableBlock* rb); +TB_ED_API void clip_restore(Ed* ed, TinyBlocks_RenderableBlock* rb); +TB_ED_API void start_path(Ed* ed, int mode, const char* def); + +/* Aba de imagem: library privada carregada por dlopen (hot reload). + As chamadas passam pela tabela tb_ed_img, entao trocar o .so em execucao + ja muda o comportamento - sem reiniciar o editor. + Quando compilando o proprio modulo, usa os nomes reais. */ +#ifdef TB_EDITOR_IMAGE_BUILD +# define render_image_tab tb_editor_image_view +# define image_click tb_editor_image_click +# define image_drag tb_editor_image_drag +# define image_release tb_editor_image_release +# define img_load_file tb_editor_image_load_file +# define img_save_out tb_editor_image_save +# define img_ensure tb_editor_image_ensure +# define img_sel_reset tb_editor_image_sel_reset +# define img_sel_commit tb_editor_image_sel_commit +#else +# define render_image_tab tb_ed_img.view +# define image_click tb_ed_img.click +# define image_drag tb_ed_img.drag +# define image_release tb_ed_img.release +# define img_load_file tb_ed_img.load_file +# define img_save_out tb_ed_img.save +# define img_ensure tb_ed_img.ensure +# define img_sel_reset tb_ed_img.sel_reset +# define img_sel_commit tb_ed_img.sel_commit +#endif + +/* Configuracoes (settings) - UI desenhada pelo editor */ +void settings_show(Ed* ed); +void settings_click(Ed* ed, float mx, float my); +void settings_key(Ed* ed, int sc, bool ctrl); +void settings_text(Ed* ed, const char* typed); +void settings_scroll_by(Ed* ed, float dy); +void settings_render(Ed* ed, TinyBlocks_RenderableBlock* rb); + +#endif /* TB_EDITOR_INTERNAL_H */ diff --git a/libraries/tinyblocks-editor/internal/tb_editor_modules.h b/libraries/tinyblocks-editor/internal/tb_editor_modules.h new file mode 100644 index 0000000..0b0fc50 --- /dev/null +++ b/libraries/tinyblocks-editor/internal/tb_editor_modules.h @@ -0,0 +1,96 @@ +/* + * TinyBlocks - tb_editor_modules.h + * Carga dinamica das libraries privadas do editor (bundle) para permitir + * HOT RELOAD: recompile so a parte que mudou (make -C libraries/... ) e o + * editor em execucao recarrega o .so sem reiniciar. + * + * O estado da interface vive em Ed/Tab (no editor), por isso trocar o modulo + * nao perde nada: so os codigos das funcoes sao substituidos. + */ +#ifndef TB_EDITOR_MODULES_H +#define TB_EDITOR_MODULES_H + +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +struct Ed; +struct Tab; +typedef struct Ed Ed; +typedef struct Tab Tab; + +/* Visibilidade dos simbolos do editor usados pelos modulos */ +#define TB_ED_API __attribute__((visibility("default"))) + +#define TB_ED_MODULE_MAX 8 + +/* API da library privada tinyblocks-editor-widgets */ +typedef struct { + TbEwColor (*col_mul) (TbEwColor, float); + void (*fill_rect) (TinyBlocks_RenderableBlock*, float, float, float, float, TbEwColor); + void (*fill_rrect) (TinyBlocks_RenderableBlock*, float, float, float, float, float, TbEwColor); + void (*fill_circle) (TinyBlocks_RenderableBlock*, float, float, float, TbEwColor); + void (*stroke_rect) (TinyBlocks_RenderableBlock*, float, float, float, float, float, TbEwColor); + void (*stroke_circle)(TinyBlocks_RenderableBlock*, float, float, float, float, TbEwColor); + void (*line) (TinyBlocks_RenderableBlock*, float, float, float, float, float, TbEwColor); + void (*text_c) (TinyBlocks_RenderableBlock*, float, float, const char*, TbEwColor, float); + float (*text_width) (const char*, float); + bool (*in_rect) (float, float, float, float, float, float); +} TbEdWidgetsApi; + +/* API da library privada tinyblocks-editor-image */ +typedef struct { + void (*view) (Ed*, TinyBlocks_RenderableBlock*); + bool (*click) (Ed*, float, float); + void (*drag) (Ed*, float, float); + void (*release) (Ed*, float, float); + void (*load_file) (Ed*, const char*, int); + void (*save) (Ed*, const char*); + void (*ensure) (Ed*, Tab*); + void (*sel_reset) (Tab*); + void (*sel_commit)(Tab*); +} TbEdImageApi; + +typedef struct { + const char* name; /* tinyblocks-editor-image */ + const char* file; /* libtinyblocks-editor-image.so */ + void* handle; + int64_t mtime; + int ok; +} TbEdModule; + +typedef struct { + TbEdModule list[TB_ED_MODULE_MAX]; + TbEdWidgetsApi widgets; + int n; + TbEdImageApi image; + bool loaded; + int reloads; + char dir[512]; /* pasta dos modulos */ + char info[160]; /* ultimo evento (status bar) */ +} TbEdModules; + +/* Tabelas vivas: o editor chama por aqui, entao a troca e instantanea */ +TB_ED_API extern TbEdImageApi tb_ed_img; +TB_ED_API extern TbEdWidgetsApi tb_ed_w; + +/* Carrega (ou recarrega) os modulos. Sempre que um .so muda de mtime + recarrega todos os modulos, na ordem. Retorna true se algo foi carregado. */ +bool tb_ed_modules_load(Ed* ed); +/* Verificacao barata (inotify/mtime): recarrega se algum .so mudou. */ +bool tb_ed_modules_check(Ed* ed); +/* Esquece os modulos carregados (nao mexe no state do editor) */ +void tb_ed_modules_clear(void); +/* Caminho de origem dos modulos (para mensagens/uso no Makefile) */ +const char* tb_ed_modules_dir(void); + +#ifdef __cplusplus +} +#endif + +#endif /* TB_EDITOR_MODULES_H */ diff --git a/libraries/tinyblocks-editor/libraries/tinyblocks-editor-image/Makefile b/libraries/tinyblocks-editor/libraries/tinyblocks-editor-image/Makefile new file mode 100644 index 0000000..20248ae --- /dev/null +++ b/libraries/tinyblocks-editor/libraries/tinyblocks-editor-image/Makefile @@ -0,0 +1,42 @@ +# Makefile da library privada tinyblocks-editor-image +# Bundle "tinyblocks-editor". Constroi .a e .so. +CC := gcc +BUILD := build + +CFLAGS := -std=c11 -Wall -Wextra -pedantic \ + -DTB_EDITOR_IMAGE_BUILD \ + -D_POSIX_C_SOURCE=200809L \ + -I../../../../include -Iinclude \ + -I../../internal \ + -I../tinyblocks-editor-widgets/include \ + -I../../../tinyblocks-graphics/include \ + -I../../../tinyblocks-variables/include \ + -I../../../tinyblocks-blueprint/include \ + -I../../../tinyblocks-environ/include \ + -I../../../tinyblocks-api/include \ + -I../../../tinyblocks-libman/include \ + -I../../../tinyblocks-syntax/include + +OBJS := $(BUILD)/tb_editor_image.o +LIB_A := $(BUILD)/libtinyblocks-editor-image.a +LIB_SO := $(BUILD)/libtinyblocks-editor-image.so + +.PHONY: all static shared clean +all: static shared +static: $(LIB_A) +shared: $(LIB_SO) + +$(BUILD)/tb_editor_image.o: src/tb_editor_image.c include/tb_editor_image.h \ + ../../internal/tb_editor_internal.h \ + ../tinyblocks-editor-widgets/include/tb_editor_widgets.h + @mkdir -p $(BUILD) + $(CC) $(CFLAGS) -fPIC -c $< -o $@ + +$(LIB_A): $(OBJS) + ar rcs $@ $^ + +$(LIB_SO): $(OBJS) + $(CC) -shared -o $@ $^ -Wl,-z,lazy + +clean: + $(RM) -r $(BUILD) diff --git a/libraries/tinyblocks-editor/libraries/tinyblocks-editor-image/include/tb_editor_image.h b/libraries/tinyblocks-editor/libraries/tinyblocks-editor-image/include/tb_editor_image.h new file mode 100644 index 0000000..088b573 --- /dev/null +++ b/libraries/tinyblocks-editor/libraries/tinyblocks-editor-image/include/tb_editor_image.h @@ -0,0 +1,46 @@ +/* + * TinyBlocks - tb_editor_image.h + * Aba "Imagem" do editor (library privada do bundle tinyblocks-editor). + * + * O estado de cada aba mora em Tab (img_layers/img_sel/...), definido no + * cabecalho interno do editor. Estas funcoes recebem o Ed dono da aba e + * operam sempre na aba corrente (CT). + */ +#ifndef TB_EDITOR_IMAGE_H +#define TB_EDITOR_IMAGE_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +struct Ed; +struct Tab; +typedef struct Ed Ed; +typedef struct Tab Tab; + +/* Desenha a aba de imagem inteira (painel, ferramentas, pagina, rodape) */ +void tb_editor_image_view(Ed* ed, TinyBlocks_RenderableBlock* rb); + +/* Entrada: clique, arrasto e soltura do botao esquerdo */ +bool tb_editor_image_click (Ed* ed, float mx, float my); +void tb_editor_image_drag (Ed* ed, float mx, float my); +void tb_editor_image_release(Ed* ed, float mx, float my); + +/* Arquivo: kind < 0 abre como documento, senao adiciona uma camada + (0 = raster, 1 = vetor). Salvaguarda achata as camadas. */ +void tb_editor_image_load_file(Ed* ed, const char* path, int kind); +void tb_editor_image_save (Ed* ed, const char* path); + +/* Garante um documento vazio (usado ao criar a aba) e limpa selecao */ +void tb_editor_image_ensure (Ed* ed, Tab* T); +void tb_editor_image_sel_reset (Tab* T); +void tb_editor_image_sel_commit(Tab* T); + +#ifdef __cplusplus +} +#endif + +#endif /* TB_EDITOR_IMAGE_H */ diff --git a/libraries/tinyblocks-editor/libraries/tinyblocks-editor-image/library.toml b/libraries/tinyblocks-editor/libraries/tinyblocks-editor-image/library.toml new file mode 100644 index 0000000..7465d79 --- /dev/null +++ b/libraries/tinyblocks-editor/libraries/tinyblocks-editor-image/library.toml @@ -0,0 +1,17 @@ +# Editor de imagem do editor (bundle "tinyblocks-editor"). +[library] +name = "tinyblocks-editor-image" +bundle = "tinyblocks-editor" +private = true +version = "1.0.0" +category = "Editor" +description = "Aba Imagem: pintura com camadas raster/vetor" +color = [255, 152, 0, 255] +dark = [230, 119, 0, 255] + +[build] +sources = ["src/tb_editor_image.c"] +includes = ["include"] +shared = "build/libtinyblocks-editor-image.so" +static = "build/libtinyblocks-editor-image.a" +depends = ["tinyblocks-editor-widgets"] diff --git a/libraries/tinyblocks-editor/libraries/tinyblocks-editor-image/src/tb_editor_image.c b/libraries/tinyblocks-editor/libraries/tinyblocks-editor-image/src/tb_editor_image.c new file mode 100644 index 0000000..b89019e --- /dev/null +++ b/libraries/tinyblocks-editor/libraries/tinyblocks-editor-image/src/tb_editor_image.c @@ -0,0 +1,1216 @@ +/* + * TinyBlocks - tb_editor_image.c + * Aba "Imagem" do editor: editor de pintura com camadas raster/vetor, + * ferramentas (pincel, linha, retangulo, elipse, preencher, borracha, + * conta-gotas, selecionar/mover/redimensionar), paleta, zoom e undo. + * + * Library privada do bundle "tinyblocks-editor": compartilha o cabecalho + * interno do editor (Ed/Tab) e as primitivas de tinyblocks-editor-widgets. + * Como as demais, pode ser usada como .so independente: os simbolos do + * editor ficam pendentes e sao resolvidos na carga. + */ +#include "../../../internal/tb_editor_internal.h" +#include "tb_editor_image.h" + +/* Helpers internos desta library (definidos mais abaixo) */ +static ImgLayer* img_active(Tab* T); +static void img_undo_clear(Tab* T); +static void img_undo_push(Tab* T); +static void img_undo_do(Tab* T); +static void img_clear_layer(Tab* T); + +/* -- Aba de imagem: editor de pintura com camadas (visual estilo Scratch) -- */ + +static const Col COL_PAINT_BG = C(233,238,242); +static const Col COL_PAINT_LINE = C(212,220,228); +static const Col COL_PAINT_SHAD = C(196,205,214); +static const Col COL_PAINT_BTN = C(255,255,255); +static const Col COL_L_RASTER = C(255,152, 0); +static const Col COL_L_VECTOR = C( 0,151,167); +static const Col COL_CHK_A = C(255,255,255); +static const Col COL_CHK_B = C(238,238,238); + +static const char* img_tool_tip(int t) { + switch (t) { + case IT_SEL: return "selecionar"; + case IT_BRUSH: return "pincel"; + case IT_LINE: return "linha"; + case IT_RECT: return "retangulo"; + case IT_ELLIPSE: return "elipse"; + case IT_FILL: return "preencher"; + case IT_ERASER: return "borracha"; + case IT_PICK: return "conta-gotas"; + } + return ""; +} + +static const Col IMG_PALETTE[12] = { + {0.10f,0.10f,0.10f,1.f}, {1.00f,1.00f,1.00f,1.f}, + {0.90f,0.15f,0.15f,1.f}, {1.00f,0.62f,0.00f,1.f}, + {1.00f,0.92f,0.20f,1.f}, {0.22f,0.75f,0.30f,1.f}, + {0.10f,0.62f,0.90f,1.f}, {0.30f,0.35f,0.90f,1.f}, + {0.62f,0.30f,0.85f,1.f}, {0.95f,0.45f,0.72f,1.f}, + {0.55f,0.38f,0.24f,1.f}, {0.60f,0.60f,0.60f,1.f} +}; + +/* Cor: HSV (roda de matiz + quadrado saturacao/valor) ------------------- */ +static Col img_hsv_col(float h, float sat, float v) { + float c = v * sat; + float hp = h / 60.f; + float x = c * (1.f - fabsf(fmodf(hp, 2.f) - 1.f)); + float r = 0, g = 0, b = 0; + if (hp < 1.f) { r = c; g = x; } + else if (hp < 2.f) { r = x; g = c; } + else if (hp < 3.f) { g = c; b = x; } + else if (hp < 4.f) { g = x; b = c; } + else if (hp < 5.f) { r = x; b = c; } + else { r = c; b = x; } + float m = v - c; + Col o = { r + m, g + m, b + m, 1.f }; + return o; +} +/* RGB atual -> HSV (mantem o matiz quando a cor e acromatica) */ +static void img_hsv_sync(Tab* T) { + float r = T->img_rgb[0] / 255.f, g = T->img_rgb[1] / 255.f, b = T->img_rgb[2] / 255.f; + float mx = r > g ? (r > b ? r : b) : (g > b ? g : b); + float mn = r < g ? (r < b ? r : b) : (g < b ? g : b); + float d = mx - mn; + float h = T->img_hue; + if (d > 0.0001f) { + if (mx == r) h = 60.f * fmodf((g - b) / d + 6.f, 6.f); + else if (mx == g) h = 60.f * ((b - r) / d + 2.f); + else h = 60.f * ((r - g) / d + 4.f); + } + if (h < 0.f) h += 360.f; + if (h >= 360.f) h -= 360.f; + T->img_hue = h; + T->img_sat = mx > 0.0001f ? d / mx : 0.f; + T->img_val = mx; +} +static void img_hsv_apply(Tab* T) { + Col c = img_hsv_col(T->img_hue, T->img_sat, T->img_val); + T->img_rgb[0] = (int)(c.r * 255.f + 0.5f); + T->img_rgb[1] = (int)(c.g * 255.f + 0.5f); + T->img_rgb[2] = (int)(c.b * 255.f + 0.5f); + T->img_swatch = -1; +} + +/* Geometria ------------------------------------------------------------- + * Layout (como no Krita): ferramentas na coluna da esquerda, tela no meio e + * na direita uma coluna com a roda de cores em cima e as camadas embaixo. */ +#define IMG_TOOL_W 54 /* coluna de ferramentas (esquerda) */ +#define IMG_RIGHT_W 210 /* coluna de cores + camadas (direita) */ +#define IMG_BAR_H 34 /* barra superior (arquivo) */ +#define IMG_FOOT_H 34 /* rodape (desfazer/limpar/zoom) */ +#define IMG_TH 44 /* lado do botao de ferramenta */ +#define IMG_ROW_H 38 /* altura da linha de camada */ +#define IMG_PAD 8 + +static float img_color_x(Ed* ed) { (void)ed; return WS_X + WS_W - IMG_RIGHT_W; } +static void img_area(Ed* ed, float* x, float* y, float* w, float* h) { + *x = WS_X + IMG_TOOL_W; + *y = WS_Y + IMG_BAR_H; + *w = WS_W - IMG_TOOL_W - IMG_RIGHT_W; + *h = WS_H - IMG_BAR_H - IMG_FOOT_H; + (void)ed; +} +/* Retangulo onde o documento (pagina) aparece. Escala = zoom puro: a pagina + sempre ocupa img_w*zoom x img_h*zoom pixels, centrada na area; nada some da + tela sozinho e nao existe "zona morta" (todo clique na area e valido). */ +static void img_view(Ed* ed, Tab* T, float* dx, float* dy, float* dw, float* dh) { + float ax, ay, aw, ah; + img_area(ed, &ax, &ay, &aw, &ah); + *dw = T->img_w * T->img_zoom; + *dh = T->img_h * T->img_zoom; + *dx = ax + (aw - *dw) * 0.5f; + *dy = ay + (ah - *dh) * 0.5f; +} +static void img_tool_rect(Ed* ed, int i, float* x, float* y) { + *x = WS_X + (IMG_TOOL_W - IMG_TH) * 0.5f; + *y = WS_Y + IMG_BAR_H + 6 + i * (IMG_TH + 6); + (void)ed; +} +static float img_foot_y(Ed* ed) { (void)ed; return WS_Y + WS_H - IMG_FOOT_H; } +static float img_pal_y(Ed* ed); +static void img_swatch_rect(Ed* ed, int i, float* x, float* y) { + /* paleta rapida: grade 3x4 na coluna de cores */ + float px = img_color_x(ed) + 14; + *x = px + (i % 3) * 62; + *y = img_pal_y(ed) + (i / 3) * 30; +} +/* Aros/quadrado da roda de cor */ +static void img_wheel_rect(Ed* ed, float* cx, float* cy, float* r_out, float* r_in) { + *cx = img_color_x(ed) + IMG_RIGHT_W * 0.5f; + *cy = WS_Y + IMG_BAR_H + 66; + *r_out = 62.f; + *r_in = 46.f; +} +static void img_sv_rect(Ed* ed, float* x, float* y, float* w, float* h) { + float cx, cy, ro, ri; + img_wheel_rect(ed, &cx, &cy, &ro, &ri); + *w = 58.f; *h = 58.f; + *x = cx - *w * 0.5f; + *y = cy - *h * 0.5f; +} +static float img_pal_y(Ed* ed) { + float cx, cy, ro, ri; + img_wheel_rect(ed, &cx, &cy, &ro, &ri); + (void)cx; + return cy + ro + 24; +} +/* Rodape da area de desenho: Desfazer / Limpar / zoom */ +static void img_foot_btn(Ed* ed, int which, float* x, float* y, float* w, float* h) { + float ax, ay, aw, ah, fy; + img_area(ed, &ax, &ay, &aw, &ah); + fy = img_foot_y(ed); + *y = fy + 5; *h = 24; + switch (which) { + case 0: *w = 78; *x = ax + 10; break; /* Desfazer */ + case 1: *w = 68; *x = ax + 96; break; /* Limpar */ + case 2: *w = 30; *x = ax + aw - 40; break; /* zoom - */ + case 3: *w = 30; *x = ax + aw - 78; break; /* zoom + */ + default: *w = 30; *x = ax + aw - 40; break; + } +} +/* Coluna da direita: rodape das camadas (botoes -/+ raster/+ vetor) */ +static float img_layers_title_y(Ed* ed) { + float cx, cy, ro, ri; + (void)cx; + img_wheel_rect(ed, &cx, &cy, &ro, &ri); + return img_pal_y(ed) + 4 * 30 + 22; +} +static float img_layers_top(Ed* ed) { return img_layers_title_y(ed) + 16; } +/* Altura adaptativa: as linhas nunca invadem os botoes do rodape */ +static float img_row_h(Ed* ed) { + float top = img_layers_top(ed); + float bot = WS_Y + WS_H - 30 - 2 * 32; + int n = CT.img_layer_n > 0 ? CT.img_layer_n : 1; + float h = IMG_ROW_H; + if (top + n * h > bot) h = (bot - top) / n; + if (h < 24.f) h = 24.f; + return h; +} +static void img_layer_row(Ed* ed, int i, float* x, float* y, float* w, float* h) { + float rh = img_row_h(ed); + *x = img_color_x(ed) + IMG_PAD; + *y = img_layers_top(ed) + i * rh; + *w = IMG_RIGHT_W - 2 * IMG_PAD; + *h = rh - 4; + (void)ed; +} +static void img_side_btn(Ed* ed, int which, float* x, float* y, float* w, float* h) { + *x = img_color_x(ed) + IMG_PAD; + *w = IMG_RIGHT_W - 2 * IMG_PAD; + *h = 26; + *y = WS_Y + WS_H - 30 - (2 - which) * 32; + (void)ed; +} + +/* Camadas --------------------------------------------------------------- */ +#define IMG_THUMB_W 40 +#define IMG_THUMB_H 30 +/* Miniatura da camada (cacheada por revisao) - como no painel do Scratch */ +static TinyBlocks_Image* img_layer_thumb(Tab* T, int i) { + ImgLayer* L = &T->img_layers[i]; + if (!L->img) return NULL; + if (L->thumb && L->thumb_rev == T->img_rev) return L->thumb; + if (!L->thumb || + tb_image_width(L->thumb) != IMG_THUMB_W || tb_image_height(L->thumb) != IMG_THUMB_H) { + if (L->thumb) tb_image_release(L->thumb); + L->thumb = tb_image_new(IMG_THUMB_W, IMG_THUMB_H, 4); + if (!L->thumb) return NULL; + } + int iw = tb_image_width(L->img), ih = tb_image_height(L->img); + if (iw < 1 || ih < 1) return L->thumb; + for (int y = 0; y < IMG_THUMB_H; y++) { + for (int x = 0; x < IMG_THUMB_W; x++) { + int sx = x * iw / IMG_THUMB_W, sy = y * ih / IMG_THUMB_H; + uint8_t r = 0, g = 0, b = 0, a = 0; + tb_image_get_pixel(L->img, sx, sy, &r, &g, &b, &a); + if (a == 0) { /* xadrez para transparencia */ + int alt = ((x / 5) + (y / 5)) & 1; + r = g = b = alt ? 238 : 255; + tb_image_set_pixel(L->thumb, x, y, r, g, b, 255); + } else { + tb_image_set_pixel(L->thumb, x, y, r, g, b, a); + } + } + } + L->thumb_rev = T->img_rev; + return L->thumb; +} + +static ImgLayer* img_active(Tab* T) { + if (T->img_layer_cur < 0 || T->img_layer_cur >= T->img_layer_n) return NULL; + return &T->img_layers[T->img_layer_cur]; +} +static TinyBlocks_Image* img_blank(int w, int h, int r, int g, int b, int a) { + if (w < 1) w = 1; + if (h < 1) h = 1; + TinyBlocks_Image* im = tb_image_new(w, h, 4); + if (!im) return NULL; + for (int y = 0; y < h; y++) + for (int x = 0; x < w; x++) + tb_image_set_pixel(im, x, y, (uint8_t)r, (uint8_t)g, (uint8_t)b, (uint8_t)a); + return im; +} +static void img_undo_clear(Tab* T) { + for (int i = 0; i < T->img_undo_n; i++) tb_image_release(T->img_undo[i]); + T->img_undo_n = 0; +} +static void img_doc_new(Ed* ed, Tab* T, int w, int h) { + img_undo_clear(T); + T->img_rev++; + for (int i = 0; i < T->img_layer_n; i++) tb_image_release(T->img_layers[i].img); + memset(T->img_layers, 0, sizeof(T->img_layers)); + T->img_layer_n = 0; + T->img_layer_cur = 0; + T->img_w = w > 0 ? w : 1; + T->img_h = h > 0 ? h : 1; + T->img_layers[0].img = img_blank(T->img_w, T->img_h, 255, 255, 255, 255); + scopy(T->img_layers[0].name, sizeof(T->img_layers[0].name), "Fundo"); + T->img_layers[0].kind = IMG_L_RASTER; + T->img_layers[0].visible = 1; + T->img_layer_n = 1; + (void)ed; +} +void tb_editor_image_ensure(Ed* ed, Tab* T) { + if (T->img_layer_n > 0 && T->img_w > 0 && T->img_h > 0) return; + float ax, ay, aw, ah; + img_area(ed, &ax, &ay, &aw, &ah); + int w = (int)(aw + 0.5f), h = (int)(ah + 0.5f); + if (w < 16) w = 16; + if (h < 16) h = 16; + img_doc_new(ed, T, w, h); + snprintf(T->name, sizeof(T->name), "Imagem"); +} +/* Cresce o documento (todas as camadas) mantendo o conteudo ancorado no + canto superior esquerdo. Historico e descartado (tamanho mudou). */ +static void img_doc_grow(Tab* T, int w, int h) { + if (w <= T->img_w && h <= T->img_h) return; + T->img_rev++; + if (w < T->img_w) w = T->img_w; + if (h < T->img_h) h = T->img_h; + if (w > 4096) w = 4096; + if (h > 4096) h = 4096; + img_undo_clear(T); + for (int i = 0; i < T->img_layer_n; i++) { + TinyBlocks_Image* old = T->img_layers[i].img; + TinyBlocks_Image* nw = img_blank(w, h, 0, 0, 0, 0); + if (!nw) continue; + if (old) { + int ow = tb_image_width(old), oh = tb_image_height(old); + for (int y = 0; y < oh && y < h; y++) + for (int x = 0; x < ow && x < w; x++) { + uint8_t r, g, b, a; + if (tb_image_get_pixel(old, x, y, &r, &g, &b, &a) && a) + tb_image_set_pixel(nw, x, y, r, g, b, a); + } + tb_image_release(old); + } + T->img_layers[i].img = nw; + } + T->img_w = w; + T->img_h = h; +} +static void img_norm(Tab* T, int* x, int* y) { + if (*x < 0) *x = 0; + if (*y < 0) *y = 0; + if (*x >= T->img_w || *y >= T->img_h) + img_doc_grow(T, *x + 32, *y + 32); +} +static bool img_layer_add(Ed* ed, Tab* T, int kind, const char* src, const char* name, + TinyBlocks_Image* content) { + if (T->img_layer_n >= IMG_MAX_LAYERS) { + snprintf(ed->hot_status, sizeof(ed->hot_status), + "Limite de %d camadas atingido", IMG_MAX_LAYERS); + ed->hot_status_ok = false; + if (content) tb_image_release(content); + return false; + } + ImgLayer* L = &T->img_layers[T->img_layer_n]; + memset(L, 0, sizeof(*L)); + L->img = content ? content : img_blank(T->img_w, T->img_h, 0, 0, 0, 0); + L->kind = kind; + L->visible = 1; + scopy(L->name, sizeof(L->name), name && name[0] ? name : + (kind == IMG_L_VECTOR ? "Vetor" : "Raster")); + if (src) scopy(L->src, sizeof(L->src), src); + T->img_layer_cur = T->img_layer_n; + T->img_layer_n++; + return true; +} + +/* Desenho --------------------------------------------------------------- */ +static bool img_pixel_at(Ed* ed, Tab* T, float mx, float my, int* px, int* py) { + float dx, dy, dw, dh; + img_view(ed, T, &dx, &dy, &dw, &dh); + if (dw <= 0 || dh <= 0) return false; + *px = (int)floorf((mx - dx) / T->img_zoom); + *py = (int)floorf((my - dy) / T->img_zoom); + return true; /* qualquer ponto da area e valido */ +} +static void img_put(Tab* T, int x, int y, int r, int g, int b, int a) { + ImgLayer* L = img_active(T); + if (!L || !L->img) return; + img_norm(T, &x, &y); + T->img_rev++; + tb_image_set_pixel(L->img, x, y, (uint8_t)r, (uint8_t)g, (uint8_t)b, (uint8_t)a); +} +static void img_line(Tab* T, int x0, int y0, int x1, int y1, int r, int g, int b, int a, int th) { + int dx = abs(x1 - x0), sx = x0 < x1 ? 1 : -1; + int dy = -abs(y1 - y0), sy = y0 < y1 ? 1 : -1; + int err = dx + dy; + for (;;) { + for (int oy = -th/2; oy <= th/2; oy++) + for (int ox = -th/2; ox <= th/2; ox++) + img_put(T, x0 + ox, y0 + oy, r, g, b, a); + if (x0 == x1 && y0 == y1) break; + int e2 = 2 * err; + if (e2 >= dy) { err += dy; x0 += sx; } + if (e2 <= dx) { err += dx; y0 += sy; } + } +} +static void img_rect(Tab* T, int x0, int y0, int x1, int y1, int r, int g, int b, int a, int th) { + if (x0 > x1) { int t = x0; x0 = x1; x1 = t; } + if (y0 > y1) { int t = y0; y0 = y1; y1 = t; } + img_line(T, x0, y0, x1, y0, r, g, b, a, th); + img_line(T, x0, y1, x1, y1, r, g, b, a, th); + img_line(T, x0, y0, x0, y1, r, g, b, a, th); + img_line(T, x1, y0, x1, y1, r, g, b, a, th); +} +static void img_ellipse(Tab* T, int x0, int y0, int x1, int y1, int r, int g, int b, int a, int th) { + int cx = (x0 + x1) / 2, cy = (y0 + y1) / 2; + int rx = abs(x1 - x0) / 2, ry = abs(y1 - y0) / 2; + if (rx < 1) rx = 1; + if (ry < 1) ry = 1; + int steps = 24 * (rx > ry ? rx : ry); + if (steps > 4096) steps = 4096; + for (int i = 0; i < steps; i++) { + double t = i * 2.0 * M_PI / steps; + int px = cx + (int)(rx * cos(t)); + int py = cy + (int)(ry * sin(t)); + for (int oy = -th/2; oy <= th/2; oy++) + for (int ox = -th/2; ox <= th/2; ox++) + img_put(T, px + ox, py + oy, r, g, b, a); + } +} +static void img_flood(Tab* T, int x0, int y0, int r, int g, int b) { + ImgLayer* L = img_active(T); + if (!L || !L->img) return; + img_norm(T, &x0, &y0); + int W = tb_image_width(L->img), H = tb_image_height(L->img); + if (x0 < 0 || y0 < 0 || x0 >= W || y0 >= H) return; + if (W > 0xFFFF || H > 0xFFFF) return; + uint8_t sr, sg, sb, sa; + if (!tb_image_get_pixel(L->img, x0, y0, &sr, &sg, &sb, &sa)) return; + if (sr == (uint8_t)r && sg == (uint8_t)g && sb == (uint8_t)b && sa == 255) return; + + size_t cap = (size_t)W * (size_t)H + 8; + int* st = (int*)malloc(cap * sizeof(int)); + if (!st) return; + size_t n = 0; + TinyBlocks_Image* im = L->img; + T->img_rev++; +#define IMG_PUSH(cx, cy) \ + do { \ + int _x = (cx), _y = (cy); \ + if (n < cap && _x >= 0 && _y >= 0 && _x < W && _y < H) { \ + uint8_t _r, _g, _b, _a; \ + if (tb_image_get_pixel(im, _x, _y, &_r, &_g, &_b, &_a) && \ + _r == sr && _g == sg && _b == sb && _a == sa) { \ + tb_image_set_pixel(im, _x, _y, (uint8_t)r, (uint8_t)g, \ + (uint8_t)b, 255); \ + st[n++] = (_y << 16) | (_x & 0xFFFF); \ + } \ + } \ + } while (0) + IMG_PUSH(x0, y0); + while (n > 0) { + int v = st[--n]; + int cx = v & 0xFFFF, cy = v >> 16; + IMG_PUSH(cx + 1, cy); + IMG_PUSH(cx - 1, cy); + IMG_PUSH(cx, cy + 1); + IMG_PUSH(cx, cy - 1); + } +#undef IMG_PUSH + free(st); +} +/* Cor composta (camada visivel mais ao topo) */ +static bool img_pick(Tab* T, int x, int y, int* r, int* g, int* b) { + for (int i = T->img_layer_n - 1; i >= 0; i--) { + if (!T->img_layers[i].visible || !T->img_layers[i].img) continue; + uint8_t pr, pg, pb, pa; + if (!tb_image_get_pixel(T->img_layers[i].img, x, y, &pr, &pg, &pb, &pa)) continue; + if (pa > 0) { *r = pr; *g = pg; *b = pb; return true; } + } + return false; +} +static void img_flatten(Tab* T, TinyBlocks_Image* dst) { + if (!dst) return; + int W = tb_image_width(dst), H = tb_image_height(dst); + for (int y = 0; y < H; y++) + for (int x = 0; x < W; x++) + tb_image_set_pixel(dst, x, y, 255, 255, 255, 255); + for (int i = 0; i < T->img_layer_n; i++) { + ImgLayer* L = &T->img_layers[i]; + if (!L->visible || !L->img) continue; + int lw = tb_image_width(L->img), lh = tb_image_height(L->img); + for (int y = 0; y < lh && y < H; y++) + for (int x = 0; x < lw && x < W; x++) { + uint8_t r, g, b, a; + if (!tb_image_get_pixel(L->img, x, y, &r, &g, &b, &a) || !a) continue; + uint8_t orr, og, ob, oa; + tb_image_get_pixel(dst, x, y, &orr, &og, &ob, &oa); + int ia = a; + int nr = (r * ia + orr * (255 - ia)) / 255; + int ng = (g * ia + og * (255 - ia)) / 255; + int nb = (b * ia + ob * (255 - ia)) / 255; + tb_image_set_pixel(dst, x, y, (uint8_t)nr, (uint8_t)ng, (uint8_t)nb, 255); + } + } +} + +/* Miniatura do documento (cache; reconstruida so quando algo muda) -------- */ + +/* Selecao: mover / redimensionar pixels ---------------------------------- */ +void tb_editor_image_sel_reset(Tab* T) { + if (T->img_sel.buf) { tb_image_release(T->img_sel.buf); T->img_sel.buf = NULL; } + memset(&T->img_sel, 0, sizeof(T->img_sel)); +} +static void img_sel_lift(Tab* T) { + ImgSel* S = &T->img_sel; + ImgLayer* L = img_active(T); + if (!L || !L->img || S->buf) return; + if (S->w < 1 || S->h < 1) return; + img_undo_push(T); + S->ox = S->x; S->oy = S->y; S->ow = S->w; S->oh = S->h; + S->buf = img_blank(S->w, S->h, 0, 0, 0, 0); + if (!S->buf) return; + for (int yy = 0; yy < S->h; yy++) + for (int xx = 0; xx < S->w; xx++) { + int sx = S->x + xx, sy = S->y + yy; + if (sx < 0 || sy < 0 || sx >= T->img_w || sy >= T->img_h) continue; + uint8_t r, g, b, a; + if (!tb_image_get_pixel(L->img, sx, sy, &r, &g, &b, &a) || !a) continue; + tb_image_set_pixel(S->buf, xx, yy, r, g, b, a); + tb_image_set_pixel(L->img, sx, sy, 0, 0, 0, 0); + } + T->img_rev++; +} +void tb_editor_image_sel_commit(Tab* T) { + ImgSel* S = &T->img_sel; + ImgLayer* L = img_active(T); + if (S->buf && L && L->img) { + for (int yy = 0; yy < S->h; yy++) { + int sy = S->h > 1 ? (int)((long long)yy * S->oh / S->h) : 0; + if (sy >= S->oh) sy = S->oh - 1; + for (int xx = 0; xx < S->w; xx++) { + int sx = S->w > 1 ? (int)((long long)xx * S->ow / S->w) : 0; + if (sx >= S->ow) sx = S->ow - 1; + uint8_t r, g, b, a; + if (sx < 0 || sy < 0) continue; + if (!tb_image_get_pixel(S->buf, sx, sy, &r, &g, &b, &a) || !a) continue; + int dx = S->x + xx, dy = S->y + yy; + if (dx < 0 || dy < 0 || dx >= T->img_w || dy >= T->img_h) continue; + tb_image_set_pixel(L->img, dx, dy, r, g, b, a); + } + } + T->img_rev++; + } + img_sel_reset(T); +} +static void img_sel_handle_pt(Tab* T, int i, int* hx, int* hy) { + ImgSel* S = &T->img_sel; + int xs[3] = { S->x, S->x + S->w / 2, S->x + S->w }; + int ys[3] = { S->y, S->y + S->h / 2, S->y + S->h }; + *hx = xs[i % 3]; + *hy = ys[i / 3]; +} +static int img_sel_handle_hit(Ed* ed, Tab* T, float mx, float my) { + ImgSel* S = &T->img_sel; + if (!S->on) return -1; + float dx, dy, dw, dh; + img_view(ed, T, &dx, &dy, &dw, &dh); + (void)dw; (void)dh; + for (int i = 0; i < 9; i++) { + if (i == 4) continue; + int hx, hy; + img_sel_handle_pt(T, i, &hx, &hy); + float px = dx + hx * T->img_zoom, py = dy + hy * T->img_zoom; + if (fabsf(mx - px) <= 7.f && fabsf(my - py) <= 7.f) return i; + } + return -1; +} +static bool img_sel_inside(Tab* T, int x, int y) { + ImgSel* S = &T->img_sel; + return S->on && x >= S->x && x < S->x + S->w && y >= S->y && y < S->y + S->h; +} +static void img_sel_resize(Tab* T, int hnd, int px, int py) { + ImgSel* S = &T->img_sel; + int x0 = S->x, y0 = S->y, x1 = S->x + S->w - 1, y1 = S->y + S->h - 1; + int col = hnd % 3, row = hnd / 3; + if (col == 0) x0 = px; + else if (col == 2) x1 = px; + if (row == 0) y0 = py; + else if (row == 2) y1 = py; + if (x1 < x0) { int t = x0; x0 = x1; x1 = t; } + if (y1 < y0) { int t = y0; y0 = y1; y1 = t; } + S->x = x0; S->y = y0; + S->w = x1 - x0 + 1; + S->h = y1 - y0 + 1; + if (S->w < 1) S->w = 1; + if (S->h < 1) S->h = 1; +} + +/* Undo ------------------------------------------------------------------ */ +static void img_undo_push(Tab* T) { + ImgLayer* L = img_active(T); + if (!L || !L->img) return; + if (T->img_undo_n >= IMG_UNDO_MAX) { + tb_image_release(T->img_undo[0]); + for (int i = 1; i < IMG_UNDO_MAX; i++) { + T->img_undo[i-1] = T->img_undo[i]; + T->img_undo_layer[i-1] = T->img_undo_layer[i]; + } + T->img_undo_n--; + } + TinyBlocks_Image* c = tb_image_clone(L->img); + if (!c) return; + T->img_undo[T->img_undo_n] = c; + T->img_undo_layer[T->img_undo_n] = T->img_layer_cur; + T->img_undo_n++; +} +static void img_undo_do(Tab* T) { + if (T->img_undo_n <= 0) return; + T->img_undo_n--; + int li = T->img_undo_layer[T->img_undo_n]; + if (li < 0 || li >= T->img_layer_n) { tb_image_release(T->img_undo[T->img_undo_n]); return; } + ImgLayer* L = &T->img_layers[li]; + if (L->img) tb_image_release(L->img); + L->img = T->img_undo[T->img_undo_n]; + T->img_undo[T->img_undo_n] = NULL; + T->img_rev++; +} + +/* Icones das ferramentas ------------------------------------------------ */ +static void img_draw_icon(TinyBlocks_RenderableBlock* rb, int tool, float cx, float cy, Col c) { + switch (tool) { + case IT_SEL: + rb_line(rb, cx - 6, cy - 8, cx - 6, cy + 7, 2.f, c); + rb_line(rb, cx - 6, cy - 8, cx + 5, cy + 1, 2.f, c); + rb_line(rb, cx - 6, cy - 1, cx + 3, cy + 7, 2.f, c); + break; + case IT_BRUSH: + rb_line(rb, cx - 8, cy + 8, cx + 3, cy - 3, 5.f, c); + rb_fill_circle(rb, cx + 6, cy - 6, 3.4f, c); + break; + case IT_LINE: + rb_line(rb, cx - 8, cy + 8, cx + 8, cy - 8, 2.f, c); + break; + case IT_RECT: + rb_stroke_rect(rb, cx - 8, cy - 6, 16, 12, 2.f, c); + break; + case IT_ELLIPSE: + rb_stroke_circle(rb, cx, cy, 8, 2.f, c); + break; + case IT_FILL: + rb_fill_rrect(rb, cx - 8, cy - 8, 13, 13, 3, c); + rb_fill_circle(rb, cx + 4, cy + 5, 4, c); + break; + case IT_ERASER: + rb_fill_rrect(rb, cx - 8, cy - 3, 16, 9, 2, c); + rb_line(rb, cx - 8, cy + 6, cx + 8, cy + 6, 2.f, col_mul(c, 0.6f)); + break; + case IT_PICK: + rb_line(rb, cx + 7, cy - 7, cx + 2, cy - 2, 3.f, c); + rb_fill_circle(rb, cx - 2, cy + 2, 4.4f, c); + break; + } +} + +/* Render ---------------------------------------------------------------- */ +void tb_editor_image_view(Ed* ed, TinyBlocks_RenderableBlock* rb) { + Tab* T = &CT; + img_ensure(ed, T); + + rb_fill_rect(rb, WS_X, WS_Y, WS_W, WS_H, COL_PAINT_BG); + + /* --- coluna esquerda: ferramentas --- */ + rb_fill_rect(rb, WS_X, WS_Y, IMG_TOOL_W, WS_H, COL_PANEL); + rb_line(rb, WS_X + IMG_TOOL_W - 1, WS_Y, WS_X + IMG_TOOL_W - 1, WS_Y + WS_H, 1.f, COL_PAINT_LINE); + for (int i = 0; i < IT_N; i++) { + float bx, by; + img_tool_rect(ed, i, &bx, &by); + bool sel = T->img_tool == i; + bool hov = in_rect(ed->mouse_x, ed->mouse_y, bx, by, IMG_TH, IMG_TH); + Col bg = sel ? COL_MENU : (hov ? COL_HOVER : COL_PAINT_BTN); + rb_fill_rrect(rb, bx, by, IMG_TH, IMG_TH, 8, bg); + if (!sel) rb_stroke_rect(rb, bx, by, IMG_TH, IMG_TH, 1.f, COL_PAINT_LINE); + img_draw_icon(rb, i, bx + IMG_TH * 0.5f, by + IMG_TH * 0.5f, sel ? COL_WHITE : COL_TEXT); + if (hov && !sel) + rb_text_c(rb, bx + IMG_TH + 6, by + IMG_TH * 0.5f, img_tool_tip(i), COL_TEXT_DIM, 10.f); + } + + /* --- barra superior (arquivo) --- */ + rb_fill_rect(rb, WS_X + IMG_TOOL_W, WS_Y, WS_W - IMG_TOOL_W, IMG_BAR_H, COL_PANEL); + rb_line(rb, WS_X + IMG_TOOL_W, WS_Y + IMG_BAR_H - 1, + WS_X + WS_W, WS_Y + IMG_BAR_H - 1, 1.f, COL_PAINT_LINE); + { + float bx = WS_X + IMG_TOOL_W + 10; + rb_fill_rrect(rb, bx, WS_Y + 5, 62, 24, 6, COL_MENU); + rb_text_c(rb, bx + (62 - tw("Abrir", FS_UI-1)) * 0.5f, WS_Y + 17, "Abrir", COL_WHITE, FS_UI-1); + bx += 70; + rb_fill_rrect(rb, bx, WS_Y + 5, 62, 24, 6, COL_MENU_DARK); + rb_text_c(rb, bx + (62 - tw("Salvar", FS_UI-1)) * 0.5f, WS_Y + 17, "Salvar", COL_WHITE, FS_UI-1); + bx += 74; + char pbuf[40]; + snprintf(pbuf, sizeof(pbuf), "%.30s", T->img_path[0] ? T->img_path : "sem arquivo"); + if (bx + tw(pbuf, FS_UI-1) < WS_X + WS_W - 260) + rb_text_c(rb, bx, WS_Y + 17, pbuf, COL_TEXT_DIM, FS_UI-1); + char info[128]; + snprintf(info, sizeof(info), "%s | camada %d/%d (%s) | %d%% | %d x %d px", + img_tool_tip(T->img_tool), T->img_layer_cur + 1, T->img_layer_n, + img_active(T) && img_active(T)->kind == IMG_L_VECTOR ? "vetor" : "raster", + (int)(T->img_zoom * 100.f + 0.5f), T->img_w, T->img_h); + rb_text_c(rb, WS_X + WS_W - 12 - tw(info, FS_UI-1), WS_Y + 17, info, COL_TEXT_DIM, FS_UI-1); + } + + /* --- area de desenho (sem limite: qualquer ponto pinta) --- */ + { + float ax, ay, aw, ah, dx, dy, dw, dh; + img_area(ed, &ax, &ay, &aw, &ah); + img_view(ed, T, &dx, &dy, &dw, &dh); + rb_fill_rect(rb, ax, ay, aw, ah, COL_PAINT_BG); + clip_set(ed, rb, ax, ay, aw, ah); + /* fundo xadrez para transparencia */ + for (int yy = 0; yy < (int)ah; yy += 16) + for (int xx = 0; xx < (int)aw; xx += 16) { + bool alt = ((xx / 16) + (yy / 16)) & 1; + rb_fill_rect(rb, ax + xx, ay + yy, 16, 16, alt ? COL_CHK_A : COL_CHK_B); + } + /* camadas (de baixo para cima) */ + for (int i = 0; i < T->img_layer_n; i++) { + if (!T->img_layers[i].visible || !T->img_layers[i].img) continue; + tb_draw_image(rb, dx, dy, dw, dh, T->img_layers[i].img); + } + /* selecao ativa: pixels flutuantes, contorno, alcas e botao excluir */ + if (T->img_sel.on) { + ImgSel* S = &T->img_sel; + float sx = dx + S->x * T->img_zoom, sy = dy + S->y * T->img_zoom; + float sw = S->w * T->img_zoom, sh = S->h * T->img_zoom; + if (S->buf) tb_draw_image(rb, sx, sy, sw, sh, S->buf); + for (float t = 0; t < sw; t += 9.f) { + float seg = sw - t < 5.f ? sw - t : 5.f; + rb_fill_rect(rb, sx + t, sy, seg, 1.f, COL_MENU); + rb_fill_rect(rb, sx + t, sy + sh - 1.f, seg, 1.f, COL_MENU); + } + for (float t = 0; t < sh; t += 9.f) { + float seg = sh - t < 5.f ? sh - t : 5.f; + rb_fill_rect(rb, sx, sy + t, 1.f, seg, COL_MENU); + rb_fill_rect(rb, sx + sw - 1.f, sy + t, 1.f, seg, COL_MENU); + } + for (int i = 0; i < 9; i++) { + if (i == 4) continue; + int hx, hy; + img_sel_handle_pt(T, i, &hx, &hy); + float px = dx + hx * T->img_zoom, py = dy + hy * T->img_zoom; + rb_fill_rect(rb, px - 4, py - 4, 9, 9, COL_WHITE); + rb_stroke_rect(rb, px - 4, py - 4, 9, 9, 1.4f, COL_MENU); + } + /* botao excluir (canto superior direito da selecao) */ + float bx2 = sx + sw - 11.f, by2 = sy + 11.f; + rb_fill_circle(rb, bx2, by2, 9.f, COL_WHITE); + rb_stroke_circle(rb, bx2, by2, 9.f, 1.4f, COL_MENU); + rb_text_c(rb, bx2 - tw("x", 12.f) * 0.5f, by2, "x", COL_MENU, 12.f); + } + /* borda da pagina */ + rb_stroke_rect(rb, dx - 1, dy - 1, dw + 2, dh + 2, 1.f, COL_PAINT_SHAD); + /* previa do traco em andamento */ + if (T->img_drag && (T->img_tool == IT_LINE || T->img_tool == IT_RECT || T->img_tool == IT_ELLIPSE)) { + float sx = dx + T->img_drag_x * T->img_zoom; + float sy = dy + T->img_drag_y * T->img_zoom; + float ex = ed->mouse_x, ey = ed->mouse_y; + if (T->img_tool == IT_LINE) rb_line(rb, sx, sy, ex, ey, 1.f, COL_MENU); + else if (T->img_tool == IT_RECT) + rb_stroke_rect(rb, sx < ex ? sx : ex, sy < ey ? sy : ey, + fabsf(ex - sx), fabsf(ey - sy), 1.f, COL_MENU); + else { + float ccx = (sx + ex) * 0.5f, ccy = (sy + ey) * 0.5f; + rb_stroke_circle(rb, ccx, ccy, fabsf(ex - sx) * 0.5f, 1.f, COL_MENU); + } + } + clip_clear(ed, rb); + rb_fill_rrect(rb, ax + 40, ay + ah - 10, aw - 80, 6, 3, COL_PAINT_SHAD); + } + + /* --- rodape: controles do desenho --- */ + { + float ax, ay, aw, ah, fy; + img_area(ed, &ax, &ay, &aw, &ah); + fy = img_foot_y(ed); + rb_fill_rect(rb, ax, fy, aw, IMG_FOOT_H, COL_PANEL); + rb_line(rb, ax, fy, WS_X + WS_W, fy, 1.f, COL_PAINT_LINE); + const char* labels[4] = { "Desfazer", "Limpar", "-", "+" }; + for (int i = 0; i < 4; i++) { + float bx, by, bw, bh; + img_foot_btn(ed, i, &bx, &by, &bw, &bh); + bool enabled = !(i == 0 && T->img_undo_n == 0); + bool hov = in_rect(ed->mouse_x, ed->mouse_y, bx, by, bw, bh); + rb_fill_rrect(rb, bx, by, bw, bh, 6, hov && enabled ? COL_HOVER : COL_PAINT_BTN); + rb_stroke_rect(rb, bx, by, bw, bh, 1.f, COL_PAINT_LINE); + rb_text_c(rb, bx + (bw - tw(labels[i], FS_UI-1)) * 0.5f, by + bh * 0.5f, + labels[i], enabled ? COL_TEXT : COL_TEXT_DIM, FS_UI - 1); + } + } + + /* --- coluna direita: cores (roda de matiz + saturacao/valor + paleta) --- */ + { + float px = img_color_x(ed); + float cx_, cy_, ro, ri; + rb_fill_rect(rb, px, WS_Y, IMG_RIGHT_W, WS_H, COL_PANEL); + rb_line(rb, px - 1, WS_Y, px - 1, WS_Y + WS_H, 1.f, COL_PAINT_LINE); + rb_text_c(rb, px + 12, WS_Y + 16, "Cores", COL_TEXT_DIM, 11.f); + + /* amostra da cor atual */ + { + Col cc = COLA(T->img_rgb[0], T->img_rgb[1], T->img_rgb[2], 255); + float sw = 30.f, sx = px + IMG_RIGHT_W - 14 - sw; + rb_fill_rrect(rb, sx, WS_Y + 5, sw, sw, 5, COL_PAINT_LINE); + rb_fill_rrect(rb, sx + 2, WS_Y + 7, sw - 4, sw - 4, 4, cc); + } + + /* roda de matiz: linhas radiais coloridas */ + img_wheel_rect(ed, &cx_, &cy_, &ro, &ri); + { + int seg = 144; + for (int i = 0; i < seg; i++) { + float a0 = (float)i / (float)seg * 6.2831853f; + Col hc = img_hsv_col((float)i / (float)seg * 360.f, 1.f, 1.f); + float cs = cosf(a0), sn = sinf(a0); + rb_line(rb, cx_ + cs * (ri + 2.f), cy_ + sn * (ri + 2.f), + cx_ + cs * (ro - 2.f), cy_ + sn * (ro - 2.f), 4.f, hc); + } + float am = T->img_hue / 360.f * 6.2831853f; + float mrx = cx_ + cosf(am) * (ri + ro) * 0.5f; + float mry = cy_ + sinf(am) * (ri + ro) * 0.5f; + rb_stroke_circle(rb, mrx, mry, 6.f, 3.f, COL_WHITE); + rb_stroke_circle(rb, mrx, mry, 6.f, 1.2f, COL_TEXT); + } + /* quadrado saturacao x valor (dentro da roda) */ + { + float sx, sy, sw2, sh2; + int n = 10; + img_sv_rect(ed, &sx, &sy, &sw2, &sh2); + for (int yy = 0; yy < n; yy++) + for (int xx = 0; xx < n; xx++) { + float s_ = (xx + 0.5f) / (float)n; + float v_ = 1.f - (yy + 0.5f) / (float)n; + Col c = img_hsv_col(T->img_hue, s_, v_); + rb_fill_rect(rb, sx + xx * sw2 / n, sy + yy * sh2 / n, + sw2 / n + 1.f, sh2 / n + 1.f, c); + } + rb_stroke_rect(rb, sx, sy, sw2, sh2, 1.f, COL_PAINT_LINE); + float mx_ = sx + T->img_sat * sw2; + float my_ = sy + (1.f - T->img_val) * sh2; + rb_stroke_circle(rb, mx_, my_, 5.f, 3.f, COL_WHITE); + rb_stroke_circle(rb, mx_, my_, 5.f, 1.2f, COL_TEXT); + } + /* paleta rapida (3 x 4) */ + rb_text_c(rb, px + 12, img_pal_y(ed) - 14, "Paleta", COL_TEXT_DIM, 10.f); + for (int i = 0; i < 12; i++) { + float sx, sy; + img_swatch_rect(ed, i, &sx, &sy); + bool hov = in_rect(ed->mouse_x, ed->mouse_y, sx, sy, 34, 22); + rb_fill_rrect(rb, sx, sy, 34, 22, 4, COL_PAINT_LINE); + rb_fill_rrect(rb, sx + 2, sy + 2, 30, 18, 3, IMG_PALETTE[i]); + if (i == T->img_swatch) rb_stroke_rect(rb, sx - 1, sy - 1, 36, 24, 2.f, COL_MENU); + else if (hov) rb_stroke_rect(rb, sx - 1, sy - 1, 36, 24, 1.4f, COL_TEXT_DIM); + } + /* informacao da cor escolhida */ + { + char inf[64]; + snprintf(inf, sizeof(inf), "#%02X%02X%02X", T->img_rgb[0], T->img_rgb[1], T->img_rgb[2]); + rb_text_c(rb, px + IMG_PAD, img_pal_y(ed) + 4 * 30 + 6, inf, COL_TEXT, FS_UI); + } + + /* ---- camadas: embaixo da roda de cores (como no Krita) ---- */ + rb_line(rb, px + IMG_PAD, img_layers_title_y(ed) - 14, + px + IMG_RIGHT_W - IMG_PAD, img_layers_title_y(ed) - 14, 1.f, COL_PAINT_LINE); + rb_text_c(rb, px + IMG_PAD, img_layers_title_y(ed), "Camadas", COL_TEXT_DIM, 11.f); + for (int i = 0; i < T->img_layer_n; i++) { + float rx, ry, rw, rh; + img_layer_row(ed, i, &rx, &ry, &rw, &rh); + bool sel = (i == T->img_layer_cur); + bool hov = in_rect(ed->mouse_x, ed->mouse_y, rx, ry, rw, rh); + rb_fill_rrect(rb, rx, ry, rw, rh, 6, sel ? COL_MENU : (hov ? COL_HOVER : COL_PAINT_BTN)); + rb_stroke_rect(rb, rx, ry, rw, rh, 1.f, sel ? COL_MENU_DARK : COL_PAINT_LINE); + Col tc = sel ? COL_WHITE : COL_TEXT; + /* olho (visibilidade) */ + if (T->img_layers[i].visible) rb_fill_circle(rb, rx + 11, ry + rh * 0.5f, 4.5f, tc); + else rb_stroke_circle(rb, rx + 11, ry + rh * 0.5f, 4.5f, 1.4f, tc); + /* miniatura (como uma fantasia do Scratch) */ + { + float tx = rx + 20, ty = ry + 4, tw_ = rw - 26, th_ = rh - 8; + rb_fill_rect(rb, tx, ty, tw_, th_ - 12, COL_WHITE); + rb_stroke_rect(rb, tx, ty, tw_, th_ - 12, 1.f, COL_PAINT_LINE); + TinyBlocks_Image* th = img_layer_thumb(T, i); + if (th) tb_draw_image(rb, tx + 1, ty + 1, tw_ - 2, th_ - 14, th); + Col bc = T->img_layers[i].kind == IMG_L_VECTOR ? COL_L_VECTOR : COL_L_RASTER; + rb_fill_rrect(rb, tx, ry + rh - 13, 13, 11, 3, bc); + rb_text_c(rb, tx + (13 - tw(T->img_layers[i].kind == IMG_L_VECTOR ? "V" : "R", 8.f)) * 0.5f, + ry + rh - 8, T->img_layers[i].kind == IMG_L_VECTOR ? "V" : "R", + COL_WHITE, 8.f); + char nm[28]; + snprintf(nm, sizeof(nm), "%.24s", T->img_layers[i].name[0] ? T->img_layers[i].name : "camada"); + rb_text_c(rb, tx + 17, ry + rh - 8, nm, tc, 9.5f); + } + } + /* botoes: excluir / nova raster / nova vetor */ + { + const char* labels[3] = { "- Camada", "+ Raster", "+ Vetor" }; + Col bgs[3] = { {236/255.f,120/255.f,110/255.f,1.f}, COL_MENU, COL_L_VECTOR }; + for (int i = 0; i < 3; i++) { + float bx2, by2, bw2, bh2; + img_side_btn(ed, i, &bx2, &by2, &bw2, &bh2); + bool enabled = !(i == 0 && T->img_layer_n <= 1); + bool hov = in_rect(ed->mouse_x, ed->mouse_y, bx2, by2, bw2, bh2); + Col bg = enabled ? (hov ? col_mul(bgs[i], 0.85f) : bgs[i]) : COL_PAINT_SHAD; + rb_fill_rrect(rb, bx2, by2, bw2, bh2, 6, bg); + rb_text_c(rb, bx2 + (bw2 - tw(labels[i], FS_UI-1)) * 0.5f, by2 + bh2 * 0.5f, + labels[i], COL_WHITE, FS_UI - 1); + } + } + } +} + +/* Entrada --------------------------------------------------------------- */ +static void img_clear_layer(Tab* T) { + ImgLayer* L = img_active(T); + if (!L || !L->img) return; + T->img_rev++; + int iw = tb_image_width(L->img), ih = tb_image_height(L->img); + for (int y = 0; y < ih; y++) + for (int x = 0; x < iw; x++) tb_image_set_pixel(L->img, x, y, 0, 0, 0, 0); +} + +bool tb_editor_image_click(Ed* ed, float mx, float my) { + Tab* T = &CT; + img_ensure(ed, T); + T->img_cdrag = 0; + + /* barra superior */ + float bx = WS_X + IMG_TOOL_W + 10; + if (my < WS_Y + IMG_BAR_H) { + if (mx >= bx && mx < bx + 62) { start_path(ed, PM_IMGLOAD, T->img_path[0] ? T->img_path : "imagem.png"); return true; } + if (mx >= bx + 70 && mx < bx + 132) { start_path(ed, PM_IMSAVE, T->img_path[0] ? T->img_path : "saida.png"); return true; } + return true; + } + /* coluna esquerda: ferramentas */ + if (mx < WS_X + IMG_TOOL_W) { + for (int i = 0; i < IT_N; i++) { + float tx, ty; + img_tool_rect(ed, i, &tx, &ty); + if (!in_rect(mx, my, tx, ty, IMG_TH, IMG_TH)) continue; + if (T->img_sel.on && i != IT_SEL) img_sel_commit(T); + T->img_tool = i; + return true; + } + return true; + } + /* coluna direita: camadas (embaixo) e cores (roda, saturacao/valor, paleta) */ + if (mx >= img_color_x(ed)) { + /* camadas */ + for (int i = 0; i < T->img_layer_n; i++) { + float rx, ry, rw, rh; + img_layer_row(ed, i, &rx, &ry, &rw, &rh); + if (!in_rect(mx, my, rx, ry, rw, rh)) continue; + if (mx < rx + 22) { T->img_layers[i].visible = !T->img_layers[i].visible; T->img_rev++; } + else if (T->img_layer_cur != i) { img_sel_commit(T); T->img_layer_cur = i; } + return true; + } + for (int i = 0; i < 3; i++) { + float sx, sy, sw, sh; + img_side_btn(ed, i, &sx, &sy, &sw, &sh); + if (!in_rect(mx, my, sx, sy, sw, sh)) continue; + if (i == 0) { + if (T->img_layer_n <= 1) return true; + img_undo_clear(T); + img_sel_reset(T); + T->img_rev++; + tb_image_release(T->img_layers[T->img_layer_cur].img); + if (T->img_layers[T->img_layer_cur].thumb) + tb_image_release(T->img_layers[T->img_layer_cur].thumb); + for (int k = T->img_layer_cur; k < T->img_layer_n - 1; k++) + T->img_layers[k] = T->img_layers[k + 1]; + T->img_layer_n--; + if (T->img_layer_cur >= T->img_layer_n) T->img_layer_cur = T->img_layer_n - 1; + snprintf(ed->hot_status, sizeof(ed->hot_status), "Camada removida"); + ed->hot_status_ok = true; + return true; + } + if (i == 1) { start_path(ed, PM_IMADDR, "camada.png"); return true; } + if (i == 2) { start_path(ed, PM_IMADDV, "camada.svg"); return true; } + } + float cx_, cy_, ro, ri; + img_wheel_rect(ed, &cx_, &cy_, &ro, &ri); + float dx = mx - cx_, dy = my - cy_; + float dist = sqrtf(dx * dx + dy * dy); + if (dist >= ri - 6.f && dist <= ro + 6.f) { + float ang = atan2f(dy, dx) * 57.2957795f; + if (ang < 0.f) ang += 360.f; + T->img_hue = ang; + img_hsv_apply(T); + T->img_cdrag = 1; + T->img_drag = 1; + ed->img_mx = mx; ed->img_my = my; + return true; + } + float sx, sy, sw2, sh2; + img_sv_rect(ed, &sx, &sy, &sw2, &sh2); + if (in_rect(mx, my, sx - 4, sy - 4, sw2 + 8, sh2 + 8)) { + float s_ = (mx - sx) / sw2, v_ = 1.f - (my - sy) / sh2; + T->img_sat = s_ < 0 ? 0 : (s_ > 1 ? 1 : s_); + T->img_val = v_ < 0 ? 0 : (v_ > 1 ? 1 : v_); + img_hsv_apply(T); + T->img_cdrag = 2; + T->img_drag = 1; + ed->img_mx = mx; ed->img_my = my; + return true; + } + for (int i = 0; i < 12; i++) { + float px2, py2; + img_swatch_rect(ed, i, &px2, &py2); + if (!in_rect(mx, my, px2, py2, 34, 22)) continue; + T->img_swatch = i; + T->img_rgb[0] = (int)(IMG_PALETTE[i].r * 255.f + 0.5f); + T->img_rgb[1] = (int)(IMG_PALETTE[i].g * 255.f + 0.5f); + T->img_rgb[2] = (int)(IMG_PALETTE[i].b * 255.f + 0.5f); + img_hsv_sync(T); + T->img_swatch = i; + return true; + } + return true; + } + /* rodape: botoes do desenho */ + float fy = img_foot_y(ed); + if (my >= fy) { + for (int i = 0; i < 4; i++) { + float rx, ry, rw, rh; + img_foot_btn(ed, i, &rx, &ry, &rw, &rh); + if (!in_rect(mx, my, rx, ry, rw, rh)) continue; + if (i == 0) { img_sel_reset(T); img_undo_do(T); return true; } + if (i == 1) { img_sel_reset(T); img_undo_push(T); img_clear_layer(T); return true; } + if (i == 2) { T->img_zoom *= 0.8f; if (T->img_zoom < 0.1f) T->img_zoom = 0.1f; return true; } + if (i == 3) { T->img_zoom *= 1.25f; if (T->img_zoom > 8.f) T->img_zoom = 8.f; return true; } + } + return true; + } + /* area de desenho */ + int px, py; + if (!img_pixel_at(ed, T, mx, my, &px, &py)) return true; + int r = T->img_rgb[0], g = T->img_rgb[1], b = T->img_rgb[2]; + if (T->img_tool == IT_PICK) { + int pr, pg, pb; + if (img_pick(T, px, py, &pr, &pg, &pb)) { + T->img_rgb[0] = pr; T->img_rgb[1] = pg; T->img_rgb[2] = pb; + img_hsv_sync(T); + T->img_swatch = -1; + snprintf(ed->hot_status, sizeof(ed->hot_status), "Cor do pixel: #%02X%02X%02X", pr, pg, pb); + ed->hot_status_ok = true; + } + return true; + } + if (T->img_tool == IT_FILL) { img_undo_push(T); img_flood(T, px, py, r, g, b); return true; } + if (T->img_tool == IT_SEL) { + ImgSel* S = &T->img_sel; + if (S->on) { + float dx, dy, dw, dh; + img_view(ed, T, &dx, &dy, &dw, &dh); + (void)dw; (void)dh; + float bxn = dx + (S->x + S->w) * T->img_zoom - 10.f; + float byn = dy + S->y * T->img_zoom + 10.f; + if ((mx - bxn) * (mx - bxn) + (my - byn) * (my - byn) <= 100.f) { + img_undo_push(T); + img_sel_reset(T); + T->img_rev++; + snprintf(ed->hot_status, sizeof(ed->hot_status), "Selecao apagada"); + ed->hot_status_ok = true; + return true; + } + } + int hnd = img_sel_handle_hit(ed, T, mx, my); + if (hnd >= 0) { + S->mode = 2; S->hnd = hnd; S->px = px; S->py = py; + T->img_drag = 1; ed->img_mx = mx; ed->img_my = my; + return true; + } + if (img_sel_inside(T, px, py)) { + S->mode = 1; S->px = px; S->py = py; + T->img_drag = 1; ed->img_mx = mx; ed->img_my = my; + return true; + } + img_sel_commit(T); + S->on = 1; + S->x = px; S->y = py; S->w = 1; S->h = 1; + S->ox = px; S->oy = py; + S->mode = 3; + T->img_drag = 1; ed->img_mx = mx; ed->img_my = my; + return true; + } + if (T->img_sel.on) img_sel_commit(T); + img_undo_push(T); + T->img_drag = 1; + T->img_drag_x = px; T->img_drag_y = py; + ed->img_mx = mx; ed->img_my = my; + if (T->img_tool == IT_BRUSH) img_put(T, px, py, r, g, b, 255); + if (T->img_tool == IT_ERASER) img_put(T, px, py, 0, 0, 0, 0); + return true; +} + +void tb_editor_image_drag(Ed* ed, float mx, float my) { + Tab* T = &CT; + if (!T->img_drag) return; + ed->img_mx = mx; ed->img_my = my; + /* arrasto na roda de cor / quadrado saturacao-valor */ + if (T->img_cdrag) { + float cx_, cy_, ro, ri, sx, sy, sw2, sh2; + img_wheel_rect(ed, &cx_, &cy_, &ro, &ri); + img_sv_rect(ed, &sx, &sy, &sw2, &sh2); + if (T->img_cdrag == 1) { + float ang = atan2f(my - cy_, mx - cx_) * 57.2957795f; + if (ang < 0.f) ang += 360.f; + T->img_hue = ang; + } else { + float s_ = (mx - sx) / sw2, v_ = 1.f - (my - sy) / sh2; + T->img_sat = s_ < 0 ? 0 : (s_ > 1 ? 1 : s_); + T->img_val = v_ < 0 ? 0 : (v_ > 1 ? 1 : v_); + } + img_hsv_apply(T); + return; + } + int px, py; + if (T->img_tool == IT_SEL && T->img_sel.mode) { + ImgSel* S = &T->img_sel; + if (!img_pixel_at(ed, T, mx, my, &px, &py)) return; + if (S->mode == 3) { + int x0 = S->ox < px ? S->ox : px, x1 = S->ox > px ? S->ox : px; + int y0 = S->oy < py ? S->oy : py, y1 = S->oy > py ? S->oy : py; + S->x = x0; S->y = y0; S->w = x1 - x0 + 1; S->h = y1 - y0 + 1; + } else if (S->mode == 1) { + S->x += px - S->px; + S->y += py - S->py; + S->px = px; S->py = py; + } else if (S->mode == 2) { + img_sel_resize(T, S->hnd, px, py); + S->px = px; S->py = py; + } + return; + } + if (T->img_tool == IT_BRUSH || T->img_tool == IT_ERASER) { + if (!img_pixel_at(ed, T, mx, my, &px, &py)) return; + int erase = (T->img_tool == IT_ERASER); + img_line(T, T->img_drag_x, T->img_drag_y, px, py, + erase ? 0 : T->img_rgb[0], erase ? 0 : T->img_rgb[1], erase ? 0 : T->img_rgb[2], + erase ? 0 : 255, 2); + T->img_drag_x = px; T->img_drag_y = py; + } +} + +void tb_editor_image_release(Ed* ed, float mx, float my) { + Tab* T = &CT; + if (!T->img_drag) return; + T->img_drag = 0; + if (T->img_cdrag) { T->img_cdrag = 0; return; } + if (T->img_tool == IT_SEL) { + ImgSel* S = &T->img_sel; + int mode = S->mode; + S->mode = 0; + if (mode == 3) { + if (S->w < 2 || S->h < 2) { img_sel_reset(T); return; } + img_sel_lift(T); + snprintf(ed->hot_status, sizeof(ed->hot_status), + "Selecao %d x %d px (arraste para mover, alcas para redimensionar)", + S->w, S->h); + ed->hot_status_ok = true; + } else if (mode == 1 || mode == 2) { + img_sel_commit(T); + } + return; + } + int px, py; + if (!img_pixel_at(ed, T, mx, my, &px, &py)) return; + int r = T->img_rgb[0], g = T->img_rgb[1], b = T->img_rgb[2]; + int x0 = T->img_drag_x, y0 = T->img_drag_y; + if (T->img_tool == IT_LINE) img_line(T, x0, y0, px, py, r, g, b, 255, 2); + else if (T->img_tool == IT_RECT) img_rect(T, x0, y0, px, py, r, g, b, 255, 2); + else if (T->img_tool == IT_ELLIPSE) img_ellipse(T, x0, y0, px, py, r, g, b, 255, 2); +} + +/* Carrega um arquivo. kind < 0 => documento novo; senao cria uma camada. */ +void tb_editor_image_load_file(Ed* ed, const char* path, int kind) { + Tab* T = &CT; + TinyBlocks_Image* im = tb_image_load(path); + if (!im) { + snprintf(ed->hot_status, sizeof(ed->hot_status), + "Nao consegui carregar '%.150s' (falta a library do formato?)", path); + ed->hot_status_ok = false; + return; + } + const char* base = strrchr(path, '/'); base = base ? base + 1 : path; + if (kind < 0) { /* abre como documento */ + img_doc_new(ed, T, tb_image_width(im), tb_image_height(im)); + img_undo_clear(T); + tb_image_release(T->img_layers[0].img); + T->img_layers[0].img = im; /* adota */ + T->img_layers[0].kind = IMG_L_RASTER; + T->img_layers[0].visible = 1; + scopy(T->img_layers[0].src, sizeof(T->img_layers[0].src), path); + scopy(T->img_layers[0].name, sizeof(T->img_layers[0].name), base); + scopy(T->img_path, sizeof(T->img_path), path); + scopy(T->name, sizeof(T->name), base); + T->img_zoom = 1.f; + snprintf(ed->hot_status, sizeof(ed->hot_status), "Imagem aberta: %.200s", path); + ed->hot_status_ok = true; + return; + } + /* camada nova, ajustada ao documento */ + int iw = tb_image_width(im), ih = tb_image_height(im); + if (T->img_layer_n == 0) img_doc_new(ed, T, iw, ih); + TinyBlocks_Image* lay = img_blank(T->img_w, T->img_h, 0, 0, 0, 0); + if (lay) { + for (int y = 0; y < ih && y < T->img_h; y++) + for (int x = 0; x < iw && x < T->img_w; x++) { + uint8_t r, g, b, a; + if (tb_image_get_pixel(im, x, y, &r, &g, &b, &a) && a) + tb_image_set_pixel(lay, x, y, r, g, b, a); + } + } + tb_image_release(im); + T->img_rev++; + if (img_layer_add(ed, T, kind, path, base, lay)) { + snprintf(ed->hot_status, sizeof(ed->hot_status), "%s '%.180s' como camada (%d)", + kind == IMG_L_VECTOR ? "SVG" : "Imagem", base, T->img_layer_n); + ed->hot_status_ok = true; + } +} + +void tb_editor_image_save(Ed* ed, const char* path) { + Tab* T = &CT; + img_ensure(ed, T); + TinyBlocks_Image* flat = tb_image_new(T->img_w, T->img_h, 4); + if (!flat) { ed->hot_status_ok = false; return; } + img_flatten(T, flat); + if (tb_image_save(flat, path)) { + scopy(T->img_path, sizeof(T->img_path), path); + snprintf(ed->hot_status, sizeof(ed->hot_status), "Imagem salva: %.200s", path); + ed->hot_status_ok = true; + } else { + snprintf(ed->hot_status, sizeof(ed->hot_status), + "Falha ao salvar '%.200s' (carregue a library do formato)", path); + ed->hot_status_ok = false; + } + tb_image_release(flat); +} + diff --git a/libraries/tinyblocks-editor/libraries/tinyblocks-editor-widgets/Makefile b/libraries/tinyblocks-editor/libraries/tinyblocks-editor-widgets/Makefile new file mode 100644 index 0000000..0a7a594 --- /dev/null +++ b/libraries/tinyblocks-editor/libraries/tinyblocks-editor-widgets/Makefile @@ -0,0 +1,31 @@ +# Makefile da library privada tinyblocks-editor-widgets +# Bundle "tinyblocks-editor": vem junto com o editor. +# Constroi build/libtinyblocks-editor-widgets.a e .so +CC := gcc +BUILD := build + +CFLAGS := -std=c11 -Wall -Wextra -pedantic \ + -D_POSIX_C_SOURCE=200809L \ + -I../../../../include -Iinclude -I../../../tinyblocks-graphics/include + +OBJS := $(BUILD)/tb_editor_widgets.o +LIB_A := $(BUILD)/libtinyblocks-editor-widgets.a +LIB_SO := $(BUILD)/libtinyblocks-editor-widgets.so + +.PHONY: all static shared clean +all: static shared +static: $(LIB_A) +shared: $(LIB_SO) + +$(BUILD)/tb_editor_widgets.o: src/tb_editor_widgets.c include/tb_editor_widgets.h + @mkdir -p $(BUILD) + $(CC) $(CFLAGS) -fPIC -c $< -o $@ + +$(LIB_A): $(OBJS) + ar rcs $@ $^ + +$(LIB_SO): $(OBJS) + $(CC) -shared -o $@ $^ + +clean: + $(RM) -r $(BUILD) diff --git a/libraries/tinyblocks-editor/libraries/tinyblocks-editor-widgets/include/tb_editor_widgets.h b/libraries/tinyblocks-editor/libraries/tinyblocks-editor-widgets/include/tb_editor_widgets.h new file mode 100644 index 0000000..6c6e5b4 --- /dev/null +++ b/libraries/tinyblocks-editor/libraries/tinyblocks-editor-widgets/include/tb_editor_widgets.h @@ -0,0 +1,46 @@ +/* + * TinyBlocks - tb_editor_widgets.h + * Library privada do editor: primitivas de desenho e "tema" (cores). + * + * E o tijolo mais baixo do editor: emite TinyBlocks_DrawCmd num + * TinyBlocks_RenderableBlock e nao guarda estado. Nao conhece o editor + * (Ed/Tab) nem o backend grafico, por isso pode ser usada por qualquer + * library do bundle do editor (blocos, imagem, codigo, dialogo...). + */ +#ifndef TB_EDITOR_WIDGETS_H +#define TB_EDITOR_WIDGETS_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Cor RGBA (0..1) */ +typedef struct { float r, g, b, a; } TbEwColor; + +#define TB_EW_RGB(r,g,b) {(r)/255.0f,(g)/255.0f,(b)/255.0f,1.0f} +#define TB_EW_RGBA(r,g,b,a) ((TbEwColor){(r)/255.0f,(g)/255.0f,(b)/255.0f,(a)/255.0f}) + +TbEwColor tb_ew_col_mul(TbEwColor c, float k); + +/* Primitivas: espelham tb_draw_* mas com TbEwColor */ +void tb_ew_fill_rect (TinyBlocks_RenderableBlock* rb, float x, float y, float w, float h, TbEwColor c); +void tb_ew_fill_rrect (TinyBlocks_RenderableBlock* rb, float x, float y, float w, float h, float rad, TbEwColor c); +void tb_ew_fill_circle(TinyBlocks_RenderableBlock* rb, float cx, float cy, float rad, TbEwColor c); +void tb_ew_stroke_rect(TinyBlocks_RenderableBlock* rb, float x, float y, float w, float h, float t, TbEwColor c); +void tb_ew_stroke_circle(TinyBlocks_RenderableBlock* rb, float cx, float cy, float rad, float t, TbEwColor c); +void tb_ew_line (TinyBlocks_RenderableBlock* rb, float x0, float y0, float x1, float y1, float w, TbEwColor c); +/* Texto alinhado a esquerda em x, centrado verticalmente em cy */ +void tb_ew_text_c (TinyBlocks_RenderableBlock* rb, float x, float cy, const char* s, TbEwColor c, float fs); +/* Largura real do texto, medida pelo backend grafico */ +float tb_ew_text_width(const char* s, float fs); + +bool tb_ew_in_rect(float mx, float my, float x, float y, float w, float h); + +#ifdef __cplusplus +} +#endif + +#endif /* TB_EDITOR_WIDGETS_H */ diff --git a/libraries/tinyblocks-editor/libraries/tinyblocks-editor-widgets/library.toml b/libraries/tinyblocks-editor/libraries/tinyblocks-editor-widgets/library.toml new file mode 100644 index 0000000..92ece36 --- /dev/null +++ b/libraries/tinyblocks-editor/libraries/tinyblocks-editor-widgets/library.toml @@ -0,0 +1,17 @@ +# Widgets privados do editor (bundle "tinyblocks-editor"). +[library] +name = "tinyblocks-editor-widgets" +bundle = "tinyblocks-editor" +private = true +version = "1.0.0" +category = "Editor" +description = "Primitivas de desenho e tema do editor" +color = [76, 151, 255, 255] +dark = [61, 121, 204, 255] + +[build] +sources = ["src/tb_editor_widgets.c"] +includes = ["include"] +shared = "build/libtinyblocks-editor-widgets.so" +static = "build/libtinyblocks-editor-widgets.a" +depends = [] diff --git a/libraries/tinyblocks-editor/libraries/tinyblocks-editor-widgets/src/tb_editor_widgets.c b/libraries/tinyblocks-editor/libraries/tinyblocks-editor-widgets/src/tb_editor_widgets.c new file mode 100644 index 0000000..9bf75ad --- /dev/null +++ b/libraries/tinyblocks-editor/libraries/tinyblocks-editor-widgets/src/tb_editor_widgets.c @@ -0,0 +1,44 @@ +/* + * TinyBlocks - tb_editor_widgets.c + * Implementacao das primitivas de desenho do editor. Sem estado: apenas + * traduz chamadas em TinyBlocks_DrawCmd. + */ +#include +#include +#include "tb_editor_widgets.h" + +TbEwColor tb_ew_col_mul(TbEwColor c, float k) { + TbEwColor r; + r.r = c.r * k; r.g = c.g * k; r.b = c.b * k; r.a = c.a; + return r; +} + +void tb_ew_fill_rect(TinyBlocks_RenderableBlock* rb, float x, float y, float w, float h, TbEwColor c) +{ tb_draw_fill_rect(rb, x, y, w, h, c.r, c.g, c.b, c.a); } + +void tb_ew_fill_rrect(TinyBlocks_RenderableBlock* rb, float x, float y, float w, float h, float rad, TbEwColor c) +{ tb_draw_fill_rrect(rb, x, y, w, h, rad < 0 ? 0 : rad, c.r, c.g, c.b, c.a); } + +void tb_ew_fill_circle(TinyBlocks_RenderableBlock* rb, float cx, float cy, float rad, TbEwColor c) +{ tb_draw_fill_circle(rb, cx, cy, rad, c.r, c.g, c.b, c.a); } + +void tb_ew_stroke_rect(TinyBlocks_RenderableBlock* rb, float x, float y, float w, float h, float t, TbEwColor c) +{ tb_draw_stroke_rect(rb, x, y, w, h, t, c.r, c.g, c.b, c.a); } + +void tb_ew_stroke_circle(TinyBlocks_RenderableBlock* rb, float cx, float cy, float rad, float t, TbEwColor c) +{ tb_draw_stroke_circle(rb, cx, cy, rad, t, c.r, c.g, c.b, c.a); } + +void tb_ew_line(TinyBlocks_RenderableBlock* rb, float x0, float y0, float x1, float y1, float w, TbEwColor c) +{ tb_draw_stroke_line(rb, x0, y0, x1, y1, w, c.r, c.g, c.b, c.a); } + +void tb_ew_text_c(TinyBlocks_RenderableBlock* rb, float x, float cy, const char* s, TbEwColor c, float fs) { + if (!s || !s[0]) return; + tb_draw_text(rb, x, cy + fs * 0.36f, s, fs, c.r, c.g, c.b, c.a); +} + +float tb_ew_text_width(const char* s, float fs) { + return tb_graphics_measure_text(s, fs); +} + +bool tb_ew_in_rect(float mx, float my, float x, float y, float w, float h) +{ return mx >= x && mx < x + w && my >= y && my < y + h; } diff --git a/libraries/tinyblocks-editor/library.toml b/libraries/tinyblocks-editor/library.toml index bf0087b..26b5f18 100644 --- a/libraries/tinyblocks-editor/library.toml +++ b/libraries/tinyblocks-editor/library.toml @@ -7,9 +7,12 @@ description = "Editor visual e blocos compostos" color = [255, 102, 128, 255] dark = [255, 51, 85, 255] +# O editor e um bundle: as libraries privadas em libraries/ vem junto. +bundle_members = ["tinyblocks-editor-widgets", "tinyblocks-editor-image"] + [build] sources = ["src/tb_editor.c", "src/tb_stage_widget.c"] includes = ["include"] shared = "build/libtinyblocks-editor.so" static = "build/libtinyblocks-editor.a" -depends = [] +depends = ["tinyblocks-editor-widgets", "tinyblocks-editor-image"] diff --git a/libraries/tinyblocks-editor/src/tb_editor.c b/libraries/tinyblocks-editor/src/tb_editor.c index 59a44a3..b7b0839 100644 --- a/libraries/tinyblocks-editor/src/tb_editor.c +++ b/libraries/tinyblocks-editor/src/tb_editor.c @@ -42,6 +42,7 @@ #include #include #include +#include #include "tb_stage_widget.h" #include "../include/tb_editor.h" @@ -58,500 +59,8 @@ 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 ===== [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 -#define TAB_H 36 -#define CAT_W 68 -#define FLY_W 250 -#define FLY_PAD 12 -#define FLY_BTN_W 150 -#define PALETTE_W (CAT_W + FLY_W) -#define STAGE_W 360 -#define STAGE_BAR_H 44 -#define PAL_Y (MENU_H + TAB_H) -#define WS_X PALETTE_W -#define WS_Y (MENU_H + TAB_H) -#define WIN_W (ed->win_w) -#define WIN_H (ed->win_h) -#define WS_W (ed->win_w - PALETTE_W - STAGE_W) -#define WS_H (ed->win_h - WS_Y) -#define TAB_W 150 -#define PLUS_W 28 +#include "../internal/tb_editor_internal.h" -/* Botoes de projeto no menu (geometria) */ -#define OPEN_BTN_X 150 -#define OPEN_BTN_W 64 -#define SAVE_BTN_X 218 -#define SAVE_BTN_W 70 -#define EXP_BTN_X 296 -#define EXP_BTN_W 84 -#define LIBM_BTN_X 388 -#define LIBM_BTN_W 104 -#define LIB_BTN_X 500 -#define LIB_BTN_W 200 - -/* Botao "Config" (settings) ancorado a direita do menu */ -#define CFG_BTN_W 78 -#define CFG_BTN_X (WIN_W - CFG_BTN_W - 10) - -/* Botao de buscar/adicionar library no fim da coluna de categorias */ -#define LIBMAN_BTN_H 56 - -/* == Geometria dos blocos === */ -#define FS 12 /* texto dos blocos */ -#define FS_UI 13 /* texto da interface */ -#define FS_SM 11 -#define BLK_GAP 5 /* espaço entre partes do rótulo */ -#define BLK_PAD 10 -#define ROW_MIN_STACK 36 -#define ROW_MIN_REP 24 -#define SLOT_MIN_H 20 -#define SLOT_MIN_W 28 -#define SLOT_LINE_H 15 -#define HAT_CAP 18 /* altura do "chapéu" acima da linha do rótulo */ -#define HAT_CAP_W 96 -#define ARM_W 16 /* braço esquerdo dos blocos C */ -#define BOT_H 22 /* braço inferior dos blocos C */ -#define MID_H 26 /* braço "senão" */ -#define MOUTH_MIN 22 -#define NOTCH_X 12 /* encaixe (macho) sob os comandos */ -#define NOTCH_W 18 -#define NOTCH_D 4 -#define PREVIEW_H 64 /* área de on_draw */ -#define PREVIEW_W 168 -#define SNAP_R 28.f - -#define MAX_WS 256 -#define MAX_INPUTS 16 -#define MAX_PARTS 40 -#define MAX_TABS 8 -#define MAX_FLY 192 -#define MAX_CATS 24 -#define MAX_CALL_DEPTH 32 -#define MAX_STEPS 500000L -#define MAX_RUN_BLOCKS 200000 -#define STAGE_BUF 16384 -#define LIT_TEXT_CAP 512 -#define MAX_HOT_TYPES 64 -#define MAX_USER_BLOCKS 16 -#define MAX_UBLK_SLOTS 8 -#define MAX_UBLK_PARTS 16 - -/* === - * Cores (paleta do Scratch 3) - componentes 0..1 - * === */ -typedef struct { float r,g,b,a; } Col; -#define C(r,g,b) {(r)/255.0f,(g)/255.0f,(b)/255.0f,1.0f} -#define COLA(r,g,b,a)((Col){(r)/255.0f,(g)/255.0f,(b)/255.0f,(a)/255.0f}) -static inline Col col_mul(Col c, float k) { return (Col){c.r*k,c.g*k,c.b*k,c.a}; } - -static const Col COL_MENU = C( 76,151,255); /* #4C97FF */ -static const Col COL_MENU_DARK = C( 61,121,204); -static const Col COL_UI_BG = C(229,240,255); /* #E5F0FF */ -static const Col COL_PANEL = C(255,255,255); -static const Col COL_FLY = C(249,249,249); -static const Col COL_WS_BG = C(249,249,249); -static const Col COL_GRID = C(221,221,221); -static const Col COL_BORDER = C(217,217,217); -static const Col COL_TEXT = C( 87, 94,117); /* #575E75 */ -static const Col COL_TEXT_DIM = C(150,155,175); -static const Col COL_TAB_OFF = C(217,227,242); -static const Col COL_HOVER = C(214,228,248); -static const Col COL_FLAG = C( 76,191, 86); /* #4CBF56 */ -static const Col COL_FLAG_DARK = C( 69,153, 61); -static const Col COL_STOP = C(236, 89, 89); /* #EC5959 */ -static const Col COL_STOP_DARK = C(184, 60, 60); -static const Col COL_WHITE = C(255,255,255); -static const Col COL_MISSING = C(170,170,170); -static const Col COL_EXT = C( 15,189,140); /* extensões */ -static const Col COL_EXT_DARK = C( 11,142,105); -static const Col COL_LIBBTN = C(255, 76, 76); /* botao de extensoes */ -static const Col COL_LIBBTN_DARK = C(211, 47, 47); -static const Col COL_VAR = C(255,140, 26); -static const Col COL_MON_BG = C(230,240,255); -static const Col COL_MON_BORDER = C(195,204,217); -static const Col COL_ERR_MENU = C(255,215,215); -static const Col COL_ERR_TEXT = C(204, 60, 60); - -/* == Categorias (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] = { - C(255,102,128), C( 76,151,255), C(153,102,255), C(207, 99,207), - C(255,191, 0), C(255,171, 25), C( 89,192, 89), C( 15,189,140), -}; - -/* == Rótulos dos blocos (%N - campo de entrada N) === */ -typedef struct { - const char* type; - const char* label; - const char* defs; /* valores iniciais dos campos, separados por '|' */ -} BlockSpec; - -static const BlockSpec s_specs[] = { - {"Events.WhenRun", "quando 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}, - {"Control.IfElse", "se %1 então", NULL}, - {"Operators.Lt", "%1 < %2", "|50"}, - {"Operators.Eq", "%1 = %2", "|50"}, - {"Operators.Gt", "%1 > %2", "|50"}, - {"Operators.And", "%1 e %2", NULL}, - {"Operators.Or", "%1 ou %2", NULL}, - {"Operators.Not", "não %1", NULL}, - {"Operators.Random", "número aleatório entre %1 e %2", "1|10"}, - {"Math.Add", "%1 + %2", NULL}, - {"Math.Sub", "%1 - %2", NULL}, - {"Math.Mul", "%1 * %2", NULL}, - {"Math.Div", "%1 / %2", NULL}, - {"Math.Mod", "resto de %1 por %2", NULL}, - {"Math.Abs", "valor absoluto de %1", NULL}, - {"Math.Max", "maior entre %1 e %2", NULL}, - {"Math.Min", "menor entre %1 e %2", NULL}, - {"Text.Concat", "junte %1 com %2", "maçã|banana"}, - {"Text.Length", "tamanho de %1", "maçã"}, - {"Literal.Text", "texto %1", NULL}, - {"Variables.Set", "mude %1 para %2", "x|0"}, - {"Variables.Change", "adicione %2 a %1", "x|1"}, - {"Variables.Get", "%1", "x"}, - {"IO.Print", "escreva %1 %2", "Olá!|"}, - {"IO.PrintInt", "escreva o número %1", NULL}, - {"Port.In", "parâmetro %1", "x"}, - {"Port.Out", "devolva %1 = %2", "resultado|"}, - {"Stage.Clear", "apague tudo", NULL}, - {"Stage.Background", "mude o fundo para r %1 g %2 b %3", "255|255|255"}, - {"Stage.PenColor", "mude a cor da caneta para r %1 g %2 b %3", "76|151|255"}, - {"Stage.PenSize", "mude o tamanho da caneta para %1", "4"}, - {"Stage.Line", "desenhe linha de x %1 y %2 até x %3 y %4", "-100|0|100|0"}, - {"Stage.Rect", "desenhe retângulo em x %1 y %2 largura %3 altura %4", "0|0|120|80"}, - {"Stage.Circle", "desenhe círculo em x %1 y %2 raio %3", "0|0|50"}, - {"Stage.Text", "escreva %1 no palco em x %2 y %3", "Olá!|-40|0"}, - /* Curvas (lista de pontos [x,y]) */ - {"Curves.Line", "reta de x %1 y %2 até x %3 y %4 com %5 passos", "0|0|100|0|20"}, - {"Curves.Bezier", "bezier de x %1 y %2 controles (%3,%4) (%5,%6) até x %7 y %8 com %9 passos", "0|0|0|80|100|80|100|0|20"}, - {"Curves.Quadratic", "curva quadrática de x %1 y %2 controle (%3,%4) até x %5 y %6 com %7 passos", "0|0|50|80|100|0|20"}, - {"Curves.Arc", "arco em (%1,%2) raio %3 de %4 a %5 graus com %6 passos", "0|0|50|0|180|24"}, - {"Curves.Circle", "círculo em (%1,%2) raio %3 com %4 passos", "0|0|50|36"}, - {"Curves.Count", "quantos pontos em %1", NULL}, - {"Curves.PointX", "x do ponto %2 de %1", "|0"}, - {"Curves.PointY", "y do ponto %2 de %1", "|0"}, - /* Base64 */ - {"Base64.Encode", "codifique em base64 %1", NULL}, - {"Base64.Decode", "decodifique base64 %1", NULL}, - /* Imagens PPM (tipo imagem do core) */ - {"PPM.Load", "carregue a imagem %1", "imagem.ppm"}, - {"PPM.Save", "grave a imagem %1 em %2", "|saida.ppm"}, - {"PPM.New", "nova imagem(%1 x %2) cor r %3 g %4 b %5", "32|32|255|0|0"}, - {"PPM.Width", "largura de %1", NULL}, - {"PPM.Height", "altura de %1", NULL}, - {"PPM.SetPixel", "pinte %1 em (%2,%3) de r %4 g %5 b %6", "|0|0|0|0|0"}, - {"PPM.GetPixel", "cor de %1 em (%2,%3)", "|0|0"}, - {"BMP.Load", "carregue o BMP %1", "imagem.bmp"}, - {"BMP.Save", "grave o BMP %1 em %2", "|saida.bmp"}, - {"PNG.Load", "carregue o PNG %1", "imagem.png"}, - {"PNG.Save", "grave o PNG %1 em %2", "|saida.png"}, - /* Imagem (ops genericas) */ - {"Image.New", "nova imagem(%1 x %2) cor r %3 g %4 b %5", "32|32|255|0|0"}, - {"Image.Width", "largura da imagem %1", NULL}, - {"Image.Height", "altura da imagem %1", NULL}, - {"Image.GetPixel", "cor da imagem %1 em (%2,%3)", "|0|0"}, - {"Image.SetPixel", "pinte a imagem %1 em (%2,%3) com r %4 g %5 b %6", "|0|0|0|0|0"}, - {"Image.Fill", "preencha a imagem %1 com r %2 g %3 b %4", "|255|255|255"}, - {"Image.Clone", "copie a imagem %1", NULL}, - {"Image.Crop", "recorte da imagem %1 em (%2,%3) tamanho %4 x %5", "|0|0|16|16"}, - {"Image.Scale", "escale a imagem %1 para %2 x %3", "|64|64"}, - {"Image.Load", "carregue a imagem %1", "imagem.png"}, - {"Image.Save", "grave a imagem %1 em %2", "|saida.png"}, - /* Vetor (vg) */ - {"VG.New", "novo desenho vetorial", NULL}, - {"VG.Line", "linha do vetor %1 de (%2,%3) a (%4,%5) cor r %6 g %7 b %8 esp %9", "|0|0|50|50|0|0|0|2"}, - {"VG.Rect", "retangulo no vetor %1 em (%2,%3) %4 x %5 cor r %6 g %7 b %8", "|0|0|40|40|255|0|0"}, - {"VG.Circle", "circulo no vetor %1 em (%2,%3) raio %4 cor r %5 g %6 b %7", "|20|20|15|0|0|255"}, - {"VG.Polygon", "poligono no vetor %1 pontos %2 fechar %3 cor r %4 g %5 b %6", "||1|0|255|0"}, - {"VG.Render", "rasterize o vetor %1 em %2 x %3 escala %4", "|64|64|1"}, - /* SVG */ - {"SVG.Parse", "interprete o SVG %1", NULL}, - {"SVG.Render", "desenhe o SVG %1 em %2 x %3", "|64|64"}, - {"SVG.Load", "carregue o SVG %1", "desenho.svg"}, -}; - -/* === - * Estruturas de dados - * === */ -typedef enum { SH_STACK, SH_HAT, SH_C1, SH_C2, SH_REPORTER, SH_BOOL } Shape; - -/* Relação de um bloco com o pai */ -#define REL_NONE (-1) -#define REL_NEXT 0 -#define REL_SUB0 1 /* REL_SUB0 + k: boca k de um bloco C */ -#define REL_ARG0 3 /* REL_ARG0 + i: campo de entrada i */ - -typedef struct { - int16_t arg; /* -1 = texto; senão índice do campo */ - int16_t len; - const char* txt; - float x, w; -} Part; - -typedef struct { - bool used; - bool dragging; - TinyBlocks_TypeBlock* type; - char type_name[64]; - float x, y; /* posição (só para o topo de uma pilha) */ - int parent, prel; - int next; - int sub[2]; - int args[MAX_INPUTS]; - char in_text[MAX_INPUTS][64]; - char lit_text[LIT_TEXT_CAP]; - - /* layout - recalculado a cada frame */ - float ax, ay, w, h; - float row_y, row_h, prev_y; - float sub_y[2], sub_h[2]; - float slot_x[MAX_INPUTS], slot_y[MAX_INPUTS], slot_w[MAX_INPUTS], slot_h[MAX_INPUTS]; - int part_n; - Part parts[MAX_PARTS]; - - TinyBlocks_Block* live_rt; /* última instância no runtime (não-owning) */ -} EdBlock; - -typedef struct { - EdBlock ws[MAX_WS]; - int top[MAX_WS]; /* pilhas de topo, em ordem de desenho */ - int top_n; - float ws_sx, ws_sy; - char name[48]; - bool is_composite; - int comp_id; - int color_idx; -} Tab; - -typedef enum { PARAM_NUM, PARAM_BOOL, PARAM_LABEL } ParamKind; -typedef struct { ParamKind kind; char name[32]; } UserParam; - -typedef struct { - char name[48]; - int input_count, output_count; - char input_names[MAX_UBLK_SLOTS][32]; - char output_names[MAX_UBLK_SLOTS][32]; - UserParam parts[MAX_UBLK_PARTS]; /* protótipo: entradas, booleanas e rótulos */ - int part_n; - Tab* snap; /* cópia da aba no momento do "Salvar" */ - TinyBlocks_TypeBlock* reg_type; - int tab_idx; - int color_idx; -} UserBlockDef; - -typedef struct { - UserBlockDef* def; - TinyBlocks_Value in[MAX_UBLK_SLOTS]; - TinyBlocks_Value out[MAX_UBLK_SLOTS]; -} CallFrame; - -typedef struct { char 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; - -typedef enum { ES_IDLE, ES_PRESS, ES_DRAG, ES_PAN } EdSt; -typedef enum { SN_NONE, SN_NEXT, SN_SUB, SN_ABOVE, SN_ARG } SnapKind; -enum { CM_DUPLICATE, CM_DELETE, CM_EDIT_DEF, CM_CLEANUP, CM_NEW_COMPOSITE, - CM_EXP_JSON, CM_EXP_XML, CM_EXP_CSV }; - -/* Modos da barra de caminho do menu (path_input) */ -enum { PM_NONE, PM_LIB, PM_LOAD, PM_SAVE, PM_EXP_JSON, PM_EXP_XML, PM_EXP_CSV }; - -/* Formatos de exportacao */ -enum { EX_JSON, EX_XML, EX_CSV }; - -typedef struct { - TinyBlocks* rt; - - 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; - float fly_scroll, fly_total_h; - - Tab tabs[MAX_TABS]; - int tab_n; - int cur_tab; - - UserBlockDef user_blocks[MAX_USER_BLOCKS]; - int user_block_n; - - char comp_name_buf[48]; - int comp_name_len; - - /* Diálogo modal "Criar um Bloco" (estilo Scratch) */ - bool comp_dialog_open; - int comp_dialog_def; /* -1 = novo; senão índice em user_blocks */ - bool comp_dialog_editing; /* true = edição de nome/rótulo em andamento */ - int comp_dialog_edit_part; /* índice da parte em edição, -1 = nome do bloco */ - char comp_dialog_name[48]; - UserParam comp_dialog_parts[MAX_UBLK_PARTS]; - int comp_dialog_part_n; - int comp_dialog_sel; /* parte selecionada (-1 = nenhuma) */ - int comp_dialog_color; - float comp_dialog_geom[MAX_UBLK_PARTS][2]; /* x,w desenhados (para hit test) */ - float comp_dialog_name_x, comp_dialog_name_w; - - bool ctx_menu_open; - bool ctx_export; /* menu de contexto aberto e o de exportacao */ - int ctx_menu_bi; - int ctx_menu_x, ctx_menu_y; - int ctx_menu_hover; - int ctx_items[8]; - int ctx_n; - - EdSt state; - int press_bi; - float press_mx, press_my; - int drag_bi; - float drag_ox, drag_oy; - SnapKind snap_kind; - int snap_bi, snap_idx; - float pan_mx, pan_my, pan_sx, pan_sy; - - bool editing; - int edit_bi, edit_in; - - int bubble_bi; - char bubble_text[128]; - TinyBlocks_JsonValue* bubble_json; /* lista de pontos (retida) ou NULL */ - TinyBlocks_Image* bubble_img; /* imagem (retida) ou NULL */ - int last_click_bi; - unsigned last_click_ms; - - char stage_buf[STAGE_BUF]; - - /* Execução */ - CallFrame frames[MAX_CALL_DEPTH]; - int frame_n; - long steps; - bool abort; - char abort_msg[160]; - TinyBlocks_Block** run_blocks; /* instâncias criadas na última execução */ - int run_n, run_cap; - Tab* live_tab; - FILE* cap_file; - int cap_saved; - - float mouse_x, mouse_y; - bool flag_hover, stop_hover, lib_hover, detach_hover; - - /* Palco: embutido no painel ou numa janela própria (Graphics.Window) */ - TinyBlocks_Block* stage; - TinyBlocks_Block* stage_win; - TinyBlocks_Block* stage_in; - - bool clip_on; - float clip[4]; - - int hot_check_frame; - char hot_status[256]; - bool hot_status_ok; - - bool path_input_active; - char path_input_buf[512]; - int path_input_len; - int 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; - - /* Configuracoes (settings) - store da tinyblocks-environ */ - bool settings_open; - int settings_sel; /* linha selecionada (-1 = nenhuma) */ - bool settings_path_focus; /* campo de caminho do CSV em foco */ - bool settings_use_env; /* caminho vindo de TINYBLOCKS_SETTINGS */ - bool settings_value_edit; /* editando o valor da linha sel. */ - bool settings_new_key; /* digitando o nome de uma nova chave */ - char settings_path[256]; - char settings_edit[256]; /* buffer do valor em edicao */ - char settings_key[64]; /* buffer da nova chave */ - int settings_scroll; - int settings_hover; - - int win_w, win_h; -} Ed; - -#define CT (ed->tabs[ed->cur_tab]) - -/* Ponteiro global para o editor ativo - os eval_fn dos blocos do editor - * (variáveis, compostos, portas) só recebem (self, rt). */ -static Ed* g_active_ed = NULL; - -static void bubble_clear(Ed* ed); - -static void palette_rebuild(Ed* ed); -static void utf8_pop(char* s); -static void append_text(char* dst, size_t cap, const char* add); -static void dlg_open(Ed* ed, int def_idx); -static void dlg_render(Ed* ed, TinyBlocks_RenderableBlock* rb); -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); -static bool hit_libman_foot(Ed* ed, float mx, float my); - -/* Configuracoes (settings) - UI desenhada pelo editor */ -static void settings_show(Ed* ed); -static void settings_click(Ed* ed, float mx, float my); -static void settings_key(Ed* ed, int sc, bool ctrl); -static void settings_text(Ed* ed, const char* typed); -static void settings_scroll_by(Ed* ed, float dy); -static void settings_render(Ed* ed, TinyBlocks_RenderableBlock* rb); - -/* === - * Helpers de desenho - emitem TinyBlocks_DrawCmd em um RenderableBlock - * === */ -static inline void rb_fill_rect(TinyBlocks_RenderableBlock* rb, float x,float y,float w,float h, Col c) -{ tb_draw_fill_rect(rb,x,y,w,h,c.r,c.g,c.b,c.a); } - -static inline void rb_fill_rrect(TinyBlocks_RenderableBlock* rb, float x,float y,float w,float h,float rad, Col c) -{ tb_draw_fill_rrect(rb,x,y,w,h,rad<0?0:rad,c.r,c.g,c.b,c.a); } - -static inline void rb_fill_circle(TinyBlocks_RenderableBlock* rb, float cx,float cy,float rad, Col c) -{ tb_draw_fill_circle(rb,cx,cy,rad,c.r,c.g,c.b,c.a); } - -static inline void rb_stroke_rect(TinyBlocks_RenderableBlock* rb, float x,float y,float w,float h,float t, Col c) -{ tb_draw_stroke_rect(rb,x,y,w,h,t,c.r,c.g,c.b,c.a); } - -static inline void rb_line(TinyBlocks_RenderableBlock* rb, float x0,float y0,float x1,float y1,float w, Col c) -{ tb_draw_stroke_line(rb,x0,y0,x1,y1,w,c.r,c.g,c.b,c.a); } /* Perninha (triangulo) do balao de previa, apontando para baixo. * bottom = linha de baixo da borda do balao. */ @@ -566,30 +75,21 @@ static void rb_bubble_tail(TinyBlocks_RenderableBlock* rb, float cx, float botto } } -static inline bool in_rect(float mx, float my, float x, float y, float w, float h) -{ return mx>=x && mx=y && myclip_on = true; ed->clip[0]=x; ed->clip[1]=y; ed->clip[2]=w; ed->clip[3]=h; tb_draw_set_clip(rb, x, y, w, h); } -static void clip_clear(Ed* ed, TinyBlocks_RenderableBlock* rb) { +TB_ED_API void clip_clear(Ed* ed, TinyBlocks_RenderableBlock* rb) { ed->clip_on = false; tb_draw_clear_clip(rb); } -static void clip_restore(Ed* ed, TinyBlocks_RenderableBlock* rb) { +TB_ED_API void clip_restore(Ed* ed, TinyBlocks_RenderableBlock* rb) { if (ed->clip_on) tb_draw_set_clip(rb, ed->clip[0], ed->clip[1], ed->clip[2], ed->clip[3]); else tb_draw_clear_clip(rb); } @@ -1627,7 +1127,7 @@ static void run_flag(Ed* ed) { } /* Libera o balão de resultado (texto + eventual lista de pontos) */ -static void bubble_clear(Ed* ed) { +void bubble_clear(Ed* ed) { if (ed->bubble_json) { tb_json_release(ed->bubble_json); ed->bubble_json = NULL; } if (ed->bubble_img) { tb_image_release(ed->bubble_img); ed->bubble_img = NULL; } ed->bubble_bi = -1; @@ -1885,7 +1385,7 @@ static void fly_add_block(Ed* ed, int cat, TinyBlocks_TypeBlock* t, const char* *y += h + 14; } -static void palette_rebuild(Ed* ed) { +void palette_rebuild(Ed* ed) { cats_rebuild(ed); memset(&ed->fly, 0, sizeof(ed->fly)); ed->fly_n = 0; @@ -1947,7 +1447,7 @@ static void tab_select(Ed* ed, int i) { palette_rebuild(ed); } -static bool tab_new(Ed* ed, const char* name, bool is_composite) { +bool tab_new_kind(Ed* ed, const char* name, bool is_composite, int kind) { if (ed->tab_n >= MAX_TABS) { snprintf(ed->hot_status, sizeof(ed->hot_status), "Limite de %d abas atingido", MAX_TABS); ed->hot_status_ok = false; @@ -1960,14 +1460,50 @@ static bool tab_new(Ed* ed, const char* name, bool is_composite) { else snprintf(T->name, sizeof(T->name), "Código %d", idx + 1); T->comp_id = -1; T->is_composite = is_composite; + T->kind = kind; + T->code_focus = -1; + T->img_tool = IT_BRUSH; + T->img_swatch = 2; + T->img_rgb[0] = 230; T->img_rgb[1] = 38; T->img_rgb[2] = 38; + T->img_zoom = 1.f; + T->img_layer_cur = -1; + if (kind == TK_IMAGE) img_ensure(ed, T); tab_select(ed, idx); return true; } +static bool tab_new(Ed* ed, const char* name, bool is_composite) { + return tab_new_kind(ed, name, is_composite, TK_BLOCKS); +} + +/* Libera os buffers de documento (codigo/imagem) de uma aba. */ +void tab_doc_free(Tab* T) { + if (!T) return; + free(T->code_text); T->code_text = NULL; T->code_len = T->code_cap = 0; + free(T->code_hl); T->code_hl = NULL; + if (T->code_toks) { + for (int i = 0; i < T->code_tok_n; i++) free(T->code_toks[i].text); + free(T->code_toks); T->code_toks = NULL; T->code_tok_n = 0; + } + for (int i = 0; i < T->img_undo_n; i++) tb_image_release(T->img_undo[i]); + T->img_undo_n = 0; + for (int i = 0; i < T->img_layer_n; i++) { + tb_image_release(T->img_layers[i].img); + if (T->img_layers[i].thumb) tb_image_release(T->img_layers[i].thumb); + T->img_layers[i].thumb = NULL; + } + T->img_layer_n = 0; + if (T->img_prev) { tb_image_release(T->img_prev); T->img_prev = NULL; } + img_sel_reset(T); +} + static void tab_close(Ed* ed, int ti) { if (ed->tab_n <= 1 || ti < 0 || ti >= ed->tab_n) return; run_reset(ed); + tab_doc_free(&ed->tabs[ti]); for (int i = ti; i < ed->tab_n - 1; i++) ed->tabs[i] = ed->tabs[i+1]; + memset(&ed->tabs[ed->tab_n - 1], 0, sizeof(Tab)); + ed->tabs[ed->tab_n - 1].code_focus = -1; ed->tab_n--; for (int u = 0; u < ed->user_block_n; u++) { int* t = &ed->user_blocks[u].tab_idx; @@ -2343,7 +1879,7 @@ static void dlg_card_rect(float* w, float* h) { *h = 88.f; } -static void dlg_open(Ed* ed, int def_idx) { +void dlg_open(Ed* ed, int def_idx) { ed->comp_dialog_open = true; ed->comp_dialog_def = def_idx; ed->comp_dialog_editing = false; @@ -2472,7 +2008,7 @@ static void dlg_ok(Ed* ed) { ed->hot_status_ok = true; } -static void dlg_render(Ed* ed, TinyBlocks_RenderableBlock* rb) { +void dlg_render(Ed* ed, TinyBlocks_RenderableBlock* rb) { if (!ed->comp_dialog_open) return; rb_fill_rect(rb, 0, 0, WIN_W, WIN_H, COLA(0, 0, 0, 120)); @@ -2593,7 +2129,7 @@ static void dlg_render(Ed* ed, TinyBlocks_RenderableBlock* rb) { rb_text_c(rb, okx + (84 - tw("OK", FS_UI)) * 0.5f, fy + 10, "OK", COL_WHITE, FS_UI); } -static bool dlg_click(Ed* ed, float mx, float my) { +bool dlg_click(Ed* ed, float mx, float my) { if (!ed->comp_dialog_open) return false; float dx = (WIN_W - DLG_W) * 0.5f, dy = (WIN_H - DLG_H) * 0.5f; if (!in_rect(mx, my, dx, dy, DLG_W, DLG_H)) { ed->comp_dialog_open = false; return true; } @@ -2640,7 +2176,7 @@ static bool dlg_click(Ed* ed, float mx, float my) { return true; } -static void dlg_key(Ed* ed, int sc) { +void dlg_key(Ed* ed, int sc) { if (sc == TB_KEY_ESCAPE) { ed->comp_dialog_open = false; return; } if (sc == TB_KEY_RETURN) { dlg_ok(ed); return; } if (ed->comp_dialog_editing && sc == TB_KEY_BACKSPACE) { @@ -2648,7 +2184,7 @@ static void dlg_key(Ed* ed, int sc) { } } -static void dlg_text(Ed* ed, const char* typed) { +void dlg_text(Ed* ed, const char* typed) { if (!ed->comp_dialog_editing) return; size_t cap; char* t = dlg_edit_target(ed, &cap); append_text(t, cap, typed); @@ -2670,10 +2206,11 @@ static bool hotlib_load(Ed* ed, const char* path) { return true; } -/* Hot reload: recarrega os .so cujo mtime mudou (delegado a tinyblocks-api). */ +/* Hot reload, delegado ao tinyblocks-api: + * - libraries privadas do editor (bundle): troca as tabelas de ponteiros; + * - libraries de blocos (extensoes): recarrega e revalida os tipos. */ static void hotlib_check(Ed* ed) { - if (++ed->hot_check_frame < 60) return; - ed->hot_check_frame = 0; + tb_ed_modules_check(ed); if (!tb_api_any_changed()) return; invalidate_types(ed); /* nenhum ponteiro de tipo pode sobreviver ao unload */ tb_api_poll_reload(); @@ -2747,13 +2284,26 @@ static void render_tab_bar(Ed* ed, TinyBlocks_RenderableBlock* rb) { if (ed->tabs[i].is_composite) { rb_fill_circle(rb, tx+14, cy, 5, s_user_colors[ed->tabs[i].color_idx]); lx = tx + 24; + } else if (ed->tabs[i].kind == TK_CODE) { + rb_fill_rrect(rb, tx+9, cy-6, 11, 13, 2, COLA(42,74,110,255)); + rb_fill_rect(rb, tx+11, cy-3, 6, 1.4f, COLA(120,190,255,255)); + rb_fill_rect(rb, tx+11, cy+0, 6, 1.4f, COLA(120,190,255,255)); + rb_fill_rect(rb, tx+11, cy+3, 4, 1.4f, COLA(120,190,255,255)); + lx = tx + 24; + } else if (ed->tabs[i].kind == TK_IMAGE) { + rb_fill_rrect(rb, tx+9, cy-6, 12, 12, 2, COLA(200,150,60,255)); + rb_fill_circle(rb, tx+13, cy-2, 2, COLA(255,235,180,255)); + lx = tx + 24; } rb_text_c(rb, lx, cy, ed->tabs[i].name, cur ? COL_MENU : COL_TEXT, FS_UI); if (ed->tab_n > 1) rb_text_c(rb, tx+TAB_W-22, cy, "=", COL_TEXT_DIM, FS_UI); } float px = 8 + ed->tab_n*TAB_W; - if (px + PLUS_W <= wbar && ed->tab_n < MAX_TABS) - rb_text_c(rb, px+8, y0 + 6 + (TAB_H-6)*0.5f, "+", COL_TEXT, 18); + if (px + PLUS_W <= wbar && ed->tab_n < MAX_TABS) { + float pcy = y0 + 6 + (TAB_H-6)*0.5f; + if (ed->plus_menu_open) rb_fill_circle(rb, px+13, pcy, 12, COL_HOVER); + rb_text_c(rb, px+8, pcy, "+", ed->plus_menu_open ? COL_MENU : COL_TEXT, 18); + } } static void render_categories(Ed* ed, TinyBlocks_RenderableBlock* rb) { @@ -2827,7 +2377,501 @@ static void render_snap(Ed* ed, TinyBlocks_RenderableBlock* rb, float ox, float rb_fill_rrect(rb, gx + ox, gy + oy, d->w, gh, 4, COLA(0,0,0,45)); } +/* ========================================================================== + * Abas de codigo e de imagem + tooltip de metadados de blocos + * ========================================================================== */ + +static Col col_from_hex(const char* h) { + if (!h || h[0] != '#') return COL_CODE_TEXT; + unsigned long v = strtoul(h + 1, NULL, 16); + return COLA((v >> 16) & 0xff, (v >> 8) & 0xff, v & 0xff, 255); +} + + +static char* decode_entities(const char* s, int n) { + char* out = (char*)malloc((size_t)n + 1); + if (!out) return NULL; + int k = 0; + for (int i = 0; i < n; ) { + if (s[i] == '&') { + if (!strncmp(s + i, "&", 5)) { out[k++] = '&'; i += 5; continue; } + if (!strncmp(s + i, "<", 4)) { out[k++] = '<'; i += 4; continue; } + if (!strncmp(s + i, ">", 4)) { out[k++] = '>'; i += 4; continue; } + if (!strncmp(s + i, """, 6)) { out[k++] = '"'; i += 6; continue; } + if (!strncmp(s + i, "'", 5)) { out[k++] = '\''; i += 5; continue; } + } + out[k++] = s[i++]; + } + out[k] = 0; + return out; +} + +/* -- Buffer de texto da aba de codigo ---------------------------------- */ +static bool code_reserve(Tab* T, int extra) { + if (T->code_len + extra + 1 <= T->code_cap) return true; + int cap = T->code_cap ? T->code_cap : 4096; + while (cap < T->code_len + extra + 1) cap *= 2; + char* p = (char*)realloc(T->code_text, (size_t)cap); + if (!p) return false; + T->code_text = p; T->code_cap = cap; + return true; +} +static void code_set_text(Tab* T, const char* s, int n) { + if (!code_reserve(T, n)) return; + if (n > 0 && s) memcpy(T->code_text, s, (size_t)n); + T->code_len = n; T->code_text[n] = 0; + T->code_hl_dirty = true; +} +static bool code_read_file(Tab* T, const char* path) { + FILE* f = fopen(path, "rb"); + if (!f) return false; + fseek(f, 0, SEEK_END); + long sz = ftell(f); + fseek(f, 0, SEEK_SET); + if (sz < 0) sz = 0; + if (!code_reserve(T, (int)sz)) { fclose(f); return false; } + size_t rd = fread(T->code_text, 1, (size_t)sz, f); + fclose(f); + T->code_len = (int)rd; T->code_text[T->code_len] = 0; + T->code_hl_dirty = true; + return true; +} +static bool code_write_file(Tab* T, const char* path) { + FILE* f = fopen(path, "wb"); + if (!f) return false; + if (T->code_len > 0) fwrite(T->code_text, 1, (size_t)T->code_len, f); + fclose(f); + return true; +} +static int code_line_count(Tab* T) { + if (!T->code_text) return 1; + int n = 1; + for (int i = 0; i < T->code_len; i++) if (T->code_text[i] == '\n') n++; + return n; +} +static void code_line_col(Tab* T, int off, int* line, int* col) { + int ln = 0, cs = 0; + if (off > T->code_len) off = T->code_len; + for (int i = 0; i < off; i++) if (T->code_text[i] == '\n') { ln++; cs = i + 1; } + if (line) *line = ln; + if (col) *col = off - cs; +} +static int code_line_start(Tab* T, int line) { + if (line <= 0) return 0; + int ln = 0; + for (int i = 0; i < T->code_len; i++) + if (T->code_text[i] == '\n') { ln++; if (ln == line) return i + 1; } + return T->code_len; +} +static int code_line_len(Tab* T, int line) { + int s = code_line_start(T, line), e = s; + while (e < T->code_len && T->code_text[e] != '\n') e++; + return e - s; +} +static void code_insert(Tab* T, const char* s, int n) { + if (n <= 0 || !s) return; + if (!code_reserve(T, n)) return; + memmove(T->code_text + T->code_caret + n, T->code_text + T->code_caret, + (size_t)(T->code_len - T->code_caret)); + memcpy(T->code_text + T->code_caret, s, (size_t)n); + T->code_len += n; T->code_text[T->code_len] = 0; T->code_caret += n; + T->code_hl_dirty = true; +} +static void code_erase(Tab* T, int from, int to) { + if (from < 0) from = 0; + if (to > T->code_len) to = T->code_len; + if (to <= from) return; + memmove(T->code_text + from, T->code_text + to, (size_t)(T->code_len - to)); + T->code_len -= (to - from); T->code_text[T->code_len] = 0; + if (T->code_caret > from) { + T->code_caret -= (to - from); + if (T->code_caret < from) T->code_caret = from; + } + T->code_hl_dirty = true; +} +static int code_prev_char(Tab* T, int off) { + if (off <= 0) return 0; + off--; + while (off > 0 && ((unsigned char)T->code_text[off] & 0xC0) == 0x80) off--; + return off; +} +static int code_next_char(Tab* T, int off) { + if (off >= T->code_len) return T->code_len; + off++; + while (off < T->code_len && ((unsigned char)T->code_text[off] & 0xC0) == 0x80) off++; + return off; +} + +static void code_toks_free(Tab* T) { + for (int i = 0; i < T->code_tok_n; i++) free(T->code_toks[i].text); + free(T->code_toks); T->code_toks = NULL; T->code_tok_n = 0; +} + +/* Realca o texto (via tinyblocks-syntax) e extrai os trechos coloridos. */ +void code_rehighlight(Tab* T) { + code_toks_free(T); + free(T->code_hl); T->code_hl = NULL; + T->code_hl_dirty = false; + if (!T->code_text) return; + T->code_hl = tb_syntax_highlight(T->code_text, T->code_lang); + if (!T->code_hl) return; + + int cap = 128, n = 0; + CodeTok* v = (CodeTok*)malloc(sizeof(CodeTok) * (size_t)cap); + if (!v) return; + const char* p = T->code_hl; + int line = -1; + int pend_start = -1; + /* emite o texto "solto" (fora de ) preservando indentacao */ + #define FLUSH_PEND() do { \ + if (pend_start >= 0) { \ + int plen = (int)(p - T->code_hl) - pend_start; \ + if (plen > 0 && line >= 0) { \ + char* txt = decode_entities(T->code_hl + pend_start, plen); \ + if (txt) { \ + int wl = (int)strlen(txt); \ + while (wl > 0 && (txt[wl-1] == '\n' || txt[wl-1] == '\r')) txt[--wl] = 0; \ + if (wl > 0) { \ + if (n == cap) { cap *= 2; v = (CodeTok*)realloc(v, sizeof(CodeTok) * (size_t)cap); } \ + v[n].line = line; \ + snprintf(v[n].color, sizeof(v[n].color), "#d4d4d4"); \ + v[n].text = txt; n++; \ + } else free(txt); \ + } \ + } \ + pend_start = -1; \ + } \ + } while (0) + + while (*p) { + if (*p == '<') { + if (!strncmp(p, "", 6)) { FLUSH_PEND(); p += 6; line++; continue; } + if (!strncmp(p, "", 7)) { FLUSH_PEND(); p += 7; continue; } + if (!strncmp(p, "'); + if (!gt) break; + char col[12] = "#d4d4d4"; + const char* c = strstr(p, "color=\""); + if (c && c < gt) { + c += 7; size_t k = 0; + while (*c && *c != '"' && k < sizeof(col) - 1) col[k++] = *c++; + col[k] = 0; + } + const char* e = strstr(gt + 1, ""); + if (!e) break; + char* txt = decode_entities(gt + 1, (int)(e - (gt + 1))); + if (txt) { + if (n == cap) { cap *= 2; v = (CodeTok*)realloc(v, sizeof(CodeTok) * (size_t)cap); } + v[n].line = line < 0 ? 0 : line; + snprintf(v[n].color, sizeof(v[n].color), "%s", col); + v[n].text = txt; n++; + } + p = e + 4; continue; + } + if (!strncmp(p, "", 4)) { p += 4; continue; } + if (!strncmp(p, "'); + p = gt ? gt + 1 : p + 5; + continue; + } + p++; continue; + } + if (pend_start < 0) pend_start = (int)(p - T->code_hl); + p++; + } + FLUSH_PEND(); + #undef FLUSH_PEND + T->code_toks = v; T->code_tok_n = n; +} + +/* Rola para deixar `line` (1-based) visivel. */ +static void code_scroll_to(Ed* ed, Tab* T, int line) { + int view = (int)((WS_H - CODE_PAD_Y * 2) / CODE_LINE_H); + if (view < 1) view = 1; + int ln = line - 1; + if (ln < T->code_scroll) T->code_scroll = ln; + if (ln > T->code_scroll + view - 3) T->code_scroll = ln - view + 3; + if (T->code_scroll < 0) T->code_scroll = 0; + (void)ed; +} + +void open_code_at(Ed* ed, const char* file, int line) { + char path[1200]; + if (!tb_meta_resolve_file(file, path, sizeof(path))) { + snprintf(ed->hot_status, sizeof(ed->hot_status), "Nao encontrei o arquivo-fonte: %.200s", file); + ed->hot_status_ok = false; + return; + } + for (int i = 0; i < ed->tab_n; i++) { + if (ed->tabs[i].kind == TK_CODE && !strcmp(ed->tabs[i].code_path, path)) { + tab_select(ed, i); + if (line > 0) { CT.code_focus = line; code_scroll_to(ed, &CT, line); } + return; + } + } + if (ed->tab_n >= MAX_TABS) { + snprintf(ed->hot_status, sizeof(ed->hot_status), "Limite de %d abas atingido", MAX_TABS); + ed->hot_status_ok = false; + return; + } + int idx = ed->tab_n; + if (!tab_new_kind(ed, NULL, false, TK_CODE)) return; + Tab* T = &ed->tabs[idx]; + scopy(T->code_path, sizeof(T->code_path), path); + const char* base = strrchr(path, '/'); base = base ? base + 1 : path; + scopy(T->name, sizeof(T->name), base); + scopy(T->code_lang, sizeof(T->code_lang), tb_syntax_normalize_lang(path)); + if (!code_read_file(T, path)) { + snprintf(ed->hot_status, sizeof(ed->hot_status), "Nao consegui abrir %.200s", path); + ed->hot_status_ok = false; + } + T->code_caret = 0; T->code_scroll = 0; T->code_hl_dirty = true; + T->code_focus = line > 0 ? line : -1; + if (line > 0) code_scroll_to(ed, T, line); +} + +/* -- Render da aba de codigo ------------------------------------------- */ +void render_code_tab(Ed* ed, TinyBlocks_RenderableBlock* rb) { + Tab* T = &CT; + const float x0 = WS_X, y0 = WS_Y; + const float w = WS_W, h = WS_H; + rb_fill_rect(rb, x0, y0, w, h, COL_CODE_BG); + + /* barra superior (arquivo / linguagem / salvar) */ + const float barh = 30; + rb_fill_rect(rb, x0, y0, w, barh, COL_CODE_BAR); + rb_line(rb, x0, y0 + barh, x0 + w, y0 + barh, 1.f, COL_TIP_BORDER); + char title[320]; + snprintf(title, sizeof(title), "%s", T->code_path[0] ? T->code_path : (T->name[0] ? T->name : "sem titulo")); + rb_text_c(rb, x0 + 10, y0 + barh * 0.5f, title, COL_CODE_TEXT, FS_UI - 2); + float lw = tw(T->code_lang, FS_UI - 2); + rb_fill_rrect(rb, x0 + w - lw - 26, y0 + 5, lw + 16, 20, 5, COL_TIP_BORDER); + rb_text_c(rb, x0 + w - lw - 18, y0 + barh * 0.5f, T->code_lang, COL_TIP_LINK, FS_UI - 2); + rb_text_c(rb, x0 + w - lw - 26 - 62, y0 + barh * 0.5f, "Salvar", COL_CODE_TEXT, FS_UI - 2); + + if (T->code_hl_dirty) code_rehighlight(T); + + const int lh = CODE_LINE_H; + const float cy0 = y0 + barh; + const int total = code_line_count(T); + int view = (int)((h - barh) / lh); + if (view < 1) view = 1; + if (T->code_scroll > total - 1) T->code_scroll = total - 1; + if (T->code_scroll < 0) T->code_scroll = 0; + + rb_fill_rect(rb, x0, cy0, CODE_GUTTER_W, h - barh, COL_CODE_GUTTER); + rb_line(rb, x0 + CODE_GUTTER_W - 1, cy0, x0 + CODE_GUTTER_W - 1, y0 + h, 1.f, COL_TIP_BORDER); + clip_set(ed, rb, x0, cy0, w, h - barh); + + int caret_line = 0, caret_col = 0; + code_line_col(T, T->code_caret, &caret_line, &caret_col); + (void)caret_col; + + int ti = 0; + while (ti < T->code_tok_n && T->code_toks[ti].line < T->code_scroll) ti++; + + for (int li = T->code_scroll; li < T->code_scroll + view && li < total; li++) { + float ly = cy0 + (li - T->code_scroll) * lh; + if (li == caret_line) rb_fill_rect(rb, x0, ly, w, lh, COL_CODE_CURLINE); + if (T->code_focus == li + 1) rb_fill_rect(rb, x0, ly, w, lh, COL_CODE_FOCUS); + char nb[16]; snprintf(nb, sizeof(nb), "%d", li + 1); + float nw = tw(nb, 11); + rb_text_c(rb, x0 + CODE_GUTTER_W - 8 - nw, ly + lh * 0.5f, nb, COL_TEXT_DIM, 11); + + float tx = x0 + CODE_GUTTER_W + CODE_PAD_X; + while (ti < T->code_tok_n && T->code_toks[ti].line == li) { + Col c = col_from_hex(T->code_toks[ti].color); + rb_text_c(rb, tx, ly + lh * 0.5f, T->code_toks[ti].text, c, CODE_FS); + tx += tw(T->code_toks[ti].text, CODE_FS); + ti++; + } + /* cursor (barra vertical) */ + if (li == caret_line && ed->state == ES_IDLE) { + int ls = code_line_start(T, li); + char tmp[1024]; + int cl = T->code_caret - ls; + if (cl > 0) { + if (cl > (int)sizeof(tmp) - 1) cl = (int)sizeof(tmp) - 1; + memcpy(tmp, T->code_text + ls, (size_t)cl); + while (cl > 0 && tmp[cl-1] == '\n') cl--; + tmp[cl] = 0; + rb_fill_rect(rb, x0 + CODE_GUTTER_W + CODE_PAD_X + tw(tmp, CODE_FS), ly + 2, 1.6f, lh - 4, COL_WHITE); + } else { + rb_fill_rect(rb, x0 + CODE_GUTTER_W + CODE_PAD_X, ly + 2, 1.6f, lh - 4, COL_WHITE); + } + } + } + clip_clear(ed, rb); + (void)ed; +} + +/* -- Entrada (mouse/teclado) da aba de codigo -------------------------- */ +bool code_click(Ed* ed, float mx, float my) { + Tab* T = &CT; + const float barh = 30; + if (my < WS_Y + barh) { + float lw = tw(T->code_lang, FS_UI - 2); + if (mx >= WS_X + WS_W - lw - 26) { + /* clica na linguagem: cicla */ + int cnt = tb_syntax_language_count(); + int cur = -1; + for (int i = 0; i < cnt; i++) + if (!strcmp(tb_syntax_language_name(i), T->code_lang)) cur = i; + snprintf(T->code_lang, sizeof(T->code_lang), "%s", tb_syntax_language_name((cur + 1) % cnt)); + T->code_hl_dirty = true; + return true; + } + if (mx >= WS_X + WS_W - lw - 26 - 62) + { start_path(ed, PM_CODESAVE, T->code_path[0] ? T->code_path : "arquivo.c"); return true; } + return true; + } + if (T->code_hl_dirty) code_rehighlight(T); + int li = T->code_scroll + (int)((my - (WS_Y + barh)) / CODE_LINE_H); + int total = code_line_count(T); + if (li < 0) li = 0; + if (li >= total) li = total - 1; + int ls = code_line_start(T, li); + int ll = code_line_len(T, li); + float cx = WS_X + CODE_GUTTER_W + CODE_PAD_X; + int col = 0; + char tmp[1024]; + while (col < ll && cx + tw("M", CODE_FS) * 0.5f < mx) { + int step = 1; + if (col + step > ll) break; + int n2 = col + step > (int)sizeof(tmp) - 1 ? (int)sizeof(tmp) - 1 - col : step; + memcpy(tmp, T->code_text + ls + col, (size_t)n2); + tmp[n2] = 0; + cx += tw(tmp, CODE_FS); + col += n2; + } + T->code_caret = ls + col; + T->code_focus = -1; + return true; +} + +bool code_key(Ed* ed, int sc, bool ctrl) { + Tab* T = &CT; + if (sc == TB_KEY_ESCAPE) { T->code_focus = -1; bubble_clear(ed); return true; } + if (ctrl) { + if (sc == (TB_KEY_A + ('s' - 'a'))) { + start_path(ed, PM_CODESAVE, T->code_path[0] ? T->code_path : "arquivo.c"); + return true; + } + if (sc == (TB_KEY_A + ('o' - 'a'))) { start_path(ed, PM_CODELOAD, "arquivo.c"); return true; } + return false; + } + if (sc == TB_KEY_RETURN) { + int l2 = 0; code_line_col(T, T->code_caret, &l2, NULL); + int ls = code_line_start(T, l2); + int indent = 0; + while (ls + indent < T->code_len && (T->code_text[ls+indent] == ' ' || T->code_text[ls+indent] == '\t')) indent++; + code_insert(T, "\n", 1); + for (int i = 0; i < indent; i++) code_insert(T, " ", 1); + return true; + } + if (sc == TB_KEY_BACKSPACE) { + if (T->code_caret > 0) code_erase(T, code_prev_char(T, T->code_caret), T->code_caret); + return true; + } + if (sc == TB_KEY_DELETE) { + if (T->code_caret < T->code_len) code_erase(T, T->code_caret, code_next_char(T, T->code_caret)); + return true; + } + if (sc == TB_KEY_TAB) { + code_insert(T, " ", 4); + return true; + } + { int l2 = 0, c2 = 0; code_line_col(T, T->code_caret, &l2, &c2); + if (sc == TB_KEY_LEFT) { T->code_caret = code_prev_char(T, T->code_caret); T->code_focus = -1; return true; } + if (sc == TB_KEY_RIGHT) { T->code_caret = code_next_char(T, T->code_caret); T->code_focus = -1; return true; } + if (sc == TB_KEY_HOME) { T->code_caret -= c2; T->code_focus = -1; return true; } + if (sc == TB_KEY_END) { T->code_caret += (code_line_len(T, l2) - c2); T->code_focus = -1; return true; } + if (sc == TB_KEY_UP) { if (l2 > 0) { int p = code_line_len(T, l2-1); T->code_caret = code_line_start(T, l2-1) + (c2 < p ? c2 : p); } T->code_focus = -1; return true; } + if (sc == TB_KEY_DOWN) { if (l2 < code_line_count(T)-1) { int p = code_line_len(T, l2+1); T->code_caret = code_line_start(T, l2+1) + (c2 < p ? c2 : p); } T->code_focus = -1; return true; } + } + return false; +} + +bool code_text(Ed* ed, const char* typed) { + (void)ed; + code_insert(&CT, typed, (int)strlen(typed)); + return true; +} + +/* A aba de imagem vive em libraries/tinyblocks-editor-image (bundle do editor). */ +/* -- Menu do botao "+" -------------------------------------------------- */ +static void plus_menu_pos(Ed* ed, float* px, float* py) { + *px = 8 + ed->tab_n * TAB_W; + *py = MENU_H + TAB_H - 2; +} + +void render_plus_menu(Ed* ed, TinyBlocks_RenderableBlock* rb) { + if (!ed->plus_menu_open) return; + float px, py; + plus_menu_pos(ed, &px, &py); + const int n = 3; + float h = 26 + n * PLUS_MENU_ITEM_H + 6; + rb_fill_rrect(rb, px - 2, py + 2, PLUS_MENU_W + 4, h + 4, 10, COLA(0,0,0,40)); + rb_fill_rrect(rb, px, py, PLUS_MENU_W, h, 8, COL_PANEL); + rb_stroke_rect(rb, px, py, PLUS_MENU_W, h, 1.f, COL_BORDER); + rb_text_c(rb, px + 12, py + 13, "Nova aba", COL_TEXT_DIM, 11.f); + const char* labels[3] = { "Blueprint", "Edicao de Imagem", "Editor de Codigo" }; + const char* subs[3] = { "montar um bloco novo", "editar SVG/imagem", "editar .c/.py/..." }; + static const Col dots[3] = {{0.30f,0.62f,1.f,1.f}, {0.98f,0.62f,0.25f,1.f}, {0.42f,0.72f,0.35f,1.f}}; + for (int i = 0; i < n; i++) { + float iy = py + 26 + i * PLUS_MENU_ITEM_H; + bool hov = ed->plus_menu_hover == i; + if (hov) rb_fill_rrect(rb, px + 4, iy, PLUS_MENU_W - 8, PLUS_MENU_ITEM_H - 2, 6, COL_HOVER); + rb_fill_circle(rb, px + 20, iy + PLUS_MENU_ITEM_H * 0.5f - 1, 6, dots[i]); + rb_text_c(rb, px + 36, iy + 12, labels[i], COL_TEXT, FS_UI - 1); + rb_text_c(rb, px + 36, iy + 25, subs[i], COL_TEXT_DIM, 10.f); + } +} + +/* -- Tooltip de metadados (Alt + hover) --------------------------------- */ +void render_tooltip(Ed* ed, TinyBlocks_RenderableBlock* rb) { + if (!ed->tip_open) return; + float x = ed->tip_x, y = ed->tip_y, w = ed->tip_w, h = ed->tip_h; + rb_fill_rrect(rb, x + 2, y + 3, w, h, 6, COLA(0,0,0,60)); + rb_fill_rrect(rb, x, y, w, h, 5, COL_TIP_BG); + rb_stroke_rect(rb, x, y, w, h, 1.f, COL_TIP_BORDER); + float ty = y + 12; + rb_text_c(rb, x + 12, ty, ed->tip_title, COL_CODE_TEXT, 12.f); + ty += 18; + rb_text_c(rb, x + 12, ty, ed->tip_loc, COL_TIP_LINK, 11.f); + ty += 16; + if (ed->tip_doc[0]) { + rb_text_c(rb, x + 12, ty, ed->tip_doc, COL_TEXT_DIM, 11.f); + ty += 16; + } + /* previa do codigo (clicavel) */ + ed->tip_prev_y = ty + 2; + rb_fill_rect(rb, x + 6, ed->tip_prev_y - 2, w - 12, ed->tip_prev_h + 4, COLA(0,0,0,45)); + float ly = ed->tip_prev_y; + const char* p = ed->tip_preview; + char line[256]; + int ln = 1; + while (*p && ln <= 8) { + const char* nl = strchr(p, '\n'); + size_t n = nl ? (size_t)(nl - p) : strlen(p); + if (n > sizeof(line) - 1) n = sizeof(line) - 1; + memcpy(line, p, n); line[n] = 0; + char pre[16]; + snprintf(pre, sizeof(pre), "%d", ed->tip_line + ln - 1); + rb_text_c(rb, x + 12, ly, pre, COL_TEXT_DIM, 10.f); + rb_text_c(rb, x + 12 + 30, ly, line, COL_CODE_TEXT, 11.f); + ly += 14; + ln++; + if (!nl) break; + p = nl + 1; + } + rb_text_c(rb, x + 12, y + h - 8, "clique para abrir o codigo nesta linha", COL_TEXT_DIM, 9.f); +} + static void render_workspace(Ed* ed, TinyBlocks_RenderableBlock* rb) { + if (CT.kind == TK_CODE) { render_code_tab(ed, rb); return; } + if (CT.kind == TK_IMAGE) { render_image_tab(ed, rb); return; } float ox = WS_X - CT.ws_sx, oy = WS_Y - CT.ws_sy; rb_fill_rect(rb, WS_X, WS_Y, WS_W, WS_H, COL_WS_BG); clip_set(ed, rb, WS_X, WS_Y, WS_W, WS_H); @@ -3111,11 +3155,11 @@ static void libman_close(Ed* ed) { ed->libman_search_focus = false; } -static bool hit_libman_foot(Ed* ed, float mx, float my) { +bool hit_libman_foot(Ed* ed, float mx, float my) { return mx < CAT_W && my >= WIN_H - LIBMAN_BTN_H; } -static void libman_show(Ed* ed) { +void libman_show(Ed* ed) { ed->libman_open = true; ed->libman_query[0] = 0; ed->libman_query_len = 0; @@ -3161,7 +3205,7 @@ 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) { +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); @@ -3240,7 +3284,7 @@ static void libman_render(Ed* ed, TinyBlocks_RenderableBlock* rb) { 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) { +void libman_click(Ed* ed, float mx, float my) { if (my < LM_HEAD_H) { if (mx < 170) libman_close(ed); return; @@ -3286,7 +3330,7 @@ static void libman_click(Ed* ed, float mx, float my) { } } -static void libman_key(Ed* ed, int sc) { +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]) { @@ -3296,13 +3340,13 @@ static void libman_key(Ed* ed, int sc) { } } -static void libman_text(Ed* ed, const char* typed) { +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) { +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); @@ -3340,7 +3384,7 @@ static void settings_sync_path(Ed* ed) { tb_environ_config_path(ed->settings_path, sizeof(ed->settings_path)); } -static void settings_show(Ed* ed) { +void settings_show(Ed* ed) { ed->settings_open = true; ed->settings_sel = -1; ed->settings_path_focus = false; @@ -3398,7 +3442,7 @@ static void settings_row_rect(Ed* ed, int i, float* x, float* y, float* w, float *w = WIN_W - 2.f * ST_MARGIN; *h = ST_ROW_H; } -static void settings_render(Ed* ed, TinyBlocks_RenderableBlock* rb) { +void settings_render(Ed* ed, TinyBlocks_RenderableBlock* rb) { if (!ed->settings_open) return; int n = tb_environ_count(); @@ -3497,7 +3541,7 @@ static void settings_render(Ed* ed, TinyBlocks_RenderableBlock* rb) { ed->hot_status_ok ? COL_TEXT_DIM : COL_ERR_MENU, FS_SM); } -static void settings_click(Ed* ed, float mx, float my) { +void settings_click(Ed* ed, float mx, float my) { if (my < ST_HEAD_H) { if (mx < 170) settings_close(ed); return; } if (my < ST_OPT_Y + ST_OPT_H) { @@ -3549,7 +3593,7 @@ static void settings_click(Ed* ed, float mx, float my) { ed->settings_value_edit = false; } -static void settings_key(Ed* ed, int sc, bool ctrl) { +void settings_key(Ed* ed, int sc, bool ctrl) { (void)ctrl; bool enter = sc == TB_KEY_RETURN; if (sc == TB_KEY_ESCAPE) { @@ -3592,13 +3636,13 @@ static void settings_key(Ed* ed, int sc, bool ctrl) { } } -static void settings_text(Ed* ed, const char* typed) { +void settings_text(Ed* ed, const char* typed) { if (ed->settings_new_key) append_text(ed->settings_key, sizeof(ed->settings_key), typed); else if (ed->settings_value_edit) append_text(ed->settings_edit, sizeof(ed->settings_edit), typed); else if (ed->settings_path_focus) append_text(ed->settings_path, sizeof(ed->settings_path), typed); } -static void settings_scroll_by(Ed* ed, float dy) { +void settings_scroll_by(Ed* ed, float dy) { ed->settings_scroll -= (int)(dy * 48.f); int off = ed->settings_new_key ? 1 : 0; int content = (tb_environ_count() + off) * ST_ROW_H + 24; @@ -3703,7 +3747,7 @@ static void cleanup_ws(Ed* ed) { /* === * Edição de texto * === */ -static void utf8_pop(char* s) { +void utf8_pop(char* s) { size_t n = strlen(s); while (n > 0) { n--; @@ -3712,7 +3756,7 @@ static void utf8_pop(char* s) { s[n] = 0; } -static void append_text(char* dst, size_t cap, const char* add) { +void append_text(char* dst, size_t cap, const char* add) { size_t n = strlen(dst), a = strlen(add); if (n + a < cap) memcpy(dst + n, add, a + 1); } @@ -3759,7 +3803,7 @@ static bool hit_export_btn(float mx, float my) { return in_rect(mx, my, EXP_BT static bool hit_libman_btn(float mx, float my) { return in_rect(mx, my, LIBM_BTN_X, 0, LIBM_BTN_W, MENU_H); } static bool hit_settings_btn(Ed* ed, float mx, float my) { return in_rect(mx, my, CFG_BTN_X, 0, CFG_BTN_W, MENU_H); } -static void start_path(Ed* ed, int mode, const char* def) { +TB_ED_API void start_path(Ed* ed, int mode, const char* def) { ed->path_input_active = true; ed->path_mode = mode; snprintf(ed->path_input_buf, sizeof(ed->path_input_buf), "%s", def ? def : ""); @@ -3854,6 +3898,32 @@ static void on_lmb_down(Ed* ed, float mx, float my) { if (ed->settings_open) { settings_click(ed, mx, my); return; } if (ed->libman_open) { libman_click(ed, mx, my); return; } if (ed->comp_dialog_open) { dlg_click(ed, mx, my); return; } + if (ed->plus_menu_open) { + float px, py; + plus_menu_pos(ed, &px, &py); + int hit = -1; + for (int i = 0; i < 3; i++) + if (in_rect(mx, my, px, py + 26 + i * PLUS_MENU_ITEM_H, PLUS_MENU_W, PLUS_MENU_ITEM_H)) hit = i; + ed->plus_menu_open = false; + if (hit == 0) { dlg_open(ed, -1); return; } + if (hit == 1) { tab_new_kind(ed, "Imagem", false, TK_IMAGE); palette_rebuild(ed); return; } + if (hit == 2) { + tab_new_kind(ed, "Sem titulo", false, TK_CODE); + snprintf(CT.code_lang, sizeof(CT.code_lang), "c"); + code_set_text(&CT, "", 0); + CT.code_hl_dirty = true; + palette_rebuild(ed); + return; + } + } + if (ed->tip_open) { + if (in_rect(mx, my, ed->tip_x, ed->tip_y, ed->tip_w, ed->tip_h)) { + open_code_at(ed, ed->tip_file, ed->tip_line); + ed->tip_open = false; + return; + } + ed->tip_open = false; + } if (ed->ctx_menu_open) { int it = ctx_hit(ed, mx, my); ed->ctx_menu_open = false; @@ -3905,7 +3975,7 @@ static void on_lmb_down(Ed* ed, float mx, float my) { return; } float px = 8 + ed->tab_n*TAB_W; - if (in_rect(mx, my, px, MENU_H, PLUS_W, TAB_H)) tab_new(ed, NULL, false); + if (in_rect(mx, my, px, MENU_H, PLUS_W, TAB_H)) ed->plus_menu_open = !ed->plus_menu_open; return; } @@ -3946,6 +4016,12 @@ static void on_lmb_down(Ed* ed, float mx, float my) { return; } + /* Abas de codigo / imagem */ + if (mx >= WS_X && mx < WIN_W - STAGE_W && my >= WS_Y) { + if (CT.kind == TK_CODE) { ed->editing = false; code_click(ed, mx, my); return; } + if (CT.kind == TK_IMAGE) { image_click(ed, mx, my); return; } + } + /* Workspace */ float wx = mx - WS_X + CT.ws_sx, wy = my - WS_Y + CT.ws_sy; int bi = hit_ws(&CT, wx, wy); @@ -3967,8 +4043,8 @@ static void on_lmb_down(Ed* ed, float mx, float my) { } static void on_lmb_up(Ed* ed, float mx, float my) { - (void)my; if (ed->comp_dialog_open) return; + if (CT.kind == TK_IMAGE && CT.img_drag) { image_release(ed, mx, my); ed->state = ES_IDLE; return; } if (ed->state == ES_DRAG && ed->drag_bi >= 0) { mark_drag(&CT, ed->drag_bi, false); if (mx < PALETTE_W) free_tree(ed, &CT, ed->drag_bi); /* solto na paleta = apagar */ @@ -4032,6 +4108,25 @@ static void on_key(Ed* ed, int sc, bool ctrl) { case PM_EXP_JSON: project_export(ed, p, EX_JSON); break; case PM_EXP_XML: project_export(ed, p, EX_XML); break; case PM_EXP_CSV: project_export(ed, p, EX_CSV); break; + case PM_IMGLOAD: if (CT.kind == TK_IMAGE) img_load_file(ed, p, -1); break; + case PM_IMSAVE: if (CT.kind == TK_IMAGE) img_save_out(ed, p); break; + case PM_IMADDR: if (CT.kind == TK_IMAGE) img_load_file(ed, p, IMG_L_RASTER); break; + case PM_IMADDV: if (CT.kind == TK_IMAGE) img_load_file(ed, p, IMG_L_VECTOR); break; + case PM_CODELOAD: { + if (CT.kind == TK_CODE) { + scopy(CT.code_path, sizeof(CT.code_path), p); + const char* b = strrchr(p, '/'); b = b ? b + 1 : p; + scopy(CT.name, sizeof(CT.name), b); + scopy(CT.code_lang, sizeof(CT.code_lang), tb_syntax_normalize_lang(p)); + if (!code_read_file(&CT, p)) { + snprintf(ed->hot_status, sizeof(ed->hot_status), "Nao consegui abrir %.200s", p); + ed->hot_status_ok = false; + } + CT.code_hl_dirty = true; + } + break; + } + case PM_CODESAVE: if (CT.kind == TK_CODE) { code_write_file(&CT, p); snprintf(ed->hot_status, sizeof(ed->hot_status), "Salvo: %.200s", p); ed->hot_status_ok = true; } break; default: hotlib_load(ed, p); break; } } @@ -4043,6 +4138,17 @@ static void on_key(Ed* ed, int sc, bool ctrl) { } return; } + if (CT.kind == TK_IMAGE && CT.img_sel.on) { + if (sc == TB_KEY_DELETE || sc == TB_KEY_BACKSPACE) { + img_sel_reset(&CT); + CT.img_rev++; + snprintf(ed->hot_status, sizeof(ed->hot_status), "Selecao apagada"); + ed->hot_status_ok = true; + return; + } + if (sc == TB_KEY_ESCAPE) { img_sel_commit(&CT); return; } + } + if (CT.kind == TK_CODE && code_key(ed, sc, ctrl)) return; if (ed->editing) { size_t cap; char* t = edit_target(ed, &cap); bool multi = is_lit_text(CT.ws[ed->edit_bi].type); @@ -4077,12 +4183,84 @@ static void on_text(Ed* ed, const char* typed) { if (ed->path_input_active) { append_text(ed->path_input_buf, sizeof(ed->path_input_buf), typed); ed->path_input_len = (int)strlen(ed->path_input_buf); + } else if (CT.kind == TK_CODE) { + code_text(ed, typed); } else if (ed->editing) { size_t cap; char* t = edit_target(ed, &cap); append_text(t, cap, typed); } } +/* === + * Tooltip de metadados: Alt + hover sobre um bloco da area de scripts + * === */ +static void update_tooltip(Ed* ed, bool alt) { + if (ed->tip_open) { + /* mantem aberto enquanto o mouse estiver sobre o tooltip ... */ + if (in_rect(ed->mouse_x, ed->mouse_y, ed->tip_x, ed->tip_y, ed->tip_w, ed->tip_h)) return; + /* ... ou sobre o proprio bloco de origem (permite soltar o Alt e clicar) */ + if (CT.kind == TK_BLOCKS && ed->tip_bi >= 0 && ed->tip_bi < MAX_WS && CT.ws[ed->tip_bi].used) { + int hb = hit_ws(&CT, ed->mouse_x - WS_X + CT.ws_sx, ed->mouse_y - WS_Y + CT.ws_sy); + if (hb == ed->tip_bi) return; + } + } + ed->tip_open = false; + if (!alt) return; + if (CT.kind != TK_BLOCKS) return; + if (ed->state != ES_IDLE) return; + float mx = ed->mouse_x, my = ed->mouse_y; + if (mx < WS_X || mx >= WIN_W - STAGE_W || my < WS_Y) return; + int bi = hit_ws(&CT, mx - WS_X + CT.ws_sx, my - WS_Y + CT.ws_sy); + if (bi < 0) return; + EdBlock* b = &CT.ws[bi]; + const TinyBlocks_BlockMeta* m = tb_meta_find(b->type_name); + if (!m) return; + + int line = tb_meta_line(m); + if (line < 1) line = 1; + char path[1200]; + path[0] = 0; + tb_meta_resolve_file(m->file, path, sizeof(path)); + snprintf(ed->tip_loc, sizeof(ed->tip_loc), "%.280s:%d", + path[0] ? path : (m->file ? m->file : "?"), line); + scopy(ed->tip_doc, sizeof(ed->tip_doc), m->doc ? m->doc : ""); + scopy(ed->tip_file, sizeof(ed->tip_file), m->file ? m->file : ""); + scopy(ed->tip_title, sizeof(ed->tip_title), m->func_name ? m->func_name : "?"); + ed->tip_preview[0] = 0; + ed->tip_line = line; + + char buf[900]; + int got = tb_meta_read_lines(m, line, 8, buf, sizeof(buf)); + if (got > 0) { + const char* nl = strchr(buf, '\n'); + size_t t = nl ? (size_t)(nl - buf) : strlen(buf); + while (t > 0 && (buf[t-1] == ' ' || buf[t-1] == '\t')) t--; + const char* st = buf; + while (st < buf + t && (*st == ' ' || *st == '\t')) st++; + snprintf(ed->tip_title, sizeof(ed->tip_title), "%.*s", (int)(t - (size_t)(st - buf)), st); + if (nl) scopy(ed->tip_preview, sizeof(ed->tip_preview), nl + 1); + } + + int prev_lines = 0; + if (ed->tip_preview[0]) { + prev_lines = 1; + for (const char* p = ed->tip_preview; *p; p++) if (*p == '\n') prev_lines++; + } + ed->tip_w = 600; + ed->tip_prev_h = (float)(prev_lines * 14 + 8); + ed->tip_h = 12 + 18 + 16 + (ed->tip_doc[0] ? 16.f : 0.f) + + 2 + ed->tip_prev_h + 16; + float bx = WS_X - CT.ws_sx + b->ax + b->w + 14; + float by = WS_Y - CT.ws_sy + b->ay - 6; + if (bx + ed->tip_w > WIN_W - 8) bx = WIN_W - ed->tip_w - 8; + if (bx < WS_X + 4) bx = WS_X + 4; + if (by + ed->tip_h > WIN_H - 8) by = WIN_H - ed->tip_h - 8; + if (by < WS_Y + 4) by = WS_Y + 4; + ed->tip_x = bx; ed->tip_y = by; + ed->tip_bi = bi; + ed->tip_open = true; +} + /* === * editor_eval - lê um snapshot de Graphics.Input por frame e atualiza o estado * === */ @@ -4115,6 +4293,17 @@ 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; + ed->plus_menu_hover = -1; + if (ed->plus_menu_open) { + float px, py; + plus_menu_pos(ed, &px, &py); + for (int i = 0; i < 3; i++) + if (in_rect(mx, my, px, py + 26 + i * PLUS_MENU_ITEM_H, PLUS_MENU_W, PLUS_MENU_ITEM_H)) + ed->plus_menu_hover = i; + } + + update_tooltip(ed, (ev_int(evb, GFX_IN_MOD_STATE) & TB_MOD_ALT) != 0); + /* == Movimento === */ if (ed->state == ES_PRESS && fabsf(mx - ed->press_mx) + fabsf(my - ed->press_my) > 4.f) start_drag(ed); @@ -4129,6 +4318,8 @@ static void editor_eval(TinyBlocks_Block* self, TinyBlocks* rt) { CT.ws_sx = ed->pan_sx - (mx - ed->pan_mx); CT.ws_sy = ed->pan_sy - (my - ed->pan_my); } + if (CT.kind == TK_IMAGE && CT.img_drag && (mx != ed->img_mx || my != ed->img_my)) + image_drag(ed, mx, my); /* == Scroll === */ double sdx = ev_real(evb, GFX_IN_SCROLL_DX); @@ -4138,6 +4329,9 @@ static void editor_eval(TinyBlocks_Block* self, TinyBlocks* rt) { settings_scroll_by(ed, (float)sdy); } else if (ed->libman_open) { libman_scroll_by(ed, (float)sdy); + } else if (CT.kind == TK_CODE && mx >= WS_X && mx < WIN_W - STAGE_W && my >= WS_Y) { + CT.code_scroll -= (int)sdy * 3; + if (CT.code_scroll < 0) CT.code_scroll = 0; } 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; @@ -4166,8 +4360,9 @@ static void editor_eval(TinyBlocks_Block* self, TinyBlocks* rt) { const char* typed = ev_text(evb, GFX_IN_TEXT); if (typed[0]) on_text(ed, typed); - /* Verifica mtime das libs vigiadas a cada ~60 frames (~1s) */ - if (++ed->hot_check_frame >= 60) { + /* Hot reload: checa os .so a cada ~30 frames (~0,5 s). + Usa o watcher (inotify) do tinyblocks-api; mtime como reserva. */ + if (++ed->hot_check_frame >= 30) { ed->hot_check_frame = 0; hotlib_check(ed); } @@ -4199,6 +4394,8 @@ static bool editor_on_draw(TinyBlocks_Block* self, TinyBlocks* rt, if (ed->state == ES_DRAG && ed->drag_bi >= 0) render_chain(ed, rb, &CT, ed->drag_bi, WS_X - CT.ws_sx, WS_Y - CT.ws_sy); + render_plus_menu(ed, rb); + render_tooltip(ed, rb); render_ctx_menu(ed, rb); dlg_render(ed, rb); libman_render(ed, rb); /* tela cheia: por cima de tudo */ @@ -4270,6 +4467,7 @@ static bool editor_instance_init(TinyBlocks_Block* self, TinyBlocks* rt) { "Clique num bloco para executá-lo sozinho.\n"); strcpy(ed->hot_status, "Abrir/Salvar projeto no menu; Ctrl+O ou arraste um .so"); ed->hot_status_ok = true; + (void)0; *(Ed**)self->userdata = ed; g_active_ed = ed; @@ -4277,6 +4475,16 @@ static bool editor_instance_init(TinyBlocks_Block* self, TinyBlocks* rt) { TinyBlocks_TypeBlock* t_stage = tb_type_block_find(rt, "Editor.Stage"); if (t_stage) ed->stage = tb_block_create(rt, t_stage); + /* Libraries privadas do editor (bundle) por dlopen ANTES de qualquer + desenho: as primitivas (tb_ed_w) vem daqui. Permite hot reload. */ + ed->mods.n = 0; + tb_ed_modules_load(ed); + + if (ed->mods.info[0] && !ed->mods.loaded) { + snprintf(ed->hot_status, sizeof(ed->hot_status), "%s", ed->mods.info); + ed->hot_status_ok = false; + } + 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 */ @@ -4303,6 +4511,7 @@ static void editor_instance_deinit(TinyBlocks_Block* self, TinyBlocks* rt) { * registradas no runtime: a fase 1 do tinyblocks_deinit já as destrói = * aqui só soltamos o que é do editor. */ bubble_clear(ed); + for (int i = 0; i < ed->tab_n; i++) tab_doc_free(&ed->tabs[i]); free(ed->run_blocks); for (int u = 0; u < ed->user_block_n; u++) free(ed->user_blocks[u].snap); tb_libman_shutdown(); diff --git a/libraries/tinyblocks-editor/src/tb_editor_modules.c b/libraries/tinyblocks-editor/src/tb_editor_modules.c new file mode 100644 index 0000000..450f2b0 --- /dev/null +++ b/libraries/tinyblocks-editor/src/tb_editor_modules.c @@ -0,0 +1,209 @@ +/* + * TinyBlocks - tb_editor_modules.c + * Carrega as libraries privadas do editor (bundle) por dlopen, usando o + * tinyblocks-api como gestor de modulos, para permitir HOT RELOAD: + * + * 1. edite uma library privada (ex: libraries/tinyblocks-editor-image) + * 2. rode "make" (so a parte que mudou e recompilada) + * 3. o editor em execucao detecta (inotify/mtime) e recarrega sozinho + * + * O estado da interface vive em Ed/Tab (no editor), entao trocar o codigo + * nao perde nada. As chamadas passam por tabelas de ponteiros (tb_ed_w, + * tb_ed_img), por isso a troca vale imediatamente para o editor inteiro. + */ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include +#include + +#include "../internal/tb_editor_internal.h" + +/* Este arquivo nomeia os campos das tabelas (w.fill_rect, ...), entao os + apelidos curtos do editor atrapalham: remove-os aqui. */ +#undef col_mul +#undef rb_fill_rect +#undef rb_fill_rrect +#undef rb_fill_circle +#undef rb_stroke_rect +#undef rb_stroke_circle +#undef rb_line +#undef rb_text_c +#undef tw +#undef in_rect + +/* Tabelas vivas (preenchidas aqui, usadas pelo editor) */ +TbEdImageApi tb_ed_img; +TbEdWidgetsApi tb_ed_w; + +/* Ordem = dependencia: widgets e a base (a imagem usa as primitivas dela) */ +static const char* s_mod_name[2] = { "tinyblocks-editor-widgets", + "tinyblocks-editor-image" }; +static const char* s_mod_file[2] = { "libtinyblocks-editor-widgets.so", + "libtinyblocks-editor-image.so" }; +static const int s_mod_n = 2; + +static char s_dir[512] = ""; + +const char* tb_ed_modules_dir(void) { return s_dir; } + +/* -- utilidades ---------------------------------------------------------- */ + +static bool file_exists(const char* p) { + struct stat st; + return p && stat(p, &st) == 0 && S_ISREG(st.st_mode); +} + +static void dir_of_exe(char* out, size_t cap) { + char buf[512]; + ssize_t n = readlink("/proc/self/exe", buf, sizeof(buf) - 1); + if (n <= 0) { snprintf(out, cap, "."); return; } + buf[n] = 0; + char* slash = strrchr(buf, '/'); + if (slash) *slash = 0; + snprintf(out, cap, "%s", buf); +} + +/* Procura o .so nos lugares conhecidos (arvore do projeto, AppImage, cwd) */ +static bool find_module(const char* name, const char* file, char* out, size_t cap) { + char exe[512]; + dir_of_exe(exe, sizeof(exe)); + const char* env = getenv("TINYBLOCKS_ED_MODULES"); + static char c[6][1024]; + snprintf(c[0], sizeof(c[0]), "libraries/tinyblocks-editor/libraries/%s/build/%s", name, file); + snprintf(c[1], sizeof(c[1]), "%s/../libraries/tinyblocks-editor/libraries/%s/build/%s", + exe, name, file); + snprintf(c[2], sizeof(c[2]), "%s/../lib/tinyblocks-editor/%s", exe, file); + snprintf(c[3], sizeof(c[3]), "%s/%s", exe, file); + snprintf(c[4], sizeof(c[4]), "%s/%s", s_dir[0] ? s_dir : ".", file); + if (env && env[0]) snprintf(c[5], sizeof(c[5]), "%s/%s", env, file); + else c[5][0] = 0; + for (int i = 0; i < 6; i++) { + if (!c[i][0]) continue; + if (file_exists(c[i])) { + snprintf(out, cap, "%s", c[i]); + char* sl = strrchr(out, '/'); + if (sl) { *sl = 0; snprintf(s_dir, sizeof(s_dir), "%s", out); *sl = '/'; } + return true; + } + } + return false; +} + +/* Copia o endereco do simbolo para o ponteiro de funcao (sem casts fora de + padrao: dlsym devolve void*, o ponteiro de funcao tem o mesmo tamanho). */ +static void sym_fn(void* dst, const char* mod, const char* name) { + void* p = tb_api_code_symbol(mod, name); + memcpy(dst, &p, sizeof(p)); +} + +/* Resolve as funcoes da library de widgets */ +static bool resolve_widgets(void) { + TbEdWidgetsApi w; + memset(&w, 0, sizeof(w)); + sym_fn(&w.col_mul, "tinyblocks-editor-widgets", "tb_ew_col_mul"); + sym_fn(&w.fill_rect, "tinyblocks-editor-widgets", "tb_ew_fill_rect"); + sym_fn(&w.fill_rrect, "tinyblocks-editor-widgets", "tb_ew_fill_rrect"); + sym_fn(&w.fill_circle, "tinyblocks-editor-widgets", "tb_ew_fill_circle"); + sym_fn(&w.stroke_rect, "tinyblocks-editor-widgets", "tb_ew_stroke_rect"); + sym_fn(&w.stroke_circle, "tinyblocks-editor-widgets", "tb_ew_stroke_circle"); + sym_fn(&w.line, "tinyblocks-editor-widgets", "tb_ew_line"); + sym_fn(&w.text_c, "tinyblocks-editor-widgets", "tb_ew_text_c"); + sym_fn(&w.text_width, "tinyblocks-editor-widgets", "tb_ew_text_width"); + sym_fn(&w.in_rect, "tinyblocks-editor-widgets", "tb_ew_in_rect"); + bool ok = w.col_mul && w.fill_rect && w.fill_rrect && w.fill_circle && w.stroke_rect && + w.stroke_circle && w.line && w.text_c && w.text_width && w.in_rect; + if (ok) tb_ed_w = w; + return ok; +} + +/* Resolve as funcoes da aba Imagem */ +static bool resolve_image(void) { + TbEdImageApi a; + memset(&a, 0, sizeof(a)); + sym_fn(&a.view, "tinyblocks-editor-image", "tb_editor_image_view"); + sym_fn(&a.click, "tinyblocks-editor-image", "tb_editor_image_click"); + sym_fn(&a.drag, "tinyblocks-editor-image", "tb_editor_image_drag"); + sym_fn(&a.release, "tinyblocks-editor-image", "tb_editor_image_release"); + sym_fn(&a.load_file, "tinyblocks-editor-image", "tb_editor_image_load_file"); + sym_fn(&a.save, "tinyblocks-editor-image", "tb_editor_image_save"); + sym_fn(&a.ensure, "tinyblocks-editor-image", "tb_editor_image_ensure"); + sym_fn(&a.sel_reset, "tinyblocks-editor-image", "tb_editor_image_sel_reset"); + sym_fn(&a.sel_commit, "tinyblocks-editor-image", "tb_editor_image_sel_commit"); + bool ok = a.view && a.click && a.drag && a.release && a.load_file && a.save && + a.ensure && a.sel_reset && a.sel_commit; + if (ok) tb_ed_img = a; + return ok; +} + +/* -- carga --------------------------------------------------------------- */ + +bool tb_ed_modules_load(Ed* ed) { + if (!tb_api_runtime()) tb_api_init(ed->rt); + tb_ed_modules_clear(); + + /* ordem de dependencia: widgets antes da imagem */ + for (int i = 0; i < s_mod_n; i++) { + char path[1024]; + if (!find_module(s_mod_name[i], s_mod_file[i], path, sizeof(path))) { + snprintf(ed->mods.info, sizeof(ed->mods.info), + "modulo nao encontrado: %s", s_mod_file[i]); + return false; + } + if (tb_api_code_load(s_mod_name[i], path) < 0) { + snprintf(ed->mods.info, sizeof(ed->mods.info), "%.120s", tb_api_last_error()); + return false; + } + ed->mods.list[ed->mods.n].name = s_mod_name[i]; + ed->mods.list[ed->mods.n].file = s_mod_file[i]; + ed->mods.list[ed->mods.n].ok = 1; + ed->mods.n++; + } + bool ok = resolve_widgets() && resolve_image(); + ed->mods.loaded = ok; + if (ok) { + snprintf(ed->mods.info, sizeof(ed->mods.info), + "Bundle do editor carregado (%.100s)", tb_api_code_count() ? s_dir : "?"); + } + return ok; +} + +void tb_ed_modules_clear(void) { + tb_api_code_unload_all(); + memset(&tb_ed_img, 0, sizeof(tb_ed_img)); + memset(&tb_ed_w, 0, sizeof(tb_ed_w)); +} + +bool tb_ed_modules_check(Ed* ed) { + if (!ed->mods.loaded) return false; + if (!tb_api_code_changed()) return false; + + /* Recarrega o bundle inteiro, em ordem: descarrega na ordem inversa + (para as dependencias soltarem) e carrega na ordem de dependencia. */ + int n = tb_api_code_count(); + char names[8][64], paths[8][512]; + int keep = n < 8 ? n : 8; + for (int i = 0; i < keep; i++) { + snprintf(names[i], sizeof(names[i]), "%s", tb_api_code_name(i)); + snprintf(paths[i], sizeof(paths[i]), "%s", tb_api_code_path(i)); + } + tb_api_code_reload_all(); + (void)names; (void)paths; + + ed->mods.n = 0; + for (int i = 0; i < s_mod_n; i++) { + ed->mods.list[ed->mods.n].name = s_mod_name[i]; + ed->mods.list[ed->mods.n].file = s_mod_file[i]; + ed->mods.list[ed->mods.n].ok = 1; + ed->mods.n++; + } + bool ok = resolve_widgets() && resolve_image(); + ed->mods.loaded = ok; + ed->mods.reloads++; + snprintf(ed->mods.info, sizeof(ed->mods.info), "Editor recarregado (%d)%s", + ed->mods.reloads, ok ? "" : " - FALHOU"); + snprintf(ed->hot_status, sizeof(ed->hot_status), "%s", ed->mods.info); + ed->hot_status_ok = ok; + return true; +} diff --git a/libraries/tinyblocks-libman/include/tb_libman.h b/libraries/tinyblocks-libman/include/tb_libman.h index 4eaca00..c86623e 100644 --- a/libraries/tinyblocks-libman/include/tb_libman.h +++ b/libraries/tinyblocks-libman/include/tb_libman.h @@ -35,6 +35,8 @@ typedef struct TbLibmanEntry { char shared[TBLM_PATH_LEN]; /* caminho do .so (pode nao existir) */ char staticlib[TBLM_PATH_LEN]; /* caminho do .a */ char depends[160]; + char bundle[48]; /* grupo (ex: "tinyblocks-editor") */ + bool private_lib; /* library interna do bundle (nao listar)*/ } TbLibmanEntry; /* -- Ciclo de vida --- */ @@ -63,6 +65,9 @@ TB_API int tb_libman_install(int i); /* tb_api_load(entry->shared) */ * Retorna quantos indices foram escritos (ate 'max'). */ TB_API int tb_libman_search(const char* query, const char* category, int* out, int max); +/* Igual, mas permite incluir as libraries privadas de bundle (private=true). */ +TB_API int tb_libman_search_ex(const char* query, const char* category, + bool include_private, int* out, int max); /* Categorias distintas encontradas (sem repeticao). Retorna n. */ TB_API int tb_libman_categories(char out[][48], int max); diff --git a/libraries/tinyblocks-libman/src/tb_libman.c b/libraries/tinyblocks-libman/src/tb_libman.c index 43ba09b..94cc292 100644 --- a/libraries/tinyblocks-libman/src/tb_libman.c +++ b/libraries/tinyblocks-libman/src/tb_libman.c @@ -55,6 +55,9 @@ static void entry_from_toml(const char* tomlpath, const char* dir) { 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", "")); + copy_str(e->bundle, sizeof(e->bundle), tb_toml_str(doc, "library.bundle", "")); + e->private_lib = tb_toml_int(doc, "library.private", 0) != 0 || + strcmp(tb_toml_str(doc, "library.private", "0"), "true") == 0; int col[4]; tb_toml_int_array(doc, "library.color", col, 4, 255); @@ -185,14 +188,16 @@ static bool contains_ci(const char* hay, const char* needle) { return false; } -int tb_libman_search(const char* query, const char* category, - int* out, int max) { - int n = 0; +int tb_libman_search_ex(const char* query, const char* category, + bool include_private, int* out, int max) { bool allcat = !category || !category[0] || strcmp(category, "Tudo") == 0; + int n = 0; for (int i = 0; i < s_n && n < max; i++) { const TbLibmanEntry* e = &s_e[i]; + if (e->private_lib && !include_private) continue; if (!allcat && strcmp(e->category, category) != 0) continue; - if (!contains_ci(e->name, query) && + if (query && query[0] && + !contains_ci(e->name, query) && !contains_ci(e->category, query) && !contains_ci(e->description, query)) continue; out[n++] = i; @@ -200,6 +205,10 @@ int tb_libman_search(const char* query, const char* category, return n; } +int tb_libman_search(const char* query, const char* category, int* out, int max) { + return tb_libman_search_ex(query, category, false, out, max); +} + int tb_libman_categories(char out[][48], int max) { int n = 0; for (int i = 0; i < s_n && n < max; i++) { diff --git a/libraries/tinyblocks-svg/src/tb_svg.c b/libraries/tinyblocks-svg/src/tb_svg.c index 550e37c..67ad2a9 100644 --- a/libraries/tinyblocks-svg/src/tb_svg.c +++ b/libraries/tinyblocks-svg/src/tb_svg.c @@ -503,6 +503,41 @@ static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name, return t && tb_library_add(lib, &t->base); } +/* Decodificador de imagem registrado no core: permite usar um .svg como + documento ou camada no editor de imagem (rasterizado no carregamento). */ +#define SVG_FILE_MAX (4u * 1024u * 1024u) +static TinyBlocks_Image* svg_image_load(const char* path) { + FILE* f = fopen(path, "rb"); + if (!f) { snprintf(s_err, sizeof(s_err), "nao consegui abrir '%s'", path); return NULL; } + if (fseek(f, 0, SEEK_END) != 0) { + fclose(f); + snprintf(s_err, sizeof(s_err), "arquivo invalido"); + return NULL; + } + long sz = ftell(f); + if (sz <= 0 || (unsigned long)sz > SVG_FILE_MAX) { + fclose(f); + snprintf(s_err, sizeof(s_err), "tamanho invalido (%ld bytes)", sz); + return NULL; + } + fseek(f, 0, SEEK_SET); + char* buf = (char*)malloc((size_t)sz + 1); + if (!buf) { fclose(f); snprintf(s_err, sizeof(s_err), "sem memoria"); return NULL; } + size_t rd = fread(buf, 1, (size_t)sz, f); + fclose(f); + buf[rd] = 0; + int W = 0, H = 0; + tb_svg_parse(buf, &W, &H); + if (W <= 0) W = 512; + if (H <= 0) H = 512; + if (W > 4096) W = 4096; + if (H > 4096) H = 4096; + TinyBlocks_Image* im = tb_svg_render(buf, W, H); + free(buf); + if (!im) snprintf(s_err, sizeof(s_err), "nao consegui rasterizar '%s'", path); + return im; +} + static bool svg_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { static const TinyBlocks_Category cat = { "SVG", @@ -510,6 +545,7 @@ static bool svg_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { { 255/255.f, 160/255.f, 0/255.f, 1.f}, }; tb_library_set_category(lib, &cat); + tb_image_register_format("svg", svg_image_load, NULL); static const TinyBlocks_SlotDesc out_vec[] = {{"vetor", TB_VALUE_VECTOR}}; static const TinyBlocks_SlotDesc out_img[] = {{"imagem", TB_VALUE_IMAGE}}; diff --git a/tests/editor_harness.c b/tests/editor_harness.c index 7c05292..6296da9 100644 --- a/tests/editor_harness.c +++ b/tests/editor_harness.c @@ -23,6 +23,8 @@ static TinyBlocks_Block *ev, *scene; static TinyBlocks_DrawCmd cmds[TB_DRAW_CMD_CAP]; static uint32_t ncmd; static int fails = 0; +static int g_mods = 0; +static void mods(int m) { g_mods = m; } static void eval_ev(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; self->dirty = false; } @@ -42,8 +44,8 @@ static void frame(float mx, float my, int ld, int lu, int rd, int sc, const char tb_block_set_output(ev, GFX_IN_MOUSE_L_UP, tb_value_integer(lu)); tb_block_set_output(ev, GFX_IN_MOUSE_R_DOWN, tb_value_integer(rd)); tb_block_set_output(ev, GFX_IN_KEY, tb_value_integer(sc)); - tb_block_set_output(ev, GFX_IN_KEY_MOD, tb_value_integer(0)); - tb_block_set_output(ev, GFX_IN_MOD_STATE, tb_value_integer(0)); + tb_block_set_output(ev, GFX_IN_KEY_MOD, tb_value_integer(g_mods)); + tb_block_set_output(ev, GFX_IN_MOD_STATE, tb_value_integer(g_mods)); tb_block_set_output(ev, GFX_IN_TEXT, tb_value_text(text ? text : "")); tb_block_set_output(ev, GFX_IN_DROP_FILE, tb_value_text("")); tb_block_set_output(ev, GFX_IN_SCROLL_DX, tb_value_real(0)); @@ -92,6 +94,60 @@ static bool ws_has(const char* s) { if (cmds[i].kind == TB_DRAW_TEXT && in_region(cmds[i].x, R_WS) && strcmp(cmds[i].text, s) == 0) return true; return false; } +static bool find_tabbar(const char* s, float* x, float* y) { + for (uint32_t i = 0; i < ncmd; i++) { + TinyBlocks_DrawCmd* c = &cmds[i]; + if (c->kind != TB_DRAW_TEXT || strcmp(c->text, s) != 0) continue; + if (c->y < 40 || c->y > 86) continue; + *x = c->x + 3; *y = c->y - c->font_size*0.36f; + return true; + } + return false; +} +static bool find_sub(const char* sub, float* x, float* y) { + for (uint32_t i = 0; i < ncmd; i++) { + TinyBlocks_DrawCmd* c = &cmds[i]; + if (c->kind != TB_DRAW_TEXT || !strstr(c->text, sub)) continue; + *x = c->x + 3; *y = c->y - c->font_size*0.36f; + return true; + } + return false; +} +/* Conta pixels nao-brancos da ultima imagem desenhada no workspace */ +static int img_nonwhite(void) { + /* A folha de desenho e a MAIOR imagem do workspace (miniaturas sao pequenas) */ + const TinyBlocks_Image* im = NULL; + float best = 0; + for (uint32_t i = 0; i < ncmd; i++) { + if (cmds[i].kind != TB_DRAW_IMAGE || !cmds[i].image || !in_region(cmds[i].x, R_WS)) continue; + float a = cmds[i].w * cmds[i].h; + if (a < 20000.f) continue; /* ignora miniaturas */ + if (a > best) { best = a; im = cmds[i].image; } + } + if (!im) return -1; + int W = tb_image_width(im), H = tb_image_height(im), n = 0; + for (int y = 0; y < H; y++) + for (int x = 0; x < W; x++) { + uint8_t r, g, b, a; + if (tb_image_get_pixel(im, x, y, &r, &g, &b, &a) && a > 0 && + (r < 240 || g < 240 || b < 240)) n++; + } + return n; +} +static bool any_substr(const char* s) { + for (uint32_t i = 0; i < ncmd; i++) + if (cmds[i].kind == TB_DRAW_TEXT && strstr(cmds[i].text, s)) return true; + return false; +} +static bool ws_substr(const char* s) { + for (uint32_t i = 0; i < ncmd; i++) + if (cmds[i].kind == TB_DRAW_TEXT && in_region(cmds[i].x, R_WS) && strstr(cmds[i].text, s)) return true; + return false; +} +static void dump_ws(void) { + for (uint32_t i = 0; i < ncmd; i++) + if (cmds[i].kind == TB_DRAW_TEXT && in_region(cmds[i].x, R_WS)) printf(" ws| %s (%.0f,%.0f)\n", cmds[i].text, cmds[i].x, cmds[i].y); +} static void dump_stage(void) { for (uint32_t i = 0; i < ncmd; i++) if (cmds[i].kind == TB_DRAW_TEXT && cmds[i].x >= 920 && cmds[i].y > 130) printf(" | %s\n", cmds[i].text); @@ -455,6 +511,139 @@ int main(void) { } CHECK(ws_has("32x32"), "balão mostra as dimensões da imagem"); + /* 21. Tooltip de metadados: Alt + hover sobre um bloco (Stage.Clear) */ + if (need("Caneta", R_CAT, 0, &x, &y)) click(x, y); + frame(0, 0, 0, 0, 0, 0, NULL); + if (need("apague tudo", R_FLY, 0, &x, &y)) drag(x, y, 520, 430); + frame(0, 0, 0, 0, 0, 0, NULL); + { + float bx = 0, by = 0; + if (find("apague tudo", R_WS, 0, &bx, &by)) { + mods(TB_MOD_ALT); + frame(bx, by, 0, 0, 0, 0, NULL); + CHECK(any_substr("eval_clear"), "Alt+hover mostra o tooltip com a funcao C"); + CHECK(any_substr("tb_pen.c"), "tooltip mostra o arquivo-fonte"); + CHECK(any_substr("Limpa o palco"), "tooltip mostra a descricao (doc)"); + /* clica na previa do codigo -> abre aba de codigo na linha */ + float px = 0, py = 0; + if (find_sub("tb_stage_clear", &px, &py)) { + mods(0); + click(px, py); + frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(any_substr("tb_pen.c"), "clique na previa abre aba de codigo do arquivo"); + CHECK(ws_substr("eval_clear"), "aba de codigo mostra o codigo na linha da funcao"); + } else { mods(0); CHECK(false, "achei a previa do codigo no tooltip"); } + } else { CHECK(false, "achei o bloco 'apague tudo' no workspace"); } + } + + /* 22. Botao "+" -> nova aba: Editor de Codigo */ + key(TB_KEY_ESCAPE, 0, 0); + frame(0, 0, 0, 0, 0, 0, NULL); + { + float px = 0, py = 0; + if (find_tabbar("+", &px, &py)) click(px, py); else { CHECK(false, "achei o botao +"); } + frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(find("Editor de Codigo", R_ANY, 0, &x, &y), "menu '+' lista as opcoes de nova aba"); + CHECK(find("Edicao de Imagem", R_ANY, 0, &x, &y), "menu '+' oferece Edicao de Imagem"); + if (need("Editor de Codigo", R_ANY, 0, &x, &y)) click(x, y); + frame(0, 0, 0, 0, 0, 0, NULL); + type("int x = 42;"); + frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(ws_has("int"), "aba de codigo realca 'int' (palavra-chave)"); + CHECK(ws_has("42"), "aba de codigo realca o numero 42"); + CHECK(ws_has(";"), "aba de codigo realca a pontuacao"); + } + + /* 23. Botao "+" -> nova aba: Edicao de Imagem */ + key(TB_KEY_ESCAPE, 0, 0); + frame(0, 0, 0, 0, 0, 0, NULL); + { + float px = 0, py = 0; + if (find_tabbar("+", &px, &py)) click(px, py); else { CHECK(false, "achei o botao +"); } + frame(0, 0, 0, 0, 0, 0, NULL); + if (need("Edicao de Imagem", R_ANY, 0, &x, &y)) click(x, y); + frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(find("Camadas", R_WS, 0, &x, &y), "aba de imagem mostra a lista de camadas"); + CHECK(find("Salvar", R_WS, 0, &x, &y), "aba de imagem mostra o botao Salvar"); + CHECK(find("Desfazer", R_WS, 0, &x, &y), "aba de imagem mostra o botao Desfazer"); + CHECK(find("Cores", R_WS, 0, &x, &y), "aba de imagem mostra a coluna de cores"); + CHECK(find("Paleta", R_WS, 0, &x, &y), "aba de imagem mostra a paleta rapida"); + CHECK(x > 700, "cores ficam na lateral direita"); + { + int imgs = 0; + for (uint32_t i = 0; i < ncmd; i++) + if (cmds[i].kind == TB_DRAW_IMAGE && in_region(cmds[i].x, R_WS)) imgs++; + CHECK(imgs >= 1, "aba de imagem desenha a folha de desenho"); + } + } + + /* 24. Pintar na aba de imagem (ferramenta pincel) */ + { + int before = img_nonwhite(); + CHECK(before == 0, "folha de desenho comeca em branco"); + click(345, 192); /* botao da ferramenta pincel */ + frame(0, 0, 0, 0, 0, 0, NULL); + drag(500, 300, 560, 400); /* pinta um traco no canvas */ + frame(0, 0, 0, 0, 0, 0, NULL); + int after = img_nonwhite(); + CHECK(after > 0, "pincel pinta pixels na folha de desenho"); + click(421, 703); /* botao Desfazer */ + frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(img_nonwhite() == 0, "Desfazer volta a folha em branco"); + click(345, 292); /* ferramenta retangulo */ + frame(0, 0, 0, 0, 0, 0, NULL); + drag(560, 280, 680, 360); + frame(0, 0, 0, 0, 0, 0, NULL); + int rect_px = img_nonwhite(); + CHECK(rect_px > 100, "ferramenta retangulo desenha o contorno"); + click(345, 342); /* ferramenta elipse */ + frame(0, 0, 0, 0, 0, 0, NULL); + drag(620, 290, 690, 390); + frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(img_nonwhite() > rect_px, "ferramenta elipse desenha o contorno"); + click(345, 392); /* ferramenta preencher */ + frame(0, 0, 0, 0, 0, 0, NULL); + click(620, 320); /* dentro do retangulo */ + frame(0, 0, 0, 0, 0, 0, NULL); + click(520, 400); /* fora das formas */ + frame(0, 0, 0, 0, 0, 0, NULL); + int fill_px = img_nonwhite(); + CHECK(fill_px > rect_px * 3, "ferramenta preencher alaga a area branca"); + click(345, 492); /* conta-gotas */ + frame(0, 0, 0, 0, 0, 0, NULL); + click(520, 400); + frame(0, 0, 0, 0, 0, 0, NULL); + { + bool found = false; + for (uint32_t i = 0; i < ncmd; i++) + if (cmds[i].kind == TB_DRAW_TEXT && strstr(cmds[i].text, "Cor do pixel")) found = true; + CHECK(found, "conta-gotas informa a cor capturada"); + } + /* 24b. Escolher uma cor na paleta lateral e desenhar com ela */ + { + click(803, 277); /* segundo quadradinho da paleta (branco) */ + frame(0, 0, 0, 0, 0, 0, NULL); + bool dark = false; + for (uint32_t i = 0; i < ncmd; i++) + if (cmds[i].kind == TB_DRAW_TEXT && strstr(cmds[i].text, "#FFFFFF")) dark = true; + CHECK(dark, "paleta lateral troca a cor da ferramenta"); + click(345, 142); /* selecionar */ + frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(find("Desfazer", R_WS, 0, &x, &y), "ferramenta selecionar continua disponivel"); + } + CHECK(find("Fundo", R_WS, 0, &x, &y), "lista de camadas mostra a camada Fundo"); + CHECK(find("+ Raster", R_WS, 0, &x, &y), "botao de nova camada raster"); + CHECK(find("+ Vetor", R_WS, 0, &x, &y), "botao de nova camada vetorial"); + CHECK(find("Fundo", R_WS, 0, &x, &y), "achei a camada Fundo"); + click(x - 29, y + 6); /* olho da camada Fundo: esconde */ + frame(0, 0, 0, 0, 0, 0, NULL); + /* sem camada visivel nao ha imagem nenhuma na folha (=-1) */ + CHECK(img_nonwhite() <= 0, "camada pode ser escondida"); + click(x - 29, y + 6); /* olho: mostra de novo */ + frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(img_nonwhite() > 0, "camada pode ser mostrada de novo"); + } + printf("comandos de desenho no último frame: %u\n", ncmd); tinyblocks_deinit(&rt); printf(fails ? "\n%d FALHA(S)\n" : "\nTUDO OK\n", fails);