Estado atual do TinyBlocks: editor estilo Scratch + graphics como interface

Snapshot do projeto antes de implementar o diálogo "Criar um Bloco":
- runtime C block-based (src/, include/)
- libraries: graphics (interface), sdl2 (backend), editor (estilo Scratch),
  python, mcp
- exemplos (hello, sdl2, editor, vector, json, customappearance, python, mcp)
- Makefile com alvo help e build do editor

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
mguinhosandClaude committed 2026-10-20 19:10:43 -03:00
commit 4950ad6006
49 files changed
+10596

No files matched your search

+43
View File
@@ -0,0 +1,43 @@
CC := gcc
BUILD := ../../build
SDL2_CFLAGS := $(shell sdl2-config --cflags)
SDL2_LIBS := $(shell sdl2-config --libs)
SDL2TTF_CFLAGS:= $(shell pkg-config --cflags SDL2_ttf 2>/dev/null)
SDL2TTF_LIBS := $(shell pkg-config --libs SDL2_ttf 2>/dev/null)
ifeq ($(SDL2TTF_LIBS),)
$(error SDL2_ttf não encontrado. Instale: sudo apt install libsdl2-ttf-dev)
endif
CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \
-D_POSIX_C_SOURCE=200809L \
-I../../include \
-Iinclude \
$(SDL2_CFLAGS) $(SDL2TTF_CFLAGS)
LDFLAGS := $(SDL2_LIBS) $(SDL2TTF_LIBS) -lm
OBJ := $(BUILD)/tb_editor.o
LIB_A := $(BUILD)/libtinyblocks-editor.a
LIB_SO := $(BUILD)/libtinyblocks-editor.so
.PHONY: all static shared clean
all: static shared
static: $(LIB_A)
shared: $(LIB_SO)
$(OBJ): src/tb_editor.c include/tb_editor.h
@mkdir -p $(BUILD)
$(CC) $(CFLAGS) -fPIC -c $< -o $@
$(LIB_A): $(OBJ)
ar rcs $@ $^
$(LIB_SO): $(OBJ)
$(CC) -shared -o $@ $^ $(LDFLAGS)
clean:
$(RM) $(OBJ) $(LIB_A) $(LIB_SO)
@@ -0,0 +1,37 @@
/*
* TinyBlocks — tb_editor.h
* Editor visual block-based (estilo Scratch) implementado como LibraryBlock.
*
* O editor é o próprio bloco "Editor.Scene": não abre janela nem processa
* eventos SDL2 diretamente. Em vez disso:
* - implementa on_draw, produzindo um TinyBlocks_RenderableBlock
* - lê o estado de input/mouse/teclado a partir de um bloco SDL2.Events
* conectado ao seu input "events"
* - deve ser conectado ao input "scene" de um bloco SDL2.App, que é quem
* de fato cria a janela, roda o loop e interpreta o RenderableBlock.
*
* Uso:
* tb_library_register(rt, tb_editor_get_library());
* tb_library_register(rt, tb_sdl2_get_library());
*
* TinyBlocks_Block* events = tb_block_create(rt, tb_type_block_find(rt,"SDL2.Events"));
* TinyBlocks_Block* scene = tb_block_create(rt, tb_type_block_find(rt,"Editor.Scene"));
* tb_block_set_default(scene, 0, tb_value_block(events));
*
* TinyBlocks_Block* app = tb_block_create(rt, tb_type_block_find(rt,"SDL2.App"));
* tb_block_set_default(app, 3, tb_value_block(scene));
* tb_block_set_default(app, 4, tb_value_block(events));
* tb_block_eval(app, rt); // roda o loop principal — bloqueia até fechar
*/
#ifndef TINYBLOCKS_EDITOR_H
#define TINYBLOCKS_EDITOR_H
#include <tinyblocks/tinyblocks.h>
TB_API const TinyBlocks_LibraryDescriptor* tb_editor_get_library(void);
TB_API const TinyBlocks_LibraryDescriptor* tinyblocks_get_library(void);
/* Enfileira um .so para ser carregado automaticamente ao abrir o editor */
TB_API void tb_editor_preload(const char* path);
#endif /* TINYBLOCKS_EDITOR_H */
File diff suppressed because it is too large. Load diff
+259
View File
@@ -0,0 +1,259 @@
/*
* TinyBlocks — tb_stage.c
* O Palco do editor: uma tela lógica de 480x360 (origem no centro, y para
* cima, como no Scratch) onde os blocos Stage.* desenham. É um componente de
* UI: o editor o embute no painel direito (chamando seu on_draw) ou o entrega
* como cena de um Graphics.Window próprio ("destacar palco").
*
* Os desenhos ficam numa lista retida e são re-emitidos a cada on_draw,
* escalados para o tamanho da área (letterbox mantendo 4:3).
*/
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tb_graphics.h>
#include "tb_stage.h"
#define STAGE_W 480.f
#define STAGE_H 360.f
#define STAGE_MAX_CMDS 4000
#define STAGE_TEXT_FS 14.f
typedef enum { SC_RECT, SC_CIRCLE, SC_LINE, SC_TEXT } StageCmdKind;
typedef struct {
StageCmdKind kind;
float a, b, c, d; /* geometria em coordenadas do palco */
float size; /* espessura da caneta */
float col[3];
char text[96];
} StageCmd;
typedef struct {
StageCmd* cmds;
int n, cap;
float bg[3];
float pen[3];
float pen_size;
float view_w, view_h;
bool full_warned;
} Stage;
static TinyBlocks_Block* s_current = NULL;
static Stage* stage_of(TinyBlocks_Block* b) { return b ? *(Stage**)b->userdata : NULL; }
TinyBlocks_Block* tb_stage_current(void) { return s_current; }
void tb_stage_set_view(TinyBlocks_Block* stage, float w, float h) {
Stage* s = stage_of(stage);
if (s && w > 0 && h > 0) { s->view_w = w; s->view_h = h; }
}
/* ══════════════════════════════════════════════════════════════════════════
* Editor.Stage
* ══════════════════════════════════════════════════════════════════════════ */
static bool stage_instance_init(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt;
Stage* s = (Stage*)calloc(1, sizeof(Stage));
if (!s) return false;
s->bg[0] = s->bg[1] = s->bg[2] = 1.f;
s->pen[0] = 76/255.f; s->pen[1] = 151/255.f; s->pen[2] = 1.f;
s->pen_size = 2.f;
s->view_w = STAGE_W; s->view_h = STAGE_H;
*(Stage**)self->userdata = s;
s_current = self;
return true;
}
static void stage_instance_deinit(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt;
Stage* s = stage_of(self);
if (s) { free(s->cmds); free(s); }
*(Stage**)self->userdata = NULL;
if (s_current == self) s_current = NULL;
}
/* input 0 (opcional): Graphics.Input da janela que mostra o palco — dá o tamanho da vista */
static void eval_stage(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
TinyBlocks_Block* in = v.kind == TB_VALUE_BLOCK ? v.as.block : NULL;
if (!in || in->output_count < GFX_IN_COUNT) return;
TinyBlocks_Value w = in->outputs[GFX_IN_WIN_W], h = in->outputs[GFX_IN_WIN_H];
if (w.kind == TB_VALUE_INTEGER && h.kind == TB_VALUE_INTEGER)
tb_stage_set_view(self, (float)w.as.integer, (float)h.as.integer);
}
static bool stage_on_draw(TinyBlocks_Block* self, TinyBlocks* rt, TinyBlocks_RenderableBlock** dst) {
(void)rt;
Stage* s = stage_of(self);
if (!s) return false;
TinyBlocks_RenderableBlock* rb = tb_renderable_acquire();
if (!rb) return false;
float sc = s->view_w / STAGE_W < s->view_h / STAGE_H ? s->view_w / STAGE_W : s->view_h / STAGE_H;
float ox = (s->view_w - STAGE_W*sc) * 0.5f, oy = (s->view_h - STAGE_H*sc) * 0.5f;
#define SX(x) (ox + ((x) + STAGE_W*0.5f) * sc)
#define SY(y) (oy + (STAGE_H*0.5f - (y)) * sc)
if (ox > 0.5f || oy > 0.5f) tb_draw_fill_rect(rb, 0, 0, s->view_w, s->view_h, 0.12f, 0.12f, 0.14f, 1.f);
tb_draw_fill_rect(rb, ox, oy, STAGE_W*sc, STAGE_H*sc, s->bg[0], s->bg[1], s->bg[2], 1.f);
tb_draw_set_clip(rb, ox, oy, STAGE_W*sc, STAGE_H*sc);
for (int i = 0; i < s->n && rb->count < TB_DRAW_CMD_CAP - 2; i++) {
const StageCmd* c = &s->cmds[i];
float r = c->col[0], g = c->col[1], b = c->col[2];
switch (c->kind) {
case SC_RECT:
tb_draw_fill_rect(rb, SX(c->a - c->c*0.5f), SY(c->b + c->d*0.5f), c->c*sc, c->d*sc, r, g, b, 1.f);
break;
case SC_CIRCLE:
tb_draw_fill_circle(rb, SX(c->a), SY(c->b), c->c*sc, r, g, b, 1.f);
break;
case SC_LINE:
tb_draw_stroke_line(rb, SX(c->a), SY(c->b), SX(c->c), SY(c->d), c->size*sc, r, g, b, 1.f);
break;
case SC_TEXT: {
float fs = STAGE_TEXT_FS * sc;
tb_draw_text(rb, SX(c->a), SY(c->b) + fs*0.36f, c->text, fs, r, g, b, 1.f);
break;
}
}
}
tb_draw_clear_clip(rb);
#undef SX
#undef SY
*dst = rb;
return true;
}
/* ══════════════════════════════════════════════════════════════════════════
* Blocos Stage.* — desenham no palco atual
* ══════════════════════════════════════════════════════════════════════════ */
static float num(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) {
TinyBlocks_Value v = tb_block_get_input(self, rt, i);
if (v.kind == TB_VALUE_REAL) return (float)v.as.real;
if (v.kind == TB_VALUE_INTEGER) return (float)v.as.integer;
if (v.kind == TB_VALUE_TEXT && v.as.text) return (float)strtod(v.as.text, NULL);
return 0.f;
}
static float chan(float v) { return v < 0 ? 0.f : v > 255 ? 1.f : v / 255.f; }
static StageCmd* push(TinyBlocks* rt, StageCmdKind kind) {
Stage* s = stage_of(s_current);
if (!s) { tinyblocks_set_error(rt, "nenhum palco (Editor.Stage) criado"); return NULL; }
if (s->n >= STAGE_MAX_CMDS) {
if (!s->full_warned) tinyblocks_set_error(rt, "palco cheio (%d desenhos) — use \"apague tudo\"", STAGE_MAX_CMDS);
s->full_warned = true;
return NULL;
}
if (s->n >= s->cap) {
int nc = s->cap ? s->cap * 2 : 64;
StageCmd* p = (StageCmd*)realloc(s->cmds, (size_t)nc * sizeof(StageCmd));
if (!p) return NULL;
s->cmds = p; s->cap = nc;
}
StageCmd* c = &s->cmds[s->n++];
memset(c, 0, sizeof(*c));
c->kind = kind;
memcpy(c->col, s->pen, sizeof(c->col));
c->size = s->pen_size;
return c;
}
static void eval_clear(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt;
Stage* s = stage_of(s_current);
if (s) { s->n = 0; s->full_warned = false; }
self->dirty = false;
}
static void eval_background(TinyBlocks_Block* self, TinyBlocks* rt) {
Stage* s = stage_of(s_current);
if (s) { s->bg[0] = chan(num(self, rt, 0)); s->bg[1] = chan(num(self, rt, 1)); s->bg[2] = chan(num(self, rt, 2)); }
self->dirty = false;
}
static void eval_pen_color(TinyBlocks_Block* self, TinyBlocks* rt) {
Stage* s = stage_of(s_current);
if (s) { s->pen[0] = chan(num(self, rt, 0)); s->pen[1] = chan(num(self, rt, 1)); s->pen[2] = chan(num(self, rt, 2)); }
self->dirty = false;
}
static void eval_pen_size(TinyBlocks_Block* self, TinyBlocks* rt) {
Stage* s = stage_of(s_current);
float v = num(self, rt, 0);
if (s) s->pen_size = v < 1.f ? 1.f : v;
self->dirty = false;
}
static void eval_line(TinyBlocks_Block* self, TinyBlocks* rt) {
StageCmd* c = push(rt, SC_LINE);
if (c) { c->a = num(self, rt, 0); c->b = num(self, rt, 1); c->c = num(self, rt, 2); c->d = num(self, rt, 3); }
self->dirty = false;
}
static void eval_rect(TinyBlocks_Block* self, TinyBlocks* rt) {
StageCmd* c = push(rt, SC_RECT);
if (c) { c->a = num(self, rt, 0); c->b = num(self, rt, 1); c->c = num(self, rt, 2); c->d = num(self, rt, 3); }
self->dirty = false;
}
static void eval_circle(TinyBlocks_Block* self, TinyBlocks* rt) {
StageCmd* c = push(rt, SC_CIRCLE);
if (c) { c->a = num(self, rt, 0); c->b = num(self, rt, 1); c->c = num(self, rt, 2); }
self->dirty = false;
}
static void eval_text(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
char buf[96] = "";
if (v.kind == TB_VALUE_TEXT && v.as.text) snprintf(buf, sizeof(buf), "%s", v.as.text);
else if (v.kind == TB_VALUE_INTEGER) snprintf(buf, sizeof(buf), "%lld", (long long)v.as.integer);
else if (v.kind == TB_VALUE_REAL) snprintf(buf, sizeof(buf), "%g", v.as.real);
StageCmd* c = push(rt, SC_TEXT);
if (c) { memcpy(c->text, buf, sizeof(c->text)); c->a = num(self, rt, 1); c->b = num(self, rt, 2); }
self->dirty = false;
}
/* ══════════════════════════════════════════════════════════════════════════
* Registro
* ══════════════════════════════════════════════════════════════════════════ */
static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name,
const TinyBlocks_SlotDesc* in, uint32_t ni,
void (*fn)(TinyBlocks_Block*, TinyBlocks*)) {
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, NULL, 0, fn);
if (!t) return false;
tb_library_add(lib, &t->base);
return true;
}
bool tb_stage_register(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
static const TinyBlocks_SlotDesc stage_in[] = {{"entrada", TB_VALUE_BLOCK}};
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, "Editor.Stage", stage_in, 1, NULL, 0, eval_stage);
if (!t) return false;
tb_type_block_set_instance_hooks(t, sizeof(Stage*), stage_instance_init, stage_instance_deinit);
t->on_draw = stage_on_draw;
tb_library_add(lib, &t->base);
static const TinyBlocks_SlotDesc rgb[] = {{"r", TB_VALUE_REAL}, {"g", TB_VALUE_REAL}, {"b", TB_VALUE_REAL}};
static const TinyBlocks_SlotDesc size[] = {{"tamanho", TB_VALUE_REAL}};
static const TinyBlocks_SlotDesc line[] = {{"x1", TB_VALUE_REAL}, {"y1", TB_VALUE_REAL},
{"x2", TB_VALUE_REAL}, {"y2", TB_VALUE_REAL}};
static const TinyBlocks_SlotDesc rect[] = {{"x", TB_VALUE_REAL}, {"y", TB_VALUE_REAL},
{"largura", TB_VALUE_REAL}, {"altura", TB_VALUE_REAL}};
static const TinyBlocks_SlotDesc circ[] = {{"x", TB_VALUE_REAL}, {"y", TB_VALUE_REAL}, {"raio", TB_VALUE_REAL}};
static const TinyBlocks_SlotDesc text[] = {{"texto", TB_VALUE_TEXT}, {"x", TB_VALUE_REAL}, {"y", TB_VALUE_REAL}};
return reg(rt, lib, "Stage.Clear", NULL, 0, eval_clear)
&& reg(rt, lib, "Stage.Background", rgb, 3, eval_background)
&& reg(rt, lib, "Stage.PenColor", rgb, 3, eval_pen_color)
&& reg(rt, lib, "Stage.PenSize", size, 1, eval_pen_size)
&& reg(rt, lib, "Stage.Line", line, 4, eval_line)
&& reg(rt, lib, "Stage.Rect", rect, 4, eval_rect)
&& reg(rt, lib, "Stage.Circle", circ, 3, eval_circle)
&& reg(rt, lib, "Stage.Text", text, 3, eval_text);
}
@@ -0,0 +1,19 @@
/*
* TinyBlocks — tb_stage.h
* Palco do editor (Editor.Stage) e blocos de desenho Stage.*.
*/
#ifndef TINYBLOCKS_EDITOR_STAGE_H
#define TINYBLOCKS_EDITOR_STAGE_H
#include <tinyblocks/tinyblocks.h>
/* Registra Editor.Stage e os blocos Stage.* na library do editor */
bool tb_stage_register(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib);
/* Tamanho da área onde o palco será desenhado (on_draw usa 0..w × 0..h) */
void tb_stage_set_view(TinyBlocks_Block* stage, float w, float h);
/* Palco onde os blocos Stage.* desenham (o último criado) */
TinyBlocks_Block* tb_stage_current(void);
#endif /* TINYBLOCKS_EDITOR_STAGE_H */
@@ -0,0 +1,126 @@
/*
* TinyBlocks — tb_graphics.h
* Interface gráfica do TinyBlocks: janelas, entrada, desenho e texto.
*
* Tudo o que é gráfico passa por aqui antes de chegar a um backend concreto.
* O backend (ex: tinyblocks-sdl2) implementa TinyBlocks_GraphicsBackend e
* pode ser trocado livremente:
* - estaticamente: tb_graphics_set_backend(tb_sdl2_graphics_backend());
* - dinamicamente: tb_graphics_load_backend("build/libtinyblocks-sdl2.so");
* (o .so exporta TINYBLOCKS_GRAPHICS_BACKEND_SYMBOL)
* Sem escolha explícita usa o backend padrão de compilação (SDL2) ou, na
* falta dele, o backend nulo (headless — útil para testes).
*
* TypeBlocks registrados por tb_graphics_get_library():
* Graphics.Input — estado de entrada de uma janela no frame (outputs GFX_IN_*)
* Graphics.Window — uma janela do SO que mostra uma cena (qualquer bloco com on_draw)
* in: título, largura, altura, cena(block), entrada(block), principal(int)
* Graphics.Run — roda o loop até a janela principal fechar
*
* Esta library não conhece nenhum consumidor (editor, palco…): só define o
* contrato e despacha para o backend. Cenas são quaisquer blocos com on_draw.
*
* Uso típico (host):
* tb_library_register(rt, tb_graphics_get_library());
* TinyBlocks_Block* in = tb_block_create(rt, tb_type_block_find(rt, "Graphics.Input"));
* TinyBlocks_Block* win = tb_block_create(rt, tb_type_block_find(rt, "Graphics.Window"));
* tb_block_set_default(win, 3, tb_value_block(cena));
* tb_block_set_default(win, 4, tb_value_block(in));
* tb_block_eval(win, rt); // abre a janela
* tb_graphics_run(rt); // loop até a janela principal fechar
*/
#ifndef TINYBLOCKS_GRAPHICS_H
#define TINYBLOCKS_GRAPHICS_H
#include <tinyblocks/tinyblocks.h>
#include <tinyblocks/tb_renderable_block.h>
/* ── Teclas (neutras; o backend traduz as suas) ──────────────────────────── */
enum {
TB_KEY_NONE = 0,
TB_KEY_ESCAPE, TB_KEY_RETURN, TB_KEY_BACKSPACE, TB_KEY_DELETE, TB_KEY_TAB,
TB_KEY_SPACE, TB_KEY_LEFT, TB_KEY_RIGHT, TB_KEY_UP, TB_KEY_DOWN,
TB_KEY_HOME, TB_KEY_END,
TB_KEY_F1, TB_KEY_F2, TB_KEY_F3, TB_KEY_F4, TB_KEY_F5, TB_KEY_F6,
TB_KEY_F7, TB_KEY_F8, TB_KEY_F9, TB_KEY_F10, TB_KEY_F11, TB_KEY_F12,
TB_KEY_A = 64, /* TB_KEY_A + n = letra 'a'+n */
TB_KEY_0 = TB_KEY_A + 26, /* TB_KEY_0 + n = dígito n */
TB_KEY_OTHER = 127
};
/* ── Modificadores (bitmask) ─────────────────────────────────────────────── */
#define TB_MOD_SHIFT 0x1
#define TB_MOD_CTRL 0x2
#define TB_MOD_ALT 0x4
/* ── Índices de output do bloco Graphics.Input ───────────────────────────── */
#define GFX_IN_MOUSE_X 0 /* real: posição X do mouse na janela */
#define GFX_IN_MOUSE_Y 1 /* real: posição Y do mouse na janela */
#define GFX_IN_MOUSE_L_HELD 2 /* int: botão esquerdo pressionado (estado) */
#define GFX_IN_MOUSE_R_HELD 3 /* int: botão direito pressionado (estado) */
#define GFX_IN_MOUSE_L_DOWN 4 /* int: 1 se pressionado neste frame */
#define GFX_IN_MOUSE_L_UP 5 /* int: 1 se solto neste frame */
#define GFX_IN_MOUSE_R_DOWN 6 /* int: 1 se pressionado neste frame */
#define GFX_IN_MOUSE_R_UP 7 /* int: 1 se solto neste frame */
#define GFX_IN_SCROLL_DX 8 /* real: scroll horizontal deste frame */
#define GFX_IN_SCROLL_DY 9 /* real: scroll vertical deste frame */
#define GFX_IN_KEY 10 /* int: TB_KEY_* pressionada neste frame */
#define GFX_IN_KEY_MOD 11 /* int: TB_MOD_* no momento da tecla */
#define GFX_IN_KEY_REPEAT 12 /* int: 1 se é repetição de tecla segurada */
#define GFX_IN_TEXT 13 /* text: texto digitado neste frame */
#define GFX_IN_CLOSE 14 /* int: 1 se o usuário pediu para fechar */
#define GFX_IN_WIN_W 15 /* int: largura atual da janela */
#define GFX_IN_WIN_H 16 /* int: altura atual da janela */
#define GFX_IN_DROP_FILE 17 /* text: caminho de arquivo solto na janela */
#define GFX_IN_MOD_STATE 18 /* int: TB_MOD_* segurados agora */
#define GFX_IN_COUNT 19
/* Estado de entrada de uma janela em um frame (preenchido pelo backend) */
typedef struct TinyBlocks_GfxInput {
float mouse_x, mouse_y;
int l_held, r_held;
int l_down, l_up, r_down, r_up;
float scroll_dx, scroll_dy;
int key, key_mod, key_repeat;
char text[64];
int close;
int win_w, win_h;
char drop_file[512];
int mod_state;
} TinyBlocks_GfxInput;
/* ── Contrato de um backend gráfico ──────────────────────────────────────── */
typedef struct TinyBlocks_GraphicsBackend {
const char* name;
bool (*init)(void); /* idempotente */
void (*shutdown)(void);
void* (*window_open)(const char* title, int w, int h); /* handle opaco ou NULL */
void (*window_close)(void* win);
void (*poll)(void); /* coleta eventos do SO */
void (*window_input)(void* win, TinyBlocks_GfxInput* out);
void (*window_present)(void* win, const TinyBlocks_RenderableBlock* rb);
float (*measure_text)(const char* text, float font_size); /* NULL = estimativa */
void (*frame_wait)(void); /* NULL = ~16 ms */
} TinyBlocks_GraphicsBackend;
/* Símbolo exportado por um backend carregado como .so */
#define TINYBLOCKS_GRAPHICS_BACKEND_SYMBOL "tinyblocks_get_graphics_backend"
typedef const TinyBlocks_GraphicsBackend* (*TinyBlocks_GetGraphicsBackendFn)(void);
/* ── API ─────────────────────────────────────────────────────────────────── */
TB_API const TinyBlocks_LibraryDescriptor* tb_graphics_get_library(void);
/* Escolhe o backend (antes de abrir a primeira janela) */
TB_API bool tb_graphics_set_backend(const TinyBlocks_GraphicsBackend* backend);
TB_API bool tb_graphics_load_backend(const char* so_path);
TB_API const TinyBlocks_GraphicsBackend* tb_graphics_backend(void);
TB_API const TinyBlocks_GraphicsBackend* tb_graphics_null_backend(void);
/* Largura de um texto na fonte do backend */
TB_API float tb_graphics_measure_text(const char* text, float font_size);
/* Loop principal: roda todas as janelas abertas até a principal fechar */
TB_API void tb_graphics_run(TinyBlocks* rt);
TB_API bool tb_graphics_window_is_open(TinyBlocks_Block* window);
#endif /* TINYBLOCKS_GRAPHICS_H */
@@ -0,0 +1,383 @@
/*
* TinyBlocks — tb_graphics.c
* Interface gráfica: escolha de backend, janelas, entrada e loop principal.
*/
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <dlfcn.h>
#include "../include/tb_graphics.h"
#ifdef TB_GRAPHICS_DEFAULT_SDL2
#include <tb_sdl2.h>
#endif
/* ══════════════════════════════════════════════════════════════════════════
* Backend nulo (headless): janelas sem tela, entrada vazia, texto estimado
* ══════════════════════════════════════════════════════════════════════════ */
typedef struct { int w, h; } NullWin;
static bool null_init(void) { return true; }
static void null_shutdown(void) { }
static void* null_open(const char* title, int w, int h) {
(void)title;
NullWin* n = (NullWin*)calloc(1, sizeof(*n));
if (n) { n->w = w; n->h = h; }
return n;
}
static void null_close(void* win) { free(win); }
static void null_poll(void) { }
static void null_input(void* win, TinyBlocks_GfxInput* out) {
memset(out, 0, sizeof(*out));
const NullWin* n = (const NullWin*)win;
if (n) { out->win_w = n->w; out->win_h = n->h; }
}
static void null_present(void* win, const TinyBlocks_RenderableBlock* rb) { (void)win; (void)rb; }
static const TinyBlocks_GraphicsBackend s_null_backend = {
.name = "null",
.init = null_init,
.shutdown = null_shutdown,
.window_open = null_open,
.window_close = null_close,
.poll = null_poll,
.window_input = null_input,
.window_present = null_present,
.measure_text = NULL,
.frame_wait = NULL,
};
const TinyBlocks_GraphicsBackend* tb_graphics_null_backend(void) { return &s_null_backend; }
/* ══════════════════════════════════════════════════════════════════════════
* Escolha do backend
* ══════════════════════════════════════════════════════════════════════════ */
static const TinyBlocks_GraphicsBackend* s_backend = NULL;
static bool s_backend_ready = false;
static void* s_backend_dl = NULL;
#define MAX_WINDOWS 16
typedef struct { TinyBlocks_Block* block; uint64_t id; } WinEntry;
static WinEntry s_wins[MAX_WINDOWS];
static int s_win_n = 0;
static uint64_t s_next_id = 1;
const TinyBlocks_GraphicsBackend* tb_graphics_backend(void) {
if (!s_backend) {
#ifdef TB_GRAPHICS_DEFAULT_SDL2
s_backend = (const TinyBlocks_GraphicsBackend*)tb_sdl2_graphics_backend();
#endif
if (!s_backend) s_backend = &s_null_backend;
}
return s_backend;
}
/* Backend inicializado; se o init falhar, cai para o nulo */
static const TinyBlocks_GraphicsBackend* backend_ready(void) {
const TinyBlocks_GraphicsBackend* b = tb_graphics_backend();
if (s_backend_ready) return b;
if (b->init && !b->init()) {
fprintf(stderr, "tinyblocks-graphics: backend '%s' falhou ao iniciar; usando 'null'\n", b->name);
s_backend = b = &s_null_backend;
}
s_backend_ready = true;
return b;
}
bool tb_graphics_set_backend(const TinyBlocks_GraphicsBackend* backend) {
if (!backend || !backend->window_open || !backend->window_present) return false;
if (backend == s_backend) return true;
if (s_win_n > 0) {
fprintf(stderr, "tinyblocks-graphics: feche as janelas antes de trocar o backend\n");
return false;
}
if (s_backend_ready && s_backend->shutdown) s_backend->shutdown();
s_backend_ready = false;
s_backend = backend;
return true;
}
bool tb_graphics_load_backend(const char* so_path) {
void* dl = dlopen(so_path, RTLD_NOW | RTLD_LOCAL);
if (!dl) {
fprintf(stderr, "tinyblocks-graphics: dlopen: %s\n", dlerror());
return false;
}
TinyBlocks_GetGraphicsBackendFn get =
(TinyBlocks_GetGraphicsBackendFn)(uintptr_t)dlsym(dl, TINYBLOCKS_GRAPHICS_BACKEND_SYMBOL);
const TinyBlocks_GraphicsBackend* b = get ? get() : NULL;
if (!b || !tb_graphics_set_backend(b)) {
fprintf(stderr, "tinyblocks-graphics: '%s' não exporta um backend válido (%s)\n",
so_path, TINYBLOCKS_GRAPHICS_BACKEND_SYMBOL);
dlclose(dl);
return false;
}
if (s_backend_dl) dlclose(s_backend_dl);
s_backend_dl = dl;
return true;
}
/* ══════════════════════════════════════════════════════════════════════════
* Medição de texto
* ══════════════════════════════════════════════════════════════════════════ */
/* Larguras de avanço da DejaVu Sans, em em, para ASCII 32..126 — estimativa
* usada quando o backend não sabe medir (ex: backend nulo). */
static const float s_adv[95] = {
.318f,.401f,.460f,.838f,.636f,.950f,.780f,.275f,.390f,.390f,.500f,.838f,.318f,.361f,.318f,.337f,
.636f,.636f,.636f,.636f,.636f,.636f,.636f,.636f,.636f,.636f,.337f,.337f,.838f,.838f,.838f,.531f,
1.0f, .684f,.686f,.698f,.770f,.632f,.575f,.775f,.752f,.295f,.295f,.656f,.557f,.863f,.748f,.787f,
.603f,.787f,.695f,.635f,.611f,.732f,.684f,.989f,.685f,.611f,.685f,.390f,.337f,.390f,.838f,.500f,
.500f,.613f,.635f,.550f,.635f,.615f,.352f,.635f,.634f,.278f,.278f,.579f,.278f,.974f,.634f,.612f,
.635f,.635f,.411f,.521f,.392f,.634f,.592f,.818f,.592f,.592f,.525f,.636f,.337f,.636f,.838f
};
static float estimate_text(const char* s, float fs) {
float w = 0.f;
for (const unsigned char* p = (const unsigned char*)s; *p; p++) {
if (*p >= 32 && *p < 127) w += s_adv[*p - 32];
else if ((*p & 0xC0) == 0xC0) w += (*p >= 0xE0) ? 0.9f : 0.62f; /* início de UTF-8 */
}
return w * fs;
}
float tb_graphics_measure_text(const char* text, float font_size) {
if (!text || !text[0]) return 0.f;
const TinyBlocks_GraphicsBackend* b = backend_ready();
return b->measure_text ? b->measure_text(text, font_size) : estimate_text(text, font_size);
}
/* ══════════════════════════════════════════════════════════════════════════
* Graphics.Input — estado de entrada de uma janela no frame
* ══════════════════════════════════════════════════════════════════════════ */
static const TinyBlocks_SlotDesc s_input_outs[GFX_IN_COUNT] = {
{"mouse_x", TB_VALUE_REAL}, {"mouse_y", TB_VALUE_REAL},
{"l_held", TB_VALUE_INTEGER}, {"r_held", TB_VALUE_INTEGER},
{"l_down", TB_VALUE_INTEGER}, {"l_up", TB_VALUE_INTEGER},
{"r_down", TB_VALUE_INTEGER}, {"r_up", TB_VALUE_INTEGER},
{"scroll_dx", TB_VALUE_REAL}, {"scroll_dy", TB_VALUE_REAL},
{"key", TB_VALUE_INTEGER}, {"key_mod", TB_VALUE_INTEGER},
{"key_repeat", TB_VALUE_INTEGER}, {"text", TB_VALUE_TEXT},
{"close", TB_VALUE_INTEGER}, {"win_w", TB_VALUE_INTEGER},
{"win_h", TB_VALUE_INTEGER}, {"drop_file", TB_VALUE_TEXT},
{"mod_state", TB_VALUE_INTEGER},
};
static void eval_input(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt;
/* Os outputs são preenchidos pelo loop; aqui só garante valores neutros */
for (uint32_t i = 0; i < self->output_count && i < GFX_IN_COUNT; i++) {
if (self->outputs[i].kind != TB_VALUE_NONE) continue;
switch (s_input_outs[i].expected_kind) {
case TB_VALUE_REAL: self->outputs[i] = tb_value_real(0.0); break;
case TB_VALUE_TEXT: self->outputs[i] = tb_value_text(""); break;
default: self->outputs[i] = tb_value_integer(0); break;
}
}
self->dirty = false;
}
static void input_push(TinyBlocks_Block* b, const TinyBlocks_GfxInput* in) {
if (!b || b->output_count < GFX_IN_COUNT) return;
#define SET(idx, v) tb_block_set_output(b, idx, v)
SET(GFX_IN_MOUSE_X, tb_value_real(in->mouse_x));
SET(GFX_IN_MOUSE_Y, tb_value_real(in->mouse_y));
SET(GFX_IN_MOUSE_L_HELD, tb_value_integer(in->l_held));
SET(GFX_IN_MOUSE_R_HELD, tb_value_integer(in->r_held));
SET(GFX_IN_MOUSE_L_DOWN, tb_value_integer(in->l_down));
SET(GFX_IN_MOUSE_L_UP, tb_value_integer(in->l_up));
SET(GFX_IN_MOUSE_R_DOWN, tb_value_integer(in->r_down));
SET(GFX_IN_MOUSE_R_UP, tb_value_integer(in->r_up));
SET(GFX_IN_SCROLL_DX, tb_value_real(in->scroll_dx));
SET(GFX_IN_SCROLL_DY, tb_value_real(in->scroll_dy));
SET(GFX_IN_KEY, tb_value_integer(in->key));
SET(GFX_IN_KEY_MOD, tb_value_integer(in->key_mod));
SET(GFX_IN_KEY_REPEAT, tb_value_integer(in->key_repeat));
SET(GFX_IN_TEXT, tb_value_text(in->text));
SET(GFX_IN_CLOSE, tb_value_integer(in->close));
SET(GFX_IN_WIN_W, tb_value_integer(in->win_w));
SET(GFX_IN_WIN_H, tb_value_integer(in->win_h));
SET(GFX_IN_DROP_FILE, tb_value_text(in->drop_file));
SET(GFX_IN_MOD_STATE, tb_value_integer(in->mod_state));
#undef SET
b->dirty = false;
}
/* ══════════════════════════════════════════════════════════════════════════
* Graphics.Window — uma janela do SO mostrando uma cena
* inputs: 0 título, 1 largura, 2 altura, 3 cena(block), 4 entrada(block),
* 5 principal(int: fechar esta janela encerra o loop; padrão 1)
* output: 0 aberta(int)
* ══════════════════════════════════════════════════════════════════════════ */
typedef struct { void* handle; uint64_t id; bool open; } WinState;
static int win_find(uint64_t id) {
for (int i = 0; i < s_win_n; i++) if (s_wins[i].id == id) return i;
return -1;
}
static void win_close(TinyBlocks_Block* self) {
WinState* ws = (WinState*)self->userdata;
if (!ws->open) return;
int i = win_find(ws->id);
if (i >= 0) { s_wins[i] = s_wins[s_win_n - 1]; s_win_n--; }
if (ws->handle && s_backend_ready) s_backend->window_close(ws->handle);
ws->handle = NULL;
ws->open = false;
tb_block_set_output(self, 0, tb_value_integer(0));
}
static bool win_instance_init(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt;
memset(self->userdata, 0, sizeof(WinState));
return true;
}
static void win_instance_deinit(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt;
win_close(self);
}
static void eval_window(TinyBlocks_Block* self, TinyBlocks* rt) {
WinState* ws = (WinState*)self->userdata;
self->dirty = false;
if (ws->open) return;
if (s_win_n >= MAX_WINDOWS) {
tinyblocks_set_error(rt, "Graphics.Window: limite de %d janelas", MAX_WINDOWS);
return;
}
TinyBlocks_Value vt = tb_block_get_input(self, rt, 0);
TinyBlocks_Value vw = tb_block_get_input(self, rt, 1);
TinyBlocks_Value vh = tb_block_get_input(self, rt, 2);
const char* title = (vt.kind == TB_VALUE_TEXT && vt.as.text) ? vt.as.text : "TinyBlocks";
int w = vw.kind == TB_VALUE_INTEGER && vw.as.integer > 0 ? (int)vw.as.integer : 640;
int h = vh.kind == TB_VALUE_INTEGER && vh.as.integer > 0 ? (int)vh.as.integer : 480;
const TinyBlocks_GraphicsBackend* b = backend_ready();
void* handle = b->window_open(title, w, h);
if (!handle) {
tinyblocks_set_error(rt, "Graphics.Window: o backend '%s' não abriu a janela", b->name);
return;
}
ws->handle = handle;
ws->id = s_next_id++;
ws->open = true;
s_wins[s_win_n++] = (WinEntry){ self, ws->id };
tb_block_set_output(self, 0, tb_value_integer(1));
}
bool tb_graphics_window_is_open(TinyBlocks_Block* window) {
if (!window || !window->type || !window->type->type_name ||
strcmp(window->type->type_name, "Graphics.Window") != 0) return false;
return ((WinState*)window->userdata)->open;
}
/* ══════════════════════════════════════════════════════════════════════════
* Loop principal
* ══════════════════════════════════════════════════════════════════════════ */
static void default_wait(void) {
struct timespec ts = { 0, 16 * 1000000L };
nanosleep(&ts, NULL);
}
void tb_graphics_run(TinyBlocks* rt) {
const TinyBlocks_GraphicsBackend* b = backend_ready();
bool running = s_win_n > 0;
while (running) {
if (b->poll) b->poll();
/* As cenas podem abrir/fechar janelas: itera sobre uma cópia dos ids */
uint64_t ids[MAX_WINDOWS];
int n = s_win_n;
for (int i = 0; i < n; i++) ids[i] = s_wins[i].id;
for (int k = 0; k < n; k++) {
int i = win_find(ids[k]);
if (i < 0) continue;
TinyBlocks_Block* wb = s_wins[i].block;
WinState* ws = (WinState*)wb->userdata;
TinyBlocks_GfxInput in;
b->window_input(ws->handle, &in);
TinyBlocks_Value vin = tb_block_get_input(wb, rt, 4);
if (vin.kind == TB_VALUE_BLOCK) input_push(vin.as.block, &in);
if (in.close) {
TinyBlocks_Value vp = tb_block_get_input(wb, rt, 5);
if (vp.kind != TB_VALUE_INTEGER || vp.as.integer) running = false;
win_close(wb);
continue;
}
TinyBlocks_RenderableBlock* rb = NULL;
TinyBlocks_Value vs = tb_block_get_input(wb, rt, 3);
TinyBlocks_Block* scene = vs.kind == TB_VALUE_BLOCK ? vs.as.block : NULL;
if (scene) {
scene->dirty = true;
tb_block_eval(scene, rt);
if (win_find(ids[k]) < 0) continue; /* a cena fechou esta janela */
if (scene->type && scene->type->on_draw) scene->type->on_draw(scene, rt, &rb);
}
b->window_present(ws->handle, rb);
if (rb) tb_renderable_release(rb);
}
tb_renderable_release_all();
if (s_win_n == 0) running = false;
if (running) { if (b->frame_wait) b->frame_wait(); else default_wait(); }
}
while (s_win_n > 0) win_close(s_wins[s_win_n - 1].block);
if (b->shutdown) b->shutdown();
s_backend_ready = false;
}
static void eval_run(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
tb_graphics_run(rt);
}
/* ══════════════════════════════════════════════════════════════════════════
* Registro da library
* ══════════════════════════════════════════════════════════════════════════ */
static bool graphics_lib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
TinyBlocks_TypeBlock* t;
t = tb_type_block_create(rt, "Graphics.Input", NULL, 0, s_input_outs, GFX_IN_COUNT, eval_input);
if (!t) return false;
tb_library_add(lib, &t->base);
static const TinyBlocks_SlotDesc win_in[] = {
{"título", TB_VALUE_TEXT}, {"largura", TB_VALUE_INTEGER}, {"altura", TB_VALUE_INTEGER},
{"cena", TB_VALUE_BLOCK}, {"entrada", TB_VALUE_BLOCK}, {"principal", TB_VALUE_INTEGER},
};
static const TinyBlocks_SlotDesc win_out[] = {{"aberta", TB_VALUE_INTEGER}};
t = tb_type_block_create(rt, "Graphics.Window", win_in, 6, win_out, 1, eval_window);
if (!t) return false;
tb_type_block_set_instance_hooks(t, sizeof(WinState), win_instance_init, win_instance_deinit);
tb_library_add(lib, &t->base);
t = tb_type_block_create(rt, "Graphics.Run", NULL, 0, NULL, 0, eval_run);
if (!t) return false;
tb_library_add(lib, &t->base);
return true;
}
static void graphics_lib_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt; (void)lib;
if (s_backend_ready && s_backend->shutdown) s_backend->shutdown();
s_backend_ready = false;
}
TINYBLOCKS_DEFINE_LIBRARY(graphics,
"tinyblocks-graphics",
"1.0.0",
graphics_lib_init,
graphics_lib_deinit)
const TinyBlocks_LibraryDescriptor* tb_graphics_get_library(void) {
return &_tb_lib_desc_graphics;
}
@@ -0,0 +1,36 @@
#ifndef TINYBLOCKS_MCP_H
#define TINYBLOCKS_MCP_H
#include <stdbool.h>
#ifdef _WIN32
# define TB_MCP_API __declspec(dllexport)
#else
# define TB_MCP_API __attribute__((visibility("default")))
#endif
/*
* tb_mcp — cliente MCP (Model Context Protocol) sobre transporte HTTP
* e stdio, implementado em Python via tinyblocks-python.
*
* Transport HTTP (streamable): url = "http://host:port/mcp"
* Transport stdio: url = "stdio://npx @modelcontextprotocol/server-filesystem /tmp"
*
* Todas as funções retornam string heap-alocada (caller frees) ou NULL em erro.
*/
TB_MCP_API bool tb_mcp_init(void);
TB_MCP_API void tb_mcp_deinit(void);
/* Lista ferramentas disponíveis → JSON array de objetos {name, description} */
TB_MCP_API char* tb_mcp_list_tools(const char* url);
/* Chama uma ferramenta com argumentos JSON → resultado JSON */
TB_MCP_API char* tb_mcp_call_tool(const char* url,
const char* tool_name,
const char* args_json);
/* Ping: verifica se o servidor responde → "ok" ou mensagem de erro */
TB_MCP_API char* tb_mcp_ping(const char* url);
#endif /* TINYBLOCKS_MCP_H */
+125
View File
@@ -0,0 +1,125 @@
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "tinyblocks-mcp/tb_mcp.h"
#include "tinyblocks-python/tb_python.h"
/* Código Python gerado por: xxd -i tb_mcp.py > tb_mcp_py.h */
#include "tb_mcp_py.h"
/* ── Singleton ───────────────────────────────────────────────────────────── */
static bool s_module_loaded = false;
static bool ensure_module(void) {
if (s_module_loaded) return true;
/*
* Executa o módulo Python em __main__ para que as funções persistam
* entre chamadas. tb_mcp_py é unsigned char[] gerado pelo xxd -i.
*/
char* err = tb_python_exec_main((const char*)tb_mcp_py);
bool ok = (err != NULL && strlen(err) == 0);
if (!ok && err) fprintf(stderr, "[tinyblocks-mcp] erro ao carregar modulo Python:\n%s\n", err);
free(err);
s_module_loaded = ok;
return ok;
}
TB_MCP_API bool tb_mcp_init(void) {
if (!tb_python_init()) return false;
return ensure_module();
}
TB_MCP_API void tb_mcp_deinit(void) {
s_module_loaded = false;
tb_python_deinit();
}
/* ── Helper: escapa string para literal Python ───────────────────────────── */
static char* py_str(const char* s) {
size_t n = strlen(s);
char* out = malloc(n * 4 + 3);
if (!out) return NULL;
char* p = out;
*p++ = '"';
for (size_t i = 0; i < n; i++) {
unsigned char c = (unsigned char)s[i];
if (c == '"') { *p++ = '\\'; *p++ = '"'; }
else if (c == '\\') { *p++ = '\\'; *p++ = '\\'; }
else if (c == '\n') { *p++ = '\\'; *p++ = 'n'; }
else if (c == '\r') { *p++ = '\\'; *p++ = 'r'; }
else if (c < 0x20) {
p += sprintf(p, "\\x%02x", c);
} else {
*p++ = (char)c;
}
}
*p++ = '"';
*p = '\0';
return out;
}
/* ── Helper genérico: monta e executa chamada Python fn(arg...) ─────────── */
static char* py_call(const char* fn, const char* const* args, int n) {
if (!ensure_module()) return strdup("erro: modulo MCP nao carregado");
/* Constrói "print(fn(arg0, arg1, ...))" */
size_t total = strlen(fn) + 16;
char** esc = malloc(n * sizeof(char*));
if (!esc) return strdup("erro: memoria");
for (int i = 0; i < n; i++) {
esc[i] = py_str(args[i]);
if (!esc[i]) {
for (int j = 0; j < i; j++) free(esc[j]);
free(esc);
return strdup("erro: memoria");
}
total += strlen(esc[i]) + 2;
}
char* code = malloc(total + 16);
if (!code) {
for (int i = 0; i < n; i++) free(esc[i]);
free(esc);
return strdup("erro: memoria");
}
char* p = code;
p += sprintf(p, "print(%s(", fn);
for (int i = 0; i < n; i++) {
if (i > 0) { *p++ = ','; *p++ = ' '; }
p += sprintf(p, "%s", esc[i]);
}
sprintf(p, "))");
for (int i = 0; i < n; i++) free(esc[i]);
free(esc);
char* out = tb_python_exec_main(code);
free(code);
/* Remove trailing newline */
if (out) {
size_t len = strlen(out);
while (len > 0 && (out[len-1] == '\n' || out[len-1] == '\r'))
out[--len] = '\0';
}
return out ? out : strdup("");
}
/* ── API pública ─────────────────────────────────────────────────────────── */
TB_MCP_API char* tb_mcp_ping(const char* url) {
const char* args[] = {url};
return py_call("mcp_ping", args, 1);
}
TB_MCP_API char* tb_mcp_list_tools(const char* url) {
const char* args[] = {url};
return py_call("mcp_list_tools", args, 1);
}
TB_MCP_API char* tb_mcp_call_tool(const char* url, const char* tool_name, const char* args_json) {
const char* args[] = {url, tool_name, args_json ? args_json : "{}"};
return py_call("mcp_call_tool", args, 3);
}
+115
View File
@@ -0,0 +1,115 @@
import json
def _http_jsonrpc(url, method, params):
import urllib.request, urllib.error
payload = json.dumps({
"jsonrpc": "2.0",
"id": 1,
"method": method,
"params": params
}).encode()
req = urllib.request.Request(
url,
data=payload,
headers={
"Content-Type": "application/json",
"Accept": "application/json",
}
)
try:
with urllib.request.urlopen(req, timeout=15) as r:
body = r.read().decode()
except urllib.error.HTTPError as e:
return {"error": {"code": e.code, "message": e.reason}}
except Exception as e:
return {"error": {"code": -1, "message": str(e)}}
try:
return json.loads(body)
except Exception as e:
return {"error": {"code": -2, "message": "invalid JSON: " + str(e)}}
def _stdio_jsonrpc(cmd, method, params):
import subprocess
args = cmd.split()
try:
proc = subprocess.Popen(
args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL
)
except FileNotFoundError as e:
return {"error": {"code": -1, "message": str(e)}}
def send(obj):
line = (json.dumps(obj) + "\n").encode()
proc.stdin.write(line)
proc.stdin.flush()
def recv():
line = proc.stdout.readline()
if not line:
return {}
return json.loads(line.decode().strip())
try:
send({"jsonrpc":"2.0","id":1,"method":"initialize","params":{
"protocolVersion":"2024-11-05",
"capabilities":{},
"clientInfo":{"name":"tinyblocks-mcp","version":"1.0"}
}})
recv()
send({"jsonrpc":"2.0","method":"notifications/initialized","params":{}})
send({"jsonrpc":"2.0","id":2,"method":method,"params":params})
resp = recv()
return resp
except Exception as e:
return {"error":{"code":-1,"message":str(e)}}
finally:
proc.terminate()
proc.wait(timeout=3)
def _dispatch(url, method, params):
if url.startswith("stdio://"):
return _stdio_jsonrpc(url[len("stdio://"):], method, params)
else:
return _http_jsonrpc(url, method, params)
def mcp_ping(url):
resp = _dispatch(url, "ping", {})
if "error" in resp:
return "erro: " + resp["error"].get("message", str(resp["error"]))
return "ok"
def mcp_list_tools(url):
resp = _dispatch(url, "tools/list", {})
if "error" in resp:
return "erro: " + resp["error"].get("message", str(resp["error"]))
result = resp.get("result", resp)
tools = result.get("tools", [])
out = []
for t in tools:
name = t.get("name","?")
desc = t.get("description","")
out.append(name + ": " + desc)
return "\n".join(out) if out else "(nenhuma ferramenta)"
def mcp_call_tool(url, tool_name, args_json):
try:
args = json.loads(args_json) if args_json and args_json.strip() else {}
except Exception as e:
return "erro: args JSON invalido: " + str(e)
resp = _dispatch(url, "tools/call", {"name": tool_name, "arguments": args})
if "error" in resp:
return "erro: " + resp["error"].get("message", str(resp["error"]))
result = resp.get("result", resp)
content = result.get("content", result)
if isinstance(content, list):
parts = []
for item in content:
if isinstance(item, dict):
parts.append(item.get("text", json.dumps(item)))
else:
parts.append(str(item))
return "\n".join(parts)
return json.dumps(content, ensure_ascii=False, indent=2)
+314
View File
@@ -0,0 +1,314 @@
unsigned char tb_mcp_py[] = {
0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x20, 0x6a, 0x73, 0x6f, 0x6e, 0x0a,
0x0a, 0x64, 0x65, 0x66, 0x20, 0x5f, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x6a,
0x73, 0x6f, 0x6e, 0x72, 0x70, 0x63, 0x28, 0x75, 0x72, 0x6c, 0x2c, 0x20,
0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x2c, 0x20, 0x70, 0x61, 0x72, 0x61,
0x6d, 0x73, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x6d, 0x70,
0x6f, 0x72, 0x74, 0x20, 0x75, 0x72, 0x6c, 0x6c, 0x69, 0x62, 0x2e, 0x72,
0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2c, 0x20, 0x75, 0x72, 0x6c, 0x6c,
0x69, 0x62, 0x2e, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x20, 0x3d, 0x20, 0x6a,
0x73, 0x6f, 0x6e, 0x2e, 0x64, 0x75, 0x6d, 0x70, 0x73, 0x28, 0x7b, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6a, 0x73, 0x6f,
0x6e, 0x72, 0x70, 0x63, 0x22, 0x3a, 0x20, 0x22, 0x32, 0x2e, 0x30, 0x22,
0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x69,
0x64, 0x22, 0x3a, 0x20, 0x31, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x22, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x22, 0x3a,
0x20, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x2c, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73,
0x22, 0x3a, 0x20, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x7d, 0x29, 0x2e, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x65, 0x28,
0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x71, 0x20, 0x3d, 0x20,
0x75, 0x72, 0x6c, 0x6c, 0x69, 0x62, 0x2e, 0x72, 0x65, 0x71, 0x75, 0x65,
0x73, 0x74, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x28, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x75, 0x72, 0x6c, 0x2c,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x61, 0x74,
0x61, 0x3d, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x2c, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x68, 0x65, 0x61, 0x64, 0x65,
0x72, 0x73, 0x3d, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e,
0x74, 0x2d, 0x54, 0x79, 0x70, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x61, 0x70,
0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x6a, 0x73,
0x6f, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74,
0x22, 0x3a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x70,
0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x6a, 0x73,
0x6f, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x29, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x74, 0x72, 0x79, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x75, 0x72, 0x6c, 0x6c, 0x69,
0x62, 0x2e, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x75, 0x72,
0x6c, 0x6f, 0x70, 0x65, 0x6e, 0x28, 0x72, 0x65, 0x71, 0x2c, 0x20, 0x74,
0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x3d, 0x31, 0x35, 0x29, 0x20, 0x61,
0x73, 0x20, 0x72, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x62, 0x6f, 0x64, 0x79, 0x20, 0x3d, 0x20,
0x72, 0x2e, 0x72, 0x65, 0x61, 0x64, 0x28, 0x29, 0x2e, 0x64, 0x65, 0x63,
0x6f, 0x64, 0x65, 0x28, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x65, 0x78,
0x63, 0x65, 0x70, 0x74, 0x20, 0x75, 0x72, 0x6c, 0x6c, 0x69, 0x62, 0x2e,
0x65, 0x72, 0x72, 0x6f, 0x72, 0x2e, 0x48, 0x54, 0x54, 0x50, 0x45, 0x72,
0x72, 0x6f, 0x72, 0x20, 0x61, 0x73, 0x20, 0x65, 0x3a, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e,
0x20, 0x7b, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x3a, 0x20, 0x7b,
0x22, 0x63, 0x6f, 0x64, 0x65, 0x22, 0x3a, 0x20, 0x65, 0x2e, 0x63, 0x6f,
0x64, 0x65, 0x2c, 0x20, 0x22, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65,
0x22, 0x3a, 0x20, 0x65, 0x2e, 0x72, 0x65, 0x61, 0x73, 0x6f, 0x6e, 0x7d,
0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x65, 0x78, 0x63, 0x65, 0x70, 0x74,
0x20, 0x45, 0x78, 0x63, 0x65, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x61,
0x73, 0x20, 0x65, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x7b, 0x22, 0x65, 0x72,
0x72, 0x6f, 0x72, 0x22, 0x3a, 0x20, 0x7b, 0x22, 0x63, 0x6f, 0x64, 0x65,
0x22, 0x3a, 0x20, 0x2d, 0x31, 0x2c, 0x20, 0x22, 0x6d, 0x65, 0x73, 0x73,
0x61, 0x67, 0x65, 0x22, 0x3a, 0x20, 0x73, 0x74, 0x72, 0x28, 0x65, 0x29,
0x7d, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x74, 0x72, 0x79, 0x3a, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75,
0x72, 0x6e, 0x20, 0x6a, 0x73, 0x6f, 0x6e, 0x2e, 0x6c, 0x6f, 0x61, 0x64,
0x73, 0x28, 0x62, 0x6f, 0x64, 0x79, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x65, 0x78, 0x63, 0x65, 0x70, 0x74, 0x20, 0x45, 0x78, 0x63, 0x65, 0x70,
0x74, 0x69, 0x6f, 0x6e, 0x20, 0x61, 0x73, 0x20, 0x65, 0x3a, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72,
0x6e, 0x20, 0x7b, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x3a, 0x20,
0x7b, 0x22, 0x63, 0x6f, 0x64, 0x65, 0x22, 0x3a, 0x20, 0x2d, 0x32, 0x2c,
0x20, 0x22, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x3a, 0x20,
0x22, 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x20, 0x4a, 0x53, 0x4f,
0x4e, 0x3a, 0x20, 0x22, 0x20, 0x2b, 0x20, 0x73, 0x74, 0x72, 0x28, 0x65,
0x29, 0x7d, 0x7d, 0x0a, 0x0a, 0x64, 0x65, 0x66, 0x20, 0x5f, 0x73, 0x74,
0x64, 0x69, 0x6f, 0x5f, 0x6a, 0x73, 0x6f, 0x6e, 0x72, 0x70, 0x63, 0x28,
0x63, 0x6d, 0x64, 0x2c, 0x20, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x2c,
0x20, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x29, 0x3a, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x20, 0x73, 0x75, 0x62,
0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x61, 0x72, 0x67, 0x73, 0x20, 0x3d, 0x20, 0x63, 0x6d, 0x64, 0x2e, 0x73,
0x70, 0x6c, 0x69, 0x74, 0x28, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x74,
0x72, 0x79, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x70, 0x72, 0x6f, 0x63, 0x20, 0x3d, 0x20, 0x73, 0x75, 0x62, 0x70, 0x72,
0x6f, 0x63, 0x65, 0x73, 0x73, 0x2e, 0x50, 0x6f, 0x70, 0x65, 0x6e, 0x28,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x61, 0x72, 0x67, 0x73, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x74, 0x64, 0x69, 0x6e,
0x3d, 0x73, 0x75, 0x62, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x2e,
0x50, 0x49, 0x50, 0x45, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x74, 0x64, 0x6f, 0x75, 0x74,
0x3d, 0x73, 0x75, 0x62, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x2e,
0x50, 0x49, 0x50, 0x45, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x74, 0x64, 0x65, 0x72, 0x72,
0x3d, 0x73, 0x75, 0x62, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x2e,
0x44, 0x45, 0x56, 0x4e, 0x55, 0x4c, 0x4c, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x65, 0x78,
0x63, 0x65, 0x70, 0x74, 0x20, 0x46, 0x69, 0x6c, 0x65, 0x4e, 0x6f, 0x74,
0x46, 0x6f, 0x75, 0x6e, 0x64, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x20, 0x61,
0x73, 0x20, 0x65, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x7b, 0x22, 0x65, 0x72,
0x72, 0x6f, 0x72, 0x22, 0x3a, 0x20, 0x7b, 0x22, 0x63, 0x6f, 0x64, 0x65,
0x22, 0x3a, 0x20, 0x2d, 0x31, 0x2c, 0x20, 0x22, 0x6d, 0x65, 0x73, 0x73,
0x61, 0x67, 0x65, 0x22, 0x3a, 0x20, 0x73, 0x74, 0x72, 0x28, 0x65, 0x29,
0x7d, 0x7d, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x66, 0x20,
0x73, 0x65, 0x6e, 0x64, 0x28, 0x6f, 0x62, 0x6a, 0x29, 0x3a, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x69, 0x6e, 0x65, 0x20,
0x3d, 0x20, 0x28, 0x6a, 0x73, 0x6f, 0x6e, 0x2e, 0x64, 0x75, 0x6d, 0x70,
0x73, 0x28, 0x6f, 0x62, 0x6a, 0x29, 0x20, 0x2b, 0x20, 0x22, 0x5c, 0x6e,
0x22, 0x29, 0x2e, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x65, 0x28, 0x29, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x70, 0x72, 0x6f, 0x63,
0x2e, 0x73, 0x74, 0x64, 0x69, 0x6e, 0x2e, 0x77, 0x72, 0x69, 0x74, 0x65,
0x28, 0x6c, 0x69, 0x6e, 0x65, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x70, 0x72, 0x6f, 0x63, 0x2e, 0x73, 0x74, 0x64, 0x69,
0x6e, 0x2e, 0x66, 0x6c, 0x75, 0x73, 0x68, 0x28, 0x29, 0x0a, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x64, 0x65, 0x66, 0x20, 0x72, 0x65, 0x63, 0x76, 0x28,
0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c,
0x69, 0x6e, 0x65, 0x20, 0x3d, 0x20, 0x70, 0x72, 0x6f, 0x63, 0x2e, 0x73,
0x74, 0x64, 0x6f, 0x75, 0x74, 0x2e, 0x72, 0x65, 0x61, 0x64, 0x6c, 0x69,
0x6e, 0x65, 0x28, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x69, 0x66, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x6c, 0x69, 0x6e, 0x65,
0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x7b, 0x7d, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75,
0x72, 0x6e, 0x20, 0x6a, 0x73, 0x6f, 0x6e, 0x2e, 0x6c, 0x6f, 0x61, 0x64,
0x73, 0x28, 0x6c, 0x69, 0x6e, 0x65, 0x2e, 0x64, 0x65, 0x63, 0x6f, 0x64,
0x65, 0x28, 0x29, 0x2e, 0x73, 0x74, 0x72, 0x69, 0x70, 0x28, 0x29, 0x29,
0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x74, 0x72, 0x79, 0x3a, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x65, 0x6e, 0x64, 0x28,
0x7b, 0x22, 0x6a, 0x73, 0x6f, 0x6e, 0x72, 0x70, 0x63, 0x22, 0x3a, 0x22,
0x32, 0x2e, 0x30, 0x22, 0x2c, 0x22, 0x69, 0x64, 0x22, 0x3a, 0x31, 0x2c,
0x22, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x22, 0x3a, 0x22, 0x69, 0x6e,
0x69, 0x74, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x22, 0x2c, 0x22, 0x70,
0x61, 0x72, 0x61, 0x6d, 0x73, 0x22, 0x3a, 0x7b, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f,
0x6e, 0x22, 0x3a, 0x22, 0x32, 0x30, 0x32, 0x34, 0x2d, 0x31, 0x31, 0x2d,
0x30, 0x35, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x61, 0x70, 0x61, 0x62, 0x69,
0x6c, 0x69, 0x74, 0x69, 0x65, 0x73, 0x22, 0x3a, 0x7b, 0x7d, 0x2c, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x22, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x22,
0x3a, 0x7b, 0x22, 0x6e, 0x61, 0x6d, 0x65, 0x22, 0x3a, 0x22, 0x74, 0x69,
0x6e, 0x79, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x2d, 0x6d, 0x63, 0x70,
0x22, 0x2c, 0x22, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0x3a,
0x22, 0x31, 0x2e, 0x30, 0x22, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x7d, 0x7d, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x72, 0x65, 0x63, 0x76, 0x28, 0x29, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x65, 0x6e, 0x64, 0x28, 0x7b,
0x22, 0x6a, 0x73, 0x6f, 0x6e, 0x72, 0x70, 0x63, 0x22, 0x3a, 0x22, 0x32,
0x2e, 0x30, 0x22, 0x2c, 0x22, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x22,
0x3a, 0x22, 0x6e, 0x6f, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69,
0x6f, 0x6e, 0x73, 0x2f, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x69,
0x7a, 0x65, 0x64, 0x22, 0x2c, 0x22, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73,
0x22, 0x3a, 0x7b, 0x7d, 0x7d, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x73, 0x65, 0x6e, 0x64, 0x28, 0x7b, 0x22, 0x6a, 0x73,
0x6f, 0x6e, 0x72, 0x70, 0x63, 0x22, 0x3a, 0x22, 0x32, 0x2e, 0x30, 0x22,
0x2c, 0x22, 0x69, 0x64, 0x22, 0x3a, 0x32, 0x2c, 0x22, 0x6d, 0x65, 0x74,
0x68, 0x6f, 0x64, 0x22, 0x3a, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x2c,
0x22, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x22, 0x3a, 0x70, 0x61, 0x72,
0x61, 0x6d, 0x73, 0x7d, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x72, 0x65, 0x73, 0x70, 0x20, 0x3d, 0x20, 0x72, 0x65, 0x63,
0x76, 0x28, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x72, 0x65, 0x73, 0x70, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x65, 0x78, 0x63, 0x65, 0x70, 0x74, 0x20, 0x45,
0x78, 0x63, 0x65, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x61, 0x73, 0x20,
0x65, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72,
0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x7b, 0x22, 0x65, 0x72, 0x72, 0x6f,
0x72, 0x22, 0x3a, 0x7b, 0x22, 0x63, 0x6f, 0x64, 0x65, 0x22, 0x3a, 0x2d,
0x31, 0x2c, 0x22, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x3a,
0x73, 0x74, 0x72, 0x28, 0x65, 0x29, 0x7d, 0x7d, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x66, 0x69, 0x6e, 0x61, 0x6c, 0x6c, 0x79, 0x3a, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x70, 0x72, 0x6f, 0x63, 0x2e, 0x74,
0x65, 0x72, 0x6d, 0x69, 0x6e, 0x61, 0x74, 0x65, 0x28, 0x29, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x70, 0x72, 0x6f, 0x63, 0x2e,
0x77, 0x61, 0x69, 0x74, 0x28, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74,
0x3d, 0x33, 0x29, 0x0a, 0x0a, 0x64, 0x65, 0x66, 0x20, 0x5f, 0x64, 0x69,
0x73, 0x70, 0x61, 0x74, 0x63, 0x68, 0x28, 0x75, 0x72, 0x6c, 0x2c, 0x20,
0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x2c, 0x20, 0x70, 0x61, 0x72, 0x61,
0x6d, 0x73, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20,
0x75, 0x72, 0x6c, 0x2e, 0x73, 0x74, 0x61, 0x72, 0x74, 0x73, 0x77, 0x69,
0x74, 0x68, 0x28, 0x22, 0x73, 0x74, 0x64, 0x69, 0x6f, 0x3a, 0x2f, 0x2f,
0x22, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x5f, 0x73, 0x74, 0x64, 0x69,
0x6f, 0x5f, 0x6a, 0x73, 0x6f, 0x6e, 0x72, 0x70, 0x63, 0x28, 0x75, 0x72,
0x6c, 0x5b, 0x6c, 0x65, 0x6e, 0x28, 0x22, 0x73, 0x74, 0x64, 0x69, 0x6f,
0x3a, 0x2f, 0x2f, 0x22, 0x29, 0x3a, 0x5d, 0x2c, 0x20, 0x6d, 0x65, 0x74,
0x68, 0x6f, 0x64, 0x2c, 0x20, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x29,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x65, 0x6c, 0x73, 0x65, 0x3a, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72,
0x6e, 0x20, 0x5f, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x6a, 0x73, 0x6f, 0x6e,
0x72, 0x70, 0x63, 0x28, 0x75, 0x72, 0x6c, 0x2c, 0x20, 0x6d, 0x65, 0x74,
0x68, 0x6f, 0x64, 0x2c, 0x20, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x29,
0x0a, 0x0a, 0x64, 0x65, 0x66, 0x20, 0x6d, 0x63, 0x70, 0x5f, 0x70, 0x69,
0x6e, 0x67, 0x28, 0x75, 0x72, 0x6c, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x72, 0x65, 0x73, 0x70, 0x20, 0x3d, 0x20, 0x5f, 0x64, 0x69, 0x73,
0x70, 0x61, 0x74, 0x63, 0x68, 0x28, 0x75, 0x72, 0x6c, 0x2c, 0x20, 0x22,
0x70, 0x69, 0x6e, 0x67, 0x22, 0x2c, 0x20, 0x7b, 0x7d, 0x29, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72,
0x22, 0x20, 0x69, 0x6e, 0x20, 0x72, 0x65, 0x73, 0x70, 0x3a, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72,
0x6e, 0x20, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x3a, 0x20, 0x22, 0x20, 0x2b,
0x20, 0x72, 0x65, 0x73, 0x70, 0x5b, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72,
0x22, 0x5d, 0x2e, 0x67, 0x65, 0x74, 0x28, 0x22, 0x6d, 0x65, 0x73, 0x73,
0x61, 0x67, 0x65, 0x22, 0x2c, 0x20, 0x73, 0x74, 0x72, 0x28, 0x72, 0x65,
0x73, 0x70, 0x5b, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x5d, 0x29,
0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e,
0x20, 0x22, 0x6f, 0x6b, 0x22, 0x0a, 0x0a, 0x64, 0x65, 0x66, 0x20, 0x6d,
0x63, 0x70, 0x5f, 0x6c, 0x69, 0x73, 0x74, 0x5f, 0x74, 0x6f, 0x6f, 0x6c,
0x73, 0x28, 0x75, 0x72, 0x6c, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x72, 0x65, 0x73, 0x70, 0x20, 0x3d, 0x20, 0x5f, 0x64, 0x69, 0x73, 0x70,
0x61, 0x74, 0x63, 0x68, 0x28, 0x75, 0x72, 0x6c, 0x2c, 0x20, 0x22, 0x74,
0x6f, 0x6f, 0x6c, 0x73, 0x2f, 0x6c, 0x69, 0x73, 0x74, 0x22, 0x2c, 0x20,
0x7b, 0x7d, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x22,
0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x20, 0x69, 0x6e, 0x20, 0x72, 0x65,
0x73, 0x70, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x22, 0x65, 0x72, 0x72, 0x6f,
0x3a, 0x20, 0x22, 0x20, 0x2b, 0x20, 0x72, 0x65, 0x73, 0x70, 0x5b, 0x22,
0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x5d, 0x2e, 0x67, 0x65, 0x74, 0x28,
0x22, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x2c, 0x20, 0x73,
0x74, 0x72, 0x28, 0x72, 0x65, 0x73, 0x70, 0x5b, 0x22, 0x65, 0x72, 0x72,
0x6f, 0x72, 0x22, 0x5d, 0x29, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72,
0x65, 0x73, 0x75, 0x6c, 0x74, 0x20, 0x3d, 0x20, 0x72, 0x65, 0x73, 0x70,
0x2e, 0x67, 0x65, 0x74, 0x28, 0x22, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74,
0x22, 0x2c, 0x20, 0x72, 0x65, 0x73, 0x70, 0x29, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x74, 0x6f, 0x6f, 0x6c, 0x73, 0x20, 0x3d, 0x20, 0x72, 0x65, 0x73,
0x75, 0x6c, 0x74, 0x2e, 0x67, 0x65, 0x74, 0x28, 0x22, 0x74, 0x6f, 0x6f,
0x6c, 0x73, 0x22, 0x2c, 0x20, 0x5b, 0x5d, 0x29, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x6f, 0x75, 0x74, 0x20, 0x3d, 0x20, 0x5b, 0x5d, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x74, 0x20, 0x69, 0x6e, 0x20, 0x74,
0x6f, 0x6f, 0x6c, 0x73, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x3d, 0x20, 0x74, 0x2e, 0x67,
0x65, 0x74, 0x28, 0x22, 0x6e, 0x61, 0x6d, 0x65, 0x22, 0x2c, 0x22, 0x3f,
0x22, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64,
0x65, 0x73, 0x63, 0x20, 0x3d, 0x20, 0x74, 0x2e, 0x67, 0x65, 0x74, 0x28,
0x22, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e,
0x22, 0x2c, 0x22, 0x22, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x6f, 0x75, 0x74, 0x2e, 0x61, 0x70, 0x70, 0x65, 0x6e, 0x64,
0x28, 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x2b, 0x20, 0x22, 0x3a, 0x20, 0x22,
0x20, 0x2b, 0x20, 0x64, 0x65, 0x73, 0x63, 0x29, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x22, 0x5c, 0x6e, 0x22,
0x2e, 0x6a, 0x6f, 0x69, 0x6e, 0x28, 0x6f, 0x75, 0x74, 0x29, 0x20, 0x69,
0x66, 0x20, 0x6f, 0x75, 0x74, 0x20, 0x65, 0x6c, 0x73, 0x65, 0x20, 0x22,
0x28, 0x6e, 0x65, 0x6e, 0x68, 0x75, 0x6d, 0x61, 0x20, 0x66, 0x65, 0x72,
0x72, 0x61, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x29, 0x22, 0x0a, 0x0a, 0x64,
0x65, 0x66, 0x20, 0x6d, 0x63, 0x70, 0x5f, 0x63, 0x61, 0x6c, 0x6c, 0x5f,
0x74, 0x6f, 0x6f, 0x6c, 0x28, 0x75, 0x72, 0x6c, 0x2c, 0x20, 0x74, 0x6f,
0x6f, 0x6c, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x2c, 0x20, 0x61, 0x72, 0x67,
0x73, 0x5f, 0x6a, 0x73, 0x6f, 0x6e, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x74, 0x72, 0x79, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x61, 0x72, 0x67, 0x73, 0x20, 0x3d, 0x20, 0x6a, 0x73, 0x6f,
0x6e, 0x2e, 0x6c, 0x6f, 0x61, 0x64, 0x73, 0x28, 0x61, 0x72, 0x67, 0x73,
0x5f, 0x6a, 0x73, 0x6f, 0x6e, 0x29, 0x20, 0x69, 0x66, 0x20, 0x61, 0x72,
0x67, 0x73, 0x5f, 0x6a, 0x73, 0x6f, 0x6e, 0x20, 0x61, 0x6e, 0x64, 0x20,
0x61, 0x72, 0x67, 0x73, 0x5f, 0x6a, 0x73, 0x6f, 0x6e, 0x2e, 0x73, 0x74,
0x72, 0x69, 0x70, 0x28, 0x29, 0x20, 0x65, 0x6c, 0x73, 0x65, 0x20, 0x7b,
0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x65, 0x78, 0x63, 0x65, 0x70, 0x74,
0x20, 0x45, 0x78, 0x63, 0x65, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x61,
0x73, 0x20, 0x65, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x22, 0x65, 0x72, 0x72,
0x6f, 0x3a, 0x20, 0x61, 0x72, 0x67, 0x73, 0x20, 0x4a, 0x53, 0x4f, 0x4e,
0x20, 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x6f, 0x3a, 0x20, 0x22,
0x20, 0x2b, 0x20, 0x73, 0x74, 0x72, 0x28, 0x65, 0x29, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x72, 0x65, 0x73, 0x70, 0x20, 0x3d, 0x20, 0x5f, 0x64, 0x69,
0x73, 0x70, 0x61, 0x74, 0x63, 0x68, 0x28, 0x75, 0x72, 0x6c, 0x2c, 0x20,
0x22, 0x74, 0x6f, 0x6f, 0x6c, 0x73, 0x2f, 0x63, 0x61, 0x6c, 0x6c, 0x22,
0x2c, 0x20, 0x7b, 0x22, 0x6e, 0x61, 0x6d, 0x65, 0x22, 0x3a, 0x20, 0x74,
0x6f, 0x6f, 0x6c, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x2c, 0x20, 0x22, 0x61,
0x72, 0x67, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x22, 0x3a, 0x20, 0x61,
0x72, 0x67, 0x73, 0x7d, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66,
0x20, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x20, 0x69, 0x6e, 0x20,
0x72, 0x65, 0x73, 0x70, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x22, 0x65, 0x72,
0x72, 0x6f, 0x3a, 0x20, 0x22, 0x20, 0x2b, 0x20, 0x72, 0x65, 0x73, 0x70,
0x5b, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x5d, 0x2e, 0x67, 0x65,
0x74, 0x28, 0x22, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x2c,
0x20, 0x73, 0x74, 0x72, 0x28, 0x72, 0x65, 0x73, 0x70, 0x5b, 0x22, 0x65,
0x72, 0x72, 0x6f, 0x72, 0x22, 0x5d, 0x29, 0x29, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x20, 0x3d, 0x20, 0x72, 0x65,
0x73, 0x70, 0x2e, 0x67, 0x65, 0x74, 0x28, 0x22, 0x72, 0x65, 0x73, 0x75,
0x6c, 0x74, 0x22, 0x2c, 0x20, 0x72, 0x65, 0x73, 0x70, 0x29, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x20, 0x3d,
0x20, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x2e, 0x67, 0x65, 0x74, 0x28,
0x22, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x22, 0x2c, 0x20, 0x72,
0x65, 0x73, 0x75, 0x6c, 0x74, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69,
0x66, 0x20, 0x69, 0x73, 0x69, 0x6e, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65,
0x28, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2c, 0x20, 0x6c, 0x69,
0x73, 0x74, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x70, 0x61, 0x72, 0x74, 0x73, 0x20, 0x3d, 0x20, 0x5b, 0x5d, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6f, 0x72, 0x20,
0x69, 0x74, 0x65, 0x6d, 0x20, 0x69, 0x6e, 0x20, 0x63, 0x6f, 0x6e, 0x74,
0x65, 0x6e, 0x74, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x69, 0x73, 0x69, 0x6e,
0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x28, 0x69, 0x74, 0x65, 0x6d, 0x2c,
0x20, 0x64, 0x69, 0x63, 0x74, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x70, 0x61, 0x72, 0x74, 0x73, 0x2e, 0x61, 0x70, 0x70, 0x65, 0x6e, 0x64,
0x28, 0x69, 0x74, 0x65, 0x6d, 0x2e, 0x67, 0x65, 0x74, 0x28, 0x22, 0x74,
0x65, 0x78, 0x74, 0x22, 0x2c, 0x20, 0x6a, 0x73, 0x6f, 0x6e, 0x2e, 0x64,
0x75, 0x6d, 0x70, 0x73, 0x28, 0x69, 0x74, 0x65, 0x6d, 0x29, 0x29, 0x29,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x65, 0x6c, 0x73, 0x65, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x70,
0x61, 0x72, 0x74, 0x73, 0x2e, 0x61, 0x70, 0x70, 0x65, 0x6e, 0x64, 0x28,
0x73, 0x74, 0x72, 0x28, 0x69, 0x74, 0x65, 0x6d, 0x29, 0x29, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72,
0x6e, 0x20, 0x22, 0x5c, 0x6e, 0x22, 0x2e, 0x6a, 0x6f, 0x69, 0x6e, 0x28,
0x70, 0x61, 0x72, 0x74, 0x73, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72,
0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x6a, 0x73, 0x6f, 0x6e, 0x2e, 0x64,
0x75, 0x6d, 0x70, 0x73, 0x28, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74,
0x2c, 0x20, 0x65, 0x6e, 0x73, 0x75, 0x72, 0x65, 0x5f, 0x61, 0x73, 0x63,
0x69, 0x69, 0x3d, 0x46, 0x61, 0x6c, 0x73, 0x65, 0x2c, 0x20, 0x69, 0x6e,
0x64, 0x65, 0x6e, 0x74, 0x3d, 0x32, 0x29, 0x0a
};
unsigned int tb_mcp_py_len = 3728;
@@ -0,0 +1,52 @@
#ifndef TINYBLOCKS_PYTHON_H
#define TINYBLOCKS_PYTHON_H
#include <stdbool.h>
#ifdef _WIN32
# define TB_PYTHON_API __declspec(dllexport)
#else
# define TB_PYTHON_API __attribute__((visibility("default")))
#endif
/*
* tb_python — wrapper fino sobre o interpretador CPython embutido.
*
* O interpretador é compartilhado em todo o processo (singleton ref-counted).
* Compile a lib como .so compartilhada para que python.so e mcp.so usem o
* mesmo intérprete: libtinyblocks-python.so.
*/
TB_PYTHON_API bool tb_python_init(void);
TB_PYTHON_API void tb_python_deinit(void);
/*
* Avalia uma expressão Python.
* names/vals: variáveis disponíveis no namespace (n itens).
* Retorna string heap-alocada com o resultado (caller frees) ou NULL em erro.
*/
TB_PYTHON_API char* tb_python_eval(const char* expr,
const char* const* names,
const double* vals, int n);
/*
* Executa código Python arbitrário.
* Captura stdout+stderr e os retorna como string heap-alocada (caller frees).
*/
TB_PYTHON_API char* tb_python_run(const char* code);
/*
* Executa código passando variáveis como locais (nome=valor float).
* Equivalente a tb_python_run mas com namespace preenchido.
*/
TB_PYTHON_API char* tb_python_run_with_vars(const char* code,
const char* const* names,
const double* vals, int n);
/*
* Executa código no namespace __main__ (definições persistem entre chamadas).
* Retorna stdout+stderr capturado (caller frees).
*/
TB_PYTHON_API char* tb_python_exec_main(const char* code);
#endif /* TINYBLOCKS_PYTHON_H */
+179
View File
@@ -0,0 +1,179 @@
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "tinyblocks-python/tb_python.h"
/* ── Singleton ref-counted ───────────────────────────────────────────────── */
static int s_refs = 0;
TB_PYTHON_API bool tb_python_init(void) {
if (s_refs++ > 0) return true;
if (Py_IsInitialized()) return true;
Py_Initialize();
/* Garante que stdout/stderr padrão existam (modo embutido pode omití-los) */
PyRun_SimpleString(
"import sys, io\n"
"if not hasattr(sys,'_tb_orig_stdout'):\n"
" sys._tb_orig_stdout = sys.stdout\n"
" sys._tb_orig_stderr = sys.stderr\n"
);
return Py_IsInitialized();
}
TB_PYTHON_API void tb_python_deinit(void) {
if (s_refs <= 0) return;
if (--s_refs == 0 && Py_IsInitialized())
Py_FinalizeEx();
}
/* ── Helper: captura stdout+stderr de uma execução ──────────────────────── */
static char* capture_run(const char* code, PyObject* local_dict) {
/* StringIO para capturar output */
PyObject* io = PyImport_ImportModule("io");
PyObject* buf = PyObject_CallMethod(io, "StringIO", NULL);
PyObject* sys = PyImport_ImportModule("sys");
PyObject_SetAttrString(sys, "stdout", buf);
PyObject_SetAttrString(sys, "stderr", buf);
PyObject* globals = PyDict_New();
PyObject* builtins = PyEval_GetBuiltins();
PyDict_SetItemString(globals, "__builtins__", builtins);
PyObject* result = PyRun_String(code, Py_file_input, globals,
local_dict ? local_dict : globals);
if (!result) {
PyErr_Print(); /* vai para buf via stderr */
PyErr_Clear();
}
Py_XDECREF(result);
Py_DECREF(globals);
/* Restaura stdout/stderr */
PyObject* orig_out = PyObject_GetAttrString(sys, "_tb_orig_stdout");
PyObject* orig_err = PyObject_GetAttrString(sys, "_tb_orig_stderr");
if (orig_out) PyObject_SetAttrString(sys, "stdout", orig_out);
if (orig_err) PyObject_SetAttrString(sys, "stderr", orig_err);
Py_XDECREF(orig_out);
Py_XDECREF(orig_err);
PyObject* val = PyObject_CallMethod(buf, "getvalue", NULL);
const char* s = val ? PyUnicode_AsUTF8(val) : NULL;
char* out = strdup(s ? s : "");
Py_XDECREF(val);
Py_DECREF(buf);
Py_DECREF(io);
Py_DECREF(sys);
return out;
}
/* ── API pública ─────────────────────────────────────────────────────────── */
TB_PYTHON_API char* tb_python_run(const char* code) {
if (!code || !Py_IsInitialized()) return strdup("");
return capture_run(code, NULL);
}
/*
* Executa código no namespace __main__ (definições persistem entre chamadas).
* Ideal para carregar módulos/funções que serão chamados depois.
*/
TB_PYTHON_API char* tb_python_exec_main(const char* code) {
if (!code || !Py_IsInitialized()) return strdup("");
PyObject* main_mod = PyImport_AddModule("__main__"); /* borrowed */
PyObject* main_dict = PyModule_GetDict(main_mod); /* borrowed */
/* Redireciona stdout/stderr */
PyObject* io = PyImport_ImportModule("io");
PyObject* buf = PyObject_CallMethod(io, "StringIO", NULL);
PyObject* sys = PyImport_ImportModule("sys");
PyObject_SetAttrString(sys, "stdout", buf);
PyObject_SetAttrString(sys, "stderr", buf);
/* Executa com main_dict como globals E locals — definições persistem */
PyObject* result = PyRun_String(code, Py_file_input, main_dict, main_dict);
if (!result) { PyErr_Print(); PyErr_Clear(); }
Py_XDECREF(result);
/* Restaura stdout/stderr */
PyObject* orig_out = PyObject_GetAttrString(sys, "_tb_orig_stdout");
PyObject* orig_err = PyObject_GetAttrString(sys, "_tb_orig_stderr");
if (orig_out) PyObject_SetAttrString(sys, "stdout", orig_out);
if (orig_err) PyObject_SetAttrString(sys, "stderr", orig_err);
Py_XDECREF(orig_out);
Py_XDECREF(orig_err);
PyObject* val = PyObject_CallMethod(buf, "getvalue", NULL);
const char* s = val ? PyUnicode_AsUTF8(val) : NULL;
char* out = strdup(s ? s : "");
Py_XDECREF(val);
Py_DECREF(buf);
Py_DECREF(io);
Py_DECREF(sys);
return out;
}
TB_PYTHON_API char* tb_python_run_with_vars(const char* code,
const char* const* names,
const double* vals, int n) {
if (!code || !Py_IsInitialized()) return strdup("");
PyObject* locals = PyDict_New();
for (int i = 0; i < n; i++) {
if (!names[i]) continue;
PyObject* v = PyFloat_FromDouble(vals[i]);
PyDict_SetItemString(locals, names[i], v);
Py_DECREF(v);
}
char* out = capture_run(code, locals);
Py_DECREF(locals);
return out;
}
TB_PYTHON_API char* tb_python_eval(const char* expr,
const char* const* names, const double* vals, int n) {
if (!expr || !Py_IsInitialized()) return strdup("<erro: Python não inicializado>");
PyObject* globals = PyDict_New();
PyObject* builtins = PyEval_GetBuiltins();
PyDict_SetItemString(globals, "__builtins__", builtins);
for (int i = 0; i < n; i++) {
if (!names[i]) continue;
PyObject* v = PyFloat_FromDouble(vals[i]);
PyDict_SetItemString(globals, names[i], v);
Py_DECREF(v);
}
PyObject* result = PyRun_String(expr, Py_eval_input, globals, globals);
char* out = NULL;
if (result) {
PyObject* str = PyObject_Str(result);
const char* s = str ? PyUnicode_AsUTF8(str) : NULL;
out = strdup(s ? s : "None");
Py_XDECREF(str);
Py_DECREF(result);
} else {
PyObject* exc = PyErr_GetRaisedException();
PyObject* str = exc ? PyObject_Str(exc) : NULL;
const char* s = str ? PyUnicode_AsUTF8(str) : NULL;
char buf[256];
snprintf(buf, sizeof(buf), "<erro: %s>", s ? s : "?");
out = strdup(buf);
Py_XDECREF(str);
Py_XDECREF(exc);
PyErr_Clear();
}
Py_DECREF(globals);
return out;
}
+30
View File
@@ -0,0 +1,30 @@
CC := gcc
CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \
-I../../include \
$(shell sdl2-config --cflags)
LDFLAGS := $(shell sdl2-config --libs)
BUILD := ../../build
LIB_SO := $(BUILD)/libtinyblocks-sdl2.so
LIB_A := $(BUILD)/libtinyblocks-sdl2.a
OBJ := $(BUILD)/tb_sdl2.o
.PHONY: all clean shared static
all: shared static
shared: $(LIB_SO)
static: $(LIB_A)
$(OBJ): src/tb_sdl2.c include/tb_sdl2.h
@mkdir -p $(BUILD)
$(CC) $(CFLAGS) -fPIC -c src/tb_sdl2.c -o $@
$(LIB_SO): $(OBJ)
$(CC) -shared -o $@ $^ $(LDFLAGS)
$(LIB_A): $(OBJ)
ar rcs $@ $^
clean:
$(RM) $(OBJ) $(LIB_SO) $(LIB_A)
@@ -0,0 +1,61 @@
/*
* TinyBlocks — tb_sdl2.h
*
* TypeBlocks disponíveis após registrar esta library:
*
* SDL2.Events — expõe o estado de eventos do frame corrente (sem inputs;
* outputs pré-preenchidos pelo SDL2.App antes de cada on_draw)
*
* SDL2.App — cria janela, roda o loop principal, chama on_draw na scene.
* in: title(text), w(int), h(int), scene(block), events(block)
*
* Blocos primitivos (uso manual):
* SDL2.Init / SDL2.Quit
* SDL2.Window / SDL2.DestroyWindow
* SDL2.Renderer / SDL2.DestroyRenderer
* SDL2.SetDrawColor / SDL2.Clear / SDL2.FillRect / SDL2.DrawRect
* SDL2.Present / SDL2.Delay / SDL2.PollEvent
*/
#ifndef TINYBLOCKS_SDL2_H
#define TINYBLOCKS_SDL2_H
#include <tinyblocks/tinyblocks.h>
TB_API const TinyBlocks_LibraryDescriptor* tb_sdl2_get_library(void);
TB_API const TinyBlocks_LibraryDescriptor* tinyblocks_get_library(void);
/* Implementação do contrato de backend da interface tinyblocks-graphics
* (struct definida em tb_graphics.h; declarada aqui só por nome para que
* quem usa os blocos SDL2.* não precise do header da interface). */
struct TinyBlocks_GraphicsBackend;
TB_API const struct TinyBlocks_GraphicsBackend* tb_sdl2_graphics_backend(void);
/* ── Índices de output do bloco SDL2.Events ──────────────────────────────── */
#define SDL2_EV_MOUSE_X 0 /* real: posição X do mouse */
#define SDL2_EV_MOUSE_Y 1 /* real: posição Y do mouse */
#define SDL2_EV_MOUSE_L_HELD 2 /* int: botão esquerdo pressionado (estado) */
#define SDL2_EV_MOUSE_R_HELD 3 /* int: botão direito pressionado (estado) */
#define SDL2_EV_MOUSE_L_DOWN 4 /* int: 1 se pressionado neste frame */
#define SDL2_EV_MOUSE_L_UP 5 /* int: 1 se solto neste frame */
#define SDL2_EV_MOUSE_R_DOWN 6 /* int: 1 se pressionado neste frame */
#define SDL2_EV_MOUSE_R_UP 7 /* int: 1 se solto neste frame */
#define SDL2_EV_SCROLL_DY 8 /* real: scroll vertical deste frame */
#define SDL2_EV_KEY_SCANCODE 9 /* int: SDL_Scancode da tecla pressionada */
#define SDL2_EV_KEY_MOD 10 /* int: SDL_Keymod (KMOD_CTRL etc.) */
#define SDL2_EV_KEY_REPEAT 11 /* int: 1 se é repeat de key held */
#define SDL2_EV_TEXT_INPUT 12 /* text: texto digitado neste frame */
#define SDL2_EV_QUIT 13 /* int: 1 se janela foi fechada */
#define SDL2_EV_WIN_W 14 /* int: largura atual da janela */
#define SDL2_EV_WIN_H 15 /* int: altura atual da janela */
#define SDL2_EV_DROP_FILE 16 /* text: caminho de arquivo arrastado */
#define SDL2_EV_SCROLL_DX 17 /* real: scroll horizontal deste frame */
#define SDL2_EV_MOD_STATE 18 /* int: SDL_GetModState() deste frame */
#define SDL2_EV_COUNT 19 /* total de outputs */
/* ── Constantes de tipo de evento (SDL2.PollEvent legado) ───────────────── */
#define TB_SDL2_EVENT_NONE 0
#define TB_SDL2_EVENT_QUIT 256
#define TB_SDL2_EVENT_KEYDOWN 768
#define TB_SDL2_EVENT_KEYUP 769
#endif /* TINYBLOCKS_SDL2_H */
File diff suppressed because it is too large. Load diff