~ knotless Search/
↑↓ move↵ open⇧↵ all results

grain.social/grain

photography-focused photo sharing platform

grain.social
1 collaborator
0
2

android: Grain on Android, drawn by HUD's Android kit

Merged chadtmiller.com asked to merge into feature/hud from grain.social/grain:next/android

Only what this pull adds. It is built on The next grain.social and grain-ios, drawn by HUD.

.knotless/workflows/android.ymlnew+59−0
@@ -0,0 +1,59 @@
# The Android app, android/: its debug build, with HUD's Android kit from
# the copy in vendor/hud, as `just android-build` makes it, so a pull moving
# that copy (`just vendor-hud <commit>`) is checked here too. The SDK setup,
# the image and the memory settings are grain-android's own workflows' (its
# .knotless/workflows), which run on these runners:
#
# - x86_64 alone: AGP publishes no linux-arm64 AAPT2, so on an arm64 runner
# the build dies in `processDebugResources`.
# - A run has 3 GB, and android/gradle.properties asks for a 4 GB heap, so
# Gradle gets less here and compiles Kotlin in its own process.
# - The SDK (cmdline-tools pinned, so an SDK moving under the pipeline turns
# no unrelated push red) and Gradle's caches are kept between runs.
#
# The debug build is signed with the SDK's debug key, so it needs no
# keystore and no secret. The release build is not here: R8 is slow.
image: eclipse-temurin:17-jdk
runners: [runner.knotless.dev]
on:
push: { refs: [refs/heads/main, refs/heads/feature/*] }
pull:
base: [refs/heads/main, refs/heads/feature/*]
paths:
- android/**
- vendor/hud/android/**
- next/grain.social.json
- .knotless/workflows/android.yml
cache: [/opt/android-sdk, /root/.gradle/caches, /root/.gradle/wrapper]
env:
CMDLINE_TOOLS: commandlinetools-linux-16111833_latest.zip
# Both track android/app/build.gradle.kts and HUD's hudkit: compileSdk 37
# is packaged as `android-37.0` under the newer SDK versioning.
ANDROID_PLATFORM: platforms;android-37.0
ANDROID_BUILD_TOOLS: build-tools;36.0.0
ANDROID_HOME: /opt/android-sdk
GRADLE_FLAGS: >-
--no-daemon
-Dorg.gradle.jvmargs=-Xmx1536m
-Pkotlin.compiler.execution.strategy=in-process
-Dorg.gradle.workers.max=2
steps:
- name: android sdk
run: |
apt-get update -qq
apt-get install -y -qq git unzip curl >/dev/null
have="$CMDLINE_TOOLS $ANDROID_PLATFORM $ANDROID_BUILD_TOOLS"
[ "$(cat "$ANDROID_HOME/.installed" 2>/dev/null)" = "$have" ] && exit 0
find "$ANDROID_HOME" -mindepth 1 -delete 2>/dev/null || true
mkdir -p "$ANDROID_HOME/cmdline-tools"
curl -fsSL -o /tmp/cmdline-tools.zip "https://dl.google.com/android/repository/$CMDLINE_TOOLS"
unzip -q /tmp/cmdline-tools.zip -d "$ANDROID_HOME/cmdline-tools"
mv "$ANDROID_HOME/cmdline-tools/cmdline-tools" "$ANDROID_HOME/cmdline-tools/latest"
sdk="$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager"
# sdkmanager reads yes once per licence and closes the pipe.
yes 2>/dev/null | "$sdk" --licenses >/dev/null 2>&1 || true
"$sdk" "platform-tools" "$ANDROID_PLATFORM" "$ANDROID_BUILD_TOOLS" >/dev/null
echo "$have" > "$ANDROID_HOME/.installed"
- name: assemble debug
timeout: 30
run: cd android && ./gradlew $GRADLE_FLAGS :app:assembleDebug
android/app/src/debug/res/xml/network_security_config.xmlnew+18−0
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Debug: a HUD server on this machine (`hud serve`, plain http) as the
emulator reaches it, and HUD's harness in front of its own PDS
(https at hud.harness.internal), whose authority (HUD's
.local/tls/ca.pem) is installed as a user certificate, or put in the
system's store of a rooted emulator. -->
<network-security-config>
<base-config>
<trust-anchors>
<certificates src="system" />
<certificates src="user" />
</trust-anchors>
</base-config>
<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/social/grain/GrainConfig.ktnew+136−0
@@ -0,0 +1,136 @@
package social.grain
import android.content.Context
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontVariation
import androidx.compose.ui.text.font.FontWeight
import kotlinx.serialization.json.JsonElement
import place.hud.kit.data.Call
import place.hud.kit.data.HudJson
import place.hud.kit.data.PushPlan
import place.hud.kit.data.Route
import place.hud.kit.data.SignInPlan
import place.hud.kit.data.TabFirst
import place.hud.kit.data.get
import place.hud.kit.data.items
import place.hud.kit.data.obj
import place.hud.kit.data.str
import place.hud.kit.data.string
import place.hud.kit.support.Glyphs
import place.hud.kit.support.Typefaces
import place.hud.kit.workspace.Palette
import place.hud.kit.workspace.Theme
/**
* The app as next/grain.social.json says it is, as the web shell and the iOS
* app read it: its name, its tabs, each a tool call drawn as the root of its
* own stack, and its look, a palette for light and one for dark. Signed out,
* a tab draws its `guest` call instead: another call, or "call" for the same
* one; a tab without one asks to sign in. Signed in, a tab with `first`
* draws the root the account's data chooses (Home, the first feed pinned:
* `Shell.chosenRoot`).
*/
class GrainConfig(json: JsonElement) {
data class Tab(
val label: String,
val icon: String,
/** The word its root screen is titled with, drawn as the app's logo, in place of `label`. */
val wordmark: String?,
val call: Call,
/** The call signed out; null where it needs an account. */
val guest: Call?,
/** Its URL path at its root, where it has one of its own (Home's `/`). */
val path: String?,
/** Where its root is chosen from the account's data, signed in. */
val first: TabFirst?,
/** How many are new on it, signed in (Notifications' unread count). */
val badge: Badge?,
) {
/** The call it draws, signed in or not, before `first` chooses; null where it needs an account. */
fun root(signedIn: Boolean): Call? = if (signedIn) call else guest
/**
* Whether its root screen has a title: not one's own profile (an
* app's view of an actor, `describe_app`), which heads itself with
* its avatar and name.
*/
val titled: Boolean get() = call.name != "describe_app"
/** Its icon, as the web draws it (HUD's glyphs: feed, compass, notification, people). */
val glyph: ImageVector? get() = Glyphs.vector(icon)
}
/** A tab's count: a call, and the path to the number in its answer (in a query's `response`). */
data class Badge(val call: Call, val count: String)
/** Where the account chose light or dark, signed in: a call, the path to the choice in its answer, and the procedure after which it is asked again. */
data class Scheme(val call: Call, val at: String, val after: String?)
/** What a row of the accounts shows (`frame.account.picture`): the call each account's own profile is read with, and its picture's, name's and handle's paths in the answer. */
data class AccountPicture(val call: Call, val at: String?, val name: String?, val handle: String?)
val domain: String = json.str("domain") ?: "grain.social"
val name: String = json.str("name") ?: domain
val tabs: List<Tab> = json.items("tabs").mapNotNull { tab ->
val label = tab.str("label") ?: return@mapNotNull null
val call = call(tab["call"]) ?: return@mapNotNull null
val guest = if (tab["guest"].string == "call") call else call(tab["guest"])
val badge = call(tab["badge"]["call"])?.let { Badge(it, tab["badge"].str("count") ?: "count") }
Tab(label, tab.str("icon") ?: "", tab.str("wordmark"), call, guest, tab.str("path"), TabFirst.of(tab["first"]), badge)
}
val light: Theme? = theme(json["look"]["light"], dark = false)
val dark: Theme? = theme(json["look"]["dark"], dark = true)
val scheme: Scheme? = call(json["scheme"]["call"])?.let { call ->
json["scheme"].str("at")?.let { Scheme(call, it, json["scheme"].str("after")) }
}
/** Its screens as URL paths: what a tapped notification or a grain.social link opens. */
val routes: List<Route> = Route.all(json)
val push: PushPlan? = PushPlan.of(json["push"])
val signIn: SignInPlan? = SignInPlan.of(json)
val accountPicture: AccountPicture? = json["frame"]["account"]["picture"].let { picture ->
call(picture["call"])?.let { AccountPicture(it, picture.str("at"), picture.str("name"), picture.str("handle")) }
}
/** The wordmark Home is titled with, else the app's name. */
val wordmark: String get() = tabs.firstNotNullOfOrNull { it.wordmark } ?: name
/** The theme for a scheme. */
fun theme(dark: Boolean): Theme? = if (dark) this.dark ?: light else light ?: this.dark
private fun theme(palette: JsonElement?, dark: Boolean): Theme? {
val colors = palette.obj ?: return null
val scheme = if (dark) "dark" else "light"
return Theme(key = "grain-$scheme", uri = null, creator = null, name = name, dark = dark, palette = Palette(colors))
}
companion object {
/** The one bundled with the app, in its assets. */
fun bundled(context: Context): GrainConfig =
GrainConfig(HudJson.parseToJsonElement(context.assets.open("grain.social.json").bufferedReader().use { it.readText() }))
/** A `{name, args}`. */
private fun call(json: JsonElement?): Call? = Call.of(json)
/**
* Grain's faces, as the web shell sets its (`look.fonts`): Plus
* Jakarta Sans for text, Syne at weight 800 for titles, both
* Google Fonts' variable TTFs (OFL), as ios/Grain/Fonts has them.
*/
val typefaces: Typefaces by lazy {
fun sans(weight: Int) = Font(
R.font.plus_jakarta_sans, FontWeight(weight),
variationSettings = FontVariation.Settings(FontVariation.weight(weight)),
)
Typefaces(
body = FontFamily(sans(400), sans(500), sans(600), sans(700)),
display = display,
)
}
/** Syne ExtraBold: the variable Syne at weight 800. */
val display: FontFamily by lazy {
FontFamily(Font(R.font.syne, FontWeight.ExtraBold, variationSettings = FontVariation.Settings(FontVariation.weight(800))))
}
}
}
android/app/src/main/java/social/grain/Level.ktnew+265−0
@@ -0,0 +1,265 @@
package social.grain
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.serialization.json.JsonObject
import place.hud.kit.data.Call
import place.hud.kit.data.Drawn
import place.hud.kit.data.HudClient
import place.hud.kit.data.HudError
import place.hud.kit.data.LastTree
import place.hud.kit.data.Skeleton
import place.hud.kit.data.Viewer
import place.hud.kit.data.get
import place.hud.kit.tree.barTitle
import place.hud.kit.tree.liftBar
import place.hud.kit.view.ViewContext
import java.util.concurrent.atomic.AtomicLong
/**
* One level of a tab's stack, as the iOS app's: the call it draws (a tab
* chosen in it swaps another in), what it answered (grown by each page
* more), or until then its tree as the account last drew it (`LastTree`),
* and whether it needed an account it was not made as. Its view context
* lives as long as it does, so what a person did to its parts (a like, a
* text opened in full) stays as they go back to it. Main thread only.
*/
@Stable
class Level(call: Call) {
/** Who it is among the levels, as its screen's saved state is kept by. */
val id: String = "level-${ids.incrementAndGet()}"
var call: Call by mutableStateOf(call)
private set
/** What its call answered; while a swapped-in call is on its way, what the call before answered (`drawnCall`). */
var drawn: Drawn? by mutableStateOf(null)
private set
/** The call whose answer is drawn. */
var drawnCall: Call? = null
private set
/** How many times what is drawn changed: what a screen wires its context afresh by. */
var answers: Int by mutableIntStateOf(0)
private set
/** Its call has been out longer than `Skeleton.DELAY_MS`. */
var slow: Boolean by mutableStateOf(false)
private set
/** The tree it draws is being read afresh: a tree as last drawn, or a level shown again. */
var refreshing: Boolean by mutableStateOf(false)
private set
/** Why reading what it draws afresh failed the last time, what is drawn left as it was; null once it answers. */
var refreshError: String? by mutableStateOf(null)
private set
var loadingMore: Boolean by mutableStateOf(false)
private set
var moreError: String? by mutableStateOf(null)
private set
/** The account the latest result was made for; null for no one. */
var viewer: Viewer? by mutableStateOf(null)
private set
var needsSignIn: Boolean by mutableStateOf(false)
private set
/** What its tree is drawn with: wired afresh with each answer. */
val context = ViewContext()
/** The posts this level has told its feed were seen. */
val told = HashSet<String>()
/** How many items the first page of what is drawn holds: those past them came a page more at a time. */
private var firstPage = 0
/** The calls a load is out for, each with the loads of it asked for meanwhile, which wait for its answer. */
private val loading = HashMap<Call, MutableList<CompletableDeferred<Unit>>>()
/** The call a tab's root draws being chosen still, from the account's data (Home's, the first feed pinned): its loads wait for it. */
var choosing: Deferred<Call>? = null
private fun draw(answer: Drawn, of: Call?) {
drawnCall = of
drawn = answer
answers += 1
}
/** Whether it draws the answer of a call before its own, while that is on its way. */
val swapping: Boolean get() = drawn != null && drawnCall != call
/** Draw `call` in its place (a tab chosen in it), once `load` brings its answer: until then, what it drew stays. */
fun swap(to: Call) {
call = to
slow = false
refreshing = false
refreshError = null
moreError = null
}
/** Draw its call's tree as `account` (null, no one) last drew it, where one is kept, until its call answers afresh. */
fun recall(account: String?) {
val kept = LastTree.recall(call, account) ?: return
val tree = Drawn.Tree(kept.ui)
viewer = kept.viewer
needsSignIn = false
firstPage = tree.pageCount ?: 0
draw(tree, call)
}
/** Its screen's title, as its tree's lifted `Bar` names it; null while it loads, or where its view names none. */
val title: String?
get() {
val ui = (drawn as? Drawn.Tree)?.ui ?: return null
val root = ui["root"] ?: return null
return liftBar(root).second?.let(::barTitle)
}
/**
* Call it afresh, its answer drawn only while it still draws that call
* (no tab chosen since), its tree kept as its screen's last
* (`LastTree`) and its shape as its skeleton; past `Skeleton.DELAY_MS`
* it is `slow`. Where none of its own is drawn, its tree as last drawn
* is, where one is kept. A tree of its call drawn is `refreshing` until
* the answer comes, and stays where the call fails. A load already out
* for its call is waited for. A tab's root whose call is being chosen
* waits for it first and draws what it chose.
*/
suspend fun load(client: HudClient) {
choosing?.let { choice ->
val chosen = choice.await()
choosing = null
if (chosen != call) swap(chosen)
}
val asked = call
loading[asked]?.let { waiting ->
val done = CompletableDeferred<Unit>()
waiting += done
done.await()
return
}
val account = client.session?.did
if (drawnCall != asked) recall(account)
val revalidating = drawnCall == asked && drawn is Drawn.Tree
loading[asked] = mutableListOf()
refreshing = revalidating
coroutineScope {
val timer = launch {
delay(Skeleton.DELAY_MS)
if (call == asked) slow = true
}
try {
val sent = System.currentTimeMillis()
val result = client.call(asked)
if (call != asked) return@coroutineScope
val fresh = Drawn.of(result)
if (revalidating && fresh is Drawn.Error) {
refreshError = fresh.message
return@coroutineScope
}
viewer = if (result.isError) null else result.viewer
needsSignIn = false
refreshError = null
show(fresh, asked, account, sent)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
if (call != asked) return@coroutineScope
needsSignIn = e is HudError.SignIn
val message = e.message ?: "Couldn't reach the server."
if (revalidating && !needsSignIn) {
refreshError = message
return@coroutineScope
}
if (needsSignIn) viewer = null
show(Drawn.Error(message), asked, account, System.currentTimeMillis())
} finally {
timer.cancel()
// Those waiting for it go on, whatever call it draws by now.
loading.remove(asked)?.forEach { it.complete(Unit) }
if (call == asked) {
slow = false
refreshing = false
}
}
}
}
/** Read it again, its answer drawn in place once it came; a failure thrown in the server's words, what is drawn left as it was. */
suspend fun reload(client: HudClient) {
val asked = call
val sent = System.currentTimeMillis()
val result = client.call(asked)
val fresh = Drawn.of(result)
if (fresh is Drawn.Error) throw HudError.Tool(fresh.message)
if (call != asked) return
viewer = result.viewer
needsSignIn = false
refreshError = null
show(fresh, asked, client.session?.did, sent)
}
/**
* Draw `call`'s answer as `account` asked it (at `sent`). A tree is kept
* as its screen's last, and its shape as its skeleton. In place of a
* tree of the same call, the pages loaded past its first stay after the
* fresh first page, so the list stays as long and where it was scrolled.
*/
private fun show(answer: Drawn, call: Call, account: String?, sent: Long) {
var shown = answer
if (answer is Drawn.Tree) {
Skeleton.remember(call, answer.ui)
LastTree.remember(call, account, answer.ui, viewer, sent)
val first = answer.pageCount ?: 0
val before = drawn
if (drawnCall == call && before != null) shown = before.refreshed(answer, firstPage)
firstPage = first
}
draw(shown, call)
}
/** A page more, its tree's `next`; dropped where another call's answer is drawn by the time it comes. */
suspend fun loadMore(client: HudClient) {
val before = drawn ?: return
val next = before.nextPage ?: return
if (loadingMore) return
val of = drawnCall
loadingMore = true
moreError = null
try {
val page = Drawn.of(client.call(next))
if (drawnCall != of) return
val grown = drawn?.appending(page)
when {
page is Drawn.Error -> moreError = page.message
grown != null -> draw(grown, of)
else -> moreError = "The next page is not of this list."
}
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
if (drawnCall == of) moreError = e.message ?: "Couldn't load more."
} finally {
loadingMore = false
}
}
/** Its tree's `ui`, where a tree is drawn. */
val ui: JsonObject? get() = (drawn as? Drawn.Tree)?.ui
private companion object {
val ids = AtomicLong()
}
}
android/app/src/main/java/social/grain/LevelScreen.ktnew+435−0
435 lines changed: not loaded until asked for.
android/app/src/main/java/social/grain/MainActivity.ktnew+126−0
@@ -0,0 +1,126 @@
package social.grain
import android.Manifest
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.launch
import place.hud.kit.data.Skeleton
/**
* Grain: next/grain.social.json's tabs along the foot, each a stack of
* HUD's server-resolved views drawn by HUD's Android kit, its tool calls
* made on the HUD server's /mcp, signed in or as a guest. A debug build
* started with `--es server <url>` calls that server from then on (an empty
* one goes back to the build's). A grain.social link (or grain://profile/…)
* opens as its route.
*/
class MainActivity : ComponentActivity() {
private lateinit var shell: Shell
private lateinit var gate: UpdateGate
/** The answer push's leave to notify waits for, while the person is asked. */
private var answer: CompletableDeferred<Boolean>? = null
private val notify = registerForActivityResult(ActivityResultContracts.RequestPermission()) { given ->
answer?.complete(given)
answer = null
}
/** Asks for `POST_NOTIFICATIONS` over this activity, for push (`FcmDevice`). */
private val ask: suspend () -> Boolean = {
val waiting = CompletableDeferred<Boolean>().also { answer = it }
notify.launch(Manifest.permission.POST_NOTIFICATIONS)
waiting.await()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
Grain.device(this).ask = ask
shell = Grain.shell(this)
gate = Grain.gate(this)
shell.attach(this)
if (savedInstanceState == null) handle(intent)
setContent {
val dark = shell.preferredDark ?: isSystemInDarkTheme()
val view = LocalView.current
// The bars' icons legible on the scheme drawn, which the account may choose apart from the device's.
SideEffect {
WindowCompat.getInsetsController(window, view).apply {
isAppearanceLightStatusBars = !dark && (shell.stories == null || shell.stories?.alone == true) && !shell.askingSignIn
isAppearanceLightNavigationBars = !dark
}
}
GrainApp(shell, gate)
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
handle(intent)
}
override fun onResume() {
super.onResume()
shell.attach(this)
lifecycleScope.launch { shell.refreshUnread() }
lifecycleScope.launch { gate.check() }
}
override fun onDestroy() {
super.onDestroy()
shell.attach(null)
Grain.device(this).let { if (it.ask === ask) it.ask = null }
answer?.complete(false)
}
/** A server named (a debug build's only: `Shell.useServer`), a tapped notification's fields (`GrainMessagingService`), and a link to open as its route. */
private fun handle(intent: Intent) {
if (BuildConfig.DEBUG) intent.getStringExtra("server")?.let(shell::useServer)
intent.getBundleExtra(GrainMessagingService.EXTRA_PUSH)?.let { fields ->
shell.push?.tapped(fields.keySet().mapNotNull { key -> fields.getString(key)?.let { key to it } }.toMap())
}
val uri = intent.data ?: return
if (intent.action != Intent.ACTION_VIEW) return
path(uri)?.let(shell::openPath)
}
/** The path a link opens: a grain.social page's, or grain://profile/…'s as /profile/…. */
private fun path(uri: Uri): String? {
val query = uri.encodedQuery?.let { "?$it" } ?: ""
return when {
uri.scheme == "https" && (uri.host == shell.config.domain || uri.host == "www.${shell.config.domain}") -> (uri.encodedPath ?: "/") + query
uri.scheme == "grain" && uri.host == "profile" -> "/profile" + (uri.encodedPath ?: "") + query
else -> null
}
}
}
/** The app's one shell and update gate, for as long as its process lives, whatever activity is on show. */
object Grain {
private var shell: Shell? = null
private var gate: UpdateGate? = null
private var device: FcmDevice? = null
fun shell(context: Context): Shell = shell ?: run {
val app = context.applicationContext
Skeleton.use(app.getSharedPreferences("hud-skeletons", Context.MODE_PRIVATE))
Shell(app, GrainConfig.bundled(app), device(app)).also { shell = it }
}
fun gate(context: Context): UpdateGate = gate ?: UpdateGate(context).also { gate = it }
/** What push asks of the device: leave to notify, through the activity on show, and FCM's token. */
fun device(context: Context): FcmDevice = device ?: FcmDevice(context).also { device = it }
}
android/app/src/main/java/social/grain/Push.ktnew+133−0
@@ -0,0 +1,133 @@
package social.grain
import android.Manifest
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import com.google.firebase.FirebaseApp
import com.google.firebase.messaging.FirebaseMessaging
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import place.hud.kit.data.Push
import kotlin.coroutines.resume
/**
* What HUD's `Push` asks of this device: leave to notify, asked once
* (Android 13 on) through the activity on show (`ask`, set by
* `MainActivity`), and FCM's token, where the build has a Firebase config
* (a release built with `google-services.json`); none, no token.
*/
class FcmDevice(context: Context) : Push.Device {
private val app = context.applicationContext
private val prefs = app.getSharedPreferences("grain", Context.MODE_PRIVATE)
/** Asks the person for `POST_NOTIFICATIONS` and answers whether they gave it; null while no activity is on show. */
var ask: (suspend () -> Boolean)? = null
override suspend fun allowed(): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return true
if (ContextCompat.checkSelfPermission(app, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) return true
if (prefs.getBoolean(ASKED, false)) return false
val ask = ask ?: return false
prefs.edit().putBoolean(ASKED, true).apply()
return ask()
}
override suspend fun token(): String? {
if (FirebaseApp.getApps(app).isEmpty()) {
Log.i(TAG, "No Firebase config in this build: no push")
return null
}
return suspendCancellableCoroutine { done ->
FirebaseMessaging.getInstance().token
.addOnSuccessListener { done.resume(it) }
.addOnFailureListener {
Log.w(TAG, "FCM gave no token: ${it.message}")
done.resume(null)
}
}
}
companion object {
private const val TAG = "push"
private const val ASKED = "push.asked"
}
}
/**
* FCM's messages for this device: grain-serve's are data only, every field
* a string, `title` and `body` beside the notification's own (`type`, and a
* `uri` or `did`), drawn here as a notification whose tap hands those
* fields to `MainActivity` (`EXTRA_PUSH`), which opens the path the app
* file's `push.open` maps them to. A token FCM rotates is registered as the
* account signed in.
*/
class GrainMessagingService : FirebaseMessagingService() {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
override fun onNewToken(token: String) {
val push = Grain.shell(this).push ?: return
scope.launch { push.registered(token) }
}
override fun onMessageReceived(message: RemoteMessage) {
val data = message.data
val title = message.notification?.title ?: data["title"] ?: return
val body = message.notification?.body ?: data["body"].orEmpty()
ensureChannel(this)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
) return
val fields = Bundle().apply { for ((key, value) in data) if (key != "title" && key != "body") putString(key, value) }
// One notification, and one tap, per subject: two about different galleries don't share a PendingIntent.
val id = (data["uri"] ?: data["did"] ?: title).hashCode()
val tap = PendingIntent.getActivity(
this,
id,
Intent(this, MainActivity::class.java).putExtra(EXTRA_PUSH, fields),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
NotificationManagerCompat.from(this).notify(id, notification(this, title, body, tap))
}
companion object {
/** The extra a tapped notification's fields come to `MainActivity` in, a Bundle of strings. */
const val EXTRA_PUSH = "social.grain.push"
const val CHANNEL_ID = "social_activity"
/** grain-android's notification: its glyph tinted, the text whole when expanded, gone once tapped. */
fun notification(context: Context, title: String, body: String, tap: PendingIntent): Notification =
NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setColor(ContextCompat.getColor(context, R.color.notification_accent))
.setContentTitle(title)
.setContentText(body)
.setStyle(NotificationCompat.BigTextStyle().bigText(body))
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(tap)
.build()
/** grain-android's channel, made where it is not (the one FCM posts to as well, the manifest's default). */
fun ensureChannel(context: Context) {
val channel = NotificationChannel(CHANNEL_ID, context.getString(R.string.notification_channel_social), NotificationManager.IMPORTANCE_DEFAULT)
.apply { description = context.getString(R.string.notification_channel_social_description) }
context.getSystemService(NotificationManager::class.java)?.createNotificationChannel(channel)
}
}
}
android/app/src/main/java/social/grain/Shell.ktnew+658−0
658 lines changed: not loaded until asked for.
android/app/src/main/java/social/grain/ShellScreen.ktnew+220−0
@@ -0,0 +1,220 @@
package social.grain
import androidx.activity.compose.BackHandler
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.background
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material3.Badge
import androidx.compose.material3.BadgedBox
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.key
import androidx.compose.runtime.saveable.SaveableStateHolder
import androidx.compose.runtime.saveable.rememberSaveableStateHolder
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
import place.hud.kit.support.HudColors
import place.hud.kit.support.HudThemed
import place.hud.kit.tree.LocalStackRoot
/**
* The app: in the scheme the account chose (light or dark), else the
* device's, in Grain's look and faces; the tabs drawn anew each time they
* start afresh (another account), as the web loads its page anew. Below
* the minimum version grain.social asks for, only "Update Grain".
*/
@Composable
fun GrainApp(shell: Shell, gate: UpdateGate) {
val dark = shell.preferredDark ?: isSystemInDarkTheme()
HudThemed(shell.config.theme(dark), GrainConfig.typefaces) {
if (gate.blocked != null) {
UpdateScreen(gate)
} else {
key(shell.starts) { ShellScreen(shell) }
}
}
}
/**
* The tab bar, each tab its own stack; over them the stories, a sheet, and
* signing in. The notifications tab is badged with how many came since
* they were last seen, asked at launch, as the app comes to the front
* (`MainActivity`), and every minute.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ShellScreen(shell: Shell) {
val saved = rememberSaveableStateHolder()
LaunchedEffect(Unit) {
while (true) {
delay(60_000)
shell.refreshUnread()
}
}
Box(Modifier.fillMaxSize().background(HudColors.tileSurface)) {
Scaffold(
bottomBar = { TabBar(shell) },
containerColor = HudColors.tileSurface,
contentWindowInsets = WindowInsets(0.dp),
) { padding ->
Box(Modifier.padding(padding)) {
val tab = shell.selected
key(tab) { TabStack(shell, tab, saved) }
}
}
BackHandler(enabled = shell.paths[shell.selected].isNotEmpty() && shell.stories == null && !shell.askingSignIn) { shell.back() }
shell.stories?.let { stories -> key(stories) { StoryPager(stories, shell) } }
if (shell.askingSignIn) SignInScreen(shell)
}
shell.sheet?.let { sheet -> key(sheet) { SheetScreen(shell, sheet) } }
}
/** The tabs along the foot, as next/grain.social.json names them, each its icon as the web draws it. */
@Composable
private fun TabBar(shell: Shell) {
NavigationBar(containerColor = HudColors.tileSurface) {
shell.config.tabs.forEachIndexed { i, tab ->
NavigationBarItem(
selected = i == shell.selected,
onClick = { shell.choose(i) },
icon = {
BadgedBox(badge = {
if (i == shell.notificationsTab && shell.unread > 0) Badge { Text(if (shell.unread > 99) "99+" else "${shell.unread}") }
}) {
val glyph = tab.glyph
if (glyph != null) Icon(glyph, contentDescription = tab.label, Modifier.size(24.dp)) else Icon(Icons.Filled.Home, tab.label)
}
},
label = { Text(tab.label) },
colors = NavigationBarItemDefaults.colors(
selectedIconColor = HudColors.accent,
selectedTextColor = HudColors.accent,
indicatorColor = HudColors.accentSoft,
unselectedIconColor = HudColors.muted,
unselectedTextColor = HudColors.muted,
),
)
}
}
}
/**
* One tab's stack: its root, titled by the tab (a wordmark, Home's "grain",
* in the display face; one's own profile heads itself, untitled), and what
* opened over it, each titled by its view's `Bar`, with a way back. Each
* level's saved state (where it was scrolled) is kept while it is on the
* stack, so going back finds it where it was.
*/
@Composable
private fun TabStack(shell: Shell, tab: Int, saved: SaveableStateHolder) {
val plan = shell.config.tabs[tab]
val path = shell.paths[tab]
val root = shell.roots[tab]
val top = path.lastOrNull() ?: root
fun depth(level: Level?): Int = if (level == null || level === root) 0 else path.indexOf(level).let { if (it < 0) Int.MAX_VALUE else it + 1 }
AnimatedContent(
targetState = top,
transitionSpec = {
if (depth(targetState) > depth(initialState)) {
slideInHorizontally { it } togetherWith slideOutHorizontally { -it / 4 } + fadeOut()
} else {
slideInHorizontally { -it / 4 } + fadeIn() togetherWith slideOutHorizontally { it }
}
},
label = "stack",
) { level ->
saved.SaveableStateProvider(level?.id ?: "sign-in-$tab") {
when {
level == null -> SignInTab(shell, plan)
level === root -> LevelScreen(
level, shell, Wiring.tab(shell, level, tab),
title = if (plan.titled) plan.wordmark ?: plan.label else null, large = true, back = null,
)
// Pushed over the tab's root: no feeds strip, whose tabs swap the screen in place.
else -> CompositionLocalProvider(LocalStackRoot provides false) {
LevelScreen(level, shell, Wiring.tab(shell, level, tab), title = level.title, large = false, back = { shell.back() })
}
}
}
}
}
/** A tab that needs an account, signed out. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun SignInTab(shell: Shell, plan: GrainConfig.Tab) {
Column(Modifier.fillMaxSize().background(HudColors.tileSurface)) {
TopAppBar(
title = { Text(plan.label, style = TextStyle(fontFamily = GrainConfig.display, fontSize = 30.sp)) },
colors = TopAppBarDefaults.topAppBarColors(containerColor = HudColors.tileSurface, titleContentColor = HudColors.text),
)
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
SignInAsk(shell, "Sign in to see your ${plan.label.lowercase()}")
}
}
}
/**
* A call shown as a sheet over what is open, as Grain's story comments:
* full height, in the app's look (over the stories, dark); what opens from
* it opens on the tab.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun SheetScreen(shell: Shell, sheet: SheetLevel) {
val state = rememberModalBottomSheetState(skipPartiallyExpanded = true)
val theme = if (sheet.overStories) shell.config.dark else shell.config.theme(shell.preferredDark ?: isSystemInDarkTheme())
HudThemed(theme, GrainConfig.typefaces) {
ModalBottomSheet(
onDismissRequest = { shell.sheet = null },
sheetState = state,
containerColor = HudColors.tileSurface,
) {
// Over a tab, not a tab's root: no feeds strip, whose tabs swap the screen in place.
CompositionLocalProvider(LocalStackRoot provides false) {
val level = sheet.level
val shown = rememberShown(level, shell, Wiring.sheet(shell, level, sheet.tab))
Column(Modifier.fillMaxSize()) {
level.title?.let { title ->
Text(
title, style = TextStyle(fontFamily = GrainConfig.display, fontSize = 18.sp), color = HudColors.text,
modifier = Modifier.padding(start = 16.dp, bottom = 8.dp),
)
}
LevelBody(level, shell, shown, Modifier.weight(1f))
}
}
}
}
}
android/app/src/main/java/social/grain/SignInScreen.ktnew+292−0
@@ -0,0 +1,292 @@
package social.grain
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
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.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.platform.UriHandler
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil3.compose.AsyncImage
import kotlinx.coroutines.delay
import place.hud.kit.data.FoundActor
import place.hud.kit.data.SignInPlan
/**
* Signing in, as grain-android's and the iOS app's sign-in, from what the
* app file's `signIn` says (HUD's `SignInPlan`): over Grain's photo,
* darkened, its wordmark, the plan's heading and line, the handle field
* with the accounts its typeahead finds for what is typed (200 ms after
* typing stops; a tap picks one and signs in), Sign in, Create one where
* the plan offers it, and its legal line, whose links open in a Custom Tab.
* Signing in goes through the HUD server's OAuth in a Custom Tab; what went
* wrong shows in red. Without a plan: "Sign in to Grain", and no
* suggestions.
*/
@Composable
fun SignInScreen(shell: Shell) {
val plan = shell.config.signIn ?: SignInPlan(title = "Sign in to ${shell.config.name}", site = "https://${shell.config.domain}")
var handle by remember { mutableStateOf("") }
var picked by remember { mutableStateOf<String?>(null) }
var suggestions by remember { mutableStateOf<List<FoundActor>>(emptyList()) }
var searching by remember { mutableStateOf(false) }
val focus = remember { FocusRequester() }
val keyboard = LocalSoftwareKeyboardController.current
val name = handle.trim()
val ready = name.isNotEmpty() && !shell.signingIn
BackHandler { shell.askingSignIn = false }
LaunchedEffect(Unit) { focus.requestFocus() }
// Asks the typeahead 200 ms after typing stops; a lookup overtaken by more typing is let go.
LaunchedEffect(handle) {
val typeahead = plan.typeahead
if (typeahead == null || handle == picked || typeahead.request(handle) == null) {
searching = false
suggestions = emptyList()
return@LaunchedEffect
}
searching = true
delay(200)
suggestions = typeahead.search(handle)
searching = false
}
fun go() {
if (!ready) return
keyboard?.hide()
suggestions = emptyList()
shell.signIn(name)
}
val links = remember(shell) { object : UriHandler { override fun openUri(uri: String) = shell.browse(uri) } }
CompositionLocalProvider(LocalUriHandler provides links) {
Box(Modifier.fillMaxSize().background(Color.Black).clickable(enabled = false) {}) {
Image(
painterResource(R.drawable.login_bg), contentDescription = null,
modifier = Modifier.fillMaxSize(), contentScale = ContentScale.Crop,
)
Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.4f)))
Column(
Modifier.fillMaxSize().systemBarsPadding().imePadding().verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Row(Modifier.fillMaxWidth()) {
TextButton(onClick = { shell.askingSignIn = false }) { Text("Cancel", color = Color.White) }
}
Spacer(Modifier.height(if (suggestions.isEmpty()) 40.dp else 12.dp))
Column(Modifier.widthIn(max = 480.dp).padding(horizontal = 24.dp), horizontalAlignment = Alignment.CenterHorizontally) {
Text(shell.config.wordmark, style = TextStyle(fontFamily = GrainConfig.display, fontSize = 44.sp), color = Color.White)
Spacer(Modifier.height(if (suggestions.isEmpty()) 48.dp else 20.dp))
if (suggestions.isEmpty()) {
Text(plan.title, color = Color.White, fontSize = 20.sp, fontWeight = FontWeight.SemiBold, textAlign = TextAlign.Center)
plan.text?.let {
Spacer(Modifier.height(6.dp))
Text(plan.linked(it), style = TextStyle(color = Color.White.copy(alpha = 0.7f), fontSize = 13.sp, textAlign = TextAlign.Center))
}
Spacer(Modifier.height(24.dp))
}
Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
HandleField(handle, plan.placeholder ?: "alice.bsky.social", searching, focus, onChange = { handle = it }, onGo = { go() })
if (suggestions.isNotEmpty()) {
Suggestions(suggestions) { actor ->
picked = actor.handle
handle = actor.handle
keyboard?.hide()
suggestions = emptyList()
shell.signIn(actor.handle)
}
}
WhiteButton(if (shell.signingIn) null else "Sign in", enabled = ready, dim = name.isEmpty(), onClick = { go() })
plan.create?.let { create ->
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
create.text?.let { Text(it, color = Color.White.copy(alpha = 0.6f), fontSize = 13.sp) }
GlassButton(create.label, enabled = !shell.signingIn) {
keyboard?.hide()
shell.signIn(create = true)
}
}
}
plan.legal?.let {
Text(plan.linked(it), style = TextStyle(color = Color.White.copy(alpha = 0.5f), fontSize = 11.sp, textAlign = TextAlign.Center))
}
}
shell.signInError?.let {
Spacer(Modifier.height(16.dp))
Text(it, color = Color(0xFFFF6B6B), fontSize = 12.sp, textAlign = TextAlign.Center)
}
Spacer(Modifier.height(40.dp))
}
}
}
}
}
/** The handle field: an @, what is typed, and a spinner while the typeahead looks. */
@Composable
private fun HandleField(value: String, placeholder: String, searching: Boolean, focus: FocusRequester, onChange: (String) -> Unit, onGo: () -> Unit) {
val shape = RoundedCornerShape(12.dp)
Row(
Modifier
.fillMaxWidth()
.background(Color.White.copy(alpha = 0.15f), shape)
.border(1.dp, Color.White.copy(alpha = 0.25f), shape)
.padding(horizontal = 16.dp, vertical = 14.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text("@", color = Color.White.copy(alpha = 0.5f), fontWeight = FontWeight.Medium)
Spacer(Modifier.size(10.dp))
Box(Modifier.weight(1f)) {
if (value.isEmpty()) Text(placeholder, color = Color.White.copy(alpha = 0.5f))
BasicTextField(
value, onChange,
modifier = Modifier.fillMaxWidth().focusRequester(focus).semantics { contentDescription = "Your handle" },
singleLine = true,
textStyle = TextStyle(color = Color.White, fontSize = 16.sp),
cursorBrush = SolidColor(Color.White),
keyboardOptions = KeyboardOptions(
capitalization = KeyboardCapitalization.None, autoCorrectEnabled = false,
keyboardType = KeyboardType.Uri, imeAction = ImeAction.Go,
),
keyboardActions = KeyboardActions(onGo = { onGo() }),
)
}
if (searching) CircularProgressIndicator(Modifier.size(16.dp), color = Color.White.copy(alpha = 0.7f), strokeWidth = 2.dp)
}
}
/** The accounts the typeahead found: each its face, name and handle; a tap picks it and signs in. */
@Composable
private fun Suggestions(found: List<FoundActor>, pick: (FoundActor) -> Unit) {
val shape = RoundedCornerShape(12.dp)
Column(
Modifier
.fillMaxWidth()
.background(Color.White.copy(alpha = 0.1f), shape)
.border(1.dp, Color.White.copy(alpha = 0.2f), shape)
.padding(vertical = 4.dp),
) {
found.forEachIndexed { i, actor ->
Row(
Modifier
.fillMaxWidth()
.clickable { pick(actor) }
.padding(horizontal = 16.dp, vertical = 8.dp)
.semantics(mergeDescendants = true) {
contentDescription = actor.displayName?.let { "$it, @${actor.handle}" } ?: "@${actor.handle}"
},
verticalAlignment = Alignment.CenterVertically,
) {
var failed by remember(actor) { mutableStateOf(false) }
Box(Modifier.size(32.dp).clip(CircleShape).background(Color.White.copy(alpha = 0.4f))) {
val picture = if (failed) actor.avatarFallback else actor.avatar ?: actor.avatarFallback
if (picture != null) {
AsyncImage(
picture, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize(),
onError = { if (!failed && actor.avatar != null) failed = true },
)
}
}
Spacer(Modifier.size(10.dp))
Column(Modifier.weight(1f)) {
actor.displayName?.let {
Text(it, color = Color.White, fontSize = 14.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
Text("@${actor.handle}", color = Color.White.copy(alpha = 0.6f), fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
if (i < found.lastIndex) HorizontalDivider(Modifier.padding(start = 58.dp), color = Color.White.copy(alpha = 0.15f))
}
}
}
/** Sign in: white, its word black, or a spinner while signing in (`label` null). */
@Composable
private fun WhiteButton(label: String?, enabled: Boolean, dim: Boolean, onClick: () -> Unit) {
Box(
Modifier
.fillMaxWidth()
.alpha(if (dim) 0.4f else 1f)
.clip(RoundedCornerShape(12.dp))
.background(Color.White)
.clickable(enabled = enabled, onClick = onClick)
.padding(vertical = 14.dp),
contentAlignment = Alignment.Center,
) {
if (label == null) {
CircularProgressIndicator(Modifier.size(20.dp), color = Color.Black, strokeWidth = 2.dp)
} else {
Text(label, color = Color.Black, fontWeight = FontWeight.SemiBold)
}
}
}
/** Create one: glass over the photo. */
@Composable
private fun GlassButton(label: String, enabled: Boolean, onClick: () -> Unit) {
val shape = RoundedCornerShape(12.dp)
Box(
Modifier
.fillMaxWidth()
.clip(shape)
.background(Color.White.copy(alpha = 0.15f))
.border(1.dp, Color.White.copy(alpha = 0.25f), shape)
.clickable(enabled = enabled, onClick = onClick)
.padding(vertical = 14.dp),
contentAlignment = Alignment.Center,
) {
Text(label, color = Color.White, fontWeight = FontWeight.SemiBold)
}
}
android/app/src/main/java/social/grain/StoryPager.ktnew+203−0
@@ -0,0 +1,203 @@
package social.grain
import androidx.activity.compose.BackHandler
import androidx.compose.animation.core.Animatable
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectVerticalDragGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshotFlow
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch
import place.hud.kit.data.Skeleton
import place.hud.kit.support.HudThemed
import place.hud.kit.support.Space
import place.hud.kit.tree.LocalSlidesTrailing
import place.hud.kit.tree.OpenedForm
import place.hud.kit.view.ResultView
import place.hud.kit.view.SkeletonView
import place.hud.kit.view.Way
import kotlin.math.abs
import kotlin.math.min
/** The room the ✕ takes at the end of the slides' top row. */
private val Close = 44.dp
/**
* The stories over the tabs, full screen on black, paged as grain-ios pages
* people's stories: the page in front with its neighbours either side read
* and drawn ahead, inactive. Swiped sideways, the page shrinks and fades as
* the neighbour that way comes in. Its `Slides` running off an end goes on
* the same way: past the last page, the stories close. Dragged down, it
* follows and shrinks a little, and past a third of the height it closes.
* Taps and holds go to the page's `Slides`. Drawn dark, whatever the
* scheme. Your story with none (`Stories.alone`): its form alone over the
* tabs, nothing drawn meanwhile; it closing, sent or not, closes the
* stories.
*/
@Composable
fun StoryPager(stories: Stories, shell: Shell) {
BackHandler { shell.closeStories() }
if (stories.alone) {
HudThemed(shell.config.dark, GrainConfig.typefaces) {
StoryPage(stories, stories.first, shell, active = true, end = {}, alone = { shell.closeStories() })
}
return
}
val pager = rememberPagerState(initialPage = stories.first) { stories.levels.size }
val scope = rememberCoroutineScope()
val dy = remember { Animatable(0f) }
val density = LocalDensity.current
LaunchedEffect(pager) { snapshotFlow { pager.currentPage }.collect(stories::moved) }
HudThemed(shell.config.dark, GrainConfig.typefaces) {
BoxWithConstraints(Modifier.fillMaxSize()) {
val height = with(density) { maxHeight.toPx() }
val down = min(dy.value / with(density) { 300.dp.toPx() }, 1f)
Box(
Modifier
.fillMaxSize()
.background(Color.Black.copy(alpha = 1 - down))
.pointerInput(stories) {
detectVerticalDragGestures(
onDragEnd = {
scope.launch {
if (dy.value > height * 0.35f) {
dy.animateTo(height + 100f)
shell.closeStories()
} else {
dy.animateTo(0f)
}
}
},
onDragCancel = { scope.launch { dy.animateTo(0f) } },
onVerticalDrag = { change, amount ->
change.consume()
scope.launch { dy.snapTo((dy.value + amount).coerceAtLeast(0f)) }
},
)
},
) {
// The slides' top row ends before the ✕, their ⋯ just before it.
CompositionLocalProvider(LocalSlidesTrailing provides Close - Space.s3) {
HorizontalPager(
state = pager,
beyondViewportPageCount = 1,
modifier = Modifier.fillMaxSize().graphicsLayer {
translationY = dy.value
scaleX = 1 - down * 0.1f
scaleY = 1 - down * 0.1f
},
) { i ->
val away = abs(pager.currentPage - i + pager.currentPageOffsetFraction).coerceAtMost(1f)
Box(
Modifier.fillMaxSize().graphicsLayer {
val scale = 1 - away * 0.08f
scaleX = scale
scaleY = scale
alpha = 1 - away
},
) {
StoryPage(
stories, i, shell,
active = i == pager.currentPage && !pager.isScrollInProgress,
end = { way ->
if (i != pager.currentPage || pager.isScrollInProgress) return@StoryPage
when (way) {
Way.Next -> if (i + 1 < stories.levels.size) scope.launch { pager.animateScrollToPage(i + 1) } else shell.closeStories()
Way.Previous -> if (i > 0) scope.launch { pager.animateScrollToPage(i - 1) }
}
},
)
}
}
}
IconButton(
onClick = { shell.closeStories() },
modifier = Modifier.align(Alignment.TopEnd).statusBarsPadding().padding(top = Space.s1).size(Close),
) {
Icon(Icons.Filled.Close, contentDescription = "Close", tint = Color.White)
}
}
}
}
}
/**
* One page of the stories: its call's answer drawn by HUD's kit with its
* level's context, in front or drawn ahead (`active`), held while a sheet
* is up over it. What opens from it closes the stories and opens on the
* tab; a story deleted (an action that leaves) closes them. With `alone`,
* only the form its call opens at (`OpenedForm`), once it answers afresh,
* nothing before, `alone` told as it closes.
*/
@Composable
private fun StoryPage(stories: Stories, i: Int, shell: Shell, active: Boolean, end: (Way) -> Unit, alone: (() -> Unit)? = null) {
val level = stories.levels[i]
val tab = stories.tab
val wiring = remember(level) {
Wiring(
open = { call ->
shell.closeStories()
shell.open(call, tab)
},
replace = { shell.replace(level, it) },
pages = null,
// Its comments as a sheet over it, the story held meanwhile.
sheet = { shell.openSheet(it, tab) },
leave = { shell.closeStories() },
wrote = { shell.wrote(level, tab) },
)
}
val shown = rememberShown(level, shell, wiring, lift = false)
val held = shell.sheet != null
SideEffect {
level.context.onEnd = end
level.context.active = active
level.context.held = held
}
LaunchedEffect(level) {
if (level.drawn == null) {
val client = shell.client
shell.scope.launch { level.load(client) }
}
}
if (alone != null) {
val body = shown.body
if (body != null && !level.refreshing && !level.swapping) OpenedForm(body, level.context, alone)
return
}
Box(Modifier.fillMaxSize().systemBarsPadding()) {
val body = shown.body
when {
level.needsSignIn -> SignInAsk(shell, "Sign in to see this")
body != null -> ResultView(body, level.context, Modifier.fillMaxSize(), onRetry = {
val client = shell.client
shell.scope.launch { level.load(client) }
})
else -> SkeletonView(Skeleton.recall(level.call), delayed = true)
}
}
}
android/app/src/main/java/social/grain/UpdateGate.ktnew+119−0
android/app/src/main/res/drawable/ic_launcher_monochrome.xmlnew+27−0
android/app/src/main/res/drawable/ic_notification.xmlnew+24−0
android/app/src/main/res/drawable-xhdpi/login_bg.jpgnew+0−0
A binary file, not shown.
android/app/src/main/res/drawable-xxhdpi/login_bg.jpgnew+0−0
A binary file, not shown.
android/app/src/main/res/font/plus_jakarta_sans.ttfnew+0−0
A binary file, not shown.
android/app/src/main/res/font/syne.ttfnew+0−0
A binary file, not shown.
android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xmlnew+18−0
android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xmlnew+18−0
android/app/src/main/res/mipmap-hdpi/ic_launcher.pngnew+0−0
A binary file, not shown.
android/app/src/main/res/mipmap-hdpi/ic_launcher_background.pngnew+0−0
A binary file, not shown.
android/app/src/main/res/mipmap-hdpi/ic_launcher_round.pngnew+0−0
A binary file, not shown.
android/app/src/main/res/mipmap-mdpi/ic_launcher.pngnew+0−0
A binary file, not shown.
android/app/src/main/res/mipmap-mdpi/ic_launcher_background.pngnew+0−0
A binary file, not shown.
android/app/src/main/res/mipmap-mdpi/ic_launcher_round.pngnew+0−0
A binary file, not shown.
android/app/src/main/res/mipmap-xhdpi/ic_launcher.pngnew+0−0
A binary file, not shown.
android/app/src/main/res/mipmap-xhdpi/ic_launcher_background.pngnew+0−0
A binary file, not shown.
android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.pngnew+0−0
A binary file, not shown.
android/app/src/main/res/mipmap-xxhdpi/ic_launcher.pngnew+0−0
A binary file, not shown.
android/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.pngnew+0−0
A binary file, not shown.
android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.pngnew+0−0
A binary file, not shown.
android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.pngnew+0−0
A binary file, not shown.
android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.pngnew+0−0
A binary file, not shown.
android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.pngnew+0−0
A binary file, not shown.
android/app/src/main/res/values/colors.xmlnew+7−0
android/app/src/main/res/values/strings.xmlnew+7−0
android/app/src/main/res/values/themes.xmlnew+10−0
android/app/src/main/res/values-night/colors.xmlnew+5−0
android/app/src/main/res/values-night/themes.xmlnew+9−0
android/app/src/main/res/xml/data_extraction_rules.xmlnew+13−0
android/app/src/main/res/xml/network_security_config.xmlnew+3−0
android/app/src/main/AndroidManifest.xmlnew+83−0
android/app/build.gradle.ktsnew+110−0
android/app/proguard-rules.pronew+1−0
android/gradle/wrapper/gradle-wrapper.jarnew+0−0
A binary file, not shown.
android/gradle/wrapper/gradle-wrapper.propertiesnew+8−0
android/.gitignorenew+6−0
android/build.gradle.ktsnew+24−0
android/gradle.propertiesnew+6−0
android/gradlewnew+234−0
android/gradlew.batnew+89−0
android/README.mdnew+111−0
android/settings.gradle.ktsnew+34−0
vendor/hud/android/gradle/libs.versions.tomlnew+55−0
vendor/hud/android/hudkit/src/main/assets/basemap/dark.jsonnew+10929−0
A large diff, not shown.
vendor/hud/android/hudkit/src/main/assets/basemap/light.jsonnew+10929−0
A large diff, not shown.
vendor/hud/android/hudkit/src/main/java/place/hud/kit/data/Client.ktnew+178−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/data/Compose.ktnew+362−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/data/Interactions.ktnew+112−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/data/Json.ktnew+172−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/data/LastTree.ktnew+155−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/data/Push.ktnew+211−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/data/Result.ktnew+198−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/data/Routes.ktnew+289−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/data/SchemeChoice.ktnew+17−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/data/SignIn.ktnew+653−0
653 lines changed: not loaded until asked for.
vendor/hud/android/hudkit/src/main/java/place/hud/kit/data/SignInPlan.ktnew+343−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/data/Skeleton.ktnew+235−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/data/TabFirst.ktnew+43−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/data/WebSignIn.ktnew+158−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/embed/EmbedCard.ktnew+72−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/embed/EmbedExternal.ktnew+165−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/embed/EmbedImages.ktnew+108−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/embed/EmbedRules.ktnew+103−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/embed/QuoteCard.ktnew+99−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/parts/Beside.ktnew+49−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/parts/ComposeFields.ktnew+1024−0
1024 lines changed: not loaded until asked for.
vendor/hud/android/hudkit/src/main/java/place/hud/kit/parts/ComposeForm.ktnew+407−0
407 lines changed: not loaded until asked for.
vendor/hud/android/hudkit/src/main/java/place/hud/kit/parts/ComposeSheet.ktnew+264−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/parts/FeedContextView.ktnew+209−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/parts/HeaderCard.ktnew+58−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/parts/Lightbox.ktnew+292−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/parts/ListLayout.ktnew+273−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/parts/PhotoBadges.ktnew+169−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/parts/ProfileCard.ktnew+86−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/parts/RowLayout.ktnew+279−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/parts/Shared.ktnew+169−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/parts/SplitLayout.ktnew+63−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/parts/TextBody.ktnew+199−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/parts/ThreadItem.ktnew+124−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/parts/ThreadLayouts.ktnew+60−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/support/Adaptive.ktnew+56−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/support/Controls.ktnew+54−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/support/Format.ktnew+75−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/support/Glyphs.ktnew+133−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/support/Picture.ktnew+101−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/support/Space.ktnew+108−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/support/Surface.ktnew+171−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/tree/Accounts.ktnew+104−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/tree/Acting.ktnew+980−0
980 lines changed: not loaded until asked for.
vendor/hud/android/hudkit/src/main/java/place/hud/kit/tree/AudioPlayer.ktnew+318−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/tree/Composing.ktnew+226−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/tree/Diff.ktnew+230−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/tree/Fields.ktnew+319−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/tree/MapView.ktnew+428−0
428 lines changed: not loaded until asked for.
vendor/hud/android/hudkit/src/main/java/place/hud/kit/tree/Marks.ktnew+188−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/tree/Media.ktnew+926−0
926 lines changed: not loaded until asked for.
vendor/hud/android/hudkit/src/main/java/place/hud/kit/tree/Navigation.ktnew+1062−0
1062 lines changed: not loaded until asked for.
vendor/hud/android/hudkit/src/main/java/place/hud/kit/tree/Pictures.ktnew+833−0
833 lines changed: not loaded until asked for.
vendor/hud/android/hudkit/src/main/java/place/hud/kit/tree/Playback.ktnew+673−0
673 lines changed: not loaded until asked for.
vendor/hud/android/hudkit/src/main/java/place/hud/kit/tree/Resolved.ktnew+105−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/tree/Structure.ktnew+444−0
444 lines changed: not loaded until asked for.
vendor/hud/android/hudkit/src/main/java/place/hud/kit/tree/TreeView.ktnew+401−0
401 lines changed: not loaded until asked for.
vendor/hud/android/hudkit/src/main/java/place/hud/kit/tree/Words.ktnew+536−0
536 lines changed: not loaded until asked for.
vendor/hud/android/hudkit/src/main/java/place/hud/kit/view/ResultView.ktnew+106−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/view/SkeletonView.ktnew+357−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/view/ViewContext.ktnew+249−0
vendor/hud/android/hudkit/src/main/java/place/hud/kit/workspace/Theme.ktnew+87−0
vendor/hud/android/hudkit/src/main/res/xml/hudkit_camera_paths.xmlnew+5−0
vendor/hud/android/hudkit/src/main/AndroidManifest.xmlnew+60−0
vendor/hud/android/hudkit/src/test/java/place/hud/kit/AccountsTest.ktnew+56−0
vendor/hud/android/hudkit/src/test/java/place/hud/kit/ClientTest.ktnew+164−0
vendor/hud/android/hudkit/src/test/java/place/hud/kit/ComposeTest.ktnew+537−0
537 lines changed: not loaded until asked for.
vendor/hud/android/hudkit/src/test/java/place/hud/kit/ContextTest.ktnew+122−0
vendor/hud/android/hudkit/src/test/java/place/hud/kit/InteractionsTest.ktnew+127−0
vendor/hud/android/hudkit/src/test/java/place/hud/kit/LastTreeTest.ktnew+192−0
vendor/hud/android/hudkit/src/test/java/place/hud/kit/LayoutTest.ktnew+233−0
vendor/hud/android/hudkit/src/test/java/place/hud/kit/OpenedFormTest.ktnew+40−0
vendor/hud/android/hudkit/src/test/java/place/hud/kit/PagesTest.ktnew+35−0
vendor/hud/android/hudkit/src/test/java/place/hud/kit/PlanTest.ktnew+251−0
vendor/hud/android/hudkit/src/test/java/place/hud/kit/ResultsTest.ktnew+145−0
vendor/hud/android/hudkit/src/test/java/place/hud/kit/RoutesTest.ktnew+293−0
vendor/hud/android/hudkit/src/test/java/place/hud/kit/SignInPlanTest.ktnew+177−0
vendor/hud/android/hudkit/src/test/java/place/hud/kit/SignInTest.ktnew+325−0
vendor/hud/android/hudkit/src/test/java/place/hud/kit/SkeletonTest.ktnew+203−0
vendor/hud/android/hudkit/src/test/java/place/hud/kit/SlidesTest.ktnew+95−0
vendor/hud/android/hudkit/src/test/java/place/hud/kit/TabFirstTest.ktnew+123−0
vendor/hud/android/hudkit/src/test/java/place/hud/kit/ThemeTest.ktnew+91−0
vendor/hud/android/hudkit/src/test/resources/robolectric.propertiesnew+2−0
vendor/hud/android/hudkit/build.gradle.ktsnew+83−0
vendor/hud/android/hudkit/consumer-rules.pronew+0−0
No changes to the content.
vendor/hud/ios/HUDKit/Sources/HUDKit/Support/Format.swift+5−4
vendor/hud/ios/HUDKit/Tests/HUDKitTests/HUDKitTests.swift+2−0
vendor/hud/web/renderer/src/format.test.tsnew+26−0
vendor/hud/web/renderer/src/format.ts+5−4
vendor/hud/COMMIT+1−1
vendor/hud/README.md+6−2
vendor/hud.sh+5−4
AGENTS.md+19−8
Justfile+19−0