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
Rebuild PDF text selection: long-press word select, platform handles, glass toolbar; remove Select Text mode
Chethan616129366e67177
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex 029aede..81e487b 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -14,6 +14,15 @@<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28" /><uses-feature android:name="android.hardware.camera" android:required="false" />+ <!-- Package visibility (Android 11+) for the text-selection toolbar's "process text" apps+ (Translate, dictionaries), the same list a TextView's selection menu offers. -->+ <queries>+ <intent>+ <action android:name="android.intent.action.PROCESS_TEXT" />+ <data android:mimeType="text/plain" />+ </intent>+ </queries>+<applicationandroid:allowBackup="true"android:enableOnBackInvokedCallback="true"diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfContinuousPage.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfContinuousPage.ktindex ab89eab..f759b29 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfContinuousPage.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfContinuousPage.kt@@ -6,7 +6,7 @@ import androidx.compose.foundation.Imageimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.borderimport androidx.compose.foundation.clickable-import androidx.compose.foundation.magnifier+import androidx.compose.foundation.text.selection.LocalTextSelectionColorsimport androidx.compose.foundation.gestures.awaitEachGestureimport androidx.compose.foundation.gestures.awaitFirstDownimport androidx.compose.foundation.gestures.detectDragGestures@@ -39,6 +39,7 @@ import androidx.compose.material.icons.rounded.StrikethroughSimport androidx.compose.material3.CircularProgressIndicatorimport androidx.compose.material3.Iconimport androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.remember@@ -64,7 +65,16 @@ import androidx.compose.ui.graphics.vector.ImageVectorimport androidx.compose.ui.geometry.CornerRadiusimport androidx.compose.ui.input.pointer.pointerInputimport androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.layout.onGloballyPositionedimport androidx.compose.ui.layout.onSizeChanged+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.CustomAccessibilityAction+import androidx.compose.ui.semantics.customActions+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.semantics.text+import androidx.compose.ui.text.AnnotatedString+import com.chethan616.clearpdf.R+import com.chethan616.clearpdf.ui.selection.PdfTextSelectionStateimport androidx.compose.ui.platform.LocalDensityimport androidx.compose.ui.text.TextStyleimport androidx.compose.ui.text.font.FontWeight@@ -79,22 +89,6 @@ import com.chethan616.clearpdf.ui.viewmodel.OcrTextRangeimport kotlin.math.maximport kotlin.math.min-/** One icon+label action in the stock-style text-selection menu (Acrobat/Drive look). */-@Composable-private fun SelectionMenuItem(icon: ImageVector, label: String, tint: Color, onClick: () -> Unit) {- Column(- Modifier- .clip(RoundedCornerShape(8.dp))- .clickable(onClick = onClick)- .padding(horizontal = 10.dp, vertical = 6.dp)- .width(52.dp),- horizontalAlignment = Alignment.CenterHorizontally- ) {- Icon(icon, label, Modifier.size(20.dp), tint)- BasicText(label, style = TextStyle(tint, 10.sp, FontWeight.Medium), maxLines = 1)- }-}-/*** A single page inside the continuous (Adobe-style) vertical viewer.*@@ -109,8 +103,6 @@ internal fun PdfContinuousPage(bitmap: Bitmap?,marks: MutableList<PdfMarkup>,ocrBlocks: List<OcrTextBlock>,- selectedOcrIds: Set<String>,- selectedOcrRanges: List<OcrTextRange>,findMatches: List<FindMatch>,currentMatchIndex: Int,showFindBar: Boolean,@@ -127,8 +119,6 @@ internal fun PdfContinuousPage(onShowControls: () -> Unit,onActiveToolChanged: (PdfEditTool) -> Unit,onActiveImageIdChanged: (Long?) -> Unit,- onClearOcrSelection: () -> Unit,- onSelectOcrRange: (List<OcrTextRange>) -> Unit,onPlaceText: (Offset) -> Unit,onPlaceNote: (Offset) -> Unit,onEditAnnotation: (Long) -> Unit,@@ -137,34 +127,21 @@ internal fun PdfContinuousPage(selectedMarkupIndex: Int = -1,onSelectMarkup: (Int) -> Unit = {},onDeleteMarkup: (Int) -> Unit = {},- onCopySelection: () -> Unit = {},- onHighlightSelection: () -> Unit = {},- onUnderlineSelection: () -> Unit = {},- onStrikeSelection: () -> Unit = {},- onSetColorLong: (Long) -> Unit = {},- onSelectAll: () -> Unit = {}+ /** The viewer's text selection: this page draws its slice of the highlight and registers its coordinates. */+ textSelection: PdfTextSelectionState) {var draftPoints by remember(page, activeTool) { mutableStateOf<List<Offset>>(emptyList()) }var draftRectStart by remember(page, activeTool) { mutableStateOf<Offset?>(null) }var draftRectEnd by remember(page, activeTool) { mutableStateOf<Offset?>(null) }- var selDragStart by remember(page, activeTool) { mutableStateOf<Offset?>(null) }- var selDragEnd by remember(page, activeTool) { mutableStateOf<Offset?>(null) }- // Live focus point for the native magnifier loupe. Offset.Unspecified hides it; while a- // selection drag is in flight it tracks the finger so text stays legible under the fingertip,- // exactly like the platform text selector.- var magnifierFocus by remember(page, activeTool) { mutableStateOf(Offset.Unspecified) }- val selectionHandleDiameterPx = with(LocalDensity.current) { 32.dp.toPx() }- val selectionHandleHitRadiusPx = with(LocalDensity.current) { 30.dp.toPx() }- // Read inside the handle-drag gesture below instead of the raw `selectedOcrRanges` parameter.- // That gesture used to key its `pointerInput` on `selectedOcrRanges` itself — but the gesture- // is also what MUTATES it on every move (`onSelectOcrRange` inside `updateRange()`), so the- // instant a drag moved past touch slop, Compose saw the key change and cancelled + restarted- // the gesture coroutine mid-drag. The restarted `awaitEachGesture` then waited on a fresh- // touch-down that never came (the same finger was already down), which is why a handle drag- // died after exactly one movement in any direction. `selectedOcrRanges` is no longer a key —- // `rememberUpdatedState` is what lets the gesture still read the *current* selection at the- // start of each new touch (to know which handle was grabbed) without needing a key at all.- val latestSelectedOcrRanges by rememberUpdatedState(selectedOcrRanges)+ val selectionColors = LocalTextSelectionColors.current+ DisposableEffect(page, textSelection) { onDispose { textSelection.unregisterPage(page, null) } }+ // Accessibility: expose the page's extracted text to TalkBack, plus a "select page text" action.+ val selectPageLabel = stringResource(R.string.selection_select_page_text)+ val pageText = remember(ocrBlocks) { textSelection.layout(page)?.text.orEmpty() }+ val pageTextSemantics = if (pageText.isEmpty()) Modifier else Modifier.semantics {+ text = AnnotatedString(pageText)+ customActions = listOf(CustomAccessibilityAction(selectPageLabel) { textSelection.selectPages(page, page); true })+ }// Page layout (rebuilt on the Pdf_Tools model): the image is drawn at its TRUE// aspect via ContentScale.FillWidth, so the box height follows the bitmap. There@@ -198,15 +175,9 @@ internal fun PdfContinuousPage(.padding(vertical = 6.dp).then(if (bitmap == null) Modifier.aspectRatio(placeholderAspect ?: (1f / 1.414f)) else Modifier).background(Color(0xFF15181E))- // Native platform loupe (Android 9+). Inactive — and a no-op on older devices —- // whenever the focus point is Unspecified, so it costs nothing outside a drag.- .magnifier(- sourceCenter = { magnifierFocus },- zoom = 1.5f,- size = DpSize(112.dp, 64.dp),- cornerRadius = 32.dp,- elevation = 4.dp- )+ // Page-local coordinates for the text selection's screen mapping (see PdfViewportTransform).+ .onGloballyPositioned { textSelection.registerPage(page, it) }+ .then(pageTextSemantics).onSizeChanged { sz ->pageCanvasSizes[page] = Size(sz.width.toFloat(), sz.height.toFloat())if (bitmap != null) pageBitmapSizes[page] = Size(bitmap.width.toFloat(), bitmap.height.toFloat())@@ -231,17 +202,11 @@ internal fun PdfContinuousPage(Canvas(Modifier.matchParentSize()) {val frame = Rect(0f, 0f, size.width, size.height)- selectedOcrRanges.forEach { range ->- ocrBlocks.firstOrNull { it.id == range.blockId }?.let { b ->- val r = expandedTextHighlightRect(ocrTextRangeToRect(b, range, frame), verticalScale = 1.35f)- // Fully rounded — half the band's own height, a real capsule — not the old 2-5px- // clamp, which read as a barely-softened rectangle. The handles hanging off each- // end are a rounded teardrop; a flat bar between them was what made the whole- // selection look like two balloons stuck onto a straight rod instead of one- // shape. Same blue family as the handles (#4285F4) so the band and the handles- // it connects to read as one selection, not two unrelated pieces.- val radius = r.height * 0.5f- drawRoundRect(Color(0xFF4285F4).copy(0.28f), r.topLeft, r.size, CornerRadius(radius, radius))+ // Text selection highlight — the platform selection colour, one band per line fragment.+ // Drawn inside the zoom layer so it scales with the page, exactly like the glyphs.+ textSelection.pageRange(page)?.let { (from, to) ->+ textSelection.layout(page)?.selectionRects(from, to, size)?.forEach { r ->+ drawRect(selectionColors.backgroundColor, r.topLeft, r.size)}}@@ -378,21 +343,6 @@ internal fun PdfContinuousPage(}}- if (activeTool == PdfEditTool.SelectText) {- ocrSelectionHandleAnchors(ocrBlocks, selectedOcrRanges, frame)?.let { (start, end) ->- // Size each handle off its own line's rendered height, clamped to a sane- // touch-target range, instead of a fixed dp that ignores the page's current- // zoom/fit-width scale (see ocrSelectionHandleLineHeights doc).- val (startLineH, endLineH) = ocrSelectionHandleLineHeights(ocrBlocks, selectedOcrRanges, frame)- ?: (selectionHandleDiameterPx to selectionHandleDiameterPx)- // DrawScope is itself a Density, so dp -> px works directly here.- val minPx = 14.dp.toPx()- val maxPx = 30.dp.toPx()- drawTextSelectionHandle(start, (startLineH * 1.1f).coerceIn(minPx, maxPx), isLeftHandle = true)- drawTextSelectionHandle(end, (endLineH * 1.1f).coerceIn(minPx, maxPx), isLeftHandle = false)- }- }-// In-progress draftsif (draftPoints.size > 1) {val isHl = activeTool == PdfEditTool.Highlight@@ -640,189 +590,7 @@ internal fun PdfContinuousPage()}- if (activeTool == PdfEditTool.SelectText) {- Box(Modifier.matchParentSize()- .pointerInput(page, ocrBlocks) {- val frame = Rect(0f, 0f, size.width.toFloat(), size.height.toFloat())- detectTapGestures(- // A tap or double-tap lands on one word. Long-press follows the platform- // text-selection convention: select that word and reveal the contextual- // Copy / Highlight actions above it.- onDoubleTap = { p -> hitTestOcrWord(ocrBlocks, p, frame)?.let { onSelectOcrRange(listOf(it)) }; onInteraction() },- onLongPress = { p -> hitTestOcrWord(ocrBlocks, p, frame)?.let { onSelectOcrRange(listOf(it)) }; onInteraction() },- onTap = { p -> hitTestOcrWord(ocrBlocks, p, frame)?.let { onSelectOcrRange(listOf(it)) } ?: onClearOcrSelection(); onInteraction() }- )- }- // Direct drag (no long-press wait): sweep a contiguous run of words in reading order- // and update the range live. The page stays in text-selection mode, while the parent- // viewer still receives two-finger pinch events for zoom.- .pointerInput(page, ocrBlocks, selectionHandleHitRadiusPx) {- fun updateRange() {- val s = selDragStart; val e = selDragEnd- if (s == null || e == null || ocrBlocks.isEmpty()) return- val frame = Rect(0f, 0f, size.width.toFloat(), size.height.toFloat())- // Character-precise sweep (native granularity) — extends smoothly across- // words, lines and paragraphs instead of snapping a whole word at a time.- onSelectOcrRange(ocrCharRangesBetween(ocrBlocks, frame, s, e))- magnifierFocus = e- }-- // Do not use detectDragGestures here: it commits to a one-finger drag before- // the second finger of a pinch arrives. That is why zooming used to leave a- // text selection behind. We wait for touch slop, then only consume while the- // gesture remains single-touch; a second finger cancels selection immediately- // and leaves the event stream available to the viewer's pinch detector.- awaitEachGesture {- val down = awaitFirstDown(requireUnconsumed = false)- val frame = Rect(0f, 0f, size.width.toFloat(), size.height.toFloat())- val handles = ocrSelectionHandleAnchors(ocrBlocks, latestSelectedOcrRanges, frame)- val handleMode = when {- handles == null -> 0- (down.position - handles.first).getDistance() <= selectionHandleHitRadiusPx -> 1- (down.position - handles.second).getDistance() <= selectionHandleHitRadiusPx -> 2- else -> 0- }- val fixedHandlePoint = when (handleMode) {- 1 -> handles?.second- 2 -> handles?.first- else -> null- }- val pointerId = down.id- var selecting = false- var multiTouch = false- do {- val event = awaitPointerEvent()- val pressed = event.changes.count { it.pressed }- if (pressed > 1) {- if (!multiTouch) {- multiTouch = true- if (selecting) onClearOcrSelection()- }- selDragStart = null- selDragEnd = null- magnifierFocus = Offset.Unspecified- } else if (!multiTouch) {- val change = event.changes.firstOrNull { it.id == pointerId }- if (change != null) {- if (!selecting && (change.position - down.position).getDistance() > viewConfiguration.touchSlop) {- selecting = true- selDragStart = fixedHandlePoint ?: down.position- selDragEnd = change.position- updateRange()- onInteraction()- } else if (selecting) {- change.consume()- selDragStart = fixedHandlePoint ?: down.position- selDragEnd = change.position- updateRange()- onInteraction()- }- }- }- } while (event.changes.any { it.pressed })- selDragStart = null- selDragEnd = null- magnifierFocus = Offset.Unspecified- }- }- )- }-- // ── Contextual selection bubble (Copy / Highlight), smart-positioned ──────val csz = pageCanvasSizes[page]- if (activeTool == PdfEditTool.SelectText && selectedOcrIds.isNotEmpty() && csz != null && csz.width > 0f) {- val frame = Rect(0f, 0f, csz.width, csz.height)- val selRects = selectedOcrRanges.mapNotNull { range ->- ocrBlocks.firstOrNull { it.id == range.blockId }?.let { ocrTextRangeToRect(it, range, frame) }- }.ifEmpty {- selectedOcrIds.mapNotNull { id -> ocrBlocks.firstOrNull { it.id == id }?.let { ocrBlockToRect(it, frame) } }- }- if (selRects.isNotEmpty()) {- val density = LocalDensity.current- val selLeft = selRects.minOf { it.left }- val selTop = selRects.minOf { it.top }- val selRight = selRects.maxOf { it.right }- val selBottom = selRects.maxOf { it.bottom }- // Is any selected word already carrying a highlight? If so the pill gains a Remove- // action — this is the fix for "tap a highlight again and there's no delete, only- // copy/highlight". The selection and the highlight live in two different models (OCR- // selection vs. the page's markup list), so we cross-reference by block id.- val selectionHasHighlight = selectedOcrIds.any { id ->- marks.any { it is PdfMarkup.TextBlockHighlightMarkup && it.blockId == id }- }- val gapPx = with(density) { 8.dp.toPx() }- val bubbleHpx = with(density) { 148.dp.toPx() }- val itemCount = if (selectionHasHighlight) 6 else 5- val bubbleWpx = with(density) { (itemCount * 60).dp.toPx() }- // Flip below the selection when it's too close to the page top.- val placeBelow = selTop < bubbleHpx + gapPx- val by = (if (placeBelow) selBottom + gapPx else selTop - bubbleHpx - gapPx).coerceIn(0f, (csz.height - bubbleHpx).coerceAtLeast(0f))- val bx = ((selLeft + selRight) / 2f - bubbleWpx / 2f).coerceIn(0f, (csz.width - bubbleWpx).coerceAtLeast(0f))-- // Icon-menu look (Acrobat/Drive-style), not a pill of coloured text: a plain- // dark card, one icon+label column per action, neutral colour throughout except- // the active/applied state and the destructive action.- val menuFg = Color(0xFFCCCCCC)- Column(- Modifier- .offset { IntOffset(bx.roundToInt(), by.roundToInt()) }- .clip(RoundedCornerShape(14.dp))- .background(Color(0xFF232629))- .border(1.dp, Color.White.copy(0.08f), RoundedCornerShape(14.dp))- ) {- Row(- Modifier- .padding(horizontal = 4.dp, vertical = 6.dp)- .horizontalScroll(rememberScrollState()),- verticalAlignment = Alignment.CenterVertically- ) {- SelectionMenuItem(Icons.Rounded.ContentCopy, "Copy", menuFg) {- onCopySelection(); onClearOcrSelection()- }- SelectionMenuItem(Icons.Rounded.SelectAll, "Select all", menuFg) { onSelectAll() }- SelectionMenuItem(- Icons.Rounded.Highlight,- if (selectionHasHighlight) "Recolor" else "Highlight",- if (selectionHasHighlight) currentColor else menuFg- ) { onHighlightSelection() }- SelectionMenuItem(Icons.Rounded.FormatUnderlined, "Underline", menuFg) { onUnderlineSelection() }- SelectionMenuItem(Icons.Rounded.StrikethroughS, "Strike", menuFg) { onStrikeSelection() }- if (selectionHasHighlight) {- SelectionMenuItem(Icons.Rounded.Delete, "Delete", Color(0xFFEF5350)) {- // Drop every highlight sitting on a selected word, then clear the- // selection so the menu dismisses.- marks.removeAll { it is PdfMarkup.TextBlockHighlightMarkup && it.blockId in selectedOcrIds }- onClearOcrSelection()- }- }- }- Box(Modifier.fillMaxWidth().height(1.dp).background(Color.White.copy(0.08f)))- Row(- Modifier- .padding(horizontal = 10.dp, vertical = 8.dp)- .horizontalScroll(rememberScrollState()),- horizontalArrangement = Arrangement.spacedBy(10.dp),- verticalAlignment = Alignment.CenterVertically- ) {- editorPalette.forEach { c ->- val isSel = c.value == currentColor.value- Box(- Modifier- .size(16.dp)- .clip(CircleShape)- .background(c)- .border(- width = if (isSel) 2.dp else 0.dp,- color = Color.White.copy(0.85f),- shape = CircleShape- )- .clickable { onSetColorLong(c.value.toLong()) }- )- }- }- }- }- }// ── Contextual Edit / Delete bar for the selected shape / text / note ──────if (activeTool == PdfEditTool.None && csz != null && csz.width > 0f) {diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerBottomToolbar.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerBottomToolbar.ktindex dd774e1..d715197 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerBottomToolbar.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerBottomToolbar.kt@@ -135,8 +135,6 @@ internal fun PdfViewerBottomToolbar(exportError: String?,exportMessage: String?,lastExportedUri: Uri?,- selectedTextCount: Int,- currentSelectedIds: Set<String>,activeIsSignature: Boolean,// Undo/clear are driven by the viewer's own history rather than by a list handed down here: the// page the user is drawing on is NOT `firstVisibleItemIndex`, so a list picked by the toolbar@@ -154,12 +152,6 @@ internal fun PdfViewerBottomToolbar(onImageDone: () -> Unit,onReplaceImage: () -> Unit,onDeleteImage: () -> Unit,- onSelectAllText: () -> Unit,- onCopyText: () -> Unit,- onHighlightSelected: () -> Unit,- onUnderlineSelected: () -> Unit,- onStrikeSelected: () -> Unit,- onClearTextSelection: () -> Unit,onSetColorLong: (Long) -> Unit,onSetStrokeWidth: (Float) -> Unit,onDismissExportFeedback: () -> Unit,@@ -198,13 +190,12 @@ internal fun PdfViewerBottomToolbar(val pillGlass = Color.Transparentval showDrawTools = drawingToolActive- val showOcrTools = activeTool == PdfEditTool.SelectText || selectedTextCount > 0val showImageTools = activeTool == PdfEditTool.Image && activeImageId != null// The two faces of the toolbar never share the screen: the SELECTOR face (the tool chips + the// blue "Editor Tools" pill) and the SUB-TOOLBAR face (draw / OCR / image). `subActive` is the// dimension that swaps them.- val subActive = showDrawTools || showOcrTools || showImageTools+ val subActive = showDrawTools || showImageTools// Apple-style hand-off. The old code removed the selector face INSTANTLY (ExitTransition.None)// while the sub-toolbar faded in, so the two vanished/appeared on top of each other. Instead we// run a tiny two-phase gate: the outgoing face fades fully out, and only THEN does the incoming@@ -366,29 +357,6 @@ internal fun PdfViewerBottomToolbar() { Icon(Icons.Rounded.Delete, stringResource(R.string.viewer_clear), Modifier.size(19.dp), Color.White) }}- showOcrTools -> {- // Plain, native-menu-style neutral buttons — no per-action rainbow- // tinting — matching the in-context selection toolbar's look.- LiquidButton(onClick = onSelectAllText, backdrop = backdrop, surfaceColor = chip) {- BasicText(stringResource(R.string.viewer_select_all), style = TextStyle(fg, 12.sp, FontWeight.Medium))- }- LiquidButton(onClick = onCopyText, backdrop = backdrop, surfaceColor = chip) {- BasicText(stringResource(R.string.copy), style = TextStyle(fg, 12.sp, FontWeight.Medium))- }- LiquidButton(onClick = onHighlightSelected, backdrop = backdrop, surfaceColor = chip) {- BasicText(stringResource(R.string.viewer_highlight), style = TextStyle(fg, 12.sp, FontWeight.Medium))- }- LiquidButton(onClick = onUnderlineSelected, backdrop = backdrop, surfaceColor = chip) {- BasicText(stringResource(R.string.viewer_underline), style = TextStyle(fg, 12.sp, FontWeight.Medium))- }- LiquidButton(onClick = onStrikeSelected, backdrop = backdrop, surfaceColor = chip) {- BasicText(stringResource(R.string.viewer_strike), style = TextStyle(fg, 12.sp, FontWeight.Medium))- }- LiquidButton(onClick = onClearTextSelection, backdrop = backdrop, surfaceColor = chip) {- BasicText(stringResource(R.string.viewer_clear), style = TextStyle(fg, 12.sp, FontWeight.Medium))- }- }-showImageTools -> {Row(modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),@@ -581,13 +549,6 @@ internal fun PdfViewerBottomToolbar(verticalAlignment = Alignment.CenterVertically) {fun wSurface(color: Color, active: Boolean) = color.copy(if (active) 0.96f else 0.80f)- val selOn = activeTool == PdfEditTool.SelectText- LiquidButton(onClick = { onSetActiveTool(if (selOn) PdfEditTool.None else PdfEditTool.SelectText) }, backdrop = backdrop, surfaceColor = wSurface(Color(0xFF7B1FA2), selOn)) {- BasicText(- if (selectedTextCount > 0) stringResource(R.string.viewer_ocr, selectedTextCount) else stringResource(R.string.viewer_select_text),- style = TextStyle(Color.White, 12.sp, FontWeight.Medium)- )- }val hlOn = activeTool == PdfEditTool.HighlightLiquidButton(onClick = { onSetActiveTool(if (hlOn) PdfEditTool.None else PdfEditTool.Highlight) }, backdrop = backdrop, surfaceColor = wSurface(Color(0xFFF9A825), hlOn)) {Row(horizontalArrangement = Arrangement.spacedBy(4.dp), verticalAlignment = Alignment.CenterVertically) {@@ -633,18 +594,6 @@ internal fun PdfViewerBottomToolbar(surfaceColor = toolSurface(Color(0xFF0097A7), drawOn)) { BasicText(stringResource(R.string.viewer_draw_tools), style = TextStyle(Color.White, 12.sp, FontWeight.Medium)) }- val selOn = activeTool == PdfEditTool.SelectText- LiquidButton(- onClick = { onSetActiveTool(if (selOn) PdfEditTool.None else PdfEditTool.SelectText) },- backdrop = backdrop,- surfaceColor = toolSurface(Color(0xFF7B1FA2), selOn)- ) {- BasicText(- if (selectedTextCount > 0) stringResource(R.string.viewer_ocr, selectedTextCount) else stringResource(R.string.viewer_select_text),- style = TextStyle(Color.White, 12.sp, FontWeight.Medium)- )- }-val imgOn = activeTool == PdfEditTool.ImageLiquidButton(onClick = { onPickImage() },@@ -703,7 +652,7 @@ internal fun PdfViewerBottomToolbar(}}- if (drawingToolActive || activeTool == PdfEditTool.SelectText || activeTool == PdfEditTool.Image || activeTool == PdfEditTool.Eraser || activeTool == PdfEditTool.Text || activeTool == PdfEditTool.Note) {+ if (drawingToolActive || activeTool == PdfEditTool.Image || activeTool == PdfEditTool.Eraser || activeTool == PdfEditTool.Text || activeTool == PdfEditTool.Note) {LiquidIconButton(onClick = { onSetActiveTool(PdfEditTool.None) },backdrop = backdrop,diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerInternals.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerInternals.ktindex 0fefd18..5886730 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerInternals.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerInternals.kt@@ -27,7 +27,7 @@ import kotlin.math.sininternal enum class ScrollOrientation { Vertical, Horizontal }-internal enum class PdfEditTool { None, Draw, Highlight, Rect, Ellipse, Line, Arrow, SelectText, Image, Eraser, Text, Note }+internal enum class PdfEditTool { None, Draw, Highlight, Rect, Ellipse, Line, Arrow, Image, Eraser, Text, Note }internal enum class ViewerToolbarMode { Main, Drawing, Selection, Image, Eraser, Search, Signature }@@ -303,20 +303,6 @@ internal fun ocrBlockToRect(block: OcrTextBlock, frame: Rect): Rect = Rect(frame.top + block.bottom * frame.height)-internal fun OcrTextBlock.wordRanges(): List<IntRange> {- if (text.isEmpty()) return emptyList()- val ranges = mutableListOf<IntRange>()- var index = 0- while (index < text.length) {- while (index < text.length && text[index].isWhitespace()) index++- if (index >= text.length) break- val start = index- while (index < text.length && !text[index].isWhitespace()) index++- ranges += start..(index - 1)- }- return ranges-}-internal fun ocrTextRangeToRect(block: OcrTextBlock, range: OcrTextRange, frame: Rect): Rect {val start = range.start.coerceIn(0, block.text.length)val end = (if (range.end < 0) block.text.length else range.end)@@ -401,302 +387,6 @@ internal fun expandedTextHighlightRect(rect: Rect, verticalScale: Float = 1f): Rreturn Rect(rect.left - padX, rect.top - padTop, rect.right + padX, rect.bottom + padBottom)}-internal fun ocrSelectionHandleAnchors(- blocks: List<OcrTextBlock>,- ranges: List<OcrTextRange>,- frame: Rect-): Pair<Offset, Offset>? {- if (ranges.isEmpty()) return null- val blocksById = blocks.associateBy { it.id }- val ordered = ranges.sortedWith(- compareBy<OcrTextRange>(- { blocksById[it.blockId]?.top ?: Float.MAX_VALUE },- { blocksById[it.blockId]?.left ?: Float.MAX_VALUE },- { it.start }- )- )- val first = ordered.first()- val last = ordered.last()- val firstRect = expandedTextHighlightRect(- ocrTextRangeToRect(blocksById[first.blockId] ?: return null, first, frame),- verticalScale = 1.35f- )- val lastRect = expandedTextHighlightRect(- ocrTextRangeToRect(blocksById[last.blockId] ?: return null, last, frame),- verticalScale = 1.35f- )- return Offset(firstRect.left, firstRect.bottom) to Offset(lastRect.right, lastRect.bottom)-}--/**- * Rendered line height (in the same canvas-local pixels as [ocrSelectionHandleAnchors]'s- * anchors) for the first/last selected line. The page is drawn at whatever zoom/fit-width- * scale is currently active, so a FIXED dp handle size looks tiny at 200% zoom and gigantic- * at fit-width (a full page's line height can be under 20px there) — handles must scale with- * the text they're anchored to, exactly like the platform text selector's do.- */-internal fun ocrSelectionHandleLineHeights(- blocks: List<OcrTextBlock>,- ranges: List<OcrTextRange>,- frame: Rect-): Pair<Float, Float>? {- if (ranges.isEmpty()) return null- val blocksById = blocks.associateBy { it.id }- val ordered = ranges.sortedWith(- compareBy<OcrTextRange>(- { blocksById[it.blockId]?.top ?: Float.MAX_VALUE },- { blocksById[it.blockId]?.left ?: Float.MAX_VALUE },- { it.start }- )- )- val firstBlock = blocksById[ordered.first().blockId] ?: return null- val lastBlock = blocksById[ordered.last().blockId] ?: return null- return (firstBlock.bottom - firstBlock.top) * frame.height to (lastBlock.bottom - lastBlock.top) * frame.height-}--/**- * Stock-Android-style selection handle: a circle with one sharp corner notched out exactly at- * [anchor] — the actual look of the system text-selection handles (and Chrome's, and Google Docs'),- * not a free-floating teardrop. The bulge always leans *toward* the selection it bounds: the left- * handle's sharp corner sits at its top-left with the circle hanging down-right (into the selected- * text), the right handle's sharp corner sits at top-right with the circle hanging down-left.- *- * The construction is the special case where a circle of radius `r` is centered exactly `(r, r)`- * diagonally from the external anchor point: the tangent lines from the anchor to that circle then- * land exactly on the horizontal and vertical through the anchor (no trig needed to find them), and- * the visible arc is the far 270° of the circle — the 90° nearest the anchor is what's replaced by- * the two straight tangent segments that meet at the sharp corner.- *- * The previous shape was a symmetric, free-floating teardrop with a flat rectangular "neck" — it- * didn't sit flush against anything, so next to the highlight band it read as two balloons stuck- * onto a separate bar rather than the band's own corner drawn out into a handle.- */-internal fun DrawScope.drawTextSelectionHandle(- anchor: Offset,- diameter: Float,- isLeftHandle: Boolean,- color: Color = Color(0xFF4285F4)-) {- val r = diameter * 0.5f- // +1 for the left handle (circle bulges right, into the selection), -1 for the right handle- // (circle bulges left, into the selection).- val sign = if (isLeftHandle) 1f else -1f- val center = Offset(anchor.x + sign * r, anchor.y + r)- val bottomTangent = Offset(anchor.x, anchor.y + r) // straight down from the anchor- // Sweeping the long way (270°, away from the anchor-facing quadrant) from `bottomTangent` back- // to the anchor's other tangent point (straight sideways from it) — direction flips with- // handedness since the circle sits on the opposite side.- val startAngleDeg = if (isLeftHandle) 180f else 0f- val sweepDeg = if (isLeftHandle) -270f else 270f-- val path = Path().apply {- moveTo(anchor.x, anchor.y)- lineTo(bottomTangent.x, bottomTangent.y)- arcTo(- rect = Rect(center.x - r, center.y - r, center.x + r, center.y + r),- startAngleDegrees = startAngleDeg,- sweepAngleDegrees = sweepDeg,- forceMoveTo = false- )- lineTo(anchor.x, anchor.y)- close()- }- drawPath(path, color)-}--internal fun OcrTextBlock.wordRangeAtPoint(point: Offset, frame: Rect): OcrTextRange? {- val blockRect = ocrBlockToRect(this, frame)- if (!Rect(blockRect.left - 6f, blockRect.top - 6f, blockRect.right + 6f, blockRect.bottom + 6f).contains(point)) return null- val word = wordRanges().minByOrNull { word ->- val wordRect = ocrTextRangeToRect(this, OcrTextRange(id, word.first, word.last + 1), frame)- val dx = when {- point.x < wordRect.left -> wordRect.left - point.x- point.x > wordRect.right -> point.x - wordRect.right- else -> 0f- }- val dy = when {- point.y < wordRect.top -> wordRect.top - point.y- point.y > wordRect.bottom -> point.y - wordRect.bottom- else -> 0f- }- dx * dx + dy * dy- } ?: return null- return OcrTextRange(id, word.first, word.last + 1)-}--internal fun hitTestOcrBlock(blocks: List<OcrTextBlock>, contentPoint: Offset, frame: Rect): OcrTextBlock? {- return blocks.firstOrNull { b ->- val r = ocrBlockToRect(b, frame)- val expanded = Rect(r.left - 4f, r.top - 4f, r.right + 4f, r.bottom + 4f)- expanded.contains(contentPoint)- }-}--internal fun hitTestOcrWord(blocks: List<OcrTextBlock>, contentPoint: Offset, frame: Rect): OcrTextRange? =- blocks.firstNotNullOfOrNull { it.wordRangeAtPoint(contentPoint, frame) }--internal fun intersects(a: Rect, b: Rect): Boolean =- a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top--/**- * The contiguous run of words between two content points, **in reading order** — a real text- * selection rather than a rectangular marquee. Words are ordered top-to-bottom and left-to-right- * within a line (lines grouped by vertical overlap); each point snaps to its nearest word, and every- * word from the earlier position to the later one is returned. This is what lets a drag select a- * whole sentence or paragraph the way selecting text on a page should, instead of one word at a time.- */-internal fun ocrRangeBetween(- blocks: List<OcrTextBlock>,- frame: Rect,- p1: Offset,- p2: Offset-): Set<String> {- if (blocks.isEmpty()) return emptySet()- val ordered = blocks.readingOrder()- val i1 = ordered.nearestBlockIndex(frame, p1)- val i2 = ordered.nearestBlockIndex(frame, p2)- if (i1 < 0 || i2 < 0) return emptySet()- val lo = minOf(i1, i2)- val hi = maxOf(i1, i2)- return ordered.subList(lo, hi + 1).map { it.id }.toSet()-}--/** Returns a contiguous word selection, grouped back into precise ranges per PDF text line. */-internal fun ocrWordRangesBetween(- blocks: List<OcrTextBlock>,- frame: Rect,- p1: Offset,- p2: Offset-): List<OcrTextRange> {- if (blocks.isEmpty()) return emptyList()- val words = blocks.readingOrder().flatMap { block ->- block.wordRanges().map { word ->- val range = OcrTextRange(block.id, word.first, word.last + 1)- OcrWordHit(range, ocrTextRangeToRect(block, range, frame))- }- }- if (words.isEmpty()) return emptyList()- val i1 = words.nearestWordIndex(p1)- val i2 = words.nearestWordIndex(p2)- val lo = minOf(i1, i2)- val hi = maxOf(i1, i2)- return words.subList(lo, hi + 1)- .groupBy { it.range.blockId }- .values- .map { group ->- OcrTextRange(- blockId = group.first().range.blockId,- start = group.minOf { it.range.start },- end = group.maxOf { it.range.end }- )- }-}--/**- * Character-precise contiguous selection between two content points — the granularity the- * native Android text selector uses. Every extracted glyph box (per-character metrics) becomes a- * hit target; the run from the character nearest [p1] to the one nearest [p2], in reading order,- * is returned as merged per-line ranges. Falls back to word granularity for lines that expose no- * per-character metrics so selection never dead-ends.- */-internal fun ocrCharRangesBetween(- blocks: List<OcrTextBlock>,- frame: Rect,- p1: Offset,- p2: Offset-): List<OcrTextRange> {- if (blocks.isEmpty()) return emptyList()- val chars = ArrayList<OcrCharHit>()- blocks.readingOrder().forEach { block ->- val n = minOf(block.charLefts.size, block.charRights.size, block.text.length)- val top = frame.top + block.top * frame.height- val bottom = frame.top + block.bottom * frame.height- for (i in 0 until n) {- val l = frame.left + block.charLefts[i] * frame.width- val r = frame.left + block.charRights[i] * frame.width- chars.add(OcrCharHit(block.id, i, Rect(min(l, r), top, max(l, r), bottom)))- }- }- // No glyph metrics on this page (image-only OCR) → keep the proven word sweep.- if (chars.isEmpty()) return ocrWordRangesBetween(blocks, frame, p1, p2)- val i1 = chars.nearestCharIndex(p1)- val i2 = chars.nearestCharIndex(p2)- val lo = min(i1, i2)- val hi = max(i1, i2)- // Each block's glyphs are emitted contiguously, so a contiguous slice yields one clean- // [start, end) range per block — exactly what the highlight / copy models expect.- return chars.subList(lo, hi + 1)- .groupBy { it.blockId }- .map { (id, hits) -> OcrTextRange(id, hits.minOf { it.charIndex }, hits.maxOf { it.charIndex } + 1) }-}--private data class OcrCharHit(val blockId: String, val charIndex: Int, val rect: Rect)--private fun List<OcrCharHit>.nearestCharIndex(point: Offset): Int =- indices.minByOrNull { index ->- val rect = this[index].rect- val dx = when {- point.x < rect.left -> rect.left - point.x- point.x > rect.right -> point.x - rect.right- else -> 0f- }- val dy = when {- point.y < rect.top -> rect.top - point.y- point.y > rect.bottom -> point.y - rect.bottom- else -> 0f- }- dx * dx + dy * dy- } ?: 0--private data class OcrWordHit(val range: OcrTextRange, val rect: Rect)--private fun List<OcrWordHit>.nearestWordIndex(point: Offset): Int =- indices.minByOrNull { index ->- val rect = this[index].rect- val dx = when {- point.x < rect.left -> rect.left - point.x- point.x > rect.right -> point.x - rect.right- else -> 0f- }- val dy = when {- point.y < rect.top -> rect.top - point.y- point.y > rect.bottom -> point.y - rect.bottom- else -> 0f- }- dx * dx + dy * dy- } ?: 0--/** Words sorted into reading order: grouped into lines by vertical overlap, then left-to-right. */-private fun List<OcrTextBlock>.readingOrder(): List<OcrTextBlock> {- if (isEmpty()) return this- val avgH = map { it.bottom - it.top }.average().toFloat().coerceAtLeast(0.001f)- val gap = avgH * 0.6f- val lines = mutableListOf<MutableList<OcrTextBlock>>()- for (b in sortedBy { it.top }) {- val last = lines.lastOrNull()- val cy = (b.top + b.bottom) / 2f- val lastCy = last?.first()?.let { (it.top + it.bottom) / 2f }- if (last == null || lastCy == null || cy - lastCy > gap) lines.add(mutableListOf(b))- else last.add(b)- }- return lines.flatMap { line -> line.sortedBy { it.left } }-}--/** Index of the word containing [p], else the nearest word by centre distance. -1 if empty. */-private fun List<OcrTextBlock>.nearestBlockIndex(frame: Rect, p: Offset): Int {- forEachIndexed { i, b -> if (ocrBlockToRect(b, frame).contains(p)) return i }- var best = -1- var bestD = Float.MAX_VALUE- forEachIndexed { i, b ->- val r = ocrBlockToRect(b, frame)- val dx = (r.left + r.right) / 2f - p.x- val dy = (r.top + r.bottom) / 2f - p.y- val d = dx * dx + dy * dy- if (d < bestD) { bestD = d; best = i }- }- return best-}-internal fun distToSegment(p: Offset, a: Offset, b: Offset): Float {val l2 = (b - a).getDistanceSq()if (l2 == 0f) return (p - a).getDistance()diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerScreen.ktindex 7d810d8..bd99c66 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerScreen.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerScreen.kt@@ -1,6 +1,8 @@package com.chethan616.clearpdf.ui.screenimport android.app.Activity+import android.content.Intent+import androidx.compose.runtime.mutableIntStateOfimport android.graphics.Bitmapimport androidx.activity.compose.BackHandlerimport androidx.activity.compose.rememberLauncherForActivityResult@@ -128,6 +130,20 @@ import com.chethan616.clearpdf.ui.theme.LocalIsDarkModeimport com.chethan616.clearpdf.ui.utils.rememberUISensorimport com.chethan616.clearpdf.ui.viewmodel.PdfViewerViewModelimport com.chethan616.clearpdf.ui.viewmodel.OcrTextRange+import com.chethan616.clearpdf.ui.selection.PdfCopiedToast+import com.chethan616.clearpdf.ui.selection.PdfSelectionActions+import com.chethan616.clearpdf.ui.selection.PdfSelectionHandles+import com.chethan616.clearpdf.ui.selection.PdfSelectionToolbar+import com.chethan616.clearpdf.ui.selection.PdfTextSelectionState+import com.chethan616.clearpdf.ui.selection.PdfViewportTransform+import com.chethan616.clearpdf.ui.selection.TextPos+import com.chethan616.clearpdf.ui.selection.pdfTextSelectionGestures+import com.chethan616.clearpdf.ui.selection.rememberSelectionAutoScroller+import androidx.compose.ui.hapticfeedback.HapticFeedbackType+import androidx.compose.ui.platform.LocalHapticFeedback+import androidx.compose.ui.layout.onGloballyPositioned+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.withTimeoutOrNullimport com.kyant.backdrop.backdrops.LayerBackdropimport com.kyant.backdrop.backdrops.layerBackdropimport com.kyant.backdrop.backdrops.rememberLayerBackdrop@@ -227,9 +243,6 @@ fun PdfViewerScreen(fun getPageMarks(page: Int): MutableList<PdfMarkup> =annotationsByPage.getOrPut(page) { mutableStateListOf() }- fun selectedTextRanges(page: Int): List<OcrTextRange> =- state.selectedOcrRangesByPage[page].orEmpty()-// Undo history: the page each added markup landed on, newest last. Undo pops the most recent// entry and removes THAT page's last mark, so "undo" means the last thing the user actually// did. The old behaviour removed the last mark of `listState.firstVisibleItemIndex`, which is@@ -242,6 +255,23 @@ fun PdfViewerScreen(// annotations onto whichever page is under the viewport centre.val listState = rememberLazyListState()+ // ── Text selection (long-press, native-style handles, glass toolbar) ─────────────────────+ val textSelection = remember { PdfTextSelectionState() }+ textSelection.blocksProvider = { p -> viewModel.uiState.value.ocrBlocksByPage[p].orEmpty() }+ var containerWidthPx by remember { mutableIntStateOf(0) }+ textSelection.transformProvider = { PdfViewportTransform(containerWidthPx.toFloat(), scale, offsetX) }+ val selectionAutoScroller = rememberSelectionAutoScroller(listState, textSelection)+ selectionAutoScroller.panBy = { dx ->+ val cw = containerWidthPx.toFloat()+ val maxOffsetX = ((cw * scale - cw) / 2f).coerceAtLeast(0f)+ val next = (offsetX + dx).coerceIn(-maxOffsetX, maxOffsetX)+ val applied = next - offsetX+ offsetX = next+ applied+ }+ var copiedTick by remember { mutableIntStateOf(0) }+ val haptics = LocalHapticFeedback.current+// iOS-style momentum for the continuous page scroll: a lower-friction exponential decay// glides longer and settles smoothly (vs the stiffer platform spline), so even 2–3 page// docs feel continuous instead of stopping abruptly. Only the fling curve changes — the@@ -393,7 +423,7 @@ fun PdfViewerScreen(activeTool = PdfEditTool.NoneselectedAnnoPage = null; selectedAnnoIndex = -1annotationsByPage.clear(); undoStack.clear(); pageCanvasSizes.clear(); pageBitmapSizes.clear()- viewModel.clearOcrSelection(state.currentPage); viewModel.clearExportFeedback()+ textSelection.resetDocument(); viewModel.clearExportFeedback()showFindBar = false; findQuery = ""; viewModel.clearSearch()}@@ -560,12 +590,11 @@ fun PdfViewerScreen(val safePageCount = state.pageCount.coerceAtLeast(1)val viewerScope = rememberCoroutineScope()val currentPageIndex = listState.firstVisibleItemIndex.coerceIn(0, safePageCount - 1)- // The bottom SelectText toolbar must act on whichever page actually holds the current OCR- // selection, not the viewport-derived currentPageIndex — otherwise scrolling after selecting- // (or the selection sitting on a page whose bottom sliver is visible, not its top) makes- // Highlight/Underline/Strike/Copy silently target the wrong page's empty selection.- val selectionPageIndex = state.selectedOcrRangesByPage.entries- .firstOrNull { it.value.isNotEmpty() }?.key ?: currentPageIndex+ // Back clears an active text selection first (registered after the viewer's own BackHandler, so+ // it takes precedence), exactly like a TextView's selection mode.+ BackHandler(enabled = textSelection.hasSelection) { textSelection.clear() }+ // Any editing tool owns the page gestures; a selection must not linger underneath it.+ LaunchedEffect(activeTool) { if (activeTool != PdfEditTool.None) textSelection.clear() }// Live backdrop that captures the ACTUAL rendered page column (dark bg + PDF// pages), so the glass chrome reflects real content instead of the static@@ -768,16 +797,27 @@ fun PdfViewerScreen(Box(Modifier.fillMaxSize()- .onSizeChanged { containerHeightPx = it.height }+ .onSizeChanged { containerHeightPx = it.height; containerWidthPx = it.width }+ // Long-press → select word. First in the chain so, once it fires, it can consume+ // in the Initial pass ahead of the zoom/tap handlers and the page list.+ .pdfTextSelectionGestures(+ state = textSelection,+ autoScroller = selectionAutoScroller,+ haptics = haptics,+ enabled = { activeTool == PdfEditTool.None },+ onSelectionStarted = { lastInteractionAtMs = System.currentTimeMillis() }+ ).then(// Keep pinch zoom available in Select Text mode. Other editing tools own// the page gesture surface because their strokes/shapes need the drag.- if (activeTool != PdfEditTool.None && activeTool != PdfEditTool.SelectText) Modifier+ if (activeTool != PdfEditTool.None) Modifierelse Modifier.pointerInput(Unit) {awaitEachGesture {awaitFirstDown(requireUnconsumed = false)do {val event = awaitPointerEvent()+ // A selection drag owns the finger: no one-finger pan underneath it.+ if (textSelection.gestureActive) continueval zoomChange = event.calculateZoom()val panChange = event.calculatePan()val zoomed = scale > 1.001f@@ -816,7 +856,13 @@ fun PdfViewerScreen().pointerInput(activeTool) {detectTapGestures(- onTap = { if (activeTool == PdfEditTool.None) controlsVisible = !controlsVisible; lastInteractionAtMs = System.currentTimeMillis() },+ onTap = {+ // Tap outside clears a text selection (and does nothing else), like a+ // TextView; otherwise it toggles the reading chrome.+ if (textSelection.hasSelection) textSelection.clear()+ else if (activeTool == PdfEditTool.None) controlsVisible = !controlsVisible+ lastInteractionAtMs = System.currentTimeMillis()+ },onDoubleTap = { tap ->if (activeTool != PdfEditTool.None) return@detectTapGesturesval cw = size.width.toFloat()@@ -848,7 +894,7 @@ fun PdfViewerScreen(scaleX = scale; scaleY = scaletranslationX = offsetX; translationY = 0ftransformOrigin = androidx.compose.ui.graphics.TransformOrigin(0.5f, 0f)- }+ }.onGloballyPositioned { textSelection.registerLayer(it) }) {LazyColumn(state = listState,@@ -874,8 +920,6 @@ fun PdfViewerScreen(bitmap = state.pageBitmaps.getOrNull(page),marks = getPageMarks(page),ocrBlocks = state.ocrBlocksByPage[page].orEmpty(),- selectedOcrIds = state.selectedOcrBlockIdsByPage[page].orEmpty(),- selectedOcrRanges = state.selectedOcrRangesByPage[page].orEmpty(),findMatches = state.findMatches,currentMatchIndex = state.currentMatchIndex,showFindBar = showFindBar,@@ -891,10 +935,6 @@ fun PdfViewerScreen(onShowControls = { controlsVisible = true },onActiveToolChanged = { activeTool = it },onActiveImageIdChanged = { activeImageId = it },- onClearOcrSelection = { viewModel.clearOcrSelection(page) },- // Replace (not append): a drag defines the whole selection live, so as- // the finger shrinks the range the deselected words must drop out too.- onSelectOcrRange = { viewModel.selectOcrRanges(page, it, append = false) },onPlaceText = { pt ->val id = System.nanoTime()getPageMarks(page).add(PdfMarkup.TextBoxMarkup(id, pt, "", currentColor, 40f))@@ -933,56 +973,13 @@ fun PdfViewerScreen(selectedMarkupIndex = if (page == selectedAnnoPage) selectedAnnoIndex else -1,onSelectMarkup = { idx ->if (idx < 0) { selectedAnnoPage = null; selectedAnnoIndex = -1 }- else { selectedAnnoPage = page; selectedAnnoIndex = idx }+ else { selectedAnnoPage = page; selectedAnnoIndex = idx; textSelection.clear() }},onDeleteMarkup = { idx ->val m = getPageMarks(page); if (idx in m.indices) m.removeAt(idx)selectedAnnoPage = null; selectedAnnoIndex = -1},- onCopySelection = {- viewModel.getSelectedOcrText(page).takeIf { it.isNotBlank() }- ?.let { clipboard.setText(AnnotatedString(it)) }- lastInteractionAtMs = System.currentTimeMillis()- },- onHighlightSelection = {- val m = getPageMarks(page)- selectedTextRanges(page).forEach { range ->- // Recolor semantics: drop any highlight already covering this exact- // range so a re-tap replaces the colour instead of stacking layers.- m.removeAll { it is PdfMarkup.TextBlockHighlightMarkup && it.blockId == range.blockId && it.start == range.start && it.end == range.end }- m.add(PdfMarkup.TextBlockHighlightMarkup(range.blockId, Color(currentColorLong), 0.38f, range.start, range.end))- recordEdit(page)- }- // Keep the selection live so the pill immediately offers Recolor / Delete —- // this is the fix for "after highlighting there's no delete option".- lastInteractionAtMs = System.currentTimeMillis()- },- onUnderlineSelection = {- val m = getPageMarks(page)- selectedTextRanges(page).forEach { range ->- if (!m.any { it is PdfMarkup.TextBlockLineMarkup && it.blockId == range.blockId && it.start == range.start && it.end == range.end && !it.strikeThrough }) {- m.add(PdfMarkup.TextBlockLineMarkup(range.blockId, Color(currentColorLong), 3f, 1f, false, range.start, range.end))- recordEdit(page)- }- }- lastInteractionAtMs = System.currentTimeMillis()- },- onStrikeSelection = {- val m = getPageMarks(page)- selectedTextRanges(page).forEach { range ->- if (!m.any { it is PdfMarkup.TextBlockLineMarkup && it.blockId == range.blockId && it.start == range.start && it.end == range.end && it.strikeThrough }) {- m.add(PdfMarkup.TextBlockLineMarkup(range.blockId, Color(currentColorLong), 3f, 1f, true, range.start, range.end))- recordEdit(page)- }- }- lastInteractionAtMs = System.currentTimeMillis()- },- onSetColorLong = { currentColorLong = it },- onSelectAll = {- val ids = state.ocrBlocksByPage[page].orEmpty().map { it.id }.toSet()- if (ids.isNotEmpty()) viewModel.selectOcrBlocks(page, ids, append = false)- lastInteractionAtMs = System.currentTimeMillis()- }+ textSelection = textSelection)}}@@ -990,6 +987,13 @@ fun PdfViewerScreen(}}+ // ── Text-selection handles + magnifier (outside the zoom layer: fixed on-screen size) ──+ PdfSelectionHandles(+ state = textSelection,+ listState = listState,+ autoScroller = selectionAutoScroller+ )+// ── Page scrubber (doubles as the fading scroll indicator) ─────────// Always present on multi-page docs so fast scrubbing is one drag away,// independent of the auto-hiding chrome. It brightens the moment the list@@ -1111,8 +1115,6 @@ fun PdfViewerScreen(exportError = state.exportError,exportMessage = state.exportMessage,lastExportedUri = state.lastExportedUri,- selectedTextCount = selectedTextRanges(currentPageIndex).size,- currentSelectedIds = state.selectedOcrBlockIdsByPage[currentPageIndex].orEmpty(),activeIsSignature = activeItem?.isSignature == true,// Undo is history-driven, not page-driven. Two earlier attempts keyed it to a// page index — first `state.currentPage` (async, lagged behind the scroll), then@@ -1123,7 +1125,7 @@ fun PdfViewerScreen(canUndo = undoStack.isNotEmpty() || annotationsByPage.any { it.value.isNotEmpty() },onUndo = { undoLastEdit(); lastInteractionAtMs = System.currentTimeMillis() },onClearPage = { clearVisiblePage(); lastInteractionAtMs = System.currentTimeMillis() },- onSetActiveTool = { activeTool = it; if (it == PdfEditTool.None) activeImageId = null; selectedAnnoPage = null; selectedAnnoIndex = -1; viewModel.clearOcrSelection(currentPageIndex) },+ onSetActiveTool = { activeTool = it; if (it == PdfEditTool.None) activeImageId = null; selectedAnnoPage = null; selectedAnnoIndex = -1; textSelection.clear() },onToggleFindBar = {showFindBar = !showFindBarif (showFindBar) viewModel.triggerOcrForAllPages(context)@@ -1143,39 +1145,6 @@ fun PdfViewerScreen(activeImageLoc()?.let { (pg, idx, _) -> getPageMarks(pg).removeAt(idx) }activeImageId = null; activeTool = PdfEditTool.None},- onSelectAllText = {- val ids = state.ocrBlocksByPage[currentPageIndex].orEmpty().map { it.id }.toSet()- if (ids.isNotEmpty()) viewModel.selectOcrBlocks(currentPageIndex, ids, false)- },- onCopyText = {- viewModel.getSelectedOcrText(selectionPageIndex).takeIf { it.isNotBlank() }- ?.let { clipboard.setText(AnnotatedString(it)) }- },- onHighlightSelected = {- val m = getPageMarks(selectionPageIndex)- selectedTextRanges(selectionPageIndex).forEach { range ->- if (!m.any { it is PdfMarkup.TextBlockHighlightMarkup && it.blockId == range.blockId && it.start == range.start && it.end == range.end })- m.add(PdfMarkup.TextBlockHighlightMarkup(range.blockId, Color(currentColorLong), 0.38f, range.start, range.end))- recordEdit(selectionPageIndex)- }- },- onUnderlineSelected = {- val m = getPageMarks(selectionPageIndex)- selectedTextRanges(selectionPageIndex).forEach { range ->- if (!m.any { it is PdfMarkup.TextBlockLineMarkup && it.blockId == range.blockId && it.start == range.start && it.end == range.end && !it.strikeThrough })- m.add(PdfMarkup.TextBlockLineMarkup(range.blockId, Color(currentColorLong), 3f, 1f, false, range.start, range.end))- recordEdit(selectionPageIndex)- }- },- onStrikeSelected = {- val m = getPageMarks(selectionPageIndex)- selectedTextRanges(selectionPageIndex).forEach { range ->- if (!m.any { it is PdfMarkup.TextBlockLineMarkup && it.blockId == range.blockId && it.start == range.start && it.end == range.end && it.strikeThrough })- m.add(PdfMarkup.TextBlockLineMarkup(range.blockId, Color(currentColorLong), 3f, 1f, true, range.start, range.end))- recordEdit(selectionPageIndex)- }- },- onClearTextSelection = { viewModel.clearOcrSelection(selectionPageIndex) },onSetColorLong = { currentColorLong = it },onSetStrokeWidth = { currentStrokeWidth = it },onDismissExportFeedback = { viewModel.clearExportFeedback() },@@ -1234,6 +1203,138 @@ fun PdfViewerScreen()}+ // ── Floating liquid-glass selection toolbar (above the chrome, like the platform's) ──+ suspend fun selectionTextLoaded(): String {+ val span = textSelection.pageSpan() ?: return ""+ val missing = span.any { it !in viewModel.uiState.value.ocrBlocksByPage }+ if (missing) {+ viewModel.triggerOcrForAllPages(context)+ withTimeoutOrNull(10_000) {+ viewModel.uiState.first { st -> span.all { it in st.ocrBlocksByPage } }+ }+ }+ return textSelection.selectedText()+ }+ fun startSafely(intent: Intent) {+ runCatching {+ if (context !is Activity) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ context.startActivity(intent)+ }+ }+ fun applyToSelection(block: (page: Int, marks: MutableList<PdfMarkup>, range: OcrTextRange) -> Boolean) {+ textSelection.rangesByPage().forEach { (page, ranges) ->+ val marks = getPageMarks(page)+ var changed = false+ ranges.forEach { r -> if (block(page, marks, r)) changed = true }+ if (changed) recordEdit(page)+ }+ lastInteractionAtMs = System.currentTimeMillis()+ }+ val selectionActions = PdfSelectionActions(+ onCopy = {+ viewerScope.launch {+ val t = selectionTextLoaded()+ if (t.isNotBlank()) {+ clipboard.setText(AnnotatedString(t))+ haptics.performHapticFeedback(HapticFeedbackType.Confirm)+ copiedTick+++ }+ textSelection.clear()+ }+ },+ onSelectAll = {+ // The whole document. Pages whose text is not extracted yet join the highlight as+ // they load (the end caret is clamped per page).+ viewModel.triggerOcrForAllPages(context)+ textSelection.select(TextPos(0, 0), TextPos(safePageCount - 1, Int.MAX_VALUE))+ },+ onShare = {+ viewerScope.launch {+ val t = selectionTextLoaded()+ if (t.isNotBlank()) {+ startSafely(Intent.createChooser(+ Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, t), null+ ))+ }+ textSelection.clear()+ }+ },+ onHighlight = { colorLong ->+ currentColorLong = colorLong+ applyToSelection { _, m, r ->+ // Re-highlighting replaces (recolours) highlights inside the range instead of stacking.+ m.removeAll { it is PdfMarkup.TextBlockHighlightMarkup && it.blockId == r.blockId && it.start >= r.start && it.end <= r.end }+ m.add(PdfMarkup.TextBlockHighlightMarkup(r.blockId, Color(colorLong), 0.38f, r.start, r.end))+ true+ }+ textSelection.clear()+ },+ onUnderline = {+ applyToSelection { _, m, r ->+ if (m.any { it is PdfMarkup.TextBlockLineMarkup && it.blockId == r.blockId && it.start == r.start && it.end == r.end && !it.strikeThrough }) false+ else m.add(PdfMarkup.TextBlockLineMarkup(r.blockId, Color(currentColorLong), 3f, 1f, false, r.start, r.end))+ }+ textSelection.clear()+ },+ onStrike = {+ applyToSelection { _, m, r ->+ if (m.any { it is PdfMarkup.TextBlockLineMarkup && it.blockId == r.blockId && it.start == r.start && it.end == r.end && it.strikeThrough }) false+ else m.add(PdfMarkup.TextBlockLineMarkup(r.blockId, Color(currentColorLong), 3f, 1f, true, r.start, r.end))+ }+ textSelection.clear()+ },+ onRemoveHighlight = {+ textSelection.rangesByPage().forEach { (page, ranges) ->+ getPageMarks(page).removeAll { m ->+ m is PdfMarkup.TextBlockHighlightMarkup && ranges.any { r -> r.blockId == m.blockId && m.start < r.end && m.end > r.start }+ }+ }+ textSelection.clear()+ },+ onSearch = {+ val q = textSelection.selectedText().replace(Regex("\\s+"), " ").trim().take(80)+ textSelection.clear()+ if (q.isNotEmpty()) {+ showFindBar = true+ findQuery = q+ viewModel.triggerOcrForAllPages(context)+ viewModel.searchText(q)+ }+ },+ onProcessText = { component ->+ viewerScope.launch {+ val t = selectionTextLoaded()+ if (t.isNotBlank()) {+ startSafely(+ Intent(Intent.ACTION_PROCESS_TEXT)+ .setComponent(component)+ .setType("text/plain")+ .putExtra(Intent.EXTRA_PROCESS_TEXT, t)+ .putExtra(Intent.EXTRA_PROCESS_TEXT_READONLY, true)+ )+ }+ }+ }+ )+ val hasHighlightOverlap = textSelection.hasSelection && textSelection.rangesByPage().any { (page, ranges) ->+ annotationsByPage[page].orEmpty().any { m ->+ m is PdfMarkup.TextBlockHighlightMarkup && ranges.any { r -> r.blockId == m.blockId && m.start < r.end && m.end > r.start }+ }+ }+ PdfSelectionToolbar(+ state = textSelection,+ listState = listState,+ backdrop = contentBackdrop,+ actions = selectionActions,+ highlightColor = currentColor,+ hasHighlightOverlap = hasHighlightOverlap+ )+ PdfCopiedToast(+ trigger = copiedTick,+ backdrop = contentBackdrop,+ modifier = Modifier.align(Alignment.BottomCenter).navigationBarsPadding().padding(bottom = 112.dp)+ )+// ── Page-jump popup (in-window, so it samples the liquid-glass backdrop) ──LiquidPageJumpPopup(visible = showPageJumpDialog,diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfSelectionOverlay.kt b/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfSelectionOverlay.ktindex b4e5203..565dacd 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfSelectionOverlay.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfSelectionOverlay.kt@@ -21,6 +21,7 @@ import androidx.compose.runtime.withFrameNanosimport androidx.compose.ui.Modifierimport androidx.compose.ui.geometry.Offsetimport androidx.compose.ui.geometry.Size+import androidx.compose.ui.geometry.isSpecifiedimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.Pathimport androidx.compose.ui.graphics.drawscope.DrawScopediff --git a/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfSelectionToolbar.kt b/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfSelectionToolbar.ktindex 4b661fe..35df187 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfSelectionToolbar.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfSelectionToolbar.kt@@ -323,7 +323,7 @@ fun PdfSelectionToolbar(val screenH = constraints.maxHeight.toFloat()val screenW = constraints.maxWidth.toFloat()val rects = state.selectionScreenRects()- val union = rects.takeIf { it.isNotEmpty() }?.reduce { a, b -> a.union(b) }+ val union = rects.takeIf { it.isNotEmpty() }?.reduce { a, b -> Rect(minOf(a.left, b.left), minOf(a.top, b.top), maxOf(a.right, b.right), maxOf(a.bottom, b.bottom)) }val visible = union?.takeIf { it.bottom > 0f && it.top < screenH }?.let { Rect(it.left, it.top.coerceAtLeast(0f), it.right, it.bottom.coerceAtMost(screenH)) }if (visible != null) lastBounds[0] = visiblediff --git a/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfTextSelectionState.kt b/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfTextSelectionState.ktindex 1640462..6690fc5 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfTextSelectionState.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfTextSelectionState.kt@@ -2,7 +2,6 @@ package com.chethan616.clearpdf.ui.selectionimport androidx.compose.runtime.Stableimport androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableFloatStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.setValueimport androidx.compose.ui.geometry.Offset@@ -59,11 +58,12 @@ class PdfTextSelectionState {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)+ /**+ * Current zoom/pan. A provider rather than a stored value so every reader (draw, layout, gesture)+ * reads the viewer's live `scale`/`offsetX` snapshot state directly and is invalidated by it.+ */+ var transformProvider: () -> PdfViewportTransform = { PdfViewportTransform(0f, 1f, 0f) }+ val transform: PdfViewportTransform get() = transformProvider()var blocksProvider: (Int) -> List<OcrTextBlock> = { emptyList() }