import com.android.build.api.variant.ResValueimport groovy.json.JsonSlurperimport org.jetbrains.kotlin.gradle.dsl.JvmTargetimport java.awt.Colorimport java.awt.Graphics2Dimport java.awt.RenderingHintsimport java.awt.geom.RoundRectangle2Dimport java.awt.image.BufferedImageimport javax.imageio.ImageIOimport java.net.URIimport java.security.MessageDigestplugins { id("com.android.application") kotlin("android") kotlin("plugin.serialization") kotlin("plugin.compose")}// ── THE APPS ARE THE REGISTRY'S ─────────────────────────────────────────────// One product flavour per app in apps/registry.json whose `android.project`// is this one (dimension `app`: books, cinemas, …), crossed with the server// it talks to (dimension `server`: live, the real Worker; dev, the dev one).// Each app's applicationId is the registry's `android.package`, its dev// build's `android.devPackage`; its name, kit and ground are its flavour.json// (apps/cotton/App/Flavours/<ios.live.flavour>/flavour.json, the iOS app's own// file, read at build time and never copied by hand); its launcher icon and splash// are its flavour's launch layers (LaunchPictures; the dev build's band from the iconset named <icon>Dev).val repo = rootProject.file("../..")// THE DEV SERVER IS A SETTING: config/dev-server.json's host, the one place the Worker's dev deploy and the// iPhone build read it too. Every flavour.json says `https://{dev-host}`; its copy in the app has it filled in.val devServerFile = repo.resolve("config/dev-server.json")check(devServerFile.isFile) { "config/dev-server.json is missing: it names the dev Worker every dev build signs in at ({\"host\": \"<your dev Worker's host>\"})" }@Suppress("UNCHECKED_CAST")val devHost = ((JsonSlurper().parse(devServerFile) asMap<String, Any?>)["host"] as? String) ?.takeIf { Regex("^[A-Za-z0-9.-]+$").matches(it) } ?: error("config/dev-server.json: \"host\" is no host name")@Suppress("UNCHECKED_CAST")val registry = (JsonSlurper().parse(repo.resolve("apps/registry.json")) asMap<String, Any?>)["apps"] asList<Map<String, Any?>>@Suppress("UNCHECKED_CAST")val local = JsonSlurper().parse(file("flavours.json")) asMap<String, Any?>// The painted layers each app carries are apps/loom/materials.json's: one list// the iPhone build reads too (scripts/ios-flavour-pictures.py), so the two// phones never carry different pictures for one app. A name ending in `*`// names every imageset of Loom's catalogue that starts so; a name that is no// imageset stops the build here.@Suppress("UNCHECKED_CAST")val materialsList = JsonSlurper().parse(repo.resolve("apps/loom/materials.json")) asMap<String, Any?>val loomImagesets: List<String> = repo.resolve("apps/loom/Sources/CottonPaper/Media.xcassets").list()!! .filter { it.endsWith(".imageset") }.map { it.removeSuffix(".imageset") }.sorted()fun pictures(names: List<String>, owner: String): List<String> = names.flatMap { name ->val hits = if (name.endsWith("*")) loomImagesets.filter { it.startsWith(name.removeSuffix("*")) } else loomImagesets.filter { it == name } check(hits.isNotEmpty()) { "apps/loom/materials.json: $owner names $name, which is no imageset of Loom's Media.xcassets" } hits}.distinct()dataclassAndroidApp(val slug: String,val name: String,val pkg: String,val flavourDir: File,val devIcon: File,val icon: File,val windowGround: String,val materials: List<String>,val dependencies: List<String>,/** An app no iPhone builds (Cotton Voice, `ios` null): its link scheme is app/flavours.json's, live and dev. */val ownScheme: Map<String, String>?,/** Libraries published only as an AAR file on their own releases page (sherpa-onnx), fetched by URL and sha256. */val aars: List<Map<String, String>>,/** Kit files the app reads itself (Cotton Voice: the voice catalogue's kinds and files), copied from the kits at build time. */val kitFiles: List<String>,/** * An Android launch on the app's own flat ground, light and dark (app/flavours.json's `flatLaunch`: Words, Comms), * with the app's mark centred on it where it has one (LaunchObject, light and dark), as its iPhone launch screen. */val flatLaunch: Map<String, String>? = null,)val apps: List<AndroidApp> = registry.filter { app -> @Suppress("UNCHECKED_CAST") (app["android"] as? Map<String, Any?>)?.get("project") == "apps/android"}.filter { app ->// A planned row is declared before its scaffold (apps/registry.schema.json): until its flavour folder lands it// is no flavour here, so one lane's new row never stops every other app's build. @Suppress("UNCHECKED_CAST")val live = (app["ios"] as? Map<String, Any?>)?.get("live") as? Map<String, Any?>val folder = if (live != null) repo.resolve("apps/cotton/App/Flavours/${live["flavour"]}") else file("flavours/${app["slug"]}") app["phase"] != "planned" || folder.resolve("flavour.json").isFile}.map { app -> @Suppress("UNCHECKED_CAST")val android = app["android"] asMap<String, Any?> @Suppress("UNCHECKED_CAST")val ios = app["ios"] asMap<String, Any?>? @Suppress("UNCHECKED_CAST")val live = ios?.get("live") asMap<String, Any?>?val slug = app["slug"] asStringval pkg = android["package"] asString check(android["devPackage"] == "$pkg.dev") { "registry: $slug's android.devPackage must be $pkg.dev (the dev build installs beside the live one)" } check(slug.all { it.isLowerCase() || it.isDigit() }) { "registry: $slug is no Gradle flavour name (lower-case letters and digits)" } @Suppress("UNCHECKED_CAST")val mine = local[slug] as? Map<String, Any?> ?: error("app/flavours.json holds no entry for $slug (its window ground)")val iconSet = repo.resolve(app["icon"] asString)// The icon as a light phone shows it: an iPhone set may also hold its dark and tinted looks (`-dark`, `-tinted`).fun png(set: File) = set.listFiles { f -> f.extension == "png" && !f.nameWithoutExtension.endsWith("-dark") && !f.nameWithoutExtension.endsWith("-tinted") }?.maxByOrNull { it.length() } ?: error("registry: $slug's icon set ${set.path} holds no PNG") @Suppress("UNCHECKED_CAST")AndroidApp( slug = slug, name = app["name"] asString, pkg = pkg,// An app the iPhone builds too reads the iPhone's flavour folder; one only Android builds keeps its own beside// this file (app/flavours/<slug>: flavour.json and the Assets.xcassets its icon and launch ground are drawn from). flavourDir = if (live != null) repo.resolve("apps/cotton/App/Flavours/${live["flavour"]}") else file("flavours/$slug"), devIcon = png(iconSet.resolveSibling(iconSet.name.replace(".appiconset", "Dev.appiconset"))), icon = png(iconSet), windowGround = mine["windowGround"] asString,// An app's own list may name a picture everyApp already carries (People's face-art-*): carried once. materials = (pictures(materialsList["everyApp"] asList<String>, "everyApp") + pictures((materialsList["apps"] asMap<String, Any?>)[slug] as? List<String> ?: error("apps/loom/materials.json holds no list for $slug (the pictures it carries)"), slug)).distinct(), dependencies = mine["dependencies"] as? List<String> ?: emptyList(), ownScheme = (mine["urlScheme"] as? Map<String, String>).also { check((it == null) == (live != null)) { "app/flavours.json: $slug's urlScheme is written where the iPhone has none (apps/cotton/project.yml) and only there" } }, aars = mine["aars"] as? List<Map<String, String>> ?: emptyList(), kitFiles = mine["kitFiles"] as? List<String> ?: emptyList(), flatLaunch = mine["flatLaunch"] as? Map<String, String>, )}check(apps.isNotEmpty()) { "registry: no app names apps/android as its android.project" }// The live apps' Play app-signing certificates, `<package>=<HEX>[|<HEX>…]` joined by `;` (the shell's CottonSigners// reads it): every registry row that lists android.signing.live, whatever its phase, since a parked app may still be// installed. Public digests, never a key.val liveSigners: String = registry.mapNotNull { row -> @Suppress("UNCHECKED_CAST")val android = row["android"] as? Map<String, Any?> ?: return@mapNotNull null @Suppress("UNCHECKED_CAST")val live = ((android["signing"] as? Map<String, Any?>)?.get("live") as? List<String>).orEmpty() live.forEach { check(Regex("^[0-9A-F]{2}(:[0-9A-F]{2}){31}$").matches(it)) { "registry: ${row["slug"]}'s android.signing.live has $it, not a SHA-256 in colon hex" } } live.takeIf { it.isNotEmpty() }?.let { "${android["package"]}=" + it.joinToString("|") { digest -> digest.replace(":", "") } }}.joinToString(";").also { check(it.isNotEmpty()) { "registry: no app lists android.signing.live, so a live build would trust no sibling" } }// Each app's URL scheme is the iPhone's (apps/cotton/project.yml's `urlScheme` under the app's flavour, the dev// build's under its `dev:`), read at build time and never written twice: a link written for one phone opens the// same app on the other. An app the iPhone gives no scheme stops the build here.val iosProject: List<String> = repo.resolve("apps/cotton/project.yml").readLines()fun urlScheme(slug: String, dev: Boolean): String { apps.single { it.slug == slug }.ownScheme?.let { own -> return own.getValue(if (dev) "dev"else"live") }val start = iosProject.indexOf(" $slug:").takeIf { it >= 0 } ?: error("apps/cotton/project.yml has no flavour $slug (its urlScheme)")val block = iosProject.drop(start + 1).takeWhile { it.isBlank() || it.startsWith(" ") }val indent = if (dev) " "else" "return block.firstNotNullOfOrNull { line -> line.takeIf { it.startsWith("${indent}urlScheme: ") }?.substringAfter(": ")?.trim() } ?: error("apps/cotton/project.yml gives $slug no ${if (dev) "dev " else ""}urlScheme")}// The painted layers and the type the faces wear are the iOS faces' own files// (apps/loom's catalogue), copied into each app's APK at build time: one// painting, never a second copy in git.val loomPaper = repo.resolve("apps/loom/Sources/CottonPaper")// The catalogue's every imageset name, carried by every app (`paper/catalogue.txt`): a picture the shell or a face// asks for that the catalogue holds and the app does not carry is a hole, and a debug build stops at the draw,// naming it (Materials.image, CottonPaper's `expect`); a name the catalogue does not hold is no picture at all.val paperCatalogue = tasks.register("writePaperCatalogue") {val out = layout.buildDirectory.dir("generated/paperCatalogue") inputs.property("names", loomImagesets) outputs.dir(out) doLast { out.get().asFile.resolve("paper").apply { mkdirs() }.resolve("catalogue.txt").writeText(loomImagesets.joinToString("\n", postfix = "\n")) }}/** An app's assets laid into the folder the variant reads (AGP sets [outputDir]). */abstract classAppAssets : Sync() { @get:OutputDirectory abstract val outputDir: DirectoryPropertyinit { into(outputDir) }}/** * COTTON ALBUMS' FACE MODEL (HyperFace-50k, the iPhone's model: coordinator, 27 Nov), into the albums flavour's * assets by its pinned SHA-256, never from git. The pin is the iPhone's own (apps/cotton/App/Flavours/albums/ * face-model.json): its `android` entry names the LiteRT file scripts/albums/convert.py makes from the SAME pinned * archive and that file's own hash. It is read from $COTTON_MODELS_DIR (default ~/.cache/cottondb/models), where * scripts/albums/face-model-android.sh puts it. An absent file or a wrong hash FAILS THE BUILD, with the reason and how * to make it: there is no fallback model. Other apps never run this task. */abstract classAlbumsFaceModel : DefaultTask() {/** The model file (may be absent: then the task fails with how to make it, not Gradle's own message). */ @get:InputFiles @get:PathSensitive(PathSensitivity.NONE) abstract val model: ConfigurableFileCollection @get:Input abstract val sha256: Property<String> @get:Input abstract val asset: Property<String> @get:OutputDirectory abstract val outputDir: DirectoryProperty @TaskActionfun place() {val file = model.singleFileval how = "Make it with scripts/albums/face-model-android.sh (it converts the pinned HyperFace50k-pal8.mlmodelc.tar " +"in the same folder), or set COTTON_MODELS_DIR."if (!file.isFile) throwGradleException("Cotton Albums face model: ${file.path} is absent. $how")val digest = MessageDigest.getInstance("SHA-256") file.inputStream().use { input ->val buffer = ByteArray(1 shl 20)while (true) { val n = input.read(buffer); if (n < 0) break; digest.update(buffer, 0, n) } }val got = digest.digest().joinToString("") { "%02x".format(it) }if (got != sha256.get()) {throwGradleException("Cotton Albums face model: ${file.path} has sha256 $got; face-model.json pins ${sha256.get()}. Delete it. $how") }val out = outputDir.get().asFile out.deleteRecursively() file.copyTo(out.resolve(asset.get())) }}/** * The app's launch screen and launcher icon, drawn at build time from the same painted sources the iPhone's launch * storyboard uses (the flavour's `Assets.xcassets`, written by scripts/gen-launch-screens.py): its ground's colour * (`LaunchGround`), the ground laid (`LaunchSurface`) with its lamp's glow where it has one (`LaunchLamp`), and the * app's object cut out of its painted icon (`LaunchObject`, the painted cut-out with its soft contact shadow). * * No painted icon has layers of its own (each is one flat 1024 painting), so the adaptive icon is drawn from the * launch screen's layers, the honest split of the same painting: the background is the app's ground with its lamp, * the foreground the object, the monochrome (themed icons) the object's silhouette. The Dev copy wears the iPhone * Dev icon's own DEV band, cut out of `AppIcon<App>Dev-1024.png`, across the object's foot inside the safe zone. * The round icon is the same adaptive icon (the launcher masks it). * * The splash (the SplashScreen API, Android 12+ and the compat path below it) is the ground's colour with the object * centred at its iPhone size (200 points across, the object about 160), drawn smaller only where it would leave * the splash's 192 dp circle. */abstract classLaunchPictures : DefaultTask() { @get:InputDirectory abstract val layers: DirectoryProperty/** Absent for an app with no cut-out object (it launches on its bare ground, so no picture's size is read). */ @get:Optional @get:InputFile abstract val storyboard: RegularFileProperty @get:Optional @get:InputFile abstract val devIcon: RegularFileProperty/** The painted icon the variant wears (the Dev one for a dev build): the adaptive icon of an app with no cut-out object. */ @get:InputFile abstract val icon: RegularFileProperty/** * The look of an app that has one (its kit's `look.json`: Cotton Vault). Its splash is the look's flat `background`, * light and dark, with no object (SHAPES "Decided" 12): the app's name follows as its first frame. Its launcher * icon is drawn from the object as any other app's. */ @get:Optional @get:InputFile abstract val look: RegularFileProperty/** A flat launch's ground, light and dark (AndroidApp.flatLaunch): no object on the splash, the ground alone. */ @get:Optional @get:Input abstract val flatLight: Property<String> @get:Optional @get:Input abstract val flatDark: Property<String> @get:OutputDirectory abstract val outputDir: DirectoryPropertyprivateval densities = mapOf("mdpi" to 1f, "hdpi" to 1.5f, "xhdpi" to 2f, "xxhdpi" to 3f, "xxxhdpi" to 4f) @TaskActionfun draw() {System.setProperty("java.awt.headless", "true")val dir = layers.get().asFileval out = outputDir.get().asFile.apply { deleteRecursively(); mkdirs() }funset(name: String) = dir.resolve("$name.imageset").takeIf { it.isDirectory }fun picture(name: String) = set(name)?.listFiles { f -> f.extension in setOf("png", "jpg", "jpeg") }?.maxByOrNull { it.length() }// The storyboard says each picture's size in points (its <image> resources): the scale the pixels are read at.val points = Regex("""<image name="(\w+)" width="([\d.]+)" height="([\d.]+)"/>""").findAll(storyboard.orNull?.asFile?.readText() ?: "") .associate { it.groupValues[1] to it.groupValues[2].toFloat() }val ground = run { @Suppress("UNCHECKED_CAST")val colour = ((JsonSlurper().parse(dir.resolve("LaunchGround.colorset/Contents.json")) asMap<String, Any?>)["colors"] asList<Map<String, Any?>>) .first()["color"] asMap<String, Any?> @Suppress("UNCHECKED_CAST")val c = colour["components"] asMap<String, String>fun channel(key: String) = Math.round(c.getValue(key).toFloat() * 255).coerceIn(0, 255)Color(channel("red"), channel("green"), channel("blue")) }// A flat app (flavour.json's `flat`, Cotton Story) lays no surface: its ground is the colour alone.val surface = picture("LaunchSurface")?.let(ImageIO::read)val lamp = picture("LaunchLamp")?.let(ImageIO::read)// An app with no cut-out painted yet (Calling, which the iPhone launches on its bare desk) launches on its// bare ground too, and its adaptive icon is its whole painted icon in the launcher's window, with no// monochrome layer (there is no object to draw one from).val objectFile = set("LaunchObject")?.resolve("LaunchObject@3x.png")?.takeIf { it.isFile }// A flat app's mark in a dark phone (LaunchObject's dark appearance, scripts/gen-launch-screens.py): its splash at night.val nightThing = set("LaunchObject")?.resolve("LaunchObject-dark@3x.png")?.takeIf { it.isFile }?.let(ImageIO::read)if (objectFile == null) return bare(out, ground, ImageIO.read(icon.get().asFile))val thing = ImageIO.read(objectFile)val surfacePerPoint = surface?.let { it.width / (points["LaunchSurface"] ?: error("the storyboard gives LaunchSurface no size")) }val lampPerPoint = lamp?.let { it.width / (points["LaunchLamp"] ?: error("the storyboard gives LaunchLamp no size")) }val objectPoints = points["LaunchObject"] ?: error("the storyboard gives LaunchObject no size")// How far the object reaches from its square's centre, as a share of the square's side (its solid part,// the soft shadow's faint edge left out).val reach = run {var far = 0.0val half = thing.width / 2.0for (y in0 until thing.height) for (x in0 until thing.width) {if ((thing.getRGB(x, y) ushr 24) >= 128) far = maxOf(far, Math.hypot(x + 0.5 - half, y + 0.5 - half)) } far / thing.width }fun canvas(px: Int) = BufferedImage(px, px, BufferedImage.TYPE_INT_ARGB)funGraphics2D.fine() = apply { setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC) setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY) setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) }fun write(image: BufferedImage, folder: String, name: String) =ImageIO.write(image, "png", out.resolve(folder).apply { mkdirs() }.resolve("$name.png"))/** The object's square [side] dp across, centred on a [box] dp canvas, at [scale] pixels a dp. */fun objectOn(box: Float, side: Float, scale: Float, picture: BufferedImage = thing): BufferedImage {val px = Math.round(box * scale)val s = Math.round(side * scale)return canvas(px).also { c -> c.createGraphics().fine().apply { drawImage(picture, (px - s) / 2, (px - s) / 2, s, s, null); dispose() } } }// The DEV band, as the iPhone's Dev icon wears it (scripts/import-app-icons.py's BAND: a fully rounded pill// from x 261 to 762 and y 834 to 946 of the 1024), cut out of that painting along the pill.val band = devIcon.orNull?.asFile?.let { file ->val icon = ImageIO.read(file) check(icon.width == 1024) { "${file.path} is no 1024 painting" }val (x0, y0, x1, y1) = listOf(261, 834, 762, 946)val pill = RoundRectangle2D.Float(0f, 0f, (x1 - x0).toFloat(), (y1 - y0).toFloat(), (y1 - y0).toFloat(), (y1 - y0).toFloat())BufferedImage(x1 - x0, y1 - y0, BufferedImage.TYPE_INT_ARGB).also { b -> b.createGraphics().fine().apply { clip(pill); drawImage(icon.getSubimage(x0, y0, x1 - x0, y1 - y0), 0, 0, null); dispose() } } }// ── The adaptive icon: 108 dp layers, of which the launcher shows the middle 72 and keeps the middle 66 whole.val layer = 108fval safe = 33f// The object's farthest solid point on the safe circle; never larger than the visible 72 dp.val iconSide = minOf(72f, safe / reach.toFloat())// The band: the iPhone's share of the icon's width (501 of 1024) of the visible 72 dp, its foot as low as the// safe circle lets its rounded ends stay inside it.val bandWidth = 72f * 501f / 1024fval bandHeight = bandWidth * 112f / 501fval bandFoot = layer / 2 + Math.sqrt((safe * safe - (bandWidth / 2 - bandHeight / 2) * (bandWidth / 2 - bandHeight / 2)).toDouble()).toFloat() - bandHeight / 2 densities.forEach { (density, scale) ->val folder = "mipmap-$density"val px = Math.round(layer * scale)// Background: the ground's colour, the ground laid and its lamp's glow at the visible window's top left,// as the launch screen lays them at the screen's (the window being the middle 72 of 108). write(canvas(px).also { c -> c.createGraphics().fine().apply { color = ground; fillRect(0, 0, px, px)// The visible window shows about one phone width of ground, 393 points: 72 dp of it.val perPoint = (72f * scale) / 393fval inset = (px - 72f * scale) / 2if (surface != null && surfacePerPoint != null) { drawImage(surface, 0, 0, Math.round(surface.width / surfacePerPoint * perPoint), Math.round(surface.height / surfacePerPoint * perPoint), null) }if (lamp != null && lampPerPoint != null) { drawImage(lamp, Math.round(inset), Math.round(inset), Math.round(lamp.width / lampPerPoint * perPoint), Math.round(lamp.height / lampPerPoint * perPoint), null) } dispose() } }, folder, "ic_launcher_background")// Foreground: the object, and the Dev copy's band over its foot.val front = objectOn(layer, iconSide, scale)// Monochrome: the object's silhouette (its solid part, the shadow's soft half left out), shaded by the// painting's own light so its form still reads in one tint: the darkest tenth of the object at 40%, the// lightest tenth whole.val mono = canvas(px)fun luma(argb: Int) = (0.2126f * (argb shr 16 and 0xFF) + 0.7152f * (argb shr 8 and 0xFF) + 0.0722f * (argb and 0xFF)) / 255fval lumas = (0 until px * px).map { front.getRGB(it % px, it / px) }.filter { (it ushr 24) >= 192 }.map(::luma).sorted()val dark = lumas.getOrElse(lumas.size / 10) { 0f }val lightest = lumas.getOrElse(lumas.size * 9 / 10) { 1f }// A drawn mark in a few flat inks (Days' pen ring, Comms' quote, Words' word and cursor) has no light of its// own to shade by: it is whole. A painting has hundreds of shades.val oneInk = lightest - dark < 0.05f || lumas.map { Math.round(it * 50) }.distinct().size <= 4val light = lightest.coerceAtLeast(dark + 0.05f)for (y in0 until px) for (x in0 until px) {val argb = front.getRGB(x, y)val solid = (((argb ushr 24) / 255f - 0.45f) / 0.3f).coerceIn(0f, 1f)val shade = if (oneInk) 1felse0.4f + 0.6f * ((luma(argb) - dark) / (light - dark)).coerceIn(0f, 1f) mono.setRGB(x, y, (Math.round(solid * shade * 255) shl 24) or 0xFFFFFF) }if (band != null) {val w = Math.round(bandWidth * scale)val h = Math.round(bandHeight * scale)val bx = (px - w) / 2valby = Math.round((bandFoot - bandHeight) * scale) front.createGraphics().fine().apply { drawImage(band, bx, by, w, h, null); dispose() }// Monochrome: the pill solid, its white letters cut out of it.val drawn = BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB).also { it.createGraphics().fine().apply { drawImage(band, 0, 0, w, h, null); dispose() } }for (y in0 until h) for (x in0 until w) {val argb = drawn.getRGB(x, y)val pill = (argb ushr 24) / 255fval g = (argb shr 8 and 0xFF) / 255f// The band's red against its white letters: green carries the letters (red's green is 66 of 255).val letter = ((g - 0.35f) / 0.5f).coerceIn(0f, 1f)val a = pill * (1f - letter)if (bx + x in0 until px && by + y in0 until px) mono.setRGB(bx + x, by + y, (Math.round(a * 255) shl 24) or 0xFFFFFF) } } write(front, folder, "ic_launcher_foreground") write(mono, folder, "ic_launcher_monochrome")// The splash's object: a 288 dp canvas whose middle 192 dp circle shows.val splashSide = minOf(objectPoints, 96f / reach.toFloat())// A flat app with a mark of its own (Days' ring, Comms' quote) shows it on its flat ground, as the iPhone's// launch screen does; one with none (Words until its mark is chosen) launches on the ground alone. write(if (look.isPresent) canvas(Math.round(288f * scale)) else objectOn(288f, splashSide, scale), "drawable-$density", "launch_object")if (nightThing != null && !look.isPresent) write(objectOn(288f, splashSide, scale, nightThing), "drawable-night-$density", "launch_object") } resources(out, ground, monochrome = true) }/** The launcher icon and splash of an app with no cut-out: the painted icon fills the visible 72 dp; the splash's object is empty. */privatefun bare(out: File, ground: Color, painted: BufferedImage) { densities.forEach { (density, scale) ->val px = Math.round(108f * scale)val visible = Math.round(72f * scale)val g = { image: BufferedImage -> image.createGraphics().apply { setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC) setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY) } }val back = BufferedImage(px, px, BufferedImage.TYPE_INT_ARGB).also { c -> g(c).apply { color = ground; fillRect(0, 0, px, px); dispose() } }val front = BufferedImage(px, px, BufferedImage.TYPE_INT_ARGB).also { c -> g(c).apply { drawImage(painted, (px - visible) / 2, (px - visible) / 2, visible, visible, null); dispose() } }val folder = out.resolve("mipmap-$density").apply { mkdirs() }ImageIO.write(back, "png", folder.resolve("ic_launcher_background.png"))ImageIO.write(front, "png", folder.resolve("ic_launcher_foreground.png"))val splash = Math.round(288f * scale)ImageIO.write(BufferedImage(splash, splash, BufferedImage.TYPE_INT_ARGB), "png", out.resolve("drawable-$density").apply { mkdirs() }.resolve("launch_object.png")) } resources(out, ground, monochrome = false) }privatefun resources(out: File, ground: Color, monochrome: Boolean) {val mono = if (monochrome) "\n <monochrome android:drawable=\"@mipmap/ic_launcher_monochrome\" />"else""val adaptive = """ |<?xml version="1.0" encoding="utf-8"?> |<!-- Drawn by the build (LaunchPictures) from the flavour's launch layers. --> |<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> | <background android:drawable="@mipmap/ic_launcher_background" /> | <foreground android:drawable="@mipmap/ic_launcher_foreground" />$mono |</adaptive-icon> |""".trimMargin() out.resolve("mipmap-anydpi").apply { mkdirs() }.let { d -> d.resolve("ic_launcher.xml").writeText(adaptive) d.resolve("ic_launcher_round.xml").writeText(adaptive) }fun launchGround(folder: String, colour: String) = out.resolve(folder).apply { mkdirs() }.resolve("launch.xml").writeText(""" |<?xml version="1.0" encoding="utf-8"?> |<resources> | <!-- The launch screen's ground (the flavour's LaunchGround, the iPhone storyboard's colour; an app with a look, its background). --> | <color name="launch_ground">$colour</color> |</resources> |""".trimMargin(), )// An app with a look launches on its look's background, in the phone's light or dark.val backgrounds = look.orNull?.asFile?.let { file -> @Suppress("UNCHECKED_CAST")val colours = (JsonSlurper().parse(file) asMap<String, Any?>)["colours"] asMap<String, Map<String, String>> colours.getValue("light").getValue("background") to colours.getValue("dark").getValue("background") }val flat = flatLight.orNull?.let { it to (flatDark.orNull ?: it) }val chosen = flat ?: backgrounds launchGround("values", chosen?.first ?: "#%02X%02X%02X".format(ground.red, ground.green, ground.blue)) chosen?.let { launchGround("values-night", it.second) } }}// RELEASE SIGNING reads the upload key from OUTSIDE the tree: the keystore's// path, a file holding its one password (store and key), and the alias. Play// App Signing holds the app key; this is only the key an upload is signed// with. Nothing of it is in gradle.properties or the repository, and a// release build without it stops and names what is missing (verifyUploadKey).// One upload key per Play app: `pnpm android:bundle --flavor <app>` names it.val uploadKeystore: String? = System.getenv("COTTON_ANDROID_KEYSTORE")?.takeIf { it.isNotBlank() }val uploadPasswordFile: String? = System.getenv("COTTON_ANDROID_KEYSTORE_PASSWORD_FILE")?.takeIf { it.isNotBlank() }val uploadAlias: String? = System.getenv("COTTON_ANDROID_KEY_ALIAS")?.takeIf { it.isNotBlank() }fun uploadKeyMissing(): String? = when { uploadKeystore == null -> "COTTON_ANDROID_KEYSTORE is not set: name the upload keystore (outside the tree)" !file(uploadKeystore).isFile -> "COTTON_ANDROID_KEYSTORE names no file: $uploadKeystore" uploadPasswordFile == null -> "COTTON_ANDROID_KEYSTORE_PASSWORD_FILE is not set: name the file holding the keystore's password" !file(uploadPasswordFile).isFile -> "COTTON_ANDROID_KEYSTORE_PASSWORD_FILE names no file: $uploadPasswordFile" uploadAlias == null -> "COTTON_ANDROID_KEY_ALIAS is not set: name the app's upload key (<app>-upload; pnpm android:bundle names it)"else -> null}/** The build number Play counts by, the same for every app: the commit's place on main's first-parent line * (`git rev-list --count --first-parent HEAD`), which only grows; `pnpm android:bundle` hands it over as * COTTON_ANDROID_VERSION_CODE after checking the commit is main's, and a build run alone counts it here. */val commitVersionCode: Intby lazy {System.getenv("COTTON_ANDROID_VERSION_CODE")?.toIntOrNull() ?: providers.exec { commandLine("git", "rev-list", "--count", "--first-parent", "HEAD"); workingDir = rootDir } .standardOutput.asText.get().trim().toInt()}// A walk on an x86_64 emulator builds for its ABI INSTEAD of the phone's// (-Pcotton.walkAbi=x86_64, debug builds only: pnpm android:walk passes it), so// the walk's APK carries one 230 MB debug core, not two; a cut carries arm64-v8a alone.val walkAbi: String? = (findProperty("cotton.walkAbi") asString?)?.takeIf { it.isNotBlank() }// CI's R8 CHECK (-Pcotton.r8Check=true, assemble<App>LiveRelease only): the release variant shrunk by R8 as Play's// is, to prove the keep rules (the JNI bridge, serialization) on every push, but unsigned and carrying the debug core// from src/debug/jniLibs: the box holds no upload key and the app's own LTO core costs ~12 minutes. An unsigned APK// installs nowhere and a bundle is refused, so nothing built this way can ship.val r8Check: Boolean = findProperty("cotton.r8Check") == "true"check(!r8Check || gradle.startParameter.taskNames.none { it.contains("bundle", ignoreCase = true) }) { "cotton.r8Check builds an unsigned APK to prove R8; a bundle is cut by pnpm android:bundle" }// THE BOX'S CUT (-Pcotton.unsignedRelease=true, bundle<App><Server>Release only: `pnpm android:bundle --unsigned`,// which `pnpm android:release` runs): the release bundle exactly as Play takes it, the app's own core and R8, but// with no signature, because no upload key is ever on the box. The signing Mac signs it with the app's upload key// (the signing script) after checking its sha256 against the box's manifest; Play refuses it unsigned.val unsignedRelease: Boolean = findProperty("cotton.unsignedRelease") == "true"check(!unsignedRelease || (!r8Check && gradle.startParameter.taskNames.all { it.contains("bundle", ignoreCase = true) && it.endsWith("Release") })) {"cotton.unsignedRelease builds only bundle<App><Server>Release (pnpm android:bundle --unsigned), never with cotton.r8Check"}android { namespace = "com.cottondb.app" compileSdk = 36 ndkVersion = "27.1.12297006" defaultConfig { minSdk = 28 targetSdk = 36 versionName = "1.0.0" ndk { abiFilters += walkAbi ?: "arm64-v8a" } } flavorDimensions += listOf("app", "server") productFlavors { apps.forEach { app -> create(app.slug) { dimension = "app" applicationId = app.pkg versionCode = commitVersionCode buildConfigField("String", "SLUG", "\"${app.slug}\"") resValue("color", "ground", app.windowGround) } }// serverSuffix names what the live and dev builds keep apart in a manifest (Sites' hand-over permission from// Comms: the live and dev builds are signed by different keys, so they may never share one permission name). create("live") { dimension = "server" buildConfigField("String", "SERVER", "\"real\"") manifestPlaceholders["serverSuffix"] = ""// The open host a Circle invitation link names (apps/business/wrangler.jsonc OPEN_HOST, live). manifestPlaceholders["openHost"] = "cottondb.com" } create("dev") { dimension = "server" applicationIdSuffix = ".dev" buildConfigField("String", "SERVER", "\"dev\"") manifestPlaceholders["serverSuffix"] = ".dev"// The dev Worker's OPEN_HOST: config/dev-server.json's host. manifestPlaceholders["openHost"] = devHost } } signingConfigs {if (uploadKeyMissing() == null) { create("upload") { storeFile = file(uploadKeystore!!)val password = file(uploadPasswordFile!!).readText().trim() storePassword = password keyPassword = password keyAlias = uploadAlias!! } } }// A release variant reads its app's own core from src/release-<app>/jniLibs (`onVariants` below says// why): the folder is its variant's source set's. sourceSets {// The call engine (Telecom, WebRTC, the room's socket, the ring's notices): Comms' since calls moved into it// (19 Nov 2026) and Calling retired (22 Nov 2026). listOf("messages").forEach { slug -> maybeCreate(slug).java.srcDir("src/calls/kotlin") maybeCreate("test${slug.replaceFirstChar { it.uppercase() }}").java.srcDir("src/testCalls/kotlin") }// Recordings (DECISIONS chat "Recordings", 23 Nov 2026): Meetings' recorder and its turn at transcription, and// Cotton Voice's engine (sherpa-onnx, the catalogue's models), compiled into Comms as well while Meetings and// Voice stay; they leave the tree once Comms carries recordings (the retirement plan). listOf("meetings", "messages").filter { slug -> apps.any { it.slug == slug } }.forEach { slug -> maybeCreate(slug).java.srcDir("src/recordings/kotlin") maybeCreate(slug).res.srcDir("src/recordings/res") } listOf("voice", "messages").filter { slug -> apps.any { it.slug == slug } }.forEach { slug -> maybeCreate(slug).java.srcDir("src/hearing/kotlin") }// The look machinery (app/src/look: a look read from the core, its type and its pieces) and the faces it reads// (Inter, JetBrains Mono, SIL OFL), for Health; Secrets draws its own Plum look (app/src/keys/.../secrets). listOf("health").filter { slug -> apps.any { it.slug == slug } }.forEach { slug -> maybeCreate(slug).java.srcDir("src/look/kotlin") maybeCreate(slug).assets.srcDir("src/look/assets") } apps.forEach { app -> listOf("Live", "Dev").forEach { server -> maybeCreate("${app.slug}${server}Release").jniLibs.srcDir("src/release-${app.slug}/jniLibs") } } } buildTypes { release { isMinifyEnabled = true isShrinkResources = true proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") signingConfig = if (r8Check || unsignedRelease) nullelse signingConfigs.findByName("upload")// The R8 check's unsigned APK may be built for an emulator's ABI (a launch measured as Play's build runs,// its core from src/debug/jniLibs/<abi>): it installs nowhere unsigned and is never cut. check(walkAbi == null || r8Check || !gradle.startParameter.taskNames.any { it.contains("Release") }) { "cotton.walkAbi is for a walk's debug build or the R8 check; a release carries arm64-v8a alone" } } } buildFeatures { compose = true buildConfig = true } compileOptions { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 isCoreLibraryDesugaringEnabled = true } packaging { jniLibs { useLegacyPackaging = false } resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" } } testOptions { unitTests.isReturnDefaultValues = true// The specimens (app/src/test<App>/specimens): Robolectric draws an app's face with the paintings and type its// APK carries, and Roborazzi holds the picture against the kept one. `-Pspecimens=record` keeps new pictures. unitTests.isIncludeAndroidResources = true unitTests.all { test ->val record = (project.findProperty("specimens") asString?) == "record" test.systemProperty("roborazzi.test.record", record.toString()) test.systemProperty("roborazzi.test.verify", (!record).toString()) test.systemProperty("robolectric.graphicsMode", "NATIVE") test.maxHeapSize = "3g" } }}kotlin { compilerOptions { jvmTarget.set(JvmTarget.JVM_17) }}/** No variant reads src/main/jniLibs: a core there would ship in every one. */val strayCore = file("src/main/jniLibs")// Each app's assets (its flavour.json, its paintings, the type), its// launcher icon, splash and names, generated per variant from the registry.androidComponents { onVariants { variant ->val app = apps.single { it.slug == variant.productFlavors.first { (dimension, _) -> dimension == "app" }.second }val dev = variant.productFlavors.any { (dimension, name) -> dimension == "server" && name == "dev" }val title = variant.name.replaceFirstChar { it.uppercase() }// The store name (flavour.json "name") is what the app says about itself; the home screen says the short// name under the icon, because the icon already says Cotton (owner, 9 Nov 2026).val short = app.name.removePrefix("Cotton ") variant.resValues.put(variant.makeResValueKey("string", "app_name"), ResValue(app.name)) variant.resValues.put(variant.makeResValueKey("string", "launcher_name"), ResValue(if (dev) "$short Dev"else short))// The words the phone itself shows for an app before it runs (a Quick Settings tile's label, a launcher// shortcut's) are its kit lines' `system` object (crates/cotton-core/kits/shell/lines/<slug>.json), each// a string resource `<slug>_<key>`: never a word written in Kotlin or XML. repo.resolve("crates/cotton-core/kits/shell/lines/${app.slug}.json").takeIf { it.isFile }?.let { lines -> @Suppress("UNCHECKED_CAST") ((JsonSlurper().parse(lines) asMap<String, Any?>)["system"] as? Map<String, Any?>)?.forEach { (key, words) -> variant.resValues.put(variant.makeResValueKey("string", "${app.slug}_$key"), ResValue(words asString)) } }// The app's own links: its manifest's filter (`${'$'}{urlScheme}`) and the shell's reading of them (ShareIntake).val scheme = urlScheme(app.slug, dev) variant.manifestPlaceholders.put("urlScheme", scheme) variant.resValues.put(variant.makeResValueKey("string", "url_scheme"), ResValue(scheme))// Which apps on the phone are Cotton's (the shell's CottonSigners): a dev build trusts its own debug key, a// live one each registry row's Play app-signing certificates (android.signing.live). variant.resValues.put(variant.makeResValueKey("string", "cotton_signers"), ResValue(if (dev) "same-signer"else liveSigners))val assets = tasks.register<AppAssets>("copy${title}Assets") { from(app.flavourDir) { include("flavour.json") filter { line -> line.replace("{dev-host}", devHost) } } from(paperCatalogue) app.kitFiles.forEach { path -> from(repo.resolve("crates/cotton-core/kits/$path")) { into("kits/${path.substringBeforeLast('/', "")}") } } app.materials.forEach { name -> from(loomPaper.resolve("Media.xcassets/$name.imageset")) { exclude("Contents.json"); into("paper") } } from(loomPaper.resolve("Resources/Fonts")) { include("LibreCaslonText-Regular.ttf", "CourierPrime-Regular.ttf", "CourierPrime-Italic.ttf", "BarlowCondensed-SemiBold.ttf", "FrauncesText-Regular.ttf", "InstrumentSerif-Italic.ttf", "MsMadi-Regular.ttf", "BarlowCondensed-ExtraBoldItalic.ttf", "Montserrat-SemiBold.ttf", "Caveat-Regular.ttf", "NunitoSans.ttf", "NunitoSans-Italic.ttf", "IBMPlexMono-Regular.ttf", "IBMPlexMono-Medium.ttf", "IBMPlexMono-SemiBold.ttf", "IBMPlexMono-Italic.ttf") into("fonts") }// Look's faces (assets/design/shared/DECISIONS.md "Look"): Atkinson Hyperlegible Next and OpenDyslexic with their// licences (both SIL OFL 1.1), carried by the apps that have a Look; Serif and Typewriter are above. Secrets' own// faces, Red Hat Text and Red Hat Mono (assets/design/keys/DECISIONS.md "The look"), stand in the same folder.// Cotton Data's own faces are here too: Instrument Sans for words, JetBrains Mono for values (assets/design/data/DECISIONS.md "The look").if (app.slug in setOf("notes", "days", "messages", "story", "keys", "data", "sites", "mail")) {// Courier Prime's upright and italic come with every app above; its bold ones and the rest from here. from(repo.resolve("assets/fonts/look")) { exclude("CourierPrime-Regular.ttf", "CourierPrime-Italic.ttf")if (app.slug != "keys") exclude("RedHat*", "OFL-RedHat*") into("fonts") } }// Cotton Notes' faces (assets/design/notes/DECISIONS.md): Figtree for the words, JetBrains Mono for code, both SIL OFL, carried by Notes alone.if (app.slug == "notes") { from(loomPaper.resolve("Resources/Fonts")) { include("Figtree.ttf", "Figtree-Italic.ttf", "OFL-Figtree.txt"); into("fonts") }// Its licence comes with Look's faces above (assets/fonts/look, since Post's ca7ebe6935): taken once. from(file("src/look/assets/fonts")) { include("JetBrainsMono-Variable.ttf"); into("fonts") } }// Cotton Albums' faces (assets/design/albums/albums.html): Figtree for the words and DM Mono (Days' cut, a plain// zero) for counts and sizes, both SIL OFL with their licences, carried by Albums alone.if (app.slug == "albums") from(loomPaper.resolve("Resources/Fonts")) { include("Figtree.ttf", "OFL-Figtree.txt", "DMMonoDays-Regular.ttf", "DMMonoDays-Medium.ttf", "OFL-DMMono.txt") into("fonts") }// Albums Dev alone: the two-phone agreement test's crops and HyperFace's expected vectors// (assets/design/albums/align/hyperface.json), for the on-device check (AlbumsBench "agree").if (app.slug == "albums" && dev) from(repo.resolve("assets/design/albums/align")) { include("*-crop.png", "face-*.png", "hyperface.json") into("albums/agreement") }// Cotton Chat's faces (assets/design/chat/DECISIONS.md "Look"): Hanken Grotesk, with Noto Sans for nine Indian// scripts matched in weight (each a weight axis only), all SIL OFL with their licences, carried by Chat alone.if (app.slug == "messages") from(app.flavourDir.resolve("ChatFonts")) { into("fonts") }// Cotton Days' one face, DM Mono Days (DM Mono, SIL OFL, with a plain zero and the upright f; assets/design/days/pen.html), carried by Days alone.if (app.slug == "days") from(loomPaper.resolve("Resources/Fonts")) { include("DMMonoDays-Light.ttf", "DMMonoDays-Regular.ttf", "DMMonoDays-Medium.ttf") into("fonts") } } variant.sources.assets?.addGeneratedSourceDirectory(assets, AppAssets::outputDir)// Albums alone carries its face model, by its pinned hash (AlbumsFaceModel).if (app.slug == "albums") { @Suppress("UNCHECKED_CAST")val pin = (JsonSlurper().parse(repo.resolve("apps/cotton/App/Flavours/albums/face-model.json")) asMap<String, Any?>)["android"] asMap<String, Any?>val models = System.getenv("COTTON_MODELS_DIR")?.takeIf { it.isNotBlank() } ?: "${System.getProperty("user.home")}/.cache/cottondb/models"val faceModel = tasks.register<AlbumsFaceModel>("place${title}FaceModel") { model.from(File(models, pin.getValue("file") asString)) sha256.set(pin.getValue("sha256") asString) asset.set("albums/hyperface/${pin.getValue("file")}") outputDir.set(layout.buildDirectory.dir("generated/albumsFaceModel/${variant.name}")) } variant.sources.assets?.addGeneratedSourceDirectory(faceModel, AlbumsFaceModel::outputDir) }val launch = tasks.register<LaunchPictures>("draw${title}LaunchPictures") { layers.set(app.flavourDir.resolve("Assets.xcassets")) app.flavourDir.resolve("LaunchScreen.storyboard").takeIf { it.isFile }?.let { storyboard.set(it) }if (dev) devIcon.set(app.devIcon) icon.set(if (dev) app.devIcon else app.icon)// The look of the kit the flavour names (flavour.json's `kit`), where it has one. @Suppress("UNCHECKED_CAST")val kit = app.flavourDir.resolve("flavour.json").takeIf { it.isFile }?.let { (JsonSlurper().parse(it) asMap<String, Any?>)["kit"] as? String } kit?.let { repo.resolve("crates/cotton-core/kits/$it/look.json") }?.takeIf { it.isFile }?.let { look.set(it) } app.flatLaunch?.let { flat -> flatLight.set(flat.getValue("light")); flatDark.set(flat.getValue("dark")) } outputDir.set(layout.buildDirectory.dir("generated/launchPictures/${variant.name}")) } variant.sources.res?.addGeneratedSourceDirectory(launch, LaunchPictures::outputDir)// A release carries the app's OWN core (15 Nov 2026): built for its kit// (`pnpm android:core <app>`, COTTON_CORE_KIT), it holds that kit's pictures and the shell's and no// other app's, 23 MB a shared core carried into every app. It sits in src/release-<app>/jniLibs (the// variant's source set names that folder, `sourceSets` above) with the kit it was built for beside it// (core-kit); a core built for another kit stops the build.if (variant.buildType == "release" && r8Check) { variant.sources.jniLibs?.addStaticSourceDirectory(file("src/debug/jniLibs").path) } elseif (variant.buildType == "release") {val home = file("src/release-${app.slug}")val lib = home.resolve("jniLibs/arm64-v8a/libcotton_android_jni.so") @Suppress("UNCHECKED_CAST")val kit = (JsonSlurper().parse(app.flavourDir.resolve("flavour.json")) asMap<String, Any?>)["kit"] asString? ?: ""val verify = tasks.register("verify${title}NativeLibrary") { doLast { check(!file("src/release/jniLibs").walkTopDown().any { it.isFile } && !strayCore.walkTopDown().any { it.isFile }) {"src/release/jniLibs or src/main/jniLibs holds a core: a release reads only its app's own, src/release-<app>/jniLibs — remove it" } check(lib.exists()) { "Missing ${lib.path}: build ${app.slug}'s own core with `pnpm android:core ${app.slug}`" }val built = home.resolve("core-kit").takeIf { it.isFile }?.readText()?.trim() check(built == kit) {"${lib.path} was built for kit '${built ?: "(no core-kit line)"}', and ${app.slug}'s kit is '$kit': it carries another app's pictures — `pnpm android:core ${app.slug}`" } } } tasks.matching { it.name == "pre${title}Build" }.configureEach { dependsOn(verify) }// AGP's merge of jniLibs folders does not read a core's bytes: one rebuilt in place under the same// name left the old core in the bundle (found on the box, 15 Nov 2026: the whole core swapped for// Books' own, the task UP-TO-DATE). The core and its kit line are inputs of the merge here. tasks.matching { it.name == "merge${title}JniLibFolders" }.configureEach { inputs.files(lib, home.resolve("core-kit")).withPropertyName("cottonCore").optional() } } firebase(app.slug, variant.applicationId.get()).forEach { (name, value) -> variant.resValues.put(variant.makeResValueKey("string", name), ResValue(value)) } }}/** * An app that takes pushes (Messages) keeps its Firebase config beside its sources (`src/<app>/google-services.json`, * one file holding the live and the dev client): the strings FirebaseInitProvider reads (`google_app_id`, * `gcm_defaultSenderId`, `google_api_key`, `project_id`) are its client's, picked by the variant's package, as the * google-services plugin would write them, so no other app carries Firebase or needs the file. An app with no * file gets none; a file with no client for the package stops the build. */fun firebase(slug: String, packageName: String): Map<String, String> {val config = file("src/$slug/google-services.json")if (!config.isFile) return emptyMap()val read = JsonSlurper().parse(config) asMap<String, Any?>val project = read["project_info"] asMap<String, Any?>val client = (read["client"] asList<Map<String, Any?>>).firstOrNull { client -> ((client["client_info"] asMap<String, Any?>)["android_client_info"] asMap<String, Any?>)["package_name"] == packageName } ?: error("src/$slug/google-services.json holds no client for $packageName")val key = ((client["api_key"] asList<Map<String, Any?>>).first())["current_key"] asStringreturn mapOf("google_app_id" to ((client["client_info"] asMap<String, Any?>)["mobilesdk_app_id"] asString),"gcm_defaultSenderId" to (project["project_number"] asString),"google_api_key" to key,"project_id" to (project["project_id"] asString), )}// The core is a Rust .so built for Android (cargo-ndk). The debug variants// carry the `android-debug` profile's core (no LTO, what CI and a walk build)// from src/debug/jniLibs: one whole core, every kit's pictures, the flavour it// opens as its manifest's. A release variant (the bundle on Play) carries its// app's own `android` profile core (size-optimised, fat LTO, its kit's// pictures alone) from src/release-<app>/jniLibs, checked in `onVariants`// above. Each variant reads only its own, so a debug core never ships in a// Play cut; neither builds without its core.val jniCoreProfiles = mapOf("debug" to "android-debug")jniCoreProfiles.forEach { (buildType, profile) ->val type = buildType.replaceFirstChar { it.uppercase() }val abi = if (buildType == "debug") walkAbi ?: "arm64-v8a"else"arm64-v8a"val lib = file("src/$buildType/jniLibs/$abi/libcotton_android_jni.so")val verify = tasks.register("verify${type}NativeLibrary") { doLast { check(strayCore.walkTopDown().none { it.isFile }) {"${strayCore.path} holds a core: a variant reads only src/debug or its app's src/release-<app> jniLibs — move it to the one its profile names" } check(lib.exists()) {"Missing ${lib.path}: build the core on the box at the $profile profile — " +"ANDROID_NDK_HOME=/opt/android-sdk/ndk/27.1.12297006 BOX_CARGO_ENV=ANDROID_NDK_HOME " +"pnpm box:cargo ndk -t $abi -P 28 build --profile $profile -p cotton-android-jni — " +"and copy its libcotton_android_jni.so from the box tree here" } } } tasks.matching { it.name.startsWith("pre") && it.name.endsWith("${type}Build") }.configureEach { dependsOn(verify) }}// A release (the bundle Play takes, the APK the walk installs) is signed with// the upload key or not built at all; the box's unsigned cut and CI's R8 check alone go without.val verifyUploadKey by tasks.registering {val missing = if (r8Check || unsignedRelease) nullelse uploadKeyMissing() doLast { check(missing == null) { missing!! } }}tasks.matching { it.name.startsWith("pre") && it.name.endsWith("ReleaseBuild") }.configureEach { dependsOn(verifyUploadKey) }/** * An AAR named by URL and sha256 (app/flavours.json `aars`): fetched once into Gradle's own cache folder * (~/.gradle/caches/cotton-aars/<sha256>/), checked against its sha256 before any build reads it, and never in git. * A file whose bytes do not match stops the build and is deleted. */fun fetchedAar(url: String, sha256: String): ConfigurableFileCollection {val name = url.substringAfterLast('/')val home = gradle.gradleUserHomeDir.resolve("caches/cotton-aars/$sha256").apply { mkdirs() }val aar = home.resolve(name)fun digest(f: File) = MessageDigest.getInstance("SHA-256").digest(f.readBytes()).joinToString("") { b -> "%02x".format(b) }if (!aar.isFile) {val part = home.resolve("$name.part") URI(url).toURL().openStream().use { input -> part.outputStream().use { out -> input.copyTo(out) } } check(digest(part) == sha256) { part.delete(); "app/flavours.json: $url does not hash to $sha256" } part.renameTo(aar) }return files(aar)}dependencies { implementation(project(":shell"))// The writing kit (:writing), in the apps that write: Notes."notesImplementation"(project(":writing"))// The shared composer (:composer), in the apps that take typed or spoken words: Story, then Chat (Messages)."storyImplementation"(project(":composer"))"messagesImplementation"(project(":composer")) coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.5")// Each app's own libraries, on its flavour alone (app/flavours.json). apps.forEach { app -> app.dependencies.forEach { "${app.slug}Implementation"(it) } } apps.forEach { app -> app.aars.forEach { aar -> "${app.slug}Implementation"(fetchedAar(aar.getValue("url"), aar.getValue("sha256"))) } } testImplementation("junit:junit:4.13.2") testImplementation("org.json:json:20240303") testImplementation("org.robolectric:robolectric:4.16") testImplementation("io.github.takahirom.roborazzi:roborazzi:1.50.0") testImplementation("io.github.takahirom.roborazzi:roborazzi-compose:1.50.0") testImplementation("androidx.compose.ui:ui-test-junit4") debugImplementation("androidx.compose.ui:ui-tooling")}