Editor: "defina" na própria aba, grupos coloridos e tente/se der erro/finalmente

- Criar um Bloco põe o chapéu "defina <nome>" na aba atual (como no
  Scratch), com os parâmetros ao lado; o corpo vale na hora. Um "devolva"
  no corpo torna o bloco um repórter.
- Menu "+": Blueprint (folha em branco), Novo bloco (aba só do bloco),
  Edição de Imagem e Editor de Código.
- Grupos como os comentários do Unreal: retângulos coloridos com título;
  arrastar o título move junto as pilhas e grupos de dentro, o canto
  redimensiona, clique duplo renomeia. Salvos no projeto.
- Blocos C com três bocas (tente / se der erro / finalmente). Um erro sem
  tratamento para o script e aparece como [ERRO] no palco; erros sobem de
  dentro de Meus Blocos para quem chamou.
- Blueprint v2: 3 bocas (REL_ARG0 = 4); projetos v1 são convertidos ao abrir.
- Rótulos dos blocos de conversão e da categoria Erros.
- Abrir projeto libera os documentos das abas de código/imagem antigas.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mguinhosandClaude Opus 5.5 committed 2026-10-22 18:39:01 -03:00
1 parent 1b39c6892d
commit 9f6a1a0eb0
8 files changed
+774 -84

No files matched your search

