Skip to content

Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.

WIP: text selection model, viewport transform, two-column text split; drop VM selection state

Chethan616d3a74ecfe1f9
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfTextLayout.kt b/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfTextLayout.kt
new file mode 100644
index 0000000..2859981
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfTextLayout.kt
@@ -0,0 +1,319 @@
+package com.chethan616.clearpdf.ui.selection
+
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.geometry.Size
+import com.chethan616.clearpdf.ui.viewmodel.OcrTextBlock
+import com.chethan616.clearpdf.ui.viewmodel.OcrTextRange
+import java.text.BreakIterator
+import kotlin.math.abs
+import kotlin.math.max
+import kotlin.math.min
+
+/**
+ * One page's extracted text, flattened into a single string in reading order so a selection is just
+ * a pair of caret offsets.
+ *
+ * Blocks (PdfBox line segments, or OCR lines for scanned pages) are ordered with a small XY-cut so a
+ * two-column page reads left column then right column instead of interleaving lines. Consecutive
+ * blocks are joined by one `'\n'` in [text]; a caret offset `o` is "between characters" (0..length).
+ *
+ * All geometry in and out is in the page's local, unscaled pixel space for a page of [Size] `size`;
+ * the blocks themselves carry coordinates normalised to 0..1.
+ */
+class PdfTextLayout(blocks: List<OcrTextBlock>) {
+
+ val blocks: List<OcrTextBlock> = readingOrder(blocks.filter { it.text.isNotEmpty() })
+
+ /** Flat offset at which each block's first character sits. */
+ private val starts: IntArray
+ val text: String
+
+ init {
+ val sb = StringBuilder()
+ starts = IntArray(this.blocks.size)
+ this.blocks.forEachIndexed { i, b ->
+ if (i > 0) sb.append('\n')
+ starts[i] = sb.length
+ sb.append(b.text)
+ }
+ text = sb.toString()
+ }
+
+ val length: Int get() = text.length
+ val isEmpty: Boolean get() = blocks.isEmpty()
+
+ private val words: BreakIterator by lazy {
+ BreakIterator.getWordInstance().also { it.setText(text) }
+ }
+
+ // ── Offset ↔ block ────────────────────────────────────────────────────────────────────────
+
+ /** Index of the block containing flat offset [o] (a separator belongs to the block before it). */
+ fun blockIndexOf(o: Int): Int {
+ if (blocks.isEmpty()) return -1
+ var lo = 0; var hi = starts.size - 1
+ while (lo < hi) {
+ val mid = (lo + hi + 1) / 2
+ if (starts[mid] <= o) lo = mid else hi = mid - 1
+ }
+ return lo
+ }
+
+ fun blockStart(i: Int): Int = starts[i]
+ fun blockEnd(i: Int): Int = starts[i] + blocks[i].text.length
+
+ /** The per-block ranges covering flat [start, end). Separators contribute nothing. */
+ fun rangesFor(start: Int, end: Int): List<OcrTextRange> {
+ if (blocks.isEmpty() || end <= start) return emptyList()
+ val out = ArrayList<OcrTextRange>()
+ val first = blockIndexOf(start)
+ val last = blockIndexOf((end - 1).coerceAtLeast(0))
+ for (i in first..last) {
+ val s = (start - starts[i]).coerceIn(0, blocks[i].text.length)
+ val e = (end - starts[i]).coerceIn(0, blocks[i].text.length)
+ if (e > s) out.add(OcrTextRange(blocks[i].id, s, e))
+ }
+ return out
+ }
+
+ fun substring(start: Int, end: Int): String =
+ text.substring(start.coerceIn(0, length), end.coerceIn(start.coerceIn(0, length), length))
+
+ // ── Geometry ──────────────────────────────────────────────────────────────────────────────
+
+ fun blockRect(i: Int, size: Size): Rect {
+ val b = blocks[i]
+ return Rect(b.left * size.width, b.top * size.height, b.right * size.width, b.bottom * size.height)
+ }
+
+ private fun charLeft(b: OcrTextBlock, c: Int, size: Size): Float =
+ (if (c < b.charLefts.size) b.charLefts[c]
+ else b.left + (b.right - b.left) * c / b.text.length.coerceAtLeast(1)) * size.width
+
+ private fun charRight(b: OcrTextBlock, c: Int, size: Size): Float =
+ (if (c < b.charRights.size) b.charRights[c]
+ else b.left + (b.right - b.left) * (c + 1) / b.text.length.coerceAtLeast(1)) * size.width
+
+ /**
+ * Highlight rectangles (one per block fragment) for flat [start, end), expanded vertically so
+ * ascenders and descenders sit inside the band like a platform text selection.
+ */
+ fun selectionRects(start: Int, end: Int, size: Size): List<Rect> {
+ if (blocks.isEmpty() || end <= start) return emptyList()
+ val out = ArrayList<Rect>()
+ val first = blockIndexOf(start)
+ val last = blockIndexOf((end - 1).coerceAtLeast(0))
+ for (i in first..last) {
+ val b = blocks[i]
+ val s = (start - starts[i]).coerceIn(0, b.text.length)
+ val e = (end - starts[i]).coerceIn(0, b.text.length)
+ if (e <= s) continue
+ val r = blockRect(i, size)
+ out.add(expandLine(Rect(charLeft(b, s, size), r.top, charRight(b, e - 1, size), r.bottom)))
+ }
+ return out
+ }
+
+ /**
+ * Where a selection handle attaches for caret [o]. The START handle sits at the left edge of the
+ * character at [o]; the END handle at the right edge of the character before [o] — so a caret
+ * sitting on a line break attaches to the line the user sees it on.
+ */
+ fun caretGeometry(o: Int, isStart: Boolean, size: Size): CaretGeometry? {
+ if (blocks.isEmpty()) return null
+ val oc = o.coerceIn(0, length)
+ val bi: Int
+ val x: Float
+ if (isStart) {
+ var i = blockIndexOf(oc)
+ var c = oc - starts[i]
+ if (c >= blocks[i].text.length && i + 1 < blocks.size) { i++; c = 0 }
+ c = c.coerceIn(0, blocks[i].text.length - 1)
+ bi = i; x = charLeft(blocks[i], c, size)
+ } else {
+ val i = blockIndexOf((oc - 1).coerceAtLeast(0))
+ val c = (oc - starts[i] - 1).coerceIn(0, blocks[i].text.length - 1)
+ bi = i; x = charRight(blocks[i], c, size)
+ }
+ val line = expandLine(blockRect(bi, size))
+ return CaretGeometry(x, line.top, line.bottom, bi)
+ }
+
+ // ── Hit testing ───────────────────────────────────────────────────────────────────────────
+
+ /**
+ * The block a point belongs to: among blocks whose (expanded) line band contains the point's y,
+ * the horizontally nearest; otherwise the vertically nearest block. Null for an empty page.
+ */
+ private fun blockAt(p: Offset, size: Size): Int {
+ if (blocks.isEmpty()) return -1
+ var best = -1
+ var bestScore = Float.MAX_VALUE
+ for (i in blocks.indices) {
+ val r = expandLine(blockRect(i, size))
+ val dy = when {
+ p.y < r.top -> r.top - p.y
+ p.y > r.bottom -> p.y - r.bottom
+ else -> 0f
+ }
+ val dx = when {
+ p.x < r.left -> r.left - p.x
+ p.x > r.right -> p.x - r.right
+ else -> 0f
+ }
+ // Vertical distance dominates: lines are picked by y first (like TextView), then the
+ // nearest column/segment on that line by x.
+ val score = dy * 1000f + dx
+ if (score < bestScore) { bestScore = score; best = i }
+ }
+ return best
+ }
+
+ /** Caret offset nearest [p]: before a character if [p] is left of its centre, after otherwise. */
+ fun caretAt(p: Offset, size: Size): Int {
+ val i = blockAt(p, size)
+ if (i < 0) return 0
+ val b = blocks[i]
+ var c = 0
+ while (c < b.text.length) {
+ val mid = (charLeft(b, c, size) + charRight(b, c, size)) / 2f
+ if (p.x < mid) break
+ c++
+ }
+ return starts[i] + c
+ }
+
+ /**
+ * The character offset under [p], or null when the press is not on (or right next to) any text —
+ * a long-press on a margin must not select some far-away word.
+ */
+ fun charAt(p: Offset, size: Size, slopPx: Float): Int? {
+ val i = blockAt(p, size)
+ if (i < 0) return null
+ val b = blocks[i]
+ val r = expandLine(blockRect(i, size))
+ val tol = max(slopPx, r.height * 0.5f)
+ if (!r.inflate(tol).contains(p)) return null
+ var best = 0
+ var bestD = Float.MAX_VALUE
+ for (c in b.text.indices) {
+ val l = charLeft(b, c, size); val rr = charRight(b, c, size)
+ val d = if (p.x < l) l - p.x else if (p.x > rr) p.x - rr else 0f
+ if (d < bestD) { bestD = d; best = c }
+ if (d == 0f) break
+ }
+ return starts[i] + best
+ }
+
+ /**
+ * The word around character offset [o]: [start, end). A press on whitespace or punctuation
+ * selects the nearest word on the same block, falling back to that single character.
+ */
+ fun wordAt(o: Int): IntRange {
+ if (length == 0) return 0 until 0
+ val oc = o.coerceIn(0, length - 1)
+ fun wordAround(x: Int): IntRange? {
+ if (x !in 0 until length || !text[x].isLetterOrDigit()) return null
+ val it = words
+ val s = if (it.isBoundary(x)) x else it.preceding(x)
+ val e = it.following(x)
+ return if (s == BreakIterator.DONE || e == BreakIterator.DONE) null else s until e
+ }
+ wordAround(oc)?.let { return it }
+ val bi = blockIndexOf(oc)
+ val bs = starts[bi]; val be = blockEnd(bi)
+ for (d in 1..40) {
+ if (oc - d >= bs) wordAround(oc - d)?.let { return it }
+ if (oc + d < be) wordAround(oc + d)?.let { return it }
+ }
+ return oc until oc + 1
+ }
+
+ data class CaretGeometry(val x: Float, val lineTop: Float, val lineBottom: Float, val blockIndex: Int) {
+ val lineHeight: Float get() = lineBottom - lineTop
+ }
+
+ companion object {
+ /**
+ * PdfBox reports each glyph box from roughly cap height down to the BASELINE, so a raw block
+ * rect clips descenders and accents. Pad it to a full typographic line, the band TextView
+ * paints.
+ */
+ fun expandLine(r: Rect): Rect {
+ val h = r.height.coerceAtLeast(1f)
+ return Rect(r.left, r.top - h * 0.26f, r.right, r.bottom + h * 0.24f)
+ }
+
+ /**
+ * Recursive XY-cut: prefer a clean vertical gutter (columns read top-to-bottom, left then
+ * right), then the single widest horizontal gap (e.g. a full-width title above columns),
+ * else plain top-to-bottom, left-to-right line order.
+ */
+ internal fun readingOrder(blocks: List<OcrTextBlock>): List<OcrTextBlock> {
+ if (blocks.size <= 1) return blocks
+ verticalCut(blocks)?.let { (l, r) -> return readingOrder(l) + readingOrder(r) }
+ horizontalCut(blocks)?.let { (t, b) -> return readingOrder(t) + readingOrder(b) }
+ return lineOrder(blocks)
+ }
+
+ private fun verticalCut(blocks: List<OcrTextBlock>): Pair<List<OcrTextBlock>, List<OcrTextBlock>>? {
+ val sorted = blocks.sortedBy { it.left }
+ var maxRight = sorted.first().right
+ var bestAt = -1
+ var bestGap = 0.015f
+ for (i in 1 until sorted.size) {
+ val gap = sorted[i].left - maxRight
+ if (gap > bestGap) { bestGap = gap; bestAt = i }
+ maxRight = max(maxRight, sorted[i].right)
+ }
+ if (bestAt < 0) return null
+ val left = sorted.subList(0, bestAt)
+ val right = sorted.subList(bestAt, sorted.size)
+ // Only a real column split: several reasonably wide lines on each side. Narrow table
+ // cells stay in row order, where "label value" reads correctly.
+ fun columnLike(side: List<OcrTextBlock>): Boolean {
+ if (side.size < 2) return false
+ val widths = side.map { it.right - it.left }.sorted()
+ return widths[widths.size / 2] >= 0.15f
+ }
+ if (!columnLike(left) || !columnLike(right)) return null
+ return left to right
+ }
+
+ private fun horizontalCut(blocks: List<OcrTextBlock>): Pair<List<OcrTextBlock>, List<OcrTextBlock>>? {
+ val sorted = blocks.sortedBy { it.top }
+ var maxBottom = sorted.first().bottom
+ var bestAt = -1
+ var bestGap = 0f
+ for (i in 1 until sorted.size) {
+ val gap = sorted[i].top - maxBottom
+ if (gap > bestGap) { bestGap = gap; bestAt = i }
+ maxBottom = max(maxBottom, sorted[i].bottom)
+ }
+ if (bestAt < 0) return null
+ val top = sorted.subList(0, bestAt)
+ val bottom = sorted.subList(bestAt, sorted.size)
+ // Only worth recursing if one side can then be column-split; otherwise line order is
+ // already correct and cheaper.
+ if (verticalCut(top) == null && verticalCut(bottom) == null) return null
+ return top to bottom
+ }
+
+ private fun lineOrder(blocks: List<OcrTextBlock>): List<OcrTextBlock> {
+ val sorted = blocks.sortedBy { it.top }
+ val lines = mutableListOf<MutableList<OcrTextBlock>>()
+ for (b in sorted) {
+ val line = lines.lastOrNull()
+ val ref = line?.first()
+ if (ref != null) {
+ val overlap = min(ref.bottom, b.bottom) - max(ref.top, b.top)
+ val h = min(ref.bottom - ref.top, b.bottom - b.top)
+ if (overlap > h * 0.5f || abs(ref.bottom - b.bottom) < h * 0.3f) { line.add(b); continue }
+ }
+ lines.add(mutableListOf(b))
+ }
+ return lines.flatMap { l -> l.sortedBy { it.left } }
+ }
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfTextSelectionState.kt b/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfTextSelectionState.kt
new file mode 100644
index 0000000..1640462
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfTextSelectionState.kt
@@ -0,0 +1,352 @@
+package com.chethan616.clearpdf.ui.selection
+
+import androidx.compose.runtime.Stable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableFloatStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.geometry.Size
+import androidx.compose.ui.layout.LayoutCoordinates
+import androidx.compose.ui.unit.toSize
+import com.chethan616.clearpdf.ui.viewmodel.OcrTextBlock
+import com.chethan616.clearpdf.ui.viewmodel.OcrTextRange
+
+/** A caret position in the document: between characters [offset]-1 and [offset] of [page]'s flat text. */
+data class TextPos(val page: Int, val offset: Int) : Comparable<TextPos> {
+ override fun compareTo(other: TextPos): Int =
+ if (page != other.page) page.compareTo(other.page) else offset.compareTo(other.offset)
+}
+
+enum class SelectionHandle { Start, End }
+
+/** A handle's attachment point in screen space: the caret's x and its line's top/bottom. */
+data class ScreenCaret(val x: Float, val lineTop: Float, val lineBottom: Float) {
+ val lineHeight: Float get() = lineBottom - lineTop
+ val lineCenterY: Float get() = (lineTop + lineBottom) / 2f
+}
+
+/**
+ * The PDF viewer's text selection: an anchor/focus pair of [TextPos], possibly spanning pages.
+ *
+ * Owned by the viewer screen (not the ViewModel — it is pure UI state, like a TextField's selection).
+ * The screen refreshes the environment every composition: [blocksProvider], [transform]; pages
+ * register their [LayoutCoordinates] so page-local geometry can be mapped to the screen through the
+ * single pure [PdfViewportTransform].
+ *
+ * Every mutable field that UI reads is snapshot state, so highlight/handles/toolbar redraw when it
+ * changes; gestures hold on to this object (a stable reference) and never key on its values —
+ * restarting a `pointerInput` mid-drag is exactly the bug that used to kill handle drags.
+ */
+@Stable
+class PdfTextSelectionState {
+
+ var anchor by mutableStateOf<TextPos?>(null)
+ private set
+ var focus by mutableStateOf<TextPos?>(null)
+ private set
+
+ /** Which handle a finger is dragging, or null. */
+ var draggingHandle by mutableStateOf<SelectionHandle?>(null)
+ internal set
+
+ /** True for the whole of a long-press→drag or handle drag (hides the toolbar, blocks panning). */
+ var gestureActive by mutableStateOf(false)
+ internal set
+
+ /** Screen point the platform magnifier should enlarge; Unspecified hides it. */
+ var magnifierCenter by mutableStateOf(Offset.Unspecified)
+ internal set
+
+ /** Current zoom/pan; written by the screen every composition / gesture frame. */
+ var transform by mutableStateOf(PdfViewportTransform(0f, 1f, 0f))
+
+ /** Bumped whenever page geometry may have moved, so draw-phase readers re-run. */
+ internal var geometryTick by mutableFloatStateOf(0f)
+
+ var blocksProvider: (Int) -> List<OcrTextBlock> = { emptyList() }
+
+ private val pageCoords = HashMap<Int, LayoutCoordinates>()
+ private var layerCoords: LayoutCoordinates? = null
+ private val layoutCache = HashMap<Int, Pair<List<OcrTextBlock>, PdfTextLayout>>()
+
+ val hasSelection: Boolean
+ get() {
+ val a = anchor ?: return false
+ val f = focus ?: return false
+ return a != f
+ }
+
+ val start: TextPos? get() { val a = anchor ?: return null; val f = focus ?: return null; return minOf(a, f) }
+ val end: TextPos? get() { val a = anchor ?: return null; val f = focus ?: return null; return maxOf(a, f) }
+
+ // ── Environment ─────────────────────────────────────────────────────────────────────────
+
+ fun layout(page: Int): PdfTextLayout? {
+ val blocks = blocksProvider(page)
+ if (blocks.isEmpty()) return null
+ layoutCache[page]?.let { (b, l) -> if (b === blocks) return l }
+ return PdfTextLayout(blocks).also { layoutCache[page] = blocks to it }
+ }
+
+ fun registerPage(page: Int, coords: LayoutCoordinates) { pageCoords[page] = coords }
+ fun unregisterPage(page: Int, coords: LayoutCoordinates?) {
+ if (coords == null || pageCoords[page] === coords) pageCoords.remove(page)
+ }
+ fun registerLayer(coords: LayoutCoordinates) { layerCoords = coords }
+
+ fun resetDocument() {
+ clear()
+ layoutCache.clear()
+ pageCoords.clear()
+ }
+
+ /** Top-left of [page] in the zoom layer's own (unscaled) coordinates, if it is laid out. */
+ fun pageOrigin(page: Int): Offset? {
+ val layer = layerCoords ?: return null
+ val pc = pageCoords[page] ?: return null
+ if (!layer.isAttached || !pc.isAttached) return null
+ return runCatching { layer.localPositionOf(pc, Offset.Zero) }.getOrNull()
+ }
+
+ fun pageSize(page: Int): Size? = pageCoords[page]?.takeIf { it.isAttached }?.size?.toSize()
+
+ /** The laid-out page under (or vertically nearest to) screen point [p]. */
+ fun pageAtScreen(p: Offset): Int? {
+ val lp = transform.screenToLayer(p)
+ var best: Int? = null
+ var bestD = Float.MAX_VALUE
+ for (page in pageCoords.keys.toList()) {
+ val o = pageOrigin(page) ?: continue
+ val s = pageSize(page) ?: continue
+ val d = when {
+ lp.y < o.y -> o.y - lp.y
+ lp.y > o.y + s.height -> lp.y - (o.y + s.height)
+ else -> 0f
+ }
+ if (d < bestD) { bestD = d; best = page }
+ }
+ return best
+ }
+
+ // ── Selection mutation ──────────────────────────────────────────────────────────────────
+
+ fun select(anchor: TextPos, focus: TextPos) {
+ this.anchor = anchor
+ this.focus = focus
+ }
+
+ fun clear() {
+ anchor = null; focus = null
+ draggingHandle = null; gestureActive = false
+ magnifierCenter = Offset.Unspecified
+ }
+
+ /** Select all the text of pages [first]..[last] whose text is loaded. */
+ fun selectPages(first: Int, last: Int) {
+ var a: TextPos? = null
+ var f: TextPos? = null
+ for (p in first..last) {
+ val l = layout(p) ?: continue
+ if (a == null) a = TextPos(p, 0)
+ f = TextPos(p, l.length)
+ }
+ if (a != null && f != null && a != f) select(a, f)
+ }
+
+ // ── Queries ─────────────────────────────────────────────────────────────────────────────
+
+ /** The selected flat range on [page], or null. */
+ fun pageRange(page: Int): Pair<Int, Int>? {
+ val s = start ?: return null
+ val e = end ?: return null
+ if (s == e || page < s.page || page > e.page) return null
+ val l = layout(page) ?: return null
+ val from = if (page == s.page) s.offset.coerceIn(0, l.length) else 0
+ val to = if (page == e.page) e.offset.coerceIn(0, l.length) else l.length
+ return if (to > from) from to to else null
+ }
+
+ /** The selection as annotation-ready (blockId, start, end) ranges, per page. */
+ fun rangesByPage(): Map<Int, List<OcrTextRange>> {
+ val s = start ?: return emptyMap()
+ val e = end ?: return emptyMap()
+ val out = LinkedHashMap<Int, List<OcrTextRange>>()
+ for (p in s.page..e.page) {
+ val (from, to) = pageRange(p) ?: continue
+ val r = layout(p)?.rangesFor(from, to).orEmpty()
+ if (r.isNotEmpty()) out[p] = r
+ }
+ return out
+ }
+
+ /** Pages the selection spans. */
+ fun pageSpan(): IntRange? {
+ val s = start ?: return null
+ val e = end ?: return null
+ return s.page..e.page
+ }
+
+ /** Plain text of the selection: lines joined by newlines, pages by a blank line. */
+ fun selectedText(): String {
+ val s = start ?: return ""
+ val e = end ?: return ""
+ val parts = ArrayList<String>()
+ for (p in s.page..e.page) {
+ val (from, to) = pageRange(p) ?: continue
+ layout(p)?.substring(from, to)?.let { if (it.isNotBlank()) parts.add(it) }
+ }
+ return parts.joinToString("\n\n")
+ }
+
+ /** Screen caret geometry for a selection end, or null when that page is not laid out. */
+ fun handleCaret(handle: SelectionHandle): ScreenCaret? {
+ val pos = (if (handle == SelectionHandle.Start) start else end) ?: return null
+ return caretOnScreen(pos, handle == SelectionHandle.Start)
+ }
+
+ fun caretOnScreen(pos: TextPos, isStart: Boolean): ScreenCaret? {
+ val l = layout(pos.page) ?: return null
+ val origin = pageOrigin(pos.page) ?: return null
+ val size = pageSize(pos.page) ?: return null
+ val g = l.caretGeometry(pos.offset, isStart, size) ?: return null
+ val t = transform
+ val top = t.pageToScreen(Offset(g.x, g.lineTop), origin)
+ val bottom = t.pageToScreen(Offset(g.x, g.lineBottom), origin)
+ return ScreenCaret(bottom.x, top.y, bottom.y)
+ }
+
+ /** Selection highlight rectangles in screen space, for pages currently laid out. */
+ fun selectionScreenRects(): List<Rect> {
+ val span = pageSpan() ?: return emptyList()
+ val out = ArrayList<Rect>()
+ for (p in span) {
+ val (from, to) = pageRange(p) ?: continue
+ val origin = pageOrigin(p) ?: continue
+ val size = pageSize(p) ?: continue
+ layout(p)?.selectionRects(from, to, size)?.forEach { out.add(transform.pageRectToScreen(it, origin)) }
+ }
+ return out
+ }
+
+ /** Caret nearest a screen point, on the page under it. */
+ fun caretAtScreen(p: Offset): TextPos? {
+ val page = pageAtScreen(p) ?: return null
+ val l = layout(page) ?: return nearestTextPageCaret(page, p)
+ val origin = pageOrigin(page) ?: return null
+ val size = pageSize(page) ?: return null
+ return TextPos(page, l.caretAt(transform.screenToPage(p, origin), size))
+ }
+
+ /** A page with no text: snap to the end of the previous text page or start of the next. */
+ private fun nearestTextPageCaret(page: Int, p: Offset): TextPos? {
+ val origin = pageOrigin(page) ?: return null
+ val size = pageSize(page) ?: return null
+ val local = transform.screenToPage(p, origin)
+ val before = local.y < size.height / 2f
+ val cur = focus ?: return null
+ return if (before) {
+ (page - 1 downTo maxOf(0, page - 3)).firstNotNullOfOrNull { q -> layout(q)?.let { TextPos(q, it.length) } }
+ } else {
+ (page + 1..page + 3).firstNotNullOfOrNull { q -> layout(q)?.let { TextPos(q, 0) } }
+ } ?: cur
+ }
+
+ // ── Gesture logic ───────────────────────────────────────────────────────────────────────
+
+ private var pressWordPage = -1
+ private var pressWord: IntRange = IntRange.EMPTY
+
+ /**
+ * Long-press: select the word under [p]. Returns false (and changes nothing) when the press is
+ * not on text.
+ */
+ fun selectWordAt(p: Offset, slopPx: Float): Boolean {
+ val page = pageAtScreen(p) ?: return false
+ val l = layout(page) ?: return false
+ val origin = pageOrigin(page) ?: return false
+ val size = pageSize(page) ?: return false
+ val local = transform.screenToPage(p, origin)
+ if (local.y < -slopPx || local.y > size.height + slopPx) return false
+ val c = l.charAt(local, size, slopPx / transform.scale.coerceAtLeast(0.01f)) ?: return false
+ val w = l.wordAt(c)
+ if (w.isEmpty()) return false
+ pressWordPage = page
+ pressWord = w
+ select(TextPos(page, w.first), TextPos(page, w.last + 1))
+ return true
+ }
+
+ /** Long-press then drag (finger still down): extend word by word, like TextView. */
+ fun extendWordSelection(p: Offset): Boolean {
+ if (pressWordPage < 0) return false
+ val raw = caretAtScreen(p) ?: return false
+ val l = layout(raw.page) ?: return false
+ val w0s = TextPos(pressWordPage, pressWord.first)
+ val w0e = TextPos(pressWordPage, pressWord.last + 1)
+ val before = anchor to focus
+ if (raw >= w0e) {
+ val c = (raw.offset - 1).coerceAtLeast(0)
+ val w = l.wordAt(c)
+ select(w0s, TextPos(raw.page, maxOf(w.last + 1, raw.offset).coerceAtMost(l.length)))
+ } else if (raw <= w0s) {
+ val w = l.wordAt(raw.offset.coerceAtMost(l.length - 1))
+ select(w0e, TextPos(raw.page, minOf(w.first, raw.offset)))
+ } else {
+ select(w0s, w0e)
+ }
+ return before != (anchor to focus)
+ }
+
+ /** Pin the opposite end as the anchor so the grabbed end becomes the focus. */
+ fun beginHandleDrag(handle: SelectionHandle) {
+ val s = start ?: return
+ val e = end ?: return
+ if (handle == SelectionHandle.Start) select(e, s) else select(s, e)
+ draggingHandle = handle
+ gestureActive = true
+ }
+
+ /**
+ * Move the focus to the caret nearest [linePoint] (a screen point on the dragged caret's line).
+ * TextView granularity: expanding snaps to whole words once past a word's middle; shrinking is
+ * character-precise. Never collapses to an empty selection. Returns true if the focus moved.
+ */
+ fun dragFocusTo(linePoint: Offset): Boolean {
+ val a = anchor ?: return false
+ val f = focus ?: return false
+ val raw = caretAtScreen(linePoint) ?: return false
+ val l = layout(raw.page) ?: return false
+ val forward = f > a
+ val expanding = if (forward) raw > f else raw < f
+ var target = raw
+ if (expanding && l.length > 0) {
+ if (forward) {
+ val w = l.wordAt((raw.offset - 1).coerceIn(0, l.length - 1))
+ if (raw.offset > w.first && raw.offset < w.last + 1) {
+ val mid = w.first + (w.last + 1 - w.first) / 2f
+ target = TextPos(raw.page, if (raw.offset >= mid) w.last + 1 else w.first)
+ }
+ } else {
+ val w = l.wordAt(raw.offset.coerceIn(0, l.length - 1))
+ if (raw.offset > w.first && raw.offset < w.last + 1) {
+ val mid = w.first + (w.last + 1 - w.first) / 2f
+ target = TextPos(raw.page, if (raw.offset <= mid) w.first else w.last + 1)
+ }
+ }
+ }
+ if (target == a) return false
+ if (target == f) return false
+ focus = target
+ return true
+ }
+
+ fun endGesture() {
+ draggingHandle = null
+ gestureActive = false
+ magnifierCenter = Offset.Unspecified
+ pressWordPage = -1
+ // A drag can leave focus before anchor; that's fine — start/end are always normalised.
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfViewportTransform.kt b/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfViewportTransform.kt
new file mode 100644
index 0000000..9c3ef8b
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfViewportTransform.kt
@@ -0,0 +1,49 @@
+package com.chethan616.clearpdf.ui.selection
+
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Rect
+
+/**
+ * The PDF viewer's document-level zoom/pan, as a pure value: the ONE place page coordinates are
+ * mapped to screen coordinates and back.
+ *
+ * The page column sits in a `graphicsLayer` with `scaleX = scaleY = scale`,
+ * `translationX = offsetX`, `translationY = 0` and `transformOrigin = (0.5, 0)` — horizontally
+ * centred, top-anchored. Vertical position comes from the LazyColumn scroll, which lives INSIDE the
+ * layer, so it is already folded into a page's [pageOrigin] (its top-left in the layer's own,
+ * unscaled coordinates).
+ *
+ * "Screen" here means the viewer container's coordinates (the overlay that hosts the handles and the
+ * toolbar), which shares its origin with the un-transformed layer.
+ */
+data class PdfViewportTransform(
+ val containerWidth: Float,
+ val scale: Float,
+ val offsetX: Float
+) {
+ private val cx get() = containerWidth / 2f
+ private val s get() = if (scale == 0f) 1f else scale
+
+ fun layerToScreen(p: Offset): Offset =
+ Offset((p.x - cx) * s + cx + offsetX, p.y * s)
+
+ fun screenToLayer(p: Offset): Offset =
+ Offset((p.x - cx - offsetX) / s + cx, p.y / s)
+
+ /** A point in a page's local, unscaled coordinates → screen. */
+ fun pageToScreen(pagePoint: Offset, pageOrigin: Offset): Offset =
+ layerToScreen(pagePoint + pageOrigin)
+
+ /** A screen point → that page's local, unscaled coordinates. */
+ fun screenToPage(screenPoint: Offset, pageOrigin: Offset): Offset =
+ screenToLayer(screenPoint) - pageOrigin
+
+ fun pageRectToScreen(r: Rect, pageOrigin: Offset): Rect {
+ val tl = pageToScreen(r.topLeft, pageOrigin)
+ val br = pageToScreen(r.bottomRight, pageOrigin)
+ return Rect(tl, br)
+ }
+
+ /** Screen length of [pageLength] page pixels. */
+ fun toScreenLength(pageLength: Float): Float = pageLength * s
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PdfViewerViewModel.kt b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PdfViewerViewModel.kt
index efa10bf..989a7ee 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PdfViewerViewModel.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PdfViewerViewModel.kt
@@ -156,8 +156,6 @@ data class PdfViewerUiState(
val sizeBytes: Long = -1,
val ocrBlocksByPage: Map<Int, List<OcrTextBlock>> = emptyMap(),
val ocrPagesInProgress: Set<Int> = emptySet(),
- val selectedOcrBlockIdsByPage: Map<Int, Set<String>> = emptyMap(),
- val selectedOcrRangesByPage: Map<Int, List<OcrTextRange>> = emptyMap(),
val isExporting: Boolean = false,
val exportMessage: String? = null,
val exportError: String? = null,
@@ -280,8 +278,6 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
pageBitmaps = List(doc.pageCount) { null },
ocrBlocksByPage = emptyMap(),
ocrPagesInProgress = emptySet(),
- selectedOcrBlockIdsByPage = emptyMap(),
- selectedOcrRangesByPage = emptyMap(),
isExporting = false,
exportMessage = null,
exportError = null,
@@ -540,141 +536,6 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
if (evicted) _uiState.value = _uiState.value.copy(pageBitmaps = bitmaps)
}
- fun toggleOcrSelection(pageIndex: Int, blockId: String) {
- val current = _uiState.value
- val selectedByPage = current.selectedOcrBlockIdsByPage.toMutableMap()
- val rangesByPage = current.selectedOcrRangesByPage.toMutableMap()
- val selected = (selectedByPage[pageIndex] ?: emptySet()).toMutableSet()
- val ranges = (rangesByPage[pageIndex] ?: emptyList()).toMutableList()
- if (!selected.add(blockId)) {
- selected.remove(blockId)
- ranges.removeAll { it.blockId == blockId }
- } else {
- val block = current.ocrBlocksByPage[pageIndex].orEmpty().firstOrNull { it.id == blockId }
- if (block != null) ranges.add(block.fullTextRange())
- }
- selectedByPage[pageIndex] = selected
- rangesByPage[pageIndex] = ranges
- _uiState.value = current.copy(
- selectedOcrBlockIdsByPage = selectedByPage,
- selectedOcrRangesByPage = rangesByPage
- )
- }
-
- fun selectOcrBlocks(pageIndex: Int, blockIds: Set<String>, append: Boolean) {
- if (blockIds.isEmpty()) return
- val current = _uiState.value
- val ranges = current.ocrBlocksByPage[pageIndex].orEmpty()
- .filter { it.id in blockIds }
- .map { it.fullTextRange() }
- selectOcrRanges(pageIndex, ranges, append)
- }
-
- fun selectOcrRanges(pageIndex: Int, ranges: List<OcrTextRange>, append: Boolean) {
- val current = _uiState.value
- val blocks = current.ocrBlocksByPage[pageIndex].orEmpty().associateBy { it.id }
- val clean = ranges.mapNotNull { range ->
- val block = blocks[range.blockId] ?: return@mapNotNull null
- val start = range.start.coerceIn(0, block.text.length)
- val end = range.end.coerceIn(start, block.text.length)
- if (end <= start) null else OcrTextRange(block.id, start, end)
- }
- if (clean.isEmpty()) return
-
- val existing = if (append) current.selectedOcrRangesByPage[pageIndex].orEmpty() else emptyList()
- val merged = (existing + clean)
- .groupBy { it.blockId }
- .values
- .flatMap { blockRanges ->
- val sorted = blockRanges.sortedBy { it.start }
- buildList<OcrTextRange> {
- sorted.forEach { range ->
- val previous = lastOrNull()
- if (previous != null && range.start <= previous.end) {
- removeAt(lastIndex)
- add(previous.copy(end = maxOf(previous.end, range.end)))
- } else add(range)
- }
- }
- }
- val selectedByPage = current.selectedOcrBlockIdsByPage.toMutableMap()
- selectedByPage[pageIndex] = merged.map { it.blockId }.toSet()
- val rangesByPage = current.selectedOcrRangesByPage.toMutableMap()
- rangesByPage[pageIndex] = merged
- _uiState.value = current.copy(
- selectedOcrBlockIdsByPage = selectedByPage,
- selectedOcrRangesByPage = rangesByPage
- )
- }
-
- fun clearOcrSelection(pageIndex: Int) {
- val current = _uiState.value
- val selectedByPage = current.selectedOcrBlockIdsByPage.toMutableMap()
- val rangesByPage = current.selectedOcrRangesByPage.toMutableMap()
- selectedByPage.remove(pageIndex)
- rangesByPage.remove(pageIndex)
- _uiState.value = current.copy(
- selectedOcrBlockIdsByPage = selectedByPage,
- selectedOcrRangesByPage = rangesByPage
- )
- }
-
- fun selectLine(pageIndex: Int, blockId: String) {
- val state = _uiState.value
- val blocks = state.ocrBlocksByPage[pageIndex] ?: return
- val anchor = blocks.firstOrNull { it.id == blockId } ?: return
- val lineBlocks = blocks.filter { b ->
- val cY = (b.top + b.bottom) / 2f
- cY >= anchor.top && cY <= anchor.bottom
- }
- selectOcrBlocks(pageIndex, lineBlocks.map { it.id }.toSet(), append = false)
- }
-
- fun selectParagraph(pageIndex: Int, blockId: String) {
- val state = _uiState.value
- val blocks = state.ocrBlocksByPage[pageIndex]?.sortedBy { it.top } ?: return
- val anchor = blocks.firstOrNull { it.id == blockId } ?: return
- val avgLineHeight = blocks.map { it.bottom - it.top }.average().toFloat().coerceAtLeast(0.01f)
- val lineGapThreshold = avgLineHeight * 1.5f
-
- val paragraphBlocks = mutableListOf<OcrTextBlock>()
- var lastTop = anchor.top
- for (b in blocks.sortedByDescending { it.top }) {
- if (b.top > anchor.bottom + lineGapThreshold) continue
- if (lastTop - b.bottom > lineGapThreshold) break
- paragraphBlocks.add(b)
- lastTop = b.top
- }
- var lastBottom = anchor.bottom
- for (b in blocks.sortedBy { it.top }) {
- if (b.bottom < anchor.top - lineGapThreshold) continue
- if (b.top - lastBottom > lineGapThreshold) break
- if (!paragraphBlocks.contains(b)) paragraphBlocks.add(b)
- lastBottom = b.bottom
- }
- if (paragraphBlocks.isNotEmpty()) {
- selectOcrBlocks(pageIndex, paragraphBlocks.map { it.id }.toSet(), append = false)
- }
- }
-
- fun getSelectedOcrText(pageIndex: Int): String {
- val state = _uiState.value
- val blocks = state.ocrBlocksByPage[pageIndex].orEmpty()
- val selected = state.selectedOcrRangesByPage[pageIndex].orEmpty()
- if (selected.isEmpty()) return ""
- val byId = blocks.associateBy { it.id }
- return selected
- .sortedWith(compareBy({ byId[it.blockId]?.top ?: Float.MAX_VALUE }, { byId[it.blockId]?.left ?: Float.MAX_VALUE }, { it.start }))
- .mapNotNull { range ->
- val block = byId[range.blockId] ?: return@mapNotNull null
- block.text.substring(range.start.coerceIn(0, block.text.length), range.end.coerceIn(0, block.text.length))
- .trim()
- .takeIf { it.isNotEmpty() }
- }
- .joinToString(" ")
- .trim()
- }
-
fun clearExportFeedback() {
_uiState.value = _uiState.value.copy(exportMessage = null, exportError = null)
}
@@ -1098,9 +959,6 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
}
}
-private fun OcrTextBlock.fullTextRange(): OcrTextRange =
- OcrTextRange(id, 0, text.length)
-
private fun PdfTextBlock.toOcrBlock() = OcrTextBlock(
id = id, text = text, left = left, top = top, right = right, bottom = bottom,
charLefts = charLefts, charRights = charRights
diff --git a/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextService.kt b/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextService.kt
index e51763e..efe9c0e 100644
--- a/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextService.kt
+++ b/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextService.kt
@@ -121,7 +121,31 @@ class PdfTextServiceImpl : PdfTextService {
}
}
- return lines.mapIndexedNotNull { lineIdx, linePositions ->
+ // A "line" above is every glyph sharing a baseline across the FULL page width, so on a
+ // two-column page the left and right columns' lines merged into one block ("...end of left
+ // sentence start of right sentence..."). Split each line wherever the horizontal gap between
+ // consecutive glyphs is far wider than any word space (> ~3x the line's average glyph
+ // width): column gutters and wide table gaps become separate blocks, ordinary word spacing
+ // (even justified) never reaches that.
+ val segments = lines.flatMap { line ->
+ val byX = line.sortedBy { it.x }
+ val avgW = byX.map { it.width }.filter { it > 0f }.average().toFloat()
+ .takeIf { !it.isNaN() && it > 0f } ?: avgH * 0.5f
+ val splitGap = avgW * 3f
+ val out = mutableListOf<MutableList<TextPosition>>()
+ var lastRight = -Float.MAX_VALUE
+ for (tp in byX) {
+ if (out.isEmpty() || (lastRight > -Float.MAX_VALUE && tp.x - lastRight > splitGap)) {
+ out.add(mutableListOf(tp))
+ } else {
+ out.last().add(tp)
+ }
+ lastRight = maxOf(lastRight, tp.x + tp.width)
+ }
+ out
+ }
+
+ return segments.mapIndexedNotNull { lineIdx, linePositions ->
val byX = linePositions.sortedBy { it.x }
// Build the line text AND per-character x bounds together so indices stay aligned.
val sb = StringBuilder()