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.

feat: v1.2.0 — text selection, decrypt animation, onboarding polish, crash fix

Chethan61667f1b9aeda8b
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 1ffedf9..1013ce3 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -38,8 +38,8 @@ android {
applicationId = "com.chethan616.clearpdf"
minSdk = 23
targetSdk = 36
- versionCode = 2
- versionName = "1.1.0"
+ versionCode = 3
+ versionName = "1.2.0"
// Keep every locale declared by the app. Filtering this to English
// removes values-pt-rBR from the packaged APK, so the language picker
// can appear to work while the app continues to resolve English.
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/components/DecryptingAnimation.kt b/app/src/main/java/com/chethan616/clearpdf/ui/components/DecryptingAnimation.kt
new file mode 100644
index 0000000..e54efbd
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/components/DecryptingAnimation.kt
@@ -0,0 +1,132 @@
+package com.chethan616.clearpdf.ui.components
+
+import androidx.compose.animation.core.FastOutSlowInEasing
+import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.animation.core.tween
+import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableFloatStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.geometry.CornerRadius
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Size
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.StrokeCap
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.util.lerp
+import com.kyant.backdrop.Backdrop
+import com.kyant.shapes.RoundedRectangle
+import kotlinx.coroutines.delay
+
+/**
+ * The "decrypting" animation: a **blue liquid-glass** document whose encrypted lines resolve as a
+ * scan beam sweeps down it, in the flat self-drawing style of the onboarding page-5 demos
+ * (`DemoAnnotate`'s signature stroking itself) — NOT the page-6 glass-disc medallion.
+ *
+ * The panel is a real [viewerGlass] surface tinted blue, so it refracts the wallpaper [backdrop] like
+ * the rest of the app's chrome; on top of it each line is faint until the beam reaches it, then it
+ * fills in solid **left-to-right** (drawn, not faded). Runs the demos' rise → hold → reset → gap loop
+ * so it reads as a repeating demonstration for as long as the decrypt is in flight.
+ */
+@Composable
+fun DecryptingAnimation(
+ backdrop: Backdrop,
+ modifier: Modifier = Modifier
+) {
+ // The blue glass tint and the two ink strengths the lines resolve between.
+ val blueGlass = Color(0xFF1E6BFF).copy(alpha = 0.34f)
+ val encrypted = Color.White.copy(alpha = 0.22f)
+ val decrypted = Color(0xFFEAF3FF)
+ val beam = Color(0xFF9AD0FF)
+
+ // Same cadence as rememberDemoLoop: lead-in, decrypt (rise) → hold on the finished page → reset
+ // (re-lock) → short gap → repeat. Reset-and-replay is exactly how DemoAnnotate loops.
+ var target by remember { mutableFloatStateOf(0f) }
+ LaunchedEffect(Unit) {
+ delay(220)
+ while (true) {
+ target = 1f
+ delay(1500) // scan down + dwell on the decrypted page
+ target = 0f
+ delay(520) // re-lock gap
+ }
+ }
+ val p by animateFloatAsState(target, tween(1050, easing = FastOutSlowInEasing), label = "decryptScan")
+
+ Box(
+ modifier
+ .size(width = 176.dp, height = 132.dp)
+ .viewerGlass(backdrop, blueGlass, shape = { RoundedRectangle(20f.dp) })
+ ) {
+ Canvas(Modifier.fillMaxSize().padding(horizontal = 22.dp, vertical = 22.dp)) {
+ val w = size.width
+ val h = size.height
+ val barH = 6.dp.toPx()
+ val radius = CornerRadius(barH / 2f, barH / 2f)
+
+ // The document's lines: (vertical fraction, width fraction), varied like real text.
+ val lines = listOf(
+ 0.02f to 0.55f, // a short "heading"
+ 0.22f to 1.00f,
+ 0.40f to 0.82f,
+ 0.58f to 0.95f,
+ 0.76f to 0.66f,
+ 0.94f to 0.88f
+ )
+
+ // The beam sweeps from just above the first line to just past the last, so every line is
+ // fully resolved before the dwell.
+ val scanY = lerp(-0.06f * h, 1.10f * h, p)
+ val band = 0.18f * h // how far ahead of the beam a line begins resolving
+
+ lines.forEach { (fy, fw) ->
+ val y = fy * h
+ val full = w * fw
+ // Encrypted (base) bar — always present, faint.
+ drawRoundRect(
+ color = encrypted,
+ topLeft = Offset(0f, y),
+ size = Size(full, barH),
+ cornerRadius = radius
+ )
+ // Decrypted fill: grows to full width as the beam passes — a left-to-right "draw".
+ val reveal = ((scanY - y + band) / band).coerceIn(0f, 1f)
+ if (reveal > 0f) {
+ drawRoundRect(
+ color = decrypted,
+ topLeft = Offset(0f, y),
+ size = Size(full * reveal, barH),
+ cornerRadius = radius
+ )
+ }
+ }
+
+ // The scan beam — a bright rule with a soft trail above it (where it has just decrypted).
+ // Hidden during the dwell/reset, when it's off the page.
+ if (scanY in 0f..h) {
+ val trail = 0.16f * h
+ val top = (scanY - trail).coerceAtLeast(0f)
+ drawRect(
+ color = beam.copy(alpha = 0.16f),
+ topLeft = Offset(0f, top),
+ size = Size(w, scanY - top)
+ )
+ drawLine(
+ color = beam,
+ start = Offset(0f, scanY),
+ end = Offset(w, scanY),
+ strokeWidth = 2f.dp.toPx(),
+ cap = StrokeCap.Round
+ )
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/components/OnboardingDemos.kt b/app/src/main/java/com/chethan616/clearpdf/ui/components/OnboardingDemos.kt
index 3b73796..da2ec5f 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/components/OnboardingDemos.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/components/OnboardingDemos.kt
@@ -1,11 +1,14 @@
package com.chethan616.clearpdf.ui.components
+import androidx.compose.animation.Crossfade
+import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
+import androidx.compose.ui.graphics.lerp as lerpColor
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
@@ -49,6 +52,7 @@ import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@@ -204,12 +208,11 @@ fun DemoDocumentOpen(isActive: Boolean, backdrop: Backdrop, glass: Color, ink: C
progress.animateTo(1f, tween(2200, easing = LinearEasing))
}
- // Once assembled, the book settles into PDF red — the app's primary format, the one the six
- // flying sheets resolve into — instead of the neutral frost it wore before. Blended off the
- // theme glass so it stays a translucent surface rather than a flat red card; the text lines
- // pick up the same red so the page reads as one coloured object.
- val bookGlass = androidx.compose.ui.graphics.lerp(glass, LiquidGlassColors.Red, 0.30f)
- val bookInk = LiquidGlassColors.Red
+ // The assembled book stays neutral glass so the CONTENT can carry the colour: each of its lines
+ // is tinted by one of the six formats that flew in, in the same order they landed, so the book
+ // visibly reads as "made of" the PDF/DOC/XLS/PPT/IMG/TXT sheets that assembled it rather than
+ // collapsing to a single red.
+ val bookGlass = glass
Box(
Modifier
@@ -268,15 +271,21 @@ fun DemoDocumentOpen(isActive: Boolean, backdrop: Backdrop, glass: Color, ink: C
scaleX = s
scaleY = s
}
- .viewerGlass(backdrop, bookGlass, shape = { RoundedRectangle(16f.dp) })
+ // withShadow = false: this book is the one surface on page 1, and its drop shadow used
+ // to snap in the instant the assembled book reached full opacity. Page 1 shows no
+ // shadow at all now — see [viewerGlass]'s `withShadow`.
+ .viewerGlass(backdrop, bookGlass, shape = { RoundedRectangle(16f.dp) }, withShadow = false)
.padding(horizontal = 15.dp, vertical = 17.dp),
contentAlignment = Alignment.TopStart
) {
// Content arrives once the book has: the last beat, so the sequence ends on something
- // legible rather than on the stack merely stopping.
+ // legible rather than on the stack merely stopping. Each line wears the colour of the
+ // format sheet at its position — in [DemoKinds] order — so the finished book carries all
+ // six colours that formed it, laid down one after another.
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
val widths = listOf(0.85f, 1f, 0.72f, 0.94f, 0.6f, 0.88f, 0.45f)
widths.forEachIndexed { idx, w ->
+ val lineTint = DemoKinds[idx % DemoKinds.size].tint
Box(
Modifier
.fillMaxWidth(w)
@@ -291,7 +300,7 @@ fun DemoDocumentOpen(isActive: Boolean, backdrop: Backdrop, glass: Color, ink: C
scaleX = t
}
.clip(RoundedCornerShape(3.dp))
- .background(bookInk.copy(if (idx == 0) 0.55f else 0.28f))
+ .background(lineTint.copy(if (idx == 0) 0.85f else 0.62f))
)
}
}
@@ -334,77 +343,110 @@ private fun OrbitSheet(tint: Color, modifier: Modifier) {
// ── Page 3 · Open anything ──────────────────────────────────────────────────────────────────────
/**
- * "Open anything", restyled to match page 5's feature panel: one `viewerGlass` panel holding a column
- * of rows, each a coloured icon tile beside the format name and its file extensions — the same
- * leading-visual + title + subtext rhythm [FeatureRows] uses, rather than the old bare grid of chips.
+ * "Open anything" as ONE liquid-glass document that becomes each format in turn, rather than a static
+ * list of rows. A single [viewerGlass] card holds a big format icon, the format name and its
+ * extensions, and a few tinted "content" lines — and it cross-fades from PDF → Word → Excel → PPT →
+ * Image on a loop, the whole card re-tinting toward each format's colour as it goes. It reads as the
+ * same reader opening anything you hand it, which is the promise the page is making, and it does it
+ * with the app's real glass instead of a generic chip grid.
*
- * Rows cascade in on [EaseOutBack] with a per-index stagger (draw-time only — the panel behind never
- * re-measures). Names reuse the localized recents category strings; extensions are literal, so this
- * adds no translated copy.
+ * One glass surface (not five), so it costs a single blur+lens pass; only the flat inner content
+ * cross-fades. Names reuse the localized recents category strings; extensions are literal.
*/
@Composable
fun DemoFileKinds(isActive: Boolean, backdrop: Backdrop, glass: Color, ink: Color, inkSoft: Color) {
- val p = rememberDemoLoop(isActive, riseMs = 760, holdMs = 1500L)
-
- data class KindRow(val icon: ImageVector, val tint: Color, val name: String, val ext: String)
- val rows = listOf(
- KindRow(Icons.Rounded.PictureAsPdf, LiquidGlassColors.Red, stringResource(R.string.recents_filter_pdf), ".pdf"),
- KindRow(Icons.Rounded.Description, LiquidGlassColors.Blue, stringResource(R.string.recents_filter_word), ".doc · .docx"),
- KindRow(Icons.Rounded.GridOn, LiquidGlassColors.Green, stringResource(R.string.recents_filter_excel), ".xls · .xlsx"),
- KindRow(Icons.Rounded.Slideshow, LiquidGlassColors.Orange, stringResource(R.string.recents_filter_ppt), ".ppt · .pptx"),
- KindRow(Icons.Rounded.Image, LiquidGlassColors.Purple, stringResource(R.string.recents_filter_image), ".jpg · .png")
+ data class KindCard(val icon: ImageVector, val tint: Color, val name: String, val ext: String)
+ val cards = listOf(
+ KindCard(Icons.Rounded.PictureAsPdf, LiquidGlassColors.Red, stringResource(R.string.recents_filter_pdf), ".pdf"),
+ KindCard(Icons.Rounded.Description, LiquidGlassColors.Blue, stringResource(R.string.recents_filter_word), ".doc · .docx"),
+ KindCard(Icons.Rounded.GridOn, LiquidGlassColors.Green, stringResource(R.string.recents_filter_excel), ".xls · .xlsx"),
+ KindCard(Icons.Rounded.Slideshow, LiquidGlassColors.Orange, stringResource(R.string.recents_filter_ppt), ".ppt · .pptx"),
+ KindCard(Icons.Rounded.Image, LiquidGlassColors.Purple, stringResource(R.string.recents_filter_image), ".jpg · .png")
+ )
+
+ // Advance the format on a dwell loop; reset to the first when the page is left so it always opens
+ // on PDF. Gated on `isActive` like every other demo — see the file header.
+ var index by remember { mutableIntStateOf(0) }
+ LaunchedEffect(isActive) {
+ if (!isActive) { index = 0; return@LaunchedEffect }
+ delay(500)
+ while (true) {
+ delay(1500)
+ index = (index + 1) % cards.size
+ }
+ }
+ val current = cards[index]
+
+ // The card tint eases toward the active format's colour, so the glass itself carries the change
+ // even between the content cross-fades. A soft blend, so it stays glass rather than a colour swatch.
+ val cardTint by animateColorAsState(
+ lerpColor(glass, current.tint, 0.16f),
+ tween(560, easing = FastOutSlowInEasing),
+ label = "fileCardTint"
)
Column(
Modifier
- .fillMaxWidth()
- .viewerGlass(backdrop, glass, shape = { RoundedRectangle(28f.dp) })
- .padding(vertical = 14.dp, horizontal = 16.dp),
- verticalArrangement = Arrangement.spacedBy(12.dp)
+ .width(212.dp)
+ .viewerGlass(backdrop, cardTint, shape = { RoundedRectangle(26f.dp) })
+ .padding(22.dp),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(16.dp)
) {
- rows.forEachIndexed { index, kind ->
- // One shared clock, re-mapped per row for the stagger — same as the tile cascade, but on
- // full rows. Draw-time (alpha / translation / scale) only.
- val head = index * 0.10f
- val local = ((p - head) / (1f - head).coerceAtLeast(0.001f)).coerceIn(0f, 1f)
- val eased = EaseOutBack.transform(local)
- Row(
- Modifier
- .fillMaxWidth()
- .graphicsLayer {
- alpha = local
- translationX = lerp(16f, 0f, eased) * density
- },
- verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.spacedBy(14.dp)
+ // The whole inner content cross-fades as one, so the icon, the name and the tinted lines all
+ // turn over together. The glass card behind is outside the fade and never re-measures.
+ Crossfade(
+ targetState = index,
+ animationSpec = tween(460, easing = FastOutSlowInEasing),
+ label = "fileKind"
+ ) { i ->
+ val k = cards[i]
+ Column(
+ Modifier.fillMaxWidth(),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(14.dp)
) {
Box(
Modifier
- .size(44.dp)
- .graphicsLayer {
- val s = lerp(0.86f, 1f, eased)
- scaleX = s; scaleY = s
- }
- .clip(RoundedCornerShape(13.dp))
- .background(kind.tint.copy(0.90f)),
+ .size(76.dp)
+ .clip(RoundedCornerShape(22.dp))
+ .background(k.tint.copy(0.92f)),
contentAlignment = Alignment.Center
) {
- Icon(kind.icon, null, Modifier.size(23.dp), Color.White)
+ Icon(k.icon, null, Modifier.size(40.dp), Color.White)
}
- Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
+ Column(
+ Modifier.fillMaxWidth(),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(3.dp)
+ ) {
BasicText(
- kind.name,
- style = TextStyle(ink, 15.sp, fontWeight = FontWeight.SemiBold),
- maxLines = 1,
- overflow = TextOverflow.Ellipsis
+ k.name,
+ style = TextStyle(ink, 19.sp, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center)
)
BasicText(
- kind.ext,
- style = TextStyle(inkSoft, 12.5.sp),
+ k.ext,
+ style = TextStyle(inkSoft, 13.sp, textAlign = TextAlign.Center),
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
+ // A few "content" lines in the format's own colour, so the card reads as a document of
+ // that kind rather than just an icon.
+ Column(
+ Modifier.fillMaxWidth().padding(top = 2.dp),
+ verticalArrangement = Arrangement.spacedBy(7.dp)
+ ) {
+ listOf(1f, 0.82f, 0.92f, 0.6f).forEach { w ->
+ Box(
+ Modifier
+ .fillMaxWidth(w)
+ .height(5.dp)
+ .clip(RoundedCornerShape(3.dp))
+ .background(k.tint.copy(0.45f))
+ )
+ }
+ }
}
}
}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/components/ViewerGlass.kt b/app/src/main/java/com/chethan616/clearpdf/ui/components/ViewerGlass.kt
index 348cae2..344f350 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/components/ViewerGlass.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/components/ViewerGlass.kt
@@ -46,7 +46,10 @@ val ViewerGlassShape: Shape = RoundedRectangle(28f.dp)
fun Modifier.viewerGlass(
backdrop: Backdrop,
color: Color,
- shape: () -> Shape = { ViewerGlassShape }
+ shape: () -> Shape = { ViewerGlassShape },
+ // Off for surfaces that must NOT cast a drop shadow — e.g. the onboarding page-1 book, whose
+ // shadow otherwise snapped in the moment the assembled book reached full opacity.
+ withShadow: Boolean = true
): Modifier = drawBackdrop(
backdrop = backdrop,
shape = shape,
@@ -55,6 +58,7 @@ fun Modifier.viewerGlass(
blur(2f.dp.toPx())
lens(12f.dp.toPx(), 24f.dp.toPx())
},
+ shadow = if (withShadow) ({ com.kyant.backdrop.shadow.Shadow.Default }) else null,
onDrawSurface = { drawRect(color) }
)
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/HomeScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/HomeScreen.kt
index 8c6b5c8..c94f720 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/HomeScreen.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/HomeScreen.kt
@@ -756,6 +756,13 @@ private fun Transition<Boolean>.entranceModifier(index: Int, density: Float): Mo
return Modifier.graphicsLayer {
this.alpha = alpha
translationY = offsetY * density
+ // Modulate alpha per draw-op instead of compositing to an offscreen buffer. The glass panels
+ // carry a soft `drawBackdrop` shadow that extends BEYOND their bounds; an offscreen layer
+ // (the default when alpha < 1) clips that overspill, so the shadow stayed invisible through
+ // the whole fade and then snapped in at full strength the instant alpha reached 1 and the
+ // offscreen switched off. Modulating avoids the buffer entirely, so the shadow fades in with
+ // its container — the way the Tools screen's panels already come in.
+ compositingStrategy = androidx.compose.ui.graphics.CompositingStrategy.ModulateAlpha
}
}
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.kt
index 3d06b4f..3b2a6fe 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
@@ -508,18 +508,24 @@ internal fun PdfContinuousPage(
onTap = { p -> val h = hitTestOcrBlock(ocrBlocks, p, frame); if (h != null) onToggleOcrSelection(h.id) else onClearOcrSelection(); onInteraction() }
)
}
+ // Direct drag (no long-press wait): in Select Text mode the page doesn't scroll, so a
+ // drag is free to mean "sweep a selection". It selects the contiguous run of words
+ // between the finger's start and its current position, in reading order, and updates
+ // LIVE as you drag — so pulling across a line or a paragraph highlights every word it
+ // crosses instead of the tap's one-word-at-a-time. A plain tap has no drag slop, so
+ // tap / double-tap / long-press above still fire for single word / line / paragraph.
.pointerInput(page, ocrBlocks) {
- detectDragGesturesAfterLongPress(
- onDragStart = { p -> selDragStart = p; selDragEnd = p; onInteraction() },
- onDrag = { ch, _ -> ch.consume(); selDragEnd = ch.position; onInteraction() },
+ 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())
+ onSelectOcrRange(ocrRangeBetween(ocrBlocks, frame, s, e))
+ }
+ detectDragGestures(
+ onDragStart = { p -> selDragStart = p; selDragEnd = p; updateRange(); onInteraction() },
+ onDrag = { ch, _ -> ch.consume(); selDragEnd = ch.position; updateRange(); onInteraction() },
onDragCancel = { selDragStart = null; selDragEnd = null },
- onDragEnd = {
- val s = selDragStart; val e = selDragEnd; selDragStart = null; selDragEnd = null
- if (s == null || e == null || ocrBlocks.isEmpty()) return@detectDragGesturesAfterLongPress
- val frame = Rect(0f, 0f, size.width.toFloat(), size.height.toFloat())
- val marquee = Rect(min(s.x, e.x), min(s.y, e.y), max(s.x, e.x), max(s.y, e.y))
- onSelectOcrRange(ocrBlocks.filter { intersects(marquee, ocrBlockToRect(it, frame)) }.map { it.id }.toSet())
- }
+ onDragEnd = { selDragStart = null; selDragEnd = null }
)
}
)
@@ -536,9 +542,16 @@ internal fun PdfContinuousPage(
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) { 44.dp.toPx() }
- val bubbleWpx = with(density) { 150.dp.toPx() }
+ val bubbleWpx = with(density) { (if (selectionHasHighlight) 226.dp else 150.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))
@@ -563,13 +576,29 @@ internal fun PdfContinuousPage(
)
Box(Modifier.width(1.dp).height(20.dp).background(Color.White.copy(0.14f)))
BasicText(
- "Highlight",
+ if (selectionHasHighlight) "Recolor" else "Highlight",
style = TextStyle(Color(0xFFFFCC33), 13.sp, FontWeight.SemiBold),
modifier = Modifier
.clip(RoundedCornerShape(18.dp))
.clickable { onHighlightSelection() }
.padding(horizontal = 16.dp, vertical = 9.dp)
)
+ if (selectionHasHighlight) {
+ Box(Modifier.width(1.dp).height(20.dp).background(Color.White.copy(0.14f)))
+ BasicText(
+ "Delete",
+ style = TextStyle(Color(0xFFFF6B6B), 13.sp, FontWeight.SemiBold),
+ modifier = Modifier
+ .clip(RoundedCornerShape(18.dp))
+ .clickable {
+ // Drop every highlight sitting on a selected word, then clear the
+ // selection so the pill dismisses.
+ marks.removeAll { it is PdfMarkup.TextBlockHighlightMarkup && it.blockId in selectedOcrIds }
+ onClearOcrSelection()
+ }
+ .padding(horizontal = 16.dp, vertical = 9.dp)
+ )
+ }
}
}
}
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.kt
index 4174fc5..62b0088 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
@@ -81,6 +81,7 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.chethan616.clearpdf.R
import com.chethan616.clearpdf.ui.components.CloseCrossIcon
+import com.chethan616.clearpdf.ui.components.GlassMotion
import com.chethan616.clearpdf.ui.components.LiquidButton
import com.chethan616.clearpdf.ui.components.LiquidIconButton
import com.chethan616.clearpdf.ui.components.ShareMorphButton
@@ -212,7 +213,11 @@ internal fun PdfViewerBottomToolbar(
var shareActive by remember { mutableStateOf(false) }
val toolCompress by animateFloatAsState(
if (shareActive) 0.84f else 1f,
- spring(dampingRatio = 0.9f, stiffness = Spring.StiffnessMediumLow),
+ // Bounce, matching the share capsule's own morph — both now run on GlassMotion.morph(), so the
+ // pill springs shut (and back open) with the same weight the cylinder has instead of deflating
+ // limply beside it. Safe to overshoot because this drives `scaleX`, a DRAW-time property: no
+ // per-frame re-measure of the glass, unlike a width/height spring (see GlassMotion's KDoc).
+ GlassMotion.morph(),
label = "toolCompress"
)
// Tell the viewer when the Editor Tools panel is open so it won't auto-hide the chrome.
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.kt
index 543d3a6..812aa1c 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
@@ -298,6 +298,60 @@ internal fun hitTestOcrBlock(blocks: List<OcrTextBlock>, contentPoint: Offset, f
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()
+}
+
+/** 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.kt
index d6bf95b..80746eb 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
@@ -71,7 +71,6 @@ import androidx.compose.material.icons.rounded.ArrowBackIosNew
import androidx.compose.material.icons.rounded.PictureAsPdf
import androidx.compose.material.icons.rounded.Search
import androidx.compose.material.icons.rounded.UploadFile
-import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
@@ -115,6 +114,7 @@ import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import com.chethan616.clearpdf.R
import com.chethan616.clearpdf.data.repository.AppSettingsManager
+import com.chethan616.clearpdf.ui.components.DecryptingAnimation
import com.chethan616.clearpdf.ui.components.LiquidButton
import com.chethan616.clearpdf.ui.components.GlassTitlePill
import com.chethan616.clearpdf.ui.components.LiquidIconButton
@@ -422,7 +422,17 @@ fun PdfViewerScreen(
// below until the first page is rendered, so the swap between these two branches is seamless.
val openingHandedDoc = !askingPassword && state.errorMessage == null && (state.isLoading || pendingLoad)
if (openingHandedDoc) {
- ViewerLoadingCurtain(isLight = isLight)
+ Box(Modifier.fillMaxSize()) {
+ ViewerLoadingCurtain(isLight = isLight)
+ // While a password PDF is actually being unlocked, play the padlock "decrypting"
+ // animation over the fill (styled after the onboarding page-5 demos). Plain opening
+ // fills (a normal load) show nothing extra — a lock would be misleading there.
+ if (state.decrypting) {
+ Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
+ DecryptingAnimation(backdrop = backdrop)
+ }
+ }
+ }
return
}
// The password prompt is an OVERLAY on this Box, not a third row inside the Column below.
@@ -845,7 +855,9 @@ fun PdfViewerScreen(
onClearOcrSelection = { viewModel.clearOcrSelection(page) },
onSelectLine = { viewModel.selectLine(page, it) },
onSelectParagraph = { viewModel.selectParagraph(page, it) },
- onSelectOcrRange = { viewModel.selectOcrBlocks(page, it, append = true) },
+ // 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.selectOcrBlocks(page, it, append = false) },
onPlaceText = { pt ->
val id = System.nanoTime()
getPageMarks(page).add(PdfMarkup.TextBoxMarkup(id, pt, "", currentColor, 40f))
@@ -1378,24 +1390,17 @@ fun PdfViewerScreen(
}
/**
- * The plain dark "opening" screen shown while a document loads — a solid fill plus a single centred
- * spinner. Deliberately opaque (no wallpaper behind) and identical in both the no-document branch and
- * the loaded viewer's fade-out overlay, so the moment the document arrives and the branches swap the
- * user sees no seam: the same spinner keeps spinning, then dissolves to reveal the first page.
+ * A plain opaque fill shown while a handed-in document loads — no spinner, no indicator, nothing to
+ * look at. It exists only so that (a) the "Open a PDF" picker never flashes before the pages arrive,
+ * and (b) the loaded viewer can fade in from behind it. It's identical in the no-document branch and
+ * the loaded overlay, so the branch swap is seamless; when the first page is ready the overlay simply
+ * fades out (see the AnimatedVisibility that hosts it) to reveal the PDF. That fade is the whole
+ * "opening" animation — deliberately just a dissolve.
*/
@Composable
private fun ViewerLoadingCurtain(isLight: Boolean) {
val bg = if (isLight) Color(0xFF0A0E14) else Color(0xFF05070B)
- Box(
- Modifier.fillMaxSize().background(bg),
- contentAlignment = Alignment.Center
- ) {
- CircularProgressIndicator(
- color = Color(0xFF1976D2),
- strokeWidth = 2.5.dp,
- modifier = Modifier.size(34.dp)
- )
- }
+ Box(Modifier.fillMaxSize().background(bg))
}
/**
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 b2d8c14..bdb4e25 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
@@ -32,6 +32,8 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
@@ -128,6 +130,10 @@ data class PdfViewerUiState(
val pageCount: Int = 0,
val currentPage: Int = 0,
val isLoading: Boolean = false,
+ // True while a password-protected PDF is being unlocked + loaded, so the viewer can show the
+ // padlock "decrypting" animation instead of the plain opening fill. Cleared on every terminal
+ // outcome (opened / wrong password / error).
+ val decrypting: Boolean = false,
val errorMessage: String? = null,
val passwordRequired: Boolean = false,
val passwordAttemptFailed: Boolean = false,
@@ -160,6 +166,12 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
private val renderedPageWidths = mutableMapOf<Int, Int>()
private val textLoadingPages = mutableSetOf<Int>()
+ // Text extraction loads the ENTIRE document with PdfBox per page (PdfTextService.extractPage), so
+ // several pages extracting at once — the eager first-pages pass, or a fast scroll — stack multiple
+ // full-document copies in RAM and can OOM a large / decrypted PDF. This serializes them to one at a
+ // time, capping the peak to a single in-flight copy. Pages still extract lazily; they just queue.
+ private val textExtractionMutex = Mutex()
+
private val textService = PdfServiceLocator.pdfTextService
companion object {
@@ -176,6 +188,8 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
textLoadingPages.clear()
_uiState.value = _uiState.value.copy(
isLoading = true,
+ // A supplied password means this call is the actual unlock → drive the decrypt animation.
+ decrypting = password != null,
errorMessage = null,
document = null,
pageBitmaps = emptyList(),
@@ -215,6 +229,7 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
pageCount = doc.pageCount,
currentPage = 0,
isLoading = false,
+ decrypting = false,
passwordRequired = false,
passwordAttemptFailed = false,
passwordUri = null,
@@ -264,6 +279,7 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
} catch (e: PdfSecurityService.PasswordRequiredException) {
_uiState.value = _uiState.value.copy(
isLoading = false,
+ decrypting = false,
passwordRequired = true,
passwordAttemptFailed = password != null,
passwordUri = uri,
@@ -272,6 +288,7 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
} catch (_: Exception) {
_uiState.value = _uiState.value.copy(
isLoading = false,
+ decrypting = false,
errorMessage = context.getString(R.string.viewer_open_failed)
)
}
@@ -345,7 +362,10 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
viewModelScope.launch {
try {
val bitmap = withContext(AppDispatchers.pdf) {
- openPdfUseCase.renderPage(doc, pageIndex, renderWidth)
+ // Guard the whole render — a large page can OOM (an Error, not an Exception), and
+ // this coroutine has only a finally, so an uncaught throwable here crashed the app
+ // mid-scroll. Returning null instead just leaves the page as a spinner placeholder.
+ runCatching { openPdfUseCase.renderPage(doc, pageIndex, renderWidth) }.getOrNull()
}
val currentState = _uiState.value
if (currentState.document?.uri != documentUri) return@launch
@@ -387,9 +407,12 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
viewModelScope.launch {
val blocks = withContext(Dispatchers.IO) {
- runCatching {
- textService.extractPage(context, doc.uri, pageIndex)
- }.getOrElse { emptyList() }
+ // One full-document PdfBox parse at a time — see [textExtractionMutex].
+ textExtractionMutex.withLock {
+ runCatching {
+ textService.extractPage(context, doc.uri, pageIndex)
+ }.getOrElse { emptyList() }
+ }
}
val current = _uiState.value
if (current.document?.uri != doc.uri) {
diff --git a/pdf-core/src/main/java/com/kyant/pdfcore/viewer/PdfViewer.kt b/pdf-core/src/main/java/com/kyant/pdfcore/viewer/PdfViewer.kt
index bc78b62..25cf588 100644
--- a/pdf-core/src/main/java/com/kyant/pdfcore/viewer/PdfViewer.kt
+++ b/pdf-core/src/main/java/com/kyant/pdfcore/viewer/PdfViewer.kt
@@ -81,7 +81,14 @@ class PdfViewerImpl : PdfViewer {
val renderer = renderers[document.uri] ?: return null
if (pageIndex < 0 || pageIndex >= renderer.pageCount) return null
- val page = renderer.openPage(pageIndex)
+ // `openPage` is a native call that can fail on a page some producers (e.g. a PdfBox-
+ // decrypted copy) emit in a form pdfium dislikes; treat any failure as "no bitmap".
+ val page = try {
+ renderer.openPage(pageIndex)
+ } catch (t: Throwable) {
+ return@withLock null
+ }
+ var bitmap: Bitmap? = null
try {
val rotation = ((rotationDegrees % 360) + 360) % 360
val swap = rotation == 90 || rotation == 270
@@ -95,7 +102,7 @@ class PdfViewerImpl : PdfViewer {
val targetW = width.coerceAtLeast(1)
val targetH = (targetW * (dispH / dispW)).toInt().coerceAtLeast(1)
- val bitmap = Bitmap.createBitmap(targetW, targetH, Bitmap.Config.ARGB_8888)
+ bitmap = Bitmap.createBitmap(targetW, targetH, Bitmap.Config.ARGB_8888)
bitmap.eraseColor(android.graphics.Color.WHITE)
// Map the source page into the (possibly rotated) target bitmap.
@@ -115,7 +122,12 @@ class PdfViewerImpl : PdfViewer {
page.render(bitmap, null, matrix, android.graphics.pdf.PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
bitmap
- } catch (e: Exception) {
+ } catch (t: Throwable) {
+ // Catch Throwable, not just Exception: a large page can throw OutOfMemoryError from
+ // Bitmap.createBitmap, which is an Error — the old `catch (Exception)` let it escape and
+ // crash the app mid-scroll (worst on big / decrypted PDFs). Free any partial bitmap so a
+ // failed render doesn't itself leak the memory that caused the failure.
+ bitmap?.recycle()
null
} finally {
runCatching { page.close() }