diff --git a/Makefile b/Makefile index be64435..4c1b081 100644 --- a/Makefile +++ b/Makefile @@ -399,6 +399,9 @@ appimage: appdir ## Gera o AppImage portatil (build/TinyBlocks-*.AppImage) run-appimage: appimage ## Gera e abre o AppImage ./$(APPIMAGE) +# ── Empacotamento Windows (.exe com MinGW) ────────────────────────────── +include packaging/windows/win.mk + icon: ## (Re)gera o icone do AppImage (packaging/tinyblocks.png) python3 $(PKG_DIR)/make_icon.py diff --git a/docs/build-e-testes.md b/docs/build-e-testes.md index 989bf9b..ad0459f 100644 --- a/docs/build-e-testes.md +++ b/docs/build-e-testes.md @@ -24,6 +24,7 @@ Makefile). | `make editor` / `make run-editor` | `build/editor` (o host do editor) / compila e abre. | | `make ed-modules` | Só as libraries privadas do editor (para hot reload com o editor aberto). | | `make appdir`, `make appimage`, `make run-appimage` | Monta `build/TinyBlocks.AppDir` e gera `build/TinyBlocks-0.1.0-x86_64.AppImage` (baixa o `appimagetool` na primeira vez). | +| `make exe`, `make run-exe`, `make clean-exe` | Gera `build/win-x86_64/TinyBlocks/TinyBlocks.exe` (com as DLLs) e `build/TinyBlocks-0.1.0-win64.zip`; abre no Wine; apaga a build Windows. | | `make icon` | Regera `packaging/tinyblocks.png`. | | `make mylib`, `vector`, `json`, `customappearance`, `python-lib`, `mcp-lib` | Plugins de exemplo. | | `make bench-vm BENCH=projeto.json` | Mede a VM do editor num projeto (abaixo). | @@ -48,6 +49,42 @@ do editor para `usr/lib/tinyblocks-editor/` e cada library de põe `usr/lib` no `LD_LIBRARY_PATH`, define `TINYBLOCKS_APPDIR` e roda o editor. +## Windows (.exe) + +`make exe` compila o editor para Windows a partir do Linux, com o MinGW-w64 +(`x86_64-w64-mingw32-gcc-posix`, pacote `gcc-mingw-w64`). O alvo fica em +`packaging/windows/win.mk`, incluído pelo Makefile da raiz. + +| Peça | O que faz | +|---|---| +| `msys2_deps.py` | Baixa do repositório do MSYS2 os pacotes MinGW (SDL2, SDL2_ttf, libpng, freetype, openssl, zlib, libsystre, ca-certificates) com as dependências, lidas do índice `mingw64.db`, e extrai em `build/.win-deps/`. Só baixa uma vez (cache em `build/.win-deps/cache`). | +| `compat/` | O POSIX que o MinGW não tem: `dlfcn.h` (sobre `LoadLibrary`), `pwd.h`, `sys/utsname.h` e `tb_win_compat.h` (`mkdir` com modo, `sysconf`, `setenv`, `readlink("/proc/self/exe")`, `strndup`, `getline`, `open_memstream`). Entra em todo fonte com `-include`; as implementações ficam em `tb_win_compat.c`. O código do projeto continua escrito para POSIX. | +| `tinyblocks.rc`, `png2ico.py` | Ícone (o PNG do AppImage dentro de um `.ico`) e a versão do `.exe`. | + +Diferenças da build Linux: + +- **Tudo num executável**: no Windows uma DLL não enxerga os símbolos do + `.exe` (não há `-rdynamic`), então o editor, os módulos privados dele + (`TB_ED_STATIC_MODULES`: as tabelas `tb_ed_w`, `tb_ed_img` e + `tb_ed_files` apontam direto para as funções) e as libraries que no Linux + viriam como `.so` (`TB_STATIC_EXTRAS`, registradas no `main.c`) entram + todos no `.exe`. Não há hot reload. `TB_STATIC_BUILD` deixa `TB_API` + vazio (nada a exportar). +- **Sockets**: `tinyblocks-socket` e o servidor MCP têm uma camada pequena + (`sock_close`, `sock_nonblock`, `sock_poll`...) sobre o Winsock. +- **Tensor**: sem `target_clones` (precisa de ifunc, que só existe no ELF); + o GEMM fica no SSE2. +- **O pacote** leva as DLLs que o `.exe` importa (achadas com `objdump -p`, + recursivamente, como o `ldd` do AppImage), a fonte DejaVu + (`fonts/`, que o backend SDL2 e a opentype procuram ao lado do + executável) e os certificados raiz (`certs/ca-bundle.crt`, que a + `tinyblocks-ssl` carrega: o OpenSSL no Windows não lê os do sistema). + +`WIN_ARCH=i686` gera a versão de 32 bits; `WIN_SUBSYS=-mconsole` abre com +uma janela de console (para ver o `printf`). Para testar no Wine com o MCP +ligado sem brigar com um editor Linux aberto: +`TINYBLOCKS_MCP_PORT=7812 wine build/win-x86_64/TinyBlocks/TinyBlocks.exe`. + ## Testes Todos compilam com ASan/UBSan (`CFLAGS_DBG`) e rodam sem janela. diff --git a/examples/editor/main.c b/examples/editor/main.c index a6719d1..9ff6e9b 100644 --- a/examples/editor/main.c +++ b/examples/editor/main.c @@ -43,6 +43,21 @@ #include #include #include +#ifdef TB_STATIC_EXTRAS +/* Build sem dlopen das libraries (Windows): as que no Linux vem como .so + entram no executavel e sao registradas aqui */ +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +#endif /* Registra uma library de categoria: se existir o .so dela no disco, carrega * por ali (assim "make libs" + hot reload recarrega a lista de blocos na @@ -92,6 +107,15 @@ int main(int argc, char** argv) { reg_core(rt, "tinyblocks-tensor", tb_tensor_get_library); reg_core(rt, "tinyblocks-ai", tb_ai_get_library); reg_core(rt, "tinyblocks-plot", tb_plot_get_library); +#ifdef TB_STATIC_EXTRAS + { + const TinyBlocks_LibraryDescriptor* (*extras[])(void) = { + tb_ppm_get_library, tb_bmp_get_library, tb_png_get_library, tb_imglib_get_library, + tb_base64_get_library, tb_curves_get_library, tb_vg_get_library, tb_svg_get_library, + tb_regex_get_library, tb_markdown_get_library, tb_opentype_get_library }; + for (size_t i = 0; i < sizeof(extras) / sizeof(extras[0]); i++) tb_library_register(rt, extras[i]()); + } +#endif /* Interface gráfica: o editor mede texto e cria o palco ao nascer */ tb_library_register(rt, tb_graphics_get_library()); diff --git a/include/tinyblocks/tb_defs.h b/include/tinyblocks/tb_defs.h index c6a4e4d..c951520 100644 --- a/include/tinyblocks/tb_defs.h +++ b/include/tinyblocks/tb_defs.h @@ -10,7 +10,9 @@ #include /* -- Visibilidade de API --- */ -#ifdef _WIN32 +#if defined(_WIN32) && defined(TB_STATIC_BUILD) +# define TB_API /* .exe estatico: nada a exportar */ +#elif defined(_WIN32) # define TB_API __declspec(dllexport) #else # define TB_API __attribute__((visibility("default"))) diff --git a/include/tinyblocks/tb_object.h b/include/tinyblocks/tb_object.h index 3205504..f92acc4 100644 --- a/include/tinyblocks/tb_object.h +++ b/include/tinyblocks/tb_object.h @@ -17,7 +17,9 @@ #include #ifndef TB_API -# ifdef _WIN32 +# if defined(_WIN32) && defined(TB_STATIC_BUILD) +# define TB_API +# elif defined(_WIN32) # define TB_API __declspec(dllexport) # else # define TB_API __attribute__((visibility("default"))) diff --git a/libraries/tinyblocks-editor/src/tb_editor_modules.c b/libraries/tinyblocks-editor/src/tb_editor_modules.c index d988a2a..63fc4ad 100644 --- a/libraries/tinyblocks-editor/src/tb_editor_modules.c +++ b/libraries/tinyblocks-editor/src/tb_editor_modules.c @@ -10,6 +10,10 @@ * O estado da interface vive em Ed/Tab (no editor), entao trocar o codigo * nao perde nada. As chamadas passam por tabelas de ponteiros (tb_ed_w, * tb_ed_img), por isso a troca vale imediatamente para o editor inteiro. + * + * Com TB_ED_STATIC_MODULES (build Windows) os modulos vem linkados no + * proprio executavel: as tabelas apontam direto para as funcoes e nao ha + * hot reload. */ #define _POSIX_C_SOURCE 200809L #include @@ -19,6 +23,11 @@ #include #include +#ifdef TB_ED_STATIC_MODULES +# include +# include +# include +#endif /* Este arquivo nomeia os campos das tabelas (w.fill_rect, ...), entao os apelidos curtos do editor atrapalham: remove-os aqui. */ @@ -159,6 +168,40 @@ static bool resolve_files(void) { /* -- carga --- */ +#ifdef TB_ED_STATIC_MODULES +bool tb_ed_modules_load(Ed* ed) { + tb_ed_w = (TbEdWidgetsApi){ + .col_mul = tb_ew_col_mul, .fill_rect = tb_ew_fill_rect, .fill_rrect = tb_ew_fill_rrect, + .fill_circle = tb_ew_fill_circle, .stroke_rect = tb_ew_stroke_rect, + .stroke_circle = tb_ew_stroke_circle, .line = tb_ew_line, .text_c = tb_ew_text_c, + .text_width = tb_ew_text_width, .in_rect = tb_ew_in_rect }; + tb_ed_img = (TbEdImageApi){ + .view = tb_editor_image_view, .click = tb_editor_image_click, .drag = tb_editor_image_drag, + .release = tb_editor_image_release, .load_file = tb_editor_image_load_file, + .save = tb_editor_image_save, .ensure = tb_editor_image_ensure, + .sel_reset = tb_editor_image_sel_reset, .sel_commit = tb_editor_image_sel_commit, + .zoom = tb_editor_image_zoom }; + tb_ed_files = (TbEdFilesApi){ + .open = tb_editor_files_open, .close = tb_editor_files_close, .view = tb_editor_files_view, + .click = tb_editor_files_click, .key = tb_editor_files_key, .text = tb_editor_files_text, + .scroll = tb_editor_files_scroll }; + ed->mods.n = 0; + for (int i = 0; i < s_mod_n; i++) { + ed->mods.list[ed->mods.n].name = s_mod_name[i]; + ed->mods.list[ed->mods.n].file = s_mod_file[i]; + ed->mods.list[ed->mods.n].ok = 1; + ed->mods.n++; + } + ed->mods.loaded = true; + snprintf(ed->mods.info, sizeof(ed->mods.info), "Bundle do editor embutido no executável"); + return true; +} + +void tb_ed_modules_clear(void) {} + +bool tb_ed_modules_check(Ed* ed) { (void)ed; return false; } + +#else bool tb_ed_modules_load(Ed* ed) { if (!tb_api_runtime()) tb_api_init(ed->rt); tb_ed_modules_clear(); @@ -228,3 +271,4 @@ bool tb_ed_modules_check(Ed* ed) { ed->hot_status_ok = ok; return true; } +#endif /* TB_ED_STATIC_MODULES */ diff --git a/libraries/tinyblocks-mcp-server/src/tb_mcp_http.c b/libraries/tinyblocks-mcp-server/src/tb_mcp_http.c index 269cb9d..d926895 100644 --- a/libraries/tinyblocks-mcp-server/src/tb_mcp_http.c +++ b/libraries/tinyblocks-mcp-server/src/tb_mcp_http.c @@ -6,15 +6,38 @@ */ #define _POSIX_C_SOURCE 200809L #include -#include +#include #include #include #include #include -#include -#include -#include -#include + +/* -- Portabilidade: sockets POSIX ou Winsock --- */ +#ifdef _WIN32 +# define WIN32_LEAN_AND_MEAN +# include +# include +# define MSG_NOSIGNAL 0 +static void sock_close(int fd) { closesocket((SOCKET)fd); } +static void sock_nonblock(int fd, bool on) { u_long m = on; ioctlsocket((SOCKET)fd, FIONBIO, &m); } +static bool sock_retry(void) { return WSAGetLastError() == WSAEINTR; } +static bool sock_later(void) { int e = WSAGetLastError(); return e == WSAEWOULDBLOCK || e == WSAEINTR; } +static bool sock_start(void) { WSADATA w; return WSAStartup(MAKEWORD(2, 2), &w) == 0; } +#else +# include +# include +# include +# include +# include +static void sock_close(int fd) { close(fd); } +static void sock_nonblock(int fd, bool on) { + int fl = fcntl(fd, F_GETFL, 0); + if (fl >= 0) fcntl(fd, F_SETFL, on ? fl | O_NONBLOCK : fl & ~O_NONBLOCK); +} +static bool sock_retry(void) { return errno == EINTR; } +static bool sock_later(void) { return errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR; } +static bool sock_start(void) { return true; } +#endif #include "tb_mcp_server_internal.h" @@ -27,24 +50,22 @@ static unsigned now_ms(void) { return (unsigned)(ts.tv_sec * 1000u + (unsigned)(ts.tv_nsec / 1000000)); } -static void set_nonblock(int fd) { - int fl = fcntl(fd, F_GETFL, 0); - if (fl >= 0) fcntl(fd, F_SETFL, fl | O_NONBLOCK); -} +static void set_nonblock(int fd) { sock_nonblock(fd, true); } bool tb_mcp_server_listen(TbMcpServer* s, int port) { if (!s) return false; tb_mcp_http_close(s); - int fd = socket(AF_INET, SOCK_STREAM, 0); + if (!sock_start()) return false; + int fd = (int)socket(AF_INET, SOCK_STREAM, 0); if (fd < 0) return false; int one = 1; - setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); + setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&one, sizeof(one)); struct sockaddr_in a; memset(&a, 0, sizeof(a)); a.sin_family = AF_INET; a.sin_port = htons((unsigned short)port); a.sin_addr.s_addr = htonl(INADDR_LOOPBACK); /* so a propria maquina */ - if (bind(fd, (struct sockaddr*)&a, sizeof(a)) != 0 || listen(fd, 16) != 0) { close(fd); return false; } + if (bind(fd, (struct sockaddr*)&a, sizeof(a)) != 0 || listen(fd, 16) != 0) { sock_close(fd); return false; } socklen_t al = sizeof(a); getsockname(fd, (struct sockaddr*)&a, &al); set_nonblock(fd); @@ -56,14 +77,14 @@ bool tb_mcp_server_listen(TbMcpServer* s, int port) { int tb_mcp_server_port(const TbMcpServer* s) { return s && s->listen_fd >= 0 ? s->port : 0; } static void conn_drop(TbMcpServer* s, int i) { - close(s->conns[i].fd); + sock_close(s->conns[i].fd); free(s->conns[i].buf); s->conns[i] = s->conns[--s->conn_n]; } void tb_mcp_http_close(TbMcpServer* s) { while (s->conn_n > 0) conn_drop(s, 0); - if (s->listen_fd >= 0) close(s->listen_fd); + if (s->listen_fd >= 0) sock_close(s->listen_fd); s->listen_fd = -1; s->port = 0; } @@ -92,11 +113,10 @@ static bool header(const char* head, size_t head_len, const char* name, char* ou } static void send_all(int fd, const char* data, size_t n) { - int fl = fcntl(fd, F_GETFL, 0); /* a resposta sai inteira */ - if (fl >= 0) fcntl(fd, F_SETFL, fl & ~O_NONBLOCK); + sock_nonblock(fd, false); /* a resposta sai inteira */ while (n > 0) { - ssize_t w = send(fd, data, n, MSG_NOSIGNAL); - if (w <= 0) { if (w < 0 && errno == EINTR) continue; return; } + long w = (long)send(fd, data, (int)n, MSG_NOSIGNAL); + if (w <= 0) { if (w < 0 && sock_retry()) continue; return; } data += w; n -= (size_t)w; } @@ -180,9 +200,9 @@ static void serve(TbMcpServer* s, TbMcpConn* c, size_t head_len, size_t body_len int tb_mcp_server_poll(TbMcpServer* s) { if (!s || s->listen_fd < 0) return 0; for (;;) { /* conexoes novas */ - int fd = accept(s->listen_fd, NULL, NULL); + int fd = (int)accept(s->listen_fd, NULL, NULL); if (fd < 0) break; - if (s->conn_n >= TB_MCP_MAX_CONNS) { close(fd); continue; } + if (s->conn_n >= TB_MCP_MAX_CONNS) { sock_close(fd); continue; } set_nonblock(fd); TbMcpConn* c = &s->conns[s->conn_n++]; memset(c, 0, sizeof(*c)); @@ -202,10 +222,10 @@ int tb_mcp_server_poll(TbMcpServer* s) { c->buf = nb; c->cap = cap; } - ssize_t r = recv(c->fd, c->buf + c->len, c->cap - c->len - 1, 0); + long r = (long)recv(c->fd, c->buf + c->len, (int)(c->cap - c->len - 1), 0); if (r > 0) { c->len += (size_t)r; continue; } if (r == 0) closed = true; - else if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) closed = true; + else if (!sock_later()) closed = true; break; } size_t hl = 0, bl = 0; diff --git a/libraries/tinyblocks-opentype/src/tb_opentype.c b/libraries/tinyblocks-opentype/src/tb_opentype.c index 1d1a624..398da47 100644 --- a/libraries/tinyblocks-opentype/src/tb_opentype.c +++ b/libraries/tinyblocks-opentype/src/tb_opentype.c @@ -288,8 +288,20 @@ const char* tb_opentype_default_font(void) { "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", "/usr/share/fonts/truetype/freefont/FreeSans.ttf", "/usr/share/fonts/TTF/DejaVuSans.ttf", + "C:/Windows/Fonts/arial.ttf", NULL }; + /* primeiro a que vai junto do programa: /fonts */ + static char bundled[1024]; + char exe[900]; + ssize_t n = readlink("/proc/self/exe", exe, sizeof(exe) - 1); + if (n > 0) { + exe[n] = 0; + char* sl = strrchr(exe, '/'); + if (sl) *sl = 0; + snprintf(bundled, sizeof(bundled), "%s/fonts/DejaVuSans.ttf", exe); + if (access(bundled, R_OK) == 0) return bundled; + } for (int i = 0; cands[i]; i++) if (access(cands[i], R_OK) == 0) return cands[i]; return NULL; } diff --git a/libraries/tinyblocks-sdl2/src/tb_sdl2.c b/libraries/tinyblocks-sdl2/src/tb_sdl2.c index 810f1aa..056fda4 100644 --- a/libraries/tinyblocks-sdl2/src/tb_sdl2.c +++ b/libraries/tinyblocks-sdl2/src/tb_sdl2.c @@ -48,7 +48,7 @@ static void eval_handle_noop(TinyBlocks_Block* self, TinyBlocks* rt) { * Fonte TTF - cache por tamanho * === */ #define FONT_CACHE_CAP 8 -#define FONT_SEARCH_COUNT 6 +#define FONT_SEARCH_COUNT 9 typedef struct { int size; TTF_Font* font; } FontEntry; @@ -62,13 +62,27 @@ static const char* s_font_paths[FONT_SEARCH_COUNT] = { "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", "/usr/share/fonts/truetype/ubuntu/Ubuntu-R.ttf", "/System/Library/Fonts/Helvetica.ttc", + "C:/Windows/Fonts/DejaVuSans.ttf", + "C:/Windows/Fonts/segoeui.ttf", + "C:/Windows/Fonts/arial.ttf", }; +/* A fonte que vai junto do programa (pacote Windows, AppImage): + /fonts/DejaVuSans.ttf */ +static TTF_Font* bundled_font(int size) { + char* base = SDL_GetBasePath(); + if (!base) return NULL; + char path[1024]; + snprintf(path, sizeof(path), "%sfonts/DejaVuSans.ttf", base); + SDL_free(base); + return TTF_OpenFont(path, size); +} + static TTF_Font* get_font(int size) { for (int i = 0; i < s_font_cache_n; i++) if (s_font_cache[i].size == size) return s_font_cache[i].font; - TTF_Font* f = NULL; + TTF_Font* f = bundled_font(size); for (int i = 0; i < FONT_SEARCH_COUNT && !f; i++) f = TTF_OpenFont(s_font_paths[i], size); diff --git a/libraries/tinyblocks-socket/src/tb_socket.c b/libraries/tinyblocks-socket/src/tb_socket.c index 2436b4f..c229482 100644 --- a/libraries/tinyblocks-socket/src/tb_socket.c +++ b/libraries/tinyblocks-socket/src/tb_socket.c @@ -5,44 +5,91 @@ #define _POSIX_C_SOURCE 200809L #define _DEFAULT_SOURCE #include -#include -#include -#include +#include #include #include #include -#include -#include -#include -#include -#include -#include + +/* -- Portabilidade: sockets POSIX ou Winsock ------------------------------ */ +#ifdef _WIN32 +# define WIN32_LEAN_AND_MEAN +# include +# include +# define MSG_NOSIGNAL 0 +static int sock_errno(void) { return WSAGetLastError(); } +static bool sock_retry(int e) { return e == WSAEINTR; } +static bool sock_timeout(int e) { return e == WSAETIMEDOUT || e == WSAEWOULDBLOCK; } +static bool sock_pending(int e) { return e == WSAEWOULDBLOCK || e == WSAEINPROGRESS; } +static void sock_close(int fd) { closesocket((SOCKET)fd); } +static void sock_nonblock(int fd, bool on) { u_long m = on; ioctlsocket((SOCKET)fd, FIONBIO, &m); } +static int sock_poll(struct pollfd* p, int n, int ms) { return WSAPoll(p, (ULONG)n, ms); } +static void sock_timeouts(int fd, int ms) { + DWORD t = (DWORD)ms; + setsockopt((SOCKET)fd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&t, sizeof(t)); + setsockopt((SOCKET)fd, SOL_SOCKET, SO_SNDTIMEO, (const char*)&t, sizeof(t)); +} +static const char* sock_strerror(int e) { + static char m[160]; + if (!FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, (DWORD)e, 0, m, sizeof(m), NULL)) + snprintf(m, sizeof(m), "erro de rede %d", e); + for (char* c = m + strlen(m); c > m && (c[-1] == '\n' || c[-1] == '\r' || c[-1] == '.'); ) *--c = 0; + return m; +} +#else +# include +# include +# include +# include +# include +# include +# include +# include +# include +static int sock_errno(void) { return errno; } +static bool sock_retry(int e) { return e == EINTR; } +static bool sock_timeout(int e) { return e == EAGAIN || e == EWOULDBLOCK; } +static bool sock_pending(int e) { return e == EINPROGRESS; } +static void sock_close(int fd) { close(fd); } +static void sock_nonblock(int fd, bool on) { + int fl = fcntl(fd, F_GETFL, 0); + fcntl(fd, F_SETFL, on ? fl | O_NONBLOCK : fl & ~O_NONBLOCK); +} +static int sock_poll(struct pollfd* p, int n, int ms) { return poll(p, (nfds_t)n, ms); } +static void sock_timeouts(int fd, int ms) { + struct timeval tv = { ms / 1000, (ms % 1000) * 1000 }; + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); + setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); +} +static const char* sock_strerror(int e) { return strerror(e); } +#endif #include "tb_socket.h" /* == TCP como TbStream ================================================ */ static long tcp_read(TbStream* s, void* buf, size_t cap) { for (;;) { - ssize_t n = recv(s->fd, buf, cap, 0); - if (n >= 0) return (long)n; - if (errno == EINTR) continue; - snprintf(s->err, sizeof(s->err), "%s", errno == EAGAIN || errno == EWOULDBLOCK ? "tempo esgotado esperando dados" : strerror(errno)); + long n = (long)recv(s->fd, buf, (int)cap, 0); + if (n >= 0) return n; + int e = sock_errno(); + if (sock_retry(e)) continue; + snprintf(s->err, sizeof(s->err), "%s", sock_timeout(e) ? "tempo esgotado esperando dados" : sock_strerror(e)); return -1; } } static long tcp_write(TbStream* s, const void* buf, size_t n) { for (;;) { - ssize_t w = send(s->fd, buf, n, MSG_NOSIGNAL); - if (w >= 0) return (long)w; - if (errno == EINTR) continue; - snprintf(s->err, sizeof(s->err), "%s", strerror(errno)); + long w = (long)send(s->fd, buf, (int)n, MSG_NOSIGNAL); + if (w >= 0) return w; + int e = sock_errno(); + if (sock_retry(e)) continue; + snprintf(s->err, sizeof(s->err), "%s", sock_strerror(e)); return -1; } } static void tcp_close(TbStream* s) { - if (s->fd >= 0) close(s->fd); + if (s->fd >= 0) sock_close(s->fd); free(s); } @@ -61,31 +108,29 @@ static TbStream* tcp_connect(const char* host, int port, int timeout_ms, char* e int fd = -1; char last[128] = "nenhum endereço respondeu"; for (struct addrinfo* a = res; a; a = a->ai_next) { - fd = socket(a->ai_family, a->ai_socktype, a->ai_protocol); + fd = (int)socket(a->ai_family, a->ai_socktype, a->ai_protocol); if (fd < 0) continue; - int fl = fcntl(fd, F_GETFL, 0); - fcntl(fd, F_SETFL, fl | O_NONBLOCK); /* connect com prazo */ - int c = connect(fd, a->ai_addr, a->ai_addrlen); - if (c < 0 && errno == EINPROGRESS) { + sock_nonblock(fd, true); /* connect com prazo */ + int c = connect(fd, a->ai_addr, (int)a->ai_addrlen); + int ce = c < 0 ? sock_errno() : 0; + if (c < 0 && sock_pending(ce)) { struct pollfd pf = { fd, POLLOUT, 0 }; - int pr = poll(&pf, 1, timeout_ms); + int pr = sock_poll(&pf, 1, timeout_ms); int soerr = 0; socklen_t sl = sizeof(soerr); - if (pr == 1) getsockopt(fd, SOL_SOCKET, SO_ERROR, &soerr, &sl); + if (pr == 1) getsockopt(fd, SOL_SOCKET, SO_ERROR, (char*)&soerr, &sl); c = (pr == 1 && soerr == 0) ? 0 : -1; - if (c) snprintf(last, sizeof(last), "%s", pr == 0 ? "tempo esgotado conectando" : strerror(soerr ? soerr : errno)); - } else if (c < 0) snprintf(last, sizeof(last), "%s", strerror(errno)); - if (c == 0) { fcntl(fd, F_SETFL, fl); break; } - close(fd); fd = -1; + if (c) snprintf(last, sizeof(last), "%s", pr == 0 ? "tempo esgotado conectando" : sock_strerror(soerr ? soerr : sock_errno())); + } else if (c < 0) snprintf(last, sizeof(last), "%s", sock_strerror(ce)); + if (c == 0) { sock_nonblock(fd, false); break; } + sock_close(fd); fd = -1; } freeaddrinfo(res); if (fd < 0) { snprintf(err, cap, "não conectou a %s:%d: %s", host, port, last); return NULL; } - struct timeval tv = { timeout_ms / 1000, (timeout_ms % 1000) * 1000 }; - setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); - setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); + sock_timeouts(fd, timeout_ms); int one = 1; - setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)); + setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const char*)&one, sizeof(one)); TbStream* s = calloc(1, sizeof(TbStream)); - if (!s) { close(fd); snprintf(err, cap, "sem memória"); return NULL; } + if (!s) { sock_close(fd); snprintf(err, cap, "sem memória"); return NULL; } s->cls = &s_tcp; s->fd = fd; return s; @@ -246,6 +291,10 @@ static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name, static bool socket_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { static const TinyBlocks_Category cat = { "Socket", {0.20f, 0.60f, 0.62f, 1.f}, {0.13f, 0.45f, 0.47f, 1.f} }; tb_library_set_category(lib, &cat); +#ifdef _WIN32 + WSADATA wsa; /* o Winsock precisa ser iniciado */ + if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) return false; +#endif lib->lib_userdata = (void*)&s_api; s_t_conn = tb_type_block_create(rt, "Socket._Conexao", NULL, 0, NULL, 0, NULL); if (!s_t_conn) return false; @@ -278,6 +327,9 @@ static bool socket_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { static void socket_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { (void)rt; lib->lib_userdata = NULL; +#ifdef _WIN32 + WSACleanup(); +#endif } TINYBLOCKS_DEFINE_LIBRARY(socket, "tinyblocks-socket", "1.0.0", socket_init, socket_deinit) diff --git a/libraries/tinyblocks-ssl/src/tb_ssl.c b/libraries/tinyblocks-ssl/src/tb_ssl.c index 920f198..68c4ad0 100644 --- a/libraries/tinyblocks-ssl/src/tb_ssl.c +++ b/libraries/tinyblocks-ssl/src/tb_ssl.c @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -89,6 +90,23 @@ static void eval_version(TinyBlocks_Block* self, TinyBlocks* rt) { self->dirty = false; } +/* Certificados que vao junto do programa: /certs/ + ca-bundle.crt. No Windows o OpenSSL nao conhece o repositorio do sistema, + entao o pacote leva o arquivo (ver packaging/windows). */ +static void load_bundled_certs(SSL_CTX* ctx) { + char exe[1024]; + ssize_t n = readlink("/proc/self/exe", exe, sizeof(exe) - 1); + if (n <= 0) return; + exe[n] = 0; + char* sl = strrchr(exe, '/'); + if (!sl) return; + snprintf(sl, sizeof(exe) - (size_t)(sl - exe), "/certs/ca-bundle.crt"); + FILE* f = fopen(exe, "rb"); + if (!f) return; + fclose(f); + SSL_CTX_load_verify_locations(ctx, exe, NULL); +} + static bool ssl_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { static const TinyBlocks_Category cat = { "SSL", {0.40f, 0.55f, 0.30f, 1.f}, {0.29f, 0.42f, 0.21f, 1.f} }; tb_library_set_category(lib, &cat); @@ -98,6 +116,7 @@ static bool ssl_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { SSL_CTX_set_min_proto_version(s_ctx, TLS1_2_VERSION); SSL_CTX_set_verify(s_ctx, SSL_VERIFY_PEER, NULL); SSL_CTX_set_default_verify_paths(s_ctx); /* certificados do sistema */ + load_bundled_certs(s_ctx); lib->lib_userdata = (void*)&s_api; static const TinyBlocks_SlotDesc out[] = {{"versão", TB_VALUE_TEXT}}; TinyBlocks_TypeBlock* t = tb_type_block_create(rt, "SSL.Version", NULL, 0, out, 1, eval_version); diff --git a/libraries/tinyblocks-tensor/src/tensor.c b/libraries/tinyblocks-tensor/src/tensor.c index fa7765f..f443e53 100644 --- a/libraries/tinyblocks-tensor/src/tensor.c +++ b/libraries/tinyblocks-tensor/src/tensor.c @@ -230,8 +230,11 @@ void tt_parallel_for(int n, TbParallelFn fn, void* ctx) { /* == GEMM ============================================================= */ /* Nucleo: C[m,n] += A[m,k] B[k,n], tudo contiguo e row-major. Quatro linhas de C por vez reaproveitam cada linha de B; o laco de dentro - vetoriza (AVX2/FMA escolhido em execucao, SSE2 nos outros). */ + vetoriza (AVX2/FMA escolhido em execucao, SSE2 nos outros). A escolha + em execucao usa ifunc, que so existe no ELF: no Windows fica o SSE2. */ +#if defined(__ELF__) && defined(__x86_64__) __attribute__((target_clones("arch=haswell", "default"))) +#endif static void kernel(int m, int n, int k, const float* A, int lda, const float* B, int ldb, float* C, int ldc) { enum { KB = 256, NB = 512 }; for (int j0 = 0; j0 < n; j0 += NB) { diff --git a/packaging/windows/compat/dlfcn.h b/packaging/windows/compat/dlfcn.h new file mode 100644 index 0000000..d2bc33a --- /dev/null +++ b/packaging/windows/compat/dlfcn.h @@ -0,0 +1,13 @@ +/* dlfcn.h para Windows (build MinGW): dlopen/dlsym/dlclose/dlerror sobre + LoadLibrary/GetProcAddress, em tb_win_compat.c. */ +#ifndef TB_WIN_DLFCN_H +#define TB_WIN_DLFCN_H +#define RTLD_LAZY 1 +#define RTLD_NOW 2 +#define RTLD_LOCAL 0 +#define RTLD_GLOBAL 0x100 +void* dlopen(const char* path, int flags); +void* dlsym(void* handle, const char* name); +int dlclose(void* handle); +char* dlerror(void); +#endif diff --git a/packaging/windows/compat/pwd.h b/packaging/windows/compat/pwd.h new file mode 100644 index 0000000..2af5935 --- /dev/null +++ b/packaging/windows/compat/pwd.h @@ -0,0 +1,7 @@ +/* pwd.h para Windows (build MinGW): so o nome e a pasta do usuario. */ +#ifndef TB_WIN_PWD_H +#define TB_WIN_PWD_H +struct passwd { char* pw_name; char* pw_dir; }; +int getuid(void); +struct passwd* getpwuid(int uid); +#endif diff --git a/packaging/windows/compat/sys/utsname.h b/packaging/windows/compat/sys/utsname.h new file mode 100644 index 0000000..502ad78 --- /dev/null +++ b/packaging/windows/compat/sys/utsname.h @@ -0,0 +1,6 @@ +/* sys/utsname.h para Windows (build MinGW): sistema, versao e arquitetura. */ +#ifndef TB_WIN_UTSNAME_H +#define TB_WIN_UTSNAME_H +struct utsname { char sysname[65], nodename[65], release[65], version[65], machine[65]; }; +int uname(struct utsname* u); +#endif diff --git a/packaging/windows/compat/tb_win_compat.c b/packaging/windows/compat/tb_win_compat.c new file mode 100644 index 0000000..12a8a28 --- /dev/null +++ b/packaging/windows/compat/tb_win_compat.c @@ -0,0 +1,175 @@ +/* tb_win_compat.c - implementacoes do tb_win_compat.h, dlfcn.h, pwd.h e + sys/utsname.h desta pasta (build Windows). */ +#define WIN32_LEAN_AND_MEAN +#include +#include +#include +#include +#include + +#include "dlfcn.h" +#include "pwd.h" +#include "sys/utsname.h" + +int tb_win_mkdir(const char* p, int mode) { (void)mode; return _mkdir(p); } + +long tb_win_sysconf(int name) { + SYSTEM_INFO si; + GetSystemInfo(&si); + if (name == 84) return (long)si.dwNumberOfProcessors; /* _SC_NPROCESSORS_ONLN */ + if (name == 30) return (long)si.dwPageSize; /* _SC_PAGESIZE */ + if (name == 85) { /* _SC_PHYS_PAGES */ + MEMORYSTATUSEX m; + m.dwLength = sizeof(m); + return GlobalMemoryStatusEx(&m) ? (long)(m.ullTotalPhys / si.dwPageSize) : -1; + } + return -1; +} + +int tb_win_setenv(const char* k, const char* v, int over) { + if (!over && getenv(k)) return 0; + return _putenv_s(k, v) == 0 ? 0 : -1; +} + +int tb_win_unsetenv(const char* k) { return _putenv_s(k, "") == 0 ? 0 : -1; } + +ssize_t tb_win_readlink(const char* path, char* buf, size_t cap) { + if (strcmp(path, "/proc/self/exe") != 0 || cap == 0) return -1; + DWORD n = GetModuleFileNameA(NULL, buf, (DWORD)cap); + if (n == 0 || n >= cap) return -1; + for (DWORD i = 0; i < n; i++) if (buf[i] == '\\') buf[i] = '/'; + return (ssize_t)n; /* como readlink: sem o '\0' */ +} + +char* tb_win_strndup(const char* s, size_t n) { + size_t len = 0; + while (len < n && s[len]) len++; + char* r = malloc(len + 1); + if (r) { memcpy(r, s, len); r[len] = 0; } + return r; +} + +ssize_t tb_win_getline(char** line, size_t* cap, FILE* f) { + if (!line || !cap || !f) return -1; + size_t n = 0; + int c; + while ((c = fgetc(f)) != EOF) { + if (n + 2 > *cap) { + size_t nc = *cap ? *cap * 2 : 128; + char* p = realloc(*line, nc); + if (!p) return -1; + *line = p; *cap = nc; + } + (*line)[n++] = (char)c; + if (c == '\n') break; + } + if (n == 0) return -1; + (*line)[n] = 0; + return (ssize_t)n; +} + +/* -- open_memstream: um arquivo temporario lembrado aqui; o fclose dele le + o conteudo para o buffer do chamador (como no POSIX) e apaga o arquivo */ +#undef fclose +typedef struct { FILE* f; char** buf; size_t* len; char path[MAX_PATH]; } MemStream; +static MemStream s_ms[8]; + +FILE* tb_win_open_memstream(char** buf, size_t* len) { + for (int i = 0; i < 8; i++) { + if (s_ms[i].f) continue; + char dir[MAX_PATH], path[MAX_PATH]; + if (!GetTempPathA(sizeof(dir), dir) || !GetTempFileNameA(dir, "tbm", 0, path)) return NULL; + FILE* f = fopen(path, "w+b"); + if (!f) { DeleteFileA(path); return NULL; } + s_ms[i].f = f; + s_ms[i].buf = buf; + s_ms[i].len = len; + memcpy(s_ms[i].path, path, sizeof(path)); + return f; + } + return NULL; +} + +int tb_win_fclose(FILE* f) { + for (int i = 0; f && i < 8; i++) { + if (s_ms[i].f != f) continue; + fflush(f); + long n = ftell(f); + if (n < 0) n = 0; + char* b = malloc((size_t)n + 1); + if (b) { rewind(f); n = (long)fread(b, 1, (size_t)n, f); b[n] = 0; } + *s_ms[i].buf = b; + if (s_ms[i].len) *s_ms[i].len = b ? (size_t)n : 0; + int r = fclose(f); + DeleteFileA(s_ms[i].path); + s_ms[i].f = NULL; + return r; + } + return fclose(f); +} + +/* -- dlfcn ------------------------------------------------------------- */ +static char s_dl_err[256]; + +void* dlopen(const char* path, int flags) { + (void)flags; + HMODULE h = path ? LoadLibraryA(path) : GetModuleHandleA(NULL); + if (!h) snprintf(s_dl_err, sizeof(s_dl_err), "LoadLibrary('%s') falhou (erro %lu)", path, GetLastError()); + return (void*)h; +} + +void* dlsym(void* h, const char* name) { + FARPROC p = GetProcAddress((HMODULE)h, name); + if (!p) snprintf(s_dl_err, sizeof(s_dl_err), "simbolo '%s' nao encontrado", name); + void* r; + memcpy(&r, &p, sizeof(r)); + return r; +} + +int dlclose(void* h) { return FreeLibrary((HMODULE)h) ? 0 : -1; } + +char* dlerror(void) { + static char out[256]; + if (!s_dl_err[0]) return NULL; + snprintf(out, sizeof(out), "%s", s_dl_err); + s_dl_err[0] = 0; + return out; +} + +/* -- pwd --------------------------------------------------------------- */ +int getuid(void) { return 0; } + +struct passwd* getpwuid(int uid) { + static char name[256], dir[512]; + static struct passwd pw; + (void)uid; + DWORD n = sizeof(name); + if (!GetUserNameA(name, &n)) snprintf(name, sizeof(name), "%s", getenv("USERNAME") ? getenv("USERNAME") : ""); + const char* h = getenv("USERPROFILE"); + snprintf(dir, sizeof(dir), "%s", h ? h : ""); + pw.pw_name = name; + pw.pw_dir = dir; + return &pw; +} + +/* -- uname ------------------------------------------------------------- */ +int uname(struct utsname* u) { + OSVERSIONINFOA v; + memset(&v, 0, sizeof(v)); + v.dwOSVersionInfoSize = sizeof(v); +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" + GetVersionExA(&v); +#pragma GCC diagnostic pop + snprintf(u->sysname, sizeof(u->sysname), "Windows"); + snprintf(u->release, sizeof(u->release), "%lu.%lu.%lu", v.dwMajorVersion, v.dwMinorVersion, v.dwBuildNumber); + snprintf(u->version, sizeof(u->version), "%s", v.szCSDVersion); + DWORD n = sizeof(u->nodename); + if (!GetComputerNameA(u->nodename, &n)) u->nodename[0] = 0; + SYSTEM_INFO si; + GetNativeSystemInfo(&si); + snprintf(u->machine, sizeof(u->machine), "%s", + si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 ? "x86_64" : + si.wProcessorArchitecture == 12 /* ARM64 */ ? "aarch64" : "i686"); + return 0; +} diff --git a/packaging/windows/compat/tb_win_compat.h b/packaging/windows/compat/tb_win_compat.h new file mode 100644 index 0000000..afd4037 --- /dev/null +++ b/packaging/windows/compat/tb_win_compat.h @@ -0,0 +1,56 @@ +/* + * tb_win_compat.h - o pouco de POSIX que o TinyBlocks usa e o MinGW nao tem. + * So entra na build Windows (incluido em todo fonte com -include, junto com + * os headers desta pasta: dlfcn.h, pwd.h, sys/utsname.h). O codigo do + * projeto continua escrito para POSIX. As implementacoes ficam em + * tb_win_compat.c, para nao espalhar o windows.h (e os nomes dele) por + * todos os fontes. + * + * mkdir(p, modo) -> _mkdir(p) + * sysconf(_SC_...) -> GetSystemInfo / GlobalMemoryStatusEx + * setenv / unsetenv -> _putenv_s + * readlink("/proc/self/exe") -> GetModuleFileName (com '/') + * strndup, getline + * open_memstream -> arquivo temporario; o fclose devolve o texto + */ +#ifndef TB_WIN_COMPAT_H +#define TB_WIN_COMPAT_H +#ifdef _WIN32 + +#include +#include + +int tb_win_mkdir(const char* p, int mode); +long tb_win_sysconf(int name); +int tb_win_setenv(const char* k, const char* v, int over); +int tb_win_unsetenv(const char* k); +ssize_t tb_win_readlink(const char* path, char* buf, size_t cap); +char* tb_win_strndup(const char* s, size_t n); +#include +ssize_t tb_win_getline(char** line, size_t* cap, FILE* f); +FILE* tb_win_open_memstream(char** buf, size_t* len); +int tb_win_fclose(FILE* f); + +/* Os headers do sistema antes das macros: a declaracao original fica intacta */ +#include +#include +#include +#include +#include +#include +#define mkdir(p, m) tb_win_mkdir((p), (m)) + +#define _SC_NPROCESSORS_ONLN 84 +#define _SC_PHYS_PAGES 85 +#define _SC_PAGESIZE 30 +#define sysconf(n) tb_win_sysconf(n) +#define setenv(k, v, o) tb_win_setenv((k), (v), (o)) +#define unsetenv(k) tb_win_unsetenv(k) +#define readlink(p, b, c) tb_win_readlink((p), (b), (c)) +#define strndup(s, n) tb_win_strndup((s), (n)) +#define getline(l, c, f) tb_win_getline((l), (c), (f)) +#define open_memstream(b, n) tb_win_open_memstream((b), (n)) +#define fclose(f) tb_win_fclose(f) + +#endif /* _WIN32 */ +#endif diff --git a/packaging/windows/msys2_deps.py b/packaging/windows/msys2_deps.py new file mode 100644 index 0000000..714268c --- /dev/null +++ b/packaging/windows/msys2_deps.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +""" +Baixa pacotes MinGW do repositorio do MSYS2 (com as dependencias) e extrai +numa pasta: include/, lib/ e bin/ (as DLLs) para compilar o TinyBlocks para +Windows a partir do Linux. + + msys2_deps.py pacote [pacote ...] + +Os pacotes sao nomes sem prefixo (SDL2, libpng...). O indice do repositorio +(.db) diz o arquivo e as dependencias de cada pacote. Os arquivos +baixados ficam em /../cache e nao sao baixados de novo. +""" +import io, os, re, subprocess, sys, tarfile, urllib.request + +MIRROR = os.environ.get("MSYS2_MIRROR", "https://repo.msys2.org/mingw") +REPO = {"x86_64": ("mingw64", "mingw-w64-x86_64-"), "i686": ("mingw32", "mingw-w64-i686-")} +# Pacotes que nao precisam ir junto (o compilador ja traz o runtime) +SKIP = {"crt", "headers", "libgccjit"} + + +def fetch(url, path): + if os.path.exists(path): + return path + print("baixando", url, flush=True) + tmp = path + ".parte" + with urllib.request.urlopen(url, timeout=60) as r, open(tmp, "wb") as f: + while True: + b = r.read(1 << 16) + if not b: + break + f.write(b) + os.replace(tmp, path) + return path + + +def unzst(path): + return subprocess.run(["zstd", "-dc", path], check=True, capture_output=True).stdout + + +def read_db(arch, cache): + repo, prefix = REPO[arch] + db = fetch(f"{MIRROR}/{arch}/{repo}.db", os.path.join(cache, f"{repo}.db")) + raw = open(db, "rb").read() + if raw[:4] == b"\x28\xb5\x2f\xfd": # zstd + raw = unzst(db) + pk = {} + with tarfile.open(fileobj=io.BytesIO(raw)) as t: + for m in t: + if not m.name.endswith("/desc"): + continue + fields, key = {}, None + for line in t.extractfile(m).read().decode().splitlines(): + if line.startswith("%") and line.endswith("%"): + key = line.strip("%"); fields[key] = [] + elif line and key: + fields[key].append(line) + name = fields["NAME"][0] + info = {"file": fields["FILENAME"][0], "deps": fields.get("DEPENDS", [])} + pk[name] = info + for p in fields.get("PROVIDES", []): + pk.setdefault(re.split(r"[<>=]", p)[0], info) + return pk, prefix + + +def main(): + if len(sys.argv) < 4 or sys.argv[1] not in REPO: + sys.exit(__doc__) + arch, dest, wanted = sys.argv[1], os.path.abspath(sys.argv[2]), sys.argv[3:] + cache = os.path.join(os.path.dirname(dest), "cache") + os.makedirs(cache, exist_ok=True) + pk, prefix = read_db(arch, cache) + todo, seen = [prefix + w for w in wanted], set() + while todo: + n = re.split(r"[<>=]", todo.pop())[0] + if n in seen or n[len(prefix):] in SKIP: + continue + seen.add(n) + if n not in pk: + sys.exit(f"pacote nao encontrado no MSYS2: {n}") + todo += pk[n]["deps"] + os.makedirs(dest, exist_ok=True) + root = REPO[arch][0] + "/" + for n in sorted(seen): + f = pk[n]["file"] + path = fetch(f"{MIRROR}/{arch}/{f}", os.path.join(cache, f)) + data = unzst(path) if f.endswith(".zst") else open(path, "rb").read() + with tarfile.open(fileobj=io.BytesIO(data)) as t: + for m in t: + if not m.name.startswith(root) or not (m.isfile() or m.isdir()): + continue + rel = m.name[len(root):] + if not rel or rel.startswith(("share/doc", "share/man", "share/info", "share/locale")): + continue + out = os.path.join(dest, rel) + if not os.path.abspath(out).startswith(dest + os.sep): + continue # nada fora da pasta + if m.isdir(): + os.makedirs(out, exist_ok=True) + else: + os.makedirs(os.path.dirname(out), exist_ok=True) + with open(out, "wb") as o: + o.write(t.extractfile(m).read()) + print(f"{len(seen)} pacotes em {dest}") + + +if __name__ == "__main__": + main() diff --git a/packaging/windows/png2ico.py b/packaging/windows/png2ico.py new file mode 100644 index 0000000..d688cb0 --- /dev/null +++ b/packaging/windows/png2ico.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python3 +"""png2ico.py : um .ico com o PNG dentro (Vista+).""" +import struct, sys + +png = open(sys.argv[1], "rb").read() +w, h = struct.unpack(">II", png[16:24]) +entry = struct.pack(" + +1 ICON "tinyblocks.ico" + +1 VERSIONINFO +FILEVERSION 0,1,0,0 +PRODUCTVERSION 0,1,0,0 +FILEOS VOS_NT_WINDOWS32 +FILETYPE VFT_APP +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "041604B0" + BEGIN + VALUE "FileDescription", "TinyBlocks - linguagem de blocos" + VALUE "ProductName", "TinyBlocks" + VALUE "ProductVersion", "0.1.0" + VALUE "OriginalFilename", "TinyBlocks.exe" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x0416, 1200 + END +END diff --git a/packaging/windows/win.mk b/packaging/windows/win.mk new file mode 100644 index 0000000..3d21c1b --- /dev/null +++ b/packaging/windows/win.mk @@ -0,0 +1,129 @@ +# ── Build para Windows (.exe) com MinGW-w64, a partir do Linux ────────── +# Incluido pelo Makefile da raiz. Alvos: +# make exe -> build/win-x86_64/TinyBlocks/ (TinyBlocks.exe + DLLs) e o .zip +# make run-exe -> abre o .exe no Wine +# make exe WIN_ARCH=i686 (32 bits) +# +# As dependencias (SDL2, SDL2_ttf, libpng, freetype, openssl, zlib, regex) +# vem dos pacotes MinGW do MSYS2 (packaging/windows/msys2_deps.py), baixados +# uma vez para build/.win-deps. O POSIX que falta no Windows esta em +# packaging/windows/compat. Diferente do Linux, o editor, os modulos dele e +# as libraries entram todos no .exe (no Windows uma DLL nao enxerga os +# simbolos do .exe, entao nao ha hot reload das libraries). + +WIN_ARCH ?= x86_64 +WIN_CC := $(WIN_ARCH)-w64-mingw32-gcc-posix +WIN_RC := $(WIN_ARCH)-w64-mingw32-windres +WIN_OBJDUMP := $(WIN_ARCH)-w64-mingw32-objdump +WIN_BITS := $(if $(filter x86_64,$(WIN_ARCH)),64,32) +WIN_DEPS := $(BUILD)/.win-deps/$(WIN_ARCH) +WIN_OUT := $(BUILD)/win-$(WIN_ARCH) +WOBJ := $(WIN_OUT)/obj +WIN_PKG := $(WIN_OUT)/$(APP_NAME) +WIN_EXE := $(WIN_PKG)/$(APP_NAME).exe +WIN_ZIP := $(BUILD)/$(APP_NAME)-$(APP_VER)-win$(WIN_BITS).zip +WIN_COMPAT := packaging/windows/compat +# -mwindows: sem janela de console (WIN_SUBSYS=-mconsole para ver o printf) +WIN_SUBSYS ?= -mwindows + +# A fonte da interface vai junto (o Windows nao tem a DejaVu) +WIN_FONTS := /usr/share/fonts/truetype/dejavu/DejaVuSans.ttf /usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf +WIN_FONT_LICENSE := /usr/share/doc/fonts-dejavu-core/copyright + +# Certificados raiz para o HTTPS (o OpenSSL no Windows nao le os do +# sistema): o bundle da Mozilla da maquina de build; senao, o do MSYS2 +WIN_CA_HOST := /etc/ssl/certs/ca-certificates.crt + +WIN_DEP_PKGS := SDL2 SDL2_ttf libpng freetype openssl zlib libsystre ca-certificates + +# Libraries que entram no .exe: as de categoria e de app (como no Linux), +# as que o editor ja linka, e as de extensao (no Linux viriam como .so) +WIN_EXTRA_LIBS := base64 curves ppm bmp png image vg svg regex markdown opentype +WIN_LIB_DIRS := $(foreach l,$(CAT_LIBS) $(APP_LIBS) $(WIN_EXTRA_LIBS) \ + editor a11y mcp-server graphics sdl2 toml json xml csv blueprint scratchblocks api libman syntax, \ + $(LIBDIR)/tinyblocks-$(l)) \ + $(ED_DIR)/libraries/tinyblocks-editor-widgets \ + $(ED_DIR)/libraries/tinyblocks-editor-image \ + $(ED_DIR)/libraries/tinyblocks-editor-files +WIN_SRCS := $(WIN_COMPAT)/tb_win_compat.c $(wildcard src/*.c) $(foreach d,$(WIN_LIB_DIRS),$(wildcard $(d)/src/*.c)) examples/editor/main.c +WIN_OBJS := $(patsubst %.c,$(WOBJ)/%.o,$(WIN_SRCS)) + +WIN_INCS := -Iinclude $(foreach d,$(wildcard $(LIBDIR)/*/include) $(wildcard $(ED_DIR)/libraries/*/include),-I$(d)) \ + -I$(WIN_COMPAT) -I$(WIN_DEPS)/include -I$(WIN_DEPS)/include/SDL2 -I$(WIN_DEPS)/include/freetype2 +WIN_CFLAGS := -std=c11 -O2 -DNDEBUG -D_POSIX_C_SOURCE=200809L -D_WIN32_WINNT=0x0601 \ + -DTB_STATIC_BUILD -DTB_ED_STATIC_MODULES -DTB_STATIC_EXTRAS \ + -include $(WIN_COMPAT)/tb_win_compat.h $(WIN_INCS) -w +WIN_LDLIBS := -L$(WIN_DEPS)/lib -lSDL2_ttf -lSDL2 -lpng16 -lfreetype -lssl -lcrypto -lz -lsystre \ + -lws2_32 -lcrypt32 -lole32 -lshell32 -luser32 -lgdi32 -lwinmm -lm \ + -static-libgcc -Wl,-Bstatic -lpthread -Wl,-Bdynamic + +# Flags de cada parte (como nos Makefiles delas) +$(WOBJ)/$(ED_DIR)/%.o: WIN_DEFS := -DTB_EDITOR_PRIVATE_API -DTB_MCP_SERVER_PRIVATE_API +$(WOBJ)/$(ED_DIR)/libraries/tinyblocks-editor-image/%.o: WIN_DEFS := -DTB_EDITOR_PRIVATE_API -DTB_EDITOR_IMAGE_BUILD +$(WOBJ)/$(ED_DIR)/libraries/tinyblocks-editor-files/%.o: WIN_DEFS := -DTB_EDITOR_PRIVATE_API -DTB_EDITOR_FILES_BUILD +$(WOBJ)/$(LIBDIR)/tinyblocks-mcp-server/%.o: WIN_DEFS := -DTB_MCP_SERVER_PRIVATE_API +$(WOBJ)/$(LIBDIR)/tinyblocks-graphics/%.o: WIN_DEFS := -DTB_GRAPHICS_DEFAULT_SDL2 +$(WOBJ)/examples/editor/%.o: WIN_DEFS := -DTB_EDITOR_PRIVATE_API + +$(WIN_DEPS)/.ok: + @echo "Baixando as dependencias Windows ($(WIN_ARCH)) do MSYS2..." + python3 -I packaging/windows/msys2_deps.py $(WIN_ARCH) $(WIN_DEPS) $(WIN_DEP_PKGS) + @touch $@ + +$(WOBJ)/%.o: %.c $(WIN_DEPS)/.ok $(WIN_COMPAT)/tb_win_compat.h + @mkdir -p $(dir $@) + @echo " CC(win) $<" + @$(WIN_CC) -I$(dir $<) -I$(dir $<)../include $(WIN_CFLAGS) $(WIN_DEFS) -MMD -MP -c $< -o $@ + +-include $(WIN_OBJS:.o=.d) + +# Icone: o PNG do AppImage dentro de um .ico (o Windows aceita PNG no ICO) +$(WOBJ)/tinyblocks.ico: $(PKG_DIR)/tinyblocks.png + @mkdir -p $(dir $@) + python3 -I packaging/windows/png2ico.py $< $@ + +$(WOBJ)/icon.o: packaging/windows/tinyblocks.rc $(WOBJ)/tinyblocks.ico + $(WIN_RC) -I $(WOBJ) $< -O coff -o $@ + +$(WIN_EXE): $(WIN_OBJS) $(WOBJ)/icon.o + @mkdir -p $(dir $@) + $(WIN_CC) $(WIN_SUBSYS) $^ -o $@ $(WIN_LDLIBS) + +# Copia para o pacote as DLLs que o .exe importa (e as que elas importam), +# como o "ldd" do AppImage; as do sistema (KERNEL32, USER32...) ficam. +win-pkg: $(WIN_EXE) + @echo "Copiando as DLLs necessarias..." + @todo="$(WIN_EXE)"; seen=""; \ + while [ -n "$$todo" ]; do \ + todo=$$(echo $$todo); f=$${todo%% *}; [ "$$todo" = "$$f" ] && todo="" || todo=$${todo#* }; \ + [ -n "$$f" ] || continue; \ + for d in $$(LC_ALL=C $(WIN_OBJDUMP) -p "$$f" | awk '/DLL Name:/{print $$3}'); do \ + src="$(WIN_DEPS)/bin/$$d"; \ + [ -f "$$src" ] || continue; \ + case " $$seen " in *" $$d "*) continue;; esac; \ + seen="$$seen $$d"; cp "$$src" $(WIN_PKG)/; todo="$$todo $$src"; \ + done; \ + done; echo " DLLs:$$seen" + @mkdir -p $(WIN_PKG)/certs $(WIN_PKG)/fonts + @if [ -s $(WIN_CA_HOST) ]; then cp $(WIN_CA_HOST) $(WIN_PKG)/certs/ca-bundle.crt; \ + else cp $(WIN_DEPS)/share/pki/ca-trust-source/ca-bundle.trust.crt $(WIN_PKG)/certs/ca-bundle.crt; fi + @cp $(WIN_FONTS) $(WIN_PKG)/fonts/ || { echo "Falta a fonte DejaVu (pacote fonts-dejavu-core)"; exit 1; } + @cp $(WIN_FONT_LICENSE) $(WIN_PKG)/fonts/LICENSE.txt 2>/dev/null || true + @cp -r examples/gan-animais $(WIN_PKG)/exemplos-gan-animais 2>/dev/null || true + @printf '%s\r\n' "TinyBlocks $(APP_VER) para Windows ($(WIN_ARCH))" "" \ + "Abra TinyBlocks.exe. As DLLs desta pasta precisam ficar junto dele." \ + "Fonte: DejaVu Sans (licenca livre, ver fonts/LICENSE.txt)." > $(WIN_PKG)/LEIA-ME.txt + +exe: win-pkg ## Gera o TinyBlocks.exe para Windows (build/win-x86_64/TinyBlocks e o .zip) + @rm -f $(WIN_ZIP) + @cd $(WIN_OUT) && python3 -I -m zipfile -c $(abspath $(WIN_ZIP)) $(APP_NAME) + @echo "Windows: $(WIN_EXE)" + @echo "Zip: $(WIN_ZIP)" + +run-exe: win-pkg ## Gera e abre o .exe no Wine + cd $(WIN_PKG) && wine $(APP_NAME).exe + +clean-exe: ## Apaga a build Windows (mantem as dependencias baixadas) + $(RM) -r $(WIN_OUT) + +.PHONY: exe run-exe win-pkg clean-exe