Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / office / src / test / java / com / vayunmathur / office / platform / OfficeViewModelDocsSlice3Test.kt

OfficeViewModelDocsSlice3Test.kt342 lines · 14.4 KiBRaw
1package com.vayunmathur.office.platform
2
3import android.net.Uri
4import com.vayunmathur.library.ui.odf.OdfContentBlock
5import com.vayunmathur.library.ui.odf.OdfDocument
6import com.vayunmathur.library.ui.odf.OdfPageSetup
7import com.vayunmathur.library.ui.odf.OdfParagraph
8import com.vayunmathur.library.ui.odf.OdfSpan
9import com.vayunmathur.library.ui.odf.OdfTable
10import com.vayunmathur.library.ui.odf.OdfTableCell
11import com.vayunmathur.library.ui.odf.OdfTableRow
12import kotlin.test.Test
13import kotlin.test.assertEquals
14import kotlin.test.assertFalse
15import kotlin.test.assertTrue
16import kotlinx.coroutines.test.runTest
17import org.junit.runner.RunWith
18import org.mockito.Mockito.`when`
19import org.robolectric.RobolectricTestRunner
20
21/**
22 * Slice 3/4: documents/recent/save-as, tracked changes, footnotes/comments,
23 * headers/footers, links, fields and in-text tables on [OfficeViewModel].
24 *
25 * Robolectric (not plain JVM): several paths use `Uri.parse`/`Uri.fromFile` statics,
26 * which are stubs on the plain JVM.
27 */
28@RunWith(RobolectricTestRunner::class)
29@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
30class OfficeViewModelDocsSlice3Test : OfficeViewModelSlice3Harness() {
31
32 private fun textDoc(vararg texts: String) = OdfDocument.TextDocument(
33 title = "Doc",
34 content = texts.map { OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(it)))) },
35 )
36
37 private fun loaded(vararg texts: String): OfficeViewModel {
38 val vm = newVm()
39 vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(textDoc(*texts))
40 return vm
41 }
42
43 private fun textOf(vm: OfficeViewModel): OdfDocument.TextDocument =
44 (vm.state.value as OfficeViewModel.ViewState.Loaded).document as OdfDocument.TextDocument
45
46 @Test
47 fun `createNewTextDocument and clearDocument`() = runTest {
48 val vm = idleVm()
49 vm.createNewTextDocument()
50 assertTrue(vm.state.value is OfficeViewModel.ViewState.Loaded)
51 assertTrue(vm.isEditMode.value)
52 assertTrue(vm.hasUnsavedChanges.value)
53 vm.clearDocument()
54 assertTrue(vm.state.value is OfficeViewModel.ViewState.Empty)
55 assertFalse(vm.isEditMode.value)
56 assertFalse(vm.hasUnsavedChanges.value)
57 assertFalse(vm.isOnline.value)
58 }
59
60 @Test
61 fun `recent files add dedupe cap and clear`() = runTest {
62 val vm = idleVm()
63 val uri = Uri.parse("file:///tmp/a.odt")
64 vm.addToRecent(app, uri, "a.odt")
65 vm.addToRecent(app, uri, "a.odt")
66 assertEquals(1, vm.getRecentFiles(app).size)
67 assertEquals("a.odt", vm.getRecentFiles(app)[0].second)
68 repeat(25) { i -> vm.addToRecent(app, Uri.parse("file:///tmp/$i.odt"), "$i.odt") }
69 assertEquals(MAX_RECENT, vm.getRecentFiles(app).size)
70 assertEquals("24.odt", vm.getRecentFiles(app)[0].second)
71 vm.clearRecentFiles(app)
72 assertTrue(vm.getRecentFiles(app).isEmpty())
73 }
74
75 @Test
76 fun `needsSaveAs and isWritable for file uris`() = runTest {
77 val vm = idleVm()
78 assertTrue(vm.needsSaveAs())
79 val missing = java.io.File(tmpDir, "nope.odt")
80 vm.originalUri = Uri.fromFile(missing)
81 // Non-existent file is not writable -> Save As needed.
82 assertTrue(vm.needsSaveAs())
83 val real = java.io.File(tmpDir, "doc.odt")
84 real.writeText("x")
85 vm.originalUri = Uri.fromFile(real)
86 assertFalse(vm.needsSaveAs())
87 assertTrue(vm.isWritable(Uri.fromFile(real)))
88 assertFalse(vm.isWritable(Uri.fromFile(missing)))
89 }
90
91 @Test
92 fun `needsSaveAs with content uri consults permission`() = runTest {
93 val vm = idleVm()
94 val uri = Uri.parse("content://com.example/docs/1")
95 `when`(app.checkCallingOrSelfUriPermission(uri, android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION))
96 .thenReturn(android.content.pm.PackageManager.PERMISSION_DENIED)
97 vm.originalUri = uri
98 assertTrue(vm.needsSaveAs())
99 }
100
101 @Test
102 fun `save with no target is a no-op without loaded doc`() = runTest {
103 val vm = idleVm()
104 vm.save()
105 assertFalse(vm.isSaving.value)
106 }
107
108 @Test
109 fun `persistToAppStorage returns file uris inside docs dir`() = runTest {
110 val vm = idleVm()
111 val inside = java.io.File(java.io.File(tmpDir, "documents").apply { mkdirs() }, "x.odt")
112 inside.writeText("x")
113 val uri = Uri.fromFile(inside)
114 assertEquals(uri, vm.persistToAppStorage(uri, "x.odt"))
115 }
116
117 @Test
118 fun `accept reject change insertion and deletion`() = runTest {
119 fun changeDoc() = textDoc("hello world").copy(
120 changes = listOf(
121 com.vayunmathur.library.ui.odf.OdfChange(id = "c1", type = "insertion"),
122 com.vayunmathur.library.ui.odf.OdfChange(id = "c2", type = "deletion"),
123 ),
124 content = listOf(
125 OdfContentBlock.Paragraph(OdfParagraph(listOf(
126 OdfSpan("hello "),
127 OdfSpan("brave ", changeId = "c1", changeKind = "insertion"),
128 OdfSpan("world", changeId = "c2", changeKind = "deletion"),
129 ))),
130 ),
131 )
132 val vm = newVm()
133 vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(changeDoc())
134 // Accept insertion: span stays, marker cleared.
135 vm.acceptChange("c1")
136 var doc = textOf(vm)
137 assertTrue(doc.changes.none { it.id == "c1" })
138 assertTrue(doc.content.joinToString("") {
139 ((it as OdfContentBlock.Paragraph).paragraph.spans.joinToString("") { s -> s.text })
140 }.contains("brave"))
141 // Reject deletion: text kept, marker cleared.
142 vm.rejectChange("c2")
143 doc = textOf(vm)
144 assertTrue(doc.changes.none { it.id == "c2" })
145 assertTrue(textOf(vm).content.joinToString("") {
146 ((it as OdfContentBlock.Paragraph).paragraph.spans.joinToString("") { s -> s.text })
147 }.contains("world"))
148 // Unknown id is a no-op.
149 vm.acceptChange("nope")
150 // Non-text doc is a no-op.
151 val sheet = newVm()
152 sheet.stateMutable.value = OfficeViewModel.ViewState.Loaded(
153 OdfDocument.Spreadsheet(title = "B", sheets = emptyList()))
154 sheet.acceptChange("c1")
155 sheet.rejectChange("c1")
156 }
157
158 @Test
159 fun `acceptAll and rejectAll changes`() = runTest {
160 fun changeDoc() = textDoc("ab").copy(
161 changes = listOf(
162 com.vayunmathur.library.ui.odf.OdfChange(id = "c1", type = "insertion"),
163 com.vayunmathur.library.ui.odf.OdfChange(id = "c2", type = "deletion"),
164 ),
165 content = listOf(
166 OdfContentBlock.Paragraph(OdfParagraph(listOf(
167 OdfSpan("a", changeId = "c1", changeKind = "insertion"),
168 OdfSpan("b", changeId = "c2", changeKind = "deletion"),
169 ))),
170 ),
171 )
172 val vm = newVm()
173 vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(changeDoc())
174 vm.acceptAllChanges()
175 var text = textOf(vm).content.joinToString("") {
176 ((it as OdfContentBlock.Paragraph).paragraph.spans.joinToString("") { s -> s.text })
177 }
178 // Insertion kept, deletion removed.
179 assertEquals("a", text)
180 assertTrue(textOf(vm).changes.isEmpty())
181 val vm2 = newVm()
182 vm2.stateMutable.value = OfficeViewModel.ViewState.Loaded(changeDoc())
183 vm2.rejectAllChanges()
184 text = textOf(vm2).content.joinToString("") {
185 ((it as OdfContentBlock.Paragraph).paragraph.spans.joinToString("") { s -> s.text })
186 }
187 // Insertion removed, deletion kept.
188 assertEquals("b", text)
189 }
190
191 @Test
192 fun `page setup header footer footnote comment`() = runTest {
193 val vm = loaded("body text")
194 vm.setPageSetup(OdfPageSetup(widthPx = 100f, heightPx = 50f))
195 assertEquals(true, textOf(vm).pageSetup!!.isLandscape)
196 vm.setHeaderText("head\ntwo")
197 vm.setFooterText("foot")
198 assertEquals(2, textOf(vm).headerParagraphs.size)
199 assertEquals(1, textOf(vm).footerParagraphs.size)
200 vm.setHeaderText(" ")
201 assertTrue(textOf(vm).headerParagraphs.isEmpty())
202 vm.insertFootnote(0, 0, 9, "note body")
203 assertEquals(1, textOf(vm).footnotes.size)
204 assertEquals("note body", textOf(vm).footnotes[0].body[0].spans[0].text)
205 assertTrue(paraHas(vm, "[1]"))
206 vm.insertComment(0, "Ann", "nice")
207 assertTrue(textOf(vm).content.joinToString("") {
208 ((it as? OdfContentBlock.Paragraph)?.paragraph?.spans?.any { s -> s.annotation != null } ?: false).toString()
209 }.contains("true"))
210 // Resolve the comment span (last span of block 0).
211 val spans = (textOf(vm).content[0] as OdfContentBlock.Paragraph).paragraph.spans
212 vm.resolveComment(0, spans.size - 1)
213 assertFalse((textOf(vm).content[0] as OdfContentBlock.Paragraph)
214 .paragraph.spans.any { it.annotation != null })
215 }
216
217 private fun paraHas(vm: OfficeViewModel, needle: String): Boolean =
218 textOf(vm).content.any {
219 ((it as? OdfContentBlock.Paragraph)?.paragraph?.spans?.joinToString("") { s -> s.text }
220 ?: "").contains(needle)
221 }
222
223 @Test
224 fun `links set inspect remove selected text`() = runTest {
225 val vm = loaded("click here now")
226 // runSelectedText reads the current run text.
227 assertEquals("click", vm.runSelectedText(0, 0, 0, 5))
228 vm.setLink(0, 0, 6, 10, "here", "https://example.com")
229 val info = vm.linkAt(0, 0, 8)
230 assertEquals("https://example.com", info!!.url)
231 assertEquals("here", info.text)
232 assertEquals(null, vm.linkAt(0, 0, 2))
233 vm.removeLinkInRun(0, 0, 6, 10)
234 assertEquals(null, vm.linkAt(0, 0, 8))
235 assertTrue(paraHas(vm, "here"))
236 }
237
238 @Test
239 fun `field insert and display values`() = runTest {
240 val vm = loaded("today: ")
241 vm.insertFieldInRun(0, 0, 7, "date", vm.fieldDisplayValue("date"))
242 assertTrue(paraHas(vm, "-"))
243 assertEquals("1", vm.fieldDisplayValue("page-number"))
244 assertEquals("1", vm.fieldDisplayValue("page-count"))
245 assertEquals("", vm.fieldDisplayValue("bogus-kind"))
246 // Metadata-backed fields.
247 vm.updateMetadata { it.copy(author = "Ann", title = "T", subject = "S", description = "D") }
248 assertEquals("Ann", vm.fieldDisplayValue("author-name"))
249 assertEquals("T", vm.fieldDisplayValue("title"))
250 assertEquals("S", vm.fieldDisplayValue("subject"))
251 assertEquals("D", vm.fieldDisplayValue("description"))
252 assertTrue(vm.fieldDisplayValue("time").contains(":"))
253 }
254
255 @Test
256 fun `in-text tables crud merge format`() = runTest {
257 val vm = loaded("top")
258 vm.insertTableForTest()
259 var table = textOf(vm).tableAt(1)
260 assertEquals(2, table.rows.size)
261 assertEquals(2, table.rows[0].cells.size)
262 vm.updateTextTableCell(1, 0, 0, "A\nB")
263 assertEquals(2, textOf(vm).tableAt(1).rows[0].cells[0].paragraphs.size)
264 vm.textTableAddRow(1, 0)
265 vm.textTableAddColumn(1, 0)
266 assertEquals(3, textOf(vm).tableAt(1).rows.size)
267 assertEquals(3, textOf(vm).tableAt(1).rows[0].cells.size)
268 vm.mergeTextTableCells(1, 0, 0, 1, 1)
269 assertEquals(2, textOf(vm).tableAt(1).rows[0].cells[0].colSpan)
270 assertTrue(textOf(vm).tableAt(1).rows[1].cells[1].isCovered)
271 vm.unmergeTextTableCells(1, 0, 0)
272 assertEquals(1, textOf(vm).tableAt(1).rows[0].cells[0].colSpan)
273 vm.setTextTableCellSpanFormat(1, 0, 0) { it.copy(bold = true) }
274 assertTrue(textOf(vm).tableAt(1).rows[0].cells[0].paragraphs.all { p ->
275 p.spans.all { it.bold }
276 })
277 vm.setTextTableCellAlignment(1, 0, 0, androidx.compose.ui.text.style.TextAlign.Center)
278 vm.setTextTableCellBackground(1, 0, 0, 0xFFFF0000L)
279 assertEquals(0xFFFF0000L, textOf(vm).tableAt(1).rows[0].cells[0].backgroundColor)
280 vm.textTableDeleteRow(1, 0)
281 vm.textTableDeleteColumn(1, 0)
282 assertEquals(2, textOf(vm).tableAt(1).rows.size)
283 // Out-of-range row/col edits are contained no-ops.
284 vm.updateTextTableCell(1, 9, 9, "z")
285 vm.textTableDeleteRow(1, 9)
286 }
287
288 private fun OfficeViewModel.insertTableForTest() {
289 insertTable(0, 2, 2)
290 }
291
292 private fun OdfDocument.TextDocument.tableAt(i: Int): OdfTable =
293 (content[i] as OdfContentBlock.Table).table
294
295 @Test
296 fun `currentDocRole online id canEdit myDisplayName`() = runTest {
297 val vm = idleVm()
298 assertEquals(OfficeRoles.OWNER, vm.currentDocRole())
299 assertEquals(null, vm.currentOnlineDocId())
300 assertTrue(vm.canEditCurrent())
301 // Offline docs are always editable; the role gate applies once online.
302 vm.currentRole = OfficeRoles.VIEWER
303 assertTrue(vm.canEditCurrent())
304 vm.currentDocId = "d1"
305 assertFalse(vm.canEditCurrent())
306 assertEquals("d1", vm.currentOnlineDocId())
307 assertTrue(vm.myDisplayName().startsWith("User "))
308 }
309
310 @Test
311 fun `signing bytes builders are canonical`() = runTest {
312 val vm = idleVm()
313 val m = OfficeMember("id1", "Ann", OfficeRoles.EDITOR)
314 assertEquals("doc|id1|editor",
315 vm.memberSigningBytes("doc", m).decodeToString())
316 assertEquals("doc|title|Hello",
317 vm.titleSigningBytes("doc", "Hello").decodeToString())
318 assertEquals("doc|owner|n1|keyB64",
319 vm.ownerSigningBytes("doc", "n1", "keyB64").decodeToString())
320 val epoch = vm.epochSigningBytes("doc", 2, mapOf("b" to "2", "a" to "1"))
321 assertEquals("doc|2|a=1|b=2", epoch.decodeToString())
322 assertEquals("https://maproj.org/of/share#id=d9&owner=${vm.syncDeviceId}",
323 vm.shareLinkFor("d9"))
324 }
325
326 @Test
327 fun `withTitle setLoadedTitle resolveShareTitle`() = runTest {
328 val vm = loaded("x")
329 val doc = textOf(vm)
330 assertEquals("N", (vm.withTitle(doc, "N") as OdfDocument.TextDocument).title)
331 vm.setLoadedTitle("Renamed")
332 assertEquals("Renamed", textOf(vm).title)
333 // First share: blank docName falls back to doc title.
334 vm.currentDocId = null
335 assertEquals("Doc", vm.resolveShareTitle(" ", "Doc"))
336 // Later share keeps the stored online title.
337 vm.currentDocId = "d1"
338 vm.onlineDocsMutable.value = listOf(
339 OfficeDocMeta(docId = "d1", title = "Stored", keyB64 = "", owner = true))
340 assertEquals("Stored", vm.resolveShareTitle("New", "Doc"))
341 }
342}