Files
tinyblocks/libraries/tinyblocks-editor/internal/tb_editor_internal.h
T
mguinhosandClaude Opus 5.5 f0abc7593a editor: explorador de arquivos (tinyblocks-editor-files) para Abrir/Salvar
Nova library privada do bundle do editor (dlopen + hot reload) com um
diálogo modal no lugar da barra de caminho: locais, trilha clicável,
lista filtrada por extensão, campo de nome e confirmação ao substituir.

- start_path() abre o explorador em todos os modos (projeto, exportar,
  imagem, código, .so); sem o módulo volta para a barra de caminho.
- O switch do Enter virou path_commit(), usado pelos dois caminhos.
- Estado em ed->fdlg para sobreviver à recarga do módulo.
- Empacotado no AppImage; 6 cenários novos no harness headless.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:03:01 -03:00

768 lines
31 KiB
C

/*
* TinyBlocks - tb_editor_internal.h
* Tipos, constantes de layout, tema e prototipos compartilhados entre o
* editor (tb_editor.c) e as libraries privadas do editor
* (libraries/tinyblocks-editor-*). Estas libraries sao um bundle privado:
* vem juntas com o editor e podem compartilhar este cabecalho.
*/
#ifndef TB_EDITOR_INTERNAL_H
#define TB_EDITOR_INTERNAL_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <tinyblocks/tinyblocks.h>
#include <tinyblocks/tb_renderable_block.h>
#include <tinyblocks/tb_json_block.h>
#include <tb_graphics.h>
#include <tinyblocks/tb_stage.h>
#include <tb_variables.h>
#include <tb_blueprint.h>
#include <tb_api.h>
#include <tb_libman.h>
#include <tb_environ.h>
#include <tb_syntax.h>
#include <tb_editor_widgets.h>
#include <tb_editor_image.h>
#include <tb_editor_files.h>
#include "../internal/tb_editor_modules.h"
#ifndef TB_EW_UNUSED
#define TB_EW_UNUSED __attribute__((unused))
#endif
/* ===
* Layout da janela
*
* ==== barra de menu (azul) ====
* == abas ===== [flag] [run] ====
* =cat= flyout (blocos) - área de scripts - palco / saída =
* =================
* === */
#define WIN_W_DEFAULT 1280
#define WIN_H_DEFAULT 720
#define MENU_H 44
#define TAB_H 36
#define CAT_W 68
#define FLY_W 250
#define FLY_PAD 12
#define FLY_BTN_W 150
#define PALETTE_W (CAT_W + FLY_W)
#define STAGE_W 360
#define STAGE_BAR_H 44
#define PAL_Y (MENU_H + TAB_H)
#define WS_X PALETTE_W
#define WS_Y (MENU_H + TAB_H)
#define WIN_W (ed->win_w)
#define WIN_H (ed->win_h)
#define WS_W (ed->win_w - PALETTE_W - STAGE_W)
#define WS_H (ed->win_h - WS_Y)
#define TAB_W 150
#define PLUS_W 28
/* Menu do botao "+" (nova aba) */
#define PLUS_MENU_W 208
#define PLUS_MENU_ITEM_H 36
/* Editor de codigo (aba de codigo) */
#define CODE_FS 13
#define CODE_GUTTER_W 46
#define CODE_LINE_H 18
#define CODE_PAD_Y 6
#define CODE_PAD_X 8
/* Tipos de aba */
enum { TK_BLOCKS, TK_CODE, TK_IMAGE };
/* Aba de imagem: editor de pintura com camadas (visual estilo Scratch) */
/* Medidas da aba de imagem ficam no modulo (tinyblocks-editor-image);
aqui so o que o estado (Tab) precisa. */
#define IMG_UNDO_MAX 6
#define IMG_MAX_LAYERS 8
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
enum { IMG_L_RASTER = 0, IMG_L_VECTOR };
/* Camada do documento de imagem (rasterizada; SVG entra como vetor) */
typedef struct {
TinyBlocks_Image* img;
TinyBlocks_Image* thumb; /* miniatura do painel "Camadas" */
unsigned thumb_rev;/* revisao em que a miniatura foi feita */
char name[48];
char src[192];
int kind;
int visible;
} ImgLayer;
/* Selecao da ferramenta "selecionar" (mover/redimensionar pixels) */
typedef struct {
int on; /* ha selecao ativa */
TinyBlocks_Image* buf; /* pixels retirados da camada (flutuantes) */
int ox, oy, ow, oh; /* regiao original (ancora do arrasto / tamanho) */
int x, y, w, h; /* retangulo atual */
int mode; /* 0 = nada, 1 = mover, 2 = redimensionar, 3 = novo */
int hnd; /* indice da alca (0..8) */
int px, py; /* ultimo ponto em coords da imagem */
} ImgSel;
enum { IT_SEL = 0, IT_BRUSH, IT_LINE, IT_RECT, IT_ELLIPSE,
IT_FILL, IT_ERASER, IT_PICK, IT_N };
/* Botoes de projeto no menu (geometria) */
#define OPEN_BTN_X 150
#define OPEN_BTN_W 64
#define SAVE_BTN_X 218
#define SAVE_BTN_W 70
#define EXP_BTN_X 296
#define EXP_BTN_W 84
#define LIBM_BTN_X 388
#define LIBM_BTN_W 104
#define LIB_BTN_X 500
#define LIB_BTN_W 200
/* Botao "Config" (settings) ancorado a direita do menu */
#define CFG_BTN_W 78
#define CFG_BTN_X (WIN_W - CFG_BTN_W - 10)
/* Botao de buscar/adicionar library no fim da coluna de categorias */
#define LIBMAN_BTN_H 56
/* == Geometria dos blocos === */
#define FS 12 /* texto dos blocos */
#define FS_UI 13 /* texto da interface */
#define FS_SM 11
#define BLK_GAP 5 /* espaço entre partes do rótulo */
#define BLK_PAD 10
#define ROW_MIN_STACK 36
#define ROW_MIN_REP 24
#define SLOT_MIN_H 20
#define SLOT_MIN_W 28
#define SLOT_LINE_H 15
#define HAT_CAP 18 /* altura do "chapéu" acima da linha do rótulo */
#define HAT_CAP_W 96
#define ARM_W 16 /* braço esquerdo dos blocos C */
#define BOT_H 22 /* braço inferior dos blocos C */
#define MID_H 26 /* braço "senão" */
#define MOUTH_MIN 22
#define NOTCH_X 12 /* encaixe (macho) sob os comandos */
#define NOTCH_W 18
#define NOTCH_D 4
#define PREVIEW_H 64 /* área de on_draw */
#define PREVIEW_W 168
#define SNAP_R 28.f
#define MAX_WS 256
#define MAX_INPUTS 16
#define MAX_PARTS 40
#define MAX_TABS 8
#define MAX_FLY 192
#define MAX_CATS 24
#define MAX_CALL_DEPTH 32
#define MAX_STEPS 500000L
#define MAX_RUN_BLOCKS 200000
#define STAGE_BUF 16384
#define LIT_TEXT_CAP 512
#define MAX_HOT_TYPES 64
#define MAX_USER_BLOCKS 16
#define MAX_UBLK_SLOTS 8
#define MAX_UBLK_PARTS 16
/* ===
* Cores (paleta do Scratch 3) - componentes 0..1
* === */
/* Copia de string com limite (helper compartilhado, sem estado) */
static inline void scopy(char* dst, size_t cap, const char* src) {
if (!dst || !cap) return;
if (!src) { dst[0] = 0; return; }
size_t n = strlen(src);
if (n >= cap) n = cap - 1;
memcpy(dst, src, n);
dst[n] = 0;
}
/* Cores e primitivas de desenho vem da library privada
tinyblocks-editor-widgets (ver tb_editor_widgets.h). Aqui so mantemos os
nomes curtos usados no codigo do editor. */
typedef TbEwColor Col;
#define C(r,g,b) TB_EW_RGB(r,g,b)
#define COLA(r,g,b,a) TB_EW_RGBA(r,g,b,a)
#define col_mul tb_ed_w.col_mul
/* O desenho do editor passa pela library privada widgets. Chamamos pela
tabela (tb_ed_w) para poder recarregar o .so em execucao (hot reload). */
#define rb_fill_rect tb_ed_w.fill_rect
#define rb_fill_rrect tb_ed_w.fill_rrect
#define rb_fill_circle tb_ed_w.fill_circle
#define rb_stroke_rect tb_ed_w.stroke_rect
#define rb_stroke_circle tb_ed_w.stroke_circle
#define rb_line tb_ed_w.line
#define rb_text_c tb_ed_w.text_c
#define tw tb_ed_w.text_width
#define in_rect tb_ed_w.in_rect
static const Col COL_MENU TB_EW_UNUSED = C( 76,151,255); /* #4C97FF */
static const Col COL_MENU_DARK TB_EW_UNUSED = C( 61,121,204);
static const Col COL_UI_BG TB_EW_UNUSED = C(229,240,255); /* #E5F0FF */
static const Col COL_PANEL TB_EW_UNUSED = C(255,255,255);
static const Col COL_FLY TB_EW_UNUSED = C(249,249,249);
static const Col COL_WS_BG TB_EW_UNUSED = C(249,249,249);
static const Col COL_GRID TB_EW_UNUSED = C(221,221,221);
static const Col COL_BORDER TB_EW_UNUSED = C(217,217,217);
static const Col COL_TEXT TB_EW_UNUSED = C( 87, 94,117); /* #575E75 */
static const Col COL_TEXT_DIM TB_EW_UNUSED = C(150,155,175);
static const Col COL_TAB_OFF TB_EW_UNUSED = C(217,227,242);
static const Col COL_HOVER TB_EW_UNUSED = C(214,228,248);
static const Col COL_FLAG TB_EW_UNUSED = C( 76,191, 86); /* #4CBF56 */
static const Col COL_FLAG_DARK TB_EW_UNUSED = C( 69,153, 61);
static const Col COL_STOP TB_EW_UNUSED = C(236, 89, 89); /* #EC5959 */
static const Col COL_STOP_DARK TB_EW_UNUSED = C(184, 60, 60);
static const Col COL_WHITE TB_EW_UNUSED = C(255,255,255);
static const Col COL_MISSING TB_EW_UNUSED = C(170,170,170);
static const Col COL_EXT TB_EW_UNUSED = C( 15,189,140); /* extensões */
static const Col COL_EXT_DARK TB_EW_UNUSED = C( 11,142,105);
static const Col COL_LIBBTN TB_EW_UNUSED = C(255, 76, 76); /* botao de extensoes */
static const Col COL_LIBBTN_DARK TB_EW_UNUSED = C(211, 47, 47);
static const Col COL_VAR TB_EW_UNUSED = C(255,140, 26);
/* Tema escuro do editor de codigo */
static const Col COL_CODE_BG TB_EW_UNUSED = C( 40, 44, 52);
static const Col COL_CODE_GUTTER TB_EW_UNUSED = C( 33, 37, 43);
static const Col COL_CODE_CURLINE TB_EW_UNUSED = C( 51, 57, 67);
static const Col COL_CODE_FOCUS TB_EW_UNUSED = C( 62, 74, 53);
static const Col COL_CODE_BAR TB_EW_UNUSED = C( 33, 37, 43);
static const Col COL_CODE_TEXT TB_EW_UNUSED = C(212, 212, 212);
static const Col COL_TIP_BG TB_EW_UNUSED = C( 37, 37, 38);
static const Col COL_TIP_BORDER TB_EW_UNUSED = C( 69, 69, 69);
static const Col COL_TIP_LINK TB_EW_UNUSED = C( 74,158,255);
static const Col COL_MON_BG TB_EW_UNUSED = C(230,240,255);
static const Col COL_MON_BORDER TB_EW_UNUSED = C(195,204,217);
static const Col COL_ERR_MENU TB_EW_UNUSED = C(255,215,215);
static const Col COL_ERR_TEXT TB_EW_UNUSED = C(204, 60, 60);
/* == Categorias (vêm das libraries; "Meus Blocos" é do editor) === */
static const Col COL_MYBLOCKS_COL TB_EW_UNUSED = C(255,102,128);
static const Col COL_MYBLOCKS_DARK TB_EW_UNUSED = C(255, 51, 85);
#define USER_COLOR_COUNT 8
static const Col s_user_colors[USER_COLOR_COUNT] TB_EW_UNUSED = {
C(255,102,128), C( 76,151,255), C(153,102,255), C(207, 99,207),
C(255,191, 0), C(255,171, 25), C( 89,192, 89), C( 15,189,140),
};
/* == Rótulos dos blocos (%N - campo de entrada N) === */
typedef struct {
const char* type;
const char* label;
const char* defs; /* valores iniciais dos campos, separados por '|' */
} BlockSpec;
static const BlockSpec s_specs[] = {
{"Events.WhenRun", "quando a bandeira for clicado", NULL},
{"Control.Repeat", "repita %1 vezes", "10"},
{"Control.RepeatUntil", "repita até que %1", NULL},
{"Control.If", "se %1 então", NULL},
{"Control.IfElse", "se %1 então", NULL},
{"Operators.Lt", "%1 < %2", "|50"},
{"Operators.Eq", "%1 = %2", "|50"},
{"Operators.Gt", "%1 > %2", "|50"},
{"Operators.And", "%1 e %2", NULL},
{"Operators.Or", "%1 ou %2", NULL},
{"Operators.Not", "não %1", NULL},
{"Operators.Random", "número aleatório entre %1 e %2", "1|10"},
{"Math.Add", "%1 + %2", NULL},
{"Math.Sub", "%1 - %2", NULL},
{"Math.Mul", "%1 * %2", NULL},
{"Math.Div", "%1 / %2", NULL},
{"Math.Mod", "resto de %1 por %2", NULL},
{"Math.Abs", "valor absoluto de %1", NULL},
{"Math.Max", "maior entre %1 e %2", NULL},
{"Math.Min", "menor entre %1 e %2", NULL},
{"Text.Concat", "junte %1 com %2", "maçã|banana"},
{"Text.Length", "tamanho de %1", "maçã"},
{"Literal.Text", "texto %1", NULL},
{"Variables.Set", "mude %1 para %2", "x|0"},
{"Variables.Change", "adicione %2 a %1", "x|1"},
{"Variables.Get", "%1", "x"},
{"IO.Print", "escreva %1 %2", "Olá!|"},
{"IO.PrintInt", "escreva o número %1", NULL},
{"Port.In", "parâmetro %1", "x"},
{"Port.Out", "devolva %1 = %2", "resultado|"},
{"Stage.Clear", "apague tudo", NULL},
{"Stage.Background", "mude o fundo para r %1 g %2 b %3", "255|255|255"},
{"Stage.PenColor", "mude a cor da caneta para r %1 g %2 b %3", "76|151|255"},
{"Stage.PenSize", "mude o tamanho da caneta para %1", "4"},
{"Stage.Line", "desenhe linha de x %1 y %2 até x %3 y %4", "-100|0|100|0"},
{"Stage.Rect", "desenhe retângulo em x %1 y %2 largura %3 altura %4", "0|0|120|80"},
{"Stage.Circle", "desenhe círculo em x %1 y %2 raio %3", "0|0|50"},
{"Stage.ImageByName", "desenhe imagem nome %1 em x %2 y %3", "|0|0"},
{"Stage.ImageByNumber", "desenhe imagem número %1 em x %2 y %3", "1|0|0"},
{"Stage.Text", "escreva %1 no palco em x %2 y %3", "Olá!|-40|0"},
/* Curvas (lista de pontos [x,y]) */
{"Curves.Line", "reta de x %1 y %2 até x %3 y %4 com %5 passos", "0|0|100|0|20"},
{"Curves.Bezier", "bezier de x %1 y %2 controles (%3,%4) (%5,%6) até x %7 y %8 com %9 passos", "0|0|0|80|100|80|100|0|20"},
{"Curves.Quadratic", "curva quadrática de x %1 y %2 controle (%3,%4) até x %5 y %6 com %7 passos", "0|0|50|80|100|0|20"},
{"Curves.Arc", "arco em (%1,%2) raio %3 de %4 a %5 graus com %6 passos", "0|0|50|0|180|24"},
{"Curves.Circle", "círculo em (%1,%2) raio %3 com %4 passos", "0|0|50|36"},
{"Curves.Count", "quantos pontos em %1", NULL},
{"Curves.PointX", "x do ponto %2 de %1", "|0"},
{"Curves.PointY", "y do ponto %2 de %1", "|0"},
/* Base64 */
{"Base64.Encode", "codifique em base64 %1", NULL},
{"Base64.Decode", "decodifique base64 %1", NULL},
/* Imagens PPM (tipo imagem do core) */
{"PPM.Load", "carregue a imagem %1", "imagem.ppm"},
{"PPM.Save", "grave a imagem %1 em %2", "|saida.ppm"},
{"PPM.New", "nova imagem(%1 x %2) cor r %3 g %4 b %5", "32|32|255|0|0"},
{"PPM.Width", "largura de %1", NULL},
{"PPM.Height", "altura de %1", NULL},
{"PPM.SetPixel", "pinte %1 em (%2,%3) de r %4 g %5 b %6", "|0|0|0|0|0"},
{"PPM.GetPixel", "cor de %1 em (%2,%3)", "|0|0"},
{"BMP.Load", "carregue o BMP %1", "imagem.bmp"},
{"BMP.Save", "grave o BMP %1 em %2", "|saida.bmp"},
{"PNG.Load", "carregue o PNG %1", "imagem.png"},
{"PNG.Save", "grave o PNG %1 em %2", "|saida.png"},
/* Imagem (ops genericas) */
{"Image.New", "nova imagem(%1 x %2) cor r %3 g %4 b %5", "32|32|255|0|0"},
{"Image.Width", "largura da imagem %1", NULL},
{"Image.Height", "altura da imagem %1", NULL},
{"Image.GetPixel", "cor da imagem %1 em (%2,%3)", "|0|0"},
{"Image.SetPixel", "pinte a imagem %1 em (%2,%3) com r %4 g %5 b %6", "|0|0|0|0|0"},
{"Image.Fill", "preencha a imagem %1 com r %2 g %3 b %4", "|255|255|255"},
{"Image.Clone", "copie a imagem %1", NULL},
{"Image.Crop", "recorte da imagem %1 em (%2,%3) tamanho %4 x %5", "|0|0|16|16"},
{"Image.Scale", "escale a imagem %1 para %2 x %3", "|64|64"},
{"Image.Load", "carregue a imagem %1", "imagem.png"},
{"Image.Save", "grave a imagem %1 em %2", "|saida.png"},
/* Vetor (vg) */
{"VG.New", "novo desenho vetorial", NULL},
{"VG.Line", "linha do vetor %1 de (%2,%3) a (%4,%5) cor r %6 g %7 b %8 esp %9", "|0|0|50|50|0|0|0|2"},
{"VG.Rect", "retangulo no vetor %1 em (%2,%3) %4 x %5 cor r %6 g %7 b %8", "|0|0|40|40|255|0|0"},
{"VG.Circle", "circulo no vetor %1 em (%2,%3) raio %4 cor r %5 g %6 b %7", "|20|20|15|0|0|255"},
{"VG.Polygon", "poligono no vetor %1 pontos %2 fechar %3 cor r %4 g %5 b %6", "||1|0|255|0"},
{"VG.Render", "rasterize o vetor %1 em %2 x %3 escala %4", "|64|64|1"},
/* SVG */
{"SVG.Parse", "interprete o SVG %1", NULL},
{"SVG.Render", "desenhe o SVG %1 em %2 x %3", "|64|64"},
{"SVG.Load", "carregue o SVG %1", "desenho.svg"},
};
/* ===
* Estruturas de dados
* === */
typedef enum { SH_STACK, SH_HAT, SH_C1, SH_C2, SH_REPORTER, SH_BOOL } Shape;
/* Relação de um bloco com o pai */
#define REL_NONE (-1)
#define REL_NEXT 0
#define REL_SUB0 1 /* REL_SUB0 + k: boca k de um bloco C */
#define REL_ARG0 3 /* REL_ARG0 + i: campo de entrada i */
typedef struct {
int16_t arg; /* -1 = texto; senão índice do campo */
int16_t len;
const char* txt;
float x, w;
} Part;
typedef struct {
bool used;
bool dragging;
TinyBlocks_TypeBlock* type;
char type_name[64];
float x, y; /* posição (só para o topo de uma pilha) */
int parent, prel;
int next;
int sub[2];
int args[MAX_INPUTS];
char in_text[MAX_INPUTS][64];
char lit_text[LIT_TEXT_CAP];
/* layout - recalculado a cada frame */
float ax, ay, w, h;
float row_y, row_h, prev_y;
float sub_y[2], sub_h[2];
float slot_x[MAX_INPUTS], slot_y[MAX_INPUTS], slot_w[MAX_INPUTS], slot_h[MAX_INPUTS];
int part_n;
Part parts[MAX_PARTS];
TinyBlocks_Block* live_rt; /* última instância no runtime (não-owning) */
} EdBlock;
/* Um trecho colorido do editor de codigo (vindo do tinyblocks-syntax). */
typedef struct { int line; char* text; char color[12]; } CodeTok;
typedef struct Tab {
EdBlock ws[MAX_WS];
int top[MAX_WS]; /* pilhas de topo, em ordem de desenho */
int top_n;
float ws_sx, ws_sy;
char name[48];
bool is_composite;
int comp_id;
int color_idx;
int kind; /* TK_BLOCKS, TK_CODE, TK_IMAGE */
/* -- aba de codigo -- */
char* code_text;
int code_len, code_cap;
int code_caret; /* posicao do cursor (offset em bytes) */
int code_scroll; /* primeira linha visivel (0-based) */
int code_focus; /* linha destacada (1-based), -1 = nenhuma */
char code_path[256];
char code_lang[16];
char* code_hl; /* XML do realce (cache) */
CodeTok* code_toks;
int code_tok_n;
bool code_hl_dirty;
/* -- aba de imagem: documento com camadas -- */
ImgLayer img_layers[IMG_MAX_LAYERS];
int img_layer_n;
int img_layer_cur;
int img_w, img_h; /* tamanho do documento em pixels */
char img_path[256]; /* arquivo do documento (salvar) */
int img_tool; /* IT_* */
int img_rgb[3]; /* cor atual (0..255) */
int img_swatch; /* paleta selecionada; -1 = cor propria */
float img_hue, img_sat, img_val; /* HSV da cor atual (roda de cor) */
int img_cdrag; /* arrasto na roda: 0=nada 1=matiz 2=SV */
float img_zoom; /* escala de exibicao (1.0 = 1:1) */
float img_pan_x; /* deslocamento da pagina (zoom no cursor) */
float img_pan_y;
int img_drag; /* traco em andamento */
int img_drag_x, img_drag_y;
TinyBlocks_Image* img_undo[IMG_UNDO_MAX];
int img_undo_layer[IMG_UNDO_MAX];
int img_undo_n;
TinyBlocks_Image* img_prev; /* miniatura (cache) */
unsigned img_prev_rev;
unsigned img_rev; /* muda a cada alteracao do documento */
ImgSel img_sel;
} Tab;
typedef enum { PARAM_NUM, PARAM_BOOL, PARAM_LABEL } ParamKind;
typedef struct { ParamKind kind; char name[32]; } UserParam;
typedef struct {
char name[48];
int input_count, output_count;
char input_names[MAX_UBLK_SLOTS][32];
char output_names[MAX_UBLK_SLOTS][32];
UserParam parts[MAX_UBLK_PARTS]; /* protótipo: entradas, booleanas e rótulos */
int part_n;
Tab* snap; /* cópia da aba no momento do "Salvar" */
TinyBlocks_TypeBlock* reg_type;
int tab_idx;
int color_idx;
} UserBlockDef;
typedef struct {
UserBlockDef* def;
TinyBlocks_Value in[MAX_UBLK_SLOTS];
TinyBlocks_Value out[MAX_UBLK_SLOTS];
} CallFrame;
typedef struct { char name[32]; char prefix[32]; Col col, dark; float fly_y;
const TinyBlocks_LibraryBlock* lib; } Cat;
typedef enum { FI_HEADER, FI_BUTTON, FI_BLOCK } FlyKind;
typedef struct { FlyKind kind; int cat; int bi; float y, h; } FlyItem;
typedef enum { ES_IDLE, ES_PRESS, ES_DRAG, ES_PAN } EdSt;
typedef enum { SN_NONE, SN_NEXT, SN_SUB, SN_ABOVE, SN_ARG } SnapKind;
enum { CM_DUPLICATE, CM_DELETE, CM_EDIT_DEF, CM_CLEANUP, CM_NEW_COMPOSITE,
CM_EXP_JSON, CM_EXP_XML, CM_EXP_CSV };
/* Modos da barra de caminho do menu (path_input) */
enum { PM_NONE, PM_LIB, PM_LOAD, PM_SAVE, PM_EXP_JSON, PM_EXP_XML, PM_EXP_CSV,
PM_IMGLOAD, PM_IMSAVE, PM_IMADDR, PM_IMADDV, PM_CODELOAD, PM_CODESAVE };
/* Explorador de arquivos (library privada tinyblocks-editor-files).
O estado vive aqui para sobreviver ao hot reload do modulo. */
#define FD_PLACES 8
typedef struct {
char name[256];
int is_dir; /* 0 = arquivo, 1 = pasta, 2 = ".." (pasta pai) */
long long size;
long long mtime;
} FileEnt;
typedef struct {
bool open;
int mode; /* PM_* a executar ao confirmar */
bool save; /* dialogo de salvar (pede substituir) */
bool confirm; /* "ja existe, substituir?" visivel */
bool all_files; /* ignora o filtro de extensoes */
bool show_hidden;
char dir[1024]; /* pasta atual (lembrada entre aberturas) */
char name[256]; /* campo "Nome" */
char def_name[256]; /* nome sugerido (volta apos entrar numa pasta) */
char filter[96]; /* ".json .xml" - vazio = todos */
char title[64];
char ok_label[24];
char err[192];
FileEnt* ents; /* listagem (alocada pelo modulo) */
int n, cap;
int sel, scroll;
int last_click_i;
unsigned last_click_ms;
char place_path[FD_PLACES][512];
char place_label[FD_PLACES][40];
int place_n;
} FileDlg;
/* Formatos de exportacao */
enum { EX_JSON, EX_XML, EX_CSV };
typedef struct Ed {
TinyBlocks* rt;
Cat cats[MAX_CATS];
int cat_n;
int myblocks_cat; /* índice da categoria "Meus Blocos" */
Tab fly; /* blocos-modelo do flyout */
FlyItem fly_items[MAX_FLY];
int fly_n;
float fly_scroll, fly_total_h;
Tab tabs[MAX_TABS];
int tab_n;
int cur_tab;
UserBlockDef user_blocks[MAX_USER_BLOCKS];
int user_block_n;
char comp_name_buf[48];
int comp_name_len;
/* Diálogo modal "Criar um Bloco" (estilo Scratch) */
bool comp_dialog_open;
int comp_dialog_def; /* -1 = novo; senão índice em user_blocks */
bool comp_dialog_editing; /* true = edição de nome/rótulo em andamento */
int comp_dialog_edit_part; /* índice da parte em edição, -1 = nome do bloco */
char comp_dialog_name[48];
UserParam comp_dialog_parts[MAX_UBLK_PARTS];
int comp_dialog_part_n;
int comp_dialog_sel; /* parte selecionada (-1 = nenhuma) */
int comp_dialog_color;
float comp_dialog_geom[MAX_UBLK_PARTS][2]; /* x,w desenhados (para hit test) */
float comp_dialog_name_x, comp_dialog_name_w;
bool ctx_menu_open;
bool ctx_export; /* menu de contexto aberto e o de exportacao */
int ctx_menu_bi;
int ctx_menu_x, ctx_menu_y;
int ctx_menu_hover;
int ctx_items[8];
int ctx_n;
EdSt state;
int press_bi;
float press_mx, press_my;
int drag_bi;
float drag_ox, drag_oy;
SnapKind snap_kind;
int snap_bi, snap_idx;
float pan_mx, pan_my, pan_sx, pan_sy;
bool editing;
int edit_bi, edit_in;
int bubble_bi;
char bubble_text[128];
TinyBlocks_JsonValue* bubble_json; /* lista de pontos (retida) ou NULL */
TinyBlocks_Image* bubble_img; /* imagem (retida) ou NULL */
int last_click_bi;
unsigned last_click_ms;
char stage_buf[STAGE_BUF];
/* Execução */
CallFrame frames[MAX_CALL_DEPTH];
int frame_n;
long steps;
bool abort;
char abort_msg[160];
TinyBlocks_Block** run_blocks; /* instâncias criadas na última execução */
int run_n, run_cap;
Tab* live_tab;
FILE* cap_file;
int cap_saved;
float mouse_x, mouse_y;
bool flag_hover, stop_hover, lib_hover, detach_hover;
/* Palco: embutido no painel ou numa janela própria (Graphics.Window) */
TinyBlocks_Block* stage;
TinyBlocks_Block* stage_win;
TinyBlocks_Block* stage_in;
bool clip_on;
float clip[4];
TbEdModules mods; /* libraries privadas (bundle) por dlopen */
int hot_check_frame; /* contador para checar hot reload */
char hot_status[256];
bool hot_status_ok;
bool path_input_active;
char path_input_buf[512];
int path_input_len;
int path_mode; /* PM_* - o que fazer no Enter */
FileDlg fdlg; /* explorador de arquivos (Abrir/Salvar) */
/* Gestor de libraries (tinyblocks-libman); a UI e desenhada aqui */
bool libman_open;
char libman_query[128];
int libman_query_len;
bool libman_search_focus;
int libman_filter; /* -1 = Tudo; senao indice em libman_cats */
char libman_cats[MAX_CATS][48];
int libman_cat_n;
int libman_scroll;
int libman_hover;
/* Configuracoes (settings) - store da tinyblocks-environ */
bool settings_open;
int settings_sel; /* linha selecionada (-1 = nenhuma) */
bool settings_path_focus; /* campo de caminho do CSV em foco */
bool settings_use_env; /* caminho vindo de TINYBLOCKS_SETTINGS */
bool settings_value_edit; /* editando o valor da linha sel. */
bool settings_new_key; /* digitando o nome de uma nova chave */
char settings_path[256];
char settings_edit[256]; /* buffer do valor em edicao */
char settings_key[64]; /* buffer da nova chave */
int settings_scroll;
int settings_hover;
/* Menu do botao "+" (nova aba) */
bool plus_menu_open;
int plus_menu_hover;
float plus_menu_x, plus_menu_y;
/* Tooltip de metadados do bloco (Alt + hover) */
bool tip_open;
int tip_bi;
float tip_x, tip_y, tip_w, tip_h;
float tip_prev_y, tip_prev_h; /* area clicavel (previa do codigo) */
char tip_title[256]; /* assinatura da funcao */
char tip_loc[320]; /* arquivo:linha */
char tip_doc[256];
char tip_file[256]; /* arquivo resolvivel */
int tip_line;
char tip_preview[768];
float img_mx, img_my; /* ultimo ponto do traco (aba de imagem) */
int win_w, win_h;
} Ed;
#define CT (ed->tabs[ed->cur_tab])
/* Ponteiro global para o editor ativo - os eval_fn dos blocos do editor
* (variáveis, compostos, portas) só recebem (self, rt). */
static Ed* g_active_ed TB_EW_UNUSED = NULL;
void bubble_clear(Ed* ed);
void palette_rebuild(Ed* ed);
void utf8_pop(char* s);
void append_text(char* dst, size_t cap, const char* add);
void dlg_open(Ed* ed, int def_idx);
void dlg_render(Ed* ed, TinyBlocks_RenderableBlock* rb);
bool dlg_click(Ed* ed, float mx, float my);
void dlg_key(Ed* ed, int sc);
void dlg_text(Ed* ed, const char* typed);
/* Gestor de libraries (tinyblocks-libman) - UI desenhada pelo editor */
void libman_show(Ed* ed);
void libman_click(Ed* ed, float mx, float my);
void libman_key(Ed* ed, int sc);
void libman_text(Ed* ed, const char* typed);
void libman_scroll_by(Ed* ed, float dy);
void libman_render(Ed* ed, TinyBlocks_RenderableBlock* rb);
bool hit_libman_foot(Ed* ed, float mx, float my);
/* Abas de codigo/imagem + tooltip de metadados */
bool tab_new_kind(Ed* ed, const char* name, bool is_composite, int kind);
void tab_doc_free(Tab* T);
void code_rehighlight(Tab* T);
void open_code_at(Ed* ed, const char* file, int line);
void render_code_tab(Ed* ed, TinyBlocks_RenderableBlock* rb);
void render_tooltip(Ed* ed, TinyBlocks_RenderableBlock* rb);
void render_plus_menu(Ed* ed, TinyBlocks_RenderableBlock* rb);
bool code_click(Ed* ed, float mx, float my);
bool code_key(Ed* ed, int sc, bool ctrl);
bool code_text(Ed* ed, const char* typed);
/* Recorte (clip) do desenho - vive no editor, usado tambem pela aba de imagem.
TB_ED_API: precisa ser visivel para os modulos carregados por dlopen. */
TB_ED_API void clip_set(Ed* ed, TinyBlocks_RenderableBlock* rb, float x, float y, float w, float h);
TB_ED_API void clip_clear(Ed* ed, TinyBlocks_RenderableBlock* rb);
TB_ED_API void clip_restore(Ed* ed, TinyBlocks_RenderableBlock* rb);
TB_ED_API void start_path(Ed* ed, int mode, const char* def);
/* Executa a acao do modo PM_* sobre o caminho escolhido (barra ou explorador) */
TB_ED_API void path_commit(Ed* ed, int mode, const char* path);
/* Aba de imagem: library privada carregada por dlopen (hot reload).
As chamadas passam pela tabela tb_ed_img, entao trocar o .so em execucao
ja muda o comportamento - sem reiniciar o editor.
Quando compilando o proprio modulo, usa os nomes reais. */
#ifdef TB_EDITOR_IMAGE_BUILD
# define render_image_tab tb_editor_image_view
# define image_click tb_editor_image_click
# define image_drag tb_editor_image_drag
# define image_release tb_editor_image_release
# define img_load_file tb_editor_image_load_file
# define img_save_out tb_editor_image_save
# define img_ensure tb_editor_image_ensure
# define img_sel_reset tb_editor_image_sel_reset
# define img_sel_commit tb_editor_image_sel_commit
# define image_zoom tb_editor_image_zoom
#else
# define render_image_tab tb_ed_img.view
# define image_click tb_ed_img.click
# define image_drag tb_ed_img.drag
# define image_release tb_ed_img.release
# define img_load_file tb_ed_img.load_file
# define img_save_out tb_ed_img.save
# define img_ensure tb_ed_img.ensure
# define img_sel_reset tb_ed_img.sel_reset
# define img_sel_commit tb_ed_img.sel_commit
# define image_zoom tb_ed_img.zoom
#endif
/* Explorador de arquivos: library privada carregada por dlopen */
#ifdef TB_EDITOR_FILES_BUILD
# define files_open tb_editor_files_open
# define files_close tb_editor_files_close
# define files_view tb_editor_files_view
# define files_click tb_editor_files_click
# define files_key tb_editor_files_key
# define files_text tb_editor_files_text
# define files_scroll tb_editor_files_scroll
#else
# define files_open tb_ed_files.open
# define files_close tb_ed_files.close
# define files_view tb_ed_files.view
# define files_click tb_ed_files.click
# define files_key tb_ed_files.key
# define files_text tb_ed_files.text
# define files_scroll tb_ed_files.scroll
#endif
/* Configuracoes (settings) - UI desenhada pelo editor */
void settings_show(Ed* ed);
void settings_click(Ed* ed, float mx, float my);
void settings_key(Ed* ed, int sc, bool ctrl);
void settings_text(Ed* ed, const char* typed);
void settings_scroll_by(Ed* ed, float dy);
void settings_render(Ed* ed, TinyBlocks_RenderableBlock* rb);
#endif /* TB_EDITOR_INTERNAL_H */