Cotton code
181 lines · 8.6 KB · KotlinRaw
package com.cottondb.android.ui.paperimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.Boximport androidx.compose.runtime.Composableimport androidx.compose.runtime.rememberimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.draw.drawBehindimport androidx.compose.ui.draw.shadowimport androidx.compose.ui.geometry.Sizeimport androidx.compose.ui.graphics.BlendModeimport androidx.compose.ui.graphics.ImageBitmapimport androidx.compose.ui.graphics.Outlineimport androidx.compose.ui.graphics.Pathimport androidx.compose.ui.graphics.Shapeimport androidx.compose.ui.graphics.drawscope.DrawScopeimport androidx.compose.ui.graphics.drawscope.withTransformimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.imageResourceimport androidx.compose.ui.unit.Densityimport androidx.compose.ui.unit.Dpimport androidx.compose.ui.unit.LayoutDirectionimport androidx.compose.ui.unit.dpimport com.cottondb.android.Rimport com.cottondb.android.design.PaperPhotoMetricsimport kotlin.math.maximport kotlin.math.min/** The photographed paper dyes used by CottonUI's memory-slip rotation. */enum class MemoryPaperDye(internal val resourceId: Int) {    Pink(R.drawable.paper_pink),    Cream(R.drawable.paper_cream),    Sage(R.drawable.paper_sage),    Blue(R.drawable.paper_blue),    Straw(R.drawable.paper_straw),    Peach(R.drawable.paper_peach);    companion object {        /** Swift's memory-slip rotation remains pink, cream, sage after Reader dyes were added. */        fun at(index: Int): MemoryPaperDye = listOf(Pink, Cream, Sage)[Math.floorMod(index, 3)]    }}enum class PaperEdge { Torn, Cut }/** A guillotine-cut sheet: straight sides and restrained, deterministic worn corners. */class CutPaperShape(private val seed: String) : Shape {    override fun createOutline(size: Size, layoutDirection: LayoutDirection, density: Density): Outline {        if (size.width <= 4f || size.height <= 4f) return Outline.Rectangle(androidx.compose.ui.geometry.Rect(0f, 0f, size.width, size.height))        val maximum = min(4.dp.value * density.density, min(size.width, size.height) * .03f)        fun wear(corner: Int): Float = maximum * (.55f + seededUnit(seed, 4_093 + corner) * .45f)        val topLeft = wear(0); val topRight = wear(1); val bottomRight = wear(2); val bottomLeft = wear(3)        return Outline.Generic(Path().apply {            moveTo(topLeft, 0f)            lineTo(size.width - topRight, 0f)            quadraticBezierTo(size.width, 0f, size.width, topRight)            lineTo(size.width, size.height - bottomRight)            quadraticBezierTo(size.width, size.height, size.width - bottomRight, size.height)            lineTo(bottomLeft, size.height)            quadraticBezierTo(0f, size.height, 0f, size.height - bottomLeft)            lineTo(0f, topLeft)            quadraticBezierTo(0f, 0f, topLeft, 0f)            close()        })    }}/** A stable deckle whose nicks always stay inside its assigned layout bounds. */class TornPaperShape(private val seed: String) : Shape {    override fun createOutline(size: Size, layoutDirection: LayoutDirection, density: Density): Outline {        if (size.width <= 4f || size.height <= 4f) return Outline.Rectangle(androidx.compose.ui.geometry.Rect(0f, 0f, size.width, size.height))        val amplitude = min(4.dp.value * density.density, max(.9f * density.density, min(size.width, size.height) * .024f))        val path = Path()        edge(path, size.width, 18.dp.value * density.density, amplitude, 0) { distance, bite ->            if (distance == 0f) path.moveTo(bite, bite) else path.lineTo(distance, bite)        }        edge(path, size.height, 18.dp.value * density.density, amplitude, 1) { distance, bite -> path.lineTo(size.width - bite, distance) }        edge(path, size.width, 18.dp.value * density.density, amplitude, 2) { distance, bite -> path.lineTo(size.width - distance, size.height - bite) }        edge(path, size.height, 18.dp.value * density.density, amplitude, 3) { distance, bite -> path.lineTo(bite, size.height - distance) }        path.close()        return Outline.Generic(path)    }    private fun edge(path: Path, length: Float, spacing: Float, amplitude: Float, side: Int, point: (Float, Float) -> Unit) {        val count = max(3, (length / spacing).toInt())        repeat(count + 1) { index ->            val distance = length * index / count            point(distance, deckle(seed, side, index, amplitude))        }    }    private fun deckle(seed: String, side: Int, index: Int, amplitude: Float): Float {        // 0.30…1.00 gives a torn edge a few long, uneven bites instead of a scallop.        val unit = seededUnit(seed, side * 65537 + index)        return amplitude * (.30f + unit * .70f)    }}/** The paper surface common to physical Compose objects. */@Composablefun TornPaper(    id: String,    dye: MemoryPaperDye,    modifier: Modifier = Modifier,    elevation: Dp = 3.dp,    edge: PaperEdge = PaperEdge.Torn,    content: @Composable () -> Unit,) {    val shape: Shape = remember(id, edge) {        when (edge) {            PaperEdge.Torn -> TornPaperShape(id)            PaperEdge.Cut -> CutPaperShape(id)        }    }    val resources = LocalContext.current.resources    val photograph = remember(dye) { ImageBitmap.imageResource(resources, dye.resourceId) }    val grain = remember { ImageBitmap.imageResource(resources, R.drawable.paper_grain) }    Box(        modifier            .shadow(elevation, shape, clip = false)            .clip(shape)            .background(androidx.compose.ui.graphics.Color.Transparent)            .drawBehind { drawPaperPhotograph(photograph, grain, PaperPhotoMetrics.flip(id)) },    ) {        content()    }}/** Swift PaperPhoto's nine slice; core metrics stay in points even on high-density Android screens. */private fun DrawScope.drawPaperPhotograph(photo: ImageBitmap, grain: ImageBitmap, flip: PaperPhotoMetrics.Flip) {    val frame = PaperPhotoMetrics.frame(size.width / density, size.height / density)    val sourceRim = PaperPhotoMetrics.rimPixels    val destinationRim = frame.capPoints * density    if (size.width <= destinationRim * 2 || size.height <= destinationRim * 2) {        withTransform({ scale(flip.horizontal, flip.vertical, center) }) {            drawImage(photo, dstSize = androidx.compose.ui.unit.IntSize(size.width.toInt(), size.height.toInt()))        }        return    }    withTransform({ scale(flip.horizontal, flip.vertical, center) }) {        drawNineSlicedPhotograph(photo, sourceRim, destinationRim)    }    if (frame.grainOpacity <= .01f) return    val tile = (PaperPhotoMetrics.grainTilePoints * density).toInt()    for (y in 0 until size.height.toInt() step tile) for (x in 0 until size.width.toInt() step tile) {        drawImage(            image = grain,            dstOffset = androidx.compose.ui.unit.IntOffset(x, y),            dstSize = androidx.compose.ui.unit.IntSize(tile, tile),            alpha = frame.grainOpacity,            blendMode = BlendMode.Multiply,        )    }}private fun DrawScope.drawNineSlicedPhotograph(photo: ImageBitmap, sourceRim: Int, destinationRim: Float) {    val sourceXs = intArrayOf(0, sourceRim, photo.width - sourceRim)    val sourceYs = intArrayOf(0, sourceRim, photo.height - sourceRim)    val destinationXs = floatArrayOf(0f, destinationRim, size.width - destinationRim)    val destinationYs = floatArrayOf(0f, destinationRim, size.height - destinationRim)    for (row in 0..2) for (column in 0..2) {        val sourceWidth = (if (column == 2) photo.width else sourceXs[column + 1]) - sourceXs[column]        val sourceHeight = (if (row == 2) photo.height else sourceYs[row + 1]) - sourceYs[row]        val destinationWidth = (if (column == 2) size.width else destinationXs[column + 1]) - destinationXs[column]        val destinationHeight = (if (row == 2) size.height else destinationYs[row + 1]) - destinationYs[row]        drawImage(            image = photo,            srcOffset = androidx.compose.ui.unit.IntOffset(sourceXs[column], sourceYs[row]),            srcSize = androidx.compose.ui.unit.IntSize(sourceWidth, sourceHeight),            dstOffset = androidx.compose.ui.unit.IntOffset(destinationXs[column].toInt(), destinationYs[row].toInt()),            dstSize = androidx.compose.ui.unit.IntSize(destinationWidth.toInt(), destinationHeight.toInt()),        )    }}private fun seededUnit(seed: String, salt: Int): Float {    var value = salt    for (character in seed) value = value * 31 + character.code    return ((value ushr 1) % 10_000).toFloat() / 10_000f}