Files
tinyblocks/tests/editor_harness.c
T
mguinhosandClaude Opus 5.5 f180eaf75a Editor: zoom (Ctrl+roda, pinca), selecao de texto e partes do bloco moveis
- Area de scripts com zoom: Ctrl+roda no ponteiro, roda rola na vertical e
  Shift+roda na horizontal; pinca com dois dedos (toque) e pinca do
  touchpad (XInput 2.4 no X11, GFX_IN_ZOOM). Desenho em escala 1 escalado
  depois (rb_scale_from); a arvore acessivel acompanha (tb_a11y_scale_from).
- SDL2: cache de fontes com 64 tamanhos e descarte do menos usado (antes
  vazava uma fonte por chamada depois de 8 tamanhos).
- Campos de texto e editor de codigo: cursor em qualquer posicao, selecao
  (mouse, Shift+setas, clique duplo), Ctrl+A/C/X/V; no toque, segurar
  seleciona a palavra com alcas e barra Recortar/Copiar/Colar/Tudo.
- "Criar um Bloco": o nome e uma parte movel (PARAM_NAME) e pode ser
  apagado quando um rotulo logo depois assume; hexagono booleano sem corte.
- Harness: cenarios 32-34 (zoom, pinca, dialogo, selecao e clipboard).

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

1711 lines
94 KiB
C

