diff --git a/Makefile b/Makefile index 409ca06..2d8bd46 100644 --- a/Makefile +++ b/Makefile @@ -66,6 +66,7 @@ SRCS := src/tinyblocks.c \ src/tb_vector_block.c \ src/tb_renderable_block.c \ src/tb_stage.c \ + src/tb_input.c \ src/tb_json_block.c \ src/tb_image.c \ src/tb_meta.c @@ -73,7 +74,7 @@ SRCS := src/tinyblocks.c \ OBJS := $(patsubst src/%.c,$(BUILD)/%.o,$(SRCS)) OBJS_DBG := $(patsubst src/%.c,$(BUILD)/%-dbg.o,$(SRCS)) -CAT_LIBS := events control operators number string variables vector appearance pen fs os environ +CAT_LIBS := events control input operators number string variables vector appearance pen fs os environ CAT_A := $(foreach l,$(CAT_LIBS),$(LIBDIR)/tinyblocks-$(l)/build/libtinyblocks-$(l).a) CAT_LDFLAGS := $(foreach l,$(CAT_LIBS),-ltinyblocks-$(l)) CAT_INCS := $(foreach l,$(CAT_LIBS),-I$(LIBDIR)/tinyblocks-$(l)/include) @@ -95,9 +96,9 @@ LIB_LDFLAGS := -L$(ED_DIR)/build -L$(GX_DIR)/build -L$(SD_DIR)/build \ editor run-editor run-sdl2 mylib vector customappearance graphics sdl2-backend test-editor \ appdir appimage run-appimage icon \ test-toml test-plugin test-blueprint test-base64 test-curves test-meta test-ppm test-bmp test-png test-image test-vg test-svg test-jpg \ - test-syntax test-os test-stdlib test-regex test-markdown test-opentype \ + test-syntax test-os test-input test-stdlib test-regex test-markdown test-opentype \ category-libs category-sos libs \ - lib-events lib-control lib-operators lib-number lib-string lib-variables lib-vector lib-appearance lib-pen lib-fs lib-os \ + lib-events lib-control lib-input lib-operators lib-number lib-string lib-variables lib-vector lib-appearance lib-pen lib-fs lib-os \ lib-environ \ lib-editor lib-graphics lib-sdl2 lib-python lib-mcp lib-toml \ lib-json lib-xml lib-csv lib-blueprint lib-base64 lib-curves lib-ppm lib-bmp lib-png lib-image lib-vg lib-svg lib-jpg lib-syntax lib-regex lib-markdown lib-opentype lib-api lib-libman \ @@ -234,7 +235,7 @@ lib-mcp: $(MAKE) -C $(MC_DIR) libs: static lib-events lib-control lib-operators lib-variables \ - lib-appearance lib-pen lib-fs lib-os lib-number lib-string lib-vector lib-environ lib-graphics lib-sdl2 lib-toml \ + lib-appearance lib-pen lib-fs lib-os lib-input lib-number lib-string lib-vector lib-environ lib-graphics lib-sdl2 lib-toml \ lib-json lib-xml lib-csv lib-blueprint lib-base64 lib-curves lib-ppm lib-bmp lib-png lib-image lib-vg lib-svg lib-jpg lib-syntax lib-regex lib-markdown lib-opentype lib-api lib-libman lib-editor @echo "Libraries OK: category + graphics + sdl2 + toml + json + xml + csv + blueprint + base64 + curves + ppm + bmp + png + image + vg + svg + jpg + syntax + regex + markdown + opentype + api + libman + editor" @@ -619,6 +620,15 @@ $(BUILD)/os_fs_test: tests/os_fs_test.c $(FS_DIR)/src/tb_fs.c $(LIBDIR)/tinybloc test-os: $(BUILD)/os_fs_test ## Roda o teste de tinyblocks-os + pastas do tinyblocks-fs (ASan/UBSan) ./$(BUILD)/os_fs_test +$(BUILD)/input_test: tests/input_test.c $(LIBDIR)/tinyblocks-input/src/tb_input.c static + @mkdir -p $(BUILD) + $(CC) $(CFLAGS_DBG) -I$(LIBDIR)/tinyblocks-input/include -I$(GFX_INC) \ + $(LIBDIR)/tinyblocks-input/src/tb_input.c tests/input_test.c \ + -o $@ -Wl,--start-group $(LIB_A) -Wl,--end-group -lm $(EXTRA_TEST_LIBS) + +test-input: $(BUILD)/input_test ## Roda o teste de tinyblocks-input + estado de entrada do core (ASan/UBSan) + ./$(BUILD)/input_test + STD_DIRS := $(LIBDIR)/tinyblocks-string $(LIBDIR)/tinyblocks-number $(LIBDIR)/tinyblocks-vector STD_SRCS := $(foreach d,$(STD_DIRS),$(d)/src/$(patsubst tinyblocks-%,tb_%,$(notdir $(d))).c) diff --git a/examples/editor/main.c b/examples/editor/main.c index 72c68bd..e00f14d 100644 --- a/examples/editor/main.c +++ b/examples/editor/main.c @@ -30,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -65,6 +66,7 @@ int main(int argc, char** argv) { Preferimos o .so: recompilar a library recarrega a paleta ao vivo. */ reg_core(rt, "tinyblocks-events", tb_events_get_library); reg_core(rt, "tinyblocks-control", tb_control_get_library); + reg_core(rt, "tinyblocks-input", tb_input_get_library); reg_core(rt, "tinyblocks-operators", tb_operators_get_library); reg_core(rt, "tinyblocks-number", tb_number_get_library); reg_core(rt, "tinyblocks-string", tb_string_get_library); diff --git a/include/tinyblocks/tb_input.h b/include/tinyblocks/tb_input.h new file mode 100644 index 0000000..5d124a4 --- /dev/null +++ b/include/tinyblocks/tb_input.h @@ -0,0 +1,54 @@ +/* + * TinyBlocks - tb_input.h + * Estado de entrada do programa (mouse, teclado, toque, sensores, cronometro) + * em coordenadas do PALCO, lido pelos blocos de Sensores (tinyblocks-input). + * + * Fica no core, como o palco (tb_stage.h): existe uma copia so, mesmo com as + * libraries carregadas como .so. Quem mostra o palco (o editor) alimenta o + * estado a cada quadro com pontos em px da VISTA do palco; aqui eles viram + * coordenadas do palco (x -240..240, y -180..180, y para cima). + * + * Teclas sao codigos 1..127 (os TB_KEY_* do tinyblocks-graphics). + */ +#ifndef TINYBLOCKS_TB_INPUT_H +#define TINYBLOCKS_TB_INPUT_H + +#include +#include + +#define TB_INPUT_MAX_KEYS 128 +#define TB_INPUT_MAX_TOUCHES 10 + +/* -- Alimentacao (host do palco), uma vez por quadro --- */ +TB_API void tb_input_begin_frame(void); /* zera o que vale so neste quadro */ +TB_API void tb_input_set_mouse(float vx, float vy, bool left, bool right); +TB_API void tb_input_add_wheel(float dy); +TB_API void tb_input_clear_keys(void); +TB_API void tb_input_set_key(int key, bool held); +TB_API void tb_input_key_pressed(int key); /* tecla apertada neste quadro */ +TB_API void tb_input_set_touches(int n, const float* vx, const float* vy); +TB_API void tb_input_set_accel(bool has, float x, float y, float z); /* m/s² */ +TB_API void tb_input_set_gyro(bool has, float x, float y, float z); /* rad/s */ +TB_API void tb_input_reset(void); /* tudo solto, cronometro zerado */ + +/* -- Leitura (blocos) --- */ +TB_API float tb_input_mouse_x(void); /* palco, preso as bordas */ +TB_API float tb_input_mouse_y(void); +TB_API bool tb_input_mouse_over_stage(void); +TB_API bool tb_input_mouse_down(void); +TB_API bool tb_input_mouse_right_down(void); +TB_API float tb_input_wheel(void); /* rolagem deste quadro */ +TB_API bool tb_input_key_held(int key); +TB_API bool tb_input_any_key_held(void); +TB_API int tb_input_last_key(void); /* 0 = nenhuma ainda */ +TB_API int tb_input_touch_count(void); +TB_API float tb_input_touch_x(int i); /* i = 0..count-1, palco */ +TB_API float tb_input_touch_y(int i); +TB_API bool tb_input_has_accel(void); +TB_API float tb_input_accel(int axis); /* 0=x 1=y 2=z */ +TB_API bool tb_input_has_gyro(void); +TB_API float tb_input_gyro(int axis); /* graus/s */ +TB_API double tb_input_timer(void); /* segundos desde o ultimo zerar */ +TB_API void tb_input_timer_reset(void); + +#endif /* TINYBLOCKS_TB_INPUT_H */ diff --git a/include/tinyblocks/tb_stage.h b/include/tinyblocks/tb_stage.h index cf443b9..ae5109e 100644 --- a/include/tinyblocks/tb_stage.h +++ b/include/tinyblocks/tb_stage.h @@ -28,6 +28,10 @@ TB_API bool tb_stage_image_number(int number, float x, float y); /* Vista: tamanho da area onde o palco sera desenhado (letterbox 4:3) */ TB_API void tb_stage_set_view(float w, float h); +/* Ponto da vista (px, origem no canto da vista) -> coordenadas do palco + (x -240..240 para a direita, y -180..180 para cima). Devolve true se o + ponto cai dentro do palco (fora da faixa do letterbox). */ +TB_API bool tb_stage_view_to_stage(float vx, float vy, float* sx, float* sy); /* Emite os desenhos num RenderableBlock ja adquirido */ TB_API bool tb_stage_render(TinyBlocks_RenderableBlock* rb); diff --git a/libraries/tinyblocks-editor/internal/tb_editor_internal.h b/libraries/tinyblocks-editor/internal/tb_editor_internal.h index 3497062..525691a 100644 --- a/libraries/tinyblocks-editor/internal/tb_editor_internal.h +++ b/libraries/tinyblocks-editor/internal/tb_editor_internal.h @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -50,16 +51,25 @@ #define FLY_W 250 #define FLY_PAD 12 #define FLY_BTN_W 150 -#define PALETTE_W (CAT_W + FLY_W) -#define STAGE_W 360 +#define PALETTE_W (CAT_W + FLY_W) /* largura padrao da paleta */ +#define STAGE_W 360 /* largura padrao da coluna do palco */ #define STAGE_BAR_H 44 -#define PAL_Y (MENU_H + TAB_H) -#define WS_X PALETTE_W -#define WS_Y (MENU_H + TAB_H) #define WIN_W (ed->win_w) #define WIN_H (ed->win_h) -#define WS_W (ed->win_w - PALETTE_W - STAGE_W) -#define WS_H (ed->win_h - WS_Y) + +/* Retangulo de cada view, calculado a cada quadro pela arvore de areas + (lay_compute em tb_editor.c). As views podem mudar de lugar e tamanho. */ +#define AREA(v) (ed->area[(v)]) +#define PAL_X (AREA(V_PALETTE).x) +#define PAL_Y (AREA(V_PALETTE).y + TAB_H) /* abaixo do cabecalho */ +#define PAL_B (AREA(V_PALETTE).y + AREA(V_PALETTE).h) +#define FLY_X (PAL_X + CAT_W) +#define FLY_R (PAL_X + AREA(V_PALETTE).w) +#define WS_X (AREA(V_SCRIPTS).x) +#define WS_Y (AREA(V_SCRIPTS).y + TAB_H) /* abaixo das abas */ +#define WS_W (AREA(V_SCRIPTS).w) +#define WS_H (AREA(V_SCRIPTS).h - TAB_H) +#define WS_R (WS_X + WS_W) #define TAB_W 150 #define PLUS_W 28 @@ -265,6 +275,25 @@ static const BlockSpec s_specs[] = { {"Events.WhenRun", "quando a bandeira for clicado", NULL}, {"Control.Repeat", "repita %1 vezes", "10"}, {"Control.Forever", "sempre", NULL}, + /* Sensores (tinyblocks-input) */ + {"Input.MouseX", "posição x do mouse", NULL}, + {"Input.MouseY", "posição y do mouse", NULL}, + {"Input.MouseDown", "mouse pressionado?", NULL}, + {"Input.MouseRight", "botão direito pressionado?", NULL}, + {"Input.MouseOver", "mouse sobre o palco?", NULL}, + {"Input.Wheel", "rolagem do mouse", NULL}, + {"Input.KeyPressed", "tecla %1 pressionada?", "espaço"}, + {"Input.LastKey", "última tecla", NULL}, + {"Input.Touching", "tocando a tela?", NULL}, + {"Input.TouchCount", "número de toques", NULL}, + {"Input.TouchX", "x do toque %1", "1"}, + {"Input.TouchY", "y do toque %1", "1"}, + {"Input.HasAccel", "tem acelerômetro?", NULL}, + {"Input.Accel", "aceleração em %1", "x"}, + {"Input.HasGyro", "tem giroscópio?", NULL}, + {"Input.Gyro", "giro em %1 (graus/s)", "x"}, + {"Input.Timer", "cronômetro", NULL}, + {"Input.ResetTimer", "zere o cronômetro", NULL}, {"Control.RepeatUntil", "repita até que %1", NULL}, {"Control.If", "se %1 então", NULL}, {"Control.IfElse", "se %1 então", NULL}, @@ -631,6 +660,52 @@ typedef struct { TinyBlocks_Block* r; } RtCacheEnt; +/* Areas (layout estilo Blender): arvore de divisoes. Cada no divide um + retangulo lado a lado (HSPLIT: a | b) ou um em cima do outro (VSPLIT: + a sobre b); as folhas sao as views. Um lado de cada divisao tem tamanho + fixo em px e o outro absorve o redimensionamento da janela. */ +enum { V_PALETTE, V_SCRIPTS, V_STAGE, V_OUTPUT, V_COUNT }; +enum { LN_LEAF, LN_HSPLIT, LN_VSPLIT }; +typedef struct { + int kind; /* LN_* */ + int a, b; /* filhos */ + int view; /* folha: V_* */ + int fix; /* lado com tamanho fixo: 0 = a, 1 = b */ + float px; /* tamanho desse lado em px */ + float x, y, w, h; /* calculados a cada quadro */ + float pos; /* coordenada da borda entre a e b */ +} LayNode; +#define LAY_MAX 16 +typedef struct { float x, y, w, h; bool shown, detached; } AreaRect; + +/* Aba destacada numa janela propria (como arrastar a aba para fora no + navegador). Enquanto a janela trata eventos ou desenha, o editor troca a + aba atual e o retangulo dos scripts pelos dela ("contexto" da aba). */ +#define TABWIN_MAX 6 +typedef struct { + int tab; /* aba mostrada (-1 = slot livre) */ + TinyBlocks_Block* win; + TinyBlocks_Block* in; + TinyBlocks_Block* scene; + float geom[4]; /* x, y na tela, largura, altura */ + bool attach_pending; + float chip_x, chip_w; /* botao "voltar" no menu */ +} TabWin; + +/* Notificacoes flutuantes (estilo EditorToaster do Godot): cada mensagem + escrita em hot_status vira um aviso com temporizador sobre a area de + scripts; mensagens repetidas viram contador. */ +#define TOAST_MAX 6 +#define TOAST_INFO_MS 4000.f +#define TOAST_ERR_MS 8000.f +typedef struct { + char text[256]; + bool ok; /* false = erro (vermelho, fica mais tempo) */ + int count; /* repeticoes da mesma mensagem */ + float left_ms, total_ms; + float x, y, w, h; /* geometria do ultimo desenho (clique/hover) */ +} Toast; + /* Formatos de exportacao */ enum { EX_JSON, EX_XML, EX_CSV }; @@ -722,16 +797,17 @@ typedef struct Ed { /* Palco: embutido no painel ou numa janela própria (Graphics.Window) */ TinyBlocks_Block* stage; - TinyBlocks_Block* stage_win; - TinyBlocks_Block* stage_in; bool clip_on; float clip[4]; TbEdModules mods; /* libraries privadas (bundle) por dlopen */ int hot_check_frame; /* contador para checar hot reload */ - char hot_status[256]; + char hot_status[256]; /* escreva aqui: vira notificacao (toast) */ bool hot_status_ok; + Toast toasts[TOAST_MAX]; /* mais nova no fim */ + int toast_n; + unsigned toast_ms; /* relogio do ultimo quadro (temporizador) */ bool path_input_active; char path_input_buf[512]; @@ -783,6 +859,40 @@ typedef struct Ed { float img_mx, img_my; /* ultimo ponto do traco (aba de imagem) */ int win_w, win_h; + + /* Areas (layout estilo Blender) */ + LayNode lay[LAY_MAX]; + int lay_n, lay_root; + AreaRect area[V_COUNT]; + int split_hover, split_drag; /* borda sob o mouse / sendo arrastada */ + int area_drag, area_drop; /* view levada pela alca / view alvo */ + + /* Views destacadas: cada uma numa janela propria (Graphics.Window com uma + cena Editor.Area). Tudo usa as coordenadas da janela principal: a area + destacada fica em (posicao da janela dela - posicao da principal). */ + TinyBlocks_Block* vwin[V_COUNT]; + TinyBlocks_Block* vwin_in[V_COUNT]; + TinyBlocks_Block* vwin_scene[V_COUNT]; + float vgeom[V_COUNT][4]; /* janela: x, y na tela, largura, altura */ + bool attach_pending[V_COUNT]; /* recolher no proximo quadro */ + int swap_pending[2]; /* trocar depois de recolher (-1 = nada) */ + float chip_x[V_COUNT], chip_w[V_COUNT]; /* botoes "voltar" no menu */ + float main_wx, main_wy; /* posicao da janela principal na tela */ + int mouse_owner; /* janela com o mouse (-1 = principal) */ + int capture_view; /* janela do clique em andamento (-2 = nenhum) */ + + /* Arrastar abas (reordenar como no navegador) */ + int tab_press; /* aba apertada (-1 = nenhuma) */ + bool tab_drag; /* passou do limiar: esta sendo arrastada */ + float tab_press_x, tab_press_y, tab_grab_dx; + + /* Abas destacadas */ + TabWin twin[TABWIN_MAX]; + int tabctx; /* janela de aba ativa (-1 = principal) */ + int ctx_main_tab; /* aba atual da principal durante o contexto */ + AreaRect main_scripts; /* area de scripts da principal */ + int drag_tab; /* aba de onde vem o bloco arrastado */ + float drag_ws_x, drag_ws_y; /* origem da area de scripts dessa aba */ } Ed; #define CT (ed->tabs[ed->cur_tab]) diff --git a/libraries/tinyblocks-editor/src/tb_editor.c b/libraries/tinyblocks-editor/src/tb_editor.c index 695d18f..fbb0b70 100644 --- a/libraries/tinyblocks-editor/src/tb_editor.c +++ b/libraries/tinyblocks-editor/src/tb_editor.c @@ -1297,6 +1297,7 @@ static void vm_stop(Ed* 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); + tb_input_timer_reset(); /* como no Scratch: a bandeira zera o cronometro */ int heads[MAX_WS], n = 0; for (int i = 0; i < CT.top_n; i++) heads[n++] = CT.top[i]; for (int i = 1; i < n; i++) @@ -1640,8 +1641,436 @@ void palette_rebuild(Ed* ed) { ed->fly_total_h = y; } +/* Altura de cada categoria: encolhe para todas caberem acima do botao de + bibliotecas (com muitas libraries carregadas a coluna fica compacta) */ +/* == Areas (layout estilo Blender) === + * Arvore de divisoes -> retangulo de cada view (paleta, scripts, palco, + * saida). Arrastar a borda entre duas areas muda o tamanho; arrastar a + * alca do cabecalho de uma area e soltar sobre outra troca as duas. */ +/* Dados da instancia de Editor.Area (cena da janela de uma view destacada) */ +typedef struct { Ed* ed; int view; } AreaScene; + +static void ed_handle_input(Ed* ed, TinyBlocks_Block* evb, int from); +static void areas_only(Ed* ed, int keep, bool saved[V_COUNT]); +static void areas_restore(Ed* ed, const bool saved[V_COUNT]); +static bool tabwin_on_draw(Ed* ed, int k, TinyBlocks_RenderableBlock** dst); +static void drag_to_ctx(Ed* ed, int tgt); +static void tabwins_close_all(Ed* ed); + +static const char* view_name(int v) { + switch (v) { + case V_PALETTE: return "Blocos"; + case V_SCRIPTS: return "Scripts"; + case V_STAGE: return "Palco"; + case V_OUTPUT: return "Saída"; + } + return "?"; +} + +static int lay_node(Ed* ed, int kind, int a, int b, int view, int fix, float px) { + if (ed->lay_n >= LAY_MAX) return -1; + LayNode* N = &ed->lay[ed->lay_n]; + memset(N, 0, sizeof(*N)); + N->kind = kind; N->a = a; N->b = b; N->view = view; N->fix = fix; N->px = px; + return ed->lay_n++; +} + +/* Layout padrao (o de sempre): paleta | scripts | palco sobre a saida */ +static void lay_default(Ed* ed) { + ed->lay_n = 0; + int pal = lay_node(ed, LN_LEAF, -1, -1, V_PALETTE, 0, 0); + int scr = lay_node(ed, LN_LEAF, -1, -1, V_SCRIPTS, 0, 0); + int stg = lay_node(ed, LN_LEAF, -1, -1, V_STAGE, 0, 0); + int out = lay_node(ed, LN_LEAF, -1, -1, V_OUTPUT, 0, 0); + int right = lay_node(ed, LN_VSPLIT, stg, out, -1, 0, STAGE_BAR_H + (STAGE_W - 16) * 0.75f + 8); + int mid = lay_node(ed, LN_HSPLIT, scr, right, -1, 1, STAGE_W); + ed->lay_root = lay_node(ed, LN_HSPLIT, pal, mid, -1, 0, PALETTE_W); +} + +/* -- Layout salvo nas configuracoes (chave "editor.layout") --------------- + * Texto curto: folha = letra da view (p paleta, s scripts, t palco, + * o saida); divisao = H|V:(a,b). O padrao e + * "H0:318(p,H1:360(s,V0:310(t,o)))". */ +static const char LAY_VIEW_CH[V_COUNT] = { 'p', 's', 't', 'o' }; + +static void lay_write(Ed* ed, int n, char* out, size_t cap) { + const LayNode* N = &ed->lay[n]; + size_t len = strlen(out); + if (len + 1 >= cap) return; + if (N->kind == LN_LEAF) { snprintf(out + len, cap - len, "%c", LAY_VIEW_CH[N->view]); return; } + snprintf(out + len, cap - len, "%c%d:%d(", N->kind == LN_HSPLIT ? 'H' : 'V', N->fix, (int)roundf(N->px)); + lay_write(ed, N->a, out, cap); + len = strlen(out); + snprintf(out + len, cap - len, ","); + lay_write(ed, N->b, out, cap); + len = strlen(out); + snprintf(out + len, cap - len, ")"); +} + +static int lay_read(Ed* ed, const char** p, int* seen) { + char c = **p; + for (int v = 0; v < V_COUNT; v++) { + if (c != LAY_VIEW_CH[v]) continue; + (*p)++; + if (*seen & (1 << v)) return -1; /* view repetida */ + *seen |= 1 << v; + return lay_node(ed, LN_LEAF, -1, -1, v, 0, 0); + } + if (c != 'H' && c != 'V') return -1; + (*p)++; + char* e; + long fix = strtol(*p, &e, 10); + if (e == *p || (fix != 0 && fix != 1) || *e != ':') return -1; + *p = e + 1; + float px = strtof(*p, &e); + if (e == *p || px <= 0 || *e != '(') return -1; + *p = e + 1; + int a = lay_read(ed, p, seen); + if (a < 0 || **p != ',') return -1; + (*p)++; + int b = lay_read(ed, p, seen); + if (b < 0 || **p != ')') return -1; + (*p)++; + return lay_node(ed, c == 'H' ? LN_HSPLIT : LN_VSPLIT, a, b, -1, (int)fix, px); +} + +/* Aplica um layout salvo; invalido (view faltando/repetida) = fica o atual */ +static bool lay_load_str(Ed* ed, const char* str) { + LayNode backup[LAY_MAX]; + int bn = ed->lay_n, broot = ed->lay_root; + memcpy(backup, ed->lay, sizeof(backup)); + ed->lay_n = 0; + int seen = 0; + const char* p = str; + int r = lay_read(ed, &p, &seen); + if (r < 0 || *p || seen != (1 << V_COUNT) - 1) { + memcpy(ed->lay, backup, sizeof(backup)); + ed->lay_n = bn; ed->lay_root = broot; + return false; + } + ed->lay_root = r; + return true; +} + +static void lay_settings_path(char* buf, size_t cap) { + const char* e = tb_environ_env_path(); + if (e[0]) snprintf(buf, cap, "%s", e); + else tb_environ_config_path(buf, cap); +} + +/* Grava o layout nas configuracoes (so quando mudou) */ +static void lay_save(Ed* ed) { + char str[256] = ""; + lay_write(ed, ed->lay_root, str, sizeof(str)); + if (!strcmp(tb_environ_get("editor.layout"), str)) return; + tb_environ_set("editor.layout", str); + char path[512]; + lay_settings_path(path, sizeof(path)); + if (!tb_environ_export_csv_meta(path, "arquivo_config", path)) { + snprintf(ed->hot_status, sizeof(ed->hot_status), "Não consegui salvar o layout: %.180s", + tb_environ_last_error()); + ed->hot_status_ok = false; + } +} + +/* Ao abrir: le o arquivo de configuracoes e aplica o layout salvo */ +static void lay_restore(Ed* ed) { + char path[512]; + lay_settings_path(path, sizeof(path)); + if (!tb_environ_has("editor.layout")) tb_environ_import_csv(path); + const char* ls = tb_environ_get("editor.layout"); + if (ls[0] && !lay_load_str(ed, ls)) { + snprintf(ed->hot_status, sizeof(ed->hot_status), "Layout salvo inválido; usando o padrão"); + ed->hot_status_ok = false; + } +} + +/* Tamanho minimo de uma subarvore na direcao horizontal ou vertical */ +static float lay_min(Ed* ed, int n, bool horiz) { + const LayNode* N = &ed->lay[n]; + if (N->kind == LN_LEAF) { + if (horiz) + return N->view == V_PALETTE ? CAT_W + 120.f : N->view == V_SCRIPTS ? 220.f : 160.f; + return N->view == V_STAGE ? STAGE_BAR_H + 60.f : N->view == V_SCRIPTS ? TAB_H + 120.f : 80.f; + } + float a = lay_min(ed, N->a, horiz), b = lay_min(ed, N->b, horiz); + return ((N->kind == LN_HSPLIT) == horiz) ? a + b : fmaxf(a, b); +} + +/* Tamanho do lado a de uma divisao com `total` px, respeitando os minimos */ +static float lay_side_a(Ed* ed, const LayNode* N, float total, float want_a) { + bool hz = N->kind == LN_HSPLIT; + float ma = lay_min(ed, N->a, hz), mb = lay_min(ed, N->b, hz); + if (total <= ma + mb) return roundf(total * ma / (ma + mb)); + if (want_a > total - mb) want_a = total - mb; + if (want_a < ma) want_a = ma; + return roundf(want_a); +} + +/* A subarvore tem alguma view na janela principal (nao destacada)? */ +static bool lay_attached(Ed* ed, int n) { + const LayNode* N = &ed->lay[n]; + if (N->kind == LN_LEAF) return !ed->vwin[N->view]; + return lay_attached(ed, N->a) || lay_attached(ed, N->b); +} + +static void lay_place(Ed* ed, int n, float x, float y, float w, float h) { + LayNode* N = &ed->lay[n]; + N->x = x; N->y = y; N->w = w; N->h = h; + N->pos = -1e9f; + if (N->kind != LN_LEAF) { + /* lado sem views na janela principal (todas destacadas): o outro ocupa tudo */ + if (!lay_attached(ed, N->a)) { lay_place(ed, N->b, x, y, w, h); return; } + if (!lay_attached(ed, N->b)) { lay_place(ed, N->a, x, y, w, h); return; } + } + if (N->kind == LN_LEAF) { + AreaRect* A = &ed->area[N->view]; + A->x = x; A->y = y; A->w = w; A->h = h; A->shown = !ed->vwin[N->view]; + return; + } + bool hz = N->kind == LN_HSPLIT; + float total = hz ? w : h; + float sa = lay_side_a(ed, N, total, N->fix == 0 ? N->px : total - N->px); + N->pos = (hz ? x : y) + sa; + if (hz) { lay_place(ed, N->a, x, y, sa, h); lay_place(ed, N->b, x + sa, y, w - sa, h); } + else { lay_place(ed, N->a, x, y, w, sa); lay_place(ed, N->b, x, y + sa, w, h - sa); } +} + +/* Abas destacadas -------------------------------------------------------- */ +static bool tab_detached(Ed* ed, int i) { + for (int k = 0; k < TABWIN_MAX; k++) if (ed->twin[k].win && ed->twin[k].tab == i) return true; + return false; +} + +/* A aba aparece na barra do contexto atual? (principal: as nao destacadas) */ +static bool tab_visible(Ed* ed, int i) { + if (ed->tabctx >= 0) return i == ed->twin[ed->tabctx].tab; + return !tab_detached(ed, i); +} + +static int tabs_visible_list(Ed* ed, int* out) { + int n = 0; + for (int i = 0; i < ed->tab_n; i++) if (tab_visible(ed, i)) out[n++] = i; + return n; +} + +static void tabwin_rect(Ed* ed, int k, AreaRect* A) { + A->x = ed->twin[k].geom[0] - ed->main_wx; + A->y = ed->twin[k].geom[1] - ed->main_wy; + A->w = ed->twin[k].geom[2]; + A->h = ed->twin[k].geom[3]; + A->shown = A->detached = true; +} + +static void lay_compute(Ed* ed) { + for (int v = 0; v < V_COUNT; v++) { ed->area[v].shown = false; ed->area[v].detached = false; } + if (ed->lay_n > 0 && lay_attached(ed, ed->lay_root)) + lay_place(ed, ed->lay_root, 0, MENU_H, WIN_W, WIN_H - MENU_H); + /* views destacadas: retangulo da janela delas, no espaco da principal */ + for (int v = 0; v < V_COUNT; v++) { + if (!ed->vwin[v]) continue; + AreaRect* A = &ed->area[v]; + A->x = ed->vgeom[v][0] - ed->main_wx; + A->y = ed->vgeom[v][1] - ed->main_wy; + A->w = ed->vgeom[v][2]; + A->h = ed->vgeom[v][3]; + A->shown = A->detached = true; + } + /* no contexto de uma aba destacada, "os scripts" sao a janela dela */ + ed->main_scripts = ed->area[V_SCRIPTS]; + if (ed->tabctx >= 0) tabwin_rect(ed, ed->tabctx, &ed->area[V_SCRIPTS]); +} + +typedef struct { int cur_tab, tabctx; } TabCtxSave; + +static void tabctx_enter(Ed* ed, int k, TabCtxSave* sv) { + sv->cur_tab = ed->cur_tab; + sv->tabctx = ed->tabctx; + ed->ctx_main_tab = ed->cur_tab; + ed->tabctx = k; + ed->cur_tab = ed->twin[k].tab; + lay_compute(ed); +} + +static void tabctx_leave(Ed* ed, const TabCtxSave* sv) { + ed->tabctx = sv->tabctx; + ed->cur_tab = sv->cur_tab; + lay_compute(ed); +} + +/* Contexto de scripts sob o ponto: k = janela de aba, -1 = principal, -2 = nenhum */ +static int ws_ctx_at(Ed* ed, float mx, float my) { + for (int k = 0; k < TABWIN_MAX; k++) { + if (!ed->twin[k].win) continue; + AreaRect A; + tabwin_rect(ed, k, &A); + if (in_rect(mx, my, A.x, A.y + TAB_H, A.w, A.h - TAB_H)) return k; + } + const AreaRect* M = &ed->main_scripts; + if (M->shown && in_rect(mx, my, M->x, M->y + TAB_H, M->w, M->h - TAB_H)) return -1; + return -2; +} + +/* View sob o ponto. Janelas podem se sobrepor na tela: a janela que tem o + mouse ganha; depois as areas da principal; por fim as destacadas. */ +static int view_at(Ed* ed, float mx, float my) { + int o = ed->mouse_owner; + /* mouse numa janela de aba: no contexto dela, e a area de scripts */ + if (o >= V_COUNT) o = (ed->tabctx >= 0 && o - V_COUNT == ed->tabctx) ? V_SCRIPTS : -1; + if (o >= 0 && o < V_COUNT && ed->area[o].shown && + in_rect(mx, my, ed->area[o].x, ed->area[o].y, ed->area[o].w, ed->area[o].h)) return o; + for (int pass = 0; pass < 2; pass++) + for (int v = 0; v < V_COUNT; v++) { + const AreaRect* A = &ed->area[v]; + if (A->shown && A->detached == (pass == 1) && in_rect(mx, my, A->x, A->y, A->w, A->h)) return v; + } + return -1; +} + +static bool in_ws(Ed* ed, float mx, float my) { + return AREA(V_SCRIPTS).shown && in_rect(mx, my, WS_X, WS_Y, WS_W, WS_H); +} + +#define SPLIT_GRAB 4.f +/* Divisao cuja borda esta sob o mouse (-1 = nenhuma) */ +static int split_at(Ed* ed, float mx, float my) { + for (int n = 0; n < ed->lay_n; n++) { + const LayNode* N = &ed->lay[n]; + if (N->kind == LN_HSPLIT && fabsf(mx - N->pos) <= SPLIT_GRAB && my >= N->y && my < N->y + N->h) + return n; + if (N->kind == LN_VSPLIT && fabsf(my - N->pos) <= SPLIT_GRAB && mx >= N->x && mx < N->x + N->w) + return n; + } + return -1; +} + +static void split_drag_to(Ed* ed, int n, float mx, float my) { + LayNode* N = &ed->lay[n]; + bool hz = N->kind == LN_HSPLIT; + float total = hz ? N->w : N->h; + float sa = lay_side_a(ed, N, total, hz ? mx - N->x : my - N->y); + N->px = N->fix == 0 ? sa : total - sa; +} + +static void lay_swap(Ed* ed, int va, int vb) { + int la = -1, lb = -1; + for (int n = 0; n < ed->lay_n; n++) { + if (ed->lay[n].kind != LN_LEAF) continue; + if (ed->lay[n].view == va) la = n; + if (ed->lay[n].view == vb) lb = n; + } + if (la < 0 || lb < 0) return; + ed->lay[la].view = vb; + ed->lay[lb].view = va; + lay_compute(ed); +} + +/* Alca do cabecalho de cada area (arrastar para trocar de lugar) */ +#define GRIP_S 18.f +static void grip_pos(Ed* ed, int v, float* gx, float* gy) { + const AreaRect* A = &ed->area[v]; + switch (v) { + case V_STAGE: *gx = A->x + A->w - 50 - GRIP_S - 8; *gy = A->y + (STAGE_BAR_H - GRIP_S) * 0.5f; break; + case V_OUTPUT: *gx = A->x + A->w - 8 - GRIP_S - 6; *gy = A->y + 6; break; + default: *gx = A->x + A->w - GRIP_S - 8; *gy = A->y + (TAB_H - GRIP_S) * 0.5f; break; + } +} + +static int grip_at(Ed* ed, float mx, float my) { + for (int v = 0; v < V_COUNT; v++) { + if (!ed->area[v].shown || (v == V_SCRIPTS && ed->tabctx >= 0)) continue; + float gx, gy; + grip_pos(ed, v, &gx, &gy); + if (in_rect(mx, my, gx, gy, GRIP_S, GRIP_S)) return v; + } + return -1; +} + +/* Botao destacar/recolher do cabecalho (o palco usa o da barra dele) */ +#define DETACH_S 26.f +static void detach_btn_pos(Ed* ed, int v, float* bx, float* by) { + float gx, gy; + grip_pos(ed, v, &gx, &gy); + *bx = gx - DETACH_S - 6; + *by = gy + GRIP_S * 0.5f - DETACH_S * 0.5f; +} + +static int detach_btn_at(Ed* ed, float mx, float my) { + for (int v = 0; v < V_COUNT; v++) { + if (v == V_STAGE || !ed->area[v].shown || (v == V_SCRIPTS && ed->tabctx >= 0)) continue; + float bx, by; + detach_btn_pos(ed, v, &bx, &by); + if (in_rect(mx, my, bx, by, DETACH_S, DETACH_S)) return v; + } + return -1; +} + +/* Icone: duas janelas (destacar) ou janela com o canto cheio (recolher) */ +static void draw_window_icon(TinyBlocks_RenderableBlock* rb, float x, float y, float s, bool detached, Col c) { + float k = s / 32.f; + if (detached) { + rb_stroke_rect(rb, x + 9*k, y + 7*k, 22*k, 18*k, 1.5f, c); + rb_fill_rect(rb, x + 12*k, y + 15*k, 10*k, 7*k, c); + } else { + rb_stroke_rect(rb, x + 9*k, y + 11*k, 15*k, 13*k, 1.5f, c); + rb_stroke_rect(rb, x + 16*k, y + 6*k, 15*k, 13*k, 1.5f, c); + } +} + +static void draw_detach_btn(Ed* ed, TinyBlocks_RenderableBlock* rb, int v) { + if (v == V_STAGE || !ed->area[v].shown) return; + float bx, by; + detach_btn_pos(ed, v, &bx, &by); + bool hov = in_rect(ed->mouse_x, ed->mouse_y, bx, by, DETACH_S, DETACH_S); + if (hov) rb_fill_rrect(rb, bx, by, DETACH_S, DETACH_S, 5, COL_HOVER); + draw_window_icon(rb, bx - 2, by, DETACH_S + 4, ed->area[v].detached, hov ? COL_MENU : COL_TEXT_DIM); +} + +static void draw_grip(Ed* ed, TinyBlocks_RenderableBlock* rb, int v) { + draw_detach_btn(ed, rb, v); + if (!ed->area[v].shown) return; + float gx, gy; + grip_pos(ed, v, &gx, &gy); + bool hov = ed->area_drag == v || in_rect(ed->mouse_x, ed->mouse_y, gx, gy, GRIP_S, GRIP_S); + if (hov) rb_fill_rrect(rb, gx - 2, gy - 2, GRIP_S + 4, GRIP_S + 4, 5, COL_HOVER); + Col c = hov ? COL_MENU : COL_TEXT_DIM; + for (int i = 0; i < 2; i++) + for (int j = 0; j < 3; j++) + rb_fill_circle(rb, gx + 6 + i * 6, gy + 3 + j * 6, 1.6f, c); +} + +/* Borda sob o mouse e alvo da troca de areas */ +static void render_areas_overlay(Ed* ed, TinyBlocks_RenderableBlock* rb) { + int sp = ed->split_drag >= 0 ? ed->split_drag : ed->split_hover; + if (sp >= 0 && ed->area_drag < 0) { + const LayNode* N = &ed->lay[sp]; + if (N->kind == LN_HSPLIT) rb_fill_rect(rb, N->pos - 1.5f, N->y, 3, N->h, COL_MENU); + else rb_fill_rect(rb, N->x, N->pos - 1.5f, N->w, 3, COL_MENU); + } + if (ed->area_drag < 0) return; + const AreaRect* S = &ed->area[ed->area_drag]; + rb_fill_rect(rb, S->x, S->y, S->w, S->h, COLA(0, 0, 0, 40)); + int t = ed->area_drop; + if (t >= 0 && t != ed->area_drag) { + const AreaRect* A = &ed->area[t]; + rb_fill_rect(rb, A->x, A->y, A->w, A->h, COLA(76, 151, 255, 60)); + rb_stroke_rect(rb, A->x + 1, A->y + 1, A->w - 2, A->h - 2, 2.f, COL_MENU); + char msg[64]; + snprintf(msg, sizeof(msg), "Trocar com %s", view_name(t)); + float w = tw(msg, FS_UI) + 24; + float cx = A->x + (A->w - w) * 0.5f, cy = A->y + A->h * 0.5f - 16; + rb_fill_rrect(rb, cx, cy, w, 32, 8, COL_MENU); + rb_text_c(rb, cx + 12, cy + 16, msg, COL_WHITE, FS_UI); + } + /* etiqueta da area levada, no mouse */ + const char* nm = view_name(ed->area_drag); + float w = tw(nm, FS_UI) + 20; + rb_fill_rrect(rb, ed->mouse_x + 12, ed->mouse_y + 10, w, 26, 6, COL_TEXT); + rb_text_c(rb, ed->mouse_x + 22, ed->mouse_y + 23, nm, COL_WHITE, FS_UI); +} + static float cat_item_h(Ed* ed) { - float h = ed->cat_n ? (WIN_H - PAL_Y) / (float)ed->cat_n : 58.f; + float h = ed->cat_n ? (PAL_B - PAL_Y - LIBMAN_BTN_H) / (float)ed->cat_n : 58.f; return h > 58.f ? 58.f : h; } @@ -1724,6 +2153,45 @@ void tab_doc_free(Tab* T) { img_sel_reset(T); } +/* Novo indice de uma aba depois de mover `from` para `to` */ +static int tab_moved_index(int o, int from, int to) { + if (o == from) return to; + if (from < to && o > from && o <= to) return o - 1; + if (from > to && o >= to && o < from) return o + 1; + return o; +} + +static Tab* tab_moved_ptr(Ed* ed, Tab* T, int from, int to) { + if (T < ed->tabs || T >= ed->tabs + ed->tab_n) return T; /* ex.: corpo de Meus Blocos */ + return &ed->tabs[tab_moved_index((int)(T - ed->tabs), from, to)]; +} + +/* Reordena as abas (arrastar na barra). Os scripts rodando continuam: os + ponteiros das threads e os indices guardados sao remapeados. */ +static void tab_move(Ed* ed, int from, int to) { + if (from == to || from < 0 || to < 0 || from >= ed->tab_n || to >= ed->tab_n) return; + Tab* tmp = malloc(sizeof(Tab)); + if (!tmp) return; + *tmp = ed->tabs[from]; + if (from < to) memmove(&ed->tabs[from], &ed->tabs[from + 1], (size_t)(to - from) * sizeof(Tab)); + else memmove(&ed->tabs[to + 1], &ed->tabs[to], (size_t)(from - to) * sizeof(Tab)); + ed->tabs[to] = *tmp; + free(tmp); + ed->cur_tab = tab_moved_index(ed->cur_tab, from, to); + for (int u = 0; u < ed->user_block_n; u++) + if (ed->user_blocks[u].tab_idx >= 0) + ed->user_blocks[u].tab_idx = tab_moved_index(ed->user_blocks[u].tab_idx, from, to); + for (int t = 0; t < ed->vm_n; t++) + for (int f = 0; f < ed->vm[t].sp; f++) + ed->vm[t].st[f].T = tab_moved_ptr(ed, ed->vm[t].st[f].T, from, to); + ed->live_tab = ed->live_tab ? tab_moved_ptr(ed, ed->live_tab, from, to) : NULL; + for (int k = 0; k < TABWIN_MAX; k++) + if (ed->twin[k].win) ed->twin[k].tab = tab_moved_index(ed->twin[k].tab, from, to); + if (ed->drag_tab >= 0) ed->drag_tab = tab_moved_index(ed->drag_tab, from, to); + ed->ctx_main_tab = tab_moved_index(ed->ctx_main_tab, from, to); + rt_cache_clear(ed); /* a chave do cache e o ponteiro da aba */ +} + static void tab_close(Ed* ed, int ti) { if (ed->tab_n <= 1 || ti < 0 || ti >= ed->tab_n) return; run_reset(ed); @@ -1736,6 +2204,8 @@ static void tab_close(Ed* ed, int ti) { int* t = &ed->user_blocks[u].tab_idx; if (*t == ti) *t = -1; else if (*t > ti) (*t)--; } + for (int k = 0; k < TABWIN_MAX; k++) + if (ed->twin[k].win && ed->twin[k].tab > ti) ed->twin[k].tab--; tab_select(ed, ed->cur_tab >= ed->tab_n ? ed->tab_n - 1 : ed->cur_tab > ti ? ed->cur_tab - 1 : ed->cur_tab); } @@ -1942,6 +2412,7 @@ static TbBlueprint* ed_to_blueprint(Ed* ed) { /* Descarta tudo do editor e reconstroi a partir da blueprint. */ static void blueprint_apply(Ed* ed, const TbBlueprint* bp) { + tabwins_close_all(ed); /* abas destacadas voltam antes de recriar as abas */ run_reset(ed); invalidate_types(ed); for (int u = 0; u < ed->user_block_n; u++) { @@ -2477,6 +2948,35 @@ static void render_menu(Ed* ed, TinyBlocks_RenderableBlock* rb) { menu_button(rb, EXP_BTN_X, EXP_BTN_W, "Exportar", (ed->ctx_menu_open && ed->ctx_export) || hit_export_btn(mx, my)); menu_button(rb, LIBM_BTN_X, LIBM_BTN_W, "Bibliotecas", ed->libman_open || hit_libman_btn(mx, my)); menu_button(rb, CFG_BTN_X, CFG_BTN_W, "Config", ed->settings_open || hit_settings_btn(ed, mx, my)); + /* views destacadas: um botao para cada (clicar recolhe de volta) */ + float cx = CFG_BTN_X - 10; + for (int v = V_COUNT - 1; v >= 0; v--) { + ed->chip_w[v] = 0; + if (!ed->vwin[v]) continue; + const char* nm = view_name(v); + float w = tw(nm, FS_UI) + 40; + cx -= w; + ed->chip_x[v] = cx; ed->chip_w[v] = w; + bool hov = in_rect(mx, my, cx, 7, w, MENU_H - 14); + rb_fill_rrect(rb, cx, 7, w, MENU_H - 14, 6, hov ? COL_MENU_DARK : COLA(255, 255, 255, 34)); + draw_window_icon(rb, cx + 2, 7 + (MENU_H - 14 - 22) * 0.5f, 22, true, COL_WHITE); + rb_text_c(rb, cx + 30, MENU_H * 0.5f, nm, COL_WHITE, FS_UI); + cx -= 8; + } + for (int k = TABWIN_MAX - 1; k >= 0; k--) { /* abas destacadas */ + TabWin* W = &ed->twin[k]; + W->chip_w = 0; + if (!W->win || W->tab < 0 || W->tab >= ed->tab_n) continue; + const char* nm = ed->tabs[W->tab].name; + float w = tw(nm, FS_UI) + 40; + cx -= w; + W->chip_x = cx; W->chip_w = w; + bool hov = in_rect(mx, my, cx, 7, w, MENU_H - 14); + rb_fill_rrect(rb, cx, 7, w, MENU_H - 14, 6, hov ? COL_MENU_DARK : COLA(255, 255, 255, 34)); + draw_window_icon(rb, cx + 2, 7 + (MENU_H - 14 - 22) * 0.5f, 22, true, COL_WHITE); + rb_text_c(rb, cx + 30, MENU_H * 0.5f, nm, COL_WHITE, FS_UI); + cx -= 8; + } if (ed->lib_hover || (active && ed->path_mode == PM_LIB)) rb_fill_rect(rb, LIB_BTN_X, 0, LIB_BTN_W, MENU_H, COL_MENU_DARK); @@ -2496,32 +2996,182 @@ static void render_menu(Ed* ed, TinyBlocks_RenderableBlock* rb) { rb_text_c(rb, bx + 10, MENU_H*0.5f, t, ed->path_input_buf[0] ? COL_TEXT : COL_TEXT_DIM, FS_UI); float cw = tw(ed->path_input_buf, FS_UI); rb_fill_rect(rb, bx + 11 + cw, MENU_H*0.5f - 8, 1.5f, 16, COL_TEXT); - } else if (ed->hot_status[0]) { - /* cabe entre "Carregar library=" e "Config"; se nao couber, mostra - o fim da mensagem (o fim de um caminho e o que importa) */ - float avail = CFG_BTN_X - 12 - (LIB_BTN_X + LIB_BTN_W + 10); - const char* s = ed->hot_status; - char buf[300]; - if (avail > 20 && tw(s, FS_SM) > avail) { - while (*s && tw(s, FS_SM) + tw("...", FS_SM) > avail) { - s++; - while ((*s & 0xC0) == 0x80) s++; - } - snprintf(buf, sizeof(buf), "...%s", s); - s = buf; - } - float w = tw(s, FS_SM); - rb_text_c(rb, CFG_BTN_X - 12 - w, MENU_H*0.5f, s, - ed->hot_status_ok ? COL_WHITE : COL_ERR_MENU, FS_SM); } } +/* == Notificacoes flutuantes (toasts) === + * Estilo EditorToaster do Godot: empilhadas no canto inferior direito da + * area de scripts, com barra de tempo; o mouse em cima pausa o tempo, o "x" + * fecha e a mesma mensagem repetida vira contador. */ +#define TOAST_W_MAX 420.f +#define TOAST_PAD 12.f +#define TOAST_LINE_H 17.f +#define TOAST_FADE 400.f + +static void toast_push(Ed* ed, const char* text, bool ok) { + for (int i = 0; i < ed->toast_n; i++) { + Toast* t = &ed->toasts[i]; + if (t->ok == ok && strcmp(t->text, text) == 0) { /* repetida: conta */ + t->count++; + t->left_ms = t->total_ms; + return; + } + } + if (ed->toast_n == TOAST_MAX) { /* cheia: sai a mais velha */ + memmove(&ed->toasts[0], &ed->toasts[1], (TOAST_MAX - 1) * sizeof(Toast)); + ed->toast_n--; + } + Toast* t = &ed->toasts[ed->toast_n++]; + memset(t, 0, sizeof(*t)); + scopy(t->text, sizeof(t->text), text); + t->ok = ok; + t->count = 1; + t->total_ms = t->left_ms = ok ? TOAST_INFO_MS : TOAST_ERR_MS; +} + +static void toast_remove(Ed* ed, int i) { + memmove(&ed->toasts[i], &ed->toasts[i + 1], (size_t)(ed->toast_n - i - 1) * sizeof(Toast)); + ed->toast_n--; +} + +static bool toast_hit(const Toast* t, float mx, float my) { + return t->w > 0 && in_rect(mx, my, t->x, t->y, t->w, t->h); +} + +/* Mensagem nova em hot_status vira toast (chamado no evento e no desenho, + para o aviso aparecer no mesmo quadro da acao) */ +static void toasts_take_status(Ed* ed) { + if (!ed->hot_status[0]) return; + toast_push(ed, ed->hot_status, ed->hot_status_ok); + ed->hot_status[0] = 0; +} + +/* Quadro: o tempo corre (pausa com o mouse em cima) e os vencidos saem */ +static void toasts_update(Ed* ed) { + toasts_take_status(ed); + unsigned now = now_ms(); + float dt = ed->toast_ms ? (float)(now - ed->toast_ms) : 0.f; + ed->toast_ms = now; + if (dt > 250.f) dt = 250.f; /* janela parada nao some com tudo */ + for (int i = ed->toast_n - 1; i >= 0; i--) { + Toast* t = &ed->toasts[i]; + if (toast_hit(t, ed->mouse_x, ed->mouse_y)) continue; + t->left_ms -= dt; + if (t->left_ms <= 0.f) toast_remove(ed, i); + } +} + +/* Quebra o texto em ate 4 linhas que caibam em maxw (corta em espaco ou '/') */ +static int toast_wrap(const char* s, float maxw, char lines[4][256]) { + int n = 0; + while (*s && n < 4) { + size_t len = strlen(s), cut = len; + if (tw(s, FS_UI) > maxw) { + char tmp[256]; + size_t best = 0; + for (size_t i = 1; i <= len && i < sizeof(tmp); i++) { + if ((s[i] & 0xC0) == 0x80) continue; /* meio de letra UTF-8 */ + memcpy(tmp, s, i); tmp[i] = 0; + if (tw(tmp, FS_UI) > maxw) break; + if (s[i] == ' ' || s[i - 1] == '/' || s[i] == 0) best = i; + cut = i; + } + if (best > 0 && n < 3) cut = best; + } + if (cut == 0) cut = 1; + if (n == 3 && s[cut]) { /* ultima linha: reticencias */ + size_t c = cut > 3 ? cut - 3 : cut; + while (c > 0 && (s[c] & 0xC0) == 0x80) c--; + snprintf(lines[n++], 256, "%.*s...", (int)c, s); + return n; + } + snprintf(lines[n++], 256, "%.*s", (int)cut, s); + s += cut; + while (*s == ' ') s++; + } + return n; +} + +static void render_toasts(Ed* ed, TinyBlocks_RenderableBlock* rb) { + toasts_take_status(ed); + bool in_ws_area = AREA(V_SCRIPTS).shown; /* falso se os scripts estao em outra janela */ + float bx = in_ws_area ? WS_X : 0.f, bw = in_ws_area ? WS_W : (float)WIN_W; + float right = bx + bw - 16.f, y = in_ws_area ? WS_Y + WS_H - 16.f : WIN_H - 16.f; + float maxw = fminf(TOAST_W_MAX, bw - 32.f); + for (int i = ed->toast_n - 1; i >= 0; i--) { /* mais nova embaixo */ + Toast* t = &ed->toasts[i]; + char text[300]; + if (t->count > 1) snprintf(text, sizeof(text), "%s (x%d)", t->text, t->count); + else scopy(text, sizeof(text), t->text); + char lines[4][256]; + int nl = toast_wrap(text, maxw - 2*TOAST_PAD - 26.f, lines); + float tw_max = 0; + for (int l = 0; l < nl; l++) tw_max = fmaxf(tw_max, tw(lines[l], FS_UI)); + float w = fmaxf(220.f, tw_max + 2*TOAST_PAD + 30.f); + if (w > maxw) w = maxw; + float h = nl * TOAST_LINE_H + 2*TOAST_PAD + 4.f; + y -= h; + t->x = right - w; t->y = y; t->w = w; t->h = h; + + float a = t->left_ms < TOAST_FADE ? fmaxf(0.f, t->left_ms / TOAST_FADE) : 1.f; + Col bar = t->ok ? COL_MENU : COL_STOP; + Col bg = COL_PANEL, txt = COL_TEXT, dim = COL_TEXT_DIM, sh = COLA(0, 0, 0, 50), bd = COL_BORDER; + bar.a *= a; bg.a *= a; txt.a *= a; dim.a *= a; sh.a *= a; bd.a *= a; + bool hov = toast_hit(t, ed->mouse_x, ed->mouse_y); + + rb_fill_rrect(rb, t->x + 2, t->y + 3, w, h, 8, sh); + rb_fill_rrect(rb, t->x, t->y, w, h, 8, bd); + rb_fill_rrect(rb, t->x + 1, t->y + 1, w - 2, h - 2, 7, bg); + rb_fill_rrect(rb, t->x + 1, t->y + 1, 5, h - 2, 2.5f, bar); /* faixa da cor */ + for (int l = 0; l < nl; l++) + rb_text_c(rb, t->x + TOAST_PAD + 4, t->y + TOAST_PAD + 2 + TOAST_LINE_H * (l + 0.5f), + lines[l], txt, FS_UI); + /* fechar */ + float cx = t->x + w - 16.f, cy = t->y + 16.f; + bool xh = in_rect(ed->mouse_x, ed->mouse_y, cx - 9, cy - 9, 18, 18); + if (xh) { Col hc = COL_HOVER; hc.a *= a; rb_fill_circle(rb, cx, cy, 9, hc); } + rb_line(rb, cx - 4, cy - 4, cx + 4, cy + 4, 1.6f, xh ? txt : dim); + rb_line(rb, cx + 4, cy - 4, cx - 4, cy + 4, 1.6f, xh ? txt : dim); + /* temporizador: barra que encolhe (para com o mouse em cima) */ + float k = t->total_ms > 0 ? fmaxf(0.f, t->left_ms / t->total_ms) : 0.f; + Col tb = bar; + if (hov) tb.a *= 0.45f; + rb_fill_rect(rb, t->x + 8, t->y + h - 5, (w - 16) * k, 2.5f, tb); + y -= 8.f; + } +} + +/* Clique no "x" de um toast fecha; o resto do toast deixa o clique passar + para o que esta embaixo (o aviso nao atrapalha arrastar blocos) */ +static bool toasts_click(Ed* ed, float mx, float my) { + for (int i = 0; i < ed->toast_n; i++) { + Toast* t = &ed->toasts[i]; + if (!toast_hit(t, mx, my)) continue; + float cx = t->x + t->w - 16.f, cy = t->y + 16.f; + if (in_rect(mx, my, cx - 11, cy - 11, 22, 22)) { toast_remove(ed, i); return true; } + return false; + } + return false; +} + static void render_tab_bar(Ed* ed, TinyBlocks_RenderableBlock* rb) { - float y0 = MENU_H, wbar = WIN_W - STAGE_W; - rb_fill_rect(rb, 0, y0, wbar, TAB_H, COL_UI_BG); - for (int i = 0; i < ed->tab_n; i++) { - float tx = 8 + i*TAB_W; - if (tx + TAB_W > wbar - PLUS_W) break; + if (!AREA(V_SCRIPTS).shown) return; + float y0 = AREA(V_SCRIPTS).y, x0 = WS_X, wbar = WS_W - GRIP_S - DETACH_S - 18; /* sobra alca e botao */ + rb_fill_rect(rb, x0, y0, WS_W, TAB_H, COL_UI_BG); + int dragged = ed->tab_drag ? ed->tab_press : -1; + int vis[MAX_TABS], vn = tabs_visible_list(ed, vis); + for (int pass = 0; pass < 2; pass++) /* 2a passada: a aba arrastada, por cima */ + for (int sl = 0; sl < vn; sl++) { + int i = vis[sl]; + if ((pass == 1) != (i == dragged)) continue; + float tx = WS_X + 8 + sl*TAB_W; + if (pass == 0 && tx + TAB_W > x0 + wbar - PLUS_W) break; + if (pass == 1) { + tx = ed->mouse_x - ed->tab_grab_dx; + if (tx < x0 + 4) tx = x0 + 4; + if (tx > x0 + wbar - TAB_W) tx = x0 + wbar - TAB_W; + rb_fill_rrect(rb, tx + 2, y0 + 8, TAB_W - 4, TAB_H - 6, 8, COLA(0, 0, 0, 40)); + } bool cur = i == ed->cur_tab; Col bg = cur ? COL_PANEL : COL_TAB_OFF; rb_fill_rrect(rb, tx, y0+6, TAB_W-4, TAB_H-6, 8, bg); @@ -2542,35 +3192,46 @@ static void render_tab_bar(Ed* ed, TinyBlocks_RenderableBlock* rb) { lx = tx + 24; } rb_text_c(rb, lx, cy, ed->tabs[i].name, cur ? COL_MENU : COL_TEXT, FS_UI); - if (ed->tab_n > 1) rb_text_c(rb, tx+TAB_W-22, cy, "=", COL_TEXT_DIM, FS_UI); + if (ed->tab_n > 1 && ed->tabctx < 0) rb_text_c(rb, tx+TAB_W-22, cy, "=", COL_TEXT_DIM, FS_UI); } - float px = 8 + ed->tab_n*TAB_W; - if (px + PLUS_W <= wbar && ed->tab_n < MAX_TABS) { + float px = WS_X + 8 + vn*TAB_W; + if (ed->tabctx < 0 && px + PLUS_W <= x0 + wbar && ed->tab_n < MAX_TABS) { float pcy = y0 + 6 + (TAB_H-6)*0.5f; if (ed->plus_menu_open) rb_fill_circle(rb, px+13, pcy, 12, COL_HOVER); rb_text_c(rb, px+8, pcy, "+", ed->plus_menu_open ? COL_MENU : COL_TEXT, 18); } + if (ed->tabctx < 0) draw_grip(ed, rb, V_SCRIPTS); /* na janela de uma aba nao ha area para mover */ } static void render_categories(Ed* ed, TinyBlocks_RenderableBlock* rb) { - rb_fill_rect(rb, 0, PAL_Y, CAT_W, WIN_H-PAL_Y, COL_PANEL); - rb_line(rb, CAT_W-1, PAL_Y, CAT_W-1, WIN_H, 1.f, COL_BORDER); + if (!AREA(V_PALETTE).shown) return; + /* cabecalho da paleta (alca para trocar de lugar) */ + rb_fill_rect(rb, PAL_X, AREA(V_PALETTE).y, AREA(V_PALETTE).w, TAB_H, COL_UI_BG); + rb_text_c(rb, PAL_X + 14, AREA(V_PALETTE).y + TAB_H * 0.5f, "Blocos", COL_TEXT_DIM, FS_UI); + draw_grip(ed, rb, V_PALETTE); + + rb_fill_rect(rb, PAL_X, PAL_Y, CAT_W, PAL_B-PAL_Y, COL_PANEL); + rb_line(rb, FLY_X-1, PAL_Y, FLY_X-1, PAL_B, 1.f, COL_BORDER); float ih = cat_item_h(ed); int cur = current_cat(ed); + float mid = PAL_X + CAT_W*0.5f; for (int c = 0; c < ed->cat_n; c++) { float iy = PAL_Y + c*ih; - if (c == cur) rb_fill_rect(rb, 0, iy, CAT_W-1, ih, COL_UI_BG); + if (c == cur) rb_fill_rect(rb, PAL_X, iy, CAT_W-1, ih, COL_UI_BG); + /* compacta: circulo e rotulo menores quando a coluna aperta */ + float k = ih >= 48.f ? 1.f : ih / 48.f; + float r = 10.f * (k < 0.6f ? 0.6f : k), fs = ih >= 40.f ? 10.f : 9.f; float cy = iy + ih*0.36f; - rb_fill_circle(rb, CAT_W*0.5f, cy, 10, ed->cats[c].dark); - rb_fill_circle(rb, CAT_W*0.5f, cy, 9, ed->cats[c].col); - float w = tw(ed->cats[c].name, 10); - rb_text_c(rb, CAT_W*0.5f - w*0.5f, iy + ih*0.76f, ed->cats[c].name, COL_TEXT, 10); + rb_fill_circle(rb, mid, cy, r, ed->cats[c].dark); + rb_fill_circle(rb, mid, cy, r - 1, ed->cats[c].col); + float w = tw(ed->cats[c].name, fs); + rb_text_c(rb, mid - w*0.5f, iy + ih*0.78f, ed->cats[c].name, COL_TEXT, fs); } /* Botao de buscar/adicionar library, no fim do painel (como o Scratch) */ - float by = WIN_H - LIBMAN_BTN_H; - bool hov = (ed->mouse_x < CAT_W && ed->mouse_y >= by && ed->mouse_y < WIN_H); - rb_fill_rect(rb, 0, by, CAT_W-1, LIBMAN_BTN_H, hov ? COL_LIBBTN_DARK : COL_LIBBTN); - float cx = CAT_W*0.5f, cy = by + LIBMAN_BTN_H*0.5f; + float by = PAL_B - LIBMAN_BTN_H; + bool hov = hit_libman_foot(ed, ed->mouse_x, ed->mouse_y); + rb_fill_rect(rb, PAL_X, by, CAT_W-1, LIBMAN_BTN_H, hov ? COL_LIBBTN_DARK : COL_LIBBTN); + float cx = mid, cy = by + LIBMAN_BTN_H*0.5f; for (int i = 0; i < 3; i++) /* livrinhos */ rb_fill_rect(rb, cx-14, cy-6 + i*5, 16, 3, COL_WHITE); rb_fill_rect(rb, cx+5, cy-6, 12, 3, COL_WHITE); /* "+" no canto */ @@ -2578,26 +3239,27 @@ static void render_categories(Ed* ed, TinyBlocks_RenderableBlock* rb) { } static void render_flyout(Ed* ed, TinyBlocks_RenderableBlock* rb) { - rb_fill_rect(rb, CAT_W, PAL_Y, FLY_W, WIN_H-PAL_Y, COL_FLY); - rb_line(rb, PALETTE_W-1, PAL_Y, PALETTE_W-1, WIN_H, 1.f, COL_BORDER); - clip_set(ed, rb, CAT_W, PAL_Y, FLY_W-1, WIN_H-PAL_Y); + if (!AREA(V_PALETTE).shown) return; + rb_fill_rect(rb, FLY_X, PAL_Y, FLY_R - FLY_X, PAL_B-PAL_Y, COL_FLY); + rb_line(rb, FLY_R-1, PAL_Y, FLY_R-1, PAL_B, 1.f, COL_BORDER); + clip_set(ed, rb, FLY_X, PAL_Y, FLY_R - FLY_X - 1, PAL_B-PAL_Y); float oy = PAL_Y - ed->fly_scroll; for (int i = 0; i < ed->fly_n; i++) { FlyItem* it = &ed->fly_items[i]; float iy = it->y + oy; - if (iy + it->h < PAL_Y || iy > WIN_H) continue; + if (iy + it->h < PAL_Y || iy > PAL_B) continue; switch (it->kind) { case FI_HEADER: - rb_text_c(rb, CAT_W + FLY_PAD, iy + it->h*0.55f, ed->cats[it->cat].name, COL_TEXT, 14); + rb_text_c(rb, FLY_X + FLY_PAD, iy + it->h*0.55f, ed->cats[it->cat].name, COL_TEXT, 14); break; case FI_BUTTON: - rb_fill_rrect(rb, CAT_W + FLY_PAD, iy+4, FLY_BTN_W, 30, 6, COL_BORDER); - rb_fill_rrect(rb, CAT_W + FLY_PAD + 1, iy+5, FLY_BTN_W-2, 28, 5, COL_PANEL); - rb_text_c(rb, CAT_W + FLY_PAD + (FLY_BTN_W - tw("Criar um Bloco", FS_UI))*0.5f, + rb_fill_rrect(rb, FLY_X + FLY_PAD, iy+4, FLY_BTN_W, 30, 6, COL_BORDER); + rb_fill_rrect(rb, FLY_X + FLY_PAD + 1, iy+5, FLY_BTN_W-2, 28, 5, COL_PANEL); + rb_text_c(rb, FLY_X + FLY_PAD + (FLY_BTN_W - tw("Criar um Bloco", FS_UI))*0.5f, iy + 19, "Criar um Bloco", COL_TEXT, FS_UI); break; case FI_BLOCK: - render_block(ed, rb, &ed->fly, it->bi, CAT_W, oy); + render_block(ed, rb, &ed->fly, it->bi, FLY_X, oy); break; } } @@ -2816,6 +3478,7 @@ void code_rehighlight(Tab* T) { p = e + 4; continue; } if (!strncmp(p, "", 4)) { p += 4; continue; } + if (!strncmp(p, "", 7)) { pend_start = -1; break; } /* fim da marcacao */ if (!strncmp(p, "'); p = gt ? gt + 1 : p + 5; @@ -3048,8 +3711,9 @@ bool code_text(Ed* ed, const char* typed) { /* A aba de imagem vive em libraries/tinyblocks-editor-image (bundle do editor). */ /* -- Menu do botao "+" -------------------------------------------------- */ static void plus_menu_pos(Ed* ed, float* px, float* py) { - *px = 8 + ed->tab_n * TAB_W; - *py = MENU_H + TAB_H - 2; + int vis[MAX_TABS]; + *px = WS_X + 8 + tabs_visible_list(ed, vis) * TAB_W; + *py = AREA(V_SCRIPTS).y + TAB_H - 2; } void render_plus_menu(Ed* ed, TinyBlocks_RenderableBlock* rb) { @@ -3246,14 +3910,11 @@ static void render_comp_panel(Ed* ed, TinyBlocks_RenderableBlock* rb) { } /* Altura da área do palco no painel (4:3 embutido; faixa curta se destacado) */ -static float stage_panel_h(Ed* ed) { - if (!ed->stage) return 0.f; - return ed->stage_win ? 40.f : (STAGE_W - 16) * 0.75f; -} - static void render_stage(Ed* ed, TinyBlocks_RenderableBlock* rb) { - float sx = WIN_W - STAGE_W, sy = MENU_H; - rb_fill_rect(rb, sx, sy, STAGE_W, WIN_H - sy, COL_UI_BG); + AreaRect A = AREA(V_STAGE); + if (!A.shown) return; + float sx = A.x, sy = A.y; + rb_fill_rect(rb, sx, sy, A.w, A.h, COL_UI_BG); /* Bandeira verde */ float fx = sx + 10, fy = sy + 6; @@ -3266,41 +3927,36 @@ static void render_stage(Ed* ed, TinyBlocks_RenderableBlock* rb) { draw_hex(rb, tx+10, fy+6, 20, 20, COL_STOP_DARK); rb_fill_circle(rb, tx+20, fy+16, 9, COL_STOP); rb_text_c(rb, sx + 110, sy + STAGE_BAR_H*0.5f, "Palco", COL_TEXT_DIM, FS_UI); + draw_grip(ed, rb, V_STAGE); /* Destacar / recolher o palco */ if (ed->stage) { - float dx = sx + STAGE_W - 50; + float dx = sx + A.w - 50; if (ed->detach_hover) rb_fill_rrect(rb, dx, fy, 40, 32, 6, COL_HOVER); - if (ed->stage_win) { - rb_stroke_rect(rb, dx+9, fy+7, 22, 18, 1.5f, COL_TEXT); - rb_fill_rect(rb, dx+12, fy+15, 10, 7, COL_TEXT); - } else { - rb_stroke_rect(rb, dx+9, fy+11, 15, 13, 1.5f, COL_TEXT); - rb_stroke_rect(rb, dx+16, fy+6, 15, 13, 1.5f, COL_TEXT); - } + draw_window_icon(rb, dx, fy, 32, A.detached, COL_TEXT); } - float bx = sx + 8, by = sy + STAGE_BAR_H, bw = STAGE_W - 16; - float ph = stage_panel_h(ed); - if (ph > 0) { + float bx = sx + 8, by = sy + STAGE_BAR_H, bw = A.w - 16; + float ph = A.h - STAGE_BAR_H - 8; + if (ed->stage && ph > 8) { rb_fill_rrect(rb, bx, by, bw, ph, 8, COL_BORDER); - if (ed->stage_win) { - rb_fill_rrect(rb, bx+1, by+1, bw-2, ph-2, 7, COL_PANEL); - const char* msg = "Palco aberto em outra janela"; - rb_text_c(rb, bx + (bw - tw(msg, FS_UI))*0.5f, by + ph*0.5f, msg, COL_TEXT_DIM, FS_UI); - } else { - TinyBlocks_RenderableBlock* sub = NULL; - tb_stage_set_view(bw-2, ph-2); - clip_set(ed, rb, bx+1, by+1, bw-2, ph-2); - if (ed->stage->type->on_draw(ed->stage, ed->rt, &sub) && sub) { - tb_draw_merge_offset(rb, sub, bx+1, by+1); - tb_renderable_release(sub); - } - clip_clear(ed, rb); + TinyBlocks_RenderableBlock* sub = NULL; + tb_stage_set_view(bw-2, ph-2); + clip_set(ed, rb, bx+1, by+1, bw-2, ph-2); + if (ed->stage->type->on_draw(ed->stage, ed->rt, &sub) && sub) { + tb_draw_merge_offset(rb, sub, bx+1, by+1); + tb_renderable_release(sub); } - by += ph + 8; + clip_clear(ed, rb); } +} - float bh = WIN_H - by - 8; +/* Saida: monitores de variaveis + console (texto dos blocos "escreva") */ +static void render_output(Ed* ed, TinyBlocks_RenderableBlock* rb) { + AreaRect A = AREA(V_OUTPUT); + if (!A.shown) return; + rb_fill_rect(rb, A.x, A.y, A.w, A.h, COL_UI_BG); + float bx = A.x + 8, by = A.y, bw = A.w - 16; + float bh = A.h - 8; rb_fill_rrect(rb, bx, by, bw, bh, 8, COL_BORDER); rb_fill_rrect(rb, bx+1, by+1, bw-2, bh-2, 7, COL_PANEL); clip_set(ed, rb, bx+2, by+2, bw-4, bh-4); @@ -3342,6 +3998,7 @@ static void render_stage(Ed* ed, TinyBlocks_RenderableBlock* rb) { if (*p == '\n') p++; } clip_clear(ed, rb); + draw_grip(ed, rb, V_OUTPUT); } #define CTX_ITEM_H 30 @@ -3406,7 +4063,8 @@ static void libman_close(Ed* ed) { } bool hit_libman_foot(Ed* ed, float mx, float my) { - return mx < CAT_W && my >= WIN_H - LIBMAN_BTN_H; + return AREA(V_PALETTE).shown && mx >= PAL_X && mx < FLY_X && + my >= PAL_B - LIBMAN_BTN_H && my < PAL_B; } void libman_show(Ed* ed) { @@ -3785,10 +4443,6 @@ void settings_render(Ed* ed, TinyBlocks_RenderableBlock* rb) { if (n == 0 && !ed->settings_new_key) rb_text_c(rb, ST_MARGIN, ST_LIST_Y + 24, "Nenhuma configuracao. Use \"+ Nova\".", COL_TEXT_DIM, FS_UI); - - if (ed->hot_status[0]) - rb_text_c(rb, ST_MARGIN, WIN_H - 22, ed->hot_status, - ed->hot_status_ok ? COL_TEXT_DIM : COL_ERR_MENU, FS_SM); } void settings_click(Ed* ed, float mx, float my) { @@ -4047,10 +4701,89 @@ static const char* ev_text(TinyBlocks_Block* evb, int idx) { return (v->kind==TB_VALUE_TEXT && v->as.text) ? v->as.text : ""; } -static bool hit_flag(Ed* ed, float mx, float my) { return in_rect(mx, my, WIN_W-STAGE_W+10, MENU_H+6, 40, 32); } -static bool hit_stop(Ed* ed, float mx, float my) { return in_rect(mx, my, WIN_W-STAGE_W+56, MENU_H+6, 40, 32); } +/* Como ev_int, mas `def` quando a saida nao foi preenchida (ex.: harness) */ +static int64_t ev_int_def(TinyBlocks_Block* evb, int idx, int64_t def) { + if (!evb || idx<0 || (uint32_t)idx>=evb->output_count) return def; + TinyBlocks_Value* v=&evb->outputs[idx]; + return v->kind==TB_VALUE_INTEGER ? v->as.integer : def; +} + +static const TinyBlocks_JsonValue* ev_json(TinyBlocks_Block* evb, int idx) { + if (!evb || idx<0 || (uint32_t)idx>=evb->output_count) return NULL; + TinyBlocks_Value* v=&evb->outputs[idx]; + return (v->kind==TB_VALUE_JSON && v->as.json && tb_json_kind(v->as.json)==TB_JSON_ARRAY) ? v->as.json : NULL; +} + +static double json_num_at(const TinyBlocks_JsonValue* arr, uint32_t i) { + TinyBlocks_JsonValue* n = tb_json_array_get(arr, i); + double d = tb_json_as_number(n, 0.0); + if (n) tb_json_release(n); + return d; +} + +static void feed_keys(TinyBlocks_Block* evb) { + const TinyBlocks_JsonValue* keys = ev_json(evb, GFX_IN_KEYS_HELD); + for (uint32_t i = 0; keys && i < tb_json_array_length(keys); i++) + tb_input_set_key((int)json_num_at(keys, i), true); + int k = (int)ev_int(evb, GFX_IN_KEY); + if (k > 0 && !ev_int(evb, GFX_IN_KEY_REPEAT)) tb_input_key_pressed(k); +} + +/* Alimenta o estado de entrada do core (blocos de Sensores) a partir da + janela onde o palco esta: no painel do editor ou destacado na janela + propria. Pontos vao em px da vista do palco; o core converte. */ +static void input_feed(Ed* ed, TinyBlocks_Block* evb) { + TinyBlocks_Block* src = evb; + float ox = AREA(V_STAGE).x + 8 + 1, oy = AREA(V_STAGE).y + STAGE_BAR_H + 1; /* vista no painel */ + if (ed->vwin_in[V_STAGE]) { src = ed->vwin_in[V_STAGE]; ox = 8 + 1; oy = STAGE_BAR_H + 1; } + + tb_input_begin_frame(); + float vx = (float)ev_real(src, GFX_IN_MOUSE_X) - ox; + float vy = (float)ev_real(src, GFX_IN_MOUSE_Y) - oy; + float sx, sy; + bool over = tb_stage_view_to_stage(vx, vy, &sx, &sy); + /* como no Scratch: apertar o mouse so conta sobre o palco */ + tb_input_set_mouse(vx, vy, over && ev_int(src, GFX_IN_MOUSE_L_HELD), + over && ev_int(src, GFX_IN_MOUSE_R_HELD)); + if (over) tb_input_add_wheel((float)ev_real(src, GFX_IN_SCROLL_DY)); + + tb_input_clear_keys(); + feed_keys(evb); + if (src != evb) feed_keys(src); + + const TinyBlocks_JsonValue* tj = ev_json(src, GFX_IN_TOUCHES); + float tx[TB_INPUT_MAX_TOUCHES], ty[TB_INPUT_MAX_TOUCHES]; + int tn = 0; + for (uint32_t i = 0; tj && i < tb_json_array_length(tj) && tn < TB_INPUT_MAX_TOUCHES; i++) { + TinyBlocks_JsonValue* p = tb_json_array_get(tj, i); + if (p && tb_json_kind(p) == TB_JSON_ARRAY && tb_json_array_length(p) >= 2) { + tx[tn] = (float)json_num_at(p, 0) - ox; + ty[tn] = (float)json_num_at(p, 1) - oy; + tn++; + } + if (p) tb_json_release(p); + } + tb_input_set_touches(tn, tx, ty); + + const TinyBlocks_JsonValue* a = ev_json(evb, GFX_IN_ACCEL); + bool ha = a && tb_json_array_length(a) >= 3; + tb_input_set_accel(ha, ha ? (float)json_num_at(a, 0) : 0, ha ? (float)json_num_at(a, 1) : 0, + ha ? (float)json_num_at(a, 2) : 0); + const TinyBlocks_JsonValue* g = ev_json(evb, GFX_IN_GYRO); + bool hg = g && tb_json_array_length(g) >= 3; + tb_input_set_gyro(hg, hg ? (float)json_num_at(g, 0) : 0, hg ? (float)json_num_at(g, 1) : 0, + hg ? (float)json_num_at(g, 2) : 0); +} + +static bool hit_flag(Ed* ed, float mx, float my) { + return AREA(V_STAGE).shown && in_rect(mx, my, AREA(V_STAGE).x + 10, AREA(V_STAGE).y + 6, 40, 32); +} +static bool hit_stop(Ed* ed, float mx, float my) { + return AREA(V_STAGE).shown && in_rect(mx, my, AREA(V_STAGE).x + 56, AREA(V_STAGE).y + 6, 40, 32); +} static bool hit_detach(Ed* ed, float mx, float my) { - return ed->stage && in_rect(mx, my, WIN_W-50, MENU_H+6, 40, 32); + return ed->stage && AREA(V_STAGE).shown && + in_rect(mx, my, AREA(V_STAGE).x + AREA(V_STAGE).w - 50, AREA(V_STAGE).y + 6, 40, 32); } static bool hit_lib_btn(float mx, float my) { return in_rect(mx, my, LIB_BTN_X, 0, LIB_BTN_W, MENU_H); } static bool hit_open_btn(float mx, float my) { return in_rect(mx, my, OPEN_BTN_X, 0, OPEN_BTN_W, MENU_H); } @@ -4075,7 +4808,7 @@ TB_ED_API void start_path(Ed* ed, int mode, const char* def) { } static int hit_fly(Ed* ed, float mx, float my) { - float fx = mx - CAT_W, fy = my - PAL_Y + ed->fly_scroll; + float fx = mx - FLY_X, fy = my - PAL_Y + ed->fly_scroll; for (int i = 0; i < ed->fly_n; i++) { FlyItem* it = &ed->fly_items[i]; if (it->kind == FI_BUTTON && in_rect(fx, fy, FLY_PAD, it->y+4, FLY_BTN_W, 30)) return i; @@ -4094,7 +4827,7 @@ static void spawn_from_fly(Ed* ed, int item, float mx, float my) { return; } top_add(&CT, ni); - float sx = F->ws[src].ax + CAT_W, sy = F->ws[src].ay + PAL_Y - ed->fly_scroll; + float sx = F->ws[src].ax + FLY_X, sy = F->ws[src].ay + PAL_Y - ed->fly_scroll; CT.ws[ni].x = sx - WS_X + CT.ws_sx; CT.ws[ni].y = sy - WS_Y + CT.ws_sy; ed->drag_bi = ni; @@ -4106,36 +4839,161 @@ static void spawn_from_fly(Ed* ed, int item, float mx, float my) { } /* Recolhe o palco para o painel (fecha a janela própria, se houver) */ -static void stage_attach(Ed* ed) { - if (ed->stage) tb_block_set_default(ed->stage, 0, tb_value_none()); - if (ed->stage_win) { tb_block_destroy(ed->stage_win, ed->rt); ed->stage_win = NULL; } - if (ed->stage_in) { tb_block_destroy(ed->stage_in, ed->rt); ed->stage_in = NULL; } +/* Recolhe a view destacada de volta para o seu lugar na janela principal. + Nunca chamar de dentro da cena da propria janela: use attach_request. */ +static void attach_view(Ed* ed, int v) { + if (!ed->vwin[v]) return; + TinyBlocks_Block* w = ed->vwin[v]; + TinyBlocks_Block* sc = ed->vwin_scene[v]; + TinyBlocks_Block* in = ed->vwin_in[v]; + ed->vwin[v] = ed->vwin_scene[v] = ed->vwin_in[v] = NULL; + tb_block_destroy(w, ed->rt); + if (sc) tb_block_destroy(sc, ed->rt); + if (in) tb_block_destroy(in, ed->rt); + if (ed->capture_view == v) ed->capture_view = -2; + if (ed->mouse_owner == v) ed->mouse_owner = -1; + lay_compute(ed); } -/* Destaca o palco: ele vira a cena de um Graphics.Window próprio */ -static void stage_detach(Ed* ed) { - TinyBlocks_TypeBlock* t_win = tb_type_block_find(ed->rt, "Graphics.Window"); - TinyBlocks_TypeBlock* t_in = tb_type_block_find(ed->rt, "Graphics.Input"); - if (!ed->stage || ed->stage_win || !t_win || !t_in) return; - ed->stage_in = tb_block_create(ed->rt, t_in); - ed->stage_win = tb_block_create(ed->rt, t_win); - if (ed->stage_in && ed->stage_win) { - TinyBlocks_Value title = tb_value_text("Palco = TinyBlocks"); - tb_block_set_default(ed->stage_win, 0, title); /* set_default clona */ - tb_value_free(&title); - tb_block_set_default(ed->stage_win, 1, tb_value_integer(480)); - tb_block_set_default(ed->stage_win, 2, tb_value_integer(360)); - tb_block_set_default(ed->stage_win, 3, tb_value_block(ed->stage)); - tb_block_set_default(ed->stage_win, 4, tb_value_block(ed->stage_in)); - tb_block_set_default(ed->stage_win, 5, tb_value_integer(0)); /* fechar não encerra o editor */ - tb_block_set_default(ed->stage, 0, tb_value_block(ed->stage_in)); - tb_block_eval(ed->stage_win, ed->rt); - } - if (!tb_graphics_window_is_open(ed->stage_win)) { - stage_attach(ed); - snprintf(ed->hot_status, sizeof(ed->hot_status), "Não foi possível abrir a janela do palco"); +static void attach_request(Ed* ed, int v) { + if (v >= 0 && v < V_COUNT && ed->vwin[v]) ed->attach_pending[v] = true; +} + +/* Destaca a view numa janela propria (Graphics.Window + cena Editor.Area) */ +static void detach_view(Ed* ed, int v) { + if (v < 0 || v >= V_COUNT || ed->vwin[v]) return; + int attached = 0; + for (int k = 0; k < V_COUNT; k++) attached += !ed->vwin[k]; + if (attached <= 1) { + snprintf(ed->hot_status, sizeof(ed->hot_status), "A janela principal precisa de pelo menos uma área"); ed->hot_status_ok = false; + return; } + TinyBlocks_TypeBlock* t_win = tb_type_block_find(ed->rt, "Graphics.Window"); + TinyBlocks_TypeBlock* t_in = tb_type_block_find(ed->rt, "Graphics.Input"); + TinyBlocks_TypeBlock* t_area = tb_type_block_find(ed->rt, "Editor.Area"); + if (!t_win || !t_in || !t_area) return; + AreaRect A = AREA(v); + float w = A.w < 240 ? 240 : A.w, h = A.h < 160 ? 160 : A.h; + TinyBlocks_Block* in = tb_block_create(ed->rt, t_in); + TinyBlocks_Block* sc = tb_block_create(ed->rt, t_area); + TinyBlocks_Block* win = tb_block_create(ed->rt, t_win); + if (!in || !sc || !win) { + if (win) tb_block_destroy(win, ed->rt); + if (sc) tb_block_destroy(sc, ed->rt); + if (in) tb_block_destroy(in, ed->rt); + return; + } + AreaScene* as = (AreaScene*)sc->userdata; + as->ed = ed; + as->view = v; + tb_block_set_default(sc, 0, tb_value_block(in)); + char title[64]; + snprintf(title, sizeof(title), "%s - TinyBlocks", view_name(v)); + TinyBlocks_Value tv = tb_value_text(title); + tb_block_set_default(win, 0, tv); /* set_default clona */ + tb_value_free(&tv); + tb_block_set_default(win, 1, tb_value_integer((int64_t)w)); + tb_block_set_default(win, 2, tb_value_integer((int64_t)h)); + tb_block_set_default(win, 3, tb_value_block(sc)); + tb_block_set_default(win, 4, tb_value_block(in)); + tb_block_set_default(win, 5, tb_value_integer(0)); /* fechar recolhe, nao encerra o editor */ + ed->vwin[v] = win; ed->vwin_in[v] = in; ed->vwin_scene[v] = sc; + /* ate a janela informar a posicao real, fica onde a area estava */ + ed->vgeom[v][0] = ed->main_wx + A.x; ed->vgeom[v][1] = ed->main_wy + A.y; + ed->vgeom[v][2] = w; ed->vgeom[v][3] = h; + tb_block_eval(win, ed->rt); + if (!tb_graphics_window_is_open(win)) { + attach_view(ed, v); + snprintf(ed->hot_status, sizeof(ed->hot_status), "Não foi possível abrir a janela de %s", view_name(v)); + ed->hot_status_ok = false; + return; + } + lay_compute(ed); +} + +/* Recolhe a aba destacada k para a barra da principal (fora do contexto dela) */ +static void attach_tab(Ed* ed, int k) { + TabWin* W = &ed->twin[k]; + if (!W->win) return; + TinyBlocks_Block* w = W->win; + TinyBlocks_Block* sc = W->scene; + TinyBlocks_Block* in = W->in; + int tab = W->tab; + W->win = W->scene = W->in = NULL; + W->tab = -1; + W->attach_pending = false; + tb_block_destroy(w, ed->rt); + if (sc) tb_block_destroy(sc, ed->rt); + if (in) tb_block_destroy(in, ed->rt); + if (ed->capture_view == V_COUNT + k) ed->capture_view = -2; + if (ed->mouse_owner == V_COUNT + k) ed->mouse_owner = -1; + if (tab >= 0 && tab < ed->tab_n) tab_select(ed, tab); + lay_compute(ed); +} + +static void tabwins_close_all(Ed* ed) { + for (int k = 0; k < TABWIN_MAX; k++) if (ed->twin[k].win) attach_tab(ed, k); +} + +/* Destaca a aba i numa janela propria (precisa sobrar uma na principal) */ +static void detach_tab(Ed* ed, int i) { + int vis[MAX_TABS], vn = tabs_visible_list(ed, vis); + if (i < 0 || i >= ed->tab_n || tab_detached(ed, i) || vn <= 1) return; + int k = -1; + for (int j = 0; j < TABWIN_MAX; j++) if (!ed->twin[j].win) { k = j; break; } + if (k < 0) { + snprintf(ed->hot_status, sizeof(ed->hot_status), "Limite de %d abas em janelas", TABWIN_MAX); + ed->hot_status_ok = false; + return; + } + TinyBlocks_TypeBlock* t_win = tb_type_block_find(ed->rt, "Graphics.Window"); + TinyBlocks_TypeBlock* t_in = tb_type_block_find(ed->rt, "Graphics.Input"); + TinyBlocks_TypeBlock* t_area = tb_type_block_find(ed->rt, "Editor.Area"); + if (!t_win || !t_in || !t_area) return; + float w = WS_W < 360 ? 360 : WS_W, h = WS_H + TAB_H < 260 ? 260 : WS_H + TAB_H; + TinyBlocks_Block* in = tb_block_create(ed->rt, t_in); + TinyBlocks_Block* sc = tb_block_create(ed->rt, t_area); + TinyBlocks_Block* win = tb_block_create(ed->rt, t_win); + if (!in || !sc || !win) { + if (win) tb_block_destroy(win, ed->rt); + if (sc) tb_block_destroy(sc, ed->rt); + if (in) tb_block_destroy(in, ed->rt); + return; + } + AreaScene* as = (AreaScene*)sc->userdata; + as->ed = ed; + as->view = V_COUNT + k; + tb_block_set_default(sc, 0, tb_value_block(in)); + char title[96]; + snprintf(title, sizeof(title), "%s - TinyBlocks", ed->tabs[i].name); + TinyBlocks_Value tv = tb_value_text(title); + tb_block_set_default(win, 0, tv); + tb_value_free(&tv); + tb_block_set_default(win, 1, tb_value_integer((int64_t)w)); + tb_block_set_default(win, 2, tb_value_integer((int64_t)h)); + tb_block_set_default(win, 3, tb_value_block(sc)); + tb_block_set_default(win, 4, tb_value_block(in)); + tb_block_set_default(win, 5, tb_value_integer(0)); + TabWin* W = &ed->twin[k]; + W->tab = i; W->win = win; W->in = in; W->scene = sc; W->attach_pending = false; + W->geom[0] = ed->main_wx + WS_X + 40; W->geom[1] = ed->main_wy + AREA(V_SCRIPTS).y + 40; + W->geom[2] = w; W->geom[3] = h; + if (ed->cur_tab == i) /* a principal mostra outra aba */ + for (int sl = 0; sl < vn; sl++) if (vis[sl] != i) { tab_select(ed, vis[sl]); break; } + tb_block_eval(win, ed->rt); + if (!tb_graphics_window_is_open(win)) { + attach_tab(ed, k); + snprintf(ed->hot_status, sizeof(ed->hot_status), "Não foi possível abrir a janela da aba"); + ed->hot_status_ok = false; + return; + } + lay_compute(ed); +} + +static void toggle_detach(Ed* ed, int v) { + if (ed->vwin[v]) attach_request(ed, v); + else detach_view(ed, v); } static void ctx_exec(Ed* ed, int id) { @@ -4159,6 +5017,7 @@ static void ctx_exec(Ed* ed, int id) { } static void on_lmb_down(Ed* ed, float mx, float my) { + if (toasts_click(ed, mx, my)) return; if (ed->settings_open) { settings_click(ed, mx, my); return; } if (ed->libman_open) { libman_click(ed, mx, my); return; } if (ed->comp_dialog_open) { dlg_click(ed, mx, my); return; } @@ -4200,7 +5059,17 @@ static void on_lmb_down(Ed* ed, float mx, float my) { bubble_clear(ed); /* Barra de menu */ - if (my < MENU_H) { + if (my < MENU_H && mx >= 0 && my >= 0) { + for (int v = 0; v < V_COUNT; v++) /* "voltar" uma view destacada */ + if (ed->vwin[v] && in_rect(mx, my, ed->chip_x[v], 7, ed->chip_w[v], MENU_H - 14)) { + attach_request(ed, v); + return; + } + for (int k = 0; k < TABWIN_MAX; k++) /* "voltar" uma aba destacada */ + if (ed->twin[k].win && in_rect(mx, my, ed->twin[k].chip_x, 7, ed->twin[k].chip_w, MENU_H - 14)) { + ed->twin[k].attach_pending = true; + return; + } if (hit_lib_btn(mx, my)) start_path(ed, PM_LIB, ""); else if (hit_open_btn(mx, my)) start_path(ed, PM_LOAD, "projeto.json"); else if (hit_save_btn(mx, my)) start_path(ed, PM_SAVE, "projeto.json"); @@ -4222,25 +5091,43 @@ static void on_lmb_down(Ed* ed, float mx, float my) { } ed->path_input_active = false; + /* Bordas entre areas (redimensionar) e alca do cabecalho (trocar de lugar) */ + int sp = split_at(ed, mx, my); + if (sp >= 0) { ed->split_drag = sp; return; } + int gv = grip_at(ed, mx, my); + if (gv >= 0) { ed->area_drag = gv; ed->area_drop = -1; return; } + int dv = detach_btn_at(ed, mx, my); + if (dv >= 0) { toggle_detach(ed, dv); return; } + int va = view_at(ed, mx, my); + /* Palco */ - if (mx >= WIN_W - STAGE_W) { + if (va == V_STAGE) { if (hit_flag(ed, mx, my)) run_flag(ed); 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); } + else if (hit_detach(ed, mx, my)) toggle_detach(ed, V_STAGE); return; } + if (va == V_OUTPUT || va < 0) return; + /* Abas */ - if (my < MENU_H + TAB_H) { - for (int i = 0; i < ed->tab_n; i++) { - float tx = 8 + i*TAB_W; - if (!in_rect(mx, my, tx, MENU_H, TAB_W-4, TAB_H)) continue; - if (ed->tab_n > 1 && mx >= tx + TAB_W - 28) tab_close(ed, i); - else tab_select(ed, i); + if (va == V_SCRIPTS && my < WS_Y) { + int vis[MAX_TABS], vn = tabs_visible_list(ed, vis); + for (int sl = 0; sl < vn; sl++) { + int i = vis[sl]; + float tx = WS_X + 8 + sl*TAB_W; + if (!in_rect(mx, my, tx, AREA(V_SCRIPTS).y, TAB_W-4, TAB_H)) continue; + if (ed->tab_n > 1 && ed->tabctx < 0 && mx >= tx + TAB_W - 28) { tab_close(ed, i); return; } + tab_select(ed, i); + ed->tab_press = i; /* arrastar = reordenar */ + ed->tab_drag = false; + ed->tab_press_x = mx; ed->tab_press_y = my; + ed->tab_grab_dx = mx - tx; return; } - float px = 8 + ed->tab_n*TAB_W; - if (in_rect(mx, my, px, MENU_H, PLUS_W, TAB_H)) ed->plus_menu_open = !ed->plus_menu_open; + float px = WS_X + 8 + vn*TAB_W; + if (ed->tabctx < 0 && in_rect(mx, my, px, AREA(V_SCRIPTS).y, PLUS_W, TAB_H)) + ed->plus_menu_open = !ed->plus_menu_open; return; } @@ -4260,8 +5147,10 @@ static void on_lmb_down(Ed* ed, float mx, float my) { } } + if (va == V_PALETTE && my < PAL_Y) return; /* cabecalho da paleta */ + /* Categorias */ - if (mx < CAT_W) { + if (va == V_PALETTE && mx < FLY_X) { if (hit_libman_foot(ed, mx, my)) { libman_show(ed); return; } int c = (int)((my - PAL_Y) / cat_item_h(ed)); if (c >= 0 && c < ed->cat_n) { @@ -4273,7 +5162,7 @@ static void on_lmb_down(Ed* ed, float mx, float my) { } /* Flyout */ - if (mx < PALETTE_W) { + if (va == V_PALETTE) { int it = hit_fly(ed, mx, my); if (it < 0) return; if (ed->fly_items[it].kind == FI_BUTTON) new_composite_tab(ed); @@ -4282,12 +5171,13 @@ static void on_lmb_down(Ed* ed, float mx, float my) { } /* Abas de codigo / imagem */ - if (mx >= WS_X && mx < WIN_W - STAGE_W && my >= WS_Y) { + if (in_ws(ed, mx, my)) { if (CT.kind == TK_CODE) { ed->editing = false; code_click(ed, mx, my); return; } if (CT.kind == TK_IMAGE) { image_click(ed, mx, my); return; } } /* Workspace */ + if (!in_ws(ed, mx, my)) return; float wx = mx - WS_X + CT.ws_sx, wy = my - WS_Y + CT.ws_sy; int bi = hit_ws(&CT, wx, wy); if (bi < 0) { @@ -4307,13 +5197,88 @@ static void on_lmb_down(Ed* ed, float mx, float my) { ed->press_mx = mx; ed->press_my = my; } +/* Leva a pilha arrastada para os scripts de outra janela (outra aba): copia + para a aba de destino, apaga da origem e encaixa la como num arrasto. */ +static void drag_to_ctx(Ed* ed, int tgt) { + int dti = tgt >= 0 ? ed->twin[tgt].tab : (ed->tabctx >= 0 ? ed->ctx_main_tab : ed->cur_tab); + if (dti < 0 || dti >= ed->tab_n || dti == ed->cur_tab) { apply_snap(ed); return; } + if (ed->tabs[dti].kind != TK_BLOCKS) { /* aba de imagem/codigo nao recebe blocos */ + snprintf(ed->hot_status, sizeof(ed->hot_status), "A aba \"%s\" não é de blocos", ed->tabs[dti].name); + ed->hot_status_ok = false; + apply_snap(ed); + return; + } + Tab* S = &CT; + Tab* D = &ed->tabs[dti]; + int si = ed->drag_bi; + float sx = S->ws[si].ax + WS_X - S->ws_sx, sy = S->ws[si].ay + WS_Y - S->ws_sy; /* tela */ + int ni = copy_tree(S, si, D, true); + if (ni < 0) { + snprintf(ed->hot_status, sizeof(ed->hot_status), "Limite de %d blocos por aba atingido", MAX_WS); + ed->hot_status_ok = false; + apply_snap(ed); + return; + } + top_add(D, ni); + free_tree(ed, S, si); + /* encaixa no destino: troca para o contexto dele so durante o calculo */ + int save_tab = ed->cur_tab; + AreaRect save_ws = ed->area[V_SCRIPTS]; + if (tgt >= 0) tabwin_rect(ed, tgt, &ed->area[V_SCRIPTS]); + else ed->area[V_SCRIPTS] = ed->main_scripts; + ed->cur_tab = dti; + D->ws[ni].x = sx - WS_X + D->ws_sx; + D->ws[ni].y = sy - WS_Y + D->ws_sy; + layout_tab(D); + ed->drag_bi = ni; + mark_drag(D, ni, true); + compute_snap(ed); + mark_drag(D, ni, false); + apply_snap(ed); + ed->cur_tab = save_tab; + ed->area[V_SCRIPTS] = save_ws; +} + static void on_lmb_up(Ed* ed, float mx, float my) { if (ed->comp_dialog_open || ed->fdlg.open) return; + if (ed->split_drag >= 0) { ed->split_drag = -1; lay_save(ed); return; } + if (ed->tab_press >= 0) { + bool was = ed->tab_drag; + int tab = ed->tab_press; + ed->tab_press = -1; + ed->tab_drag = false; + if (!was) return; + float bar_y = AREA(V_SCRIPTS).y; + if (ed->tabctx < 0) { + if (my < bar_y - 30 || my > bar_y + TAB_H + 40) detach_tab(ed, tab); + } else { + const AreaRect* M = &ed->main_scripts; + if (M->shown && in_rect(mx, my, M->x, M->y - 10, M->w, TAB_H + 30)) + ed->twin[ed->tabctx].attach_pending = true; /* volta para a barra */ + } + return; + } + if (ed->area_drag >= 0) { + int sv = ed->area_drag, tv = ed->area_drop; + bool outside = mx < 0 || my < 0 || mx >= WIN_W || my >= WIN_H; + if (tv >= 0 && tv != sv && !ed->vwin[tv]) { + if (ed->vwin[sv]) { /* volta para a principal no lugar de tv */ + attach_request(ed, sv); + ed->swap_pending[0] = sv; ed->swap_pending[1] = tv; + } else { lay_swap(ed, sv, tv); lay_save(ed); } + } else if (tv < 0 && outside && !ed->vwin[sv]) { + detach_view(ed, sv); /* solta fora da janela: destaca */ + } + ed->area_drag = ed->area_drop = -1; + return; + } rt_cache_clear(ed); /* soltar/encaixar muda o programa que esta rodando */ if (CT.kind == TK_IMAGE && CT.img_drag) { image_release(ed, mx, my); ed->state = ES_IDLE; return; } if (ed->state == ES_DRAG && ed->drag_bi >= 0) { mark_drag(&CT, ed->drag_bi, false); - if (mx < PALETTE_W) free_tree(ed, &CT, ed->drag_bi); /* solto na paleta = apagar */ + int tgt = ws_ctx_at(ed, mx, my); + if (view_at(ed, mx, my) == V_PALETTE) free_tree(ed, &CT, ed->drag_bi); /* solto na paleta = apagar */ + else if (tgt != -2 && tgt != ed->tabctx) drag_to_ctx(ed, tgt); else apply_snap(ed); } else if (ed->state == ES_PRESS) { ed->state = ES_IDLE; @@ -4338,7 +5303,7 @@ static void on_rmb_down(Ed* ed, float mx, float my) { if (ed->fdlg.open) return; if (ed->ctx_menu_open) { ed->ctx_menu_open = false; ed->ctx_export = false; return; } if (ed->state != ES_IDLE) return; - if (my < WS_Y || mx < WS_X || mx >= WIN_W - STAGE_W) return; + if (!in_ws(ed, mx, my)) return; int bi = hit_ws(&CT, mx - WS_X + CT.ws_sx, my - WS_Y + CT.ws_sy); ed->ctx_n = 0; if (bi >= 0) { @@ -4441,7 +5406,7 @@ static void on_key(Ed* ed, int sc, bool ctrl) { } if (sc == TB_KEY_DELETE && ed->state == ES_IDLE) { float mx = ed->mouse_x, my = ed->mouse_y; - if (mx >= WS_X && mx < WIN_W - STAGE_W && my >= WS_Y) { + if (in_ws(ed, mx, my)) { int bi = hit_ws(&CT, mx - WS_X + CT.ws_sx, my - WS_Y + CT.ws_sy); if (bi >= 0) delete_heal(ed, &CT, bi); } @@ -4485,7 +5450,7 @@ static void update_tooltip(Ed* ed, bool alt) { if (CT.kind != TK_BLOCKS) return; if (ed->state != ES_IDLE) return; float mx = ed->mouse_x, my = ed->mouse_y; - if (mx < WS_X || mx >= WIN_W - STAGE_W || my < WS_Y) return; + if (!in_ws(ed, mx, my)) return; int bi = hit_ws(&CT, mx - WS_X + CT.ws_sx, my - WS_Y + CT.ws_sy); if (bi < 0) return; EdBlock* b = &CT.ws[bi]; @@ -4540,23 +5505,77 @@ static void update_tooltip(Ed* ed, bool alt) { /* === * editor_eval - lê um snapshot de Graphics.Input por frame e atualiza o estado * === */ -static void editor_eval(TinyBlocks_Block* self, TinyBlocks* rt) { - Ed* ed = *(Ed**)self->userdata; - self->dirty = false; - if (!ed) return; +/* Alguma view ou aba esta numa janela propria? */ +static bool any_window_detached(Ed* ed) { + for (int v = 0; v < V_COUNT; v++) if (ed->vwin[v]) return true; + for (int k = 0; k < TABWIN_MAX; k++) if (ed->twin[k].win) return true; + return false; +} + +/* Entrada de uma janela do editor: a principal (from = -1) ou a de uma view + destacada (from = V_*). Pontos viram coordenadas da janela principal. */ +static void ed_handle_input(Ed* ed, TinyBlocks_Block* evb, int from) { g_active_ed = ed; + if (from < 0) { + int ww = (int)ev_int(evb, GFX_IN_WIN_W); + int wh = (int)ev_int(evb, GFX_IN_WIN_H); + if (ww > 0) ed->win_w = ww; + if (wh > 0) ed->win_h = wh; + ed->main_wx = (float)ev_int(evb, GFX_IN_WIN_X); + ed->main_wy = (float)ev_int(evb, GFX_IN_WIN_Y); + /* recolher pedido de dentro de uma janela destacada / janela fechada */ + for (int v = 0; v < V_COUNT; v++) { + if (ed->vwin[v] && !tb_graphics_window_is_open(ed->vwin[v])) ed->attach_pending[v] = true; + if (ed->attach_pending[v]) { ed->attach_pending[v] = false; attach_view(ed, v); } + } + for (int k = 0; k < TABWIN_MAX; k++) { + TabWin* W = &ed->twin[k]; + if (W->win && (W->attach_pending || !tb_graphics_window_is_open(W->win))) attach_tab(ed, k); + } + if (ed->swap_pending[0] >= 0) { + lay_swap(ed, ed->swap_pending[0], ed->swap_pending[1]); + ed->swap_pending[0] = ed->swap_pending[1] = -1; + lay_save(ed); + } + } else if (from >= V_COUNT) { /* janela de uma aba destacada */ + int ww = (int)ev_int(evb, GFX_IN_WIN_W), wh = (int)ev_int(evb, GFX_IN_WIN_H); + TabWin* W = &ed->twin[from - V_COUNT]; + if (ww > 0 && wh > 0) { + W->geom[0] = (float)ev_int(evb, GFX_IN_WIN_X); + W->geom[1] = (float)ev_int(evb, GFX_IN_WIN_Y); + W->geom[2] = (float)ww; + W->geom[3] = (float)wh; + } + } else { + int ww = (int)ev_int(evb, GFX_IN_WIN_W), wh = (int)ev_int(evb, GFX_IN_WIN_H); + if (ww > 0 && wh > 0) { + ed->vgeom[from][0] = (float)ev_int(evb, GFX_IN_WIN_X); + ed->vgeom[from][1] = (float)ev_int(evb, GFX_IN_WIN_Y); + ed->vgeom[from][2] = (float)ww; + ed->vgeom[from][3] = (float)wh; + } + } + lay_compute(ed); - TinyBlocks_Block* evb = editor_events_block(self, rt); - if (!evb) return; - - int ww = (int)ev_int(evb, GFX_IN_WIN_W); - int wh = (int)ev_int(evb, GFX_IN_WIN_H); - if (ww > 0) ed->win_w = ww; - if (wh > 0) ed->win_h = wh; - - float mx = (float)ev_real(evb, GFX_IN_MOUSE_X); - float my = (float)ev_real(evb, GFX_IN_MOUSE_Y); - ed->mouse_x = mx; ed->mouse_y = my; + /* o mouse e da janela que esta sob ele (ou da que comecou um arrasto) */ + int ov = from >= V_COUNT ? V_SCRIPTS : from; /* janela de aba = os scripts do contexto */ + float ox = from < 0 ? 0.f : AREA(ov).x, oy = from < 0 ? 0.f : AREA(ov).y; + bool clicked = ev_int(evb, GFX_IN_MOUSE_L_DOWN) || ev_int(evb, GFX_IN_MOUSE_L_UP) || + ev_int(evb, GFX_IN_MOUSE_R_DOWN); /* o evento traz a posicao certa */ + if (ev_int_def(evb, GFX_IN_MOUSE_IN, 1) || ed->capture_view == from || clicked) { + TinyBlocks_Value* gxv = (uint32_t)GFX_IN_GMOUSE_Y < evb->output_count ? &evb->outputs[GFX_IN_GMOUSE_X] : NULL; + if (gxv && gxv->kind == TB_VALUE_REAL && any_window_detached(ed)) { + /* com janelas destacadas: posicao global - posicao da principal */ + ed->mouse_x = (float)ev_real(evb, GFX_IN_GMOUSE_X) - ed->main_wx; + ed->mouse_y = (float)ev_real(evb, GFX_IN_GMOUSE_Y) - ed->main_wy; + } else { + ed->mouse_x = (float)ev_real(evb, GFX_IN_MOUSE_X) + ox; + ed->mouse_y = (float)ev_real(evb, GFX_IN_MOUSE_Y) + oy; + } + ed->mouse_owner = from; + } + float mx = ed->mouse_x, my = ed->mouse_y; + if (from < 0) toasts_update(ed); layout_tab(&CT); /* == Hover === */ @@ -4565,8 +5584,6 @@ static void editor_eval(TinyBlocks_Block* self, TinyBlocks* rt) { ed->lib_hover = hit_lib_btn(mx, my); ed->detach_hover = hit_detach(ed, mx, my); - /* Janela do palco fechada pelo usuário: o palco volta para o painel */ - if (ed->stage_win && !tb_graphics_window_is_open(ed->stage_win)) stage_attach(ed); ed->ctx_menu_hover = ed->ctx_menu_open ? ctx_hit(ed, mx, my) : -1; ed->plus_menu_hover = -1; @@ -4580,17 +5597,43 @@ static void editor_eval(TinyBlocks_Block* self, TinyBlocks* rt) { update_tooltip(ed, (ev_int(evb, GFX_IN_MOD_STATE) & TB_MOD_ALT) != 0); + /* == Areas: borda sendo arrastada / area levada pela alca === */ + if (ed->split_drag >= 0) { split_drag_to(ed, ed->split_drag, mx, my); lay_compute(ed); } + if (ed->area_drag >= 0) ed->area_drop = view_at(ed, mx, my); + bool modal = ed->settings_open || ed->libman_open || ed->comp_dialog_open || ed->fdlg.open; + ed->split_hover = modal ? -1 : split_at(ed, mx, my); + + /* == Aba sendo arrastada: reordena ao passar do meio da vizinha === */ + if (ed->tab_press >= 0 && (ed->capture_view == -2 || ed->capture_view == from)) { + if (!ed->tab_drag && fabsf(mx - ed->tab_press_x) + fabsf(my - ed->tab_press_y) > 6.f) + ed->tab_drag = true; + if (ed->tab_drag) { + int vis[MAX_TABS], vn = tabs_visible_list(ed, vis); + int slot = (int)floorf((mx - ed->tab_grab_dx - (WS_X + 8) + TAB_W * 0.5f) / TAB_W); + if (slot < 0) slot = 0; + if (slot >= vn) slot = vn - 1; + if (vn > 1 && vis[slot] != ed->tab_press) { + int to = vis[slot]; + tab_move(ed, ed->tab_press, to); + ed->tab_press = to; + } + } + } + /* == Movimento === */ - if (ed->state == ES_PRESS && fabsf(mx - ed->press_mx) + fabsf(my - ed->press_my) > 4.f) + if (ed->state == ES_PRESS && fabsf(mx - ed->press_mx) + fabsf(my - ed->press_my) > 4.f && + (ed->capture_view == -2 || ed->capture_view == from)) start_drag(ed); - if (ed->state == ES_DRAG && ed->drag_bi >= 0) { + if (ed->state == ES_DRAG && ed->drag_bi >= 0 && (ed->capture_view == -2 || ed->capture_view == from)) { EdBlock* b = &CT.ws[ed->drag_bi]; + ed->drag_tab = ed->cur_tab; + ed->drag_ws_x = WS_X; ed->drag_ws_y = WS_Y; b->x = mx - ed->drag_ox - WS_X + CT.ws_sx; b->y = my - ed->drag_oy - WS_Y + CT.ws_sy; layout_tab(&CT); compute_snap(ed); } - if (ed->state == ES_PAN) { + if (ed->state == ES_PAN && (ed->capture_view == -2 || ed->capture_view == from)) { CT.ws_sx = ed->pan_sx - (mx - ed->pan_mx); CT.ws_sy = ed->pan_sy - (my - ed->pan_my); } @@ -4607,16 +5650,16 @@ static void editor_eval(TinyBlocks_Block* self, TinyBlocks* rt) { settings_scroll_by(ed, (float)sdy); } else if (ed->libman_open) { libman_scroll_by(ed, (float)sdy); - } else if (CT.kind == TK_CODE && mx >= WS_X && mx < WIN_W - STAGE_W && my >= WS_Y) { + } else if (CT.kind == TK_CODE && in_ws(ed, mx, my)) { CT.code_scroll -= (int)sdy * 3; if (CT.code_scroll < 0) CT.code_scroll = 0; - } else if (CT.kind == TK_IMAGE && mx >= WS_X && mx < WIN_W - STAGE_W && my >= WS_Y) { + } else if (CT.kind == TK_IMAGE && in_ws(ed, mx, my)) { /* roda do mouse na aba de imagem = zoom no cursor (nao pinta) */ image_zoom(ed, mx, my, (int)(sdy > 0 ? 1 : sdy < 0 ? -1 : 0)); - } else if (mx >= WS_X && mx < WIN_W - STAGE_W && my >= WS_Y) { + } else if (in_ws(ed, mx, my)) { CT.ws_sx -= (float)sdx * 40.f; CT.ws_sy -= (float)sdy * 40.f; - } else if (mx < PALETTE_W && my >= PAL_Y) { + } else if (view_at(ed, mx, my) == V_PALETTE && my >= PAL_Y) { ed->fly_scroll -= (float)sdy * 48.f; if (ed->fly_scroll > fly_max_scroll(ed)) ed->fly_scroll = fly_max_scroll(ed); if (ed->fly_scroll < 0) ed->fly_scroll = 0; @@ -4631,9 +5674,9 @@ static void editor_eval(TinyBlocks_Block* self, TinyBlocks* rt) { else if (len > 5 && strcmp(dropped + len - 5, ".json") == 0) project_load(ed, dropped); } - if (ev_int(evb, GFX_IN_MOUSE_L_DOWN)) on_lmb_down(ed, mx, my); + if (ev_int(evb, GFX_IN_MOUSE_L_DOWN)) { ed->capture_view = from; on_lmb_down(ed, mx, my); } if (ev_int(evb, GFX_IN_MOUSE_R_DOWN)) on_rmb_down(ed, mx, my); - if (ev_int(evb, GFX_IN_MOUSE_L_UP)) on_lmb_up(ed, mx, my); + if (ev_int(evb, GFX_IN_MOUSE_L_UP)) { on_lmb_up(ed, mx, my); ed->capture_view = -2; } int sc = (int)ev_int(evb, GFX_IN_KEY); if (sc != 0) on_key(ed, sc, (ev_int(evb, GFX_IN_KEY_MOD) & TB_MOD_CTRL) != 0); @@ -4641,6 +5684,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); + if (from >= 0) return; /* o resto e uma vez por quadro (principal) */ + input_feed(ed, evb); /* Sensores: mouse/teclado/toque/sensores do palco */ vm_frame(ed); /* scripts rodando (sempre / repita) avancam um quadro */ /* Hot reload: checa os .so a cada ~30 frames (~0,5 s). @@ -4651,6 +5696,136 @@ static void editor_eval(TinyBlocks_Block* self, TinyBlocks* rt) { } } +static void editor_eval(TinyBlocks_Block* self, TinyBlocks* rt) { + Ed* ed = *(Ed**)self->userdata; + self->dirty = false; + if (!ed) return; + TinyBlocks_Block* evb = editor_events_block(self, rt); + if (evb) ed_handle_input(ed, evb, -1); +} + +/* Pilha arrastada: desenhada em todas as janelas (o bloco pode passar de + uma para outra), a partir da aba e da area de onde ela saiu */ +static void render_drag_chain(Ed* ed, TinyBlocks_RenderableBlock* rb) { + int t = ed->drag_tab >= 0 && ed->drag_tab < ed->tab_n ? ed->drag_tab : ed->cur_tab; + Tab* T = &ed->tabs[t]; + if (ed->drag_bi < 0 || !T->ws[ed->drag_bi].used) return; + render_chain(ed, rb, T, ed->drag_bi, ed->drag_ws_x - T->ws_sx, ed->drag_ws_y - T->ws_sy); +} + +/* Mostra so a view `keep` (-1 = so as da janela principal) durante um desenho */ +static void areas_only(Ed* ed, int keep, bool saved[V_COUNT]) { + for (int v = 0; v < V_COUNT; v++) { + saved[v] = ed->area[v].shown; + if (keep < 0 ? ed->area[v].detached : v != keep) ed->area[v].shown = false; + } +} + +static void areas_restore(Ed* ed, const bool saved[V_COUNT]) { + for (int v = 0; v < V_COUNT; v++) ed->area[v].shown = saved[v]; +} + +/* Desloca os comandos (desenho no espaco da principal -> janela destacada) */ +static void rb_translate(TinyBlocks_RenderableBlock* rb, float dx, float dy) { + for (uint32_t i = 0; i < rb->count; i++) { + TinyBlocks_DrawCmd* c = &rb->cmds[i]; + switch (c->kind) { + case TB_DRAW_CLEAR: + case TB_DRAW_CLEAR_CLIP: + break; + case TB_DRAW_STROKE_LINE: /* w,h sao o segundo ponto */ + c->x += dx; c->y += dy; c->w += dx; c->h += dy; + break; + default: + c->x += dx; c->y += dy; + break; + } + } +} + +/* Editor.Area: cena da janela de uma view destacada */ +/* A janela da cena ainda existe? (view destacada ou aba destacada) */ +static bool scene_alive(const AreaScene* as) { + if (!as || !as->ed || as->view < 0) return false; + if (as->view < V_COUNT) return as->ed->vwin[as->view] != NULL; + int k = as->view - V_COUNT; + return k < TABWIN_MAX && as->ed->twin[k].win != NULL; +} + +static void area_eval(TinyBlocks_Block* self, TinyBlocks* rt) { + self->dirty = false; + AreaScene* as = (AreaScene*)self->userdata; + if (!scene_alive(as)) return; + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + if (v.kind != TB_VALUE_BLOCK || !v.as.block) return; + if (as->view < V_COUNT) { ed_handle_input(as->ed, v.as.block, as->view); return; } + TabCtxSave sv; + tabctx_enter(as->ed, as->view - V_COUNT, &sv); + ed_handle_input(as->ed, v.as.block, as->view); + tabctx_leave(as->ed, &sv); +} + +static bool area_on_draw(TinyBlocks_Block* self, TinyBlocks* rt, TinyBlocks_RenderableBlock** dst) { + (void)rt; + AreaScene* as = (AreaScene*)self->userdata; + if (!scene_alive(as)) return false; + Ed* ed = as->ed; + int v = as->view; + if (v >= V_COUNT) return tabwin_on_draw(ed, v - V_COUNT, dst); + TinyBlocks_RenderableBlock* rb = tb_renderable_acquire(); + if (!rb) return false; + lay_compute(ed); + layout_tab(&CT); + tb_draw_clear(rb, COL_UI_BG.r, COL_UI_BG.g, COL_UI_BG.b, 1.f); + bool saved[V_COUNT]; + areas_only(ed, v, saved); + switch (v) { + case V_PALETTE: render_flyout(ed, rb); render_categories(ed, rb); break; + case V_SCRIPTS: render_workspace(ed, rb); render_comp_panel(ed, rb); render_tab_bar(ed, rb); break; + case V_STAGE: render_stage(ed, rb); break; + case V_OUTPUT: render_output(ed, rb); break; + } + if (ed->state == ES_DRAG && ed->drag_bi >= 0) /* bloco arrastado entre janelas */ + render_drag_chain(ed, rb); + render_areas_overlay(ed, rb); + if (v == V_SCRIPTS) { render_plus_menu(ed, rb); render_tooltip(ed, rb); render_ctx_menu(ed, rb); } + areas_restore(ed, saved); + rb_translate(rb, -AREA(v).x, -AREA(v).y); + *dst = rb; + return true; +} + +/* Janela de uma aba destacada: barra com a aba + area de scripts dela */ +static bool tabwin_on_draw(Ed* ed, int k, TinyBlocks_RenderableBlock** dst) { + TinyBlocks_RenderableBlock* rb = tb_renderable_acquire(); + if (!rb) return false; + TabCtxSave sv; + tabctx_enter(ed, k, &sv); + layout_tab(&CT); + tb_draw_clear(rb, COL_UI_BG.r, COL_UI_BG.g, COL_UI_BG.b, 1.f); + render_workspace(ed, rb); + render_comp_panel(ed, rb); + render_tab_bar(ed, rb); + if (ed->state == ES_DRAG && ed->drag_bi >= 0) render_drag_chain(ed, rb); + render_tooltip(ed, rb); + render_ctx_menu(ed, rb); + float ox = AREA(V_SCRIPTS).x, oy = AREA(V_SCRIPTS).y; + tabctx_leave(ed, &sv); + rb_translate(rb, -ox, -oy); + *dst = rb; + return true; +} + +static bool area_instance_init(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + if (self->userdata) { AreaScene* as = (AreaScene*)self->userdata; as->ed = NULL; as->view = -1; } + return true; +} + +static void area_instance_deinit(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)self; (void)rt; +} + /* === * editor_on_draw - compõe o frame inteiro em um RenderableBlock * === */ @@ -4662,21 +5837,26 @@ static bool editor_on_draw(TinyBlocks_Block* self, TinyBlocks* rt, TinyBlocks_RenderableBlock* rb = tb_renderable_acquire(); if (!rb) return false; + lay_compute(ed); layout_tab(&CT); tb_draw_clear(rb, COL_UI_BG.r, COL_UI_BG.g, COL_UI_BG.b, 1.f); + bool saved[V_COUNT]; + areas_only(ed, -1, saved); /* as destacadas desenham na janela delas */ render_workspace(ed, rb); render_comp_panel(ed, rb); render_flyout(ed, rb); render_categories(ed, rb); render_stage(ed, rb); + render_output(ed, rb); render_tab_bar(ed, rb); render_menu(ed, rb); /* A pilha arrastada fica por cima de tudo (pode passar sobre a paleta) */ if (ed->state == ES_DRAG && ed->drag_bi >= 0) - render_chain(ed, rb, &CT, ed->drag_bi, WS_X - CT.ws_sx, WS_Y - CT.ws_sy); + render_drag_chain(ed, rb); + render_areas_overlay(ed, rb); render_plus_menu(ed, rb); render_tooltip(ed, rb); render_ctx_menu(ed, rb); @@ -4684,6 +5864,8 @@ static bool editor_on_draw(TinyBlocks_Block* self, TinyBlocks* rt, if (ed->fdlg.open && files_view) files_view(ed, rb); libman_render(ed, rb); /* tela cheia: por cima de tudo */ settings_render(ed, rb); + render_toasts(ed, rb); /* avisos flutuam por cima de tudo */ + areas_restore(ed, saved); *dst = rb; return true; @@ -4731,6 +5913,17 @@ static bool editor_instance_init(TinyBlocks_Block* self, TinyBlocks* rt) { ed->rt = rt; ed->win_w = WIN_W_DEFAULT; ed->win_h = WIN_H_DEFAULT; + lay_default(ed); + lay_restore(ed); /* layout salvo nas configuracoes */ + ed->split_hover = ed->split_drag = ed->area_drag = ed->area_drop = -1; + ed->swap_pending[0] = ed->swap_pending[1] = -1; + ed->mouse_owner = -1; + ed->capture_view = -2; + ed->tab_press = -1; + ed->tabctx = -1; + ed->drag_tab = -1; + for (int k = 0; k < TABWIN_MAX; k++) ed->twin[k].tab = -1; + lay_compute(ed); ed->drag_bi = -1; ed->press_bi = -1; @@ -4835,6 +6028,14 @@ static bool editor_lib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { tb_type_block_set_instance_hooks(t, sizeof(Ed*), editor_instance_init, editor_instance_deinit); t->on_draw = editor_on_draw; tb_library_add(lib, &t->base); + + /* Editor.Area - uma view do editor destacada numa janela propria */ + TinyBlocks_TypeBlock* ta = tb_type_block_create(rt, "Editor.Area", + scene_in, 1, NULL, 0, area_eval); + if (!ta) return false; + tb_type_block_set_instance_hooks(ta, sizeof(AreaScene), area_instance_init, area_instance_deinit); + ta->on_draw = area_on_draw; + tb_library_add(lib, &ta->base); return true; } diff --git a/libraries/tinyblocks-graphics/include/tb_graphics.h b/libraries/tinyblocks-graphics/include/tb_graphics.h index 529b520..bb0af3d 100644 --- a/libraries/tinyblocks-graphics/include/tb_graphics.h +++ b/libraries/tinyblocks-graphics/include/tb_graphics.h @@ -73,7 +73,18 @@ enum { #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 +#define GFX_IN_KEYS_HELD 19 /* json: lista dos TB_KEY_* segurados agora */ +#define GFX_IN_TOUCHES 20 /* json: toques [[x,y],...] em px da janela */ +#define GFX_IN_ACCEL 21 /* json: [x,y,z] em m/s² ou [] sem sensor */ +#define GFX_IN_GYRO 22 /* json: [x,y,z] em rad/s ou [] sem sensor */ +#define GFX_IN_WIN_X 23 /* int: posição da janela na tela (x) */ +#define GFX_IN_WIN_Y 24 /* int: posição da janela na tela (y) */ +#define GFX_IN_MOUSE_IN 25 /* int: 1 se o mouse está sobre esta janela */ +#define GFX_IN_GMOUSE_X 26 /* real: mouse na tela (global), x */ +#define GFX_IN_GMOUSE_Y 27 /* real: mouse na tela (global), y */ +#define GFX_IN_COUNT 28 + +#define GFX_MAX_TOUCHES 10 /* Estado de entrada de uma janela em um frame (preenchido pelo backend) */ typedef struct TinyBlocks_GfxInput { @@ -87,6 +98,15 @@ typedef struct TinyBlocks_GfxInput { int win_w, win_h; char drop_file[512]; int mod_state; + unsigned char keys_held[128]; /* indice = TB_KEY_* */ + int touch_n; /* dedos na tela agora */ + float touch_x[GFX_MAX_TOUCHES], touch_y[GFX_MAX_TOUCHES]; /* px da janela */ + int has_accel, has_gyro; /* o dispositivo tem o sensor? */ + float accel[3]; /* m/s² (inclui a gravidade) */ + float gyro[3]; /* rad/s */ + int win_x, win_y; /* posicao da janela na tela */ + int mouse_in; /* o mouse esta sobre esta janela */ + float gmouse_x, gmouse_y; /* mouse na tela (coordenadas globais) */ } TinyBlocks_GfxInput; /* -- Contrato de um backend gráfico --- */ diff --git a/libraries/tinyblocks-graphics/src/tb_graphics.c b/libraries/tinyblocks-graphics/src/tb_graphics.c index d4a4a5d..3b3e7ef 100644 --- a/libraries/tinyblocks-graphics/src/tb_graphics.c +++ b/libraries/tinyblocks-graphics/src/tb_graphics.c @@ -9,6 +9,7 @@ #include #include +#include #include "../include/tb_graphics.h" #ifdef TB_GRAPHICS_DEFAULT_SDL2 @@ -164,6 +165,11 @@ static const TinyBlocks_SlotDesc s_input_outs[GFX_IN_COUNT] = { {"close", TB_VALUE_INTEGER}, {"win_w", TB_VALUE_INTEGER}, {"win_h", TB_VALUE_INTEGER}, {"drop_file", TB_VALUE_TEXT}, {"mod_state", TB_VALUE_INTEGER}, + {"keys_held", TB_VALUE_JSON}, {"touches", TB_VALUE_JSON}, + {"accel", TB_VALUE_JSON}, {"gyro", TB_VALUE_JSON}, + {"win_x", TB_VALUE_INTEGER}, {"win_y", TB_VALUE_INTEGER}, + {"mouse_in", TB_VALUE_INTEGER}, + {"gmouse_x", TB_VALUE_REAL}, {"gmouse_y", TB_VALUE_REAL}, }; static void eval_input(TinyBlocks_Block* self, TinyBlocks* rt) { @@ -174,12 +180,57 @@ static void eval_input(TinyBlocks_Block* self, TinyBlocks* rt) { 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; + case TB_VALUE_JSON: { + TinyBlocks_JsonValue* e = tb_json_array(); + self->outputs[i] = tb_value_json(e); + tb_json_release(e); + break; + } default: self->outputs[i] = tb_value_integer(0); break; } } self->dirty = false; } +/* Valores JSON das saidas de dispositivo (teclas seguradas, toques, sensores) */ +static void json_push_num(TinyBlocks_JsonValue* arr, double d) { + TinyBlocks_JsonValue* n = tb_json_number(d); + if (n) { tb_json_array_push(arr, n); tb_json_release(n); } +} + +static TinyBlocks_Value json_out(TinyBlocks_JsonValue* arr) { + TinyBlocks_Value v = tb_value_json(arr); /* retem */ + tb_json_release(arr); + return v; +} + +static TinyBlocks_Value json_keys(const TinyBlocks_GfxInput* in) { + TinyBlocks_JsonValue* arr = tb_json_array(); + for (int k = 1; arr && k < 128; k++) + if (in->keys_held[k]) json_push_num(arr, k); + return json_out(arr); +} + +static TinyBlocks_Value json_touches(const TinyBlocks_GfxInput* in) { + TinyBlocks_JsonValue* arr = tb_json_array(); + int n = in->touch_n < GFX_MAX_TOUCHES ? in->touch_n : GFX_MAX_TOUCHES; + for (int i = 0; arr && i < n; i++) { + TinyBlocks_JsonValue* p = tb_json_array(); + if (!p) break; + json_push_num(p, in->touch_x[i]); + json_push_num(p, in->touch_y[i]); + tb_json_array_push(arr, p); + tb_json_release(p); + } + return json_out(arr); +} + +static TinyBlocks_Value json_vec3(int has, const float v[3]) { + TinyBlocks_JsonValue* arr = tb_json_array(); + for (int i = 0; arr && has && i < 3; i++) json_push_num(arr, v[i]); + return json_out(arr); +} + 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) @@ -202,6 +253,15 @@ static void input_push(TinyBlocks_Block* b, const TinyBlocks_GfxInput* in) { 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)); + SET(GFX_IN_KEYS_HELD, json_keys(in)); + SET(GFX_IN_TOUCHES, json_touches(in)); + SET(GFX_IN_ACCEL, json_vec3(in->has_accel, in->accel)); + SET(GFX_IN_GYRO, json_vec3(in->has_gyro, in->gyro)); + SET(GFX_IN_WIN_X, tb_value_integer(in->win_x)); + SET(GFX_IN_WIN_Y, tb_value_integer(in->win_y)); + SET(GFX_IN_MOUSE_IN, tb_value_integer(in->mouse_in)); + SET(GFX_IN_GMOUSE_X, tb_value_real(in->gmouse_x)); + SET(GFX_IN_GMOUSE_Y, tb_value_real(in->gmouse_y)); #undef SET b->dirty = false; } diff --git a/libraries/tinyblocks-input/Makefile b/libraries/tinyblocks-input/Makefile new file mode 100644 index 0000000..b68cec6 --- /dev/null +++ b/libraries/tinyblocks-input/Makefile @@ -0,0 +1,29 @@ +# Makefile da library input (categoria "Sensores") +# Constroi build/libtinyblocks-input.a e build/libtinyblocks-input.so +CC := gcc +BUILD := build + +CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \ + -I../../include -Iinclude -I../tinyblocks-graphics/include + +OBJ := $(BUILD)/tb_input.o +LIB_A := $(BUILD)/libtinyblocks-input.a +LIB_SO := $(BUILD)/libtinyblocks-input.so + +.PHONY: all static shared clean +all: static shared +static: $(LIB_A) +shared: $(LIB_SO) + +$(OBJ): src/tb_input.c include/tb_input_lib.h ../tinyblocks-graphics/include/tb_graphics.h + @mkdir -p $(BUILD) + $(CC) $(CFLAGS) -fPIC -c $< -o $@ + +$(LIB_A): $(OBJ) + ar rcs $@ $^ + +$(LIB_SO): $(OBJ) + $(CC) -shared -o $@ $^ -lm + +clean: + $(RM) -r $(BUILD) diff --git a/libraries/tinyblocks-input/include/tb_input_lib.h b/libraries/tinyblocks-input/include/tb_input_lib.h new file mode 100644 index 0000000..80e3c46 --- /dev/null +++ b/libraries/tinyblocks-input/include/tb_input_lib.h @@ -0,0 +1,20 @@ +/* + * TinyBlocks - tb_input_lib.h + * Library tinyblocks-input: blocos de Sensores (mouse, teclado, toque, + * acelerometro, giroscopio e cronometro). Le o estado do core + * (tinyblocks/tb_input.h), alimentado por quem mostra o palco. + */ +#ifndef TINYBLOCKS_INPUT_LIB_H +#define TINYBLOCKS_INPUT_LIB_H + +#include + +TB_API const TinyBlocks_LibraryDescriptor* tb_input_get_library(void); + +/* Codigo TB_KEY_* de um nome de tecla ("espaço", "seta para cima", "a", + "7", "enter", "space", "up"...); "qualquer"/"any" = -1; 0 = desconhecida */ +TB_API int tb_input_key_from_name(const char* name); +/* Nome em portugues de um TB_KEY_* ("" se desconhecido) */ +TB_API const char* tb_input_key_name(int key); + +#endif /* TINYBLOCKS_INPUT_LIB_H */ diff --git a/libraries/tinyblocks-input/library.toml b/libraries/tinyblocks-input/library.toml new file mode 100644 index 0000000..d29c347 --- /dev/null +++ b/libraries/tinyblocks-input/library.toml @@ -0,0 +1,15 @@ +# Metadados da library input. Lido pela UI/build sem recompilar o .so. +[library] +name = "tinyblocks-input" +version = "1.0.0" +category = "Sensores" +description = "Mouse, teclado, toque, acelerometro, giroscopio e cronometro" +color = [92, 177, 214, 255] +dark = [46, 142, 184, 255] + +[build] +sources = ["src/tb_input.c"] +includes = ["include"] +shared = "build/libtinyblocks-input.so" +static = "build/libtinyblocks-input.a" +depends = [] diff --git a/libraries/tinyblocks-input/src/tb_input.c b/libraries/tinyblocks-input/src/tb_input.c new file mode 100644 index 0000000..40bcf3c --- /dev/null +++ b/libraries/tinyblocks-input/src/tb_input.c @@ -0,0 +1,270 @@ +/* + * TinyBlocks - tb_input.c (library tinyblocks-input) + * Categoria "Sensores": Input.MouseX / MouseY / Wheel / KeyPressed / + * LastKey / TouchCount / TouchX / TouchY / Accel / Gyro / Timer / + * ResetTimer e os booleanos Input.MouseDown / MouseRight / MouseOver / + * Touching / HasAccel / HasGyro. + * + * Nao conhece janela nem editor: le o estado do core (tinyblocks/tb_input.h) + * em coordenadas do palco. Os nomes de tecla usam os TB_KEY_* do + * tinyblocks-graphics (so o cabecalho). + */ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include "tb_input_lib.h" + +/* -- Nomes de tecla ------------------------------------------------------- */ + +typedef struct { const char* name; int key; } KeyName; + +/* O primeiro nome de cada tecla e o usado em "ultima tecla" */ +static const KeyName s_keys[] = { + {"espaço", TB_KEY_SPACE}, {"espaco", TB_KEY_SPACE}, {"space", TB_KEY_SPACE}, + {"seta para cima", TB_KEY_UP}, {"cima", TB_KEY_UP}, {"up", TB_KEY_UP}, + {"seta para baixo", TB_KEY_DOWN}, {"baixo", TB_KEY_DOWN}, {"down", TB_KEY_DOWN}, + {"seta para esquerda", TB_KEY_LEFT}, {"esquerda", TB_KEY_LEFT}, {"left", TB_KEY_LEFT}, + {"seta para direita", TB_KEY_RIGHT}, {"direita", TB_KEY_RIGHT}, {"right", TB_KEY_RIGHT}, + {"enter", TB_KEY_RETURN}, {"return", TB_KEY_RETURN}, + {"esc", TB_KEY_ESCAPE}, {"escape", TB_KEY_ESCAPE}, + {"apagar", TB_KEY_BACKSPACE}, {"backspace", TB_KEY_BACKSPACE}, + {"delete", TB_KEY_DELETE}, {"del", TB_KEY_DELETE}, + {"tab", TB_KEY_TAB}, + {"home", TB_KEY_HOME}, {"end", TB_KEY_END}, +}; + +TB_API int tb_input_key_from_name(const char* name) { + if (!name) return 0; + while (isspace((unsigned char)*name)) name++; + size_t n = strlen(name); + while (n && isspace((unsigned char)name[n - 1])) n--; + if (n == 0) return 0; + char buf[32]; + if (n >= sizeof(buf)) return 0; + memcpy(buf, name, n); + buf[n] = 0; + if (!strcasecmp(buf, "qualquer") || !strcasecmp(buf, "any")) return -1; + if (n == 1) { + char c = (char)tolower((unsigned char)buf[0]); + if (c >= 'a' && c <= 'z') return TB_KEY_A + (c - 'a'); + if (c >= '0' && c <= '9') return TB_KEY_0 + (c - '0'); + } + if ((buf[0] == 'f' || buf[0] == 'F') && n <= 3) { + int k = atoi(buf + 1); + if (k >= 1 && k <= 12) return TB_KEY_F1 + (k - 1); + } + for (size_t i = 0; i < sizeof(s_keys) / sizeof(s_keys[0]); i++) + if (!strcasecmp(buf, s_keys[i].name)) return s_keys[i].key; + return 0; +} + +TB_API const char* tb_input_key_name(int key) { + static char one[4][8]; + static int slot = 0; + if (key >= TB_KEY_A && key < TB_KEY_A + 26) { + char* b = one[slot++ & 3]; + snprintf(b, 8, "%c", 'a' + (key - TB_KEY_A)); + return b; + } + if (key >= TB_KEY_0 && key < TB_KEY_0 + 10) { + char* b = one[slot++ & 3]; + snprintf(b, 8, "%c", '0' + (key - TB_KEY_0)); + return b; + } + if (key >= TB_KEY_F1 && key <= TB_KEY_F12) { + char* b = one[slot++ & 3]; + snprintf(b, 8, "f%d", key - TB_KEY_F1 + 1); + return b; + } + for (size_t i = 0; i < sizeof(s_keys) / sizeof(s_keys[0]); i++) + if (s_keys[i].key == key) return s_keys[i].name; + return ""; +} + +/* -- Entradas/saidas ------------------------------------------------------ */ + +static const char* in_text(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { + TinyBlocks_Value v = tb_block_get_input(self, rt, i); + static char num[32]; + if (v.kind == TB_VALUE_TEXT && v.as.text) return v.as.text; + if (v.kind == TB_VALUE_INTEGER) { snprintf(num, sizeof(num), "%lld", (long long)v.as.integer); return num; } + return ""; +} + +static long long in_int(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { + TinyBlocks_Value v = tb_block_get_input(self, rt, i); + if (v.kind == TB_VALUE_INTEGER) return v.as.integer; + if (v.kind == TB_VALUE_REAL) return (long long)llround(v.as.real); + if (v.kind == TB_VALUE_TEXT && v.as.text) return strtoll(v.as.text, NULL, 10); + return 0; +} + +/* Eixo "x"/"y"/"z" (ou 1/2/3) -> 0..2; -1 se invalido */ +static int in_axis(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { + const char* s = in_text(self, rt, i); + while (isspace((unsigned char)*s)) s++; + switch (tolower((unsigned char)*s)) { + case 'x': case '1': return 0; + case 'y': case '2': return 1; + case 'z': case '3': return 2; + default: return -1; + } +} + +/* Numero: inteiro quando exato (como o Scratch mostra "120", nao "120.0") */ +static void out_num(TinyBlocks_Block* self, double x) { + if (x == floor(x) && fabs(x) < 1e15) tb_block_set_output(self, 0, tb_value_integer((int64_t)x)); + else tb_block_set_output(self, 0, tb_value_real(x)); + self->dirty = false; +} + +static void out_bool(TinyBlocks_Block* self, bool b) { + tb_block_set_output(self, 0, tb_value_integer(b ? 1 : 0)); + self->dirty = false; +} + +/* -- Blocos --------------------------------------------------------------- */ + +static void eval_mouse_x(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_num(self, roundf(tb_input_mouse_x())); } +static void eval_mouse_y(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_num(self, roundf(tb_input_mouse_y())); } +static void eval_mouse_down(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_bool(self, tb_input_mouse_down()); } +static void eval_mouse_right(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_bool(self, tb_input_mouse_right_down()); } +static void eval_mouse_over(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_bool(self, tb_input_mouse_over_stage()); } +static void eval_wheel(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_num(self, tb_input_wheel()); } + +static void eval_key_pressed(TinyBlocks_Block* self, TinyBlocks* rt) { + const char* nm = in_text(self, rt, 0); + int k = tb_input_key_from_name(nm); + if (k == 0 && nm[0]) tinyblocks_set_error(rt, "tecla desconhecida: '%s'", nm); + out_bool(self, k < 0 ? tb_input_any_key_held() : tb_input_key_held(k)); +} + +static void eval_last_key(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + tb_block_set_output(self, 0, tb_value_text(tb_input_key_name(tb_input_last_key()))); + self->dirty = false; +} + +static void eval_touch_count(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_num(self, tb_input_touch_count()); } +static void eval_touching(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_bool(self, tb_input_touch_count() > 0); } + +static void eval_touch_x(TinyBlocks_Block* self, TinyBlocks* rt) { + out_num(self, roundf(tb_input_touch_x((int)in_int(self, rt, 0) - 1))); +} +static void eval_touch_y(TinyBlocks_Block* self, TinyBlocks* rt) { + out_num(self, roundf(tb_input_touch_y((int)in_int(self, rt, 0) - 1))); +} + +static void eval_has_accel(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_bool(self, tb_input_has_accel()); } +static void eval_has_gyro(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_bool(self, tb_input_has_gyro()); } + +/* sensores: 2 casas, para nao piscar com o ruido */ +static void eval_accel(TinyBlocks_Block* self, TinyBlocks* rt) { + int a = in_axis(self, rt, 0); + out_num(self, a < 0 ? 0.0 : round(tb_input_accel(a) * 100.0) / 100.0); +} +static void eval_gyro(TinyBlocks_Block* self, TinyBlocks* rt) { + int a = in_axis(self, rt, 0); + out_num(self, a < 0 ? 0.0 : round(tb_input_gyro(a) * 100.0) / 100.0); +} + +static void eval_timer(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + out_num(self, round(tb_input_timer() * 1000.0) / 1000.0); +} +static void eval_reset_timer(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + tb_input_timer_reset(); + self->dirty = false; +} + +/* -- Registro ------------------------------------------------------------- */ + +static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name, + const TinyBlocks_SlotDesc* in, uint32_t ni, + const TinyBlocks_SlotDesc* out, uint32_t no, + void (*fn)(TinyBlocks_Block*, TinyBlocks*)) { + TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, out, no, fn); + return t && tb_library_add(lib, &t->base); +} + +static bool input_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + static const TinyBlocks_Category cat = { + "Sensores", + { 92/255.f, 177/255.f, 214/255.f, 1.f}, + { 46/255.f, 142/255.f, 184/255.f, 1.f}, + }; + tb_library_set_category(lib, &cat); + + TB_BLOCK_META("Input.MouseX", "eval_mouse_x", "Posicao x do mouse no palco (-240 a 240)"); + TB_BLOCK_META("Input.MouseY", "eval_mouse_y", "Posicao y do mouse no palco (-180 a 180)"); + TB_BLOCK_META("Input.MouseDown", "eval_mouse_down", "Verdadeiro enquanto o botao do mouse estiver apertado"); + TB_BLOCK_META("Input.MouseRight", "eval_mouse_right", "Verdadeiro enquanto o botao direito estiver apertado"); + TB_BLOCK_META("Input.MouseOver", "eval_mouse_over", "Verdadeiro se o mouse estiver sobre o palco"); + TB_BLOCK_META("Input.Wheel", "eval_wheel", "Quanto a roda do mouse girou neste quadro"); + TB_BLOCK_META("Input.KeyPressed", "eval_key_pressed", "Verdadeiro enquanto a tecla estiver apertada"); + TB_BLOCK_META("Input.LastKey", "eval_last_key", "Nome da ultima tecla apertada"); + TB_BLOCK_META("Input.TouchCount", "eval_touch_count", "Quantos dedos estao na tela"); + TB_BLOCK_META("Input.Touching", "eval_touching", "Verdadeiro se algum dedo estiver na tela"); + TB_BLOCK_META("Input.TouchX", "eval_touch_x", "Posicao x do toque N no palco"); + TB_BLOCK_META("Input.TouchY", "eval_touch_y", "Posicao y do toque N no palco"); + TB_BLOCK_META("Input.HasAccel", "eval_has_accel", "Verdadeiro se o aparelho tiver acelerometro"); + TB_BLOCK_META("Input.Accel", "eval_accel", "Aceleracao no eixo x, y ou z (m/s², inclui a gravidade)"); + TB_BLOCK_META("Input.HasGyro", "eval_has_gyro", "Verdadeiro se o aparelho tiver giroscopio"); + TB_BLOCK_META("Input.Gyro", "eval_gyro", "Velocidade de giro no eixo x, y ou z (graus por segundo)"); + TB_BLOCK_META("Input.Timer", "eval_timer", "Segundos desde a bandeira verde (ou do ultimo zerar)"); + TB_BLOCK_META("Input.ResetTimer", "eval_reset_timer", "Zera o cronometro"); + + static const TinyBlocks_SlotDesc key_in[] = {{"tecla", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc n_in[] = {{"n", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc axis_in[] = {{"eixo", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc num_out[] = {{"numero", TB_VALUE_NONE}}; + static const TinyBlocks_SlotDesc txt_out[] = {{"texto", TB_VALUE_TEXT}}; + /* saidas terminadas em '?' = blocos booleanos (hexagonais no editor) */ + static const TinyBlocks_SlotDesc down_out[] = {{"pressionado?", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc over_out[] = {{"sobre o palco?", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc key_out[] = {{"pressionada?", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc touch_out[] = {{"tocando?", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc has_out[] = {{"tem?", TB_VALUE_INTEGER}}; + + return reg(rt, lib, "Input.MouseX", NULL, 0, num_out, 1, eval_mouse_x) + && reg(rt, lib, "Input.MouseY", NULL, 0, num_out, 1, eval_mouse_y) + && reg(rt, lib, "Input.MouseDown", NULL, 0, down_out, 1, eval_mouse_down) + && reg(rt, lib, "Input.MouseRight", NULL, 0, down_out, 1, eval_mouse_right) + && reg(rt, lib, "Input.MouseOver", NULL, 0, over_out, 1, eval_mouse_over) + && reg(rt, lib, "Input.Wheel", NULL, 0, num_out, 1, eval_wheel) + && reg(rt, lib, "Input.KeyPressed", key_in, 1, key_out, 1, eval_key_pressed) + && reg(rt, lib, "Input.LastKey", NULL, 0, txt_out, 1, eval_last_key) + && reg(rt, lib, "Input.Touching", NULL, 0, touch_out, 1, eval_touching) + && reg(rt, lib, "Input.TouchCount", NULL, 0, num_out, 1, eval_touch_count) + && reg(rt, lib, "Input.TouchX", n_in, 1, num_out, 1, eval_touch_x) + && reg(rt, lib, "Input.TouchY", n_in, 1, num_out, 1, eval_touch_y) + && reg(rt, lib, "Input.HasAccel", NULL, 0, has_out, 1, eval_has_accel) + && reg(rt, lib, "Input.Accel", axis_in, 1, num_out, 1, eval_accel) + && reg(rt, lib, "Input.HasGyro", NULL, 0, has_out, 1, eval_has_gyro) + && reg(rt, lib, "Input.Gyro", axis_in, 1, num_out, 1, eval_gyro) + && reg(rt, lib, "Input.Timer", NULL, 0, num_out, 1, eval_timer) + && reg(rt, lib, "Input.ResetTimer", NULL, 0, NULL, 0, eval_reset_timer); +} + +static void input_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + (void)rt; (void)lib; +} + +TINYBLOCKS_DEFINE_LIBRARY(input, + "tinyblocks-input", + "1.0.0", + input_init, + input_deinit) + +const TinyBlocks_LibraryDescriptor* tb_input_get_library(void) { + return &_tb_lib_desc_input; +} diff --git a/libraries/tinyblocks-sdl2/src/tb_sdl2.c b/libraries/tinyblocks-sdl2/src/tb_sdl2.c index b4c532b..9210d36 100644 --- a/libraries/tinyblocks-sdl2/src/tb_sdl2.c +++ b/libraries/tinyblocks-sdl2/src/tb_sdl2.c @@ -398,6 +398,7 @@ typedef struct SdlWin { SDL_Renderer* ren; Uint32 id; TinyBlocks_GfxInput in; + int pos_fresh; /* posicao do mouse veio de um evento neste quadro */ struct SdlWin* next; } SdlWin; @@ -439,6 +440,24 @@ static SdlWin* win_by_id(Uint32 id) { return NULL; } +/* Sensores do dispositivo (celular/tablet; no desktop costuma nao haver) */ +static SDL_Sensor* s_accel = NULL; +static SDL_Sensor* s_gyro = NULL; + +static void sensors_open(void) { + if (SDL_InitSubSystem(SDL_INIT_SENSOR) != 0) return; + for (int i = 0; i < SDL_NumSensors(); i++) { + SDL_SensorType t = SDL_SensorGetDeviceType(i); + if (t == SDL_SENSOR_ACCEL && !s_accel) s_accel = SDL_SensorOpen(i); + if (t == SDL_SENSOR_GYRO && !s_gyro) s_gyro = SDL_SensorOpen(i); + } +} + +static void sensors_close(void) { + if (s_accel) { SDL_SensorClose(s_accel); s_accel = NULL; } + if (s_gyro) { SDL_SensorClose(s_gyro); s_gyro = NULL; } +} + static bool be_init(void) { if (s_be_inited) return true; if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0) { @@ -452,6 +471,7 @@ static bool be_init(void) { } SDL_EventState(SDL_DROPFILE, SDL_ENABLE); SDL_StartTextInput(); + sensors_open(); s_be_inited = true; return true; } @@ -468,6 +488,7 @@ static void be_window_close(void* handle) { static void be_shutdown(void) { if (!s_be_inited) return; while (s_wins) be_window_close(s_wins); + sensors_close(); fonts_close_all(); TTF_Quit(); SDL_Quit(); @@ -512,6 +533,9 @@ static bool s_has_pending = false; static bool be_apply(SDL_Event* ev) { SdlWin* w = NULL; switch (ev->type) { + case SDL_QUIT: /* SIGTERM/Ctrl+C ou o SO pediu para sair */ + for (w = s_wins; w; w = w->next) w->in.close = 1; + break; case SDL_WINDOWEVENT: if ((w = win_by_id(ev->window.windowID)) && ev->window.event == SDL_WINDOWEVENT_CLOSE) w->in.close = 1; @@ -520,6 +544,7 @@ static bool be_apply(SDL_Event* ev) { if ((w = win_by_id(ev->motion.windowID))) { w->in.mouse_x = (float)ev->motion.x; w->in.mouse_y = (float)ev->motion.y; + w->pos_fresh = 1; } break; case SDL_MOUSEBUTTONDOWN: @@ -528,6 +553,7 @@ static bool be_apply(SDL_Event* ev) { bool down = ev->type == SDL_MOUSEBUTTONDOWN; w->in.mouse_x = (float)ev->button.x; w->in.mouse_y = (float)ev->button.y; + w->pos_fresh = 1; /* clique repetido no mesmo quadro: espera o proximo */ if (ev->button.button == SDL_BUTTON_LEFT && (down ? w->in.l_down : w->in.l_up)) return false; if (ev->button.button == SDL_BUTTON_LEFT) { if (down) w->in.l_down = 1; else w->in.l_up = 1; } @@ -580,6 +606,7 @@ static void be_poll(void) { in->text[0] = 0; in->drop_file[0] = 0; in->close = 0; + w->pos_fresh = 0; } if (s_has_pending) { @@ -591,6 +618,36 @@ static void be_poll(void) { if (!be_apply(&ev)) { s_pending = ev; s_has_pending = true; } } + /* Dispositivo: teclas seguradas (janela com o foco do teclado), dedos na + tela e sensores (todas as janelas) */ + SDL_Window* kfocus = SDL_GetKeyboardFocus(); + int nkeys = 0; + const Uint8* ks = SDL_GetKeyboardState(&nkeys); + unsigned char held[128]; + memset(held, 0, sizeof(held)); + for (int sc = 0; ks && sc < nkeys; sc++) { + if (!ks[sc]) continue; + int k = map_key((SDL_Scancode)sc); + if (k > 0 && k < 128) held[k] = 1; + } + float tx[GFX_MAX_TOUCHES], ty[GFX_MAX_TOUCHES]; /* 0..1 na janela */ + int tn = 0; + for (int d = 0; d < SDL_GetNumTouchDevices(); d++) { + SDL_TouchID tid = SDL_GetTouchDevice(d); + for (int f = 0; f < SDL_GetNumTouchFingers(tid) && tn < GFX_MAX_TOUCHES; f++) { + SDL_Finger* fg = SDL_GetTouchFinger(tid, f); + if (fg) { tx[tn] = fg->x; ty[tn] = fg->y; tn++; } + } + } + float acc[3] = {0, 0, 0}, gyr[3] = {0, 0, 0}; + bool has_acc = s_accel && SDL_SensorGetData(s_accel, acc, 3) == 0; + bool has_gyr = s_gyro && SDL_SensorGetData(s_gyro, gyr, 3) == 0; + + /* Mouse na tela: consulta direta, confiavel mesmo logo depois de o + gerenciador de janelas mover a janela (a posicao local do SDL atrasa) */ + int gmx = 0, gmy = 0; + SDL_GetGlobalMouseState(&gmx, &gmy); + /* Estado contínuo: botões segurados só valem na janela com o foco do mouse */ SDL_Window* focus = SDL_GetMouseFocus(); int mx, my; @@ -598,11 +655,28 @@ static void be_poll(void) { int mods = map_mod((Uint16)SDL_GetModState()); for (SdlWin* w = s_wins; w; w = w->next) { bool f = w->win == focus; - if (f) { w->in.mouse_x = (float)mx; w->in.mouse_y = (float)my; } + /* a posicao do evento vale mais: o estado global fica velho quando a + janela acabou de ganhar o foco com aquele mesmo clique */ + if (f && !w->pos_fresh) { w->in.mouse_x = (float)mx; w->in.mouse_y = (float)my; } w->in.l_held = f && (btns & SDL_BUTTON_LMASK) ? 1 : 0; w->in.r_held = f && (btns & SDL_BUTTON_RMASK) ? 1 : 0; w->in.mod_state = mods; SDL_GetWindowSize(w->win, &w->in.win_w, &w->in.win_h); + SDL_GetWindowPosition(w->win, &w->in.win_x, &w->in.win_y); + w->in.gmouse_x = (float)gmx; + w->in.gmouse_y = (float)gmy; + w->in.mouse_in = f ? 1 : 0; + if (w->win == kfocus) memcpy(w->in.keys_held, held, sizeof(held)); + else memset(w->in.keys_held, 0, sizeof(w->in.keys_held)); + w->in.touch_n = (w->win == kfocus || w->win == focus) ? tn : 0; + for (int i = 0; i < w->in.touch_n; i++) { + w->in.touch_x[i] = tx[i] * (float)w->in.win_w; + w->in.touch_y[i] = ty[i] * (float)w->in.win_h; + } + w->in.has_accel = has_acc; + w->in.has_gyro = has_gyr; + memcpy(w->in.accel, acc, sizeof(acc)); + memcpy(w->in.gyro, gyr, sizeof(gyr)); } } diff --git a/src/tb_input.c b/src/tb_input.c new file mode 100644 index 0000000..fa163d5 --- /dev/null +++ b/src/tb_input.c @@ -0,0 +1,122 @@ +/* + * TinyBlocks - tb_input.c + * Estado de entrada em coordenadas do palco (ver tb_input.h). + */ +#define _POSIX_C_SOURCE 200809L +#include +#include + +#include "tinyblocks/tb_input.h" +#include "tinyblocks/tb_stage.h" + +#define HALF_W 240.f +#define HALF_H 180.f +#define RAD2DEG 57.29577951308232f + +typedef struct { + float mx, my; /* palco, sem prender */ + bool over, left, right; + float wheel; + unsigned char keys[TB_INPUT_MAX_KEYS]; + int last_key; + int touch_n; + float tx[TB_INPUT_MAX_TOUCHES], ty[TB_INPUT_MAX_TOUCHES]; + bool has_accel, has_gyro; + float accel[3], gyro[3]; + double timer_t0; + bool timer_started; +} InputState; + +static InputState s_in; + +static double now_s(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9; +} + +static float clampf(float v, float lo, float hi) { return v < lo ? lo : v > hi ? hi : v; } + +/* -- Alimentacao --- */ + +void tb_input_begin_frame(void) { + s_in.wheel = 0.f; +} + +void tb_input_set_mouse(float vx, float vy, bool left, bool right) { + s_in.over = tb_stage_view_to_stage(vx, vy, &s_in.mx, &s_in.my); + s_in.left = left; + s_in.right = right; +} + +void tb_input_add_wheel(float dy) { s_in.wheel += dy; } + +void tb_input_clear_keys(void) { memset(s_in.keys, 0, sizeof(s_in.keys)); } + +void tb_input_set_key(int key, bool held) { + if (key > 0 && key < TB_INPUT_MAX_KEYS) s_in.keys[key] = held ? 1 : 0; +} + +void tb_input_key_pressed(int key) { + if (key > 0 && key < TB_INPUT_MAX_KEYS) s_in.last_key = key; +} + +void tb_input_set_touches(int n, const float* vx, const float* vy) { + if (n < 0) n = 0; + if (n > TB_INPUT_MAX_TOUCHES) n = TB_INPUT_MAX_TOUCHES; + s_in.touch_n = n; + for (int i = 0; i < n; i++) tb_stage_view_to_stage(vx[i], vy[i], &s_in.tx[i], &s_in.ty[i]); +} + +void tb_input_set_accel(bool has, float x, float y, float z) { + s_in.has_accel = has; + s_in.accel[0] = has ? x : 0.f; s_in.accel[1] = has ? y : 0.f; s_in.accel[2] = has ? z : 0.f; +} + +void tb_input_set_gyro(bool has, float x, float y, float z) { + s_in.has_gyro = has; + s_in.gyro[0] = has ? x : 0.f; s_in.gyro[1] = has ? y : 0.f; s_in.gyro[2] = has ? z : 0.f; +} + +void tb_input_reset(void) { + memset(&s_in, 0, sizeof(s_in)); +} + +/* -- Leitura --- */ + +float tb_input_mouse_x(void) { return clampf(s_in.mx, -HALF_W, HALF_W); } +float tb_input_mouse_y(void) { return clampf(s_in.my, -HALF_H, HALF_H); } +bool tb_input_mouse_over_stage(void) { return s_in.over; } +bool tb_input_mouse_down(void) { return s_in.left; } +bool tb_input_mouse_right_down(void) { return s_in.right; } +float tb_input_wheel(void) { return s_in.wheel; } + +bool tb_input_key_held(int key) { + return key > 0 && key < TB_INPUT_MAX_KEYS && s_in.keys[key]; +} + +bool tb_input_any_key_held(void) { + for (int k = 1; k < TB_INPUT_MAX_KEYS; k++) if (s_in.keys[k]) return true; + return false; +} + +int tb_input_last_key(void) { return s_in.last_key; } + +int tb_input_touch_count(void) { return s_in.touch_n; } +float tb_input_touch_x(int i) { return (i >= 0 && i < s_in.touch_n) ? s_in.tx[i] : 0.f; } +float tb_input_touch_y(int i) { return (i >= 0 && i < s_in.touch_n) ? s_in.ty[i] : 0.f; } + +bool tb_input_has_accel(void) { return s_in.has_accel; } +float tb_input_accel(int axis) { return (axis >= 0 && axis < 3) ? s_in.accel[axis] : 0.f; } +bool tb_input_has_gyro(void) { return s_in.has_gyro; } +float tb_input_gyro(int axis) { return (axis >= 0 && axis < 3) ? s_in.gyro[axis] * RAD2DEG : 0.f; } + +double tb_input_timer(void) { + if (!s_in.timer_started) { s_in.timer_t0 = now_s(); s_in.timer_started = true; } + return now_s() - s_in.timer_t0; +} + +void tb_input_timer_reset(void) { + s_in.timer_t0 = now_s(); + s_in.timer_started = true; +} diff --git a/src/tb_stage.c b/src/tb_stage.c index 56bb586..748720c 100644 --- a/src/tb_stage.c +++ b/src/tb_stage.c @@ -124,6 +124,18 @@ void tb_stage_set_view(float w, float h) { if (w > 0 && h > 0) { s_stage.view_w = w; s_stage.view_h = h; } } +bool tb_stage_view_to_stage(float vx, float vy, float* sx, float* sy) { + const Stage* s = &s_stage; + float sc = s->view_w / STAGE_W < s->view_h / STAGE_H ? s->view_w / STAGE_W : s->view_h / STAGE_H; + if (sc <= 0.f) sc = 1.f; + float ox = (s->view_w - STAGE_W*sc) * 0.5f, oy = (s->view_h - STAGE_H*sc) * 0.5f; + float x = (vx - ox) / sc - STAGE_W * 0.5f; + float y = STAGE_H * 0.5f - (vy - oy) / sc; + if (sx) *sx = x; + if (sy) *sy = y; + return x >= -STAGE_W * 0.5f && x <= STAGE_W * 0.5f && y >= -STAGE_H * 0.5f && y <= STAGE_H * 0.5f; +} + void tb_stage_reset(void) { free(s_stage.cmds); s_stage.cmds = NULL; s_stage.n = 0; s_stage.cap = 0; diff --git a/tests/editor_harness.c b/tests/editor_harness.c index 27d4a9a..fac8a1c 100644 --- a/tests/editor_harness.c +++ b/tests/editor_harness.c @@ -1,3 +1,4 @@ +#define _POSIX_C_SOURCE 200809L /* Harness headless do editor: dirige Editor.Scene com um bloco de eventos * falso e inspeciona os comandos de desenho produzidos por on_draw. */ #include @@ -19,6 +20,8 @@ #include #include #include +#include +#include static TinyBlocks* rt; static TinyBlocks_Block *ev, *scene; @@ -93,9 +96,10 @@ static bool stage_has(const char* s) { if (cmds[i].kind == TB_DRAW_TEXT && cmds[i].x >= 920 && strstr(cmds[i].text, s)) return true; return false; } +/* Mensagens de status: palco/saída ou avisos flutuantes (toasts), em qualquer lugar */ static bool any_has(const char* s) { for (uint32_t i = 0; i < ncmd; i++) - if (cmds[i].kind == TB_DRAW_TEXT && cmds[i].x >= 920 && strstr(cmds[i].text, s)) return true; + if (cmds[i].kind == TB_DRAW_TEXT && strstr(cmds[i].text, s)) return true; return false; } static bool ws_has(const char* s) { @@ -192,6 +196,10 @@ static bool need(const char* s, int region, int nth, float* x, float* y) { } int main(void) { + /* configurações isoladas: o harness não lê nem grava o ~/.config real */ + setenv("XDG_CONFIG_HOME", "/tmp/tb_harness_cfg", 1); + unsetenv("TINYBLOCKS_SETTINGS"); + remove("/tmp/tb_harness_cfg/tinyblocks/settings.csv"); tinyblocks_init(&rt, NULL); tb_graphics_set_backend(tb_graphics_null_backend()); tb_library_register(rt, tb_events_get_library()); @@ -203,6 +211,7 @@ int main(void) { tb_library_register(rt, tb_curves_get_library()); tb_library_register(rt, tb_base64_get_library()); tb_library_register(rt, tb_ppm_get_library()); + tb_library_register(rt, tb_input_get_library()); tb_library_register(rt, tb_graphics_get_library()); tb_library_register(rt, tb_editor_get_library()); (void)eval_ev; @@ -370,10 +379,22 @@ int main(void) { CHECK(circles == circles_before, "\"apague tudo\" limpa o palco"); /* 11. Destacar o palco numa janela própria e recolher de volta */ - click(1280 - 50 + 20, 44 + 22); - CHECK(any_has("Palco aberto em outra janela"), "palco destacado abre janela própria"); - click(1280 - 50 + 20, 44 + 22); - CHECK(!any_has("Palco aberto em outra janela"), "palco recolhido volta ao painel"); + { + click(1280 - 50 + 20, 44 + 22); + frame(0, 0, 0, 0, 0, 0, NULL); + /* a área do palco sai da janela principal; fica um botão "Palco" no menu */ + bool no_menu = false, no_painel = false; + float cx = 0, cy = 0; + for (uint32_t i = 0; i < ncmd; i++) { + if (cmds[i].kind != TB_DRAW_TEXT || strcmp(cmds[i].text, "Palco") != 0) continue; + if (cmds[i].y < 44) { no_menu = true; cx = cmds[i].x + 3; cy = 22; } + else no_painel = true; + } + CHECK(no_menu && !no_painel, "palco destacado abre janela própria (botão \"Palco\" no menu)"); + if (no_menu) click(cx, cy); /* recolhe no próximo quadro */ + frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(find("Palco", R_ANY, 0, &x, &y) && x > 920 && y > 44, "palco recolhido volta ao painel"); + } /* 12. Salvar e abrir projeto (.json) via tinyblocks-blueprint */ const char* proj = "/tmp/tb_harness_proj.json"; @@ -383,6 +404,22 @@ int main(void) { type(proj); key(TB_KEY_RETURN, 0, 0); CHECK(any_has("Projeto salvo"), "salvar projeto escreve o .json"); + { + /* aviso flutuante (toast) sobre a área de scripts, não no menu */ + bool flutua = false; + for (uint32_t i = 0; i < ncmd; i++) + if (cmds[i].kind == TB_DRAW_TEXT && strstr(cmds[i].text, "Projeto salvo") && + cmds[i].x > 318 && cmds[i].x < 920 && cmds[i].y > 400) flutua = true; + CHECK(flutua, "mensagem vira aviso flutuante no canto da área de scripts"); + /* salvar de novo: a mesma mensagem vira contador (x2) */ + if (need("Salvar", R_FLY, 0, &x, &y)) click(x, y); + for (int i = 0; i < 40; i++) key(TB_KEY_BACKSPACE, 0, 0); + type(proj); + key(TB_KEY_RETURN, 0, 0); + if (find("Substituir", R_ANY, 0, &x, &y)) click(x, y); + frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(any_has("(x2)"), "mensagem repetida vira contador (x2)"); + } 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(proj); @@ -546,6 +583,45 @@ int main(void) { remove(fj); } + /* 13e. Sensores: posição do mouse no palco e última tecla, num "sempre" */ + { + const char* sj = "/tmp/tb_harness_sensores.json"; + FILE* sf = fopen(sj, "wb"); + if (sf) { + fputs("{\"format\":\"tinyblocks-project\",\"version\":1,\"cur_tab\":0," + "\"tabs\":[{\"name\":\"Sensores\",\"composite\":false,\"comp_id\":-1,\"color\":0," + "\"blocks\":[" + "{\"i\":0,\"type\":\"Events.WhenRun\",\"x\":40,\"y\":40,\"next\":1}," + "{\"i\":1,\"type\":\"Control.Forever\",\"x\":40,\"y\":100,\"parent\":0,\"prel\":0,\"sub\":[2,-1]}," + "{\"i\":2,\"type\":\"Stage.Clear\",\"x\":0,\"y\":0,\"parent\":1,\"prel\":1,\"next\":3}," + "{\"i\":3,\"type\":\"IO.Print\",\"x\":0,\"y\":0,\"parent\":2,\"prel\":0,\"args\":[4,5]}," + "{\"i\":4,\"type\":\"Input.MouseX\",\"x\":0,\"y\":0,\"parent\":3,\"prel\":3}," + "{\"i\":5,\"type\":\"Input.LastKey\",\"x\":0,\"y\":0,\"parent\":3,\"prel\":4}" + "],\"top\":[0]}],\"user_blocks\":[],\"variables\":[]}", sf); + fclose(sf); + } + 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(sj); + key(TB_KEY_RETURN, 0, 0); + frame(0, 0, 0, 0, 0, 0, NULL); + flag(); + /* vista do palco no painel: origem (929, 89), 342 px = 480 do palco; + x do palco 100 -> 929 + 171 + 100 * 342/480 */ + float px = 929.f + 171.f + 100.f * 342.f / 480.f, py = 89.f + 100.f; + for (int i = 0; i < 3; i++) frame(px, py, 0, 0, 0, 0, NULL); + CHECK(stage_has("100"), "posição x do mouse sobre o palco = 100"); + if (!stage_has("100")) + for (uint32_t i = 0; i < ncmd; i++) + if (cmds[i].kind == TB_DRAW_TEXT && cmds[i].x >= 920) printf(" palco: '%s'\n", cmds[i].text); + frame(px, py, 0, 0, 0, TB_KEY_SPACE, NULL); + for (int i = 0; i < 3; i++) frame(px, py, 0, 0, 0, 0, NULL); + CHECK(stage_has("espaço"), "última tecla = espaço"); + click(1280 - 360 + 76, 44 + 22); /* botão vermelho */ + frame(0, 0, 0, 0, 0, 0, NULL); + remove(sj); + } + /* 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) @@ -705,6 +781,7 @@ int main(void) { CHECK(ws_has("int"), "aba de codigo realca 'int' (palavra-chave)"); CHECK(ws_has("42"), "aba de codigo realca o numero 42"); CHECK(ws_has(";"), "aba de codigo realca a pontuacao"); + CHECK(!any_has(""), "aba de codigo nao mostra a marcacao "); } /* 23. Botao "+" -> nova aba: Edicao de Imagem */ @@ -797,6 +874,82 @@ int main(void) { CHECK(img_nonwhite() > 0, "camada pode ser mostrada de novo"); } + /* 22. Áreas estilo Blender: redimensionar arrastando a borda, trocar de lugar pela alça */ + { + frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(find("Blocos", R_ANY, 0, &x, &y) && x < 100, "paleta tem cabeçalho \"Blocos\" com alça"); + /* borda paleta | scripts em x = 318: arrasta 100 px para a direita */ + drag(318, 400, 418, 400); + frame(0, 0, 0, 0, 0, 0, NULL); + bool largo = false; + for (uint32_t i = 0; i < ncmd; i++) + if (cmds[i].kind == TB_DRAW_SET_CLIP && cmds[i].x == 68 && cmds[i].w > 340) largo = true; + CHECK(largo, "arrastar a borda alarga a paleta (418 px)"); + float px0 = 0, py0 = 0; + CHECK(find("Palco", R_ANY, 0, &px0, &py0) && px0 > 920, "palco continua na direita"); + /* alça do palco (ao lado do botão de destacar) -> solta sobre os scripts */ + drag(1280 - 50 - 18 - 8 + 9, 44 + 22, 640, 400); + frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(find("Palco", R_ANY, 0, &x, &y) && x > 418 && x < 900, "alça troca o palco com a área de scripts"); + /* e de volta: a alça do palco agora está no meio da tela */ + drag(418 + (1280 - 360 - 418) - 50 - 18 - 8 + 9, 44 + 22, 1100, 200); /* scripts, em cima à direita */ + frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(find("Palco", R_ANY, 0, &x, &y) && x > 920, "trocar de novo devolve o palco à direita"); + /* layout salvo nas configurações (arquivo isolado do harness) */ + CHECK(!strcmp(tb_environ_get("editor.layout"), "H0:418(p,H1:360(s,V0:310(t,o)))"), + "layout salvo em editor.layout (paleta com 418 px)"); + FILE* cf = fopen("/tmp/tb_harness_cfg/tinyblocks/settings.csv", "rb"); + char cbuf[1024] = ""; + if (cf) { size_t n = fread(cbuf, 1, sizeof(cbuf) - 1, cf); cbuf[n] = 0; fclose(cf); } + CHECK(strstr(cbuf, "editor.layout") != NULL, "layout gravado no arquivo de configurações"); + } + + /* 23. Abas: arrastar na barra reordena (como no navegador) */ + { + frame(0, 0, 0, 0, 0, 0, NULL); + /* rótulos das abas na barra (y 44..80), em ordem de x */ + char nomes[8][64]; float xs[8]; int n = 0; + for (uint32_t i = 0; i < ncmd && n < 8; i++) { + if (cmds[i].kind != TB_DRAW_TEXT || cmds[i].y < 50 || cmds[i].y > 80) continue; + if (cmds[i].x < 318 || cmds[i].x > 900 || !strcmp(cmds[i].text, "=") || !strcmp(cmds[i].text, "+")) continue; + snprintf(nomes[n], 64, "%s", cmds[i].text); xs[n] = cmds[i].x; n++; + } + CHECK(n >= 2, "há pelo menos duas abas para reordenar"); + if (n >= 2) { + char primeira[64]; snprintf(primeira, 64, "%s", nomes[0]); + float sx = xs[0] + 10; + drag(sx, 62, sx + 150 + 20, 62); /* passa do meio da vizinha */ + frame(0, 0, 0, 0, 0, 0, NULL); + float nx = 0, ny = 0; + bool achou = false; + for (uint32_t i = 0; i < ncmd; i++) + if (cmds[i].kind == TB_DRAW_TEXT && !strcmp(cmds[i].text, primeira) && cmds[i].y > 50 && cmds[i].y < 80) { + nx = cmds[i].x; ny = cmds[i].y; achou = true; + } + (void)ny; + CHECK(achou && nx > xs[1] - 20, "arrastar a aba para a direita troca a ordem com a vizinha"); + + /* arrastar a aba para longe da barra destaca numa janela própria */ + drag(nx + 10, 62, nx + 10, 400); + frame(0, 0, 0, 0, 0, 0, NULL); + bool na_barra = false, no_menu = false; + float mxp = 0; + for (uint32_t i = 0; i < ncmd; i++) { + if (cmds[i].kind != TB_DRAW_TEXT || strcmp(cmds[i].text, primeira) != 0) continue; + if (cmds[i].y > 50 && cmds[i].y < 80) na_barra = true; + if (cmds[i].y < 44) { no_menu = true; mxp = cmds[i].x + 3; } + } + CHECK(!na_barra && no_menu, "aba arrastada para fora vira janela (botão no menu)"); + if (no_menu) click(mxp, 22); /* volta para a barra */ + frame(0, 0, 0, 0, 0, 0, NULL); + na_barra = false; + for (uint32_t i = 0; i < ncmd; i++) + if (cmds[i].kind == TB_DRAW_TEXT && !strcmp(cmds[i].text, primeira) && cmds[i].y > 50 && cmds[i].y < 80) + na_barra = true; + CHECK(na_barra, "botão no menu traz a aba de volta para a barra"); + } + } + printf("comandos de desenho no último frame: %u\n", ncmd); tinyblocks_deinit(&rt); printf(fails ? "\n%d FALHA(S)\n" : "\nTUDO OK\n", fails); diff --git a/tests/input_test.c b/tests/input_test.c new file mode 100644 index 0000000..3927647 --- /dev/null +++ b/tests/input_test.c @@ -0,0 +1,124 @@ +/* + * input_test.c - testa o estado de entrada do core (tb_input) e os blocos + * de Sensores da tinyblocks-input: mouse em coordenadas do palco, teclas + * por nome, toques, sensores e cronometro. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int fails = 0; +#define CHECK(c, m) do { if (c) printf("ok %s\n", m); else { printf("FAIL %s\n", m); fails++; } } while (0) + +static TinyBlocks* rt; +static TinyBlocks_Block* last; + +static TinyBlocks_Value* run(const char* type, const char* arg) { + if (last) { tb_block_destroy(last, rt); last = NULL; } + TinyBlocks_TypeBlock* t = tb_rt_find_type(rt, type); + if (!t) { printf(" (tipo %s nao existe)\n", type); return NULL; } + last = tb_block_create(rt, t); + if (arg) { + TinyBlocks_Value v = t->input_descs[0].expected_kind == TB_VALUE_INTEGER + ? tb_value_integer(atoll(arg)) : tb_value_text(arg); + tb_block_set_default(last, 0, v); + tb_value_free(&v); + } + tb_block_eval(last, rt); + return last->output_count ? &last->outputs[0] : NULL; +} + +static long long num(TinyBlocks_Value* v) { + if (!v) return -99999; + if (v->kind == TB_VALUE_INTEGER) return v->as.integer; + if (v->kind == TB_VALUE_REAL) return llround(v->as.real); + return -99999; +} +static double real(TinyBlocks_Value* v) { + if (!v) return -99999; + return v->kind == TB_VALUE_REAL ? v->as.real : v->kind == TB_VALUE_INTEGER ? (double)v->as.integer : -99999; +} + +int main(void) { + tinyblocks_init(&rt, NULL); + TinyBlocks_LibraryBlock* lib = tb_library_register(rt, tb_input_get_library()); + CHECK(lib && !strcmp(tb_library_category(lib)->name, "Sensores"), "categoria 'Sensores'"); + + /* vista 480x360 = palco 1:1; (240,180) da vista = centro do palco */ + tb_stage_set_view(480, 360); + tb_input_reset(); + tb_input_begin_frame(); + tb_input_set_mouse(240, 180, false, false); + CHECK(num(run("Input.MouseX", NULL)) == 0 && num(run("Input.MouseY", NULL)) == 0, + "centro da vista = (0, 0) do palco"); + tb_input_set_mouse(480, 0, true, false); + CHECK(num(run("Input.MouseX", NULL)) == 240 && num(run("Input.MouseY", NULL)) == 180, + "canto superior direito = (240, 180), y para cima"); + CHECK(num(run("Input.MouseDown", NULL)) == 1, "mouse pressionado?"); + tb_input_set_mouse(900, 500, false, false); + CHECK(num(run("Input.MouseX", NULL)) == 240 && num(run("Input.MouseOver", NULL)) == 0, + "fora do palco: posição presa na borda e 'sobre o palco?' falso"); + + /* vista maior com faixas (letterbox): 960x540 -> escala 1.5, faixas laterais */ + tb_stage_set_view(960, 540); + tb_input_set_mouse(480, 270, false, false); + CHECK(num(run("Input.MouseX", NULL)) == 0 && num(run("Input.MouseY", NULL)) == 0, + "letterbox: centro continua (0, 0)"); + tb_input_set_mouse(120 + 720, 270, false, false); + CHECK(num(run("Input.MouseX", NULL)) == 240, "letterbox: borda direita do palco = 240"); + tb_stage_set_view(480, 360); + + /* teclado */ + CHECK(tb_input_key_from_name("espaço") == TB_KEY_SPACE && tb_input_key_from_name("Space") == TB_KEY_SPACE && + tb_input_key_from_name("seta para cima") == TB_KEY_UP && tb_input_key_from_name("a") == TB_KEY_A && + tb_input_key_from_name("7") == TB_KEY_0 + 7 && tb_input_key_from_name("qualquer") == -1 && + tb_input_key_from_name("f5") == TB_KEY_F5, "nomes de tecla (PT/EN, letras, números, F)"); + tb_input_clear_keys(); + tb_input_set_key(TB_KEY_SPACE, true); + CHECK(num(run("Input.KeyPressed", "espaço")) == 1, "tecla espaço pressionada?"); + CHECK(num(run("Input.KeyPressed", "a")) == 0, "tecla a não pressionada"); + CHECK(num(run("Input.KeyPressed", "qualquer")) == 1, "qualquer tecla"); + tb_input_clear_keys(); + CHECK(num(run("Input.KeyPressed", "qualquer")) == 0, "soltou todas"); + tb_input_key_pressed(TB_KEY_UP); + TinyBlocks_Value* lk = run("Input.LastKey", NULL); + CHECK(lk && lk->kind == TB_VALUE_TEXT && !strcmp(lk->as.text, "seta para cima"), "última tecla em português"); + + /* toque */ + float tx[2] = {240, 0}, ty[2] = {180, 0}; + tb_input_set_touches(2, tx, ty); + CHECK(num(run("Input.TouchCount", NULL)) == 2 && num(run("Input.Touching", NULL)) == 1, "dois dedos na tela"); + CHECK(num(run("Input.TouchX", "2")) == -240 && num(run("Input.TouchY", "2")) == 180, "toque 2 no canto (-240, 180)"); + tb_input_set_touches(0, NULL, NULL); + CHECK(num(run("Input.Touching", NULL)) == 0, "sem toque"); + + /* sensores */ + CHECK(num(run("Input.HasAccel", NULL)) == 0 && num(run("Input.HasGyro", NULL)) == 0, "sem sensores por padrão"); + tb_input_set_accel(true, 0.5f, -9.81f, 0.f); + tb_input_set_gyro(true, 0.f, 0.f, 3.14159265f); + CHECK(num(run("Input.HasAccel", NULL)) == 1 && fabs(real(run("Input.Accel", "y")) + 9.81) < 1e-6, + "acelerômetro y = -9.81"); + CHECK(fabs(real(run("Input.Gyro", "z")) - 180.0) < 0.01, "giroscópio em graus/s (pi rad/s = 180)"); + + /* cronômetro */ + run("Input.ResetTimer", NULL); + double t = real(run("Input.Timer", NULL)); + CHECK(t >= 0 && t < 0.5, "zere o cronômetro"); + + /* booleanos declarados com '?' */ + TinyBlocks_TypeBlock* tk = tb_rt_find_type(rt, "Input.KeyPressed"); + CHECK(tk && tk->output_descs[0].name[strlen(tk->output_descs[0].name) - 1] == '?', + "tecla pressionada? é booleano ('?')"); + + if (last) tb_block_destroy(last, rt); + tinyblocks_deinit(&rt); + if (fails) printf("\n%d FALHA(S)\n", fails); + else printf("\nTUDO OK\n"); + return fails != 0; +}