// SPDX-License-Identifier: GPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® /* ImsdMessages.Ui:Canvas — the window and what every screen draws with: the font, the word wrapper over it, and four compositing layers. Within one fused dispatch all quads composite before all text, so the scrolling content (clipped to its area), the chrome above it and any sheet above that are separate dispatches in that order; the background is a quad of its own because the swapchain is never cleared. */ module; #include "vulkan/vulkan.h" export module ImsdMessages.Ui:Canvas; import std; import Crafter.Graphics; import Crafter.Event; import ImsdMessages; export namespace ImsdMessages::Ui { using Color = std::array; struct Theme { Color bg = { 0.96f, 0.96f, 0.97f, 1.0f }; Color surface = { 1.0f, 1.0f, 1.0f, 1.0f }; Color text = { 0.11f, 0.11f, 0.12f, 1.0f }; Color muted = { 0.43f, 0.43f, 0.45f, 1.0f }; Color accent = { 0.18f, 0.44f, 0.93f, 1.0f }; Color onAccent = { 1.0f, 1.0f, 1.0f, 1.0f }; Color bubbleIn = { 0.91f, 0.91f, 0.92f, 1.0f }; Color bubbleOut = { 0.18f, 0.44f, 0.93f, 1.0f }; Color banner = { 1.0f, 0.95f, 0.80f, 1.0f }; Color bannerText = { 0.40f, 0.30f, 0.01f, 1.0f }; Color divider = { 0.88f, 0.88f, 0.89f, 1.0f }; Color danger = { 0.80f, 0.16f, 0.16f, 1.0f }; Color scrim = { 0.0f, 0.0f, 0.0f, 0.35f }; static Theme Light() { return Theme{}; } static Theme Dark() { Theme t; t.bg = { 0.07f, 0.07f, 0.08f, 1.0f }; t.surface = { 0.12f, 0.12f, 0.13f, 1.0f }; t.text = { 0.93f, 0.93f, 0.94f, 1.0f }; t.muted = { 0.62f, 0.62f, 0.65f, 1.0f }; t.bubbleIn = { 0.18f, 0.18f, 0.20f, 1.0f }; t.banner = { 0.30f, 0.26f, 0.10f, 1.0f }; t.bannerText = { 0.98f, 0.88f, 0.55f, 1.0f }; t.divider = { 0.20f, 0.20f, 0.22f, 1.0f }; t.danger = { 0.90f, 0.30f, 0.30f, 1.0f }; t.scrim = { 0.0f, 0.0f, 0.0f, 0.55f }; return t; } // The system's accent colour, with text on it dark or light as its // brightness asks. void Accent(std::array rgb) { accent = { rgb[0], rgb[1], rgb[2], 1.0f }; bubbleOut = accent; const float luminance = 0.2126f * rgb[0] + 0.7152f * rgb[1] + 0.0722f * rgb[2]; onAccent = luminance > 0.6f ? Color{ 0.08f, 0.08f, 0.09f, 1.0f } : Color{ 1.0f, 1.0f, 1.0f, 1.0f }; } }; // One compositing layer: its own item buffers — one set per frame in // flight, the frame's own filled — and one fused dispatch. A frame still // on the GPU reads its items as it runs, and the atlas evicts glyphs: a // later frame written into the same buffers could name cells that frame // drew other glyphs in (Crafter.Graphics a4be6f1, the library's usage // contract since). class Layer { public: void Create(Crafter::UIRenderer& ui, Crafter::FontAtlas& atlas, std::uint32_t quadCap, std::uint32_t circleCap, std::uint32_t glyphCap) { constexpr VkBufferUsageFlags usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; constexpr VkMemoryPropertyFlags memory = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; for (Items& f : frames) { f.quads.Create(usage, memory, quadCap); f.circles.Create(usage, memory, circleCap); f.glyphs.Create(usage, memory, glyphCap); f.quadSlot.emplace(ui.RegisterBuffer(f.quads)); f.circleSlot.emplace(ui.RegisterBuffer(f.circles)); f.glyphSlot.emplace(ui.RegisterBuffer(f.glyphs)); } this->quadCap = quadCap; this->circleCap = circleCap; this->glyphCap = glyphCap; buf.quadCount = &quadCount; buf.quadCap = quadCap; buf.glyphCount = &glyphCount; buf.glyphCap = glyphCap; buf.atlas = &atlas; buf.renderer = &ui; } // The frame's set of buffers: everything recorded until Submit goes // into it. void Begin(std::uint32_t frameIdx) { current = frameIdx; buf.quads = frames[current].quads.value; buf.glyphs = frames[current].glyphs.value; quadCount = 0; circleCount = 0; glyphCount = 0; clip = { 0.0f, 0.0f, 1e9f, 1e9f }; overflow = false; glyphsWaiting = 0; } void SetClip(Box b) { clip = { b.x, b.y, b.w, b.h }; } Crafter::UIBuffer& Buf() noexcept { return buf; } void Quad(Box b, Color c, float radius = 0, float outline = 0, Color outlineColor = {}) { if (quadCount >= quadCap) { overflow = true; return; } frames[current].quads.value[quadCount++] = Crafter::QuadItem{ b.x, b.y, b.w, b.h, c[0], c[1], c[2], c[3], radius, radius, radius, radius, outline, outlineColor[0], outlineColor[1], outlineColor[2] }; } void Circle(Point center, float radius, Color c) { if (circleCount >= circleCap) { overflow = true; return; } frames[current].circles.value[circleCount++] = Crafter::CircleItem{ center.x, center.y, radius, 0, c[0], c[1], c[2], c[3], 0, 0, 0, 0 }; } // One line; returns its advance. float Text(std::string_view text, float x, float baselineY, Crafter::Font& font, float px, Color c, Crafter::TextAlign align = Crafter::TextAlign::Left) { const std::uint32_t before = glyphCount; const float advance = Crafter::DrawText(buf, text, x, baselineY, font, px, c, align); if (glyphCount == before && !text.empty() && glyphCount >= glyphCap) overflow = true; // A glyph with ink that found no room in the atlas drew blank and // gets a cell when the next frame begins (the library's contract): // counted, so the frame is asked for. for (std::size_t i = 0; i < text.size();) { const std::uint32_t cp = DecodeUtf8(text, i); if (const Crafter::Glyph* g = buf.atlas->Lookup(font, cp); g && g->w > 0 && !g->Resident()) ++glyphsWaiting; } return advance; } void Submit(VkCommandBuffer cmd, Crafter::UIRenderer& ui) { Items& f = frames[current]; if (quadCount) f.quads.FlushDevice(cmd, VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); if (circleCount) f.circles.FlushDevice(cmd, VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); if (glyphCount) f.glyphs.FlushDevice(cmd, VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); if (!quadCount && !circleCount && !glyphCount) return; ui.DispatchFused(cmd, { *f.quadSlot, quadCount, clip }, { *f.circleSlot, circleCount, clip }, {}, { *f.glyphSlot, glyphCount, clip }); } bool Overflowed() const noexcept { return overflow; } std::uint32_t GlyphsWaiting() const noexcept { return glyphsWaiting; } private: struct Items { Crafter::GraphicsBuffer quads; Crafter::GraphicsBuffer circles; Crafter::GraphicsBuffer glyphs; std::optional quadSlot; std::optional circleSlot; std::optional glyphSlot; }; std::array frames; std::uint32_t current = 0; std::uint32_t quadCap = 0; std::uint32_t circleCap = 0; std::uint32_t glyphCap = 0; std::uint32_t quadCount = 0; std::uint32_t circleCount = 0; std::uint32_t glyphCount = 0; std::array clip = { 0.0f, 0.0f, 1e9f, 1e9f }; bool overflow = false; std::uint32_t glyphsWaiting = 0; // glyphs drawn blank this frame for want of an atlas cell Crafter::UIBuffer buf; }; class Canvas { // Declared first so they die last: a layer's buffer slots hand their // numbers back to the heap when they go, so the heap (and the // renderer, which holds slots of its own) must still exist then. The // atlas destroys its image and the heap, in sets mode, holds a view // of it, so the heap goes before the atlas. Members are destroyed in // the reverse order of their declaration, whatever their access. std::optional window; std::optional font; Crafter::FontAtlas atlas; Crafter::GraphicsDescriptorHeap heap; Crafter::UIRenderer ui; std::optional> buildSub; std::optional wrapper; public: Theme theme; Layer background; Layer content; Layer chrome; Layer overlay; // The screens draw into the layers from here, once per frame. std::function onDraw; // The device once per process, then the window, the heap, the font, // the atlas, the renderer and the layers. Sizes in dp; the // compositor decides the real size on a phone anyway. void Create(std::uint32_t widthDp, std::uint32_t heightDp, std::string_view title, std::string_view appId, const std::filesystem::path& assetDir, const std::filesystem::path& cacheDir) { static bool deviceReady = false; static std::string deviceError; // a failed set-up is final: the app asks the library for nothing it could ask less of if (!deviceError.empty()) throw std::runtime_error(deviceError); if (!deviceReady) { std::error_code ec; std::filesystem::create_directories(cacheDir, ec); Crafter::Device::pipelineCachePath = cacheDir / "pipeline_cache.bin"; try { Crafter::Device::Initialize(); } catch (const std::exception& e) { deviceError = std::format("{} (the device's set-up is not run again)", e.what()); throw; } deviceReady = true; } window.emplace(widthDp, heightDp, title); window->SetAppId(appId); VkCommandBuffer init = window->StartInit(); heap.Initialize(16, 48, 4); // buffers: four layers, three buffers each, per frame in flight (36 at three frames; the rest spare) window->descriptorHeap = &heap; font.emplace(assetDir / "NotoSans-Regular.ttf"); atlas.Initialize(init); ui.fontAtlas = &atlas; ui.Initialize(*window, heap, init, assetDir / "ui-quads.comp.spv", assetDir / "ui-circles.comp.spv", assetDir / "ui-images.comp.spv", assetDir / "ui-text.comp.spv", assetDir / "ui-fused.comp.spv"); window->passes.push_back(&ui); background.Create(ui, atlas, 4, 4, 64); content.Create(ui, atlas, 2048, 256, 16384); chrome.Create(ui, atlas, 256, 32, 2048); overlay.Create(ui, atlas, 128, 16, 1024); buildSub.emplace(&ui.onBuild, [this](Crafter::UIBuildArgs a) { Frame(a.cmd, a.frameIdx); }); wrapper.emplace([this](std::uint32_t cp, float px) { return static_cast(font->AdvanceUnits(cp)) * font->ScaleForSize(px); }); window->FinishInit(); } Crafter::Window& Window() noexcept { return *window; } const Crafter::Window& Window() const noexcept { return *window; } Crafter::Font& Font() noexcept { return *font; } WordWrapper& Wrapper() noexcept { return *wrapper; } float Scale() const noexcept { return window->scale > 0 ? window->scale : 1.0f; } float Dp(float dp) const noexcept { return std::round(dp * Scale()); } float Width() const noexcept { return static_cast(window->width); } float Height() const noexcept { return static_cast(window->height); } float Ascent(float px) { return font->AscentPx(px); } float LineHeight(float px) { return font->LineHeight(px); } // A line's width as DrawText advances it (the font's unrounded // advances, none for a newline), so a caret or a following run lands // where the glyphs end. float TextWidth(std::string_view text, float px) { const float scale = font->ScaleForSize(px); float width = 0; for (std::size_t i = 0; i < text.size();) { const std::uint32_t cp = DecodeUtf8(text, i); if (cp == 0) break; if (cp != '\n') width += static_cast(font->AdvanceUnits(cp)) * scale; } return width; } // The byte offset in a line nearest to x from its start, by the // widths TextWidth measures: where a tap puts the cursor. std::size_t NearestByte(std::string_view line, float px, float x) { if (x <= 0) return 0; const float scale = font->ScaleForSize(px); float width = 0; float bestDistance = x; std::size_t best = 0; for (std::size_t i = 0; i < line.size();) { const std::uint32_t cp = DecodeUtf8(line, i); if (cp == 0) break; if (cp != '\n') width += static_cast(font->AdvanceUnits(cp)) * scale; const float distance = std::abs(x - width); if (distance > bestDistance) break; // the widths only grow; at a tie the later offset wins (past a zero-width mark) bestDistance = distance; best = i; } return best; } // The baseline that centres one line of text in a box. float CenteredBaseline(Box b, float px) { return b.y + (b.h - LineHeight(px)) / 2.0f + Ascent(px); } // True when any layer dropped items this frame (buffers too small). bool Overflowed() const noexcept { return background.Overflowed() || content.Overflowed() || chrome.Overflowed() || overlay.Overflowed(); } // Glyphs drawn blank this frame for want of an atlas cell: they get // one when a later frame begins, from glyphs not drawn in the last // framesInFlight + 1 frames (Gesture's FrameWait asks for the frames). std::uint32_t GlyphsWaiting() const noexcept { return background.GlyphsWaiting() + content.GlyphsWaiting() + chrome.GlyphsWaiting() + overlay.GlyphsWaiting(); } static constexpr std::uint32_t framesInFlight = Crafter::Window::numFrames; private: void Frame(VkCommandBuffer cmd, std::uint32_t frameIdx) { background.Begin(frameIdx); content.Begin(frameIdx); chrome.Begin(frameIdx); overlay.Begin(frameIdx); background.Quad({ 0, 0, Width(), Height() }, theme.bg); if (onDraw) onDraw(cmd); background.Submit(cmd, ui); content.Submit(cmd, ui); chrome.Submit(cmd, ui); overlay.Submit(cmd, ui); } }; }