Files
tinyblocks/libraries/tinyblocks-editor/src/tb_editor.c
T
mguinhosandClaude Opus 5.5 81f198f189 Headers do editor em include/, com a API privada atrás de um guard
- tb_editor_internal.h e tb_editor_modules.h (antes em internal/) e
  tb_stage_widget.h (antes em src/) foram para
  libraries/tinyblocks-editor/include/.
- Os três são API privada: só compilam com TB_EDITOR_PRIVATE_API (o
  editor, os módulos do bundle e o harness definem); fora disso um
  #error manda incluir tb_editor.h.
- Includes viraram <tb_editor_internal.h> etc.; Makefiles sem -Isrc /
  -Iinternal; library.toml descreve os fontes e o define.

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

6951 lines
276 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 <stddef.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_scratchblocks.h>
#include <strings.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 <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
* === */
/* Texto, numero, verdade e nome do tipo vem das classes de valor do core
(tb_value_to_text, tb_value_as_integer, tb_value_truthy, tb_value_type_name). */
/* 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;
}
/* A forma vem do tipo (a library declara): bloco C = classe de fluxo,
chapeu/booleano = shape ou saida TB_SLOT_BOOLEAN */
static Shape shape_of(const TinyBlocks_TypeBlock* t) {
if (!t) return SH_STACK;
if (t->flow) return t->flow->mouths >= 3 ? SH_C3 : t->flow->mouths == 2 ? SH_C2 : SH_C1;
switch (t->shape) {
case TB_SHAPE_HAT: return SH_HAT;
case TB_SHAPE_STACK: return SH_STACK;
case TB_SHAPE_REPORTER: return SH_REPORTER;
case TB_SHAPE_BOOLEAN: return SH_BOOL;
default: break;
}
if (t->output_desc_count == 1 && (tb_type_block_output_flags(t, 0) & TB_SLOT_BOOLEAN)) 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; }
/* Bocas de um bloco C (0 se nao for C) */
static int shape_mouths(Shape s) { return s == SH_C1 ? 1 : s == SH_C2 ? 2 : s == SH_C3 ? 3 : 0; }
/* Texto da faixa entre a boca k e a k+1 ("senão", "se der erro"...) */
static const char* mouth_label(const TinyBlocks_TypeBlock* t, int k) {
if (!t || !t->flow || k < 0 || k >= TB_FLOW_MAX_MOUTHS - 1) return "";
return t->flow->labels[k] ? t->flow->labels[k] : "";
}
/* Bloco "tampa" (como o "sempre" do Scratch): nada encaixa embaixo dele */
static bool is_cap(const TinyBlocks_TypeBlock* t) {
return t && t->flow && t->flow->cap;
}
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;
}
/* Campo hexagonal (recebe booleano): traco do campo, declarado no tipo */
static bool slot_is_bool(const TinyBlocks_TypeBlock* t, int i) {
return i >= 0 && (tb_type_block_input_flags(t, (uint32_t)i) & TB_SLOT_BOOLEAN);
}
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] = b->sub[2] = -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 < MAX_MOUTHS; 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] = n->sub[2] = -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 < MAX_MOUTHS; 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;
}
#define PART_PROTO (-2) /* prototipo do bloco dentro do chapeu "defina" */
static void add_part(EdBlock* b, int arg, const char* s, int len) {
if (b->part_n >= MAX_PARTS) return;
if (arg == -1) {
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 (t->type_name && strcmp(t->type_name, "Port.Define") == 0) {
/* "defina [prototipo]": o nome (campo 0) nao e editavel aqui */
add_part(b, -1, "defina", 6);
add_part(b, PART_PROTO, NULL, 0);
return;
}
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);
/* == Prototipo dentro do "defina" (como no Scratch) ===
* Um bloco interno com o nome e os parametros do bloco definido; cada
* parametro e um reporter que se arrasta para fora ("parâmetro [x]"). */
#define PROTO_H 30.f
#define PROTO_PAD 8.f
#define PILL_H 22.f
#define PROTO_ITEMS (MAX_UBLK_PARTS + 1)
typedef struct {
int n;
float x[PROTO_ITEMS], w[PROTO_ITEMS];
const char* txt[PROTO_ITEMS];
bool param[PROTO_ITEMS];
} ProtoLayout;
/* Itens do prototipo, x relativo ao comeco do bloco interno */
static void proto_layout(const EdBlock* b, ProtoLayout* L) {
const char* name = b->in_text[0];
UserBlockDef* def = g_active_ed ? user_def_find(g_active_ed, name) : NULL;
float x = PROTO_PAD;
L->n = 0;
L->txt[0] = name[0] ? name : "bloco"; L->param[0] = false;
L->x[0] = x; L->w[0] = tw(L->txt[0], FS); x += L->w[0] + BLK_GAP; L->n = 1;
for (int k = 0; def && k < def->part_n && L->n < PROTO_ITEMS; k++) {
const UserParam* pp = &def->parts[k];
bool par = pp->kind != PARAM_LABEL;
const char* t = pp->name[0] ? pp->name : (par ? "entrada" : "");
if (!t[0]) continue;
int i = L->n++;
L->txt[i] = t; L->param[i] = par; L->x[i] = x;
L->w[i] = tw(t, FS) + (par ? 20.f : 0.f);
x += L->w[i] + BLK_GAP;
}
}
static float proto_measure(const EdBlock* b) {
ProtoLayout L;
proto_layout(b, &L);
return L.x[L.n - 1] + L.w[L.n - 1] + PROTO_PAD;
}
/* Parametro sob (wx, wy) num "defina" ja medido; -1 se nenhum */
static int proto_param_at(const EdBlock* b, float wx, float wy, ProtoLayout* L, float* px, float* py) {
for (int i = 0; i < b->part_n; i++) {
if (b->parts[i].arg != PART_PROTO) continue;
proto_layout(b, L);
float bx = b->ax + b->parts[i].x;
float cy = b->ay + b->row_y + b->row_h * 0.5f;
for (int k = 0; k < L->n; k++) {
if (!L->param[k]) continue;
float x0 = bx + L->x[k], y0 = cy - PILL_H * 0.5f;
if (in_rect(wx, wy, x0, y0, L->w[k], PILL_H)) { *px = x0; *py = y0; return k; }
}
}
return -1;
}
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 == PART_PROTO) {
p->w = proto_measure(b);
if (PROTO_H + 8 > row_h) row_h = PROTO_H + 8;
} else 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: case SH_C3: {
int mouths = shape_mouths(sh);
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 < mouths - 1) 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 < MAX_MOUTHS; 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 (shape_mouths(sh) > 0) {
if (lx < ARM_W || ly < b->row_h || ly >= b->h - BOT_H) return true;
for (int k = 0; k + 1 < shape_mouths(sh); k++) /* faixas do meio */
if (ly >= b->sub_y[k] + b->sub_h[k] && ly < b->sub_y[k + 1]) return true;
return false;
}
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 < MAX_MOUTHS; 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 com o nome de uma variavel (traco TB_SLOT_VARIABLE): desenhado
* laranja (cor da categoria), como no Scratch. */
static bool slot_is_var_name(const TinyBlocks_TypeBlock* t, int s) {
return s >= 0 && (tb_type_block_input_flags(t, (uint32_t)s) & TB_SLOT_VARIABLE);
}
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: case SH_C3: {
float r[5][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" */
{ x, y + b->sub_y[1] + b->sub_h[1], w, MID_H }, /* "finalmente" */
};
int n = 2 + shape_mouths(sh);
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 == PART_PROTO) {
ProtoLayout L;
proto_layout(b, &L);
float px = x + p->x, py = cy - PROTO_H * 0.5f;
rb_fill_rrect(rb, px, py, p->w, PROTO_H, 6, d);
rb_fill_rrect(rb, px + 1, py + 1, p->w - 2, PROTO_H - 2, 5, col_mul(c, 0.92f));
for (int k = 0; k < L.n; k++) {
if (L.param[k]) { /* parametro: reporter arrastavel */
float qx = px + L.x[k], qy = cy - PILL_H * 0.5f;
rb_fill_rrect(rb, qx, qy, L.w[k], PILL_H, PILL_H * 0.5f, d);
rb_fill_rrect(rb, qx + 1, qy + 1, L.w[k] - 2, PILL_H - 2, PILL_H * 0.5f - 1, c);
rb_text_c(rb, qx + 10, cy, L.txt[k], COL_WHITE, FS);
} else {
rb_text_c(rb, px + L.x[k], cy, L.txt[k], COL_WHITE, FS);
}
}
} else 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);
}
for (int k = 0; k + 1 < shape_mouths(sh); k++)
rb_text_c(rb, x + BLK_PAD, y + b->sub_y[k] + b->sub_h[k] + MID_H*0.5f,
mouth_label(b->type, k), COL_WHITE, FS);
/* == Bocas (pilhas internas) === */
int mouths = shape_mouths(sh);
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) {
for (int i = 0; i < ed->vm_n; i++) { tb_vars_scope_free(ed->vm[i].scope); ed->vm[i].scope = NULL; }
tb_vars_scope_set(NULL);
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);
}
/* Erro levantado por um bloco (tinyblocks_set_error) e ainda nao tratado */
static bool err_pending(Ed* ed) {
const char* e = tinyblocks_last_error(ed->rt);
return e && e[0];
}
static void err_take(Ed* ed, char* out, size_t cap) {
snprintf(out, cap, "%s", tinyblocks_last_error(ed->rt));
tinyblocks_clear_error(ed->rt);
}
/* Erro que ninguem tratou: o script para e o palco mostra */
static void err_uncaught(Ed* ed, const char* msg) {
char line[300];
snprintf(line, sizeof(line), "[ERRO] %s\n", msg);
stage_append(ed, line);
}
static bool step(Ed* ed) {
if (++ed->steps > MAX_STEPS) run_abort(ed, "limite de passos atingido (laço infinito?)");
return !ed->abort;
}
/* == Executor (scripts quadro a quadro, estilo Scratch 3) ===
* Cada script e uma pilha explicita de VmFrame. Um bloco C nao e conhecido
* pelo nome: a classe de fluxo dele (TinyBlocks_FlowClass) escolhe a boca a
* rodar, pede pausa (lacos) ou trata um erro que subiu ("tente"). vm_frame
* avanca as threads varias vezes no mesmo quadro ate todas pausarem ou
* terminarem. O corpo de Meus Blocos roda no mesmo executor, sem pausas. */
#define VM_FRAME_MS 12u
static unsigned now_ms(void);
static const TinyBlocks_FlowClass* frame_flow(Ed* ed, VmFrame* f) {
EdBlock* B = &f->T->ws[f->bi];
TinyBlocks_TypeBlock* t = B->used ? blk_type(ed, B) : NULL;
return t ? t->flow : NULL;
}
/* TinyBlocks_Flow.arg: avalia uma entrada do bloco C deste frame */
static TinyBlocks_Value flow_arg(TinyBlocks_Flow* fl, uint32_t slot) {
VmFrame* f = (VmFrame*)((char*)fl - offsetof(VmFrame, flow));
return g_active_ed ? eval_arg(g_active_ed, f->T, f->bi, (int)slot) : tb_value_none();
}
static void vm_push(Ed* ed, VmThread* th, Tab* T, int bi, int kind) {
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;
memset(&f->flow, 0, sizeof(f->flow));
f->flow.rt = ed->rt;
f->flow.arg = flow_arg;
}
/* Um erro na thread: desempilha ate um bloco C cuja classe trate o erro e
entra na boca que ela escolher. false = ninguem tratou (msg = o erro). */
static bool vm_throw(Ed* ed, VmThread* th, char* msg, size_t cap) {
err_take(ed, msg, cap);
while (th->sp > 0) {
VmFrame* f = &th->st[th->sp - 1];
if (f->kind == VF_FLOW) {
const TinyBlocks_FlowClass* fc = frame_flow(ed, f);
int m = fc && fc->error ? fc->error(&f->flow, msg) : TB_FLOW_DONE;
if (m >= 0 && m < fc->mouths) {
vm_push(ed, th, f->T, f->T->ws[f->bi].sub[m], VF_CHAIN);
return true;
}
}
th->sp--;
}
return false;
}
/* Avanca a thread ate a proxima pausa (true) ou ate terminar (false).
sync: roda de uma vez (ignora pausas) e deixa um erro sem tratamento
pendente para quem chamou. */
static bool vm_step(Ed* ed, VmThread* th, bool sync) {
while (th->sp > 0 && !ed->abort) {
if (err_pending(ed)) {
char msg[200];
if (vm_throw(ed, th, msg, sizeof(msg))) continue;
if (sync) tinyblocks_set_error(ed->rt, "%s", msg); /* sobe para quem chamou */
else err_uncaught(ed, msg);
break;
}
VmFrame* f = &th->st[th->sp - 1];
Tab* T = f->T;
if (f->kind == VF_FLOW) { /* bloco C: a classe escolhe */
const TinyBlocks_FlowClass* fc = frame_flow(ed, f);
if (!fc) { th->sp--; continue; } /* apagado com o programa rodando */
if (!step(ed)) break;
int m = fc->next(&f->flow);
if (m == TB_FLOW_YIELD) { if (sync) continue; return true; }
if (m < 0 || m >= fc->mouths) { th->sp--; continue; }
vm_push(ed, th, T, T->ws[f->bi].sub[m], VF_CHAIN);
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;
Shape sh = shape_of(t);
if (sh == SH_HAT || shape_is_value(sh)) continue;
if (t->flow) { vm_push(ed, th, T, bi, VF_FLOW); continue; }
TinyBlocks_Block* r = get_rt(ed, T, bi);
if (r) tb_block_eval(r, ed->rt);
if (t->flags & TB_TYPE_REDRAW) ed->redraw_req = true; /* caneta: mostra este quadro */
}
th->sp = 0;
return false;
}
/* Roda uma pilha de uma vez (corpo de Meus Blocos), no mesmo executor */
static void run_chain(Ed* ed, Tab* T, int head) {
VmThread* th = malloc(sizeof(*th));
if (!th) { run_abort(ed, "sem memória para rodar o bloco"); return; }
th->sp = 0;
th->scope = NULL;
vm_push(ed, th, T, head, VF_CHAIN);
vm_step(ed, th, true);
free(th);
}
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;
th->scope = tb_vars_scope_new(NULL); /* variaveis locais deste script */
vm_push(ed, th, T, head, VF_CHAIN);
ed->vm_running = true;
}
/* 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 define_sync(Ed* ed);
static void run_begin(Ed* ed, bool clear) {
define_sync(ed); /* "devolva" novo no corpo de um "defina" */
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++) {
VmThread* th = &ed->vm[i];
if (th->sp <= 0) continue;
tb_vars_scope_set(th->scope);
if (vm_step(ed, th, false)) alive = true;
else { tb_vars_scope_set(NULL); tb_vars_scope_free(th->scope); th->scope = NULL; }
tb_vars_scope_set(NULL);
}
} 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);
tb_input_timer_reset(); /* como no Scratch: a bandeira zera o cronometro */
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]];
TinyBlocks_TypeBlock* t = blk_type(ed, b);
if (t && t->event && strcmp(t->event, TB_EVENT_FLAG) == 0) { /* chapeus da bandeira */
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. "lista de pontos" é
coisa do editor (desenha os pontos); o resto vem da classe do valor. */
static const char* value_type_name(const TinyBlocks_Value* v) {
if (v->kind == TB_VALUE_JSON && v->as.json && json_is_points(v->as.json)) return "lista de pontos";
return tb_value_type_name(*v);
}
/* 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;
}
tb_value_to_text(*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")
* === */
/* == 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;
}
/* "defina <nome>": so marca onde a definicao comeca */
static void eval_port_define(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt;
self->dirty = false;
}
static void eval_port_in(TinyBlocks_Block* self, TinyBlocks* rt) {
CallFrame* f = cur_frame();
TinyBlocks_Value out = tb_value_none();
if (f) {
const char* label = tb_block_input_text(self, rt, 0);
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) {
const char* label = tb_block_input_text(self, rt, 0);
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;
}
/* == "defina": definicao de Meus Blocos dentro de uma aba comum ===
* Como no Scratch: o chapeu "defina <nome>" fica junto dos outros scripts e o
* corpo e a pilha embaixo dele (sem precisar de uma aba so para o bloco). */
bool tab_has_define(const Tab* T) {
for (int i = 0; i < T->top_n; i++) {
const EdBlock* b = &T->ws[T->top[i]];
if (b->used && strcmp(b->type_name, "Port.Define") == 0) return true;
}
return false;
}
/* Chapeu "defina <nome>" em alguma aba (indice; *tab = aba) ou -1 */
static int define_find(Ed* ed, const char* name, int* tab) {
for (int t = 0; t < ed->tab_n; t++) {
Tab* T = &ed->tabs[t];
if (!tab_class(T)->blocks) continue;
for (int i = 0; i < T->top_n; i++) {
EdBlock* b = &T->ws[T->top[i]];
if (b->used && strcmp(b->type_name, "Port.Define") == 0 && strcmp(b->in_text[0], name) == 0) {
*tab = t;
return T->top[i];
}
}
}
return -1;
}
/* Nomes dos "devolva" na pilha (com os corpos de repita/se) */
static void define_outputs(Tab* T, int bi, char names[][32], int* n) {
for (; bi >= 0 && *n < MAX_UBLK_SLOTS; bi = T->ws[bi].next) {
EdBlock* b = &T->ws[bi];
if (strcmp(b->type_name, "Port.Out") == 0) {
char lbl[32];
snprintf(lbl, sizeof(lbl), "%.31s", b->in_text[0][0] ? b->in_text[0] : "resultado");
bool dup = false;
for (int k = 0; k < *n; k++) if (!strcmp(names[k], lbl)) dup = true;
if (!dup) strcpy(names[(*n)++], lbl);
}
define_outputs(T, b->sub[0], names, n);
define_outputs(T, b->sub[1], names, n);
define_outputs(T, b->sub[2], names, n);
}
}
static void comp_make_type(Ed* ed, UserBlockDef* def);
/* Mantem o tipo de cada bloco definido por "defina" de acordo com os
"devolva" do corpo (um "devolva" novo transforma o bloco em reporter).
Nao mexe durante a execucao. */
static void define_sync(Ed* ed) {
if (ed->vm_running) return;
for (int t = 0; t < ed->tab_n; t++) {
Tab* T = &ed->tabs[t];
if (!tab_class(T)->blocks) continue;
for (int i = 0; i < T->top_n; i++) {
EdBlock* b = &T->ws[T->top[i]];
if (!b->used || strcmp(b->type_name, "Port.Define") != 0 || !b->in_text[0][0]) continue;
if (user_def_find(ed, b->in_text[0]) || ed->user_block_n >= MAX_USER_BLOCKS) continue;
UserBlockDef* def = &ed->user_blocks[ed->user_block_n++];
memset(def, 0, sizeof(*def));
def->tab_idx = -1;
snprintf(def->name, sizeof(def->name), "%.47s", b->in_text[0]);
}
}
for (int u = 0; u < ed->user_block_n; u++) {
UserBlockDef* def = &ed->user_blocks[u];
int t, hat = define_find(ed, def->name, &t);
if (hat < 0) continue;
char names[MAX_UBLK_SLOTS][32];
int n = 0;
define_outputs(&ed->tabs[t], ed->tabs[t].ws[hat].next, names, &n);
bool same = def->reg_type && n == def->output_count;
for (int k = 0; same && k < n; k++) same = !strcmp(names[k], def->output_names[k]);
if (same) continue;
def->output_count = n;
memcpy(def->output_names, names, sizeof(names[0]) * (size_t)n);
comp_make_type(ed, def);
}
}
/* Novo chapeu "defina" na aba atual, abaixo dos scripts, com um
"parametro" de cada entrada ao lado (para arrastar para o corpo) */
static void define_place(Ed* ed, UserBlockDef* def) {
TinyBlocks_TypeBlock* t_def = tb_type_block_find(ed->rt, "Port.Define");
if (!t_def) return;
Tab* T = &CT;
layout_tab(T);
float y = 40;
for (int i = 0; i < T->top_n; i++) {
EdBlock* b = &T->ws[T->top[i]];
float bottom = b->y + chain_h(T, T->top[i]);
if (bottom + 48 > y) y = bottom + 48;
}
int hat = blk_new(T, t_def);
if (hat < 0) return;
snprintf(T->ws[hat].in_text[0], sizeof(T->ws[hat].in_text[0]), "%s", def->name);
T->ws[hat].x = 40;
T->ws[hat].y = y;
top_add(T, hat);
layout_tab(T);
/* rola para o chapeu novo ficar a vista */
T->ws_sx = 0;
if (y - T->ws_sy > WS_H - 120 || y < T->ws_sy) T->ws_sy = y - 60;
}
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);
int def_tab = -1, def_hat = def ? define_find(ed, def->name, &def_tab) : -1;
if (!def || (def_hat < 0 && !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;
TbVarScope* outer = tb_vars_scope_current();
TbVarScope* local = tb_vars_scope_new(NULL); /* locais da chamada: nao veem as de quem chamou */
tb_vars_scope_set(local);
for (int i = 0; i < def->input_count; i++)
f->in[i] = tb_value_clone(tb_block_get_input(self, rt, (uint32_t)i));
if (def_hat >= 0) { /* "defina" numa aba: roda a pilha dele */
Tab* D = &ed->tabs[def_tab];
run_chain(ed, D, D->ws[def_hat].next);
goto done;
}
/* Aba so do bloco: 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]);
done:
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]);
tb_vars_scope_set(outer);
tb_vars_scope_free(local);
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 (t->flags & TB_TYPE_HIDDEN) return true; /* infraestrutura / "defina" */
if (strcmp(n, "Port.In") == 0) return !CT.is_composite; /* sai de dentro do "defina" */
if (strncmp(n, "Port.", 5) == 0) return !CT.is_composite && !tab_has_define(&CT);
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;
}
/* Altura de cada categoria: encolhe para todas caberem acima do botao de
bibliotecas (com muitas libraries carregadas a coluna fica compacta) */
/* == Areas (layout estilo Blender) ===
* Arvore de divisoes -> retangulo de cada view (paleta, scripts, palco,
* saida). Arrastar a borda entre duas areas muda o tamanho; arrastar a
* alca do cabecalho de uma area e soltar sobre outra troca as duas. */
/* Dados da instancia de Editor.Area (cena da janela de uma view destacada) */
typedef struct { Ed* ed; int view; } AreaScene;
static void ed_handle_input(Ed* ed, TinyBlocks_Block* evb, int from);
static void areas_only(Ed* ed, int keep, bool saved[V_COUNT]);
static void areas_restore(Ed* ed, const bool saved[V_COUNT]);
static bool tabwin_on_draw(Ed* ed, int k, TinyBlocks_RenderableBlock** dst);
static void drag_to_ctx(Ed* ed, int tgt);
static void tabwins_close_all(Ed* ed);
/* == Areas como classes ===
* Paleta, scripts, palco e saida sao ViewClass: nome, tamanho minimo,
* desenho, popups (por cima) e posicao da alca. A janela principal e as
* janelas destacadas desenham pela mesma tabela. */
typedef struct ViewClass {
const char* name;
float min_w, min_h;
void (*render)(Ed* ed, TinyBlocks_RenderableBlock* rb);
void (*overlay)(Ed* ed, TinyBlocks_RenderableBlock* rb); /* popups da area */
void (*grip)(const AreaRect* A, float* gx, float* gy); /* NULL = canto do cabecalho */
} ViewClass;
static const ViewClass* view_class(int v);
static const char* view_name(int v) {
const ViewClass* vc = view_class(v);
return vc ? vc->name : "?";
}
static int lay_node(Ed* ed, int kind, int a, int b, int view, int fix, float px) {
if (ed->lay_n >= LAY_MAX) return -1;
LayNode* N = &ed->lay[ed->lay_n];
memset(N, 0, sizeof(*N));
N->kind = kind; N->a = a; N->b = b; N->view = view; N->fix = fix; N->px = px;
return ed->lay_n++;
}
/* Layout padrao (o de sempre): paleta | scripts | palco sobre a saida */
static void lay_default(Ed* ed) {
ed->lay_n = 0;
int pal = lay_node(ed, LN_LEAF, -1, -1, V_PALETTE, 0, 0);
int scr = lay_node(ed, LN_LEAF, -1, -1, V_SCRIPTS, 0, 0);
int stg = lay_node(ed, LN_LEAF, -1, -1, V_STAGE, 0, 0);
int out = lay_node(ed, LN_LEAF, -1, -1, V_OUTPUT, 0, 0);
int right = lay_node(ed, LN_VSPLIT, stg, out, -1, 0, STAGE_BAR_H + (STAGE_W - 16) * 0.75f + 8);
int mid = lay_node(ed, LN_HSPLIT, scr, right, -1, 1, STAGE_W);
ed->lay_root = lay_node(ed, LN_HSPLIT, pal, mid, -1, 0, PALETTE_W);
}
/* -- Layout salvo nas configuracoes (chave "editor.layout") ---------------
* Texto curto: folha = letra da view (p paleta, s scripts, t palco,
* o saida); divisao = H|V<lado fixo>:<px>(a,b). O padrao e
* "H0:318(p,H1:360(s,V0:310(t,o)))". */
static const char LAY_VIEW_CH[V_COUNT] = { 'p', 's', 't', 'o' };
static void lay_write(Ed* ed, int n, char* out, size_t cap) {
const LayNode* N = &ed->lay[n];
size_t len = strlen(out);
if (len + 1 >= cap) return;
if (N->kind == LN_LEAF) { snprintf(out + len, cap - len, "%c", LAY_VIEW_CH[N->view]); return; }
snprintf(out + len, cap - len, "%c%d:%d(", N->kind == LN_HSPLIT ? 'H' : 'V', N->fix, (int)roundf(N->px));
lay_write(ed, N->a, out, cap);
len = strlen(out);
snprintf(out + len, cap - len, ",");
lay_write(ed, N->b, out, cap);
len = strlen(out);
snprintf(out + len, cap - len, ")");
}
static int lay_read(Ed* ed, const char** p, int* seen) {
char c = **p;
for (int v = 0; v < V_COUNT; v++) {
if (c != LAY_VIEW_CH[v]) continue;
(*p)++;
if (*seen & (1 << v)) return -1; /* view repetida */
*seen |= 1 << v;
return lay_node(ed, LN_LEAF, -1, -1, v, 0, 0);
}
if (c != 'H' && c != 'V') return -1;
(*p)++;
char* e;
long fix = strtol(*p, &e, 10);
if (e == *p || (fix != 0 && fix != 1) || *e != ':') return -1;
*p = e + 1;
float px = strtof(*p, &e);
if (e == *p || px <= 0 || *e != '(') return -1;
*p = e + 1;
int a = lay_read(ed, p, seen);
if (a < 0 || **p != ',') return -1;
(*p)++;
int b = lay_read(ed, p, seen);
if (b < 0 || **p != ')') return -1;
(*p)++;
return lay_node(ed, c == 'H' ? LN_HSPLIT : LN_VSPLIT, a, b, -1, (int)fix, px);
}
/* Aplica um layout salvo; invalido (view faltando/repetida) = fica o atual */
static bool lay_load_str(Ed* ed, const char* str) {
LayNode backup[LAY_MAX];
int bn = ed->lay_n, broot = ed->lay_root;
memcpy(backup, ed->lay, sizeof(backup));
ed->lay_n = 0;
int seen = 0;
const char* p = str;
int r = lay_read(ed, &p, &seen);
if (r < 0 || *p || seen != (1 << V_COUNT) - 1) {
memcpy(ed->lay, backup, sizeof(backup));
ed->lay_n = bn; ed->lay_root = broot;
return false;
}
ed->lay_root = r;
return true;
}
static void lay_settings_path(char* buf, size_t cap) {
const char* e = tb_environ_env_path();
if (e[0]) snprintf(buf, cap, "%s", e);
else tb_environ_config_path(buf, cap);
}
/* Grava o layout nas configuracoes (so quando mudou) */
static void lay_save(Ed* ed) {
char str[256] = "";
lay_write(ed, ed->lay_root, str, sizeof(str));
if (!strcmp(tb_environ_get("editor.layout"), str)) return;
tb_environ_set("editor.layout", str);
char path[512];
lay_settings_path(path, sizeof(path));
if (!tb_environ_export_csv_meta(path, "arquivo_config", path)) {
snprintf(ed->hot_status, sizeof(ed->hot_status), "Não consegui salvar o layout: %.180s",
tb_environ_last_error());
ed->hot_status_ok = false;
}
}
/* Ao abrir: le o arquivo de configuracoes e aplica o layout salvo */
static void lay_restore(Ed* ed) {
char path[512];
lay_settings_path(path, sizeof(path));
if (!tb_environ_has("editor.layout")) tb_environ_import_csv(path);
const char* ls = tb_environ_get("editor.layout");
if (ls[0] && !lay_load_str(ed, ls)) {
snprintf(ed->hot_status, sizeof(ed->hot_status), "Layout salvo inválido; usando o padrão");
ed->hot_status_ok = false;
}
}
/* Tamanho minimo de uma subarvore na direcao horizontal ou vertical */
static float lay_min(Ed* ed, int n, bool horiz) {
const LayNode* N = &ed->lay[n];
if (N->kind == LN_LEAF) {
const ViewClass* vc = view_class(N->view);
return vc ? (horiz ? vc->min_w : vc->min_h) : 80.f;
}
float a = lay_min(ed, N->a, horiz), b = lay_min(ed, N->b, horiz);
return ((N->kind == LN_HSPLIT) == horiz) ? a + b : fmaxf(a, b);
}
/* Tamanho do lado a de uma divisao com `total` px, respeitando os minimos */
static float lay_side_a(Ed* ed, const LayNode* N, float total, float want_a) {
bool hz = N->kind == LN_HSPLIT;
float ma = lay_min(ed, N->a, hz), mb = lay_min(ed, N->b, hz);
if (total <= ma + mb) return roundf(total * ma / (ma + mb));
if (want_a > total - mb) want_a = total - mb;
if (want_a < ma) want_a = ma;
return roundf(want_a);
}
/* A subarvore tem alguma view na janela principal (nao destacada)? */
static bool lay_attached(Ed* ed, int n) {
const LayNode* N = &ed->lay[n];
if (N->kind == LN_LEAF) return !ed->vwin[N->view];
return lay_attached(ed, N->a) || lay_attached(ed, N->b);
}
static void lay_place(Ed* ed, int n, float x, float y, float w, float h) {
LayNode* N = &ed->lay[n];
N->x = x; N->y = y; N->w = w; N->h = h;
N->pos = -1e9f;
if (N->kind != LN_LEAF) {
/* lado sem views na janela principal (todas destacadas): o outro ocupa tudo */
if (!lay_attached(ed, N->a)) { lay_place(ed, N->b, x, y, w, h); return; }
if (!lay_attached(ed, N->b)) { lay_place(ed, N->a, x, y, w, h); return; }
}
if (N->kind == LN_LEAF) {
AreaRect* A = &ed->area[N->view];
A->x = x; A->y = y; A->w = w; A->h = h; A->shown = !ed->vwin[N->view];
return;
}
bool hz = N->kind == LN_HSPLIT;
float total = hz ? w : h;
float sa = lay_side_a(ed, N, total, N->fix == 0 ? N->px : total - N->px);
N->pos = (hz ? x : y) + sa;
if (hz) { lay_place(ed, N->a, x, y, sa, h); lay_place(ed, N->b, x + sa, y, w - sa, h); }
else { lay_place(ed, N->a, x, y, w, sa); lay_place(ed, N->b, x, y + sa, w, h - sa); }
}
/* Abas destacadas -------------------------------------------------------- */
static bool tab_detached(Ed* ed, int i) {
for (int k = 0; k < TABWIN_MAX; k++) if (ed->twin[k].win && ed->twin[k].tab == i) return true;
return false;
}
/* A aba aparece na barra do contexto atual? (principal: as nao destacadas) */
static bool tab_visible(Ed* ed, int i) {
if (ed->tabctx >= 0) return i == ed->twin[ed->tabctx].tab;
return !tab_detached(ed, i);
}
static int tabs_visible_list(Ed* ed, int* out) {
int n = 0;
for (int i = 0; i < ed->tab_n; i++) if (tab_visible(ed, i)) out[n++] = i;
return n;
}
static void tabwin_rect(Ed* ed, int k, AreaRect* A) {
A->x = ed->twin[k].geom[0] - ed->main_wx;
A->y = ed->twin[k].geom[1] - ed->main_wy;
A->w = ed->twin[k].geom[2];
A->h = ed->twin[k].geom[3];
A->shown = A->detached = true;
}
static void lay_compute(Ed* ed) {
for (int v = 0; v < V_COUNT; v++) { ed->area[v].shown = false; ed->area[v].detached = false; }
if (ed->lay_n > 0 && lay_attached(ed, ed->lay_root))
lay_place(ed, ed->lay_root, 0, MENU_H, WIN_W, WIN_H - MENU_H);
/* views destacadas: retangulo da janela delas, no espaco da principal */
for (int v = 0; v < V_COUNT; v++) {
if (!ed->vwin[v]) continue;
AreaRect* A = &ed->area[v];
A->x = ed->vgeom[v][0] - ed->main_wx;
A->y = ed->vgeom[v][1] - ed->main_wy;
A->w = ed->vgeom[v][2];
A->h = ed->vgeom[v][3];
A->shown = A->detached = true;
}
/* no contexto de uma aba destacada, "os scripts" sao a janela dela */
ed->main_scripts = ed->area[V_SCRIPTS];
if (ed->tabctx >= 0) tabwin_rect(ed, ed->tabctx, &ed->area[V_SCRIPTS]);
}
typedef struct { int cur_tab, tabctx; } TabCtxSave;
static void tabctx_enter(Ed* ed, int k, TabCtxSave* sv) {
sv->cur_tab = ed->cur_tab;
sv->tabctx = ed->tabctx;
ed->ctx_main_tab = ed->cur_tab;
ed->tabctx = k;
ed->cur_tab = ed->twin[k].tab;
lay_compute(ed);
}
static void tabctx_leave(Ed* ed, const TabCtxSave* sv) {
ed->tabctx = sv->tabctx;
ed->cur_tab = sv->cur_tab;
lay_compute(ed);
}
/* Contexto de scripts sob o ponto: k = janela de aba, -1 = principal, -2 = nenhum */
static int ws_ctx_at(Ed* ed, float mx, float my) {
for (int k = 0; k < TABWIN_MAX; k++) {
if (!ed->twin[k].win) continue;
AreaRect A;
tabwin_rect(ed, k, &A);
if (in_rect(mx, my, A.x, A.y + TAB_H, A.w, A.h - TAB_H)) return k;
}
const AreaRect* M = &ed->main_scripts;
if (M->shown && in_rect(mx, my, M->x, M->y + TAB_H, M->w, M->h - TAB_H)) return -1;
return -2;
}
/* View sob o ponto. Janelas podem se sobrepor na tela: a janela que tem o
mouse ganha; depois as areas da principal; por fim as destacadas. */
static int view_at(Ed* ed, float mx, float my) {
int o = ed->mouse_owner;
/* mouse numa janela de aba: no contexto dela, e a area de scripts */
if (o >= V_COUNT) o = (ed->tabctx >= 0 && o - V_COUNT == ed->tabctx) ? V_SCRIPTS : -1;
if (o >= 0 && o < V_COUNT && ed->area[o].shown &&
in_rect(mx, my, ed->area[o].x, ed->area[o].y, ed->area[o].w, ed->area[o].h)) return o;
for (int pass = 0; pass < 2; pass++)
for (int v = 0; v < V_COUNT; v++) {
const AreaRect* A = &ed->area[v];
if (A->shown && A->detached == (pass == 1) && in_rect(mx, my, A->x, A->y, A->w, A->h)) return v;
}
return -1;
}
static bool in_ws(Ed* ed, float mx, float my) {
return AREA(V_SCRIPTS).shown && in_rect(mx, my, WS_X, WS_Y, WS_W, WS_H);
}
#define SPLIT_GRAB 4.f
/* Divisao cuja borda esta sob o mouse (-1 = nenhuma) */
static int split_at(Ed* ed, float mx, float my) {
for (int n = 0; n < ed->lay_n; n++) {
const LayNode* N = &ed->lay[n];
if (N->kind == LN_HSPLIT && fabsf(mx - N->pos) <= SPLIT_GRAB && my >= N->y && my < N->y + N->h)
return n;
if (N->kind == LN_VSPLIT && fabsf(my - N->pos) <= SPLIT_GRAB && mx >= N->x && mx < N->x + N->w)
return n;
}
return -1;
}
static void split_drag_to(Ed* ed, int n, float mx, float my) {
LayNode* N = &ed->lay[n];
bool hz = N->kind == LN_HSPLIT;
float total = hz ? N->w : N->h;
float sa = lay_side_a(ed, N, total, hz ? mx - N->x : my - N->y);
N->px = N->fix == 0 ? sa : total - sa;
}
static void lay_swap(Ed* ed, int va, int vb) {
int la = -1, lb = -1;
for (int n = 0; n < ed->lay_n; n++) {
if (ed->lay[n].kind != LN_LEAF) continue;
if (ed->lay[n].view == va) la = n;
if (ed->lay[n].view == vb) lb = n;
}
if (la < 0 || lb < 0) return;
ed->lay[la].view = vb;
ed->lay[lb].view = va;
lay_compute(ed);
}
/* Alca do cabecalho de cada area (arrastar para trocar de lugar) */
#define GRIP_S 18.f
static void grip_pos(Ed* ed, int v, float* gx, float* gy) {
const AreaRect* A = &ed->area[v];
const ViewClass* vc = view_class(v);
if (vc && vc->grip) { vc->grip(A, gx, gy); return; }
*gx = A->x + A->w - GRIP_S - 8;
*gy = A->y + (TAB_H - GRIP_S) * 0.5f;
}
static void stage_grip(const AreaRect* A, float* gx, float* gy) {
*gx = A->x + A->w - 50 - GRIP_S - 8; *gy = A->y + (STAGE_BAR_H - GRIP_S) * 0.5f;
}
static void output_grip(const AreaRect* A, float* gx, float* gy) {
*gx = A->x + A->w - 8 - GRIP_S - 6; *gy = A->y + 6;
}
static int grip_at(Ed* ed, float mx, float my) {
for (int v = 0; v < V_COUNT; v++) {
if (!ed->area[v].shown || (v == V_SCRIPTS && ed->tabctx >= 0)) continue;
float gx, gy;
grip_pos(ed, v, &gx, &gy);
if (in_rect(mx, my, gx, gy, GRIP_S, GRIP_S)) return v;
}
return -1;
}
/* Botao destacar/recolher do cabecalho (o palco usa o da barra dele) */
#define DETACH_S 26.f
static void detach_btn_pos(Ed* ed, int v, float* bx, float* by) {
float gx, gy;
grip_pos(ed, v, &gx, &gy);
*bx = gx - DETACH_S - 6;
*by = gy + GRIP_S * 0.5f - DETACH_S * 0.5f;
}
static int detach_btn_at(Ed* ed, float mx, float my) {
for (int v = 0; v < V_COUNT; v++) {
if (v == V_STAGE || !ed->area[v].shown || (v == V_SCRIPTS && ed->tabctx >= 0)) continue;
float bx, by;
detach_btn_pos(ed, v, &bx, &by);
if (in_rect(mx, my, bx, by, DETACH_S, DETACH_S)) return v;
}
return -1;
}
/* Icone: duas janelas (destacar) ou janela com o canto cheio (recolher) */
static void draw_window_icon(TinyBlocks_RenderableBlock* rb, float x, float y, float s, bool detached, Col c) {
float k = s / 32.f;
if (detached) {
rb_stroke_rect(rb, x + 9*k, y + 7*k, 22*k, 18*k, 1.5f, c);
rb_fill_rect(rb, x + 12*k, y + 15*k, 10*k, 7*k, c);
} else {
rb_stroke_rect(rb, x + 9*k, y + 11*k, 15*k, 13*k, 1.5f, c);
rb_stroke_rect(rb, x + 16*k, y + 6*k, 15*k, 13*k, 1.5f, c);
}
}
static void draw_detach_btn(Ed* ed, TinyBlocks_RenderableBlock* rb, int v) {
if (v == V_STAGE || !ed->area[v].shown) return;
float bx, by;
detach_btn_pos(ed, v, &bx, &by);
bool hov = in_rect(ed->mouse_x, ed->mouse_y, bx, by, DETACH_S, DETACH_S);
if (hov) rb_fill_rrect(rb, bx, by, DETACH_S, DETACH_S, 5, COL_HOVER);
draw_window_icon(rb, bx - 2, by, DETACH_S + 4, ed->area[v].detached, hov ? COL_MENU : COL_TEXT_DIM);
}
static void draw_grip(Ed* ed, TinyBlocks_RenderableBlock* rb, int v) {
draw_detach_btn(ed, rb, v);
if (!ed->area[v].shown) return;
float gx, gy;
grip_pos(ed, v, &gx, &gy);
bool hov = ed->area_drag == v || in_rect(ed->mouse_x, ed->mouse_y, gx, gy, GRIP_S, GRIP_S);
if (hov) rb_fill_rrect(rb, gx - 2, gy - 2, GRIP_S + 4, GRIP_S + 4, 5, COL_HOVER);
Col c = hov ? COL_MENU : COL_TEXT_DIM;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 3; j++)
rb_fill_circle(rb, gx + 6 + i * 6, gy + 3 + j * 6, 1.6f, c);
}
/* Borda sob o mouse e alvo da troca de areas */
static void render_areas_overlay(Ed* ed, TinyBlocks_RenderableBlock* rb) {
int sp = ed->split_drag >= 0 ? ed->split_drag : ed->split_hover;
if (sp >= 0 && ed->area_drag < 0) {
const LayNode* N = &ed->lay[sp];
if (N->kind == LN_HSPLIT) rb_fill_rect(rb, N->pos - 1.5f, N->y, 3, N->h, COL_MENU);
else rb_fill_rect(rb, N->x, N->pos - 1.5f, N->w, 3, COL_MENU);
}
if (ed->area_drag < 0) return;
const AreaRect* S = &ed->area[ed->area_drag];
rb_fill_rect(rb, S->x, S->y, S->w, S->h, COLA(0, 0, 0, 40));
int t = ed->area_drop;
if (t >= 0 && t != ed->area_drag) {
const AreaRect* A = &ed->area[t];
rb_fill_rect(rb, A->x, A->y, A->w, A->h, COLA(76, 151, 255, 60));
rb_stroke_rect(rb, A->x + 1, A->y + 1, A->w - 2, A->h - 2, 2.f, COL_MENU);
char msg[64];
snprintf(msg, sizeof(msg), "Trocar com %s", view_name(t));
float w = tw(msg, FS_UI) + 24;
float cx = A->x + (A->w - w) * 0.5f, cy = A->y + A->h * 0.5f - 16;
rb_fill_rrect(rb, cx, cy, w, 32, 8, COL_MENU);
rb_text_c(rb, cx + 12, cy + 16, msg, COL_WHITE, FS_UI);
}
/* etiqueta da area levada, no mouse */
const char* nm = view_name(ed->area_drag);
float w = tw(nm, FS_UI) + 20;
rb_fill_rrect(rb, ed->mouse_x + 12, ed->mouse_y + 10, w, 26, 6, COL_TEXT);
rb_text_c(rb, ed->mouse_x + 22, ed->mouse_y + 23, nm, COL_WHITE, FS_UI);
}
static float cat_item_h(Ed* ed) {
float h = ed->cat_n ? (PAL_B - PAL_Y - LIBMAN_BTN_H) / (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 (tab_class(T)->init) tab_class(T)->init(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);
}
/* Novo indice de uma aba depois de mover `from` para `to` */
static int tab_moved_index(int o, int from, int to) {
if (o == from) return to;
if (from < to && o > from && o <= to) return o - 1;
if (from > to && o >= to && o < from) return o + 1;
return o;
}
static Tab* tab_moved_ptr(Ed* ed, Tab* T, int from, int to) {
if (T < ed->tabs || T >= ed->tabs + ed->tab_n) return T; /* ex.: corpo de Meus Blocos */
return &ed->tabs[tab_moved_index((int)(T - ed->tabs), from, to)];
}
/* Reordena as abas (arrastar na barra). Os scripts rodando continuam: os
ponteiros das threads e os indices guardados sao remapeados. */
static void tab_move(Ed* ed, int from, int to) {
if (from == to || from < 0 || to < 0 || from >= ed->tab_n || to >= ed->tab_n) return;
Tab* tmp = malloc(sizeof(Tab));
if (!tmp) return;
*tmp = ed->tabs[from];
if (from < to) memmove(&ed->tabs[from], &ed->tabs[from + 1], (size_t)(to - from) * sizeof(Tab));
else memmove(&ed->tabs[to + 1], &ed->tabs[to], (size_t)(from - to) * sizeof(Tab));
ed->tabs[to] = *tmp;
free(tmp);
ed->cur_tab = tab_moved_index(ed->cur_tab, from, to);
for (int u = 0; u < ed->user_block_n; u++)
if (ed->user_blocks[u].tab_idx >= 0)
ed->user_blocks[u].tab_idx = tab_moved_index(ed->user_blocks[u].tab_idx, from, to);
for (int t = 0; t < ed->vm_n; t++)
for (int f = 0; f < ed->vm[t].sp; f++)
ed->vm[t].st[f].T = tab_moved_ptr(ed, ed->vm[t].st[f].T, from, to);
ed->live_tab = ed->live_tab ? tab_moved_ptr(ed, ed->live_tab, from, to) : NULL;
for (int k = 0; k < TABWIN_MAX; k++)
if (ed->twin[k].win) ed->twin[k].tab = tab_moved_index(ed->twin[k].tab, from, to);
if (ed->drag_tab >= 0) ed->drag_tab = tab_moved_index(ed->drag_tab, from, to);
ed->ctx_main_tab = tab_moved_index(ed->ctx_main_tab, from, to);
rt_cache_clear(ed); /* a chave do cache e o ponteiro da aba */
}
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)--;
}
for (int k = 0; k < TABWIN_MAX; k++)
if (ed->twin[k].win && ed->twin[k].tab > ti) ed->twin[k].tab--;
tab_select(ed, ed->cur_tab >= ed->tab_n ? ed->tab_n - 1
: ed->cur_tab > ti ? ed->cur_tab - 1 : ed->cur_tab);
}
/* "Criar um Bloco": numa aba de blocos o "defina" fica na propria aba */
static void new_composite_tab(Ed* ed) {
dlg_open(ed, -1);
ed->comp_dialog_in_tab = tab_class(&CT)->blocks && !CT.is_composite;
}
static void open_def(Ed* ed, const char* uname) {
UserBlockDef* def = user_def_find(ed, uname);
if (!def) return;
int t, hat = define_find(ed, def->name, &t);
if (hat >= 0) { /* vai ate o "defina" */
tab_select(ed, t);
CT.ws_sx = CT.ws[hat].x - 40;
CT.ws_sy = CT.ws[hat].y - 60;
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");
if (!def->snap) def->snap = (Tab*)malloc(sizeof(Tab));
if (def->snap) *def->snap = *T;
def->tab_idx = (int)(T - ed->tabs);
comp_make_type(ed, def);
}
/* (Re)cria o tipo User.<nome> com as entradas/saidas atuais de def */
static void comp_make_type(Ed* ed, UserBlockDef* def) {
/* 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; }
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);
for (int i = 0; def->reg_type && i < def->input_count; i++) {
const UserParam* p = user_param_at(def, i);
if (p && p->kind == PARAM_BOOL) tb_type_block_set_input_flags(def->reg_type, (uint32_t)i, TB_SLOT_BOOLEAN);
}
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];
B->group_n = T->group_n < TB_BP_MAX_GROUPS ? T->group_n : TB_BP_MAX_GROUPS;
for (int g = 0; g < B->group_n; g++) {
const WsGroup* G = &T->groups[g];
B->groups[g] = (TbBpGroup){ G->x, G->y, G->w, G->h, G->color, "" };
snprintf(B->groups[g].title, sizeof(B->groups[g].title), "%s", G->title);
}
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 < MAX_MOUTHS; 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;
}
/* Blocos de uma aba da blueprint -> aba do editor (os mesmos indices) */
static void bp_tab_load(Ed* ed, const TbBpTab* B, Tab* T) {
for (int i = 0; i < MAX_WS; i++) {
memset(&T->ws[i], 0, sizeof(T->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] = T->ws[i].sub[2] = -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 < MAX_MOUTHS; 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];
}
/* Descarta tudo do editor e reconstroi a partir da blueprint. */
static void blueprint_apply(Ed* ed, const TbBlueprint* bp) {
tabwins_close_all(ed); /* abas destacadas voltam antes de recriar as abas */
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++) { tab_doc_free(&ed->tabs[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];
Tab* T = &ed->tabs[ed->tab_n++];
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;
bp_tab_load(ed, B, T);
T->group_n = B->group_n < MAX_GROUPS ? B->group_n : MAX_GROUPS;
for (int g = 0; g < T->group_n; g++) {
const TbBpGroup* G = &B->groups[g];
T->groups[g] = (WsGroup){ G->x, G->y, G->w, G->h, G->color, "" };
snprintf(T->groups[g].title, sizeof(T->groups[g].title), "%s", G->title);
}
}
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]);
else {
int t, hat = define_find(ed, d->name, &t);
if (hat >= 0) {
d->tab_idx = -1;
d->output_count = 0;
define_outputs(&ed->tabs[t], ed->tabs[t].ws[hat].next, d->output_names, &d->output_count);
comp_make_type(ed, d);
}
}
}
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 sb_import_file(Ed* ed, const char* path);
static bool has_ext(const char* path, const char* ext) {
size_t n = strlen(path), e = strlen(ext);
return n > e && !strcasecmp(path + n - e, ext);
}
static bool project_load(Ed* ed, const char* path) {
if (has_ext(path, ".txt") || has_ext(path, ".sb") || has_ext(path, ".scratchblocks"))
return sb_import_file(ed, path); /* notacao de texto do forum do Scratch */
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;
}
/* ===
* Notacao de texto do forum do Scratch ("scratchblocks"): exportar a aba
* atual / importar como aba nova (library tinyblocks-scratchblocks)
* === */
static void cleanup_ws(Ed* ed);
static int sb_shape(const char* type, void* ud) {
Ed* ed = (Ed*)ud;
TinyBlocks_TypeBlock* t = tb_type_block_find(ed->rt, type);
if (!t) return -1;
if (is_cap(t)) return TB_SB_CAP;
switch (shape_of(t)) {
case SH_HAT: return TB_SB_HAT;
case SH_C1: return TB_SB_C1;
case SH_C2: return TB_SB_C2;
case SH_C3: return TB_SB_C2;
case SH_REPORTER: return TB_SB_REPORTER;
case SH_BOOL: return TB_SB_BOOLEAN;
default: return TB_SB_STACK;
}
}
static int sb_slot_kind(const char* type, int slot, void* ud) {
Ed* ed = (Ed*)ud;
TinyBlocks_TypeBlock* t = tb_type_block_find(ed->rt, type);
if (!t || slot < 0 || slot >= input_count(t)) return TB_SB_SLOT_TEXT;
if (slot_is_bool(t, slot)) return TB_SB_SLOT_BOOL;
TinyBlocks_ValueKind k = t->input_descs[slot].expected_kind;
return (k == TB_VALUE_INTEGER || k == TB_VALUE_REAL) ? TB_SB_SLOT_NUM : TB_SB_SLOT_TEXT;
}
/* categoria do editor -> categoria do scratchblocks (cor no forum) */
static const char* sb_category(const char* type, void* ud) {
Ed* ed = (Ed*)ud;
int k = cat_of(ed, type);
const char* c = k >= 0 ? ed->cats[k].name : "";
static const struct { const char* pt; const char* sb; } map[] = {
{"Eventos", "events"}, {"Controle", "control"}, {"Sensores", "sensing"},
{"Operadores", "operators"}, {"Números", "operators"}, {"Texto", "operators"},
{"Variáveis", "variables"}, {"Listas", "list"}, {"Aparência", "looks"},
{"Caneta", "pen"}, {"Meus Blocos", "custom"},
};
for (size_t i = 0; i < sizeof(map) / sizeof(map[0]); i++)
if (!strcmp(c, map[i].pt)) return map[i].sb;
return "extension";
}
/* Contexto: rotulos em portugues do editor + callbacks */
static TbSbContext sb_context(Ed* ed, TbSbLabel** labels_out) {
size_t n = sizeof(s_specs) / sizeof(s_specs[0]);
TbSbLabel* L = calloc(n, sizeof(TbSbLabel));
int k = 0;
for (size_t i = 0; L && i < n; i++) {
L[k].type = s_specs[i].type;
L[k].label = s_specs[i].label;
k++;
}
*labels_out = L;
TbSbContext cx = { L, L ? k : 0, sb_shape, sb_slot_kind, sb_category, ed };
return cx;
}
static void sb_export_file(Ed* ed, const char* path) {
if (!tab_class(&CT)->blocks) {
snprintf(ed->hot_status, sizeof(ed->hot_status), "Só abas de blocos viram scratchblocks");
ed->hot_status_ok = false;
return;
}
TbBlueprint* bp = ed_to_blueprint(ed);
TbSbLabel* labels = NULL;
TbSbContext cx = sb_context(ed, &labels);
char* txt = bp ? tb_scratchblocks_export(&bp->tabs[ed->cur_tab], &cx) : NULL;
FILE* f = txt ? fopen(path, "wb") : NULL;
bool ok = f && fputs(txt, f) >= 0;
if (f) fclose(f);
snprintf(ed->hot_status, sizeof(ed->hot_status), ok ? "Exportado (scratchblocks): %.200s"
: "Falha ao exportar: %.200s", path);
ed->hot_status_ok = ok;
free(txt);
free(labels);
tb_blueprint_free(bp);
}
static bool sb_import_text(Ed* ed, const char* text, const char* name);
static bool sb_import_file(Ed* ed, const char* path) {
FILE* f = fopen(path, "rb");
char* text = NULL;
if (f) {
fseek(f, 0, SEEK_END);
long n = ftell(f);
fseek(f, 0, SEEK_SET);
text = n >= 0 ? malloc((size_t)n + 1) : NULL;
if (text) { size_t r = fread(text, 1, (size_t)n, f); text[r] = 0; }
fclose(f);
}
if (!text) {
snprintf(ed->hot_status, sizeof(ed->hot_status), "Não consegui ler %.200s", path);
ed->hot_status_ok = false;
return false;
}
const char* base = strrchr(path, '/');
bool ok = sb_import_text(ed, text, base ? base + 1 : path);
free(text);
return ok;
}
/* Texto em scratchblocks -> aba nova chamada `name` */
static bool sb_import_text(Ed* ed, const char* text, const char* name) {
TbBpTab* B = calloc(1, sizeof(TbBpTab));
if (!B) return false;
TbSbLabel* labels = NULL;
TbSbContext cx = sb_context(ed, &labels);
char warn[200] = "";
int n = tb_scratchblocks_import(text, B, &cx, warn, sizeof(warn));
free(labels);
const char* base = name;
if (n <= 0 || !tab_new_kind(ed, base, false, TK_BLOCKS)) {
if (n <= 0) snprintf(ed->hot_status, sizeof(ed->hot_status), "Nenhum script em %.200s", name);
else snprintf(ed->hot_status, sizeof(ed->hot_status), "Limite de abas atingido");
ed->hot_status_ok = false;
free(B);
return false;
}
bp_tab_load(ed, B, &CT);
free(B);
layout_tab(&CT);
cleanup_ws(ed); /* arruma as pilhas uma embaixo da outra */
palette_rebuild(ed);
if (warn[0]) snprintf(ed->hot_status, sizeof(ed->hot_status), "Importado com avisos: %.180s", warn);
else snprintf(ed->hot_status, sizeof(ed->hot_status), "Importado: %d script(s) de %.160s", n, base);
ed->hot_status_ok = !warn[0];
return true;
}
/* -- Previa da exportacao: o texto que vai para o forum ----------------- */
#define SBP_HEAD_H 46
#define SBP_FOOT_H 58
#define SBP_LINE_H 19
static void sbp_geom(Ed* ed, float* x, float* y, float* w, float* h) {
*w = fminf(760.f, WIN_W - 80.f);
*h = fminf(560.f, WIN_H - 80.f);
*x = (WIN_W - *w) * 0.5f;
*y = (WIN_H - *h) * 0.5f;
}
static void sbp_close(Ed* ed) {
ed->sbp_open = false;
free(ed->sbp_text);
ed->sbp_text = NULL;
}
/* Gera o texto da aba atual e abre a previa */
static void sbp_open(Ed* ed) {
if (!tab_class(&CT)->blocks) {
snprintf(ed->hot_status, sizeof(ed->hot_status), "Só abas de blocos viram scratchblocks");
ed->hot_status_ok = false;
return;
}
TbBlueprint* bp = ed_to_blueprint(ed);
TbSbLabel* labels = NULL;
TbSbContext cx = sb_context(ed, &labels);
char* txt = bp ? tb_scratchblocks_export(&bp->tabs[ed->cur_tab], &cx) : NULL;
free(labels);
tb_blueprint_free(bp);
if (!txt) return;
free(ed->sbp_text);
ed->sbp_text = txt;
ed->sbp_scroll = 0;
ed->sbp_open = true;
}
static int sbp_lines(const char* s) {
int n = 0;
for (const char* p = s; *p; p++) if (*p == '\n') n++;
return n;
}
static void sbp_button(TinyBlocks_RenderableBlock* rb, float x, float y, float w, const char* label,
bool primary, bool hov) {
Col bg = primary ? (hov ? COL_MENU_DARK : COL_MENU) : (hov ? COL_HOVER : COL_PANEL);
if (!primary) rb_fill_rrect(rb, x, y, w, 34, 17, COL_BORDER);
rb_fill_rrect(rb, x + (primary ? 0 : 1), y + (primary ? 0 : 1), w - (primary ? 0 : 2), 34 - (primary ? 0 : 2), 16, bg);
rb_text_c(rb, x + (w - tw(label, FS_UI)) * 0.5f, y + 17, label, primary ? COL_WHITE : COL_TEXT, FS_UI);
}
/* Botoes do rodape: 0 Copiar, 1 Salvar..., 2 Fechar (direita para esquerda) */
static void sbp_button_pos(Ed* ed, int i, float* bx, float* by, float* bw) {
float x, y, w, h;
sbp_geom(ed, &x, &y, &w, &h);
static const float widths[3] = { 150, 110, 100 };
float r = x + w - 16;
for (int k = 0; k <= i; k++) { r -= widths[k]; if (k < i) r -= 10; }
*bx = r; *by = y + h - SBP_FOOT_H + 12; *bw = widths[i];
}
static void sbp_render(Ed* ed, TinyBlocks_RenderableBlock* rb) {
if (!ed->sbp_open || !ed->sbp_text) return;
float x, y, w, h;
sbp_geom(ed, &x, &y, &w, &h);
rb_fill_rect(rb, 0, 0, WIN_W, WIN_H, COLA(0, 0, 0, 120));
rb_fill_rrect(rb, x + 3, y + 4, w, h, 12, COLA(0, 0, 0, 70));
rb_fill_rrect(rb, x, y, w, h, 12, COL_PANEL);
rb_fill_rrect(rb, x, y, w, SBP_HEAD_H, 12, COL_MENU);
rb_fill_rect(rb, x, y + SBP_HEAD_H - 12, w, 12, COL_MENU);
char title[96];
snprintf(title, sizeof(title), "Prévia scratchblocks - %s", CT.name);
rb_text_c(rb, x + 18, y + SBP_HEAD_H * 0.5f, title, COL_WHITE, 17);
/* texto, numa area escura como a aba de codigo */
float cx = x + 14, cy = y + SBP_HEAD_H + 12, cw = w - 28, ch = h - SBP_HEAD_H - SBP_FOOT_H - 18;
rb_fill_rrect(rb, cx, cy, cw, ch, 8, COLA(30, 30, 30, 255));
clip_set(ed, rb, cx + 4, cy + 4, cw - 8, ch - 8);
int total = sbp_lines(ed->sbp_text);
int visible = (int)((ch - 16) / SBP_LINE_H);
if (ed->sbp_scroll > total - visible) ed->sbp_scroll = total - visible;
if (ed->sbp_scroll < 0) ed->sbp_scroll = 0;
const char* p = ed->sbp_text;
for (int l = 0; *p; l++) {
size_t n = strcspn(p, "\n");
if (l >= ed->sbp_scroll && l < ed->sbp_scroll + visible) {
char line[256];
size_t m = n < sizeof(line) - 1 ? n : sizeof(line) - 1;
memcpy(line, p, m); line[m] = 0;
int ind = 0;
while (line[ind] == ' ') ind++;
const char* body = line + ind;
float ly = cy + 12 + (l - ed->sbp_scroll + 0.5f) * SBP_LINE_H;
/* "end"/"else" apagados, o resto claro; " :: categoria" apagado */
bool kw = !strcmp(body, "end") || !strcmp(body, "else");
char main_part[256];
snprintf(main_part, sizeof(main_part), "%s", body);
char* cat = strstr(main_part, " :: ");
if (cat) *cat = 0;
float lx = cx + 14 + ind * 8.f;
rb_text_c(rb, lx, ly, main_part, kw ? COLA(150, 160, 180, 255) : COLA(230, 230, 230, 255), FS_UI);
if (cat) rb_text_c(rb, lx + tw(main_part, FS_UI) + 6, ly, body + (cat - main_part) + 1,
COLA(120, 130, 150, 255), FS_UI);
}
p += n;
if (*p == '\n') p++;
}
clip_clear(ed, rb);
/* rodape */
char info[96];
snprintf(info, sizeof(info), "%d linhas - Copiar já inclui [scratchblocks]", total);
rb_text_c(rb, x + 18, y + h - SBP_FOOT_H * 0.5f, info, COL_TEXT_DIM, FS_SM);
static const char* labels[3] = { "Copiar", "Salvar...", "Fechar" };
for (int i = 0; i < 3; i++) {
float bx, by, bw;
sbp_button_pos(ed, i, &bx, &by, &bw);
sbp_button(rb, bx, by, bw, labels[i], i == 0, in_rect(ed->mouse_x, ed->mouse_y, bx, by, bw, 34));
}
}
static void sbp_copy(Ed* ed) {
if (!ed->sbp_text) return;
size_t n = strlen(ed->sbp_text) + 40;
char* clip = malloc(n);
if (!clip) return;
snprintf(clip, n, "[scratchblocks]\n%s[/scratchblocks]\n", ed->sbp_text);
bool ok = tb_graphics_set_clipboard(clip);
free(clip);
snprintf(ed->hot_status, sizeof(ed->hot_status), ok ? "Copiado - é só colar no fórum"
: "Não consegui copiar");
ed->hot_status_ok = ok;
}
static void sbp_click(Ed* ed, float mx, float my) {
for (int i = 0; i < 3; i++) {
float bx, by, bw;
sbp_button_pos(ed, i, &bx, &by, &bw);
if (!in_rect(mx, my, bx, by, bw, 34)) continue;
if (i == 0) sbp_copy(ed);
else if (i == 1) { sbp_close(ed); start_path(ed, PM_EXP_SB, "script.txt"); }
else sbp_close(ed);
return;
}
}
/* Colar do forum: a area de transferencia vira uma aba nova */
static void sb_paste(Ed* ed) {
char* t = tb_graphics_get_clipboard();
if (!t || !t[0]) {
snprintf(ed->hot_status, sizeof(ed->hot_status), "A área de transferência está vazia");
ed->hot_status_ok = false;
} else {
sb_import_text(ed, t, "Colado");
}
free(t);
}
/* ===
* 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_in_tab = false;
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);
}
/* "defina" numa aba comum: atualiza o chapeu (ou cria, se o bloco e novo) */
int d_tab = -1, d_hat = define_find(ed, rename ? old_name : def->name, &d_tab);
bool new_def = ed->comp_dialog_def < 0;
if (d_hat >= 0 || (new_def && ed->comp_dialog_in_tab)) {
if (d_hat >= 0) {
Tab* D = &ed->tabs[d_tab];
snprintf(D->ws[d_hat].in_text[0], sizeof(D->ws[d_hat].in_text[0]), "%s", def->name);
} else {
define_place(ed, def);
}
def->tab_idx = -1;
def->output_count = 0;
define_outputs(d_hat >= 0 ? &ed->tabs[d_tab] : &CT,
d_hat >= 0 ? ed->tabs[d_tab].ws[d_hat].next : -1, def->output_names, &def->output_count);
comp_make_type(ed, def);
ed->comp_dialog_open = false;
ed->comp_dialog_editing = false;
snprintf(ed->hot_status, sizeof(ed->hot_status), new_def
? "Bloco \"%s\" criado: monte o corpo embaixo do \"defina\""
: "Bloco \"%s\" atualizado", def->name);
ed->hot_status_ok = true;
return;
}
/* 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));
/* views destacadas: um botao para cada (clicar recolhe de volta) */
float cx = CFG_BTN_X - 10;
for (int v = V_COUNT - 1; v >= 0; v--) {
ed->chip_w[v] = 0;
if (!ed->vwin[v]) continue;
const char* nm = view_name(v);
float w = tw(nm, FS_UI) + 40;
cx -= w;
ed->chip_x[v] = cx; ed->chip_w[v] = w;
bool hov = in_rect(mx, my, cx, 7, w, MENU_H - 14);
rb_fill_rrect(rb, cx, 7, w, MENU_H - 14, 6, hov ? COL_MENU_DARK : COLA(255, 255, 255, 34));
draw_window_icon(rb, cx + 2, 7 + (MENU_H - 14 - 22) * 0.5f, 22, true, COL_WHITE);
rb_text_c(rb, cx + 30, MENU_H * 0.5f, nm, COL_WHITE, FS_UI);
cx -= 8;
}
for (int k = TABWIN_MAX - 1; k >= 0; k--) { /* abas destacadas */
TabWin* W = &ed->twin[k];
W->chip_w = 0;
if (!W->win || W->tab < 0 || W->tab >= ed->tab_n) continue;
const char* nm = ed->tabs[W->tab].name;
float w = tw(nm, FS_UI) + 40;
cx -= w;
W->chip_x = cx; W->chip_w = w;
bool hov = in_rect(mx, my, cx, 7, w, MENU_H - 14);
rb_fill_rrect(rb, cx, 7, w, MENU_H - 14, 6, hov ? COL_MENU_DARK : COLA(255, 255, 255, 34));
draw_window_icon(rb, cx + 2, 7 + (MENU_H - 14 - 22) * 0.5f, 22, true, COL_WHITE);
rb_text_c(rb, cx + 30, MENU_H * 0.5f, nm, COL_WHITE, FS_UI);
cx -= 8;
}
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);
}
}
/* == Notificacoes flutuantes (toasts) ===
* Estilo EditorToaster do Godot: empilhadas no canto inferior direito da
* area de scripts, com barra de tempo; o mouse em cima pausa o tempo, o "x"
* fecha e a mesma mensagem repetida vira contador. */
#define TOAST_W_MAX 420.f
#define TOAST_PAD 12.f
#define TOAST_LINE_H 17.f
#define TOAST_FADE 400.f
static void toast_push(Ed* ed, const char* text, bool ok) {
for (int i = 0; i < ed->toast_n; i++) {
Toast* t = &ed->toasts[i];
if (t->ok == ok && strcmp(t->text, text) == 0) { /* repetida: conta */
t->count++;
t->left_ms = t->total_ms;
return;
}
}
if (ed->toast_n == TOAST_MAX) { /* cheia: sai a mais velha */
memmove(&ed->toasts[0], &ed->toasts[1], (TOAST_MAX - 1) * sizeof(Toast));
ed->toast_n--;
}
Toast* t = &ed->toasts[ed->toast_n++];
memset(t, 0, sizeof(*t));
scopy(t->text, sizeof(t->text), text);
t->ok = ok;
t->count = 1;
t->total_ms = t->left_ms = ok ? TOAST_INFO_MS : TOAST_ERR_MS;
}
static void toast_remove(Ed* ed, int i) {
memmove(&ed->toasts[i], &ed->toasts[i + 1], (size_t)(ed->toast_n - i - 1) * sizeof(Toast));
ed->toast_n--;
}
static bool toast_hit(const Toast* t, float mx, float my) {
return t->w > 0 && in_rect(mx, my, t->x, t->y, t->w, t->h);
}
/* Mensagem nova em hot_status vira toast (chamado no evento e no desenho,
para o aviso aparecer no mesmo quadro da acao) */
static void toasts_take_status(Ed* ed) {
if (!ed->hot_status[0]) return;
toast_push(ed, ed->hot_status, ed->hot_status_ok);
ed->hot_status[0] = 0;
}
/* Quadro: o tempo corre (pausa com o mouse em cima) e os vencidos saem */
static void toasts_update(Ed* ed) {
toasts_take_status(ed);
unsigned now = now_ms();
float dt = ed->toast_ms ? (float)(now - ed->toast_ms) : 0.f;
ed->toast_ms = now;
if (dt > 250.f) dt = 250.f; /* janela parada nao some com tudo */
for (int i = ed->toast_n - 1; i >= 0; i--) {
Toast* t = &ed->toasts[i];
if (toast_hit(t, ed->mouse_x, ed->mouse_y)) continue;
t->left_ms -= dt;
if (t->left_ms <= 0.f) toast_remove(ed, i);
}
}
/* Quebra o texto em ate 4 linhas que caibam em maxw (corta em espaco ou '/') */
static int toast_wrap(const char* s, float maxw, char lines[4][256]) {
int n = 0;
while (*s && n < 4) {
size_t len = strlen(s), cut = len;
if (tw(s, FS_UI) > maxw) {
char tmp[256];
size_t best = 0;
for (size_t i = 1; i <= len && i < sizeof(tmp); i++) {
if ((s[i] & 0xC0) == 0x80) continue; /* meio de letra UTF-8 */
memcpy(tmp, s, i); tmp[i] = 0;
if (tw(tmp, FS_UI) > maxw) break;
if (s[i] == ' ' || s[i - 1] == '/' || s[i] == 0) best = i;
cut = i;
}
if (best > 0 && n < 3) cut = best;
}
if (cut == 0) cut = 1;
if (n == 3 && s[cut]) { /* ultima linha: reticencias */
size_t c = cut > 3 ? cut - 3 : cut;
while (c > 0 && (s[c] & 0xC0) == 0x80) c--;
snprintf(lines[n++], 256, "%.*s...", (int)c, s);
return n;
}
snprintf(lines[n++], 256, "%.*s", (int)cut, s);
s += cut;
while (*s == ' ') s++;
}
return n;
}
static void render_toasts(Ed* ed, TinyBlocks_RenderableBlock* rb) {
toasts_take_status(ed);
bool in_ws_area = AREA(V_SCRIPTS).shown; /* falso se os scripts estao em outra janela */
float bx = in_ws_area ? WS_X : 0.f, bw = in_ws_area ? WS_W : (float)WIN_W;
float right = bx + bw - 16.f, y = in_ws_area ? WS_Y + WS_H - 16.f : WIN_H - 16.f;
float maxw = fminf(TOAST_W_MAX, bw - 32.f);
for (int i = ed->toast_n - 1; i >= 0; i--) { /* mais nova embaixo */
Toast* t = &ed->toasts[i];
char text[300];
if (t->count > 1) snprintf(text, sizeof(text), "%s (x%d)", t->text, t->count);
else scopy(text, sizeof(text), t->text);
char lines[4][256];
int nl = toast_wrap(text, maxw - 2*TOAST_PAD - 26.f, lines);
float tw_max = 0;
for (int l = 0; l < nl; l++) tw_max = fmaxf(tw_max, tw(lines[l], FS_UI));
float w = fmaxf(220.f, tw_max + 2*TOAST_PAD + 30.f);
if (w > maxw) w = maxw;
float h = nl * TOAST_LINE_H + 2*TOAST_PAD + 4.f;
y -= h;
t->x = right - w; t->y = y; t->w = w; t->h = h;
float a = t->left_ms < TOAST_FADE ? fmaxf(0.f, t->left_ms / TOAST_FADE) : 1.f;
Col bar = t->ok ? COL_MENU : COL_STOP;
Col bg = COL_PANEL, txt = COL_TEXT, dim = COL_TEXT_DIM, sh = COLA(0, 0, 0, 50), bd = COL_BORDER;
bar.a *= a; bg.a *= a; txt.a *= a; dim.a *= a; sh.a *= a; bd.a *= a;
bool hov = toast_hit(t, ed->mouse_x, ed->mouse_y);
rb_fill_rrect(rb, t->x + 2, t->y + 3, w, h, 8, sh);
rb_fill_rrect(rb, t->x, t->y, w, h, 8, bd);
rb_fill_rrect(rb, t->x + 1, t->y + 1, w - 2, h - 2, 7, bg);
rb_fill_rrect(rb, t->x + 1, t->y + 1, 5, h - 2, 2.5f, bar); /* faixa da cor */
for (int l = 0; l < nl; l++)
rb_text_c(rb, t->x + TOAST_PAD + 4, t->y + TOAST_PAD + 2 + TOAST_LINE_H * (l + 0.5f),
lines[l], txt, FS_UI);
/* fechar */
float cx = t->x + w - 16.f, cy = t->y + 16.f;
bool xh = in_rect(ed->mouse_x, ed->mouse_y, cx - 9, cy - 9, 18, 18);
if (xh) { Col hc = COL_HOVER; hc.a *= a; rb_fill_circle(rb, cx, cy, 9, hc); }
rb_line(rb, cx - 4, cy - 4, cx + 4, cy + 4, 1.6f, xh ? txt : dim);
rb_line(rb, cx + 4, cy - 4, cx - 4, cy + 4, 1.6f, xh ? txt : dim);
/* temporizador: barra que encolhe (para com o mouse em cima) */
float k = t->total_ms > 0 ? fmaxf(0.f, t->left_ms / t->total_ms) : 0.f;
Col tb = bar;
if (hov) tb.a *= 0.45f;
rb_fill_rect(rb, t->x + 8, t->y + h - 5, (w - 16) * k, 2.5f, tb);
y -= 8.f;
}
}
/* Clique no "x" de um toast fecha; o resto do toast deixa o clique passar
para o que esta embaixo (o aviso nao atrapalha arrastar blocos) */
static bool toasts_click(Ed* ed, float mx, float my) {
for (int i = 0; i < ed->toast_n; i++) {
Toast* t = &ed->toasts[i];
if (!toast_hit(t, mx, my)) continue;
float cx = t->x + t->w - 16.f, cy = t->y + 16.f;
if (in_rect(mx, my, cx - 11, cy - 11, 22, 22)) { toast_remove(ed, i); return true; }
return false;
}
return false;
}
static void render_tab_bar(Ed* ed, TinyBlocks_RenderableBlock* rb) {
if (!AREA(V_SCRIPTS).shown) return;
float y0 = AREA(V_SCRIPTS).y, x0 = WS_X, wbar = WS_W - GRIP_S - DETACH_S - 18; /* sobra alca e botao */
rb_fill_rect(rb, x0, y0, WS_W, TAB_H, COL_UI_BG);
int dragged = ed->tab_drag ? ed->tab_press : -1;
int vis[MAX_TABS], vn = tabs_visible_list(ed, vis);
for (int pass = 0; pass < 2; pass++) /* 2a passada: a aba arrastada, por cima */
for (int sl = 0; sl < vn; sl++) {
int i = vis[sl];
if ((pass == 1) != (i == dragged)) continue;
float tx = WS_X + 8 + sl*TAB_W;
if (pass == 0 && tx + TAB_W > x0 + wbar - PLUS_W) break;
if (pass == 1) {
tx = ed->mouse_x - ed->tab_grab_dx;
if (tx < x0 + 4) tx = x0 + 4;
if (tx > x0 + wbar - TAB_W) tx = x0 + wbar - TAB_W;
rb_fill_rrect(rb, tx + 2, y0 + 8, TAB_W - 4, TAB_H - 6, 8, COLA(0, 0, 0, 40));
}
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 (tab_class(&ed->tabs[i])->icon && tab_class(&ed->tabs[i])->icon(rb, tx, cy)) {
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 && ed->tabctx < 0) rb_text_c(rb, tx+TAB_W-22, cy, "=", COL_TEXT_DIM, FS_UI);
}
float px = WS_X + 8 + vn*TAB_W;
if (ed->tabctx < 0 && px + PLUS_W <= x0 + 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);
}
if (ed->tabctx < 0) draw_grip(ed, rb, V_SCRIPTS); /* na janela de uma aba nao ha area para mover */
}
static void render_categories(Ed* ed, TinyBlocks_RenderableBlock* rb) {
if (!AREA(V_PALETTE).shown) return;
/* cabecalho da paleta (alca para trocar de lugar) */
rb_fill_rect(rb, PAL_X, AREA(V_PALETTE).y, AREA(V_PALETTE).w, TAB_H, COL_UI_BG);
rb_text_c(rb, PAL_X + 14, AREA(V_PALETTE).y + TAB_H * 0.5f, "Blocos", COL_TEXT_DIM, FS_UI);
draw_grip(ed, rb, V_PALETTE);
rb_fill_rect(rb, PAL_X, PAL_Y, CAT_W, PAL_B-PAL_Y, COL_PANEL);
rb_line(rb, FLY_X-1, PAL_Y, FLY_X-1, PAL_B, 1.f, COL_BORDER);
float ih = cat_item_h(ed);
int cur = current_cat(ed);
float mid = PAL_X + CAT_W*0.5f;
for (int c = 0; c < ed->cat_n; c++) {
float iy = PAL_Y + c*ih;
if (c == cur) rb_fill_rect(rb, PAL_X, iy, CAT_W-1, ih, COL_UI_BG);
/* compacta: circulo e rotulo menores quando a coluna aperta */
float k = ih >= 48.f ? 1.f : ih / 48.f;
float r = 10.f * (k < 0.6f ? 0.6f : k), fs = ih >= 40.f ? 10.f : 9.f;
float cy = iy + ih*0.36f;
rb_fill_circle(rb, mid, cy, r, ed->cats[c].dark);
rb_fill_circle(rb, mid, cy, r - 1, ed->cats[c].col);
float w = tw(ed->cats[c].name, fs);
rb_text_c(rb, mid - w*0.5f, iy + ih*0.78f, ed->cats[c].name, COL_TEXT, fs);
}
/* Botao de buscar/adicionar library, no fim do painel (como o Scratch) */
float by = PAL_B - LIBMAN_BTN_H;
bool hov = hit_libman_foot(ed, ed->mouse_x, ed->mouse_y);
rb_fill_rect(rb, PAL_X, by, CAT_W-1, LIBMAN_BTN_H, hov ? COL_LIBBTN_DARK : COL_LIBBTN);
float cx = mid, 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) {
if (!AREA(V_PALETTE).shown) return;
rb_fill_rect(rb, FLY_X, PAL_Y, FLY_R - FLY_X, PAL_B-PAL_Y, COL_FLY);
rb_line(rb, FLY_R-1, PAL_Y, FLY_R-1, PAL_B, 1.f, COL_BORDER);
clip_set(ed, rb, FLY_X, PAL_Y, FLY_R - FLY_X - 1, PAL_B-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 > PAL_B) continue;
switch (it->kind) {
case FI_HEADER:
rb_text_c(rb, FLY_X + FLY_PAD, iy + it->h*0.55f, ed->cats[it->cat].name, COL_TEXT, 14);
break;
case FI_BUTTON:
rb_fill_rrect(rb, FLY_X + FLY_PAD, iy+4, FLY_BTN_W, 30, 6, COL_BORDER);
rb_fill_rrect(rb, FLY_X + FLY_PAD + 1, iy+5, FLY_BTN_W-2, 28, 5, COL_PANEL);
rb_text_c(rb, FLY_X + 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, FLY_X, 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>", 7)) { pend_start = -1; break; } /* fim da marcacao */
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) {
int vis[MAX_TABS];
*px = WS_X + 8 + tabs_visible_list(ed, vis) * TAB_W;
*py = AREA(V_SCRIPTS).y + 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 = PLUS_MENU_N;
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[PLUS_MENU_N] = { "Blueprint", "Novo bloco", "Edição de Imagem", "Editor de Código" };
const char* subs[PLUS_MENU_N] = { "folha em branco para scripts", "montar um bloco em Meus Blocos",
"editar SVG/imagem", "editar .c/.py/..." };
static const Col dots[PLUS_MENU_N] = {{0.30f,0.62f,1.f,1.f}, {1.f,0.40f,0.50f,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);
}
/* == Classes de aba (ver TabClass) ===================================== */
static void code_tab_click(Ed* ed, float mx, float my) { ed->editing = false; code_click(ed, mx, my); }
static bool code_tab_scroll(Ed* ed, float mx, float my, double dx, double dy) {
(void)mx; (void)my; (void)dx;
CT.code_scroll -= (int)dy * 3;
if (CT.code_scroll < 0) CT.code_scroll = 0;
return true;
}
static bool code_tab_icon(TinyBlocks_RenderableBlock* rb, float x, float cy) {
rb_fill_rrect(rb, x+9, cy-6, 11, 13, 2, COLA(42,74,110,255));
rb_fill_rect(rb, x+11, cy-3, 6, 1.4f, COLA(120,190,255,255));
rb_fill_rect(rb, x+11, cy+0, 6, 1.4f, COLA(120,190,255,255));
rb_fill_rect(rb, x+11, cy+3, 4, 1.4f, COLA(120,190,255,255));
return true;
}
static void image_tab_init(Ed* ed, Tab* T) { img_ensure(ed, T); }
static void image_tab_render(Ed* ed, TinyBlocks_RenderableBlock* rb) { render_image_tab(ed, rb); }
static void image_tab_click(Ed* ed, float mx, float my) { image_click(ed, mx, my); }
static bool image_tab_release(Ed* ed, float mx, float my) {
if (!CT.img_drag) return false;
image_release(ed, mx, my);
return true;
}
static void image_tab_motion(Ed* ed, float mx, float my) {
if (CT.img_drag && (mx != ed->img_mx || my != ed->img_my)) image_drag(ed, mx, my);
}
/* selecao: Delete apaga, Esc fixa */
static bool image_tab_key(Ed* ed, int sc, bool ctrl) {
(void)ctrl;
if (!CT.img_sel.on) return false;
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 true;
}
if (sc == TB_KEY_ESCAPE) { img_sel_commit(&CT); return true; }
return false;
}
/* roda do mouse = zoom no cursor (nao pinta) */
static bool image_tab_scroll(Ed* ed, float mx, float my, double dx, double dy) {
(void)dx;
image_zoom(ed, mx, my, (int)(dy > 0 ? 1 : dy < 0 ? -1 : 0));
return true;
}
static bool image_tab_icon(TinyBlocks_RenderableBlock* rb, float x, float cy) {
rb_fill_rrect(rb, x+9, cy-6, 12, 12, 2, COLA(200,150,60,255));
rb_fill_circle(rb, x+13, cy-2, 2, COLA(255,235,180,255));
return true;
}
static const TabClass s_tab_classes[] = {
[TK_BLOCKS] = { "Blocos", true, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL },
[TK_CODE] = { "Código", false, NULL, render_code_tab, code_tab_click, NULL, NULL,
code_key, code_text, code_tab_scroll, code_tab_icon },
[TK_IMAGE] = { "Imagem", false, image_tab_init, image_tab_render, image_tab_click,
image_tab_release, image_tab_motion, image_tab_key, NULL,
image_tab_scroll, image_tab_icon },
};
const TabClass* tab_class(const Tab* T) {
int k = T ? T->kind : TK_BLOCKS;
if (k < 0 || k >= (int)(sizeof(s_tab_classes) / sizeof(s_tab_classes[0]))) k = TK_BLOCKS;
return &s_tab_classes[k];
}
/* == Grupos (retangulos coloridos que juntam pilhas) === */
static int group_at(Tab* T, float wx, float wy, bool head_only) {
for (int g = T->group_n - 1; g >= 0; g--) {
WsGroup* G = &T->groups[g];
if (!in_rect(wx, wy, G->x, G->y, G->w, G->h)) continue;
if (head_only && wy > G->y + GRP_HEAD_H &&
!(wx > G->x + G->w - GRP_GRIP && wy > G->y + G->h - GRP_GRIP)) continue;
return g;
}
return -1;
}
static void groups_render(Ed* ed, TinyBlocks_RenderableBlock* rb, float ox, float oy) {
for (int g = 0; g < CT.group_n; g++) {
WsGroup* G = &CT.groups[g];
Col c = s_user_colors[G->color % USER_COLOR_COUNT];
float x = ox + G->x, y = oy + G->y;
Col body = c; body.a = 0.16f;
Col head = c; head.a = 0.75f;
rb_fill_rrect(rb, x, y, G->w, G->h, 10, body);
rb_fill_rrect(rb, x, y, G->w, GRP_HEAD_H, 10, head);
rb_fill_rect(rb, x, y + GRP_HEAD_H - 10, G->w, 10, head);
rb_stroke_rect(rb, x, y, G->w, G->h, 1.5f, col_mul(c, 0.8f));
const char* t = G->title[0] ? G->title : (ed->grp_edit == g ? "" : "Grupo");
rb_text_c(rb, x + 12, y + GRP_HEAD_H * 0.5f, t, COL_WHITE, FS_UI);
if (ed->grp_edit == g) /* cursor do titulo */
rb_fill_rect(rb, x + 13 + tw(t, FS_UI), y + 7, 2, GRP_HEAD_H - 14, COL_WHITE);
/* alca de redimensionar: tres riscos no canto */
Col gr = col_mul(c, 0.7f);
for (int k = 0; k < 3; k++)
for (int j = 0; j <= k; j++)
rb_fill_rect(rb, x + G->w - 6 - (k - j) * 4, y + G->h - 6 - j * 4, 2, 2, gr);
}
}
/* Limites de uma pilha (todos os blocos dela, ja com layout) */
static void stack_bounds(Tab* T, int root, float* x0, float* y0, float* x1, float* y1) {
*x0 = *y0 = 1e9f; *x1 = *y1 = -1e9f;
for (int i = 0; i < MAX_WS; i++) {
EdBlock* b = &T->ws[i];
if (!b->used || stack_root(T, i) != root) continue;
if (b->ax < *x0) *x0 = b->ax;
if (b->ay < *y0) *y0 = b->ay;
if (b->ax + b->w > *x1) *x1 = b->ax + b->w;
if (b->ay + b->h > *y1) *y1 = b->ay + b->h;
}
}
static int group_add(Ed* ed, float x, float y, float w, float h) {
Tab* T = &CT;
if (T->group_n >= MAX_GROUPS) {
snprintf(ed->hot_status, sizeof(ed->hot_status), "Limite de %d grupos por aba", MAX_GROUPS);
ed->hot_status_ok = false;
return -1;
}
int g = T->group_n++;
WsGroup* G = &T->groups[g];
memset(G, 0, sizeof(*G));
G->x = x; G->y = y; G->w = w; G->h = h;
G->color = (g + 1) % USER_COLOR_COUNT;
snprintf(G->title, sizeof(G->title), "Grupo %d", g + 1);
if (G->y < T->ws_sy + 6) T->ws_sy = G->y - 6; /* titulo a vista */
if (G->x < T->ws_sx + 6) T->ws_sx = G->x - 6;
return g;
}
static void group_delete(Tab* T, int g) {
if (g < 0 || g >= T->group_n) return;
memmove(&T->groups[g], &T->groups[g + 1], (size_t)(T->group_n - g - 1) * sizeof(WsGroup));
T->group_n--;
}
/* Comeca a mover o grupo g: guarda as pilhas e grupos que estao dentro */
static void group_press(Ed* ed, int g, float mx, float my, int mode) {
Tab* T = &CT;
WsGroup* G = &T->groups[g];
ed->grp_drag = g; ed->grp_mode = mode;
ed->grp_mx = mx; ed->grp_my = my;
ed->grp_ox = G->x; ed->grp_oy = G->y; ed->grp_ow = G->w; ed->grp_oh = G->h;
ed->grp_mem_n = ed->grp_sub_n = 0;
if (mode != 1) return;
for (int i = 0; i < T->top_n; i++) {
EdBlock* b = &T->ws[T->top[i]];
if (!in_rect(b->x, b->y, G->x, G->y, G->w, G->h)) continue;
ed->grp_mem[ed->grp_mem_n] = T->top[i];
ed->grp_mem_pos[ed->grp_mem_n][0] = b->x;
ed->grp_mem_pos[ed->grp_mem_n][1] = b->y;
ed->grp_mem_n++;
}
for (int k = 0; k < T->group_n; k++) {
WsGroup* S = &T->groups[k];
if (k == g || S->x < G->x || S->y < G->y || S->x + S->w > G->x + G->w || S->y + S->h > G->y + G->h) continue;
ed->grp_sub[ed->grp_sub_n] = k;
ed->grp_sub_pos[ed->grp_sub_n][0] = S->x;
ed->grp_sub_pos[ed->grp_sub_n][1] = S->y;
ed->grp_sub_n++;
}
}
static void group_motion(Ed* ed, float mx, float my) {
Tab* T = &CT;
if (ed->grp_drag < 0 || ed->grp_drag >= T->group_n) return;
WsGroup* G = &T->groups[ed->grp_drag];
float dx = mx - ed->grp_mx, dy = my - ed->grp_my;
if (ed->grp_mode == 2) {
G->w = fmaxf(120.f, ed->grp_ow + dx);
G->h = fmaxf(GRP_HEAD_H + 40.f, ed->grp_oh + dy);
return;
}
G->x = ed->grp_ox + dx; G->y = ed->grp_oy + dy;
for (int i = 0; i < ed->grp_mem_n; i++) {
EdBlock* b = &T->ws[ed->grp_mem[i]];
if (!b->used) continue;
b->x = ed->grp_mem_pos[i][0] + dx;
b->y = ed->grp_mem_pos[i][1] + dy;
}
for (int i = 0; i < ed->grp_sub_n; i++) {
WsGroup* S = &T->groups[ed->grp_sub[i]];
S->x = ed->grp_sub_pos[i][0] + dx;
S->y = ed->grp_sub_pos[i][1] + dy;
}
layout_tab(T);
}
static void render_workspace(Ed* ed, TinyBlocks_RenderableBlock* rb) {
const TabClass* tc = tab_class(&CT);
if (tc->render) { tc->render(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);
groups_render(ed, rb, ox, oy);
if (CT.top_n == 0 && CT.group_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 void render_stage(Ed* ed, TinyBlocks_RenderableBlock* rb) {
AreaRect A = AREA(V_STAGE);
if (!A.shown) return;
float sx = A.x, sy = A.y;
rb_fill_rect(rb, sx, sy, A.w, A.h, 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);
draw_grip(ed, rb, V_STAGE);
/* Destacar / recolher o palco */
if (ed->stage) {
float dx = sx + A.w - 50;
if (ed->detach_hover) rb_fill_rrect(rb, dx, fy, 40, 32, 6, COL_HOVER);
draw_window_icon(rb, dx, fy, 32, A.detached, COL_TEXT);
}
float bx = sx + 8, by = sy + STAGE_BAR_H, bw = A.w - 16;
float ph = A.h - STAGE_BAR_H - 8;
if (ed->stage && ph > 8) {
rb_fill_rrect(rb, bx, by, bw, ph, 8, COL_BORDER);
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);
}
}
/* Saida: monitores de variaveis + console (texto dos blocos "escreva") */
static void render_output(Ed* ed, TinyBlocks_RenderableBlock* rb) {
AreaRect A = AREA(V_OUTPUT);
if (!A.shown) return;
rb_fill_rect(rb, A.x, A.y, A.w, A.h, COL_UI_BG);
float bx = A.x + 8, by = A.y, bw = A.w - 16;
float bh = A.h - 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) tb_value_to_text(*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);
draw_grip(ed, rb, V_OUTPUT);
}
#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_GROUP_NEW: return "Novo grupo aqui";
case CM_GROUP_STACK: return "Agrupar esta pilha";
case CM_GROUP_RENAME: return "Renomear grupo";
case CM_GROUP_COLOR: return "Trocar a cor do grupo";
case CM_GROUP_DELETE: return "Apagar grupo (mantém os blocos)";
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";
case CM_EXP_SB: return "Exportar scratchblocks";
case CM_PASTE_SB: return "Colar scratchblocks";
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 AREA(V_PALETTE).shown && mx >= PAL_X && mx < FLY_X &&
my >= PAL_B - LIBMAN_BTN_H && my < PAL_B;
}
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);
}
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 = shape_mouths(bs);
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 : "";
}
/* Como ev_int, mas `def` quando a saida nao foi preenchida (ex.: harness) */
static int64_t ev_int_def(TinyBlocks_Block* evb, int idx, int64_t def) {
if (!evb || idx<0 || (uint32_t)idx>=evb->output_count) return def;
TinyBlocks_Value* v=&evb->outputs[idx];
return v->kind==TB_VALUE_INTEGER ? v->as.integer : def;
}
static const TinyBlocks_JsonValue* ev_json(TinyBlocks_Block* evb, int idx) {
if (!evb || idx<0 || (uint32_t)idx>=evb->output_count) return NULL;
TinyBlocks_Value* v=&evb->outputs[idx];
return (v->kind==TB_VALUE_JSON && v->as.json && tb_json_kind(v->as.json)==TB_JSON_ARRAY) ? v->as.json : NULL;
}
static double json_num_at(const TinyBlocks_JsonValue* arr, uint32_t i) {
TinyBlocks_JsonValue* n = tb_json_array_get(arr, i);
double d = tb_json_as_number(n, 0.0);
if (n) tb_json_release(n);
return d;
}
static void feed_keys(TinyBlocks_Block* evb) {
const TinyBlocks_JsonValue* keys = ev_json(evb, GFX_IN_KEYS_HELD);
for (uint32_t i = 0; keys && i < tb_json_array_length(keys); i++)
tb_input_set_key((int)json_num_at(keys, i), true);
int k = (int)ev_int(evb, GFX_IN_KEY);
if (k > 0 && !ev_int(evb, GFX_IN_KEY_REPEAT)) tb_input_key_pressed(k);
}
/* Alimenta o estado de entrada do core (blocos de Sensores) a partir da
janela onde o palco esta: no painel do editor ou destacado na janela
propria. Pontos vao em px da vista do palco; o core converte. */
static void input_feed(Ed* ed, TinyBlocks_Block* evb) {
TinyBlocks_Block* src = evb;
float ox = AREA(V_STAGE).x + 8 + 1, oy = AREA(V_STAGE).y + STAGE_BAR_H + 1; /* vista no painel */
if (ed->vwin_in[V_STAGE]) { src = ed->vwin_in[V_STAGE]; ox = 8 + 1; oy = STAGE_BAR_H + 1; }
tb_input_begin_frame();
float vx = (float)ev_real(src, GFX_IN_MOUSE_X) - ox;
float vy = (float)ev_real(src, GFX_IN_MOUSE_Y) - oy;
float sx, sy;
bool over = tb_stage_view_to_stage(vx, vy, &sx, &sy);
/* como no Scratch: apertar o mouse so conta sobre o palco */
tb_input_set_mouse(vx, vy, over && ev_int(src, GFX_IN_MOUSE_L_HELD),
over && ev_int(src, GFX_IN_MOUSE_R_HELD));
if (over) tb_input_add_wheel((float)ev_real(src, GFX_IN_SCROLL_DY));
tb_input_clear_keys();
feed_keys(evb);
if (src != evb) feed_keys(src);
const TinyBlocks_JsonValue* tj = ev_json(src, GFX_IN_TOUCHES);
float tx[TB_INPUT_MAX_TOUCHES], ty[TB_INPUT_MAX_TOUCHES];
int tn = 0;
for (uint32_t i = 0; tj && i < tb_json_array_length(tj) && tn < TB_INPUT_MAX_TOUCHES; i++) {
TinyBlocks_JsonValue* p = tb_json_array_get(tj, i);
if (p && tb_json_kind(p) == TB_JSON_ARRAY && tb_json_array_length(p) >= 2) {
tx[tn] = (float)json_num_at(p, 0) - ox;
ty[tn] = (float)json_num_at(p, 1) - oy;
tn++;
}
if (p) tb_json_release(p);
}
tb_input_set_touches(tn, tx, ty);
const TinyBlocks_JsonValue* a = ev_json(evb, GFX_IN_ACCEL);
bool ha = a && tb_json_array_length(a) >= 3;
tb_input_set_accel(ha, ha ? (float)json_num_at(a, 0) : 0, ha ? (float)json_num_at(a, 1) : 0,
ha ? (float)json_num_at(a, 2) : 0);
const TinyBlocks_JsonValue* g = ev_json(evb, GFX_IN_GYRO);
bool hg = g && tb_json_array_length(g) >= 3;
tb_input_set_gyro(hg, hg ? (float)json_num_at(g, 0) : 0, hg ? (float)json_num_at(g, 1) : 0,
hg ? (float)json_num_at(g, 2) : 0);
}
static bool hit_flag(Ed* ed, float mx, float my) {
return AREA(V_STAGE).shown && in_rect(mx, my, AREA(V_STAGE).x + 10, AREA(V_STAGE).y + 6, 40, 32);
}
static bool hit_stop(Ed* ed, float mx, float my) {
return AREA(V_STAGE).shown && in_rect(mx, my, AREA(V_STAGE).x + 56, AREA(V_STAGE).y + 6, 40, 32);
}
static bool hit_detach(Ed* ed, float mx, float my) {
return ed->stage && AREA(V_STAGE).shown &&
in_rect(mx, my, AREA(V_STAGE).x + AREA(V_STAGE).w - 50, AREA(V_STAGE).y + 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 - FLY_X, 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 + FLY_X, 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) */
/* Recolhe a view destacada de volta para o seu lugar na janela principal.
Nunca chamar de dentro da cena da propria janela: use attach_request. */
static void attach_view(Ed* ed, int v) {
if (!ed->vwin[v]) return;
TinyBlocks_Block* w = ed->vwin[v];
TinyBlocks_Block* sc = ed->vwin_scene[v];
TinyBlocks_Block* in = ed->vwin_in[v];
ed->vwin[v] = ed->vwin_scene[v] = ed->vwin_in[v] = NULL;
tb_block_destroy(w, ed->rt);
if (sc) tb_block_destroy(sc, ed->rt);
if (in) tb_block_destroy(in, ed->rt);
if (ed->capture_view == v) ed->capture_view = -2;
if (ed->mouse_owner == v) ed->mouse_owner = -1;
lay_compute(ed);
}
static void attach_request(Ed* ed, int v) {
if (v >= 0 && v < V_COUNT && ed->vwin[v]) ed->attach_pending[v] = true;
}
/* Destaca a view numa janela propria (Graphics.Window + cena Editor.Area) */
static void detach_view(Ed* ed, int v) {
if (v < 0 || v >= V_COUNT || ed->vwin[v]) return;
int attached = 0;
for (int k = 0; k < V_COUNT; k++) attached += !ed->vwin[k];
if (attached <= 1) {
snprintf(ed->hot_status, sizeof(ed->hot_status), "A janela principal precisa de pelo menos uma área");
ed->hot_status_ok = false;
return;
}
TinyBlocks_TypeBlock* t_win = tb_type_block_find(ed->rt, "Graphics.Window");
TinyBlocks_TypeBlock* t_in = tb_type_block_find(ed->rt, "Graphics.Input");
TinyBlocks_TypeBlock* t_area = tb_type_block_find(ed->rt, "Editor.Area");
if (!t_win || !t_in || !t_area) return;
AreaRect A = AREA(v);
float w = A.w < 240 ? 240 : A.w, h = A.h < 160 ? 160 : A.h;
TinyBlocks_Block* in = tb_block_create(ed->rt, t_in);
TinyBlocks_Block* sc = tb_block_create(ed->rt, t_area);
TinyBlocks_Block* win = tb_block_create(ed->rt, t_win);
if (!in || !sc || !win) {
if (win) tb_block_destroy(win, ed->rt);
if (sc) tb_block_destroy(sc, ed->rt);
if (in) tb_block_destroy(in, ed->rt);
return;
}
AreaScene* as = (AreaScene*)sc->userdata;
as->ed = ed;
as->view = v;
tb_block_set_default(sc, 0, tb_value_block(in));
char title[64];
snprintf(title, sizeof(title), "%s - TinyBlocks", view_name(v));
TinyBlocks_Value tv = tb_value_text(title);
tb_block_set_default(win, 0, tv); /* set_default clona */
tb_value_free(&tv);
tb_block_set_default(win, 1, tb_value_integer((int64_t)w));
tb_block_set_default(win, 2, tb_value_integer((int64_t)h));
tb_block_set_default(win, 3, tb_value_block(sc));
tb_block_set_default(win, 4, tb_value_block(in));
tb_block_set_default(win, 5, tb_value_integer(0)); /* fechar recolhe, nao encerra o editor */
ed->vwin[v] = win; ed->vwin_in[v] = in; ed->vwin_scene[v] = sc;
/* ate a janela informar a posicao real, fica onde a area estava */
ed->vgeom[v][0] = ed->main_wx + A.x; ed->vgeom[v][1] = ed->main_wy + A.y;
ed->vgeom[v][2] = w; ed->vgeom[v][3] = h;
tb_block_eval(win, ed->rt);
if (!tb_graphics_window_is_open(win)) {
attach_view(ed, v);
snprintf(ed->hot_status, sizeof(ed->hot_status), "Não foi possível abrir a janela de %s", view_name(v));
ed->hot_status_ok = false;
return;
}
lay_compute(ed);
}
/* Recolhe a aba destacada k para a barra da principal (fora do contexto dela) */
static void attach_tab(Ed* ed, int k) {
TabWin* W = &ed->twin[k];
if (!W->win) return;
TinyBlocks_Block* w = W->win;
TinyBlocks_Block* sc = W->scene;
TinyBlocks_Block* in = W->in;
int tab = W->tab;
W->win = W->scene = W->in = NULL;
W->tab = -1;
W->attach_pending = false;
tb_block_destroy(w, ed->rt);
if (sc) tb_block_destroy(sc, ed->rt);
if (in) tb_block_destroy(in, ed->rt);
if (ed->capture_view == V_COUNT + k) ed->capture_view = -2;
if (ed->mouse_owner == V_COUNT + k) ed->mouse_owner = -1;
if (tab >= 0 && tab < ed->tab_n) tab_select(ed, tab);
lay_compute(ed);
}
static void tabwins_close_all(Ed* ed) {
for (int k = 0; k < TABWIN_MAX; k++) if (ed->twin[k].win) attach_tab(ed, k);
}
/* Destaca a aba i numa janela propria (precisa sobrar uma na principal) */
static void detach_tab(Ed* ed, int i) {
int vis[MAX_TABS], vn = tabs_visible_list(ed, vis);
if (i < 0 || i >= ed->tab_n || tab_detached(ed, i) || vn <= 1) return;
int k = -1;
for (int j = 0; j < TABWIN_MAX; j++) if (!ed->twin[j].win) { k = j; break; }
if (k < 0) {
snprintf(ed->hot_status, sizeof(ed->hot_status), "Limite de %d abas em janelas", TABWIN_MAX);
ed->hot_status_ok = false;
return;
}
TinyBlocks_TypeBlock* t_win = tb_type_block_find(ed->rt, "Graphics.Window");
TinyBlocks_TypeBlock* t_in = tb_type_block_find(ed->rt, "Graphics.Input");
TinyBlocks_TypeBlock* t_area = tb_type_block_find(ed->rt, "Editor.Area");
if (!t_win || !t_in || !t_area) return;
float w = WS_W < 360 ? 360 : WS_W, h = WS_H + TAB_H < 260 ? 260 : WS_H + TAB_H;
TinyBlocks_Block* in = tb_block_create(ed->rt, t_in);
TinyBlocks_Block* sc = tb_block_create(ed->rt, t_area);
TinyBlocks_Block* win = tb_block_create(ed->rt, t_win);
if (!in || !sc || !win) {
if (win) tb_block_destroy(win, ed->rt);
if (sc) tb_block_destroy(sc, ed->rt);
if (in) tb_block_destroy(in, ed->rt);
return;
}
AreaScene* as = (AreaScene*)sc->userdata;
as->ed = ed;
as->view = V_COUNT + k;
tb_block_set_default(sc, 0, tb_value_block(in));
char title[96];
snprintf(title, sizeof(title), "%s - TinyBlocks", ed->tabs[i].name);
TinyBlocks_Value tv = tb_value_text(title);
tb_block_set_default(win, 0, tv);
tb_value_free(&tv);
tb_block_set_default(win, 1, tb_value_integer((int64_t)w));
tb_block_set_default(win, 2, tb_value_integer((int64_t)h));
tb_block_set_default(win, 3, tb_value_block(sc));
tb_block_set_default(win, 4, tb_value_block(in));
tb_block_set_default(win, 5, tb_value_integer(0));
TabWin* W = &ed->twin[k];
W->tab = i; W->win = win; W->in = in; W->scene = sc; W->attach_pending = false;
W->geom[0] = ed->main_wx + WS_X + 40; W->geom[1] = ed->main_wy + AREA(V_SCRIPTS).y + 40;
W->geom[2] = w; W->geom[3] = h;
if (ed->cur_tab == i) /* a principal mostra outra aba */
for (int sl = 0; sl < vn; sl++) if (vis[sl] != i) { tab_select(ed, vis[sl]); break; }
tb_block_eval(win, ed->rt);
if (!tb_graphics_window_is_open(win)) {
attach_tab(ed, k);
snprintf(ed->hot_status, sizeof(ed->hot_status), "Não foi possível abrir a janela da aba");
ed->hot_status_ok = false;
return;
}
lay_compute(ed);
}
static void toggle_detach(Ed* ed, int v) {
if (ed->vwin[v]) attach_request(ed, v);
else detach_view(ed, v);
}
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 && !strcmp(T->ws[bi].type->type_name, "Port.Define")) {
UserBlockDef* def = user_def_find(ed, T->ws[bi].in_text[0]); /* nome e parametros */
if (def) dlg_open(ed, (int)(def - ed->user_blocks));
} else 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_GROUP_NEW: {
int g = group_add(ed, ed->ctx_wx - 20, ed->ctx_wy - 14, 360, 240);
if (g >= 0) ed->grp_edit = g; /* ja digita o titulo */
break;
}
case CM_GROUP_STACK: {
int root = stack_root(T, bi);
layout_tab(T);
float x0, y0, x1, y1;
stack_bounds(T, root, &x0, &y0, &x1, &y1);
int g = group_add(ed, x0 - 16, y0 - GRP_HEAD_H - 14, (x1 - x0) + 32, (y1 - y0) + GRP_HEAD_H + 34);
if (g >= 0) ed->grp_edit = g;
break;
}
case CM_GROUP_RENAME: ed->grp_edit = ed->ctx_menu_grp; break;
case CM_GROUP_COLOR:
if (ed->ctx_menu_grp >= 0 && ed->ctx_menu_grp < T->group_n)
T->groups[ed->ctx_menu_grp].color = (T->groups[ed->ctx_menu_grp].color + 1) % USER_COLOR_COUNT;
break;
case CM_GROUP_DELETE: group_delete(T, ed->ctx_menu_grp); ed->grp_edit = -1; 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;
case CM_EXP_SB: sbp_open(ed); break; /* previa: copiar ou salvar */
case CM_PASTE_SB: sb_paste(ed); break;
default: break;
}
}
/* == Dialogos modais como classes ===
* Cada dialogo (configuracoes, bibliotecas, explorador, previa do
* scratchblocks, "Criar um Bloco") e uma ModalClass. A entrada vai para o
* aberto mais alto; o desenho vai de baixo para cima. */
typedef struct ModalClass {
const char* name;
bool (*is_open)(Ed* ed);
void (*render)(Ed* ed, TinyBlocks_RenderableBlock* rb);
void (*click)(Ed* ed, float mx, float my);
void (*key)(Ed* ed, int sc, bool ctrl);
void (*text)(Ed* ed, const char* typed);
void (*scroll)(Ed* ed, float dy);
} ModalClass;
static bool settings_is_open(Ed* ed) { return ed->settings_open; }
static void settings_scroll_m(Ed* ed, float dy) { settings_scroll_by(ed, dy); }
static bool libman_is_open(Ed* ed) { return ed->libman_open; }
static void libman_key_m(Ed* ed, int sc, bool ctrl) { (void)ctrl; libman_key(ed, sc); }
static void libman_scroll_m(Ed* ed, float dy) { libman_scroll_by(ed, dy); }
/* o explorador vem do modulo do editor (pode faltar) */
static bool files_is_open(Ed* ed) { return ed->fdlg.open; }
static void files_render_m(Ed* ed, TinyBlocks_RenderableBlock* rb) { if (files_view) files_view(ed, rb); }
static void files_click_m(Ed* ed, float mx, float my) { if (files_click) files_click(ed, mx, my); }
static void files_key_m(Ed* ed, int sc, bool ctrl) { if (files_key) files_key(ed, sc, ctrl); else ed->fdlg.open = false; }
static void files_text_m(Ed* ed, const char* t) { if (files_text) files_text(ed, t); }
static void files_scroll_m(Ed* ed, float dy) { if (files_scroll) files_scroll(ed, dy); }
static bool sbp_is_open(Ed* ed) { return ed->sbp_open; }
static void sbp_key(Ed* ed, int sc, bool ctrl) {
if (sc == TB_KEY_ESCAPE) sbp_close(ed);
else if (ctrl && sc == TB_KEY_A + ('c' - 'a')) sbp_copy(ed);
}
static void sbp_scroll(Ed* ed, float dy) { ed->sbp_scroll -= (int)(dy * 3); }
static bool dlg_is_open(Ed* ed) { return ed->comp_dialog_open; }
static void dlg_key_m(Ed* ed, int sc, bool ctrl) { (void)ctrl; dlg_key(ed, sc); }
static void dlg_click_m(Ed* ed, float mx, float my) { dlg_click(ed, mx, my); }
static const ModalClass s_modals[] = { /* do mais alto para o mais baixo */
{ "configurações", settings_is_open, settings_render, settings_click, settings_key, settings_text, settings_scroll_m },
{ "bibliotecas", libman_is_open, libman_render, libman_click, libman_key_m, libman_text, libman_scroll_m },
{ "explorador", files_is_open, files_render_m, files_click_m, files_key_m, files_text_m, files_scroll_m },
{ "scratchblocks", sbp_is_open, sbp_render, sbp_click, sbp_key, NULL, sbp_scroll },
{ "criar bloco", dlg_is_open, dlg_render, dlg_click_m, dlg_key_m, dlg_text, NULL },
};
#define MODAL_N ((int)(sizeof(s_modals) / sizeof(s_modals[0])))
/* Dialogo aberto mais alto (recebe a entrada), ou NULL */
static const ModalClass* modal_top(Ed* ed) {
for (int i = 0; i < MODAL_N; i++) if (s_modals[i].is_open(ed)) return &s_modals[i];
return NULL;
}
static void modals_render(Ed* ed, TinyBlocks_RenderableBlock* rb) {
for (int i = MODAL_N - 1; i >= 0; i--)
if (s_modals[i].is_open(ed) && s_modals[i].render) s_modals[i].render(ed, rb);
}
static void on_lmb_down(Ed* ed, float mx, float my) {
if (toasts_click(ed, mx, my)) return;
const ModalClass* mc = modal_top(ed);
if (mc) { if (mc->click) mc->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 < PLUS_MENU_N; 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) { tab_new(ed, NULL, false); return; } /* folha em branco */
if (hit == 1) { dlg_open(ed, -1); return; } /* aba so do bloco */
if (hit == 2) { tab_new_kind(ed, "Imagem", false, TK_IMAGE); palette_rebuild(ed); return; }
if (hit == 3) {
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 && mx >= 0 && my >= 0) {
for (int v = 0; v < V_COUNT; v++) /* "voltar" uma view destacada */
if (ed->vwin[v] && in_rect(mx, my, ed->chip_x[v], 7, ed->chip_w[v], MENU_H - 14)) {
attach_request(ed, v);
return;
}
for (int k = 0; k < TABWIN_MAX; k++) /* "voltar" uma aba destacada */
if (ed->twin[k].win && in_rect(mx, my, ed->twin[k].chip_x, 7, ed->twin[k].chip_w, MENU_H - 14)) {
ed->twin[k].attach_pending = true;
return;
}
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_items[ed->ctx_n++] = CM_EXP_SB;
ed->ctx_items[ed->ctx_n++] = CM_PASTE_SB;
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;
/* Bordas entre areas (redimensionar) e alca do cabecalho (trocar de lugar) */
int sp = split_at(ed, mx, my);
if (sp >= 0) { ed->split_drag = sp; return; }
int gv = grip_at(ed, mx, my);
if (gv >= 0) { ed->area_drag = gv; ed->area_drop = -1; return; }
int dv = detach_btn_at(ed, mx, my);
if (dv >= 0) { toggle_detach(ed, dv); return; }
int va = view_at(ed, mx, my);
/* Palco */
if (va == V_STAGE) {
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)) toggle_detach(ed, V_STAGE);
return;
}
if (va == V_OUTPUT || va < 0) return;
/* Abas */
if (va == V_SCRIPTS && my < WS_Y) {
int vis[MAX_TABS], vn = tabs_visible_list(ed, vis);
for (int sl = 0; sl < vn; sl++) {
int i = vis[sl];
float tx = WS_X + 8 + sl*TAB_W;
if (!in_rect(mx, my, tx, AREA(V_SCRIPTS).y, TAB_W-4, TAB_H)) continue;
if (ed->tab_n > 1 && ed->tabctx < 0 && mx >= tx + TAB_W - 28) { tab_close(ed, i); return; }
tab_select(ed, i);
ed->tab_press = i; /* arrastar = reordenar */
ed->tab_drag = false;
ed->tab_press_x = mx; ed->tab_press_y = my;
ed->tab_grab_dx = mx - tx;
return;
}
float px = WS_X + 8 + vn*TAB_W;
if (ed->tabctx < 0 && in_rect(mx, my, px, AREA(V_SCRIPTS).y, 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;
}
}
if (va == V_PALETTE && my < PAL_Y) return; /* cabecalho da paleta */
/* Categorias */
if (va == V_PALETTE && mx < FLY_X) {
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 (va == V_PALETTE) {
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 (in_ws(ed, mx, my)) {
const TabClass* tc = tab_class(&CT);
if (tc->click) { tc->click(ed, mx, my); return; }
}
/* Workspace */
if (!in_ws(ed, mx, my)) return;
float wx = mx - WS_X + CT.ws_sx, wy = my - WS_Y + CT.ws_sy;
int bi = hit_ws(&CT, wx, wy);
ed->grp_edit = -1;
if (bi < 0) {
int g = group_at(&CT, wx, wy, true);
if (g >= 0) {
WsGroup* G = &CT.groups[g];
bool grip = wx > G->x + G->w - GRP_GRIP && wy > G->y + G->h - GRP_GRIP;
unsigned t = now_ms();
if (!grip && g == ed->grp_last_click && t - ed->grp_last_ms <= 400u) {
ed->grp_edit = g; /* clique duplo no titulo: renomear */
ed->grp_last_click = -1;
return;
}
ed->grp_last_click = g; ed->grp_last_ms = t;
group_press(ed, g, mx, my, grip ? 2 : 1);
return;
}
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;
}
{
ProtoLayout L; float qx, qy;
int k = proto_param_at(&CT.ws[bi], wx, wy, &L, &qx, &qy);
TinyBlocks_TypeBlock* t_in = k >= 0 ? tb_type_block_find(ed->rt, "Port.In") : NULL;
int ni = t_in ? blk_new(&CT, t_in) : -1;
if (ni >= 0) {
snprintf(CT.ws[ni].in_text[0], sizeof(CT.ws[ni].in_text[0]), "%s", L.txt[k]);
top_add(&CT, ni);
CT.ws[ni].x = qx; CT.ws[ni].y = qy;
float sx = qx + WS_X - CT.ws_sx, sy = qy + 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);
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;
}
/* Leva a pilha arrastada para os scripts de outra janela (outra aba): copia
para a aba de destino, apaga da origem e encaixa la como num arrasto. */
static void drag_to_ctx(Ed* ed, int tgt) {
int dti = tgt >= 0 ? ed->twin[tgt].tab : (ed->tabctx >= 0 ? ed->ctx_main_tab : ed->cur_tab);
if (dti < 0 || dti >= ed->tab_n || dti == ed->cur_tab) { apply_snap(ed); return; }
if (!tab_class(&ed->tabs[dti])->blocks) { /* aba de imagem/codigo nao recebe blocos */
snprintf(ed->hot_status, sizeof(ed->hot_status), "A aba \"%s\" não é de blocos", ed->tabs[dti].name);
ed->hot_status_ok = false;
apply_snap(ed);
return;
}
Tab* S = &CT;
Tab* D = &ed->tabs[dti];
int si = ed->drag_bi;
float sx = S->ws[si].ax + WS_X - S->ws_sx, sy = S->ws[si].ay + WS_Y - S->ws_sy; /* tela */
int ni = copy_tree(S, si, D, true);
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;
apply_snap(ed);
return;
}
top_add(D, ni);
free_tree(ed, S, si);
/* encaixa no destino: troca para o contexto dele so durante o calculo */
int save_tab = ed->cur_tab;
AreaRect save_ws = ed->area[V_SCRIPTS];
if (tgt >= 0) tabwin_rect(ed, tgt, &ed->area[V_SCRIPTS]);
else ed->area[V_SCRIPTS] = ed->main_scripts;
ed->cur_tab = dti;
D->ws[ni].x = sx - WS_X + D->ws_sx;
D->ws[ni].y = sy - WS_Y + D->ws_sy;
layout_tab(D);
ed->drag_bi = ni;
mark_drag(D, ni, true);
compute_snap(ed);
mark_drag(D, ni, false);
apply_snap(ed);
ed->cur_tab = save_tab;
ed->area[V_SCRIPTS] = save_ws;
}
static void on_lmb_up(Ed* ed, float mx, float my) {
if (modal_top(ed)) return;
if (ed->split_drag >= 0) { ed->split_drag = -1; lay_save(ed); return; }
if (ed->tab_press >= 0) {
bool was = ed->tab_drag;
int tab = ed->tab_press;
ed->tab_press = -1;
ed->tab_drag = false;
if (!was) return;
float bar_y = AREA(V_SCRIPTS).y;
if (ed->tabctx < 0) {
if (my < bar_y - 30 || my > bar_y + TAB_H + 40) detach_tab(ed, tab);
} else {
const AreaRect* M = &ed->main_scripts;
if (M->shown && in_rect(mx, my, M->x, M->y - 10, M->w, TAB_H + 30))
ed->twin[ed->tabctx].attach_pending = true; /* volta para a barra */
}
return;
}
if (ed->area_drag >= 0) {
int sv = ed->area_drag, tv = ed->area_drop;
bool outside = mx < 0 || my < 0 || mx >= WIN_W || my >= WIN_H;
if (tv >= 0 && tv != sv && !ed->vwin[tv]) {
if (ed->vwin[sv]) { /* volta para a principal no lugar de tv */
attach_request(ed, sv);
ed->swap_pending[0] = sv; ed->swap_pending[1] = tv;
} else { lay_swap(ed, sv, tv); lay_save(ed); }
} else if (tv < 0 && outside && !ed->vwin[sv]) {
detach_view(ed, sv); /* solta fora da janela: destaca */
}
ed->area_drag = ed->area_drop = -1;
return;
}
if (ed->grp_drag >= 0) { ed->grp_drag = -1; return; }
rt_cache_clear(ed); /* soltar/encaixar muda o programa que esta rodando */
if (tab_class(&CT)->release && tab_class(&CT)->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);
int tgt = ws_ctx_at(ed, mx, my);
if (view_at(ed, mx, my) == V_PALETTE) free_tree(ed, &CT, ed->drag_bi); /* solto na paleta = apagar */
else if (tgt != -2 && tgt != ed->tabctx) drag_to_ctx(ed, tgt);
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 (modal_top(ed)) return;
if (ed->ctx_menu_open) { ed->ctx_menu_open = false; ed->ctx_export = false; return; }
if (ed->state != ES_IDLE) return;
if (!in_ws(ed, mx, my)) return;
if (!tab_class(&CT)->blocks) return;
float wx = mx - WS_X + CT.ws_sx, wy = my - WS_Y + CT.ws_sy;
int bi = hit_ws(&CT, wx, wy);
int g = bi < 0 ? group_at(&CT, wx, wy, false) : -1;
ed->ctx_n = 0;
ed->ctx_menu_grp = g;
ed->ctx_wx = wx; ed->ctx_wy = wy;
if (bi >= 0) {
const TinyBlocks_TypeBlock* t = CT.ws[bi].type;
bool is_def = t && strcmp(t->type_name, "Port.Define") == 0;
if (!is_def) ed->ctx_items[ed->ctx_n++] = CM_DUPLICATE; /* dois "defina" iguais nao */
ed->ctx_items[ed->ctx_n++] = CM_DELETE;
if (is_def || (t && strncmp(t->type_name, "User.", 5) == 0)) ed->ctx_items[ed->ctx_n++] = CM_EDIT_DEF;
ed->ctx_items[ed->ctx_n++] = CM_GROUP_STACK;
} else if (g >= 0) {
ed->ctx_items[ed->ctx_n++] = CM_GROUP_RENAME;
ed->ctx_items[ed->ctx_n++] = CM_GROUP_COLOR;
ed->ctx_items[ed->ctx_n++] = CM_GROUP_DELETE;
ed->ctx_items[ed->ctx_n++] = CM_GROUP_NEW;
} else {
ed->ctx_items[ed->ctx_n++] = CM_CLEANUP;
ed->ctx_items[ed->ctx_n++] = CM_NEW_COMPOSITE;
ed->ctx_items[ed->ctx_n++] = CM_GROUP_NEW;
}
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, TB_BP_FMT_JSON); break;
case PM_EXP_XML: project_export(ed, p, TB_BP_FMT_XML); break;
case PM_EXP_CSV: project_export(ed, p, TB_BP_FMT_CSV); break;
case PM_EXP_SB: sb_export_file(ed, p); 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);
const ModalClass* mc = modal_top(ed);
if (mc) { if (mc->key) mc->key(ed, sc, ctrl); return; }
if (ed->ctx_menu_open) { if (sc == TB_KEY_ESCAPE) ed->ctx_menu_open = false; return; }
if (ed->grp_edit >= 0 && ed->grp_edit < CT.group_n && !ed->path_input_active) {
char* t = CT.groups[ed->grp_edit].title;
if (sc == TB_KEY_RETURN || sc == TB_KEY_ESCAPE) ed->grp_edit = -1;
else if (sc == TB_KEY_BACKSPACE) {
size_t n = strlen(t);
while (n > 0 && ((unsigned char)t[n - 1] & 0xC0) == 0x80) n--; /* letra UTF-8 inteira */
if (n > 0) t[n - 1] = 0;
}
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 (tab_class(&CT)->key && tab_class(&CT)->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 (in_ws(ed, mx, my)) {
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);
const ModalClass* mc = modal_top(ed);
if (mc) { if (mc->text) mc->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 (tab_class(&CT)->text && tab_class(&CT)->text(ed, typed)) {
/* a aba tratou */
} else if (ed->grp_edit >= 0 && ed->grp_edit < CT.group_n) {
append_text(CT.groups[ed->grp_edit].title, sizeof(CT.groups[0].title), 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 (tab_class(&CT)->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 (!tab_class(&CT)->blocks) return;
if (ed->state != ES_IDLE) return;
float mx = ed->mouse_x, my = ed->mouse_y;
if (!in_ws(ed, mx, my)) 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
* === */
/* Alguma view ou aba esta numa janela propria? */
static bool any_window_detached(Ed* ed) {
for (int v = 0; v < V_COUNT; v++) if (ed->vwin[v]) return true;
for (int k = 0; k < TABWIN_MAX; k++) if (ed->twin[k].win) return true;
return false;
}
/* Entrada de uma janela do editor: a principal (from = -1) ou a de uma view
destacada (from = V_*). Pontos viram coordenadas da janela principal. */
static void ed_handle_input(Ed* ed, TinyBlocks_Block* evb, int from) {
g_active_ed = ed;
if (from < 0) {
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;
ed->main_wx = (float)ev_int(evb, GFX_IN_WIN_X);
ed->main_wy = (float)ev_int(evb, GFX_IN_WIN_Y);
/* recolher pedido de dentro de uma janela destacada / janela fechada */
for (int v = 0; v < V_COUNT; v++) {
if (ed->vwin[v] && !tb_graphics_window_is_open(ed->vwin[v])) ed->attach_pending[v] = true;
if (ed->attach_pending[v]) { ed->attach_pending[v] = false; attach_view(ed, v); }
}
for (int k = 0; k < TABWIN_MAX; k++) {
TabWin* W = &ed->twin[k];
if (W->win && (W->attach_pending || !tb_graphics_window_is_open(W->win))) attach_tab(ed, k);
}
if (ed->swap_pending[0] >= 0) {
lay_swap(ed, ed->swap_pending[0], ed->swap_pending[1]);
ed->swap_pending[0] = ed->swap_pending[1] = -1;
lay_save(ed);
}
} else if (from >= V_COUNT) { /* janela de uma aba destacada */
int ww = (int)ev_int(evb, GFX_IN_WIN_W), wh = (int)ev_int(evb, GFX_IN_WIN_H);
TabWin* W = &ed->twin[from - V_COUNT];
if (ww > 0 && wh > 0) {
W->geom[0] = (float)ev_int(evb, GFX_IN_WIN_X);
W->geom[1] = (float)ev_int(evb, GFX_IN_WIN_Y);
W->geom[2] = (float)ww;
W->geom[3] = (float)wh;
}
} else {
int ww = (int)ev_int(evb, GFX_IN_WIN_W), wh = (int)ev_int(evb, GFX_IN_WIN_H);
if (ww > 0 && wh > 0) {
ed->vgeom[from][0] = (float)ev_int(evb, GFX_IN_WIN_X);
ed->vgeom[from][1] = (float)ev_int(evb, GFX_IN_WIN_Y);
ed->vgeom[from][2] = (float)ww;
ed->vgeom[from][3] = (float)wh;
}
}
lay_compute(ed);
/* o mouse e da janela que esta sob ele (ou da que comecou um arrasto) */
int ov = from >= V_COUNT ? V_SCRIPTS : from; /* janela de aba = os scripts do contexto */
float ox = from < 0 ? 0.f : AREA(ov).x, oy = from < 0 ? 0.f : AREA(ov).y;
bool clicked = ev_int(evb, GFX_IN_MOUSE_L_DOWN) || ev_int(evb, GFX_IN_MOUSE_L_UP) ||
ev_int(evb, GFX_IN_MOUSE_R_DOWN); /* o evento traz a posicao certa */
if (ev_int_def(evb, GFX_IN_MOUSE_IN, 1) || ed->capture_view == from || clicked) {
TinyBlocks_Value* gxv = (uint32_t)GFX_IN_GMOUSE_Y < evb->output_count ? &evb->outputs[GFX_IN_GMOUSE_X] : NULL;
if (gxv && gxv->kind == TB_VALUE_REAL && any_window_detached(ed)) {
/* com janelas destacadas: posicao global - posicao da principal */
ed->mouse_x = (float)ev_real(evb, GFX_IN_GMOUSE_X) - ed->main_wx;
ed->mouse_y = (float)ev_real(evb, GFX_IN_GMOUSE_Y) - ed->main_wy;
} else {
ed->mouse_x = (float)ev_real(evb, GFX_IN_MOUSE_X) + ox;
ed->mouse_y = (float)ev_real(evb, GFX_IN_MOUSE_Y) + oy;
}
ed->mouse_owner = from;
}
float mx = ed->mouse_x, my = ed->mouse_y;
if (from < 0) toasts_update(ed);
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);
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 < PLUS_MENU_N; 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);
/* == Areas: borda sendo arrastada / area levada pela alca === */
if (ed->split_drag >= 0) { split_drag_to(ed, ed->split_drag, mx, my); lay_compute(ed); }
if (ed->area_drag >= 0) ed->area_drop = view_at(ed, mx, my);
bool modal = modal_top(ed) != NULL;
ed->split_hover = modal ? -1 : split_at(ed, mx, my);
/* == Aba sendo arrastada: reordena ao passar do meio da vizinha === */
if (ed->tab_press >= 0 && (ed->capture_view == -2 || ed->capture_view == from)) {
if (!ed->tab_drag && fabsf(mx - ed->tab_press_x) + fabsf(my - ed->tab_press_y) > 6.f)
ed->tab_drag = true;
if (ed->tab_drag) {
int vis[MAX_TABS], vn = tabs_visible_list(ed, vis);
int slot = (int)floorf((mx - ed->tab_grab_dx - (WS_X + 8) + TAB_W * 0.5f) / TAB_W);
if (slot < 0) slot = 0;
if (slot >= vn) slot = vn - 1;
if (vn > 1 && vis[slot] != ed->tab_press) {
int to = vis[slot];
tab_move(ed, ed->tab_press, to);
ed->tab_press = to;
}
}
}
/* == Movimento === */
if (ed->state == ES_PRESS && fabsf(mx - ed->press_mx) + fabsf(my - ed->press_my) > 4.f &&
(ed->capture_view == -2 || ed->capture_view == from))
start_drag(ed);
if (ed->state == ES_DRAG && ed->drag_bi >= 0 && (ed->capture_view == -2 || ed->capture_view == from)) {
EdBlock* b = &CT.ws[ed->drag_bi];
ed->drag_tab = ed->cur_tab;
ed->drag_ws_x = WS_X; ed->drag_ws_y = WS_Y;
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->grp_drag >= 0 && (ed->capture_view == -2 || ed->capture_view == from))
group_motion(ed, mx, my);
if (ed->state == ES_PAN && (ed->capture_view == -2 || ed->capture_view == from)) {
CT.ws_sx = ed->pan_sx - (mx - ed->pan_mx);
CT.ws_sy = ed->pan_sy - (my - ed->pan_my);
}
if (tab_class(&CT)->motion) tab_class(&CT)->motion(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) {
const ModalClass* mc = modal_top(ed);
if (mc) {
if (mc->scroll) mc->scroll(ed, (float)sdy);
} else if (in_ws(ed, mx, my) && tab_class(&CT)->scroll) {
tab_class(&CT)->scroll(ed, mx, my, sdx, sdy);
} else if (in_ws(ed, mx, my)) {
CT.ws_sx -= (float)sdx * 40.f;
CT.ws_sy -= (float)sdy * 40.f;
} else if (view_at(ed, mx, my) == V_PALETTE && 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)) { ed->capture_view = from; 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); ed->capture_view = -2; }
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);
if (from >= 0) return; /* o resto e uma vez por quadro (principal) */
input_feed(ed, evb); /* Sensores: mouse/teclado/toque/sensores do palco */
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);
}
}
static void editor_eval(TinyBlocks_Block* self, TinyBlocks* rt) {
Ed* ed = *(Ed**)self->userdata;
self->dirty = false;
if (!ed) return;
TinyBlocks_Block* evb = editor_events_block(self, rt);
if (evb) ed_handle_input(ed, evb, -1);
}
/* Pilha arrastada: desenhada em todas as janelas (o bloco pode passar de
uma para outra), a partir da aba e da area de onde ela saiu */
static void render_drag_chain(Ed* ed, TinyBlocks_RenderableBlock* rb) {
int t = ed->drag_tab >= 0 && ed->drag_tab < ed->tab_n ? ed->drag_tab : ed->cur_tab;
Tab* T = &ed->tabs[t];
if (ed->drag_bi < 0 || !T->ws[ed->drag_bi].used) return;
render_chain(ed, rb, T, ed->drag_bi, ed->drag_ws_x - T->ws_sx, ed->drag_ws_y - T->ws_sy);
}
/* Mostra so a view `keep` (-1 = so as da janela principal) durante um desenho */
static void areas_only(Ed* ed, int keep, bool saved[V_COUNT]) {
for (int v = 0; v < V_COUNT; v++) {
saved[v] = ed->area[v].shown;
if (keep < 0 ? ed->area[v].detached : v != keep) ed->area[v].shown = false;
}
}
static void areas_restore(Ed* ed, const bool saved[V_COUNT]) {
for (int v = 0; v < V_COUNT; v++) ed->area[v].shown = saved[v];
}
/* Desloca os comandos (desenho no espaco da principal -> janela destacada) */
static void rb_translate(TinyBlocks_RenderableBlock* rb, float dx, float dy) {
for (uint32_t i = 0; i < rb->count; i++) {
TinyBlocks_DrawCmd* c = &rb->cmds[i];
switch (c->kind) {
case TB_DRAW_CLEAR:
case TB_DRAW_CLEAR_CLIP:
break;
case TB_DRAW_STROKE_LINE: /* w,h sao o segundo ponto */
c->x += dx; c->y += dy; c->w += dx; c->h += dy;
break;
default:
c->x += dx; c->y += dy;
break;
}
}
}
/* Editor.Area: cena da janela de uma view destacada */
/* A janela da cena ainda existe? (view destacada ou aba destacada) */
static bool scene_alive(const AreaScene* as) {
if (!as || !as->ed || as->view < 0) return false;
if (as->view < V_COUNT) return as->ed->vwin[as->view] != NULL;
int k = as->view - V_COUNT;
return k < TABWIN_MAX && as->ed->twin[k].win != NULL;
}
static void area_eval(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
AreaScene* as = (AreaScene*)self->userdata;
if (!scene_alive(as)) return;
TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
if (v.kind != TB_VALUE_BLOCK || !v.as.block) return;
if (as->view < V_COUNT) { ed_handle_input(as->ed, v.as.block, as->view); return; }
TabCtxSave sv;
tabctx_enter(as->ed, as->view - V_COUNT, &sv);
ed_handle_input(as->ed, v.as.block, as->view);
tabctx_leave(as->ed, &sv);
}
static void palette_view_render(Ed* ed, TinyBlocks_RenderableBlock* rb) {
render_flyout(ed, rb);
render_categories(ed, rb);
}
static void scripts_view_render(Ed* ed, TinyBlocks_RenderableBlock* rb) {
render_workspace(ed, rb);
render_comp_panel(ed, rb);
render_tab_bar(ed, rb);
}
static void scripts_view_overlay(Ed* ed, TinyBlocks_RenderableBlock* rb) {
render_plus_menu(ed, rb);
render_tooltip(ed, rb);
render_ctx_menu(ed, rb);
}
static const ViewClass s_views[V_COUNT] = {
[V_PALETTE] = { "Blocos", CAT_W + 120.f, 80.f, palette_view_render, NULL, NULL },
[V_SCRIPTS] = { "Scripts", 220.f, TAB_H + 120.f, scripts_view_render, scripts_view_overlay, NULL },
[V_STAGE] = { "Palco", 160.f, STAGE_BAR_H + 60.f, render_stage, NULL, stage_grip },
[V_OUTPUT] = { "Saída", 160.f, 80.f, render_output, NULL, output_grip },
};
static const ViewClass* view_class(int v) {
return (v >= 0 && v < V_COUNT) ? &s_views[v] : NULL;
}
static bool area_on_draw(TinyBlocks_Block* self, TinyBlocks* rt, TinyBlocks_RenderableBlock** dst) {
(void)rt;
AreaScene* as = (AreaScene*)self->userdata;
if (!scene_alive(as)) return false;
Ed* ed = as->ed;
int v = as->view;
if (v >= V_COUNT) return tabwin_on_draw(ed, v - V_COUNT, dst);
TinyBlocks_RenderableBlock* rb = tb_renderable_acquire();
if (!rb) return false;
lay_compute(ed);
layout_tab(&CT);
tb_draw_clear(rb, COL_UI_BG.r, COL_UI_BG.g, COL_UI_BG.b, 1.f);
bool saved[V_COUNT];
areas_only(ed, v, saved);
const ViewClass* vc = view_class(v);
if (vc) vc->render(ed, rb);
if (ed->state == ES_DRAG && ed->drag_bi >= 0) /* bloco arrastado entre janelas */
render_drag_chain(ed, rb);
render_areas_overlay(ed, rb);
if (vc && vc->overlay) vc->overlay(ed, rb);
areas_restore(ed, saved);
rb_translate(rb, -AREA(v).x, -AREA(v).y);
*dst = rb;
return true;
}
/* Janela de uma aba destacada: barra com a aba + area de scripts dela */
static bool tabwin_on_draw(Ed* ed, int k, TinyBlocks_RenderableBlock** dst) {
TinyBlocks_RenderableBlock* rb = tb_renderable_acquire();
if (!rb) return false;
TabCtxSave sv;
tabctx_enter(ed, k, &sv);
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_tab_bar(ed, rb);
if (ed->state == ES_DRAG && ed->drag_bi >= 0) render_drag_chain(ed, rb);
render_tooltip(ed, rb);
render_ctx_menu(ed, rb);
float ox = AREA(V_SCRIPTS).x, oy = AREA(V_SCRIPTS).y;
tabctx_leave(ed, &sv);
rb_translate(rb, -ox, -oy);
*dst = rb;
return true;
}
static bool area_instance_init(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt;
if (self->userdata) { AreaScene* as = (AreaScene*)self->userdata; as->ed = NULL; as->view = -1; }
return true;
}
static void area_instance_deinit(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)self; (void)rt;
}
/* ===
* 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;
lay_compute(ed);
layout_tab(&CT);
tb_draw_clear(rb, COL_UI_BG.r, COL_UI_BG.g, COL_UI_BG.b, 1.f);
bool saved[V_COUNT];
areas_only(ed, -1, saved); /* as destacadas desenham na janela delas */
for (int v = 0; v < V_COUNT; v++) view_class(v)->render(ed, rb); /* as escondidas nao desenham */
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_drag_chain(ed, rb);
render_areas_overlay(ed, rb);
render_plus_menu(ed, rb);
render_tooltip(ed, rb);
render_ctx_menu(ed, rb);
modals_render(ed, rb); /* de baixo para cima; configuracoes por cima de tudo */
render_toasts(ed, rb); /* avisos flutuam por cima de tudo */
areas_restore(ed, saved);
*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;
lay_default(ed);
lay_restore(ed); /* layout salvo nas configuracoes */
ed->split_hover = ed->split_drag = ed->area_drag = ed->area_drop = -1;
ed->swap_pending[0] = ed->swap_pending[1] = -1;
ed->mouse_owner = -1;
ed->capture_view = -2;
ed->tab_press = -1;
ed->tabctx = -1;
ed->grp_drag = ed->grp_edit = ed->grp_last_click = ed->ctx_menu_grp = -1;
ed->drag_tab = -1;
for (int k = 0; k < TABWIN_MAX; k++) ed->twin[k].tab = -1;
lay_compute(ed);
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->sbp_text);
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.Define", port_label, 1, NULL, 0, eval_port_define);
TinyBlocks_TypeBlock* tdef = tb_type_block_find(rt, "Port.Define");
tb_type_block_set_shape(tdef, TB_SHAPE_HAT);
tb_type_block_set_flags(tdef, TB_TYPE_HIDDEN); /* nasce pelo "Criar um Bloco" */
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);
tb_type_block_set_flags(t, TB_TYPE_HIDDEN);
t->on_draw = editor_on_draw;
tb_library_add(lib, &t->base);
/* Editor.Area - uma view do editor destacada numa janela propria */
TinyBlocks_TypeBlock* ta = tb_type_block_create(rt, "Editor.Area",
scene_in, 1, NULL, 0, area_eval);
if (!ta) return false;
tb_type_block_set_instance_hooks(ta, sizeof(AreaScene), area_instance_init, area_instance_deinit);
tb_type_block_set_flags(ta, TB_TYPE_HIDDEN);
ta->on_draw = area_on_draw;
tb_library_add(lib, &ta->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;
}