@@ -77,6 +77,7 @@
/* Menu do botao "+" (nova aba) */
#define PLUS_MENU_W 208
#define PLUS_MENU_ITEM_H 36
#define PLUS_MENU_N 4
/* Editor de codigo (aba de codigo) */
#define CODE_FS 13
@@ -172,6 +173,9 @@ enum { IT_SEL = 0, IT_BRUSH, IT_LINE, IT_RECT, IT_ELLIPSE,
#define MAX_INPUTS 16
#define MAX_PARTS 40
#define MAX_TABS 8
#define MAX_GROUPS 32
#define GRP_HEAD_H 28 /* faixa do titulo (arrastar = mover tudo) */
#define GRP_GRIP 16 /* canto de baixo a direita: redimensionar */
#define MAX_FLY 192
#define MAX_CATS 24
#define MAX_CALL_DEPTH 32
@@ -201,6 +205,14 @@ static inline void scopy(char* dst, size_t cap, const char* src) {
tinyblocks-editor-widgets (ver tb_editor_widgets.h). Aqui so mantemos os
nomes curtos usados no codigo do editor. */
typedef TbEwColor Col;
/* Grupo (como os comentarios do Unreal): retangulo colorido atras dos
blocos; arrastar o titulo leva junto as pilhas e grupos de dentro. */
typedef struct {
float x, y, w, h; /* coordenadas da area de trabalho */
int color; /* indice em s_user_colors */
char title[48];
} WsGroup;
#define C(r,g,b) TB_EW_RGB(r,g,b)
#define COLA(r,g,b,a) TB_EW_RGBA(r,g,b,a)
#define col_mul tb_ed_w.col_mul
@@ -298,6 +310,18 @@ static const BlockSpec s_specs[] = {
{"Control.RepeatUntil", "repita até que %1", NULL},
{"Control.If", "se %1 então", NULL},
{"Control.IfElse", "se %1 então", NULL},
{"Errors.TryCatch", "tente", NULL},
{"Errors.Try", "tente", NULL},
{"Errors.Raise", "lance o erro %1", "algo deu errado"},
{"Errors.Caught", "erro capturado", NULL},
{"Errors.Attempt", "tente obter %1", ""},
{"Errors.Ok", "Ok( %1 )", "42"},
{"Errors.Err", "Erro( %1 )", "não achei"},
{"Errors.IsOk", "%1 é ok?", ""},
{"Errors.IsErr", "%1 é erro?", ""},
{"Errors.UnwrapOr", "valor de %1 ou %2", "|0"},
{"Errors.Unwrap", "desembrulhe %1", ""},
{"Errors.Message", "mensagem do erro %1", ""},
{"Operators.Lt", "%1 < %2", "|50"},
{"Operators.Eq", "%1 = %2", "|50"},
{"Operators.Gt", "%1 > %2", "|50"},
@@ -324,6 +348,7 @@ static const BlockSpec s_specs[] = {
{"Variables.Delete", "apague a variável %1", "contador"},
{"IO.Print", "escreva %1 %2", "Olá!|"},
{"IO.PrintInt", "escreva o número %1", NULL},
{"Port.Define", "defina %1", "meu bloco"},
{"Port.In", "parâmetro %1", "x"},
{"Port.Out", "devolva %1 = %2", "resultado|"},
{"Stage.Clear", "apague tudo", NULL},
@@ -381,6 +406,9 @@ static const BlockSpec s_specs[] = {
{"Number.IsEven", "%1 é par?", "4"},
{"Number.IsPrime", "%1 é primo?", "7"},
{"Number.IsInteger", "%1 é inteiro?", "2.5"},
{"Number.From", "número de %1", "3,5"},
{"Number.ToBase", "%1 na base %2", "255|16"},
{"Number.FromBase", "%1 da base %2 para número", "ff|16"},
/* Texto (tinyblocks-string) */
{"String.Upper", "maiúsculas de %1", "maçã"},
{"String.Lower", "minúsculas de %1", "MAÇÃ"},
@@ -398,7 +426,11 @@ static const BlockSpec s_specs[] = {
{"String.EndsWith", "%1 termina com %2?", "foto.png|.png"},
{"String.IsNumber", "%1 é número?", "3.14"},
{"String.IsEmpty", "%1 está vazio?", ""},
{"String.From", "texto de %1", "42"},
{"String.Code", "código da letra %1", "A"},
{"String.FromCode", "letra do código %1", "65"},
/* Listas (tinyblocks-vector) */
{"List.From", "lista de %1", "maçã, banana, uva"},
{"List.Empty", "lista vazia", NULL},
{"List.Of", "lista com %1 %2 %3", "maçã|banana|uva"},
{"List.Range", "números de %1 até %2", "1|10"},
@@ -458,6 +490,10 @@ static const BlockSpec s_specs[] = {
{"Image.Scale", "escale a imagem %1 para %2 x %3", "|64|64"},
{"Image.Load", "carregue a imagem %1", "imagem.png"},
{"Image.Save", "grave a imagem %1 em %2", "|saida.png"},
{"Image.ToList", "pixels da imagem %1", NULL},
{"Image.FromList", "imagem de largura %1 com os pixels %2", "2|[[255,0,0],[0,0,255]]"},
{"Image.Gray", "imagem %1 em tons de cinza", NULL},
{"Image.ToText", "desenho em texto da imagem %1 com %2 colunas", "|40"},
/* Vetor (vg) */
{"VG.New", "novo desenho vetorial", NULL},
{"VG.Line", "linha do vetor %1 de (%2,%3) a (%4,%5) cor r %6 g %7 b %8 esp %9", "|0|0|50|50|0|0|0|2"},
@@ -474,13 +510,14 @@ static const BlockSpec s_specs[] = {
/* ===
* Estruturas de dados
* === */
typedef enum { SH_STACK, SH_HAT, SH_C1, SH_C2, SH_REPORTER, SH_BOOL } Shape;
typedef enum { SH_STACK, SH_HAT, SH_C1, SH_C2, SH_REPORTER, SH_BOOL, SH_C3 } Shape;
/* Relação de um bloco com o pai */
#define REL_NONE (-1)
#define REL_NEXT 0
#define REL_SUB0 1 /* REL_SUB0 + k: boca k de um bloco C */
#define REL_ARG0 3 /* REL_ARG0 + i: campo de entrada i */
#define REL_ARG0 4 /* REL_ARG0 + i: campo de entrada i */
#define MAX_MOUTHS 3 /* bocas de um bloco C (tente/se der erro/finalmente) */
typedef struct {
int16_t arg; /* -1 = texto; senão índice do campo */
@@ -497,7 +534,7 @@ typedef struct {
float x, y; /* posição (só para o topo de uma pilha) */
int parent, prel;
int next;
int sub[2];
int sub[MAX_MOUTHS];
int args[MAX_INPUTS];
char in_text[MAX_INPUTS][64];
char lit_text[LIT_TEXT_CAP];
@@ -505,7 +542,7 @@ typedef struct {
/* layout - recalculado a cada frame */
float ax, ay, w, h;
float row_y, row_h, prev_y;
float sub_y[2], sub_h[2];
float sub_y[MAX_MOUTHS], sub_h[MAX_MOUTHS];
float slot_x[MAX_INPUTS], slot_y[MAX_INPUTS], slot_w[MAX_INPUTS], slot_h[MAX_INPUTS];
int part_n;
Part parts[MAX_PARTS];
@@ -564,9 +601,12 @@ typedef struct Tab {
unsigned img_prev_rev;
unsigned img_rev; /* muda a cada alteracao do documento */
ImgSel img_sel;
WsGroup groups[MAX_GROUPS];
int group_n;
} Tab;
typedef enum { PARAM_NUM, PARAM_BOOL, PARAM_LABEL } ParamKind;
typedef struct { ParamKind kind; char name[32]; } UserParam;
typedef struct {
@@ -597,7 +637,8 @@ typedef struct { FlyKind kind; int cat; int bi; float y, h; } FlyItem;
typedef enum { ES_IDLE, ES_PRESS, ES_DRAG, ES_PAN } EdSt;
typedef enum { SN_NONE, SN_NEXT, SN_SUB, SN_ABOVE, SN_ARG } SnapKind;
enum { CM_DUPLICATE, CM_DELETE, CM_EDIT_DEF, CM_CLEANUP, CM_NEW_COMPOSITE,
CM_EXP_JSON, CM_EXP_XML, CM_EXP_CSV, CM_EXP_SB, CM_PASTE_SB };
CM_EXP_JSON, CM_EXP_XML, CM_EXP_CSV, CM_EXP_SB, CM_PASTE_SB,
CM_GROUP_NEW, CM_GROUP_STACK, CM_GROUP_RENAME, CM_GROUP_COLOR, CM_GROUP_DELETE };
/* Modos da barra de caminho do menu (path_input) */
enum { PM_NONE, PM_LIB, PM_LOAD, PM_SAVE, PM_EXP_JSON, PM_EXP_XML, PM_EXP_CSV,
@@ -641,13 +682,16 @@ typedef struct {
/* Execucao em "threads" (estilo Scratch 3): cada script da bandeira tem uma
pilha explicita e pausa no fim de cada volta de laco; o editor avanca as
threads a cada quadro (ver vm_frame em tb_editor.c). */
enum { VF_CHAIN, VF_REPEAT, VF_UNTIL, VF_FOREVER };
enum { VF_CHAIN, VF_REPEAT, VF_UNTIL, VF_FOREVER, VF_TRY };
typedef struct {
Tab* T;
int bi; /* CHAIN: proximo bloco; laco: o bloco do laco */
int kind; /* VF_* */
long long n; /* REPEAT: voltas que faltam */
bool in_iter; /* laco: uma volta esta em andamento */
int phase; /* TRY: 0 tente, 1 se der erro, 2 finalmente */
char pend[200]; /* TRY: erro a relancar depois do finalmente */
char saved[200]; /* TRY: "erro capturado" de fora (restaura) */
} VmFrame;
#define VM_STACK 64
#define VM_THREADS 32
@@ -739,6 +783,7 @@ typedef struct Ed {
/* Diálogo modal "Criar um Bloco" (estilo Scratch) */
bool comp_dialog_open;
int comp_dialog_def; /* -1 = novo; senão índice em user_blocks */
bool comp_dialog_in_tab; /* novo bloco: chapéu "defina" na aba atual */
bool comp_dialog_editing; /* true = edição de nome/rótulo em andamento */
int comp_dialog_edit_part; /* índice da parte em edição, -1 = nome do bloco */
char comp_dialog_name[48];
@@ -752,6 +797,19 @@ typedef struct Ed {
bool ctx_menu_open;
bool ctx_export; /* menu de contexto aberto e o de exportacao */
int ctx_menu_bi;
int ctx_menu_grp; /* grupo sob o clique direito, ou -1 */
float ctx_wx, ctx_wy; /* ponto do clique na area de trabalho */
/* Grupos: arrasto (1 = mover com o conteudo, 2 = redimensionar) e titulo */
int grp_drag, grp_mode;
float grp_mx, grp_my, grp_ox, grp_oy, grp_ow, grp_oh;
int grp_mem[MAX_WS], grp_mem_n; /* pilhas levadas junto */
float grp_mem_pos[MAX_WS][2];
int grp_sub[MAX_GROUPS], grp_sub_n; /* grupos de dentro */
float grp_sub_pos[MAX_GROUPS][2];
int grp_edit; /* titulo em edicao, ou -1 */
int grp_last_click;
unsigned grp_last_ms;
int ctx_menu_x, ctx_menu_y;
int ctx_menu_hover;
int ctx_items[8];
@@ -934,6 +992,7 @@ bool hit_libman_foot(Ed* ed, float mx, float my);
/* Abas de codigo/imagem + tooltip de metadados */
bool tab_new_kind(Ed* ed, const char* name, bool is_composite, int kind);
bool tab_has_define(const Tab* T);
void tab_doc_free(Tab* T);
void code_rehighlight(Tab* T);
void open_code_at(Ed* ed, const char* file, int line);
+533 -47
View File
@@ -217,11 +217,14 @@ static int input_count(const TinyBlocks_TypeBlock* t) {
static Shape shape_of(const TinyBlocks_TypeBlock* t) {
if (!t || !t->type_name) return SH_STACK;
const char* n = t->type_name;
if (strncmp(n, "Events.", 7) == 0) return SH_HAT;
if (strncmp(n, "Events.", 7) == 0 ||
strcmp(n, "Port.Define") == 0) return SH_HAT;
if (strcmp(n, "Control.If") == 0 || strcmp(n, "Control.Repeat") == 0 ||
strcmp(n, "Control.RepeatUntil") == 0 ||
strcmp(n, "Control.Forever") == 0) return SH_C1;
if (strcmp(n, "Control.IfElse") == 0) return SH_C2;
if (strcmp(n, "Control.IfElse") == 0 ||
strcmp(n, "Errors.TryCatch") == 0) return SH_C2;
if (strcmp(n, "Errors.Try") == 0) return SH_C3;
if (strcmp(n, "Operators.Lt") == 0 || strcmp(n, "Operators.Eq") == 0 ||
strcmp(n, "Operators.Gt") == 0 || strcmp(n, "Operators.And") == 0 ||
strcmp(n, "Operators.Or") == 0 || strcmp(n, "Operators.Not") == 0)
@@ -238,6 +241,16 @@ static Shape shape_of(const TinyBlocks_TypeBlock* t) {
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) {
const char* n = t && t->type_name ? t->type_name : "";
if (!strncmp(n, "Errors.Try", 10)) return k == 0 ? "se der erro" : "finalmente";
return "senão";
}
/* Bloco "tampa" (como o "sempre" do Scratch): nada encaixa embaixo dele */
static bool is_cap(const TinyBlocks_TypeBlock* t) {
return t && t->type_name && strcmp(t->type_name, "Control.Forever") == 0;
@@ -369,7 +382,7 @@ static int blk_alloc(Tab* T) {
memset(b, 0, sizeof(*b));
b->used = true;
b->parent = -1; b->prel = REL_NONE; b->next = -1;
b->sub[0] = b->sub[1] = -1;
b->sub[0] = b->sub[1] = b->sub[2] = -1;
for (int s = 0; s < MAX_INPUTS; s++) b->args[s] = -1;
return i;
}
@@ -477,7 +490,7 @@ static void mark_drag(Tab* T, int bi, bool v) {
EdBlock* b = &T->ws[bi];
b->dragging = v;
for (int s = 0; s < MAX_INPUTS; s++) if (b->args[s] >= 0) mark_drag(T, b->args[s], v);
for (int k = 0; k < 2; k++) if (b->sub[k] >= 0) mark_drag(T, b->sub[k], v);
for (int k = 0; k < MAX_MOUTHS; k++) if (b->sub[k] >= 0) mark_drag(T, b->sub[k], v);
}
}
@@ -491,7 +504,7 @@ static int copy_tree(Tab* S, int si, Tab* D, bool with_next) {
const EdBlock* o = &S->ws[c];
*n = *o;
n->parent = -1; n->prel = REL_NONE; n->next = -1;
n->sub[0] = n->sub[1] = -1;
n->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++) {
@@ -516,7 +529,7 @@ static void free_tree(Ed* ed, Tab* T, int bi) {
EdBlock* b = &T->ws[bi];
int nx = b->next;
for (int s = 0; s < MAX_INPUTS; s++) if (b->args[s] >= 0) free_tree(ed, T, b->args[s]);
for (int k = 0; k < 2; k++) if (b->sub[k] >= 0) free_tree(ed, T, b->sub[k]);
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;
@@ -699,15 +712,15 @@ static void measure(Tab* T, int bi) {
switch (sh) {
case SH_HAT: if (w < HAT_CAP_W + 16) w = HAT_CAP_W + 16; break;
case SH_STACK: if (w < 64) w = 64; break;
case SH_C1: case SH_C2: {
int mouths = sh == SH_C2 ? 2 : 1;
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 == 0 && mouths == 2) y += MID_H;
if (k < mouths - 1) y += MID_H;
}
h = y + BOT_H;
if (w < 150) w = 150;
@@ -730,7 +743,7 @@ static void place(Tab* T, int bi, float x, float y) {
b->ax = x; b->ay = y;
for (int s = 0; s < MAX_INPUTS; s++)
if (b->args[s] >= 0) place(T, b->args[s], x + b->slot_x[s], y + b->slot_y[s]);
for (int k = 0; k < 2; k++)
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]);
}
@@ -753,9 +766,11 @@ static bool body_contains(const EdBlock* b, float x, float y) {
if (!in_rect(x, y, b->ax, b->ay, b->w, b->h)) return false;
float lx = x - b->ax, ly = y - b->ay;
Shape sh = shape_of(b->type);
if (sh == SH_C1 || sh == SH_C2) {
if (shape_mouths(sh) > 0) {
if (lx < ARM_W || ly < b->row_h || ly >= b->h - BOT_H) return true;
return sh == SH_C2 && ly >= b->sub_y[0] + b->sub_h[0] && ly < b->sub_y[1];
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;
@@ -771,7 +786,7 @@ static int hit_one(Tab* T, int bi, float x, float y) {
int r = hit_one(T, b->args[s], x, y);
if (r >= 0) return r;
}
for (int k = 0; k < 2; k++) {
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;
@@ -871,14 +886,15 @@ static void render_block(Ed* ed, TinyBlocks_RenderableBlock* rb, Tab* T, int bi,
rb_fill_rrect(rb, x+1, y+1, HAT_CAP_W-2, HAT_CAP*2 + 2, HAT_CAP-1, c);
rb_fill_rrect(rb, x+1, y + HAT_CAP + 1, w-2, h - HAT_CAP - 2, 3, c);
break;
case SH_C1: case SH_C2: {
float r[4][4] = {
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 = sh == SH_C2 ? 4 : 3;
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;
@@ -910,11 +926,12 @@ static void render_block(Ed* ed, TinyBlocks_RenderableBlock* rb, Tab* T, int bi,
else if (b->args[p->arg] < 0)
draw_slot(rb, b, p->arg, x, y, d, can_edit && ed->edit_in == p->arg);
}
if (sh == SH_C2)
rb_text_c(rb, x + BLK_PAD, y + b->sub_y[0] + b->sub_h[0] + MID_H*0.5f, "senão", COL_WHITE, FS);
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 = sh == SH_C1 ? 1 : sh == SH_C2 ? 2 : 0;
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);
@@ -1091,13 +1108,33 @@ static TinyBlocks_Value eval_arg(Ed* ed, Tab* T, int bi, int s) {
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;
}
/* Roda uma pilha de uma vez (corpo de Meus Blocos). Um erro para a pilha e
fica pendente para quem chamou (o "tente" mais proximo trata). */
static void run_chain(Ed* ed, Tab* T, int head) {
for (int bi = head; bi >= 0 && step(ed); bi = T->ws[bi].next) {
for (int bi = head; bi >= 0 && !err_pending(ed) && step(ed); bi = T->ws[bi].next) {
EdBlock* b = &T->ws[bi];
TinyBlocks_TypeBlock* t = blk_type(ed, b);
if (!t) continue;
@@ -1109,24 +1146,42 @@ static void run_chain(Ed* ed, Tab* T, int head) {
TinyBlocks_Value v = eval_arg(ed, T, bi, 0);
long long n = value_to_ll(&v);
tb_value_free(&v);
for (long long k = 0; k < n && step(ed); k++) run_chain(ed, T, b->sub[0]);
for (long long k = 0; k < n && !err_pending(ed) && step(ed); k++) run_chain(ed, T, b->sub[0]);
} else if (strcmp(tn, "Control.RepeatUntil") == 0) {
for (;;) {
TinyBlocks_Value v = eval_arg(ed, T, bi, 0);
bool done = value_truthy(&v);
tb_value_free(&v);
if (done || !step(ed)) break;
if (done || err_pending(ed) || !step(ed)) break;
run_chain(ed, T, b->sub[0]);
}
} else if (strcmp(tn, "Control.Forever") == 0) {
/* dentro de Meus Blocos roda sem pausar: so o limite de passos para */
while (step(ed)) run_chain(ed, T, b->sub[0]);
while (!err_pending(ed) && step(ed)) run_chain(ed, T, b->sub[0]);
} else if (strcmp(tn, "Control.If") == 0 || strcmp(tn, "Control.IfElse") == 0) {
TinyBlocks_Value v = eval_arg(ed, T, bi, 0);
bool cond = value_truthy(&v);
tb_value_free(&v);
if (err_pending(ed)) return;
if (cond) run_chain(ed, T, b->sub[0]);
else if (sh == SH_C2) run_chain(ed, T, b->sub[1]);
} else if (strcmp(tn, "Errors.TryCatch") == 0 || strcmp(tn, "Errors.Try") == 0) {
run_chain(ed, T, b->sub[0]);
if (ed->abort) return;
if (err_pending(ed)) { /* se der erro */
char msg[200], saved[200];
err_take(ed, msg, sizeof(msg));
snprintf(saved, sizeof(saved), "%s", tinyblocks_caught_error(ed->rt));
tinyblocks_set_caught_error(ed->rt, msg);
run_chain(ed, T, b->sub[1]);
tinyblocks_set_caught_error(ed->rt, saved);
}
if (sh == SH_C3 && !ed->abort) { /* finalmente: sempre */
char pend[200] = "";
if (err_pending(ed)) err_take(ed, pend, sizeof(pend));
run_chain(ed, T, b->sub[2]);
if (pend[0] && !err_pending(ed)) tinyblocks_set_error(ed->rt, "%s", pend);
}
} else {
TinyBlocks_Block* r = get_rt(ed, T, bi);
if (r) tb_block_eval(r, ed->rt);
@@ -1146,6 +1201,7 @@ static void vm_push(Ed* ed, VmThread* th, Tab* T, int bi, int kind, long long n)
if (th->sp >= VM_STACK) { run_abort(ed, "blocos aninhados demais"); return; }
VmFrame* f = &th->st[th->sp++];
f->T = T; f->bi = bi; f->kind = kind; f->n = n; f->in_iter = false;
f->phase = 0; f->pend[0] = f->saved[0] = 0;
}
static void vm_start(Ed* ed, Tab* T, int head) {
@@ -1157,11 +1213,59 @@ static void vm_start(Ed* ed, Tab* T, int head) {
ed->vm_running = true;
}
/* Um erro na thread: desempilha ate o "tente" mais proximo e entra no
"se der erro" (ou no "finalmente", guardando o erro para depois).
false = ninguem tratou (a thread acaba). */
static bool vm_throw(Ed* ed, VmThread* th) {
char msg[200];
err_take(ed, msg, sizeof(msg));
while (th->sp > 0) {
VmFrame* f = &th->st[th->sp - 1];
if (f->kind != VF_TRY) { th->sp--; continue; }
EdBlock* B = &f->T->ws[f->bi];
bool has_finally = shape_of(B->type) == SH_C3;
if (f->phase == 0) { /* no tente: vai para o se der erro */
f->phase = 1;
snprintf(f->saved, sizeof(f->saved), "%s", tinyblocks_caught_error(ed->rt));
tinyblocks_set_caught_error(ed->rt, msg);
vm_push(ed, th, f->T, B->sub[1], VF_CHAIN, 0);
return true;
}
if (f->phase == 1) tinyblocks_set_caught_error(ed->rt, f->saved);
if (f->phase == 1 && has_finally) { /* erro no se der erro: finalmente e relanca */
f->phase = 2;
snprintf(f->pend, sizeof(f->pend), "%s", msg);
vm_push(ed, th, f->T, B->sub[2], VF_CHAIN, 0);
return true;
}
th->sp--; /* erro no finalmente: sobe */
}
err_uncaught(ed, msg);
return false;
}
/* Executa a thread ate a proxima pausa (true) ou ate terminar (false) */
static bool vm_step(Ed* ed, VmThread* th) {
while (th->sp > 0 && !ed->abort) {
if (err_pending(ed) && !vm_throw(ed, th)) break;
if (th->sp <= 0) break;
VmFrame* f = &th->st[th->sp - 1];
Tab* T = f->T;
if (f->kind == VF_TRY) { /* uma parte do tente acabou bem */
EdBlock* B = &T->ws[f->bi];
bool has_finally = B->used && shape_of(B->type) == SH_C3;
if (f->phase == 1) tinyblocks_set_caught_error(ed->rt, f->saved);
if (f->phase < 2 && has_finally) {
f->phase = 2;
vm_push(ed, th, T, B->sub[2], VF_CHAIN, 0);
continue;
}
char pend[200];
snprintf(pend, sizeof(pend), "%s", f->pend);
th->sp--;
if (pend[0]) tinyblocks_set_error(ed->rt, "%s", pend); /* relanca */
continue;
}
if (f->kind != VF_CHAIN) {
EdBlock* L = &T->ws[f->bi];
if (!L->used) { th->sp--; continue; } /* laco apagado com o programa rodando */
@@ -1202,8 +1306,12 @@ static bool vm_step(Ed* ed, VmThread* th) {
TinyBlocks_Value v = eval_arg(ed, T, bi, 0);
bool cond = value_truthy(&v);
tb_value_free(&v);
if (err_pending(ed)) continue;
if (cond) vm_push(ed, th, T, b->sub[0], VF_CHAIN, 0);
else if (sh == SH_C2) vm_push(ed, th, T, b->sub[1], VF_CHAIN, 0);
} else if (strcmp(tn, "Errors.TryCatch") == 0 || strcmp(tn, "Errors.Try") == 0) {
vm_push(ed, th, T, bi, VF_TRY, 0);
vm_push(ed, th, T, b->sub[0], VF_CHAIN, 0);
} else {
TinyBlocks_Block* r = get_rt(ed, T, bi);
if (r) tb_block_eval(r, ed->rt);
@@ -1256,7 +1364,10 @@ static void cap_end(Ed* ed) {
}
/* 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;
@@ -1467,6 +1578,12 @@ static CallFrame* cur_frame(void) {
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();
@@ -1493,13 +1610,118 @@ static void eval_port_out(TinyBlocks_Block* self, TinyBlocks* rt) {
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 (T->kind != TK_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 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");
TinyBlocks_TypeBlock* t_in = tb_type_block_find(ed->rt, "Port.In");
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);
float px = 40 + T->ws[hat].w + 24;
for (int k = 0; t_in && k < def->input_count; k++) {
int bi = blk_new(T, t_in);
if (bi < 0) break;
snprintf(T->ws[bi].in_text[0], sizeof(T->ws[bi].in_text[0]), "%s", def->input_names[k]);
T->ws[bi].x = px;
T->ws[bi].y = y + 6;
top_add(T, bi);
layout_tab(T);
px += T->ws[bi].w + 12;
}
/* 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);
if (!def || !def->snap) return;
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++];
@@ -1511,7 +1733,12 @@ static void eval_composite(TinyBlocks_Block* self, TinyBlocks* rt) {
for (int i = 0; i < def->input_count; i++)
f->in[i] = tb_value_clone(tb_block_get_input(self, rt, (uint32_t)i));
/* Roda os scripts da definição de cima para baixo */
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];
@@ -1523,6 +1750,7 @@ static void eval_composite(TinyBlocks_Block* self, TinyBlocks* rt) {
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();
@@ -1580,7 +1808,8 @@ static bool type_hidden(Ed* ed, const TinyBlocks_TypeBlock* t) {
if (!n || n[0] == '_' || strstr(n, "._")) return true;
if (strncmp(n, "Editor.", 7) == 0 || strncmp(n, "Graphics.", 9) == 0) return true;
if (strcmp(n, "Literal.Integer") == 0 || strcmp(n, "Literal.Real") == 0) return true;
if (strncmp(n, "Port.", 5) == 0) return !CT.is_composite;
if (strcmp(n, "Port.Define") == 0) return true; /* nasce pelo "Criar um Bloco" */
if (strncmp(n, "Port.", 5) == 0) return !CT.is_composite && !tab_has_define(&CT);
return false;
}
@@ -2229,13 +2458,22 @@ static void tab_close(Ed* ed, int ti) {
: 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 = CT.kind == TK_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;
@@ -2315,13 +2553,18 @@ static void comp_register(Ed* ed, UserBlockDef* def, Tab* T) {
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; }
if (!def->snap) def->snap = (Tab*)malloc(sizeof(Tab));
if (def->snap) *def->snap = *T;
TinyBlocks_SlotDesc in_s[MAX_UBLK_SLOTS], out_s[MAX_UBLK_SLOTS];
for (int i = 0; i < def->input_count; i++) in_s[i] = (TinyBlocks_SlotDesc){def->input_names[i], TB_VALUE_NONE};
for (int i = 0; i < def->output_count; i++) out_s[i] = (TinyBlocks_SlotDesc){def->output_names[i], TB_VALUE_NONE};
@@ -2331,8 +2574,6 @@ static void comp_register(Ed* ed, UserBlockDef* def, Tab* T) {
def->input_count ? in_s : NULL, (uint32_t)def->input_count,
def->output_count ? out_s : NULL, (uint32_t)def->output_count,
eval_composite);
def->tab_idx = (int)(T - ed->tabs);
retype_all(ed);
}
@@ -2379,6 +2620,12 @@ static TbBlueprint* ed_to_blueprint(Ed* ed) {
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;
@@ -2387,7 +2634,7 @@ static TbBlueprint* ed_to_blueprint(Ed* ed) {
snprintf(o->type, sizeof(o->type), "%s", b->type_name);
o->x = b->x; o->y = b->y;
o->parent = b->parent; o->prel = b->prel; o->next = b->next;
for (int k = 0; k < 2; k++) o->sub[k] = b->sub[k];
for (int 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]);
@@ -2434,7 +2681,7 @@ 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] = -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++) {
@@ -2446,7 +2693,7 @@ static void bp_tab_load(Ed* ed, const TbBpTab* B, Tab* T) {
b->type = b->type_name[0] ? tb_type_block_find(ed->rt, b->type_name) : NULL;
b->x = o->x; b->y = o->y;
b->parent = o->parent; b->prel = o->prel; b->next = o->next;
for (int k = 0; k < 2; k++) b->sub[k] = o->sub[k];
for (int 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]);
@@ -2468,7 +2715,7 @@ static void blueprint_apply(Ed* ed, const TbBlueprint* bp) {
free(d->snap); d->snap = NULL;
}
ed->user_block_n = 0;
for (int t = 0; t < ed->tab_n; t++) memset(&ed->tabs[t], 0, sizeof(Tab));
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();
@@ -2502,6 +2749,12 @@ static void blueprint_apply(Ed* ed, const TbBlueprint* bp) {
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++) {
@@ -2510,6 +2763,15 @@ static void blueprint_apply(Ed* ed, const TbBlueprint* bp) {
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++) {
@@ -2587,6 +2849,7 @@ static int sb_shape(const char* type, void* ud) {
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;
@@ -2906,6 +3169,7 @@ static void dlg_card_rect(float* w, float* h) {
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;
@@ -3012,6 +3276,30 @@ static void dlg_ok(Ed* ed) {
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);
@@ -4046,15 +4334,17 @@ void render_plus_menu(Ed* ed, TinyBlocks_RenderableBlock* rb) {
if (!ed->plus_menu_open) return;
float px, py;
plus_menu_pos(ed, &px, &py);
const int n = 3;
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[3] = { "Blueprint", "Edicao de Imagem", "Editor de Codigo" };
const char* subs[3] = { "montar um bloco novo", "editar SVG/imagem", "editar .c/.py/..." };
static const Col dots[3] = {{0.30f,0.62f,1.f,1.f}, {0.98f,0.62f,0.25f,1.f}, {0.42f,0.72f,0.35f,1.f}};
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;
@@ -4105,6 +4395,130 @@ void render_tooltip(Ed* ed, TinyBlocks_RenderableBlock* rb) {
rb_text_c(rb, x + 12, y + h - 8, "clique para abrir o codigo nesta linha", COL_TEXT_DIM, 9.f);
}
/* == 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) {
if (CT.kind == TK_CODE) { render_code_tab(ed, rb); return; }
if (CT.kind == TK_IMAGE) { render_image_tab(ed, rb); return; }
@@ -4119,7 +4533,9 @@ static void render_workspace(Ed* ed, TinyBlocks_RenderableBlock* rb) {
for (float gy = WS_Y - offy; gy < WS_Y + WS_H; gy += g)
rb_fill_rect(rb, gx, gy, 2, 2, COL_GRID);
if (CT.top_n == 0) {
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á";
@@ -4334,6 +4750,11 @@ static const char* ctx_label(int 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";
@@ -4948,7 +5369,7 @@ static void compute_snap(Ed* ed) {
if (ds != SH_HAT) {
if (!is_cap(B->type) && !(drag_cap && B->next >= 0))
consider(ed, &best, SN_NEXT, i, 0, d->x, d->y, B->ax, B->ay + B->h);
int mouths = bs == SH_C1 ? 1 : bs == SH_C2 ? 2 : 0;
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]);
@@ -5337,6 +5758,26 @@ static void ctx_exec(Ed* ed, int id) {
case CM_EDIT_DEF: if (T->ws[bi].type) open_def(ed, T->ws[bi].type->type_name + 5); break;
case CM_CLEANUP: cleanup_ws(ed); break;
case CM_NEW_COMPOSITE: new_composite_tab(ed); break;
case CM_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;
@@ -5357,12 +5798,13 @@ static void on_lmb_down(Ed* ed, float mx, float my) {
float px, py;
plus_menu_pos(ed, &px, &py);
int hit = -1;
for (int i = 0; i < 3; i++)
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) { dlg_open(ed, -1); return; }
if (hit == 1) { tab_new_kind(ed, "Imagem", false, TK_IMAGE); palette_rebuild(ed); return; }
if (hit == 2) {
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);
@@ -5513,7 +5955,22 @@ static void on_lmb_down(Ed* ed, float mx, float my) {
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;
@@ -5605,6 +6062,7 @@ static void on_lmb_up(Ed* ed, float mx, float my) {
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 (CT.kind == TK_IMAGE && CT.img_drag) { image_release(ed, mx, my); ed->state = ES_IDLE; return; }
if (ed->state == ES_DRAG && ed->drag_bi >= 0) {
@@ -5637,16 +6095,28 @@ static void on_rmb_down(Ed* ed, float mx, float my) {
if (ed->ctx_menu_open) { ed->ctx_menu_open = false; ed->ctx_export = false; return; }
if (ed->state != ES_IDLE) return;
if (!in_ws(ed, mx, my)) return;
int bi = hit_ws(&CT, mx - WS_X + CT.ws_sx, my - WS_Y + CT.ws_sy);
if (CT.kind != TK_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) {
ed->ctx_items[ed->ctx_n++] = CM_DUPLICATE;
ed->ctx_items[ed->ctx_n++] = CM_DELETE;
const TinyBlocks_TypeBlock* t = CT.ws[bi].type;
if (t && strncmp(t->type_name, "User.", 5) == 0) ed->ctx_items[ed->ctx_n++] = CM_EDIT_DEF;
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;
@@ -5702,6 +6172,16 @@ static void on_key(Ed* ed, int sc, bool 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; }
@@ -5765,6 +6245,8 @@ static void on_text(Ed* ed, const char* typed) {
ed->path_input_len = (int)strlen(ed->path_input_buf);
} else if (CT.kind == TK_CODE) {
code_text(ed, typed);
} 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);
@@ -5929,7 +6411,7 @@ static void ed_handle_input(Ed* ed, TinyBlocks_Block* evb, int from) {
if (ed->plus_menu_open) {
float px, py;
plus_menu_pos(ed, &px, &py);
for (int i = 0; i < 3; i++)
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;
}
@@ -5972,6 +6454,8 @@ static void ed_handle_input(Ed* ed, TinyBlocks_Block* evb, int from) {
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);
@@ -6263,6 +6747,7 @@ static bool editor_instance_init(TinyBlocks_Block* self, TinyBlocks* rt) {
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);
@@ -6357,6 +6842,7 @@ static bool editor_lib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
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);
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);