Bloco "sempre" e execução quadro a quadro (threads estilo Scratch 3)

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mguinhosandClaude Opus 5.5 committed 2026-10-22 13:10:42 -03:00
1 parent fa0eb5dac8
commit d85dd1b624
4 files changed
+297 -22

No files matched your search

@@ -31,6 +31,8 @@ static bool control_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
"Repete o corpo do bloco o numero de vezes indicado");
TB_BLOCK_META("Control.RepeatUntil", "eval_noop",
"Repete o corpo enquanto a condicao for falsa");
TB_BLOCK_META("Control.Forever", "eval_noop",
"Repete o corpo para sempre (ate clicar no botao vermelho)");
TB_BLOCK_META("Control.If", "eval_noop",
"Executa o corpo se a condicao for verdadeira");
TB_BLOCK_META("Control.IfElse", "eval_noop",
@@ -40,6 +42,7 @@ static bool control_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
static const TinyBlocks_SlotDesc cond_in[] = {{"condição", TB_VALUE_INTEGER}};
return reg(rt, lib, "Control.Repeat", times_in, 1)
&& reg(rt, lib, "Control.RepeatUntil", cond_in, 1)
&& reg(rt, lib, "Control.Forever", NULL, 0)
&& reg(rt, lib, "Control.If", cond_in, 1)
&& reg(rt, lib, "Control.IfElse", cond_in, 1);
}
@@ -264,6 +264,7 @@ typedef struct {
static const BlockSpec s_specs[] = {
{"Events.WhenRun", "quando a bandeira for clicado", NULL},
{"Control.Repeat", "repita %1 vezes", "10"},
{"Control.Forever", "sempre", NULL},
{"Control.RepeatUntil", "repita até que %1", NULL},
{"Control.If", "se %1 então", NULL},
{"Control.IfElse", "se %1 então", NULL},
@@ -596,6 +597,33 @@ typedef struct {
int place_n;
} FileDlg;
/* 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 };
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 */
} VmFrame;
#define VM_STACK 64
#define VM_THREADS 32
typedef struct {
VmFrame st[VM_STACK];
int sp;
} VmThread;
/* Cache das arvores do runtime por (aba, bloco, profundidade de chamada):
cada comando e montado uma vez por execucao e reavaliado depois. */
#define RT_CACHE_CAP 4096
typedef struct {
Tab* T;
int bi, depth;
TinyBlocks_Block* r;
} RtCacheEnt;
/* Formatos de exportacao */
enum { EX_JSON, EX_XML, EX_CSV };
@@ -670,6 +698,13 @@ typedef struct Ed {
bool abort;
char abort_msg[160];
TinyBlocks_Block** run_blocks; /* instâncias criadas na última execução */
VmThread vm[VM_THREADS];/* scripts rodando (bandeira / clique) */
int vm_n;
bool vm_running;
bool redraw_req; /* um bloco do palco pediu redesenho */
int vm_var_n; /* variaveis conhecidas (refaz a paleta) */
RtCacheEnt rt_cache[RT_CACHE_CAP];
int rt_cache_n;
int run_n, run_cap;
Tab* live_tab;
FILE* cap_file;
+216 -21
View File
@@ -217,7 +217,8 @@ static Shape shape_of(const TinyBlocks_TypeBlock* t) {
const char* n = t->type_name;
if (strncmp(n, "Events.", 7) == 0) return SH_HAT;
if (strcmp(n, "Control.If") == 0 || strcmp(n, "Control.Repeat") == 0 ||
strcmp(n, "Control.RepeatUntil") == 0) return SH_C1;
strcmp(n, "Control.RepeatUntil") == 0 ||
strcmp(n, "Control.Forever") == 0) return SH_C1;
if (strcmp(n, "Control.IfElse") == 0) return SH_C2;
if (strcmp(n, "Operators.Lt") == 0 || strcmp(n, "Operators.Eq") == 0 ||
strcmp(n, "Operators.Gt") == 0 || strcmp(n, "Operators.And") == 0 ||
@@ -235,6 +236,11 @@ static Shape shape_of(const TinyBlocks_TypeBlock* t) {
static bool shape_is_value(Shape s) { return s == SH_REPORTER || s == SH_BOOL; }
/* Bloco "tampa" (como o "sempre" do Scratch): nada encaixa embaixo dele */
static bool is_cap(const TinyBlocks_TypeBlock* t) {
return t && t->type_name && strcmp(t->type_name, "Control.Forever") == 0;
}
static UserBlockDef* user_def_find(Ed* ed, const char* name);
/* idx-ésima entrada (NUM/BOOL) do protótipo; NULL se fora do intervalo */
@@ -929,7 +935,7 @@ static void render_block(Ed* ed, TinyBlocks_RenderableBlock* rb, Tab* T, int bi,
}
/* Encaixe inferior por último: fica sobre o topo do bloco seguinte */
if (!shape_is_value(sh)) draw_bump(rb, x, y + h, c, d);
if (!shape_is_value(sh) && !is_cap(b->type)) draw_bump(rb, x, y + h, c, d);
}
/* Desenha de baixo para cima, para cada encaixe cobrir o bloco seguinte */
@@ -964,8 +970,12 @@ static void clear_live(Tab* T) {
for (int i = 0; i < MAX_WS; i++) T->ws[i].live_rt = NULL;
}
/* Destrói as instâncias do runtime da execução anterior */
/* Destrói as instâncias do runtime da execução anterior (e para os scripts) */
static void run_reset(Ed* ed) {
ed->vm_n = 0;
ed->vm_running = false;
ed->rt_cache_n = 0;
memset(ed->rt_cache, 0, sizeof(ed->rt_cache));
for (int i = ed->run_n - 1; i >= 0; i--) tb_block_destroy(ed->run_blocks[i], ed->rt);
ed->run_n = 0;
for (int t = 0; t < ed->tab_n; t++) clear_live(&ed->tabs[t]);
@@ -1016,9 +1026,51 @@ static TinyBlocks_Block* build_rt(Ed* ed, Tab* T, int bi) {
return r;
}
/* Esquece as arvores em cache (sem destrui-las: continuam em run_blocks).
Chamado quando o usuario edita algo, para a edicao valer no programa
que esta rodando. */
static void rt_cache_clear(Ed* ed) {
if (!ed->rt_cache_n) return;
ed->rt_cache_n = 0;
memset(ed->rt_cache, 0, sizeof(ed->rt_cache));
}
/* Marca a arvore inteira como "suja" para ser reavaliada */
static void rt_mark_dirty(TinyBlocks_Block* r, int depth) {
if (!r || depth > 64) return;
r->dirty = true;
for (uint32_t i = 0; i < r->input_count; i++)
if (r->inputs[i].source) rt_mark_dirty(r->inputs[i].source, depth + 1);
}
/* Arvore do runtime do bloco bi: montada na primeira vez e reaproveitada
depois (chave: aba, bloco e profundidade de chamada de Meus Blocos, para
uma recursao nao reusar uma arvore que ainda esta sendo avaliada). */
static TinyBlocks_Block* get_rt(Ed* ed, Tab* T, int bi) {
int depth = ed->frame_n;
uintptr_t h = ((uintptr_t)T >> 4) * 31u + (uintptr_t)bi * 131u + (uintptr_t)depth * 7u;
for (int k = 0; k < RT_CACHE_CAP; k++) {
RtCacheEnt* e = &ed->rt_cache[(h + (uintptr_t)k) % RT_CACHE_CAP];
if (!e->r) {
TinyBlocks_Block* r = build_rt(ed, T, bi);
/* deixa folga na tabela; cheia, so nao guarda */
if (r && ed->rt_cache_n < RT_CACHE_CAP * 3 / 4) {
e->T = T; e->bi = bi; e->depth = depth; e->r = r;
ed->rt_cache_n++;
}
return r;
}
if (e->T == T && e->bi == bi && e->depth == depth) {
rt_mark_dirty(e->r, 0);
return e->r;
}
}
return build_rt(ed, T, bi);
}
/* Avalia um repórter; devolve uma cópia (owned) do primeiro output */
static TinyBlocks_Value eval_reporter(Ed* ed, Tab* T, int bi) {
TinyBlocks_Block* r = build_rt(ed, T, bi);
TinyBlocks_Block* r = get_rt(ed, T, bi);
if (!r) return tb_value_none();
tb_block_eval(r, ed->rt);
return r->output_count > 0 ? tb_value_clone(r->outputs[0]) : tb_value_none();
@@ -1059,6 +1111,9 @@ static void run_chain(Ed* ed, Tab* T, int head) {
if (done || !step(ed)) break;
run_chain(ed, T, b->sub[0]);
}
} else if (strcmp(tn, "Control.Forever") == 0) {
/* dentro de Meus Blocos roda sem pausar: so o limite de passos para */
while (step(ed)) run_chain(ed, T, b->sub[0]);
} else if (strcmp(tn, "Control.If") == 0 || strcmp(tn, "Control.IfElse") == 0) {
TinyBlocks_Value v = eval_arg(ed, T, bi, 0);
bool cond = value_truthy(&v);
@@ -1066,18 +1121,93 @@ static void run_chain(Ed* ed, Tab* T, int head) {
if (cond) run_chain(ed, T, b->sub[0]);
else if (sh == SH_C2) run_chain(ed, T, b->sub[1]);
} else {
TinyBlocks_Block* r = build_rt(ed, T, bi);
TinyBlocks_Block* r = get_rt(ed, T, bi);
if (r) tb_block_eval(r, ed->rt);
}
}
}
/* Início/fim de uma execução: zera o runtime e captura o stdout no palco */
static void run_begin(Ed* ed, bool clear) {
run_reset(ed);
ed->steps = 0; ed->abort = false; ed->abort_msg[0] = 0; ed->frame_n = 0;
ed->live_tab = &CT;
if (clear) ed->stage_buf[0] = 0;
/* == Threads (scripts rodando quadro a quadro, estilo Scratch 3) ===
* Cada script e uma pilha explicita de VmFrame. Um laco pausa no fim de
* cada volta; vm_frame avanca as threads varias vezes no mesmo quadro ate
* todas pausarem/terminarem, um bloco do palco pedir redesenho ou acabar o
* tempo do quadro. Assim contas terminam na hora e desenhos animam. */
#define VM_FRAME_MS 12u
static unsigned now_ms(void);
static void vm_push(Ed* ed, VmThread* th, Tab* T, int bi, int kind, long long n) {
if (th->sp >= VM_STACK) { run_abort(ed, "blocos aninhados demais"); return; }
VmFrame* f = &th->st[th->sp++];
f->T = T; f->bi = bi; f->kind = kind; f->n = n; f->in_iter = false;
}
static void vm_start(Ed* ed, Tab* T, int head) {
if (ed->vm_n >= VM_THREADS) return;
VmThread* th = &ed->vm[ed->vm_n++];
th->sp = 0;
vm_push(ed, th, T, head, VF_CHAIN, 0);
ed->vm_running = true;
}
/* Executa a thread ate a proxima pausa (true) ou ate terminar (false) */
static bool vm_step(Ed* ed, VmThread* th) {
while (th->sp > 0 && !ed->abort) {
VmFrame* f = &th->st[th->sp - 1];
Tab* T = f->T;
if (f->kind != VF_CHAIN) {
EdBlock* L = &T->ws[f->bi];
if (!L->used) { th->sp--; continue; } /* laco apagado com o programa rodando */
if (f->in_iter) { f->in_iter = false; return true; } /* fim de uma volta: pausa */
if (f->kind == VF_REPEAT) {
if (f->n <= 0) { th->sp--; continue; }
f->n--;
} else if (f->kind == VF_UNTIL) {
TinyBlocks_Value v = eval_arg(ed, T, f->bi, 0);
bool done = value_truthy(&v);
tb_value_free(&v);
if (done) { th->sp--; continue; }
}
f->in_iter = true;
vm_push(ed, th, T, L->sub[0], VF_CHAIN, 0);
continue;
}
if (f->bi < 0 || !T->ws[f->bi].used) { th->sp--; continue; }
int bi = f->bi;
EdBlock* b = &T->ws[bi];
f->bi = b->next;
if (!step(ed)) break;
TinyBlocks_TypeBlock* t = blk_type(ed, b);
if (!t) continue;
const char* tn = t->type_name;
Shape sh = shape_of(t);
if (sh == SH_HAT || shape_is_value(sh)) continue;
if (strcmp(tn, "Control.Repeat") == 0) {
TinyBlocks_Value v = eval_arg(ed, T, bi, 0);
long long n = value_to_ll(&v);
tb_value_free(&v);
if (n > 0) vm_push(ed, th, T, bi, VF_REPEAT, n);
} else if (strcmp(tn, "Control.RepeatUntil") == 0) {
vm_push(ed, th, T, bi, VF_UNTIL, 0);
} else if (strcmp(tn, "Control.Forever") == 0) {
vm_push(ed, th, T, bi, VF_FOREVER, 0);
} else if (strcmp(tn, "Control.If") == 0 || strcmp(tn, "Control.IfElse") == 0) {
TinyBlocks_Value v = eval_arg(ed, T, bi, 0);
bool cond = value_truthy(&v);
tb_value_free(&v);
if (cond) vm_push(ed, th, T, b->sub[0], VF_CHAIN, 0);
else if (sh == SH_C2) vm_push(ed, th, T, b->sub[1], VF_CHAIN, 0);
} else {
TinyBlocks_Block* r = get_rt(ed, T, bi);
if (r) tb_block_eval(r, ed->rt);
if (strncmp(tn, "Stage.", 6) == 0) ed->redraw_req = true; /* caneta: mostra este quadro */
}
}
th->sp = 0;
return false;
}
/* Captura o stdout (blocos "escreva") enquanto os blocos rodam */
static void cap_begin(Ed* ed) {
fflush(stdout);
ed->cap_file = tmpfile();
ed->cap_saved = -1;
@@ -1088,7 +1218,8 @@ static void run_begin(Ed* ed, bool clear) {
}
}
static void run_end(Ed* ed) {
/* Devolve o stdout e manda o que foi escrito (e avisos/erros) ao palco */
static void cap_end(Ed* ed) {
if (ed->cap_file) {
fflush(stdout);
dup2(ed->cap_saved, STDOUT_FILENO);
@@ -1112,11 +1243,57 @@ static void run_end(Ed* ed) {
char msg[200];
snprintf(msg, sizeof(msg), "[ERRO] %s\n", ed->abort_msg);
stage_append(ed, msg);
ed->abort_msg[0] = 0;
}
}
/* Início/fim de uma execução: zera o runtime */
static void run_begin(Ed* ed, bool clear) {
run_reset(ed);
ed->steps = 0; ed->abort = false; ed->abort_msg[0] = 0; ed->frame_n = 0;
ed->live_tab = &CT;
ed->vm_var_n = tb_variables_count();
if (clear) ed->stage_buf[0] = 0;
}
static void run_end(Ed* ed) {
ed->vm_running = false;
ed->vm_n = 0;
ed->live_tab = NULL;
palette_rebuild(ed); /* variáveis novas aparecem no flyout */
}
/* Um quadro dos scripts rodando: avanca as threads ate todas pausarem ou
terminarem, a caneta pedir redesenho ou acabar o tempo do quadro. */
static void vm_frame(Ed* ed) {
if (!ed->vm_running) return;
g_active_ed = ed;
cap_begin(ed);
unsigned t0 = now_ms();
ed->redraw_req = false;
ed->steps = 0; /* limite de passos vale por quadro */
bool alive;
do {
alive = false;
for (int i = 0; i < ed->vm_n && !ed->abort; i++)
if (ed->vm[i].sp > 0 && vm_step(ed, &ed->vm[i])) alive = true;
} while (alive && !ed->abort && !ed->redraw_req && now_ms() - t0 < VM_FRAME_MS);
cap_end(ed);
if (!alive || ed->abort) {
run_end(ed);
} else if (tb_variables_count() != ed->vm_var_n) {
ed->vm_var_n = tb_variables_count();
palette_rebuild(ed); /* variavel nova com o programa rodando */
}
}
/* Botao vermelho: para todos os scripts */
static void vm_stop(Ed* ed) {
bool was = ed->vm_running;
run_reset(ed);
if (was) run_end(ed);
}
/* Bandeira verde: roda os scripts "quando a bandeira for clicado", de cima para baixo */
static void run_flag(Ed* ed) {
run_begin(ed, true);
@@ -1127,15 +1304,19 @@ static void run_flag(Ed* ed) {
int tmp = heads[j]; heads[j] = heads[j-1]; heads[j-1] = tmp;
}
int started = 0;
for (int i = 0; i < n && !ed->abort; i++) {
for (int i = 0; i < n; i++) {
EdBlock* b = &CT.ws[heads[i]];
if (blk_type(ed, b) && strcmp(b->type->type_name, "Events.WhenRun") == 0) {
run_chain(ed, &CT, heads[i]);
vm_start(ed, &CT, heads[i]);
started++;
}
}
if (!started) {
run_end(ed);
if (!started) stage_append(ed, "Nenhum script começa com \"quando a bandeira for clicado\".\n");
stage_append(ed, "Nenhum script começa com \"quando a bandeira for clicado\".\n");
return;
}
vm_frame(ed); /* primeiro quadro ja: scripts curtos terminam aqui */
}
/* Libera o balão de resultado (texto + eventual lista de pontos) */
@@ -1236,13 +1417,16 @@ static void run_click(Ed* ed, int bi) {
Shape sh = shape_of(blk_type(ed, &CT.ws[root]));
run_begin(ed, false);
if (shape_is_value(sh)) {
cap_begin(ed);
TinyBlocks_Value v = eval_reporter(ed, &CT, root);
cap_end(ed);
bubble_set(ed, root, &v);
tb_value_free(&v);
} else {
run_chain(ed, &CT, root);
}
run_end(ed);
} else {
vm_start(ed, &CT, root); /* a pilha roda como script (pode ter "sempre") */
vm_frame(ed);
}
}
/* Relógio monotônico em milissegundos (detecção de clique duplo) */
@@ -3073,7 +3257,7 @@ static void render_stage(Ed* ed, TinyBlocks_RenderableBlock* rb) {
/* Bandeira verde */
float fx = sx + 10, fy = sy + 6;
if (ed->flag_hover) rb_fill_rrect(rb, fx, fy, 40, 32, 6, COL_HOVER);
if (ed->flag_hover || ed->vm_running) rb_fill_rrect(rb, fx, fy, 40, 32, 6, COL_HOVER);
rb_fill_rect(rb, fx+13, fy+6, 2, 21, COL_FLAG_DARK);
rb_fill_rrect(rb, fx+15, fy+6, 15, 11, 2, COL_FLAG);
/* Parar */
@@ -3770,18 +3954,24 @@ static void compute_snap(Ed* ed) {
}
float dh = chain_h(T, ed->drag_bi);
/* pilha que termina numa "tampa" (sempre) so encaixa onde nada vem depois */
int last = ed->drag_bi;
while (T->ws[last].next >= 0) last = T->ws[last].next;
bool drag_cap = is_cap(T->ws[last].type);
for (int i = 0; i < MAX_WS; i++) {
EdBlock* B = &T->ws[i];
if (!B->used || B->dragging) continue;
Shape bs = shape_of(B->type);
if (shape_is_value(bs)) continue;
if (ds != SH_HAT) {
if (!is_cap(B->type) && !(drag_cap && B->next >= 0))
consider(ed, &best, SN_NEXT, i, 0, d->x, d->y, B->ax, B->ay + B->h);
int mouths = bs == SH_C1 ? 1 : bs == SH_C2 ? 2 : 0;
for (int k = 0; k < mouths; k++)
if (!(drag_cap && B->sub[k] >= 0))
consider(ed, &best, SN_SUB, i, k, d->x, d->y, B->ax + ARM_W, B->ay + B->sub_y[k]);
}
if (B->parent < 0 && bs != SH_HAT)
if (B->parent < 0 && bs != SH_HAT && !drag_cap)
consider(ed, &best, SN_ABOVE, i, 0, d->x, d->y + dh, B->ax, B->ay);
}
}
@@ -4035,7 +4225,7 @@ static void on_lmb_down(Ed* ed, float mx, float my) {
/* Palco */
if (mx >= WIN_W - STAGE_W) {
if (hit_flag(ed, mx, my)) run_flag(ed);
else if (hit_stop(ed, mx, my)) { run_reset(ed); ed->stage_buf[0] = 0; }
else if (hit_stop(ed, mx, my)) { vm_stop(ed); ed->stage_buf[0] = 0; }
else if (hit_detach(ed, mx, my)) { if (ed->stage_win) stage_attach(ed); else stage_detach(ed); }
return;
}
@@ -4119,6 +4309,7 @@ static void on_lmb_down(Ed* ed, float mx, float my) {
static void on_lmb_up(Ed* ed, float mx, float my) {
if (ed->comp_dialog_open || ed->fdlg.open) return;
rt_cache_clear(ed); /* soltar/encaixar muda o programa que esta rodando */
if (CT.kind == TK_IMAGE && CT.img_drag) { image_release(ed, mx, my); ed->state = ES_IDLE; return; }
if (ed->state == ES_DRAG && ed->drag_bi >= 0) {
mark_drag(&CT, ed->drag_bi, false);
@@ -4201,6 +4392,7 @@ TB_ED_API void path_commit(Ed* ed, int mode, const char* p) {
static void on_key(Ed* ed, int sc, bool ctrl) {
bool enter = sc == TB_KEY_RETURN;
rt_cache_clear(ed);
if (ed->settings_open) { settings_key(ed, sc, ctrl); return; }
if (ed->libman_open) { libman_key(ed, sc); return; }
if (ed->comp_dialog_open) { dlg_key(ed, sc); return; }
@@ -4259,6 +4451,7 @@ static void on_key(Ed* ed, int sc, bool ctrl) {
}
static void on_text(Ed* ed, const char* typed) {
rt_cache_clear(ed);
if (ed->settings_open) { settings_text(ed, typed); return; }
if (ed->libman_open) { libman_text(ed, typed); return; }
if (ed->comp_dialog_open) { dlg_text(ed, typed); return; }
@@ -4448,6 +4641,8 @@ static void editor_eval(TinyBlocks_Block* self, TinyBlocks* rt) {
const char* typed = ev_text(evb, GFX_IN_TEXT);
if (typed[0]) on_text(ed, typed);
vm_frame(ed); /* scripts rodando (sempre / repita) avancam um quadro */
/* Hot reload: checa os .so a cada ~30 frames (~0,5 s).
Usa o watcher (inotify) do tinyblocks-api; mtime como reserva. */
if (++ed->hot_check_frame >= 30) {
+43 -1
View File
@@ -342,7 +342,11 @@ int main(void) {
if (need("Controle", R_CAT, 0, &x, &y)) click(x, y);
if (need("repita até que", R_FLY, 0, &x, &y)) drag(x, y, 700, 300);
if (need("repita até que", R_WS, 0, &x, &y)) click(x, y);
CHECK(stage_has("limite de passos"), "laço infinito é abortado com aviso");
/* 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(!stage_has("limite de passos"), "laço sem fim roda sem travar (sem aviso de limite)");
click(1280 - 360 + 76, 44 + 22); /* botão vermelho */
frame(0, 0, 0, 0, 0, 0, NULL);
/* 10. Caneta: desenhar no palco embutido */
int circles_before = 0;
@@ -504,6 +508,44 @@ int main(void) {
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);
}
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(fj);
key(TB_KEY_RETURN, 0, 0);
frame(0, 0, 0, 0, 0, 0, NULL);
CHECK(find("sempre", R_WS, 0, &x, &y), "bloco 'sempre' aparece no projeto");
flag();
for (int i = 0; i < 6; i++) frame(0, 0, 0, 0, 0, 0, NULL);
int voltas = 0;
for (uint32_t i = 0; i < ncmd; i++)
if (cmds[i].kind == TB_DRAW_TEXT && cmds[i].x >= 920 && strstr(cmds[i].text, "volta")) voltas++;
CHECK(voltas >= 4 && voltas <= 12, "'sempre' com caneta anima: ~uma volta por quadro");
click(1280 - 360 + 76, 44 + 22); /* botão vermelho */
for (int i = 0; i < 6; i++) frame(0, 0, 0, 0, 0, 0, NULL);
int depois = 0;
for (uint32_t i = 0; i < ncmd; i++)
if (cmds[i].kind == TB_DRAW_TEXT && cmds[i].x >= 920 && strstr(cmds[i].text, "volta")) depois++;
CHECK(depois == 0, "botão vermelho para o 'sempre' (e limpa a saída)");
remove(fj);
}
/* 14. Exportar pelo menu de contexto do botao Exportar */
if (need("Exportar", R_FLY, 0, &x, &y)) click(x, y);
CHECK(find("Exportar JSON", R_FLY, 0, &x, &y) && find("Exportar XML", R_FLY, 0, &x, &y)