chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
place.hud.hudkit 0.6.0 Latest 5 packages
0
0
Android: HUDKit in Compose draws every view, in a gallery app
android/app/src/debug/res/xml/network_security_config.xmlnew+9−0
| @@ -0,0 +1,9 @@ | ||
<?xml version="1.0" encoding="utf-8"?> | ||
<!-- A debug build reaches `just serve` on this machine, plain http, as the emulator names it (10.0.2.2). --> | ||
<network-security-config> | ||
<base-config cleartextTrafficPermitted="false" /> | ||
<domain-config cleartextTrafficPermitted="true"> | ||
<domain includeSubdomains="false">10.0.2.2</domain> | ||
<domain includeSubdomains="false">localhost</domain> | ||
</domain-config> | ||
</network-security-config> | ||
android/app/src/main/java/place/hud/app/GalleryScreen.ktnew+279−0
| @@ -0,0 +1,279 @@ | ||
package place.hud.app | ||
| ||
import android.content.Context | ||
import android.util.Log | ||
import androidx.compose.foundation.background | ||
import androidx.compose.foundation.border | ||
import androidx.compose.foundation.layout.Arrangement | ||
import androidx.compose.foundation.layout.Box | ||
import androidx.compose.foundation.layout.Column | ||
import androidx.compose.foundation.layout.PaddingValues | ||
import androidx.compose.foundation.layout.Row | ||
import androidx.compose.foundation.layout.Spacer | ||
import androidx.compose.foundation.layout.fillMaxSize | ||
import androidx.compose.foundation.layout.fillMaxWidth | ||
import androidx.compose.foundation.layout.height | ||
import androidx.compose.foundation.layout.padding | ||
import androidx.compose.foundation.layout.safeDrawingPadding | ||
import androidx.compose.foundation.layout.size | ||
import androidx.compose.foundation.pager.HorizontalPager | ||
import androidx.compose.foundation.pager.rememberPagerState | ||
import androidx.compose.foundation.rememberScrollState | ||
import androidx.compose.foundation.shape.RoundedCornerShape | ||
import androidx.compose.foundation.verticalScroll | ||
import androidx.compose.material3.HorizontalDivider | ||
import androidx.compose.material3.Text | ||
import androidx.compose.runtime.Composable | ||
import androidx.compose.runtime.CompositionLocalProvider | ||
import androidx.compose.runtime.LaunchedEffect | ||
import androidx.compose.runtime.getValue | ||
import androidx.compose.runtime.produceState | ||
import androidx.compose.ui.Alignment | ||
import androidx.compose.ui.Modifier | ||
import androidx.compose.ui.draw.clip | ||
import androidx.compose.ui.platform.LocalContext | ||
import androidx.compose.ui.text.font.FontFamily | ||
import androidx.compose.ui.text.style.TextAlign | ||
import androidx.compose.ui.text.style.TextOverflow | ||
import androidx.compose.ui.unit.dp | ||
import kotlinx.coroutines.Dispatchers | ||
import kotlinx.coroutines.withContext | ||
import kotlinx.serialization.json.JsonArray | ||
import kotlinx.serialization.json.JsonElement | ||
import kotlinx.serialization.json.JsonObject | ||
import kotlinx.serialization.json.JsonPrimitive | ||
import place.hud.kit.data.Call | ||
import place.hud.kit.data.Drawn | ||
import place.hud.kit.data.EmptyObject | ||
import place.hud.kit.data.HudJson | ||
import place.hud.kit.data.ToolResult | ||
import place.hud.kit.data.get | ||
import place.hud.kit.data.isTrue | ||
import place.hud.kit.data.items | ||
import place.hud.kit.data.json | ||
import place.hud.kit.data.number | ||
import place.hud.kit.data.obj | ||
import place.hud.kit.data.str | ||
import place.hud.kit.data.string | ||
import place.hud.kit.support.HudColors | ||
import place.hud.kit.support.HudType | ||
import place.hud.kit.support.Picture | ||
import place.hud.kit.support.Source | ||
import place.hud.kit.support.Space | ||
import place.hud.kit.tree.LocalListBleed | ||
import place.hud.kit.tree.LocalShown | ||
import place.hud.kit.tree.Shown | ||
import place.hud.kit.view.ResultView | ||
import place.hud.kit.view.ViewContext | ||
| ||
// The gallery, for design review: every drawing HUD makes as a tile, one a | ||
// page, from the sample answers `just gallery-data` writes to | ||
// target/gallery/gallery.json, a debug build's asset: the same ones the web's | ||
// `just gallery` and the iOS app's gallery draw, to compare tile for tile. | ||
// Each tile's body is its result's `_meta.ui` drawn by HUDKit; what it opens | ||
// or writes does nothing but log. Launched with `--es gallery <entry id>`, it | ||
// starts at that entry. | ||
| ||
private const val TAG = "gallery" | ||
| ||
/** Where the recorded answers' server-proxied URLs (blobs, icons) point: the server they were recorded from. */ | ||
private const val RECORDED = "http://localhost:8787/" | ||
| ||
/** One entry of gallery.json, read for drawing. */ | ||
class GalleryEntry( | ||
val id: String, | ||
val index: Int, | ||
val group: String, | ||
val note: String, | ||
val title: String, | ||
val icon: String?, | ||
val handle: String?, | ||
val drawn: Drawn, | ||
val context: ViewContext, | ||
) | ||
| ||
private sealed interface Loaded { | ||
data object Missing : Loaded | ||
data class Failed(val why: String) : Loaded | ||
data class Ready(val entries: List<GalleryEntry>) : Loaded | ||
} | ||
| ||
@Composable | ||
fun GalleryScreen(server: String, start: String?) { | ||
val context = LocalContext.current | ||
val loaded by produceState<Loaded?>(null, server) { value = withContext(Dispatchers.IO) { load(context, server) } } | ||
Box(Modifier.fillMaxSize().background(HudColors.canvas).safeDrawingPadding(), contentAlignment = Alignment.Center) { | ||
when (val now = loaded) { | ||
null -> Unit | ||
Loaded.Missing -> Notice("No gallery", "Run `just gallery-data`, then build the app again.") | ||
is Loaded.Failed -> Notice("Couldn't read the gallery", now.why) | ||
is Loaded.Ready -> Strip(now.entries, start) | ||
} | ||
} | ||
} | ||
| ||
@Composable | ||
private fun Notice(title: String, words: String) { | ||
Column(Modifier.padding(Space.s5), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(Space.s2)) { | ||
Text(title, style = HudType.heading) | ||
Text(words, style = HudType.body, color = HudColors.muted, textAlign = TextAlign.Center) | ||
} | ||
} | ||
| ||
@Composable | ||
private fun Strip(entries: List<GalleryEntry>, start: String?) { | ||
val first = entries.indexOfFirst { it.id == start }.coerceAtLeast(0) | ||
val pager = rememberPagerState(initialPage = first) { entries.size } | ||
LaunchedEffect(first) { pager.scrollToPage(first) } | ||
HorizontalPager( | ||
pager, | ||
contentPadding = PaddingValues(horizontal = Space.s3, vertical = Space.s2), | ||
pageSpacing = Space.s2, | ||
beyondViewportPageCount = 0, | ||
key = { entries[it].id }, | ||
) { page -> | ||
val entry = entries[page] | ||
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(Space.s1)) { | ||
Column(Modifier.padding(horizontal = Space.s1)) { | ||
Text("${entry.index + 1}/${entries.size} ${entry.id}", style = HudType.caption.copy(fontFamily = FontFamily.Monospace), color = HudColors.muted) | ||
Text(entry.note, style = HudType.caption, color = HudColors.muted, maxLines = 2, minLines = 2, overflow = TextOverflow.Ellipsis) | ||
} | ||
Tile(entry, Modifier.weight(1f)) | ||
} | ||
} | ||
} | ||
| ||
/** One entry as a workspace tile: a header, its result drawn under it as a tile's body draws it. */ | ||
@Composable | ||
private fun Tile(entry: GalleryEntry, modifier: Modifier) { | ||
val shape = RoundedCornerShape(16.dp) | ||
Column(modifier.fillMaxWidth().clip(shape).background(HudColors.tileSurface).border(0.5.dp, HudColors.hairline, shape)) { | ||
Row( | ||
Modifier.fillMaxWidth().padding(horizontal = Space.s3, vertical = Space.s2), | ||
horizontalArrangement = Arrangement.spacedBy(Space.s2), | ||
verticalAlignment = Alignment.CenterVertically, | ||
) { | ||
if (entry.icon != null) Picture(Source(entry.icon), Modifier.size(20.dp).clip(RoundedCornerShape(4.dp)), placeholder = "") | ||
Text(entry.title, style = HudType.heading, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false)) | ||
if (entry.handle != null) Text("@${entry.handle}", style = HudType.small, color = HudColors.muted, maxLines = 1, overflow = TextOverflow.Ellipsis) | ||
} | ||
HorizontalDivider(color = HudColors.hairline, thickness = 0.5.dp) | ||
CompositionLocalProvider(LocalShown provides Shown(entry.title, entry.handle)) { | ||
if (entry.drawn.pagesItself) { | ||
ResultView(entry.drawn, entry.context, Modifier.fillMaxSize()) | ||
} else { | ||
CompositionLocalProvider(LocalListBleed provides Space.s3) { | ||
Column( | ||
Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = Space.s3, vertical = Space.s2), | ||
verticalArrangement = Arrangement.spacedBy(Space.s3), | ||
) { | ||
ResultView(entry.drawn, entry.context) | ||
Spacer(Modifier.height(Space.s3)) | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} | ||
| ||
private fun load(context: Context, server: String): Loaded { | ||
val text = try { | ||
context.assets.open("gallery.json").bufferedReader().use { it.readText() } | ||
} catch (_: java.io.FileNotFoundException) { | ||
return Loaded.Missing | ||
} | ||
return try { | ||
val json = HudJson.parseToJsonElement(text) | ||
if (json["v"].number != 1.0) return Loaded.Failed("gallery.json is not version 1.") | ||
Loaded.Ready(entries(json, server)) | ||
} catch (e: Exception) { | ||
Loaded.Failed(e.message ?: e.toString()) | ||
} | ||
} | ||
| ||
private fun entries(json: JsonElement, server: String): List<GalleryEntry> { | ||
val me = json["me"] | ||
val tiles = json.items("tiles") | ||
// What a form asks of a tool (`query`, `link_card`, …): the answer of a tile of that call, as the web's gallery answers it. | ||
val answers = HashMap<Call, JsonElement>() | ||
for (tile in tiles) { | ||
val call = Call.of(tile["call"]) ?: continue | ||
val found = tile["result"]["structuredContent"] ?: continue | ||
answers.putIfAbsent(call, moved(found, server)) | ||
} | ||
return tiles.mapIndexedNotNull { i, tile -> | ||
val id = tile.str("id") ?: return@mapIndexedNotNull null | ||
val header = tile["header"] ?: return@mapIndexedNotNull null | ||
val result = ToolResult(moved(tile["result"] ?: EmptyObject, server)) | ||
val drawn = Drawn.of(result) | ||
GalleryEntry( | ||
id = id, | ||
index = i, | ||
group = tile.str("group") ?: "", | ||
note = tile.str("note") ?: "", | ||
title = header.str("title") ?: Call.of(tile["call"])?.name ?: id, | ||
icon = header.str("icon")?.let { server.trimEnd('/') + it }, | ||
handle = handle(header.str("account"), me), | ||
drawn = drawn, | ||
context = inert(id, result, drawn, answers), | ||
) | ||
} | ||
} | ||
| ||
/** The account a tile shows by handle: as the header names it, `me` as the gallery's own; a DID it has no handle for, none. */ | ||
private fun handle(account: String?, me: JsonElement?): String? = when { | ||
account == null -> null | ||
account == "me" || account == me.str("did") -> me.str("handle") | ||
account.startsWith("did:") -> null | ||
else -> account | ||
} | ||
| ||
/** An answer with every URL of the recording server moved to `server`, so its blobs and icons load from the app's. */ | ||
private fun moved(json: JsonElement, server: String): JsonElement = when (json) { | ||
is JsonPrimitive -> if (json.isString && json.content.startsWith(RECORDED)) JsonPrimitive(server + json.content.removePrefix(RECORDED)) else json | ||
is JsonArray -> JsonArray(json.map { moved(it, server) }) | ||
is JsonObject -> JsonObject(json.mapValues { moved(it.value, server) }) | ||
} | ||
| ||
/** | ||
* The context a tile's result draws with, as a workspace tile's: its handlers | ||
* there, so it draws what it would, but each only logs; a tool a form calls | ||
* answers as the gallery's tile of that call does (a write, with nothing | ||
* written), an upload with a made-up blob. | ||
*/ | ||
private fun inert(id: String, result: ToolResult, drawn: Drawn, answers: Map<Call, JsonElement>): ViewContext { | ||
val ui = (drawn as? Drawn.Tree)?.ui | ||
return ViewContext().apply { | ||
trusted = ui?.get("trusted").isTrue | ||
onOpenActor = { Log.i(TAG, "$id: open actor $it") } | ||
onOpenLink = { Log.i(TAG, "$id: open link $it") } | ||
onReplace = { Log.i(TAG, "$id: tab ${it.name}") } | ||
onCall = { call, _ -> Log.i(TAG, "$id: open ${call.name}") } | ||
if (result.viewer != null) { | ||
onAction = { action -> | ||
Log.i(TAG, "$id: action ${action.tool.name}") | ||
null | ||
} | ||
onTool = { call -> | ||
Log.i(TAG, "$id: tool ${call.name}") | ||
answers[call] ?: if (call.name == "apply_writes") json("results" to emptyList<Any>()) else error("The gallery has no answer for ${call.name}.") | ||
} | ||
onUpload = { bytes, progress -> | ||
Log.i(TAG, "$id: upload ${bytes.size} bytes") | ||
progress(1f) | ||
json( | ||
"\$type" to "blob", | ||
"ref" to mapOf("\$link" to "bafkreigallerygallerygallerygallerygallerygallerygallerygall"), | ||
"mimeType" to "image/jpeg", | ||
"size" to bytes.size, | ||
) | ||
} | ||
} | ||
onMore = { Log.i(TAG, "$id: page more") } | ||
onReload = { Log.i(TAG, "$id: reload") } | ||
val report = ui?.get("report") | ||
if (report["feed"].string != null && report["seen"].isTrue) { | ||
onInteraction = { event, _ -> Log.i(TAG, "$id: interaction $event") } | ||
} | ||
} | ||
} | ||
android/app/src/main/java/place/hud/app/MainActivity.ktnew+21−0
| @@ -0,0 +1,21 @@ | ||
package place.hud.app | ||
| ||
import android.os.Bundle | ||
import androidx.activity.ComponentActivity | ||
import androidx.activity.compose.setContent | ||
import androidx.activity.enableEdgeToEdge | ||
import place.hud.kit.support.HudThemed | ||
| ||
/** The app: for now, the gallery, every drawing HUD makes as a tile. */ | ||
class MainActivity : ComponentActivity() { | ||
override fun onCreate(savedInstanceState: Bundle?) { | ||
super.onCreate(savedInstanceState) | ||
enableEdgeToEdge() | ||
val start = intent.getStringExtra("gallery") | ||
setContent { | ||
HudThemed(theme = null) { | ||
GalleryScreen(server = BuildConfig.SERVER, start = start) | ||
} | ||
} | ||
} | ||
} | ||
android/app/src/main/res/values/strings.xmlnew+4−0
| @@ -0,0 +1,4 @@ | ||
<?xml version="1.0" encoding="utf-8"?> | ||
<resources> | ||
<string name="app_name">HUD</string> | ||
</resources> | ||
android/app/src/main/res/xml/network_security_config.xmlnew+5−0
| @@ -0,0 +1,5 @@ | ||
<?xml version="1.0" encoding="utf-8"?> | ||
<!-- HTTPS alone. A debug build's own (src/debug) lets in a server on this machine. --> | ||
<network-security-config> | ||
<base-config cleartextTrafficPermitted="false" /> | ||
</network-security-config> | ||
android/app/src/main/AndroidManifest.xmlnew+21−0
| @@ -0,0 +1,21 @@ | ||
<?xml version="1.0" encoding="utf-8"?> | ||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"> | ||
| ||
<uses-permission android:name="android.permission.INTERNET" /> | ||
| ||
<application | ||
android:label="@string/app_name" | ||
android:networkSecurityConfig="@xml/network_security_config" | ||
android:supportsRtl="true" | ||
android:theme="@android:style/Theme.Material.NoActionBar"> | ||
<activity | ||
android:name=".MainActivity" | ||
android:exported="true" | ||
android:windowSoftInputMode="adjustResize"> | ||
<intent-filter> | ||
<action android:name="android.intent.action.MAIN" /> | ||
<category android:name="android.intent.category.LAUNCHER" /> | ||
</intent-filter> | ||
</activity> | ||
</application> | ||
</manifest> | ||
android/app/build.gradle.ktsnew+73−0
| @@ -0,0 +1,73 @@ | ||
// The Android app around HUDKit (`:hudkit`). For now its one screen is the | ||
// gallery: every drawing HUD makes as a tile, from the sample answers | ||
// `just gallery-data` writes to target/gallery/gallery.json, which a debug | ||
// build carries as an asset, as the iOS app's Debug builds do. | ||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget | ||
| ||
plugins { | ||
alias(libs.plugins.android.application) | ||
alias(libs.plugins.kotlin.compose) | ||
} | ||
| ||
android { | ||
namespace = "place.hud.app" | ||
compileSdk = 37 | ||
| ||
defaultConfig { | ||
applicationId = "place.hud.app" | ||
minSdk = 28 | ||
targetSdk = 36 | ||
versionCode = 1 | ||
versionName = "0.1.0" | ||
} | ||
| ||
buildTypes { | ||
debug { | ||
applicationIdSuffix = ".debug" | ||
// A server on this machine (`just serve`), as the emulator reaches it. | ||
buildConfigField("String", "SERVER", "\"http://10.0.2.2:8787/\"") | ||
} | ||
release { | ||
buildConfigField("String", "SERVER", "\"https://hud.place/\"") | ||
isMinifyEnabled = true | ||
isShrinkResources = true | ||
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt")) | ||
} | ||
} | ||
| ||
// The gallery's sample answers, in debug alone; built without them, the | ||
// gallery says how to make them. | ||
sourceSets.getByName("debug").assets.directories.add(layout.buildDirectory.dir("generated/gallery").get().asFile.path) | ||
| ||
compileOptions { | ||
sourceCompatibility = JavaVersion.VERSION_17 | ||
targetCompatibility = JavaVersion.VERSION_17 | ||
} | ||
| ||
buildFeatures { | ||
compose = true | ||
buildConfig = true | ||
} | ||
} | ||
| ||
kotlin { | ||
compilerOptions { | ||
jvmTarget.set(JvmTarget.JVM_17) | ||
} | ||
} | ||
| ||
val galleryData = tasks.register<Copy>("galleryData") { | ||
description = "Copies target/gallery/gallery.json, from `just gallery-data`, into the debug build's assets." | ||
from(rootProject.file("../target/gallery")) { include("gallery.json") } | ||
into(layout.buildDirectory.dir("generated/gallery")) | ||
} | ||
tasks.matching { it.name == "mergeDebugAssets" }.configureEach { dependsOn(galleryData) } | ||
| ||
dependencies { | ||
implementation(project(":hudkit")) | ||
implementation(libs.androidx.core.ktx) | ||
implementation(libs.androidx.activity.compose) | ||
implementation(libs.androidx.lifecycle.runtime.compose) | ||
implementation(libs.kotlinx.coroutines.android) | ||
debugImplementation(libs.androidx.ui.tooling) | ||
} | ||
android/gradle/wrapper/gradle-wrapper.jarnew+0−0
A binary file, not shown.
android/gradle/wrapper/gradle-wrapper.propertiesnew+7−0
| @@ -0,0 +1,7 @@ | ||
distributionBase=GRADLE_USER_HOME | ||
distributionPath=wrapper/dists | ||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip | ||
networkTimeout=10000 | ||
validateDistributionUrl=true | ||
zipStoreBase=GRADLE_USER_HOME | ||
zipStorePath=wrapper/dists | ||
android/gradle/libs.versions.tomlnew+48−0
| @@ -0,0 +1,48 @@ | ||
[versions] | ||
agp = "9.3.1" | ||
kotlin = "2.3.21" | ||
coreKtx = "1.19.0" | ||
lifecycle = "2.11.0" | ||
activityCompose = "1.13.0" | ||
composeBom = "2026.08.00" | ||
serialization = "1.11.0" | ||
coroutines = "1.10.2" | ||
okhttp = "5.5.0" | ||
coil = "3.5.0" | ||
media3 = "1.11.1" | ||
junit = "4.13.2" | ||
robolectric = "4.16" | ||
testCore = "1.7.0" | ||
| ||
[libraries] | ||
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } | ||
androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycle" } | ||
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" } | ||
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" } | ||
androidx-ui = { group = "androidx.compose.ui", name = "ui" } | ||
androidx-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" } | ||
androidx-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" } | ||
androidx-foundation = { group = "androidx.compose.foundation", name = "foundation" } | ||
androidx-material3 = { group = "androidx.compose.material3", name = "material3" } | ||
androidx-material-icons-core = { group = "androidx.compose.material", name = "material-icons-core" } | ||
androidx-media3-exoplayer = { group = "androidx.media3", name = "media3-exoplayer", version.ref = "media3" } | ||
androidx-media3-exoplayer-hls = { group = "androidx.media3", name = "media3-exoplayer-hls", version.ref = "media3" } | ||
androidx-media3-ui-compose = { group = "androidx.media3", name = "media3-ui-compose", version.ref = "media3" } | ||
kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "serialization" } | ||
kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "coroutines" } | ||
kotlinx-coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version.ref = "coroutines" } | ||
okhttp = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhttp" } | ||
coil-compose = { group = "io.coil-kt.coil3", name = "coil-compose", version.ref = "coil" } | ||
coil-network-okhttp = { group = "io.coil-kt.coil3", name = "coil-network-okhttp", version.ref = "coil" } | ||
androidx-exifinterface = { group = "androidx.exifinterface", name = "exifinterface", version = "1.4.2" } | ||
junit = { group = "junit", name = "junit", version.ref = "junit" } | ||
robolectric = { group = "org.robolectric", name = "robolectric", version.ref = "robolectric" } | ||
androidx-test-core = { group = "androidx.test", name = "core", version.ref = "testCore" } | ||
androidx-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" } | ||
androidx-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" } | ||
| ||
[plugins] | ||
android-application = { id = "com.android.application", version.ref = "agp" } | ||
android-library = { id = "com.android.library", version.ref = "agp" } | ||
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } | ||
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } | ||
android/hudkit/src/main/java/place/hud/kit/data/Compose.ktnew+334−0
| @@ -0,0 +1,334 @@ | ||
package place.hud.kit.data | ||
| ||
import android.graphics.Bitmap | ||
import android.graphics.BitmapFactory | ||
import android.graphics.Matrix | ||
import androidx.exifinterface.media.ExifInterface | ||
import kotlinx.serialization.json.JsonArray | ||
import kotlinx.serialization.json.JsonElement | ||
import kotlinx.serialization.json.JsonNull | ||
import kotlinx.serialization.json.JsonObject | ||
import kotlinx.serialization.json.JsonPrimitive | ||
import java.io.ByteArrayInputStream | ||
import java.io.ByteArrayOutputStream | ||
import java.text.BreakIterator | ||
import java.time.LocalDateTime | ||
import java.time.ZoneId | ||
import java.time.ZoneOffset | ||
import java.time.format.DateTimeFormatter | ||
import kotlin.math.max | ||
import kotlin.math.min | ||
import kotlin.math.roundToInt | ||
import kotlin.math.roundToLong | ||
| ||
// What a `Compose` form makes of what a person wrote and picked, apart from | ||
// drawing it: the links, mentions and tags of its text as the server marks | ||
// them (crates/hud-core/src/richtext.rs), the values it sends | ||
// (`apply_writes`' `values`), and its photos made ready to upload (their | ||
// EXIF read from the original as Grain writes it, then scaled and | ||
// re-encoded as a JPEG small enough). | ||
| ||
/** | ||
* The links, mentions and tags in a text, by the server's rules: words | ||
* apart by whitespace, an opening bracket before one and punctuation after | ||
* it left out; `@` and a handle with a dot; `#` (or `#`) and 1 to 64 | ||
* characters, not all digits, with no second `#`; an http(s) URL with a | ||
* dotted host. Positions are the text's UTF-16 units, as a text field's. | ||
*/ | ||
internal object ComposeFacets { | ||
sealed interface Kind { | ||
data class Link(val url: String) : Kind | ||
| ||
/** A handle, lowercased, without its @. */ | ||
data class Mention(val handle: String) : Kind | ||
| ||
/** A tag, without its #. */ | ||
data class Tag(val tag: String) : Kind | ||
} | ||
| ||
/** One marked word: where it starts and ends (exclusive), and what it is. */ | ||
data class Mark(val start: Int, val end: Int, val kind: Kind) | ||
| ||
/** The `@` word typed at a caret: what follows the @, and where the word starts and ends, which a picked account replaces. */ | ||
data class Typed(val prefix: String, val start: Int, val end: Int) | ||
| ||
/** The longest tag marked, in characters. */ | ||
const val TAG_MAX = 64 | ||
| ||
/** The marks of `text`, in its order. */ | ||
fun marks(text: String): List<Mark> = words(text).mapNotNull { mark(text, it) } | ||
| ||
/** Each word of `text`: a run between whitespace. */ | ||
fun words(text: String): List<IntRange> { | ||
val out = mutableListOf<IntRange>() | ||
var start = -1 | ||
for (i in text.indices) { | ||
if (text[i].isWhitespace()) { | ||
if (start >= 0) out += start until i | ||
start = -1 | ||
} else if (start < 0) { | ||
start = i | ||
} | ||
} | ||
if (start >= 0) out += start until text.length | ||
return out | ||
} | ||
| ||
private val leads = setOf('(', '[', '"', '\'') | ||
private val trails = setOf('.', ',', ';', ':', '!', '?', ')', ']', '"', '\'') | ||
| ||
private fun mark(text: String, word: IntRange): Mark? { | ||
var start = word.first | ||
var end = word.last + 1 | ||
while (start < end && text[start] in leads) start++ | ||
while (end > start && text[end - 1] in trails) end-- | ||
if (start == end) return null | ||
val trimmed = text.substring(start, end) | ||
if (trimmed.startsWith("@")) { | ||
val handle = trimmed.drop(1).lowercase() | ||
return if (isHandle(handle)) Mark(start, end, Kind.Mention(handle)) else null | ||
} | ||
if (trimmed.startsWith("#") || trimmed.startsWith("#")) { | ||
val tag = trimmed.drop(1) | ||
val n = tag.codePointCount(0, tag.length) | ||
val ok = n in 1..TAG_MAX && '#' !in tag && '#' !in tag && !tag.all { it in '0'..'9' } | ||
return if (ok) Mark(start, end, Kind.Tag(tag)) else null | ||
} | ||
if (trimmed.startsWith("https://") || trimmed.startsWith("http://")) { | ||
val host = host(trimmed) ?: return null | ||
return if ('.' in host) Mark(start, end, Kind.Link(trimmed)) else null | ||
} | ||
return null | ||
} | ||
| ||
/** An http(s) URL's host, as a URL parser finds it: what its authority names, without credentials or port. */ | ||
private fun host(url: String): String? { | ||
val rest = url.substringAfter("://") | ||
val authority = rest.substring(0, rest.indexOfAny(charArrayOf('/', '?', '#', '\\')).takeIf { it >= 0 } ?: rest.length) | ||
val hostPort = authority.substringAfterLast('@') | ||
val host = if (hostPort.startsWith("[")) hostPort.substringBefore(']') + "]" else hostPort.substringBefore(':') | ||
return host.ifEmpty { null } | ||
} | ||
| ||
/** | ||
* A handle as atproto's syntax has one: two or more dotted labels of | ||
* letters, digits and inner hyphens, the last starting with a letter. | ||
*/ | ||
fun isHandle(s: String): Boolean { | ||
if (s.length > 253) return false | ||
val labels = s.split('.') | ||
if (labels.size < 2) return false | ||
for (label in labels) { | ||
if (label.length !in 1..63 || label.first() == '-' || label.last() == '-') return false | ||
if (!label.all { it in 'a'..'z' || it in 'A'..'Z' || it in '0'..'9' || it == '-' }) return false | ||
} | ||
val last = labels.last().first() | ||
return last in 'a'..'z' || last in 'A'..'Z' | ||
} | ||
| ||
/** | ||
* The `@` word the caret is at the end of, as typed so far (`@da`): what | ||
* follows the @ (at least one character), and its range, which a picked | ||
* account replaces. | ||
*/ | ||
fun typing(text: String, caret: Int): Typed? { | ||
if (caret < 0 || caret > text.length) return null | ||
var start = caret | ||
while (start > 0 && !text[start - 1].isWhitespace()) start-- | ||
val word = text.substring(start, caret) | ||
if (!word.startsWith("@") || word.length < 2) return null | ||
var end = caret | ||
while (end < text.length && !text[end].isWhitespace()) end++ | ||
return Typed(word.drop(1), start, end) | ||
} | ||
| ||
/** The first http(s) link in a text, as written. */ | ||
fun firstLink(text: String): String? = marks(text).firstNotNullOfOrNull { (it.kind as? Kind.Link)?.url } | ||
| ||
/** How many characters a person sees in a text: its grapheme clusters, as a field's `max` counts them. */ | ||
fun graphemes(text: String): Int { | ||
val it = BreakIterator.getCharacterInstance() | ||
it.setText(text) | ||
var n = 0 | ||
while (it.next() != BreakIterator.DONE) n++ | ||
return n | ||
} | ||
} | ||
| ||
/** What a `Compose` sends: the view's `given` values with the fields' beside them, those absent left out. */ | ||
internal object ComposeValues { | ||
fun merged(given: JsonElement?, fields: List<Pair<String, JsonElement?>>): JsonObject { | ||
val out = (given.obj ?: EmptyObject).toMutableMap() | ||
for ((name, value) in fields) if (value != null) out[name] = value | ||
return JsonObject(out) | ||
} | ||
| ||
/** | ||
* A `choice` field's value: its picked options' values, arrays joined; | ||
* none, or an `only` option of `null` alone, absent. | ||
*/ | ||
fun choice(picked: List<JsonElement>): JsonElement? { | ||
val given = picked.filter { it !is JsonNull } | ||
if (given.isEmpty()) return null | ||
if (given.all { it is JsonArray }) return JsonArray(given.flatMap { it as JsonArray }) | ||
return if (given.size == 1) given[0] else JsonArray(given) | ||
} | ||
| ||
/** A text's value: what was written, trimmed; nothing written, absent. */ | ||
fun text(written: String): JsonElement? { | ||
val trimmed = written.trim() | ||
return if (trimmed.isEmpty()) null else JsonPrimitive(trimmed) | ||
} | ||
} | ||
| ||
/** | ||
* A photo's EXIF as Grain writes it (`social.grain.photo.exif`), from the | ||
* tags `ExifInterface` reads of the original: its times and lengths as | ||
* integers a million times larger, only what is there. | ||
*/ | ||
internal object ComposeExif { | ||
/** A photo's tags, by `ExifInterface`'s names: as text, and as a number where they are one. */ | ||
interface Tags { | ||
fun string(tag: String): String? | ||
fun number(tag: String): Double? | ||
} | ||
| ||
/** The tags `ExifInterface` reads, a list's first value where a tag has several. */ | ||
fun tags(exif: ExifInterface): Tags = object : Tags { | ||
override fun string(tag: String): String? = exif.getAttribute(tag) | ||
| ||
override fun number(tag: String): Double? = | ||
exif.getAttributeDouble(tag, Double.NaN).takeUnless { it.isNaN() } | ||
?: exif.getAttribute(tag)?.substringBefore(',')?.trim()?.toDoubleOrNull() | ||
} | ||
| ||
fun grain(tags: Tags, zone: ZoneId = ZoneId.systemDefault()): JsonObject? { | ||
val out = LinkedHashMap<String, JsonElement>() | ||
val taken = tags.string(ExifInterface.TAG_DATETIME_ORIGINAL) | ||
date(taken, tags.string(ExifInterface.TAG_OFFSET_TIME_ORIGINAL), zone)?.let { out["dateTimeOriginal"] = JsonPrimitive(it) } | ||
tags.number(ExifInterface.TAG_EXPOSURE_TIME)?.let { out["exposureTime"] = JsonPrimitive((it * 1_000_000).roundToLong()) } | ||
tags.number(ExifInterface.TAG_F_NUMBER)?.let { out["fNumber"] = JsonPrimitive((it * 1_000_000).roundToLong()) } | ||
tags.number(ExifInterface.TAG_FOCAL_LENGTH_IN_35MM_FILM)?.let { out["focalLengthIn35mmFormat"] = JsonPrimitive(it.roundToLong()) } | ||
tags.number(ExifInterface.TAG_PHOTOGRAPHIC_SENSITIVITY)?.let { out["iSO"] = JsonPrimitive(it.roundToLong()) } | ||
tags.number(ExifInterface.TAG_FLASH)?.let { v -> FLASH[v.toInt()]?.let { out["flash"] = JsonPrimitive(it) } } | ||
for ((tag, name) in listOf( | ||
ExifInterface.TAG_MAKE to "make", | ||
ExifInterface.TAG_MODEL to "model", | ||
ExifInterface.TAG_LENS_MAKE to "lensMake", | ||
ExifInterface.TAG_LENS_MODEL to "lensModel", | ||
)) { | ||
tags.string(tag)?.trim()?.takeIf { it.isNotEmpty() }?.let { out[name] = JsonPrimitive(it) } | ||
} | ||
return if (out.isEmpty()) null else JsonObject(out) | ||
} | ||
| ||
private val written = DateTimeFormatter.ofPattern("yyyy:MM:dd HH:mm:ss") | ||
| ||
/** EXIF's `2024:05:01 14:03:22`, in its offset when it gives one, else the device's zone. */ | ||
private fun date(s: String?, offset: String?, zone: ZoneId): String? { | ||
val local = s?.let { runCatching { LocalDateTime.parse(it.trim(), written) }.getOrNull() } ?: return null | ||
val at = offset?.let { runCatching { ZoneOffset.of(it.trim()) }.getOrNull() } | ||
?.let { local.toInstant(it) } | ||
?: local.atZone(zone).toInstant() | ||
return isoString(at) | ||
} | ||
| ||
/** EXIF's flash values, in its own words, as Grain's app reads them. */ | ||
val FLASH: Map<Int, String> = mapOf( | ||
0x00 to "Flash did not fire", | ||
0x01 to "Flash fired", | ||
0x05 to "Strobe return light not detected", | ||
0x07 to "Strobe return light detected", | ||
0x09 to "Flash fired, compulsory flash mode", | ||
0x0D to "Flash fired, compulsory flash mode, return light not detected", | ||
0x0F to "Flash fired, compulsory flash mode, return light detected", | ||
0x10 to "Flash did not fire, compulsory flash mode", | ||
0x18 to "Flash did not fire, auto mode", | ||
0x19 to "Flash fired, auto mode", | ||
0x1D to "Flash fired, auto mode, return light not detected", | ||
0x1F to "Flash fired, auto mode, return light detected", | ||
0x20 to "No flash function", | ||
0x41 to "Flash fired, red-eye reduction mode", | ||
0x45 to "Flash fired, red-eye reduction mode, return light not detected", | ||
0x47 to "Flash fired, red-eye reduction mode, return light detected", | ||
0x49 to "Flash fired, compulsory flash mode, red-eye reduction mode", | ||
0x4D to "Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected", | ||
0x4F to "Flash fired, compulsory flash mode, red-eye reduction mode, return light detected", | ||
0x59 to "Flash fired, auto mode, red-eye reduction mode", | ||
0x5D to "Flash fired, auto mode, return light not detected, red-eye reduction mode", | ||
0x5F to "Flash fired, auto mode, return light detected, red-eye reduction mode", | ||
) | ||
} | ||
| ||
/** | ||
* A photo made ready to upload: a JPEG of at most `maxSide` pixels a side and | ||
* `maxBytes`, upright, without the original's metadata (a bitmap encoded | ||
* afresh carries none); its size; and the original's EXIF, when asked. | ||
*/ | ||
internal class PreparedPhoto(val jpeg: ByteArray, val width: Int, val height: Int, val exif: JsonObject?) { | ||
class Failure(message: String) : Exception(message) { | ||
companion object { | ||
val notAnImage get() = Failure("This isn't an image HUD can read.") | ||
val tooLarge get() = Failure("This image is too large to send, even made smaller.") | ||
} | ||
} | ||
| ||
companion object { | ||
fun make(original: ByteArray, maxSide: Int, maxBytes: Int, exif: Boolean): PreparedPhoto { | ||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } | ||
BitmapFactory.decodeByteArray(original, 0, original.size, bounds) | ||
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) throw Failure.notAnImage | ||
val read = runCatching { ExifInterface(ByteArrayInputStream(original)) }.getOrNull() | ||
val orientation = read?.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL) ?: ExifInterface.ORIENTATION_NORMAL | ||
val longest = max(bounds.outWidth, bounds.outHeight) | ||
var side = min(maxSide, max(longest, 1)) | ||
// Read at the smallest power of two over the size wanted, so a large original costs little memory. | ||
var sample = 1 | ||
while (longest / (sample * 2) >= side) sample *= 2 | ||
val decoded = BitmapFactory.decodeByteArray(original, 0, original.size, BitmapFactory.Options().apply { inSampleSize = sample }) | ||
?: throw Failure.notAnImage | ||
try { | ||
// Smaller each time the lowest quality is still too large. | ||
repeat(4) { | ||
val image = upright(decoded, side, orientation) | ||
try { | ||
for (quality in 90 downTo 30 step 10) { | ||
val out = ByteArrayOutputStream() | ||
if (!image.compress(Bitmap.CompressFormat.JPEG, quality, out)) throw Failure.notAnImage | ||
if (out.size() <= maxBytes) { | ||
return PreparedPhoto(out.toByteArray(), image.width, image.height, if (exif && read != null) ComposeExif.grain(ComposeExif.tags(read)) else null) | ||
} | ||
} | ||
} finally { | ||
if (image !== decoded) image.recycle() | ||
} | ||
side = side * 3 / 4 | ||
} | ||
} finally { | ||
decoded.recycle() | ||
} | ||
throw Failure.tooLarge | ||
} | ||
| ||
/** The image at `side` pixels on its longer side at most, turned as its EXIF orientation says. */ | ||
private fun upright(image: Bitmap, side: Int, orientation: Int): Bitmap { | ||
val scale = min(1f, side.toFloat() / max(image.width, image.height)) | ||
val matrix = Matrix() | ||
matrix.postScale(scale, scale) | ||
when (orientation) { | ||
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.postScale(-1f, 1f) | ||
ExifInterface.ORIENTATION_ROTATE_180 -> matrix.postRotate(180f) | ||
ExifInterface.ORIENTATION_FLIP_VERTICAL -> matrix.postScale(1f, -1f) | ||
ExifInterface.ORIENTATION_TRANSPOSE -> { matrix.postRotate(90f); matrix.postScale(-1f, 1f) } | ||
ExifInterface.ORIENTATION_ROTATE_90 -> matrix.postRotate(90f) | ||
ExifInterface.ORIENTATION_TRANSVERSE -> { matrix.postRotate(-90f); matrix.postScale(-1f, 1f) } | ||
ExifInterface.ORIENTATION_ROTATE_270 -> matrix.postRotate(270f) | ||
} | ||
if (scale == 1f && matrix.isIdentity) return image | ||
val w = (image.width * scale).roundToInt().coerceAtLeast(1) | ||
val h = (image.height * scale).roundToInt().coerceAtLeast(1) | ||
if (orientation <= ExifInterface.ORIENTATION_NORMAL) return Bitmap.createScaledBitmap(image, w, h, true) | ||
return Bitmap.createBitmap(image, 0, 0, image.width, image.height, matrix, true) | ||
} | ||
} | ||
} | ||
android/hudkit/src/main/java/place/hud/kit/data/Json.ktnew+147−0
android/hudkit/src/main/java/place/hud/kit/data/Result.ktnew+148−0
android/hudkit/src/main/java/place/hud/kit/embed/EmbedCard.ktnew+72−0
android/hudkit/src/main/java/place/hud/kit/embed/EmbedExternal.ktnew+165−0
android/hudkit/src/main/java/place/hud/kit/embed/EmbedImages.ktnew+108−0
android/hudkit/src/main/java/place/hud/kit/embed/EmbedRules.ktnew+103−0
android/hudkit/src/main/java/place/hud/kit/embed/QuoteCard.ktnew+99−0
android/hudkit/src/main/java/place/hud/kit/parts/ComposeFields.ktnew+643−0
643 lines changed: not loaded until asked for.
android/hudkit/src/main/java/place/hud/kit/parts/ComposeForm.ktnew+268−0
android/hudkit/src/main/java/place/hud/kit/parts/ComposeSheet.ktnew+227−0
android/hudkit/src/main/java/place/hud/kit/parts/FeedContextView.ktnew+209−0
android/hudkit/src/main/java/place/hud/kit/parts/HeaderCard.ktnew+53−0
android/hudkit/src/main/java/place/hud/kit/parts/Lightbox.ktnew+292−0
android/hudkit/src/main/java/place/hud/kit/parts/ListLayout.ktnew+135−0
android/hudkit/src/main/java/place/hud/kit/parts/ProfileCard.ktnew+82−0
android/hudkit/src/main/java/place/hud/kit/parts/RowLayout.ktnew+275−0
android/hudkit/src/main/java/place/hud/kit/parts/TextBody.ktnew+149−0
android/hudkit/src/main/java/place/hud/kit/parts/ThreadItem.ktnew+124−0
android/hudkit/src/main/java/place/hud/kit/parts/ThreadLayouts.ktnew+60−0
android/hudkit/src/main/java/place/hud/kit/support/Controls.ktnew+40−0
android/hudkit/src/main/java/place/hud/kit/support/Format.ktnew+73−0
android/hudkit/src/main/java/place/hud/kit/support/Glyphs.ktnew+119−0
android/hudkit/src/main/java/place/hud/kit/support/Picture.ktnew+85−0
android/hudkit/src/main/java/place/hud/kit/support/Space.ktnew+74−0
android/hudkit/src/main/java/place/hud/kit/support/Surface.ktnew+138−0
android/hudkit/src/main/java/place/hud/kit/tree/Acting.ktnew+653−0
653 lines changed: not loaded until asked for.
android/hudkit/src/main/java/place/hud/kit/tree/AudioPlayer.ktnew+318−0
android/hudkit/src/main/java/place/hud/kit/tree/Composing.ktnew+94−0
android/hudkit/src/main/java/place/hud/kit/tree/Diff.ktnew+230−0
android/hudkit/src/main/java/place/hud/kit/tree/Fields.ktnew+319−0
android/hudkit/src/main/java/place/hud/kit/tree/Marks.ktnew+154−0
android/hudkit/src/main/java/place/hud/kit/tree/Media.ktnew+500−0
500 lines changed: not loaded until asked for.
android/hudkit/src/main/java/place/hud/kit/tree/Playback.ktnew+673−0
673 lines changed: not loaded until asked for.
android/hudkit/src/main/java/place/hud/kit/tree/Resolved.ktnew+105−0
android/hudkit/src/main/java/place/hud/kit/tree/Structure.ktnew+268−0
android/hudkit/src/main/java/place/hud/kit/tree/TreeView.ktnew+252−0
android/hudkit/src/main/java/place/hud/kit/tree/Words.ktnew+567−0
567 lines changed: not loaded until asked for.
android/hudkit/src/main/java/place/hud/kit/view/ResultView.ktnew+106−0
android/hudkit/src/main/java/place/hud/kit/view/ViewContext.ktnew+148−0
android/hudkit/src/main/java/place/hud/kit/workspace/Theme.ktnew+87−0
android/hudkit/src/test/java/place/hud/kit/ComposeTest.ktnew+256−0
android/hudkit/src/test/java/place/hud/kit/ResultsTest.ktnew+143−0
android/hudkit/src/test/java/place/hud/kit/ThemeTest.ktnew+91−0
android/hudkit/src/test/resources/robolectric.propertiesnew+2−0
android/hudkit/build.gradle.ktsnew+76−0
android/hudkit/consumer-rules.pronew+0−0
No changes to the content.