Files
tinyblocks/libraries/tinyblocks-editor/src/tb_editor.c
T
mguinhosandClaude Opus 5.5 d85dd1b624 Bloco "sempre" e execução quadro a quadro (threads estilo Scratch 3)
- tinyblocks-control: Control.Forever ("sempre"), um bloco-tampa: sem
  encaixe embaixo e uma pilha que termina nele só encaixa no fim.
- Bandeira e clique numa pilha criam threads com pilha explícita
  (sequência / repita / repita até / sempre). Laços pausam no fim de cada
  volta; a cada quadro o editor avança as threads até todas pausarem, a
  caneta pedir redesenho ou passar o tempo do quadro: contas terminam na
  hora, desenhos animam. Botão vermelho para tudo; a bandeira fica acesa
  enquanto algo roda. Laço sem fim não é mais abortado por limite de
  passos (dentro de Meus Blocos continua síncrono, com limite).
- Árvores do runtime em cache por (aba, bloco, profundidade de chamada),
  reavaliadas a cada volta: "sempre" não acumula blocos; editar com o
  programa rodando invalida o cache.
- stdout capturado por quadro.
- Harness: laço sem fim não trava e para no botão vermelho; "sempre"
  anima uma volta por quadro.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 13:10:42 -03:00

4854 lines
189 KiB
C

