diff --git a/CMakeLists.txt b/CMakeLists.txt index cdbca59..d92f6cf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -59,7 +59,7 @@ include(third_party/hermes.cmake) set(BUREAU_HERMES_FRAMEWORKS "${bureau_hermes_framework_dir}" CACHE INTERNAL "") if(TARGET bureau_hermes) add_library(bureau_js STATIC - src/js/host.cpp src/js/inspect.cpp src/js/ui.cpp src/js/view_bridge.cpp + src/js/awake_clock.cpp src/js/host.cpp src/js/inspect.cpp src/js/ui.cpp src/js/view_bridge.cpp src/js/net/base64.cpp src/js/net/handshake.cpp src/js/net/http_request.cpp src/js/net/websocket_frame.cpp) if(WIN32) diff --git a/include/bureau/backends/quads.h b/include/bureau/backends/quads.h index f130fbb..f0ec234 100644 --- a/include/bureau/backends/quads.h +++ b/include/bureau/backends/quads.h @@ -3,6 +3,7 @@ // itself; see the backends for the one pipeline they need. #pragma once +#include #include #include @@ -47,9 +48,20 @@ struct Batches { std::vector runs; }; +/** The most vertices a frame draws: 128 MB, which every backend's device + * takes in one buffer (Direct3D 11 guarantees no more). */ +inline constexpr std::size_t kMaxVertices = (std::size_t{128} << 20) / sizeof(Vertex); + /** `list` for a target of `width` by `height` pixels, onto which it stretches * when it was laid out for another size: a window leaving fullscreen draws the - * old list into its smaller frame until the UI lays out again. */ + * old list into its smaller frame until the UI lays out again. A quad wholly + * outside its clip is left out, as the scissor would discard it, and past + * kMaxVertices the rest are: the topmost content goes rather than the frame. */ Batches batchesOf(const DisplayList& list, int width, int height); +/** The bytes a vertex buffer holding `held` bytes is made again at for + * `needed`: twice the larger, so a growing list reallocates rarely, and never + * past what kMaxVertices fill, which batchesOf never needs more than. */ +std::uint64_t vertexBufferBytes(std::uint64_t needed, std::uint64_t held); + } // namespace bureau::backends diff --git a/include/bureau/bridge.h b/include/bureau/bridge.h index e9e4d06..f194861 100644 --- a/include/bureau/bridge.h +++ b/include/bureau/bridge.h @@ -29,6 +29,10 @@ jsi::Value jsString(jsi::Runtime& runtime, const std::string& value); /** A value from JavaScript as JSON, through its own JSON.stringify. */ nlohmann::json jsonOf(jsi::Runtime& runtime, const jsi::Value& value); +/** JSON's text for JavaScript. A byte that is not UTF-8 reads as U+FFFD, so + * one bad string costs a letter rather than the turn that carried it. */ +std::string jsonText(const nlohmann::json& value); + void define(jsi::Runtime& runtime, jsi::Object& object, const char* name, jsi::HostFunctionType body); diff --git a/include/bureau/ui.h b/include/bureau/ui.h index c9e8ced..c62a7e2 100644 --- a/include/bureau/ui.h +++ b/include/bureau/ui.h @@ -56,7 +56,10 @@ class Ui { /** The looks, as JSON (tools/tokens.ts). */ std::string tokens; /** A file the UI asks for by its path under the game's assets (`/fonts/…`, - * pictures); nothing when there is none. On the UI's thread. */ + * pictures); nothing when there is none. On the UI's thread for the + * view's faces and pictures, and on a thread of the UI's own for what + * TypeScript reads (`assetText`, `assetBytes`), so it must be safe to + * call from both. */ std::function(const std::string& path)> readAsset; /** The window, in points, and its device pixels per point. */ float width = 1280; diff --git a/kit/native_platform.ts b/kit/native_platform.ts index 31ed7c5..5bb1f5c 100644 --- a/kit/native_platform.ts +++ b/kit/native_platform.ts @@ -11,7 +11,9 @@ import type { KitPlatform, KitStorage } from "./platform.ts"; interface Native { log(level: string, text: string): void; - assetText(path: string): string | null; + /** Reads off the interface's thread and calls `done` with the file, or + * null when there is none. */ + assetText(path: string, done: (text: string | null) => void): void; setClipboard?(text: string): void; storageGet?(key: string): string | null; storageSet?(key: string, value: string): void; @@ -62,7 +64,9 @@ export const platform: KitPlatform = { return Promise.resolve(); }, }, - assets: { text: (path) => Promise.resolve(native.assetText(path)) }, + assets: { + text: (path) => new Promise((resolve) => native.assetText(path, resolve)), + }, shell: { identity: undefined, isSteamDeck: false }, log: { error: (message, ...details) => diff --git a/src/backends/d3d11.cpp b/src/backends/d3d11.cpp index e05f88a..3f5010e 100644 --- a/src/backends/d3d11.cpp +++ b/src/backends/d3d11.cpp @@ -195,11 +195,13 @@ void D3D11Backend::draw(ID3D11DeviceContext* context, const DisplayList& list, Impl& d3d = *impl_; if (d3d.pixelShader == nullptr || list.quads.empty()) return; const auto batches = backends::batchesOf(list, width, height); + if (batches.vertices.empty()) return; const UINT bytes = static_cast(batches.vertices.size() * sizeof(backends::Vertex)); if (bytes > d3d.vertexCapacity) { release(d3d.vertices); - d3d.vertexCapacity = bytes * 2; + d3d.vertexCapacity = + static_cast(backends::vertexBufferBytes(bytes, d3d.vertexCapacity)); D3D11_BUFFER_DESC description{}; description.ByteWidth = d3d.vertexCapacity; description.Usage = D3D11_USAGE_DYNAMIC; diff --git a/src/backends/d3d12.cpp b/src/backends/d3d12.cpp index 6c34036..22f7483 100644 --- a/src/backends/d3d12.cpp +++ b/src/backends/d3d12.cpp @@ -322,11 +322,13 @@ void D3D12Backend::draw(ID3D12GraphicsCommandList* commands, UINT slot, Impl& d3d = *impl_; if (d3d.pipeline == nullptr || list.quads.empty()) return; const auto batches = backends::batchesOf(list, width, height); + if (batches.vertices.empty()) return; const UINT64 bytes = batches.vertices.size() * sizeof(backends::Vertex); HostBuffer& vertices = d3d.slots[slot].vertices; if (bytes > vertices.capacity) { + const UINT64 size = backends::vertexBufferBytes(bytes, vertices.capacity); d3d.destroyBuffer(vertices); - vertices = d3d.createBuffer(bytes * 2); + vertices = d3d.createBuffer(size); } std::memcpy(vertices.mapped, batches.vertices.data(), bytes); diff --git a/src/backends/metal.mm b/src/backends/metal.mm index 7563511..01cad1f 100644 --- a/src/backends/metal.mm +++ b/src/backends/metal.mm @@ -140,6 +140,7 @@ fragment float4 fs_main(VertexOut input [[stage_in]], if (impl_->pipeline == nil || list.quads.empty()) return; id pass = (__bridge id)encoder; const auto batches = backends::batchesOf(list, width, height); + if (batches.vertices.empty()) return; id vertices = [impl_->device newBufferWithBytes:batches.vertices.data() length:batches.vertices.size() * sizeof(backends::Vertex) diff --git a/src/backends/opengl.cpp b/src/backends/opengl.cpp index f356525..fb80dbf 100644 --- a/src/backends/opengl.cpp +++ b/src/backends/opengl.cpp @@ -409,6 +409,7 @@ void OpenGlBackend::draw(const DisplayList& list, int width, int height) { if (list.quads.empty()) return; Impl& gl = *impl_; const auto batches = backends::batchesOf(list, width, height); + if (batches.vertices.empty()) return; GLint program = 0, vertexArray = 0, arrayBuffer = 0, activeTexture = 0; GLint texture[2] = {}, sampler[2] = {}; diff --git a/src/backends/quads.cpp b/src/backends/quads.cpp index 4aa63ae..3338296 100644 --- a/src/backends/quads.cpp +++ b/src/backends/quads.cpp @@ -28,14 +28,37 @@ Scissor scissorOf(const Clip& clip, const DisplayList& list, int width, return {left, top, right - left, bottom - top}; } +/** Whether any of `corners` can reach a pixel of `clip`: a scissor keeps + * nothing of a quad off it, so a long list's rows out of sight cost nothing. */ +bool reaches(const Vertex (&corners)[4], const Clip& clip) { + if (clip.width <= 0 || clip.height <= 0) return false; + float left = corners[0].x, right = corners[0].x; + float top = corners[0].y, bottom = corners[0].y; + for (const Vertex& corner : corners) { + left = std::min(left, corner.x); + right = std::max(right, corner.x); + top = std::min(top, corner.y); + bottom = std::max(bottom, corner.y); + } + const bool across = right > clip.x && left < clip.x + clip.width; + const bool down = bottom > clip.y && top < clip.y + clip.height; + return across && down; +} + } // namespace +std::uint64_t vertexBufferBytes(std::uint64_t needed, std::uint64_t held) { + const std::uint64_t most = kMaxVertices * sizeof(Vertex); + return std::min(std::max(needed, held) * 2, most); +} + Batches batchesOf(const DisplayList& list, int width, int height) { Batches batches; - batches.vertices.reserve(list.quads.size() * 6); + batches.vertices.reserve(std::min(list.quads.size() * 6, kMaxVertices)); int page = -1; int clip = -1; for (const Quad& quad : list.quads) { + if (batches.vertices.size() + 6 > kMaxVertices) break; const float mode = static_cast(quad.mode); const float stipple = static_cast(quad.stipple); const float smooth = quad.smooth ? 1.0f : 0.0f; @@ -58,10 +81,11 @@ Batches batchesOf(const DisplayList& list, int width, int height) { corner.y = quad.originY + x * sine + y * cosine; } } + const Clip& rect = + list.clips[std::min(quad.clip, list.clips.size() - 1)]; + if (!reaches(corners, rect)) continue; const bool startsRun = quad.page != page || quad.clip != clip; if (startsRun) { - const Clip& rect = - list.clips[std::min(quad.clip, list.clips.size() - 1)]; batches.runs.push_back( {static_cast(batches.vertices.size()), 0, quad.page, scissorOf(rect, list, width, height)}); diff --git a/src/backends/vulkan.cpp b/src/backends/vulkan.cpp index b2225e9..b9ab516 100644 --- a/src/backends/vulkan.cpp +++ b/src/backends/vulkan.cpp @@ -459,11 +459,14 @@ void VulkanBackend::draw(VkCommandBuffer commands, std::uint32_t slot, Impl& vk = *impl_; if (vk.pipeline == VK_NULL_HANDLE || list.quads.empty()) return; const auto batches = backends::batchesOf(list, width, height); + if (batches.vertices.empty()) return; const VkDeviceSize bytes = batches.vertices.size() * sizeof(backends::Vertex); HostBuffer& vertices = vk.slots[slot].vertices; if (bytes > vertices.capacity) { + const VkDeviceSize size = + backends::vertexBufferBytes(bytes, vertices.capacity); vk.destroyBuffer(vertices); - vertices = vk.createBuffer(bytes * 2, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT); + vertices = vk.createBuffer(size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT); } std::memcpy(vertices.mapped, batches.vertices.data(), bytes); diff --git a/src/js/awake_clock.cpp b/src/js/awake_clock.cpp new file mode 100644 index 0000000..19cd0dc --- /dev/null +++ b/src/js/awake_clock.cpp @@ -0,0 +1,66 @@ +// LEAN_AND_MEAN and NOMINMAX before any include: pulls in less +// and leaves std::min and std::max alone. +#if defined(_WIN32) +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#endif + +#include "awake_clock.h" + +#include + +#if defined(__APPLE__) +#include +#endif + +namespace bureau::js { + +#if defined(__APPLE__) + +std::int64_t awakeNanoseconds() { + return static_cast(clock_gettime_nsec_np(CLOCK_UPTIME_RAW)); +} + +#elif defined(_WIN32) + +namespace { + +using UnbiasedTime = VOID(WINAPI*)(PULONGLONG); + +/** Windows 10's precise unbiased interrupt time, in 100 ns units, leaves out + * sleep and hibernation; looked up rather than linked, since only mincore.lib + * names it. */ +UnbiasedTime unbiasedTime() { + const HMODULE kernel = GetModuleHandleW(L"kernelbase.dll"); + if (kernel == nullptr) return nullptr; + return reinterpret_cast( + GetProcAddress(kernel, "QueryUnbiasedInterruptTimePrecise")); +} + +} // namespace + +std::int64_t awakeNanoseconds() { + static const UnbiasedTime read = unbiasedTime(); + if (read == nullptr) { + return std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()) + .count(); + } + ULONGLONG hundreds = 0; + read(&hundreds); + return static_cast(hundreds) * 100; +} + +#else + +// CLOCK_MONOTONIC, which stops while Linux and Android suspend. +std::int64_t awakeNanoseconds() { + return std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()) + .count(); +} + +#endif + +} // namespace bureau::js diff --git a/src/js/awake_clock.h b/src/js/awake_clock.h new file mode 100644 index 0000000..18c3059 --- /dev/null +++ b/src/js/awake_clock.h @@ -0,0 +1,15 @@ +#pragma once + +#include + +namespace bureau::js { + +/** + * Nanoseconds the machine has spent awake, from an arbitrary start: the clock + * behind performance.now(). It stops while the machine sleeps, so a game can + * tell a sleep (the wall clock ran on alone) from a thread that stalled. + * std::chrono::steady_clock runs on through sleep on macOS and Windows. + */ +std::int64_t awakeNanoseconds(); + +} // namespace bureau::js diff --git a/src/js/host.cpp b/src/js/host.cpp index bce59f1..589d429 100644 --- a/src/js/host.cpp +++ b/src/js/host.cpp @@ -1,5 +1,7 @@ #include "host.h" +#include "awake_clock.h" + #include #include #if BUREAU_ENABLE_DEBUGGER @@ -7,6 +9,8 @@ #include #endif +#include "net/base64.h" + #include #include #include @@ -17,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -71,6 +76,76 @@ std::string profilerFailure(Call&& call) { } } +[[noreturn]] void throwError(jsi::Runtime& js, const char* kind, + const std::string& message) { + jsi::Value error = js.global().getPropertyAsFunction(js, kind) + .callAsConstructor(js, jsi::String::createFromUtf8( + js, message)); + throw jsi::JSError(js, std::move(error)); +} + +/** One of an options object's string choices, or `fallback` when it names + * none; anything else is a TypeError, as the standard says. */ +std::string option(jsi::Runtime& js, const jsi::Object& options, + const char* name, const char* fallback, + std::initializer_list allowed) { + const jsi::Value value = options.getProperty(js, name); + if (value.isUndefined()) return fallback; + const std::string chosen = + value.isString() ? value.getString(js).utf8(js) : std::string(); + for (const char* known : allowed) { + if (chosen == known) return chosen; + } + throwError(js, "TypeError", + std::string("Uint8Array.fromBase64: unknown ") + name); +} + +/** ECMAScript 2026's `Uint8Array.fromBase64`, while Hermes has none: a + * loop in Hermes's interpreter takes a quarter of a second over a megabyte + * of base64, all of it in one turn. */ +void install_from_base64(jsi::Runtime& js) { + jsi::Object uint8 = js.global().getPropertyAsObject(js, "Uint8Array"); + if (!uint8.getProperty(js, "fromBase64").isUndefined()) return; + const auto fromBase64 = [](jsi::Runtime& js, const jsi::Value&, + const jsi::Value* args, size_t count) { + if (count == 0 || !args[0].isString()) + throwError(js, "TypeError", "Uint8Array.fromBase64 reads a string"); + const bool hasOptions = count > 1 && !args[1].isUndefined(); + if (hasOptions && !args[1].isObject()) + throwError(js, "TypeError", "Uint8Array.fromBase64's options"); + const jsi::Object options = + hasOptions ? args[1].getObject(js) : jsi::Object(js); + const bool url = + option(js, options, "alphabet", "base64", {"base64", "base64url"}) == + "base64url"; + const std::string last = + option(js, options, "lastChunkHandling", "loose", + {"loose", "strict", "stop-before-partial"}); + const net::LastChunk handling = + last == "strict" ? net::LastChunk::Strict + : last == "stop-before-partial" ? net::LastChunk::StopBeforePartial + : net::LastChunk::Loose; + const net::Decoded decoded = + net::fromBase64(args[0].getString(js).utf8(js), url, handling); + if (!decoded.error.empty()) throwError(js, "SyntaxError", decoded.error); + const double length = static_cast(decoded.bytes.size()); + jsi::Object array = js.global() + .getPropertyAsFunction(js, "Uint8Array") + .callAsConstructor(js, length) + .getObject(js); + jsi::ArrayBuffer buffer = + array.getProperty(js, "buffer").getObject(js).getArrayBuffer(js); + if (!decoded.bytes.empty()) { + std::memcpy(buffer.data(js), decoded.bytes.data(), decoded.bytes.size()); + } + return jsi::Value(std::move(array)); + }; + uint8.setProperty(js, "fromBase64", + jsi::Function::createFromHostFunction( + js, jsi::PropNameID::forAscii(js, "fromBase64"), 1, + fromBase64)); +} + // A microtask that throws ends the drain with a JSError: callers guard it, // or it escapes the engine thread and terminates the program unreported. void drain(jsi::Runtime& runtime) { @@ -101,7 +176,7 @@ std::string name_of(jsi::Runtime& runtime, const jsi::Function& callback) { struct Host::Impl { Impl(std::vector bytes, Options chosen) : bytecode(std::move(bytes)), options(std::move(chosen)) { - started = std::chrono::steady_clock::now(); + startedNs = awakeNanoseconds(); worker = std::thread([this] { run(); }); invoke([](jsi::Runtime&) {}); } @@ -126,7 +201,8 @@ struct Host::Impl { std::vector bytecode; Options options; - std::chrono::steady_clock::time_point started; + /** performance.now()'s zero, on the awake clock. */ + std::int64_t startedNs = 0; std::thread worker; std::mutex mutex; std::condition_variable wake; @@ -207,9 +283,7 @@ struct Host::Impl { double clock() const { if (!options.realClock) return now_ms; - return std::chrono::duration( - std::chrono::steady_clock::now() - started) - .count(); + return static_cast(awakeNanoseconds() - startedNs) / 1e6; } void set_step(std::string step) { @@ -378,6 +452,7 @@ struct Host::Impl { })); } js.global().setProperty(js, "console", std::move(console)); + install_from_base64(js); if (options.install) options.install(*runtime); } diff --git a/src/js/net/base64.cpp b/src/js/net/base64.cpp index dc5ce0b..8923c36 100644 --- a/src/js/net/base64.cpp +++ b/src/js/net/base64.cpp @@ -1,6 +1,6 @@ #include "base64.h" -#include +#include namespace bureau::net { namespace { @@ -8,6 +8,21 @@ namespace { constexpr std::string_view kAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +/** A letter's six bits, or -1 for a character outside the alphabet. */ +int sextet(char letter, bool url) { + if (letter >= 'A' && letter <= 'Z') return letter - 'A'; + if (letter >= 'a' && letter <= 'z') return letter - 'a' + 26; + if (letter >= '0' && letter <= '9') return letter - '0' + 52; + if (letter == (url ? '-' : '+')) return 62; + if (letter == (url ? '_' : '/')) return 63; + return -1; +} + +bool isAsciiWhitespace(char letter) { + return letter == ' ' || letter == '\t' || letter == '\n' || letter == '\f' || + letter == '\r'; +} + } // namespace std::string base64(const std::uint8_t* bytes, std::size_t length) { @@ -27,4 +42,70 @@ std::string base64(const std::uint8_t* bytes, std::size_t length) { return encoded; } +Decoded fromBase64(std::string_view text, bool url, LastChunk last) { + Decoded decoded; + decoded.bytes.reserve(text.size() / 4 * 3 + 2); + std::uint32_t chunk = 0; + int letters = 0; + std::size_t index = 0; + const auto skipWhitespace = [&] { + while (index < text.size() && isAsciiWhitespace(text[index])) ++index; + }; + const auto failed = [&](const char* why) { + decoded.bytes.clear(); + decoded.error = why; + return std::move(decoded); + }; + // A chunk of two or three letters: one or two bytes, and the bits left + // over, which only a strict reading refuses. + const auto shortChunk = [&] { + const int bytes = letters - 1; + const std::uint32_t whole = chunk << (6 * (4 - letters)); + const std::uint32_t spare = bytes == 1 ? whole & 0xFFFF : whole & 0xFF; + if (last == LastChunk::Strict && spare != 0) + return failed("base64 with bits after its last byte"); + decoded.bytes.push_back(static_cast(whole >> 16)); + if (bytes == 2) + decoded.bytes.push_back(static_cast(whole >> 8)); + return std::move(decoded); + }; + for (;;) { + skipWhitespace(); + if (index == text.size()) { + if (letters == 0 || last == LastChunk::StopBeforePartial) + return decoded; + if (last == LastChunk::Strict) + return failed("base64 without its padding"); + if (letters == 1) return failed("base64 ending in a lone letter"); + return shortChunk(); + } + const char letter = text[index++]; + if (letter == '=') { + if (letters < 2) return failed("base64 padding too early"); + skipWhitespace(); + if (letters == 2) { + if (index == text.size()) { + if (last == LastChunk::StopBeforePartial) return decoded; + return failed("base64 with half its padding"); + } + if (text[index] == '=') { + ++index; + skipWhitespace(); + } + } + if (index < text.size()) return failed("base64 with text after padding"); + return shortChunk(); + } + const int value = sextet(letter, url); + if (value < 0) return failed("a character outside base64"); + chunk = (chunk << 6) | static_cast(value); + if (++letters < 4) continue; + decoded.bytes.push_back(static_cast(chunk >> 16)); + decoded.bytes.push_back(static_cast(chunk >> 8)); + decoded.bytes.push_back(static_cast(chunk)); + chunk = 0; + letters = 0; + } +} + } // namespace bureau::net diff --git a/src/js/net/base64.h b/src/js/net/base64.h index 6098959..01ace1f 100644 --- a/src/js/net/base64.h +++ b/src/js/net/base64.h @@ -1,19 +1,36 @@ -// Base64, for the two places bytes have to travel inside text. +// Base64, for the places bytes have to travel inside text. // -// The handshake's accept key is one; the terrain field is the other, and it is +// The handshake's accept key is one; the terrain field is another, and it is // the reason this is not a detail of the handshake any more — 296 KB of // lattice inside the JSON the terrain route answers with is not something to // spell out as an array of numbers (`bytesToBase64` in `terrain_field.ts` -// says the same on the other side). +// says the same on the other side). The third is `Uint8Array.fromBase64`, +// which Hermes lacks and a loop in its interpreter runs fifty times slower. #pragma once #include #include #include +#include +#include namespace bureau::net { /** Standard base64 with padding: the alphabet `atob` reads. */ std::string base64(const std::uint8_t* bytes, std::size_t length); +/** What `Uint8Array.fromBase64` does with a last chunk shorter than four + * letters (its `lastChunkHandling` option). */ +enum class LastChunk { Loose, Strict, StopBeforePartial }; + +struct Decoded { + std::vector bytes; + /** Why the text is not base64; empty when it is. */ + std::string error; +}; + +/** ECMAScript's FromBase64: ASCII whitespace skipped anywhere, `url` for the + * `-_` alphabet in place of `+/`. */ +Decoded fromBase64(std::string_view text, bool url, LastChunk last); + } // namespace bureau::net diff --git a/src/js/ui.cpp b/src/js/ui.cpp index 9c836da..165adb2 100644 --- a/src/js/ui.cpp +++ b/src/js/ui.cpp @@ -2,12 +2,15 @@ #include +#include #include #include +#include #include #include #include #include +#include #include #include @@ -98,6 +101,51 @@ struct Ui::Impl { /** The UI's thread's: animation time, when something holds it still. */ std::optional frozenClock; + /** The client's own files (`assetText`, `assetBytes`), read on a thread of + * their own and answered on the UI's: a disk that takes seconds over one + * file holds that thread, not the interface. */ + std::mutex readsMutex; + std::condition_variable readsQueued; + std::deque> reads; + bool readsStopped = false; + std::thread reader; + /** The callbacks those reads answer, for the runtime that asked: the UI's + * thread's, and gone with that runtime. */ + std::shared_ptr pendingReads; + + void readLater(std::function read) { + std::lock_guard lock(readsMutex); + if (readsStopped) return; + reads.push_back(std::move(read)); + readsQueued.notify_one(); + } + + void readInTurn() { + for (;;) { + std::function read; + { + std::unique_lock lock(readsMutex); + readsQueued.wait(lock, + [this] { return readsStopped || !reads.empty(); }); + if (readsStopped) return; + read = std::move(reads.front()); + reads.pop_front(); + } + read(); + } + } + + /** Waits for the file being read, if any; the rest are never answered. */ + void stopReading() { + { + std::lock_guard lock(readsMutex); + readsStopped = true; + reads.clear(); + readsQueued.notify_one(); + } + if (reader.joinable()) reader.join(); + } + /** What the UI's thread is in the middle of, outermost first: it writes, * any thread reads. */ mutable std::mutex doingMutex; @@ -133,7 +181,7 @@ struct Ui::Impl { /** After every turn: the view's new frame. */ void publish(double nowMs) { const bool changed = view->frame(frozenClock.value_or(nowMs)); - std::string textInput = view->textInput().dump(); + std::string textInput = bridge::jsonText(view->textInput()); const bool busy = changed ? view->windowBusy() : true; std::lock_guard lock(mutex); mailbox.textInput = std::move(textInput); @@ -215,22 +263,52 @@ struct Ui::Impl { array.setValueAtIndex(runtime, 2, jsi::Value(scale)); return jsi::Value(runtime, array); }); - define(js, native, "assetText", - [this](jsi::Runtime& runtime, const jsi::Value&, - const jsi::Value* args, size_t count) { - const auto bytes = readAsset(stringArg(runtime, args, count, 0)); - return bytes ? jsString(runtime, *bytes) : jsi::Value::null(); - }); - define(js, native, "assetBytes", - [this](jsi::Runtime& runtime, const jsi::Value&, - const jsi::Value* args, size_t count) { - auto bytes = readAsset(stringArg(runtime, args, count, 0)); - if (!bytes) return jsi::Value::null(); - return jsi::Value( - runtime, - jsi::ArrayBuffer(runtime, - std::make_shared(std::move(*bytes)))); - }); + pendingReads = std::make_shared(); + defineRead(js, native, "assetText", + [](jsi::Runtime& runtime, std::string bytes) { + return jsString(runtime, bytes); + }); + defineRead( + js, native, "assetBytes", [](jsi::Runtime& runtime, std::string bytes) { + return jsi::Value( + runtime, jsi::ArrayBuffer( + runtime, std::make_shared(std::move(bytes)))); + }); + } + + /** `name(path, done)`: reads the file off the UI's thread, then calls + * `done` on it with the file as `valueOf` makes it, or null when there is + * none. */ + void defineRead(jsi::Runtime& js, jsi::Object& native, const char* name, + jsi::Value (*valueOf)(jsi::Runtime&, std::string)) { + define( + js, native, name, + [this, valueOf](jsi::Runtime& runtime, const jsi::Value&, + const jsi::Value* args, size_t count) { + const bool answerable = count >= 2 && args[1].isObject() && + args[1].asObject(runtime).isFunction(runtime); + if (!answerable) return jsi::Value::undefined(); + const int id = + pendingReads->keep(args[1].asObject(runtime).asFunction(runtime)); + std::weak_ptr asker = pendingReads; + readLater([this, path = stringArg(runtime, args, count, 0), id, asker, + valueOf] { + auto bytes = + options.readAsset ? options.readAsset(path) : std::nullopt; + post( + [asker, id, valueOf, + bytes = std::move(bytes)](jsi::Runtime& js) mutable { + const auto state = asker.lock(); + if (!state) return; + auto done = state->take(id); + if (!done) return; + done->call(js, bytes ? valueOf(js, std::move(*bytes)) + : jsi::Value::null()); + }, + "asset"); + }); + return jsi::Value::undefined(); + }); } }; @@ -258,6 +336,7 @@ Ui::Ui(Options options) : impl_(std::make_unique()) { impl->view->setSurfaceListener(impl->options.surfacePointer); impl->view->setClipboard(impl->options.readClipboard, impl->options.writeClipboard); + impl->reader = std::thread([impl] { impl->readInTurn(); }); } Ui::~Ui() { stop(); } @@ -279,6 +358,7 @@ void Ui::start() { options.install = [impl](jsi::Runtime& js) { impl->installNative(js); }; options.uninstall = [impl](jsi::Runtime& js) { impl->view->setDispatch(nullptr); + impl->pendingReads.reset(); if (impl->options.uninstall) impl->options.uninstall(js); }; options.afterTurn = [impl](jsi::Runtime& js, double nowMs) { @@ -303,6 +383,10 @@ void Ui::stop() { if (impl->stopped) return; impl->stopped = true; impl->held.clear(); + } + impl->stopReading(); + { + std::lock_guard lock(impl->mutex); if (!impl->host) return; } // Queued tasks read host(), so they run while it still holds the engine. diff --git a/src/js/view_bridge.cpp b/src/js/view_bridge.cpp index ae3015b..9f0efe9 100644 --- a/src/js/view_bridge.cpp +++ b/src/js/view_bridge.cpp @@ -50,6 +50,10 @@ Json jsonOf(jsi::Runtime& runtime, const jsi::Value& value) { return Json::parse(encoded.asString(runtime).utf8(runtime), nullptr, false); } +std::string jsonText(const Json& value) { + return value.dump(-1, ' ', false, Json::error_handler_t::replace); +} + void define(jsi::Runtime& runtime, jsi::Object& object, const char* name, jsi::HostFunctionType body) { object.setProperty(runtime, name, @@ -96,7 +100,7 @@ void installViewBridge(jsi::Runtime& runtime, jsi::Object& native, View& view) { dispatch.asObject(runtime).asFunction(runtime).call( runtime, jsi::Value(node), jsi::String::createFromUtf8(runtime, std::string(handler)), - jsi::String::createFromUtf8(runtime, args.dump())); + jsi::String::createFromUtf8(runtime, bridge::jsonText(args))); return bridge::jsonOf(runtime, answer); }); diff --git a/src/text/paragraph.cpp b/src/text/paragraph.cpp index 086b7c5..b44bb1e 100644 --- a/src/text/paragraph.cpp +++ b/src/text/paragraph.cpp @@ -205,20 +205,45 @@ Font* Typesetter::primary(const style::TypeStyle& type, float scale) { Typesetter::Chain Typesetter::chain(const style::TypeStyle& type, float scale, const std::string& language) { - Chain chain; + Chain chain(fonts_); if (Font* first = primary(type, scale)) chain.fonts.push_back(first); for (const auto& family : tokens_.fallbackFamilies(language)) { const auto* face = tokens_.face(family, type.weight); if (face == nullptr || face->source.empty()) continue; - Font* font = - fonts_.font(face->source, type.size * scale * face->sizeAdjust); - const bool known = std::find(chain.fonts.begin(), chain.fonts.end(), - font) != chain.fonts.end(); - if (font != nullptr && !known) chain.fonts.push_back(font); + chain.fallbacks.emplace_back(face->source, + type.size * scale * face->sizeAdjust); } return chain; } +Font* Typesetter::Chain::openNext() { + while (opened < fallbacks.size()) { + const auto& [source, size] = fallbacks[opened++]; + Font* font = library.font(source, size); + const bool known = + std::find(fonts.begin(), fonts.end(), font) != fonts.end(); + if (font == nullptr || known) continue; + fonts.push_back(font); + return font; + } + return nullptr; +} + +Font* Typesetter::Chain::first() { + if (fonts.empty()) openNext(); + return fonts.empty() ? nullptr : fonts.front(); +} + +Font* Typesetter::Chain::fontFor(char32_t code) { + for (Font* font : fonts) { + if (font->glyphFor(code) != 0) return font; + } + while (Font* font = openNext()) { + if (font->glyphFor(code) != 0) return font; + } + return first(); +} + Paragraph Typesetter::fit(const std::vector& spans, const ParagraphOptions& options) { ParagraphOptions sized = options; @@ -333,15 +358,11 @@ Paragraph Typesetter::set(const std::vector& spans, clusters.push_back(atom); continue; } - const Chain fonts = chain(*span.type, span.scale, options.language); - if (fonts.fonts.empty()) continue; + Chain fonts = chain(*span.type, span.scale, options.language); + if (fonts.first() == nullptr) continue; const auto fontAt = [&](char32_t code) { const bool blank = code == ' ' || code == '\n'; - if (blank) return fonts.fonts.front(); - for (Font* font : fonts.fonts) { - if (font->glyphFor(code) != 0) return font; - } - return fonts.fonts.front(); + return blank ? fonts.first() : fonts.fontFor(code); }; const float letterSpacing = span.type->letterSpacing * span.scale; const float wordSpacing = span.type->wordSpacing * span.scale; diff --git a/src/text/paragraph.h b/src/text/paragraph.h index 0e36ca7..ceb37f5 100644 --- a/src/text/paragraph.h +++ b/src/text/paragraph.h @@ -143,8 +143,28 @@ class Typesetter { private: Paragraph fit(const std::vector& spans, const ParagraphOptions& options); + /** A run's faces in the order its characters try them: the style's own, + * then the language's fallbacks, each opened only when a character the + * faces before it lack needs it. Opening every face up front read the + * shipped CJK faces, ten megabytes each, before the first Latin label. */ struct Chain { + explicit Chain(FontLibrary& library) : library(library) {} + FontLibrary& library; std::vector fonts; + /** Every fallback's file and size, in order; those before `opened` have + * been opened. */ + std::vector> fallbacks; + size_t opened = 0; + + /** The first face, which spaces and characters no face has take. */ + Font* first(); + /** The first face with a glyph for `code`, else `first()`. */ + Font* fontFor(char32_t code); + + private: + /** The next fallback that opens and is not in `fonts` yet, added to it; + * null when none is left. */ + Font* openNext(); }; Chain chain(const style::TypeStyle& type, float scale, const std::string& language); diff --git a/src/view/view_input.cpp b/src/view/view_input.cpp index 067429b..ab86669 100644 --- a/src/view/view_input.cpp +++ b/src/view/view_input.cpp @@ -1046,9 +1046,11 @@ void View::typed(const std::string& entered) { selectAll_ = false; value.insert(caret, accepted); caret += accepted.size(); + // The length counts UTF-16 units, as the client's checks do; counting bytes + // cut a letter such as é in half, and JSON refused the field's value. const float maxLength = number(*found, "maxLength", -1); - if (maxLength >= 0 && value.size() > static_cast(maxLength)) { - value.resize(static_cast(maxLength)); + if (maxLength >= 0) { + value.resize(byteOffset(value, static_cast(maxLength))); caret = std::min(caret, value.size()); } live.caret = caret; diff --git a/tests/js_host_test.cpp b/tests/js_host_test.cpp index fe093c2..766e28d 100644 --- a/tests/js_host_test.cpp +++ b/tests/js_host_test.cpp @@ -3,6 +3,7 @@ #include +#include "../src/js/awake_clock.h" #include "../src/js/host.h" #include "../src/tree/tree.h" @@ -139,6 +140,19 @@ TEST_CASE("a real clock stamps frames with performance.now()'s time") { CHECK(host.take_error().empty()); } +TEST_CASE("the awake clock keeps time with the steady clock while awake") { + const auto steadyStarted = std::chrono::steady_clock::now(); + const std::int64_t awakeStarted = bureau::js::awakeNanoseconds(); + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + const double awakeMs = + static_cast(bureau::js::awakeNanoseconds() - awakeStarted) / 1e6; + const double steadyMs = std::chrono::duration( + std::chrono::steady_clock::now() - steadyStarted) + .count(); + CHECK(awakeMs >= 50); + CHECK(awakeMs == doctest::Approx(steadyMs).epsilon(0.1)); +} + TEST_CASE("Unicode case mapping normalization and the committed collation " "lists and formatting fixtures") { bureau::js::Host host(read_bytes(BUREAU_UNICODE_BUNDLE)); @@ -334,6 +348,94 @@ TEST_CASE("a profile stopped into a missing folder answers why") { CHECK_FALSE(host.stop_profile("/no-such-folder/profile.json").empty()); } +namespace { + +/** What `Uint8Array.fromBase64(text, options)` answers in the host: its + * bytes, or the name of the error it throws. */ +struct FromBase64 { + std::vector bytes; + std::string thrown; +}; + +FromBase64 fromBase64(const std::string& text, + const char* lastChunkHandling = nullptr) { + bureau::js::Host host(read_bytes(BUREAU_CLOSURE_BUNDLE)); + FromBase64 answer; + host.invoke([&](facebook::jsi::Runtime& js) { + auto read = js.global() + .getPropertyAsObject(js, "Uint8Array") + .getPropertyAsFunction(js, "fromBase64"); + facebook::jsi::Object options(js); + if (lastChunkHandling != nullptr) { + options.setProperty( + js, "lastChunkHandling", + facebook::jsi::String::createFromAscii(js, lastChunkHandling)); + } + try { + auto array = + read.call(js, facebook::jsi::String::createFromUtf8(js, text), + std::move(options)) + .getObject(js); + const int length = + static_cast(array.getProperty(js, "length").asNumber()); + for (int index = 0; index < length; ++index) { + answer.bytes.push_back(static_cast( + array.getProperty(js, std::to_string(index).c_str()).asNumber())); + } + } catch (const facebook::jsi::JSError& error) { + answer.thrown = error.value() + .getObject(js) + .getProperty(js, "name") + .getString(js) + .utf8(js); + } + }); + return answer; +} + +} // namespace + +TEST_CASE("Uint8Array.fromBase64 reads padded base64 into its bytes") { + CHECK(fromBase64("AQID/f4=").bytes == std::vector{1, 2, 3, 253, 254}); +} + +TEST_CASE("Uint8Array.fromBase64 reads a last byte padded twice") { + CHECK(fromBase64("AQID/Q==").bytes == std::vector{1, 2, 3, 253}); +} + +TEST_CASE("Uint8Array.fromBase64 skips ASCII whitespace") { + CHECK(fromBase64(" AQ\nID\t").bytes == std::vector{1, 2, 3}); +} + +TEST_CASE("Uint8Array.fromBase64 reads a loose last chunk without padding") { + CHECK(fromBase64("AQID/Q").bytes == std::vector{1, 2, 3, 253}); +} + +TEST_CASE("Uint8Array.fromBase64 refuses a character outside base64") { + CHECK(fromBase64("AQ-D").thrown == "SyntaxError"); +} + +TEST_CASE("Uint8Array.fromBase64 refuses half a padding") { + CHECK(fromBase64("AQID/Q=").thrown == "SyntaxError"); +} + +TEST_CASE("a strict Uint8Array.fromBase64 refuses bits after the last byte") { + CHECK(fromBase64("AQID/R==", "strict").thrown == "SyntaxError"); +} + +TEST_CASE("a strict Uint8Array.fromBase64 refuses a chunk without padding") { + CHECK(fromBase64("AQID/Q", "strict").thrown == "SyntaxError"); +} + +TEST_CASE("Uint8Array.fromBase64 stops before a partial chunk when asked") { + CHECK(fromBase64("AQID/Q", "stop-before-partial").bytes == + std::vector{1, 2, 3}); +} + +TEST_CASE("Uint8Array.fromBase64 refuses an unknown last chunk handling") { + CHECK(fromBase64("AQID", "lenient").thrown == "TypeError"); +} + #if BUREAU_ENABLE_DEBUGGER TEST_CASE("a busy VM coalesces missed display refreshes") { bureau::js::Host::Options options; diff --git a/tests/paragraph_test.cpp b/tests/paragraph_test.cpp index afaf5ae..3ac6856 100644 --- a/tests/paragraph_test.cpp +++ b/tests/paragraph_test.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include "goldens.h" @@ -144,6 +145,27 @@ TEST_CASE("fallback glyphs use their own face adjustment") { CHECK(english.lines[0].glyphs[1].font->size() == doctest::Approx(16.92)); } +TEST_CASE("text its own face covers reads no other face") { + std::vector read; + bureau::style::Tokens tokens; + std::ifstream file(BUREAU_TOKENS_JSON); + REQUIRE(tokens.load(std::string{std::istreambuf_iterator{file}, {}})); + bureau::text::FontLibrary fonts([&](const std::string& path) { + read.push_back(path); + return readPublic(path); + }); + bureau::text::Typesetter typesetter(fonts, tokens); + bureau::text::Span span; + span.text = "Pressed 3 times"; + span.type = tokens.type("text", "en"); + bureau::text::ParagraphOptions options; + options.strut = span.type; + + typesetter.set({span}, options); + + CHECK(read == std::vector{"/fonts/Jersey25-Regular.ttf"}); +} + TEST_CASE("a centered line offsets its glyphs once, by the line") { Setting setting; bureau::text::ParagraphOptions options; diff --git a/tests/quads_test.cpp b/tests/quads_test.cpp index fbd46bc..c0919fa 100644 --- a/tests/quads_test.cpp +++ b/tests/quads_test.cpp @@ -6,6 +6,7 @@ using bureau::Clip; using bureau::DisplayList; using bureau::Quad; using bureau::backends::batchesOf; +using bureau::backends::vertexBufferBytes; namespace { @@ -62,7 +63,7 @@ TEST_CASE("a new page starts a run") { TEST_CASE("a new clip starts a run with its scissor") { const auto batches = batchesOf( - listOf({fill(0, 0, 1, 1, 0, 0), fill(1, 1, 2, 2, 0, 1)}), 100, 50); + listOf({fill(0, 0, 1, 1, 0, 0), fill(11, 11, 12, 12, 0, 1)}), 100, 50); REQUIRE(batches.runs.size() == 2); CHECK(batches.runs[1].scissor.x == 10); CHECK(batches.runs[1].scissor.y == 10); @@ -71,7 +72,7 @@ TEST_CASE("a new clip starts a run with its scissor") { } TEST_CASE("a list drawn into a smaller target scales its scissors inside it") { - const auto batches = batchesOf(listOf({fill(0, 0, 1, 1, 0, 1)}), 50, 25); + const auto batches = batchesOf(listOf({fill(11, 11, 12, 12, 0, 1)}), 50, 25); REQUIRE(batches.runs.size() == 1); CHECK(batches.runs[0].scissor.x == 5); CHECK(batches.runs[0].scissor.y == 5); @@ -80,7 +81,7 @@ TEST_CASE("a list drawn into a smaller target scales its scissors inside it") { } TEST_CASE("a clip past the list stays inside the target") { - auto list = listOf({fill(0, 0, 1, 1, 0, 1)}); + auto list = listOf({fill(95, 45, 96, 46, 0, 1)}); list.clips[1] = Clip{90, 40, 50, 50}; const auto batches = batchesOf(list, 100, 50); CHECK(batches.runs[0].scissor.width == 10); @@ -88,11 +89,13 @@ TEST_CASE("a clip past the list stays inside the target") { } TEST_CASE("a quad turns about its origin") { - Quad quad = fill(0, 0, 2, 0, 0, 0); + Quad quad = fill(10, 10, 12, 11, 0, 0); quad.angle = 3.14159265f; + quad.originX = 10; + quad.originY = 10; const auto batches = batchesOf(listOf({quad}), 100, 50); - CHECK(batches.vertices[1].x == doctest::Approx(-2.0f)); - CHECK(batches.vertices[1].y == doctest::Approx(0.0f).epsilon(0.001)); + CHECK(batches.vertices[1].x == doctest::Approx(8.0f)); + CHECK(batches.vertices[1].y == doctest::Approx(10.0f)); } TEST_CASE("nothing to draw is no run") { @@ -100,3 +103,63 @@ TEST_CASE("nothing to draw is no run") { CHECK(batches.vertices.empty()); CHECK(batches.runs.empty()); } + +TEST_CASE("a quad outside its clip is not drawn") { + const auto batches = batchesOf(listOf({fill(40, 40, 45, 45, 0, 1)}), 100, 50); + CHECK(batches.vertices.empty()); + CHECK(batches.runs.empty()); +} + +TEST_CASE("a quad below the window is not drawn") { + const auto batches = batchesOf(listOf({fill(0, 60, 10, 70, 0, 0)}), 100, 50); + CHECK(batches.vertices.empty()); +} + +TEST_CASE("a quad reaching into its clip is drawn whole") { + const auto batches = batchesOf(listOf({fill(5, 5, 11, 11, 0, 1)}), 100, 50); + REQUIRE(batches.vertices.size() == 6); + CHECK(batches.vertices[0].x == 5); +} + +TEST_CASE("a quad turned into its clip is drawn") { + Quad quad = fill(0, 0, 4, 4, 0, 1); + quad.angle = 3.14159265f; + quad.originX = 14; + quad.originY = 14; + const auto batches = batchesOf(listOf({quad}), 100, 50); + CHECK(batches.vertices.size() == 6); +} + +TEST_CASE("an empty clip draws nothing") { + auto list = listOf({fill(10, 10, 20, 20, 0, 1)}); + list.clips[1] = Clip{10, 10, 0, 20}; + const auto batches = batchesOf(list, 100, 50); + CHECK(batches.vertices.empty()); +} + +TEST_CASE("a list with a run culled away starts the next run afresh") { + const auto batches = batchesOf(listOf({fill(0, 0, 1, 1, 0, 0), + fill(40, 40, 45, 45, 0, 1), + fill(2, 2, 3, 3, 0, 0)}), + 100, 50); + REQUIRE(batches.runs.size() == 1); + CHECK(batches.runs[0].vertexCount == 12); +} + +TEST_CASE("a frame draws no more than the most vertices a buffer holds") { + const auto quads = std::vector(bureau::backends::kMaxVertices / 6 + 10, + fill(0, 0, 1, 1, 0, 0)); + const auto batches = batchesOf(listOf(quads), 100, 50); + CHECK(batches.vertices.size() == bureau::backends::kMaxVertices / 6 * 6); + CHECK(batches.runs[0].vertexCount == batches.vertices.size()); +} + +TEST_CASE("a vertex buffer grows to twice what a frame needs") { + CHECK(vertexBufferBytes(1000, 800) == 2000); +} + +TEST_CASE("a vertex buffer never grows past the most a frame draws") { + const std::uint64_t most = + bureau::backends::kMaxVertices * sizeof(bureau::backends::Vertex); + CHECK(vertexBufferBytes(most, most - 1) == most); +} diff --git a/tests/ui_test.cpp b/tests/ui_test.cpp index e1f5305..5cd5a01 100644 --- a/tests/ui_test.cpp +++ b/tests/ui_test.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -35,6 +36,9 @@ std::optional readFile(const std::string& path) { return std::string(std::istreambuf_iterator{file}, {}); } +/** A file whose read waits for the test (Game::slowDisk). */ +const std::string kSlowFile = "/keyboards/readings.json"; + /** A little game: the hello bundle, with its one function of its own. */ struct Game { std::atomic pressed{0}; @@ -43,6 +47,9 @@ struct Game { std::string doingInPress; std::mutex readsMutex; std::map doingInRead; + /** kSlowFile's read lasts until this is set: a disk taking its time. */ + std::promise slowDisk; + std::shared_future slowDiskDone = slowDisk.get_future().share(); std::shared_ptr list; std::unique_ptr ui; @@ -59,6 +66,8 @@ struct Game { std::lock_guard lock(readsMutex); doingInRead[path] = ui->doing(); } + // Bounded, so a read on the UI's thread fails the test, not hangs it. + if (path == kSlowFile) slowDiskDone.wait_for(std::chrono::seconds(5)); return readFile(std::string(BUREAU_ASSETS_DIR) + path); }; options.width = 320; @@ -158,17 +167,71 @@ TEST_CASE("a handler at work is named with the node it is on") { game.ui->stop(); } -TEST_CASE("a file being read is named") { +TEST_CASE("a face being read is named") { + Game game; + game.until([&] { return game.drew(); }); + std::lock_guard lock(game.readsMutex); + CHECK(game.doingInRead["/fonts/Jersey25-Regular.ttf"] == + "read /fonts/Jersey25-Regular.ttf"); + game.ui->stop(); +} + +TEST_CASE("the interface answers while a file TypeScript asked for is read") { Game game; game.until([&] { return game.drew(); }); - game.ui->invoke([](jsi::Runtime& js) { + std::mutex answerMutex; + std::optional answer; + game.ui->invoke([&](jsi::Runtime& js) { + const auto done = jsi::Function::createFromHostFunction( + js, jsi::PropNameID::forAscii(js, "done"), 1, + [&](jsi::Runtime& runtime, const jsi::Value&, const jsi::Value* args, + size_t) { + std::lock_guard lock(answerMutex); + answer = args[0].asString(runtime).utf8(runtime); + return jsi::Value::undefined(); + }); js.global() .getPropertyAsObject(js, "__native") .getPropertyAsFunction(js, "assetText") - .call(js, "/no-such-file.txt"); + .call(js, kSlowFile, done); }); - std::lock_guard lock(game.readsMutex); - CHECK(game.doingInRead["/no-such-file.txt"] == "read /no-such-file.txt"); + + bool answeredWhileReading = true; + game.ui->invoke([&](jsi::Runtime&) { + std::lock_guard lock(answerMutex); + answeredWhileReading = answer.has_value(); + }); + game.slowDisk.set_value(); + game.until([&] { + std::lock_guard lock(answerMutex); + return answer.has_value(); + }); + + CHECK_FALSE(answeredWhileReading); + CHECK(answer->starts_with("{")); + game.ui->stop(); +} + +TEST_CASE("a file TypeScript asks for that is not there answers null") { + Game game; + game.until([&] { return game.drew(); }); + std::atomic answeredNull{false}; + game.ui->invoke([&](jsi::Runtime& js) { + const auto done = jsi::Function::createFromHostFunction( + js, jsi::PropNameID::forAscii(js, "done"), 1, + [&](jsi::Runtime&, const jsi::Value&, const jsi::Value* args, size_t) { + answeredNull = args[0].isNull(); + return jsi::Value::undefined(); + }); + js.global() + .getPropertyAsObject(js, "__native") + .getPropertyAsFunction(js, "assetBytes") + .call(js, "/no-such-file.bin", done); + }); + + game.until([&] { return answeredNull.load(); }); + + CHECK(answeredNull); game.ui->stop(); } @@ -265,6 +328,17 @@ TEST_CASE("a task posted before the start runs after it, and one after the stop CHECK(ran.load() == 1); } +TEST_CASE("JSON for JavaScript reads a letter cut in half as a replacement character") { + const nlohmann::json cut = nlohmann::json::array({"Sevill\xC3"}); + CHECK(bureau::bridge::jsonText(cut) == "[\"Sevill\xEF\xBF\xBD\"]"); +} + +TEST_CASE("JSON for JavaScript reads a Windows code page letter as a replacement character") { + // "Jo\xE3o" is João in Windows-1252. + const nlohmann::json ansi = {{"name", "Jo\xE3o"}}; + CHECK(bureau::bridge::jsonText(ansi) == "{\"name\":\"Jo\xEF\xBF\xBDo\"}"); +} + TEST_CASE("a mouse move with none waiting asks for a task") { bureau::js::PointerMoves moves; CHECK(moves.hold(moveTo(10))); diff --git a/tests/view_test.cpp b/tests/view_test.cpp index e78908c..a01bf93 100644 --- a/tests/view_test.cpp +++ b/tests/view_test.cpp @@ -1526,6 +1526,30 @@ TEST_CASE("native field length counts UTF-16 units without cutting a character") CHECK(fixture.handled("onChange").back().args == Json::array({"東京"})); } +TEST_CASE("typed text counts a field's length in letters, not bytes") { + Fixture fixture; + fixture.commit(Stream().create(1, "bureau-field", + {{"value", ""}, {"onChange", true}, + {"maxLength", 3}}).append(0, 1)); + fixture.view.focus(1, true); + fixture.view.typed("ñañ"); + CHECK(fixture.handled("onChange").back().args == Json::array({"ñañ"})); +} + +TEST_CASE("typed text past a field's length keeps the last letter whole") { + Fixture fixture; + fixture.commit(Stream().create(1, "bureau-field", + {{"value", "Sevill"}, {"onChange", true}, + {"maxLength", 7}}).append(0, 1)); + fixture.view.focus(1, true); + fixture.view.typed("éa"); + fixture.commit(Stream().props(1, {{"value", "Sevillé"}})); + CHECK(fixture.handled("onChange").back().args.dump() == R"(["Sevillé"])"); + CHECK(fixture.view.textInput()["selectionEnd"] == 7); + CHECK(fixture.view.textInput().dump().find(R"("value":"Sevillé")") != + std::string::npos); +} + TEST_CASE("native text acknowledges an edit only after React commits its value") { Fixture fixture; fixture.commit(Stream().create(1, "bureau-field",