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
Reader: highlight-group delete, trim-not-wipe partial highlight removal, markup bar motion
Chethan6168b32c1c64471
diff --git a/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt b/app/src/main/java/com/chethan616/clearpdf/MainActivity.ktindex 719e95d..c74be0e 100644--- a/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt+++ b/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt@@ -29,6 +29,13 @@ class MainActivity : ComponentActivity() {enableEdgeToEdge()super.onCreate(savedInstanceState)WindowCompat.setDecorFitsSystemWindows(window, false)+ // Belt-and-suspenders against the translucent scrim Android can draw behind the nav bar+ // (API 29-34; reported as a "grey band" around it on some OEM skins/Android versions even+ // with enableEdgeToEdge()). The app paints its own full-bleed background in every screen,+ // so that scrim is never needed and only ever shows as a seam.+ if (Build.VERSION.SDK_INT in Build.VERSION_CODES.Q..Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {+ window.isNavigationBarContrastEnforced = false+ }// A locale change restarts this Activity. DocsApp animates both halves of that restart, so// the system's own cross-fade would just stack on top of ours.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 986ac26..b3f4b80 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@@ -19,6 +19,7 @@ import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPressimport androidx.compose.foundation.gestures.detectTapGesturesimport androidx.compose.foundation.gestures.waitForUpOrCancellationimport androidx.compose.foundation.horizontalScroll+import androidx.compose.foundation.interaction.collectIsPressedAsStateimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Row@@ -759,9 +760,12 @@ private val MarkupBarHeight = 48.dp/*** Contextual Edit / Delete / dismiss capsule for a selected markup (shape, text box, note, text- * highlight/underline/strike). Same frosted material and theme ink as the selection toolbar and the- * dialogs, instead of the old near-opaque dark slab with hard-coded English labels. Dismissal also- * works by tapping anywhere else in the viewer or pressing Back.+ * highlight/underline/strike). Clear chrome glass — pure refraction, like the bottom toolbar's own+ * circles and [com.chethan616.clearpdf.ui.components.ShareMorphButton]'s idle state — instead of a+ * dialog-weight platter, since this floats over the document the same way that chrome does. The+ * entrance is the same family of spring ShareMorph uses: a real overshoot on scale (not clamped away)+ * while alpha stays critically damped, so it springs in with actual weight instead of a flat fade.+ * Dismissal also works by tapping anywhere else in the viewer or pressing Back.*/@Composableprivate fun MarkupActionBar(@@ -777,25 +781,29 @@ private fun MarkupActionBar(val haptics = androidx.compose.ui.platform.LocalHapticFeedback.currentvar shown by remember { mutableStateOf(false) }LaunchedEffect(Unit) { shown = true }- val pop by androidx.compose.animation.core.animateFloatAsState(+ // Alpha settles critically damped (a bouncing alpha reads as a flicker, per GlassMotion's own+ // rule); scale is left to overshoot past 1 and spring back — the actual "pop" ShareMorph has.+ val alpha by androidx.compose.animation.core.animateFloatAsState(if (shown) 1f else 0f,+ com.chethan616.clearpdf.ui.components.GlassMotion.fade(),+ label = "markupBarAlpha"+ )+ val scale by androidx.compose.animation.core.animateFloatAsState(+ if (shown) 1f else 0.72f,com.chethan616.clearpdf.ui.components.GlassMotion.pop(),- label = "markupBarPop"+ label = "markupBarScale")Row(modifier.width(MarkupBarWidth).height(MarkupBarHeight).graphicsLayer {- alpha = pop.coerceIn(0f, 1f)- val sc = 0.9f + 0.1f * pop- scaleX = sc; scaleY = sc+ this.alpha = alpha.coerceIn(0f, 1f)+ scaleX = scale; scaleY = scale}- .viewerGlass(- backdrop,- com.chethan616.clearpdf.ui.components.glassDialogSurface(isDark),- shape = { com.kyant.shapes.Capsule }- )+ // Clear glass: only the backdrop refraction + lens carry the material, same as the+ // toolbar's own circles. A tinted/opaque fill here is what read as "not liquid glass".+ .viewerGlass(backdrop, Color.Transparent, shape = { com.kyant.shapes.Capsule }).padding(horizontal = 4.dp),verticalAlignment = Alignment.CenterVertically) {@@ -809,37 +817,44 @@ private fun MarkupActionBar(onDelete()}Box(Modifier.width(1.dp).height(22.dp).background(ink.copy(0.12f)))- Box(- Modifier- .size(40.dp)- .clip(CircleShape)- .clickable(onClick = onDismiss),- contentAlignment = Alignment.Center- ) {- Icon(Icons.Rounded.Close, stringResource(R.string.done), Modifier.size(18.dp), ink.copy(0.85f))+ MarkupBarItem(Icons.Rounded.Close, stringResource(R.string.done), ink.copy(0.85f), Modifier.width(44.dp), iconOnly = true) {+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.ContextClick)+ onDismiss()}}}+/** One pill of [MarkupActionBar]: presses down and springs back, like [LiquidButton]'s deformation —+ * the old plain `clickable` had no press feedback at all, the one thing that most read as "not a+ * real button" next to ShareMorph and the rest of the toolbar. */@Composableprivate fun MarkupBarItem(icon: androidx.compose.ui.graphics.vector.ImageVector,label: String,color: Color,modifier: Modifier = Modifier,+ iconOnly: Boolean = false,onClick: () -> Unit) {+ val interaction = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }+ val pressed by interaction.collectIsPressedAsState()+ val press by androidx.compose.animation.core.animateFloatAsState(+ if (pressed) com.chethan616.clearpdf.ui.components.GlassMotion.PressedScale else 1f,+ com.chethan616.clearpdf.ui.components.GlassMotion.press(),+ label = "markupItemPress"+ )Row(modifier.fillMaxHeight().padding(vertical = 4.dp)+ .graphicsLayer { scaleX = press; scaleY = press }.clip(com.kyant.shapes.Capsule)- .clickable(onClick = onClick)- .padding(horizontal = 8.dp),- verticalAlignment = Alignment.CenterVertically,- horizontalArrangement = Arrangement.spacedBy(6.dp, Alignment.CenterHorizontally)+ .clickable(interactionSource = interaction, indication = null, onClick = onClick)+ .padding(horizontal = if (iconOnly) 0.dp else 8.dp),+ horizontalArrangement = Arrangement.spacedBy(6.dp, Alignment.CenterHorizontally),+ verticalAlignment = Alignment.CenterVertically) {- Icon(icon, null, Modifier.size(17.dp), color)- BasicText(label, style = TextStyle(color, 14.sp, FontWeight.SemiBold), maxLines = 1)+ Icon(icon, if (iconOnly) label else null, Modifier.size(17.dp), color)+ if (!iconOnly) BasicText(label, style = TextStyle(color, 14.sp, FontWeight.SemiBold), maxLines = 1)}}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 b1c7d57..0555ca0 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@@ -72,7 +72,15 @@ internal sealed class PdfMarkup {val color: Color,val alpha: Float = 0.30f,val start: Int = 0,- val end: Int = -1+ val end: Int = -1,+ // One highlight gesture over a multi-line / multi-sentence selection produces one of+ // these PER LINE (the text layout breaks the selection at line boundaries), so a single+ // "highlight this paragraph" tap created several sibling markups sharing no link back to+ // each other. Tapping any one of them to delete it only ever removed that one line, which+ // read as "deletes a word, not the group I selected" for anything spanning more than one+ // line. All siblings created by the same [applyToSelection] call share this id (0L = none,+ // only ever produced by code predating this field); deleting one deletes the whole id.+ val groupId: Long = 0L) : PdfMarkup()data class TextBlockLineMarkup(@@ -82,7 +90,9 @@ internal sealed class PdfMarkup {val alpha: Float = 1f,val strikeThrough: Boolean = false,val start: Int = 0,- val end: Int = -1+ val end: Int = -1,+ /** See [TextBlockHighlightMarkup.groupId]. */+ val groupId: Long = 0L) : PdfMarkup()data class ImageMarkup(@@ -135,8 +145,7 @@ internal sealed class PdfMarkup {}is TextBoxMarkup -> {val lines = if (text.isEmpty()) 1 else text.split("\n").size- val w = (text.split("\n").maxOfOrNull { it.length } ?: 1).coerceAtLeast(1) * fontSize * 0.6f- val r = Rect(position.x - 6f, position.y - 6f, position.x + w + 6f, position.y + fontSize * 1.2f * lines + 6f)+ val r = Rect(position.x - 6f, position.y - 6f, position.x + measuredTextWidth() + 6f, position.y + fontSize * 1.2f * lines + 6f)r.contains(p)}is NoteMarkup -> {@@ -163,6 +172,25 @@ internal fun PdfMarkup.isTransformable(): Boolean = this is PdfMarkup.StrokeMark/** Whether a bottom-right resize handle applies (notes are a fixed-size icon → move only). */internal fun PdfMarkup.isResizable(): Boolean = isTransformable() && this !is PdfMarkup.NoteMarkup+/**+ * Real glyph-measured width of a [PdfMarkup.TextBoxMarkup]'s widest line at its current font size,+ * instead of the old `charCount * fontSize * 0.6` guess. That guess was reused by [hitTest] and+ * [movableBounds] to place BOTH the selection outline and the bottom-right resize handle — an+ * estimate that drifts further from the real rendered glyphs as [PdfMarkup.TextBoxMarkup.fontSize]+ * grows (narrow vs. wide character mixes, non-Latin scripts), so a resize drag's handle hit test+ * raced ahead of or behind the finger and the selection frame visibly swam away from the text being+ * resized — reported as "the text moves while resizing" (#48).+ */+private fun PdfMarkup.TextBoxMarkup.measuredTextWidth(): Float {+ val paint = cachedTextBoxPaint+ paint.textSize = fontSize+ val lines = if (text.isEmpty()) listOf("") else text.split("\n")+ return (lines.maxOfOrNull { paint.measureText(it) } ?: 0f).coerceAtLeast(fontSize * 1.2f)+}++/** One reusable [android.graphics.Paint] for text measurement — avoids allocating one per call. */+private val cachedTextBoxPaint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG)+/** Content-space bounding box used for the selection frame + hit-testing during transform. */internal fun PdfMarkup.movableBounds(): Rect? = when (this) {is PdfMarkup.StrokeMarkup -> {@@ -178,8 +206,7 @@ internal fun PdfMarkup.movableBounds(): Rect? = when (this) {is PdfMarkup.ImageMarkup -> Rect(min(start.x, end.x), min(start.y, end.y), max(start.x, end.x), max(start.y, end.y))is PdfMarkup.TextBoxMarkup -> {val lines = if (text.isEmpty()) 1 else text.split("\n").size- val w = ((text.split("\n").maxOfOrNull { it.length } ?: 1).coerceAtLeast(3)) * fontSize * 0.6f- Rect(position.x, position.y, position.x + w, position.y + fontSize * 1.2f * lines)+ Rect(position.x, position.y, position.x + measuredTextWidth(), position.y + fontSize * 1.2f * lines)}is PdfMarkup.NoteMarkup -> Rect(anchor.x, anchor.y, anchor.x + 30f, anchor.y + 30f)else -> null@@ -277,7 +304,11 @@ internal fun PdfMarkup.resizedBy(drag: Offset, bounds: Rect): PdfMarkup = when (copy(points = points.map { pivot + (it - pivot) * f })}is PdfMarkup.TextBoxMarkup -> {- val factor = ((bounds.height + drag.y) / bounds.height.coerceAtLeast(1f)).coerceIn(0.3f, 6f)+ // Half-sensitivity: at a typical ~48px line height, an ordinary 15-20px per-event drag+ // used to read as a 30-40% font-size jump in one frame — "cumbersome" (#48). A fast swipe+ // still reaches the same range over a few frames; it just no longer overshoots on the first one.+ val dampedDrag = drag.y * 0.5f+ val factor = ((bounds.height + dampedDrag) / bounds.height.coerceAtLeast(1f)).coerceIn(0.3f, 6f)copy(fontSize = (fontSize * factor).coerceIn(10f, 400f))}else -> thisdiff --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 d73a91a..4786ce6 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@@ -78,6 +78,7 @@ import androidx.compose.material.icons.rounded.ArrowBackIosNewimport androidx.compose.material.icons.rounded.PictureAsPdfimport androidx.compose.material.icons.rounded.Searchimport androidx.compose.material.icons.rounded.DarkMode+import androidx.compose.material.icons.rounded.Deleteimport androidx.compose.material.icons.rounded.LightModeimport androidx.compose.material.icons.rounded.UploadFileimport androidx.compose.material.icons.rounded.Edit@@ -1189,7 +1190,32 @@ fun PdfViewerScreen(}},onDeleteMarkup = { idx ->- val m = getPageMarks(page); if (idx in m.indices) m.removeAt(idx)+ val m = getPageMarks(page)+ val target = m.getOrNull(idx)+ // A highlight/underline/strike over a multi-line selection is+ // several sibling markups (one per line) stamped with the same+ // groupId when they were created. Deleting one must delete the+ // whole passage, on every page it touches, or tapping the ONE+ // line under your finger only ever "deleted a word" out of the+ // paragraph you actually selected.+ val groupId = when (target) {+ is PdfMarkup.TextBlockHighlightMarkup -> target.groupId+ is PdfMarkup.TextBlockLineMarkup -> target.groupId+ else -> 0L+ }+ if (groupId != 0L) {+ annotationsByPage.keys.toList().forEach { pg ->+ val pageMarks = getPageMarks(pg)+ val before = pageMarks.size+ pageMarks.removeAll { mk ->+ (mk is PdfMarkup.TextBlockHighlightMarkup && mk.groupId == groupId) ||+ (mk is PdfMarkup.TextBlockLineMarkup && mk.groupId == groupId)+ }+ if (pageMarks.size != before) recordEdit(pg)+ }+ } else if (idx in m.indices) {+ m.removeAt(idx)+ }selectedAnnoPage = null; selectedAnnoIndex = -1selectedMarkupGroupPage = null; selectedMarkupGroup = emptySet()},@@ -1380,20 +1406,43 @@ fun PdfViewerScreen(exit = fadeOut(tween(120)) + scaleOut(targetScale = 0.96f),modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 88.dp)) {- LiquidButton(- onClick = {- selectedMarkupGroup = emptySet()- selectedMarkupGroupPage = null- lastInteractionAtMs = System.currentTimeMillis()- },- backdrop = contentBackdrop,- surfaceColor = chromeField- ) {- BasicText(- stringResource(R.string.viewer_lasso_selected_count, selectedMarkupGroup.size) +- " · " + stringResource(R.string.viewer_lasso_done),- style = TextStyle(bottomFg, 13.sp, fontWeight = FontWeight.SemiBold)- )+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {+ // Lasso-selecting several markups and asking to delete them was previously only+ // possible one at a time (the group pill only offered "Done"/deselect) — the same+ // "selecting a group doesn't let you delete the group" complaint as the highlight+ // groupId fix above, for the lasso tool's own multi-select.+ LiquidButton(+ onClick = {+ val page = selectedMarkupGroupPage+ if (page != null) {+ val m = getPageMarks(page)+ selectedMarkupGroup.sortedDescending().forEach { i -> if (i in m.indices) m.removeAt(i) }+ recordEdit(page)+ }+ selectedMarkupGroup = emptySet()+ selectedMarkupGroupPage = null+ lastInteractionAtMs = System.currentTimeMillis()+ },+ backdrop = contentBackdrop,+ tint = LiquidGlassColors.Red+ ) {+ Icon(Icons.Rounded.Delete, stringResource(R.string.delete), Modifier.size(16.dp), Color.White)+ }+ LiquidButton(+ onClick = {+ selectedMarkupGroup = emptySet()+ selectedMarkupGroupPage = null+ lastInteractionAtMs = System.currentTimeMillis()+ },+ backdrop = contentBackdrop,+ surfaceColor = chromeField+ ) {+ BasicText(+ stringResource(R.string.viewer_lasso_selected_count, selectedMarkupGroup.size) ++ " · " + stringResource(R.string.viewer_lasso_done),+ style = TextStyle(bottomFg, 13.sp, fontWeight = FontWeight.SemiBold)+ )+ }}}@@ -1572,8 +1621,13 @@ fun PdfViewerScreen(}fun applyToSelection(snapToWords: Boolean = false,- block: (page: Int, marks: MutableList<PdfMarkup>, range: OcrTextRange) -> Boolean+ block: (page: Int, marks: MutableList<PdfMarkup>, range: OcrTextRange, groupId: Long) -> Boolean) {+ // One id for every markup this single call creates, even across pages (a highlight can+ // span a page break) and across the several per-line markups one multi-line selection+ // becomes. Lets a later tap-to-delete remove the whole passage instead of one line of it+ // — see [PdfMarkup.TextBlockHighlightMarkup.groupId].+ val groupId = System.nanoTime()textSelection.rangesByPage().forEach { (page, ranges) ->val marks = getPageMarks(page)var changed = false@@ -1582,7 +1636,7 @@ fun PdfViewerScreen(val pageBlocks = if (snapToWords) state.ocrBlocksByPage[page].orEmpty().associateBy { it.id } else emptyMap()ranges.forEach { raw ->val r = if (snapToWords) pageBlocks[raw.blockId]?.let { raw.snappedToWords(it.text) } ?: raw else raw- if (block(page, marks, r)) changed = true+ if (block(page, marks, r, groupId)) changed = true}if (changed) recordEdit(page)}@@ -1619,33 +1673,56 @@ fun PdfViewerScreen(},onHighlight = { colorLong ->currentColorLong = colorLong- applyToSelection(snapToWords = true) { _, m, r ->+ applyToSelection(snapToWords = true) { _, m, r, groupId ->// 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))+ m.add(PdfMarkup.TextBlockHighlightMarkup(r.blockId, Color(colorLong), 0.38f, r.start, r.end, groupId))true}textSelection.clear()},onUnderline = {- applyToSelection(snapToWords = true) { _, m, r ->+ applyToSelection(snapToWords = true) { _, m, r, groupId ->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))+ else m.add(PdfMarkup.TextBlockLineMarkup(r.blockId, Color(currentColorLong), 3f, 1f, false, r.start, r.end, groupId))}textSelection.clear()},onStrike = {- applyToSelection(snapToWords = true) { _, m, r ->+ applyToSelection(snapToWords = true) { _, m, r, groupId ->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))+ else m.add(PdfMarkup.TextBlockLineMarkup(r.blockId, Color(currentColorLong), 3f, 1f, true, r.start, r.end, groupId))}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 }+ val marks = getPageMarks(page)+ var changed = false+ ranges.forEach { r ->+ // Trim, don't blanket-remove: a highlighted PARAGRAPH is one or more+ // TextBlockHighlightMarkup per line (see groupId above), and each line's own+ // markup can easily cover more than the word you then select inside it —+ // removing the whole markup on any overlap deleted the highlight off the+ // entire line for a one-word selection. Split the overlapping markup instead,+ // keeping whatever's left on either side of the removed span.+ var i = 0+ while (i < marks.size) {+ val m = marks[i] as? PdfMarkup.TextBlockHighlightMarkup+ if (m == null || m.blockId != r.blockId || m.start >= r.end || m.end <= r.start) {+ i++; continue+ }+ val replacements = buildList {+ if (m.start < r.start) add(m.copy(start = m.start, end = r.start))+ if (m.end > r.end) add(m.copy(start = r.end, end = m.end))+ }+ marks.removeAt(i)+ marks.addAll(i, replacements)+ i += replacements.size+ changed = true+ }}+ if (changed) recordEdit(page)}textSelection.clear()},