Cotton code
200 lines · 12.1 KB · KotlinRaw
package com.cottondb.notesimport android.app.Applicationimport android.graphics.Bitmapimport android.net.Uriimport android.webkit.WebResourceRequestimport android.webkit.WebSettingsimport androidx.activity.ComponentActivityimport androidx.compose.ui.test.junit4.createAndroidComposeRuleimport androidx.compose.ui.test.onNodeWithTagimport androidx.compose.ui.test.performClickimport androidx.compose.ui.text.font.FontFamilyimport com.cottondb.writing.editor.Stylingimport com.cottondb.writing.editor.WritingKeysimport com.cottondb.writing.theme.Writingimport com.cottondb.writing.theme.WritingThemeimport com.cottondb.writing.theme.WritingTypeimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.jsonObjectimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertFalseimport org.junit.Assert.assertNotNullimport org.junit.Assert.assertTrueimport org.junit.Ruleimport org.junit.Testimport org.junit.rules.TemporaryFolderimport org.junit.runner.RunWithimport org.robolectric.RobolectricTestRunnerimport org.robolectric.Shadows.shadowOfimport org.robolectric.annotation.Configimport org.robolectric.annotation.GraphicsMode/** * RULE (Words' attached files, 22 Nov 2026; CONTRACT.md section 15): a file a note carries opens read-only in the reader * the core names: a web page in a sealed web view (scripts off, no network, nothing loaded but its words, no interface * to the app), Markdown drawn as a note, a PDF's pages, a picture whole; anything else is asked about before another * app. Until this a note's web page, Markdown or PDF was not shown at all. Invented files. */@RunWith(RobolectricTestRunner::class)@GraphicsMode(GraphicsMode.Mode.NATIVE)@Config(sdk = [35], application = Application::class, qualifiers = "w411dp-h891dp-xxhdpi")class NotesFilesTest {    @get:Rule val compose = createAndroidComposeRule<ComponentActivity>()    @get:Rule val folder = TemporaryFolder()    private val theme = WritingTheme.of("linen", "Linen", Json.parseToJsonElement("""{"ground":"#F7F5F0","text":"#2E2E31","heading":"#1C1C1E","secondary":"#8A8A8F","accent":"#D2453A"}""").jsonObject)    private val type = WritingType(FontFamily.Default, 17f, 1.5f, 600f, FontFamily.Monospace)    private val words = FileWords("Back", "Share", "This file could not be read.", "Not here yet", "Open this link in your browser?", "Open", "Close", "Whole size")    private fun file(opens: String?, here: Boolean = true, refused: String? = null, name: String = "Invented file"): JsonObject = Json.parseToJsonElement(        """{"id":"doc-1","name":"$name","opens":${opens?.let { "\"$it\"" } ?: "null"},"here":$here,"refused":${refused?.let { "\"$it\"" } ?: "null"},"key":"k"}""",    ).jsonObject    @Test fun each_answer_taps_to_its_one_act() {        assertEquals(NotesFiles.Tap.Read("page"), NotesFiles.tap(file("page")))        assertEquals(NotesFiles.Tap.Read("note"), NotesFiles.tap(file("note")))        assertEquals(NotesFiles.Tap.Read("pdf"), NotesFiles.tap(file("pdf")))        assertEquals(NotesFiles.Tap.Read("picture"), NotesFiles.tap(file("picture")))        assertEquals(NotesFiles.Tap.Elsewhere, NotesFiles.tap(file("elsewhere")))        // Not in this copy: fetched first, never a dead tap.        assertEquals(NotesFiles.Tap.Fetch, NotesFiles.tap(file(null, here = false)))        assertEquals(NotesFiles.Tap.Refuse("Too big"), NotesFiles.tap(file("page", refused = "Too big")))    }    private fun reads(opens: String, path: String, shows: String) {        compose.setContent {            Writing(theme, type) {                FileReader(file(opens, name = "Invented $opens"), path, false, words, WritingKeys.none, style = { Styling.of(JsonObject(emptyMap())) }, onBack = {}, onShare = {}, onLink = {})            }        }        compose.waitForIdle()        compose.onNodeWithTag("file-$opens").assertExists()        compose.waitUntil(5_000) { compose.onAllNodes(androidx.compose.ui.test.hasTestTag(shows)).fetchSemanticsNodes().isNotEmpty() }        compose.onNodeWithTag("file-reader-name").assertExists()        compose.onNodeWithTag("file-reader-back").assertExists()    }    @Test fun a_web_page_opens_in_the_sealed_web_view() {        val page = folder.newFile("page.html").apply { writeText("<h1>Invented page</h1><script>document.title='ran'</script><img src='https://tracker.example/pixel.gif'>") }        reads("page", page.path, "file-page-web")    }    @Test fun markdown_opens_drawn_as_a_note() {        val md = folder.newFile("packing.md").apply { writeText("# Packing\n\n- Passport\n- Charger\n\n[Invented link](https://example.com)") }        reads("note", md.path, "file-note-text")    }    @Test fun a_picture_opens_whole_to_pinch() {        val png = folder.newFile("map.png")        Bitmap.createBitmap(8, 6, Bitmap.Config.ARGB_8888).apply { eraseColor(android.graphics.Color.RED) }.compress(Bitmap.CompressFormat.PNG, 100, png.outputStream())        reads("picture", png.path, "file-picture-zoom")    }    @Test fun a_pdf_opens_its_pages() {        val pdf = folder.newFile("tickets.pdf").apply { writeBytes(onePagePdf()) }        // Robolectric's PdfRenderer draws no page: the PDF reader stands (its pages on a phone, seen on the emulator), never another reader.        reads("pdf", pdf.path, "file-pdf")        compose.onNodeWithTag("file-page-web").assertDoesNotExist()        compose.onNodeWithTag("file-note-text").assertDoesNotExist()    }    /** The smallest PDF of one blank page, written by hand (its cross-reference offsets counted). */    private fun onePagePdf(): ByteArray {        val objects = listOf(            "<< /Type /Catalog /Pages 2 0 R >>",            "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 280] /Resources << >> >>",        )        val out = StringBuilder("%PDF-1.4\n")        val offsets = objects.mapIndexed { i, body -> out.length.also { out.append("${i + 1} 0 obj\n$body\nendobj\n") } }        val xref = out.length        out.append("xref\n0 ${objects.size + 1}\n0000000000 65535 f \n")        offsets.forEach { out.append(String.format("%010d 00000 n \n", it)) }        out.append("trailer\n<< /Size ${objects.size + 1} /Root 1 0 R >>\nstartxref\n$xref\n%%EOF\n")        return out.toString().toByteArray(Charsets.US_ASCII)    }    @Test fun the_web_view_is_locked_scripts_off_no_network_no_files_no_interface() {        val context = androidx.test.core.app.ApplicationProvider.getApplicationContext<Application>()        val followed = ArrayList<String>()        val web = NotesFileSeal.view(context, "<p>Invented</p>") { followed += it }        val s = web.settings        assertFalse("scripts off", s.javaScriptEnabled)        assertFalse(s.javaScriptCanOpenWindowsAutomatically)        assertTrue("no network", s.blockNetworkLoads)        assertTrue(s.blockNetworkImage)        assertFalse("no file address", s.allowFileAccess)        assertFalse(s.allowContentAccess)        @Suppress("DEPRECATION") assertFalse(s.allowFileAccessFromFileURLs)        @Suppress("DEPRECATION") assertFalse(s.allowUniversalAccessFromFileURLs)        assertFalse(s.domStorageEnabled)        assertEquals(WebSettings.LOAD_NO_CACHE, s.cacheMode)        // No interface reaches the app: nothing was added to the page.        val shadow = shadowOf(web)        listOf("Android", "app", "cotton", "words", "bridge").forEach { assertEquals("no $it interface", null, shadow.getJavascriptInterface(it)) }        // The page was handed in as its words, at a host that is no host: never a path on the phone.        assertEquals(NotesFileSeal.BASE, shadow.lastLoadDataWithBaseURL.baseUrl)        val client = shadow.webViewClient        fun asked(url: String, gesture: Boolean = false, main: Boolean = false) = object : WebResourceRequest {            override fun getUrl(): Uri = Uri.parse(url)            override fun isForMainFrame() = main            override fun isRedirect() = false            override fun hasGesture() = gesture            override fun getMethod() = "GET"            override fun getRequestHeaders(): Map<String, String> = emptyMap()        }        listOf("https://tracker.example/pixel.gif", "https://cdnjs.cloudflare.com/ajax/libs/d3/7.9.0/d3.min.js", "${NotesFileSeal.BASE}style.css", "file:///data/user/0/com.cottondb.notes.dev/databases/personal.db", "content://contacts/1", "data:image/png;base64,AAAA").forEach { url ->            val answer = client.shouldInterceptRequest(web, asked(url))            assertNotNull("$url refused", answer)            assertEquals("$url refused", 403, answer!!.statusCode)        }        // The page's own words, the main frame's one load, pass (refused, the page stood "Webpage not available" on the        // emulator); a frame or picture of `data:text/html` the page names does not, nor a main frame anywhere else.        assertEquals(null, client.shouldInterceptRequest(web, asked("data:text/html;charset=utf-8;base64,PHA+", main = true)))        assertEquals(403, client.shouldInterceptRequest(web, asked("data:text/html;charset=utf-8;base64,PHA+"))!!.statusCode)        assertEquals(403, client.shouldInterceptRequest(web, asked("https://tracker.example/", main = true))!!.statusCode)        assertEquals(403, client.shouldInterceptRequest(web, asked("file:///etc/hosts", main = true))!!.statusCode)        // A link followed is asked about, never opened by the page; a redirect the page makes alone goes nowhere.        assertTrue(client.shouldOverrideUrlLoading(web, asked("https://example.com/", gesture = true)))        assertTrue(client.shouldOverrideUrlLoading(web, asked("https://elsewhere.example/", gesture = false)))        assertTrue(client.shouldOverrideUrlLoading(web, asked("javascript:alert(1)", gesture = true)))        assertEquals(listOf("https://example.com/"), followed)        // A jump inside the page stays in it.        assertFalse(client.shouldOverrideUrlLoading(web, asked("${NotesFileSeal.BASE}#packing", gesture = true)))        web.destroy()    }    /** At the largest text a short name stood broken mid-word beside its kind ("packing.m / d", the emulator, 22 Nov 2026). */    @Test fun a_files_name_stands_whole_at_size_two() {        val file = Json.parseToJsonElement("""{"id":"doc-md","name":"packing.md","about":"Markdown · 225 B","opens":"note","here":true,"label":"Open packing.md"}""").jsonObject        compose.setContent {            val d = androidx.compose.ui.platform.LocalDensity.current            androidx.compose.runtime.CompositionLocalProvider(androidx.compose.ui.platform.LocalDensity provides androidx.compose.ui.unit.Density(d.density, fontScale = 2f)) {                Writing(theme, type) { NoteFiles(listOf(file), more = { "" }, onOpen = {}) {} }            }        }        compose.waitForIdle()        val out = ArrayList<androidx.compose.ui.text.TextLayoutResult>()        compose.onNodeWithTag("note-file-name", useUnmergedTree = true).fetchSemanticsNode().config[androidx.compose.ui.semantics.SemanticsActions.GetTextLayoutResult].action!!.invoke(out)        val laid = out.single()        assertTrue("one line, every letter: ${laid.lineCount} lines", laid.lineCount == 1 && laid.getLineEnd(0, visibleEnd = true) == "packing.md".length)    }    @Test fun a_notes_files_stand_under_its_top_bar_and_more_than_three_fold_into_a_line() {        var opened: String? = null        var more = false        val files = (1..5).map { n -> Json.parseToJsonElement("""{"id":"doc-$n","name":"Invented $n","about":"PDF · 2 KB","opens":"pdf","here":true,"label":"Open Invented $n"}""").jsonObject }        compose.setContent { Writing(theme, type) { NoteFiles(files, more = { n -> "$n more files" }, onOpen = { opened = it["id"].toString() }) { more = true } } }        compose.onNodeWithTag("note-file-doc-1").assertExists()        compose.onNodeWithTag("note-file-doc-2").assertExists()        compose.onNodeWithTag("note-file-doc-3").assertDoesNotExist()        compose.onNodeWithTag("note-file-more").assertExists()        compose.onNodeWithTag("note-file-doc-2").performClick()        assertEquals("\"doc-2\"", opened)        compose.onNodeWithTag("note-file-more").performClick()        assertTrue(more)    }}