nano-ui-sdl-web (empty) → 0.2.0.0
raw patch · 26 files changed
+4752/−0 lines, 26 filesdep +basedep +bytestringdep +containersbinary-added
Dependencies added: base, bytestring, containers, nano-ui, nano-ui-emit, nano-ui-sdl-web, nano-ui-ttf, primitive, text, vector
Files
- CHANGELOG.md +12/−0
- LICENSE +20/−0
- LICENSE-Inter +92/−0
- README.md +104/−0
- cbits/nano_ui_web_atlas.c +159/−0
- cbits/nano_ui_web_atlas.h +45/−0
- examples/WebDemo.hs +39/−0
- lib/NanoUI/Backend/SdlWeb.hs +101/−0
- lib/NanoUI/SdlWeb/Internal/Debug.hs +29/−0
- lib/NanoUI/SdlWeb/Internal/Files.hs +142/−0
- lib/NanoUI/SdlWeb/Internal/Font.hs +146/−0
- lib/NanoUI/SdlWeb/Internal/Fonts.hs +83/−0
- lib/NanoUI/SdlWeb/Internal/Host.hs +359/−0
- lib/NanoUI/SdlWeb/Internal/Input.hs +203/−0
- lib/NanoUI/SdlWeb/Internal/Render.hs +339/−0
- lib/NanoUI/SdlWeb/Internal/Session.hs +559/−0
- nano-ui-sdl-web.cabal +137/−0
- scripts/build-wasi-deps.sh +143/−0
- scripts/build-web.sh +114/−0
- scripts/smoke-test.cjs +160/−0
- test/Spec.hs +555/−0
- web/favicon.svg +18/−0
- web/fonts/inter-extended.ttf binary
- web/index.html +28/−0
- web/main.js +34/−0
- web/nano-ui-sdl-web.js +1131/−0
+ CHANGELOG.md view
@@ -0,0 +1,12 @@+# Changelog++## 0.2.0.0 -- 2026-12-02++Initial release.++- `NanoUI.Backend.SdlWeb` runs `nano-ui` views in a browser `<canvas>` using GHC's `wasm32` backend, WebGL2 rendering (including `nano-ui-shader` GLSL ES 300 surface shaders and subtree effects), and `nano-ui-ttf` text shaping with bundled Inter (`LICENSE-Inter`).+- Supports `WebFontInstalled`, `WebFontUrl`, `WebFontSearch` (with optional Fontsource loading), runtime font switching (`setSdlWebUiFont`), and extended fallback fonts (`webFallbackFonts`).+- Browser file dialogs (`openWebFiles`, `openWebFolder`, `saveWebFile`) returning `WebFile` names and bytes.+- `requestAnimationFrame`-paced animation frames, viewport-aware wake pausing, pointer capture/touch handling, and `askSdlWebDebug` / `SdlWebDebugSnapshot` telemetry (`formatFpsRows`, `formatDrawRows`, `formatExplainRows`).+- Installs the browser loader (`web/`), `LICENSE-Inter`, `scripts/build-wasi-deps.sh`, optional static bundler `scripts/build-web.sh` (works both in downstream projects and in the repository), and headless Chromium smoke test (`scripts/smoke-test.cjs`) as Cabal `data-files`.+- 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-Inter view
@@ -0,0 +1,92 @@+Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION AND CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.
+ README.md view
@@ -0,0 +1,104 @@+# nano-ui-sdl-web++Browser backend for [nano-ui](https://github.com/goolord/nano-ui), targeting GHC's WebAssembly backend. Text shaping uses the same SDL3_ttf engine as [nano-ui-sdl](https://hackage.haskell.org/package/nano-ui-sdl) (HarfBuzz + FreeType into a texture atlas) and frames draw with WebGL2.++```haskell+{-# LANGUAGE CPP, OverloadedStrings #-}++import NanoUI+import NanoUI.Backend.SdlWeb (defaultSdlWebOptions, runSdlWebApp)++main :: IO ()+main = runSdlWebApp defaultSdlWebOptions (label "Hello")++#if defined(wasm32_HOST_ARCH)+foreign export javascript "nanoMain" main :: IO ()+#endif+```++`runSdlWebAppReduce` pairs `model -> NanoUIE msg ()` with an update function just like `runSdlAppReduce`. Configure page title (`webWindowSettings`), themes or `prefers-color-scheme` tracking (`webThemeFor`), fonts, base size, and extra UI scale through `SdlWebOptions`.++## Building for the browser++Building for WebAssembly requires Linux or macOS with [ghc-wasm-meta](https://gitlab.haskell.org/haskell-wasm/ghc-wasm-meta) (GHC 9.14, Cabal 3.14, and `node` on `PATH` for Template Haskell font embedding).++### 1. One-time WASI C libraries++Upstream SDL3 does not publish prebuilt `wasm32-wasi` static archives, so cross-compile FreeType, HarfBuzz, SDL3, and SDL3_ttf into `~/.nano-ui-wasi` once per machine using `scripts/build-wasi-deps.sh` (shipped in `nano-ui-sdl-web`'s `data-files` and source tarball):++```bash+source ~/.ghc-wasm/env+cabal unpack nano-ui-sdl-web+nano-ui-sdl-web-0.2.0.0/scripts/build-wasi-deps.sh+```++### 2. Project setup++Start from [`templates/web`](https://github.com/goolord/nano-ui/tree/main/templates/web) (`nix flake init -t github:goolord/nano-ui#web`), or configure an executable as a Wasm reactor exporting `nanoMain`:++```cabal+executable my-webapp+ main-is: Main.hs+ default-language: GHC2024+ default-extensions: OverloadedStrings+ build-depends:+ base >=4.20 && <4.23+ , nano-ui ^>=0.2+ , nano-ui-sdl-web ^>=0.2+ , text ^>=2.1+ if arch(wasm32)+ default-extensions: JavaScriptFFI+ ghc-options:+ -no-hs-main+ -optl-mexec-model=reactor+ "-optl-Wl,--export=hs_init,--export=nanoMain"+```++Add `split-sections: True` in `cabal.project` so the linker strips unreachable code:++```cabal+package *+ split-sections: True+```++### 3. Standard GHC Wasm pipeline++You can use Vite, esbuild, or your own HTML page directly. Build the `.wasm` binary and run GHC's `post-link.mjs` before `wasm-opt` strips the JSFFI custom section:++```bash+source ~/.ghc-wasm/env+export PKG_CONFIG_PATH=~/.nano-ui-wasi/lib/pkgconfig++wasm32-wasi-cabal build -j1 my-webapp+wasm="$(wasm32-wasi-cabal list-bin my-webapp)"+"$(wasm32-wasi-ghc --print-libdir)/post-link.mjs" -i "$wasm" -o dist-web/ghc_wasm_jsffi.js+wasm-opt --strip-debug -O2 "$wasm" -o dist-web/main.wasm+```++Serve three browser assets alongside `main.wasm` and `ghc_wasm_jsffi.js`:++- `web/nano-ui-sdl-web.js` (loaded before starting Wasm) and `web/main.js` (ES module loader), both installed in `nano-ui-sdl-web`'s Cabal `data-files` directory (`share/web/`).+- `@bjorn3/browser_wasi_shim` from npm.+- `fonts/inter-extended.ttf` (from `web/fonts/`), unless you set `webFallbackFonts = []` or supply your own font URLs.++If you prefer a self-contained static directory with no JS bundler, `scripts/build-web.sh [out-dir [cabal-target]]` runs the steps above and copies the assets (`CABAL_PROJECT` and `WASM_OPT_FLAGS` override defaults):++```bash+PKG_CONFIG_PATH=~/.nano-ui-wasi/lib/pkgconfig \+ bash path/to/nano-ui-sdl-web/scripts/build-web.sh dist-web my-webapp+python3 -m http.server -d dist-web 8000+```++## Browser-specific behavior++- **Fonts:** Embedded Inter covers printable ASCII to keep `.wasm` small; extended Latin, Greek, Cyrillic, and symbols come from `webFallbackFonts` (`fonts/inter-extended.ttf` by default). `WebFontSearch` and `webFontFamilies` use Chromium's Local Font Access API (prompting lazily on the first canvas click/key, or explicitly via `listWebFontFamilies`) and an optional Fontsource CDN catalog (`webFontService = Just Fontsource`, off by default so apps make no third-party requests unless you opt in). Explicit fonts also load via `WebFontUrl` (requires CORS if cross-origin) or `WebFontBytes`.+- **File dialogs:** `openWebFiles`, `openWebFolder`, and `saveWebFile` work on filenames and byte contents (`showSaveFilePicker` in Chromium, standard download fallback in Firefox and Safari). Launch them from a `useTask` started inside a click handler so the browser allows the picker gesture.+- **Canvas and windowing:** Give `<canvas>` an explicit CSS size; the backend matches the WebGL drawing buffer to that box multiplied by `devicePixelRatio` and tracks resizes. `setWindowTitle` updates `document.title`, and clipboard reads see text copied or pasted within the page.++## Documentation++- [The nano-ui Book](https://goolord.github.io/nano-ui/book/): Tutorials, widget gallery, and backend overview.++## License++MIT. The bundled Inter font is under the SIL Open Font License 1.1 (`LICENSE-Inter`); include `LICENSE-Inter` when distributing builds.
+ cbits/nano_ui_web_atlas.c view
@@ -0,0 +1,159 @@+#include "nano_ui_web_atlas.h"++#include <stdlib.h>+#include <string.h>++/* Glyphs fill page 0, then each later page in turn. A reset empties every+ * page but keeps their memory, and a page is cleared when it is opened+ * again. Placement is nano_ui_ttf_shared.h's, which nano_ui_text_atlas.c+ * uses too, so a glyph lands at the same UVs on both backends. */+struct NanoUiWebAtlas {+ uint8_t *pixels[NANO_UI_WEB_ATLAS_PAGES];+ /* The changed rect of each page as x0, y0, x1, y1; empty when x1 <= x0. */+ int dirty[NANO_UI_WEB_ATLAS_PAGES][4];+ NanoUiAtlasCursor cur;+};++static void mark_dirty(NanoUiWebAtlas *atlas, int page, int x, int y, int w, int h)+{+ int *d = atlas->dirty[page];+ if (d[2] <= d[0]) {+ d[0] = x;+ d[1] = y;+ d[2] = x + w;+ d[3] = y + h;+ return;+ }+ d[0] = x < d[0] ? x : d[0];+ d[1] = y < d[1] ? y : d[1];+ d[2] = x + w > d[2] ? x + w : d[2];+ d[3] = y + h > d[3] ? y + h : d[3];+}++/* Every page gets the white patch, so each starts its cursor the same way;+ * shapes sample the one on page 0. */+static void clear_page(NanoUiWebAtlas *atlas, int page)+{+ const int size = NANO_UI_WEB_ATLAS_SIZE;+ uint8_t *px = atlas->pixels[page];+ memset(px, 0, (size_t)size * size * 4);+ for (int y = 0; y < NANO_UI_WHITE_PATCH_SIZE; y++) {+ memset(px + (size_t)y * size * 4, 0xff, NANO_UI_WHITE_PATCH_SIZE * 4);+ }+ mark_dirty(atlas, page, 0, 0, size, size);+}++/* Start glyphs on page `page`: allocate or clear it and put the cursor+ * after its white patch. The atlas is a void pointer for+ * nano_ui_atlas_slot_for. */+static bool open_page(void *self, int page)+{+ NanoUiWebAtlas *atlas = (NanoUiWebAtlas *)self;+ if (!atlas->pixels[page]) {+ const size_t size = NANO_UI_WEB_ATLAS_SIZE;+ atlas->pixels[page] = (uint8_t *)malloc(size * size * 4);+ if (!atlas->pixels[page]) {+ return false;+ }+ }+ clear_page(atlas, page);+ nano_ui_atlas_cursor_open(&atlas->cur, page);+ return true;+}++NanoUiWebAtlas *nano_ui_web_atlas_create(void)+{+ return (NanoUiWebAtlas *)calloc(1, sizeof(NanoUiWebAtlas));+}++void nano_ui_web_atlas_destroy(NanoUiWebAtlas *atlas)+{+ if (!atlas) {+ return;+ }+ for (int i = 0; i < NANO_UI_WEB_ATLAS_PAGES; i++) {+ free(atlas->pixels[i]);+ }+ free(atlas);+}++uint8_t *nano_ui_web_atlas_pixels(NanoUiWebAtlas *atlas, int page)+{+ if (!atlas || page < 0 || page >= NANO_UI_WEB_ATLAS_PAGES) {+ return NULL;+ }+ return atlas->pixels[page];+}++bool nano_ui_web_atlas_take_dirty(NanoUiWebAtlas *atlas, int page, int out[4])+{+ if (!atlas || page < 0 || page >= NANO_UI_WEB_ATLAS_PAGES || !atlas->pixels[page]) {+ return false;+ }+ int *d = atlas->dirty[page];+ if (d[2] <= d[0] || d[3] <= d[1]) {+ return false;+ }+ out[0] = d[0];+ out[1] = d[1];+ out[2] = d[2] - d[0];+ out[3] = d[3] - d[1];+ d[0] = d[1] = d[2] = d[3] = 0;+ return true;+}++void nano_ui_web_atlas_mark_all_dirty(NanoUiWebAtlas *atlas)+{+ if (!atlas) {+ return;+ }+ for (int i = 0; i < NANO_UI_WEB_ATLAS_PAGES; i++) {+ if (atlas->pixels[i]) {+ mark_dirty(atlas, i, 0, 0, NANO_UI_WEB_ATLAS_SIZE, NANO_UI_WEB_ATLAS_SIZE);+ }+ }+}++bool nano_ui_web_atlas_insert_surface(+ NanoUiWebAtlas *atlas,+ SDL_Surface *surface,+ float uv[4])+{+ if (!atlas || !surface || !uv || surface->format != SDL_PIXELFORMAT_RGBA32) {+ return false;+ }+ int gw = surface->w;+ int gh = surface->h;+ if (gw <= 0 || gh <= 0) {+ return false;+ }+ int page = 0;+ int x = 0;+ int y = 0;+ if (!nano_ui_atlas_slot_for(&atlas->cur, atlas, open_page, gw, gh, &page, &x, &y)) {+ return false;+ }+ const size_t stride = (size_t)NANO_UI_WEB_ATLAS_SIZE * 4;+ uint8_t *dst = atlas->pixels[page] + (size_t)y * stride + (size_t)x * 4;+ const uint8_t *src = (const uint8_t *)surface->pixels;+ for (int row = 0; row < gh; row++) {+ memcpy(dst + (size_t)row * stride, src + (size_t)row * surface->pitch, (size_t)gw * 4);+ }+ mark_dirty(atlas, page, x, y, gw, gh);+ nano_ui_atlas_commit(&atlas->cur, page, x, y, gw, gh, uv);+ return true;+}++void nano_ui_web_atlas_reset(NanoUiWebAtlas *atlas)+{+ if (!atlas) {+ return;+ }+ /* Page 0 is cleared now; the others are cleared when glyphs reach them+ * again. */+ if (atlas->pixels[0]) {+ open_page(atlas, 0);+ } else {+ atlas->cur.pages = 0;+ }+}
+ cbits/nano_ui_web_atlas.h view
@@ -0,0 +1,45 @@+#ifndef NANO_UI_WEB_ATLAS_H+#define NANO_UI_WEB_ATLAS_H++#include <SDL3/SDL.h>+#include <stdbool.h>+#include <stdint.h>++#include "nano_ui_ttf_shared.h"++/* Pages the atlas opens before it is out of space, and the width and height+ * of a page in pixels: nano-ui-ttf's, which nano_ui_text_atlas.c in+ * nano-ui-sdl uses too. */+#define NANO_UI_WEB_ATLAS_PAGES NANO_UI_GLYPH_ATLAS_PAGES+#define NANO_UI_WEB_ATLAS_SIZE NANO_UI_GLYPH_ATLAS_SIZE++/* The glyph atlas of nano_ui_text_atlas.c in nano-ui-sdl, kept in memory+ * instead of SDL textures: each page is RGBA32 pixels, and the area written+ * since the page was last uploaded is kept so only that goes to the GPU. */+typedef struct NanoUiWebAtlas NanoUiWebAtlas;++NanoUiWebAtlas *nano_ui_web_atlas_create(void);+void nano_ui_web_atlas_destroy(NanoUiWebAtlas *atlas);++/* The pixels of page `page`, NANO_UI_WEB_ATLAS_SIZE * 4 bytes a row, or NULL+ * for a page never opened. */+uint8_t *nano_ui_web_atlas_pixels(NanoUiWebAtlas *atlas, int page);++/* Write the rect of page `page` changed since the last call (x, y, width,+ * height) and forget it. False when nothing changed. */+bool nano_ui_web_atlas_take_dirty(NanoUiWebAtlas *atlas, int page, int out[4]);++/* Mark every open page changed in full, after the GPU lost its textures. */+void nano_ui_web_atlas_mark_all_dirty(NanoUiWebAtlas *atlas);++/* Copy an RGBA32 glyph surface into the atlas, on a new page once the last+ * one is full, and write its u0, v0, u1 and v1: normalised to [0,1] within+ * the page, plus the page's number in u. False when no page has room. */+bool nano_ui_web_atlas_insert_surface(+ NanoUiWebAtlas *atlas,+ SDL_Surface *surface,+ float uv[4]);++void nano_ui_web_atlas_reset(NanoUiWebAtlas *atlas);++#endif
+ examples/WebDemo.hs view
@@ -0,0 +1,39 @@+{-# LANGUAGE CPP #-}++-- | Minimal smoke-test view for the browser backend: a counter, text input,+-- font-size slider, and checkbox rendered with the bundled Inter font.+module Main (main) where++import Data.Text qualified as T+import NanoUI+import NanoUI.Backend.SdlWeb (SdlWebOptions (..), defaultSdlWebOptions, runSdlWebApp)++main :: IO ()+main =+ runSdlWebApp+ defaultSdlWebOptions {webWindowSettings = defaultWindowSettings {wsTitle = "nano-ui on the web"}}+ demo++#if defined(wasm32_HOST_ARCH)+foreign export javascript "nanoMain" main :: IO ()+#endif++demo :: NanoUI ()+demo = columnWith (gap 12 . padAll 24) $ do+ heading "nano-ui-sdl-web"+ label "Text shaped by SDL_ttf, rendered with WebGL2."+ row $ do+ n <- useVar (0 :: Int)+ whenM (button "-") (modifyVar n (subtract 1))+ label . T.pack . show =<< readVar n+ whenM (button "+") (modifyVar n (+ 1))+ name <- useVar "world"+ size <- useVar 16+ shout <- useVar False+ textInput name+ slider 10 48 size+ checkbox "Shout" shout+ greeting <- ("Hello, " <>) . (<> "!") <$> readVar name+ loud <- readVar shout+ px <- readVar size+ labelWith (fontSize px) (if loud then T.toUpper greeting else greeting)
+ lib/NanoUI/Backend/SdlWeb.hs view
@@ -0,0 +1,101 @@+-- |+-- Module : NanoUI.Backend.SdlWeb+-- Description : WebAssembly browser backend for nano-ui+-- Copyright : (c) 2026 Zachary Churchill+-- License : MIT+-- Maintainer : zacharyachurchill@gmail.com+--+-- Run nano-ui views in a browser canvas with the SDL backend's text:+-- SDL_ttf shapes and rasterises glyphs (FreeType and HarfBuzz), the same+-- glyph atlas layout holds them, and WebGL2 draws the frame's triangles as+-- @SDL_RenderGeometry@ does on the desktop. Build the program with+-- @wasm32-wasi-ghc@ and load it with @web/nano-ui-sdl-web.js@; see the+-- package README.+--+-- > main :: IO ()+-- > main = runSdlWebApp defaultSdlWebOptions (label "Hello")+-- >+-- > foreign export javascript "nanoMain" main :: IO ()+module NanoUI.Backend.SdlWeb+ ( -- * Running+ runSdlWebApp+ , runSdlWebAppReduce+ , SdlWebOptions (..)+ , defaultSdlWebOptions+ , WebFont (..)+ , browserAvailable++ -- * Fonts+ , WebFontService (..)+ , webFontFamilies+ , setSdlWebUiFont+ , listWebFontFamilies++ -- * File dialogs+ , FileFilter (..)+ , FileDialogOptions (..)+ , defaultFileDialogOptions+ , WebFile (..)+ , openWebFiles+ , openWebFolder+ , saveWebFile++ -- * Debugging+ , SdlWebDebugSnapshot (..)+ , CoreDebugSnapshot (..)+ , askSdlWebDebug+ , formatFpsRows+ , formatDrawRows+ , formatExplainRows+ ) where++import NanoUI (NanoUI)+import NanoUI.Emit (NanoUIE, newReducer, reduceFrame)+import NanoUI.Backend (runFrame)+import NanoUI.Internal.Debug (CoreDebugSnapshot (..), formatDrawRows, formatExplainRows, formatFpsRows)+import NanoUI.SdlWeb.Internal.Debug (SdlWebDebugSnapshot (..))+import NanoUI.SdlWeb.Internal.Files+ ( FileDialogOptions (..)+ , FileFilter (..)+ , WebFile (..)+ , defaultFileDialogOptions+ , openWebFiles+ , openWebFolder+ , saveWebFile+ )+import NanoUI.SdlWeb.Internal.Host (browserAvailable, browserHost)+import NanoUI.SdlWeb.Internal.Session+ ( SdlWebOptions (..)+ , WebFont (..)+ , WebFontService (..)+ , askSdlWebDebug+ , defaultSdlWebOptions+ , listWebFontFamilies+ , runWebSession+ , setSdlWebUiFont+ , webFontFamilies+ )++-- | Run a view in the page's canvas until it quits. The view is rebuilt for+-- each frame. In a native build this throws: the program runs only as+-- WebAssembly in a browser ('browserAvailable').+runSdlWebApp :: SdlWebOptions -> NanoUI () -> IO ()+runSdlWebApp opts ui = do+ host <- browserHost+ runWebSession host opts $ \ctx inp ->+ (\(_, drawData, dirty) -> (drawData, dirty)) <$> runFrame ctx inp ui++-- | Run a model-driven view, folding emitted messages through the update+-- function in emission order, as @runSdlAppReduce@ does on the desktop.+runSdlWebAppReduce ::+ Eq model =>+ SdlWebOptions+ -> (msg -> model -> model)+ -> model+ -> (model -> NanoUIE msg ())+ -> IO ()+runSdlWebAppReduce opts update model view = do+ host <- browserHost+ reducer <- newReducer update model+ runWebSession host opts $ \ctx inp ->+ (\(_, drawData, dirty) -> (drawData, dirty)) <$> reduceFrame reducer ctx inp view
+ lib/NanoUI/SdlWeb/Internal/Debug.hs view
@@ -0,0 +1,29 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | What the browser session reports about itself: the core's frame timings+-- with the canvas, its pixel ratio, the UI font and the WebGL renderer.+module NanoUI.SdlWeb.Internal.Debug+ ( SdlWebDebugSnapshot (..)+ ) where++import Data.Text (Text)+import NanoUI.Internal.Debug (CoreDebugSnapshot)++-- | A sample of the session, refreshed at most four times a second while a+-- view asks for it. The core's window size is the canvas's CSS box in+-- layout units.+data SdlWebDebugSnapshot = SdlWebDebugSnapshot+ { dbgCore :: !CoreDebugSnapshot+ , dbgScale :: !Float+ -- ^ Drawing-buffer pixels per layout unit: the pixel ratio times the UI+ -- scale.+ , dbgPixelRatio :: !Float+ -- ^ The page's @devicePixelRatio@, which follows the browser's zoom.+ , dbgFont :: !String+ -- ^ The UI font: the bundled Inter, an installed family or a URL.+ , dbgRenderer :: !Text+ -- ^ The WebGL renderer, as the browser names it.+ , dbgRefreshHz :: !Int+ -- ^ The rate frames are paced at while something animates.+ }+ deriving (Eq, Show)
+ lib/NanoUI/SdlWeb/Internal/Files.hs view
@@ -0,0 +1,142 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | File dialogs in the browser. A page sees no paths: opening hands over+-- the chosen files' names and bytes, and saving hands the browser bytes to+-- write where the user says (a save dialog where the browser has one, else+-- a download under the suggested name). Browsers show these only right+-- after a click or key press on the page, so run them from a task the press+-- starts ('NanoUI.useTask'); each waits for the user.+module NanoUI.SdlWeb.Internal.Files+ ( FileFilter (..)+ , FileDialogOptions (..)+ , defaultFileDialogOptions+ , WebFile (..)+ , FileDialogMode (..)+ , pickFiles+ , saveFile+ , decodePicked+ , openWebFiles+ , openWebFolder+ , saveWebFile+ ) where++import Data.Bits (shiftL, (.|.))+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Internal as BSI+import Data.ByteString.Unsafe (unsafeUseAsCStringLen)+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Foreign.Ptr (castPtr)+import NanoUI.SdlWeb.Internal.Host (WebHost (..), browserAvailable, browserHost, withUtf8)++-- | A file type to offer, as nano-ui-sdl's dialogs take it.+data FileFilter = FileFilter+ { filterName :: !Text+ -- ^ Human-readable label, e.g. @"Haskell source"@.+ , filterPattern :: !Text+ -- ^ Semicolon-separated extension list, e.g. @"hs;lhs"@, or @"*"@.+ }+ deriving (Eq, Show)++-- | Options for the browser's file dialogs. Browsers pick the starting+-- folder themselves, so there is no default location.+data FileDialogOptions = FileDialogOptions+ { dialogFilters :: ![FileFilter]+ -- ^ File types to offer (ignored when choosing a folder).+ , dialogAllowMany :: !Bool+ -- ^ Allow choosing more than one file.+ }+ deriving (Eq, Show)++-- | No filters, one file.+defaultFileDialogOptions :: FileDialogOptions+defaultFileDialogOptions = FileDialogOptions [] False++-- | A file the user chose: its name (for a folder's files, the path inside+-- the folder, with @/@) and its bytes.+data WebFile = WebFile+ { webFileName :: !String+ , webFileBytes :: !ByteString+ }+ deriving (Eq, Show)++-- | What 'pickFiles' asks the user for.+data FileDialogMode = PickFiles | PickFolder+ deriving (Eq, Show)++-- | Show the file chooser on a host. 'Nothing' when the user cancelled or+-- the chooser failed.+pickFiles :: WebHost -> FileDialogMode -> FileDialogOptions -> IO (Maybe [WebFile])+pickFiles host mode opts = do+ let modeCode = case mode of PickFiles -> 0; PickFolder -> 1+ n <- withUtf8 (filterLines (dialogFilters opts)) $ \p len ->+ whPickFiles host modeCode (dialogAllowMany opts) p len+ if n < 0+ then pure Nothing+ else Just . decodePicked <$> BSI.create n (whTakePicked host)++-- | Save bytes on a host, suggesting a name. The name the file was saved+-- under (the suggested one for a download), or 'Nothing' when the user+-- cancelled or saving failed.+saveFile :: WebHost -> FileDialogOptions -> String -> ByteString -> IO (Maybe String)+saveFile host opts name bytes = do+ n <-+ withUtf8 (T.pack name) $ \np nn ->+ withUtf8 (filterLines (dialogFilters opts)) $ \fp fn ->+ unsafeUseAsCStringLen bytes $ \(dp, dn) ->+ whSaveFile host np nn fp fn (castPtr dp) dn+ if n < 0+ then pure Nothing+ else Just . T.unpack . TE.decodeUtf8Lenient <$> BSI.create n (whTakePicked host)++-- | The files in the answer from 'whPickFiles': per file a 32-bit little-endian+-- name length, the UTF-8 name, a 32-bit length and the bytes. A truncated+-- record ends the list.+decodePicked :: ByteString -> [WebFile]+decodePicked buf+ | BS.length buf < 4 = []+ | otherwise =+ let (nameLen, rest) = word32 buf+ (name, rest') = BS.splitAt nameLen rest+ (dataLen, rest'') = word32 rest'+ (bytes, rest''') = BS.splitAt dataLen rest''+ in if BS.length name < nameLen || BS.length rest' < 4 || BS.length bytes < dataLen+ then []+ else WebFile (T.unpack (TE.decodeUtf8Lenient name)) bytes : decodePicked rest'''+ where+ word32 b =+ ( foldr (\i acc -> acc `shiftL` 8 .|. fromIntegral (BS.index b i)) 0 [0 .. 3]+ , BS.drop 4 b+ )++-- | The filters as the page reads them: a line per filter, its name, a tab+-- and its extension list.+filterLines :: [FileFilter] -> Text+filterLines = T.intercalate "\n" . map (\f -> filterName f <> "\t" <> filterPattern f)++-- | Let the user choose files, and read them; 'Nothing' when they+-- cancelled, or outside a browser. Run it from a task a press starts.+openWebFiles :: FileDialogOptions -> IO (Maybe [WebFile])+openWebFiles opts = inBrowser Nothing $ \host -> pickFiles host PickFiles opts++-- | Let the user choose a folder, and read every file in it, named by its+-- path inside the folder; 'Nothing' when they cancelled, or outside a+-- browser. Run it from a task a press starts.+openWebFolder :: IO (Maybe [WebFile])+openWebFolder = inBrowser Nothing $ \host -> pickFiles host PickFolder defaultFileDialogOptions++-- | Save bytes as a file, suggesting a name. Chromium-based browsers show a+-- save dialog (@showSaveFilePicker@, which no other browser implements);+-- the others download the file under the suggested name, which Firefox+-- saves where its "Always ask you where to save files" setting says. The+-- name it was saved under, or 'Nothing' when the user cancelled, saving+-- failed, or this is not a browser. Run it from a task a press starts.+saveWebFile :: FileDialogOptions -> String -> ByteString -> IO (Maybe String)+saveWebFile opts name bytes = inBrowser Nothing $ \host -> saveFile host opts name bytes++inBrowser :: a -> (WebHost -> IO a) -> IO a+inBrowser outside k+ | browserAvailable = k =<< browserHost+ | otherwise = pure outside
+ lib/NanoUI/SdlWeb/Internal/Font.hs view
@@ -0,0 +1,146 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | Browser SDL_ttf font cache and in-memory glyph atlas integration built+-- over "NanoUI.Ttf.Internal.Font", with fallback fonts for the characters+-- the UI font lacks: the page has no system fonts to find them in, so they+-- are fonts the session loaded at start.+module NanoUI.SdlWeb.Internal.Font+ ( FontSource (..)+ , WebFallbacks+ , newWebFallbacks+ , webFontHooks+ , withTtf+ , fontSourceLabel+ , embeddedFontSource+ , GlyphAtlas+ , newGlyphAtlas+ , destroyGlyphAtlas+ , prepareGlyphAtlasForFrame+ , markGlyphPagesDirty+ , glyphPageUploads+ , closeEvictedFonts+ , glyphAtlasFull+ , glyphAtlasSize+ , SdlFontCache+ , sfcGlyphAtlas+ , newSdlFontCache+ , destroySdlFontCache+ , reloadSdlFontCache+ , sdlFontCacheSource+ , withSdlFontCache+ ) where++import Control.Monad (forM, when)+import Data.ByteString (ByteString)+import Data.IORef (IORef)+import Data.Maybe (catMaybes)+import Data.Word (Word8)+import Foreign.C.Types (CBool (..), CFloat (..), CInt (..))+import Foreign.Marshal.Array (allocaArray, peekArray)+import Foreign.Ptr (Ptr, nullPtr)+import NanoUI.Backend (glyphAtlasPages)+import NanoUI.Ttf.Internal.Font+ ( AtlasOps (..)+ , FontHooks (..)+ , FontSource (..)+ , GlyphAtlas (..)+ , SdlFontCache (..)+ , closeEvictedFonts+ , defaultFontHooks+ , destroyGlyphAtlas+ , destroySdlFontCache+ , embeddedFontSource+ , fontSourceLabel+ , glyphAtlasFull+ , glyphAtlasSize+ , openFontBytes+ , prepareGlyphAtlasForFrame+ , reloadSdlFontCache+ , sdlFontCacheSource+ , withSdlFontCache+ )+import NanoUI.Ttf.Internal.Font qualified as Ttf+import NanoUI.Ttf.Internal.Support (CoveragePool, closeCoveragePool, ensurePoolCoverage, newCoveragePool)++-- | Fallback fonts loaded from bytes, backed by a lazy 'CoveragePool'.+newtype WebFallbacks = WebFallbacks (CoveragePool ByteString)++-- | Fallbacks from font files' bytes, tried in order.+newWebFallbacks :: [ByteString] -> IO WebFallbacks+newWebFallbacks sources = WebFallbacks <$> newCoveragePool (pure sources) (`openFontBytes` 12)++-- | Font hooks that attach a fallback to a face for each character it+-- lacks, as nano-ui-sdl does with the system's fonts, and close the probes+-- before SDL_ttf shuts down.+webFontHooks :: WebFallbacks -> FontHooks+webFontHooks (WebFallbacks pool) =+ defaultFontHooks+ { fhEnsureCoverage = ensurePoolCoverage pool+ , fhOnTtfQuit = closeCoveragePool pool+ }++-- | Bracket an action with SDL_ttf initialisation, closing the hooks'+-- probes before it shuts down.+withTtf :: FontHooks -> IO a -> IO a+withTtf = Ttf.withTtf++-- | Open the base sans and mono fonts at the pixel density, with the hooks'+-- fallbacks.+newSdlFontCache :: FontHooks -> FontSource -> FontSource -> GlyphAtlas -> Float -> IORef Float -> IO SdlFontCache+newSdlFontCache = Ttf.newSdlFontCache++-- | Create a CPU-backed glyph atlas whose dirty sub-rects upload to WebGL2.+newGlyphAtlas :: IO GlyphAtlas+newGlyphAtlas = do+ atlas <- textAtlasCreate+ when (atlas == nullPtr) $ fail "nano_ui_web_atlas_create failed (glyph)"+ Ttf.newGlyphAtlas+ AtlasOps+ { aoHandle = atlas+ , aoDestroy = textAtlasDestroy atlas+ , aoReset = textAtlasReset atlas+ , aoInsertSurface = textAtlasInsertSurface atlas+ }++-- | The glyph pages changed since the last call: each page's number, its+-- pixels ('glyphAtlasSize' square, RGBA, 4 bytes a pixel) and the changed+-- rect as x, y, width and height.+glyphPageUploads :: GlyphAtlas -> IO [(Int, Ptr Word8, (Int, Int, Int, Int))]+glyphPageUploads ga = fmap catMaybes . forM [0 .. glyphAtlasPages - 1] $ \page ->+ allocaArray 4 $ \out -> do+ let handle = aoHandle (gaOps ga)+ changed <- textAtlasTakeDirty handle (fromIntegral page) out+ if changed == 0+ then pure Nothing+ else do+ rect <- peekArray 4 out+ pixels <- textAtlasPixels handle (fromIntegral page)+ pure $ case map fromIntegral rect of+ [x, y, w, h] -> Just (page, pixels, (x, y, w, h))+ _ -> Nothing++-- | Upload every open page in full with the next 'glyphPageUploads', after+-- the GPU lost its textures.+markGlyphPagesDirty :: GlyphAtlas -> IO ()+markGlyphPagesDirty = textAtlasMarkAllDirty . aoHandle . gaOps++foreign import ccall unsafe "nano_ui_web_atlas_create"+ textAtlasCreate :: IO (Ptr ())++foreign import ccall unsafe "nano_ui_web_atlas_destroy"+ textAtlasDestroy :: Ptr () -> IO ()++foreign import ccall unsafe "nano_ui_web_atlas_reset"+ textAtlasReset :: Ptr () -> IO ()++foreign import ccall unsafe "nano_ui_web_atlas_pixels"+ textAtlasPixels :: Ptr () -> CInt -> IO (Ptr Word8)++foreign import ccall unsafe "nano_ui_web_atlas_take_dirty"+ textAtlasTakeDirty :: Ptr () -> CInt -> Ptr CInt -> IO CBool++foreign import ccall unsafe "nano_ui_web_atlas_mark_all_dirty"+ textAtlasMarkAllDirty :: Ptr () -> IO ()++foreign import ccall unsafe "nano_ui_web_atlas_insert_surface"+ textAtlasInsertSurface :: Ptr () -> Ptr () -> Ptr CFloat -> IO CBool
+ lib/NanoUI/SdlWeb/Internal/Fonts.hs view
@@ -0,0 +1,83 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | Fonts beyond the bundled Inter: the families installed on the machine,+-- which the browser lists and hands over as bytes through the Local Font+-- Access API once the user allows it, a font service's families, and font+-- files fetched by URL. Also the WebGL renderer's name, for the debug+-- snapshot. Each reads a+-- 'WebHost'; the browser's calls are in "NanoUI.SdlWeb.Internal.Host".+module NanoUI.SdlWeb.Internal.Fonts+ ( FontOrigin (..)+ , findFontFamilies+ , knownFontFamilies+ , loadFontBytes+ , searchCandidates+ , rendererName+ ) where++import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Internal as BSI+import Data.List (nub)+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Foreign.Marshal.Alloc (allocaBytes)+import Foreign.Ptr (castPtr)+import NanoUI.SdlWeb.Internal.Host (WebHost (..), readHostText, withUtf8)+import NanoUI.Ttf.Internal.Support (expandGenericFamily, normalizeFamily)++-- | Where 'loadFontBytes' finds a font.+data FontOrigin+ = InstalledFamily+ -- ^ An installed family, by name; its regular face, else its first.+ | FontUrl+ -- ^ A font file at a URL, fetched with the page's credentials rules.+ | FamilyByName+ -- ^ A family by name: installed when the user has allowed it, else from+ -- the font service, if the session has one.+ deriving (Eq, Show)++-- | The installed font families, sorted and without repeats, or why they+-- cannot be listed. Browsers ask the user the first time, and only right+-- after a click or key press on the page; Chromium-based browsers have the+-- API, Firefox and Safari do not.+findFontFamilies :: WebHost -> IO (Either String [String])+findFontFamilies host = do+ n <- whFindFonts host+ case n of+ -1 -> pure (Left "this browser cannot list installed fonts (Chromium-based browsers can)")+ _+ | n < 0 -> pure (Left "access to the installed fonts was declined")+ | n == 0 -> pure (Right [])+ | otherwise -> allocaBytes n $ \buf -> do+ whTakeFontList host buf+ names <- TE.decodeUtf8Lenient <$> BS.packCStringLen (castPtr buf, n)+ pure (Right (nub (filter (not . null) (map T.unpack (T.lines names)))))++-- | A font file's bytes, or 'Nothing' when it could not be loaded (no such+-- family, a failed fetch, access declined).+loadFontBytes :: WebHost -> FontOrigin -> String -> IO (Maybe ByteString)+loadFontBytes host origin name = do+ let kind = case origin of InstalledFamily -> 0; FontUrl -> 1; FamilyByName -> 2+ n <- withUtf8 (T.pack name) (whLoadFont host kind)+ if n <= 0+ then pure Nothing+ else Just <$> BSI.create n (whTakeFontBytes host)++-- | The font families known so far: the installed ones the user has let+-- the browser list, then the font service's catalogue, without repeats.+knownFontFamilies :: WebHost -> IO [String]+knownFontFamilies host =+ maybe [] (filter (not . null) . map T.unpack . T.lines) <$> readHostText (whFontFamilies host)++-- | The families a search tries for a name: the name itself, or for the+-- generic CSS families (@sans-serif@, @serif@, @monospace@) the same common+-- families nano-ui-sdl's search tries.+searchCandidates :: String -> [String]+searchCandidates name = fromMaybe [name] (expandGenericFamily (normalizeFamily name))++-- | The WebGL renderer's description, as the browser gives it.+rendererName :: WebHost -> IO Text+rendererName host = fromMaybe "WebGL2" <$> readHostText (whRendererInfo host)
+ lib/NanoUI/SdlWeb/Internal/Host.hs view
@@ -0,0 +1,359 @@+{-# LANGUAGE CPP #-}+{-# OPTIONS_HADDOCK not-home #-}++-- | What a session asks of the page it runs in: the canvas, the event+-- queue, WebGL, the text input element and the clipboard. 'browserHost'+-- calls @web/nano-ui-sdl-web.js@ through GHC's JavaScript FFI when built+-- with @wasm32-wasi-ghc@. A native build has the same module with every+-- browser call failing, so the rest of the package builds and its tests+-- run against a 'WebHost' of their own.+--+-- FFI conventions. The JavaScript imports are @unsafe@, synchronous calls,+-- except the wait for events, the font queries and the file dialogs: a+-- @safe@ import runs as an async function, so the calling Haskell thread+-- waits for its promise while the browser's event loop runs and delivers+-- the events. Pointers passed to the page point into the module's memory, which the page reads and writes through views of it.+-- Text crosses as UTF-8 bytes and a length. The wake ('whWake') is safe from+-- any Haskell thread. The C imports in "NanoUI.SdlWeb.Internal.Font" are+-- @unsafe@ calls into the text atlas.+module NanoUI.SdlWeb.Internal.Host+ ( WebHost (..)+ , browserHost+ , browserAvailable+ -- * Event records+ , eventRecordSize+ -- * Draw command records+ , commandRecordSize+ , imageAtlasSlot+ -- * Canvas facts+ , CanvasInfo (..)+ , queryCanvas+ -- * Host UTF-8 helpers+ , withUtf8+ , readHostText+ ) where++import qualified Data.ByteString as BS+import Data.ByteString.Unsafe (unsafeUseAsCStringLen)+import Data.Int (Int32)+import Data.Text (Text)+import qualified Data.Text.Encoding as TE+import Data.Word (Word8)+import Foreign.Marshal.Alloc (allocaBytes)+import Foreign.Marshal.Array (allocaArray, peekArray)+import Foreign.Ptr (Ptr, castPtr, nullPtr)+#if defined(wasm32_HOST_ARCH)+import Control.Exception (evaluate)+import Control.Monad (void)+#endif++-- | The page's side of a session. Pointers are into the module's memory;+-- the page reads and writes through views of it. Text goes across as UTF-8+-- bytes and a length.+data WebHost = WebHost+ { whQueryCanvas :: Ptr Float -> IO ()+ -- ^ Write five floats: the canvas's CSS width and height, the device+ -- pixel ratio, 1 when the page has keyboard focus (else 0), and the+ -- colour scheme the page prefers (0 none, 1 light, 2 dark).+ , whTakeEvents :: Ptr Word8 -> Int -> IO Int+ -- ^ Move up to @n@ queued events into the buffer, 'eventRecordSize'+ -- bytes each, and answer how many.+ , whWaitEvents :: Int -> IO ()+ -- ^ Return once an event is queued, a wake ('whWake') arrived, or the+ -- milliseconds passed; a negative wait has no limit. Returns at once when+ -- either is already pending.+ , whWake :: IO ()+ -- ^ End the current wait, or the next one. Safe from any Haskell thread.+ , whResizeBacking :: Int -> Int -> IO ()+ -- ^ Size the canvas's drawing buffer in device pixels.+ , whUploadTexture :: Int -> Int -> Int -> Ptr Word8 -> Int -> Int -> Int -> Int -> Int -> IO ()+ -- ^ Texture slot, its width and height, RGBA pixels and their row length+ -- in pixels, then the rect to copy (x, y, width, height). The texture is+ -- made, or remade at a new size, before the copy.+ , whBeginFrame :: Bool -> Double -> Double -> Double -> Double -> Double -> Int -> Int -> IO ()+ -- ^ Whether to clear first, the clear colour (red, green, blue, alpha,+ -- 0 to 1), the scale from layout units to device pixels, and the+ -- drawing buffer's width and height.+ , whDraw :: Ptr Word8 -> Int -> Ptr Word8 -> Int -> Ptr Word8 -> Int -> IO ()+ -- ^ Vertices and their count (32 bytes each: position, colour, UV, as+ -- 32-bit floats), indices and their count (32-bit), then draw commands+ -- and their count ('commandRecordSize' bytes each).+ , whRegisterShader :: Int -> Ptr Word8 -> Int -> IO Bool+ -- ^ Compile and link a GLSL ES 300 fragment shader under shader slot+ -- @slot@ (@>= 1@), returning whether compilation and linking succeeded.+ , whUploadUniforms :: Ptr Word8 -> Int -> IO ()+ -- ^ Copy the frame's std140 shader uniform bytes to the host before 'whDraw'.+ , whAcquireTarget :: Int -> Int -> Ptr Int32 -> IO Int+ -- ^ Acquire a 64px-bucketed pooled RGBA8 offscreen WebGL2 framebuffer,+ -- writing its physical @(capW, capH)@ into the 2-int buffer and returning+ -- its non-negative slot index (or -1 on failure).+ , whReleaseTarget :: Int -> IO ()+ -- ^ Return a pooled offscreen target slot to the free pool.+ , whBindTarget :: Int -> Bool -> Double -> Double -> IO ()+ -- ^ Bind pooled target @slot >= 0@, or the default canvas backbuffer when+ -- @slot < 0@, optionally clearing to transparent black and setting logical+ -- vertex origin @(ox, oy)@.+ , whCompositeEffect :: Int -> Int -> Bool -> Ptr Float -> Ptr Int32 -> Ptr Word8 -> Int -> IO ()+ -- ^ Composite pooled texture @srcSlot@ through shader @shaderSlot@ onto the+ -- bound target. @blendCopy@ disables blending for intermediate passes;+ -- @rectUvPtr@ holds 8 floats @(dx, dy, dw, dh, u0, v0, u1, v1)@;+ -- @scissorPtr@ holds 5 ints @(hasScissor, sx, sy, sw, sh)@; @uPtr/uLen@+ -- holds the pass's patched std140 uniform block.+ , whSetCursor :: Ptr Word8 -> Int -> IO ()+ -- ^ The canvas's CSS cursor, @none@ to hide it.+ , whTextInput :: Int -> Double -> Double -> Double -> Double -> IO ()+ -- ^ Start or move text input for a purpose (0 text, 1 password, 2+ -- number) over a rect in CSS pixels, so the input method's window sits+ -- at the caret; a negative purpose stops it.+ , whClipboardRead :: Ptr Word8 -> Int -> IO Int+ -- ^ Copy up to @n@ bytes of the clipboard text the page last saw into+ -- the buffer, and answer its full length, or -1 when it has seen none.+ , whClipboardWrite :: Ptr Word8 -> Int -> IO ()+ , whSetTitle :: Ptr Word8 -> Int -> IO ()+ , whRendererInfo :: Ptr Word8 -> Int -> IO Int+ -- ^ Copy up to @n@ bytes of the WebGL renderer's description into the+ -- buffer, and answer its full length.+ , whFindFonts :: IO Int+ -- ^ Ask the browser for the installed font families (the Local Font+ -- Access API, which asks the user). Answers the byte length of their+ -- names, one a line, for 'whTakeFontList'; -1 when the browser has no+ -- such API, -2 when the user or the page's policy declined.+ , whTakeFontList :: Ptr Word8 -> IO ()+ -- ^ Copy the names 'whFindFonts' found into the buffer.+ , whLoadFont :: Int -> Ptr Word8 -> Int -> IO Int+ -- ^ Load a font file's bytes: an installed family's regular face (kind+ -- 0), a URL (kind 1), or a family by name (kind 2: installed when the user+ -- has allowed it, else from the font service), named in UTF-8. Answers+ -- their length for 'whTakeFontBytes', or -1 when it could not be loaded.+ , whTakeFontBytes :: Ptr Word8 -> IO ()+ -- ^ Copy the bytes 'whLoadFont' loaded into the buffer.+ , whStartFontDiscovery :: Int -> IO ()+ -- ^ Start finding font families, once: the installed ones (at once when+ -- the user has allowed it; while the browser has not asked yet, at the+ -- next press on the page) and a font service's catalogue (0 none, 1+ -- Fontsource). Each arrival bumps 'whFontsVersion' and wakes the session.+ , whFontsVersion :: IO Int+ -- ^ How many times the known families changed.+ , whFontFamilies :: Ptr Word8 -> Int -> IO Int+ -- ^ Copy up to @n@ bytes of the known families (installed first, one a+ -- line) into the buffer, and answer the full length.+ , whPickFiles :: Int -> Bool -> Ptr Word8 -> Int -> IO Int+ -- ^ Show the browser's file chooser: files (mode 0) or a folder's files+ -- (mode 1), several or one, with the filters as UTF-8 lines of a name, a+ -- tab and a semicolon-separated extension list. Answers the byte length+ -- of the files it read, for 'whTakePicked': each a 32-bit little-endian+ -- name length, the name, a 32-bit length and the bytes. -1 when the user+ -- cancelled, -2 when it failed.+ , whSaveFile :: Ptr Word8 -> Int -> Ptr Word8 -> Int -> Ptr Word8 -> Int -> IO Int+ -- ^ Save bytes as a file: the suggested name, the filters (as for+ -- 'whPickFiles'), then the bytes. Where the browser has a save dialog it+ -- shows it, else it downloads the file under the suggested name. Answers+ -- the byte length of the name saved under, for 'whTakePicked'; -1 when+ -- the user cancelled, -2 when it failed.+ , whTakePicked :: Ptr Word8 -> IO ()+ -- ^ Copy what 'whPickFiles' or 'whSaveFile' answered into the buffer.+ }++-- | Bytes in one event record: kind, three integer fields and the+-- modifiers as 32-bit integers, then three 32-bit floats.+-- "NanoUI.SdlWeb.Internal.Input" reads them.+eventRecordSize :: Int+eventRecordSize = 32++-- | Bytes in one draw command record, twelve 32-bit integers: texture slot+-- (-1 for none), first index, index count, whether to scissor, the scissor+-- rect in device pixels from the top left (x, y, width, height), shader slot+-- (0 for standard geometry), uniform byte offset, uniform byte length, and a+-- reserved word.+commandRecordSize :: Int+commandRecordSize = 48++-- | The texture slot of the image atlas. Slots 0 to 3 are the glyph pages.+imageAtlasSlot :: Int+imageAtlasSlot = 4++-- | What 'whQueryCanvas' reports.+data CanvasInfo = CanvasInfo+ { ciWidth :: !Float+ , ciHeight :: !Float+ , ciPixelRatio :: !Float+ , ciFocused :: !Bool+ , ciScheme :: !Int+ }+ deriving (Eq, Show)++-- | Query the canvas's logical size, device pixel ratio, focus state, and+-- color scheme from the browser host.+queryCanvas :: WebHost -> IO CanvasInfo+queryCanvas host = allocaArray 5 $ \p -> do+ whQueryCanvas host p+ peekArray 5 p >>= \case+ [w, h, ratio, focused, scheme] -> pure (CanvasInfo w h (if ratio > 0 then ratio else 1) (focused /= 0) (round scheme))+ _ -> pure (CanvasInfo 0 0 1 False 0)++-- | Pass text to a host callback as UTF-8 bytes and their byte length.+withUtf8 :: Text -> (Ptr Word8 -> Int -> IO a) -> IO a+withUtf8 t k = unsafeUseAsCStringLen (TE.encodeUtf8 t) $ \(p, n) -> k (castPtr p) n++-- | Read a UTF-8 string from a two-call host getter (first call queries the+-- byte length; a negative result means unavailable).+readHostText :: (Ptr Word8 -> Int -> IO Int) -> IO (Maybe Text)+readHostText fetch = do+ len <- fetch nullPtr 0+ if len < 0+ then pure Nothing+ else if len == 0+ then pure (Just "")+ else allocaBytes len $ \buf -> do+ n <- fetch buf len+ if n < 0+ then pure Nothing+ else Just . TE.decodeUtf8Lenient <$> BS.packCStringLen (castPtr buf, min n len)++-- | Whether 'browserHost' reaches a browser: a @wasm32@ build.+browserAvailable :: Bool++-- | The page's own host, @globalThis.nanoUiSdlWeb@ from+-- @web/nano-ui-sdl-web.js@.+browserHost :: IO WebHost++#if defined(wasm32_HOST_ARCH)+browserAvailable = True++browserHost = do+ jsAttach+ pure+ WebHost+ { whQueryCanvas = jsQueryCanvas+ , whTakeEvents = jsTakeEvents+ , whWaitEvents = \ms -> void (evaluate =<< jsWaitEvents ms)+ , whWake = jsWake+ , whResizeBacking = jsResizeBacking+ , whUploadTexture = jsUploadTexture+ , whBeginFrame = \clear r g b a scale w h -> jsBeginFrame (fromEnum clear) r g b a scale w h+ , whDraw = jsDraw+ , whRegisterShader = \slot p n -> (/= 0) <$> jsRegisterShader slot p n+ , whUploadUniforms = jsUploadUniforms+ , whAcquireTarget = jsAcquireTarget+ , whReleaseTarget = jsReleaseTarget+ , whBindTarget = \slot clear ox oy -> jsBindTarget slot (fromEnum clear) ox oy+ , whCompositeEffect = \srcSlot shSlot blendCopy rPtr sPtr uPtr uLen ->+ jsCompositeEffect srcSlot shSlot (fromEnum blendCopy) rPtr sPtr uPtr uLen+ , whSetCursor = jsSetCursor+ , whTextInput = jsTextInput+ , whClipboardRead = jsClipboardRead+ , whClipboardWrite = jsClipboardWrite+ , whSetTitle = jsSetTitle+ , whRendererInfo = jsRendererInfo+ , whFindFonts = evaluate =<< jsFindFonts+ , whTakeFontList = jsTakeFontList+ , whLoadFont = \kind p n -> evaluate =<< jsLoadFont kind p n+ , whTakeFontBytes = jsTakeFontBytes+ , whStartFontDiscovery = jsStartFontDiscovery+ , whFontsVersion = jsFontsVersion+ , whFontFamilies = jsFontFamilies+ , whPickFiles = \mode many p n -> evaluate =<< jsPickFiles mode (fromEnum many) p n+ , whSaveFile = \np nn fp fn dp dn -> evaluate =<< jsSaveFile np nn fp fn dp dn+ , whTakePicked = jsTakePicked+ }++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.attach(__exports.memory)"+ jsAttach :: IO ()++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.queryCanvas($1)"+ jsQueryCanvas :: Ptr Float -> IO ()++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.takeEvents($1, $2)"+ jsTakeEvents :: Ptr Word8 -> Int -> IO Int++-- A safe import runs as an async function: the calling Haskell thread waits+-- for its promise, and the browser's event loop runs meanwhile, which is+-- what delivers the events.+foreign import javascript safe "await globalThis.nanoUiSdlWeb.waitEvents($1); return 0;"+ jsWaitEvents :: Int -> IO Int++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.wake()"+ jsWake :: IO ()++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.resizeBacking($1, $2)"+ jsResizeBacking :: Int -> Int -> IO ()++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.uploadTexture($1, $2, $3, $4, $5, $6, $7, $8, $9)"+ jsUploadTexture :: Int -> Int -> Int -> Ptr Word8 -> Int -> Int -> Int -> Int -> Int -> IO ()++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.beginFrame($1, $2, $3, $4, $5, $6, $7, $8)"+ jsBeginFrame :: Int -> Double -> Double -> Double -> Double -> Double -> Int -> Int -> IO ()++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.draw($1, $2, $3, $4, $5, $6)"+ jsDraw :: Ptr Word8 -> Int -> Ptr Word8 -> Int -> Ptr Word8 -> Int -> IO ()++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.registerShader($1, $2, $3)"+ jsRegisterShader :: Int -> Ptr Word8 -> Int -> IO Int++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.uploadUniforms($1, $2)"+ jsUploadUniforms :: Ptr Word8 -> Int -> IO ()++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.acquireTarget($1, $2, $3)"+ jsAcquireTarget :: Int -> Int -> Ptr Int32 -> IO Int++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.releaseTarget($1)"+ jsReleaseTarget :: Int -> IO ()++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.bindTarget($1, $2, $3, $4)"+ jsBindTarget :: Int -> Int -> Double -> Double -> IO ()++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.compositeEffect($1, $2, $3, $4, $5, $6, $7)"+ jsCompositeEffect :: Int -> Int -> Int -> Ptr Float -> Ptr Int32 -> Ptr Word8 -> Int -> IO ()++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.setCursor($1, $2)"+ jsSetCursor :: Ptr Word8 -> Int -> IO ()++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.textInput($1, $2, $3, $4, $5)"+ jsTextInput :: Int -> Double -> Double -> Double -> Double -> IO ()++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.clipboardRead($1, $2)"+ jsClipboardRead :: Ptr Word8 -> Int -> IO Int++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.clipboardWrite($1, $2)"+ jsClipboardWrite :: Ptr Word8 -> Int -> IO ()++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.setTitle($1, $2)"+ jsSetTitle :: Ptr Word8 -> Int -> IO ()++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.rendererInfo($1, $2)"+ jsRendererInfo :: Ptr Word8 -> Int -> IO Int++foreign import javascript safe "return await globalThis.nanoUiSdlWeb.findFonts();"+ jsFindFonts :: IO Int++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.takeFontList($1)"+ jsTakeFontList :: Ptr Word8 -> IO ()++foreign import javascript safe "return await globalThis.nanoUiSdlWeb.loadFont($1, $2, $3);"+ jsLoadFont :: Int -> Ptr Word8 -> Int -> IO Int++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.takeFontBytes($1)"+ jsTakeFontBytes :: Ptr Word8 -> IO ()++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.startFontDiscovery($1)"+ jsStartFontDiscovery :: Int -> IO ()++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.fontsVersionNow()"+ jsFontsVersion :: IO Int++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.fontFamilies($1, $2)"+ jsFontFamilies :: Ptr Word8 -> Int -> IO Int++foreign import javascript safe "return await globalThis.nanoUiSdlWeb.pickFiles($1, $2, $3, $4);"+ jsPickFiles :: Int -> Int -> Ptr Word8 -> Int -> IO Int++foreign import javascript safe "return await globalThis.nanoUiSdlWeb.saveFile($1, $2, $3, $4, $5, $6);"+ jsSaveFile :: Ptr Word8 -> Int -> Ptr Word8 -> Int -> Ptr Word8 -> Int -> IO Int++foreign import javascript unsafe "globalThis.nanoUiSdlWeb.takePicked($1)"+ jsTakePicked :: Ptr Word8 -> IO ()+#else+browserAvailable = False++browserHost = ioError (userError "nano-ui-sdl-web runs in a browser: build the program with wasm32-wasi-ghc")+#endif
+ lib/NanoUI/SdlWeb/Internal/Input.hs view
@@ -0,0 +1,203 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | Browser events, as @web/nano-ui-sdl-web.js@ queues them, decoded and+-- folded into 'Input'.+--+-- Each event is an 'eventRecordSize'-byte record: kind, three integer+-- fields (@a@, @b@, @c@) and the modifier bits as 32-bit integers, then+-- three 32-bit floats (@x@, @y@, @z@). The kinds and their fields:+--+-- * 1 resize: the canvas's size or pixel ratio changed (read at sync)+-- * 2 motion: @x@, @y@ in CSS pixels+-- * 3 button: @a@ the DOM button number, @b@ 1 down or 0 up+-- * 4 leave: the pointer left the canvas+-- * 5 scroll: @x@, @y@ in wheel notches, positive right and down+-- * 6 key: @a@ the key ('decodeKey'), @b@ 1 down or 0 up+-- * 7 character typed: @a@ the code point+-- * 8 composition: @a@ characters to follow as kind 9, @b@ the caret,+-- @c@ the selection's length+-- * 9 composition character: @a@ the code point+-- * 10 focus lost+-- * 11 redraw: the drawing buffer was cleared or the GL context restored+--+-- The modifier bits are 1 Shift, 2 Ctrl, 4 Alt, 8 Meta and 16 Num Lock.+module NanoUI.SdlWeb.Internal.Input+ ( WebEvent (..)+ , decodeEvents+ , PartialComposition+ , decodeEventBatch+ , finishComposition+ , decodeKey+ , applyWebEvent+ , isButtonEdge+ , cssCursor+ ) where++import Data.Bits ((.&.))+import Data.Char (chr, isControl, isUpper, toLower)+import Data.Int (Int32)+import Data.Text (Text)+import qualified Data.Text as T+import Data.Word (Word8)+import Foreign.Ptr (Ptr)+import Foreign.Storable (peekByteOff)+import NanoUI (V2 (..), v2Add)+import NanoUI.Backend+ ( Input (..)+ , Key (..)+ , Modifiers+ , UiCursorKind (..)+ , applyComposition+ , applyKey+ , applyMouseButton+ , applyPointerLeave+ , keypadKey+ , modifiersFromBits+ , mouseButtonNumber+ , releaseAllKeys+ )+import NanoUI.SdlWeb.Internal.Host (eventRecordSize)++-- | A decoded browser event. Positions are in layout units.+data WebEvent+ = EvResize+ | EvMotion !Float !Float !Modifiers+ | EvButton !Int !Bool !Modifiers+ | EvLeave+ | EvScroll !Float !Float+ | EvKey !(Maybe Key) !Bool !Modifiers+ -- ^ 'Nothing' for a modifier key, which changes only the modifiers.+ | EvChar !Char+ | EvComposition !Text !Int !Int+ | EvFocusLost+ | EvRedraw+ deriving (Eq, Show)++-- | Decode @n@ records from a buffer. CSS pixels become layout units at the+-- zoom: the UI scale on top of the device pixel ratio. A composition whose+-- characters run past the buffer ends with those it has; a caller reading+-- the queue in batches uses 'decodeEventBatch' to carry it on.+decodeEvents :: Float -> Ptr Word8 -> Int -> IO [WebEvent]+decodeEvents zoom buf n = do+ (evs, partial) <- decodeEventBatch zoom Nothing buf n+ pure (evs ++ maybe [] (pure . finishComposition) partial)++-- | A composition (kind 8) whose characters (kind 9) run past the end of a+-- batch: how many are still to come, those read so far, newest first, and+-- the caret and selection length.+data PartialComposition = PartialComposition !Int ![Char] !Int !Int+ deriving (Eq, Show)++-- | The composition event for what has arrived of one.+finishComposition :: PartialComposition -> WebEvent+finishComposition (PartialComposition _ chars caret len) = EvComposition (T.pack (reverse chars)) caret len++-- | 'decodeEvents' for one batch of a queue read in batches: it continues a+-- composition the batch before left unfinished, and answers one this batch+-- leaves unfinished, for the next.+decodeEventBatch :: Float -> Maybe PartialComposition -> Ptr Word8 -> Int -> IO ([WebEvent], Maybe PartialComposition)+decodeEventBatch zoom carried buf n = case carried of+ Nothing -> go 0+ Just partial -> composing partial 0+ where+ at i k = fromIntegral <$> (peekByteOff buf (i * eventRecordSize + k * 4) :: IO Int32)+ -- Take a composition's characters from record @i@ on, as far as they+ -- go in this batch. A record of another kind ends it early.+ composing p@(PartialComposition left chars caret len) i+ | left <= 0 = first (finishComposition p :) <$> go i+ | i >= n = pure ([], Just p)+ | otherwise = do+ kind <- at i 0+ if kind /= (9 :: Int)+ then first (finishComposition p :) <$> go i+ else do+ ch <- chr . clampChar <$> at i 1+ composing (PartialComposition (left - 1) (ch : chars) caret len) (i + 1)+ first f (a, b) = (f a, b)+ go i+ | i >= n = pure ([], Nothing)+ | otherwise = do+ let float k = peekByteOff buf (i * eventRecordSize + k * 4) :: IO Float+ next ev = first (ev :) <$> go (i + 1)+ kind <- at i 0+ a <- at i 1+ b <- at i 2+ c <- at i 3+ mods <- (\m -> modifiersFromBits (m :: Int) 1 2 4 8) <$> at i 4+ numLock <- (\m -> m .&. (16 :: Int) /= 0) <$> at i 4+ x <- float 5+ y <- float 6+ case kind :: Int of+ 1 -> next EvResize+ 2 -> next (EvMotion (x / zoom) (y / zoom) mods)+ 3 -> next (EvButton a (b /= 0) mods)+ 4 -> next EvLeave+ 5 -> next (EvScroll x y)+ 6 -> next (EvKey (decodeKey numLock a) (b /= 0) mods)+ 7+ | typed a -> next (EvChar (chr a))+ | otherwise -> go (i + 1)+ -- The composition's characters follow as kind 9 records.+ 8 -> composing (PartialComposition (max 0 a) [] b c) (i + 1)+ 10 -> next EvFocusLost+ 11 -> next EvRedraw+ _ -> go (i + 1)+ clampChar v = if v < 0 || v > 0x10FFFF then 0xFFFD else v+ -- Control characters type nothing: a chord's key event reports it.+ typed v = v > 0 && v <= 0x10FFFF && not (isControl (chr v))++-- | The key a key record names. A positive code is a key that types that+-- character (lowercase); a negative one a named key: -1 to -21 in the order+-- of 'Key' from 'KeyBackspace' to 'KeyMenu', -(100 + n) for F@n@, and+-- -(300 + c) for the keypad key that types @c@ under Num Lock. Zero is a+-- modifier key.+decodeKey :: Bool -> Int -> Maybe Key+decodeKey numLock code+ | code > 0 = Just (KeyChar (lowerChar (chr (min 0x10FFFF code))))+ | code <= -300 = keypadKey numLock (chr (negate code - 300))+ | code <= -101 && code >= -124 = Just (KeyF (negate code - 100))+ | code < 0 && code >= -21 = Just (named !! (negate code - 1))+ | otherwise = Nothing+ where+ lowerChar ch = if isUpper ch then toLower ch else ch+ named =+ [ KeyBackspace, KeyDelete, KeyEnter, KeyEscape, KeyTab+ , KeyLeft, KeyRight, KeyUp, KeyDown, KeyHome, KeyEnd, KeyPageUp, KeyPageDown+ , KeyInsert, KeySpace, KeyPrintScreen, KeyPause, KeyCapsLock, KeyNumLock+ , KeyScrollLock, KeyMenu+ ]++-- | Fold a decoded event into the frame's input. Resize events change+-- nothing here: the sync reads the canvas.+applyWebEvent :: Input -> WebEvent -> Input+applyWebEvent inp = \case+ EvResize -> inp+ EvMotion x y mods -> inp {inputMousePos = V2 x y, inputModifiers = mods}+ -- DOM buttons are numbered from 0 in 'mouseButtonNumber' order: left,+ -- middle, right, back, forward.+ EvButton btn down mods -> (applyMouseButton (mouseButtonNumber (btn + 1)) down inp) {inputModifiers = mods}+ -- A drag keeps its pointer ('applyPointerLeave').+ EvLeave -> applyPointerLeave inp+ EvScroll dx dy -> inp {inputScroll = v2Add (inputScroll inp) (V2 dx dy)}+ -- 'applyKey' tells auto-repeats from presses because the key is held.+ EvKey key down mods -> (maybe inp (\k -> applyKey k down inp) key) {inputModifiers = mods}+ EvChar ch -> inp {inputChars = T.snoc (inputChars inp) ch}+ EvComposition txt caret len -> applyComposition txt caret len inp+ EvFocusLost -> releaseAllKeys inp+ EvRedraw -> inp {inputWindowRedraw = True}++-- | Presses and releases end a frame's batch of events, so each frame sees+-- at most one edge per button.+isButtonEdge :: WebEvent -> Bool+isButtonEdge = \case EvButton {} -> True; _ -> False++-- | The CSS cursor for a cursor kind. Browsers have every kind, so none+-- falls back: each constructor's name after @UiCursor@ in kebab case is its+-- CSS name ('UiCursorNwseResize' is @nwse-resize@), and 'UiCursorHidden'+-- is @none@.+cssCursor :: UiCursorKind -> Text+cssCursor UiCursorHidden = "none"+cssCursor kind = T.pack (kebab (drop (length ("UiCursor" :: String)) (show kind)))+ where+ kebab [] = []+ kebab (c : cs) = toLower c : concatMap (\ch -> if isUpper ch then ['-', toLower ch] else [ch]) cs
+ lib/NanoUI/SdlWeb/Internal/Render.hs view
@@ -0,0 +1,339 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | A frame's draw data as WebGL draw commands: the texture uploads it+-- needs, then each command clipped to its rect and the damage, as+-- nano-ui-sdl's @NanoUI.Sdl.Internal.Render@ submits them to SDL.+module NanoUI.SdlWeb.Internal.Render+ ( Renderer+ , newRenderer+ , freeRenderer+ , forgetTextures+ , syncTextures+ , renderDrawData+ , DrawCommand (..)+ , drawCommands'+ , snapDamage+ ) where++import Control.Monad (forM_, unless, when)+import Data.ByteString.Unsafe (unsafeUseAsCStringLen)+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.Int (Int32)+import qualified Data.Map.Strict as Map+import Data.Primitive.ByteArray (ByteArray, copyByteArrayToAddr, sizeofByteArray)+import Data.Primitive.SmallArray (indexSmallArray, sizeofSmallArray, smallArrayFromListN)+import qualified Data.Text.Encoding as TE+import qualified Data.Vector.Unboxed as U+import Data.Word (Word64, Word8)+import Foreign.ForeignPtr (withForeignPtr)+import Foreign.Marshal.Alloc (allocaBytes, free, mallocBytes, reallocBytes)+import Foreign.Marshal.Array (allocaArray, pokeArray)+import Foreign.Ptr (Ptr, castPtr, nullPtr)+import Foreign.Storable (peekElemOff, pokeElemOff)+import NanoUI (Rect (..), colorA, colorB, colorG, colorR)+import NanoUI.Backend+ ( AtlasUpload (..)+ , Context+ , Damage (..)+ , DrawCmd (..)+ , DrawData (..)+ , EffectDriver (..)+ , EffectPassDraw (..)+ , ShaderCall (..)+ , ShaderProgram (..)+ , atlasChanges+ , atlasTextureId+ , clipPixelEdges+ , cmdEffectiveClip+ , execEffectSpans+ , snapDamage+ , textureGlyphPage+ , withEffectUniforms+ )+import NanoUI.SdlWeb.Internal.Font (GlyphAtlas, glyphAtlasSize, glyphPageUploads)+import NanoUI.SdlWeb.Internal.Host (WebHost (..), commandRecordSize, imageAtlasSlot)++-- | The session's draw state: the command buffer, reused across frames, the+-- image atlas generation on the GPU, and the registered shader cache.+data Renderer = Renderer+ { rCommands :: !(IORef (Ptr Word8, Int))+ -- ^ The buffer and its capacity in commands.+ , rImageGeneration :: !(IORef Int)+ , rShaders :: !(IORef (Map.Map Word64 Int, Int))+ -- ^ Registered shader slots by program hash (0 marks a failed compile),+ -- paired with the next 1-based slot ID.+ }++-- | Allocate an empty browser renderer state with no command buffer or+-- uploaded textures yet.+newRenderer :: IO Renderer+newRenderer = Renderer <$> newIORef (nullPtr, 0) <*> newIORef 0 <*> newIORef (Map.empty, 1)++-- | Free the renderer's native command buffer.+freeRenderer :: Renderer -> IO ()+freeRenderer r = do+ (buf, _) <- readIORef (rCommands r)+ free buf+ writeIORef (rCommands r) (nullPtr, 0)++-- | Upload the image atlas in full with the next 'syncTextures' and drop+-- cached shader slots after the GPU lost its WebGL context. The glyph pages+-- are marked on the atlas ('NanoUI.SdlWeb.Internal.Font.markGlyphPagesDirty').+forgetTextures :: Renderer -> IO ()+forgetTextures r = do+ writeIORef (rImageGeneration r) 0+ writeIORef (rShaders r) (Map.empty, 1)++-- | Upload what changed in the glyph pages and the image atlas since the+-- last call, before a frame that may draw from them.+syncTextures :: WebHost -> Renderer -> GlyphAtlas -> Context -> IO ()+syncTextures host r glyphs ctx = do+ let page = round glyphAtlasSize+ uploads <- glyphPageUploads glyphs+ forM_ uploads $ \(slot, pixels, (x, y, w, h)) ->+ whUploadTexture host slot page page pixels page x y w h+ gen <- readIORef (rImageGeneration r)+ atlasChanges ctx gen >>= \case+ Nothing -> pure ()+ Just (w, h, pixels, gen', upload) -> do+ let rects = case upload of+ AtlasWhole -> [(0, 0, w, h)]+ -- A texture never made, or lost, takes the whole atlas.+ AtlasRegions rs -> if gen == 0 then [(0, 0, w, h)] else rs+ withForeignPtr pixels $ \p ->+ forM_ rects $ \(x, y, rw, rh) ->+ whUploadTexture host imageAtlasSlot w h p w x y rw rh+ writeIORef (rImageGeneration r) gen'++-- | One WebGL draw: texture slot (-1 for none), index range, optional scissor+-- in device pixels from the top left, and shader call index (0 for standard+-- geometry; 1-based index into 'drawShaderCalls' otherwise).+data DrawCommand = DrawCommand+ { dcSlot :: !Int+ , dcFirst :: !Int+ , dcCount :: !Int+ , dcScissor :: !(Maybe (Int, Int, Int, Int))+ , dcShaderCall :: !Int+ }+ deriving (Eq, Show)++-- | The draws for a frame's commands over its damage, at a scale, into a+-- drawing buffer of a pixel size. Each command is clipped to its own rect+-- and to the damage, in the device pixels 'clipPixelEdges' gives, as+-- nano-ui-sdl clips; one with nothing left is dropped. A command that+-- continues the last one's indices with the same texture, shader and scissor+-- joins it, which turns most of a frame into a few draws.+drawCommands' :: Float -> (Int, Int) -> Damage -> DrawData -> [DrawCommand]+drawCommands' scale (pw, ph) damage dd =+ drawCommandsSlice scale (pw, ph) 0 0 mDamage (drawCommands dd) 0 (U.length (drawCommands dd))+ where+ mDamage = case damage of+ DamageFull -> Nothing+ DamageClip r -> Just r++drawCommandsSlice ::+ Float ->+ (Int, Int) ->+ Float ->+ Float ->+ Maybe Rect ->+ U.Vector DrawCmd ->+ Int ->+ Int ->+ [DrawCommand]+drawCommandsSlice scale (pw, ph) ox oy mDamage rawCmds lo hi = reverse (go lo [])+ where+ go !i acc+ | i >= hi = acc+ | otherwise = go (i + 1) (step acc (U.unsafeIndex rawCmds i))+ step acc cmd+ | count < 3 = acc+ | otherwise = case cmdEffectiveClip mDamage cmd of+ Nothing -> acc+ Just mClip ->+ let shifted = if ox == 0 && oy == 0 then mClip else fmap (\(Rect x y w h) -> Rect (x - ox) (y - oy) w h) mClip+ scissor = fmap toPixels shifted+ in case scissor of+ Just (_, _, sw, sh) | sw <= 0 || sh <= 0 -> acc+ _ ->+ push+ (DrawCommand (slotOf (cmdTextureId cmd)) (fromIntegral (cmdIndexOffset cmd)) count scissor (fromIntegral (cmdShader cmd)))+ acc+ where+ count = fromIntegral (cmdIndexCount cmd)+ push c (prev : rest)+ | dcShaderCall prev == 0+ && dcShaderCall c == 0+ && dcSlot prev == dcSlot c+ && dcScissor prev == dcScissor c+ && dcFirst prev + dcCount prev == dcFirst c =+ prev {dcCount = dcCount prev + dcCount c} : rest+ push c acc = c : acc+ toPixels = toPixelScissor scale (pw, ph)+ slotOf tex+ | page >= 0 = page+ | tex == atlasTextureId = imageAtlasSlot+ | otherwise = -1+ where+ page = textureGlyphPage tex++-- | Convert a logical clip rectangle into a clamped device-pixel scissor+-- @(x, y, width, height)@ within a @(pw, ph)@ target.+toPixelScissor :: Float -> (Int, Int) -> Rect -> (Int, Int, Int, Int)+toPixelScissor scale (pw, ph) r =+ let (x0, y0, x1, y1) = clipPixelEdges scale r+ cx0 = max 0 x0+ cy0 = max 0 y0+ in (cx0, cy0, min pw x1 - cx0, min ph y1 - cy0)++-- | Look up or lazily register a GLSL ES 300 shader program on the host,+-- returning its 1-based slot (or 0 if unavailable or compilation failed).+ensureShaderSlot :: WebHost -> Renderer -> ShaderCall -> IO Int+ensureShaderSlot host r sc = do+ (cache, nextSlot) <- readIORef (rShaders r)+ case Map.lookup (scHash sc) cache of+ Just slot -> pure slot+ Nothing -> case spGlslEs300 (scProgram sc) of+ Nothing -> do+ writeIORef (rShaders r) (Map.insert (scHash sc) 0 cache, nextSlot)+ pure 0+ Just src -> do+ let bytes = TE.encodeUtf8 src+ ok <- unsafeUseAsCStringLen bytes $ \(p, len) ->+ whRegisterShader host nextSlot (castPtr p) len+ let slot = if ok then nextSlot else 0+ next' = if ok then nextSlot + 1 else nextSlot+ writeIORef (rShaders r) (Map.insert (scHash sc) slot cache, next')+ pure slot++-- | Draw a frame over its damage. A full frame clears to the draw data's+-- colour first; a partial one paints over the frame the drawing buffer+-- kept, as the draw list starts a clip frame with its own backdrop.+renderDrawData :: WebHost -> Renderer -> Float -> (Int, Int) -> Damage -> DrawData -> IO ()+renderDrawData host r scale (pw, ph) damage dd = do+ let full = case damage of DamageFull -> True; DamageClip _ -> False+ mDamage = case damage of DamageFull -> Nothing; DamageClip rect -> Just rect+ clear = drawClear dd+ unit v = realToFrac v :: Double+ calls = drawShaderCalls dd+ uBytes = drawUniformBytes dd+ uSize = sizeofByteArray uBytes+ spans = drawEffectSpans dd+ uploadUniforms =+ when (sizeofSmallArray calls > 0 && uSize > 0) $+ allocaBytes uSize $ \uPtr -> do+ copyByteArrayToAddr uPtr uBytes 0 uSize+ whUploadUniforms host uPtr uSize+ whBeginFrame host full (unit (colorR clear) / 255) (unit (colorG clear) / 255) (unit (colorB clear) / 255) (unit (colorA clear) / 255) (realToFrac scale) pw ph+ if sizeofSmallArray spans == 0+ then do+ let cmds = drawCommands' scale (pw, ph) damage dd+ unless (null cmds) $ do+ uploadUniforms+ withForeignPtr (drawVertices dd) $ \vp ->+ withForeignPtr (drawIndices dd) $ \ip ->+ submitCommands host r dd vp ip cmds+ else do+ uploadUniforms+ let rawCmds = drawCommands dd+ withForeignPtr (drawVertices dd) $ \vp ->+ withForeignPtr (drawIndices dd) $ \ip -> do+ let drv =+ EffectDriver+ { edScale = scale+ , edFlipY = True+ , edPreparePasses = \passes -> do+ let !n = sizeofSmallArray passes+ slots <- mapM (ensureShaderSlot host r . indexSmallArray passes) [0 .. n - 1]+ pure (if any (<= 0) slots then Nothing else Just (smallArrayFromListN n slots))+ , edAcquireTarget = acquireWebTarget host+ , edReleaseTarget = whReleaseTarget host+ , edBindTarget = \slot clr ox oy ->+ True <$ whBindTarget host slot clr (realToFrac ox) (realToFrac oy)+ , edFlush = pure ()+ , edEmitPlain = \_ cw ch ox oy curDmg from to ->+ submitCommands host r dd vp ip (drawCommandsSlice scale (cw, ch) ox oy curDmg rawCmds from to)+ , edAfterSpanContent = \_ -> pure ()+ , edCompositePass = \shSlot sc pd dstW dstH -> do+ let mScissor = fmap (toPixelScissor scale (dstW, dstH)) (epdClip pd)+ nonEmpty = case mScissor of+ Just (_, _, sw, sh) -> sw > 0 && sh > 0+ Nothing -> True+ when nonEmpty $+ compositeWebPass host shSlot mScissor sc uBytes pd+ }+ execEffectSpans drv spans 0 (-1) (pw, ph) 0 0 mDamage 0 (U.length rawCmds)++submitCommands :: WebHost -> Renderer -> DrawData -> Ptr Word8 -> Ptr Word8 -> [DrawCommand] -> IO ()+submitCommands host r dd vp ip cmds =+ unless (null cmds) $ do+ let n = length cmds+ calls = drawShaderCalls dd+ buf <- commandBuffer r n+ let ints = castPtr buf :: Ptr Int32+ resolveShader callIdx+ | callIdx <= 0 || callIdx > sizeofSmallArray calls = pure (0, 0, 0)+ | otherwise = do+ let sc = indexSmallArray calls (callIdx - 1)+ shSlot <- ensureShaderSlot host r sc+ pure (shSlot, scUniformOffset sc, scUniformLength sc)+ forM_ (zip [0 ..] cmds) $ \(i, DrawCommand slot first count scissor callIdx) -> do+ (shSlot, uOff, uLen) <- resolveShader callIdx+ let put k v = pokeElemOff ints (i * (commandRecordSize `div` 4) + k) (fromIntegral v)+ (on, sx, sy, sw, sh) = maybe (0, 0, 0, 0, 0) (\(x, y, w, h) -> (1 :: Int, x, y, w, h)) scissor+ put 0 slot+ put 1 first+ put 2 count+ put 3 on+ put 4 sx+ put 5 sy+ put 6 sw+ put 7 sh+ put 8 shSlot+ put 9 uOff+ put 10 uLen+ put 11 (0 :: Int)+ whDraw host vp (drawVertexCount dd) ip (drawIndexCount dd) buf n++acquireWebTarget :: WebHost -> Int -> Int -> IO (Int, Int, Int)+acquireWebTarget host minW minH =+ allocaArray 2 $ \capsPtr -> do+ slot <- whAcquireTarget host minW minH capsPtr+ if slot < 0+ then pure (-1, 0, 0)+ else do+ cw <- fromIntegral <$> peekElemOff capsPtr 0+ ch <- fromIntegral <$> peekElemOff capsPtr 1+ pure (slot, cw, ch)++{-# NOINLINE compositeWebPass #-}+compositeWebPass ::+ WebHost ->+ Int ->+ Maybe (Int, Int, Int, Int) ->+ ShaderCall ->+ ByteArray ->+ EffectPassDraw ->+ IO ()+compositeWebPass host shSlot mScissor sc uniformBytes pd = do+ let (hasSc, sx, sy, sw, sh) = case mScissor of+ Nothing -> (0 :: Int32, 0, 0, 0, 0)+ Just (x, y, w, h) -> (1, fromIntegral x, fromIntegral y, fromIntegral w, fromIntegral h)+ allocaArray 8 $ \rvPtr ->+ allocaArray 5 $ \scPtr ->+ withEffectUniforms sc uniformBytes pd $ \uPtr uLen -> do+ pokeArray rvPtr [epdDstX pd, epdDstY pd, epdDstW pd, epdDstH pd, epdU0 pd, epdV0 pd, epdU1 pd, epdV1 pd]+ pokeArray scPtr [hasSc, sx, sy, sw, sh]+ whCompositeEffect host (epdSrcSlot pd) shSlot (epdIntermediate pd) rvPtr scPtr uPtr uLen++-- | The command buffer, grown to hold at least @n@ commands.+commandBuffer :: Renderer -> Int -> IO (Ptr Word8)+commandBuffer r n = do+ (buf, cap) <- readIORef (rCommands r)+ if n <= cap && buf /= nullPtr+ then pure buf+ else do+ let cap' = max 64 (max n (cap * 2))+ buf' <- if buf == nullPtr then mallocBytes (cap' * commandRecordSize) else reallocBytes buf (cap' * commandRecordSize)+ when (buf' == nullPtr) $ fail "nano-ui-sdl-web: out of memory for draw commands"+ buf' <$ writeIORef (rCommands r) (buf', cap')
+ lib/NanoUI/SdlWeb/Internal/Session.hs view
@@ -0,0 +1,559 @@+{-# LANGUAGE MultiWayIf #-}+{-# LANGUAGE TypeFamilies #-}+{-# OPTIONS_HADDOCK not-home #-}+-- The 'BackendSession' instance for the browser session is an orphan by+-- construction: the core owns the backend kind, and this package owns its+-- session.+{-# OPTIONS_GHC -Wno-orphans #-}++-- | The browser session: options, the event loop over a 'WebHost', display+-- sync, and frame presentation. The loop is "NanoUI.Runner"'s, as on the+-- desktop backends: its wait for events is a wait on a JavaScript promise,+-- which lets the browser run until an event or a wake arrives.+module NanoUI.SdlWeb.Internal.Session+ ( SdlWebOptions (..)+ , defaultSdlWebOptions+ , WebFont (..)+ , WebFontService (..)+ , runWebSession+ , WebFrame+ -- * From the view+ , setSdlWebUiFont+ , webFontFamilies+ , askSdlWebDebug+ , listWebFontFamilies+ ) where++import Control.Exception (bracket, finally)+import Control.Monad (forM_, unless, when)+import Data.ByteString (ByteString)+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import GHC.TypeLits (symbolSing)+import System.IO (hPutStrLn, stderr)+import Data.Maybe (isJust)+import Data.Text (Text)+import Foreign.Marshal.Alloc (allocaBytes)+import GHC.Clock (getMonotonicTime)+import NanoUI+ ( Appearance (..)+ , NanoUI+ , Rect (..)+ , ShaderCapabilities (..)+ , Size (..)+ , Theme+ , WindowSettings (..)+ , defaultWindowSettings+ )+import NanoUI.Backend+ ( Backend (..)+ , BackendSession+ , Damage (..)+ , DrawData (..)+ , Input (..)+ , InputPurpose (..)+ , TextInputArea (..)+ , UiCursorKind (..)+ , WindowHost (..)+ , WindowState (..)+ , closeWindowHost+ , cancelTasks+ , damageIsEmpty+ , defaultWindowHost+ , defaultWindowState+ , emptyInput+ , followSystemThemeIO+ , installWindowHost+ , markDirty+ , noWindowCapabilities+ , reportWindowState+ , setExplainLayout+ , setShaderCapabilities+ , setSystemAppearance+ , setWakeLoop+ , syncCursorKind+ , takeDamage+ , textInputArea+ , uiCursorKind+ , WindowCapabilities (..)+ , SBackend (..)+ , applyPointerLeave+ , askBackendSession+ , setBackendSession+ )+import NanoUI.Internal.Context (Context, retainedFrameStale, setDrawSnapScale, withFramePaint)+import NanoUI.Internal.Debug (CoreDebugSnapshot (..), noteDebugFrame, noteDebugSkip, refreshDebugSnapshot)+import NanoUI.Monad (askContext, liftIO)+import NanoUI.Runner (DebugSamplerRef, SessionDriver (..), newDebugSampler, pacingMsFor, runSessionLoop, shouldRedrawFrame)+import NanoUI.Backend (newPixelContext, withClipboard, withTheme)+import NanoUI.SdlWeb.Internal.Debug (SdlWebDebugSnapshot (..))+import NanoUI.SdlWeb.Internal.Font+import NanoUI.SdlWeb.Internal.Fonts (FontOrigin (..), findFontFamilies, knownFontFamilies, loadFontBytes, rendererName, searchCandidates)+import NanoUI.SdlWeb.Internal.Host+import NanoUI.SdlWeb.Internal.Input+import NanoUI.SdlWeb.Internal.Render+import NanoUI.Ttf.Internal.Font (beginTtfFrame, ttfFrameDropped)+import NanoUI.Ttf.Internal.Support (syncSdlFontCache)++-- | A font for the web runners. The browser has no font directories: a+-- font other than the bundled Inter is an installed family the browser hands+-- over (see 'listWebFontFamilies'), a file fetched by URL, or bytes the+-- program embeds. A font that cannot be loaded falls back to Inter, as a+-- missing font does on the desktop.+data WebFont+ = WebFontInter+ -- ^ The bundled Inter subset.+ | WebFontBytes !ByteString !String+ -- ^ A font file's bytes and a label for it.+ | WebFontInstalled !String+ -- ^ An installed family by name, through the Local Font Access API+ -- (Chromium-based browsers, after the user allows it). Its regular face,+ -- else the first the browser lists.+ | WebFontUrl !String+ -- ^ A TrueType or OpenType file at a URL. Another origin must allow the+ -- page to read it (CORS).+ | WebFontSearch ![String]+ -- ^ The first of these families that can be had, as+ -- @NanoUI.Backend.Sdl.FontSearch@ searches the desktop's: installed (once+ -- the user has let the browser list them), else from the font service+ -- ('webFontService'). Names compare ignoring case, spaces, @-@ and @_@;+ -- @sans-serif@, @serif@ and @monospace@ stand for common families. With+ -- none found, the bundled Inter.+ deriving (Eq, Show)++-- | Where families come from when they are not installed, or not allowed.+data WebFontService+ = Fontsource+ -- ^ Fontsource (fontsource.org): about 2,100 open-licence families,+ -- Google Fonts' among them, as TrueType from its CDN (cdn.jsdelivr.net).+ -- The page fetches the catalogue when 'webFontFamilies' is first asked+ -- for, and each family's regular face when it is used.+ deriving (Eq, Show)++-- | Options for the web runners. The canvas's size is the page's, so the+-- window settings give only the title ('wsTitle'), which becomes the+-- document's.+data SdlWebOptions = SdlWebOptions+ { webWindowSettings :: !WindowSettings+ , webTheme :: !(Maybe Theme)+ -- ^ Initial UI theme override (default: 'Nothing').+ , webThemeFor :: !(Maybe (Maybe Appearance -> Theme))+ -- ^ Pick the theme from the colour scheme the page prefers+ -- (@prefers-color-scheme@), and follow it when it changes (default:+ -- 'Nothing').+ , webFont :: !WebFont+ -- ^ UI font (default: 'WebFontInter').+ , webMonoFont :: !WebFont+ -- ^ Monospace font (default: 'WebFontInter', set on a grid of whole+ -- pixels).+ , webFontService :: !(Maybe WebFontService)+ -- ^ A service to list families from and load them by name, in every+ -- browser (default: 'Nothing': the page contacts no third party). Firefox+ -- and Safari give a page no installed fonts, so there a service is the+ -- only source of families beyond the page's own.+ , webFallbackFonts :: ![WebFont]+ -- ^ Fonts for the characters the UI and monospace fonts lack, tried in+ -- order, as the desktop finds them among the system's fonts. Loaded when+ -- the session starts; one that will not load is left out, with a console+ -- warning. The default is the wider Inter that @scripts/build-web.sh@+ -- serves beside the page, @fonts/inter-extended.ttf@: Latin beyond ASCII,+ -- Greek, Cyrillic, punctuation and common symbols, which the bundled+ -- ASCII Inter lacks.+ , webFontSize :: !Float+ -- ^ Base font size in points (default: 16).+ , webUiScale :: !Float+ -- ^ Zoom of the whole UI on top of the device pixel ratio, which already+ -- follows the browser's own zoom (default: 1).+ , webRefreshHz :: !Int+ -- ^ Frame pacing rate while animating (default: 60).+ , webExplainLayout :: !Bool+ -- ^ Start with the layout overlay on (default: 'False').+ , webShouldQuit :: !(Input -> Bool)+ -- ^ End the session when this holds for a frame's input (default: never).+ }++-- | Default browser session options: 'defaultWindowSettings', bundled Inter+-- at 16 px, extended-Latin fallback font, 1x UI scale, and 60 Hz animation+-- pacing.+defaultSdlWebOptions :: SdlWebOptions+defaultSdlWebOptions =+ SdlWebOptions+ { webWindowSettings = defaultWindowSettings+ , webTheme = Nothing+ , webThemeFor = Nothing+ , webFont = WebFontInter+ , webMonoFont = WebFontInter+ , webFontService = Nothing+ , webFallbackFonts = [WebFontUrl "fonts/inter-extended.ttf"]+ , webFontSize = 16+ , webUiScale = 1+ , webRefreshHz = 60+ , webExplainLayout = False+ , webShouldQuit = const False+ }++-- | A frame's UI pass: its draw data, and whether the context needs another+-- frame.+type WebFrame = Context -> Input -> IO (DrawData, Bool)++-- | The session's state beyond the context.+data WebEnv = WebEnv+ { weHost :: !WebHost+ , weFonts :: !SdlFontCache+ , weRenderer :: !Renderer+ , weScale :: !(IORef Float)+ -- ^ Device pixels per layout unit: the pixel ratio times the UI scale.+ , weZoom :: !Float+ , weBacking :: !(IORef (Int, Int))+ -- ^ The drawing buffer's size in device pixels.+ , wePresented :: !(IORef (Int, Int, Float))+ -- ^ Buffer size and scale of the last presented frame. The buffer keeps+ -- that frame, so a frame at another size or scale has nothing to keep and+ -- paints in full.+ , weCursor :: !(IORef UiCursorKind)+ , weTextInput :: !(IORef (Maybe (InputPurpose, Rect)))+ , weDebug :: !DebugSamplerRef+ , weDebugPublished :: !(IORef (Maybe SdlWebDebugSnapshot))+ , weFontRequest :: !(IORef WebFont)+ -- ^ The UI font the view asked for ('setSdlWebUiFont').+ , weFontApplied :: !(IORef WebFont)+ -- ^ The UI font the font cache has open.+ , weRendererName :: !Text+ , weRefreshHz :: !Int+ , weFontService :: !(Maybe WebFontService)+ , weFamilies :: !(IORef (Maybe (Int, [String])))+ -- ^ The families 'webFontFamilies' last read, at the page's version of+ -- them; 'Nothing' until a view first asks.+ }++-- | A browser session keeps its environment on the context, so the view's+-- calls ('setSdlWebUiFont', 'askSdlWebDebug') find it without a handle.+type instance BackendSession ('Custom "sdl-web") = WebEnv++webSession :: SBackend ('Custom "sdl-web")+webSession = SCustom symbolSing++-- | Run a session on a host until the view quits or 'webShouldQuit' holds.+runWebSession :: WebHost -> SdlWebOptions -> WebFrame -> IO ()+runWebSession host opts frame = do+ base <- newPixelContext+ ctx0 <- maybe (pure base) (withTheme base) (webTheme opts)+ forM_ (webThemeFor opts) (followSystemThemeIO ctx0)+ setExplainLayout ctx0 (webExplainLayout opts)+ canvas <- queryCanvas host+ let zoom = if webUiScale opts > 0 then webUiScale opts else 1+ scaleRef <- newIORef (ciPixelRatio canvas * zoom)+ -- A search by name needs the service named before it loads anything.+ when (any isSearch [webFont opts, webMonoFont opts]) $+ whStartFontDiscovery host (serviceCode (webFontService opts))+ sans <- resolveWebFont host (webFont opts)+ mono <- resolveWebFont host (webMonoFont opts)+ fallbacks <- newWebFallbacks . concat =<< mapM (loadFallback host) (webFallbackFonts opts)+ let hooks = webFontHooks fallbacks+ rendererLabel <- rendererName host+ withTtf hooks $+ bracket newGlyphAtlas destroyGlyphAtlas $ \glyphs ->+ bracket (newSdlFontCache hooks sans mono glyphs (webFontSize opts) scaleRef) destroySdlFontCache $ \fonts ->+ bracket newRenderer freeRenderer $ \renderer -> do+ env <-+ WebEnv host fonts renderer scaleRef zoom+ <$> newIORef (0, 0)+ <*> newIORef (0, 0, 0)+ <*> newIORef UiCursorDefault+ <*> newIORef Nothing+ <*> newDebugSampler+ <*> newIORef Nothing+ <*> newIORef (webFont opts)+ <*> newIORef (webFont opts)+ <*> pure rendererLabel+ <*> pure refreshHz+ <*> pure (webFontService opts)+ <*> newIORef Nothing+ ctx1 <- withWebFonts env ctx0+ setBackendSession ctx1 webSession env+ setShaderCapabilities ctx1 (ShaderCapabilities True True)+ setDrawSnapScale ctx1 =<< readIORef scaleRef+ setWakeLoop ctx1 (whWake host)+ installWindowHost ctx1 (webWindowSettings opts) $+ defaultWindowHost+ { hostCapabilities = noWindowCapabilities {wcTitle = True}+ , hostSetTitle = \t -> withUtf8 t (whSetTitle host)+ }+ withUtf8 (wsTitle (webWindowSettings opts)) (whSetTitle host)+ (ctx2, inp0) <- syncWeb env ctx1 (applyPointerLeave emptyInput)+ let draw c inp force = drawWeb env c inp force (frame c inp)+ drv =+ SessionDriver+ { sdPollEvents = pollWeb env+ , sdWaitEvents = \t -> whWaitEvents host t >> pollWeb env+ , sdPacedWait = Nothing+ , sdApplyEvent = applyWebEvent+ , sdIsButtonEdge = isButtonEdge+ , sdIsSessionQuit = const False+ , sdSyncDisplay = syncWeb env+ , sdDebug = weDebug env+ , sdContinuous = False+ , sdVsyncOff = False+ , sdPacingMs = pacingMsFor (1 / fromIntegral refreshHz)+ , sdPresentPaces = pure False+ , sdShouldDraw = \c prevInp inp wasAnim refreshDue -> shouldRedrawFrame c prevInp inp wasAnim False refreshDue+ , sdDraw = draw+ , sdOnCursor = syncCursor env+ , sdShouldQuit = webShouldQuit opts+ , sdAlignSec = 1 / fromIntegral refreshHz+ , sdWindows = Nothing+ }+ -- The opening frame paints before the loop waits, so the canvas+ -- has content at once; if it left the context dirty, the loop+ -- draws the next frame without waiting.+ (do _ <- draw ctx2 inp0 True+ runSessionLoop drv ctx2 inp0)+ `finally` (closeWindowHost ctx2 `finally` cancelTasks ctx2)+ where+ refreshHz = if webRefreshHz opts > 0 then webRefreshHz opts else 60+ isSearch = \case WebFontSearch _ -> True; _ -> False++-- | The page's code for a font service.+serviceCode :: Maybe WebFontService -> Int+serviceCode = \case Nothing -> 0; Just Fontsource -> 1++-- | The font source for a 'WebFont', loading an installed family or a URL+-- | Resolve a 'WebFont' into raw font bytes and its display label, or 'Nothing'+-- for 'WebFontInter' or when loading failed (logging @warnPrefix@ on failure).+loadWebFontBytes :: WebHost -> String -> WebFont -> IO (Maybe (ByteString, String))+loadWebFontBytes host warnPrefix = \case+ WebFontInter -> pure Nothing+ WebFontBytes bytes label -> pure (Just (bytes, label))+ WebFontInstalled family -> load InstalledFamily family+ WebFontUrl url -> load FontUrl url+ WebFontSearch names -> firstOf (concatMap searchCandidates names)+ where+ load origin name =+ loadFontBytes host origin name >>= \case+ Just bytes -> pure (Just (bytes, name))+ Nothing -> Nothing <$ hPutStrLn stderr (warnPrefix <> show name)+ firstOf [] = pure Nothing+ firstOf (name : rest) =+ loadFontBytes host FamilyByName name >>= \case+ Just bytes -> pure (Just (bytes, name))+ Nothing -> firstOf rest++-- | A UI font as a font source, fetching an installed family or a URL+-- through the page. One that cannot be loaded is the bundled Inter, with a+-- warning on the console.+resolveWebFont :: WebHost -> WebFont -> IO FontSource+resolveWebFont host wf =+ maybe embeddedFontSource (uncurry FontFromMemory)+ <$> loadWebFontBytes host "nano-ui-sdl-web: could not load the font (using Inter): " wf++-- | A fallback font's bytes: none for the bundled Inter, which is the UI+-- font's own fallback already, or for a font that will not load.+loadFallback :: WebHost -> WebFont -> IO [ByteString]+loadFallback host wf =+ maybe [] (pure . fst)+ <$> loadWebFontBytes host "nano-ui-sdl-web: could not load the fallback font " wf++-- | Ask for a UI font. The session loads and applies it before the next+-- frame, which this asks for: the glyph atlas, metrics and text all change+-- together, as @setSdlUiFont@ does on the desktop.+-- Loading an installed family or a URL waits for the page, so that frame+-- comes when the font is in. Asking for the font already asked for does+-- nothing.+setSdlWebUiFont :: WebFont -> NanoUI ()+setSdlWebUiFont font = do+ ctx <- askContext+ askBackendSession webSession >>= mapM_ (\env -> liftIO $ do+ cur <- readIORef (weFontRequest env)+ unless (cur == font) $ writeIORef (weFontRequest env) font >> markDirty ctx)++-- | The session's frame statistics, canvas, font and renderer, refreshed at+-- most four times a second; 'Nothing' outside a browser session. Asking+-- keeps the sampler running and asks for frames at its rate, so ask only+-- while the numbers are on screen.+askSdlWebDebug :: NanoUI (Maybe SdlWebDebugSnapshot)+askSdlWebDebug =+ askBackendSession webSession >>= traverse (\env -> liftIO $+ refreshDebugSnapshot (weDebug env) (weDebugPublished env) $ \core -> do+ canvas <- queryCanvas (weHost env)+ scale <- readIORef (weScale env)+ source <- sdlFontCacheSource (weFonts env)+ let zoom = weZoom env+ pure+ SdlWebDebugSnapshot+ { dbgCore = core {dbgWinW = ciWidth canvas / zoom, dbgWinH = ciHeight canvas / zoom}+ , dbgScale = scale+ , dbgPixelRatio = ciPixelRatio canvas+ , dbgFont = fontSourceLabel source+ , dbgRenderer = weRendererName env+ , dbgRefreshHz = weRefreshHz env+ })++-- | The font families there are to choose from, for 'WebFontSearch', as+-- @NanoUI.Backend.Sdl.listFontFamilies@ lists the desktop's: the installed+-- ones (Chromium-based browsers, once the user allows it), then the font+-- service's ('webFontService'). The first call starts finding them and+-- answers what is known, possibly nothing; the view runs again as more+-- arrive. While the browser has not asked the user about installed fonts,+-- it asks at their next click or key press on the page, the only moment a+-- browser shows that question; the answer is kept for the site, so later+-- visits list them at once. Firefox and Safari have no installed fonts to+-- give, so there the list is the service's.+webFontFamilies :: NanoUI [String]+webFontFamilies =+ askBackendSession webSession >>= \case+ Nothing -> pure []+ Just env -> liftIO $ do+ known <- readIORef (weFamilies env)+ when (known == Nothing) $ whStartFontDiscovery (weHost env) (serviceCode (weFontService env))+ version <- whFontsVersion (weHost env)+ case known of+ Just (seen, families) | seen == version -> pure families+ _ -> do+ families <- knownFontFamilies (weHost env)+ families <$ writeIORef (weFamilies env) (Just (version, families))++-- | The installed font families alone, asking the user now; or why they+-- cannot be listed: the browser has no Local Font Access API (only+-- Chromium-based browsers have it), the user declined, or this is not a+-- browser. 'webFontFamilies' is the usual way, which asks at the user's next+-- press by itself. A browser shows the question only right after a click or+-- key press, so call this from a task the press starts ('NanoUI.useTask'). It+-- waits for the user's answer.+listWebFontFamilies :: IO (Either String [String])+listWebFontFamilies+ | browserAvailable = findFontFamilies =<< browserHost+ | otherwise = pure (Left "installed fonts are listed in a browser only")++-- | The context with the font cache's metrics and resolver, and the page's+-- clipboard.+withWebFonts :: WebEnv -> Context -> IO Context+withWebFonts env ctx = do+ c <- withSdlFontCache (weFonts env) ctx+ pure (withClipboard c (readClipboard (weHost env)) (writeClipboard (weHost env)))++-- | Take the queued events, decoded at the zoom. The queue is read in+-- batches, and a composition whose characters run on into the next batch+-- is carried over to it whole.+pollWeb :: WebEnv -> IO [WebEvent]+pollWeb env = allocaBytes (batch * eventRecordSize) $ \buf -> go buf Nothing []+ where+ batch = 256+ go buf carried acc = do+ n <- whTakeEvents (weHost env) buf batch+ (evs, partial) <- decodeEventBatch (weZoom env) carried buf n+ let acc' = acc ++ evs+ if n < batch+ then pure (acc' ++ maybe [] (pure . finishComposition) partial)+ else go buf partial acc'++-- | Read the canvas's size, pixel ratio, focus and colour scheme into the+-- frame's input and the window state. A new pixel ratio, or a UI font the+-- view asked for, reopens the fonts, which hands back a new context and+-- repaints everything.+syncWeb :: WebEnv -> Context -> Input -> IO (Context, Input)+syncWeb env ctx inp = do+ canvas <- queryCanvas (weHost env)+ let zoom = weZoom env+ scale = ciPixelRatio canvas * zoom+ pw = max 1 (round (ciWidth canvas * ciPixelRatio canvas))+ ph = max 1 (round (ciHeight canvas * ciPixelRatio canvas))+ oldScale <- readIORef (weScale env)+ -- A view that lists the families runs again when more arrive.+ readIORef (weFamilies env) >>= mapM_ (\(seen, _) -> do+ version <- whFontsVersion (weHost env)+ unless (version == seen) (markDirty ctx))+ requested <- readIORef (weFontRequest env)+ applied <- readIORef (weFontApplied env)+ let scaleChanged = abs (scale - oldScale) > 1e-4+ fontChanged = requested /= applied+ ctx' <-+ if scaleChanged || fontChanged+ then do+ writeIORef (weScale env) scale+ setDrawSnapScale ctx scale+ source <-+ if fontChanged+ then resolveWebFont (weHost env) requested+ else sdlFontCacheSource (weFonts env)+ writeIORef (weFontApplied env) requested+ let attachClip c = withClipboard c (readClipboard (weHost env)) (writeClipboard (weHost env))+ syncSdlFontCache (weFonts env) ctx source attachClip+ else pure ctx+ backing <- readIORef (weBacking env)+ unless (backing == (pw, ph)) $ do+ whResizeBacking (weHost env) pw ph+ writeIORef (weBacking env) (pw, ph)+ setSystemAppearance ctx' $ case ciScheme canvas of+ 1 -> Just AppearanceLight+ 2 -> Just AppearanceDark+ _ -> Nothing+ reportWindowState ctx' defaultWindowState {winScale = scale, winFocused = ciFocused canvas}+ let size = Size (max 1 (ciWidth canvas / zoom)) (max 1 (ciHeight canvas / zoom))+ pure (ctx', inp {inputWindowSize = size})++-- | Run a frame's UI pass and paint its damage, as nano-ui-sdl's draw path+-- does: the glyph atlas is maintained before the pass, and a frame that+-- could not place its glyphs is dropped for one after the atlas resets.+drawWeb :: WebEnv -> Context -> Input -> Bool -> IO (DrawData, Bool) -> IO Bool+drawWeb env ctx inp force evaluateUi = do+ let fonts = weFonts env+ glyphs = sfcGlyphAtlas fonts+ freshAtlas <- beginTtfFrame fonts ctx+ scale <- readIORef (weScale env)+ (pw, ph) <- readIORef (weBacking env)+ presented <- readIORef (wePresented env)+ let paintFull = retainedFrameStale force inp presented (pw, ph, scale)+ when (inputWindowRedraw inp) $ do+ -- A restored GL context lost every texture.+ markGlyphPagesDirty glyphs+ forgetTextures (weRenderer env)+ t0 <- getMonotonicTime+ -- A full frame draws whole whatever its damage, so its pass works none+ -- out.+ (drawData, dirty) <- withFramePaint ctx paintFull paintFull evaluateUi+ t1 <- getMonotonicTime+ syncTextInput env ctx+ damage <- takeDamage ctx+ atlasReset <- ttfFrameDropped fonts ctx freshAtlas+ if+ | atlasReset -> True <$ noteDebugSkip (weDebug env)+ | damageIsEmpty damage && not paintFull -> dirty <$ noteDebugSkip (weDebug env)+ | otherwise -> do+ syncTextures (weHost env) (weRenderer env) glyphs ctx+ renderDrawData (weHost env) (weRenderer env) scale (pw, ph) (if paintFull then DamageFull else snapDamage scale damage) drawData+ writeIORef (wePresented env) (pw, ph, scale)+ t2 <- getMonotonicTime+ noteDebugFrame (weDebug env) t0 t1 t2 t2 drawData+ pure dirty++-- | Start, move or stop the page's text input to match the focused text+-- widget, so its input method and on-screen keyboard follow the caret.+syncTextInput :: WebEnv -> Context -> IO ()+syncTextInput env ctx = do+ area <- textInputArea ctx+ let zoom = weZoom env+ next = (\a -> (textInputAreaPurpose a, textInputAreaRect a)) <$> area+ current <- readIORef (weTextInput env)+ unless (next == current) $ do+ writeIORef (weTextInput env) next+ case next of+ Nothing -> when (isJust current) $ whTextInput (weHost env) (-1) 0 0 0 0+ Just (purpose, Rect x y w h) ->+ let code = case purpose of InputNormal -> 0; InputSecure -> 1; InputNumeric -> 2+ css v = realToFrac (v * zoom)+ in whTextInput (weHost env) code (css x) (css y) (css (max 1 w)) (css (max 1 h))++-- | Set the canvas's cursor when the wanted kind changes.+syncCursor :: WebEnv -> Context -> Input -> IO ()+syncCursor env ctx inp =+ uiCursorKind ctx inp >>= syncCursorKind (weCursor env) shown (setCss . cssCursor)+ where+ setCss txt = withUtf8 txt (whSetCursor (weHost env))+ -- Hiding is a cursor of its own in CSS; showing again sets the kind next.+ shown visible = unless visible (setCss (cssCursor UiCursorHidden))++-- | The clipboard text the page last saw: its length first, then the bytes.+readClipboard :: WebHost -> IO (Maybe Text)+readClipboard host = readHostText (whClipboardRead host)++writeClipboard :: WebHost -> Text -> IO Bool+writeClipboard host txt = True <$ withUtf8 txt (whClipboardWrite host)
+ nano-ui-sdl-web.cabal view
@@ -0,0 +1,137 @@+cabal-version: 3.4+name: nano-ui-sdl-web+version: 0.2.0.0+synopsis: Browser backend for nano-ui with SDL_ttf text and WebGL2+description:+ Runs nano-ui views in a browser canvas. Built with GHC's WebAssembly+ backend, it shapes and rasterises text with SDL_ttf, as nano-ui-sdl does,+ and draws with WebGL2. Requires SDL3 and SDL3_ttf (built for wasm32-wasi+ for the browser) and pkg-config. The bundled Inter font is under the SIL+ Open Font License 1.1.+license: MIT AND OFL-1.1+license-files:+ LICENSE+ LICENSE-Inter+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++data-files:+ LICENSE-Inter+ web/*.js+ web/*.html+ web/*.svg+ web/fonts/*.ttf+ scripts/*.sh+ scripts/*.cjs++extra-source-files:+ cbits/*.h++source-repository head+ type: git+ location: https://github.com/goolord/nano-ui.git+ subdir: packages/nano-ui-sdl-web++flag sdl+ description: Build the backend. Needs SDL3, SDL3_ttf, and pkg-config.+ manual: True+ default: True++common extensions+ default-language: GHC2024+ default-extensions:+ OverloadedStrings+ if arch(wasm32)+ default-extensions: JavaScriptFFI++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.SdlWeb+ NanoUI.SdlWeb.Internal.Host+ NanoUI.SdlWeb.Internal.Input+ NanoUI.SdlWeb.Internal.Render+ NanoUI.SdlWeb.Internal.Session+ NanoUI.SdlWeb.Internal.Font+ NanoUI.SdlWeb.Internal.Fonts+ NanoUI.SdlWeb.Internal.Files+ NanoUI.SdlWeb.Internal.Debug+ build-depends:+ base >=4.20 && <4.23,+ bytestring ^>=0.12,+ containers >=0.7 && <0.9,+ nano-ui ^>=0.2,+ nano-ui-emit ^>=0.2,+ nano-ui-ttf ^>=0.2,+ primitive ^>=0.9,+ text >=2.1.2 && <2.2,+ vector ^>=0.13+ hs-source-dirs: lib+ if !flag(sdl)+ buildable: False+ if flag(sdl)+ c-sources: cbits/nano_ui_web_atlas.c+ include-dirs: cbits+ pkgconfig-depends: sdl3 >= 3.2, sdl3-ttf >= 3.2++-- The browser demo. Under wasm32 it is a reactor module whose nanoMain+-- export web/nano-ui-sdl-web.js calls; a native build only checks it+-- compiles, and running it says it needs a browser.+executable nano-ui-sdl-web-demo+ import: extensions+ import: warnings+ main-is: WebDemo.hs+ hs-source-dirs: examples+ build-depends:+ base >=4.20 && <4.23,+ nano-ui ^>=0.2,+ nano-ui-sdl-web,+ text ^>=2.1+ if arch(wasm32)+ ghc-options: -no-hs-main -optl-mexec-model=reactor "-optl-Wl,--export=hs_init,--export=nanoMain"+ if !flag(sdl)+ buildable: False++-- Runs sessions natively against a host of its own: the events it queues,+-- and the textures and draws it records.+test-suite nano-ui-sdl-web-test+ import: extensions+ import: warnings+ type: exitcode-stdio-1.0+ main-is: Spec.hs+ hs-source-dirs: test+ build-depends:+ base >=4.20 && <4.23,+ bytestring ^>=0.12,+ containers >=0.7 && <0.9,+ nano-ui ^>=0.2,+ nano-ui-sdl-web,+ nano-ui-ttf ^>=0.2,+ primitive ^>=0.9,+ text ^>=2.1,+ vector ^>=0.13+ if !flag(sdl)+ buildable: False
+ scripts/build-wasi-deps.sh view
@@ -0,0 +1,143 @@+#!/usr/bin/env bash+# Build FreeType, HarfBuzz, SDL3 and SDL3_ttf for wasm32-wasi with the C+# toolchain of GHC's wasm backend, and install them with pkg-config files+# that cabal can link statically.+#+# source ~/.ghc-wasm/env # from ghc-wasm-meta+# packages/nano-ui-sdl-web/scripts/build-wasi-deps.sh [prefix]+#+# The prefix defaults to ~/.nano-ui-wasi. Sources are downloaded into+# $prefix/src. Needs git, cmake, ninja, perl and pkg-config.+#+# SDL has no WASI platform. SDL3 is configured as a console Unix build with+# every subsystem SDL_ttf does not use turned off, and no threads: SDL_ttf+# needs only SDL's surfaces, IO streams and allocator. Three small patches+# to SDL's sources make that build go through (see where SDL is built).+set -euo pipefail++prefix="${1:-$HOME/.nano-ui-wasi}"+src="$prefix/src"+build="$prefix/build"+mkdir -p "$src" "$build"++cc="${CC:-wasm32-wasi-clang}"+cxx="${CXX:-wasm32-wasi-clang++}"+ar="${AR:-wasm32-wasi-ar}"+ranlib="${RANLIB:-wasm32-wasi-ranlib}"+command -v "$cc" >/dev/null || { echo "no $cc: source ~/.ghc-wasm/env first" >&2; exit 1; }++# wasi-libc keeps signals, mmap, getpid and process clocks behind these.+# -fPIC: ghc-wasm-meta's cabal config builds shared Haskell libraries (Template+# Haskell loads them), and the libraries that use these get linked into them.+emulated="-fPIC -D_WASI_EMULATED_SIGNAL -D_WASI_EMULATED_MMAN -D_WASI_EMULATED_GETPID -D_WASI_EMULATED_PROCESS_CLOCKS"+emulated_libs="-lwasi-emulated-signal -lwasi-emulated-mman -lwasi-emulated-getpid -lwasi-emulated-process-clocks"+# FreeType's rasterisers recover from a full cell buffer with setjmp and+# longjmp, which wasi-libc provides only on Wasm exception handling, and its+# public headers include setjmp.h, so everything that includes them needs+# the flag too.+sjlj="-mllvm -wasm-enable-sjlj"++fetch() { # name url tag+ if [ ! -d "$src/$1" ]; then+ git clone --depth 1 --branch "$3" "$2" "$src/$1"+ fi+}++cmake_wasi() { # name source-dir extra-args...; $cflags adds C flags+ local name="$1" dir="$2"+ shift 2+ cmake -S "$dir" -B "$build/$name" -G Ninja \+ -DCMAKE_SYSTEM_NAME=WASI \+ -DCMAKE_SYSTEM_PROCESSOR=wasm32 \+ -DCMAKE_C_COMPILER="$cc" \+ -DCMAKE_CXX_COMPILER="$cxx" \+ -DCMAKE_AR="$(command -v "$ar")" \+ -DCMAKE_RANLIB="$(command -v "$ranlib")" \+ -DCMAKE_C_FLAGS="$emulated $sjlj ${cflags:-}" \+ -DCMAKE_CXX_FLAGS="$emulated $sjlj -fno-exceptions -DHB_NO_MT" \+ -DCMAKE_BUILD_TYPE=Release \+ -DCMAKE_INSTALL_PREFIX="$prefix" \+ -DCMAKE_PREFIX_PATH="$prefix" \+ -DCMAKE_FIND_ROOT_PATH="$prefix" \+ -DBUILD_SHARED_LIBS=OFF \+ "$@"+ cmake --build "$build/$name"+ cmake --install "$build/$name"+}++fetch freetype https://gitlab.freedesktop.org/freetype/freetype.git VER-2-13-3+fetch harfbuzz https://github.com/harfbuzz/harfbuzz.git 10.4.0+fetch SDL https://github.com/libsdl-org/SDL.git release-3.2.26+fetch SDL_ttf https://github.com/libsdl-org/SDL_ttf.git release-3.2.2++cmake_wasi freetype "$src/freetype" \+ -DFT_DISABLE_ZLIB=ON -DFT_DISABLE_BZIP2=ON -DFT_DISABLE_PNG=ON \+ -DFT_DISABLE_HARFBUZZ=ON -DFT_DISABLE_BROTLI=ON++cmake_wasi harfbuzz "$src/harfbuzz" \+ -DHB_HAVE_FREETYPE=ON -DHB_BUILD_SUBSET=OFF -DHB_BUILD_UTILS=OFF -DHB_HAVE_GLIB=OFF \+ -DHB_HAVE_ICU=OFF -DHB_HAVE_GOBJECT=OFF -DHB_BUILD_TESTS=OFF++# The patches below start from the checked-out sources each run.+git -C "$src/SDL" checkout -- CMakeLists.txt src/dynapi/SDL_dynapi.h+# CMake knows no WASI platform, so it sets neither UNIX nor anything else+# SDL picks a platform by; SDL is told it is on Unix (-DUNIX=ON below) to+# take its POSIX sources. SDL allows a build without threads only for+# Emscripten; let WASI use the same generic thread stubs. wasi-libc's poll.h+# has no POLLPRI, which SDL's Unix poll helper names.+perl -0pi -e 's/(carefully vetted to work without threads\n\s*if\()EMSCRIPTEN\)/$1EMSCRIPTEN OR CMAKE_SYSTEM_NAME STREQUAL "WASI")/' \+ "$src/SDL/CMakeLists.txt"+# SDL's Unix URL opener forks a process; WASI takes the dummy instead.+perl -0pi -e 's/\n sdl_glob_sources\("\$\{SDL3_SOURCE_DIR\}\/src\/misc\/unix\/\*\.c"\)\n set\(HAVE_SDL_MISC TRUE\)\n/\n if(NOT CMAKE_SYSTEM_NAME STREQUAL "WASI")\n sdl_glob_sources("\${SDL3_SOURCE_DIR}\/src\/misc\/unix\/*.c")\n set(HAVE_SDL_MISC TRUE)\n endif()\n/' \+ "$src/SDL/CMakeLists.txt"+# The dynamic API loads SDL from a shared library; a static WASI build has+# no dlopen, so it is off, as for Emscripten.+perl -0pi -e 's/(#elif defined\(SDL_PLATFORM_EMSCRIPTEN\)[^\n]*\n#define SDL_DYNAMIC_API 0\n)/$1#elif defined(__wasi__)\n#define SDL_DYNAMIC_API 0\n/' \+ "$src/SDL/src/dynapi/SDL_dynapi.h"++cflags="-DPOLLPRI=0" cmake_wasi SDL "$src/SDL" -DUNIX=ON \+ -DSDL_STATIC=ON -DSDL_SHARED=OFF -DSDL_TEST_LIBRARY=OFF -DSDL_TESTS=OFF -DSDL_EXAMPLES=OFF \+ -DSDL_UNIX_CONSOLE_BUILD=ON -DSDL_THREADS=OFF -DSDL_PTHREADS=OFF \+ -DSDL_AUDIO=OFF -DSDL_JOYSTICK=OFF -DSDL_HAPTIC=OFF -DSDL_HIDAPI=OFF -DSDL_SENSOR=OFF \+ -DSDL_POWER=OFF -DSDL_CAMERA=OFF -DSDL_DIALOG=OFF -DSDL_GPU=OFF -DSDL_TRAY=OFF \+ -DSDL_DUMMYVIDEO=ON -DSDL_OFFSCREEN=OFF -DSDL_OPENGL=OFF -DSDL_OPENGLES=OFF -DSDL_VULKAN=OFF \+ -DSDL_LIBC=ON++cmake_wasi SDL_ttf "$src/SDL_ttf" \+ -DSDLTTF_VENDORED=OFF -DSDLTTF_HARFBUZZ=ON -DSDLTTF_PLUTOSVG=OFF -DSDLTTF_SAMPLES=OFF++# cabal asks pkg-config for --libs without --static, so fold each file's+# private requirements and libraries into its public ones, and add what a+# static link of these needs from wasi-sdk: the WASI emulation libraries,+# HarfBuzz's C++ runtime and FreeType's setjmp, with the flag FreeType's+# headers need.+for pc in "$prefix"/lib/pkgconfig/*.pc; do+ awk -v extra_sdl="$emulated_libs" -v sjlj="$sjlj" -v name="$(basename "$pc" .pc)" '+ /^Requires\.private:/ { sub(/^Requires\.private:/, ""); reqp = reqp " " $0; next }+ /^Libs\.private:/ { sub(/^Libs\.private:/, ""); libp = libp " " $0; next }+ { lines[++n] = $0 }+ END {+ for (i = 1; i <= n; i++) {+ line = lines[i]+ if (line ~ /^Requires:/) { line = line reqp; reqp = "" }+ if (line ~ /^Libs:/) {+ line = line libp+ # HarfBuzz is built without threads (HB_NO_MT), and -pthread asks+ # wasm-ld for shared memory the browser module does not have.+ gsub(/ -pthread/, "", line)+ if (name == "sdl3") line = line " " extra_sdl+ if (name == "harfbuzz") line = line " -lc++ -lc++abi"+ if (name == "freetype2") line = line " -lsetjmp"+ libp = ""+ }+ if (line ~ /^Cflags:/ && name == "freetype2") line = line " " sjlj+ print line+ }+ if (reqp != "") print "Requires:" reqp+ }' "$pc" > "$pc.tmp"+ mv "$pc.tmp" "$pc"+done++echo+echo "Installed in $prefix. Build the demo with:"+echo " PKG_CONFIG_PATH=$prefix/lib/pkgconfig packages/nano-ui-sdl-web/scripts/build-web.sh"
+ scripts/build-web.sh view
@@ -0,0 +1,114 @@+#!/usr/bin/env bash+# Optional bundler for nano-ui-sdl-web programs: compiles a wasm32 target with+# GHC's wasm backend and writes a self-contained static directory containing+# the HTML shell, JS runtime, wasm module, JSFFI glue, browser_wasi_shim, and+# fallback font.+#+# source ~/.ghc-wasm/env+# export PKG_CONFIG_PATH=~/.nano-ui-wasi/lib/pkgconfig # build-wasi-deps.sh+# bash path/to/nano-ui-sdl-web/scripts/build-web.sh [out-dir [cabal-target]]+# python3 -m http.server -d <out-dir> 8000+#+# Works both inside the nano-ui repository and in downstream projects (using+# this script from `cabal unpack nano-ui-sdl-web` or from nano-ui-sdl-web's+# installed Cabal data-dir).+#+# Inside the nano-ui repository, out-dir defaults to <repo>/dist-web, target+# defaults to nano-ui-sdl-web:exe:nano-ui-sdl-web-demo, and cabal.project.wasm+# is selected automatically. In a downstream project, cabal runs in the current+# directory, out-dir defaults to ./dist-web, and cabal-target names your+# executable (or may be omitted if the project has a single executable). Set+# CABAL_PROJECT to pass an explicit --project-file to wasm32-wasi-cabal.+#+# The target must be an executable built as a reactor module that exports+# nanoMain (see the nano-ui-sdl-web README). Needs node and npm (both come+# with ghc-wasm-meta) for the JSFFI glue and the WASI shim.+#+# WASM_OPT_FLAGS are wasm-opt's optimisation flags (default -O2; -Oz makes a+# smaller, somewhat slower module). The script ends by printing the module's+# size as linked, as served, and under gzip, which is how a web server sends+# it.+set -euo pipefail++script_dir="$(cd "$(dirname "$0")" && pwd)"+pkg="$(cd "$script_dir/.." && pwd)"+cwd="$(pwd)"++# Detect whether we are running inside the nano-ui monorepo (from its root+# or any subdirectory) rather than a separate downstream project.+in_monorepo=0+repo=""+if [ -f "$pkg/../../cabal.project.wasm" ]; then+ repo="$(cd "$pkg/../.." && pwd)"+ case "$cwd/" in+ "$repo/"*) in_monorepo=1 ;;+ esac+fi++project_args=()+target_args=()+if [ -n "${CABAL_PROJECT:-}" ]; then+ project_args=(--project-file="$CABAL_PROJECT")+elif [ "$in_monorepo" -eq 1 ]; then+ project_args=(--project-file="$repo/cabal.project.wasm")+elif [ -f "$cwd/cabal.project.wasm" ]; then+ project_args=(--project-file="$cwd/cabal.project.wasm")+fi++if [ "$in_monorepo" -eq 1 ]; then+ work_dir="$repo"+ out="${1:-$repo/dist-web}"+ target="${2:-nano-ui-sdl-web:exe:nano-ui-sdl-web-demo}"+ target_args=("$target")+else+ work_dir="$cwd"+ out="${1:-$cwd/dist-web}"+ if [ -n "${2:-}" ]; then+ target="$2"+ target_args=("$target")+ elif [ "$cwd" = "$pkg" ]; then+ target="nano-ui-sdl-web:exe:nano-ui-sdl-web-demo"+ target_args=("$target")+ else+ target="default executable"+ fi+fi+shim_version="0.4.1"++command -v wasm32-wasi-cabal >/dev/null || { echo "no wasm32-wasi-cabal: source ~/.ghc-wasm/env first" >&2; exit 1; }++# -j1 keeps one GHC process at a time, as the native CI build does.+(cd "$work_dir" && wasm32-wasi-cabal build -j1 ${project_args[@]+"${project_args[@]}"} ${target_args[@]+"${target_args[@]}"})+wasm="$(cd "$work_dir" && wasm32-wasi-cabal list-bin ${project_args[@]+"${project_args[@]}"} ${target_args[@]+"${target_args[@]}"})"++mkdir -p "$out"+out="$(cd "$out" && pwd)"+cp "$pkg"/web/index.html "$pkg"/web/favicon.svg "$pkg"/web/main.js "$pkg"/web/nano-ui-sdl-web.js "$out"/+# The fallback font the default options load, with its licence.+mkdir -p "$out/fonts"+cp "$pkg"/web/fonts/*.ttf "$out/fonts/"+if [ -f "$pkg/LICENSE-Inter" ]; then+ cp "$pkg/LICENSE-Inter" "$out/fonts/"+fi+# The glue the module's JavaScript imports need, generated from the module+# before wasm-opt drops the custom section it is read from.+"$(wasm32-wasi-ghc --print-libdir)/post-link.mjs" -i "$wasm" -o "$out/ghc_wasm_jsffi.js"+if command -v wasm-opt >/dev/null; then+ # shellcheck disable=SC2086+ wasm-opt --strip-debug ${WASM_OPT_FLAGS:--O2} "$wasm" -o "$out/main.wasm"+else+ cp "$wasm" "$out/main.wasm"+fi++# The WASI shim main.js imports, from npm, with its licences.+tmp="$(mktemp -d)"+trap 'rm -rf "$tmp"' EXIT+(cd "$tmp" && npm pack --silent "@bjorn3/browser_wasi_shim@$shim_version" >/dev/null && tar xzf ./*.tgz)+rm -rf "$out/browser_wasi_shim"+mkdir -p "$out/browser_wasi_shim"+cp "$tmp"/package/dist/*.js "$tmp"/package/LICENSE-* "$out/browser_wasi_shim/"++echo "Size of $target: $(wc -c <"$wasm") bytes linked," \+ "$(wc -c <"$out/main.wasm") served, $(gzip -9 -c "$out/main.wasm" | wc -c) under gzip."+echo "Built $out. Serve it with:"+echo " python3 -m http.server -d $out 8000"
+ scripts/smoke-test.cjs view
@@ -0,0 +1,160 @@+// Load a directory build-web.sh made in headless Chromium and check the+// program runs: the page sets its title from Haskell, the canvas gets a+// frame with text on it, a click at the given point changes the frame, and+// nothing is logged as an error.+//+// node packages/nano-ui-sdl-web/scripts/smoke-test.cjs <dir> <x> <y> [screenshot.png]+// node packages/nano-ui-sdl-web/scripts/smoke-test.cjs <dir> - - [screenshot.png]+//+// The point is in CSS pixels of a 1280x800 page; pick one on a control+// whose press redraws something. With "- -" for the point there is no+// click: the program animates on its own, so its frame never settles for a+// click to change, and the check is that the frame changes with no input.+// The page's own <title> may then already be the program's. The+// screenshot, if named, is taken at the end whether the checks pass or not. Needs the playwright package (ghc-wasm-meta+// installs it under NODE_PATH). SMOKE_CHROME names a Chrome or Chromium+// binary to use instead of Playwright's own.+"use strict";++const http = require("http");+const fs = require("fs");+const path = require("path");+const { chromium } = require("playwright");++const [dir, x, y, shot] = process.argv.slice(2);+const animated = x === "-" && y === "-";+if (!dir || x === undefined || y === undefined) {+ console.error("usage: smoke-test.cjs <dir> <x> <y> [screenshot.png] (- - for x y: no click)");+ process.exit(2);+}++const types = {+ ".html": "text/html", ".js": "text/javascript", ".mjs": "text/javascript",+ ".wasm": "application/wasm", ".css": "text/css", ".png": "image/png",+ ".svg": "image/svg+xml",+};++function serve(root) {+ const server = http.createServer((req, res) => {+ const url = decodeURIComponent(new URL(req.url, "http://localhost").pathname);+ let file = path.join(root, url);+ if (!file.startsWith(path.resolve(root))) { res.writeHead(403); res.end(); return; }+ if (fs.existsSync(file) && fs.statSync(file).isDirectory()) file = path.join(file, "index.html");+ fs.readFile(file, (err, data) => {+ if (err) { res.writeHead(404); res.end(); return; }+ res.writeHead(200, { "Content-Type": types[path.extname(file)] || "application/octet-stream" });+ res.end(data);+ });+ });+ return new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve(server)));+}++// A summary of the canvas's pixels: how many distinct colours a coarse grid+// of samples has, and a hash of those samples.+async function canvasSummary(page) {+ return page.evaluate(() => {+ const c = document.querySelector("canvas");+ const probe = document.createElement("canvas");+ probe.width = c.width;+ probe.height = c.height;+ const ctx = probe.getContext("2d");+ ctx.drawImage(c, 0, 0);+ const data = ctx.getImageData(0, 0, c.width, c.height).data;+ const colours = new Set();+ let hash = 0;+ for (let i = 0; i < data.length; i += 4 * 7) {+ const v = (data[i] << 16) | (data[i + 1] << 8) | data[i + 2];+ colours.add(v);+ hash = (hash * 31 + v) | 0;+ }+ return { colours: colours.size, hash };+ });+}++async function waitFor(what, ms, check) {+ const deadline = Date.now() + ms;+ for (;;) {+ const result = await check();+ if (result) return result;+ if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`);+ await new Promise((r) => setTimeout(r, 200));+ }+}++(async () => {+ const server = await serve(path.resolve(dir));+ const url = `http://127.0.0.1:${server.address().port}/`;+ const browser = await chromium.launch({+ executablePath: process.env.SMOKE_CHROME || undefined,+ // WebGL2 on the CPU, for machines with no GPU.+ args: ["--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--ignore-gpu-blocklist"],+ });+ const errors = [];+ const page = await browser.newPage({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: 1 });+ try {+ page.on("pageerror", (e) => errors.push(`page error: ${e.message}`));+ // A failed response is judged by its URL below; the console's own line+ // for it names none. Browsers ask for /favicon.ico unprompted.+ page.on("console", (m) => {+ if (m.type() === "error" && !m.text().startsWith("Failed to load resource")) errors.push(`console error: ${m.text()}`);+ else if (m.type() !== "error") console.log(`[page] ${m.text()}`);+ });+ // Only the page's own files count: a font service on another origin+ // may be down, and the page falls back to its own fonts then.+ const own = (u) => new URL(u).origin === new URL(url).origin;+ page.on("response", (r) => {+ if (own(r.url()) && r.status() >= 400 && new URL(r.url()).pathname !== "/favicon.ico") errors.push(`HTTP ${r.status()}: ${r.url()}`);+ });+ page.on("requestfailed", (r) => { if (own(r.url())) errors.push(`request failed: ${r.url()}`); });+ await page.goto(url);+ const title = await waitFor("the program to set the title", 60000, async () => {+ const t = await page.title();+ return (animated || t !== "nano-ui") && t ? t : (errors.length ? Promise.reject(new Error(errors.join("\n"))) : null);+ });+ console.log(`title: ${title}`);+ // With no title to wait for first, the program may still be loading.+ const first = await waitFor("a frame with text", animated ? 90000 : 30000, async () => {+ const s = await canvasSummary(page);+ return s.colours >= 8 ? s : null;+ });+ console.log(`first frame: ${first.colours} colours sampled`);+ if (animated) {+ await waitFor("the frame to change with no input", 10000, async () => {+ await new Promise((r) => setTimeout(r, 300));+ const s = await canvasSummary(page);+ return s.hash !== first.hash ? s : null;+ });+ console.log("the frame changed with no input");+ if (errors.length) throw new Error(errors.join("\n"));+ console.log(`ok: ${url}`);+ return;+ }+ // Hover first and let the frame settle, so only the press can change it.+ await page.mouse.move(Number(x), Number(y));+ let hovered = await canvasSummary(page);+ await waitFor("the hovered frame to settle", 10000, async () => {+ await new Promise((r) => setTimeout(r, 500));+ const s = await canvasSummary(page);+ const same = s.hash === hovered.hash;+ hovered = s;+ return same;+ });+ await page.mouse.down();+ await page.mouse.up();+ const after = await waitFor("the click to redraw the frame", 10000, async () => {+ await new Promise((r) => setTimeout(r, 300));+ const s = await canvasSummary(page);+ return s.hash !== hovered.hash ? s : null;+ });+ console.log(`after the click at ${x},${y}: ${after.colours} colours sampled`);+ if (errors.length) throw new Error(errors.join("\n"));+ console.log(`ok: ${url}`);+ } finally {+ if (shot) await page.screenshot({ path: shot }).catch(() => {});+ await browser.close();+ server.close();+ }+})().catch((e) => {+ console.error(`FAIL: ${e.message}`);+ process.exit(1);+});
+ test/Spec.hs view
@@ -0,0 +1,555 @@+{-# LANGUAGE DataKinds #-}+-- | Sessions run natively against a scripted host: it answers the canvas+-- queries, queues each step's events when the session waits, and records+-- the texture uploads and draws the session sends.+module Main (main) where++import Control.Exception (Exception, catch, throwIO)+import Data.ByteString.Unsafe (unsafeUseAsCStringLen)+import Foreign.Marshal.Utils (copyBytes)+import NanoUI.Backend.SdlWeb (SdlWebDebugSnapshot (..), CoreDebugSnapshot (..), WebFont (..), WebFontService (..), askSdlWebDebug, listWebFontFamilies, setSdlWebUiFont, webFontFamilies)+import NanoUI.SdlWeb.Internal.Files+ ( FileDialogMode (..)+ , FileDialogOptions (..)+ , FileFilter (..)+ , WebFile (..)+ , decodePicked+ , defaultFileDialogOptions+ , openWebFiles+ , pickFiles+ , saveFile+ )+import NanoUI.SdlWeb.Internal.Fonts (findFontFamilies)+import NanoUI.Ttf.Internal.Inter (fontInterBytes, fontInterLabel)+import NanoUI.Ttf.Internal.Font (FontHooks (..), SdlFont (..), closeFont, openFontBytes, readSdlFont)+import qualified NanoUI.Ttf.Internal.Font as Ttf+import NanoUI.SdlWeb.Internal.Font (newWebFallbacks, webFontHooks)+import qualified Data.IntMap.Strict as IM+import Control.Monad (forM_, when)+import Control.Monad.IO.Class (liftIO)+import Data.IORef (IORef, atomicModifyIORef', modifyIORef', newIORef, readIORef, writeIORef)+import Data.Int (Int32)+import qualified Data.Primitive.PrimArray as PA+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import qualified Data.ByteString as BS+import qualified Data.Vector.Unboxed as U+import Data.Word (Word8)+import Foreign.ForeignPtr (newForeignPtr_)+import Foreign.Ptr (Ptr, castPtr, nullPtr)+import Foreign.Storable (peekByteOff, pokeByteOff, pokeElemOff)+import NanoUI (NanoUI, Rect (..), Shader, ShaderKind (..), UiCursorKind (..), V2 (..), askInput, box, button, column, colorRGB, fixedWH, label, shaderBox, withShader)+import NanoUI.Shader.Raw (emptyShaderProgram, rawLayerShader, rawShader)+import NanoUI.Backend+ ( Composition (..), Damage (..), DrawCmd (..), DrawData (..), Input (..), Key (..), Layer (..), ShaderProgram (..), glyphAtlasPages+ , emptyEffectSpans, emptyShaderCalls, emptyUniformBytes+ , glyphPageTextureId, pixelEdges, snapDamage, vertexSize+ )+import NanoUI.SdlWeb.Internal.Host+import NanoUI.SdlWeb.Internal.Input (cssCursor, decodeKey)+import NanoUI.SdlWeb.Internal.Render (DrawCommand (..), drawCommands')+import NanoUI.SdlWeb.Internal.Session (SdlWebOptions (..), WebFrame, defaultSdlWebOptions, runWebSession)+import NanoUI.Testing (runFrame)+import NanoUI.Testing.Runner (check, runChecks)+import NanoUI.Ttf.Internal.Header (glyphAtlasPageCount, vertexBytes)++-- ---------------------------------------------------------------------------+-- The scripted host++-- | One event record: kind, a, b, c, modifiers, x, y, z.+type Record = (Int, Int, Int, Int, Int, Float, Float, Float)++-- | What happens at one wait: the canvas's new width, height and pixel+-- ratio, if they change, and the events queued.+type Step = (Maybe (Float, Float, Float), [Record])++data Upload = Upload {upSlot :: Int, upW :: Int, upRect :: (Int, Int, Int, Int), upInk :: Bool}+ deriving (Show)++data Frame = Frame+ { frClear :: Bool+ , frScale :: Double+ , frSize :: (Int, Int)+ , frDraws :: [(Int, Int, Int, Maybe (Int, Int, Int, Int))]+ , frShaderDraws :: [(Int, Int, Int)]+ , frIndexCount :: Int+ }+ deriving (Show)++data Recorded = Recorded+ { recUploads :: IORef [Upload]+ , recFrames :: IORef [Frame]+ , recBacking :: IORef [(Int, Int)]+ , recCursor :: IORef [T.Text]+ , recTitle :: IORef [T.Text]+ , recFontsAsked :: IORef [String]+ , recFilters :: IORef [T.Text]+ , recSaved :: IORef [(T.Text, BS.ByteString)]+ , recDiscovery :: IORef [Int]+ , recShaders :: IORef [(Int, T.Text)]+ , recUniforms :: IORef [BS.ByteString]+ , recTargets :: IORef [(String, Int)]+ , recComposites :: IORef [(Int, Int, Bool, Int)]+ }++data ScriptDone = ScriptDone deriving (Show)++instance Exception ScriptDone++-- | A host whose canvas is @canvas@ and whose events come from the steps,+-- one step each time the session waits. Once the steps are out, a wait with+-- a limit ends without events, so a busy session settles; the session ends+-- at its first wait with no limit.+scriptedHost :: IORef (Float, Float, Float) -> [Step] -> IO (WebHost, Recorded)+scriptedHost canvas steps0 = do+ steps <- newIORef steps0+ queue <- newIORef []+ idle <- newIORef (0 :: Int)+ nextTarget <- newIORef (0 :: Int)+ rec <- Recorded <$> newIORef [] <*> newIORef [] <*> newIORef [] <*> newIORef [] <*> newIORef [] <*> newIORef [] <*> newIORef [] <*> newIORef [] <*> newIORef [] <*> newIORef [] <*> newIORef [] <*> newIORef [] <*> newIORef []+ pendingFont <- newIORef BS.empty+ picked <- newIORef BS.empty+ extended <- BS.readFile extendedFontPath+ let take' buf n = do+ evs <- readIORef queue+ let (now, later) = splitAt n evs+ writeIORef queue later+ forM_ (zip [0 ..] now) $ \(i, (k, a, b, c, m, x, y, z)) -> do+ let o = i * eventRecordSize+ forM_ (zip [0 ..] [k, a, b, c, m]) $ \(j, v) -> pokeByteOff buf (o + j * 4) (fromIntegral v :: Int32)+ forM_ (zip [5 ..] [x, y, z]) $ \(j, v) -> pokeByteOff buf (o + j * 4) v+ pure (length now)+ wait ms = do+ pending <- readIORef queue+ when (null pending) $+ readIORef steps >>= \case+ (resized, evs) : rest -> do+ writeIORef steps rest+ mapM_ (writeIORef canvas) resized+ writeIORef queue evs+ [] -> do+ n <- readIORef idle+ writeIORef idle (n + 1)+ when (ms < 0 || n > 50) (throwIO ScriptDone)+ utf8 p n = TE.decodeUtf8 <$> BS.packCStringLen (castPtr p, n)+ host =+ WebHost+ { whQueryCanvas = \p -> do+ (w, h, ratio) <- readIORef canvas+ forM_ (zip [0 ..] [w, h, ratio, 1, 2]) $ \(i, v) -> pokeElemOff p i v+ , whTakeEvents = take'+ , whWaitEvents = wait+ , whWake = pure ()+ , whResizeBacking = \w h -> modifyIORef' (recBacking rec) ((w, h) :)+ , whUploadTexture = \slot w _ pixels row x y rw rh -> do+ ink <- anyInk pixels row x y rw rh+ modifyIORef' (recUploads rec) (Upload slot w (x, y, rw, rh) ink :)+ , whBeginFrame = \clear _ _ _ _ scale w h ->+ modifyIORef' (recFrames rec) (Frame clear scale (w, h) [] [] 0 :)+ , whDraw = \_ _ _ icount cmds n -> do+ decoded <- mapM (readCommand cmds) [0 .. n - 1]+ let draws = map fst decoded+ shDraws = filter (\(s, _, _) -> s > 0) (map snd decoded)+ modifyIORef' (recFrames rec) $ \case+ f : fs -> f {frDraws = draws, frShaderDraws = shDraws, frIndexCount = icount} : fs+ [] -> []+ , whRegisterShader = \slot p n -> do+ src <- utf8 p n+ modifyIORef' (recShaders rec) ((slot, src) :)+ pure True+ , whUploadUniforms = \p n -> do+ bs <- BS.packCStringLen (castPtr p, n)+ modifyIORef' (recUniforms rec) (bs :)+ , whAcquireTarget = \minW minH outCaps -> do+ slot <- atomicModifyIORef' nextTarget (\k -> (k + 1, k))+ let capW = max 64 (((minW + 63) `div` 64) * 64)+ capH = max 64 (((minH + 63) `div` 64) * 64)+ pokeElemOff outCaps 0 (fromIntegral capW)+ pokeElemOff outCaps 1 (fromIntegral capH)+ modifyIORef' (recTargets rec) (("acquire", slot) :)+ pure slot+ , whReleaseTarget = \slot ->+ modifyIORef' (recTargets rec) (("release", slot) :)+ , whBindTarget = \slot _ _ _ ->+ modifyIORef' (recTargets rec) (("bind", slot) :)+ , whCompositeEffect = \srcSlot shSlot blendCopy _ _ _ uLen ->+ modifyIORef' (recComposites rec) ((srcSlot, shSlot, blendCopy, uLen) :)+ , whSetCursor = \p n -> utf8 p n >>= \t -> modifyIORef' (recCursor rec) (t :)+ , whTextInput = \_ _ _ _ _ -> pure ()+ , whClipboardRead = \_ _ -> pure (-1)+ , whClipboardWrite = \_ _ -> pure ()+ , whSetTitle = \p n -> utf8 p n >>= \t -> modifyIORef' (recTitle rec) (t :)+ , whRendererInfo = \p n -> copyOut p n testRenderer+ , whFindFonts = pure (BS.length testFamilies)+ , whTakeFontList = \p -> () <$ copyOut p (BS.length testFamilies) testFamilies+ , whLoadFont = \kind p n -> do+ name <- T.unpack <$> utf8 p n+ modifyIORef' (recFontsAsked rec) (name :)+ -- The host serves the bundled Inter at one URL and the wider+ -- fallback Inter where the default options look for it, and+ -- has no installed families.+ let serve b = BS.length b <$ writeIORef pendingFont b+ -- By name it has Noto Sans (as Inter's bytes).+ case (kind, name) of+ (1, "fonts/inter.ttf") -> serve fontInterBytes+ (1, "fonts/inter-extended.ttf") -> serve extended+ (2, "Noto Sans") -> serve fontInterBytes+ _ -> pure (-1)+ , whTakeFontBytes = \p -> readIORef pendingFont >>= \b -> () <$ copyOut p (BS.length b) b+ -- The chooser picks two files, or is cancelled when asked for a+ -- folder.+ , whPickFiles = \mode _ p n -> do+ utf8 p n >>= \t -> modifyIORef' (recFilters rec) (t :)+ if mode == 1+ then pure (-1)+ else BS.length testPicked <$ writeIORef picked testPicked+ , whSaveFile = \np nn _ _ dp dn -> do+ name <- utf8 np nn+ bytes <- BS.packCStringLen (castPtr dp, dn)+ modifyIORef' (recSaved rec) ((name, bytes) :)+ let saved = TE.encodeUtf8 name+ BS.length saved <$ writeIORef picked saved+ , whTakePicked = \p -> readIORef picked >>= \b -> () <$ copyOut p (BS.length b) b+ , whStartFontDiscovery = \service -> modifyIORef' (recDiscovery rec) (service :)+ , whFontsVersion = length <$> readIORef (recDiscovery rec)+ , whFontFamilies = \p n -> do+ started <- readIORef (recDiscovery rec)+ copyOut p n (if null started then "" else "Inter\nNoto Sans")+ }+ pure (host, rec)++-- | The fallback font the page serves, from the package's sources.+extendedFontPath :: FilePath+extendedFontPath = "web/fonts/inter-extended.ttf"++-- | What the scripted host reports as its WebGL renderer and its installed+-- font families.+testRenderer, testFamilies :: BS.ByteString+testRenderer = "WebGL2, Scripted"+testFamilies = "Inter\nNoto Sans\nInter"++-- | Two files as the page packs them: a 32-bit little-endian name length,+-- the name, a 32-bit length and the bytes, each.+testPicked :: BS.ByteString+testPicked = BS.concat [record "notes.txt" "hello", record "d/\195\169.bin" "\0\1\2"]+ where+ record name bytes = BS.concat [le (BS.length name), name, le (BS.length bytes), bytes]+ le n = BS.pack [fromIntegral (n `div` (256 ^ k)) | k <- [0 .. 3 :: Int]]++-- | Copy up to @n@ bytes of @b@ to @p@, and answer @b@'s full length.+copyOut :: Ptr Word8 -> Int -> BS.ByteString -> IO Int+copyOut p n b = do+ when (n > 0) $ unsafeUseAsCStringLen b $ \(src, len) -> copyBytes p (castPtr src) (min n len)+ pure (BS.length b)++readCommand :: Ptr Word8 -> Int -> IO ((Int, Int, Int, Maybe (Int, Int, Int, Int)), (Int, Int, Int))+readCommand buf i = do+ let at k = fromIntegral <$> (peekByteOff buf (i * commandRecordSize + k * 4) :: IO Int32)+ [slot, first, count, on, x, y, w, h, shSlot, uOff, uLen] <- mapM at [0 .. 10]+ pure ((slot, first, count, if on /= 0 then Just (x, y, w, h) else Nothing), (shSlot, uOff, uLen))++-- | Whether any pixel in a rect has alpha, skipping the 4x4 white patch+-- every page starts with.+anyInk :: Ptr Word8 -> Int -> Int -> Int -> Int -> Int -> IO Bool+anyInk pixels row x0 y0 w h = go x0 y0+ where+ go x y+ | y >= y0 + h = pure False+ | x >= x0 + w = go x0 (y + 1)+ | x < 4 && y < 4 = go (x + 1) y+ | otherwise = do+ a <- peekByteOff pixels ((y * row + x) * 4 + 3) :: IO Word8+ if a /= 0 then pure True else go (x + 1) y++runScript :: (Float, Float, Float) -> [Step] -> WebFrame -> IO Recorded+runScript canvas0 steps frame = do+ canvas <- newIORef canvas0+ (host, rec) <- scriptedHost canvas steps+ runWebSession host defaultSdlWebOptions frame `catch` \ScriptDone -> pure ()+ pure rec++viewFrame :: NanoUI () -> WebFrame+viewFrame ui ctx inp = (\(_, dd, dirty) -> (dd, dirty)) <$> runFrame ctx inp ui++motion :: Float -> Float -> Record+motion x y = (2, 0, 0, 0, 0, x, y, 0)++press, release, resize :: Record+press = (3, 0, 1, 0, 0, 0, 0, 0)+release = (3, 0, 0, 0, 0, 0, 0, 0)+resize = (1, 0, 0, 0, 0, 0, 0, 0)++events :: [Record] -> Step+events evs = (Nothing, evs)++-- ---------------------------------------------------------------------------++main :: IO ()+main =+ runChecks+ [ ("pure", pureChecks)+ , ("opening", openingFrame)+ , ("click", clickFrame)+ , ("pixel-ratio", pixelRatioChange)+ , ("long-composition", longComposition)+ , ("fonts-and-debug", fontsAndDebug)+ , ("file-dialogs", fileDialogs)+ , ("fallback-fonts", fallbackFonts)+ , ("font-search", fontSearch)+ , ("shaders", shaderSession)+ ]++pureChecks :: IORef Int -> IO ()+pureChecks failed = do+ check failed "cssCursor nwse-resize" (cssCursor UiCursorNwseResize == "nwse-resize")+ check failed "cssCursor context-menu" (cssCursor UiCursorContextMenu == "context-menu")+ check failed "cssCursor hidden is none" (cssCursor UiCursorHidden == "none")+ check failed "decodeKey character" (decodeKey False 97 == Just (KeyChar 'a'))+ check failed "decodeKey uppercase lowers" (decodeKey False 65 == Just (KeyChar 'a'))+ check failed "decodeKey named" (decodeKey False (-1) == Just KeyBackspace && decodeKey False (-21) == Just KeyMenu)+ check failed "decodeKey F5" (decodeKey False (-105) == Just (KeyF 5))+ check failed "decodeKey keypad under Num Lock" (decodeKey True (-(300 + 55)) == Just (KeyChar '7'))+ check failed "decodeKey keypad without Num Lock" (decodeKey False (-(300 + 55)) == Just KeyHome)+ check failed "decodeKey modifier" (decodeKey False 0 == Nothing)+ -- Commands that continue each other's indices with one texture and clip+ -- join; a command outside the damage is dropped.+ dd <- fakeDrawData+ [ DrawCmd 0 0 100 100 (glyphPageTextureId 0) 0 6 LayerContent 0+ , DrawCmd 0 0 100 100 (glyphPageTextureId 0) 6 6 LayerContent 0+ , DrawCmd 0 0 100 100 (glyphPageTextureId 1) 12 6 LayerContent 0+ , DrawCmd 500 500 10 10 (glyphPageTextureId 1) 18 6 LayerContent 0+ ]+ let full = drawCommands' 1 (800, 600) DamageFull dd+ check failed "drawCommands' joins neighbours" (map dcCount full == [12, 6, 6])+ check failed "drawCommands' slots" (map dcSlot full == [0, 1, 1])+ let partial = drawCommands' 2 (800, 600) (DamageClip (Rect 10 10 20 20)) dd+ check failed "drawCommands' drops commands outside the damage" (length partial == 2)+ check failed "drawCommands' scissors to the damage in pixels" (all ((== Just (20, 20, 40, 40)) . dcScissor) partial)+ -- Damage snapped to whole pixels comes back from layout units a rounding+ -- error off them at some scales; the scissor stays on the snapped pixels.+ let cases = [(s, Rect x x 20.3 7.9) | s <- [1, 1.1, 1.2, 1.25, 1.3, 1.4, 1.5, 1.75, 2.25, 3], x <- [0.3, 3.7, 10.1, 33.3, 77.7]]+ snapped s r = case snapDamage s (DamageClip r) of+ DamageClip r' -> r'+ DamageFull -> r+ want s r = let (x0, y0, x1, y1) = pixelEdges s r in Just (x0, y0, x1 - x0, y1 - y0)+ scissorOf s r = map dcScissor (drawCommands' s (800, 600) (DamageClip (snapped s r)) dd)+ check failed "drawCommands' test cases include a damage edge a rounding error off its pixel"+ (any (\(s, r) -> pixelEdges s (snapped s r) /= pixelEdges s r) cases)+ check failed "drawCommands' scissors snapped damage to its own pixels at fractional scales"+ (all (\(s, r) -> all (== want s r) (take 1 (scissorOf s r))) cases)+ check failed "nano_ui_ttf_shared.h: NANO_UI_VERTEX_BYTES is the core's vertexSize" (vertexBytes == vertexSize)+ check failed "nano_ui_ttf_shared.h: NANO_UI_GLYPH_ATLAS_PAGES is the core's glyphAtlasPages" (glyphAtlasPageCount == glyphAtlasPages)++fakeDrawData :: [DrawCmd] -> IO DrawData+fakeDrawData cmds = do+ fp <- newForeignPtr_ nullPtr+ pure+ DrawData+ { drawVertices = fp+ , drawVertexCount = 0+ , drawIndices = fp+ , drawIndexCount = 24+ , drawCommands = U.fromList cmds+ , drawLayerOffsets = PA.primArrayFromList [0, 0, length cmds, length cmds, length cmds]+ , drawClear = colorRGB 0 0 0+ , drawShaderCalls = emptyShaderCalls+ , drawUniformBytes = emptyUniformBytes+ , drawEffectSpans = emptyEffectSpans+ }++openingFrame :: IORef Int -> IO ()+openingFrame failed = do+ rec <- runScript (800, 600, 1) [] (viewFrame (column (label "Hello from SDL_ttf")))+ frames <- reverse <$> readIORef (recFrames rec)+ uploads <- reverse <$> readIORef (recUploads rec)+ backing <- readIORef (recBacking rec)+ titles <- readIORef (recTitle rec)+ check failed "opening: drawing buffer sized to the canvas" (backing == [(800, 600)])+ check failed "opening: title set" (titles == ["nano-ui"])+ case frames of+ f : _ -> do+ check failed "opening: first frame clears" (frClear f)+ check failed "opening: first frame draws" (not (null (frDraws f)))+ check failed "opening: draws stay inside the indices" (all (\(_, first, n, _) -> first >= 0 && first + n <= frIndexCount f) (frDraws f))+ check failed "opening: draws use glyph pages, the image atlas or no texture" (all (\(s, _, _, _) -> s >= -1 && s <= 4) (frDraws f))+ check failed "opening: text draws from glyph page 0" (any (\(s, _, _, _) -> s == 0) (frDraws f))+ [] -> check failed "opening: a frame was drawn" False+ let page0 = filter ((== 0) . upSlot) uploads+ check failed "opening: glyph page 0 uploaded at 2048" (not (null page0) && all ((== 2048) . upW) page0)+ check failed "opening: glyph page 0 holds rasterised glyphs" (any upInk page0)++-- | A UI font asked for from the view is loaded through the host before the+-- next frame, the debug snapshot names it and the host's renderer, a font+-- that cannot be loaded falls back to Inter, and the host's family list+-- comes back sorted out of repeats.+fontsAndDebug :: IORef Int -> IO ()+fontsAndDebug failed = do+ snaps <- newIORef []+ passes <- newIORef (0 :: Int)+ let view font = column $ do+ n <- liftIO (atomicModifyIORef' passes (\k -> (k + 1, k)))+ if n == 0+ then setSdlWebUiFont font+ else askSdlWebDebug >>= mapM_ (\s -> liftIO (modifyIORef' snaps (s :)))+ label "Fonts"+ script = [events [motion 5 5], events [motion 6 6]]+ rec <- runScript (800, 600, 1) script (viewFrame (view (WebFontUrl "fonts/inter.ttf")))+ asked <- readIORef (recFontsAsked rec)+ check failed "fonts: the fallback at start, then the URL, through the host" (asked == ["fonts/inter.ttf", "fonts/inter-extended.ttf"])+ readIORef snaps >>= \case+ s : _ -> do+ check failed ("fonts: the snapshot names the loaded font (" <> dbgFont s <> ")") (dbgFont s == "fonts/inter.ttf")+ check failed "fonts: the snapshot names the host's renderer" (dbgRenderer s == "WebGL2, Scripted")+ check failed "fonts: the snapshot has the canvas size" (dbgWinW (dbgCore s) == 800 && dbgWinH (dbgCore s) == 600)+ [] -> check failed "fonts: askSdlWebDebug answers in a session" False+ writeIORef snaps [] >> writeIORef passes 0+ _ <- runScript (800, 600, 1) script (viewFrame (view (WebFontInstalled "Missing Sans")))+ readIORef snaps >>= \case+ s : _ -> check failed ("fonts: a missing family falls back to Inter (" <> dbgFont s <> ")") (dbgFont s == fontInterLabel)+ [] -> check failed "fonts: askSdlWebDebug answers after a failed load" False+ (host, _) <- newIORef (800, 600, 1) >>= \c -> scriptedHost c []+ families <- findFontFamilies host+ check failed "fonts: the family list drops repeats" (families == Right ["Inter", "Noto Sans"])+ outside <- listWebFontFamilies+ check failed "fonts: listing needs a browser" (either (const True) (const False) outside)++-- | A search by name skips a family the host cannot load and takes the next,+-- with the service named first; the view's family list comes from the host+-- once it starts discovery, and a change to it runs the view again.+fontSearch :: IORef Int -> IO ()+fontSearch failed = do+ listed <- newIORef []+ let opts = defaultSdlWebOptions {webFont = WebFontSearch ["Missing Sans", "Noto Sans"], webFontService = Just Fontsource}+ view = column $ do+ families <- webFontFamilies+ font <- maybe "" dbgFont <$> askSdlWebDebug+ liftIO (modifyIORef' listed ((families, font) :))+ label "Search"+ canvas <- newIORef (800, 600, 1)+ (host, rec) <- scriptedHost canvas [events [motion 5 5], events [motion 6 6]]+ runWebSession host opts (viewFrame view) `catch` \ScriptDone -> pure ()+ asked <- reverse <$> readIORef (recFontsAsked rec)+ check failed "search: the missing family, then the next" (take 2 asked == ["Missing Sans", "Noto Sans"])+ started <- reverse <$> readIORef (recDiscovery rec)+ check failed "search: discovery starts with Fontsource named" (take 1 started == [1])+ seen <- reverse <$> readIORef listed+ check failed "search: the view gets the host's families" (any ((== ["Inter", "Noto Sans"]) . fst) seen)+ check failed "search: the UI font is the family found" (any ((== "Noto Sans") . snd) seen)++-- | A face gets the fallback attached for a character it lacks that the+-- fallback has (the ellipsis, which the bundled ASCII Inter lacks), and none+-- for ASCII or for a character neither has.+fallbackFonts :: IORef Int -> IO ()+fallbackFonts failed = do+ extended <- BS.readFile extendedFontPath+ fallbacks <- newWebFallbacks [extended]+ let hooks = webFontHooks fallbacks+ Ttf.withTtf hooks $ do+ let face = openFontBytes fontInterBytes 16 >>= readSdlFont 16+ attachedFor txt = do+ sf <- face+ fhEnsureCoverage hooks sf txt+ IM.size <$> readIORef (sfFallbacks sf) <* closeFont sf+ ascii <- attachedFor "Open File..."+ check failed "fallback: none for ASCII" (ascii == 0)+ ellipsis <- attachedFor "Open File\8230"+ check failed "fallback: attached for the ellipsis" (ellipsis == 1)+ accents <- attachedFor "caf\233 \945\946\947 \1046"+ check failed "fallback: one attachment covers accents, Greek and Cyrillic" (accents == 1)+ han <- attachedFor "\20013"+ check failed "fallback: none for a character neither font has" (han == 0)++-- | The file chooser's files come back decoded with UTF-8 names, the+-- filters reach the page as lines, a cancel is 'Nothing', saving hands the+-- page the name and bytes, and outside a browser nothing opens.+fileDialogs :: IORef Int -> IO ()+fileDialogs failed = do+ (host, rec) <- newIORef (800, 600, 1) >>= \c -> scriptedHost c []+ let opts = defaultFileDialogOptions {dialogFilters = [FileFilter "Text" "txt;md"], dialogAllowMany = True}+ files <- pickFiles host PickFiles opts+ check failed "files: both files, in order, with their bytes"+ (files == Just [WebFile "notes.txt" "hello", WebFile "d/\233.bin" "\0\1\2"])+ filters <- readIORef (recFilters rec)+ check failed "files: filters reach the page as name, tab, extensions" (filters == ["Text\ttxt;md"])+ folder <- pickFiles host PickFolder defaultFileDialogOptions+ check failed "files: a cancelled chooser is Nothing" (folder == Nothing)+ saved <- saveFile host opts "out.txt" "bytes"+ check failed "files: saving answers the name saved under" (saved == Just "out.txt")+ readIORef (recSaved rec) >>= check failed "files: the page gets the name and bytes" . (== [("out.txt", "bytes")])+ check failed "files: a truncated record ends the list" (decodePicked (BS.take 10 testPicked) == [])+ outside <- openWebFiles opts+ check failed "files: nothing opens outside a browser" (outside == Nothing)++clickFrame :: IORef Int -> IO ()+clickFrame failed = do+ clicks <- newIORef (0 :: Int)+ let view = column $ do+ clicked <- button "Press"+ when clicked (liftIO (modifyIORef' clicks (+ 1)))+ -- The button sits at the window's top-left; a press and release over it+ -- is one click.+ rec <- runScript (800, 600, 1) [events [motion 20 15], events [press], events [release]] (viewFrame view)+ n <- readIORef clicks+ frames <- reverse <$> readIORef (recFrames rec)+ cursors <- readIORef (recCursor rec)+ check failed "click: one click" (n == 1)+ check failed "click: later frames paint their damage only" (any (not . frClear) (drop 1 frames))+ check failed "click: partial frames are scissored" (all (\f -> frClear f || all (\(_, _, _, s) -> s /= Nothing) (frDraws f)) frames)+ check failed "click: the button sets a CSS cursor" (any (`elem` ["pointer", "default"]) cursors)++-- | A composition longer than the 256 records the session reads at a time+-- arrives whole, though its characters run on into the next batch.+longComposition :: IORef Int -> IO ()+longComposition failed = do+ seen <- newIORef []+ let txt = take 300 (cycle ['\x3042' .. '\x3093'])+ composition = (8, length txt, 2, 1, 0, 0, 0, 0) : [(9, fromEnum ch, 0, 0, 0, 0, 0, 0) | ch <- txt]+ view = do+ inp <- askInput+ liftIO (modifyIORef' seen (inputComposition inp :))+ label "Composing"+ _ <- runScript (800, 600, 1) [events (composition ++ [motion 5 5])] (viewFrame view)+ got <- readIORef seen+ check failed "composition: one longer than a batch arrives whole" (Just (Composition (T.pack txt) 2 1) `elem` got)++pixelRatioChange :: IORef Int -> IO ()+pixelRatioChange failed = do+ -- The second step moves the canvas to a pixel ratio of 2, as a browser+ -- zoom or a move to another display does.+ rec <- runScript (800, 600, 1) [events [motion 5 5], (Just (800, 600, 2), [resize])] (viewFrame (label "Scaled"))+ frames <- reverse <$> readIORef (recFrames rec)+ backing <- reverse <$> readIORef (recBacking rec)+ uploads <- readIORef (recUploads rec)+ let scaled = dropWhile ((/= 2) . frScale) frames+ check failed "ratio: drawing buffer resized to device pixels" (backing == [(800, 600), (1600, 1200)])+ check failed "ratio: the first frame at scale 2 clears and draws" (case scaled of f : _ -> frClear f && not (null (frDraws f)); [] -> False)+ check failed "ratio: glyph page 0 uploaded again for the new size" (length (filter ((== 0) . upSlot) uploads) >= 2)++shaderSession :: IORef Int -> IO ()+shaderSession failed = do+ let es300 = "#version 300 es\nprecision highp float;\nout vec4 outColor;\nvoid main() { outColor = vec4(1.0); }\n"+ es300Eff = "#version 300 es\nprecision highp float;\nuniform sampler2D uInput;\nin vec2 vUv;\nout vec4 outColor;\nvoid main() { outColor = texture(uInput, vUv); }\n"+ sh :: Shader 'Surface Float+ sh = rawShader emptyShaderProgram {spGlslEs300 = Just es300}+ eff :: Shader 'LayerEffect Float+ eff = rawLayerShader (const (V2 8 8)) emptyShaderProgram {spGlslEs300 = Just es300Eff, spNeedsTex = True}+ view = column $ do+ label "Shader"+ shaderBox (fixedWH 80 40) sh 0.5+ withShader eff 1.0 (box (fixedWH 60 30) (colorRGB 200 50 50))+ rec <- runScript (800, 600, 1) [events [motion 10 10]] (viewFrame view)+ shaders <- reverse <$> readIORef (recShaders rec)+ uniforms <- readIORef (recUniforms rec)+ frames <- reverse <$> readIORef (recFrames rec)+ targets <- reverse <$> readIORef (recTargets rec)+ composites <- reverse <$> readIORef (recComposites rec)+ check failed "shaders: surface + layer GLSL ES 300 programs registered" (length shaders == 2)+ check failed "shaders: uniform bytes uploaded" (not (null uniforms) && all ((>= 64) . BS.length) uniforms)+ check failed "shaders: draw command references surface shader slot"+ (any (any (\(s, _, l) -> s > 0 && l == 64) . frShaderDraws) frames)+ let acquires = [slot | ("acquire", slot) <- targets]+ releases = [slot | ("release", slot) <- targets]+ check failed "shaders: Tier 2 acquires and balances offscreen targets"+ (not (null acquires) && length acquires == length releases)+ check failed "shaders: Tier 2 composites offscreen target through effect shader"+ (any (\(_, shSlot, blendCopy, uLen) -> shSlot > 0 && not blendCopy && uLen == 64) composites)
+ web/favicon.svg view
@@ -0,0 +1,18 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">+ <defs>+ <clipPath id="nano-ui-eye"><path d="M7.5 34.5C13.5 18.8 25.2 15.6 38.8 18.0C47.2 19.5 53.2 23.8 57.2 29.8C51.6 44.8 41.6 51.2 30.2 51.2C19.2 51.2 11.4 44.8 7.5 34.5Z"/></clipPath>+ <clipPath id="nano-ui-sq"><path d="M20 3H44C56.2 3 61 7.8 61 20V44C61 56.2 56.2 61 44 61H20C7.8 61 3 56.2 3 44V20C3 7.8 7.8 3 20 3Z"/></clipPath>+ <linearGradient id="nano-ui-rim" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0%" stop-color="#ffffff" stop-opacity="0.18"/>+ <stop offset="55%" stop-color="#ffffff" stop-opacity="0.06"/>+ <stop offset="100%" stop-color="#ffffff" stop-opacity="0.08"/>+ </linearGradient>+ </defs>+ <path d="M20 3H44C56.2 3 61 7.8 61 20V44C61 56.2 56.2 61 44 61H20C7.8 61 3 56.2 3 44V20C3 7.8 7.8 3 20 3Z" fill="#6150a5"/>+ <path d="M20 3H44C56.2 3 61 7.8 61 20V44C61 56.2 56.2 61 44 61H20C7.8 61 3 56.2 3 44V20C3 7.8 7.8 3 20 3Z" fill="none" stroke="url(#nano-ui-rim)" stroke-width="2" clip-path="url(#nano-ui-sq)"/>+ <path d="M7.5 34.5C13.5 18.8 25.2 15.6 38.8 18.0C47.2 19.5 53.2 23.8 57.2 29.8C51.6 44.8 41.6 51.2 30.2 51.2C19.2 51.2 11.4 44.8 7.5 34.5Z" fill="#f4f4f2"/>+ <g clip-path="url(#nano-ui-eye)">+ <path d="M36.2 21A15.6 15.6 0 1 0 36.2 52.2A15.6 15.6 0 1 0 36.2 21Z" fill="#16141f"/>+ <path d="M28.44 29.61C28.73 29.32 29.54 28.38 30.18 27.85C30.83 27.33 31.55 26.83 32.31 26.46C33.08 26.09 33.93 25.79 34.78 25.63C35.63 25.46 36.54 25.41 37.41 25.48C38.28 25.56 39.18 25.77 40 26.08C40.81 26.4 41.59 26.87 42.29 27.39C42.98 27.9 43.62 28.53 44.16 29.19C44.7 29.85 45.17 30.58 45.54 31.33C45.9 32.08 46.18 32.89 46.36 33.68C46.54 34.48 46.63 35.31 46.62 36.11C46.61 36.91 46.5 37.72 46.31 38.48C46.12 39.24 45.83 39.98 45.48 40.66C45.12 41.34 44.68 41.98 44.19 42.54C43.7 43.11 43.13 43.62 42.54 44.04C41.94 44.46 41.29 44.82 40.63 45.08C39.97 45.35 39.26 45.53 38.58 45.63C37.89 45.73 37.18 45.74 36.5 45.68C35.83 45.61 35.15 45.46 34.53 45.24C33.9 45.03 33.3 44.73 32.75 44.37C32.21 44.02 31.71 43.6 31.27 43.14C30.84 42.68 30.46 42.16 30.15 41.62C29.85 41.09 29.61 40.5 29.44 39.92C29.28 39.34 29.18 38.73 29.16 38.15C29.14 37.56 29.19 36.96 29.31 36.39C29.42 35.83 29.61 35.27 29.85 34.76C30.09 34.25 30.4 33.76 30.75 33.33C31.09 32.91 31.5 32.52 31.93 32.19C32.35 31.86 32.83 31.58 33.3 31.37C33.78 31.16 34.3 31 34.8 30.91C35.3 30.81 35.82 30.78 36.32 30.81C36.82 30.83 37.32 30.92 37.78 31.06C38.25 31.2 38.89 31.53 39.11 31.63A1.43 1.43 0 0 1 38.04 34.27L38.04 34.27C37.93 34.22 37.6 34.02 37.35 33.93C37.11 33.85 36.84 33.78 36.57 33.75C36.31 33.73 36.02 33.73 35.75 33.76C35.47 33.8 35.18 33.87 34.92 33.97C34.65 34.08 34.38 34.22 34.14 34.38C33.89 34.55 33.66 34.76 33.45 34.98C33.25 35.21 33.07 35.47 32.92 35.75C32.77 36.03 32.65 36.34 32.57 36.65C32.5 36.96 32.45 37.3 32.45 37.63C32.45 37.96 32.49 38.31 32.57 38.64C32.65 38.97 32.77 39.3 32.94 39.61C33.1 39.92 33.31 40.23 33.55 40.5C33.79 40.77 34.07 41.02 34.38 41.23C34.69 41.44 35.03 41.62 35.39 41.75C35.75 41.89 36.14 41.98 36.53 42.03C36.92 42.07 37.34 42.08 37.74 42.02C38.15 41.97 38.56 41.87 38.96 41.72C39.35 41.57 39.74 41.37 40.1 41.12C40.45 40.87 40.8 40.57 41.1 40.24C41.39 39.91 41.67 39.52 41.88 39.12C42.1 38.71 42.28 38.26 42.4 37.8C42.52 37.34 42.6 36.85 42.61 36.36C42.62 35.88 42.57 35.37 42.47 34.88C42.37 34.39 42.2 33.89 41.98 33.42C41.76 32.96 41.48 32.5 41.15 32.09C40.82 31.68 40.43 31.29 40.01 30.95C39.59 30.61 39.11 30.32 38.62 30.05C38.12 29.77 37.59 29.52 37.03 29.32C36.46 29.12 35.85 28.94 35.21 28.84C34.57 28.74 33.88 28.68 33.19 28.71C32.49 28.75 31.74 28.85 31.03 29.07C30.31 29.3 29.26 29.88 28.91 30.04Z" fill="#ffffff"/>+ </g>+</svg>
+ web/fonts/inter-extended.ttf view
binary file changed (absent → 154248 bytes)
+ web/index.html view
@@ -0,0 +1,28 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <title>nano-ui</title>+ <link rel="icon" type="image/svg+xml" href="favicon.svg">+ <!-- Preload main.wasm and JS modules immediately instead of waiting for+ main.js to finish parsing its import chain. -->+ <link rel="preload" href="main.wasm" as="fetch" type="application/wasm" crossorigin>+ <link rel="modulepreload" href="main.js">+ <link rel="modulepreload" href="ghc_wasm_jsffi.js">+ <link rel="modulepreload" href="browser_wasi_shim/index.js">+ <style>+ html, body { margin: 0; height: 100%; overflow: hidden; background: #1d1f21; }+ canvas { display: block; width: 100vw; height: 100vh; }+ </style>+</head>+<body>+ <canvas id="nano-ui"></canvas>+ <script src="nano-ui-sdl-web.js"></script>+ <script type="module">+ import { start } from "./main.js";+ start(document.getElementById("nano-ui"), "main.wasm", { rtsFlags: "-T" })+ .catch((e) => { console.error(e); document.body.textContent = String(e); });+ </script>+</body>+</html>
+ web/main.js view
@@ -0,0 +1,34 @@+// Load a nano-ui-sdl-web program: the wasm module scripts/build-web.sh+// links, the JSFFI glue GHC's post-link.mjs generates for it, and the WASI+// shim, all served beside this file. The page's canvas is passed to the+// runtime in nano-ui-sdl-web.js before the program starts.+import { WASI, OpenFile, File, ConsoleStdout } from "./browser_wasi_shim/index.js";+import ghcWasmJsffi from "./ghc_wasm_jsffi.js";++// rtsFlags are GHC runtime options, read through GHCRTS as a reactor module+// takes no command line: "-T" keeps the statistics askSdlWebDebug's runtime+// rows show. env is more of the program's environment, as { NAME: "value" }:+// what the page has to tell the program before it starts, which the program+// reads with System.Environment.lookupEnv.+export async function start(canvas, wasmUrl, { rtsFlags = "", env = {} } = {}) {+ globalThis.nanoUiSdlWeb.setup(canvas);+ const fds = [+ new OpenFile(new File([])),+ ConsoleStdout.lineBuffered((msg) => console.log(msg)),+ ConsoleStdout.lineBuffered((msg) => console.warn(msg)),+ ];+ const environment = Object.entries(env).map(([name, value]) => `${name}=${value}`);+ if (rtsFlags) environment.push(`GHCRTS=${rtsFlags}`);+ const wasi = new WASI([], environment, fds);+ // The glue reads the instance's exports, which exist only once it is+ // instantiated; it is handed the object they are copied into.+ const exports = {};+ const { instance } = await WebAssembly.instantiateStreaming(fetch(wasmUrl), {+ wasi_snapshot_preview1: wasi.wasiImport,+ ghc_wasm_jsffi: ghcWasmJsffi(exports),+ });+ Object.assign(exports, instance.exports);+ wasi.initialize(instance);+ instance.exports.hs_init(0, 0);+ await instance.exports.nanoMain();+}
+ web/nano-ui-sdl-web.js view
@@ -0,0 +1,1131 @@+// The page's side of nano-ui-sdl-web: the canvas, its WebGL2 renderer, the+// event queue the Haskell session reads, and the text input element.+// NanoUI.SdlWeb.Internal.Host lists the calls; NanoUI.SdlWeb.Internal.Input+// documents the event records. Load this before the wasm module and call+// nanoUiSdlWeb.setup(canvas).++const EVENT_WORDS = 8; // eventRecordSize / 4++// A timed wait this short paces an animation (two frames at 60 Hz), and+// ends on one of the display's frames. FRAME_SLACK_MS is how far before its+// time such a wait may end: the session measures a frame from its own start,+// a little after the display's, so the frame it is waiting for comes a+// little early.+const FRAME_WAIT_MS = 34;+const FRAME_SLACK_MS = 4;+const COMMAND_WORDS = 12; // commandRecordSize / 4++const EV_RESIZE = 1;+const EV_MOTION = 2;+const EV_BUTTON = 3;+const EV_LEAVE = 4;+const EV_SCROLL = 5;+const EV_KEY = 6;+const EV_CHAR = 7;+const EV_COMPOSITION = 8;+const EV_COMPOSITION_CHAR = 9;+const EV_FOCUS_LOST = 10;+const EV_REDRAW = 11;++// Named keys, numbered as decodeKey in NanoUI.SdlWeb.Internal.Input reads+// them: -1 to -21 in the order of Key from KeyBackspace to KeyMenu.+const NAMED_KEYS = {+ Backspace: -1, Delete: -2, Enter: -3, NumpadEnter: -3, Escape: -4, Tab: -5,+ ArrowLeft: -6, ArrowRight: -7, ArrowUp: -8, ArrowDown: -9, Home: -10, End: -11,+ PageUp: -12, PageDown: -13, Insert: -14, Space: -15, PrintScreen: -16, Pause: -17,+ CapsLock: -18, NumLock: -19, ScrollLock: -20, ContextMenu: -21,+};++// Keys that type a character on a US layout, by KeyboardEvent.code: the+// key's character when the layout's own cannot be read (a chord changed it).+const US_KEYS = {+ Backquote: "`", Minus: "-", Equal: "=", BracketLeft: "[", BracketRight: "]",+ Backslash: "\\", Semicolon: ";", Quote: "'", Comma: ",", Period: ".", Slash: "/",+ IntlBackslash: "\\", NumpadDivide: "/", NumpadMultiply: "*", NumpadSubtract: "-",+ NumpadAdd: "+", NumpadEqual: "=",+};++const MODIFIER_CODES = new Set([+ "ShiftLeft", "ShiftRight", "ControlLeft", "ControlRight", "AltLeft", "AltRight",+ "MetaLeft", "MetaRight", "OSLeft", "OSRight",+]);++const VERTEX_SHADER = `#version 300 es+in vec2 aPos;+in vec4 aColor;+in vec2 aUv;+uniform vec2 uScale;+uniform vec2 uOrigin;+out vec4 vColor;+out vec2 vUv;+void main() {+ vec2 p = aPos - uOrigin;+ gl_Position = vec4(p.x * uScale.x - 1.0, 1.0 - p.y * uScale.y, 0.0, 1.0);+ vColor = aColor;+ vUv = aUv;+}`;++const FRAGMENT_SHADER = `#version 300 es+precision mediump float;+in vec4 vColor;+in vec2 vUv;+uniform sampler2D uTex;+out vec4 outColor;+void main() {+ outColor = texture(uTex, vUv) * vColor;+}`;++class NanoUiSdlWeb {+ constructor() {+ this.memory = null;+ this.canvas = null;+ this.gl = null;+ this.queue = [];+ this.waiter = null;+ this.waitTimer = null;+ this.waitFrame = null;+ this.shown = true;+ this.held = false;+ this.wakePending = false;+ this.settleTimer = null;+ this.clipboard = null;+ this.focused = false;+ this.colorScheme = null;+ this.composing = false;+ this.textInputOn = false;+ this.scale = 1;+ this.backing = [1, 1];+ this.curSize = [1, 1];+ this.originX = 0;+ this.originY = 0;+ this.uScaleX = 1;+ this.uScaleY = 1;+ this.textures = [];+ this.textureSizes = [];+ this.shaders = new Map();+ this.targets = [];+ this.uniformData = new Uint8Array(0);+ this.encoder = new TextEncoder();+ this.decoder = new TextDecoder();+ this.localFonts = null;+ this.installedFamilies = [];+ this.serviceFamilies = [];+ this.fontService = 0;+ this.fontsVersion = 0;+ this.discovering = false;+ this.fontList = new Uint8Array(0);+ this.fontBytes = new Uint8Array(0);+ this.picked = new Uint8Array(0);+ }++ // ---------------------------------------------------------------- setup++ setup(canvas) {+ this.canvas = canvas;+ canvas.tabIndex = -1;+ // Every touch goes to the program unless the page's inline style says+ // otherwise: "pan-y" on a canvas in a scrolling page lets a vertical+ // swipe scroll the page (see pointercancel in listenPointer).+ if (!canvas.style.touchAction) canvas.style.touchAction = "none";+ canvas.style.outline = "none";+ this.input = this.makeTextInput();+ this.initGl();+ canvas.addEventListener("webglcontextlost", (e) => e.preventDefault());+ canvas.addEventListener("webglcontextrestored", () => {+ this.initGl();+ this.push(EV_REDRAW);+ });+ this.listenPointer(canvas);+ this.listenKeys(this.input);+ this.pinCssSize(canvas);+ // Only a change of the CSS box is a resize: the session sets the+ // drawing buffer from it, and must not hear back from its own change.+ let box = [canvas.clientWidth, canvas.clientHeight];+ new ResizeObserver(() => {+ const now = [canvas.clientWidth, canvas.clientHeight];+ if (now[0] === box[0] && now[1] === box[1]) return;+ box = now;+ this.push(EV_RESIZE);+ }).observe(canvas);+ this.watchPixelRatio();+ // A canvas scrolled out of the viewport shows nothing, so its timed+ // waits are held (waitEvents) and one frame is drawn when it is back.+ new IntersectionObserver((entries) => {+ this.shown = entries[entries.length - 1].isIntersecting;+ if (this.shown && this.held) this.release();+ }).observe(canvas);+ const scheme = window.matchMedia("(prefers-color-scheme: dark)");+ scheme.addEventListener("change", () => this.push(EV_RESIZE));+ this.focusInput();+ }++ // The session sizes the drawing buffer from the canvas's CSS box, times+ // devicePixelRatio. A canvas the page gives no CSS width or height takes+ // its box from the drawing buffer, so each resize would grow the next+ // (doubling at a ratio of 2). An axis whose box follows the buffer is+ // fixed at the size it has now.+ pinCssSize(canvas) {+ const [w, h] = [canvas.width, canvas.height];+ const [cw, ch] = [canvas.clientWidth, canvas.clientHeight];+ canvas.width = w + 16;+ canvas.height = h + 16;+ const followsW = canvas.clientWidth !== cw;+ const followsH = canvas.clientHeight !== ch;+ canvas.width = w;+ canvas.height = h;+ if (followsW) canvas.style.width = `${cw}px`;+ if (followsH) canvas.style.height = `${ch}px`;+ }++ // The element keys and text go through. A textarea receives typed text,+ // input method compositions and pastes; it sits over the caret while text+ // input is on, so the input method's window opens there.+ makeTextInput() {+ const ta = document.createElement("textarea");+ ta.setAttribute("autocomplete", "off");+ ta.setAttribute("autocorrect", "off");+ ta.setAttribute("autocapitalize", "off");+ ta.setAttribute("spellcheck", "false");+ ta.setAttribute("aria-hidden", "true");+ Object.assign(ta.style, {+ position: "fixed", left: "0px", top: "0px", width: "1px", height: "1px",+ opacity: "0", border: "0", padding: "0", margin: "0", resize: "none",+ overflow: "hidden", whiteSpace: "pre", pointerEvents: "none", zIndex: "-1",+ });+ ta.inputMode = "none";+ document.body.appendChild(ta);+ ta.addEventListener("focus", () => { this.focused = true; this.push(EV_RESIZE); });+ ta.addEventListener("blur", () => { this.focused = false; this.push(EV_FOCUS_LOST); });+ return ta;+ }++ focusInput() {+ if (document.activeElement !== this.input) this.input.focus({ preventScroll: true });+ }++ linkProgram(fragSrc, logErrors) {+ const gl = this.gl;+ const compile = (type, src, label) => {+ const sh = gl.createShader(type);+ gl.shaderSource(sh, src);+ gl.compileShader(sh);+ if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {+ const msg = gl.getShaderInfoLog(sh);+ gl.deleteShader(sh);+ if (logErrors) { console.error(`nano-ui-sdl-web: ${label} shader compile failed:`, msg); return null; }+ throw new Error(msg);+ }+ return sh;+ };+ const vs = compile(gl.VERTEX_SHADER, VERTEX_SHADER, "vertex");+ if (!vs) return null;+ const fs = compile(gl.FRAGMENT_SHADER, fragSrc, "fragment");+ if (!fs) { gl.deleteShader(vs); return null; }+ const program = gl.createProgram();+ gl.attachShader(program, vs);+ gl.attachShader(program, fs);+ // Pin attribute locations 0/1/2 so custom fragment shader programs share the same VAO.+ gl.bindAttribLocation(program, 0, "aPos");+ gl.bindAttribLocation(program, 1, "aColor");+ gl.bindAttribLocation(program, 2, "aUv");+ gl.linkProgram(program);+ gl.deleteShader(vs);+ gl.deleteShader(fs);+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {+ const msg = gl.getProgramInfoLog(program);+ gl.deleteProgram(program);+ if (logErrors) { console.error("nano-ui-sdl-web: shader link failed:", msg); return null; }+ throw new Error(msg);+ }+ return program;+ }++ useDefaultProgram() {+ const gl = this.gl;+ gl.useProgram(this.defaultProgram);+ gl.uniform2f(this.uScale, this.uScaleX, this.uScaleY);+ gl.uniform2f(this.uOrigin, this.originX, this.originY);+ }++ bindUniformBlock(bytes) {+ const gl = this.gl;+ gl.bindBuffer(gl.UNIFORM_BUFFER, this.shaderUbo);+ gl.bufferData(gl.UNIFORM_BUFFER, bytes, gl.STREAM_DRAW);+ gl.bindBufferBase(gl.UNIFORM_BUFFER, 0, this.shaderUbo);+ }++ initGl() {+ const gl = this.canvas.getContext("webgl2", {+ alpha: false, antialias: false, depth: false, stencil: false,+ premultipliedAlpha: false, preserveDrawingBuffer: true,+ });+ if (!gl) throw new Error("nano-ui-sdl-web: WebGL2 is not available");+ this.gl = gl;+ const program = this.linkProgram(FRAGMENT_SHADER, false);+ this.defaultProgram = program;+ gl.useProgram(program);+ this.uScale = gl.getUniformLocation(program, "uScale");+ this.uOrigin = gl.getUniformLocation(program, "uOrigin");+ gl.uniform1i(gl.getUniformLocation(program, "uTex"), 0);+ this.vertexBuffer = gl.createBuffer();+ this.indexBuffer = gl.createBuffer();+ this.shaderUbo = gl.createBuffer();+ const vao = gl.createVertexArray();+ this.vao = vao;+ gl.bindVertexArray(vao);+ gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);+ // A vertex is 32 bytes: position, colour (0 to 1) and UV, as floats.+ // The stride is the core's vertexSize (NanoUI.Internal.Draw.Types) and+ // NANO_UI_VERTEX_BYTES in nano-ui-ttf's nano_ui_ttf_shared.h; JavaScript+ // cannot read either, so nano-ui-sdl-web-test checks only that those two+ // agree. Change all three together.+ const attrs = [[0, 2, 0], [1, 4, 8], [2, 2, 24]];+ const setupAttrs = () => {+ for (const [loc, size, offset] of attrs) {+ gl.enableVertexAttribArray(loc);+ gl.vertexAttribPointer(loc, size, gl.FLOAT, false, 32, offset);+ }+ };+ setupAttrs();+ this.effectVbo = gl.createBuffer();+ this.effectVao = gl.createVertexArray();+ gl.bindVertexArray(this.effectVao);+ gl.bindBuffer(gl.ARRAY_BUFFER, this.effectVbo);+ setupAttrs();+ gl.bindVertexArray(this.vao);+ // SDL_BLENDMODE_BLEND: colour by source alpha, alpha accumulating.+ gl.enable(gl.BLEND);+ gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);+ gl.activeTexture(gl.TEXTURE0);+ this.white = this.makeTexture(1, 1, new Uint8Array([255, 255, 255, 255]));+ this.textures = [];+ this.textureSizes = [];+ this.shaders = new Map();+ this.targets = [];+ this.uniformData = new Uint8Array(0);+ this.geometryUploaded = false;+ }++ makeTexture(w, h, pixels) {+ const gl = this.gl;+ const tex = gl.createTexture();+ gl.bindTexture(gl.TEXTURE_2D, tex);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, pixels);+ // Linear filtering, as the SDL backend's atlases use.+ 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);+ return tex;+ }++ // A change of devicePixelRatio (browser zoom, a move to another display)+ // matches no media query for the old ratio; watch the new one each time.+ watchPixelRatio() {+ const query = window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);+ query.addEventListener("change", () => {+ this.push(EV_RESIZE);+ this.watchPixelRatio();+ }, { once: true });+ }++ // ---------------------------------------------------------------- events++ push(kind, a = 0, b = 0, c = 0, mods = 0, x = 0, y = 0, z = 0) {+ this.queue.push([kind, a, b, c, mods, x, y, z]);+ this.settle();+ }++ // Answer a waiting session from a task of its own, after the event's+ // default actions: a paste a Ctrl+V key starts is then already in hand+ // when the session reads the clipboard for that key.+ settle() {+ if (!this.waiter || this.settleTimer !== null) return;+ this.settleTimer = setTimeout(() => {+ this.settleTimer = null;+ this.release();+ }, 0);+ }++ release() {+ const resolve = this.waiter;+ this.waiter = null;+ this.held = false;+ if (this.waitTimer !== null) {+ clearTimeout(this.waitTimer);+ this.waitTimer = null;+ }+ if (this.waitFrame !== null) {+ cancelAnimationFrame(this.waitFrame);+ this.waitFrame = null;+ }+ if (resolve) resolve();+ }++ static mods(e) {+ let m = 0;+ if (e.shiftKey) m |= 1;+ if (e.ctrlKey) m |= 2;+ if (e.altKey) m |= 4;+ if (e.metaKey) m |= 8;+ if (e.getModifierState && e.getModifierState("NumLock")) m |= 16;+ return m;+ }++ pointerPos(e) {+ const r = this.canvas.getBoundingClientRect();+ return [e.clientX - r.left, e.clientY - r.top];+ }++ listenPointer(canvas) {+ canvas.addEventListener("pointermove", (e) => {+ const [x, y] = this.pointerPos(e);+ this.push(EV_MOTION, 0, 0, 0, NanoUiSdlWeb.mods(e), x, y);+ });+ canvas.addEventListener("pointerdown", (e) => {+ e.preventDefault();+ this.focusInput();+ // Capture keeps a drag's motion and release coming from outside.+ canvas.setPointerCapture(e.pointerId);+ const [x, y] = this.pointerPos(e);+ this.push(EV_MOTION, 0, 0, 0, NanoUiSdlWeb.mods(e), x, y);+ this.push(EV_BUTTON, e.button, 1, 0, NanoUiSdlWeb.mods(e));+ });+ canvas.addEventListener("pointerup", (e) => {+ const [x, y] = this.pointerPos(e);+ this.push(EV_MOTION, 0, 0, 0, NanoUiSdlWeb.mods(e), x, y);+ this.push(EV_BUTTON, e.button, 0, 0, NanoUiSdlWeb.mods(e));+ });+ // The browser took the pointer for a gesture of its own, as when a+ // touch on a canvas whose touch-action allows panning starts to scroll+ // the page. No pointerup follows. The button is released here, far from+ // the canvas, so the widget that was pressed gets no click.+ canvas.addEventListener("pointercancel", (e) => {+ this.push(EV_MOTION, 0, 0, 0, NanoUiSdlWeb.mods(e), -1e5, -1e5);+ this.push(EV_BUTTON, Math.max(e.button, 0), 0, 0, NanoUiSdlWeb.mods(e));+ this.push(EV_LEAVE);+ });+ canvas.addEventListener("pointerleave", () => this.push(EV_LEAVE));+ canvas.addEventListener("contextmenu", (e) => e.preventDefault());+ canvas.addEventListener("wheel", (e) => {+ e.preventDefault();+ // Notches, as SDL reports the wheel: a line is a third of one, and a+ // pixel delta a hundredth.+ const unit = e.deltaMode === 1 ? 1 / 3 : e.deltaMode === 2 ? 3 : 1 / 100;+ this.push(EV_SCROLL, 0, 0, 0, NanoUiSdlWeb.mods(e), e.deltaX * unit, e.deltaY * unit);+ }, { passive: false });+ }++ // The key code decodeKey reads: positive for a key that types a+ // character, negative for a named key, 0 for a modifier.+ static keyCode(e) {+ if (MODIFIER_CODES.has(e.code)) return 0;+ if (e.code in NAMED_KEYS) return NAMED_KEYS[e.code];+ const f = /^F(\d+)$/.exec(e.key);+ if (f) return -(100 + Number(f[1]));+ const pad = /^Numpad(\d)$/.exec(e.code);+ if (pad) return -(300 + pad[1].charCodeAt(0));+ if (e.code === "NumpadDecimal") return -(300 + 46);+ // The layout's character, when no chord changed it.+ if ([...e.key].length === 1 && !e.ctrlKey && !e.altKey && !e.metaKey) {+ return e.key.toLowerCase().codePointAt(0);+ }+ const letter = /^Key([A-Z])$/.exec(e.code);+ if (letter) return letter[1].toLowerCase().charCodeAt(0);+ const digit = /^Digit(\d)$/.exec(e.code);+ if (digit) return digit[1].charCodeAt(0);+ if (e.code in US_KEYS) return US_KEYS[e.code].charCodeAt(0);+ return null;+ }++ listenKeys(ta) {+ const key = (e, down) => {+ if (e.isComposing || e.keyCode === 229) return;+ const code = NanoUiSdlWeb.keyCode(e);+ if (code === null) return;+ this.push(EV_KEY, code, down ? 1 : 0, 0, NanoUiSdlWeb.mods(e));+ // Let typing reach the textarea (Space too: it is a named key that+ // also types, as SDL reports it), and Ctrl/Cmd+C, X and V raise their+ // clipboard events; everything else is the view's.+ const chord = e.ctrlKey || e.metaKey;+ const clip = chord && ["KeyC", "KeyX", "KeyV"].includes(e.code);+ const types = e.code === "Space" && !chord && !e.altKey;+ if (down && ((code < 0 && !types) || (chord && !clip))) e.preventDefault();+ };+ ta.addEventListener("keydown", (e) => key(e, true));+ ta.addEventListener("keyup", (e) => key(e, false));+ ta.addEventListener("input", (e) => {+ if (this.composing) return;+ if (e.inputType === "insertText" || e.inputType === "insertReplacementText") {+ this.pushText(e.data || "");+ }+ ta.value = "";+ });+ ta.addEventListener("compositionstart", () => { this.composing = true; });+ ta.addEventListener("compositionupdate", (e) => this.pushComposition(e.data || ""));+ ta.addEventListener("compositionend", (e) => {+ this.composing = false;+ this.pushComposition("");+ this.pushText(e.data || "");+ ta.value = "";+ });+ ta.addEventListener("paste", (e) => {+ e.preventDefault();+ this.clipboard = e.clipboardData ? e.clipboardData.getData("text/plain") : this.clipboard;+ });+ ta.addEventListener("copy", (e) => e.preventDefault());+ ta.addEventListener("cut", (e) => e.preventDefault());+ }++ pushText(text) {+ for (const ch of text) this.push(EV_CHAR, ch.codePointAt(0));+ }++ pushComposition(text) {+ const chars = [...text];+ this.push(EV_COMPOSITION, chars.length, chars.length, 0);+ for (const ch of chars) this.push(EV_COMPOSITION_CHAR, ch.codePointAt(0));+ }++ // ---------------------------------------------------------------- host calls++ attach(memory) {+ this.memory = memory;+ }++ bytes(ptr, len) {+ return new Uint8Array(this.memory.buffer, ptr, len);+ }++ text(ptr, len) {+ return this.decoder.decode(this.bytes(ptr, len).slice());+ }++ setColorScheme(scheme) {+ this.colorScheme = scheme === "dark" || scheme === "light" ? scheme : null;+ if (this.canvas) this.push(EV_RESIZE);+ }++ queryCanvas(ptr) {+ const out = new Float32Array(this.memory.buffer, ptr, 5);+ out[0] = this.canvas.clientWidth;+ out[1] = this.canvas.clientHeight;+ out[2] = window.devicePixelRatio || 1;+ out[3] = this.focused && document.hasFocus() ? 1 : 0;+ if (this.colorScheme === "dark") {+ out[4] = 2;+ } else if (this.colorScheme === "light") {+ out[4] = 1;+ } else {+ const dark = window.matchMedia("(prefers-color-scheme: dark)").matches;+ const light = window.matchMedia("(prefers-color-scheme: light)").matches;+ out[4] = dark ? 2 : light ? 1 : 0;+ }+ }++ takeEvents(ptr, n) {+ const count = Math.min(n, this.queue.length);+ if (count === 0) return 0;+ const ints = new Int32Array(this.memory.buffer, ptr, count * EVENT_WORDS);+ const floats = new Float32Array(this.memory.buffer, ptr, count * EVENT_WORDS);+ for (let i = 0; i < count; i++) {+ const ev = this.queue[i];+ const o = i * EVENT_WORDS;+ for (let k = 0; k < 5; k++) ints[o + k] = ev[k];+ floats[o + 5] = ev[5];+ floats[o + 6] = ev[6];+ floats[o + 7] = ev[7];+ }+ this.queue.splice(0, count);+ return count;+ }++ waitEvents(ms) {+ if (this.queue.length > 0 || this.wakePending) {+ this.wakePending = false;+ return Promise.resolve();+ }+ return new Promise((resolve) => {+ this.waiter = () => {+ this.wakePending = false;+ resolve();+ };+ if (ms < 0) return;+ // Out of view there is no frame to show, so a timed wait holds for an+ // event or for the canvas to come back.+ if (!this.shown) {+ this.held = true;+ return;+ }+ // A longer wait is a timer. A frame's wait ends on the display's+ // first frame at or after its time: a timer's steps are coarser than+ // a frame (15.6 ms on Windows), which drops every other one, and the+ // display's frames stop while the tab is hidden.+ if (ms > FRAME_WAIT_MS) {+ this.waitTimer = setTimeout(() => this.release(), ms);+ return;+ }+ const due = performance.now() + ms - FRAME_SLACK_MS;+ const onFrame = () => {+ this.waitFrame = null;+ if (performance.now() >= due) this.release();+ else this.waitFrame = requestAnimationFrame(onFrame);+ };+ this.waitFrame = requestAnimationFrame(onFrame);+ });+ }++ wake() {+ this.wakePending = true;+ if (this.waiter) this.settle();+ }++ resizeBacking(w, h) {+ this.canvas.width = w;+ this.canvas.height = h;+ this.backing = [w, h];+ }++ uploadTexture(slot, w, h, ptr, rowPixels, x, y, rw, rh) {+ const gl = this.gl;+ const size = this.textureSizes[slot];+ if (!this.textures[slot] || !size || size[0] !== w || size[1] !== h) {+ if (this.textures[slot]) gl.deleteTexture(this.textures[slot]);+ this.textures[slot] = this.makeTexture(w, h, null);+ this.textureSizes[slot] = [w, h];+ }+ gl.bindTexture(gl.TEXTURE_2D, this.textures[slot]);+ gl.pixelStorei(gl.UNPACK_ROW_LENGTH, rowPixels);+ gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, x);+ gl.pixelStorei(gl.UNPACK_SKIP_ROWS, y);+ const source = this.bytes(ptr, rowPixels * 4 * (y + rh));+ gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, rw, rh, gl.RGBA, gl.UNSIGNED_BYTE, source);+ gl.pixelStorei(gl.UNPACK_ROW_LENGTH, 0);+ gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, 0);+ gl.pixelStorei(gl.UNPACK_SKIP_ROWS, 0);+ }++ registerShader(slot, srcPtr, srcLen) {+ const gl = this.gl;+ const program = this.linkProgram(this.text(srcPtr, srcLen), true);+ if (!program) return 0;+ const blk = gl.getUniformBlockIndex(program, "NanoShaderBlock");+ if (blk !== gl.INVALID_INDEX) {+ gl.uniformBlockBinding(program, blk, 0);+ }+ const uScale = gl.getUniformLocation(program, "uScale");+ const uOrigin = gl.getUniformLocation(program, "uOrigin");+ const uInput = gl.getUniformLocation(program, "uInput");+ this.shaders.set(slot, { program, uScale, uOrigin, uInput });+ return 1;+ }++ uploadUniforms(ptr, len) {+ if (len <= 0) {+ this.uniformData = new Uint8Array(0);+ } else {+ this.uniformData = this.bytes(ptr, len).slice();+ }+ }++ acquireTarget(minW, minH, outCapsPtr) {+ const gl = this.gl;+ const needW = minW > 0 ? ((minW + 63) & ~63) : 64;+ const needH = minH > 0 ? ((minH + 63) & ~63) : 64;+ let best = -1;+ for (let i = 0; i < this.targets.length; i++) {+ const s = this.targets[i];+ if (!s.inUse && s.capW >= needW && s.capH >= needH && s.capW <= needW * 2 && s.capH <= needH * 2) {+ best = i;+ break;+ }+ }+ if (best < 0) {+ const tex = this.makeTexture(needW, needH, null);+ const fbo = gl.createFramebuffer();+ gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);+ const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ if (status !== gl.FRAMEBUFFER_COMPLETE) {+ gl.deleteFramebuffer(fbo);+ gl.deleteTexture(tex);+ return -1;+ }+ best = this.targets.length;+ this.targets.push({ fbo, tex, capW: needW, capH: needH, inUse: false });+ }+ const slot = this.targets[best];+ slot.inUse = true;+ const out = new Int32Array(this.memory.buffer, outCapsPtr, 2);+ out[0] = slot.capW;+ out[1] = slot.capH;+ return best;+ }++ releaseTarget(slot) {+ if (slot >= 0 && slot < this.targets.length) {+ this.targets[slot].inUse = false;+ }+ }++ bindTarget(slot, clear, ox, oy) {+ const gl = this.gl;+ if (slot >= 0 && slot < this.targets.length) {+ const s = this.targets[slot];+ gl.bindFramebuffer(gl.FRAMEBUFFER, s.fbo);+ this.curSize = [s.capW, s.capH];+ } else {+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ this.curSize = [this.backing[0], this.backing[1]];+ }+ this.originX = ox;+ this.originY = oy;+ this.uScaleX = (2 * this.scale) / this.curSize[0];+ this.uScaleY = (2 * this.scale) / this.curSize[1];+ gl.viewport(0, 0, this.curSize[0], this.curSize[1]);+ gl.disable(gl.SCISSOR_TEST);+ if (clear) {+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);+ }+ this.useDefaultProgram();+ }++ compositeEffect(srcSlot, shaderSlot, blendCopy, rectUvPtr, scissorPtr, uPtr, uLen) {+ const gl = this.gl;+ if (srcSlot < 0 || srcSlot >= this.targets.length) return;+ const entry = this.shaders.get(shaderSlot);+ if (!entry) return;+ const rv = new Float32Array(this.memory.buffer, rectUvPtr, 8);+ const sc = new Int32Array(this.memory.buffer, scissorPtr, 5);+ const [dx, dy, dw, dh, u0, v0, u1, v1] = rv;+ const quad = new Float32Array([+ dx, dy, 1, 1, 1, 1, u0, v0,+ dx + dw, dy, 1, 1, 1, 1, u1, v0,+ dx + dw, dy + dh, 1, 1, 1, 1, u1, v1,+ dx, dy, 1, 1, 1, 1, u0, v0,+ dx + dw, dy + dh, 1, 1, 1, 1, u1, v1,+ dx, dy + dh, 1, 1, 1, 1, u0, v1,+ ]);+ gl.useProgram(entry.program);+ if (entry.uScale !== null) gl.uniform2f(entry.uScale, 2 / this.curSize[0], 2 / this.curSize[1]);+ if (entry.uOrigin !== null) gl.uniform2f(entry.uOrigin, 0, 0);+ if (entry.uInput !== null) gl.uniform1i(entry.uInput, 0);+ if (uLen > 0) this.bindUniformBlock(this.bytes(uPtr, uLen));+ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, this.targets[srcSlot].tex);+ // Always blend straight-alpha output into premultiplied offscreen targets+ // (cleared to 0,0,0,0) and onto the backbuffer.+ void blendCopy;+ gl.enable(gl.BLEND);+ gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);+ if (sc[0]) {+ gl.enable(gl.SCISSOR_TEST);+ gl.scissor(sc[1], this.curSize[1] - sc[2] - sc[4], sc[3], sc[4]);+ } else {+ gl.disable(gl.SCISSOR_TEST);+ }+ gl.bindVertexArray(this.effectVao);+ gl.bindBuffer(gl.ARRAY_BUFFER, this.effectVbo);+ gl.bufferData(gl.ARRAY_BUFFER, quad, gl.STREAM_DRAW);+ gl.drawArrays(gl.TRIANGLES, 0, 6);++ gl.bindVertexArray(this.vao);+ gl.enable(gl.BLEND);+ gl.disable(gl.SCISSOR_TEST);+ this.useDefaultProgram();+ }++ beginFrame(clear, r, g, b, a, scale, w, h) {+ const gl = this.gl;+ this.scale = scale;+ this.backing = [w, h];+ this.curSize = [w, h];+ this.originX = 0;+ this.originY = 0;+ this.uScaleX = (2 * scale) / w;+ this.uScaleY = (2 * scale) / h;+ this.geometryUploaded = false;+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ gl.viewport(0, 0, w, h);+ this.useDefaultProgram();+ if (clear) {+ gl.disable(gl.SCISSOR_TEST);+ gl.clearColor(r, g, b, a);+ gl.clear(gl.COLOR_BUFFER_BIT);+ }+ }++ draw(vertices, vertexCount, indices, indexCount, commands, commandCount) {+ const gl = this.gl;+ gl.bindVertexArray(this.vao);+ // Upload the frame's shared vertex/index buffers once per frame instead of+ // re-uploading them for every plain command slice around Tier 2 effects.+ if (!this.geometryUploaded) {+ gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);+ gl.bufferData(gl.ARRAY_BUFFER, this.bytes(vertices, vertexCount * 32), gl.STREAM_DRAW);+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);+ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.bytes(indices, indexCount * 4), gl.STREAM_DRAW);+ this.geometryUploaded = true;+ }+ const cmds = new Int32Array(this.memory.buffer, commands, commandCount * COMMAND_WORDS);+ const height = this.curSize[1];+ let activeShader = 0;+ for (let i = 0; i < commandCount; i++) {+ const o = i * COMMAND_WORDS;+ const slot = cmds[o];+ const shaderSlot = cmds[o + 8];+ if (shaderSlot > 0) {+ const entry = this.shaders.get(shaderSlot);+ if (!entry) continue;+ if (activeShader !== shaderSlot) {+ gl.useProgram(entry.program);+ if (entry.uScale !== null) gl.uniform2f(entry.uScale, this.uScaleX, this.uScaleY);+ if (entry.uOrigin !== null) gl.uniform2f(entry.uOrigin, this.originX, this.originY);+ if (entry.uInput !== null) gl.uniform1i(entry.uInput, 0);+ activeShader = shaderSlot;+ }+ const uOff = cmds[o + 9];+ const uLen = cmds[o + 10];+ if (uLen > 0 && uOff + uLen <= this.uniformData.length) {+ this.bindUniformBlock(this.uniformData.subarray(uOff, uOff + uLen));+ }+ } else if (activeShader !== 0) {+ this.useDefaultProgram();+ activeShader = 0;+ }+ gl.bindTexture(gl.TEXTURE_2D, (slot >= 0 && this.textures[slot]) || this.white);+ if (cmds[o + 3]) {+ gl.enable(gl.SCISSOR_TEST);+ // GL's scissor counts rows from the bottom.+ gl.scissor(cmds[o + 4], height - cmds[o + 5] - cmds[o + 7], cmds[o + 6], cmds[o + 7]);+ } else {+ gl.disable(gl.SCISSOR_TEST);+ }+ gl.drawElements(gl.TRIANGLES, cmds[o + 2], gl.UNSIGNED_INT, cmds[o + 1] * 4);+ }+ if (activeShader !== 0) this.useDefaultProgram();+ gl.disable(gl.SCISSOR_TEST);+ }++ setCursor(ptr, len) {+ this.canvas.style.cursor = this.text(ptr, len);+ }++ textInput(purpose, x, y, w, h) {+ const ta = this.input;+ this.textInputOn = purpose >= 0;+ ta.inputMode = purpose < 0 ? "none" : purpose === 2 ? "decimal" : "text";+ const r = this.canvas.getBoundingClientRect();+ Object.assign(ta.style, {+ left: `${r.left + x}px`, top: `${r.top + y}px`,+ width: `${Math.max(1, w)}px`, height: `${Math.max(1, h)}px`,+ });+ }++ clipboardRead(ptr, n) {+ if (this.clipboard === null) return -1;+ const encoded = this.encoder.encode(this.clipboard);+ if (n > 0) this.bytes(ptr, Math.min(n, encoded.length)).set(encoded.subarray(0, n));+ return encoded.length;+ }++ clipboardWrite(ptr, len) {+ const text = this.text(ptr, len);+ this.clipboard = text;+ if (navigator.clipboard) navigator.clipboard.writeText(text).catch(() => {});+ }++ setTitle(ptr, len) {+ document.title = this.text(ptr, len);+ }++ // Copy up to n bytes of encoded text to ptr; answer its full length.+ writeText(text, ptr, n) {+ const encoded = this.encoder.encode(text);+ if (n > 0) this.bytes(ptr, Math.min(n, encoded.length)).set(encoded.subarray(0, n));+ return encoded.length;+ }++ // The WebGL renderer's name: the unmasked one where the browser gives it.+ rendererInfo(ptr, n) {+ const gl = this.gl;+ let name = gl.getParameter(gl.RENDERER);+ const info = gl.getExtension("WEBGL_debug_renderer_info");+ if (info) name = gl.getParameter(info.UNMASKED_RENDERER_WEBGL) || name;+ return this.writeText(`WebGL2, ${name}`, ptr, n);+ }++ // ---------------------------------------------------------------- fonts++ // Font families come from two places. Installed ones, through the Local+ // Font Access API (Chromium-based browsers): once the user has allowed it+ // they are read at once; while the browser has not asked yet, the request+ // waits for the next press on the page, the only moment a browser shows+ // the question. And a font service's catalogue (1: Fontsource), in every+ // browser. Each arrival bumps fontsVersion and wakes the session, which+ // reads the merged list with fontFamilies.+ startFontDiscovery(service) {+ if (this.discovering) return;+ this.discovering = true;+ this.fontService = service;+ if (service === 1) {+ fetch("https://api.fontsource.org/v1/fonts")+ .then((r) => (r.ok ? r.json() : []))+ .then((fonts) => {+ this.serviceFamilies = fonts.map((f) => f.family);+ this.fontsChanged();+ })+ .catch((e) => console.warn("nano-ui-sdl-web: the font service's list is not available:", e));+ }+ if (typeof window.queryLocalFonts !== "function" || !navigator.permissions) return;+ navigator.permissions.query({ name: "local-fonts" }).then((status) => {+ if (status.state === "granted") {+ this.readInstalled();+ } else if (status.state === "prompt") {+ // The next press asks; its own effect on the page goes on as usual.+ const ask = () => {+ this.canvas.removeEventListener("pointerdown", ask, true);+ this.input.removeEventListener("keydown", ask, true);+ this.readInstalled();+ };+ this.canvas.addEventListener("pointerdown", ask, true);+ this.input.addEventListener("keydown", ask, true);+ }+ status.addEventListener("change", () => { if (status.state === "granted") this.readInstalled(); });+ }).catch(() => {});+ }++ readInstalled() {+ return window.queryLocalFonts().then((fonts) => {+ this.localFonts = fonts;+ this.installedFamilies = [...new Set(fonts.map((f) => f.family))];+ this.fontsChanged();+ }).catch((e) => console.warn("nano-ui-sdl-web: installed fonts not available:", e));+ }++ fontsChanged() {+ this.fontsVersion++;+ this.wake();+ }++ fontsVersionNow() {+ return this.fontsVersion;+ }++ // The families known so far, installed first, sorted and without repeats,+ // a line each.+ fontFamilies(ptr, n) {+ const seen = new Set();+ const all = [];+ for (const f of [...this.installedFamilies].sort().concat([...this.serviceFamilies].sort())) {+ if (!seen.has(f)) { seen.add(f); all.push(f); }+ }+ return this.writeText(all.join("\n"), ptr, n);+ }++ // A family name as the desktop's font search compares them.+ static fontKey(name) {+ return name.toLowerCase().replace(/[\s_-]/g, "");+ }++ // The installed fonts, through the Local Font Access API, asking the user+ // if the browser has not yet. Answers the length of the sorted family+ // names, one a line, for takeFontList; -1 without the API, -2 declined.+ async findFonts() {+ if (typeof window.queryLocalFonts !== "function") return -1;+ try {+ this.localFonts = await window.queryLocalFonts();+ } catch (e) {+ console.warn("nano-ui-sdl-web: installed fonts not available:", e);+ return -2;+ }+ this.installedFamilies = [...new Set(this.localFonts.map((f) => f.family))];+ const families = [...this.installedFamilies].sort();+ this.fontList = this.encoder.encode(families.join("\n"));+ return this.fontList.length;+ }++ takeFontList(ptr) {+ this.bytes(ptr, this.fontList.length).set(this.fontList);+ this.fontList = new Uint8Array(0);+ }++ // An installed family's regular face, else its first, or null. Reads the+ // installed fonts first when the user has allowed it but they have not+ // been read yet; never asks.+ async installedFace(name) {+ if (!this.localFonts && typeof window.queryLocalFonts === "function" && navigator.permissions) {+ try {+ const status = await navigator.permissions.query({ name: "local-fonts" });+ if (status.state === "granted") await this.readInstalled();+ } catch (e) { /* no permission query: nothing installed to read */ }+ }+ if (!this.localFonts) return null;+ const key = NanoUiSdlWeb.fontKey(name);+ const faces = this.localFonts.filter((f) => NanoUiSdlWeb.fontKey(f.family) === key);+ return faces.find((f) => /^(regular|normal|book|roman)$/i.test(f.style)) || faces[0] || null;+ }++ // A family's regular face from the font service, as TrueType, or null.+ async serviceFace(name) {+ if (this.fontService !== 1) return null;+ const id = name.toLowerCase().trim().replace(/[\s_]+/g, "-");+ const r = await fetch(`https://api.fontsource.org/v1/fonts/${encodeURIComponent(id)}`);+ if (!r.ok) return null;+ const font = await r.json();+ const weight = font.variants["400"] ? "400" : Object.keys(font.variants)[0];+ const style = font.variants[weight].normal ? "normal" : Object.keys(font.variants[weight])[0];+ const subsets = font.variants[weight][style];+ const subset = subsets[font.defSubset] || subsets.latin || Object.values(subsets)[0];+ const file = await fetch(subset.url.ttf);+ return file.ok ? file.blob() : null;+ }++ // A font file's bytes: an installed family's regular face (kind 0), a URL+ // (kind 1), or a family by name (kind 2): installed if the user has+ // allowed it, else from the font service. Answers their length for+ // takeFontBytes, or -1.+ async loadFont(kind, ptr, len) {+ const name = this.text(ptr, len);+ try {+ let blob = null;+ if (kind === 0) {+ if (!this.localFonts && typeof window.queryLocalFonts === "function") {+ this.localFonts = await window.queryLocalFonts();+ }+ blob = await this.installedFace(name).then((face) => (face ? face.blob() : null));+ } else if (kind === 1) {+ const response = await fetch(name);+ if (response.ok) blob = await response.blob();+ } else {+ const face = await this.installedFace(name);+ blob = face ? await face.blob() : await this.serviceFace(name);+ }+ if (!blob) return -1;+ this.fontBytes = new Uint8Array(await blob.arrayBuffer());+ return this.fontBytes.length;+ } catch (e) {+ console.warn(`nano-ui-sdl-web: could not load the font ${name}:`, e);+ return -1;+ }+ }++ takeFontBytes(ptr) {+ this.bytes(ptr, this.fontBytes.length).set(this.fontBytes);+ this.fontBytes = new Uint8Array(0);+ }++ // ---------------------------------------------------------------- files++ // Filters as Haskell sends them, a line each of a name, a tab and a+ // semicolon-separated extension list, as names with ".ext" lists. "*"+ // stands for any file, so a filter holding it lists none.+ static parseFilters(text) {+ return text.split("\n").filter((line) => line.includes("\t")).map((line) => {+ const [name, pattern] = line.split("\t");+ const exts = pattern.split(";").map((e) => e.trim()).filter((e) => e);+ return { name, extensions: exts.includes("*") ? [] : exts.map((e) => `.${e.replace(/^\./, "")}`) };+ });+ }++ // Keep bytes for takePicked; answer their length.+ setPicked(bytes) {+ this.picked = bytes;+ return bytes.length;+ }++ takePicked(ptr) {+ this.bytes(ptr, this.picked.length).set(this.picked);+ this.picked = new Uint8Array(0);+ }++ // The file chooser: files (mode 0) or every file in a folder (mode 1).+ // The chosen files are read and packed, each a little-endian 32-bit name+ // length, the UTF-8 name, a 32-bit length and the bytes. -1 cancelled,+ // -2 failed.+ async pickFiles(mode, many, ptr, len) {+ const filters = NanoUiSdlWeb.parseFilters(this.text(ptr, len));+ const input = document.createElement("input");+ input.type = "file";+ input.multiple = many !== 0;+ if (mode === 1) {+ input.webkitdirectory = true;+ } else {+ const exts = filters.flatMap((f) => f.extensions);+ if (exts.length && !filters.some((f) => f.extensions.length === 0)) input.accept = exts.join(",");+ }+ input.style.display = "none";+ document.body.appendChild(input);+ try {+ const files = await new Promise((resolve) => {+ input.addEventListener("change", () => resolve([...input.files]), { once: true });+ input.addEventListener("cancel", () => resolve(null), { once: true });+ input.click();+ });+ if (!files) return -1;+ const parts = [];+ for (const file of files) {+ parts.push(this.encoder.encode(file.webkitRelativePath || file.name));+ parts.push(new Uint8Array(await file.arrayBuffer()));+ }+ const out = new Uint8Array(parts.reduce((n, p) => n + 4 + p.length, 0));+ const view = new DataView(out.buffer);+ let o = 0;+ for (const p of parts) {+ view.setUint32(o, p.length, true);+ out.set(p, o + 4);+ o += 4 + p.length;+ }+ return this.setPicked(out);+ } catch (e) {+ console.warn("nano-ui-sdl-web: the file chooser failed:", e);+ return -2;+ } finally {+ input.remove();+ }+ }++ // Save bytes: through the browser's save dialog where it has one, else as+ // a download under the suggested name. Answers the length of the name it+ // was saved under, for takePicked; -1 cancelled, -2 failed.+ async saveFile(namePtr, nameLen, filtersPtr, filtersLen, dataPtr, dataLen) {+ const name = this.text(namePtr, nameLen);+ const filters = NanoUiSdlWeb.parseFilters(this.text(filtersPtr, filtersLen));+ // Copied now: the module's memory may move while the dialog is open.+ const data = this.bytes(dataPtr, dataLen).slice();+ try {+ if (typeof window.showSaveFilePicker === "function") {+ const types = filters.filter((f) => f.extensions.length)+ .map((f) => ({ description: f.name, accept: { "application/octet-stream": f.extensions } }));+ let handle;+ try {+ handle = await window.showSaveFilePicker({ suggestedName: name, types: types.length ? types : undefined });+ } catch (e) {+ if (e.name === "AbortError") return -1;+ throw e;+ }+ const writable = await handle.createWritable();+ await writable.write(data);+ await writable.close();+ return this.setPicked(this.encoder.encode(handle.name));+ }+ const url = URL.createObjectURL(new Blob([data]));+ const link = document.createElement("a");+ link.href = url;+ link.download = name;+ document.body.appendChild(link);+ link.click();+ link.remove();+ setTimeout(() => URL.revokeObjectURL(url), 60000);+ return this.setPicked(this.encoder.encode(name));+ } catch (e) {+ console.warn("nano-ui-sdl-web: saving failed:", e);+ return -2;+ }+ }+}++globalThis.nanoUiSdlWeb = new NanoUiSdlWeb();