diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml
index 38694435..c4a73bae 100644
--- a/.github/workflows/ci.yaml
+++ b/.github/workflows/ci.yaml
@@ -7,28 +7,61 @@ on:
permissions:
actions: write
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
jobs:
- nix:
+ android:
runs-on: ubuntu-latest
+ timeout-minutes: 45
steps:
- uses: actions/checkout@v4
- name: Local cache
uses: actions/cache@v4
with:
path: /nix/store
- key: "${{ runner.os }}-nix-cache"
+ key: "${{ runner.os }}-nix-android-cache"
+ restore-keys: |
+ ${{ runner.os }}-nix-android-
- uses: cachix/install-nix-action@v31
with:
- nix_path: nixpkgs=channel:nixos-unstable
extra_nix_config: |
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
+ extra-substituters = https://nix-cache.jappie.me
+ extra-trusted-public-keys = nix-cache.jappie.me:WjkKcvFtHih2i+n7bdsrJ3HuGboJiU2hA2CZbf9I9oc=
+ - run: nix-build nix/ci.nix
+ - name: Run combined emulator test (lifecycle + UI + buttons + scroll)
+ run: nix-build nix/ci.nix -A emulator-all -o result-emulator-all && ./result-emulator-all/bin/test-all
+ - name: Cancel workflow on failure
+ if: failure()
+ continue-on-error: true
+ run: gh run cancel ${{ github.run_id }}
+ env:
+ GH_TOKEN: ${{ github.token }}
- - uses: cachix/cachix-action@v15
+ # armv7a (armeabi-v7a) — 32-bit ARM, used by Wear OS watches
+ android-armv7a-emulator:
+ runs-on: ubuntu-latest
+ timeout-minutes: 45
+ steps:
+ - uses: actions/checkout@v4
+ - name: Local cache
+ uses: actions/cache@v4
+ with:
+ path: /nix/store
+ key: "${{ runner.os }}-nix-android-armv7a-emu"
+ restore-keys: |
+ ${{ runner.os }}-nix-android-armv7a-
+ ${{ runner.os }}-nix-android-
+ - uses: cachix/install-nix-action@v31
with:
- name: jappie
- signingKey: '${{ secrets.CACHIX_SIGNING_KEY }}'
- - run: nix-build
- - run: nix-shell --run "echo OK"
+ extra_nix_config: |
+ access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
+ extra-substituters = https://nix-cache.jappie.me
+ extra-trusted-public-keys = nix-cache.jappie.me:WjkKcvFtHih2i+n7bdsrJ3HuGboJiU2hA2CZbf9I9oc=
+ - name: Run armv7a emulator test
+ run: nix-build nix/ci.nix -A emulator-armv7a -o result-emulator-armv7a && ./result-emulator-armv7a/bin/test-all
- name: Cancel workflow on failure
if: failure()
continue-on-error: true
@@ -36,40 +69,55 @@ jobs:
env:
GH_TOKEN: ${{ github.token }}
- cabal:
- runs-on: ${{ matrix.os }}
-
- strategy:
- fail-fast: true
- matrix:
- ghc:
- - '9.12'
- - '9.10'
- - '9.8'
- - '9.6'
- os: [ubuntu-latest, macOS-latest, windows-latest]
-
+ ios:
+ runs-on: macos-latest
+ timeout-minutes: 45
steps:
- uses: actions/checkout@v4
- - uses: haskell-actions/setup@v2
+ - name: Local cache
+ uses: actions/cache@v4
+ with:
+ path: /nix/store
+ key: "${{ runner.os }}-nix-ios-cache"
+ restore-keys: |
+ ${{ runner.os }}-nix-ios-
+ - uses: cachix/install-nix-action@v31
with:
- ghc-version: ${{ matrix.ghc }}
+ extra_nix_config: |
+ access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
+ extra-substituters = https://nix-cache.jappie.me
+ extra-trusted-public-keys = nix-cache.jappie.me:WjkKcvFtHih2i+n7bdsrJ3HuGboJiU2hA2CZbf9I9oc=
+ - run: nix-build nix/ci.nix -A simulator-all -A ios-lib
+ - name: Run combined simulator test (lifecycle + UI + buttons + scroll)
+ run: nix-build nix/ci.nix -A simulator-all -o result-simulator-all && ./result-simulator-all/bin/test-all-ios
+ - name: Cancel workflow on failure
+ if: failure()
+ continue-on-error: true
+ run: gh run cancel ${{ github.run_id }}
+ env:
+ GH_TOKEN: ${{ github.token }}
- - name: Cabal cache
+ watchos:
+ runs-on: macos-latest
+ steps:
+ - uses: actions/checkout@v4
+ - name: Local cache
uses: actions/cache@v4
- env:
- cache-name: cache-cabal
with:
- path: ~/.cabal
- key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/*.cabal') }}-${{ hashFiles('**/cabal.project') }}
+ path: /nix/store
+ key: "${{ runner.os }}-nix-watchos-cache"
restore-keys: |
- ${{ runner.os }}-build-${{ env.cache-name }}-
- - name: Cabal update
- run: cabal update
- - name: Build using cabal
- run: cabal build all
- - name: Test
- run: cabal test all
+ ${{ runner.os }}-nix-watchos-
+ ${{ runner.os }}-nix-ios-
+ - uses: cachix/install-nix-action@v31
+ with:
+ extra_nix_config: |
+ access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
+ extra-substituters = https://nix-cache.jappie.me
+ extra-trusted-public-keys = nix-cache.jappie.me:WjkKcvFtHih2i+n7bdsrJ3HuGboJiU2hA2CZbf9I9oc=
+ - run: nix-build nix/ci.nix -A watchos-simulator-all -A watchos-lib
+ - name: Run combined watchOS simulator test
+ run: nix-build nix/ci.nix -A watchos-simulator-all -o result-watchos && ./result-watchos/bin/test-all-watchos
- name: Cancel workflow on failure
if: failure()
continue-on-error: true
diff --git a/.gitignore b/.gitignore
index 07c507a4..80abfac7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,8 +4,16 @@ network-uri-lenses.cabal
dist*
.#*
result
+result-*
TAGS
*.hi
*.o
-.envrc
\ No newline at end of file
+.envrc
+
+# Generated Xcode project (recreated via xcodegen)
+ios/HaskellMobile.xcodeproj/
+
+# Staging dirs populated from nix build output
+ios/lib/
+ios/include/
\ No newline at end of file
diff --git a/Changelog.md b/Changelog.md
index a3425a34..2452b314 100644
--- a/Changelog.md
+++ b/Changelog.md
@@ -1,6 +1,5 @@
-# Change log for template project
+# Change log for haskell-mobile
-## Version 0.0.0
-
-import [template](https://github.com/jappeace/template).
+## Version 1.0.0
+Initial release of haskell-mobile.
diff --git a/LICENSE b/LICENSE
index 416e727a..1ffd4bd7 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,6 +1,6 @@
MIT License
-Copyright (c) 2025 Jappie Klooster
+Copyright (c) 2026 Jappie Klooster
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
diff --git a/Readme.md b/Readme.md
index 212c412f..12083e46 100644
--- a/Readme.md
+++ b/Readme.md
@@ -1,89 +1,271 @@
-[](https://jappieklooster.nl/tag/haskell.html)
-[](https://github.com/jappeace/haskell-template-project/actions)
-[](https://discord.gg/Hp4agqy)
-[](https://hackage.haskell.org/package/template)
+[](https://github.com/jappeace/haskell-mobile/actions)
-> The eye that looks ahead to the safe course is closed forever.
+> To see a need and wait to be asked, is to already refuse.
-Haskell project template.
+# Haskell Mobile
-Set up cabal within a nix shell.
-If you like nix this is a good way of doing haskell development.
+Write mobile apps in Haskell.
+This project cross-compiles a Haskell library to Android (APK) and iOS (static library / IPA),
+with a thin platform-native UI layer (Kotlin for Android, Swift for iOS).
-similar to: https://github.com/monadfix/nix-cabal
-except this has a makefile and ghcid.
-We also make aggressive use of [pinning](https://wiki.nixos.org/wiki/FAQ/Pinning_Nixpkgs)
-ensuring project builds for ever (theoretically).
+## Building
-Comes with:
-+ [GHCID](https://jappieklooster.nl/ghcid-for-multi-package-projects.html)
-+ a nix shell, meaning somewhat platform independence.
- + which is pinned by default
-+ A couple of handy make commands.
-+ Starting haskell files, assuming we put practically all code in library
-+ Working test suite.
-+ functioining CI (pick your favorite or keep both)
- + for various platforms with cabal
+### Native (desktop)
-## Usage
+Enter the Nix shell and use cabal:
-### Modifying for your project
-Assuming the name of your new project is `new-project`.
+```bash
+nix-shell
+cabal build all
+cabal test all
+```
+
+Or use the makefile shortcuts (`make build`, `make test`, `make ghcid`).
+
+### Android APK
+```bash
+nix-build nix/android.nix # cross-compiled Haskell library
+nix-build nix/apk.nix # full APK
```
-git clone git@github.com:jappeace/haskell-template-project.git new-project
-cd new-project
+
+The APK is written to `result/haskell-mobile.apk`.
+
+### iOS static library
+
+Requires macOS (same ISA as iOS aarch64):
+
+```bash
+nix-build nix/ios.nix
```
-+ [ ] Edit template.cabal,
- + [ ] find and replace template with `new-project`
- + [ ] Update copyright
- + [ ] Update github
-+ [ ] rename template.cabal to new-project.cabal
-+ [ ] Edit Changelog.md
- + [ ] replace template with `new-project`
- + [ ] Also describe your version 1.0.0 release.
-+ [x] Edit default.nix and shell.nix, replace template with `new-project`.
-+ [ ] Edit copyright in LICENSE
-+ [ ] For automatic bound bumping: In “Settings” → “Actions” → “General” → “Workflow permissions” tick “Allow GitHub Actions to create and approve pull requests”
-
-#### Reconfigure remotes
+Produces `result/lib/libHaskellMobile.a` and `result/include/HaskellMobile.h`.
+
+### iOS app (local dev)
+
+After building the static library, generate an Xcode project with [XcodeGen](https://github.com/yonaskolb/XcodeGen):
+
+```bash
+# Stage the Haskell library where the Xcode project expects it
+mkdir -p ios/lib ios/include
+cp result/lib/libHaskellMobile.a ios/lib/
+cp result/include/HaskellMobile.h ios/include/
+
+# Generate and open
+nix-shell -p xcodegen --run "cd ios && xcodegen generate"
+open ios/HaskellMobile.xcodeproj
```
-git remote add template git@github.com:jappeace/haskell-template-project.git
-git remote set-url origin git@github.com:YOUR-ORG-OR-USER-NAME/new-project.git
+
+Configure signing in Xcode (team, bundle ID, provisioning profile), then build and run.
+
+## Installing
+
+### Android
+
+```bash
+adb install result/haskell-mobile.apk
```
-We can get template updates like this if we want to by doing `git pull template`.
-There will be a large amount of conflicts, but the merge commit should solve them permanently.
+### iOS
-#### Readme
+Use Xcode to deploy to a connected device, or download the IPA artifact from the
+[CI Actions page](https://github.com/jappeace/haskell-mobile/actions) (master builds only, when signing secrets are configured).
-+ [ ] Select desired badges.
- + [ ] Point build badges to right project
-+ [ ] Give short project description.
-+ [ ] Add new quote suited for the project.
- For example for [fakedata-quickcheck](https://github.com/fakedata-haskell/fakedata-quickcheck#readme)
- I used Kant because
- he dealt with the question "what is truth" a lot.
-+ [ ] Truncate this checklist
-+ [ ] Truncate motivation for using this template
+## CI
-### Tools
-Enter the nix shell.
+The GitHub Actions workflow runs four jobs:
+
+| Job | Platform | What it does |
+|-----|----------|--------------|
+| `nix` | Linux | `nix-build` + `nix-shell` smoke test |
+| `android` | Linux | Cross-compile to Android, build APK (master) |
+| `ios` | macOS | Cross-compile to iOS static lib, build IPA if signing secrets are set (master) |
+| `cabal` | Linux/macOS/Windows | GHC 9.6 / 9.8 / 9.10 / 9.12 matrix build + tests |
+
+### iOS signing secrets
+
+The IPA build is conditional: without secrets, CI only builds the static library.
+To enable IPA builds, add these repository secrets:
+
+| Secret | Description |
+|--------|-------------|
+| `APPLE_CERTIFICATE_BASE64` | Base64-encoded `.p12` distribution certificate |
+| `APPLE_CERTIFICATE_PASSWORD` | Password for the `.p12` file |
+| `APPLE_PROVISIONING_PROFILE_BASE64` | Base64-encoded `.mobileprovision` file |
+| `APPLE_TEAM_ID` | Apple Developer Team ID |
+
+Generate the base64 values with:
+
+```bash
+base64 -i Certificates.p12 | pbcopy
+base64 -i App.mobileprovision | pbcopy
```
-nix-shell
+
+## Architecture
+
+### Boot Sequence
+
+Platform builds produce a **library** (`.so` on Android, `.a` on iOS), not an executable.
+The user writes a `main :: IO (Ptr AppContext)` that calls `startMobileApp` — no
+`foreign export ccall` needed. The C bridge runs it using the GHC RTS API and
+captures the returned context pointer.
+
+#### Android
+
+`JNI_OnLoad` (`cbits/jni_bridge.c`) — Android's JVM calls this automatically when
+`System.loadLibrary("haskellmobile")` loads the `.so`. It runs:
+
+```c
+hs_init(NULL, NULL); // 1. start GHC runtime
+g_ctx = haskellRunMain(); // 2. run user's main, get context pointer
```
-You can checkout the makefile to see what's available:
+
+#### iOS
+
+Same sequence. The Swift bridge (`ios/HaskellMobile/HaskellBridge.swift`) calls:
+
+```swift
+hs_init(nil, nil)
+context = haskellRunMain()
```
-cat makefile
+
+The `.a` static library is linked directly into the Xcode project —
+Swift calls the C functions without JNI.
+
+#### What each step does
+
+1. **`hs_init`** — Starts the GHC runtime (GC, thread scheduler, IO manager).
+ Does **not** call `main`.
+
+2. **`haskellRunMain`** (`cbits/run_main.c`) — A C function that evaluates the user's
+ Haskell `main` via the GHC RTS API and captures the return value:
+ ```c
+ Capability *cap = rts_lock();
+ HaskellObj result;
+ rts_evalIO(&cap, &ZCMain_main_closure, &result);
+ void *ctx = rts_getPtr(result);
+ rts_unlock(cap);
+ return ctx;
+ ```
+ GHC compiles `Main.main` into a closure called `ZCMain_main_closure` (Z-encoded
+ symbol for `:Main.main`). The user's `main` calls `startMobileApp`, which creates
+ an `AppContext` (bundling the `MobileApp`'s callbacks, render state, permission
+ state, and view function) and returns it as a `StablePtr`.
+
+After boot, the platform calls FFI exports (`haskellRenderUI`, `haskellOnUIEvent`,
+`haskellOnLifecycle`) passing the context pointer. All state lives in the `AppContext` —
+no global mutable variables.
+
+#### Desktop (executable)
+
+`app/Main.hs` is a desktop demo. GHC's generated C `main()` stub calls `hs_main`,
+which does `hs_init` + `rts_evalLazyIO(main)` + `hs_exit` automatically. The user's
+`main` calls `startMobileApp`, then simulates lifecycle events using the returned context.
+
+`app/MobileMain.hs` is the mobile entry point for the demo — it's compiled into the
+`.so`/`.a` by the nix build scripts. Downstream users write their own `Main.hs`.
+
+### AppContext
+
+The `AppContext` (`src/HaskellMobile/AppContext.hs`) bundles all per-session state:
+
+```haskell
+data MobileApp = MobileApp
+ { maContext :: MobileContext -- lifecycle callbacks
+ , maView :: UserState -> IO Widget -- returns the current UI tree
+ }
+
+data AppContext = AppContext
+ { acMobileContext :: MobileContext
+ , acRenderState :: RenderState
+ , acPermissionState :: PermissionState
+ , acViewFunction :: IORef (UserState -> IO Widget)
+ }
+
+startMobileApp :: MobileApp -> IO (Ptr AppContext)
```
-### Running
+All FFI entry points (`haskellRenderUI`, `haskellOnUIEvent`, `haskellOnLifecycle`)
+receive the `AppContext` pointer and read all state from it.
+
+### Rendering Cycle
+
+When native code calls `renderUI`:
+
+1. `haskellRenderUI` reads the view function from `AppContext`, calls it to get the `Widget` tree
+2. `renderWidget` (`src/HaskellMobile/Render.hs`) clears the screen, walks the tree
+ calling `Bridge.createNode` / `Bridge.addChild` / `Bridge.setHandler`, and registers
+ callbacks (click handlers, text change handlers) in `IntMap`s keyed by callback ID
+3. When the user taps a button, native code calls `haskellOnUIEvent` with a callback ID,
+ which looks up and fires the `IO ()` action from the `IntMap`, then re-renders
+
+Text input changes go through `haskellOnUITextChange` instead, which dispatches the
+text callback but does **not** re-render (to avoid cursor/flicker issues on Android).
+
+### How User Code Plugs In
+
+A downstream user provides two things:
+
+1. **A `MobileApp` value** — their `maView` returns the widget tree, their `maContext`
+ handles lifecycle events.
+
+2. **A `Main.hs`** with a `main :: IO (Ptr AppContext)` that calls `startMobileApp`. No
+ `foreign export ccall` needed — `cbits/run_main.c` calls it via the GHC RTS API.
+ The nix build scripts accept the user's Main.hs as the `mainModule` parameter.
+
+Example user `Main.hs`:
+
+```haskell
+module Main where
+
+import Foreign.Ptr (Ptr)
+import HaskellMobile (startMobileApp, AppContext)
+import MyApp (myApp) -- user's MobileApp
+
+main :: IO (Ptr AppContext)
+main = startMobileApp myApp
```
-make run
+
+Build for Android with:
+
+```nix
+import ./nix/android.nix { mainModule = ./my-app/Main.hs; }
```
-### Fast filewatch which runs tests
```
-make ghcid
+Android: JNI_OnLoad -> hs_init -> haskellRunMain -> main -> startMobileApp(app) -> Ptr AppContext
+ |
+ bundles MobileApp into AppContext
+ |
+ renderUI -> haskellRenderUI(ctx) -> acViewFunction -> Widget tree -> Bridge
+ onClick -> haskellOnUIEvent(ctx) -> IntMap lookup -> fire IO action -> re-render
```
+
+### Key Files
+
+| File | Role |
+|------|------|
+| `app/Main.hs` | Desktop demo executable — calls `startMobileApp` and simulates lifecycle |
+| `app/MobileMain.hs` | Demo mobile entry point — a `main :: IO (Ptr AppContext)`. Downstream users write their own |
+| `cbits/run_main.c` | Calls `rts_evalIO(&ZCMain_main_closure)` — runs the user's Haskell main and captures the returned context pointer |
+| `src/HaskellMobile.hs` | FFI exports: `haskellGreet`, `haskellRenderUI`, `haskellOnUIEvent`, `haskellOnUITextChange`, `startMobileApp` |
+| `src/HaskellMobile/Types.hs` | `MobileApp` record and `UserState` type |
+| `src/HaskellMobile/App.hs` | Default app (counter demo) — replace with your own |
+| `src/HaskellMobile/Lifecycle.hs` | `LifecycleEvent` enum, `MobileContext`, `haskellOnLifecycle` FFI export |
+| `src/HaskellMobile/Widget.hs` | `Widget` ADT: `Text`, `Button`, `TextInput`, `Row`, `Column` |
+| `src/HaskellMobile/UIBridge.hs` | Haskell FFI imports for the C UI bridge (`createNode`, `setRoot`, etc.) |
+| `src/HaskellMobile/Render.hs` | Rendering engine: walks `Widget` tree, issues bridge calls, manages callback registries |
+| `cbits/jni_bridge.c` | Android JNI entry points — calls Haskell FFI exports |
+| `cbits/ui_bridge.c` | C-side UI bridge (callback storage, stub implementations for desktop) |
+| `cbits/ui_bridge_android.c` | Android-specific UI bridge (calls back into Java via JNI) |
+| `cbits/platform_log.c` | Platform logging (`__android_log_print` / `os_log` / `fprintf(stderr)`) |
+| `include/HaskellMobile.h` | C header for all Haskell FFI exports |
+| `include/UIBridge.h` | C header for the UI bridge callbacks |
+
+# Roadmap
+
++ Test out lifecycles.
+ + Need logging support in respective frameworks, make sure they get triggered.
++ Figure out how to do UI
+ + need to be able to register callbacks on events, eg onButtonClick
+ + tranistion between UI's?
diff --git a/TODO/lifecycles.md b/TODO/lifecycles.md
new file mode 100644
index 00000000..d137671d
--- /dev/null
+++ b/TODO/lifecycles.md
@@ -0,0 +1,39 @@
+# Deferred Lifecycle Events
+
+Lifecycle events not yet implemented due to lack of cross-platform equivalents
+or requiring platform-specific APIs beyond the current scope.
+
+## Android-Only (deferred)
+
+| Event | Reason |
+|-------|--------|
+| `onRestart` | No iOS equivalent; rare use case (Start already covers re-entering foreground) |
+| `onSaveInstanceState` | Android-specific state persistence; iOS uses different restoration APIs |
+| `onRestoreInstanceState` | Counterpart to onSaveInstanceState; same reasoning |
+| `onConfigurationChanged` | Android-specific (rotation, locale change); iOS handles via SwiftUI environment |
+| `onTrimMemory(level)` | Granular memory pressure with level parameter; iOS equivalent (didReceiveMemoryWarning) is a separate API |
+
+## iOS-Only (deferred)
+
+| Event | Reason |
+|-------|--------|
+| `viewWillAppear` / `viewDidAppear` | UIKit ViewController lifecycle, not available in SwiftUI without bridging |
+| `viewWillDisappear` / `viewDidDisappear` | Same as above |
+| `viewIsAppearing` (iOS 17+) | UIKit-only, requires iOS 17 minimum |
+| `applicationWillTerminate` | Requires UIApplicationDelegate; SwiftUI has no direct equivalent |
+| `didReceiveMemoryWarning` | Requires NotificationCenter subscription (`.UIApplication.didReceiveMemoryWarningNotification`) |
+| State restoration | iOS uses NSUserActivity / scene-based state restoration, very different model from Android |
+
+## Currently Implemented
+
+| Event | Code | Android | iOS |
+|-------|------|---------|-----|
+| Create | 0 | `onCreate` | App `init()` |
+| Start | 1 | `onStart` | (not fired) |
+| Resume | 2 | `onResume` | `.active` |
+| Pause | 3 | `onPause` | `.inactive` |
+| Stop | 4 | `onStop` | `.background` |
+| Destroy | 5 | `onDestroy` | (not fired) |
+| LowMemory | 6 | `onLowMemory` | (not fired) |
+
+iOS fires Create/Resume/Pause/Stop. Start/Destroy/LowMemory are Android-only in practice.
diff --git a/android/AndroidManifest.xml b/android/AndroidManifest.xml
new file mode 100644
index 00000000..8674dc53
--- /dev/null
+++ b/android/AndroidManifest.xml
@@ -0,0 +1,33 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/android/java/me/jappie/haskellmobile/HaskellMobileActivity.java b/android/java/me/jappie/haskellmobile/HaskellMobileActivity.java
new file mode 100644
index 00000000..232d2a9b
--- /dev/null
+++ b/android/java/me/jappie/haskellmobile/HaskellMobileActivity.java
@@ -0,0 +1,160 @@
+package me.jappie.haskellmobile;
+
+import android.app.Activity;
+import android.content.pm.PackageManager;
+import android.Manifest;
+import android.os.Bundle;
+import android.text.Editable;
+import android.text.TextWatcher;
+import android.view.View;
+import android.widget.EditText;
+
+/**
+ * Base Activity that wires up all haskell-mobile JNI boilerplate.
+ * Consumer apps extend this class instead of copy-pasting the native
+ * declarations, lifecycle forwarding, permission handling, etc.
+ *
+ * JNI native method resolution uses the declaring class for symbol names,
+ * so these native methods always resolve to
+ * Java_me_jappie_haskellmobile_HaskellMobileActivity_* regardless of
+ * which subclass the runtime object is.
+ */
+public class HaskellMobileActivity extends Activity implements View.OnClickListener {
+
+ static {
+ System.loadLibrary("haskellmobile");
+ }
+
+ private native String greet(String name);
+ private native void renderUI();
+ private native void onButtonClick(View view);
+ private native void onTextChange(View view, String text);
+ private native void onLifecycleCreate();
+ private native void onLifecycleStart();
+ private native void onLifecycleResume();
+ private native void onLifecyclePause();
+ private native void onLifecycleStop();
+ private native void onLifecycleDestroy();
+ private native void onLifecycleLowMemory();
+ private native void onPermissionResult(int requestCode, int statusCode);
+
+ /**
+ * Map a permission code (from PermissionBridge.h) to an Android permission string.
+ * Must match the PERMISSION_* constants in the C header.
+ */
+ private String permissionCodeToString(int permissionCode) {
+ switch (permissionCode) {
+ case 0: return Manifest.permission.ACCESS_FINE_LOCATION;
+ case 1: return Manifest.permission.BLUETOOTH_SCAN;
+ case 2: return Manifest.permission.CAMERA;
+ case 3: return Manifest.permission.RECORD_AUDIO;
+ case 4: return Manifest.permission.READ_CONTACTS;
+ case 5: return Manifest.permission.READ_EXTERNAL_STORAGE;
+ default: return null;
+ }
+ }
+
+ /**
+ * Request a runtime permission. Called from native code via JNI.
+ * permissionCode: one of PERMISSION_* constants from PermissionBridge.h.
+ * requestId: opaque ID passed back in the result callback.
+ */
+ public void requestPermission(int permissionCode, int requestId) {
+ String permission = permissionCodeToString(permissionCode);
+ if (permission == null) {
+ onPermissionResult(requestId, 1); // PERMISSION_DENIED
+ return;
+ }
+ if (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) {
+ onPermissionResult(requestId, 0); // PERMISSION_GRANTED
+ return;
+ }
+ requestPermissions(new String[]{ permission }, requestId);
+ }
+
+ /**
+ * Check whether a permission is currently granted. Called from native code via JNI.
+ * Returns 0 (PERMISSION_GRANTED) or 1 (PERMISSION_DENIED).
+ */
+ public int checkPermission(int permissionCode) {
+ String permission = permissionCodeToString(permissionCode);
+ if (permission == null) return 1;
+ return checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED ? 0 : 1;
+ }
+
+ @Override
+ public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
+ super.onRequestPermissionsResult(requestCode, permissions, grantResults);
+ int statusCode = (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) ? 0 : 1;
+ onPermissionResult(requestCode, statusCode);
+ }
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ onLifecycleCreate();
+ // Render UI from Haskell instead of XML layout
+ renderUI();
+ }
+
+ @Override
+ public void onClick(View v) {
+ onButtonClick(v);
+ }
+
+ /**
+ * Register a TextWatcher on an EditText. Called from native code
+ * when a TextInput widget has an EventTextChange handler.
+ * The watcher forwards text changes to the native onTextChange method.
+ */
+ public void registerTextWatcher(final EditText editText) {
+ editText.addTextChangedListener(new TextWatcher() {
+ @Override
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
+
+ @Override
+ public void onTextChanged(CharSequence s, int start, int before, int count) {}
+
+ @Override
+ public void afterTextChanged(Editable s) {
+ onTextChange(editText, s.toString());
+ }
+ });
+ }
+
+ @Override
+ protected void onStart() {
+ super.onStart();
+ onLifecycleStart();
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ onLifecycleResume();
+ }
+
+ @Override
+ protected void onPause() {
+ super.onPause();
+ onLifecyclePause();
+ }
+
+ @Override
+ protected void onStop() {
+ super.onStop();
+ onLifecycleStop();
+ }
+
+ @Override
+ protected void onDestroy() {
+ super.onDestroy();
+ onLifecycleDestroy();
+ }
+
+ @Override
+ public void onLowMemory() {
+ super.onLowMemory();
+ onLifecycleLowMemory();
+ }
+}
diff --git a/android/java/me/jappie/haskellmobile/MainActivity.java b/android/java/me/jappie/haskellmobile/MainActivity.java
new file mode 100644
index 00000000..c2b65b84
--- /dev/null
+++ b/android/java/me/jappie/haskellmobile/MainActivity.java
@@ -0,0 +1,3 @@
+package me.jappie.haskellmobile;
+
+public class MainActivity extends HaskellMobileActivity {}
diff --git a/android/res/layout/activity_main.xml b/android/res/layout/activity_main.xml
new file mode 100644
index 00000000..2d03a957
--- /dev/null
+++ b/android/res/layout/activity_main.xml
@@ -0,0 +1,14 @@
+
+
+
+
+
+
diff --git a/android/res/values/strings.xml b/android/res/values/strings.xml
new file mode 100644
index 00000000..ed751031
--- /dev/null
+++ b/android/res/values/strings.xml
@@ -0,0 +1,4 @@
+
+
+ Haskell Mobile
+
diff --git a/app/Main.hs b/app/Main.hs
index 30f12435..4e274b3c 100644
--- a/app/Main.hs
+++ b/app/Main.hs
@@ -1,7 +1,33 @@
-
+{-# LANGUAGE OverloadedStrings #-}
module Main where
-import qualified Template
+import HaskellMobile (startMobileApp, platformLog, AppContext(..), derefAppContext)
+import HaskellMobile.App (mobileApp)
+import HaskellMobile.Lifecycle (LifecycleEvent(..), MobileContext(onLifecycle))
+-- | Desktop entry point. Creates the app context, then simulates a mobile
+-- lifecycle to exercise the callbacks.
+--
+-- On Android\/iOS, the platform bridge runs the user's @main@ via
+-- @haskellRunMain()@ (cbits\/run_main.c) instead of GHC's generated
+-- C main stub.
main :: IO ()
-main = Template.main
+main = do
+ ctxPtr <- startMobileApp mobileApp
+ appCtx <- derefAppContext ctxPtr
+ platformLog "Haskell app registered"
+ let listen = onLifecycle (acMobileContext appCtx)
+
+ -- Simulate the platform sending lifecycle events
+ listen Create
+ listen Start
+ listen Resume
+
+ platformLog "App is now in foreground"
+
+ listen Pause
+ listen Stop
+ listen LowMemory
+ listen Destroy
+
+ platformLog "App lifecycle complete"
diff --git a/app/MobileMain.hs b/app/MobileMain.hs
new file mode 100644
index 00000000..d051e8e3
--- /dev/null
+++ b/app/MobileMain.hs
@@ -0,0 +1,20 @@
+{-# LANGUAGE OverloadedStrings #-}
+-- | Mobile entry point for the demo app.
+--
+-- The platform bridge (Android JNI, iOS Swift) runs this @main@
+-- after @hs_init@ via the RTS API (@rts_evalIO@ on the
+-- @ZCMain_main_closure@ symbol). No @foreign export ccall@ needed.
+--
+-- Downstream users write their own version of this file with a
+-- plain @main :: IO (Ptr AppContext)@ that calls @startMobileApp@.
+module Main where
+
+import Foreign.Ptr (Ptr)
+import HaskellMobile (startMobileApp, platformLog, AppContext)
+import HaskellMobile.App (mobileApp)
+
+-- | Create the app context and return it to the platform bridge.
+main :: IO (Ptr AppContext)
+main = do
+ platformLog "Haskell app registered"
+ startMobileApp mobileApp
diff --git a/cbits/android_stubs.c b/cbits/android_stubs.c
new file mode 100644
index 00000000..3e5c23fe
--- /dev/null
+++ b/cbits/android_stubs.c
@@ -0,0 +1,15 @@
+/*
+ * Stubs for symbols that GHC RTS expects but Android bionic libc lacks.
+ * Only compiled in on Android builds; the #ifdef makes this a no-op
+ * on regular (glibc/musl) builds.
+ *
+ * Add more stubs here as link errors reveal missing symbols.
+ */
+
+#ifdef __ANDROID__
+
+/* GHC's RTS uses these internally via libc wrappers that bionic omits */
+void __svfscanf(void) {}
+void __vfwscanf(void) {}
+
+#endif
diff --git a/cbits/jni_bridge.c b/cbits/jni_bridge.c
new file mode 100644
index 00000000..fc07bcd7
--- /dev/null
+++ b/cbits/jni_bridge.c
@@ -0,0 +1,171 @@
+/*
+ * JNI bridge between Android Java and Haskell FFI exports.
+ *
+ * This file is compiled by NDK clang (not cabal), and linked into
+ * libhaskellmobile.so alongside the Haskell static library.
+ *
+ * The Java package name is controlled by -DJNI_PACKAGE at compile time;
+ * see include/JniBridge.h for defaults.
+ */
+
+#include
+#include
+#include
+#include "HsFFI.h"
+#include "JniBridge.h"
+#include "PermissionBridge.h"
+
+/* Runs the user's Haskell main via RTS API (cbits/run_main.c).
+ * Returns the opaque AppContext pointer. */
+extern void *haskellRunMain(void);
+
+/* Locale detection (cbits/locale.c) */
+extern void setSystemLocale(const char *locale);
+
+/* Log detected locale from Haskell (HaskellMobile.Locale) */
+extern void haskellLogLocale(void);
+
+/* Haskell foreign exports */
+extern char* haskellGreet(const char* name);
+extern void haskellOnLifecycle(void *ctx, int eventType);
+extern void haskellRenderUI(void *ctx);
+extern void haskellOnUIEvent(void *ctx, int callbackId);
+extern void haskellOnUITextChange(void *ctx, int callbackId, const char *text);
+extern void haskellOnPermissionResult(void *ctx, int32_t requestId, int32_t statusCode);
+
+/* Android UI bridge (from ui_bridge_android.c) */
+extern void setup_android_ui_bridge(JNIEnv *env, jobject activity, void *haskellCtx);
+extern void android_handle_click(JNIEnv *env, jobject view, void *haskellCtx);
+extern void android_handle_text_change(JNIEnv *env, jobject view, jstring text, void *haskellCtx);
+
+/* Android permission bridge (from permission_bridge_android.c) */
+extern void setup_android_permission_bridge(JNIEnv *env, jobject activity, void *haskellCtx);
+
+/* Lifecycle event codes (must match HaskellMobile.h) */
+#define LIFECYCLE_CREATE 0
+#define LIFECYCLE_START 1
+#define LIFECYCLE_RESUME 2
+#define LIFECYCLE_PAUSE 3
+#define LIFECYCLE_STOP 4
+#define LIFECYCLE_DESTROY 5
+#define LIFECYCLE_LOW_MEMORY 6
+
+/* Opaque Haskell context pointer, created during JNI_OnLoad */
+static void *g_haskell_ctx = NULL;
+
+JNIEXPORT jint JNICALL
+JNI_OnLoad(JavaVM *vm, void *reserved)
+{
+ hs_init(NULL, NULL);
+ g_haskell_ctx = haskellRunMain();
+
+ /* Cache the system locale from Android's Locale.getDefault().toLanguageTag() */
+ {
+ JNIEnv *env;
+ (*vm)->GetEnv(vm, (void**)&env, JNI_VERSION_1_6);
+
+ jclass localeClass = (*env)->FindClass(env, "java/util/Locale");
+ jmethodID getDefault = (*env)->GetStaticMethodID(env, localeClass,
+ "getDefault", "()Ljava/util/Locale;");
+ jobject locale = (*env)->CallStaticObjectMethod(env, localeClass, getDefault);
+ jmethodID toLanguageTag = (*env)->GetMethodID(env, localeClass,
+ "toLanguageTag", "()Ljava/lang/String;");
+ jstring jtag = (*env)->CallObjectMethod(env, locale, toLanguageTag);
+
+ const char *ctag = (*env)->GetStringUTFChars(env, jtag, NULL);
+ setSystemLocale(strdup(ctag));
+ (*env)->ReleaseStringUTFChars(env, jtag, ctag);
+
+ haskellLogLocale();
+ }
+
+ return JNI_VERSION_1_6;
+}
+
+JNIEXPORT void JNICALL
+JNI_OnUnload(JavaVM *vm, void *reserved)
+{
+ hs_exit();
+}
+
+JNIEXPORT jstring JNICALL
+JNI_METHOD(greet)(JNIEnv *env, jobject thiz, jstring jname)
+{
+ const char *cname = (*env)->GetStringUTFChars(env, jname, NULL);
+ if (cname == NULL) {
+ return NULL; /* OutOfMemoryError already thrown */
+ }
+
+ char *cresult = haskellGreet(cname);
+ (*env)->ReleaseStringUTFChars(env, jname, cname);
+
+ jstring jresult = (*env)->NewStringUTF(env, cresult);
+ free(cresult);
+
+ return jresult;
+}
+
+/* --- UI bridge JNI methods --- */
+
+JNIEXPORT void JNICALL
+JNI_METHOD(renderUI)(JNIEnv *env, jobject thiz)
+{
+ setup_android_ui_bridge(env, thiz, g_haskell_ctx);
+ setup_android_permission_bridge(env, thiz, g_haskell_ctx);
+ haskellRenderUI(g_haskell_ctx);
+}
+
+JNIEXPORT void JNICALL
+JNI_METHOD(onButtonClick)(JNIEnv *env, jobject thiz, jobject view)
+{
+ android_handle_click(env, view, g_haskell_ctx);
+}
+
+JNIEXPORT void JNICALL
+JNI_METHOD(onTextChange)(JNIEnv *env, jobject thiz, jobject view, jstring text)
+{
+ android_handle_text_change(env, view, text, g_haskell_ctx);
+}
+
+/* Lifecycle JNI callbacks */
+JNIEXPORT void JNICALL
+JNI_METHOD(onLifecycleCreate)(JNIEnv *env, jobject thiz)
+{
+ haskellOnLifecycle(g_haskell_ctx, LIFECYCLE_CREATE);
+}
+
+JNIEXPORT void JNICALL
+JNI_METHOD(onLifecycleStart)(JNIEnv *env, jobject thiz)
+{
+ haskellOnLifecycle(g_haskell_ctx, LIFECYCLE_START);
+}
+
+JNIEXPORT void JNICALL
+JNI_METHOD(onLifecycleResume)(JNIEnv *env, jobject thiz)
+{
+ haskellOnLifecycle(g_haskell_ctx, LIFECYCLE_RESUME);
+}
+
+JNIEXPORT void JNICALL
+JNI_METHOD(onLifecyclePause)(JNIEnv *env, jobject thiz)
+{
+ haskellOnLifecycle(g_haskell_ctx, LIFECYCLE_PAUSE);
+}
+
+JNIEXPORT void JNICALL
+JNI_METHOD(onLifecycleStop)(JNIEnv *env, jobject thiz)
+{
+ haskellOnLifecycle(g_haskell_ctx, LIFECYCLE_STOP);
+}
+
+JNIEXPORT void JNICALL
+JNI_METHOD(onLifecycleDestroy)(JNIEnv *env, jobject thiz)
+{
+ haskellOnLifecycle(g_haskell_ctx, LIFECYCLE_DESTROY);
+}
+
+JNIEXPORT void JNICALL
+JNI_METHOD(onLifecycleLowMemory)(JNIEnv *env, jobject thiz)
+{
+ haskellOnLifecycle(g_haskell_ctx, LIFECYCLE_LOW_MEMORY);
+}
diff --git a/cbits/locale.c b/cbits/locale.c
new file mode 100644
index 00000000..1f94adf6
--- /dev/null
+++ b/cbits/locale.c
@@ -0,0 +1,33 @@
+/*
+ * Platform-specific locale detection.
+ *
+ * Uses a set/get pattern: platform bridges call setSystemLocale() during
+ * initialization, and Haskell code reads it via getSystemLocale().
+ *
+ * Android: jni_bridge.c calls setSystemLocale() in JNI_OnLoad after
+ * querying Locale.getDefault().toLanguageTag() via JNI.
+ * iOS: UIBridgeIOS.m calls setSystemLocale() in setup_ios_ui_bridge
+ * after querying NSLocale.currentLocale.
+ * Desktop: falls back to LANG environment variable, then "en".
+ */
+
+#include
+
+static const char *g_system_locale = NULL;
+
+void setSystemLocale(const char *locale)
+{
+ g_system_locale = locale; /* caller owns the memory (static/strdup'd) */
+}
+
+const char* getSystemLocale(void)
+{
+ if (g_system_locale) return g_system_locale;
+#ifndef __ANDROID__
+ {
+ const char *lang = getenv("LANG");
+ if (lang) return lang;
+ }
+#endif
+ return "en";
+}
diff --git a/cbits/mac2watchos.c b/cbits/mac2watchos.c
new file mode 100644
index 00000000..24f6a82d
--- /dev/null
+++ b/cbits/mac2watchos.c
@@ -0,0 +1,195 @@
+/*
+ * mac2watchos — Rewrite Mach-O platform tags from macOS to watchOS.
+ *
+ * Based on zw3rk/mobile-core-tools mac2ios.c, adapted for watchOS.
+ * Patches LC_BUILD_VERSION platform from PLATFORM_MACOS (1) to
+ * PLATFORM_WATCHOS (4) or PLATFORM_WATCHOSSIMULATOR (9), and
+ * rewrites legacy LC_VERSION_MIN_MACOSX to LC_VERSION_MIN_WATCHOS.
+ *
+ * Usage:
+ * mac2watchos [-s] FILE
+ * -s set platform to WATCHOSSIMULATOR (default: WATCHOS)
+ */
+
+#include
+#include
+#include
+#include
+#include
+
+/* ---------- Mach-O structures (from mobile-core-tools/macho.h) ---------- */
+
+typedef int cpu_type_t;
+typedef int cpu_subtype_t;
+
+typedef struct _mach_header_64 {
+ uint32_t magic;
+ cpu_type_t cputype;
+ cpu_subtype_t cpusubtype;
+ uint32_t filetype;
+ uint32_t ncmds;
+ uint32_t sizeofcmds;
+ uint32_t flags;
+ uint32_t reserved;
+} mach_header_64;
+
+typedef struct _load_command {
+ uint32_t cmd;
+ uint32_t cmdsize;
+} load_command;
+
+struct build_version_command {
+ uint32_t cmd;
+ uint32_t cmdsize;
+ uint32_t platform;
+ uint32_t minos;
+ uint32_t sdk;
+ uint32_t ntools;
+};
+
+#define LC_VERSION_MIN_MACOSX 0x24
+#define LC_VERSION_MIN_WATCHOS 0x30
+#define LC_BUILD_VERSION 0x32
+
+#define PLATFORM_WATCHOS 4
+#define PLATFORM_WATCHOSSIMULATOR 9
+
+/* ---------- AR archive header (from mobile-core-tools/ar.h) ---------- */
+
+typedef struct _ar_header {
+ char ident[16];
+ char mtime[12];
+ char oid[6];
+ char uid[6];
+ char mode[8];
+ char size[10];
+ char end[2];
+} ar_header;
+
+/* ---------- Implementation ---------- */
+
+/* 64 KB buffer — load commands are limited to ~16 KB, header is ~64 bytes */
+static uint8_t buffer[64 * 1024];
+
+static void patch_object(FILE *fp, size_t len, int platform) {
+ int pos = ftell(fp);
+
+ fread(buffer, sizeof(buffer), 1, fp);
+
+ mach_header_64 *hdr = (mach_header_64 *)buffer;
+
+ if (!(hdr->magic == 0xfeedface /* 32-bit */
+ || hdr->magic == 0xfeedfacf /* 64-bit */
+ || hdr->magic == 0xcafebabe)) { /* Universal */
+ fseek(fp, pos, SEEK_SET);
+ return;
+ }
+
+ size_t offset = sizeof(mach_header_64);
+ load_command *cmd;
+ while (offset < sizeof(mach_header_64) + hdr->sizeofcmds) {
+ cmd = (load_command *)(buffer + offset);
+ switch (cmd->cmd) {
+ case LC_VERSION_MIN_MACOSX: {
+ cmd->cmd = LC_VERSION_MIN_WATCHOS;
+ printf("Changing LC_VERSION_MIN_ from: %d -> %d\n",
+ LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_WATCHOS);
+ fseek(fp, pos + offset, SEEK_SET);
+ fwrite(buffer + offset, sizeof(struct build_version_command), 1, fp);
+ break;
+ }
+ case LC_BUILD_VERSION: {
+ struct build_version_command *bvc =
+ (struct build_version_command *)(buffer + offset);
+ printf("Changing platform from: %d -> %d\n",
+ bvc->platform, platform);
+ bvc->platform = platform;
+ fseek(fp, pos + offset, SEEK_SET);
+ fwrite(buffer + offset, sizeof(struct build_version_command), 1, fp);
+ break;
+ }
+ default:
+ break;
+ }
+ offset += cmd->cmdsize;
+ }
+ fseek(fp, pos, SEEK_SET);
+}
+
+static uint32_t parse_ar_size(char *s, size_t maxlen) {
+ uint32_t ret = 0;
+ for (size_t i = 0; i < maxlen; i++) {
+ if (s[i] < 48 || s[i] > 57) break;
+ ret = ret * 10 + s[i] - 48;
+ }
+ return ret;
+}
+
+static int parse_archive(FILE *fp, int platform) {
+ int pos = ftell(fp);
+
+ char magic[8];
+ fread(&magic, sizeof(magic), 1, fp);
+ if (0 != strncmp(magic, "!\n", 8)) {
+ printf("Doesn't look like an archive. Should start with '!\\n'\n");
+ return 1;
+ }
+
+ ar_header entry;
+ char ident[128];
+ while (fread(&entry, sizeof(ar_header), 1, fp)) {
+ size_t payload = parse_ar_size(entry.size, 10);
+ if (0 == strncmp(entry.ident, "#1/", 3)) {
+ int ident_len = parse_ar_size(entry.ident + 3, 16 - 3);
+ fread(&ident, ident_len, 1, fp);
+ payload -= ident_len;
+ } else {
+ strncpy(ident, entry.ident, 16);
+ }
+ printf("%6zu %s\n", payload, ident);
+ if (0 != strncmp(ident, "__.SYMDEF", 9))
+ patch_object(fp, payload, platform);
+ fseek(fp, payload, SEEK_CUR);
+ }
+ fseek(fp, pos, SEEK_SET);
+ return 0;
+}
+
+int main(int argc, char **argv) {
+ opterr = 0;
+ int c;
+ int platform = PLATFORM_WATCHOS;
+
+ while ((c = getopt(argc, argv, "hs")) != -1) {
+ switch (c) {
+ case 'h':
+ printf("mac2watchos -- tool to rewrite the platform in object files\n");
+ printf("Usage: mac2watchos FILE\n");
+ printf(" -h show this help message\n");
+ printf(" -s set platform to WATCHOSSIMULATOR\n");
+ printf(" by default we set WATCHOS\n");
+ return EXIT_SUCCESS;
+ case 's':
+ platform = PLATFORM_WATCHOSSIMULATOR;
+ break;
+ default:
+ break;
+ }
+ }
+
+ if (optind == argc) {
+ printf("expecting FILE argument.");
+ return EXIT_FAILURE;
+ }
+
+ FILE *ptr = fopen(argv[optind], "rb+");
+ if (NULL == ptr) {
+ printf("Failed to open %s\n", argv[optind]);
+ return EXIT_FAILURE;
+ }
+
+ int ret = parse_archive(ptr, platform);
+ fclose(ptr);
+
+ return ret;
+}
diff --git a/cbits/numa_stubs.c b/cbits/numa_stubs.c
new file mode 100644
index 00000000..ccda989a
--- /dev/null
+++ b/cbits/numa_stubs.c
@@ -0,0 +1,13 @@
+// Stub implementations for libnuma functions.
+// Android doesn't have libnuma, but GHC's RTS references these symbols
+// when statically linked. The RTS checks numa_available() at init time
+// and disables NUMA if it returns -1.
+#include
+
+int numa_available(void) { return -1; } // NUMA not available
+long mbind(void *a, unsigned long b, int c, const unsigned long *d,
+ unsigned long e, unsigned f) { return -1; }
+void numa_bitmask_free(void *bitmask) { (void)bitmask; }
+void *numa_get_mems_allowed(void) { return NULL; }
+int numa_num_configured_nodes(void) { return 1; }
+int numa_run_on_node(int node) { (void)node; return -1; }
diff --git a/cbits/permission_bridge.c b/cbits/permission_bridge.c
new file mode 100644
index 00000000..d65b6169
--- /dev/null
+++ b/cbits/permission_bridge.c
@@ -0,0 +1,51 @@
+/*
+ * Platform-agnostic permission bridge dispatcher.
+ *
+ * Stores function pointers filled by the platform (Android/iOS).
+ * Each permission_* function delegates to the corresponding pointer.
+ * When no callbacks are registered (desktop), functions log to stderr
+ * and auto-grant so that cabal build/test works without native code.
+ *
+ * The opaque Haskell context pointer is threaded through permission_request
+ * rather than stored as a global, allowing multiple contexts to coexist.
+ */
+
+#include "PermissionBridge.h"
+#include
+
+/* Haskell FFI export (called from desktop stub to dispatch result back) */
+extern void haskellOnPermissionResult(void *ctx, int32_t requestId, int32_t statusCode);
+
+static void (*g_request_impl)(void *, int32_t, int32_t) = NULL;
+static int32_t (*g_check_impl)(int32_t) = NULL;
+
+void permission_register_impl(
+ void (*request)(void *, int32_t, int32_t),
+ int32_t (*check)(int32_t))
+{
+ g_request_impl = request;
+ g_check_impl = check;
+}
+
+void permission_request(void *ctx, int32_t permissionCode, int32_t requestId)
+{
+ if (g_request_impl) {
+ g_request_impl(ctx, permissionCode, requestId);
+ return;
+ }
+ /* Desktop stub: auto-grant and dispatch synchronously */
+ fprintf(stderr, "[PermissionBridge stub] permission_request(code=%d, id=%d) -> auto-grant\n",
+ permissionCode, requestId);
+ haskellOnPermissionResult(ctx, requestId, PERMISSION_GRANTED);
+}
+
+int32_t permission_check(int32_t permissionCode)
+{
+ if (g_check_impl) {
+ return g_check_impl(permissionCode);
+ }
+ /* Desktop stub: always granted */
+ fprintf(stderr, "[PermissionBridge stub] permission_check(code=%d) -> granted\n",
+ permissionCode);
+ return PERMISSION_GRANTED;
+}
diff --git a/cbits/permission_bridge_android.c b/cbits/permission_bridge_android.c
new file mode 100644
index 00000000..bc21fd72
--- /dev/null
+++ b/cbits/permission_bridge_android.c
@@ -0,0 +1,107 @@
+/*
+ * Android implementation of the permission bridge callbacks.
+ *
+ * Uses JNI to call Activity.requestPermission() and Activity.checkPermission().
+ * Compiled by NDK clang, not cabal.
+ *
+ * All functions run on the main/UI thread — the same thread that
+ * calls haskellRenderUI from Java.
+ */
+
+#include
+#include
+#include "PermissionBridge.h"
+#include "JniBridge.h"
+
+#define LOG_TAG "PermissionBridge"
+#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
+#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
+
+/* Haskell FFI export (dispatches result back to Haskell callback) */
+extern void haskellOnPermissionResult(void *ctx, int32_t requestId, int32_t statusCode);
+
+/* ---- Global state (valid only on the UI thread) ---- */
+static JNIEnv *g_env = NULL;
+static jobject g_activity = NULL; /* global ref to Activity */
+static void *g_haskell_ctx = NULL; /* stored per-request for async JNI callback */
+
+/* Cached JNI method IDs */
+static jmethodID g_method_requestPermission;
+static jmethodID g_method_checkPermission;
+
+/* ---- Permission bridge implementations ---- */
+
+static void android_permission_request(void *ctx, int32_t permissionCode, int32_t requestId)
+{
+ JNIEnv *env = g_env;
+ if (!env || !g_activity) {
+ LOGE("permission_request: bridge not initialized");
+ return;
+ }
+
+ /* Store context for the async JNI callback */
+ g_haskell_ctx = ctx;
+
+ LOGI("permission_request(code=%d, id=%d)", permissionCode, requestId);
+ (*env)->CallVoidMethod(env, g_activity, g_method_requestPermission,
+ (jint)permissionCode, (jint)requestId);
+}
+
+static int32_t android_permission_check(int32_t permissionCode)
+{
+ JNIEnv *env = g_env;
+ if (!env || !g_activity) {
+ LOGE("permission_check: bridge not initialized");
+ return PERMISSION_DENIED;
+ }
+
+ jint result = (*env)->CallIntMethod(env, g_activity, g_method_checkPermission,
+ (jint)permissionCode);
+ LOGI("permission_check(code=%d) -> %d", permissionCode, result);
+ return (int32_t)result;
+}
+
+/* ---- Public API ---- */
+
+/*
+ * Set up the Android permission bridge. Called from jni_bridge.c
+ * during renderUI (after the Activity is available).
+ * Resolves JNI method IDs and registers callbacks with the
+ * platform-agnostic dispatcher.
+ */
+void setup_android_permission_bridge(JNIEnv *env, jobject activity, void *haskellCtx)
+{
+ g_env = env;
+ g_haskell_ctx = haskellCtx;
+
+ if (!g_activity) {
+ g_activity = (*env)->NewGlobalRef(env, activity);
+ }
+
+ jclass actClass = (*env)->GetObjectClass(env, activity);
+
+ g_method_requestPermission = (*env)->GetMethodID(env, actClass,
+ "requestPermission", "(II)V");
+ g_method_checkPermission = (*env)->GetMethodID(env, actClass,
+ "checkPermission", "(I)I");
+
+ if (!g_method_requestPermission || !g_method_checkPermission) {
+ LOGE("Failed to resolve permission JNI method IDs — permission bridge disabled");
+ (*env)->ExceptionClear(env);
+ return;
+ }
+
+ permission_register_impl(android_permission_request, android_permission_check);
+
+ LOGI("Android permission bridge initialized");
+}
+
+/* ---- JNI callback from Java onRequestPermissionsResult ---- */
+
+JNIEXPORT void JNICALL
+JNI_METHOD(onPermissionResult)(JNIEnv *env, jobject thiz, jint requestId, jint statusCode)
+{
+ g_env = env;
+ LOGI("onPermissionResult(requestId=%d, statusCode=%d)", requestId, statusCode);
+ haskellOnPermissionResult(g_haskell_ctx, (int32_t)requestId, (int32_t)statusCode);
+}
diff --git a/cbits/platform_log.c b/cbits/platform_log.c
new file mode 100644
index 00000000..f63e4d6a
--- /dev/null
+++ b/cbits/platform_log.c
@@ -0,0 +1,34 @@
+/*
+ * Platform-aware logging for HaskellMobile.
+ *
+ * Uses Android logcat, Apple os_log, or stderr depending on platform.
+ * Called from Haskell via FFI to log lifecycle events and diagnostics.
+ */
+
+#ifdef __ANDROID__
+#include
+#elif defined(__APPLE__)
+#include
+
+/* Use a named subsystem so os_log messages appear in `log stream --level info`.
+ * OS_LOG_DEFAULT with OS_LOG_TYPE_INFO may not be surfaced by log stream. */
+static os_log_t haskell_log(void) {
+ static os_log_t log = NULL;
+ if (!log) {
+ log = os_log_create("me.jappie.haskellmobile", "HaskellMobile");
+ }
+ return log;
+}
+#else
+#include
+#endif
+
+void haskellMobileLog(const char *msg) {
+#ifdef __ANDROID__
+ __android_log_print(ANDROID_LOG_INFO, "HaskellMobile", "%s", msg);
+#elif defined(__APPLE__)
+ os_log_with_type(haskell_log(), OS_LOG_TYPE_INFO, "%{public}s", msg);
+#else
+ fprintf(stderr, "[HaskellMobile] %s\n", msg);
+#endif
+}
diff --git a/cbits/run_main.c b/cbits/run_main.c
new file mode 100644
index 00000000..d631140c
--- /dev/null
+++ b/cbits/run_main.c
@@ -0,0 +1,28 @@
+/*
+ * Run the user's Haskell main after hs_init.
+ *
+ * GHC compiles Main.main into ZCMain_main_closure, but does not
+ * make it callable as a C function. This wrapper uses the RTS API
+ * (rts_evalIO) to evaluate that closure and capture the return value,
+ * which is a Ptr AppContext.
+ *
+ * This removes the need for "foreign export ccall" in the user's
+ * Main.hs — they write a plain main :: IO (Ptr AppContext) and we
+ * call it, returning the context pointer to the platform bridge.
+ */
+
+#include "Rts.h"
+
+/* GHC's Z-encoded symbol for :Main.main (the program's main closure) */
+extern StgClosure ZCMain_main_closure;
+
+void* haskellRunMain(void)
+{
+ Capability *cap = rts_lock();
+ HaskellObj result;
+ rts_evalIO(&cap, &ZCMain_main_closure, &result);
+ rts_checkSchedStatus("haskellRunMain", cap);
+ void *ctx = rts_getPtr(result);
+ rts_unlock(cap);
+ return ctx;
+}
diff --git a/cbits/ui_bridge.c b/cbits/ui_bridge.c
new file mode 100644
index 00000000..0c269d76
--- /dev/null
+++ b/cbits/ui_bridge.c
@@ -0,0 +1,116 @@
+/*
+ * Platform-agnostic UI bridge dispatcher.
+ *
+ * Stores a pointer to UIBridgeCallbacks (filled by Android/iOS).
+ * Each ui_* function delegates to the corresponding function pointer.
+ * When no callbacks are registered (desktop), functions log to stderr
+ * and return dummy IDs so that cabal build/test works without native UI.
+ */
+
+#include "UIBridge.h"
+#include
+
+static UIBridgeCallbacks *g_callbacks = NULL;
+static int32_t g_stub_next_id = 1;
+
+void ui_register_callbacks(UIBridgeCallbacks *callbacks)
+{
+ g_callbacks = callbacks;
+}
+
+int32_t ui_create_node(int32_t nodeType)
+{
+ if (g_callbacks && g_callbacks->createNode) {
+ return g_callbacks->createNode(nodeType);
+ }
+ int32_t id = g_stub_next_id++;
+ fprintf(stderr, "[UIBridge stub] createNode(type=%d) -> %d\n", nodeType, id);
+ return id;
+}
+
+void ui_set_str_prop(int32_t nodeId, int32_t propId, const char *value)
+{
+ if (g_callbacks && g_callbacks->setStrProp) {
+ g_callbacks->setStrProp(nodeId, propId, value);
+ return;
+ }
+ fprintf(stderr, "[UIBridge stub] setStrProp(node=%d, prop=%d, value=\"%s\")\n",
+ nodeId, propId, value ? value : "(null)");
+}
+
+void ui_set_num_prop(int32_t nodeId, int32_t propId, double value)
+{
+ if (g_callbacks && g_callbacks->setNumProp) {
+ g_callbacks->setNumProp(nodeId, propId, value);
+ return;
+ }
+ fprintf(stderr, "[UIBridge stub] setNumProp(node=%d, prop=%d, value=%.2f)\n",
+ nodeId, propId, value);
+}
+
+void ui_set_image_data(int32_t nodeId, const uint8_t *data, int32_t length)
+{
+ if (g_callbacks && g_callbacks->setImageData) {
+ g_callbacks->setImageData(nodeId, data, length);
+ return;
+ }
+ fprintf(stderr, "[UIBridge stub] setImageData(node=%d, %d bytes)\n", nodeId, length);
+}
+
+void ui_set_handler(int32_t nodeId, int32_t eventType, int32_t callbackId)
+{
+ if (g_callbacks && g_callbacks->setHandler) {
+ g_callbacks->setHandler(nodeId, eventType, callbackId);
+ return;
+ }
+ fprintf(stderr, "[UIBridge stub] setHandler(node=%d, event=%d, callback=%d)\n",
+ nodeId, eventType, callbackId);
+}
+
+void ui_add_child(int32_t parentId, int32_t childId)
+{
+ if (g_callbacks && g_callbacks->addChild) {
+ g_callbacks->addChild(parentId, childId);
+ return;
+ }
+ fprintf(stderr, "[UIBridge stub] addChild(parent=%d, child=%d)\n",
+ parentId, childId);
+}
+
+void ui_remove_child(int32_t parentId, int32_t childId)
+{
+ if (g_callbacks && g_callbacks->removeChild) {
+ g_callbacks->removeChild(parentId, childId);
+ return;
+ }
+ fprintf(stderr, "[UIBridge stub] removeChild(parent=%d, child=%d)\n",
+ parentId, childId);
+}
+
+void ui_destroy_node(int32_t nodeId)
+{
+ if (g_callbacks && g_callbacks->destroyNode) {
+ g_callbacks->destroyNode(nodeId);
+ return;
+ }
+ fprintf(stderr, "[UIBridge stub] destroyNode(node=%d)\n", nodeId);
+}
+
+void ui_set_root(int32_t nodeId)
+{
+ if (g_callbacks && g_callbacks->setRoot) {
+ g_callbacks->setRoot(nodeId);
+ return;
+ }
+ fprintf(stderr, "[UIBridge stub] setRoot(node=%d)\n", nodeId);
+}
+
+void ui_clear(void)
+{
+ if (g_callbacks && g_callbacks->clear) {
+ g_callbacks->clear();
+ return;
+ }
+ g_stub_next_id = 1;
+ fprintf(stderr, "[UIBridge stub] clear()\n");
+}
diff --git a/cbits/ui_bridge_android.c b/cbits/ui_bridge_android.c
new file mode 100644
index 00000000..ba9cc808
--- /dev/null
+++ b/cbits/ui_bridge_android.c
@@ -0,0 +1,792 @@
+/*
+ * Android implementation of the UI bridge callbacks.
+ *
+ * Uses JNI to create Android views (TextView, Button, LinearLayout)
+ * and manage the view hierarchy. Compiled by NDK clang, not cabal.
+ *
+ * All functions run on the main/UI thread — the same thread that
+ * calls haskellRenderUI from Java.
+ */
+
+#include
+#include
+#include
+#include
+#include "UIBridge.h"
+
+#define LOG_TAG "UIBridge"
+#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
+#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
+
+/* --- Node pool configuration ---
+ *
+ * Two compile-time flags control the pool strategy:
+ * -DMAX_NODES=N Override the static pool size (default 256).
+ * -DDYNAMIC_NODE_POOL Use malloc/realloc; MAX_NODES is ignored.
+ *
+ * Re-renders clear all nodes, so the pool only bounds a single frame. */
+#ifdef DYNAMIC_NODE_POOL
+ static jobject *g_nodes = NULL;
+ static int32_t g_pool_capacity = 0;
+ #define INITIAL_POOL_SIZE 256
+#else
+ #ifndef MAX_NODES
+ #define MAX_NODES 256
+ #endif
+ static jobject g_nodes[MAX_NODES];
+#endif
+static int32_t g_next_node_id = 1;
+
+/* Haskell FFI exports (declared here since this file is compiled by NDK) */
+extern void haskellOnUIEvent(void *ctx, int callbackId);
+extern void haskellOnUITextChange(void *ctx, int callbackId, const char *text);
+
+/* ---- Global state (valid only on the UI thread) ---- */
+static JNIEnv *g_env = NULL;
+static jobject g_activity = NULL; /* global ref to Activity */
+
+/* ---- Per-button callback IDs stored as view tags ---- */
+
+/* Cached JNI class/method IDs (resolved once in setup) */
+static jclass g_class_TextView;
+static jclass g_class_Button;
+static jclass g_class_EditText;
+static jclass g_class_LinearLayout;
+static jclass g_class_ScrollView;
+static jclass g_class_ImageView;
+static jclass g_class_BitmapFactory;
+static jclass g_class_ViewGroup;
+static jclass g_class_ViewGroup_LayoutParams;
+static jclass g_class_Integer;
+
+static jmethodID g_ctor_TextView;
+static jmethodID g_ctor_Button;
+static jmethodID g_ctor_EditText;
+static jmethodID g_ctor_LinearLayout;
+static jmethodID g_ctor_ScrollView;
+static jmethodID g_ctor_ImageView;
+static jmethodID g_ctor_ViewGroup_LayoutParams;
+static jmethodID g_ctor_Integer;
+
+static jmethodID g_method_setText;
+static jmethodID g_method_setHint;
+static jmethodID g_method_setOrientation;
+static jmethodID g_method_addView;
+static jmethodID g_method_removeView;
+static jmethodID g_method_removeAllViews;
+static jmethodID g_method_setContentView;
+static jmethodID g_method_setTag;
+static jmethodID g_method_getTag;
+static jmethodID g_method_intValue;
+static jmethodID g_method_setOnClickListener;
+static jmethodID g_method_registerTextWatcher;
+static jmethodID g_method_setInputType;
+static jmethodID g_method_setTextSize;
+static jmethodID g_method_setPadding;
+static jmethodID g_method_setGravity_TextView;
+static jmethodID g_method_setGravity_LinearLayout;
+static jmethodID g_method_setLayoutParams;
+static jmethodID g_method_setTextColor;
+static jmethodID g_method_setBackgroundColor;
+static jmethodID g_method_setImageBitmap;
+static jmethodID g_method_setScaleType;
+static jmethodID g_method_decodeByteArray;
+static jmethodID g_method_decodeFile;
+
+/* LinearLayout orientation constants */
+static jint ORIENTATION_VERTICAL = 1;
+static jint ORIENTATION_HORIZONTAL = 0;
+
+/* ---- Forward declarations ---- */
+static int32_t android_create_node(int32_t nodeType);
+static void android_set_str_prop(int32_t nodeId, int32_t propId, const char *value);
+static void android_set_num_prop(int32_t nodeId, int32_t propId, double value);
+static void android_set_image_data(int32_t nodeId, const uint8_t *data, int32_t length);
+static void android_set_handler(int32_t nodeId, int32_t eventType, int32_t callbackId);
+static void android_add_child(int32_t parentId, int32_t childId);
+static void android_remove_child(int32_t parentId, int32_t childId);
+static void android_destroy_node(int32_t nodeId);
+static void android_set_root(int32_t nodeId);
+static void android_clear(void);
+
+static UIBridgeCallbacks g_android_callbacks = {
+ .createNode = android_create_node,
+ .setStrProp = android_set_str_prop,
+ .setNumProp = android_set_num_prop,
+ .setImageData = android_set_image_data,
+ .setHandler = android_set_handler,
+ .addChild = android_add_child,
+ .removeChild = android_remove_child,
+ .destroyNode = android_destroy_node,
+ .setRoot = android_set_root,
+ .clear = android_clear,
+};
+
+/* ---- JNI class/method resolution ---- */
+static int resolve_jni_ids(JNIEnv *env, jobject activity)
+{
+ /* Resolve classes */
+ jclass cls;
+
+ cls = (*env)->FindClass(env, "android/widget/TextView");
+ if (!cls) return -1;
+ g_class_TextView = (*env)->NewGlobalRef(env, cls);
+
+ cls = (*env)->FindClass(env, "android/widget/Button");
+ if (!cls) return -1;
+ g_class_Button = (*env)->NewGlobalRef(env, cls);
+
+ cls = (*env)->FindClass(env, "android/widget/EditText");
+ if (!cls) return -1;
+ g_class_EditText = (*env)->NewGlobalRef(env, cls);
+
+ cls = (*env)->FindClass(env, "android/widget/LinearLayout");
+ if (!cls) return -1;
+ g_class_LinearLayout = (*env)->NewGlobalRef(env, cls);
+
+ cls = (*env)->FindClass(env, "android/widget/ScrollView");
+ if (!cls) return -1;
+ g_class_ScrollView = (*env)->NewGlobalRef(env, cls);
+
+ cls = (*env)->FindClass(env, "android/widget/ImageView");
+ if (!cls) return -1;
+ g_class_ImageView = (*env)->NewGlobalRef(env, cls);
+
+ cls = (*env)->FindClass(env, "android/graphics/BitmapFactory");
+ if (!cls) return -1;
+ g_class_BitmapFactory = (*env)->NewGlobalRef(env, cls);
+
+ cls = (*env)->FindClass(env, "android/view/ViewGroup");
+ if (!cls) return -1;
+ g_class_ViewGroup = (*env)->NewGlobalRef(env, cls);
+
+ cls = (*env)->FindClass(env, "android/view/ViewGroup$LayoutParams");
+ if (!cls) return -1;
+ g_class_ViewGroup_LayoutParams = (*env)->NewGlobalRef(env, cls);
+
+ cls = (*env)->FindClass(env, "java/lang/Integer");
+ if (!cls) return -1;
+ g_class_Integer = (*env)->NewGlobalRef(env, cls);
+
+ /* Resolve constructors */
+ g_ctor_TextView = (*env)->GetMethodID(env, g_class_TextView,
+ "", "(Landroid/content/Context;)V");
+ g_ctor_Button = (*env)->GetMethodID(env, g_class_Button,
+ "", "(Landroid/content/Context;)V");
+ g_ctor_EditText = (*env)->GetMethodID(env, g_class_EditText,
+ "", "(Landroid/content/Context;)V");
+ g_ctor_LinearLayout = (*env)->GetMethodID(env, g_class_LinearLayout,
+ "", "(Landroid/content/Context;)V");
+ g_ctor_ScrollView = (*env)->GetMethodID(env, g_class_ScrollView,
+ "", "(Landroid/content/Context;)V");
+ g_ctor_ImageView = (*env)->GetMethodID(env, g_class_ImageView,
+ "", "(Landroid/content/Context;)V");
+ g_ctor_ViewGroup_LayoutParams = (*env)->GetMethodID(env,
+ g_class_ViewGroup_LayoutParams, "", "(II)V");
+ g_ctor_Integer = (*env)->GetMethodID(env, g_class_Integer,
+ "", "(I)V");
+
+ /* Resolve methods */
+ g_method_setText = (*env)->GetMethodID(env, g_class_TextView,
+ "setText", "(Ljava/lang/CharSequence;)V");
+ g_method_setHint = (*env)->GetMethodID(env, g_class_TextView,
+ "setHint", "(Ljava/lang/CharSequence;)V");
+ g_method_setOrientation = (*env)->GetMethodID(env, g_class_LinearLayout,
+ "setOrientation", "(I)V");
+ g_method_addView = (*env)->GetMethodID(env, g_class_ViewGroup,
+ "addView", "(Landroid/view/View;)V");
+ g_method_removeView = (*env)->GetMethodID(env, g_class_ViewGroup,
+ "removeView", "(Landroid/view/View;)V");
+ g_method_removeAllViews = (*env)->GetMethodID(env, g_class_ViewGroup,
+ "removeAllViews", "()V");
+
+ /* Activity.setContentView(View) */
+ jclass activityClass = (*env)->GetObjectClass(env, activity);
+ g_method_setContentView = (*env)->GetMethodID(env, activityClass,
+ "setContentView", "(Landroid/view/View;)V");
+
+ /* View.setTag / getTag for storing callback IDs */
+ jclass viewClass = (*env)->FindClass(env, "android/view/View");
+ g_method_setTag = (*env)->GetMethodID(env, viewClass,
+ "setTag", "(Ljava/lang/Object;)V");
+ g_method_getTag = (*env)->GetMethodID(env, viewClass,
+ "getTag", "()Ljava/lang/Object;");
+
+ g_method_intValue = (*env)->GetMethodID(env, g_class_Integer,
+ "intValue", "()I");
+
+ /* View.setOnClickListener(OnClickListener) — Activity implements it */
+ g_method_setOnClickListener = (*env)->GetMethodID(env, viewClass,
+ "setOnClickListener", "(Landroid/view/View$OnClickListener;)V");
+
+ /* Activity.registerTextWatcher(EditText) — our custom Java method */
+ jclass actClass = (*env)->GetObjectClass(env, activity);
+ g_method_registerTextWatcher = (*env)->GetMethodID(env, actClass,
+ "registerTextWatcher", "(Landroid/widget/EditText;)V");
+ if (!g_method_registerTextWatcher) {
+ LOGE("registerTextWatcher not found — text input events disabled");
+ (*env)->ExceptionClear(env);
+ }
+
+ /* EditText.setInputType(int) */
+ g_method_setInputType = (*env)->GetMethodID(env, g_class_EditText,
+ "setInputType", "(I)V");
+
+ /* TextView.setTextSize(float) — sets size in scaled pixels */
+ g_method_setTextSize = (*env)->GetMethodID(env, g_class_TextView,
+ "setTextSize", "(F)V");
+
+ /* View.setPadding(int,int,int,int) — sets padding in pixels */
+ g_method_setPadding = (*env)->GetMethodID(env, viewClass,
+ "setPadding", "(IIII)V");
+
+ /* TextView.setGravity(int) — sets text alignment */
+ g_method_setGravity_TextView = (*env)->GetMethodID(env, g_class_TextView,
+ "setGravity", "(I)V");
+
+ /* LinearLayout.setGravity(int) — centers children */
+ g_method_setGravity_LinearLayout = (*env)->GetMethodID(env, g_class_LinearLayout,
+ "setGravity", "(I)V");
+
+ /* View.setLayoutParams(ViewGroup.LayoutParams) — needed to set MATCH_PARENT width */
+ g_method_setLayoutParams = (*env)->GetMethodID(env, viewClass,
+ "setLayoutParams", "(Landroid/view/ViewGroup$LayoutParams;)V");
+
+ /* TextView.setTextColor(int) — sets ARGB text color */
+ g_method_setTextColor = (*env)->GetMethodID(env, g_class_TextView,
+ "setTextColor", "(I)V");
+
+ /* View.setBackgroundColor(int) — sets ARGB background color */
+ g_method_setBackgroundColor = (*env)->GetMethodID(env, viewClass,
+ "setBackgroundColor", "(I)V");
+
+ /* ImageView.setImageBitmap(Bitmap) */
+ g_method_setImageBitmap = (*env)->GetMethodID(env, g_class_ImageView,
+ "setImageBitmap", "(Landroid/graphics/Bitmap;)V");
+
+ /* ImageView.setScaleType(ImageView.ScaleType) */
+ g_method_setScaleType = (*env)->GetMethodID(env, g_class_ImageView,
+ "setScaleType", "(Landroid/widget/ImageView$ScaleType;)V");
+
+ /* BitmapFactory.decodeByteArray(byte[], int, int) -> Bitmap */
+ g_method_decodeByteArray = (*env)->GetStaticMethodID(env, g_class_BitmapFactory,
+ "decodeByteArray", "([BII)Landroid/graphics/Bitmap;");
+
+ /* BitmapFactory.decodeFile(String) -> Bitmap */
+ g_method_decodeFile = (*env)->GetStaticMethodID(env, g_class_BitmapFactory,
+ "decodeFile", "(Ljava/lang/String;)Landroid/graphics/Bitmap;");
+
+ /* Clear any pending exception from optional method lookups above */
+ if ((*env)->ExceptionCheck(env)) {
+ LOGE("JNI exception during resolve_jni_ids — clearing");
+ (*env)->ExceptionClear(env);
+ }
+
+ return 0;
+}
+
+/* ---- Node pool helpers ---- */
+
+#ifdef DYNAMIC_NODE_POOL
+/* Grow the pool so that nodeId < g_pool_capacity. */
+static int ensure_pool_capacity(int32_t needed)
+{
+ if (needed < g_pool_capacity) return 0;
+ int32_t new_cap = g_pool_capacity ? g_pool_capacity : INITIAL_POOL_SIZE;
+ while (new_cap <= needed) new_cap *= 2;
+ jobject *new_pool = realloc(g_nodes, (size_t)new_cap * sizeof(jobject));
+ if (!new_pool) {
+ LOGE("Node pool realloc failed (requested %d slots)", new_cap);
+ return -1;
+ }
+ memset(new_pool + g_pool_capacity, 0,
+ (size_t)(new_cap - g_pool_capacity) * sizeof(jobject));
+ g_nodes = new_pool;
+ g_pool_capacity = new_cap;
+ return 0;
+}
+#endif
+
+static jobject get_node(int32_t nodeId)
+{
+#ifdef DYNAMIC_NODE_POOL
+ if (nodeId < 1 || nodeId >= g_pool_capacity) return NULL;
+#else
+ if (nodeId < 1 || nodeId >= MAX_NODES) return NULL;
+#endif
+ return g_nodes[nodeId];
+}
+
+/* ---- Hex color parser ---- */
+
+/*
+ * Parse a hex color string (#RGB, #RRGGBB, or #AARRGGBB) into a jint ARGB value.
+ * Returns 0 (transparent black) on invalid input.
+ */
+static jint parse_hex_color(const char *hex)
+{
+ if (!hex || hex[0] != '#') return 0;
+ const char *digits = hex + 1;
+ size_t len = strlen(digits);
+ unsigned long raw = strtoul(digits, NULL, 16);
+
+ switch (len) {
+ case 3: {
+ /* #RGB -> #FFRRGGBB (expand each nibble) */
+ unsigned int r = (raw >> 8) & 0xF;
+ unsigned int g = (raw >> 4) & 0xF;
+ unsigned int b = raw & 0xF;
+ return (jint)(0xFF000000u | (r * 0x11u) << 16 | (g * 0x11u) << 8 | (b * 0x11u));
+ }
+ case 6:
+ /* #RRGGBB -> #FFRRGGBB */
+ return (jint)(0xFF000000u | (raw & 0xFFFFFFu));
+ case 8:
+ /* #AARRGGBB — already complete */
+ return (jint)raw;
+ default:
+ return 0;
+ }
+}
+
+/* ---- Callback implementation ---- */
+
+static int32_t android_create_node(int32_t nodeType)
+{
+#ifdef DYNAMIC_NODE_POOL
+ if (ensure_pool_capacity(g_next_node_id) != 0) {
+ LOGE("Node pool exhausted (realloc failed at %d)", g_next_node_id);
+ return 0;
+ }
+#else
+ if (g_next_node_id >= MAX_NODES) {
+ LOGE("Node pool exhausted (max %d)", MAX_NODES);
+ return 0;
+ }
+#endif
+
+ JNIEnv *env = g_env;
+ jobject view = NULL;
+
+ switch (nodeType) {
+ case UI_NODE_TEXT:
+ view = (*env)->NewObject(env, g_class_TextView, g_ctor_TextView, g_activity);
+ break;
+ case UI_NODE_BUTTON:
+ view = (*env)->NewObject(env, g_class_Button, g_ctor_Button, g_activity);
+ break;
+ case UI_NODE_COLUMN: {
+ view = (*env)->NewObject(env, g_class_LinearLayout, g_ctor_LinearLayout, g_activity);
+ (*env)->CallVoidMethod(env, view, g_method_setOrientation, ORIENTATION_VERTICAL);
+ break;
+ }
+ case UI_NODE_ROW: {
+ view = (*env)->NewObject(env, g_class_LinearLayout, g_ctor_LinearLayout, g_activity);
+ (*env)->CallVoidMethod(env, view, g_method_setOrientation, ORIENTATION_HORIZONTAL);
+ break;
+ }
+ case UI_NODE_TEXT_INPUT:
+ view = (*env)->NewObject(env, g_class_EditText, g_ctor_EditText, g_activity);
+ break;
+ case UI_NODE_SCROLL_VIEW:
+ view = (*env)->NewObject(env, g_class_ScrollView, g_ctor_ScrollView, g_activity);
+ break;
+ case UI_NODE_IMAGE:
+ view = (*env)->NewObject(env, g_class_ImageView, g_ctor_ImageView, g_activity);
+ break;
+ default:
+ LOGE("Unknown node type: %d", nodeType);
+ return 0;
+ }
+
+ if (!view) {
+ LOGE("Failed to create view for type %d", nodeType);
+ return 0;
+ }
+
+ int32_t nodeId = g_next_node_id++;
+ g_nodes[nodeId] = (*env)->NewGlobalRef(env, view);
+ (*env)->DeleteLocalRef(env, view);
+
+ LOGI("createNode(type=%d) -> %d", nodeType, nodeId);
+ return nodeId;
+}
+
+static void android_set_str_prop(int32_t nodeId, int32_t propId, const char *value)
+{
+ JNIEnv *env = g_env;
+ jobject view = get_node(nodeId);
+ if (!view) return;
+
+ switch (propId) {
+ case UI_PROP_TEXT: {
+ LOGI("setStrProp(node=%d, text=\"%s\")", nodeId, value);
+ jstring jstr = (*env)->NewStringUTF(env, value);
+ (*env)->CallVoidMethod(env, view, g_method_setText, jstr);
+ (*env)->DeleteLocalRef(env, jstr);
+ break;
+ }
+ case UI_PROP_HINT: {
+ LOGI("setStrProp(node=%d, hint=\"%s\")", nodeId, value);
+ jstring jstr = (*env)->NewStringUTF(env, value);
+ (*env)->CallVoidMethod(env, view, g_method_setHint, jstr);
+ (*env)->DeleteLocalRef(env, jstr);
+ break;
+ }
+ case UI_PROP_COLOR: {
+ LOGI("setStrProp(node=%d, color=\"%s\")", nodeId, value);
+ if ((*env)->IsInstanceOf(env, view, g_class_TextView)) {
+ jint argb = parse_hex_color(value);
+ (*env)->CallVoidMethod(env, view, g_method_setTextColor, argb);
+ }
+ break;
+ }
+ case UI_PROP_BG_COLOR: {
+ LOGI("setStrProp(node=%d, bgColor=\"%s\")", nodeId, value);
+ jint argb = parse_hex_color(value);
+ (*env)->CallVoidMethod(env, view, g_method_setBackgroundColor, argb);
+ break;
+ }
+ case UI_PROP_IMAGE_RESOURCE: {
+ LOGI("setStrProp(node=%d, imageResource=\"%s\")", nodeId, value);
+ /* Resource lookup: getResources().getIdentifier(name, "drawable", packageName) */
+ if ((*env)->IsInstanceOf(env, view, g_class_ImageView)) {
+ jclass actClass = (*env)->GetObjectClass(env, g_activity);
+ jmethodID getResources = (*env)->GetMethodID(env, actClass,
+ "getResources", "()Landroid/content/res/Resources;");
+ jmethodID getPackageName = (*env)->GetMethodID(env, actClass,
+ "getPackageName", "()Ljava/lang/String;");
+ jobject resources = (*env)->CallObjectMethod(env, g_activity, getResources);
+ jstring packageName = (*env)->CallObjectMethod(env, g_activity, getPackageName);
+ jclass resClass = (*env)->GetObjectClass(env, resources);
+ jmethodID getIdentifier = (*env)->GetMethodID(env, resClass,
+ "getIdentifier", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I");
+ jmethodID getDrawable = (*env)->GetMethodID(env, resClass,
+ "getDrawable", "(I)Landroid/graphics/drawable/Drawable;");
+ jstring jname = (*env)->NewStringUTF(env, value);
+ jstring jtype = (*env)->NewStringUTF(env, "drawable");
+ jint resId = (*env)->CallIntMethod(env, resources, getIdentifier,
+ jname, jtype, packageName);
+ if (resId != 0) {
+ jobject drawable = (*env)->CallObjectMethod(env, resources, getDrawable, resId);
+ jmethodID setImageDrawable = (*env)->GetMethodID(env, g_class_ImageView,
+ "setImageDrawable", "(Landroid/graphics/drawable/Drawable;)V");
+ (*env)->CallVoidMethod(env, view, setImageDrawable, drawable);
+ (*env)->DeleteLocalRef(env, drawable);
+ } else {
+ LOGE("Resource not found: %s", value);
+ }
+ (*env)->DeleteLocalRef(env, jname);
+ (*env)->DeleteLocalRef(env, jtype);
+ (*env)->DeleteLocalRef(env, packageName);
+ (*env)->DeleteLocalRef(env, resources);
+ }
+ break;
+ }
+ case UI_PROP_IMAGE_FILE: {
+ LOGI("setStrProp(node=%d, imageFile=\"%s\")", nodeId, value);
+ if ((*env)->IsInstanceOf(env, view, g_class_ImageView)) {
+ jstring jpath = (*env)->NewStringUTF(env, value);
+ jobject bitmap = (*env)->CallStaticObjectMethod(env,
+ g_class_BitmapFactory, g_method_decodeFile, jpath);
+ if (bitmap) {
+ (*env)->CallVoidMethod(env, view, g_method_setImageBitmap, bitmap);
+ (*env)->DeleteLocalRef(env, bitmap);
+ } else {
+ LOGE("Failed to decode file: %s", value);
+ }
+ (*env)->DeleteLocalRef(env, jpath);
+ }
+ break;
+ }
+ default:
+ LOGI("setStrProp: unknown propId %d", propId);
+ break;
+ }
+}
+
+static void android_set_num_prop(int32_t nodeId, int32_t propId, double value)
+{
+ JNIEnv *env = g_env;
+ jobject view = get_node(nodeId);
+ if (!view) return;
+
+ switch (propId) {
+ case UI_PROP_FONT_SIZE:
+ /* setTextSize only makes sense on TextView subclasses */
+ if ((*env)->IsInstanceOf(env, view, g_class_TextView)) {
+ (*env)->CallVoidMethod(env, view, g_method_setTextSize, (jfloat)value);
+ LOGI("setNumProp(node=%d, fontSize=%.1f)", nodeId, value);
+ } else {
+ LOGI("setNumProp: fontSize ignored on non-TextView node=%d", nodeId);
+ }
+ break;
+ case UI_PROP_PADDING: {
+ jint px = (jint)value;
+ (*env)->CallVoidMethod(env, view, g_method_setPadding, px, px, px, px);
+ LOGI("setNumProp(node=%d, padding=%d)", nodeId, px);
+ break;
+ }
+ case UI_PROP_INPUT_TYPE: {
+ /* Haskell 0 = InputText -> Android TYPE_CLASS_TEXT (1)
+ * Haskell 1 = InputNumber -> Android TYPE_CLASS_NUMBER |
+ * TYPE_NUMBER_FLAG_DECIMAL (8194)
+ */
+ jint androidType;
+ if ((int)value == 1) {
+ androidType = 8194; /* TYPE_CLASS_NUMBER | TYPE_NUMBER_FLAG_DECIMAL */
+ } else {
+ androidType = 1; /* TYPE_CLASS_TEXT */
+ }
+ (*env)->CallVoidMethod(env, view, g_method_setInputType, androidType);
+ LOGI("setNumProp(node=%d, inputType=%d, android=%d)", nodeId, (int)value, androidType);
+ break;
+ }
+ case UI_PROP_GRAVITY: {
+ /* Haskell 0 = AlignStart -> Gravity.START (0x00800003)
+ * Haskell 1 = AlignCenter -> Gravity.CENTER_HORIZONTAL (1)
+ * Haskell 2 = AlignEnd -> Gravity.END (0x00800005)
+ */
+ jint gravity;
+ switch ((int)value) {
+ case 1: gravity = 1; break; /* CENTER_HORIZONTAL */
+ case 2: gravity = 0x00800005; break; /* END */
+ default: gravity = 0x00800003; break; /* START */
+ }
+ if ((*env)->IsInstanceOf(env, view, g_class_TextView)) {
+ (*env)->CallVoidMethod(env, view, g_method_setGravity_TextView, gravity);
+ /* Set width to MATCH_PARENT so gravity has room to take effect */
+ jobject layoutParams = (*env)->NewObject(env,
+ g_class_ViewGroup_LayoutParams, g_ctor_ViewGroup_LayoutParams,
+ (jint)-1, (jint)-2); /* MATCH_PARENT, WRAP_CONTENT */
+ (*env)->CallVoidMethod(env, view, g_method_setLayoutParams, layoutParams);
+ (*env)->DeleteLocalRef(env, layoutParams);
+ } else if ((*env)->IsInstanceOf(env, view, g_class_LinearLayout)) {
+ (*env)->CallVoidMethod(env, view, g_method_setGravity_LinearLayout, gravity);
+ }
+ LOGI("setNumProp(node=%d, gravity=%d)", nodeId, gravity);
+ break;
+ }
+ case UI_PROP_SCALE_TYPE: {
+ /* Haskell 0 = ScaleFit -> FIT_CENTER
+ * Haskell 1 = ScaleFill -> CENTER_CROP
+ * Haskell 2 = ScaleNone -> CENTER
+ */
+ if ((*env)->IsInstanceOf(env, view, g_class_ImageView)) {
+ jclass scaleTypeClass = (*env)->FindClass(env, "android/widget/ImageView$ScaleType");
+ const char *fieldName;
+ switch ((int)value) {
+ case 1: fieldName = "CENTER_CROP"; break;
+ case 2: fieldName = "CENTER"; break;
+ default: fieldName = "FIT_CENTER"; break;
+ }
+ jfieldID field = (*env)->GetStaticFieldID(env, scaleTypeClass,
+ fieldName, "Landroid/widget/ImageView$ScaleType;");
+ jobject scaleType = (*env)->GetStaticObjectField(env, scaleTypeClass, field);
+ (*env)->CallVoidMethod(env, view, g_method_setScaleType, scaleType);
+ (*env)->DeleteLocalRef(env, scaleType);
+ (*env)->DeleteLocalRef(env, scaleTypeClass);
+ }
+ LOGI("setNumProp(node=%d, scaleType=%d)", nodeId, (int)value);
+ break;
+ }
+ default:
+ LOGI("setNumProp: unknown propId %d", propId);
+ break;
+ }
+}
+
+static void android_set_image_data(int32_t nodeId, const uint8_t *data, int32_t length)
+{
+ JNIEnv *env = g_env;
+ jobject view = get_node(nodeId);
+ if (!view) return;
+ if (!(*env)->IsInstanceOf(env, view, g_class_ImageView)) return;
+
+ /* Create Java byte[] and copy data */
+ jbyteArray jdata = (*env)->NewByteArray(env, length);
+ (*env)->SetByteArrayRegion(env, jdata, 0, length, (const jbyte *)data);
+
+ /* BitmapFactory.decodeByteArray(byte[], offset, length) */
+ jobject bitmap = (*env)->CallStaticObjectMethod(env,
+ g_class_BitmapFactory, g_method_decodeByteArray, jdata, (jint)0, (jint)length);
+ if (bitmap) {
+ (*env)->CallVoidMethod(env, view, g_method_setImageBitmap, bitmap);
+ (*env)->DeleteLocalRef(env, bitmap);
+ } else {
+ LOGE("setImageData: BitmapFactory.decodeByteArray failed (node=%d, %d bytes)", nodeId, length);
+ }
+ (*env)->DeleteLocalRef(env, jdata);
+
+ LOGI("setImageData(node=%d, %d bytes)", nodeId, length);
+}
+
+static void android_set_handler(int32_t nodeId, int32_t eventType, int32_t callbackId)
+{
+ JNIEnv *env = g_env;
+ jobject view = get_node(nodeId);
+ if (!view) return;
+
+ /* Store callbackId as the view's tag (Integer) */
+ jobject tagObj = (*env)->NewObject(env, g_class_Integer, g_ctor_Integer, callbackId);
+ (*env)->CallVoidMethod(env, view, g_method_setTag, tagObj);
+ (*env)->DeleteLocalRef(env, tagObj);
+
+ switch (eventType) {
+ case UI_EVENT_CLICK:
+ /* Register the Activity (which implements OnClickListener) as handler */
+ (*env)->CallVoidMethod(env, view, g_method_setOnClickListener, g_activity);
+ LOGI("setHandler(node=%d, click, callback=%d)", nodeId, callbackId);
+ break;
+ case UI_EVENT_TEXT_CHANGE:
+ /* Register a TextWatcher via our Java helper */
+ if (g_method_registerTextWatcher) {
+ (*env)->CallVoidMethod(env, g_activity, g_method_registerTextWatcher, view);
+ LOGI("setHandler(node=%d, textChange, callback=%d)", nodeId, callbackId);
+ } else {
+ LOGE("setHandler: registerTextWatcher unavailable, skipping node=%d", nodeId);
+ }
+ break;
+ default:
+ LOGI("setHandler: unknown eventType %d", eventType);
+ break;
+ }
+}
+
+static void android_add_child(int32_t parentId, int32_t childId)
+{
+ JNIEnv *env = g_env;
+ jobject parent = get_node(parentId);
+ jobject child = get_node(childId);
+ if (!parent || !child) return;
+
+ (*env)->CallVoidMethod(env, parent, g_method_addView, child);
+}
+
+static void android_remove_child(int32_t parentId, int32_t childId)
+{
+ JNIEnv *env = g_env;
+ jobject parent = get_node(parentId);
+ jobject child = get_node(childId);
+ if (!parent || !child) return;
+
+ (*env)->CallVoidMethod(env, parent, g_method_removeView, child);
+}
+
+static void android_destroy_node(int32_t nodeId)
+{
+ JNIEnv *env = g_env;
+ jobject view = get_node(nodeId);
+ if (!view) return;
+
+ (*env)->DeleteGlobalRef(env, view);
+ g_nodes[nodeId] = NULL;
+}
+
+static void android_set_root(int32_t nodeId)
+{
+ JNIEnv *env = g_env;
+ jobject view = get_node(nodeId);
+ if (!view) return;
+
+ (*env)->CallVoidMethod(env, g_activity, g_method_setContentView, view);
+ LOGI("setRoot(node=%d)", nodeId);
+}
+
+static void android_clear(void)
+{
+ JNIEnv *env = g_env;
+ for (int i = 1; i < g_next_node_id; i++) {
+ if (g_nodes[i]) {
+ (*env)->DeleteGlobalRef(env, g_nodes[i]);
+ g_nodes[i] = NULL;
+ }
+ }
+ g_next_node_id = 1;
+ /* Dynamic mode: keep the allocation to avoid malloc/free churn each frame.
+ * Static mode: nothing extra to do — array is stack-allocated. */
+ LOGI("clear()");
+}
+
+/* ---- Public API ---- */
+
+/*
+ * Set up the Android UI bridge. Called from Java before haskellRenderUI.
+ * Resolves JNI IDs and registers callbacks with the platform-agnostic
+ * dispatcher.
+ */
+void setup_android_ui_bridge(JNIEnv *env, jobject activity, void *haskellCtx)
+{
+ g_env = env;
+ g_activity = (*env)->NewGlobalRef(env, activity);
+ (void)haskellCtx; /* context is now owned by jni_bridge.c */
+
+#ifdef DYNAMIC_NODE_POOL
+ if (!g_nodes) {
+ g_pool_capacity = INITIAL_POOL_SIZE;
+ g_nodes = calloc((size_t)g_pool_capacity, sizeof(jobject));
+ } else {
+ memset(g_nodes, 0, (size_t)g_pool_capacity * sizeof(jobject));
+ }
+#else
+ memset(g_nodes, 0, sizeof(g_nodes));
+#endif
+ g_next_node_id = 1;
+
+ if (resolve_jni_ids(env, activity) != 0) {
+ LOGE("Failed to resolve JNI IDs for UI bridge");
+ return;
+ }
+
+ ui_register_callbacks(&g_android_callbacks);
+ LOGI("Android UI bridge initialized");
+}
+
+/*
+ * Handle a click event from Java. Looks up the callbackId from the
+ * view's tag and dispatches to Haskell.
+ */
+void android_handle_click(JNIEnv *env, jobject view, void *haskellCtx)
+{
+ /* Update g_env in case we're called from a different JNI attach */
+ g_env = env;
+
+ jobject tagObj = (*env)->CallObjectMethod(env, view, g_method_getTag);
+ if (!tagObj) {
+ LOGI("Click on view with no tag — ignoring");
+ return;
+ }
+
+ jint callbackId = (*env)->CallIntMethod(env, tagObj, g_method_intValue);
+ (*env)->DeleteLocalRef(env, tagObj);
+
+ LOGI("Click dispatched: callbackId=%d", callbackId);
+ haskellOnUIEvent(haskellCtx, callbackId);
+}
+
+/*
+ * Handle a text change event from Java. Looks up the callbackId from
+ * the view's tag and dispatches to Haskell with the new text.
+ * Does NOT trigger a re-render (avoids EditText cursor/flicker).
+ */
+void android_handle_text_change(JNIEnv *env, jobject view, jstring text, void *haskellCtx)
+{
+ g_env = env;
+
+ jobject tagObj = (*env)->CallObjectMethod(env, view, g_method_getTag);
+ if (!tagObj) {
+ LOGI("Text change on view with no tag — ignoring");
+ return;
+ }
+
+ jint callbackId = (*env)->CallIntMethod(env, tagObj, g_method_intValue);
+ (*env)->DeleteLocalRef(env, tagObj);
+
+ const char *ctext = (*env)->GetStringUTFChars(env, text, NULL);
+ if (!ctext) return;
+
+ LOGI("Text change dispatched: callbackId=%d, text=\"%s\"", callbackId, ctext);
+ haskellOnUITextChange(haskellCtx, callbackId, ctext);
+
+ (*env)->ReleaseStringUTFChars(env, text, ctext);
+}
diff --git a/default.nix b/default.nix
index 9e6b8117..1542de09 100644
--- a/default.nix
+++ b/default.nix
@@ -1,4 +1,4 @@
{ hpkgs ? import ./nix/hpkgs.nix {}
,
}:
-hpkgs.template-project
+hpkgs.haskell-mobile-project
diff --git a/docs/cross-compilation-gaps.md b/docs/cross-compilation-gaps.md
new file mode 100644
index 00000000..75f8ce4d
--- /dev/null
+++ b/docs/cross-compilation-gaps.md
@@ -0,0 +1,150 @@
+# Why Haskell-Mobile Needs Nix Hacks: What Cabal Is Missing
+
+## Executive Summary
+
+The haskell-mobile project uses **~20 distinct workarounds** in its Nix build system to cross-compile Haskell to Android, iOS, and watchOS. These fall into categories that reveal fundamental gaps in both GHC and Cabal's cross-compilation story. The core problem: **Cabal was designed for native builds and has never been seriously adapted for mobile cross-compilation**.
+
+---
+
+## The 6 Most Pressing Issues
+
+### 1. `--with-PROG` Not Propagated to Dependencies ([cabal#4939](https://github.com/haskell/cabal/issues/4939))
+
+**The hack:** Nix creates symlink farms (`ln -s cross-ghc $TMPDIR/cross-bin/ghc`) and patches `build-tool-depends: hsc2hs` out of every dependency's `.cabal` file with `sed`.
+
+**The problem:** When you set `--with-hsc2hs=/path/to/cross-hsc2hs` or `--hsc2hs-options=--cross-compile`, cabal applies these **only to your local package**, not to dependencies. Every dependency that uses `.hsc` files silently uses the wrong `hsc2hs`.
+
+**What cabal needs:** A `--cross-prefix` flag or automatic propagation of tool overrides to all transitive dependencies. This was reported in 2018 and called "utterly unusable for cross-compilation."
+
+### 2. `Setup.hs` Compiled with Cross-Compiler ([cabal#1493](https://github.com/haskell/cabal/issues/1493), [cabal#2085](https://github.com/haskell/cabal/issues/2085))
+
+**The hack:** haskell-mobile only works because its dependencies happen to use `build-type: Simple`. If any dependency used `build-type: Custom`, the build would fail entirely.
+
+**The problem:** Cabal compiles `Setup.hs` with whatever GHC is configured. If that's a cross-compiler, the resulting `Setup` binary targets ARM and can't run on the x86 build machine. There is no `--with-build-ghc` flag.
+
+**What cabal needs:** Distinguish between "build machine GHC" (for running Setup.hs, hsc2hs, etc.) and "target GHC" (for compiling the actual library). This is the single biggest architectural gap.
+
+### 3. No Standalone `foreign-library` on Non-Windows ([cabal#6097](https://github.com/haskell/cabal/issues/6097))
+
+**The hack:** Nix bypasses cabal entirely for the linking step. It manually discovers all GHC boot library `.a` files via `find`, then links them with `--whole-archive` into a single `.so` (Android) or merges them with `libtool -static` into a single `.a` (iOS).
+
+**The problem:** Cabal's `foreign-library` stanza supports a `standalone` option that bundles the RTS, but it **only works on Windows**. On Android/iOS, the produced library has dangling dependencies on GHC's shared libraries, which don't exist on the device.
+
+**What cabal needs:** `standalone` support on all platforms. On Android, this means `--whole-archive` linking of boot libs into one `.so`. On iOS, it means `libtool -static` merging into one `.a`. This is the #1 feature that would eliminate the most Nix code.
+
+### 4. No Way to Bundle Runtime Dependencies
+
+**The hack:** Nix manually copies `libgmp.so` and `libffi.so` from the cross-compilation sysroot into the APK's `lib/` directory.
+
+**The problem:** GHC depends on libgmp and libffi at runtime, but Android doesn't provide them. Cabal has no concept of "runtime dependencies that must be shipped alongside the output." It assumes the target system has these libraries.
+
+**What cabal needs:** A `bundle-libs` or `runtime-deps` field that specifies shared libraries to include in the output. Or, better yet: static linking of gmp/ffi into the RTS when targeting mobile (GHC-level fix).
+
+### 5. FFI Exports Silently Dropped by Linker
+
+**The hack:** Nix passes `-Wl,-u,haskellRunMain -Wl,-u,haskellOnLifecycle ...` for every single FFI export symbol -- 9 symbols manually listed.
+
+**The problem:** GHC's `foreign export ccall` produces C-callable symbols, but the linker sees no references to them (they're called from JNI/ObjC at runtime, not from Haskell). The linker garbage-collects them as "unreferenced." Every new FFI export requires updating the Nix build with another `-Wl,-u` flag.
+
+**What cabal needs:** Automatic detection and preservation of `foreign export` symbols. When building a `foreign-library`, cabal/GHC should emit a linker script or use `--export-dynamic` to keep all FFI exports alive.
+
+### 6. Mach-O Platform Tag Rewriting (mac2ios / mac2watchos)
+
+**The hack:** haskell-mobile includes two custom C programs (`mac2ios.c`, `mac2watchos.c`) that parse Mach-O binaries and rewrite `LC_BUILD_VERSION` from `PLATFORM_MACOS` to `PLATFORM_IOS` or `PLATFORM_WATCHOS`. Every compiled `.a` file goes through this binary patching.
+
+**The problem:** GHC on macOS always produces macOS-tagged binaries, even when the output is intended for iOS/watchOS. Apple's Xcode linker rejects macOS-tagged objects when building iOS apps.
+
+**What GHC needs:** A `-fplatform-ios` / `-fplatform-watchos` flag, or proper cross-compilation target triples (`aarch64-apple-ios`, `aarch64-apple-watchos`) that emit the correct platform tags. This is a GHC issue, not cabal.
+
+---
+
+## Additional Hacks (Less Critical but Still Painful)
+
+| Hack | What It Does | Root Cause |
+|------|-------------|------------|
+| Source copy to writable dir | Copies all `.hs`/`.c` files out of Nix store | GHC writes `_stub.h` next to sources; read-only stores break this |
+| NUMA stubs (`numa_stubs.c`) | Provides fake `numa_available()` etc. | GHC RTS references libnuma; Android lacks it |
+| Android libc stubs (`android_stubs.c`) | Stubs for `__svfscanf`, `__vfwscanf` | GHC RTS references GNU libc symbols absent from bionic |
+| `run_main.c` wrapper | Calls `rts_evalLazyIO(ZCMain_main_closure)` | No standard C entry point for Haskell `main` in shared lib mode |
+| ARM page size (`-Wl,-z,max-page-size=16384`) | Sets correct 16KB page alignment | GHC/linker defaults to 4KB; ARM uses 16KB |
+| Library discovery via `find` | Searches `$GHC_PKG_DIR` for `libHS*.a` by glob | Library names have hash suffixes; no API to query paths |
+| armv7a profiling disabled | `enableProfiledLibs = false` for 32-bit ARM | LLVM ARM32 backend crashes on profiled code |
+| compiler-rt patches | 4 separate patches to nixpkgs compiler-rt | armv7a not recognized as valid ARM32 arch |
+| boot package hardcoding | List of 15 packages to exclude from cross-build | No `ghc-pkg --boot-packages` query |
+| `project.yml` Python patching | Injects `OTHER_CFLAGS` into Xcode config | No way to pass C flags through cabal to Xcode |
+| Two-stage NDK compilation | JNI bridge compiled by NDK clang, not GHC | GHC's C compiler doesn't know about JNI headers |
+| cabal2nix spy derivation | Extracts deps without building | No `cabal plan --to-json` for dependency info |
+
+---
+
+## What's Improving
+
+### ghc-toolchain (GHC 9.10+, not yet default)
+
+Replaces the 10,000-line `./configure` script. Long-term goal: **runtime-retargetable GHC** where one GHC can target multiple platforms via `ghc --target=aarch64-linux-android`. This would eliminate needing separate cross-compiler builds. Status: shipping but not default; full retargetability is years out.
+
+- [Well-Typed blog post](https://well-typed.com/blog/2023/10/improving-ghc-configuration-and-cross-compilation-with-ghc-toolchain/)
+- [GHC #11470 - Runtime retargetable cross-compilation](https://gitlab.haskell.org/ghc/ghc/-/issues/11470)
+
+### Explicit Level Imports (GHC 9.14)
+
+[Proposal #682](https://ghc-proposals.readthedocs.io/en/latest/proposals/0682-explicit-level-imports.html) -- distinguishes compile-time imports from runtime imports, reducing the scope of Template Haskell cross-compilation problems.
+
+---
+
+## Template Haskell and Cross-Compilation
+
+Template Haskell splices execute code at compile time on the **build machine**, but when cross-compiling, the code targets the **target machine** and can't run locally.
+
+**Current workaround:** GHC's `-fexternal-interpreter` with `iserv-proxy` + `remote-iserv`, delegating TH evaluation to an emulator (QEMU for Android, iOS Simulator for iOS). This works but is slow and fragile.
+
+**haskell-mobile's approach:** Avoid TH entirely. The project and its dependencies don't use Template Haskell, sidestepping the problem. This limits which Hackage packages can be used as dependencies.
+
+---
+
+## Reference Implementations
+
+### SimpleX Chat
+
+The most prominent production Haskell app on Android/iOS. Uses **haskell.nix** (not plain nixpkgs) for cross-compilation infrastructure. Ships `libsimplex.so` via `ghc -shared` with static linking. Maintains custom forks of several Hackage packages for Android compatibility.
+
+### haskell-mobile (this project)
+
+Uses **plain nixpkgs** (not haskell.nix) with `pkgsCross.aarch64-android-prebuilt`. Simpler but requires more manual workarounds. The Nix code in `nix/lib.nix` is essentially a hand-written cross-compilation build system.
+
+---
+
+## Priority Ranking: What Would Help haskell-mobile Most
+
+1. **`foreign-library standalone` on all platforms** -- eliminates the entire `--whole-archive` / `libtool -static` / boot library discovery machinery (~40% of Nix build code)
+2. **Build/host tool distinction in cabal** -- eliminates `Setup.hs` problem and `hsc2hs` propagation hacks
+3. **FFI export preservation** -- eliminates manual `-Wl,-u` symbol lists
+4. **GHC iOS/watchOS platform tags** -- eliminates mac2ios/mac2watchos binary patchers
+5. **GHC `--without-numa` for mobile targets** -- eliminates NUMA/libc stubs
+6. **`cabal plan --to-json`** -- eliminates cabal2nix spy derivation for dependency resolution
+7. **Runtime dependency bundling** -- eliminates manual libgmp/libffi copying
+
+---
+
+## Key References
+
+- [Cabal #4939 - new-build unusable for cross-compilation](https://github.com/haskell/cabal/issues/4939)
+- [Cabal #1493 - Setup.hs with local compiler](https://github.com/haskell/cabal/issues/1493)
+- [Cabal #2085 - Avoid compiling setup for cross](https://github.com/haskell/cabal/issues/2085)
+- [Cabal #9321 - Cross-compilation conditional](https://github.com/haskell/cabal/issues/9321)
+- [Cabal #5887 - Incorrect --host=](https://github.com/haskell/cabal/issues/5887)
+- [Cabal #9222 - extra-lib-dirs not propagated](https://github.com/haskell/cabal/issues/9222)
+- [Cabal #6097 - -staticlib for Android](https://github.com/haskell/cabal/issues/6097)
+- [GHC #10324 - Shared library tricks don't work on Android](https://gitlab.haskell.org/ghc/ghc/-/issues/10324)
+- [GHC #11470 - Runtime retargetable cross-compilation](https://gitlab.haskell.org/ghc/ghc/-/issues/11470)
+- [GHC Proposal #682 - Explicit Level Imports](https://ghc-proposals.readthedocs.io/en/latest/proposals/0682-explicit-level-imports.html)
+- [zw3rk: The Haskell Cabal and Cross Compilation](https://medium.com/@zw3rk/the-haskell-cabal-and-cross-compilation-e9885fd5e2f)
+- [zw3rk: Haskell Cross Compiler for Android](https://medium.com/@zw3rk/a-haskell-cross-compiler-for-android-8e297cb74e8a)
+- [zw3rk: Haskell Cross Compiler for iOS](https://medium.com/@zw3rk/a-haskell-cross-compiler-for-ios-7cc009abe208)
+- [Cabal foreign-library discussion (Discourse)](https://discourse.haskell.org/t/cabals-foreign-library-stanza/6516)
+
+---
+
+## Conclusion
+
+**Nix is doing the job of a cross-compilation-aware build system because cabal isn't one.** Every hack in haskell-mobile exists because cabal assumes you're building natively and GHC assumes the target has a full POSIX environment. The most impactful single change would be making `foreign-library standalone` work on Linux/macOS, which would eliminate roughly 40% of the Nix build infrastructure.
diff --git a/docs/flutter-feature-comparison.md b/docs/flutter-feature-comparison.md
new file mode 100644
index 00000000..5cc359a9
--- /dev/null
+++ b/docs/flutter-feature-comparison.md
@@ -0,0 +1,444 @@
+# Flutter Feature Comparison with haskell-mobile
+
+A feature-by-feature comparison of Flutter's capabilities against what haskell-mobile currently supports. This serves as both a gap analysis and a roadmap reference.
+
+---
+
+## Feature Matrix
+
+| # | Feature Area | Flutter | haskell-mobile | Gap |
+|---|---|---|---|---|
+| 1 | [Widgets (basic)](#1-basic-widgets) | ~180 built-in widgets | 8 widget types | Large |
+| 2 | [Layout system](#2-layout-system) | Constraint-based, Flex, Stack, Grid, Sliver | Column, Row, ScrollView | Large |
+| 3 | [Text rendering](#3-text-rendering) | Rich text, spans, fonts, selectable | Plain text with font size and color | Medium |
+| 4 | [Input handling](#4-input-handling) | Text, gestures, focus, keyboard shortcuts | Button tap, text input (text/numeric) | Large |
+| 5 | [Scrolling and lists](#5-scrolling-and-lists) | ListView, GridView, Slivers, lazy loading | ScrollView (full rebuild, no lazy) | Large |
+| 6 | [Navigation and routing](#6-navigation-and-routing) | Navigator 2.0, named routes, deep links | None (manual view switching) | Large |
+| 7 | [Animation](#7-animation) | Implicit, explicit, hero, physics-based | None | Full gap |
+| 8 | [Theming and styling](#8-theming-and-styling) | Material 3, Cupertino, full theme system | Padding, text/bg color, font size, alignment | Large |
+| 9 | [Images and media](#9-images-and-media) | Network images, caching, SVG, video, audio | Resource, raw bytes, file path (static) | Large |
+| 10 | [State management](#10-state-management) | setState, InheritedWidget, Provider, Riverpod, Bloc | IORef + full re-render | Medium |
+| 11 | [Platform integration](#11-platform-integration) | Platform channels, Dart FFI, 350+ pub.dev plugins | Permissions, lifecycle, locale, logging | Large |
+| 12 | [Accessibility](#12-accessibility) | Semantics tree, screen reader labels, roles | None (relies on native widget defaults) | Large |
+| 13 | [Internationalization](#13-internationalization) | intl, ARB files, plural/gender, date/number formatting | Key-value translation with locale fallback | Medium |
+| 14 | [Testing](#14-testing) | Widget tests, golden tests, integration tests, driver | Unit tests, FFI dispatch tests, demo apps | Medium |
+| 15 | [Incremental rendering](#15-incremental-rendering) | Element tree diffing, repaint boundaries, retained layers | Full clear-and-rebuild every frame | Large |
+| 16 | [Platform targets](#16-platform-targets) | Android, iOS, web, macOS, Windows, Linux | Android, iOS, watchOS, desktop (test) | Small |
+| 17 | [Hot reload](#17-hot-reload) | Sub-second with state preservation | None (recompile + redeploy) | Large |
+| 18 | [Custom painting](#18-custom-painting) | Canvas API, CustomPainter, shaders | None | Full gap |
+| 19 | [Forms and validation](#19-forms-and-validation) | Form widget, validators, controllers | TextInput with onChange callback | Large |
+| 20 | [Networking](#20-networking) | http, dio, web sockets, gRPC | None in framework (user brings own) | N/A |
+
+---
+
+## Detailed Comparison
+
+### 1. Basic Widgets
+
+**Flutter** provides ~180 built-in widgets organized into categories: layout, text, input, display, scrolling, dialog, navigation, and platform-adaptive (Material and Cupertino). Core examples: `Container`, `Text`, `Image`, `Icon`, `Card`, `Chip`, `Divider`, `Checkbox`, `Radio`, `Switch`, `Slider`, `DropdownButton`, `PopupMenu`, `BottomSheet`, `Dialog`, `Scaffold`, `AppBar`, `TabBar`, `Drawer`, `FloatingActionButton`.
+
+**haskell-mobile** has 8 widget constructors:
+
+| Widget | Description |
+|---|---|
+| `Text` | Read-only label with optional `FontConfig` |
+| `Button` | Tappable with label + `IO ()` handler |
+| `TextInput` | Controlled text field (text or numeric keyboard) |
+| `Column` | Vertical layout container |
+| `Row` | Horizontal layout container |
+| `ScrollView` | Vertical scrolling container |
+| `Image` | From resource name, raw bytes, or file path |
+| `Styled` | Wrapper applying `WidgetStyle` to any widget |
+
+**Gap**: Most of Flutter's widget catalog has no equivalent. Missing: checkboxes, radio buttons, switches, sliders, dropdowns, dialogs, bottom sheets, cards, dividers, icons, progress indicators, chips, tooltips, snackbars, app bars, tabs, drawers, FABs.
+
+---
+
+### 2. Layout System
+
+**Flutter** uses a constraint-based layout where parent widgets pass `BoxConstraints` (min/max width and height) down to children, children report their size back up, and parents position children. Layout containers include:
+
+- `Row`, `Column` -- flex-based linear layout with `mainAxisAlignment`, `crossAxisAlignment`, `flex`, `Expanded`, `Flexible`, `Spacer`
+- `Stack` -- overlapping children with `Positioned` for absolute placement
+- `Wrap` -- like Row/Column but wraps to next line when full
+- `GridView` -- 2D grid with fixed or dynamic column counts
+- `Table` -- explicit row/column table layout
+- `CustomMultiChildLayout` -- arbitrary positioning via delegate
+- `ConstrainedBox`, `SizedBox`, `FractionallySizedBox` -- size constraints
+- `Padding`, `Center`, `Align` -- positioning modifiers
+- `AspectRatio`, `FittedBox`, `IntrinsicWidth/Height` -- sizing utilities
+
+**haskell-mobile** has:
+
+- `Column [Widget]` -- vertical stacking
+- `Row [Widget]` -- horizontal stacking
+- `ScrollView [Widget]` -- vertical scrolling
+- `wsPadding` in `WidgetStyle` -- uniform padding
+
+No flex weights, no alignment control on containers, no stacking/overlapping, no grid, no explicit sizing constraints, no wrapping.
+
+**Gap**: No `Expanded`/`Flexible` equivalents, no `Stack`, no `Grid`, no alignment on Row/Column, no explicit size constraints, no aspect ratio control.
+
+---
+
+### 3. Text Rendering
+
+**Flutter** supports:
+- `Text` with `TextStyle` (font family, size, weight, style, color, decoration, letter spacing, word spacing, height, shadows, background)
+- `RichText` with `TextSpan` tree for mixed-style inline text
+- `SelectableText` for copy-paste
+- `Text.rich` shorthand
+- Text overflow modes (ellipsis, fade, clip)
+- Maximum lines
+- Custom fonts loaded from assets
+- Right-to-left text support
+
+**haskell-mobile** supports:
+- `Text TextConfig` with `FontConfig` containing `fontSize`
+- Text color via `wsTextColor` in `WidgetStyle`
+- Text alignment (`AlignStart`, `AlignCenter`, `AlignEnd`)
+
+**Gap**: No rich text / mixed-style spans, no font weight/style/family selection, no text overflow handling, no selectable text, no text decoration, no custom fonts.
+
+---
+
+### 4. Input Handling
+
+**Flutter** supports:
+- `TextField` / `TextFormField` with full control (selection, cursor, input formatting, obscuring)
+- `GestureDetector` (tap, double-tap, long-press, pan, scale, drag)
+- `InkWell` / `InkResponse` (material ripple on tap)
+- `Dismissible` (swipe-to-dismiss)
+- `Draggable` / `DragTarget`
+- `FocusNode` / `FocusScope` for keyboard focus management
+- `RawKeyboardListener` / `KeyboardListener`
+- `Listener` (raw pointer events)
+- `MouseRegion` (hover, enter, exit)
+- `AbsorbPointer` / `IgnorePointer` (event blocking)
+
+**haskell-mobile** supports:
+- `Button` with `IO ()` click callback
+- `TextInput` with `tiOnChange :: Text -> IO ()` callback, controlled value, hint text
+- Two keyboard types: `InputText`, `InputNumber`
+
+**Gap**: No gesture recognition (swipe, long-press, drag, scale), no focus management, no keyboard event handling, no pointer/hover events, no input formatting or masking.
+
+---
+
+### 5. Scrolling and Lists
+
+**Flutter** supports:
+- `ListView` -- lazy-loading scrollable list (only builds visible items)
+- `ListView.builder` -- on-demand item construction from index
+- `GridView` / `GridView.builder` -- 2D lazy grid
+- `CustomScrollView` with `Slivers` -- composable scrolling
+- `SliverList`, `SliverGrid`, `SliverAppBar`, `SliverToBoxAdapter`
+- `PageView` -- horizontal page swiping
+- `NestedScrollView` -- coordinated scrolling
+- `ReorderableListView` -- drag-to-reorder
+- `RefreshIndicator` -- pull-to-refresh
+- Scroll controllers, scroll physics, scroll notifications
+- Estimated total scroll extent for scroll bar accuracy
+
+**haskell-mobile** supports:
+- `ScrollView [Widget]` -- vertically scrollable container with all children built eagerly
+
+**Gap**: No lazy list construction (all items built on every render), no grid scrolling, no horizontal scrolling, no scroll controllers, no pull-to-refresh, no reorderable lists, no slivers, no pagination.
+
+---
+
+### 6. Navigation and Routing
+
+**Flutter** supports:
+- `Navigator` with push/pop stack
+- `Navigator 2.0` declarative API with `Router`, `RouteInformationParser`, `RouterDelegate`
+- Named routes with arguments
+- Deep linking from URLs
+- `Hero` animations across routes
+- Bottom navigation bars, tab bars, drawers
+- `go_router` (most popular declarative router)
+- Dialog/modal/bottom sheet presentation
+- `WillPopScope` / `PopScope` for back-button interception
+
+**haskell-mobile** has no navigation system. The app is a single `maView :: UserState -> IO Widget` function. To simulate multiple screens, the user would need to manage screen state manually and branch in the view function.
+
+**Gap**: No navigation stack, no route management, no deep linking, no screen transitions, no modal presentation.
+
+---
+
+### 7. Animation
+
+**Flutter** supports:
+- **Implicit animations**: `AnimatedContainer`, `AnimatedOpacity`, `AnimatedPositioned`, `AnimatedCrossFade`, `AnimatedSwitcher` (~20 implicit animation widgets)
+- **Explicit animations**: `AnimationController`, `Tween`, `CurvedAnimation`, `AnimatedBuilder`
+- **Hero animations**: Shared element transitions across routes
+- **Physics-based animations**: `SpringSimulation`, `FrictionSimulation`, `GravitySimulation`
+- **Staggered animations**: Sequential/overlapping animation sequences
+- **Custom animation curves**: 40+ built-in curves (ease, bounce, elastic, etc.)
+- **Lottie** support via plugin for After Effects animations
+- **Rive** support for interactive vector animations
+- Frame-accurate vsync-driven animation at 60/120fps
+
+**haskell-mobile** has no animation support. The rendering model is full clear-and-rebuild on each event-triggered re-render. There is no concept of frame-by-frame updates, interpolation, or timed transitions.
+
+**Gap**: Complete. No animation of any kind.
+
+---
+
+### 8. Theming and Styling
+
+**Flutter** supports:
+- `ThemeData` with 50+ configurable properties (color scheme, typography, shape, elevation, component themes)
+- Material Design 3 with dynamic color
+- Cupertino (iOS-style) theme
+- `Theme.of(context)` for inherited theme access
+- Dark mode / light mode switching
+- Custom component themes (`ElevatedButtonTheme`, `InputDecorationTheme`, etc.)
+- `TextTheme` with predefined type scale
+- `ColorScheme` with semantic color roles
+- Platform-adaptive styling (`Platform.isIOS`)
+
+**haskell-mobile** supports via `WidgetStyle`:
+- `wsPadding :: Double` -- uniform padding
+- `wsTextAlign :: TextAlignment` -- start, center, end
+- `wsTextColor :: Color` -- 8-bit RGBA
+- `wsBackgroundColor :: Color` -- 8-bit RGBA
+- `FontConfig` with `fontSize :: Double`
+- `Color` type with hex parsing (`colorFromText`)
+
+Applied via `Styled WidgetStyle Widget` wrapper.
+
+**Gap**: No theme inheritance, no dark mode, no elevation/shadow, no border/radius, no margin, no per-component themes, no typography scale, no font weight/family.
+
+---
+
+### 9. Images and Media
+
+**Flutter** supports:
+- `Image.network` -- load from URL with placeholder and error handling
+- `Image.asset` -- load from app bundle
+- `Image.file` -- load from filesystem
+- `Image.memory` -- load from bytes
+- Image caching (in-memory LRU cache)
+- SVG rendering (via `flutter_svg`)
+- Video playback (`video_player`)
+- Audio playback (`audioplayers`, `just_audio`)
+- Camera (`camera` plugin)
+- Animated GIFs
+- `BoxFit` modes (contain, cover, fill, fitWidth, fitHeight, none, scaleDown)
+- `FilterQuality` for sampling
+- `ColorFilter`, `ImageFilter` for effects
+
+**haskell-mobile** supports via `ImageConfig`:
+- `ImageResource Text` -- platform bundled resource by name
+- `ImageData ByteString` -- raw PNG/JPEG bytes
+- `ImageFile Text` -- file path on disk
+- `ScaleType`: `ScaleFit`, `ScaleFill`, `ScaleNone`
+
+**Gap**: No network image loading, no image caching, no SVG, no video, no audio, no camera, no animated images, no image filters.
+
+---
+
+### 10. State Management
+
+**Flutter** built-in:
+- `setState()` -- triggers rebuild of the `StatefulWidget`'s subtree only
+- `InheritedWidget` -- O(1) ancestor data lookup, selective rebuild via `updateShouldNotify`
+- `ValueNotifier` / `ChangeNotifier` -- observable pattern
+- `StreamBuilder` / `FutureBuilder` -- async data binding
+
+Popular packages: Provider, Riverpod, Bloc/Cubit, GetX, MobX, Redux.
+
+Flutter's key advantage: incremental rebuild. Only the dirty subtree is rebuilt; unchanged subtrees are skipped via element identity matching.
+
+**haskell-mobile**:
+- `IORef (Maybe MobileApp)` stores the registered app
+- `RenderState` tracks callback registries (fresh `IntMap` each render)
+- Full re-render of entire widget tree on every event
+- User manages their own state via closures in `IO`
+
+The model is simple and correct, but every render rebuilds the entire widget tree and sends the full tree across FFI. There is no diffing or incremental update.
+
+**Gap**: No incremental rendering (full tree rebuild every time), no built-in observable/reactive patterns, no scoped rebuilds.
+
+---
+
+### 11. Platform Integration
+
+**Flutter** provides:
+- Platform channels (`MethodChannel`, `EventChannel`) for bidirectional native communication
+- Dart FFI for direct C library binding
+- 350+ first-party and community plugins on pub.dev
+- Camera, GPS, file picker, share, local notifications, push notifications, biometrics, in-app purchase, maps, web view, sensors, battery, connectivity, device info, etc.
+
+**haskell-mobile** provides:
+- **Permissions**: Request/check for Location, Bluetooth, Camera, Microphone, Contacts, Storage
+- **Lifecycle events**: Create, Start, Resume, Pause, Stop, Destroy, LowMemory
+- **Locale detection**: `getSystemLocale` via JNI (Android) / system API (iOS)
+- **Platform logging**: logcat (Android), os_log (iOS), stderr (desktop)
+- **Error handling**: `onError` callback for Haskell exceptions
+
+All platform integration goes through the C bridge (`UIBridge.h`, `PermissionBridge.h`). Adding new platform features requires modifying the C bridge, the Kotlin/Swift bridge, and the Haskell FFI exports.
+
+**Gap**: No camera capture, no GPS/location data, no file picker, no notifications, no network info, no sensors, no maps, no web view, no biometrics. The bridge pattern works but each new feature requires three-layer implementation.
+
+---
+
+### 12. Accessibility
+
+**Flutter** supports:
+- `Semantics` widget with 40+ properties (label, hint, value, role, actions, live region, etc.)
+- `SemanticsProperties` for custom semantic annotations
+- `MergeSemantics` / `ExcludeSemantics` for tree control
+- `SemanticsService.announce()` for screen reader announcements
+- Built-in platform integration: TalkBack (Android), VoiceOver (iOS)
+- `debugDumpSemanticsTree()` for inspection
+- Accessibility guidelines checking (large fonts, sufficient contrast)
+- Traversal ordering
+
+**haskell-mobile** has no explicit accessibility support. Native widgets (Button, TextInput) inherit platform defaults (the button label will be read by TalkBack/VoiceOver), but there are no semantic annotations, no custom labels, no role overrides, no live region support.
+
+**Gap**: No semantic annotations, no custom accessibility labels, no traversal control, no screen reader announcements.
+
+---
+
+### 13. Internationalization
+
+**Flutter** supports:
+- `intl` package with ICU message syntax
+- ARB (Application Resource Bundle) files
+- Plural forms, gender, select
+- Date formatting (`DateFormat`)
+- Number formatting (`NumberFormat`)
+- Currency formatting
+- Bidirectional text
+- `Localizations` widget for inherited locale
+- Code generation via `intl_utils` or `gen-l10n`
+- 78+ locales supported out of the box for Material widgets
+
+**haskell-mobile** supports:
+- `I18n` module with `translate :: Map Locale (Map Key Text) -> Locale -> Key -> Either TranslateFailure Text`
+- Fallback chain: exact locale -> language-only -> error
+- `Locale` type with ISO 639-1 language enum (70+ languages) + optional region
+- BCP-47 tag parsing (`parseLocale`)
+- System locale detection (`getSystemLocale`)
+
+**Gap**: No plural/gender forms, no date/number/currency formatting, no bidirectional text support, no ARB files, no code generation. The basic translation lookup works but lacks ICU message syntax.
+
+---
+
+### 14. Testing
+
+**Flutter** supports:
+- **Unit tests**: Standard Dart test package
+- **Widget tests**: Render widgets in test, find by type/text/key, tap/enter text, pump frames
+- **Golden tests**: Pixel-perfect screenshot comparison
+- **Integration tests**: `integration_test` package with real device/emulator
+- **Flutter Driver**: UI automation
+- `WidgetTester` with `pumpWidget`, `tap`, `enterText`, `pumpAndSettle`
+- `find.byType`, `find.text`, `find.byKey`
+- Mock platform channels
+
+**haskell-mobile** supports:
+- Unit tests via Tasty (QuickCheck + HUnit)
+- Tests for: FFI dispatch, lifecycle routing, widget rendering (serialization to C bridge calls), callback registration, text input handling, ScrollView rendering, Image widget variants, Styled widget, text alignment, color parsing, locale parsing, i18n translation, permission dispatch, AppContext lifecycle, exception handling
+- Demo apps (counter, scrollview, textinput, permission, image) as smoke tests
+- Desktop stubs allow `cabal test` without mobile devices
+
+**Gap**: No widget-level rendering tests (cannot render and interact with actual UI), no golden/screenshot tests, no integration tests on device. The existing tests validate the Haskell-side logic and C bridge serialization, which is solid, but cannot test the actual native rendering.
+
+---
+
+### 15. Incremental Rendering
+
+**Flutter**:
+- Element tree persists across frames; only dirty elements rebuild
+- Layout uses cutoff optimizations (same constraints = skip subtree)
+- Repaint boundaries isolate repainting to subtrees
+- Retained layer rendering (unchanged layers reuse GPU bitmaps)
+- `const` widgets skip rebuild via identity check
+- O(n) reconciliation only on changed subtrees
+
+**haskell-mobile**:
+- Full clear-and-rebuild on every render
+- Callback registry (`IntMap`) is cleared and recreated each render
+- Every widget tree is serialized to C bridge calls from scratch
+- Platform native side presumably clears and recreates all views
+
+**Gap**: No tree diffing, no incremental updates, no retained rendering. Every UI event triggers a full tree serialization and native view recreation.
+
+---
+
+### 16. Platform Targets
+
+**Flutter**: Android, iOS, web (CanvasKit/HTML), macOS, Windows, Linux -- all from one codebase.
+
+**haskell-mobile**: Android (APK via Kotlin/JNI), iOS (static library linked into Xcode), watchOS (Swift bridge), desktop (GHC executable for testing).
+
+**Gap**: Small. haskell-mobile covers the key mobile targets. No web support, but that is a different problem space. watchOS support is a unique advantage that Flutter lacks (Flutter has no watchOS target).
+
+---
+
+### 17. Hot Reload
+
+**Flutter**: Sub-second hot reload preserving app state. The Dart VM injects updated source code into the running isolate, the framework re-runs `build()` on affected widgets, and the UI updates immediately. Hot restart (full restart without state preservation) is also available.
+
+**haskell-mobile**: No hot reload. Changes require recompilation (which involves cross-compilation via Nix for mobile targets) and redeployment to the device. Development iteration uses the desktop target for faster feedback.
+
+**Gap**: Complete. GHC does not support injecting code into a running process. The desktop build target partially mitigates this for logic iteration but not for UI testing on device.
+
+---
+
+### 18. Custom Painting
+
+**Flutter**: `CustomPainter` provides a `Canvas` API for arbitrary 2D drawing: lines, arcs, paths, text, images, gradients, shadows, blend modes, clip regions. Used for charts, custom shapes, games, signatures. Also supports fragment shaders via `FragmentProgram`.
+
+**haskell-mobile**: No custom painting. All rendering is through the predefined widget types.
+
+**Gap**: Complete. Adding a canvas/paint API would require significant bridge work.
+
+---
+
+### 19. Forms and Validation
+
+**Flutter**: `Form` widget groups `TextFormField` widgets. `TextFormField` has `validator` callback returning error string or null. `Form.validate()` runs all validators. `TextEditingController` for programmatic text access. `InputDecoration` for labels, hints, error text, prefixes, suffixes, icons. `FocusNode` for focus management between fields.
+
+**haskell-mobile**: `TextInput` with controlled value (`tiValue`), change callback (`tiOnChange`), hint text (`tiHint`), and keyboard type. No validation, no error display, no form grouping, no focus control.
+
+**Gap**: No validation framework, no error display on inputs, no form grouping, no focus management.
+
+---
+
+### 20. Networking
+
+**Flutter**: The `http` package provides HTTP client. `dio` adds interceptors, retry, upload progress. `web_socket_channel` for WebSockets. `grpc` for gRPC. All async via Dart futures/streams.
+
+**haskell-mobile**: No networking in the framework. Users bring their own (e.g., `http-client`, `req`, `network`). This is arguably the correct approach -- networking is not a UI framework concern.
+
+**Gap**: N/A. Not a framework responsibility, but Flutter's ecosystem makes it seamless.
+
+---
+
+## Summary: Where haskell-mobile Stands
+
+### What haskell-mobile does well
+
+1. **Type safety** -- The widget tree is an algebraic data type. Invalid widget compositions are compile errors.
+2. **Simplicity** -- The entire framework is small enough to understand in a single sitting.
+3. **watchOS support** -- Flutter does not target watchOS at all.
+4. **Direct FFI** -- No serialization bridge. Haskell compiles to native code and calls C functions directly, similar to Dart's advantage over JavaScript.
+5. **Testable without devices** -- Desktop stubs allow full logic testing via `cabal test`.
+6. **Correct concurrency** -- Haskell's runtime handles threading correctly; no async bridge latency.
+
+### Highest-impact gaps to close
+
+Ranked by impact on real-world app development:
+
+1. **Incremental rendering** -- Full tree rebuild on every event does not scale. A diffing/patching strategy (even a simple one) would dramatically improve performance with larger UIs.
+2. **More widgets** -- Checkbox, switch, slider, dropdown, dialog, and progress indicator would cover most common app UI patterns.
+3. **Navigation** -- A screen stack with push/pop is essential for multi-screen apps.
+4. **Layout flexibility** -- Flex weights on Row/Column, Stack for overlapping, explicit sizing.
+5. **Gesture recognition** -- Swipe, long-press, and drag are expected in mobile UIs.
+6. **Animation** -- Even basic implicit animations (fade, slide) would make the framework feel production-ready.
+7. **Richer text** -- Font weight, font family, and multi-style text spans.
+8. **Accessibility** -- Semantic labels on widgets for screen readers.
diff --git a/docs/rendering-comparison.md b/docs/rendering-comparison.md
new file mode 100644
index 00000000..592f8905
--- /dev/null
+++ b/docs/rendering-comparison.md
@@ -0,0 +1,464 @@
+# How React Native and Flutter Do Rendering
+
+A technical comparison of the two dominant cross-platform mobile frameworks, written from the perspective of haskell-mobile's architecture.
+
+---
+
+## Executive Summary
+
+React Native and Flutter take fundamentally different approaches to mobile rendering:
+
+- **React Native** renders through the platform's native UI toolkit. It runs JavaScript that produces a virtual component tree, diffs it, and sends mutation instructions to iOS UIKit / Android Views. The platform does the actual drawing.
+- **Flutter** owns the entire rendering surface. It runs Dart code that produces a render object tree, lays it out, paints it onto a Canvas, and submits GPU commands directly via Impeller (Metal/Vulkan). The platform provides only a blank surface.
+
+Both use a declarative widget model with tree reconciliation, but diverge completely at the rendering layer.
+
+| Concern | React Native | Flutter |
+|---|---|---|
+| Language | JavaScript (Hermes VM) | Dart (AOT-compiled to native) |
+| UI toolkit | Platform-native (UIKit, Android Views) | Custom (Impeller/Skia drawing engine) |
+| Layout engine | Yoga (C++ flexbox) | Built-in constraint propagation |
+| Tree diffing | O(n) heuristic (type + key) | O(n) linear child-list |
+| JS-native bridge | JSI (direct C++ host objects) | None needed (Dart compiles to native) |
+| Thread model | 3 threads (JS, Shadow, UI) | 4 task runners (merging to 2) |
+
+---
+
+## Part 1: React
+
+### 1.1 Architecture Overview
+
+React's rendering pipeline separates **reconciliation** (what changed) from **rendering** (applying changes to a host environment). This separation allows the same reconciler to power both React DOM and React Native.
+
+The pipeline:
+
+1. **Trigger** -- A state change (`setState`, `useState` setter) enqueues an update on the relevant fiber node.
+2. **Render phase (reconciliation)** -- React traverses the fiber tree, calls component render functions, produces new React elements, and diffs them against the previous tree. This phase is **interruptible** under concurrent rendering. No host mutations occur.
+3. **Commit phase** -- React synchronously applies all computed mutations to the host environment (DOM insertions on web; native view creation on mobile). This phase is **not interruptible**.
+4. **Passive effects** -- `useEffect` cleanup and setup run asynchronously after commit.
+
+### 1.2 Virtual DOM and Fiber Architecture
+
+#### Virtual DOM
+
+The virtual DOM is a lightweight, in-memory tree of plain JavaScript objects describing the intended UI:
+
+```javascript
+{ type: 'View', props: { style: { flex: 1 }, children: [...] } }
+```
+
+On state change, React generates a new element tree, diffs it against the previous one, and computes the minimal set of mutations.
+
+#### Fiber Nodes
+
+Each component instance maps to a **fiber node** -- a mutable JS object containing:
+
+| Field | Purpose |
+|---|---|
+| `type` | Component function/class or host element tag |
+| `stateNode` | Reference to the native view or component instance |
+| `child` | First child fiber (linked list, not array) |
+| `sibling` | Next sibling fiber |
+| `return` | Parent fiber |
+| `alternate` | Corresponding node in the other tree (current vs. work-in-progress) |
+| `pendingProps` | New props at start of work |
+| `memoizedProps` | Props after work completes (bail out if equal to pendingProps) |
+| `memoizedState` | Current state; for function components, head of hooks linked list |
+| `flags` | Bitmask of side effects (Placement, Update, Deletion) |
+| `lanes` | Bitmask of pending priority lanes |
+
+The `child`/`sibling`/`return` pointers form a linked-list tree that React traverses iteratively (no recursion, no stack overflow on deep trees).
+
+#### Double Buffering
+
+React maintains two fiber trees simultaneously:
+
+- **Current tree** -- what is on screen.
+- **Work-in-progress (WIP) tree** -- being constructed during the render phase.
+
+Each fiber's `alternate` points to its counterpart. At commit, React swaps the root pointer: WIP becomes current, and the old current is reused as the next WIP tree.
+
+#### The Work Loop
+
+```
+function workLoopConcurrent() {
+ while (workInProgress !== null && !shouldYield()) {
+ performUnitOfWork(workInProgress);
+ }
+}
+```
+
+`performUnitOfWork` calls:
+
+1. **`beginWork(fiber)`** -- top-down: calls the component function, returns child fiber. Bails out early if props and state are unchanged.
+2. **`completeWork(fiber)`** -- bottom-up: creates/updates the host node, builds the effect list.
+
+Traversal: descend via `child` (calling `beginWork`), at leaves call `completeWork` and follow `sibling`, when siblings exhausted `completeWork` the parent via `return`.
+
+#### Diffing Algorithm
+
+React achieves O(n) diffing via two heuristics:
+
+1. **Elements of different types produce entirely different trees.** A `` replaced by `` tears down the old subtree entirely.
+2. **`key` props hint at stable identity.** In child lists, keys allow matching elements across renders to detect adds, removes, and moves.
+
+### 1.3 React Native: From JavaScript to Native Views
+
+#### New Architecture (default since React Native 0.76)
+
+Three pillars replace the old asynchronous JSON bridge:
+
+**JSI (JavaScript Interface)** -- A C++ API that exposes native objects directly to JavaScript. No JSON serialization. Synchronous calls when needed. Engine-agnostic (works with Hermes, JSC, V8).
+
+**TurboModules** -- Lazily-loaded native modules backed by JSI with Codegen-generated type-safe C++ interfaces.
+
+**Fabric Renderer** -- New rendering system with a shared C++ core:
+- Represents UI as an **immutable C++ shadow tree** (structural sharing for unchanged nodes).
+- Supports concurrent rendering (shadow trees can be built on any thread).
+- Layout via Yoga runs during the commit phase.
+
+#### Fabric Rendering Pipeline
+
+**Phase 1 -- Render**: React executes component logic on the JS thread, producing React elements. Fabric creates a corresponding C++ shadow tree.
+
+**Phase 2 -- Commit**: Yoga calculates layout on the shadow tree. The new tree is promoted as "next tree to mount."
+
+**Phase 3 -- Mount**: The diff between old and new shadow trees produces mount instructions (create view, update props, delete view, insert/remove child) executed on the **UI main thread**.
+
+#### Component Mapping
+
+| React Native | iOS (UIKit) | Android |
+|---|---|---|
+| `` | `UIView` | `ViewGroup` |
+| `` | Custom text view | `TextView` |
+| `` | `UIImageView` | `ImageView` |
+| `` | `UIScrollView` | `ScrollView` |
+| `` | `UITextField` | `EditText` |
+
+Each component has a native **ComponentDescriptor** (Fabric) that creates, updates, and destroys the native view.
+
+#### Threading Model
+
+| Thread | Role |
+|---|---|
+| **JavaScript** | Executes Dart code, produces element trees |
+| **Shadow/Background** | Yoga layout, shadow tree construction (under Fabric, can run on any thread) |
+| **UI/Main** | Mounts native views, handles touch events |
+
+Events flow in reverse: native touch → C++ event → JSI → JavaScript handler.
+
+### 1.4 Yoga Layout Engine
+
+Yoga is a C++20 flexbox engine. Each `yoga::Node` corresponds to a view. Layout via `YGNodeCalculateLayout()` does a multi-pass traversal:
+
+1. **Top-down** -- Distribute space along main axis per `flexGrow`/`flexShrink`. Invoke **measure callbacks** for leaf nodes with intrinsic size (text).
+2. **Bottom-up** -- Resolve sizes of wrapping containers.
+3. **Top-down** -- Resolve percentages, alignment, absolute positioning.
+
+Yoga minimizes measure callback invocations (expensive for text) and caches layout results when constraints haven't changed.
+
+### 1.5 Priority Scheduling (Lanes)
+
+React uses a 31-bit bitmask system with priority groups:
+
+| Lane | Priority | Use |
+|---|---|---|
+| `SyncLane` | Highest | Discrete user events (tap, keypress) |
+| `InputContinuousLane` | High | Drag, scroll |
+| `DefaultLane` | Normal | Standard `setState` |
+| `TransitionLane` (x16) | Low | `useTransition`; interruptible |
+| `IdleLane` | Lowest | Offscreen work |
+
+The scheduler works in ~5ms chunks, yielding to the browser/platform via `MessageChannel` to keep the UI responsive. Higher-priority updates can interrupt in-progress lower-priority renders.
+
+---
+
+## Part 2: Flutter
+
+### 2.1 Architecture Overview
+
+Flutter is a layered system:
+
+```
+ Dart Application Code
+ ─────────────────────
+ Flutter Framework (Dart)
+ Material / Cupertino / Widgets / Rendering
+ ─────────────────────
+ Flutter Engine (C/C++)
+ Impeller/Skia, Dart VM, dart:ui, Text
+ ─────────────────────
+ Platform Embedder (per-OS native code)
+ ─────────────────────
+ Operating System
+```
+
+The **Framework** (Dart) contains widgets, rendering, animation. The **Engine** (C++) provides the Dart runtime, graphics backend, and text layout. The **Embedder** provides a rendering surface, lifecycle, and input events.
+
+### 2.2 The Three Trees
+
+Flutter maintains three parallel trees:
+
+**Widget Tree** -- Immutable, lightweight configuration objects. Recreated on every rebuild (cheap). Widgets describe UI declaratively. A `Container` with a color internally becomes a `ColoredBox`.
+
+**Element Tree** -- Persistent, mutable runtime representation. Each widget inflates into an `Element` holding the current widget and (for `StatefulWidget`) the `State` object. Elements survive across rebuilds; destroyed only when widget type or key changes. Two categories:
+- `ComponentElement` -- hosts other elements, has no `RenderObject`.
+- `RenderObjectElement` -- intermediary between widget and `RenderObject`.
+
+**RenderObject Tree** -- Used for layout, painting, hit testing, compositing. Long-lived and mutable. Stores geometry and visual properties. A projection of the element tree: only `RenderObjectWidget`-backed elements contribute a node. Layout and paint walk only this tree.
+
+**`BuildContext`** is the `Element` itself.
+
+### 2.3 Reconciliation
+
+Flutter uses **linear child-list reconciliation** (not tree diffing):
+
+1. Match children from beginning and end of old and new lists by `runtimeType` and `key`.
+2. Hash remaining unmatched old children by `key`.
+3. Walk remaining new children, querying hash table for matches.
+4. Unmatched old children are unmounted.
+5. Matched children are updated; unmatched new children create fresh elements.
+
+Optimized for common cases: identical lists, single insertion/removal, key-based reordering.
+
+#### Element Lifecycle
+
+1. **`mount()`** -- Inserted into tree, creates `RenderObject`.
+2. **`update(widget)`** -- Parent rebuilds with same-type widget, propagates changes.
+3. **`deactivate()`** -- Removed from tree (may be reactivated same frame via `GlobalKey`).
+4. **`unmount()`** -- End of frame, resources released.
+
+`GlobalKey` enables tree surgery: a widget moved to a different tree location preserves its `Element`, `State`, and `RenderObject`.
+
+### 2.4 Layout System
+
+Single-pass constraint-based layout:
+
+1. **Constraints go down** -- Parent calls `child.layout(BoxConstraints(...))`.
+2. **Sizes go up** -- Child computes its size within constraints and returns.
+3. **Parent sets position** -- Via `parentData`.
+
+Each render object visited at most twice (down and up). O(n) worst case.
+
+```dart
+class BoxConstraints {
+ final double minWidth, maxWidth;
+ final double minHeight, maxHeight;
+ bool get isTight => minWidth == maxWidth && minHeight == maxHeight;
+}
+```
+
+#### Layout Cutoff Optimizations
+
+- Not dirty + same constraints → skip entire subtree.
+- Tight constraints → child size fully determined, parent skips re-layout even if child internals change.
+- `sizedByParent` → size depends only on constraints, more aggressive cutoff.
+- `parentUsesSize` → if false, child size changes don't propagate upward.
+
+#### Sliver Protocol
+
+For scrollable content, `RenderSliver` receives viewport-aware `SliverConstraints` (visible space, scroll offset). Returns `SliverGeometry`. Enables:
+- Lazy child construction (only visible items).
+- Interleaved build and layout (framework can call `build()` during layout for slivers).
+
+### 2.5 Painting and Compositing
+
+After layout, `PipelineOwner.flushPaint()` processes dirty render objects in back-to-front depth order.
+
+Each `paint(PaintingContext, Offset)` call records draw commands onto a `Canvas` via `PictureRecorder`. When a compositing boundary is hit (opacity, clip, repaint boundary), the current recording finalizes into a `PictureLayer` and a new layer is pushed.
+
+#### Layer Tree
+
+Painting produces a tree of `Layer` objects:
+
+| Layer | Purpose |
+|---|---|
+| `ContainerLayer` | Parent of child layers |
+| `OffsetLayer` | Position offset (repaint boundaries use this) |
+| `PictureLayer` | Immutable sequence of draw commands |
+| `ClipPathLayer` | Clipping |
+| `OpacityLayer` | Transparency |
+| `TextureLayer` | External textures |
+| `PlatformViewLayer` | Native views embedded in Flutter |
+
+#### Retained Rendering
+
+Unchanged layers reuse previously rasterized bitmaps via `SceneBuilder.addRetained()`. Each layer tracks whether it needs re-adding to the scene.
+
+#### Scene Submission
+
+1. Root `ContainerLayer` calls `buildScene()` using `SceneBuilder`.
+2. `SceneBuilder.build()` produces an immutable `Scene`.
+3. `Scene` is submitted to the engine via `FlutterView.render(scene)`.
+4. Engine converts to `LayerTree` → GPU commands → pixels.
+
+### 2.6 Impeller (Graphics Engine)
+
+Impeller replaces Skia as Flutter's GPU rendering backend:
+
+- **No runtime shader compilation** -- All shaders (~50) are hand-authored and compiled offline at engine build time. No shader jank ever.
+- **All Pipeline State Objects (PSOs) precompiled and cached.**
+- **Hardware Abstraction Layer (HAL)** -- Uniform interface over Metal (iOS/macOS), Vulkan (Android API 29+), OpenGL ES (Android fallback).
+- **Entity/Content system** -- Each drawable is an `Entity` with a transform matrix, `Contents` (rendering implementation), blend mode, and clip depth. Geometry and shading are cleanly separated.
+- **Tessellation** -- Vector paths broken into triangles for GPU rendering via geometry classes with `GetPositionBuffer()`.
+
+Status (Flutter 3.27+):
+- iOS: Impeller only (Skia removed).
+- Android: Impeller default on API 29+ (Vulkan), OpenGL ES fallback.
+- Web: Not Impeller; uses CanvasKit/SkWasm (Skia-based).
+
+Impeller still uses Skia's `SkParagraph` for text layout and Skia's image codecs for decompression.
+
+### 2.7 Platform Embedding
+
+Flutter owns the **entire rendering surface**. The platform provides only a blank canvas:
+
+**Android**: `FlutterActivity` hosts a `FlutterView` (a `FrameLayout` wrapping either `FlutterSurfaceView` or `FlutterTextureView`). The engine draws directly to the `Surface`.
+
+**iOS**: `FlutterViewController` attaches to a `FlutterEngine`. Rendering via Metal to `CAMetalLayer`.
+
+**Platform Views** (native widgets inside Flutter): Hybrid composition copies native view textures into Flutter's compositing pipeline. Hit testing and gestures are bridged between coordinate systems.
+
+### 2.8 Update Cycle (Frame Pipeline)
+
+When `setState()` is called:
+
+1. Element marked dirty, `scheduleFrame()` called.
+2. Engine requests vsync from platform.
+3. On vsync:
+
+| Phase | What happens |
+|---|---|
+| **Animation** | Tickers/AnimationControllers update values |
+| **Build** | Dirty elements call `build()`, reconcile children |
+| **Layout** | `flushLayout()` -- constraints down, sizes up |
+| **Compositing bits** | `flushCompositingBits()` -- update layer requirements |
+| **Paint** | `flushPaint()` -- record draw commands into layer tree |
+| **Composite** | `compositeFrame()` -- build Scene, submit to engine |
+| **Semantics** | `flushSemantics()` -- update accessibility tree |
+
+Target: 60 or 120 fps (16.6ms or 8.3ms frame budget).
+
+### 2.9 Dart Runtime
+
+**AOT compilation** -- Release builds compile Dart to native ARM/x64 machine code. No JIT overhead, no serialization bridge.
+
+**Single-threaded event loop** -- Cooperative scheduling within each isolate. Frame callbacks run synchronously. If a phase exceeds the frame budget, jank occurs.
+
+**Isolates** -- For CPU-bound work (>100ms), spawn an isolate (separate memory, message passing). No shared-memory concurrency bugs.
+
+**No serialization bridge** -- Dart code communicates with the C++ engine via `dart:ui` directly (compiled to native). Platform channels use serialization but only for platform API access, not rendering.
+
+### 2.10 Threading Model
+
+Historically four task runners:
+
+| Runner | Role |
+|---|---|
+| **Platform** | Main OS thread, lifecycle, plugin API calls |
+| **UI** | Dart execution, build/layout/paint |
+| **Raster** | GPU command submission |
+| **IO** | Image decompression, texture prep |
+
+As of Flutter 3.29+, **UI and Platform threads are merged** on iOS and Android. Dart code runs directly on the native platform thread. The raster thread remains separate.
+
+---
+
+## Part 3: Comparison and Lessons for haskell-mobile
+
+### 3.1 Rendering Strategy
+
+| | React Native | Flutter | haskell-mobile |
+|---|---|---|---|
+| **Strategy** | Delegate to platform | Own the surface | Delegate to platform |
+| **Native look** | Automatic (uses real native widgets) | Must be reimplemented (Material/Cupertino) | Automatic (native widgets) |
+| **Consistency** | Varies by platform version | Pixel-identical everywhere | Varies by platform |
+| **Drawing custom UI** | Difficult (need native modules) | Natural (Canvas API) | Not yet supported |
+
+haskell-mobile follows the React Native strategy: send widget descriptions across a language boundary and let the platform render them. This gives native look-and-feel for free but introduces a communication boundary.
+
+### 3.2 Language Boundary
+
+| | React Native | Flutter | haskell-mobile |
+|---|---|---|---|
+| **Bridge** | JSI (C++ host objects, sync capable) | None (Dart compiles to native) | FFI (`foreign export ccall`) |
+| **Serialization** | Eliminated with JSI | None | C structs / manual marshaling |
+| **Latency** | Low (direct C++ calls) | Zero | Low (direct function calls) |
+
+Flutter's biggest architectural advantage is that Dart compiles to native code and shares the process with the engine. There is no bridge at all for rendering.
+
+React Native's JSI eliminates the old serialization bottleneck but still crosses a language boundary (JS VM → C++).
+
+haskell-mobile uses direct FFI exports, which is conceptually similar to JSI but lower-level. The main pain point is marshaling complex data structures across the boundary.
+
+### 3.3 Layout
+
+| | React Native | Flutter |
+|---|---|---|
+| **Engine** | Yoga (C++ flexbox subset) | Built-in constraint propagation |
+| **Model** | CSS flexbox properties | BoxConstraints (min/max width/height) |
+| **Complexity** | Multi-pass (up to 3+ passes) | Single-pass with cutoffs |
+| **Custom protocols** | No | Yes (RenderSliver for scrolling) |
+
+Flutter's layout is simpler (single-pass, O(n)) but less familiar to web developers. Yoga implements a more complex multi-pass algorithm to match CSS flexbox semantics.
+
+For haskell-mobile, layout is currently handled by the platform (iOS Auto Layout, Android LayoutParams). If haskell-mobile ever needs its own layout engine, Flutter's constraint propagation model is simpler to implement than full flexbox.
+
+### 3.4 Tree Reconciliation
+
+Both use O(n) algorithms with similar structure:
+
+| | React | Flutter |
+|---|---|---|
+| **Identity** | `type` + `key` | `runtimeType` + `key` |
+| **Children** | Positional comparison + key map | Match ends, then key hash table |
+| **Unchanged** | Skip subtree (memoizedProps === pendingProps) | Skip subtree (identical widget reference) |
+| **State** | Preserved when type+key match | Preserved when runtimeType+key match |
+
+The algorithms are nearly identical in spirit. Both prioritize the common case (lists that barely change) and use keys for reordering.
+
+### 3.5 What This Means for haskell-mobile
+
+**React Native's model is closer to what haskell-mobile does**: both describe a native widget tree from a non-native language and send updates across a boundary. Key lessons:
+
+1. **Immutable shadow trees with structural sharing** (Fabric) are the right model for cross-boundary rendering. haskell-mobile's widget descriptions should be diffable with minimal allocation.
+
+2. **Layout should stay on the native side** unless there's a strong reason to move it. Both React Native and haskell-mobile benefit from Yoga/platform layout because it avoids reimplementing text measurement and platform conventions.
+
+3. **Synchronous communication matters**. React Native's move from async bridge to synchronous JSI was their biggest architectural improvement. haskell-mobile already has synchronous FFI, which is an advantage.
+
+4. **The Flutter model (own the surface) eliminates the bridge problem entirely** but requires reimplementing all platform UI. This is a massive engineering investment that only makes sense with a large team.
+
+5. **AOT compilation eliminates the serialization bridge entirely**. Haskell's compiled-to-native story via GHC is analogous to Dart's AOT compilation -- both produce native machine code that can call C functions directly. This is a structural advantage over JavaScript-based frameworks.
+
+---
+
+## References
+
+### React
+- [React Official: Render and Commit](https://react.dev/learn/render-and-commit)
+- [React Legacy: Reconciliation](https://legacy.reactjs.org/docs/reconciliation.html)
+- [React Native Architecture](https://reactnative.dev/architecture/landing-page)
+- [React Native: Fabric Renderer](https://reactnative.dev/architecture/fabric-renderer)
+- [React Native: Render Pipeline](https://reactnative.dev/architecture/render-pipeline)
+- [React Native: Threading Model](https://reactnative.dev/architecture/threading-model)
+- [GitHub: acdlite/react-fiber-architecture](https://github.com/acdlite/react-fiber-architecture)
+- [AG Grid: Inside Fiber Reconciliation](https://blog.ag-grid.com/inside-fiber-an-in-depth-overview-of-the-new-reconciliation-algorithm-in-react/)
+- [jser.dev: What are Lanes in React Source Code?](https://jser.dev/react/2022/03/26/lanes-in-react/)
+- [GitHub: facebook/yoga](https://github.com/facebook/yoga)
+- [Yoga Official](https://www.yogalayout.dev/)
+- [Meta Engineering: Yoga](https://engineering.fb.com/2016/12/07/android/yoga-a-cross-platform-layout-engine/)
+
+### Flutter
+- [Flutter: Inside Flutter](https://docs.flutter.dev/resources/inside-flutter)
+- [Flutter: Architectural Overview](https://docs.flutter.dev/resources/architectural-overview)
+- [Flutter: Impeller Rendering Engine](https://docs.flutter.dev/perf/impeller)
+- [Flutter Engine Architecture](https://github.com/flutter/flutter/blob/main/docs/about/The-Engine-architecture.md)
+- [Impeller README (flutter/engine)](https://github.com/flutter/engine/blob/main/impeller/README.md)
+- [DeepWiki: Flutter Engine Architecture](https://deepwiki.com/flutter/flutter/4-engine-architecture)
+- [Flutter: Understanding Constraints](https://docs.flutter.dev/ui/layout/constraints)
+- [PipelineOwner API](https://api.flutter.dev/flutter/rendering/PipelineOwner-class.html)
+- [RenderBox API](https://api.flutter.dev/flutter/rendering/RenderBox-class.html)
+- [Dart Concurrency](https://dart.dev/language/concurrency)
+- [Flutter Isolates](https://docs.flutter.dev/perf/isolates)
+- [Thread Merge (GitHub issue)](https://github.com/flutter/flutter/issues/150525)
diff --git a/template.cabal b/haskell-mobile.cabal
similarity index 58%
rename from template.cabal
rename to haskell-mobile.cabal
index 426dcb4f..f3bcc227 100644
--- a/template.cabal
+++ b/haskell-mobile.cabal
@@ -1,12 +1,12 @@
cabal-version: 3.0
-name: template
+name: haskell-mobile
version: 1.0.0
-homepage: https://github.com/jappeace/template#readme
-bug-reports: https://github.com/jappeace/template/issues
+homepage: https://github.com/jappeace/haskell-mobile#readme
+bug-reports: https://github.com/jappeace/haskell-mobile/issues
author: Jappie Klooster
maintainer: hi@jappie.me
-copyright: 2025 Jappie Klooster
+copyright: 2026 Jappie Klooster
license: MIT
license-file: LICENSE
build-type: Simple
@@ -18,10 +18,10 @@ extra-doc-files:
source-repository head
type: git
- location: https://github.com/jappeace/template
+ location: https://github.com/jappeace/haskell-mobile
common common-options
- default-extensions:
+ default-extensions:
EmptyCase
FlexibleContexts
FlexibleInstances
@@ -51,7 +51,6 @@ common common-options
-fdefer-diagnostics -Wunused-packages
-fenable-th-splice-warnings
-fno-omit-yields
- -threaded -rtsopts "-with-rtsopts=-N -M7G -T -Iw10"
build-depends:
base >=4.9.1.0 && <4.22.0
@@ -61,11 +60,31 @@ common common-options
library
import: common-options
exposed-modules:
- Template
- other-modules:
- Paths_template
+ HaskellMobile
+ HaskellMobile.AppContext
+ HaskellMobile.Types
+ HaskellMobile.App
+ HaskellMobile.Lifecycle
+ HaskellMobile.Widget
+ HaskellMobile.UIBridge
+ HaskellMobile.Render
+ HaskellMobile.Locale
+ HaskellMobile.I18n
+ HaskellMobile.Permission
hs-source-dirs:
src
+ build-depends:
+ text,
+ containers,
+ bytestring
+ c-sources:
+ cbits/android_stubs.c
+ cbits/platform_log.c
+ cbits/ui_bridge.c
+ cbits/locale.c
+ cbits/permission_bridge.c
+ include-dirs:
+ include
executable exe
import: common-options
@@ -73,20 +92,21 @@ executable exe
hs-source-dirs:
app
build-depends:
- template
- ghc-options: -Wno-unused-packages
+ haskell-mobile
+ ghc-options: -Wno-unused-packages -threaded -rtsopts "-with-rtsopts=-N -M7G -T -Iw10"
test-suite unit
import: common-options
type: exitcode-stdio-1.0
main-is: Test.hs
- ghc-options: -Wno-unused-packages
- other-modules:
- Paths_template
+ ghc-options: -Wno-unused-packages -threaded -rtsopts "-with-rtsopts=-N -M7G -T -Iw10"
hs-source-dirs:
test
build-depends:
tasty,
tasty-hunit,
tasty-quickcheck,
- template
+ haskell-mobile,
+ containers,
+ text,
+ bytestring
diff --git a/include/HaskellMobile.h b/include/HaskellMobile.h
new file mode 100644
index 00000000..1442bcc4
--- /dev/null
+++ b/include/HaskellMobile.h
@@ -0,0 +1,71 @@
+#ifndef HASKELL_MOBILE_H
+#define HASKELL_MOBILE_H
+
+#include
+
+/* GHC RTS initialization (call before any Haskell function) */
+void hs_init(int *argc, char **argv[]);
+
+/* Haskell FFI exports */
+char *haskellGreet(const char *name);
+
+/* Run the user's Haskell main :: IO (Ptr AppContext).
+ * Uses the GHC RTS API to evaluate ZCMain_main_closure and capture
+ * the returned context pointer — no foreign export ccall needed in
+ * the user's Main.hs.
+ * Call after hs_init(). Returns an opaque pointer to be passed to
+ * all subsequent haskell* calls. */
+void *haskellRunMain(void);
+
+/* Platform-aware logging (Android logcat / Apple os_log / stderr) */
+void haskellMobileLog(const char *msg);
+
+/* Lifecycle event codes */
+#define LIFECYCLE_CREATE 0
+#define LIFECYCLE_START 1
+#define LIFECYCLE_RESUME 2
+#define LIFECYCLE_PAUSE 3
+#define LIFECYCLE_STOP 4
+#define LIFECYCLE_DESTROY 5
+#define LIFECYCLE_LOW_MEMORY 6
+
+/* Notify Haskell of a lifecycle event. Unknown codes are silently ignored.
+ * ctx must be a pointer returned by haskellRunMain(). */
+void haskellOnLifecycle(void *ctx, int eventType);
+
+/* Render the UI tree. Calls appView to get the widget description,
+ * then issues ui_* calls through the registered bridge callbacks.
+ * ctx must be a pointer returned by haskellRunMain(). */
+void haskellRenderUI(void *ctx);
+
+/* Dispatch a UI event (e.g. button click). Fires the callback
+ * registered for the given callbackId, then re-renders.
+ * ctx must be a pointer returned by haskellRunMain(). */
+void haskellOnUIEvent(void *ctx, int32_t callbackId);
+
+/* Dispatch a text change event. Fires the text-change callback
+ * registered for the given callbackId with the new text value.
+ * Does NOT re-render (avoids cursor/flicker issues).
+ * ctx must be a pointer returned by haskellRunMain(). */
+void haskellOnUITextChange(void *ctx, int32_t callbackId, const char *text);
+
+
+/* Log the detected system locale via platformLog.
+ * Called from platform bridges after setSystemLocale(). */
+void haskellLogLocale(void);
+
+/* Set the system locale string. Called by platform bridges during init.
+ * The caller owns the memory (must be static or strdup'd). */
+void setSystemLocale(const char *locale);
+
+/* Get the system locale string. Returns the value set by setSystemLocale(),
+ * or falls back to LANG env var (desktop) or "en" (default). */
+const char* getSystemLocale(void);
+
+/* Dispatch a permission result from native code back to Haskell.
+ * requestId: opaque ID from the original permission_request() call.
+ * statusCode: PERMISSION_GRANTED (0) or PERMISSION_DENIED (1).
+ * ctx must be a pointer returned by haskellRunMain(). */
+void haskellOnPermissionResult(void *ctx, int32_t requestId, int32_t statusCode);
+
+#endif /* HASKELL_MOBILE_H */
diff --git a/include/JniBridge.h b/include/JniBridge.h
new file mode 100644
index 00000000..2246f8b7
--- /dev/null
+++ b/include/JniBridge.h
@@ -0,0 +1,28 @@
+/*
+ * JniBridge.h — CPP macros for parameterised JNI symbol names.
+ *
+ * Consumers pass -DJNI_PACKAGE=me_jappie_myapp when compiling
+ * jni_bridge.c (and any extra JNI C sources) so the resulting
+ * symbols match the Java package of the actual application.
+ *
+ * Default: me_jappie_haskellmobile (haskell-mobile's own demo app).
+ */
+
+#ifndef JNI_BRIDGE_H
+#define JNI_BRIDGE_H
+
+#ifndef JNI_PACKAGE
+#define JNI_PACKAGE me_jappie_haskellmobile
+#endif
+
+#ifndef JNI_CLASS
+#define JNI_CLASS HaskellMobileActivity
+#endif
+
+/* Two levels of indirection so JNI_PACKAGE / JNI_CLASS are expanded
+ before token-pasting. */
+#define JNI_METHOD_NAME3(pkg, cls, m) Java_ ## pkg ## _ ## cls ## _ ## m
+#define JNI_METHOD_NAME2(pkg, cls, m) JNI_METHOD_NAME3(pkg, cls, m)
+#define JNI_METHOD(m) JNI_METHOD_NAME2(JNI_PACKAGE, JNI_CLASS, m)
+
+#endif /* JNI_BRIDGE_H */
diff --git a/include/PermissionBridge.h b/include/PermissionBridge.h
new file mode 100644
index 00000000..d7723c32
--- /dev/null
+++ b/include/PermissionBridge.h
@@ -0,0 +1,45 @@
+#ifndef PERMISSION_BRIDGE_H
+#define PERMISSION_BRIDGE_H
+
+#include
+
+/* Permission codes (must match HaskellMobile.Permission) */
+#define PERMISSION_LOCATION 0
+#define PERMISSION_BLUETOOTH 1
+#define PERMISSION_CAMERA 2
+#define PERMISSION_MICROPHONE 3
+#define PERMISSION_CONTACTS 4
+#define PERMISSION_STORAGE 5
+
+/* Permission status codes (must match HaskellMobile.Permission) */
+#define PERMISSION_GRANTED 0
+#define PERMISSION_DENIED 1
+
+/*
+ * Platform-agnostic permission bridge.
+ *
+ * Haskell calls permission_request / permission_check through these wrappers.
+ * When no platform callbacks are registered (desktop), stubs auto-grant
+ * so that cabal build/test works without native code.
+ *
+ * On Android/iOS the platform-specific setup function fills in real
+ * implementations via permission_register_impl().
+ */
+
+/* Request a runtime permission asynchronously.
+ * ctx: opaque Haskell context pointer (passed through to callback).
+ * permissionCode: one of PERMISSION_* constants.
+ * requestId: opaque ID from Haskell (used to dispatch the result). */
+void permission_request(void *ctx, int32_t permissionCode, int32_t requestId);
+
+/* Check whether a permission is currently granted (synchronous).
+ * Returns PERMISSION_GRANTED or PERMISSION_DENIED. */
+int32_t permission_check(int32_t permissionCode);
+
+/* Register platform-specific implementations.
+ * Called by platform setup functions (setup_android_permission_bridge, etc). */
+void permission_register_impl(
+ void (*request)(void *, int32_t, int32_t),
+ int32_t (*check)(int32_t));
+
+#endif /* PERMISSION_BRIDGE_H */
diff --git a/include/UIBridge.h b/include/UIBridge.h
new file mode 100644
index 00000000..ad9bd5f8
--- /dev/null
+++ b/include/UIBridge.h
@@ -0,0 +1,67 @@
+#ifndef UI_BRIDGE_H
+#define UI_BRIDGE_H
+
+#include
+
+/* Node types */
+#define UI_NODE_TEXT 0
+#define UI_NODE_BUTTON 1
+#define UI_NODE_COLUMN 2
+#define UI_NODE_ROW 3
+#define UI_NODE_TEXT_INPUT 4
+#define UI_NODE_SCROLL_VIEW 5
+#define UI_NODE_IMAGE 6
+
+/* Property IDs for string properties */
+#define UI_PROP_TEXT 0
+#define UI_PROP_COLOR 1
+#define UI_PROP_HINT 2
+#define UI_PROP_BG_COLOR 3
+#define UI_PROP_IMAGE_RESOURCE 4
+#define UI_PROP_IMAGE_FILE 5
+
+/* Property IDs for numeric properties */
+#define UI_PROP_FONT_SIZE 0
+#define UI_PROP_PADDING 1
+#define UI_PROP_INPUT_TYPE 2
+#define UI_PROP_GRAVITY 3
+#define UI_PROP_SCALE_TYPE 4
+
+/* Event types */
+#define UI_EVENT_CLICK 0
+#define UI_EVENT_TEXT_CHANGE 1
+
+/*
+ * Function pointer table filled by the platform (Android/iOS).
+ * Haskell calls through these pointers via ui_* wrappers.
+ * When NULL (desktop), stubs log to stderr and return dummy IDs.
+ */
+typedef struct UIBridgeCallbacks {
+ int32_t (*createNode)(int32_t nodeType);
+ void (*setStrProp)(int32_t nodeId, int32_t propId, const char *value);
+ void (*setNumProp)(int32_t nodeId, int32_t propId, double value);
+ void (*setImageData)(int32_t nodeId, const uint8_t *data, int32_t length);
+ void (*setHandler)(int32_t nodeId, int32_t eventType, int32_t callbackId);
+ void (*addChild)(int32_t parentId, int32_t childId);
+ void (*removeChild)(int32_t parentId, int32_t childId);
+ void (*destroyNode)(int32_t nodeId);
+ void (*setRoot)(int32_t nodeId);
+ void (*clear)(void);
+} UIBridgeCallbacks;
+
+/* Register platform callbacks. Ownership is NOT transferred. */
+void ui_register_callbacks(UIBridgeCallbacks *callbacks);
+
+/* Platform-agnostic wrappers (delegate to callbacks or desktop stubs) */
+int32_t ui_create_node(int32_t nodeType);
+void ui_set_str_prop(int32_t nodeId, int32_t propId, const char *value);
+void ui_set_num_prop(int32_t nodeId, int32_t propId, double value);
+void ui_set_image_data(int32_t nodeId, const uint8_t *data, int32_t length);
+void ui_set_handler(int32_t nodeId, int32_t eventType, int32_t callbackId);
+void ui_add_child(int32_t parentId, int32_t childId);
+void ui_remove_child(int32_t parentId, int32_t childId);
+void ui_destroy_node(int32_t nodeId);
+void ui_set_root(int32_t nodeId);
+void ui_clear(void);
+
+#endif /* UI_BRIDGE_H */
diff --git a/ios/HaskellMobile/ContentView.swift b/ios/HaskellMobile/ContentView.swift
new file mode 100644
index 00000000..380cbcf1
--- /dev/null
+++ b/ios/HaskellMobile/ContentView.swift
@@ -0,0 +1,56 @@
+import SwiftUI
+import UIKit
+
+/// Wraps a UIViewController whose view hierarchy is built by Haskell
+/// via the iOS UI bridge (UIBridgeIOS.m).
+struct HaskellUIView: UIViewControllerRepresentable {
+ func makeUIViewController(context: Context) -> UIViewController {
+ let vc = UIViewController()
+ vc.view.backgroundColor = .systemBackground
+ let ptr = Unmanaged.passUnretained(vc).toOpaque()
+ setup_ios_ui_bridge(ptr, HaskellBridge.getContext())
+
+ HaskellBridge.renderUI()
+
+ // CI auto-test: simulate button tap 3s after the initial render.
+ // Scheduled here (not in App.init) so the tap always fires AFTER
+ // the first render — on slow CI simulators, init() can run 60s+
+ // before SwiftUI creates the view.
+ if CommandLine.arguments.contains("--autotest") {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
+ HaskellBridge.onUIEvent(0)
+ }
+ }
+
+ // CI auto-test: exercise both "+" and "-" buttons.
+ // Sequence: +, +, -, -, - → Counter: 1, 2, 1, 0, -1
+ if CommandLine.arguments.contains("--autotest-buttons") {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
+ HaskellBridge.onUIEvent(0) // + → Counter: 1
+ }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
+ HaskellBridge.onUIEvent(0) // + → Counter: 2
+ }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 7) {
+ HaskellBridge.onUIEvent(1) // - → Counter: 1
+ }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 9) {
+ HaskellBridge.onUIEvent(1) // - → Counter: 0
+ }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 11) {
+ HaskellBridge.onUIEvent(1) // - → Counter: -1
+ }
+ }
+
+ return vc
+ }
+
+ func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
+}
+
+struct ContentView: View {
+ var body: some View {
+ HaskellUIView()
+ .edgesIgnoringSafeArea(.all)
+ }
+}
diff --git a/ios/HaskellMobile/HaskellBridge.swift b/ios/HaskellMobile/HaskellBridge.swift
new file mode 100644
index 00000000..e8e78521
--- /dev/null
+++ b/ios/HaskellMobile/HaskellBridge.swift
@@ -0,0 +1,61 @@
+import Foundation
+import os.log
+
+/// Swift wrapper around the Haskell FFI functions exposed via C.
+class HaskellBridge {
+ private static let bridgeLog = OSLog(subsystem: "me.jappie.haskellmobile", category: "UIBridge")
+ // Lifecycle event codes (must match HaskellMobile.h)
+ static let lifecycleCreate: Int32 = 0
+ static let lifecycleStart: Int32 = 1
+ static let lifecycleResume: Int32 = 2
+ static let lifecyclePause: Int32 = 3
+ static let lifecycleStop: Int32 = 4
+ static let lifecycleDestroy: Int32 = 5
+ static let lifecycleLowMemory: Int32 = 6
+
+ /// Opaque Haskell context pointer, created during initialization.
+ private static var context: UnsafeMutableRawPointer?
+
+ /// Initialize the Haskell RTS. Must be called before any other Haskell function.
+ static func initialize() {
+ hs_init(nil, nil)
+ context = haskellRunMain()
+ setup_ios_permission_bridge(context)
+ }
+
+ /// Call Haskell's haskellGreet and return the result as a Swift String.
+ /// The C-allocated string is freed after copying.
+ static func greet(_ name: String) -> String {
+ let result = haskellGreet(name)!
+ let greeting = String(cString: result)
+ free(result)
+ return greeting
+ }
+
+ /// Notify Haskell of a lifecycle event.
+ static func onLifecycle(_ event: Int32) {
+ haskellOnLifecycle(context, event)
+ }
+
+ /// Render the Haskell UI tree via the registered bridge callbacks.
+ static func renderUI() {
+ haskellRenderUI(context)
+ }
+
+ /// Dispatch a UI event (e.g. button tap) to Haskell, which re-renders.
+ static func onUIEvent(_ callbackId: Int32) {
+ os_log("Click dispatched: callbackId=%d", log: bridgeLog, type: .info, callbackId)
+ haskellOnUIEvent(context, callbackId)
+ }
+
+ /// Dispatch a text change event to Haskell (does not re-render).
+ static func onUITextChange(_ callbackId: Int32, text: String) {
+ haskellOnUITextChange(context, callbackId, text)
+ }
+
+ /// Return the opaque Haskell context pointer (for passing to C bridge setup).
+ static func getContext() -> UnsafeMutableRawPointer? {
+ return context
+ }
+
+}
diff --git a/ios/HaskellMobile/HaskellMobile-Bridging-Header.h b/ios/HaskellMobile/HaskellMobile-Bridging-Header.h
new file mode 100644
index 00000000..452972c5
--- /dev/null
+++ b/ios/HaskellMobile/HaskellMobile-Bridging-Header.h
@@ -0,0 +1,9 @@
+#include "HaskellMobile.h"
+#include "UIBridge.h"
+#include "PermissionBridge.h"
+
+/* iOS UI bridge setup — called from Swift before haskellRenderUI */
+void setup_ios_ui_bridge(void *viewController, void *haskellCtx);
+
+/* iOS permission bridge setup — called from Swift during initialisation */
+void setup_ios_permission_bridge(void *haskellCtx);
diff --git a/ios/HaskellMobile/HaskellMobileApp.swift b/ios/HaskellMobile/HaskellMobileApp.swift
new file mode 100644
index 00000000..3df7e606
--- /dev/null
+++ b/ios/HaskellMobile/HaskellMobileApp.swift
@@ -0,0 +1,29 @@
+import SwiftUI
+
+@main
+struct HaskellMobileApp: App {
+ @Environment(\.scenePhase) private var scenePhase
+
+ init() {
+ HaskellBridge.initialize()
+ HaskellBridge.onLifecycle(HaskellBridge.lifecycleCreate)
+ }
+
+ var body: some Scene {
+ WindowGroup {
+ ContentView()
+ }
+ .onChange(of: scenePhase) { newPhase in
+ switch newPhase {
+ case .active:
+ HaskellBridge.onLifecycle(HaskellBridge.lifecycleResume)
+ case .inactive:
+ HaskellBridge.onLifecycle(HaskellBridge.lifecyclePause)
+ case .background:
+ HaskellBridge.onLifecycle(HaskellBridge.lifecycleStop)
+ @unknown default:
+ break
+ }
+ }
+ }
+}
diff --git a/ios/HaskellMobile/PermissionBridgeIOS.m b/ios/HaskellMobile/PermissionBridgeIOS.m
new file mode 100644
index 00000000..db1f0b4f
--- /dev/null
+++ b/ios/HaskellMobile/PermissionBridgeIOS.m
@@ -0,0 +1,154 @@
+/*
+ * iOS implementation of the permission bridge callbacks.
+ *
+ * Uses platform APIs (AVFoundation, Contacts, CoreLocation) to check
+ * and request permissions. Compiled by Xcode, not GHC.
+ *
+ * All functions run on the main thread.
+ */
+
+#import
+#import
+#import
+#import
+#include "PermissionBridge.h"
+
+#define LOG_TAG "PermissionBridge"
+static os_log_t g_log;
+
+#define LOGI(fmt, ...) os_log_info(g_log, fmt, ##__VA_ARGS__)
+#define LOGE(fmt, ...) os_log_error(g_log, fmt, ##__VA_ARGS__)
+
+/* Haskell FFI export (dispatches result back to Haskell callback) */
+extern void haskellOnPermissionResult(void *ctx, int32_t requestId, int32_t statusCode);
+
+/* ---- Location manager delegate ---- */
+
+@interface PermissionLocationDelegate : NSObject
+@property (nonatomic, assign) int32_t requestId;
+@property (nonatomic, assign) void *haskellCtx;
+@property (nonatomic, strong) CLLocationManager *manager;
+@end
+
+@implementation PermissionLocationDelegate
+
+- (void)locationManagerDidChangeAuthorization:(CLLocationManager *)manager {
+ CLAuthorizationStatus status = manager.authorizationStatus;
+ /* Only dispatch once we have a definitive answer */
+ if (status == kCLAuthorizationStatusNotDetermined) return;
+
+ int32_t result = (status == kCLAuthorizationStatusAuthorizedWhenInUse ||
+ status == kCLAuthorizationStatusAuthorizedAlways)
+ ? PERMISSION_GRANTED : PERMISSION_DENIED;
+
+ LOGI("location authorization changed: %d -> result=%d", (int)status, result);
+ haskellOnPermissionResult(self.haskellCtx, self.requestId, result);
+}
+
+@end
+
+/* Retained delegate instance (must outlive the authorization flow) */
+static PermissionLocationDelegate *g_location_delegate = nil;
+
+/* ---- Permission bridge implementations ---- */
+
+static int32_t ios_permission_check(int32_t permissionCode)
+{
+ switch (permissionCode) {
+ case PERMISSION_CAMERA: {
+ AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
+ return (status == AVAuthorizationStatusAuthorized) ? PERMISSION_GRANTED : PERMISSION_DENIED;
+ }
+ case PERMISSION_MICROPHONE: {
+ AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
+ return (status == AVAuthorizationStatusAuthorized) ? PERMISSION_GRANTED : PERMISSION_DENIED;
+ }
+ case PERMISSION_CONTACTS: {
+ CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
+ return (status == CNAuthorizationStatusAuthorized) ? PERMISSION_GRANTED : PERMISSION_DENIED;
+ }
+ case PERMISSION_LOCATION: {
+ CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
+ return (status == kCLAuthorizationStatusAuthorizedWhenInUse ||
+ status == kCLAuthorizationStatusAuthorizedAlways)
+ ? PERMISSION_GRANTED : PERMISSION_DENIED;
+ }
+ case PERMISSION_BLUETOOTH:
+ case PERMISSION_STORAGE:
+ /* Bluetooth uses CBCentralManager state machine (not a simple check);
+ * storage is always available on modern iOS. Auto-grant both. */
+ return PERMISSION_GRANTED;
+ default:
+ LOGE("permission_check: unknown code %d", permissionCode);
+ return PERMISSION_DENIED;
+ }
+}
+
+static void ios_permission_request(void *ctx, int32_t permissionCode, int32_t requestId)
+{
+ LOGI("permission_request(code=%d, id=%d)", permissionCode, requestId);
+
+ switch (permissionCode) {
+ case PERMISSION_CAMERA: {
+ [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
+ dispatch_async(dispatch_get_main_queue(), ^{
+ haskellOnPermissionResult(ctx, requestId,
+ granted ? PERMISSION_GRANTED : PERMISSION_DENIED);
+ });
+ }];
+ break;
+ }
+ case PERMISSION_MICROPHONE: {
+ [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
+ dispatch_async(dispatch_get_main_queue(), ^{
+ haskellOnPermissionResult(ctx, requestId,
+ granted ? PERMISSION_GRANTED : PERMISSION_DENIED);
+ });
+ }];
+ break;
+ }
+ case PERMISSION_CONTACTS: {
+ CNContactStore *store = [[CNContactStore alloc] init];
+ [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError *error) {
+ dispatch_async(dispatch_get_main_queue(), ^{
+ haskellOnPermissionResult(ctx, requestId,
+ granted ? PERMISSION_GRANTED : PERMISSION_DENIED);
+ });
+ }];
+ break;
+ }
+ case PERMISSION_LOCATION: {
+ g_location_delegate = [[PermissionLocationDelegate alloc] init];
+ g_location_delegate.requestId = requestId;
+ g_location_delegate.haskellCtx = ctx;
+ g_location_delegate.manager = [[CLLocationManager alloc] init];
+ g_location_delegate.manager.delegate = g_location_delegate;
+ [g_location_delegate.manager requestWhenInUseAuthorization];
+ break;
+ }
+ case PERMISSION_BLUETOOTH:
+ case PERMISSION_STORAGE:
+ /* Auto-grant (see ios_permission_check comment) */
+ haskellOnPermissionResult(ctx, requestId, PERMISSION_GRANTED);
+ break;
+ default:
+ LOGE("permission_request: unknown code %d", permissionCode);
+ haskellOnPermissionResult(ctx, requestId, PERMISSION_DENIED);
+ break;
+ }
+}
+
+/* ---- Public API ---- */
+
+/*
+ * Set up the iOS permission bridge. Called from Swift during initialisation.
+ * Registers callbacks with the platform-agnostic dispatcher.
+ */
+void setup_ios_permission_bridge(void *haskellCtx)
+{
+ g_log = os_log_create("me.jappie.haskellmobile", LOG_TAG);
+
+ permission_register_impl(ios_permission_request, ios_permission_check);
+
+ LOGI("iOS permission bridge initialized");
+}
diff --git a/ios/HaskellMobile/UIBridgeIOS.m b/ios/HaskellMobile/UIBridgeIOS.m
new file mode 100644
index 00000000..c4a68dae
--- /dev/null
+++ b/ios/HaskellMobile/UIBridgeIOS.m
@@ -0,0 +1,673 @@
+/*
+ * iOS implementation of the UI bridge callbacks.
+ *
+ * Uses UIKit to create iOS views (UILabel, UIButton, UIStackView)
+ * and manage the view hierarchy. Compiled by Xcode, not GHC.
+ *
+ * All functions run on the main thread — the same thread that
+ * calls haskellRenderUI from Swift.
+ */
+
+#import
+#import
+#include
+#include
+#include "UIBridge.h"
+
+#define LOG_TAG "UIBridge"
+static os_log_t g_log;
+
+#define LOGI(fmt, ...) os_log_info(g_log, fmt, ##__VA_ARGS__)
+#define LOGE(fmt, ...) os_log_error(g_log, fmt, ##__VA_ARGS__)
+
+/* --- Node pool configuration ---
+ *
+ * Two compile-time flags control the pool strategy:
+ * -DMAX_NODES=N Override the static pool size (default 256).
+ * -DDYNAMIC_NODE_POOL Use malloc/realloc; MAX_NODES is ignored.
+ *
+ * Re-renders clear all nodes, so the pool only bounds a single frame. */
+#ifdef DYNAMIC_NODE_POOL
+ static __strong UIView **g_nodes = NULL;
+ static __strong UIView **g_content_views = NULL;
+ static int32_t g_pool_capacity = 0;
+ #define INITIAL_POOL_SIZE 256
+#else
+ #ifndef MAX_NODES
+ #define MAX_NODES 256
+ #endif
+ static __strong UIView *g_nodes[MAX_NODES];
+ static __strong UIView *g_content_views[MAX_NODES];
+#endif
+static int32_t g_next_node_id = 1;
+
+/* Haskell FFI exports (declared here since this file is compiled by Xcode) */
+extern void haskellOnUIEvent(void *ctx, int callbackId);
+extern void haskellOnUITextChange(void *ctx, int callbackId, const char *text);
+
+/* Locale detection (cbits/locale.c) */
+extern void setSystemLocale(const char *locale);
+
+/* Log detected locale from Haskell (HaskellMobile.Locale) */
+extern void haskellLogLocale(void);
+
+/* ---- Global state (valid only on the main thread) ---- */
+static UIViewController *g_viewController = nil;
+
+/* ---- Singleton handler for button taps ---- */
+@interface IOSBridgeHandler : NSObject
+@property (nonatomic, assign) void *haskellCtx;
++ (instancetype)shared;
+- (void)handleTap:(UIButton *)sender;
+- (void)handleTextChange:(UITextField *)sender;
+@end
+
+@implementation IOSBridgeHandler
+
++ (instancetype)shared {
+ static IOSBridgeHandler *instance = nil;
+ static dispatch_once_t onceToken;
+ dispatch_once(&onceToken, ^{
+ instance = [[IOSBridgeHandler alloc] init];
+ });
+ return instance;
+}
+
+- (void)handleTap:(UIButton *)sender {
+ int32_t callbackId = (int32_t)sender.tag;
+ LOGI("Click dispatched: callbackId=%d", callbackId);
+ haskellOnUIEvent(self.haskellCtx, callbackId);
+}
+
+- (void)handleTextChange:(UITextField *)sender {
+ int32_t callbackId = (int32_t)sender.tag;
+ NSString *text = sender.text ?: @"";
+ LOGI("TextChange dispatched: callbackId=%d text=\"%{public}s\"", callbackId, [text UTF8String]);
+ haskellOnUITextChange(self.haskellCtx, callbackId, [text UTF8String]);
+}
+
+@end
+
+/* ---- Node pool helpers ---- */
+
+#ifdef DYNAMIC_NODE_POOL
+/* Grow both pools so that nodeId < g_pool_capacity.
+ * ARC pointers: allocate new array with calloc (nil-init), copy old
+ * pointers, free old array. ARC retains are on the individual view
+ * assignments, not the array allocation itself. */
+static int ensure_pool_capacity(int32_t needed)
+{
+ if (needed < g_pool_capacity) return 0;
+ int32_t new_cap = g_pool_capacity ? g_pool_capacity : INITIAL_POOL_SIZE;
+ while (new_cap <= needed) new_cap *= 2;
+
+ __strong UIView **new_nodes = (__strong UIView **)calloc((size_t)new_cap, sizeof(UIView *));
+ __strong UIView **new_content = (__strong UIView **)calloc((size_t)new_cap, sizeof(UIView *));
+ if (!new_nodes || !new_content) {
+ LOGE("Node pool calloc failed (requested %d slots)", new_cap);
+ free(new_nodes);
+ free(new_content);
+ return -1;
+ }
+ if (g_nodes) {
+ memcpy(new_nodes, g_nodes, (size_t)g_pool_capacity * sizeof(UIView *));
+ free(g_nodes);
+ }
+ if (g_content_views) {
+ memcpy(new_content, g_content_views, (size_t)g_pool_capacity * sizeof(UIView *));
+ free(g_content_views);
+ }
+ g_nodes = new_nodes;
+ g_content_views = new_content;
+ g_pool_capacity = new_cap;
+ return 0;
+}
+#endif
+
+static UIView *get_node(int32_t nodeId)
+{
+#ifdef DYNAMIC_NODE_POOL
+ if (nodeId < 1 || nodeId >= g_pool_capacity) return nil;
+#else
+ if (nodeId < 1 || nodeId >= MAX_NODES) return nil;
+#endif
+ return g_nodes[nodeId];
+}
+
+/* ---- Forward declarations ---- */
+static int32_t ios_create_node(int32_t nodeType);
+static void ios_set_str_prop(int32_t nodeId, int32_t propId, const char *value);
+static void ios_set_num_prop(int32_t nodeId, int32_t propId, double value);
+static void ios_set_image_data(int32_t nodeId, const uint8_t *data, int32_t length);
+static void ios_set_handler(int32_t nodeId, int32_t eventType, int32_t callbackId);
+static void ios_add_child(int32_t parentId, int32_t childId);
+static void ios_remove_child(int32_t parentId, int32_t childId);
+static void ios_destroy_node(int32_t nodeId);
+static void ios_set_root(int32_t nodeId);
+static void ios_clear(void);
+
+static UIBridgeCallbacks g_ios_callbacks = {
+ .createNode = ios_create_node,
+ .setStrProp = ios_set_str_prop,
+ .setNumProp = ios_set_num_prop,
+ .setImageData = ios_set_image_data,
+ .setHandler = ios_set_handler,
+ .addChild = ios_add_child,
+ .removeChild = ios_remove_child,
+ .destroyNode = ios_destroy_node,
+ .setRoot = ios_set_root,
+ .clear = ios_clear,
+};
+
+/* ---- Hex color parser ---- */
+
+/*
+ * Parse a hex color string (#RGB, #RRGGBB, or #AARRGGBB) into a UIColor.
+ * Returns nil on invalid input.
+ */
+static UIColor *parse_hex_color(const char *hex)
+{
+ if (!hex || hex[0] != '#') return nil;
+ NSString *digits = [NSString stringWithUTF8String:hex + 1];
+ unsigned int raw = 0;
+ NSScanner *scanner = [NSScanner scannerWithString:digits];
+ if (![scanner scanHexInt:&raw]) return nil;
+
+ CGFloat alpha, red, green, blue;
+ switch (digits.length) {
+ case 3: {
+ /* #RGB -> expand each nibble */
+ unsigned int r = (raw >> 8) & 0xF;
+ unsigned int g = (raw >> 4) & 0xF;
+ unsigned int b = raw & 0xF;
+ alpha = 1.0;
+ red = (r * 0x11) / 255.0;
+ green = (g * 0x11) / 255.0;
+ blue = (b * 0x11) / 255.0;
+ break;
+ }
+ case 6:
+ /* #RRGGBB */
+ alpha = 1.0;
+ red = ((raw >> 16) & 0xFF) / 255.0;
+ green = ((raw >> 8) & 0xFF) / 255.0;
+ blue = (raw & 0xFF) / 255.0;
+ break;
+ case 8:
+ /* #AARRGGBB */
+ alpha = ((raw >> 24) & 0xFF) / 255.0;
+ red = ((raw >> 16) & 0xFF) / 255.0;
+ green = ((raw >> 8) & 0xFF) / 255.0;
+ blue = (raw & 0xFF) / 255.0;
+ break;
+ default:
+ return nil;
+ }
+ return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
+}
+
+/* ---- Callback implementation ---- */
+
+static int32_t ios_create_node(int32_t nodeType)
+{
+#ifdef DYNAMIC_NODE_POOL
+ if (ensure_pool_capacity(g_next_node_id) != 0) {
+ LOGE("Node pool exhausted (realloc failed at %d)", g_next_node_id);
+ return 0;
+ }
+#else
+ if (g_next_node_id >= MAX_NODES) {
+ LOGE("Node pool exhausted (max %d)", MAX_NODES);
+ return 0;
+ }
+#endif
+
+ UIView *view = nil;
+
+ switch (nodeType) {
+ case UI_NODE_TEXT: {
+ UILabel *label = [[UILabel alloc] init];
+ label.textAlignment = NSTextAlignmentCenter;
+ label.translatesAutoresizingMaskIntoConstraints = NO;
+ view = label;
+ break;
+ }
+ case UI_NODE_BUTTON: {
+ UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
+ button.translatesAutoresizingMaskIntoConstraints = NO;
+ [button addTarget:[IOSBridgeHandler shared]
+ action:@selector(handleTap:)
+ forControlEvents:UIControlEventTouchUpInside];
+ view = button;
+ break;
+ }
+ case UI_NODE_COLUMN: {
+ UIStackView *stack = [[UIStackView alloc] init];
+ stack.axis = UILayoutConstraintAxisVertical;
+ stack.alignment = UIStackViewAlignmentCenter;
+ stack.spacing = 8;
+ stack.translatesAutoresizingMaskIntoConstraints = NO;
+ view = stack;
+ break;
+ }
+ case UI_NODE_ROW: {
+ UIStackView *stack = [[UIStackView alloc] init];
+ stack.axis = UILayoutConstraintAxisHorizontal;
+ stack.alignment = UIStackViewAlignmentCenter;
+ stack.spacing = 8;
+ stack.translatesAutoresizingMaskIntoConstraints = NO;
+ view = stack;
+ break;
+ }
+ case UI_NODE_TEXT_INPUT: {
+ UITextField *textField = [[UITextField alloc] init];
+ textField.borderStyle = UITextBorderStyleRoundedRect;
+ textField.translatesAutoresizingMaskIntoConstraints = NO;
+ view = textField;
+ break;
+ }
+ case UI_NODE_IMAGE: {
+ UIImageView *imageView = [[UIImageView alloc] init];
+ imageView.contentMode = UIViewContentModeScaleAspectFit;
+ imageView.translatesAutoresizingMaskIntoConstraints = NO;
+ view = imageView;
+ break;
+ }
+ case UI_NODE_SCROLL_VIEW: {
+ UIScrollView *scrollView = [[UIScrollView alloc] init];
+ scrollView.translatesAutoresizingMaskIntoConstraints = NO;
+ /* Inner content stack — children are added here, not into scrollView directly */
+ UIStackView *contentStack = [[UIStackView alloc] init];
+ contentStack.axis = UILayoutConstraintAxisVertical;
+ contentStack.alignment = UIStackViewAlignmentFill;
+ contentStack.spacing = 0;
+ contentStack.translatesAutoresizingMaskIntoConstraints = NO;
+ [scrollView addSubview:contentStack];
+ UILayoutGuide *contentGuide = scrollView.contentLayoutGuide;
+ UILayoutGuide *frameGuide = scrollView.frameLayoutGuide;
+ [NSLayoutConstraint activateConstraints:@[
+ [contentStack.topAnchor constraintEqualToAnchor:contentGuide.topAnchor],
+ [contentStack.leadingAnchor constraintEqualToAnchor:contentGuide.leadingAnchor],
+ [contentStack.trailingAnchor constraintEqualToAnchor:contentGuide.trailingAnchor],
+ [contentStack.bottomAnchor constraintEqualToAnchor:contentGuide.bottomAnchor],
+ [contentStack.widthAnchor constraintEqualToAnchor:frameGuide.widthAnchor],
+ ]];
+ int32_t nodeId = g_next_node_id++;
+ g_nodes[nodeId] = scrollView;
+ g_content_views[nodeId] = contentStack;
+ LOGI("createNode(type=%d) -> %d", nodeType, nodeId);
+ return nodeId;
+ }
+ default:
+ LOGE("Unknown node type: %d", nodeType);
+ return 0;
+ }
+
+ int32_t nodeId = g_next_node_id++;
+ g_nodes[nodeId] = view;
+
+ LOGI("createNode(type=%d) -> %d", nodeType, nodeId);
+ return nodeId;
+}
+
+/* Show placeholder text inside an ImageView when the image source fails to load. */
+static void ios_set_image_placeholder(UIImageView *imageView, const char *message)
+{
+ UILabel *placeholder = [[UILabel alloc] init];
+ placeholder.text = [NSString stringWithUTF8String:message];
+ placeholder.textColor = [UIColor secondaryLabelColor];
+ placeholder.font = [UIFont systemFontOfSize:12.0];
+ placeholder.textAlignment = NSTextAlignmentCenter;
+ placeholder.translatesAutoresizingMaskIntoConstraints = NO;
+ [imageView addSubview:placeholder];
+ [NSLayoutConstraint activateConstraints:@[
+ [placeholder.centerXAnchor constraintEqualToAnchor:imageView.centerXAnchor],
+ [placeholder.centerYAnchor constraintEqualToAnchor:imageView.centerYAnchor],
+ ]];
+}
+
+static void ios_set_str_prop(int32_t nodeId, int32_t propId, const char *value)
+{
+ UIView *view = get_node(nodeId);
+ if (!view) return;
+
+ NSString *str = [NSString stringWithUTF8String:value];
+
+ switch (propId) {
+ case UI_PROP_TEXT:
+ LOGI("setStrProp(node=%d, text=\"%{public}s\")", nodeId, value);
+ if ([view isKindOfClass:[UILabel class]]) {
+ ((UILabel *)view).text = str;
+ } else if ([view isKindOfClass:[UIButton class]]) {
+ [((UIButton *)view) setTitle:str forState:UIControlStateNormal];
+ } else if ([view isKindOfClass:[UITextField class]]) {
+ ((UITextField *)view).text = str;
+ }
+ break;
+ case UI_PROP_HINT:
+ LOGI("setStrProp(node=%d, hint=\"%{public}s\")", nodeId, value);
+ if ([view isKindOfClass:[UITextField class]]) {
+ ((UITextField *)view).placeholder = str;
+ }
+ break;
+ case UI_PROP_COLOR: {
+ LOGI("setStrProp(node=%d, color=\"%{public}s\")", nodeId, value);
+ UIColor *color = parse_hex_color(value);
+ if (!color) break;
+ if ([view isKindOfClass:[UILabel class]]) {
+ ((UILabel *)view).textColor = color;
+ } else if ([view isKindOfClass:[UIButton class]]) {
+ [((UIButton *)view) setTitleColor:color forState:UIControlStateNormal];
+ } else if ([view isKindOfClass:[UITextField class]]) {
+ ((UITextField *)view).textColor = color;
+ }
+ break;
+ }
+ case UI_PROP_BG_COLOR: {
+ LOGI("setStrProp(node=%d, bgColor=\"%{public}s\")", nodeId, value);
+ UIColor *color = parse_hex_color(value);
+ if (!color) break;
+ view.backgroundColor = color;
+ break;
+ }
+ case UI_PROP_IMAGE_RESOURCE: {
+ LOGI("setStrProp(node=%d, imageResource=\"%{public}s\")", nodeId, value);
+ if ([view isKindOfClass:[UIImageView class]]) {
+ UIImage *image = [UIImage imageNamed:str];
+ if (image) {
+ ((UIImageView *)view).image = image;
+ } else {
+ LOGE("Image resource not found: %{public}s", value);
+ ios_set_image_placeholder((UIImageView *)view, "Image not found");
+ }
+ }
+ break;
+ }
+ case UI_PROP_IMAGE_FILE: {
+ LOGI("setStrProp(node=%d, imageFile=\"%{public}s\")", nodeId, value);
+ if ([view isKindOfClass:[UIImageView class]]) {
+ UIImage *image = [UIImage imageWithContentsOfFile:str];
+ if (image) {
+ ((UIImageView *)view).image = image;
+ } else {
+ LOGE("Failed to load image file: %{public}s", value);
+ ios_set_image_placeholder((UIImageView *)view, "Image not found");
+ }
+ }
+ break;
+ }
+ default:
+ LOGI("setStrProp: unknown propId %d", propId);
+ break;
+ }
+}
+
+static void ios_set_num_prop(int32_t nodeId, int32_t propId, double value)
+{
+ UIView *view = get_node(nodeId);
+ if (!view) return;
+
+ switch (propId) {
+ case UI_PROP_FONT_SIZE: {
+ UIFont *font = [UIFont systemFontOfSize:(CGFloat)value];
+ if ([view isKindOfClass:[UILabel class]]) {
+ ((UILabel *)view).font = font;
+ } else if ([view isKindOfClass:[UIButton class]]) {
+ ((UIButton *)view).titleLabel.font = font;
+ } else if ([view isKindOfClass:[UITextField class]]) {
+ ((UITextField *)view).font = font;
+ } else {
+ LOGI("setNumProp: fontSize ignored on non-text node=%d", nodeId);
+ break;
+ }
+ LOGI("setNumProp(node=%d, fontSize=%.1f)", nodeId, value);
+ break;
+ }
+ case UI_PROP_INPUT_TYPE: {
+ int inputType = (int)value;
+ if ([view isKindOfClass:[UITextField class]]) {
+ UIKeyboardType kbType;
+ switch (inputType) {
+ case 1: kbType = UIKeyboardTypeDecimalPad; break;
+ default: kbType = UIKeyboardTypeDefault; break;
+ }
+ ((UITextField *)view).keyboardType = kbType;
+ }
+ LOGI("setNumProp(node=%d, inputType=%d)", nodeId, inputType);
+ break;
+ }
+ case UI_PROP_PADDING: {
+ CGFloat pt = (CGFloat)value;
+ view.layoutMargins = UIEdgeInsetsMake(pt, pt, pt, pt);
+ LOGI("setNumProp(node=%d, padding=%.1f)", nodeId, value);
+ break;
+ }
+ case UI_PROP_SCALE_TYPE: {
+ /* Haskell 0 = ScaleFit, 1 = ScaleFill, 2 = ScaleNone */
+ if ([view isKindOfClass:[UIImageView class]]) {
+ UIViewContentMode mode;
+ switch ((int)value) {
+ case 1: mode = UIViewContentModeScaleAspectFill; break;
+ case 2: mode = UIViewContentModeCenter; break;
+ default: mode = UIViewContentModeScaleAspectFit; break;
+ }
+ ((UIImageView *)view).contentMode = mode;
+ }
+ LOGI("setNumProp(node=%d, scaleType=%d)", nodeId, (int)value);
+ break;
+ }
+ case UI_PROP_GRAVITY: {
+ /* Haskell 0 = AlignStart, 1 = AlignCenter, 2 = AlignEnd */
+ int gravity = (int)value;
+ if ([view isKindOfClass:[UILabel class]]) {
+ NSTextAlignment align;
+ switch (gravity) {
+ case 1: align = NSTextAlignmentCenter; break;
+ case 2: align = NSTextAlignmentRight; break;
+ default: align = NSTextAlignmentLeft; break;
+ }
+ ((UILabel *)view).textAlignment = align;
+ } else if ([view isKindOfClass:[UIButton class]]) {
+ UIControlContentHorizontalAlignment align;
+ switch (gravity) {
+ case 1: align = UIControlContentHorizontalAlignmentCenter; break;
+ case 2: align = UIControlContentHorizontalAlignmentTrailing; break;
+ default: align = UIControlContentHorizontalAlignmentLeading; break;
+ }
+ ((UIButton *)view).contentHorizontalAlignment = align;
+ } else if ([view isKindOfClass:[UIStackView class]]) {
+ UIStackViewAlignment align;
+ switch (gravity) {
+ case 1: align = UIStackViewAlignmentCenter; break;
+ case 2: align = UIStackViewAlignmentTrailing; break;
+ default: align = UIStackViewAlignmentLeading; break;
+ }
+ ((UIStackView *)view).alignment = align;
+ }
+ LOGI("setNumProp(node=%d, gravity=%d)", nodeId, gravity);
+ break;
+ }
+ default:
+ LOGI("setNumProp: unknown propId %d", propId);
+ break;
+ }
+}
+
+static void ios_set_image_data(int32_t nodeId, const uint8_t *data, int32_t length)
+{
+ UIView *view = get_node(nodeId);
+ if (!view) return;
+ if (![view isKindOfClass:[UIImageView class]]) return;
+
+ NSData *nsdata = [NSData dataWithBytes:data length:(NSUInteger)length];
+ UIImage *image = [UIImage imageWithData:nsdata];
+ if (image) {
+ ((UIImageView *)view).image = image;
+ } else {
+ LOGE("setImageData: failed to decode %d bytes (node=%d)", length, nodeId);
+ ios_set_image_placeholder((UIImageView *)view, "Image not found");
+ }
+ LOGI("setImageData(node=%d, %d bytes)", nodeId, length);
+}
+
+static void ios_set_handler(int32_t nodeId, int32_t eventType, int32_t callbackId)
+{
+ UIView *view = get_node(nodeId);
+ if (!view) return;
+
+ switch (eventType) {
+ case UI_EVENT_CLICK:
+ view.tag = callbackId;
+ LOGI("setHandler(node=%d, click, callback=%d)", nodeId, callbackId);
+ break;
+ case UI_EVENT_TEXT_CHANGE:
+ view.tag = callbackId;
+ if ([view isKindOfClass:[UITextField class]]) {
+ [(UITextField *)view addTarget:[IOSBridgeHandler shared]
+ action:@selector(handleTextChange:)
+ forControlEvents:UIControlEventEditingChanged];
+ }
+ LOGI("setHandler(node=%d, textChange, callback=%d)", nodeId, callbackId);
+ break;
+ default:
+ LOGI("setHandler: unknown eventType %d", eventType);
+ break;
+ }
+}
+
+static void ios_add_child(int32_t parentId, int32_t childId)
+{
+ UIView *parent = get_node(parentId);
+ UIView *child = get_node(childId);
+ if (!parent || !child) return;
+
+ /* For ScrollView nodes, children go into the content stack, not the scroll view itself */
+ UIView *addTarget = nil;
+#ifdef DYNAMIC_NODE_POOL
+ if (parentId >= 0 && parentId < g_pool_capacity)
+ addTarget = g_content_views[parentId];
+#else
+ if (parentId >= 0 && parentId < MAX_NODES)
+ addTarget = g_content_views[parentId];
+#endif
+ if (!addTarget) addTarget = parent;
+ if ([addTarget isKindOfClass:[UIStackView class]]) {
+ [(UIStackView *)addTarget addArrangedSubview:child];
+ } else {
+ [addTarget addSubview:child];
+ }
+}
+
+static void ios_remove_child(int32_t parentId, int32_t childId)
+{
+ UIView *parent = get_node(parentId);
+ UIView *child = get_node(childId);
+ if (!parent || !child) return;
+
+ if ([parent isKindOfClass:[UIStackView class]]) {
+ [(UIStackView *)parent removeArrangedSubview:child];
+ }
+ [child removeFromSuperview];
+}
+
+static void ios_destroy_node(int32_t nodeId)
+{
+ UIView *view = get_node(nodeId);
+ if (!view) return;
+
+ [view removeFromSuperview];
+ g_nodes[nodeId] = nil;
+}
+
+static void ios_set_root(int32_t nodeId)
+{
+ UIView *view = get_node(nodeId);
+ if (!view) return;
+
+ UIView *container = g_viewController.view;
+
+ /* Remove any previously set root views (but keep the container) */
+ for (UIView *sub in container.subviews) {
+ [sub removeFromSuperview];
+ }
+
+ [container addSubview:view];
+
+ /* Pin root view to fill the safe area / full screen.
+ * Using fill instead of center lets ScrollView expand to the full viewport. */
+ view.translatesAutoresizingMaskIntoConstraints = NO;
+ [NSLayoutConstraint activateConstraints:@[
+ [view.topAnchor constraintEqualToAnchor:container.safeAreaLayoutGuide.topAnchor],
+ [view.leadingAnchor constraintEqualToAnchor:container.leadingAnchor],
+ [view.trailingAnchor constraintEqualToAnchor:container.trailingAnchor],
+ [view.bottomAnchor constraintEqualToAnchor:container.bottomAnchor],
+ ]];
+
+ LOGI("setRoot(node=%d)", nodeId);
+}
+
+static void ios_clear(void)
+{
+ for (int i = 1; i < g_next_node_id; i++) {
+ if (g_nodes[i]) {
+ [g_nodes[i] removeFromSuperview];
+ g_nodes[i] = nil;
+ }
+ /* Clear content_views in the same pass */
+#ifdef DYNAMIC_NODE_POOL
+ if (g_content_views && i < g_pool_capacity)
+#endif
+ g_content_views[i] = nil;
+ }
+ g_next_node_id = 1;
+ /* Dynamic mode: keep allocations to avoid malloc/free churn each frame. */
+ LOGI("clear()");
+}
+
+/* ---- Public API ---- */
+
+/*
+ * Set up the iOS UI bridge. Called from Swift before haskellRenderUI.
+ * Registers callbacks with the platform-agnostic dispatcher.
+ *
+ * viewController: opaque pointer to the UIViewController (cast from Swift)
+ * haskellCtx: opaque Haskell context pointer
+ */
+void setup_ios_ui_bridge(void *viewController, void *haskellCtx)
+{
+ g_log = os_log_create("me.jappie.haskellmobile", LOG_TAG);
+
+ g_viewController = (__bridge UIViewController *)viewController;
+ [IOSBridgeHandler shared].haskellCtx = haskellCtx;
+
+#ifdef DYNAMIC_NODE_POOL
+ if (!g_nodes) {
+ g_pool_capacity = INITIAL_POOL_SIZE;
+ g_nodes = (__strong UIView **)calloc((size_t)g_pool_capacity, sizeof(UIView *));
+ g_content_views = (__strong UIView **)calloc((size_t)g_pool_capacity, sizeof(UIView *));
+ } else {
+ for (int i = 0; i < g_pool_capacity; i++) {
+ g_nodes[i] = nil;
+ g_content_views[i] = nil;
+ }
+ }
+#else
+ memset(g_nodes, 0, sizeof(g_nodes));
+ memset(g_content_views, 0, sizeof(g_content_views));
+#endif
+ g_next_node_id = 1;
+
+ ui_register_callbacks(&g_ios_callbacks);
+ LOGI("iOS UI bridge initialized");
+
+ /* Cache the system locale from NSLocale.currentLocale */
+ {
+ NSString *lang = [[NSLocale currentLocale] languageCode];
+ NSString *region = [[NSLocale currentLocale] countryCode];
+ NSString *tag = region
+ ? [NSString stringWithFormat:@"%@-%@", lang, region]
+ : lang;
+ setSystemLocale(strdup([tag UTF8String]));
+ haskellLogLocale();
+ }
+}
diff --git a/ios/project.yml b/ios/project.yml
new file mode 100644
index 00000000..bfbfe4df
--- /dev/null
+++ b/ios/project.yml
@@ -0,0 +1,32 @@
+name: HaskellMobile
+options:
+ bundleIdPrefix: me.jappie
+ deploymentTarget:
+ iOS: "15.0"
+
+targets:
+ HaskellMobile:
+ type: application
+ platform: iOS
+ sources:
+ - HaskellMobile
+ info:
+ path: HaskellMobile/Info.plist
+ properties:
+ CFBundleShortVersionString: "1.0"
+ CFBundleVersion: "1"
+ NSLocationWhenInUseUsageDescription: "This app needs your location."
+ NSBluetoothAlwaysUsageDescription: "This app needs Bluetooth access."
+ NSCameraUsageDescription: "This app needs camera access."
+ NSMicrophoneUsageDescription: "This app needs microphone access."
+ NSContactsUsageDescription: "This app needs access to your contacts."
+ UIApplicationSceneManifest:
+ UIApplicationSupportsMultipleScenes: false
+ UISceneConfigurations: {}
+ settings:
+ base:
+ PRODUCT_BUNDLE_IDENTIFIER: me.jappie.haskellmobile
+ SWIFT_OBJC_BRIDGING_HEADER: HaskellMobile/HaskellMobile-Bridging-Header.h
+ LIBRARY_SEARCH_PATHS: ["$(inherited)", "$(PROJECT_DIR)/lib"]
+ HEADER_SEARCH_PATHS: ["$(inherited)", "$(PROJECT_DIR)/include"]
+ OTHER_LDFLAGS: ["$(inherited)", "-lHaskellMobile", "-lz", "-liconv", "-lffi", "-lc++", "-framework", "AVFoundation", "-framework", "Contacts", "-framework", "CoreLocation"]
diff --git a/makefile b/makefile
index 544da9b4..c53c6c37 100644
--- a/makefile
+++ b/makefile
@@ -6,6 +6,14 @@ build:
test:
cabal test -j --ghc-options $(OPTIMIZATION)
+test-emulator:
+ nix-build nix/emulator.nix -o result-emulator
+ ./result-emulator/bin/test-lifecycle
+
+test-simulator:
+ nix-build nix/simulator.nix -o result-simulator
+ ./result-simulator/bin/test-lifecycle-ios
+
haddock:
cabal haddock all
diff --git a/nix/android.nix b/nix/android.nix
new file mode 100644
index 00000000..ef91484e
--- /dev/null
+++ b/nix/android.nix
@@ -0,0 +1,20 @@
+# Android shared library — thin wrapper around lib.nix.
+{ sources ? import ../npins
+, androidArch ? "aarch64"
+, mainModule ? ../app/MobileMain.hs
+, consumerCabalFile ? null
+, consumerCabal2Nix ? null
+, hpkgs ? (_: _: {}) # consumer haskellPackages overrides
+, maxNodes ? 256 # static pool size (ignored when dynamicNodePool=true)
+, dynamicNodePool ? false # use malloc/realloc instead of fixed array
+}:
+let
+ lib = import ./lib.nix { inherit sources androidArch; };
+ crossDeps = import ./cross-deps.nix {
+ inherit sources androidArch consumerCabalFile consumerCabal2Nix hpkgs;
+ };
+in
+lib.mkAndroidLib {
+ haskellMobileSrc = ../.;
+ inherit mainModule crossDeps maxNodes dynamicNodePool;
+}
diff --git a/nix/apk.nix b/nix/apk.nix
new file mode 100644
index 00000000..58a59fa9
--- /dev/null
+++ b/nix/apk.nix
@@ -0,0 +1,17 @@
+# APK packaging — thin wrapper around lib.nix.
+# Builds a multi-arch APK containing both arm64-v8a and armeabi-v7a.
+{ sources ? import ../npins }:
+let
+ lib = import ./lib.nix { inherit sources; };
+ sharedLibAarch64 = import ./android.nix { inherit sources; androidArch = "aarch64"; };
+ sharedLibArmv7a = import ./android.nix { inherit sources; androidArch = "armv7a"; };
+in
+lib.mkApk {
+ sharedLibs = [
+ { lib = sharedLibAarch64; abiDir = "arm64-v8a"; }
+ { lib = sharedLibArmv7a; abiDir = "armeabi-v7a"; }
+ ];
+ androidSrc = ../android;
+ apkName = "haskell-mobile.apk";
+ name = "haskell-mobile-apk";
+}
diff --git a/nix/ci.nix b/nix/ci.nix
new file mode 100644
index 00000000..1f179ee6
--- /dev/null
+++ b/nix/ci.nix
@@ -0,0 +1,26 @@
+{ sources ? import ../npins }:
+let
+ isDarwin = builtins.currentSystem == "aarch64-darwin"
+ || builtins.currentSystem == "x86_64-darwin";
+in {
+ # Build artifacts
+ native = import ../default.nix {};
+ android-aarch64 = import ./android.nix { inherit sources; };
+ android-armv7a = import ./android.nix { inherit sources; androidArch = "armv7a"; };
+ apk = import ./apk.nix { inherit sources; };
+ consumer-link-test = import ./test-link-consumer.nix { inherit sources; };
+
+ # Android combined test script (boot + run via CI: nix-build ... -o out && ./out/bin/test-all)
+ emulator-all = import ./emulator-all.nix { inherit sources; };
+ # armv7a (armeabi-v7a) emulator test — covers Wear OS watches (32-bit ARM)
+ emulator-armv7a = import ./emulator-all.nix { inherit sources; androidArch = "armv7a"; };
+} // (if isDarwin then {
+ # iOS library for artifact upload
+ ios-lib = import ./ios.nix { inherit sources; };
+ # iOS combined test script (boot + run via CI: nix-build ... -o out && ./out/bin/test-all-ios)
+ simulator-all = import ./simulator-all.nix { inherit sources; };
+ # watchOS library for artifact upload
+ watchos-lib = import ./watchos.nix { inherit sources; };
+ # watchOS combined test script (boot + run via CI)
+ watchos-simulator-all = import ./watchos-simulator-all.nix { inherit sources; };
+} else {})
diff --git a/nix/collect-deps.nix b/nix/collect-deps.nix
new file mode 100644
index 00000000..7e07a63f
--- /dev/null
+++ b/nix/collect-deps.nix
@@ -0,0 +1,81 @@
+# Collect pre-built Haskell package outputs into a single directory.
+#
+# Takes a list of nixpkgs haskellPackages derivations (already built by
+# nixpkgs infrastructure), walks their transitive closure via
+# propagatedBuildInputs, and collects .conf / .a files into:
+# $out/lib/*.a — static archives (only those referenced by hs-libraries)
+# $out/pkgdb/ — GHC package database (.conf + cache)
+#
+# This uses standard nixpkgs outputs rather than manual cabal builds.
+{ pkgs
+, ghcPkgCmd # full path to ghc-pkg (or cross ghc-pkg)
+, deps # list of haskellPackages derivations
+}:
+let
+ # GHC boot/wired-in packages — already provided by the cross-GHC, so they
+ # must not be collected again. Also excludes haskell-mobile itself
+ # (compiled separately in mkAndroidLib/mkIOSLib).
+ bootPackageNames = [
+ "base" "ghc-prim" "ghc-bignum" "ghc-internal" "integer-gmp"
+ "bytestring" "text" "array" "deepseq" "containers"
+ "template-haskell" "transformers" "mtl" "stm" "exceptions"
+ "filepath" "directory" "process" "unix" "time" "binary"
+ "parsec" "pretty" "ghc-boot-th" "ghc-boot" "ghc-heap"
+ "hpc" "Cabal" "Cabal-syntax" "os-string"
+ "haskell-mobile"
+ ];
+
+ isBootPackage = name: builtins.elem name bootPackageNames;
+
+ # Walk propagatedBuildInputs transitively to collect all Haskell deps.
+ collectTransitive = seen: drvs:
+ builtins.foldl' (acc: drv:
+ let name = drv.pname or "";
+ in if name == "" || isBootPackage name || builtins.hasAttr name acc
+ then acc
+ else
+ let subDeps = builtins.filter
+ (d: d ? pname && d ? isHaskellLibrary)
+ (drv.propagatedBuildInputs or []);
+ in collectTransitive (acc // { "${name}" = drv; }) subDeps
+ ) seen drvs;
+
+ allDeps = builtins.attrValues (collectTransitive {} deps);
+
+ depsList = builtins.concatStringsSep " " (map toString allDeps);
+
+in pkgs.runCommand "haskell-mobile-collected-deps" {
+ nativeBuildInputs = [ pkgs.findutils ];
+} ''
+ mkdir -p $out/lib $out/pkgdb
+
+ for pkg in ${depsList}; do
+ echo "Processing: $pkg"
+
+ # Copy .conf files, skipping benchmark/test sub-libraries
+ for conf in $(find "$pkg" -name "*.conf" -path "*/package.conf.d/*"); do
+ LIB_NAME=$(grep '^lib-name:' "$conf" | sed 's/^lib-name: *//' || true)
+ case "$LIB_NAME" in
+ *benchmark*|*test*) echo " skip sub-lib: $LIB_NAME"; continue ;;
+ esac
+ cp "$conf" $out/pkgdb/
+
+ # Copy only .a files referenced by this .conf's hs-libraries field
+ HS_LIBS=$(grep '^hs-libraries:' "$conf" | sed 's/^hs-libraries: *//')
+ for lib in $HS_LIBS; do
+ aFile=$(find "$pkg" -name "lib$lib.a" ! -name "*_p.a" | head -1)
+ if [ -n "$aFile" ]; then
+ cp "$aFile" $out/lib/
+ fi
+ done
+ done
+ done
+
+ ${ghcPkgCmd} --package-db=$out/pkgdb recache
+
+ echo "=== Package database ==="
+ ${ghcPkgCmd} --package-db=$out/pkgdb list
+
+ echo "=== Libraries ==="
+ ls -lh $out/lib/
+''
diff --git a/nix/cross-deps.nix b/nix/cross-deps.nix
new file mode 100644
index 00000000..7ab3fe9d
--- /dev/null
+++ b/nix/cross-deps.nix
@@ -0,0 +1,68 @@
+# Cross-compile Hackage packages for Android (aarch64 or armv7a).
+#
+# Uses nixpkgs haskellPackages infrastructure to build packages, then
+# collects the results via collect-deps.nix. The output contains:
+# $out/lib/*.a — static archives
+# $out/pkgdb/ — GHC package database (.conf + cache)
+#
+# Consumers supply their own dependencies via consumerCabalFile (IFD),
+# consumerCabal2Nix (pre-generated), or hpkgs overrides.
+{ sources
+, androidArch ? "aarch64"
+, consumerCabalFile ? null
+, consumerCabal2Nix ? null
+, hpkgs ? (_: _: {}) # consumer haskellPackages overrides
+}:
+let
+ archConfig = {
+ aarch64 = { crossAttr = "aarch64-android-prebuilt"; };
+ armv7a = { crossAttr = "armv7a-android-prebuilt"; };
+ }.${androidArch};
+
+ # armv7a: compiler-rt's cmake doesn't include "armv7a" in its ARM32 arch
+ # list, so builtin targets are empty and the build produces no output.
+ # We patch the nixpkgs source to fix this (see patch-compiler-rt.py).
+ nixpkgsSrc = import ./patched-nixpkgs.nix {
+ nixpkgsSrc = sources.nixpkgs;
+ inherit androidArch;
+ };
+
+ pkgs = import nixpkgsSrc {
+ config.allowUnfree = true;
+ config.android_sdk.accept_license = true;
+ };
+
+ # Cross-compilation toolchain
+ androidPkgs = pkgs.pkgsCross.${archConfig.crossAttr};
+
+ # Default overrides needed for cross-compilation:
+ # - vector: test suite uses GHC plugins (inspection-testing), incompatible
+ # with cross-compilation's external interpreter.
+ defaultOverrides = self: super: {
+ vector = pkgs.haskell.lib.dontBenchmark (pkgs.haskell.lib.dontCheck super.vector);
+ };
+
+ # armv7a: disable profiling — LLVM ARM backend crashes in
+ # ARMAsmPrinter::emitXXStructor when compiling profiled libraries.
+ ghcOverride = if androidArch == "armv7a"
+ then {
+ ghc = androidPkgs.haskellPackages.ghc.override { enableProfiledLibs = false; };
+ }
+ else {};
+
+ crossHaskellPkgs = androidPkgs.haskellPackages.override ({
+ overrides = pkgs.lib.composeExtensions defaultOverrides hpkgs;
+ } // ghcOverride);
+
+ ghc = crossHaskellPkgs.ghc;
+ ghcPkgCmd = "${ghc}/bin/${ghc.targetPrefix}ghc-pkg";
+
+ resolvedDeps = import ./resolve-deps.nix {
+ inherit pkgs consumerCabalFile consumerCabal2Nix;
+ haskellPkgs = crossHaskellPkgs;
+ };
+
+in import ./collect-deps.nix {
+ inherit pkgs ghcPkgCmd;
+ deps = resolvedDeps;
+}
diff --git a/nix/emulator-all.nix b/nix/emulator-all.nix
new file mode 100644
index 00000000..849fe315
--- /dev/null
+++ b/nix/emulator-all.nix
@@ -0,0 +1,489 @@
+# Android emulator combined integration test.
+#
+# Single emulator session covering all test suites:
+#
+# Phase 1 — Counter app (lifecycle + UI rendering + two-button sequence)
+# Verifies: Lifecycle events, setRoot/setStrProp/setHandler logcat,
+# uiautomator view hierarchy, + and - buttons, counter state.
+#
+# Phase 2 — Scroll demo app
+# Verifies: createNode(type=5), android.widget.ScrollView in hierarchy,
+# swipe reveals Reached Bottom, tap dispatches click event.
+#
+# One boot + teardown cycle instead of four.
+#
+# Usage:
+# nix-build nix/emulator-all.nix -o result-emulator-all
+# ./result-emulator-all/bin/test-all
+{ sources ? import ../npins, androidArch ? "aarch64" }:
+let
+ pkgs = import sources.nixpkgs {
+ config.allowUnfree = true;
+ config.android_sdk.accept_license = true;
+ };
+
+ abiDir = { aarch64 = "arm64-v8a"; armv7a = "armeabi-v7a"; }.${androidArch};
+
+ # API 34 x86_64 emulator only has arm64-v8a translation (no armeabi-v7a).
+ # API 30 still has 32-bit ARM translation, needed for Wear OS armv7a APKs.
+ emulatorApiLevel = { aarch64 = "34"; armv7a = "30"; }.${androidArch};
+
+ lib = import ./lib.nix { inherit sources androidArch; };
+
+ counterAndroid = import ./android.nix { inherit sources androidArch; };
+ counterApk = lib.mkApk {
+ sharedLibs = [{ lib = counterAndroid; inherit abiDir; }];
+ androidSrc = ../android;
+ apkName = "haskell-mobile.apk";
+ name = "haskell-mobile-apk";
+ };
+
+ scrollAndroid = import ./android.nix {
+ inherit sources androidArch;
+ mainModule = ../test/ScrollDemoMain.hs;
+ };
+ scrollApk = lib.mkApk {
+ sharedLibs = [{ lib = scrollAndroid; inherit abiDir; }];
+ androidSrc = ../android;
+ apkName = "haskell-mobile-scroll.apk";
+ name = "haskell-mobile-scroll-apk";
+ };
+
+ textinputAndroid = import ./android.nix {
+ inherit sources androidArch;
+ mainModule = ../test/TextInputDemoMain.hs;
+ };
+ textinputApk = lib.mkApk {
+ sharedLibs = [{ lib = textinputAndroid; inherit abiDir; }];
+ androidSrc = ../android;
+ apkName = "haskell-mobile-textinput.apk";
+ name = "haskell-mobile-textinput-apk";
+ };
+
+ permissionAndroid = import ./android.nix {
+ inherit sources androidArch;
+ mainModule = ../test/PermissionDemoMain.hs;
+ };
+ permissionApk = lib.mkApk {
+ sharedLibs = [{ lib = permissionAndroid; inherit abiDir; }];
+ androidSrc = ../android;
+ apkName = "haskell-mobile-permission.apk";
+ name = "haskell-mobile-permission-apk";
+ };
+
+ imageAndroid = import ./android.nix {
+ inherit sources androidArch;
+ mainModule = ../test/ImageDemoMain.hs;
+ };
+ imageApk = lib.mkApk {
+ sharedLibs = [{ lib = imageAndroid; inherit abiDir; }];
+ androidSrc = ../android;
+ apkName = "haskell-mobile-image.apk";
+ name = "haskell-mobile-image-apk";
+ };
+
+ nodepoolAndroid = import ./android.nix {
+ inherit sources androidArch;
+ mainModule = ../test/NodePoolTestMain.hs;
+ dynamicNodePool = true;
+ };
+ nodepoolApk = lib.mkApk {
+ sharedLibs = [{ lib = nodepoolAndroid; inherit abiDir; }];
+ androidSrc = ../android;
+ apkName = "haskell-mobile-nodepool.apk";
+ name = "haskell-mobile-nodepool-apk";
+ };
+
+ androidComposition = pkgs.androidenv.composeAndroidPackages {
+ platformVersions = [ emulatorApiLevel ];
+ includeEmulator = true;
+ includeSystemImages = true;
+ systemImageTypes = [ "google_apis_playstore" ];
+ abiVersions = [ "x86_64" ];
+ cmdLineToolsVersion = "8.0";
+ };
+
+ sdk = androidComposition.androidsdk;
+ sdkRoot = "${sdk}/libexec/android-sdk";
+
+ platformVersion = emulatorApiLevel;
+ systemImageType = "google_apis_playstore";
+ abiVersion = "x86_64";
+ imagePackage = "system-images;android-${platformVersion};${systemImageType};${abiVersion}";
+
+ testScripts = builtins.path { path = ../test; name = "test-scripts"; };
+
+in pkgs.stdenv.mkDerivation {
+ name = "haskell-mobile-emulator-all-tests";
+
+ dontUnpack = true;
+
+ buildPhase = ''
+ mkdir -p $out/bin
+
+ cat > $out/bin/test-all << 'SCRIPT'
+#!/usr/bin/env bash
+set -euo pipefail
+
+# --- Configuration ---
+export ANDROID_SDK_ROOT="${sdkRoot}"
+export ANDROID_HOME="${sdkRoot}"
+unset ANDROID_NDK_HOME 2>/dev/null || true
+ADB="$ANDROID_SDK_ROOT/platform-tools/adb"
+EMULATOR="$ANDROID_SDK_ROOT/emulator/emulator"
+AVDMANAGER="${sdk}/bin/avdmanager"
+COUNTER_APK="${counterApk}/haskell-mobile.apk"
+SCROLL_APK="${scrollApk}/haskell-mobile-scroll.apk"
+TEXTINPUT_APK="${textinputApk}/haskell-mobile-textinput.apk"
+PERMISSION_APK="${permissionApk}/haskell-mobile-permission.apk"
+IMAGE_APK="${imageApk}/haskell-mobile-image.apk"
+NODEPOOL_APK="${nodepoolApk}/haskell-mobile-nodepool.apk"
+PACKAGE="me.jappie.haskellmobile"
+ACTIVITY=".MainActivity"
+DEVICE_NAME="test_all"
+TEST_SCRIPTS="${testScripts}"
+
+# --- Debug: show SDK structure ---
+echo "=== SDK structure ==="
+echo "SDK_ROOT: $ANDROID_SDK_ROOT"
+ls "$ANDROID_SDK_ROOT/" 2>/dev/null || echo "(cannot list SDK root)"
+echo "--- system-images ---"
+ls -R "$ANDROID_SDK_ROOT/system-images/" 2>/dev/null | head -20 || echo "(no system-images)"
+echo "=== End SDK structure ==="
+
+# --- KVM detection ---
+if [ -e /dev/kvm ] && [ -r /dev/kvm ] && [ -w /dev/kvm ]; then
+ echo "KVM detected -- using hardware acceleration"
+ ACCEL_FLAG=""
+ BOOT_TIMEOUT=180
+else
+ echo "No KVM -- using software emulation (slow boot expected)"
+ ACCEL_FLAG="-no-accel"
+ BOOT_TIMEOUT=900
+fi
+
+# --- Temp dirs ---
+WORK_DIR=$(mktemp -d /tmp/haskell-mobile-emu-all-XXXX)
+export HOME="$WORK_DIR/home"
+export ANDROID_USER_HOME="$WORK_DIR/user-home"
+export ANDROID_AVD_HOME="$WORK_DIR/avd"
+export ANDROID_EMULATOR_HOME="$WORK_DIR/emulator-home"
+export TMPDIR="$WORK_DIR/tmp"
+mkdir -p "$HOME" "$ANDROID_USER_HOME" "$ANDROID_AVD_HOME" "$ANDROID_EMULATOR_HOME" "$TMPDIR"
+
+"$ADB" kill-server 2>/dev/null || true
+"$ADB" start-server 2>/dev/null || true
+
+EMU_PID=""
+PORT=""
+
+# Phase result tracking
+PHASE1_OK=0
+PHASE2_OK=0
+PHASE3_OK=0
+PHASE4_OK=0
+PHASE5_OK=0
+PHASE6_OK=0
+
+cleanup() {
+ echo ""
+ echo "=== Cleaning up ==="
+ if [ -n "$EMU_PID" ] && kill -0 "$EMU_PID" 2>/dev/null; then
+ echo "Killing emulator (PID $EMU_PID)"
+ kill "$EMU_PID" 2>/dev/null || true
+ wait "$EMU_PID" 2>/dev/null || true
+ fi
+ if [ -n "$PORT" ]; then
+ "$ADB" -s "emulator-$PORT" emu kill 2>/dev/null || true
+ fi
+ rm -rf "$WORK_DIR"
+ echo "Cleanup done."
+}
+trap cleanup EXIT
+
+# --- Find free port ---
+echo "=== Finding free emulator port ==="
+for p in $(seq 5554 2 5584); do
+ if ! "$ADB" devices 2>/dev/null | grep -q "emulator-$p"; then
+ PORT=$p
+ break
+ fi
+done
+
+if [ -z "$PORT" ]; then
+ echo "ERROR: No free emulator port found (5554-5584 all in use)"
+ exit 1
+fi
+echo "Using port: $PORT"
+export ANDROID_SERIAL="emulator-$PORT"
+EMULATOR_SERIAL="emulator-$PORT"
+
+# --- Create AVD ---
+echo "=== Creating AVD ==="
+echo "n" | "$AVDMANAGER" create avd \
+ --force \
+ --name "$DEVICE_NAME" \
+ --package "${imagePackage}" \
+ --device "pixel_6" \
+ -p "$ANDROID_AVD_HOME/$DEVICE_NAME.avd"
+
+cat >> "$ANDROID_AVD_HOME/$DEVICE_NAME.avd/config.ini" << 'AVDCONF'
+hw.ramSize = 4096
+hw.gpu.enabled = yes
+hw.gpu.mode = swiftshader_indirect
+disk.dataPartition.size = 2G
+AVDCONF
+
+echo "=== AVD config.ini ==="
+cat "$ANDROID_AVD_HOME/$DEVICE_NAME.avd/config.ini"
+echo "=== End config.ini ==="
+
+# Fix system image path if needed
+SYSIMG_DIR="$ANDROID_SDK_ROOT/system-images/android-${platformVersion}/${systemImageType}/${abiVersion}"
+if [ ! -d "$SYSIMG_DIR" ]; then
+ echo "WARNING: Expected system image dir not found: $SYSIMG_DIR"
+ FOUND_SYSIMG=$(find "$ANDROID_SDK_ROOT" -name "system.img" -print -quit 2>/dev/null || echo "")
+ if [ -n "$FOUND_SYSIMG" ]; then
+ SYSIMG_DIR=$(dirname "$FOUND_SYSIMG")
+ echo "Found system image at: $SYSIMG_DIR"
+ sed -i "s|^image.sysdir.1=.*|image.sysdir.1=$SYSIMG_DIR/|" "$ANDROID_AVD_HOME/$DEVICE_NAME.avd/config.ini"
+ echo "Patched image.sysdir.1 in AVD config"
+ else
+ echo "ERROR: Could not find system.img anywhere in SDK"
+ fi
+else
+ echo "System image dir exists: $SYSIMG_DIR"
+fi
+
+# --- Boot emulator ---
+echo "=== Booting emulator ==="
+"$EMULATOR" \
+ -avd "$DEVICE_NAME" \
+ -no-window \
+ -no-audio \
+ -no-boot-anim \
+ -no-metrics \
+ -port "$PORT" \
+ -gpu swiftshader_indirect \
+ -no-snapshot \
+ -memory 4096 \
+ $ACCEL_FLAG \
+ &
+EMU_PID=$!
+echo "Emulator PID: $EMU_PID"
+
+# --- Wait for boot ---
+echo "=== Waiting for boot (timeout: ''${BOOT_TIMEOUT}s) ==="
+BOOT_DONE=""
+ELAPSED=0
+while [ $ELAPSED -lt $BOOT_TIMEOUT ]; do
+ BOOT_DONE=$("$ADB" -s "emulator-$PORT" shell getprop sys.boot_completed 2>/dev/null | tr -d '\r\n' || echo "")
+ if [ "$BOOT_DONE" = "1" ]; then
+ echo "Boot completed after ~''${ELAPSED}s"
+ break
+ fi
+ sleep 10
+ ELAPSED=$((ELAPSED + 10))
+ if [ $((ELAPSED % 60)) -eq 0 ]; then
+ echo " Still waiting... (''${ELAPSED}s elapsed)"
+ fi
+done
+
+if [ "$BOOT_DONE" != "1" ]; then
+ echo "ERROR: Emulator failed to boot within ''${BOOT_TIMEOUT}s"
+ exit 1
+fi
+
+echo "Waiting for device to settle..."
+sleep 30
+
+# ===========================================================================
+# PHASE 1 + PHASE 2 — Run test scripts
+# ===========================================================================
+export ADB EMULATOR_SERIAL COUNTER_APK SCROLL_APK TEXTINPUT_APK PERMISSION_APK IMAGE_APK NODEPOOL_APK PACKAGE ACTIVITY WORK_DIR
+
+PHASE1_EXIT=0
+PHASE2_EXIT=0
+PHASE3_EXIT=0
+PHASE4_EXIT=0
+PHASE5_EXIT=0
+PHASE6_EXIT=0
+
+# run_with_retry LABEL COMMAND [ARGS...]
+# Runs the command up to 10 times. Succeeds on first pass, fails only if all 10 fail.
+# If the command outputs "FATAL:", retrying is pointless (e.g. native library failed
+# to load), so we stop immediately and report the error.
+run_with_retry() {
+ local label="$1"; shift
+ local max_attempts=10
+ local attempt=1
+ local output_file="$WORK_DIR/retry_''${label}.log"
+ while [ $attempt -le $max_attempts ]; do
+ echo "[$label] attempt $attempt/$max_attempts"
+ if "$@" 2>&1 | tee "$output_file"; then
+ echo "[$label] PASSED on attempt $attempt"
+ return 0
+ fi
+ if grep -q "^FATAL:" "$output_file" 2>/dev/null; then
+ echo "[$label] FATAL error detected — not retrying"
+ return 1
+ fi
+ echo "[$label] attempt $attempt FAILED"
+ attempt=$((attempt + 1))
+ if [ $attempt -le $max_attempts ]; then
+ echo "[$label] retrying in 5s..."
+ sleep 5
+ fi
+ done
+ echo "[$label] FAILED after $max_attempts attempts"
+ return 1
+}
+
+echo ""
+echo "--- lifecycle ---"
+run_with_retry "lifecycle" bash "$TEST_SCRIPTS/android/lifecycle.sh" || PHASE1_EXIT=1
+echo "--- ui ---"
+run_with_retry "ui" bash "$TEST_SCRIPTS/android/ui.sh" || PHASE1_EXIT=1
+echo "--- buttons ---"
+run_with_retry "buttons" bash "$TEST_SCRIPTS/android/buttons.sh" || PHASE1_EXIT=1
+echo "--- scroll ---"
+run_with_retry "scroll" bash "$TEST_SCRIPTS/android/scroll.sh" || PHASE2_EXIT=1
+echo "--- styled ---"
+run_with_retry "styled" bash "$TEST_SCRIPTS/android/styled.sh" || PHASE1_EXIT=1
+echo "--- locale ---"
+run_with_retry "locale" bash "$TEST_SCRIPTS/android/locale.sh" || PHASE1_EXIT=1
+echo "--- textinput ---"
+run_with_retry "textinput" bash "$TEST_SCRIPTS/android/textinput.sh" || PHASE3_EXIT=1
+echo "--- permission ---"
+run_with_retry "permission" bash "$TEST_SCRIPTS/android/permission.sh" || PHASE4_EXIT=1
+echo "--- image ---"
+run_with_retry "image" bash "$TEST_SCRIPTS/android/image.sh" || PHASE6_EXIT=1
+echo "--- node-pool ---"
+run_with_retry "node-pool" bash "$TEST_SCRIPTS/android/node-pool.sh" || PHASE5_EXIT=1
+
+# --- Phase results ---
+if [ $PHASE1_EXIT -eq 0 ]; then
+ PHASE1_OK=1
+ echo ""
+ echo "PHASE 1 PASSED"
+else
+ echo ""
+ echo "PHASE 1 FAILED"
+fi
+
+if [ $PHASE2_EXIT -eq 0 ]; then
+ PHASE2_OK=1
+ echo ""
+ echo "PHASE 2 PASSED"
+else
+ echo ""
+ echo "PHASE 2 FAILED"
+fi
+
+if [ $PHASE3_EXIT -eq 0 ]; then
+ PHASE3_OK=1
+ echo ""
+ echo "PHASE 3 PASSED"
+else
+ PHASE3_OK=0
+ echo ""
+ echo "PHASE 3 FAILED"
+fi
+
+if [ $PHASE4_EXIT -eq 0 ]; then
+ PHASE4_OK=1
+ echo ""
+ echo "PHASE 4 PASSED"
+else
+ PHASE4_OK=0
+ echo ""
+ echo "PHASE 4 FAILED"
+fi
+
+if [ $PHASE5_EXIT -eq 0 ]; then
+ PHASE5_OK=1
+ echo ""
+ echo "PHASE 5 PASSED"
+else
+ PHASE5_OK=0
+ echo ""
+ echo "PHASE 5 FAILED"
+fi
+
+if [ $PHASE6_EXIT -eq 0 ]; then
+ PHASE6_OK=1
+ echo ""
+ echo "PHASE 6 PASSED"
+else
+ PHASE6_OK=0
+ echo ""
+ echo "PHASE 6 FAILED"
+fi
+
+# ===========================================================================
+# Final report
+# ===========================================================================
+echo ""
+echo "============================================================"
+echo "FINAL REPORT"
+echo "============================================================"
+
+FINAL_EXIT=0
+
+if [ $PHASE1_OK -eq 1 ]; then
+ echo "PASS Phase 1 — Counter app (lifecycle + UI + buttons)"
+else
+ echo "FAIL Phase 1 — Counter app (lifecycle + UI + buttons)"
+ FINAL_EXIT=1
+fi
+
+if [ $PHASE2_OK -eq 1 ]; then
+ echo "PASS Phase 2 — Scroll demo app"
+else
+ echo "FAIL Phase 2 — Scroll demo app"
+ FINAL_EXIT=1
+fi
+
+if [ $PHASE3_OK -eq 1 ]; then
+ echo "PASS Phase 3 — TextInput demo app"
+else
+ echo "FAIL Phase 3 — TextInput demo app"
+ FINAL_EXIT=1
+fi
+
+if [ $PHASE4_OK -eq 1 ]; then
+ echo "PASS Phase 4 — Permission demo app"
+else
+ echo "FAIL Phase 4 — Permission demo app"
+ FINAL_EXIT=1
+fi
+
+if [ $PHASE5_OK -eq 1 ]; then
+ echo "PASS Phase 5 — Node pool stress test (300 nodes, dynamic pool)"
+else
+ echo "FAIL Phase 5 — Node pool stress test (300 nodes, dynamic pool)"
+ FINAL_EXIT=1
+fi
+
+if [ $PHASE6_OK -eq 1 ]; then
+ echo "PASS Phase 6 — Image demo app"
+else
+ echo "FAIL Phase 6 — Image demo app"
+ FINAL_EXIT=1
+fi
+
+echo ""
+if [ $FINAL_EXIT -eq 0 ]; then
+ echo "All combined emulator integration checks passed!"
+else
+ echo "Some combined emulator integration checks FAILED."
+fi
+
+exit $FINAL_EXIT
+SCRIPT
+
+ chmod +x $out/bin/test-all
+ '';
+
+ installPhase = "true";
+}
diff --git a/nix/hpkgs.nix b/nix/hpkgs.nix
index 2b64da0e..e8736b6f 100644
--- a/nix/hpkgs.nix
+++ b/nix/hpkgs.nix
@@ -8,6 +8,6 @@ pkgs.haskellPackages.override {
overrides = hnew: hold: {
# NB this is a bit silly because nix files are now considered for the build
# bigger projects should consider putting haskell stuff in a subfolder
- template-project = hnew.callCabal2nix "template-project" ../. { };
+ haskell-mobile-project = hnew.callCabal2nix "haskell-mobile" ../. { };
};
}
diff --git a/nix/ios-deps.nix b/nix/ios-deps.nix
new file mode 100644
index 00000000..415e8806
--- /dev/null
+++ b/nix/ios-deps.nix
@@ -0,0 +1,36 @@
+# Build Hackage packages with the host GHC for iOS.
+#
+# iOS builds use the native macOS GHC (not a cross-GHC) — the resulting
+# Mach-O is later patched with mac2ios. Uses nixpkgs haskellPackages
+# infrastructure, then collects the results via collect-deps.nix.
+#
+# Output structure (same as cross-deps.nix):
+# $out/lib/*.a — static archives
+# $out/pkgdb/ — GHC package database (.conf + cache)
+#
+# Consumers supply their own dependencies via consumerCabalFile (IFD),
+# consumerCabal2Nix (pre-generated), or hpkgs overrides.
+{ sources
+, consumerCabalFile ? null
+, consumerCabal2Nix ? null
+, hpkgs ? (_: _: {}) # consumer haskellPackages overrides
+}:
+let
+ pkgs = import sources.nixpkgs {};
+
+ nativeHaskellPkgs = pkgs.haskellPackages.override {
+ overrides = hpkgs;
+ };
+
+ ghc = nativeHaskellPkgs.ghc;
+ ghcPkgCmd = "${ghc}/bin/ghc-pkg";
+
+ resolvedDeps = import ./resolve-deps.nix {
+ inherit pkgs consumerCabalFile consumerCabal2Nix;
+ haskellPkgs = nativeHaskellPkgs;
+ };
+
+in import ./collect-deps.nix {
+ inherit pkgs ghcPkgCmd;
+ deps = resolvedDeps;
+}
diff --git a/nix/ios.nix b/nix/ios.nix
new file mode 100644
index 00000000..82b07ad1
--- /dev/null
+++ b/nix/ios.nix
@@ -0,0 +1,23 @@
+# iOS static library — thin wrapper around lib.nix.
+#
+# maxNodes / dynamicNodePool are not used here — UIBridgeIOS.m is compiled
+# by Xcode, not GHC. These flags flow through mkSimulatorApp instead
+# (which injects OTHER_CFLAGS into project.yml).
+{ sources ? import ../npins
+, simulator ? false
+, mainModule ? ../app/MobileMain.hs
+, consumerCabalFile ? null
+, consumerCabal2Nix ? null
+, hpkgs ? (_: _: {}) # consumer haskellPackages overrides
+}:
+let
+ lib = import ./lib.nix { inherit sources; };
+ iosDeps = import ./ios-deps.nix {
+ inherit sources consumerCabalFile consumerCabal2Nix hpkgs;
+ };
+in
+lib.mkIOSLib {
+ haskellMobileSrc = ../.;
+ inherit mainModule simulator;
+ crossDeps = iosDeps;
+}
diff --git a/nix/lib.nix b/nix/lib.nix
new file mode 100644
index 00000000..92824bfd
--- /dev/null
+++ b/nix/lib.nix
@@ -0,0 +1,677 @@
+# Reusable builder functions for haskell-mobile based projects.
+#
+# Returns an attrset of 6 builder functions:
+# mkAndroidLib — cross-compile Haskell to .so for Android (aarch64 or armv7a)
+# mkApk — package .so + Java + resources into signed APK
+# mkIOSLib — compile Haskell to .a for iOS (device or simulator)
+# mkSimulatorApp — stage iOS sources + pre-built library for xcodebuild
+# mkWatchOSLib — compile Haskell to .a for watchOS (device or simulator)
+# mkWatchOSSimulatorApp — stage watchOS sources + pre-built library for xcodebuild
+#
+# Usage:
+# let lib = import ./lib.nix { sources = import ../npins; };
+# in lib.mkAndroidLib { haskellMobileSrc = ../.; mainModule = ../app/MobileMain.hs; }
+{ sources, androidArch ? "aarch64" }:
+let
+ archConfig = {
+ aarch64 = {
+ crossAttr = "aarch64-android-prebuilt";
+ ndkTarget = "aarch64-linux-android26";
+ ghcPkgArch = "aarch64-linux";
+ abiDir = "arm64-v8a";
+ };
+ armv7a = {
+ crossAttr = "armv7a-android-prebuilt";
+ ndkTarget = "armv7a-linux-androideabi26";
+ ghcPkgArch = "armv7-linux";
+ abiDir = "armeabi-v7a";
+ };
+ }.${androidArch};
+
+ # armv7a: compiler-rt's cmake doesn't include "armv7a" in its ARM32 arch
+ # list, so builtin targets are empty and the build produces no output.
+ # We patch the nixpkgs source to fix this (see patch-compiler-rt.py).
+ nixpkgsSrc = import ./patched-nixpkgs.nix {
+ nixpkgsSrc = sources.nixpkgs;
+ inherit androidArch;
+ };
+
+ pkgs = import nixpkgsSrc {
+ config.allowUnfree = true;
+ config.android_sdk.accept_license = true;
+ };
+
+ # --- Android cross-compilation infrastructure ---
+ androidPkgs = pkgs.pkgsCross.${archConfig.crossAttr};
+ # armv7a uses the LLVM backend (no NCG for 32-bit ARM). Building profiled
+ # libraries with the LLVM ARM backend triggers an llc crash in
+ # ARMAsmPrinter::emitXXStructor (LLVM bug). Disable profiling for armv7a.
+ ghc = if androidArch == "armv7a"
+ then androidPkgs.haskellPackages.ghc.override { enableProfiledLibs = false; }
+ else androidPkgs.haskellPackages.ghc;
+ ghcCmd = "${ghc}/bin/${ghc.targetPrefix}ghc";
+ ghcPkgDir = "${ghc}/lib/${ghc.targetPrefix}ghc-${ghc.version}/lib/${archConfig.ghcPkgArch}-ghc-${ghc.version}";
+
+ androidComposition = pkgs.androidenv.composeAndroidPackages {
+ includeNDK = true;
+ };
+ ndk = "${androidComposition.ndk-bundle}/libexec/android-sdk/ndk/${androidComposition.ndk-bundle.version}";
+ ndkCc = "${ndk}/toolchains/llvm/prebuilt/linux-x86_64/bin/${archConfig.ndkTarget}-clang";
+ sysroot = "${ndk}/toolchains/llvm/prebuilt/linux-x86_64/sysroot";
+
+ # --- APK toolchain ---
+ apkComposition = pkgs.androidenv.composeAndroidPackages {
+ buildToolsVersions = [ "34.0.0" ];
+ platformVersions = [ "34" ];
+ includeNDK = false;
+ };
+ androidSdk = apkComposition.androidsdk;
+ buildTools = "${androidSdk}/libexec/android-sdk/build-tools/34.0.0";
+ platform = "${androidSdk}/libexec/android-sdk/platforms/android-34";
+
+in {
+
+ # ---------------------------------------------------------------------------
+ # mkAndroidLib: Cross-compile Haskell to shared .so for Android (aarch64/armv7a)
+ # ---------------------------------------------------------------------------
+ mkAndroidLib =
+ { haskellMobileSrc
+ , mainModule
+ , pname ? "haskell-mobile-android"
+ , soName ? "libhaskellmobile.so"
+ , javaPackageName ? "me.jappie.haskellmobile"
+ , extraJniBridge ? []
+ , extraNdkCompile ? (_: _: "")
+ , extraModuleCopy ? ""
+ , extraLinkObjects ? []
+ , extraGhcIncludeDirs ? []
+ , crossDeps ? null # output of cross-deps.nix (lib/, hi/, pkgdb/)
+ , maxNodes ? 256 # static pool size (ignored when dynamicNodePool=true)
+ , dynamicNodePool ? false # use malloc/realloc instead of fixed array
+ }:
+ let
+ jniPackageMacro = builtins.replaceStrings ["."] ["_"] javaPackageName;
+ in
+ pkgs.stdenv.mkDerivation {
+ inherit pname;
+ version = "0.1.0.0";
+
+ src = haskellMobileSrc + "/src";
+
+ nativeBuildInputs = [ ghc ];
+ buildInputs = [ androidPkgs.libffi androidPkgs.gmp ];
+
+ buildPhase = ''
+ # Discover RTS include path for HsFFI.h
+ GHC_LIBDIR=$(${ghcCmd} --print-libdir)
+ RTS_INCLUDE=$(dirname $(find $GHC_LIBDIR -name "HsFFI.h" | head -1))
+
+ echo "GHC: ${ghcCmd}"
+ echo "GHC libdir: $GHC_LIBDIR"
+ echo "RTS include: $RTS_INCLUDE"
+
+ # Step 1: Compile JNI bridge and Android UI bridge with NDK clang
+ # Core library C files always use me_jappie_haskellmobile because
+ # native methods are declared on HaskellMobileActivity (the library's
+ # own class), not the consumer's subclass.
+ ${ndkCc} -c -fPIC \
+ -DJNI_PACKAGE=me_jappie_haskellmobile \
+ -I${sysroot}/usr/include \
+ -I$RTS_INCLUDE \
+ -I${haskellMobileSrc}/include \
+ -o jni_bridge.o \
+ ${haskellMobileSrc}/cbits/jni_bridge.c
+
+ ${ndkCc} -c -fPIC \
+ ${if dynamicNodePool then "-DDYNAMIC_NODE_POOL"
+ else if maxNodes != 256 then "-DMAX_NODES=${toString maxNodes}"
+ else ""} \
+ -I${sysroot}/usr/include \
+ -I$RTS_INCLUDE \
+ -I${haskellMobileSrc}/include \
+ -o ui_bridge_android.o \
+ ${haskellMobileSrc}/cbits/ui_bridge_android.c
+
+ ${ndkCc} -c -fPIC \
+ -DJNI_PACKAGE=me_jappie_haskellmobile \
+ -I${sysroot}/usr/include \
+ -I$RTS_INCLUDE \
+ -I${haskellMobileSrc}/include \
+ -o permission_bridge_android.o \
+ ${haskellMobileSrc}/cbits/permission_bridge_android.c
+
+ # Compile extra JNI bridge sources (consumer-specific JNI methods)
+ ${builtins.concatStringsSep "\n" (builtins.genList (i:
+ let src = builtins.elemAt extraJniBridge i;
+ base = builtins.replaceStrings ["/"] ["_"] (builtins.baseNameOf src);
+ oName = "extra_jni_${toString i}.o";
+ in ''
+ ${ndkCc} -c -fPIC \
+ -DJNI_PACKAGE=${jniPackageMacro} \
+ -I${sysroot}/usr/include \
+ -I$RTS_INCLUDE \
+ -I${haskellMobileSrc}/include \
+ -o ${oName} \
+ ${src}
+ '') (builtins.length extraJniBridge))}
+
+ # Extra NDK compilation (e.g. SQLite, storage helpers)
+ ${extraNdkCompile ndkCc sysroot}
+
+ # Step 2: Copy source modules into writable build directory.
+ # GHC writes _stub.h files next to sources, so they can't live in
+ # the read-only nix store.
+ mkdir -p HaskellMobile
+ cp ${haskellMobileSrc}/src/HaskellMobile/Types.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile/Lifecycle.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile/Widget.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile/UIBridge.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile/Render.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile/Locale.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile/I18n.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile/Permission.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile.hs .
+
+ # Default App.hs — only copy if not already present (consumer may override)
+ if [ ! -f HaskellMobile/App.hs ]; then
+ cp ${haskellMobileSrc}/src/HaskellMobile/App.hs HaskellMobile/
+ fi
+
+ # Extra module copies (consumer overrides, additional modules)
+ ${extraModuleCopy}
+
+ # Copy user entry point (plain main :: IO (), no foreign export needed)
+ cp ${mainModule} Main.hs
+
+ # Step 3: Copy C sources that GHC compiles into writable build dir.
+ # GHC writes .o.tmp files next to C sources; nix store is read-only.
+ mkdir -p cbits
+ cp ${haskellMobileSrc}/cbits/android_stubs.c cbits/
+ cp ${haskellMobileSrc}/cbits/platform_log.c cbits/
+ cp ${haskellMobileSrc}/cbits/numa_stubs.c cbits/
+ cp ${haskellMobileSrc}/cbits/ui_bridge.c cbits/
+ cp ${haskellMobileSrc}/cbits/run_main.c cbits/
+ cp ${haskellMobileSrc}/cbits/locale.c cbits/
+ cp ${haskellMobileSrc}/cbits/permission_bridge.c cbits/
+
+ # Step 4: Compile Haskell to shared library with cross-GHC.
+ # Discover library paths dynamically — hash suffixes vary across nixpkgs.
+ GHC_PKG_DIR="${ghcPkgDir}"
+
+ find_lib() {
+ local result
+ # Exclude debug (_debug), profiling (_p), threaded (_thr) variants
+ # and GHC shared library stubs (*-ghc*).
+ result=$(find "$GHC_PKG_DIR" -name "libHS$1-*.a" \
+ ! -name '*_debug*' ! -name '*_p.a' ! -name '*_thr*' \
+ ! -name '*-ghc*' | head -1)
+ if [ -z "$result" ]; then
+ echo "ERROR: Could not find library: $1" >&2
+ exit 1
+ fi
+ echo "$result"
+ }
+
+ RTS_LIB=$(find_lib "rts")
+ GHC_PRIM_LIB=$(find_lib "ghc-prim")
+ GHC_BIGNUM_LIB=$(find_lib "ghc-bignum")
+ GHC_INTERNAL_LIB=$(find_lib "ghc-internal")
+ BASE_LIB=$(find_lib "base")
+ INTEGER_GMP_LIB=$(find_lib "integer-gmp")
+ TEXT_LIB=$(find_lib "text")
+ ARRAY_LIB=$(find_lib "array")
+ DEEPSEQ_LIB=$(find_lib "deepseq")
+ CONTAINERS_LIB=$(find_lib "containers")
+ TRANSFORMERS_LIB=$(find_lib "transformers")
+ TIME_LIB=$(find_lib "time")
+
+ echo "Libraries discovered:"
+ echo " rts: $RTS_LIB"
+ echo " ghc-prim: $GHC_PRIM_LIB"
+ echo " base: $BASE_LIB"
+ echo " containers: $CONTAINERS_LIB"
+
+ ${ghcCmd} -shared -O2 \
+ -o ${soName} \
+ -I${haskellMobileSrc}/include \
+ ${builtins.concatStringsSep " " (map (d: "-I${d}") extraGhcIncludeDirs)} \
+ ${if crossDeps != null then "-package-db ${crossDeps}/pkgdb -i${crossDeps}/hi" else ""} \
+ Main.hs \
+ HaskellMobile.hs \
+ cbits/android_stubs.c \
+ cbits/platform_log.c \
+ cbits/numa_stubs.c \
+ cbits/ui_bridge.c \
+ cbits/run_main.c \
+ cbits/locale.c \
+ cbits/permission_bridge.c \
+ -optl-L${androidPkgs.gmp}/lib \
+ -optl-L${androidPkgs.libffi}/lib \
+ -optl-lffi \
+ -optl-llog \
+ -optl-Wl,-z,max-page-size=16384 \
+ -optl$(pwd)/jni_bridge.o \
+ -optl$(pwd)/ui_bridge_android.o \
+ -optl$(pwd)/permission_bridge_android.o \
+ ${builtins.concatStringsSep " " (builtins.genList (i: "-optl$(pwd)/extra_jni_${toString i}.o") (builtins.length extraJniBridge))} \
+ ${builtins.concatStringsSep " " (map (o: "-optl${o}") extraLinkObjects)} \
+ -optl-Wl,-u,haskellRunMain \
+ -optl-Wl,-u,haskellGreet \
+ -optl-Wl,-u,haskellOnLifecycle \
+ -optl-Wl,-u,haskellRenderUI \
+ -optl-Wl,-u,haskellOnUIEvent \
+ -optl-Wl,-u,haskellOnUITextChange \
+ -optl-Wl,-u,haskellOnPermissionResult \
+ -optl-Wl,-u,haskellLogLocale \
+ -optl-Wl,--no-undefined \
+ -optl-Wl,--whole-archive \
+ -optl$RTS_LIB \
+ -optl$GHC_PRIM_LIB \
+ -optl$GHC_BIGNUM_LIB \
+ -optl$GHC_INTERNAL_LIB \
+ -optl$BASE_LIB \
+ -optl$INTEGER_GMP_LIB \
+ -optl$TEXT_LIB \
+ -optl$ARRAY_LIB \
+ -optl$DEEPSEQ_LIB \
+ -optl$CONTAINERS_LIB \
+ -optl$TRANSFORMERS_LIB \
+ -optl$TIME_LIB \
+ ${if crossDeps != null then "$(for a in ${crossDeps}/lib/*.a; do echo -n \"-optl$a \"; done)" else ""} \
+ -optl-Wl,--no-whole-archive
+ '';
+
+ installPhase = ''
+ mkdir -p $out/lib/${archConfig.abiDir}
+ cp ${soName} $out/lib/${archConfig.abiDir}/
+
+ # Bundle runtime dependencies (not provided by Android)
+ cp ${androidPkgs.gmp}/lib/libgmp.so $out/lib/${archConfig.abiDir}/
+ cp ${androidPkgs.libffi}/lib/libffi.so $out/lib/${archConfig.abiDir}/
+ '';
+ };
+
+ # ---------------------------------------------------------------------------
+ # mkApk: Package shared library + Java + resources into a signed APK
+ # ---------------------------------------------------------------------------
+ mkApk =
+ { sharedLibs ? null # list of { lib = ; abiDir = "arm64-v8a"; }
+ , sharedLib ? null # backward compat: single lib drv (assumes arm64-v8a)
+ , androidSrc
+ , baseJavaSrc ? null # path to haskell-mobile's android/java/ for consumer APKs
+ , apkName ? "app.apk"
+ , name ? "app-apk"
+ }:
+ let
+ resolvedLibs =
+ if sharedLibs != null then sharedLibs
+ else if sharedLib != null then [{ lib = sharedLib; abiDir = "arm64-v8a"; }]
+ else builtins.throw "mkApk: either sharedLibs or sharedLib must be provided";
+ in
+ pkgs.stdenv.mkDerivation {
+ inherit name;
+
+ src = androidSrc;
+
+ nativeBuildInputs = with pkgs; [
+ jdk17_headless
+ zip
+ unzip
+ ];
+
+ buildPhase = ''
+ export HOME=$TMPDIR
+
+ echo "=== Step 1: Compile resources with aapt2 ==="
+ mkdir -p compiled_res
+ ${buildTools}/aapt2 compile \
+ --dir res \
+ -o compiled_res/
+
+ echo "=== Step 2: Link resources with aapt2 ==="
+ mkdir -p gen
+ ${buildTools}/aapt2 link \
+ -I ${platform}/android.jar \
+ --manifest AndroidManifest.xml \
+ --java gen \
+ -o base.apk \
+ compiled_res/*.flat
+
+ echo "=== Step 3: Compile Java sources ==="
+ mkdir -p classes
+ find gen -name "*.java" -print
+
+ javac \
+ -source 11 -target 11 \
+ -classpath ${platform}/android.jar \
+ -d classes \
+ $(find gen -name '*.java') \
+ $(find java -name '*.java') \
+ ${if baseJavaSrc != null then "$(find ${baseJavaSrc} -name '*.java')" else ""}
+
+ echo "=== Step 4: Convert to DEX ==="
+ mkdir -p dex_out
+ ${buildTools}/d8 \
+ --min-api 26 \
+ --output dex_out \
+ $(find classes -name "*.class")
+
+ echo "=== Step 5: Build APK ==="
+ cp base.apk unsigned.apk
+ cd dex_out
+ zip -j ../unsigned.apk classes.dex
+ cd ..
+ ${builtins.concatStringsSep "\n" (map (sl: ''
+ mkdir -p lib/${sl.abiDir}
+ cp ${sl.lib}/lib/${sl.abiDir}/*.so lib/${sl.abiDir}/
+ '') resolvedLibs)}
+ zip -r unsigned.apk lib/
+
+ echo "=== Step 6: Zipalign ==="
+ ${buildTools}/zipalign -f 4 unsigned.apk aligned.apk
+
+ echo "=== Step 7: Sign APK ==="
+ keytool -genkeypair \
+ -keystore debug.keystore \
+ -storepass android \
+ -keypass android \
+ -alias debug \
+ -keyalg RSA \
+ -keysize 2048 \
+ -validity 10000 \
+ -dname "CN=Debug, OU=Debug, O=Debug, L=Debug, ST=Debug, C=US"
+
+ ${buildTools}/apksigner sign \
+ --ks debug.keystore \
+ --ks-pass pass:android \
+ --key-pass pass:android \
+ --ks-key-alias debug \
+ --out ${apkName} \
+ aligned.apk
+ '';
+
+ installPhase = ''
+ mkdir -p $out
+ cp ${apkName} $out/
+ '';
+ };
+
+ # ---------------------------------------------------------------------------
+ # mkIOSLib: Compile Haskell to static .a for iOS (device or simulator)
+ # ---------------------------------------------------------------------------
+ mkIOSLib =
+ { haskellMobileSrc
+ , mainModule
+ , simulator ? false
+ , pname ? "haskell-mobile-ios"
+ , extraModuleCopy ? ""
+ , crossDeps ? null # output of ios-deps.nix (lib/, hi/, pkgdb/)
+ }:
+ let
+ iosPkgs = import sources.nixpkgs {};
+ iosGhc = iosPkgs.haskellPackages.ghc;
+ mac2ios = import (haskellMobileSrc + "/nix/mac2ios.nix") { inherit sources; pkgs = iosPkgs; };
+ gmpStatic = iosPkgs.gmp.overrideAttrs (old: {
+ dontDisableStatic = true;
+ });
+ in
+ iosPkgs.stdenv.mkDerivation {
+ inherit pname;
+ version = "0.1.0.0";
+
+ src = haskellMobileSrc + "/src";
+
+ nativeBuildInputs = [ iosGhc iosPkgs.cctools ];
+ buildInputs = [ iosPkgs.libffi gmpStatic ];
+
+ buildPhase = ''
+ mkdir -p HaskellMobile
+ cp ${haskellMobileSrc}/src/HaskellMobile/Types.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile/Lifecycle.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile/Widget.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile/UIBridge.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile/Render.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile/Locale.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile/I18n.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile/Permission.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile.hs .
+
+ # Default App.hs — only copy if not already present
+ if [ ! -f HaskellMobile/App.hs ]; then
+ cp ${haskellMobileSrc}/src/HaskellMobile/App.hs HaskellMobile/
+ fi
+
+ # Extra module copies
+ ${extraModuleCopy}
+
+ cp ${mainModule} Main.hs
+
+ # Copy C sources into writable build dir (GHC writes .o next to them)
+ mkdir -p cbits
+ cp ${haskellMobileSrc}/cbits/platform_log.c cbits/
+ cp ${haskellMobileSrc}/cbits/ui_bridge.c cbits/
+ cp ${haskellMobileSrc}/cbits/run_main.c cbits/
+ cp ${haskellMobileSrc}/cbits/locale.c cbits/
+ cp ${haskellMobileSrc}/cbits/permission_bridge.c cbits/
+
+ ghc -staticlib \
+ -O2 \
+ -o libHaskellMobile.a \
+ -I${haskellMobileSrc}/include \
+ ${if crossDeps != null then "-package-db ${crossDeps}/pkgdb -i${crossDeps}/hi" else ""} \
+ -optl-lffi \
+ -optl-Wl,-u,_haskellRunMain \
+ -optl-Wl,-u,_haskellGreet \
+ -optl-Wl,-u,_haskellOnLifecycle \
+ -optl-Wl,-u,_haskellRenderUI \
+ -optl-Wl,-u,_haskellOnUIEvent \
+ -optl-Wl,-u,_haskellOnPermissionResult \
+ -optl-Wl,-u,_haskellLogLocale \
+ cbits/platform_log.c \
+ cbits/ui_bridge.c \
+ cbits/run_main.c \
+ cbits/locale.c \
+ cbits/permission_bridge.c \
+ Main.hs \
+ HaskellMobile.hs
+ '';
+
+ installPhase = ''
+ mkdir -p $out/lib $out/include
+
+ echo "Merging static archives into libHaskellMobile.a"
+ libtool -static -o libCombined.a libHaskellMobile.a \
+ ${gmpStatic}/lib/libgmp.a \
+ ${if crossDeps != null then "${crossDeps}/lib/*.a" else ""}
+ mv libCombined.a libHaskellMobile.a
+
+ ${mac2ios}/bin/mac2ios ${if simulator then "-s" else ""} libHaskellMobile.a
+ cp libHaskellMobile.a $out/lib/
+ cp ${haskellMobileSrc}/include/HaskellMobile.h $out/include/HaskellMobile.h
+ cp ${haskellMobileSrc}/include/UIBridge.h $out/include/UIBridge.h
+ cp ${haskellMobileSrc}/include/PermissionBridge.h $out/include/PermissionBridge.h
+ '';
+ };
+
+ # ---------------------------------------------------------------------------
+ # mkSimulatorApp: Stage iOS sources + pre-built library for xcodebuild
+ # ---------------------------------------------------------------------------
+ mkSimulatorApp =
+ { iosLib
+ , iosSrc
+ , name ? "simulator-app"
+ , maxNodes ? 256 # static pool size (ignored when dynamicNodePool=true)
+ , dynamicNodePool ? false # use malloc/realloc instead of fixed array
+ }:
+ let
+ nodePoolCFlags =
+ if dynamicNodePool then ["-DDYNAMIC_NODE_POOL"]
+ else if maxNodes != 256 then ["-DMAX_NODES=${toString maxNodes}"]
+ else [];
+ # Inject OTHER_CFLAGS into project.yml when non-default pool settings used.
+ # Uses single-quoted -c and argv to avoid shell quoting issues.
+ flagYaml = ''[${builtins.concatStringsSep ", " (map (f: ''"${f}"'') nodePoolCFlags)}]'';
+ patchProjectYml =
+ if nodePoolCFlags == [] then ""
+ else ''
+ ${pkgs.python3}/bin/python3 -c '
+import sys
+yml = open(sys.argv[1]).read()
+yml = yml.replace(
+ "OTHER_LDFLAGS:",
+ "OTHER_CFLAGS: " + sys.argv[2] + "\n OTHER_LDFLAGS:"
+)
+open(sys.argv[1], "w").write(yml)
+' "$out/share/ios/project.yml" '${flagYaml}'
+ '';
+ in
+ pkgs.stdenv.mkDerivation {
+ inherit name;
+
+ dontUnpack = true;
+
+ buildPhase = ''
+ mkdir -p $out/share/ios/lib $out/share/ios/include
+
+ cp -r ${iosSrc}/HaskellMobile $out/share/ios/
+ cp ${iosSrc}/project.yml $out/share/ios/project.yml
+ chmod u+w $out/share/ios/project.yml
+
+ cp ${iosLib}/lib/libHaskellMobile.a $out/share/ios/lib/
+ cp ${iosLib}/include/HaskellMobile.h $out/share/ios/include/
+ cp ${iosLib}/include/UIBridge.h $out/share/ios/include/
+ cp ${iosLib}/include/PermissionBridge.h $out/share/ios/include/
+ ${patchProjectYml}
+ '';
+
+ installPhase = "true";
+ };
+
+ # ---------------------------------------------------------------------------
+ # mkWatchOSLib: Compile Haskell to static .a for watchOS (device or simulator)
+ # ---------------------------------------------------------------------------
+ mkWatchOSLib =
+ { haskellMobileSrc
+ , mainModule
+ , simulator ? false
+ , pname ? "haskell-mobile-watchos"
+ , extraModuleCopy ? ""
+ , crossDeps ? null # output of ios-deps.nix (lib/, hi/, pkgdb/)
+ }:
+ let
+ iosPkgs = import sources.nixpkgs {};
+ iosGhc = iosPkgs.haskellPackages.ghc;
+ mac2watchos = import (haskellMobileSrc + "/nix/mac2watchos.nix") {
+ inherit sources; pkgs = iosPkgs;
+ };
+ gmpStatic = iosPkgs.gmp.overrideAttrs (old: {
+ dontDisableStatic = true;
+ });
+ in
+ iosPkgs.stdenv.mkDerivation {
+ inherit pname;
+ version = "0.1.0.0";
+
+ src = haskellMobileSrc + "/src";
+
+ nativeBuildInputs = [ iosGhc iosPkgs.cctools ];
+ buildInputs = [ iosPkgs.libffi gmpStatic ];
+
+ buildPhase = ''
+ mkdir -p HaskellMobile
+ cp ${haskellMobileSrc}/src/HaskellMobile/Types.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile/Lifecycle.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile/Widget.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile/UIBridge.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile/Render.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile/Locale.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile/I18n.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile/Permission.hs HaskellMobile/
+ cp ${haskellMobileSrc}/src/HaskellMobile.hs .
+
+ # Default App.hs — only copy if not already present
+ if [ ! -f HaskellMobile/App.hs ]; then
+ cp ${haskellMobileSrc}/src/HaskellMobile/App.hs HaskellMobile/
+ fi
+
+ # Extra module copies
+ ${extraModuleCopy}
+
+ cp ${mainModule} Main.hs
+
+ # Copy C sources into writable build dir (GHC writes .o next to them)
+ mkdir -p cbits
+ cp ${haskellMobileSrc}/cbits/platform_log.c cbits/
+ cp ${haskellMobileSrc}/cbits/ui_bridge.c cbits/
+ cp ${haskellMobileSrc}/cbits/run_main.c cbits/
+ cp ${haskellMobileSrc}/cbits/locale.c cbits/
+ cp ${haskellMobileSrc}/cbits/permission_bridge.c cbits/
+
+ ghc -staticlib \
+ -O2 \
+ -o libHaskellMobile.a \
+ -I${haskellMobileSrc}/include \
+ ${if crossDeps != null then "-package-db ${crossDeps}/pkgdb -i${crossDeps}/hi" else ""} \
+ -optl-lffi \
+ -optl-Wl,-u,_haskellRunMain \
+ -optl-Wl,-u,_haskellGreet \
+ -optl-Wl,-u,_haskellOnLifecycle \
+ -optl-Wl,-u,_haskellRenderUI \
+ -optl-Wl,-u,_haskellOnUIEvent \
+ -optl-Wl,-u,_haskellOnPermissionResult \
+ -optl-Wl,-u,_haskellLogLocale \
+ cbits/platform_log.c \
+ cbits/ui_bridge.c \
+ cbits/run_main.c \
+ cbits/locale.c \
+ cbits/permission_bridge.c \
+ Main.hs \
+ HaskellMobile.hs
+ '';
+
+ installPhase = ''
+ mkdir -p $out/lib $out/include
+
+ echo "Merging static archives into libHaskellMobile.a"
+ libtool -static -o libCombined.a libHaskellMobile.a \
+ ${gmpStatic}/lib/libgmp.a \
+ ${if crossDeps != null then "${crossDeps}/lib/*.a" else ""}
+ mv libCombined.a libHaskellMobile.a
+
+ ${mac2watchos}/bin/mac2watchos ${if simulator then "-s" else ""} libHaskellMobile.a
+ cp libHaskellMobile.a $out/lib/
+ cp ${haskellMobileSrc}/include/HaskellMobile.h $out/include/HaskellMobile.h
+ cp ${haskellMobileSrc}/include/UIBridge.h $out/include/UIBridge.h
+ cp ${haskellMobileSrc}/include/PermissionBridge.h $out/include/PermissionBridge.h
+ '';
+ };
+
+ # ---------------------------------------------------------------------------
+ # mkWatchOSSimulatorApp: Stage watchOS sources + pre-built library for xcodebuild
+ # ---------------------------------------------------------------------------
+ mkWatchOSSimulatorApp =
+ { watchosLib
+ , watchosSrc
+ , name ? "watchos-simulator-app"
+ }:
+ pkgs.stdenv.mkDerivation {
+ inherit name;
+
+ dontUnpack = true;
+
+ buildPhase = ''
+ mkdir -p $out/share/watchos/lib $out/share/watchos/include
+
+ cp -r ${watchosSrc}/HaskellMobile $out/share/watchos/
+ cp ${watchosSrc}/project.yml $out/share/watchos/project.yml
+
+ cp ${watchosLib}/lib/libHaskellMobile.a $out/share/watchos/lib/
+ cp ${watchosLib}/include/HaskellMobile.h $out/share/watchos/include/
+ cp ${watchosLib}/include/UIBridge.h $out/share/watchos/include/
+ cp ${watchosLib}/include/PermissionBridge.h $out/share/watchos/include/
+ '';
+
+ installPhase = "true";
+ };
+
+}
diff --git a/nix/mac2ios.nix b/nix/mac2ios.nix
new file mode 100644
index 00000000..959ef92d
--- /dev/null
+++ b/nix/mac2ios.nix
@@ -0,0 +1,17 @@
+# Build the mac2ios tool from zw3rk/mobile-core-tools.
+# Patches Mach-O platform tags from macOS to iOS in static archives.
+{ sources ? import ../npins
+, pkgs ? import sources.nixpkgs {}
+}:
+pkgs.stdenv.mkDerivation {
+ pname = "mac2ios";
+ version = "unstable";
+ src = sources.mobile-core-tools;
+ buildPhase = ''
+ $CC -o mac2ios mac2ios.c
+ '';
+ installPhase = ''
+ mkdir -p $out/bin
+ cp mac2ios $out/bin/
+ '';
+}
diff --git a/nix/mac2watchos.nix b/nix/mac2watchos.nix
new file mode 100644
index 00000000..3ae3c406
--- /dev/null
+++ b/nix/mac2watchos.nix
@@ -0,0 +1,17 @@
+# Build the mac2watchos tool.
+# Patches Mach-O platform tags from macOS to watchOS in static archives.
+{ sources ? import ../npins
+, pkgs ? import sources.nixpkgs {}
+}:
+pkgs.stdenv.mkDerivation {
+ pname = "mac2watchos";
+ version = "unstable";
+ src = ../cbits;
+ buildPhase = ''
+ $CC -o mac2watchos mac2watchos.c
+ '';
+ installPhase = ''
+ mkdir -p $out/bin
+ cp mac2watchos $out/bin/
+ '';
+}
diff --git a/nix/patch-compiler-rt.py b/nix/patch-compiler-rt.py
new file mode 100644
index 00000000..562c3156
--- /dev/null
+++ b/nix/patch-compiler-rt.py
@@ -0,0 +1,169 @@
+"""Patch nixpkgs for armv7a-android cross-compilation.
+
+Fixes three issues in the nixpkgs source tree:
+
+1. compiler-rt: armv7a not in ARM32 arch set, so cmake detects zero supported
+ architectures. Also, Android baremetal builds can't detect arch because
+ -nodefaultlibs prevents check_symbol_exists from linking.
+
+2. compiler-rt: os_version_check.c requires pthread.h, unavailable in baremetal.
+
+3. LLVM package set: llvmPackages.clang for Android uses libcxxClang which
+ depends on libcxx. Building libcxx requires a working cross-linker,
+ but the bootstrap clang-wrapper only has GNU binutils (no ld.lld), and
+ ld.bfd can't link Android libraries (zstd-compressed debug sections,
+ missing builtins path). Fix: use libstdcxxClang (libcxx=null) for
+ Android targets. GHC's LLVMAS only needs assembly, not C++ support.
+
+Usage: python3 patch-compiler-rt.py
+ Writes to $out (set by Nix derivation builder).
+"""
+import os
+import shutil
+import stat
+import sys
+
+nixpkgs_src = sys.argv[1]
+out = os.environ["out"]
+
+shutil.copytree(nixpkgs_src, out, symlinks=True)
+
+target = os.path.join(
+ out,
+ "pkgs", "development", "compilers", "llvm", "common",
+ "compiler-rt", "default.nix",
+)
+
+for dirpath, dirnames, filenames in os.walk(os.path.dirname(target)):
+ os.chmod(dirpath, os.stat(dirpath).st_mode | stat.S_IWUSR)
+ for fn in filenames:
+ fp = os.path.join(dirpath, fn)
+ os.chmod(fp, os.stat(fp).st_mode | stat.S_IWUSR)
+
+with open(target, "r") as f:
+ content = f.read()
+
+# We insert our block between the closing '' of the X86 fix and the next
+# + lib.optionalString. The marker is the unique sequence:
+# ''\n + lib.optionalString (!haveLibc)
+marker = " ''\n + lib.optionalString (!haveLibc)"
+
+if marker not in content:
+ print("ERROR: Could not find insertion marker in compiler-rt default.nix",
+ file=sys.stderr)
+ sys.exit(1)
+
+# The armv7a block to insert (raw Nix source code).
+# Three fixes:
+# 1. Add armv7a to ARM32 set in builtin-config-ix.cmake so builtins are
+# built for this architecture.
+# 2. Define armv7a_SOURCES as alias for arm_SOURCES in CMakeLists.txt.
+# 3. Fix Android baremetal builds in base-config-ix.cmake:
+# For Android, cmake normally calls detect_target_arch() which uses
+# check_symbol_exists(__arm__). In baremetal builds, -nodefaultlibs
+# prevents the test from linking, so detection fails and SUPPORTED_ARCH
+# is empty. We add a COMPILER_RT_DEFAULT_TARGET_ONLY check to use
+# add_default_target_arch() directly (bypassing the broken detection).
+#
+# Note: in Nix multiline strings (''..''), ''${ prevents interpolation,
+# producing literal ${...} in the shell output. Shell single quotes
+# are unrelated to the Nix '' delimiters.
+# Use $'...\n...' bash syntax for the base-config-ix.cmake replacement to
+# avoid Nix multiline string whitespace stripping, which would eat the
+# leading spaces that are significant in the cmake source.
+base_find = (
+ r"$' # Examine compiler output to determine target architecture.\n"
+ r" detect_target_arch()'"
+)
+base_replace = (
+ r"$' # Examine compiler output to determine target architecture.\n"
+ r" if(COMPILER_RT_DEFAULT_TARGET_ONLY)\n"
+ r" add_default_target_arch(''${COMPILER_RT_DEFAULT_TARGET_ARCH})\n"
+ r" else()\n"
+ r" detect_target_arch()\n"
+ r" endif()'"
+)
+armv7a_block = "\n".join([
+ " ''",
+ ' + lib.optionalString (stdenv.hostPlatform.parsed.cpu.name == "armv7a") ' + "''",
+ " substituteInPlace cmake/builtin-config-ix.cmake \\",
+ " --replace-fail 'set(ARM32 arm armhf' 'set(ARM32 armv7a arm armhf'",
+ " substituteInPlace lib/builtins/CMakeLists.txt \\",
+ " --replace-fail 'set(armv7_SOURCES ''${arm_SOURCES})' \\",
+ r" $'set(armv7_SOURCES ''${arm_SOURCES})\nset(armv7a_SOURCES ''${arm_SOURCES})'",
+ # os_version_check.c requires pthread.h which doesn't exist in baremetal.
+ # Insert a list(REMOVE_ITEM) before the existing baremetal conditional.
+ " substituteInPlace lib/builtins/CMakeLists.txt \\",
+ r" --replace-fail 'if(NOT FUCHSIA AND NOT COMPILER_RT_BAREMETAL_BUILD AND NOT COMPILER_RT_GPU_BUILD)' $'if(COMPILER_RT_BAREMETAL_BUILD)\n list(REMOVE_ITEM GENERIC_SOURCES os_version_check.c)\nendif()\nif(NOT FUCHSIA AND NOT COMPILER_RT_BAREMETAL_BUILD AND NOT COMPILER_RT_GPU_BUILD)'",
+ " substituteInPlace cmake/base-config-ix.cmake \\",
+ " --replace-fail " + base_find + " \\",
+ " " + base_replace,
+ " ''",
+ " + lib.optionalString (!haveLibc)",
+])
+
+content = content.replace(marker, armv7a_block, 1)
+
+with open(target, "w") as f:
+ f.write(content)
+
+print("Patched " + target)
+
+# --- Patch 2: LLVM package set ---
+# GHC's LLVM backend (required for armv7a, no NCG) depends on
+# llvmPackages.clang for LLVMAS. The default `clang` for non-useLLVM
+# non-Darwin targets is `libcxxClang`, which depends on
+# targetLlvmPackages.libcxx. Building libcxx requires the bootstrap
+# clang-wrapper with GNU binutils, but ld.bfd can't link Android
+# libraries (zstd-compressed debug sections, missing builtins path).
+#
+# Fix: for Android targets, use libstdcxxClang (which has libcxx=null)
+# instead. GHC only needs clang for assembly (LLVMAS), not C++, so
+# the absence of libc++ headers/libraries is fine.
+llvm_pkg_set = os.path.join(
+ out,
+ "pkgs", "development", "compilers", "llvm", "common",
+ "default.nix",
+)
+
+llvm_dir = os.path.dirname(llvm_pkg_set)
+for dirpath, dirnames, filenames in os.walk(llvm_dir):
+ os.chmod(dirpath, os.stat(dirpath).st_mode | stat.S_IWUSR)
+ for fn in filenames:
+ fp = os.path.join(dirpath, fn)
+ os.chmod(fp, os.stat(fp).st_mode | stat.S_IWUSR)
+
+with open(llvm_pkg_set, "r") as f:
+ llvm_content = f.read()
+
+# The clang selection logic in the LLVM package set:
+# else if stdenv.targetPlatform.useLLVM or false then
+# self.clangUseLLVM
+# else if (targetPackages.stdenv or stdenv).cc.isGNU then
+# self.libstdcxxClang
+# else
+# self.libcxxClang;
+#
+# We add an Android check before the isGNU/libcxxClang fallback,
+# to select libstdcxxClang (no libcxx dependency) for Android.
+llvm_marker = (
+ "else if (targetPackages.stdenv or stdenv).cc.isGNU then\n"
+ " self.libstdcxxClang"
+)
+
+if llvm_marker not in llvm_content:
+ print("WARNING: Could not find LLVM clang selection marker, "
+ "skipping LLVM package set patch", file=sys.stderr)
+else:
+ llvm_replacement = (
+ "else if stdenv.targetPlatform.isAndroid then\n"
+ " self.libstdcxxClang\n"
+ " else if (targetPackages.stdenv or stdenv).cc.isGNU then\n"
+ " self.libstdcxxClang"
+ )
+ llvm_content = llvm_content.replace(llvm_marker, llvm_replacement, 1)
+
+ with open(llvm_pkg_set, "w") as f:
+ f.write(llvm_content)
+
+ print("Patched " + llvm_pkg_set)
diff --git a/nix/patched-nixpkgs.nix b/nix/patched-nixpkgs.nix
new file mode 100644
index 00000000..62f5609d
--- /dev/null
+++ b/nix/patched-nixpkgs.nix
@@ -0,0 +1,21 @@
+# Produce a patched copy of nixpkgs where compiler-rt recognises "armv7a"
+# as a valid ARM32 architecture. Without this, cmake detects zero supported
+# architectures and the compiler-rt build produces an empty output, breaking
+# the entire armv7a-android cross-compilation toolchain.
+#
+# This mirrors the existing X86 precedent already in nixpkgs where i486/i586/
+# i686 are added to the X86 set via substituteInPlace + a source alias patch.
+#
+# When androidArch is not "armv7a", returns the original nixpkgs source as-is.
+{ nixpkgsSrc, androidArch }:
+if androidArch != "armv7a" then nixpkgsSrc
+else
+let
+ # Import a minimal nixpkgs to get runCommand + python3
+ minPkgs = import nixpkgsSrc {};
+in
+minPkgs.runCommand "nixpkgs-armv7a-patched" {
+ nativeBuildInputs = [ minPkgs.python3 ];
+} ''
+ python3 ${./patch-compiler-rt.py} ${nixpkgsSrc}
+''
diff --git a/nix/resolve-deps.nix b/nix/resolve-deps.nix
new file mode 100644
index 00000000..2f9ca6d6
--- /dev/null
+++ b/nix/resolve-deps.nix
@@ -0,0 +1,87 @@
+# Resolve consumer Haskell dependencies.
+#
+# Given a cabal file (IFD) or pre-generated cabal2nix derivation function,
+# resolves the full transitive closure of non-boot Haskell packages using
+# nixpkgs haskellPackages. Returns actual derivations for use with
+# collect-deps.nix.
+#
+# When neither consumerCabalFile nor consumerCabal2Nix is given, returns [].
+{ pkgs
+, haskellPkgs ? pkgs.haskellPackages
+, consumerCabalFile ? null
+, consumerCabal2Nix ? null
+}:
+let
+ # Get cabal2nix function: either provided directly or generated via IFD
+ cabal2nixFn =
+ if consumerCabal2Nix != null then consumerCabal2Nix
+ else if consumerCabalFile != null then
+ import (pkgs.runCommand "consumer-cabal2nix" {
+ nativeBuildInputs = [ pkgs.cabal2nix ];
+ } ''
+ cabal2nix ${builtins.dirOf consumerCabalFile} > $out
+ '')
+ else null;
+
+ # Use a spy mkDerivation to extract the dependency list without building.
+ # haskellPackages.callPackage passes real packages for each dep name;
+ # our fake mkDerivation just captures the attrs cabal2nix produces.
+ depInfo =
+ if cabal2nixFn != null
+ then haskellPkgs.callPackage cabal2nixFn { mkDerivation = attrs: attrs; }
+ else { libraryHaskellDepends = []; };
+
+ directDeps = depInfo.libraryHaskellDepends or [];
+
+ # GHC boot/wired-in packages — already provided by the cross-GHC, so they
+ # must not be cross-compiled again. Also excludes haskell-mobile itself
+ # (compiled separately in mkAndroidLib/mkIOSLib).
+ bootPackageNames = [
+ "base" "ghc-prim" "ghc-bignum" "ghc-internal" "integer-gmp"
+ "bytestring" "text" "array" "deepseq" "containers"
+ "template-haskell" "transformers" "mtl" "stm" "exceptions"
+ "filepath" "directory" "process" "unix" "time" "binary"
+ "parsec" "pretty" "ghc-boot-th" "ghc-boot" "ghc-heap"
+ "hpc" "Cabal" "Cabal-syntax" "os-string"
+ "haskell-mobile"
+ ];
+
+ isBootPackage = name: builtins.elem name bootPackageNames;
+
+ # Test/benchmark framework packages — never needed at runtime in mobile apps.
+ # cabal2nix merges internal sub-library deps into libraryHaskellDepends
+ # (e.g. vector's benchmarks-O2 → tasty, random), which leaks these into
+ # propagatedBuildInputs. Their transitive deps (unix, process via
+ # optparse-applicative) cause link failures because boot packages aren't
+ # linked into the .so. We exclude them from the transitive walk; consumers
+ # who genuinely need these can add them via the hpkgs overlay.
+ testFrameworkNames = [
+ "tasty" "tasty-bench" "tasty-hunit" "tasty-quickcheck" "tasty-smallcheck"
+ "hspec" "hspec-core" "hspec-discover" "hspec-expectations"
+ "HUnit"
+ "criterion" "gauge"
+ ];
+
+ isExcluded = name: isBootPackage name || builtins.elem name testFrameworkNames;
+
+ # Recursively collect all non-boot, non-test-framework Haskell deps from
+ # propagatedBuildInputs.
+ collectDeps = seen: deps:
+ builtins.foldl' (acc: dep:
+ let name = dep.pname or "";
+ in if name == "" || isExcluded name || builtins.hasAttr name acc
+ then acc
+ else
+ let subDeps = builtins.filter
+ (d: d ? pname && d ? isHaskellLibrary)
+ (dep.propagatedBuildInputs or []);
+ in collectDeps (acc // { "${name}" = dep; }) subDeps
+ ) seen deps;
+
+ nonBootDirect = builtins.filter
+ (d: d ? pname && !(isBootPackage d.pname))
+ directDeps;
+
+ allDeps = collectDeps {} nonBootDirect;
+
+in builtins.attrValues allDeps
diff --git a/nix/simulator-all.nix b/nix/simulator-all.nix
new file mode 100644
index 00000000..85ec967e
--- /dev/null
+++ b/nix/simulator-all.nix
@@ -0,0 +1,603 @@
+# iOS Simulator combined integration test.
+#
+# Single simulator session covering all test suites:
+#
+# Phase 1 — Counter app (lifecycle + UI rendering + two-button sequence)
+# Verifies: Lifecycle: Create/Resume, setRoot/setStrProp/setHandler,
+# --autotest fires Counter: 1, --autotest-buttons fires full sequence.
+#
+# Phase 2 — Scroll demo app
+# Verifies: createNode(type=5), setRoot, Click dispatched: callbackId=0.
+#
+# One boot + teardown cycle instead of four.
+#
+# Usage:
+# nix-build nix/simulator-all.nix -o result-simulator-all
+# ./result-simulator-all/bin/test-all-ios
+{ sources ? import ../npins }:
+let
+ pkgs = import sources.nixpkgs {};
+
+ lib = import ./lib.nix { inherit sources; };
+
+ counterSimApp = import ./simulator-app.nix { inherit sources; };
+
+ scrollIos = import ./ios.nix {
+ inherit sources;
+ mainModule = ../test/ScrollDemoMain.hs;
+ simulator = true;
+ };
+ scrollSimApp = lib.mkSimulatorApp {
+ iosLib = scrollIos;
+ iosSrc = ../ios;
+ name = "haskell-mobile-scroll-simulator-app";
+ };
+
+ textinputIos = import ./ios.nix {
+ inherit sources;
+ mainModule = ../test/TextInputDemoMain.hs;
+ simulator = true;
+ };
+ textinputSimApp = lib.mkSimulatorApp {
+ iosLib = textinputIos;
+ iosSrc = ../ios;
+ name = "haskell-mobile-textinput-simulator-app";
+ };
+
+ permissionIos = import ./ios.nix {
+ inherit sources;
+ mainModule = ../test/PermissionDemoMain.hs;
+ simulator = true;
+ };
+ permissionSimApp = lib.mkSimulatorApp {
+ iosLib = permissionIos;
+ iosSrc = ../ios;
+ name = "haskell-mobile-permission-simulator-app";
+ };
+
+ imageIos = import ./ios.nix {
+ inherit sources;
+ mainModule = ../test/ImageDemoMain.hs;
+ simulator = true;
+ };
+ imageSimApp = lib.mkSimulatorApp {
+ iosLib = imageIos;
+ iosSrc = ../ios;
+ name = "haskell-mobile-image-simulator-app";
+ };
+
+ nodepoolIos = import ./ios.nix {
+ inherit sources;
+ mainModule = ../test/NodePoolTestMain.hs;
+ simulator = true;
+ };
+ nodepoolSimApp = lib.mkSimulatorApp {
+ iosLib = nodepoolIos;
+ iosSrc = ../ios;
+ name = "haskell-mobile-nodepool-simulator-app";
+ dynamicNodePool = true;
+ };
+
+ xcodegen = pkgs.xcodegen;
+
+ testScripts = builtins.path { path = ../test; name = "test-scripts"; };
+
+in pkgs.stdenv.mkDerivation {
+ name = "haskell-mobile-simulator-all-tests";
+
+ dontUnpack = true;
+
+ buildPhase = ''
+ mkdir -p $out/bin
+
+ cat > $out/bin/test-all-ios << 'SCRIPT'
+#!/usr/bin/env bash
+set -euo pipefail
+
+# --- Configuration ---
+BUNDLE_ID="me.jappie.haskellmobile"
+SCHEME="HaskellMobile"
+DEVICE_TYPE="iPhone 16"
+COUNTER_SHARE_DIR="${counterSimApp}/share/ios"
+SCROLL_SHARE_DIR="${scrollSimApp}/share/ios"
+TEXTINPUT_SHARE_DIR="${textinputSimApp}/share/ios"
+PERMISSION_SHARE_DIR="${permissionSimApp}/share/ios"
+IMAGE_SHARE_DIR="${imageSimApp}/share/ios"
+NODEPOOL_SHARE_DIR="${nodepoolSimApp}/share/ios"
+TEST_SCRIPTS="${testScripts}"
+
+# --- Temp working directory ---
+WORK_DIR=$(mktemp -d /tmp/haskell-mobile-sim-all-XXXX)
+SIM_UDID=""
+
+# Phase result tracking
+PHASE1_OK=0
+PHASE2_OK=0
+PHASE3_OK=0
+PHASE4_OK=0
+PHASE5_OK=0
+PHASE6_OK=0
+
+cleanup() {
+ echo ""
+ echo "=== Cleaning up ==="
+ if [ -n "$SIM_UDID" ]; then
+ echo "Shutting down simulator $SIM_UDID"
+ xcrun simctl shutdown "$SIM_UDID" 2>/dev/null || true
+ echo "Deleting simulator $SIM_UDID"
+ xcrun simctl delete "$SIM_UDID" 2>/dev/null || true
+ fi
+ rm -rf "$WORK_DIR"
+ echo "Cleanup done."
+}
+trap cleanup EXIT
+
+echo "=== iOS Simulator All-Tests ==="
+echo "Working directory: $WORK_DIR"
+
+# ===========================================================================
+# PHASE 0 — Build both apps + boot simulator
+# ===========================================================================
+echo ""
+echo "============================================================"
+echo "PHASE 0: Build apps and boot simulator"
+echo "============================================================"
+
+# --- Stage and build counter app ---
+echo "=== Staging counter app ==="
+mkdir -p "$WORK_DIR/counter/lib" "$WORK_DIR/counter/include"
+cp "$COUNTER_SHARE_DIR/lib/libHaskellMobile.a" "$WORK_DIR/counter/lib/"
+cp "$COUNTER_SHARE_DIR/include/HaskellMobile.h" "$WORK_DIR/counter/include/"
+cp "$COUNTER_SHARE_DIR/include/UIBridge.h" "$WORK_DIR/counter/include/"
+cp "$COUNTER_SHARE_DIR/include/PermissionBridge.h" "$WORK_DIR/counter/include/"
+cp -r "$COUNTER_SHARE_DIR/HaskellMobile" "$WORK_DIR/counter/"
+cp "$COUNTER_SHARE_DIR/project.yml" "$WORK_DIR/counter/"
+chmod -R u+w "$WORK_DIR/counter"
+
+echo "=== Generating counter Xcode project ==="
+cd "$WORK_DIR/counter"
+${xcodegen}/bin/xcodegen generate
+
+echo "=== Building counter app for simulator ==="
+xcodebuild build \
+ -project HaskellMobile.xcodeproj \
+ -scheme "$SCHEME" \
+ -sdk iphonesimulator \
+ -configuration Release \
+ -derivedDataPath "$WORK_DIR/counter-build" \
+ CODE_SIGN_IDENTITY=- \
+ CODE_SIGNING_ALLOWED=NO \
+ ARCHS=arm64 \
+ ONLY_ACTIVE_ARCH=NO \
+ | tail -20
+
+COUNTER_APP=$(find "$WORK_DIR/counter-build" -name "*.app" -type d | head -1)
+if [ -z "$COUNTER_APP" ]; then
+ echo "ERROR: Could not find counter .app bundle"
+ exit 1
+fi
+echo "Counter app: $COUNTER_APP"
+
+# --- Stage and build scroll demo app ---
+echo "=== Staging scroll demo app ==="
+mkdir -p "$WORK_DIR/scroll/lib" "$WORK_DIR/scroll/include"
+cp "$SCROLL_SHARE_DIR/lib/libHaskellMobile.a" "$WORK_DIR/scroll/lib/"
+cp "$SCROLL_SHARE_DIR/include/HaskellMobile.h" "$WORK_DIR/scroll/include/"
+cp "$SCROLL_SHARE_DIR/include/UIBridge.h" "$WORK_DIR/scroll/include/"
+cp "$SCROLL_SHARE_DIR/include/PermissionBridge.h" "$WORK_DIR/scroll/include/"
+cp -r "$SCROLL_SHARE_DIR/HaskellMobile" "$WORK_DIR/scroll/"
+cp "$SCROLL_SHARE_DIR/project.yml" "$WORK_DIR/scroll/"
+chmod -R u+w "$WORK_DIR/scroll"
+
+echo "=== Generating scroll Xcode project ==="
+cd "$WORK_DIR/scroll"
+${xcodegen}/bin/xcodegen generate
+
+echo "=== Building scroll demo app for simulator ==="
+xcodebuild build \
+ -project HaskellMobile.xcodeproj \
+ -scheme "$SCHEME" \
+ -sdk iphonesimulator \
+ -configuration Release \
+ -derivedDataPath "$WORK_DIR/scroll-build" \
+ CODE_SIGN_IDENTITY=- \
+ CODE_SIGNING_ALLOWED=NO \
+ ARCHS=arm64 \
+ ONLY_ACTIVE_ARCH=NO \
+ | tail -20
+
+SCROLL_APP=$(find "$WORK_DIR/scroll-build" -name "*.app" -type d | head -1)
+if [ -z "$SCROLL_APP" ]; then
+ echo "ERROR: Could not find scroll .app bundle"
+ exit 1
+fi
+echo "Scroll app: $SCROLL_APP"
+
+# --- Stage and build textinput demo app ---
+echo "=== Staging textinput demo app ==="
+mkdir -p "$WORK_DIR/textinput/lib" "$WORK_DIR/textinput/include"
+cp "$TEXTINPUT_SHARE_DIR/lib/libHaskellMobile.a" "$WORK_DIR/textinput/lib/"
+cp "$TEXTINPUT_SHARE_DIR/include/HaskellMobile.h" "$WORK_DIR/textinput/include/"
+cp "$TEXTINPUT_SHARE_DIR/include/UIBridge.h" "$WORK_DIR/textinput/include/"
+cp "$TEXTINPUT_SHARE_DIR/include/PermissionBridge.h" "$WORK_DIR/textinput/include/"
+cp -r "$TEXTINPUT_SHARE_DIR/HaskellMobile" "$WORK_DIR/textinput/"
+cp "$TEXTINPUT_SHARE_DIR/project.yml" "$WORK_DIR/textinput/"
+chmod -R u+w "$WORK_DIR/textinput"
+
+echo "=== Generating textinput Xcode project ==="
+cd "$WORK_DIR/textinput"
+${xcodegen}/bin/xcodegen generate
+
+echo "=== Building textinput demo app for simulator ==="
+xcodebuild build \
+ -project HaskellMobile.xcodeproj \
+ -scheme "$SCHEME" \
+ -sdk iphonesimulator \
+ -configuration Release \
+ -derivedDataPath "$WORK_DIR/textinput-build" \
+ CODE_SIGN_IDENTITY=- \
+ CODE_SIGNING_ALLOWED=NO \
+ ARCHS=arm64 \
+ ONLY_ACTIVE_ARCH=NO \
+ | tail -20
+
+TEXTINPUT_APP=$(find "$WORK_DIR/textinput-build" -name "*.app" -type d | head -1)
+if [ -z "$TEXTINPUT_APP" ]; then
+ echo "ERROR: Could not find textinput .app bundle"
+ exit 1
+fi
+echo "TextInput app: $TEXTINPUT_APP"
+
+# --- Stage and build permission demo app ---
+echo "=== Staging permission demo app ==="
+mkdir -p "$WORK_DIR/permission/lib" "$WORK_DIR/permission/include"
+cp "$PERMISSION_SHARE_DIR/lib/libHaskellMobile.a" "$WORK_DIR/permission/lib/"
+cp "$PERMISSION_SHARE_DIR/include/HaskellMobile.h" "$WORK_DIR/permission/include/"
+cp "$PERMISSION_SHARE_DIR/include/UIBridge.h" "$WORK_DIR/permission/include/"
+cp "$PERMISSION_SHARE_DIR/include/PermissionBridge.h" "$WORK_DIR/permission/include/"
+cp -r "$PERMISSION_SHARE_DIR/HaskellMobile" "$WORK_DIR/permission/"
+cp "$PERMISSION_SHARE_DIR/project.yml" "$WORK_DIR/permission/"
+chmod -R u+w "$WORK_DIR/permission"
+
+echo "=== Generating permission Xcode project ==="
+cd "$WORK_DIR/permission"
+${xcodegen}/bin/xcodegen generate
+
+echo "=== Building permission demo app for simulator ==="
+xcodebuild build \
+ -project HaskellMobile.xcodeproj \
+ -scheme "$SCHEME" \
+ -sdk iphonesimulator \
+ -configuration Release \
+ -derivedDataPath "$WORK_DIR/permission-build" \
+ CODE_SIGN_IDENTITY=- \
+ CODE_SIGNING_ALLOWED=NO \
+ ARCHS=arm64 \
+ ONLY_ACTIVE_ARCH=NO \
+ | tail -20
+
+PERMISSION_APP=$(find "$WORK_DIR/permission-build" -name "*.app" -type d | head -1)
+if [ -z "$PERMISSION_APP" ]; then
+ echo "ERROR: Could not find permission .app bundle"
+ exit 1
+fi
+echo "Permission app: $PERMISSION_APP"
+
+# --- Stage and build image test app ---
+echo "=== Staging image test app ==="
+mkdir -p "$WORK_DIR/image/lib" "$WORK_DIR/image/include"
+cp "$IMAGE_SHARE_DIR/lib/libHaskellMobile.a" "$WORK_DIR/image/lib/"
+cp "$IMAGE_SHARE_DIR/include/HaskellMobile.h" "$WORK_DIR/image/include/"
+cp "$IMAGE_SHARE_DIR/include/UIBridge.h" "$WORK_DIR/image/include/"
+cp "$IMAGE_SHARE_DIR/include/PermissionBridge.h" "$WORK_DIR/image/include/"
+cp -r "$IMAGE_SHARE_DIR/HaskellMobile" "$WORK_DIR/image/"
+cp "$IMAGE_SHARE_DIR/project.yml" "$WORK_DIR/image/"
+chmod -R u+w "$WORK_DIR/image"
+
+echo "=== Generating image Xcode project ==="
+cd "$WORK_DIR/image"
+${xcodegen}/bin/xcodegen generate
+
+echo "=== Building image test app for simulator ==="
+xcodebuild build \
+ -project HaskellMobile.xcodeproj \
+ -scheme "$SCHEME" \
+ -sdk iphonesimulator \
+ -configuration Release \
+ -derivedDataPath "$WORK_DIR/image-build" \
+ CODE_SIGN_IDENTITY=- \
+ CODE_SIGNING_ALLOWED=NO \
+ ARCHS=arm64 \
+ ONLY_ACTIVE_ARCH=NO \
+ | tail -20
+
+IMAGE_APP=$(find "$WORK_DIR/image-build" -name "*.app" -type d | head -1)
+if [ -z "$IMAGE_APP" ]; then
+ echo "ERROR: Could not find image .app bundle"
+ exit 1
+fi
+echo "Image app: $IMAGE_APP"
+
+# --- Stage and build node-pool test app ---
+echo "=== Staging node-pool test app ==="
+mkdir -p "$WORK_DIR/nodepool/lib" "$WORK_DIR/nodepool/include"
+cp "$NODEPOOL_SHARE_DIR/lib/libHaskellMobile.a" "$WORK_DIR/nodepool/lib/"
+cp "$NODEPOOL_SHARE_DIR/include/HaskellMobile.h" "$WORK_DIR/nodepool/include/"
+cp "$NODEPOOL_SHARE_DIR/include/UIBridge.h" "$WORK_DIR/nodepool/include/"
+cp "$NODEPOOL_SHARE_DIR/include/PermissionBridge.h" "$WORK_DIR/nodepool/include/"
+cp -r "$NODEPOOL_SHARE_DIR/HaskellMobile" "$WORK_DIR/nodepool/"
+cp "$NODEPOOL_SHARE_DIR/project.yml" "$WORK_DIR/nodepool/"
+chmod -R u+w "$WORK_DIR/nodepool"
+
+echo "=== Generating node-pool Xcode project ==="
+cd "$WORK_DIR/nodepool"
+${xcodegen}/bin/xcodegen generate
+
+echo "=== Building node-pool test app for simulator ==="
+xcodebuild build \
+ -project HaskellMobile.xcodeproj \
+ -scheme "$SCHEME" \
+ -sdk iphonesimulator \
+ -configuration Release \
+ -derivedDataPath "$WORK_DIR/nodepool-build" \
+ CODE_SIGN_IDENTITY=- \
+ CODE_SIGNING_ALLOWED=NO \
+ ARCHS=arm64 \
+ ONLY_ACTIVE_ARCH=NO \
+ | tail -20
+
+NODEPOOL_APP=$(find "$WORK_DIR/nodepool-build" -name "*.app" -type d | head -1)
+if [ -z "$NODEPOOL_APP" ]; then
+ echo "ERROR: Could not find node-pool .app bundle"
+ exit 1
+fi
+echo "NodePool app: $NODEPOOL_APP"
+
+# --- Discover latest iOS runtime ---
+echo "=== Discovering iOS runtime ==="
+RUNTIME=$(xcrun simctl list runtimes -j \
+ | python3 -c "
+import json, sys
+data = json.load(sys.stdin)
+ios_runtimes = [r for r in data['runtimes'] if r['platform'] == 'iOS' and r['isAvailable']]
+if not ios_runtimes:
+ print('ERROR: No available iOS runtimes', file=sys.stderr)
+ sys.exit(1)
+print(ios_runtimes[-1]['identifier'])
+")
+echo "Runtime: $RUNTIME"
+
+# --- Create and boot simulator ---
+echo "=== Creating simulator ==="
+SIM_UDID=$(xcrun simctl create "test-all-ios" "$DEVICE_TYPE" "$RUNTIME" \
+ | tr -d '[:space:]')
+
+if [ -z "$SIM_UDID" ]; then
+ echo "ERROR: Failed to create simulator device"
+ exit 1
+fi
+echo "Simulator UDID: $SIM_UDID"
+
+echo "=== Booting simulator ==="
+xcrun simctl boot "$SIM_UDID"
+
+BOOT_TIMEOUT=120
+BOOT_ELAPSED=0
+STATE="Unknown"
+while [ $BOOT_ELAPSED -lt $BOOT_TIMEOUT ]; do
+ STATE=$(xcrun simctl list devices -j \
+ | python3 -c "
+import json, sys
+data = json.load(sys.stdin)
+for runtime_devs in data['devices'].values():
+ for d in runtime_devs:
+ if d['udid'] == '$SIM_UDID':
+ print(d['state'])
+ sys.exit(0)
+print('Unknown')
+")
+ if [ "$STATE" = "Booted" ]; then
+ echo "Simulator booted after ~''${BOOT_ELAPSED}s"
+ break
+ fi
+ sleep 2
+ BOOT_ELAPSED=$((BOOT_ELAPSED + 2))
+done
+
+if [ "$STATE" != "Booted" ]; then
+ echo "ERROR: Simulator failed to boot within ''${BOOT_TIMEOUT}s"
+ exit 1
+fi
+
+sleep 5
+
+# ===========================================================================
+# PHASE 1 + PHASE 2 — Run test scripts
+# ===========================================================================
+export SIM_UDID BUNDLE_ID COUNTER_APP SCROLL_APP TEXTINPUT_APP PERMISSION_APP IMAGE_APP NODEPOOL_APP WORK_DIR
+
+PHASE1_EXIT=0
+PHASE2_EXIT=0
+PHASE3_EXIT=0
+PHASE4_EXIT=0
+PHASE5_EXIT=0
+PHASE6_EXIT=0
+
+# run_with_retry LABEL COMMAND [ARGS...]
+# Runs the command up to 10 times. Succeeds on first pass, fails only if all 10 fail.
+# If the command outputs "FATAL:", retrying is pointless (e.g. native library failed
+# to load), so we stop immediately and report the error.
+run_with_retry() {
+ local label="$1"; shift
+ local max_attempts=10
+ local attempt=1
+ local output_file="$WORK_DIR/retry_''${label}.log"
+ while [ $attempt -le $max_attempts ]; do
+ echo "[$label] attempt $attempt/$max_attempts"
+ if "$@" 2>&1 | tee "$output_file"; then
+ echo "[$label] PASSED on attempt $attempt"
+ return 0
+ fi
+ if grep -q "^FATAL:" "$output_file" 2>/dev/null; then
+ echo "[$label] FATAL error detected — not retrying"
+ return 1
+ fi
+ echo "[$label] attempt $attempt FAILED"
+ attempt=$((attempt + 1))
+ if [ $attempt -le $max_attempts ]; then
+ echo "[$label] retrying in 5s..."
+ sleep 5
+ fi
+ done
+ echo "[$label] FAILED after $max_attempts attempts"
+ return 1
+}
+
+echo ""
+echo "--- lifecycle ---"
+run_with_retry "lifecycle" bash "$TEST_SCRIPTS/ios/lifecycle.sh" || PHASE1_EXIT=1
+echo "--- ui ---"
+run_with_retry "ui" bash "$TEST_SCRIPTS/ios/ui.sh" || PHASE1_EXIT=1
+echo "--- buttons ---"
+run_with_retry "buttons" bash "$TEST_SCRIPTS/ios/buttons.sh" || PHASE1_EXIT=1
+echo "--- scroll ---"
+run_with_retry "scroll" bash "$TEST_SCRIPTS/ios/scroll.sh" || PHASE2_EXIT=1
+echo "--- styled ---"
+run_with_retry "styled" bash "$TEST_SCRIPTS/ios/styled.sh" || PHASE1_EXIT=1
+echo "--- locale ---"
+run_with_retry "locale" bash "$TEST_SCRIPTS/ios/locale.sh" || PHASE1_EXIT=1
+echo "--- textinput ---"
+run_with_retry "textinput" bash "$TEST_SCRIPTS/ios/textinput.sh" || PHASE3_EXIT=1
+echo "--- permission ---"
+run_with_retry "permission" bash "$TEST_SCRIPTS/ios/permission.sh" || PHASE4_EXIT=1
+echo "--- image ---"
+run_with_retry "image" bash "$TEST_SCRIPTS/ios/image.sh" || PHASE6_EXIT=1
+echo "--- node-pool ---"
+run_with_retry "node-pool" bash "$TEST_SCRIPTS/ios/node-pool.sh" || PHASE5_EXIT=1
+
+# --- Phase results ---
+if [ $PHASE1_EXIT -eq 0 ]; then
+ PHASE1_OK=1
+ echo ""
+ echo "PHASE 1 PASSED"
+else
+ echo ""
+ echo "PHASE 1 FAILED"
+fi
+
+if [ $PHASE2_EXIT -eq 0 ]; then
+ PHASE2_OK=1
+ echo ""
+ echo "PHASE 2 PASSED"
+else
+ echo ""
+ echo "PHASE 2 FAILED"
+fi
+
+if [ $PHASE3_EXIT -eq 0 ]; then
+ PHASE3_OK=1
+ echo ""
+ echo "PHASE 3 PASSED"
+else
+ PHASE3_OK=0
+ echo ""
+ echo "PHASE 3 FAILED"
+fi
+
+if [ $PHASE4_EXIT -eq 0 ]; then
+ PHASE4_OK=1
+ echo ""
+ echo "PHASE 4 PASSED"
+else
+ PHASE4_OK=0
+ echo ""
+ echo "PHASE 4 FAILED"
+fi
+
+if [ $PHASE5_EXIT -eq 0 ]; then
+ PHASE5_OK=1
+ echo ""
+ echo "PHASE 5 PASSED"
+else
+ PHASE5_OK=0
+ echo ""
+ echo "PHASE 5 FAILED"
+fi
+
+if [ $PHASE6_EXIT -eq 0 ]; then
+ PHASE6_OK=1
+ echo ""
+ echo "PHASE 6 PASSED"
+else
+ PHASE6_OK=0
+ echo ""
+ echo "PHASE 6 FAILED"
+fi
+
+# ===========================================================================
+# Final report
+# ===========================================================================
+echo ""
+echo "============================================================"
+echo "FINAL REPORT"
+echo "============================================================"
+
+FINAL_EXIT=0
+
+if [ $PHASE1_OK -eq 1 ]; then
+ echo "PASS Phase 1 — Counter app (lifecycle + UI + buttons)"
+else
+ echo "FAIL Phase 1 — Counter app (lifecycle + UI + buttons)"
+ FINAL_EXIT=1
+fi
+
+if [ $PHASE2_OK -eq 1 ]; then
+ echo "PASS Phase 2 — Scroll demo app"
+else
+ echo "FAIL Phase 2 — Scroll demo app"
+ FINAL_EXIT=1
+fi
+
+if [ $PHASE3_OK -eq 1 ]; then
+ echo "PASS Phase 3 — TextInput demo app"
+else
+ echo "FAIL Phase 3 — TextInput demo app"
+ FINAL_EXIT=1
+fi
+
+if [ $PHASE4_OK -eq 1 ]; then
+ echo "PASS Phase 4 — Permission demo app"
+else
+ echo "FAIL Phase 4 — Permission demo app"
+ FINAL_EXIT=1
+fi
+
+if [ $PHASE5_OK -eq 1 ]; then
+ echo "PASS Phase 5 — Node pool stress test (300 nodes, dynamic pool)"
+else
+ echo "FAIL Phase 5 — Node pool stress test (300 nodes, dynamic pool)"
+ FINAL_EXIT=1
+fi
+
+if [ $PHASE6_OK -eq 1 ]; then
+ echo "PASS Phase 6 — Image demo app"
+else
+ echo "FAIL Phase 6 — Image demo app"
+ FINAL_EXIT=1
+fi
+
+echo ""
+if [ $FINAL_EXIT -eq 0 ]; then
+ echo "All combined simulator integration checks passed!"
+else
+ echo "Some combined simulator integration checks FAILED."
+fi
+
+exit $FINAL_EXIT
+SCRIPT
+
+ chmod +x $out/bin/test-all-ios
+ '';
+
+ installPhase = "true";
+}
diff --git a/nix/simulator-app.nix b/nix/simulator-app.nix
new file mode 100644
index 00000000..932827f0
--- /dev/null
+++ b/nix/simulator-app.nix
@@ -0,0 +1,11 @@
+# Staged iOS simulator app — thin wrapper around lib.nix.
+{ sources ? import ../npins }:
+let
+ lib = import ./lib.nix { inherit sources; };
+ iosLib = import ./ios.nix { inherit sources; simulator = true; };
+in
+lib.mkSimulatorApp {
+ inherit iosLib;
+ iosSrc = ../ios;
+ name = "haskell-mobile-simulator-app";
+}
diff --git a/nix/test-link-consumer.nix b/nix/test-link-consumer.nix
new file mode 100644
index 00000000..129e37b3
--- /dev/null
+++ b/nix/test-link-consumer.nix
@@ -0,0 +1,7 @@
+# Consumer link test: build the Android library with a minimal consumer entry
+# point that does not export any test-only symbols.
+#
+# Fails with "undefined reference to haskellFoo" if jni_bridge.c calls a
+# haskell* function that is only exported from App.hs (consumer-replaceable).
+{ sources ? import ../npins }:
+import ./android.nix { inherit sources; mainModule = ../test/ScrollDemoMain.hs; }
diff --git a/nix/watchos-simulator-all.nix b/nix/watchos-simulator-all.nix
new file mode 100644
index 00000000..991d01bc
--- /dev/null
+++ b/nix/watchos-simulator-all.nix
@@ -0,0 +1,530 @@
+# watchOS Simulator combined integration test.
+#
+# Single simulator session covering all test suites:
+#
+# Phase 1 — Counter app (lifecycle + UI rendering + two-button sequence)
+# Verifies: Lifecycle: Create/Resume, setRoot/setStrProp/setHandler,
+# --autotest fires Counter: 1, --autotest-buttons fires full sequence.
+#
+# Phase 2 — Scroll demo app
+# Verifies: createNode(type=5), setRoot, Click dispatched: callbackId=0.
+#
+# One boot + teardown cycle instead of four.
+#
+# Usage:
+# nix-build nix/watchos-simulator-all.nix -o result-watchos-simulator-all
+# ./result-watchos-simulator-all/bin/test-all-watchos
+{ sources ? import ../npins }:
+let
+ pkgs = import sources.nixpkgs {};
+
+ lib = import ./lib.nix { inherit sources; };
+
+ counterSimApp = import ./watchos-simulator-app.nix { inherit sources; };
+
+ scrollWatchos = import ./watchos.nix {
+ inherit sources;
+ mainModule = ../test/ScrollDemoMain.hs;
+ simulator = true;
+ };
+ scrollSimApp = lib.mkWatchOSSimulatorApp {
+ watchosLib = scrollWatchos;
+ watchosSrc = ../watchos;
+ name = "haskell-mobile-watchos-scroll-simulator-app";
+ };
+
+ textinputWatchos = import ./watchos.nix {
+ inherit sources;
+ mainModule = ../test/TextInputDemoMain.hs;
+ simulator = true;
+ };
+ textinputSimApp = lib.mkWatchOSSimulatorApp {
+ watchosLib = textinputWatchos;
+ watchosSrc = ../watchos;
+ name = "haskell-mobile-watchos-textinput-simulator-app";
+ };
+
+ imageWatchos = import ./watchos.nix {
+ inherit sources;
+ mainModule = ../test/ImageDemoMain.hs;
+ simulator = true;
+ };
+ imageSimApp = lib.mkWatchOSSimulatorApp {
+ watchosLib = imageWatchos;
+ watchosSrc = ../watchos;
+ name = "haskell-mobile-watchos-image-simulator-app";
+ };
+
+ # watchOS uses a Swift dictionary (unbounded) — no DYNAMIC_NODE_POOL needed.
+ # This test just confirms 300 nodes render successfully.
+ nodepoolWatchos = import ./watchos.nix {
+ inherit sources;
+ mainModule = ../test/NodePoolTestMain.hs;
+ simulator = true;
+ };
+ nodepoolSimApp = lib.mkWatchOSSimulatorApp {
+ watchosLib = nodepoolWatchos;
+ watchosSrc = ../watchos;
+ name = "haskell-mobile-watchos-nodepool-simulator-app";
+ };
+
+ xcodegen = pkgs.xcodegen;
+
+ testScripts = builtins.path { path = ../test; name = "test-scripts"; };
+
+in pkgs.stdenv.mkDerivation {
+ name = "haskell-mobile-watchos-simulator-all-tests";
+
+ dontUnpack = true;
+
+ buildPhase = ''
+ mkdir -p $out/bin
+
+ cat > $out/bin/test-all-watchos << 'SCRIPT'
+#!/usr/bin/env bash
+set -euo pipefail
+
+# --- Configuration ---
+BUNDLE_ID="me.jappie.haskellmobile.watchkitapp"
+SCHEME="HaskellMobile"
+DEVICE_TYPE="Apple Watch Series 9 (45mm)"
+COUNTER_SHARE_DIR="${counterSimApp}/share/watchos"
+SCROLL_SHARE_DIR="${scrollSimApp}/share/watchos"
+TEXTINPUT_SHARE_DIR="${textinputSimApp}/share/watchos"
+IMAGE_SHARE_DIR="${imageSimApp}/share/watchos"
+NODEPOOL_SHARE_DIR="${nodepoolSimApp}/share/watchos"
+TEST_SCRIPTS="${testScripts}"
+
+# --- Temp working directory ---
+WORK_DIR=$(mktemp -d /tmp/haskell-mobile-watchos-sim-all-XXXX)
+SIM_UDID=""
+
+# Phase result tracking
+PHASE1_OK=0
+PHASE2_OK=0
+PHASE3_OK=0
+PHASE4_OK=0
+PHASE5_OK=0
+
+cleanup() {
+ echo ""
+ echo "=== Cleaning up ==="
+ if [ -n "$SIM_UDID" ]; then
+ echo "Shutting down simulator $SIM_UDID"
+ xcrun simctl shutdown "$SIM_UDID" 2>/dev/null || true
+ echo "Deleting simulator $SIM_UDID"
+ xcrun simctl delete "$SIM_UDID" 2>/dev/null || true
+ fi
+ rm -rf "$WORK_DIR"
+ echo "Cleanup done."
+}
+trap cleanup EXIT
+
+echo "=== watchOS Simulator All-Tests ==="
+echo "Working directory: $WORK_DIR"
+
+# ===========================================================================
+# PHASE 0 — Build both apps + boot simulator
+# ===========================================================================
+echo ""
+echo "============================================================"
+echo "PHASE 0: Build apps and boot simulator"
+echo "============================================================"
+
+# --- Stage and build counter app ---
+echo "=== Staging counter app ==="
+mkdir -p "$WORK_DIR/counter/lib" "$WORK_DIR/counter/include"
+cp "$COUNTER_SHARE_DIR/lib/libHaskellMobile.a" "$WORK_DIR/counter/lib/"
+cp "$COUNTER_SHARE_DIR/include/HaskellMobile.h" "$WORK_DIR/counter/include/"
+cp "$COUNTER_SHARE_DIR/include/UIBridge.h" "$WORK_DIR/counter/include/"
+cp "$COUNTER_SHARE_DIR/include/PermissionBridge.h" "$WORK_DIR/counter/include/"
+cp -r "$COUNTER_SHARE_DIR/HaskellMobile" "$WORK_DIR/counter/"
+cp "$COUNTER_SHARE_DIR/project.yml" "$WORK_DIR/counter/"
+chmod -R u+w "$WORK_DIR/counter"
+
+echo "=== Generating counter Xcode project ==="
+cd "$WORK_DIR/counter"
+${xcodegen}/bin/xcodegen generate
+
+echo "=== Building counter app for watchOS simulator ==="
+xcodebuild build \
+ -project HaskellMobile.xcodeproj \
+ -scheme "$SCHEME" \
+ -sdk watchsimulator \
+ -configuration Release \
+ -derivedDataPath "$WORK_DIR/counter-build" \
+ CODE_SIGN_IDENTITY=- \
+ CODE_SIGNING_ALLOWED=NO \
+ ARCHS=arm64 \
+ ONLY_ACTIVE_ARCH=NO \
+ | tail -20
+
+COUNTER_APP=$(find "$WORK_DIR/counter-build" -name "*.app" -type d | head -1)
+if [ -z "$COUNTER_APP" ]; then
+ echo "ERROR: Could not find counter .app bundle"
+ exit 1
+fi
+echo "Counter app: $COUNTER_APP"
+
+# --- Stage and build scroll demo app ---
+echo "=== Staging scroll demo app ==="
+mkdir -p "$WORK_DIR/scroll/lib" "$WORK_DIR/scroll/include"
+cp "$SCROLL_SHARE_DIR/lib/libHaskellMobile.a" "$WORK_DIR/scroll/lib/"
+cp "$SCROLL_SHARE_DIR/include/HaskellMobile.h" "$WORK_DIR/scroll/include/"
+cp "$SCROLL_SHARE_DIR/include/UIBridge.h" "$WORK_DIR/scroll/include/"
+cp "$SCROLL_SHARE_DIR/include/PermissionBridge.h" "$WORK_DIR/scroll/include/"
+cp -r "$SCROLL_SHARE_DIR/HaskellMobile" "$WORK_DIR/scroll/"
+cp "$SCROLL_SHARE_DIR/project.yml" "$WORK_DIR/scroll/"
+chmod -R u+w "$WORK_DIR/scroll"
+
+echo "=== Generating scroll Xcode project ==="
+cd "$WORK_DIR/scroll"
+${xcodegen}/bin/xcodegen generate
+
+echo "=== Building scroll demo app for watchOS simulator ==="
+xcodebuild build \
+ -project HaskellMobile.xcodeproj \
+ -scheme "$SCHEME" \
+ -sdk watchsimulator \
+ -configuration Release \
+ -derivedDataPath "$WORK_DIR/scroll-build" \
+ CODE_SIGN_IDENTITY=- \
+ CODE_SIGNING_ALLOWED=NO \
+ ARCHS=arm64 \
+ ONLY_ACTIVE_ARCH=NO \
+ | tail -20
+
+SCROLL_APP=$(find "$WORK_DIR/scroll-build" -name "*.app" -type d | head -1)
+if [ -z "$SCROLL_APP" ]; then
+ echo "ERROR: Could not find scroll .app bundle"
+ exit 1
+fi
+echo "Scroll app: $SCROLL_APP"
+
+# --- Stage and build textinput demo app ---
+echo "=== Staging textinput demo app ==="
+mkdir -p "$WORK_DIR/textinput/lib" "$WORK_DIR/textinput/include"
+cp "$TEXTINPUT_SHARE_DIR/lib/libHaskellMobile.a" "$WORK_DIR/textinput/lib/"
+cp "$TEXTINPUT_SHARE_DIR/include/HaskellMobile.h" "$WORK_DIR/textinput/include/"
+cp "$TEXTINPUT_SHARE_DIR/include/UIBridge.h" "$WORK_DIR/textinput/include/"
+cp "$TEXTINPUT_SHARE_DIR/include/PermissionBridge.h" "$WORK_DIR/textinput/include/"
+cp -r "$TEXTINPUT_SHARE_DIR/HaskellMobile" "$WORK_DIR/textinput/"
+cp "$TEXTINPUT_SHARE_DIR/project.yml" "$WORK_DIR/textinput/"
+chmod -R u+w "$WORK_DIR/textinput"
+
+echo "=== Generating textinput Xcode project ==="
+cd "$WORK_DIR/textinput"
+${xcodegen}/bin/xcodegen generate
+
+echo "=== Building textinput demo app for watchOS simulator ==="
+xcodebuild build \
+ -project HaskellMobile.xcodeproj \
+ -scheme "$SCHEME" \
+ -sdk watchsimulator \
+ -configuration Release \
+ -derivedDataPath "$WORK_DIR/textinput-build" \
+ CODE_SIGN_IDENTITY=- \
+ CODE_SIGNING_ALLOWED=NO \
+ ARCHS=arm64 \
+ ONLY_ACTIVE_ARCH=NO \
+ | tail -20
+
+TEXTINPUT_APP=$(find "$WORK_DIR/textinput-build" -name "*.app" -type d | head -1)
+if [ -z "$TEXTINPUT_APP" ]; then
+ echo "ERROR: Could not find textinput .app bundle"
+ exit 1
+fi
+echo "TextInput app: $TEXTINPUT_APP"
+
+# --- Stage and build node-pool test app ---
+echo "=== Staging image test app ==="
+mkdir -p "$WORK_DIR/image/lib" "$WORK_DIR/image/include"
+cp "$IMAGE_SHARE_DIR/lib/libHaskellMobile.a" "$WORK_DIR/image/lib/"
+cp "$IMAGE_SHARE_DIR/include/HaskellMobile.h" "$WORK_DIR/image/include/"
+cp "$IMAGE_SHARE_DIR/include/UIBridge.h" "$WORK_DIR/image/include/"
+cp "$IMAGE_SHARE_DIR/include/PermissionBridge.h" "$WORK_DIR/image/include/"
+cp -r "$IMAGE_SHARE_DIR/HaskellMobile" "$WORK_DIR/image/"
+cp "$IMAGE_SHARE_DIR/project.yml" "$WORK_DIR/image/"
+chmod -R u+w "$WORK_DIR/image"
+
+echo "=== Generating image Xcode project ==="
+cd "$WORK_DIR/image"
+${xcodegen}/bin/xcodegen generate
+
+echo "=== Building image test app for watchOS simulator ==="
+xcodebuild build \
+ -project HaskellMobile.xcodeproj \
+ -scheme "$SCHEME" \
+ -sdk watchsimulator \
+ -configuration Release \
+ -derivedDataPath "$WORK_DIR/image-build" \
+ CODE_SIGN_IDENTITY=- \
+ CODE_SIGNING_ALLOWED=NO \
+ ARCHS=arm64 \
+ ONLY_ACTIVE_ARCH=NO \
+ | tail -20
+
+IMAGE_APP=$(find "$WORK_DIR/image-build" -name "*.app" -type d | head -1)
+if [ -z "$IMAGE_APP" ]; then
+ echo "ERROR: Could not find image .app bundle"
+ exit 1
+fi
+echo "Image app: $IMAGE_APP"
+
+echo "=== Staging node-pool test app ==="
+mkdir -p "$WORK_DIR/nodepool/lib" "$WORK_DIR/nodepool/include"
+cp "$NODEPOOL_SHARE_DIR/lib/libHaskellMobile.a" "$WORK_DIR/nodepool/lib/"
+cp "$NODEPOOL_SHARE_DIR/include/HaskellMobile.h" "$WORK_DIR/nodepool/include/"
+cp "$NODEPOOL_SHARE_DIR/include/UIBridge.h" "$WORK_DIR/nodepool/include/"
+cp "$NODEPOOL_SHARE_DIR/include/PermissionBridge.h" "$WORK_DIR/nodepool/include/"
+cp -r "$NODEPOOL_SHARE_DIR/HaskellMobile" "$WORK_DIR/nodepool/"
+cp "$NODEPOOL_SHARE_DIR/project.yml" "$WORK_DIR/nodepool/"
+chmod -R u+w "$WORK_DIR/nodepool"
+
+echo "=== Generating node-pool Xcode project ==="
+cd "$WORK_DIR/nodepool"
+${xcodegen}/bin/xcodegen generate
+
+echo "=== Building node-pool test app for watchOS simulator ==="
+xcodebuild build \
+ -project HaskellMobile.xcodeproj \
+ -scheme "$SCHEME" \
+ -sdk watchsimulator \
+ -configuration Release \
+ -derivedDataPath "$WORK_DIR/nodepool-build" \
+ CODE_SIGN_IDENTITY=- \
+ CODE_SIGNING_ALLOWED=NO \
+ ARCHS=arm64 \
+ ONLY_ACTIVE_ARCH=NO \
+ | tail -20
+
+NODEPOOL_APP=$(find "$WORK_DIR/nodepool-build" -name "*.app" -type d | head -1)
+if [ -z "$NODEPOOL_APP" ]; then
+ echo "ERROR: Could not find node-pool .app bundle"
+ exit 1
+fi
+echo "NodePool app: $NODEPOOL_APP"
+
+# --- Discover latest watchOS runtime ---
+echo "=== Discovering watchOS runtime ==="
+RUNTIME=$(xcrun simctl list runtimes -j \
+ | python3 -c "
+import json, sys
+data = json.load(sys.stdin)
+watchos_runtimes = [r for r in data['runtimes'] if r['platform'] == 'watchOS' and r['isAvailable']]
+if not watchos_runtimes:
+ print('ERROR: No available watchOS runtimes', file=sys.stderr)
+ sys.exit(1)
+print(watchos_runtimes[-1]['identifier'])
+")
+echo "Runtime: $RUNTIME"
+
+# --- Create and boot simulator ---
+echo "=== Creating simulator ==="
+SIM_UDID=$(xcrun simctl create "test-all-watchos" "$DEVICE_TYPE" "$RUNTIME" \
+ | tr -d '[:space:]')
+
+if [ -z "$SIM_UDID" ]; then
+ echo "ERROR: Failed to create simulator device"
+ exit 1
+fi
+echo "Simulator UDID: $SIM_UDID"
+
+echo "=== Booting simulator ==="
+xcrun simctl boot "$SIM_UDID"
+
+BOOT_TIMEOUT=120
+BOOT_ELAPSED=0
+STATE="Unknown"
+while [ $BOOT_ELAPSED -lt $BOOT_TIMEOUT ]; do
+ STATE=$(xcrun simctl list devices -j \
+ | python3 -c "
+import json, sys
+data = json.load(sys.stdin)
+for runtime_devs in data['devices'].values():
+ for d in runtime_devs:
+ if d['udid'] == '$SIM_UDID':
+ print(d['state'])
+ sys.exit(0)
+print('Unknown')
+")
+ if [ "$STATE" = "Booted" ]; then
+ echo "Simulator booted after ~''${BOOT_ELAPSED}s"
+ break
+ fi
+ sleep 2
+ BOOT_ELAPSED=$((BOOT_ELAPSED + 2))
+done
+
+if [ "$STATE" != "Booted" ]; then
+ echo "ERROR: Simulator failed to boot within ''${BOOT_TIMEOUT}s"
+ exit 1
+fi
+
+sleep 5
+
+# ===========================================================================
+# PHASE 1 + PHASE 2 — Run test scripts
+# ===========================================================================
+# Log subsystem differs from bundle ID for watchOS (bundle ID has .watchkitapp suffix)
+LOG_SUBSYSTEM="me.jappie.haskellmobile"
+export SIM_UDID BUNDLE_ID LOG_SUBSYSTEM COUNTER_APP SCROLL_APP TEXTINPUT_APP IMAGE_APP NODEPOOL_APP WORK_DIR
+
+PHASE1_EXIT=0
+PHASE2_EXIT=0
+PHASE3_EXIT=0
+PHASE4_EXIT=0
+PHASE5_EXIT=0
+
+# run_with_retry LABEL COMMAND [ARGS...]
+# Runs the command up to 10 times. Succeeds on first pass, fails only if all 10 fail.
+run_with_retry() {
+ local label="$1"; shift
+ local max_attempts=10
+ local attempt=1
+ while [ $attempt -le $max_attempts ]; do
+ echo "[$label] attempt $attempt/$max_attempts"
+ if "$@"; then
+ echo "[$label] PASSED on attempt $attempt"
+ return 0
+ fi
+ echo "[$label] attempt $attempt FAILED"
+ attempt=$((attempt + 1))
+ if [ $attempt -le $max_attempts ]; then
+ echo "[$label] retrying in 5s..."
+ sleep 5
+ fi
+ done
+ echo "[$label] FAILED after $max_attempts attempts"
+ return 1
+}
+
+echo ""
+echo "--- lifecycle ---"
+run_with_retry "lifecycle" bash "$TEST_SCRIPTS/watchos/lifecycle.sh" || PHASE1_EXIT=1
+echo "--- ui ---"
+run_with_retry "ui" bash "$TEST_SCRIPTS/watchos/ui.sh" || PHASE1_EXIT=1
+echo "--- buttons ---"
+run_with_retry "buttons" bash "$TEST_SCRIPTS/watchos/buttons.sh" || PHASE1_EXIT=1
+echo "--- scroll ---"
+run_with_retry "scroll" bash "$TEST_SCRIPTS/watchos/scroll.sh" || PHASE2_EXIT=1
+echo "--- styled ---"
+run_with_retry "styled" bash "$TEST_SCRIPTS/watchos/styled.sh" || PHASE1_EXIT=1
+echo "--- locale ---"
+run_with_retry "locale" bash "$TEST_SCRIPTS/watchos/locale.sh" || PHASE1_EXIT=1
+echo "--- textinput ---"
+run_with_retry "textinput" bash "$TEST_SCRIPTS/watchos/textinput.sh" || PHASE3_EXIT=1
+echo "--- image ---"
+run_with_retry "image" bash "$TEST_SCRIPTS/watchos/image.sh" || PHASE5_EXIT=1
+echo "--- node-pool ---"
+run_with_retry "node-pool" bash "$TEST_SCRIPTS/watchos/node-pool.sh" || PHASE4_EXIT=1
+
+# --- Phase results ---
+if [ $PHASE1_EXIT -eq 0 ]; then
+ PHASE1_OK=1
+ echo ""
+ echo "PHASE 1 PASSED"
+else
+ echo ""
+ echo "PHASE 1 FAILED"
+fi
+
+if [ $PHASE2_EXIT -eq 0 ]; then
+ PHASE2_OK=1
+ echo ""
+ echo "PHASE 2 PASSED"
+else
+ echo ""
+ echo "PHASE 2 FAILED"
+fi
+
+if [ $PHASE3_EXIT -eq 0 ]; then
+ PHASE3_OK=1
+ echo ""
+ echo "PHASE 3 PASSED"
+else
+ PHASE3_OK=0
+ echo ""
+ echo "PHASE 3 FAILED"
+fi
+
+if [ $PHASE4_EXIT -eq 0 ]; then
+ PHASE4_OK=1
+ echo ""
+ echo "PHASE 4 PASSED"
+else
+ PHASE4_OK=0
+ echo ""
+ echo "PHASE 4 FAILED"
+fi
+
+if [ $PHASE5_EXIT -eq 0 ]; then
+ PHASE5_OK=1
+ echo ""
+ echo "PHASE 5 PASSED"
+else
+ PHASE5_OK=0
+ echo ""
+ echo "PHASE 5 FAILED"
+fi
+
+# ===========================================================================
+# Final report
+# ===========================================================================
+echo ""
+echo "============================================================"
+echo "FINAL REPORT"
+echo "============================================================"
+
+FINAL_EXIT=0
+
+if [ $PHASE1_OK -eq 1 ]; then
+ echo "PASS Phase 1 — Counter app (lifecycle + UI + buttons)"
+else
+ echo "FAIL Phase 1 — Counter app (lifecycle + UI + buttons)"
+ FINAL_EXIT=1
+fi
+
+if [ $PHASE2_OK -eq 1 ]; then
+ echo "PASS Phase 2 — Scroll demo app"
+else
+ echo "FAIL Phase 2 — Scroll demo app"
+ FINAL_EXIT=1
+fi
+
+if [ $PHASE3_OK -eq 1 ]; then
+ echo "PASS Phase 3 — TextInput demo app"
+else
+ echo "FAIL Phase 3 — TextInput demo app"
+ FINAL_EXIT=1
+fi
+
+if [ $PHASE4_OK -eq 1 ]; then
+ echo "PASS Phase 4 — Node pool stress test (300 nodes)"
+else
+ echo "FAIL Phase 4 — Node pool stress test (300 nodes)"
+ FINAL_EXIT=1
+fi
+
+if [ $PHASE5_OK -eq 1 ]; then
+ echo "PASS Phase 5 — Image demo app"
+else
+ echo "FAIL Phase 5 — Image demo app"
+ FINAL_EXIT=1
+fi
+
+echo ""
+if [ $FINAL_EXIT -eq 0 ]; then
+ echo "All combined watchOS simulator integration checks passed!"
+else
+ echo "Some combined watchOS simulator integration checks FAILED."
+fi
+
+exit $FINAL_EXIT
+SCRIPT
+
+ chmod +x $out/bin/test-all-watchos
+ '';
+
+ installPhase = "true";
+}
diff --git a/nix/watchos-simulator-app.nix b/nix/watchos-simulator-app.nix
new file mode 100644
index 00000000..83cdd31a
--- /dev/null
+++ b/nix/watchos-simulator-app.nix
@@ -0,0 +1,11 @@
+# Staged watchOS simulator app — thin wrapper around lib.nix.
+{ sources ? import ../npins }:
+let
+ lib = import ./lib.nix { inherit sources; };
+ watchosLib = import ./watchos.nix { inherit sources; simulator = true; };
+in
+lib.mkWatchOSSimulatorApp {
+ inherit watchosLib;
+ watchosSrc = ../watchos;
+ name = "haskell-mobile-watchos-simulator-app";
+}
diff --git a/nix/watchos.nix b/nix/watchos.nix
new file mode 100644
index 00000000..a4901c85
--- /dev/null
+++ b/nix/watchos.nix
@@ -0,0 +1,19 @@
+# watchOS static library — thin wrapper around lib.nix.
+{ sources ? import ../npins
+, simulator ? false
+, mainModule ? ../app/MobileMain.hs
+, consumerCabalFile ? null
+, consumerCabal2Nix ? null
+, hpkgs ? (_: _: {}) # consumer haskellPackages overrides
+}:
+let
+ lib = import ./lib.nix { inherit sources; };
+ iosDeps = import ./ios-deps.nix {
+ inherit sources consumerCabalFile consumerCabal2Nix hpkgs;
+ };
+in
+lib.mkWatchOSLib {
+ haskellMobileSrc = ../.;
+ inherit mainModule simulator;
+ crossDeps = iosDeps;
+}
diff --git a/npins/default.nix b/npins/default.nix
index 65924762..884fc8cc 100644
--- a/npins/default.nix
+++ b/npins/default.nix
@@ -9,8 +9,15 @@
*/
# Generated by npins. Do not modify; will be overwritten regularly
let
- data = builtins.fromJSON (builtins.readFile ./sources.json);
- version = data.version;
+ # Backwards-compatibly make something that previously didn't take any arguments take some
+ # The function must return an attrset, and will unfortunately be eagerly evaluated
+ # Same thing, but it catches eval errors on the default argument so that one may still call it with other arguments
+ mkFunctor =
+ fn:
+ let
+ e = builtins.tryEval (fn { });
+ in
+ (if e.success then e.value else { error = fn { }; }) // { __functor = _self: fn; };
# https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/lists.nix#L295
range =
@@ -21,7 +28,6 @@ let
# https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/strings.nix#L269
stringAsChars = f: s: concatStrings (map f (stringToCharacters s));
- concatMapStrings = f: list: concatStrings (map f list);
concatStrings = builtins.concatStringsSep "";
# If the environment variable NPINS_OVERRIDE_${name} is set, then use
@@ -48,41 +54,87 @@ let
mkSource =
name: spec:
+ {
+ pkgs ? null,
+ }:
assert spec ? type;
let
+ # Unify across builtin and pkgs fetchers.
+ # `fetchGit` requires a wrapper because of slight API differences.
+ fetchers =
+ if pkgs == null then
+ {
+ inherit (builtins) fetchTarball fetchurl;
+ # For some fucking reason, fetchGit has a different signature than the other builtin fetchers …
+ fetchGit = args: (builtins.fetchGit args).outPath;
+ }
+ else
+ {
+ fetchTarball =
+ {
+ url,
+ sha256,
+ }:
+ pkgs.fetchzip {
+ inherit url sha256;
+ extension = "tar";
+ };
+ inherit (pkgs) fetchurl;
+ fetchGit =
+ {
+ url,
+ submodules,
+ rev,
+ name,
+ narHash,
+ }:
+ pkgs.fetchgit {
+ inherit url rev name;
+ fetchSubmodules = submodules;
+ hash = narHash;
+ };
+ };
+
+ # Dispatch to the correct code path based on the type
path =
if spec.type == "Git" then
- mkGitSource spec
+ mkGitSource fetchers spec
else if spec.type == "GitRelease" then
- mkGitSource spec
+ mkGitSource fetchers spec
else if spec.type == "PyPi" then
- mkPyPiSource spec
+ mkPyPiSource fetchers spec
else if spec.type == "Channel" then
- mkChannelSource spec
+ mkChannelSource fetchers spec
else if spec.type == "Tarball" then
- mkTarballSource spec
+ mkTarballSource fetchers spec
+ else if spec.type == "Container" then
+ mkContainerSource pkgs spec
else
builtins.throw "Unknown source type ${spec.type}";
in
spec // { outPath = mayOverride name path; };
mkGitSource =
+ {
+ fetchTarball,
+ fetchGit,
+ ...
+ }:
{
repository,
revision,
url ? null,
submodules,
hash,
- branch ? null,
...
}:
assert repository ? type;
# At the moment, either it is a plain git repository (which has an url), or it is a GitHub/GitLab repository
# In the latter case, there we will always be an url to the tarball
if url != null && !submodules then
- builtins.fetchTarball {
+ fetchTarball {
inherit url;
- sha256 = hash; # FIXME: check nix version & use SRI hashes
+ sha256 = hash;
}
else
let
@@ -93,6 +145,8 @@ let
"https://github.com/${repository.owner}/${repository.repo}.git"
else if repository.type == "GitLab" then
"${repository.server}/${repository.repo_path}.git"
+ else if repository.type == "Forgejo" then
+ "${repository.server}/${repository.owner}/${repository.repo}.git"
else
throw "Unrecognized repository type ${repository.type}";
urlToName =
@@ -107,40 +161,89 @@ let
"${if matched == null then "source" else builtins.head matched}${appendShort}";
name = urlToName url revision;
in
- builtins.fetchGit {
+ fetchGit {
rev = revision;
- inherit name;
- # hash = hash;
- inherit url submodules;
+ narHash = hash;
+
+ inherit name submodules url;
};
mkPyPiSource =
- { url, hash, ... }:
- builtins.fetchurl {
+ { fetchurl, ... }:
+ {
+ url,
+ hash,
+ ...
+ }:
+ fetchurl {
inherit url;
sha256 = hash;
};
mkChannelSource =
- { url, hash, ... }:
- builtins.fetchTarball {
+ { fetchTarball, ... }:
+ {
+ url,
+ hash,
+ ...
+ }:
+ fetchTarball {
inherit url;
sha256 = hash;
};
mkTarballSource =
+ { fetchTarball, ... }:
{
url,
locked_url ? url,
hash,
...
}:
- builtins.fetchTarball {
+ fetchTarball {
url = locked_url;
sha256 = hash;
};
+
+ mkContainerSource =
+ pkgs:
+ {
+ image_name,
+ image_tag,
+ image_digest,
+ ...
+ }:
+ if pkgs == null then
+ builtins.throw "container sources require passing in a Nixpkgs value: https://github.com/andir/npins/blob/master/README.md#using-the-nixpkgs-fetchers"
+ else
+ pkgs.dockerTools.pullImage {
+ imageName = image_name;
+ imageDigest = image_digest;
+ finalImageTag = image_tag;
+ };
in
-if version == 5 then
- builtins.mapAttrs mkSource data.pins
-else
- throw "Unsupported format version ${toString version} in sources.json. Try running `npins upgrade`"
+mkFunctor (
+ {
+ input ? ./sources.json,
+ }:
+ let
+ data =
+ if builtins.isPath input then
+ # while `readFile` will throw an error anyways if the path doesn't exist,
+ # we still need to check beforehand because *our* error can be caught but not the one from the builtin
+ # *piegames sighs*
+ if builtins.pathExists input then
+ builtins.fromJSON (builtins.readFile input)
+ else
+ throw "Input path ${toString input} does not exist"
+ else if builtins.isAttrs input then
+ input
+ else
+ throw "Unsupported input type ${builtins.typeOf input}, must be a path or an attrset";
+ version = data.version;
+ in
+ if version == 7 then
+ builtins.mapAttrs (name: spec: mkFunctor (mkSource name spec)) data.pins
+ else
+ throw "Unsupported format version ${toString version} in sources.json. Try running `npins upgrade`"
+)
diff --git a/npins/sources.json b/npins/sources.json
index 7ed749b7..1e498aa4 100644
--- a/npins/sources.json
+++ b/npins/sources.json
@@ -1,11 +1,24 @@
{
"pins": {
+ "mobile-core-tools": {
+ "type": "Git",
+ "repository": {
+ "type": "GitHub",
+ "owner": "zw3rk",
+ "repo": "mobile-core-tools"
+ },
+ "branch": "master",
+ "submodules": false,
+ "revision": "90e0a52893288bfe85e5ed6bff9cee077e3d18c7",
+ "url": "https://github.com/zw3rk/mobile-core-tools/archive/90e0a52893288bfe85e5ed6bff9cee077e3d18c7.tar.gz",
+ "hash": "sha256-/1Eppd4g/30hU/LKG84VWOgjOfrWfesBqM7eNmnOf08="
+ },
"nixpkgs": {
"type": "Channel",
"name": "nixpkgs-unstable",
- "url": "https://releases.nixos.org/nixpkgs/nixpkgs-25.11pre891648.f6b44b240152/nixexprs.tar.xz",
- "hash": "0rljaahlkcrcjqd9sj5iyv9zng4yqns1215kanm7hi4w9gri0b74"
+ "url": "https://releases.nixos.org/nixpkgs/nixpkgs-26.05pre975217.5e11f7acce6c/nixexprs.tar.xz",
+ "hash": "sha256-avkT2TR2Wh/TQTysYGFOkGiF5+2R2nS7TZOfQ4omieQ="
}
},
- "version": 5
+ "version": 7
}
diff --git a/shell.nix b/shell.nix
index 0a680f57..74ff27da 100644
--- a/shell.nix
+++ b/shell.nix
@@ -3,7 +3,7 @@
pkgs ? import ./nix/pkgs.nix {},
}:
hpkgs.shellFor {
- packages = ps: [ ps."template-project" ];
+ packages = ps: [ ps."haskell-mobile-project" ];
withHoogle = false;
buildInputs = [
diff --git a/src/HaskellMobile.hs b/src/HaskellMobile.hs
new file mode 100644
index 00000000..35f9687b
--- /dev/null
+++ b/src/HaskellMobile.hs
@@ -0,0 +1,216 @@
+{-# LANGUAGE ForeignFunctionInterface #-}
+{-# LANGUAGE OverloadedStrings #-}
+module HaskellMobile
+ ( MobileApp(..)
+ , UserState(..)
+ , startMobileApp
+ -- FFI exports
+ , haskellGreet
+ , haskellRenderUI
+ , haskellOnUIEvent
+ , haskellOnLifecycle
+ , haskellOnPermissionResult
+ -- Error handling
+ , errorWidget
+ -- Re-exports from Lifecycle
+ , LifecycleEvent(..)
+ , MobileContext(..)
+ , defaultMobileContext
+ , loggingMobileContext
+ , platformLog
+ , newMobileContext
+ , freeMobileContext
+ -- Re-exports from AppContext
+ , AppContext(..)
+ , newAppContext
+ , freeAppContext
+ , derefAppContext
+ -- Re-exports from Locale
+ , Language(..)
+ , Locale(..)
+ , LocaleFailure(..)
+ , getSystemLocale
+ , parseLocale
+ , localeToText
+ , languageToCode
+ , languageFromCode
+ -- Re-exports from I18n
+ , Key(..)
+ , TranslateFailure(..)
+ , translate
+ -- Re-exports from Permission
+ , Permission(..)
+ , PermissionStatus(..)
+ , PermissionState(..)
+ , requestPermission
+ , checkPermission
+ )
+where
+
+import Control.Exception (SomeException, catch)
+import Data.IORef (readIORef, writeIORef)
+import Data.Text (pack)
+import Foreign.C.String (CString, newCString, peekCString)
+import Foreign.C.Types (CInt(..))
+import Foreign.Ptr (Ptr)
+import HaskellMobile.AppContext (AppContext(..), newAppContext, freeAppContext, derefAppContext)
+import HaskellMobile.Lifecycle
+ ( LifecycleEvent(..)
+ , MobileContext(..)
+ , defaultMobileContext
+ , loggingMobileContext
+ , platformLog
+ , newMobileContext
+ , freeMobileContext
+ , lifecycleFromInt
+ )
+import HaskellMobile.I18n (Key(..), TranslateFailure(..), translate)
+import HaskellMobile.Locale (Language(..), Locale(..), LocaleFailure(..), getSystemLocale, parseLocale, localeToText, languageToCode, languageFromCode)
+import HaskellMobile.Permission
+ ( Permission(..)
+ , PermissionStatus(..)
+ , PermissionState(..)
+ , requestPermission
+ , checkPermission
+ , dispatchPermissionResult
+ )
+import HaskellMobile.Render (renderWidget, dispatchEvent, dispatchTextEvent)
+import HaskellMobile.Types (MobileApp(..), UserState(..))
+import HaskellMobile.Widget (ButtonConfig(..), FontConfig(..), TextConfig(..), Widget(..))
+
+-- | Create an 'AppContext' from a 'MobileApp' and return it as a typed
+-- pointer suitable for the C FFI. This is the user-facing API: the user's
+-- @main@ calls this to initialise the framework.
+startMobileApp :: MobileApp -> IO (Ptr AppContext)
+startMobileApp = newAppContext
+
+-- | Wrap an IO action in a catch-all exception handler.
+-- On failure, logs the exception, overwrites the context's view
+-- with an error widget, and fires the user's 'onError' callback.
+withExceptionHandler :: Ptr AppContext -> IO () -> IO ()
+withExceptionHandler ctxPtr action =
+ catch action (handleException ctxPtr)
+
+-- | Handle an uncaught exception from an FFI entry point.
+-- Overwrites the context's view function with an error widget so
+-- that subsequent renders show the error on screen. The error widget
+-- includes a dismiss button that restores the original view.
+-- Also logs via 'platformLog' and best-effort fires 'onError'.
+handleException :: Ptr AppContext -> SomeException -> IO ()
+handleException ctxPtr exc = do
+ appCtx <- derefAppContext ctxPtr
+ originalView <- readIORef (acViewFunction appCtx)
+ writeIORef (acViewFunction appCtx)
+ (\_userState -> pure (errorWidget ctxPtr originalView exc))
+ platformLog ("Uncaught exception: " <> pack (show exc))
+ renderWidget (acRenderState appCtx)
+ (errorWidget ctxPtr originalView exc)
+ fireUserErrorCallback appCtx exc
+
+-- | Best-effort: read the context's 'onError' callback and fire it.
+-- Catches any secondary exception so we never crash in the error handler.
+fireUserErrorCallback :: AppContext -> SomeException -> IO ()
+fireUserErrorCallback appCtx exc =
+ catch
+ (onError (acMobileContext appCtx) exc)
+ (\secondaryExc ->
+ platformLog ("onError callback failed: " <> pack (show (secondaryExc :: SomeException))))
+
+-- | Render the current view: read the view function from AppContext and
+-- render its widget.
+renderView :: Ptr AppContext -> IO ()
+renderView ctxPtr = do
+ appCtx <- derefAppContext ctxPtr
+ viewFunction <- readIORef (acViewFunction appCtx)
+ let userState = UserState { userPermissionState = acPermissionState appCtx }
+ widget <- viewFunction userState
+ renderWidget (acRenderState appCtx) widget
+
+-- | A widget that displays an error message with a dismiss button.
+-- The dismiss button restores the original view via a closure.
+errorWidget :: Ptr AppContext -> (UserState -> IO Widget) -> SomeException -> Widget
+errorWidget ctxPtr originalView exc = Column
+ [ Text TextConfig
+ { tcLabel = "An error occurred"
+ , tcFontConfig = Just (FontConfig 20.0)
+ }
+ , Text TextConfig
+ { tcLabel = pack (show exc)
+ , tcFontConfig = Nothing
+ }
+ , Button ButtonConfig
+ { bcLabel = "Dismiss"
+ , bcAction = do
+ appCtx <- derefAppContext ctxPtr
+ writeIORef (acViewFunction appCtx) originalView
+ , bcFontConfig = Nothing
+ }
+ ]
+
+-- | Takes a name as CString, returns "Hello from Haskell, !" as CString.
+-- Caller is responsible for freeing the returned CString.
+haskellGreet :: CString -> IO CString
+haskellGreet cname = do
+ name <- peekCString cname
+ newCString ("Hello from Haskell, " ++ name ++ "!")
+
+foreign export ccall haskellGreet :: CString -> IO CString
+
+-- | Render the UI tree. Dereferences the context pointer to obtain the
+-- 'RenderState', reads the view function from 'AppContext'
+-- to get the widget description, then issues ui_* calls through the
+-- registered bridge callbacks. Catches exceptions and shows error widget.
+haskellRenderUI :: Ptr AppContext -> IO ()
+haskellRenderUI ctxPtr =
+ withExceptionHandler ctxPtr (renderView ctxPtr)
+
+foreign export ccall haskellRenderUI :: Ptr AppContext -> IO ()
+
+-- | Handle a UI event from native code. Dispatches the callback
+-- identified by @callbackId@, then re-renders the UI.
+haskellOnUIEvent :: Ptr AppContext -> CInt -> IO ()
+haskellOnUIEvent ctxPtr callbackId =
+ withExceptionHandler ctxPtr $ do
+ appCtx <- derefAppContext ctxPtr
+ dispatchEvent (acRenderState appCtx) (fromIntegral callbackId)
+ renderView ctxPtr
+
+foreign export ccall haskellOnUIEvent :: Ptr AppContext -> CInt -> IO ()
+
+-- | Handle a text change event from native code. Dispatches the callback
+-- identified by @callbackId@ with the new text value. Does NOT re-render
+-- to avoid EditText cursor/flicker issues on Android.
+haskellOnUITextChange :: Ptr AppContext -> CInt -> CString -> IO ()
+haskellOnUITextChange ctxPtr callbackId cstr =
+ withExceptionHandler ctxPtr $ do
+ appCtx <- derefAppContext ctxPtr
+ str <- peekCString cstr
+ dispatchTextEvent (acRenderState appCtx) (fromIntegral callbackId) (pack str)
+
+foreign export ccall haskellOnUITextChange :: Ptr AppContext -> CInt -> CString -> IO ()
+
+-- | Handle a permission result from native code. Dispatches to the
+-- callback registered by 'requestPermission'.
+haskellOnPermissionResult :: Ptr AppContext -> CInt -> CInt -> IO ()
+haskellOnPermissionResult ctxPtr requestId statusCode =
+ withExceptionHandler ctxPtr $ do
+ appCtx <- derefAppContext ctxPtr
+ dispatchPermissionResult (acPermissionState appCtx) requestId statusCode
+
+foreign export ccall haskellOnPermissionResult :: Ptr AppContext -> CInt -> CInt -> IO ()
+
+-- | FFI entry point called from platform code.
+-- Takes a context pointer and an event code.
+-- Dereferences as 'AppContext' and dispatches to the 'onLifecycle' callback
+-- of the inner 'MobileContext'. Unknown event codes are silently ignored.
+-- Catches exceptions and fires 'onError'.
+haskellOnLifecycle :: Ptr AppContext -> CInt -> IO ()
+haskellOnLifecycle ctxPtr code =
+ withExceptionHandler ctxPtr $
+ case lifecycleFromInt code of
+ Just event -> do
+ appCtx <- derefAppContext ctxPtr
+ onLifecycle (acMobileContext appCtx) event
+ Nothing -> pure ()
+
+foreign export ccall haskellOnLifecycle :: Ptr AppContext -> CInt -> IO ()
diff --git a/src/HaskellMobile/App.hs b/src/HaskellMobile/App.hs
new file mode 100644
index 00000000..540e2a58
--- /dev/null
+++ b/src/HaskellMobile/App.hs
@@ -0,0 +1,92 @@
+{-# LANGUAGE OverloadedStrings #-}
+-- | Default implementation of the mobile app.
+-- Provides 'loggingMobileContext' as the application context and a simple
+-- counter demo as the default UI.
+module HaskellMobile.App (mobileApp, scrollDemoApp, textInputDemoApp) where
+
+import Data.IORef (IORef, newIORef, readIORef, modifyIORef')
+import Data.Text qualified as Text
+import HaskellMobile.Types (MobileApp(..))
+import HaskellMobile.Lifecycle (loggingMobileContext)
+import HaskellMobile.Widget (ButtonConfig(..), Color(..), FontConfig(..), InputType(..), TextAlignment(..), TextConfig(..), TextInputConfig(..), Widget(..), WidgetStyle(..))
+import System.IO.Unsafe (unsafePerformIO)
+
+-- | The default mobile app — logs every lifecycle event and shows a counter.
+mobileApp :: MobileApp
+mobileApp = MobileApp
+ { maContext = loggingMobileContext
+ , maView = \_userState ->counterView
+ }
+
+-- | Global counter state for the demo app.
+counter :: IORef Int
+counter = unsafePerformIO (newIORef 0)
+{-# NOINLINE counter #-}
+
+-- | Counter demo: displays current count with +/- buttons.
+counterView :: IO Widget
+counterView = do
+ n <- readIORef counter
+ pure $ Column
+ [ Styled (WidgetStyle (Just 16.0) (Just AlignCenter) (Just (Color 255 0 0 255)) (Just (Color 0 255 0 255)))
+ (Text TextConfig
+ { tcLabel = "Counter: " <> Text.pack (show n)
+ , tcFontConfig = Just (FontConfig 24.0)
+ })
+ , Row [ Button ButtonConfig
+ { bcLabel = "+", bcAction = modifyIORef' counter (+ 1), bcFontConfig = Nothing }
+ , Button ButtonConfig
+ { bcLabel = "-", bcAction = modifyIORef' counter (subtract 1), bcFontConfig = Nothing }
+ ]
+ ]
+
+-- | Scroll demo: 20 text items + a button at the bottom inside a ScrollView.
+-- Used by integration tests to verify the ScrollView FFI binding end-to-end.
+scrollDemoApp :: MobileApp
+scrollDemoApp = MobileApp
+ { maContext = loggingMobileContext
+ , maView = \_userState ->scrollDemoView
+ }
+
+-- | Builds a ScrollView containing 20 text items followed by a button.
+-- The button's callback ID is 0 (first registered), matching the --autotest dispatch.
+scrollDemoView :: IO Widget
+scrollDemoView = pure $ ScrollView
+ [ Column
+ ( map (\itemNumber -> Text TextConfig
+ { tcLabel = "Item " <> Text.pack (show (itemNumber :: Int)), tcFontConfig = Nothing }) [1..20]
+ ++ [Button ButtonConfig
+ { bcLabel = "Reached Bottom", bcAction = pure (), bcFontConfig = Nothing }]
+ )
+ ]
+
+-- | TextInput demo: renders numeric and text inputs side by side.
+-- Used by integration tests to verify InputType FFI binding end-to-end.
+textInputDemoApp :: MobileApp
+textInputDemoApp = MobileApp
+ { maContext = loggingMobileContext
+ , maView = \_userState ->textInputDemoView
+ }
+
+-- | Builds a Column with a label and two TextInputs of different InputType.
+textInputDemoView :: IO Widget
+textInputDemoView = pure $ Column
+ [ Text TextConfig { tcLabel = "TextInput Demo", tcFontConfig = Nothing }
+ , TextInput TextInputConfig
+ { tiInputType = InputNumber
+ , tiHint = "enter weight (kg)"
+ , tiValue = ""
+ , tiOnChange = \_ -> pure ()
+ , tiFontConfig = Nothing
+ }
+ , TextInput TextInputConfig
+ { tiInputType = InputText
+ , tiHint = "enter name"
+ , tiValue = ""
+ , tiOnChange = \_ -> pure ()
+ , tiFontConfig = Nothing
+ }
+ ]
+
+
+
diff --git a/src/HaskellMobile/AppContext.hs b/src/HaskellMobile/AppContext.hs
new file mode 100644
index 00000000..87df93fe
--- /dev/null
+++ b/src/HaskellMobile/AppContext.hs
@@ -0,0 +1,58 @@
+-- | Internal context type that bundles a 'MobileContext' (user callbacks)
+-- with a 'RenderState' (UI callback registry), a 'PermissionState'
+-- (permission callback registry), and the current view function.
+-- Passed through the C FFI as a single 'StablePtr', eliminating the
+-- need for global mutable state.
+module HaskellMobile.AppContext
+ ( AppContext(..)
+ , newAppContext
+ , freeAppContext
+ , derefAppContext
+ )
+where
+
+import Data.IORef (IORef, newIORef, writeIORef)
+import Foreign.Ptr (Ptr, castPtr)
+import Foreign.StablePtr (StablePtr, castPtrToStablePtr, castStablePtrToPtr, newStablePtr, deRefStablePtr, freeStablePtr)
+import HaskellMobile.Lifecycle (MobileContext)
+import HaskellMobile.Permission (PermissionState(..), newPermissionState)
+import HaskellMobile.Render (RenderState, newRenderState)
+import HaskellMobile.Types (MobileApp(..), UserState(..))
+import HaskellMobile.Widget (Widget)
+
+-- | Combines user-supplied lifecycle callbacks with the rendering engine's
+-- mutable state, the permission callback registry, and the current view
+-- function. One of these is created per platform bridge session.
+data AppContext = AppContext
+ { acMobileContext :: MobileContext
+ , acRenderState :: RenderState
+ , acPermissionState :: PermissionState
+ , acViewFunction :: IORef (UserState -> IO Widget)
+ }
+
+-- | Create a fresh 'AppContext' from a 'MobileApp', allocating a new
+-- 'RenderState' and 'PermissionState' internally. Returns a typed pointer
+-- suitable for passing through the C FFI (C sees @void *@).
+newAppContext :: MobileApp -> IO (Ptr AppContext)
+newAppContext mobileApp = do
+ renderState <- newRenderState
+ permissionState <- newPermissionState
+ viewRef <- newIORef (maView mobileApp)
+ let appContext = AppContext
+ { acMobileContext = maContext mobileApp
+ , acRenderState = renderState
+ , acPermissionState = permissionState
+ , acViewFunction = viewRef
+ }
+ ptr <- castPtr . castStablePtrToPtr <$> newStablePtr appContext
+ -- Write the context pointer back so requestPermission can pass it to C.
+ writeIORef (psContextPtr permissionState) (castPtr ptr)
+ pure ptr
+
+-- | Release a pointer previously created by 'newAppContext'.
+freeAppContext :: Ptr AppContext -> IO ()
+freeAppContext ptr = freeStablePtr (castPtrToStablePtr (castPtr ptr) :: StablePtr AppContext)
+
+-- | Dereference a typed pointer back to an 'AppContext'.
+derefAppContext :: Ptr AppContext -> IO AppContext
+derefAppContext ptr = deRefStablePtr (castPtrToStablePtr (castPtr ptr))
diff --git a/src/HaskellMobile/I18n.hs b/src/HaskellMobile/I18n.hs
new file mode 100644
index 00000000..fa544729
--- /dev/null
+++ b/src/HaskellMobile/I18n.hs
@@ -0,0 +1,45 @@
+{-# LANGUAGE OverloadedStrings #-}
+module HaskellMobile.I18n
+ ( Key(..)
+ , TranslateFailure(..)
+ , translate
+ ) where
+
+import Data.Map.Strict (Map)
+import Data.Map.Strict qualified as Map
+import Data.Text (Text)
+import HaskellMobile.Locale (Locale(..))
+
+-- | Translation key. Newtype for type safety.
+newtype Key = Key { unKey :: Text }
+ deriving (Show, Eq, Ord)
+
+-- | Reasons a translation lookup can fail.
+data TranslateFailure
+ = LocaleNotFound Locale
+ -- ^ The translations map has no entry for this locale.
+ | KeyNotFound Locale Key
+ -- ^ The locale exists but does not contain this key.
+ deriving (Show, Eq)
+
+-- | Look up a translation key with fallback chain:
+--
+-- 1. Exact locale match (e.g., @\"nl-NL\"@)
+-- 2. Language-only match (e.g., @\"nl\"@)
+-- 3. Error describing which step failed
+translate :: Map Locale (Map Key Text) -> Locale -> Key -> Either TranslateFailure Text
+translate translations locale key =
+ case lookupKey translations locale key of
+ Right foundText -> Right foundText
+ Left _exactFailure ->
+ let fallbackLocale = locale { locRegion = Nothing }
+ in lookupKey translations fallbackLocale key
+
+lookupKey :: Map Locale (Map Key Text) -> Locale -> Key -> Either TranslateFailure Text
+lookupKey translations locale key =
+ case Map.lookup locale translations of
+ Nothing -> Left (LocaleNotFound locale)
+ Just keyMap ->
+ case Map.lookup key keyMap of
+ Nothing -> Left (KeyNotFound locale key)
+ Just value -> Right value
diff --git a/src/HaskellMobile/Lifecycle.hs b/src/HaskellMobile/Lifecycle.hs
new file mode 100644
index 00000000..18ce0dfb
--- /dev/null
+++ b/src/HaskellMobile/Lifecycle.hs
@@ -0,0 +1,92 @@
+{-# LANGUAGE ForeignFunctionInterface #-}
+{-# LANGUAGE OverloadedStrings #-}
+module HaskellMobile.Lifecycle
+ ( LifecycleEvent(..)
+ , lifecycleFromInt
+ , lifecycleToInt
+ , MobileContext(..)
+ , defaultMobileContext
+ , loggingMobileContext
+ , platformLog
+ , newMobileContext
+ , freeMobileContext
+ )
+where
+
+import Control.Exception (SomeException)
+import Data.Text (Text, pack, unpack)
+import Foreign.C.String (CString, withCString)
+import Foreign.C.Types (CInt(..))
+import Foreign.StablePtr (StablePtr, newStablePtr, freeStablePtr)
+
+-- | Lifecycle events that can be received from the host platform.
+-- Maps to Android Activity lifecycle and iOS ScenePhase transitions.
+data LifecycleEvent
+ = Create
+ | Start
+ | Resume
+ | Pause
+ | Stop
+ | Destroy
+ | LowMemory
+ deriving (Show, Eq, Ord, Enum, Bounded)
+
+-- | Convert a C int to a 'LifecycleEvent'. Returns 'Nothing' for unknown codes.
+lifecycleFromInt :: CInt -> Maybe LifecycleEvent
+lifecycleFromInt 0 = Just Create
+lifecycleFromInt 1 = Just Start
+lifecycleFromInt 2 = Just Resume
+lifecycleFromInt 3 = Just Pause
+lifecycleFromInt 4 = Just Stop
+lifecycleFromInt 5 = Just Destroy
+lifecycleFromInt 6 = Just LowMemory
+lifecycleFromInt _ = Nothing
+
+-- | Convert a 'LifecycleEvent' to its C int code (0--6).
+lifecycleToInt :: LifecycleEvent -> CInt
+lifecycleToInt Create = 0
+lifecycleToInt Start = 1
+lifecycleToInt Resume = 2
+lifecycleToInt Pause = 3
+lifecycleToInt Stop = 4
+lifecycleToInt Destroy = 5
+lifecycleToInt LowMemory = 6
+
+-- | Opaque context holding user-defined callbacks for mobile platform events.
+-- Passed through the C FFI as a 'StablePtr', so each platform bridge
+-- (or test) owns its own independent context — no global mutable state.
+data MobileContext = MobileContext
+ { onLifecycle :: LifecycleEvent -> IO ()
+ , onError :: SomeException -> IO ()
+ }
+
+-- | A no-op context. Suitable as a default when no callbacks are needed.
+-- Logs errors via 'platformLog' by default so they are not silently swallowed.
+defaultMobileContext :: MobileContext
+defaultMobileContext = MobileContext
+ { onLifecycle = \_ -> pure ()
+ , onError = \exc -> platformLog ("Error: " <> pack (show exc))
+ }
+
+foreign import ccall "haskellMobileLog" c_haskellMobileLog :: CString -> IO ()
+
+-- | Log a message using the platform-appropriate mechanism:
+-- Android logcat, Apple os_log, or stderr on desktop.
+platformLog :: Text -> IO ()
+platformLog msg = withCString (unpack msg) c_haskellMobileLog
+
+-- | A context that logs every lifecycle event via 'platformLog'.
+loggingMobileContext :: MobileContext
+loggingMobileContext = MobileContext
+ { onLifecycle = \event -> platformLog ("Lifecycle: " <> pack (show event))
+ , onError = \exc -> platformLog ("Error: " <> pack (show exc))
+ }
+
+-- | Pin a 'MobileContext' on the GHC heap and return a 'StablePtr' to it.
+-- The caller must eventually call 'freeMobileContext' to release the pointer.
+newMobileContext :: MobileContext -> IO (StablePtr MobileContext)
+newMobileContext = newStablePtr
+
+-- | Release a 'StablePtr' previously created by 'newMobileContext'.
+freeMobileContext :: StablePtr MobileContext -> IO ()
+freeMobileContext = freeStablePtr
diff --git a/src/HaskellMobile/Locale.hs b/src/HaskellMobile/Locale.hs
new file mode 100644
index 00000000..65568314
--- /dev/null
+++ b/src/HaskellMobile/Locale.hs
@@ -0,0 +1,268 @@
+{-# LANGUAGE ForeignFunctionInterface #-}
+{-# LANGUAGE OverloadedStrings #-}
+module HaskellMobile.Locale
+ ( Language(..)
+ , Locale(..)
+ , LocaleFailure(..)
+ , getSystemLocale
+ , parseLocale
+ , localeToText
+ , languageToCode
+ , languageFromCode
+ , haskellLogLocale
+ ) where
+
+import Data.Char (isAlpha, isDigit, toUpper)
+import Data.Map.Strict (Map)
+import Data.Map.Strict qualified as Map
+import Data.Text (Text)
+import Data.Text qualified as Text
+import Foreign.C.String (CString, peekCString)
+import HaskellMobile.Lifecycle (platformLog)
+
+-- | ISO 639-1 language codes as a sum type.
+data Language
+ = Af -- ^ Afrikaans
+ | Am -- ^ Amharic
+ | Ar -- ^ Arabic
+ | Az -- ^ Azerbaijani
+ | Be -- ^ Belarusian
+ | Bg -- ^ Bulgarian
+ | Bn -- ^ Bengali
+ | Bs -- ^ Bosnian
+ | Ca -- ^ Catalan
+ | Cs -- ^ Czech
+ | Cy -- ^ Welsh
+ | Da -- ^ Danish
+ | De -- ^ German
+ | El -- ^ Greek
+ | En -- ^ English
+ | Es -- ^ Spanish
+ | Et -- ^ Estonian
+ | Eu -- ^ Basque
+ | Fa -- ^ Persian
+ | Fi -- ^ Finnish
+ | Fr -- ^ French
+ | Ga -- ^ Irish
+ | Gl -- ^ Galician
+ | Gu -- ^ Gujarati
+ | He -- ^ Hebrew
+ | Hi -- ^ Hindi
+ | Hr -- ^ Croatian
+ | Hu -- ^ Hungarian
+ | Hy -- ^ Armenian
+ | Id -- ^ Indonesian
+ | Is -- ^ Icelandic
+ | It -- ^ Italian
+ | Ja -- ^ Japanese
+ | Ka -- ^ Georgian
+ | Kk -- ^ Kazakh
+ | Km -- ^ Khmer
+ | Kn -- ^ Kannada
+ | Ko -- ^ Korean
+ | Lt -- ^ Lithuanian
+ | Lv -- ^ Latvian
+ | Mk -- ^ Macedonian
+ | Ml -- ^ Malayalam
+ | Mn -- ^ Mongolian
+ | Mr -- ^ Marathi
+ | Ms -- ^ Malay
+ | My -- ^ Burmese
+ | Nb -- ^ Norwegian Bokmal
+ | Ne -- ^ Nepali
+ | Nl -- ^ Dutch
+ | No -- ^ Norwegian
+ | Pa -- ^ Punjabi
+ | Pl -- ^ Polish
+ | Pt -- ^ Portuguese
+ | Ro -- ^ Romanian
+ | Ru -- ^ Russian
+ | Si -- ^ Sinhala
+ | Sk -- ^ Slovak
+ | Sl -- ^ Slovenian
+ | Sq -- ^ Albanian
+ | Sr -- ^ Serbian
+ | Sv -- ^ Swedish
+ | Sw -- ^ Swahili
+ | Ta -- ^ Tamil
+ | Te -- ^ Telugu
+ | Th -- ^ Thai
+ | Tl -- ^ Filipino
+ | Tr -- ^ Turkish
+ | Uk -- ^ Ukrainian
+ | Ur -- ^ Urdu
+ | Uz -- ^ Uzbek
+ | Vi -- ^ Vietnamese
+ | Zh -- ^ Chinese
+ | Zu -- ^ Zulu
+ deriving (Show, Eq, Ord, Bounded, Enum)
+
+-- | A parsed BCP-47 locale tag with language and optional region.
+data Locale = Locale
+ { locLanguage :: Language -- ^ ISO 639-1 language code
+ , locRegion :: Maybe Text -- ^ ISO 3166-1 region code: @\"US\"@, @\"NL\"@, @\"CN\"@
+ } deriving (Show, Eq, Ord)
+
+-- | Reasons a locale tag may fail to parse.
+data LocaleFailure
+ = EmptyLocaleTag
+ | InvalidLanguageCode Text
+ | InvalidRegionCode Text
+ | MalformedLocaleTag Text
+ deriving (Show, Eq)
+
+foreign import ccall "getSystemLocale" c_getSystemLocale :: IO CString
+
+-- | Query the system locale from the host platform.
+--
+-- * Android: @Locale.getDefault().toLanguageTag()@ (cached at JNI_OnLoad)
+-- * iOS: @NSLocale.currentLocale@ (queried at bridge setup)
+-- * Desktop: @LANG@ environment variable, defaults to @\"en\"@
+getSystemLocale :: IO Text
+getSystemLocale = do
+ cstr <- c_getSystemLocale
+ Text.pack <$> peekCString cstr
+
+-- | Render a 'Language' to its ISO 639-1 code.
+languageToCode :: Language -> Text
+languageToCode Af = "af"
+languageToCode Am = "am"
+languageToCode Ar = "ar"
+languageToCode Az = "az"
+languageToCode Be = "be"
+languageToCode Bg = "bg"
+languageToCode Bn = "bn"
+languageToCode Bs = "bs"
+languageToCode Ca = "ca"
+languageToCode Cs = "cs"
+languageToCode Cy = "cy"
+languageToCode Da = "da"
+languageToCode De = "de"
+languageToCode El = "el"
+languageToCode En = "en"
+languageToCode Es = "es"
+languageToCode Et = "et"
+languageToCode Eu = "eu"
+languageToCode Fa = "fa"
+languageToCode Fi = "fi"
+languageToCode Fr = "fr"
+languageToCode Ga = "ga"
+languageToCode Gl = "gl"
+languageToCode Gu = "gu"
+languageToCode He = "he"
+languageToCode Hi = "hi"
+languageToCode Hr = "hr"
+languageToCode Hu = "hu"
+languageToCode Hy = "hy"
+languageToCode Id = "id"
+languageToCode Is = "is"
+languageToCode It = "it"
+languageToCode Ja = "ja"
+languageToCode Ka = "ka"
+languageToCode Kk = "kk"
+languageToCode Km = "km"
+languageToCode Kn = "kn"
+languageToCode Ko = "ko"
+languageToCode Lt = "lt"
+languageToCode Lv = "lv"
+languageToCode Mk = "mk"
+languageToCode Ml = "ml"
+languageToCode Mn = "mn"
+languageToCode Mr = "mr"
+languageToCode Ms = "ms"
+languageToCode My = "my"
+languageToCode Nb = "nb"
+languageToCode Ne = "ne"
+languageToCode Nl = "nl"
+languageToCode No = "no"
+languageToCode Pa = "pa"
+languageToCode Pl = "pl"
+languageToCode Pt = "pt"
+languageToCode Ro = "ro"
+languageToCode Ru = "ru"
+languageToCode Si = "si"
+languageToCode Sk = "sk"
+languageToCode Sl = "sl"
+languageToCode Sq = "sq"
+languageToCode Sr = "sr"
+languageToCode Sv = "sv"
+languageToCode Sw = "sw"
+languageToCode Ta = "ta"
+languageToCode Te = "te"
+languageToCode Th = "th"
+languageToCode Tl = "tl"
+languageToCode Tr = "tr"
+languageToCode Uk = "uk"
+languageToCode Ur = "ur"
+languageToCode Uz = "uz"
+languageToCode Vi = "vi"
+languageToCode Zh = "zh"
+languageToCode Zu = "zu"
+
+-- | Parse a lowercase ISO 639-1 code into a 'Language'.
+languageFromCode :: Text -> Maybe Language
+languageFromCode code = Map.lookup (Text.toLower code) codeToLanguageMap
+
+-- | Lookup table built once from the complete 'Language' enumeration.
+codeToLanguageMap :: Map Text Language
+codeToLanguageMap =
+ Map.fromList [(languageToCode lang, lang) | lang <- [minBound .. maxBound]]
+
+-- | Parse a BCP-47 locale tag like @\"en\"@, @\"en-US\"@, @\"nl-NL\"@.
+--
+-- Splits on @\'-\'@ or @\'_\'@, validates language (2-letter ISO 639-1)
+-- and optional region (2 uppercase alpha or 3 digits).
+-- Language is looked up in the 'Language' enum, region is normalised to uppercase.
+parseLocale :: Text -> Either LocaleFailure Locale
+parseLocale tag
+ | Text.null tag = Left EmptyLocaleTag
+ | otherwise =
+ case splitLocaleTag tag of
+ [rawLang] ->
+ case languageFromCode rawLang of
+ Nothing -> Left (InvalidLanguageCode rawLang)
+ Just lang -> Right (Locale lang Nothing)
+ [rawLang, rawRegion] ->
+ case languageFromCode rawLang of
+ Nothing -> Left (InvalidLanguageCode rawLang)
+ Just lang ->
+ case validateRegion rawRegion of
+ Left failure -> Left failure
+ Right region -> Right (Locale lang (Just region))
+ _ -> Left (MalformedLocaleTag tag)
+
+-- | Render a 'Locale' back to its BCP-47 text form.
+localeToText :: Locale -> Text
+localeToText (Locale lang Nothing) = languageToCode lang
+localeToText (Locale lang (Just region)) = languageToCode lang <> "-" <> region
+
+-- | Log the detected system locale. Called from platform bridges during init.
+haskellLogLocale :: IO ()
+haskellLogLocale = do
+ raw <- getSystemLocale
+ platformLog ("Locale raw: " <> raw)
+ case parseLocale raw of
+ Right locale -> platformLog ("Locale parsed: " <> localeToText locale)
+ Left failure -> platformLog ("Locale parse failed: " <> Text.pack (show failure))
+
+foreign export ccall haskellLogLocale :: IO ()
+
+-- Internal helpers
+
+-- | Split a locale tag on @\'-\'@ or @\'_\'@ into at most 2 parts
+-- (language and optional region). Extra segments are dropped to keep
+-- the result simple — we only care about language + region.
+splitLocaleTag :: Text -> [Text]
+splitLocaleTag input =
+ let parts = Text.split (\c -> c == '-' || c == '_') input
+ in take 2 (filter (not . Text.null) parts)
+
+-- | Validate and normalise a region code.
+-- Accepts 2 alpha characters (normalised to uppercase) or 3 digits.
+validateRegion :: Text -> Either LocaleFailure Text
+validateRegion raw
+ | Text.length raw == 2 && Text.all isAlpha raw =
+ Right (Text.map toUpper raw)
+ | Text.length raw == 3 && Text.all isDigit raw =
+ Right raw
+ | otherwise = Left (InvalidRegionCode raw)
diff --git a/src/HaskellMobile/Permission.hs b/src/HaskellMobile/Permission.hs
new file mode 100644
index 00000000..f53e0a64
--- /dev/null
+++ b/src/HaskellMobile/Permission.hs
@@ -0,0 +1,140 @@
+{-# LANGUAGE ForeignFunctionInterface #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+-- | Runtime permission management for mobile platforms.
+--
+-- Provides a callback-based API for requesting and checking dangerous
+-- permissions at runtime. On desktop (no platform bridge registered)
+-- the C stub auto-grants every permission so that @cabal test@ works
+-- without native code.
+--
+-- The callback registry follows the same sequential 'IORef' 'Int32'
+-- pattern used by "HaskellMobile.Render".
+module HaskellMobile.Permission
+ ( Permission(..)
+ , PermissionStatus(..)
+ , PermissionState(..)
+ , newPermissionState
+ , permissionToInt
+ , permissionStatusFromInt
+ , requestPermission
+ , checkPermission
+ , dispatchPermissionResult
+ )
+where
+
+import Data.IORef (IORef, newIORef, readIORef, writeIORef, modifyIORef')
+import Data.Int (Int32)
+import Data.IntMap.Strict (IntMap)
+import Data.IntMap.Strict qualified as IntMap
+import Foreign.C.Types (CInt(..))
+import Foreign.Ptr (Ptr, nullPtr)
+import System.IO (hPutStrLn, stderr)
+
+-- | Dangerous permissions that require runtime consent on mobile.
+data Permission
+ = PermissionLocation
+ | PermissionBluetooth
+ | PermissionCamera
+ | PermissionMicrophone
+ | PermissionContacts
+ | PermissionStorage
+ deriving (Show, Eq, Ord, Enum, Bounded)
+
+-- | Result of a permission request or check.
+data PermissionStatus
+ = PermissionGranted
+ | PermissionDenied
+ deriving (Show, Eq, Ord, Enum, Bounded)
+
+-- | Mutable state for the permission callback registry.
+-- Holds pending callbacks, the next request ID counter, and
+-- the opaque context pointer passed to the C bridge for dispatch.
+data PermissionState = PermissionState
+ { psCallbacks :: IORef (IntMap (PermissionStatus -> IO ()))
+ -- ^ Map from requestId -> result callback
+ , psNextId :: IORef Int32
+ -- ^ Next available request ID
+ , psContextPtr :: IORef (Ptr ())
+ -- ^ Opaque context pointer passed to the C bridge.
+ -- Set by 'AppContext.newAppContext' after the 'StablePtr' is created.
+ }
+
+-- | Create a fresh 'PermissionState' with no pending callbacks.
+-- The context pointer is initially null and must be set via
+-- 'psContextPtr' before calling 'requestPermission'.
+newPermissionState :: IO PermissionState
+newPermissionState = do
+ callbacks <- newIORef IntMap.empty
+ nextId <- newIORef 0
+ contextPtr <- newIORef nullPtr
+ pure PermissionState
+ { psCallbacks = callbacks
+ , psNextId = nextId
+ , psContextPtr = contextPtr
+ }
+
+-- | Convert a 'Permission' to its C bridge integer code.
+-- Must match the @PERMISSION_*@ constants in @PermissionBridge.h@.
+permissionToInt :: Permission -> CInt
+permissionToInt PermissionLocation = 0
+permissionToInt PermissionBluetooth = 1
+permissionToInt PermissionCamera = 2
+permissionToInt PermissionMicrophone = 3
+permissionToInt PermissionContacts = 4
+permissionToInt PermissionStorage = 5
+
+-- | Convert a C bridge status code to 'PermissionStatus'.
+-- Returns 'Nothing' for unknown codes.
+permissionStatusFromInt :: CInt -> Maybe PermissionStatus
+permissionStatusFromInt 0 = Just PermissionGranted
+permissionStatusFromInt 1 = Just PermissionDenied
+permissionStatusFromInt _ = Nothing
+
+-- | Request a runtime permission. Registers @callback@ and calls the
+-- C bridge asynchronously. The callback fires when the platform
+-- responds (or synchronously on desktop via the auto-grant stub).
+-- The opaque context pointer stored in 'psContextPtr' is threaded
+-- through to the C bridge so it can dispatch results back.
+requestPermission :: PermissionState -> Permission -> (PermissionStatus -> IO ()) -> IO ()
+requestPermission permissionState permission callback = do
+ requestId <- readIORef (psNextId permissionState)
+ modifyIORef' (psCallbacks permissionState) (IntMap.insert (fromIntegral requestId) callback)
+ writeIORef (psNextId permissionState) (requestId + 1)
+ ctx <- readIORef (psContextPtr permissionState)
+ c_permissionRequest ctx (permissionToInt permission) (fromIntegral requestId)
+
+-- | Check whether a permission is currently granted (synchronous).
+checkPermission :: Permission -> IO PermissionStatus
+checkPermission permission = do
+ result <- c_permissionCheck (permissionToInt permission)
+ case permissionStatusFromInt result of
+ Just status -> pure status
+ Nothing -> do
+ hPutStrLn stderr $ "checkPermission: unknown status code " ++ show result
+ pure PermissionDenied
+
+-- | Dispatch a permission result from the platform back to the
+-- registered Haskell callback. Removes the callback after firing.
+-- Unknown request IDs or status codes are silently logged to stderr.
+dispatchPermissionResult :: PermissionState -> CInt -> CInt -> IO ()
+dispatchPermissionResult permissionState requestId statusCode =
+ case permissionStatusFromInt statusCode of
+ Nothing -> hPutStrLn stderr $
+ "dispatchPermissionResult: unknown status code " ++ show statusCode
+ Just status -> do
+ callbacks <- readIORef (psCallbacks permissionState)
+ case IntMap.lookup (fromIntegral requestId) callbacks of
+ Nothing -> hPutStrLn stderr $
+ "dispatchPermissionResult: unknown request ID " ++ show requestId
+ Just callback -> do
+ modifyIORef' (psCallbacks permissionState) (IntMap.delete (fromIntegral requestId))
+ callback status
+
+-- | FFI import: request a permission via the C bridge.
+-- Takes an opaque context pointer, permission code, and request ID.
+foreign import ccall "permission_request"
+ c_permissionRequest :: Ptr () -> CInt -> CInt -> IO ()
+
+-- | FFI import: check a permission via the C bridge.
+foreign import ccall "permission_check"
+ c_permissionCheck :: CInt -> IO CInt
diff --git a/src/HaskellMobile/Render.hs b/src/HaskellMobile/Render.hs
new file mode 100644
index 00000000..a7225a6a
--- /dev/null
+++ b/src/HaskellMobile/Render.hs
@@ -0,0 +1,196 @@
+{-# LANGUAGE ImportQualifiedPost #-}
+-- | Rendering engine that converts a 'Widget' tree into native UI
+-- via the C bridge.
+--
+-- Uses a full clear-and-rebuild strategy on every render.
+-- Maintains callback registries so native button presses and text
+-- changes can be dispatched back to Haskell 'IO' actions.
+module HaskellMobile.Render
+ ( RenderState(..)
+ , newRenderState
+ , renderWidget
+ , dispatchEvent
+ , dispatchTextEvent
+ )
+where
+
+import Data.IORef (IORef, newIORef, readIORef, writeIORef, modifyIORef')
+import Data.Int (Int32)
+import Data.IntMap.Strict (IntMap)
+import Data.IntMap.Strict qualified as IntMap
+import Data.Text (Text, pack)
+import HaskellMobile.Widget (ButtonConfig(..), FontConfig(..), ImageConfig(..), ImageSource(..), InputType(..), ResourceName(..), ScaleType(..), TextAlignment(..), TextConfig(..), TextInputConfig(..), Widget(..), WidgetStyle(..), colorToHex)
+import HaskellMobile.UIBridge qualified as Bridge
+import System.IO (hPutStrLn, stderr)
+
+-- | Mutable state for the rendering engine.
+-- Holds the callback registries and next callback ID counter.
+data RenderState = RenderState
+ { rsCallbacks :: IORef (IntMap (IO ()))
+ -- ^ Map from callbackId -> IO action (for clicks)
+ , rsTextCallbacks :: IORef (IntMap (Text -> IO ()))
+ -- ^ Map from callbackId -> text change handler
+ , rsNextId :: IORef Int32
+ -- ^ Next available callback ID
+ }
+
+-- | Create a fresh 'RenderState' with no registered callbacks.
+newRenderState :: IO RenderState
+newRenderState = do
+ callbacks <- newIORef IntMap.empty
+ textCallbacks <- newIORef IntMap.empty
+ nextId <- newIORef 0
+ pure RenderState
+ { rsCallbacks = callbacks
+ , rsTextCallbacks = textCallbacks
+ , rsNextId = nextId
+ }
+
+-- | Register a click callback and return its ID.
+registerCallback :: RenderState -> IO () -> IO Int32
+registerCallback rs action = do
+ cid <- readIORef (rsNextId rs)
+ modifyIORef' (rsCallbacks rs) (IntMap.insert (fromIntegral cid) action)
+ writeIORef (rsNextId rs) (cid + 1)
+ pure cid
+
+-- | Register a text-change callback and return its ID.
+registerTextCallback :: RenderState -> (Text -> IO ()) -> IO Int32
+registerTextCallback rs action = do
+ cid <- readIORef (rsNextId rs)
+ modifyIORef' (rsTextCallbacks rs) (IntMap.insert (fromIntegral cid) action)
+ writeIORef (rsNextId rs) (cid + 1)
+ pure cid
+
+-- | Reset both callback registries (called before each re-render).
+resetCallbacks :: RenderState -> IO ()
+resetCallbacks rs = do
+ writeIORef (rsCallbacks rs) IntMap.empty
+ writeIORef (rsTextCallbacks rs) IntMap.empty
+ writeIORef (rsNextId rs) 0
+
+-- | Map an 'InputType' to the numeric code sent to the platform bridge.
+inputTypeToInt :: InputType -> Int32
+inputTypeToInt InputText = 0
+inputTypeToInt InputNumber = 1
+
+-- | Apply a 'FontConfig' to a rendered node if present.
+applyFontConfig :: Int32 -> Maybe FontConfig -> IO ()
+applyFontConfig nodeId (Just (FontConfig size)) =
+ Bridge.setNumProp nodeId Bridge.PropFontSize size
+applyFontConfig _nodeId Nothing = pure ()
+
+-- | Render a single 'Widget' node, returning its native node ID.
+renderNode :: RenderState -> Widget -> IO Int32
+renderNode _rs (Text config) = do
+ nodeId <- Bridge.createNode Bridge.NodeText
+ Bridge.setStrProp nodeId Bridge.PropText (tcLabel config)
+ applyFontConfig nodeId (tcFontConfig config)
+ pure nodeId
+renderNode rs (Button config) = do
+ nodeId <- Bridge.createNode Bridge.NodeButton
+ Bridge.setStrProp nodeId Bridge.PropText (bcLabel config)
+ callbackId <- registerCallback rs (bcAction config)
+ Bridge.setHandler nodeId Bridge.EventClick callbackId
+ applyFontConfig nodeId (bcFontConfig config)
+ pure nodeId
+renderNode rs (TextInput config) = do
+ nodeId <- Bridge.createNode Bridge.NodeTextInput
+ Bridge.setStrProp nodeId Bridge.PropText (tiValue config)
+ Bridge.setStrProp nodeId Bridge.PropHint (tiHint config)
+ Bridge.setNumProp nodeId Bridge.PropInputType (fromIntegral (inputTypeToInt (tiInputType config)))
+ callbackId <- registerTextCallback rs (tiOnChange config)
+ Bridge.setHandler nodeId Bridge.EventTextChange callbackId
+ applyFontConfig nodeId (tiFontConfig config)
+ pure nodeId
+renderNode rs (Column children) = do
+ nodeId <- Bridge.createNode Bridge.NodeColumn
+ renderChildren rs nodeId children
+ pure nodeId
+renderNode rs (Row children) = do
+ nodeId <- Bridge.createNode Bridge.NodeRow
+ renderChildren rs nodeId children
+ pure nodeId
+renderNode rs (ScrollView children) = do
+ nodeId <- Bridge.createNode Bridge.NodeScrollView
+ renderChildren rs nodeId children
+ pure nodeId
+renderNode _rs (Image config) = do
+ nodeId <- Bridge.createNode Bridge.NodeImage
+ case icSource config of
+ ImageResource (ResourceName name) -> Bridge.setStrProp nodeId Bridge.PropImageResource name
+ ImageData bytes -> Bridge.setImageData nodeId bytes
+ ImageFile path -> Bridge.setStrProp nodeId Bridge.PropImageFile (pack path)
+ Bridge.setNumProp nodeId Bridge.PropScaleType (scaleTypeToDouble (icScaleType config))
+ pure nodeId
+renderNode rs (Styled style child) = do
+ nodeId <- renderNode rs child
+ applyStyle nodeId style
+ pure nodeId
+
+-- | Render a list of children and add them to a parent container.
+renderChildren :: RenderState -> Int32 -> [Widget] -> IO ()
+renderChildren rs parentId children =
+ mapM_ (\child -> do
+ childId <- renderNode rs child
+ Bridge.addChild parentId childId
+ ) children
+
+-- | Map a 'ScaleType' to the numeric code sent to the platform bridge.
+scaleTypeToDouble :: ScaleType -> Double
+scaleTypeToDouble ScaleFit = 0
+scaleTypeToDouble ScaleFill = 1
+scaleTypeToDouble ScaleNone = 2
+
+-- | Map a 'TextAlignment' to the numeric code sent to the platform bridge.
+textAlignToDouble :: TextAlignment -> Double
+textAlignToDouble AlignStart = 0
+textAlignToDouble AlignCenter = 1
+textAlignToDouble AlignEnd = 2
+
+-- | Apply 'WidgetStyle' overrides to a rendered node by calling
+-- 'Bridge.setNumProp' / 'Bridge.setStrProp' for each 'Just' field.
+applyStyle :: Int32 -> WidgetStyle -> IO ()
+applyStyle nodeId style = do
+ case wsPadding style of
+ Just padding -> Bridge.setNumProp nodeId Bridge.PropPadding padding
+ Nothing -> pure ()
+ case wsTextAlign style of
+ Just alignment -> Bridge.setNumProp nodeId Bridge.PropGravity (textAlignToDouble alignment)
+ Nothing -> pure ()
+ case wsTextColor style of
+ Just color -> Bridge.setStrProp nodeId Bridge.PropColor (colorToHex color)
+ Nothing -> pure ()
+ case wsBackgroundColor style of
+ Just color -> Bridge.setStrProp nodeId Bridge.PropBgColor (colorToHex color)
+ Nothing -> pure ()
+
+-- | Full render: clear the screen, reset callbacks, build the widget
+-- tree, and set the root node.
+renderWidget :: RenderState -> Widget -> IO ()
+renderWidget rs widget = do
+ Bridge.clear
+ resetCallbacks rs
+ rootId <- renderNode rs widget
+ Bridge.setRoot rootId
+
+-- | Dispatch a native click event to the registered Haskell callback.
+-- Logs an error to stderr if the callbackId is not found.
+dispatchEvent :: RenderState -> Int32 -> IO ()
+dispatchEvent rs callbackId = do
+ callbacks <- readIORef (rsCallbacks rs)
+ case IntMap.lookup (fromIntegral callbackId) callbacks of
+ Just action -> action
+ Nothing -> hPutStrLn stderr $
+ "dispatchEvent: unknown callback ID " ++ show callbackId
+
+-- | Dispatch a native text-change event to the registered Haskell callback.
+-- Does NOT trigger a re-render (avoids EditText flicker on Android).
+-- Logs an error to stderr if the callbackId is not found.
+dispatchTextEvent :: RenderState -> Int32 -> Text -> IO ()
+dispatchTextEvent rs callbackId newText = do
+ callbacks <- readIORef (rsTextCallbacks rs)
+ case IntMap.lookup (fromIntegral callbackId) callbacks of
+ Just action -> action newText
+ Nothing -> hPutStrLn stderr $
+ "dispatchTextEvent: unknown callback ID " ++ show callbackId
diff --git a/src/HaskellMobile/Types.hs b/src/HaskellMobile/Types.hs
new file mode 100644
index 00000000..84ce34b1
--- /dev/null
+++ b/src/HaskellMobile/Types.hs
@@ -0,0 +1,28 @@
+-- | Core types for the mobile app framework.
+-- Separated from "HaskellMobile" so that downstream modules
+-- (e.g. "HaskellMobile.App") can import 'MobileApp' without
+-- creating an import cycle through the main facade.
+module HaskellMobile.Types
+ ( MobileApp(..)
+ , UserState(..)
+ )
+where
+
+import HaskellMobile.Lifecycle (MobileContext)
+import HaskellMobile.Permission (PermissionState)
+import HaskellMobile.Widget (Widget)
+
+-- | State made available to the view function by the framework.
+-- Contains handles to platform subsystems that the user's UI code
+-- may need (e.g. requesting permissions). Extended as the framework
+-- gains new capabilities.
+data UserState = UserState
+ { userPermissionState :: PermissionState
+ }
+
+-- | Application definition record. Downstream apps create one of these
+-- and pass it to 'startMobileApp'.
+data MobileApp = MobileApp
+ { maContext :: MobileContext
+ , maView :: UserState -> IO Widget
+ }
diff --git a/src/HaskellMobile/UIBridge.hs b/src/HaskellMobile/UIBridge.hs
new file mode 100644
index 00000000..5d97db50
--- /dev/null
+++ b/src/HaskellMobile/UIBridge.hs
@@ -0,0 +1,157 @@
+{-# LANGUAGE ForeignFunctionInterface #-}
+-- | Low-level FFI bindings to the C UI bridge (@cbits/ui_bridge.c@).
+--
+-- These functions delegate to platform-native implementations on
+-- Android/iOS and fall back to stderr stubs on desktop.
+module HaskellMobile.UIBridge
+ ( NodeType(..)
+ , nodeTypeToInt
+ , PropId(..)
+ , propIdToInt
+ , EventType(..)
+ , eventTypeToInt
+ , createNode
+ , setStrProp
+ , setNumProp
+ , setImageData
+ , setHandler
+ , addChild
+ , removeChild
+ , destroyNode
+ , setRoot
+ , clear
+ )
+where
+
+import Data.ByteString (ByteString)
+import Data.ByteString qualified as BS
+import Data.Int (Int32)
+import Data.Text (Text, unpack)
+import Data.Word (Word8)
+import Foreign.C.String (CString, withCString)
+import Foreign.C.Types (CInt(..), CDouble(..))
+import Foreign.Ptr (Ptr, castPtr)
+
+-- | Widget node types corresponding to @UI_NODE_*@ in @UIBridge.h@.
+data NodeType
+ = NodeText
+ | NodeButton
+ | NodeColumn
+ | NodeRow
+ | NodeTextInput
+ | NodeScrollView
+ | NodeImage
+ deriving (Show, Eq, Enum, Bounded)
+
+-- | Map a 'NodeType' to its C integer code.
+nodeTypeToInt :: NodeType -> Int32
+nodeTypeToInt NodeText = 0
+nodeTypeToInt NodeButton = 1
+nodeTypeToInt NodeColumn = 2
+nodeTypeToInt NodeRow = 3
+nodeTypeToInt NodeTextInput = 4
+nodeTypeToInt NodeScrollView = 5
+nodeTypeToInt NodeImage = 6
+
+-- | Property identifiers for 'setStrProp' and 'setNumProp'.
+data PropId
+ = PropText
+ | PropColor
+ | PropHint
+ | PropBgColor
+ | PropFontSize
+ | PropPadding
+ | PropInputType
+ | PropGravity
+ | PropImageResource
+ | PropImageFile
+ | PropScaleType
+ deriving (Show, Eq, Enum, Bounded)
+
+-- | Map a 'PropId' to its C integer code.
+propIdToInt :: PropId -> Int32
+propIdToInt PropText = 0
+propIdToInt PropColor = 1
+propIdToInt PropHint = 2
+propIdToInt PropBgColor = 3
+propIdToInt PropImageResource = 4
+propIdToInt PropImageFile = 5
+propIdToInt PropFontSize = 0
+propIdToInt PropPadding = 1
+propIdToInt PropInputType = 2
+propIdToInt PropGravity = 3
+propIdToInt PropScaleType = 4
+
+-- | Event types corresponding to @UI_EVENT_*@ in @UIBridge.h@.
+data EventType
+ = EventClick
+ | EventTextChange
+ deriving (Show, Eq, Enum, Bounded)
+
+-- | Map an 'EventType' to its C integer code.
+eventTypeToInt :: EventType -> Int32
+eventTypeToInt EventClick = 0
+eventTypeToInt EventTextChange = 1
+
+-- Raw FFI imports
+foreign import ccall "ui_create_node" c_createNode :: CInt -> IO CInt
+foreign import ccall "ui_set_str_prop" c_setStrProp :: CInt -> CInt -> CString -> IO ()
+foreign import ccall "ui_set_num_prop" c_setNumProp :: CInt -> CInt -> CDouble -> IO ()
+foreign import ccall "ui_set_image_data" c_setImageData :: CInt -> Ptr Word8 -> CInt -> IO ()
+foreign import ccall "ui_set_handler" c_setHandler :: CInt -> CInt -> CInt -> IO ()
+foreign import ccall "ui_add_child" c_addChild :: CInt -> CInt -> IO ()
+foreign import ccall "ui_remove_child" c_removeChild :: CInt -> CInt -> IO ()
+foreign import ccall "ui_destroy_node" c_destroyNode :: CInt -> IO ()
+foreign import ccall "ui_set_root" c_setRoot :: CInt -> IO ()
+foreign import ccall "ui_clear" c_clear :: IO ()
+
+-- | Create a native node of the given type. Returns an opaque node ID.
+createNode :: NodeType -> IO Int32
+createNode nt = fromIntegral <$> c_createNode (fromIntegral (nodeTypeToInt nt))
+
+-- | Set a string property on a node.
+setStrProp :: Int32 -> PropId -> Text -> IO ()
+setStrProp nodeId propId value =
+ withCString (unpack value) $ \cstr ->
+ c_setStrProp (fromIntegral nodeId) (fromIntegral (propIdToInt propId)) cstr
+
+-- | Set a numeric property on a node.
+setNumProp :: Int32 -> PropId -> Double -> IO ()
+setNumProp nodeId propId value =
+ c_setNumProp (fromIntegral nodeId) (fromIntegral (propIdToInt propId)) (realToFrac value)
+
+-- | Set raw image data (PNG/JPEG bytes) on a node.
+setImageData :: Int32 -> ByteString -> IO ()
+setImageData nodeId imageBytes =
+ BS.useAsCStringLen imageBytes $ \(ptr, len) ->
+ c_setImageData (fromIntegral nodeId) (castPtr ptr) (fromIntegral len)
+
+-- | Register an event handler on a node. The @callbackId@ is looked up
+-- in the 'RenderState' callback registry when the event fires.
+setHandler :: Int32 -> EventType -> Int32 -> IO ()
+setHandler nodeId eventType callbackId =
+ c_setHandler (fromIntegral nodeId) (fromIntegral (eventTypeToInt eventType)) (fromIntegral callbackId)
+
+-- | Add a child node to a parent container.
+addChild :: Int32 -> Int32 -> IO ()
+addChild parentId childId =
+ c_addChild (fromIntegral parentId) (fromIntegral childId)
+
+-- | Remove a child node from a parent container.
+removeChild :: Int32 -> Int32 -> IO ()
+removeChild parentId childId =
+ c_removeChild (fromIntegral parentId) (fromIntegral childId)
+
+-- | Destroy a node and free its native resources.
+destroyNode :: Int32 -> IO ()
+destroyNode nodeId =
+ c_destroyNode (fromIntegral nodeId)
+
+-- | Set a node as the root of the display.
+setRoot :: Int32 -> IO ()
+setRoot nodeId =
+ c_setRoot (fromIntegral nodeId)
+
+-- | Clear all nodes (called before re-render).
+clear :: IO ()
+clear = c_clear
diff --git a/src/HaskellMobile/Widget.hs b/src/HaskellMobile/Widget.hs
new file mode 100644
index 00000000..628d5731
--- /dev/null
+++ b/src/HaskellMobile/Widget.hs
@@ -0,0 +1,193 @@
+{-# LANGUAGE ImportQualifiedPost #-}
+-- | Declarative UI widget ADT.
+--
+-- Pure data describing the UI tree. Rendering is handled by
+-- "HaskellMobile.Render", which traverses this tree and issues
+-- FFI calls to the platform bridge.
+module HaskellMobile.Widget
+ ( FontConfig(..)
+ , TextConfig(..)
+ , ButtonConfig(..)
+ , InputType(..)
+ , TextInputConfig(..)
+ , ScaleType(..)
+ , ResourceName(..)
+ , ImageSource(..)
+ , ImageConfig(..)
+ , Widget(..)
+ , WidgetStyle(..)
+ , TextAlignment(..)
+ , Color(..)
+ , colorFromText
+ , colorToHex
+ , defaultStyle
+ )
+where
+
+import Data.ByteString (ByteString)
+import Data.Char (digitToInt, isHexDigit, intToDigit)
+import Data.Text (Text)
+import Data.Text qualified as Text
+import Data.Word (Word8)
+
+-- | Font configuration for text-bearing widgets.
+-- Only 'Text', 'Button', and 'TextInput' can carry a 'FontConfig'.
+newtype FontConfig = FontConfig
+ { fontSize :: Double
+ -- ^ Font size in platform-native units (sp on Android, pt on iOS).
+ } deriving (Show, Eq)
+
+-- | Configuration for a read-only text label.
+data TextConfig = TextConfig
+ { tcLabel :: Text
+ -- ^ The text content to display.
+ , tcFontConfig :: Maybe FontConfig
+ -- ^ Optional font override.
+ } deriving (Show, Eq)
+
+-- | Configuration for a tappable button.
+data ButtonConfig = ButtonConfig
+ { bcLabel :: Text
+ -- ^ The button's label text.
+ , bcAction :: IO ()
+ -- ^ Callback fired when the button is tapped.
+ , bcFontConfig :: Maybe FontConfig
+ -- ^ Optional font override.
+ }
+
+-- | The kind of on-screen keyboard to show for a 'TextInput'.
+data InputType
+ = InputText -- ^ Default text keyboard.
+ | InputNumber -- ^ Numeric keyboard with decimal support.
+ deriving (Show, Eq)
+
+-- | Configuration for a text input field.
+-- Follows a controlled-component pattern: Haskell owns the state.
+data TextInputConfig = TextInputConfig
+ { tiInputType :: InputType
+ -- ^ Which on-screen keyboard to present.
+ , tiHint :: Text
+ -- ^ Placeholder text shown when the field is empty.
+ , tiValue :: Text
+ -- ^ Current text value (controlled by Haskell).
+ , tiOnChange :: Text -> IO ()
+ -- ^ Callback fired when the user edits the field.
+ , tiFontConfig :: Maybe FontConfig
+ -- ^ Optional font override.
+ }
+
+-- | Horizontal text alignment for text-bearing widgets.
+data TextAlignment
+ = AlignStart -- ^ Left-aligned (LTR) or right-aligned (RTL).
+ | AlignCenter -- ^ Centered horizontally.
+ | AlignEnd -- ^ Right-aligned (LTR) or left-aligned (RTL).
+ deriving (Show, Eq)
+
+-- | An RGBA color with 8-bit channels.
+data Color = Color
+ { colorRed :: Word8
+ , colorGreen :: Word8
+ , colorBlue :: Word8
+ , colorAlpha :: Word8
+ } deriving (Show, Eq)
+
+-- | Parse a hex color string: @"#RGB"@, @"#RRGGBB"@, or @"#AARRGGBB"@.
+-- Returns 'Nothing' on invalid input.
+colorFromText :: Text -> Maybe Color
+colorFromText raw = do
+ ('#', digits) <- Text.uncons raw
+ let hex = Text.unpack digits
+ if all isHexDigit hex
+ then case hex of
+ [r1, g1, b1] ->
+ let expand ch = let val = digitToInt ch in fromIntegral (val * 16 + val)
+ in Just (Color (expand r1) (expand g1) (expand b1) 255)
+ [r1, r2, g1, g2, b1, b2] ->
+ Just (Color (hexByte r1 r2) (hexByte g1 g2) (hexByte b1 b2) 255)
+ [a1, a2, r1, r2, g1, g2, b1, b2] ->
+ Just (Color (hexByte r1 r2) (hexByte g1 g2) (hexByte b1 b2) (hexByte a1 a2))
+ _ -> Nothing
+ else Nothing
+
+-- | Convert two hex characters to a Word8.
+hexByte :: Char -> Char -> Word8
+hexByte high low = fromIntegral (digitToInt high * 16 + digitToInt low)
+
+-- | Convert a 'Color' to a hex string in @"#AARRGGBB"@ format for the C bridge.
+colorToHex :: Color -> Text
+colorToHex (Color r g b a) = Text.pack ('#' : toHexByte a ++ toHexByte r ++ toHexByte g ++ toHexByte b)
+ where
+ toHexByte :: Word8 -> String
+ toHexByte byte = [intToDigit (fromIntegral byte `div` 16), intToDigit (fromIntegral byte `mod` 16)]
+
+-- | Visual style overrides for a widget node.
+-- Font size is not here — it belongs in the config records of
+-- text-bearing widgets ('TextConfig', 'ButtonConfig', 'TextInputConfig').
+data WidgetStyle = WidgetStyle
+ { wsPadding :: Maybe Double
+ -- ^ Uniform padding in platform-native units (px on Android, pt on iOS).
+ , wsTextAlign :: Maybe TextAlignment
+ -- ^ Horizontal text alignment override.
+ , wsTextColor :: Maybe Color
+ -- ^ Text color.
+ , wsBackgroundColor :: Maybe Color
+ -- ^ Background color.
+ } deriving (Show, Eq)
+
+-- | No style overrides — all fields are 'Nothing'.
+defaultStyle :: WidgetStyle
+defaultStyle = WidgetStyle
+ { wsPadding = Nothing
+ , wsTextAlign = Nothing
+ , wsTextColor = Nothing
+ , wsBackgroundColor = Nothing
+ }
+
+-- | How an image should be scaled within its bounds.
+data ScaleType
+ = ScaleFit -- ^ Scale to fit within bounds, preserving aspect ratio.
+ | ScaleFill -- ^ Scale to fill bounds, preserving aspect ratio (may crop).
+ | ScaleNone -- ^ No scaling; display at native resolution.
+ deriving (Show, Eq)
+
+-- | A platform resource name (e.g. @"ic_launcher"@, @"logo"@).
+-- Wraps a 'Text' value that identifies a drawable\/image resource
+-- bundled with the app. No compile-time guarantee that the resource
+-- exists — a missing resource shows \"Image not found\" placeholder text
+-- on iOS\/watchOS and an empty view on Android (with an error log).
+newtype ResourceName = ResourceName { unResourceName :: Text }
+ deriving (Show, Eq)
+
+-- | Source of image data for an 'Image' widget.
+data ImageSource
+ = ImageResource ResourceName -- ^ Platform resource by name.
+ | ImageData ByteString -- ^ Raw image bytes (PNG/JPEG).
+ | ImageFile FilePath -- ^ Absolute file path to an image on disk.
+ deriving (Show, Eq)
+
+-- | Configuration for an image widget.
+data ImageConfig = ImageConfig
+ { icSource :: ImageSource
+ -- ^ Where the image data comes from.
+ , icScaleType :: ScaleType
+ -- ^ How the image is scaled.
+ } deriving (Show, Eq)
+
+-- | A declarative description of a UI element.
+data Widget
+ = Text TextConfig
+ -- ^ A read-only text label.
+ | Button ButtonConfig
+ -- ^ A tappable button with a label and click handler.
+ | TextInput TextInputConfig
+ -- ^ A text input field.
+ | Column [Widget]
+ -- ^ A vertical container laying out children top-to-bottom.
+ | Row [Widget]
+ -- ^ A horizontal container laying out children left-to-right.
+ | ScrollView [Widget]
+ -- ^ A vertically scrollable container.
+ | Image ImageConfig
+ -- ^ An image widget displaying resource, file, or raw data.
+ | Styled WidgetStyle Widget
+ -- ^ Apply visual style overrides to a child widget.
diff --git a/src/Template.hs b/src/Template.hs
deleted file mode 100644
index e1d3f5bd..00000000
--- a/src/Template.hs
+++ /dev/null
@@ -1,7 +0,0 @@
-module Template
- ( main
- )
-where
-
-main :: IO ()
-main = putStrLn "hello, world flaky"
diff --git a/test/ImageDemoMain.hs b/test/ImageDemoMain.hs
new file mode 100644
index 00000000..2f752c48
--- /dev/null
+++ b/test/ImageDemoMain.hs
@@ -0,0 +1,58 @@
+{-# LANGUAGE OverloadedStrings #-}
+-- | Mobile entry point for the image-demo test app.
+--
+-- Used by the emulator and simulator Image integration tests.
+-- Starts directly in image-demo mode so no runtime switching is needed.
+module Main where
+
+import Data.ByteString qualified as BS
+import Foreign.Ptr (Ptr)
+import HaskellMobile (startMobileApp, platformLog, loggingMobileContext, MobileApp(..), AppContext)
+import HaskellMobile.Widget (ImageConfig(..), ImageSource(..), ResourceName(..), ScaleType(..), TextConfig(..), Widget(..))
+
+main :: IO (Ptr AppContext)
+main = do
+ platformLog "Image demo app registered"
+ startMobileApp imageDemoApp
+
+-- | Image demo: displays images from all three source types.
+-- Exercises every ImageSource constructor and every ScaleType variant.
+imageDemoApp :: MobileApp
+imageDemoApp = MobileApp
+ { maContext = loggingMobileContext
+ , maView = \_userState -> imageDemoView
+ }
+
+-- | Builds a Column with a label and three Image widgets (resource, data, file).
+imageDemoView :: IO Widget
+imageDemoView = pure $ Column
+ [ Text TextConfig { tcLabel = "Image Demo", tcFontConfig = Nothing }
+ , Image ImageConfig
+ { icSource = ImageResource (ResourceName "ic_launcher")
+ , icScaleType = ScaleFit
+ }
+ , Image ImageConfig
+ { icSource = ImageData onePixelRedPng
+ , icScaleType = ScaleFill
+ }
+ , Image ImageConfig
+ { icSource = ImageFile "/nonexistent/test.png"
+ , icScaleType = ScaleNone
+ }
+ ]
+
+-- | A minimal 1x1 red PNG image (67 bytes).
+-- Used for integration testing of the ImageData source path.
+onePixelRedPng :: BS.ByteString
+onePixelRedPng = BS.pack
+ [ 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A -- PNG signature
+ , 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52 -- IHDR chunk
+ , 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01 -- 1x1
+ , 0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53 -- 8-bit RGB
+ , 0xDE -- IHDR CRC
+ , 0x00, 0x00, 0x00, 0x0C, 0x49, 0x44, 0x41, 0x54 -- IDAT chunk
+ , 0x08, 0xD7, 0x63, 0xF8, 0xCF, 0xC0, 0x00, 0x00 -- zlib red pixel
+ , 0x00, 0x02, 0x00, 0x01, 0xE2, 0x21, 0xBC, 0x33 -- IDAT CRC
+ , 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44 -- IEND chunk
+ , 0xAE, 0x42, 0x60, 0x82 -- IEND CRC
+ ]
diff --git a/test/NodePoolTestMain.hs b/test/NodePoolTestMain.hs
new file mode 100644
index 00000000..dd069127
--- /dev/null
+++ b/test/NodePoolTestMain.hs
@@ -0,0 +1,27 @@
+{-# LANGUAGE OverloadedStrings #-}
+-- | Mobile entry point for the node-pool stress-test app.
+--
+-- Renders 300 nodes (1 Column + 299 Text children) to exceed the
+-- default MAX_NODES=256 limit. Used by integration tests to verify
+-- that configurable / dynamic node pools work end-to-end.
+module Main where
+
+import Data.Text (pack)
+import Foreign.Ptr (Ptr)
+import HaskellMobile (MobileApp(..), UserState(..), startMobileApp, AppContext)
+import HaskellMobile.Lifecycle (loggingMobileContext)
+import HaskellMobile.Widget (TextConfig(..), Widget(..))
+
+-- | Render 300 nodes: 1 Column parent + 299 Text children.
+nodePoolTestView :: UserState -> IO Widget
+nodePoolTestView _userState = pure $ Column $
+ map (\itemNumber -> Text TextConfig
+ { tcLabel = "Item " <> pack (show (itemNumber :: Int))
+ , tcFontConfig = Nothing
+ }) [1..299]
+
+main :: IO (Ptr AppContext)
+main = startMobileApp MobileApp
+ { maContext = loggingMobileContext
+ , maView = nodePoolTestView
+ }
diff --git a/test/PermissionDemoMain.hs b/test/PermissionDemoMain.hs
new file mode 100644
index 00000000..574aba20
--- /dev/null
+++ b/test/PermissionDemoMain.hs
@@ -0,0 +1,47 @@
+{-# LANGUAGE OverloadedStrings #-}
+-- | Mobile entry point for the permission-demo test app.
+--
+-- Used by the emulator and simulator permission integration tests.
+-- Starts directly in permission-demo mode so no runtime switching is needed.
+module Main where
+
+import Data.Text (pack)
+import Foreign.Ptr (Ptr)
+import HaskellMobile
+ ( MobileApp(..)
+ , UserState(..)
+ , Permission(..)
+ , PermissionStatus(..)
+ , startMobileApp
+ , platformLog
+ , requestPermission
+ , loggingMobileContext
+ , AppContext
+ )
+import HaskellMobile.Widget (ButtonConfig(..), TextConfig(..), Widget(..))
+
+main :: IO (Ptr AppContext)
+main = do
+ platformLog "Permission demo app registered"
+ startMobileApp permissionDemoApp
+
+-- | Permission demo: requests camera permission on button tap.
+-- Used by integration tests to verify the permission FFI bridge end-to-end.
+permissionDemoApp :: MobileApp
+permissionDemoApp = MobileApp
+ { maContext = loggingMobileContext
+ , maView = permissionDemoView
+ }
+
+-- | Builds a Column with a label and a "Request Camera" button.
+-- The button's callback ID is 0 (first registered), matching --autotest dispatch.
+permissionDemoView :: UserState -> IO Widget
+permissionDemoView userState = pure $ Column
+ [ Text TextConfig { tcLabel = "Permission Demo", tcFontConfig = Nothing }
+ , Button ButtonConfig
+ { bcLabel = "Request Camera"
+ , bcAction = requestPermission (userPermissionState userState) PermissionCamera $ \status ->
+ platformLog ("Permission result: " <> pack (show status))
+ , bcFontConfig = Nothing
+ }
+ ]
diff --git a/test/ScrollDemoMain.hs b/test/ScrollDemoMain.hs
new file mode 100644
index 00000000..0e29a101
--- /dev/null
+++ b/test/ScrollDemoMain.hs
@@ -0,0 +1,15 @@
+{-# LANGUAGE OverloadedStrings #-}
+-- | Mobile entry point for the scroll-demo test app.
+--
+-- Used by the emulator and simulator ScrollView integration tests.
+-- Starts directly in scroll-demo mode so no runtime switching is needed.
+module Main where
+
+import Foreign.Ptr (Ptr)
+import HaskellMobile (startMobileApp, platformLog, AppContext)
+import HaskellMobile.App (scrollDemoApp)
+
+main :: IO (Ptr AppContext)
+main = do
+ platformLog "Scroll demo app registered"
+ startMobileApp scrollDemoApp
diff --git a/test/Test.hs b/test/Test.hs
index 3565d893..1eec9b90 100644
--- a/test/Test.hs
+++ b/test/Test.hs
@@ -4,14 +4,77 @@ import Test.Tasty
import Test.Tasty.QuickCheck as QC
import Test.Tasty.HUnit
-import Data.List(sort)
-import qualified Template
+import Data.ByteString qualified as BS
+import Data.Either (isLeft)
+import Data.List (isInfixOf, sort)
+import Data.IntMap.Strict qualified as IntMap
+import Control.Exception (IOException, throwIO, try)
+import Data.IORef (newIORef, readIORef, modifyIORef', writeIORef)
+import Data.Map.Strict qualified as Map
+import Data.Text qualified as Text
+import Foreign.C.String (newCString, peekCString)
+import Foreign.Marshal.Alloc (free)
+import Foreign.Ptr (Ptr)
+import HaskellMobile
+ ( MobileApp(..)
+ , UserState(..)
+ , startMobileApp
+ , haskellGreet
+ , haskellRenderUI
+ , haskellOnUIEvent
+ , haskellOnLifecycle
+ , freeAppContext
+ , derefAppContext
+ , AppContext(..)
+ )
+import HaskellMobile.AppContext (newAppContext)
+import HaskellMobile.Locale
+ ( Language(..)
+ , Locale(..)
+ , LocaleFailure(..)
+ , getSystemLocale
+ , parseLocale
+ , localeToText
+ )
+import HaskellMobile.I18n
+ ( Key(..)
+ , TranslateFailure(..)
+ , translate
+ )
+import HaskellMobile.App (mobileApp)
+import HaskellMobile.Lifecycle
+ ( LifecycleEvent(..)
+ , MobileContext(..)
+ , defaultMobileContext
+ , lifecycleFromInt
+ , lifecycleToInt
+ , loggingMobileContext
+ )
+import HaskellMobile.Widget (ButtonConfig(..), Color(..), FontConfig(..), ImageConfig(..), ImageSource(..), InputType(..), ResourceName(..), ScaleType(..), TextAlignment(..), TextConfig(..), TextInputConfig(..), Widget(..), WidgetStyle(..), colorFromText, colorToHex, defaultStyle)
+import HaskellMobile.Permission
+ ( Permission(..)
+ , PermissionStatus(..)
+ , PermissionState(..)
+ , newPermissionState
+ , requestPermission
+ , checkPermission
+ , dispatchPermissionResult
+ , permissionToInt
+ , permissionStatusFromInt
+ )
+import HaskellMobile.Render (newRenderState, renderWidget, dispatchEvent, dispatchTextEvent)
main :: IO ()
-main = defaultMain tests
+main = do
+ -- Create a single FFI context for permission round-trip tests.
+ -- The C desktop stub uses a process-wide g_permission_ctx, so only
+ -- one context can be active for FFI permission dispatch.
+ ffiCtxPtr <- startMobileApp mobileApp
+ ffiAppCtx <- derefAppContext ffiCtxPtr
+ defaultMain (tests (acPermissionState ffiAppCtx))
-tests :: TestTree
-tests = testGroup "Tests" [qcProps, unitTests]
+tests :: PermissionState -> TestTree
+tests ffiPermState = testGroup "Tests" [qcProps, unitTests, lifecycleTests, uiTests, scrollViewTests, textInputTests, imageTests, styledTests, textAlignTests, colorTests, registrationTests, localeTests, i18nTests, permissionTests ffiPermState, appContextTests, exceptionHandlerTests]
qcProps :: TestTree
qcProps = testGroup "(checked by QuickCheck)"
@@ -35,6 +98,879 @@ unitTests = testGroup "Unit tests"
-- the following test does not hold
, testCase "List comparison (same length)" $
oneTwoThree `compare` [1,2,3] @?= EQ
- , testCase "run main" $ do
- Template.main
+ , testCase "haskellGreet returns correct greeting" $ do
+ cname <- newCString "World"
+ cresult <- haskellGreet cname
+ result <- peekCString cresult
+ free cresult
+ free cname
+ result @?= "Hello from Haskell, World!"
+ , testCase "haskellGreet with different input" $ do
+ cname <- newCString "Android"
+ cresult <- haskellGreet cname
+ result <- peekCString cresult
+ free cresult
+ free cname
+ result @?= "Hello from Haskell, Android!"
+ ]
+
+-- | Helper: create an 'AppContext' from a 'MobileApp',
+-- run an action with the typed 'Ptr AppContext', then free the context.
+withAppContext :: MobileApp -> (Ptr AppContext -> IO a) -> IO a
+withAppContext app action = do
+ ptr <- newAppContext app
+ result <- action ptr
+ freeAppContext ptr
+ pure result
+
+-- | Helper: create an 'AppContext' with the given lifecycle callback,
+-- run an action with the typed 'Ptr AppContext', then free the context.
+withContext :: (LifecycleEvent -> IO ()) -> (Ptr AppContext -> IO a) -> IO a
+withContext callback action = withAppContext dummyApp action
+ where
+ dummyApp = MobileApp
+ { maContext = MobileContext { onLifecycle = callback, onError = \_ -> pure () }
+ , maView = \_userState -> pure (Text TextConfig { tcLabel = "dummy", tcFontConfig = Nothing })
+ }
+
+allEvents :: [LifecycleEvent]
+allEvents = [Create, Start, Resume, Pause, Stop, Destroy, LowMemory]
+
+lifecycleTests :: TestTree
+lifecycleTests = testGroup "Lifecycle"
+ [ testCase "lifecycleToInt produces sequential codes 0-6" $
+ map lifecycleToInt allEvents @?= [0, 1, 2, 3, 4, 5, 6]
+ , testCase "lifecycleFromInt roundtrips for all events" $
+ mapM_ (\event ->
+ lifecycleFromInt (lifecycleToInt event) @?= Just event
+ ) allEvents
+ , testCase "lifecycleFromInt returns Nothing for unknown codes" $ do
+ lifecycleFromInt 7 @?= Nothing
+ lifecycleFromInt (-1) @?= Nothing
+ lifecycleFromInt 100 @?= Nothing
+ , testCase "callback receives dispatched event" $ do
+ ref <- newIORef ([] :: [LifecycleEvent])
+ withContext (\event -> modifyIORef' ref (++ [event])) $ \ctx ->
+ haskellOnLifecycle ctx 2
+ received <- readIORef ref
+ received @?= [Resume]
+ , testCase "unknown codes are silently ignored" $ do
+ ref <- newIORef (0 :: Int)
+ withContext (\_ -> modifyIORef' ref (+ 1)) $ \ctx -> do
+ haskellOnLifecycle ctx 99
+ haskellOnLifecycle ctx (-1)
+ count <- readIORef ref
+ count @?= 0
+ , testCase "all 7 event types received in order" $ do
+ ref <- newIORef ([] :: [LifecycleEvent])
+ withContext (\event -> modifyIORef' ref (++ [event])) $ \ctx ->
+ mapM_ (haskellOnLifecycle ctx . lifecycleToInt) allEvents
+ received <- readIORef ref
+ received @?= allEvents
+ , testCase "loggingMobileContext handles all events without throwing" $
+ mapM_ (onLifecycle loggingMobileContext) allEvents
+ , testCase "mobileApp context handles all events without throwing" $
+ mapM_ (onLifecycle (maContext mobileApp)) allEvents
+ ]
+
+uiTests :: TestTree
+uiTests = testGroup "UI"
+ [ testCase "callback dispatch fires registered action" $ do
+ ref <- newIORef (0 :: Int)
+ rs <- newRenderState
+ let widget = Button ButtonConfig
+ { bcLabel = "click me", bcAction = modifyIORef' ref (+ 1), bcFontConfig = Nothing }
+ renderWidget rs widget
+ -- After rendering, callback 0 should be the button's handler
+ dispatchEvent rs 0
+ count <- readIORef ref
+ count @?= 1
+
+ , testCase "multiple callbacks each fire independently" $ do
+ refA <- newIORef False
+ refB <- newIORef False
+ rs <- newRenderState
+ let widget = Row
+ [ Button ButtonConfig
+ { bcLabel = "A", bcAction = modifyIORef' refA (const True), bcFontConfig = Nothing }
+ , Button ButtonConfig
+ { bcLabel = "B", bcAction = modifyIORef' refB (const True), bcFontConfig = Nothing }
+ ]
+ renderWidget rs widget
+ -- Only fire callback 0 (button A)
+ dispatchEvent rs 0
+ a <- readIORef refA
+ b <- readIORef refB
+ a @?= True
+ b @?= False
+ -- Now fire callback 1 (button B)
+ dispatchEvent rs 1
+ b' <- readIORef refB
+ b' @?= True
+
+ , testCase "re-render resets callback IDs" $ do
+ refOld <- newIORef False
+ refNew <- newIORef False
+ rs <- newRenderState
+ -- First render with old callback
+ renderWidget rs (Button ButtonConfig
+ { bcLabel = "old", bcAction = modifyIORef' refOld (const True), bcFontConfig = Nothing })
+ -- Second render replaces it
+ renderWidget rs (Button ButtonConfig
+ { bcLabel = "new", bcAction = modifyIORef' refNew (const True), bcFontConfig = Nothing })
+ dispatchEvent rs 0
+ old <- readIORef refOld
+ new <- readIORef refNew
+ old @?= False
+ new @?= True
+
+ , testCase "dispatching unknown callback ID logs error" $ do
+ rs <- newRenderState
+ renderWidget rs (Text TextConfig { tcLabel = "no buttons", tcFontConfig = Nothing })
+ -- Should not throw (logs to stderr)
+ dispatchEvent rs 42
+ dispatchEvent rs 999
+
+ , testCase "nested widget tree renders without error" $ do
+ rs <- newRenderState
+ let widget = Column
+ [ Text TextConfig { tcLabel = "header", tcFontConfig = Nothing }
+ , Row
+ [ Button ButtonConfig
+ { bcLabel = "a", bcAction = pure (), bcFontConfig = Nothing }
+ , Column
+ [ Text TextConfig { tcLabel = "nested", tcFontConfig = Nothing }
+ , Button ButtonConfig
+ { bcLabel = "b", bcAction = pure (), bcFontConfig = Nothing }
+ ]
+ ]
+ , Text TextConfig { tcLabel = "footer", tcFontConfig = Nothing }
+ ]
+ -- Should not throw — exercises all node types
+ renderWidget rs widget
+
+ , testCase "mobileApp view returns a widget" $ do
+ dummyPermState <- newPermissionState
+ let dummyUserState = UserState { userPermissionState = dummyPermState }
+ widget <- maView mobileApp dummyUserState
+ -- mobileApp is the counter demo; verify it's a column
+ case widget of
+ Column _ -> pure ()
+ Text _ -> assertFailure "expected Column, got Text"
+ Button _ -> assertFailure "expected Column, got Button"
+ TextInput _ -> assertFailure "expected Column, got TextInput"
+ Image _ -> assertFailure "expected Column, got Image"
+ Row _ -> assertFailure "expected Column, got Row"
+ ScrollView _ -> assertFailure "expected Column, got ScrollView"
+ Styled _ _ -> assertFailure "expected Column, got Styled"
+ ]
+
+-- | Tests for the ScrollView widget binding.
+-- These exercise the Haskell render path shared by both Android and iOS —
+-- the platform bridge (JNI / UIKit) receives UI_NODE_SCROLL_VIEW (5) and
+-- is responsible for mapping it to a native scroll container.
+scrollViewTests :: TestTree
+scrollViewTests = testGroup "ScrollView"
+ [ testCase "ScrollView renders without error" $ do
+ rs <- newRenderState
+ renderWidget rs (ScrollView
+ [ Text TextConfig { tcLabel = "item 1", tcFontConfig = Nothing }
+ , Text TextConfig { tcLabel = "item 2", tcFontConfig = Nothing }
+ ])
+
+ , testCase "button inside ScrollView fires its callback" $ do
+ ref <- newIORef (0 :: Int)
+ rs <- newRenderState
+ renderWidget rs $ ScrollView
+ [ Button ButtonConfig
+ { bcLabel = "press me", bcAction = modifyIORef' ref (+ 1), bcFontConfig = Nothing } ]
+ dispatchEvent rs 0
+ count <- readIORef ref
+ count @?= 1
+
+ , testCase "ScrollView with nested Column renders and dispatches correctly" $ do
+ ref <- newIORef False
+ rs <- newRenderState
+ renderWidget rs $ ScrollView
+ [ Column
+ [ Text TextConfig { tcLabel = "header", tcFontConfig = Nothing }
+ , Button ButtonConfig
+ { bcLabel = "action", bcAction = modifyIORef' ref (const True), bcFontConfig = Nothing }
+ ]
+ ]
+ dispatchEvent rs 0
+ fired <- readIORef ref
+ fired @?= True
+
+ , testCase "re-render inside ScrollView resets callbacks" $ do
+ refOld <- newIORef False
+ refNew <- newIORef False
+ rs <- newRenderState
+ renderWidget rs $ ScrollView [Button ButtonConfig
+ { bcLabel = "old", bcAction = modifyIORef' refOld (const True), bcFontConfig = Nothing }]
+ renderWidget rs $ ScrollView [Button ButtonConfig
+ { bcLabel = "new", bcAction = modifyIORef' refNew (const True), bcFontConfig = Nothing }]
+ dispatchEvent rs 0
+ old <- readIORef refOld
+ new <- readIORef refNew
+ old @?= False
+ new @?= True
+ ]
+
+textInputTests :: TestTree
+textInputTests = testGroup "TextInput"
+ [ testCase "text callback fires with correct value" $ do
+ ref <- newIORef ("" :: String)
+ rs <- newRenderState
+ let widget = TextInput TextInputConfig
+ { tiInputType = InputText, tiHint = "hint", tiValue = ""
+ , tiOnChange = \t -> modifyIORef' ref (const (show t))
+ , tiFontConfig = Nothing }
+ renderWidget rs widget
+ -- Callback 0 is the text change handler
+ dispatchTextEvent rs 0 "hello"
+ val <- readIORef ref
+ val @?= show ("hello" :: String)
+
+ , testCase "text callback receives updated value" $ do
+ ref <- newIORef ("" :: String)
+ rs <- newRenderState
+ let widget = TextInput TextInputConfig
+ { tiInputType = InputText, tiHint = "enter weight", tiValue = "80"
+ , tiOnChange = \t -> modifyIORef' ref (const (show t))
+ , tiFontConfig = Nothing }
+ renderWidget rs widget
+ dispatchTextEvent rs 0 "95.5"
+ val <- readIORef ref
+ val @?= show ("95.5" :: String)
+
+ , testCase "dispatchTextEvent with unknown ID does not crash" $ do
+ rs <- newRenderState
+ renderWidget rs (Text TextConfig { tcLabel = "no inputs", tcFontConfig = Nothing })
+ -- Should not throw
+ dispatchTextEvent rs 42 "ignored"
+ dispatchTextEvent rs 999 "also ignored"
+
+ , testCase "text and click callbacks share ID space without collision" $ do
+ clickRef <- newIORef False
+ textRef <- newIORef ("" :: String)
+ rs <- newRenderState
+ let widget = Column
+ [ Button ButtonConfig
+ { bcLabel = "ok", bcAction = modifyIORef' clickRef (const True), bcFontConfig = Nothing }
+ , TextInput TextInputConfig
+ { tiInputType = InputText, tiHint = "hint", tiValue = ""
+ , tiOnChange = \t -> modifyIORef' textRef (const (show t))
+ , tiFontConfig = Nothing }
+ ]
+ renderWidget rs widget
+ -- Button gets callback 0, TextInput gets callback 1
+ dispatchEvent rs 0
+ dispatchTextEvent rs 1 "typed"
+ click <- readIORef clickRef
+ text <- readIORef textRef
+ click @?= True
+ text @?= show ("typed" :: String)
+
+ , testCase "re-render resets text callbacks" $ do
+ refOld <- newIORef ("" :: String)
+ refNew <- newIORef ("" :: String)
+ rs <- newRenderState
+ renderWidget rs $ TextInput TextInputConfig
+ { tiInputType = InputText, tiHint = "old", tiValue = ""
+ , tiOnChange = \t -> modifyIORef' refOld (const (show t))
+ , tiFontConfig = Nothing }
+ renderWidget rs $ TextInput TextInputConfig
+ { tiInputType = InputText, tiHint = "new", tiValue = ""
+ , tiOnChange = \t -> modifyIORef' refNew (const (show t))
+ , tiFontConfig = Nothing }
+ dispatchTextEvent rs 0 "val"
+ old <- readIORef refOld
+ new <- readIORef refNew
+ old @?= ""
+ new @?= show ("val" :: String)
+
+ , testCase "InputNumber callback fires correctly" $ do
+ ref <- newIORef ("" :: String)
+ rs <- newRenderState
+ let widget = TextInput TextInputConfig
+ { tiInputType = InputNumber, tiHint = "weight", tiValue = ""
+ , tiOnChange = \t -> modifyIORef' ref (const (show t))
+ , tiFontConfig = Nothing }
+ renderWidget rs widget
+ dispatchTextEvent rs 0 "72.5"
+ val <- readIORef ref
+ val @?= show ("72.5" :: String)
+
+ , testCase "InputText and InputNumber coexist with independent callbacks" $ do
+ textRef <- newIORef ("" :: String)
+ numberRef <- newIORef ("" :: String)
+ rs <- newRenderState
+ let widget = Column
+ [ TextInput TextInputConfig
+ { tiInputType = InputText, tiHint = "name", tiValue = ""
+ , tiOnChange = \t -> modifyIORef' textRef (const (show t))
+ , tiFontConfig = Nothing }
+ , TextInput TextInputConfig
+ { tiInputType = InputNumber, tiHint = "weight", tiValue = ""
+ , tiOnChange = \t -> modifyIORef' numberRef (const (show t))
+ , tiFontConfig = Nothing }
+ ]
+ renderWidget rs widget
+ -- TextInput gets callback 0, InputNumber gets callback 1
+ dispatchTextEvent rs 0 "Alice"
+ dispatchTextEvent rs 1 "60.0"
+ tVal <- readIORef textRef
+ nVal <- readIORef numberRef
+ tVal @?= show ("Alice" :: String)
+ nVal @?= show ("60.0" :: String)
+ ]
+
+-- | Tests for the Image widget binding.
+imageTests :: TestTree
+imageTests = testGroup "Image"
+ [ testCase "Image with resource renders without error" $ do
+ rs <- newRenderState
+ renderWidget rs $ Image ImageConfig
+ { icSource = ImageResource (ResourceName "ic_launcher"), icScaleType = ScaleFit }
+
+ , testCase "Image with ByteString data renders without error" $ do
+ rs <- newRenderState
+ let bytes = BS.pack [0x89, 0x50, 0x4E, 0x47, 0x00, 0x00, 0x00, 0x00]
+ renderWidget rs $ Image ImageConfig
+ { icSource = ImageData bytes, icScaleType = ScaleFill }
+
+ , testCase "Image with file path renders without error" $ do
+ rs <- newRenderState
+ renderWidget rs $ Image ImageConfig
+ { icSource = ImageFile "/nonexistent/test.png", icScaleType = ScaleNone }
+
+ , testCase "Image inside Column renders" $ do
+ rs <- newRenderState
+ renderWidget rs $ Column
+ [ Text TextConfig { tcLabel = "header", tcFontConfig = Nothing }
+ , Image ImageConfig
+ { icSource = ImageResource (ResourceName "logo"), icScaleType = ScaleFit }
+ ]
+
+ , testCase "Styled Image renders without error" $ do
+ rs <- newRenderState
+ renderWidget rs $ Styled defaultStyle
+ (Image ImageConfig
+ { icSource = ImageResource (ResourceName "icon"), icScaleType = ScaleNone })
+
+ , testCase "ScaleFit renders without error" $ do
+ rs <- newRenderState
+ renderWidget rs $ Image ImageConfig
+ { icSource = ImageResource (ResourceName "fit_test"), icScaleType = ScaleFit }
+
+ , testCase "ScaleFill renders without error" $ do
+ rs <- newRenderState
+ renderWidget rs $ Image ImageConfig
+ { icSource = ImageResource (ResourceName "fill_test"), icScaleType = ScaleFill }
+
+ , testCase "ScaleNone renders without error" $ do
+ rs <- newRenderState
+ renderWidget rs $ Image ImageConfig
+ { icSource = ImageResource (ResourceName "none_test"), icScaleType = ScaleNone }
+ ]
+
+-- | Tests for the Styled widget wrapper.
+styledTests :: TestTree
+styledTests = testGroup "Styled"
+ [ testCase "Styled Text renders without error" $ do
+ rs <- newRenderState
+ renderWidget rs $ Styled (WidgetStyle (Just 8.0) Nothing Nothing Nothing)
+ (Text TextConfig { tcLabel = "styled", tcFontConfig = Just (FontConfig 20.0) })
+
+ , testCase "Styled Button fires callback" $ do
+ ref <- newIORef (0 :: Int)
+ rs <- newRenderState
+ renderWidget rs $ Styled (WidgetStyle Nothing Nothing Nothing Nothing)
+ (Button ButtonConfig
+ { bcLabel = "tap", bcAction = modifyIORef' ref (+ 1)
+ , bcFontConfig = Just (FontConfig 16.0) })
+ dispatchEvent rs 0
+ count <- readIORef ref
+ count @?= 1
+
+ , testCase "Styled Column renders children and dispatches" $ do
+ ref <- newIORef False
+ rs <- newRenderState
+ renderWidget rs $ Styled defaultStyle
+ (Column [ Text TextConfig { tcLabel = "info", tcFontConfig = Nothing }
+ , Button ButtonConfig
+ { bcLabel = "go", bcAction = modifyIORef' ref (const True), bcFontConfig = Nothing }
+ ])
+ dispatchEvent rs 0
+ fired <- readIORef ref
+ fired @?= True
+
+ , testCase "nested Styled applies both styles" $ do
+ rs <- newRenderState
+ renderWidget rs $
+ Styled (WidgetStyle (Just 12.0) Nothing Nothing Nothing)
+ (Styled (WidgetStyle Nothing Nothing Nothing Nothing)
+ (Text TextConfig { tcLabel = "double styled", tcFontConfig = Just (FontConfig 18.0) }))
+
+ , testCase "defaultStyle is a no-op" $ do
+ rs <- newRenderState
+ renderWidget rs $ Styled defaultStyle
+ (Text TextConfig { tcLabel = "plain", tcFontConfig = Nothing })
+
+ , testCase "re-render resets callbacks through Styled" $ do
+ refOld <- newIORef False
+ refNew <- newIORef False
+ rs <- newRenderState
+ renderWidget rs $ Styled defaultStyle
+ (Button ButtonConfig
+ { bcLabel = "old", bcAction = modifyIORef' refOld (const True), bcFontConfig = Nothing })
+ renderWidget rs $ Styled defaultStyle
+ (Button ButtonConfig
+ { bcLabel = "new", bcAction = modifyIORef' refNew (const True), bcFontConfig = Nothing })
+ dispatchEvent rs 0
+ old <- readIORef refOld
+ new <- readIORef refNew
+ old @?= False
+ new @?= True
+ ]
+
+-- | Tests for TextAlignment support in Styled widgets.
+textAlignTests :: TestTree
+textAlignTests = testGroup "TextAlignment"
+ [ testCase "Styled with AlignCenter renders without error" $ do
+ rs <- newRenderState
+ renderWidget rs $ Styled (WidgetStyle Nothing (Just AlignCenter) Nothing Nothing)
+ (Text TextConfig { tcLabel = "centered", tcFontConfig = Nothing })
+
+ , testCase "Styled with AlignCenter on Button fires callback" $ do
+ ref <- newIORef (0 :: Int)
+ rs <- newRenderState
+ renderWidget rs $ Styled (WidgetStyle Nothing (Just AlignCenter) Nothing Nothing)
+ (Button ButtonConfig
+ { bcLabel = "tap", bcAction = modifyIORef' ref (+ 1), bcFontConfig = Nothing })
+ dispatchEvent rs 0
+ count <- readIORef ref
+ count @?= 1
+
+ , testCase "defaultStyle has no text alignment" $
+ wsTextAlign defaultStyle @?= Nothing
+
+ , testCase "Styled with AlignEnd renders without error" $ do
+ rs <- newRenderState
+ renderWidget rs $ Styled (WidgetStyle Nothing (Just AlignEnd) Nothing Nothing)
+ (Text TextConfig { tcLabel = "end aligned", tcFontConfig = Nothing })
+ ]
+
+-- | Tests for color support in Styled widgets.
+colorTests :: TestTree
+colorTests = testGroup "Colors"
+ [ testCase "Styled with textColor renders and callback fires" $ do
+ ref <- newIORef (0 :: Int)
+ rs <- newRenderState
+ renderWidget rs $ Styled (WidgetStyle Nothing Nothing (Just (Color 255 0 0 255)) Nothing)
+ (Button ButtonConfig
+ { bcLabel = "red", bcAction = modifyIORef' ref (+ 1), bcFontConfig = Nothing })
+ dispatchEvent rs 0
+ count <- readIORef ref
+ count @?= 1
+
+ , testCase "Styled with backgroundColor renders without error" $ do
+ rs <- newRenderState
+ renderWidget rs $ Styled (WidgetStyle Nothing Nothing Nothing (Just (Color 0 255 0 255)))
+ (Text TextConfig { tcLabel = "green bg", tcFontConfig = Nothing })
+
+ , testCase "both textColor and backgroundColor together" $ do
+ ref <- newIORef (0 :: Int)
+ rs <- newRenderState
+ renderWidget rs $ Styled (WidgetStyle Nothing Nothing (Just (Color 255 0 0 255)) (Just (Color 0 255 0 255)))
+ (Button ButtonConfig
+ { bcLabel = "colored", bcAction = modifyIORef' ref (+ 1), bcFontConfig = Nothing })
+ dispatchEvent rs 0
+ count <- readIORef ref
+ count @?= 1
+
+ , testCase "defaultStyle has no colors" $ do
+ wsTextColor defaultStyle @?= Nothing
+ wsBackgroundColor defaultStyle @?= Nothing
+
+ , testCase "nested Styled with different colors renders" $ do
+ rs <- newRenderState
+ renderWidget rs $
+ Styled (WidgetStyle Nothing Nothing (Just (Color 255 0 0 255)) Nothing)
+ (Styled (WidgetStyle Nothing Nothing Nothing (Just (Color 0 0 255 255)))
+ (Text TextConfig { tcLabel = "nested colors", tcFontConfig = Nothing }))
+
+ , testCase "colorFromText parses #RRGGBB" $
+ colorFromText "#FF0000" @?= Just (Color 255 0 0 255)
+
+ , testCase "colorFromText parses #RGB" $
+ colorFromText "#F00" @?= Just (Color 255 0 0 255)
+
+ , testCase "colorFromText parses #AARRGGBB" $
+ colorFromText "#80FF0000" @?= Just (Color 255 0 0 128)
+
+ , testCase "colorFromText rejects invalid input" $ do
+ colorFromText "" @?= Nothing
+ colorFromText "FF0000" @?= Nothing
+ colorFromText "#GG0000" @?= Nothing
+
+ , testCase "colorToHex roundtrips through colorFromText" $ do
+ let color = Color 255 128 0 255
+ colorFromText (colorToHex color) @?= Just color
+ ]
+
+-- | Tests for the AppContext-based registration.
+-- Each test creates its own context, so no shared global state.
+registrationTests :: TestTree
+registrationTests = testGroup "Registration"
+ [ testCase "startMobileApp returns working context" $ do
+ ctxPtr <- startMobileApp mobileApp
+ appCtx <- derefAppContext ctxPtr
+ -- Verify the context has a working lifecycle callback
+ mapM_ (onLifecycle (acMobileContext appCtx)) [Create, Destroy]
+ freeAppContext ctxPtr
+
+ , testCase "view function produces a widget through AppContext" $ do
+ let customApp = MobileApp
+ { maContext = MobileContext { onLifecycle = \_ -> pure (), onError = \_ -> pure () }
+ , maView = \_userState -> pure (Text TextConfig { tcLabel = "custom", tcFontConfig = Nothing })
+ }
+ ctxPtr <- newAppContext customApp
+ appCtx <- derefAppContext ctxPtr
+ dummyPermState <- newPermissionState
+ let dummyUserState = UserState { userPermissionState = dummyPermState }
+ viewFn <- readIORef (acViewFunction appCtx)
+ widget <- viewFn dummyUserState
+ case widget of
+ Text config -> tcLabel config @?= "custom"
+ _ -> assertFailure "expected Text \"custom\""
+ freeAppContext ctxPtr
+
+ , testCase "two contexts are independent" $ do
+ let appA = MobileApp
+ { maContext = defaultMobileContext
+ , maView = \_userState -> pure (Text TextConfig { tcLabel = "A", tcFontConfig = Nothing })
+ }
+ appB = MobileApp
+ { maContext = defaultMobileContext
+ , maView = \_userState -> pure (Text TextConfig { tcLabel = "B", tcFontConfig = Nothing })
+ }
+ ctxPtrA <- newAppContext appA
+ ctxPtrB <- newAppContext appB
+ appCtxA <- derefAppContext ctxPtrA
+ appCtxB <- derefAppContext ctxPtrB
+ dummyPermState <- newPermissionState
+ let dummyUserState = UserState { userPermissionState = dummyPermState }
+ viewFnA <- readIORef (acViewFunction appCtxA)
+ viewFnB <- readIORef (acViewFunction appCtxB)
+ widgetA <- viewFnA dummyUserState
+ widgetB <- viewFnB dummyUserState
+ case widgetA of
+ Text config -> tcLabel config @?= "A"
+ _ -> assertFailure "expected Text \"A\""
+ case widgetB of
+ Text config -> tcLabel config @?= "B"
+ _ -> assertFailure "expected Text \"B\""
+ freeAppContext ctxPtrA
+ freeAppContext ctxPtrB
+ ]
+
+localeTests :: TestTree
+localeTests = testGroup "Locale"
+ [ testCase "parseLocale parses language-only tag" $
+ parseLocale "en" @?= Right (Locale En Nothing)
+ , testCase "parseLocale parses language-region tag" $
+ parseLocale "nl-NL" @?= Right (Locale Nl (Just "NL"))
+ , testCase "parseLocale handles underscore separator" $
+ parseLocale "en_US" @?= Right (Locale En (Just "US"))
+ , testCase "parseLocale normalises case" $
+ parseLocale "EN-us" @?= Right (Locale En (Just "US"))
+ , testCase "parseLocale accepts 3-digit region code" $
+ parseLocale "en-001" @?= Right (Locale En (Just "001"))
+ , testCase "parseLocale rejects empty tag" $
+ parseLocale "" @?= Left EmptyLocaleTag
+ , testCase "parseLocale rejects unknown language code" $
+ isLeft (parseLocale "xx") @?= True
+ , testCase "parseLocale rejects invalid language" $
+ isLeft (parseLocale "123") @?= True
+ , testCase "parseLocale rejects single-char language" $
+ isLeft (parseLocale "e") @?= True
+ , testCase "localeToText roundtrips" $ do
+ let locale = Locale Nl (Just "NL")
+ parseLocale (localeToText locale) @?= Right locale
+ , testCase "localeToText language-only" $
+ localeToText (Locale En Nothing) @?= "en"
+ , testCase "localeToText language-region" $
+ localeToText (Locale Nl (Just "NL")) @?= "nl-NL"
+ , testCase "getSystemLocale returns non-empty text" $ do
+ locale <- getSystemLocale
+ assertBool "locale should not be empty" (not (Text.null locale))
+ ]
+
+i18nTests :: TestTree
+i18nTests = testGroup "I18n"
+ [ testCase "translate finds exact locale match" $ do
+ let translations = Map.fromList
+ [ (Locale Nl (Just "NL"), Map.fromList [(Key "greeting", "Hallo")])
+ , (Locale En Nothing, Map.fromList [(Key "greeting", "Hello")])
+ ]
+ translate translations (Locale Nl (Just "NL")) (Key "greeting") @?= Right "Hallo"
+ , testCase "translate falls back to language-only" $ do
+ let translations = Map.fromList
+ [ (Locale Nl Nothing, Map.fromList [(Key "greeting", "Hallo")])
+ ]
+ translate translations (Locale Nl (Just "BE")) (Key "greeting") @?= Right "Hallo"
+ , testCase "translate reports KeyNotFound for missing key" $ do
+ let translations = Map.fromList
+ [ (Locale En Nothing, Map.fromList [(Key "greeting", "Hello")])
+ ]
+ translate translations (Locale En Nothing) (Key "farewell")
+ @?= Left (KeyNotFound (Locale En Nothing) (Key "farewell"))
+ , testCase "translate reports LocaleNotFound for missing locale" $ do
+ let translations = Map.fromList
+ [ (Locale En Nothing, Map.fromList [(Key "greeting", "Hello")])
+ ]
+ translate translations (Locale Ja Nothing) (Key "greeting")
+ @?= Left (LocaleNotFound (Locale Ja Nothing))
+ , testCase "translate prefers exact match over fallback" $ do
+ let translations = Map.fromList
+ [ (Locale Nl Nothing, Map.fromList [(Key "greeting", "Hallo")])
+ , (Locale Nl (Just "BE"), Map.fromList [(Key "greeting", "Hoi")])
+ ]
+ translate translations (Locale Nl (Just "BE")) (Key "greeting") @?= Right "Hoi"
+ ]
+
+-- | Permission tests. The @ffiPermState@ parameter is the 'PermissionState'
+-- from a context created once in 'main' via 'startMobileApp'. This
+-- ensures the C desktop stub's @g_permission_ctx@ points to a valid context
+-- for the FFI round-trip tests, without racing with other tests.
+permissionTests :: PermissionState -> TestTree
+permissionTests ffiPermState = testGroup "Permission"
+ [ testCase "requestPermission fires callback with PermissionGranted on desktop" $ do
+ -- Uses the shared FFI context because the C desktop stub dispatches
+ -- via haskellOnPermissionResult(g_permission_ctx, ...).
+ ref <- newIORef (Nothing :: Maybe PermissionStatus)
+ requestPermission ffiPermState PermissionCamera
+ (\status -> modifyIORef' ref (const (Just status)))
+ result <- readIORef ref
+ result @?= Just PermissionGranted
+
+ , testCase "checkPermission returns PermissionGranted on desktop" $ do
+ status <- checkPermission PermissionLocation
+ status @?= PermissionGranted
+
+ , testCase "dispatchPermissionResult with PermissionDenied fires callback correctly" $ do
+ ref <- newIORef (Nothing :: Maybe PermissionStatus)
+ permState <- newPermissionState
+ modifyIORef' (psCallbacks permState) (\_ ->
+ IntMap.singleton 0 (\status -> modifyIORef' ref (const (Just status))))
+ dispatchPermissionResult permState 0 1
+ result <- readIORef ref
+ result @?= Just PermissionDenied
+
+ , testCase "callback is removed after dispatch (second dispatch is a no-op)" $ do
+ ref <- newIORef (0 :: Int)
+ permState <- newPermissionState
+ modifyIORef' (psCallbacks permState) (\_ ->
+ IntMap.singleton 0 (\_ -> modifyIORef' ref (+ 1)))
+ dispatchPermissionResult permState 0 0
+ count1 <- readIORef ref
+ count1 @?= 1
+ -- Second dispatch for same ID should be a no-op (callback removed)
+ dispatchPermissionResult permState 0 0
+ count2 <- readIORef ref
+ count2 @?= 1
+
+ , testCase "unknown request ID does not crash" $ do
+ permState <- newPermissionState
+ -- Should not throw (logs to stderr)
+ dispatchPermissionResult permState 999 0
+
+ , testCase "unknown status code does not fire callback" $ do
+ ref <- newIORef (0 :: Int)
+ permState <- newPermissionState
+ modifyIORef' (psCallbacks permState) (\_ ->
+ IntMap.singleton 0 (\_ -> modifyIORef' ref (+ 1)))
+ dispatchPermissionResult permState 0 42
+ count <- readIORef ref
+ count @?= 0
+
+ , testCase "multiple simultaneous pending requests dispatch independently" $ do
+ -- Uses the shared FFI context for the desktop stub round-trip
+ refA <- newIORef (Nothing :: Maybe PermissionStatus)
+ refB <- newIORef (Nothing :: Maybe PermissionStatus)
+ requestPermission ffiPermState PermissionCamera
+ (\status -> modifyIORef' refA (const (Just status)))
+ requestPermission ffiPermState PermissionContacts
+ (\status -> modifyIORef' refB (const (Just status)))
+ resultA <- readIORef refA
+ resultB <- readIORef refB
+ resultA @?= Just PermissionGranted
+ resultB @?= Just PermissionGranted
+
+ , testCase "permissionToInt covers all constructors" $ do
+ permissionToInt PermissionLocation @?= 0
+ permissionToInt PermissionBluetooth @?= 1
+ permissionToInt PermissionCamera @?= 2
+ permissionToInt PermissionMicrophone @?= 3
+ permissionToInt PermissionContacts @?= 4
+ permissionToInt PermissionStorage @?= 5
+
+ , testCase "permissionStatusFromInt roundtrips valid codes" $ do
+ permissionStatusFromInt 0 @?= Just PermissionGranted
+ permissionStatusFromInt 1 @?= Just PermissionDenied
+
+ , testCase "permissionStatusFromInt returns Nothing for unknown codes" $ do
+ permissionStatusFromInt 2 @?= Nothing
+ permissionStatusFromInt (-1) @?= Nothing
+ permissionStatusFromInt 100 @?= Nothing
+ ]
+
+-- | Tests for the AppContext FFI path.
+appContextTests :: TestTree
+appContextTests = testGroup "AppContext"
+ [ testCase "newAppContext produces working lifecycle context" $ do
+ ref <- newIORef ([] :: [LifecycleEvent])
+ let app = MobileApp
+ { maContext = MobileContext { onLifecycle = \event -> modifyIORef' ref (++ [event]), onError = \_ -> pure () }
+ , maView = \_userState -> pure (Text TextConfig { tcLabel = "dummy", tcFontConfig = Nothing })
+ }
+ ctxPtr <- newAppContext app
+ haskellOnLifecycle ctxPtr 0 -- Create
+ haskellOnLifecycle ctxPtr 2 -- Resume
+ haskellOnLifecycle ctxPtr 5 -- Destroy
+ freeAppContext ctxPtr
+ received <- readIORef ref
+ received @?= [Create, Resume, Destroy]
+ ]
+
+-- | Helper: check whether the context's view function produces an error widget
+-- (a Column whose first child is a Text with "An error occurred").
+viewIsErrorWidget :: Ptr AppContext -> IO Bool
+viewIsErrorWidget ctxPtr = do
+ appCtx <- derefAppContext ctxPtr
+ viewFn <- readIORef (acViewFunction appCtx)
+ let userState = UserState { userPermissionState = acPermissionState appCtx }
+ widget <- viewFn userState
+ case widget of
+ Column (Text config : _) -> pure (tcLabel config == "An error occurred")
+ Column _ -> pure False
+ Text _ -> pure False
+ Button _ -> pure False
+ TextInput _ -> pure False
+ Image _ -> pure False
+ Row _ -> pure False
+ ScrollView _ -> pure False
+ Styled _ _ -> pure False
+
+-- | Tests for the default exception handler that wraps FFI entry points.
+-- Each test creates its own context, so no shared global mutation.
+exceptionHandlerTests :: TestTree
+exceptionHandlerTests = testGroup "ExceptionHandler"
+ [ testCase "exception in view is caught and view replaced with error widget" $ do
+ let crashingApp = MobileApp
+ { maContext = defaultMobileContext
+ , maView = \_userState -> throwIO (userError "test-boom")
+ }
+ ctxPtr <- newAppContext crashingApp
+ haskellRenderUI ctxPtr
+ isError <- viewIsErrorWidget ctxPtr
+ assertBool "view should be replaced with error widget" isError
+ freeAppContext ctxPtr
+
+ , testCase "exception in button callback is caught" $ do
+ let crashingApp = MobileApp
+ { maContext = defaultMobileContext
+ , maView = \_userState -> pure $ Button ButtonConfig
+ { bcLabel = "crash"
+ , bcAction = throwIO (userError "button-boom")
+ , bcFontConfig = Nothing
+ }
+ }
+ ctxPtr <- newAppContext crashingApp
+ -- First render to register the button callback
+ haskellRenderUI ctxPtr
+ -- Dispatch the button, which throws — handler overwrites view
+ haskellOnUIEvent ctxPtr 0
+ isError <- viewIsErrorWidget ctxPtr
+ assertBool "view should be error widget after button callback exception" isError
+ freeAppContext ctxPtr
+
+ , testCase "dismiss restores original view after transient error" $ do
+ -- Transient error: throws once, then succeeds
+ shouldThrow <- newIORef True
+ let transientView _userState = do
+ throwing <- readIORef shouldThrow
+ if throwing
+ then do
+ writeIORef shouldThrow False
+ throwIO (userError "transient-error")
+ else pure $ Text TextConfig { tcLabel = "recovered", tcFontConfig = Nothing }
+ transientApp = MobileApp
+ { maContext = defaultMobileContext
+ , maView = transientView
+ }
+ ctxPtr <- newAppContext transientApp
+ -- First render throws, error widget shown, flag cleared
+ haskellRenderUI ctxPtr
+ isError <- viewIsErrorWidget ctxPtr
+ assertBool "should show error widget" isError
+ -- Dispatch callback 0 (the dismiss button in the error widget).
+ -- This restores the original transientView, which now succeeds.
+ haskellOnUIEvent ctxPtr 0
+ isStillError <- viewIsErrorWidget ctxPtr
+ assertBool "should no longer show error widget after dismiss" (not isStillError)
+ freeAppContext ctxPtr
+
+ , testCase "onError callback fires on exception" $ do
+ ref <- newIORef (Nothing :: Maybe String)
+ let ctx = MobileContext
+ { onLifecycle = \_ -> pure ()
+ , onError = \exc -> writeIORef ref (Just (show exc))
+ }
+ crashingApp = MobileApp
+ { maContext = ctx
+ , maView = \_userState -> throwIO (userError "onError-test")
+ }
+ ctxPtr <- newAppContext crashingApp
+ haskellRenderUI ctxPtr
+ firedValue <- readIORef ref
+ case firedValue of
+ Nothing -> assertFailure "onError callback should have been fired"
+ Just msg -> assertBool "onError should receive the exception" ("onError-test" `isInfixOf` msg)
+ freeAppContext ctxPtr
+
+ , testCase "exception in onError does not crash" $ do
+ let ctx = MobileContext
+ { onLifecycle = \_ -> pure ()
+ , onError = \_ -> throwIO (userError "secondary-boom")
+ }
+ crashingApp = MobileApp
+ { maContext = ctx
+ , maView = \_userState -> throwIO (userError "primary-boom")
+ }
+ ctxPtr <- newAppContext crashingApp
+ -- Should not crash despite both view and onError throwing
+ result <- try @IOException (haskellRenderUI ctxPtr)
+ case result of
+ Left exc -> assertFailure ("haskellRenderUI should not throw, but got: " ++ show exc)
+ Right () -> pure ()
+ freeAppContext ctxPtr
+
+ , testCase "exception in lifecycle handler is caught" $ do
+ let crashingApp = MobileApp
+ { maContext = MobileContext
+ { onLifecycle = \_ -> throwIO (userError "lifecycle-boom")
+ , onError = \_ -> pure ()
+ }
+ , maView = \_userState -> pure (Text TextConfig { tcLabel = "dummy", tcFontConfig = Nothing })
+ }
+ ctxPtr <- newAppContext crashingApp
+ -- Should not crash
+ result <- try @IOException (haskellOnLifecycle ctxPtr 0)
+ case result of
+ Left exc -> assertFailure ("haskellOnLifecycle should not throw, but got: " ++ show exc)
+ Right () -> pure ()
+ freeAppContext ctxPtr
]
diff --git a/test/TextInputDemoMain.hs b/test/TextInputDemoMain.hs
new file mode 100644
index 00000000..c2919454
--- /dev/null
+++ b/test/TextInputDemoMain.hs
@@ -0,0 +1,15 @@
+{-# LANGUAGE OverloadedStrings #-}
+-- | Mobile entry point for the text-input-demo test app.
+--
+-- Used by the emulator and simulator TextInput integration tests.
+-- Starts directly in text-input-demo mode so no runtime switching is needed.
+module Main where
+
+import Foreign.Ptr (Ptr)
+import HaskellMobile (startMobileApp, platformLog, AppContext)
+import HaskellMobile.App (textInputDemoApp)
+
+main :: IO (Ptr AppContext)
+main = do
+ platformLog "TextInput demo app registered"
+ startMobileApp textInputDemoApp
diff --git a/test/android/buttons.sh b/test/android/buttons.sh
new file mode 100755
index 00000000..ceeaa78b
--- /dev/null
+++ b/test/android/buttons.sh
@@ -0,0 +1,80 @@
+#!/usr/bin/env bash
+# Android buttons test: 5-tap sequence (+, +, -, -, -) verifying counter state transitions.
+#
+# Required env vars (set by emulator-all.nix harness):
+# ADB, EMULATOR_SERIAL, COUNTER_APK, PACKAGE, ACTIVITY, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+install_apk "$COUNTER_APK" || { echo "FAIL: install_apk"; exit 1; }
+
+LOGCAT_FILE="$WORK_DIR/buttons_log.txt"
+
+"$ADB" -s "$EMULATOR_SERIAL" logcat -c
+> "$LOGCAT_FILE"
+"$ADB" -s "$EMULATOR_SERIAL" logcat '*:I' > "$LOGCAT_FILE" 2>&1 &
+LOGCAT_STREAM_PID=$!
+
+"$ADB" -s "$EMULATOR_SERIAL" shell am start -n "$PACKAGE/$ACTIVITY"
+
+# Wait for initial render
+wait_for_logcat "setStrProp.*Counter: 0" 120
+WAIT_RC=$?
+if [ $WAIT_RC -eq 2 ]; then
+ dump_logcat "buttons"
+ echo "FATAL: Native library failed to load — aborting"
+ kill "$LOGCAT_STREAM_PID" 2>/dev/null || true
+ exit 1
+fi
+sleep 5
+
+assert_logcat "$LOGCAT_FILE" "setStrProp.*Counter: 0" "Counter: 0 at start"
+
+# Tap 1: + → Counter: 1
+echo "=== Tap 1: + (expect Counter: 1) ==="
+tap_button "+" || "$ADB" -s "$EMULATOR_SERIAL" shell input tap 300 600
+sleep 3
+assert_logcat "$LOGCAT_FILE" "setStrProp.*Counter: 1" "Counter: 1 after tap 1"
+
+# Tap 2: + → Counter: 2
+echo "=== Tap 2: + (expect Counter: 2) ==="
+tap_button "+" || "$ADB" -s "$EMULATOR_SERIAL" shell input tap 300 600
+sleep 3
+assert_logcat "$LOGCAT_FILE" "setStrProp.*Counter: 2" "Counter: 2 after tap 2"
+
+# Tap 3: - → Counter: 1 again (expect ≥2 occurrences)
+echo "=== Tap 3: - (expect Counter: 1 again) ==="
+tap_button "-" || "$ADB" -s "$EMULATOR_SERIAL" shell input tap 700 600
+sleep 3
+count_1=$(grep -c 'setStrProp.*Counter: 1' "$LOGCAT_FILE" 2>/dev/null || echo "0")
+if [ "$count_1" -ge 2 ]; then
+ echo "PASS: Counter: 1 seen $count_1 times (tap 3)"
+else
+ echo "FAIL: Counter: 1 seen $count_1 times, expected >=2 (tap 3)"
+ EXIT_CODE=1
+fi
+
+# Tap 4: - → Counter: 0 again (expect ≥2 occurrences)
+echo "=== Tap 4: - (expect Counter: 0 again) ==="
+tap_button "-" || "$ADB" -s "$EMULATOR_SERIAL" shell input tap 700 600
+sleep 3
+count_0=$(grep -c 'setStrProp.*Counter: 0' "$LOGCAT_FILE" 2>/dev/null || echo "0")
+if [ "$count_0" -ge 2 ]; then
+ echo "PASS: Counter: 0 seen $count_0 times (tap 4)"
+else
+ echo "FAIL: Counter: 0 seen $count_0 times, expected >=2 (tap 4)"
+ EXIT_CODE=1
+fi
+
+# Tap 5: - → Counter: -1
+echo "=== Tap 5: - (expect Counter: -1) ==="
+tap_button "-" || "$ADB" -s "$EMULATOR_SERIAL" shell input tap 700 600
+sleep 3
+assert_logcat "$LOGCAT_FILE" "setStrProp.*Counter: -1" "Counter: -1 after tap 5"
+
+kill "$LOGCAT_STREAM_PID" 2>/dev/null || true
+"$ADB" -s "$EMULATOR_SERIAL" uninstall "$PACKAGE" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/android/helpers.sh b/test/android/helpers.sh
new file mode 100755
index 00000000..a6251965
--- /dev/null
+++ b/test/android/helpers.sh
@@ -0,0 +1,168 @@
+#!/usr/bin/env bash
+# Common helper functions for Android emulator test scripts.
+# Source this file; do not run directly.
+#
+# Required env vars (set by emulator-all.nix harness):
+# ADB — path to adb binary
+# EMULATOR_SERIAL — e.g. emulator-5554
+# PACKAGE — me.jappie.haskellmobile
+# ACTIVITY — .MainActivity
+# WORK_DIR — temp dir for scratch files
+
+# install_apk APK_PATH
+# Installs the given APK with up to 3 attempts, 10s delay between retries.
+install_apk() {
+ local apk_path="$1"
+ local install_ok=0
+ for attempt in 1 2 3; do
+ if "$ADB" -s "$EMULATOR_SERIAL" install -t "$apk_path" 2>&1; then
+ install_ok=1
+ break
+ fi
+ echo "Install attempt $attempt failed, retrying in 10s..."
+ sleep 10
+ done
+ if [ $install_ok -eq 0 ]; then
+ echo "ERROR: Failed to install $apk_path after 3 attempts"
+ return 1
+ fi
+ echo "APK installed: $apk_path"
+ return 0
+}
+
+# Fatal patterns that indicate the native library failed to load.
+# When any of these appear in logcat, further retries are pointless.
+FATAL_PATTERNS="UnsatisfiedLinkError|dlopen failed|cannot locate symbol|SIGABRT|SIGSEGV|Fatal signal"
+
+# check_fatal_logcat
+# Checks logcat for fatal native-library errors.
+# If found, prints the relevant lines and returns 0 (meaning "fatal found").
+# Returns 1 if no fatal error detected.
+check_fatal_logcat() {
+ local logcat_poll="$WORK_DIR/logcat_fatal.txt"
+ "$ADB" -s "$EMULATOR_SERIAL" logcat -d '*:E' > "$logcat_poll" 2>&1
+ if grep -qE "$FATAL_PATTERNS" "$logcat_poll" 2>/dev/null; then
+ echo ""
+ echo "=== FATAL: Native library loading error detected ==="
+ grep -E "$FATAL_PATTERNS" "$logcat_poll" | tail -20
+ echo "=== End fatal logcat ==="
+ echo ""
+ return 0
+ fi
+ return 1
+}
+
+# dump_logcat LABEL
+# Dumps recent logcat errors to stdout for CI visibility.
+dump_logcat() {
+ local label="$1"
+ local logcat_dump="$WORK_DIR/logcat_dump_${label}.txt"
+ "$ADB" -s "$EMULATOR_SERIAL" logcat -d '*:W' > "$logcat_dump" 2>&1
+ echo ""
+ echo "=== Logcat dump ($label) — last 40 warning/error lines ==="
+ tail -40 "$logcat_dump"
+ echo "=== End logcat dump ==="
+ echo ""
+}
+
+# wait_for_logcat PATTERN TIMEOUT_SECONDS
+# Polls logcat dump every 2s until PATTERN is found.
+# Also checks for fatal native-library errors each poll cycle.
+# Returns 0 on success, 1 on timeout, 2 on fatal crash detected.
+wait_for_logcat() {
+ local pattern="$1"
+ local timeout_seconds="$2"
+ local logcat_poll="$WORK_DIR/logcat_poll.txt"
+ local elapsed=0
+ while [ $elapsed -lt "$timeout_seconds" ]; do
+ "$ADB" -s "$EMULATOR_SERIAL" logcat -d '*:I' > "$logcat_poll" 2>&1
+ if grep -q "$pattern" "$logcat_poll" 2>/dev/null; then
+ echo "Found '$pattern' after ~${elapsed}s"
+ return 0
+ fi
+ # Check for fatal errors every 10s to avoid spamming adb
+ if [ $((elapsed % 10)) -eq 0 ] && [ $elapsed -gt 0 ]; then
+ if check_fatal_logcat; then
+ echo "ERROR: Fatal crash detected while waiting for '$pattern'"
+ return 2
+ fi
+ fi
+ sleep 2
+ elapsed=$((elapsed + 2))
+ done
+ echo "WARNING: '$pattern' not found after ${timeout_seconds}s"
+ # One last check: was it a crash?
+ if check_fatal_logcat; then
+ return 2
+ fi
+ return 1
+}
+
+# tap_button BUTTON_TEXT
+# Uses uiautomator dump to find a button by text, extract its bounds,
+# compute the centre, and issue an adb input tap.
+tap_button() {
+ local button_text="$1"
+ local dump_file="$WORK_DIR/ui_tap.xml"
+ local dump_ok=0
+
+ for attempt in 1 2 3; do
+ if "$ADB" -s "$EMULATOR_SERIAL" shell uiautomator dump /data/local/tmp/ui.xml 2>&1 | grep -q "dumped"; then
+ "$ADB" -s "$EMULATOR_SERIAL" pull /data/local/tmp/ui.xml "$dump_file" 2>/dev/null
+ dump_ok=1
+ break
+ fi
+ echo " uiautomator dump attempt $attempt failed, retrying in 5s..."
+ sleep 5
+ done
+
+ if [ $dump_ok -eq 0 ]; then
+ echo "WARNING: Could not dump UI hierarchy for '$button_text' tap"
+ return 1
+ fi
+
+ local bounds=""
+ if [ "$button_text" = "+" ]; then
+ bounds=$(grep -o 'text="[+]"[^>]*bounds="\[[0-9]*,[0-9]*\]\[[0-9]*,[0-9]*\]"' "$dump_file" 2>/dev/null \
+ || grep -o 'text="\+"[^>]*bounds="\[[0-9]*,[0-9]*\]\[[0-9]*,[0-9]*\]"' "$dump_file" 2>/dev/null \
+ || echo "")
+ else
+ bounds=$(grep -o "text=\"$button_text\"[^>]*bounds=\"\[[0-9]*,[0-9]*\]\[[0-9]*,[0-9]*\]\"" "$dump_file" 2>/dev/null \
+ || echo "")
+ fi
+
+ if [ -z "$bounds" ]; then
+ echo "WARNING: Could not find '$button_text' button bounds in UI dump"
+ return 1
+ fi
+
+ local coords
+ coords=$(echo "$bounds" | head -1 | grep -o '\[[0-9]*,[0-9]*\]\[[0-9]*,[0-9]*\]')
+ local left top right bottom
+ left=$(echo "$coords" | sed 's/^\[//;s/,.*//')
+ top=$(echo "$coords" | sed 's/^\[[0-9]*,//;s/\].*//')
+ right=$(echo "$coords" | sed 's/.*\]\[//;s/,.*//')
+ bottom=$(echo "$coords" | sed 's/.*,//;s/\]//')
+
+ local tap_x tap_y
+ tap_x=$(( (left + right) / 2 ))
+ tap_y=$(( (top + bottom) / 2 ))
+ echo "Tapping '$button_text' at ($tap_x, $tap_y)"
+ "$ADB" -s "$EMULATOR_SERIAL" shell input tap "$tap_x" "$tap_y"
+ return 0
+}
+
+# assert_logcat LOGFILE PATTERN LABEL
+# Greps LOGFILE for PATTERN, prints PASS/FAIL with LABEL.
+# Sets EXIT_CODE=1 on failure (EXIT_CODE must be declared in caller).
+assert_logcat() {
+ local logfile="$1"
+ local pattern="$2"
+ local label="$3"
+ if grep -q "$pattern" "$logfile" 2>/dev/null; then
+ echo "PASS: $label"
+ else
+ echo "FAIL: $label"
+ EXIT_CODE=1
+ fi
+}
diff --git a/test/android/image.sh b/test/android/image.sh
new file mode 100755
index 00000000..a80316b6
--- /dev/null
+++ b/test/android/image.sh
@@ -0,0 +1,45 @@
+#!/usr/bin/env bash
+# Android image test: install image APK, assert all 3 ImageSource paths are exercised.
+#
+# Required env vars (set by emulator-all.nix harness):
+# ADB, EMULATOR_SERIAL, IMAGE_APK, PACKAGE, ACTIVITY, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+install_apk "$IMAGE_APK" || { echo "FAIL: install_apk"; exit 1; }
+
+"$ADB" -s "$EMULATOR_SERIAL" logcat -c
+"$ADB" -s "$EMULATOR_SERIAL" shell am start -n "$PACKAGE/$ACTIVITY"
+
+wait_for_logcat "setRoot" 120
+WAIT_RC=$?
+if [ $WAIT_RC -eq 2 ]; then
+ dump_logcat "image"
+ echo "FATAL: Native library failed to load — aborting"
+ exit 1
+fi
+sleep 5
+
+LOGCAT_FILE="$WORK_DIR/image_logcat.txt"
+"$ADB" -s "$EMULATOR_SERIAL" logcat -d '*:I' > "$LOGCAT_FILE" 2>&1
+
+# All 3 Image nodes created (type=6)
+assert_logcat "$LOGCAT_FILE" "createNode.*type=6" "createNode(type=6) Image node"
+
+# Test case 1: ImageResource — setStrProp with imageResource
+assert_logcat "$LOGCAT_FILE" "setStrProp.*imageResource.*ic_launcher" "ImageResource: setStrProp with resource name"
+
+# Test case 2: ImageData — setImageData called
+assert_logcat "$LOGCAT_FILE" "setImageData.*node=.*bytes" "ImageData: setImageData called"
+
+# Test case 3: ImageFile — setStrProp with imageFile
+assert_logcat "$LOGCAT_FILE" "setStrProp.*imageFile.*/nonexistent/test.png" "ImageFile: setStrProp with file path"
+
+# ScaleType set on image nodes
+assert_logcat "$LOGCAT_FILE" "setNumProp.*scaleType" "ScaleType: setNumProp called"
+
+"$ADB" -s "$EMULATOR_SERIAL" uninstall "$PACKAGE" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/android/lifecycle.sh b/test/android/lifecycle.sh
new file mode 100755
index 00000000..ecf08a33
--- /dev/null
+++ b/test/android/lifecycle.sh
@@ -0,0 +1,37 @@
+#!/usr/bin/env bash
+# Android lifecycle test: install counter app, launch, assert lifecycle events.
+#
+# Required env vars (set by emulator-all.nix harness):
+# ADB, EMULATOR_SERIAL, COUNTER_APK, PACKAGE, ACTIVITY, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+install_apk "$COUNTER_APK" || { echo "FAIL: install_apk"; exit 1; }
+
+"$ADB" -s "$EMULATOR_SERIAL" logcat -c
+"$ADB" -s "$EMULATOR_SERIAL" shell am start -n "$PACKAGE/$ACTIVITY"
+
+wait_for_logcat "Android UI bridge initialized" 60
+WAIT_RC=$?
+if [ $WAIT_RC -eq 2 ]; then
+ dump_logcat "lifecycle"
+ echo "FATAL: Native library failed to load — aborting"
+ exit 1
+fi
+
+# Dump final logcat for assertions
+LOGCAT_FILE="$WORK_DIR/lifecycle_logcat.txt"
+"$ADB" -s "$EMULATOR_SERIAL" logcat -d '*:I' > "$LOGCAT_FILE" 2>&1
+
+assert_logcat "$LOGCAT_FILE" "Lifecycle: Create" "Lifecycle: Create"
+assert_logcat "$LOGCAT_FILE" "Lifecycle: Resume" "Lifecycle: Resume"
+assert_logcat "$LOGCAT_FILE" "Android UI bridge initialized" "Android UI bridge initialized"
+assert_logcat "$LOGCAT_FILE" "setRoot" "setRoot"
+assert_logcat "$LOGCAT_FILE" "setStrProp.*Counter: 0" "setStrProp Counter: 0"
+assert_logcat "$LOGCAT_FILE" "setHandler.*click" "setHandler click"
+
+"$ADB" -s "$EMULATOR_SERIAL" uninstall "$PACKAGE" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/android/locale.sh b/test/android/locale.sh
new file mode 100755
index 00000000..0c2f5f09
--- /dev/null
+++ b/test/android/locale.sh
@@ -0,0 +1,37 @@
+#!/usr/bin/env bash
+# Android locale test: launch counter app, assert locale detection logs.
+#
+# haskellLogLocale is called from JNI_OnLoad, logging:
+# "Locale raw: "
+# "Locale parsed: "
+#
+# Required env vars (set by emulator-all.nix harness):
+# ADB, EMULATOR_SERIAL, COUNTER_APK, PACKAGE, ACTIVITY, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+install_apk "$COUNTER_APK" || { echo "FAIL: install_apk"; exit 1; }
+
+"$ADB" -s "$EMULATOR_SERIAL" logcat -c
+"$ADB" -s "$EMULATOR_SERIAL" shell am start -n "$PACKAGE/$ACTIVITY"
+
+wait_for_logcat "Locale parsed:" 60
+WAIT_RC=$?
+if [ $WAIT_RC -eq 2 ]; then
+ dump_logcat "locale"
+ echo "FATAL: Native library failed to load — aborting"
+ exit 1
+fi
+
+LOGCAT_FILE="$WORK_DIR/locale_logcat.txt"
+"$ADB" -s "$EMULATOR_SERIAL" logcat -d '*:I' > "$LOGCAT_FILE" 2>&1
+
+assert_logcat "$LOGCAT_FILE" "Locale raw:" "Locale raw tag logged"
+assert_logcat "$LOGCAT_FILE" "Locale parsed:" "Locale parsed tag logged"
+
+"$ADB" -s "$EMULATOR_SERIAL" shell am force-stop "$PACKAGE" 2>/dev/null || true
+"$ADB" -s "$EMULATOR_SERIAL" uninstall "$PACKAGE" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/android/node-pool.sh b/test/android/node-pool.sh
new file mode 100644
index 00000000..39dd2f16
--- /dev/null
+++ b/test/android/node-pool.sh
@@ -0,0 +1,47 @@
+#!/usr/bin/env bash
+# Node pool integration test (Android).
+#
+# Verifies that all 300 nodes render without pool exhaustion.
+# Requires NODEPOOL_APK (built with dynamicNodePool=true) to be set.
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+source "$SCRIPT_DIR/helpers.sh"
+
+EXIT_CODE=0
+
+echo "=== Node Pool Test ==="
+
+# Install the node-pool APK (built with dynamic pool)
+"$ADB" -s "$EMULATOR_SERIAL" shell am force-stop "$PACKAGE" 2>/dev/null || true
+"$ADB" -s "$EMULATOR_SERIAL" logcat -c 2>/dev/null || true
+install_apk "$NODEPOOL_APK"
+
+echo "Launching node-pool test app..."
+"$ADB" -s "$EMULATOR_SERIAL" shell am start -n "$PACKAGE/$ACTIVITY" 2>&1
+sleep 5
+
+# Wait for setRoot (full UI rendered)
+wait_for_logcat "setRoot" 30
+
+LOGFILE="$WORK_DIR/logcat_nodepool.txt"
+"$ADB" -s "$EMULATOR_SERIAL" logcat -d '*:I' > "$LOGFILE" 2>&1
+
+# Assert: setRoot was called (full UI rendered)
+assert_logcat "$LOGFILE" "setRoot" "setRoot called — full UI rendered"
+
+# Assert: node 300 was created (1 Column + 299 Text = 300 nodes)
+assert_logcat "$LOGFILE" "createNode.*-> 300" "All 300 nodes created"
+
+# Assert: no pool exhaustion
+if grep -q "Node pool exhausted" "$LOGFILE" 2>/dev/null; then
+ echo "FAIL: Node pool exhaustion detected"
+ EXIT_CODE=1
+else
+ echo "PASS: No pool exhaustion"
+fi
+
+# Uninstall
+"$ADB" -s "$EMULATOR_SERIAL" uninstall "$PACKAGE" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/android/permission.sh b/test/android/permission.sh
new file mode 100644
index 00000000..cca1f24c
--- /dev/null
+++ b/test/android/permission.sh
@@ -0,0 +1,35 @@
+#!/usr/bin/env bash
+# Android permission test: install permission APK, pre-grant camera, tap button,
+# assert that the permission result callback fires.
+#
+# Required env vars (set by emulator-all.nix harness):
+# ADB, EMULATOR_SERIAL, PERMISSION_APK, PACKAGE, ACTIVITY, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+install_apk "$PERMISSION_APK" || { echo "FAIL: install_apk"; exit 1; }
+
+# Pre-grant camera permission so the system dialog does not appear
+"$ADB" -s "$EMULATOR_SERIAL" shell pm grant "$PACKAGE" android.permission.CAMERA
+
+"$ADB" -s "$EMULATOR_SERIAL" logcat -c
+"$ADB" -s "$EMULATOR_SERIAL" shell am start -n "$PACKAGE/$ACTIVITY"
+
+wait_for_logcat "setRoot" 120 || true
+sleep 5
+
+# Tap the "Request Camera" button
+tap_button "Request Camera" || { echo "FAIL: could not tap Request Camera"; EXIT_CODE=1; }
+sleep 3
+
+LOGCAT_FILE="$WORK_DIR/permission_logcat.txt"
+"$ADB" -s "$EMULATOR_SERIAL" logcat -d '*:I' > "$LOGCAT_FILE" 2>&1
+
+assert_logcat "$LOGCAT_FILE" "Permission result: PermissionGranted" "permission callback fires with PermissionGranted"
+assert_logcat "$LOGCAT_FILE" "permission_request\|PermissionBridge" "permission bridge log present"
+
+"$ADB" -s "$EMULATOR_SERIAL" uninstall "$PACKAGE" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/android/scroll.sh b/test/android/scroll.sh
new file mode 100755
index 00000000..029e44d1
--- /dev/null
+++ b/test/android/scroll.sh
@@ -0,0 +1,101 @@
+#!/usr/bin/env bash
+# Android scroll test: install scroll APK, assert ScrollView renders, swipe reveals button, tap it.
+#
+# Required env vars (set by emulator-all.nix harness):
+# ADB, EMULATOR_SERIAL, SCROLL_APK, PACKAGE, ACTIVITY, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+install_apk "$SCROLL_APK" || { echo "FAIL: install_apk"; exit 1; }
+
+"$ADB" -s "$EMULATOR_SERIAL" logcat -c
+"$ADB" -s "$EMULATOR_SERIAL" shell am start -n "$PACKAGE/$ACTIVITY"
+
+wait_for_logcat "setRoot" 120
+WAIT_RC=$?
+if [ $WAIT_RC -eq 2 ]; then
+ dump_logcat "scroll"
+ echo "FATAL: Native library failed to load — aborting"
+ exit 1
+fi
+sleep 5
+
+LOGCAT_FILE="$WORK_DIR/scroll_logcat.txt"
+"$ADB" -s "$EMULATOR_SERIAL" logcat -d '*:I' > "$LOGCAT_FILE" 2>&1
+
+assert_logcat "$LOGCAT_FILE" "createNode.*type=5" "createNode(type=5) scroll view"
+
+# Verify ScrollView in view hierarchy
+SCROLL_DUMP="$WORK_DIR/scroll_ui.xml"
+scroll_dump_ok=0
+for attempt in 1 2 3; do
+ if "$ADB" -s "$EMULATOR_SERIAL" shell uiautomator dump /data/local/tmp/ui.xml 2>&1 | grep -q "dumped"; then
+ "$ADB" -s "$EMULATOR_SERIAL" pull /data/local/tmp/ui.xml "$SCROLL_DUMP" 2>/dev/null
+ scroll_dump_ok=1
+ break
+ fi
+ echo " uiautomator dump attempt $attempt failed, retrying in 5s..."
+ sleep 5
+done
+
+if [ $scroll_dump_ok -eq 1 ]; then
+ if grep -q 'android.widget.ScrollView' "$SCROLL_DUMP" 2>/dev/null; then
+ echo "PASS: android.widget.ScrollView in view hierarchy"
+ else
+ echo "FAIL: android.widget.ScrollView not in view hierarchy"
+ EXIT_CODE=1
+ fi
+else
+ echo "FAIL: Could not dump scroll view hierarchy"
+ EXIT_CODE=1
+fi
+
+# Swipe up to reveal Reached Bottom button
+echo "=== Swipe up to reveal Reached Bottom ==="
+"$ADB" -s "$EMULATOR_SERIAL" shell input swipe 540 1500 540 500
+sleep 3
+
+SCROLL_DUMP2="$WORK_DIR/scroll_ui2.xml"
+scroll_dump2_ok=0
+for attempt in 1 2 3; do
+ if "$ADB" -s "$EMULATOR_SERIAL" shell uiautomator dump /data/local/tmp/ui.xml 2>&1 | grep -q "dumped"; then
+ "$ADB" -s "$EMULATOR_SERIAL" pull /data/local/tmp/ui.xml "$SCROLL_DUMP2" 2>/dev/null
+ scroll_dump2_ok=1
+ break
+ fi
+ echo " uiautomator dump attempt $attempt failed, retrying in 5s..."
+ sleep 5
+done
+
+if [ $scroll_dump2_ok -eq 1 ]; then
+ if grep -q 'Reached Bottom' "$SCROLL_DUMP2" 2>/dev/null; then
+ echo "PASS: Reached Bottom visible after swipe"
+ else
+ echo "FAIL: Reached Bottom not visible after swipe"
+ EXIT_CODE=1
+ fi
+else
+ echo "FAIL: Could not dump view hierarchy after swipe"
+ EXIT_CODE=1
+fi
+
+# Tap Reached Bottom button
+echo "=== Tap Reached Bottom ==="
+tap_done=0
+if [ $scroll_dump2_ok -eq 1 ]; then
+ tap_button "Reached Bottom" && tap_done=1 || true
+fi
+if [ $tap_done -eq 0 ]; then
+ echo "Using fallback tap at (540, 1400)"
+ "$ADB" -s "$EMULATOR_SERIAL" shell input tap 540 1400
+fi
+sleep 5
+
+"$ADB" -s "$EMULATOR_SERIAL" logcat -d '*:I' > "$LOGCAT_FILE" 2>&1
+assert_logcat "$LOGCAT_FILE" "Click dispatched" "Click dispatched after Reached Bottom tap"
+
+"$ADB" -s "$EMULATOR_SERIAL" uninstall "$PACKAGE" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/android/styled.sh b/test/android/styled.sh
new file mode 100755
index 00000000..09e3edf4
--- /dev/null
+++ b/test/android/styled.sh
@@ -0,0 +1,39 @@
+#!/usr/bin/env bash
+# Android styled test: install counter APK, assert setNumProp calls for fontSize, padding, and gravity.
+#
+# The counter app wraps its label with Styled (WidgetStyle (Just 16.0) (Just AlignCenter)),
+# so rendering must trigger setNumProp for fontSize, padding, and gravity.
+#
+# Required env vars (set by emulator-all.nix harness):
+# ADB, EMULATOR_SERIAL, COUNTER_APK, PACKAGE, ACTIVITY, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+install_apk "$COUNTER_APK" || { echo "FAIL: install_apk"; exit 1; }
+
+"$ADB" -s "$EMULATOR_SERIAL" logcat -c
+"$ADB" -s "$EMULATOR_SERIAL" shell am start -n "$PACKAGE/$ACTIVITY"
+
+wait_for_logcat "setRoot" 120
+WAIT_RC=$?
+if [ $WAIT_RC -eq 2 ]; then
+ dump_logcat "styled"
+ echo "FATAL: Native library failed to load — aborting"
+ exit 1
+fi
+sleep 5
+
+LOGCAT_FILE="$WORK_DIR/styled_logcat.txt"
+"$ADB" -s "$EMULATOR_SERIAL" logcat -d '*:I' > "$LOGCAT_FILE" 2>&1
+
+assert_logcat "$LOGCAT_FILE" "setNumProp.*fontSize" "setNumProp dispatched for fontSize"
+assert_logcat "$LOGCAT_FILE" "setNumProp.*padding" "setNumProp dispatched for padding"
+assert_logcat "$LOGCAT_FILE" "setNumProp.*gravity" "setNumProp dispatched for gravity"
+assert_logcat "$LOGCAT_FILE" "setStrProp.*color" "setStrProp dispatched for color (text color)"
+assert_logcat "$LOGCAT_FILE" "setStrProp.*bgColor" "setStrProp dispatched for bgColor (background color)"
+
+"$ADB" -s "$EMULATOR_SERIAL" uninstall "$PACKAGE" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/android/textinput.sh b/test/android/textinput.sh
new file mode 100644
index 00000000..cee7b6f8
--- /dev/null
+++ b/test/android/textinput.sh
@@ -0,0 +1,58 @@
+#!/usr/bin/env bash
+# Android textinput test: install textinput APK, assert InputType is applied via setNumProp.
+#
+# Required env vars (set by emulator-all.nix harness):
+# ADB, EMULATOR_SERIAL, TEXTINPUT_APK, PACKAGE, ACTIVITY, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+install_apk "$TEXTINPUT_APK" || { echo "FAIL: install_apk"; exit 1; }
+
+"$ADB" -s "$EMULATOR_SERIAL" logcat -c
+"$ADB" -s "$EMULATOR_SERIAL" shell am start -n "$PACKAGE/$ACTIVITY"
+
+wait_for_logcat "setRoot" 120
+WAIT_RC=$?
+if [ $WAIT_RC -eq 2 ]; then
+ dump_logcat "textinput"
+ echo "FATAL: Native library failed to load — aborting"
+ exit 1
+fi
+sleep 5
+
+LOGCAT_FILE="$WORK_DIR/textinput_logcat.txt"
+"$ADB" -s "$EMULATOR_SERIAL" logcat -d '*:I' > "$LOGCAT_FILE" 2>&1
+
+assert_logcat "$LOGCAT_FILE" "createNode.*type=4" "createNode(type=4) TextInput node"
+assert_logcat "$LOGCAT_FILE" "setNumProp.*inputType=1.*android=8194" "setNumProp InputNumber -> TYPE_CLASS_NUMBER|DECIMAL"
+
+# Verify EditText in view hierarchy
+TEXTINPUT_DUMP="$WORK_DIR/textinput_ui.xml"
+dump_ok=0
+for attempt in 1 2 3; do
+ if "$ADB" -s "$EMULATOR_SERIAL" shell uiautomator dump /data/local/tmp/ui.xml 2>&1 | grep -q "dumped"; then
+ "$ADB" -s "$EMULATOR_SERIAL" pull /data/local/tmp/ui.xml "$TEXTINPUT_DUMP" 2>/dev/null
+ dump_ok=1
+ break
+ fi
+ echo " uiautomator dump attempt $attempt failed, retrying in 5s..."
+ sleep 5
+done
+
+if [ $dump_ok -eq 1 ]; then
+ if grep -q 'android.widget.EditText' "$TEXTINPUT_DUMP" 2>/dev/null; then
+ echo "PASS: android.widget.EditText in view hierarchy"
+ else
+ echo "FAIL: android.widget.EditText not in view hierarchy"
+ EXIT_CODE=1
+ fi
+else
+ echo "FAIL: Could not dump textinput view hierarchy"
+ EXIT_CODE=1
+fi
+
+"$ADB" -s "$EMULATOR_SERIAL" uninstall "$PACKAGE" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/android/ui.sh b/test/android/ui.sh
new file mode 100755
index 00000000..cc0ec89e
--- /dev/null
+++ b/test/android/ui.sh
@@ -0,0 +1,43 @@
+#!/usr/bin/env bash
+# Android UI test: install counter app, launch, assert initial render, tap +, assert Counter: 1.
+#
+# Required env vars (set by emulator-all.nix harness):
+# ADB, EMULATOR_SERIAL, COUNTER_APK, PACKAGE, ACTIVITY, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+install_apk "$COUNTER_APK" || { echo "FAIL: install_apk"; exit 1; }
+
+"$ADB" -s "$EMULATOR_SERIAL" logcat -c
+"$ADB" -s "$EMULATOR_SERIAL" shell am start -n "$PACKAGE/$ACTIVITY"
+
+wait_for_logcat "setRoot" 120
+WAIT_RC=$?
+if [ $WAIT_RC -eq 2 ]; then
+ dump_logcat "ui"
+ echo "FATAL: Native library failed to load — aborting"
+ exit 1
+fi
+sleep 5
+
+LOGCAT_FILE="$WORK_DIR/ui_logcat.txt"
+"$ADB" -s "$EMULATOR_SERIAL" logcat -d '*:I' > "$LOGCAT_FILE" 2>&1
+
+assert_logcat "$LOGCAT_FILE" "setRoot" "initial setRoot"
+assert_logcat "$LOGCAT_FILE" "setStrProp.*Counter: 0" "initial Counter: 0"
+assert_logcat "$LOGCAT_FILE" "setHandler.*click" "setHandler click"
+
+# Tap + button
+tap_button "+" || "$ADB" -s "$EMULATOR_SERIAL" shell input tap 300 600
+sleep 5
+
+"$ADB" -s "$EMULATOR_SERIAL" logcat -d '*:I' > "$LOGCAT_FILE" 2>&1
+
+assert_logcat "$LOGCAT_FILE" "Click dispatched" "Click dispatched after + tap"
+assert_logcat "$LOGCAT_FILE" "setStrProp.*Counter: 1" "Counter: 1 after + tap"
+
+"$ADB" -s "$EMULATOR_SERIAL" uninstall "$PACKAGE" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/ios/buttons.sh b/test/ios/buttons.sh
new file mode 100755
index 00000000..5c0405bf
--- /dev/null
+++ b/test/ios/buttons.sh
@@ -0,0 +1,71 @@
+#!/usr/bin/env bash
+# iOS buttons test: launch with --autotest-buttons, assert full counter sequence.
+#
+# Required env vars (set by simulator-all.nix harness):
+# SIM_UDID, BUNDLE_ID, COUNTER_APP, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+xcrun simctl install "$SIM_UDID" "$COUNTER_APP"
+echo "Counter app installed."
+
+BUTTONS_START=$(date "+%Y-%m-%d %H:%M:%S")
+
+LOG_FILE="$WORK_DIR/buttons_log.txt"
+> "$LOG_FILE"
+xcrun simctl spawn "$SIM_UDID" log stream \
+ --level info \
+ --predicate "process == \"HaskellMobile\"" \
+ --style compact \
+ > "$LOG_FILE" 2>&1 &
+LOG_STREAM_PID=$!
+sleep 2
+
+xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID" --autotest-buttons
+
+# Wait for final value Counter: -1
+wait_for_log "$LOG_FILE" "setStrProp.*Counter: -1" 60
+WAIT_RC=$?
+if [ $WAIT_RC -eq 2 ]; then
+ dump_ios_log "$LOG_FILE" "buttons"
+ echo "FATAL: Native library failed to load — aborting"
+ exit 1
+fi
+
+kill "$LOG_STREAM_PID" 2>/dev/null || true
+sleep 1
+
+# Retrieve full log for reliable assertion; fall back to stream log if empty
+FULL_LOG="$WORK_DIR/buttons_full.txt"
+get_full_log "$BUTTONS_START" "$FULL_LOG"
+
+if ! grep -q "setStrProp" "$FULL_LOG" 2>/dev/null; then
+ echo " 'log show' empty, using stream log"
+ FULL_LOG="$LOG_FILE"
+fi
+
+assert_log "$FULL_LOG" "setStrProp.*Counter: 0" "Counter: 0 in sequence"
+assert_log "$FULL_LOG" "setStrProp.*Counter: 1" "Counter: 1 in sequence"
+assert_log "$FULL_LOG" "setStrProp.*Counter: 2" "Counter: 2 in sequence"
+assert_log "$FULL_LOG" "setStrProp.*Counter: -1" "Counter: -1 in sequence"
+
+# Warn (not fail) if occurrence counts are lower than expected (log deduplication)
+count_1=$(grep -c 'setStrProp.*Counter: 1' "$FULL_LOG" 2>/dev/null || echo "0")
+if [ "$count_1" -ge 2 ]; then
+ echo "PASS: Counter: 1 appeared $count_1 times"
+else
+ echo "WARN: Counter: 1 seen $count_1 time(s), expected 2 (log may deduplicate)"
+fi
+
+count_0=$(grep -c 'setStrProp.*Counter: 0' "$FULL_LOG" 2>/dev/null || echo "0")
+if [ "$count_0" -ge 2 ]; then
+ echo "PASS: Counter: 0 appeared $count_0 times"
+else
+ echo "WARN: Counter: 0 seen $count_0 time(s), expected 2 (log may deduplicate)"
+fi
+
+xcrun simctl uninstall "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/ios/helpers.sh b/test/ios/helpers.sh
new file mode 100755
index 00000000..edbb209a
--- /dev/null
+++ b/test/ios/helpers.sh
@@ -0,0 +1,101 @@
+#!/usr/bin/env bash
+# Common helper functions for iOS simulator test scripts.
+# Source this file; do not run directly.
+#
+# Required env vars (set by simulator-all.nix harness):
+# SIM_UDID — simulator UUID
+# BUNDLE_ID — me.jappie.haskellmobile
+# WORK_DIR — temp dir for log files
+
+# Fatal patterns that indicate the native library failed to load on iOS.
+# When any of these appear in the log, further retries are pointless.
+IOS_FATAL_PATTERNS="dyld: Library not loaded|Symbol not found|image not found|SIGABRT|SIGSEGV|Fatal signal|EXC_BAD_ACCESS|EXC_CRASH"
+
+# check_fatal_log LOGFILE
+# Checks log file for fatal native-library errors.
+# If found, prints the relevant lines and returns 0 (meaning "fatal found").
+# Returns 1 if no fatal error detected.
+check_fatal_log() {
+ local logfile="$1"
+ if grep -qE "$IOS_FATAL_PATTERNS" "$logfile" 2>/dev/null; then
+ echo ""
+ echo "=== FATAL: Native library loading error detected ==="
+ grep -E "$IOS_FATAL_PATTERNS" "$logfile" | tail -20
+ echo "=== End fatal log ==="
+ echo ""
+ return 0
+ fi
+ return 1
+}
+
+# dump_ios_log LOGFILE LABEL
+# Dumps recent log lines to stdout for CI visibility.
+dump_ios_log() {
+ local logfile="$1"
+ local label="$2"
+ echo ""
+ echo "=== Log dump ($label) — last 40 lines ==="
+ tail -40 "$logfile"
+ echo "=== End log dump ==="
+ echo ""
+}
+
+# wait_for_log LOGFILE PATTERN TIMEOUT_SECONDS
+# Polls LOGFILE for PATTERN every 2s.
+# Also checks for fatal native-library errors each poll cycle.
+# Returns 0 on success, 1 on timeout, 2 on fatal crash detected.
+wait_for_log() {
+ local logfile="$1"
+ local pattern="$2"
+ local timeout_seconds="$3"
+ local elapsed=0
+ while [ $elapsed -lt "$timeout_seconds" ]; do
+ if grep -q "$pattern" "$logfile" 2>/dev/null; then
+ echo "Found '$pattern' after ~${elapsed}s"
+ return 0
+ fi
+ # Check for fatal errors every 10s
+ if [ $((elapsed % 10)) -eq 0 ] && [ $elapsed -gt 0 ]; then
+ if check_fatal_log "$logfile"; then
+ echo "ERROR: Fatal crash detected while waiting for '$pattern'"
+ return 2
+ fi
+ fi
+ sleep 2
+ elapsed=$((elapsed + 2))
+ done
+ echo "WARNING: '$pattern' not found after ${timeout_seconds}s"
+ # One last check: was it a crash?
+ if check_fatal_log "$logfile"; then
+ return 2
+ fi
+ return 1
+}
+
+# assert_log LOGFILE PATTERN LABEL
+# Greps LOGFILE for PATTERN, prints PASS/FAIL with LABEL.
+# Sets EXIT_CODE=1 on failure (EXIT_CODE must be declared in caller).
+assert_log() {
+ local logfile="$1"
+ local pattern="$2"
+ local label="$3"
+ if grep -qE "$pattern" "$logfile" 2>/dev/null; then
+ echo "PASS: $label"
+ else
+ echo "FAIL: $label"
+ EXIT_CODE=1
+ fi
+}
+
+# get_full_log START_TIME OUTFILE
+# Retrieves persistent log entries since START_TIME for BUNDLE_ID into OUTFILE.
+get_full_log() {
+ local start_time="$1"
+ local outfile="$2"
+ xcrun simctl spawn "$SIM_UDID" log show \
+ --start "$start_time" \
+ --predicate "subsystem == \"$BUNDLE_ID\"" \
+ --style compact \
+ --info \
+ > "$outfile" 2>&1 || true
+}
diff --git a/test/ios/image.sh b/test/ios/image.sh
new file mode 100755
index 00000000..63970fbf
--- /dev/null
+++ b/test/ios/image.sh
@@ -0,0 +1,78 @@
+#!/usr/bin/env bash
+# iOS image test: install image app, launch, assert all 3 ImageSource paths are exercised.
+#
+# Required env vars (set by simulator-all.nix harness):
+# SIM_UDID, BUNDLE_ID, IMAGE_APP, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+xcrun simctl install "$SIM_UDID" "$IMAGE_APP"
+echo "Image app installed."
+
+IMAGE_START=$(date "+%Y-%m-%d %H:%M:%S")
+
+STREAM_LOG="$WORK_DIR/image_stream.txt"
+> "$STREAM_LOG"
+xcrun simctl spawn "$SIM_UDID" log stream \
+ --level info \
+ --predicate "subsystem == \"$BUNDLE_ID\"" \
+ --style compact \
+ > "$STREAM_LOG" 2>&1 &
+LOG_STREAM_PID=$!
+sleep 5
+
+xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID"
+
+render_done=0
+wait_for_log "$STREAM_LOG" "setRoot" 60
+WAIT_RC=$?
+if [ $WAIT_RC -eq 2 ]; then
+ dump_ios_log "$STREAM_LOG" "image"
+ echo "FATAL: Native library failed to load — aborting"
+ exit 1
+fi
+if [ $WAIT_RC -eq 0 ]; then
+ render_done=1
+fi
+
+if [ $render_done -eq 0 ]; then
+ echo "WARNING: setRoot not found — retrying with relaunch"
+ xcrun simctl terminate "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+ sleep 3
+ > "$STREAM_LOG"
+ xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID"
+ wait_for_log "$STREAM_LOG" "setRoot" 60 || true
+fi
+
+sleep 5
+
+kill "$LOG_STREAM_PID" 2>/dev/null || true
+sleep 1
+
+FULL_LOG="$WORK_DIR/image_full.txt"
+get_full_log "$IMAGE_START" "$FULL_LOG"
+
+if ! grep -q "setRoot" "$FULL_LOG" 2>/dev/null; then
+ echo " 'log show' empty/incomplete, using stream log"
+ FULL_LOG="$STREAM_LOG"
+fi
+
+# All 3 Image nodes created (type=6)
+assert_log "$FULL_LOG" "createNode\(type=6\)" "createNode(type=6) — UIImageView created"
+
+# Test case 1: ImageResource
+assert_log "$FULL_LOG" "setStrProp.*imageResource.*ic_launcher" "ImageResource path set"
+
+# Test case 2: ImageData
+assert_log "$FULL_LOG" "setImageData" "ImageData called"
+
+# Test case 3: ImageFile
+assert_log "$FULL_LOG" "setStrProp.*imageFile.*/nonexistent" "ImageFile path set"
+
+assert_log "$FULL_LOG" "setRoot" "setRoot"
+
+xcrun simctl uninstall "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/ios/lifecycle.sh b/test/ios/lifecycle.sh
new file mode 100755
index 00000000..f4bffac5
--- /dev/null
+++ b/test/ios/lifecycle.sh
@@ -0,0 +1,67 @@
+#!/usr/bin/env bash
+# iOS lifecycle test: install counter app, launch, assert lifecycle events.
+#
+# Required env vars (set by simulator-all.nix harness):
+# SIM_UDID, BUNDLE_ID, COUNTER_APP, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+xcrun simctl install "$SIM_UDID" "$COUNTER_APP"
+echo "Counter app installed."
+
+LOG_FILE="$WORK_DIR/lifecycle_log.txt"
+> "$LOG_FILE"
+xcrun simctl spawn "$SIM_UDID" log stream \
+ --level info \
+ --predicate "subsystem == \"$BUNDLE_ID\"" \
+ --style compact \
+ > "$LOG_FILE" 2>&1 &
+LOG_STREAM_PID=$!
+sleep 5
+
+xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID"
+
+# Poll for lifecycle events
+lifecycle_done=0
+wait_for_log "$LOG_FILE" "Lifecycle: Create" 60
+WAIT_RC=$?
+if [ $WAIT_RC -eq 2 ]; then
+ dump_ios_log "$LOG_FILE" "lifecycle"
+ echo "FATAL: Native library failed to load — aborting"
+ exit 1
+fi
+if [ $WAIT_RC -eq 0 ]; then
+ wait_for_log "$LOG_FILE" "Lifecycle: Resume" 5
+ WAIT_RC2=$?
+ if [ $WAIT_RC2 -eq 2 ]; then
+ dump_ios_log "$LOG_FILE" "lifecycle"
+ echo "FATAL: Native library failed to load — aborting"
+ exit 1
+ fi
+ if [ $WAIT_RC2 -eq 0 ]; then
+ lifecycle_done=1
+ fi
+fi
+
+if [ $lifecycle_done -eq 0 ]; then
+ echo "WARNING: Lifecycle events not found — retrying with relaunch"
+ xcrun simctl terminate "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+ sleep 3
+ > "$LOG_FILE"
+ xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID"
+ wait_for_log "$LOG_FILE" "Lifecycle: Create" 30 || true
+fi
+
+assert_log "$LOG_FILE" "Lifecycle: Create" "Lifecycle: Create"
+assert_log "$LOG_FILE" "Lifecycle: Resume" "Lifecycle: Resume"
+assert_log "$LOG_FILE" "setRoot" "setRoot"
+assert_log "$LOG_FILE" "setStrProp.*Counter:" "setStrProp Counter label"
+assert_log "$LOG_FILE" "setHandler.*click" "setHandler click"
+
+xcrun simctl terminate "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+kill "$LOG_STREAM_PID" 2>/dev/null || true
+xcrun simctl uninstall "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/ios/locale.sh b/test/ios/locale.sh
new file mode 100755
index 00000000..7b7214f9
--- /dev/null
+++ b/test/ios/locale.sh
@@ -0,0 +1,45 @@
+#!/usr/bin/env bash
+# iOS locale test: launch counter app, assert locale detection logs.
+#
+# haskellLogLocale is called from setup_ios_ui_bridge, logging:
+# "Locale raw: "
+# "Locale parsed: "
+#
+# Required env vars (set by simulator-all.nix harness):
+# SIM_UDID, BUNDLE_ID, COUNTER_APP, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+xcrun simctl install "$SIM_UDID" "$COUNTER_APP"
+echo "Counter app installed."
+
+LOG_FILE="$WORK_DIR/locale_log.txt"
+> "$LOG_FILE"
+xcrun simctl spawn "$SIM_UDID" log stream \
+ --level info \
+ --predicate "subsystem == \"$BUNDLE_ID\"" \
+ --style compact \
+ > "$LOG_FILE" 2>&1 &
+LOG_STREAM_PID=$!
+sleep 5
+
+xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID"
+
+wait_for_log "$LOG_FILE" "Locale parsed:" 60
+WAIT_RC=$?
+if [ $WAIT_RC -eq 2 ]; then
+ dump_ios_log "$LOG_FILE" "locale"
+ echo "FATAL: Native library failed to load — aborting"
+ exit 1
+fi
+
+assert_log "$LOG_FILE" "Locale raw:" "Locale raw tag logged"
+assert_log "$LOG_FILE" "Locale parsed:" "Locale parsed tag logged"
+
+xcrun simctl terminate "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+kill "$LOG_STREAM_PID" 2>/dev/null || true
+xcrun simctl uninstall "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/ios/node-pool.sh b/test/ios/node-pool.sh
new file mode 100644
index 00000000..bea2631f
--- /dev/null
+++ b/test/ios/node-pool.sh
@@ -0,0 +1,47 @@
+#!/usr/bin/env bash
+# Node pool integration test (iOS Simulator).
+#
+# Verifies that all 300 nodes render without pool exhaustion.
+# Requires NODEPOOL_APP to be set (built with dynamicNodePool=true).
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+source "$SCRIPT_DIR/helpers.sh"
+
+EXIT_CODE=0
+
+echo "=== Node Pool Test (iOS) ==="
+
+START_TIME=$(date -u +"%Y-%m-%d %H:%M:%S")
+
+xcrun simctl terminate "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+sleep 1
+
+echo "Installing node-pool test app..."
+xcrun simctl install "$SIM_UDID" "$NODEPOOL_APP"
+
+echo "Launching node-pool test app..."
+xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID"
+sleep 8
+
+LOGFILE="$WORK_DIR/log_nodepool_ios.txt"
+get_full_log "$START_TIME" "$LOGFILE"
+
+# Assert: setRoot was called (full UI rendered)
+assert_log "$LOGFILE" "setRoot" "setRoot called — full UI rendered"
+
+# Assert: node 300 was created
+assert_log "$LOGFILE" "createNode.*-> 300" "All 300 nodes created"
+
+# Assert: no pool exhaustion
+if grep -qE "Node pool exhausted" "$LOGFILE" 2>/dev/null; then
+ echo "FAIL: Node pool exhaustion detected"
+ EXIT_CODE=1
+else
+ echo "PASS: No pool exhaustion"
+fi
+
+# Uninstall
+xcrun simctl uninstall "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/ios/permission.sh b/test/ios/permission.sh
new file mode 100644
index 00000000..496090da
--- /dev/null
+++ b/test/ios/permission.sh
@@ -0,0 +1,65 @@
+#!/usr/bin/env bash
+# iOS permission test: install permission app, pre-grant camera, launch with
+# --autotest, assert that the permission result callback fires.
+#
+# Required env vars (set by simulator-all.nix harness):
+# SIM_UDID, BUNDLE_ID, PERMISSION_APP, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+xcrun simctl install "$SIM_UDID" "$PERMISSION_APP"
+echo "Permission app installed."
+
+# Pre-grant camera permission so the system dialog does not appear
+xcrun simctl privacy "$SIM_UDID" grant camera "$BUNDLE_ID"
+
+PERMISSION_START=$(date "+%Y-%m-%d %H:%M:%S")
+
+STREAM_LOG="$WORK_DIR/permission_stream.txt"
+> "$STREAM_LOG"
+xcrun simctl spawn "$SIM_UDID" log stream \
+ --level info \
+ --predicate "subsystem == \"$BUNDLE_ID\"" \
+ --style compact \
+ > "$STREAM_LOG" 2>&1 &
+LOG_STREAM_PID=$!
+sleep 5
+
+# Launch with --autotest to auto-tap button 0 after 3s
+xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID" --autotest
+
+render_done=0
+wait_for_log "$STREAM_LOG" "setRoot" 60 && render_done=1 || true
+
+if [ $render_done -eq 0 ]; then
+ echo "WARNING: setRoot not found — retrying with relaunch"
+ xcrun simctl terminate "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+ sleep 3
+ > "$STREAM_LOG"
+ xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID" --autotest
+ wait_for_log "$STREAM_LOG" "setRoot" 60 || true
+fi
+
+# Wait for autotest tap + permission result
+sleep 10
+
+kill "$LOG_STREAM_PID" 2>/dev/null || true
+sleep 1
+
+FULL_LOG="$WORK_DIR/permission_full.txt"
+get_full_log "$PERMISSION_START" "$FULL_LOG"
+
+if ! grep -q "setRoot" "$FULL_LOG" 2>/dev/null; then
+ echo " 'log show' empty/incomplete, using stream log"
+ FULL_LOG="$STREAM_LOG"
+fi
+
+assert_log "$FULL_LOG" "Permission result: PermissionGranted" "permission callback fires with PermissionGranted"
+assert_log "$FULL_LOG" "createNode" "createNode called (app renders)"
+assert_log "$FULL_LOG" "setRoot" "setRoot"
+
+xcrun simctl uninstall "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/ios/scroll.sh b/test/ios/scroll.sh
new file mode 100755
index 00000000..a71fadf5
--- /dev/null
+++ b/test/ios/scroll.sh
@@ -0,0 +1,72 @@
+#!/usr/bin/env bash
+# iOS scroll test: install scroll app, launch with --autotest, assert scroll + click events.
+#
+# Required env vars (set by simulator-all.nix harness):
+# SIM_UDID, BUNDLE_ID, SCROLL_APP, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+xcrun simctl install "$SIM_UDID" "$SCROLL_APP"
+echo "Scroll app installed."
+
+SCROLL_START=$(date "+%Y-%m-%d %H:%M:%S")
+
+STREAM_LOG="$WORK_DIR/scroll_stream.txt"
+> "$STREAM_LOG"
+xcrun simctl spawn "$SIM_UDID" log stream \
+ --level info \
+ --predicate "subsystem == \"$BUNDLE_ID\"" \
+ --style compact \
+ > "$STREAM_LOG" 2>&1 &
+LOG_STREAM_PID=$!
+sleep 5
+
+xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID" --autotest
+
+render_done=0
+wait_for_log "$STREAM_LOG" "setRoot" 60
+WAIT_RC=$?
+if [ $WAIT_RC -eq 2 ]; then
+ dump_ios_log "$STREAM_LOG" "scroll"
+ echo "FATAL: Native library failed to load — aborting"
+ exit 1
+fi
+if [ $WAIT_RC -eq 0 ]; then
+ render_done=1
+fi
+
+if [ $render_done -eq 0 ]; then
+ echo "WARNING: setRoot not found — retrying with relaunch"
+ xcrun simctl terminate "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+ sleep 3
+ > "$STREAM_LOG"
+ xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID" --autotest
+ wait_for_log "$STREAM_LOG" "setRoot" 60 || true
+fi
+
+# Auto-tap fires 3s after render; poll stream log until click appears or 30s timeout
+wait_for_log "$STREAM_LOG" "Click dispatched" 30 || true
+# Extra buffer so the persistent log store catches up before log show
+sleep 5
+
+kill "$LOG_STREAM_PID" 2>/dev/null || true
+sleep 1
+
+# Retrieve full log from persistent store; fall back to stream log if empty
+FULL_LOG="$WORK_DIR/scroll_full.txt"
+get_full_log "$SCROLL_START" "$FULL_LOG"
+
+if ! grep -q "setRoot" "$FULL_LOG" 2>/dev/null; then
+ echo " 'log show' empty/incomplete, using stream log"
+ FULL_LOG="$STREAM_LOG"
+fi
+
+assert_log "$FULL_LOG" 'createNode\(type=5\)' "createNode(type=5)"
+assert_log "$FULL_LOG" "setRoot" "setRoot"
+assert_log "$FULL_LOG" "Click dispatched: callbackId=0" "Click dispatched: callbackId=0"
+
+xcrun simctl uninstall "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/ios/styled.sh b/test/ios/styled.sh
new file mode 100755
index 00000000..09a932e0
--- /dev/null
+++ b/test/ios/styled.sh
@@ -0,0 +1,48 @@
+#!/usr/bin/env bash
+# iOS styled test: install counter app, assert setNumProp calls for fontSize, padding, and gravity.
+#
+# The counter app wraps its label with Styled (WidgetStyle (Just 16.0) (Just AlignCenter)),
+# so rendering must trigger setNumProp for fontSize, padding, and gravity.
+#
+# Required env vars (set by simulator-all.nix harness):
+# SIM_UDID, BUNDLE_ID, COUNTER_APP, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+xcrun simctl install "$SIM_UDID" "$COUNTER_APP"
+echo "Counter app installed."
+
+LOG_FILE="$WORK_DIR/styled_log.txt"
+> "$LOG_FILE"
+xcrun simctl spawn "$SIM_UDID" log stream \
+ --level info \
+ --predicate "subsystem == \"$BUNDLE_ID\"" \
+ --style compact \
+ > "$LOG_FILE" 2>&1 &
+LOG_STREAM_PID=$!
+sleep 5
+
+xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID"
+
+wait_for_log "$LOG_FILE" "setNumProp" 60
+WAIT_RC=$?
+if [ $WAIT_RC -eq 2 ]; then
+ dump_ios_log "$LOG_FILE" "styled"
+ echo "FATAL: Native library failed to load — aborting"
+ exit 1
+fi
+sleep 5
+
+assert_log "$LOG_FILE" "setNumProp.*fontSize" "setNumProp dispatched for fontSize"
+assert_log "$LOG_FILE" "setNumProp.*padding" "setNumProp dispatched for padding"
+assert_log "$LOG_FILE" "setNumProp.*gravity" "setNumProp dispatched for gravity"
+assert_log "$LOG_FILE" "setStrProp.*color" "setStrProp dispatched for color (text color)"
+assert_log "$LOG_FILE" "setStrProp.*bgColor" "setStrProp dispatched for bgColor (background color)"
+
+xcrun simctl terminate "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+kill "$LOG_STREAM_PID" 2>/dev/null || true
+xcrun simctl uninstall "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/ios/textinput.sh b/test/ios/textinput.sh
new file mode 100644
index 00000000..d2559ef4
--- /dev/null
+++ b/test/ios/textinput.sh
@@ -0,0 +1,72 @@
+#!/usr/bin/env bash
+# iOS textinput test: install textinput app, launch, assert it renders without crashing.
+#
+# TextInput is not yet fully implemented on iOS, so this is a smoke test:
+# verify that the app starts and createNode is called.
+#
+# Required env vars (set by simulator-all.nix harness):
+# SIM_UDID, BUNDLE_ID, TEXTINPUT_APP, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+xcrun simctl install "$SIM_UDID" "$TEXTINPUT_APP"
+echo "TextInput app installed."
+
+TEXTINPUT_START=$(date "+%Y-%m-%d %H:%M:%S")
+
+STREAM_LOG="$WORK_DIR/textinput_stream.txt"
+> "$STREAM_LOG"
+xcrun simctl spawn "$SIM_UDID" log stream \
+ --level info \
+ --predicate "subsystem == \"$BUNDLE_ID\"" \
+ --style compact \
+ > "$STREAM_LOG" 2>&1 &
+LOG_STREAM_PID=$!
+sleep 5
+
+xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID"
+
+render_done=0
+wait_for_log "$STREAM_LOG" "setRoot" 60
+WAIT_RC=$?
+if [ $WAIT_RC -eq 2 ]; then
+ dump_ios_log "$STREAM_LOG" "textinput"
+ echo "FATAL: Native library failed to load — aborting"
+ exit 1
+fi
+if [ $WAIT_RC -eq 0 ]; then
+ render_done=1
+fi
+
+if [ $render_done -eq 0 ]; then
+ echo "WARNING: setRoot not found — retrying with relaunch"
+ xcrun simctl terminate "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+ sleep 3
+ > "$STREAM_LOG"
+ xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID"
+ wait_for_log "$STREAM_LOG" "setRoot" 60 || true
+fi
+
+sleep 5
+
+kill "$LOG_STREAM_PID" 2>/dev/null || true
+sleep 1
+
+FULL_LOG="$WORK_DIR/textinput_full.txt"
+get_full_log "$TEXTINPUT_START" "$FULL_LOG"
+
+if ! grep -q "setRoot" "$FULL_LOG" 2>/dev/null; then
+ echo " 'log show' empty/incomplete, using stream log"
+ FULL_LOG="$STREAM_LOG"
+fi
+
+assert_log "$FULL_LOG" "createNode" "createNode called (app renders without crashing)"
+assert_log "$FULL_LOG" "createNode\(type=4\)" "createNode(type=4) — UITextField created"
+assert_log "$FULL_LOG" "setHandler.*textChange" "setHandler with textChange — onChange registered"
+assert_log "$FULL_LOG" "setRoot" "setRoot"
+
+xcrun simctl uninstall "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/ios/ui.sh b/test/ios/ui.sh
new file mode 100755
index 00000000..2b166b20
--- /dev/null
+++ b/test/ios/ui.sh
@@ -0,0 +1,53 @@
+#!/usr/bin/env bash
+# iOS UI test: install counter app, launch with --autotest, assert Counter: 1.
+#
+# Required env vars (set by simulator-all.nix harness):
+# SIM_UDID, BUNDLE_ID, COUNTER_APP, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+xcrun simctl install "$SIM_UDID" "$COUNTER_APP"
+echo "Counter app installed."
+
+LOG_FILE="$WORK_DIR/ui_log.txt"
+> "$LOG_FILE"
+xcrun simctl spawn "$SIM_UDID" log stream \
+ --level info \
+ --predicate "subsystem == \"$BUNDLE_ID\"" \
+ --style compact \
+ > "$LOG_FILE" 2>&1 &
+LOG_STREAM_PID=$!
+sleep 5
+
+xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID" --autotest
+
+ui_done=0
+wait_for_log "$LOG_FILE" "setStrProp.*Counter: 1" 60
+WAIT_RC=$?
+if [ $WAIT_RC -eq 2 ]; then
+ dump_ios_log "$LOG_FILE" "ui"
+ echo "FATAL: Native library failed to load — aborting"
+ exit 1
+fi
+if [ $WAIT_RC -eq 0 ]; then
+ ui_done=1
+fi
+
+if [ $ui_done -eq 0 ]; then
+ echo "WARNING: Counter: 1 not found — retrying with relaunch"
+ xcrun simctl terminate "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+ sleep 3
+ > "$LOG_FILE"
+ xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID" --autotest
+ wait_for_log "$LOG_FILE" "setStrProp.*Counter: 1" 60 || true
+fi
+
+assert_log "$LOG_FILE" "setStrProp.*Counter: 1" "Counter: 1 after --autotest tap"
+
+xcrun simctl terminate "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+kill "$LOG_STREAM_PID" 2>/dev/null || true
+xcrun simctl uninstall "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/watchos/buttons.sh b/test/watchos/buttons.sh
new file mode 100644
index 00000000..ff5f4c99
--- /dev/null
+++ b/test/watchos/buttons.sh
@@ -0,0 +1,65 @@
+#!/usr/bin/env bash
+# watchOS buttons test: launch with --autotest-buttons, assert full counter sequence.
+#
+# Required env vars (set by watchos-simulator-all.nix harness):
+# SIM_UDID, BUNDLE_ID, COUNTER_APP, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+xcrun simctl install "$SIM_UDID" "$COUNTER_APP"
+echo "Counter app installed."
+
+BUTTONS_START=$(date "+%Y-%m-%d %H:%M:%S")
+
+LOG_FILE="$WORK_DIR/buttons_log.txt"
+> "$LOG_FILE"
+xcrun simctl spawn "$SIM_UDID" log stream \
+ --level info \
+ --predicate "process == \"HaskellMobile\"" \
+ --style compact \
+ > "$LOG_FILE" 2>&1 &
+LOG_STREAM_PID=$!
+sleep 2
+
+xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID" --autotest-buttons
+
+# Wait for final value Counter: -1
+wait_for_log "$LOG_FILE" "setStrProp.*Counter: -1" 60 || true
+
+kill "$LOG_STREAM_PID" 2>/dev/null || true
+sleep 1
+
+# Retrieve full log for reliable assertion; fall back to stream log if empty
+FULL_LOG="$WORK_DIR/buttons_full.txt"
+get_full_log "$BUTTONS_START" "$FULL_LOG"
+
+if ! grep -q "setStrProp" "$FULL_LOG" 2>/dev/null; then
+ echo " 'log show' empty, using stream log"
+ FULL_LOG="$LOG_FILE"
+fi
+
+assert_log "$FULL_LOG" "setStrProp.*Counter: 0" "Counter: 0 in sequence"
+assert_log "$FULL_LOG" "setStrProp.*Counter: 1" "Counter: 1 in sequence"
+assert_log "$FULL_LOG" "setStrProp.*Counter: 2" "Counter: 2 in sequence"
+assert_log "$FULL_LOG" "setStrProp.*Counter: -1" "Counter: -1 in sequence"
+
+# Warn (not fail) if occurrence counts are lower than expected (log deduplication)
+count_1=$(grep -c 'setStrProp.*Counter: 1' "$FULL_LOG" 2>/dev/null || echo "0")
+if [ "$count_1" -ge 2 ]; then
+ echo "PASS: Counter: 1 appeared $count_1 times"
+else
+ echo "WARN: Counter: 1 seen $count_1 time(s), expected 2 (log may deduplicate)"
+fi
+
+count_0=$(grep -c 'setStrProp.*Counter: 0' "$FULL_LOG" 2>/dev/null || echo "0")
+if [ "$count_0" -ge 2 ]; then
+ echo "PASS: Counter: 0 appeared $count_0 times"
+else
+ echo "WARN: Counter: 0 seen $count_0 time(s), expected 2 (log may deduplicate)"
+fi
+
+xcrun simctl uninstall "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/watchos/helpers.sh b/test/watchos/helpers.sh
new file mode 100644
index 00000000..72c9839c
--- /dev/null
+++ b/test/watchos/helpers.sh
@@ -0,0 +1,57 @@
+#!/usr/bin/env bash
+# Common helper functions for watchOS simulator test scripts.
+# Source this file; do not run directly.
+#
+# Required env vars (set by watchos-simulator-all.nix harness):
+# SIM_UDID — simulator UUID
+# BUNDLE_ID — me.jappie.haskellmobile.watchkitapp (for simctl commands)
+# LOG_SUBSYSTEM — me.jappie.haskellmobile (for os_log predicates)
+# WORK_DIR — temp dir for log files
+
+# wait_for_log LOGFILE PATTERN TIMEOUT_SECONDS
+# Polls LOGFILE for PATTERN every 2s.
+# Returns 0 on success, 1 on timeout.
+wait_for_log() {
+ local logfile="$1"
+ local pattern="$2"
+ local timeout_seconds="$3"
+ local elapsed=0
+ while [ $elapsed -lt "$timeout_seconds" ]; do
+ if grep -q "$pattern" "$logfile" 2>/dev/null; then
+ echo "Found '$pattern' after ~${elapsed}s"
+ return 0
+ fi
+ sleep 2
+ elapsed=$((elapsed + 2))
+ done
+ echo "WARNING: '$pattern' not found after ${timeout_seconds}s"
+ return 1
+}
+
+# assert_log LOGFILE PATTERN LABEL
+# Greps LOGFILE for PATTERN, prints PASS/FAIL with LABEL.
+# Sets EXIT_CODE=1 on failure (EXIT_CODE must be declared in caller).
+assert_log() {
+ local logfile="$1"
+ local pattern="$2"
+ local label="$3"
+ if grep -qE "$pattern" "$logfile" 2>/dev/null; then
+ echo "PASS: $label"
+ else
+ echo "FAIL: $label"
+ EXIT_CODE=1
+ fi
+}
+
+# get_full_log START_TIME OUTFILE
+# Retrieves persistent log entries since START_TIME for LOG_SUBSYSTEM into OUTFILE.
+get_full_log() {
+ local start_time="$1"
+ local outfile="$2"
+ xcrun simctl spawn "$SIM_UDID" log show \
+ --start "$start_time" \
+ --predicate "subsystem == \"$LOG_SUBSYSTEM\"" \
+ --style compact \
+ --info \
+ > "$outfile" 2>&1 || true
+}
diff --git a/test/watchos/image.sh b/test/watchos/image.sh
new file mode 100755
index 00000000..733c7f9a
--- /dev/null
+++ b/test/watchos/image.sh
@@ -0,0 +1,69 @@
+#!/usr/bin/env bash
+# watchOS image test: install image app, launch, assert all 3 ImageSource paths are exercised.
+#
+# Required env vars (set by watchos-simulator-all.nix harness):
+# SIM_UDID, BUNDLE_ID, IMAGE_APP, WORK_DIR, LOG_SUBSYSTEM
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+xcrun simctl install "$SIM_UDID" "$IMAGE_APP"
+echo "Image app installed."
+
+IMAGE_START=$(date "+%Y-%m-%d %H:%M:%S")
+
+STREAM_LOG="$WORK_DIR/image_stream.txt"
+> "$STREAM_LOG"
+xcrun simctl spawn "$SIM_UDID" log stream \
+ --level info \
+ --predicate "subsystem == \"$LOG_SUBSYSTEM\"" \
+ --style compact \
+ > "$STREAM_LOG" 2>&1 &
+LOG_STREAM_PID=$!
+sleep 5
+
+xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID"
+
+render_done=0
+wait_for_log "$STREAM_LOG" "setRoot" 60 && render_done=1 || true
+
+if [ $render_done -eq 0 ]; then
+ echo "WARNING: setRoot not found — retrying with relaunch"
+ xcrun simctl terminate "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+ sleep 3
+ > "$STREAM_LOG"
+ xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID"
+ wait_for_log "$STREAM_LOG" "setRoot" 60 || true
+fi
+
+sleep 5
+
+kill "$LOG_STREAM_PID" 2>/dev/null || true
+sleep 1
+
+FULL_LOG="$WORK_DIR/image_full.txt"
+get_full_log "$IMAGE_START" "$FULL_LOG"
+
+if ! grep -q "setRoot" "$FULL_LOG" 2>/dev/null; then
+ echo " 'log show' empty/incomplete, using stream log"
+ FULL_LOG="$STREAM_LOG"
+fi
+
+# All 3 Image nodes created (type=6)
+assert_log "$FULL_LOG" "createNode\(type=6\)" "createNode(type=6) — Image node created"
+
+# Test case 1: ImageResource
+assert_log "$FULL_LOG" "setStrProp.*imageResource.*ic_launcher" "ImageResource path set"
+
+# Test case 2: ImageData
+assert_log "$FULL_LOG" "setImageData" "ImageData called"
+
+# Test case 3: ImageFile
+assert_log "$FULL_LOG" "setStrProp.*imageFile.*/nonexistent" "ImageFile path set"
+
+assert_log "$FULL_LOG" "setRoot" "setRoot"
+
+xcrun simctl uninstall "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/watchos/lifecycle.sh b/test/watchos/lifecycle.sh
new file mode 100644
index 00000000..9aa1d217
--- /dev/null
+++ b/test/watchos/lifecycle.sh
@@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+# watchOS lifecycle test: install counter app, launch, assert lifecycle events.
+#
+# Required env vars (set by watchos-simulator-all.nix harness):
+# SIM_UDID, BUNDLE_ID, COUNTER_APP, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+xcrun simctl install "$SIM_UDID" "$COUNTER_APP"
+echo "Counter app installed."
+
+LOG_FILE="$WORK_DIR/lifecycle_log.txt"
+> "$LOG_FILE"
+xcrun simctl spawn "$SIM_UDID" log stream \
+ --level info \
+ --predicate "subsystem == \"$LOG_SUBSYSTEM\"" \
+ --style compact \
+ > "$LOG_FILE" 2>&1 &
+LOG_STREAM_PID=$!
+sleep 5
+
+xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID"
+
+# Poll for lifecycle events
+lifecycle_done=0
+if wait_for_log "$LOG_FILE" "Lifecycle: Create" 60 && wait_for_log "$LOG_FILE" "Lifecycle: Resume" 5; then
+ lifecycle_done=1
+fi
+
+if [ $lifecycle_done -eq 0 ]; then
+ echo "WARNING: Lifecycle events not found — retrying with relaunch"
+ xcrun simctl terminate "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+ sleep 3
+ > "$LOG_FILE"
+ xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID"
+ wait_for_log "$LOG_FILE" "Lifecycle: Create" 30 || true
+fi
+
+assert_log "$LOG_FILE" "Lifecycle: Create" "Lifecycle: Create"
+assert_log "$LOG_FILE" "Lifecycle: Resume" "Lifecycle: Resume"
+assert_log "$LOG_FILE" "setRoot" "setRoot"
+assert_log "$LOG_FILE" "setStrProp.*Counter:" "setStrProp Counter label"
+assert_log "$LOG_FILE" "setHandler.*click" "setHandler click"
+
+xcrun simctl terminate "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+kill "$LOG_STREAM_PID" 2>/dev/null || true
+xcrun simctl uninstall "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/watchos/locale.sh b/test/watchos/locale.sh
new file mode 100644
index 00000000..bd400c35
--- /dev/null
+++ b/test/watchos/locale.sh
@@ -0,0 +1,35 @@
+#!/usr/bin/env bash
+# watchOS locale test: launch counter app, assert locale detection logs.
+#
+# Required env vars (set by watchos-simulator-all.nix harness):
+# SIM_UDID, BUNDLE_ID, COUNTER_APP, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+xcrun simctl install "$SIM_UDID" "$COUNTER_APP"
+echo "Counter app installed."
+
+LOG_FILE="$WORK_DIR/locale_log.txt"
+> "$LOG_FILE"
+xcrun simctl spawn "$SIM_UDID" log stream \
+ --level info \
+ --predicate "subsystem == \"$LOG_SUBSYSTEM\"" \
+ --style compact \
+ > "$LOG_FILE" 2>&1 &
+LOG_STREAM_PID=$!
+sleep 5
+
+xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID"
+
+wait_for_log "$LOG_FILE" "Locale parsed:" 60 || true
+
+assert_log "$LOG_FILE" "Locale raw:" "Locale raw tag logged"
+assert_log "$LOG_FILE" "Locale parsed:" "Locale parsed tag logged"
+
+xcrun simctl terminate "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+kill "$LOG_STREAM_PID" 2>/dev/null || true
+xcrun simctl uninstall "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/watchos/node-pool.sh b/test/watchos/node-pool.sh
new file mode 100644
index 00000000..46207c00
--- /dev/null
+++ b/test/watchos/node-pool.sh
@@ -0,0 +1,40 @@
+#!/usr/bin/env bash
+# Node pool integration test (watchOS Simulator).
+#
+# watchOS uses a Swift dictionary (unbounded), so this test should
+# always pass — it simply confirms that 300 nodes render successfully.
+# Requires NODEPOOL_APP to be set.
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+source "$SCRIPT_DIR/helpers.sh"
+
+EXIT_CODE=0
+
+echo "=== Node Pool Test (watchOS) ==="
+
+START_TIME=$(date -u +"%Y-%m-%d %H:%M:%S")
+
+xcrun simctl terminate "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+sleep 1
+
+echo "Installing node-pool test app..."
+xcrun simctl install "$SIM_UDID" "$NODEPOOL_APP"
+
+echo "Launching node-pool test app..."
+xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID"
+sleep 8
+
+LOGFILE="$WORK_DIR/log_nodepool_watchos.txt"
+get_full_log "$START_TIME" "$LOGFILE"
+
+# Assert: setRoot was called (full UI rendered)
+assert_log "$LOGFILE" "setRoot" "setRoot called — full UI rendered"
+
+# Assert: node 300 was created
+assert_log "$LOGFILE" "createNode.*-> 300" "All 300 nodes created"
+
+# Uninstall
+xcrun simctl uninstall "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/watchos/scroll.sh b/test/watchos/scroll.sh
new file mode 100644
index 00000000..a935cb3f
--- /dev/null
+++ b/test/watchos/scroll.sh
@@ -0,0 +1,63 @@
+#!/usr/bin/env bash
+# watchOS scroll test: install scroll app, launch with --autotest, assert scroll + click events.
+#
+# Required env vars (set by watchos-simulator-all.nix harness):
+# SIM_UDID, BUNDLE_ID, SCROLL_APP, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+xcrun simctl install "$SIM_UDID" "$SCROLL_APP"
+echo "Scroll app installed."
+
+SCROLL_START=$(date "+%Y-%m-%d %H:%M:%S")
+
+STREAM_LOG="$WORK_DIR/scroll_stream.txt"
+> "$STREAM_LOG"
+xcrun simctl spawn "$SIM_UDID" log stream \
+ --level info \
+ --predicate "subsystem == \"$LOG_SUBSYSTEM\"" \
+ --style compact \
+ > "$STREAM_LOG" 2>&1 &
+LOG_STREAM_PID=$!
+sleep 5
+
+xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID" --autotest
+
+render_done=0
+wait_for_log "$STREAM_LOG" "setRoot" 60 && render_done=1 || true
+
+if [ $render_done -eq 0 ]; then
+ echo "WARNING: setRoot not found — retrying with relaunch"
+ xcrun simctl terminate "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+ sleep 3
+ > "$STREAM_LOG"
+ xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID" --autotest
+ wait_for_log "$STREAM_LOG" "setRoot" 60 || true
+fi
+
+# Auto-tap fires 3s after render; poll stream log until click appears or 30s timeout
+wait_for_log "$STREAM_LOG" "Click dispatched" 30 || true
+# Extra buffer so the persistent log store catches up before log show
+sleep 5
+
+kill "$LOG_STREAM_PID" 2>/dev/null || true
+sleep 1
+
+# Retrieve full log from persistent store; fall back to stream log if empty
+FULL_LOG="$WORK_DIR/scroll_full.txt"
+get_full_log "$SCROLL_START" "$FULL_LOG"
+
+if ! grep -q "setRoot" "$FULL_LOG" 2>/dev/null; then
+ echo " 'log show' empty/incomplete, using stream log"
+ FULL_LOG="$STREAM_LOG"
+fi
+
+assert_log "$FULL_LOG" 'createNode\(type=5\)' "createNode(type=5)"
+assert_log "$FULL_LOG" "setRoot" "setRoot"
+assert_log "$FULL_LOG" "Click dispatched: callbackId=0" "Click dispatched: callbackId=0"
+
+xcrun simctl uninstall "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/watchos/styled.sh b/test/watchos/styled.sh
new file mode 100644
index 00000000..12e68e54
--- /dev/null
+++ b/test/watchos/styled.sh
@@ -0,0 +1,38 @@
+#!/usr/bin/env bash
+# watchOS styled test: install counter app, assert setNumProp calls for fontSize + padding.
+#
+# Required env vars (set by watchos-simulator-all.nix harness):
+# SIM_UDID, BUNDLE_ID, COUNTER_APP, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+xcrun simctl install "$SIM_UDID" "$COUNTER_APP"
+echo "Counter app installed."
+
+LOG_FILE="$WORK_DIR/styled_log.txt"
+> "$LOG_FILE"
+xcrun simctl spawn "$SIM_UDID" log stream \
+ --level info \
+ --predicate "subsystem == \"$LOG_SUBSYSTEM\"" \
+ --style compact \
+ > "$LOG_FILE" 2>&1 &
+LOG_STREAM_PID=$!
+sleep 5
+
+xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID"
+
+wait_for_log "$LOG_FILE" "setNumProp" 60 || true
+sleep 5
+
+assert_log "$LOG_FILE" "setNumProp.*fontSize" "setNumProp dispatched for fontSize"
+assert_log "$LOG_FILE" "setNumProp.*padding" "setNumProp dispatched for padding"
+assert_log "$LOG_FILE" "setStrProp.*color" "setStrProp dispatched for color (text color)"
+assert_log "$LOG_FILE" "setStrProp.*bgColor" "setStrProp dispatched for bgColor (background color)"
+
+xcrun simctl terminate "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+kill "$LOG_STREAM_PID" 2>/dev/null || true
+xcrun simctl uninstall "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/watchos/textinput.sh b/test/watchos/textinput.sh
new file mode 100644
index 00000000..e6ab4893
--- /dev/null
+++ b/test/watchos/textinput.sh
@@ -0,0 +1,58 @@
+#!/usr/bin/env bash
+# watchOS textinput test: install textinput app, launch, assert it renders without crashing.
+#
+# Required env vars (set by watchos-simulator-all.nix harness):
+# SIM_UDID, BUNDLE_ID, TEXTINPUT_APP, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+xcrun simctl install "$SIM_UDID" "$TEXTINPUT_APP"
+echo "TextInput app installed."
+
+TEXTINPUT_START=$(date "+%Y-%m-%d %H:%M:%S")
+
+STREAM_LOG="$WORK_DIR/textinput_stream.txt"
+> "$STREAM_LOG"
+xcrun simctl spawn "$SIM_UDID" log stream \
+ --level info \
+ --predicate "subsystem == \"$LOG_SUBSYSTEM\"" \
+ --style compact \
+ > "$STREAM_LOG" 2>&1 &
+LOG_STREAM_PID=$!
+sleep 5
+
+xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID"
+
+render_done=0
+wait_for_log "$STREAM_LOG" "setRoot" 60 && render_done=1 || true
+
+if [ $render_done -eq 0 ]; then
+ echo "WARNING: setRoot not found — retrying with relaunch"
+ xcrun simctl terminate "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+ sleep 3
+ > "$STREAM_LOG"
+ xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID"
+ wait_for_log "$STREAM_LOG" "setRoot" 60 || true
+fi
+
+sleep 5
+
+kill "$LOG_STREAM_PID" 2>/dev/null || true
+sleep 1
+
+FULL_LOG="$WORK_DIR/textinput_full.txt"
+get_full_log "$TEXTINPUT_START" "$FULL_LOG"
+
+if ! grep -q "setRoot" "$FULL_LOG" 2>/dev/null; then
+ echo " 'log show' empty/incomplete, using stream log"
+ FULL_LOG="$STREAM_LOG"
+fi
+
+assert_log "$FULL_LOG" "createNode" "createNode called (app renders without crashing)"
+assert_log "$FULL_LOG" "setRoot" "setRoot"
+
+xcrun simctl uninstall "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/test/watchos/ui.sh b/test/watchos/ui.sh
new file mode 100644
index 00000000..029f7ac1
--- /dev/null
+++ b/test/watchos/ui.sh
@@ -0,0 +1,44 @@
+#!/usr/bin/env bash
+# watchOS UI test: install counter app, launch with --autotest, assert Counter: 1.
+#
+# Required env vars (set by watchos-simulator-all.nix harness):
+# SIM_UDID, BUNDLE_ID, COUNTER_APP, WORK_DIR
+set -euo pipefail
+source "$(dirname "$0")/helpers.sh"
+
+EXIT_CODE=0
+
+xcrun simctl install "$SIM_UDID" "$COUNTER_APP"
+echo "Counter app installed."
+
+LOG_FILE="$WORK_DIR/ui_log.txt"
+> "$LOG_FILE"
+xcrun simctl spawn "$SIM_UDID" log stream \
+ --level info \
+ --predicate "subsystem == \"$LOG_SUBSYSTEM\"" \
+ --style compact \
+ > "$LOG_FILE" 2>&1 &
+LOG_STREAM_PID=$!
+sleep 5
+
+xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID" --autotest
+
+ui_done=0
+wait_for_log "$LOG_FILE" "setStrProp.*Counter: 1" 60 && ui_done=1 || true
+
+if [ $ui_done -eq 0 ]; then
+ echo "WARNING: Counter: 1 not found — retrying with relaunch"
+ xcrun simctl terminate "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+ sleep 3
+ > "$LOG_FILE"
+ xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID" --autotest
+ wait_for_log "$LOG_FILE" "setStrProp.*Counter: 1" 60 || true
+fi
+
+assert_log "$LOG_FILE" "setStrProp.*Counter: 1" "Counter: 1 after --autotest tap"
+
+xcrun simctl terminate "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+kill "$LOG_STREAM_PID" 2>/dev/null || true
+xcrun simctl uninstall "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true
+
+exit $EXIT_CODE
diff --git a/watchos/HaskellMobile/ContentView.swift b/watchos/HaskellMobile/ContentView.swift
new file mode 100644
index 00000000..c4596985
--- /dev/null
+++ b/watchos/HaskellMobile/ContentView.swift
@@ -0,0 +1,200 @@
+import SwiftUI
+
+/// Recursive SwiftUI renderer for the Haskell widget tree.
+struct NodeView: View {
+ @ObservedObject var node: WatchUINode
+
+ var body: some View {
+ let content = nodeContent
+ .ifLet(node.fontSize) { view, size in
+ view.font(.system(size: size))
+ }
+ .ifLet(node.padding) { view, pad in
+ view.padding(pad)
+ }
+ .ifLet(node.textColor.flatMap { Color(hex: $0) }) { view, color in
+ view.foregroundColor(color)
+ }
+ .ifLet(node.backgroundColor.flatMap { Color(hex: $0) }) { view, color in
+ view.background(color)
+ }
+ return content
+ }
+
+ @ViewBuilder
+ private var nodeContent: some View {
+ switch node.nodeType {
+ case 0: // UI_NODE_TEXT
+ Text(node.text)
+ case 1: // UI_NODE_BUTTON
+ Button(node.text) {
+ HaskellBridge.onUIEvent(node.callbackId)
+ }
+ case 2: // UI_NODE_COLUMN
+ VStack {
+ ForEach(node.children) { child in
+ NodeView(node: child)
+ }
+ }
+ case 3: // UI_NODE_ROW
+ HStack {
+ ForEach(node.children) { child in
+ NodeView(node: child)
+ }
+ }
+ case 4: // UI_NODE_TEXT_INPUT
+ TextInputNodeView(node: node)
+ case 5: // UI_NODE_SCROLL_VIEW
+ ScrollView {
+ VStack {
+ ForEach(node.children) { child in
+ NodeView(node: child)
+ }
+ }
+ }
+ case 6: // UI_NODE_IMAGE
+ ImageNodeView(node: node)
+ default:
+ EmptyView()
+ }
+ }
+}
+
+/// Separate view for text input to manage local editing state.
+struct TextInputNodeView: View {
+ @ObservedObject var node: WatchUINode
+ @State private var editingText: String = ""
+
+ var body: some View {
+ TextField(node.hint, text: $editingText, onCommit: {
+ HaskellBridge.onUITextChange(node.callbackId, editingText)
+ })
+ .onAppear {
+ editingText = node.text
+ }
+ }
+}
+
+/// SwiftUI renderer for Image nodes.
+/// Supports resource name, raw data, and file path sources with configurable scale type.
+struct ImageNodeView: View {
+ @ObservedObject var node: WatchUINode
+
+ var body: some View {
+ if let resourceName = node.imageResource {
+ imageWithScaleType(Image(resourceName))
+ } else if let data = node.imageData, let uiImage = UIImage(data: data) {
+ imageWithScaleType(Image(uiImage: uiImage))
+ } else if let filePath = node.imageFile, let uiImage = UIImage(contentsOfFile: filePath) {
+ imageWithScaleType(Image(uiImage: uiImage))
+ } else {
+ Text("Image not found")
+ .foregroundColor(.secondary)
+ .font(.caption)
+ }
+ }
+
+ @ViewBuilder
+ private func imageWithScaleType(_ image: Image) -> some View {
+ switch node.scaleType {
+ case 1:
+ image.resizable().scaledToFill()
+ case 2:
+ image
+ default:
+ image.resizable().scaledToFit()
+ }
+ }
+}
+
+/// ContentView wraps the Haskell-driven node tree.
+struct ContentView: View {
+ @ObservedObject var state = WatchUIBridgeState.shared
+
+ var body: some View {
+ Group {
+ if let root = state.rootNode {
+ NodeView(node: root)
+ } else {
+ Text("Loading...")
+ }
+ }
+ .onAppear {
+ setup_watchos_ui_bridge(HaskellBridge.getContext())
+ HaskellBridge.renderUI()
+
+ // CI auto-test: simulate button tap 3s after the initial render.
+ if CommandLine.arguments.contains("--autotest") {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
+ HaskellBridge.onUIEvent(0)
+ }
+ }
+
+ // CI auto-test: exercise both "+" and "-" buttons.
+ if CommandLine.arguments.contains("--autotest-buttons") {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
+ HaskellBridge.onUIEvent(0) // + -> Counter: 1
+ }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
+ HaskellBridge.onUIEvent(0) // + -> Counter: 2
+ }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 7) {
+ HaskellBridge.onUIEvent(1) // - -> Counter: 1
+ }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 9) {
+ HaskellBridge.onUIEvent(1) // - -> Counter: 0
+ }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 11) {
+ HaskellBridge.onUIEvent(1) // - -> Counter: -1
+ }
+ }
+ }
+ }
+}
+
+/// Conditional modifier helper.
+extension View {
+ @ViewBuilder
+ func ifLet(_ value: T?, transform: (Self, T) -> Content) -> some View {
+ if let value = value {
+ transform(self, value)
+ } else {
+ self
+ }
+ }
+}
+
+/// Parse hex color strings (#RGB, #RRGGBB, or #AARRGGBB) into SwiftUI Color.
+extension Color {
+ init?(hex: String) {
+ guard hex.hasPrefix("#") else { return nil }
+ let digits = String(hex.dropFirst())
+ guard let raw = UInt64(digits, radix: 16) else { return nil }
+
+ let red: Double
+ let green: Double
+ let blue: Double
+ let opacity: Double
+
+ switch digits.count {
+ case 3:
+ let r = Double((raw >> 8) & 0xF) * 0x11
+ let g = Double((raw >> 4) & 0xF) * 0x11
+ let b = Double(raw & 0xF) * 0x11
+ red = r / 255.0; green = g / 255.0; blue = b / 255.0; opacity = 1.0
+ case 6:
+ red = Double((raw >> 16) & 0xFF) / 255.0
+ green = Double((raw >> 8) & 0xFF) / 255.0
+ blue = Double(raw & 0xFF) / 255.0
+ opacity = 1.0
+ case 8:
+ opacity = Double((raw >> 24) & 0xFF) / 255.0
+ red = Double((raw >> 16) & 0xFF) / 255.0
+ green = Double((raw >> 8) & 0xFF) / 255.0
+ blue = Double(raw & 0xFF) / 255.0
+ default:
+ return nil
+ }
+ self.init(red: red, green: green, blue: blue, opacity: opacity)
+ }
+}
diff --git a/watchos/HaskellMobile/HaskellBridge.swift b/watchos/HaskellMobile/HaskellBridge.swift
new file mode 100644
index 00000000..16fb92a5
--- /dev/null
+++ b/watchos/HaskellMobile/HaskellBridge.swift
@@ -0,0 +1,61 @@
+import Foundation
+import os.log
+
+/// Swift wrapper around the Haskell FFI functions exposed via C.
+class HaskellBridge {
+ private static let bridgeLog = OSLog(subsystem: "me.jappie.haskellmobile", category: "UIBridge")
+ // Lifecycle event codes (must match HaskellMobile.h)
+ static let lifecycleCreate: Int32 = 0
+ static let lifecycleStart: Int32 = 1
+ static let lifecycleResume: Int32 = 2
+ static let lifecyclePause: Int32 = 3
+ static let lifecycleStop: Int32 = 4
+ static let lifecycleDestroy: Int32 = 5
+ static let lifecycleLowMemory: Int32 = 6
+
+ /// Opaque Haskell context pointer, created during initialization.
+ private static var context: UnsafeMutableRawPointer?
+
+ /// Initialize the Haskell RTS. Must be called before any other Haskell function.
+ static func initialize() {
+ hs_init(nil, nil)
+ context = haskellRunMain()
+ }
+
+ /// Call Haskell's haskellGreet and return the result as a Swift String.
+ /// The C-allocated string is freed after copying.
+ static func greet(_ name: String) -> String {
+ let result = haskellGreet(name)!
+ let greeting = String(cString: result)
+ free(result)
+ return greeting
+ }
+
+ /// Notify Haskell of a lifecycle event.
+ static func onLifecycle(_ event: Int32) {
+ haskellOnLifecycle(context, event)
+ }
+
+ /// Render the Haskell UI tree via the registered bridge callbacks.
+ static func renderUI() {
+ haskellRenderUI(context)
+ }
+
+ /// Dispatch a UI event (e.g. button tap) to Haskell, which re-renders.
+ static func onUIEvent(_ callbackId: Int32) {
+ os_log("Click dispatched: callbackId=%d", log: bridgeLog, type: .info, callbackId)
+ haskellOnUIEvent(context, callbackId)
+ }
+
+ /// Dispatch a text change event to Haskell.
+ static func onUITextChange(_ callbackId: Int32, _ text: String) {
+ os_log("Text changed: callbackId=%d", log: bridgeLog, type: .info, callbackId)
+ haskellOnUITextChange(context, callbackId, text)
+ }
+
+ /// Return the opaque Haskell context pointer (for passing to C bridge setup).
+ static func getContext() -> UnsafeMutableRawPointer? {
+ return context
+ }
+
+}
diff --git a/watchos/HaskellMobile/HaskellMobile-Bridging-Header.h b/watchos/HaskellMobile/HaskellMobile-Bridging-Header.h
new file mode 100644
index 00000000..fbafae2c
--- /dev/null
+++ b/watchos/HaskellMobile/HaskellMobile-Bridging-Header.h
@@ -0,0 +1,10 @@
+#include "HaskellMobile.h"
+#include "UIBridge.h"
+#include "PermissionBridge.h"
+
+/* Dispatch a text change event to Haskell.
+ * Not declared in HaskellMobile.h but exported via foreign export ccall. */
+void haskellOnUITextChange(void *ctx, int32_t callbackId, const char *text);
+
+/* watchOS UI bridge setup — called from Swift before haskellRenderUI */
+void setup_watchos_ui_bridge(void *haskellCtx);
diff --git a/watchos/HaskellMobile/HaskellMobileApp.swift b/watchos/HaskellMobile/HaskellMobileApp.swift
new file mode 100644
index 00000000..3df7e606
--- /dev/null
+++ b/watchos/HaskellMobile/HaskellMobileApp.swift
@@ -0,0 +1,29 @@
+import SwiftUI
+
+@main
+struct HaskellMobileApp: App {
+ @Environment(\.scenePhase) private var scenePhase
+
+ init() {
+ HaskellBridge.initialize()
+ HaskellBridge.onLifecycle(HaskellBridge.lifecycleCreate)
+ }
+
+ var body: some Scene {
+ WindowGroup {
+ ContentView()
+ }
+ .onChange(of: scenePhase) { newPhase in
+ switch newPhase {
+ case .active:
+ HaskellBridge.onLifecycle(HaskellBridge.lifecycleResume)
+ case .inactive:
+ HaskellBridge.onLifecycle(HaskellBridge.lifecyclePause)
+ case .background:
+ HaskellBridge.onLifecycle(HaskellBridge.lifecycleStop)
+ @unknown default:
+ break
+ }
+ }
+ }
+}
diff --git a/watchos/HaskellMobile/UIBridgeSetup.c b/watchos/HaskellMobile/UIBridgeSetup.c
new file mode 100644
index 00000000..780f5ef4
--- /dev/null
+++ b/watchos/HaskellMobile/UIBridgeSetup.c
@@ -0,0 +1,62 @@
+/*
+ * watchOS UI bridge setup — registers Swift @_cdecl callbacks
+ * with the platform-agnostic UIBridge dispatcher.
+ *
+ * The Swift functions (watchos_create_node, watchos_set_str_prop, etc.)
+ * are defined via @_cdecl in WatchUIBridgeState.swift.
+ */
+
+#include "UIBridge.h"
+#include
+#include
+
+/* Locale detection (cbits/locale.c) */
+extern void setSystemLocale(const char *locale);
+
+/* Log detected locale from Haskell (HaskellMobile.Locale) */
+extern void haskellLogLocale(void);
+
+/* Forward declarations of Swift @_cdecl functions */
+extern int32_t watchos_create_node(int32_t nodeType);
+extern void watchos_set_str_prop(int32_t nodeId, int32_t propId, const char *value);
+extern void watchos_set_num_prop(int32_t nodeId, int32_t propId, double value);
+extern void watchos_set_image_data(int32_t nodeId, const uint8_t *data, int32_t length);
+extern void watchos_set_handler(int32_t nodeId, int32_t eventType, int32_t callbackId);
+extern void watchos_add_child(int32_t parentId, int32_t childId);
+extern void watchos_remove_child(int32_t parentId, int32_t childId);
+extern void watchos_destroy_node(int32_t nodeId);
+extern void watchos_set_root(int32_t nodeId);
+extern void watchos_clear(void);
+
+static UIBridgeCallbacks g_watchos_callbacks = {
+ .createNode = watchos_create_node,
+ .setStrProp = watchos_set_str_prop,
+ .setNumProp = watchos_set_num_prop,
+ .setImageData = watchos_set_image_data,
+ .setHandler = watchos_set_handler,
+ .addChild = watchos_add_child,
+ .removeChild = watchos_remove_child,
+ .destroyNode = watchos_destroy_node,
+ .setRoot = watchos_set_root,
+ .clear = watchos_clear,
+};
+
+/*
+ * Set up the watchOS UI bridge. Called from Swift before haskellRenderUI.
+ * Registers callbacks with the platform-agnostic dispatcher.
+ *
+ * haskellCtx: opaque Haskell context pointer
+ */
+void setup_watchos_ui_bridge(void *haskellCtx)
+{
+ ui_register_callbacks(&g_watchos_callbacks);
+
+ os_log_t log = os_log_create("me.jappie.haskellmobile", "UIBridge");
+ os_log_info(log, "watchOS UI bridge initialized");
+
+ /* Cache the system locale from NSLocale via Foundation.
+ * On watchOS we default to "en" — the locale query is done
+ * in Swift (HaskellBridge) if needed. */
+ setSystemLocale("en");
+ haskellLogLocale();
+}
diff --git a/watchos/HaskellMobile/WatchUIBridgeState.swift b/watchos/HaskellMobile/WatchUIBridgeState.swift
new file mode 100644
index 00000000..6676df12
--- /dev/null
+++ b/watchos/HaskellMobile/WatchUIBridgeState.swift
@@ -0,0 +1,163 @@
+import SwiftUI
+import os.log
+
+private let bridgeLog = OSLog(subsystem: "me.jappie.haskellmobile", category: "UIBridge")
+
+/// Singleton holding the node pool and root node for SwiftUI rendering.
+/// Haskell calls clear/createNode/setStrProp/setRoot etc. via C callbacks.
+/// Only setRoot publishes the change to trigger SwiftUI re-render.
+class WatchUIBridgeState: ObservableObject {
+ static let shared = WatchUIBridgeState()
+
+ @Published var rootNode: WatchUINode?
+ var nodes: [Int32: WatchUINode] = [:]
+ var nextNodeId: Int32 = 1
+
+ private init() {}
+
+ func createNode(nodeType: Int32) -> Int32 {
+ let nodeId = nextNodeId
+ nextNodeId += 1
+ let node = WatchUINode(id: nodeId, nodeType: nodeType)
+ nodes[nodeId] = node
+ os_log("createNode(type=%d) -> %d", log: bridgeLog, type: .info, nodeType, nodeId)
+ return nodeId
+ }
+
+ func setStrProp(nodeId: Int32, propId: Int32, value: String) {
+ guard let node = nodes[nodeId] else { return }
+ switch propId {
+ case 0: // UI_PROP_TEXT
+ os_log("setStrProp(node=%d, text=\"%{public}s\")", log: bridgeLog, type: .info, nodeId, value)
+ node.text = value
+ case 1: // UI_PROP_COLOR
+ os_log("setStrProp(node=%d, color=\"%{public}s\")", log: bridgeLog, type: .info, nodeId, value)
+ node.textColor = value
+ case 2: // UI_PROP_HINT
+ os_log("setStrProp(node=%d, hint=\"%{public}s\")", log: bridgeLog, type: .info, nodeId, value)
+ node.hint = value
+ case 3: // UI_PROP_BG_COLOR
+ os_log("setStrProp(node=%d, bgColor=\"%{public}s\")", log: bridgeLog, type: .info, nodeId, value)
+ node.backgroundColor = value
+ case 4: // UI_PROP_IMAGE_RESOURCE
+ os_log("setStrProp(node=%d, imageResource=\"%{public}s\")", log: bridgeLog, type: .info, nodeId, value)
+ node.imageResource = value
+ case 5: // UI_PROP_IMAGE_FILE
+ os_log("setStrProp(node=%d, imageFile=\"%{public}s\")", log: bridgeLog, type: .info, nodeId, value)
+ node.imageFile = value
+ default:
+ os_log("setStrProp: unknown propId %d", log: bridgeLog, type: .info, propId)
+ }
+ }
+
+ func setNumProp(nodeId: Int32, propId: Int32, value: Double) {
+ guard let node = nodes[nodeId] else { return }
+ switch propId {
+ case 0: // UI_PROP_FONT_SIZE
+ os_log("setNumProp(node=%d, fontSize=%.1f)", log: bridgeLog, type: .info, nodeId, value)
+ node.fontSize = CGFloat(value)
+ case 1: // UI_PROP_PADDING
+ os_log("setNumProp(node=%d, padding=%.1f)", log: bridgeLog, type: .info, nodeId, value)
+ node.padding = CGFloat(value)
+ case 2: // UI_PROP_INPUT_TYPE
+ os_log("setNumProp(node=%d, inputType=%.0f)", log: bridgeLog, type: .info, nodeId, value)
+ node.inputType = Int32(value)
+ case 4: // UI_PROP_SCALE_TYPE
+ os_log("setNumProp(node=%d, scaleType=%.0f)", log: bridgeLog, type: .info, nodeId, value)
+ node.scaleType = Int32(value)
+ default:
+ os_log("setNumProp: unknown propId %d", log: bridgeLog, type: .info, propId)
+ }
+ }
+
+ func setHandler(nodeId: Int32, eventType: Int32, callbackId: Int32) {
+ guard let node = nodes[nodeId] else { return }
+ node.callbackId = callbackId
+ os_log("setHandler(node=%d, click, callback=%d)", log: bridgeLog, type: .info, nodeId, callbackId)
+ }
+
+ func addChild(parentId: Int32, childId: Int32) {
+ guard let parent = nodes[parentId], let child = nodes[childId] else { return }
+ parent.children.append(child)
+ }
+
+ func removeChild(parentId: Int32, childId: Int32) {
+ guard let parent = nodes[parentId] else { return }
+ parent.children.removeAll { $0.id == childId }
+ }
+
+ func destroyNode(nodeId: Int32) {
+ nodes.removeValue(forKey: nodeId)
+ }
+
+ func setRoot(nodeId: Int32) {
+ rootNode = nodes[nodeId]
+ os_log("setRoot(node=%d)", log: bridgeLog, type: .info, nodeId)
+ }
+
+ func setImageData(nodeId: Int32, data: UnsafePointer?, length: Int32) {
+ guard let node = nodes[nodeId], let data = data else { return }
+ node.imageData = Data(bytes: data, count: Int(length))
+ os_log("setImageData(node=%d, %d bytes)", log: bridgeLog, type: .info, nodeId, length)
+ }
+
+ func clear() {
+ rootNode = nil
+ nodes.removeAll()
+ nextNodeId = 1
+ os_log("clear()", log: bridgeLog, type: .info)
+ }
+}
+
+// MARK: - C-callable bridge functions (@_cdecl)
+
+@_cdecl("watchos_create_node")
+func watchos_create_node(_ nodeType: Int32) -> Int32 {
+ return WatchUIBridgeState.shared.createNode(nodeType: nodeType)
+}
+
+@_cdecl("watchos_set_str_prop")
+func watchos_set_str_prop(_ nodeId: Int32, _ propId: Int32, _ value: UnsafePointer?) {
+ let str = value.map { String(cString: $0) } ?? ""
+ WatchUIBridgeState.shared.setStrProp(nodeId: nodeId, propId: propId, value: str)
+}
+
+@_cdecl("watchos_set_num_prop")
+func watchos_set_num_prop(_ nodeId: Int32, _ propId: Int32, _ value: Double) {
+ WatchUIBridgeState.shared.setNumProp(nodeId: nodeId, propId: propId, value: value)
+}
+
+@_cdecl("watchos_set_handler")
+func watchos_set_handler(_ nodeId: Int32, _ eventType: Int32, _ callbackId: Int32) {
+ WatchUIBridgeState.shared.setHandler(nodeId: nodeId, eventType: eventType, callbackId: callbackId)
+}
+
+@_cdecl("watchos_add_child")
+func watchos_add_child(_ parentId: Int32, _ childId: Int32) {
+ WatchUIBridgeState.shared.addChild(parentId: parentId, childId: childId)
+}
+
+@_cdecl("watchos_remove_child")
+func watchos_remove_child(_ parentId: Int32, _ childId: Int32) {
+ WatchUIBridgeState.shared.removeChild(parentId: parentId, childId: childId)
+}
+
+@_cdecl("watchos_destroy_node")
+func watchos_destroy_node(_ nodeId: Int32) {
+ WatchUIBridgeState.shared.destroyNode(nodeId: nodeId)
+}
+
+@_cdecl("watchos_set_root")
+func watchos_set_root(_ nodeId: Int32) {
+ WatchUIBridgeState.shared.setRoot(nodeId: nodeId)
+}
+
+@_cdecl("watchos_set_image_data")
+func watchos_set_image_data(_ nodeId: Int32, _ data: UnsafePointer?, _ length: Int32) {
+ WatchUIBridgeState.shared.setImageData(nodeId: nodeId, data: data, length: length)
+}
+
+@_cdecl("watchos_clear")
+func watchos_clear() {
+ WatchUIBridgeState.shared.clear()
+}
diff --git a/watchos/HaskellMobile/WatchUINode.swift b/watchos/HaskellMobile/WatchUINode.swift
new file mode 100644
index 00000000..120e794b
--- /dev/null
+++ b/watchos/HaskellMobile/WatchUINode.swift
@@ -0,0 +1,28 @@
+import SwiftUI
+import os.log
+
+/// Observable node model for SwiftUI rendering.
+/// Each node has a type, properties, children, and an optional callback ID.
+class WatchUINode: ObservableObject, Identifiable {
+ let id: Int32
+ let nodeType: Int32
+
+ @Published var text: String = ""
+ @Published var hint: String = ""
+ @Published var fontSize: CGFloat?
+ @Published var padding: CGFloat?
+ @Published var inputType: Int32 = 0
+ @Published var callbackId: Int32 = -1
+ @Published var textColor: String?
+ @Published var backgroundColor: String?
+ @Published var imageResource: String?
+ @Published var imageFile: String?
+ @Published var imageData: Data?
+ @Published var scaleType: Int32 = 0
+ @Published var children: [WatchUINode] = []
+
+ init(id: Int32, nodeType: Int32) {
+ self.id = id
+ self.nodeType = nodeType
+ }
+}
diff --git a/watchos/project.yml b/watchos/project.yml
new file mode 100644
index 00000000..10161a96
--- /dev/null
+++ b/watchos/project.yml
@@ -0,0 +1,27 @@
+name: HaskellMobile
+options:
+ bundleIdPrefix: me.jappie
+ deploymentTarget:
+ watchOS: "9.0"
+
+targets:
+ HaskellMobile:
+ type: application
+ platform: watchOS
+ sources:
+ - HaskellMobile
+ info:
+ path: HaskellMobile/Info.plist
+ properties:
+ CFBundleShortVersionString: "1.0"
+ CFBundleVersion: "1"
+ WKApplication: true
+ WKRunsIndependentlyOfCompanionApp: true
+ WKCompanionAppBundleIdentifier: me.jappie.haskellmobile
+ settings:
+ base:
+ PRODUCT_BUNDLE_IDENTIFIER: me.jappie.haskellmobile.watchkitapp
+ SWIFT_OBJC_BRIDGING_HEADER: HaskellMobile/HaskellMobile-Bridging-Header.h
+ LIBRARY_SEARCH_PATHS: ["$(inherited)", "$(PROJECT_DIR)/lib"]
+ HEADER_SEARCH_PATHS: ["$(inherited)", "$(PROJECT_DIR)/include"]
+ OTHER_LDFLAGS: ["$(inherited)", "-lHaskellMobile", "-lz", "-liconv", "-lffi", "-lc++"]