/*
* TinyBlocks - tb_editor.c
* Editor visual no estilo Scratch, implementado como TypeBlock "Editor.Scene".
*
* Não abre janela nem conhece backend: implementa on_draw (produzindo um
* 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <unistd.h>
#include <dlfcn.h>
#include <sys/stat.h>
#include <time.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_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);
}
#include "../internal/tb_editor_internal.h"
/* Perninha (triangulo) do balao de previa, apontando para baixo.
* bottom = linha de baixo da borda do balao. */
static void rb_bubble_tail(TinyBlocks_RenderableBlock* rb, float cx, float bottom, Col fill) {
for (int k = 0; k < 6; k++) {
float hw = 4.0f * (1.0f - (float)k / 6.0f);
rb_fill_rect(rb, cx - hw, bottom + k, hw * 2.0f, 1.0f, COL_BORDER);
}
for (int k = 0; k < 5; k++) {
float hw = 2.6f * (1.0f - (float)k / 5.0f);
rb_fill_rect(rb, cx - hw, bottom - 1 + k, hw * 2.0f, 1.0f, fill);
}
}
/* Largura real do texto, medida pelo backend gráfico */
/* Texto centralizado verticalmente em cy */
TB_ED_API void clip_set(Ed* ed, TinyBlocks_RenderableBlock* rb, float x, float y, float w, float h) {
ed->clip_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);
}
TB_ED_API void clip_clear(Ed* ed, TinyBlocks_RenderableBlock* rb) {
ed->clip_on = false;
tb_draw_clear_clip(rb);
}
TB_ED_API void clip_restore(Ed* ed, TinyBlocks_RenderableBlock* rb) {
if (ed->clip_on) tb_draw_set_clip(rb, ed->clip[0], ed->clip[1], ed->clip[2], ed->clip[3]);
else tb_draw_clear_clip(rb);
}
/* 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: {
char* js = v->as.json ? tb_json_stringify(v->as.json) : NULL;
snprintf(buf, cap, "%s", js ? js : "[json]");
free(js);
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 ||
strcmp(n, "Control.Forever") == 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;
/* Convencao para as libraries: uma unica saida cujo nome termina em '?'
(ex.: "é pasta?") e um bloco booleano. */
if (t->output_desc_count == 1 && t->output_descs && t->output_descs[0].name) {
const char* on = t->output_descs[0].name;
size_t ol = strlen(on);
if (ol > 0 && on[ol - 1] == '?') 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; }
/* Bloco "tampa" (como o "sempre" do Scratch): nada encaixa embaixo dele */
static bool is_cap(const TinyBlocks_TypeBlock* t) {
return t && t->type_name && strcmp(t->type_name, "Control.Forever") == 0;
}
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) && !is_cap(b->type)) 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 (e para os scripts) */
static void run_reset(Ed* ed) {
ed->vm_n = 0;
ed->vm_running = false;
ed->rt_cache_n = 0;
memset(ed->rt_cache, 0, sizeof(ed->rt_cache));
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;
}
/* Esquece as arvores em cache (sem destrui-las: continuam em run_blocks).
Chamado quando o usuario edita algo, para a edicao valer no programa
que esta rodando. */
static void rt_cache_clear(Ed* ed) {
if (!ed->rt_cache_n) return;
ed->rt_cache_n = 0;
memset(ed->rt_cache, 0, sizeof(ed->rt_cache));
}
/* Marca a arvore inteira como "suja" para ser reavaliada */
static void rt_mark_dirty(TinyBlocks_Block* r, int depth) {
if (!r || depth > 64) return;
r->dirty = true;
for (uint32_t i = 0; i < r->input_count; i++)
if (r->inputs[i].source) rt_mark_dirty(r->inputs[i].source, depth + 1);
}
/* Arvore do runtime do bloco bi: montada na primeira vez e reaproveitada
depois (chave: aba, bloco e profundidade de chamada de Meus Blocos, para
uma recursao nao reusar uma arvore que ainda esta sendo avaliada). */
static TinyBlocks_Block* get_rt(Ed* ed, Tab* T, int bi) {
int depth = ed->frame_n;
uintptr_t h = ((uintptr_t)T >> 4) * 31u + (uintptr_t)bi * 131u + (uintptr_t)depth * 7u;
for (int k = 0; k < RT_CACHE_CAP; k++) {
RtCacheEnt* e = &ed->rt_cache[(h + (uintptr_t)k) % RT_CACHE_CAP];
if (!e->r) {
TinyBlocks_Block* r = build_rt(ed, T, bi);
/* deixa folga na tabela; cheia, so nao guarda */
if (r && ed->rt_cache_n < RT_CACHE_CAP * 3 / 4) {
e->T = T; e->bi = bi; e->depth = depth; e->r = r;
ed->rt_cache_n++;
}
return r;
}
if (e->T == T && e->bi == bi && e->depth == depth) {
rt_mark_dirty(e->r, 0);
return e->r;
}
}
return build_rt(ed, T, bi);
}
/* 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 = get_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.Forever") == 0) {
/* dentro de Meus Blocos roda sem pausar: so o limite de passos para */
while (step(ed)) 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 = get_rt(ed, T, bi);
if (r) tb_block_eval(r, ed->rt);
}
}
}
/* == Threads (scripts rodando quadro a quadro, estilo Scratch 3) ===
* Cada script e uma pilha explicita de VmFrame. Um laco pausa no fim de
* cada volta; vm_frame avanca as threads varias vezes no mesmo quadro ate
* todas pausarem/terminarem, um bloco do palco pedir redesenho ou acabar o
* tempo do quadro. Assim contas terminam na hora e desenhos animam. */
#define VM_FRAME_MS 12u
static unsigned now_ms(void);
static void vm_push(Ed* ed, VmThread* th, Tab* T, int bi, int kind, long long n) {
if (th->sp >= VM_STACK) { run_abort(ed, "blocos aninhados demais"); return; }
VmFrame* f = &th->st[th->sp++];
f->T = T; f->bi = bi; f->kind = kind; f->n = n; f->in_iter = false;
}
static void vm_start(Ed* ed, Tab* T, int head) {
if (ed->vm_n >= VM_THREADS) return;
VmThread* th = &ed->vm[ed->vm_n++];
th->sp = 0;
vm_push(ed, th, T, head, VF_CHAIN, 0);
ed->vm_running = true;
}
/* Executa a thread ate a proxima pausa (true) ou ate terminar (false) */
static bool vm_step(Ed* ed, VmThread* th) {
while (th->sp > 0 && !ed->abort) {
VmFrame* f = &th->st[th->sp - 1];
Tab* T = f->T;
if (f->kind != VF_CHAIN) {
EdBlock* L = &T->ws[f->bi];
if (!L->used) { th->sp--; continue; } /* laco apagado com o programa rodando */
if (f->in_iter) { f->in_iter = false; return true; } /* fim de uma volta: pausa */
if (f->kind == VF_REPEAT) {
if (f->n <= 0) { th->sp--; continue; }
f->n--;
} else if (f->kind == VF_UNTIL) {
TinyBlocks_Value v = eval_arg(ed, T, f->bi, 0);
bool done = value_truthy(&v);
tb_value_free(&v);
if (done) { th->sp--; continue; }
}
f->in_iter = true;
vm_push(ed, th, T, L->sub[0], VF_CHAIN, 0);
continue;
}
if (f->bi < 0 || !T->ws[f->bi].used) { th->sp--; continue; }
int bi = f->bi;
EdBlock* b = &T->ws[bi];
f->bi = b->next;
if (!step(ed)) break;
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);
if (n > 0) vm_push(ed, th, T, bi, VF_REPEAT, n);
} else if (strcmp(tn, "Control.RepeatUntil") == 0) {
vm_push(ed, th, T, bi, VF_UNTIL, 0);
} else if (strcmp(tn, "Control.Forever") == 0) {
vm_push(ed, th, T, bi, VF_FOREVER, 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) vm_push(ed, th, T, b->sub[0], VF_CHAIN, 0);
else if (sh == SH_C2) vm_push(ed, th, T, b->sub[1], VF_CHAIN, 0);
} else {
TinyBlocks_Block* r = get_rt(ed, T, bi);
if (r) tb_block_eval(r, ed->rt);
if (strncmp(tn, "Stage.", 6) == 0) ed->redraw_req = true; /* caneta: mostra este quadro */
}
}
th->sp = 0;
return false;
}
/* Captura o stdout (blocos "escreva") enquanto os blocos rodam */
static void cap_begin(Ed* ed) {
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; }
}
}
/* Devolve o stdout e manda o que foi escrito (e avisos/erros) ao palco */
static void cap_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->abort_msg[0] = 0;
}
}
/* Início/fim de uma execução: zera o runtime */
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;
ed->vm_var_n = tb_variables_count();
if (clear) ed->stage_buf[0] = 0;
}
static void run_end(Ed* ed) {
ed->vm_running = false;
ed->vm_n = 0;
ed->live_tab = NULL;
palette_rebuild(ed); /* variáveis novas aparecem no flyout */
}
/* Um quadro dos scripts rodando: avanca as threads ate todas pausarem ou
terminarem, a caneta pedir redesenho ou acabar o tempo do quadro. */
static void vm_frame(Ed* ed) {
if (!ed->vm_running) return;
g_active_ed = ed;
cap_begin(ed);
unsigned t0 = now_ms();
ed->redraw_req = false;
ed->steps = 0; /* limite de passos vale por quadro */
bool alive;
do {
alive = false;
for (int i = 0; i < ed->vm_n && !ed->abort; i++)
if (ed->vm[i].sp > 0 && vm_step(ed, &ed->vm[i])) alive = true;
} while (alive && !ed->abort && !ed->redraw_req && now_ms() - t0 < VM_FRAME_MS);
cap_end(ed);
if (!alive || ed->abort) {
run_end(ed);
} else if (tb_variables_count() != ed->vm_var_n) {
ed->vm_var_n = tb_variables_count();
palette_rebuild(ed); /* variavel nova com o programa rodando */
}
}
/* Botao vermelho: para todos os scripts */
static void vm_stop(Ed* ed) {
bool was = ed->vm_running;
run_reset(ed);
if (was) run_end(ed);
}
/* 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; i++) {
EdBlock* b = &CT.ws[heads[i]];
if (blk_type(ed, b) && strcmp(b->type->type_name, "Events.WhenRun") == 0) {
vm_start(ed, &CT, heads[i]);
started++;
}
}
if (!started) {
run_end(ed);
stage_append(ed, "Nenhum script começa com \"quando a bandeira for clicado\".\n");
return;
}
vm_frame(ed); /* primeiro quadro ja: scripts curtos terminam aqui */
}
/* Libera o balão de resultado (texto + eventual lista de pontos) */
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;
ed->bubble_type[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;
}
/* Nome do tipo do valor, para o balão de resultado */
static const char* value_type_name(const TinyBlocks_Value* v) {
switch (v->kind) {
case TB_VALUE_INTEGER: return "número inteiro";
case TB_VALUE_REAL: return "número real";
case TB_VALUE_TEXT: return "texto";
case TB_VALUE_BLOCK: return "bloco";
case TB_VALUE_VECTOR: return "desenho vetorial";
case TB_VALUE_IMAGE: return "imagem";
case TB_VALUE_JSON:
if (!v->as.json) return "JSON";
if (json_is_points(v->as.json)) return "lista de pontos";
switch (tb_json_kind(v->as.json)) {
case TB_JSON_ARRAY: return "lista";
case TB_JSON_OBJECT: return "objeto JSON";
default: return "JSON";
}
default: return "nada";
}
}
/* 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;
scopy(ed->bubble_type, sizeof(ed->bubble_type), value_type_name(v));
/* bloco booleano (hexagonal): verdadeiro/falso, como no Scratch */
if (root >= 0 && shape_of(blk_type(ed, &CT.ws[root])) == SH_BOOL &&
(v->kind == TB_VALUE_INTEGER || v->kind == TB_VALUE_REAL)) {
bool t = v->kind == TB_VALUE_INTEGER ? v->as.integer != 0 : v->as.real != 0.0;
scopy(ed->bubble_type, sizeof(ed->bubble_type), "booleano");
scopy(ed->bubble_text, sizeof(ed->bubble_text), t ? "verdadeiro" : "falso");
return;
}
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)) {
cap_begin(ed);
TinyBlocks_Value v = eval_reporter(ed, &CT, root);
cap_end(ed);
bubble_set(ed, root, &v);
tb_value_free(&v);
run_end(ed);
} else {
vm_start(ed, &CT, root); /* a pilha roda como script (pode ter "sempre") */
vm_frame(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;
}
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);
}
bool tab_new_kind(Ed* ed, const char* name, bool is_composite, int kind) {
if (ed->tab_n >= MAX_TABS) {
snprintf(ed->hot_status, sizeof(ed->hot_status), "Limite de %d abas atingido", MAX_TABS);
ed->hot_status_ok = false;
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;
T->kind = kind;
T->code_focus = -1;
T->img_tool = IT_BRUSH;
T->img_swatch = 2;
T->img_rgb[0] = 230; T->img_rgb[1] = 38; T->img_rgb[2] = 38;
T->img_zoom = 1.f;
T->img_layer_cur = -1;
if (kind == TK_IMAGE) img_ensure(ed, T);
tab_select(ed, idx);
return true;
}
static bool tab_new(Ed* ed, const char* name, bool is_composite) {
return tab_new_kind(ed, name, is_composite, TK_BLOCKS);
}
/* Libera os buffers de documento (codigo/imagem) de uma aba. */
void tab_doc_free(Tab* T) {
if (!T) return;
free(T->code_text); T->code_text = NULL; T->code_len = T->code_cap = 0;
free(T->code_hl); T->code_hl = NULL;
if (T->code_toks) {
for (int i = 0; i < T->code_tok_n; i++) free(T->code_toks[i].text);
free(T->code_toks); T->code_toks = NULL; T->code_tok_n = 0;
}
for (int i = 0; i < T->img_undo_n; i++) tb_image_release(T->img_undo[i]);
T->img_undo_n = 0;
for (int i = 0; i < T->img_layer_n; i++) {
tb_image_release(T->img_layers[i].img);
if (T->img_layers[i].thumb) tb_image_release(T->img_layers[i].thumb);
T->img_layers[i].thumb = NULL;
}
T->img_layer_n = 0;
if (T->img_prev) { tb_image_release(T->img_prev); T->img_prev = NULL; }
img_sel_reset(T);
}
static void tab_close(Ed* ed, int ti) {
if (ed->tab_n <= 1 || ti < 0 || ti >= ed->tab_n) return;
run_reset(ed);
tab_doc_free(&ed->tabs[ti]);
for (int i = ti; i < ed->tab_n - 1; i++) ed->tabs[i] = ed->tabs[i+1];
memset(&ed->tabs[ed->tab_n - 1], 0, sizeof(Tab));
ed->tabs[ed->tab_n - 1].code_focus = -1;
ed->tab_n--;
for (int u = 0; u < ed->user_block_n; u++) {
int* t = &ed->user_blocks[u].tab_idx;
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;
}
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;
}
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);
}
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;
}
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);
}
}
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, delegado ao tinyblocks-api:
* - libraries privadas do editor (bundle): troca as tabelas de ponteiros;
* - libraries de blocos (extensoes): recarrega e revalida os tipos. */
static void hotlib_check(Ed* ed) {
tb_ed_modules_check(ed);
if (!tb_api_any_changed()) return;
invalidate_types(ed); /* nenhum ponteiro de tipo pode sobreviver ao unload */
tb_api_poll_reload();
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);
/* Tipo do valor no topo dos baloes graficos (imagem, lista de pontos) */
static void bubble_type_label(Ed* ed, TinyBlocks_RenderableBlock* rb, float bx, float by) {
if (!ed->bubble_type[0]) return;
rb_text_c(rb, bx + 10, by + 12, ed->bubble_type, COL_TEXT_DIM, 10.f);
}
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) || (ed->fdlg.open && ed->fdlg.mode == PM_LOAD) || hit_open_btn(mx, my));
menu_button(rb, SAVE_BTN_X, SAVE_BTN_W, "Salvar", (active && ed->path_mode == PM_SAVE) || (ed->fdlg.open && ed->fdlg.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]) {
/* cabe entre "Carregar library=" e "Config"; se nao couber, mostra
o fim da mensagem (o fim de um caminho e o que importa) */
float avail = CFG_BTN_X - 12 - (LIB_BTN_X + LIB_BTN_W + 10);
const char* s = ed->hot_status;
char buf[300];
if (avail > 20 && tw(s, FS_SM) > avail) {
while (*s && tw(s, FS_SM) + tw("...", FS_SM) > avail) {
s++;
while ((*s & 0xC0) == 0x80) s++;
}
snprintf(buf, sizeof(buf), "...%s", s);
s = buf;
}
float w = tw(s, FS_SM);
rb_text_c(rb, CFG_BTN_X - 12 - w, MENU_H*0.5f, s,
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;
} else if (ed->tabs[i].kind == TK_CODE) {
rb_fill_rrect(rb, tx+9, cy-6, 11, 13, 2, COLA(42,74,110,255));
rb_fill_rect(rb, tx+11, cy-3, 6, 1.4f, COLA(120,190,255,255));
rb_fill_rect(rb, tx+11, cy+0, 6, 1.4f, COLA(120,190,255,255));
rb_fill_rect(rb, tx+11, cy+3, 4, 1.4f, COLA(120,190,255,255));
lx = tx + 24;
} else if (ed->tabs[i].kind == TK_IMAGE) {
rb_fill_rrect(rb, tx+9, cy-6, 12, 12, 2, COLA(200,150,60,255));
rb_fill_circle(rb, tx+13, cy-2, 2, COLA(255,235,180,255));
lx = tx + 24;
}
rb_text_c(rb, lx, cy, ed->tabs[i].name, cur ? COL_MENU : COL_TEXT, FS_UI);
if (ed->tab_n > 1) rb_text_c(rb, tx+TAB_W-22, cy, "=", COL_TEXT_DIM, FS_UI);
}
float px = 8 + ed->tab_n*TAB_W;
if (px + PLUS_W <= wbar && ed->tab_n < MAX_TABS) {
float pcy = y0 + 6 + (TAB_H-6)*0.5f;
if (ed->plus_menu_open) rb_fill_circle(rb, px+13, pcy, 12, COL_HOVER);
rb_text_c(rb, px+8, pcy, "+", ed->plus_menu_open ? COL_MENU : COL_TEXT, 18);
}
}
static void render_categories(Ed* ed, TinyBlocks_RenderableBlock* rb) {
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));
}
/* ==========================================================================
* Abas de codigo e de imagem + tooltip de metadados de blocos
* ========================================================================== */
static Col col_from_hex(const char* h) {
if (!h || h[0] != '#') return COL_CODE_TEXT;
unsigned long v = strtoul(h + 1, NULL, 16);
return COLA((v >> 16) & 0xff, (v >> 8) & 0xff, v & 0xff, 255);
}
static char* decode_entities(const char* s, int n) {
char* out = (char*)malloc((size_t)n + 1);
if (!out) return NULL;
int k = 0;
for (int i = 0; i < n; ) {
if (s[i] == '&') {
if (!strncmp(s + i, "&amp;", 5)) { out[k++] = '&'; i += 5; continue; }
if (!strncmp(s + i, "&lt;", 4)) { out[k++] = '<'; i += 4; continue; }
if (!strncmp(s + i, "&gt;", 4)) { out[k++] = '>'; i += 4; continue; }
if (!strncmp(s + i, "&quot;", 6)) { out[k++] = '"'; i += 6; continue; }
if (!strncmp(s + i, "&#39;", 5)) { out[k++] = '\''; i += 5; continue; }
}
out[k++] = s[i++];
}
out[k] = 0;
return out;
}
/* -- Buffer de texto da aba de codigo ---------------------------------- */
static bool code_reserve(Tab* T, int extra) {
if (T->code_len + extra + 1 <= T->code_cap) return true;
int cap = T->code_cap ? T->code_cap : 4096;
while (cap < T->code_len + extra + 1) cap *= 2;
char* p = (char*)realloc(T->code_text, (size_t)cap);
if (!p) return false;
T->code_text = p; T->code_cap = cap;
return true;
}
static void code_set_text(Tab* T, const char* s, int n) {
if (!code_reserve(T, n)) return;
if (n > 0 && s) memcpy(T->code_text, s, (size_t)n);
T->code_len = n; T->code_text[n] = 0;
T->code_hl_dirty = true;
}
static bool code_read_file(Tab* T, const char* path) {
FILE* f = fopen(path, "rb");
if (!f) return false;
fseek(f, 0, SEEK_END);
long sz = ftell(f);
fseek(f, 0, SEEK_SET);
if (sz < 0) sz = 0;
if (!code_reserve(T, (int)sz)) { fclose(f); return false; }
size_t rd = fread(T->code_text, 1, (size_t)sz, f);
fclose(f);
T->code_len = (int)rd; T->code_text[T->code_len] = 0;
T->code_hl_dirty = true;
return true;
}
static bool code_write_file(Tab* T, const char* path) {
FILE* f = fopen(path, "wb");
if (!f) return false;
if (T->code_len > 0) fwrite(T->code_text, 1, (size_t)T->code_len, f);
fclose(f);
return true;
}
static int code_line_count(Tab* T) {
if (!T->code_text) return 1;
int n = 1;
for (int i = 0; i < T->code_len; i++) if (T->code_text[i] == '\n') n++;
return n;
}
static void code_line_col(Tab* T, int off, int* line, int* col) {
int ln = 0, cs = 0;
if (off > T->code_len) off = T->code_len;
for (int i = 0; i < off; i++) if (T->code_text[i] == '\n') { ln++; cs = i + 1; }
if (line) *line = ln;
if (col) *col = off - cs;
}
static int code_line_start(Tab* T, int line) {
if (line <= 0) return 0;
int ln = 0;
for (int i = 0; i < T->code_len; i++)
if (T->code_text[i] == '\n') { ln++; if (ln == line) return i + 1; }
return T->code_len;
}
static int code_line_len(Tab* T, int line) {
int s = code_line_start(T, line), e = s;
while (e < T->code_len && T->code_text[e] != '\n') e++;
return e - s;
}
static void code_insert(Tab* T, const char* s, int n) {
if (n <= 0 || !s) return;
if (!code_reserve(T, n)) return;
memmove(T->code_text + T->code_caret + n, T->code_text + T->code_caret,
(size_t)(T->code_len - T->code_caret));
memcpy(T->code_text + T->code_caret, s, (size_t)n);
T->code_len += n; T->code_text[T->code_len] = 0; T->code_caret += n;
T->code_hl_dirty = true;
}
static void code_erase(Tab* T, int from, int to) {
if (from < 0) from = 0;
if (to > T->code_len) to = T->code_len;
if (to <= from) return;
memmove(T->code_text + from, T->code_text + to, (size_t)(T->code_len - to));
T->code_len -= (to - from); T->code_text[T->code_len] = 0;
if (T->code_caret > from) {
T->code_caret -= (to - from);
if (T->code_caret < from) T->code_caret = from;
}
T->code_hl_dirty = true;
}
static int code_prev_char(Tab* T, int off) {
if (off <= 0) return 0;
off--;
while (off > 0 && ((unsigned char)T->code_text[off] & 0xC0) == 0x80) off--;
return off;
}
static int code_next_char(Tab* T, int off) {
if (off >= T->code_len) return T->code_len;
off++;
while (off < T->code_len && ((unsigned char)T->code_text[off] & 0xC0) == 0x80) off++;
return off;
}
static void code_toks_free(Tab* T) {
for (int i = 0; i < T->code_tok_n; i++) free(T->code_toks[i].text);
free(T->code_toks); T->code_toks = NULL; T->code_tok_n = 0;
}
/* Realca o texto (via tinyblocks-syntax) e extrai os trechos coloridos. */
void code_rehighlight(Tab* T) {
code_toks_free(T);
free(T->code_hl); T->code_hl = NULL;
T->code_hl_dirty = false;
if (!T->code_text) return;
T->code_hl = tb_syntax_highlight(T->code_text, T->code_lang);
if (!T->code_hl) return;
int cap = 128, n = 0;
CodeTok* v = (CodeTok*)malloc(sizeof(CodeTok) * (size_t)cap);
if (!v) return;
const char* p = T->code_hl;
int line = -1;
int pend_start = -1;
/* emite o texto "solto" (fora de <t>) preservando indentacao */
#define FLUSH_PEND() do { \
if (pend_start >= 0) { \
int plen = (int)(p - T->code_hl) - pend_start; \
if (plen > 0 && line >= 0) { \
char* txt = decode_entities(T->code_hl + pend_start, plen); \
if (txt) { \
int wl = (int)strlen(txt); \
while (wl > 0 && (txt[wl-1] == '\n' || txt[wl-1] == '\r')) txt[--wl] = 0; \
if (wl > 0) { \
if (n == cap) { cap *= 2; v = (CodeTok*)realloc(v, sizeof(CodeTok) * (size_t)cap); } \
v[n].line = line; \
snprintf(v[n].color, sizeof(v[n].color), "#d4d4d4"); \
v[n].text = txt; n++; \
} else free(txt); \
} \
} \
pend_start = -1; \
} \
} while (0)
while (*p) {
if (*p == '<') {
if (!strncmp(p, "<line>", 6)) { FLUSH_PEND(); p += 6; line++; continue; }
if (!strncmp(p, "</line>", 7)) { FLUSH_PEND(); p += 7; continue; }
if (!strncmp(p, "<t ", 3)) {
FLUSH_PEND();
const char* gt = strchr(p, '>');
if (!gt) break;
char col[12] = "#d4d4d4";
const char* c = strstr(p, "color=\"");
if (c && c < gt) {
c += 7; size_t k = 0;
while (*c && *c != '"' && k < sizeof(col) - 1) col[k++] = *c++;
col[k] = 0;
}
const char* e = strstr(gt + 1, "</t>");
if (!e) break;
char* txt = decode_entities(gt + 1, (int)(e - (gt + 1)));
if (txt) {
if (n == cap) { cap *= 2; v = (CodeTok*)realloc(v, sizeof(CodeTok) * (size_t)cap); }
v[n].line = line < 0 ? 0 : line;
snprintf(v[n].color, sizeof(v[n].color), "%s", col);
v[n].text = txt; n++;
}
p = e + 4; continue;
}
if (!strncmp(p, "</t>", 4)) { p += 4; continue; }
if (!strncmp(p, "<code", 5)) {
const char* gt = strchr(p, '>');
p = gt ? gt + 1 : p + 5;
continue;
}
p++; continue;
}
if (pend_start < 0) pend_start = (int)(p - T->code_hl);
p++;
}
FLUSH_PEND();
#undef FLUSH_PEND
T->code_toks = v; T->code_tok_n = n;
}
/* Rola para deixar `line` (1-based) visivel. */
static void code_scroll_to(Ed* ed, Tab* T, int line) {
int view = (int)((WS_H - CODE_PAD_Y * 2) / CODE_LINE_H);
if (view < 1) view = 1;
int ln = line - 1;
if (ln < T->code_scroll) T->code_scroll = ln;
if (ln > T->code_scroll + view - 3) T->code_scroll = ln - view + 3;
if (T->code_scroll < 0) T->code_scroll = 0;
(void)ed;
}
void open_code_at(Ed* ed, const char* file, int line) {
char path[1200];
if (!tb_meta_resolve_file(file, path, sizeof(path))) {
snprintf(ed->hot_status, sizeof(ed->hot_status), "Nao encontrei o arquivo-fonte: %.200s", file);
ed->hot_status_ok = false;
return;
}
for (int i = 0; i < ed->tab_n; i++) {
if (ed->tabs[i].kind == TK_CODE && !strcmp(ed->tabs[i].code_path, path)) {
tab_select(ed, i);
if (line > 0) { CT.code_focus = line; code_scroll_to(ed, &CT, line); }
return;
}
}
if (ed->tab_n >= MAX_TABS) {
snprintf(ed->hot_status, sizeof(ed->hot_status), "Limite de %d abas atingido", MAX_TABS);
ed->hot_status_ok = false;
return;
}
int idx = ed->tab_n;
if (!tab_new_kind(ed, NULL, false, TK_CODE)) return;
Tab* T = &ed->tabs[idx];
scopy(T->code_path, sizeof(T->code_path), path);
const char* base = strrchr(path, '/'); base = base ? base + 1 : path;
scopy(T->name, sizeof(T->name), base);
scopy(T->code_lang, sizeof(T->code_lang), tb_syntax_normalize_lang(path));
if (!code_read_file(T, path)) {
snprintf(ed->hot_status, sizeof(ed->hot_status), "Nao consegui abrir %.200s", path);
ed->hot_status_ok = false;
}
T->code_caret = 0; T->code_scroll = 0; T->code_hl_dirty = true;
T->code_focus = line > 0 ? line : -1;
if (line > 0) code_scroll_to(ed, T, line);
}
/* -- Render da aba de codigo ------------------------------------------- */
void render_code_tab(Ed* ed, TinyBlocks_RenderableBlock* rb) {
Tab* T = &CT;
const float x0 = WS_X, y0 = WS_Y;
const float w = WS_W, h = WS_H;
rb_fill_rect(rb, x0, y0, w, h, COL_CODE_BG);
/* barra superior (arquivo / linguagem / salvar) */
const float barh = 30;
rb_fill_rect(rb, x0, y0, w, barh, COL_CODE_BAR);
rb_line(rb, x0, y0 + barh, x0 + w, y0 + barh, 1.f, COL_TIP_BORDER);
char title[320];
snprintf(title, sizeof(title), "%s", T->code_path[0] ? T->code_path : (T->name[0] ? T->name : "sem titulo"));
rb_text_c(rb, x0 + 10, y0 + barh * 0.5f, title, COL_CODE_TEXT, FS_UI - 2);
float lw = tw(T->code_lang, FS_UI - 2);
rb_fill_rrect(rb, x0 + w - lw - 26, y0 + 5, lw + 16, 20, 5, COL_TIP_BORDER);
rb_text_c(rb, x0 + w - lw - 18, y0 + barh * 0.5f, T->code_lang, COL_TIP_LINK, FS_UI - 2);
rb_text_c(rb, x0 + w - lw - 26 - 62, y0 + barh * 0.5f, "Salvar", COL_CODE_TEXT, FS_UI - 2);
if (T->code_hl_dirty) code_rehighlight(T);
const int lh = CODE_LINE_H;
const float cy0 = y0 + barh;
const int total = code_line_count(T);
int view = (int)((h - barh) / lh);
if (view < 1) view = 1;
if (T->code_scroll > total - 1) T->code_scroll = total - 1;
if (T->code_scroll < 0) T->code_scroll = 0;
rb_fill_rect(rb, x0, cy0, CODE_GUTTER_W, h - barh, COL_CODE_GUTTER);
rb_line(rb, x0 + CODE_GUTTER_W - 1, cy0, x0 + CODE_GUTTER_W - 1, y0 + h, 1.f, COL_TIP_BORDER);
clip_set(ed, rb, x0, cy0, w, h - barh);
int caret_line = 0, caret_col = 0;
code_line_col(T, T->code_caret, &caret_line, &caret_col);
(void)caret_col;
int ti = 0;
while (ti < T->code_tok_n && T->code_toks[ti].line < T->code_scroll) ti++;
for (int li = T->code_scroll; li < T->code_scroll + view && li < total; li++) {
float ly = cy0 + (li - T->code_scroll) * lh;
if (li == caret_line) rb_fill_rect(rb, x0, ly, w, lh, COL_CODE_CURLINE);
if (T->code_focus == li + 1) rb_fill_rect(rb, x0, ly, w, lh, COL_CODE_FOCUS);
char nb[16]; snprintf(nb, sizeof(nb), "%d", li + 1);
float nw = tw(nb, 11);
rb_text_c(rb, x0 + CODE_GUTTER_W - 8 - nw, ly + lh * 0.5f, nb, COL_TEXT_DIM, 11);
float tx = x0 + CODE_GUTTER_W + CODE_PAD_X;
while (ti < T->code_tok_n && T->code_toks[ti].line == li) {
Col c = col_from_hex(T->code_toks[ti].color);
rb_text_c(rb, tx, ly + lh * 0.5f, T->code_toks[ti].text, c, CODE_FS);
tx += tw(T->code_toks[ti].text, CODE_FS);
ti++;
}
/* cursor (barra vertical) */
if (li == caret_line && ed->state == ES_IDLE) {
int ls = code_line_start(T, li);
char tmp[1024];
int cl = T->code_caret - ls;
if (cl > 0) {
if (cl > (int)sizeof(tmp) - 1) cl = (int)sizeof(tmp) - 1;
memcpy(tmp, T->code_text + ls, (size_t)cl);
while (cl > 0 && tmp[cl-1] == '\n') cl--;
tmp[cl] = 0;
rb_fill_rect(rb, x0 + CODE_GUTTER_W + CODE_PAD_X + tw(tmp, CODE_FS), ly + 2, 1.6f, lh - 4, COL_WHITE);
} else {
rb_fill_rect(rb, x0 + CODE_GUTTER_W + CODE_PAD_X, ly + 2, 1.6f, lh - 4, COL_WHITE);
}
}
}
clip_clear(ed, rb);
(void)ed;
}
/* -- Entrada (mouse/teclado) da aba de codigo -------------------------- */
bool code_click(Ed* ed, float mx, float my) {
Tab* T = &CT;
const float barh = 30;
if (my < WS_Y + barh) {
float lw = tw(T->code_lang, FS_UI - 2);
if (mx >= WS_X + WS_W - lw - 26) {
/* clica na linguagem: cicla */
int cnt = tb_syntax_language_count();
int cur = -1;
for (int i = 0; i < cnt; i++)
if (!strcmp(tb_syntax_language_name(i), T->code_lang)) cur = i;
snprintf(T->code_lang, sizeof(T->code_lang), "%s", tb_syntax_language_name((cur + 1) % cnt));
T->code_hl_dirty = true;
return true;
}
if (mx >= WS_X + WS_W - lw - 26 - 62)
{ start_path(ed, PM_CODESAVE, T->code_path[0] ? T->code_path : "arquivo.c"); return true; }
return true;
}
if (T->code_hl_dirty) code_rehighlight(T);
int li = T->code_scroll + (int)((my - (WS_Y + barh)) / CODE_LINE_H);
int total = code_line_count(T);
if (li < 0) li = 0;
if (li >= total) li = total - 1;
int ls = code_line_start(T, li);
int ll = code_line_len(T, li);
float cx = WS_X + CODE_GUTTER_W + CODE_PAD_X;
int col = 0;
char tmp[1024];
while (col < ll && cx + tw("M", CODE_FS) * 0.5f < mx) {
int step = 1;
if (col + step > ll) break;
int n2 = col + step > (int)sizeof(tmp) - 1 ? (int)sizeof(tmp) - 1 - col : step;
memcpy(tmp, T->code_text + ls + col, (size_t)n2);
tmp[n2] = 0;
cx += tw(tmp, CODE_FS);
col += n2;
}
T->code_caret = ls + col;
T->code_focus = -1;
return true;
}
bool code_key(Ed* ed, int sc, bool ctrl) {
Tab* T = &CT;
if (sc == TB_KEY_ESCAPE) { T->code_focus = -1; bubble_clear(ed); return true; }
if (ctrl) {
if (sc == (TB_KEY_A + ('s' - 'a'))) {
start_path(ed, PM_CODESAVE, T->code_path[0] ? T->code_path : "arquivo.c");
return true;
}
if (sc == (TB_KEY_A + ('o' - 'a'))) { start_path(ed, PM_CODELOAD, "arquivo.c"); return true; }
return false;
}
if (sc == TB_KEY_RETURN) {
int l2 = 0; code_line_col(T, T->code_caret, &l2, NULL);
int ls = code_line_start(T, l2);
int indent = 0;
while (ls + indent < T->code_len && (T->code_text[ls+indent] == ' ' || T->code_text[ls+indent] == '\t')) indent++;
code_insert(T, "\n", 1);
for (int i = 0; i < indent; i++) code_insert(T, " ", 1);
return true;
}
if (sc == TB_KEY_BACKSPACE) {
if (T->code_caret > 0) code_erase(T, code_prev_char(T, T->code_caret), T->code_caret);
return true;
}
if (sc == TB_KEY_DELETE) {
if (T->code_caret < T->code_len) code_erase(T, T->code_caret, code_next_char(T, T->code_caret));
return true;
}
if (sc == TB_KEY_TAB) {
code_insert(T, " ", 4);
return true;
}
{ int l2 = 0, c2 = 0; code_line_col(T, T->code_caret, &l2, &c2);
if (sc == TB_KEY_LEFT) { T->code_caret = code_prev_char(T, T->code_caret); T->code_focus = -1; return true; }
if (sc == TB_KEY_RIGHT) { T->code_caret = code_next_char(T, T->code_caret); T->code_focus = -1; return true; }
if (sc == TB_KEY_HOME) { T->code_caret -= c2; T->code_focus = -1; return true; }
if (sc == TB_KEY_END) { T->code_caret += (code_line_len(T, l2) - c2); T->code_focus = -1; return true; }
if (sc == TB_KEY_UP) { if (l2 > 0) { int p = code_line_len(T, l2-1); T->code_caret = code_line_start(T, l2-1) + (c2 < p ? c2 : p); } T->code_focus = -1; return true; }
if (sc == TB_KEY_DOWN) { if (l2 < code_line_count(T)-1) { int p = code_line_len(T, l2+1); T->code_caret = code_line_start(T, l2+1) + (c2 < p ? c2 : p); } T->code_focus = -1; return true; }
}
return false;
}
bool code_text(Ed* ed, const char* typed) {
(void)ed;
code_insert(&CT, typed, (int)strlen(typed));
return true;
}
/* A aba de imagem vive em libraries/tinyblocks-editor-image (bundle do editor). */
/* -- Menu do botao "+" -------------------------------------------------- */
static void plus_menu_pos(Ed* ed, float* px, float* py) {
*px = 8 + ed->tab_n * TAB_W;
*py = MENU_H + TAB_H - 2;
}
void render_plus_menu(Ed* ed, TinyBlocks_RenderableBlock* rb) {
if (!ed->plus_menu_open) return;
float px, py;
plus_menu_pos(ed, &px, &py);
const int n = 3;
float h = 26 + n * PLUS_MENU_ITEM_H + 6;
rb_fill_rrect(rb, px - 2, py + 2, PLUS_MENU_W + 4, h + 4, 10, COLA(0,0,0,40));
rb_fill_rrect(rb, px, py, PLUS_MENU_W, h, 8, COL_PANEL);
rb_stroke_rect(rb, px, py, PLUS_MENU_W, h, 1.f, COL_BORDER);
rb_text_c(rb, px + 12, py + 13, "Nova aba", COL_TEXT_DIM, 11.f);
const char* labels[3] = { "Blueprint", "Edicao de Imagem", "Editor de Codigo" };
const char* subs[3] = { "montar um bloco novo", "editar SVG/imagem", "editar .c/.py/..." };
static const Col dots[3] = {{0.30f,0.62f,1.f,1.f}, {0.98f,0.62f,0.25f,1.f}, {0.42f,0.72f,0.35f,1.f}};
for (int i = 0; i < n; i++) {
float iy = py + 26 + i * PLUS_MENU_ITEM_H;
bool hov = ed->plus_menu_hover == i;
if (hov) rb_fill_rrect(rb, px + 4, iy, PLUS_MENU_W - 8, PLUS_MENU_ITEM_H - 2, 6, COL_HOVER);
rb_fill_circle(rb, px + 20, iy + PLUS_MENU_ITEM_H * 0.5f - 1, 6, dots[i]);
rb_text_c(rb, px + 36, iy + 12, labels[i], COL_TEXT, FS_UI - 1);
rb_text_c(rb, px + 36, iy + 25, subs[i], COL_TEXT_DIM, 10.f);
}
}
/* -- Tooltip de metadados (Alt + hover) --------------------------------- */
void render_tooltip(Ed* ed, TinyBlocks_RenderableBlock* rb) {
if (!ed->tip_open) return;
float x = ed->tip_x, y = ed->tip_y, w = ed->tip_w, h = ed->tip_h;
rb_fill_rrect(rb, x + 2, y + 3, w, h, 6, COLA(0,0,0,60));
rb_fill_rrect(rb, x, y, w, h, 5, COL_TIP_BG);
rb_stroke_rect(rb, x, y, w, h, 1.f, COL_TIP_BORDER);
float ty = y + 12;
rb_text_c(rb, x + 12, ty, ed->tip_title, COL_CODE_TEXT, 12.f);
ty += 18;
rb_text_c(rb, x + 12, ty, ed->tip_loc, COL_TIP_LINK, 11.f);
ty += 16;
if (ed->tip_doc[0]) {
rb_text_c(rb, x + 12, ty, ed->tip_doc, COL_TEXT_DIM, 11.f);
ty += 16;
}
/* previa do codigo (clicavel) */
ed->tip_prev_y = ty + 2;
rb_fill_rect(rb, x + 6, ed->tip_prev_y - 2, w - 12, ed->tip_prev_h + 4, COLA(0,0,0,45));
float ly = ed->tip_prev_y;
const char* p = ed->tip_preview;
char line[256];
int ln = 1;
while (*p && ln <= 8) {
const char* nl = strchr(p, '\n');
size_t n = nl ? (size_t)(nl - p) : strlen(p);
if (n > sizeof(line) - 1) n = sizeof(line) - 1;
memcpy(line, p, n); line[n] = 0;
char pre[16];
snprintf(pre, sizeof(pre), "%d", ed->tip_line + ln - 1);
rb_text_c(rb, x + 12, ly, pre, COL_TEXT_DIM, 10.f);
rb_text_c(rb, x + 12 + 30, ly, line, COL_CODE_TEXT, 11.f);
ly += 14;
ln++;
if (!nl) break;
p = nl + 1;
}
rb_text_c(rb, x + 12, y + h - 8, "clique para abrir o codigo nesta linha", COL_TEXT_DIM, 9.f);
}
static void render_workspace(Ed* ed, TinyBlocks_RenderableBlock* rb) {
if (CT.kind == TK_CODE) { render_code_tab(ed, rb); return; }
if (CT.kind == TK_IMAGE) { render_image_tab(ed, rb); return; }
float ox = WS_X - CT.ws_sx, oy = WS_Y - CT.ws_sy;
rb_fill_rect(rb, WS_X, WS_Y, WS_W, WS_H, COL_WS_BG);
clip_set(ed, rb, WS_X, WS_Y, WS_W, WS_H);
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 = 174, PAD = 10, HEAD = 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_bubble_tail(rb, bx + 22, by + BH - 1, COL_WHITE);
bubble_type_label(ed, rb, bx, by);
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 - HEAD;
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 + HEAD + (BH-HEAD-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 = 154, PAD = 16, HEAD = 14;
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_bubble_tail(rb, bx + 22, by + BH - 1, COL_WHITE);
bubble_type_label(ed, rb, bx, by);
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 - HEAD;
float sc = (float)((aw/spanx < ah/spany) ? aw/spanx : ah/spany);
float gx = bx + PAD + (aw - (float)spanx*sc)*0.5f;
float gy = by + HEAD + 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 {
/* tipo (pequeno, em cima) + valor */
float w = fmaxf(tw(ed->bubble_text, FS), tw(ed->bubble_type, 10.f)) + 20;
float bx = b->ax + ox + 8, by = b->ay + oy - 44;
rb_fill_rrect(rb, bx, by, w, 38, 8, COL_BORDER);
rb_fill_rrect(rb, bx+1, by+1, w-2, 36, 7, COL_WHITE);
rb_bubble_tail(rb, bx + 16, by + 37, COL_WHITE);
rb_text_c(rb, bx + 10, by + 11, ed->bubble_type, COL_TEXT_DIM, 10.f);
rb_text_c(rb, bx + 10, by + 26, 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 || ed->vm_running) 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;
}
bool hit_libman_foot(Ed* ed, float mx, float my) {
return mx < CAT_W && my >= WIN_H - LIBMAN_BTN_H;
}
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;
}
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);
}
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;
}
}
}
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);
}
}
}
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);
}
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));
}
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;
}
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);
}
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;
}
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;
}
}
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);
}
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);
/* pilha que termina numa "tampa" (sempre) so encaixa onde nada vem depois */
int last = ed->drag_bi;
while (T->ws[last].next >= 0) last = T->ws[last].next;
bool drag_cap = is_cap(T->ws[last].type);
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) {
if (!is_cap(B->type) && !(drag_cap && B->next >= 0))
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++)
if (!(drag_cap && B->sub[k] >= 0))
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 && !drag_cap)
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
* === */
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;
}
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); }
TB_ED_API void start_path(Ed* ed, int mode, const char* def) {
/* Explorador de arquivos (tinyblocks-editor-files); sem o modulo, cai
na barra de caminho do menu. */
if (files_open) {
ed->path_input_active = false;
ed->path_mode = PM_NONE;
files_open(ed, mode, def);
return;
}
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->fdlg.open) { if (files_click) files_click(ed, mx, my); return; }
if (ed->plus_menu_open) {
float px, py;
plus_menu_pos(ed, &px, &py);
int hit = -1;
for (int i = 0; i < 3; i++)
if (in_rect(mx, my, px, py + 26 + i * PLUS_MENU_ITEM_H, PLUS_MENU_W, PLUS_MENU_ITEM_H)) hit = i;
ed->plus_menu_open = false;
if (hit == 0) { dlg_open(ed, -1); return; }
if (hit == 1) { tab_new_kind(ed, "Imagem", false, TK_IMAGE); palette_rebuild(ed); return; }
if (hit == 2) {
tab_new_kind(ed, "Sem titulo", false, TK_CODE);
snprintf(CT.code_lang, sizeof(CT.code_lang), "c");
code_set_text(&CT, "", 0);
CT.code_hl_dirty = true;
palette_rebuild(ed);
return;
}
}
if (ed->tip_open) {
if (in_rect(mx, my, ed->tip_x, ed->tip_y, ed->tip_w, ed->tip_h)) {
open_code_at(ed, ed->tip_file, ed->tip_line);
ed->tip_open = false;
return;
}
ed->tip_open = false;
}
if (ed->ctx_menu_open) {
int it = ctx_hit(ed, mx, my);
ed->ctx_menu_open = false;
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)) { vm_stop(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)) ed->plus_menu_open = !ed->plus_menu_open;
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;
}
/* Abas de codigo / imagem */
if (mx >= WS_X && mx < WIN_W - STAGE_W && my >= WS_Y) {
if (CT.kind == TK_CODE) { ed->editing = false; code_click(ed, mx, my); return; }
if (CT.kind == TK_IMAGE) { image_click(ed, mx, my); return; }
}
/* Workspace */
float wx = mx - WS_X + CT.ws_sx, wy = my - WS_Y + CT.ws_sy;
int bi = hit_ws(&CT, wx, wy);
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) {
if (ed->comp_dialog_open || ed->fdlg.open) return;
rt_cache_clear(ed); /* soltar/encaixar muda o programa que esta rodando */
if (CT.kind == TK_IMAGE && CT.img_drag) { image_release(ed, mx, my); ed->state = ES_IDLE; return; }
if (ed->state == ES_DRAG && ed->drag_bi >= 0) {
mark_drag(&CT, ed->drag_bi, false);
if (mx < PALETTE_W) free_tree(ed, &CT, ed->drag_bi); /* solto na paleta = apagar */
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->fdlg.open) return;
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;
}
/* Executa a acao do modo PM_* sobre o caminho escolhido (barra de caminho
do menu ou explorador de arquivos). */
TB_ED_API void path_commit(Ed* ed, int mode, const char* p) {
if (!p || !p[0]) return;
switch (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;
case PM_IMGLOAD: if (CT.kind == TK_IMAGE) img_load_file(ed, p, -1); break;
case PM_IMSAVE: if (CT.kind == TK_IMAGE) img_save_out(ed, p); break;
case PM_IMADDR: if (CT.kind == TK_IMAGE) img_load_file(ed, p, IMG_L_RASTER); break;
case PM_IMADDV: if (CT.kind == TK_IMAGE) img_load_file(ed, p, IMG_L_VECTOR); break;
case PM_CODELOAD: {
if (CT.kind == TK_CODE) {
scopy(CT.code_path, sizeof(CT.code_path), p);
const char* b = strrchr(p, '/'); b = b ? b + 1 : p;
scopy(CT.name, sizeof(CT.name), b);
scopy(CT.code_lang, sizeof(CT.code_lang), tb_syntax_normalize_lang(p));
if (!code_read_file(&CT, p)) {
snprintf(ed->hot_status, sizeof(ed->hot_status), "Nao consegui abrir %.200s", p);
ed->hot_status_ok = false;
}
CT.code_hl_dirty = true;
}
break;
}
case PM_CODESAVE: if (CT.kind == TK_CODE) { code_write_file(&CT, p); snprintf(ed->hot_status, sizeof(ed->hot_status), "Salvo: %.200s", p); ed->hot_status_ok = true; } break;
default: hotlib_load(ed, p); break;
}
}
static void on_key(Ed* ed, int sc, bool ctrl) {
bool enter = sc == TB_KEY_RETURN;
rt_cache_clear(ed);
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->fdlg.open) { if (files_key) files_key(ed, sc, ctrl); else ed->fdlg.open = false; 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) {
int mode = ed->path_mode;
ed->path_input_active = false;
ed->path_mode = PM_NONE;
if (ed->path_input_buf[0]) path_commit(ed, mode, ed->path_input_buf);
} else if (sc == TB_KEY_BACKSPACE) {
utf8_pop(ed->path_input_buf);
ed->path_input_len = (int)strlen(ed->path_input_buf);
}
return;
}
if (CT.kind == TK_IMAGE && CT.img_sel.on) {
if (sc == TB_KEY_DELETE || sc == TB_KEY_BACKSPACE) {
img_sel_reset(&CT);
CT.img_rev++;
snprintf(ed->hot_status, sizeof(ed->hot_status), "Selecao apagada");
ed->hot_status_ok = true;
return;
}
if (sc == TB_KEY_ESCAPE) { img_sel_commit(&CT); return; }
}
if (CT.kind == TK_CODE && code_key(ed, sc, ctrl)) return;
if (ed->editing) {
size_t cap; char* t = edit_target(ed, &cap);
bool multi = is_lit_text(CT.ws[ed->edit_bi].type);
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) {
rt_cache_clear(ed);
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->fdlg.open) { if (files_text) files_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 (CT.kind == TK_CODE) {
code_text(ed, typed);
} else if (ed->editing) {
size_t cap; char* t = edit_target(ed, &cap);
append_text(t, cap, typed);
}
}
/* ===
* Tooltip de metadados: Alt + hover sobre um bloco da area de scripts
* === */
static void update_tooltip(Ed* ed, bool alt) {
if (ed->tip_open) {
/* mantem aberto enquanto o mouse estiver sobre o tooltip ... */
if (in_rect(ed->mouse_x, ed->mouse_y, ed->tip_x, ed->tip_y, ed->tip_w, ed->tip_h)) return;
/* ... ou sobre o proprio bloco de origem (permite soltar o Alt e clicar) */
if (CT.kind == TK_BLOCKS && ed->tip_bi >= 0 && ed->tip_bi < MAX_WS && CT.ws[ed->tip_bi].used) {
int hb = hit_ws(&CT, ed->mouse_x - WS_X + CT.ws_sx, ed->mouse_y - WS_Y + CT.ws_sy);
if (hb == ed->tip_bi) return;
}
}
ed->tip_open = false;
if (!alt) return;
if (CT.kind != TK_BLOCKS) return;
if (ed->state != ES_IDLE) return;
float mx = ed->mouse_x, my = ed->mouse_y;
if (mx < WS_X || mx >= WIN_W - STAGE_W || my < WS_Y) return;
int bi = hit_ws(&CT, mx - WS_X + CT.ws_sx, my - WS_Y + CT.ws_sy);
if (bi < 0) return;
EdBlock* b = &CT.ws[bi];
const TinyBlocks_BlockMeta* m = tb_meta_find(b->type_name);
if (!m) return;
int line = tb_meta_line(m);
if (line < 1) line = 1;
char path[1200];
path[0] = 0;
tb_meta_resolve_file(m->file, path, sizeof(path));
snprintf(ed->tip_loc, sizeof(ed->tip_loc), "%.280s:%d",
path[0] ? path : (m->file ? m->file : "?"), line);
scopy(ed->tip_doc, sizeof(ed->tip_doc), m->doc ? m->doc : "");
scopy(ed->tip_file, sizeof(ed->tip_file), m->file ? m->file : "");
scopy(ed->tip_title, sizeof(ed->tip_title), m->func_name ? m->func_name : "?");
ed->tip_preview[0] = 0;
ed->tip_line = line;
char buf[900];
int got = tb_meta_read_lines(m, line, 8, buf, sizeof(buf));
if (got > 0) {
const char* nl = strchr(buf, '\n');
size_t t = nl ? (size_t)(nl - buf) : strlen(buf);
while (t > 0 && (buf[t-1] == ' ' || buf[t-1] == '\t')) t--;
const char* st = buf;
while (st < buf + t && (*st == ' ' || *st == '\t')) st++;
snprintf(ed->tip_title, sizeof(ed->tip_title), "%.*s", (int)(t - (size_t)(st - buf)), st);
if (nl) scopy(ed->tip_preview, sizeof(ed->tip_preview), nl + 1);
}
int prev_lines = 0;
if (ed->tip_preview[0]) {
prev_lines = 1;
for (const char* p = ed->tip_preview; *p; p++) if (*p == '\n') prev_lines++;
}
ed->tip_w = 600;
ed->tip_prev_h = (float)(prev_lines * 14 + 8);
ed->tip_h = 12 + 18 + 16 + (ed->tip_doc[0] ? 16.f : 0.f)
+ 2 + ed->tip_prev_h + 16;
float bx = WS_X - CT.ws_sx + b->ax + b->w + 14;
float by = WS_Y - CT.ws_sy + b->ay - 6;
if (bx + ed->tip_w > WIN_W - 8) bx = WIN_W - ed->tip_w - 8;
if (bx < WS_X + 4) bx = WS_X + 4;
if (by + ed->tip_h > WIN_H - 8) by = WIN_H - ed->tip_h - 8;
if (by < WS_Y + 4) by = WS_Y + 4;
ed->tip_x = bx; ed->tip_y = by;
ed->tip_bi = bi;
ed->tip_open = true;
}
/* ===
* editor_eval - lê um snapshot de Graphics.Input por frame e atualiza o estado
* === */
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;
ed->plus_menu_hover = -1;
if (ed->plus_menu_open) {
float px, py;
plus_menu_pos(ed, &px, &py);
for (int i = 0; i < 3; i++)
if (in_rect(mx, my, px, py + 26 + i * PLUS_MENU_ITEM_H, PLUS_MENU_W, PLUS_MENU_ITEM_H))
ed->plus_menu_hover = i;
}
update_tooltip(ed, (ev_int(evb, GFX_IN_MOD_STATE) & TB_MOD_ALT) != 0);
/* == Movimento === */
if (ed->state == ES_PRESS && fabsf(mx - ed->press_mx) + fabsf(my - ed->press_my) > 4.f)
start_drag(ed);
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);
}
if (CT.kind == TK_IMAGE && CT.img_drag && (mx != ed->img_mx || my != ed->img_my))
image_drag(ed, mx, my);
/* == Scroll === */
double sdx = ev_real(evb, GFX_IN_SCROLL_DX);
double sdy = ev_real(evb, GFX_IN_SCROLL_DY);
if (sdx != 0.0 || sdy != 0.0) {
if (ed->fdlg.open) {
if (files_scroll) files_scroll(ed, (float)sdy);
} else if (ed->settings_open) {
settings_scroll_by(ed, (float)sdy);
} else if (ed->libman_open) {
libman_scroll_by(ed, (float)sdy);
} else if (CT.kind == TK_CODE && mx >= WS_X && mx < WIN_W - STAGE_W && my >= WS_Y) {
CT.code_scroll -= (int)sdy * 3;
if (CT.code_scroll < 0) CT.code_scroll = 0;
} else if (CT.kind == TK_IMAGE && mx >= WS_X && mx < WIN_W - STAGE_W && my >= WS_Y) {
/* roda do mouse na aba de imagem = zoom no cursor (nao pinta) */
image_zoom(ed, mx, my, (int)(sdy > 0 ? 1 : sdy < 0 ? -1 : 0));
} else if (mx >= WS_X && mx < WIN_W - STAGE_W && my >= WS_Y) {
CT.ws_sx -= (float)sdx * 40.f;
CT.ws_sy -= (float)sdy * 40.f;
} 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);
vm_frame(ed); /* scripts rodando (sempre / repita) avancam um quadro */
/* Hot reload: checa os .so a cada ~30 frames (~0,5 s).
Usa o watcher (inotify) do tinyblocks-api; mtime como reserva. */
if (++ed->hot_check_frame >= 30) {
ed->hot_check_frame = 0;
hotlib_check(ed);
}
}
/* ===
* 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_plus_menu(ed, rb);
render_tooltip(ed, rb);
render_ctx_menu(ed, rb);
dlg_render(ed, rb);
if (ed->fdlg.open && files_view) files_view(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;
(void)0;
*(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);
/* Libraries privadas do editor (bundle) por dlopen ANTES de qualquer
desenho: as primitivas (tb_ed_w) vem daqui. Permite hot reload. */
ed->mods.n = 0;
tb_ed_modules_load(ed);
if (ed->mods.info[0] && !ed->mods.loaded) {
snprintf(ed->hot_status, sizeof(ed->hot_status), "%s", ed->mods.info);
ed->hot_status_ok = false;
}
palette_rebuild(ed);
tb_libman_init(rt); /* liga tinyblocks-api e adota as libs embutidas */
tb_libman_scan_defaults(); /* procura library.toml em libraries/ e ~/.tinyblocks */
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);
for (int i = 0; i < ed->tab_n; i++) tab_doc_free(&ed->tabs[i]);
free(ed->fdlg.ents);
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;
}