/* * TinyBlocks - tb_editor.c * Editor visual no estilo Scratch, implementado como TypeBlock "Editor.Scene". * * Não abre janela nem conhece backend: implementa on_draw (produzindo um * TinyBlocks_RenderableBlock) e lê a entrada de um bloco Graphics.Input * conectado ao seu input "events". É a cena de um Graphics.Window da * interface tinyblocks-graphics, que escolhe o backend (SDL2 ou outro). * * O Palco (Editor.Stage, tb_stage.c) é um componente à parte: fica embutido * no painel direito ou, ao ser destacado, vira a cena de outro Graphics.Window. * * Modelo de programação (igual ao Scratch): * - blocos de comando se empilham formando scripts (executados de cima para baixo); * - repórteres (blocos com saída) encaixam nos campos de entrada de outros blocos; * - blocos de controle (repita / se / se-senão / repita até) têm "bocas" * que abrigam outra pilha; * - "quando a bandeira for clicado" inicia um script quando a bandeira verde é clicada. * * Execução: cada comando vira uma árvore de blocos do runtime (cada repórter * encaixado - uma conexão de input) avaliada com tb_block_eval. A sequência * e os blocos de controle são interpretados pelo próprio editor. */ #define _POSIX_C_SOURCE 200809L #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "tb_stage_widget.h" #include "../include/tb_editor.h" /* === * Fila de preload (tb_editor_preload antes do bloco entrar em uso) * === */ #define MAX_PRELOAD 16 static char s_preload[MAX_PRELOAD][512]; static int s_preload_n = 0; TB_API void tb_editor_preload(const char* path) { if (!path || s_preload_n >= MAX_PRELOAD) return; strncpy(s_preload[s_preload_n++], path, 511); } /* === * Layout da janela * * ==== barra de menu (azul) ==== * == abas ===== [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 /* 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"}, }; /* === * 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); } static inline bool in_rect(float mx, float my, float x, float y, float w, float h) { return mx>=x && mx=y && myclip_on = true; ed->clip[0]=x; ed->clip[1]=y; ed->clip[2]=w; ed->clip[3]=h; tb_draw_set_clip(rb, x, y, w, h); } static void clip_clear(Ed* ed, TinyBlocks_RenderableBlock* rb) { ed->clip_on = false; tb_draw_clear_clip(rb); } static void clip_restore(Ed* ed, TinyBlocks_RenderableBlock* rb) { if (ed->clip_on) tb_draw_set_clip(rb, ed->clip[0], ed->clip[1], ed->clip[2], ed->clip[3]); else tb_draw_clear_clip(rb); } /* Hexágono (repórter booleano) desenhado em faixas de 1px */ static void draw_hex(TinyBlocks_RenderableBlock* rb, float x, float y, float w, float h, Col c) { float half = h*0.5f; int rows = (int)(h + 0.5f); for (int r = 0; r < rows; r++) { float in = fabsf(r + 0.5f - half); if (in > w*0.5f) in = w*0.5f; rb_fill_rect(rb, x+in, y+r, w-2*in, 1.f, c); } } /* Encaixe trapezoidal sob um comando; y - borda inferior do bloco */ static void draw_bump(TinyBlocks_RenderableBlock* rb, float x, float y, Col c, Col d) { float bx = x + NOTCH_X; for (int r = 0; r <= NOTCH_D; r++) rb_fill_rect(rb, bx+r-1, y-1+r, NOTCH_W-2*r+2, 1.f, d); for (int r = 0; r < NOTCH_D; r++) rb_fill_rect(rb, bx+r, y-1+r, NOTCH_W-2*r, 1.f, c); } /* === * Valores * === */ static void value_to_str(const TinyBlocks_Value* v, char* buf, size_t cap) { switch (v->kind) { case TB_VALUE_INTEGER: snprintf(buf, cap, "%lld", (long long)v->as.integer); break; case TB_VALUE_REAL: snprintf(buf, cap, "%g", v->as.real); break; case TB_VALUE_TEXT: snprintf(buf, cap, "%s", v->as.text ? v->as.text : ""); break; case TB_VALUE_BLOCK: snprintf(buf, cap, "[bloco]"); break; case TB_VALUE_VECTOR: snprintf(buf, cap, "[vetor]"); break; case TB_VALUE_JSON: snprintf(buf, cap, "[json]"); break; case TB_VALUE_IMAGE: snprintf(buf, cap, "[imagem %dx%d]", tb_image_width(v->as.image), tb_image_height(v->as.image)); break; default: buf[0] = 0; break; } } static bool value_num(const TinyBlocks_Value* v, double* d) { if (v->kind == TB_VALUE_INTEGER) { *d = (double)v->as.integer; return true; } if (v->kind == TB_VALUE_REAL) { *d = v->as.real; return true; } if (v->kind == TB_VALUE_TEXT && v->as.text && v->as.text[0]) { char* e; *d = strtod(v->as.text, &e); return *e == 0; } return false; } static long long value_to_ll(const TinyBlocks_Value* v) { double d; if (v->kind == TB_VALUE_INTEGER) return v->as.integer; return value_num(v, &d) ? llround(d) : 0; } static bool value_truthy(const TinyBlocks_Value* v) { switch (v->kind) { case TB_VALUE_INTEGER: return v->as.integer != 0; case TB_VALUE_REAL: return v->as.real != 0.0; case TB_VALUE_TEXT: { const char* t = v->as.text ? v->as.text : ""; if (!t[0] || strcmp(t, "0") == 0) return false; const char* f = "false"; for (; *t && *f; t++, f++) if (tolower((unsigned char)*t) != *f) return true; return *t || *f; } case TB_VALUE_BLOCK: return v->as.block != NULL; default: return false; } } /* Converte o texto de um campo no valor esperado pelo slot. * Slots sem tipo (NONE) adivinham: inteiro, real ou texto. */ static TinyBlocks_Value value_from_text(const char* raw, TinyBlocks_ValueKind k) { char* e; switch (k) { case TB_VALUE_INTEGER: { long long v = strtoll(raw, &e, 10); if (*e == '.' || *e == 'e' || *e == 'E') v = llround(strtod(raw, NULL)); return tb_value_integer(v); } case TB_VALUE_REAL: return tb_value_real(strtod(raw, NULL)); case TB_VALUE_TEXT: return tb_value_text(raw); case TB_VALUE_NONE: { long long iv = strtoll(raw, &e, 10); if (*e == 0) return tb_value_integer(iv); double dv = strtod(raw, &e); if (*e == 0) return tb_value_real(dv); return tb_value_text(raw); } default: return tb_value_none(); } } /* === * Tipos de bloco: forma, categoria, rótulo * === */ static const char* display_name(const char* full) { if (!full) return "?"; const char* p = strrchr(full,'.'); return p ? p+1 : full; } static const BlockSpec* spec_of(const char* tn) { if (!tn) return NULL; for (size_t i = 0; i < sizeof(s_specs)/sizeof(s_specs[0]); i++) if (strcmp(s_specs[i].type, tn) == 0) return &s_specs[i]; return NULL; } static int input_count(const TinyBlocks_TypeBlock* t) { if (!t) return 0; return t->input_desc_count < MAX_INPUTS ? (int)t->input_desc_count : MAX_INPUTS; } static Shape shape_of(const TinyBlocks_TypeBlock* t) { if (!t || !t->type_name) return SH_STACK; const char* n = t->type_name; if (strncmp(n, "Events.", 7) == 0) return SH_HAT; if (strcmp(n, "Control.If") == 0 || strcmp(n, "Control.Repeat") == 0 || strcmp(n, "Control.RepeatUntil") == 0) return SH_C1; if (strcmp(n, "Control.IfElse") == 0) return SH_C2; if (strcmp(n, "Operators.Lt") == 0 || strcmp(n, "Operators.Eq") == 0 || strcmp(n, "Operators.Gt") == 0 || strcmp(n, "Operators.And") == 0 || strcmp(n, "Operators.Or") == 0 || strcmp(n, "Operators.Not") == 0) return SH_BOOL; return t->output_desc_count > 0 ? SH_REPORTER : SH_STACK; } static bool shape_is_value(Shape s) { return s == SH_REPORTER || s == SH_BOOL; } static UserBlockDef* user_def_find(Ed* ed, const char* name); /* idx-ésima entrada (NUM/BOOL) do protótipo; NULL se fora do intervalo */ static const UserParam* user_param_at(const UserBlockDef* def, int idx) { if (!def || idx < 0) return NULL; int k = 0; for (int i = 0; i < def->part_n; i++) { if (def->parts[i].kind == PARAM_LABEL) continue; if (k == idx) return &def->parts[i]; k++; } return NULL; } static bool slot_is_bool(const TinyBlocks_TypeBlock* t, int i) { if (!t || !t->type_name) return false; const char* n = t->type_name; if (strncmp(n, "User.", 5) == 0) { UserBlockDef* def = g_active_ed ? user_def_find(g_active_ed, n + 5) : NULL; const UserParam* p = user_param_at(def, i); return p && p->kind == PARAM_BOOL; } if (i == 0 && (strcmp(n,"Control.If") == 0 || strcmp(n,"Control.IfElse") == 0 || strcmp(n,"Control.RepeatUntil") == 0)) return true; return strcmp(n,"Operators.And") == 0 || strcmp(n,"Operators.Or") == 0 || strcmp(n,"Operators.Not") == 0; } static bool is_lit_text(const TinyBlocks_TypeBlock* t) { return t && t->type_name && strcmp(t->type_name, "Literal.Text") == 0; } static void type_prefix(const char* n, char* out, size_t cap) { const char* dot = strchr(n, '.'); size_t len = dot ? (size_t)(dot - n) : strlen(n); if (len >= cap) len = cap - 1; memcpy(out, n, len); out[len] = 0; } /* Categoria de um TypeBlock: pela library que o contém, ou por prefixo. */ static int cat_of_type(Ed* ed, const TinyBlocks_TypeBlock* t) { if (!t || !t->type_name) return -1; const char* n = t->type_name; if (strncmp(n, "User.", 5) == 0 || strncmp(n, "Port.", 5) == 0) return ed->myblocks_cat; if (t->base.parent && t->base.parent->kind == TB_KIND_LIBRARY) { const TinyBlocks_LibraryBlock* lib = (const TinyBlocks_LibraryBlock*)t->base.parent; for (int i = 0; i < ed->cat_n; i++) if (ed->cats[i].lib == lib) return i; } char pre[32]; type_prefix(n, pre, sizeof(pre)); for (int i = 0; i < ed->cat_n; i++) if (ed->cats[i].prefix[0] && strcmp(ed->cats[i].prefix, pre) == 0) return i; return -1; } static int cat_of(Ed* ed, const char* n) { if (!n) return -1; return cat_of_type(ed, tb_type_block_find(ed->rt, n)); } static UserBlockDef* user_def_find(Ed* ed, const char* name) { for (int i = 0; i < ed->user_block_n; i++) if (strcmp(ed->user_blocks[i].name, name) == 0) return &ed->user_blocks[i]; return NULL; } static void block_cols(Ed* ed, const EdBlock* b, Col* c, Col* d) { const TinyBlocks_TypeBlock* t = b->type; if (!t || !t->type_name) { *c = COL_MISSING; *d = col_mul(COL_MISSING, 0.75f); return; } if (strncmp(t->type_name, "User.", 5) == 0) { UserBlockDef* def = user_def_find(ed, t->type_name + 5); *c = s_user_colors[def ? def->color_idx : 0]; *d = col_mul(*c, 0.8f); return; } int k = cat_of(ed, t->type_name); if (k < 0) { *c = COL_EXT; *d = COL_EXT_DARK; return; } *c = ed->cats[k].col; *d = ed->cats[k].dark; } /* === * Pool de blocos de uma aba (índices estáveis, sem compactação) * === */ static void blk_defaults(EdBlock* b) { const TinyBlocks_TypeBlock* t = b->type; int n = input_count(t); for (int i = 0; i < n; i++) { TinyBlocks_ValueKind k = t->input_descs[i].expected_kind; if ((k == TB_VALUE_INTEGER || k == TB_VALUE_REAL) && !slot_is_bool(t, i)) strcpy(b->in_text[i], "0"); } /* Blocos compostos mostram o nome do parâmetro como valor inicial */ if (t && t->type_name && strncmp(t->type_name, "User.", 5) == 0 && g_active_ed) { UserBlockDef* def = user_def_find(g_active_ed, t->type_name + 5); if (def) { int k = 0; for (int i = 0; i < def->part_n && k < n; i++) { if (def->parts[i].kind == PARAM_LABEL) continue; if (def->parts[i].kind == PARAM_NUM) snprintf(b->in_text[k], sizeof(b->in_text[k]), "%s", def->parts[i].name); else b->in_text[k][0] = 0; k++; } } } const BlockSpec* sp = t ? spec_of(t->type_name) : NULL; const char* p = sp ? sp->defs : NULL; for (int i = 0; i < n && p; i++) { const char* e = strchr(p, '|'); size_t len = e ? (size_t)(e - p) : strlen(p); if (len > 63) len = 63; memcpy(b->in_text[i], p, len); b->in_text[i][len] = 0; p = e ? e + 1 : NULL; } } static int blk_alloc(Tab* T) { for (int i = 0; i < MAX_WS; i++) { if (T->ws[i].used) continue; EdBlock* b = &T->ws[i]; memset(b, 0, sizeof(*b)); b->used = true; b->parent = -1; b->prel = REL_NONE; b->next = -1; b->sub[0] = b->sub[1] = -1; for (int s = 0; s < MAX_INPUTS; s++) b->args[s] = -1; return i; } return -1; } static int blk_new(Tab* T, TinyBlocks_TypeBlock* type) { int i = blk_alloc(T); if (i < 0) return -1; EdBlock* b = &T->ws[i]; b->type = type; if (type && type->type_name) strncpy(b->type_name, type->type_name, 63); blk_defaults(b); return i; } static void top_remove(Tab* T, int bi) { for (int i = 0; i < T->top_n; i++) { if (T->top[i] != bi) continue; memmove(&T->top[i], &T->top[i+1], (size_t)(T->top_n - i - 1) * sizeof(int)); T->top_n--; return; } } /* Adiciona (ou traz para a frente) uma pilha de topo */ static void top_add(Tab* T, int bi) { top_remove(T, bi); if (T->top_n < MAX_WS) T->top[T->top_n++] = bi; } /* Liga child ao pai na relação rel (child - -1 desliga) */ static void blk_link(Tab* T, int parent, int rel, int child) { EdBlock* p = &T->ws[parent]; if (rel == REL_NEXT) p->next = child; else if (rel < REL_ARG0) p->sub[rel - REL_SUB0] = child; else p->args[rel - REL_ARG0] = child; if (child >= 0) { T->ws[child].parent = parent; T->ws[child].prel = rel; } } static int linked(Tab* T, int parent, int rel) { EdBlock* p = &T->ws[parent]; if (rel == REL_NEXT) return p->next; if (rel < REL_ARG0) return p->sub[rel - REL_SUB0]; return p->args[rel - REL_ARG0]; } /* Solta bi do pai; vira topo de pilha (levando os blocos abaixo dele) */ static void detach(Tab* T, int bi) { EdBlock* b = &T->ws[bi]; if (b->parent < 0) return; blk_link(T, b->parent, b->prel, -1); b->parent = -1; b->prel = REL_NONE; top_add(T, bi); } static int chain_last(Tab* T, int bi) { while (T->ws[bi].next >= 0) bi = T->ws[bi].next; return bi; } static int stack_root(Tab* T, int bi) { while (T->ws[bi].parent >= 0) bi = T->ws[bi].parent; return bi; } static float chain_h(Tab* T, int head) { float h = 0; for (int c = head; c >= 0; c = T->ws[c].next) h += T->ws[c].h; return h; } /* Insere a pilha bi (de topo) em parent/rel; o que estava lá vai para baixo dela */ static void attach_insert(Tab* T, int parent, int rel, int bi) { top_remove(T, bi); int old = linked(T, parent, rel); int last = chain_last(T, bi); blk_link(T, parent, rel, bi); if (old >= 0) blk_link(T, last, REL_NEXT, old); } /* Encaixa a pilha bi acima da pilha de topo target */ static void attach_above(Tab* T, int target, int bi) { float dh = chain_h(T, bi); top_remove(T, target); blk_link(T, chain_last(T, bi), REL_NEXT, target); T->ws[bi].x = T->ws[target].x; T->ws[bi].y = T->ws[target].y - dh; } /* Encaixa o repórter bi no campo s; um repórter que já estava lá é expulso */ static void attach_arg(Tab* T, int parent, int s, int bi) { top_remove(T, bi); int old = T->ws[parent].args[s]; if (old >= 0) { detach(T, old); T->ws[old].x = T->ws[old].ax + 20; T->ws[old].y = T->ws[old].ay + 24; } blk_link(T, parent, REL_ARG0 + s, bi); } static void mark_drag(Tab* T, int bi, bool v) { for (; bi >= 0; bi = T->ws[bi].next) { EdBlock* b = &T->ws[bi]; b->dragging = v; for (int s = 0; s < MAX_INPUTS; s++) if (b->args[s] >= 0) mark_drag(T, b->args[s], v); for (int k = 0; k < 2; k++) if (b->sub[k] >= 0) mark_drag(T, b->sub[k], v); } } /* Cópia profunda (repórteres, bocas e - se with_next - os blocos abaixo) */ static int copy_tree(Tab* S, int si, Tab* D, bool with_next) { int first = -1, prev = -1; for (int c = si; c >= 0; c = with_next ? S->ws[c].next : -1) { int ni = blk_alloc(D); if (ni < 0) break; EdBlock* n = &D->ws[ni]; const EdBlock* o = &S->ws[c]; *n = *o; n->parent = -1; n->prel = REL_NONE; n->next = -1; n->sub[0] = n->sub[1] = -1; n->live_rt = NULL; n->dragging = false; for (int s = 0; s < MAX_INPUTS; s++) n->args[s] = -1; for (int s = 0; s < MAX_INPUTS; s++) { if (o->args[s] < 0) continue; int k = copy_tree(S, o->args[s], D, false); if (k >= 0) blk_link(D, ni, REL_ARG0 + s, k); } for (int k = 0; k < 2; k++) { if (o->sub[k] < 0) continue; int h = copy_tree(S, o->sub[k], D, true); if (h >= 0) blk_link(D, ni, REL_SUB0 + k, h); } if (prev >= 0) blk_link(D, prev, REL_NEXT, ni); else first = ni; prev = ni; } return first; } /* Libera bi, tudo o que está encaixado nele e os blocos abaixo */ static void free_tree(Ed* ed, Tab* T, int bi) { while (bi >= 0) { EdBlock* b = &T->ws[bi]; int nx = b->next; for (int s = 0; s < MAX_INPUTS; s++) if (b->args[s] >= 0) free_tree(ed, T, b->args[s]); for (int k = 0; k < 2; k++) if (b->sub[k] >= 0) free_tree(ed, T, b->sub[k]); top_remove(T, bi); if (T == &CT) { if (ed->editing && ed->edit_bi == bi) ed->editing = false; if (ed->bubble_bi == bi) bubble_clear(ed); } b->used = false; b->live_rt = NULL; bi = nx; } } /* Apaga só bi (com o que está encaixado nele); os blocos abaixo sobem */ static void delete_heal(Ed* ed, Tab* T, int bi) { EdBlock* b = &T->ws[bi]; int nx = b->next, par = b->parent, rel = b->prel; if (nx >= 0) { b->next = -1; T->ws[nx].parent = -1; T->ws[nx].prel = REL_NONE; } if (par >= 0) blk_link(T, par, rel, -1); b->parent = -1; if (nx >= 0) { if (par >= 0) blk_link(T, par, rel, nx); else { T->ws[nx].x = b->x; T->ws[nx].y = b->y; top_add(T, nx); } } free_tree(ed, T, bi); } /* === * Layout: mede (tamanhos) e posiciona (coordenadas do workspace) * === */ static const char* slot_src(const EdBlock* b, int s) { return (is_lit_text(b->type) && s == 0) ? b->lit_text : b->in_text[s]; } static int text_lines(const char* s) { int n = 1; for (; *s; s++) if (*s == '\n') n++; return n; } /* Copia a linha idx de s em out (truncada para exibição) */ static bool text_line(const char* s, int idx, char* out, size_t cap) { for (int i = 0; i < idx; i++) { s = strchr(s, '\n'); if (!s) return false; s++; } size_t n = strcspn(s, "\n"); size_t lim = cap - 4 < 48 ? cap - 4 : 48; bool cut = n > lim; if (cut) { n = lim; while (n > 0 && ((unsigned char)s[n] & 0xC0) == 0x80) n--; } memcpy(out, s, n); out[n] = 0; if (cut) strcat(out, "="); return true; } static void slot_size(const EdBlock* b, int s, float* w, float* h) { if (slot_is_bool(b->type, s)) { *w = 40; *h = SLOT_MIN_H; return; } const char* src = slot_src(b, s); int lines = text_lines(src); float mw = 0; char line[64]; for (int l = 0; l < lines; l++) { text_line(src, l, line, sizeof(line)); float lw = tw(line, FS); if (lw > mw) mw = lw; } *w = fmaxf(SLOT_MIN_W, mw + 16); *h = fmaxf(SLOT_MIN_H, lines*SLOT_LINE_H + 6); } static const char* part_str(const Part* p, char* buf, size_t cap) { size_t n = (size_t)p->len < cap - 1 ? (size_t)p->len : cap - 1; memcpy(buf, p->txt, n); buf[n] = 0; return buf; } static void add_part(EdBlock* b, int arg, const char* s, int len) { if (b->part_n >= MAX_PARTS) return; if (arg < 0) { while (len > 0 && *s == ' ') { s++; len--; } while (len > 0 && s[len-1] == ' ') len--; if (len <= 0) return; } Part* p = &b->parts[b->part_n++]; p->arg = (int16_t)arg; p->txt = s; p->len = (int16_t)len; p->x = p->w = 0; } static void build_parts(EdBlock* b) { b->part_n = 0; const TinyBlocks_TypeBlock* t = b->type; if (!t) { add_part(b, -1, b->type_name, (int)strlen(b->type_name)); return; } int n = input_count(t); bool used[MAX_INPUTS] = {0}; const BlockSpec* sp = spec_of(t->type_name); if (sp) { const char* p = sp->label; const char* seg = p; while (*p) { if (p[0] == '%' && p[1] >= '1' && p[1] <= '9') { add_part(b, -1, seg, (int)(p - seg)); int a = p[1] - '1'; if (a < n) { add_part(b, a, NULL, 0); used[a] = true; } p += 2; seg = p; } else p++; } add_part(b, -1, seg, (int)(p - seg)); } else if (t->type_name && strncmp(t->type_name, "User.", 5) == 0) { UserBlockDef* def = g_active_ed ? user_def_find(g_active_ed, t->type_name + 5) : NULL; if (!def) { add_part(b, -1, t->type_name + 5, (int)strlen(t->type_name + 5)); } else { add_part(b, -1, def->name, (int)strlen(def->name)); int ii = 0; for (int k = 0; k < def->part_n; k++) { UserParam* pp = &def->parts[k]; if (pp->kind == PARAM_LABEL) { add_part(b, -1, pp->name, (int)strlen(pp->name)); } else if (ii < n) { add_part(b, ii, NULL, 0); used[ii] = true; ii++; } } } } else { const char* nm = display_name(t->type_name); add_part(b, -1, nm, (int)strlen(nm)); } /* Campos que o rótulo não cita: "nome [campo]" ao final */ for (int i = 0; i < n; i++) { if (used[i]) continue; const char* sn = t->input_descs[i].name; if (sn) add_part(b, -1, sn, (int)strlen(sn)); add_part(b, i, NULL, 0); } } static void measure(Tab* T, int bi); static float measure_chain(Tab* T, int head) { float h = 0; for (int c = head; c >= 0; c = T->ws[c].next) { measure(T, c); h += T->ws[c].h; } return h; } static void measure(Tab* T, int bi) { EdBlock* b = &T->ws[bi]; Shape sh = shape_of(b->type); bool val = shape_is_value(sh); build_parts(b); float pad = sh == SH_BOOL ? 12.f : BLK_PAD; float row_h = val ? ROW_MIN_REP : ROW_MIN_STACK; float x = pad; char buf[96]; for (int i = 0; i < b->part_n; i++) { Part* p = &b->parts[i]; p->x = x; if (p->arg < 0) { p->w = tw(part_str(p, buf, sizeof(buf)), FS); } else { int s = p->arg; float aw, ah; if (b->args[s] >= 0) { measure(T, b->args[s]); aw = T->ws[b->args[s]].w; ah = T->ws[b->args[s]].h; } else slot_size(b, s, &aw, &ah); b->slot_x[s] = x; b->slot_w[s] = aw; b->slot_h[s] = ah; p->w = aw; if (ah + 8 > row_h) row_h = ah + 8; } x += p->w + BLK_GAP; } float w = b->part_n ? x - BLK_GAP + pad : 2*pad; b->row_y = sh == SH_HAT ? HAT_CAP : 0.f; b->row_h = row_h; for (int i = 0; i < b->part_n; i++) { int s = b->parts[i].arg; if (s >= 0) b->slot_y[s] = b->row_y + (row_h - b->slot_h[s]) * 0.5f; } float h = b->row_y + row_h; switch (sh) { case SH_HAT: if (w < HAT_CAP_W + 16) w = HAT_CAP_W + 16; break; case SH_STACK: if (w < 64) w = 64; break; case SH_C1: case SH_C2: { int mouths = sh == SH_C2 ? 2 : 1; float y = row_h; for (int k = 0; k < mouths; k++) { float ch = b->sub[k] >= 0 ? measure_chain(T, b->sub[k]) : 0.f; b->sub_y[k] = y; b->sub_h[k] = ch > MOUTH_MIN ? ch : MOUTH_MIN; y += b->sub_h[k]; if (k == 0 && mouths == 2) y += MID_H; } h = y + BOT_H; if (w < 150) w = 150; break; } default: if (w < row_h) w = row_h; break; } b->prev_y = 0; if (b->type && b->type->on_draw) { b->prev_y = h; h += PREVIEW_H; if (w < PREVIEW_W) w = PREVIEW_W; } b->w = w; b->h = h; } static void place_chain(Tab* T, int head, float x, float y); static void place(Tab* T, int bi, float x, float y) { EdBlock* b = &T->ws[bi]; b->ax = x; b->ay = y; for (int s = 0; s < MAX_INPUTS; s++) if (b->args[s] >= 0) place(T, b->args[s], x + b->slot_x[s], y + b->slot_y[s]); for (int k = 0; k < 2; k++) if (b->sub[k] >= 0) place_chain(T, b->sub[k], x + ARM_W, y + b->sub_y[k]); } static void place_chain(Tab* T, int head, float x, float y) { for (int c = head; c >= 0; c = T->ws[c].next) { place(T, c, x, y); y += T->ws[c].h; } } static void layout_tab(Tab* T) { for (int i = 0; i < T->top_n; i++) { int h = T->top[i]; measure_chain(T, h); place_chain(T, h, T->ws[h].x, T->ws[h].y); } } /* === * Hit testing (coordenadas do workspace) * === */ static bool body_contains(const EdBlock* b, float x, float y) { if (!in_rect(x, y, b->ax, b->ay, b->w, b->h)) return false; float lx = x - b->ax, ly = y - b->ay; Shape sh = shape_of(b->type); if (sh == SH_C1 || sh == SH_C2) { if (lx < ARM_W || ly < b->row_h || ly >= b->h - BOT_H) return true; return sh == SH_C2 && ly >= b->sub_y[0] + b->sub_h[0] && ly < b->sub_y[1]; } if (sh == SH_HAT && ly < HAT_CAP && lx > HAT_CAP_W) return false; return true; } static int hit_chain(Tab* T, int head, float x, float y); /* Bloco mais interno sob (x,y) dentro de bi */ static int hit_one(Tab* T, int bi, float x, float y) { EdBlock* b = &T->ws[bi]; for (int s = 0; s < MAX_INPUTS; s++) { if (b->args[s] < 0) continue; int r = hit_one(T, b->args[s], x, y); if (r >= 0) return r; } for (int k = 0; k < 2; k++) { if (b->sub[k] < 0) continue; int r = hit_chain(T, b->sub[k], x, y); if (r >= 0) return r; } return body_contains(b, x, y) ? bi : -1; } static int hit_chain(Tab* T, int head, float x, float y) { for (int c = head; c >= 0; c = T->ws[c].next) { int r = hit_one(T, c, x, y); if (r >= 0) return r; } return -1; } static int hit_ws(Tab* T, float x, float y) { for (int i = T->top_n - 1; i >= 0; i--) { int r = hit_chain(T, T->top[i], x, y); if (r >= 0) return r; } return -1; } /* Campo vazio de bi sob (x,y) */ static int hit_slot(Tab* T, int bi, float x, float y) { EdBlock* b = &T->ws[bi]; for (int s = 0; s < input_count(b->type); s++) { if (b->args[s] >= 0) continue; if (in_rect(x, y, b->ax + b->slot_x[s], b->ay + b->slot_y[s], b->slot_w[s], b->slot_h[s])) return s; } return -1; } /* === * Renderização de blocos * === */ /* Campo de nome de variavel (slot 0 de Variables.Get/Set/Change): * desenhado laranja (cor da categoria), como no Scratch. */ static bool slot_is_var_name(const TinyBlocks_TypeBlock* t, int s) { if (!t || !t->type_name || s != 0) return false; const char* n = t->type_name; return strcmp(n, "Variables.Get") == 0 || strcmp(n, "Variables.Set") == 0 || strcmp(n, "Variables.Change") == 0; } static void draw_slot(TinyBlocks_RenderableBlock* rb, const EdBlock* b, int s, float x, float y, Col dark, bool editing) { float sx = x + b->slot_x[s], sy = y + b->slot_y[s]; float sw = b->slot_w[s], sh = b->slot_h[s]; if (slot_is_bool(b->type, s)) { draw_hex(rb, sx, sy, sw, sh, col_mul(dark, 0.9f)); return; } bool varname = slot_is_var_name(b->type, s); /* Laranja num tom mais escuro que o bloco, para o campo aparecer * (como o "vinco" do dropdown de variavel do Scratch). */ Col border = varname ? col_mul(COL_VAR, 0.60f) : COLA(0,0,0,40); Col fill = varname ? col_mul(COL_VAR, 0.82f) : COL_WHITE; Col txt = varname ? COL_WHITE : COL_TEXT; const char* src = slot_src(b, s); int lines = text_lines(src); float rad = lines > 1 ? 4.f : sh*0.5f; rb_fill_rrect(rb, sx, sy, sw, sh, rad, editing ? COL_MENU : border); rb_fill_rrect(rb, sx+1, sy+1, sw-2, sh-2, rad-1, fill); char line[64]; float ly = sy + (sh - lines*SLOT_LINE_H)*0.5f + SLOT_LINE_H*0.5f; float end_x = sx + sw*0.5f; for (int l = 0; l < lines; l++) { text_line(src, l, line, sizeof(line)); float lw = tw(line, FS); float lx = lines > 1 ? sx + 7 : sx + (sw - lw)*0.5f; rb_text_c(rb, lx, ly, line, txt, FS); end_x = lx + lw; ly += SLOT_LINE_H; } if (editing) rb_fill_rect(rb, end_x + 1, ly - SLOT_LINE_H - 7, 1.5f, 14, txt); } static void render_chain(Ed* ed, TinyBlocks_RenderableBlock* rb, Tab* T, int head, float ox, float oy); static void render_block(Ed* ed, TinyBlocks_RenderableBlock* rb, Tab* T, int bi, float ox, float oy) { EdBlock* b = &T->ws[bi]; Shape sh = shape_of(b->type); Col c, d; block_cols(ed, b, &c, &d); float x = b->ax + ox, y = b->ay + oy, w = b->w, h = b->h; /* == Corpo: contorno escuro + preenchimento === */ switch (sh) { case SH_HAT: rb_fill_rrect(rb, x, y, HAT_CAP_W, HAT_CAP*2 + 4, HAT_CAP, d); rb_fill_rrect(rb, x, y + HAT_CAP, w, h - HAT_CAP, 4, d); rb_fill_rrect(rb, x+1, y+1, HAT_CAP_W-2, HAT_CAP*2 + 2, HAT_CAP-1, c); rb_fill_rrect(rb, x+1, y + HAT_CAP + 1, w-2, h - HAT_CAP - 2, 3, c); break; case SH_C1: case SH_C2: { float r[4][4] = { { x, y, w, b->row_h }, /* braço superior */ { x, y, ARM_W, h }, /* braço esquerdo */ { x, y + h - BOT_H, w, BOT_H }, /* braço inferior */ { x, y + b->sub_y[0] + b->sub_h[0], w, MID_H }, /* "senão" */ }; int n = sh == SH_C2 ? 4 : 3; for (int i = 0; i < n; i++) rb_fill_rrect(rb, r[i][0], r[i][1], r[i][2], r[i][3], 4, d); for (int i = 0; i < n; i++) rb_fill_rrect(rb, r[i][0]+1, r[i][1]+1, r[i][2]-2, r[i][3]-2, 3, c); break; } case SH_REPORTER: { float rad = b->prev_y > 0 ? 8.f : h*0.5f; rb_fill_rrect(rb, x, y, w, h, rad, d); rb_fill_rrect(rb, x+1, y+1, w-2, h-2, rad-1, c); break; } case SH_BOOL: draw_hex(rb, x, y, w, h, d); draw_hex(rb, x+1, y+1, w-2, h-2, c); break; default: rb_fill_rrect(rb, x, y, w, h, 4, d); rb_fill_rrect(rb, x+1, y+1, w-2, h-2, 3, c); break; } /* == Rótulo e campos vazios === */ float cy = y + b->row_y + b->row_h*0.5f; char buf[96]; bool can_edit = ed->editing && T == &CT && ed->edit_bi == bi; for (int i = 0; i < b->part_n; i++) { const Part* p = &b->parts[i]; if (p->arg < 0) rb_text_c(rb, x + p->x, cy, part_str(p, buf, sizeof(buf)), COL_WHITE, FS); else if (b->args[p->arg] < 0) draw_slot(rb, b, p->arg, x, y, d, can_edit && ed->edit_in == p->arg); } if (sh == SH_C2) rb_text_c(rb, x + BLK_PAD, y + b->sub_y[0] + b->sub_h[0] + MID_H*0.5f, "senão", COL_WHITE, FS); /* == Bocas (pilhas internas) === */ int mouths = sh == SH_C1 ? 1 : sh == SH_C2 ? 2 : 0; for (int k = 0; k < mouths; k++) { if (b->sub[k] >= 0) render_chain(ed, rb, T, b->sub[k], ox, oy); draw_bump(rb, x + ARM_W, y + b->sub_y[k], c, d); } /* == Repórteres encaixados === */ for (int s = 0; s < MAX_INPUTS; s++) if (b->args[s] >= 0) render_block(ed, rb, T, b->args[s], ox, oy); /* == Área de on_draw === */ if (b->prev_y > 0) { float py = y + b->prev_y; rb_fill_rrect(rb, x+4, py, w-8, PREVIEW_H-4, 4, col_mul(c, 0.85f)); if (b->live_rt) { TinyBlocks_RenderableBlock* sub = NULL; tb_draw_set_clip(rb, x+4, py, w-8, PREVIEW_H-4); if (b->type->on_draw(b->live_rt, ed->rt, &sub) && sub) { tb_draw_merge_offset(rb, sub, x, py); tb_renderable_release(sub); } clip_restore(ed, rb); } } /* Encaixe inferior por último: fica sobre o topo do bloco seguinte */ if (!shape_is_value(sh)) draw_bump(rb, x, y + h, c, d); } /* Desenha de baixo para cima, para cada encaixe cobrir o bloco seguinte */ static void render_chain(Ed* ed, TinyBlocks_RenderableBlock* rb, Tab* T, int head, float ox, float oy) { int ids[MAX_WS], n = 0; for (int c = head; c >= 0 && n < MAX_WS; c = T->ws[c].next) ids[n++] = c; for (int i = n - 1; i >= 0; i--) render_block(ed, rb, T, ids[i], ox, oy); } /* === * Execução * === */ static void stage_append(Ed* ed, const char* s) { size_t cur = strlen(ed->stage_buf), add = strlen(s); if (add >= STAGE_BUF/2) { s += add - STAGE_BUF/2; add = strlen(s); } if (cur + add >= STAGE_BUF - 1) { size_t drop = cur + add - (STAGE_BUF - 1); const char* nl = strchr(ed->stage_buf + drop, '\n'); drop = nl ? (size_t)(nl - ed->stage_buf) + 1 : cur; memmove(ed->stage_buf, ed->stage_buf + drop, cur - drop + 1); } strcat(ed->stage_buf, s); } static void run_abort(Ed* ed, const char* msg) { if (ed->abort) return; ed->abort = true; snprintf(ed->abort_msg, sizeof(ed->abort_msg), "%s", msg); } static void clear_live(Tab* T) { for (int i = 0; i < MAX_WS; i++) T->ws[i].live_rt = NULL; } /* Destrói as instâncias do runtime da execução anterior */ static void run_reset(Ed* ed) { for (int i = ed->run_n - 1; i >= 0; i--) tb_block_destroy(ed->run_blocks[i], ed->rt); ed->run_n = 0; for (int t = 0; t < ed->tab_n; t++) clear_live(&ed->tabs[t]); /* Referências a blocos (não-owning) agora estariam penduradas */ tb_variables_reset_blocks(); } static void run_track(Ed* ed, TinyBlocks_Block* b) { if (ed->run_n >= ed->run_cap) { int nc = ed->run_cap ? ed->run_cap*2 : 256; TinyBlocks_Block** p = realloc(ed->run_blocks, (size_t)nc * sizeof(*p)); if (!p) return; ed->run_blocks = p; ed->run_cap = nc; } ed->run_blocks[ed->run_n++] = b; } static TinyBlocks_TypeBlock* blk_type(Ed* ed, EdBlock* b) { if (!b->type && b->type_name[0]) b->type = tb_type_block_find(ed->rt, b->type_name); return b->type; } /* Converte o bloco bi (e seus repórteres) em uma árvore de blocos do runtime */ static TinyBlocks_Block* build_rt(Ed* ed, Tab* T, int bi) { EdBlock* b = &T->ws[bi]; TinyBlocks_TypeBlock* t = blk_type(ed, b); if (!t) return NULL; if (ed->run_n >= MAX_RUN_BLOCKS) { run_abort(ed, "limite de blocos em execução atingido"); return NULL; } TinyBlocks_Block* r = tb_block_create(ed->rt, t); if (!r) return NULL; run_track(ed, r); if (T == ed->live_tab) b->live_rt = r; bool lit = is_lit_text(t); for (int s = 0; s < input_count(t); s++) { if (b->args[s] >= 0) { TinyBlocks_Block* c = build_rt(ed, T, b->args[s]); if (c && c->output_count > 0) tb_block_connect(r, (uint32_t)s, c, 0); continue; } const char* raw = slot_src(b, s); if (!raw[0]) continue; TinyBlocks_ValueKind k = lit ? TB_VALUE_TEXT : t->input_descs[s].expected_kind; TinyBlocks_Value v = value_from_text(raw, k); tb_block_set_default(r, (uint32_t)s, v); tb_value_free(&v); } return r; } /* Avalia um repórter; devolve uma cópia (owned) do primeiro output */ static TinyBlocks_Value eval_reporter(Ed* ed, Tab* T, int bi) { TinyBlocks_Block* r = build_rt(ed, T, bi); if (!r) return tb_value_none(); tb_block_eval(r, ed->rt); return r->output_count > 0 ? tb_value_clone(r->outputs[0]) : tb_value_none(); } static TinyBlocks_Value eval_arg(Ed* ed, Tab* T, int bi, int s) { EdBlock* b = &T->ws[bi]; if (b->args[s] >= 0) return eval_reporter(ed, T, b->args[s]); const char* raw = slot_src(b, s); if (!raw[0] || !b->type) return tb_value_none(); return value_from_text(raw, b->type->input_descs[s].expected_kind); } static bool step(Ed* ed) { if (++ed->steps > MAX_STEPS) run_abort(ed, "limite de passos atingido (laço infinito?)"); return !ed->abort; } static void run_chain(Ed* ed, Tab* T, int head) { for (int bi = head; bi >= 0 && step(ed); bi = T->ws[bi].next) { EdBlock* b = &T->ws[bi]; TinyBlocks_TypeBlock* t = blk_type(ed, b); if (!t) continue; const char* tn = t->type_name; Shape sh = shape_of(t); if (sh == SH_HAT || shape_is_value(sh)) continue; if (strcmp(tn, "Control.Repeat") == 0) { TinyBlocks_Value v = eval_arg(ed, T, bi, 0); long long n = value_to_ll(&v); tb_value_free(&v); for (long long k = 0; k < n && step(ed); k++) run_chain(ed, T, b->sub[0]); } else if (strcmp(tn, "Control.RepeatUntil") == 0) { for (;;) { TinyBlocks_Value v = eval_arg(ed, T, bi, 0); bool done = value_truthy(&v); tb_value_free(&v); if (done || !step(ed)) break; run_chain(ed, T, b->sub[0]); } } else if (strcmp(tn, "Control.If") == 0 || strcmp(tn, "Control.IfElse") == 0) { TinyBlocks_Value v = eval_arg(ed, T, bi, 0); bool cond = value_truthy(&v); tb_value_free(&v); if (cond) run_chain(ed, T, b->sub[0]); else if (sh == SH_C2) run_chain(ed, T, b->sub[1]); } else { TinyBlocks_Block* r = build_rt(ed, T, bi); if (r) tb_block_eval(r, ed->rt); } } } /* Início/fim de uma execução: zera o runtime e captura o stdout no palco */ static void run_begin(Ed* ed, bool clear) { run_reset(ed); ed->steps = 0; ed->abort = false; ed->abort_msg[0] = 0; ed->frame_n = 0; ed->live_tab = &CT; if (clear) ed->stage_buf[0] = 0; fflush(stdout); ed->cap_file = tmpfile(); ed->cap_saved = -1; if (ed->cap_file) { ed->cap_saved = dup(STDOUT_FILENO); if (ed->cap_saved >= 0) dup2(fileno(ed->cap_file), STDOUT_FILENO); else { fclose(ed->cap_file); ed->cap_file = NULL; } } } static void run_end(Ed* ed) { if (ed->cap_file) { fflush(stdout); dup2(ed->cap_saved, STDOUT_FILENO); close(ed->cap_saved); rewind(ed->cap_file); char buf[STAGE_BUF]; size_t n = fread(buf, 1, sizeof(buf) - 1, ed->cap_file); buf[n] = 0; fclose(ed->cap_file); ed->cap_file = NULL; stage_append(ed, buf); } const char* err = tinyblocks_last_error(ed->rt); if (err && err[0]) { char warn[512]; snprintf(warn, sizeof(warn), "[AVISO] %s\n", err); stage_append(ed, warn); tinyblocks_clear_error(ed->rt); } if (ed->abort_msg[0]) { char msg[200]; snprintf(msg, sizeof(msg), "[ERRO] %s\n", ed->abort_msg); stage_append(ed, msg); } ed->live_tab = NULL; palette_rebuild(ed); /* variáveis novas aparecem no flyout */ } /* Bandeira verde: roda os scripts "quando a bandeira for clicado", de cima para baixo */ static void run_flag(Ed* ed) { run_begin(ed, true); int heads[MAX_WS], n = 0; for (int i = 0; i < CT.top_n; i++) heads[n++] = CT.top[i]; for (int i = 1; i < n; i++) for (int j = i; j > 0 && CT.ws[heads[j]].y < CT.ws[heads[j-1]].y; j--) { int tmp = heads[j]; heads[j] = heads[j-1]; heads[j-1] = tmp; } int started = 0; for (int i = 0; i < n && !ed->abort; i++) { EdBlock* b = &CT.ws[heads[i]]; if (blk_type(ed, b) && strcmp(b->type->type_name, "Events.WhenRun") == 0) { run_chain(ed, &CT, heads[i]); started++; } } run_end(ed); if (!started) stage_append(ed, "Nenhum script começa com \"quando a bandeira for clicado\".\n"); } /* Libera o balão de resultado (texto + eventual lista de pontos) */ static 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; ed->bubble_text[0] = 0; } /* Um array JSON é "lista de pontos" quando todos os itens são [x, y]? */ static bool json_is_points(const TinyBlocks_JsonValue* j) { if (!j || tb_json_kind(j) != TB_JSON_ARRAY) return false; uint32_t n = tb_json_array_length(j); if (n < 2) return false; for (uint32_t i = 0; i < n; i++) { TinyBlocks_JsonValue* p = tb_json_array_get(j, (uint32_t)i); bool ok = p && tb_json_kind(p) == TB_JSON_ARRAY && tb_json_array_length(p) >= 2; if (p) tb_json_release(p); if (!ok) return false; } return true; } /* Lê o ponto i de uma lista [[x,y],...] */ static bool json_point_at(const TinyBlocks_JsonValue* arr, int i, double* x, double* y) { if (!arr || tb_json_kind(arr) != TB_JSON_ARRAY) return false; TinyBlocks_JsonValue* p = tb_json_array_get(arr, (uint32_t)i); if (!p) return false; bool ok = tb_json_kind(p) == TB_JSON_ARRAY && tb_json_array_length(p) >= 2; if (ok) { TinyBlocks_JsonValue* p0 = tb_json_array_get(p, 0); TinyBlocks_JsonValue* p1 = tb_json_array_get(p, 1); if (x) *x = tb_json_as_number(p0, 0.0); if (y) *y = tb_json_as_number(p1, 0.0); tb_json_release(p0); tb_json_release(p1); } tb_json_release(p); return ok; } /* Mostra o resultado de um repórter no balão (estilo Scratch) */ static void bubble_set(Ed* ed, int root, TinyBlocks_Value* v) { bubble_clear(ed); ed->bubble_bi = root; if (v->kind == TB_VALUE_JSON && v->as.json && json_is_points(v->as.json)) { tb_json_retain(v->as.json); ed->bubble_json = v->as.json; snprintf(ed->bubble_text, sizeof(ed->bubble_text), "%u pontos", (unsigned)tb_json_array_length(v->as.json)); return; } if (v->kind == TB_VALUE_IMAGE && v->as.image) { tb_image_retain(v->as.image); ed->bubble_img = v->as.image; snprintf(ed->bubble_text, sizeof(ed->bubble_text), "%dx%d", tb_image_width(v->as.image), tb_image_height(v->as.image)); return; } value_to_str(v, ed->bubble_text, sizeof(ed->bubble_text)); if (!ed->bubble_text[0]) strcpy(ed->bubble_text, "(vazio)"); } /* Clique num bloco: roda a pilha inteira, ou mostra o valor de um repórter */ static void run_click(Ed* ed, int bi) { int root = stack_root(&CT, bi); Shape sh = shape_of(blk_type(ed, &CT.ws[root])); run_begin(ed, false); if (shape_is_value(sh)) { TinyBlocks_Value v = eval_reporter(ed, &CT, root); bubble_set(ed, root, &v); tb_value_free(&v); } else { run_chain(ed, &CT, root); } run_end(ed); } /* Relógio monotônico em milissegundos (detecção de clique duplo) */ static unsigned now_ms(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (unsigned)(ts.tv_sec * 1000u + ts.tv_nsec / 1000000u); } /* === * Portas de blocos compostos ("Meus Blocos") * === */ static void input_name(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i, char* out, size_t cap) { TinyBlocks_Value v = tb_block_get_input(self, rt, i); value_to_str(&v, out, cap); } /* == Blocos compostos ("Meus Blocos") === * A definição é uma aba com scripts; "parâmetro [x]" lê os inputs da chamada * e "devolva [y] - (v)" escreve os outputs. */ static CallFrame* cur_frame(void) { Ed* ed = g_active_ed; return (ed && ed->frame_n > 0) ? &ed->frames[ed->frame_n - 1] : NULL; } static void eval_port_in(TinyBlocks_Block* self, TinyBlocks* rt) { CallFrame* f = cur_frame(); TinyBlocks_Value out = tb_value_none(); if (f) { char label[64]; input_name(self, rt, 0, label, sizeof(label)); for (int i = 0; i < f->def->input_count; i++) if (strcmp(f->def->input_names[i], label) == 0) { out = tb_value_clone(f->in[i]); break; } } tb_block_set_output(self, 0, out); self->dirty = false; } static void eval_port_out(TinyBlocks_Block* self, TinyBlocks* rt) { CallFrame* f = cur_frame(); if (f) { char label[64]; input_name(self, rt, 0, label, sizeof(label)); for (int i = 0; i < f->def->output_count; i++) { if (strcmp(f->def->output_names[i], label) != 0) continue; tb_value_free(&f->out[i]); f->out[i] = tb_value_clone(tb_block_get_input(self, rt, 1)); break; } } self->dirty = false; } static void eval_composite(TinyBlocks_Block* self, TinyBlocks* rt) { Ed* ed = g_active_ed; self->dirty = false; const char* tn = self->type ? self->type->type_name : ""; if (!ed || strncmp(tn, "User.", 5) != 0) return; UserBlockDef* def = user_def_find(ed, tn + 5); if (!def || !def->snap) return; if (ed->frame_n >= MAX_CALL_DEPTH) { run_abort(ed, "recursão profunda demais em bloco composto"); return; } CallFrame* f = &ed->frames[ed->frame_n++]; memset(f, 0, sizeof(*f)); f->def = def; for (int i = 0; i < def->input_count; i++) f->in[i] = tb_value_clone(tb_block_get_input(self, rt, (uint32_t)i)); /* Roda os scripts da definição de cima para baixo */ Tab* S = def->snap; int heads[MAX_WS], n = 0; for (int i = 0; i < S->top_n; i++) heads[n++] = S->top[i]; for (int i = 1; i < n; i++) for (int j = i; j > 0 && S->ws[heads[j]].y < S->ws[heads[j-1]].y; j--) { int tmp = heads[j]; heads[j] = heads[j-1]; heads[j-1] = tmp; } for (int i = 0; i < n && !ed->abort; i++) if (!shape_is_value(shape_of(blk_type(ed, &S->ws[heads[i]])))) run_chain(ed, S, heads[i]); for (int i = 0; i < def->output_count; i++) { tb_block_set_output(self, (uint32_t)i, f->out[i]); /* transfere ownership */ f->out[i] = tb_value_none(); } for (int i = 0; i < def->input_count; i++) tb_value_free(&f->in[i]); ed->frame_n--; } /* === * Tipos: invalidação/re-resolução (hot reload e redefinição de compostos) * === */ static void invalidate_tab(Tab* T) { for (int i = 0; i < MAX_WS; i++) { T->ws[i].type = NULL; T->ws[i].live_rt = NULL; } } static void invalidate_types(Ed* ed) { run_reset(ed); for (int t = 0; t < ed->tab_n; t++) invalidate_tab(&ed->tabs[t]); for (int u = 0; u < ed->user_block_n; u++) if (ed->user_blocks[u].snap) invalidate_tab(ed->user_blocks[u].snap); invalidate_tab(&ed->fly); } static void retype_tab(Ed* ed, Tab* T) { for (int i = 0; i < MAX_WS; i++) { EdBlock* b = &T->ws[i]; if (!b->used) continue; b->type = b->type_name[0] ? tb_type_block_find(ed->rt, b->type_name) : NULL; if (!b->type) continue; /* O tipo pode ter perdido campos: repórteres órfãos ficam soltos */ for (int s = input_count(b->type); s < MAX_INPUTS; s++) { int c = b->args[s]; if (c < 0) continue; detach(T, c); T->ws[c].x = b->ax + b->w + 16; T->ws[c].y = b->ay; } } } static void retype_all(Ed* ed) { for (int t = 0; t < ed->tab_n; t++) retype_tab(ed, &ed->tabs[t]); for (int u = 0; u < ed->user_block_n; u++) if (ed->user_blocks[u].snap) retype_tab(ed, ed->user_blocks[u].snap); palette_rebuild(ed); } /* === * Paleta: categorias + flyout * === */ static bool type_hidden(Ed* ed, const TinyBlocks_TypeBlock* t) { const char* n = t->type_name; if (!n || n[0] == '_' || strstr(n, "._")) return true; if (strncmp(n, "Editor.", 7) == 0 || strncmp(n, "Graphics.", 9) == 0) return true; if (strcmp(n, "Literal.Integer") == 0 || strcmp(n, "Literal.Real") == 0) return true; if (strncmp(n, "Port.", 5) == 0) return !CT.is_composite; return false; } static void cats_rebuild(Ed* ed) { ed->cat_n = 0; /* 1) Categoria declarada por cada library, na ordem de registro */ for (uint32_t i = 0; i < tb_rt_library_count(ed->rt) && ed->cat_n < MAX_CATS; i++) { TinyBlocks_LibraryBlock* lib = tb_rt_library_at(ed->rt, i); const TinyBlocks_Category* cat = tb_library_category(lib); if (!cat || !cat->name) continue; Cat* c = &ed->cats[ed->cat_n++]; memset(c, 0, sizeof(*c)); snprintf(c->name, sizeof(c->name), "%s", cat->name); c->col = (Col){cat->color[0], cat->color[1], cat->color[2], cat->color[3]}; c->dark = (Col){cat->dark[0], cat->dark[1], cat->dark[2], cat->dark[3]}; c->lib = lib; } /* 2) "Meus Blocos" pertence ao editor */ ed->myblocks_cat = -1; if (ed->cat_n < MAX_CATS) { Cat* c = &ed->cats[ed->cat_n++]; memset(c, 0, sizeof(*c)); snprintf(c->name, sizeof(c->name), "Meus Blocos"); c->col = COL_MYBLOCKS_COL; c->dark = COL_MYBLOCKS_DARK; ed->myblocks_cat = ed->cat_n - 1; } /* 3) Uma categoria por prefixo para libraries/tipos sem categoria */ for (uint32_t i = 0; i < tb_rt_type_count(ed->rt) && ed->cat_n < MAX_CATS; i++) { TinyBlocks_TypeBlock* t = tb_rt_type_at(ed->rt, i); if (type_hidden(ed, t) || cat_of_type(ed, t) >= 0) continue; Cat* c = &ed->cats[ed->cat_n++]; memset(c, 0, sizeof(*c)); type_prefix(t->type_name, c->prefix, sizeof(c->prefix)); strncpy(c->name, c->prefix, sizeof(c->name) - 1); c->name[sizeof(c->name) - 1] = 0; c->col = COL_EXT; c->dark = COL_EXT_DARK; } } static void fly_add_block(Ed* ed, int cat, TinyBlocks_TypeBlock* t, const char* first, float* y) { if (ed->fly_n >= MAX_FLY) return; int bi = blk_new(&ed->fly, t); if (bi < 0) return; if (first) strncpy(ed->fly.ws[bi].in_text[0], first, 63); measure(&ed->fly, bi); place(&ed->fly, bi, FLY_PAD, *y); float h = ed->fly.ws[bi].h; ed->fly_items[ed->fly_n++] = (FlyItem){FI_BLOCK, cat, bi, *y, h + NOTCH_D}; *y += h + 14; } static void palette_rebuild(Ed* ed) { cats_rebuild(ed); memset(&ed->fly, 0, sizeof(ed->fly)); ed->fly_n = 0; float y = 8; TinyBlocks_TypeBlock* var_get = tb_type_block_find(ed->rt, "Variables.Get"); int var_cat = cat_of(ed, "Variables.Get"); for (int c = 0; c < ed->cat_n && ed->fly_n < MAX_FLY; c++) { ed->cats[c].fly_y = y; ed->fly_items[ed->fly_n++] = (FlyItem){FI_HEADER, c, -1, y, 34}; y += 34; if (c == ed->myblocks_cat && ed->fly_n < MAX_FLY) { ed->fly_items[ed->fly_n++] = (FlyItem){FI_BUTTON, c, -1, y, 42}; y += 42; } for (uint32_t i = 0; i < tb_rt_type_count(ed->rt); i++) { TinyBlocks_TypeBlock* t = tb_rt_type_at(ed->rt, i); if (type_hidden(ed, t) || cat_of_type(ed, t) != c) continue; fly_add_block(ed, c, t, NULL, &y); } if (var_get && c == var_cat) for (int v = 0; v < tb_variables_count(); v++) fly_add_block(ed, c, var_get, tb_variables_name(v), &y); y += 10; } ed->fly_total_h = y; } static float cat_item_h(Ed* ed) { float h = ed->cat_n ? (WIN_H - PAL_Y) / (float)ed->cat_n : 58.f; return h > 58.f ? 58.f : h; } static int current_cat(Ed* ed) { int cur = 0; for (int c = 0; c < ed->cat_n; c++) if (ed->cats[c].fly_y <= ed->fly_scroll + 16) cur = c; return cur; } static float fly_max_scroll(Ed* ed) { float m = ed->fly_total_h - 60; return m > 0 ? m : 0; } /* === * Abas e blocos compostos * === */ static void tab_select(Ed* ed, int i) { if (i < 0 || i >= ed->tab_n) return; ed->cur_tab = i; ed->editing = false; bubble_clear(ed); if (CT.is_composite) { const char* nm = CT.comp_id >= 0 ? ed->user_blocks[CT.comp_id].name : ""; strncpy(ed->comp_name_buf, nm, sizeof(ed->comp_name_buf) - 1); ed->comp_name_buf[sizeof(ed->comp_name_buf) - 1] = 0; ed->comp_name_len = (int)strlen(ed->comp_name_buf); } palette_rebuild(ed); } static bool tab_new(Ed* ed, const char* name, bool is_composite) { if (ed->tab_n >= MAX_TABS) { snprintf(ed->hot_status, sizeof(ed->hot_status), "Limite de %d abas atingido", MAX_TABS); ed->hot_status_ok = false; return false; } int idx = ed->tab_n++; Tab* T = &ed->tabs[idx]; memset(T, 0, sizeof(*T)); if (name && name[0]) strncpy(T->name, name, sizeof(T->name) - 1); else snprintf(T->name, sizeof(T->name), "Código %d", idx + 1); T->comp_id = -1; T->is_composite = is_composite; tab_select(ed, idx); return true; } static void tab_close(Ed* ed, int ti) { if (ed->tab_n <= 1 || ti < 0 || ti >= ed->tab_n) return; run_reset(ed); for (int i = ti; i < ed->tab_n - 1; i++) ed->tabs[i] = ed->tabs[i+1]; ed->tab_n--; for (int u = 0; u < ed->user_block_n; u++) { int* t = &ed->user_blocks[u].tab_idx; if (*t == ti) *t = -1; else if (*t > ti) (*t)--; } tab_select(ed, ed->cur_tab >= ed->tab_n ? ed->tab_n - 1 : ed->cur_tab > ti ? ed->cur_tab - 1 : ed->cur_tab); } static void new_composite_tab(Ed* ed) { dlg_open(ed, -1); } static void open_def(Ed* ed, const char* uname) { UserBlockDef* def = user_def_find(ed, uname); if (!def) return; if (def->tab_idx >= 0 && def->tab_idx < ed->tab_n) { tab_select(ed, def->tab_idx); return; } /* A aba foi fechada: recria a partir da cópia salva */ if (!def->snap || !tab_new(ed, def->name, true)) return; Tab* T = &CT; *T = *def->snap; clear_live(T); snprintf(T->name, sizeof(T->name), "%s", def->name); T->is_composite = true; T->comp_id = (int)(def - ed->user_blocks); T->color_idx = def->color_idx; def->tab_idx = ed->cur_tab; tab_select(ed, ed->cur_tab); } static void collect_labels(Tab* T, const char* type_name, char names[][32], int* count, const char* fallback) { *count = 0; for (int i = 0; i < MAX_WS && *count < MAX_UBLK_SLOTS; i++) { EdBlock* b = &T->ws[i]; if (!b->used || strcmp(b->type_name, type_name) != 0) continue; char lbl[32]; if (b->in_text[0][0]) snprintf(lbl, sizeof(lbl), "%.31s", b->in_text[0]); else snprintf(lbl, sizeof(lbl), fallback, *count); bool dup = false; for (int k = 0; k < *count; k++) if (strcmp(names[k], lbl) == 0) dup = true; if (!dup) strcpy(names[(*count)++], lbl); } } /* Reconcilia os blocos Port.In do corpo com as entradas do protótipo */ static void comp_sync_inputs(Ed* ed, UserBlockDef* def, Tab* T) { int ids[MAX_WS], n = 0; for (int i = 0; i < MAX_WS; i++) { EdBlock* b = &T->ws[i]; if (b->used && strcmp(b->type_name, "Port.In") == 0) ids[n++] = i; } TinyBlocks_TypeBlock* t_in = tb_type_block_find(ed->rt, "Port.In"); for (int k = 0; k < def->input_count; k++) { int bi = k < n ? ids[k] : (t_in ? blk_new(T, t_in) : -1); if (bi < 0) break; snprintf(T->ws[bi].in_text[0], sizeof(T->ws[bi].in_text[0]), "%s", def->input_names[k]); if (k >= n) { T->ws[bi].x = 40; T->ws[bi].y = 70 + (k - n) * 52; top_add(T, bi); } } for (int k = def->input_count; k < n; k++) free_tree(ed, T, ids[k]); } /* Deriva os nomes das entradas a partir das partes do protótipo */ static void comp_build_input_names(UserBlockDef* def) { def->input_count = 0; for (int i = 0; i < def->part_n && def->input_count < MAX_UBLK_SLOTS; i++) { if (def->parts[i].kind == PARAM_LABEL) continue; char nm[64]; if (def->parts[i].name[0]) snprintf(nm, sizeof(nm), "%s", def->parts[i].name); else snprintf(nm, sizeof(nm), "entrada %d", def->input_count + 1); char base[40]; snprintf(base, sizeof(base), "%.31s", nm); for (int suffix = 1; ; suffix++) { bool dup = false; for (int j = 0; j < def->input_count; j++) if (strcmp(def->input_names[j], nm) == 0) { dup = true; break; } if (!dup) break; snprintf(nm, sizeof(nm), "%.24s %d", base, suffix + 1); } snprintf(def->input_names[def->input_count], 32, "%.31s", nm); def->input_count++; } } /* Salva corpo da aba e re-registra o tipo do bloco composto */ static void comp_register(Ed* ed, UserBlockDef* def, Tab* T) { snprintf(T->name, sizeof(T->name), "%s", def->name); T->is_composite = true; T->comp_id = (int)(def - ed->user_blocks); T->color_idx = def->color_idx; comp_sync_inputs(ed, def, T); collect_labels(T, "Port.Out", def->output_names, &def->output_count, "out%d"); /* Instâncias e referências ao tipo antigo precisam sumir antes de destruí-lo */ invalidate_types(ed); if (def->reg_type) { tb_block_destroy(&def->reg_type->base, ed->rt); def->reg_type = NULL; } if (!def->snap) def->snap = (Tab*)malloc(sizeof(Tab)); if (def->snap) *def->snap = *T; TinyBlocks_SlotDesc in_s[MAX_UBLK_SLOTS], out_s[MAX_UBLK_SLOTS]; for (int i = 0; i < def->input_count; i++) in_s[i] = (TinyBlocks_SlotDesc){def->input_names[i], TB_VALUE_NONE}; for (int i = 0; i < def->output_count; i++) out_s[i] = (TinyBlocks_SlotDesc){def->output_names[i], TB_VALUE_NONE}; char type_name[64]; snprintf(type_name, sizeof(type_name), "User.%s", def->name); def->reg_type = tb_type_block_create(ed->rt, type_name, def->input_count ? in_s : NULL, (uint32_t)def->input_count, def->output_count ? out_s : NULL, (uint32_t)def->output_count, eval_composite); def->tab_idx = (int)(T - ed->tabs); retype_all(ed); } static void save_composite_from_tab(Ed* ed) { if (!ed->comp_name_buf[0]) { snprintf(ed->hot_status, sizeof(ed->hot_status), "Digite um nome para o bloco antes de salvar."); ed->hot_status_ok = false; return; } UserBlockDef* def = user_def_find(ed, ed->comp_name_buf); if (!def) { if (ed->user_block_n >= MAX_USER_BLOCKS) { snprintf(ed->hot_status, sizeof(ed->hot_status), "Limite de blocos compostos atingido."); ed->hot_status_ok = false; return; } def = &ed->user_blocks[ed->user_block_n++]; memset(def, 0, sizeof(*def)); def->tab_idx = ed->cur_tab; def->color_idx = CT.color_idx; snprintf(def->name, sizeof(def->name), "%s", ed->comp_name_buf); collect_labels(&CT, "Port.In", def->input_names, &def->input_count, "in%d"); } comp_register(ed, def, &CT); snprintf(ed->hot_status, sizeof(ed->hot_status), "Bloco \"%s\" salvo em Meus Blocos", def->name); ed->hot_status_ok = true; } /* === * Blueprint: conversao Ed <-> TbBlueprint e I/O de projeto * === */ static TbBlueprint* ed_to_blueprint(Ed* ed) { TbBlueprint* bp = tb_blueprint_new(); if (!bp) return NULL; bp->cur_tab = ed->cur_tab; for (int ti = 0; ti < ed->tab_n; ti++) { Tab* T = &ed->tabs[ti]; int idx = tb_blueprint_add_tab(bp, T->name, T->is_composite); if (idx < 0) break; TbBpTab* B = &bp->tabs[idx]; B->comp_id = T->comp_id; B->color_idx = T->color_idx; B->ws_sx = T->ws_sx; B->ws_sy = T->ws_sy; B->top_n = T->top_n; for (int i = 0; i < T->top_n; i++) B->top[i] = T->top[i]; for (int i = 0; i < MAX_WS; i++) { EdBlock* b = &T->ws[i]; if (!b->used) continue; TbBpBlock* o = &B->blocks[i]; o->used = true; snprintf(o->type, sizeof(o->type), "%s", b->type_name); o->x = b->x; o->y = b->y; o->parent = b->parent; o->prel = b->prel; o->next = b->next; for (int k = 0; k < 2; k++) o->sub[k] = b->sub[k]; for (int s = 0; s < MAX_INPUTS; s++) { o->args[s] = b->args[s]; snprintf(o->in_text[s], sizeof(o->in_text[s]), "%s", b->in_text[s]); } snprintf(o->lit, sizeof(o->lit), "%s", b->lit_text); } } for (int u = 0; u < ed->user_block_n && bp->user_block_n < TB_BP_MAX_UBLOCKS; u++) { UserBlockDef* d = &ed->user_blocks[u]; TbBpUserBlock* o = &bp->user_blocks[bp->user_block_n++]; memset(o, 0, sizeof(*o)); snprintf(o->name, sizeof(o->name), "%s", d->name); o->input_count = d->input_count; o->output_count = d->output_count; for (int i = 0; i < d->input_count && i < TB_BP_MAX_USLOTS; i++) snprintf(o->input_names[i], 32, "%s", d->input_names[i]); for (int i = 0; i < d->output_count && i < TB_BP_MAX_USLOTS; i++) snprintf(o->output_names[i], 32, "%s", d->output_names[i]); o->part_n = d->part_n; for (int i = 0; i < d->part_n && i < TB_BP_MAX_UPARTS; i++) { o->parts[i].kind = (TbBpParamKind)d->parts[i].kind; snprintf(o->parts[i].name, 32, "%s", d->parts[i].name); } o->color_idx = d->color_idx; o->tab_idx = d->tab_idx; } for (int i = 0; i < tb_variables_count() && bp->var_n < TB_BP_MAX_VARS; i++) { const TinyBlocks_Value* v = tb_variables_value(i); TbBpVar* o = &bp->vars[bp->var_n++]; memset(o, 0, sizeof(*o)); snprintf(o->name, sizeof(o->name), "%s", tb_variables_name(i)); if (v && v->kind == TB_VALUE_INTEGER) { o->kind = TB_BP_VAL_INT; o->num = (double)v->as.integer; } else if (v && v->kind == TB_VALUE_REAL) { o->kind = TB_BP_VAL_REAL; o->num = v->as.real; } else if (v && v->kind == TB_VALUE_TEXT && v->as.text) { o->kind = TB_BP_VAL_TEXT; snprintf(o->text, sizeof(o->text), "%s", v->as.text); } else o->kind = TB_BP_VAL_INT; } return bp; } /* Descarta tudo do editor e reconstroi a partir da blueprint. */ static void blueprint_apply(Ed* ed, const TbBlueprint* bp) { run_reset(ed); invalidate_types(ed); for (int u = 0; u < ed->user_block_n; u++) { UserBlockDef* d = &ed->user_blocks[u]; if (d->reg_type) { tb_block_destroy(&d->reg_type->base, ed->rt); d->reg_type = NULL; } free(d->snap); d->snap = NULL; } ed->user_block_n = 0; for (int t = 0; t < ed->tab_n; t++) memset(&ed->tabs[t], 0, sizeof(Tab)); ed->tab_n = 0; tb_variables_clear(); for (int u = 0; u < bp->user_block_n && ed->user_block_n < MAX_USER_BLOCKS; u++) { const TbBpUserBlock* o = &bp->user_blocks[u]; UserBlockDef* d = &ed->user_blocks[ed->user_block_n++]; memset(d, 0, sizeof(*d)); snprintf(d->name, sizeof(d->name), "%s", o->name); d->input_count = o->input_count; d->output_count = o->output_count; for (int i = 0; i < o->input_count && i < MAX_UBLK_SLOTS; i++) snprintf(d->input_names[i], 32, "%s", o->input_names[i]); for (int i = 0; i < o->output_count && i < MAX_UBLK_SLOTS; i++) snprintf(d->output_names[i], 32, "%s", o->output_names[i]); d->part_n = o->part_n; for (int i = 0; i < o->part_n && i < MAX_UBLK_PARTS; i++) { d->parts[i].kind = (ParamKind)o->parts[i].kind; snprintf(d->parts[i].name, 32, "%s", o->parts[i].name); } d->color_idx = o->color_idx; d->tab_idx = o->tab_idx; } for (int ti = 0; ti < bp->tab_count && ed->tab_n < MAX_TABS; ti++) { const TbBpTab* B = &bp->tabs[ti]; int idx = ed->tab_n++; Tab* T = &ed->tabs[idx]; memset(T, 0, sizeof(*T)); snprintf(T->name, sizeof(T->name), "%s", B->name); T->is_composite = B->composite; T->comp_id = B->comp_id; T->color_idx = B->color_idx; T->ws_sx = B->ws_sx; T->ws_sy = B->ws_sy; for (int i = 0; i < MAX_WS; i++) { T->ws[i].parent = -1; T->ws[i].prel = REL_NONE; T->ws[i].next = -1; T->ws[i].sub[0] = T->ws[i].sub[1] = -1; for (int s = 0; s < MAX_INPUTS; s++) T->ws[i].args[s] = -1; } for (int i = 0; i < MAX_WS; i++) { const TbBpBlock* o = &B->blocks[i]; if (!o->used) continue; EdBlock* b = &T->ws[i]; b->used = true; snprintf(b->type_name, sizeof(b->type_name), "%s", o->type); b->type = b->type_name[0] ? tb_type_block_find(ed->rt, b->type_name) : NULL; b->x = o->x; b->y = o->y; b->parent = o->parent; b->prel = o->prel; b->next = o->next; for (int k = 0; k < 2; k++) b->sub[k] = o->sub[k]; for (int s = 0; s < MAX_INPUTS; s++) { b->args[s] = o->args[s]; snprintf(b->in_text[s], sizeof(b->in_text[s]), "%s", o->in_text[s]); } snprintf(b->lit_text, sizeof(b->lit_text), "%s", o->lit); } T->top_n = B->top_n < MAX_WS ? B->top_n : MAX_WS; for (int i = 0; i < T->top_n; i++) T->top[i] = B->top[i]; } for (int u = 0; u < ed->user_block_n; u++) { UserBlockDef* d = &ed->user_blocks[u]; int ti = -1; for (int t = 0; t < ed->tab_n; t++) if (ed->tabs[t].comp_id == u && ed->tabs[t].is_composite) { ti = t; break; } if (ti >= 0) comp_register(ed, d, &ed->tabs[ti]); } for (int i = 0; i < bp->var_n; i++) { const TbBpVar* v = &bp->vars[i]; char buf[160]; if (v->kind == TB_BP_VAL_INT) snprintf(buf, sizeof(buf), "%lld", (long long)v->num); else if (v->kind == TB_BP_VAL_REAL) snprintf(buf, sizeof(buf), "%g", v->num); else snprintf(buf, sizeof(buf), "%s", v->text); tb_variables_set_text(v->name, buf); } ed->cur_tab = (bp->cur_tab >= 0 && bp->cur_tab < ed->tab_n) ? bp->cur_tab : 0; palette_rebuild(ed); tab_select(ed, ed->cur_tab); ed->stage_buf[0] = 0; } static bool project_load(Ed* ed, const char* path) { char err[160] = ""; TbBlueprint* bp = tb_blueprint_load_file(path, err, sizeof(err)); if (!bp) { snprintf(ed->hot_status, sizeof(ed->hot_status), "Falha ao abrir: %.200s", err[0] ? err : path); ed->hot_status_ok = false; return false; } blueprint_apply(ed, bp); tb_blueprint_free(bp); snprintf(ed->hot_status, sizeof(ed->hot_status), "Projeto aberto: %.200s", path); ed->hot_status_ok = true; return true; } static bool project_save(Ed* ed, const char* path) { TbBlueprint* bp = ed_to_blueprint(ed); bool ok = bp && tb_blueprint_save_file(bp, path, TB_BP_FMT_JSON, true); tb_blueprint_free(bp); snprintf(ed->hot_status, sizeof(ed->hot_status), ok ? "Projeto salvo: %.200s" : "Falha ao salvar: %.200s", path); ed->hot_status_ok = ok; return ok; } static bool project_export(Ed* ed, const char* path, int fmt) { TbBlueprint* bp = ed_to_blueprint(ed); bool ok = bp && tb_blueprint_save_file(bp, path, fmt, true); tb_blueprint_free(bp); snprintf(ed->hot_status, sizeof(ed->hot_status), ok ? "Exportado %s: %.200s" : "Falha ao exportar %s: %.200s", tb_blueprint_format_name(fmt), path); ed->hot_status_ok = ok; return ok; } /* === * Diálogo modal "Criar um Bloco" (estilo Scratch) * === */ #define DLG_W 580 #define DLG_H 380 #define DLG_HEAD_H 50 /* Geometria do protótipo: preenche comp_dialog_geom e devolve o retângulo */ static void dlg_geom(Ed* ed, float* bx, float* by, float* bw, float* bh) { const float pad = 14.f, gap = 8.f; float x = pad; ed->comp_dialog_name_x = x; ed->comp_dialog_name_w = fmaxf(96.f, tw(ed->comp_dialog_name[0] ? ed->comp_dialog_name : "nome do bloco", FS) + 26.f); x += ed->comp_dialog_name_w + gap; for (int i = 0; i < ed->comp_dialog_part_n; i++) { UserParam* p = &ed->comp_dialog_parts[i]; const char* label = p->name[0] ? p->name : (p->kind == PARAM_LABEL ? "rótulo" : "entrada"); float w; if (p->kind == PARAM_LABEL) w = tw(label, FS) + 4.f; else w = fmaxf(p->kind == PARAM_BOOL ? 36.f : 48.f, tw(label, FS) + 24.f); ed->comp_dialog_geom[i][0] = x; ed->comp_dialog_geom[i][1] = w; x += w + gap; } float w = x - gap + pad; float dx = (WIN_W - DLG_W) * 0.5f, dy = (WIN_H - DLG_H) * 0.5f; *bw = w; *bh = 40.f; *bx = dx + (DLG_W - w) * 0.5f; *by = dy + DLG_HEAD_H + 46.f; } /* Dimensões de um card "Adicionar=" */ static void dlg_card_rect(float* w, float* h) { *w = (DLG_W - 56.f - 32.f) / 3.f; *h = 88.f; } static void dlg_open(Ed* ed, int def_idx) { ed->comp_dialog_open = true; ed->comp_dialog_def = def_idx; ed->comp_dialog_editing = false; ed->comp_dialog_edit_part = -1; ed->comp_dialog_sel = -1; ed->comp_dialog_name[0] = 0; ed->comp_dialog_part_n = 0; ed->comp_dialog_color = 0; if (def_idx >= 0 && def_idx < ed->user_block_n) { UserBlockDef* def = &ed->user_blocks[def_idx]; snprintf(ed->comp_dialog_name, sizeof(ed->comp_dialog_name), "%s", def->name); ed->comp_dialog_color = def->color_idx; ed->comp_dialog_part_n = def->part_n; memcpy(ed->comp_dialog_parts, def->parts, sizeof(UserParam) * def->part_n); } else { ed->comp_dialog_part_n = 0; } ed->comp_dialog_editing = true; ed->comp_dialog_edit_part = -1; } static char* dlg_edit_target(Ed* ed, size_t* cap) { if (ed->comp_dialog_edit_part < 0) { *cap = sizeof(ed->comp_dialog_name); return ed->comp_dialog_name; } *cap = sizeof(ed->comp_dialog_parts[0].name); return ed->comp_dialog_parts[ed->comp_dialog_edit_part].name; } static void dlg_add_part(Ed* ed, ParamKind kind) { if (ed->comp_dialog_part_n >= MAX_UBLK_PARTS) return; int i = ed->comp_dialog_part_n++; ed->comp_dialog_parts[i].kind = kind; ed->comp_dialog_parts[i].name[0] = 0; ed->comp_dialog_sel = i; ed->comp_dialog_editing = true; ed->comp_dialog_edit_part = i; } static void dlg_delete_part(Ed* ed, int i) { if (i < 0 || i >= ed->comp_dialog_part_n) return; for (int k = i; k < ed->comp_dialog_part_n - 1; k++) ed->comp_dialog_parts[k] = ed->comp_dialog_parts[k + 1]; ed->comp_dialog_part_n--; ed->comp_dialog_sel = -1; ed->comp_dialog_editing = false; ed->comp_dialog_edit_part = -1; } static void dlg_move_part(Ed* ed, int dir) { int i = ed->comp_dialog_sel, j = i + dir; if (i < 0 || j < 0 || j >= ed->comp_dialog_part_n) return; UserParam tmp = ed->comp_dialog_parts[i]; ed->comp_dialog_parts[i] = ed->comp_dialog_parts[j]; ed->comp_dialog_parts[j] = tmp; ed->comp_dialog_sel = j; if (ed->comp_dialog_edit_part == i) ed->comp_dialog_edit_part = j; else if (ed->comp_dialog_edit_part == j) ed->comp_dialog_edit_part = i; } static void dlg_ok(Ed* ed) { char nm[48]; snprintf(nm, sizeof(nm), "%s", ed->comp_dialog_name); if (!nm[0]) snprintf(nm, sizeof(nm), "meu bloco"); UserBlockDef* def; if (ed->comp_dialog_def >= 0 && ed->comp_dialog_def < ed->user_block_n) def = &ed->user_blocks[ed->comp_dialog_def]; else { if (ed->user_block_n >= MAX_USER_BLOCKS) { snprintf(ed->hot_status, sizeof(ed->hot_status), "Limite de blocos compostos atingido."); ed->hot_status_ok = false; return; } def = &ed->user_blocks[ed->user_block_n++]; memset(def, 0, sizeof(*def)); def->tab_idx = -1; } char old_name[48]; snprintf(old_name, sizeof(old_name), "%s", def->name); bool rename = old_name[0] && strcmp(old_name, nm) != 0; snprintf(def->name, sizeof(def->name), "%s", nm); def->color_idx = ed->comp_dialog_color; def->part_n = ed->comp_dialog_part_n; memcpy(def->parts, ed->comp_dialog_parts, sizeof(UserParam) * def->part_n); comp_build_input_names(def); if (rename) { if (def->reg_type) { invalidate_types(ed); tb_block_destroy(&def->reg_type->base, ed->rt); def->reg_type = NULL; } char old_type[64], new_type[64]; snprintf(old_type, sizeof(old_type), "User.%s", old_name); snprintf(new_type, sizeof(new_type), "User.%s", def->name); for (int t = 0; t < ed->tab_n; t++) for (int i = 0; i < MAX_WS; i++) { EdBlock* b = &ed->tabs[t].ws[i]; if (b->used && strcmp(b->type_name, old_type) == 0) snprintf(b->type_name, sizeof(b->type_name), "%s", new_type); } if (def->snap) snprintf(def->snap->name, sizeof(def->snap->name), "%s", def->name); } /* Aba de definição: reusa a existente, ou restaura/cria */ if (def->tab_idx >= 0 && def->tab_idx < ed->tab_n) { tab_select(ed, def->tab_idx); } else { if (!tab_new(ed, def->name, true)) return; def->tab_idx = ed->cur_tab; if (def->snap) { CT = *def->snap; clear_live(&CT); } } CT.is_composite = true; CT.color_idx = def->color_idx; comp_register(ed, def, &CT); ed->comp_dialog_open = false; ed->comp_dialog_editing = false; snprintf(ed->comp_name_buf, sizeof(ed->comp_name_buf), "%s", def->name); ed->comp_name_len = (int)strlen(ed->comp_name_buf); snprintf(ed->hot_status, sizeof(ed->hot_status), "Bloco \"%s\" salvo em Meus Blocos", def->name); ed->hot_status_ok = true; } static 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)); float dx = (WIN_W - DLG_W) * 0.5f, dy = (WIN_H - DLG_H) * 0.5f; Col accent = s_user_colors[ed->comp_dialog_color]; Col dark = col_mul(accent, 0.78f); rb_fill_rrect(rb, dx + 3, dy + 4, DLG_W, DLG_H, 12, COLA(0, 0, 0, 70)); rb_fill_rrect(rb, dx, dy, DLG_W, DLG_H, 12, COL_PANEL); /* Cabeçalho */ rb_fill_rrect(rb, dx, dy, DLG_W, DLG_HEAD_H, 12, accent); rb_fill_rect(rb, dx, dy + DLG_HEAD_H - 12, DLG_W, 12, accent); const char* title = ed->comp_dialog_def >= 0 ? "Editar Bloco" : "Criar um Bloco"; rb_text_c(rb, dx + (DLG_W - tw(title, 18)) * 0.5f, dy + DLG_HEAD_H * 0.5f, title, COL_WHITE, 18); rb_fill_circle(rb, dx + DLG_W - 26, dy + DLG_HEAD_H * 0.5f, 12, COLA(255, 255, 255, 60)); rb_text_c(rb, dx + DLG_W - 30, dy + DLG_HEAD_H * 0.5f, "=", COL_WHITE, 18); /* Protótipo do bloco */ float bx, by, bw, bh; dlg_geom(ed, &bx, &by, &bw, &bh); rb_fill_rrect(rb, bx, by, bw, bh, 4, dark); rb_fill_rrect(rb, bx + 1, by + 1, bw - 2, bh - 2, 3, accent); draw_bump(rb, bx, by + bh, accent, dark); /* Campo do nome do bloco */ { float nfx = bx + ed->comp_dialog_name_x, nfy = by + 7, nfw = ed->comp_dialog_name_w, nfh = bh - 14; rb_fill_rrect(rb, nfx, nfy, nfw, nfh, nfh * 0.5f, COLA(0, 0, 0, 40)); rb_fill_rrect(rb, nfx + 1, nfy + 1, nfw - 2, nfh - 2, nfh * 0.5f - 1, COL_WHITE); const char* nm = ed->comp_dialog_name[0] ? ed->comp_dialog_name : "nome do bloco"; float lw = tw(nm, FS); rb_text_c(rb, nfx + (nfw - lw) * 0.5f, nfy + nfh * 0.5f, nm, ed->comp_dialog_name[0] ? COL_TEXT : COL_TEXT_DIM, FS); if (ed->comp_dialog_editing && ed->comp_dialog_edit_part < 0) rb_fill_rect(rb, nfx + (nfw + lw) * 0.5f + 2, nfy + 4, 1.5f, nfh - 8, COL_TEXT); } /* Partes do protótipo */ for (int i = 0; i < ed->comp_dialog_part_n; i++) { UserParam* p = &ed->comp_dialog_parts[i]; const char* label = p->name[0] ? p->name : (p->kind == PARAM_LABEL ? "rótulo" : "entrada"); float px = bx + ed->comp_dialog_geom[i][0], pw = ed->comp_dialog_geom[i][1]; float py = by + 7, ph = bh - 14; bool sel = ed->comp_dialog_sel == i; if (p->kind == PARAM_LABEL) { rb_text_c(rb, px, by + bh * 0.5f, label, p->name[0] ? COL_WHITE : COLA(255, 255, 255, 150), FS); } else if (p->kind == PARAM_BOOL) { draw_hex(rb, px, py, pw, ph, sel ? COL_WHITE : COLA(0, 0, 0, 40)); rb_text_c(rb, px + (pw - tw(label, FS)) * 0.5f, py + ph * 0.5f, label, p->name[0] ? COL_TEXT : COL_TEXT_DIM, FS); } else { rb_fill_rrect(rb, px, py, pw, ph, ph * 0.5f, sel ? COL_MENU : COLA(0, 0, 0, 40)); rb_fill_rrect(rb, px + 1, py + 1, pw - 2, ph - 2, ph * 0.5f - 1, COL_WHITE); rb_text_c(rb, px + (pw - tw(label, FS)) * 0.5f, py + ph * 0.5f, label, p->name[0] ? COL_TEXT : COL_TEXT_DIM, FS); } if (sel) rb_stroke_rect(rb, px - 2, py - 2, pw + 4, ph + 4, 2, COL_TEXT); if (ed->comp_dialog_editing && ed->comp_dialog_edit_part == i && p->kind != PARAM_LABEL) { float lw = tw(label, FS); rb_fill_rect(rb, px + (pw + lw) * 0.5f + 2, py + 5, 1.5f, ph - 10, COL_TEXT); } } /* Controles - apagar - da parte selecionada */ if (ed->comp_dialog_sel >= 0) { float ctr = bx + bw * 0.5f, cty = by - 26; rb_text_c(rb, ctr - 44, cty, "=", COL_TEXT, 22); rb_text_c(rb, ctr + 40, cty, "=", COL_TEXT, 22); rb_fill_rect(rb, ctr - 7, cty - 8, 14, 3, COL_TEXT); rb_fill_rect(rb, ctr - 4, cty - 12, 8, 4, COL_TEXT); rb_fill_rect(rb, ctr - 6, cty - 4, 12, 12, COL_TEXT); } /* Cards de adicionar */ float cw, ch; dlg_card_rect(&cw, &ch); float cx0 = dx + 28.f; float cy0 = by + bh + 34.f; const char* lines[3][3] = { {"Adicionar uma", "entrada", "numérica ou texto"}, {"Adicionar uma", "entrada", "booleana"}, {"Adicionar um", "rótulo", ""}, }; for (int i = 0; i < 3; i++) { float cx = cx0 + i * (cw + 16.f); bool hover = in_rect(ed->mouse_x, ed->mouse_y, cx, cy0, cw, ch); rb_fill_rrect(rb, cx, cy0, cw, ch, 8, hover ? COL_HOVER : COL_PANEL); rb_stroke_rect(rb, cx + 0.5f, cy0 + 0.5f, cw - 1, ch - 1, 1, hover ? COL_MENU : COL_BORDER); float iy = cy0 + 16.f; if (i == 0) { rb_fill_rrect(rb, cx + cw * 0.5f - 22, iy, 44, 22, 11, accent); rb_text_c(rb, cx + cw * 0.5f - 14, iy + 11, "= = =", COL_WHITE, FS); } else if (i == 1) { draw_hex(rb, cx + cw * 0.5f - 20, iy, 40, 22, accent); } else { rb_fill_rrect(rb, cx + cw * 0.5f - 22, iy, 44, 22, 4, accent); rb_text_c(rb, cx + cw * 0.5f - 11, iy + 11, "text", COL_WHITE, FS); } float ty = cy0 + 46.f; for (int l = 0; l < 3 && lines[i][l][0]; l++) { rb_text_c(rb, cx + (cw - tw(lines[i][l], FS)) * 0.5f, ty, lines[i][l], COL_TEXT, FS); ty += 16.f; } } /* Cores + Cancelar/OK */ float fy = dy + DLG_H - 40.f; for (int ci = 0; ci < USER_COLOR_COUNT; ci++) { float sx = dx + 28.f + ci * 30.f; if (ed->comp_dialog_color == ci) rb_fill_rrect(rb, sx - 2, fy - 2, 26, 26, 6, COL_TEXT); rb_fill_rrect(rb, sx, fy, 22, 22, 5, s_user_colors[ci]); } float okx = dx + DLG_W - 28.f - 84.f, cax = okx - 96.f; rb_fill_rrect(rb, cax, fy - 8, 84, 36, 8, COL_BORDER); rb_text_c(rb, cax + (84 - tw("Cancelar", FS_UI)) * 0.5f, fy + 10, "Cancelar", COL_TEXT, FS_UI); rb_fill_rrect(rb, okx, fy - 8, 84, 36, 8, accent); 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) { 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; } if (in_rect(mx, my, dx + DLG_W - 44, dy, 44, DLG_HEAD_H)) { ed->comp_dialog_open = false; return true; } float bx, by, bw, bh; dlg_geom(ed, &bx, &by, &bw, &bh); if (in_rect(mx, my, bx + ed->comp_dialog_name_x, by + 7, ed->comp_dialog_name_w, bh - 14)) { ed->comp_dialog_editing = true; ed->comp_dialog_edit_part = -1; ed->comp_dialog_sel = -1; return true; } for (int i = 0; i < ed->comp_dialog_part_n; i++) { if (in_rect(mx, my, bx + ed->comp_dialog_geom[i][0], by + 7, ed->comp_dialog_geom[i][1], bh - 14)) { ed->comp_dialog_sel = i; ed->comp_dialog_editing = true; ed->comp_dialog_edit_part = i; return true; } } if (ed->comp_dialog_sel >= 0) { float ctr = bx + bw * 0.5f, cty = by - 26; if (in_rect(mx, my, ctr - 60, cty - 16, 34, 32)) { dlg_move_part(ed, -1); return true; } if (in_rect(mx, my, ctr - 16, cty - 16, 32, 32)) { dlg_delete_part(ed, ed->comp_dialog_sel); return true; } if (in_rect(mx, my, ctr + 26, cty - 16, 34, 32)) { dlg_move_part(ed, 1); return true; } } float cw, ch; dlg_card_rect(&cw, &ch); float cx0 = dx + 28.f, cy0 = by + bh + 34.f; for (int i = 0; i < 3; i++) { float cx = cx0 + i * (cw + 16.f); if (in_rect(mx, my, cx, cy0, cw, ch)) { dlg_add_part(ed, i == 0 ? PARAM_NUM : i == 1 ? PARAM_BOOL : PARAM_LABEL); return true; } } float fy = dy + DLG_H - 40.f; for (int ci = 0; ci < USER_COLOR_COUNT; ci++) if (in_rect(mx, my, dx + 28.f + ci * 30.f, fy, 22, 22)) { ed->comp_dialog_color = ci; return true; } float okx = dx + DLG_W - 28.f - 84.f, cax = okx - 96.f; if (in_rect(mx, my, okx, fy - 8, 84, 36)) { dlg_ok(ed); return true; } if (in_rect(mx, my, cax, fy - 8, 84, 36)) { ed->comp_dialog_open = false; return true; } ed->comp_dialog_editing = false; ed->comp_dialog_edit_part = -1; return true; } static 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) { size_t cap; char* t = dlg_edit_target(ed, &cap); (void)cap; utf8_pop(t); } } static 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); } /* === * Hot reload de libraries .so * === */ static bool hotlib_load(Ed* ed, const char* path) { int idx = tb_api_load(path); if (idx < 0) { snprintf(ed->hot_status, sizeof(ed->hot_status), "%s", tb_api_last_error()); ed->hot_status_ok = false; return false; } retype_all(ed); /* blocos que estavam sem tipo podem ganhar um agora */ snprintf(ed->hot_status, sizeof(ed->hot_status), "Carregado: %s", path); ed->hot_status_ok = true; return true; } /* Hot reload: recarrega os .so cujo mtime mudou (delegado a tinyblocks-api). */ static void hotlib_check(Ed* ed) { if (++ed->hot_check_frame < 60) return; ed->hot_check_frame = 0; if (!tb_api_any_changed()) return; invalidate_types(ed); /* nenhum ponteiro de tipo pode sobreviver ao unload */ tb_api_poll_reload(); retype_all(ed); snprintf(ed->hot_status, sizeof(ed->hot_status), "Hot reload: libraries recarregadas"); ed->hot_status_ok = true; } /* === * Renderização da interface * === */ static bool hit_open_btn(float mx, float my); static bool hit_save_btn(float mx, float my); static bool hit_export_btn(float mx, float my); static bool hit_libman_btn(float mx, float my); static bool hit_settings_btn(Ed* ed, float mx, float my); static void menu_button(TinyBlocks_RenderableBlock* rb, float x, float w, const char* label, bool active) { rb_fill_rrect(rb, x, 7, w, MENU_H - 14, 6, active ? COL_MENU_DARK : COLA(255, 255, 255, 34)); rb_text_c(rb, x + (w - tw(label, FS_UI)) * 0.5f, MENU_H * 0.5f, label, COL_WHITE, FS_UI); } static void render_menu(Ed* ed, TinyBlocks_RenderableBlock* rb) { rb_fill_rect(rb, 0, 0, WIN_W, MENU_H, COL_MENU); rb_text_c(rb, 18, MENU_H*0.5f, "TinyBlocks", COL_WHITE, 20); float mx = ed->mouse_x, my = ed->mouse_y; bool active = ed->path_input_active; menu_button(rb, OPEN_BTN_X, OPEN_BTN_W, "Abrir", (active && ed->path_mode == PM_LOAD) || hit_open_btn(mx, my)); menu_button(rb, SAVE_BTN_X, SAVE_BTN_W, "Salvar", (active && ed->path_mode == PM_SAVE) || hit_save_btn(mx, my)); menu_button(rb, EXP_BTN_X, EXP_BTN_W, "Exportar", (ed->ctx_menu_open && ed->ctx_export) || hit_export_btn(mx, my)); menu_button(rb, LIBM_BTN_X, LIBM_BTN_W, "Bibliotecas", ed->libman_open || hit_libman_btn(mx, my)); menu_button(rb, CFG_BTN_X, CFG_BTN_W, "Config", ed->settings_open || hit_settings_btn(ed, mx, my)); if (ed->lib_hover || (active && ed->path_mode == PM_LIB)) rb_fill_rect(rb, LIB_BTN_X, 0, LIB_BTN_W, MENU_H, COL_MENU_DARK); rb_text_c(rb, LIB_BTN_X + 14, MENU_H*0.5f, "Carregar library=", COL_WHITE, FS_UI); if (ed->path_input_active) { float bx = LIB_BTN_X + LIB_BTN_W + 10, bw = WIN_W - bx - 16; rb_fill_rrect(rb, bx, 7, bw, MENU_H-14, 6, COL_WHITE); const char* prompt = ed->path_mode == PM_LOAD ? "caminho do projeto .json (Enter abre, Esc cancela)" : ed->path_mode == PM_SAVE ? "caminho para salvar o projeto .json" : ed->path_mode == PM_EXP_JSON ? "caminho para exportar .json" : ed->path_mode == PM_EXP_XML ? "caminho para exportar .xml" : ed->path_mode == PM_EXP_CSV ? "caminho para exportar .csv" : "caminho do .so (Enter carrega, Esc cancela)"; const char* t = ed->path_input_buf[0] ? ed->path_input_buf : prompt; rb_text_c(rb, bx + 10, MENU_H*0.5f, t, ed->path_input_buf[0] ? COL_TEXT : COL_TEXT_DIM, FS_UI); float cw = tw(ed->path_input_buf, FS_UI); rb_fill_rect(rb, bx + 11 + cw, MENU_H*0.5f - 8, 1.5f, 16, COL_TEXT); } else if (ed->hot_status[0]) { float w = tw(ed->hot_status, FS_SM); rb_text_c(rb, CFG_BTN_X - 12 - w, MENU_H*0.5f, ed->hot_status, ed->hot_status_ok ? COL_WHITE : COL_ERR_MENU, FS_SM); } } static void render_tab_bar(Ed* ed, TinyBlocks_RenderableBlock* rb) { float y0 = MENU_H, wbar = WIN_W - STAGE_W; rb_fill_rect(rb, 0, y0, wbar, TAB_H, COL_UI_BG); for (int i = 0; i < ed->tab_n; i++) { float tx = 8 + i*TAB_W; if (tx + TAB_W > wbar - PLUS_W) break; bool cur = i == ed->cur_tab; Col bg = cur ? COL_PANEL : COL_TAB_OFF; rb_fill_rrect(rb, tx, y0+6, TAB_W-4, TAB_H-6, 8, bg); rb_fill_rect(rb, tx, y0+TAB_H-8, TAB_W-4, 8, bg); float cy = y0 + 6 + (TAB_H-6)*0.5f, lx = tx + 12; if (ed->tabs[i].is_composite) { rb_fill_circle(rb, tx+14, cy, 5, s_user_colors[ed->tabs[i].color_idx]); lx = tx + 24; } rb_text_c(rb, lx, cy, ed->tabs[i].name, cur ? COL_MENU : COL_TEXT, FS_UI); if (ed->tab_n > 1) rb_text_c(rb, tx+TAB_W-22, cy, "=", COL_TEXT_DIM, FS_UI); } float px = 8 + ed->tab_n*TAB_W; if (px + PLUS_W <= wbar && ed->tab_n < MAX_TABS) rb_text_c(rb, px+8, y0 + 6 + (TAB_H-6)*0.5f, "+", COL_TEXT, 18); } static void render_categories(Ed* ed, TinyBlocks_RenderableBlock* rb) { rb_fill_rect(rb, 0, PAL_Y, CAT_W, WIN_H-PAL_Y, COL_PANEL); rb_line(rb, CAT_W-1, PAL_Y, CAT_W-1, WIN_H, 1.f, COL_BORDER); float ih = cat_item_h(ed); int cur = current_cat(ed); for (int c = 0; c < ed->cat_n; c++) { float iy = PAL_Y + c*ih; if (c == cur) rb_fill_rect(rb, 0, iy, CAT_W-1, ih, COL_UI_BG); float cy = iy + ih*0.36f; rb_fill_circle(rb, CAT_W*0.5f, cy, 10, ed->cats[c].dark); rb_fill_circle(rb, CAT_W*0.5f, cy, 9, ed->cats[c].col); float w = tw(ed->cats[c].name, 10); rb_text_c(rb, CAT_W*0.5f - w*0.5f, iy + ih*0.76f, ed->cats[c].name, COL_TEXT, 10); } /* Botao de buscar/adicionar library, no fim do painel (como o Scratch) */ float by = WIN_H - LIBMAN_BTN_H; bool hov = (ed->mouse_x < CAT_W && ed->mouse_y >= by && ed->mouse_y < WIN_H); rb_fill_rect(rb, 0, by, CAT_W-1, LIBMAN_BTN_H, hov ? COL_LIBBTN_DARK : COL_LIBBTN); float cx = CAT_W*0.5f, cy = by + LIBMAN_BTN_H*0.5f; for (int i = 0; i < 3; i++) /* livrinhos */ rb_fill_rect(rb, cx-14, cy-6 + i*5, 16, 3, COL_WHITE); rb_fill_rect(rb, cx+5, cy-6, 12, 3, COL_WHITE); /* "+" no canto */ rb_fill_rect(rb, cx+9.5f, cy-10, 3, 11, COL_WHITE); } static void render_flyout(Ed* ed, TinyBlocks_RenderableBlock* rb) { rb_fill_rect(rb, CAT_W, PAL_Y, FLY_W, WIN_H-PAL_Y, COL_FLY); rb_line(rb, PALETTE_W-1, PAL_Y, PALETTE_W-1, WIN_H, 1.f, COL_BORDER); clip_set(ed, rb, CAT_W, PAL_Y, FLY_W-1, WIN_H-PAL_Y); float oy = PAL_Y - ed->fly_scroll; for (int i = 0; i < ed->fly_n; i++) { FlyItem* it = &ed->fly_items[i]; float iy = it->y + oy; if (iy + it->h < PAL_Y || iy > WIN_H) continue; switch (it->kind) { case FI_HEADER: rb_text_c(rb, CAT_W + FLY_PAD, iy + it->h*0.55f, ed->cats[it->cat].name, COL_TEXT, 14); break; case FI_BUTTON: rb_fill_rrect(rb, CAT_W + FLY_PAD, iy+4, FLY_BTN_W, 30, 6, COL_BORDER); rb_fill_rrect(rb, CAT_W + FLY_PAD + 1, iy+5, FLY_BTN_W-2, 28, 5, COL_PANEL); rb_text_c(rb, CAT_W + FLY_PAD + (FLY_BTN_W - tw("Criar um Bloco", FS_UI))*0.5f, iy + 19, "Criar um Bloco", COL_TEXT, FS_UI); break; case FI_BLOCK: render_block(ed, rb, &ed->fly, it->bi, CAT_W, oy); break; } } clip_clear(ed, rb); } static void render_snap(Ed* ed, TinyBlocks_RenderableBlock* rb, float ox, float oy) { if (ed->state != ES_DRAG || ed->snap_kind == SN_NONE) return; Tab* T = &CT; EdBlock* d = &T->ws[ed->drag_bi]; EdBlock* t = &T->ws[ed->snap_bi]; if (ed->snap_kind == SN_ARG) { int s = ed->snap_idx; float sx = t->ax + ox + t->slot_x[s], sy = t->ay + oy + t->slot_y[s]; rb_stroke_rect(rb, sx-3, sy-3, t->slot_w[s]+6, t->slot_h[s]+6, 1.f, COLA(0,0,0,70)); rb_stroke_rect(rb, sx-2, sy-2, t->slot_w[s]+4, t->slot_h[s]+4, 2.f, COL_WHITE); return; } float gh = chain_h(T, ed->drag_bi), gx = t->ax, gy; if (ed->snap_kind == SN_NEXT) gy = t->ay + t->h; else if (ed->snap_kind == SN_SUB) { gx = t->ax + ARM_W; gy = t->ay + t->sub_y[ed->snap_idx]; } else gy = t->ay - gh; rb_fill_rrect(rb, gx + ox, gy + oy, d->w, gh, 4, COLA(0,0,0,45)); } static void render_workspace(Ed* ed, TinyBlocks_RenderableBlock* rb) { float ox = WS_X - CT.ws_sx, oy = WS_Y - CT.ws_sy; rb_fill_rect(rb, WS_X, WS_Y, WS_W, WS_H, COL_WS_BG); clip_set(ed, rb, WS_X, WS_Y, WS_W, WS_H); const float g = 40.f; float offx = fmodf(CT.ws_sx, g); if (offx < 0) offx += g; float offy = fmodf(CT.ws_sy, g); if (offy < 0) offy += g; for (float gx = WS_X - offx; gx < WS_X + WS_W; gx += g) for (float gy = WS_Y - offy; gy < WS_Y + WS_H; gy += g) rb_fill_rect(rb, gx, gy, 2, 2, COL_GRID); if (CT.top_n == 0) { const char* hint = CT.is_composite ? "Arraste \"parâmetro\" e \"devolva\" de Meus Blocos para montar o bloco" : "Arraste blocos da paleta para cá"; rb_text_c(rb, WS_X + (WS_W - tw(hint, FS_UI))*0.5f, WS_Y + WS_H*0.45f, hint, COL_TEXT_DIM, FS_UI); } for (int i = 0; i < CT.top_n; i++) { if (ed->state == ES_DRAG && CT.top[i] == ed->drag_bi) continue; render_chain(ed, rb, &CT, CT.top[i], ox, oy); } render_snap(ed, rb, ox, oy); if (ed->bubble_bi >= 0 && CT.ws[ed->bubble_bi].used) { EdBlock* b = &CT.ws[ed->bubble_bi]; if (ed->bubble_img) { /* Balão com prévia da imagem (escalada, mantendo proporção) */ const float BW = 184, BH = 160, PAD = 10; float bx = b->ax + ox + 8, by = b->ay + oy - (BH + 6); rb_fill_rrect(rb, bx, by, BW, BH, 10, COL_BORDER); rb_fill_rrect(rb, bx+1, by+1, BW-2, BH-2, 9, COL_WHITE); rb_fill_rect(rb, bx + 16, by + BH - 2, 10, 5, COL_WHITE); int iw = tb_image_width(ed->bubble_img); int ih = tb_image_height(ed->bubble_img); if (iw > 0 && ih > 0) { float aw = BW - 2*PAD, ah = BH - 2*PAD - 12; float sc = aw/iw < ah/ih ? aw/iw : ah/ih; float dw = iw*sc, dh = ih*sc; tb_draw_image(rb, bx + (BW-dw)*0.5f, by + (BH-12-dh)*0.5f, dw, dh, ed->bubble_img); } rb_text_c(rb, bx + 10, by + BH - 4, ed->bubble_text, COL_TEXT_DIM, 11.f); } else if (ed->bubble_json) { /* Balão com prévia gráfica de uma lista de pontos (curva) */ const float BW = 180, BH = 140, PAD = 16; float bx = b->ax + ox + 8, by = b->ay + oy - (BH + 6); rb_fill_rrect(rb, bx, by, BW, BH, 10, COL_BORDER); rb_fill_rrect(rb, bx+1, by+1, BW-2, BH-2, 9, COL_WHITE); rb_fill_rect(rb, bx + 16, by + BH - 2, 10, 5, COL_WHITE); int n = (int)tb_json_array_length(ed->bubble_json); double minx = 1e30, maxx = -1e30, miny = 1e30, maxy = -1e30; for (int i = 0; i < n; i++) { double px, py; if (!json_point_at(ed->bubble_json, i, &px, &py)) continue; if (px < minx) minx = px; if (px > maxx) maxx = px; if (py < miny) miny = py; if (py > maxy) maxy = py; } double spanx = maxx - minx, spany = maxy - miny; if (spanx < 1e-9) { spanx = 1; minx -= 0.5; } if (spany < 1e-9) { spany = 1; miny -= 0.5; } float aw = BW - 2*PAD, ah = BH - 2*PAD - 12; float sc = (float)((aw/spanx < ah/spany) ? aw/spanx : ah/spany); float gx = bx + PAD + (aw - (float)spanx*sc)*0.5f; float gy = by + PAD + (ah - (float)spany*sc)*0.5f; Col cc = COLA(233, 30, 99, 255); float lx = 0, ly = 0, fx = 0, fy = 0, ex = 0, ey = 0; for (int i = 0; i < n; i++) { double px, py; if (!json_point_at(ed->bubble_json, i, &px, &py)) continue; float sx = gx + (float)(px - minx)*sc; float sy = gy + (float)(maxy - py)*sc; /* y para baixo */ if (i > 0) rb_line(rb, lx, ly, sx, sy, 1.6f, cc); lx = sx; ly = sy; if (i == 0) { fx = sx; fy = sy; } ex = sx; ey = sy; } rb_fill_circle(rb, fx, fy, 3.2f, COLA(76,175,80,255)); /* início */ rb_fill_circle(rb, ex, ey, 3.2f, COLA(229,57,53,255)); /* fim */ rb_text_c(rb, bx + 10, by + BH - 4, ed->bubble_text, COL_TEXT_DIM, 11.f); } else { float w = tw(ed->bubble_text, FS) + 20; float bx = b->ax + ox + 8, by = b->ay + oy - 32; rb_fill_rrect(rb, bx, by, w, 26, 8, COL_BORDER); rb_fill_rrect(rb, bx+1, by+1, w-2, 24, 7, COL_WHITE); rb_fill_rect(rb, bx + 12, by + 25, 8, 4, COL_WHITE); rb_text_c(rb, bx + 10, by + 13, ed->bubble_text, COL_TEXT, FS); } } clip_clear(ed, rb); } /* == Barra do bloco composto (canto superior direito do workspace) === */ #define CP_W 440 #define CP_H 44 static void comp_panel_pos(Ed* ed, float* px, float* py) { *px = WS_X + WS_W - CP_W - 10; *py = WS_Y + 10; } static void render_comp_panel(Ed* ed, TinyBlocks_RenderableBlock* rb) { if (!CT.is_composite) return; float px, py; comp_panel_pos(ed, &px, &py); rb_fill_rrect(rb, px, py, CP_W, CP_H, 8, COL_BORDER); rb_fill_rrect(rb, px+1, py+1, CP_W-2, CP_H-2, 7, COL_PANEL); Col c = s_user_colors[CT.color_idx]; rb_fill_rrect(rb, px+10, py+10, 24, 24, 6, col_mul(c, 0.8f)); rb_fill_rrect(rb, px+11, py+11, 22, 22, 5, c); const char* nm = ed->comp_name_buf[0] ? ed->comp_name_buf : "Novo bloco"; rb_text_c(rb, px+44, py+CP_H*0.5f, nm, COL_TEXT, FS_UI); float bx = px + CP_W - 10; bx -= 78; rb_fill_rrect(rb, bx, py+8, 78, 28, 6, c); rb_text_c(rb, bx + (78 - tw("Salvar", FS_UI))*0.5f, py+CP_H*0.5f, "Salvar", COL_WHITE, FS_UI); bx -= 96; rb_fill_rrect(rb, bx, py+8, 88, 28, 6, COL_BORDER); rb_text_c(rb, bx + (88 - tw("Editar bloco", FS_UI))*0.5f, py+CP_H*0.5f, "Editar bloco", COL_TEXT, FS_UI); } /* Altura da área do palco no painel (4:3 embutido; faixa curta se destacado) */ static float stage_panel_h(Ed* ed) { if (!ed->stage) return 0.f; return ed->stage_win ? 40.f : (STAGE_W - 16) * 0.75f; } static void render_stage(Ed* ed, TinyBlocks_RenderableBlock* rb) { float sx = WIN_W - STAGE_W, sy = MENU_H; rb_fill_rect(rb, sx, sy, STAGE_W, WIN_H - sy, COL_UI_BG); /* Bandeira verde */ float fx = sx + 10, fy = sy + 6; if (ed->flag_hover) rb_fill_rrect(rb, fx, fy, 40, 32, 6, COL_HOVER); rb_fill_rect(rb, fx+13, fy+6, 2, 21, COL_FLAG_DARK); rb_fill_rrect(rb, fx+15, fy+6, 15, 11, 2, COL_FLAG); /* Parar */ float tx = sx + 56; if (ed->stop_hover) rb_fill_rrect(rb, tx, fy, 40, 32, 6, COL_HOVER); draw_hex(rb, tx+10, fy+6, 20, 20, COL_STOP_DARK); rb_fill_circle(rb, tx+20, fy+16, 9, COL_STOP); rb_text_c(rb, sx + 110, sy + STAGE_BAR_H*0.5f, "Palco", COL_TEXT_DIM, FS_UI); /* Destacar / recolher o palco */ if (ed->stage) { float dx = sx + STAGE_W - 50; if (ed->detach_hover) rb_fill_rrect(rb, dx, fy, 40, 32, 6, COL_HOVER); if (ed->stage_win) { rb_stroke_rect(rb, dx+9, fy+7, 22, 18, 1.5f, COL_TEXT); rb_fill_rect(rb, dx+12, fy+15, 10, 7, COL_TEXT); } else { rb_stroke_rect(rb, dx+9, fy+11, 15, 13, 1.5f, COL_TEXT); rb_stroke_rect(rb, dx+16, fy+6, 15, 13, 1.5f, COL_TEXT); } } float bx = sx + 8, by = sy + STAGE_BAR_H, bw = STAGE_W - 16; float ph = stage_panel_h(ed); if (ph > 0) { rb_fill_rrect(rb, bx, by, bw, ph, 8, COL_BORDER); if (ed->stage_win) { rb_fill_rrect(rb, bx+1, by+1, bw-2, ph-2, 7, COL_PANEL); const char* msg = "Palco aberto em outra janela"; rb_text_c(rb, bx + (bw - tw(msg, FS_UI))*0.5f, by + ph*0.5f, msg, COL_TEXT_DIM, FS_UI); } else { TinyBlocks_RenderableBlock* sub = NULL; tb_stage_set_view(bw-2, ph-2); clip_set(ed, rb, bx+1, by+1, bw-2, ph-2); if (ed->stage->type->on_draw(ed->stage, ed->rt, &sub) && sub) { tb_draw_merge_offset(rb, sub, bx+1, by+1); tb_renderable_release(sub); } clip_clear(ed, rb); } by += ph + 8; } float bh = WIN_H - by - 8; rb_fill_rrect(rb, bx, by, bw, bh, 8, COL_BORDER); rb_fill_rrect(rb, bx+1, by+1, bw-2, bh-2, 7, COL_PANEL); clip_set(ed, rb, bx+2, by+2, bw-4, bh-4); /* Monitores de variáveis */ float y = by + 10; for (int v = 0; v < tb_variables_count() && y < by + bh*0.5f; v++) { const char* vname = tb_variables_name(v); const TinyBlocks_Value* vv = tb_variables_value(v); char val[64]; if (vv) value_to_str(vv, val, sizeof(val)); else val[0] = 0; float nw = tw(vname, FS), vw = fmaxf(30, tw(val, FS) + 14); float mw = nw + vw + 26; rb_fill_rrect(rb, bx+10, y, mw, 26, 5, COL_MON_BORDER); rb_fill_rrect(rb, bx+11, y+1, mw-2, 24, 4, COL_MON_BG); rb_text_c(rb, bx+18, y+13, vname, COL_TEXT, FS); rb_fill_rrect(rb, bx+18+nw+6, y+4, vw, 18, 4, COL_VAR); rb_text_c(rb, bx+18+nw+6 + (vw - tw(val, FS))*0.5f, y+13, val, COL_WHITE, FS); y += 32; } /* Console: mostra as últimas linhas que cabem */ const float lh = FS_SM + 5; int total = text_lines(ed->stage_buf); int fit = (int)((by + bh - 8 - y) / lh); int skip = total > fit ? total - fit : 0; const char* p = ed->stage_buf; for (int l = 0; *p; l++) { size_t n = strcspn(p, "\n"); if (l >= skip) { char line[128]; size_t m = n < sizeof(line) - 1 ? n : sizeof(line) - 1; memcpy(line, p, m); line[m] = 0; bool err = strncmp(line, "[ERRO]", 6) == 0 || strncmp(line, "[AVISO]", 7) == 0; rb_text_c(rb, bx + 12, y + lh*0.5f, line, err ? COL_ERR_TEXT : COL_TEXT, FS_SM); y += lh; } p += n; if (*p == '\n') p++; } clip_clear(ed, rb); } #define CTX_ITEM_H 30 #define CTX_W 190 static const char* ctx_label(int id) { switch (id) { case CM_DUPLICATE: return "Duplicar"; case CM_DELETE: return "Apagar bloco"; case CM_EDIT_DEF: return "Editar definição"; case CM_CLEANUP: return "Organizar blocos"; case CM_NEW_COMPOSITE: return "Criar um bloco"; case CM_EXP_JSON: return "Exportar JSON"; case CM_EXP_XML: return "Exportar XML"; case CM_EXP_CSV: return "Exportar CSV"; default: return ""; } } static void ctx_pos(Ed* ed, float* x, float* y) { float mh = ed->ctx_n*CTX_ITEM_H + 8; *x = ed->ctx_menu_x; *y = ed->ctx_menu_y; if (*x + CTX_W > WIN_W) *x = WIN_W - CTX_W; if (*y + mh > WIN_H) *y = WIN_H - mh; } static int ctx_hit(Ed* ed, float mx, float my) { float x, y; ctx_pos(ed, &x, &y); if (!in_rect(mx, my, x, y+4, CTX_W, ed->ctx_n*CTX_ITEM_H)) return -1; return (int)((my - y - 4) / CTX_ITEM_H); } static void render_ctx_menu(Ed* ed, TinyBlocks_RenderableBlock* rb) { if (!ed->ctx_menu_open) return; float x, y; ctx_pos(ed, &x, &y); float mh = ed->ctx_n*CTX_ITEM_H + 8; rb_fill_rrect(rb, x+2, y+3, CTX_W, mh, 6, COLA(0,0,0,40)); rb_fill_rrect(rb, x, y, CTX_W, mh, 6, COL_BORDER); rb_fill_rrect(rb, x+1, y+1, CTX_W-2, mh-2, 5, COL_PANEL); for (int i = 0; i < ed->ctx_n; i++) { float iy = y + 4 + i*CTX_ITEM_H; if (ed->ctx_menu_hover == i) rb_fill_rect(rb, x+1, iy, CTX_W-2, CTX_ITEM_H, COL_UI_BG); rb_text_c(rb, x+14, iy + CTX_ITEM_H*0.5f, ctx_label(ed->ctx_items[i]), COL_TEXT, FS_UI); } } /* === * Gestor de libraries (tinyblocks-libman) - UI do editor * === */ #define LM_HEAD_H 64 #define LM_MARGIN 40 #define LM_CARD_H 190 #define LM_CARD_GAP 24 #define LM_CHIP_H 34 #define LM_CHIP_GAP 10 #define LM_SEARCH_W 340 #define LM_CARD_W ((WIN_W - 2*LM_MARGIN - LM_CARD_GAP) / 2) #define LM_MAX_CHIPS (MAX_CATS + 1) static void libman_close(Ed* ed) { ed->libman_open = false; ed->libman_search_focus = false; } static 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) { ed->libman_open = true; ed->libman_query[0] = 0; ed->libman_query_len = 0; ed->libman_search_focus = true; ed->libman_filter = -1; ed->libman_scroll = 0; ed->libman_hover = -1; ed->libman_cat_n = tb_libman_categories(ed->libman_cats, MAX_CATS); ed->path_input_active = false; ed->ctx_menu_open = false; } static const char* libman_filter_name(Ed* ed) { return (ed->libman_filter >= 0 && ed->libman_filter < ed->libman_cat_n) ? ed->libman_cats[ed->libman_filter] : "Tudo"; } static int libman_chip_labels(Ed* ed, const char** out) { out[0] = "Tudo"; int n = 1; for (int i = 0; i < ed->libman_cat_n && n < LM_MAX_CHIPS; i++) out[n++] = ed->libman_cats[i]; return n; } /* Posiciona as chips (layout que quebra linha). Retorna a altura total * (relativa ao topo, a partir de LM_HEAD_H). */ static float libman_chip_layout(Ed* ed, float rects[][4]) { const char* labels[LM_MAX_CHIPS]; int n = libman_chip_labels(ed, labels); float x0 = LM_MARGIN + LM_SEARCH_W + 24; float x = x0, y = LM_HEAD_H + 14, rowmax = y; for (int i = 0; i < n; i++) { float w = tw(labels[i], FS_UI) + 28; if (x + w > WIN_W - LM_MARGIN) { x = x0; y += LM_CHIP_H + LM_CHIP_GAP; } if (rects) { rects[i][0] = x; rects[i][1] = y; rects[i][2] = w; rects[i][3] = LM_CHIP_H; } x += w + LM_CHIP_GAP; rowmax = y; } return rowmax + LM_CHIP_H + 14 - LM_HEAD_H; } static float libman_grid_y(Ed* ed) { return LM_HEAD_H + libman_chip_layout(ed, NULL) + 8; } static void libman_render(Ed* ed, TinyBlocks_RenderableBlock* rb) { if (!ed->libman_open) return; int hits[TBLM_MAX_ENTRIES]; int nh = tb_libman_search(ed->libman_query, libman_filter_name(ed), hits, TBLM_MAX_ENTRIES); float gridY = libman_grid_y(ed); /* Fundo */ rb_fill_rect(rb, 0, 0, WIN_W, WIN_H, COL_UI_BG); /* Cabeçalho */ rb_fill_rect(rb, 0, 0, WIN_W, LM_HEAD_H, COL_MENU); float bx = LM_MARGIN, by = LM_HEAD_H*0.5f; rb_fill_circle(rb, bx, by, 16, COLA(255,255,255,40)); rb_line(rb, bx+4, by-7, bx-5, by, 2.f, COL_WHITE); rb_line(rb, bx-5, by, bx+4, by+7, 2.f, COL_WHITE); rb_text_c(rb, bx + 28, by, "Voltar", COL_WHITE, FS_UI); { const char* t = "Escolha uma Extensão"; rb_text_c(rb, (WIN_W - tw(t, 20))*0.5f, by, t, COL_WHITE, 20); } /* Barra de filtros */ float fh = libman_chip_layout(ed, NULL); rb_fill_rect(rb, 0, LM_HEAD_H, WIN_W, fh, COL_PANEL); float sx = LM_MARGIN, sy = LM_HEAD_H + 14; rb_fill_rrect(rb, sx, sy, LM_SEARCH_W, 44, 22, COL_UI_BG); if (ed->libman_search_focus) rb_stroke_rect(rb, sx-1, sy-1, LM_SEARCH_W+2, 46, 2.f, COL_MENU); { const char* t = ed->libman_query[0] ? ed->libman_query : "Buscar"; rb_text_c(rb, sx + 16, sy + 22, t, ed->libman_query[0] ? COL_TEXT : COL_TEXT_DIM, FS_UI); if (ed->libman_search_focus) { float cw = tw(ed->libman_query, FS_UI); rb_fill_rect(rb, sx + 16 + cw, sy + 12, 1.5f, 20, COL_TEXT); } } { const char* labels[LM_MAX_CHIPS]; int n = libman_chip_labels(ed, labels); float rects[LM_MAX_CHIPS][4]; libman_chip_layout(ed, rects); for (int i = 0; i < n; i++) { bool sel = (i == 0) ? (ed->libman_filter < 0) : (ed->libman_filter == i-1); rb_fill_rrect(rb, rects[i][0], rects[i][1], rects[i][2], rects[i][3], 17, sel ? COL_MENU : COL_UI_BG); rb_text_c(rb, rects[i][0] + 14, rects[i][1] + LM_CHIP_H*0.5f, labels[i], sel ? COL_WHITE : COL_TEXT, FS_UI); } } /* Grade de cartoes (com recorte e rolagem) */ rb_fill_rect(rb, 0, gridY, WIN_W, WIN_H - gridY, COL_UI_BG); clip_set(ed, rb, 0, gridY, WIN_W, WIN_H - gridY); for (int k = 0; k < nh; k++) { int col = k % 2, row = k / 2; float x = LM_MARGIN + col*(LM_CARD_W + LM_CARD_GAP); float y = gridY + 8 + row*(LM_CARD_H + LM_CARD_GAP) - ed->libman_scroll; if (y + LM_CARD_H < gridY) continue; if (y > WIN_H) break; const TbLibmanEntry* e = tb_libman_entry(hits[k]); if (!e) continue; Col c = { e->color[0]/255.f, e->color[1]/255.f, e->color[2]/255.f, 1.f }; rb_fill_rrect(rb, x, y, LM_CARD_W, LM_CARD_H, 8, COL_PANEL); rb_fill_rrect(rb, x, y, LM_CARD_W, 56, 8, c); rb_fill_rect(rb, x, y + 40, LM_CARD_W, 16, c); rb_text_c(rb, x + 16, y + 28, e->category, COL_WHITE, FS_UI); rb_text_c(rb, x + 16, y + 84, e->name, COL_TEXT, 18); rb_text_c(rb, x + 16, y + 114, e->description, COL_TEXT_DIM, FS_UI); rb_text_c(rb, x + 16, y + LM_CARD_H - 22, e->shared, COL_TEXT_DIM, FS_SM); if (tb_libman_loaded(hits[k])) { rb_fill_circle(rb, x + LM_CARD_W - 24, y + 28, 8, COL_FLAG); rb_text_c(rb, x + LM_CARD_W - 110, y + LM_CARD_H - 22, "carregada", COL_FLAG, FS_SM); } if (ed->libman_hover == k) rb_stroke_rect(rb, x-1, y-1, LM_CARD_W+2, LM_CARD_H+2, 2.f, COL_MENU); } clip_clear(ed, rb); if (nh == 0) rb_text_c(rb, LM_MARGIN, gridY + 40, "Nenhuma library encontrada.", COL_TEXT_DIM, FS_UI); } static void libman_click(Ed* ed, float mx, float my) { if (my < LM_HEAD_H) { if (mx < 170) libman_close(ed); return; } float gridY = libman_grid_y(ed); if (my < gridY) { if (in_rect(mx, my, LM_MARGIN, LM_HEAD_H + 14, LM_SEARCH_W, 44)) { ed->libman_search_focus = true; return; } const char* labels[LM_MAX_CHIPS]; int n = libman_chip_labels(ed, labels); float rects[LM_MAX_CHIPS][4]; libman_chip_layout(ed, rects); for (int i = 0; i < n; i++) if (in_rect(mx, my, rects[i][0], rects[i][1], rects[i][2], rects[i][3])) { ed->libman_filter = i - 1; ed->libman_scroll = 0; ed->libman_search_focus = false; return; } ed->libman_search_focus = false; return; } ed->libman_search_focus = false; if (mx < LM_MARGIN || mx >= WIN_W - LM_MARGIN) return; int hits[TBLM_MAX_ENTRIES]; int nh = tb_libman_search(ed->libman_query, libman_filter_name(ed), hits, TBLM_MAX_ENTRIES); for (int k = 0; k < nh; k++) { int col = k % 2, row = k / 2; float x = LM_MARGIN + col*(LM_CARD_W + LM_CARD_GAP); float y = gridY + 8 + row*(LM_CARD_H + LM_CARD_GAP) - ed->libman_scroll; if (y + LM_CARD_H < gridY || y > WIN_H) continue; if (in_rect(mx, my, x, y, LM_CARD_W, LM_CARD_H)) { const TbLibmanEntry* e = tb_libman_entry(hits[k]); if (e && e->shared[0]) hotlib_load(ed, e->shared); else { snprintf(ed->hot_status, sizeof(ed->hot_status), "%s: caminho do .so indisponivel", e ? e->name : "?"); ed->hot_status_ok = false; } libman_close(ed); return; } } } static void libman_key(Ed* ed, int sc) { if (sc == TB_KEY_ESCAPE) { libman_close(ed); return; } if (sc == TB_KEY_BACKSPACE && ed->libman_search_focus) { if (ed->libman_query[0]) { utf8_pop(ed->libman_query); ed->libman_query_len = (int)strlen(ed->libman_query); } } } static void libman_text(Ed* ed, const char* typed) { if (!ed->libman_search_focus) return; append_text(ed->libman_query, sizeof(ed->libman_query), typed); ed->libman_query_len = (int)strlen(ed->libman_query); } static void libman_scroll_by(Ed* ed, float dy) { ed->libman_scroll -= (int)(dy * 48.f); int hits[TBLM_MAX_ENTRIES]; int nh = tb_libman_search(ed->libman_query, libman_filter_name(ed), hits, TBLM_MAX_ENTRIES); int rows = (nh + 1) / 2; float gridY = libman_grid_y(ed); int content = rows * (LM_CARD_H + LM_CARD_GAP) + 16; int visible = (int)(WIN_H - gridY); int maxs = content - visible; if (maxs < 0) maxs = 0; if (ed->libman_scroll > maxs) ed->libman_scroll = maxs; if (ed->libman_scroll < 0) ed->libman_scroll = 0; } /* === * Configuracoes (settings) - store da tinyblocks-environ, salvo/exportado em CSV * === */ #define ST_HEAD_H 64 #define ST_OPT_Y ST_HEAD_H #define ST_OPT_H 40 #define ST_TOOL_Y (ST_HEAD_H + ST_OPT_H) #define ST_TOOL_H 64 #define ST_MARGIN 40 #define ST_ROW_H 40 #define ST_LIST_Y (ST_TOOL_Y + ST_TOOL_H + 6) #define ST_BTN_H 40 #define ST_ENV_LABEL "Detectar caminho de TINYBLOCKS_SETTINGS" /* Recalcula o caminho do config: da variavel de ambiente (se o toggle * estiver ligado e a variavel existir) ou o caminho padrao do sistema. */ static void settings_sync_path(Ed* ed) { if (ed->settings_use_env) { const char* e = tb_environ_env_path(); if (e[0]) { snprintf(ed->settings_path, sizeof(ed->settings_path), "%s", e); return; } } tb_environ_config_path(ed->settings_path, sizeof(ed->settings_path)); } static void settings_show(Ed* ed) { ed->settings_open = true; ed->settings_sel = -1; ed->settings_path_focus = false; ed->settings_value_edit = false; ed->settings_new_key = false; ed->settings_scroll = 0; ed->settings_hover = -1; settings_sync_path(ed); ed->libman_open = false; ed->path_input_active = false; ed->ctx_menu_open = false; } static void settings_close(Ed* ed) { ed->settings_open = false; ed->settings_value_edit = false; ed->settings_new_key = false; ed->settings_path_focus = false; } static float settings_btn_w(int i) { return i == 1 ? 150.f : 96.f; } static void settings_btn_rect(Ed* ed, int i, float* x, float* y, float* w, float* h) { float gap = 12.f, cur = WIN_W - ST_MARGIN; float pos[3]; for (int k = 2; k >= 0; k--) { cur -= settings_btn_w(k); pos[k] = cur; cur -= gap; } *x = pos[i]; *y = ST_TOOL_Y + 12.f; *w = settings_btn_w(i); *h = ST_BTN_H; } static void settings_path_rect(Ed* ed, float* x, float* y, float* w, float* h) { float bx; settings_btn_rect(ed, 0, &bx, y, w, h); *x = ST_MARGIN; *w = bx - 20.f - ST_MARGIN; } static void st_button(TinyBlocks_RenderableBlock* rb, float x, float y, float w, float h, const char* label, bool active) { rb_fill_rrect(rb, x, y, w, h, 6, active ? COL_MENU_DARK : COL_MENU); rb_text_c(rb, x + (w - tw(label, FS_UI)) * 0.5f, y + h * 0.5f, label, COL_WHITE, FS_UI); } static void settings_export(Ed* ed, const char* path) { if (!path || !path[0]) path = ed->settings_path; bool ok = tb_environ_export_csv_meta(path, "arquivo_config", path); if (ok) snprintf(ed->hot_status, sizeof(ed->hot_status), "Configuracoes salvas (CSV): %.200s", path); else snprintf(ed->hot_status, sizeof(ed->hot_status), "Falha ao salvar: %.200s", tb_environ_last_error()); ed->hot_status_ok = ok; } /* Rect da linha i (com o deslocamento da linha "nova chave", se ativa). */ static void settings_row_rect(Ed* ed, int i, float* x, float* y, float* w, float* h) { int off = ed->settings_new_key ? 1 : 0; *x = ST_MARGIN; *y = ST_LIST_Y + (i + off) * ST_ROW_H - ed->settings_scroll; *w = WIN_W - 2.f * ST_MARGIN; *h = ST_ROW_H; } static void settings_render(Ed* ed, TinyBlocks_RenderableBlock* rb) { if (!ed->settings_open) return; int n = tb_environ_count(); rb_fill_rect(rb, 0, 0, WIN_W, WIN_H, COL_UI_BG); /* Cabecalho */ rb_fill_rect(rb, 0, 0, WIN_W, ST_HEAD_H, COL_MENU); float bx = ST_MARGIN, by = ST_HEAD_H * 0.5f; rb_fill_circle(rb, bx, by, 16, COLA(255,255,255,40)); rb_line(rb, bx+4, by-7, bx-5, by, 2.f, COL_WHITE); rb_line(rb, bx-5, by, bx+4, by+7, 2.f, COL_WHITE); rb_text_c(rb, bx + 28, by, "Voltar", COL_WHITE, FS_UI); { const char* t = "Configurações"; rb_text_c(rb, (WIN_W - tw(t, 20)) * 0.5f, by, t, COL_WHITE, 20); } /* Opcoes: toggle de deteccao do caminho pela variavel de ambiente */ rb_fill_rect(rb, 0, ST_OPT_Y, WIN_W, ST_OPT_H, COL_FLY); { float cb = ST_OPT_Y + (ST_OPT_H - 20) * 0.5f; rb_fill_rrect(rb, ST_MARGIN, cb, 20, 20, 4, ed->settings_use_env ? COL_MENU : COL_WHITE); rb_stroke_rect(rb, ST_MARGIN, cb, 20, 20, 2.f, COL_MENU); if (ed->settings_use_env) { rb_line(rb, ST_MARGIN + 4, cb + 10, ST_MARGIN + 8, cb + 15, 2.5f, COL_WHITE); rb_line(rb, ST_MARGIN + 8, cb + 15, ST_MARGIN + 16, cb + 5, 2.5f, COL_WHITE); } rb_text_c(rb, ST_MARGIN + 30, ST_OPT_Y + ST_OPT_H*0.5f, ST_ENV_LABEL, COL_TEXT, FS_UI); const char* e = tb_environ_env_path(); const char* hint = e[0] ? e : "TINYBLOCKS_SETTINGS nao definida"; rb_text_c(rb, WIN_W - ST_MARGIN - tw(hint, FS_SM), ST_OPT_Y + ST_OPT_H*0.5f, hint, e[0] ? COL_TEXT_DIM : COL_ERR_MENU, FS_SM); } /* Barra de ferramentas */ rb_fill_rect(rb, 0, ST_TOOL_Y, WIN_W, ST_TOOL_H, COL_PANEL); { float px, py, pw, ph; settings_path_rect(ed, &px, &py, &pw, &ph); rb_fill_rrect(rb, px, py, pw, ph, 6, COL_WHITE); if (ed->settings_path_focus) rb_stroke_rect(rb, px-1, py-1, pw+2, ph+2, 2.f, COL_MENU); rb_text_c(rb, px + 12, py + ph*0.5f, ed->settings_path, COL_TEXT, FS_UI); if (ed->settings_path_focus) { float cw = tw(ed->settings_path, FS_UI); rb_fill_rect(rb, px + 13 + cw, py + ph*0.5f - 9, 1.5f, 18, COL_TEXT); } } for (int i = 0; i < 3; i++) { float x, y, w, h; settings_btn_rect(ed, i, &x, &y, &w, &h); bool hov = in_rect(ed->mouse_x, ed->mouse_y, x, y, w, h); st_button(rb, x, y, w, h, i == 0 ? "Salvar" : i == 1 ? "Exportar CSV" : "+ Nova", hov); } /* Lista */ rb_fill_rect(rb, 0, ST_LIST_Y, WIN_W, WIN_H - ST_LIST_Y, COL_UI_BG); clip_set(ed, rb, 0, ST_LIST_Y, WIN_W, WIN_H - ST_LIST_Y); if (ed->settings_new_key) { float y = ST_LIST_Y - ed->settings_scroll; rb_fill_rrect(rb, ST_MARGIN, y + 2, WIN_W - 2*ST_MARGIN, ST_ROW_H - 4, 6, COL_PANEL); rb_text_c(rb, ST_MARGIN + 16, y + ST_ROW_H*0.5f, "+", COL_MENU, FS_UI); const char* t = ed->settings_key[0] ? ed->settings_key : "nome da chave (Enter confirma, Esc cancela)"; rb_text_c(rb, ST_MARGIN + 40, y + ST_ROW_H*0.5f, t, ed->settings_key[0] ? COL_TEXT : COL_TEXT_DIM, FS_UI); if (ed->settings_key[0]) { float cw = tw(ed->settings_key, FS_UI); rb_fill_rect(rb, ST_MARGIN + 41 + cw, y + ST_ROW_H*0.5f - 9, 1.5f, 18, COL_TEXT); } } for (int i = 0; i < n; i++) { float x, y, w, h; settings_row_rect(ed, i, &x, &y, &w, &h); if (y + h < ST_LIST_Y || y > WIN_H) continue; bool sel = (i == ed->settings_sel); rb_fill_rrect(rb, x, y + 2, w, h - 4, 6, sel ? COL_PANEL : COL_FLY); if (sel && !ed->settings_value_edit) rb_stroke_rect(rb, x, y+1, w, h-2, 2.f, COL_MENU); rb_text_c(rb, x + 16, y + h*0.5f, tb_environ_key(i), COL_TEXT, FS_UI); float vx = x + 16 + tw("", FS_UI) + 260.f; if (vx > x + w - 260.f) vx = x + w - 260.f; if (sel && ed->settings_value_edit) { rb_fill_rrect(rb, vx - 6, y + 6, w - (vx - x) - 4, h - 12, 4, COL_WHITE); rb_text_c(rb, vx, y + h*0.5f, ed->settings_edit, COL_TEXT, FS_UI); float cw = tw(ed->settings_edit, FS_UI); rb_fill_rect(rb, vx + 1 + cw, y + h*0.5f - 9, 1.5f, 18, COL_TEXT); } else { rb_text_c(rb, vx, y + h*0.5f, tb_environ_value_at(i), COL_TEXT_DIM, FS_UI); } } clip_clear(ed, rb); if (n == 0 && !ed->settings_new_key) rb_text_c(rb, ST_MARGIN, ST_LIST_Y + 24, "Nenhuma configuracao. Use \"+ Nova\".", COL_TEXT_DIM, FS_UI); if (ed->hot_status[0]) rb_text_c(rb, ST_MARGIN, WIN_H - 22, ed->hot_status, ed->hot_status_ok ? COL_TEXT_DIM : COL_ERR_MENU, FS_SM); } static 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) { if (in_rect(mx, my, ST_MARGIN, ST_OPT_Y, 540, ST_OPT_H)) { ed->settings_use_env = !ed->settings_use_env; settings_sync_path(ed); } return; } if (my < ST_TOOL_Y + ST_TOOL_H) { float px, py, pw, ph; settings_path_rect(ed, &px, &py, &pw, &ph); if (in_rect(mx, my, px, py, pw, ph)) { ed->settings_path_focus = true; ed->settings_value_edit = false; ed->settings_new_key = false; return; } for (int i = 0; i < 3; i++) { float x, y, w, h; settings_btn_rect(ed, i, &x, &y, &w, &h); if (!in_rect(mx, my, x, y, w, h)) continue; ed->settings_path_focus = false; if (i == 0) settings_export(ed, ed->settings_path); else if (i == 1) settings_export(ed, ed->settings_path); else { ed->settings_new_key = true; ed->settings_key[0] = 0; ed->settings_value_edit = false; ed->settings_sel = -1; ed->settings_scroll = 0; } return; } ed->settings_path_focus = false; return; } if (ed->settings_new_key && in_rect(mx, my, ST_MARGIN, ST_LIST_Y - ed->settings_scroll, WIN_W - 2*ST_MARGIN, ST_ROW_H)) return; int n = tb_environ_count(); for (int i = 0; i < n; i++) { float x, y, w, h; settings_row_rect(ed, i, &x, &y, &w, &h); if (!in_rect(mx, my, x, y, w, h)) continue; ed->settings_sel = i; ed->settings_new_key = false; ed->settings_path_focus = false; ed->settings_value_edit = true; const char* v = tb_environ_value_at(i); strncpy(ed->settings_edit, v ? v : "", sizeof(ed->settings_edit) - 1); ed->settings_edit[sizeof(ed->settings_edit) - 1] = 0; return; } ed->settings_sel = -1; ed->settings_value_edit = false; } static void settings_key(Ed* ed, int sc, bool ctrl) { (void)ctrl; bool enter = sc == TB_KEY_RETURN; if (sc == TB_KEY_ESCAPE) { if (ed->settings_new_key) { ed->settings_new_key = false; ed->settings_key[0] = 0; } else if (ed->settings_value_edit) ed->settings_value_edit = false; else settings_close(ed); return; } if (ed->settings_new_key) { if (enter && ed->settings_key[0]) { tb_environ_set(ed->settings_key, ""); ed->settings_new_key = false; ed->settings_sel = tb_environ_count() - 1; ed->settings_value_edit = true; ed->settings_edit[0] = 0; ed->settings_scroll = 0; } else if (sc == TB_KEY_BACKSPACE) { utf8_pop(ed->settings_key); } return; } if (ed->settings_value_edit && ed->settings_sel >= 0) { if (enter) { const char* k = tb_environ_key(ed->settings_sel); if (k) tb_environ_set(k, ed->settings_edit); ed->settings_value_edit = false; } else if (sc == TB_KEY_BACKSPACE) { utf8_pop(ed->settings_edit); } return; } if (ed->settings_path_focus && sc == TB_KEY_BACKSPACE) { utf8_pop(ed->settings_path); return; } if (sc == TB_KEY_DELETE && ed->settings_sel >= 0) { const char* k = tb_environ_key(ed->settings_sel); if (k) tb_environ_unset(k); ed->settings_sel = -1; } } static 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) { 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; int visible = (int)(WIN_H - ST_LIST_Y); int maxs = content - visible; if (maxs < 0) maxs = 0; if (ed->settings_scroll > maxs) ed->settings_scroll = maxs; if (ed->settings_scroll < 0) ed->settings_scroll = 0; } /* === * Arrastar e encaixar * === */ static void start_drag(Ed* ed) { Tab* T = &CT; int bi = ed->press_bi; EdBlock* b = &T->ws[bi]; float sx = b->ax + WS_X - T->ws_sx, sy = b->ay + WS_Y - T->ws_sy; float ax = b->ax, ay = b->ay; detach(T, bi); top_add(T, bi); b->x = ax; b->y = ay; ed->drag_bi = bi; ed->drag_ox = ed->press_mx - sx; ed->drag_oy = ed->press_my - sy; mark_drag(T, bi, true); ed->state = ES_DRAG; ed->snap_kind = SN_NONE; bubble_clear(ed); } static void consider(Ed* ed, float* best, SnapKind k, int bi, int idx, float x0, float y0, float x1, float y1) { float d = hypotf(x1 - x0, y1 - y0); if (d >= *best) return; *best = d; ed->snap_kind = k; ed->snap_bi = bi; ed->snap_idx = idx; } static void compute_snap(Ed* ed) { Tab* T = &CT; EdBlock* d = &T->ws[ed->drag_bi]; Shape ds = shape_of(d->type); float best = SNAP_R; ed->snap_kind = SN_NONE; if (shape_is_value(ds)) { /* Repórter: o lado esquerdo procura um campo de entrada */ float px = d->x, py = d->y + d->h*0.5f; for (int i = 0; i < MAX_WS; i++) { EdBlock* B = &T->ws[i]; if (!B->used || B->dragging || !B->type) continue; for (int s = 0; s < input_count(B->type); s++) { if (ds == SH_REPORTER && slot_is_bool(B->type, s)) continue; consider(ed, &best, SN_ARG, i, s, px, py, B->ax + B->slot_x[s], B->ay + B->slot_y[s] + B->slot_h[s]*0.5f); } } return; } float dh = chain_h(T, ed->drag_bi); for (int i = 0; i < MAX_WS; i++) { EdBlock* B = &T->ws[i]; if (!B->used || B->dragging) continue; Shape bs = shape_of(B->type); if (shape_is_value(bs)) continue; if (ds != SH_HAT) { consider(ed, &best, SN_NEXT, i, 0, d->x, d->y, B->ax, B->ay + B->h); int mouths = bs == SH_C1 ? 1 : bs == SH_C2 ? 2 : 0; for (int k = 0; k < mouths; k++) consider(ed, &best, SN_SUB, i, k, d->x, d->y, B->ax + ARM_W, B->ay + B->sub_y[k]); } if (B->parent < 0 && bs != SH_HAT) consider(ed, &best, SN_ABOVE, i, 0, d->x, d->y + dh, B->ax, B->ay); } } static void apply_snap(Ed* ed) { Tab* T = &CT; int bi = ed->drag_bi, t = ed->snap_bi; switch (ed->snap_kind) { case SN_NEXT: attach_insert(T, t, REL_NEXT, bi); break; case SN_SUB: attach_insert(T, t, REL_SUB0 + ed->snap_idx, bi); break; case SN_ABOVE: attach_above(T, t, bi); break; case SN_ARG: attach_arg(T, t, ed->snap_idx, bi); break; default: break; } } static void cleanup_ws(Ed* ed) { Tab* T = &CT; layout_tab(T); float y = 24 + T->ws_sy; for (int i = 0; i < T->top_n; i++) { EdBlock* b = &T->ws[T->top[i]]; b->x = 24 + T->ws_sx; b->y = y; y += chain_h(T, T->top[i]) + 28; } } /* === * Edição de texto * === */ static void utf8_pop(char* s) { size_t n = strlen(s); while (n > 0) { n--; if (((unsigned char)s[n] & 0xC0) != 0x80) break; } s[n] = 0; } static void append_text(char* dst, size_t cap, const char* add) { size_t n = strlen(dst), a = strlen(add); if (n + a < cap) memcpy(dst + n, add, a + 1); } static char* edit_target(Ed* ed, size_t* cap) { EdBlock* b = &CT.ws[ed->edit_bi]; if (is_lit_text(b->type) && ed->edit_in == 0) { *cap = LIT_TEXT_CAP; return b->lit_text; } *cap = sizeof(b->in_text[0]); return b->in_text[ed->edit_in]; } /* === * Input * === */ static TinyBlocks_Block* editor_events_block(TinyBlocks_Block* self, TinyBlocks* rt) { TinyBlocks_Value v = tb_block_get_input(self, rt, 0); return v.kind == TB_VALUE_BLOCK ? v.as.block : NULL; } static int64_t ev_int(TinyBlocks_Block* evb, int idx) { if (!evb || idx<0 || (uint32_t)idx>=evb->output_count) return 0; TinyBlocks_Value* v=&evb->outputs[idx]; return v->kind==TB_VALUE_INTEGER ? v->as.integer : 0; } static double ev_real(TinyBlocks_Block* evb, int idx) { if (!evb || idx<0 || (uint32_t)idx>=evb->output_count) return 0.0; TinyBlocks_Value* v=&evb->outputs[idx]; return v->kind==TB_VALUE_REAL ? v->as.real : 0.0; } static const char* ev_text(TinyBlocks_Block* evb, int idx) { if (!evb || idx<0 || (uint32_t)idx>=evb->output_count) return ""; TinyBlocks_Value* v=&evb->outputs[idx]; return (v->kind==TB_VALUE_TEXT && v->as.text) ? v->as.text : ""; } static bool hit_flag(Ed* ed, float mx, float my) { return in_rect(mx, my, WIN_W-STAGE_W+10, MENU_H+6, 40, 32); } static bool hit_stop(Ed* ed, float mx, float my) { return in_rect(mx, my, WIN_W-STAGE_W+56, MENU_H+6, 40, 32); } static bool hit_detach(Ed* ed, float mx, float my) { return ed->stage && in_rect(mx, my, WIN_W-50, MENU_H+6, 40, 32); } static bool hit_lib_btn(float mx, float my) { return in_rect(mx, my, LIB_BTN_X, 0, LIB_BTN_W, MENU_H); } static bool hit_open_btn(float mx, float my) { return in_rect(mx, my, OPEN_BTN_X, 0, OPEN_BTN_W, MENU_H); } static bool hit_save_btn(float mx, float my) { return in_rect(mx, my, SAVE_BTN_X, 0, SAVE_BTN_W, MENU_H); } static bool hit_export_btn(float mx, float my) { return in_rect(mx, my, EXP_BTN_X, 0, EXP_BTN_W, MENU_H); } static bool hit_libman_btn(float mx, float my) { return in_rect(mx, my, LIBM_BTN_X, 0, LIBM_BTN_W, MENU_H); } static 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) { ed->path_input_active = true; ed->path_mode = mode; snprintf(ed->path_input_buf, sizeof(ed->path_input_buf), "%s", def ? def : ""); ed->path_input_len = (int)strlen(ed->path_input_buf); } static int hit_fly(Ed* ed, float mx, float my) { float fx = mx - CAT_W, fy = my - PAL_Y + ed->fly_scroll; for (int i = 0; i < ed->fly_n; i++) { FlyItem* it = &ed->fly_items[i]; if (it->kind == FI_BUTTON && in_rect(fx, fy, FLY_PAD, it->y+4, FLY_BTN_W, 30)) return i; if (it->kind == FI_BLOCK && hit_one(&ed->fly, it->bi, fx, fy) >= 0) return i; } return -1; } static void spawn_from_fly(Ed* ed, int item, float mx, float my) { Tab* F = &ed->fly; int src = ed->fly_items[item].bi; int ni = copy_tree(F, src, &CT, false); if (ni < 0) { snprintf(ed->hot_status, sizeof(ed->hot_status), "Limite de %d blocos por aba atingido", MAX_WS); ed->hot_status_ok = false; return; } top_add(&CT, ni); float sx = F->ws[src].ax + CAT_W, sy = F->ws[src].ay + PAL_Y - ed->fly_scroll; CT.ws[ni].x = sx - WS_X + CT.ws_sx; CT.ws[ni].y = sy - WS_Y + CT.ws_sy; ed->drag_bi = ni; ed->drag_ox = mx - sx; ed->drag_oy = my - sy; mark_drag(&CT, ni, true); ed->state = ES_DRAG; ed->snap_kind = SN_NONE; layout_tab(&CT); } /* Recolhe o palco para o painel (fecha a janela própria, se houver) */ static void stage_attach(Ed* ed) { if (ed->stage) tb_block_set_default(ed->stage, 0, tb_value_none()); if (ed->stage_win) { tb_block_destroy(ed->stage_win, ed->rt); ed->stage_win = NULL; } if (ed->stage_in) { tb_block_destroy(ed->stage_in, ed->rt); ed->stage_in = NULL; } } /* Destaca o palco: ele vira a cena de um Graphics.Window próprio */ static void stage_detach(Ed* ed) { TinyBlocks_TypeBlock* t_win = tb_type_block_find(ed->rt, "Graphics.Window"); TinyBlocks_TypeBlock* t_in = tb_type_block_find(ed->rt, "Graphics.Input"); if (!ed->stage || ed->stage_win || !t_win || !t_in) return; ed->stage_in = tb_block_create(ed->rt, t_in); ed->stage_win = tb_block_create(ed->rt, t_win); if (ed->stage_in && ed->stage_win) { TinyBlocks_Value title = tb_value_text("Palco = TinyBlocks"); tb_block_set_default(ed->stage_win, 0, title); /* set_default clona */ tb_value_free(&title); tb_block_set_default(ed->stage_win, 1, tb_value_integer(480)); tb_block_set_default(ed->stage_win, 2, tb_value_integer(360)); tb_block_set_default(ed->stage_win, 3, tb_value_block(ed->stage)); tb_block_set_default(ed->stage_win, 4, tb_value_block(ed->stage_in)); tb_block_set_default(ed->stage_win, 5, tb_value_integer(0)); /* fechar não encerra o editor */ tb_block_set_default(ed->stage, 0, tb_value_block(ed->stage_in)); tb_block_eval(ed->stage_win, ed->rt); } if (!tb_graphics_window_is_open(ed->stage_win)) { stage_attach(ed); snprintf(ed->hot_status, sizeof(ed->hot_status), "Não foi possível abrir a janela do palco"); ed->hot_status_ok = false; } } static void ctx_exec(Ed* ed, int id) { Tab* T = &CT; int bi = ed->ctx_menu_bi; switch (id) { case CM_DUPLICATE: { int ni = copy_tree(T, bi, T, true); if (ni >= 0) { top_add(T, ni); T->ws[ni].x = T->ws[bi].ax + 24; T->ws[ni].y = T->ws[bi].ay + 24; } break; } case CM_DELETE: delete_heal(ed, T, bi); break; case CM_EDIT_DEF: if (T->ws[bi].type) open_def(ed, T->ws[bi].type->type_name + 5); break; case CM_CLEANUP: cleanup_ws(ed); break; case CM_NEW_COMPOSITE: new_composite_tab(ed); break; case CM_EXP_JSON: start_path(ed, PM_EXP_JSON, "projeto.json"); break; case CM_EXP_XML: start_path(ed, PM_EXP_XML, "projeto.xml"); break; case CM_EXP_CSV: start_path(ed, PM_EXP_CSV, "projeto.csv"); break; default: break; } } 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->ctx_menu_open) { int it = ctx_hit(ed, mx, my); ed->ctx_menu_open = false; ed->ctx_export = false; if (it >= 0 && it < ed->ctx_n) ctx_exec(ed, ed->ctx_items[it]); return; } ed->editing = false; bubble_clear(ed); /* Barra de menu */ if (my < MENU_H) { if (hit_lib_btn(mx, my)) start_path(ed, PM_LIB, ""); else if (hit_open_btn(mx, my)) start_path(ed, PM_LOAD, "projeto.json"); else if (hit_save_btn(mx, my)) start_path(ed, PM_SAVE, "projeto.json"); else if (hit_libman_btn(mx, my)) libman_show(ed); else if (hit_settings_btn(ed, mx, my)) settings_show(ed); else if (hit_export_btn(mx, my)) { ed->ctx_n = 0; ed->ctx_items[ed->ctx_n++] = CM_EXP_JSON; ed->ctx_items[ed->ctx_n++] = CM_EXP_XML; ed->ctx_items[ed->ctx_n++] = CM_EXP_CSV; ed->ctx_menu_open = true; ed->ctx_export = true; ed->ctx_menu_bi = -1; ed->ctx_menu_x = (int)EXP_BTN_X; ed->ctx_menu_y = (int)MENU_H; ed->ctx_menu_hover = -1; } else ed->path_input_active = false; return; } ed->path_input_active = false; /* Palco */ if (mx >= WIN_W - STAGE_W) { if (hit_flag(ed, mx, my)) run_flag(ed); else if (hit_stop(ed, mx, my)) { run_reset(ed); ed->stage_buf[0] = 0; } else if (hit_detach(ed, mx, my)) { if (ed->stage_win) stage_attach(ed); else stage_detach(ed); } return; } /* Abas */ if (my < MENU_H + TAB_H) { for (int i = 0; i < ed->tab_n; i++) { float tx = 8 + i*TAB_W; if (!in_rect(mx, my, tx, MENU_H, TAB_W-4, TAB_H)) continue; if (ed->tab_n > 1 && mx >= tx + TAB_W - 28) tab_close(ed, i); else tab_select(ed, i); return; } float px = 8 + ed->tab_n*TAB_W; if (in_rect(mx, my, px, MENU_H, PLUS_W, TAB_H)) tab_new(ed, NULL, false); return; } /* Barra do bloco composto */ if (CT.is_composite) { float px, py; comp_panel_pos(ed, &px, &py); if (in_rect(mx, my, px, py, CP_W, CP_H)) { float bx = px + CP_W - 10; bx -= 78; if (in_rect(mx, my, bx, py+8, 78, 28)) { save_composite_from_tab(ed); return; } bx -= 96; if (in_rect(mx, my, bx, py+8, 88, 28)) { if (CT.comp_id >= 0) dlg_open(ed, CT.comp_id); return; } return; } } /* Categorias */ if (mx < CAT_W) { if (hit_libman_foot(ed, mx, my)) { libman_show(ed); return; } int c = (int)((my - PAL_Y) / cat_item_h(ed)); if (c >= 0 && c < ed->cat_n) { ed->fly_scroll = ed->cats[c].fly_y - 4; if (ed->fly_scroll > fly_max_scroll(ed)) ed->fly_scroll = fly_max_scroll(ed); if (ed->fly_scroll < 0) ed->fly_scroll = 0; } return; } /* Flyout */ if (mx < PALETTE_W) { int it = hit_fly(ed, mx, my); if (it < 0) return; if (ed->fly_items[it].kind == FI_BUTTON) new_composite_tab(ed); else spawn_from_fly(ed, it, mx, my); return; } /* Workspace */ float wx = mx - WS_X + CT.ws_sx, wy = my - WS_Y + CT.ws_sy; int bi = hit_ws(&CT, wx, wy); if (bi < 0) { ed->state = ES_PAN; ed->pan_mx = mx; ed->pan_my = my; ed->pan_sx = CT.ws_sx; ed->pan_sy = CT.ws_sy; return; } int s = hit_slot(&CT, bi, wx, wy); if (s >= 0 && !slot_is_bool(CT.ws[bi].type, s)) { ed->editing = true; ed->edit_bi = bi; ed->edit_in = s; return; } top_add(&CT, stack_root(&CT, bi)); ed->state = ES_PRESS; ed->press_bi = bi; ed->press_mx = mx; ed->press_my = my; } static void on_lmb_up(Ed* ed, float mx, float my) { (void)my; if (ed->comp_dialog_open) 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 */ else apply_snap(ed); } else if (ed->state == ES_PRESS) { ed->state = ES_IDLE; int bi = ed->press_bi; Shape sh = shape_of(blk_type(ed, &CT.ws[bi])); unsigned t = now_ms(); bool dbl = (bi == ed->last_click_bi) && (t - ed->last_click_ms <= 400u); ed->last_click_bi = bi; ed->last_click_ms = t; if (shape_is_value(sh)) { if (dbl) run_click(ed, bi); /* balão de resultado: clique duplo */ } else { run_click(ed, bi); } } ed->state = ES_IDLE; ed->drag_bi = -1; ed->snap_kind = SN_NONE; } static void on_rmb_down(Ed* ed, float mx, float my) { if (ed->ctx_menu_open) { ed->ctx_menu_open = false; ed->ctx_export = false; return; } if (ed->state != ES_IDLE) return; if (my < WS_Y || mx < WS_X || mx >= WIN_W - STAGE_W) return; int bi = hit_ws(&CT, mx - WS_X + CT.ws_sx, my - WS_Y + CT.ws_sy); ed->ctx_n = 0; if (bi >= 0) { ed->ctx_items[ed->ctx_n++] = CM_DUPLICATE; ed->ctx_items[ed->ctx_n++] = CM_DELETE; const TinyBlocks_TypeBlock* t = CT.ws[bi].type; if (t && strncmp(t->type_name, "User.", 5) == 0) ed->ctx_items[ed->ctx_n++] = CM_EDIT_DEF; } else { ed->ctx_items[ed->ctx_n++] = CM_CLEANUP; ed->ctx_items[ed->ctx_n++] = CM_NEW_COMPOSITE; } ed->ctx_menu_open = true; ed->ctx_export = false; ed->ctx_menu_bi = bi; ed->ctx_menu_x = (int)mx; ed->ctx_menu_y = (int)my; ed->ctx_menu_hover = -1; } static void on_key(Ed* ed, int sc, bool ctrl) { bool enter = sc == TB_KEY_RETURN; if (ed->settings_open) { settings_key(ed, sc, ctrl); return; } if (ed->libman_open) { libman_key(ed, sc); return; } if (ed->comp_dialog_open) { dlg_key(ed, sc); return; } if (ed->ctx_menu_open) { if (sc == TB_KEY_ESCAPE) ed->ctx_menu_open = false; return; } if (ed->path_input_active) { if (sc == TB_KEY_ESCAPE) { ed->path_input_active = false; ed->path_mode = PM_NONE; } else if (enter) { const char* p = ed->path_input_buf; if (p[0]) { switch (ed->path_mode) { case PM_LOAD: project_load(ed, p); break; case PM_SAVE: project_save(ed, p); break; 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; default: hotlib_load(ed, p); break; } } ed->path_input_active = false; ed->path_mode = PM_NONE; } else if (sc == TB_KEY_BACKSPACE) { utf8_pop(ed->path_input_buf); ed->path_input_len = (int)strlen(ed->path_input_buf); } return; } if (ed->editing) { size_t cap; char* t = edit_target(ed, &cap); bool multi = is_lit_text(CT.ws[ed->edit_bi].type); if (sc == TB_KEY_ESCAPE || (enter && !multi)) ed->editing = false; else if (enter) append_text(t, cap, "\n"); else if (sc == TB_KEY_BACKSPACE) utf8_pop(t); return; } if (ctrl && sc == (TB_KEY_A + ('l' - 'a'))) { libman_show(ed); return; } if (ctrl && sc == (TB_KEY_A + ('o' - 'a'))) { start_path(ed, PM_LIB, ""); return; } if (sc == TB_KEY_DELETE && ed->state == ES_IDLE) { float mx = ed->mouse_x, my = ed->mouse_y; if (mx >= WS_X && mx < WIN_W - STAGE_W && my >= WS_Y) { int bi = hit_ws(&CT, mx - WS_X + CT.ws_sx, my - WS_Y + CT.ws_sy); if (bi >= 0) delete_heal(ed, &CT, bi); } return; } if (sc == TB_KEY_F5) run_flag(ed); } static void on_text(Ed* ed, const char* typed) { if (ed->settings_open) { settings_text(ed, typed); return; } if (ed->libman_open) { libman_text(ed, typed); return; } if (ed->comp_dialog_open) { dlg_text(ed, typed); return; } if (ed->path_input_active) { append_text(ed->path_input_buf, sizeof(ed->path_input_buf), typed); ed->path_input_len = (int)strlen(ed->path_input_buf); } else if (ed->editing) { size_t cap; char* t = edit_target(ed, &cap); append_text(t, cap, typed); } } /* === * editor_eval - lê um snapshot de Graphics.Input por frame e atualiza o estado * === */ static void editor_eval(TinyBlocks_Block* self, TinyBlocks* rt) { Ed* ed = *(Ed**)self->userdata; self->dirty = false; if (!ed) return; g_active_ed = ed; TinyBlocks_Block* evb = editor_events_block(self, rt); if (!evb) return; int ww = (int)ev_int(evb, GFX_IN_WIN_W); int wh = (int)ev_int(evb, GFX_IN_WIN_H); if (ww > 0) ed->win_w = ww; if (wh > 0) ed->win_h = wh; float mx = (float)ev_real(evb, GFX_IN_MOUSE_X); float my = (float)ev_real(evb, GFX_IN_MOUSE_Y); ed->mouse_x = mx; ed->mouse_y = my; layout_tab(&CT); /* == Hover === */ ed->flag_hover = hit_flag(ed, mx, my); ed->stop_hover = hit_stop(ed, mx, my); ed->lib_hover = hit_lib_btn(mx, my); ed->detach_hover = hit_detach(ed, mx, my); /* Janela do palco fechada pelo usuário: o palco volta para o painel */ if (ed->stage_win && !tb_graphics_window_is_open(ed->stage_win)) stage_attach(ed); ed->ctx_menu_hover = ed->ctx_menu_open ? ctx_hit(ed, mx, my) : -1; /* == Movimento === */ if (ed->state == ES_PRESS && fabsf(mx - ed->press_mx) + fabsf(my - ed->press_my) > 4.f) start_drag(ed); if (ed->state == ES_DRAG && ed->drag_bi >= 0) { EdBlock* b = &CT.ws[ed->drag_bi]; b->x = mx - ed->drag_ox - WS_X + CT.ws_sx; b->y = my - ed->drag_oy - WS_Y + CT.ws_sy; layout_tab(&CT); compute_snap(ed); } if (ed->state == ES_PAN) { CT.ws_sx = ed->pan_sx - (mx - ed->pan_mx); CT.ws_sy = ed->pan_sy - (my - ed->pan_my); } /* == Scroll === */ double sdx = ev_real(evb, GFX_IN_SCROLL_DX); double sdy = ev_real(evb, GFX_IN_SCROLL_DY); if (sdx != 0.0 || sdy != 0.0) { if (ed->settings_open) { settings_scroll_by(ed, (float)sdy); } else if (ed->libman_open) { libman_scroll_by(ed, (float)sdy); } else if (mx >= WS_X && mx < WIN_W - STAGE_W && my >= WS_Y) { CT.ws_sx -= (float)sdx * 40.f; CT.ws_sy -= (float)sdy * 40.f; } else if (mx < PALETTE_W && my >= PAL_Y) { ed->fly_scroll -= (float)sdy * 48.f; if (ed->fly_scroll > fly_max_scroll(ed)) ed->fly_scroll = fly_max_scroll(ed); if (ed->fly_scroll < 0) ed->fly_scroll = 0; } } /* == Drop de arquivo === */ const char* dropped = ev_text(evb, GFX_IN_DROP_FILE); if (dropped[0]) { size_t len = strlen(dropped); if (len > 3 && strcmp(dropped + len - 3, ".so") == 0) hotlib_load(ed, dropped); else if (len > 5 && strcmp(dropped + len - 5, ".json") == 0) project_load(ed, dropped); } if (ev_int(evb, GFX_IN_MOUSE_L_DOWN)) on_lmb_down(ed, mx, my); if (ev_int(evb, GFX_IN_MOUSE_R_DOWN)) on_rmb_down(ed, mx, my); if (ev_int(evb, GFX_IN_MOUSE_L_UP)) on_lmb_up(ed, mx, my); int sc = (int)ev_int(evb, GFX_IN_KEY); if (sc != 0) on_key(ed, sc, (ev_int(evb, GFX_IN_KEY_MOD) & TB_MOD_CTRL) != 0); const char* typed = ev_text(evb, GFX_IN_TEXT); if (typed[0]) on_text(ed, typed); /* Verifica mtime das libs vigiadas a cada ~60 frames (~1s) */ if (++ed->hot_check_frame >= 60) { ed->hot_check_frame = 0; hotlib_check(ed); } } /* === * editor_on_draw - compõe o frame inteiro em um RenderableBlock * === */ static bool editor_on_draw(TinyBlocks_Block* self, TinyBlocks* rt, TinyBlocks_RenderableBlock** dst) { (void)rt; Ed* ed = *(Ed**)self->userdata; if (!ed) return false; TinyBlocks_RenderableBlock* rb = tb_renderable_acquire(); if (!rb) return false; layout_tab(&CT); tb_draw_clear(rb, COL_UI_BG.r, COL_UI_BG.g, COL_UI_BG.b, 1.f); render_workspace(ed, rb); render_comp_panel(ed, rb); render_flyout(ed, rb); render_categories(ed, rb); render_stage(ed, rb); render_tab_bar(ed, rb); render_menu(ed, rb); /* A pilha arrastada fica por cima de tudo (pode passar sobre a paleta) */ if (ed->state == ES_DRAG && ed->drag_bi >= 0) render_chain(ed, rb, &CT, ed->drag_bi, WS_X - CT.ws_sx, WS_Y - CT.ws_sy); render_ctx_menu(ed, rb); dlg_render(ed, rb); libman_render(ed, rb); /* tela cheia: por cima de tudo */ settings_render(ed, rb); *dst = rb; return true; } /* === * Ciclo de vida da instância * === */ static int seed_blk(Ed* ed, const char* tn, const char* a0, const char* a1) { TinyBlocks_TypeBlock* t = tb_type_block_find(ed->rt, tn); int bi = t ? blk_new(&CT, t) : -1; if (bi < 0) return -1; if (a0) strncpy(CT.ws[bi].in_text[0], a0, 63); if (a1) strncpy(CT.ws[bi].in_text[1], a1, 63); return bi; } /* Script de exemplo no primeiro workspace */ static void seed_example(Ed* ed) { int hat = seed_blk(ed, "Events.WhenRun", NULL, NULL); int set = seed_blk(ed, "Variables.Set", "x", "0"); int rep = seed_blk(ed, "Control.Repeat", "5", NULL); int chg = seed_blk(ed, "Variables.Change", "x", "1"); int prt = seed_blk(ed, "IO.Print", "x vale", ""); int get = seed_blk(ed, "Variables.Get", "x", NULL); int all[] = { hat, set, rep, chg, prt, get }; for (int i = 0; i < 6; i++) { if (all[i] >= 0) continue; for (int k = 0; k < 6; k++) if (all[k] >= 0) free_tree(ed, &CT, all[k]); return; } Tab* T = &CT; T->ws[hat].x = 40; T->ws[hat].y = 40; top_add(T, hat); blk_link(T, hat, REL_NEXT, set); blk_link(T, set, REL_NEXT, rep); blk_link(T, rep, REL_SUB0, chg); blk_link(T, chg, REL_NEXT, prt); blk_link(T, prt, REL_ARG0 + 1, get); } static bool editor_instance_init(TinyBlocks_Block* self, TinyBlocks* rt) { Ed* ed = (Ed*)calloc(1, sizeof(Ed)); if (!ed) return false; ed->rt = rt; ed->win_w = WIN_W_DEFAULT; ed->win_h = WIN_H_DEFAULT; ed->drag_bi = -1; ed->press_bi = -1; ed->edit_bi = -1; bubble_clear(ed); ed->ctx_menu_bi = -1; ed->path_mode = PM_NONE; ed->settings_sel = -1; ed->settings_use_env = false; settings_sync_path(ed); ed->tab_n = 1; ed->cur_tab = 0; strcpy(ed->tabs[0].name, "Código"); ed->tabs[0].comp_id = -1; strcpy(ed->stage_buf, "Clique na bandeira verde (ou F5) para executar.\n" "Clique num bloco para executá-lo sozinho.\n"); strcpy(ed->hot_status, "Abrir/Salvar projeto no menu; Ctrl+O ou arraste um .so"); ed->hot_status_ok = true; *(Ed**)self->userdata = ed; g_active_ed = ed; TinyBlocks_TypeBlock* t_stage = tb_type_block_find(rt, "Editor.Stage"); if (t_stage) ed->stage = tb_block_create(rt, t_stage); palette_rebuild(ed); tb_libman_init(rt); /* liga tinyblocks-api e adota as libs embutidas */ tb_libman_scan_defaults(); /* procura library.toml em libraries/ e ~/.tinyblocks */ for (int i = 0; i < s_preload_n; i++) hotlib_load(ed, s_preload[i]); s_preload_n = 0; seed_example(ed); /* Configuracoes iniciais (store da tinyblocks-environ) */ if (tb_environ_count() == 0) { tb_environ_set("autor", ""); tb_environ_set("projeto", "sem_titulo"); tb_environ_set("tema", "claro"); tb_environ_set("escala", "1.0"); tb_environ_set("autosave", "0"); } return true; } static void editor_instance_deinit(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; Ed* ed = *(Ed**)self->userdata; if (!ed) return; /* As instâncias em run_blocks (e o palco e sua janela) são TB_KIND_BLOCK * registradas no runtime: a fase 1 do tinyblocks_deinit já as destrói = * aqui só soltamos o que é do editor. */ bubble_clear(ed); free(ed->run_blocks); for (int u = 0; u < ed->user_block_n; u++) free(ed->user_blocks[u].snap); tb_libman_shutdown(); if (g_active_ed == ed) g_active_ed = NULL; free(ed); *(Ed**)self->userdata = NULL; } /* === * Registra a library * === */ static void reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name, const TinyBlocks_SlotDesc* in, uint32_t ni, const TinyBlocks_SlotDesc* out, uint32_t no, void (*fn)(TinyBlocks_Block*, TinyBlocks*)) { TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, out, no, fn); if (t) tb_library_add(lib, &t->base); } static bool editor_lib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { /* Portas de blocos compostos */ static const TinyBlocks_SlotDesc port_label[] = {{"nome", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc port_out_in[] = {{"nome", TB_VALUE_TEXT}, {"valor", TB_VALUE_NONE}}; static const TinyBlocks_SlotDesc any_out[] = {{"valor", TB_VALUE_NONE}}; reg(rt, lib, "Port.In", port_label, 1, any_out, 1, eval_port_in); reg(rt, lib, "Port.Out", port_out_in, 2, NULL, 0, eval_port_out); /* Palco (Editor.Stage); os blocos Stage.* ficam na library Caneta */ if (!tb_stage_register(rt, lib)) return false; /* Editor.Scene - produz um RenderableBlock via on_draw; não abre janela */ static const TinyBlocks_SlotDesc scene_in[] = { {"events", TB_VALUE_BLOCK} }; TinyBlocks_TypeBlock* t = tb_type_block_create(rt, "Editor.Scene", scene_in, 1, NULL, 0, editor_eval); if (!t) return false; tb_type_block_set_instance_hooks(t, sizeof(Ed*), editor_instance_init, editor_instance_deinit); t->on_draw = editor_on_draw; tb_library_add(lib, &t->base); return true; } static void editor_lib_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { (void)rt; (void)lib; } TINYBLOCKS_DEFINE_LIBRARY(editor, "tinyblocks-editor", "2.0.0", editor_lib_init, editor_lib_deinit) const TinyBlocks_LibraryDescriptor* tb_editor_get_library(void) { return &_tb_lib_desc_editor; }