diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 38694435..17eb5a41 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -7,8 +7,12 @@ on: permissions: actions: write +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + jobs: - nix: + android: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -16,19 +20,30 @@ jobs: 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 }} - - uses: cachix/cachix-action@v15 with: name: jappie - signingKey: '${{ secrets.CACHIX_SIGNING_KEY }}' + authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}' - run: nix-build - - run: nix-shell --run "echo OK" + - run: nix-build nix/android.nix + - run: nix-build nix/apk.nix -o result-apk + - name: Upload Android APK + if: github.ref == 'refs/heads/master' + uses: actions/upload-artifact@v4 + with: + name: haskell-mobile-android + path: result-apk/haskell-mobile.apk + - name: Build UI test + run: nix-build nix/emulator-ui.nix -o result-emulator-ui + - name: Run UI rendering test + run: ./result-emulator-ui/bin/test-ui - name: Cancel workflow on failure if: failure() continue-on-error: true @@ -36,40 +51,42 @@ 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 steps: - uses: actions/checkout@v4 - - uses: haskell-actions/setup@v2 - with: - ghc-version: ${{ matrix.ghc }} - - - name: Cabal cache + - 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-ios-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-ios- + - uses: cachix/install-nix-action@v31 + with: + extra_nix_config: | + access-tokens = github.com=${{ secrets.GITHUB_TOKEN }} + - uses: cachix/cachix-action@v15 + with: + name: jappie + authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}' + - run: nix-build nix/ios.nix + - name: Build simulator test + run: nix-build nix/simulator.nix -o result-simulator + - name: Run simulator lifecycle test + run: ./result-simulator/bin/test-lifecycle-ios + - name: Build UI test + run: nix-build nix/simulator-ui.nix -o result-simulator-ui + - name: Run UI rendering test + run: ./result-simulator-ui/bin/test-ui-ios + - name: Upload iOS library + if: github.ref == 'refs/heads/master' + uses: actions/upload-artifact@v4 + with: + name: haskell-mobile-ios + path: | + result/lib/libHaskellMobile.a + result/include/HaskellMobile.h - 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..00155c94 100644 --- a/Readme.md +++ b/Readme.md @@ -1,89 +1,110 @@ -[![https://jappieklooster.nl](https://img.shields.io/badge/blog-jappieklooster.nl-lightgrey)](https://jappieklooster.nl/tag/haskell.html) -[![Github actions build status](https://img.shields.io/github/actions/workflow/status/jappeace/haskell-template-project/nix.yaml?branch=master)](https://github.com/jappeace/haskell-template-project/actions) -[![Jappiejappie](https://img.shields.io/badge/discord-jappiejappie-black?logo=discord)](https://discord.gg/Hp4agqy) -[![Hackage version](https://img.shields.io/hackage/v/template.svg?label=Hackage)](https://hackage.haskell.org/package/template) +[![CI](https://img.shields.io/github/actions/workflow/status/jappeace/haskell-mobile/ci.yaml?branch=master)](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`. - -``` -git clone git@github.com:jappeace/haskell-template-project.git new-project -cd new-project +```bash +nix-shell +cabal build all +cabal test all ``` -+ [ ] 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 -``` -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 +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 ``` -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. +The APK is written to `result/haskell-mobile.apk`. -#### Readme +### iOS static library -+ [ ] 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 +Requires macOS (same ISA as iOS aarch64): -### Tools -Enter the nix shell. -``` -nix-shell -``` -You can checkout the makefile to see what's available: -``` -cat makefile +```bash +nix-build nix/ios.nix ``` -### Running -``` -make run +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 ``` -### Fast filewatch which runs tests +Configure signing in Xcode (team, bundle ID, provisioning profile), then build and run. + +## Installing + +### Android + +```bash +adb install result/haskell-mobile.apk ``` -make ghcid + +### iOS + +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). + +## CI + +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 ``` + +# 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..da0ac9f3 --- /dev/null +++ b/android/AndroidManifest.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + diff --git a/android/java/me/jappie/haskellmobile/MainActivity.java b/android/java/me/jappie/haskellmobile/MainActivity.java new file mode 100644 index 00000000..4d876332 --- /dev/null +++ b/android/java/me/jappie/haskellmobile/MainActivity.java @@ -0,0 +1,96 @@ +package me.jappie.haskellmobile; + +import android.app.Activity; +import android.os.Bundle; +import android.text.Editable; +import android.text.TextWatcher; +import android.view.View; +import android.widget.EditText; + +public class MainActivity 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(); + + @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/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..7ba11428 100644 --- a/app/Main.hs +++ b/app/Main.hs @@ -1,7 +1,27 @@ - module Main where -import qualified Template +import HaskellMobile (appContext, platformLog) +import HaskellMobile.Lifecycle (LifecycleEvent(..), MobileContext(onLifecycle)) +-- | Simulate a mobile app lifecycle. +-- On Android\/iOS the platform bridge dispatches these events via +-- 'haskellOnLifecycle'. Here we drive them from Haskell to show +-- that the listener callback fires for every event. main :: IO () -main = Template.main +main = do + platformLog "Waiting for lifecycle events..." + let listen = onLifecycle appContext + + -- 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/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..be0fdbee --- /dev/null +++ b/cbits/jni_bridge.c @@ -0,0 +1,133 @@ +/* + * 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. + */ + +#include +#include +#include +#include "HsFFI.h" + +/* Haskell foreign exports */ +extern void haskellInit(void); +extern char* haskellGreet(const char* name); +extern void *haskellCreateContext(void); +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); + +/* 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); +extern void android_handle_text_change(JNIEnv *env, jobject view, jstring text); + +/* 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); + haskellInit(); + g_haskell_ctx = haskellCreateContext(); + return JNI_VERSION_1_6; +} + +JNIEXPORT void JNICALL +JNI_OnUnload(JavaVM *vm, void *reserved) +{ + hs_exit(); +} + +JNIEXPORT jstring JNICALL +Java_me_jappie_haskellmobile_MainActivity_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 +Java_me_jappie_haskellmobile_MainActivity_renderUI(JNIEnv *env, jobject thiz) +{ + setup_android_ui_bridge(env, thiz, g_haskell_ctx); + haskellRenderUI(g_haskell_ctx); +} + +JNIEXPORT void JNICALL +Java_me_jappie_haskellmobile_MainActivity_onButtonClick(JNIEnv *env, jobject thiz, jobject view) +{ + android_handle_click(env, view); +} + +JNIEXPORT void JNICALL +Java_me_jappie_haskellmobile_MainActivity_onTextChange(JNIEnv *env, jobject thiz, jobject view, jstring text) +{ + android_handle_text_change(env, view, text); +} + +/* Lifecycle JNI callbacks */ +JNIEXPORT void JNICALL +Java_me_jappie_haskellmobile_MainActivity_onLifecycleCreate(JNIEnv *env, jobject thiz) +{ + haskellOnLifecycle(g_haskell_ctx, LIFECYCLE_CREATE); +} + +JNIEXPORT void JNICALL +Java_me_jappie_haskellmobile_MainActivity_onLifecycleStart(JNIEnv *env, jobject thiz) +{ + haskellOnLifecycle(g_haskell_ctx, LIFECYCLE_START); +} + +JNIEXPORT void JNICALL +Java_me_jappie_haskellmobile_MainActivity_onLifecycleResume(JNIEnv *env, jobject thiz) +{ + haskellOnLifecycle(g_haskell_ctx, LIFECYCLE_RESUME); +} + +JNIEXPORT void JNICALL +Java_me_jappie_haskellmobile_MainActivity_onLifecyclePause(JNIEnv *env, jobject thiz) +{ + haskellOnLifecycle(g_haskell_ctx, LIFECYCLE_PAUSE); +} + +JNIEXPORT void JNICALL +Java_me_jappie_haskellmobile_MainActivity_onLifecycleStop(JNIEnv *env, jobject thiz) +{ + haskellOnLifecycle(g_haskell_ctx, LIFECYCLE_STOP); +} + +JNIEXPORT void JNICALL +Java_me_jappie_haskellmobile_MainActivity_onLifecycleDestroy(JNIEnv *env, jobject thiz) +{ + haskellOnLifecycle(g_haskell_ctx, LIFECYCLE_DESTROY); +} + +JNIEXPORT void JNICALL +Java_me_jappie_haskellmobile_MainActivity_onLifecycleLowMemory(JNIEnv *env, jobject thiz) +{ + haskellOnLifecycle(g_haskell_ctx, LIFECYCLE_LOW_MEMORY); +} 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/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/ui_bridge.c b/cbits/ui_bridge.c new file mode 100644 index 00000000..89c57277 --- /dev/null +++ b/cbits/ui_bridge.c @@ -0,0 +1,107 @@ +/* + * 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_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..345a1248 --- /dev/null +++ b/cbits/ui_bridge_android.c @@ -0,0 +1,428 @@ +/* + * 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__) + +/* Maximum number of native views we can hold at once. + * Re-renders clear all nodes, so this only bounds a single frame. */ +#define MAX_NODES 256 + +/* 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 */ +static void *g_haskell_ctx = NULL; /* opaque Haskell context */ + +/* Node pool: indexed by nodeId (1-based, 0 = invalid) */ +static jobject g_nodes[MAX_NODES]; +static int32_t g_next_node_id = 1; + +/* ---- 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_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_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; + +/* 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_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, + .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/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_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"); + + return 0; +} + +/* ---- Node pool helpers ---- */ +static jobject get_node(int32_t nodeId) +{ + if (nodeId < 1 || nodeId >= MAX_NODES) return NULL; + return g_nodes[nodeId]; +} + +/* ---- Callback implementation ---- */ + +static int32_t android_create_node(int32_t nodeType) +{ + if (g_next_node_id >= MAX_NODES) { + LOGE("Node pool exhausted (max %d)", MAX_NODES); + return 0; + } + + 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; + 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; + } + default: + LOGI("setStrProp: unknown propId %d", propId); + break; + } +} + +static void android_set_num_prop(int32_t nodeId, int32_t propId, double value) +{ + /* TODO: Implement font size, padding, etc. */ + LOGI("setNumProp(node=%d, prop=%d, value=%.2f) — not yet implemented", nodeId, propId, value); +} + +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 */ + (*env)->CallVoidMethod(env, g_activity, g_method_registerTextWatcher, view); + LOGI("setHandler(node=%d, textChange, callback=%d)", nodeId, callbackId); + 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; + 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); + g_haskell_ctx = haskellCtx; + + memset(g_nodes, 0, sizeof(g_nodes)); + 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) +{ + /* 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(g_haskell_ctx, 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) +{ + 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(g_haskell_ctx, 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/template.cabal b/haskell-mobile.cabal similarity index 64% rename from template.cabal rename to haskell-mobile.cabal index 426dcb4f..379443b1 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,23 @@ common common-options library import: common-options exposed-modules: - Template - other-modules: - Paths_template + HaskellMobile + HaskellMobile.App + HaskellMobile.Lifecycle + HaskellMobile.Widget + HaskellMobile.UIBridge + HaskellMobile.Render hs-source-dirs: src + build-depends: + text, + containers + c-sources: + cbits/android_stubs.c + cbits/platform_log.c + cbits/ui_bridge.c + include-dirs: + include executable exe import: common-options @@ -73,20 +84,18 @@ 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 diff --git a/include/HaskellMobile.h b/include/HaskellMobile.h new file mode 100644 index 00000000..2c99aa8a --- /dev/null +++ b/include/HaskellMobile.h @@ -0,0 +1,43 @@ +#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 */ +void haskellInit(void); +char *haskellGreet(const char *name); + +/* Create a default mobile context. Returns an opaque pointer. + * Call after haskellInit(). */ +void *haskellCreateContext(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 haskellCreateContext(). */ +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 haskellCreateContext(). */ +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 haskellCreateContext(). */ +void haskellOnUIEvent(void *ctx, int32_t callbackId); + +#endif /* HASKELL_MOBILE_H */ diff --git a/include/UIBridge.h b/include/UIBridge.h new file mode 100644 index 00000000..437e8473 --- /dev/null +++ b/include/UIBridge.h @@ -0,0 +1,57 @@ +#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 + +/* Property IDs for string properties */ +#define UI_PROP_TEXT 0 +#define UI_PROP_COLOR 1 +#define UI_PROP_HINT 2 + +/* Property IDs for numeric properties */ +#define UI_PROP_FONT_SIZE 0 +#define UI_PROP_PADDING 1 + +/* 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 (*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_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..3e824a85 --- /dev/null +++ b/ios/HaskellMobile/ContentView.swift @@ -0,0 +1,35 @@ +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 a "+" 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) + } + } + + 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..8d5b8f6f --- /dev/null +++ b/ios/HaskellMobile/HaskellBridge.swift @@ -0,0 +1,52 @@ +import Foundation + +/// Swift wrapper around the Haskell FFI functions exposed via C. +class HaskellBridge { + // 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) + haskellInit() + context = haskellCreateContext() + } + + /// 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) { + haskellOnUIEvent(context, callbackId) + } + + /// 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..b408b5ca --- /dev/null +++ b/ios/HaskellMobile/HaskellMobile-Bridging-Header.h @@ -0,0 +1,5 @@ +#include "HaskellMobile.h" +#include "UIBridge.h" + +/* iOS UI bridge setup — called from Swift before haskellRenderUI */ +void setup_ios_ui_bridge(void *viewController, 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/UIBridgeIOS.m b/ios/HaskellMobile/UIBridgeIOS.m new file mode 100644 index 00000000..a43ae041 --- /dev/null +++ b/ios/HaskellMobile/UIBridgeIOS.m @@ -0,0 +1,286 @@ +/* + * 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__) + +/* Maximum number of native views we can hold at once. + * Re-renders clear all nodes, so this only bounds a single frame. */ +#define MAX_NODES 256 + +/* Haskell FFI exports (declared here since this file is compiled by Xcode) */ +extern void haskellOnUIEvent(void *ctx, int callbackId); + +/* ---- Global state (valid only on the main thread) ---- */ +static UIViewController *g_viewController = nil; +static void *g_haskell_ctx = NULL; + +/* Node pool: indexed by nodeId (1-based, 0 = invalid) */ +static __strong UIView *g_nodes[MAX_NODES]; +static int32_t g_next_node_id = 1; + +/* ---- Singleton handler for button taps ---- */ +@interface IOSBridgeHandler : NSObject ++ (instancetype)shared; +- (void)handleTap:(UIButton *)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(g_haskell_ctx, callbackId); +} + +@end + +/* ---- Node pool helpers ---- */ +static UIView *get_node(int32_t nodeId) +{ + if (nodeId < 1 || nodeId >= MAX_NODES) return nil; + 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_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, + .setHandler = ios_set_handler, + .addChild = ios_add_child, + .removeChild = ios_remove_child, + .destroyNode = ios_destroy_node, + .setRoot = ios_set_root, + .clear = ios_clear, +}; + +/* ---- Callback implementation ---- */ + +static int32_t ios_create_node(int32_t nodeType) +{ + if (g_next_node_id >= MAX_NODES) { + LOGE("Node pool exhausted (max %d)", MAX_NODES); + return 0; + } + + 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; + } + 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; +} + +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]; + } + break; + default: + LOGI("setStrProp: unknown propId %d", propId); + break; + } +} + +static void ios_set_num_prop(int32_t nodeId, int32_t propId, double value) +{ + /* TODO: Implement font size, padding, etc. */ + LOGI("setNumProp(node=%d, prop=%d, value=%.2f) — not yet implemented", nodeId, propId, value); +} + +static void ios_set_handler(int32_t nodeId, int32_t eventType, int32_t callbackId) +{ + UIView *view = get_node(nodeId); + if (!view) return; + + if (eventType != UI_EVENT_CLICK) { + LOGI("setHandler: unknown eventType %d", eventType); + return; + } + + /* Store callbackId in the view's tag property */ + view.tag = callbackId; + + LOGI("setHandler(node=%d, click, callback=%d)", nodeId, callbackId); +} + +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; + + if ([parent isKindOfClass:[UIStackView class]]) { + [(UIStackView *)parent addArrangedSubview:child]; + } else { + [parent 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]; + + /* Center the root view in the view controller's view */ + view.translatesAutoresizingMaskIntoConstraints = NO; + [NSLayoutConstraint activateConstraints:@[ + [view.centerXAnchor constraintEqualToAnchor:container.centerXAnchor], + [view.centerYAnchor constraintEqualToAnchor:container.centerYAnchor], + ]]; + + 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; + } + } + g_next_node_id = 1; + 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; + g_haskell_ctx = haskellCtx; + + memset(g_nodes, 0, sizeof(g_nodes)); + g_next_node_id = 1; + + ui_register_callbacks(&g_ios_callbacks); + LOGI("iOS UI bridge initialized"); +} diff --git a/ios/project.yml b/ios/project.yml new file mode 100644 index 00000000..2ab3cb69 --- /dev/null +++ b/ios/project.yml @@ -0,0 +1,27 @@ +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" + 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++"] 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..0c23e55d --- /dev/null +++ b/nix/android.nix @@ -0,0 +1,130 @@ +# Android shared library build pipeline. +# Builds Haskell to a shared .so for aarch64-android using nixpkgs +# cross-compilation (pkgsCross.aarch64-android-prebuilt) instead of +# haskell.nix, which builds GHC from source without cache hits. +# +# Uses Google's prebuilt NDK toolchain via nixpkgs, avoiding the +# LLVM 19 compiler-rt issue (NixOS/nixpkgs#380604). +{ sources ? import ../npins }: +let + pkgs = import sources.nixpkgs { + config.allowUnfree = true; + config.android_sdk.accept_license = true; + }; + + # Cross-compilation packages for Android using prebuilt NDK toolchain + androidPkgs = pkgs.pkgsCross.aarch64-android-prebuilt; + + # Cross-GHC: runs on x86_64-linux, produces aarch64-android code + ghc = androidPkgs.haskellPackages.ghc; + ghcCmd = "${ghc}/bin/${ghc.targetPrefix}ghc"; + + # Path to GHC's boot library static archives (for static linking into .so) + ghcPkgDir = "${ghc}/lib/${ghc.targetPrefix}ghc-${ghc.version}/lib/aarch64-linux-ghc-${ghc.version}"; + + # NDK toolchain for compiling the JNI bridge C code + 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/aarch64-linux-android26-clang"; + sysroot = "${ndk}/toolchains/llvm/prebuilt/linux-x86_64/sysroot"; + +in pkgs.stdenv.mkDerivation { + pname = "haskell-mobile-android"; + version = "0.1.0.0"; + + src = ../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 + ${ndkCc} -c -fPIC \ + -I${sysroot}/usr/include \ + -I$RTS_INCLUDE \ + -I${../include} \ + -o jni_bridge.o \ + ${../cbits/jni_bridge.c} + + ${ndkCc} -c -fPIC \ + -I${sysroot}/usr/include \ + -I$RTS_INCLUDE \ + -I${../include} \ + -o ui_bridge_android.o \ + ${../cbits/ui_bridge_android.c} + + # Step 2: Copy extra source modules into the 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 ${../src}/HaskellMobile/Lifecycle.hs HaskellMobile/ + cp ${../src}/HaskellMobile/App.hs HaskellMobile/ + cp ${../src}/HaskellMobile/Widget.hs HaskellMobile/ + cp ${../src}/HaskellMobile/UIBridge.hs HaskellMobile/ + cp ${../src}/HaskellMobile/Render.hs HaskellMobile/ + + # Step 3: Compile Haskell to shared library with cross-GHC. + # We use --whole-archive to statically link GHC's boot libraries + # (RTS, base, ghc-prim, etc.) into our .so — Android's linker + # can't find GHC's separate shared libraries at runtime. + GHC_PKG_DIR="${ghcPkgDir}" + + # Discover containers library archive (hash varies by GHC version) + CONTAINERS_LIB=$(find $GHC_PKG_DIR -name "libHScontainers-*.a" | head -1) + echo "Containers lib: $CONTAINERS_LIB" + + ${ghcCmd} -shared -O2 \ + -o libhaskellmobile.so \ + -I${../include} \ + HaskellMobile.hs \ + ${../cbits/android_stubs.c} \ + ${../cbits/platform_log.c} \ + ${../cbits/numa_stubs.c} \ + ${../cbits/ui_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-Wl,-u,haskellInit \ + -optl-Wl,-u,haskellGreet \ + -optl-Wl,-u,haskellOnLifecycle \ + -optl-Wl,-u,haskellCreateContext \ + -optl-Wl,-u,haskellRenderUI \ + -optl-Wl,-u,haskellOnUIEvent \ + -optl-Wl,-u,haskellOnUITextChange \ + -optl-Wl,--whole-archive \ + -optl$GHC_PKG_DIR/rts-1.0.2/libHSrts-1.0.2.a \ + -optl$GHC_PKG_DIR/ghc-prim-0.12.0-b5b0/libHSghc-prim-0.12.0-b5b0.a \ + -optl$GHC_PKG_DIR/ghc-bignum-1.3-3be2/libHSghc-bignum-1.3-3be2.a \ + -optl$GHC_PKG_DIR/ghc-internal-9.1003.0-04f5/libHSghc-internal-9.1003.0-04f5.a \ + -optl$GHC_PKG_DIR/base-4.20.2.0-ecb4/libHSbase-4.20.2.0-ecb4.a \ + -optl$GHC_PKG_DIR/integer-gmp-1.1-e5a1/libHSinteger-gmp-1.1-e5a1.a \ + -optl$GHC_PKG_DIR/text-2.1.3-8cdf/libHStext-2.1.3-8cdf.a \ + -optl$GHC_PKG_DIR/array-0.5.8.0-39be/libHSarray-0.5.8.0-39be.a \ + -optl$GHC_PKG_DIR/deepseq-1.5.0.0-dd79/libHSdeepseq-1.5.0.0-dd79.a \ + -optl$CONTAINERS_LIB \ + -optl-Wl,--no-whole-archive + ''; + + installPhase = '' + mkdir -p $out/lib/arm64-v8a + cp libhaskellmobile.so $out/lib/arm64-v8a/ + + # Bundle runtime dependencies (not provided by Android) + cp ${androidPkgs.gmp}/lib/libgmp.so $out/lib/arm64-v8a/ + cp ${androidPkgs.libffi}/lib/libffi.so $out/lib/arm64-v8a/ + ''; +} diff --git a/nix/apk.nix b/nix/apk.nix new file mode 100644 index 00000000..a9a1a9c8 --- /dev/null +++ b/nix/apk.nix @@ -0,0 +1,112 @@ +{ sources ? import ../npins }: +let + pkgs = import sources.nixpkgs { + config.allowUnfree = true; + config.android_sdk.accept_license = true; + }; + + sharedLib = import ./android.nix { inherit sources; }; + + androidComposition = pkgs.androidenv.composeAndroidPackages { + buildToolsVersions = [ "34.0.0" ]; + platformVersions = [ "34" ]; + includeNDK = false; + }; + + androidSdk = androidComposition.androidsdk; + buildTools = "${androidSdk}/libexec/android-sdk/build-tools/34.0.0"; + platform = "${androidSdk}/libexec/android-sdk/platforms/android-34"; + +in pkgs.stdenv.mkDerivation { + name = "haskell-mobile-apk"; + + src = ../android; + + 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 R.java + find gen -name "*.java" -print + + # Compile R.java and MainActivity.java + javac \ + -source 11 -target 11 \ + -classpath ${platform}/android.jar \ + -d classes \ + gen/me/jappie/haskellmobile/R.java \ + java/me/jappie/haskellmobile/MainActivity.java + + 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 ===" + # Start from the base APK (has resources + manifest) + cp base.apk unsigned.apk + + # Add DEX file + cd dex_out + zip -j ../unsigned.apk classes.dex + cd .. + + # Add native libraries (main .so + runtime dependencies like libgmp, libffi) + mkdir -p lib/arm64-v8a + cp ${sharedLib}/lib/arm64-v8a/*.so lib/arm64-v8a/ + zip -r unsigned.apk lib/ + + echo "=== Step 6: Zipalign ===" + ${buildTools}/zipalign -f 4 unsigned.apk aligned.apk + + echo "=== Step 7: Sign APK ===" + # Generate a debug keystore + 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 haskell-mobile.apk \ + aligned.apk + ''; + + installPhase = '' + mkdir -p $out + cp haskell-mobile.apk $out/ + ''; +} diff --git a/nix/ci.nix b/nix/ci.nix new file mode 100644 index 00000000..f6d56bcf --- /dev/null +++ b/nix/ci.nix @@ -0,0 +1,36 @@ +{ sources ? import ../npins }: +let + pkgs = import sources.nixpkgs { + config.allowUnfree = true; + config.android_sdk.accept_license = true; + }; + isDarwin = builtins.currentSystem == "aarch64-darwin" + || builtins.currentSystem == "x86_64-darwin"; + + runTest = name: testDrv: scriptName: + pkgs.runCommand "run-${name}" { __noChroot = true; } '' + ${testDrv}/bin/${scriptName} + touch $out + ''; +in { + # Build artifacts + native = import ../default.nix {}; + android = import ./android.nix { inherit sources; }; + apk = import ./apk.nix { inherit sources; }; + + # Android tests (Linux) + emulator-test = runTest "emulator-test" + (import ./emulator.nix { inherit sources; }) "test-lifecycle"; + emulator-ui-test = runTest "emulator-ui-test" + (import ./emulator-ui.nix { inherit sources; }) "test-ui"; + emulator-ui-buttons-test = runTest "emulator-ui-buttons-test" + (import ./emulator-ui-buttons.nix { inherit sources; }) "test-ui-buttons"; +} // (if isDarwin then { + ios = import ./ios.nix { inherit sources; }; + simulator-test = runTest "simulator-test" + (import ./simulator.nix { inherit sources; }) "test-lifecycle-ios"; + simulator-ui-test = runTest "simulator-ui-test" + (import ./simulator-ui.nix { inherit sources; }) "test-ui-ios"; + simulator-ui-buttons-test = runTest "simulator-ui-buttons-test" + (import ./simulator-ui-buttons.nix { inherit sources; }) "test-ui-buttons-ios"; +} else {}) diff --git a/nix/emulator-ui.nix b/nix/emulator-ui.nix new file mode 100644 index 00000000..17f0897b --- /dev/null +++ b/nix/emulator-ui.nix @@ -0,0 +1,449 @@ +# Android emulator UI rendering test. +# +# Boots an emulator, installs the APK, and verifies: +# 1. The counter app renders (logcat: setStrProp with "Counter: 0", setRoot, setHandler) +# 2. The view hierarchy contains expected elements (uiautomator dump) +# 3. Tapping the "+" button updates state (logcat: Click dispatched, Counter: 1) +# 4. The updated view hierarchy reflects the new state +# +# Independent from nix/emulator.nix (lifecycle test) — can run in parallel. +# +# Usage: +# nix-build nix/emulator-ui.nix -o result-emulator-ui +# ./result-emulator-ui/bin/test-ui +{ sources ? import ../npins }: +let + pkgs = import sources.nixpkgs { + config.allowUnfree = true; + config.android_sdk.accept_license = true; + }; + + apk = import ./apk.nix { inherit sources; }; + + androidComposition = pkgs.androidenv.composeAndroidPackages { + platformVersions = [ "34" ]; + includeEmulator = true; + includeSystemImages = true; + systemImageTypes = [ "google_apis_playstore" ]; + abiVersions = [ "x86_64" ]; + cmdLineToolsVersion = "8.0"; + }; + + sdk = androidComposition.androidsdk; + sdkRoot = "${sdk}/libexec/android-sdk"; + + platformVersion = "34"; + systemImageType = "google_apis_playstore"; + abiVersion = "x86_64"; + imagePackage = "system-images;android-${platformVersion};${systemImageType};${abiVersion}"; + +in pkgs.stdenv.mkDerivation { + name = "haskell-mobile-emulator-ui-test"; + + dontUnpack = true; + + buildPhase = '' + mkdir -p $out/bin + + cat > $out/bin/test-ui << 'SCRIPT' +#!/usr/bin/env bash +set -euo pipefail + +# --- Configuration --- +export ANDROID_SDK_ROOT="${sdkRoot}" +export ANDROID_HOME="${sdkRoot}" +# Prevent the emulator from finding the runner's pre-installed SDK +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" +APK_PATH="${apk}/haskell-mobile.apk" +PACKAGE="me.jappie.haskellmobile" +ACTIVITY=".MainActivity" +DEVICE_NAME="test_ui" + +# --- 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 ===" + +# Detect KVM +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-ui-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" + +# Restart ADB server so it uses our fresh HOME for key generation. +"$ADB" kill-server 2>/dev/null || true +"$ADB" start-server 2>/dev/null || true + +LOGCAT_FILE="$WORK_DIR/logcat.txt" +UI_DUMP="$WORK_DIR/ui.xml" +UI_DUMP2="$WORK_DIR/ui2.xml" +EMU_PID="" + +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 + "$ADB" -s "emulator-$PORT" emu kill 2>/dev/null || true + rm -rf "$WORK_DIR" + echo "Cleanup done." +} +trap cleanup EXIT + +# --- Find free port --- +echo "=== Finding free emulator port ===" +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" + +# --- 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 + +# Debug: show AVD config +echo "=== AVD config.ini ===" +cat "$ANDROID_AVD_HOME/$DEVICE_NAME.avd/config.ini" +echo "=== End config.ini ===" + +# Fix system image path if needed: the nix SDK may store system images +# in a different structure. Patch image.sysdir.1 to point to the actual location. +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" + echo "Searching for system image..." + 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" + # Patch the AVD config to point to the correct location + 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 + +# Wait for device to settle +echo "Waiting for device to settle..." +sleep 30 + +# --- Install APK --- +echo "=== Installing APK ===" +INSTALL_OK=0 +for attempt in 1 2 3; do + if "$ADB" -s "emulator-$PORT" 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 after 3 attempts" + exit 1 +fi +echo "APK installed." + +# --- Clear and capture logcat --- +echo "=== Preparing logcat ===" +"$ADB" -s "emulator-$PORT" logcat -c + +"$ADB" -s "emulator-$PORT" logcat '*:I' > "$LOGCAT_FILE" 2>&1 & +LOGCAT_PID=$! +sleep 2 + +# --- Launch activity --- +echo "=== Launching $PACKAGE/$ACTIVITY ===" +"$ADB" -s "emulator-$PORT" shell am start -n "$PACKAGE/$ACTIVITY" + +# --- Step 2: Wait for initial render --- +echo "=== Waiting for initial render (timeout: 120s) ===" +POLL_TIMEOUT=120 +POLL_ELAPSED=0 +RENDER_DONE=0 + +while [ $POLL_ELAPSED -lt $POLL_TIMEOUT ]; do + if grep -q "setRoot" "$LOGCAT_FILE" 2>/dev/null; then + RENDER_DONE=1 + echo "Initial render detected after ~''${POLL_ELAPSED}s" + break + fi + sleep 2 + POLL_ELAPSED=$((POLL_ELAPSED + 2)) +done + +if [ $RENDER_DONE -eq 0 ]; then + echo "WARNING: setRoot not found in logcat after ''${POLL_TIMEOUT}s" +fi + +# Extra settle time for the view hierarchy to stabilize +sleep 5 + +# --- Step 3: Verify initial render via logcat --- +echo "" +echo "=== Verifying initial render (logcat) ===" +EXIT_CODE=0 + +if grep -q 'setStrProp.*Counter: 0' "$LOGCAT_FILE" 2>/dev/null; then + echo "PASS: Initial render — Counter: 0 in logcat" +else + echo "FAIL: Initial render — Counter: 0 in logcat" + EXIT_CODE=1 +fi + +if grep -q 'setRoot' "$LOGCAT_FILE" 2>/dev/null; then + echo "PASS: Initial render — setRoot in logcat" +else + echo "FAIL: Initial render — setRoot in logcat" + EXIT_CODE=1 +fi + +if grep -q 'setHandler.*click' "$LOGCAT_FILE" 2>/dev/null; then + echo "PASS: Initial render — button handlers in logcat" +else + echo "FAIL: Initial render — button handlers in logcat" + EXIT_CODE=1 +fi + +# --- Step 4: Verify view hierarchy via uiautomator dump --- +echo "" +echo "=== Verifying view hierarchy (uiautomator) ===" + +# uiautomator dump can be flaky, retry a few times +DUMP_OK=0 +for attempt in 1 2 3; do + if "$ADB" -s "emulator-$PORT" shell uiautomator dump /data/local/tmp/ui.xml 2>&1 | grep -q "dumped"; then + "$ADB" -s "emulator-$PORT" pull /data/local/tmp/ui.xml "$UI_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 'Counter: 0' "$UI_DUMP" 2>/dev/null; then + echo "PASS: UI hierarchy — Counter: 0 visible" + else + echo "FAIL: UI hierarchy — Counter: 0 visible" + EXIT_CODE=1 + fi + + if grep -q 'text="\+"' "$UI_DUMP" 2>/dev/null || grep -q 'text="+"' "$UI_DUMP" 2>/dev/null; then + echo "PASS: UI hierarchy — + button visible" + else + echo "FAIL: UI hierarchy — + button visible" + EXIT_CODE=1 + fi + + if grep -q 'text="-"' "$UI_DUMP" 2>/dev/null; then + echo "PASS: UI hierarchy — - button visible" + else + echo "FAIL: UI hierarchy — - button visible" + EXIT_CODE=1 + fi +else + echo "FAIL: UI hierarchy — could not dump view hierarchy" + EXIT_CODE=1 +fi + +# --- Step 5: Simulate "+" button tap --- +echo "" +echo "=== Tapping + button ===" + +TAP_DONE=0 +if [ $DUMP_OK -eq 1 ]; then + # Extract bounds of the "+" button from uiautomator XML + # Format: bounds="[left,top][right,bottom]" + BOUNDS=$(grep -o 'text="[+]"[^>]*bounds="\[[0-9]*,[0-9]*\]\[[0-9]*,[0-9]*\]"' "$UI_DUMP" 2>/dev/null \ + || grep -o 'text="\+"[^>]*bounds="\[[0-9]*,[0-9]*\]\[[0-9]*,[0-9]*\]"' "$UI_DUMP" 2>/dev/null \ + || echo "") + + if [ -n "$BOUNDS" ]; then + # Parse [left,top][right,bottom] + COORDS=$(echo "$BOUNDS" | grep -o '\[[0-9]*,[0-9]*\]\[[0-9]*,[0-9]*\]') + LEFT=$(echo "$COORDS" | grep -o '\[' | head -1 ; echo "$COORDS" | sed 's/\[//;s/,.*//') + 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/\]//') + + TAP_X=$(( (LEFT + RIGHT) / 2 )) + TAP_Y=$(( (TOP + BOTTOM) / 2 )) + echo "Tapping + button at ($TAP_X, $TAP_Y)" + "$ADB" -s "emulator-$PORT" shell input tap "$TAP_X" "$TAP_Y" + TAP_DONE=1 + else + echo "WARNING: Could not find + button bounds, trying text-based search fallback" + fi +fi + +# Fallback: try tapping via coordinates if bounds extraction failed +if [ $TAP_DONE -eq 0 ]; then + echo "Using fallback: tapping center-right area of screen" + # The counter app has a column layout: text on top, + and - buttons below + "$ADB" -s "emulator-$PORT" shell input tap 300 600 + TAP_DONE=1 +fi + +# Wait for re-render +echo "Waiting for re-render..." +sleep 5 + +# --- Step 6: Verify re-render via logcat --- +echo "" +echo "=== Verifying re-render (logcat) ===" + +if grep -q 'Click dispatched: callbackId=' "$LOGCAT_FILE" 2>/dev/null; then + echo "PASS: Button tap — Click dispatched in logcat" +else + echo "FAIL: Button tap — Click dispatched in logcat" + EXIT_CODE=1 +fi + +if grep -q 'setStrProp.*Counter: 1' "$LOGCAT_FILE" 2>/dev/null; then + echo "PASS: Re-render — Counter: 1 in logcat" +else + echo "FAIL: Re-render — Counter: 1 in logcat" + EXIT_CODE=1 +fi + +# --- Step 7: Verify updated view hierarchy --- +echo "" +echo "=== Verifying updated view hierarchy ===" + +DUMP2_OK=0 +for attempt in 1 2 3; do + if "$ADB" -s "emulator-$PORT" shell uiautomator dump /data/local/tmp/ui.xml 2>&1 | grep -q "dumped"; then + "$ADB" -s "emulator-$PORT" pull /data/local/tmp/ui.xml "$UI_DUMP2" 2>/dev/null + DUMP2_OK=1 + break + fi + echo " uiautomator dump attempt $attempt failed, retrying in 5s..." + sleep 5 +done + +if [ $DUMP2_OK -eq 1 ]; then + if grep -q 'Counter: 1' "$UI_DUMP2" 2>/dev/null; then + echo "PASS: UI hierarchy — Counter: 1 after tap" + else + echo "FAIL: UI hierarchy — Counter: 1 after tap" + EXIT_CODE=1 + fi +else + echo "FAIL: UI hierarchy — could not dump updated view hierarchy" + EXIT_CODE=1 +fi + +# Kill logcat capture +kill "$LOGCAT_PID" 2>/dev/null || true + +# --- Report --- +echo "" +echo "=== Filtered logcat (UIBridge) ===" +grep -i "UIBridge" "$LOGCAT_FILE" 2>/dev/null || echo "(no UIBridge lines)" +echo "--- End filtered logcat ---" + +echo "" +if [ $EXIT_CODE -eq 0 ]; then + echo "All UI rendering checks passed!" +else + echo "Some UI rendering checks failed." +fi + +exit $EXIT_CODE +SCRIPT + + chmod +x $out/bin/test-ui + ''; + + installPhase = "true"; +} diff --git a/nix/emulator.nix b/nix/emulator.nix new file mode 100644 index 00000000..037ecfde --- /dev/null +++ b/nix/emulator.nix @@ -0,0 +1,277 @@ +# Android emulator test for lifecycle callbacks. +# +# Builds a self-contained script that: +# 1. Boots an Android emulator (auto-detects KVM for acceleration) +# 2. Installs the Haskell Mobile APK +# 3. Launches the activity +# 4. Checks logcat for lifecycle event messages +# +# Usage: +# nix-build nix/emulator.nix -o result-emulator +# ./result-emulator/bin/test-lifecycle +{ sources ? import ../npins }: +let + pkgs = import sources.nixpkgs { + config.allowUnfree = true; + config.android_sdk.accept_license = true; + }; + + apk = import ./apk.nix { inherit sources; }; + + androidComposition = pkgs.androidenv.composeAndroidPackages { + platformVersions = [ "34" ]; + includeEmulator = true; + includeSystemImages = true; + systemImageTypes = [ "google_apis_playstore" ]; + abiVersions = [ "x86_64" ]; + cmdLineToolsVersion = "8.0"; + }; + + sdk = androidComposition.androidsdk; + sdkRoot = "${sdk}/libexec/android-sdk"; + + platformVersion = "34"; + systemImageType = "google_apis_playstore"; + abiVersion = "x86_64"; + imagePackage = "system-images;android-${platformVersion};${systemImageType};${abiVersion}"; + +in pkgs.stdenv.mkDerivation { + name = "haskell-mobile-emulator-test"; + + dontUnpack = true; + + buildPhase = '' + mkdir -p $out/bin + + cat > $out/bin/test-lifecycle << 'SCRIPT' +#!/usr/bin/env bash +set -euo pipefail + +# --- Configuration --- +export ANDROID_SDK_ROOT="${sdkRoot}" +ADB="$ANDROID_SDK_ROOT/platform-tools/adb" +EMULATOR="$ANDROID_SDK_ROOT/emulator/emulator" +AVDMANAGER="${sdk}/bin/avdmanager" +APK_PATH="${apk}/haskell-mobile.apk" +PACKAGE="me.jappie.haskellmobile" +ACTIVITY=".MainActivity" +DEVICE_NAME="test_lifecycle" + +# Detect KVM +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-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" + +# Restart ADB server so it uses our fresh HOME for key generation. +# Without this, a stale ADB server may hold old keys causing +# the emulator to show "unauthorized". +"$ADB" kill-server 2>/dev/null || true +"$ADB" start-server 2>/dev/null || true + +LOGCAT_FILE="$WORK_DIR/logcat.txt" +EMU_PID="" + +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 + # Also kill via adb + "$ADB" -s "emulator-$PORT" emu kill 2>/dev/null || true + rm -rf "$WORK_DIR" + echo "Cleanup done." +} +trap cleanup EXIT + +# --- Find free port --- +echo "=== Finding free emulator port ===" +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" + +# --- 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" + +# Configure 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 + +# --- 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 --- +# Poll-based wait (adb wait-for-device can fail with protocol faults) +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 + +# Wait for device to become fully responsive +echo "Waiting for device to settle..." +sleep 30 + +# --- Install APK --- +echo "=== Installing APK ===" +INSTALL_OK=0 +for attempt in 1 2 3; do + if "$ADB" -s "emulator-$PORT" 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 after 3 attempts" + exit 1 +fi +echo "APK installed." + +# --- Clear and capture logcat --- +echo "=== Preparing logcat ===" +"$ADB" -s "emulator-$PORT" logcat -c + +# Capture all logcat output (we filter later) to catch crashes too +"$ADB" -s "emulator-$PORT" logcat '*:I' > "$LOGCAT_FILE" 2>&1 & +LOGCAT_PID=$! + +# Small delay to ensure logcat is running +sleep 2 + +# --- Launch activity --- +echo "=== Launching $PACKAGE/$ACTIVITY ===" +"$ADB" -s "emulator-$PORT" shell am start -n "$PACKAGE/$ACTIVITY" + +# Wait for activity to start and log +sleep 10 + +# --- Poll logcat for lifecycle events --- +echo "=== Checking for lifecycle events (timeout: 120s) ===" +EVENTS=("Lifecycle: Create" "Lifecycle: Start" "Lifecycle: Resume" "Android UI bridge initialized") +POLL_TIMEOUT=120 +POLL_ELAPSED=0 +ALL_FOUND=0 + +while [ $POLL_ELAPSED -lt $POLL_TIMEOUT ]; do + FOUND_COUNT=0 + for event in "''${EVENTS[@]}"; do + if grep -q "$event" "$LOGCAT_FILE" 2>/dev/null; then + FOUND_COUNT=$((FOUND_COUNT + 1)) + fi + done + + if [ $FOUND_COUNT -eq ''${#EVENTS[@]} ]; then + ALL_FOUND=1 + break + fi + + sleep 2 + POLL_ELAPSED=$((POLL_ELAPSED + 2)) +done + +# Kill logcat capture +kill "$LOGCAT_PID" 2>/dev/null || true + +# --- Report results --- +echo "" +echo "=== Results ===" +echo "--- HaskellMobile logcat ---" +grep -i "HaskellMobile\|UIBridge\|haskellmobile\|loadLibrary\|FATAL\|CRASH\|System.load" "$LOGCAT_FILE" 2>/dev/null || echo "(no matching lines)" +echo "--- End filtered logcat ---" +echo "" + +EXIT_CODE=0 +for event in "''${EVENTS[@]}"; do + if grep -q "$event" "$LOGCAT_FILE" 2>/dev/null; then + echo "PASS: $event" + else + echo "FAIL: $event (not found in logcat)" + EXIT_CODE=1 + fi +done + +echo "" +if [ $EXIT_CODE -eq 0 ]; then + echo "All lifecycle events verified successfully!" +else + echo "Some lifecycle events were not detected." +fi + +exit $EXIT_CODE +SCRIPT + + chmod +x $out/bin/test-lifecycle + ''; + + 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.nix b/nix/ios.nix new file mode 100644 index 00000000..a4720acd --- /dev/null +++ b/nix/ios.nix @@ -0,0 +1,75 @@ +# iOS static library build pipeline. +# Builds Haskell to a single .a using GHC -staticlib, then patches +# Mach-O platform tags from macOS to iOS using mac2ios. +# This is a macOS-only build (same ISA as iOS aarch64). +# +# Uses pre-built GHC from nixpkgs (cache.nixos.org) instead of +# haskell.nix, which tries to build GHC from source and OOMs on +# CI runners with limited RAM. +{ sources ? import ../npins +, simulator ? false +}: +let + pkgs = import sources.nixpkgs {}; + + ghc = pkgs.haskellPackages.ghc; + + mac2ios = import ./mac2ios.nix { inherit sources pkgs; }; + + # Need static libgmp.a for merging into the iOS static library. + # Default macOS nix gmp only builds shared; override to include static. + gmpStatic = pkgs.gmp.overrideAttrs (old: { + dontDisableStatic = true; + }); + +in pkgs.stdenv.mkDerivation { + pname = "haskell-mobile-ios"; + version = "0.1.0.0"; + + src = ../src; + + nativeBuildInputs = [ ghc pkgs.cctools ]; + buildInputs = [ pkgs.libffi gmpStatic ]; + + buildPhase = '' + # Copy extra source modules into the 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 ${../src}/HaskellMobile/Lifecycle.hs HaskellMobile/ + cp ${../src}/HaskellMobile/App.hs HaskellMobile/ + cp ${../src}/HaskellMobile/Widget.hs HaskellMobile/ + cp ${../src}/HaskellMobile/UIBridge.hs HaskellMobile/ + cp ${../src}/HaskellMobile/Render.hs HaskellMobile/ + + ghc -staticlib \ + -O2 \ + -o libHaskellMobile.a \ + -I${../include} \ + -optl-lffi \ + -optl-Wl,-u,_haskellInit \ + -optl-Wl,-u,_haskellGreet \ + -optl-Wl,-u,_haskellOnLifecycle \ + -optl-Wl,-u,_haskellCreateContext \ + -optl-Wl,-u,_haskellRenderUI \ + -optl-Wl,-u,_haskellOnUIEvent \ + ${../cbits/platform_log.c} \ + ${../cbits/ui_bridge.c} \ + HaskellMobile.hs + ''; + + installPhase = '' + mkdir -p $out/lib $out/include + + # Merge libgmp.a into the Haskell static library so downstream + # consumers don't need to link libgmp separately. + echo "Merging libgmp.a into libHaskellMobile.a" + libtool -static -o libCombined.a libHaskellMobile.a ${gmpStatic}/lib/libgmp.a + mv libCombined.a libHaskellMobile.a + + ${mac2ios}/bin/mac2ios ${if simulator then "-s" else ""} libHaskellMobile.a + cp libHaskellMobile.a $out/lib/ + cp ${../include/HaskellMobile.h} $out/include/HaskellMobile.h + cp ${../include/UIBridge.h} $out/include/UIBridge.h + ''; +} 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/simulator-app.nix b/nix/simulator-app.nix new file mode 100644 index 00000000..1567f401 --- /dev/null +++ b/nix/simulator-app.nix @@ -0,0 +1,40 @@ +# Staged iOS simulator app sources. +# +# Bundles everything needed to build the iOS app for the simulator: +# - Pre-built Haskell static library (from ios.nix with simulator=true) +# - Swift/ObjC sources from ios/HaskellMobile/ +# - C headers (HaskellMobile.h, UIBridge.h) +# - project.yml for xcodegen +# +# Does NOT run xcodegen/xcodebuild (requires Xcode, not in Nix sandbox). +# Consumer test scripts (simulator.nix, simulator-ui.nix) handle the build. +# +# Usage: +# simulatorApp = import ./simulator-app.nix { inherit sources; }; +# # Then reference ${simulatorApp}/share/ios/... +{ sources ? import ../npins }: +let + pkgs = import sources.nixpkgs {}; + + iosLib = import ./ios.nix { inherit sources; simulator = true; }; + +in pkgs.stdenv.mkDerivation { + name = "haskell-mobile-simulator-app"; + + dontUnpack = true; + + buildPhase = '' + mkdir -p $out/share/ios/lib $out/share/ios/include + + # Stage Swift + ObjC sources + cp -r ${../ios}/HaskellMobile $out/share/ios/ + cp ${../ios/project.yml} $out/share/ios/project.yml + + # Stage pre-built Haskell library + headers + 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/ + ''; + + installPhase = "true"; +} diff --git a/nix/simulator-ui.nix b/nix/simulator-ui.nix new file mode 100644 index 00000000..d2a705f8 --- /dev/null +++ b/nix/simulator-ui.nix @@ -0,0 +1,309 @@ +# iOS Simulator UI rendering test. +# +# Builds and installs the app with --autotest, then verifies: +# 1. The counter app renders (os_log: setStrProp with counter label, setRoot, setHandler) +# 2. The auto-tap fires after 3s (os_log: Counter: 1 — proves initial value was 0) +# +# Independent from nix/simulator.nix (lifecycle test) — can run in parallel. +# +# Usage: +# nix-build nix/simulator-ui.nix -o result-simulator-ui +# ./result-simulator-ui/bin/test-ui-ios +{ sources ? import ../npins }: +let + pkgs = import sources.nixpkgs {}; + + simulatorApp = import ./simulator-app.nix { inherit sources; }; + + xcodegen = pkgs.xcodegen; + +in pkgs.stdenv.mkDerivation { + name = "haskell-mobile-simulator-ui-test"; + + dontUnpack = true; + + buildPhase = '' + mkdir -p $out/bin + + cat > $out/bin/test-ui-ios << 'SCRIPT' +#!/usr/bin/env bash +set -euo pipefail + +# --- Configuration --- +BUNDLE_ID="me.jappie.haskellmobile" +SCHEME="HaskellMobile" +DEVICE_TYPE="iPhone 16" +SHARE_DIR="${simulatorApp}/share/ios" + +# --- Temp working directory --- +WORK_DIR=$(mktemp -d /tmp/haskell-mobile-sim-ui-XXXX) +SIM_UDID="" + +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 UI Rendering Test ===" +echo "Working directory: $WORK_DIR" + +# --- Stage library and sources --- +echo "=== Staging Xcode project ===" +mkdir -p "$WORK_DIR/ios/lib" "$WORK_DIR/ios/include" +cp "$SHARE_DIR/lib/libHaskellMobile.a" "$WORK_DIR/ios/lib/" +cp "$SHARE_DIR/include/HaskellMobile.h" "$WORK_DIR/ios/include/" +cp "$SHARE_DIR/include/UIBridge.h" "$WORK_DIR/ios/include/" +cp -r "$SHARE_DIR/HaskellMobile" "$WORK_DIR/ios/" +cp "$SHARE_DIR/project.yml" "$WORK_DIR/ios/" +chmod -R u+w "$WORK_DIR/ios" + +# --- Generate Xcode project --- +echo "=== Generating Xcode project ===" +cd "$WORK_DIR/ios" +${xcodegen}/bin/xcodegen generate + +# --- Build for simulator --- +echo "=== Building for iOS Simulator ===" +xcodebuild build \ + -project HaskellMobile.xcodeproj \ + -scheme "$SCHEME" \ + -sdk iphonesimulator \ + -configuration Release \ + -derivedDataPath "$WORK_DIR/build" \ + CODE_SIGN_IDENTITY=- \ + CODE_SIGNING_ALLOWED=NO \ + ARCHS=arm64 \ + ONLY_ACTIVE_ARCH=NO \ + | tail -20 + +echo "Build succeeded." + +# --- Find .app bundle --- +APP_PATH=$(find "$WORK_DIR/build" -name "*.app" -type d | head -1) +if [ -z "$APP_PATH" ]; then + echo "ERROR: Could not find .app bundle in build output" + exit 1 +fi +echo "App bundle: $APP_PATH" + +# --- 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-ui-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" + +# Wait for simulator to finish booting +BOOT_TIMEOUT=120 +BOOT_ELAPSED=0 +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 + +# Brief settle time +sleep 5 + +# --- Install app --- +echo "=== Installing app ===" +xcrun simctl install "$SIM_UDID" "$APP_PATH" +echo "App installed." + +# --- Start log capture --- +echo "=== Starting log capture ===" +LOG_FILE="$WORK_DIR/os_log.txt" + +# Use subsystem predicate — matches os_log_create("me.jappie.haskellmobile", ...) +# in platform_log.c. More reliable than process name on newer iOS runtimes. +xcrun simctl spawn "$SIM_UDID" log stream \ + --level info \ + --predicate "subsystem == \"me.jappie.haskellmobile\"" \ + --style compact \ + > "$LOG_FILE" 2>&1 & +LOG_PID=$! + +# Give log stream generous time to fully attach before launching app +sleep 5 + +# --- Launch app with --autotest --- +echo "=== Launching $BUNDLE_ID with --autotest ===" +xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID" --autotest + +# --- Wait for initial render --- +echo "=== Waiting for initial render (timeout: 60s) ===" +POLL_TIMEOUT=60 +POLL_ELAPSED=0 +RENDER_DONE=0 + +while [ $POLL_ELAPSED -lt $POLL_TIMEOUT ]; do + if grep -q "setRoot" "$LOG_FILE" 2>/dev/null; then + RENDER_DONE=1 + echo "Initial render detected after ~''${POLL_ELAPSED}s" + break + fi + sleep 2 + POLL_ELAPSED=$((POLL_ELAPSED + 2)) +done + +# --- Retry: log stream can miss early startup messages --- +if [ $RENDER_DONE -eq 0 ]; then + echo "WARNING: setRoot not found — retrying with app relaunch" + xcrun simctl terminate "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true + sleep 3 + > "$LOG_FILE" + xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID" --autotest + + POLL_TIMEOUT=60 + POLL_ELAPSED=0 + while [ $POLL_ELAPSED -lt $POLL_TIMEOUT ]; do + if grep -q "setRoot" "$LOG_FILE" 2>/dev/null; then + RENDER_DONE=1 + echo "Initial render detected after relaunch (~''${POLL_ELAPSED}s)" + break + fi + sleep 2 + POLL_ELAPSED=$((POLL_ELAPSED + 2)) + done + + if [ $RENDER_DONE -eq 0 ]; then + echo "WARNING: setRoot not found after retry" + fi +fi + +# --- Verify initial render --- +echo "" +echo "=== Verifying initial render (os_log) ===" +EXIT_CODE=0 + +# Note: we do NOT check for "Counter: 0" here — os_log can miss messages +# from early app startup. "Counter: 1" (checked below) implicitly proves +# the counter started at 0, was incremented once, and re-rendered. +if grep -q 'setStrProp.*Counter:' "$LOG_FILE" 2>/dev/null; then + echo "PASS: Initial render — counter label rendered" +else + echo "FAIL: Initial render — counter label not found in os_log" + EXIT_CODE=1 +fi + +if grep -q 'setRoot' "$LOG_FILE" 2>/dev/null; then + echo "PASS: Initial render — setRoot in os_log" +else + echo "FAIL: Initial render — setRoot in os_log" + EXIT_CODE=1 +fi + +if grep -q 'setHandler.*click' "$LOG_FILE" 2>/dev/null; then + echo "PASS: Initial render — button handlers in os_log" +else + echo "FAIL: Initial render — button handlers in os_log" + EXIT_CODE=1 +fi + +# --- Wait for auto-tap re-render (3s delay in app + margin) --- +# The --autotest flag calls haskellOnUIEvent directly (bypassing ObjC handler), +# so we detect the tap via the re-rendered "Counter: 1" in os_log. +echo "" +echo "=== Waiting for auto-tap re-render (timeout: 30s) ===" +POLL_ELAPSED=0 +POLL_TIMEOUT=30 +TAP_DONE=0 + +while [ $POLL_ELAPSED -lt $POLL_TIMEOUT ]; do + if grep -q 'setStrProp.*Counter: 1' "$LOG_FILE" 2>/dev/null; then + TAP_DONE=1 + echo "Re-render detected after ~''${POLL_ELAPSED}s" + break + fi + sleep 2 + POLL_ELAPSED=$((POLL_ELAPSED + 2)) +done + +if [ $TAP_DONE -eq 0 ]; then + echo "WARNING: Counter: 1 not found after ''${POLL_TIMEOUT}s" +fi + +# --- Verify re-render --- +echo "" +echo "=== Verifying re-render (os_log) ===" + +if grep -q 'setStrProp.*Counter: 1' "$LOG_FILE" 2>/dev/null; then + echo "PASS: Re-render — Counter: 1 in os_log" +else + echo "FAIL: Re-render — Counter: 1 in os_log" + EXIT_CODE=1 +fi + +# Stop log capture +kill "$LOG_PID" 2>/dev/null || true + +# --- Report --- +echo "" +echo "=== Filtered log (UIBridge) ===" +grep -i "UIBridge\|setRoot\|setStrProp\|setHandler\|Click dispatched\|Counter:" "$LOG_FILE" 2>/dev/null || echo "(no relevant lines)" +echo "--- End filtered log ---" + +echo "" +if [ $EXIT_CODE -eq 0 ]; then + echo "All UI rendering checks passed!" +else + echo "Some UI rendering checks failed." +fi + +exit $EXIT_CODE +SCRIPT + + chmod +x $out/bin/test-ui-ios + ''; + + installPhase = "true"; +} diff --git a/nix/simulator.nix b/nix/simulator.nix new file mode 100644 index 00000000..bbc9ac65 --- /dev/null +++ b/nix/simulator.nix @@ -0,0 +1,267 @@ +# iOS Simulator test for lifecycle callbacks. +# +# Uses simulator-app.nix for staged sources, then provides a test script that: +# 1. Generates an Xcode project with xcodegen +# 2. Builds the app with xcodebuild for iphonesimulator +# 3. Boots an iOS Simulator, installs the .app, launches it +# 4. Captures os_log output and checks for lifecycle events +# +# Usage: +# nix-build nix/simulator.nix -o result-simulator +# ./result-simulator/bin/test-lifecycle-ios +{ sources ? import ../npins }: +let + pkgs = import sources.nixpkgs {}; + + simulatorApp = import ./simulator-app.nix { inherit sources; }; + + xcodegen = pkgs.xcodegen; + +in pkgs.stdenv.mkDerivation { + name = "haskell-mobile-simulator-test"; + + dontUnpack = true; + + buildPhase = '' + mkdir -p $out/bin + + cat > $out/bin/test-lifecycle-ios << 'SCRIPT' +#!/usr/bin/env bash +set -euo pipefail + +# --- Configuration --- +BUNDLE_ID="me.jappie.haskellmobile" +SCHEME="HaskellMobile" +DEVICE_TYPE="iPhone 16" +SHARE_DIR="${simulatorApp}/share/ios" + +# --- Temp working directory --- +WORK_DIR=$(mktemp -d /tmp/haskell-mobile-sim-XXXX) +SIM_UDID="" + +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 Lifecycle Test ===" +echo "Working directory: $WORK_DIR" + +# --- Stage library and sources --- +echo "=== Staging Xcode project ===" +mkdir -p "$WORK_DIR/ios/lib" "$WORK_DIR/ios/include" +cp "$SHARE_DIR/lib/libHaskellMobile.a" "$WORK_DIR/ios/lib/" +cp "$SHARE_DIR/include/HaskellMobile.h" "$WORK_DIR/ios/include/" +cp "$SHARE_DIR/include/UIBridge.h" "$WORK_DIR/ios/include/" +cp -r "$SHARE_DIR/HaskellMobile" "$WORK_DIR/ios/" +cp "$SHARE_DIR/project.yml" "$WORK_DIR/ios/" +# Nix store files are read-only; make writable so cleanup and xcodebuild work +chmod -R u+w "$WORK_DIR/ios" + +# --- Generate Xcode project --- +echo "=== Generating Xcode project ===" +cd "$WORK_DIR/ios" +${xcodegen}/bin/xcodegen generate + +# --- Build for simulator --- +echo "=== Building for iOS Simulator ===" +xcodebuild build \ + -project HaskellMobile.xcodeproj \ + -scheme "$SCHEME" \ + -sdk iphonesimulator \ + -configuration Release \ + -derivedDataPath "$WORK_DIR/build" \ + CODE_SIGN_IDENTITY=- \ + CODE_SIGNING_ALLOWED=NO \ + ARCHS=arm64 \ + ONLY_ACTIVE_ARCH=NO \ + | tail -20 + +echo "Build succeeded." + +# --- Find .app bundle --- +APP_PATH=$(find "$WORK_DIR/build" -name "*.app" -type d | head -1) +if [ -z "$APP_PATH" ]; then + echo "ERROR: Could not find .app bundle in build output" + exit 1 +fi +echo "App bundle: $APP_PATH" + +# --- 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-lifecycle-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" + +# Wait for simulator to finish booting +BOOT_TIMEOUT=120 +BOOT_ELAPSED=0 +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 + +# Brief settle time +sleep 5 + +# --- Install app --- +echo "=== Installing app ===" +xcrun simctl install "$SIM_UDID" "$APP_PATH" +echo "App installed." + +# --- Start log capture --- +echo "=== Starting log capture ===" +LOG_FILE="$WORK_DIR/os_log.txt" + +# Use subsystem predicate — matches os_log_create("me.jappie.haskellmobile", ...) +# in platform_log.c. More reliable than process name on newer iOS runtimes. +xcrun simctl spawn "$SIM_UDID" log stream \ + --level info \ + --predicate "subsystem == \"me.jappie.haskellmobile\"" \ + --style compact \ + > "$LOG_FILE" 2>&1 & +LOG_PID=$! + +# Give log stream generous time to fully attach before launching app +sleep 5 + +check_events() { + local FOUND_COUNT=0 + for event in "''${EVENTS[@]}"; do + if grep -q "$event" "$LOG_FILE" 2>/dev/null; then + FOUND_COUNT=$((FOUND_COUNT + 1)) + fi + done + [ $FOUND_COUNT -eq ''${#EVENTS[@]} ] +} + +# --- Launch app --- +echo "=== Launching $BUNDLE_ID ===" +EVENTS=("Lifecycle: Create" "Lifecycle: Resume") +xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID" + +# --- Poll for lifecycle events --- +echo "=== Checking for lifecycle events (timeout: 60s) ===" +POLL_TIMEOUT=60 +POLL_ELAPSED=0 +ALL_FOUND=0 + +while [ $POLL_ELAPSED -lt $POLL_TIMEOUT ]; do + if check_events; then + ALL_FOUND=1 + break + fi + sleep 2 + POLL_ELAPSED=$((POLL_ELAPSED + 2)) +done + +# --- Retry: log stream can miss early startup messages --- +# On retry, the stream has been attached for over a minute, so it will +# reliably capture the lifecycle events from a fresh app launch. +if [ $ALL_FOUND -eq 0 ]; then + echo "" + echo "=== Retrying: terminating and relaunching app ===" + xcrun simctl terminate "$SIM_UDID" "$BUNDLE_ID" 2>/dev/null || true + sleep 3 + > "$LOG_FILE" + xcrun simctl launch "$SIM_UDID" "$BUNDLE_ID" + + POLL_TIMEOUT=30 + POLL_ELAPSED=0 + while [ $POLL_ELAPSED -lt $POLL_TIMEOUT ]; do + if check_events; then + ALL_FOUND=1 + break + fi + sleep 2 + POLL_ELAPSED=$((POLL_ELAPSED + 2)) + done +fi + +# Stop log capture +kill "$LOG_PID" 2>/dev/null || true + +# --- Report results --- +echo "" +echo "=== Results ===" +echo "--- Captured log ---" +cat "$LOG_FILE" 2>/dev/null || echo "(no log output)" +echo "--- End log ---" +echo "" + +EXIT_CODE=0 +for event in "''${EVENTS[@]}"; do + if grep -q "$event" "$LOG_FILE" 2>/dev/null; then + echo "PASS: $event" + else + echo "FAIL: $event (not found in os_log)" + EXIT_CODE=1 + fi +done + +echo "" +if [ $EXIT_CODE -eq 0 ]; then + echo "All lifecycle events verified successfully!" +else + echo "Some lifecycle events were not detected." +fi + +exit $EXIT_CODE +SCRIPT + + chmod +x $out/bin/test-lifecycle-ios + ''; + + installPhase = "true"; +} 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..29bc679a 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" + "hash": "sha256-5CwQ80ucRHiqVbMEEbTFnjz70/axSJ0aliyzSaFSkmY=" } }, - "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..0d04de82 --- /dev/null +++ b/src/HaskellMobile.hs @@ -0,0 +1,96 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +module HaskellMobile + ( main + , haskellInit + , haskellGreet + , haskellCreateContext + , appContext + , appView + , LifecycleEvent(..) + , MobileContext(..) + , defaultMobileContext + , loggingMobileContext + , platformLog + , newMobileContext + , freeMobileContext + ) +where + +import Foreign.C.String (CString, newCString, peekCString) +import Foreign.C.Types (CInt(..)) +import Foreign.Ptr (Ptr) +import Foreign.StablePtr (castStablePtrToPtr) +import HaskellMobile.App (appContext, appView) +import HaskellMobile.Lifecycle + ( LifecycleEvent(..) + , MobileContext(..) + , defaultMobileContext + , loggingMobileContext + , platformLog + , newMobileContext + , freeMobileContext + ) +import Data.Text (pack) +import HaskellMobile.Render (RenderState, newRenderState, renderWidget, dispatchEvent, dispatchTextEvent) +import System.IO.Unsafe (unsafePerformIO) + +-- | Global render state, shared across all render/event cycles. +-- Safe because all UI calls happen on the main thread. +globalRenderState :: RenderState +globalRenderState = unsafePerformIO newRenderState +{-# NOINLINE globalRenderState #-} + +main :: IO () +main = putStrLn "hello, world flaky" + +-- | Placeholder for RTS initialization, called from JNI_OnLoad +haskellInit :: IO () +haskellInit = putStrLn "Haskell RTS initialized" + +foreign export ccall haskellInit :: IO () + +-- | 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 + +-- | Create a default 'MobileContext' and return it as an opaque pointer +-- for C code. Called by platform bridges after 'haskellInit'. +haskellCreateContext :: IO (Ptr ()) +haskellCreateContext = castStablePtrToPtr <$> newMobileContext appContext + +foreign export ccall haskellCreateContext :: IO (Ptr ()) + +-- | Render the UI tree. Calls 'appView' to get the widget description, +-- then issues ui_* calls through the registered bridge callbacks. +-- The @ctx@ pointer is accepted for API consistency but not used for rendering. +haskellRenderUI :: Ptr () -> IO () +haskellRenderUI _ctxPtr = do + widget <- appView + renderWidget globalRenderState widget + +foreign export ccall haskellRenderUI :: Ptr () -> IO () + +-- | Handle a UI event from native code. Dispatches the callback +-- identified by @callbackId@, then re-renders the UI. +haskellOnUIEvent :: Ptr () -> CInt -> IO () +haskellOnUIEvent _ctxPtr callbackId = do + dispatchEvent globalRenderState (fromIntegral callbackId) + widget <- appView + renderWidget globalRenderState widget + +foreign export ccall haskellOnUIEvent :: Ptr () -> 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 () -> CInt -> CString -> IO () +haskellOnUITextChange _ctxPtr callbackId cstr = do + str <- peekCString cstr + dispatchTextEvent globalRenderState (fromIntegral callbackId) (pack str) + +foreign export ccall haskellOnUITextChange :: Ptr () -> CInt -> CString -> IO () diff --git a/src/HaskellMobile/App.hs b/src/HaskellMobile/App.hs new file mode 100644 index 00000000..478e39c9 --- /dev/null +++ b/src/HaskellMobile/App.hs @@ -0,0 +1,31 @@ +{-# LANGUAGE OverloadedStrings #-} +-- | Default implementation of the @HaskellMobile.App@ Backpack signature. +-- Provides 'loggingMobileContext' as the application context and a simple +-- counter demo as the default UI. +module HaskellMobile.App (appContext, appView) where + +import Data.IORef (IORef, newIORef, readIORef, modifyIORef') +import Data.Text (pack) +import HaskellMobile.Lifecycle (MobileContext, loggingMobileContext) +import HaskellMobile.Widget (Widget(..)) +import System.IO.Unsafe (unsafePerformIO) + +-- | The default application context — logs every lifecycle event. +appContext :: MobileContext +appContext = loggingMobileContext + +-- | Global counter state for the demo app. +counter :: IORef Int +counter = unsafePerformIO (newIORef 0) +{-# NOINLINE counter #-} + +-- | Counter demo: displays current count with +/- buttons. +appView :: IO Widget +appView = do + n <- readIORef counter + pure $ Column + [ Text ("Counter: " <> pack (show n)) + , Row [ Button "+" (modifyIORef' counter (+ 1)) + , Button "-" (modifyIORef' counter (subtract 1)) + ] + ] diff --git a/src/HaskellMobile/Lifecycle.hs b/src/HaskellMobile/Lifecycle.hs new file mode 100644 index 00000000..b84b3b22 --- /dev/null +++ b/src/HaskellMobile/Lifecycle.hs @@ -0,0 +1,102 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +{-# LANGUAGE OverloadedStrings #-} +module HaskellMobile.Lifecycle + ( LifecycleEvent(..) + , lifecycleFromInt + , lifecycleToInt + , MobileContext(..) + , defaultMobileContext + , loggingMobileContext + , platformLog + , newMobileContext + , freeMobileContext + , haskellOnLifecycle + ) +where + +import Data.Text (Text, pack, unpack) +import Foreign.C.String (CString, withCString) +import Foreign.C.Types (CInt(..)) +import Foreign.Ptr (Ptr) +import Foreign.StablePtr (StablePtr, castPtrToStablePtr, newStablePtr, deRefStablePtr, 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 () + } + +-- | A no-op context. Suitable as a default when no callbacks are needed. +defaultMobileContext :: MobileContext +defaultMobileContext = MobileContext + { onLifecycle = \_ -> pure () + } + +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)) + } + +-- | 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 + +-- | FFI entry point called from platform code. +-- Takes an opaque context pointer and an event code. +-- Dispatches to the 'onLifecycle' callback. Unknown event codes are silently ignored. +haskellOnLifecycle :: Ptr () -> CInt -> IO () +haskellOnLifecycle ctxPtr code = + case lifecycleFromInt code of + Just event -> do + ctx <- deRefStablePtr (castPtrToStablePtr ctxPtr) + onLifecycle ctx event + Nothing -> pure () + +foreign export ccall haskellOnLifecycle :: Ptr () -> CInt -> IO () diff --git a/src/HaskellMobile/Render.hs b/src/HaskellMobile/Render.hs new file mode 100644 index 00000000..2cb1c992 --- /dev/null +++ b/src/HaskellMobile/Render.hs @@ -0,0 +1,136 @@ +{-# 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) +import HaskellMobile.Widget (Widget(..)) +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 + +-- | Render a single 'Widget' node, returning its native node ID. +renderNode :: RenderState -> Widget -> IO Int32 +renderNode _rs (Text label) = do + nodeId <- Bridge.createNode Bridge.NodeText + Bridge.setStrProp nodeId Bridge.PropText label + pure nodeId +renderNode rs (Button label action) = do + nodeId <- Bridge.createNode Bridge.NodeButton + Bridge.setStrProp nodeId Bridge.PropText label + callbackId <- registerCallback rs action + Bridge.setHandler nodeId Bridge.EventClick callbackId + pure nodeId +renderNode rs (TextInput hint value onChange) = do + nodeId <- Bridge.createNode Bridge.NodeTextInput + Bridge.setStrProp nodeId Bridge.PropText value + Bridge.setStrProp nodeId Bridge.PropHint hint + callbackId <- registerTextCallback rs onChange + Bridge.setHandler nodeId Bridge.EventTextChange callbackId + 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 + +-- | 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 + +-- | 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/UIBridge.hs b/src/HaskellMobile/UIBridge.hs new file mode 100644 index 00000000..b1098803 --- /dev/null +++ b/src/HaskellMobile/UIBridge.hs @@ -0,0 +1,129 @@ +{-# 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 + , setHandler + , addChild + , removeChild + , destroyNode + , setRoot + , clear + ) +where + +import Foreign.C.String (CString, withCString) +import Foreign.C.Types (CInt(..), CDouble(..)) +import Data.Int (Int32) +import Data.Text (Text, unpack) + +-- | Widget node types corresponding to @UI_NODE_*@ in @UIBridge.h@. +data NodeType + = NodeText + | NodeButton + | NodeColumn + | NodeRow + | NodeTextInput + 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 + +-- | Property identifiers for 'setStrProp' and 'setNumProp'. +data PropId + = PropText + | PropColor + | PropHint + | PropFontSize + | PropPadding + 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 PropFontSize = 0 +propIdToInt PropPadding = 1 + +-- | 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_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) + +-- | 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..65505dfa --- /dev/null +++ b/src/HaskellMobile/Widget.hs @@ -0,0 +1,25 @@ +-- | 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 + ( Widget(..) + ) +where + +import Data.Text (Text) + +-- | A declarative description of a UI element. +data Widget + = Text Text + -- ^ A read-only text label. + | Button Text (IO ()) + -- ^ A tappable button with a label and click handler. + | TextInput Text Text (Text -> IO ()) + -- ^ A text input field: placeholder, current value, onChange handler. + -- Follows a controlled-component pattern: Haskell owns the state. + | Column [Widget] + -- ^ A vertical container laying out children top-to-bottom. + | Row [Widget] + -- ^ A horizontal container laying out children left-to-right. 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/Test.hs b/test/Test.hs index 3565d893..dbab4aab 100644 --- a/test/Test.hs +++ b/test/Test.hs @@ -4,14 +4,32 @@ import Test.Tasty import Test.Tasty.QuickCheck as QC import Test.Tasty.HUnit -import Data.List(sort) -import qualified Template +import Data.List (sort) +import Data.IORef (newIORef, readIORef, modifyIORef') +import Foreign.C.String (newCString, peekCString) +import Foreign.Marshal.Alloc (free) +import Foreign.Ptr (Ptr) +import Foreign.StablePtr (castStablePtrToPtr) +import qualified HaskellMobile +import HaskellMobile (appContext, appView) +import HaskellMobile.Lifecycle + ( LifecycleEvent(..) + , MobileContext(..) + , lifecycleFromInt + , lifecycleToInt + , loggingMobileContext + , newMobileContext + , freeMobileContext + , haskellOnLifecycle + ) +import HaskellMobile.Widget (Widget(..)) +import HaskellMobile.Render (newRenderState, renderWidget, dispatchEvent, dispatchTextEvent) main :: IO () main = defaultMain tests tests :: TestTree -tests = testGroup "Tests" [qcProps, unitTests] +tests = testGroup "Tests" [qcProps, unitTests, lifecycleTests, uiTests, textInputTests] qcProps :: TestTree qcProps = testGroup "(checked by QuickCheck)" @@ -36,5 +54,207 @@ unitTests = testGroup "Unit tests" , testCase "List comparison (same length)" $ oneTwoThree `compare` [1,2,3] @?= EQ , testCase "run main" $ do - Template.main + HaskellMobile.main + , testCase "haskellGreet returns correct greeting" $ do + cname <- newCString "World" + cresult <- HaskellMobile.haskellGreet cname + result <- peekCString cresult + free cresult + free cname + result @?= "Hello from Haskell, World!" + , testCase "haskellGreet with different input" $ do + cname <- newCString "Android" + cresult <- HaskellMobile.haskellGreet cname + result <- peekCString cresult + free cresult + free cname + result @?= "Hello from Haskell, Android!" + ] + +-- | Helper: create a context with the given callback, run an action with +-- the opaque 'Ptr ()', then free the context. +withContext :: (LifecycleEvent -> IO ()) -> (Ptr () -> IO a) -> IO a +withContext callback action = do + sptr <- newMobileContext MobileContext { onLifecycle = callback } + let ptr = castStablePtrToPtr sptr + result <- action ptr + freeMobileContext sptr + pure result + +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 "appContext handles all events without throwing" $ + mapM_ (onLifecycle appContext) allEvents + ] + +uiTests :: TestTree +uiTests = testGroup "UI" + [ testCase "callback dispatch fires registered action" $ do + ref <- newIORef (0 :: Int) + rs <- newRenderState + let widget = Button "click me" (modifyIORef' ref (+ 1)) + 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 "A" (modifyIORef' refA (const True)) + , Button "B" (modifyIORef' refB (const True)) + ] + 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 "old" (modifyIORef' refOld (const True))) + -- Second render replaces it + renderWidget rs (Button "new" (modifyIORef' refNew (const True))) + 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 "no buttons") + -- 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 "header" + , Row + [ Button "a" (pure ()) + , Column + [ Text "nested" + , Button "b" (pure ()) + ] + ] + , Text "footer" + ] + -- Should not throw — exercises all node types + renderWidget rs widget + + , testCase "appView returns a widget" $ do + widget <- appView + -- appView 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" + Row _ -> assertFailure "expected Column, got Row" + ] + +textInputTests :: TestTree +textInputTests = testGroup "TextInput" + [ testCase "text callback fires with correct value" $ do + ref <- newIORef ("" :: String) + rs <- newRenderState + let widget = TextInput "hint" "" (\t -> modifyIORef' ref (const (show t))) + 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 "enter weight" "80" (\t -> modifyIORef' ref (const (show t))) + 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 "no inputs") + -- 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 "ok" (modifyIORef' clickRef (const True)) + , TextInput "hint" "" (\t -> modifyIORef' textRef (const (show t))) + ] + 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 "old" "" (\t -> modifyIORef' refOld (const (show t)))) + renderWidget rs (TextInput "new" "" (\t -> modifyIORef' refNew (const (show t)))) + dispatchTextEvent rs 0 "val" + old <- readIORef refOld + new <- readIORef refNew + old @?= "" + new @?= show ("val" :: String) ]