nano-ui-rgfw (empty) → 0.2.0.0
raw patch · 21 files changed
+4943/−0 lines, 21 filesdep +basedep +bytestringdep +containersbinary-added
Dependencies added: base, bytestring, containers, file-embed, hashable, nano-ui, nano-ui-emit, nano-ui-rgfw, nano-ui-rgfw-bindings, nano-ui-shader, primitive, text, vector
Files
- CHANGELOG.md +10/−0
- LICENSE +20/−0
- LICENSE-Cozette +21/−0
- README.md +33/−0
- cbits/nano_ui_gl.c +912/−0
- data/cozette.min.otb binary
- examples/RgfwDemo.hs +3/−0
- examples/RgfwDemoCommon.hs +457/−0
- examples/RgfwProfile.hs +234/−0
- lib/NanoUI/Backend/Rgfw.hs +62/−0
- lib/NanoUI/Rgfw/Internal/Context.hs +77/−0
- lib/NanoUI/Rgfw/Internal/Debug.hs +184/−0
- lib/NanoUI/Rgfw/Internal/Font/Cozette.hs +427/−0
- lib/NanoUI/Rgfw/Internal/Gl.hs +647/−0
- lib/NanoUI/Rgfw/Internal/Input.hs +243/−0
- lib/NanoUI/Rgfw/Internal/Session.hs +616/−0
- nano-ui-rgfw.cabal +128/−0
- test/NanoUI/Rgfw/Render.hs +126/−0
- test/NanoUI/Rgfw/Wake.hs +95/−0
- test/NanoUI/Rgfw/Window.hs +324/−0
- test/Spec.hs +324/−0
+ CHANGELOG.md view
@@ -0,0 +1,10 @@+# Changelog++## 0.2.0.0 -- 2026-12-02++Initial release.++- `NanoUI.Backend.Rgfw` runs `nano-ui` views in a native OpenGL 3.2 window using bundled RGFW (`nano-ui-rgfw-bindings`) and the bundled Cozette bitmap font (`LICENSE-Cozette`), requiring no external SDL or FreeType C libraries.+- Supports `nano-ui-shader` GLSL 150 surface shaders and offscreen subtree effects, retained damage-clipped framebuffer rendering, image atlas textures, multi-thread wakeups, clipboard, cursor shapes, full keyboard/mouse input, and `WindowSettings` window commands (`askWindow`, `quit`, `requestScreenshot`, excluding transparency/opacity).+- Supports Elm-style reducer apps (`NanoUIE msg ()` from `nano-ui-emit`), `optTheme` / `optThemeFor`, `optExplainLayout`, and `askRgfwDebug` / `debugWindowBody`.+- Builds with GHC 9.10 through 9.14 (`base >=4.20 && <4.23`).
+ LICENSE view
@@ -0,0 +1,20 @@+Copyright (c) 2026 goolord++Permission is hereby granted, free of charge, to any person obtaining+a copy of this software and associated documentation files (the+"Software"), to deal in the Software without restriction, including+without limitation the rights to use, copy, modify, merge, publish,+distribute, sublicense, and/or sell copies of the Software, and to+permit persons to whom the Software is furnished to do so, subject to+the following conditions:++The above copyright notice and this permission notice shall be included+in all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ LICENSE-Cozette view
@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2020, Ines <ines@moonwit.ch>++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.
+ README.md view
@@ -0,0 +1,33 @@+# nano-ui-rgfw++Lightweight desktop backend for [nano-ui](https://github.com/goolord/nano-ui) built on [RGFW](https://github.com/ColleagueRiley/RGFW) and OpenGL 3.2. RGFW's C source compiles with the package and text renders with the bundled [Cozette](https://github.com/slavfox/Cozette) bitmap font, so there are no dependencies beyond native OS windowing and OpenGL.++```haskell+{-# LANGUAGE OverloadedStrings #-}++import NanoUI+import NanoUI.Backend.Rgfw (RgfwOptions (..), defaultRgfwOptions, runRgfwApp)++main :: IO ()+main = runRgfwApp defaultRgfwOptions {optScale = 2} (label "Hello")+```++`runRgfwAppReduce` pairs a `model -> NanoUIE msg ()` view with `msg -> model -> model` (via `nano-ui-emit`), and `runRgfwAppWith` runs custom initialization after window creation and before frame 1. Configure window geometry (`optWindow`, using core `WindowSettings`), theme, UI scale (`optScale = 0` follows the monitor scale), and animation refresh rate through `RgfwOptions`.++Core themes work here via `applyRgfwTheme`, which adapts surfaces to square corners and 1 px borders. Cozette renders at 7x13 px at 1x scale (EPX-upscaled at 2x and 4x) as a single fixed-size bitmap font, so `fontSize` and `fontMono` do not change glyph size, and all RGFW windows are opaque. Use [nano-ui-sdl](https://hackage.haskell.org/package/nano-ui-sdl) when you need TrueType typography, IME pre-edit, OS file drops, or translucent windows.++## System requirements++- **Linux:** X11, Xcursor, Xrandr, and Xi development headers, plus OpenGL 3.2+- **macOS:** Cocoa and OpenGL 3.2+- **Windows:** `gdi32`, `user32`, `shell32`, and OpenGL 3.2++Link executables with `-threaded` so background tasks keep running while the event loop sleeps.++## Documentation++- [The nano-ui Book](https://goolord.github.io/nano-ui/book/): Tutorials, widget gallery, and backend overview.++## License++MIT. The bundled Cozette bitmap font is MIT-licensed by its author (`LICENSE-Cozette`); include that notice alongside distributed applications.
+ cbits/nano_ui_gl.c view
@@ -0,0 +1,912 @@+/* OpenGL 3.2 core renderer for the RGFW host.+ *+ * Geometry is the core's shared draw buffer uploaded as-is (32-byte vertices:+ * position, RGBA, UV; 32-bit indices) and drawn per command under a scissor.+ * Image-atlas commands sample it tinted by vertex colour; other geometry is+ * flat. Text is pre-clipped glyph quads in physical pixels, sampled from an+ * R8 coverage atlas.+ *+ * Frames draw into a retained offscreen framebuffer, which keeps the pixels+ * outside a frame's damage, and every present copies it to the window: the+ * window's back buffer is undefined after a swap, the retained one is not.+ *+ * GL entry points are resolved through RGFW's loader, so this file needs no+ * GL headers and adds no link dependencies. */++#include <stddef.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++typedef void (*rgfw_proc)(void);+extern rgfw_proc RGFW_getProcAddress_OpenGL(const char* procname);++#if defined(_WIN32)+#define NGL_API __stdcall+#else+#define NGL_API+#endif++typedef uint32_t GLenum;+typedef uint32_t GLuint;+typedef uint32_t GLbitfield;+typedef int32_t GLint;+typedef int32_t GLsizei;+typedef float GLfloat;+typedef uint8_t GLboolean;+typedef char GLchar;+typedef intptr_t GLsizeiptr;++#define GL_FALSE 0+#define GL_ONE 1+#define GL_TRIANGLES 0x0004+#define GL_SRC_ALPHA 0x0302+#define GL_ONE_MINUS_SRC_ALPHA 0x0303+#define GL_CULL_FACE 0x0B44+#define GL_DEPTH_TEST 0x0B71+#define GL_BLEND 0x0BE2+#define GL_SCISSOR_TEST 0x0C11+#define GL_UNPACK_ROW_LENGTH 0x0CF2+#define GL_UNPACK_ALIGNMENT 0x0CF5+#define GL_PACK_ALIGNMENT 0x0D05+#define GL_TEXTURE_2D 0x0DE1+#define GL_UNSIGNED_BYTE 0x1401+#define GL_UNSIGNED_INT 0x1405+#define GL_FLOAT 0x1406+#define GL_RED 0x1903+#define GL_VERSION 0x1F02+#define GL_NEAREST 0x2600+#define GL_LINEAR 0x2601+#define GL_TEXTURE_MAG_FILTER 0x2800+#define GL_TEXTURE_MIN_FILTER 0x2801+#define GL_TEXTURE_WRAP_S 0x2802+#define GL_TEXTURE_WRAP_T 0x2803+#define GL_COLOR_BUFFER_BIT 0x4000+#define GL_CLAMP_TO_EDGE 0x812F+#define GL_R8 0x8229+#define GL_RGBA 0x1908+#define GL_RGBA8 0x8058+#define GL_READ_FRAMEBUFFER 0x8CA8+#define GL_DRAW_FRAMEBUFFER 0x8CA9+#define GL_FRAMEBUFFER_COMPLETE 0x8CD5+#define GL_COLOR_ATTACHMENT0 0x8CE0+#define GL_FRAMEBUFFER 0x8D40+#define GL_TEXTURE0 0x84C0+#define GL_TEXTURE1 0x84C1+#define GL_ARRAY_BUFFER 0x8892+#define GL_ELEMENT_ARRAY_BUFFER 0x8893+#define GL_STREAM_DRAW 0x88E0+#define GL_UNIFORM_BUFFER 0x8A11+#define GL_INVALID_INDEX 0xFFFFFFFFu+#define GL_FRAGMENT_SHADER 0x8B30+#define GL_VERTEX_SHADER 0x8B31+#define GL_COMPILE_STATUS 0x8B81+#define GL_LINK_STATUS 0x8B82+#define GL_FRAMEBUFFER_SRGB 0x8DB9++#define NGL_FUNCS \+ X(const uint8_t*, GetString, (GLenum)) \+ X(void, Viewport, (GLint, GLint, GLsizei, GLsizei)) \+ X(void, Scissor, (GLint, GLint, GLsizei, GLsizei)) \+ X(void, ClearColor, (GLfloat, GLfloat, GLfloat, GLfloat)) \+ X(void, Clear, (GLbitfield)) \+ X(void, Enable, (GLenum)) \+ X(void, Disable, (GLenum)) \+ X(void, BlendFuncSeparate, (GLenum, GLenum, GLenum, GLenum)) \+ X(void, PixelStorei, (GLenum, GLint)) \+ X(GLuint, CreateShader, (GLenum)) \+ X(void, ShaderSource, (GLuint, GLsizei, const GLchar* const*, const GLint*)) \+ X(void, CompileShader, (GLuint)) \+ X(void, GetShaderiv, (GLuint, GLenum, GLint*)) \+ X(void, GetShaderInfoLog, (GLuint, GLsizei, GLsizei*, GLchar*)) \+ X(void, DeleteShader, (GLuint)) \+ X(GLuint, CreateProgram, (void)) \+ X(void, AttachShader, (GLuint, GLuint)) \+ X(void, BindAttribLocation, (GLuint, GLuint, const GLchar*)) \+ X(void, LinkProgram, (GLuint)) \+ X(void, GetProgramiv, (GLuint, GLenum, GLint*)) \+ X(void, GetProgramInfoLog, (GLuint, GLsizei, GLsizei*, GLchar*)) \+ X(void, DeleteProgram, (GLuint)) \+ X(void, UseProgram, (GLuint)) \+ X(GLint, GetUniformLocation, (GLuint, const GLchar*)) \+ X(GLuint, GetUniformBlockIndex, (GLuint, const GLchar*)) \+ X(void, UniformBlockBinding, (GLuint, GLuint, GLuint)) \+ X(void, BindBufferBase, (GLenum, GLuint, GLuint)) \+ X(void, Uniform1i, (GLint, GLint)) \+ X(void, Uniform1f, (GLint, GLfloat)) \+ X(void, Uniform2f, (GLint, GLfloat, GLfloat)) \+ X(void, GenVertexArrays, (GLsizei, GLuint*)) \+ X(void, BindVertexArray, (GLuint)) \+ X(void, DeleteVertexArrays, (GLsizei, const GLuint*)) \+ X(void, GenBuffers, (GLsizei, GLuint*)) \+ X(void, BindBuffer, (GLenum, GLuint)) \+ X(void, BufferData, (GLenum, GLsizeiptr, const void*, GLenum)) \+ X(void, DeleteBuffers, (GLsizei, const GLuint*)) \+ X(void, EnableVertexAttribArray, (GLuint)) \+ X(void, VertexAttribPointer, (GLuint, GLint, GLenum, GLboolean, GLsizei, const void*)) \+ X(void, DrawElements, (GLenum, GLsizei, GLenum, const void*)) \+ X(void, DrawArrays, (GLenum, GLint, GLsizei)) \+ X(void, GenTextures, (GLsizei, GLuint*)) \+ X(void, BindTexture, (GLenum, GLuint)) \+ X(void, ActiveTexture, (GLenum)) \+ X(void, TexParameteri, (GLenum, GLenum, GLint)) \+ X(void, TexImage2D, (GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void*)) \+ X(void, TexSubImage2D, (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void*)) \+ X(void, DeleteTextures, (GLsizei, const GLuint*)) \+ X(void, ReadPixels, (GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void*)) \+ X(void, GenFramebuffers, (GLsizei, GLuint*)) \+ X(void, BindFramebuffer, (GLenum, GLuint)) \+ X(void, FramebufferTexture2D, (GLenum, GLenum, GLenum, GLuint, GLint)) \+ X(GLenum, CheckFramebufferStatus, (GLenum)) \+ X(void, DeleteFramebuffers, (GLsizei, const GLuint*)) \+ X(void, BlitFramebuffer, (GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum))++typedef struct ngl_api {+#define X(ret, name, args) ret(NGL_API* name) args;+ NGL_FUNCS+#undef X+} ngl_api;++/* Must match the core's vertexSize / indexSize. nano-ui-rgfw-test checks+ * them through nano_ui_gl_vertex_bytes and nano_ui_gl_index_bytes. */+enum { NGL_VERTEX_BYTES = 32, NGL_INDEX_BYTES = 4 };++/* One vertex of the core's draw buffer and of the text quads Gl.hs writes+ * (writeSpanQuads): position, RGBA from 0 to 1, UV. ngl_vertex_layout points+ * the attributes at these fields. */+typedef struct ngl_vertex {+ float x, y;+ float r, g, b, a;+ float u, v;+} ngl_vertex;++_Static_assert(sizeof(ngl_vertex) == NGL_VERTEX_BYTES, "ngl_vertex must be the core's 32-byte vertex");+_Static_assert(offsetof(ngl_vertex, r) == 8, "colour follows the 2-float position");+_Static_assert(offsetof(ngl_vertex, u) == 24, "UV follows the 4-float colour");+_Static_assert(sizeof(uint32_t) == NGL_INDEX_BYTES, "indices are 32-bit");++int32_t nano_ui_gl_vertex_bytes(void) { return NGL_VERTEX_BYTES; }+int32_t nano_ui_gl_index_bytes(void) { return NGL_INDEX_BYTES; }++enum { NGL_MODE_NONE, NGL_MODE_GEOMETRY, NGL_MODE_IMAGE, NGL_MODE_TEXT };++typedef struct ngl_shader_entry {+ uint64_t hash;+ GLuint program;+ GLint uViewport;+ GLint uOrigin;+ GLint uScale;+ GLint uInput;+ int failed;+} ngl_shader_entry;++typedef struct ngl_target_slot {+ GLuint fbo;+ GLuint tex;+ int32_t capW;+ int32_t capH;+ int inUse;+} ngl_target_slot;++typedef struct nano_ui_gl {+ ngl_api gl;+ GLuint program;+ GLint uViewport, uOrigin, uScale, uTextured, uAtlas, uImages;+ GLuint geomVao, geomVbo, geomEbo;+ GLuint textVao, textVbo;+ GLuint effectVao, effectVbo;+ GLuint shaderUbo;+ ngl_shader_entry* shaders;+ int shaderCount, shaderCap;+ ngl_target_slot* targets;+ int targetCount, targetCap;+ GLuint atlas;+ GLuint images; /* the core's RGBA image atlas, texture unit 1 */+ int32_t imagesW, imagesH;+ GLuint retainFbo, retainTex;+ int32_t retainCapW, retainCapH; /* texture size, the window rounded up */+ int32_t fbW, fbH;+ int32_t curW, curH; /* currently bound framebuffer dimensions */+ float originX, originY; /* logical origin subtracted for offscreen effect targets */+ float scale; /* logical -> physical, for geometry vertices */+ int mode;+} nano_ui_gl;++static const char* ngl_vertex_src =+ "#version 150\n"+ "in vec2 aPos;\n"+ "in vec4 aColor;\n"+ "in vec2 aUV;\n"+ "uniform vec2 uViewport;\n"+ "uniform vec2 uOrigin;\n"+ "uniform float uScale;\n"+ "out vec4 vColor;\n"+ "out vec2 vUV;\n"+ "void main() {\n"+ " vec2 p = (aPos - uOrigin) * uScale;\n"+ " gl_Position = vec4(p.x / uViewport.x * 2.0 - 1.0, 1.0 - p.y / uViewport.y * 2.0, 0.0, 1.0);\n"+ " vColor = aColor;\n"+ " vUV = aUV;\n"+ "}\n";++static const char* ngl_fragment_src =+ "#version 150\n"+ "in vec4 vColor;\n"+ "in vec2 vUV;\n"+ "uniform sampler2D uAtlas;\n"+ "uniform sampler2D uImages;\n"+ "uniform float uTextured;\n"+ "out vec4 fragColor;\n"+ "void main() {\n"+ " if (uTextured > 1.5) {\n"+ " fragColor = texture(uImages, vUV) * vColor;\n"+ " } else {\n"+ " float coverage = uTextured > 0.5 ? texture(uAtlas, vUV).r : 1.0;\n"+ " fragColor = vec4(vColor.rgb, vColor.a * coverage);\n"+ " }\n"+ "}\n";++static int ngl_load(ngl_api* gl) {+#define X(ret, name, args) \+ gl->name = (ret(NGL_API*) args)RGFW_getProcAddress_OpenGL("gl" #name); \+ if (gl->name == NULL) { \+ fprintf(stderr, "nano-ui-rgfw: OpenGL entry point gl%s is unavailable\n", #name); \+ return 0; \+ }+ NGL_FUNCS+#undef X+ return 1;+}++static GLuint ngl_compile(ngl_api* gl, GLenum type, const char* src) {+ GLuint shader = gl->CreateShader(type);+ GLint ok = 0;+ gl->ShaderSource(shader, 1, &src, NULL);+ gl->CompileShader(shader);+ gl->GetShaderiv(shader, GL_COMPILE_STATUS, &ok);+ if (!ok) {+ char log[1024];+ gl->GetShaderInfoLog(shader, sizeof log, NULL, log);+ fprintf(stderr, "nano-ui-rgfw: shader compile failed: %s\n", log);+ gl->DeleteShader(shader);+ return 0;+ }+ return shader;+}++static GLuint ngl_link_program(ngl_api* gl, const char* fragSrc, const char* errPrefix) {+ GLuint vs = ngl_compile(gl, GL_VERTEX_SHADER, ngl_vertex_src);+ GLuint fs = vs ? ngl_compile(gl, GL_FRAGMENT_SHADER, fragSrc) : 0;+ GLint ok = 0;+ if (!fs) {+ if (vs) gl->DeleteShader(vs);+ return 0;+ }+ GLuint prog = gl->CreateProgram();+ gl->AttachShader(prog, vs);+ gl->AttachShader(prog, fs);+ gl->BindAttribLocation(prog, 0, "aPos");+ gl->BindAttribLocation(prog, 1, "aColor");+ gl->BindAttribLocation(prog, 2, "aUV");+ gl->LinkProgram(prog);+ gl->DeleteShader(vs);+ gl->DeleteShader(fs);+ gl->GetProgramiv(prog, GL_LINK_STATUS, &ok);+ if (!ok) {+ char log[1024];+ gl->GetProgramInfoLog(prog, sizeof log, NULL, log);+ fprintf(stderr, "nano-ui-rgfw: %s: %s\n", errPrefix, log);+ gl->DeleteProgram(prog);+ return 0;+ }+ return prog;+}++static int ngl_link(nano_ui_gl* r) {+ ngl_api* gl = &r->gl;+ r->program = ngl_link_program(gl, ngl_fragment_src, "shader link failed");+ if (!r->program) return 0;+ r->uViewport = gl->GetUniformLocation(r->program, "uViewport");+ r->uOrigin = gl->GetUniformLocation(r->program, "uOrigin");+ r->uScale = gl->GetUniformLocation(r->program, "uScale");+ r->uTextured = gl->GetUniformLocation(r->program, "uTextured");+ r->uAtlas = gl->GetUniformLocation(r->program, "uAtlas");+ r->uImages = gl->GetUniformLocation(r->program, "uImages");+ return 1;+}++static void ngl_vertex_layout(ngl_api* gl) {+ gl->EnableVertexAttribArray(0);+ gl->VertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, NGL_VERTEX_BYTES, (const void*)offsetof(ngl_vertex, x));+ gl->EnableVertexAttribArray(1);+ gl->VertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, NGL_VERTEX_BYTES, (const void*)offsetof(ngl_vertex, r));+ gl->EnableVertexAttribArray(2);+ gl->VertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, NGL_VERTEX_BYTES, (const void*)offsetof(ngl_vertex, u));+}++static int ngl_major_version(const uint8_t* version) {+ int major = 0;+ if (version == NULL) return 0;+ for (; *version >= '0' && *version <= '9'; version++) major = major * 10 + (*version - '0');+ return major;+}++void nano_ui_gl_destroy(nano_ui_gl* r);++/* Requires the target context to be current. Returns NULL (after logging the+ * reason to stderr) when the context cannot run the renderer. */+nano_ui_gl* nano_ui_gl_create(void) {+ nano_ui_gl* r = (nano_ui_gl*)calloc(1, sizeof *r);+ if (r == NULL) return NULL;+ ngl_api* gl = &r->gl;+ if (!ngl_load(gl)) {+ free(r);+ return NULL;+ }+ const uint8_t* version = gl->GetString(GL_VERSION);+ if (ngl_major_version(version) < 3) {+ fprintf(stderr, "nano-ui-rgfw: OpenGL 3.2 required, context reports %s\n",+ version ? (const char*)version : "no version");+ free(r);+ return NULL;+ }+ if (!ngl_link(r)) {+ nano_ui_gl_destroy(r);+ return NULL;+ }++ gl->GenVertexArrays(1, &r->geomVao);+ gl->GenBuffers(1, &r->geomVbo);+ gl->GenBuffers(1, &r->geomEbo);+ gl->BindVertexArray(r->geomVao);+ gl->BindBuffer(GL_ARRAY_BUFFER, r->geomVbo);+ gl->BindBuffer(GL_ELEMENT_ARRAY_BUFFER, r->geomEbo);+ ngl_vertex_layout(gl);++ gl->GenVertexArrays(1, &r->textVao);+ gl->GenBuffers(1, &r->textVbo);+ gl->BindVertexArray(r->textVao);+ gl->BindBuffer(GL_ARRAY_BUFFER, r->textVbo);+ ngl_vertex_layout(gl);++ gl->GenVertexArrays(1, &r->effectVao);+ gl->GenBuffers(1, &r->effectVbo);+ gl->BindVertexArray(r->effectVao);+ gl->BindBuffer(GL_ARRAY_BUFFER, r->effectVbo);+ ngl_vertex_layout(gl);+ gl->BindVertexArray(0);+ gl->GenBuffers(1, &r->shaderUbo);++ gl->GenTextures(1, &r->atlas);+ gl->BindTexture(GL_TEXTURE_2D, r->atlas);+ gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);+ gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);+ gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);+ gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);++ gl->UseProgram(r->program);+ gl->Uniform1i(r->uAtlas, 0);+ gl->Uniform1i(r->uImages, 1);+ return r;+}++void nano_ui_gl_destroy(nano_ui_gl* r) {+ if (r == NULL) return;+ ngl_api* gl = &r->gl;+ if (r->shaders) {+ for (int i = 0; i < r->shaderCount; i++) {+ if (r->shaders[i].program) gl->DeleteProgram(r->shaders[i].program);+ }+ free(r->shaders);+ }+ if (r->targets) {+ for (int i = 0; i < r->targetCount; i++) {+ if (r->targets[i].fbo) gl->DeleteFramebuffers(1, &r->targets[i].fbo);+ if (r->targets[i].tex) gl->DeleteTextures(1, &r->targets[i].tex);+ }+ free(r->targets);+ }+ if (r->shaderUbo) gl->DeleteBuffers(1, &r->shaderUbo);+ if (r->effectVbo) gl->DeleteBuffers(1, &r->effectVbo);+ if (r->effectVao) gl->DeleteVertexArrays(1, &r->effectVao);+ if (r->retainFbo) gl->DeleteFramebuffers(1, &r->retainFbo);+ if (r->retainTex) gl->DeleteTextures(1, &r->retainTex);+ if (r->atlas) gl->DeleteTextures(1, &r->atlas);+ if (r->images) gl->DeleteTextures(1, &r->images);+ if (r->textVbo) gl->DeleteBuffers(1, &r->textVbo);+ if (r->textVao) gl->DeleteVertexArrays(1, &r->textVao);+ if (r->geomEbo) gl->DeleteBuffers(1, &r->geomEbo);+ if (r->geomVbo) gl->DeleteBuffers(1, &r->geomVbo);+ if (r->geomVao) gl->DeleteVertexArrays(1, &r->geomVao);+ if (r->program) gl->DeleteProgram(r->program);+ free(r);+}++/* Replace the glyph atlas. Pixels are the software blitter's white-on-black+ * bake; the low byte of each pixel is its coverage. Returns 0 on allocation+ * failure. */+int32_t nano_ui_gl_upload_atlas(nano_ui_gl* r, const uint32_t* pixels, int32_t w, int32_t h) {+ ngl_api* gl = &r->gl;+ size_t n = (size_t)w * (size_t)h;+ uint8_t* coverage = (uint8_t*)malloc(n > 0 ? n : 1);+ if (coverage == NULL) return 0;+ for (size_t i = 0; i < n; i++) coverage[i] = (uint8_t)(pixels[i] & 0xFF);+ gl->BindTexture(GL_TEXTURE_2D, r->atlas);+ gl->PixelStorei(GL_UNPACK_ALIGNMENT, 1);+ gl->TexImage2D(GL_TEXTURE_2D, 0, GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, coverage);+ free(coverage);+ return 1;+}++/* Sync the image texture with the core's atlasW x atlasH RGBA image atlas.+ * With whole set, reallocate the texture at that size and upload everything;+ * otherwise upload only the x, y, w, h rect. Returns 0 if a rect upload finds+ * no texture of the atlas's size. */+int32_t nano_ui_gl_upload_images(nano_ui_gl* r, const uint8_t* pixels, int32_t atlasW, int32_t atlasH,+ int32_t x, int32_t y, int32_t w, int32_t h, int32_t whole) {+ ngl_api* gl = &r->gl;+ if (!whole && (r->images == 0 || r->imagesW != atlasW || r->imagesH != atlasH)) return 0;+ if (r->images == 0) {+ gl->GenTextures(1, &r->images);+ gl->ActiveTexture(GL_TEXTURE1);+ gl->BindTexture(GL_TEXTURE_2D, r->images);+ gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);+ gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);+ gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);+ gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);+ } else {+ gl->ActiveTexture(GL_TEXTURE1);+ gl->BindTexture(GL_TEXTURE_2D, r->images);+ }+ gl->PixelStorei(GL_UNPACK_ALIGNMENT, 1);+ if (whole) {+ gl->TexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, atlasW, atlasH, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);+ r->imagesW = atlasW;+ r->imagesH = atlasH;+ } else {+ gl->PixelStorei(GL_UNPACK_ROW_LENGTH, atlasW);+ gl->TexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE,+ pixels + ((size_t)y * (size_t)atlasW + (size_t)x) * 4);+ gl->PixelStorei(GL_UNPACK_ROW_LENGTH, 0);+ }+ gl->ActiveTexture(GL_TEXTURE0);+ return 1;+}++/* Pixels the retained texture is rounded up to, in each dimension. */+enum { NGL_RETAIN_BLOCK = 256 };++static int32_t ngl_round_up(int32_t n) {+ return (n + NGL_RETAIN_BLOCK - 1) / NGL_RETAIN_BLOCK * NGL_RETAIN_BLOCK;+}++/* Make the retained framebuffer hold at least w x h pixels. A texture well+ * past the window is given back, but not for a shrink of a block or so, which+ * a drag back out would undo. Returns 1 if the texture was replaced, which+ * discards its pixels, 0 if it was kept, and -1 on failure. */+static int ngl_ensure_retain(nano_ui_gl* r, int32_t w, int32_t h) {+ ngl_api* gl = &r->gl;+ int fits = r->retainFbo && w <= r->retainCapW && h <= r->retainCapH;+ int roomy = r->retainCapW - w > 2 * NGL_RETAIN_BLOCK || r->retainCapH - h > 2 * NGL_RETAIN_BLOCK;+ if (fits && !roomy) return 0;+ if (!r->retainFbo) {+ gl->GenFramebuffers(1, &r->retainFbo);+ gl->GenTextures(1, &r->retainTex);+ }+ r->retainCapW = ngl_round_up(w);+ r->retainCapH = ngl_round_up(h);+ gl->BindTexture(GL_TEXTURE_2D, r->retainTex);+ gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);+ gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);+ gl->TexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, r->retainCapW, r->retainCapH, 0, GL_RGBA,+ GL_UNSIGNED_BYTE, NULL);+ gl->BindFramebuffer(GL_FRAMEBUFFER, r->retainFbo);+ gl->FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, r->retainTex, 0);+ if (gl->CheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {+ fprintf(stderr, "nano-ui-rgfw: retained framebuffer is incomplete\n");+ gl->BindFramebuffer(GL_FRAMEBUFFER, 0);+ r->retainCapW = 0;+ r->retainCapH = 0;+ return -1;+ }+ return 1;+}++/* Start a frame on the retained framebuffer: viewport, fixed pipeline state,+ * and the logical -> physical scale for this frame's geometry. A full frame+ * clears everything; otherwise nothing is cleared, since the frame's own+ * backdrop covers what it repaints, and nothing is drawn outside the damage+ * box, where the pixels are last frame's; the core has already cut every+ * command and span to the damage. A framebuffer replaced for a new size holds+ * no last frame and is cleared too, so a caller must paint a frame at a new+ * size in full. Returns 0 if the retained framebuffer cannot be made, and 1+ * otherwise. */+int32_t nano_ui_gl_begin(nano_ui_gl* r, int32_t fbW, int32_t fbH, float scale, float red,+ float green, float blue, int32_t full) {+ ngl_api* gl = &r->gl;+ r->fbW = fbW > 0 ? fbW : 1;+ r->fbH = fbH > 0 ? fbH : 1;+ r->curW = r->fbW;+ r->curH = r->fbH;+ r->originX = 0.0f;+ r->originY = 0.0f;+ r->scale = scale;+ r->mode = NGL_MODE_NONE;+ int replaced = ngl_ensure_retain(r, r->fbW, r->fbH);+ if (replaced < 0) return 0;+ gl->BindFramebuffer(GL_FRAMEBUFFER, r->retainFbo);+ gl->Viewport(0, 0, r->fbW, r->fbH);+ gl->Disable(GL_DEPTH_TEST);+ gl->Disable(GL_CULL_FACE);+ gl->Disable(GL_FRAMEBUFFER_SRGB);+ gl->Disable(GL_SCISSOR_TEST);+ if (full || replaced) {+ gl->ClearColor(red, green, blue, 1.0f);+ gl->Clear(GL_COLOR_BUFFER_BIT);+ }+ gl->Enable(GL_BLEND);+ gl->BlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);+ gl->UseProgram(r->program);+ gl->Uniform2f(r->uViewport, (GLfloat)r->fbW, (GLfloat)r->fbH);+ gl->Uniform2f(r->uOrigin, 0.0f, 0.0f);+ gl->ActiveTexture(GL_TEXTURE1);+ gl->BindTexture(GL_TEXTURE_2D, r->images);+ gl->ActiveTexture(GL_TEXTURE0);+ gl->BindTexture(GL_TEXTURE_2D, r->atlas);+ return 1;+}++/* Read the bottom-left w x h of the retained frame as RGBA rows, bottom row+ * first, into out, which holds w * h * 4 bytes. Pixels past the last frame's+ * size are undefined. */+void nano_ui_gl_read_retained(nano_ui_gl* r, int32_t w, int32_t h, uint8_t* out) {+ ngl_api* gl = &r->gl;+ gl->BindFramebuffer(GL_READ_FRAMEBUFFER, r->retainFbo);+ gl->PixelStorei(GL_PACK_ALIGNMENT, 1);+ gl->ReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, out);+ gl->BindFramebuffer(GL_FRAMEBUFFER, 0);+}++/* Read the window's back buffer after present and before the swap, which+ * leaves it undefined, as nano_ui_gl_read_retained does. Used by tests of+ * the present. */+void nano_ui_gl_read_window(nano_ui_gl* r, int32_t w, int32_t h, uint8_t* out) {+ ngl_api* gl = &r->gl;+ gl->BindFramebuffer(GL_READ_FRAMEBUFFER, 0);+ gl->PixelStorei(GL_PACK_ALIGNMENT, 1);+ gl->ReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, out);+ gl->BindFramebuffer(GL_FRAMEBUFFER, 0);+}++/* Copy the retained frame to the window's back buffer. The caller swaps. */+void nano_ui_gl_present(nano_ui_gl* r) {+ ngl_api* gl = &r->gl;+ gl->Disable(GL_SCISSOR_TEST);+ gl->BindFramebuffer(GL_READ_FRAMEBUFFER, r->retainFbo);+ gl->BindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);+ gl->BlitFramebuffer(0, 0, r->fbW, r->fbH, 0, 0, r->fbW, r->fbH, GL_COLOR_BUFFER_BIT, GL_NEAREST);+ gl->BindFramebuffer(GL_FRAMEBUFFER, 0);+ r->mode = NGL_MODE_NONE;+}++void nano_ui_gl_upload_geometry(nano_ui_gl* r, const void* vertices, int32_t vertexCount,+ const void* indices, int32_t indexCount) {+ ngl_api* gl = &r->gl;+ r->mode = NGL_MODE_NONE;+ gl->BindVertexArray(r->geomVao);+ gl->BindBuffer(GL_ARRAY_BUFFER, r->geomVbo);+ gl->BufferData(GL_ARRAY_BUFFER, (GLsizeiptr)vertexCount * NGL_VERTEX_BYTES,+ vertexCount > 0 ? vertices : NULL, GL_STREAM_DRAW);+ gl->BufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)indexCount * NGL_INDEX_BYTES,+ indexCount > 0 ? indices : NULL, GL_STREAM_DRAW);+}++void nano_ui_gl_upload_text(nano_ui_gl* r, const void* vertices, int32_t vertexCount) {+ ngl_api* gl = &r->gl;+ r->mode = NGL_MODE_NONE;+ gl->BindVertexArray(r->textVao);+ gl->BindBuffer(GL_ARRAY_BUFFER, r->textVbo);+ gl->BufferData(GL_ARRAY_BUFFER, (GLsizeiptr)vertexCount * NGL_VERTEX_BYTES,+ vertexCount > 0 ? vertices : NULL, GL_STREAM_DRAW);+}++/* Draw one command's index range, sampling the image texture if image is+ * set. The clip is in top-left physical pixels, already intersected with the+ * framebuffer; vertices are logical and scaled in the vertex shader by the+ * frame's scale. */+void nano_ui_gl_draw_geometry(nano_ui_gl* r, int32_t x0, int32_t y0, int32_t x1, int32_t y1,+ uint32_t firstIndex, uint32_t indexCount, int32_t image) {+ ngl_api* gl = &r->gl;+ int mode = image && r->images ? NGL_MODE_IMAGE : NGL_MODE_GEOMETRY;+ if (r->mode != mode) {+ if (r->mode != NGL_MODE_GEOMETRY && r->mode != NGL_MODE_IMAGE) {+ gl->BindVertexArray(r->geomVao);+ gl->Uniform1f(r->uScale, r->scale);+ gl->Uniform2f(r->uOrigin, r->originX, r->originY);+ gl->Enable(GL_SCISSOR_TEST);+ }+ gl->Uniform1f(r->uTextured, mode == NGL_MODE_IMAGE ? 2.0f : 0.0f);+ r->mode = mode;+ }+ gl->Scissor(x0, r->curH - y1, x1 - x0, y1 - y0);+ gl->DrawElements(GL_TRIANGLES, (GLsizei)indexCount, GL_UNSIGNED_INT,+ (const void*)((uintptr_t)firstIndex * NGL_INDEX_BYTES));+}++/* Look up or compile and link a cached fragment shader keyed by its 64-bit+ * program hash. Failed compilations are cached so broken shaders never spam+ * error logs on every frame. */+static ngl_shader_entry* ngl_get_shader(nano_ui_gl* r, uint64_t hash, const char* fragSrc, int32_t fragLen) {+ for (int i = 0; i < r->shaderCount; i++) {+ if (r->shaders[i].hash == hash) return &r->shaders[i];+ }+ if (r->shaderCount == r->shaderCap) {+ int newCap = r->shaderCap > 0 ? r->shaderCap * 2 : 16;+ ngl_shader_entry* grown = (ngl_shader_entry*)realloc(r->shaders, (size_t)newCap * sizeof *grown);+ if (grown == NULL) return NULL;+ r->shaders = grown;+ r->shaderCap = newCap;+ }+ ngl_shader_entry* entry = &r->shaders[r->shaderCount++];+ memset(entry, 0, sizeof *entry);+ entry->hash = hash;+ entry->uViewport = -1;+ entry->uOrigin = -1;+ entry->uScale = -1;+ entry->uInput = -1;+ if (fragSrc == NULL || fragLen <= 0) {+ entry->failed = 1;+ return entry;+ }+ char* srcCopy = (char*)malloc((size_t)fragLen + 1);+ if (srcCopy == NULL) {+ entry->failed = 1;+ return entry;+ }+ memcpy(srcCopy, fragSrc, (size_t)fragLen);+ srcCopy[fragLen] = '\0';++ ngl_api* gl = &r->gl;+ GLuint prog = ngl_link_program(gl, srcCopy, "custom shader link failed");+ free(srcCopy);+ if (!prog) {+ entry->failed = 1;+ return entry;+ }+ GLuint blk = gl->GetUniformBlockIndex(prog, "NanoShaderBlock");+ if (blk != GL_INVALID_INDEX) {+ gl->UniformBlockBinding(prog, blk, 0);+ }+ entry->program = prog;+ entry->uViewport = gl->GetUniformLocation(prog, "uViewport");+ entry->uOrigin = gl->GetUniformLocation(prog, "uOrigin");+ entry->uScale = gl->GetUniformLocation(prog, "uScale");+ entry->uInput = gl->GetUniformLocation(prog, "uInput");+ return entry;+}++static void ngl_bind_shader_uniforms(+ nano_ui_gl* r, ngl_shader_entry* entry, float ox, float oy, float scale,+ const void* uniformBytes, int32_t uniformLen) {+ ngl_api* gl = &r->gl;+ gl->UseProgram(entry->program);+ if (entry->uViewport >= 0) gl->Uniform2f(entry->uViewport, (GLfloat)r->curW, (GLfloat)r->curH);+ if (entry->uOrigin >= 0) gl->Uniform2f(entry->uOrigin, ox, oy);+ if (entry->uScale >= 0) gl->Uniform1f(entry->uScale, scale);+ if (entry->uInput >= 0) gl->Uniform1i(entry->uInput, 0);+ if (uniformLen > 0 && uniformBytes != NULL) {+ gl->BindBuffer(GL_UNIFORM_BUFFER, r->shaderUbo);+ gl->BufferData(GL_UNIFORM_BUFFER, (GLsizeiptr)uniformLen, uniformBytes, GL_STREAM_DRAW);+ gl->BindBufferBase(GL_UNIFORM_BUFFER, 0, r->shaderUbo);+ }+}++static void ngl_restore_default(nano_ui_gl* r) {+ ngl_api* gl = &r->gl;+ gl->UseProgram(r->program);+ gl->Uniform2f(r->uViewport, (GLfloat)r->curW, (GLfloat)r->curH);+ gl->Uniform2f(r->uOrigin, r->originX, r->originY);+ r->mode = NGL_MODE_NONE;+}++/* Draw one shader-backed geometry command with its std140 uniform block bound+ * at UBO binding 0, then restore the default renderer program. */+int32_t nano_ui_gl_draw_shader(nano_ui_gl* r, int32_t x0, int32_t y0, int32_t x1, int32_t y1,+ uint32_t firstIndex, uint32_t indexCount, uint64_t hash,+ const char* fragSrc, int32_t fragLen, const void* uniformBytes,+ int32_t uniformLen) {+ ngl_shader_entry* entry = ngl_get_shader(r, hash, fragSrc, fragLen);+ if (entry == NULL || entry->failed || entry->program == 0) return 0;+ ngl_api* gl = &r->gl;+ ngl_bind_shader_uniforms(r, entry, r->originX, r->originY, r->scale, uniformBytes, uniformLen);+ gl->BindVertexArray(r->geomVao);+ gl->Enable(GL_SCISSOR_TEST);+ gl->Scissor(x0, r->curH - y1, x1 - x0, y1 - y0);+ gl->DrawElements(GL_TRIANGLES, (GLsizei)indexCount, GL_UNSIGNED_INT,+ (const void*)((uintptr_t)firstIndex * NGL_INDEX_BYTES));+ ngl_restore_default(r);+ return 1;+}++/* Draw a range of the uploaded glyph vertices (physical pixels, pre-clipped). */+void nano_ui_gl_draw_text(nano_ui_gl* r, int32_t firstVertex, int32_t vertexCount) {+ ngl_api* gl = &r->gl;+ if (vertexCount <= 0) return;+ if (r->mode != NGL_MODE_TEXT) {+ gl->BindVertexArray(r->textVao);+ gl->Uniform1f(r->uTextured, 1.0f);+ gl->Uniform1f(r->uScale, 1.0f);+ gl->Uniform2f(r->uOrigin, r->originX * r->scale, r->originY * r->scale);+ gl->Disable(GL_SCISSOR_TEST);+ r->mode = NGL_MODE_TEXT;+ }+ gl->DrawArrays(GL_TRIANGLES, firstVertex, vertexCount);+}++/* Acquire a 64px-bucketed pooled RGBA8 offscreen framebuffer for Tier 2+ * subtree effects. Returns a non-negative slot index or -1 on failure. */+int32_t nano_ui_gl_acquire_target(nano_ui_gl* r, int32_t minW, int32_t minH,+ int32_t* outCapW, int32_t* outCapH) {+ if (r == NULL) return -1;+ int32_t needW = minW > 0 ? ((minW + 63) & ~63) : 64;+ int32_t needH = minH > 0 ? ((minH + 63) & ~63) : 64;+ int best = -1;+ for (int i = 0; i < r->targetCount; i++) {+ ngl_target_slot* s = &r->targets[i];+ if (!s->inUse && s->fbo && s->tex &&+ s->capW >= needW && s->capH >= needH &&+ s->capW <= needW * 2 && s->capH <= needH * 2) {+ best = i;+ break;+ }+ }+ if (best < 0) {+ if (r->targetCount == r->targetCap) {+ int newCap = r->targetCap > 0 ? r->targetCap * 2 : 8;+ ngl_target_slot* grown = (ngl_target_slot*)realloc(r->targets, (size_t)newCap * sizeof *grown);+ if (grown == NULL) return -1;+ r->targets = grown;+ r->targetCap = newCap;+ }+ ngl_api* gl = &r->gl;+ GLuint fbo = 0, tex = 0;+ gl->GenFramebuffers(1, &fbo);+ gl->GenTextures(1, &tex);+ gl->ActiveTexture(GL_TEXTURE0);+ gl->BindTexture(GL_TEXTURE_2D, tex);+ gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);+ gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);+ gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);+ gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);+ gl->TexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, needW, needH, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);+ gl->BindFramebuffer(GL_FRAMEBUFFER, fbo);+ gl->FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex, 0);+ GLenum status = gl->CheckFramebufferStatus(GL_FRAMEBUFFER);+ gl->BindTexture(GL_TEXTURE_2D, r->atlas);+ if (status != GL_FRAMEBUFFER_COMPLETE) {+ gl->DeleteFramebuffers(1, &fbo);+ gl->DeleteTextures(1, &tex);+ return -1;+ }+ best = r->targetCount++;+ r->targets[best].fbo = fbo;+ r->targets[best].tex = tex;+ r->targets[best].capW = needW;+ r->targets[best].capH = needH;+ }+ r->targets[best].inUse = 1;+ if (outCapW) *outCapW = r->targets[best].capW;+ if (outCapH) *outCapH = r->targets[best].capH;+ return (int32_t)best;+}++void nano_ui_gl_release_target(nano_ui_gl* r, int32_t slot) {+ if (r != NULL && slot >= 0 && slot < r->targetCount) {+ r->targets[slot].inUse = 0;+ }+}++/* Bind pooled offscreen target slot (>= 0), or the retained framebuffer when+ * slot < 0. Updates viewport, active target dimensions, and logical origin. */+int32_t nano_ui_gl_bind_target(nano_ui_gl* r, int32_t slot, int32_t clearTransparent,+ float ox, float oy) {+ if (r == NULL) return 0;+ ngl_api* gl = &r->gl;+ if (slot >= 0 && slot < r->targetCount) {+ ngl_target_slot* s = &r->targets[slot];+ gl->BindFramebuffer(GL_FRAMEBUFFER, s->fbo);+ r->curW = s->capW;+ r->curH = s->capH;+ } else {+ gl->BindFramebuffer(GL_FRAMEBUFFER, r->retainFbo);+ r->curW = r->fbW;+ r->curH = r->fbH;+ }+ r->originX = ox;+ r->originY = oy;+ gl->Viewport(0, 0, r->curW, r->curH);+ gl->Disable(GL_SCISSOR_TEST);+ if (clearTransparent) {+ gl->ClearColor(0.0f, 0.0f, 0.0f, 0.0f);+ gl->Clear(GL_COLOR_BUFFER_BIT);+ }+ gl->ActiveTexture(GL_TEXTURE0);+ gl->BindTexture(GL_TEXTURE_2D, r->atlas);+ ngl_restore_default(r);+ return 1;+}++/* Composite pooled source target srcSlot onto the currently bound target at+ * physical pixel rect (dx, dy, dw, dh) with UVs (u0, v0)..(u1, v1) through a+ * cached GLSL 150 fragment shader. */+int32_t nano_ui_gl_composite_effect(+ nano_ui_gl* r, int32_t srcSlot,+ float dx, float dy, float dw, float dh,+ float u0, float v0, float u1, float v1,+ int32_t hasScissor, int32_t sx0, int32_t sy0, int32_t sx1, int32_t sy1,+ int32_t blendCopy,+ uint64_t hash, const char* fragSrc, int32_t fragLen,+ const void* uniformBytes, int32_t uniformLen) {+ if (r == NULL || srcSlot < 0 || srcSlot >= r->targetCount || !r->targets[srcSlot].tex) {+ return 0;+ }+ (void)blendCopy;+ ngl_shader_entry* entry = ngl_get_shader(r, hash, fragSrc, fragLen);+ ngl_api* gl = &r->gl;+ const ngl_vertex quad[6] = {+ { dx, dy, 1.f, 1.f, 1.f, 1.f, u0, v0 },+ { dx + dw, dy, 1.f, 1.f, 1.f, 1.f, u1, v0 },+ { dx + dw, dy + dh, 1.f, 1.f, 1.f, 1.f, u1, v1 },+ { dx, dy, 1.f, 1.f, 1.f, 1.f, u0, v0 },+ { dx + dw, dy + dh, 1.f, 1.f, 1.f, 1.f, u1, v1 },+ { dx, dy + dh, 1.f, 1.f, 1.f, 1.f, u0, v1 },+ };+ if (hasScissor) {+ gl->Enable(GL_SCISSOR_TEST);+ gl->Scissor(sx0, r->curH - sy1, sx1 - sx0, sy1 - sy0);+ } else {+ gl->Disable(GL_SCISSOR_TEST);+ }+ gl->Enable(GL_BLEND);+ if (entry == NULL || entry->failed || entry->program == 0) {+ /* Fallback: blit the offscreen premultiplied target unshaded so the+ * wrapped subtree stays visible if shader compilation fails. */+ gl->UseProgram(r->program);+ gl->Uniform2f(r->uViewport, (GLfloat)r->curW, (GLfloat)r->curH);+ gl->Uniform2f(r->uOrigin, 0.0f, 0.0f);+ gl->Uniform1f(r->uScale, 1.0f);+ gl->Uniform1f(r->uTextured, 2.0f);+ gl->ActiveTexture(GL_TEXTURE1);+ gl->BindTexture(GL_TEXTURE_2D, r->targets[srcSlot].tex);+ gl->BlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);+ gl->BindVertexArray(r->effectVao);+ gl->BindBuffer(GL_ARRAY_BUFFER, r->effectVbo);+ gl->BufferData(GL_ARRAY_BUFFER, (GLsizeiptr)sizeof(quad), quad, GL_STREAM_DRAW);+ gl->DrawArrays(GL_TRIANGLES, 0, 6);+ gl->BindTexture(GL_TEXTURE_2D, r->images);+ gl->ActiveTexture(GL_TEXTURE0);+ gl->BlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);+ gl->Disable(GL_SCISSOR_TEST);+ gl->Uniform1f(r->uScale, r->scale);+ ngl_restore_default(r);+ return 1;+ }+ ngl_bind_shader_uniforms(r, entry, 0.0f, 0.0f, 1.0f, uniformBytes, uniformLen);+ gl->ActiveTexture(GL_TEXTURE0);+ gl->BindTexture(GL_TEXTURE_2D, r->targets[srcSlot].tex);+ /* Always blend with straight-alpha-to-premultiplied (SRC_ALPHA, 1-SRC_ALPHA,+ * ONE, 1-SRC_ALPHA) so both intermediate cleared targets and the final+ * composite share premultiplied offscreen representation. */+ gl->BlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);+ gl->BindVertexArray(r->effectVao);+ gl->BindBuffer(GL_ARRAY_BUFFER, r->effectVbo);+ gl->BufferData(GL_ARRAY_BUFFER, (GLsizeiptr)sizeof(quad), quad, GL_STREAM_DRAW);+ gl->DrawArrays(GL_TRIANGLES, 0, 6);++ gl->Enable(GL_BLEND);+ gl->Disable(GL_SCISSOR_TEST);+ gl->BindTexture(GL_TEXTURE_2D, r->atlas);+ ngl_restore_default(r);+ return 1;+}
+ data/cozette.min.otb view
binary file changed (absent → 18492 bytes)
+ examples/RgfwDemo.hs view
@@ -0,0 +1,3 @@+module Main (main) where++import RgfwDemoCommon (main)
+ examples/RgfwDemoCommon.hs view
@@ -0,0 +1,457 @@+module RgfwDemoCommon+ ( Model (..)+ , appView+ , initialModel+ , main+ , physScaleFor+ , themeForChoice+ ) where++import Control.Monad (void, when)+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import qualified Data.Text as T+import NanoUI+ ( Input (..)+ , NanoUI+ , Size (..)+ , Theme+ , constVar+ , enumRadioBy+ , button+ , button'+ , checkbox+ , contextMenu+ , fillH+ , fillW+ , fixedH+ , fixedW+ , flex+ , gap+ , gridWith+ , label+ , menuHeader+ , menuItem+ , menuItemDisabled+ , menuItemShortcut+ , menuSeparator+ , padAll+ , panelWith+ , respClicked+ , rowWith+ , separator+ , slider+ , tab+ , tabBar+ , textArea'+ , textInput+ , whenM+ , floatingWindow'+ )+import NanoUI.Themes+ ( tomorrowMidnightMinDarkTheme+ , tomorrowMinLightTheme+ , tomorrowNightMinDarkTheme+ )+import NanoUI.Monad (askInput)+import NanoUI.Shortcut (cmdOrCtrl, key)+import NanoUI.Backend.Rgfw+ ( RgfwOptions (..)+ , WindowSettings (..)+ , askRgfwDebug+ , debugWindowBody+ , defaultRgfwOptions+ , defaultWindowSettings+ , emptyRgfwDebug+ , runRgfwAppReduceCustom+ )+import NanoUI.Emit qualified as Emit+import Data.Hashable (Hashable (..))++data TabChoice+ = TabControls+ | TabGallery+ | TabAbout+ | TabDiagnostics+ deriving (Bounded, Enum, Eq, Show)++instance Hashable TabChoice where+ hashWithSalt salt = hashWithSalt salt . fromEnum++data ThemeChoice+ = ThemeNight+ | ThemeLight+ | ThemeMidnight+ deriving (Bounded, Enum, Eq, Show)++data ProfileChoice+ = ProfileFast+ | ProfileBalanced+ | ProfileQuality+ deriving (Bounded, Enum, Eq, Show)++-- | In the order the scale button cycles through them.+data DpiScaleChoice+ = DpiScaleAuto+ | DpiScale1+ | DpiScale15+ | DpiScale2+ | DpiScale3+ | DpiScale05+ deriving (Bounded, Enum, Eq, Show)++formatDpiScale :: DpiScaleChoice -> Text+formatDpiScale DpiScaleAuto = "Auto (OS)"+formatDpiScale sc = T.pack (show (physScaleFor sc)) <> "x"++physScaleFor :: DpiScaleChoice -> Float+physScaleFor DpiScaleAuto = 0.0 -- 0.0 means: use the DPI reported by the OS by default+physScaleFor DpiScale05 = 0.5+physScaleFor DpiScale1 = 1.0+physScaleFor DpiScale15 = 1.5+physScaleFor DpiScale2 = 2.0+physScaleFor DpiScale3 = 3.0++data Msg+ = SetTab !TabChoice+ | CycleTheme+ | CycleScale+ | Increment+ | Decrement+ | Reset+ | ToggleTurbo !Bool+ | SetVolume !Float+ | SetOpacity !Float+ | SetInputText !Text+ | SetNotesText !Text+ | SetProfile !ProfileChoice+ | ClearNotes+ | ToggleDebug !Bool+ deriving (Eq, Show)++data Model = Model+ { activeTab :: !TabChoice+ , currentTheme :: !ThemeChoice+ , dpiScale :: !DpiScaleChoice+ , counter :: !Int+ , turboOn :: !Bool+ , volumeVal :: !Float+ , opacityVal :: !Float+ , textVal :: !Text+ , notesVal :: !Text+ , profileOpt :: !ProfileChoice+ , totalClicks :: !Int+ , debugOpen :: !Bool+ }+ deriving (Eq, Show)++initialModel :: Model+initialModel =+ Model+ { activeTab = TabControls+ , currentTheme = ThemeNight+ , dpiScale = DpiScaleAuto+ , counter = 42+ , turboOn = True+ , volumeVal = 0.72+ , opacityVal = 0.90+ , textVal = "nano-ui rgfw edition"+ , notesVal = "Edit me.\nSecond line."+ , profileOpt = ProfileBalanced+ , totalClicks = 0+ , debugOpen = False+ }++themeForChoice :: ThemeChoice -> Theme+themeForChoice ThemeNight = tomorrowNightMinDarkTheme+themeForChoice ThemeLight = tomorrowMinLightTheme+themeForChoice ThemeMidnight = tomorrowMidnightMinDarkTheme++nextEnum :: (Eq a, Enum a, Bounded a) => a -> a+nextEnum x+ | x == maxBound = minBound+ | otherwise = succ x++update :: Msg -> Model -> Model+update msg m =+ let !m' = m {totalClicks = totalClicks m + 1}+ in case msg of+ SetTab t -> m' {activeTab = t}+ CycleTheme -> m' {currentTheme = nextEnum (currentTheme m)}+ CycleScale -> m' {dpiScale = nextEnum (dpiScale m)}+ Increment -> m' {counter = counter m + 1}+ Decrement -> m' {counter = counter m - 1}+ Reset -> m' {counter = 0}+ ToggleTurbo b -> m' {turboOn = b}+ SetVolume v -> m' {volumeVal = max 0 (min 1 v)}+ SetOpacity v -> m' {opacityVal = max 0 (min 1 v)}+ SetInputText t -> m' {textVal = t}+ SetNotesText t -> m' {notesVal = t}+ SetProfile p -> m' {profileOpt = p}+ ClearNotes -> m' {notesVal = ""}+ ToggleDebug b -> m' {debugOpen = b}++appView :: Model -> Emit.NanoUIE Msg ()+appView m = do+ panelWith (padAll 12 . gap 8 . fillW . fillH) $ do+ rowWith (gap 8 . fixedH 24 . fillW) $ do+ label "nano-ui on RGFW"+ flex++ Emit.emitWhen+ ( button+ ( case currentTheme m of+ ThemeNight -> "[Theme: Tomorrow Night]"+ ThemeLight -> "[Theme: Tomorrow Light]"+ ThemeMidnight -> "[Theme: Midnight Black]"+ )+ )+ CycleTheme++ Emit.emitWhen+ (button ("[" <> formatDpiScale (dpiScale m) <> " DPI Scale]"))+ CycleScale++ Emit.emitWhen+ (button (if debugOpen m then "[Debug: ON]" else "[Debug: OFF]"))+ (ToggleDebug (not (debugOpen m)))++ Emit.emitChanged+ ( `tabBar`+ [ tab TabControls "Controls" ()+ , tab TabGallery "Unicode Gallery" ()+ , tab TabAbout "About" ()+ , tab TabDiagnostics "Diagnostics" ()+ ]+ )+ (activeTab m)+ SetTab++ separator++ case activeTab m of+ TabControls -> viewControlsTab m+ TabGallery -> viewGalleryTab+ TabAbout -> viewAboutTab+ TabDiagnostics -> viewDiagnosticsTab m++ when (debugOpen m) $ do+ snap <- fromMaybe emptyRgfwDebug <$> askRgfwDebug+ (win, _) <- floatingWindow' (constVar True) "Debug" (debugWindowBody snap)+ when (respClicked win) (Emit.emit (ToggleDebug False))++viewControlsTab :: Model -> Emit.NanoUIE Msg ()+viewControlsTab m = do+ let volPct = round (volumeVal m * 100) :: Int+ opPct = round (opacityVal m * 100) :: Int+ gridWith 2 (gap 12 . fillW . fillH) $ do+ panelWith (padAll 10 . gap 6 . fixedW 380 . fillH) $ do+ label "Controls"+ separator++ gridWith 4 (gap 6 . fixedH 22 . fillW) $ do+ label ("Counter: " <> T.pack (show (counter m)))+ Emit.emitWhen (button " +1 ") Increment+ Emit.emitWhen (button " -1 ") Decrement+ Emit.emitWhen (button " Reset ") Reset++ gridWith 1 (gap 6 . fixedH 20) $ do+ Emit.emitChanged (checkbox "Turbo mode") (turboOn m) ToggleTurbo++ gridWith 2 (gap 6 . fixedH 22) $ do+ label "Context Menu:"+ menuBtn <- button' "Right-click Me"+ void $ contextMenu menuBtn $ do+ menuHeader "Edit Actions"+ menuSeparator+ whenM+ (menuItemShortcut "Cut" (cmdOrCtrl <> key 'x'))+ (Emit.emit (SetNotesText "Cut text to clipboard"))+ whenM+ (menuItemShortcut "Copy" (cmdOrCtrl <> key 'c'))+ (Emit.emit (SetNotesText "Copied text to clipboard"))+ whenM+ (menuItemShortcut "Paste" (cmdOrCtrl <> key 'v'))+ (Emit.emit (SetNotesText "Pasted text from clipboard"))+ menuSeparator+ menuHeader "System"+ whenM (menuItem "Reset Counter") (Emit.emit Reset)+ menuItemDisabled "Disabled Command"++ gridWith 1 (gap 2) $ do+ label ("Master Volume: " <> T.pack (show volPct) <> "%")+ Emit.emitChanged (slider 0 1) (volumeVal m) SetVolume++ gridWith 1 (gap 2) $ do+ label ("Surface Opacity: " <> T.pack (show opPct) <> "%")+ Emit.emitChanged (slider 0 1) (opacityVal m) SetOpacity++ gridWith 1 (gap 2) $ do+ label "Single-line Text Input:"+ Emit.emitChanged textInput (textVal m) SetInputText++ gridWith 1 (gap 2) $ do+ gridWith 2 (gap 4 . fixedH 18) $ do+ label "Multi-line Notes Field:"+ Emit.emitWhen (button "Clear") ClearNotes+ Emit.emitEdited textArea' (notesVal m) SetNotesText++ gridWith 1 (gap 2) $ do+ label "Preset:"+ Emit.emitChanged+ ( enumRadioBy+ ( \case+ ProfileFast -> "Fast (Low Latency)"+ ProfileBalanced -> "Balanced (Standard)"+ ProfileQuality -> "Quality (High Detail)"+ )+ )+ (profileOpt m)+ SetProfile++ panelWith (padAll 10 . gap 8 . fillW . fillH) $ do+ label "State"+ separator++ gridWith 2 (gap 6) $ do+ label "Active Theme:"+ label (T.pack (show (currentTheme m)))+ let+ scText = case dpiScale m of+ DpiScaleAuto -> "Auto (OS reported)"+ sc ->+ formatDpiScale sc <> " (" <> T.pack (show (physScaleFor sc)) <> "x)"+ label "DPI Scale:"+ label scText+ label "Counter Value:"+ label (T.pack (show (counter m)))+ label "Turbo Mode:"+ label (if turboOn m then "[ENABLED]" else "[DISABLED]")+ label "Volume Slider:"+ label (T.pack (show volPct) <> "%")+ label "Opacity Slider:"+ label (T.pack (show opPct) <> "%")+ label "Profile Selected:"+ label (T.pack (show (profileOpt m)))+ label "Text Input:"+ label (textVal m)+ label "Total Clicks:"+ label (T.pack (show (totalClicks m)))++ separator++ label "Block-character bars:"+ gridWith 2 (gap 4) $ do+ let+ makeBar pct =+ let+ filled = max 0 (min 20 (pct `div` 5))+ empty = 20 - filled+ in+ T.replicate filled "█" <> T.replicate empty "░"+ label "Master Volume:"+ label ("[" <> makeBar volPct <> "] " <> T.pack (show volPct) <> "%")+ label "Surface Opacity:"+ label ("[" <> makeBar opPct <> "] " <> T.pack (show opPct) <> "%")++-- | A sample of the glyphs in the bundled Cozette font.+viewGalleryTab :: NanoUI ()+viewGalleryTab = do+ panelWith (padAll 10 . gap 8 . fillW . fillH) $ do+ label "Cozette glyphs"+ separator++ gridWith 1 (gap 8) $ do+ gridWith 1 (gap 2) $ do+ label "Printable ASCII:"+ label "!\"#$%&'()*+,-./0123456789:;<=>?"+ label "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_"+ label "`abcdefghijklmnopqrstuvwxyz{|}~"++ separator++ gridWith 1 (gap 2) $ do+ label "Greek:"+ label "Δ Ω Σ α β γ δ ε θ λ μ π ρ τ ω"++ gridWith 1 (gap 2) $ do+ label "Math and logic:"+ label "± × ÷ √ ∞ ≤ ≥ ≠ ≈ ≡ ∀ ∃ ∈ ∉ ∧ ∨ ∂ ∇"++ gridWith 1 (gap 2) $ do+ label "Box drawing:"+ label "┌───┬───┐ ╔═══╦═══╗ ┏━━━┳━━━┓"+ label "│ A │ B │ ║ X ║ Y ║ ┃ 1 ┃ 2 ┃"+ label "├───┼───┤ ╠═══╬═══╣ ┣━━━╋━━━┫"+ label "│ C │ D │ ║ Z ║ W ║ ┃ 3 ┃ 4 ┃"+ label "└───┴───┘ ╚═══╩═══╝ ┗━━━┻━━━┛"++ gridWith 1 (gap 2) $ do+ label "Blocks and shades:"+ label "█ ▓ ▒ ░ ▀ ▄ ▌ ▐ ▖ ▗ ▘ ▙ ▚ ▛ ▜ ▝ ▞ ▟"++ gridWith 1 (gap 2) $ do+ label "Keys:"+ label "⏎ Enter ⇥ Tab ⌃ Ctrl ⌥ Alt ⌘ Cmd ⌫ Bksp ⎋ Esc"++ separator++ gridWith 1 (gap 4) $ do+ label "Icon buttons:"+ gridWith 4 (gap 4 . fixedH 24 . fillW) $+ mapM_+ (void . button)+ [ "\xF002 Search", "\xF004 Health", "\xF005 Star", "\xF00C Check"+ , "\xF00D Close", "\xF013 Settings", "\xF01E Reload", "\xF026 Mute"+ , "\xF028 Sound", "\xF04B Play", "\xF04C Pause", "\xF04D Stop"+ , "\xF188 Debug", "\xF11B Gamepad", "⏎ Enter", "⎋ Esc"+ ]++viewAboutTab :: NanoUI ()+viewAboutTab =+ panelWith (padAll 10 . gap 8 . fillW . fillH) $ do+ label "About"+ separator+ label "Text uses the bundled Cozette bitmap font, so no font files are needed."+ label "Themes are made square: corner radius 0 and 1px borders, so drawn boxes match hit boxes."+ label "The scale button cycles Auto, 1x, 1.5x, 2x, 3x and 0.5x; Auto follows the monitor."++viewDiagnosticsTab :: Model -> Emit.NanoUIE Msg ()+viewDiagnosticsTab m = do+ Size w h <- inputWindowSize <$> askInput+ panelWith (padAll 10 . gap 8 . fillW . fillH) $ do+ label "Diagnostics"+ separator++ gridWith 2 (gap 4) $ do+ label "Window:"+ label+ ( T.pack (show (round w :: Int))+ <> " x "+ <> T.pack (show (round h :: Int))+ <> " logical px"+ )+ label "Scale:"+ label (formatDpiScale (dpiScale m))+ label "Renderer:"+ label "OpenGL 3.2 core"+ label "Active Tab:"+ label (T.pack (show (activeTab m)))+ label "Current Theme:"+ label (T.pack (show (currentTheme m)))+ label "Interaction Clicks:"+ label (T.pack (show (totalClicks m)))++ separator++ Emit.emitWhen+ (button (if debugOpen m then "[Close Debug Window]" else "[Open Debug Window]"))+ (ToggleDebug (not (debugOpen m)))++main :: IO ()+main = do+ let opts =+ defaultRgfwOptions+ { optWindow = defaultWindowSettings {wsTitle = "nano-ui RGFW demo"}+ }+ runRgfwAppReduceCustom opts (\m -> (themeForChoice (currentTheme m), physScaleFor (dpiScale m))) update initialModel appView
+ examples/RgfwProfile.hs view
@@ -0,0 +1,234 @@+-- | Frame loop of the RGFW demo on the OpenGL path, in a hidden window: prints+-- the mean wall time and allocation of each workload, and can be profiled+-- with +RTS -p.+module Main (main) where++import Control.Exception (bracket)+import Control.Monad (forM_, unless, void, when)+import qualified Data.ByteString as BS+import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)+import qualified Data.Text as T+import NanoUI+ ( AlignX (..)+ , AlignY (..)+ , FontWeight (..)+ , Input (..)+ , NanoUI+ , Rect (..)+ , Size (..)+ , TextFont (..)+ , V2 (..)+ , Var+ , box+ , canvas+ , colorRGBA+ , columnWith+ , defaultTextFont+ , drawText+ , drawTextWith+ , fillH+ , fillW+ , fixedH+ , fixedWH+ , flex+ , gap+ , inlineText+ , label+ , newVar+ , readVar+ , richText+ , rowWith+ , strong+ , tight+ , writeVarIO+ )+import NanoUI.Backend (Damage (..), emptyInput)+import NanoUI.Testing (ctxPaintFull, collectRasterSpans, damageIsEmpty, runFrame, takeDamage, takeDamagePieces)+import NanoUI.Testing.Harness (measureRuns)+import NanoUI.Emit (runNanoUIE)+import NanoUI.Rgfw.Internal.Context (newRgfwContext)+import NanoUI.Rgfw.Internal.Font.Cozette (getCozetteFont)+import NanoUI.Rgfw.Internal.Gl (freeGlRenderer, newGlRenderer, readRetainedPixels, renderArenaGl)+import qualified RGFW as R+import RgfwDemoCommon (Model (..), currentTheme, dpiScale, initialModel, physScaleFor, themeForChoice)+import RgfwDemoCommon qualified as Demo++iterations :: Int+iterations = 500++physW, physH :: Int+physW = 1680+physH = 1040++-- | Mean wall time and allocation per run after a short warmup.+measure :: String -> IO () -> IO ()+measure = measureRuns 20 iterations++main :: IO ()+main = do+ let appView model = void (runNanoUIE (Demo.appView model))+ m = initialModel+ theme = themeForChoice (currentTheme m)+ userScale = physScaleFor (dpiScale m)+ !scale = if userScale > 0.0 then userScale else 1.0+ !logW = max 1 (round (fromIntegral physW / scale) :: Int)+ !logH = max 1 (round (fromIntegral physH / scale) :: Int)+ inp =+ emptyInput+ { inputWindowSize = Size (fromIntegral logW) (fromIntegral logH)+ , inputMousePos = V2 400 300+ }+ bracket+ (R.createWindowGL "nano-ui-rgfw-profile" 0 0 physW physH R.rgfw_windowHide 3 2)+ (mapM_ R.closeWindow) $ \case+ Nothing -> fail "Failed to create a hidden RGFW window with an OpenGL 3.2 context."+ Just win -> bracket newGlRenderer freeGlRenderer $ \renderer -> do+ -- As the runner draws a frame: a forced frame paints in full, and+ -- any other paints only its damage.+ -- Returns whether the frame drew anything.+ let present ctx force frameInp view = do+ writeIORef (ctxPaintFull ctx) force+ (_, draw, _) <- runFrame ctx frameInp view+ damage <- takeDamage ctx+ let drawn = force || not (damageIsEmpty damage)+ when drawn $ do+ (baseSpans, overlaySpans) <- collectRasterSpans ctx frameInp+ pieces <- if force then pure [] else takeDamagePieces ctx+ renderArenaGl renderer getCozetteFont scale physW physH+ (if force then DamageFull else damage) pieces draw baseSpans overlaySpans+ R.swapBuffersGL win+ pure drawn+ -- Partial frames 16 ms apart until nothing changes, so hover+ -- fades finish, then the same state painted in full must give+ -- the same pixels.+ check name ctx frameInp view = do+ let settle :: Int -> IO ()+ settle n = do+ drawn <- present ctx False frameInp {inputDeltaTime = 0.016} view+ when drawn $+ if n < 200 then settle (n + 1) else fail ("never settled: " ++ name)+ settle (0 :: Int)+ partial <- readRetainedPixels renderer physW physH+ _ <- present ctx True frameInp view+ full <- readRetainedPixels renderer physW physH+ unless (partial == full) $+ fail ("partial repaint differs from a full one: " ++ name ++ ", "+ ++ show (length (filter id (BS.zipWith (/=) partial full))) ++ " bytes")+ fresh = do+ ctx <- newRgfwContext theme+ _ <- present ctx True inp (appView m)+ pure ctx+ ctxFull <- fresh+ measure "Demo, forced full" (void (present ctxFull True inp (appView m)))+ ctxHover <- fresh+ hoverRef <- newIORef (0 :: Int)+ measure "Demo, hover sweep" $ do+ k <- tick hoverRef+ -- Down the left column, where each step crosses a widget edge.+ void (present ctxHover False inp {inputMousePos = V2 120 (fromIntegral (60 + k `mod` 500))} (appView m))+ ctxCount <- fresh+ countRef <- newIORef (0 :: Int)+ measure "Demo, counter changes" $ do+ k <- tick countRef+ void (present ctxCount False inp (appView m {counter = k}))+ ctxFar <- fresh+ farRef <- newIORef (0 :: Int)+ measure "Demo, counter + far hover" $ do+ k <- tick farRef+ void $ present ctxFar False inp {inputMousePos = V2 (fromIntegral (logW - 60)) (fromIntegral (logH - 40 - k `mod` 2 * 20))} (appView m {counter = k})+ -- The bound: a window full of text, where every glyph is a quad.+ ctxWall <- newRgfwContext theme+ _ <- present ctxWall True inp (textWall 0)+ measure "Text wall, forced full" (void (present ctxWall True inp (textWall 0)))+ wallRef <- newIORef (0 :: Int)+ measure "Text wall, counter changes" $ do+ k <- tick wallRef+ void (present ctxWall False inp (textWall k))+ -- Two small changes in opposite corners, whose bounding box is most+ -- of the window.+ ctxCorners <- newRgfwContext theme+ _ <- present ctxCorners True inp (textCorners 0)+ cornersRef <- newIORef (0 :: Int)+ measure "Text wall, corner counters" $ do+ k <- tick cornersRef+ void (present ctxCorners False inp (textCorners k))+ -- Text in drawings, which the paint records as spans.+ ctxDrawn <- newRgfwContext theme+ _ <- present ctxDrawn True inp (drawingText 0)+ measure "Drawing text, forced full" (void (present ctxDrawn True inp (drawingText 0)))+ drawnRef <- newIORef (0 :: Int)+ measure "Drawing text, counter changes" $ do+ k <- tick drawnRef+ void (present ctxDrawn False inp (drawingText k))+ ctxCheck <- fresh+ forM_ [60, 90 .. 700 :: Int] $ \y ->+ check ("hover at y=" ++ show y) ctxCheck inp {inputMousePos = V2 120 (fromIntegral y)} (appView m)+ forM_ [1 .. 5 :: Int] $ \k ->+ check ("counter " ++ show k) ctxCheck inp (appView m {counter = k})+ forM_ [1 .. 3 :: Int] $ \k -> check ("text wall " ++ show k) ctxWall inp (textWall k)+ forM_ [1 .. 3 :: Int] $ \k -> check ("corners " ++ show k) ctxCorners inp (textCorners k)+ -- Other contexts drew since: start from this one's own pixels.+ _ <- present ctxDrawn True inp (drawingText 0)+ forM_ [1 .. 3 :: Int] $ \k -> check ("drawing text " ++ show k) ctxDrawn inp (drawingText k)+ forM_ [40, 140 .. 440 :: Int] $ \y ->+ check ("drawing text, hover at y=" ++ show y) ctxDrawn inp {inputMousePos = V2 120 (fromIntegral y)} (drawingText 3)+ -- Model state the view reads from a Var, written between frames: a+ -- counter label, and a box whose colour changes at an unchanged rect.+ countVar <- newVar (0 :: Int)+ ctxVar <- newRgfwContext theme+ _ <- present ctxVar True inp (varView countVar)+ forM_ [1 .. 5 :: Int] $ \k -> do+ writeVarIO countVar k+ check ("var counter " ++ show k) ctxVar inp (varView countVar)+ putStrLn "partial repaints match full ones"+ putStrLn ("profiled RGFW demo frames at " ++ show physW ++ "x" ++ show physH)+ where+ tick :: IORef Int -> IO Int+ tick ref = readIORef ref <* modifyIORef' ref (+ 1)++-- | A counter over enough wrapped paragraphs to fill the window.+textWall :: Int -> NanoUI ()+textWall k = columnWith (tight . gap 4 . fillW) $ do+ label (T.pack ("frame " <> show k))+ forM_ paragraphs label++-- | The text wall with a second counter in the bottom-right corner.+textCorners :: Int -> NanoUI ()+textCorners k = columnWith (tight . gap 4 . fillW . fillH) $ do+ textWall k+ flex+ rowWith (tight . fillW) $ do+ flex+ label (T.pack ("frame " <> show k))++-- | A counter in a canvas of labels, plain and bold, over rich text+-- paragraphs: all of it drawing text.+drawingText :: Int -> NanoUI ()+drawingText k = columnWith (tight . gap 4 . fillW) $ do+ void $ canvas (fillW . fixedH 200) $ \(Rect x y w _) ->+ forM_ [0 .. 11 :: Int] $ \r -> forM_ [0 .. 5 :: Int] $ \c -> do+ let at = V2 (x + fromIntegral c * w / 6) (y + fromIntegral r * 16)+ txt = T.pack (if r + c == 0 then "frame " <> show k else "cell " <> show (r * 6 + c))+ if even (r + c)+ then drawText at AlignStart AlignTop txt ink+ else drawTextWith defaultTextFont {textFontWeight = WeightBold} at AlignStart AlignTop txt ink+ forM_ (take 8 paragraphs) $ \p -> richText [inlineText p, strong " and bold"]+ where+ ink = colorRGBA 0xC5 0xC8 0xC6 255++-- | A counter label and a coloured box that follow a Var, above text that+-- does not.+varView :: Var Int -> NanoUI ()+varView v = columnWith (tight . gap 4 . fillW) $ do+ k <- readVar v+ label (T.pack ("count " <> show k))+ box (fixedWH 80 40) (colorRGBA (fromIntegral ((k * 70) `mod` 256)) 90 140 255)+ forM_ (take 4 paragraphs) label++paragraphs :: [T.Text]+paragraphs =+ [ T.unwords [ws !! ((i * 7 + j * 3) `mod` length ws) | j <- [0 .. 119 :: Int]]+ | i <- [1 .. 16 :: Int]+ ]+ where+ ws = T.words "the quick brown fox jumps over a lazy dog while seven wizards quietly hex bold nymphs and pack my box with five dozen liquor jugs"
+ lib/NanoUI/Backend/Rgfw.hs view
@@ -0,0 +1,62 @@+-- |+-- Module : NanoUI.Backend.Rgfw+-- Description : RGFW and OpenGL 3.2 backend for nano-ui+-- Copyright : (c) 2026 Zachary Churchill+-- License : MIT+-- Maintainer : zacharyachurchill@gmail.com+--+-- Run nano-ui views in an RGFW window with OpenGL 3.2 and the bundled+-- Cozette bitmap font. 'runRgfwApp' runs a view; 'runRgfwAppReduce' runs a+-- view against a model and an update function for "NanoUI.Emit".+module NanoUI.Backend.Rgfw+ ( -- * Running+ runRgfwApp+ , runRgfwAppWith+ , runRgfwAppReduce+ , runRgfwAppReduceCustom+ , runRgfwAppReduceCustomWith++ -- * Options and window settings+ , RgfwOptions (..)+ , defaultRgfwOptions+ , WindowSettings (..)+ , defaultWindowSettings+ , WindowPosition (..)+ , WindowMode (..)++ -- * Low-level context+ , newRgfwContext+ , applyRgfwTheme++ -- * Debugging+ , RgfwDebugSampler+ , newRgfwDebugSampler+ , RgfwDebugSnapshot (..)+ , CoreDebugSnapshot (..)+ , RgfwFrameStats (..)+ , askRgfwDebug+ , debugWindowBody+ , emptyRgfwDebug+ ) where++import NanoUI (WindowMode (..), WindowPosition (..), WindowSettings (..), defaultWindowSettings)+import NanoUI.Internal.Debug (CoreDebugSnapshot (..))+import NanoUI.Rgfw.Internal.Context (applyRgfwTheme, newRgfwContext)+import NanoUI.Rgfw.Internal.Debug+ ( RgfwDebugSnapshot (..)+ , RgfwFrameStats (..)+ , RgfwDebugSampler+ , newRgfwDebugSampler+ , askRgfwDebug+ , debugWindowBody+ , emptyRgfwDebug+ )+import NanoUI.Rgfw.Internal.Session+ ( RgfwOptions (..)+ , defaultRgfwOptions+ , runRgfwApp+ , runRgfwAppWith+ , runRgfwAppReduce+ , runRgfwAppReduceCustom+ , runRgfwAppReduceCustomWith+ )
+ lib/NanoUI/Rgfw/Internal/Context.hs view
@@ -0,0 +1,77 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | Context setup for RGFW: Cozette metrics, square geometry, text drawn+-- from spans, and square themes.+module NanoUI.Rgfw.Internal.Context+ ( newRgfwContext+ , applyRgfwTheme+ , TextSpan+ , paintInLayerOrder+ ) where++import Data.Text (Text)+import NanoUI (Color, Rect, ShaderCapabilities (..), Theme, borderWidth, cornerRadius, everyStyle)+import NanoUI.Backend (Layer (..), measureTextIO, newPixelContext, setShaderCapabilities)+import NanoUI.Internal.Context+ ( Context+ , setDrawExternalText+ , setDrawSquareGeometry+ , setTheme+ , withFontMetrics+ , withFontResolver+ , withMonoFontMetrics+ )+import NanoUI.Rgfw.Internal.Font.Cozette (cozetteMetrics)++-- | Pixel context configured for RGFW: Cozette metrics, square geometry+-- (every primitive reaches the renderer as a flat quad or triangle), text+-- left to the span stamper, and the given theme made square+-- ('applyRgfwTheme'). Sessions, tests and profiles share it so they render+-- the same frame.+--+-- The span stamper draws every span in Cozette's one 6x13 cell, so text of+-- every size and face, monospace included, is laid out in that cell: font+-- sizes change nothing here. Text in drawings and canvases (rich text,+-- Markdown, chart labels) reaches it as spans too, one per line, which+-- 'NanoUI.Testing.collectRasterSpans' returns after the widget text.+newRgfwContext :: Theme -> IO Context+newRgfwContext theme = do+ ctx0 <- newPixelContext+ -- The resolver goes last: the metric setters reinstall the default one,+ -- which scales the metrics to the size asked for.+ let ctx =+ withFontResolver+ (withMonoFontMetrics (withFontMetrics ctx0 cozetteMetrics) cozetteMetrics)+ (\_ _ _ _ -> pure (cozetteMetrics, False))+ (\_ _ _ _ -> measureTextIO cozetteMetrics)+ setDrawSquareGeometry ctx True+ setDrawExternalText ctx True+ setShaderCapabilities ctx (ShaderCapabilities True True)+ applyRgfwTheme ctx theme+ pure ctx++-- | Switch to a theme with every surface square: corner radius 0 and a 1px+-- border, so geometry matches hit boxes. A no-op when it is unchanged;+-- otherwise caches are dropped and the context is marked dirty.+applyRgfwTheme :: Context -> Theme -> IO ()+applyRgfwTheme ctx = setTheme ctx . everyStyle (cornerRadius 0 . borderWidth 1)++-- | A collected text span (see 'NanoUI.Testing.collectRasterSpans'): rect,+-- text, foreground, background, and clip, in logical pixels.+type TextSpan = (Rect, Text, Color, Color, Rect)++-- | The paint order the OpenGL renderer and the test suite's software+-- rasteriser follow: background and content+-- geometry, base text spans (after content, so scroll tracks cannot erase box+-- rules), overlay geometry, floating chrome (window scrollbars), then overlay+-- text spans. Each text list holds drawing text too, the page's in the base+-- spans and floating panels' in the overlay ones, so it is drawn above+-- every shape of its layer, including its own drawing's later shapes.+paintInLayerOrder :: (Layer -> IO ()) -> IO () -> IO () -> IO ()+paintInLayerOrder geometry baseText overlayText = do+ geometry LayerBackground+ geometry LayerContent+ baseText+ geometry LayerOverlay+ geometry LayerChrome+ overlayText
+ lib/NanoUI/Rgfw/Internal/Debug.hs view
@@ -0,0 +1,184 @@+{-# LANGUAGE TypeFamilies #-}+{-# OPTIONS_HADDOCK not-home #-}+-- The 'BackendSession' instance for the RGFW session is an orphan by+-- construction: the core owns the backend kind, and this package owns its+-- session type.+{-# OPTIONS_GHC -Wno-orphans #-}++-- | RGFW frame statistics and the debug window body that shows them with the+-- core debug rows and the layout overlay toggle.+module NanoUI.Rgfw.Internal.Debug+ ( RgfwDebugSnapshot (..)+ , RgfwFrameStats (..)+ , RgfwDebugSampler (..)+ , newRgfwDebugSampler+ , rgfwSession+ , emptyRgfwDebug+ , askRgfwDebug+ , debugWindowBody+ ) where++import Control.Monad (when)+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.Text (Text)+import qualified Data.Text as T+import GHC.TypeLits (symbolSing)+import Text.Printf (printf)++import NanoUI+ ( NanoUI+ , Size (..)+ , V2 (..)+ , checkbox+ , explainLayout+ , explainedNode+ , explainingLayout+ , heading+ , inputMousePos+ , inputWindowSize+ , kvBlock+ , scope+ , separator+ , liftIO+ , withValue+ )+import NanoUI.Backend (Backend (..), BackendSession, SBackend (..), askBackendSession)+import NanoUI.Internal.Monad (askInput)+import NanoUI.Internal.Debug+ ( CoreDebugSnapshot (..)+ , DebugSamplerRef+ , emptyCoreDebugSnapshot+ , formatDrawRows+ , formatExplainRows+ , formatFpsRows+ , newDebugSampler+ , refreshDebugSnapshot+ )+import NanoUI.Rgfw.Internal.Font.Cozette (CozetteScalePath (..), cozetteScalePath)++-- | RGFW-specific facts about the last presented frame.+data RgfwFrameStats = RgfwFrameStats+ { fsNodes :: !Int+ , fsPhysW :: !Int+ , fsPhysH :: !Int+ , fsScale :: !Float -- ^ active logical -> physical scale+ , fsMonScale :: !Float -- ^ monitor-reported scale+ }+ deriving (Eq, Show)++-- | Published core timings and RGFW physical-frame statistics.+data RgfwDebugSnapshot = RgfwDebugSnapshot+ { dbgCore :: !CoreDebugSnapshot+ , dbgFrame :: !RgfwFrameStats+ }+ deriving (Eq, Show)++-- | The core sampler and the latest frame stats.+data RgfwDebugSampler = RgfwDebugSampler+ { rdsSampler :: !DebugSamplerRef+ , rdsFrame :: !(IORef RgfwFrameStats)+ , rdsPublished :: !(IORef (Maybe RgfwDebugSnapshot))+ , rdsRows :: !(IORef (Maybe RgfwDebugRows))+ }++-- | An RGFW session keeps its debug sampler on the context, so views read+-- it without taking a handle.+type instance BackendSession ('Custom "rgfw") = RgfwDebugSampler++-- | The RGFW session's backend, for 'NanoUI.Backend.withBackendSession'.+rgfwSession :: SBackend ('Custom "rgfw")+rgfwSession = SCustom symbolSing++-- | Allocate a sampler with empty timing and frame stats. The runners make+-- their own and keep it on the context; a custom loop feeds this one and+-- installs it with @'NanoUI.Backend.withBackendSession' ctx 'rgfwSession'@+-- for 'askRgfwDebug' to find. The sampler's fields and 'rgfwSession' are+-- in "NanoUI.Rgfw.Internal.Debug".+newRgfwDebugSampler :: IO RgfwDebugSampler+newRgfwDebugSampler =+ RgfwDebugSampler+ <$> newDebugSampler+ <*> newIORef (dbgFrame emptyRgfwDebug)+ <*> newIORef Nothing+ <*> newIORef Nothing++-- | Placeholder with zero counts and unit scale before measurements exist.+emptyRgfwDebug :: RgfwDebugSnapshot+emptyRgfwDebug =+ RgfwDebugSnapshot+ { dbgCore = emptyCoreDebugSnapshot+ , dbgFrame = RgfwFrameStats {fsNodes = 0, fsPhysW = 0, fsPhysH = 0, fsScale = 1, fsMonScale = 1}+ }++-- | Read the RGFW session's debug data, refreshing at most four times per+-- second. Queries keep the session's debug refresh active. 'Nothing' when no+-- RGFW session drives the view, such as in headless tests.+askRgfwDebug :: NanoUI (Maybe RgfwDebugSnapshot)+askRgfwDebug = askBackendSession rgfwSession >>= traverse snapshot+ where+ snapshot s = do+ inp <- askInput+ liftIO $ refreshDebugSnapshot (rdsSampler s) (rdsPublished s) $ \core -> do+ let Size lw lh = inputWindowSize inp+ V2 mx my = inputMousePos inp+ frame <- readIORef (rdsFrame s)+ pure RgfwDebugSnapshot {dbgCore = core {dbgWinW = lw, dbgWinH = lh, dbgMouseX = mx, dbgMouseY = my}, dbgFrame = frame}++-- | Arena nodes plus the draw buffer sizes.+layoutRows :: RgfwDebugSnapshot -> Rows+layoutRows s = ("nodes", T.pack (show (fsNodes (dbgFrame s)))) : formatDrawRows (dbgCore s)++displayRows :: RgfwDebugSnapshot -> Rows+displayRows s =+ [ ("logical win", T.pack (printf "%.0fx%.0f" (dbgWinW c) (dbgWinH c)))+ , ("physical win", T.pack (printf "%dx%d" (fsPhysW f) (fsPhysH f)))+ , ("scale active", T.pack (printf "%.2fx" (fsScale f)))+ , ("scale monitor", T.pack (printf "%.2fx" (fsMonScale f)))+ , ("glyph path", glyphPath)+ , ("mouse pos", T.pack (printf "%.0f, %.0f" (dbgMouseX c) (dbgMouseY c)))+ ]+ where+ c = dbgCore s+ f = dbgFrame s+ glyphPath = case cozetteScalePath (fsScale f) of+ ScaleExact1x -> "1x bitmap"+ ScaleExact2x -> "2x EPX bitmap"+ ScaleExact4x -> "4x EPX bitmap"+ ScaleBoxFrom2x -> "box-averaged 2x EPX"+ ScaleBoxFrom4x -> "box-averaged 4x EPX"++-- | The readout's formatted rows with the snapshot they show. The snapshot+-- refreshes at 4 Hz, so rows are formatted once per refresh, not every frame.+data RgfwDebugRows = RgfwDebugRows !RgfwDebugSnapshot !(Rows, Rows, Rows, Rows)++type Rows = [(Text, Text)]++-- | Draw timing, geometry, display, and RTS rows for a snapshot, plus a+-- layout overlay checkbox that, when on, shows the node under the pointer.+-- Place this inside a window or panel; it creates no container.+debugWindowBody :: RgfwDebugSnapshot -> NanoUI ()+debugWindowBody snap = do+ owner <- askBackendSession rgfwSession+ (fps, layout, display, rts) <- liftIO $ do+ cached <- maybe (pure Nothing) (readIORef . rdsRows) owner+ case cached of+ Just (RgfwDebugRows shown rows) | shown == snap -> pure rows+ _ -> do+ let rows = (formatFpsRows (dbgCore snap), layoutRows snap, displayRows snap, dbgRts (dbgCore snap))+ mapM_ (\o -> writeIORef (rdsRows o) (Just (RgfwDebugRows snap rows))) owner+ pure rows+ heading "Frame"+ kvBlock fps+ separator+ heading "Layout & Draw"+ kvBlock layout+ on <- explainingLayout+ (_, explain) <- withValue on (checkbox "Outline layout nodes")+ explainLayout explain+ scope $ when explain (kvBlock . formatExplainRows =<< explainedNode)+ separator+ heading "Display & Scale"+ kvBlock display+ separator+ heading "RTS Runtime"+ kvBlock rts
+ lib/NanoUI/Rgfw/Internal/Font/Cozette.hs view
@@ -0,0 +1,427 @@+{-# LANGUAGE TemplateHaskell #-}+{-# OPTIONS_HADDOCK not-home #-}++-- | The bundled Cozette bitmap font: glyph lookup, metrics, and glyph bitmaps+-- at 1x, 2x and 4x (EPX-scaled), box-averaged for other scales.+module NanoUI.Rgfw.Internal.Font.Cozette+ ( CozetteFont (..)+ , getCozetteFont+ , cozetteMetrics+ , cozetteCharAdvance+ , cozetteLineHeight+ , cozetteAscent+ , cozetteGlyphWidth+ , cozetteGlyphHeight+ , CozetteScalePath (..)+ , cozetteScalePath+ , cozetteGlyphFootprint+ , charToGlyphId+ , cozetteGlyphBit+ , renderGlyphScaledToBuffer+ , foldPenPositions+ ) where++import Control.Monad (forM_, when)+import Control.Monad.ST (ST, runST)+import Data.Bits (Bits, setBit, shiftL, shiftR, testBit, (.&.), (.|.))+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import Data.Char (ord)+import Data.FileEmbed (embedFileRelative)+import Data.Primitive.PrimArray+ ( PrimArray+ , indexPrimArray+ , primArrayFromList+ , sizeofPrimArray+ , newPrimArray+ , unsafeFreezePrimArray+ , writePrimArray+ )+import Data.Primitive.Types (Prim)+import Data.Text (Text)+import qualified Data.Text as T+import Data.Word (Word16, Word32, Word8)+import Foreign.Ptr (Ptr)+import Foreign.Storable (peekElemOff, pokeElemOff)+import NanoUI.Backend (FontMetrics (..), roundHalfUp)++-- | Horizontal character advance: 6 logical pixels at unit scale.+cozetteCharAdvance :: Float+cozetteCharAdvance = 6.0++-- | Line spacing: 13 logical pixels at unit scale.+cozetteLineHeight :: Float+cozetteLineHeight = 13.0++-- | Baseline offset from the line top: 10 logical pixels.+cozetteAscent :: Float+cozetteAscent = 10.0++-- | Bitmap width in native font pixels, including overhang beyond the advance.+cozetteGlyphWidth :: Int+cozetteGlyphWidth = 7++-- | Bitmap height in native font pixels.+cozetteGlyphHeight :: Int+cozetteGlyphHeight = 13++-- | Parsed character map and glyph bitmaps at 1x, 2x, and 4x scales.+-- Use 'getCozetteFont' for the bundled font.+data CozetteFont = CozetteFont+ { cfNumGlyphs :: {-# UNPACK #-} !Int+ , cfGroups :: !(PrimArray Word32) -- start, end, glyph: three a group+ , cfGlyphData1x :: !(PrimArray Word8) -- 921 * 13 bytes of row-unpacked Word8s (1 byte per row)+ , cfGlyphData2x :: !(PrimArray Word16) -- 921 * 26 Word16s (14 bits per row, 26 rows per glyph)+ , cfGlyphData4x :: !(PrimArray Word32) -- 921 * 52 Word32s (28 bits per row, 52 rows per glyph)+ }++{-# NOINLINE embeddedFontBytes #-}+embeddedFontBytes :: ByteString+embeddedFontBytes = $(embedFileRelative "data/cozette.min.otb")++-- | Shared parsed copy of the embedded Cozette font. No filesystem lookup is needed.+{-# NOINLINE getCozetteFont #-}+getCozetteFont :: CozetteFont+getCozetteFont = parseCozette embeddedFontBytes++{-# INLINE parseWord16 #-}+parseWord16 :: ByteString -> Int -> Word32+parseWord16 bs off =+ let !b0 = fromIntegral (BS.index bs off)+ !b1 = fromIntegral (BS.index bs (off + 1))+ in (b0 `Data.Bits.shiftL` 8) .|. b1++{-# INLINE parseWord32 #-}+parseWord32 :: ByteString -> Int -> Word32+parseWord32 bs off =+ let !b0 = fromIntegral (BS.index bs off)+ !b1 = fromIntegral (BS.index bs (off + 1))+ !b2 = fromIntegral (BS.index bs (off + 2))+ !b3 = fromIntegral (BS.index bs (off + 3))+ in (b0 `Data.Bits.shiftL` 24)+ .|. (b1 `Data.Bits.shiftL` 16)+ .|. (b2 `Data.Bits.shiftL` 8)+ .|. b3++parseCozette :: ByteString -> CozetteFont+parseCozette bs = runST $ do+ -- Parse SFNT table directory+ let numTables = fromIntegral (parseWord16 bs 4)+ findTable tag i+ | i >= numTables = (0 :: Int, 0 :: Int)+ | otherwise =+ let off = 12 + i * 16+ tTag = BS.take 4 (BS.drop off bs)+ tOff = fromIntegral (parseWord32 bs (off + 8))+ tLen = fromIntegral (parseWord32 bs (off + 12))+ in if tTag == tag+ then (tOff, tLen)+ else findTable tag (i + 1)+ (cmapOff, _) = findTable "cmap" 0+ (ebdtOff, _) = findTable "EBDT" 0+ (eblcOff, _) = findTable "EBLC" 0++ -- Parse cmap format 12+ let subOff = fromIntegral (parseWord32 bs (cmapOff + 8))+ fmt12Off = cmapOff + subOff+ nGroups = fromIntegral (parseWord32 bs (fmt12Off + 12))+ groups =+ [ let gOff = fmt12Off + 16 + g * 12+ s = parseWord32 bs gOff+ e = parseWord32 bs (gOff + 4)+ gid = parseWord32 bs (gOff + 8)+ in (s, e, gid)+ | g <- [0 .. nGroups - 1]+ ]++ -- Parse EBLC subtable for glyph offsets+ let subArrayOff = fromIntegral (parseWord32 bs (eblcOff + 8))+ addOff = fromIntegral (parseWord32 bs (eblcOff + subArrayOff + 4))+ stOff = eblcOff + subArrayOff + addOff+ lastGlyph = fromIntegral (parseWord16 bs (eblcOff + subArrayOff + 2))+ numGlyphs = lastGlyph + 1+ imgDataOff = fromIntegral (parseWord32 bs (stOff + 4))++ -- Unpack each glyph's 7x13 bitmap (bits packed MSB first, rows back to+ -- back, the image possibly shorter than 12 bytes) into one byte per row.+ rows1x <- newPrimArray (numGlyphs * 13)+ forM_ [0 .. numGlyphs - 1] $ \g -> do+ let off1 = fromIntegral (parseWord32 bs (stOff + 8 + g * 4))+ off2 = fromIntegral (parseWord32 bs (stOff + 8 + (g + 1) * 4))+ src = ebdtOff + imgDataOff + off1+ packedBit i =+ let b = i `shiftR` 3+ in b < off2 - off1 && testBit (BS.index bs (src + b)) (7 - i .&. 7)+ row r = foldl' (\acc c -> if packedBit (r * 7 + c) then setBit acc (7 - c) else acc) 0 [0 .. 6]+ forM_ [0 .. 12] $ \r -> writePrimArray rows1x (g * 13 + r) (row r :: Word8)+ frozen1x <- unsafeFreezePrimArray rows1x+ frozen2x <- buildEpxTable numGlyphs 7 13 15 (rowBit frozen1x 7 13 7)+ frozen4x <- buildEpxTable numGlyphs 14 26 31 (rowBit frozen2x 14 26 15)+ pure $ CozetteFont numGlyphs (primArrayFromList (concat [[start, end, glyph] | (start, end, glyph) <- groups])) frozen1x frozen2x frozen4x++-- | The EPX (Scale2x) rule: the 2x2 block replacing pixel @e@, given its+-- neighbours above (@b@), left (@d@), right (@f@) and below (@h@), as+-- (top-left, top-right, bottom-left, bottom-right).+{-# INLINE epx #-}+epx :: Eq a => a -> a -> a -> a -> a -> (a, a, a, a)+epx b d e f h+ | b /= h && d /= f =+ ( if d == b then d else e+ , if b == f then f else e+ , if d == h then d else e+ , if h == f then f else e+ )+ | otherwise = (e, e, e, e)++-- | EPX-double every glyph of a table: @srcW@ x @srcH@ source bits per glyph+-- (@bitAt gid col row@, unset outside the glyph) become 2 * @srcH@ rows of+-- 2 * @srcW@ bits, column 0 at bit @msb@.+{-# INLINE buildEpxTable #-}+buildEpxTable :: (Prim w, Bits w, Num w) => Int -> Int -> Int -> Int -> (Int -> Int -> Int -> Bool) -> ST s (PrimArray w)+buildEpxTable !numGlyphs !srcW !srcH !msb bitAt = do+ out <- newPrimArray (numGlyphs * 2 * srcH)+ let forGlyph !gid = when (gid < numGlyphs) $ do+ forRow gid 0+ forGlyph (gid + 1)+ forRow !gid !r = when (r < srcH) $ do+ let (!top, !bot) = rowPair gid r 0 0 0+ !base = gid * 2 * srcH + 2 * r+ writePrimArray out base top+ writePrimArray out (base + 1) bot+ forRow gid (r + 1)+ rowPair !gid !r !c !top !bot+ | c >= srcW = (top, bot)+ | otherwise =+ let (e0, e1, e2, e3) =+ epx (bitAt gid c (r - 1)) (bitAt gid (c - 1) r) (bitAt gid c r) (bitAt gid (c + 1) r) (bitAt gid c (r + 1))+ !bit0 = msb - 2 * c+ put v i acc = if v then setBit acc i else acc+ in rowPair gid r (c + 1) (put e1 (bit0 - 1) (put e0 bit0 top)) (put e3 (bit0 - 1) (put e2 bit0 bot))+ forGlyph 0+ unsafeFreezePrimArray out++-- | Pixel @(col, row)@ of glyph @gid@ in a table of @h@ rows per glyph with+-- column 0 at bit @msb@; unset outside the @w@ x @h@ glyph.+{-# INLINE rowBit #-}+rowBit :: (Prim w, Bits w) => PrimArray w -> Int -> Int -> Int -> Int -> Int -> Int -> Bool+rowBit arr w h msb gid c r =+ c >= 0 && c < w && r >= 0 && r < h && testBit (indexPrimArray arr (gid * h + r)) (msb - c)++-- | Whether a pixel is set in a glyph at scale 1 (7x13), 2 (14x26) or 4+-- (28x52). An unknown glyph reads as glyph 0.+cozetteGlyphBit :: CozetteFont -> Int -> Word32 -> Int -> Int -> Bool+cozetteGlyphBit font scale gid = case scale of+ 1 -> rowBit (cfGlyphData1x font) 7 13 7 g+ 2 -> rowBit (cfGlyphData2x font) 14 26 15 g+ _ -> rowBit (cfGlyphData4x font) 28 52 31 g+ where+ g = if fromIntegral gid < cfNumGlyphs font then fromIntegral gid else 0++-- | Find a glyph, substituting ASCII for selected UI icons. Unsupported+-- characters map to glyph 0, the missing-glyph bitmap.+{-# INLINE charToGlyphId #-}+charToGlyphId :: CozetteFont -> Char -> Word32+charToGlyphId font c =+ let !cp = fromIntegral (ord c)+ in if cp >= 32 && cp <= 126+ then cp - 31 -- Fast ASCII path+ else case cp of+ 0xf00d -> 57 -- FontAwesome times (\xf00d) -> 'X'+ 0x00d7 -> 57 -- Multiplication sign (×, \xd7) -> 'X'+ 0x2715 -> 57 -- Multiplication X (✕) -> 'X'+ 0x2716 -> 57 -- Heavy multiplication X (✖) -> 'X'+ 0xf078 -> 87 -- FontAwesome chevron-down (\xf078) -> 'v'+ 0xf054 -> 31 -- FontAwesome chevron-right (\xf054) -> '>'+ 0xf0d8 -> 63 -- FontAwesome caret-up (\xf0d8) -> '^'+ 0xf0d7 -> 87 -- FontAwesome caret-down (\xf0d7) -> 'v'+ 0xf046 -> 89 -- FontAwesome check-square (\xf046) -> 'x'+ 0xf096 -> 1 -- FontAwesome square (\xf096) -> ' '+ _ -> binarySearch (cfGroups font) cp+ where+ binarySearch grps cp = go 0 (sizeofPrimArray grps `div` 3 - 1)+ where+ go !lo !hi+ | lo > hi = 0+ | otherwise =+ let !mid = (lo + hi) `div` 2+ !start = indexPrimArray grps (mid * 3)+ !end = indexPrimArray grps (mid * 3 + 1)+ !glyph = indexPrimArray grps (mid * 3 + 2)+ in if cp < start+ then go lo (mid - 1)+ else if cp > end+ then go (mid + 1) hi+ else glyph + (cp - start)++-- | How a glyph is drawn at a scale.+data CozetteScalePath+ = ScaleExact1x -- ^ within 0.05 of 1x: the 7x13 bitmap+ | ScaleExact2x -- ^ within 0.05 of 2x: the EPX 14x26 bitmap+ | ScaleExact4x -- ^ within 0.05 of 4x: the double-EPX 28x52 bitmap+ | ScaleBoxFrom2x -- ^ other scales below 2x: the 14x26 bitmap, box-averaged+ | ScaleBoxFrom4x -- ^ other scales: the 28x52 bitmap, box-averaged+ deriving (Eq, Show)++-- | Choose native, EPX-expanded, or box-averaged glyphs for a display scale.+-- Below 1x the glyphs shrink with the pen grid, box-averaged from 2x.+cozetteScalePath :: Float -> CozetteScalePath+cozetteScalePath s+ | abs (s - 1.0) < 0.05 = ScaleExact1x+ | abs (s - 2.0) < 0.05 = ScaleExact2x+ | abs (s - 4.0) < 0.05 = ScaleExact4x+ | s < 2.0 = ScaleBoxFrom2x+ | otherwise = ScaleBoxFrom4x++-- | Pixel footprint of one glyph drawn at a scale.+cozetteGlyphFootprint :: Float -> (Int, Int)+cozetteGlyphFootprint s = case cozetteScalePath s of+ ScaleExact1x -> (cozetteGlyphWidth, cozetteGlyphHeight)+ ScaleExact2x -> (2 * cozetteGlyphWidth, 2 * cozetteGlyphHeight)+ ScaleExact4x -> (4 * cozetteGlyphWidth, 4 * cozetteGlyphHeight)+ _ ->+ ( max 1 (round (fromIntegral cozetteGlyphWidth * s))+ , max 1 (round (fromIntegral cozetteGlyphHeight * s))+ )++-- | Stamp one glyph with its top-left at (penX, penY) into a @stride@-wide+-- BGRA buffer, clipped to [clipX0, clipX1) x [clipY0, clipY1). Exact scales+-- copy a bitmap; other scales box-average the next larger EPX bitmap and+-- blend by coverage. Glyph 1 (space) draws nothing; unknown ids draw glyph 0.+-- Not inlined: the GL host only calls it while baking its glyph atlas.+{-# NOINLINE renderGlyphScaledToBuffer #-}+renderGlyphScaledToBuffer ::+ Ptr Word32 ->+ Int ->+ Int ->+ Int ->+ Int ->+ Int ->+ Float ->+ Int ->+ Int ->+ Word32 ->+ CozetteFont ->+ Word32 ->+ IO ()+renderGlyphScaledToBuffer !dst !stride !clipX0 !clipY0 !clipX1 !clipY1 !scale !penX !penY !color !font !gid =+ when (glyph /= 1) $ case cozetteScalePath scale of+ ScaleExact1x -> blitMask dst stride penX penY color (rowsOf 13) (colsOf 7) row1x+ ScaleExact2x -> blitMask dst stride penX penY color (rowsOf 26) (colsOf 14) row2x+ ScaleExact4x -> blitMask dst stride penX penY color (rowsOf 52) (colsOf 28) row4x+ ScaleBoxFrom2x -> boxed 14 26 row2x+ ScaleBoxFrom4x -> boxed 28 52 row4x+ where+ !glyph = if fromIntegral gid < cfNumGlyphs font then fromIntegral gid else 0 :: Int+ -- Bitmap rows as masks with column 0 at bit 31.+ row1x r = fromIntegral (indexPrimArray (cfGlyphData1x font) (glyph * 13 + r)) `shiftL` 24+ row2x r = fromIntegral (indexPrimArray (cfGlyphData2x font) (glyph * 26 + r)) `shiftL` 16+ row4x r = indexPrimArray (cfGlyphData4x font) (glyph * 52 + r)+ -- The part of an h-row / w-column footprint inside the clip.+ rowsOf h = (max 0 (clipY0 - penY), min h (clipY1 - penY))+ colsOf w = (max 0 (clipX0 - penX), min w (clipX1 - penX))+ boxed :: Int -> Int -> (Int -> Word32) -> IO ()+ boxed !srcW !srcH row = goRow dy0+ where+ (!tw, !th) = cozetteGlyphFootprint scale+ !scaleX = fromIntegral srcW / fromIntegral tw :: Float+ !scaleY = fromIntegral srcH / fromIntegral th :: Float+ (!dy0, !dy1) = rowsOf th+ (!dx0, !dx1) = colsOf tw+ goRow !dy = when (dy < dy1) $ do+ let !y0 = fromIntegral dy * scaleY+ !y1 = fromIntegral (dy + 1) * scaleY+ !base = (penY + dy) * stride + penX+ goCol !dx = when (dx < dx1) $ do+ let !off = base + dx+ !cov = boxCoverage srcW srcH row (fromIntegral dx * scaleX) (fromIntegral (dx + 1) * scaleX) y0 y1+ !effA = round (fromIntegral srcA * cov) :: Int+ -- Skip near-transparent coverage; overwrite near-opaque.+ when (effA > 3) $+ if effA >= 252+ then pokeElemOff dst off color+ else do+ d <- peekElemOff dst off+ let !invA = 255 - effA+ mix s = fromIntegral ((channel color s * effA + channel d s * invA + 127) `div` 255) :: Word32+ pokeElemOff dst off (0xFF000000 .|. (mix 16 `shiftL` 16) .|. (mix 8 `shiftL` 8) .|. mix 0)+ goCol (dx + 1)+ goCol dx0+ goRow (dy + 1)+ !srcA = channel color 24+ channel w s = fromIntegral ((w `shiftR` s) .&. 0xFF) :: Int++-- | Write @color@ wherever a row mask (column 0 at bit 31) has a bit set, over+-- the given row and column ranges of a glyph at (penX, penY).+{-# INLINE blitMask #-}+blitMask :: Ptr Word32 -> Int -> Int -> Int -> Word32 -> (Int, Int) -> (Int, Int) -> (Int -> Word32) -> IO ()+blitMask !dst !stride !penX !penY !color (!r0, !r1) (!c0, !c1) row = goRow r0+ where+ goRow !r = when (r < r1) $ do+ let !bits = row r+ when (bits /= 0) $ goCol ((penY + r) * stride + penX) bits c0+ goRow (r + 1)+ goCol !base !bits !c = when (c < c1) $ do+ when (testBit bits (31 - c)) $ pokeElemOff dst (base + c) color+ goCol base bits (c + 1)++-- | Covered fraction, in [0, 1], of the texel box [x0, x1) x [y0, y1) on a+-- @srcW@ x @srcH@ grid whose rows are masks with column 0 at bit 31.+{-# INLINE boxCoverage #-}+boxCoverage :: Int -> Int -> (Int -> Word32) -> Float -> Float -> Float -> Float -> Float+boxCoverage !srcW !srcH row !x0 !x1 !y0 !y1+ | area > 0 = max 0 (min 1 (goRow (max 0 (floor y0)) 0 / area))+ | otherwise = 0+ where+ !area = (x1 - x0) * (y1 - y0)+ !syMax = min (srcH - 1) (floor (y1 - 1e-5))+ !sxMin = max 0 (floor x0)+ !sxMax = min (srcW - 1) (floor (x1 - 1e-5))+ goRow !sy !acc+ | sy > syMax = acc+ | otherwise =+ let !ovY = max 0 (min (fromIntegral (sy + 1)) y1 - max (fromIntegral sy) y0)+ in goRow (sy + 1) (acc + goCol (row sy) ovY sxMin 0)+ goCol !bits !ovY !sx !acc+ | sx > sxMax = acc+ | otherwise =+ let !ovX = max 0 (min (fromIntegral (sx + 1)) x1 - max (fromIntegral sx) x0)+ !inc = if testBit bits (31 - sx) then ovX * ovY else 0+ in goCol bits ovY (sx + 1) (acc + inc)++-- | Visit the glyph pen positions (physical pixels) of a text run laid out+-- from logical (logX, logY) at a scale, threading an accumulator. @\\r@+-- returns to column 0, @\\n@ starts the next line, and space (glyph 1)+-- advances without a visit.+{-# INLINE foldPenPositions #-}+foldPenPositions :: CozetteFont -> Float -> Float -> Float -> a -> (a -> Int -> Int -> Word32 -> IO a) -> Text -> IO a+foldPenPositions font !scale !logX !logY z step = go (0 :: Int) (0 :: Int) z+ where+ -- Ties up like nano-ui's onGrid, so pens stay in phase with snapped+ -- geometry at fractional scales (125%: a 6px advance is 7.5 device px).+ pen origin i advance = roundHalfUp ((origin + fromIntegral i * advance) * scale)+ go !col !line !acc t = case T.uncons t of+ Nothing -> pure acc+ Just ('\r', rest) -> go 0 line acc rest+ Just ('\n', rest) -> go 0 (line + 1) acc rest+ Just (c, rest) -> do+ let !gid = charToGlyphId font c+ acc' <-+ if gid == 1+ then pure acc+ else step acc (pen logX col cozetteCharAdvance) (pen logY line cozetteLineHeight) gid+ go (col + 1) line acc' rest++-- | Fixed-advance layout metrics with no shaping, kerning, or glyph callback.+-- The RGFW renderer draws the bitmap glyphs separately.+cozetteMetrics :: FontMetrics+cozetteMetrics =+ FontMetrics+ { fmLineHeight = cozetteLineHeight+ , fmAscent = cozetteAscent+ , fmSnapScale = 1.0+ , fmAdvance = \_ -> cozetteCharAdvance+ , fmKerning = \_ _ -> 0+ , fmShape = \_ -> Nothing+ , fmGlyph = \_ -> Nothing+ , fmBackend = Nothing+ }
+ lib/NanoUI/Rgfw/Internal/Gl.hs view
@@ -0,0 +1,647 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | OpenGL presentation for the RGFW host.+--+-- Geometry goes to the GPU straight from the core's shared 'DrawData'+-- buffers, one scissored draw per command; image-atlas commands sample the+-- texture 'syncImagesGl' maintains. Text comes from the collected+-- spans: every glyph is a quad sampled from an atlas that the Cozette+-- software blitter bakes at the current scale, so glyph pixels match what the+-- blitter stamps.+--+-- Frames draw into a retained framebuffer and a present copies it to the+-- window, so a frame whose damage is a clip draws only inside it.+--+-- The frame must come from a context built by+-- 'NanoUI.Rgfw.Internal.Context.newRgfwContext' (external text: the buffer holds no+-- text quads). Draw order is 'NanoUI.Rgfw.Internal.Context.paintInLayerOrder'.+module NanoUI.Rgfw.Internal.Gl+ ( GlRenderer+ , newGlRenderer+ , freeGlRenderer+ , renderArenaGl+ , syncImagesGl+ , readRetainedPixels+ , readWindowPixels+ , retainedPixels+ , GlyphAtlas (..)+ , glyphAtlasFor+ , atlasCell+ , bakeGlyphAtlas+ , writeSpanQuads+ , toPhysRect+ , physClip+ , glBufferStrides+ ) where++import Control.Exception (bracket)+import Control.Monad (foldM, forM_, void, when)+import Data.Bits (shiftR, (.&.))+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.Int (Int32)+import qualified Data.IntMap.Strict as IM+import Data.Maybe (fromMaybe, isJust)+import Data.Primitive.ByteArray (ByteArray, copyByteArrayToAddr, sizeofByteArray)+import Data.Primitive.PrimArray (indexPrimArray)+import Data.Primitive.SmallArray (SmallArray, indexSmallArray, sizeofSmallArray)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Internal as BSI+import qualified Data.ByteString.Unsafe as BSU+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import qualified Data.Text.Foreign as TF+import qualified Data.Vector.Unboxed as U+import Data.Word (Word32, Word64, Word8)+import Foreign.C.Types (CChar)+import Foreign.ForeignPtr (withForeignPtr)+import Foreign.Marshal.Alloc (alloca, allocaBytes, callocBytes, free, reallocBytes)+import Foreign.Marshal.Utils (copyBytes)+import Foreign.Ptr (Ptr, nullPtr, plusPtr)+import Foreign.Storable (peek, pokeByteOff)+import NanoUI (Color (..), Rect (..), RgbaPixels, rectInflate, rgbaPixels)+import NanoUI.Backend (Damage (..), roundHalfUp)+import NanoUI.Rgfw.Internal.Context (TextSpan, paintInLayerOrder)+import NanoUI.Rgfw.Internal.Font.Cozette+ ( CozetteFont (..)+ , cozetteGlyphFootprint+ , cozetteLineHeight+ , foldPenPositions+ , renderGlyphScaledToBuffer+ )+import NanoUI.Backend+ ( AtlasUpload (..)+ , Context+ , DrawCmd (..)+ , DrawData (..)+ , EffectDriver (..)+ , EffectPassDraw (..)+ , EffectSpan (..)+ , Layer (..)+ , ShaderCall (..)+ , ShaderProgram (..)+ , atlasChanges+ , atlasTextureId+ , execEffectSpans+ , forDrawCmdsInLayer_+ , vertexSize+ , withEffectUniforms+ )++-- | Opaque C renderer state (cbits/nano_ui_gl.c).+data NanoUiGl++foreign import ccall unsafe "nano_ui_gl_create"+ c_create :: IO (Ptr NanoUiGl)++foreign import ccall unsafe "nano_ui_gl_destroy"+ c_destroy :: Ptr NanoUiGl -> IO ()++foreign import ccall unsafe "nano_ui_gl_upload_atlas"+ c_uploadAtlas :: Ptr NanoUiGl -> Ptr Word32 -> Int32 -> Int32 -> IO Int32++foreign import ccall unsafe "nano_ui_gl_upload_images"+ c_uploadImages :: Ptr NanoUiGl -> Ptr Word8 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> IO Int32++foreign import ccall unsafe "nano_ui_gl_begin"+ c_begin :: Ptr NanoUiGl -> Int32 -> Int32 -> Float -> Float -> Float -> Float -> Int32 -> IO Int32++foreign import ccall unsafe "nano_ui_gl_present"+ c_present :: Ptr NanoUiGl -> IO ()++foreign import ccall unsafe "nano_ui_gl_read_retained"+ c_readRetained :: Ptr NanoUiGl -> Int32 -> Int32 -> Ptr Word8 -> IO ()++foreign import ccall unsafe "nano_ui_gl_read_window"+ c_readWindow :: Ptr NanoUiGl -> Int32 -> Int32 -> Ptr Word8 -> IO ()++foreign import ccall unsafe "nano_ui_gl_upload_geometry"+ c_uploadGeometry :: Ptr NanoUiGl -> Ptr Word8 -> Int32 -> Ptr Word8 -> Int32 -> IO ()++foreign import ccall unsafe "nano_ui_gl_upload_text"+ c_uploadText :: Ptr NanoUiGl -> Ptr Word8 -> Int32 -> IO ()++foreign import ccall unsafe "nano_ui_gl_draw_geometry"+ c_drawGeometry :: Ptr NanoUiGl -> Int32 -> Int32 -> Int32 -> Int32 -> Word32 -> Word32 -> Int32 -> IO ()++foreign import ccall unsafe "nano_ui_gl_draw_shader"+ c_drawShader ::+ Ptr NanoUiGl ->+ Int32 -> Int32 -> Int32 -> Int32 ->+ Word32 -> Word32 ->+ Word64 -> Ptr CChar -> Int32 ->+ Ptr Word8 -> Int32 ->+ IO Int32++foreign import ccall unsafe "nano_ui_gl_draw_text"+ c_drawText :: Ptr NanoUiGl -> Int32 -> Int32 -> IO ()++foreign import ccall unsafe "nano_ui_gl_acquire_target"+ c_acquireTarget :: Ptr NanoUiGl -> Int32 -> Int32 -> Ptr Int32 -> Ptr Int32 -> IO Int32++foreign import ccall unsafe "nano_ui_gl_release_target"+ c_releaseTarget :: Ptr NanoUiGl -> Int32 -> IO ()++foreign import ccall unsafe "nano_ui_gl_bind_target"+ c_bindTarget :: Ptr NanoUiGl -> Int32 -> Int32 -> Float -> Float -> IO Int32++foreign import ccall unsafe "nano_ui_gl_composite_effect"+ c_compositeEffect ::+ Ptr NanoUiGl -> Int32 ->+ Float -> Float -> Float -> Float ->+ Float -> Float -> Float -> Float ->+ Int32 -> Int32 -> Int32 -> Int32 -> Int32 ->+ Int32 ->+ Word64 -> Ptr CChar -> Int32 ->+ Ptr Word8 -> Int32 ->+ IO Int32++foreign import ccall unsafe "nano_ui_gl_vertex_bytes"+ c_vertexBytes :: IO Int32++foreign import ccall unsafe "nano_ui_gl_index_bytes"+ c_indexBytes :: IO Int32++-- | The vertex and index strides in bytes nano_ui_gl.c reads the draw+-- buffers with. They must equal the core's 'vertexSize' and+-- 'NanoUI.Testing.indexSize'; nano-ui-rgfw-test checks.+glBufferStrides :: IO (Int, Int)+glBufferStrides = (,) <$> (fromIntegral <$> c_vertexBytes) <*> (fromIntegral <$> c_indexBytes)++-- | GPU resources and glyph scratch storage owned by one OpenGL context.+-- Release with 'freeGlRenderer' while that context is still current.+data GlRenderer = GlRenderer+ { glHandle :: !(Ptr NanoUiGl)+ , glAtlas :: !(IORef (Maybe GlyphAtlas))+ , glText :: !(IORef (Ptr Word8, Int)) -- ^ glyph vertex scratch, capacity in vertices+ , glImages :: !(IORef Int) -- ^ image atlas generation uploaded, 0 for none+ }++-- | Build the renderer on the calling thread's current OpenGL context.+newGlRenderer :: IO GlRenderer+newGlRenderer = do+ h <- c_create+ when (h == nullPtr) $+ fail "nano-ui-rgfw: OpenGL renderer setup failed (needs an OpenGL 3.2 core context)"+ GlRenderer h <$> newIORef Nothing <*> newIORef (nullPtr, 0) <*> newIORef 0++-- | Release the GPU objects (the context must still be current) and the+-- glyph vertex scratch.+freeGlRenderer :: GlRenderer -> IO ()+freeGlRenderer r = do+ c_destroy (glHandle r)+ (p, _) <- readIORef (glText r)+ free p++-- | Draw a frame into the retained framebuffer and copy it to the current+-- context's default framebuffer. The caller swaps buffers.+--+-- A 'DamageClip' frame redraws only its damage and keeps the other pixels+-- from the frames before, so its 'DrawData' may leave out what lies outside.+-- Its damage pieces ('NanoUI.Testing.takeDamagePieces'), when it has some,+-- are all it redraws: text is cut to each, as draw commands already are.+-- A frame at a new size has no such pixels and must be a 'DamageFull' one.+renderArenaGl ::+ GlRenderer ->+ CozetteFont ->+ Float -> -- logical (layout) -> physical (pixel) scale+ Int -> -- framebuffer width (physical pixels)+ Int -> -- framebuffer height+ Damage -> -- what to redraw, in logical pixels+ [Rect] -> -- the damage's pieces, if any+ DrawData -> -- the frame, and the colour a full frame clears to+ [TextSpan] -> -- base spans+ [TextSpan] -> -- overlay spans+ IO ()+renderArenaGl r font !scale !fbW !fbH damage pieces drawData baseSpans overlaySpans = do+ let !h = glHandle r+ (!full, mDamage, textBoxes) = case damage of+ DamageFull -> (1, Nothing, [(0, 0, fbW, fbH)])+ DamageClip rect -> (0, Just rect, map (damageBox scale fbW fbH) (if null pieces then [rect] else pieces))+ (!bgR, !bgG, !bgB, _) = colorFloats (drawClear drawData)+ began <- c_begin h (fromIntegral fbW) (fromIntegral fbH) scale bgR bgG bgB full+ when (began == 0) $ fail "nano-ui-rgfw: retained framebuffer setup failed"+ atlas <- ensureAtlas r font scale+ let effectSpans = drawEffectSpans drawData+ withForeignPtr (drawVertices drawData) $ \vp ->+ withForeignPtr (drawIndices drawData) $ \ip ->+ c_uploadGeometry h vp (fromIntegral (drawVertexCount drawData)) ip (fromIntegral (drawIndexCount drawData))+ if sizeofSmallArray effectSpans == 0+ then do+ buf <- ensureTextCapacity r ((spanChars baseSpans + spanChars overlaySpans) * 6 * length textBoxes)+ let spansIn spans n0 = foldM (\n tb -> foldM (writeSpanQuads atlas font tb buf) n spans) n0 textBoxes+ nBase <- spansIn baseSpans 0+ nAll <- spansIn overlaySpans nBase+ c_uploadText h buf (fromIntegral nAll)+ paintInLayerOrder+ (\layer -> forDrawCmdsInLayer_ layer drawData (drawCmd h scale fbW fbH 0 0 (drawShaderCalls drawData) (drawUniformBytes drawData)))+ (c_drawText h 0 (fromIntegral nBase))+ (c_drawText h (fromIntegral nBase) (fromIntegral (nAll - nBase)))+ else+ renderArenaGlWithEffects r h atlas font scale fbW fbH mDamage textBoxes drawData effectSpans baseSpans overlaySpans+ c_present h++-- | Render a frame containing Tier 2 subtree effects into pooled offscreen+-- OpenGL 3.2 framebuffers. Cozette text spans falling inside an effect span+-- are drawn into that span's offscreen target before its shader passes run.+{-# NOINLINE renderArenaGlWithEffects #-}+renderArenaGlWithEffects ::+ GlRenderer ->+ Ptr NanoUiGl ->+ GlyphAtlas ->+ CozetteFont ->+ Float ->+ Int ->+ Int ->+ Maybe Rect ->+ [(Int, Int, Int, Int)] ->+ DrawData ->+ SmallArray EffectSpan ->+ [TextSpan] ->+ [TextSpan] ->+ IO ()+renderArenaGlWithEffects r h atlas font !scale !fbW !fbH mDamage textBoxes drawData effectSpans baseSpans overlaySpans = do+ let nSpans = sizeofSmallArray effectSpans+ allSpans = [indexSmallArray effectSpans i | i <- [0 .. nSpans - 1]]+ isBaseLayer l = l == LayerBackground || l == LayerContent+ ownerOf isBase (Rect tx ty tw th, _, _, _, _) =+ let !cx = tx + tw * 0.5+ !cy = ty + th * 0.5+ inBounds (Rect bx by bw bh) = cx >= bx && cx <= bx + bw && cy >= by && cy <= by + bh+ matches =+ [ esId sp+ | sp <- allSpans+ , isBaseLayer (esLayer sp) == isBase+ , inBounds (esBounds sp)+ ]+ in case matches of+ [] -> 0+ xs -> maximum xs+ -- Partition spans into root vs. per-effect buckets in one linear pass.+ partitionSpans isBase =+ foldr+ (\s (roots, byId) ->+ let !eid = ownerOf isBase s+ in if eid == 0+ then (s : roots, byId)+ else (roots, IM.insertWith (++) eid [s] byId))+ ([], IM.empty)+ (rootBase, baseById) = partitionSpans True baseSpans+ (rootOver, overById) = partitionSpans False overlaySpans+ spansById = IM.unionWith (++) baseById overById+ effectIds = [esId sp | sp <- allSpans]+ totalVerts =+ ((spanChars rootBase + spanChars rootOver) * length textBoxes+ + IM.foldl' (\acc ss -> acc + spanChars ss) 0 spansById)+ * 6+ buf <- ensureTextCapacity r totalVerts+ let writeBoxes boxes spans n0 = foldM (\n tb -> foldM (writeSpanQuads atlas font tb buf) n spans) n0 boxes+ nRootBase <- writeBoxes textBoxes rootBase 0+ nRootOver <- writeBoxes textBoxes rootOver nRootBase+ (spanRanges, nFinal) <-+ foldM+ (\(acc, n0) eid ->+ case IM.lookup eid spansById of+ Nothing -> pure (acc, n0)+ Just ss -> do+ n1 <- writeBoxes [(0, 0, fbW, fbH)] ss n0+ pure (IM.insert eid (n0, n1 - n0) acc, n1))+ (IM.empty, nRootOver)+ effectIds+ c_uploadText h buf (fromIntegral nFinal)+ let rawCmds = drawCommands drawData+ offsets = drawLayerOffsets drawData+ shaderCalls = drawShaderCalls drawData+ uBytes = drawUniformBytes drawData+ drawSpanText eid =+ case IM.lookup eid spanRanges of+ Just (startV, cntV) | cntV > 0 -> c_drawText h (fromIntegral startV) (fromIntegral cntV)+ _ -> pure ()+ drv =+ EffectDriver+ { edScale = scale+ , edFlipY = True+ , edPreparePasses = \passes ->+ pure $+ if all (\i -> isJust (spGlsl150 (scProgram (indexSmallArray passes i)))) [0 .. sizeofSmallArray passes - 1]+ then Just passes+ else Nothing+ , edAcquireTarget = acquireGlTarget h+ , edReleaseTarget = c_releaseTarget h . fromIntegral+ , edBindTarget = \slot clr ox oy ->+ (/= 0) <$> c_bindTarget h (fromIntegral slot) (if clr then 1 else 0) ox oy+ , edFlush = pure ()+ , edEmitPlain = \_ cw ch ox oy _ from to ->+ let loop !i = when (i < to) (drawCmd h scale cw ch ox oy shaderCalls uBytes (U.unsafeIndex rawCmds i) >> loop (i + 1))+ in loop from+ , edAfterSpanContent = drawSpanText+ , edCompositePass = \_ sc pd dstW dstH ->+ case epdClip pd of+ Nothing -> compositeGlPass h sc uBytes pd (0, 0, 0, 0, 0)+ Just clipR ->+ forM_ (physClip scale dstW dstH clipR) $ \(sx0, sy0, sx1, sy1) ->+ compositeGlPass h sc uBytes pd (1, sx0, sy0, sx1, sy1)+ }+ renderLayer layer =+ let !lo = indexPrimArray offsets (fromEnum layer)+ !hi = indexPrimArray offsets (fromEnum layer + 1)+ in execEffectSpans drv effectSpans 0 (-1) (fbW, fbH) 0 0 mDamage lo hi+ paintInLayerOrder+ renderLayer+ (c_drawText h 0 (fromIntegral nRootBase))+ (c_drawText h (fromIntegral nRootBase) (fromIntegral (nRootOver - nRootBase)))++acquireGlTarget :: Ptr NanoUiGl -> Int -> Int -> IO (Int, Int, Int)+acquireGlTarget h minW minH =+ alloca $ \pW ->+ alloca $ \pH -> do+ slot <- c_acquireTarget h (fromIntegral minW) (fromIntegral minH) pW pH+ if slot < 0+ then pure (-1, 0, 0)+ else do+ cw <- peek pW+ ch <- peek pH+ pure (fromIntegral slot, fromIntegral cw, fromIntegral ch)++{-# NOINLINE compositeGlPass #-}+compositeGlPass ::+ Ptr NanoUiGl ->+ ShaderCall ->+ ByteArray ->+ EffectPassDraw ->+ (Int32, Int, Int, Int, Int) ->+ IO ()+compositeGlPass h sc uniformBytes pd (hasSc, sx0, sy0, sx1, sy1) =+ case spGlsl150 (scProgram sc) of+ Nothing -> pure ()+ Just src -> do+ let srcUtf8 = TE.encodeUtf8 src+ blendCopy = if epdIntermediate pd then 1 else 0 :: Int32+ BSU.unsafeUseAsCStringLen srcUtf8 $ \(srcPtr, srcLen) ->+ withEffectUniforms sc uniformBytes pd $ \uPtr uLen ->+ void $+ c_compositeEffect+ h (fromIntegral (epdSrcSlot pd))+ (epdDstX pd) (epdDstY pd) (epdDstW pd) (epdDstH pd)+ (epdU0 pd) (epdV0 pd) (epdU1 pd) (epdV1 pd)+ hasSc (fromIntegral sx0) (fromIntegral sy0) (fromIntegral sx1) (fromIntegral sy1)+ blendCopy (scHash sc) srcPtr (fromIntegral srcLen)+ uPtr (fromIntegral uLen)++-- | Upload image atlas changes since the last sync: dirty rects, or the+-- whole atlas after a resize or on first use. Call before 'renderArenaGl'+-- with the GL context current.+syncImagesGl :: GlRenderer -> Context -> IO ()+syncImagesGl r ctx = do+ since <- readIORef (glImages r)+ changes <- atlasChanges ctx since+ forM_ changes $ \(w, h, pixels, gen, upload) -> do+ let put whole (x, y, rw, rh) =+ (/= 0) <$> withForeignPtr pixels (\p ->+ c_uploadImages (glHandle r) p (fromIntegral w) (fromIntegral h)+ (fromIntegral x) (fromIntegral y) (fromIntegral rw) (fromIntegral rh) whole)+ ok <- case upload of+ AtlasWhole -> put 1 (0, 0, w, h)+ AtlasRegions rects -> and <$> mapM (put 0) rects+ -- A failed rect upload (no texture yet) forces a full upload next frame.+ writeIORef (glImages r) (if ok then gen else 0)++-- | The retained frame's pixels, for checking what frames drew: RGBA rows,+-- bottom row first, of its bottom-left w x h. Pixels past the last frame's+-- size are undefined.+readRetainedPixels :: GlRenderer -> Int -> Int -> IO BS.ByteString+readRetainedPixels r w h =+ BSI.create (w * h * 4) (c_readRetained (glHandle r) (fromIntegral w) (fromIntegral h))++-- | The window back buffer after the last present, in the same layout as+-- 'readRetainedPixels'. For tests; read before the swap, after which the+-- back buffer is undefined.+readWindowPixels :: GlRenderer -> Int -> Int -> IO BS.ByteString+readWindowPixels r w h =+ BSI.create (w * h * 4) (c_readWindow (glHandle r) (fromIntegral w) (fromIntegral h))++-- | The retained frame as a top-down screenshot. @w@ x @h@ must be the last+-- frame's size; each is clamped to at least 1.+retainedPixels :: GlRenderer -> Int -> Int -> IO (Maybe RgbaPixels)+retainedPixels r w0 h0 = do+ let w = max 1 w0+ h = max 1 h0+ row = w * 4+ bottomUp <- readRetainedPixels r w h+ pixels <- BSI.create (h * row) $ \dst ->+ BSU.unsafeUseAsCString bottomUp $ \src ->+ mapM_ (\y -> copyBytes (dst `plusPtr` (y * row)) (src `plusPtr` ((h - 1 - y) * row)) row) [0 .. h - 1]+ pure (rgbaPixels w h pixels)++-- | The physical pixels a damage rect repaints, as @(x0, y0, x1, y1)@ within+-- a w x h framebuffer. The core paints a clip frame's backdrop one logical+-- pixel past the damage, and the box is the scissor a command clipped to that+-- backdrop gets, so text never lands on a pixel the backdrop left.+damageBox :: Float -> Int -> Int -> Rect -> (Int, Int, Int, Int)+damageBox !scale !w !h = fromMaybe (0, 0, 0, 0) . physClip scale w h . rectInflate 1++drawCmd :: Ptr NanoUiGl -> Float -> Int -> Int -> Float -> Float -> SmallArray ShaderCall -> ByteArray -> DrawCmd -> IO ()+drawCmd h !scale !curW !curH !ox !oy shaderCalls uniformBytes cmd+ | cmdIndexCount cmd < 3 = pure ()+ | otherwise =+ case physClip scale curW curH (Rect (cmdClipX cmd - ox) (cmdClipY cmd - oy) (cmdClipW cmd) (cmdClipH cmd)) of+ Nothing -> pure ()+ Just (x0, y0, x1, y1) ->+ let !shIdx = fromIntegral (cmdShader cmd) :: Int+ in if shIdx > 0 && shIdx <= sizeofSmallArray shaderCalls+ then drawShaderCmd h x0 y0 x1 y1 cmd (indexSmallArray shaderCalls (shIdx - 1)) uniformBytes+ else+ c_drawGeometry h (fromIntegral x0) (fromIntegral y0) (fromIntegral x1) (fromIntegral y1)+ (cmdIndexOffset cmd) (cmdIndexCount cmd) (if cmdTextureId cmd == atlasTextureId then 1 else 0)++{-# NOINLINE drawShaderCmd #-}+drawShaderCmd :: Ptr NanoUiGl -> Int -> Int -> Int -> Int -> DrawCmd -> ShaderCall -> ByteArray -> IO ()+drawShaderCmd h x0 y0 x1 y1 cmd sc uniformBytes =+ case spGlsl150 (scProgram sc) of+ Nothing -> pure ()+ Just src -> do+ let srcUtf8 = TE.encodeUtf8 src+ !uOff = scUniformOffset sc+ !uLen = min (scUniformLength sc) (max 0 (sizeofByteArray uniformBytes - uOff))+ BSU.unsafeUseAsCStringLen srcUtf8 $ \(srcPtr, srcLen) ->+ if uLen > 0+ then allocaBytes uLen $ \uPtr -> do+ copyByteArrayToAddr uPtr uniformBytes uOff uLen+ void $+ c_drawShader h (fromIntegral x0) (fromIntegral y0) (fromIntegral x1) (fromIntegral y1)+ (cmdIndexOffset cmd) (cmdIndexCount cmd) (scHash sc) srcPtr (fromIntegral srcLen)+ uPtr (fromIntegral uLen)+ else+ void $+ c_drawShader h (fromIntegral x0) (fromIntegral y0) (fromIntegral x1) (fromIntegral y1)+ (cmdIndexOffset cmd) (cmdIndexCount cmd) (scHash sc) srcPtr (fromIntegral srcLen)+ nullPtr 0++-- | Scale logical x/y/width/height to physical pixels, snapping both edges+-- with half-up rounding. Returns x/y/width/height with non-negative extents.+--+-- The SDL and web backends round a clip outwards instead+-- ('NanoUI.Testing.clipPixelEdges'), to cover the pixels of damage they+-- snapped outwards ('NanoUI.Backend.snapDamage'). This backend snaps no+-- damage: it repaints a logical pixel past it ('damageBox'), and rounds+-- each scissor edge to the pixel 'roundHalfUp' snaps geometry and Cozette+-- glyph pens to, so a scissor edge falls where the shapes it cuts end, and+-- two clips that meet share an edge with no pixel between or under both.+{-# INLINE toPhysRect #-}+toPhysRect :: Float -> Float -> Float -> Float -> Float -> (Int, Int, Int, Int)+toPhysRect !scale !rx !ry !rw !rh =+ let !x0 = roundHalfUp (rx * scale)+ !y0 = roundHalfUp (ry * scale)+ !x1 = roundHalfUp ((rx + rw) * scale)+ !y1 = roundHalfUp ((ry + rh) * scale)+ in (x0, y0, max 0 (x1 - x0), max 0 (y1 - y0))++-- | A logical clip rect scaled to physical pixels and intersected with a+-- w x h target, as @(x0, y0, x1, y1)@ with exclusive ends; 'Nothing' if empty.+{-# INLINE physClip #-}+physClip :: Float -> Int -> Int -> Rect -> Maybe (Int, Int, Int, Int)+physClip !scale !w !h = physClipIn scale (0, 0, w, h)++-- | 'physClip' intersected with a box of physical pixels instead of a target.+{-# INLINE physClipIn #-}+physClipIn :: Float -> (Int, Int, Int, Int) -> Rect -> Maybe (Int, Int, Int, Int)+physClipIn !scale (!bx0, !by0, !bx1, !by1) (Rect x y rw rh) =+ let (!px, !py, !pw, !ph) = toPhysRect scale x y rw rh+ !x0 = max bx0 px+ !y0 = max by0 py+ !x1 = min bx1 (px + pw)+ !y1 = min by1 (py + ph)+ in if x0 >= x1 || y0 >= y1 then Nothing else Just (x0, y0, x1, y1)++-- | Cell grid of one glyph bake. Every glyph owns a 'gaCellW' x 'gaCellH'+-- cell: the footprint 'renderGlyphScaledToBuffer' stamps at 'gaScale'.+data GlyphAtlas = GlyphAtlas+ { gaScale :: !Float+ , gaCellW :: !Int+ , gaCellH :: !Int+ , gaCols :: !Int+ , gaWidth :: !Int+ , gaHeight :: !Int+ }+ deriving (Eq, Show)++-- | A roughly square atlas holding every glyph of the font at a scale.+glyphAtlasFor :: CozetteFont -> Float -> GlyphAtlas+glyphAtlasFor font !scale =+ let (!cw, !ch) = cozetteGlyphFootprint scale+ !n = max 1 (cfNumGlyphs font)+ !cols = max 1 (ceiling (sqrt (fromIntegral (n * ch) / fromIntegral cw :: Double)))+ !rows = (n + cols - 1) `quot` cols+ in GlyphAtlas scale cw ch cols (cols * cw) (rows * ch)++-- | Top-left texel of a glyph's cell.+atlasCell :: GlyphAtlas -> Int -> (Int, Int)+atlasCell ga gid =+ let (!row, !col) = gid `quotRem` gaCols ga+ in (col * gaCellW ga, row * gaCellH ga)++-- | Stamp every glyph into its cell with the software blitter, opaque white+-- over transparent black, and hand the pixels to the continuation: each+-- pixel's low byte is its coverage. The pixels are freed afterwards.+bakeGlyphAtlas :: CozetteFont -> GlyphAtlas -> (Ptr Word32 -> IO a) -> IO a+bakeGlyphAtlas font ga k =+ bracket (callocBytes (gaWidth ga * gaHeight ga * 4)) free $ \px -> do+ let go !gid = when (gid < cfNumGlyphs font) $ do+ let (!cx, !cy) = atlasCell ga gid+ renderGlyphScaledToBuffer px (gaWidth ga) cx cy (cx + gaCellW ga) (cy + gaCellH ga)+ (gaScale ga) cx cy 0xFFFFFFFF font (fromIntegral gid)+ go (gid + 1)+ go 0+ k px++ensureAtlas :: GlRenderer -> CozetteFont -> Float -> IO GlyphAtlas+ensureAtlas r font !scale = do+ cur <- readIORef (glAtlas r)+ case cur of+ Just ga | gaScale ga == scale -> pure ga+ _ -> do+ let !ga = glyphAtlasFor font scale+ ok <- bakeGlyphAtlas font ga $ \px ->+ c_uploadAtlas (glHandle r) px (fromIntegral (gaWidth ga)) (fromIntegral (gaHeight ga))+ when (ok == 0) $ fail "nano-ui-rgfw: glyph atlas upload failed"+ writeIORef (glAtlas r) (Just ga)+ pure ga++ensureTextCapacity :: GlRenderer -> Int -> IO (Ptr Word8)+ensureTextCapacity r !needVerts = do+ (p, cap) <- readIORef (glText r)+ if needVerts <= cap+ then pure p+ else do+ let !cap' = maximum [needVerts, cap * 2, 4096]+ p' <- reallocBytes p (cap' * vertexSize)+ writeIORef (glText r) (p', cap')+ pure p'++-- | Upper bound on a span list's glyph count: the UTF-8 byte length, which is+-- O(1) per span.+spanChars :: [TextSpan] -> Int+spanChars = foldl' (\acc (_, t, _, _, _) -> acc + TF.lengthWord8 t) 0++-- | Append a span's glyph quads to a vertex buffer, 6 vertices per glyph in+-- the core's vertex layout: physical-pixel position, span colour, atlas UV.+-- Pen positions are 'foldPenPositions' at the atlas scale. Quads are clipped+-- to the span clip and a box of physical pixels, @(x0, y0, x1, y1)@, with UVs+-- cut to match, so text draws need no scissor. A span whose glyphs all lie+-- outside is skipped without visiting them. The buffer must have room for 6+-- vertices per character; returns the new vertex count.+writeSpanQuads :: GlyphAtlas -> CozetteFont -> (Int, Int, Int, Int) -> Ptr Word8 -> Int -> TextSpan -> IO Int+writeSpanQuads ga font box buf !n0 (Rect rx ry _ _, txt, fg, _, clip) =+ case physClipIn scale box clip of+ Nothing -> pure n0+ Just (cx0, cy0, cx1, cy1)+ -- No pen lies left of or above the span origin, and each line's pen+ -- lies at most 'lineStep' (plus a pixel of rounding) below the last.+ -- Counting lines is left for spans that begin above the box.+ | penX0 >= cx1 || penY0 >= cy1 -> pure n0+ | penY0 + gaCellH ga <= cy0 && penY0 + newlines * lineStep + gaCellH ga + 1 <= cy0 -> pure n0+ | otherwise ->+ let quad !n !penX !penY !glyph =+ let !gid = if fromIntegral glyph < cfNumGlyphs font then fromIntegral glyph else 0+ (!ax, !ay) = atlasCell ga gid+ !x0 = max cx0 penX+ !y0 = max cy0 penY+ !x1 = min cx1 (penX + gaCellW ga)+ !y1 = min cy1 (penY + gaCellH ga)+ u x = fromIntegral (ax + x - penX) / aw+ v y = fromIntegral (ay + y - penY) / ah+ in if x0 >= x1 || y0 >= y1+ then pure n+ else do+ vertex n x0 y0 (u x0) (v y0)+ vertex (n + 1) x1 y0 (u x1) (v y0)+ vertex (n + 2) x1 y1 (u x1) (v y1)+ vertex (n + 3) x0 y0 (u x0) (v y0)+ vertex (n + 4) x1 y1 (u x1) (v y1)+ vertex (n + 5) x0 y1 (u x0) (v y1)+ pure (n + 6)+ in foldPenPositions font scale rx ry n0 quad txt+ where+ !scale = gaScale ga+ !penX0 = roundHalfUp (rx * scale)+ !penY0 = roundHalfUp (ry * scale)+ newlines = T.count "\n" txt+ !lineStep = ceiling (cozetteLineHeight * scale) :: Int+ !aw = fromIntegral (gaWidth ga) :: Float+ !ah = fromIntegral (gaHeight ga) :: Float+ (!fr, !fgG, !fb, !fa) = colorFloats fg+ vertex :: Int -> Int -> Int -> Float -> Float -> IO ()+ vertex !i !x !y !u !v = do+ let !off = i * vertexSize+ pokeByteOff buf off (fromIntegral x :: Float)+ pokeByteOff buf (off + 4) (fromIntegral y :: Float)+ pokeByteOff buf (off + 8) fr+ pokeByteOff buf (off + 12) fgG+ pokeByteOff buf (off + 16) fb+ pokeByteOff buf (off + 20) fa+ pokeByteOff buf (off + 24) u+ pokeByteOff buf (off + 28) v++colorFloats :: Color -> (Float, Float, Float, Float)+colorFloats (Color w) = (chan 24, chan 16, chan 8, chan 0)+ where+ chan s = fromIntegral ((w `shiftR` s) .&. 0xFF) / 255
+ lib/NanoUI/Rgfw/Internal/Input.hs view
@@ -0,0 +1,243 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | Translation of RGFW events into 'NanoUI.Input.Input': key and modifier+-- tables, the cursor table, and the decoding of a drained event queue. The+-- session ("NanoUI.Rgfw.Internal.Session") polls the queue and folds the+-- decoded events into each frame's input.+module NanoUI.Rgfw.Internal.Input+ ( RgfwEvent (..)+ , pollRgfwEvents+ , prepareRgfwEvent+ , decodeRgfwEvents+ , applyRgfwEvent+ , isRgfwButtonEdge+ , isRgfwClose+ , mapRgfwCursor+ ) where++import Data.Bits (complement, (.&.), (.|.))+import Data.Char (chr, isControl, isDigit, toLower)+import Data.IORef (IORef, readIORef, writeIORef)+import Data.Maybe (mapMaybe)+import qualified Data.Text as T+import Data.Word (Word8, Word32)+import Foreign.Ptr (Ptr)+import NanoUI (V2 (..), v2Add)+import NanoUI.Backend+ ( Input (..)+ , Key (..)+ , Modifiers (..)+ , applyKey+ , applyMouseButton+ , applyPointerLeave+ , cursorFallback+ , keypadKey+ , modifiersFromBits+ , mouseButtonNumber+ , releaseAllKeys+ )+import NanoUI.Backend (UiCursorKind (..))+import qualified RGFW as R++-- | The key for an RGFW key code and its modifier bits.+mapRgfwKey :: Word32 -> Word8 -> Maybe Key+mapRgfwKey k m+ | Just named <- lookup k namedRgfwKeys = Just named+ | Just c <- lookup k keypadRgfwKeys = keypadKey (m .&. R.rgfw_modNumLock /= 0) c+ | k >= R.rgfw_keyF1 && k <= R.rgfw_keyF24 = Just (KeyF (fromIntegral (k - R.rgfw_keyF1) + 1))+ -- Codes below 128 are the ASCII characters the keys type unshifted on a US+ -- layout.+ | k > 32 && k < 127 = Just (KeyChar (toLower (chr (fromIntegral k))))+ | otherwise = Nothing++namedRgfwKeys :: [(Word32, Key)]+namedRgfwKeys =+ [ (R.rgfw_keyEscape, KeyEscape)+ , (R.rgfw_keyReturn, KeyEnter)+ , (R.rgfw_keyPadReturn, KeyEnter)+ , (R.rgfw_keyTab, KeyTab)+ , (R.rgfw_keyBackSpace, KeyBackspace)+ , (R.rgfw_keyDelete, KeyDelete)+ , (R.rgfw_keyLeft, KeyLeft)+ , (R.rgfw_keyRight, KeyRight)+ , (R.rgfw_keyUp, KeyUp)+ , (R.rgfw_keyDown, KeyDown)+ , (R.rgfw_keyHome, KeyHome)+ , (R.rgfw_keyEnd, KeyEnd)+ , (R.rgfw_keyPageUp, KeyPageUp)+ , (R.rgfw_keyPageDown, KeyPageDown)+ , (R.rgfw_keyInsert, KeyInsert)+ , (R.rgfw_keySpace, KeySpace)+ , (R.rgfw_keyPrintScreen, KeyPrintScreen)+ , (R.rgfw_keyPause, KeyPause)+ , (R.rgfw_keyCapsLock, KeyCapsLock)+ , (R.rgfw_keyNumLock, KeyNumLock)+ , (R.rgfw_keyScrollLock, KeyScrollLock)+ , (R.rgfw_keyMenu, KeyMenu)+ , (R.rgfw_keyPadSlash, KeyChar '/')+ , (R.rgfw_keyPadMultiply, KeyChar '*')+ , (R.rgfw_keyPadMinus, KeyChar '-')+ , (R.rgfw_keyPadPlus, KeyChar '+')+ , (R.rgfw_keyPadEqual, KeyChar '=')+ ]++-- | Keypad digit and point codes, by the character each types ('keypadKey').+keypadRgfwKeys :: [(Word32, Char)]+keypadRgfwKeys =+ zip+ [R.rgfw_keyPad0, R.rgfw_keyPad1, R.rgfw_keyPad2, R.rgfw_keyPad3, R.rgfw_keyPad4, R.rgfw_keyPad5, R.rgfw_keyPad6, R.rgfw_keyPad7, R.rgfw_keyPad8, R.rgfw_keyPad9, R.rgfw_keyPadPeriod]+ "0123456789."++modsFromRgfw :: Word8 -> Modifiers+modsFromRgfw m = modifiersFromBits m R.rgfw_modShift R.rgfw_modControl R.rgfw_modAlt R.rgfw_modSuper++-- | The modifier bits of a key event, counting the key itself. On X11 and+-- Windows RGFW reads the bits before it records the key, so a modifier key's+-- press lacks its own bit and its release still has it. On macOS the bits+-- are already current.+ownModifier :: Word32 -> Bool -> Word8 -> Word8+ownModifier k down m = case lookup k modifierRgfwKeys of+ Just (bit, _) -> if down then m .|. bit else m .&. complement bit+ Nothing -> m++-- | Modifier keys, with their bit and the key on the other side.+modifierRgfwKeys :: [(Word32, (Word8, Word32))]+modifierRgfwKeys =+ [ (R.rgfw_keyShiftL, (R.rgfw_modShift, R.rgfw_keyShiftR))+ , (R.rgfw_keyShiftR, (R.rgfw_modShift, R.rgfw_keyShiftL))+ , (R.rgfw_keyControlL, (R.rgfw_modControl, R.rgfw_keyControlR))+ , (R.rgfw_keyControlR, (R.rgfw_modControl, R.rgfw_keyControlL))+ , (R.rgfw_keyAltL, (R.rgfw_modAlt, R.rgfw_keyAltR))+ , (R.rgfw_keyAltR, (R.rgfw_modAlt, R.rgfw_keyAltL))+ , (R.rgfw_keySuperL, (R.rgfw_modSuper, R.rgfw_keySuperR))+ , (R.rgfw_keySuperR, (R.rgfw_modSuper, R.rgfw_keySuperL))+ ]++-- | The RGFW standard cursor for a cursor kind, after 'cursorFallback'.+-- 'R.rgfw_mouseArrow' stands for the platform's default arrow.+mapRgfwCursor :: UiCursorKind -> Word8+mapRgfwCursor kind = case cursorFallback kind of+ UiCursorPointer -> R.rgfw_mousePointingHand+ UiCursorText -> R.rgfw_mouseIbeam+ UiCursorNsResize -> R.rgfw_mouseResizeNS+ UiCursorEwResize -> R.rgfw_mouseResizeEW+ UiCursorNwseResize -> R.rgfw_mouseResizeNWSE+ UiCursorNeswResize -> R.rgfw_mouseResizeNESW+ UiCursorNotAllowed -> R.rgfw_mouseNotAllowed+ UiCursorWait -> R.rgfw_mouseWait+ UiCursorProgress -> R.rgfw_mouseProgress+ UiCursorCrosshair -> R.rgfw_mouseCrosshair+ UiCursorMove -> R.rgfw_mouseResizeAll+ UiCursorNResize -> R.rgfw_mouseResizeN+ UiCursorNeResize -> R.rgfw_mouseResizeNE+ UiCursorEResize -> R.rgfw_mouseResizeE+ UiCursorSeResize -> R.rgfw_mouseResizeSE+ UiCursorSResize -> R.rgfw_mouseResizeS+ UiCursorSwResize -> R.rgfw_mouseResizeSW+ UiCursorWResize -> R.rgfw_mouseResizeW+ UiCursorNwResize -> R.rgfw_mouseResizeNW+ _ -> R.rgfw_mouseArrow++-- | An RGFW event translated for the input fold.+data RgfwEvent+ = RgfwEvClose+ | RgfwEvResize -- ^ window size or monitor scale changed (read back at sync)+ | RgfwEvMotion !Float !Float+ | RgfwEvButton !Word8 !Bool+ | RgfwEvLeave -- ^ the pointer left the window+ | RgfwEvScroll !Float !Float+ | RgfwEvChar !Char -- ^ typed character+ | RgfwEvKey !Word32 !Word8 !Bool -- ^ key, modifiers, down (including repeats) or up+ | RgfwEvFocusLost -- ^ the window lost keyboard focus+ | RgfwEvRedraw -- ^ the window was uncovered or restored: paint it all++-- | Drain the RGFW queue, recording scale changes for the next sync, which+-- reads the window size itself. Character keys are remapped to the current+-- layout (@layoutKey@).+pollRgfwEvents :: R.Window -> Ptr R.RGFW_event -> IORef Float -> IORef Float -> IO [RgfwEvent]+pollRgfwEvents win evPtr scaleRef monScaleRef = do+ raw <- drain []+ scale <- readIORef scaleRef+ pure (decodeRgfwEvents scale raw)+ where+ drain acc =+ R.pollEvent win evPtr >>= \case+ R.EventNone -> pure (reverse acc)+ ev -> prepareRgfwEvent monScaleRef ev >>= \ev' -> drain (ev' : acc)++-- | Read one raw event before decoding: record a scale change for the next+-- sync, and remap a key to the current layout.+prepareRgfwEvent :: IORef Float -> R.Event -> IO R.Event+prepareRgfwEvent monScaleRef ev = case ev of+ R.EventScaleUpdate sx _ -> ev <$ writeIORef monScaleRef (if sx > 0 then sx else 1)+ R.EventKeyPress k m -> relayout R.EventKeyPress k m+ R.EventKeyRepeat k m -> relayout R.EventKeyRepeat k m+ -- A modifier key let go while the one on the other side is down+ -- leaves the modifier held, as that key's repeat would.+ R.EventKeyRelease k m+ | Just (_, twin) <- lookup k modifierRgfwKeys ->+ (\held -> if held then R.EventKeyRepeat twin m else ev) <$> R.isKeyDown twin+ | otherwise -> relayout R.EventKeyRelease k m+ _ -> pure ev+ where+ relayout event k m = (\k' -> event k' m) <$> layoutKey k+ -- RGFW key codes are what the key types on a US layout. Letter and+ -- punctuation keys are remapped to the current layout when the result is+ -- ASCII. Digits stay, since some layouts type symbols there unshifted.+ layoutKey k+ | k > 32 && k < 127 && not (isDigit (chr (fromIntegral k))) =+ maybe k (\mapped -> if mapped > 32 && mapped < 127 then mapped else k) <$> R.physicalToMappedKey k+ | otherwise = pure k++-- | Translate a batch of raw events in queue order. Pointer positions are+-- divided by the logical scale. Control characters are dropped: some+-- platforms send Ctrl+letter as one, and the key event already reports the+-- chord.+decodeRgfwEvents :: Float -> [R.Event] -> [RgfwEvent]+decodeRgfwEvents scale = mapMaybe $ \case+ R.EventWindowClose -> Just RgfwEvClose+ R.EventWindowResize _ _ -> Just RgfwEvResize+ R.EventScaleUpdate _ _ -> Just RgfwEvResize+ R.EventMouseMotion x y -> Just (RgfwEvMotion (fromIntegral x / scale) (fromIntegral y / scale))+ R.EventMouseButton btn down -> Just (RgfwEvButton btn down)+ -- RGFW's wheel is positive up and left; the input's is down and right.+ R.EventMouseScroll dx dy -> Just (RgfwEvScroll (negate dx) (negate dy))+ R.EventOther t+ | t == R.rgfw_mouseLeave -> Just RgfwEvLeave+ | t == R.rgfw_windowFocusOut -> Just RgfwEvFocusLost+ | t == R.rgfw_windowRefresh || t == R.rgfw_windowRestored -> Just RgfwEvRedraw+ R.EventKeyPress k m -> Just (RgfwEvKey k m True)+ R.EventKeyRepeat k m -> Just (RgfwEvKey k m True)+ R.EventKeyRelease k m -> Just (RgfwEvKey k m False)+ -- Every character but the controls types, joiners and bidi marks included.+ -- On macOS, RGFW passes on the private-use characters AppKit gives arrow+ -- and function keys (U+F700 to U+F747), which type nothing. The rest of+ -- the private-use area types, the Apple logo (U+F8FF) among it.+ R.EventKeyChar ch | not (isControl ch) && not (ch >= '\xF700' && ch <= '\xF747') -> Just (RgfwEvChar ch)+ _ -> Nothing++-- | Accumulate a decoded event into frame input. The caller handles close+-- and resize events separately; motion coordinates are already scaled by decoding.+applyRgfwEvent :: Input -> RgfwEvent -> Input+applyRgfwEvent inp ev = case ev of+ RgfwEvClose -> inp+ RgfwEvResize -> inp+ RgfwEvMotion x y -> inp {inputMousePos = V2 x y}+ -- RGFW numbers buttons from 0 in 'mouseButtonNumber' order: left, middle,+ -- right, back, forward, then the rest.+ RgfwEvButton btn down -> applyMouseButton (mouseButtonNumber (fromIntegral btn + 1)) down inp+ -- A drag keeps its pointer ('applyPointerLeave').+ RgfwEvLeave -> applyPointerLeave inp+ RgfwEvScroll dx dy -> inp {inputScroll = v2Add (inputScroll inp) (V2 dx dy)}+ RgfwEvChar c -> inp {inputChars = T.snoc (inputChars inp) c}+ -- 'applyKey' detects auto-repeat because the key is already held.+ RgfwEvKey k m down ->+ (maybe inp (\key -> applyKey key down inp) (mapRgfwKey k m)) {inputModifiers = modsFromRgfw (ownModifier k down m)}+ RgfwEvFocusLost -> releaseAllKeys inp+ RgfwEvRedraw -> inp {inputWindowRedraw = True}++-- | Whether an event presses or releases a mouse button, and whether it+-- closes the window.+isRgfwButtonEdge, isRgfwClose :: RgfwEvent -> Bool+isRgfwButtonEdge = \case RgfwEvButton {} -> True; _ -> False+isRgfwClose = \case RgfwEvClose -> True; _ -> False
+ lib/NanoUI/Rgfw/Internal/Session.hs view
@@ -0,0 +1,616 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | The RGFW window session: options, the runners, the window and its+-- OpenGL presentation. The events it polls are translated into+-- 'NanoUI.Input.Input' by "NanoUI.Rgfw.Internal.Input".+--+-- RGFW reports no IME composition. On X11, as on Windows, its input context+-- leaves drawing the composition to the input method, and committed text+-- arrives as key-char events. So 'NanoUI.Input.inputComposition' stays+-- 'Nothing', and fields receive committed text as typing.+--+-- Files dropped on the window are not reported: 'NanoUI.Input.inputDrops'+-- stays empty, so drop zones see no drops.+module NanoUI.Rgfw.Internal.Session+ ( RgfwOptions (..)+ , defaultRgfwOptions+ , runRgfwApp+ , runRgfwAppWith+ , runRgfwAppReduce+ , runRgfwAppReduceCustom+ , runRgfwAppReduceCustomWith+ -- * Input translation+ -- (defined in "NanoUI.Rgfw.Internal.Input")+ , RgfwEvent+ , decodeRgfwEvents+ , applyRgfwEvent+ -- * Cursors+ , mapRgfwCursor+ ) where++import Control.Exception (bracket, finally, onException)+import Control.Monad (forM_, unless, void, when)+import Data.Bits ((.&.), (.|.))+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.List (find)+import Data.Maybe (fromMaybe)+import qualified Data.Text as T+import Foreign.Ptr (Ptr, nullPtr)+import GHC.Clock (getMonotonicTime)+import NanoUI+ ( Appearance+ , NanoUI+ , Size (..)+ , Theme (..)+ , V2 (..)+ , WindowMode (..)+ , WindowPosition (..)+ , WindowSettings (..)+ , defaultWindowSettings+ , rgbaBytes+ , rgbaHeight+ , rgbaWidth+ )+import NanoUI.Themes (tomorrowNightMinDarkTheme)+import NanoUI.Backend+ ( Damage (..)+ , Input (..)+ , WindowCapabilities (..)+ , WindowHost (..)+ , WindowState (..)+ , allWindowCapabilities+ , answerScreenshots+ , cancelTasks+ , closeWindowHost+ , applyPointerLeave+ , defaultWindowHost+ , defaultWindowState+ , emptyInput+ , inBoundThread+ , installWindowHost+ , reportWindowState+ , setExplainLayout+ , setDrawPixelScale+ , setWakeLoop+ , sizeLimitAt+ , syncCursorKind+ , withBackendSession+ )+import NanoUI.Internal.Context+ ( Context (..)+ , retainedFrameStale+ , setBackendSession+ , withClipboard+ , withFramePaint+ )+import NanoUI.Backend+ ( DrawData (..)+ , UiCursorKind (..)+ , runFrame+ , collectRasterSpans+ , damageIsEmpty+ , takeDamage+ , takeDamagePieces+ , uiCursorKind+ )+import NanoUI.Internal.Debug (noteDebugFrame, noteDebugSkip)+import NanoUI.Emit (NanoUIE, newReducer, reduceFrame, reducerModel)+import NanoUI.Runner+ ( SessionDriver (..)+ , pacingMsFor+ , runSessionLoop+ , shouldRedrawFrame+ )+import NanoUI.Runner.Windows (WindowOps (..), afterMainPass, closeWindows, loopWindows, newWindows, openWindows)+import NanoUI.Internal.Layout.Arena (arenaCount)+import NanoUI.Rgfw.Internal.Context (applyRgfwTheme, newRgfwContext)+import NanoUI.Rgfw.Internal.Debug+ ( RgfwDebugSampler (..)+ , RgfwFrameStats (..)+ , newRgfwDebugSampler+ , rgfwSession+ )+import NanoUI.Rgfw.Internal.Font.Cozette (getCozetteFont)+import NanoUI.Rgfw.Internal.Input+ ( RgfwEvent+ , applyRgfwEvent+ , decodeRgfwEvents+ , isRgfwButtonEdge+ , isRgfwClose+ , mapRgfwCursor+ , pollRgfwEvents+ , prepareRgfwEvent+ )+import NanoUI.Rgfw.Internal.Gl (GlRenderer, freeGlRenderer, newGlRenderer, renderArenaGl, retainedPixels, syncImagesGl)+import qualified RGFW as R++-- | Window and rendering options for the RGFW runners.+data RgfwOptions = RgfwOptions+ { optWindow :: !WindowSettings+ -- ^ The window (default: 'defaultWindowSettings'). Sizes are in layout+ -- units, converted at the opening scale. RGFW places windows itself, so+ -- 'WindowPositionDefault' centres the window. 'wsTransparent' and+ -- 'wsOpacity' do nothing: RGFW windows are always opaque.+ , optTheme :: !Theme+ -- ^ Any core theme; the backend draws it square ('NanoUI.Backend.Rgfw.applyRgfwTheme').+ -- The @Custom@ runners take the theme from the model instead.+ , optThemeFor :: !(Maybe (Maybe Appearance -> Theme))+ -- ^ Pick the theme from the desktop's light or dark setting, such as+ -- @'NanoUI.lightDark' light dark@, like SDL's @sdlAppThemeFor@ (default:+ -- 'Nothing'). When set it replaces 'optTheme'. RGFW cannot read the+ -- setting, so the function gets 'Nothing' and 'NanoUI.lightDark' picks+ -- dark. The @Custom@ runners take the theme from the model instead.+ , optScale :: !Float+ -- ^ UI scale. @0@ follows the monitor's scale.+ , optRefreshHz :: !Int+ -- ^ Frame pacing rate while animating. @0@ means 60.+ , optExplainLayout :: !Bool+ -- ^ Start with the layout overlay (an outline of every layout node) on.+ -- Views toggle it with @explainLayout@.+ }++-- | A 'defaultWindowSettings' window with the dark theme, the monitor's+-- scale, and 60 Hz animation pacing.+defaultRgfwOptions :: RgfwOptions+defaultRgfwOptions =+ RgfwOptions+ { optWindow = defaultWindowSettings+ , optTheme = tomorrowNightMinDarkTheme+ , optThemeFor = Nothing+ , optScale = 0.0+ , optRefreshHz = 0+ , optExplainLayout = False+ }++-- | 'optThemeFor' applied to 'Nothing', since RGFW cannot read the+-- appearance; else 'optTheme'.+optionsTheme :: RgfwOptions -> Theme+optionsTheme opts = maybe (optTheme opts) ($ Nothing) (optThemeFor opts)++-- | Run a view in an owned RGFW/OpenGL window until quit. Native resources are+-- released on exit. Throws an 'IOError' when the window or its OpenGL 3.2+-- context cannot be created.+runRgfwApp :: RgfwOptions -> NanoUI () -> IO ()+runRgfwApp opts app = runRgfwAppReduce opts (\() m -> m) () (\_ -> app)++-- | 'runRgfwApp' with a setup action run once the window and its OpenGL+-- context exist, before the first frame, that returns the view.+runRgfwAppWith :: RgfwOptions -> IO (NanoUI ()) -> IO ()+runRgfwAppWith opts setup =+ runRgfwAppReduceCustomWith opts (\_ -> (optionsTheme opts, optScale opts)) (\() m -> m) () setup (\app _ -> app)++-- | Model-driven runner. Fold emitted messages through the update function+-- in order, with the message type checked at compile time.+runRgfwAppReduce ::+ Eq model =>+ RgfwOptions ->+ (msg -> model -> model) ->+ model ->+ (model -> NanoUIE msg ()) ->+ IO ()+runRgfwAppReduce opts =+ runRgfwAppReduceCustom opts (\_ -> (optionsTheme opts, optScale opts))++-- | Reducer runner whose theme and UI scale are derived from the current+-- model. A non-positive scale falls back to 'optScale', then the monitor's.+-- 'optTheme' and 'optThemeFor' are not used; the model supplies the theme.+-- OpenGL calls remain on the creating OS thread; native resources are+-- released on exit.+runRgfwAppReduceCustom ::+ Eq model =>+ RgfwOptions ->+ (model -> (Theme, Float)) ->+ (msg -> model -> model) ->+ model ->+ (model -> NanoUIE msg ()) ->+ IO ()+runRgfwAppReduceCustom opts getThemeAndScale updateModel initialModel view =+ runRgfwAppReduceCustomWith opts getThemeAndScale updateModel initialModel (pure ()) (\_ -> view)++-- | 'runRgfwAppReduceCustom' with a setup action run once the window and its+-- OpenGL context exist, before the first frame, whose result the view takes.+runRgfwAppReduceCustomWith ::+ Eq model =>+ RgfwOptions ->+ (model -> (Theme, Float)) ->+ (msg -> model -> model) ->+ model ->+ IO env ->+ (env -> model -> NanoUIE msg ()) ->+ IO ()+runRgfwAppReduceCustomWith opts getThemeAndScale updateModel initialModel setup appView = inBoundThread $ do+ sh <- RgfwShared opts <$> newIORef (snd (getThemeAndScale initialModel)) <*> newIORef Nothing+ bracket (createRgfwWindow sh settings) R.closeWindow (runWindow sh)+ where+ settings = optWindow opts+ runWindow sh win = do+ rw <- setupRgfwWindow sh settings win+ reducer <- newReducer updateModel initialModel+ let initTheme = fst (getThemeAndScale initialModel)+ -- The theme last applied, before squaring: comparing it with the+ -- model's theme skips rebuilding the squared theme on every frame.+ themeRef <- newIORef initTheme+ ctx <- newRgfwWindowContext initTheme+ env <- setup+ setExplainLayout ctx (optExplainLayout opts)+ installRgfwHost settings rw ctx+ initInp <- rgfwOpeningInput rw++ let cleanup = closeRgfwContext ctx+ release r = cleanup `finally` (useGl sh win >> freeGlRenderer r)+ bracket (newGlRenderer `onException` cleanup) release $ \renderer -> R.withEventBuffer $ \evPtr -> do+ windows <- newWindows (childOps sh)+ let drawOne force c curInp =+ presentRgfw sh rw renderer force c curInp $ do+ curModel <- reducerModel reducer+ let (frameTheme, _) = getThemeAndScale curModel+ appliedTheme <- readIORef themeRef+ when (frameTheme /= appliedTheme) $ do+ writeIORef themeRef frameTheme+ applyRgfwTheme c frameTheme+ -- A reduced message that switched themes changed the model, so+ -- the core marks the frame dirty and the next one applies it.+ reduceFrame reducer c curInp (appView env)+ -- With further windows open, one drain takes every window's+ -- events and queues the others' on them; with none, this+ -- window's own events are taken as in a session of one.+ pollMain = do+ kids <- openWindows windows+ if null kids+ then pollRgfwEvents win evPtr (rwScale rw) (rwMonScale rw)+ else drainRgfwEvents evPtr rw [(rwWin (rcWindow c), (c, queue)) | (c, queue) <- kids]+ drv =+ SessionDriver+ { sdPollEvents = pollMain+ , sdWaitEvents = \t -> R.waitForEvent t >> pollMain+ , sdPacedWait = Nothing+ , sdApplyEvent = applyRgfwEvent+ , sdIsButtonEdge = isRgfwButtonEdge+ , sdIsSessionQuit = isRgfwClose+ , sdSyncDisplay = \c inp -> do+ curModel <- reducerModel reducer+ writeIORef (rsUserScale sh) $! snd (getThemeAndScale curModel)+ syncRgfwDisplay sh rw c inp+ , sdDebug = rdsSampler (rwDebug rw)+ , sdContinuous = False+ , sdVsyncOff = True+ -- Presents are unthrottled (swap interval 0, no vsync), so a+ -- live in-view animation is paced at the refresh period+ -- instead of spinning.+ , sdPacingMs = rgfwPacingMs opts+ , sdPresentPaces = pure False+ , sdShouldDraw = \c prevInp inpSynced wasAnim refreshDue ->+ shouldRedrawFrame c prevInp inpSynced wasAnim False refreshDue+ , sdDraw = \c curInp forceFull -> drawOne forceFull c curInp+ , sdOnCursor = syncRgfwCursor rw+ , sdShouldQuit = \_ -> False+ , sdAlignSec = 1 / fromIntegral (rgfwRefreshHz opts)+ , sdWindows = Just (loopWindows windows)+ }+ -- Present the opening frame before entering the loop so the window has+ -- content immediately; once idle the loop blocks with no redraws. If+ -- the opening frame marked the context dirty, the loop draws the+ -- follow-up frame immediately instead of blocking for input. The+ -- windows it declared open now. Views find the debug sampler on the+ -- context ('askRgfwDebug').+ withBackendSession ctx rgfwSession (rwDebug rw) $ do+ _ <- drawOne True ctx initInp+ afterMainPass windows ctx+ runSessionLoop drv ctx initInp `finally` closeWindows windows++-- | What the windows of one RGFW session share: the options, the UI scale+-- the model asks for, and the window whose OpenGL context is current.+data RgfwShared = RgfwShared+ { rsOpts :: !RgfwOptions+ , rsUserScale :: !(IORef Float)+ , rsCurrent :: !(IORef (Maybe R.Window))+ }++-- | One window and the state drawing into it needs.+data RgfwWindow = RgfwWindow+ { rwWin :: !R.Window+ , rwScale :: !(IORef Float)+ , rwMonScale :: !(IORef Float)+ , rwSize :: !(IORef (Int, Int))+ , rwPresented :: !(IORef (Int, Int, Float))+ -- ^ Physical size and scale of the last presented frame. The retained+ -- framebuffer holds that frame, so a frame at another size or scale has+ -- nothing to keep and paints in full.+ , rwCursor :: !(IORef UiCursorKind)+ , rwDebug :: !RgfwDebugSampler+ }++rgfwRefreshHz :: RgfwOptions -> Int+rgfwRefreshHz opts = if optRefreshHz opts > 0 then optRefreshHz opts else 60++rgfwPacingMs :: RgfwOptions -> Int+rgfwPacingMs opts = pacingMsFor (1 / fromIntegral (rgfwRefreshHz opts))++-- | The model's scale, else the options', else the monitor's.+resolveScale :: RgfwOptions -> Float -> Float -> Float+resolveScale opts userScale monScale = fromMaybe 1 (find (> 0) [userScale, optScale opts, monScale])++-- | Native pixel size of a layout size at a scale.+pixelsAt :: Float -> Size -> (Int, Int)+pixelsAt scale (Size w h) = (max 1 (round (w * scale)), max 1 (round (h * scale)))++-- | Native pixels to layout units at a scale.+logicalSize :: (Int, Int) -> Float -> Size+logicalSize (pw, ph) scale = Size (units pw) (units ph)+ where+ units v = fromIntegral (max 1 (round (fromIntegral v / scale) :: Int))++-- | Open a window for the settings, hidden, at the requested scale: the+-- monitor's scale is unknown until the window exists. 'setupRgfwWindow'+-- sizes it once that scale is known, and 'installRgfwHost' shows it. Its+-- OpenGL context is current afterwards.+createRgfwWindow :: RgfwShared -> WindowSettings -> IO R.Window+createRgfwWindow sh settings = do+ userScale <- readIORef (rsUserScale sh)+ let flags =+ R.rgfw_windowHide+ .|. (if wsResizable settings then 0 else R.rgfw_windowNoResize)+ .|. (if wsMode settings == Fullscreen then R.rgfw_windowFullscreen else 0)+ (openW, openH) = pixelsAt (resolveScale (rsOpts sh) userScale 1) (wsSize settings)+ R.createWindowGL (T.unpack (wsTitle settings)) 0 0 openW openH flags 3 2 >>= \case+ Nothing -> fail "nano-ui-rgfw: could not create a window with an OpenGL 3.2 core context"+ Just win -> win <$ writeIORef (rsCurrent sh) (Just win)++-- | Size a window just opened at its monitor's scale.+setupRgfwWindow :: RgfwShared -> WindowSettings -> R.Window -> IO RgfwWindow+setupRgfwWindow sh settings win = do+ userScale <- readIORef (rsUserScale sh)+ monScaleInit <- R.windowScale win+ let opts = rsOpts sh+ !monScale = if monScaleInit > 0.0 then monScaleInit else 1.0+ !scale = resolveScale opts userScale monScale+ -- A window opened fullscreen already covers its monitor, and resizing it+ -- would shrink it on Windows.+ phys <-+ if wsMode settings == Fullscreen+ then R.windowSize win+ else do+ let phys = pixelsAt scale (wsSize settings)+ when (phys /= pixelsAt (resolveScale opts userScale 1) (wsSize settings)) $ uncurry (R.resizeWindow win) phys+ pure phys+ RgfwWindow win+ <$> newIORef scale+ <*> newIORef monScale+ <*> newIORef phys+ <*> newIORef (0, 0, 0)+ <*> newIORef UiCursorDefault+ <*> newRgfwDebugSampler++-- | The opening input: the window's size, and the pointer off the window+-- until an entry or a motion says where it is, not on the widget in the+-- top-left corner.+rgfwOpeningInput :: RgfwWindow -> IO Input+rgfwOpeningInput rw = do+ phys <- readIORef (rwSize rw)+ scale <- readIORef (rwScale rw)+ pure (applyPointerLeave emptyInput {inputWindowSize = logicalSize phys scale})++-- | A context for a window's view, with the theme squared and the+-- clipboard, and a wake that ends the event wait (or the next one).+newRgfwWindowContext :: Theme -> IO Context+newRgfwWindowContext theme = do+ ctx <- (\c -> withClipboard c R.readClipboardText R.writeClipboardText) <$> newRgfwContext theme+ ctx <$ setWakeLoop ctx R.stopWaitForEvent++-- | Cancel a window's view's requests and background jobs, as it closes.+closeRgfwContext :: Context -> IO ()+closeRgfwContext ctx = closeWindowHost ctx `finally` cancelTasks ctx++-- | Install the host that carries out a view's window requests, report the+-- window's state, and show it unless the settings hide it.+installRgfwHost :: WindowSettings -> RgfwWindow -> Context -> IO ()+installRgfwHost settings rw ctx = do+ -- Size limits are in layout units, converted at the current scale.+ let win = rwWin rw+ limit set s = do+ scale <- readIORef (rwScale rw)+ uncurry (set win) (sizeLimitAt scale (0, 0) s)+ place = case wsPosition settings of+ WindowPositionDefault -> WindowPositionCentered+ p -> p+ installWindowHost ctx settings {wsPosition = place} $+ defaultWindowHost+ { hostCapabilities = allWindowCapabilities {wcOpacity = False}+ , hostSetTitle = R.setWindowName win+ , hostSetIcon = \p -> void (R.setWindowIcon win (rgbaWidth p) (rgbaHeight p) (rgbaBytes p))+ , hostSetMinSize = limit R.setWindowMinSize+ , hostSetMaxSize = limit R.setWindowMaxSize+ -- No 'hostSetOpacity': RGFW windows cannot fade.+ , hostSetMode = \case+ -- Leaving fullscreen restores the geometry saved on entering+ -- it, which on Windows a windowed window has none of.+ Windowed -> do+ full <- (\f -> f .&. R.rgfw_windowFullscreen /= 0) <$> R.windowFlags win+ when full (R.setWindowFullscreen win False)+ R.showWindow win+ Fullscreen -> R.showWindow win >> R.setWindowFullscreen win True+ Hidden -> R.hideWindow win+ , hostMove = R.moveWindow win+ , hostCenter = R.centerWindow win+ , hostResize = \s -> readIORef (rwScale rw) >>= \scale -> uncurry (R.resizeWindow win) (pixelsAt scale s)+ , hostMinimize = R.minimizeWindow win+ , hostMaximize = R.maximizeWindow win+ , hostRestore = R.restoreWindow win+ }+ reportWindowState ctx =<< rgfwWindowState win =<< readIORef (rwScale rw)+ unless (wsMode settings == Hidden) (R.showWindow win)++-- | Make the window's OpenGL context current, unless it is.+useGl :: RgfwShared -> R.Window -> IO ()+useGl sh win = do+ cur <- readIORef (rsCurrent sh)+ unless (cur == Just win) $ R.makeCurrentGL win >> writeIORef (rsCurrent sh) (Just win)++-- | Read the window's size and scale into the frame's input.+syncRgfwDisplay :: RgfwShared -> RgfwWindow -> Context -> Input -> IO (Context, Input)+syncRgfwDisplay sh rw c inp = do+ -- A minimized window reports 0x0 (on Windows): keep the last real size.+ (curWinW, curWinH) <- R.windowSize (rwWin rw)+ (pw0, ph0) <- readIORef (rwSize rw)+ let (pw, ph) = if curWinW > 0 && curWinH > 0 then (curWinW, curWinH) else (pw0, ph0)+ writeIORef (rwSize rw) (pw, ph)+ curMonScale <- readIORef (rwMonScale rw)+ userScale <- readIORef (rsUserScale sh)+ oldScale <- readIORef (rwScale rw)+ let !newScale = resolveScale (rsOpts sh) userScale curMonScale+ -- Motion was divided by the old scale when decoded.+ V2 mx my = inputMousePos inp+ !k = oldScale / newScale+ mouse = if k == 1 then inputMousePos inp else V2 (mx * k) (my * k)+ writeIORef (rwScale rw) newScale+ setDrawPixelScale c newScale+ reportWindowState c =<< rgfwWindowState (rwWin rw) newScale+ pure (c, inp {inputWindowSize = logicalSize (pw, ph) newScale, inputMousePos = mouse})++-- | Touch the platform cursor only when the wanted kind changes.+-- 'UiCursorHidden' hides the pointer. Each window has its own.+syncRgfwCursor :: RgfwWindow -> Context -> Input -> IO ()+syncRgfwCursor rw c inp = uiCursorKind c inp >>= syncCursorKind (rwCursor rw) (R.showMouse win) (setIcon . mapRgfwCursor)+ where+ win = rwWin rw+ setIcon icon = void $ if icon == R.rgfw_mouseArrow then R.setMouseDefault win else R.setMouseStandard win icon++-- | Run a frame's UI pass and present it. A frame whose damage is empty+-- would swap in the picture already on screen, so it skips the render and+-- the swap: an animation scrolled out of view costs its UI pass and nothing+-- on the GPU. The opening frame and an animation's settle frame are forced.+-- Other frames paint only their damage over the retained last frame.+presentRgfw :: RgfwShared -> RgfwWindow -> GlRenderer -> Bool -> Context -> Input -> IO (a, DrawData, Bool) -> IO Bool+presentRgfw sh rw renderer force c curInp runUi = do+ useGl sh win+ tUiStart <- getMonotonicTime+ curScale <- readIORef (rwScale rw)+ setDrawPixelScale c curScale+ (pw, ph) <- readIORef (rwSize rw)+ presented <- readIORef (rwPresented rw)+ let !paintFull = retainedFrameStale force curInp presented (pw, ph, curScale)+ -- A full frame draws whole whatever its damage, so its pass works none+ -- out.+ (_, drawData, dirtyAfterUi) <- withFramePaint c paintFull paintFull runUi+ tUiEnd <- getMonotonicTime+ damage <- takeDamage c+ if damageIsEmpty damage && not paintFull+ then do+ noteDebugSkip (rdsSampler debugSampler)+ -- Nothing was drawn, so the retained framebuffer holds this frame.+ answerScreenshots c (retainedPixels renderer pw ph)+ pure dirtyAfterUi+ else do+ curMonScale <- readIORef (rwMonScale rw)+ (baseSpans, overlaySpans) <- collectRasterSpans c curInp+ pieces <- if paintFull then pure [] else takeDamagePieces c+ syncImagesGl renderer c+ -- A full frame clears to the draw data's colour, the page+ -- over the window colour of the theme it was painted in.+ renderArenaGl renderer getCozetteFont curScale pw ph+ (if paintFull then DamageFull else damage) pieces drawData baseSpans overlaySpans+ writeIORef (rwPresented rw) $! (pw, ph, curScale)+ tSwapStart <- getMonotonicTime+ R.swapBuffersGL win+ tSwapEnd <- getMonotonicTime+ answerScreenshots c (retainedPixels renderer pw ph)+ nodes <- arenaCount (ctxNodeArena c)+ noteDebugFrame (rdsSampler debugSampler) tUiStart tUiEnd tSwapStart tSwapEnd drawData+ writeIORef (rdsFrame debugSampler)+ RgfwFrameStats+ { fsNodes = nodes+ , fsPhysW = pw+ , fsPhysH = ph+ , fsScale = curScale+ , fsMonScale = curMonScale+ }+ pure dirtyAfterUi+ where+ win = rwWin rw+ debugSampler = rwDebug rw++-- | A further window ('NanoUI.nativeWindow'): the window, its renderer, and+-- the context its view runs on.+data RgfwChild = RgfwChild+ { rcWindow :: !RgfwWindow+ , rcRenderer :: !GlRenderer+ , rcContext :: !Context+ }++-- | How the session opens, draws and closes further windows. Each has its+-- own OpenGL context and renderer; the first window's drain queues their+-- events ('drainRgfwEvents').+childOps :: RgfwShared -> WindowOps RgfwChild RgfwEvent+childOps sh =+ WindowOps+ { -- A step that throws undoes those before it, in reverse: the+ -- renderer is freed with its window's OpenGL context current, the+ -- view's context closed, and the window closed, as 'woClose' does.+ woOpen = \parentCtx settings -> do+ win <- createRgfwWindow sh settings+ (`onException` (R.closeWindow win >> writeIORef (rsCurrent sh) Nothing)) $ do+ rw <- setupRgfwWindow sh settings win+ ctx <- newRgfwWindowContext =<< readIORef (ctxTheme parentCtx)+ (`onException` closeRgfwContext ctx) $ do+ renderer <- newGlRenderer+ (`onException` (useGl sh win >> freeGlRenderer renderer)) $ do+ installRgfwHost settings rw ctx+ setBackendSession ctx rgfwSession (rwDebug rw)+ pure (RgfwChild rw renderer ctx, ctx)+ , woClose = \c -> do+ let win = rwWin (rcWindow c)+ closeRgfwContext (rcContext c) `finally` do+ useGl sh win+ freeGlRenderer (rcRenderer c)+ R.closeWindow win+ writeIORef (rsCurrent sh) Nothing+ , woApplyEvent = applyRgfwEvent+ , woIsButtonEdge = isRgfwButtonEdge+ , woIsClose = isRgfwClose+ , woSync = syncRgfwDisplay sh . rcWindow+ , woDraw = \c ctx view inp force -> presentRgfw sh (rcWindow c) (rcRenderer c) force ctx inp (runFrame ctx inp view)+ -- Each window has its own cursor.+ , woCursor = syncRgfwCursor . rcWindow+ , woPacingMs = \_ -> rgfwPacingMs (rsOpts sh)+ -- Resizes are drawn by the loop's passes only.+ , woWatchResize = \_ _ -> pure (pure ())+ }++-- | Take every window's events: the first window's are answered, and each+-- further window's queued on it. Events for a window just closed go nowhere.+drainRgfwEvents :: Ptr R.RGFW_event -> RgfwWindow -> [(R.Window, (RgfwChild, RgfwEvent -> IO ()))] -> IO [RgfwEvent]+drainRgfwEvents evPtr first kids = do+ raw <- go []+ forM_ kids $ \(win, (c, queue)) -> decodeFor (rcWindow c) [ev | (w, ev) <- raw, w == win] >>= mapM_ queue+ decodeFor first [ev | (w, ev) <- raw, w == rwWin first || w == R.Window nullPtr]+ where+ -- Prepared in queue order, for the window each is for: a scale change+ -- applies to that window's later events.+ go acc =+ R.pollAnyEvent evPtr >>= \case+ Nothing -> pure (reverse acc)+ Just (win, ev) -> do+ let target = maybe first (rcWindow . fst) (lookup win kids)+ ev' <- prepareRgfwEvent (rwMonScale target) ev+ go ((win, ev') : acc)+ decodeFor rw evs+ | null evs = pure []+ | otherwise = (`decodeRgfwEvents` evs) <$> readIORef (rwScale rw)++-- | The window's state at a scale, from what RGFW tracks through its events,+-- so reading it costs no round trip to the desktop.+rgfwWindowState :: R.Window -> Float -> IO WindowState+rgfwWindowState win scale = do+ (x, y) <- R.windowPosition win+ flags <- R.windowFlags win+ focused <- R.windowFocused win+ let has bit = flags .&. bit /= 0+ pure+ defaultWindowState+ { winScale = scale+ , winPosition = Just (x, y)+ , winFocused = focused+ , winMaximized = has R.rgfw_windowMaximize+ , winMinimized = has R.rgfw_windowMinimize+ , winFullscreen = has R.rgfw_windowFullscreen+ }
+ nano-ui-rgfw.cabal view
@@ -0,0 +1,128 @@+cabal-version: 3.4+name: nano-ui-rgfw+version: 0.2.0.0+synopsis: RGFW and OpenGL window backend for nano-ui+description:+ Runs nano-ui views in a native window through RGFW and OpenGL 3.2, with+ the Cozette bitmap font bundled for text.+license: MIT+license-files:+ LICENSE+ LICENSE-Cozette+author: goolord+maintainer: zacharyachurchill@gmail.com+homepage: https://github.com/goolord/nano-ui+bug-reports: https://github.com/goolord/nano-ui/issues+category: Graphics+build-type: Simple+tested-with: GHC ==9.10.3 || ==9.14.1+extra-doc-files:+ CHANGELOG.md+ README.md++extra-source-files: data/cozette.min.otb++source-repository head+ type: git+ location: https://github.com/goolord/nano-ui.git+ subdir: packages/nano-ui-rgfw++common extensions+ default-language: GHC2024+ default-extensions:+ OverloadedStrings++common warnings+ ghc-options:+ -Wall+ -Wextra+ -Wcompat+ -Widentities+ -Wincomplete-record-updates+ -Wincomplete-uni-patterns+ -Wmissing-export-lists+ -Wmissing-home-modules+ -Wpartial-fields+ -Wredundant-constraints+ -Wunused-packages++library+ import: extensions+ import: warnings+ exposed-modules:+ NanoUI.Backend.Rgfw+ NanoUI.Rgfw.Internal.Context+ NanoUI.Rgfw.Internal.Debug+ NanoUI.Rgfw.Internal.Font.Cozette+ NanoUI.Rgfw.Internal.Gl+ NanoUI.Rgfw.Internal.Input+ NanoUI.Rgfw.Internal.Session+ c-sources: cbits/nano_ui_gl.c+ build-depends:+ base >=4.20 && <4.23,+ bytestring ^>=0.12,+ containers >=0.7 && <0.9,+ file-embed ^>=0.0.16,+ nano-ui ^>=0.2,+ nano-ui-emit ^>=0.2,+ nano-ui-rgfw-bindings ^>=0.2,+ primitive ^>=0.9,+ text ^>=2.1,+ vector ^>=0.13+ hs-source-dirs: lib++executable nano-ui-rgfw-demo+ import: extensions+ import: warnings+ main-is: RgfwDemo.hs+ other-modules: RgfwDemoCommon+ -- Threaded, so background tasks run while the loop waits for events.+ ghc-options: -threaded+ build-depends:+ base >=4.20 && <4.23,+ hashable ^>=1.5,+ nano-ui ^>=0.2,+ nano-ui-emit ^>=0.2,+ nano-ui-rgfw,+ text ^>=2.1+ hs-source-dirs: examples++executable nano-ui-rgfw-profile+ import: extensions+ import: warnings+ main-is: RgfwProfile.hs+ other-modules: RgfwDemoCommon+ ghc-options: -rtsopts "-with-rtsopts=-A64m -T -I0"+ build-depends:+ base >=4.20 && <4.23,+ bytestring ^>=0.12,+ hashable ^>=1.5,+ nano-ui ^>=0.2,+ nano-ui-emit ^>=0.2,+ nano-ui-rgfw,+ nano-ui-rgfw-bindings ^>=0.2,+ text ^>=2.1+ hs-source-dirs: examples++test-suite nano-ui-rgfw-test+ import: extensions+ import: warnings+ type: exitcode-stdio-1.0+ main-is: Spec.hs+ other-modules:+ NanoUI.Rgfw.Render+ NanoUI.Rgfw.Window+ NanoUI.Rgfw.Wake+ -- Threaded: the wake test's job and producer run while the loop blocks in RGFW.+ ghc-options: -threaded+ build-depends:+ base >=4.20 && <4.23,+ bytestring ^>=0.12,+ nano-ui ^>=0.2,+ nano-ui-emit ^>=0.2,+ nano-ui-rgfw,+ nano-ui-rgfw-bindings ^>=0.2,+ nano-ui-shader ^>=0.2,+ primitive ^>=0.9,+ text ^>=2.1+ hs-source-dirs: test
+ test/NanoUI/Rgfw/Render.hs view
@@ -0,0 +1,126 @@+-- | The reference software rasteriser the tests check RGFW frames with: a+-- BGRA pixel buffer, every primitive of the core's 'DrawData' filled flat,+-- and the collected text spans stamped with the Cozette bitmap font, in+-- 'paintInLayerOrder'.+--+-- The frame must come from 'NanoUI.Rgfw.Internal.Context.newRgfwContext':+-- square geometry leaves only flat quads and triangles in the buffer, and+-- external text leaves no text quads, so glyphs come from the spans alone.+module NanoUI.Rgfw.Render+ ( RgfwSurface (..)+ , withSurface+ , packColor+ , renderArena+ ) where++import Control.Exception (bracket)+import Control.Monad (forM_, when)+import Data.Bits (shiftL, shiftR, (.&.), (.|.))+import Data.Text qualified as T+import Data.Word (Word32)+import Foreign.ForeignPtr (withForeignPtr)+import Foreign.Marshal.Alloc (free, mallocBytes)+import Foreign.Ptr (Ptr)+import Foreign.Storable (peekByteOff, peekElemOff, pokeElemOff)+import NanoUI (Color (..), Rect (..))+import NanoUI.Backend (roundHalfUp)+import NanoUI.Rgfw.Internal.Context (TextSpan, paintInLayerOrder)+import NanoUI.Rgfw.Internal.Font.Cozette (CozetteFont, foldPenPositions, renderGlyphScaledToBuffer)+import NanoUI.Rgfw.Internal.Gl (physClip, toPhysRect)+import NanoUI.Testing (DrawCmd (..), DrawData (..), forDrawCmdsInLayer_, indexSize, vertexSize)++data RgfwSurface = RgfwSurface+ { sWidth :: !Int+ , sHeight :: !Int+ , sBuffer :: !(Ptr Word32)+ }++type RGBA = (Float, Float, Float, Float)++-- | A @w@ by @h@ surface cleared to @bg@, freed after @k@.+withSurface :: Int -> Int -> Word32 -> (RgfwSurface -> IO a) -> IO a+withSurface w h bg k = bracket (mallocBytes (w * h * 4)) free $ \buf -> do+ forM_ [0 .. w * h - 1] $ \i -> pokeElemOff buf i bg+ k (RgfwSurface w h buf)++-- | A colour as a BGRA surface word (ARGB from the high byte down).+packColor :: Color -> Word32+packColor (Color w) = (w `shiftL` 24) .|. (w `shiftR` 8)++-- | Rasterise a frame at @scale@ physical pixels per layout unit, with its+-- base and overlay text spans.+renderArena :: RgfwSurface -> CozetteFont -> Float -> DrawData -> [TextSpan] -> [TextSpan] -> IO ()+renderArena surf font scale dd base overlay =+ paintInLayerOrder (\layer -> forDrawCmdsInLayer_ layer dd (fillCmd surf scale dd)) (stamp base) (stamp overlay)+ where+ stamp = mapM_ $ \(Rect x y _ _, txt, fg, _, clip) ->+ case physClip scale (sWidth surf) (sHeight surf) clip of+ Just (cx0, cy0, cx1, cy1) | not (T.null txt) ->+ let glyph () px py =+ renderGlyphScaledToBuffer (sBuffer surf) (sWidth surf) cx0 cy0 cx1 cy1 scale px py (packColor fg) font+ in foldPenPositions font scale x y () glyph txt+ _ -> pure ()++-- | Fill a command's primitives: quads (six indices @a b c a c d@) and+-- triangles (three), each in the average of its corner colours.+fillCmd :: RgfwSurface -> Float -> DrawData -> DrawCmd -> IO ()+fillCmd surf scale dd cmd = case physClip scale (sWidth surf) (sHeight surf) cmdClip of+ Nothing -> pure ()+ Just clip -> withForeignPtr (drawVertices dd) $ \vp -> withForeignPtr (drawIndices dd) $ \ip -> do+ let start = fromIntegral (cmdIndexOffset cmd)+ index i = fromIntegral <$> (peekByteOff ip (i * indexSize) :: IO Word32)+ vertex i = do+ [x, y, r, g, b, a] <- mapM (\o -> peekByteOff vp (i * vertexSize + o)) [0, 4 .. 20]+ pure ((x, y), (r, g, b, a))+ walk (a : b : c : a' : c' : d : rest) | a' == a && c' == c = mapM vertex [a, b, c, d] >>= quad >> walk rest+ walk (a : b : c : rest) = mapM vertex [a, b, c] >>= convex >> walk rest+ walk _ = pure ()+ quad vs+ | axisAligned = case toPhysRect scale x0 y0 (x1 - x0) (y1 - y0) of+ (px, py, pw, ph) ->+ let (fx0, fy0, cx1, cy1) = clip+ in forM_ [max fy0 py .. min cy1 (py + ph) - 1] $ \row ->+ forM_ [max fx0 px .. min cx1 (px + pw) - 1] $ \col -> poke col row (average vs)+ | otherwise = convex vs+ where+ (xs, ys) = unzip (map fst vs)+ (x0, x1, y0, y1) = (minimum xs, maximum xs, minimum ys, maximum ys)+ near lo hi v = abs (v - lo) < 1.0e-3 || abs (v - hi) < 1.0e-3+ axisAligned = all (near x0 x1) xs && all (near y0 y1) ys+ convex vs = fillConvex clip [(phys x, phys y) | ((x, y), _) <- vs] (average vs)+ phys v = roundHalfUp (v * scale)+ poke col row c = when (alpha8 c > 0) (blendInto surf col row c)+ fillConvex (cx0, cy0, cx1, cy1) pts c = when (area /= 0) $+ forM_ [max cy0 (minimum (map snd pts)) .. min (cy1 - 1) (maximum (map snd pts))] $ \row ->+ forM_ [max cx0 (minimum (map fst pts)) .. min (cx1 - 1) (maximum (map fst pts))] $ \col ->+ when (all (inside col row) edges) (poke col row c)+ where+ edges = zip pts (drop 1 pts ++ take 1 pts)+ area = sum [f ax * f by - f bx * f ay | ((ax, ay), (bx, by)) <- edges]+ inside col row ((ax, ay), (bx, by)) =+ let (pxc, pyc) = (f col + 0.5, f row + 0.5)+ in ((f bx - f ax) * (pyc - f ay) - (f by - f ay) * (pxc - f ax)) * signum area >= 0+ mapM index [start .. start + fromIntegral (cmdIndexCount cmd) - 1] >>= walk+ where+ cmdClip = Rect (cmdClipX cmd) (cmdClipY cmd) (cmdClipW cmd) (cmdClipH cmd)+ f :: Int -> Float+ f = fromIntegral++average :: [((Float, Float), RGBA)] -> RGBA+average vs = (mean 0, mean 1, mean 2, mean 3)+ where+ mean i = sum [[r, g, b, a] !! i | (_, (r, g, b, a)) <- vs] / fromIntegral (length vs)++alpha8 :: RGBA -> Int+alpha8 (_, _, _, a) = max 0 (min 255 (round (a * 255)))++-- | Write an opaque colour, or blend a translucent one over the pixel.+blendInto :: RgfwSurface -> Int -> Int -> RGBA -> IO ()+blendInto surf col row c@(r, g, b, a) = do+ let i = row * sWidth surf + col+ t = if alpha8 c >= 255 then 1 else max 0 (min 1 a)+ byte v = fromIntegral (max 0 (min 255 (round (v * 255) :: Int))) :: Word32+ dst <- peekElemOff (sBuffer surf) i+ let channel s v = byte (v * t + fromIntegral ((dst `shiftR` s) .&. 0xFF) / 255 * (1 - t))+ pokeElemOff (sBuffer surf) i $+ 0xFF000000 .|. (channel 16 r `shiftL` 16) .|. (channel 8 g `shiftL` 8) .|. channel 0 b
+ test/NanoUI/Rgfw/Wake.hs view
@@ -0,0 +1,95 @@+-- | The RGFW session's wake: another thread can interrupt the loop's event wait.+module NanoUI.Rgfw.Wake (testRgfwWake) where++import Control.Concurrent+ (forkIO, getNumCapabilities, killThread, newEmptyMVar, setNumCapabilities, takeMVar, threadDelay, tryPutMVar, yield)+import Control.Exception (SomeException, try)+import Control.Monad (join, void, when)+import Control.Monad.IO.Class (liftIO)+import Data.IORef (atomicModifyIORef', atomicWriteIORef, newIORef, readIORef, writeIORef)+import Foreign.C.Types (CInt (..))+import GHC.Clock (getMonotonicTime)+import NanoUI+ (Size (..), WindowMode (..), WindowSettings (..), askWake, defaultWindowSettings, label, newTask, quit, useTask)+import NanoUI.Backend.Rgfw (RgfwOptions (..), defaultRgfwOptions, runRgfwApp)+import NanoUI.Rgfw.Window (hasDisplay)+import System.CPUTime (getCPUTime)+import System.IO (hFlush, stdout)+import System.Timeout (timeout)++foreign import ccall "exit" c_exit :: CInt -> IO ()++-- | A background job's wake shows its result while the loop waits for+-- events; after a stream faster than frames stops, the loop idles instead of+-- spinning; 'quit' ends the session. Skipped on Linux without an X+-- display, and without an OpenGL 3.2 window. A missed wake would block+-- forever, so a failed check exits the process.+testRgfwWake :: IO ()+testRgfwWake =+ hasDisplay >>= \case+ False -> putStrLn "[SKIP] RGFW wake: no X display"+ True -> do+ -- Two capabilities let the producer wake the loop while it is drawing,+ -- not only while it waits.+ caps <- getNumCapabilities+ when (caps < 2) (setNumCapabilities 2)+ passes <- newIORef (0 :: Int)+ phase <- newIORef (0 :: Int)+ wakeRef <- newIORef (pure ())+ latest <- newIORef (0 :: Int)+ shown <- newEmptyMVar+ streamed <- newEmptyMVar+ job <- newTask+ producer <- newTask+ let failNow msg = putStrLn ("[FAIL] RGFW wake: " ++ msg) >> hFlush stdout >> c_exit 1+ await what signal = timeout 5000000 (takeMVar signal) >>= maybe (failNow (what ++ " never showed")) pure+ next p = writeIORef phase p >> join (readIORef wakeRef)+ -- For a fifth of a second, write each value where the view reads it+ -- and wake, faster than frames; then write -1 to mark the end.+ produce wake = do+ t0 <- getMonotonicTime+ let go i = do+ atomicWriteIORef latest i >> wake+ t <- getMonotonicTime+ if t - t0 < 0.2 then yield >> go (i + 1) else atomicWriteIORef latest (-1) >> wake+ go 1+ view = do+ liftIO (atomicModifyIORef' passes (\n -> (n + 1, ())))+ wake <- askWake+ liftIO (writeIORef wakeRef wake)+ liftIO (readIORef phase) >>= \case+ 0 -> do+ r <- useTask job ("job" :: String) (threadDelay 50000 >> pure (42 :: Int))+ when (r == Just 42) (liftIO (void (tryPutMVar shown ())))+ label "job"+ 1 -> do+ _ <- useTask producer ("stream" :: String) (produce wake)+ v <- liftIO (readIORef latest)+ when (v == -1) (liftIO (void (tryPutMVar streamed ())))+ label "stream"+ _ -> quit+ watcher <- forkIO $ do+ await "the job's result" shown+ next 1+ await "the stream's last value" streamed+ threadDelay 100000+ c0 <- getCPUTime+ f0 <- readIORef passes+ threadDelay 400000+ c1 <- getCPUTime+ f1 <- readIORef passes+ let cpu = fromIntegral (c1 - c0) / 1e12 :: Double+ when (cpu > 0.12 || f1 /= f0) $+ failNow ("after the stream the loop used " ++ show cpu ++ " s of CPU and ran " ++ show (f1 - f0) ++ " passes")+ next 2+ -- Hidden, so pointer motion over it cannot run passes while it idles.+ let hidden = defaultWindowSettings {wsSize = Size 200 150, wsMode = Hidden}+ result <- try (runRgfwApp defaultRgfwOptions {optWindow = hidden} view)+ ran <- readIORef passes+ case result of+ _ | ran == 0 -> killThread watcher >> putStrLn "[SKIP] RGFW wake: no OpenGL 3.2 window"+ Right () ->+ readIORef phase >>= \case+ 2 -> putStrLn "[PASS] RGFW wake: a job's result and a stream show, the loop idles, and quit ends it"+ _ -> failNow "the session ended by itself"+ Left (e :: SomeException) -> failNow ("the session ended with " ++ show e)
+ test/NanoUI/Rgfw/Window.hs view
@@ -0,0 +1,324 @@+{-# LANGUAGE DataKinds #-}+-- | Window tests, skipped without a display or an OpenGL 3.2 window.+module NanoUI.Rgfw.Window (hasDisplay, testChildWindow, testGlWindow, testSessionWindow) where++import Control.Exception (IOException, bracket, try)+import Control.Monad (forM, void, when)+import Control.Monad.IO.Class (liftIO)+import Data.ByteString qualified as BS+import Data.Either (isRight)+import Data.IORef (modifyIORef', newIORef, readIORef, writeIORef)+import Data.Maybe (isJust)+import Data.Primitive.SmallArray (smallArrayFromList)+import Data.Text qualified as T+import Foreign.C.Types (CUChar (..))+import Foreign.Ptr (Ptr)+import NanoUI+ ( AlignX (..), AlignY (..), Input (..), Modifiers (..), MouseButton (..), NanoUI, Pressable (..)+ , Rect (..), Shader, ShaderKind (..), Size (..), V2 (..), V4 (..), WindowMode (..), WindowSettings (..)+ , WindowState (..), askInput, askWindow, box, button', canvas, colorB, colorBlack, colorG, colorR, colorRGBA, column+ , columnWith, defaultWindowSettings, drawText, fixedWH, inlineText, padAll, pageColor+ , quit, requestFrame, rgbaBytes, rgbaHeight, rgbaWidth, richText, setWindowTitle, shaderBox, strong+ , tight, windowColor, windowSize, withShader+ )+import NanoUI.Shader.Raw (emptyShaderProgram, rawShader)+import NanoUI.Themes (tomorrowNightMinDarkTheme)+import NanoUI.Widgets.Custom (DrawOp (..), drawing)+import NanoUI.Shader (TintParams (..), composeColor, gaussianBlur, grayscale, groupOpacity, tint)+import NanoUI.Backend (Damage (..), ShaderProgram (..))+import NanoUI.Backend.Rgfw (RgfwOptions (..), defaultRgfwOptions, runRgfwApp, runRgfwAppReduce)+import NanoUI qualified as UI+import NanoUI.Emit (NanoUIE, emit)+import GHC.Clock (getMonotonicTime)+import NanoUI.Internal.Context (Context (..))+import NanoUI.Rgfw.Internal.Context (newRgfwContext)+import NanoUI.Rgfw.Internal.Font.Cozette (getCozetteFont)+import NanoUI.Rgfw.Internal.Gl+ (freeGlRenderer, newGlRenderer, readRetainedPixels, readWindowPixels, renderArenaGl, retainedPixels)+import NanoUI.Testing (collectRasterSpans, damageIsEmpty, runFrame, takeDamage, takeDamagePieces)+import NanoUI.Testing.Harness (centerOf, withInputOff)+import RGFW qualified as R+import System.Environment (lookupEnv)+import System.Info (os)++-- RGFW's own entry points for a key or button event: they record the key or+-- button and queue the event, as the platform code does.+foreign import ccall "RGFW_getRootWindow" c_RGFW_getRootWindow :: IO (Ptr R.RGFW_window)++foreign import ccall "RGFW_keyCallback"+ c_RGFW_keyCallback :: Ptr R.RGFW_window -> CUChar -> CUChar -> CUChar -> CUChar -> IO ()++foreign import ccall "RGFW_mouseButtonCallback"+ c_RGFW_mouseButtonCallback :: Ptr R.RGFW_window -> CUChar -> CUChar -> IO ()++-- | Whether to try a window: on Linux only with an X display. Elsewhere the+-- tests try one and skip when it does not open.+hasDisplay :: IO Bool+hasDisplay = if os == "linux" then isJust <$> lookupEnv "DISPLAY" else pure True++-- | The OpenGL renderer draws into a hidden window, read back as a+-- screenshot. The window stays opaque even where a translucent page colour+-- is painted twice, rows run top to bottom, and text in drawings repaints+-- with them: settled through partial frames while the pointer hovers a+-- button and a counter changes, a page has the pixels a full repaint draws.+testGlWindow :: (String -> Bool -> IO ()) -> IO ()+testGlWindow assert =+ hasDisplay >>= \case+ False -> putStrLn "[SKIP] OpenGL window: no display"+ True -> bracket (R.createWindowGL "nano-ui-rgfw-test" 0 0 w h R.rgfw_windowHide 3 2) (mapM_ R.closeWindow) $ \case+ Nothing -> putStrLn "[SKIP] OpenGL window: no OpenGL 3.2 window"+ Just _ -> bracket newGlRenderer freeGlRenderer $ \renderer -> do+ let inp = withInputOff (fromIntegral w) (fromIntegral h)+ -- As the session draws a frame: a forced one in full, any other+ -- only its damage. Returns whether it drew.+ present ctx force frameInp ui = do+ writeIORef (ctxPaintFull ctx) force+ (_, draw, _) <- runFrame ctx frameInp ui+ damage <- takeDamage ctx+ let drawn = force || not (damageIsEmpty damage)+ when drawn $ do+ (base, overlay) <- collectRasterSpans ctx frameInp+ pieces <- if force then pure [] else takeDamagePieces ctx+ let whole = if force then DamageFull else damage+ renderArenaGl renderer getCozetteFont 1 w h whole pieces draw base overlay+ pure drawn+ name s = "OpenGL window: " ++ s+ -- An opaque box, then the page colour painted twice, as a page's+ -- scroller paints over the backdrop.+ boxes <- newRgfwContext (pageColor backdrop (windowColor backdrop tomorrowNightMinDarkTheme))+ let opsBox ops = void (drawing (fixedWH 40 20) (smallArrayFromList . ops))+ _ <- present boxes True inp . columnWith tight $ do+ opsBox (\r -> [FillRect r red])+ opsBox (\r -> [FillRect r backdrop, FillRect r backdrop])+ img <- maybe (fail "OpenGL window: no screenshot") pure =<< retainedPixels renderer w h+ let at x y = [fromIntegral (BS.index (rgbaBytes img) ((y * w + x) * 4 + c)) | c <- [0 .. 3]]+ pixels = [(y, at x y) | y <- [0 .. h - 1], x <- [0 .. w - 1]]+ reds = [y | (y, p) <- pixels, take 3 p == rgb red]+ assert (name "screenshot size") (rgbaWidth img == w && rgbaHeight img == h)+ assert (name "the page colour, opaque") (at (w - 1) (h - 1) == rgb backdrop ++ [255])+ assert (name "the page colour stays opaque, painted twice") $+ and [p !! 3 == 255 | (_, p) <- pixels, take 3 p == rgb backdrop]+ assert (name "an opaque box") (length reds == 800 && all (< 20) reds)+ -- A read smaller than the frame fills only its own buffer.+ corner <- readRetainedPixels renderer 2 1+ full <- readRetainedPixels renderer w h+ assert (name "a smaller read is the bottom-left corner") (corner == BS.take 8 full)+ -- The present copies the retained frame; read it from the back buffer+ -- before any swap, colour only, as the visual may have no alpha.+ win <- readWindowPixels renderer w h+ let shown x y = [fromIntegral (BS.index win (((h - 1 - y) * w + x) * 4 + c)) | c <- [0 .. 2]]+ near want got = and (zipWith (\a b -> abs (a - b) <= 2) want got)+ assert (name "the present shows the page colour") (near (rgb backdrop) (shown (w - 1) (h - 1)))+ assert (name "the present shows an opaque box") (near (rgb red) (shown 5 5))+ ctx <- newRgfwContext tomorrowNightMinDarkTheme+ btn <- newIORef (V2 0 0)+ let view k = column $ do+ b <- button' "hover"+ liftIO (writeIORef btn (centerOf b))+ let counter = T.pack (" at " ++ show k)+ void $ richText [inlineText "rich text beside ", strong "a counter", inlineText counter]+ void $ canvas (fixedWH 160 20) $ \(Rect x y _ _) ->+ drawText (V2 x y) AlignStart AlignTop (T.pack ("canvas " ++ show k)) ink+ settle n frameInp ui = do+ drawn <- present ctx False frameInp {inputDeltaTime = 0.016} ui+ when (drawn && n < (200 :: Int)) (settle (n + 1) frameInp ui)+ -- Partial frames until nothing changes, then the same state in full.+ same frameInp ui = do+ settle 0 frameInp ui+ partial <- readRetainedPixels renderer w h+ _ <- present ctx True frameInp ui+ (partial ==) <$> readRetainedPixels renderer w h+ _ <- present ctx True inp (view 0)+ over <- readIORef btn+ let hovered = inp {inputMousePos = over}+ results <- forM [(1, hovered), (2, hovered), (3, inp), (4 :: Int, hovered)] $ \(k, i) -> same i (view k)+ texts <- readRetainedPixels renderer w h+ let isInk i = map (BS.index texts . (i +)) [0 .. 2] == [colorR ink, colorG ink, colorB ink]+ inked = filter isInk [0, 4 .. BS.length texts - 4]+ assert (name "partial repaints of drawing text match full ones") (and results)+ assert (name "the canvas text is drawn") (not (null inked))+ -- Tier 1 surface shader: uniform block layout + UV interpolation + partial repaint.+ let glsl150Src =+ T.unlines+ [ "#version 150"+ , "in vec4 vColor;"+ , "in vec2 vUV;"+ , "layout(std140) uniform NanoShaderBlock {"+ , " vec4 uRect;"+ , " vec4 uUvRect;"+ , " vec4 uMeta;"+ , " vec4 uTint;"+ , "};"+ , "out vec4 fragColor;"+ , "void main() {"+ , " vec2 uv = (vUV - uUvRect.xy) / uUvRect.zw;"+ , " fragColor = vec4(uv.x, uTint.g, uTint.b, 1.0) * vColor;"+ , "}"+ ]+ surfShader :: Shader 'Surface V4+ surfShader = rawShader emptyShaderProgram {spGlsl150 = Just glsl150Src}+ shCtx <- newRgfwContext (pageColor backdrop (windowColor backdrop tomorrowNightMinDarkTheme))+ let shUi u = columnWith tight (shaderBox (fixedWH 40 20) surfShader u)+ _ <- present shCtx True inp (shUi (V4 0 0.5 0.75 1))+ shImg1 <- maybe (fail "OpenGL window: no shader screenshot 1") pure =<< retainedPixels renderer w h+ let pxOf im x y = [fromIntegral (BS.index (rgbaBytes im) ((y * w + x) * 4 + c)) | c <- [0 .. 3]] :: [Int]+ near4 a b = and (zipWith (\u v -> abs (u - v) <= 3) a b)+ -- Left edge x=0 -> uv.x ~ 0.0125 -> R ~ 3; right edge x=39 -> uv.x ~ 0.9875 -> R ~ 252.+ assert (name "surface shader left pixel") (near4 [3, 128, 191, 255] (pxOf shImg1 0 10))+ assert (name "surface shader right pixel") (near4 [252, 128, 191, 255] (pxOf shImg1 39 10))+ assert (name "surface shader outside stays backdrop") (near4 (rgb backdrop ++ [255]) (pxOf shImg1 60 10))+ -- Identical uniform produces zero damage (idle costs nothing).+ drawnIdle <- present shCtx False inp (shUi (V4 0 0.5 0.75 1))+ assert (name "surface shader idle draws nothing") (not drawnIdle)+ -- Updating uniform repaints the shader box partially.+ drawnDirty <- present shCtx False inp (shUi (V4 0 0.25 1.0 1))+ assert (name "surface shader uniform change redraws") drawnDirty+ shImg2 <- maybe (fail "OpenGL window: no shader screenshot 2") pure =<< retainedPixels renderer w h+ assert (name "surface shader updated pixel") (near4 [252, 64, 255, 255] (pxOf shImg2 39 10))++ -- Tier 2 subtree effects on OpenGL 3.2: grayscale, fused ColorEffect,+ -- separable 2-pass gaussianBlur bleed halo, and nested groupOpacity.+ efCtx <- newRgfwContext (pageColor colorBlack (windowColor colorBlack tomorrowNightMinDarkTheme))+ let srcCol = colorRGBA 200 40 20 255+ _ <- present efCtx True inp (columnWith tight (withShader grayscale 1.0 (box (fixedWH 60 40) srcCol)))+ efGray <- maybe (fail "OpenGL window: no grayscale screenshot") pure =<< retainedPixels renderer w h+ -- 0.2126*200 + 0.7152*40 + 0.0722*20 = 72.57 -> ~73+ assert (name "Tier 2 grayscale OpenGL readback") (near4 [73, 73, 73, 255] (pxOf efGray 30 20))++ let fused = composeColor grayscale tint+ fusedU = (1.0, TintParams (colorRGBA 0 80 240 255) 0.5)+ _ <- present efCtx True inp (columnWith tight (withShader fused fusedU (box (fixedWH 60 40) srcCol)))+ efFused <- maybe (fail "OpenGL window: no fused screenshot") pure =<< retainedPixels renderer w h+ -- mix (73, 73, 73) (0, 80, 240) 0.5 = (36, 76, 156)+ assert (name "Tier 2 fused composeColor OpenGL readback") (near4 [36, 76, 156, 255] (pxOf efFused 30 20))++ _ <-+ present efCtx True inp $+ columnWith (padAll 30 . tight) $+ withShader gaussianBlur 4.0 (box (fixedWH 40 40) (colorRGBA 255 0 0 255))+ efBlur <- maybe (fail "OpenGL window: no blur screenshot") pure =<< retainedPixels renderer w h+ let centerOk = case pxOf efBlur 50 50 of+ [cr, cg, cb, _] -> cr > 200 && cg < 10 && cb < 10+ _ -> False+ haloOk = case pxOf efBlur 27 50 of+ [hr, hg, hb, _] -> hr > 15 && hr < 245 && hg < 10 && hb < 10+ _ -> False+ farPx = pxOf efBlur 5 50+ assert (name "Tier 2 gaussianBlur center stays bright red") centerOk+ assert (name "Tier 2 gaussianBlur bleed halo outside box") haloOk+ assert (name "Tier 2 gaussianBlur stays within margin") (farPx == [0, 0, 0, 255])++ _ <-+ present efCtx True inp $+ columnWith tight $+ withShader groupOpacity 0.5 $+ withShader grayscale 1.0 (box (fixedWH 60 40) srcCol)+ efNest <- maybe (fail "OpenGL window: no nested screenshot") pure =<< retainedPixels renderer w h+ assert (name "Tier 2 nested groupOpacity(grayscale) OpenGL readback") (near4 [36, 36, 36, 255] (pxOf efNest 30 20))+ where+ w = 240+ h = 120+ backdrop = colorRGBA 10 20 30 128+ red = colorRGBA 200 30 60 255+ ink = colorRGBA 0x12 0xEE 0x34 255+ rgb c = map fromIntegral [colorR c, colorG c, colorB c] :: [Int]++-- | A session window opens at its layout-unit size and requested scale (both+-- visible to the view), takes a title from the view, and closes when the+-- view quits. Until the pointer comes, it is off the window, not on the+-- widget in the top-left corner. Letting go of one Shift while the other is+-- down leaves Shift held, so a click after it is a Shift-click; the keys+-- come with the modifier bits from before each, as RGFW reads them on X11+-- and Windows.+testSessionWindow :: (String -> Bool -> IO ()) -> IO ()+testSessionWindow assert =+ hasDisplay >>= \case+ False -> putStrLn "[SKIP] RGFW session window: no display"+ True -> do+ frames <- newIORef (0 :: Int)+ opened <- newIORef Nothing+ clicked <- newIORef Nothing+ let root f = c_RGFW_getRootWindow >>= f+ key k m down = root (\win -> c_RGFW_keyCallback win (CUChar (fromIntegral k)) (CUChar m) 0 (flag down))+ click down = root (\win -> c_RGFW_mouseButtonCallback win (CUChar R.rgfw_mouseLeft) (flag down))+ flag down = if down then 1 else 0 :: CUChar+ view :: NanoUI ()+ view = do+ inp <- askInput+ n <- liftIO (readIORef frames <* modifyIORef' frames (+ 1))+ case n of+ -- RGFW queues events only once the session has polled.+ 0 -> do+ size <- windowSize+ st <- askWindow+ let V2 mx my = inputMousePos inp+ setWindowTitle "renamed"+ liftIO (writeIORef opened (Just (size, winScale st, mx < -1000 && my < -1000)))+ requestFrame+ 1 -> do+ liftIO $ do+ key R.rgfw_keyShiftR 0 True+ key R.rgfw_keyShiftL R.rgfw_modShift True+ key R.rgfw_keyShiftL R.rgfw_modShift False+ click True+ requestFrame+ _+ | heldIn MouseLeft inp || n > 20 -> do+ liftIO $ do+ writeIORef clicked (Just (heldIn MouseLeft inp && modShift (inputModifiers inp)))+ click False+ key R.rgfw_keyShiftR R.rgfw_modShift False+ quit+ | otherwise -> requestFrame+ hidden = defaultWindowSettings {wsSize = Size 200 150, wsMode = Hidden}+ options = defaultRgfwOptions {optScale = 2, optWindow = hidden}+ ended <- try (runRgfwApp options view)+ readIORef opened >>= \case+ Nothing -> putStrLn "[SKIP] RGFW session window: no OpenGL 3.2 window"+ Just (size, scale, offWindow) -> do+ shiftClick <- readIORef clicked+ assert "RGFW session window: its size in layout units at its scale"+ ((size, scale) == (Size 200 150, 2) && isRight (ended :: Either IOException ()))+ assert "RGFW session window: the pointer starts off the window" offWindow+ assert "RGFW session: one Shift let go while the other is down keeps Shift" (shiftClick == Just True)++-- | A reducer session's further window ('UI.nativeWindow'), hidden: it runs+-- its view on its own OpenGL context, a message it emits reaches the model,+-- and it sees the new model through the declaring view's frame, which it+-- closes over. 'quit' in it closes it and writes 'False', which the first+-- window shows promptly though nothing else wakes it.+testChildWindow :: (String -> Bool -> IO ()) -> IO ()+testChildWindow assert =+ hasDisplay >>= \case+ False -> putStrLn "[SKIP] RGFW further window: no display"+ True -> do+ open <- UI.newVar True+ passes <- newIORef (0 :: Int)+ childSaw <- newIORef []+ closedAt <- newIORef Nothing+ noticedAt <- newIORef Nothing+ let hidden = defaultWindowSettings {wsSize = Size 200 150, wsMode = Hidden}+ options = defaultRgfwOptions {optScale = 1, optWindow = hidden}+ view :: Int -> NanoUIE () ()+ view m = do+ n <- liftIO (readIORef passes <* modifyIORef' passes (+ 1))+ UI.nativeWindow open hidden {wsTitle = "second"} $ do+ UI.wakeAfter 0.02+ liftIO (modifyIORef' childSaw (m :))+ when (m == 0) (emit ())+ when (m >= 1) $ do+ liftIO (getMonotonicTime >>= writeIORef closedAt . Just)+ quit+ stillOpen <- UI.readVar open+ when (not stillOpen) $ liftIO (getMonotonicTime >>= writeIORef noticedAt . Just)+ when (not stillOpen || n > 2000) quit+ ended <- try (runRgfwAppReduce options (\() k -> k + 1) (0 :: Int) view)+ saw <- readIORef childSaw+ if null saw && not (isRight (ended :: Either IOException ()))+ then putStrLn "[SKIP] RGFW further window: no OpenGL 3.2 window"+ else do+ assert "RGFW further window: runs its view" (0 `elem` saw)+ assert "RGFW further window: its message reaches the model, which its view sees" (any (>= 1) saw)+ shut <- not <$> UI.readVarIO open+ lag <- (\a b -> (-) <$> b <*> a) <$> readIORef closedAt <*> readIORef noticedAt+ assert "RGFW further window: quit in it closes it, which the first window shows" (shut && maybe False (< 1) lag)
+ test/Spec.hs view
@@ -0,0 +1,324 @@+module Main (main) where++import Control.Exception (bracket)+import Control.Monad (filterM, forM_, void)+import Data.Bits ((.|.))+import Data.Foldable (toList)+import Data.IORef (IORef)+import Data.List (nub)+import Data.Text qualified as T+import Data.Word (Word32)+import Foreign.Marshal.Alloc (allocaBytes, callocBytes, free)+import Foreign.Storable (peekByteOff, peekElemOff)+import NanoUI+ ( AlignX (..), AlignY (..), NanoUI, Rect (..), Style (..), Theme (..), UiCursorKind (..), V2 (..), button+ , canvas, checkbox, colorRGBA, column, constVar, drawText, fixedWH, fontColor, fontMono, fontSize, inlineWith+ , labelWith, richText, floatingWindow'+ )+import NanoUI.Themes (tomorrowNightMinDarkTheme)+import NanoUI.Backend (cursorFallback)+import NanoUI.Input+ ( Input (..), Key (..), Modifiers (..), MouseButton (..), Pressable (..), buttonsToList+ , emptyInput, noModifiers+ )+import NanoUI.Internal.Layout.Arena (NodeType (..))+import NanoUI.Rgfw.Internal.Context (newRgfwContext)+import NanoUI.Rgfw.Internal.Font.Cozette+ ( CozetteFont (..), charToGlyphId, cozetteGlyphBit, cozetteGlyphFootprint, getCozetteFont+ , renderGlyphScaledToBuffer+ )+import NanoUI.Rgfw.Internal.Gl+ (GlyphAtlas (..), atlasCell, bakeGlyphAtlas, glBufferStrides, glyphAtlasFor, toPhysRect, writeSpanQuads)+import NanoUI.Rgfw.Internal.Session (applyRgfwEvent, decodeRgfwEvents, mapRgfwCursor)+import NanoUI.Rgfw.Render (RgfwSurface (..), packColor, renderArena, withSurface)+import NanoUI.Rgfw.Wake (testRgfwWake)+import NanoUI.Rgfw.Window (testChildWindow, testGlWindow, testSessionWindow)+import NanoUI.Testing (Context, collectRasterSpans, indexSize, vertexSize)+import NanoUI.Testing.Assert (run2Frames)+import NanoUI.Testing.Harness (DemoSpan, nodesOfType, withInputOff)+import NanoUI.Testing.Runner (check, runChecks)+import RGFW (Event (..))+import RGFW.Raw qualified as R++-- | Each named check, under a common prefix.+checks :: IORef Int -> String -> [(String, Bool)] -> IO ()+checks failed prefix = mapM_ (\(name, ok) -> check failed (prefix ++ name) ok)++type Pixels = Int -> Int -> IO Word32++-- | Draw a view's second frame (pointer outside the window) onto a software+-- surface cleared to @bg@, then pass the spans and a pixel reader to @k@.+raster :: Context -> Int -> Int -> Word32 -> NanoUI a -> (a -> ([DemoSpan], [DemoSpan]) -> Pixels -> IO b) -> IO b+raster ctx w h bg ui k = do+ let inp = withInputOff (fromIntegral w) (fromIntegral h)+ (a, draw, _) <- run2Frames ctx inp ui+ spans@(base, overlay) <- collectRasterSpans ctx inp+ withSurface w h bg $ \surf -> do+ renderArena surf getCozetteFont 1 draw base overlay+ k a spans (\x y -> peekElemOff (sBuffer surf) (y * w + x))++-- | The pixels of @r@ (rounded) whose colour is @c@, out of all of them.+inkIn :: Pixels -> Word32 -> Rect -> IO (Int, Int)+inkIn px c (Rect x y w h) = do+ let box = [(i, j) | j <- [round y .. round (y + h) - 1], i <- [round x .. round (x + w) - 1]]+ lit <- length <$> filterM (\(i, j) -> (== c) <$> px i j) box+ pure (lit, length box)++-- | Some, but not most, of a span's box is ink: glyphs, not a solid box.+glyphs :: (Int, Int) -> Bool+glyphs (lit, total) = lit > 0 && lit * 2 < total++-- | Fold a batch of RGFW events into one 'Input'.+applied :: [Event] -> Input+applied = foldl' applyRgfwEvent emptyInput . decodeRgfwEvents 1++-- | Reference EPX (Scale2x) of a @w@ by @h@ bit query.+scale2x :: Int -> Int -> (Int -> Int -> Bool) -> Int -> Int -> Bool+scale2x w h get c2 r2+ | c2 < 0 || c2 >= w * 2 || r2 < 0 || r2 >= h * 2 = False+ | above /= below && left /= right && vertical == horizontal = vertical+ | otherwise = get c r+ where+ (c, r) = (c2 `div` 2, r2 `div` 2)+ at x y = x >= 0 && x < w && y >= 0 && y < h && get x y+ (above, below, left, right) = (at c (r - 1), at c (r + 1), at (c - 1) r, at (c + 1) r)+ vertical = if even r2 then above else below+ horizontal = if even c2 then left else right++-- | The scaled glyph tables, the OpenGL glyph atlas, span quads, and the+-- physical rects of fractional scales.+testGlyphs :: IORef Int -> IO ()+testGlyphs failed = do+ let font = getCozetteFont+ -- The 14x26 table is Scale2x of the 7x13 one, and 28x52 of 14x26.+ forM_ [(2, 1, 7, 13), (4, 2, 14, 26)] $ \(scale, from, w, h) -> forM_ [1, 2, 34, 36, 65, 95] $ \gid ->+ check failed ("Scale" ++ show scale ++ "x table matches scale2x for glyph " ++ show gid) $+ and+ [ cozetteGlyphBit font scale gid x y == scale2x w h (cozetteGlyphBit font from gid) x y+ | y <- [0 .. 2 * h - 1]+ , x <- [0 .. 2 * w - 1]+ ]+ strides <- glBufferStrides+ check failed "nano_ui_gl.c reads the core's vertex and index strides" (strides == (vertexSize, indexSize))+ let (x1, _, w1, _) = toPhysRect 1.33 0 0 63.7 30+ (x2, _, _, _) = toPhysRect 1.33 63.7 0 63.7 30+ check failed "Adjacent widgets at fractional scale have zero gap/overlap" (x1 + w1 == x2)+ -- The atlas holds every glyph as the software blitter stamps it at that+ -- scale; below 1x the pens close up, so the glyphs shrink with them.+ check failed "glyphs below 1x shrink with the pen grid" $+ map cozetteGlyphFootprint [0.5, 0.75, 1.0] == [(4, 6), (5, 10), (7, 13)]+ forM_ [0.5, 1.0, 1.5, 2.0, 3.0, 4.0] $ \scale -> do+ let ga = glyphAtlasFor font scale+ (cw, ch) = (gaCellW ga, gaCellH ga)+ at = " at scale " ++ show scale+ check failed ("glyph atlas grid fits every glyph" ++ at)+ (gaCols ga * (gaHeight ga `div` ch) >= cfNumGlyphs font && gaWidth ga == gaCols ga * cw)+ bakeGlyphAtlas font ga $ \atlas -> forM_ ("A@#|" :: String) $ \c -> do+ let gid = fromIntegral (charToGlyphId font c)+ (ax, ay) = atlasCell ga gid+ bracket (callocBytes (cw * ch * 4)) free $ \solo -> do+ renderGlyphScaledToBuffer solo cw 0 0 cw ch scale 0 0 0xFFFFFFFF font (fromIntegral gid)+ cell <- sequence+ [peekElemOff atlas (row * gaWidth ga + col) | row <- [ay .. ay + ch - 1], col <- [ax .. ax + cw - 1]]+ expected <- mapM (peekElemOff solo) [0 .. cw * ch - 1]+ check failed ("glyph atlas cell " ++ show c ++ " matches the blitter" ++ at) $+ cell == expected && any (/= 0) expected+ -- Span quads land on the software pen positions (spaces skipped, newlines+ -- reset the column) and clipping trims positions and UVs together.+ let ga = glyphAtlasFor font 2.0+ red = colorRGBA 255 0 0 255+ (aw, ah) = (fromIntegral (gaWidth ga), fromIntegral (gaHeight ga)) :: (Float, Float)+ (ax, ay) = atlasCell ga (fromIntegral (charToGlyphId font 'A'))+ uv u v = [fromIntegral u / aw, fromIntegral v / ah]+ quads g origin txt clip = allocaBytes (64 * 32) $ \buf -> do+ n <- writeSpanQuads g font (0, 0, 200, 100) buf 0 (origin, txt, red, red, clip)+ vs <- mapM (\i -> mapM (\o -> peekByteOff buf (i * 32 + o)) [0, 4, 24, 28]) [0 .. n - 1]+ pure (n, vs :: [[Float]])+ at10 = Rect 10 5 0 0+ (n1, v1) <- quads ga at10 "A B\nC" (Rect 0 0 100 50)+ (n2, v2) <- quads ga at10 "A" (Rect 12 0 100 50)+ (n3, _) <- quads ga at10 "A" (Rect 150 80 10 10)+ -- At 1.5x a span at (11, 7) puts its pen at (16.5, 10.5), which rounds up.+ (_, v4) <- quads (glyphAtlasFor font 1.5) (Rect 11 7 0 0) "A" (Rect 0 0 100 50)+ checks failed "span quads: "+ [ ("one quad per visible glyph", n1 == 18)+ , ("first glyph at the scaled pen", take 1 v1 == [[20, 10] ++ uv ax ay])+ , ("newline resets the column", map (take 2) (take 1 (drop 12 v1)) == [[20, 36]])+ , ("clip trims position and UV", n2 == 6 && take 1 v2 == [[24, 10] ++ uv (ax + 4) ay])+ , ("clip outside the framebuffer emits nothing", n3 == 0)+ , ("the pen rounds half up at 1.5x", map (take 2) (take 1 v4) == [[17, 11]])+ ]++-- | An RGFW context renders square, themed widgets, and stamps widget,+-- sized, monospace, canvas and rich text as glyphs in the Cozette cell.+testThemedRaster :: IORef Int -> IO ()+testThemedRaster failed = do+ let theme = tomorrowNightMinDarkTheme+ ink = colorRGBA 0x12 0xEE 0x34 255+ ui = column $ do+ void (button "Button")+ checkbox "Checkbox label" (constVar True)+ labelWith (fontSize 26) "Title"+ labelWith fontMono "1234"+ _ <- canvas (fixedWH 200 20) (\(Rect x y _ _) -> drawText (V2 x y) AlignStart AlignTop "Label" ink)+ richText [inlineWith (fontColor ink) "a rich text paragraph"]+ ctx <- newRgfwContext theme+ raster ctx 240 200 (packColor (themeWindow theme)) ui $ \_ (base, _) px -> do+ nodesOfType NodeButton ctx >>= \case+ (_, Rect bx by bw bh) : _ -> do+ let (x0, y0, x1, y1) = (round bx, round by, round (bx + bw) - 1, round (by + bh) - 1)+ corners <- mapM (uncurry px) [(x0, y0), (x1, y0), (x0, y1), (x1, y1)]+ fill <- px (x0 + 2) (y0 + 2)+ check failed "Button corners are square (border colour)" $+ all (== packColor (styleBorder (themeButton theme))) corners+ check failed "Button fill uses the theme" (fill == packColor (styleBg (themeButton theme)))+ [] -> check failed "Button node present" False+ labelInk <- sequence [inkIn px (packColor fg) r | (r, "Checkbox label", fg, _, _) <- base]+ check failed "Checkbox label is glyphs, not solid boxes" (map glyphs labelInk == [True])+ -- Cozette stamps every span from its one cell, so each span is as wide+ -- as the glyphs drawn in it.+ check failed "Sized and monospace text spans measure the Cozette cell" $+ [(t, w, h) | (Rect _ _ w h, t, _, _, _) <- base, t `elem` ["Title", "1234"]]+ == [("Title", 30, 13), ("1234", 24, 13)]+ drawings <- map snd <$> nodesOfType NodeDrawing ctx+ let inkSpans = [r | (r, _, fg, _, _) <- base, fg == ink]+ inside (Rect rx ry rw rh) (x, y) =+ fromIntegral x >= rx && fromIntegral x < rx + rw && fromIntegral y >= ry && fromIntegral y < ry + rh+ inked <- filterM (\(x, y) -> (== packColor ink) <$> px x y) [(x, y) | y <- [0 .. 199], x <- [0 .. 239]]+ drawingInk <- mapM (inkIn px (packColor ink)) inkSpans+ check failed "Canvas and rich text are glyphs, not solid boxes" (length inkSpans >= 2 && all glyphs drawingInk)+ check failed "No drawing text outside its drawing" (all (\p -> any (`inside` p) drawings) inked)++-- | A floating window paints over the page: its chrome is the theme's, the+-- page's drawing text under it is hidden, and its own drawing text shows+-- over its background.+testWindowLayer :: IORef Int -> IO ()+testWindowLayer failed = do+ let theme = tomorrowNightMinDarkTheme+ under = colorRGBA 0x12 0xEE 0x34 255+ over = colorRGBA 0xEE 0x12 0x34 255+ text c (Rect x y _ _) = drawText (V2 x y) AlignStart AlignTop c+ page = void $ canvas (fixedWH 240 120) $ \(Rect x y w h) ->+ forM_ [0 .. 8 :: Int] $ \i -> text (T.replicate 40 "#") (Rect x (y + 13 * fromIntegral i) w h) under+ win = floatingWindow' (constVar True) "Z" (canvas (fixedWH 60 20) (\r -> text "over" r over))+ inkAt col px = filterM (\(x, y) -> (== packColor col) <$> px x y)+ alone <- newRgfwContext theme+ pageInk <- raster alone 240 120 0 page $ \_ _ px ->+ inkAt under px [(x, y) | y <- [0 .. 119], x <- [0 .. 239]]+ ctx <- newRgfwContext theme+ raster ctx 240 120 0 (page >> win) $ \_ (_, overlay) px ->+ nodesOfType NodeWindow ctx >>= \case+ (_, Rect wx wy ww wh) : _ -> do+ -- A pixel in from the window's edges, which may be fractional.+ let inWindow (x, y) =+ fromIntegral x >= wx + 1 && fromIntegral x < wx + ww - 1+ && fromIntegral y >= wy + 1 && fromIntegral y < wy + wh - 1+ covered = filter inWindow pageInk+ shown <- inkAt under px covered+ chrome <- px (round (wx + ww / 2)) (round wy + 4)+ overInk <- mapM (inkIn px (packColor over)) [r | (r, _, fg, _, _) <- overlay, fg == over]+ check failed "A floating window paints its theme's chrome over the page" $+ chrome == packColor (styleBg (themeFloatingWindow theme))+ check failed "A floating window covers the page's drawing text" (not (null covered) && null shown)+ check failed "Drawing text in a floating window shows over its background" (map glyphs overInk == [True])+ [] -> check failed "Floating window node present in arena" False++-- | RGFW keyboard translation. A Ctrl+letter keystroke is a chord that+-- types nothing, whichever of its key-char and key-press events RGFW queues+-- first.+testRgfwKeys :: IORef Int -> IO ()+testRgfwKeys failed = do+ let chars = inputChars . applied+ keys = toList . inputKeys . applied+ mods = inputModifiers . applied+ keyL = fromIntegral (fromEnum 'l')+ plainL = [EventKeyChar 'l', EventKeyPress keyL 0]+ ctrlLCharFirst = [EventKeyChar '\x0c', EventKeyPress keyL R.rgfw_modControl]+ ctrlLPressFirst = [EventKeyPress keyL R.rgfw_modControl, EventKeyChar '\x0c']+ chord evs = chars evs == "" && keys evs == [KeyChar 'l'] && modCtrl (mods evs)+ blurred = applied [EventKeyPress keyL R.rgfw_modControl, EventOther R.rgfw_windowFocusOut]+ pad1 = R.rgfw_keyPad1 + 1+ shift = noModifiers {modShift = True}+ checks failed "RGFW keys: "+ [ ("repeated key-char events all type", chars [EventKeyChar 'l', EventKeyChar 'l'] == "ll")+ , ( "a joiner types, and macOS arrow-key characters do not"+ , chars [EventKeyChar '\x200C', EventKeyChar '\xF702'] == "\x200C"+ )+ , ( "private-use characters past the macOS function keys type"+ , chars [EventKeyChar '\xF747', EventKeyChar '\xF748', EventKeyChar '\xF8FF'] == "\xF748\xF8FF"+ )+ , ("repeated keystrokes all type", chars (plainL ++ plainL) == "ll")+ , ("a keystroke is its character key as well", keys plainL == [KeyChar 'l'])+ , ("Ctrl+L queued char-first is a chord", chord ctrlLCharFirst)+ , ("Ctrl+L queued press-first is a chord", chord ctrlLPressFirst)+ , ("Ctrl+L twice presses twice", keys (ctrlLCharFirst ++ ctrlLPressFirst) == [KeyChar 'l', KeyChar 'l'])+ , ("every key repeats", keys [EventKeyPress keyL 0, EventKeyRepeat keyL 0] == [KeyChar 'l', KeyChar 'l'])+ , ( "losing the keyboard lets go of the keys held"+ , null (inputKeysHeld blurred) && pressedIn (KeyChar 'l') blurred && releasedIn (KeyChar 'l') blurred+ && inputModifiers blurred == noModifiers+ )+ , ( "function keys, paging and Super"+ , keys [EventKeyPress (R.rgfw_keyF1 + 4) 0, EventKeyPress R.rgfw_keyPageDown 0] == [KeyF 5, KeyPageDown]+ && mods [EventKeyPress keyL R.rgfw_modSuper] == noModifiers {modSuper = True}+ )+ , ( "the keypad types with Num Lock and navigates without"+ , keys [EventKeyPress pad1 R.rgfw_modNumLock] == [KeyChar '2']+ && keys [EventKeyPress pad1 0] == [KeyDown]+ && keys [EventKeyPress R.rgfw_keyPadReturn 0] == [KeyEnter]+ )+ , -- On X11 and Windows a modifier key's own events carry the bits from+ -- before them: Shift's press lacks Shift and its release still has it.+ ( "a modifier is held from its own press to its own release"+ , map mods+ [ [EventKeyPress R.rgfw_keyShiftL 0]+ , [EventKeyPress R.rgfw_keyControlR R.rgfw_modShift]+ , [EventKeyPress R.rgfw_keyShiftL 0, EventKeyRelease R.rgfw_keyShiftL R.rgfw_modShift]+ , [EventKeyRelease R.rgfw_keyAltR (R.rgfw_modAlt .|. R.rgfw_modSuper)]+ ]+ == [shift, shift {modCtrl = True}, noModifiers, noModifiers {modSuper = True}]+ )+ ]++-- | RGFW pointer translation, window repaints, and cursor shapes.+testRgfwPointer :: IORef Int -> IO ()+testRgfwPointer failed = do+ let pressedBy b = buttonsToList (inputButtonsPressed (applied [EventMouseButton b True]))+ buttons = R.rgfw_mouseMiddle : R.rgfw_mouseMisc1 : [R.rgfw_mouseMisc2 .. R.rgfw_mouseMisc2 + 3]+ gone = applied [EventMouseMotion 30 40, EventOther R.rgfw_mouseLeave]+ redraws evs = inputWindowRedraw (applied evs)+ wheel = inputScroll . applied . map (uncurry EventMouseScroll)+ checks failed "RGFW pointer: "+ [ -- RGFW's wheel is positive up and left, the input's down and right.+ ("a batch of wheel events accumulates", wheel [(0, 1), (0.5, 2)] == V2 (-0.5) (-3))+ , ("the wheel turned down and right scrolls down and right", wheel [(-1, -1)] == V2 1 1)+ , ( "middle, misc 1 and misc 2 are middle, back and forward; misc 3 to 5 the next buttons"+ , concatMap pressedBy buttons == [MouseMiddle, MouseBack, MouseForward] ++ map MouseOther [6, 7, 8]+ )+ , ("leaving the window moves the pointer off it", let V2 x y = inputMousePos gone in x < -1000 && y < -1000)+ , ( "an uncovered or restored window repaints in full"+ , redraws [EventOther R.rgfw_windowRefresh] && redraws [EventOther R.rgfw_windowRestored]+ && not (redraws [EventMouseMotion 1 1])+ )+ ]+ -- Each kind RGFW has a cursor for (its own fallback, bar the hidden one)+ -- shows a cursor of its own.+ let kinds = [minBound .. maxBound]+ native = [mapRgfwCursor k | k <- kinds, cursorFallback k == k, k /= UiCursorHidden]+ checks failed "RGFW cursors: "+ [ ("each native shape shows its own cursor", length (nub native) == length native)+ , ("every other kind falls back to a native one", all ((`elem` native) . mapRgfwCursor) kinds)+ ]++main :: IO ()+main =+ runChecks+ [ ("keys", testRgfwKeys)+ , ("pointer", testRgfwPointer)+ , ("glyphs", testGlyphs)+ , ("themed-raster", testThemedRaster)+ , ("window-layer", testWindowLayer)+ , ("gl-window", testGlWindow . check)+ , ("session-window", testSessionWindow . check)+ , ("child-window", testChildWindow . check)+ , ("wake", const testRgfwWake)+ ]