diff --git a/CMakeLists.txt b/CMakeLists.txt index b94babda..39bdcfea 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -354,9 +354,19 @@ add_executable(test_ge_renderer tests/test_ge_renderer.cpp) target_link_libraries(test_ge_renderer PRIVATE p3p3ds_core) add_test(NAME p3p_ge_renderer COMMAND test_ge_renderer) # Builder (ISO -> .3dsx) pieces that run on the host and are unit-tested here. -add_library(p3p3ds_builder_core STATIC platform/pc/builder/psp_eboot.cpp platform/pc/builder/game_prep.cpp) +add_library(p3p3ds_builder_core STATIC platform/pc/builder/psp_eboot.cpp platform/pc/builder/game_prep.cpp + platform/pc/builder/update_check.cpp) target_include_directories(p3p3ds_builder_core PUBLIC platform/pc/builder) target_link_libraries(p3p3ds_builder_core PUBLIC p3p3ds_core) +# The Builder's version lives in one place, builder.rc (release.yml checks +# release tags against it); the update check (#67) reads it from there. +file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/platform/pc/builder/builder.rc" _builder_version_line REGEX "VALUE \"FileVersion\"") +string(REGEX MATCH "[0-9]+\\.[0-9]+\\.[0-9]+" P3P3DS_BUILDER_VERSION "${_builder_version_line}") +if(NOT P3P3DS_BUILDER_VERSION) + message(FATAL_ERROR "no FileVersion in platform/pc/builder/builder.rc") +endif() +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/platform/pc/builder/builder.rc") +target_compile_definitions(p3p3ds_builder_core PRIVATE P3P3DS_BUILDER_VERSION="${P3P3DS_BUILDER_VERSION}") # ISO -> eboot.elf for the developer setup (tools/prepare_game.py delegates to it). # Built without game files, so a fresh checkout can prepare the ELF first. add_executable(p3p_prepare_elf platform/pc/builder/prepare_elf_main.cpp) @@ -367,7 +377,7 @@ endif() if(WIN32) enable_language(RC) add_executable(p3p3ds_builder WIN32 platform/pc/builder/builder_main.cpp platform/pc/builder/pipeline.cpp platform/pc/builder/builder.rc) - target_link_libraries(p3p3ds_builder PRIVATE p3p3ds_builder_core p3p3ds_core comctl32 comdlg32 shell32 ole32) + target_link_libraries(p3p3ds_builder PRIVATE p3p3ds_builder_core p3p3ds_core comctl32 comdlg32 shell32 ole32 winhttp) target_compile_definitions(p3p3ds_builder PRIVATE UNICODE _UNICODE) if(MINGW) target_link_options(p3p3ds_builder PRIVATE -municode -static) @@ -380,6 +390,9 @@ endif() set_target_properties(p3p3ds_builder PROPERTIES OUTPUT_NAME "P3P3DS-Builder") configure_file(profiles/p3p/config/aot_layout.hpp.in generated/aot_layout.hpp @ONLY) target_include_directories(p3p3ds_builder PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/generated") +add_executable(test_update_check tests/test_update_check.cpp) +target_link_libraries(test_update_check PRIVATE p3p3ds_builder_core) +add_test(NAME p3p_update_check COMMAND test_update_check "${P3P3DS_BUILDER_VERSION}") add_executable(test_psp_eboot tests/test_psp_eboot.cpp) target_link_libraries(test_psp_eboot PRIVATE p3p3ds_builder_core p3p3ds_core) file(GLOB P3P_LOCAL_ISOS "${CMAKE_CURRENT_SOURCE_DIR}/*.iso") diff --git a/README.md b/README.md index d9c886a6..ba22ea78 100644 --- a/README.md +++ b/README.md @@ -115,6 +115,8 @@ You need: 3. Wait about 5-15 minutes: the game's code is translated to C++ and compiled for the 3DS on all CPU cores, with a progress bar, a time estimate and Persona 3 trivia. An interrupted build continues where it stopped. 4. The builder can copy everything to your SD card itself; otherwise copy as shown below. +When a newer Builder is released, the window shows **Update: Builder X.Y.Z is available** in its bottom left corner; the button opens the release page. The Windows wizard only asks GitHub for the latest release tag when it starts (nothing is downloaded or installed, no identifiers are sent); `--no-update-check` or the environment variable `P3P3DS_NO_UPDATE_CHECK=1` turns that off, and `--cli` builds never check. `P3P3DS-Builder.exe --check-update` prints the result in a console, `--version` shows the version. + On Linux the builder is a console program (`P3P3DS-Builder--linux.tar.gz`): `./P3P3DS-Builder --iso [--devkitpro ] [--out ] [--jobs ]`; devkitPro is looked up in `$DEVKITPRO`, then `/opt/devkitpro`. On NixOS run it inside `p3p-3ds` from `shell.nix`, where devkitPro's prebuilt binaries work. The builder package (about 2 MB zipped) contains no game data: only the prebuilt P3P3DS runtime for the 3DS, the code generator and the community CWCheat patch list; everything made from the game is generated on your PC. Measured clean builds on a 12-thread CPU: 4 min 23 s with 12 compiler jobs, 4 min 55 s with 7 (the builder picks the number from CPU cores and free memory). diff --git a/docs/CURRENT_STATE.md b/docs/CURRENT_STATE.md index 9a390257..f9267069 100644 --- a/docs/CURRENT_STATE.md +++ b/docs/CURRENT_STATE.md @@ -2,6 +2,16 @@ This is the current source of truth, newest entries first. Evidence concerns ULUS-10512; each section says whether it was measured on the PC runner, in Azahar or on a real New 3DS. +## Builder 0.3.3 release preparation (2026-11-05) + +- `platform/pc/builder/builder.rc` FileVersion and ProductVersion 0.3.3 ([#69](https://github.com/endercodezz/P3P3DS/issues/69)). Contents since 0.3.2: Builder update notice (#67), texture packs (texpack converter, PPSSPP-compatible keys, replacement on the PC and in the 3DS renderer), native game preparation (#33), host time audit docs (#50), Zig BinDiff tool. +- [UNVERIFIED] Texture replacement on the New 3DS (Azahar or hardware): merged on the maintainer's decision without that check. + +## Builder shows when a newer release exists (#67, 2026-11-05) + +- `platform/pc/builder/update_check.cpp` (version parsing, top-level `tag_name` of a GitHub releases/latest response, comparison; no network code) and the wizard (`builder_main.cpp`): on start a detached thread GETs `https://api.github.com/repos/endercodezz/P3P3DS/releases/latest` with WinHTTP (5 s timeouts, `User-Agent: P3P3DS-Builder/`), and a newer tag shows a bottom-left button that opens `https://github.com/endercodezz/P3P3DS/releases/tag/`. The page URL is built from the validated tag, never taken from the response. Off with `--no-update-check` or `P3P3DS_NO_UPDATE_CHECK`; `--cli` never checks; `--check-update` prints the result; `P3P3DS_UPDATE_URL` overrides the URL for tests. The version comes from `builder.rc` FileVersion through CMake, so a release still bumps one place. +- [VERIFIED] Windows: real API: "latest release: v0.3.2; no update" in about 1 s. Local test server returning `v9.9.9` (with a foreign `html_url` and a nested `tag_name`): banner "Update: Builder 9.9.9 is available" (window capture `.tmp/upd/banner.png`), page built from the tag. Unreachable server: no banner, `--check-update` returns after about 2 s. Server log: 0 requests from `--cli`, `--no-update-check` and `P3P3DS_NO_UPDATE_CHECK=1`. Imports: system DLLs and UCRT only, plus `WINHTTP.dll`. `test_update_check` and CTest 32/32. [UNVERIFIED] Linux console Builder: only `--version`, no check. + ## Texture pack format: Rust writer and C++ reader tested together (#63, 2026-11-05) - CTest `p3p_texpack_build_rgba8` / `p3p_texpack_build_auto` run `p3p-texpack build` on `tools/texpack/tests/fixtures` (`textures.ini` there), `p3p_texpack_roundtrip` (`tests/test_texture_pack_roundtrip.cpp`) reads both packs with the runtime's `TexturePack` and compares every texel with the fixture formulas after the format's rules (header, entry order, alignment, row order, tiling, format codes, channel packing, keep-original entry). Registered only when CMake finds `cargo` (Linux CI and local builds; not the MSYS2 Windows job). diff --git a/docs/NEXT_STEPS.md b/docs/NEXT_STEPS.md index 1852c822..63fa0689 100644 --- a/docs/NEXT_STEPS.md +++ b/docs/NEXT_STEPS.md @@ -2,11 +2,12 @@ Updated 2026-11-05. What is done and measured lives in [`CURRENT_STATE.md`](CURRENT_STATE.md); this file only lists what comes next, in the maintainer's priority order. Every step names how it will be verified (CLAUDE.md section 3: measure first). Each step is tracked as a [GitHub issue](https://github.com/endercodezz/P3P3DS/issues) and lands through a pull request that closes it (CLAUDE.md section 16). -## Where the project stands (0.3.2) +## Where the project stands (0.3.3) - Whole `.text` statically recompiled, HLE kernel, VFS with the mod chain, GE executor, deterministic PC runner with scripted input; the PC route plays through the first battle (maintainer's save, local route). - New 3DS (0.3.0/0.3.1, New 2DS XL): PICA200 renderer with a vertex shader (transform, skinning, lighting), GE back end on core 2, real-time pacing, save/load menu on the bottom screen. Dorm 28-30 fps, dialogue mostly 30, battle 16-25 fps; a user's 0.3.1 run at 97-99 % speed; no sound, no opening movie. - 0.3.2 includes the startup logo fix (4d198db, verified in Azahar and reported working by the maintainer on console in [#5](https://github.com/endercodezz/P3P3DS/issues/5)). +- 0.3.3: texture packs made for PPSSPP convert with `tools/texpack` and replace textures on the PC ([#62](https://github.com/endercodezz/P3P3DS/pull/62)); the New 3DS path (`sdmc:/p3p3ds/textures`) is in the build but not yet tested on Azahar or hardware ([#23](https://github.com/endercodezz/P3P3DS/issues/23)). The Builder shows when a newer release exists ([#67](https://github.com/endercodezz/P3P3DS/issues/67)). - P3P3DS Builder for Windows and Linux; releases built by GitHub Actions. ## 0. Check fades and transitions on hardware diff --git a/platform/pc/builder/builder.rc b/platform/pc/builder/builder.rc index 95c49c88..bc6346fc 100644 --- a/platform/pc/builder/builder.rc +++ b/platform/pc/builder/builder.rc @@ -5,8 +5,8 @@ 1 RT_MANIFEST "builder.manifest" VS_VERSION_INFO VERSIONINFO -FILEVERSION 0,3,2,0 -PRODUCTVERSION 0,3,2,0 +FILEVERSION 0,3,3,0 +PRODUCTVERSION 0,3,3,0 FILEOS VOS_NT_WINDOWS32 FILETYPE VFT_APP BEGIN @@ -16,10 +16,10 @@ BEGIN BEGIN VALUE "CompanyName", "enderlit aka endercodezz" VALUE "FileDescription", "P3P3DS Builder - Persona 3 Portable for New 3DS" - VALUE "FileVersion", "0.3.2" + VALUE "FileVersion", "0.3.3" VALUE "LegalCopyright", "MIT License. Persona 3 Portable (c) ATLUS." VALUE "ProductName", "P3P3DS Builder" - VALUE "ProductVersion", "0.3.2" + VALUE "ProductVersion", "0.3.3" END END BLOCK "VarFileInfo" diff --git a/platform/pc/builder/builder_main.cpp b/platform/pc/builder/builder_main.cpp index c471f95a..7ec92994 100644 --- a/platform/pc/builder/builder_main.cpp +++ b/platform/pc/builder/builder_main.cpp @@ -5,6 +5,7 @@ // [--jobs ] [--work ]` runs the same build in a console. // Linux and other POSIX hosts: console only, same options (`--cli` optional). #include "pipeline.hpp" +#include "update_check.hpp" #ifdef _WIN32 #include "fun_facts.hpp" @@ -16,6 +17,7 @@ #include #include #include +#include #endif #include @@ -67,12 +69,12 @@ int run_console(const Settings &s) { namespace { constexpr int kWidth = 620, kHeight = 470, kHeader = 64; -constexpr UINT WM_BUILD_PROGRESS = WM_APP + 1, WM_BUILD_LOG = WM_APP + 2, WM_BUILD_DONE = WM_APP + 3; +constexpr UINT WM_BUILD_PROGRESS = WM_APP + 1, WM_BUILD_LOG = WM_APP + 2, WM_BUILD_DONE = WM_APP + 3, WM_UPDATE_FOUND = WM_APP + 4; constexpr UINT_PTR kFactTimer = 1; enum Id : int { IdBack = 100, IdNext, IdCancel, IdIso, IdIsoBrowse, IdIsoStatus, IdDkp, IdDkpBrowse, IdDkpStatus, IdDkpLink, IdOut, IdOutBrowse, IdSdCheck, IdSdDrive, - IdStep, IdBar, IdTime, IdFact, IdNextFact, IdLog, IdOpenFolder, + IdStep, IdBar, IdTime, IdFact, IdNextFact, IdLog, IdOpenFolder, IdUpdate, IdUpdateClose, }; enum Page { Welcome, Setup, Build, Finish }; @@ -85,6 +87,8 @@ struct App { HWND back{}, next{}, cancel{}; HWND iso{}, iso_status{}, dkp{}, dkp_status{}, out{}, sd_check{}, sd_drive{}; HWND step{}, bar{}, time{}, fact{}, log{}, finish_text{}, open_folder{}; + HWND update{}, update_close{}; + std::wstring update_page; fs::path exe_dir; std::unique_ptr pipeline; std::thread worker; @@ -242,7 +246,8 @@ void create_controls() { L"This wizard builds P3P3DS - Persona 3 Portable running natively on the New Nintendo 3DS - " L"from your own copy of the game (ULUS-10512).\n\n" L"It reads the game's executable from your ISO, translates it to native 3DS code and packages " - L"p3p3ds.3dsx for the Homebrew Launcher. Nothing is downloaded.\n\n" + L"p3p3ds.3dsx for the Homebrew Launcher. Nothing is downloaded; the Builder only asks GitHub whether a newer " + L"version exists (start it with --no-update-check to turn that off).\n\n" L"You need: your Persona 3 Portable ISO, and devkitPro with the 3DS development tools installed. " L"The build takes about 5-15 minutes depending on your CPU.\n\n" L"The result contains code made from your game: it is for you only. Please do not share it.\n\n" @@ -290,7 +295,13 @@ void create_controls() { reinterpret_cast(IdNext), app.inst, nullptr); app.cancel = CreateWindowExW(0, L"BUTTON", L"Exit", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, kWidth - 108, kHeight - 44, 86, 28, app.wnd, reinterpret_cast(IdCancel), app.inst, nullptr); - for (HWND b : {app.back, app.next, app.cancel}) SendMessageW(b, WM_SETFONT, reinterpret_cast(app.font), TRUE); + // Update banner (#67), hidden until a newer release is found. + app.update = CreateWindowExW(0, L"BUTTON", L"", WS_CHILD | BS_PUSHBUTTON, left, kHeight - 44, 230, 28, app.wnd, + reinterpret_cast(IdUpdate), app.inst, nullptr); + app.update_close = CreateWindowExW(0, L"BUTTON", L"x", WS_CHILD | BS_PUSHBUTTON, left + 234, kHeight - 44, 28, 28, app.wnd, + reinterpret_cast(IdUpdateClose), app.inst, nullptr); + for (HWND b : {app.back, app.next, app.cancel, app.update, app.update_close}) + SendMessageW(b, WM_SETFONT, reinterpret_cast(app.font), TRUE); // Defaults: the single ISO next to the builder, devkitPro guess, output folder next to the builder. for (const auto &e : fs::directory_iterator(app.exe_dir)) @@ -367,6 +378,11 @@ LRESULT CALLBACK wnd_proc(HWND h, UINT msg, WPARAM wp, LPARAM lp) { if (!f.empty()) SetWindowTextW(app.out, f.c_str()); } else if (id == IdDkpLink) { ShellExecuteW(h, L"open", L"https://devkitpro.org/wiki/Getting_Started", nullptr, nullptr, SW_SHOWNORMAL); + } else if (id == IdUpdate) { + ShellExecuteW(h, L"open", app.update_page.c_str(), nullptr, nullptr, SW_SHOWNORMAL); + } else if (id == IdUpdateClose) { + ShowWindow(app.update, SW_HIDE); + ShowWindow(app.update_close, SW_HIDE); } else if (id == IdNextFact) { next_fact(); } else if (id == IdOpenFolder) { @@ -400,6 +416,15 @@ LRESULT CALLBACK wnd_proc(HWND h, UINT msg, WPARAM wp, LPARAM lp) { SendMessageW(app.log, EM_REPLACESEL, FALSE, reinterpret_cast(w.c_str())); return 0; } + case WM_UPDATE_FOUND: { + std::unique_ptr update(reinterpret_cast(lp)); + app.update_page = widen(update->page); + const std::wstring label = L"Update: Builder " + widen(version_string(update->version)) + L" is available"; + SetWindowTextW(app.update, label.c_str()); + ShowWindow(app.update, SW_SHOW); + ShowWindow(app.update_close, SW_SHOW); + return 0; + } case WM_BUILD_DONE: { std::unique_ptr err(reinterpret_cast(lp)); if (app.worker.joinable()) app.worker.join(); @@ -435,6 +460,62 @@ LRESULT CALLBACK wnd_proc(HWND h, UINT msg, WPARAM wp, LPARAM lp) { } } +// GET `url` with WinHTTP (system DLL; the Builder stays statically linked +// against system DLLs only). Empty on any failure; 5 s timeouts; at most 1 MiB. +std::string http_get(const std::wstring &url) { + wchar_t host[256], path[2048]; + URL_COMPONENTS parts{}; + parts.dwStructSize = sizeof parts; + parts.lpszHostName = host; + parts.dwHostNameLength = 256; + parts.lpszUrlPath = path; + parts.dwUrlPathLength = 2048; + if (!WinHttpCrackUrl(url.c_str(), 0, 0, &parts)) return {}; + const std::wstring agent = L"P3P3DS-Builder/" + widen(version_string(builder_version())); + std::string body; + HINTERNET session = WinHttpOpen(agent.c_str(), WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); + HINTERNET connection = session ? WinHttpConnect(session, host, parts.nPort, 0) : nullptr; + HINTERNET request = connection ? WinHttpOpenRequest(connection, L"GET", path, nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, + parts.nScheme == INTERNET_SCHEME_HTTPS ? WINHTTP_FLAG_SECURE : 0) + : nullptr; + if (session) WinHttpSetTimeouts(session, 5000, 5000, 5000, 5000); + DWORD status = 0, size = sizeof status; + if (request && WinHttpSendRequest(request, L"Accept: application/vnd.github+json\r\n", static_cast(-1), WINHTTP_NO_REQUEST_DATA, 0, 0, 0) && + WinHttpReceiveResponse(request, nullptr) && + WinHttpQueryHeaders(request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &status, &size, + WINHTTP_NO_HEADER_INDEX) && + status == 200) { + char buffer[8192]; + DWORD read = 0; + while (body.size() < (1u << 20) && WinHttpReadData(request, buffer, sizeof buffer, &read) && read > 0) body.append(buffer, read); + } + if (request) WinHttpCloseHandle(request); + if (connection) WinHttpCloseHandle(connection); + if (session) WinHttpCloseHandle(session); + return body; +} + +bool update_check_enabled(int argc, wchar_t **argv) { + for (int i = 1; i < argc; ++i) + if (std::wstring(argv[i]) == L"--no-update-check") return false; + const char *off = std::getenv(kNoUpdateCheckEnv); + return off == nullptr || off[0] == '\0' || std::string(off) == "0"; +} + +// Asks GitHub for the latest release on a detached thread (a slow network +// must not hold up closing the window) and posts WM_UPDATE_FOUND if it is newer. +void start_update_check(HWND wnd) { + const char *override_url = std::getenv(kUpdateUrlEnv); + const std::wstring url = widen(override_url && override_url[0] ? override_url : kLatestReleaseUrl); + std::thread([wnd, url] { + const std::string body = http_get(url); + if (auto update = newer_release(body, builder_version())) { + auto *message = new Update(std::move(*update)); + if (!PostMessageW(wnd, WM_UPDATE_FOUND, 0, reinterpret_cast(message))) delete message; // window already gone + } + }).detach(); +} + int run_cli(int argc, wchar_t **argv) { // Keep a redirected stdout (file/pipe); otherwise write to the parent console. const HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); @@ -465,6 +546,27 @@ int WINAPI wWinMain(HINSTANCE inst, HINSTANCE, PWSTR, int show) { wchar_t **argv = CommandLineToArgvW(GetCommandLineW(), &argc); for (int i = 1; i < argc; ++i) if (std::wstring(argv[i]) == L"--cli") return run_cli(argc, argv); + for (int i = 1; i < argc; ++i) + if (std::wstring(argv[i]) == L"--check-update") { // console: the wizard's check, printed + const HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); + if (out == nullptr || out == INVALID_HANDLE_VALUE || GetFileType(out) == FILE_TYPE_UNKNOWN) { + if (!AttachConsole(ATTACH_PARENT_PROCESS)) AllocConsole(); + std::freopen("CONOUT$", "w", stdout); + } + const char *override_url = std::getenv(kUpdateUrlEnv); + const std::string body = http_get(widen(override_url && override_url[0] ? override_url : kLatestReleaseUrl)); + const auto tag = latest_release_tag(body); + const auto update = newer_release(body, builder_version()); + std::printf("P3P3DS Builder %s; latest release: %s; %s\n", version_string(builder_version()).c_str(), + tag ? tag->c_str() : "unknown (no answer)", update ? ("update available: " + update->page).c_str() : "no update"); + return 0; + } + for (int i = 1; i < argc; ++i) + if (std::wstring(argv[i]) == L"--version") { + const std::wstring text = L"P3P3DS Builder " + widen(version_string(builder_version())); + MessageBoxW(nullptr, text.c_str(), L"P3P3DS Builder", MB_OK | MB_ICONINFORMATION); + return 0; + } SetProcessDPIAware(); INITCOMMONCONTROLSEX icc{sizeof icc, ICC_PROGRESS_CLASS | ICC_STANDARD_CLASSES}; @@ -496,6 +598,7 @@ int WINAPI wWinMain(HINSTANCE inst, HINSTANCE, PWSTR, int show) { create_controls(); show_page(Welcome); ShowWindow(app.wnd, show); + if (update_check_enabled(argc, argv)) start_update_check(app.wnd); MSG msg; while (GetMessageW(&msg, nullptr, 0, 0)) { if (!IsDialogMessageW(app.wnd, &msg)) { @@ -518,6 +621,10 @@ int main(int argc, char **argv) { const std::string a = argv[i]; const bool has_value = i + 1 < argc; if (a == "--cli") continue; + if (a == "--version") { + std::printf("P3P3DS Builder %s\n", version_string(builder_version()).c_str()); + return 0; + } if (a == "--help" || a == "-h") { std::printf("usage: %s --iso [--devkitpro ] [--out ] [--jobs ] [--work ]\n", argv[0]); return 0; diff --git a/platform/pc/builder/update_check.cpp b/platform/pc/builder/update_check.cpp new file mode 100644 index 00000000..9df018e5 --- /dev/null +++ b/platform/pc/builder/update_check.cpp @@ -0,0 +1,81 @@ +// See update_check.hpp. +#include "update_check.hpp" + +#ifndef P3P3DS_BUILDER_VERSION +#error "P3P3DS_BUILDER_VERSION must come from builder.rc (CMakeLists.txt)" +#endif + +namespace p3p3ds::builder { + +std::optional parse_version(std::string_view text) { + if (!text.empty() && (text.front() == 'v' || text.front() == 'V')) text.remove_prefix(1); + unsigned parts[3]{}; + for (int i = 0; i < 3; ++i) { + std::size_t n = 0; + unsigned value = 0; + while (n < text.size() && text[n] >= '0' && text[n] <= '9') { + value = value * 10 + static_cast(text[n] - '0'); + if (++n > 4) return std::nullopt; + } + if (n == 0) return std::nullopt; + parts[i] = value; + text.remove_prefix(n); + if (i < 2) { + if (text.empty() || text.front() != '.') return std::nullopt; + text.remove_prefix(1); + } + } + if (!text.empty()) return std::nullopt; + return Version{parts[0], parts[1], parts[2]}; +} + +std::string version_string(const Version &v) { + return std::to_string(v.major) + "." + std::to_string(v.minor) + "." + std::to_string(v.patch); +} + +std::optional latest_release_tag(std::string_view json) { + // The release object's own keys sit at depth 1; nested objects (author, + // assets) are skipped so their fields can't be mistaken for the tag. + int depth = 0; + bool in_string = false; + std::size_t string_start = 0; + for (std::size_t i = 0; i < json.size(); ++i) { + const char c = json[i]; + if (in_string) { + if (c == '\\') { ++i; continue; } + if (c != '"') continue; + in_string = false; + if (depth != 1 || json.substr(string_start, i - string_start) != "tag_name") continue; + std::size_t j = i + 1; + while (j < json.size() && (json[j] == ' ' || json[j] == '\t' || json[j] == '\r' || json[j] == '\n')) ++j; + if (j >= json.size() || json[j] != ':') continue; // a value, not a key + ++j; + while (j < json.size() && (json[j] == ' ' || json[j] == '\t' || json[j] == '\r' || json[j] == '\n')) ++j; + if (j >= json.size() || json[j] != '"') return std::nullopt; + const std::size_t start = ++j; + while (j < json.size() && json[j] != '"' && json[j] != '\\') ++j; + if (j >= json.size() || json[j] != '"') return std::nullopt; // unterminated or escaped + return std::string(json.substr(start, j - start)); + } + if (c == '"') { in_string = true; string_start = i + 1; } + else if (c == '{' || c == '[') ++depth; + else if (c == '}' || c == ']') --depth; + } + return std::nullopt; +} + +std::optional newer_release(std::string_view json, const Version ¤t) { + const auto tag = latest_release_tag(json); + if (!tag) return std::nullopt; + const auto version = parse_version(*tag); + if (!version || !(*version > current)) return std::nullopt; + // The tag passed parse_version, so it is only 'v', digits and dots. + return Update{*version, std::string(kReleasesPageBase) + *tag}; +} + +Version builder_version() { + static const Version v = parse_version(P3P3DS_BUILDER_VERSION).value_or(Version{}); + return v; +} + +} // namespace p3p3ds::builder diff --git a/platform/pc/builder/update_check.hpp b/platform/pc/builder/update_check.hpp new file mode 100644 index 00000000..341c7ed7 --- /dev/null +++ b/platform/pc/builder/update_check.hpp @@ -0,0 +1,45 @@ +#pragma once +// "A newer Builder is available" (#67): the wizard asks GitHub for the latest +// release and compares its tag with its own version. This part has no network +// code (builder_main.cpp does the request) so it can be unit-tested. +#include +#include +#include +#include + +namespace p3p3ds::builder { + +// GitHub REST API: latest published release (drafts and pre-releases excluded). +inline constexpr const char *kLatestReleaseUrl = "https://api.github.com/repos/endercodezz/P3P3DS/releases/latest"; +inline constexpr const char *kReleasesPageBase = "https://github.com/endercodezz/P3P3DS/releases/tag/"; +// Set to anything but "" or "0": no update check (also --no-update-check). +inline constexpr const char *kNoUpdateCheckEnv = "P3P3DS_NO_UPDATE_CHECK"; +// Test hook: request this URL instead of kLatestReleaseUrl. +inline constexpr const char *kUpdateUrlEnv = "P3P3DS_UPDATE_URL"; + +struct Version { + unsigned major{}, minor{}, patch{}; + auto operator<=>(const Version &) const = default; +}; + +// "v1.2.3" or "1.2.3"; anything else (suffixes such as "-rc1", missing or extra +// parts, values above 9999) -> nullopt. +[[nodiscard]] std::optional parse_version(std::string_view text); +[[nodiscard]] std::string version_string(const Version &v); + +// The top-level "tag_name" string of a releases/latest response; nullopt for +// anything unexpected (error bodies, escapes, non-version tags). +[[nodiscard]] std::optional latest_release_tag(std::string_view json); + +struct Update { + Version version; + std::string page; // kReleasesPageBase + tag, built locally (never a URL from the response) +}; + +// The release in `json` when it is newer than `current`. +[[nodiscard]] std::optional newer_release(std::string_view json, const Version ¤t); + +// The version this Builder was built as (FileVersion in builder.rc). +[[nodiscard]] Version builder_version(); + +} // namespace p3p3ds::builder diff --git a/tests/test_update_check.cpp b/tests/test_update_check.cpp new file mode 100644 index 00000000..ebbff6af --- /dev/null +++ b/tests/test_update_check.cpp @@ -0,0 +1,77 @@ +// Builder update check (#67, platform/pc/builder/update_check.cpp): version +// parsing and comparison, the tag of a GitHub releases/latest response, and +// the release page URL built from it. +// test_update_check +#include "update_check.hpp" + +#include +#include + +using namespace p3p3ds::builder; + +namespace { +int failures = 0; +void check(bool ok, const char *what) { + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } +} + +// Shape of a real api.github.com releases/latest response (trimmed): the +// author object and assets carry their own html_url / name fields. +const char *kResponse = R"({ + "url": "https://api.github.com/repos/endercodezz/P3P3DS/releases/1", + "html_url": "https://github.com/endercodezz/P3P3DS/releases/tag/v0.3.3", + "id": 1, + "author": {"login": "endercodezz", "tag_name": "v9.9.9", "html_url": "https://github.com/endercodezz"}, + "tag_name" : "v0.3.3", + "name": "P3P3DS Builder 0.3.3", + "draft": false, + "prerelease": false, + "assets": [{"name": "P3P3DS-Builder-0.3.3.zip", "tag_name": "v8.0.0"}] +})"; +} // namespace + +int main(int argc, char **argv) { + // Versions. + check(parse_version("v0.3.2") == Version{0, 3, 2}, "v0.3.2"); + check(parse_version("1.10.0") == Version{1, 10, 0}, "1.10.0"); + check(!parse_version("v0.3"), "two parts"); + check(!parse_version("v0.3.2.1"), "four parts"); + check(!parse_version("v0.3.3-rc1"), "suffix"); + check(!parse_version("v0.3.x"), "letters"); + check(!parse_version(""), "empty"); + check(!parse_version("v12345.0.0"), "too long"); + check(Version{0, 10, 0} > Version{0, 9, 9}, "numeric, not lexical order"); + check(version_string({1, 2, 30}) == "1.2.30", "version_string"); + + // Tag of the release object, not of nested objects. + const auto tag = latest_release_tag(kResponse); + check(tag && *tag == "v0.3.3", "top-level tag_name"); + check(!latest_release_tag(R"({"message":"API rate limit exceeded for 1.2.3.4.","documentation_url":"https://docs.github.com"})"), + "rate-limit body"); + check(!latest_release_tag(R"({"message":"Not Found"})"), "not found body"); + check(!latest_release_tag(R"({"tag_name": 3})"), "non-string tag"); + check(!latest_release_tag(R"({"tag_name": "v0.3.3)"), "unterminated"); + check(!latest_release_tag(R"({"tag_name": "v0\".3.3"})"), "escaped quote"); + check(!latest_release_tag("Service unavailable"), "not JSON"); + check(!latest_release_tag(""), "empty body"); + check(!latest_release_tag(R"({"name": "tag_name"})"), "tag_name as a value"); + + // Newer? + auto update = newer_release(kResponse, {0, 3, 2}); + check(update && update->version == Version{0, 3, 3}, "0.3.3 is newer than 0.3.2"); + check(update && update->page == "https://github.com/endercodezz/P3P3DS/releases/tag/v0.3.3", "page built from the tag"); + check(!newer_release(kResponse, {0, 3, 3}), "same version"); + check(!newer_release(kResponse, {0, 4, 0}), "older release"); + check(!newer_release(R"({"tag_name": "v0.4.0-beta"})", {0, 3, 2}), "pre-release style tag"); + check(!newer_release(R"j({"tag_name": "javascript:alert(1)"})j", {0, 0, 0}), "a tag that is not a version never becomes a URL"); + + // Built-in version = builder.rc FileVersion. + if (argc > 1) check(parse_version(argv[1]) == builder_version(), "builder_version matches builder.rc"); + check(builder_version() > Version{0, 0, 0}, "builder_version parsed"); + + if (failures == 0) std::printf("test_update_check: all checks passed (builder %s)\n", version_string(builder_version()).c_str()); + return failures == 0 ? 0 : 1; +}