Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.
Rust androiddocument-scannerdocximage-editorjetpack-composekotlinliquid-glassofflineopen-sourcepdfpdf-compressorpdf-editorpdf-mergerpdf-readerpdf-splitterpdf-toolspdf-viewerpptxspreadsheet-editorxlsx
Word documents open in their own editor (#73)
chethan616551e57add42a
diff --git a/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt b/app/src/main/java/com/chethan616/clearpdf/MainActivity.ktindex c62f6cb..8ec3dce 100644--- a/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt+++ b/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt@@ -87,11 +87,14 @@ open class MainActivity : ComponentActivity() {}?.takeIf { uri -> isSupportedDocumentIntent(intent?.type, uri.toString()) }// Route an incoming document by its kind: spreadsheets → interactive grid, images → image- // editor, everything else → the PDF viewer.+ // editor, .docx → the Word editor, everything else → the PDF viewer.val effectiveRoute = if (incomingPdfUri != null) {- when (com.chethan616.clearpdf.utils.docKindOf(queryDisplayName(incomingPdfUri))) {+ val incomingName = queryDisplayName(incomingPdfUri)+ when (com.chethan616.clearpdf.utils.docKindOf(incomingName)) {com.chethan616.clearpdf.utils.DocKind.Excel -> "spreadsheet"com.chethan616.clearpdf.utils.DocKind.Image -> "image_editor"+ com.chethan616.clearpdf.utils.DocKind.Word ->+ if (incomingName?.lowercase()?.trim()?.endsWith(".docx") == true) "docx_editor" else "pdf_viewer"else -> "pdf_viewer"}} else shortcutRoutediff --git a/app/src/main/java/com/chethan616/clearpdf/docx/DocxEdits.kt b/app/src/main/java/com/chethan616/clearpdf/docx/DocxEdits.ktnew file mode 100644index 0000000..7de8b43--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/docx/DocxEdits.kt@@ -0,0 +1,254 @@+package com.chethan616.clearpdf.docx++/**+ * Pure editing operations on [DocPara]s. Each returns new paragraphs (dropping their original XML,+ * so the writer serializes them again) and never touches anything else.+ */+object DocxEdits {++ /** The paragraph mark's own formatting, which Word gives to text typed into an empty paragraph. */+ fun markFmt(p: DocPara): CharFmt {+ var r = Props.child(p.pPr, "rPr") ?: return CharFmt.Plain+ for (k in listOf("ins", "del", "rPrChange", "moveFrom", "moveTo")) r = Props.setR(r, k, null)+ return CharFmt(r)+ }++ /** The format new text typed at [at] picks up: the character before it, as in Word. */+ fun fmtAt(p: DocPara, at: Int): CharFmt {+ fun plain(f: CharFmt, keepLink: Boolean) = if (f.obj != null || (!keepLink && f.link != null)) CharFmt(f.rPr, if (keepLink) f.link else null) else f+ val before = (at - 1 downTo 0).firstOrNull { p.fmts[it].obj == null && p.text[it] != OBJ_CHAR }+ val after = (at until p.text.length).firstOrNull { p.fmts[it].obj == null }+ if (before != null) {+ val f = p.fmts[before]+ // Typing inside a link extends it; typing right after one doesn't.+ val inside = f.link != null && after != null && p.fmts[after].link == f.link+ return plain(f, inside)+ }+ if (after != null) return plain(p.fmts[after], false)+ return markFmt(p)+ }++ /** Applies the field's new text to [p]; inserted characters take [typing]. */+ fun typed(p: DocPara, newText: String, typing: CharFmt): DocPara {+ val old = p.text+ if (old == newText) return p+ var pre = 0+ val max = minOf(old.length, newText.length)+ while (pre < max && old[pre] == newText[pre]) pre+++ var suf = 0+ while (suf < max - pre && old[old.length - 1 - suf] == newText[newText.length - 1 - suf]) suf+++ val fmts = ArrayList<CharFmt>(newText.length)+ for (i in 0 until pre) fmts.add(p.fmts[i])+ for (i in pre until newText.length - suf) fmts.add(typing)+ for (i in old.length - suf until old.length) fmts.add(p.fmts[i])+ // Word's page marks move with the text after the edit.+ val delta = newText.length - old.length+ val marks = p.marks.map { m -> if (m <= pre) m else if (m >= old.length - suf) m + delta else pre }.distinct()+ return p.edited(text = newText, fmts = fmts, marks = marks)+ }++ /** Splits at [at]; the section break (if this paragraph ends a section) moves to the second half. */+ fun split(p: DocPara, at: Int, styles: DocxStyles): Pair<DocPara, DocPara> {+ val a = p.edited(+ text = p.text.substring(0, at), fmts = p.fmts.subList(0, at).toList(),+ pPr = Props.setP(p.pPr, "sectPr", null), marks = p.marks.filter { it < at }+ )+ var bPpr = p.pPr+ if (at >= p.text.length) {+ // Enter at the end of a heading starts its "next" style (Normal), as in Word.+ val sid = Props.p(p.pPr).styleId+ val next = sid?.let { styles.byId[it]?.next }+ if (next != null && next != sid) {+ bPpr = if (next == styles.defaultParagraphId) Props.setP(bPpr, "pStyle", null)+ else Props.setP(bPpr, "pStyle", "<w:pStyle w:val=\"${XmlScan.escape(next)}\"/>")+ }+ }+ val b = DocPara(+ id = DocIds.next(), origin = null, openTag = "<w:p>", pPr = bPpr, extras = "",+ text = p.text.substring(at), fmts = p.fmts.subList(at, p.text.length).toList(), editable = true,+ marks = p.marks.filter { it >= at }.map { it - at }+ )+ return a to b+ }++ fun merge(prev: DocPara, cur: DocPara): DocPara {+ var pPr = prev.pPr+ Props.child(cur.pPr, "sectPr")?.let { pPr = Props.setP(pPr, "sectPr", it) }+ return prev.edited(+ text = prev.text + cur.text, fmts = prev.fmts + cur.fmts, pPr = pPr, extras = prev.extras + cur.extras,+ marks = prev.marks + cur.marks.map { it + prev.text.length }+ )+ }++ /** Rewrites the formatting of [start, end) through [f] (pictures and other objects excepted). */+ fun format(p: DocPara, start: Int, end: Int, f: (CharFmt) -> CharFmt): DocPara {+ if (start >= end) return p+ val cache = HashMap<CharFmt, CharFmt>()+ val fmts = p.fmts.toMutableList()+ var changed = false+ for (i in start.coerceAtLeast(0) until end.coerceAtMost(fmts.size)) {+ val old = fmts[i]+ if (old.obj != null) continue+ val n = cache.getOrPut(old) { f(old) }+ if (n != old) { fmts[i] = n; changed = true }+ }+ return if (changed) p.edited(fmts = fmts) else p+ }++ // ── run properties ─────────────────────────────────────────────────────────++ enum class Toggle { BOLD, ITALIC, UNDERLINE, STRIKE, SUPERSCRIPT, SUBSCRIPT }++ /** Character properties the paragraph and character styles give, before direct formatting. */+ fun styleProps(p: DocPara, f: CharFmt, styles: DocxStyles): RProps {+ val base = styles.paragraphStyle(Props.p(p.pPr).styleId).second+ val rs = Props.r(f.rPr).rStyle+ return if (rs != null) styles.characterStyle(rs).over(base) else base+ }++ fun effective(p: DocPara, f: CharFmt, styles: DocxStyles): RProps = Props.r(f.rPr).over(styleProps(p, f, styles))++ fun toggle(p: DocPara, f: CharFmt, styles: DocxStyles, t: Toggle, on: Boolean): CharFmt {+ val inherited = styleProps(p, f, styles)+ var r = f.rPr+ fun set(local: String, onXml: String, offXml: String, styleOn: Boolean) {+ r = Props.setR(r, local, if (on == styleOn) null else if (on) onXml else offXml)+ }+ when (t) {+ Toggle.BOLD -> {+ set("b", "<w:b/>", "<w:b w:val=\"0\"/>", inherited.bold == true)+ set("bCs", "<w:bCs/>", "<w:bCs w:val=\"0\"/>", inherited.bold == true)+ }+ Toggle.ITALIC -> {+ set("i", "<w:i/>", "<w:i w:val=\"0\"/>", inherited.italic == true)+ set("iCs", "<w:iCs/>", "<w:iCs w:val=\"0\"/>", inherited.italic == true)+ }+ Toggle.UNDERLINE -> set("u", "<w:u w:val=\"single\"/>", "<w:u w:val=\"none\"/>", inherited.underline == true)+ Toggle.STRIKE -> {+ r = Props.setR(r, "dstrike", null)+ set("strike", "<w:strike/>", "<w:strike w:val=\"0\"/>", inherited.strike == true)+ }+ Toggle.SUPERSCRIPT -> r = Props.setR(r, "vertAlign", if (on) "<w:vertAlign w:val=\"superscript\"/>" else null)+ Toggle.SUBSCRIPT -> r = Props.setR(r, "vertAlign", if (on) "<w:vertAlign w:val=\"subscript\"/>" else null)+ }+ return f.copy(rPr = r)+ }++ fun withSize(f: CharFmt, halfPoints: Int): CharFmt {+ var r = Props.setR(f.rPr, "sz", "<w:sz w:val=\"$halfPoints\"/>")+ r = Props.setR(r, "szCs", "<w:szCs w:val=\"$halfPoints\"/>")+ return f.copy(rPr = r)+ }++ /** [argb] null → automatic colour. */+ fun withColor(f: CharFmt, argb: Int?): CharFmt =+ f.copy(rPr = Props.setR(f.rPr, "color", argb?.let { "<w:color w:val=\"${Props.hex6(it)}\"/>" }))++ /** A named Word highlight when the colour is one, run shading otherwise; null clears both. */+ fun withHighlight(f: CharFmt, argb: Int?): CharFmt {+ var r = Props.setR(f.rPr, "highlight", null)+ r = Props.setR(r, "shd", null)+ if (argb != null) {+ val name = HighlightColors.entries.firstOrNull { (it.value and 0xFFFFFF) == (argb and 0xFFFFFF) }?.key+ r = if (name != null) Props.setR(r, "highlight", "<w:highlight w:val=\"$name\"/>")+ else Props.setR(r, "shd", "<w:shd w:val=\"clear\" w:color=\"auto\" w:fill=\"${Props.hex6(argb)}\"/>")+ }+ return f.copy(rPr = r)+ }++ fun withFont(f: CharFmt, font: String): CharFmt {+ val e = XmlScan.escape(font)+ return f.copy(rPr = Props.setR(f.rPr, "rFonts", "<w:rFonts w:ascii=\"$e\" w:hAnsi=\"$e\" w:cs=\"$e\"/>"))+ }++ fun cleared(f: CharFmt): CharFmt = f.copy(rPr = "")++ // ── paragraph properties ───────────────────────────────────────────────────++ fun withStyle(p: DocPara, styleId: String?, styles: DocxStyles): DocPara {+ val sid = styleId?.takeIf { it != styles.defaultParagraphId }+ var pPr = Props.setP(p.pPr, "pStyle", sid?.let { "<w:pStyle w:val=\"${XmlScan.escape(it)}\"/>" })+ // A heading's own size/colour shows only once the text's direct size and colour step aside,+ // the way Word's style gallery behaves for runs formatted by hand.+ val fmts = p.fmts.map { f ->+ if (f.obj != null) f else {+ var r = Props.setR(f.rPr, "sz", null)+ r = Props.setR(r, "szCs", null)+ r = Props.setR(r, "color", null)+ r = Props.setR(r, "rFonts", null)+ if (r == f.rPr) f else f.copy(rPr = r)+ }+ }+ // List paragraphs keep their list; others drop a stale indent left by the old style.+ if (Props.p(pPr).numId == null) pPr = Props.setP(pPr, "ind", null)+ return p.edited(pPr = pPr, fmts = fmts)+ }++ /** "left", "center", "right" or "both". */+ fun withAlign(p: DocPara, jc: String): DocPara =+ p.edited(pPr = Props.setP(p.pPr, "jc", if (jc == "left") null else "<w:jc w:val=\"$jc\"/>"))++ /** Sets (or with [numId] null, removes) list membership. */+ fun withList(p: DocPara, numId: Int?, styles: DocxStyles, ilvl: Int = 0): DocPara {+ val styleList = styles.paragraphStyle(Props.p(p.pPr).styleId).first.numId.let { it != null && it != 0 }+ val numPr = when {+ numId != null -> "<w:numPr><w:ilvl w:val=\"$ilvl\"/><w:numId w:val=\"$numId\"/></w:numPr>"+ // The style itself makes a list: only an explicit "no list" (numId 0) takes it out.+ styleList -> "<w:numPr><w:ilvl w:val=\"0\"/><w:numId w:val=\"0\"/></w:numPr>"+ else -> null+ }+ var pPr = Props.setP(p.pPr, "numPr", numPr)+ pPr = Props.setP(pPr, "ind", null)+ return p.edited(pPr = pPr)+ }++ fun withLeftIndent(p: DocPara, left: Int): DocPara {+ val old = Props.child(p.pPr, "ind")+ val keep = old?.let { XmlScan.scan(it).children.firstOrNull() }+ val sb = StringBuilder("<w:ind w:left=\"").append(left.coerceAtLeast(0)).append('"')+ if (keep != null) for (a in listOf("right", "firstLine", "hanging")) keep.attr(old, a)?.let { sb.append(" w:").append(a).append("=\"").append(it).append('"') }+ sb.append("/>")+ return p.edited(pPr = Props.setP(p.pPr, "ind", if (left <= 0 && keep == null) null else sb.toString()))+ }++ /** Adds Word's built-in definition of a gallery style the document doesn't have yet. */+ fun ensureStyle(styles: DocxStyles, name: String): String? {+ styles.byName(name)?.let { return it.id }+ val def = BuiltInStyles[name] ?: return null+ var id = def.first+ var n = 1+ while (styles.byId.containsKey(id)) id = def.first + (n++)+ val base = styles.defaultParagraphId+ val basedOn = if (base != null) "<w:basedOn w:val=\"${XmlScan.escape(base)}\"/><w:next w:val=\"${XmlScan.escape(base)}\"/>" else ""+ val xml = "<w:style w:type=\"paragraph\" w:styleId=\"$id\"><w:name w:val=\"${name.lowercase().let { if (it.startsWith("heading")) it else name }}\"/>$basedOn" ++ "<w:qFormat/>${def.second}${def.third}</w:style>"+ styles.added.add(xml)+ styles.byId[id] = StyleDef(id, name, "paragraph", base, base, def.second, def.third, "", false, false)+ styles.invalidate()+ return id+ }++ private val major = "<w:rFonts w:asciiTheme=\"majorHAnsi\" w:eastAsiaTheme=\"majorEastAsia\" w:hAnsiTheme=\"majorHAnsi\" w:cstheme=\"majorBidi\"/>"++ /** name → (style id, pPr, rPr), Word 2016's defaults. */+ val BuiltInStyles: Map<String, Triple<String, String, String>> = linkedMapOf(+ "Title" to Triple("Title",+ "<w:pPr><w:spacing w:after=\"0\" w:line=\"240\" w:lineRule=\"auto\"/><w:contextualSpacing/></w:pPr>",+ "<w:rPr>$major<w:spacing w:val=\"-10\"/><w:kern w:val=\"28\"/><w:sz w:val=\"56\"/><w:szCs w:val=\"56\"/></w:rPr>"),+ "Subtitle" to Triple("Subtitle",+ "<w:pPr><w:spacing w:after=\"160\"/></w:pPr>",+ "<w:rPr><w:color w:val=\"5A5A5A\"/><w:spacing w:val=\"15\"/><w:sz w:val=\"22\"/><w:szCs w:val=\"22\"/></w:rPr>"),+ "heading 1" to Triple("Heading1",+ "<w:pPr><w:keepNext/><w:keepLines/><w:spacing w:before=\"240\" w:after=\"0\"/><w:outlineLvl w:val=\"0\"/></w:pPr>",+ "<w:rPr>$major<w:color w:val=\"2F5496\"/><w:sz w:val=\"32\"/><w:szCs w:val=\"32\"/></w:rPr>"),+ "heading 2" to Triple("Heading2",+ "<w:pPr><w:keepNext/><w:keepLines/><w:spacing w:before=\"40\" w:after=\"0\"/><w:outlineLvl w:val=\"1\"/></w:pPr>",+ "<w:rPr>$major<w:color w:val=\"2F5496\"/><w:sz w:val=\"26\"/><w:szCs w:val=\"26\"/></w:rPr>"),+ "heading 3" to Triple("Heading3",+ "<w:pPr><w:keepNext/><w:keepLines/><w:spacing w:before=\"40\" w:after=\"0\"/><w:outlineLvl w:val=\"2\"/></w:pPr>",+ "<w:rPr>$major<w:color w:val=\"1F3763\"/><w:sz w:val=\"24\"/><w:szCs w:val=\"24\"/></w:rPr>"),+ "Quote" to Triple("Quote",+ "<w:pPr><w:spacing w:before=\"200\" w:after=\"160\"/><w:ind w:left=\"864\" w:right=\"864\"/><w:jc w:val=\"center\"/></w:pPr>",+ "<w:rPr><w:i/><w:iCs/><w:color w:val=\"404040\"/></w:rPr>")+ )+}diff --git a/app/src/main/java/com/chethan616/clearpdf/docx/DocxModel.kt b/app/src/main/java/com/chethan616/clearpdf/docx/DocxModel.ktnew file mode 100644index 0000000..baf1156--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/docx/DocxModel.kt@@ -0,0 +1,154 @@+package com.chethan616.clearpdf.docx++import androidx.compose.runtime.Immutable++/**+ * One character's formatting: its run's raw `<w:rPr>` (kept verbatim, edited element by element),+ * the `<w:hyperlink …>` start tag wrapping it, or — for [obj] — a whole run kept verbatim (a+ * picture, a page break, a footnote mark…) that stands as a single U+FFFC in the paragraph text.+ */+@Immutable+data class CharFmt(val rPr: String, val link: String? = null, val obj: String? = null) {+ companion object {+ val Plain = CharFmt("")+ }+}++/** U+FFFC stands for an object run inside [DocPara.text]. */+const val OBJ_CHAR = '\uFFFC'++sealed interface DocBlock {+ val id: Long+}++/**+ * A paragraph. [origin] is its original XML, written back untouched while it is non-null; any+ * edit produces a copy without it, and only those are serialized again.+ */+@Immutable+class DocPara(+ override val id: Long,+ val origin: String?,+ val openTag: String,+ val pPr: String,+ /** Bookmarks and similar markers; re-emitted at the start of the paragraph. */+ val extras: String,+ val text: String,+ /** One entry per char of [text]. */+ val fmts: List<CharFmt>,+ val editable: Boolean,+ /**+ * Where Word started a new page inside this paragraph when it last laid the file out+ * (`w:lastRenderedPageBreak`), as offsets into [text]. The viewer shows Word's pages by them.+ */+ val marks: List<Int> = emptyList()+) : DocBlock {+ fun edited(+ text: String = this.text,+ fmts: List<CharFmt> = this.fmts,+ pPr: String = this.pPr,+ id: Long = this.id,+ openTag: String = this.openTag,+ extras: String = this.extras,+ marks: List<Int> = this.marks+ ): DocPara = DocPara(id, null, openTag, pPr, extras, text, fmts, editable, marks.filter { it in 0..text.length })++ val isEmpty: Boolean get() = text.isEmpty()+}++sealed interface TableItem+sealed interface RowItem++/** Verbatim XML: section properties, content controls, bookmarks between blocks… */+@Immutable+class DocRaw(+ override val id: Long,+ val xml: String,+ /** Read-only content to show for it (a table of contents' paragraphs, a cover page…). */+ val preview: List<DocBlock> = emptyList()+) : DocBlock, TableItem, RowItem++@Immutable+class DocTable(+ override val id: Long,+ val origin: String?,+ /** Start tag through `tblGrid`, verbatim. */+ val head: String,+ val items: List<TableItem>,+ val tail: String,+ /** Grid column widths, twips. */+ val grid: List<Int>,+ val tblPr: String+) : DocBlock {+ val rows: List<DocRow> get() = items.filterIsInstance<DocRow>()+ fun withItems(items: List<TableItem>) = DocTable(id, null, head, items, tail, grid, tblPr)+}++@Immutable+class DocRow(val id: Long, val head: String, val items: List<RowItem>, val tail: String, val trPr: String) : TableItem {+ val cells: List<DocCell> get() = items.filterIsInstance<DocCell>()+ fun withItems(items: List<RowItem>) = DocRow(id, head, items, tail, trPr)+}++@Immutable+class DocCell(val id: Long, val head: String, val blocks: List<DocBlock>, val tail: String, val tcPr: String) : RowItem {+ fun withBlocks(blocks: List<DocBlock>) = DocCell(id, head, blocks, tail, tcPr)+}++/** Page size and margins of the (last) section, twips. */+@Immutable+data class PageSetup(+ val width: Int = 11906,+ val height: Int = 16838,+ val left: Int = 1440,+ val right: Int = 1440,+ val top: Int = 1440,+ val bottom: Int = 1440+)++@Immutable+class DocState(val blocks: List<DocBlock>)++/** Walks every paragraph, tables and previews included, in reading order. */+fun forEachPara(blocks: List<DocBlock>, includePreview: Boolean = true, f: (DocPara) -> Unit) {+ for (b in blocks) when (b) {+ is DocPara -> f(b)+ is DocTable -> for (r in b.rows) for (c in r.cells) forEachPara(c.blocks, includePreview, f)+ is DocRaw -> if (includePreview) forEachPara(b.preview, true, f)+ }+}++fun findPara(blocks: List<DocBlock>, id: Long): DocPara? {+ for (b in blocks) when (b) {+ is DocPara -> if (b.id == id) return b+ is DocTable -> for (r in b.rows) for (c in r.cells) findPara(c.blocks, id)?.let { return it }+ is DocRaw -> {}+ }+ return null+}++/**+ * Rebuilds only the path down to the block list that holds paragraph [id], replacing that list+ * with [f]'s result. Everything else keeps its identity, so unchanged paragraphs are neither+ * re-serialized nor recomposed. Null when [id] isn't in an editable container.+ */+fun mapContainerOf(blocks: List<DocBlock>, id: Long, f: (List<DocBlock>) -> List<DocBlock>): List<DocBlock>? {+ if (blocks.any { it is DocPara && it.id == id }) return f(blocks)+ for ((i, b) in blocks.withIndex()) {+ if (b !is DocTable) continue+ for ((ri, item) in b.items.withIndex()) {+ if (item !is DocRow) continue+ for ((ci, cellItem) in item.items.withIndex()) {+ if (cellItem !is DocCell) continue+ val inner = mapContainerOf(cellItem.blocks, id, f) ?: continue+ val row = item.withItems(item.items.toMutableList().also { it[ci] = cellItem.withBlocks(inner) })+ val table = b.withItems(b.items.toMutableList().also { it[ri] = row })+ return blocks.toMutableList().also { it[i] = table }+ }+ }+ }+ return null+}++fun replacePara(blocks: List<DocBlock>, para: DocPara): List<DocBlock>? =+ mapContainerOf(blocks, para.id) { list -> list.map { if (it is DocPara && it.id == para.id) para else it } }diff --git a/app/src/main/java/com/chethan616/clearpdf/docx/DocxObjects.kt b/app/src/main/java/com/chethan616/clearpdf/docx/DocxObjects.ktnew file mode 100644index 0000000..b5cc2bf--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/docx/DocxObjects.kt@@ -0,0 +1,62 @@+package com.chethan616.clearpdf.docx++/** What an object run is, for drawing it: a picture, a text box's content, or a page break. */+class ObjInfo(+ /** Relationship id of the picture. */+ val imageRid: String?,+ /** Size in points (0 when unknown). */+ val widthPt: Float,+ val heightPt: Float,+ val textBox: List<DocBlock>,+ val pageBreak: Boolean,+ /** A floating picture's horizontal alignment ("left", "center", "right"), when it gives one. */+ val hAlign: String? = null+)++object DocxObjects {+ private val cache = HashMap<String, ObjInfo>()++ fun info(obj: String): ObjInfo = synchronized(cache) { cache[obj] } ?: parse(obj).also {+ synchronized(cache) { if (cache.size > 2000) cache.clear(); cache[obj] = it }+ }++ fun isPageBreak(obj: String?): Boolean =+ obj != null && obj.contains("br") && (obj.contains("type=\"page\"") || obj.contains("type='page'"))++ private fun parse(obj: String): ObjInfo {+ val root = XmlScan.scan(obj)+ val blip = root.descendant("blip")+ var rid = blip?.attr(obj, "embed")+ var w = 0f+ var h = 0f+ root.descendant("extent")?.let { e ->+ w = (e.attr(obj, "cx")?.toFloatOrNull() ?: 0f) / 12700f+ h = (e.attr(obj, "cy")?.toFloatOrNull() ?: 0f) / 12700f+ }+ if (rid == null) {+ // Legacy VML picture: <v:imagedata r:id> inside a shape sized by its CSS style.+ root.descendant("imagedata")?.let { img ->+ rid = img.attr(obj, "id")+ val style = generateSequence(img.parent) { it.parent }.firstNotNullOfOrNull { it.attr(obj, "style") } ?: ""+ w = cssPt(style, "width")+ h = cssPt(style, "height")+ }+ }+ val txbx = root.descendant("txbxContent")+ val text = if (txbx != null) DocxReader.Ctx(obj).container(txbx.children, readOnly = true) else emptyList()+ val hAlign = root.descendant("positionH")?.child("align")?.let { XmlScan.unescape(it.inner(obj)).trim() }+ return ObjInfo(rid, w, h, text, isPageBreak(obj), hAlign)+ }++ private fun cssPt(style: String, key: String): Float {+ val m = Regex("(?:^|;)\\s*$key\\s*:\\s*([0-9.]+)\\s*(pt|px|in|cm|mm)?").find(style) ?: return 0f+ val v = m.groupValues[1].toFloatOrNull() ?: return 0f+ return when (m.groupValues[2]) {+ "px" -> v * 0.75f+ "in" -> v * 72f+ "cm" -> v * 28.3465f+ "mm" -> v * 2.83465f+ else -> v+ }+ }+}diff --git a/app/src/main/java/com/chethan616/clearpdf/docx/DocxProps.kt b/app/src/main/java/com/chethan616/clearpdf/docx/DocxProps.ktnew file mode 100644index 0000000..824b978--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/docx/DocxProps.kt@@ -0,0 +1,478 @@+package com.chethan616.clearpdf.docx++/** Character properties of an `<w:rPr>`; null fields are unset (inherit). Sizes in half-points. */+data class RProps(+ val bold: Boolean? = null,+ val italic: Boolean? = null,+ val underline: Boolean? = null,+ val strike: Boolean? = null,+ val size: Int? = null,+ /** ARGB, or 0 for "auto". */+ val color: Int? = null,+ /** ARGB of a highlight or run shading. */+ val highlight: Int? = null,+ val font: String? = null,+ val fontTheme: String? = null,+ val caps: Boolean? = null,+ val smallCaps: Boolean? = null,+ val vertAlign: String? = null,+ val vanish: Boolean? = null,+ val rStyle: String? = null+) {+ fun over(base: RProps): RProps = RProps(+ bold ?: base.bold, italic ?: base.italic, underline ?: base.underline, strike ?: base.strike,+ size ?: base.size, color ?: base.color, highlight ?: base.highlight,+ if (font != null || fontTheme != null) font else base.font,+ if (font != null || fontTheme != null) fontTheme else base.fontTheme,+ caps ?: base.caps, smallCaps ?: base.smallCaps, vertAlign ?: base.vertAlign, vanish ?: base.vanish,+ rStyle ?: base.rStyle+ )+}++/** Paragraph properties of a `<w:pPr>`; lengths in twips. */+data class PProps(+ val styleId: String? = null,+ val align: String? = null,+ val before: Int? = null,+ val after: Int? = null,+ val line: Int? = null,+ val lineRule: String? = null,+ val left: Int? = null,+ val right: Int? = null,+ val firstLine: Int? = null,+ val hanging: Int? = null,+ val numId: Int? = null,+ val ilvl: Int? = null,+ val bidi: Boolean? = null,+ val shading: Int? = null,+ val pageBreakBefore: Boolean? = null,+ val contextual: Boolean? = null,+ val borderBottom: Boolean? = null+) {+ fun over(base: PProps): PProps = PProps(+ styleId ?: base.styleId, align ?: base.align, before ?: base.before, after ?: base.after,+ line ?: base.line, lineRule ?: base.lineRule, left ?: base.left, right ?: base.right,+ if (firstLine != null || hanging != null) firstLine else base.firstLine,+ if (firstLine != null || hanging != null) hanging else base.hanging,+ numId ?: base.numId, ilvl ?: base.ilvl, bidi ?: base.bidi, shading ?: base.shading,+ pageBreakBefore ?: base.pageBreakBefore, contextual ?: base.contextual, borderBottom ?: base.borderBottom+ )+}++/** Word's named highlight colours. */+val HighlightColors: Map<String, Int> = linkedMapOf(+ "yellow" to 0xFFFFFF00.toInt(), "green" to 0xFF00FF00.toInt(), "cyan" to 0xFF00FFFF.toInt(),+ "magenta" to 0xFFFF00FF.toInt(), "blue" to 0xFF0000FF.toInt(), "red" to 0xFFFF0000.toInt(),+ "darkBlue" to 0xFF000080.toInt(), "darkCyan" to 0xFF008080.toInt(), "darkGreen" to 0xFF008000.toInt(),+ "darkMagenta" to 0xFF800080.toInt(), "darkRed" to 0xFF800000.toInt(), "darkYellow" to 0xFF808000.toInt(),+ "darkGray" to 0xFF808080.toInt(), "lightGray" to 0xFFC0C0C0.toInt(), "black" to 0xFF000000.toInt(),+ "white" to 0xFFFFFFFF.toInt()+)++internal object Props {++ private val rCache = HashMap<String, RProps>()+ private val pCache = HashMap<String, PProps>()++ fun hex(v: String?): Int? {+ if (v == null || v.equals("auto", true)) return null+ val n = v.toLongOrNull(16) ?: return null+ return (0xFF000000 or (n and 0xFFFFFF)).toInt()+ }++ private fun onOff(xml: String, n: XNode): Boolean {+ val v = n.attr(xml, "val") ?: return true+ return !(v == "0" || v.equals("false", true) || v.equals("off", true))+ }++ /** Parses an `<w:rPr>…</w:rPr>` (or the empty string). */+ fun r(rPr: String): RProps {+ if (rPr.isEmpty()) return RProps()+ synchronized(rCache) { rCache[rPr]?.let { return it } }+ val root = XmlScan.scan(rPr).children.firstOrNull() ?: return RProps()+ var p = RProps()+ for (c in root.children) {+ p = when (c.local) {+ "b" -> p.copy(bold = onOff(rPr, c))+ "i" -> p.copy(italic = onOff(rPr, c))+ "u" -> p.copy(underline = (c.attr(rPr, "val") ?: "single") != "none")+ "strike", "dstrike" -> if (onOff(rPr, c)) p.copy(strike = true) else p.copy(strike = p.strike ?: false)+ "sz" -> c.attr(rPr, "val")?.toFloatOrNull()?.let { p.copy(size = it.toInt()) } ?: p+ "color" -> {+ val v = c.attr(rPr, "val")+ p.copy(color = if (v == null || v.equals("auto", true)) 0 else hex(v) ?: 0)+ }+ "highlight" -> {+ val v = c.attr(rPr, "val")+ if (v == null || v == "none") p.copy(highlight = 0) else p.copy(highlight = HighlightColors[v] ?: p.highlight)+ }+ "shd" -> {+ val fill = hex(c.attr(rPr, "fill"))+ if (fill != null && p.highlight == null) p.copy(highlight = fill) else p+ }+ "rFonts" -> {+ val f = c.attr(rPr, "ascii") ?: c.attr(rPr, "hAnsi") ?: c.attr(rPr, "cs")+ val t = c.attr(rPr, "asciiTheme") ?: c.attr(rPr, "hAnsiTheme")+ if (f != null || t != null) p.copy(font = f, fontTheme = if (f == null) t else null) else p+ }+ "caps" -> p.copy(caps = onOff(rPr, c))+ "smallCaps" -> p.copy(smallCaps = onOff(rPr, c))+ "vertAlign" -> p.copy(vertAlign = c.attr(rPr, "val"))+ "vanish" -> p.copy(vanish = onOff(rPr, c))+ "rStyle" -> p.copy(rStyle = c.attr(rPr, "val"))+ else -> p+ }+ }+ synchronized(rCache) { if (rCache.size > 4000) rCache.clear(); rCache[rPr] = p }+ return p+ }++ /** Parses an `<w:pPr>…</w:pPr>` (or the empty string). */+ fun p(pPr: String): PProps {+ if (pPr.isEmpty()) return PProps()+ synchronized(pCache) { pCache[pPr]?.let { return it } }+ val root = XmlScan.scan(pPr).children.firstOrNull() ?: return PProps()+ var p = PProps()+ fun tw(n: XNode, a: String): Int? = n.attr(pPr, a)?.toFloatOrNull()?.toInt()+ for (c in root.children) {+ p = when (c.local) {+ "pStyle" -> p.copy(styleId = c.attr(pPr, "val"))+ "jc" -> p.copy(align = c.attr(pPr, "val"))+ "spacing" -> p.copy(+ before = tw(c, "before") ?: p.before,+ after = tw(c, "after") ?: p.after,+ line = tw(c, "line") ?: p.line,+ lineRule = c.attr(pPr, "lineRule") ?: p.lineRule+ )+ "ind" -> p.copy(+ left = tw(c, "left") ?: tw(c, "start") ?: p.left,+ right = tw(c, "right") ?: tw(c, "end") ?: p.right,+ firstLine = tw(c, "firstLine") ?: if (c.attr(pPr, "hanging") != null) 0 else p.firstLine,+ hanging = tw(c, "hanging") ?: if (c.attr(pPr, "firstLine") != null) 0 else p.hanging+ )+ "numPr" -> p.copy(+ numId = c.child("numId")?.attr(pPr, "val")?.toIntOrNull() ?: p.numId,+ ilvl = c.child("ilvl")?.attr(pPr, "val")?.toIntOrNull() ?: p.ilvl+ )+ "bidi" -> p.copy(bidi = onOff(pPr, c))+ "shd" -> p.copy(shading = hex(c.attr(pPr, "fill")))+ "pageBreakBefore" -> p.copy(pageBreakBefore = onOff(pPr, c))+ "contextualSpacing" -> p.copy(contextual = onOff(pPr, c))+ "pBdr" -> p.copy(borderBottom = c.child("bottom")?.attr(pPr, "val")?.let { it != "none" && it != "nil" })+ else -> p+ }+ }+ synchronized(pCache) { if (pCache.size > 4000) pCache.clear(); pCache[pPr] = p }+ return p+ }++ // ── editing property elements ──────────────────────────────────────────────++ val RPR_ORDER = listOf(+ "rStyle", "rFonts", "b", "bCs", "i", "iCs", "caps", "smallCaps", "strike", "dstrike", "outline", "shadow",+ "emboss", "imprint", "noProof", "snapToGrid", "vanish", "webHidden", "color", "spacing", "w", "kern",+ "position", "sz", "szCs", "highlight", "u", "effect", "bdr", "shd", "fitText", "vertAlign", "rtl", "cs",+ "em", "lang", "eastAsianLayout", "specVanish", "oMath"+ )++ val PPR_ORDER = listOf(+ "pStyle", "keepNext", "keepLines", "pageBreakBefore", "framePr", "widowControl", "numPr",+ "suppressLineNumbers", "pBdr", "shd", "tabs", "suppressAutoHyphens", "kinsoku", "wordWrap",+ "overflowPunct", "topLinePunct", "autoSpaceDE", "autoSpaceDN", "bidi", "adjustRightInd", "snapToGrid",+ "spacing", "ind", "contextualSpacing", "mirrorIndents", "suppressOverlap", "jc", "textDirection",+ "textAlignment", "textboxTightWrap", "outlineLvl", "divId", "cnfStyle", "rPr", "sectPr", "pPrChange"+ )++ /**+ * Returns [props] (an `<w:rPr>` or `<w:pPr>`, possibly empty) with every child named [local]+ * removed and [element] (when non-null) inserted where the schema's sequence puts it. Word+ * rejects property elements out of order, so this never appends blindly.+ */+ fun setChild(props: String, wrapper: String, order: List<String>, local: String, element: String?): String {+ val root = if (props.isEmpty()) null else XmlScan.scan(props).children.firstOrNull()+ val children = ArrayList<Pair<String, String>>()+ if (root != null) for (c in root.children) if (c.local != local) children.add(c.local to c.text(props))+ if (element != null) {+ val idx = order.indexOf(local)+ var at = children.size+ for ((k, ch) in children.withIndex()) {+ val o = order.indexOf(ch.first)+ if (o < 0 || o > idx) { at = k; break }+ }+ children.add(at, local to element)+ }+ if (children.isEmpty()) return ""+ val open = root?.startTag(props)?.let { if (it.endsWith("/>")) it.dropLast(2) + ">" else it } ?: "<$wrapper>"+ val name = root?.name ?: wrapper+ return buildString {+ append(open)+ for (c in children) append(c.second)+ append("</").append(name).append('>')+ }+ }++ fun setR(rPr: String, local: String, element: String?) = setChild(rPr, "w:rPr", RPR_ORDER, local, element)+ fun setP(pPr: String, local: String, element: String?) = setChild(pPr, "w:pPr", PPR_ORDER, local, element)++ /** The raw XML of the child [local] of a props element, or null. */+ fun child(props: String, local: String): String? {+ if (props.isEmpty()) return null+ val root = XmlScan.scan(props).children.firstOrNull() ?: return null+ return root.child(local)?.text(props)+ }++ fun hex6(argb: Int): String = String.format("%06X", argb and 0xFFFFFF)+}++class StyleDef(+ val id: String,+ val name: String,+ val type: String,+ val basedOn: String?,+ val next: String?,+ val pPr: String,+ val rPr: String,+ val tblPr: String,+ val isDefault: Boolean,+ val hidden: Boolean,+ /** Table styles: conditional formats (firstRow, band1Horz…) → (tcPr, rPr). */+ val conditional: Map<String, Pair<String, String>> = emptyMap()+)++/** styles.xml: the style table and document defaults. Styles added while editing go in [added]. */+class DocxStyles(+ val defaultRPr: String,+ val defaultPPr: String,+ val byId: MutableMap<String, StyleDef>,+ val xml: String?+) {+ val added = ArrayList<String>()++ val defaultParagraphId: String? by lazy {+ byId.values.firstOrNull { it.type == "paragraph" && it.isDefault }?.id ?: byId["Normal"]?.id+ }++ fun byName(name: String): StyleDef? = byId.values.firstOrNull { it.name.equals(name, ignoreCase = true) }++ /** The style and its `basedOn` ancestors, root first. */+ fun chain(id: String?): List<StyleDef> {+ val out = ArrayList<StyleDef>()+ var cur = id?.let { byId[it] }+ var guard = 0+ while (cur != null && guard++ < 16) {+ out.add(0, cur)+ cur = cur.basedOn?.let { byId[it] }+ }+ return out+ }++ private val pCache = HashMap<String?, Pair<PProps, RProps>>()++ /** Paragraph and character properties a paragraph style gives (defaults included). */+ fun paragraphStyle(id: String?): Pair<PProps, RProps> = synchronized(pCache) {+ pCache.getOrPut(id) {+ var pp = Props.p(defaultPPr)+ var rp = Props.r(defaultRPr)+ val chain = chain(id ?: defaultParagraphId).ifEmpty { chain(defaultParagraphId) }+ for (s in chain) {+ pp = Props.p(s.pPr).over(pp)+ rp = Props.r(s.rPr).over(rp)+ }+ pp to rp+ }+ }++ fun characterStyle(id: String?): RProps {+ if (id == null) return RProps()+ var rp = RProps()+ for (s in chain(id)) rp = Props.r(s.rPr).over(rp)+ return rp+ }++ fun invalidate() = synchronized(pCache) { pCache.clear() }++ companion object {+ fun parse(xml: String?): DocxStyles {+ if (xml == null) return DocxStyles("", "", HashMap(), null)+ val root = XmlScan.scan(xml).children.firstOrNull { it.local == "styles" }+ ?: return DocxStyles("", "", HashMap(), xml)+ val defaults = root.child("docDefaults")+ val dr = defaults?.child("rPrDefault")?.child("rPr")?.text(xml) ?: ""+ val dp = defaults?.child("pPrDefault")?.child("pPr")?.text(xml) ?: ""+ val map = LinkedHashMap<String, StyleDef>()+ for (s in root.childrenNamed("style")) {+ val id = s.attr(xml, "styleId") ?: continue+ map[id] = StyleDef(+ id = id,+ name = s.child("name")?.attr(xml, "val") ?: id,+ type = s.attr(xml, "type") ?: "paragraph",+ basedOn = s.child("basedOn")?.attr(xml, "val"),+ next = s.child("next")?.attr(xml, "val"),+ pPr = s.child("pPr")?.text(xml) ?: "",+ rPr = s.child("rPr")?.text(xml) ?: "",+ tblPr = s.child("tblPr")?.text(xml) ?: "",+ isDefault = s.attr(xml, "default").let { it == "1" || it == "true" },+ hidden = s.child("semiHidden") != null,+ conditional = s.childrenNamed("tblStylePr").mapNotNull { c ->+ val type = c.attr(xml, "type") ?: return@mapNotNull null+ type to ((c.child("tcPr")?.text(xml) ?: "") to (c.child("rPr")?.text(xml) ?: ""))+ }.toMap()+ )+ }+ return DocxStyles(dr, dp, map, xml)+ }+ }+}++class NumLevel(val start: Int, val fmt: String, val text: String, val pPr: String, val rPr: String)++/** numbering.xml: list definitions. Lists created while editing go in [addedAbstract] / [addedNums]. */+class DocxNumbering(+ val abstracts: MutableMap<Int, Map<Int, NumLevel>>,+ /** numId → abstractNumId. */+ val nums: MutableMap<Int, Int>,+ /** numId → (ilvl → start override). */+ val overrides: MutableMap<Int, Map<Int, Int>>,+ val xml: String?+) {+ val addedAbstract = ArrayList<String>()+ val addedNums = ArrayList<String>()++ fun level(numId: Int, ilvl: Int): NumLevel? = nums[numId]?.let { abstracts[it] }?.get(ilvl)++ /** A list of the given kind made for this document while editing (created once). */+ fun ensureList(bullet: Boolean): Int {+ val key = if (bullet) "bullet" else "decimal"+ created[key]?.let { return it }+ val absId = ((abstracts.keys.maxOrNull() ?: 0) + 1).coerceAtLeast(9000)+ val numId = (nums.keys.maxOrNull() ?: 0) + 1+ val levels = HashMap<Int, NumLevel>()+ val sb = StringBuilder("<w:abstractNum w:abstractNumId=\"$absId\"><w:multiLevelType w:val=\"hybridMultilevel\"/>")+ val bullets = listOf("•", "◦", "▪")+ val decimals = listOf("decimal", "lowerLetter", "lowerRoman")+ for (l in 0..8) {+ val left = 720 * (l + 1)+ val fmt = if (bullet) "bullet" else decimals[l % 3]+ val text = if (bullet) bullets[l % 3] else "%${l + 1}."+ val pPr = "<w:pPr><w:ind w:left=\"$left\" w:hanging=\"360\"/></w:pPr>"+ val rPr = if (bullet) "<w:rPr><w:rFonts w:ascii=\"Arial\" w:hAnsi=\"Arial\" w:hint=\"default\"/></w:rPr>" else ""+ levels[l] = NumLevel(1, fmt, text, pPr, rPr)+ sb.append("<w:lvl w:ilvl=\"$l\"><w:start w:val=\"1\"/><w:numFmt w:val=\"$fmt\"/>")+ .append("<w:lvlText w:val=\"").append(XmlScan.escape(text)).append("\"/><w:lvlJc w:val=\"left\"/>")+ .append(pPr).append(rPr).append("</w:lvl>")+ }+ sb.append("</w:abstractNum>")+ abstracts[absId] = levels+ nums[numId] = absId+ addedAbstract.add(sb.toString())+ addedNums.add("<w:num w:numId=\"$numId\"><w:abstractNumId w:val=\"$absId\"/></w:num>")+ created[key] = numId+ return numId+ }++ private val created = HashMap<String, Int>()++ val modified: Boolean get() = addedNums.isNotEmpty()++ fun isBullet(numId: Int): Boolean = level(numId, 0)?.fmt == "bullet"++ companion object {+ fun parse(xml: String?): DocxNumbering {+ val abstracts = HashMap<Int, Map<Int, NumLevel>>()+ val nums = HashMap<Int, Int>()+ val overrides = HashMap<Int, Map<Int, Int>>()+ if (xml == null) return DocxNumbering(abstracts, nums, overrides, null)+ val root = XmlScan.scan(xml).children.firstOrNull { it.local == "numbering" }+ ?: return DocxNumbering(abstracts, nums, overrides, xml)+ for (a in root.childrenNamed("abstractNum")) {+ val id = a.attr(xml, "abstractNumId")?.toIntOrNull() ?: continue+ val levels = HashMap<Int, NumLevel>()+ for (l in a.childrenNamed("lvl")) {+ val ilvl = l.attr(xml, "ilvl")?.toIntOrNull() ?: continue+ levels[ilvl] = NumLevel(+ start = l.child("start")?.attr(xml, "val")?.toIntOrNull() ?: 1,+ fmt = l.child("numFmt")?.attr(xml, "val") ?: "decimal",+ text = l.child("lvlText")?.attr(xml, "val") ?: "",+ pPr = l.child("pPr")?.text(xml) ?: "",+ rPr = l.child("rPr")?.text(xml) ?: ""+ )+ }+ abstracts[id] = levels+ }+ for (n in root.childrenNamed("num")) {+ val id = n.attr(xml, "numId")?.toIntOrNull() ?: continue+ val abs = n.child("abstractNumId")?.attr(xml, "val")?.toIntOrNull() ?: continue+ nums[id] = abs+ val ov = HashMap<Int, Int>()+ for (o in n.childrenNamed("lvlOverride")) {+ val ilvl = o.attr(xml, "ilvl")?.toIntOrNull() ?: continue+ o.child("startOverride")?.attr(xml, "val")?.toIntOrNull()?.let { ov[ilvl] = it }+ }+ if (ov.isNotEmpty()) overrides[id] = ov+ }+ return DocxNumbering(abstracts, nums, overrides, xml)+ }++ fun format(n: Int, fmt: String): String = when (fmt) {+ "lowerLetter" -> letters(n).lowercase()+ "upperLetter" -> letters(n)+ "lowerRoman" -> roman(n).lowercase()+ "upperRoman" -> roman(n)+ "decimalZero" -> if (n < 10) "0$n" else "$n"+ "none" -> ""+ else -> n.toString()+ }++ private fun letters(n: Int): String {+ if (n <= 0) return ""+ val c = ('A' + (n - 1) % 26)+ return c.toString().repeat((n - 1) / 26 + 1)+ }++ private fun roman(n: Int): String {+ if (n <= 0 || n > 3999) return n.toString()+ val v = intArrayOf(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)+ val s = arrayOf("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I")+ var x = n+ return buildString { for (i in v.indices) while (x >= v[i]) { append(s[i]); x -= v[i] } }+ }++ /** Symbol-font bullets come through as private-use characters. */+ fun bulletGlyph(text: String): String {+ val c = text.firstOrNull() ?: return "•"+ return when (c.code) {+ 0xF0B7, 0xF06C, 0x00B7, 0xF0A8 -> "•"+ 0xF0A7, 0xF0FC -> "▪"+ 0xF0D8, 0xF0E0 -> "➢"+ 0x006F -> "◦"+ 0xF076 -> "❖"+ 0xF0FB -> "✓"+ else -> if (c.code in 0xF000..0xF0FF) "•" else text+ }+ }+ }+}++/** The theme's heading and body fonts. */+class DocxTheme(val major: String?, val minor: String?) {+ fun resolve(themeRef: String?): String? = when {+ themeRef == null -> null+ themeRef.startsWith("major") -> major+ else -> minor+ }++ companion object {+ fun parse(xml: String?): DocxTheme {+ if (xml == null) return DocxTheme(null, null)+ fun latin(tag: String): String? {+ val i = xml.indexOf(tag)+ if (i < 0) return null+ val j = xml.indexOf("latin", i)+ if (j < 0) return null+ val end = xml.indexOf('>', j)+ return XmlScan.attr("<" + xml.substring(j, end + 1), "typeface")?.ifBlank { null }+ }+ return DocxTheme(latin("majorFont"), latin("minorFont"))+ }+ }+}diff --git a/app/src/main/java/com/chethan616/clearpdf/docx/DocxReader.kt b/app/src/main/java/com/chethan616/clearpdf/docx/DocxReader.ktnew file mode 100644index 0000000..a15a1f3--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/docx/DocxReader.kt@@ -0,0 +1,304 @@+package com.chethan616.clearpdf.docx++import java.io.InputStream+import java.util.concurrent.atomic.AtomicLong+import java.util.zip.ZipInputStream++internal object DocIds {+ private val n = AtomicLong(1)+ fun next(): Long = n.getAndIncrement()+}++/** Everything about the opened file the editor needs besides its blocks. */+class DocxPackage(+ val mainPath: String,+ val xml: String,+ /** Offset just past `<w:body>`. */+ val bodyOpenEnd: Int,+ /** Offset of `</w:body>`. */+ val bodyCloseStart: Int,+ val styles: DocxStyles,+ val stylesPath: String,+ val numbering: DocxNumbering,+ val numberingPath: String,+ val theme: DocxTheme,+ /** Relationship id → zip entry path (internal targets only). */+ val rels: Map<String, String>,+ /** Relationship id → URL, for hyperlinks. */+ val links: Map<String, String>,+ val relsPath: String,+ val relsXml: String?,+ val contentTypes: String?,+ /** Zip entry path → bytes, for pictures. */+ val media: Map<String, ByteArray>,+ val page: PageSetup,+ /** False for documents this editor can show but can't safely write (Strict OOXML, odd prefixes). */+ val writable: Boolean+) {+ fun image(rid: String): ByteArray? = rels[rid]?.let { media[it] }+}++/**+ * Reads a .docx into [DocBlock]s. Paragraphs and tables keep their original XML, so whatever the+ * editor doesn't model survives a save byte for byte.+ */+object DocxReader {++ private const val MEDIA_BUDGET = 60L * 1024 * 1024++ fun read(input: InputStream): Pair<DocxPackage, DocState>? {+ val parts = HashMap<String, String>()+ val media = HashMap<String, ByteArray>()+ var mediaBytes = 0L+ ZipInputStream(input).use { zip ->+ while (true) {+ val e = zip.nextEntry ?: break+ val n = e.name.removePrefix("/")+ val lower = n.lowercase()+ if (lower.endsWith(".xml") || lower.endsWith(".rels")) {+ parts[n] = zip.readBytes().toString(Charsets.UTF_8)+ } else if (!e.isDirectory && mediaBytes < MEDIA_BUDGET && isPicture(lower)) {+ val b = zip.readBytes()+ mediaBytes += b.size+ media[n] = b+ }+ }+ }+ val rootRels = parts["_rels/.rels"]+ val mainPath = rootRels?.let { relsOf(it, "") }?.firstOrNull { it.type.endsWith("/officeDocument") }?.target+ ?.takeIf { parts.containsKey(it) } ?: "word/document.xml"+ val xml = parts[mainPath] ?: return null+ val dir = mainPath.substringBeforeLast('/', "")+ val relsPath = (if (dir.isEmpty()) "" else "$dir/") + "_rels/" + mainPath.substringAfterLast('/') + ".rels"+ val relsXml = parts[relsPath]+ val rels = relsXml?.let { relsOf(it, dir) } ?: emptyList()+ val relMap = rels.filter { !it.external }.associate { it.id to it.target }+ val stylesPath = rels.firstOrNull { it.type.endsWith("/styles") }?.target ?: join(dir, "styles.xml")+ val numberingPath = rels.firstOrNull { it.type.endsWith("/numbering") }?.target ?: join(dir, "numbering.xml")+ val themePath = rels.firstOrNull { it.type.endsWith("/theme") }?.target++ val root = XmlScan.scan(xml)+ val document = root.children.firstOrNull { it.local == "document" } ?: return null+ val body = document.child("body") ?: return null+ val strict = xml.contains("purl.oclc.org/ooxml/wordprocessingml")+ val writable = !strict && body.name == "w:body" && body.end > body.startTagEnd++ val ctx = Ctx(xml)+ val blocks = ctx.container(body.children, readOnly = !writable)+ val bodyClose = xml.lastIndexOf("</", body.end - 1).coerceAtLeast(body.startTagEnd)++ val page = body.children.lastOrNull { it.local == "sectPr" }?.let { s ->+ val sz = s.child("pgSz")+ val mar = s.child("pgMar")+ fun tw(n: XNode?, a: String, d: Int) = n?.attr(xml, a)?.toFloatOrNull()?.toInt() ?: d+ PageSetup(+ width = tw(sz, "w", 11906), height = tw(sz, "h", 16838),+ left = tw(mar, "left", 1440), right = tw(mar, "right", 1440),+ top = tw(mar, "top", 1440), bottom = tw(mar, "bottom", 1440)+ )+ } ?: PageSetup()++ val pkg = DocxPackage(+ mainPath = mainPath,+ xml = xml,+ bodyOpenEnd = body.startTagEnd,+ bodyCloseStart = bodyClose,+ styles = DocxStyles.parse(parts[stylesPath]),+ stylesPath = stylesPath,+ numbering = DocxNumbering.parse(parts[numberingPath]),+ numberingPath = numberingPath,+ theme = DocxTheme.parse(themePath?.let { parts[it] }),+ rels = relMap,+ links = rels.filter { it.external }.associate { it.id to it.target },+ relsPath = relsPath,+ relsXml = relsXml,+ contentTypes = parts["[Content_Types].xml"],+ media = media,+ page = page,+ writable = writable+ )+ return pkg to DocState(blocks)+ }++ private fun isPicture(n: String) =+ n.endsWith(".png") || n.endsWith(".jpg") || n.endsWith(".jpeg") || n.endsWith(".gif") ||+ n.endsWith(".bmp") || n.endsWith(".webp") || n.endsWith(".jfif")++ class Rel(val id: String, val type: String, val target: String, val external: Boolean)++ fun relsOf(xml: String, baseDir: String): List<Rel> {+ val root = XmlScan.scan(xml).children.firstOrNull() ?: return emptyList()+ return root.childrenNamed("Relationship").mapNotNull { r ->+ val id = r.attr(xml, "Id") ?: return@mapNotNull null+ val target = r.attr(xml, "Target") ?: return@mapNotNull null+ val external = r.attr(xml, "TargetMode").equals("External", true)+ Rel(id, r.attr(xml, "Type") ?: "", if (external) target else resolve(baseDir, target), external)+ }+ }++ private fun join(dir: String, name: String) = if (dir.isEmpty()) name else "$dir/$name"++ fun resolve(baseDir: String, target: String): String {+ if (target.startsWith("/")) return target.removePrefix("/")+ val parts = ArrayList<String>()+ if (baseDir.isNotEmpty()) parts.addAll(baseDir.split('/'))+ for (seg in target.split('/')) when (seg) {+ "", "." -> {}+ ".." -> if (parts.isNotEmpty()) parts.removeAt(parts.size - 1)+ else -> parts.add(seg)+ }+ return parts.joinToString("/")+ }++ /** Parses one XML string's blocks; also used for text boxes inside a picture run. */+ internal class Ctx(val xml: String) {+ private val interned = HashMap<CharFmt, CharFmt>()+ private fun intern(f: CharFmt) = interned.getOrPut(f) { f }++ fun container(children: List<XNode>, readOnly: Boolean): List<DocBlock> {+ val out = ArrayList<DocBlock>(children.size)+ for (c in children) out.add(+ when (c.local) {+ "p" -> para(c, readOnly)+ "tbl" -> table(c, readOnly)+ "sdt" -> DocRaw(DocIds.next(), c.text(xml), c.child("sdtContent")?.let { container(it.children, true) } ?: emptyList())+ "customXml" -> DocRaw(DocIds.next(), c.text(xml), container(c.children, true))+ else -> DocRaw(DocIds.next(), c.text(xml))+ }+ )+ return out+ }++ private val markers = setOf(+ "bookmarkStart", "bookmarkEnd", "permStart", "permEnd", "commentRangeStart", "commentRangeEnd"+ )++ fun para(p: XNode, readOnly: Boolean): DocPara {+ val text = StringBuilder()+ val fmts = ArrayList<CharFmt>()+ val extras = StringBuilder()+ val marks = ArrayList<Int>()+ var editable = !readOnly++ fun add(s: String, f: CharFmt) {+ for (ch in s) { text.append(ch); fmts.add(f) }+ }++ fun run(r: XNode, link: String?) {+ val rPr = r.child("rPr")?.text(xml) ?: ""+ val fmt = intern(CharFmt(rPr, link))+ for (c in r.children) when (c.local) {+ "rPr" -> {}+ "lastRenderedPageBreak" -> if (marks.lastOrNull() != text.length) marks.add(text.length)+ "t" -> add(XmlScan.unescape(c.inner(xml)), fmt)+ "tab" -> add("\t", fmt)+ "br", "cr" -> {+ val type = c.attr(xml, "type")+ if (type == null || type == "textWrapping") add("\n", fmt)+ else add(OBJ_CHAR.toString(), intern(CharFmt(rPr, link, objXml(r, rPr, c))))+ }+ "noBreakHyphen" -> add("\u2011", fmt)+ "softHyphen" -> add("\u00AD", fmt)+ "delText", "instrText", "delInstrText", "fldChar" -> editable = false+ else -> add(OBJ_CHAR.toString(), intern(CharFmt(rPr, link, objXml(r, rPr, c))))+ }+ }++ fun deep(n: XNode) {+ for (c in n.children) when (c.local) {+ "r" -> run(c, null)+ "rPr", "pPr", "sdtPr", "sdtEndPr", "del", "moveFrom" -> {}+ else -> deep(c)+ }+ }++ for (c in p.children) when (c.local) {+ "pPr", "proofErr" -> {}+ "r" -> run(c, null)+ "hyperlink" -> {+ val tag = c.startTag(xml)+ if (tag.endsWith("/>")) continue+ for (h in c.children) when {+ h.local == "r" -> run(h, tag)+ h.local in markers -> extras.append(h.text(xml))+ h.local == "proofErr" -> {}+ else -> { editable = false; deep(h) }+ }+ }+ in markers -> extras.append(c.text(xml))+ else -> { editable = false; deep(c) }+ }+ // Symbols set in fonts we can't draw, maths, fields… still show their text, but such+ // paragraphs aren't offered for editing (their structure can't be re-flowed safely).+ val open = p.startTag(xml).let { if (it.endsWith("/>")) it.dropLast(2).trimEnd() + ">" else it }+ return DocPara(+ id = DocIds.next(),+ origin = p.text(xml),+ openTag = open,+ pPr = p.child("pPr")?.text(xml) ?: "",+ extras = extras.toString(),+ text = text.toString(),+ fmts = fmts,+ editable = editable,+ marks = marks+ )+ }++ private fun objXml(r: XNode, rPr: String, child: XNode): String {+ val open = r.startTag(xml).let { if (it.endsWith("/>")) it.dropLast(2).trimEnd() + ">" else it }+ return open + rPr + child.text(xml) + "</" + r.name + ">"+ }++ private fun closeStart(n: XNode): Int = xml.lastIndexOf("</", n.end - 1).coerceAtLeast(n.startTagEnd)++ fun table(t: XNode, readOnly: Boolean): DocBlock {+ val items = t.children.filter { it.local != "tblPr" && it.local != "tblGrid" }+ if (items.isEmpty() || t.end <= t.startTagEnd) return DocRaw(DocIds.next(), t.text(xml))+ val grid = t.child("tblGrid")?.childrenNamed("gridCol")?.map { it.attr(xml, "w")?.toFloatOrNull()?.toInt() ?: 0 }+ ?: emptyList()+ return DocTable(+ id = DocIds.next(),+ origin = t.text(xml),+ head = xml.substring(t.start, items.first().start),+ items = items.map { if (it.local == "tr") row(it, readOnly) else DocRaw(DocIds.next(), it.text(xml)) },+ tail = xml.substring(items.last().end, t.end),+ grid = grid,+ tblPr = t.child("tblPr")?.text(xml) ?: ""+ )+ }++ private fun row(tr: XNode, readOnly: Boolean): DocRow {+ val items = tr.children.filter { it.local != "tblPrEx" && it.local != "trPr" }+ val trPr = tr.child("trPr")?.text(xml) ?: ""+ if (items.isEmpty() || tr.end <= tr.startTagEnd) {+ val cs = closeStart(tr)+ return DocRow(DocIds.next(), xml.substring(tr.start, cs).let { if (it.endsWith("/>")) it.dropLast(2) + ">" else it },+ emptyList(), "</${tr.name}>", trPr)+ }+ return DocRow(+ id = DocIds.next(),+ head = xml.substring(tr.start, items.first().start),+ items = items.map { if (it.local == "tc") cell(it, readOnly) else DocRaw(DocIds.next(), it.text(xml)) },+ tail = xml.substring(items.last().end, tr.end),+ trPr = trPr+ )+ }++ private fun cell(tc: XNode, readOnly: Boolean): DocCell {+ val blocks = tc.children.filter { it.local != "tcPr" }+ val tcPr = tc.child("tcPr")?.text(xml) ?: ""+ if (blocks.isEmpty() || tc.end <= tc.startTagEnd) {+ val cs = closeStart(tc)+ return DocCell(DocIds.next(), xml.substring(tc.start, cs).let { if (it.endsWith("/>")) it.dropLast(2) + ">" else it },+ emptyList(), "</${tc.name}>", tcPr)+ }+ return DocCell(+ id = DocIds.next(),+ head = xml.substring(tc.start, blocks.first().start),+ blocks = container(blocks, readOnly),+ tail = xml.substring(blocks.last().end, tc.end),+ tcPr = tcPr+ )+ }+ }+}diff --git a/app/src/main/java/com/chethan616/clearpdf/docx/DocxWriter.kt b/app/src/main/java/com/chethan616/clearpdf/docx/DocxWriter.ktnew file mode 100644index 0000000..7785669--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/docx/DocxWriter.kt@@ -0,0 +1,237 @@+package com.chethan616.clearpdf.docx++import java.io.File+import java.io.InputStream+import java.io.OutputStream+import java.util.zip.ZipEntry+import java.util.zip.ZipInputStream+import java.util.zip.ZipOutputStream++/**+ * Writes an edited document back into its package. Untouched paragraphs and tables are copied from+ * the original XML verbatim; only edited ones are serialized again. Every other zip entry is+ * streamed through unchanged, except styles / numbering when the edits needed new definitions.+ */+object DocxWriter {++ private const val NUMBERING_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering"+ private const val STYLES_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"+ private const val W_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"++ fun write(pkg: DocxPackage, state: DocState, source: File, dest: File) {+ val parts = parts(pkg, state)+ source.inputStream().buffered().use { input ->+ dest.outputStream().buffered().use { out -> rewrite(input, out, parts.first, parts.second) }+ }+ }++ fun documentXml(pkg: DocxPackage, state: DocState): String {+ val sb = StringBuilder(pkg.xml.length + 1024)+ sb.append(pkg.xml, 0, pkg.bodyOpenEnd)+ blocks(state.blocks, sb)+ sb.append(pkg.xml, pkg.bodyCloseStart, pkg.xml.length)+ return sb.toString()+ }++ /** (entry → new bytes, new entries). */+ private fun parts(pkg: DocxPackage, state: DocState): Pair<Map<String, ByteArray>, Map<String, ByteArray>> {+ val replace = HashMap<String, ByteArray>()+ val add = LinkedHashMap<String, ByteArray>()+ replace[pkg.mainPath] = documentXml(pkg, state).toByteArray(Charsets.UTF_8)+ var rels = pkg.relsXml+ var types = pkg.contentTypes+ val dir = pkg.mainPath.substringBeforeLast('/', "")++ val num = pkg.numbering+ if (num.modified) {+ val abstracts = num.addedAbstract.joinToString("")+ val nums = num.addedNums.joinToString("")+ val existing = num.xml+ if (existing != null) {+ replace[pkg.numberingPath] = insertNumbering(existing, abstracts, nums).toByteArray(Charsets.UTF_8)+ } else {+ add[pkg.numberingPath] = ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" ++ "<w:numbering xmlns:w=\"$W_NS\">$abstracts$nums</w:numbering>").toByteArray(Charsets.UTF_8)+ rels = addRel(rels, NUMBERING_TYPE, relTarget(dir, pkg.numberingPath))+ types = addOverride(types, "/" + pkg.numberingPath, "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml")+ }+ }+ val st = pkg.styles+ if (st.added.isNotEmpty()) {+ val extra = st.added.joinToString("")+ val existing = st.xml+ if (existing != null) {+ val close = existing.lastIndexOf("</")+ replace[pkg.stylesPath] = (existing.substring(0, close) + extra + existing.substring(close)).toByteArray(Charsets.UTF_8)+ } else {+ add[pkg.stylesPath] = ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" ++ "<w:styles xmlns:w=\"$W_NS\">$extra</w:styles>").toByteArray(Charsets.UTF_8)+ rels = addRel(rels, STYLES_TYPE, relTarget(dir, pkg.stylesPath))+ types = addOverride(types, "/" + pkg.stylesPath, "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml")+ }+ }+ if (rels != pkg.relsXml && rels != null) {+ if (pkg.relsXml != null) replace[pkg.relsPath] = rels.toByteArray(Charsets.UTF_8) else add[pkg.relsPath] = rels.toByteArray(Charsets.UTF_8)+ }+ if (types != pkg.contentTypes && types != null) replace["[Content_Types].xml"] = types.toByteArray(Charsets.UTF_8)+ return replace to add+ }++ private fun relTarget(dir: String, path: String): String =+ if (dir.isNotEmpty() && path.startsWith("$dir/")) path.removePrefix("$dir/") else "/$path"++ /** `abstractNum`s go after the existing ones, `num`s after theirs — the schema's sequence. */+ internal fun insertNumbering(xml: String, abstracts: String, nums: String): String {+ val root = XmlScan.scan(xml).children.firstOrNull { it.local == "numbering" } ?: return xml+ val absAt = (root.children.lastOrNull { it.local == "abstractNum" } ?: root.children.lastOrNull { it.local == "numPicBullet" })?.end+ ?: root.startTagEnd+ val numAt = root.children.firstOrNull { it.local == "numIdMacAtCleanup" }?.start ?: xml.lastIndexOf("</")+ return xml.substring(0, absAt) + abstracts + xml.substring(absAt, numAt) + nums + xml.substring(numAt)+ }++ private fun addRel(rels: String?, type: String, target: String): String {+ val base = rels ?: "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" ++ "<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\"></Relationships>"+ var n = 1+ while (base.contains("Id=\"rIdCp$n\"")) n+++ val close = base.lastIndexOf("</")+ return base.substring(0, close) + "<Relationship Id=\"rIdCp$n\" Type=\"$type\" Target=\"$target\"/>" + base.substring(close)+ }++ private fun addOverride(types: String?, partName: String, contentType: String): String? {+ types ?: return null+ if (types.contains("PartName=\"$partName\"")) return types+ val close = types.lastIndexOf("</")+ return types.substring(0, close) + "<Override PartName=\"$partName\" ContentType=\"$contentType\"/>" + types.substring(close)+ }++ private fun rewrite(input: InputStream, output: OutputStream, replace: Map<String, ByteArray>, add: Map<String, ByteArray>) {+ ZipInputStream(input).use { zin ->+ val zout = ZipOutputStream(output)+ val buf = ByteArray(64 * 1024)+ val seen = HashSet<String>()+ while (true) {+ val e = zin.nextEntry ?: break+ val n = e.name.removePrefix("/")+ if (!seen.add(n)) continue+ val out = ZipEntry(e.name).apply { if (e.time != -1L) time = e.time }+ zout.putNextEntry(out)+ val bytes = replace[n]+ if (bytes != null) zout.write(bytes)+ else while (true) {+ val k = zin.read(buf)+ if (k <= 0) break+ zout.write(buf, 0, k)+ }+ zout.closeEntry()+ }+ for ((n, bytes) in add) {+ if (n in seen) continue+ zout.putNextEntry(ZipEntry(n))+ zout.write(bytes)+ zout.closeEntry()+ }+ zout.finish()+ zout.flush()+ }+ }++ // ── serialization ──────────────────────────────────────────────────────────++ fun blocks(list: List<DocBlock>, sb: StringBuilder) {+ for (b in list) when (b) {+ is DocPara -> para(b, sb)+ is DocTable -> table(b, sb)+ is DocRaw -> sb.append(b.xml)+ }+ }++ private fun table(t: DocTable, sb: StringBuilder) {+ if (t.origin != null) { sb.append(t.origin); return }+ sb.append(t.head)+ for (item in t.items) when (item) {+ is DocRow -> {+ sb.append(item.head)+ for (ri in item.items) when (ri) {+ is DocCell -> {+ sb.append(ri.head)+ blocks(ri.blocks, sb)+ sb.append(ri.tail)+ }+ is DocRaw -> sb.append(ri.xml)+ }+ sb.append(item.tail)+ }+ is DocRaw -> sb.append(item.xml)+ }+ sb.append(t.tail)+ }++ private fun tagName(open: String): String =+ open.substring(1).takeWhile { !it.isWhitespace() && it != '>' && it != '/' }++ fun para(p: DocPara, sb: StringBuilder) {+ if (p.origin != null) { sb.append(p.origin); return }+ sb.append(p.openTag).append(p.pPr).append(p.extras)+ val n = p.text.length+ var i = 0+ while (i < n) {+ val link = p.fmts[i].link+ var j = i+ while (j < n && p.fmts[j].link == link) j+++ if (link != null) {+ sb.append(link)+ runs(p, i, j, sb)+ sb.append("</").append(tagName(link)).append('>')+ } else runs(p, i, j, sb)+ i = j+ }+ sb.append("</").append(tagName(p.openTag)).append('>')+ }++ private fun runs(p: DocPara, from: Int, to: Int, sb: StringBuilder) {+ var k = from+ while (k < to) {+ val f = p.fmts[k]+ if (f.obj != null) {+ sb.append(f.obj)+ k+++ continue+ }+ var m = k+ while (m < to && p.fmts[m].obj == null && p.fmts[m].rPr == f.rPr) m+++ run(f.rPr, p.text, k, m, sb)+ k = m+ }+ }++ private fun run(rPr: String, text: String, from: Int, to: Int, sb: StringBuilder) {+ sb.append("<w:r>").append(rPr)+ val buf = StringBuilder()+ fun flush() {+ if (buf.isEmpty()) return+ sb.append("<w:t xml:space=\"preserve\">").append(XmlScan.escape(buf.toString())).append("</w:t>")+ buf.setLength(0)+ }+ var i = from+ while (i < to) {+ val c = text[i]+ when {+ c == '\t' -> { flush(); sb.append("<w:tab/>") }+ c == '\n' || c == '\r' -> { flush(); sb.append("<w:br/>") }+ c == '\u2011' -> { flush(); sb.append("<w:noBreakHyphen/>") }+ c == '\u00AD' -> { flush(); sb.append("<w:softHyphen/>") }+ c == OBJ_CHAR -> {}+ c.isHighSurrogate() -> {+ if (i + 1 < to && text[i + 1].isLowSurrogate()) { buf.append(c).append(text[i + 1]); i++ }+ }+ c.isLowSurrogate() -> {}+ c < ' ' || c == '\uFFFE' || c == '\uFFFF' -> {}+ else -> buf.append(c)+ }+ i+++ }+ flush()+ sb.append("</w:r>")+ }+}diff --git a/app/src/main/java/com/chethan616/clearpdf/docx/DocxXml.kt b/app/src/main/java/com/chethan616/clearpdf/docx/DocxXml.ktnew file mode 100644index 0000000..25f6cdd--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/docx/DocxXml.kt@@ -0,0 +1,152 @@+package com.chethan616.clearpdf.docx++/**+ * A light element tree over an XML string that remembers where every element starts and ends.+ *+ * The editor rewrites only what changed: an edited paragraph is serialized again and spliced into+ * the original text at its exact range, and everything else (unknown elements, tracked changes,+ * bookmarks, section properties…) is copied through character for character. A DOM would+ * re-serialize the whole part and lose that fidelity; this keeps offsets instead.+ */+internal class XNode(val name: String, val start: Int, val parent: XNode?) {+ /** Offset just past the start tag's `>`. */+ var startTagEnd: Int = start+ /** Offset just past the end tag's `>` (or the self-closing tag). */+ var end: Int = start+ val children = ArrayList<XNode>(2)++ val local: String get() = name.substringAfter(':')++ fun child(local: String): XNode? = children.firstOrNull { it.local == local }+ fun childrenNamed(local: String): List<XNode> = children.filter { it.local == local }++ fun descendant(local: String): XNode? {+ for (c in children) {+ if (c.local == local) return c+ c.descendant(local)?.let { return it }+ }+ return null+ }++ fun text(xml: String): String = xml.substring(start, end)+ fun inner(xml: String): String = if (end > startTagEnd) xml.substring(startTagEnd, (end - name.length - 3).coerceAtLeast(startTagEnd)) else ""+ fun startTag(xml: String): String = xml.substring(start, startTagEnd)++ /** An attribute of the start tag, matched by local name (`w:val` and `val` both match `val`). */+ fun attr(xml: String, localName: String): String? = XmlScan.attr(startTag(xml), localName)+}++internal object XmlScan {++ /** Scans [xml] into a tree; the returned root is a pseudo-node spanning the whole string. */+ fun scan(xml: String): XNode {+ val root = XNode("#root", 0, null).also { it.end = xml.length; it.startTagEnd = 0 }+ var cur = root+ var i = xml.indexOf('<')+ val n = xml.length+ while (i in 0 until n) {+ when {+ xml.startsWith("<?", i) -> { i = xml.indexOf("?>", i).let { if (it < 0) n else it + 2 } }+ xml.startsWith("<!--", i) -> { i = xml.indexOf("-->", i).let { if (it < 0) n else it + 3 } }+ xml.startsWith("<![CDATA[", i) -> { i = xml.indexOf("]]>", i).let { if (it < 0) n else it + 3 } }+ xml.startsWith("<!", i) -> { i = xml.indexOf('>', i).let { if (it < 0) n else it + 1 } }+ xml.startsWith("</", i) -> {+ val close = xml.indexOf('>', i)+ if (close < 0) break+ val name = xml.substring(i + 2, close).trim()+ // Pop to the matching element (tolerant of the odd unclosed tag).+ var node: XNode? = cur+ while (node != null && node !== root && node.name != name) node = node.parent+ if (node != null && node !== root) {+ node.end = close + 1+ cur = node.parent ?: root+ }+ i = close + 1+ }+ else -> {+ val tagEnd = tagEnd(xml, i)+ if (tagEnd < 0) break+ var nameEnd = i + 1+ while (nameEnd < n && !xml[nameEnd].isWhitespace() && xml[nameEnd] != '>' && xml[nameEnd] != '/') nameEnd+++ val node = XNode(xml.substring(i + 1, nameEnd), i, cur)+ node.startTagEnd = tagEnd + 1+ cur.children.add(node)+ if (xml[tagEnd - 1] == '/') {+ node.end = tagEnd + 1+ } else {+ cur = node+ }+ i = tagEnd + 1+ }+ }+ if (i < n) i = xml.indexOf('<', i).let { if (it < 0) n else it }+ }+ return root+ }++ /** Index of the `>` closing the tag that starts at [from], skipping quoted attribute values. */+ private fun tagEnd(xml: String, from: Int): Int {+ var q: Char? = null+ var i = from + 1+ while (i < xml.length) {+ val c = xml[i]+ if (q != null) { if (c == q) q = null }+ else if (c == '"' || c == '\'') q = c+ else if (c == '>') return i+ i+++ }+ return -1+ }++ private val attrRegex = Regex("""([A-Za-z_][\w.:-]*)\s*=\s*("([^"]*)"|'([^']*)')""")++ fun attr(startTag: String, localName: String): String? {+ for (m in attrRegex.findAll(startTag)) {+ val key = m.groupValues[1]+ if (key == localName || key.substringAfter(':') == localName && !key.startsWith("xmlns")) {+ return unescape(m.groupValues[3].ifEmpty { m.groupValues[4] })+ }+ }+ return null+ }++ fun escape(s: String): String {+ val sb = StringBuilder(s.length + 8)+ for (c in s) when (c) {+ '&' -> sb.append("&")+ '<' -> sb.append("<")+ '>' -> sb.append(">")+ '"' -> sb.append(""")+ else -> sb.append(c)+ }+ return sb.toString()+ }++ fun unescape(s: String): String {+ if (s.indexOf('&') < 0) return s+ val sb = StringBuilder(s.length)+ var i = 0+ while (i < s.length) {+ val c = s[i]+ if (c == '&') {+ val semi = s.indexOf(';', i)+ if (semi > i) {+ val ent = s.substring(i + 1, semi)+ val rep: String? = when {+ ent == "amp" -> "&"+ ent == "lt" -> "<"+ ent == "gt" -> ">"+ ent == "quot" -> "\""+ ent == "apos" -> "'"+ ent.startsWith("#x") -> ent.drop(2).toIntOrNull(16)?.let { String(Character.toChars(it)) }+ ent.startsWith("#") -> ent.drop(1).toIntOrNull()?.let { String(Character.toChars(it)) }+ else -> null+ }+ if (rep != null) { sb.append(rep); i = semi + 1; continue }+ }+ }+ sb.append(c); i+++ }+ return sb.toString()+ }+}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassToolbar.kt b/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassToolbar.ktindex a9425e4..f2723da 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassToolbar.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassToolbar.kt@@ -45,9 +45,6 @@ import com.chethan616.clearpdf.ui.theme.LiquidGlassColorsimport com.chethan616.clearpdf.ui.theme.LocalIsDarkModeimport com.kyant.backdrop.Backdropimport com.kyant.backdrop.drawBackdrop-import com.kyant.backdrop.effects.blur-import com.kyant.backdrop.effects.lens-import com.kyant.backdrop.effects.vibrancyimport com.kyant.backdrop.highlight.Highlightimport com.kyant.shapes.Capsule@@ -65,6 +62,7 @@ fun GlassToolbar(val isDark = LocalIsDarkMode.currentval containerColor = if (isDark) Color(0xFF1E1E1E).copy(0.42f) else Color(0xFFFAFAFA).copy(0.42f)val scroll = rememberScrollState()+ val style = GlassSettings.styleBox(modifier@@ -72,15 +70,13 @@ fun GlassToolbar(.drawBackdrop(backdrop = backdrop,shape = { Capsule },- effects = {- vibrancy()- blur(8f.dp.toPx())- lens(16f.dp.toPx(), 32f.dp.toPx())- },- highlight = { Highlight.Ambient },+ // The user's Liquid Glass settings (blur, refraction, tint, highlight…), like every+ // other glass surface; this stack used to be hand-rolled and ignored them.+ effects = { glassEffects(style, 8f.dp.toPx(), 16f.dp.toPx(), 32f.dp.toPx()) },+ highlight = { glassHighlight(style, Highlight.Ambient) },shadow = null,innerShadow = null,- onDrawSurface = { drawRect(containerColor) }+ onDrawSurface = { drawRect(containerColor.glassTint(style)) }).clip(Capsule),contentAlignment = Alignment.CenterStartdiff --git a/app/src/main/java/com/chethan616/clearpdf/ui/navigation/DocsNavGraph.kt b/app/src/main/java/com/chethan616/clearpdf/ui/navigation/DocsNavGraph.ktindex 4896779..41140ed 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/navigation/DocsNavGraph.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/navigation/DocsNavGraph.kt@@ -101,10 +101,12 @@ private const val ROUTE_HTML_TO_PDF = "html_to_pdf"private const val ROUTE_FILL_FORM = "fill_form"private const val ROUTE_SPREADSHEET_BASE = "spreadsheet"private const val ROUTE_IMAGE_EDITOR_BASE = "image_editor"+private const val ROUTE_DOCX_BASE = "docx_editor"private const val ARG_PDF_URI = "uri"private const val ROUTE_VIEWER = "$ROUTE_VIEWER_BASE?$ARG_PDF_URI={$ARG_PDF_URI}"private const val ROUTE_SPREADSHEET = "$ROUTE_SPREADSHEET_BASE?$ARG_PDF_URI={$ARG_PDF_URI}"private const val ROUTE_IMAGE_EDITOR = "$ROUTE_IMAGE_EDITOR_BASE?$ARG_PDF_URI={$ARG_PDF_URI}"+private const val ROUTE_DOCX = "$ROUTE_DOCX_BASE?$ARG_PDF_URI={$ARG_PDF_URI}"private val OPEN_DOC_MIMES = arrayOf("application/pdf",@@ -156,6 +158,10 @@ private fun NavHostController.navigateToDocument(when (docKindOf(name)) {DocKind.Excel -> navigate("$ROUTE_SPREADSHEET_BASE?$ARG_PDF_URI=${Uri.encode(uri.toString())}") { launchSingleTop = true }DocKind.Image -> navigate("$ROUTE_IMAGE_EDITOR_BASE?$ARG_PDF_URI=${Uri.encode(uri.toString())}") { launchSingleTop = true }+ // .docx opens in the Word editor (#73); .doc/.odt/.rtf still go through the PDF path.+ DocKind.Word -> if (name?.lowercase()?.trim()?.endsWith(".docx") == true)+ navigate("$ROUTE_DOCX_BASE?$ARG_PDF_URI=${Uri.encode(uri.toString())}") { launchSingleTop = true }+ else navigateToPdfViewer(uri)else -> navigateToPdfViewer(uri)}}@@ -183,7 +189,8 @@ private fun isDocViewerRoute(route: String?): Boolean =route != null && (route.startsWith(ROUTE_VIEWER_BASE) ||route.startsWith(ROUTE_SPREADSHEET_BASE) ||- route.startsWith(ROUTE_IMAGE_EDITOR_BASE)+ route.startsWith(ROUTE_IMAGE_EDITOR_BASE) ||+ route.startsWith(ROUTE_DOCX_BASE))/**@@ -564,6 +571,29 @@ fun DocsNavGraph()}+ composable(+ route = ROUTE_DOCX,+ arguments = listOf(navArgument(ARG_PDF_URI) { type = NavType.StringType; nullable = true; defaultValue = null }),+ enterTransition = { documentLiftIn() },+ popExitTransition = {+ androidx.compose.animation.fadeOut(tween(200, easing = androidx.compose.animation.core.FastOutSlowInEasing))+ }+ ) { backStackEntry ->+ val context = LocalContext.current+ val vm: com.chethan616.clearpdf.ui.viewmodel.DocxEditorViewModel = viewModel()+ val routeUri = backStackEntry.arguments?.getString(ARG_PDF_URI)?.let { parseViewerUriArg(it) }+ LaunchedEffect(routeUri, incomingPdfUri) {+ val target = routeUri ?: incomingPdfUri+ if (target != null) vm.load(context, target)+ }+ com.chethan616.clearpdf.ui.screen.DocxEditorScreen(+ backdrop = backdrop,+ viewModel = vm,+ onBack = { navController.popBackStack() },+ onOpenPdf = { pdfUri -> navController.navigateToPdfViewer(pdfUri) }+ )+ }+composable(route = ROUTE_IMAGE_EDITOR,arguments = listOf(navArgument(ARG_PDF_URI) { type = NavType.StringType; nullable = true; defaultValue = null }),diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/DocxEditorScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/DocxEditorScreen.ktnew file mode 100644index 0000000..451c9b7--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/DocxEditorScreen.kt@@ -0,0 +1,1712 @@+package com.chethan616.clearpdf.ui.screen++import android.app.Activity+import android.content.Context+import android.content.ContextWrapper+import android.graphics.Bitmap+import android.graphics.BitmapFactory+import android.util.LruCache+import android.widget.Toast+import androidx.activity.compose.BackHandler+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.animation.AnimatedVisibility+import androidx.compose.animation.core.RepeatMode+import androidx.compose.animation.core.animateFloat+import androidx.compose.animation.core.infiniteRepeatable+import androidx.compose.animation.core.rememberInfiniteTransition+import androidx.compose.animation.core.tween+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.animation.scaleIn+import androidx.compose.animation.scaleOut+import androidx.compose.animation.slideInVertically+import androidx.compose.animation.slideOutVertically+import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.gestures.calculateCentroid+import androidx.compose.foundation.gestures.calculateZoom+import androidx.compose.foundation.gestures.scrollBy+import androidx.compose.foundation.horizontalScroll+import androidx.compose.foundation.interaction.MutableInteractionSource+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.IntrinsicSize+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.WindowInsets+import androidx.compose.foundation.layout.asPaddingValues+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.imePadding+import androidx.compose.foundation.layout.navigationBars+import androidx.compose.foundation.layout.navigationBarsPadding+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.statusBars+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.layout.widthIn+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.BasicText+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.foundation.text.KeyboardActions+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.foundation.text.selection.SelectionContainer+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.automirrored.rounded.Redo+import androidx.compose.material.icons.automirrored.rounded.Undo+import androidx.compose.material.icons.rounded.Add+import androidx.compose.material.icons.rounded.BorderColor+import androidx.compose.material.icons.rounded.Check+import androidx.compose.material.icons.rounded.DarkMode+import androidx.compose.material.icons.rounded.Edit+import androidx.compose.material.icons.rounded.FontDownload+import androidx.compose.material.icons.rounded.FormatAlignCenter+import androidx.compose.material.icons.rounded.FormatAlignJustify+import androidx.compose.material.icons.rounded.FormatAlignLeft+import androidx.compose.material.icons.rounded.FormatAlignRight+import androidx.compose.material.icons.rounded.FormatBold+import androidx.compose.material.icons.rounded.FormatClear+import androidx.compose.material.icons.rounded.FormatColorText+import androidx.compose.material.icons.rounded.FormatIndentDecrease+import androidx.compose.material.icons.rounded.FormatIndentIncrease+import androidx.compose.material.icons.rounded.FormatItalic+import androidx.compose.material.icons.rounded.FormatListBulleted+import androidx.compose.material.icons.rounded.FormatListNumbered+import androidx.compose.material.icons.rounded.FormatStrikethrough+import androidx.compose.material.icons.rounded.FormatUnderlined+import androidx.compose.material.icons.rounded.IosShare+import androidx.compose.material.icons.rounded.LightMode+import androidx.compose.material.icons.rounded.PictureAsPdf+import androidx.compose.material.icons.rounded.Print+import androidx.compose.material.icons.rounded.Remove+import androidx.compose.material.icons.rounded.SaveAs+import androidx.compose.material.icons.rounded.Search+import androidx.compose.material.icons.rounded.Superscript+import androidx.compose.material.icons.rounded.TextFields+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.Icon+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.derivedStateOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.produceState+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.runtime.snapshotFlow+import androidx.compose.runtime.withFrameNanos+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.focus.onFocusChanged+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.graphics.toArgb+import androidx.compose.ui.hapticfeedback.HapticFeedbackType+import androidx.compose.ui.input.key.Key+import androidx.compose.ui.input.key.key+import androidx.compose.ui.input.key.onPreviewKeyEvent+import androidx.compose.ui.input.pointer.PointerEventPass+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.platform.LocalFocusManager+import androidx.compose.ui.platform.LocalHapticFeedback+import androidx.compose.ui.platform.LocalLayoutDirection+import androidx.compose.ui.platform.LocalView+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.AnnotatedString+import androidx.compose.ui.text.TextRange+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.KeyboardType+import androidx.compose.ui.text.input.OffsetMapping+import androidx.compose.ui.text.input.TextFieldValue+import androidx.compose.ui.text.input.TransformedText+import androidx.compose.ui.text.input.VisualTransformation+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.LayoutDirection+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.core.view.WindowCompat+import com.chethan616.clearpdf.R+import com.chethan616.clearpdf.data.repository.AppSettingsManager+import com.chethan616.clearpdf.data.repository.RecentFilesManager+import com.chethan616.clearpdf.docx.CharFmt+import com.chethan616.clearpdf.docx.DocBlock+import com.chethan616.clearpdf.docx.DocPara+import com.chethan616.clearpdf.docx.DocRaw+import com.chethan616.clearpdf.docx.DocRow+import com.chethan616.clearpdf.docx.DocTable+import com.chethan616.clearpdf.docx.DocxEdits+import com.chethan616.clearpdf.docx.DocxObjects+import com.chethan616.clearpdf.docx.DocxPackage+import com.chethan616.clearpdf.docx.DocxStyles+import com.chethan616.clearpdf.docx.HighlightColors+import com.chethan616.clearpdf.docx.OBJ_CHAR+import com.chethan616.clearpdf.docx.ObjInfo+import com.chethan616.clearpdf.docx.Props+import com.chethan616.clearpdf.docx.RProps+import com.chethan616.clearpdf.docx.XNode+import com.chethan616.clearpdf.docx.XmlScan+import com.chethan616.clearpdf.docx.findPara+import com.chethan616.clearpdf.docx.forEachPara+import com.chethan616.clearpdf.ui.components.GlassBackButton+import com.chethan616.clearpdf.ui.components.GlassColorPicker+import com.chethan616.clearpdf.ui.components.GlassDialog+import com.chethan616.clearpdf.ui.components.GlassDialogAction+import com.chethan616.clearpdf.ui.components.GlassDropdownOption+import com.chethan616.clearpdf.ui.components.GlassMotion+import com.chethan616.clearpdf.ui.components.GlassScreenScaffold+import com.chethan616.clearpdf.ui.components.GlassTitlePill+import com.chethan616.clearpdf.ui.components.GlassToolButton+import com.chethan616.clearpdf.ui.components.GlassToolbar+import com.chethan616.clearpdf.ui.components.LiquidGlassDropdown+import com.chethan616.clearpdf.ui.components.LiquidIconButton+import com.chethan616.clearpdf.ui.components.LocalBackToLibraryAction+import com.chethan616.clearpdf.ui.components.NightPaper+import com.chethan616.clearpdf.ui.components.OfficeStandardColors+import com.chethan616.clearpdf.ui.components.OfficeThemeColors+import com.chethan616.clearpdf.ui.components.UnsavedChangesDialog+import com.chethan616.clearpdf.ui.components.chipGlass+import com.chethan616.clearpdf.ui.components.liquidRowClick+import com.chethan616.clearpdf.ui.components.rememberScreenBackdrop+import com.chethan616.clearpdf.ui.components.viewerGlass+import com.chethan616.clearpdf.ui.theme.LiquidGlassColors+import com.chethan616.clearpdf.ui.theme.LocalIsDarkMode+import com.chethan616.clearpdf.ui.utils.rememberUISensor+import com.chethan616.clearpdf.ui.viewmodel.DocxEditorViewModel+import com.chethan616.clearpdf.utils.PdfPrint+import com.kyant.backdrop.Backdrop+import com.kyant.backdrop.backdrops.LayerBackdrop+import com.kyant.shapes.Capsule+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.debounce+import kotlinx.coroutines.flow.distinctUntilChanged+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import kotlin.math.roundToInt++/** Stands before every paragraph's text in its field, so Backspace at the start is observable. */+private const val ZWSP = '\u200B'++private val PaperCorner = 6.dp+/** Desk showing around the pages, as in LibreOffice Writer. */+private val DeskGutter = 8.dp+private val PageGap = 14.dp++private enum class DocPanel { NONE, TEXT_COLOR, HIGHLIGHT }++/** Formatting chosen with nothing selected: it applies to what is typed next at [at]. */+private class Pending(val paraId: Long, val at: Int, val fmt: CharFmt)++private sealed class DocItem(val key: Any, val page: Int) {+ /** A paragraph, or (reading) the part of one that falls on [page], when Word broke it across pages. */+ class Para(+ val para: DocPara,+ val readOnly: Boolean,+ page: Int,+ val range: IntRange? = null+ ) : DocItem(if (range == null) para.id else "${para.id}:${range.first}", page) {+ var spaceTop = true+ var spaceBottom = true+ val first: Boolean get() = range == null || range.first == 0+ val last: Boolean get() = range == null || range.last >= para.text.length - 1+ }+ class TRow(val table: DocTable, val row: DocRow, val rowIndex: Int, val readOnly: Boolean, page: Int) : DocItem("r" + row.id, page)+ /** The end of one page and the start of the next ([page]). */+ class Gap(key: String, page: Int) : DocItem(key, page)+ class Top : DocItem("top", 0)+ class Bottom(page: Int) : DocItem("bottom", page)+}++private class Flat(val items: List<DocItem>, val indexOf: Map<Long, Int>, val pageStarts: List<Int>) {+ val pages: Int get() = pageStarts.size+}++/**+ * The document as one list for the LazyColumn, in pages. A page ends where Word ended it when it+ * last laid the file out (its `lastRenderedPageBreak` marks, after Gander), at page and section+ * breaks, and before paragraphs set to start a page. While reading, a paragraph Word broke across+ * two pages is shown in two parts; while editing it stays whole (one field) and the page ends after it.+ */+private fun flatten(blocks: List<DocBlock>, styles: DocxStyles, splitParas: Boolean): Flat {+ val items = ArrayList<DocItem>()+ val index = HashMap<Long, Int>()+ val pageStarts = arrayListOf(0)+ items.add(DocItem.Top())+ var page = 0+ var pending = false+ var inked = false+ var lastPara: DocItem.Para? = null+ var lastStyle: String? = null+ var lastContextual = false++ fun breakHere() { if (inked) pending = true }+ fun beforeContent() {+ if (!pending) return+ page+++ pageStarts.add(items.size)+ items.add(DocItem.Gap("g$page", page))+ pending = false+ inked = false+ lastPara = null+ }++ fun add(list: List<DocBlock>, readOnly: Boolean) {+ for (b in list) when (b) {+ is DocPara -> {+ val direct = Props.p(b.pPr)+ val pp = direct.over(styles.paragraphStyle(direct.styleId).first)+ if (pp.pageBreakBefore == true) breakHere()+ val len = b.text.length+ fun shows(i: Int): Boolean {+ val c = b.text[i]+ return !(c.isWhitespace() || (c == OBJ_CHAR && DocxObjects.isPageBreak(b.fmts.getOrNull(i)?.obj)))+ }+ val firstInk = (0 until len).firstOrNull { shows(it) } ?: len+ val lastInkEnd = ((len - 1) downTo 0).firstOrNull { shows(it) }?.plus(1) ?: 0+ val cuts = sortedSetOf<Int>()+ cuts.addAll(b.marks)+ b.fmts.forEachIndexed { i, f -> if (DocxObjects.isPageBreak(f.obj)) cuts.add(i + 1) }+ if (cuts.any { it <= firstInk } && firstInk < len) breakHere()+ val trailing = cuts.any { it >= lastInkEnd && lastInkEnd > 0 }+ // Cuts inside the text, each leaving visible text on both sides.+ val inner = ArrayList<Int>()+ var prev = firstInk+ for (c in cuts) {+ if (c <= firstInk || c >= lastInkEnd) continue+ if ((prev until c).any { shows(it) }) { inner.add(c); prev = c }+ }+ val style = direct.styleId ?: styles.defaultParagraphId+ val contextual = pp.contextual == true+ val ro = readOnly || !b.editable+ val starts = index.containsKey(b.id).not()+ if (inner.isEmpty() || !splitParas) {+ beforeContent()+ val item = DocItem.Para(b, ro, page)+ lastPara?.let { prevItem ->+ if (lastStyle == style) {+ if (lastContextual) prevItem.spaceBottom = false+ if (contextual) item.spaceTop = false+ }+ }+ if (starts) index[b.id] = items.size+ items.add(item)+ inked = true+ lastPara = item; lastStyle = style; lastContextual = contextual+ if (inner.isNotEmpty()) breakHere()+ } else {+ var from = 0+ for ((k, c) in (inner + len).withIndex()) {+ if (k > 0) breakHere()+ beforeContent()+ val item = DocItem.Para(b, ro, page, from until c)+ if (k == 0 && starts) index[b.id] = items.size+ items.add(item)+ inked = true+ from = c+ }+ lastPara = null+ }+ if (trailing) breakHere()+ val sect = Props.child(b.pPr, "sectPr")+ if (sect != null && !sect.contains("continuous")) breakHere()+ }+ is DocTable -> {+ lastPara = null+ for ((ri, r) in b.rows.withIndex()) {+ var marked = false+ for (c in r.cells) forEachPara(c.blocks) { if (it.marks.isNotEmpty()) marked = true }+ if (marked) breakHere()+ beforeContent()+ val at = items.size+ for (c in r.cells) forEachPara(c.blocks) { index[it.id] = at }+ items.add(DocItem.TRow(b, r, ri, readOnly, page))+ inked = true+ }+ }+ is DocRaw -> if (b.preview.isNotEmpty()) add(b.preview, true)+ }+ }+ add(blocks, false)+ items.add(DocItem.Bottom(page))+ return Flat(items, index, pageStarts)+}++/** Shared state and callbacks every paragraph needs; one object so items take one parameter. */+private class DocEnv(+ val pkg: DocxPackage,+ val editMode: Boolean,+ val activeId: Long?,+ val activeValue: TextFieldValue,+ val focusTarget: Long?,+ val labels: Map<Long, String>,+ val hits: Map<Long, List<IntRange>>,+ val currentHit: Pair<Long, IntRange>?,+ val accent: Color,+ /** Width between the page margins. */+ val textWidth: Dp,+ val onChange: (DocPara, TextFieldValue) -> Unit,+ val onFocused: (DocPara) -> Unit,+ val onBlurred: (DocPara) -> Unit,+ val onFocusConsumed: () -> Unit,+ val onReadOnlyTap: () -> Unit+)++private tailrec fun Context.findActivity(): Activity? = when (this) {+ is Activity -> this+ is ContextWrapper -> baseContext.findActivity()+ else -> null+}++/**+ * The Word editor (#73): a .docx opens as a document, not as a converted PDF. Its pages are shown+ * as on a desktop: true proportions and margins, Word's own page breaks, pinch to zoom. The pencil+ * makes every paragraph and table cell editable in place, with a Writer-style formatting bar and a+ * tool dock; saving patches the original .docx.+ *+ * Its light or dark look follows the document's reader mode, not the app theme: the desk, every+ * glass control, menu and dialog take their ink from the paper they sit on (DESIGN.md: ink adapts+ * to what is behind the glass).+ */+@Composable+fun DocxEditorScreen(+ backdrop: LayerBackdrop,+ viewModel: DocxEditorViewModel,+ onBack: () -> Unit,+ onOpenPdf: (android.net.Uri) -> Unit+) {+ val appDark = LocalIsDarkMode.current+ val context = LocalContext.current+ // The moon button's choice is saved; until then the paper follows the theme and #74's setting.+ val autoDarkPaper = appDark && remember { AppSettingsManager.getAutoDarkPages(context) }+ var paperDarkOverride by rememberSaveable { mutableStateOf<Boolean?>(null) }+ val paperDark = paperDarkOverride ?: autoDarkPaper++ // The status bar sits over the page too: dark icons on white paper, light ones on dark.+ val view = LocalView.current+ DisposableEffect(view, paperDark) {+ val window = view.context.findActivity()?.window+ val ctrl = window?.let { WindowCompat.getInsetsController(it, view) }+ ctrl?.isAppearanceLightStatusBars = !paperDark+ onDispose { ctrl?.isAppearanceLightStatusBars = !appDark }+ }++ CompositionLocalProvider(LocalIsDarkMode provides paperDark) {+ DocxEditorContent(backdrop, viewModel, onBack, onOpenPdf, paperDark) { paperDarkOverride = !paperDark }+ }+}++@Composable+private fun DocxEditorContent(+ backdrop: LayerBackdrop,+ viewModel: DocxEditorViewModel,+ onBack: () -> Unit,+ onOpenPdf: (android.net.Uri) -> Unit,+ paperDark: Boolean,+ onTogglePaper: () -> Unit+) {+ val text = LiquidGlassColors.text(paperDark)+ val sub = LiquidGlassColors.secondary(paperDark)+ val accent = LiquidGlassColors.Blue+ val context = LocalContext.current+ val haptics = LocalHapticFeedback.current+ val focusManager = LocalFocusManager.current+ val scope = rememberCoroutineScope()+ val uiSensor = rememberUISensor()+ val density = LocalDensity.current+ val desk = if (paperDark) Color(0xFF0D0D0F) else Color(0xFFE3E4E9)++ val meta = viewModel.meta+ val pkg = viewModel.pkg+ val doc = viewModel.doc+ val editable = viewModel.editable++ var editMode by rememberSaveable { mutableStateOf(false) }+ /** The paragraph field that has focus; Enter is swallowed while none has (see the root Box). */+ var focusedField by remember { mutableStateOf<Long?>(null) }+ // 1 = the page fits the screen's width, as a desktop shows a whole page.+ var zoomTarget by rememberSaveable { mutableFloatStateOf(1f) }+ val zoom = (zoomTarget * 20f).roundToInt() / 20f+ val pinchFocus = remember { floatArrayOf(0f, 0f) }+ var activeId by remember { mutableStateOf<Long?>(null) }+ var activeValue by remember { mutableStateOf(TextFieldValue()) }+ var focusTarget by remember { mutableStateOf<Long?>(null) }+ var pending by remember { mutableStateOf<Pending?>(null) }+ var panel by remember { mutableStateOf(DocPanel.NONE) }+ var showSearch by remember { mutableStateOf(false) }+ var searchQuery by remember { mutableStateOf("") }+ var currentMatch by remember { mutableIntStateOf(0) }+ var confirmExit by remember { mutableStateOf(false) }+ var exitAfterSave by remember { mutableStateOf(false) }+ var readOnlyHinted by remember { mutableStateOf(false) }+ var showGoTo by remember { mutableStateOf(false) }+ val searchFocus = remember { FocusRequester() }+ val listState = rememberLazyListState()+ val hScroll = rememberScrollState()++ val carlito = remember { DocxLook.carlito() }+ // Paragraph properties only (indents, lists, styles): independent of size and colour.+ val propsLook = remember(pkg) { pkg?.let { DocxLook(it, false, 1f, 1f, carlito) } }+ val flat = remember(doc, pkg, editMode) { if (doc != null && pkg != null) flatten(doc.blocks, pkg.styles, !editMode) else null }+ val labels = remember(doc, pkg) { if (doc != null && pkg != null) numberingLabels(pkg, doc.blocks) else emptyMap() }++ // Find, off the main thread and debounced.+ val matches by produceState(emptyList<Pair<Long, IntRange>>(), doc, searchQuery) {+ val q = searchQuery.trim()+ val d = doc+ if (q.isEmpty() || d == null) { value = emptyList(); return@produceState }+ delay(160)+ value = withContext(Dispatchers.Default) {+ val out = ArrayList<Pair<Long, IntRange>>()+ forEachPara(d.blocks) { p ->+ var i = p.text.indexOf(q, ignoreCase = true)+ while (i >= 0 && out.size < 5000) {+ out.add(p.id to (i until i + q.length))+ i = p.text.indexOf(q, i + q.length, ignoreCase = true)+ }+ }+ out+ }+ }+ val hitsByPara = remember(matches) { matches.groupBy({ it.first }, { it.second }) }+ fun itemOfHit(id: Long, at: Int): Int? {+ val f = flat ?: return null+ val start = f.indexOf[id] ?: return null+ // A paragraph shown in parts: the part holding the match.+ var best = start+ for (i in start until f.items.size) {+ val it = f.items[i] as? DocItem.Para ?: break+ if (it.para.id != id) break+ if (it.range == null || at in it.range) { best = i; break }+ }+ return best+ }+ fun scrollToItem(idx: Int) {+ scope.launch { listState.animateScrollToItem(idx, -with(density) { 160.dp.roundToPx() }) }+ }+ LaunchedEffect(matches) {+ currentMatch = 0+ matches.firstOrNull()?.let { (id, r) -> itemOfHit(id, r.first)?.let(::scrollToItem) }+ }+ fun goToMatch(delta: Int) {+ if (matches.isEmpty()) return+ currentMatch = ((currentMatch + delta) % matches.size + matches.size) % matches.size+ matches[currentMatch].let { (id, r) -> itemOfHit(id, r.first)?.let(::scrollToItem) }+ }++ val counts by produceState(0 to 0, doc) {+ val d = doc ?: return@produceState+ delay(300)+ value = withContext(Dispatchers.Default) { countWords(d.blocks) }+ }+ val currentPage by remember(flat) {+ derivedStateOf { flat?.items?.getOrNull(listState.firstVisibleItemIndex + 1)?.page ?: 0 }+ }++ // Picks up where you left off: the page last read, then remembers it (after Gander).+ var resumed by remember { mutableStateOf(false) }+ LaunchedEffect(flat) {+ val f = flat ?: return@LaunchedEffect+ if (!resumed) {+ resumed = true+ val p = viewModel.resumePage+ if (p in 1 until f.pages) listState.scrollToItem(f.pageStarts[p])+ }+ }+ LaunchedEffect(flat, meta.sourceUri) {+ val uri = meta.sourceUri ?: return@LaunchedEffect+ val pages = flat?.pages ?: return@LaunchedEffect+ @OptIn(kotlinx.coroutines.FlowPreview::class)+ snapshotFlow { currentPage }.distinctUntilChanged().debounce(600).collect { p ->+ withContext(Dispatchers.IO) { runCatching { RecentFilesManager.updateProgress(context, uri, p, pages) } }+ }+ }++ // Pinch zoom keeps the point under the fingers in place.+ var lastZoom by remember { mutableFloatStateOf(zoom) }+ LaunchedEffect(zoom) {+ val r = zoom / lastZoom+ lastZoom = zoom+ if (r == 1f) return@LaunchedEffect+ withFrameNanos { }+ val fx = pinchFocus[0]+ val fy = pinchFocus[1]+ hScroll.scrollTo(((hScroll.value + fx) * r - fx).roundToInt().coerceAtLeast(0))+ listState.scrollBy((listState.firstVisibleItemScrollOffset + fy) * (r - 1f))+ }++ // Undo / redo replaced the document: the open field re-reads its paragraph.+ LaunchedEffect(viewModel.restoreEpoch) {+ val id = activeId ?: return@LaunchedEffect+ val p = viewModel.para(id)+ if (p == null) { activeId = null; return@LaunchedEffect }+ val s = activeValue.selection+ activeValue = TextFieldValue(ZWSP + p.text, TextRange(s.start.coerceIn(1, p.text.length + 1), s.end.coerceIn(1, p.text.length + 1)))+ pending = null+ }++ // The formatting bar pushes the page down; at the top of the document, show its first line.+ LaunchedEffect(editMode) {+ if (listState.firstVisibleItemIndex == 0) listState.scrollToItem(0)+ }++ // A paragraph about to take focus may be just off screen (Enter on the last visible line).+ LaunchedEffect(focusTarget) {+ val id = focusTarget ?: return@LaunchedEffect+ val idx = flat?.indexOf?.get(id) ?: return@LaunchedEffect+ val visible = listState.layoutInfo.visibleItemsInfo+ if (visible.none { it.index == idx } || visible.lastOrNull()?.index == idx) {+ listState.animateScrollToItem(idx, -with(density) { 220.dp.roundToPx() })+ }+ }++ fun activate(id: Long, caret: Int) {+ val p = viewModel.para(id) ?: return+ activeId = id+ activeValue = TextFieldValue(ZWSP + p.text, TextRange(1 + caret.coerceIn(0, p.text.length)))+ pending = null+ focusTarget = id+ }++ fun onChange(para: DocPara, v: TextFieldValue) {+ val cur = viewModel.para(para.id) ?: return+ var raw = v.text+ var sel = v.selection+ var composition = v.composition+ if (raw.isEmpty() || raw[0] != ZWSP) {+ if (raw == cur.text) {+ // Backspace at the very start: join this paragraph to the one above.+ val res = viewModel.mergeWithPrevious(cur.id)+ when {+ res == null -> { activeId = cur.id; activeValue = TextFieldValue(ZWSP + cur.text, TextRange(1)) }+ res.first < 0 -> { activeId = null; focusManager.clearFocus() }+ else -> activate(res.first, res.second)+ }+ return+ }+ // A selection that included the marker was replaced: put the marker back.+ raw = ZWSP + raw+ sel = TextRange(sel.start + 1, sel.end + 1)+ composition = null+ }+ val newText = raw.substring(1)+ sel = TextRange(sel.start.coerceAtLeast(1), sel.end.coerceAtLeast(1))+ val old = cur.text+ var pre = 0+ val max = minOf(old.length, newText.length)+ while (pre < max && old[pre] == newText[pre]) pre+++ var suf = 0+ while (suf < max - pre && old[old.length - 1 - suf] == newText[newText.length - 1 - suf]) suf+++ val insEnd = newText.length - suf+ val typing = pending?.takeIf { it.paraId == cur.id && it.at == pre }?.fmt ?: DocxEdits.fmtAt(cur, pre)+ val nl = (pre until insEnd).firstOrNull { newText[it] == '\n' }+ if (nl != null) {+ // Enter (or pasted lines): each new line break typed starts a new paragraph.+ var id = cur.id+ var t = newText+ var k: Int = nl+ var end = insEnd+ while (true) {+ val joined = t.removeRange(k, k + 1)+ val newId = viewModel.split(id, joined, k, typing) ?: break+ id = newId+ t = joined.substring(k)+ end -= k + 1+ val next = (0 until end.coerceAtMost(t.length)).firstOrNull { t[it] == '\n' }+ if (next == null) break+ k = next+ }+ activate(id, end.coerceAtLeast(0))+ return+ }+ if (newText != old) {+ viewModel.typed(cur.id, newText, typing)+ pending = null+ } else if (pending != null && (pending?.paraId != cur.id || sel.start - 1 != pending?.at)) {+ pending = null+ }+ if (activeId != cur.id) viewModel.breakUndoGroup()+ activeId = cur.id+ activeValue = TextFieldValue(raw, sel, composition)+ }++ fun onFocused(para: DocPara) {+ focusedField = para.id+ if (activeId != para.id) {+ viewModel.breakUndoGroup()+ activeId = para.id+ activeValue = TextFieldValue(ZWSP + para.text, TextRange(1))+ pending = null+ }+ }++ fun exitEdit() {+ focusManager.clearFocus()+ activeId = null+ pending = null+ panel = DocPanel.NONE+ editMode = false+ }++ // ── formatting ─────────────────────────────────────────────────────────────++ val styles = pkg?.styles+ val activePara = activeId?.let { id -> doc?.let { findPara(it.blocks, id) } }?.takeIf { it.editable }+ val selModel = activePara?.let { p ->+ val s = activeValue.selection+ (s.min - 1).coerceIn(0, p.text.length) to (s.max - 1).coerceIn(0, p.text.length)+ }+ val curFmt: CharFmt? = if (activePara != null && selModel != null) {+ pending?.takeIf { it.paraId == activePara.id && it.at == selModel.first }?.fmt+ ?: if (selModel.first == selModel.second) DocxEdits.fmtAt(activePara, selModel.first)+ else activePara.fmts.getOrNull(selModel.first) ?: CharFmt.Plain+ } else null+ val curProps: RProps? = if (activePara != null && curFmt != null && styles != null) DocxEdits.effective(activePara, curFmt, styles) else null+ val curPara = if (activePara != null && propsLook != null) propsLook.para(activePara).props else null++ fun applyChar(transform: (DocPara, CharFmt) -> CharFmt) {+ val p = activePara ?: return+ val (s0, e0) = selModel ?: return+ var a = s0+ var b = e0+ if (a == b) {+ val w = wordAround(p.text, a)+ if (w != null) { a = w.first; b = w.second } else {+ val base = pending?.takeIf { it.paraId == p.id && it.at == a }?.fmt ?: DocxEdits.fmtAt(p, a)+ pending = Pending(p.id, a, transform(p, base))+ return+ }+ }+ val np = DocxEdits.format(p, a, b) { transform(p, it) }+ if (np !== p) viewModel.replace(np)+ }++ fun applyPara(f: (DocPara) -> DocPara) {+ val p = activePara ?: return+ viewModel.mapParas(listOf(p.id), f)+ }++ fun toggle(t: DocxEdits.Toggle, current: Boolean) {+ val s = styles ?: return+ applyChar { p, f -> DocxEdits.toggle(p, f, s, t, !current) }+ }++ // ── saving, sharing, printing ──────────────────────────────────────────────++ val saveAsLauncher = rememberLauncherForActivityResult(+ ActivityResultContracts.CreateDocument("application/vnd.openxmlformats-officedocument.wordprocessingml.document")+ ) { uri ->+ if (uri != null) viewModel.save(context, uri) { res ->+ if (res is DocxEditorViewModel.SaveResult.Saved) {+ Toast.makeText(context, R.string.docx_saved, Toast.LENGTH_SHORT).show()+ if (exitAfterSave) onBack()+ } else Toast.makeText(context, R.string.docx_save_failed, Toast.LENGTH_SHORT).show()+ } else exitAfterSave = false+ }+ fun save(asCopy: Boolean) {+ if (asCopy) { saveAsLauncher.launch(viewModel.suggestedSaveAsName()); return }+ viewModel.save(context, null) { res ->+ when (res) {+ is DocxEditorViewModel.SaveResult.Saved -> {+ haptics.performHapticFeedback(HapticFeedbackType.Confirm)+ Toast.makeText(context, R.string.docx_saved, Toast.LENGTH_SHORT).show()+ if (exitAfterSave) onBack()+ }+ is DocxEditorViewModel.SaveResult.NeedsSaveAs -> saveAsLauncher.launch(viewModel.suggestedSaveAsName())+ is DocxEditorViewModel.SaveResult.Failed -> Toast.makeText(context, R.string.docx_save_failed, Toast.LENGTH_SHORT).show()+ }+ }+ }++ // The exact page layout comes from the PDF path, which uses the Office engine (LibreOffice)+ // whenever it is installed.+ fun openAsPdf() {+ if (!viewModel.dirty) meta.sourceUri?.let(onOpenPdf)+ else viewModel.exportToPdf(context) { pdf ->+ if (pdf != null) onOpenPdf(pdf) else Toast.makeText(context, R.string.docx_read_failed, Toast.LENGTH_SHORT).show()+ }+ }+ fun print() {+ Toast.makeText(context, R.string.docx_preparing_print, Toast.LENGTH_SHORT).show()+ viewModel.exportToPdf(context) { pdf ->+ if (pdf == null || !PdfPrint.print(context, pdf, meta.fileName.substringBeforeLast('.')))+ Toast.makeText(context, R.string.docx_print_failed, Toast.LENGTH_SHORT).show()+ }+ }++ fun requestBack() {+ when {+ showGoTo -> showGoTo = false+ panel != DocPanel.NONE -> panel = DocPanel.NONE+ showSearch -> { showSearch = false; searchQuery = "" }+ editMode -> exitEdit()+ viewModel.dirty -> confirmExit = true+ else -> onBack()+ }+ }+ BackHandler(enabled = showGoTo || panel != DocPanel.NONE || showSearch || editMode || viewModel.dirty) { requestBack() }++ val screenBackdrop = rememberScreenBackdrop(backdrop)+ val statusTop = WindowInsets.statusBars.asPaddingValues().calculateTopPadding()+ val ribbonHeight = 52.dp+ // Clear glass like the PDF viewer's chrome; the tint and ink follow the paper (see above).+ val chipTint = chipGlass(onLight = !paperDark)++ Box(+ Modifier+ .fillMaxSize()+ // While editing, Enter belongs to the paragraph being typed in. A hardware Enter (a+ // keyboard, a Chromebook) that arrives while focus sits elsewhere would otherwise "click"+ // whichever glass button holds focus: Save, Done, Share.+ .onPreviewKeyEvent { e ->+ editMode && focusedField == null && (e.key == Key.Enter || e.key == Key.NumPadEnter)+ }+ ) {+ GlassScreenScaffold(+ backdrop = backdrop,+ screenBackdrop = screenBackdrop,+ contentHorizontalPadding = 0.dp,+ headerHorizontalPadding = 12.dp,+ header = { headerBackdrop ->+ Row(+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(10.dp),+ modifier = Modifier.fillMaxWidth()+ ) {+ GlassBackButton(+ onBack = { requestBack() },+ backdrop = headerBackdrop,+ foreground = text,+ onLongPressBack = if (viewModel.dirty || editMode) ({ requestBack() }) else LocalBackToLibraryAction.current,+ longPressLabel = if (viewModel.dirty || editMode) stringResource(R.string.back) else null+ )+ Box(Modifier.weight(1f), contentAlignment = Alignment.Center) {+ GlassTitlePill(+ text = (if (viewModel.dirty) "• " else "") + meta.fileName.ifBlank { stringResource(R.string.viewer_title) },+ backdrop = headerBackdrop,+ surfaceColor = chipTint,+ contentColor = text+ )+ }+ if (viewModel.dirty && editable) {+ val savePulse = if (meta.saving) {+ val t = rememberInfiniteTransition(label = "docSavePulse")+ t.animateFloat(1f, 0.35f, infiniteRepeatable(tween(520), RepeatMode.Reverse), label = "docSavePulseA").value+ } else 1f+ LiquidIconButton(onClick = { if (!meta.saving) save(false) }, backdrop = headerBackdrop) {+ Icon(Icons.Rounded.Check, stringResource(R.string.sheet_save), Modifier.size(22.dp).graphicsLayer { alpha = savePulse }, accent)+ }+ }+ if (!editMode) {+ LiquidIconButton(onClick = { showSearch = true }, backdrop = headerBackdrop) {+ Icon(Icons.Rounded.Search, stringResource(R.string.viewer_find), Modifier.size(20.dp), text)+ }+ LiquidIconButton(onClick = onTogglePaper, backdrop = headerBackdrop) {+ Icon(+ if (paperDark) Icons.Rounded.LightMode else Icons.Rounded.DarkMode,+ stringResource(if (paperDark) R.string.viewer_page_colors_original else R.string.viewer_page_dark_mode),+ Modifier.size(19.dp), text+ )+ }+ }+ if (editable && doc != null) {+ LiquidIconButton(+ onClick = { if (editMode) exitEdit() else { editMode = true; showSearch = false; searchQuery = "" } },+ backdrop = headerBackdrop,+ surfaceColor = if (editMode) accent.copy(0.22f) else Color.Unspecified+ ) {+ if (editMode) BasicText(stringResource(R.string.sheet_done), style = TextStyle(accent, 13.sp, FontWeight.SemiBold))+ else Icon(Icons.Rounded.Edit, stringResource(R.string.sheet_edit), Modifier.size(19.dp), text)+ }+ }+ }+ }+ ) { contentPadding ->+ when {+ meta.isLoading -> Box(Modifier.fillMaxSize().background(desk), contentAlignment = Alignment.Center) {+ CircularProgressIndicator(color = accent, strokeWidth = 2.5.dp)+ }+ pkg == null || doc == null || flat == null -> Column(+ Modifier.fillMaxSize().background(desk).padding(24.dp),+ verticalArrangement = Arrangement.Center,+ horizontalAlignment = Alignment.CenterHorizontally+ ) {+ BasicText(stringResource(R.string.docx_read_failed), style = TextStyle(sub, 15.sp, textAlign = TextAlign.Center))+ if (meta.sourceUri != null) {+ Spacer(Modifier.height(16.dp))+ Row(+ Modifier.clip(RoundedCornerShape(20.dp)).liquidRowClick(corner = 20.dp) { openAsPdf() }+ .background(accent.copy(0.14f)).padding(horizontal = 18.dp, vertical = 10.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ Icon(Icons.Rounded.PictureAsPdf, null, Modifier.size(18.dp), accent)+ BasicText(stringResource(R.string.docx_open_as_pdf), style = TextStyle(accent, 15.sp, FontWeight.SemiBold))+ }+ }+ }+ else -> BoxWithConstraints(+ Modifier+ .fillMaxSize()+ .background(desk)+ // While editing, the page ends above the keyboard and the tool dock, so the+ // paragraph being typed into is never under either.+ .then(if (editMode) Modifier.imePadding().padding(bottom = 76.dp) else Modifier)+ // Two fingers zoom the page (around the point between them); one scrolls.+ .pointerInput(Unit) {+ awaitEachGesture {+ awaitFirstDown(requireUnconsumed = false)+ do {+ val event = awaitPointerEvent(PointerEventPass.Initial)+ if (event.changes.count { it.pressed } >= 2) {+ val z = event.calculateZoom()+ if (z != 1f) {+ val c = event.calculateCentroid(useCurrent = true)+ pinchFocus[0] = c.x+ pinchFocus[1] = c.y+ zoomTarget = (zoomTarget * z).coerceIn(1f, 5f)+ event.changes.forEach { it.consume() }+ }+ }+ } while (event.changes.any { it.pressed })+ }+ }+ ) {+ val page = pkg.page+ val pageWidthPt = (page.width / 20f).coerceAtLeast(72f)+ val fit = ((maxWidth - DeskGutter * 2).value / pageWidthPt).coerceAtLeast(0.1f)+ val dpPerPt = fit * zoom+ val look = remember(pkg, paperDark, dpPerPt, density.fontScale) {+ DocxLook(pkg, paperDark, dpPerPt, density.fontScale, carlito)+ }+ fun tw(v: Int): Dp = (v.coerceAtLeast(0) / 20f * dpPerPt).dp+ val pageW = (pageWidthPt * dpPerPt).dp+ val marginL = tw(page.left)+ val marginR = tw(page.right)+ val marginT = tw(page.top)+ val marginB = tw(page.bottom)+ val env = DocEnv(+ pkg = pkg,+ editMode = editMode,+ activeId = activeId,+ activeValue = activeValue,+ focusTarget = focusTarget,+ labels = labels,+ hits = hitsByPara,+ currentHit = matches.getOrNull(currentMatch),+ accent = accent,+ textWidth = pageW - marginL - marginR,+ onChange = ::onChange,+ onFocused = ::onFocused,+ onBlurred = { p -> if (focusedField == p.id) focusedField = null },+ onFocusConsumed = { focusTarget = null },+ onReadOnlyTap = {+ if (!readOnlyHinted) {+ readOnlyHinted = true+ Toast.makeText(context, R.string.docx_readonly_part, Toast.LENGTH_LONG).show()+ }+ }+ )+ val navBottom = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding()+ val topRound = RoundedCornerShape(topStart = PaperCorner, topEnd = PaperCorner)+ val bottomRound = RoundedCornerShape(bottomStart = PaperCorner, bottomEnd = PaperCorner)+ // One list in one place for both modes: swapping it in and out of the selection+ // container left the shared LazyListState holding a prefetch handle of the+ // disposed list, which crashed the next measure.+ SelectionContainer {+ Box(Modifier.fillMaxSize().horizontalScroll(hScroll)) {+ LazyColumn(+ state = listState,+ contentPadding = PaddingValues(+ start = DeskGutter, end = DeskGutter,+ top = contentPadding.calculateTopPadding() + if (editMode) ribbonHeight + 8.dp else 0.dp,+ bottom = if (editMode) 16.dp else navBottom + 76.dp+ ),+ modifier = Modifier.width(pageW + DeskGutter * 2).fillMaxHeight()+ ) {+ items(flat.items, key = { it.key }, contentType = { it::class }) { item ->+ when (item) {+ is DocItem.Top -> Box(Modifier.width(pageW).height(marginT).background(look.paper, topRound))+ is DocItem.Bottom -> Box(Modifier.width(pageW).height(marginB).background(look.paper, bottomRound))+ is DocItem.Gap -> Column(Modifier.width(pageW)) {+ Box(Modifier.fillMaxWidth().height(marginB).background(look.paper, bottomRound))+ Spacer(Modifier.height(PageGap))+ Box(Modifier.fillMaxWidth().height(marginT).background(look.paper, topRound))+ }+ is DocItem.Para -> Box(Modifier.width(pageW).background(look.paper).padding(start = marginL, end = marginR)) {+ ParagraphBlock(+ item.para, look, env, item.readOnly,+ spaceTop = item.spaceTop && item.first, spaceBottom = item.spaceBottom && item.last,+ range = item.range+ )+ }+ is DocItem.TRow -> Box(Modifier.width(pageW).background(look.paper).padding(start = marginL, end = marginR)) {+ TableRowBlock(item.table, item.row, item.rowIndex, look, env, item.readOnly, env.textWidth)+ }+ }+ }+ }+ }+ }+ }+ }+ }++ // ── edit-mode chrome: formatting bar on top, tool dock above the keyboard ──+ if (pkg != null && styles != null) {+ AnimatedVisibility(+ visible = editMode,+ enter = fadeIn(GlassMotion.fade()),+ exit = fadeOut(GlassMotion.fade()),+ modifier = Modifier.align(Alignment.TopCenter).padding(top = statusTop + 48.dp + 10.dp)+ ) {+ FormatRibbon(+ backdrop = screenBackdrop.glass,+ enabled = activePara != null,+ styleName = curPara?.styleId?.let { styles.byId[it]?.name } ?: styles.defaultParagraphId?.let { styles.byId[it]?.name } ?: "Normal",+ fontName = curProps?.let { it.font ?: pkg.theme.resolve(it.fontTheme) } ?: pkg.theme.minor ?: "Calibri",+ sizeHalfPts = curProps?.size ?: 22,+ text = text,+ accent = accent,+ tint = chipTint,+ onStyle = { name ->+ val id = if (name.equals("Normal", true)) styles.defaultParagraphId else DocxEdits.ensureStyle(styles, name)+ applyPara { DocxEdits.withStyle(it, id, styles) }+ },+ onFont = { f -> applyChar { _, fmt -> DocxEdits.withFont(fmt, f) } },+ onSize = { hp -> applyChar { _, fmt -> DocxEdits.withSize(fmt, hp) } },+ modifier = Modifier.height(ribbonHeight)+ )+ }+ AnimatedVisibility(+ visible = editMode,+ enter = fadeIn(GlassMotion.fade()) + slideInVertically { it / 3 },+ exit = fadeOut(GlassMotion.fade()) + slideOutVertically { it / 3 },+ modifier = Modifier.align(Alignment.BottomCenter).navigationBarsPadding().imePadding()+ .padding(start = 10.dp, end = 10.dp, bottom = 8.dp)+ ) {+ val bold = curProps?.bold == true+ val italic = curProps?.italic == true+ val underline = curProps?.underline == true+ val strike = curProps?.strike == true+ val sup = curProps?.vertAlign == "superscript"+ val align = curPara?.align ?: "left"+ val numId = curPara?.numId?.takeIf { it != 0 }+ val bullet = numId != null && pkg.numbering.isBullet(numId)+ val has = activePara != null+ GlassToolbar(backdrop = screenBackdrop.glass, modifier = Modifier.fillMaxWidth()) {+ GlassToolButton(Icons.AutoMirrored.Rounded.Undo, stringResource(R.string.sheet_undo), false, { viewModel.undo() }, enabled = viewModel.canUndo, accent = accent)+ GlassToolButton(Icons.AutoMirrored.Rounded.Redo, stringResource(R.string.sheet_redo), false, { viewModel.redo() }, enabled = viewModel.canRedo, accent = accent)+ GlassToolButton(Icons.Rounded.FormatBold, stringResource(R.string.sheet_bold), bold, { toggle(DocxEdits.Toggle.BOLD, bold) }, enabled = has, accent = accent)+ GlassToolButton(Icons.Rounded.FormatItalic, stringResource(R.string.sheet_italic), italic, { toggle(DocxEdits.Toggle.ITALIC, italic) }, enabled = has, accent = accent)+ GlassToolButton(Icons.Rounded.FormatUnderlined, stringResource(R.string.sheet_underline), underline, { toggle(DocxEdits.Toggle.UNDERLINE, underline) }, enabled = has, accent = accent)+ GlassToolButton(Icons.Rounded.FormatStrikethrough, stringResource(R.string.sheet_strike), strike, { toggle(DocxEdits.Toggle.STRIKE, strike) }, enabled = has, accent = accent)+ GlassToolButton(Icons.Rounded.FormatColorText, stringResource(R.string.sheet_text_color), panel == DocPanel.TEXT_COLOR, { panel = if (panel == DocPanel.TEXT_COLOR) DocPanel.NONE else DocPanel.TEXT_COLOR }, enabled = has, accent = accent)+ GlassToolButton(Icons.Rounded.BorderColor, stringResource(R.string.docx_highlight), panel == DocPanel.HIGHLIGHT, { panel = if (panel == DocPanel.HIGHLIGHT) DocPanel.NONE else DocPanel.HIGHLIGHT }, enabled = has, accent = accent)+ GlassToolButton(+ when (align) {+ "center" -> Icons.Rounded.FormatAlignCenter+ "right", "end" -> Icons.Rounded.FormatAlignRight+ "both", "distribute" -> Icons.Rounded.FormatAlignJustify+ else -> Icons.Rounded.FormatAlignLeft+ },+ stringResource(R.string.docx_align), false,+ {+ val next = when (align) { "center" -> "right"; "right", "end" -> "both"; "both", "distribute" -> "left"; else -> "center" }+ applyPara { DocxEdits.withAlign(it, next) }+ },+ enabled = has, accent = accent+ )+ GlassToolButton(Icons.Rounded.FormatListBulleted, stringResource(R.string.docx_bullets), bullet, {+ applyPara { p -> DocxEdits.withList(p, if (bullet) null else pkg.numbering.ensureList(true), styles) }+ }, enabled = has, accent = accent)+ GlassToolButton(Icons.Rounded.FormatListNumbered, stringResource(R.string.docx_numbering), numId != null && !bullet, {+ applyPara { p -> DocxEdits.withList(p, if (numId != null && !bullet) null else pkg.numbering.ensureList(false), styles) }+ }, enabled = has, accent = accent)+ GlassToolButton(Icons.Rounded.FormatIndentDecrease, stringResource(R.string.docx_indent_less), false, {+ propsLook?.let { l -> applyPara { p -> indent(p, -1, l, styles) } }+ }, enabled = has, accent = accent)+ GlassToolButton(Icons.Rounded.FormatIndentIncrease, stringResource(R.string.docx_indent_more), false, {+ propsLook?.let { l -> applyPara { p -> indent(p, 1, l, styles) } }+ }, enabled = has, accent = accent)+ GlassToolButton(Icons.Rounded.Superscript, stringResource(R.string.docx_superscript), sup, { toggle(DocxEdits.Toggle.SUPERSCRIPT, sup) }, enabled = has, accent = accent)+ GlassToolButton(Icons.Rounded.FormatClear, stringResource(R.string.docx_clear), false, { applyChar { _, f -> DocxEdits.cleared(f) } }, enabled = has, accent = accent)+ GlassToolButton(Icons.Rounded.SaveAs, stringResource(R.string.sheet_save_as), false, { save(true) }, accent = accent)+ }+ }+ }++ // ── reading chrome: page counter, print, PDF layout and share ──+ if (doc != null && flat != null && !editMode && !showSearch) {+ Row(+ Modifier.align(Alignment.BottomStart).navigationBarsPadding().padding(start = 12.dp, bottom = 10.dp)+ .height(44.dp)+ .viewerGlass(screenBackdrop.glass, chipTint, shape = { Capsule })+ .clip(Capsule)+ .liquidRowClick(corner = 22.dp) { showGoTo = true }+ .padding(horizontal = 16.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ BasicText(+ stringResource(R.string.docx_page_of, currentPage + 1, flat.pages) ++ if (zoom != 1f) " · ${(zoom * 100).roundToInt()}%" else "",+ style = TextStyle(text, 12.sp, FontWeight.SemiBold),+ maxLines = 1+ )+ }+ Row(+ Modifier.align(Alignment.BottomEnd).navigationBarsPadding().padding(end = 12.dp, bottom = 10.dp),+ horizontalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ LiquidIconButton(onClick = { print() }, backdrop = screenBackdrop.glass, modifier = Modifier.size(44.dp)) {+ Icon(Icons.Rounded.Print, stringResource(R.string.docx_print), Modifier.size(20.dp), text)+ }+ LiquidIconButton(onClick = { openAsPdf() }, backdrop = screenBackdrop.glass, modifier = Modifier.size(44.dp)) {+ Icon(Icons.Rounded.PictureAsPdf, stringResource(R.string.docx_open_as_pdf), Modifier.size(20.dp), text)+ }+ LiquidIconButton(+ onClick = { viewModel.currentFile(context) { u -> u?.let { shareFile(context, it) } } },+ backdrop = screenBackdrop.glass,+ modifier = Modifier.size(44.dp)+ ) {+ Icon(Icons.Rounded.IosShare, stringResource(R.string.viewer_share_document), Modifier.size(20.dp), text)+ }+ }+ }++ // Find: the same glass bar as the PDF viewer's, refracting the live page behind it.+ AnimatedVisibility(+ visible = showSearch,+ enter = fadeIn(tween(180)) + slideInVertically { it },+ exit = fadeOut(tween(140)) + slideOutVertically { it },+ modifier = Modifier.align(Alignment.BottomCenter).navigationBarsPadding().imePadding().padding(horizontal = 12.dp, vertical = 12.dp)+ ) {+ PdfSearchBar(+ query = searchQuery,+ matchCount = matches.size,+ currentMatchIndex = currentMatch,+ focusRequester = searchFocus,+ backdrop = screenBackdrop.content,+ uiSensor = uiSensor,+ fg = text,+ fgSoft = sub,+ surface = Color.Transparent,+ onQueryChange = { searchQuery = it },+ onPrevMatch = { goToMatch(-1) },+ onNextMatch = { goToMatch(1) },+ onClose = { showSearch = false; searchQuery = "" }+ )+ }++ // Text / highlight colour.+ AnimatedVisibility(+ visible = panel != DocPanel.NONE,+ enter = fadeIn(GlassMotion.fade()) + scaleIn(GlassMotion.pop(), initialScale = 0.94f),+ exit = fadeOut(GlassMotion.fade()) + scaleOut(targetScale = 0.96f),+ modifier = Modifier.fillMaxSize()+ ) {+ var lastPanel by remember { mutableStateOf(DocPanel.TEXT_COLOR) }+ if (panel != DocPanel.NONE) lastPanel = panel+ val highlight = lastPanel == DocPanel.HIGHLIGHT+ Box(Modifier.fillMaxSize().clickable(remember { MutableInteractionSource() }, indication = null) { panel = DocPanel.NONE }) {+ val current = if (highlight) curProps?.highlight else curProps?.color+ GlassColorPicker(+ color = current?.takeIf { it != 0 }?.let { Color(it) } ?: if (highlight) Color.Transparent else Color.Black,+ onColorChange = { c ->+ val argb = c.toArgb()+ applyChar { _, f -> if (highlight) DocxEdits.withHighlight(f, argb) else DocxEdits.withColor(f, argb) }+ },+ backdrop = screenBackdrop.glass,+ themeColors = if (highlight) HighlightColors.values.take(10).map { Color(it) } else OfficeThemeColors,+ standardColors = if (highlight) HighlightColors.values.drop(6).take(10).map { Color(it) } else OfficeStandardColors,+ onClear = {+ applyChar { _, f -> if (highlight) DocxEdits.withHighlight(f, null) else DocxEdits.withColor(f, null) }+ panel = DocPanel.NONE+ },+ clearLabel = stringResource(if (highlight) R.string.docx_no_highlight else R.string.sheet_automatic),+ modifier = Modifier+ .align(Alignment.BottomCenter)+ .navigationBarsPadding()+ .imePadding()+ .padding(start = 12.dp, end = 12.dp, bottom = 84.dp)+ .widthIn(max = 420.dp)+ .clickable(remember { MutableInteractionSource() }, indication = null) {}+ )+ }+ }++ // Go to page, the page counter's dialog.+ if (flat != null) {+ var pageInput by remember(showGoTo) { mutableStateOf("") }+ fun go() {+ val n = pageInput.trim().toIntOrNull() ?: return+ val p = (n - 1).coerceIn(0, flat.pages - 1)+ showGoTo = false+ scope.launch { listState.scrollToItem(flat.pageStarts[p]) }+ }+ GlassDialog(+ visible = showGoTo,+ onDismiss = { showGoTo = false },+ backdrop = screenBackdrop.glass,+ title = stringResource(R.string.docx_go_to_page),+ actions = {+ GlassDialogAction(stringResource(R.string.docx_fit_width), onClick = { zoomTarget = 1f; showGoTo = false })+ GlassDialogAction(stringResource(R.string.docx_go), onClick = { go() }, primary = true, enabled = pageInput.toIntOrNull() != null)+ }+ ) {+ val nf = remember { java.text.NumberFormat.getIntegerInstance() }+ BasicText(+ stringResource(R.string.docx_status, nf.format(counts.first), nf.format(counts.second)),+ style = TextStyle(sub, 13.sp)+ )+ Spacer(Modifier.height(12.dp))+ val fieldFocus = remember { FocusRequester() }+ LaunchedEffect(showGoTo) { if (showGoTo) runCatching { delay(120); fieldFocus.requestFocus() } }+ BasicTextField(+ value = pageInput,+ onValueChange = { v -> pageInput = v.filter { it.isDigit() }.take(5) },+ singleLine = true,+ textStyle = TextStyle(text, 17.sp, FontWeight.SemiBold),+ cursorBrush = SolidColor(accent),+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Go),+ keyboardActions = KeyboardActions(onGo = { go() }),+ modifier = Modifier+ .fillMaxWidth()+ .heightIn(min = 46.dp)+ .clip(RoundedCornerShape(14.dp))+ .background(text.copy(0.07f))+ .padding(horizontal = 14.dp, vertical = 12.dp)+ .focusRequester(fieldFocus),+ decorationBox = { inner ->+ if (pageInput.isEmpty()) BasicText(+ stringResource(R.string.docx_page_hint, flat.pages),+ style = TextStyle(sub, 17.sp)+ )+ inner()+ }+ )+ }+ }++ UnsavedChangesDialog(+ visible = confirmExit,+ onDiscard = { confirmExit = false; onBack() },+ onCancel = { confirmExit = false },+ onSave = { confirmExit = false; exitAfterSave = true; save(false) },+ backdrop = screenBackdrop.glass,+ title = stringResource(R.string.unsaved_title),+ body = stringResource(R.string.docx_unsaved_body),+ saveLabel = stringResource(R.string.sheet_save),+ accent = accent+ )+ }+}++private fun indent(p: DocPara, dir: Int, look: DocxLook, styles: DocxStyles): DocPara {+ val pp = look.para(p).props+ val numId = pp.numId?.takeIf { it != 0 }+ return if (numId != null) DocxEdits.withList(p, numId, styles, ((pp.ilvl ?: 0) + dir).coerceIn(0, 8))+ else DocxEdits.withLeftIndent(p, (Props.p(p.pPr).left ?: 0) + 720 * dir)+}++/** The word the caret is strictly inside (Word formats the whole word then), or null. */+private fun wordAround(text: String, at: Int): Pair<Int, Int>? {+ fun w(c: Char) = c.isLetterOrDigit() || c == '\'' || c == '’'+ if (at <= 0 || at >= text.length || !w(text[at - 1]) || !w(text[at])) return null+ var a = at+ var b = at+ while (a > 0 && w(text[a - 1])) a--+ while (b < text.length && w(text[b])) b+++ return a to b+}++// ── formatting bar ─────────────────────────────────────────────────────────────++private val GalleryStyles = listOf("Normal", "Title", "Subtitle", "heading 1", "heading 2", "heading 3", "Quote")+private val Fonts = listOf("Calibri", "Aptos", "Arial", "Times New Roman", "Georgia", "Cambria", "Verdana", "Courier New")+private val SizesHalfPts = listOf(16, 18, 20, 21, 22, 24, 28, 32, 36, 40, 44, 48, 52, 56, 72, 96, 144)++@Composable+private fun styleLabel(name: String): String = when (name.lowercase()) {+ "normal" -> stringResource(R.string.docx_style_normal)+ "title" -> stringResource(R.string.docx_style_title)+ "subtitle" -> stringResource(R.string.docx_style_subtitle)+ "heading 1" -> stringResource(R.string.docx_style_h1)+ "heading 2" -> stringResource(R.string.docx_style_h2)+ "heading 3" -> stringResource(R.string.docx_style_h3)+ "quote" -> stringResource(R.string.docx_style_quote)+ else -> name.replaceFirstChar { it.uppercase() }+}++/** LibreOffice Writer's "Formatting" bar, in glass: paragraph style · font · size. */+@Composable+private fun FormatRibbon(+ backdrop: Backdrop,+ enabled: Boolean,+ styleName: String,+ fontName: String,+ sizeHalfPts: Int,+ text: Color,+ accent: Color,+ tint: Color,+ onStyle: (String) -> Unit,+ onFont: (String) -> Unit,+ onSize: (Int) -> Unit,+ modifier: Modifier = Modifier+) {+ val styleOptions = (if (GalleryStyles.none { it.equals(styleName, true) }) listOf(styleName) else emptyList()) + GalleryStyles+ val fontOptions = (if (Fonts.none { it.equals(fontName, true) }) listOf(fontName) else emptyList()) + Fonts+ Row(+ modifier+ .fillMaxWidth()+ .graphicsLayer { alpha = if (enabled) 1f else 0.55f }+ .horizontalScroll(rememberScrollState())+ .padding(horizontal = 12.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ LiquidGlassDropdown(+ options = styleOptions.map { GlassDropdownOption(it.lowercase(), styleLabel(it)) },+ selected = styleName.lowercase(),+ onSelect = { v -> if (enabled) onStyle(styleOptions.first { it.lowercase() == v }) },+ backdrop = backdrop,+ leadingIcon = Icons.Rounded.TextFields,+ accent = accent,+ triggerSurface = tint,+ contentColor = text,+ modifier = Modifier.width(150.dp)+ )+ LiquidGlassDropdown(+ options = fontOptions.map { GlassDropdownOption(it, it) },+ selected = fontOptions.firstOrNull { it.equals(fontName, true) } ?: fontName,+ onSelect = { if (enabled) onFont(it) },+ backdrop = backdrop,+ leadingIcon = Icons.Rounded.FontDownload,+ accent = accent,+ triggerSurface = tint,+ contentColor = text,+ modifier = Modifier.width(158.dp)+ )+ Row(+ Modifier.height(44.dp).viewerGlass(backdrop, tint, shape = { Capsule }),+ verticalAlignment = Alignment.CenterVertically+ ) {+ val down = SizesHalfPts.lastOrNull { it < sizeHalfPts } ?: SizesHalfPts.first()+ val up = SizesHalfPts.firstOrNull { it > sizeHalfPts } ?: SizesHalfPts.last()+ Box(Modifier.size(44.dp).clip(Capsule).liquidRowClick(corner = 22.dp, enabled = enabled) { onSize(down) }, contentAlignment = Alignment.Center) {+ Icon(Icons.Rounded.Remove, stringResource(R.string.docx_size_down), Modifier.size(18.dp), text)+ }+ val pt = sizeHalfPts / 2f+ BasicText(+ if (pt % 1f == 0f) pt.toInt().toString() else pt.toString(),+ Modifier.widthIn(min = 26.dp),+ style = TextStyle(text, 15.sp, FontWeight.SemiBold, textAlign = TextAlign.Center)+ )+ Box(Modifier.size(44.dp).clip(Capsule).liquidRowClick(corner = 22.dp, enabled = enabled) { onSize(up) }, contentAlignment = Alignment.Center) {+ Icon(Icons.Rounded.Add, stringResource(R.string.docx_size_up), Modifier.size(18.dp), text)+ }+ }+ }+}++// ── paragraphs ────────────────────────────────────────────────────────────────++/** Shows the paragraph's runs in the field; the leading marker and objects stay invisible. */+private class DocTransformation(private val annotated: AnnotatedString) : VisualTransformation {+ override fun filter(text: AnnotatedString): TransformedText {+ val t = text.text+ val out = if (t.length == annotated.length + 1) AnnotatedString(ZWSP.toString()) + annotated+ else AnnotatedString(t.replace(OBJ_CHAR, ZWSP))+ return TransformedText(out, OffsetMapping.Identity)+ }+}++@Composable+private fun ParagraphBlock(+ para: DocPara,+ look: DocxLook,+ env: DocEnv,+ readOnly: Boolean,+ spaceTop: Boolean = true,+ spaceBottom: Boolean = true,+ cell: RProps? = null,+ /** The part of the paragraph shown here, when Word broke it across pages (reading only). */+ range: IntRange? = null,+ maxWidth: Dp = env.textWidth+) {+ val pl = remember(para.pPr, look, cell) { look.para(para, cell) }+ val editable = env.editMode && !readOnly && para.editable && range == null+ val hits = env.hits[para.id].orEmpty()+ val current = env.currentHit?.takeIf { it.first == para.id }?.second+ val full = remember(para, look, cell, hits, current, editable) {+ look.annotate(para, pl, cell, hits, current, withLinks = !editable)+ }+ val annotated = remember(full, range) { if (range == null) full else full.subSequence(range.first, (range.last + 1).coerceAtMost(full.length)) }+ val objects = remember(para, range) {+ para.fmts.withIndex().filter { (i, f) -> f.obj != null && (range == null || i in range) }.map { DocxObjects.info(it.value.obj!!) }+ }+ val pictures = objects.filter { it.imageRid != null }+ val boxes = objects.filter { it.textBox.isNotEmpty() }+ val blank = remember(annotated) { annotated.text.all { it == ZWSP || it.isWhitespace() } }+ val first = range == null || range.first == 0+ val label = if (first) env.labels[para.id] else null+ val dir = if (pl.rtl) LayoutDirection.Rtl else LocalLayoutDirection.current++ CompositionLocalProvider(LocalLayoutDirection provides dir) {+ Column(+ Modifier+ .fillMaxWidth()+ .padding(top = if (spaceTop) pl.before else 0.dp, bottom = if (spaceBottom) pl.after else 0.dp)+ .then(if (pl.shading != null) Modifier.background(pl.shading) else Modifier)+ .padding(start = pl.padStart, end = pl.padEnd)+ ) {+ val paraAlign = when (pl.style.textAlign) {+ TextAlign.Center -> Alignment.CenterHorizontally+ TextAlign.End, TextAlign.Right -> Alignment.End+ else -> Alignment.Start+ }+ for (pic in pictures) {+ val align = when (pic.hAlign) {+ "center" -> Alignment.CenterHorizontally+ "right", "outside" -> Alignment.End+ "left", "inside" -> Alignment.Start+ else -> paraAlign+ }+ DocPicture(pic, env.pkg, look, maxWidth - pl.padStart - pl.padEnd, align)+ }+ for (box in boxes) {+ Column(+ Modifier.fillMaxWidth().padding(vertical = 4.dp)+ .border(0.5.dp, look.ink.copy(0.22f), RoundedCornerShape(4.dp))+ .padding(8.dp)+ ) {+ for (b in box.textBox) StaticBlock(b, look, env)+ }+ }+ if (!(blank && (pictures.isNotEmpty() || boxes.isNotEmpty()) && !editable)) {+ Row(Modifier.fillMaxWidth()) {+ if (label != null) {+ BasicText(+ label,+ Modifier.width(pl.hanging).alignByBaseline(),+ style = pl.style.copy(textAlign = TextAlign.Start, textIndent = null),+ maxLines = 1+ )+ }+ Box(Modifier.weight(1f).alignByBaseline()) {+ if (editable) ParaField(para, pl, full, env)+ else BasicText(+ annotated,+ style = if (first) pl.style else pl.style.copy(textIndent = null),+ modifier = if (env.editMode && !readOnly) Modifier.clickable(remember { MutableInteractionSource() }, indication = null) { env.onReadOnlyTap() } else Modifier+ )+ }+ }+ }+ if (pl.borderBottom && (range == null || range.last >= para.text.length - 1)) {+ Box(Modifier.fillMaxWidth().padding(top = 3.dp).height(1.dp).background(look.ink.copy(0.55f)))+ }+ }+ }+}++@Composable+private fun ParaField(para: DocPara, pl: ParaLook, annotated: AnnotatedString, env: DocEnv) {+ val active = env.activeId == para.id+ val value = if (active) {+ val v = env.activeValue+ if (v.text.length == para.text.length + 1 && v.text.endsWith(para.text)) v+ else TextFieldValue(ZWSP + para.text, TextRange(v.selection.start.coerceIn(1, para.text.length + 1), v.selection.end.coerceIn(1, para.text.length + 1)))+ } else TextFieldValue(ZWSP + para.text, TextRange(1))+ val focus = remember { FocusRequester() }+ LaunchedEffect(env.focusTarget) {+ if (env.focusTarget == para.id) {+ runCatching { focus.requestFocus() }+ env.onFocusConsumed()+ }+ }+ val transformation = remember(annotated) { DocTransformation(annotated) }+ BasicTextField(+ value = value,+ onValueChange = { env.onChange(para, it) },+ textStyle = pl.style,+ cursorBrush = SolidColor(env.accent),+ visualTransformation = transformation,+ modifier = Modifier+ .fillMaxWidth()+ .focusRequester(focus)+ .onFocusChanged { if (it.isFocused) env.onFocused(para) else env.onBlurred(para) }+ )+}++/** Content shown but not edited: text boxes, content controls, nested previews. */+@Composable+private fun StaticBlock(block: DocBlock, look: DocxLook, env: DocEnv) {+ when (block) {+ is DocPara -> ParagraphBlock(block, look, env, readOnly = true)+ is DocTable -> Column(Modifier.fillMaxWidth()) {+ for ((i, r) in block.rows.withIndex()) TableRowBlock(block, r, i, look, env, readOnly = true, availWidth = env.textWidth)+ }+ is DocRaw -> for (b in block.preview) StaticBlock(b, look, env)+ }+}++// ── pictures ──────────────────────────────────────────────────────────────────++private class DecodedPicture(val image: ImageBitmap, val paperLike: Boolean)++private object DocImages {+ private val cache = object : LruCache<String, Pair<Bitmap, Boolean>>(48 * 1024 * 1024) {+ override fun sizeOf(key: String, value: Pair<Bitmap, Boolean>) = value.first.byteCount+ }++ fun decode(key: String, bytes: ByteArray, targetW: Int): DecodedPicture? {+ cache.get(key)?.let { return DecodedPicture(it.first.asImageBitmap(), it.second) }+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)+ if (bounds.outWidth <= 0) return null+ var sample = 1+ while (bounds.outWidth / (sample * 2) >= targetW.coerceAtLeast(1)) sample *= 2+ val bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample }) ?: return null+ // A scan or a chart on white turns over with dark paper; a photograph never does.+ val paper = runCatching { NightPaper.looksLikePaper(bmp) }.getOrDefault(false)+ cache.put(key, bmp to paper)+ return DecodedPicture(bmp.asImageBitmap(), paper)+ }+}++@Composable+private fun DocPicture(info: ObjInfo, pkg: DocxPackage, look: DocxLook, maxWidth: Dp, align: Alignment.Horizontal) {+ val rid = info.imageRid ?: return+ val bytes = remember(pkg, rid) { pkg.image(rid) }+ val want = if (info.widthPt > 0f) (info.widthPt * look.scale).dp else maxWidth+ val w = want.coerceAtMost(maxWidth.coerceAtLeast(24.dp)).coerceAtLeast(12.dp)+ val px = with(LocalDensity.current) { w.roundToPx() }+ val bucket = (px / 128 + 1) * 128+ val pic by produceState<DecodedPicture?>(null, bytes, bucket) {+ val b = bytes ?: return@produceState+ value = withContext(Dispatchers.IO) { runCatching { DocImages.decode("$rid@${System.identityHashCode(pkg)}@$bucket", b, bucket) }.getOrNull() }+ }+ val ratio = if (info.widthPt > 0f && info.heightPt > 0f) info.heightPt / info.widthPt+ else pic?.image?.let { it.height.toFloat() / it.width.coerceAtLeast(1) } ?: 0.6f+ Column(Modifier.fillMaxWidth().padding(vertical = 2.dp), horizontalAlignment = align) {+ Box(+ Modifier.width(w).aspectRatio((1f / ratio.coerceIn(0.05f, 20f)))+ .background(if (pic == null) look.ink.copy(0.06f) else Color.Transparent)+ ) {+ pic?.let {+ Image(+ it.image, null, Modifier.fillMaxSize(), contentScale = ContentScale.Fit,+ colorFilter = if (look.dark && it.paperLike) NightPaper.filter else null+ )+ }+ }+ }+}++// ── tables ────────────────────────────────────────────────────────────────────++private class TableLook(+ val fractions: FloatArray,+ val width: Dp,+ val indent: Dp,+ val jc: String?,+ val borders: Boolean,+ val headerFill: Int?,+ val headerR: RProps?,+ val bandFill: Int?,+ val firstRow: Boolean,+ val bands: Boolean,+ val scale: Float+)++private class CellProps(val span: Int, val vContinue: Boolean, val fill: Int?, val vAlign: String?)++private val cellPropsCache = HashMap<String, CellProps>()+private val tableLookCache = java.util.WeakHashMap<DocTable, Pair<Float, TableLook>>()++private fun cellProps(tcPr: String): CellProps = synchronized(cellPropsCache) {+ cellPropsCache.getOrPut(tcPr) {+ val root = if (tcPr.isEmpty()) null else XmlScan.scan(tcPr).children.firstOrNull()+ fun child(n: String): XNode? = root?.child(n)+ val vm = child("vMerge")+ CellProps(+ span = child("gridSpan")?.attr(tcPr, "val")?.toIntOrNull()?.coerceAtLeast(1) ?: 1,+ vContinue = vm != null && (vm.attr(tcPr, "val") ?: "continue") == "continue",+ fill = Props.hex(child("shd")?.attr(tcPr, "fill")),+ vAlign = child("vAlign")?.attr(tcPr, "val")+ )+ }+}++/**+ * A table at its real size on the page: Word's column grid, alignment and indent. Only a table+ * wider than the page's text area (plus a little of the margin, which Word allows) is shrunk.+ */+private fun tableLookOf(t: DocTable, pkg: DocxPackage, look: DocxLook, availWidth: Dp): TableLook {+ val cacheKey = look.scale * 100_000f + availWidth.value+ synchronized(tableLookCache) { tableLookCache[t]?.let { if (it.first == cacheKey) return it.second } }+ val tblPr = if (t.tblPr.isEmpty()) null else XmlScan.scan(t.tblPr).children.firstOrNull()+ val styleId = tblPr?.child("tblStyle")?.attr(t.tblPr, "val")+ val chain = pkg.styles.chain(styleId)+ fun bordersIn(xml: String): Boolean? {+ val n = (if (xml.isEmpty()) null else XmlScan.scan(xml).children.firstOrNull())?.child("tblBorders") ?: return null+ return n.children.any { b -> (b.attr(xml, "val") ?: "none").let { it != "none" && it != "nil" } }+ }+ var borders = bordersIn(t.tblPr)+ if (borders == null) for (s in chain.asReversed()) { borders = bordersIn(s.tblPr); if (borders != null) break }+ val lookEl = tblPr?.child("tblLook")+ val lookVal = lookEl?.attr(t.tblPr, "val")?.toIntOrNull(16) ?: 0x04A0+ val firstRow = lookEl?.attr(t.tblPr, "firstRow")?.let { it == "1" || it == "true" } ?: (lookVal and 0x20 != 0)+ val noHBand = lookEl?.attr(t.tblPr, "noHBand")?.let { it == "1" || it == "true" } ?: (lookVal and 0x200 != 0)+ var headFill: Int? = null+ var headR: RProps? = null+ var bandFill: Int? = null+ for (s in chain) {+ s.conditional["firstRow"]?.let { (tc, r) ->+ cellProps(tc).fill?.let { headFill = it }+ if (r.isNotEmpty()) headR = Props.r(r).over(headR ?: RProps())+ }+ s.conditional["band1Horz"]?.let { (tc, _) -> cellProps(tc).fill?.let { bandFill = it } }+ }+ val cols = if (t.grid.isNotEmpty() && t.grid.sum() > 0) t.grid else {+ val n = t.rows.maxOfOrNull { r -> r.cells.sumOf { cellProps(it.tcPr).span } } ?: 1+ List(n.coerceAtLeast(1)) { 1 }+ }+ val total = cols.sum().toFloat().coerceAtLeast(1f)+ val natural = if (t.grid.isNotEmpty()) (total / 20f * look.scale).dp else availWidth+ val room = availWidth * 1.12f+ val scale = if (natural > room) (room.value / natural.value).coerceIn(0.45f, 1f) else 1f+ val jc = tblPr?.child("jc")?.attr(t.tblPr, "val")+ val ind = tblPr?.child("tblInd")?.let { n ->+ if (n.attr(t.tblPr, "type") == "dxa" || n.attr(t.tblPr, "type") == null) (n.attr(t.tblPr, "w")?.toFloatOrNull() ?: 0f) / 20f * look.scale else 0f+ } ?: 0f+ val tl = TableLook(+ fractions = FloatArray(cols.size) { cols[it] / total },+ width = natural * scale,+ indent = ind.dp,+ jc = jc,+ borders = borders == true,+ headerFill = headFill,+ headerR = headR,+ bandFill = bandFill,+ firstRow = firstRow,+ bands = !noHBand,+ scale = (scale * 20f).roundToInt() / 20f+ )+ synchronized(tableLookCache) { tableLookCache[t] = cacheKey to tl }+ return tl+}++@Composable+private fun TableRowBlock(table: DocTable, row: DocRow, rowIndex: Int, look: DocxLook, env: DocEnv, readOnly: Boolean, availWidth: Dp) {+ val tl = remember(table, look, availWidth) { tableLookOf(table, env.pkg, look, availWidth) }+ val cellLook = look.scaled(tl.scale)+ val lastRow = rowIndex == table.rows.lastIndex+ val gridBefore = remember(row.trPr) {+ if (row.trPr.isEmpty()) 0 else XmlScan.scan(row.trPr).children.firstOrNull()?.child("gridBefore")?.attr(row.trPr, "val")?.toIntOrNull() ?: 0+ }+ val header = tl.firstRow && rowIndex == 0+ val banded = tl.bands && tl.bandFill != null && !header && (rowIndex - if (tl.firstRow) 1 else 0) % 2 == 0+ val line = if (tl.borders) look.ink.copy(0.55f) else if (env.editMode) look.ink.copy(0.14f) else Color.Transparent+ fun frac(from: Int, span: Int): Float {+ var f = 0f+ for (i in from until (from + span).coerceAtMost(tl.fractions.size)) f += tl.fractions[i]+ return f.coerceAtLeast(0.0001f)+ }+ val boxAlign = when (tl.jc) {+ "center" -> Alignment.TopCenter+ "right", "end" -> Alignment.TopEnd+ else -> Alignment.TopStart+ }+ Box(Modifier.fillMaxWidth(), contentAlignment = boxAlign) {+ Row(+ Modifier+ .then(if (boxAlign == Alignment.TopStart && tl.indent != 0.dp) Modifier.offset(x = tl.indent) else Modifier)+ .width(tl.width)+ .height(IntrinsicSize.Min)+ ) {+ var col = gridBefore+ if (gridBefore > 0) Spacer(Modifier.weight(frac(0, gridBefore)))+ val cells = row.cells+ for ((ci, cell) in cells.withIndex()) {+ val cp = cellProps(cell.tcPr)+ val fill = cp.fill ?: if (header) tl.headerFill else if (banded) tl.bandFill else null+ val lastCell = ci == cells.lastIndex+ val f = frac(col, cp.span)+ val cellWidth = tl.width * f+ Box(+ Modifier+ .weight(f)+ .fillMaxHeight()+ .then(look.fillOf(fill)?.let { Modifier.background(it) } ?: Modifier)+ .drawBehind {+ if (line.alpha == 0f) return@drawBehind+ val sw = 1.dp.toPx().coerceAtMost(2f)+ if (!cp.vContinue) drawLine(line, Offset(0f, 0f), Offset(size.width, 0f), sw)+ drawLine(line, Offset(0f, 0f), Offset(0f, size.height), sw)+ if (lastCell) drawLine(line, Offset(size.width, 0f), Offset(size.width, size.height), sw)+ if (lastRow) drawLine(line, Offset(0f, size.height), Offset(size.width, size.height), sw)+ }+ .padding(horizontal = (5.4f * cellLook.scale).dp, vertical = 1.dp),+ contentAlignment = when (cp.vAlign) {+ "center" -> Alignment.CenterStart+ "bottom" -> Alignment.BottomStart+ else -> Alignment.TopStart+ }+ ) {+ if (!cp.vContinue) Column(Modifier.fillMaxWidth()) {+ val inner = cellWidth - (10.8f * cellLook.scale).dp+ for (b in cell.blocks) when (b) {+ is DocPara -> ParagraphBlock(b, cellLook, env, readOnly || !b.editable, cell = if (header) tl.headerR else null, maxWidth = inner)+ is DocTable -> Column(Modifier.fillMaxWidth()) {+ for ((i, r) in b.rows.withIndex()) TableRowBlock(b, r, i, cellLook, env, readOnly, inner)+ }+ is DocRaw -> for (x in b.preview) StaticBlock(x, cellLook, env)+ }+ }+ }+ col += cp.span+ }+ val used = col+ if (used < tl.fractions.size) Spacer(Modifier.weight(frac(used, tl.fractions.size - used)))+ }+ }+}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/DocxLook.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/DocxLook.ktnew file mode 100644index 0000000..9221499--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/DocxLook.kt@@ -0,0 +1,304 @@+package com.chethan616.clearpdf.ui.screen++import androidx.compose.ui.graphics.Color+import androidx.compose.ui.text.AnnotatedString+import androidx.compose.ui.text.LinkAnnotation+import androidx.compose.ui.text.SpanStyle+import androidx.compose.ui.text.TextLinkStyles+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.font.Font+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.font.FontStyle+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.BaselineShift+import androidx.compose.ui.text.style.LineHeightStyle+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextDecoration+import androidx.compose.ui.text.style.TextDirection+import androidx.compose.ui.text.style.TextIndent+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.em+import androidx.compose.ui.unit.sp+import com.chethan616.clearpdf.ui.components.NightPaper+import com.chethan616.clearpdf.R+import com.chethan616.clearpdf.docx.CharFmt+import com.chethan616.clearpdf.docx.DocBlock+import com.chethan616.clearpdf.docx.DocPara+import com.chethan616.clearpdf.docx.DocxNumbering+import com.chethan616.clearpdf.docx.DocxPackage+import com.chethan616.clearpdf.docx.OBJ_CHAR+import com.chethan616.clearpdf.docx.PProps+import com.chethan616.clearpdf.docx.Props+import com.chethan616.clearpdf.docx.RProps+import com.chethan616.clearpdf.docx.XmlScan+import com.chethan616.clearpdf.docx.forEachPara++/** How one paragraph sits on the page. Lengths already scaled to the screen. */+internal class ParaLook(+ val style: TextStyle,+ val padStart: Dp,+ val padEnd: Dp,+ val before: Dp,+ val after: Dp,+ /** List label column (hanging indent); 0 when none. */+ val hanging: Dp,+ val shading: Color?,+ val rtl: Boolean,+ val borderBottom: Boolean,+ /** Character properties the paragraph style gives its text. */+ val rBase: RProps,+ val props: PProps+)++/**+ * Turns document formatting into Compose text styles for one paper colour and zoom. Points become+ * `scale` sp, so a page reflows to the phone's width at a readable size (Word's "mobile view")+ * instead of shrinking a whole A4 line onto it.+ */+internal class DocxLook(+ val pkg: DocxPackage,+ val dark: Boolean,+ /** Screen dp per point: the page is laid out at its true proportions, scaled to the screen. */+ val scale: Float,+ /** The system font scale; text sizes are divided by it so the page keeps Word's line breaks. */+ private val fontScale: Float,+ private val carlito: FontFamily+) {+ /** sp per point for text, so a 12 pt run is exactly as wide (in dp) as the page expects. */+ private val sp = scale / fontScale.coerceAtLeast(0.5f)+ val paper = if (dark) Color(0xFF1C1C1E) else Color.White+ val ink = if (dark) Color(0xFFE6E6EA) else Color(0xFF111111)+ val link = if (dark) Color(0xFF6CB4FF) else Color(0xFF0563C1)+ private val styles = pkg.styles+ private val paraCache = HashMap<String, ParaLook>()+ private val scaledCache = HashMap<Float, DocxLook>()++ /** The same look at a fraction of the size, for tables too wide for the screen. */+ fun scaled(f: Float): DocxLook =+ if (f >= 0.999f) this else scaledCache.getOrPut(f) { DocxLook(pkg, dark, scale * f, fontScale, carlito) }++ fun family(name: String?, themeRef: String?): FontFamily {+ val n = (name ?: pkg.theme.resolve(themeRef) ?: pkg.theme.minor ?: "Calibri").lowercase()+ return when {+ n.startsWith("calibri") || n.startsWith("carlito") || n.startsWith("aptos") || n.startsWith("candara") ||+ n.startsWith("corbel") -> carlito+ n.contains("times") || n.contains("georgia") || n.contains("cambria") || n.contains("garamond") ||+ n.contains("book antiqua") || n.contains("palatino") || n.contains("constantia") || n.contains("serif") &&+ !n.contains("sans") || n.contains("baskerville") || n.contains("century") || n.contains("bookman") -> FontFamily.Serif+ n.contains("courier") || n.contains("consolas") || n.contains("mono") || n.contains("lucida console") -> FontFamily.Monospace+ else -> FontFamily.SansSerif+ }+ }++ /** Text colour; on dark paper turned over like the PDF viewer's dark reader (hue kept). */+ fun inkOf(argb: Int?): Color {+ if (argb == null || argb == 0) return ink+ return if (dark) NightPaper.color(Color(argb)) else Color(argb)+ }++ /** Highlight / shading, turned over the same way on dark paper. */+ fun fillOf(argb: Int?): Color? {+ if (argb == null || argb == 0) return null+ if ((argb and 0xFFFFFF) == 0xFFFFFF) return if (dark) null else Color.White+ return if (dark) NightPaper.color(Color(argb)) else Color(argb)+ }++ fun para(p: DocPara, cell: RProps? = null): ParaLook {+ val key = p.pPr + (cell?.hashCode() ?: 0)+ paraCache[key]?.let { return it }+ val direct = Props.p(p.pPr)+ val (styleP, styleR) = styles.paragraphStyle(direct.styleId)+ var pp = direct.over(styleP)+ val numId = pp.numId?.takeIf { it != 0 }+ if (numId != null) {+ val lvl = pkg.numbering.level(numId, (pp.ilvl ?: 0).coerceIn(0, 8))+ if (lvl != null) pp = direct.over(Props.p(lvl.pPr).over(styleP))+ }+ val r = cell?.over(styleR) ?: styleR+ val sizePt = (r.size ?: 22) / 2f+ val fontSize = (sizePt * sp).sp+ val mult = if (pp.lineRule == null || pp.lineRule == "auto") (pp.line ?: 240) / 240f else 1f+ val lineHeight = when {+ pp.lineRule == "exact" && pp.line != null -> (pp.line!! / 20f * sp).sp+ pp.lineRule == "atLeast" && pp.line != null -> maxOf(pp.line!! / 20f * sp, sizePt * sp * 1.2f).sp+ mult in 0.98f..1.02f -> androidx.compose.ui.unit.TextUnit.Unspecified+ else -> (1.2f * mult).em+ }+ val left = (pp.left ?: 0).coerceAtLeast(0)+ val hangingTw = if (numId != null) (pp.hanging ?: 360) else 0+ val firstLine = if (numId == null) (pp.firstLine ?: 0) - (pp.hanging ?: 0) else 0+ val startTw = if (numId != null) (left - hangingTw).coerceAtLeast(0) else left + minOf(firstLine, 0)+ val align = when (pp.align) {+ "center" -> TextAlign.Center+ "right", "end" -> if (pp.bidi == true) TextAlign.Left else TextAlign.End+ "both", "distribute", "lowKashida", "mediumKashida", "highKashida" -> TextAlign.Justify+ else -> TextAlign.Start+ }+ val style = TextStyle(+ color = inkOf(r.color),+ fontSize = fontSize,+ fontWeight = if (r.bold == true) FontWeight.Bold else FontWeight.Normal,+ fontStyle = if (r.italic == true) FontStyle.Italic else FontStyle.Normal,+ fontFamily = family(r.font, r.fontTheme),+ textAlign = align,+ textDirection = if (pp.bidi == true) TextDirection.Rtl else TextDirection.Content,+ lineHeight = lineHeight,+ lineHeightStyle = if (lineHeight != androidx.compose.ui.unit.TextUnit.Unspecified)+ LineHeightStyle(LineHeightStyle.Alignment.Center, LineHeightStyle.Trim.None) else null,+ textIndent = if (firstLine > 0) TextIndent(firstLine = (firstLine / 20f * sp).sp) else null+ )+ val look = ParaLook(+ style = style,+ padStart = tw(startTw),+ padEnd = tw((pp.right ?: 0).coerceAtLeast(0)),+ before = tw(pp.before ?: 0),+ after = tw(pp.after ?: 0),+ hanging = if (numId != null) tw(hangingTw).coerceAtLeast((sizePt * scale * 1.1f).dp) else 0.dp,+ shading = fillOf(pp.shading),+ rtl = pp.bidi == true,+ borderBottom = pp.borderBottom == true,+ rBase = r,+ props = pp+ )+ if (paraCache.size > 3000) paraCache.clear()+ paraCache[key] = look+ return look+ }++ private fun tw(twips: Int): Dp = (twips / 20f * scale).dp++ /**+ * The paragraph's text with its runs' formatting. Objects show as zero-width spaces (pictures+ * are drawn above the text), so offsets stay one-to-one with the model and the text field.+ */+ fun annotate(+ p: DocPara,+ look: ParaLook,+ cell: RProps? = null,+ hits: List<IntRange> = emptyList(),+ current: IntRange? = null,+ withLinks: Boolean = false+ ): AnnotatedString {+ val text = p.text+ val display = CharArray(text.length)+ val b = AnnotatedString.Builder(text.length)+ var i = 0+ val styleCache = HashMap<CharFmt, Pair<SpanStyle, RProps>>()+ while (i < text.length) {+ val f = p.fmts.getOrElse(i) { CharFmt.Plain }+ var j = i + 1+ while (j < text.length && p.fmts.getOrNull(j) === f) j+++ val (span, eff) = styleCache.getOrPut(f) { spanFor(f, look, cell) }+ for (k in i until j) {+ val c = text[k]+ display[k] = when {+ c == OBJ_CHAR -> '\u200B'+ eff.caps == true || eff.smallCaps == true -> c.uppercaseChar()+ else -> c+ }+ }+ b.append(String(display, i, j - i))+ b.addStyle(span, i, j)+ if (withLinks && f.link != null) {+ val rid = XmlScan.attr(f.link, "id")+ val url = rid?.let { pkg.links[it] }+ if (url != null) b.addLink(LinkAnnotation.Url(url, TextLinkStyles(span)), i, j)+ }+ i = j+ }+ val hitBg = if (dark) Color(0x66FFD60A) else Color(0x80FFD60A)+ val curBg = Color(0xFFFF9F0A).copy(alpha = if (dark) 0.75f else 0.6f)+ for (h in hits) {+ val s = h.first.coerceIn(0, text.length)+ val e = (h.last + 1).coerceIn(0, text.length)+ if (s < e) b.addStyle(SpanStyle(background = if (h == current) curBg else hitBg), s, e)+ }+ return b.toAnnotatedString()+ }++ private fun spanFor(f: CharFmt, look: ParaLook, cell: RProps?): Pair<SpanStyle, RProps> {+ val direct = Props.r(f.rPr)+ val charStyle = direct.rStyle?.let { styles.characterStyle(it) }+ val base = charStyle?.over(look.rBase) ?: look.rBase+ val eff = direct.over(cell?.over(base) ?: base)+ var size = (eff.size ?: 22) / 2f * sp+ val vert = eff.vertAlign+ if (vert == "superscript" || vert == "subscript") size *= 0.65f+ if (eff.smallCaps == true && eff.caps != true) size *= 0.8f+ val isLink = f.link != null && (eff.color == null || eff.color == 0)+ val deco = buildList {+ if (eff.underline == true || isLink) add(TextDecoration.Underline)+ if (eff.strike == true) add(TextDecoration.LineThrough)+ }+ val span = SpanStyle(+ color = if (eff.vanish == true) Color.Transparent else if (isLink) link else inkOf(eff.color),+ fontSize = if (eff.vanish == true) 1.sp else size.sp,+ fontWeight = if (eff.bold == true) FontWeight.Bold else FontWeight.Normal,+ fontStyle = if (eff.italic == true) FontStyle.Italic else FontStyle.Normal,+ fontFamily = family(eff.font, eff.fontTheme),+ textDecoration = if (deco.isEmpty()) TextDecoration.None else TextDecoration.combine(deco),+ background = fillOf(eff.highlight) ?: Color.Unspecified,+ baselineShift = when (vert) {+ "superscript" -> BaselineShift.Superscript+ "subscript" -> BaselineShift.Subscript+ else -> null+ }+ )+ return span to eff+ }++ companion object {+ fun carlito(): FontFamily = FontFamily(+ Font(R.font.carlito_regular, FontWeight.Normal),+ Font(R.font.carlito_bold, FontWeight.Bold)+ )+ }+}++/** List labels ("1.", "a)", "•") for every numbered paragraph, counted in reading order. */+internal fun numberingLabels(pkg: DocxPackage, blocks: List<DocBlock>): Map<Long, String> {+ val out = HashMap<Long, String>()+ val num = pkg.numbering+ if (num.nums.isEmpty()) return out+ val counters = HashMap<Int, IntArray>()+ val started = HashSet<Int>()+ val unset = Int.MIN_VALUE+ forEachPara(blocks) { p ->+ val direct = Props.p(p.pPr)+ val pp = direct.over(pkg.styles.paragraphStyle(direct.styleId).first)+ val numId = pp.numId?.takeIf { it != 0 } ?: return@forEachPara+ val ilvl = (pp.ilvl ?: 0).coerceIn(0, 8)+ val abs = num.nums[numId] ?: return@forEachPara+ val lvl = num.level(numId, ilvl) ?: return@forEachPara+ val arr = counters.getOrPut(abs) { IntArray(9) { unset } }+ if (started.add(numId)) num.overrides[numId]?.forEach { (l, start) -> if (l in 0..8) arr[l] = start - 1 }+ arr[ilvl] = if (arr[ilvl] == unset) lvl.start else arr[ilvl] + 1+ for (k in ilvl + 1..8) arr[k] = unset+ out[p.id] = if (lvl.fmt == "bullet") DocxNumbering.bulletGlyph(lvl.text)+ else Regex("%([1-9])").replace(lvl.text) { m ->+ val k = m.groupValues[1].toInt() - 1+ val l = num.level(numId, k)+ val v = if (arr[k] == unset) (l?.start ?: 1) else arr[k]+ DocxNumbering.format(v, l?.fmt ?: "decimal")+ }+ }+ return out+}++/** Words and characters (no spaces), the way a word processor's status bar counts them. */+internal fun countWords(blocks: List<DocBlock>): Pair<Int, Int> {+ var words = 0+ var chars = 0+ forEachPara(blocks, includePreview = true) { p ->+ var inWord = false+ for (c in p.text) {+ if (c == OBJ_CHAR) continue+ if (!c.isWhitespace()) chars+++ val w = !c.isWhitespace()+ if (w && !inWord) words+++ inWord = w+ }+ }+ return words to chars+}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/DocxEditorViewModel.kt b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/DocxEditorViewModel.ktnew file mode 100644index 0000000..dcf32dc--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/DocxEditorViewModel.kt@@ -0,0 +1,333 @@+package com.chethan616.clearpdf.ui.viewmodel++import android.content.Context+import android.net.Uri+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.lifecycle.ViewModel+import androidx.lifecycle.viewModelScope+import com.chethan616.clearpdf.data.repository.LocalDocumentMirror+import com.chethan616.clearpdf.data.repository.RecentFile+import com.chethan616.clearpdf.data.repository.RecentFilesManager+import com.chethan616.clearpdf.docx.DocBlock+import com.chethan616.clearpdf.docx.DocPara+import com.chethan616.clearpdf.docx.DocState+import com.chethan616.clearpdf.docx.DocxEdits+import com.chethan616.clearpdf.docx.DocxPackage+import com.chethan616.clearpdf.docx.DocxReader+import com.chethan616.clearpdf.docx.DocxWriter+import com.chethan616.clearpdf.docx.findPara+import com.chethan616.clearpdf.docx.mapContainerOf+import com.chethan616.clearpdf.docx.replacePara+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import java.io.File+import java.io.FileOutputStream++/**+ * The Word editor's document: loads a .docx into blocks, keeps undo/redo as whole-document+ * snapshots (cheap: blocks are immutable and shared), and saves by patching the pristine local+ * mirror with [DocxWriter], so only what was edited is rewritten.+ *+ * The document lives in snapshot state rather than a flow: text fields read it in the same frame+ * they write it, which an asynchronously collected flow can't guarantee (the IME would see stale+ * text and the caret would jump).+ */+class DocxEditorViewModel : ViewModel() {++ data class Meta(+ val fileName: String = "",+ /** Local mirror of the file as opened (never modified). */+ val fileUri: Uri? = null,+ /** The uri the user opened — the "Save" target. */+ val sourceUri: Uri? = null,+ val isLoading: Boolean = true,+ val error: String? = null,+ val saving: Boolean = false+ )++ var meta by mutableStateOf(Meta())+ private set+ var pkg by mutableStateOf<DocxPackage?>(null)+ private set+ var doc by mutableStateOf<DocState?>(null)+ private set+ private var saved: DocState? = null+ /** The document as opened: the local mirror already holds exactly this. */+ private var original: DocState? = null+ private val undoStack = ArrayList<DocState>()+ private val redoStack = ArrayList<DocState>()+ var canUndo by mutableStateOf(false)+ private set+ var canRedo by mutableStateOf(false)+ private set+ /** Bumped when undo/redo replace the document, so an open text field re-reads its paragraph. */+ var restoreEpoch by mutableStateOf(0)+ private set++ val dirty: Boolean get() = doc != null && doc !== saved+ val editable: Boolean get() = pkg?.writable == true && meta.fileUri?.scheme == "file"++ private var started = false+ /** The page last read in this document (from Recents), to reopen at. */+ var resumePage = 0+ private set+ private var lastKey: String? = null+ private var lastAt = 0L++ fun load(context: Context, uri: Uri) {+ if (started) return+ started = true+ viewModelScope.launch {+ runCatching { context.contentResolver.takePersistableUriPermission(uri, android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION) }+ runCatching { context.contentResolver.takePersistableUriPermission(uri, android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION) }+ resumePage = withContext(Dispatchers.IO) {+ runCatching { RecentFilesManager.getRecents(context).firstOrNull { it.uriString == uri.toString() }?.currentPage }.getOrNull() ?: 0+ }+ val name = withContext(Dispatchers.IO) {+ runCatching { queryName(context, uri) }.getOrNull()+ ?: RecentFilesManager.getRecents(context).firstOrNull { it.uriString == uri.toString() }?.name+ ?: uri.lastPathSegment ?: "Document.docx"+ }+ val loaded = withContext(Dispatchers.IO) {+ val readable = runCatching { LocalDocumentMirror.resolve(context, uri, "docx") }.getOrDefault(uri)+ val local = runCatching { mirrorToCache(context, readable, name) }.getOrDefault(readable)+ val parsed = runCatching { context.contentResolver.openInputStream(local)?.use { DocxReader.read(it) } }.getOrNull()+ parsed to local+ }+ val (parsed, local) = loaded+ if (parsed == null) {+ meta = Meta(fileName = name, fileUri = local, sourceUri = uri, isLoading = false, error = "Couldn't read this document.")+ return@launch+ }+ pkg = parsed.first+ doc = parsed.second+ saved = parsed.second+ original = parsed.second+ meta = Meta(fileName = name, fileUri = local, sourceUri = uri, isLoading = false)+ withContext(Dispatchers.IO) {+ runCatching {+ RecentFilesManager.addRecent(context, RecentFile(name = name, uriString = uri.toString(), timestamp = System.currentTimeMillis()))+ }+ }+ }+ }++ // ── edit log ───────────────────────────────────────────────────────────────++ /**+ * Replaces the document. Typing into one paragraph coalesces into one undo step (per [key],+ * until a pause); everything else is its own step.+ */+ private fun commit(next: DocState, key: String? = null) {+ val cur = doc ?: return+ if (next === cur) return+ val now = System.currentTimeMillis()+ val coalesce = key != null && key == lastKey && now - lastAt < 1500+ if (!coalesce) {+ undoStack.add(cur)+ if (undoStack.size > 200) undoStack.removeAt(0)+ }+ lastKey = key+ lastAt = now+ redoStack.clear()+ doc = next+ canUndo = undoStack.isNotEmpty()+ canRedo = false+ }++ /** Ends typing coalescing, so the next keystroke starts a new undo step. */+ fun breakUndoGroup() { lastKey = null }++ fun undo() {+ val prev = undoStack.removeLastOrNull() ?: return+ doc?.let { redoStack.add(it) }+ doc = prev+ lastKey = null+ canUndo = undoStack.isNotEmpty(); canRedo = true+ restoreEpoch+++ }++ fun redo() {+ val next = redoStack.removeLastOrNull() ?: return+ doc?.let { undoStack.add(it) }+ doc = next+ lastKey = null+ canUndo = true; canRedo = redoStack.isNotEmpty()+ restoreEpoch+++ }++ fun para(id: Long): DocPara? = doc?.let { findPara(it.blocks, id) }++ /** Typing: the field's text changed. */+ fun typed(id: Long, newText: String, typing: com.chethan616.clearpdf.docx.CharFmt) {+ val d = doc ?: return+ val p = findPara(d.blocks, id) ?: return+ val np = DocxEdits.typed(p, newText, typing)+ if (np === p) return+ replacePara(d.blocks, np)?.let { commit(DocState(it), "type$id") }+ }++ fun replace(para: DocPara, grouped: Boolean = false) {+ val d = doc ?: return+ replacePara(d.blocks, para)?.let { commit(DocState(it), if (grouped) "fmt${para.id}" else null) }+ }++ /** Enter: splits paragraph [id] at [at] and returns the new paragraph's id. */+ fun split(id: Long, text: String, at: Int, typing: com.chethan616.clearpdf.docx.CharFmt): Long? {+ val d = doc ?: return null+ val p0 = findPara(d.blocks, id) ?: return null+ val p = DocxEdits.typed(p0, text, typing)+ val (a, b) = DocxEdits.split(p, at.coerceIn(0, p.text.length), pkg!!.styles)+ val blocks = mapContainerOf(d.blocks, id) { list ->+ val out = ArrayList<DocBlock>(list.size + 1)+ for (x in list) if (x is DocPara && x.id == id) { out.add(a); out.add(b) } else out.add(x)+ out+ } ?: return null+ lastKey = null+ commit(DocState(blocks))+ return b.id+ }++ /**+ * Backspace at the start of paragraph [id]: joins it to the paragraph before it. Returns that+ * paragraph's id and where the caret goes, or null when there is nothing to join with.+ */+ fun mergeWithPrevious(id: Long): Pair<Long, Int>? {+ val d = doc ?: return null+ var result: Pair<Long, Int>? = null+ val blocks = mapContainerOf(d.blocks, id) { list ->+ val i = list.indexOfFirst { it is DocPara && it.id == id }+ val prev = list.getOrNull(i - 1)+ val cur = list[i] as DocPara+ if (prev is DocPara && prev.editable) {+ val merged = DocxEdits.merge(prev, cur)+ result = prev.id to prev.text.length+ list.toMutableList().also { it[i - 1] = merged; it.removeAt(i) }+ } else if (prev != null && cur.isEmpty && i < list.size - 1) {+ // An empty paragraph after a table or picture: just remove it.+ result = -1L to 0+ list.toMutableList().also { it.removeAt(i) }+ } else list+ } ?: return null+ if (result != null) { lastKey = null; commit(DocState(blocks)) }+ return result+ }++ /** Paragraph-level change applied to every paragraph id in [ids]. */+ fun mapParas(ids: Collection<Long>, f: (DocPara) -> DocPara) {+ var blocks = doc?.blocks ?: return+ for (id in ids) {+ val p = findPara(blocks, id) ?: continue+ if (!p.editable) continue+ val np = f(p)+ if (np !== p) blocks = replacePara(blocks, np) ?: blocks+ }+ if (blocks !== doc?.blocks) { lastKey = null; commit(DocState(blocks)) }+ }++ // ── saving ─────────────────────────────────────────────────────────────────++ private fun buildPatched(context: Context): File? {+ val p = pkg ?: return null+ val d = doc ?: return null+ val src = meta.fileUri?.takeIf { it.scheme == "file" }?.path?.let(::File) ?: return null+ val dir = File(context.cacheDir, "docs").apply { mkdirs() }+ val safe = meta.fileName.replace(Regex("[^A-Za-z0-9._-]"), "_").ifBlank { "document.docx" }+ .let { if (it.lowercase().endsWith(".docx")) it else "$it.docx" }+ val out = File(dir, "edited_${System.currentTimeMillis()}_$safe")+ return runCatching { DocxWriter.write(p, d, src, out); out }.getOrElse { out.delete(); null }+ }++ sealed class SaveResult {+ data object Saved : SaveResult()+ data object NeedsSaveAs : SaveResult()+ data class Failed(val message: String) : SaveResult()+ }++ fun save(context: Context, target: Uri?, onDone: (SaveResult) -> Unit) {+ if (meta.saving || !editable) return+ val dest = target ?: meta.sourceUri ?: return onDone(SaveResult.NeedsSaveAs)+ val snapshot = doc+ meta = meta.copy(saving = true)+ viewModelScope.launch {+ val result = withContext(Dispatchers.IO) {+ val patched = buildPatched(context) ?: return@withContext SaveResult.Failed("Couldn't write the document.")+ try {+ if (writeWithBackup(context, dest, patched)) SaveResult.Saved+ else if (target == null) SaveResult.NeedsSaveAs else SaveResult.Failed("Couldn't save to that location.")+ } finally {+ patched.delete()+ }+ }+ meta = meta.copy(saving = false)+ if (result is SaveResult.Saved) saved = snapshot+ onDone(result)+ }+ }++ /** Copy [file] over [uri], restoring the previous content if the write fails midway. */+ private fun writeWithBackup(context: Context, uri: Uri, file: File): Boolean {+ val cr = context.contentResolver+ val backup = File(context.cacheDir, "docs/backup_${System.currentTimeMillis()}")+ val hadBackup = runCatching { cr.openInputStream(uri)?.use { i -> backup.outputStream().use { i.copyTo(it) } } != null }.getOrDefault(false)+ return try {+ val out = runCatching { cr.openOutputStream(uri, "wt") }.getOrNull()+ ?: runCatching { cr.openOutputStream(uri, "w") }.getOrNull()+ ?: return false+ out.use { o -> file.inputStream().use { it.copyTo(o) } }+ backup.delete()+ true+ } catch (e: Throwable) {+ if (hadBackup) runCatching { cr.openOutputStream(uri, "wt")?.use { o -> backup.inputStream().use { it.copyTo(o) } } }+ .onSuccess { backup.delete() }+ false+ }+ }++ fun suggestedSaveAsName(): String {+ val n = meta.fileName.ifBlank { "Document.docx" }+ return n.substringBeforeLast('.') + " (edited).docx"+ }++ /** The edited document (or the original when unedited) as a file uri. */+ fun currentFile(context: Context, onDone: (Uri?) -> Unit) {+ val uri = meta.fileUri ?: return onDone(null)+ if (doc === original) return onDone(uri)+ viewModelScope.launch {+ val out = withContext(Dispatchers.IO) { buildPatched(context)?.let { Uri.fromFile(it) } }+ onDone(out ?: uri)+ }+ }++ fun exportToPdf(context: Context, onDone: (Uri?) -> Unit) {+ currentFile(context) { src ->+ if (src == null) return@currentFile onDone(null)+ viewModelScope.launch {+ val out = withContext(Dispatchers.IO) {+ runCatching { com.chethan616.clearpdf.utils.UniversalDocumentConverter.convertToPdf(context, src) }.getOrNull()+ }+ onDone(out)+ }+ }+ }++ private fun mirrorToCache(context: Context, uri: Uri, name: String): Uri {+ val dir = File(context.cacheDir, "docs").apply { mkdirs() }+ val safe = name.replace(Regex("[^A-Za-z0-9._-]"), "_").ifBlank { "document.docx" }+ val file = File(dir, "${System.currentTimeMillis()}_$safe")+ context.contentResolver.openInputStream(uri)?.use { input ->+ FileOutputStream(file).use { input.copyTo(it) }+ } ?: return uri+ if (file.length() == 0L) { file.delete(); return uri }+ return Uri.fromFile(file)+ }++ private fun queryName(context: Context, uri: Uri): String? =+ context.contentResolver.query(uri, null, null, null, null)?.use { c ->+ val i = c.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)+ if (i != -1 && c.moveToFirst()) c.getString(i) else null+ }+}diff --git a/app/src/main/java/com/chethan616/clearpdf/utils/PdfPrint.kt b/app/src/main/java/com/chethan616/clearpdf/utils/PdfPrint.ktnew file mode 100644index 0000000..a2dae87--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/utils/PdfPrint.kt@@ -0,0 +1,62 @@+package com.chethan616.clearpdf.utils++import android.content.Context+import android.net.Uri+import android.os.Bundle+import android.os.CancellationSignal+import android.os.ParcelFileDescriptor+import android.print.PageRange+import android.print.PrintAttributes+import android.print.PrintDocumentAdapter+import android.print.PrintDocumentInfo+import android.print.PrintManager+import java.io.FileOutputStream++/**+ * Prints a PDF exactly as it is through Android's own print screen (after Gander's Print). Word and+ * other Office files are converted first — by the Office engine (LibreOffice) when it is installed,+ * so the printout matches the document's real pages.+ */+object PdfPrint {++ fun print(context: Context, pdf: Uri, jobName: String): Boolean {+ val manager = context.getSystemService(Context.PRINT_SERVICE) as? PrintManager ?: return false+ val name = jobName.ifBlank { "Document" }+ return runCatching {+ manager.print(name, Adapter(context.applicationContext, pdf, name), PrintAttributes.Builder().build())+ }.isSuccess+ }++ private class Adapter(private val context: Context, private val pdf: Uri, private val name: String) : PrintDocumentAdapter() {+ override fun onLayout(+ oldAttributes: PrintAttributes?,+ newAttributes: PrintAttributes?,+ cancellationSignal: CancellationSignal?,+ callback: LayoutResultCallback,+ extras: Bundle?+ ) {+ if (cancellationSignal?.isCanceled == true) { callback.onLayoutCancelled(); return }+ val info = PrintDocumentInfo.Builder(if (name.endsWith(".pdf", true)) name else "$name.pdf")+ .setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)+ .build()+ callback.onLayoutFinished(info, oldAttributes != newAttributes)+ }++ override fun onWrite(+ pages: Array<out PageRange>?,+ destination: ParcelFileDescriptor,+ cancellationSignal: CancellationSignal?,+ callback: WriteResultCallback+ ) {+ try {+ context.contentResolver.openInputStream(pdf)?.use { input ->+ FileOutputStream(destination.fileDescriptor).use { out -> input.copyTo(out) }+ } ?: run { callback.onWriteFailed(null); return }+ if (cancellationSignal?.isCanceled == true) callback.onWriteCancelled()+ else callback.onWriteFinished(arrayOf(PageRange.ALL_PAGES))+ } catch (e: Exception) {+ callback.onWriteFailed(e.message)+ }+ }+ }+}diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex 3752018..971c2aa 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -362,6 +362,7 @@<string name="language_spanish">Spanish</string><string name="language_italian">Italian</string><string name="language_russian">Russian</string>+ <string name="language_arabic">Arabic</string><string name="recents_open">Open</string><string name="recents_share">Share</string><string name="recents_details">Details</string>@@ -748,6 +749,41 @@<string name="sheet_vertical">Vertical</string><string name="sheet_automatic">Automatic</string><string name="sheet_no_fill">No fill</string>++ <!-- Word editor -->+ <string name="docx_style_normal">Normal</string>+ <string name="docx_style_title">Title</string>+ <string name="docx_style_subtitle">Subtitle</string>+ <string name="docx_style_h1">Heading 1</string>+ <string name="docx_style_h2">Heading 2</string>+ <string name="docx_style_h3">Heading 3</string>+ <string name="docx_style_quote">Quote</string>+ <string name="docx_size_down">Smaller text</string>+ <string name="docx_size_up">Larger text</string>+ <string name="docx_highlight">Highlight</string>+ <string name="docx_no_highlight">No highlight</string>+ <string name="docx_align">Align</string>+ <string name="docx_bullets">Bullets</string>+ <string name="docx_numbering">Numbers</string>+ <string name="docx_indent_less">Outdent</string>+ <string name="docx_indent_more">Indent</string>+ <string name="docx_superscript">Super</string>+ <string name="docx_clear">Clear</string>+ <string name="docx_status">%1$s words · %2$s characters</string>+ <string name="docx_open_as_pdf">Open as PDF</string>+ <string name="docx_readonly_part">This part has tracked changes or fields, so it can\'t be edited here. Open as PDF to see its final layout.</string>+ <string name="docx_read_failed">Couldn\'t read this document.</string>+ <string name="docx_saved">Saved</string>+ <string name="docx_save_failed">Couldn\'t save the document</string>+ <string name="docx_unsaved_body">Your changes to this document haven\'t been saved yet.</string>+ <string name="docx_page_of">Page %1$d of %2$d</string>+ <string name="docx_go_to_page">Go to page</string>+ <string name="docx_page_hint">1 to %1$d</string>+ <string name="docx_go">Go</string>+ <string name="docx_fit_width">Fit page width</string>+ <string name="docx_print">Print</string>+ <string name="docx_preparing_print">Preparing to print…</string>+ <string name="docx_print_failed">Couldn\'t print this document</string><string name="sheet_insert_row_above">Insert row above</string><string name="sheet_insert_row_below">Insert row below</string><string name="sheet_delete_rows">Delete rows</string>@@ -814,6 +850,16 @@<string name="whats_new_fixes_title">Fixes</string><string name="whats_new_fixes_desc">PowerPoint titles no longer get cut off, images open reliably, and resized text stays where you put it.</string><string name="whats_new_continue">Continue</string>+ <string name="whats_new_word_title">Word documents, edited in place</string>+ <string name="whats_new_word_desc">A .docx opens in pages, like on a desktop. Tap the pencil to type, style, add lists and save back to the same file.</string>+ <string name="whats_new_night_title">Dark reading that keeps photos</string>+ <string name="whats_new_night_desc">Dark pages keep blue headings blue and leave photographs as they were printed, in PDFs, slides and Word files.</string>+ <string name="whats_new_xlsx_title">Spreadsheets as Excel shows them</string>+ <string name="whats_new_xlsx_desc">Pictures and logos appear, text fits its cells, and sheets are white paper with a dark switch.</string>+ <string name="whats_new_lang_title">Arabic, and more of every language</string>+ <string name="whats_new_lang_desc">ClearPDF now speaks Arabic, and Arabic text copies and searches in the right order.</string>+ <string name="whats_new_print_title">Print and pick up where you left off</string>+ <string name="whats_new_print_desc">Print Word documents in their real layout, and reopen them at the page you were reading.</string><string name="tour_edit_text_title">Edit the PDF\'s own text</string><string name="tour_edit_text_message">Tap the edit icon and pick Text, then tap any line to rewrite it in its own font. Or long-press a word and tap Edit text.</string><string name="tour_recents_menu_title">Quick actions</string>diff --git a/app/src/test/java/com/chethan616/clearpdf/docx/DocxRoundTripTest.kt b/app/src/test/java/com/chethan616/clearpdf/docx/DocxRoundTripTest.ktnew file mode 100644index 0000000..587e171--- /dev/null+++ b/app/src/test/java/com/chethan616/clearpdf/docx/DocxRoundTripTest.kt@@ -0,0 +1,224 @@+package com.chethan616.clearpdf.docx++import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertTrue+import org.junit.Test+import java.io.ByteArrayOutputStream+import java.io.File+import java.util.zip.ZipEntry+import java.util.zip.ZipInputStream+import java.util.zip.ZipOutputStream++class DocxRoundTripTest {++ private val ns = "xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" " ++ "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\""++ private fun docx(body: String, extra: Map<String, String> = emptyMap()): ByteArray {+ val parts = linkedMapOf(+ "[Content_Types].xml" to "<?xml version=\"1.0\"?><Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">" ++ "<Default Extension=\"xml\" ContentType=\"application/xml\"/>" ++ "<Override PartName=\"/word/document.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml\"/></Types>",+ "_rels/.rels" to "<?xml version=\"1.0\"?><Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">" ++ "<Relationship Id=\"rId1\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument\" Target=\"word/document.xml\"/></Relationships>",+ "word/_rels/document.xml.rels" to "<?xml version=\"1.0\"?><Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">" ++ "<Relationship Id=\"rId9\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink\" Target=\"https://example.com\" TargetMode=\"External\"/></Relationships>",+ "word/document.xml" to "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><w:document $ns><w:body>$body" ++ "<w:sectPr><w:pgSz w:w=\"12240\" w:h=\"15840\"/></w:sectPr></w:body></w:document>"+ )+ parts.putAll(extra)+ val bos = ByteArrayOutputStream()+ ZipOutputStream(bos).use { z ->+ for ((n, c) in parts) { z.putNextEntry(ZipEntry(n)); z.write(c.toByteArray()); z.closeEntry() }+ }+ return bos.toByteArray()+ }++ private fun read(bytes: ByteArray) = DocxReader.read(bytes.inputStream())!!++ private fun paras(state: DocState): List<DocPara> {+ val out = ArrayList<DocPara>()+ forEachPara(state.blocks, includePreview = false) { out.add(it) }+ return out+ }++ private fun save(bytes: ByteArray, pkg: DocxPackage, state: DocState): ByteArray {+ val src = File.createTempFile("src", ".docx").apply { writeBytes(bytes); deleteOnExit() }+ val out = File.createTempFile("out", ".docx").apply { deleteOnExit() }+ DocxWriter.write(pkg, state, src, out)+ return out.readBytes()+ }++ private fun entry(bytes: ByteArray, name: String): String? {+ ZipInputStream(bytes.inputStream()).use { z ->+ while (true) {+ val e = z.nextEntry ?: return null+ if (e.name == name) return z.readBytes().toString(Charsets.UTF_8)+ }+ }+ }++ private val body = "<w:p w14:paraId=\"1\" xmlns:w14=\"x\"><w:pPr><w:pStyle w:val=\"Heading1\"/></w:pPr>" ++ "<w:r><w:rPr><w:sz w:val=\"28\"/></w:rPr><w:t>Hello </w:t></w:r><w:proofErr w:type=\"spellStart\"/>" ++ "<w:r><w:rPr><w:i/></w:rPr><w:t>world</w:t></w:r><w:bookmarkStart w:id=\"0\" w:name=\"b\"/><w:bookmarkEnd w:id=\"0\"/></w:p>" ++ "<w:p><w:r><w:t xml:space=\"preserve\">Second & line</w:t></w:r><w:r><w:tab/><w:t>tabbed</w:t></w:r></w:p>" ++ "<w:p><w:hyperlink r:id=\"rId9\"><w:r><w:t>link</w:t></w:r></w:hyperlink><w:r><w:t> after</w:t></w:r></w:p>" ++ "<w:p><w:ins w:id=\"5\" w:author=\"a\"><w:r><w:t>tracked</w:t></w:r></w:ins></w:p>" ++ "<w:tbl><w:tblPr><w:tblStyle w:val=\"TableGrid\"/></w:tblPr><w:tblGrid><w:gridCol w:w=\"4000\"/><w:gridCol w:w=\"4000\"/></w:tblGrid>" ++ "<w:tr><w:tc><w:tcPr><w:tcW w:w=\"4000\" w:type=\"dxa\"/></w:tcPr><w:p><w:r><w:t>A1</w:t></w:r></w:p></w:tc>" ++ "<w:tc><w:p><w:r><w:t>B1</w:t></w:r></w:p></w:tc></w:tr></w:tbl>"++ @Test+ fun readsTextRunsAndStructure() {+ val (pkg, state) = read(docx(body))+ val ps = paras(state)+ assertEquals("Hello world", ps[0].text)+ assertEquals("Second & line\ttabbed", ps[1].text)+ assertEquals("link after", ps[2].text)+ assertEquals("tracked", ps[3].text)+ assertFalse("tracked changes are not editable", ps[3].editable)+ assertTrue(ps[0].editable)+ assertEquals("A1", ps[4].text)+ assertEquals("B1", ps[5].text)+ assertEquals("https://example.com", pkg.links["rId9"])+ assertEquals(12240, pkg.page.width)+ assertTrue(ps[0].extras.contains("bookmarkStart"))+ }++ @Test+ fun untouchedDocumentIsWrittenVerbatim() {+ val bytes = docx(body)+ val (pkg, state) = read(bytes)+ assertEquals(pkg.xml, DocxWriter.documentXml(pkg, state))+ }++ @Test+ fun typingKeepsFormattingAndOtherParagraphs() {+ val bytes = docx(body)+ val (pkg, state) = read(bytes)+ val p = paras(state)[0]+ val typed = DocxEdits.typed(p, "Hello big world", DocxEdits.fmtAt(p, 6))+ val next = DocState(replacePara(state.blocks, typed)!!)+ val out = save(bytes, pkg, next)+ val xml = entry(out, "word/document.xml")!!+ // The untouched paragraphs, table included, are byte-identical.+ assertTrue(xml.contains("<w:p><w:r><w:t xml:space=\"preserve\">Second & line</w:t></w:r><w:r><w:tab/><w:t>tabbed</w:t></w:r></w:p>"))+ assertTrue(xml.contains("<w:tc><w:p><w:r><w:t>B1</w:t></w:r></w:p></w:tc>"))+ val (_, again) = read(out)+ val q = paras(again)[0]+ assertEquals("Hello big world", q.text)+ // "big " was typed after "Hello " (size 14pt): it carries that run's formatting.+ assertEquals(q.fmts[0].rPr, q.fmts[6].rPr)+ assertTrue(q.fmts[10].rPr.contains("<w:i/>"))+ assertTrue(q.pPr.contains("Heading1"))+ assertTrue(q.extras.contains("bookmarkStart"))+ assertEquals("link after", paras(again)[2].text)+ }++ @Test+ fun boldGoesInSchemaOrder() {+ val (pkg, state) = read(docx(body))+ val p = paras(state)[0]+ val bold = DocxEdits.format(p, 0, 5) { DocxEdits.toggle(p, it, pkg.styles, DocxEdits.Toggle.BOLD, true) }+ val rPr = bold.fmts[0].rPr+ assertTrue(rPr, rPr.indexOf("<w:b/>") in 0 until rPr.indexOf("<w:sz "))+ assertEquals(rPr, bold.fmts[4].rPr)+ // The space after "Hello" was not in the range.+ assertFalse(bold.fmts[5].rPr.contains("<w:b/>"))+ }++ @Test+ fun splitAndMergeRoundTrip() {+ val bytes = docx(body)+ val (pkg, state) = read(bytes)+ val p = paras(state)[1]+ val (a, b) = DocxEdits.split(p, 6, pkg.styles)+ assertEquals("Second", a.text)+ assertEquals(" & line\ttabbed", b.text)+ val blocks = mapContainerOf(state.blocks, p.id) { list ->+ list.flatMap { if (it is DocPara && it.id == p.id) listOf(a, b) else listOf(it) }+ }!!+ val out = save(bytes, pkg, DocState(blocks))+ val ps = paras(read(out).second)+ assertEquals("Second", ps[1].text)+ assertEquals(" & line\ttabbed", ps[2].text)+ assertEquals("Second & line\ttabbed", DocxEdits.merge(a, b).text)+ }++ @Test+ fun hyperlinkSurvivesEditing() {+ val bytes = docx(body)+ val (pkg, state) = read(bytes)+ val p = paras(state)[2]+ val typed = DocxEdits.typed(p, "link after it", DocxEdits.fmtAt(p, 10))+ val out = save(bytes, pkg, DocState(replacePara(state.blocks, typed)!!))+ val xml = entry(out, "word/document.xml")!!+ assertTrue(xml, xml.contains("<w:hyperlink r:id=\"rId9\"><w:r><w:t xml:space=\"preserve\">link</w:t></w:r></w:hyperlink>"))+ assertEquals("link after it", paras(read(out).second)[2].text)+ }++ @Test+ fun editingATableCellRebuildsOnlyThatTable() {+ val bytes = docx(body)+ val (pkg, state) = read(bytes)+ val cell = paras(state)[5]+ val typed = DocxEdits.typed(cell, "B1!", DocxEdits.fmtAt(cell, 2))+ val out = save(bytes, pkg, DocState(replacePara(state.blocks, typed)!!))+ val xml = entry(out, "word/document.xml")!!+ assertTrue(xml.contains("<w:tblStyle w:val=\"TableGrid\"/>"))+ assertTrue(xml.contains("<w:tcW w:w=\"4000\" w:type=\"dxa\"/>"))+ assertEquals(listOf("A1", "B1!"), paras(read(out).second).drop(4).map { it.text })+ }++ @Test+ fun newListCreatesNumberingPart() {+ val bytes = docx(body)+ val (pkg, state) = read(bytes)+ val p = paras(state)[1]+ val numId = pkg.numbering.ensureList(bullet = true)+ val listed = DocxEdits.withList(p, numId, pkg.styles)+ val out = save(bytes, pkg, DocState(replacePara(state.blocks, listed)!!))+ val numbering = entry(out, "word/numbering.xml")+ assertNotNull(numbering)+ assertTrue(entry(out, "word/_rels/document.xml.rels")!!.contains("relationships/numbering"))+ assertTrue(entry(out, "[Content_Types].xml")!!.contains("/word/numbering.xml"))+ val (pkg2, state2) = read(out)+ assertTrue(pkg2.numbering.isBullet(numId))+ assertEquals(numId, Props.p(paras(state2)[1].pPr).numId)+ }++ @Test+ fun numberingInsertKeepsSchemaOrder() {+ val xml = "<w:numbering $ns><w:abstractNum w:abstractNumId=\"0\"/><w:num w:numId=\"1\"><w:abstractNumId w:val=\"0\"/></w:num></w:numbering>"+ val out = DocxWriter.insertNumbering(xml, "<w:abstractNum w:abstractNumId=\"9\"/>", "<w:num w:numId=\"2\"/>")+ assertTrue(out.indexOf("abstractNumId=\"9\"") < out.indexOf("<w:num w:numId=\"1\""))+ assertTrue(out.indexOf("<w:num w:numId=\"2\"/>") > out.indexOf("<w:num w:numId=\"1\""))+ }++ @Test+ fun keepsWordPageMarksThroughEdits() {+ val body = "<w:p><w:r><w:t xml:space=\"preserve\">end of page one </w:t></w:r><w:r><w:lastRenderedPageBreak/><w:t>start of two</w:t></w:r></w:p>"+ val (_, state) = read(docx(body))+ val p = paras(state)[0]+ assertEquals(listOf(16), p.marks)+ // Typing before the mark moves it; typing after leaves it.+ val typed = DocxEdits.typed(p, "the end of page one start of two", CharFmt.Plain)+ assertEquals(listOf(20), typed.marks)+ val (a, b) = DocxEdits.split(typed, 4, read(docx(body)).first.styles)+ assertEquals(emptyList<Int>(), a.marks)+ assertEquals(listOf(16), b.marks)+ assertEquals(listOf(20), DocxEdits.merge(a, b).marks)+ }++ @Test+ fun escapesAndDropsInvalidCharacters() {+ val bytes = docx(body)+ val (pkg, state) = read(bytes)+ val p = paras(state)[1]+ val typed = DocxEdits.typed(p, "a<b>&\u0001c", CharFmt.Plain)+ val out = save(bytes, pkg, DocState(replacePara(state.blocks, typed)!!))+ assertEquals("a<b>&c", paras(read(out).second)[1].text)+ }+}