#define _POSIX_C_SOURCE 200809L
/* Harness headless do editor: dirige Editor.Scene com um bloco de eventos
* falso e inspeciona os comandos de desenho produzidos por on_draw. */
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <tinyblocks/tinyblocks.h>
#include <tinyblocks/tb_renderable_block.h>
#include <tb_editor.h>
#include <tb_graphics.h>
#include <tb_events.h>
#include <tb_control.h>
#include <tb_errors.h>
#include <tb_operators.h>
#include <tb_number.h>
#include <tb_string.h>
#include <tb_vector.h>
#include <tb_variables.h>
#include <tb_appearance.h>
#include <tb_pen.h>
#include <tb_curves.h>
#include <tb_base64.h>
#include <tb_ppm.h>
#include <tb_input_lib.h>
#include <tb_environ.h>
#include <tb_a11y.h>
#include <tb_mcp_server.h>
static TinyBlocks* rt;
static TinyBlocks_Block *ev, *scene;
static TinyBlocks_DrawCmd cmds[TB_DRAW_CMD_CAP];
static uint32_t ncmd;
static int fails = 0;
static int g_mods = 0;
static void mods(int m) { g_mods = m; }
static void eval_ev(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; self->dirty = false; }
static void draw(void) {
TinyBlocks_RenderableBlock* rb = NULL;
if (scene->type->on_draw(scene, rt, &rb) && rb) {
ncmd = rb->count;
memcpy(cmds, rb->cmds, ncmd * sizeof(cmds[0]));
}
tb_renderable_release_all();
}
static float g_scroll_dy = 0.f;
static int g_win_w = 1280, g_win_h = 720;
static int g_l_held = 0; /* botao/dedo segurado (GFX_IN_MOUSE_L_HELD) */
static float g_zoom = 0.f; /* pinca do touchpad (GFX_IN_ZOOM) */
static int g_touch_n = 0; /* dedos na tela (pinca) */
static float g_touch[2][2];
static TinyBlocks_Value touches_json(void) {
TinyBlocks_JsonValue* arr = tb_json_array();
for (int i = 0; arr && i < g_touch_n; i++) {
TinyBlocks_JsonValue* p = tb_json_array();
for (int k = 0; p && k < 2; k++) {
TinyBlocks_JsonValue* n = tb_json_number(g_touch[i][k]);
if (n) { tb_json_array_push(p, n); tb_json_release(n); }
}
if (p) { tb_json_array_push(arr, p); tb_json_release(p); }
}
TinyBlocks_Value v = tb_value_json(arr);
tb_json_release(arr);
return v;
}
static void frame(float mx, float my, int ld, int lu, int rd, int sc, const char* text) {
tb_block_set_output(ev, GFX_IN_MOUSE_X, tb_value_real(mx));
tb_block_set_output(ev, GFX_IN_MOUSE_Y, tb_value_real(my));
tb_block_set_output(ev, GFX_IN_MOUSE_L_DOWN, tb_value_integer(ld));
tb_block_set_output(ev, GFX_IN_MOUSE_L_UP, tb_value_integer(lu));
tb_block_set_output(ev, GFX_IN_MOUSE_R_DOWN, tb_value_integer(rd));
tb_block_set_output(ev, GFX_IN_KEY, tb_value_integer(sc));
tb_block_set_output(ev, GFX_IN_KEY_MOD, tb_value_integer(g_mods));
tb_block_set_output(ev, GFX_IN_MOD_STATE, tb_value_integer(g_mods));
tb_block_set_output(ev, GFX_IN_TEXT, tb_value_text(text ? text : ""));
tb_block_set_output(ev, GFX_IN_DROP_FILE, tb_value_text(""));
tb_block_set_output(ev, GFX_IN_SCROLL_DX, tb_value_real(0));
tb_block_set_output(ev, GFX_IN_SCROLL_DY, tb_value_real(g_scroll_dy));
tb_block_set_output(ev, GFX_IN_WIN_W, tb_value_integer(g_win_w));
tb_block_set_output(ev, GFX_IN_WIN_H, tb_value_integer(g_win_h));
tb_block_set_output(ev, GFX_IN_TOUCHES, touches_json());
tb_block_set_output(ev, GFX_IN_ZOOM, tb_value_real(g_zoom));
tb_block_set_output(ev, GFX_IN_MOUSE_L_HELD, tb_value_integer(g_l_held));
tb_block_eval(scene, rt);
draw();
g_scroll_dy = 0.f;
g_zoom = 0.f;
}
/* == Interface de acessibilidade: componentes por papel + nome ===
* (nao depende do texto desenhado nem de coordenadas fixas) */
static TinyBlocks_A11yTree* A(void) { return tb_editor_accessible(scene); }
static const TinyBlocks_A11yNode* N(int n) { return tb_a11y_node(A(), n); }
static int ax_in(int from, TinyBlocks_A11yRole r, const char* name) { return tb_a11y_find(A(), from, r, name, 0); }
static int ax_part(int from, TinyBlocks_A11yRole r, const char* part) { return tb_a11y_find_part(A(), from, r, part, 0); }
static int ax_need(int from, TinyBlocks_A11yRole r, const char* name) {
int n = ax_in(from, r, name);
if (n < 0) { printf("FAIL não achei o %s \"%s\" na árvore acessível\n", tb_a11y_role_name(r), name); fails++; }
return n;
}
static const char* ax_value(int n) { return n >= 0 ? N(n)->value : ""; }
static int ax_count(int from, TinyBlocks_A11yRole r, const char* name) {
int k = 0;
while (tb_a11y_find(A(), from, r, name, k) >= 0) k++;
return k;
}
/* Texto em qualquer lugar do quadro (ex.: marcação que não deve aparecer) */
static bool any_has(const char* s) {
for (uint32_t i = 0; i < ncmd; i++)
if (cmds[i].kind == TB_DRAW_TEXT && strstr(cmds[i].text, s)) return true;
return false;
}
/* Pixels não-brancos da folha de desenho: a MAIOR imagem desenhada no painel
* da aba (as miniaturas das camadas são pequenas); -1 se não há imagem */
static int img_nonwhite(void) {
const TinyBlocks_A11yNode* w = N(ax_in(0, TB_A11Y_TAB_PANEL, NULL));
const TinyBlocks_Image* im = NULL;
float best = 0;
for (uint32_t i = 0; w && i < ncmd; i++) {
if (cmds[i].kind != TB_DRAW_IMAGE || !cmds[i].image) continue;
if (cmds[i].x < w->x || cmds[i].x > w->x + w->w) continue;
float a = cmds[i].w * cmds[i].h;
if (a < 20000.f) continue;
if (a > best) { best = a; im = cmds[i].image; }
}
if (!im) return -1;
int W = tb_image_width(im), H = tb_image_height(im), n = 0;
for (int y = 0; y < H; y++)
for (int x = 0; x < W; x++) {
uint8_t r, g, b, a;
if (tb_image_get_pixel(im, x, y, &r, &g, &b, &a) && a > 0 &&
(r < 240 || g < 240 || b < 240)) n++;
}
return n;
}
/* Numa falha, mostra a saída (console), lida da árvore */
static void dump_console(void) {
int c = ax_in(ax_in(0, TB_A11Y_PANE, "Saída"), TB_A11Y_LIST, "Console");
for (int i = c >= 0 ? N(c)->first_child : -1; i >= 0; i = N(i)->next_sibling) printf(" | %s\n", N(i)->name);
}
#define CHECK(cond, msg) do { if (cond) printf("ok %s\n", msg); else { printf("FAIL %s\n", msg); fails++; dump_console(); } } while (0)
static void click(float x, float y) { frame(x, y, 1, 0, 0, 0, NULL); frame(x, y, 0, 1, 0, 0, NULL); }
static void drag(float x0, float y0, float x1, float y1) {
frame(x0, y0, 1, 0, 0, 0, NULL);
frame(x0 + 8, y0 + 8, 0, 0, 0, 0, NULL);
frame(x1, y1, 0, 0, 0, 0, NULL);
frame(x1, y1, 0, 1, 0, 0, NULL);
}
static void type(const char* s) { frame(0, 0, 0, 0, 0, 0, s); }
static void key(int sc, float x, float y) { frame(x, y, 0, 0, 0, sc, NULL); }
/* Executa uma acao acessivel e roda um quadro (a arvore e redesenhada) */
static bool ax_do(int n, TinyBlocks_A11yAction a) {
if (n < 0) return false;
float x, y;
tb_a11y_point(A(), n, &x, &y);
bool ok = tb_a11y_do_action(A(), n, a);
frame(x, y, 0, 0, 0, 0, NULL);
return ok;
}
/* == Servidor MCP do editor: chama uma ferramenta (era moderna, sem rede) ===
* Devolve o texto do resultado (malloc); *err = isError; *sc = structuredContent
* (referencia nova, ou NULL) */
static char* mcp(const char* tool, const char* args, bool* err, TinyBlocks_JsonValue** sc) {
char* req = malloc(strlen(args) + 512);
sprintf(req, "{\"jsonrpc\":\"2.0\",\"id\":7,\"method\":\"tools/call\",\"params\":{\"name\":\"%s\","
"\"arguments\":%s,\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\","
"\"io.modelcontextprotocol/clientCapabilities\":{}}}}", tool, args);
int st = 0;
char* resp = tb_mcp_server_handle(tb_editor_mcp_server(scene), req, NULL, &st);
free(req);
TinyBlocks_JsonValue* r = resp ? tb_json_parse(resp, NULL, 0) : NULL;
free(resp);
TinyBlocks_JsonValue* res = r ? tb_json_object_get(r, "result") : NULL;
TinyBlocks_JsonValue* ie = res ? tb_json_object_get(res, "isError") : NULL;
TinyBlocks_JsonValue* content = res ? tb_json_object_get(res, "content") : NULL;
TinyBlocks_JsonValue* first = content ? tb_json_array_get(content, 0) : NULL;
TinyBlocks_JsonValue* text = first ? tb_json_object_get(first, "text") : NULL;
if (err) *err = !res || tb_json_as_bool(ie, false);
if (sc) *sc = res ? tb_json_object_get(res, "structuredContent") : NULL;
char* out = strdup(text && tb_json_as_string(text) ? tb_json_as_string(text) : "");
tb_json_release(text); tb_json_release(first); tb_json_release(content);
tb_json_release(ie); tb_json_release(res); tb_json_release(r);
frame(0, 0, 0, 0, 0, 0, NULL); /* a interface mostra o que mudou */
return out;
}
/* Numero num caminho do structuredContent: "stacks.0.id" */
static double sc_num(const TinyBlocks_JsonValue* v, const char* path) {
char key[64];
TinyBlocks_JsonValue* cur = (TinyBlocks_JsonValue*)v;
if (cur) tb_json_retain(cur);
while (cur && *path) {
size_t n = strcspn(path, ".");
snprintf(key, sizeof(key), "%.*s", (int)n, path);
TinyBlocks_JsonValue* nx = tb_json_kind(cur) == TB_JSON_ARRAY ? tb_json_array_get(cur, (uint32_t)atoi(key))
: tb_json_object_get(cur, key);
tb_json_release(cur);
cur = nx;
path += n + (path[n] == '.');
}
double d = cur ? tb_json_as_number(cur, -1) : -1;
tb_json_release(cur);
return d;
}
/* Arrastar e soltar pela arvore (o editor decide o encaixe pelo papel do destino) */
static bool ax_drop(int src, int dst) {
if (src < 0 || dst < 0) { printf("FAIL soltar: origem %d, destino %d\n", src, dst); fails++; return false; }
bool ok = tb_a11y_drop(A(), src, dst);
frame(0, 0, 0, 0, 0, 0, NULL);
return ok;
}
/* Soltar com o canto da origem em (x, y) relativo ao canto do destino */
static bool ax_drop_at(int src, int dst, float x, float y) {
if (src < 0 || dst < 0) { printf("FAIL soltar: origem %d, destino %d\n", src, dst); fails++; return false; }
bool ok = tb_a11y_drop_at(A(), src, dst, x, y);
frame(0, 0, 0, 0, 0, 0, NULL);
return ok;
}
/* Partes da tela */
static int ws(void) { return ax_in(0, TB_A11Y_TAB_PANEL, NULL); }
static int pane(const char* n) { return ax_in(0, TB_A11Y_PANE, n); }
static int pal(void) { return ax_in(pane("Blocos"), TB_A11Y_LIST, "Paleta"); }
static int menu_btn(const char* n) { return ax_need(ax_in(0, TB_A11Y_TOOLBAR, "Menu"), TB_A11Y_BUTTON, n); }
static void cat(const char* n) {
ax_do(ax_need(ax_in(0, TB_A11Y_TAB_LIST, "Categorias"), TB_A11Y_TAB, n), TB_A11Y_ACT_ACTIVATE);
}
/* Bloco da paleta, na categoria, pelo trecho do rotulo */
static int pal_block(const char* category, const char* part) {
int n = ax_part(ax_in(pal(), TB_A11Y_GROUP, category), TB_A11Y_BLOCK, part);
if (n < 0) { printf("FAIL não achei \"%s\" em %s na paleta\n", part, category); fails++; }
return n;
}
static int ws_block(const char* part, int nth) { return tb_a11y_find_part(A(), ws(), TB_A11Y_BLOCK, part, nth); }
static int ws_count(const char* part) {
int k = 0;
while (ws_block(part, k) >= 0) k++;
return k;
}
/* 1o bloco da pilha solta cujo nome comeca com o rotulo */
static int stack_head(const char* label) {
char nm[160];
snprintf(nm, sizeof(nm), "Pilha: %s", label);
return ax_in(ax_part(ws(), TB_A11Y_LIST, nm), TB_A11Y_BLOCK, NULL);
}
static int field(int block, int nth) { return block >= 0 ? tb_a11y_find(A(), block, TB_A11Y_TEXT_FIELD, NULL, nth) : -1; }
static void flag(void) { ax_do(ax_in(pane("Palco"), TB_A11Y_BUTTON, "Executar"), TB_A11Y_ACT_ACTIVATE); }
static void stop(void) { ax_do(ax_in(pane("Palco"), TB_A11Y_BUTTON, "Parar"), TB_A11Y_ACT_ACTIVATE); }
/* Linha da saida (console) que contem `sub`: posicao (0..) ou -1 */
static int console_line(const char* sub) {
int c = ax_in(pane("Saída"), TB_A11Y_LIST, "Console");
int n = c >= 0 ? tb_a11y_find_part(A(), c, TB_A11Y_LABEL, sub, 0) : -1;
if (n < 0) return -1;
int k = 0;
for (int i = N(c)->first_child; i >= 0 && i != n; i = N(i)->next_sibling) k++;
return k;
}
static bool console_has(const char* sub) { return console_line(sub) >= 0; }
static int console_count(const char* sub) {
int c = ax_in(pane("Saída"), TB_A11Y_LIST, "Console"), k = 0;
while (c >= 0 && tb_a11y_find_part(A(), c, TB_A11Y_LABEL, sub, k) >= 0) k++;
return k;
}
static bool toast_has(const char* sub) { return ax_part(0, TB_A11Y_STATUS, sub) >= 0; }
static const char* result_value(void) { return ax_value(ax_in(0, TB_A11Y_STATUS, "Resultado")); }
/* Apaga o campo com o foco (o valor dele na arvore) */
static void clear_focus(void) {
for (int i = 0; i < 300 && tb_a11y_focus(A()) >= 0 && N(tb_a11y_focus(A()))->value[0]; i++)
key(TB_KEY_BACKSPACE, 0, 0);
}
/* Escreve um caminho no campo com o foco e confirma */
static void type_path(const char* path) { clear_focus(); type(path); key(TB_KEY_RETURN, 0, 0); }
/* Ponto a uma fracao do retangulo do componente (pintar na folha, mover o mouse no palco) */
static void at(int node, float fx, float fy, float* x, float* y) {
*x = node >= 0 ? N(node)->x + N(node)->w * fx : 0;
*y = node >= 0 ? N(node)->y + N(node)->h * fy : 0;
}
/* Desenho dentro do retangulo de um componente (para conferir o que se ve) */
static bool cmd_in(const TinyBlocks_DrawCmd* c, int node) {
return node >= 0 && c->x >= N(node)->x && c->x <= N(node)->x + N(node)->w &&
c->y >= N(node)->y && c->y <= N(node)->y + N(node)->h;
}
static int drawn_count(TinyBlocks_DrawCmdKind kind, int node) {
int k = 0;
for (uint32_t i = 0; i < ncmd; i++) if (cmds[i].kind == kind && cmd_in(&cmds[i], node)) k++;
return k;
}
static bool drawn_text(int node, const char* sub) {
for (uint32_t i = 0; i < ncmd; i++)
if (cmds[i].kind == TB_DRAW_TEXT && cmd_in(&cmds[i], node) && strstr(cmds[i].text, sub)) return true;
return false;
}
int main(void) {
/* configurações isoladas: o harness não lê nem grava o ~/.config real */
setenv("XDG_CONFIG_HOME", "/tmp/tb_harness_cfg", 1);
setenv("TINYBLOCKS_MCP_PORT", "0", 1); /* o servidor MCP atende sem rede (cenario 29) */
unsetenv("TINYBLOCKS_SETTINGS");
remove("/tmp/tb_harness_cfg/tinyblocks/settings.csv");
tinyblocks_init(&rt, NULL);
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_number_get_library());
tb_library_register(rt, tb_string_get_library());
tb_library_register(rt, tb_vector_get_library());
tb_library_register(rt, tb_variables_get_library());
tb_library_register(rt, tb_appearance_get_library());
tb_library_register(rt, tb_pen_get_library());
tb_library_register(rt, tb_curves_get_library());
tb_library_register(rt, tb_base64_get_library());
tb_library_register(rt, tb_ppm_get_library());
tb_library_register(rt, tb_input_get_library());
tb_library_register(rt, tb_graphics_get_library());
tb_library_register(rt, tb_editor_get_library());
(void)eval_ev;
ev = tb_block_create(rt, tb_type_block_find(rt, "Graphics.Input"));
scene = tb_block_create(rt, tb_type_block_find(rt, "Editor.Scene"));
tb_block_set_default(scene, 0, tb_value_block(ev));
frame(0, 0, 0, 0, 0, 0, NULL);
printf("comandos de desenho no 1º frame: %u (cap %d)\n", ncmd, TB_DRAW_CMD_CAP);
CHECK(ncmd > 100 && ncmd < TB_DRAW_CMD_CAP, "frame inicial cabe no RenderableBlock");
/* 1. Script de exemplo */
flag();
CHECK(console_has("x vale = 1") && console_has("x vale = 5") && !console_has("x vale = 6"),
"bandeira roda o script de exemplo (x vale = 1..5)");
/* 2. Arrastar "escreva" da paleta para uma área livre e ativar */
cat("Aparência");
ax_drop_at(pal_block("Aparência", "escreva"), ws(), 282, 470);
CHECK(ws_count("escreva") == 2, "bloco da paleta aparece na área de scripts");
ax_do(stack_head("escreva"), TB_A11Y_ACT_ACTIVATE);
CHECK(console_has("Olá!"), "ativar o bloco solto executa (Olá!)");
/* 3. Encaixar o "escreva Olá!" logo abaixo do chapéu */
ax_drop(stack_head("escreva"), ws_block("quando a bandeira for clicado", 0));
flag();
CHECK(console_has("Olá!") && console_has("x vale = 5"), "encaixe sob o chapéu: script roda os dois");
CHECK(console_line("Olá!") >= 0 && console_line("Olá!") < console_line("x vale = 1"),
"ordem de execução: Olá! antes de x vale");
/* 4. Repórter "+": solto, editar campos, ativar duas vezes - balão */
cat("Operadores");
ax_drop_at(pal_block("Operadores", ") + ("), ws(), 322, 390);
{
int plus = stack_head("(0) + (0)");
ax_do(field(plus, 0), TB_A11Y_ACT_EDIT);
key(TB_KEY_BACKSPACE, 0, 0); type("2"); key(TB_KEY_RETURN, 0, 0);
ax_do(field(stack_head("(2) + (0)"), 1), TB_A11Y_ACT_EDIT);
key(TB_KEY_BACKSPACE, 0, 0); type("3"); key(TB_KEY_RETURN, 0, 0);
plus = stack_head("(2) + (3)");
ax_do(plus, TB_A11Y_ACT_ACTIVATE);
ax_do(plus, TB_A11Y_ACT_ACTIVATE); /* clique duplo */
}
CHECK(!strcmp(result_value(), "5"), "clique duplo no repórter mostra balão com 5 (2+3)");
/* 5. Encaixar o repórter (2+3) no campo de "mude x para (0)" */
ax_drop(stack_head("(2) + (3)"), field(ws_block("mude (x) para", 0), 1));
flag();
CHECK(console_has("x vale = 10") && console_has("x vale = 6") && !console_has("x vale = 5"),
"repórter encaixado: x começa em 5 (x vale = 6..10)");
/* 6. Delete com o mouse sobre o "escreva Olá!" apaga só ele; o resto sobe */
{
float px, py;
int b = ws_block("escreva (Olá!)", 0);
if (b >= 0) { tb_a11y_point(A(), b, &px, &py); key(TB_KEY_DELETE, px, py); }
}
flag();
CHECK(!console_has("Olá!") && console_has("x vale = 10"), "Delete remove o bloco e mantém o resto do script");
/* 7. Soltar o bloco sobre a paleta apaga */
cat("Aparência");
ax_drop_at(pal_block("Aparência", "escreva"), ws(), 382, 520);
{
int before = ws_count("escreva");
ax_drop(stack_head("escreva"), pal());
CHECK(ws_count("escreva") == before - 1, "soltar bloco sobre a paleta apaga");
}
/* 8. Bloco composto "dobro(n)" criado pelo diálogo; corpo: devolva n + 1.
* Tudo achado pela interface de acessibilidade (papel + nome). */
cat("Meus Blocos");
ax_do(ax_need(pal(), TB_A11Y_BUTTON, "Criar um Bloco"), TB_A11Y_ACT_ACTIVATE);
{
int dlg = ax_need(0, TB_A11Y_DIALOG, "Criar um Bloco");
int nome = ax_in(dlg, TB_A11Y_TEXT_FIELD, "Nome do bloco");
CHECK(dlg >= 0 && (N(dlg)->states & TB_A11Y_MODAL), "diálogo \"Criar um Bloco\" na árvore, modal");
CHECK(nome >= 0 && tb_a11y_focus(A()) == nome, "o foco abre no campo \"Nome do bloco\"");
}
type("dobro");
CHECK(!strcmp(ax_value(ax_in(0, TB_A11Y_TEXT_FIELD, "Nome do bloco")), "dobro"), "o nome digitado é o valor do campo");
ax_do(ax_need(ax_in(0, TB_A11Y_DIALOG, "Criar um Bloco"), TB_A11Y_BUTTON, "Adicionar entrada de número ou texto"),
TB_A11Y_ACT_ACTIVATE);
type("n");
CHECK(!strcmp(ax_value(tb_a11y_focus(A())), "n"), "a entrada nova recebe o foco e o nome n");
ax_do(ax_need(ax_in(0, TB_A11Y_DIALOG, "Criar um Bloco"), TB_A11Y_BUTTON, "OK"), TB_A11Y_ACT_ACTIVATE);
CHECK(ax_in(0, TB_A11Y_DIALOG, "Criar um Bloco") < 0, "OK fecha o diálogo");
int panel = ax_in(0, TB_A11Y_TAB_PANEL, NULL);
int def = ax_in(panel, TB_A11Y_BLOCK, "defina dobro (n)");
/* como no Scratch: o "defina" aparece na própria aba, e o parâmetro só dentro dele */
CHECK(def >= 0, "Criar um Bloco põe \"defina dobro (n)\" na mesma aba");
CHECK(ax_count(panel, TB_A11Y_BLOCK, "n") == 1 && ax_in(def, TB_A11Y_BLOCK, "n") >= 0,
"sem parâmetros soltos: o \"n\" está no protótipo do defina");
CHECK(ax_in(panel, TB_A11Y_BLOCK, "quando a bandeira for clicado") >= 0, "sem abrir aba nova: os scripts continuam ali");
/* posição do "defina" no painel, para soltar coisas ao lado dele */
float dfx = def >= 0 ? N(def)->x - N(panel)->x : 0, dfy = def >= 0 ? N(def)->y - N(panel)->y : 0;
/* devolva embaixo do "defina"; um "+" solto ao lado */
cat("Meus Blocos");
ax_drop(ax_part(pal(), TB_A11Y_BLOCK, "devolva"), ax_in(ws(), TB_A11Y_BLOCK, "defina dobro (n)"));
cat("Operadores");
{
int ops = ax_in(pal(), TB_A11Y_GROUP, "Operadores");
ax_drop_at(ax_part(ops, TB_A11Y_BLOCK, ") + ("), ws(), dfx + 300, dfy + 110);
}
/* o parâmetro sai arrastando de dentro do "defina" para o 1o campo do "+" */
{
panel = ax_in(0, TB_A11Y_TAB_PANEL, NULL);
int plus = ax_in(ax_in(panel, TB_A11Y_LIST, "Pilha: (0) + (0)"), TB_A11Y_BLOCK, "(0) + (0)");
int slot = ax_in(plus, TB_A11Y_TEXT_FIELD, NULL);
ax_drop(ax_in(ax_in(panel, TB_A11Y_BLOCK, "defina dobro (n)"), TB_A11Y_BLOCK, "n"), slot);
panel = ax_in(0, TB_A11Y_TAB_PANEL, NULL);
CHECK(ax_in(panel, TB_A11Y_BLOCK, "(n) + (0)") >= 0, "arrastar o parâmetro do defina põe \"n\" no +");
}
/* 1 no outro campo do "+" */
ax_do(ax_in(ax_in(0, TB_A11Y_BLOCK, "(n) + (0)"), TB_A11Y_TEXT_FIELD, NULL), TB_A11Y_ACT_EDIT);
key(TB_KEY_BACKSPACE, 0, 0);
type("1"); key(TB_KEY_RETURN, 0, 0);
/* o "+" no campo de valor do devolva (o 2o campo) */
{
int dev = ax_part(ax_in(0, TB_A11Y_TAB_PANEL, NULL), TB_A11Y_BLOCK, "devolva");
int val = dev >= 0 ? tb_a11y_find(A(), dev, TB_A11Y_TEXT_FIELD, NULL, 1) : -1;
ax_drop(ax_need(0, TB_A11Y_BLOCK, "(n) + (1)"), val);
CHECK(ax_part(ax_in(0, TB_A11Y_TAB_PANEL, NULL), TB_A11Y_BLOCK, "= ((n) + (1))") >= 0,
"corpo: devolva (n) + (1)");
}
cat("Meus Blocos");
{
int mine = ax_in(pal(), TB_A11Y_GROUP, "Meus Blocos");
int call = ax_in(mine, TB_A11Y_BLOCK, "dobro (n)");
CHECK(call >= 0, "bloco dobro aparece em Meus Blocos");
ax_drop_at(call, ws(), dfx + 330, dfy - 60);
}
{
panel = ax_in(0, TB_A11Y_TAB_PANEL, NULL);
int call = ax_in(panel, TB_A11Y_BLOCK, "dobro (n)");
ax_do(ax_in(call, TB_A11Y_TEXT_FIELD, NULL), TB_A11Y_ACT_EDIT);
key(TB_KEY_BACKSPACE, 0, 0);
type("21"); key(TB_KEY_RETURN, 0, 0);
call = ax_in(ax_in(0, TB_A11Y_TAB_PANEL, NULL), TB_A11Y_BLOCK, "dobro (21)");
ax_do(call, TB_A11Y_ACT_ACTIVATE);
ax_do(call, TB_A11Y_ACT_ACTIVATE); /* clique duplo: balão com o valor */
}
CHECK(!strcmp(ax_value(ax_in(0, TB_A11Y_STATUS, "Resultado")), "22"), "bloco composto dobro(21) = 22");
/* 9. Laço infinito é interrompido */
cat("Controle");
ax_drop_at(pal_block("Controle", "repita até que"), ws(), 382, 220);
ax_do(stack_head("repita até que"), TB_A11Y_ACT_ACTIVATE);
/* laço sem fim roda quadro a quadro (estilo Scratch): não trava nem aborta */
for (int i = 0; i < 5; i++) frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(!console_has("limite de passos"), "laço sem fim roda sem travar (sem aviso de limite)");
stop();
/* 10. Caneta: desenhar no palco embutido */
{
int stage = ax_in(pane("Palco"), TB_A11Y_CANVAS, "Palco");
int circles_before = drawn_count(TB_DRAW_FILL_CIRCLE, stage);
cat("Caneta");
ax_drop_at(pal_block("Caneta", "desenhe círculo em x"), ws(), 282, 570);
ax_do(stack_head("desenhe círculo em x"), TB_A11Y_ACT_ACTIVATE);
stage = ax_in(pane("Palco"), TB_A11Y_CANVAS, "Palco");
float scx, scy, cx = 0, cy = 0;
at(stage, 0.5f, 0.5f, &scx, &scy);
for (uint32_t i = 0; i < ncmd; i++)
if (cmds[i].kind == TB_DRAW_FILL_CIRCLE && cmd_in(&cmds[i], stage)) { cx = cmds[i].x; cy = cmds[i].y; }
printf(" círculo no palco: (%.1f, %.1f), centro do palco (%.1f, %.1f)\n", cx, cy, scx, scy);
CHECK(drawn_count(TB_DRAW_FILL_CIRCLE, stage) == circles_before + 1 &&
fabsf(cx - scx) < 2 && fabsf(cy - scy) < 2, "bloco da caneta desenha círculo centrado no palco embutido");
cat("Caneta");
ax_drop_at(pal_block("Caneta", "apague tudo"), ws(), 420, 600); /* longe do círculo (não encaixa) */
ax_do(stack_head("apague tudo"), TB_A11Y_ACT_ACTIVATE);
CHECK(drawn_count(TB_DRAW_FILL_CIRCLE, ax_in(pane("Palco"), TB_A11Y_CANVAS, "Palco")) == circles_before,
"\"apague tudo\" limpa o palco");
}
/* 11. Destacar o palco numa janela própria e recolher de volta */
ax_do(ax_in(pane("Palco"), TB_A11Y_BUTTON, "Destacar o palco"), TB_A11Y_ACT_ACTIVATE);
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(pane("Palco") < 0 && ax_in(ax_in(0, TB_A11Y_TOOLBAR, "Menu"), TB_A11Y_BUTTON, "Palco") >= 0,
"palco destacado abre janela própria (botão \"Palco\" no menu)");
ax_do(ax_in(ax_in(0, TB_A11Y_TOOLBAR, "Menu"), TB_A11Y_BUTTON, "Palco"), TB_A11Y_ACT_ACTIVATE);
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(pane("Palco") >= 0 && ax_in(pane("Palco"), TB_A11Y_BUTTON, "Executar") >= 0, "palco recolhido volta ao painel");
/* 12. Salvar e abrir projeto (.json) via tinyblocks-blueprint */
const char* proj = "/tmp/tb_harness_proj.json";
remove(proj);
ax_do(menu_btn("Salvar"), TB_A11Y_ACT_ACTIVATE);
type_path(proj);
CHECK(toast_has("Projeto salvo"), "salvar projeto escreve o .json");
{
/* aviso flutuante (toast) sobre a área de scripts, embaixo */
int t = ax_part(0, TB_A11Y_STATUS, "Projeto salvo"), sc = pane("Scripts");
CHECK(t >= 0 && sc >= 0 && N(t)->x > N(sc)->x && N(t)->x + N(t)->w <= N(sc)->x + N(sc)->w &&
N(t)->y > N(sc)->y + N(sc)->h * 0.5f, "mensagem vira aviso flutuante no canto da área de scripts");
/* salvar de novo: a mesma mensagem vira contador */
ax_do(menu_btn("Salvar"), TB_A11Y_ACT_ACTIVATE);
type_path(proj);
ax_do(ax_in(ax_in(0, TB_A11Y_DIALOG, "Substituir arquivo"), TB_A11Y_BUTTON, "Substituir"), TB_A11Y_ACT_ACTIVATE);
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(!strcmp(ax_value(ax_part(0, TB_A11Y_STATUS, "Projeto salvo")), "2 vezes"), "mensagem repetida vira contador");
}
ax_do(menu_btn("Abrir"), TB_A11Y_ACT_ACTIVATE);
type_path(proj);
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(toast_has("Projeto aberto"), "abrir projeto le o .json");
CHECK(ws_block("quando a bandeira for clicado", 0) >= 0, "estado restaurado apos abrir (chapéu de exemplo de volta)");
remove(proj);
/* 13. Abrir um projeto escrito a mao (aba distinta) */
const char* openjson = "/tmp/tb_harness_open.json";
FILE* pf = fopen(openjson, "wb");
if (pf) {
fputs("{\"format\":\"tinyblocks-project\",\"version\":1,\"cur_tab\":0,"
"\"tabs\":[{\"name\":\"Aberto!\",\"composite\":false,\"comp_id\":-1,\"color\":0,"
"\"blocks\":["
"{\"i\":0,\"type\":\"Events.WhenRun\",\"x\":40,\"y\":40,\"next\":1},"
"{\"i\":1,\"type\":\"IO.Print\",\"x\":40,\"y\":100,\"in_text\":[\"Oi do arquivo\",\"\"]},"
"{\"i\":2,\"type\":\"Stage.Circle\",\"x\":40,\"y\":180,\"in_text\":[\"0\",\"0\",\"80\"]}"
"],\"top\":[0,2]}],"
"\"user_blocks\":[],\"variables\":[{\"name\":\"x\",\"kind\":0,\"num\":7,\"text\":\"\"}]}", pf);
fclose(pf);
}
ax_do(menu_btn("Abrir"), TB_A11Y_ACT_ACTIVATE);
type_path(openjson);
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(ax_in(ax_in(0, TB_A11Y_TAB_LIST, "Abas"), TB_A11Y_TAB, "Aberto!") >= 0, "abrir projeto de arquivo externo (aba Aberto!)");
CHECK(ws_block("escreva (Oi do arquivo)", 0) >= 0, "bloco do arquivo externo aparece na área de scripts");
remove(openjson);
/* 13b. Explorador de arquivos (tinyblocks-editor-files) */
{
const char* fdir = "/tmp/tb_harness_fdlg";
char fp[256];
mkdir(fdir, 0755);
snprintf(fp, sizeof(fp), "%s/sub", fdir);
mkdir(fp, 0755);
snprintf(fp, sizeof(fp), "%s/nota.md", fdir);
FILE* tf = fopen(fp, "wb");
if (tf) { fputs("oi", tf); fclose(tf); }
snprintf(fp, sizeof(fp), "%s/proj.json", fdir);
tf = fopen(fp, "wb");
if (tf) {
fputs("{\"format\":\"tinyblocks-project\",\"version\":1,\"cur_tab\":0,"
"\"tabs\":[{\"name\":\"Explorado\",\"composite\":false,\"comp_id\":-1,\"color\":0,"
"\"blocks\":[{\"i\":0,\"type\":\"Events.WhenRun\",\"x\":40,\"y\":40}],"
"\"top\":[0]}],\"user_blocks\":[],\"variables\":[]}", tf);
fclose(tf);
}
ax_do(menu_btn("Abrir"), TB_A11Y_ACT_ACTIVATE);
int dlg = ax_in(0, TB_A11Y_DIALOG, "Abrir projeto");
CHECK(dlg >= 0 && tb_a11y_focus(A()) == ax_in(dlg, TB_A11Y_TEXT_FIELD, "Nome"),
"Abrir mostra o explorador de arquivos, com o foco no nome");
type_path(fdir);
int files = ax_in(ax_in(0, TB_A11Y_DIALOG, "Abrir projeto"), TB_A11Y_LIST, "Arquivos");
CHECK(ax_in(files, TB_A11Y_LIST_ITEM, "proj.json") >= 0 && ax_in(files, TB_A11Y_LIST_ITEM, "sub") >= 0 &&
ax_in(files, TB_A11Y_LIST_ITEM, "nota.md") < 0, "explorador lista pastas + .json e filtra o resto");
int pj = ax_in(files, TB_A11Y_LIST_ITEM, "proj.json");
ax_do(pj, TB_A11Y_ACT_ACTIVATE);
ax_do(pj, TB_A11Y_ACT_ACTIVATE); /* clique duplo */
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(toast_has("Projeto aberto") && ax_in(ax_in(0, TB_A11Y_TAB_LIST, "Abas"), TB_A11Y_TAB, "Explorado") >= 0,
"duplo clique no explorador abre o projeto");
ax_do(menu_btn("Salvar"), TB_A11Y_ACT_ACTIVATE);
CHECK(ax_in(0, TB_A11Y_DIALOG, "Salvar projeto") >= 0, "Salvar mostra o explorador de arquivos");
type_path("proj");
int conf = ax_in(0, TB_A11Y_DIALOG, "Substituir arquivo");
CHECK(conf >= 0, "salvar sobre arquivo existente pede confirmação");
ax_do(ax_in(conf, TB_A11Y_BUTTON, "Substituir"), TB_A11Y_ACT_ACTIVATE);
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(toast_has("Projeto salvo") && ax_in(0, TB_A11Y_DIALOG, "Salvar projeto") < 0,
"Substituir grava o .json (extensão completada) e fecha");
ax_do(menu_btn("Abrir"), TB_A11Y_ACT_ACTIVATE);
key(TB_KEY_ESCAPE, 0, 0);
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(ax_in(0, TB_A11Y_DIALOG, "Abrir projeto") < 0, "Esc fecha o explorador");
remove(fp);
snprintf(fp, sizeof(fp), "%s/nota.md", fdir); remove(fp);
snprintf(fp, sizeof(fp), "%s/sub", fdir); rmdir(fp);
rmdir(fdir);
}
/* 13c. "desenhe [lista de pontos]" (Caneta) + tipo do valor no balão */
{
const char* dj = "/tmp/tb_harness_draw.json";
FILE* df = fopen(dj, "wb");
if (df) {
fputs("{\"format\":\"tinyblocks-project\",\"version\":1,\"cur_tab\":0,"
"\"tabs\":[{\"name\":\"Desenho\",\"composite\":false,\"comp_id\":-1,\"color\":0,"
"\"blocks\":["
"{\"i\":0,\"type\":\"Events.WhenRun\",\"x\":40,\"y\":40,\"next\":1},"
"{\"i\":1,\"type\":\"Stage.Draw\",\"x\":40,\"y\":100,\"parent\":0,\"prel\":0,"
"\"args\":[2,-1,-1],\"in_text\":[\"\",\"0\",\"0\"]},"
"{\"i\":2,\"type\":\"Curves.Line\",\"x\":0,\"y\":0,\"parent\":1,\"prel\":3,"
"\"in_text\":[\"-100\",\"0\",\"100\",\"50\",\"10\"]},"
"{\"i\":3,\"type\":\"Curves.Line\",\"x\":40,\"y\":220,"
"\"in_text\":[\"0\",\"0\",\"100\",\"0\",\"20\"]}"
"],\"top\":[0,3]}],\"user_blocks\":[],\"variables\":[]}", df);
fclose(df);
}
ax_do(menu_btn("Abrir"), TB_A11Y_ACT_ACTIVATE);
type_path(dj);
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(ax_in(ax_in(0, TB_A11Y_TAB_LIST, "Abas"), TB_A11Y_TAB, "Desenho") >= 0, "projeto com 'desenhe' aberto");
int before = drawn_count(TB_DRAW_STROKE_LINE, ax_in(pane("Palco"), TB_A11Y_CANVAS, "Palco"));
flag();
frame(0, 0, 0, 0, 0, 0, NULL);
int after = drawn_count(TB_DRAW_STROKE_LINE, ax_in(pane("Palco"), TB_A11Y_CANVAS, "Palco"));
CHECK(after >= before + 10, "desenhe (reta com 10 passos) traça 10 segmentos no palco");
/* repórter solto (o encaixado roda a pilha inteira, como no Scratch) */
int reta = stack_head("reta de x");
ax_do(reta, TB_A11Y_ACT_ACTIVATE);
ax_do(reta, TB_A11Y_ACT_ACTIVATE);
CHECK(!strcmp(N(ax_in(0, TB_A11Y_STATUS, "Resultado"))->description, "lista de pontos"),
"balão mostra o tipo 'lista de pontos'");
remove(dj);
}
/* 13d. "sempre": uma volta por quadro quando desenha; para no botão vermelho */
{
const char* fj = "/tmp/tb_harness_forever.json";
FILE* ff = fopen(fj, "wb");
if (ff) {
fputs("{\"format\":\"tinyblocks-project\",\"version\":1,\"cur_tab\":0,"
"\"tabs\":[{\"name\":\"Sempre\",\"composite\":false,\"comp_id\":-1,\"color\":0,"
"\"blocks\":["
"{\"i\":0,\"type\":\"Events.WhenRun\",\"x\":40,\"y\":40,\"next\":1},"
"{\"i\":1,\"type\":\"Control.Forever\",\"x\":40,\"y\":100,\"parent\":0,\"prel\":0,\"sub\":[2,-1]},"
"{\"i\":2,\"type\":\"IO.Print\",\"x\":0,\"y\":0,\"parent\":1,\"prel\":1,\"next\":3,"
"\"in_text\":[\"volta\",\"\"]},"
"{\"i\":3,\"type\":\"Stage.Circle\",\"x\":0,\"y\":0,\"parent\":2,\"prel\":0,"
"\"in_text\":[\"0\",\"0\",\"30\"]}"
"],\"top\":[0]}],\"user_blocks\":[],\"variables\":[]}", ff);
fclose(ff);
}
ax_do(menu_btn("Abrir"), TB_A11Y_ACT_ACTIVATE);
type_path(fj);
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(ws_block("sempre", 0) >= 0, "bloco 'sempre' aparece no projeto");
flag();
for (int i = 0; i < 6; i++) frame(0, 0, 0, 0, 0, 0, NULL);
int voltas = console_count("volta");
CHECK(voltas >= 4 && voltas <= 12, "'sempre' com caneta anima: ~uma volta por quadro");
stop();
for (int i = 0; i < 6; i++) frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(console_count("volta") == 0, "botão vermelho para o 'sempre' (e limpa a saída)");
remove(fj);
}
/* 13e. Sensores: posição do mouse no palco e última tecla, num "sempre" */
{
const char* sj = "/tmp/tb_harness_sensores.json";
FILE* sf = fopen(sj, "wb");
if (sf) {
fputs("{\"format\":\"tinyblocks-project\",\"version\":1,\"cur_tab\":0,"
"\"tabs\":[{\"name\":\"Sensores\",\"composite\":false,\"comp_id\":-1,\"color\":0,"
"\"blocks\":["
"{\"i\":0,\"type\":\"Events.WhenRun\",\"x\":40,\"y\":40,\"next\":1},"
"{\"i\":1,\"type\":\"Control.Forever\",\"x\":40,\"y\":100,\"parent\":0,\"prel\":0,\"sub\":[2,-1]},"
"{\"i\":2,\"type\":\"Stage.Clear\",\"x\":0,\"y\":0,\"parent\":1,\"prel\":1,\"next\":3},"
"{\"i\":3,\"type\":\"IO.Print\",\"x\":0,\"y\":0,\"parent\":2,\"prel\":0,\"args\":[4,5]},"
"{\"i\":4,\"type\":\"Input.MouseX\",\"x\":0,\"y\":0,\"parent\":3,\"prel\":3},"
"{\"i\":5,\"type\":\"Input.LastKey\",\"x\":0,\"y\":0,\"parent\":3,\"prel\":4}"
"],\"top\":[0]}],\"user_blocks\":[],\"variables\":[]}", sf);
fclose(sf);
}
ax_do(menu_btn("Abrir"), TB_A11Y_ACT_ACTIVATE);
type_path(sj);
frame(0, 0, 0, 0, 0, 0, NULL);
flag();
/* o palco tem 480 de largura: x = 100 fica a 100/480 da largura à direita do centro */
int stage = ax_in(pane("Palco"), TB_A11Y_CANVAS, "Palco");
float px, py;
at(stage, 0.5f + 100.f / 480.f, 0.4f, &px, &py);
for (int i = 0; i < 3; i++) frame(px, py, 0, 0, 0, 0, NULL);
CHECK(console_has("100"), "posição x do mouse sobre o palco = 100");
frame(px, py, 0, 0, 0, TB_KEY_SPACE, NULL);
for (int i = 0; i < 3; i++) frame(px, py, 0, 0, 0, 0, NULL);
CHECK(console_has("espaço"), "última tecla = espaço");
stop();
remove(sj);
}
/* 14. Exportar pelo menu do botão Exportar */
ax_do(menu_btn("Exportar"), TB_A11Y_ACT_ACTIVATE);
{
int m = ax_in(0, TB_A11Y_MENU, "Menu de contexto");
CHECK(ax_in(m, TB_A11Y_MENU_ITEM, "Exportar JSON") >= 0 && ax_in(m, TB_A11Y_MENU_ITEM, "Exportar XML") >= 0 &&
ax_in(m, TB_A11Y_MENU_ITEM, "Exportar CSV") >= 0, "botão Exportar abre menu com JSON/XML/CSV");
const char* expf = "/tmp/tb_harness_export.xml";
remove(expf);
ax_do(ax_in(m, TB_A11Y_MENU_ITEM, "Exportar XML"), TB_A11Y_ACT_ACTIVATE);
type_path(expf);
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(toast_has("Exportado xml"), "exportar XML pelo menu escreve o arquivo");
remove(expf);
}
/* 15. Regressão: arrastar um bloco da Caneta para o chapéu */
cat("Caneta");
{
int before = ws_count("apague tudo");
ax_drop(pal_block("Caneta", "apague tudo"), ws_block("quando a bandeira for clicado", 0));
CHECK(ws_count("apague tudo") == before + 1, "arrastar bloco da Caneta para o chapéu");
}
/* 16. Gestor de libraries (tinyblocks-libman), UI desenhada pelo editor */
CHECK(ax_in(ax_in(0, TB_A11Y_TAB_LIST, "Categorias"), TB_A11Y_TAB, "Blueprint") < 0,
"categoria Blueprint ainda não existe");
ax_do(menu_btn("Bibliotecas"), TB_A11Y_ACT_ACTIVATE);
{
int lm = ax_in(0, TB_A11Y_DIALOG, "Escolha uma Extensão");
CHECK(lm >= 0, "abre a tela do libman");
CHECK(tb_a11y_focus(A()) == ax_in(lm, TB_A11Y_TEXT_FIELD, "Buscar"), "libman abre com o foco na busca");
type("blueprint");
frame(0, 0, 0, 0, 0, 0, NULL);
int item = ax_in(ax_in(0, TB_A11Y_LIST, "Libraries"), TB_A11Y_LIST_ITEM, "tinyblocks-blueprint");
CHECK(item >= 0, "busca filtra por nome");
ax_do(item, TB_A11Y_ACT_ACTIVATE);
CHECK(ax_in(0, TB_A11Y_DIALOG, "Escolha uma Extensão") < 0, "libman fecha após carregar");
CHECK(ax_in(ax_in(0, TB_A11Y_TAB_LIST, "Categorias"), TB_A11Y_TAB, "Blueprint") >= 0,
"library carregada aparece na paleta");
}
/* 17. Botão de extensões no fim do painel (estilo Scratch) */
ax_do(ax_in(pane("Blocos"), TB_A11Y_BUTTON, "Adicionar extensão"), TB_A11Y_ACT_ACTIVATE);
CHECK(ax_in(0, TB_A11Y_DIALOG, "Escolha uma Extensão") >= 0, "botão de extensões no painel abre o libman");
key(TB_KEY_ESCAPE, 0, 0);
frame(0, 0, 0, 0, 0, 0, NULL);
/* 18. Tela de Configurações (settings da tinyblocks-environ) */
remove("build/settings_test.csv");
setenv("TINYBLOCKS_SETTINGS", "build/settings_test.csv", 1);
ax_do(menu_btn("Config"), TB_A11Y_ACT_ACTIVATE);
{
int cfg = ax_in(0, TB_A11Y_DIALOG, "Configurações");
CHECK(cfg >= 0, "botão Config abre a tela de configurações");
int env = ax_in(cfg, TB_A11Y_CHECKBOX, "Detectar caminho de TINYBLOCKS_SETTINGS");
CHECK(env >= 0, "mostra o toggle da variável de ambiente");
CHECK(ax_in(cfg, TB_A11Y_LIST_ITEM, "autor") >= 0, "lista as settings do store (autor)");
ax_do(env, TB_A11Y_ACT_ACTIVATE);
CHECK(!strcmp(ax_value(ax_in(0, TB_A11Y_TEXT_FIELD, "Arquivo de configurações")), "build/settings_test.csv"),
"toggle passa a usar o caminho de TINYBLOCKS_SETTINGS");
ax_do(ax_in(ax_in(0, TB_A11Y_DIALOG, "Configurações"), TB_A11Y_LIST_ITEM, "autor"), TB_A11Y_ACT_ACTIVATE);
CHECK(N(tb_a11y_focus(A()))->role == TB_A11Y_LIST_ITEM, "a linha escolhida fica editando (com o foco)");
type("maria");
key(TB_KEY_RETURN, 0, 0);
frame(0, 0, 0, 0, 0, 0, NULL);
ax_do(ax_in(ax_in(0, TB_A11Y_DIALOG, "Configurações"), TB_A11Y_BUTTON, "Salvar"), TB_A11Y_ACT_ACTIVATE);
FILE* sf = fopen("build/settings_test.csv", "rb");
char sbuf[512] = "";
if (sf) { size_t sn = fread(sbuf, 1, sizeof(sbuf)-1, sf); sbuf[sn] = 0; fclose(sf); }
CHECK(strstr(sbuf, "# arquivo_config,build/settings_test.csv") != NULL,
"CSV inclui o caminho do arquivo de configuração");
CHECK(strstr(sbuf, "chave,valor") != NULL, "settings salvas em CSV (cabeçalho)");
CHECK(strstr(sbuf, "autor,maria") != NULL, "valor editado gravado no CSV");
remove("build/settings_test.csv");
}
key(TB_KEY_ESCAPE, 0, 0); /* fecha a tela */
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(ax_in(0, TB_A11Y_DIALOG, "Configurações") < 0, "Esc fecha as configurações");
unsetenv("TINYBLOCKS_SETTINGS");
/* 19. Prévia de resultado: curva (lista de pontos) em balão, clique duplo */
cat("Curvas");
ax_drop_at(pal_block("Curvas", "círculo em ("), ws(), 302, 420);
{
int c = stack_head("círculo em (");
ax_do(c, TB_A11Y_ACT_ACTIVATE);
ax_do(c, TB_A11Y_ACT_ACTIVATE);
}
CHECK(drawn_count(TB_DRAW_STROKE_LINE, ws()) >= 20, "clique duplo na curva desenha a polilinha no balão");
CHECK(strstr(result_value(), "37 pontos") != NULL, "balão mostra a contagem de pontos da curva");
/* 20. Prévia de imagem: PPM.New em balão desenha TB_DRAW_IMAGE */
cat("PPM");
ax_drop_at(pal_block("PPM", "nova imagem("), ws(), 322, 440);
{
int im = stack_head("nova imagem(");
ax_do(im, TB_A11Y_ACT_ACTIVATE);
ax_do(im, TB_A11Y_ACT_ACTIVATE);
}
CHECK(drawn_count(TB_DRAW_IMAGE, ws()) >= 1, "clique duplo numa imagem desenha TB_DRAW_IMAGE no balão");
CHECK(strstr(result_value(), "32x32") != NULL, "balão mostra as dimensões da imagem");
/* 21. Tooltip de metadados: Alt + mouse sobre um bloco (Stage.Clear) */
cat("Caneta");
ax_drop_at(pal_block("Caneta", "apague tudo"), ws(), 202, 350);
{
float bx, by;
int b = stack_head("apague tudo");
tb_a11y_point(A(), b, &bx, &by);
mods(TB_MOD_ALT);
frame(bx, by, 0, 0, 0, 0, NULL);
int tip = ax_in(0, TB_A11Y_TOOLTIP, NULL);
CHECK(tip >= 0 && strstr(N(tip)->name, "eval_clear"), "Alt + mouse mostra a dica com a função C");
CHECK(tip >= 0 && strstr(N(tip)->value, "tb_pen.c"), "dica mostra o arquivo-fonte");
CHECK(tip >= 0 && strstr(N(tip)->description, "Limpa o palco"), "dica mostra a descrição (doc)");
mods(0);
/* a prévia do código abre a aba de código na linha */
ax_do(ax_in(tip, TB_A11Y_BUTTON, "Abrir o código nesta linha"), TB_A11Y_ACT_ACTIVATE);
int code = ax_in(0, TB_A11Y_TEXT_FIELD, "Código");
CHECK(code >= 0 && strstr(N(code)->description, "tb_pen.c"), "a prévia abre aba de código do arquivo");
CHECK(drawn_text(ws(), "eval_clear"), "aba de código mostra o código na linha da função");
}
/* 22. Botão "+" -> nova aba: Editor de Código */
key(TB_KEY_ESCAPE, 0, 0);
frame(0, 0, 0, 0, 0, 0, NULL);
ax_do(ax_in(ax_in(0, TB_A11Y_TAB_LIST, "Abas"), TB_A11Y_BUTTON, "Nova aba"), TB_A11Y_ACT_ACTIVATE);
{
int m = ax_in(0, TB_A11Y_MENU, "Nova aba");
CHECK(ax_in(m, TB_A11Y_MENU_ITEM, "Editor de Código") >= 0 && ax_in(m, TB_A11Y_MENU_ITEM, "Novo bloco") >= 0 &&
ax_in(m, TB_A11Y_MENU_ITEM, "Blueprint") >= 0, "menu '+' lista Blueprint, Novo bloco, Imagem e Código");
CHECK(ax_in(m, TB_A11Y_MENU_ITEM, "Edição de Imagem") >= 0, "menu '+' oferece Edição de Imagem");
ax_do(ax_in(m, TB_A11Y_MENU_ITEM, "Editor de Código"), TB_A11Y_ACT_ACTIVATE);
type("int x = 42;");
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(!strcmp(ax_value(ax_in(0, TB_A11Y_TEXT_FIELD, "Código")), "int x = 42;"), "o código digitado é o valor do campo");
CHECK(drawn_text(ws(), "int"), "aba de código realça 'int' (palavra-chave)");
CHECK(drawn_text(ws(), "42"), "aba de código realça o número 42");
CHECK(drawn_text(ws(), ";"), "aba de código realça a pontuação");
CHECK(!drawn_text(0, "</code>") && !any_has("</code>"), "aba de código não mostra a marcação </code>");
/* seleção e área de transferência no editor de código */
mods(TB_MOD_SHIFT); key(TB_KEY_HOME, 0, 0); mods(0);
mods(TB_MOD_CTRL); key(TB_KEY_A + ('c' - 'a'), 0, 0); mods(0);
key(TB_KEY_END, 0, 0); key(TB_KEY_RETURN, 0, 0);
mods(TB_MOD_CTRL); key(TB_KEY_A + ('v' - 'a'), 0, 0); mods(0);
/* o valor acessível é a linha do cursor; a descrição diz qual */
#define CODE_LINE ax_value(ax_in(0, TB_A11Y_TEXT_FIELD, "Código"))
#define CODE_DESC N(ax_in(0, TB_A11Y_TEXT_FIELD, "Código"))->description
CHECK(!strcmp(CODE_LINE, "int x = 42;") && !strncmp(CODE_DESC, "linha 2 ", 8),
"código: Shift+Home seleciona, Ctrl+C / Ctrl+V duplicam a linha");
mods(TB_MOD_SHIFT); key(TB_KEY_LEFT, 0, 0); key(TB_KEY_LEFT, 0, 0); key(TB_KEY_LEFT, 0, 0); mods(0);
mods(TB_MOD_CTRL); key(TB_KEY_A + ('x' - 'a'), 0, 0); mods(0);
type("7;");
CHECK(!strcmp(CODE_LINE, "int x = 7;"), "código: Ctrl+X recorta a seleção e digitar substitui");
key(TB_KEY_UP, 0, 0);
CHECK(!strcmp(CODE_LINE, "int x = 42;") && !strncmp(CODE_DESC, "linha 1 ", 8), "código: a 1ª linha ficou igual");
mods(TB_MOD_CTRL); key(TB_KEY_A + ('a' - 'a'), 0, 0); mods(0);
type("ok");
CHECK(!strcmp(CODE_LINE, "ok") && !strncmp(CODE_DESC, "linha 1 ", 8), "código: Ctrl+A seleciona tudo");
#undef CODE_LINE
#undef CODE_DESC
}
/* 23. Botão "+" -> nova aba: Edição de Imagem */
key(TB_KEY_ESCAPE, 0, 0);
frame(0, 0, 0, 0, 0, 0, NULL);
ax_do(ax_in(ax_in(0, TB_A11Y_TAB_LIST, "Abas"), TB_A11Y_BUTTON, "Nova aba"), TB_A11Y_ACT_ACTIVATE);
ax_do(ax_in(ax_in(0, TB_A11Y_MENU, "Nova aba"), TB_A11Y_MENU_ITEM, "Edição de Imagem"), TB_A11Y_ACT_ACTIVATE);
{
int w = ws();
CHECK(ax_in(w, TB_A11Y_LIST, "Camadas") >= 0, "aba de imagem mostra a lista de camadas");
CHECK(ax_in(ax_in(w, TB_A11Y_TOOLBAR, "Arquivo"), TB_A11Y_BUTTON, "Salvar") >= 0, "aba de imagem mostra o botão Salvar");
CHECK(ax_in(w, TB_A11Y_BUTTON, "Desfazer") >= 0, "aba de imagem mostra o botão Desfazer");
int cores = ax_in(w, TB_A11Y_GROUP, "Cores");
CHECK(cores >= 0 && ax_in(cores, TB_A11Y_LIST, "Paleta de cores") >= 0, "aba de imagem mostra as cores e a paleta rápida");
CHECK(cores >= 0 && N(cores)->x > N(w)->x + N(w)->w * 0.5f, "cores ficam na lateral direita");
CHECK(drawn_count(TB_DRAW_IMAGE, w) >= 1, "aba de imagem desenha a folha de desenho");
}
/* 24. Pintar na aba de imagem */
{
float x0, y0, x1, y1;
int tools = ax_in(ws(), TB_A11Y_TOOLBAR, "Ferramentas");
CHECK(img_nonwhite() == 0, "folha de desenho começa em branco");
ax_do(ax_in(tools, TB_A11Y_RADIO, "pincel"), TB_A11Y_ACT_ACTIVATE);
CHECK(N(ax_in(ax_in(ws(), TB_A11Y_TOOLBAR, "Ferramentas"), TB_A11Y_RADIO, "pincel"))->states & TB_A11Y_CHECKED,
"a ferramenta escolhida fica marcada");
int folha = ax_in(ws(), TB_A11Y_CANVAS, "Folha");
at(folha, 0.2f, 0.2f, &x0, &y0); at(folha, 0.35f, 0.5f, &x1, &y1);
drag(x0, y0, x1, y1); /* um traço na folha */
CHECK(img_nonwhite() > 0, "pincel pinta pixels na folha de desenho");
ax_do(ax_in(ws(), TB_A11Y_BUTTON, "Desfazer"), TB_A11Y_ACT_ACTIVATE);
CHECK(img_nonwhite() == 0, "Desfazer volta a folha em branco");
ax_do(ax_in(ax_in(ws(), TB_A11Y_TOOLBAR, "Ferramentas"), TB_A11Y_RADIO, "retangulo"), TB_A11Y_ACT_ACTIVATE);
folha = ax_in(ws(), TB_A11Y_CANVAS, "Folha");
at(folha, 0.55f, 0.3f, &x0, &y0); at(folha, 0.8f, 0.5f, &x1, &y1);
drag(x0, y0, x1, y1);
int rect_px = img_nonwhite();
CHECK(rect_px > 100, "ferramenta retângulo desenha o contorno");
ax_do(ax_in(ax_in(ws(), TB_A11Y_TOOLBAR, "Ferramentas"), TB_A11Y_RADIO, "elipse"), TB_A11Y_ACT_ACTIVATE);
at(folha, 0.65f, 0.32f, &x0, &y0); at(folha, 0.85f, 0.6f, &x1, &y1);
drag(x0, y0, x1, y1);
CHECK(img_nonwhite() > rect_px, "ferramenta elipse desenha o contorno");
ax_do(ax_in(ax_in(ws(), TB_A11Y_TOOLBAR, "Ferramentas"), TB_A11Y_RADIO, "preencher"), TB_A11Y_ACT_ACTIVATE);
at(folha, 0.58f, 0.45f, &x0, &y0); click(x0, y0); /* dentro do retângulo */
at(folha, 0.2f, 0.8f, &x0, &y0); click(x0, y0); /* fora das formas */
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(img_nonwhite() > rect_px * 3, "ferramenta preencher alaga a área branca");
ax_do(ax_in(ax_in(ws(), TB_A11Y_TOOLBAR, "Ferramentas"), TB_A11Y_RADIO, "conta-gotas"), TB_A11Y_ACT_ACTIVATE);
click(x0, y0);
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(toast_has("Cor do pixel"), "conta-gotas informa a cor capturada");
/* 24b. Escolher uma cor na paleta lateral */
ax_do(ax_in(ax_in(ws(), TB_A11Y_LIST, "Paleta de cores"), TB_A11Y_RADIO, "Branco"), TB_A11Y_ACT_ACTIVATE);
CHECK(!strcmp(ax_value(ax_in(ws(), TB_A11Y_LABEL, "Cor atual")), "#FFFFFF"), "paleta lateral troca a cor da ferramenta");
ax_do(ax_in(ax_in(ws(), TB_A11Y_TOOLBAR, "Ferramentas"), TB_A11Y_RADIO, "selecionar"), TB_A11Y_ACT_ACTIVATE);
CHECK(ax_in(ws(), TB_A11Y_BUTTON, "Desfazer") >= 0, "ferramenta selecionar continua disponível");
int camadas = ax_in(ws(), TB_A11Y_LIST, "Camadas");
CHECK(ax_in(camadas, TB_A11Y_LIST_ITEM, "Fundo") >= 0, "lista de camadas mostra a camada Fundo");
CHECK(ax_in(camadas, TB_A11Y_BUTTON, "Nova camada raster") >= 0, "botão de nova camada raster");
CHECK(ax_in(camadas, TB_A11Y_BUTTON, "Nova camada vetorial") >= 0, "botão de nova camada vetorial");
int eye = ax_in(ax_in(camadas, TB_A11Y_LIST_ITEM, "Fundo"), TB_A11Y_CHECKBOX, "Visível");
CHECK(eye >= 0 && (N(eye)->states & TB_A11Y_CHECKED), "camada Fundo começa visível");
ax_do(eye, TB_A11Y_ACT_ACTIVATE);
/* sem camada visível não há imagem nenhuma na folha (-1) */
CHECK(img_nonwhite() <= 0, "camada pode ser escondida");
ax_do(ax_in(ax_in(ax_in(ws(), TB_A11Y_LIST, "Camadas"), TB_A11Y_LIST_ITEM, "Fundo"), TB_A11Y_CHECKBOX, "Visível"),
TB_A11Y_ACT_ACTIVATE);
CHECK(img_nonwhite() > 0, "camada pode ser mostrada de novo");
}
/* 22b. Áreas estilo Blender: redimensionar arrastando a borda, trocar de lugar pela alça */
{
frame(0, 0, 0, 0, 0, 0, NULL);
int pb = pane("Blocos");
CHECK(pb >= 0 && N(pb)->x < 100 && ax_in(pb, TB_A11Y_BUTTON, "Mover a área Blocos") >= 0,
"paleta é a área \"Blocos\", com alça");
/* borda paleta | scripts: 100 px para a direita */
int sep = ax_in(0, TB_A11Y_SEPARATOR, "Borda entre Blocos e Scripts");
ax_drop_at(sep, sep, 100, 0);
CHECK(fabsf(N(pane("Blocos"))->w - 418.f) < 1.f, "arrastar a borda alarga a paleta (418 px)");
CHECK(N(pane("Palco"))->x > 900, "palco continua na direita");
/* alça do palco -> solta sobre os scripts */
ax_drop(ax_in(pane("Palco"), TB_A11Y_BUTTON, "Mover a área Palco"), pane("Scripts"));
CHECK(N(pane("Palco"))->x >= 418 && N(pane("Palco"))->x < 900, "alça troca o palco com a área de scripts");
/* e de volta: os scripts agora estão à direita */
ax_drop(ax_in(pane("Palco"), TB_A11Y_BUTTON, "Mover a área Palco"), pane("Scripts"));
CHECK(N(pane("Palco"))->x > 900, "trocar de novo devolve o palco à direita");
/* layout salvo nas configurações (arquivo isolado do harness) */
CHECK(!strcmp(tb_environ_get("editor.layout"), "H0:418(p,H1:360(s,V0:310(t,o)))"),
"layout salvo em editor.layout (paleta com 418 px)");
FILE* cf = fopen("/tmp/tb_harness_cfg/tinyblocks/settings.csv", "rb");
char cbuf[1024] = "";
if (cf) { size_t n = fread(cbuf, 1, sizeof(cbuf) - 1, cf); cbuf[n] = 0; fclose(cf); }
CHECK(strstr(cbuf, "editor.layout") != NULL, "layout gravado no arquivo de configurações");
}
/* 23b. Abas: soltar uma aba sobre a vizinha reordena (como no navegador) */
{
frame(0, 0, 0, 0, 0, 0, NULL);
int tabs = ax_in(0, TB_A11Y_TAB_LIST, "Abas");
int t0 = tb_a11y_find(A(), tabs, TB_A11Y_TAB, NULL, 0), t1 = tb_a11y_find(A(), tabs, TB_A11Y_TAB, NULL, 1);
CHECK(t0 >= 0 && t1 >= 0, "há pelo menos duas abas para reordenar");
if (t0 >= 0 && t1 >= 0) {
char primeira[128];
snprintf(primeira, sizeof(primeira), "%s", N(t0)->name);
ax_drop(t0, t1);
tabs = ax_in(0, TB_A11Y_TAB_LIST, "Abas");
CHECK(!strcmp(N(tb_a11y_find(A(), tabs, TB_A11Y_TAB, NULL, 1))->name, primeira),
"soltar a aba sobre a vizinha troca a ordem");
/* soltar a aba longe da barra destaca numa janela própria */
int t = ax_in(tabs, TB_A11Y_TAB, primeira), sc = pane("Scripts");
ax_drop_at(t, sc, N(t)->x - N(sc)->x, 300);
CHECK(ax_in(ax_in(0, TB_A11Y_TAB_LIST, "Abas"), TB_A11Y_TAB, primeira) < 0 &&
ax_in(ax_in(0, TB_A11Y_TOOLBAR, "Menu"), TB_A11Y_BUTTON, primeira) >= 0,
"aba arrastada para fora vira janela (botão no menu)");
ax_do(ax_in(ax_in(0, TB_A11Y_TOOLBAR, "Menu"), TB_A11Y_BUTTON, primeira), TB_A11Y_ACT_ACTIVATE);
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(ax_in(ax_in(0, TB_A11Y_TAB_LIST, "Abas"), TB_A11Y_TAB, primeira) >= 0,
"botão no menu traz a aba de volta para a barra");
}
}
/* 24. Notação do fórum (scratchblocks): Abrir .txt cria aba; Exportar gera o texto */
{
const char* src = "/tmp/tb_harness_sb.txt";
const char* dst = "/tmp/tb_harness_sb_out.txt";
const char* script =
"when flag clicked\n"
"set [x v] to (0)\n"
"repeat (3)\n"
" change [x v] by (1)\n"
"end\n"
"say (x)\n";
FILE* f = fopen(src, "wb");
if (f) { fputs(script, f); fclose(f); }
remove(dst);
frame(0, 0, 0, 0, 0, 0, NULL);
ax_do(menu_btn("Abrir"), TB_A11Y_ACT_ACTIVATE);
type_path(src);
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(toast_has("Importado: 1 script"), "Abrir um .txt em scratchblocks cria aba com o script");
CHECK(toast_has("de tb_harness_sb.txt"), "aba nova recebe o nome do arquivo");
CHECK(ws_block("repita", 0) >= 0, "blocos importados aparecem (repita)");
ax_do(menu_btn("Exportar"), TB_A11Y_ACT_ACTIVATE);
ax_do(ax_in(ax_in(0, TB_A11Y_MENU, "Menu de contexto"), TB_A11Y_MENU_ITEM, "Exportar scratchblocks"),
TB_A11Y_ACT_ACTIVATE);
int prev = ax_part(0, TB_A11Y_DIALOG, "Prévia scratchblocks");
CHECK(prev >= 0 && strstr(ax_value(ax_in(prev, TB_A11Y_TEXT_FIELD, "scratchblocks")), "when flag clicked") &&
ax_in(prev, TB_A11Y_BUTTON, "Copiar") >= 0, "Exportar scratchblocks abre a prévia com o texto");
ax_do(ax_in(prev, TB_A11Y_BUTTON, "Copiar"), TB_A11Y_ACT_ACTIVATE);
char* clip = tb_graphics_get_clipboard();
CHECK(clip && strstr(clip, "[scratchblocks]\nwhen flag clicked\n") && strstr(clip, "[/scratchblocks]"),
"Copiar põe o texto com [scratchblocks] na área de transferência");
free(clip);
ax_do(ax_in(ax_part(0, TB_A11Y_DIALOG, "Prévia scratchblocks"), TB_A11Y_BUTTON, "Salvar..."), TB_A11Y_ACT_ACTIVATE);
type_path(dst);
frame(0, 0, 0, 0, 0, 0, NULL);
char got[512] = "";
f = fopen(dst, "rb");
if (f) { size_t n = fread(got, 1, sizeof(got) - 1, f); got[n] = 0; fclose(f); }
CHECK(!strcmp(got, script), "Exportar scratchblocks gera o mesmo texto");
if (strcmp(got, script)) printf("---- exportado:\n%s----\n", got);
/* colar do fórum: a área de transferência vira uma aba */
tb_graphics_set_clipboard("[scratchblocks]\nwhen flag clicked\nerase all\n[/scratchblocks]\n");
ax_do(menu_btn("Exportar"), TB_A11Y_ACT_ACTIVATE);
ax_do(ax_in(ax_in(0, TB_A11Y_MENU, "Menu de contexto"), TB_A11Y_MENU_ITEM, "Colar scratchblocks"),
TB_A11Y_ACT_ACTIVATE);
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(toast_has("Importado: 1 script(s) de Colado"), "Colar scratchblocks importa da área de transferência");
remove(src); remove(dst);
}
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);
}
ax_do(menu_btn("Abrir"), TB_A11Y_ACT_ACTIVATE);
type_path(pj);
frame(0, 0, 0, 0, 0, 0, NULL);
int tente = ws_block("tente", 0);
CHECK(tente >= 0 && ax_in(tente, TB_A11Y_GROUP, "se der erro") >= 0 && ax_in(tente, TB_A11Y_GROUP, "finalmente") >= 0,
"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(console_has("deu ruim") && !console_has("nao roda"), "erro pula o resto do tente e vai para o se der erro");
CHECK(console_has("no finalmente"), "finalmente roda depois");
CHECK(console_has("77"), "tente obter + desembrulhe + valor de ... ou: erro vira valor (Result)");
CHECK(console_has("[ERRO] sem tente") && !console_has("nunca"), "erro sem tente para o script e aparece na saída");
remove(pj);
}
/* 25. Grupos (como no Unreal): agrupar a pilha e mover tudo pelo título */
{
frame(0, 0, 0, 0, 0, 0, NULL);
int hat = ws_block("quando a bandeira for clicado", 0);
CHECK(hat >= 0, "achei o chapéu");
if (hat >= 0) {
int w = ws();
ax_drop_at(hat, w, N(hat)->x - N(w)->x + 40, N(hat)->y - N(w)->y + 160); /* longe da barra de abas */
hat = ws_block("quando a bandeira for clicado", 0);
float hx0 = N(hat)->x, hy0 = N(hat)->y;
ax_do(hat, TB_A11Y_ACT_MENU);
ax_do(ax_in(ax_in(0, TB_A11Y_MENU, "Menu de contexto"), TB_A11Y_MENU_ITEM, "Agrupar esta pilha"),
TB_A11Y_ACT_ACTIVATE);
CHECK(N(tb_a11y_focus(A()))->role == TB_A11Y_GROUP, "o título do grupo novo recebe o foco");
for (int i = 0; i < 12; i++) key(TB_KEY_BACKSPACE, 0, 0);
type("Principal");
key(TB_KEY_RETURN, 0, 0);
int g = ax_in(ws(), TB_A11Y_GROUP, "Principal");
CHECK(g >= 0, "Agrupar esta pilha cria o grupo com título");
float gx0 = g >= 0 ? N(g)->x : 0;
w = ws();
ax_drop_at(g, w, N(g)->x - N(w)->x + 120, N(g)->y - N(w)->y + 70); /* arrasta pelo título */
hat = ws_block("quando a bandeira for clicado", 0);
CHECK(hat >= 0 && fabsf(N(hat)->x - (hx0 + 120)) < 2 && fabsf(N(hat)->y - (hy0 + 70)) < 2,
"arrastar o título do grupo move a pilha junto");
g = ax_in(ws(), TB_A11Y_GROUP, "Principal");
CHECK(g >= 0 && fabsf(N(g)->x - (gx0 + 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);
ax_do(menu_btn("Salvar"), TB_A11Y_ACT_ACTIVATE);
type_path(gp);
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");
}
}
/* 27. Dois blocos definidos na mesma aba: os dois aparecem em Meus Blocos */
{
const char* nomes[2] = { "render", "draw button" };
for (int k = 0; k < 2; k++) {
cat("Meus Blocos");
ax_do(ax_need(pal(), TB_A11Y_BUTTON, "Criar um Bloco"), TB_A11Y_ACT_ACTIVATE);
type(nomes[k]); /* o foco abre no nome do bloco */
key(TB_KEY_RETURN, 0, 0);
}
cat("Meus Blocos");
int mine = ax_in(pal(), TB_A11Y_GROUP, "Meus Blocos");
CHECK(ax_in(mine, TB_A11Y_BLOCK, "render") >= 0 && ax_in(mine, TB_A11Y_BLOCK, "draw button") >= 0,
"dois blocos definidos aparecem na paleta");
}
/* 28. Interface de acessibilidade: estrutura, estados, eventos, acoes */
{
frame(0, 0, 0, 0, 0, 0, NULL);
int menu = ax_in(0, TB_A11Y_TOOLBAR, "Menu");
CHECK(menu >= 0 && ax_in(menu, TB_A11Y_BUTTON, "Abrir") >= 0 && ax_in(menu, TB_A11Y_BUTTON, "Salvar") >= 0 &&
ax_in(menu, TB_A11Y_BUTTON, "Config") >= 0 && ax_in(menu, TB_A11Y_BUTTON, "Carregar library...") >= 0,
"a11y: barra de menu com os botões");
CHECK(ax_in(0, TB_A11Y_PANE, "Blocos") >= 0 && ax_in(0, TB_A11Y_PANE, "Scripts") >= 0 &&
ax_in(0, TB_A11Y_PANE, "Palco") >= 0 && ax_in(0, TB_A11Y_PANE, "Saída") >= 0,
"a11y: as quatro áreas são painéis");
int run = ax_in(ax_in(0, TB_A11Y_PANE, "Palco"), TB_A11Y_BUTTON, "Executar");
uint32_t run_id = run >= 0 ? N(run)->id : 0;
char d[256];
CHECK(run >= 0 && !strcmp(tb_a11y_describe(A(), run, d, sizeof(d)), "Executar, botão"),
"a11y: o narrador diz \"Executar, botão\"");
/* categoria: ativar seleciona (e gera evento de estado) */
int cats = ax_in(0, TB_A11Y_TAB_LIST, "Categorias");
ax_do(ax_in(cats, TB_A11Y_TAB, "Controle"), TB_A11Y_ACT_ACTIVATE);
int ctl = ax_in(ax_in(0, TB_A11Y_TAB_LIST, "Categorias"), TB_A11Y_TAB, "Controle");
bool ev_state = false;
for (int i = 0; i < tb_a11y_event_count(A()); i++) {
const TinyBlocks_A11yEvent* e = tb_a11y_event(A(), i);
if (e->kind == TB_A11Y_EV_STATE && e->node == ctl) ev_state = true;
}
CHECK(ctl >= 0 && (N(ctl)->states & TB_A11Y_SELECTED) && ev_state,
"a11y: ativar a categoria a seleciona (evento de estado)");
int sel = 0;
for (int k = 0; tb_a11y_find(A(), cats, TB_A11Y_TAB, NULL, k) >= 0; k++)
if (N(tb_a11y_find(A(), cats, TB_A11Y_TAB, NULL, k))->states & TB_A11Y_SELECTED) sel++;
CHECK(sel == 1, "a11y: uma categoria selecionada por vez");
run = ax_in(0, TB_A11Y_BUTTON, "Executar");
CHECK(run >= 0 && N(run)->id == run_id, "a11y: ids estáveis entre quadros");
/* blocos da paleta fora da vista ficam OFFSCREEN, mas estão na árvore */
int pl = pal();
int far = ax_in(pl, TB_A11Y_GROUP, "Meus Blocos");
CHECK(far >= 0 && (N(far)->states & TB_A11Y_OFFSCREEN) && ax_in(pl, TB_A11Y_GROUP, "Controle") >= 0 &&
!(N(ax_in(pl, TB_A11Y_GROUP, "Controle"))->states & TB_A11Y_OFFSCREEN),
"a11y: a paleta toda está na árvore; o que não aparece é OFFSCREEN");
/* dialogo: abrir pelo botão, evento SHOWN, voltar fecha */
ax_do(ax_in(0, TB_A11Y_BUTTON, "Config"), TB_A11Y_ACT_ACTIVATE);
int dlg = ax_in(0, TB_A11Y_DIALOG, "Configurações");
bool shown = false;
for (int i = 0; i < tb_a11y_event_count(A()); i++)
if (tb_a11y_event(A(), i)->kind == TB_A11Y_EV_SHOWN && tb_a11y_event(A(), i)->node == dlg) shown = true;
CHECK(dlg >= 0 && (N(dlg)->states & TB_A11Y_MODAL) && shown, "a11y: Config abre um diálogo modal (evento)");
ax_do(ax_in(dlg, TB_A11Y_BUTTON, "Voltar"), TB_A11Y_ACT_ACTIVATE);
CHECK(ax_in(0, TB_A11Y_DIALOG, "Configurações") < 0, "a11y: Voltar fecha o diálogo");
/* menu "+": o botão fica EXPANDED e o menu tem os itens */
ax_do(ax_in(ax_in(0, TB_A11Y_TAB_LIST, "Abas"), TB_A11Y_BUTTON, "Nova aba"), TB_A11Y_ACT_ACTIVATE);
int pm = ax_in(0, TB_A11Y_MENU, "Nova aba");
CHECK(pm >= 0 && ax_in(pm, TB_A11Y_MENU_ITEM, "Editor de Código") >= 0 &&
(N(ax_in(0, TB_A11Y_BUTTON, "Nova aba"))->states & TB_A11Y_EXPANDED),
"a11y: o menu \"Nova aba\" abre com os itens");
ax_do(ax_in(pm, TB_A11Y_MENU_ITEM, "Editor de Código"), TB_A11Y_ACT_ACTIVATE);
int code = ax_in(0, TB_A11Y_TEXT_FIELD, "Código");
CHECK(code >= 0 && tb_a11y_focus(A()) == code, "a11y: aba de código é um campo de texto com o foco");
type("int x;");
CHECK(!strcmp(ax_value(ax_in(0, TB_A11Y_TEXT_FIELD, "Código")), "int x;"), "a11y: valor = linha do cursor");
{ /* fecha a aba de codigo (a selecionada) */
int tabs = ax_in(0, TB_A11Y_TAB_LIST, "Abas"), cur = -1;
for (int k = 0, t; (t = tb_a11y_find(A(), tabs, TB_A11Y_TAB, NULL, k)) >= 0; k++)
if (N(t)->states & TB_A11Y_SELECTED) cur = t;
ax_do(ax_in(cur, TB_A11Y_BUTTON, "Fechar aba"), TB_A11Y_ACT_ACTIVATE);
CHECK(ax_in(0, TB_A11Y_TEXT_FIELD, "Código") < 0, "a11y: \"Fechar aba\" fecha a aba");
}
/* menu de contexto num bloco */
int hat = ax_in(ax_in(0, TB_A11Y_TAB_PANEL, NULL), TB_A11Y_BLOCK, "quando a bandeira for clicado");
CHECK(hat >= 0 && (N(hat)->states & TB_A11Y_OFFSCREEN), "a11y: bloco fora da vista é OFFSCREEN");
ax_do(hat, TB_A11Y_ACT_MENU); /* rola até ele e abre o menu */
int cm = ax_in(0, TB_A11Y_MENU, "Menu de contexto");
CHECK(cm >= 0 && ax_in(cm, TB_A11Y_MENU_ITEM, "Duplicar") >= 0, "a11y: menu de contexto do bloco");
key(TB_KEY_ESCAPE, 0, 0);
/* ponte de texto (um narrador simples) */
FILE* log = tmpfile();
if (log) {
TinyBlocks_A11yBridge b = tb_a11y_log_bridge(log);
tb_a11y_set_bridge(A(), &b);
ax_do(ax_in(0, TB_A11Y_BUTTON, "Config"), TB_A11Y_ACT_ACTIVATE);
ax_do(ax_in(ax_in(0, TB_A11Y_DIALOG, "Configurações"), TB_A11Y_BUTTON, "Voltar"), TB_A11Y_ACT_ACTIVATE);
tb_a11y_set_bridge(A(), NULL);
char lb[2048] = "";
rewind(log);
size_t n = fread(lb, 1, sizeof(lb) - 1, log);
lb[n] = 0;
fclose(log);
CHECK(strstr(lb, "[a11y] abriu: Configurações, diálogo") != NULL, "a11y: a ponte recebe os eventos");
}
}
/* 29. Servidor MCP do editor: um agente edita as pilhas por codigo */
{
bool err;
TinyBlocks_JsonValue* sc = NULL;
char* t;
TinyBlocks_JsonValue* tl = NULL;
{
int st = 0;
char* r = tb_mcp_server_handle(tb_editor_mcp_server(scene),
"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\",\"params\":{\"_meta\":{"
"\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\",\"io.modelcontextprotocol/clientCapabilities\":{}}}}",
NULL, &st);
CHECK(r && strstr(r, "\"add_scratchblocks\"") && strstr(r, "\"replace_stack\"") && strstr(r, "\"move_block\"") &&
strstr(r, "\"ui_action\""), "mcp: o editor lista as ferramentas");
free(r);
}
(void)tl;
t = mcp("new_tab", "{\"name\":\"Agente\"}", &err, NULL);
CHECK(!err && (N(ax_in(ax_in(0, TB_A11Y_TAB_LIST, "Abas"), TB_A11Y_TAB, "Agente"))->states & TB_A11Y_SELECTED),
"mcp: new_tab cria e seleciona a aba");
free(t);
t = mcp("add_scratchblocks", "{\"code\":\"when flag clicked\\nset [x v] to (0)\\nrepeat (3)\\n"
"change [x v] by (1)\\nend\\nsay (x)\\n\",\"x\":40,\"y\":40}", &err, &sc);
int stack = (int)sc_num(sc, "stacks.0.id");
tb_json_release(sc);
CHECK(!err && stack >= 0 && ax_in(ws(), TB_A11Y_LIST, "Pilha: quando a bandeira for clicado") >= 0 &&
ws_block("repita (3) vezes", 0) >= 0, "mcp: add_scratchblocks cria a pilha (aparece na aba)");
free(t);
t = mcp("list_stacks", "{}", &err, &sc);
CHECK(!err && strstr(t, "repeat (3)") && strstr(t, "repita (3) vezes") && sc_num(sc, "stacks.0.id") == stack,
"mcp: list_stacks mostra o código e os blocos com ids");
/* acha o id do "repita" na lista de blocos */
int rep_id = -1;
for (int i = 0; i < 20; i++) {
char path[32];
snprintf(path, sizeof(path), "stacks.0.blocks.%d.id", i);
int id = (int)sc_num(sc, path);
if (id < 0) break;
TinyBlocks_JsonValue* stks = tb_json_object_get(sc, "stacks");
TinyBlocks_JsonValue* st0 = tb_json_array_get(stks, 0);
TinyBlocks_JsonValue* bl = tb_json_object_get(st0, "blocks");
TinyBlocks_JsonValue* b = tb_json_array_get(bl, (uint32_t)i);
TinyBlocks_JsonValue* ty = tb_json_object_get(b, "type");
if (ty && !strcmp(tb_json_as_string(ty), "Control.Repeat")) rep_id = id;
tb_json_release(ty); tb_json_release(b); tb_json_release(bl); tb_json_release(st0); tb_json_release(stks);
}
tb_json_release(sc);
free(t);
CHECK(rep_id >= 0, "mcp: o id do repita está na lista");
t = mcp("run", "{}", &err, NULL);
free(t);
for (int i = 0; i < 5; i++) frame(0, 0, 0, 0, 0, 0, NULL);
t = mcp("get_output", "{}", &err, NULL);
CHECK(!err && strstr(t, "Saida:\n3"), "mcp: run + get_output (a pilha escreve 3)");
free(t);
char args[256];
snprintf(args, sizeof(args), "{\"block\":%d,\"inputs\":{\"vezes\":5}}", rep_id);
t = mcp("set_inputs", args, &err, NULL);
CHECK(!err && strstr(t, "repeat (5)") && ws_block("repita (5) vezes", 0) >= 0, "mcp: set_inputs muda o campo");
free(t);
snprintf(args, sizeof(args), "{\"type\":\"IO.Print\",\"inputs\":{\"0\":\"fim\"},\"below\":%d}", rep_id);
t = mcp("add_block", args, &err, &sc);
int fim = (int)sc_num(sc, "block");
tb_json_release(sc);
CHECK(!err && fim >= 0 && strstr(t, "say [fim]"), "mcp: add_block encaixa embaixo do repita");
free(t);
snprintf(args, sizeof(args), "{\"block\":%d,\"into\":%d,\"mouth\":0,\"alone\":true}", fim, rep_id);
t = mcp("move_block", args, &err, NULL);
CHECK(!err && strstr(t, "repeat (5)\n say [fim]\n change [x v] by (1)\nend\nsay (x)"),
"mcp: move_block (alone) põe só o bloco no começo da boca");
free(t);
snprintf(args, sizeof(args), "{\"block\":%d,\"below\":%d,\"alone\":true}", fim, rep_id);
t = mcp("move_block", args, &err, NULL);
CHECK(!err && strstr(t, "repeat (5)\n change [x v] by (1)\nend\nsay [fim]\nsay (x)"),
"mcp: move_block encaixa embaixo (o que estava ali vai depois)");
free(t);
t = mcp("move_block", "{\"block\":9999,\"x\":0,\"y\":0}", &err, NULL);
CHECK(err && strstr(t, "nao existe"), "mcp: bloco inexistente vira erro da ferramenta");
free(t);
snprintf(args, sizeof(args), "{\"block\":%d,\"below\":%d}", rep_id, fim);
t = mcp("move_block", args, &err, NULL);
CHECK(err && strstr(t, "nele mesmo"), "mcp: não encaixa um bloco dentro dele mesmo");
free(t);
t = mcp("add_block", "{\"type\":\"Nao.Existe\"}", &err, NULL);
CHECK(err && strstr(t, "list_block_types"), "mcp: tipo desconhecido sugere list_block_types");
free(t);
snprintf(args, sizeof(args), "{\"stack\":%d}", stack);
t = mcp("get_scratchblocks", args, &err, NULL);
CHECK(!err && strstr(t, "when flag clicked") && strstr(t, "repeat (5)"), "mcp: get_scratchblocks de uma pilha");
free(t);
snprintf(args, sizeof(args), "{\"stack\":%d,\"x\":300,\"y\":200}", stack);
float y_before = N(ax_in(ws(), TB_A11Y_LIST, "Pilha: quando a bandeira for clicado"))->y;
t = mcp("move_stack", args, &err, NULL);
CHECK(!err && N(ax_in(ws(), TB_A11Y_LIST, "Pilha: quando a bandeira for clicado"))->y > y_before,
"mcp: move_stack leva a pilha (a interface acompanha)");
free(t);
snprintf(args, sizeof(args), "{\"stack\":%d,\"code\":\"when flag clicked\\nsay [trocado]\\n\"}", stack);
t = mcp("replace_stack", args, &err, &sc);
int stack2 = (int)sc_num(sc, "stacks.0.id");
tb_json_release(sc);
CHECK(!err && ws_block("repita", 0) < 0 && ws_block("escreva (trocado)", 0) >= 0, "mcp: replace_stack troca o código");
free(t);
snprintf(args, sizeof(args), "{\"stack\":%d,\"code\":\"isso nao e scratchblocks\"}", stack2);
t = mcp("replace_stack", args, &err, NULL);
CHECK(err && ws_block("escreva (trocado)", 0) >= 0, "mcp: código inválido não apaga a pilha");
free(t);
snprintf(args, sizeof(args), "{\"stack\":%d}", stack2);
t = mcp("delete_stack", args, &err, NULL);
CHECK(!err && ax_in(ws(), TB_A11Y_LIST, NULL) < 0, "mcp: delete_stack apaga a pilha");
free(t);
/* a interface pela arvore acessivel */
t = mcp("ui_action", "{\"role\":\"botão\",\"name\":\"Config\"}", &err, NULL);
CHECK(!err && ax_in(0, TB_A11Y_DIALOG, "Configurações") >= 0, "mcp: ui_action clica no botão Config");
free(t);
t = mcp("ui_tree", "{\"within\":\"Configurações\"}", &err, NULL);
CHECK(!err && strstr(t, "Configurações, diálogo") && strstr(t, "Voltar, botão"), "mcp: ui_tree mostra o diálogo");
free(t);
t = mcp("ui_type", "{\"key\":\"escape\"}", &err, NULL);
CHECK(!err && ax_in(0, TB_A11Y_DIALOG, "Configurações") < 0, "mcp: ui_type aperta Esc e fecha");
free(t);
/* colar de uma vez mais blocos que o limite antigo por aba (256) */
{
size_t cap = 400 * 40 + 64;
char* big = (char*)malloc(cap);
size_t p = 0;
p += snprintf(big + p, cap - p, "{\"code\":\"when flag clicked\\n");
for (int i = 0; i < 300; i++) p += snprintf(big + p, cap - p, "change [colados v] by (1)\\n");
p += snprintf(big + p, cap - p, "\",\"x\":40,\"y\":600}");
t = mcp("add_scratchblocks", big, &err, NULL);
free(big);
CHECK(!err && ws_count("adicione (1) a (colados)") >= 300,
"mcp: cola 300 blocos numa aba (o limite antigo era 256)");
free(t);
}
}
/* 14. Aba grande: mais blocos que o limite antigo (256): carrega, roda e salva */
{
const int N = 600;
const char* bigp = "/tmp/tb_harness_big.json";
remove(bigp);
FILE* bf = fopen(bigp, "wb");
CHECK(bf != NULL, "aba grande: projeto de teste escrito");
if (bf) {
fputs("{\"format\":\"tinyblocks-project\",\"version\":2,\"cur_tab\":0,"
"\"tabs\":[{\"name\":\"Grande\",\"composite\":false,\"comp_id\":-1,\"color\":0,\"blocks\":[", bf);
fprintf(bf, "{\"i\":0,\"type\":\"Events.WhenRun\",\"x\":40,\"y\":40,\"next\":1}");
for (int i = 1; i <= N; i++)
fprintf(bf, ",{\"i\":%d,\"type\":\"Variables.Change\",\"parent\":%d,\"prel\":0,\"next\":%d,"
"\"in_text\":[\"cont\",\"1\"]}", i, i - 1, i + 1);
fprintf(bf, ",{\"i\":%d,\"type\":\"IO.Print\",\"parent\":%d,\"prel\":0,"
"\"in_text\":[\"cont\",\"\"],"
"\"args\":[-1,%d,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1]}", N + 1, N, N + 2);
fprintf(bf, ",{\"i\":%d,\"type\":\"Variables.Get\",\"parent\":%d,\"prel\":5,"
"\"in_text\":[\"cont\"]}", N + 2, N + 1);
fputs("],\"top\":[0]}],\"user_blocks\":[],"
"\"variables\":[{\"name\":\"cont\",\"kind\":0,\"num\":0,\"text\":\"\"}]}", bf);
fclose(bf);
}
ax_do(menu_btn("Abrir"), TB_A11Y_ACT_ACTIVATE);
type_path(bigp);
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(ax_in(ax_in(0, TB_A11Y_TAB_LIST, "Abas"), TB_A11Y_TAB, "Grande") >= 0,
"aba grande: abre o projeto de 602 blocos");
CHECK(ws_count("adicione (1) a (cont)") >= N,
"aba grande: os 600 blocos entram na área de scripts");
{
/* a area de scripts e desenhada antes do palco: sem culling os
* blocos fora da vista comem o teto de comandos e o palco some */
int stage = ax_in(pane("Palco"), TB_A11Y_CANVAS, "Palco");
CHECK(stage >= 0 && drawn_count(TB_DRAW_FILL_RECT, stage) > 0,
"aba grande: o palco continua desenhado (culling dos blocos fora da vista)");
CHECK(pane("Saída") >= 0 && ncmd < TB_DRAW_CMD_CAP,
"aba grande: os comandos de desenho não estouram o teto");
}
flag();
for (int i = 0; i < 4; i++) frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(console_has("cont = 600"), "aba grande: o script roda inteiro (a VM passa do bloco 256)");
stop();
const char* bigp2 = "/tmp/tb_harness_big2.json";
remove(bigp2);
ax_do(menu_btn("Salvar"), TB_A11Y_ACT_ACTIVATE);
type_path(bigp2);
CHECK(toast_has("Projeto salvo"), "aba grande: salva o projeto");
ax_do(menu_btn("Abrir"), TB_A11Y_ACT_ACTIVATE);
type_path(bigp2);
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(ws_count("adicione (1) a (cont)") >= N, "aba grande: volta inteira do arquivo salvo");
remove(bigp);
remove(bigp2);
}
/* 30. Expressoes compiladas (tb_editor_jit.c): mesma saida que no por no */
{
bool err = false;
char* t = mcp("new_tab", "{\"name\":\"Contas\"}", &err, NULL);
free(t);
t = mcp("add_scratchblocks", "{\"code\":\"when flag clicked\\n"
"set [t v] to [abc]\\nset [n v] to (7)\\n"
"delete all of [L v]\\nadd (1) to [L v]\\nadd (5) to [L v]\\n"
"say (join [a=] ((n) / (2)))\\n"
"say (join [b=] (((n) - (1)) * (0.5)))\\n"
"say (join [c=] ((t) + (1)))\\n"
"say (join [d=] ((item (2) of [L v]) * (10)))\\n"
"if <<(t) = [ABC]> and <not <(n) < (5)>>> then\\nsay [e=sim]\\nend\\n"
"if <[abd] > (t)> then\\nsay [f=sim]\\nend\\n"
"say (join [g=] ((n) * (n)))\\n"
"set [m v] to (n)\\nchange [m v] by (0.5)\\nset [m v] to ((m) * (2))\\n"
"set [s v] to (t)\\nchange [k2 v] by (3)\\nsay (join (join [h=] (m)) (join (s) (k2)))\\n\",\"x\":40,\"y\":40}", &err, NULL);
CHECK(!err, "contas: cria o script");
free(t);
flag();
for (int i = 0; i < 3; i++) frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(console_has("a=3.5"), "compilado: (7) / (2) = 3.5");
CHECK(console_has("b=3"), "compilado: ((7) - (1)) * (0.5) = 3");
CHECK(console_has("c=1"), "compilado: texto numa conta vale 0");
CHECK(console_has("d=50"), "compilado: item de lista (não compilado) dentro da conta");
CHECK(console_has("e=sim"), "compilado: = compara texto sem maiúsculas; não; e");
CHECK(console_has("f=sim"), "compilado: > entre textos compara o texto");
CHECK(console_has("g=49"), "compilado: inteiro * inteiro");
CHECK(console_has("h=15abc3"), "comando compilado: mude para (variável / conta com ela mesma), mude por (0.5), "
"texto copiado, mude por cria a variável");
stop();
}
/* 30b. Encaixes de bloco (TB_SLOT_CODE / TB_SLOT_STACK): o bloco encaixado
* vai como codigo (JSON) e nao roda */
{
bool err = false;
char* t = mcp("new_tab", "{\"name\":\"Encaixes\"}", &err, NULL);
free(t);
t = mcp("add_scratchblocks", "{\"code\":\"when flag clicked\\n"
"say (join [e=] (código de ((seno de (x)) * (2))))\\n"
"say (join [p=] (código da pilha))\\nend\\n"
"say (join [x=] (x))\\n\",\"x\":40,\"y\":40}", &err, NULL);
CHECK(!err, "encaixes: cria o script");
int stk = -1;
const char* at = t ? strstr(t, "código da pilha (Control.StackCode") : NULL;
while (at && at > t && at[-1] != '[') at--;
if (at && at > t) stk = atoi(at);
free(t);
char args[160];
snprintf(args, sizeof(args), "{\"type\":\"Variables.Set\",\"inputs\":[\"x\",\"10\"],\"into\":%d,\"input\":0}", stk);
t = mcp("add_block", args, &err, NULL);
CHECK(!err && stk >= 0, "mcp: um comando entra no encaixe de pilha (into + input)");
free(t);
flag();
for (int i = 0; i < 3; i++) frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(console_has("e={\"type\":\"Math.Mul\",\"inputs\":[{\"type\":\"Number.Sin\""),
"encaixe de expressão: o código do repórter, em JSON");
CHECK(console_has("p=[{\"type\":\"Variables.Set\",\"inputs\":[\"x\",10]}]"),
"encaixe de pilha: a lista dos comandos");
CHECK(console_has("x=0"), "o comando no encaixe não rodou (x continua sem valor)");
stop();
}
/* 31. Modo compacto (celular em retrato): menu com "☰", alternador
* Código|Palco, paleta em gaveta que abre pela categoria */
{
g_win_w = 400; g_win_h = 800;
frame(0, 0, 0, 0, 0, 0, NULL);
frame(0, 0, 0, 0, 0, 0, NULL);
int menu = ax_in(0, TB_A11Y_TOOLBAR, "Menu");
CHECK(ax_in(menu, TB_A11Y_BUTTON, "Mais opções") >= 0, "compacto: botão ☰ no menu");
CHECK(ax_in(menu, TB_A11Y_BUTTON, "Bibliotecas") < 0, "compacto: Bibliotecas sai da barra");
CHECK(pane("Palco") < 0 && pane("Scripts") >= 0, "compacto: só os scripts (sem palco ao lado)");
ax_do(ax_need(menu, TB_A11Y_BUTTON, "Mais opções"), TB_A11Y_ACT_ACTIVATE);
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(ax_in(ax_in(0, TB_A11Y_MENU, NULL), TB_A11Y_MENU_ITEM, "Bibliotecas") >= 0,
"compacto: Bibliotecas no menu ☰");
frame(200, 400, 1, 0, 0, 0, NULL); /* clicar fora fecha o menu */
frame(200, 400, 0, 1, 0, 0, NULL);
CHECK(ax_in(0, TB_A11Y_MENU, NULL) < 0, "compacto: clicar fora fecha o ☰");
CHECK(pal() < 0, "compacto: gaveta da paleta começa fechada");
cat("Controle");
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(pal() >= 0, "compacto: tocar na categoria abre a gaveta");
int before = ws_count("sempre");
ax_drop_at(pal_block("Controle", "sempre"), ws(), 200, 500);
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(ws_count("sempre") == before + 1 && pal() < 0, "compacto: tirar bloco da gaveta fecha a gaveta");
ax_do(ax_need(ax_in(0, TB_A11Y_TOOLBAR, "Menu"), TB_A11Y_TAB, "Palco"), TB_A11Y_ACT_ACTIVATE);
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(pane("Palco") >= 0 && pane("Saída") >= 0 && pane("Scripts") < 0, "compacto: aba Palco mostra palco e saída");
g_win_w = 1280; g_win_h = 720;
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(pane("Palco") >= 0 && pane("Scripts") >= 0 && pane("Blocos") >= 0, "janela larga volta ao layout de áreas");
}
/* 32. Zoom da area de scripts: roda do mouse (ancorada no ponteiro) e
* pinca com dois dedos; clique/arrasto continuam acertando o bloco */
{
int b = ws_block("sempre", 0);
const TinyBlocks_A11yNode* n0 = b >= 0 ? N(b) : NULL;
float w0 = n0 ? n0->w : 0, px = 0, py = 0;
if (b >= 0) tb_a11y_point(A(), b, &px, &py);
CHECK(b >= 0 && w0 > 0, "zoom: bloco na área de scripts");
float bx0 = b >= 0 ? N(b)->x : 0, by0 = b >= 0 ? N(b)->y : 0;
g_scroll_dy = 1.f; /* roda sozinha: rola na vertical */
frame(px, py, 0, 0, 0, 0, NULL);
b = ws_block("sempre", 0);
CHECK(b >= 0 && fabsf(N(b)->y - (by0 + 40.f)) < 0.5f && fabsf(N(b)->x - bx0) < 0.5f && N(b)->w == w0,
"roda: desloca na vertical, sem zoom");
mods(TB_MOD_SHIFT); /* Shift+roda: horizontal */
g_scroll_dy = -1.f;
frame(px, py, 0, 0, 0, 0, NULL);
mods(0);
b = ws_block("sempre", 0);
CHECK(b >= 0 && fabsf(N(b)->x - (bx0 - 40.f)) < 0.5f && fabsf(N(b)->y - (by0 + 40.f)) < 0.5f,
"Shift+roda: desloca na horizontal");
g_scroll_dy = -1.f; /* volta ao lugar */
frame(px, py, 0, 0, 0, 0, NULL);
mods(TB_MOD_SHIFT); g_scroll_dy = 1.f;
frame(px, py, 0, 0, 0, 0, NULL);
mods(TB_MOD_CTRL); /* Ctrl+roda: zoom */
g_scroll_dy = 3.f;
frame(px, py, 0, 0, 0, 0, NULL);
mods(0);
frame(px, py, 0, 0, 0, 0, NULL);
b = ws_block("sempre", 0);
float r = b >= 0 ? N(b)->w / w0 : 0;
CHECK(fabsf(r - 1.331f) < 0.01f, "Ctrl+roda para cima aproxima (1,1 por passo)");
float qx = 0, qy = 0;
if (b >= 0) tb_a11y_point(A(), b, &qx, &qy);
CHECK(fabsf(qx - px) < 1.f && fabsf(qy - py) < 1.f, "zoom: o ponto sob o ponteiro fica parado");
float x0 = b >= 0 ? N(b)->x : 0;
drag(qx, qy, qx + 60, qy + 30); /* arrasto com zoom: acompanha o mouse */
b = ws_block("sempre", 0);
CHECK(b >= 0 && fabsf(N(b)->x - (x0 + 60)) < 1.f, "zoom: arrastar o bloco segue o ponteiro");
/* pinca: os dedos se afastam ao dobro -> zoom dobra */
tb_a11y_point(A(), b, &px, &py);
float w1 = N(b)->w;
g_touch_n = 2;
g_touch[0][0] = px - 30; g_touch[0][1] = py;
g_touch[1][0] = px + 30; g_touch[1][1] = py;
frame(px - 30, py, 1, 0, 0, 0, NULL);
g_touch[0][0] = px - 45; g_touch[1][0] = px + 45;
frame(px - 45, py, 0, 0, 0, 0, NULL);
g_touch[0][0] = px - 60; g_touch[1][0] = px + 60;
frame(px - 60, py, 0, 0, 0, 0, NULL);
b = ws_block("sempre", 0);
r = b >= 0 ? N(b)->w / w1 : 0;
CHECK(fabsf(r - 2.f) < 0.02f, "pinça: afastar os dedos aproxima");
tb_a11y_point(A(), b, &qx, &qy);
CHECK(fabsf(qx - px) < 1.f, "pinça: ancorada no meio dos dedos");
g_touch_n = 0;
frame(px - 60, py, 0, 1, 0, 0, NULL);
CHECK(ax_in(0, TB_A11Y_MENU, NULL) < 0 && fabsf(N(ws_block("sempre", 0))->w / w1 - 2.f) < 0.02f,
"pinça: soltar não abre menu nem mexe");
g_zoom = 0.5f; /* pinca do touchpad: fecha pela metade */
frame(px, py, 0, 0, 0, 0, NULL);
CHECK(fabsf(N(ws_block("sempre", 0))->w / w1 - 1.f) < 0.02f, "pinça no touchpad: afasta pelo fator");
mods(TB_MOD_CTRL);
g_scroll_dy = -40.f; /* afasta ate o minimo */
frame(px, py, 0, 0, 0, 0, NULL);
mods(0);
frame(px, py, 0, 0, 0, 0, NULL);
CHECK(fabsf(N(ws_block("sempre", 0))->w / w0 - 0.3f) < 0.01f, "zoom: mínimo de 30%");
}
/* 33. Diálogo de bloco: o campo do nome também se apaga (o rótulo
* seguinte vira o nome); sozinho, sem rótulo depois, não */
{
cat("Meus Blocos");
ax_do(ax_need(pal(), TB_A11Y_BUTTON, "Criar um Bloco"), TB_A11Y_ACT_ACTIVATE);
int dlg = ax_need(0, TB_A11Y_DIALOG, "Criar um Bloco");
type("a");
ax_do(ax_in(dlg, TB_A11Y_TEXT_FIELD, "Nome do bloco"), TB_A11Y_ACT_ACTIVATE);
CHECK(ax_in(dlg, TB_A11Y_BUTTON, "Apagar a parte") < 0, "nome sozinho: sem lixeira (o bloco precisa de nome)");
ax_do(ax_need(dlg, TB_A11Y_BUTTON, "Adicionar rótulo"), TB_A11Y_ACT_ACTIVATE);
type("vezes");
dlg = ax_in(0, TB_A11Y_DIALOG, "Criar um Bloco");
ax_do(ax_in(dlg, TB_A11Y_TEXT_FIELD, "Nome do bloco"), TB_A11Y_ACT_ACTIVATE);
dlg = ax_in(0, TB_A11Y_DIALOG, "Criar um Bloco");
int nome = ax_in(dlg, TB_A11Y_TEXT_FIELD, "Nome do bloco");
CHECK(nome >= 0 && (N(nome)->states & TB_A11Y_SELECTED), "clicar no nome seleciona o campo");
ax_do(ax_need(dlg, TB_A11Y_BUTTON, "Apagar a parte"), TB_A11Y_ACT_ACTIVATE);
dlg = ax_in(0, TB_A11Y_DIALOG, "Criar um Bloco");
CHECK(!strcmp(ax_value(ax_in(dlg, TB_A11Y_TEXT_FIELD, "Nome do bloco")), "vezes") &&
ax_in(dlg, TB_A11Y_TEXT_FIELD, "Rótulo") < 0, "apagar o nome: o rótulo seguinte vira o nome");
ax_do(ax_need(dlg, TB_A11Y_BUTTON, "Cancelar"), TB_A11Y_ACT_ACTIVATE);
/* reordenar: o rótulo passa para a frente do nome */
ax_do(ax_need(pal(), TB_A11Y_BUTTON, "Criar um Bloco"), TB_A11Y_ACT_ACTIVATE);
type("girar");
dlg = ax_in(0, TB_A11Y_DIALOG, "Criar um Bloco");
ax_do(ax_need(dlg, TB_A11Y_BUTTON, "Adicionar entrada de número ou texto"), TB_A11Y_ACT_ACTIVATE);
type("g");
dlg = ax_in(0, TB_A11Y_DIALOG, "Criar um Bloco");
ax_do(ax_need(dlg, TB_A11Y_BUTTON, "Adicionar rótulo"), TB_A11Y_ACT_ACTIVATE);
type("vezes");
dlg = ax_in(0, TB_A11Y_DIALOG, "Criar um Bloco");
ax_do(ax_need(dlg, TB_A11Y_BUTTON, "Mover para a esquerda"), TB_A11Y_ACT_ACTIVATE);
dlg = ax_in(0, TB_A11Y_DIALOG, "Criar um Bloco");
ax_do(ax_need(dlg, TB_A11Y_BUTTON, "Mover para a esquerda"), TB_A11Y_ACT_ACTIVATE);
dlg = ax_in(0, TB_A11Y_DIALOG, "Criar um Bloco");
int proto = ax_in(dlg, TB_A11Y_BLOCK, "Protótipo");
int first = proto >= 0 ? tb_a11y_find(A(), proto, TB_A11Y_TEXT_FIELD, NULL, 0) : -1;
CHECK(first >= 0 && !strcmp(N(first)->name, "Rótulo"), "mover para a esquerda passa o rótulo à frente do nome");
/* o nome também se move: vai para o fim */
ax_do(ax_in(dlg, TB_A11Y_TEXT_FIELD, "Nome do bloco"), TB_A11Y_ACT_ACTIVATE);
dlg = ax_in(0, TB_A11Y_DIALOG, "Criar um Bloco");
ax_do(ax_need(dlg, TB_A11Y_BUTTON, "Mover para a direita"), TB_A11Y_ACT_ACTIVATE);
dlg = ax_in(0, TB_A11Y_DIALOG, "Criar um Bloco");
ax_do(ax_need(dlg, TB_A11Y_BUTTON, "OK"), TB_A11Y_ACT_ACTIVATE);
frame(0, 0, 0, 0, 0, 0, NULL);
cat("Meus Blocos");
CHECK(ax_in(ax_in(pal(), TB_A11Y_GROUP, "Meus Blocos"), TB_A11Y_BLOCK, "vezes (g) girar") >= 0,
"bloco com o nome no fim: \"vezes (g) girar\"");
CHECK(ax_part(ws(), TB_A11Y_BLOCK, "defina vezes (g) girar") >= 0, "o defina segue a mesma ordem");
}
/* 34. Campos de texto: cursor, seleção, Ctrl+A/C/X/V e, no toque,
* segurar seleciona a palavra e mostra a barra Recortar/Copiar/... */
{
cat("Meus Blocos");
ax_do(ax_need(pal(), TB_A11Y_BUTTON, "Criar um Bloco"), TB_A11Y_ACT_ACTIVATE);
type("abc def");
#define NOME ax_value(ax_in(ax_in(0, TB_A11Y_DIALOG, "Criar um Bloco"), TB_A11Y_TEXT_FIELD, "Nome do bloco"))
mods(TB_MOD_SHIFT); for (int i = 0; i < 3; i++) key(TB_KEY_LEFT, 0, 0); mods(0);
mods(TB_MOD_CTRL); key(TB_KEY_A + ('c' - 'a'), 0, 0); mods(0);
key(TB_KEY_END, 0, 0);
mods(TB_MOD_CTRL); key(TB_KEY_A + ('v' - 'a'), 0, 0); mods(0);
CHECK(!strcmp(NOME, "abc defdef"), "campo: Shift+← seleciona, Ctrl+C e Ctrl+V colam no cursor");
key(TB_KEY_HOME, 0, 0); type("X");
CHECK(!strcmp(NOME, "Xabc defdef"), "campo: Home leva o cursor ao começo e digitar insere ali");
mods(TB_MOD_CTRL); key(TB_KEY_A + ('a' - 'a'), 0, 0); key(TB_KEY_A + ('x' - 'a'), 0, 0); mods(0);
CHECK(!strcmp(NOME, ""), "campo: Ctrl+A + Ctrl+X recortam tudo");
mods(TB_MOD_CTRL); key(TB_KEY_A + ('v' - 'a'), 0, 0); mods(0);
CHECK(!strcmp(NOME, "Xabc defdef"), "campo: Ctrl+V cola de volta");
mods(TB_MOD_SHIFT); key(TB_KEY_LEFT, 0, 0); mods(0);
key(TB_KEY_BACKSPACE, 0, 0);
CHECK(!strcmp(NOME, "Xabc defde"), "campo: Backspace apaga a seleção");
/* toque: segurar o dedo na palavra "defde" (lado direito do campo) */
int nome = ax_in(ax_in(0, TB_A11Y_DIALOG, "Criar um Bloco"), TB_A11Y_TEXT_FIELD, "Nome do bloco");
float fx = N(nome)->x + N(nome)->w * 0.5f + 20.f, fy = N(nome)->y + N(nome)->h * 0.5f;
g_touch_n = 1; g_touch[0][0] = fx; g_touch[0][1] = fy; g_l_held = 1;
frame(fx, fy, 1, 0, 0, 0, NULL);
usleep(620 * 1000);
frame(fx, fy, 0, 0, 0, 0, NULL);
frame(fx, fy, 0, 0, 0, 0, NULL);
g_touch_n = 0; g_l_held = 0;
frame(fx, fy, 0, 1, 0, 0, NULL);
int bar = ax_in(0, TB_A11Y_TOOLBAR, "Seleção");
CHECK(bar >= 0 && ax_in(bar, TB_A11Y_BUTTON, "Copiar") >= 0 && ax_in(bar, TB_A11Y_BUTTON, "Colar") >= 0,
"toque: segurar no texto mostra a barra Recortar/Copiar/Colar/Selecionar tudo");
CHECK(!strcmp(NOME, "Xabc defde"), "toque: soltar depois de segurar não muda o texto");
ax_do(ax_in(bar, TB_A11Y_BUTTON, "Recortar"), TB_A11Y_ACT_ACTIVATE);
CHECK(!strcmp(NOME, "Xabc "), "toque: Recortar tira a palavra segurada");
#undef NOME
ax_do(ax_need(ax_in(0, TB_A11Y_DIALOG, "Criar um Bloco"), TB_A11Y_BUTTON, "Cancelar"), TB_A11Y_ACT_ACTIVATE);
}
tinyblocks_deinit(&rt);
printf(fails ? "\n%d FALHA(S)\n" : "\nTUDO OK\n", fails);
return fails != 0;
}