From 9f6a1a0eb067192ea5dac6e12cc3fe408757e162 Mon Sep 17 00:00:00 2001 From: mguinhos Date: Thu, 22 Oct 2026 18:39:01 -0300 Subject: [PATCH] =?UTF-8?q?Editor:=20"defina"=20na=20pr=C3=B3pria=20aba,?= =?UTF-8?q?=20grupos=20coloridos=20e=20tente/se=20der=20erro/finalmente?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Criar um Bloco põe o chapéu "defina " 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 --- Makefile | 6 +- examples/editor/main.c | 2 + .../tinyblocks-blueprint/include/blueprint.h | 14 +- .../tinyblocks-blueprint/src/blueprint.c | 6 +- .../tinyblocks-blueprint/src/serialize.c | 43 +- .../internal/tb_editor_internal.h | 71 ++- libraries/tinyblocks-editor/src/tb_editor.c | 580 ++++++++++++++++-- tests/editor_harness.c | 136 +++- 8 files changed, 774 insertions(+), 84 deletions(-) diff --git a/Makefile b/Makefile index 6912343..ffc21d3 100644 --- a/Makefile +++ b/Makefile @@ -76,7 +76,7 @@ SRCS := src/tinyblocks.c \ OBJS := $(patsubst src/%.c,$(BUILD)/%.o,$(SRCS)) OBJS_DBG := $(patsubst src/%.c,$(BUILD)/%-dbg.o,$(SRCS)) -CAT_LIBS := events control input operators number string variables vector appearance pen fs os environ +CAT_LIBS := events control errors input operators number string variables vector appearance pen fs os environ CAT_A := $(foreach l,$(CAT_LIBS),$(LIBDIR)/tinyblocks-$(l)/build/libtinyblocks-$(l).a) CAT_LDFLAGS := $(foreach l,$(CAT_LIBS),-ltinyblocks-$(l)) CAT_INCS := $(foreach l,$(CAT_LIBS),-I$(LIBDIR)/tinyblocks-$(l)/include) @@ -101,7 +101,7 @@ LIB_LDFLAGS := -L$(ED_DIR)/build -L$(GX_DIR)/build -L$(SD_DIR)/build \ test-toml test-plugin test-blueprint test-base64 test-curves test-meta test-ppm test-bmp test-png test-image test-vg test-svg test-jpg \ test-syntax test-os test-vars test-scratchblocks test-input test-stdlib test-regex test-markdown test-opentype \ category-libs category-sos libs \ - lib-events lib-control lib-input lib-operators lib-number lib-string lib-variables lib-vector lib-appearance lib-pen lib-fs lib-os \ + lib-events lib-control lib-errors lib-input lib-operators lib-number lib-string lib-variables lib-vector lib-appearance lib-pen lib-fs lib-os \ lib-environ \ lib-editor lib-graphics lib-sdl2 lib-python lib-mcp lib-toml \ lib-json lib-xml lib-csv lib-blueprint lib-base64 lib-curves lib-ppm lib-bmp lib-png lib-image lib-vg lib-svg lib-jpg lib-syntax lib-scratchblocks lib-regex lib-markdown lib-opentype lib-api lib-libman \ @@ -240,7 +240,7 @@ lib-python: lib-mcp: $(MAKE) -C $(MC_DIR) -libs: static lib-events lib-control lib-operators lib-variables \ +libs: static lib-events lib-control lib-errors lib-operators lib-variables \ lib-appearance lib-pen lib-fs lib-os lib-input lib-number lib-string lib-vector lib-environ lib-graphics lib-sdl2 lib-toml \ lib-json lib-xml lib-csv lib-blueprint lib-base64 lib-curves lib-ppm lib-bmp lib-png lib-image lib-vg lib-svg lib-jpg lib-syntax lib-scratchblocks lib-regex lib-markdown lib-opentype lib-api lib-libman lib-editor @echo "Libraries OK: category + graphics + sdl2 + toml + json + xml + csv + blueprint + base64 + curves + ppm + bmp + png + image + vg + svg + jpg + syntax + regex + markdown + opentype + api + libman + editor" diff --git a/examples/editor/main.c b/examples/editor/main.c index e00f14d..4cfa477 100644 --- a/examples/editor/main.c +++ b/examples/editor/main.c @@ -30,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -66,6 +67,7 @@ int main(int argc, char** argv) { Preferimos o .so: recompilar a library recarrega a paleta ao vivo. */ reg_core(rt, "tinyblocks-events", tb_events_get_library); reg_core(rt, "tinyblocks-control", tb_control_get_library); + reg_core(rt, "tinyblocks-errors", tb_errors_get_library); reg_core(rt, "tinyblocks-input", tb_input_get_library); reg_core(rt, "tinyblocks-operators", tb_operators_get_library); reg_core(rt, "tinyblocks-number", tb_number_get_library); diff --git a/libraries/tinyblocks-blueprint/include/blueprint.h b/libraries/tinyblocks-blueprint/include/blueprint.h index df46e9b..0f3bcad 100644 --- a/libraries/tinyblocks-blueprint/include/blueprint.h +++ b/libraries/tinyblocks-blueprint/include/blueprint.h @@ -27,6 +27,7 @@ #define TB_BP_MAX_USLOTS 8 #define TB_BP_MAX_VARS 64 #define TB_BP_LIT_CAP 512 +#define TB_BP_MAX_GROUPS 32 /* Formatos de serializacao */ enum { TB_BP_FMT_JSON, TB_BP_FMT_XML, TB_BP_FMT_CSV }; @@ -35,7 +36,7 @@ enum { TB_BP_FMT_JSON, TB_BP_FMT_XML, TB_BP_FMT_CSV }; #define TB_BP_REL_NONE (-1) #define TB_BP_REL_NEXT 0 #define TB_BP_REL_SUB0 1 -#define TB_BP_REL_ARG0 3 +#define TB_BP_REL_ARG0 4 /* bocas 0..2 (SUB0..SUB0+2); era 3 no formato v1 */ /* -- Blocos e abas --- */ typedef struct { @@ -44,12 +45,19 @@ typedef struct { float x, y; int parent, prel; int next; - int sub[2]; + int sub[3]; int args[TB_BP_MAX_INPUTS]; char in_text[TB_BP_MAX_INPUTS][64]; char lit[TB_BP_LIT_CAP]; } TbBpBlock; +/* Grupo: retangulo colorido com titulo que junta varias pilhas */ +typedef struct { + float x, y, w, h; + int color; + char title[48]; +} TbBpGroup; + typedef struct { TbBpBlock blocks[TB_BP_MAX_WS]; int top[TB_BP_MAX_WS]; @@ -59,6 +67,8 @@ typedef struct { bool composite; int comp_id; /* indice em user_blocks, ou -1 */ int color_idx; + TbBpGroup groups[TB_BP_MAX_GROUPS]; + int group_n; } TbBpTab; /* -- Blocos compostos (protótipo) --- */ diff --git a/libraries/tinyblocks-blueprint/src/blueprint.c b/libraries/tinyblocks-blueprint/src/blueprint.c index 12c7435..48eced4 100644 --- a/libraries/tinyblocks-blueprint/src/blueprint.c +++ b/libraries/tinyblocks-blueprint/src/blueprint.c @@ -29,7 +29,7 @@ void tb_blueprint_clear(TbBlueprint* bp) { t->blocks[b].parent = -1; t->blocks[b].prel = TB_BP_REL_NONE; t->blocks[b].next = -1; - t->blocks[b].sub[0] = t->blocks[b].sub[1] = -1; + t->blocks[b].sub[0] = t->blocks[b].sub[1] = t->blocks[b].sub[2] = -1; for (int s = 0; s < TB_BP_MAX_INPUTS; s++) t->blocks[b].args[s] = -1; } } @@ -49,7 +49,7 @@ int tb_blueprint_add_tab(TbBlueprint* bp, const char* name, bool composite) { t->blocks[b].parent = -1; t->blocks[b].prel = TB_BP_REL_NONE; t->blocks[b].next = -1; - t->blocks[b].sub[0] = t->blocks[b].sub[1] = -1; + t->blocks[b].sub[0] = t->blocks[b].sub[1] = t->blocks[b].sub[2] = -1; for (int s = 0; s < TB_BP_MAX_INPUTS; s++) t->blocks[b].args[s] = -1; } return idx; @@ -70,7 +70,7 @@ int tb_blueprint_alloc_block(TbBpTab* t) { b->parent = -1; b->prel = TB_BP_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 < TB_BP_MAX_INPUTS; s++) b->args[s] = -1; return i; } diff --git a/libraries/tinyblocks-blueprint/src/serialize.c b/libraries/tinyblocks-blueprint/src/serialize.c index 457b82f..74f3cf3 100644 --- a/libraries/tinyblocks-blueprint/src/serialize.c +++ b/libraries/tinyblocks-blueprint/src/serialize.c @@ -28,7 +28,7 @@ TinyBlocks_JsonValue* tb_blueprint_to_json(const TbBlueprint* bp) { TinyBlocks_JsonValue* root = tb_json_object(); if (!root) return NULL; PUT(root, "format", tb_json_string("tinyblocks-project")); - PUT(root, "version", tb_json_number(1)); + PUT(root, "version", tb_json_number(2)); /* v2: 3 bocas, REL_ARG0 = 4 */ PUT(root, "cur_tab", tb_json_number(bp->cur_tab)); TinyBlocks_JsonValue* tabs = tb_json_array(); @@ -57,7 +57,7 @@ TinyBlocks_JsonValue* tb_blueprint_to_json(const TbBlueprint* bp) { PUT(o, "prel", tb_json_number(b->prel)); PUT(o, "next", tb_json_number(b->next)); TinyBlocks_JsonValue* sub = tb_json_array(); - for (int k = 0; k < 2; k++) { TinyBlocks_JsonValue* e = tb_json_number(b->sub[k]); tb_json_array_push(sub, e); tb_json_release(e); } + for (int k = 0; k < 3; k++) { TinyBlocks_JsonValue* e = tb_json_number(b->sub[k]); tb_json_array_push(sub, e); tb_json_release(e); } PUT(o, "sub", sub); TinyBlocks_JsonValue* args = tb_json_array(); for (int s = 0; s < TB_BP_MAX_INPUTS; s++) { TinyBlocks_JsonValue* e = tb_json_number(b->args[s]); tb_json_array_push(args, e); tb_json_release(e); } @@ -72,6 +72,22 @@ TinyBlocks_JsonValue* tb_blueprint_to_json(const TbBlueprint* bp) { TinyBlocks_JsonValue* top = tb_json_array(); PUT(jt, "top", top); for (int i = 0; i < T->top_n; i++) { TinyBlocks_JsonValue* e = tb_json_number(T->top[i]); tb_json_array_push(top, e); tb_json_release(e); } + if (T->group_n > 0) { + TinyBlocks_JsonValue* jg = tb_json_array(); + PUT(jt, "groups", jg); + for (int g = 0; g < T->group_n; g++) { + const TbBpGroup* G = &T->groups[g]; + TinyBlocks_JsonValue* o = tb_json_object(); + PUT(o, "x", tb_json_number(G->x)); + PUT(o, "y", tb_json_number(G->y)); + PUT(o, "w", tb_json_number(G->w)); + PUT(o, "h", tb_json_number(G->h)); + PUT(o, "color", tb_json_number(G->color)); + PUT(o, "title", tb_json_string(G->title)); + tb_json_array_push(jg, o); + tb_json_release(o); + } + } tb_json_array_push(tabs, jt); tb_json_release(jt); } @@ -152,6 +168,7 @@ TbBlueprint* tb_blueprint_from_json(const TinyBlocks_JsonValue* root) { if (!root) return NULL; TbBlueprint* bp = tb_blueprint_new(); if (!bp) return NULL; + int version = (int)jget_num(root, "version", 1); TinyBlocks_JsonValue* ubs = tb_json_object_get(root, "user_blocks"); for (uint32_t u = 0; ubs && u < tb_json_array_length(ubs) && bp->user_block_n < TB_BP_MAX_UBLOCKS; u++) { @@ -200,9 +217,10 @@ TbBlueprint* tb_blueprint_from_json(const TinyBlocks_JsonValue* root) { b->y = (float)jget_num(o, "y", 0); b->parent = (int)jget_num(o, "parent", -1); b->prel = (int)jget_num(o, "prel", TB_BP_REL_NONE); + if (version < 2 && b->prel >= 3) b->prel++; /* v1: campos comecavam em 3 */ b->next = (int)jget_num(o, "next", -1); TinyBlocks_JsonValue* sub = tb_json_object_get(o, "sub"); - for (int k = 0; k < 2; k++) { TinyBlocks_JsonValue* e = tb_json_array_get(sub, (uint32_t)k); b->sub[k] = e ? (int)tb_json_as_number(e, -1) : -1; tb_json_release(e); } + for (int k = 0; k < 3; k++) { TinyBlocks_JsonValue* e = tb_json_array_get(sub, (uint32_t)k); b->sub[k] = e ? (int)tb_json_as_number(e, -1) : -1; tb_json_release(e); } tb_json_release(sub); TinyBlocks_JsonValue* args = tb_json_object_get(o, "args"); for (int s = 0; s < TB_BP_MAX_INPUTS; s++) { TinyBlocks_JsonValue* e = tb_json_array_get(args, (uint32_t)s); b->args[s] = e ? (int)tb_json_as_number(e, -1) : -1; tb_json_release(e); } @@ -228,6 +246,21 @@ TbBlueprint* tb_blueprint_from_json(const TinyBlocks_JsonValue* root) { tb_json_release(e); } tb_json_release(top); + + TinyBlocks_JsonValue* jg = tb_json_object_get(jt, "groups"); + T->group_n = 0; + for (uint32_t i = 0; jg && i < tb_json_array_length(jg) && T->group_n < TB_BP_MAX_GROUPS; i++) { + TinyBlocks_JsonValue* o = tb_json_array_get(jg, i); + TbBpGroup* G = &T->groups[T->group_n++]; + G->x = (float)jget_num(o, "x", 0); + G->y = (float)jget_num(o, "y", 0); + G->w = (float)jget_num(o, "w", 300); + G->h = (float)jget_num(o, "h", 200); + G->color = (int)jget_num(o, "color", 0); + snprintf(G->title, sizeof(G->title), "%s", jget_str(o, "title", "")); + tb_json_release(o); + } + tb_json_release(jg); tb_json_release(jt); } tb_json_release(tabs); @@ -360,7 +393,7 @@ static void blueprint_xml(Buf* b, const TbBlueprint* bp) { bs(b, "\n"); bs(b, "\n"); bindent(b, 1); bs(b, "\n"); @@ -391,7 +424,7 @@ static void blueprint_xml(Buf* b, const TbBlueprint* bp) { xattr_num(b, "next", bl->next); bs(b, ">\n"); bindent(b, 5); bs(b, ""); - for (int k = 0; k < 2; k++) { char t[24]; snprintf(t, sizeof(t), "%d", bl->sub[k]); bs(b, t); } + for (int k = 0; k < 3; k++) { char t[24]; snprintf(t, sizeof(t), "%d", bl->sub[k]); bs(b, t); } bs(b, "\n"); bindent(b, 5); bs(b, ""); for (int s = 0; s < TB_BP_MAX_INPUTS; s++) { char t[24]; snprintf(t, sizeof(t), "%d", bl->args[s]); bs(b, t); } diff --git a/libraries/tinyblocks-editor/internal/tb_editor_internal.h b/libraries/tinyblocks-editor/internal/tb_editor_internal.h index d1dc4e5..6496b29 100644 --- a/libraries/tinyblocks-editor/internal/tb_editor_internal.h +++ b/libraries/tinyblocks-editor/internal/tb_editor_internal.h @@ -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); diff --git a/libraries/tinyblocks-editor/src/tb_editor.c b/libraries/tinyblocks-editor/src/tb_editor.c index 90781bb..cf651ff 100644 --- a/libraries/tinyblocks-editor/src/tb_editor.c +++ b/libraries/tinyblocks-editor/src/tb_editor.c @@ -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 ": 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 " 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 " 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. 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); diff --git a/tests/editor_harness.c b/tests/editor_harness.c index 1d564f3..6c68822 100644 --- a/tests/editor_harness.c +++ b/tests/editor_harness.c @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -91,6 +92,20 @@ static bool find(const char* s, int region, int nth, float* x, float* y) { return false; } +/* Bloco "+" na area de trabalho (nao o "+" da barra de abas) */ +static bool block_plus(float* x, float* y, float min_y) { + for (int k = 0; find("+", R_WS, k, x, y); k++) if (*y > min_y) return true; + printf("FAIL não achei o bloco \"+\"\n"); fails++; + return false; +} + +/* Texto s na mesma linha de (ax, ay), a direita de ax */ +static bool find_near(const char* s, float ax, float ay, float* x, float* y) { + for (int k = 0; find(s, R_WS, k, x, y); k++) + if (*y > ay - 6 && *y < ay + 6 && *x > ax) return true; + return false; +} + static bool stage_has(const char* s) { for (uint32_t i = 0; i < ncmd; i++) if (cmds[i].kind == TB_DRAW_TEXT && cmds[i].x >= 920 && strstr(cmds[i].text, s)) return true; @@ -204,6 +219,7 @@ int main(void) { tb_graphics_set_backend(tb_graphics_null_backend()); tb_library_register(rt, tb_events_get_library()); tb_library_register(rt, tb_control_get_library()); + tb_library_register(rt, tb_errors_get_library()); tb_library_register(rt, tb_operators_get_library()); tb_library_register(rt, tb_variables_get_library()); tb_library_register(rt, tb_appearance_get_library()); @@ -300,50 +316,56 @@ int main(void) { if (need("numérica ou texto", R_WS, 0, &x, &y)) click(x, y); type("n"); key(TB_KEY_RETURN, 0, 0); /* OK no diálogo */ - CHECK(ws_has("parâmetro"), "diálogo cria o bloco composto e o corpo com o parâmetro"); + /* como no Scratch: o "defina" aparece na própria aba, com o parâmetro ao lado */ + CHECK(ws_has("defina") && ws_has("parâmetro"), "Criar um Bloco põe \"defina dobro\" e o parâmetro na mesma aba"); + CHECK(ws_has("quando a bandeira for clicado"), "sem abrir aba nova: os scripts continuam ali"); + hx = 0; hy = 0; + need("defina", R_WS, 0, &hx, &hy); if (need("Meus Blocos", R_CAT, 0, &x, &y)) click(x, y); - if (need("devolva", R_FLY, 0, &x, &y)) drag(x, y, 450, 300); + if (need("devolva", R_FLY, 0, &x, &y)) drag(x, y, hx, hy + 44); /* embaixo do "defina" */ if (need("Operadores", R_CAT, 0, &x, &y)) click(x, y); - if (need("+", R_FLY, 0, &x, &y)) drag(x, y, 470, 450); + if (need("+", R_FLY, 0, &x, &y)) drag(x, y, hx + 300, hy + 110); /* encaixa o parâmetro n no slot esquerdo do "+" */ { float px, py, zx, zy; - if (need("parâmetro", R_WS, 0, &px, &py) && need("+", R_WS, 0, &x, &y)) { + if (need("parâmetro", R_WS, 0, &px, &py) && block_plus(&x, &y, hy + 20)) { int k = 0; bool got = false; while (find("0", R_WS, k++, &zx, &zy)) if (zy > y - 4 && zy < y + 4 && zx < x) { got = true; break; } - if (!got) { printf("FAIL slot esquerdo do +\n"); fails++; } + if (!got) { printf("FAIL slot esquerdo do + (+ em %.0f,%.0f)\n", x, y); fails++; } else drag(px, py, px + ((zx - 3 - 10) - (px - 3 - 10)), zy); } } /* digita 1 no slot direito do "+" */ - if (need("+", R_WS, 0, &x, &y)) { + if (block_plus(&x, &y, hy + 20)) { float zx, zy; int k = 0; while (find("0", R_WS, k++, &zx, &zy)) if (zy > y - 4 && zy < y + 4 && zx > x) { click(zx, zy); type("1"); key(TB_KEY_RETURN, 0, 0); break; } } - if (need("+", R_WS, 0, &x, &y) && need("=", R_WS, 0, &x2, &y2)) { + if (block_plus(&x, &y, hy + 20) && need("=", R_WS, 0, &x2, &y2)) { float rep_left = x - 3 - 10; { float px, py; if (find("parâmetro", R_WS, 0, &px, &py)) rep_left = px - 3 - 10 - 10; } drag(x, y, x + ((x2 + 12) - rep_left), y + (y2 - y)); } - if (need("Salvar", R_WS, 0, &x, &y)) click(x, y); - CHECK(find("dobro", R_ANY, 0, &x, &y), "bloco composto salvo"); - if (need("Código", R_ANY, 0, &x, &y)) click(x, y); if (need("Meus Blocos", R_CAT, 0, &x, &y)) click(x, y); - if (need("dobro", R_FLY, 0, &x, &y)) drag(x, y, 650, 640); + CHECK(find("dobro", R_FLY, 0, &x, &y), "bloco dobro aparece em Meus Blocos"); + if (need("dobro", R_FLY, 0, &x, &y)) drag(x, y, hx + 330, hy - 30); { float sx, sy; - if (find("n", R_WS, 0, &sx, &sy)) { + float dx2 = 0, dy2 = 0; + for (int k = 0; find("dobro", R_WS, k, &x, &y); k++) if (y < hy) { dx2 = x; dy2 = y; } + if (dx2 > 0 && find_near("n", dx2, dy2, &sx, &sy)) { click(sx, sy); key(TB_KEY_BACKSPACE, 0, 0); type("21"); key(TB_KEY_RETURN, 0, 0); } } - if (need("dobro", R_WS, 0, &x, &y)) { click(x, y); click(x, y); } + { int k = 0; float bx = 0, by = 0; + while (find("dobro", R_WS, k, &x, &y)) { if (y < hy) { bx = x; by = y; } k++; } /* a chamada, não o "defina" */ + if (bx > 0) { click(bx, by); click(bx, by); } } CHECK(ws_has("22"), "bloco composto dobro(21) = 22"); if (!ws_has("22")) { for (uint32_t i = 0; i < ncmd; i++) if (cmds[i].kind==TB_DRAW_TEXT && in_region(cmds[i].x,R_WS)) printf(" ws: %s (%.0f,%.0f)\n", cmds[i].text, cmds[i].x, cmds[i].y); } @@ -772,9 +794,10 @@ int main(void) { float px = 0, py = 0; if (find_tabbar("+", &px, &py)) click(px, py); else { CHECK(false, "achei o botao +"); } frame(0, 0, 0, 0, 0, 0, NULL); - CHECK(find("Editor de Codigo", R_ANY, 0, &x, &y), "menu '+' lista as opcoes de nova aba"); - CHECK(find("Edicao de Imagem", R_ANY, 0, &x, &y), "menu '+' oferece Edicao de Imagem"); - if (need("Editor de Codigo", R_ANY, 0, &x, &y)) click(x, y); + CHECK(find("Editor de Código", R_ANY, 0, &x, &y) && find("Novo bloco", R_ANY, 0, &x, &y) && + find("Blueprint", R_ANY, 0, &x, &y), "menu '+' lista Blueprint, Novo bloco, Imagem e Código"); + CHECK(find("Edição de Imagem", R_ANY, 0, &x, &y), "menu '+' oferece Edição de Imagem"); + if (need("Editor de Código", R_ANY, 0, &x, &y)) click(x, y); frame(0, 0, 0, 0, 0, 0, NULL); type("int x = 42;"); frame(0, 0, 0, 0, 0, 0, NULL); @@ -784,14 +807,14 @@ int main(void) { CHECK(!any_has(""), "aba de codigo nao mostra a marcacao "); } - /* 23. Botao "+" -> nova aba: Edicao de Imagem */ + /* 23. Botao "+" -> nova aba: Edição de Imagem */ key(TB_KEY_ESCAPE, 0, 0); frame(0, 0, 0, 0, 0, 0, NULL); { float px = 0, py = 0; if (find_tabbar("+", &px, &py)) click(px, py); else { CHECK(false, "achei o botao +"); } frame(0, 0, 0, 0, 0, 0, NULL); - if (need("Edicao de Imagem", R_ANY, 0, &x, &y)) click(x, y); + if (need("Edição de Imagem", R_ANY, 0, &x, &y)) click(x, y); frame(0, 0, 0, 0, 0, 0, NULL); CHECK(find("Camadas", R_WS, 0, &x, &y), "aba de imagem mostra a lista de camadas"); CHECK(find("Salvar", R_WS, 0, &x, &y), "aba de imagem mostra o botao Salvar"); @@ -1004,6 +1027,83 @@ int main(void) { } printf("comandos de desenho no último frame: %u\n", ncmd); + /* 26. Erros: tente / se der erro / finalmente, resultados e erro sem tratamento */ + { + const char* pj = "/tmp/tb_harness_try.json"; + FILE* f = fopen(pj, "wb"); + if (f) { + fputs("{\"format\":\"tinyblocks-project\",\"version\":2,\"cur_tab\":0,\"tabs\":[{\"name\":\"Erros\",\"composite\":false,\"comp_id\":-1,\"color\":0,\"blocks\":[" + "{\"i\":0,\"type\":\"Events.WhenRun\",\"x\":40,\"y\":40,\"next\":1}," + "{\"i\":1,\"type\":\"Errors.Try\",\"parent\":0,\"prel\":0,\"next\":7,\"sub\":[2,3,5]}," + "{\"i\":2,\"type\":\"Errors.Raise\",\"parent\":1,\"prel\":1,\"next\":6,\"in_text\":[\"deu ruim\"]}," + "{\"i\":6,\"type\":\"IO.Print\",\"parent\":2,\"prel\":0,\"in_text\":[\"nao roda\",\"\"]}," + "{\"i\":3,\"type\":\"IO.Print\",\"parent\":1,\"prel\":2,\"args\":[-1,4],\"in_text\":[\"pegou\",\"\"]}," + "{\"i\":4,\"type\":\"Errors.Caught\",\"parent\":3,\"prel\":5}," + "{\"i\":5,\"type\":\"IO.Print\",\"parent\":1,\"prel\":3,\"in_text\":[\"no finalmente\",\"\"]}," + "{\"i\":7,\"type\":\"IO.Print\",\"parent\":1,\"prel\":0,\"next\":8,\"args\":[-1,9],\"in_text\":[\"resultado\",\"\"]}," + "{\"i\":9,\"type\":\"Errors.UnwrapOr\",\"parent\":7,\"prel\":5,\"args\":[10,-1],\"in_text\":[\"\",\"77\"]}," + "{\"i\":10,\"type\":\"Errors.Attempt\",\"parent\":9,\"prel\":4,\"args\":[11]}," + "{\"i\":11,\"type\":\"Errors.Unwrap\",\"parent\":10,\"prel\":4,\"args\":[12]}," + "{\"i\":12,\"type\":\"Errors.Err\",\"parent\":11,\"prel\":4,\"in_text\":[\"x\"]}," + "{\"i\":8,\"type\":\"Errors.Raise\",\"parent\":7,\"prel\":0,\"next\":13,\"in_text\":[\"sem tente\"]}," + "{\"i\":13,\"type\":\"IO.Print\",\"parent\":8,\"prel\":0,\"in_text\":[\"nunca\",\"\"]}" + "],\"top\":[0]}],\"user_blocks\":[],\"variables\":[]}", f); + fclose(f); + } + if (need("Abrir", R_FLY, 0, &x, &y)) click(x, y); + for (int i = 0; i < 40; i++) key(TB_KEY_BACKSPACE, 0, 0); + type(pj); + key(TB_KEY_RETURN, 0, 0); + if (find("Descartar", R_ANY, 0, &x, &y)) click(x, y); + frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(ws_has("tente") && ws_has("se der erro") && ws_has("finalmente"), + "bloco tente / se der erro / finalmente com três bocas"); + flag(); + for (int i = 0; i < 3; i++) frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(stage_has("deu ruim") && !stage_has("nao roda"), "erro pula o resto do tente e vai para o se der erro"); + CHECK(stage_has("no finalmente"), "finalmente roda depois"); + CHECK(stage_has("77"), "tente obter + desembrulhe + valor de ... ou: erro vira valor (Result)"); + CHECK(stage_has("[ERRO] sem tente") && !stage_has("nunca"), "erro sem tente para o script e aparece no palco"); + remove(pj); + } + + /* 25. Grupos (como no Unreal): agrupar a pilha e mover tudo pelo título */ + { + float hx0, hy0; + frame(0, 0, 0, 0, 0, 0, NULL); + if (need("quando a bandeira for clicado", R_WS, 0, &hx0, &hy0)) { + drag(hx0, hy0, hx0 + 40, hy0 + 160); /* longe da barra de abas */ + need("quando a bandeira for clicado", R_WS, 0, &hx0, &hy0); + frame(hx0, hy0, 0, 0, 1, 0, NULL); /* botão direito na pilha */ + frame(hx0, hy0, 0, 0, 0, 0, NULL); + if (need("Agrupar esta pilha", R_ANY, 0, &x, &y)) click(x, y); + for (int i = 0; i < 12; i++) key(TB_KEY_BACKSPACE, 0, 0); + type("Principal"); + key(TB_KEY_RETURN, 0, 0); + CHECK(find("Principal", R_WS, 0, &x, &y), "Agrupar esta pilha cria o grupo com título"); + float tx = x, ty = y; + drag(tx, ty, tx + 120, ty + 70); /* arrasta pelo título */ + float nx, ny; + CHECK(find("quando a bandeira for clicado", R_WS, 0, &nx, &ny) && + fabsf(nx - (hx0 + 120)) < 2 && fabsf(ny - (hy0 + 70)) < 2, + "arrastar o título do grupo move a pilha junto"); + CHECK(find("Principal", R_WS, 0, &x, &y) && fabsf(x - (tx + 120)) < 2, + "o grupo vai junto com a pilha"); + + /* salvar e abrir de novo mantém o grupo */ + const char* gp = "/tmp/tb_harness_grp.json"; + remove(gp); + if (need("Salvar", R_FLY, 0, &x, &y)) click(x, y); + for (int i = 0; i < 40; i++) key(TB_KEY_BACKSPACE, 0, 0); + type(gp); + key(TB_KEY_RETURN, 0, 0); + FILE* f = fopen(gp, "rb"); + char buf[65536] = ""; + if (f) { size_t n = fread(buf, 1, sizeof(buf) - 1, f); buf[n] = 0; fclose(f); } + CHECK(strstr(buf, "\"groups\"") && strstr(buf, "Principal"), "projeto salvo guarda os grupos"); + } + } + tinyblocks_deinit(&rt); printf(fails ? "\n%d FALHA(S)\n" : "\nTUDO OK\n", fails); return fails != 0;