build-d-android-lib.nixnix · 274 linesall
# `legacyPackages.buildDAndroidLib`: a D application's whole closure as one
# shared library per ABI — the `lib<name>.so` a NativeActivity APK loads.
#
# Raw ldc2, not dub: dub cannot drive a cross build. `-i` compiles every module
# the main file reaches (the in-tree closure and the registry deps unzipped
# from their flake inputs), so the module graph, not a source list, is the
# build surface — which is also why an Android build only ever type-checks the
# `version (Android)` code it actually reaches (see docs/specs/hue/android.md).
#
# Shared by hue (hue.nix) and the terminal (terminal.nix); anything either of
# them needs that the other does not is a parameter here, never a fork.
{ inputs, lib, ... }:
let
  # Whether this system can build Android at all (./host.nix).
  androidHost = import ./host.nix { inherit inputs; };
in
{
  perSystem =
    {
      config,
      pkgs,
      system,
      inputs',
      ...
    }:
    let
      ndk = config.legacyPackages.androidNdk;
      sources = config.legacyPackages.sparklesSources;
    in
    lib.optionalAttrs (androidHost system).supported {
      legacyPackages.buildDAndroidLib =
        {
          pname,
          # The `.so` stem: `lib<libName>.so`, which is also what the
          # manifest's `android.app.lib_name` names.
          libName,
          # The D entry module, relative to the repo root.
          mainFile,
          # Source directories (repo-relative): the closure `-I` paths plus
          # anything else the build reads (C shims, string imports).
          srcDirs,
          # The dub `versions` of the configuration being mirrored, including
          # the `Have_*` set of its dependency graph.
          versions,
          # dub-registry dependencies: `{ name; src; }` with `src` the
          # registry zip (a flake input).
          dubDeps ? [ ],
          stringImportDirs ? [ ],
          # C files compiled through ImportC. List implementation files
          # explicitly: -i reaches declarations but not unimported bodies.
          cFiles ? [ "libs/android/c/jni_c.c" ],
          # Extra ImportC include dirs (store paths).
          cIncludes ? [ ],
          # Static archives to link, per ABI: `abi: [ path ... ]`.
          staticLibs ? (abi: [ ]),
          # Append a stable `{}` `.build_info` section so a later
          # `--update-section` has something to replace. The contents do not
          # name a commit, so this derivation stays cached across commits.
          emptyBuildInfo ? false,
          # Link for raylib's `native_app_glue`: keep its `ANativeActivity_onCreate`
          # entry and route `fopen` through its asset-aware wrapper. An app whose
          # activity `sparkles:wsi` owns (milestone MA) links neither.
          raylibGlue ? true,
          description ? "D application as an Android shared library, per ABI",
        }:
        pkgs.stdenv.mkDerivation {
          inherit pname;
          version = "0.1.0";
          src = sources.sourceFor srcDirs;

          nativeBuildInputs = [
            (androidHost system).ldcAndroid
            pkgs.unzip
          ]
          ++ lib.optional emptyBuildInfo pkgs.llvm-binutils-sparkles;

          buildPhase = ''
            runHook preBuild

            ${lib.concatMapStrings (d: ''
              mkdir -p dub-imports/${d.name}
              (cd dub-imports/${d.name} && unzip -q ${d.src})
            '') dubDeps}

            ${lib.concatMapStrings (t: ''
              ldc2 -mtriple=${t.triple} -relocation-model=pic -O2 -g \
                ${ndk.dPrefixMapFlags} \
                -preview=in -preview=dip1000 \
                ${toString (map (v: "-d-version=${v}") versions)} \
                ${toString (map (dir: "-J=${dir}") stringImportDirs)} \
                ${toString (map (dir: "-I=${dir}") srcDirs)} \
                ${toString (map (d: ''-I="$(echo dub-imports/${d.name}/*/source)"'') dubDeps)} \
                -P-U__SIZEOF_INT128__ \
                ${toString (map (inc: "-P-I${inc}") cIncludes)} \
                -i \
                ${mainFile} \
                ${toString cFiles} \
                ${toString (staticLibs t.abi)} \
                -shared -link-defaultlib-shared=false \
                ${lib.optionalString raylibGlue "-L-Wl,-u,ANativeActivity_onCreate -L-Wl,--wrap=fopen"} \
                -L-llog -L-landroid -L-lEGL -L-lGLESv2 -L-lOpenSLES -L-lm -L-ldl \
                -L${ndk.pageAlignFlags} \
                -of=lib${libName}-${t.abi}.so
            '') (lib.attrValues ndk.targets)}

            runHook postBuild
          '';

          installPhase = ''
            runHook preInstall
            ${lib.concatMapStrings (t: ''
              install -Dm644 lib${libName}-${t.abi}.so $out/lib/${t.abi}/lib${libName}.so
            '') (lib.attrValues ndk.targets)}
            ${lib.optionalString emptyBuildInfo ''
              emptyInfo=${config.legacyPackages.emptyBuildInfoJson}
              ${lib.concatMapStrings (t: ''
                llvm-objcopy --add-section .build_info=$emptyInfo \
                  "$out/lib/${t.abi}/lib${libName}.so"
              '') (lib.attrValues ndk.targets)}
            ''}
            runHook postInstall
          '';

          # Unstripped for ndk-stack; the APK carries the same bytes so a device
          # tombstone symbolizes against this output directly.
          dontStrip = true;
          disallowedReferences = ndk.toolchainPaths;

          meta = {
            inherit description;
            platforms = (androidHost system).platforms;
          };
        };

      # The native half of a raylib app's Android library (hue, the
      # terminal): the C bodies ImportC compiles, the headers they include,
      # the static archives linked per ABI, and the dub-registry packages
      # `-i` compiles (the same pins as nix/dub-lock.json). Spread into a
      # `buildDAndroidLib` call.
      #
      # The io_uring binding (sparkles.event_horizon.sys.uring) never compiles
      # here: the uring backend is version-gated off the Android triple (the app
      # seccomp policy denies io_uring_setup), and the triple selects the
      # kqueue backend over the statically linked libkqueue-android instead
      # (backend/select.d, libkqueue.nix).
      legacyPackages.androidAppNative = {
        cFiles = [
          "libs/android/c/jni_c.c"
          "libs/ghostty/src/sparkles/ghostty/ghostty_modes.c"
          "libs/raylib-text/src/sparkles/raylib_text/shaping_c.c"
        ];
        cIncludes = [
          "${config.packages.tree-sitter-android}/include"
          "${config.packages.libghostty-vt-android}/include"
          "${config.packages.freetype-android}/include/freetype2"
          "${config.packages.harfbuzz-android}/include/harfbuzz"
        ];
        staticLibs = abi: [
          "${config.packages.raylib-android}/lib/${abi}/libraylib.a"
          "${config.packages.harfbuzz-android}/lib/${abi}/libharfbuzz.a"
          "${config.packages.freetype-android}/lib/${abi}/libfreetype.a"
          "${config.packages.freetype-android}/lib/${abi}/libpng16.a"
          "${config.packages.freetype-android}/lib/${abi}/libz.a"
          "${config.packages.tree-sitter-android}/lib/${abi}/libtree-sitter.a"
          "${config.packages.libghostty-vt-android}/lib/${abi}/libghostty-vt.a"
          "${config.packages.libkqueue-android}/lib/${abi}/libkqueue.a"
        ];
        # Spelled out: `ci check credits` reads this list.
        dubDeps = [
          {
            name = "raylib-d";
            src = inputs.dub-raylib-d;
          }
          {
            name = "optional";
            src = inputs.dub-optional;
          }
          {
            name = "bolts";
            src = inputs.dub-bolts;
          }
        ];
      };

      # The native libraries an app's `.so` links, as build-info components.
      # hue and the terminal link the same set (their `staticLibs`). libpng
      # and zlib are archives inside the freetype output: one store path, two
      # component names. `abi` is unused while every Android package is one
      # multi-ABI output; a later per-ABI output is the only change here.
      legacyPackages.androidNativeComponents =
        abi:
        let
          at = pkg: {
            version = pkg.version or "unknown";
            storePath = pkg.outPath;
          };
          ft = config.packages.freetype-android;
        in
        assert abi != "";
        {
          raylib = at config.packages.raylib-android;
          harfbuzz = at config.packages.harfbuzz-android;
          freetype = at ft;
          libpng = {
            version = pkgs.libpng.version;
            storePath = ft.outPath;
          };
          zlib = {
            version = pkgs.zlib.version;
            storePath = ft.outPath;
          };
          tree-sitter = at config.packages.tree-sitter-android;
          libghostty-vt = {
            version = inputs'.ghostty.packages.libghostty-vt.version or "unknown";
            storePath = config.packages.libghostty-vt-android.outPath;
          };
          libkqueue = at config.packages.libkqueue-android;
        };

      # Step 2 for an Android library built with `emptyBuildInfo = true`: a
      # copy whose `.build_info` section holds the document (`TPG2`), per ABI.
      # The unstamped library stays cached across commits; only this copy
      # changes with the commit. The components are the desktop document's
      # in-tree set plus `nativeComponents abi`, and `check` runs (with
      # `assertBuildInfo`) at evaluation time, as `buildSparklesApp` does.
      legacyPackages.stampAndroidLib =
        {
          unstamped,
          libName,
          # The app directory, `apps/<name>`; the document is `sparkles:<name>`.
          app,
          version ? "0.1.0",
          buildType ? "checked",
          links ? { },
          nativeComponents ? config.legacyPackages.androidNativeComponents,
          check ? (doc: doc),
        }:
        let
          targets = lib.attrValues ndk.targets;
          inTree = config.legacyPackages.inTreeComponents (sources.componentNames "apps/${app}");
          infoFor =
            t:
            config.legacyPackages.sparklesBuildInfo {
              name = "sparkles:${app}";
              inherit version buildType links;
              components = inTree // nativeComponents t.abi;
            };
          checked = t: check (config.legacyPackages.assertBuildInfo (infoFor t).document);
          jsonFor = t: pkgs.writeText "build-info-${t.abi}.json" (builtins.seq (checked t) (infoFor t).json);
        in
        pkgs.runCommand "lib${libName}-android-build-info"
          {
            dontStrip = true;
            nativeBuildInputs = [ pkgs.llvm-binutils-sparkles ];
            passthru = {
              inherit unstamped;
              buildInfo = lib.listToAttrs (
                map (t: {
                  name = t.abi;
                  value = checked t;
                }) targets
              );
            };
          }
          ''
            cp -a ${unstamped} "$out"
            chmod -R u+w "$out"
            ${lib.concatMapStrings (t: ''
              llvm-objcopy --update-section .build_info=${jsonFor t} \
                "$out/lib/${t.abi}/lib${libName}.so"
            '') targets}
          '';
    };
}