package com.cottondb.messages.chat import android.app.Application import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Canvas import android.graphics.LinearGradient import android.graphics.Paint import android.graphics.Shader import android.util.Base64 import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import org.robolectric.annotation.GraphicsMode /** * A PICTURE'S PREVIEW as the sending phone makes it (CONTRACT.md "Pictures at once", 23 Nov 2026: pictures took 1 to * 2 s to appear, blank boxes meanwhile, because a Cotton picture carried no preview): at most 32 px a side, a JPEG of * at most 2,000 bytes, base64 with no line breaks, which the core takes as `payload::preview_of` does. */ @RunWith(RobolectricTestRunner::class) @GraphicsMode(GraphicsMode.Mode.NATIVE) @Config(sdk = [35], application = Application::class) class PicturePreviewTest { @get:Rule val tmp = TemporaryFolder() /** An invented photograph the size of the walk's (2016 x 1512), a busy wash so it does not compress to nothing. */ private fun photo(w: Int = 2016, h: Int = 1512): java.io.File { val b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888) Canvas(b).drawRect(0f, 0f, w.toFloat(), h.toFloat(), Paint().apply { shader = LinearGradient(0f, 0f, w.toFloat(), h.toFloat(), 0xFF3F7A9C.toInt(), 0xFFA6D80F.toInt(), Shader.TileMode.MIRROR) }) return tmp.newFile("invented.jpg").apply { outputStream().use { b.compress(Bitmap.CompressFormat.JPEG, 92, it) } } } @Test fun a_photo_gives_a_small_jpeg_at_its_own_shape() { val preview = PicturePreview.of(photo()) assertNotNull(preview) assertTrue("no line breaks", '\n' !in preview!!) val bytes = Base64.decode(preview, Base64.NO_WRAP) assertTrue("at most 2,000 bytes, was ${bytes.size}", bytes.size <= PicturePreview.MAX_BYTES) assertTrue("a JPEG", bytes[0] == 0xFF.toByte() && bytes[1] == 0xD8.toByte()) assertTrue("within the core's 2,800 characters", preview.length <= 2_800) val drawn = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) assertEquals(32, drawn.width) assertEquals(24, drawn.height) } @Test fun a_tall_photo_keeps_its_shape() { val drawn = PicturePreview.bitmap(PicturePreview.of(photo(900, 1600))!!)!! assertEquals(32, drawn.height) assertEquals(18, drawn.width) } @Test fun what_is_not_a_picture_gives_none() { assertNull(PicturePreview.of(tmp.newFile("notes.txt").apply { writeText("invented words") })) assertNull(PicturePreview.of(java.io.File(tmp.root, "missing.jpg"))) } }