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: fluid document-lift nav transitions, theme-aware sign screen, snappier recents

Chethan616248ab198e172
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/DocsApp.kt b/app/src/main/java/com/chethan616/clearpdf/ui/DocsApp.kt
index 0511966..a932bf5 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/DocsApp.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/DocsApp.kt
@@ -64,6 +64,7 @@ import com.chethan616.clearpdf.ui.components.DocsBottomTabs
import com.chethan616.clearpdf.ui.components.LiquidButton
import com.chethan616.clearpdf.ui.components.liquidGlassPanel
import com.chethan616.clearpdf.ui.navigation.DocsNavGraph
+import com.chethan616.clearpdf.ui.navigation.ROUTE_ONBOARDING
import com.chethan616.clearpdf.ui.theme.LocalIsDarkMode
import com.chethan616.clearpdf.ui.utils.StarPromptEventBus
import com.chethan616.clearpdf.ui.utils.rememberUISensor
@@ -90,6 +91,19 @@ fun DocsApp(shortcutRoute: String? = null, incomingPdfUri: android.net.Uri? = nu
com.chethan616.clearpdf.ui.utils.LocaleHelper.getLocalizedContext(context, selectedLocale)
}
+ // Read ONCE. `setOnboardingComplete()` flips this mid-session, and re-reading it would swap the
+ // NavHost's start destination underneath a live back stack. A first launch that arrives via a
+ // share or a shortcut skips the tour and goes straight to the document — the flag is left unset,
+ // so onboarding still appears on the next ordinary cold start rather than being lost.
+ val needsOnboarding = remember {
+ !OnboardingManager.hasCompletedOnboarding(context) &&
+ shortcutRoute == null && incomingPdfUri == null
+ }
+ // The locale the Activity actually booted with. Onboarding changes `selectedLocale` in place for
+ // the flow's own strings, but the rest of the app was built by `attachBaseContext` against this
+ // one, so only a difference from *this* value justifies a restart at the end.
+ val bootLocale = remember { selectedLocale }
+
var themeMode by rememberSaveable { mutableIntStateOf(AppSettingsManager.getThemeMode(context)) }
var showWallpaper by rememberSaveable { mutableStateOf(AppSettingsManager.getShowWallpaper(context)) }
var customWallpaper by rememberSaveable { mutableStateOf(AppSettingsManager.getCustomWallpaper(context)) }
@@ -203,9 +217,10 @@ fun DocsApp(shortcutRoute: String? = null, incomingPdfUri: android.net.Uri? = nu
}
}
- // Handle app shortcut deep links
+ // Handle app shortcut deep links. Guarded on the gate so a shortcut can never fire on top of
+ // the tour — though `needsOnboarding` is already false whenever a shortcut is present.
LaunchedEffect(shortcutRoute) {
- if (shortcutRoute != null) {
+ if (shortcutRoute != null && !needsOnboarding) {
navController.navigate(shortcutRoute) { launchSingleTop = true }
}
}
@@ -300,7 +315,34 @@ fun DocsApp(shortcutRoute: String? = null, incomingPdfUri: android.net.Uri? = nu
localeSwitching = true
}
},
- incomingPdfUri = incomingPdfUri
+ incomingPdfUri = incomingPdfUri,
+ startDestination = if (needsOnboarding) ROUTE_ONBOARDING else "home",
+ // In place: persist + update the hoisted state, which re-provides LocalResources
+ // above, so every `stringResource` in the flow re-resolves. No recreate, or the
+ // tour would relaunch at page one mid-flow.
+ onOnboardingLocaleSelected = { code ->
+ val normalized = com.chethan616.clearpdf.ui.utils.LocaleHelper.normalizeForUi(code)
+ if (normalized != selectedLocale) {
+ OnboardingManager.setSelectedLocale(context, normalized)
+ selectedLocale = normalized
+ }
+ },
+ onOnboardingFinished = {
+ OnboardingManager.setOnboardingComplete(context)
+ // Only now, and only if the choice actually differs from what
+ // `attachBaseContext` built the app with, is a restart worth its cost — it
+ // is what makes non-Compose strings (toasts, notifications) follow suit.
+ if (selectedLocale != bootLocale) {
+ com.chethan616.clearpdf.ui.utils.LocaleHelper.applyLocale(
+ context = context,
+ languageTag = selectedLocale,
+ recreate = false,
+ updateAppCompat = false
+ )
+ com.chethan616.clearpdf.ui.utils.LocaleHelper.markLocaleFadePending(context)
+ localeSwitching = true
+ }
+ }
)
}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassSearchHeader.kt b/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassSearchHeader.kt
index 20ce75b..e3c24ae 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassSearchHeader.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassSearchHeader.kt
@@ -397,7 +397,10 @@ fun GlassSectionLabel(text: String, modifier: Modifier = Modifier) {
BasicText(
text.uppercase(),
style = TextStyle(
- color = LiquidGlassColors.secondary(LocalIsDarkMode.current),
+ // Full-weight ink (black in light, white in dark) rather than the grouped-list grey —
+ // the Tools section headers (Organize / Convert / Edit / Optimize / Secure) read as
+ // proper titles this way instead of fading into the wallpaper.
+ color = LiquidGlassColors.text(LocalIsDarkMode.current),
fontSize = 12.sp,
fontWeight = FontWeight.SemiBold,
letterSpacing = 0.8.sp
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassTitlePill.kt b/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassTitlePill.kt
index 3d47909..7600838 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassTitlePill.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassTitlePill.kt
@@ -64,6 +64,12 @@ fun GlassTitlePill(
modifier: Modifier = Modifier,
onClick: (() -> Unit)? = null,
surfaceColor: Color = Color.Unspecified,
+ /**
+ * Overrides the theme ink. Only the viewers need this: their chrome is picked from the *page's*
+ * luminance rather than the app theme, so on a white page in dark mode the label has to go dark
+ * while the rest of the app stays light-on-dark.
+ */
+ contentColor: Color = Color.Unspecified,
/** Only the typeface may vary — size and weight stay at the viewer's 13 sp SemiBold. */
fontFamily: FontFamily? = null,
animateIn: Boolean = true
@@ -74,6 +80,7 @@ fun GlassTitlePill(
} else {
if (isDarkMode) Color(0xFF1E1E1E).copy(0.35f) else Color(0xFFFAFAFA).copy(0.35f)
}
+ val resolvedInk = if (contentColor.isSpecified) contentColor else LiquidGlassColors.text(isDarkMode)
var shown by remember { mutableStateOf(!animateIn) }
LaunchedEffect(Unit) { shown = true }
@@ -101,7 +108,7 @@ fun GlassTitlePill(
BasicText(
text,
style = TextStyle(
- color = LiquidGlassColors.text(isDarkMode),
+ color = resolvedInk,
fontSize = 13.sp,
fontWeight = FontWeight.SemiBold,
fontFamily = fontFamily
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidBottomTabs.kt b/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidBottomTabs.kt
index 1deb939..f1da65e 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidBottomTabs.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidBottomTabs.kt
@@ -169,7 +169,12 @@ fun LiquidBottomTabs(
shape = { Capsule },
effects = {
vibrancy()
- blur(8f.dp.toPx())
+ // Half the original 8 dp. This is the tab bar's own surface only — the
+ // selection capsule below draws through `tabsBackdrop`, which keeps its
+ // own blur, so softening the bar does not soften the slider riding on it.
+ // The lens is untouched: at 24x24 it is what gives the bar its edge, and
+ // dropping the blur without it would flatten the whole capsule.
+ blur(4f.dp.toPx())
lens(24f.dp.toPx(), 24f.dp.toPx())
},
layerBlock = {
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
new file mode 100644
index 0000000..3b73796
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/components/OnboardingDemos.kt
@@ -0,0 +1,645 @@
+package com.chethan616.clearpdf.ui.components
+
+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.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.text.BasicText
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.rounded.Description
+import androidx.compose.material.icons.rounded.GridOn
+import androidx.compose.material.icons.rounded.Image
+import androidx.compose.material.icons.rounded.PictureAsPdf
+import androidx.compose.material.icons.rounded.Search
+import androidx.compose.material.icons.rounded.Slideshow
+import androidx.compose.material3.Icon
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableFloatStateOf
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.Path
+import androidx.compose.ui.graphics.PathMeasure
+import androidx.compose.ui.graphics.StrokeCap
+import androidx.compose.ui.graphics.drawscope.Stroke
+import androidx.compose.ui.graphics.graphicsLayer
+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.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import androidx.compose.ui.util.lerp
+import com.chethan616.clearpdf.R
+import com.chethan616.clearpdf.ui.theme.LiquidGlassColors
+import com.kyant.backdrop.Backdrop
+import com.kyant.shapes.Capsule
+import com.kyant.shapes.RoundedRectangle
+import kotlinx.coroutines.delay
+import kotlin.math.cos
+import kotlin.math.sin
+
+/**
+ * The live animation replays that sit on the onboarding pages.
+ *
+ * Every one of these is a **sibling** of a real component, never a modification of it. The app's
+ * production animations are gesture-driven — `ShareMorphButton` morphs off a long-press,
+ * `GlassSearchHeader` off a tap — and bolting a "demo mode" parameter onto a shipping component so
+ * onboarding can puppet it is how those components rot. Instead each replay re-uses the *same*
+ * [GlassMotion] spec and the same easing curves as the thing it is teaching, so the motion is
+ * genuinely identical even though the code is separate. The one exception is [DemoToolsMenu], which
+ * drives the real [GlassCapsuleMenu] unmodified because that component already exposes a
+ * caller-owned `progress`.
+ *
+ * **Every replay takes `isActive`.** `HorizontalPager` composes the pages either side of the current
+ * one, so without gating each loop on visibility all five demos run at once, off-screen, forever.
+ */
+
+/** Matches ToolsScreen's tile entrance — a real overshoot, on scale only. */
+private val EaseOutBack = CubicBezierEasing(0.34f, 1.56f, 0.64f, 1f)
+
+/** One file kind: the label page 3 prints on its chips, and the colour both pages carry. */
+private data class DemoKind(val label: String, val tint: Color)
+
+/**
+ * The file-kind palette, shared by page 1's orbiting sheets and page 3's chip grid so the two pages
+ * teach the same colour language rather than each inventing its own. Order follows `DocKind`'s
+ * (`utils/DocKind.kt`), and the length is deliberately [OrbitPages] — page 1 maps one kind per sheet
+ * by index, so the two must stay the same size.
+ */
+private val DemoKinds = listOf(
+ DemoKind("PDF", LiquidGlassColors.Red),
+ DemoKind("DOC", LiquidGlassColors.Blue),
+ DemoKind("XLS", LiquidGlassColors.Green),
+ DemoKind("PPT", LiquidGlassColors.Orange),
+ DemoKind("IMG", LiquidGlassColors.Purple),
+ DemoKind("TXT", LiquidGlassColors.Teal)
+)
+
+/**
+ * Drives a demo loop: returns a 0..1 float that ramps over [riseMs], holds, resets, and repeats,
+ * but only while [isActive].
+ *
+ * Uses a keyed `LaunchedEffect` + `animateFloatAsState` rather than `rememberInfiniteTransition`
+ * because these replays need a **hold** at the end of each cycle — the user has to actually see the
+ * finished state before it rewinds. An infinite transition with `RepeatMode.Restart` snaps back with
+ * no dwell, which reads as a stutter rather than a demonstration.
+ */
+@Composable
+private fun rememberDemoLoop(
+ isActive: Boolean,
+ riseMs: Int = 620,
+ holdMs: Long = 1500L,
+ gapMs: Long = 420L
+): Float {
+ var target by remember { mutableFloatStateOf(0f) }
+ LaunchedEffect(isActive) {
+ if (!isActive) { target = 0f; return@LaunchedEffect }
+ // Small lead-in so the page has settled before the demo starts playing.
+ delay(280)
+ while (true) {
+ target = 1f
+ delay(riseMs + holdMs)
+ target = 0f
+ delay(gapMs)
+ }
+ }
+ val v by animateFloatAsState(target, tween(riseMs, easing = FastOutSlowInEasing), label = "demoLoop")
+ return v
+}
+
+// ── Page 1 · Welcome ────────────────────────────────────────────────────────────────────────────
+
+/** Sheets in the orbit. Six reads as "a document's worth" without the centre turning to mush. */
+private const val OrbitPages = 6
+
+/** Radius of the loose orbit, in dp, before the vortex takes over. */
+private const val OrbitRadius = 74f
+
+private const val TwoPi = 6.2831855f
+private const val Pi = 3.1415927f
+
+/** Footprint of a single sheet, and therefore of the assembled book. */
+private val SheetW = 122.dp
+private val SheetH = 158.dp
+
+/**
+ * Smoothstep.
+ *
+ * Used in place of an `Easing` object because every phase below is a *slice* of one linear clock
+ * that each sheet re-maps for itself — an `Easing` would have to be re-transformed per sheet anyway,
+ * and as a plain function the whole trajectory stays one readable expression.
+ */
+private fun smooth(t: Float): Float {
+ val x = t.coerceIn(0f, 1f)
+ return x * x * (3f - 2f * x)
+}
+
+/** How far the assembled book has taken over from the last sheet to land. */
+private fun bookIn(p: Float): Float = ((p - 0.82f) / 0.15f).coerceIn(0f, 1f)
+
+/**
+ * Loose pages orbiting the centre, drawn into a vortex, folding as they fall, and settling into a
+ * book.
+ *
+ * **The spiral is emergent, not scripted.** There is not a single control point or keyframed path
+ * here: each sheet's radius collapses while its angular speed *climbs* (`pull²`), and those two
+ * together are what bends the trajectory inward. A constant sweep against a shrinking radius reads
+ * as a straight run at the centre; accelerating the sweep is what makes it curve. It also means the
+ * paths never cross the same way twice as the stagger shifts them, which is why the motion reads as
+ * organic rather than as six objects on rails.
+ *
+ * **Each sheet runs the same shape on its own delayed clock.** Without the per-index `head` offset
+ * all six arrive as one clump; with it the deck assembles a sheet at a time, and `depth` doubles as
+ * both the landing order and the fan offset in the settled stack, so the first to arrive ends up
+ * furthest back.
+ *
+ * The fold is `rotationY`, not a `scaleX` squeeze — the near edge has to actually foreshorten or it
+ * reads as a card being squashed rather than paper being creased. `cameraDistance` is pulled in
+ * tight to exaggerate that at this size.
+ *
+ * **Only the book is glass.** Six orbiting glass surfaces would mean six blur-and-lens passes per
+ * frame; the flying sheets are flat fills moved by `graphicsLayer`, which costs nothing, and the one
+ * glass surface arrives at the end, stationary, cross-faded over the top sheet it replaces.
+ */
+@Composable
+fun DemoDocumentOpen(isActive: Boolean, backdrop: Backdrop, glass: Color, ink: Color) {
+ val progress = remember { Animatable(0f) }
+ val fade = remember { Animatable(0f) }
+
+ // Hand-rolled rather than [rememberDemoLoop]: this demo needs a LINEAR clock, because every
+ // curve above is carved out of it by hand and a second easing on top would double-ease them.
+ //
+ // It plays ONCE and holds on the finished book — no rewind loop. Looping it would play the
+ // assembly in reverse (the book exploding back into an orbit), and the ask is a single, settled
+ // demonstration. It re-arms only when the page is left and re-entered, which this effect's
+ // `isActive` key already gives for free.
+ LaunchedEffect(isActive) {
+ if (!isActive) { fade.snapTo(0f); progress.snapTo(0f); return@LaunchedEffect }
+ delay(240)
+ fade.animateTo(1f, tween(300, easing = FastOutSlowInEasing))
+ 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
+
+ Box(
+ Modifier
+ .size(224.dp)
+ .graphicsLayer { alpha = fade.value },
+ contentAlignment = Alignment.Center
+ ) {
+ repeat(OrbitPages) { i ->
+ val depth = (OrbitPages - 1 - i).toFloat()
+ val base = (i.toFloat() / OrbitPages) * TwoPi
+ // Alternating fold direction, so the deck does not crease as one slab.
+ val dir = if (i % 2 == 0) 1f else -1f
+
+ OrbitSheet(
+ // One kind per sheet, in `DemoKinds` order — so the six formats the app opens fly in
+ // as themselves and assemble into the one reader, and page 3's chip grid later
+ // repeats the same colours for the same formats.
+ tint = DemoKinds[i].tint,
+ modifier = Modifier.graphicsLayer {
+ val p = progress.value
+ val head = i * 0.045f
+ val local = ((p - head) / (1f - head)).coerceIn(0f, 1f)
+ // Orbit through the opening stretch, in-fall through the middle, settled after.
+ val pull = smooth(((local - 0.18f) / 0.58f).coerceIn(0f, 1f))
+
+ val angle = base + (0.40f * local + 1.15f * pull * pull) * TwoPi
+ val radius = OrbitRadius * (1f - pull) * density
+
+ translationX = cos(angle) * radius + (depth * 2.4f * density) * pull
+ translationY = sin(angle) * radius + (-depth * 2.8f * density) * pull
+
+ // Peaks mid-flight and relaxes: creased on the way in, flat on landing.
+ val fold = sin(pull * Pi)
+ rotationY = 64f * fold * dir
+ rotationZ = lerp(sin(angle) * 17f, depth * 1.7f, pull) + 22f * fold * dir
+ cameraDistance = 14f
+
+ val s = lerp(0.32f, 1f, pull)
+ scaleX = s
+ scaleY = s
+ // The top sheet is the one the glass book replaces, so it hands over rather
+ // than sitting underneath and darkening it.
+ alpha = smooth(local * 4f) *
+ if (i == OrbitPages - 1) 1f - bookIn(p) else 1f
+ }
+ )
+ }
+
+ Box(
+ Modifier
+ .size(width = SheetW, height = SheetH)
+ .graphicsLayer {
+ val b = bookIn(progress.value)
+ alpha = b
+ val s = lerp(0.97f, 1f, b)
+ scaleX = s
+ scaleY = s
+ }
+ .viewerGlass(backdrop, bookGlass, shape = { RoundedRectangle(16f.dp) })
+ .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.
+ 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 ->
+ Box(
+ Modifier
+ .fillMaxWidth(w)
+ .height(if (idx == 0) 8.dp else 5.dp)
+ .graphicsLayer {
+ val head = idx * 0.10f
+ val t = ((bookIn(progress.value) - head) / (1f - head))
+ .coerceIn(0f, 1f)
+ alpha = t
+ // Grows from the left edge, like a line of text being laid down.
+ transformOrigin = androidx.compose.ui.graphics.TransformOrigin(0f, 0.5f)
+ scaleX = t
+ }
+ .clip(RoundedCornerShape(3.dp))
+ .background(bookInk.copy(if (idx == 0) 0.55f else 0.28f))
+ )
+ }
+ }
+ }
+ }
+}
+
+/**
+ * One flying page. Flat by design — see [DemoDocumentOpen]; the bars are what make a rounded
+ * rectangle read as a document once it is down at a third of its size.
+ *
+ * [tint] is the sheet's file kind, from [DemoKinds]. Card and bars share it so a sheet reads as one
+ * coloured object rather than a coloured card with grey lines on it. Both alphas sit a little above
+ * the neutral ones they replace (0.16 / 0.24): a hue needs more weight than grey to register at the
+ * 0.32 flight scale, under a 64° fold.
+ */
+@Composable
+private fun OrbitSheet(tint: Color, modifier: Modifier) {
+ Box(
+ modifier
+ .size(width = SheetW, height = SheetH)
+ .clip(RoundedCornerShape(14.dp))
+ .background(tint.copy(0.20f))
+ .padding(horizontal = 14.dp, vertical = 16.dp)
+ ) {
+ Column(verticalArrangement = Arrangement.spacedBy(9.dp)) {
+ listOf(0.80f, 1f, 0.66f, 0.92f, 0.50f).forEach { w ->
+ Box(
+ Modifier
+ .fillMaxWidth(w)
+ .height(5.dp)
+ .clip(RoundedCornerShape(3.dp))
+ .background(tint.copy(0.34f))
+ )
+ }
+ }
+ }
+}
+
+// ── 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.
+ *
+ * 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.
+ */
+@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")
+ )
+
+ Column(
+ Modifier
+ .fillMaxWidth()
+ .viewerGlass(backdrop, glass, shape = { RoundedRectangle(28f.dp) })
+ .padding(vertical = 14.dp, horizontal = 16.dp),
+ verticalArrangement = Arrangement.spacedBy(12.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)
+ ) {
+ 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)),
+ contentAlignment = Alignment.Center
+ ) {
+ Icon(kind.icon, null, Modifier.size(23.dp), Color.White)
+ }
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
+ BasicText(
+ kind.name,
+ style = TextStyle(ink, 15.sp, fontWeight = FontWeight.SemiBold),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ BasicText(
+ kind.ext,
+ style = TextStyle(inkSoft, 12.5.sp),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+ }
+ }
+}
+
+// ── Page 5 · The feature slots ──────────────────────────────────────────────────────────────────
+
+/**
+ * Height of a feature row's leading demo slot.
+ *
+ * Kept modest on purpose. The features page is the tallest in the flow, and the demo area is a
+ * `weight(1f)` box between fixed top and bottom padding — on a 640 dp-tall phone that box is only
+ * around 280 dp, and the panel has to fit inside it or it overlaps the copy underneath.
+ */
+private val SlotHeight = 50.dp
+
+/**
+ * A pen stroke drawing itself across a mini page, then a highlighter sweeping under it.
+ *
+ * The reveal is a [PathMeasure] trim rather than an animated point list: sampling `getSegment` gives
+ * a stroke that grows at a constant *arc-length* rate, so it draws at an even speed through the
+ * curve. Interpolating the control points instead makes it visibly rush the straight sections.
+ */
+@Composable
+fun DemoAnnotate(isActive: Boolean, ink: Color) {
+ val p = rememberDemoLoop(isActive, riseMs = 900, holdMs = 1100L)
+
+ Box(
+ Modifier
+ .size(width = 72.dp, height = SlotHeight)
+ .clip(RoundedCornerShape(10.dp))
+ .background(ink.copy(0.10f))
+ ) {
+ androidx.compose.foundation.Canvas(Modifier.fillMaxSize().padding(8.dp)) {
+ val w = size.width
+ val h = size.height
+
+ // Two text lines for the stroke to sit against.
+ listOf(0.24f, 0.52f).forEach { fy ->
+ drawLine(
+ ink.copy(0.30f),
+ Offset(0f, h * fy),
+ Offset(w * 0.92f, h * fy),
+ strokeWidth = 2.dp.toPx(),
+ cap = StrokeCap.Round
+ )
+ }
+
+ // The highlighter sweeps first, under the signature — same order a user works in.
+ val hl = (p / 0.45f).coerceIn(0f, 1f)
+ if (hl > 0f) {
+ drawLine(
+ Color(0xFFFFD60A).copy(0.55f),
+ Offset(0f, h * 0.24f),
+ Offset(w * 0.92f * hl, h * 0.24f),
+ strokeWidth = 9.dp.toPx(),
+ cap = StrokeCap.Butt
+ )
+ }
+
+ // A signature-ish squiggle, trimmed by arc length.
+ val sig = ((p - 0.35f) / 0.65f).coerceIn(0f, 1f)
+ if (sig > 0f) {
+ val path = Path().apply {
+ moveTo(w * 0.05f, h * 0.86f)
+ cubicTo(w * 0.20f, h * 0.60f, w * 0.28f, h * 1.02f, w * 0.44f, h * 0.80f)
+ cubicTo(w * 0.58f, h * 0.62f, w * 0.62f, h * 0.98f, w * 0.78f, h * 0.76f)
+ cubicTo(w * 0.86f, h * 0.66f, w * 0.90f, h * 0.80f, w * 0.95f, h * 0.72f)
+ }
+ val measure = PathMeasure().apply { setPath(path, false) }
+ val drawn = Path()
+ measure.getSegment(0f, measure.length * sig, drawn, true)
+ drawPath(
+ drawn,
+ Color(0xFF0A84FF),
+ style = Stroke(width = 2.4f.dp.toPx(), cap = StrokeCap.Round)
+ )
+ }
+ }
+ }
+}
+
+/**
+ * The search capsule unfurling out of its circle, replaying `GlassSearchHeader`'s open.
+ *
+ * Keeps that component's split exactly: the **width** is critically damped ([GlassMotion.settle]'s
+ * shape, via a linear-ish ease here since it drives real layout) while the glyph's quarter-turn and
+ * the field's scale ride an overshooting curve. A bouncing width would re-measure every frame and
+ * re-run the blur underneath.
+ */
+@Composable
+fun DemoSearch(isActive: Boolean, backdrop: Backdrop, glass: Color, ink: Color) {
+ val p = rememberDemoLoop(isActive, riseMs = 620, holdMs = 1400L)
+ val eased = FastOutSlowInEasing.transform(p)
+ val overshoot = EaseOutBack.transform(p)
+
+ Box(Modifier.size(width = 72.dp, height = SlotHeight), contentAlignment = Alignment.CenterEnd) {
+ Box(
+ Modifier
+ // Layout width: eased, never overshooting. A capsule that sprang past its target
+ // would drive this negative-adjacent and re-measure the glass every frame.
+ .width(lerp(34f, 72f, eased).dp)
+ .height(34.dp)
+ .viewerGlass(backdrop, glass, shape = { Capsule }),
+ contentAlignment = Alignment.CenterStart
+ ) {
+ Icon(
+ Icons.Rounded.Search,
+ null,
+ Modifier
+ .padding(start = 9.dp)
+ .size(16.dp)
+ // Draw-time property, so this is where the bounce is allowed to live.
+ .graphicsLayer { rotationZ = lerp(0f, 90f, overshoot) },
+ ink.copy(0.75f)
+ )
+ // A caret and a "typed" bar appear once the capsule has room for them.
+ Box(
+ Modifier
+ .padding(start = 32.dp)
+ .graphicsLayer {
+ alpha = ((p - 0.45f) / 0.55f).coerceIn(0f, 1f)
+ transformOrigin = androidx.compose.ui.graphics.TransformOrigin(0f, 0.5f)
+ scaleX = ((p - 0.45f) / 0.55f).coerceIn(0f, 1f)
+ }
+ .width(26.dp)
+ .height(5.dp)
+ .clip(RoundedCornerShape(3.dp))
+ .background(ink.copy(0.45f))
+ )
+ }
+ }
+}
+
+/**
+ * The real [GlassCapsuleMenu], driven by a looping progress float.
+ *
+ * No replay needed and no new drawing code: the component already takes `progress` from its caller
+ * precisely so whatever opened it can own the clock, which makes it the one production animation
+ * onboarding can show *literally* rather than by imitation.
+ *
+ * The rise is deliberately slower than the real menu's. Its `StaggerFraction` of 0.07 is a fraction
+ * of `progress`, not a duration, so at the gesture's ~560 ms the three circles land about 39 ms
+ * apart — legible when your own finger caused it, indistinguishable from simultaneous when you are
+ * watching. Stretching the clock is the only knob that widens the cascade without touching the
+ * component, and it costs nothing here because nothing is waiting on this animation.
+ *
+ * Must be given its natural width. See `OnboardingScreen.FeatureRows` — this is a `Row` of 40 dp
+ * circles, and a constraint narrower than its content silently drops actions rather than shrinking.
+ */
+@Composable
+fun DemoToolsMenu(
+ isActive: Boolean,
+ backdrop: Backdrop,
+ uiSensor: com.chethan616.clearpdf.ui.utils.UISensor,
+ glass: Color,
+ actions: List<GlassMenuAction>
+) {
+ val p = rememberDemoLoop(isActive, riseMs = 820, holdMs = 1600L)
+ GlassCapsuleMenu(
+ actions = actions,
+ backdrop = backdrop,
+ uiSensor = uiSensor,
+ progress = p,
+ surfaceColor = glass
+ )
+}
+
+// ── Page 5 · Ready ──────────────────────────────────────────────────────────────────────────────
+
+/**
+ * A glass disc springs in, then a checkmark draws itself inside it.
+ *
+ * Same [PathMeasure] trim as [DemoAnnotate] — the tick is *drawn*, not faded in, which is what makes
+ * it read as a confirmation rather than an icon appearing. Plays once per visit rather than looping:
+ * a checkmark that keeps un-checking itself undermines the "you're all set" it is illustrating.
+ */
+@Composable
+fun DemoReady(isActive: Boolean, backdrop: Backdrop, glass: Color) {
+ var play by remember { mutableIntStateOf(0) }
+ LaunchedEffect(isActive) { if (isActive) { delay(220); play = 1 } else play = 0 }
+
+ val disc by animateFloatAsState(
+ if (play == 1) 1f else 0f,
+ GlassMotion.morph(),
+ label = "readyDisc"
+ )
+ val tick by animateFloatAsState(
+ if (play == 1) 1f else 0f,
+ tween(520, delayMillis = 180, easing = FastOutSlowInEasing),
+ label = "readyTick"
+ )
+
+ Box(Modifier.size(132.dp), contentAlignment = Alignment.Center) {
+ // A soft accent halo behind the glass, flat, so it can pulse without costing a re-blur.
+ Box(
+ Modifier
+ .size(120.dp)
+ .graphicsLayer {
+ val s = lerp(0.7f, 1f, disc.coerceIn(0f, 1f))
+ scaleX = s; scaleY = s
+ alpha = 0.22f * disc.coerceIn(0f, 1f)
+ }
+ .clip(CircleShape)
+ .background(LiquidGlassColors.Green)
+ )
+ Box(
+ Modifier
+ .size(96.dp)
+ .graphicsLayer {
+ val s = lerp(0.82f, 1f, disc)
+ scaleX = s; scaleY = s
+ alpha = disc.coerceIn(0f, 1f)
+ }
+ .viewerGlass(backdrop, glass, shape = { Capsule }),
+ contentAlignment = Alignment.Center
+ ) {
+ androidx.compose.foundation.Canvas(Modifier.size(44.dp)) {
+ if (tick <= 0f) return@Canvas
+ val w = size.width
+ val h = size.height
+ val path = Path().apply {
+ moveTo(w * 0.16f, h * 0.53f)
+ lineTo(w * 0.41f, h * 0.76f)
+ lineTo(w * 0.85f, h * 0.26f)
+ }
+ val measure = PathMeasure().apply { setPath(path, false) }
+ val drawn = Path()
+ measure.getSegment(0f, measure.length * tick, drawn, true)
+ drawPath(
+ drawn,
+ LiquidGlassColors.Green,
+ style = Stroke(width = 4.5f.dp.toPx(), cap = StrokeCap.Round)
+ )
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/components/ShareMorphButton.kt b/app/src/main/java/com/chethan616/clearpdf/ui/components/ShareMorphButton.kt
index 825ee0e..f1e197f 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/components/ShareMorphButton.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/components/ShareMorphButton.kt
@@ -1,8 +1,9 @@
package com.chethan616.clearpdf.ui.components
+import androidx.compose.animation.animateColorAsState
+import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.RepeatMode
-import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateDp
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateFloatAsState
@@ -62,6 +63,19 @@ import com.kyant.shapes.Capsule
* and forces `drawBackdrop` to re-run its blur and lens at a new size. Damping here is a performance
* fix as much as a visual one.
*/
+/** The blue builds on this rather than on the finger's raw travel. See the call site for why. */
+private val TintRamp = CubicBezierEasing(0.45f, 0f, 0.55f, 1f)
+
+/**
+ * Ceiling on the blue's opacity, so the armed capsule is still glass and not paint.
+ *
+ * Not lower than this. The icons on top are white, and the backdrop here is usually a white PDF
+ * page — every point of transparency lightens the blue toward the page and costs icon contrast.
+ * 0.82 leaves the refraction clearly visible while landing close to the contrast the old opaque
+ * fill had.
+ */
+private const val MaxTintAlpha = 0.82f
+
@Composable
fun ShareMorphButton(
backdrop: LayerBackdrop,
@@ -114,11 +128,41 @@ fun ShareMorphButton(
)
val progress = (-dragUp / thresholdPx).coerceIn(0f, 1f)
- // Raw drag distance tracks the finger 1:1, which makes the blue arrive abruptly. Easing it lets
- // the tint build gently and settle right as the gesture arms.
- val eased = FastOutSlowInEasing.transform(progress)
+ // A symmetric S-curve, not [FastOutSlowInEasing]. Fast-out-slow-in front-loads — it is already
+ // past 0.9 at 80% of the travel — so the blue rushed in over the first few millimetres and then
+ // sat there, which made the tint feel like a state the capsule flipped into rather than
+ // something the gesture was building. This starts gently, does its work through the middle of
+ // the swipe, and eases into the commit.
+ val easedDrag = TintRamp.transform(progress)
val armed = progress >= 1f
- val surface = lerp(glass, blue, eased)
+ // Reading the finger position straight into the colour had two problems: it jittered with every
+ // pointer sample on the way up, and on release `dragUp` resets to 0 in one frame, so the blue
+ // vanished instantly instead of receding with the capsule. The spring smooths both. It is
+ // deliberately softer than a tracking spring would be (Medium/1500 chased the finger closely
+ // enough to reintroduce the jitter) — the slight lag is what makes the colour read as fading in.
+ // Colour is a draw-time property, so this costs a paint, not a re-measure.
+ val eased by animateFloatAsState(
+ if (armed) 1f else easedDrag,
+ spring(dampingRatio = 1f, stiffness = 320f),
+ label = "shareMorphTint"
+ )
+ // Arming brightens the blue rather than just reaching the end of the ramp, so the commit point
+ // is visible and not only felt through the haptic.
+ val tint by animateColorAsState(
+ if (armed) Color(0xFF4AA8FF) else blue,
+ tween(240, easing = FastOutSlowInEasing),
+ label = "shareMorphArmed"
+ )
+ // Note the alpha cap. Lerping all the way to an opaque blue turned the capsule into a flat
+ // painted pill at the top of the gesture — the one moment the material should be most obviously
+ // alive. Held under 1 it stays a tint *through* the glass: the backdrop still refracts, and the
+ // colour reads as the surface picking up blue rather than the surface being replaced by it.
+ // The viewer passes a fully clear [glass] so the idle capsule is pure refraction like Home's
+ // circles. `Color.Transparent` is transparent *black*, though, and Compose interpolates colour
+ // and alpha together — ramping from it smeared the middle of the swipe through a muddy navy.
+ // Starting from the tint's own hue at zero alpha keeps the ramp blue the whole way up.
+ val base = if (glass.alpha == 0f) tint.copy(alpha = 0f) else glass
+ val surface = lerp(base, tint.copy(alpha = MaxTintAlpha), eased)
// Fire exactly once on the false→true edge. Keying the effect on `armed` alone also fired on
// first composition and again on disarm.
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 508f0dc..348cae2 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
@@ -1,8 +1,15 @@
package com.chethan616.clearpdf.ui.components
+import androidx.compose.foundation.ScrollState
import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.drawWithContent
+import androidx.compose.ui.graphics.BlendMode
+import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.CompositingStrategy
import androidx.compose.ui.graphics.Shape
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.kyant.backdrop.Backdrop
import com.kyant.backdrop.drawBackdrop
@@ -27,10 +34,19 @@ import com.kyant.shapes.RoundedRectangle
* Takes an explicit [color] rather than resolving the theme, so it is not `@Composable` and each
* viewer passes the same `chromeGlass` its buttons already use.
*/
+/**
+ * The corner curve [viewerGlass] paints by default.
+ *
+ * Hoisted out of the default argument because anything that *clips* to a viewerGlass surface has to
+ * use the same curve — a clip and a paint that disagree by even a couple of dp reads as a chipped
+ * edge. See [carouselEdges].
+ */
+val ViewerGlassShape: Shape = RoundedRectangle(28f.dp)
+
fun Modifier.viewerGlass(
backdrop: Backdrop,
color: Color,
- shape: () -> Shape = { RoundedRectangle(28f.dp) }
+ shape: () -> Shape = { ViewerGlassShape }
): Modifier = drawBackdrop(
backdrop = backdrop,
shape = shape,
@@ -42,6 +58,74 @@ fun Modifier.viewerGlass(
onDrawSurface = { drawRect(color) }
)
+/**
+ * Rounded clip plus a soft, scroll-aware edge mask for a horizontally scrolling strip that rides on a
+ * [viewerGlass] surface.
+ *
+ * **The bug this exists to kill.** `Modifier.horizontalScroll` clips to its node's *rectangular*
+ * bounds, and [viewerGlass] only ever *draws* its rounded shape — `drawBackdrop` paints, it does not
+ * clip. A scrolling row of chips on glass was therefore chopped by a straight vertical line sitting
+ * inside the capsule's own curve: the one thing a floating glass control must never look like. With
+ * this, chips slide in and out *behind* the container's curved ends instead.
+ *
+ * Apply it **inside** the glass and **outside** the scroll, with the padding moved to the far end:
+ *
+ * ```
+ * .viewerGlass(backdrop, glass)
+ * .carouselEdges(state)
+ * .horizontalScroll(state)
+ * .padding(horizontal = 12.dp, vertical = 10.dp)
+ * ```
+ *
+ * Two things about that order matter. The glass is drawn by the modifier to the *left*, so it is
+ * outside this layer and the capsule keeps its full opacity at the edges — only the chips fade.
+ * And padding after the scroll is *content* padding that travels with the content, so the first and
+ * last chips rest with the same inset as the gaps between them yet can still reach the true edge
+ * mid-scroll. Before the scroll it insets the viewport, which is what put the straight cut 12 dp in
+ * from the curve.
+ *
+ * The fade reads [state] inside the draw lambda, so scrolling invalidates draw only and never
+ * recomposes. It is absent at rest on the left, retires as you reach the right end, and is short
+ * ([fade] defaults to 18 dp) — a hint that there is more to the side, not a vignette.
+ */
+fun Modifier.carouselEdges(
+ state: ScrollState,
+ shape: Shape = ViewerGlassShape,
+ fade: Dp = 18.dp
+): Modifier = this
+ // One layer does both jobs. `Offscreen` is not decoration: it is what makes the `DstIn` below
+ // mask this strip rather than punch a hole through everything already on the canvas.
+ .graphicsLayer {
+ compositingStrategy = CompositingStrategy.Offscreen
+ clip = true
+ this.shape = shape
+ }
+ .drawWithContent {
+ drawContent()
+ val w = size.width
+ val fadePx = fade.toPx()
+ if (w <= fadePx * 2f) return@drawWithContent
+
+ val max = state.maxValue
+ // `maxValue` is Int.MAX_VALUE until the strip has been measured. Treated as "nothing to
+ // scroll", otherwise a row that fits flashes a trailing fade on its first frame.
+ val scrollable = max in 1..<Int.MAX_VALUE
+ val lead = if (scrollable) (state.value / fadePx).coerceIn(0f, 1f) else 0f
+ val trail = if (scrollable) ((max - state.value) / fadePx).coerceIn(0f, 1f) else 0f
+ if (lead == 0f && trail == 0f) return@drawWithContent
+
+ val edge = fadePx / w
+ drawRect(
+ Brush.horizontalGradient(
+ 0f to Color.Black.copy(alpha = 1f - lead),
+ edge to Color.Black,
+ 1f - edge to Color.Black,
+ 1f to Color.Black.copy(alpha = 1f - trail)
+ ),
+ blendMode = BlendMode.DstIn
+ )
+ }
+
/**
* The neutral chrome tint the theme-driven viewers pair with [viewerGlass], so their panels and their
* buttons resolve the same colour from one place instead of each screen writing the literal.
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/navigation/DocsNavGraph.kt b/app/src/main/java/com/chethan616/clearpdf/ui/navigation/DocsNavGraph.kt
index 08a0b01..071f3b5 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/navigation/DocsNavGraph.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/navigation/DocsNavGraph.kt
@@ -30,6 +30,7 @@ import com.chethan616.clearpdf.ui.screen.ExtractTextScreen
import com.chethan616.clearpdf.ui.screen.ImagesToPdfScreen
import com.chethan616.clearpdf.ui.screen.HomeScreen
import com.chethan616.clearpdf.ui.screen.MergePdfScreen
+import com.chethan616.clearpdf.ui.screen.OnboardingScreen
import com.chethan616.clearpdf.ui.screen.SpreadsheetViewerScreen
import com.chethan616.clearpdf.ui.screen.ImageEditorScreen
import com.chethan616.clearpdf.ui.viewmodel.SpreadsheetViewModel
@@ -69,6 +70,9 @@ import com.chethan616.clearpdf.ui.viewmodel.SplitPdfViewModel
import com.chethan616.clearpdf.ui.viewmodel.ScanViewModel
import com.kyant.backdrop.backdrops.LayerBackdrop
+/** Public so `DocsApp` can pick it as the start destination on a first run. */
+const val ROUTE_ONBOARDING = "onboarding"
+
private const val ROUTE_HOME = "home"
private const val ROUTE_TOOLS = "tools"
private const val ROUTE_SETTINGS = "settings"
@@ -132,8 +136,14 @@ private fun NavHostController.navigateToPdfViewer(uri: Uri? = null) {
/** Open a document by its kind: spreadsheets (.xlsx/.xls) go to the interactive grid viewer, all
* other kinds to the PDF viewer (which converts non-PDFs to a PDF as before). */
-private fun NavHostController.navigateToDocument(context: android.content.Context, uri: Uri) {
- val name = runCatching {
+private fun NavHostController.navigateToDocument(
+ context: android.content.Context,
+ uri: Uri,
+ // Supplied when the caller already knows the real name (recents stores it). Only fall back to
+ // querying the provider when we genuinely don't — a freshly picked uri.
+ knownName: String? = null
+) {
+ val name = knownName?.ifBlank { null } ?: runCatching {
context.contentResolver.query(uri, null, null, null, null)?.use { c ->
val i = c.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)
if (i != -1 && c.moveToFirst()) c.getString(i) else null
@@ -155,6 +165,23 @@ private fun routeToTabIdx(route: String?): Int = when (route) {
else -> 0
}
+/**
+ * The document viewers (PDF / spreadsheet / image). Opening or closing one should read like the
+ * document lifting off the screen behind it, so during those transitions the underneath screen is
+ * held perfectly still and opaque — NO fade, NO slide — while only the viewer scales + fades.
+ *
+ * That single rule is what kills the flicker: a scaling viewer is briefly smaller than full-screen,
+ * and if the screen behind is mid-fade (or already gone) its edges flash the bare window. Keeping
+ * the backdrop screen static and fully drawn means those edges always reveal a stable image, and
+ * because every screen shares the same wallpaper the lift looks seamless.
+ */
+private fun isDocViewerRoute(route: String?): Boolean =
+ route != null && (
+ route.startsWith(ROUTE_VIEWER_BASE) ||
+ route.startsWith(ROUTE_SPREADSHEET_BASE) ||
+ route.startsWith(ROUTE_IMAGE_EDITOR_BASE)
+ )
+
@Composable
fun DocsNavGraph(
navController: NavHostController,
@@ -171,11 +198,17 @@ fun DocsNavGraph(
onCustomWallpaperChanged: (String?) -> Unit = {},
selectedLocale: String,
onLocaleChanged: (String) -> Unit,
- incomingPdfUri: Uri? = null
+ incomingPdfUri: Uri? = null,
+ startDestination: String = ROUTE_HOME,
+ // Onboarding's language picker takes this instead of [onLocaleChanged]: it must NOT restart the
+ // Activity, or the flow would relaunch at page one under the user. The restart, if the choice
+ // actually changed anything, is deferred to [onOnboardingFinished].
+ onOnboardingLocaleSelected: (String) -> Unit = {},
+ onOnboardingFinished: () -> Unit = {}
) {
NavHost(
navController = navController,
- startDestination = ROUTE_HOME,
+ startDestination = startDestination,
enterTransition = {
val isMainTabSwitch = initialState.destination.route in MAIN_TAB_ROUTES && targetState.destination.route in MAIN_TAB_ROUTES
if (isMainTabSwitch) {
@@ -198,7 +231,11 @@ fun DocsNavGraph(
},
exitTransition = {
val isMainTabSwitch = initialState.destination.route in MAIN_TAB_ROUTES && targetState.destination.route in MAIN_TAB_ROUTES
- if (isMainTabSwitch) {
+ if (isDocViewerRoute(targetState.destination.route) && !isDocViewerRoute(initialState.destination.route)) {
+ // Opening a document viewer: hold this screen still + opaque behind the lifting
+ // viewer so its scaling edges never flash the bare window. See [isDocViewerRoute].
+ ExitTransition.None
+ } else if (isMainTabSwitch) {
val dist = kotlin.math.abs(routeToTabIdx(targetState.destination.route) - routeToTabIdx(initialState.destination.route))
val fadeDuration = if (dist >= 2) 520 else 350
androidx.compose.animation.fadeOut(
@@ -218,7 +255,12 @@ fun DocsNavGraph(
},
popEnterTransition = {
val isMainTabSwitch = initialState.destination.route in MAIN_TAB_ROUTES && targetState.destination.route in MAIN_TAB_ROUTES
- if (isMainTabSwitch) {
+ if (isDocViewerRoute(initialState.destination.route) && !isDocViewerRoute(targetState.destination.route)) {
+ // Returning from a document viewer: this screen is already there — don't re-animate
+ // it. Just let the viewer scale/fade away on top of it. Re-fading it in was the
+ // "flash + black edge" flicker on back. See [isDocViewerRoute].
+ EnterTransition.None
+ } else if (isMainTabSwitch) {
val dist = kotlin.math.abs(routeToTabIdx(targetState.destination.route) - routeToTabIdx(initialState.destination.route))
val fadeDuration = if (dist >= 2) 520 else 350
androidx.compose.animation.fadeIn(
@@ -258,6 +300,42 @@ fun DocsNavGraph(
}
) {
+ // ── First run ──
+
+ composable(ROUTE_ONBOARDING) {
+ OnboardingScreen(
+ backdrop = backdrop,
+ selectedLocale = selectedLocale,
+ onLocaleSelected = onOnboardingLocaleSelected,
+ // The real hoisted appearance state, not a copy: the tour's own glass re-tints as
+ // the user taps, and whatever they pick is already persisted by the time they leave.
+ themeMode = themeMode,
+ onThemeModeChanged = onThemeModeChanged,
+ showWallpaper = showWallpaper,
+ onShowWallpaperChanged = onShowWallpaperChanged,
+ hasCustomWallpaper = hasCustomWallpaper,
+ onCustomWallpaperChanged = onCustomWallpaperChanged,
+ onFinish = {
+ // The host records completion and, only if the locale actually changed, starts
+ // its fade + recreate. Either way we leave this route.
+ onOnboardingFinished()
+ // Two arrivals to unwind. On a first run onboarding IS the start destination and
+ // there is nothing behind it, so we navigate to Home and drop this route. On a
+ // replay from Settings the stack is [home, settings, onboarding] — navigating
+ // would push a second Home and strand Settings under it, so pop instead and land
+ // back on the Settings row the replay was launched from.
+ if (navController.previousBackStackEntry != null) {
+ navController.popBackStack()
+ } else {
+ navController.navigate(ROUTE_HOME) {
+ popUpTo(ROUTE_ONBOARDING) { inclusive = true }
+ launchSingleTop = true
+ }
+ }
+ }
+ )
+ }
+
// ── Main tabs ──
composable(ROUTE_HOME) {
@@ -280,10 +358,11 @@ fun DocsNavGraph(
onNavigateToScan = {
navController.navigate(ROUTE_SCAN) { launchSingleTop = true }
},
- onRecentFileSelected = { uri ->
+ onRecentFileSelected = { uri, name ->
// Route by document kind: spreadsheets open in the interactive grid viewer,
- // everything else in the PDF viewer.
- navController.navigateToDocument(homeContext, uri)
+ // everything else in the PDF viewer. The name comes from the recents entry
+ // rather than a fresh provider query — see [navigateToDocument].
+ navController.navigateToDocument(homeContext, uri, name)
}
)
}
@@ -313,7 +392,14 @@ fun DocsNavGraph(
}
composable(ROUTE_SETTINGS) {
+ val settingsContext = LocalContext.current
SettingsScreen(
+ onReplayOnboarding = {
+ // Clear the flag too, not just navigate: otherwise quitting the replay early
+ // leaves the tour marked "seen" while the user never finished it.
+ com.chethan616.clearpdf.data.repository.OnboardingManager.resetOnboarding(settingsContext)
+ navController.navigate(ROUTE_ONBOARDING) { launchSingleTop = true }
+ },
backdrop = backdrop,
isDarkMode = isDarkMode,
onDarkModeChanged = onDarkModeChanged,
@@ -364,30 +450,27 @@ fun DocsNavGraph(
defaultValue = null
}
),
- // "Document lifts open" transition: a quick fade + a soft-spring zoom-up from slightly
- // smaller, with a subtle rise from below — like the tapped card opening into the reader.
- // (Springs settle instead of stopping flat, which reads more premium than a linear zoom.)
+ // "Document lifts open": one coordinated fade + soft-spring zoom-up from slightly
+ // smaller. The screen behind is held static+opaque (see [isDocViewerRoute]), so the
+ // lift reads against a stable backdrop with no edge flash. The earlier vertical slide is
+ // gone — a single centered scale settling on a spring is cleaner and flicker-free.
enterTransition = {
- androidx.compose.animation.fadeIn(tween(220, easing = androidx.compose.animation.core.FastOutSlowInEasing)) +
+ androidx.compose.animation.fadeIn(tween(200, easing = androidx.compose.animation.core.FastOutSlowInEasing)) +
androidx.compose.animation.scaleIn(
- initialScale = 0.90f,
- animationSpec = androidx.compose.animation.core.spring(
- dampingRatio = 0.82f,
- stiffness = androidx.compose.animation.core.Spring.StiffnessMediumLow
- )
- ) +
- androidx.compose.animation.slideInVertically(
+ initialScale = 0.92f,
animationSpec = androidx.compose.animation.core.spring(
- dampingRatio = 0.9f,
+ dampingRatio = 0.85f,
stiffness = androidx.compose.animation.core.Spring.StiffnessMediumLow
)
- ) { it / 14 }
+ )
},
exitTransition = { androidx.compose.animation.fadeOut(tween(160)) },
popEnterTransition = { androidx.compose.animation.fadeIn(tween(200)) },
+ // Closing: the viewer settles back down + fades, revealing the (already-present) screen
+ // underneath. Symmetric with the open so back feels like the inverse of the lift.
popExitTransition = {
- androidx.compose.animation.fadeOut(tween(220, easing = androidx.compose.animation.core.FastOutSlowInEasing)) +
- androidx.compose.animation.scaleOut(targetScale = 0.93f, animationSpec = tween(240, easing = androidx.compose.animation.core.FastOutSlowInEasing))
+ androidx.compose.animation.fadeOut(tween(210, easing = androidx.compose.animation.core.FastOutSlowInEasing)) +
+ androidx.compose.animation.scaleOut(targetScale = 0.94f, animationSpec = tween(220, easing = androidx.compose.animation.core.FastOutSlowInEasing))
}
) { backStackEntry ->
val context = LocalContext.current
@@ -414,13 +497,20 @@ fun DocsNavGraph(
composable(
route = ROUTE_SPREADSHEET,
arguments = listOf(navArgument(ARG_PDF_URI) { type = NavType.StringType; nullable = true; defaultValue = null }),
+ // Same "document lifts open" as the PDF viewer (see that route) for a uniform feel.
enterTransition = {
- androidx.compose.animation.fadeIn(tween(220, easing = androidx.compose.animation.core.FastOutSlowInEasing)) +
- androidx.compose.animation.scaleIn(initialScale = 0.94f, animationSpec = tween(300, easing = androidx.compose.animation.core.FastOutSlowInEasing))
+ androidx.compose.animation.fadeIn(tween(200, easing = androidx.compose.animation.core.FastOutSlowInEasing)) +
+ androidx.compose.animation.scaleIn(
+ initialScale = 0.92f,
+ animationSpec = androidx.compose.animation.core.spring(
+ dampingRatio = 0.85f,
+ stiffness = androidx.compose.animation.core.Spring.StiffnessMediumLow
+ )
+ )
},
popExitTransition = {
- androidx.compose.animation.fadeOut(tween(200)) +
- androidx.compose.animation.scaleOut(targetScale = 0.94f, animationSpec = tween(220))
+ androidx.compose.animation.fadeOut(tween(210, easing = androidx.compose.animation.core.FastOutSlowInEasing)) +
+ androidx.compose.animation.scaleOut(targetScale = 0.94f, animationSpec = tween(220, easing = androidx.compose.animation.core.FastOutSlowInEasing))
}
) { backStackEntry ->
val context = LocalContext.current
@@ -441,13 +531,20 @@ fun DocsNavGraph(
composable(
route = ROUTE_IMAGE_EDITOR,
arguments = listOf(navArgument(ARG_PDF_URI) { type = NavType.StringType; nullable = true; defaultValue = null }),
+ // Same "document lifts open" as the PDF viewer (see that route) for a uniform feel.
enterTransition = {
- androidx.compose.animation.fadeIn(tween(220, easing = androidx.compose.animation.core.FastOutSlowInEasing)) +
- androidx.compose.animation.scaleIn(initialScale = 0.94f, animationSpec = tween(300, easing = androidx.compose.animation.core.FastOutSlowInEasing))
+ androidx.compose.animation.fadeIn(tween(200, easing = androidx.compose.animation.core.FastOutSlowInEasing)) +
+ androidx.compose.animation.scaleIn(
+ initialScale = 0.92f,
+ animationSpec = androidx.compose.animation.core.spring(
+ dampingRatio = 0.85f,
+ stiffness = androidx.compose.animation.core.Spring.StiffnessMediumLow
+ )
+ )
},
popExitTransition = {
- androidx.compose.animation.fadeOut(tween(200)) +
- androidx.compose.animation.scaleOut(targetScale = 0.94f, animationSpec = tween(220))
+ androidx.compose.animation.fadeOut(tween(210, easing = androidx.compose.animation.core.FastOutSlowInEasing)) +
+ androidx.compose.animation.scaleOut(targetScale = 0.94f, animationSpec = tween(220, easing = androidx.compose.animation.core.FastOutSlowInEasing))
}
) { backStackEntry ->
val context = LocalContext.current
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 08a79d8..33d23ba 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
@@ -5,6 +5,7 @@ import android.net.Uri
import android.view.HapticFeedbackConstants
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.Animatable
+import androidx.compose.animation.core.FastOutLinearInEasing
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.Transition
@@ -23,6 +24,9 @@ import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
+import androidx.compose.ui.input.pointer.util.VelocityTracker
+import androidx.compose.ui.layout.layout
+import kotlin.math.roundToInt
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
@@ -71,6 +75,7 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
@@ -106,6 +111,8 @@ import com.chethan616.clearpdf.ui.utils.rememberUISensor
import com.chethan616.clearpdf.utils.DocKind
import com.chethan616.clearpdf.utils.docKindOf
import com.kyant.backdrop.backdrops.LayerBackdrop
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date
@@ -121,7 +128,11 @@ fun HomeScreen(
backdrop: LayerBackdrop,
onNavigateToOpenPdf: () -> Unit,
onNavigateToScan: () -> Unit,
- onRecentFileSelected: (Uri) -> Unit
+ // The stored display name travels with the uri. Re-querying DISPLAY_NAME at tap time is a
+ // guess that fails exactly when it matters: a lapsed permission or a provider that answers with
+ // its own internal name sends a .docx down the plain-PDF route. Recents already knows what the
+ // file is called, so routing should ask recents.
+ onRecentFileSelected: (Uri, String) -> Unit
) {
val homeRecentLimit = 5
val isDarkMode = LocalIsDarkMode.current
@@ -132,6 +143,7 @@ fun HomeScreen(
val redAccent = LiquidGlassColors.Red
val uiSensor = rememberUISensor()
val context = LocalContext.current
+ val homeScope = rememberCoroutineScope()
var recents by remember { mutableStateOf(RecentFilesManager.getRecents(context)) }
var showAllRecents by remember { mutableStateOf(false) }
@@ -224,8 +236,13 @@ fun HomeScreen(
item(key = "hero") {
AnimatedVisibility(
visible = !searchActive,
- enter = fadeIn(tween(220)) + expandVertically(tween(260)),
- exit = fadeOut(tween(160)) + shrinkVertically(tween(220))
+ // Desync the fade from the height so the glass is invisible whenever its size is
+ // moving — an alpha-0 liquidGlassPanel draws nothing, so the collapse can't show
+ // its per-frame re-blur, and the recents panel's rise reads as a clean fade rather
+ // than a shimmer. Open the height first, then fade in; fade out fast, then finish
+ // shrinking unseen.
+ enter = expandVertically(tween(240)) + fadeIn(tween(200, delayMillis = 110)),
+ exit = fadeOut(tween(120)) + shrinkVertically(tween(240))
) {
Column(
Modifier
@@ -422,15 +439,18 @@ fun HomeScreen(
isLight = isLight,
textColor = text,
secondaryColor = sub,
- onClick = { onRecentFileSelected(recent.uri) },
+ onClick = { onRecentFileSelected(recent.uri, recent.name) },
onLongClick = { top, height ->
selectedRecent = recent
selectedRecentAnchorY = top
selectedRecentRowHeight = height
},
onSwipeDelete = {
- RecentFilesManager.removeRecent(context, recent.uri)
+ // Drop it from the list immediately (cheap, keyed rows), and
+ // persist off the main thread so the terminal relayout the
+ // removal triggers never blocks a frame during the exit.
recents = recents.filterNot { it.uriString == recent.uriString }
+ homeScope.launch(Dispatchers.IO) { RecentFilesManager.removeRecent(context, recent.uri) }
}
)
}
@@ -488,7 +508,7 @@ fun HomeScreen(
actions = listOf(
GlassMenuAction(
Icons.Rounded.FileOpen, stringResource(R.string.recents_open), Color(0xFF0088FF)
- ) { selectedRecent = null; onRecentFileSelected(recent.uri) },
+ ) { selectedRecent = null; onRecentFileSelected(recent.uri, recent.name) },
GlassMenuAction(
if (recent.pinned) Icons.Rounded.PushPin else Icons.Outlined.PushPin,
stringResource(if (recent.pinned) R.string.recents_unpin else R.string.recents_pin),
@@ -717,6 +737,60 @@ private fun Transition<Boolean>.entranceModifier(index: Int, density: Float): Mo
}
}
+/** Fraction of the row width a swipe must cross to commit the delete. */
+private const val SwipeCommitFraction = 0.40f
+
+/**
+ * How "armed" a swipe of [travel] px looks on a row [width] px wide: 0 until the swipe is well
+ * underway, ramping to 1 right at [SwipeCommitFraction]. Drives the delete icon's scale.
+ */
+private fun armProgress(travel: Float, width: Float): Float {
+ if (width <= 0f) return 0f
+ val p = (travel / width).coerceIn(0f, 1f)
+ return ((p - (SwipeCommitFraction - 0.22f)) / 0.22f).coerceIn(0f, 1f)
+}
+
+/** Fraction of the row width over which the slab reaches its full red. */
+private const val RedRampFraction = 0.25f
+
+/** The pale red the slab starts on, so the first quarter of the swipe reads as a hint. */
+private val SwipeRedLight = Color(0xFFEF7B7B).copy(alpha = 0.55f)
+
+/** The committed red. Reached at [RedRampFraction] and held for the rest of the travel. */
+private val SwipeRedFull = Color(0xFFE53935)
+
+/**
+ * The slab colour for a swipe of [travel] px on a row [width] px wide.
+ *
+ * Separate from [armProgress] on purpose. The icon is allowed to hold back and then pop right at
+ * the commit point, but the colour is the thing you read first, and ramping it against a 0.40
+ * threshold meant the row stayed almost neutral through most of the gesture and then went red in a
+ * rush. Full red by a quarter of the width instead: pale while you are still deciding, unambiguous
+ * well before you have to commit, and flat afterwards so the last half of the travel does not keep
+ * shifting under the finger.
+ */
+private fun swipeRed(travel: Float, width: Float): Color {
+ if (width <= 0f) return SwipeRedLight
+ val t = (travel / (width * RedRampFraction)).coerceIn(0f, 1f)
+ return lerp(SwipeRedLight, SwipeRedFull, t)
+}
+
+/**
+ * Row geometry, deliberately **not** snapshot state.
+ *
+ * `onGloballyPositioned` fires for a row whenever it is re-placed, and a delete re-places every row
+ * below the one collapsing on every frame of the animation. Writing these into `mutableStateOf`
+ * therefore recomposed most of the list ~60 times a second for the length of the delete — each of
+ * those recompositions re-running `docKindOf`, the size/date formatting and the badge lookup for a
+ * row whose contents had not changed at all. Nothing observes these reactively: the long-press and
+ * the drag both read them at gesture time, long after they are set.
+ */
+private class RowMetrics {
+ var topY = 0f
+ var height = 0f
+ var width = 1f
+}
+
/**
* One recents entry. Liquid-glass press: no grey ripple; the row eases down with a soft
* spring while held (like an Apple button), then springs back on release. It reports its
@@ -732,9 +806,7 @@ private fun RecentRow(
onLongClick: (top: Float, height: Float) -> Unit,
onSwipeDelete: () -> Unit
) {
- var rowTopY by remember { mutableStateOf(0f) }
- var rowHeightPx by remember { mutableStateOf(0f) }
- var rowWidthPx by remember { mutableStateOf(1f) }
+ val metrics = remember { RowMetrics() }
val rowInteraction = remember { MutableInteractionSource() }
val rowPressed by rowInteraction.collectIsPressedAsState()
val rowScale by animateFloatAsState(
@@ -745,17 +817,45 @@ private fun RecentRow(
// Swipe-to-delete. Left only: a rightward drag has no meaning here, and allowing it would
// just expose empty space behind the row.
val swipeX = remember { Animatable(0f) }
+ // Runs 1 -> 0 after the row has slid off, so the gap below closes instead of snapping shut.
+ // These rows sit in a plain Column (not LazyItemScope), so `animateItem()` isn't available.
+ val collapse = remember { Animatable(1f) }
+ // Opacity of the row AND its red slab together.
+ //
+ // The old exit slid the card all the way off to `-width` and then closed the gap. That left the
+ // slab as the only thing on screen for the whole collapse — a bare red band shrinking while the
+ // rows underneath slid up past it, which is the overlap glitch. Fading the pair as one object
+ // means the red can never outlive the card it belongs to.
+ val exitAlpha = remember { Animatable(1f) }
val scope = rememberCoroutineScope()
val view = LocalView.current
Box(
Modifier
.fillMaxWidth()
+ // `collapse` is read at MEASURE time, so the shrink invalidates layout without
+ // recomposing, and the curve is monotonic so it never overshoots into a negative height.
+ //
+ // This *does* knowingly break the no-animated-layout rule. The row itself is a plain
+ // background, but it sits inside the recents `liquidGlassPanel`, which wraps its
+ // children — so shrinking a row resizes the panel and re-runs its blur, lens and depth
+ // effect once per frame. It is bought deliberately: the alternative is the list snapping
+ // shut, and ~200 ms of re-blur on one panel is the cheapest way to avoid that. It is
+ // affordable only because everything else in the delete was made free — see [RowMetrics]
+ // for the recomposition storm that used to run alongside it.
+ .layout { measurable, constraints ->
+ val placeable = measurable.measure(constraints)
+ val h = (placeable.height * collapse.value).roundToInt().coerceAtLeast(0)
+ layout(placeable.width, h) { placeable.place(0, 0) }
+ }
+ // Read inside the lambda, so the fade invalidates draw only. Wraps both the slab and
+ // the card, which is the whole point — see [exitAlpha].
+ .graphicsLayer { alpha = exitAlpha.value }
.clip(RoundedCornerShape(16.dp))
.onGloballyPositioned {
- rowTopY = it.localToRoot(androidx.compose.ui.geometry.Offset.Zero).y
- rowHeightPx = it.size.height.toFloat()
- rowWidthPx = it.size.width.toFloat().coerceAtLeast(1f)
+ metrics.topY = it.localToRoot(androidx.compose.ui.geometry.Offset.Zero).y
+ metrics.height = it.size.height.toFloat()
+ metrics.width = it.size.width.toFloat().coerceAtLeast(1f)
}
) {
// The delete slab behind the row. Every read of `swipeX` here happens inside a draw
@@ -765,10 +865,9 @@ private fun RecentRow(
.matchParentSize()
.graphicsLayer { alpha = if (swipeX.value < 0f) 1f else 0f }
.drawBehind {
- // Deepens once the swipe is past the commit threshold, so the row tells you it
- // will delete before you let go.
- val armed = -swipeX.value > size.width * 0.40f
- drawRect(Color(0xFFE53935).copy(if (armed) 0.92f else 0.55f))
+ // Pale for the first quarter of the travel, solid red from there on. See
+ // [swipeRed] — the ramp is deliberately much earlier than the commit point.
+ drawRect(swipeRed(-swipeX.value, size.width))
},
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.End
@@ -776,7 +875,19 @@ private fun RecentRow(
Icon(
Icons.Rounded.DeleteOutline,
stringResource(R.string.recents_swipe_delete),
- Modifier.padding(end = 20.dp).size(22.dp),
+ Modifier
+ .padding(end = 20.dp)
+ .size(22.dp)
+ // Reads `swipeX` inside the layer block, so the drag invalidates draw only.
+ .graphicsLayer {
+ val travel = -swipeX.value
+ val w = metrics.width
+ val t = armProgress(travel, w)
+ val s = 0.82f + 0.33f * t
+ scaleX = s; scaleY = s
+ // Without this the icon is fully formed after one pixel of drag.
+ alpha = (travel / (w * 0.12f)).coerceIn(0f, 1f)
+ },
Color.White
)
}
@@ -795,30 +906,86 @@ private fun RecentRow(
interactionSource = rowInteraction,
indication = null,
onClick = onClick,
- onLongClick = { onLongClick(rowTopY, rowHeightPx) }
+ onLongClick = { onLongClick(metrics.topY, metrics.height) }
)
// A pinned row is an explicit "keep this" — it doesn't swipe away.
.then(
- if (recent.pinned) Modifier else Modifier.pointerInput(rowWidthPx) {
+ if (recent.pinned) Modifier else Modifier.pointerInput(Unit) {
+ val velocityTracker = VelocityTracker()
+ // Both live in the gesture scope, not in composition, so neither the arming
+ // tick nor the drag itself recomposes the row.
+ var wasArmed = false
+ // The authoritative drag offset. Reading it back off `swipeX` instead was a
+ // lag bug: `snapTo` is suspending, so it lands on the next dispatch, and
+ // every pointer event that arrived in the same frame computed its target
+ // from the same stale value — the row fell behind a fast finger.
+ var offset = 0f
detectHorizontalDragGestures(
+ onDragStart = {
+ velocityTracker.resetTracking()
+ wasArmed = false
+ offset = swipeX.value
+ },
onDragEnd = {
- if (-swipeX.value > rowWidthPx * 0.40f) {
+ val vx = velocityTracker.calculateVelocity().x
+ val commitAt = metrics.width * SwipeCommitFraction
+ // Commit on distance OR on a fast flick. Requiring 40% of the row
+ // every time made a quick, confident swipe spring back.
+ if (-offset > commitAt || vx < -900f) {
view.performHapticFeedback(HapticFeedbackConstants.CONFIRM)
scope.launch {
- swipeX.animateTo(-rowWidthPx, tween(160, easing = FastOutSlowInEasing))
+ // 1. Settle to a definite armed position and STAY there. The
+ // card is still on screen, sitting on full red, so the
+ // delete is acknowledged before anything is taken away. A
+ // distance commit is already past this, so for those this
+ // is a no-op; a flick commit slides in to meet it.
+ val hold = minOf(offset, -metrics.width * SwipeCommitFraction)
+ swipeX.animateTo(hold, tween(120, easing = FastOutSlowInEasing))
+ // 2. Fade the card+slab out FAST and as one object, THEN
+ // collapse the now-invisible row to close the gap.
+ //
+ // The collapse resizes the recents `liquidGlassPanel`, which
+ // re-runs its blur+lens+depth shader EVERY frame it animates —
+ // and hiding the row (exitAlpha≈0) hides that visually but does
+ // NOT make the shader free, so a long spring tail was burning
+ // ~300ms of full-panel re-blur for sub-pixel height deltas: the
+ // visible lag. A short, tail-free tween keeps the gap-close
+ // smooth while shrinking that re-blur window to a handful of
+ // frames. `FastOutLinearInEasing` front-loads the motion so it
+ // reads as an immediate close, not a drawn-out shrink.
+ exitAlpha.animateTo(0f, tween(120, easing = FastOutLinearInEasing))
+ collapse.animateTo(0f, tween(120, easing = FastOutLinearInEasing))
+ // Row is zero-height and invisible by now, so the removal's
+ // relayout can't land mid-animation. Persistence itself is
+ // handed to IO inside onSwipeDelete.
onSwipeDelete()
}
} else {
- scope.launch { swipeX.animateTo(0f, spring(dampingRatio = 0.8f, stiffness = 500f)) }
+ scope.launch { swipeX.animateTo(0f, spring(dampingRatio = 0.68f, stiffness = 420f)) }
}
},
onDragCancel = {
- scope.launch { swipeX.animateTo(0f, spring(dampingRatio = 0.8f, stiffness = 500f)) }
+ scope.launch { swipeX.animateTo(0f, spring(dampingRatio = 0.68f, stiffness = 420f)) }
}
) { change, dragAmount ->
// Consume horizontal only, so the LazyColumn keeps its vertical scroll.
change.consume()
- scope.launch { swipeX.snapTo((swipeX.value + dragAmount).coerceIn(-rowWidthPx, 0f)) }
+ velocityTracker.addPosition(change.uptimeMillis, change.position)
+ val width = metrics.width
+ val commitAt = width * SwipeCommitFraction
+ // Past the commit point the row gets heavier — further travel moves it
+ // at a third speed. The threshold becomes something you feel through the
+ // resistance rather than a number you cross blind.
+ val resisted =
+ if (-offset > commitAt && dragAmount < 0f) dragAmount * 0.32f else dragAmount
+ offset = (offset + resisted).coerceIn(-width, 0f)
+ val nowArmed = -offset > commitAt
+ if (nowArmed != wasArmed) {
+ wasArmed = nowArmed
+ view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
+ }
+ val target = offset
+ scope.launch { swipeX.snapTo(target) }
}
}
)
@@ -857,8 +1024,27 @@ private fun RecentRow(
BasicText("$timeStr$sizeStr$countStr", style = TextStyle(secondaryColor, 11.sp))
}
+ // Pinned marker. A bare floating glyph read like a stray icon; contain it in the same
+ // kind of translucent tinted chip the rest of the app uses so it reads as an
+ // intentional status badge. The pin leans slightly, the way a real one sits.
if (recent.pinned) {
- Icon(Icons.Rounded.PushPin, stringResource(R.string.recents_unpin), Modifier.size(13.dp), Color(0xFFFF9500))
+ val pinOrange = Color(0xFFFF9500)
+ Box(
+ Modifier
+ .size(24.dp)
+ .clip(RoundedCornerShape(50))
+ .background(pinOrange.copy(alpha = if (isLight) 0.16f else 0.24f)),
+ contentAlignment = Alignment.Center
+ ) {
+ Icon(
+ Icons.Rounded.PushPin,
+ stringResource(R.string.recents_unpin),
+ Modifier
+ .size(13.dp)
+ .graphicsLayer { rotationZ = -30f },
+ pinOrange
+ )
+ }
}
Box(
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/OnboardingScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/OnboardingScreen.kt
new file mode 100644
index 0000000..8735463
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/OnboardingScreen.kt
@@ -0,0 +1,744 @@
+package com.chethan616.clearpdf.ui.screen
+
+import android.content.Intent
+import android.net.Uri
+import androidx.activity.compose.BackHandler
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.animation.core.FastOutSlowInEasing
+import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.animation.core.tween
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.navigationBarsPadding
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.statusBarsPadding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.pager.HorizontalPager
+import androidx.compose.foundation.pager.rememberPagerState
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.text.BasicText
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.automirrored.rounded.CallSplit
+import androidx.compose.material.icons.automirrored.rounded.MergeType
+import androidx.compose.material.icons.rounded.Compress
+import androidx.compose.material.icons.rounded.DarkMode
+import androidx.compose.material.icons.rounded.LightMode
+import androidx.compose.material.icons.rounded.PhoneAndroid
+import androidx.compose.material.icons.rounded.PhotoLibrary
+import androidx.compose.material.icons.rounded.Refresh
+import androidx.compose.material.icons.rounded.Wallpaper
+import androidx.compose.material3.Icon
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.graphics.vector.ImageVector
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.platform.LocalDensity
+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
+import androidx.compose.ui.util.lerp
+import com.chethan616.clearpdf.R
+import com.chethan616.clearpdf.data.repository.AppSettingsManager
+import com.chethan616.clearpdf.ui.components.DemoAnnotate
+import com.chethan616.clearpdf.ui.components.DemoDocumentOpen
+import com.chethan616.clearpdf.ui.components.DemoFileKinds
+import com.chethan616.clearpdf.ui.components.DemoReady
+import com.chethan616.clearpdf.ui.components.DemoSearch
+import com.chethan616.clearpdf.ui.components.DemoToolsMenu
+import com.chethan616.clearpdf.ui.components.GlassMenuAction
+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.LiquidToggle
+import com.chethan616.clearpdf.ui.components.viewerChromeGlass
+import com.chethan616.clearpdf.ui.components.viewerGlass
+import com.chethan616.clearpdf.ui.theme.LiquidGlassColors
+import com.chethan616.clearpdf.ui.theme.LocalIsDarkMode
+import com.chethan616.clearpdf.ui.utils.rememberUISensor
+import com.kyant.backdrop.backdrops.LayerBackdrop
+import com.kyant.shapes.Capsule
+import kotlinx.coroutines.launch
+
+private const val PageCount = 6
+
+/**
+ * First-run tour. Six pages, each explaining a feature by **replaying the app's own animation** for
+ * it rather than showing a picture of it — see `OnboardingDemos.kt`.
+ *
+ * Two structural decisions drive the layout:
+ *
+ * **The chrome lives outside the pager.** `HorizontalPager` positions pages by layout offset, so a
+ * glass surface inside a page moves relative to its backdrop on every frame of a swipe, and
+ * `drawBackdrop` re-runs its blur and lens each time. Keeping the CTA, the dots and Skip stationary
+ * means a swipe only ever drags the one glass surface a page genuinely needs.
+ *
+ * **Only the current page animates.** The pager composes its neighbours ahead of time, so each demo
+ * is gated on `isActive` — otherwise all five loops run at once, off-screen, for the whole flow.
+ *
+ * The language page changes [selectedLocale] *in place*: the caller re-provides `LocalResources`, so
+ * every `stringResource` below re-resolves and the remaining pages translate without an Activity
+ * restart. That only holds while this file avoids `context.getString`, which it does.
+ *
+ * The appearance page is the same idea one step further — [themeMode] and [showWallpaper] are the
+ * app's real hoisted state, so changing them here re-tints the tour itself as you tap. That is the
+ * whole point of putting the page here rather than in Settings: the glass is the product, and the
+ * fastest way to teach it is to let the user watch it react.
+ */
+@Composable
+fun OnboardingScreen(
+ backdrop: LayerBackdrop,
+ selectedLocale: String,
+ onLocaleSelected: (String) -> Unit,
+ themeMode: Int,
+ onThemeModeChanged: (Int) -> Unit,
+ showWallpaper: Boolean,
+ onShowWallpaperChanged: (Boolean) -> Unit,
+ hasCustomWallpaper: Boolean,
+ onCustomWallpaperChanged: (String?) -> Unit,
+ onFinish: () -> Unit
+) {
+ val isDark = LocalIsDarkMode.current
+ val uiSensor = rememberUISensor()
+ val scope = rememberCoroutineScope()
+ val pagerState = rememberPagerState(pageCount = { PageCount })
+
+ val ink = LiquidGlassColors.text(isDark)
+ val inkSoft = LiquidGlassColors.secondary(isDark)
+ // Higher alpha than the viewers' chrome tint: onboarding floats over the wallpaper rather than
+ // over a document, and at this recipe's 2 dp blur the wallpaper comes through nearly sharp.
+ val glass = if (isDark) Color(0xFF20242C).copy(0.80f) else Color.White.copy(0.72f)
+
+ val last = pagerState.currentPage == PageCount - 1
+
+ // Back steps through the flow. Deliberately DISABLED on page one rather than consumed there: on
+ // a first run that leaves the system default (exit the app, tour returns next launch), and on a
+ // replay from Settings it falls through to the nav host and returns to Settings. Consuming it
+ // would make back silently dead on the first page in both cases.
+ BackHandler(enabled = pagerState.currentPage > 0) {
+ scope.launch { pagerState.animateScrollToPage(pagerState.currentPage - 1) }
+ }
+
+ val advance: () -> Unit = {
+ if (last) {
+ onFinish()
+ } else {
+ scope.launch { pagerState.animateScrollToPage(pagerState.currentPage + 1) }
+ }
+ Unit
+ }
+
+ Box(Modifier.fillMaxSize()) {
+
+ HorizontalPager(
+ state = pagerState,
+ modifier = Modifier.fillMaxSize()
+ ) { page ->
+ val isActive = pagerState.currentPage == page
+ OnboardingPage(
+ page = page,
+ isActive = isActive,
+ backdrop = backdrop,
+ uiSensor = uiSensor,
+ glass = glass,
+ ink = ink,
+ inkSoft = inkSoft,
+ selectedLocale = selectedLocale,
+ onLocaleSelected = onLocaleSelected,
+ themeMode = themeMode,
+ onThemeModeChanged = onThemeModeChanged,
+ showWallpaper = showWallpaper,
+ onShowWallpaperChanged = onShowWallpaperChanged,
+ hasCustomWallpaper = hasCustomWallpaper,
+ onCustomWallpaperChanged = onCustomWallpaperChanged,
+ isDark = isDark
+ )
+ }
+
+ // ── Stationary chrome ───────────────────────────────────────────────────────────────────
+ // Skip fades out on the last page instead of being removed, so the row above the pager does
+ // not reflow underneath the swipe.
+ val skipAlpha by animateFloatAsState(
+ if (last) 0f else 1f,
+ tween(220, easing = FastOutSlowInEasing),
+ label = "onboardingSkipAlpha"
+ )
+ Row(
+ Modifier
+ .align(Alignment.TopEnd)
+ .statusBarsPadding()
+ .padding(horizontal = 20.dp, vertical = 12.dp)
+ .graphicsLayer { alpha = skipAlpha },
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ if (!last) {
+ LiquidButton(
+ onClick = onFinish,
+ backdrop = backdrop,
+ // The viewers' chrome tint, not the page's `glass`. Both are the same minimal
+ // recipe, so the difference is purely opacity: at 0.80/0.72 the panels behind
+ // the demos need to hold small text, but a bare Skip capsule at that weight
+ // reads as a painted pill — the lens has nothing to refract. Dropping to the
+ // viewers' 0.70/0.55 is what makes it look like the buttons it is quoting.
+ surfaceColor = viewerChromeGlass(isDark)
+ ) {
+ BasicText(
+ stringResource(R.string.onboarding_skip),
+ style = TextStyle(ink, 14.sp, fontWeight = FontWeight.SemiBold),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+ }
+
+ Column(
+ Modifier
+ .align(Alignment.BottomCenter)
+ .fillMaxWidth()
+ .navigationBarsPadding()
+ .padding(horizontal = 28.dp)
+ .padding(bottom = 28.dp),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(18.dp)
+ ) {
+ PageDots(current = pagerState.currentPage, count = PageCount, ink = ink)
+
+ // `ink`, not `inkSoft`. Everything in this Column sits directly on the wallpaper with no
+ // glass under it, and the secondary token is a mid grey that has to survive on whatever
+ // photo is behind it. Full-strength ink (near-white on dark, near-black on light) is the
+ // only value that holds in both, so the hierarchy is carried by size and weight instead.
+ BasicText(
+ stringResource(R.string.onboarding_step, pagerState.currentPage + 1, PageCount),
+ style = TextStyle(ink.copy(0.8f), 12.sp, fontWeight = FontWeight.Medium),
+ maxLines = 1
+ )
+
+ LiquidButton(
+ onClick = advance,
+ backdrop = backdrop,
+ tint = Color(0xFF0088FF),
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ // Cross-faded rather than swapped: the label changes on the last page and a hard
+ // swap inside a capsule that is not resizing reads as a glitch.
+ val ctaProgress by animateFloatAsState(
+ if (last) 1f else 0f,
+ GlassMotion.fade(),
+ label = "onboardingCta"
+ )
+ Box(contentAlignment = Alignment.Center) {
+ if (ctaProgress < 0.999f) {
+ BasicText(
+ stringResource(R.string.onboarding_cta_continue),
+ style = TextStyle(Color.White, 16.sp, fontWeight = FontWeight.Bold),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.graphicsLayer { alpha = 1f - ctaProgress }
+ )
+ }
+ if (ctaProgress > 0.001f) {
+ BasicText(
+ stringResource(R.string.onboarding_cta_get_started),
+ style = TextStyle(Color.White, 16.sp, fontWeight = FontWeight.Bold),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.graphicsLayer { alpha = ctaProgress }
+ )
+ }
+ }
+ }
+ }
+ }
+}
+
+/** Flat pills — no glass — so the active one can stretch without costing a blur pass. */
+@Composable
+private fun PageDots(current: Int, count: Int, ink: Color) {
+ Row(horizontalArrangement = Arrangement.spacedBy(7.dp)) {
+ repeat(count) { i ->
+ val active = i == current
+ val w by animateFloatAsState(
+ if (active) 22f else 7f,
+ GlassMotion.settle(),
+ label = "dotWidth$i"
+ )
+ val a by animateFloatAsState(
+ if (active) 0.9f else 0.28f,
+ GlassMotion.fade(),
+ label = "dotAlpha$i"
+ )
+ Box(
+ Modifier
+ .width(w.dp)
+ .height(7.dp)
+ .clip(CircleShape)
+ .background(ink.copy(a))
+ )
+ }
+ }
+}
+
+@Composable
+private fun OnboardingPage(
+ page: Int,
+ isActive: Boolean,
+ backdrop: LayerBackdrop,
+ uiSensor: com.chethan616.clearpdf.ui.utils.UISensor,
+ glass: Color,
+ ink: Color,
+ inkSoft: Color,
+ selectedLocale: String,
+ onLocaleSelected: (String) -> Unit,
+ themeMode: Int,
+ onThemeModeChanged: (Int) -> Unit,
+ showWallpaper: Boolean,
+ onShowWallpaperChanged: (Boolean) -> Unit,
+ hasCustomWallpaper: Boolean,
+ onCustomWallpaperChanged: (String?) -> Unit,
+ isDark: Boolean
+) {
+ val title: String
+ val subtitle: String
+ when (page) {
+ 0 -> { title = stringResource(R.string.onboarding_welcome_title); subtitle = stringResource(R.string.onboarding_welcome_subtitle) }
+ 1 -> { title = stringResource(R.string.onboarding_language_title); subtitle = stringResource(R.string.onboarding_language_subtitle) }
+ 2 -> { title = stringResource(R.string.onboarding_appearance_title); subtitle = stringResource(R.string.onboarding_appearance_subtitle) }
+ 3 -> { title = stringResource(R.string.onboarding_files_title); subtitle = stringResource(R.string.onboarding_files_subtitle) }
+ 4 -> { title = stringResource(R.string.onboarding_features_title); subtitle = stringResource(R.string.onboarding_features_subtitle) }
+ else -> { title = stringResource(R.string.onboarding_ready_title); subtitle = stringResource(R.string.onboarding_ready_subtitle) }
+ }
+
+ // Copy rises in behind the demo on every visit, so paging back and forth feels alive rather than
+ // landing on a static slab. Draw-time properties only.
+ val enter by animateFloatAsState(
+ if (isActive) 1f else 0f,
+ tween(360, easing = FastOutSlowInEasing),
+ label = "pageEnter"
+ )
+ val density = LocalDensity.current.density
+
+ Column(
+ Modifier
+ .fillMaxSize()
+ .statusBarsPadding()
+ // Top clears the Skip capsule; bottom clears the dots + step counter + CTA.
+ .padding(horizontal = 32.dp)
+ .padding(top = 56.dp, bottom = 170.dp),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.Center
+ ) {
+ Box(Modifier.weight(1f), contentAlignment = Alignment.Center) {
+ when (page) {
+ 0 -> DemoDocumentOpen(isActive, backdrop, glass, ink)
+ 1 -> LanguageChooser(backdrop, glass, ink, inkSoft, selectedLocale, onLocaleSelected, isDark)
+ 2 -> AppearanceChooser(
+ backdrop, glass, ink, inkSoft, isDark,
+ themeMode, onThemeModeChanged, showWallpaper, onShowWallpaperChanged,
+ hasCustomWallpaper, onCustomWallpaperChanged
+ )
+ 3 -> DemoFileKinds(isActive, backdrop, glass, ink, inkSoft)
+ 4 -> FeatureRows(isActive, backdrop, uiSensor, glass, ink, inkSoft)
+ else -> DemoReady(isActive, backdrop, glass)
+ }
+ }
+
+ Spacer(Modifier.height(28.dp))
+
+ Column(
+ Modifier.graphicsLayer {
+ alpha = enter
+ translationY = lerp(16f, 0f, enter) * density
+ },
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ BasicText(
+ title,
+ style = TextStyle(ink, 27.sp, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center)
+ )
+ // Also `ink` — see the step counter's note. This block is the largest run of text in the
+ // app with nothing but wallpaper behind it.
+ BasicText(
+ subtitle,
+ style = TextStyle(ink.copy(0.86f), 15.sp, textAlign = TextAlign.Center, lineHeight = 21.sp)
+ )
+ if (page == PageCount - 1) {
+ Spacer(Modifier.height(4.dp))
+ Box(
+ Modifier
+ .viewerGlass(backdrop, glass, shape = { Capsule })
+ .padding(horizontal = 14.dp, vertical = 8.dp)
+ ) {
+ BasicText(
+ stringResource(R.string.onboarding_privacy_badge),
+ style = TextStyle(inkSoft, 11.sp, fontWeight = FontWeight.Medium, textAlign = TextAlign.Center)
+ )
+ }
+ }
+ }
+ }
+}
+
+/**
+ * Page 2 is the only interactive one — the real segmented control from Settings, not a replay.
+ *
+ * Selecting here does **not** restart the Activity; the caller updates the hoisted locale state and
+ * re-provides `LocalResources`, so this whole screen re-composes translated. The restart, if the
+ * choice actually changed anything, is deferred to "Get Started".
+ */
+@Composable
+private fun LanguageChooser(
+ backdrop: LayerBackdrop,
+ glass: Color,
+ ink: Color,
+ inkSoft: Color,
+ selectedLocale: String,
+ onLocaleSelected: (String) -> Unit,
+ isDark: Boolean
+) {
+ val accent = Color(0xFF0088FF)
+ Column(
+ Modifier
+ .fillMaxWidth()
+ .viewerGlass(backdrop, glass)
+ .padding(20.dp),
+ verticalArrangement = Arrangement.spacedBy(14.dp)
+ ) {
+ BasicText(
+ stringResource(R.string.onboarding_language_label),
+ style = TextStyle(inkSoft, 13.sp, fontWeight = FontWeight.SemiBold)
+ )
+ listOf("en" to R.string.language_english, "pt-BR" to R.string.language_portuguese).forEach { (code, res) ->
+ val selected = selectedLocale == code
+ LiquidButton(
+ onClick = { onLocaleSelected(code) },
+ backdrop = backdrop,
+ tint = if (selected) accent else Color.Unspecified,
+ surfaceColor = if (selected) Color.Unspecified else (if (isDark) Color.White.copy(0.10f) else Color.Black.copy(0.06f)),
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ BasicText(
+ stringResource(res),
+ style = TextStyle(
+ if (selected) Color.White else ink,
+ 15.sp,
+ fontWeight = if (selected) FontWeight.Bold else FontWeight.Medium
+ ),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+ }
+}
+
+/**
+ * Page 3 — theme and background, the second interactive page.
+ *
+ * Both controls write straight through to the app's real hoisted state, so the tour re-themes under
+ * the user's finger: the panel they just tapped is itself glass over the wallpaper, which makes this
+ * the one place in the app where the setting and its preview are the same pixels. Turning the
+ * background off here is also the honest way to show what that does — the demos on the later pages
+ * are the exact surfaces affected.
+ *
+ * Mirrors `SettingsScreen`'s appearance section (`:279-320`, `:578-587`) rather than sharing code
+ * with it: that section is embedded in a scrolling settings layout with its own panel chrome and
+ * cascade offsets, and lifting it out would mean parameterising it for two very different hosts.
+ */
+@Composable
+private fun AppearanceChooser(
+ backdrop: LayerBackdrop,
+ glass: Color,
+ ink: Color,
+ inkSoft: Color,
+ isDark: Boolean,
+ themeMode: Int,
+ onThemeModeChanged: (Int) -> Unit,
+ showWallpaper: Boolean,
+ onShowWallpaperChanged: (Boolean) -> Unit,
+ hasCustomWallpaper: Boolean,
+ onCustomWallpaperChanged: (String?) -> Unit
+) {
+ val context = LocalContext.current
+ // Same contract Settings uses: `OpenDocument` plus a persisted read grant, because the chosen
+ // image has to survive the restart that finishing the tour may trigger.
+ val wallpaperPicker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri: Uri? ->
+ if (uri != null) {
+ runCatching {
+ context.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ }
+ AppSettingsManager.setCustomWallpaper(context, uri.toString())
+ onCustomWallpaperChanged(uri.toString())
+ }
+ }
+
+ data class ThemeOption(val idx: Int, val label: String, val icon: ImageVector, val accent: Color)
+ val options = listOf(
+ ThemeOption(0, stringResource(R.string.settings_theme_auto), Icons.Rounded.PhoneAndroid, Color(0xFF0088FF)),
+ ThemeOption(1, stringResource(R.string.settings_theme_light), Icons.Rounded.LightMode, Color(0xFFFFA726)),
+ ThemeOption(2, stringResource(R.string.settings_theme_dark), Icons.Rounded.DarkMode, Color(0xFF7C4DFF))
+ )
+
+ // Tighter than the language page's 20/14 on purpose. This panel now carries six rows, and the
+ // demo area it sits in is a `weight(1f)` box between fixed top and bottom padding — around
+ // 275 dp on a 640 dp-tall phone. At 20/14 the gallery row pushed it past that and the panel
+ // clipped rather than the page scrolling.
+ Column(
+ Modifier
+ .fillMaxWidth()
+ .viewerGlass(backdrop, glass)
+ .padding(18.dp),
+ verticalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ BasicText(
+ stringResource(R.string.settings_appearance),
+ style = TextStyle(inkSoft, 13.sp, fontWeight = FontWeight.SemiBold)
+ )
+
+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ options.forEach { option ->
+ val selected = themeMode == option.idx
+ val cc = if (selected) Color.White else ink
+ LiquidButton(
+ onClick = { onThemeModeChanged(option.idx) },
+ backdrop = backdrop,
+ tint = if (selected) option.accent else Color.Unspecified,
+ surfaceColor = if (selected) Color.Unspecified else (if (isDark) Color.White.copy(0.10f) else Color.Black.copy(0.06f)),
+ modifier = Modifier.weight(1f)
+ ) {
+ // Icon above label rather than beside it: three segments across a 32dp-inset page
+ // leaves ~80dp each, and "Escuro"/"Claro" next to a 16dp icon clips in pt-BR.
+ Column(
+ Modifier.fillMaxWidth(),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(4.dp)
+ ) {
+ Icon(option.icon, null, Modifier.size(18.dp), cc)
+ BasicText(
+ option.label,
+ style = TextStyle(cc, 12.sp, fontWeight = if (selected) FontWeight.Bold else FontWeight.Medium),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+ }
+ }
+
+ BasicText(
+ when (themeMode) {
+ 1 -> stringResource(R.string.settings_theme_light_desc)
+ 2 -> stringResource(R.string.settings_theme_dark_desc)
+ else -> stringResource(R.string.settings_theme_auto_desc)
+ },
+ style = TextStyle(inkSoft.copy(0.8f), 12.sp),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+
+ Box(Modifier.fillMaxWidth().height(1.dp).background(ink.copy(0.10f)))
+
+ Row(
+ Modifier.fillMaxWidth(),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ Icon(Icons.Rounded.Wallpaper, null, Modifier.size(20.dp), inkSoft)
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ BasicText(
+ stringResource(R.string.settings_background),
+ style = TextStyle(ink, 14.sp, fontWeight = FontWeight.SemiBold),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ BasicText(
+ stringResource(R.string.settings_background_desc),
+ style = TextStyle(inkSoft, 12.sp, lineHeight = 16.sp),
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ LiquidToggle(
+ selected = { showWallpaper },
+ onSelect = onShowWallpaperChanged,
+ backdrop = backdrop
+ )
+ }
+
+ // Only while the background is actually on, and only one control wide — the brief was "don't
+ // make it too cluttered", and a picker for a background that is switched off is a row the
+ // user has to read past to find out it does nothing. Reset joins it only once there is
+ // something to reset, so the common case stays a single button.
+ if (showWallpaper) {
+ Row(
+ Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ LiquidButton(
+ onClick = { wallpaperPicker.launch(arrayOf("image/*")) },
+ backdrop = backdrop,
+ surfaceColor = if (isDark) Color.White.copy(0.10f) else Color.Black.copy(0.06f),
+ modifier = Modifier.weight(1f)
+ ) {
+ Row(
+ Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(7.dp, Alignment.CenterHorizontally),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Icon(Icons.Rounded.PhotoLibrary, null, Modifier.size(15.dp), ink)
+ BasicText(
+ stringResource(R.string.settings_bg_gallery),
+ style = TextStyle(ink, 13.sp, fontWeight = FontWeight.SemiBold),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+ if (hasCustomWallpaper) {
+ LiquidIconButton(
+ onClick = {
+ AppSettingsManager.clearCustomWallpaper(context)
+ onCustomWallpaperChanged(null)
+ },
+ backdrop = backdrop,
+ surfaceColor = if (isDark) Color.White.copy(0.10f) else Color.Black.copy(0.06f),
+ modifier = Modifier.size(40.dp)
+ ) {
+ Icon(Icons.Rounded.Refresh, stringResource(R.string.settings_reset), Modifier.size(17.dp), inkSoft)
+ }
+ }
+ }
+ }
+ }
+}
+
+/**
+ * Page 5: the three headline features. The first two are compact rows with a micro-demo in their
+ * leading slot; the third is a full-width showcase.
+ *
+ * **Why the third one breaks the row shape.** `GlassCapsuleMenu` is a horizontal `Row` of 40dp
+ * circles — 152dp wide with three actions. A 72dp leading slot constrains it to 72dp, and a `Row`
+ * that runs out of width does not wrap or shrink, it measures the overflow at zero: the demo
+ * rendered as a lone Merge button with the other two actions silently gone. Scaling it down with a
+ * `graphicsLayer` would not have fixed the measurement either, and would have composited the glass
+ * at less than half size so its blur and lens read at the wrong scale. Giving it the panel's full
+ * width instead lets the real component measure at its real size, which is the only way this demo is
+ * worth showing at all — it is the one production animation onboarding plays literally.
+ *
+ * All of it shares one glass panel: four separate glass surfaces would cost four blur passes for no
+ * visual gain, the same reasoning `GlassCapsuleMenu` and `ToolSectionPanel` already follow.
+ */
+@Composable
+private fun FeatureRows(
+ isActive: Boolean,
+ backdrop: LayerBackdrop,
+ uiSensor: com.chethan616.clearpdf.ui.utils.UISensor,
+ glass: Color,
+ ink: Color,
+ inkSoft: Color
+) {
+ val toolActions = remember {
+ listOf(
+ GlassMenuAction(Icons.AutoMirrored.Rounded.MergeType, "Merge", LiquidGlassColors.Red) {},
+ GlassMenuAction(Icons.AutoMirrored.Rounded.CallSplit, "Split", LiquidGlassColors.Purple) {},
+ GlassMenuAction(Icons.Rounded.Compress, "Compress", LiquidGlassColors.Green) {}
+ )
+ }
+
+ Column(
+ Modifier
+ .fillMaxWidth()
+ .viewerGlass(backdrop, glass)
+ .padding(vertical = 14.dp, horizontal = 16.dp),
+ verticalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ FeatureRow(
+ title = stringResource(R.string.feature_annotate_title),
+ desc = stringResource(R.string.feature_annotate_desc),
+ ink = ink, inkSoft = inkSoft
+ ) { DemoAnnotate(isActive, ink) }
+
+ FeatureRow(
+ title = stringResource(R.string.feature_search_title),
+ desc = stringResource(R.string.feature_search_desc),
+ ink = ink, inkSoft = inkSoft
+ ) { DemoSearch(isActive, backdrop, glass, ink) }
+
+ // A hairline before the shape changes, so the wider third entry reads as deliberate emphasis
+ // rather than a row that failed to line up with the two above it.
+ Box(Modifier.fillMaxWidth().height(1.dp).background(ink.copy(0.10f)))
+
+ Column(verticalArrangement = Arrangement.spacedBy(3.dp)) {
+ BasicText(
+ stringResource(R.string.feature_tools_title),
+ style = TextStyle(ink, 15.sp, fontWeight = FontWeight.SemiBold),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ BasicText(
+ stringResource(R.string.feature_tools_desc),
+ style = TextStyle(inkSoft, 12.5.sp, lineHeight = 17.sp),
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ Box(
+ Modifier.fillMaxWidth().padding(top = 2.dp),
+ contentAlignment = Alignment.Center
+ ) {
+ DemoToolsMenu(isActive, backdrop, uiSensor, glass, toolActions)
+ }
+ }
+}
+
+@Composable
+private fun FeatureRow(
+ title: String,
+ desc: String,
+ ink: Color,
+ inkSoft: Color,
+ demo: @Composable () -> Unit
+) {
+ Row(
+ Modifier.fillMaxWidth(),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(14.dp)
+ ) {
+ demo()
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
+ BasicText(
+ title,
+ style = TextStyle(ink, 15.sp, fontWeight = FontWeight.SemiBold),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ BasicText(
+ desc,
+ style = TextStyle(inkSoft, 12.5.sp, lineHeight = 17.sp),
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+}
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 fb90f8e..3d06b4f 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
@@ -87,6 +87,8 @@ internal fun PdfContinuousPage(
pageCanvasSizes: SnapshotStateMap<Int, Size>,
pageBitmapSizes: SnapshotStateMap<Int, Size>,
onInteraction: () -> Unit,
+ /** A stroke/shape just landed on this page. Feeds the viewer's undo history. */
+ onMarkAdded: () -> Unit = {},
onToggleControls: () -> Unit,
onShowControls: () -> Unit,
onActiveToolChanged: (PdfEditTool) -> Unit,
@@ -419,6 +421,7 @@ internal fun PdfContinuousPage(
onDrag = { ch, _ -> ch.consume(); if (freehand) draftPoints = draftPoints + ch.position else draftRectEnd = ch.position },
onDragCancel = { draftPoints = emptyList(); draftRectStart = null; draftRectEnd = null },
onDragEnd = {
+ val before = marks.size
when (activeTool) {
PdfEditTool.Draw -> if (draftPoints.size > 1) marks.add(PdfMarkup.StrokeMarkup(draftPoints, currentColor, currentStrokeWidth, 0.95f))
PdfEditTool.Highlight -> if (draftPoints.size > 1) marks.add(PdfMarkup.StrokeMarkup(draftPoints, currentColor, currentStrokeWidth * 3.5f, 0.32f))
@@ -428,6 +431,9 @@ internal fun PdfContinuousPage(
PdfEditTool.Arrow -> draftRectStart?.let { s -> draftRectEnd?.let { e -> marks.add(PdfMarkup.LineMarkup(s, e, currentColor, currentStrokeWidth, 1f, true)) } }
else -> Unit
}
+ // Every branch above is conditional (a tap with <2 points adds nothing), so
+ // compare sizes rather than assuming the drag produced a mark.
+ if (marks.size > before) onMarkAdded()
draftPoints = emptyList(); draftRectStart = null; draftRectEnd = null
}
)
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 36ed963..4174fc5 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
@@ -2,11 +2,13 @@ package com.chethan616.clearpdf.ui.screen
import android.net.Uri
import androidx.compose.animation.AnimatedVisibility
-import androidx.compose.animation.ExitTransition
+import androidx.compose.animation.EnterExitState
import androidx.compose.animation.Crossfade
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateDpAsState
+import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress
@@ -82,11 +84,19 @@ import com.chethan616.clearpdf.ui.components.CloseCrossIcon
import com.chethan616.clearpdf.ui.components.LiquidButton
import com.chethan616.clearpdf.ui.components.LiquidIconButton
import com.chethan616.clearpdf.ui.components.ShareMorphButton
+import com.chethan616.clearpdf.ui.components.carouselEdges
import com.chethan616.clearpdf.ui.components.viewerGlass
import com.chethan616.clearpdf.ui.utils.UISensor
import com.chethan616.clearpdf.utils.DocKind
import com.kyant.backdrop.backdrops.LayerBackdrop
+/**
+ * How long one face (selector or sub-toolbar) takes to fade out before the other fades in. The
+ * fade-out tweens use the same value, so the incoming face starts exactly as the outgoing one lands
+ * at alpha 0 — a clean sequential cross-fade with no overlap.
+ */
+private const val FaceHandoffMillis = 150
+
@Composable
internal fun PdfViewerBottomToolbar(
// display state
@@ -107,9 +117,13 @@ internal fun PdfViewerBottomToolbar(
selectedTextCount: Int,
currentSelectedIds: Set<String>,
activeIsSignature: Boolean,
- // marks for undo/clear (current page)
- currentPageMarks: MutableList<PdfMarkup>,
+ // 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
+ // was routinely the wrong one.
+ canUndo: Boolean,
// callbacks
+ onUndo: () -> Unit,
+ onClearPage: () -> Unit,
onSetActiveTool: (PdfEditTool) -> Unit,
onToggleFindBar: () -> Unit,
onShowSignaturePad: () -> Unit,
@@ -132,6 +146,10 @@ internal fun PdfViewerBottomToolbar(
onOpenAnotherPdf: () -> Unit,
onShareDocument: () -> Unit,
onEditorOpenChanged: (Boolean) -> Unit = {},
+ // Same purpose as [onEditorOpenChanged]: a long-press on the share capsule is a gesture the
+ // viewer cannot see, so without this the 5s chrome auto-hide fires mid-hold and takes the button
+ // out from under the finger.
+ onShareHoldChanged: (Boolean) -> Unit = {},
onRecolorSignature: (Long) -> Unit,
backdrop: LayerBackdrop,
uiSensor: UISensor,
@@ -146,10 +164,45 @@ internal fun PdfViewerBottomToolbar(
) {
val accent = Color(0xFF1976D2)
+ // The floating pills paint nothing at all, exactly as Home's controls do: `LiquidIconButton` is
+ // called there with no `surfaceColor`, so its `onDrawSurface` is a no-op and the button is pure
+ // refraction. `drawRect(Color.Transparent)` is the same no-op for the `viewerGlass` surfaces
+ // here. The header's back and search circles already work this way; without this the Editor
+ // Tools pill, the tool row and the share capsule were the only chrome left carrying a tint, and
+ // sitting beside clear circles they read as slabs.
+ //
+ // `glass` is deliberately still used for the *panels* (the draw/OCR/image sub-toolbar and the
+ // export-feedback strip): those are dense rows of controls that need a plate to sit on, and they
+ // cover the document rather than floating over it.
+ val pillGlass = Color.Transparent
+
val showDrawTools = drawingToolActive
val showOcrTools = activeTool == PdfEditTool.SelectText || selectedTextCount > 0
val 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
+ // 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
+ // face fade in — they never overlap in layout, which is also what used to make the sub-toolbar
+ // open on top and then visibly drop as the pill collapsed.
+ var selectorGate by remember { mutableStateOf(!subActive) }
+ var subGate by remember { mutableStateOf(subActive) }
+ LaunchedEffect(subActive) {
+ if (subActive) {
+ selectorGate = false // chips + Editor-Tools pill begin fading out
+ delay(FaceHandoffMillis.toLong()) // wait for them to clear
+ subGate = true // sub-toolbar fades in
+ } else {
+ subGate = false // sub-toolbar begins fading out
+ delay(FaceHandoffMillis.toLong())
+ selectorGate = true // chips + pill fade back in
+ }
+ }
+
// Collapsed by default (just the "Editor Tools" pill + "Open PDF" circle). Tapping
// the pill expands the tool set above it. Image selection auto-expands so its tools show.
var editorOpen by remember { mutableStateOf(false) }
@@ -173,7 +226,6 @@ internal fun PdfViewerBottomToolbar(
// Both are bottom-anchored: when the capsule morphs taller than the column, the WRAPPER grows
// (real layout height = strictly upward, no overflow/clip), while the column stays pinned to the
// bottom — so the tool panels and the "Editor Tools" pill never move.
- val shareRowVisible = !showDrawTools && !showOcrTools && !showImageTools && !showFindBar && !showSignaturePad
Box(Modifier.fillMaxWidth()) {
Column(
Modifier.fillMaxWidth().align(Alignment.BottomCenter),
@@ -184,14 +236,31 @@ internal fun PdfViewerBottomToolbar(
// Rises ABOVE the pinned main row with an Apple-style spring slide + fade.
// Only this panel moves, so re-blur is confined to one surface.
AnimatedVisibility(
- visible = editorOpen && (showDrawTools || showOcrTools || showImageTools) && !showFindBar && !showSignaturePad,
- // Grow UPWARD from the pinned "Editor Tools" bar (expandVertically from Bottom) so the
- // bar never moves. Spring physics (not a linear tween) give the liquid Apple feel.
- enter = fadeIn(tween(200)) + expandVertically(spring(dampingRatio = 0.82f, stiffness = Spring.StiffnessLow), expandFrom = Alignment.Bottom),
- exit = fadeOut(tween(140)) + shrinkVertically(spring(dampingRatio = 1f, stiffness = Spring.StiffnessMedium), shrinkTowards = Alignment.Bottom)
+ // `subGate` is delayed by [FaceHandoffMillis] after a sub-tool becomes active, so the
+ // selector face has already faded out before this fades in — the two never coexist.
+ visible = subGate && editorOpen && !showFindBar && !showSignaturePad,
+ // Fade only for the LAYOUT (one measure), and a draw-time bottom-anchored `scaleY` unfurl
+ // for the motion — the same technique as the Editor-Tools reveal. `expandVertically` here
+ // re-measured this `viewerGlass` panel every frame and re-ran its blur + lens with it,
+ // which is why the reveal read as rigid/instant rather than liquid.
+ enter = fadeIn(tween(200)),
+ exit = fadeOut(tween(FaceHandoffMillis))
) {
+ val reveal by transition.animateFloat(
+ transitionSpec = {
+ if (targetState == EnterExitState.Visible) spring(dampingRatio = 0.72f, stiffness = 300f)
+ else spring(dampingRatio = 1f, stiffness = Spring.StiffnessMedium)
+ },
+ label = "drawToolsReveal"
+ ) { if (it == EnterExitState.Visible) 1f else 0f }
Column(
Modifier.fillMaxWidth()
+ .graphicsLayer {
+ scaleY = 0.9f + 0.1f * reveal
+ transformOrigin = TransformOrigin(0.5f, 1f)
+ translationY = (1f - reveal) * 8.dp.toPx()
+ }
+ .clipToBounds()
.graphicsLayer { scaleX = toolCompress; transformOrigin = TransformOrigin(0f, 0.5f) }
.viewerGlass(backdrop, glass).padding(12.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
@@ -209,8 +278,18 @@ internal fun PdfViewerBottomToolbar(
modifier = Modifier.size(40.dp)
) { CloseCrossIcon(Modifier.size(13.dp), Color.White) }
Box(Modifier.width(1.dp).height(26.dp).background(fg.copy(0.14f)))
+ // Same curved-edge treatment as the main Editor-Tools carousel: clip to the
+ // rounded shape (not the scroll's straight rectangular edge) and fade the ends so
+ // the pen / shapes / OCR buttons slide away behind the capsule curve instead of
+ // being chopped by a hard vertical line. Content padding keeps the first/last
+ // button spaced like the rest.
+ val toolRowScroll = rememberScrollState()
Row(
- modifier = Modifier.weight(1f).horizontalScroll(rememberScrollState()),
+ modifier = Modifier
+ .weight(1f)
+ .carouselEdges(toolRowScroll)
+ .horizontalScroll(toolRowScroll)
+ .padding(horizontal = 4.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
@@ -246,13 +325,13 @@ internal fun PdfViewerBottomToolbar(
}
Box(Modifier.width(1.dp).height(26.dp).background(fg.copy(0.14f)))
LiquidIconButton(
- onClick = { if (currentPageMarks.isNotEmpty()) currentPageMarks.removeAt(currentPageMarks.lastIndex) },
+ onClick = onUndo,
backdrop = backdrop,
surfaceColor = chip,
modifier = Modifier.size(40.dp)
- ) { Icon(Icons.Rounded.Undo, stringResource(R.string.viewer_undo), Modifier.size(19.dp), fg) }
+ ) { Icon(Icons.Rounded.Undo, stringResource(R.string.viewer_undo), Modifier.size(19.dp), fg.copy(if (canUndo) 1f else 0.35f)) }
LiquidIconButton(
- onClick = { currentPageMarks.clear() },
+ onClick = onClearPage,
backdrop = backdrop,
surfaceColor = Color(0xFFC62828).copy(0.85f),
modifier = Modifier.size(40.dp)
@@ -328,9 +407,16 @@ internal fun PdfViewerBottomToolbar(
}
// Attributes — stroke sizes (draw only) + colour beads on ONE line,
- // so the toolbar stays compact instead of stacking rows.
+ // so the toolbar stays compact instead of stacking rows. Same curved-edge fade as the
+ // tool row above, so the colour beads disappear behind the capsule curve rather than a
+ // straight cut.
+ val attrRowScroll = rememberScrollState()
Row(
- Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),
+ Modifier
+ .fillMaxWidth()
+ .carouselEdges(attrRowScroll)
+ .horizontalScroll(attrRowScroll)
+ .padding(horizontal = 4.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
@@ -398,14 +484,31 @@ internal fun PdfViewerBottomToolbar(
// the editor is open. Hidden once a sub-tool is active (focused mode) so the
// screen isn't stacked with panels — the sub-toolbar's ✕ returns here.
AnimatedVisibility(
- visible = editorOpen && !showDrawTools && !showOcrTools && !showFindBar && !showSignaturePad && activeImageId == null,
- // Unfold UPWARD from the pinned bar (no slide) so the "Editor Tools" pill stays put.
- // Spring = liquid feel.
- enter = fadeIn(tween(200)) + expandVertically(spring(dampingRatio = 0.82f, stiffness = Spring.StiffnessLow), expandFrom = Alignment.Bottom),
- // Instant exit → releases its layout space immediately so the sub-toolbar
- // below never gets pushed up and then dropped ("stays top, then comes down").
- exit = ExitTransition.None
+ // Gated by `selectorGate`, which drops the instant a sub-tool becomes active — so the
+ // chips fade out FIRST and the sub-toolbar (held back by `subGate`) only fades in once
+ // this space is clear. The two faces no longer overlap, so a real fading exit is finally
+ // safe here: it can hold its layout space while it fades because nothing is fading in on
+ // top of it yet.
+ visible = selectorGate && editorOpen && !showFindBar && !showSignaturePad && activeImageId == null,
+ enter = fadeIn(tween(200)),
+ exit = fadeOut(tween(FaceHandoffMillis))
) {
+ val reveal by transition.animateFloat(
+ transitionSpec = {
+ if (targetState == EnterExitState.Visible) spring(dampingRatio = 0.72f, stiffness = 300f)
+ else spring(dampingRatio = 1f, stiffness = Spring.StiffnessMedium)
+ },
+ label = "editorToolsReveal"
+ ) { if (it == EnterExitState.Visible) 1f else 0f }
+ Box(
+ Modifier
+ .graphicsLayer {
+ scaleY = 0.9f + 0.1f * reveal
+ transformOrigin = TransformOrigin(0.5f, 1f)
+ translationY = (1f - reveal) * 8.dp.toPx()
+ }
+ .clipToBounds()
+ ) {
if (docKind == DocKind.Ppt) {
// PowerPoint editing isn't available yet — a friendly placeholder instead of the
// annotation tools (which don't map cleanly onto slides).
@@ -413,7 +516,7 @@ internal fun PdfViewerBottomToolbar(
Modifier
.fillMaxWidth()
.graphicsLayer { scaleX = toolCompress; transformOrigin = TransformOrigin(0f, 0.5f) }
- .viewerGlass(backdrop, glass)
+ .viewerGlass(backdrop, pillGlass)
.padding(horizontal = 16.dp, vertical = 16.dp),
horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.CenterHorizontally),
verticalAlignment = Alignment.CenterVertically
@@ -424,13 +527,17 @@ internal fun PdfViewerBottomToolbar(
} else if (docKind == DocKind.Word) {
// Curated Word reading/markup set — Select Text, Highlight, Find. No PDF-centric
// shapes / add-image / text-box / note / eraser / sign.
+ val wordScroll = rememberScrollState()
Row(
Modifier
.fillMaxWidth()
.graphicsLayer { scaleX = toolCompress; transformOrigin = TransformOrigin(0f, 0.5f) }
- .viewerGlass(backdrop, glass)
- .padding(horizontal = 12.dp, vertical = 10.dp)
- .horizontalScroll(rememberScrollState()),
+ .viewerGlass(backdrop, pillGlass)
+ // Clip to the capsule's own curve and soften the ends. See [carouselEdges]
+ // for why the padding has to come after the scroll, not before it.
+ .carouselEdges(wordScroll)
+ .horizontalScroll(wordScroll)
+ .padding(horizontal = 12.dp, vertical = 10.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
@@ -457,13 +564,18 @@ internal fun PdfViewerBottomToolbar(
}
}
} else {
+ val toolScroll = rememberScrollState()
Row(
Modifier
.fillMaxWidth()
.graphicsLayer { scaleX = toolCompress; transformOrigin = TransformOrigin(0f, 0.5f) }
- .viewerGlass(backdrop, glass)
- .padding(horizontal = 12.dp, vertical = 10.dp)
- .horizontalScroll(rememberScrollState()),
+ .viewerGlass(backdrop, pillGlass)
+ // The chips are meant to disappear behind the capsule's curved ends. Without
+ // this the scroll viewport clipped them with a straight vertical line inset
+ // from the curve. See [carouselEdges] — the padding order is load-bearing.
+ .carouselEdges(toolScroll)
+ .horizontalScroll(toolScroll)
+ .padding(horizontal = 12.dp, vertical = 10.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
@@ -536,6 +648,18 @@ internal fun PdfViewerBottomToolbar(
}
}
+ // Undo used to live only inside the draw strip, so placing a text box, a note, an
+ // image or a signature left nothing to undo with. The draw strip has its own copy,
+ // hence the exclusion here.
+ if (canUndo && !drawingToolActive) {
+ LiquidButton(onClick = onUndo, backdrop = backdrop, surfaceColor = chip) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
+ Icon(Icons.Rounded.Undo, null, Modifier.size(14.dp), fg)
+ BasicText(stringResource(R.string.viewer_undo), style = TextStyle(fg, 12.sp, FontWeight.Medium))
+ }
+ }
+ }
+
if (drawingToolActive || activeTool == PdfEditTool.SelectText || activeTool == PdfEditTool.Image || activeTool == PdfEditTool.Eraser || activeTool == PdfEditTool.Text || activeTool == PdfEditTool.Note) {
LiquidIconButton(
onClick = { onSetActiveTool(PdfEditTool.None) },
@@ -561,15 +685,18 @@ internal fun PdfViewerBottomToolbar(
}
}
}
+ }
}
// ── Collapsed home bar: one "Editor Tools" pill (expands the tools above it)
// + a compact circular "Open another PDF" button. Hidden while a sub-tool is
// active so that focused mode shows ONLY the sub-toolbar (one panel).
AnimatedVisibility(
- visible = !showDrawTools && !showOcrTools && !showImageTools && !showFindBar && !showSignaturePad,
+ // Same `selectorGate` as the tool chips above, so the blue "Editor Tools" pill fades out
+ // in lockstep with them — "both pills at the same time" — before the sub-toolbar arrives.
+ visible = selectorGate && !showFindBar && !showSignaturePad,
enter = fadeIn(tween(180)),
- exit = ExitTransition.None
+ exit = fadeOut(tween(FaceHandoffMillis))
) {
Row(
Modifier.fillMaxWidth(),
@@ -586,7 +713,7 @@ internal fun PdfViewerBottomToolbar(
},
backdrop = backdrop,
tint = if (editorOpen) accent else Color.Unspecified,
- surfaceColor = if (editorOpen) Color.Unspecified else glass,
+ surfaceColor = if (editorOpen) Color.Unspecified else pillGlass,
modifier = Modifier.weight(1f)
) {
Row(
@@ -614,18 +741,20 @@ internal fun PdfViewerBottomToolbar(
// (not inside it) and bottom-anchored, morphing it taller grows only this wrapper Box
// upward — the column (tool panels + pill) stays pinned to the base and never moves.
AnimatedVisibility(
- visible = shareRowVisible,
+ // Sits in the pill row's reserved slot, so it rides the same `selectorGate` and fades out
+ // alongside the pill instead of popping away on its own.
+ visible = selectorGate && !showFindBar && !showSignaturePad,
enter = fadeIn(tween(180)),
- exit = ExitTransition.None,
+ exit = fadeOut(tween(FaceHandoffMillis)),
modifier = Modifier.align(Alignment.BottomEnd)
) {
ShareMorphButton(
backdrop = backdrop,
- glass = glass,
+ glass = pillGlass,
fg = fg,
onOpen = onOpenAnotherPdf,
onShare = onShareDocument,
- onShareModeChanged = { shareActive = it }
+ onShareModeChanged = { shareActive = it; onShareHoldChanged(it) }
)
}
}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerDialogs.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerDialogs.kt
index 060bea0..be3274a 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerDialogs.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerDialogs.kt
@@ -1,7 +1,10 @@
package com.chethan616.clearpdf.ui.screen
import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.EnterExitState
import androidx.compose.animation.core.Spring
+import androidx.compose.animation.core.animateFloat
+import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
@@ -12,6 +15,7 @@ import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
+import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -26,8 +30,14 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.text.BasicTextField
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.rounded.Check
+import androidx.compose.material.icons.rounded.KeyboardArrowDown
+import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
@@ -39,22 +49,34 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
+import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
+import androidx.compose.ui.graphics.TransformOrigin
+import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.layout.onGloballyPositioned
+import androidx.compose.ui.layout.positionInWindow
+import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.IntOffset
+import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
+import androidx.compose.ui.zIndex
import com.chethan616.clearpdf.R
import com.chethan616.clearpdf.ui.components.DestructiveGlassButton
+import com.chethan616.clearpdf.ui.components.GlassMotion
import com.chethan616.clearpdf.ui.components.LiquidButton
import com.chethan616.clearpdf.ui.components.liquidGlassPanel
import com.chethan616.clearpdf.ui.utils.UISensor
import com.kyant.backdrop.backdrops.LayerBackdrop
import kotlinx.coroutines.delay
+import kotlin.math.roundToInt
/**
* Page-jump popup rendered **in-window** (not a [Dialog]) so the liquid-glass panel
@@ -274,6 +296,282 @@ internal fun AnnotationEditorDialog(
}
}
+/** Which file the viewer's Share action should hand off. */
+internal enum class ShareFormat { ORIGINAL, PDF }
+
+/**
+ * Share/export chooser, rendered in-window in the same glass family as [LiquidPageJumpPopup]. For a
+ * converted document (a .docx opened as a PDF) it offers the original file *or* a PDF via a bouncy
+ * [LiquidGlassDropdown]; when PDF is the target it can encrypt with a password. A plain PDF skips the
+ * format row and just offers the encrypt toggle.
+ *
+ * The dialog only collects intent — the actual file work (encrypt, wrap, chooser) happens off the UI
+ * thread in the caller.
+ */
+@Composable
+internal fun ExportShareDialog(
+ visible: Boolean,
+ // Uppercase token for the original file when it isn't a PDF (e.g. "DOCX"); null for a plain PDF.
+ originalExt: String?,
+ backdrop: LayerBackdrop,
+ uiSensor: UISensor,
+ fg: Color,
+ fgSoft: Color,
+ surface: Color,
+ field: Color,
+ onDismiss: () -> Unit,
+ onShare: (format: ShareFormat, encrypt: Boolean, password: String) -> Unit
+) {
+ // Keyed on `visible` so every open starts fresh.
+ var formatIndex by remember(visible) { mutableStateOf(0) }
+ var encrypt by remember(visible) { mutableStateOf(false) }
+ var password by remember(visible) { mutableStateOf("") }
+ var dropdownOpen by remember(visible) { mutableStateOf(false) }
+ val passwordFocus = remember { FocusRequester() }
+ val density = LocalDensity.current
+
+ val pdfOnly = originalExt == null
+ val pdfSelected = pdfOnly || formatIndex == 1
+ val canShare = !(pdfSelected && encrypt && password.isBlank())
+ val options = if (pdfOnly) emptyList() else listOf(originalExt, stringResource(R.string.viewer_share_pdf))
+
+ // Trigger anchor in the dialog Box's coordinate space, so the dropdown menu is an OVERLAY that
+ // never grows the glass panel. Growing that panel re-runs its blur+lens every frame — the exact
+ // "expand/minimize lag" being fixed here.
+ var boxWin by remember { mutableStateOf(Offset.Zero) }
+ var trigWin by remember { mutableStateOf(Offset.Zero) }
+ var trigSize by remember { mutableStateOf(IntSize.Zero) }
+
+ val chevron by animateFloatAsState(if (dropdownOpen) 180f else 0f, GlassMotion.morph(), label = "shareDropChevron")
+
+ LaunchedEffect(encrypt, pdfSelected) {
+ if (encrypt && pdfSelected) { delay(120); runCatching { passwordFocus.requestFocus() } }
+ }
+
+ Box(Modifier.fillMaxSize()) {
+ AnimatedVisibility(
+ visible = visible,
+ enter = fadeIn(tween(200)),
+ exit = fadeOut(tween(180)),
+ modifier = Modifier.fillMaxSize()
+ ) {
+ Box(
+ Modifier
+ .fillMaxSize()
+ .background(Color.Black.copy(0.45f))
+ .pointerInput(Unit) { detectTapGestures { onDismiss() } }
+ )
+ }
+
+ AnimatedVisibility(
+ visible = visible,
+ enter = fadeIn(tween(220)) +
+ scaleIn(initialScale = 0.85f, animationSpec = spring(dampingRatio = 0.72f, stiffness = Spring.StiffnessMediumLow)),
+ exit = fadeOut(tween(140)) + scaleOut(targetScale = 0.9f, animationSpec = tween(150)),
+ modifier = Modifier.align(Alignment.Center).imePadding()
+ ) {
+ Box(
+ Modifier
+ .widthIn(max = 340.dp)
+ .fillMaxWidth(0.86f)
+ .onGloballyPositioned { boxWin = it.positionInWindow() }
+ ) {
+ Column(
+ Modifier
+ .fillMaxWidth()
+ .liquidGlassPanel(backdrop, uiSensor, surface)
+ .padding(22.dp),
+ verticalArrangement = Arrangement.spacedBy(16.dp)
+ ) {
+ BasicText(
+ stringResource(R.string.viewer_share_title),
+ style = TextStyle(fg, 17.sp, fontWeight = FontWeight.Bold)
+ )
+
+ if (!pdfOnly) {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ BasicText(
+ stringResource(R.string.viewer_share_format),
+ style = TextStyle(fgSoft, 12.sp, fontWeight = FontWeight.Medium)
+ )
+ // Trigger only — the menu is drawn as a dialog overlay below (so the panel
+ // never resizes). Reports its window position + size to anchor that menu.
+ LiquidButton(
+ onClick = { dropdownOpen = !dropdownOpen },
+ backdrop = backdrop,
+ surfaceColor = field,
+ modifier = Modifier
+ .fillMaxWidth()
+ .onGloballyPositioned { trigWin = it.positionInWindow(); trigSize = it.size }
+ ) {
+ Row(
+ Modifier.fillMaxWidth().padding(vertical = 2.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.SpaceBetween
+ ) {
+ BasicText(
+ options.getOrElse(formatIndex) { "" },
+ style = TextStyle(fg, 14.sp, fontWeight = FontWeight.SemiBold)
+ )
+ Icon(
+ Icons.Rounded.KeyboardArrowDown,
+ null,
+ Modifier.size(20.dp).graphicsLayer { rotationZ = chevron },
+ fgSoft
+ )
+ }
+ }
+ }
+ }
+
+ if (pdfSelected) {
+ // Segmented Normal | Encrypted. Deterministic — a plain tap on `LiquidToggle`
+ // fires both its clickable and its drag-stop, cancelling out, so it could get
+ // stuck on and never prompt for a password. Two buttons set a definite value.
+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ listOf(false to R.string.viewer_share_normal, true to R.string.viewer_share_encrypted)
+ .forEach { (enc, labelRes) ->
+ val sel = encrypt == enc
+ LiquidButton(
+ onClick = { encrypt = enc },
+ backdrop = backdrop,
+ tint = if (sel) Color(0xFF1976D2) else Color.Unspecified,
+ surfaceColor = if (sel) Color.Unspecified else field,
+ modifier = Modifier.weight(1f)
+ ) {
+ BasicText(
+ stringResource(labelRes),
+ style = TextStyle(if (sel) Color.White else fg, 13.sp, fontWeight = FontWeight.SemiBold),
+ modifier = Modifier.padding(vertical = 2.dp)
+ )
+ }
+ }
+ }
+ if (encrypt) {
+ Box(
+ Modifier
+ .fillMaxWidth()
+ .clip(RoundedCornerShape(12.dp))
+ .background(field)
+ .border(1.dp, fg.copy(0.18f), RoundedCornerShape(12.dp))
+ .padding(horizontal = 12.dp, vertical = 12.dp)
+ ) {
+ if (password.isEmpty()) {
+ BasicText(
+ stringResource(R.string.viewer_share_password_hint),
+ style = TextStyle(fgSoft, 14.sp)
+ )
+ }
+ BasicTextField(
+ value = password,
+ onValueChange = { password = it },
+ singleLine = true,
+ textStyle = TextStyle(fg, 14.sp),
+ cursorBrush = SolidColor(fg),
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
+ modifier = Modifier.fillMaxWidth().focusRequester(passwordFocus)
+ )
+ }
+ }
+ }
+
+ Row(
+ Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(12.dp, Alignment.End)
+ ) {
+ LiquidButton(onClick = onDismiss, backdrop = backdrop, surfaceColor = field) {
+ BasicText(stringResource(R.string.cancel), style = TextStyle(fg, 13.sp, FontWeight.Medium))
+ }
+ LiquidButton(
+ onClick = {
+ if (canShare) onShare(
+ if (pdfSelected) ShareFormat.PDF else ShareFormat.ORIGINAL,
+ encrypt && pdfSelected,
+ password
+ )
+ },
+ backdrop = backdrop,
+ tint = if (canShare) Color(0xFF1976D2) else Color(0xFF1976D2).copy(0.4f)
+ ) {
+ BasicText(stringResource(R.string.viewer_share_button), style = TextStyle(Color.White, 13.sp, fontWeight = FontWeight.Bold))
+ }
+ }
+ }
+
+ // Tap-outside catcher for an open dropdown. `matchParentSize` reads the panel's size
+ // without contributing to it, so it doesn't grow the dialog.
+ if (dropdownOpen) {
+ Box(
+ Modifier
+ .matchParentSize()
+ .pointerInput(Unit) { detectTapGestures { dropdownOpen = false } }
+ )
+ }
+
+ // Dropdown menu overlay — anchored under the trigger, drawn last (on top), and NOT
+ // wrapped by the glass panel, so opening/closing it costs nothing on the panel. The
+ // bounce is all draw-time (a `pop()` spring driving alpha + a translationY overshoot +
+ // a small scaleY grow), so the menu's own glass never re-blurs while it springs.
+ if (!pdfOnly && (dropdownOpen || trigSize != IntSize.Zero)) {
+ val menuOffset = IntOffset(
+ (trigWin.x - boxWin.x).roundToInt(),
+ (trigWin.y - boxWin.y).roundToInt() + trigSize.height + with(density) { 6.dp.roundToPx() }
+ )
+ val menuWidth = with(density) { trigSize.width.toDp() }
+ AnimatedVisibility(
+ visible = dropdownOpen,
+ enter = fadeIn(tween(110)),
+ exit = fadeOut(tween(90)),
+ modifier = Modifier.align(Alignment.TopStart).offset { menuOffset }.zIndex(1f)
+ ) {
+ val reveal by transition.animateFloat(
+ transitionSpec = {
+ if (targetState == EnterExitState.Visible) GlassMotion.pop() else GlassMotion.settle()
+ },
+ label = "shareMenuReveal"
+ ) { if (it == EnterExitState.Visible) 1f else 0f }
+ Column(
+ Modifier
+ .width(menuWidth)
+ .graphicsLayer {
+ alpha = reveal.coerceIn(0f, 1f)
+ translationY = (1f - reveal) * (-14.dp.toPx())
+ scaleY = 0.9f + 0.1f * reveal
+ transformOrigin = TransformOrigin(0.5f, 0f)
+ }
+ .liquidGlassPanel(backdrop, uiSensor, field)
+ .padding(4.dp),
+ verticalArrangement = Arrangement.spacedBy(2.dp)
+ ) {
+ options.forEachIndexed { i, opt ->
+ val selected = i == formatIndex
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .clip(RoundedCornerShape(12.dp))
+ .clickable(
+ interactionSource = remember { MutableInteractionSource() },
+ indication = null
+ ) { formatIndex = i; dropdownOpen = false }
+ .padding(horizontal = 14.dp, vertical = 11.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.SpaceBetween
+ ) {
+ BasicText(
+ opt,
+ style = TextStyle(fg, 14.sp, fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium)
+ )
+ if (selected) Icon(Icons.Rounded.Check, null, Modifier.size(16.dp), fg)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
// Shared annotation / shape colour palette (dark inks read well on white pages; a few
// vivid accents for shapes and notes).
internal val editorPalette: List<Color> = listOf(
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 8dc2760..0d11701 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
@@ -8,6 +8,7 @@ import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateDecay
+import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
@@ -27,7 +28,9 @@ import androidx.compose.foundation.gestures.calculatePan
import androidx.compose.foundation.gestures.calculateZoom
import androidx.compose.ui.geometry.isSpecified
import androidx.compose.foundation.gestures.detectTapGestures
+import androidx.compose.animation.animateColorAsState
import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.LazyListLayoutInfo
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.layout.Arrangement
@@ -37,6 +40,7 @@ import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
+import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.ime
@@ -48,6 +52,7 @@ import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.union
import androidx.compose.foundation.verticalScroll
+import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.graphicsLayer
@@ -115,6 +120,7 @@ import com.chethan616.clearpdf.ui.components.GlassTitlePill
import com.chethan616.clearpdf.ui.components.LiquidIconButton
import com.chethan616.clearpdf.ui.components.ViewerChromeGlass
import com.chethan616.clearpdf.ui.components.LiquidSaveSheet
+import com.chethan616.clearpdf.ui.components.liquidGlassPanel
import com.chethan616.clearpdf.ui.components.viewerChromeGlass
import com.chethan616.clearpdf.ui.components.viewerGlass
import com.chethan616.clearpdf.ui.theme.LocalIsDarkMode
@@ -123,9 +129,11 @@ import com.chethan616.clearpdf.ui.viewmodel.PdfViewerViewModel
import com.kyant.backdrop.backdrops.LayerBackdrop
import com.kyant.backdrop.backdrops.layerBackdrop
import com.kyant.backdrop.backdrops.rememberLayerBackdrop
+import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
import kotlin.math.roundToInt
@Composable
@@ -154,6 +162,10 @@ fun PdfViewerScreen(
// True while the bottom "Editor Tools" panel is expanded — keeps the chrome from auto-hiding
// so the user can browse tools without it disappearing.
var editorToolsOpen by rememberSaveable { mutableStateOf(false) }
+ // True for as long as the share capsule is held morphed open. Not saveable on purpose: a
+ // configuration change cancels the pointer gesture, so a persisted `true` would pin the chrome
+ // open forever with no finger left to release it.
+ var shareHolding by remember { mutableStateOf(false) }
var lastInteractionAtMs by rememberSaveable { mutableStateOf(System.currentTimeMillis()) }
// Adobe-style single-axis reading: the viewer is vertical-only. Horizontal
// panning is still allowed inside a zoomed page (handled in PdfContinuousPage).
@@ -165,6 +177,7 @@ fun PdfViewerScreen(
var currentStrokeWidth by rememberSaveable { mutableFloatStateOf(6f) }
var activeImageId by remember { mutableStateOf<Long?>(null) }
var showSaveDialog by rememberSaveable { mutableStateOf(false) }
+ var showShareDialog by remember { mutableStateOf(false) }
var showFindBar by rememberSaveable { mutableStateOf(false) }
var findQuery by rememberSaveable { mutableStateOf("") }
val findFocusRequester = remember { FocusRequester() }
@@ -207,6 +220,14 @@ fun PdfViewerScreen(
fun getPageMarks(page: Int): MutableList<PdfMarkup> =
annotationsByPage.getOrPut(page) { mutableStateListOf() }
+ // 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
+ // the first *partially* visible page — usually a sliver of the previous page while you draw on
+ // the one filling the screen, so undo silently no-op'd on an empty list. The same trap is
+ // already documented for image placement at `activeImageLoc`.
+ val undoStack = remember { mutableStateListOf<Int>() }
+
// Declared here (rather than lower) so the image/signature launchers below can place
// annotations onto whichever page is under the viewport centre.
val listState = rememberLazyListState()
@@ -257,6 +278,32 @@ fun PdfViewerScreen(
return page to Offset(frame.center.x, localY)
}
+ /** Record that [page] just gained a markup, so undo can find it again. */
+ fun recordEdit(page: Int) { undoStack.add(page) }
+
+ /**
+ * Remove the most recently added markup, wherever it lives. Entries can go stale — the eraser
+ * and the shape editor delete marks without touching the stack — so pop past any page that has
+ * since been emptied. If the history is exhausted (or was never populated) fall back to the page
+ * under the viewport centre, which is the page the user is looking at.
+ */
+ fun undoLastEdit() {
+ while (undoStack.isNotEmpty()) {
+ val page = undoStack.removeAt(undoStack.lastIndex)
+ val marks = getPageMarks(page)
+ if (marks.isNotEmpty()) { marks.removeAt(marks.lastIndex); return }
+ }
+ val marks = getPageMarks(viewportPlacementTarget().first)
+ if (marks.isNotEmpty()) marks.removeAt(marks.lastIndex)
+ }
+
+ /** Clear every markup on the page under the viewport centre — the one the user can see. */
+ fun clearVisiblePage() {
+ val page = viewportPlacementTarget().first
+ getPageMarks(page).clear()
+ undoStack.removeAll { it == page }
+ }
+
// Add a new image/signature centred at the viewport-target on the correct page, sized
// to the page and clamped fully on-page. Shared by the image picker and signature pad.
fun placeImageMarkup(bmp: Bitmap, isSignature: Boolean) {
@@ -276,6 +323,7 @@ fun PdfViewerScreen(
val cy = center.y.coerceIn(h / 2f, (cs.height - h / 2f).coerceAtLeast(h / 2f))
val id = System.nanoTime()
marks.add(PdfMarkup.ImageMarkup(id, bmp, Offset(cx - w / 2f, cy - h / 2f), Offset(cx + w / 2f, cy + h / 2f), isSignature))
+ recordEdit(page)
activeImageId = id; activeTool = PdfEditTool.Image; controlsVisible = true
}
@@ -334,19 +382,21 @@ fun PdfViewerScreen(
scale = 1f; offsetX = 0f
activeTool = PdfEditTool.None
selectedAnnoPage = null; selectedAnnoIndex = -1
- annotationsByPage.clear(); pageCanvasSizes.clear(); pageBitmapSizes.clear()
+ annotationsByPage.clear(); undoStack.clear(); pageCanvasSizes.clear(); pageBitmapSizes.clear()
viewModel.clearOcrSelection(state.currentPage); viewModel.clearExportFeedback()
showFindBar = false; findQuery = ""; viewModel.clearSearch()
}
- LaunchedEffect(state.document, controlsVisible, controlsPinned, activeTool, editorToolsOpen, lastInteractionAtMs) {
- if (state.document != null && controlsVisible && !controlsPinned && scale <= 1.01f && activeTool == PdfEditTool.None && !editorToolsOpen) {
+ LaunchedEffect(state.document, controlsVisible, controlsPinned, activeTool, editorToolsOpen, shareHolding, lastInteractionAtMs) {
+ if (state.document != null && controlsVisible && !controlsPinned && scale <= 1.01f && activeTool == PdfEditTool.None && !editorToolsOpen && !shareHolding) {
val snap = lastInteractionAtMs
// Comfortable auto-hide window; any interaction bumps lastInteractionAtMs and
- // restarts this. It never fires while a tool is active (activeTool != None) OR while
- // the Editor Tools panel is open, so browsing tools won't hide the chrome.
+ // restarts this. It never fires while a tool is active (activeTool != None), while
+ // the Editor Tools panel is open, or while the share capsule is held — a long-press
+ // produces no pointer events for the viewer to see, so without that last guard the
+ // chrome hid itself out from under the finger mid-gesture.
delay(5000)
- if (controlsVisible && !controlsPinned && scale <= 1.01f && activeTool == PdfEditTool.None && !editorToolsOpen && snap == lastInteractionAtMs)
+ if (controlsVisible && !controlsPinned && scale <= 1.01f && activeTool == PdfEditTool.None && !editorToolsOpen && !shareHolding && snap == lastInteractionAtMs)
controlsVisible = false
}
}
@@ -361,57 +411,88 @@ fun PdfViewerScreen(
// ── No-document state ─────────────────────────────────────────────────
if (state.document == null) {
- Column(
- Modifier.fillMaxSize().statusBarsPadding().padding(16.dp),
- verticalArrangement = Arrangement.spacedBy(16.dp)
- ) {
- // Same trio as the loaded viewer's chrome: back circle · centered title pill · balancer.
- Row(
- Modifier.fillMaxWidth(),
- verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.spacedBy(10.dp)
+ // The password prompt is an OVERLAY on this Box, not a third row inside the Column below.
+ //
+ // It used to be a sibling of the "Open a PDF" card in a `spacedBy(16.dp)` Column whose middle
+ // section carried `weight(1f)`. So the moment the prompt and the keyboard were both up, the
+ // weighted section was squeezed and the card was chopped mid-sentence — the whole point of a
+ // password dialog is that the thing behind it stays intact.
+ Box(Modifier.fillMaxSize()) {
+ Column(
+ Modifier.fillMaxSize().statusBarsPadding().padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(16.dp)
) {
- LiquidIconButton(
- onClick = onBack,
- backdrop = backdrop,
- surfaceColor = Color.White.copy(0.08f)
+ // Same trio as the loaded viewer's chrome: back circle · centered title pill · balancer.
+ Row(
+ Modifier.fillMaxWidth(),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
- Icon(Icons.Rounded.ArrowBackIosNew, stringResource(R.string.back), Modifier.size(16.dp), text)
- }
- Box(Modifier.weight(1f), contentAlignment = Alignment.Center) {
- GlassTitlePill(stringResource(R.string.viewer_title), backdrop)
+ // No `surfaceColor`, like Home's — this circle used to paint a white 8% wash that
+ // nothing else in the app does.
+ LiquidIconButton(onClick = onBack, backdrop = backdrop) {
+ Icon(Icons.Rounded.ArrowBackIosNew, stringResource(R.string.back), Modifier.size(16.dp), text)
+ }
+ Box(Modifier.weight(1f), contentAlignment = Alignment.Center) {
+ GlassTitlePill(stringResource(R.string.viewer_title), backdrop)
+ }
+ Spacer(Modifier.size(40.dp))
}
- Spacer(Modifier.size(40.dp))
- }
- Column(
- Modifier.fillMaxWidth().weight(1f).verticalScroll(rememberScrollState()),
- verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically)
- ) {
Column(
- Modifier.fillMaxWidth().viewerGlass(backdrop, viewerChromeGlass(isDarkMode)).padding(28.dp),
- horizontalAlignment = Alignment.CenterHorizontally,
- verticalArrangement = Arrangement.spacedBy(16.dp)
+ Modifier.fillMaxWidth().weight(1f).verticalScroll(rememberScrollState()),
+ verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically)
) {
- Icon(Icons.Rounded.PictureAsPdf, null, Modifier.size(56.dp), accent)
- BasicText(stringResource(R.string.viewer_open_pdf), style = TextStyle(text, 20.sp, fontWeight = FontWeight.SemiBold))
- BasicText(stringResource(R.string.viewer_select_file), style = TextStyle(sub, 14.sp, textAlign = TextAlign.Center))
- LiquidButton(onClick = { pdfPickerLauncher.launch(arrayOf("*/*")) }, backdrop = backdrop, tint = accent) {
- Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {
- Icon(Icons.Rounded.UploadFile, null, Modifier.size(18.dp), Color.White)
- BasicText(stringResource(R.string.viewer_pick_pdf), style = TextStyle(Color.White, 15.sp, fontWeight = FontWeight.Medium))
+ Column(
+ Modifier.fillMaxWidth().viewerGlass(backdrop, viewerChromeGlass(isDarkMode)).padding(28.dp),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(16.dp)
+ ) {
+ Icon(Icons.Rounded.PictureAsPdf, null, Modifier.size(56.dp), accent)
+ BasicText(stringResource(R.string.viewer_open_pdf), style = TextStyle(text, 20.sp, fontWeight = FontWeight.SemiBold))
+ BasicText(stringResource(R.string.viewer_select_file), style = TextStyle(sub, 14.sp, textAlign = TextAlign.Center))
+ LiquidButton(onClick = { pdfPickerLauncher.launch(arrayOf("*/*")) }, backdrop = backdrop, tint = accent) {
+ Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {
+ Icon(Icons.Rounded.UploadFile, null, Modifier.size(18.dp), Color.White)
+ BasicText(stringResource(R.string.viewer_pick_pdf), style = TextStyle(Color.White, 15.sp, fontWeight = FontWeight.Medium))
+ }
}
}
+ state.errorMessage?.let { BasicText(it, style = TextStyle(Color(0xFFD32F2F), 14.sp)) }
}
- state.errorMessage?.let { BasicText(it, style = TextStyle(Color(0xFFD32F2F), 14.sp)) }
}
+
+ // ── Password prompt (in-window, so the glass samples the real backdrop) ──
+ val askingPassword = state.passwordRequired && state.passwordUri != null
+
+ // Dimming scrim. Deliberately NOT tap-to-dismiss, unlike LiquidPageJumpPopup: there is
+ // nothing behind this to go back to — dismissing would leave a locked document and an
+ // empty screen. Back already exits the viewer.
AnimatedVisibility(
- visible = state.passwordRequired && state.passwordUri != null,
- enter = fadeIn() + scaleIn(initialScale = 0.96f),
- exit = fadeOut() + scaleOut(targetScale = 0.98f),
- modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp).imePadding()
+ visible = askingPassword,
+ enter = fadeIn(tween(200)),
+ exit = fadeOut(tween(180)),
+ modifier = Modifier.fillMaxSize()
+ ) {
+ Box(Modifier.fillMaxSize().background(Color.Black.copy(0.45f)))
+ }
+
+ AnimatedVisibility(
+ visible = askingPassword,
+ // LiquidPageJumpPopup's entrance, verbatim, so the app has one dialog motion.
+ enter = fadeIn(tween(220)) +
+ scaleIn(initialScale = 0.85f, animationSpec = spring(dampingRatio = 0.72f, stiffness = Spring.StiffnessMediumLow)),
+ exit = fadeOut(tween(140)) + scaleOut(targetScale = 0.9f, animationSpec = tween(150)),
+ modifier = Modifier.align(Alignment.Center).imePadding()
) {
Column(
- Modifier.fillMaxWidth().viewerGlass(backdrop, viewerChromeGlass(isDarkMode)).padding(16.dp),
+ Modifier
+ .widthIn(max = 340.dp)
+ .fillMaxWidth(0.86f)
+ // The heavy stack, not `viewerGlass`: this is a dialog over a scrim and needs
+ // an edge of its own. No `containerColorOverride` — there is no page to sample
+ // in this branch, so the theme tint is the right one.
+ .liquidGlassPanel(backdrop, uiSensor)
+ .padding(22.dp),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
BasicText(stringResource(R.string.pdf_password_title), style = TextStyle(text, 17.sp, fontWeight = FontWeight.SemiBold))
@@ -462,22 +543,49 @@ fun PdfViewerScreen(
// chrome palette (glass surface + foreground) so text/icons are always legible:
// dark ink on a light page, white ink on a dark page.
//
- // EXCEPT on a single-page document. That page is centred (see `Arrangement.Center` on the
- // LazyColumn below), so the chrome floats over wide black bands rather than over the page, and
- // sampling the page then picks the wrong palette: `chromeField` is only 6% alpha, so it sets no
- // value of its own and every toolbar button just refracts the black beneath it — while its
- // icon/label takes the *dark* foreground chosen from the white page. Dark on black is invisible.
- // Pinning the dark branch is safe either way, since white-on-dark glass reads fine over both the
- // black band and a white page (it is what every multi-page document already uses).
+ // Single-page documents used to be pinned to the dark branch. That was over-broad and is the
+ // reason the chrome looked stuck in dark mode: a converted .docx is usually one page, so *every*
+ // Word document and every one-page PDF got dark glass no matter the page or the theme.
+ //
+ // The reason for the pin was real, though. A lone page is centred (`Arrangement.Center` on the
+ // LazyColumn below), so the chrome can float over the near-black canvas rather than over the
+ // page — and at 66% the light surface set little value of its own, leaving buttons refracting
+ // black while their icons took the *dark* foreground chosen from the white page. The fix is to
+ // make the light surface actually opaque enough to stand on its own (78%, below) instead of
+ // throwing away a correct luminance reading. Dark ink on that holds up over the black band and
+ // over the page alike.
val currentPageBitmap = state.pageBitmaps.getOrNull(currentPageIndex)
- val isLightChrome = remember(currentPageBitmap, safePageCount) {
- if (safePageCount == 1) false
- else currentPageBitmap?.let { averageLuminance(it) > 0.60f } ?: false
+ // Whole-page luminance still drives the DIALOG panels (chromePanel / panelFg): those sit over a
+ // scrim on an opaque surface, not over the live document, so a single global reading is right.
+ // The floating BARS no longer use this — they sample the content directly behind each bar
+ // (topFg / bottomFg, computed once containerHeightPx is known, further down). That is what makes
+ // the icons dynamic per-region, kills the "doesn't flip until you scroll deep into page 3" lag,
+ // and tracks the zoomed region on a single page. The old single-page white-pin is gone with it —
+ // band sampling reads the dark letterbox as dark (→ white ink) on its own.
+ val isLightChrome = remember(currentPageBitmap) {
+ currentPageBitmap?.let { averageLuminance(it) > 0.60f } ?: false
}
- val chromeFg = if (isLightChrome) Color(0xFF15171C) else Color.White
- val chromeFgSoft = if (isLightChrome) Color(0xFF15171C).copy(0.62f) else Color.White.copy(0.62f)
- val chromeGlass = if (isLightChrome) Color(0xFFEFF1F4).copy(0.66f) else ViewerChromeGlass
- val chromeField = if (isLightChrome) Color.Black.copy(0.06f) else Color.White.copy(0.10f)
+ // Home's tint, verbatim — the same expression GlassTitlePill and GlassSearchPill resolve — but
+ // picked off the *page's* luminance instead of the theme, so a white scan in dark mode still gets
+ // the light surface.
+ //
+ // This used to be 0.78/0.62, roughly twice Home's weight, and it was painted onto controls Home
+ // leaves entirely clear: `LiquidIconButton` with no `surfaceColor` draws nothing at all in
+ // `onDrawSurface`, so Home's circles are pure refraction. Over a white page a 62% #12151C slab
+ // composites to about #6C6C6C, which is why the chrome read as grey blobs sitting *on* the
+ // document rather than as glass floating over it. The effect stack was never the difference —
+ // `LiquidIconButton` and `viewerGlass` both run vibrancy + blur 2 + lens 12x24 — only the tint was.
+ val chromeGlass = if (isLightChrome) Color(0xFFFAFAFA).copy(0.35f) else Color(0xFF1E1E1E).copy(0.35f)
+ // Dialogs keep the old, heavier tint. They sit over a 45% black scrim and carry dense content, and
+ // the app's own rule is that the heavy stack stays reserved for them (see ViewerGlass's KDoc).
+ val chromePanel = if (isLightChrome) Color(0xFFEFF1F4).copy(0.78f) else ViewerChromeGlass
+ // The dialogs' ink deliberately does *not* take the single-page pin above. Their surface is
+ // `chromePanel`, which is opaque enough to be its own background, so it is the panel the text has
+ // to contrast with — not the canvas. Pinning these to white alongside the floating chrome would
+ // put white text on a 78% white panel every time a one-page document happened to be light.
+ val panelFg = if (isLightChrome) Color(0xFF15171C) else Color.White
+ val panelFgSoft = if (isLightChrome) Color(0xFF15171C).copy(0.62f) else Color.White.copy(0.62f)
+ val chromeField = if (isLightChrome) Color.Black.copy(0.10f) else Color.White.copy(0.10f)
// The top visible page drives text extraction + bitmap caching.
LaunchedEffect(listState) {
@@ -527,6 +635,64 @@ fun PdfViewerScreen(
var containerHeightPx by remember { mutableStateOf(0) }
+ // ── Adaptive control ink, sampled per bar (Apple-style) ──────────────────────────────
+ // Each bar reads the luminance of the content *directly behind it*, so on a page that is a
+ // dark image up top and a white canvas below, the top bar goes white while the bottom toolbar
+ // goes dark — and both update the instant that content scrolls or zooms under them, not when
+ // the page becomes the first fully-visible item. Bands are in screen px; the content Box is
+ // scaled about a top origin with translationY = 0, so a screen Y maps to the LazyColumn's own
+ // coordinate as screenY / scale (see [bandLuminance]).
+ val topBandBottomPx = with(density) { 96.dp.toPx() }
+ val bottomBandDepthPx = with(density) { 140.dp.toPx() }
+ var topBarLight by remember { mutableStateOf(false) }
+ var bottomBarLight by remember { mutableStateOf(false) }
+ // Hysteresis: flip to light at 0.62, back to dark at 0.58, so a page hovering near the
+ // midpoint doesn't strobe while scrolling. The colour crossfade below smooths the flip
+ // itself. The sampling runs in a coroutine off `snapshotFlow`, so scrolling recomputes the
+ // luminance every frame but only an actual light/dark flip ever recomposes the chrome.
+ LaunchedEffect(containerHeightPx) {
+ snapshotFlow {
+ bandLuminance(listState.layoutInfo, state.pageBitmaps, scale, 0f, topBandBottomPx)
+ }.collect { lum ->
+ if (lum > 0.62f) topBarLight = true else if (lum < 0.58f) topBarLight = false
+ }
+ }
+ LaunchedEffect(containerHeightPx) {
+ snapshotFlow {
+ val h = containerHeightPx.toFloat()
+ if (h <= 0f) 0f
+ else bandLuminance(listState.layoutInfo, state.pageBitmaps, scale, h - bottomBandDepthPx, h)
+ }.collect { lum ->
+ if (lum > 0.62f) bottomBarLight = true else if (lum < 0.58f) bottomBarLight = false
+ }
+ }
+ val topFg by animateColorAsState(if (topBarLight) Color(0xFF15171C) else Color.White, tween(200), label = "topBarInk")
+ val bottomFg by animateColorAsState(if (bottomBarLight) Color(0xFF15171C) else Color.White, tween(200), label = "bottomBarInk")
+ val topFgSoft = topFg.copy(alpha = 0.62f)
+ val bottomFgSoft = bottomFg.copy(alpha = 0.62f)
+
+ // The find bar is the one control that does NOT sit at the screen edge: with the keyboard up
+ // it floats at the top of the IME, so the bottom-of-screen band (behind the keyboard) is the
+ // wrong reading for it. Sample the band directly above the IME instead, so its text and its
+ // prev/next/close icons adapt to the page content actually behind the search bar. When the
+ // keyboard is down the IME inset is 0 and this collapses to the same bottom band.
+ val imeInset = WindowInsets.ime
+ var findBarLight by remember { mutableStateOf(false) }
+ LaunchedEffect(containerHeightPx) {
+ snapshotFlow {
+ val h = containerHeightPx.toFloat()
+ if (h <= 0f) 0f
+ else {
+ val bottom = (h - imeInset.getBottom(density)).coerceAtLeast(bottomBandDepthPx)
+ bandLuminance(listState.layoutInfo, state.pageBitmaps, scale, bottom - bottomBandDepthPx, bottom)
+ }
+ }.collect { lum ->
+ if (lum > 0.62f) findBarLight = true else if (lum < 0.58f) findBarLight = false
+ }
+ }
+ val findFg by animateColorAsState(if (findBarLight) Color(0xFF15171C) else Color.White, tween(200), label = "findBarInk")
+ val findFgSoft = findFg.copy(alpha = 0.62f)
+
// ── Continuous vertical page column with document-level zoom/pan ─────
// layerBackdrop + background live INSIDE this Box so the captured layer holds
// the dark base + PDF pages; the glass chrome samples it (real reflections).
@@ -656,6 +822,7 @@ fun PdfViewerScreen(
pageCanvasSizes = pageCanvasSizes,
pageBitmapSizes = pageBitmapSizes,
onInteraction = { lastInteractionAtMs = System.currentTimeMillis() },
+ onMarkAdded = { recordEdit(page) },
onToggleControls = { controlsVisible = !controlsVisible },
onShowControls = { controlsVisible = true },
onActiveToolChanged = { activeTool = it },
@@ -668,12 +835,14 @@ fun PdfViewerScreen(
onPlaceText = { pt ->
val id = System.nanoTime()
getPageMarks(page).add(PdfMarkup.TextBoxMarkup(id, pt, "", currentColor, 40f))
+ recordEdit(page)
editingAnnoId = id; editingAnnoPage = page; editingAnnoIsNote = false; annotationDraft = ""
activeTool = PdfEditTool.None; controlsVisible = true
},
onPlaceNote = { pt ->
val id = System.nanoTime()
getPageMarks(page).add(PdfMarkup.NoteMarkup(id, pt, "", Color(0xFFFFC107)))
+ recordEdit(page)
editingAnnoId = id; editingAnnoPage = page; editingAnnoIsNote = true; annotationDraft = ""
activeTool = PdfEditTool.None; controlsVisible = true
},
@@ -772,39 +941,54 @@ fun PdfViewerScreen(
exit = fadeOut(tween(150)) + slideOutVertically { -it / 2 },
modifier = Modifier.align(Alignment.TopCenter)
) {
- // Compact, balanced top toolbar: back · centered page pill · search.
- // Page navigation lives in the right-edge scrubber + scroll, so no
- // oversized prev/next controls cover the document.
+ // Home and Tools' header trio, verbatim: back circle · centred [GlassTitlePill] ·
+ // search circle, 10 dp apart. The pill is the same widget carrying "ClearPDF" on
+ // Home rather than a look-alike `LiquidButton`, so the two screens can't drift; only
+ // the palette differs, because the viewer picks its chrome from the *page's*
+ // luminance instead of the theme.
+ //
+ // Page navigation lives in the right-edge scrubber + scroll, so no oversized
+ // prev/next controls cover the document.
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth()
) {
- LiquidIconButton(onClick = onBack, backdrop = contentBackdrop, surfaceColor = chromeGlass) {
- Icon(Icons.Rounded.ArrowBackIosNew, stringResource(R.string.back), Modifier.size(16.dp), chromeFg)
+ // No `surfaceColor`, exactly as Home calls it: the circle paints nothing of its own
+ // and is pure refraction. Only the icon's colour adapts to the page.
+ LiquidIconButton(onClick = onBack, backdrop = contentBackdrop) {
+ Icon(Icons.Rounded.ArrowBackIosNew, stringResource(R.string.back), Modifier.size(16.dp), topFg)
}
- Spacer(Modifier.weight(1f))
- LiquidButton(
- onClick = { showPageJumpDialog = true },
- backdrop = contentBackdrop,
- surfaceColor = chromeGlass
- ) {
- BasicText(
- stringResource(R.string.viewer_page_of, currentPageIndex + 1, safePageCount),
- style = TextStyle(chromeFg, 13.sp, FontWeight.SemiBold)
+ // A weighted Box rather than two weighted spacers: the back circle and the
+ // search circle are the same 40 dp, so this centres the pill on the row exactly
+ // the way Home's header does, and a long "Page 100 / 1000" grows symmetrically.
+ Box(Modifier.weight(1f), contentAlignment = Alignment.Center) {
+ GlassTitlePill(
+ text = stringResource(R.string.viewer_page_of, currentPageIndex + 1, safePageCount),
+ backdrop = contentBackdrop,
+ onClick = { showPageJumpDialog = true },
+ // Transparent, not omitted: omitting falls back to the theme's 0.35 tint,
+ // and this pill sits between two circles that paint nothing at all, so any
+ // tint at all makes it read as a slab bolted between two pieces of glass.
+ // `drawRect(Color.Transparent)` is the same no-op `LiquidIconButton`
+ // performs when it is given no `surfaceColor`.
+ surfaceColor = Color.Transparent,
+ contentColor = topFg,
+ // The enclosing AnimatedVisibility already slides and fades the whole bar
+ // in every time the chrome returns; the pill's own spring would stack on
+ // top of that and read as a stutter. Same call the find bar makes.
+ animateIn = false
)
}
- Spacer(Modifier.weight(1f))
LiquidIconButton(
onClick = {
showFindBar = !showFindBar
if (showFindBar) viewModel.triggerOcrForAllPages(context)
else { focusManager.clearFocus(); viewModel.clearSearch(); findQuery = "" }
},
- backdrop = contentBackdrop,
- surfaceColor = chromeGlass
+ backdrop = contentBackdrop
) {
- Icon(Icons.Rounded.Search, stringResource(R.string.viewer_find), Modifier.size(20.dp), chromeFg)
+ Icon(Icons.Rounded.Search, stringResource(R.string.viewer_find), Modifier.size(20.dp), topFg)
}
}
}
@@ -836,13 +1020,15 @@ fun PdfViewerScreen(
selectedTextCount = state.selectedOcrBlockIdsByPage[currentPageIndex]?.size ?: 0,
currentSelectedIds = state.selectedOcrBlockIdsByPage[currentPageIndex].orEmpty(),
activeIsSignature = activeItem?.isSignature == true,
- // Undo + all page-scoped edit actions must target the SYNCHRONOUS visible
- // page (currentPageIndex = listState.firstVisibleItemIndex), NOT the async
- // state.currentPage mirror updated via snapshotFlow. Drawing/placement inside
- // the LazyColumn item uses that same synchronous index, so keying the toolbar
- // to state.currentPage caused a transient mismatch right after open/scroll →
- // undo removed from the wrong (empty) page list and no-op'd on the first try.
- currentPageMarks = getPageMarks(currentPageIndex),
+ // 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
+ // `listState.firstVisibleItemIndex` (the first *partially* visible page, which
+ // while you draw is usually a sliver of the PREVIOUS page). Both removed from the
+ // wrong, usually empty, list. There is no page index that reliably means "what
+ // the user just did", so the viewer records each addition instead.
+ 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) },
onToggleFindBar = {
showFindBar = !showFindBar
@@ -899,31 +1085,14 @@ fun PdfViewerScreen(
onOpenExportedFile = { state.lastExportedUri?.let { viewModel.openPdf(context, it) } },
onOpenAnotherPdf = { pdfPickerLauncher.launch(arrayOf("*/*")) },
onEditorOpenChanged = { editorToolsOpen = it },
- onShareDocument = {
- val uri = state.document?.uri
- if (uri != null) {
- // A file:// uri can't be handed to other apps directly; wrap it via
- // the app FileProvider. content:// uris share as-is.
- val shareUri = if (uri.scheme == "file") {
- runCatching {
- androidx.core.content.FileProvider.getUriForFile(
- context, "${context.packageName}.provider", java.io.File(uri.path!!)
- )
- }.getOrNull() ?: uri
- } else uri
- val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
- type = "application/pdf"
- putExtra(android.content.Intent.EXTRA_STREAM, shareUri)
- addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION)
- }
- runCatching {
- context.startActivity(
- android.content.Intent.createChooser(send, null)
- .addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
- )
- }
- }
- },
+ // Bumping the timestamp on RELEASE is half the fix: otherwise the hold ends and
+ // the effect resumes a window that is already most of the way expired, so the
+ // chrome blinks out a moment after the finger lifts.
+ onShareHoldChanged = { shareHolding = it; lastInteractionAtMs = System.currentTimeMillis() },
+ // Share now opens the export chooser instead of firing a PDF straight out — a
+ // .docx used to always leave as the converted PDF, silently. The dialog lets the
+ // user pick the original file vs a PDF (and encrypt the PDF). See ExportShareDialog.
+ onShareDocument = { showShareDialog = true },
onRecolorSignature = { cl ->
activeImageLoc()?.let { (pg, idx, sig) ->
if (sig.isSignature) getPageMarks(pg)[idx] = sig.copy(bitmap = recolorSignatureBitmap(sig.bitmap, Color(cl).toArgb()))
@@ -931,8 +1100,8 @@ fun PdfViewerScreen(
},
backdrop = contentBackdrop,
uiSensor = uiSensor,
- fg = chromeFg,
- fgSoft = chromeFgSoft,
+ fg = bottomFg,
+ fgSoft = bottomFgSoft,
glass = chromeGlass,
chip = chromeField,
docKind = com.chethan616.clearpdf.utils.docKindOf(state.fileName)
@@ -958,8 +1127,8 @@ fun PdfViewerScreen(
focusRequester = findFocusRequester,
backdrop = contentBackdrop,
uiSensor = uiSensor,
- fg = chromeFg,
- fgSoft = chromeFgSoft,
+ fg = findFg,
+ fgSoft = findFgSoft,
surface = chromeGlass,
onQueryChange = { q -> findQuery = q; viewModel.searchText(q) },
onPrevMatch = { viewModel.prevMatch(); lastInteractionAtMs = System.currentTimeMillis() },
@@ -975,9 +1144,9 @@ fun PdfViewerScreen(
pageCount = safePageCount,
backdrop = contentBackdrop,
uiSensor = uiSensor,
- fg = chromeFg,
- fgSoft = chromeFgSoft,
- surface = chromeGlass,
+ fg = panelFg,
+ fgSoft = panelFgSoft,
+ surface = chromePanel,
field = chromeField,
onDismiss = { showPageJumpDialog = false },
onJumpToPage = { targetPage -> showPageJumpDialog = false; scrollToPage(targetPage) }
@@ -993,9 +1162,9 @@ fun PdfViewerScreen(
initialColor = editingAnnoColor,
backdrop = contentBackdrop,
uiSensor = uiSensor,
- fg = chromeFg,
- fgSoft = chromeFgSoft,
- surface = chromeGlass,
+ fg = panelFg,
+ fgSoft = panelFgSoft,
+ surface = chromePanel,
field = chromeField,
onDismiss = {
getPageMarks(editingAnnoPage).removeAll { m -> matches(m) &&
@@ -1031,9 +1200,9 @@ fun PdfViewerScreen(
initialColor = shape.shapeColor(),
backdrop = contentBackdrop,
uiSensor = uiSensor,
- fg = chromeFg,
- fgSoft = chromeFgSoft,
- surface = chromeGlass,
+ fg = panelFg,
+ fgSoft = panelFgSoft,
+ surface = chromePanel,
field = chromeField,
onColorChange = { c ->
val cur = list.getOrNull(editingShapeIndex)
@@ -1057,9 +1226,9 @@ fun PdfViewerScreen(
initialFileName = state.document?.name?.substringBeforeLast('.')?.let { "${it}_Edited" } ?: "Document",
backdrop = contentBackdrop,
uiSensor = uiSensor,
- fg = chromeFg,
- fgSoft = chromeFgSoft,
- surface = chromeGlass,
+ fg = panelFg,
+ fgSoft = panelFgSoft,
+ surface = chromePanel,
field = chromeField,
onDismiss = { showSaveDialog = false },
onSave = { fileName, overrideUri ->
@@ -1068,6 +1237,83 @@ fun PdfViewerScreen(
if (overlays.isNotEmpty()) viewModel.exportEditedPdf(context, overlays, fileName, overrideUri)
}
)
+
+ // ── Share / export chooser ──
+ // Original vs PDF (with optional encryption). `originalExt` is null for a plain PDF, which
+ // collapses the dialog to just the encrypt toggle.
+ val shareExt = state.fileName.substringAfterLast('.', "").uppercase()
+ ExportShareDialog(
+ visible = showShareDialog,
+ originalExt = if (shareExt.isNotBlank() && shareExt != "PDF") shareExt else null,
+ backdrop = contentBackdrop,
+ uiSensor = uiSensor,
+ fg = panelFg,
+ fgSoft = panelFgSoft,
+ surface = chromePanel,
+ field = chromeField,
+ onDismiss = { showShareDialog = false },
+ onShare = { format, encrypt, password ->
+ showShareDialog = false
+ viewerScope.launch {
+ // All file work off the main thread: copy/encrypt, then hand a FileProvider uri to
+ // the chooser. Everything lands in cacheDir/shared, which the app FileProvider
+ // serves (file_paths.xml cache-path "/").
+ val payload = withContext(Dispatchers.IO) {
+ runCatching {
+ fun wrap(u: android.net.Uri): android.net.Uri =
+ if (u.scheme == "file")
+ androidx.core.content.FileProvider.getUriForFile(
+ context, "${context.packageName}.provider", java.io.File(u.path!!)
+ )
+ else u
+ val shareDir = java.io.File(context.cacheDir, "shared").apply { mkdirs() }
+ when (format) {
+ ShareFormat.ORIGINAL -> state.originalUri?.let { orig ->
+ // Mirror the original into our own storage so the target app can
+ // actually read it — a SAF uri from another provider can't be
+ // re-granted to a third app.
+ val safeName = state.fileName.ifBlank { "document.$shareExt" }
+ .replace(Regex("[^A-Za-z0-9._-]"), "_")
+ val out = java.io.File(shareDir, "${System.currentTimeMillis()}_$safeName")
+ context.contentResolver.openInputStream(orig)?.use { input ->
+ out.outputStream().use { input.copyTo(it) }
+ } ?: return@runCatching null
+ androidx.core.content.FileProvider.getUriForFile(
+ context, "${context.packageName}.provider", out
+ ) to (context.contentResolver.getType(orig) ?: "application/octet-stream")
+ }
+ ShareFormat.PDF -> state.document?.uri?.let { pdf ->
+ if (encrypt && password.isNotBlank()) {
+ val out = java.io.File(shareDir, "protected_${System.currentTimeMillis()}.pdf")
+ val outUri = androidx.core.content.FileProvider.getUriForFile(
+ context, "${context.packageName}.provider", out
+ )
+ com.kyant.pdfcore.security.PdfSecurityService.encryptToUri(context, pdf, outUri, password)
+ outUri to "application/pdf"
+ } else {
+ wrap(pdf) to "application/pdf"
+ }
+ }
+ }
+ }.getOrNull()
+ }
+ if (payload != null) {
+ val (shareUri, mime) = payload
+ val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
+ type = mime
+ putExtra(android.content.Intent.EXTRA_STREAM, shareUri)
+ addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ }
+ runCatching {
+ context.startActivity(
+ android.content.Intent.createChooser(send, null)
+ .addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
+ )
+ }
+ }
+ }
+ }
+ )
}
// ── Dialogs ───────────────────────────────────────────────────────────
@@ -1099,6 +1345,79 @@ fun PdfViewerScreen(
* resolution. Drives the viewer's adaptive chrome contrast (dark ink on light pages,
* white ink on dark pages).
*/
+/**
+ * Perceptual luminance of a vertical slice `[fTop, fBottom]` (fractions of height) of [bitmap],
+ * sampled on a sparse 8x5 grid across the central 80% of the width. Deliberately uses `getPixel`
+ * on the live bitmap rather than `createScaledBitmap` so it is cheap enough to run per scroll frame.
+ * Central-width only: the far edges are usually margins that don't sit under a control.
+ */
+private fun regionLuminance(bitmap: Bitmap, fTop: Float, fBottom: Float): Float = runCatching {
+ val w = bitmap.width
+ val h = bitmap.height
+ if (w <= 0 || h <= 0) return@runCatching 0f
+ val y0 = (fTop.coerceIn(0f, 1f) * h).toInt().coerceIn(0, h - 1)
+ val y1 = (fBottom.coerceIn(0f, 1f) * h).toInt().coerceIn(y0 + 1, h)
+ val x0 = (w * 0.1f).toInt().coerceIn(0, w - 1)
+ val x1 = (w * 0.9f).toInt().coerceIn(x0 + 1, w)
+ val cols = 8
+ val rows = 5
+ var sum = 0.0
+ var n = 0
+ for (r in 0 until rows) {
+ val py = (y0 + (y1 - y0) * (r + 0.5f) / rows).toInt().coerceIn(0, h - 1)
+ for (c in 0 until cols) {
+ val px = (x0 + (x1 - x0) * (c + 0.5f) / cols).toInt().coerceIn(0, w - 1)
+ val p = bitmap.getPixel(px, py)
+ val rr = ((p shr 16) and 0xFF) / 255.0
+ val gg = ((p shr 8) and 0xFF) / 255.0
+ val bb = (p and 0xFF) / 255.0
+ sum += 0.299 * rr + 0.587 * gg + 0.114 * bb
+ n++
+ }
+ }
+ if (n == 0) 0f else (sum / n).toFloat()
+}.getOrDefault(0f)
+
+/**
+ * Average luminance of the document content behind a screen-space horizontal band
+ * `[screenTopPx, screenBottomPx]`, i.e. behind one of the floating bars.
+ *
+ * The content Box scales about a top origin with `translationY = 0`, and the LazyColumn's
+ * `visibleItemsInfo.offset` is already in list-local (unscaled, viewport-relative, centring-folded)
+ * coordinates — so a screen Y maps to list-local as `screenY / scale`. Each visible page item that
+ * intersects the band contributes its overlapping slice, weighted by how much of the band it covers.
+ * Returns 0 (→ dark → white ink) when the band sits over the empty letterbox with no page under it,
+ * which is exactly what a single unzoomed page's centred layout should read as behind its bars.
+ */
+private fun bandLuminance(
+ layoutInfo: LazyListLayoutInfo,
+ pageBitmaps: List<Bitmap?>,
+ scale: Float,
+ screenTopPx: Float,
+ screenBottomPx: Float
+): Float {
+ val s = scale.coerceAtLeast(0.01f)
+ val lTop = screenTopPx / s
+ val lBottom = screenBottomPx / s
+ var lum = 0.0
+ var weight = 0.0
+ for (item in layoutInfo.visibleItemsInfo) {
+ if (item.size <= 0) continue
+ val io = item.offset.toFloat()
+ val ib = io + item.size.toFloat()
+ val interTop = maxOf(io, lTop)
+ val interBottom = minOf(ib, lBottom)
+ val cover = interBottom - interTop
+ if (cover <= 0f) continue
+ val bmp = pageBitmaps.getOrNull(item.index) ?: continue
+ val fTop = (interTop - io) / item.size
+ val fBottom = (interBottom - io) / item.size
+ lum += regionLuminance(bmp, fTop, fBottom).toDouble() * cover
+ weight += cover.toDouble()
+ }
+ return if (weight <= 0.0) 0f else (lum / weight).toFloat()
+}
+
private fun averageLuminance(bitmap: Bitmap): Float = runCatching {
val w = 12
val h = 16
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/SettingsScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/SettingsScreen.kt
index 0f7e52d..0ba8e02 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/SettingsScreen.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/SettingsScreen.kt
@@ -8,6 +8,7 @@ import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
+import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -26,6 +27,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.rounded.AutoAwesome
import androidx.compose.material.icons.rounded.AutoFixHigh
import androidx.compose.material.icons.rounded.Code
import androidx.compose.material.icons.rounded.Compress
@@ -94,7 +96,8 @@ fun SettingsScreen(
hasCustomWallpaper: Boolean = false,
onCustomWallpaperChanged: (String?) -> Unit = {},
selectedLocale: String = "en",
- onLocaleChanged: (String) -> Unit = {}
+ onLocaleChanged: (String) -> Unit = {},
+ onReplayOnboarding: () -> Unit = {}
) {
val isLight = !isDarkMode
val text = if (isLight) Color(0xFF222222) else Color(0xFFF0F0F0)
@@ -616,6 +619,36 @@ fun SettingsScreen(
}
}
}
+
+ // Replaying the tour also clears the completion flag (see the nav graph), so quitting
+ // the replay early does not leave it marked as seen-but-never-finished.
+ Spacer(Modifier.height(12.dp))
+ LiquidButton(
+ onClick = onReplayOnboarding,
+ backdrop = backdrop,
+ surfaceColor = if (isLight) Color.Black.copy(0.06f) else Color.White.copy(0.10f),
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Row(
+ Modifier.fillMaxWidth(),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ Icon(Icons.Rounded.AutoAwesome, null, Modifier.size(18.dp), label)
+ Column(Modifier.weight(1f)) {
+ BasicText(
+ stringResource(R.string.settings_replay_onboarding),
+ style = TextStyle(text, 14.sp, fontWeight = FontWeight.SemiBold),
+ maxLines = 1, overflow = TextOverflow.Ellipsis
+ )
+ BasicText(
+ stringResource(R.string.settings_replay_onboarding_desc),
+ style = TextStyle(sub, 12.sp),
+ maxLines = 1, overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+ }
}
// ── About & Open Source ──
@@ -804,6 +837,16 @@ private fun LicenseItem(
BasicText(stringResource(R.string.settings_license_author, author), style = TextStyle(subColor, 12.sp))
}
BasicText(license, style = TextStyle(subColor, 11.sp))
- BasicText(url, style = TextStyle(Color(0xFF0088FF), 11.sp))
+ val context = LocalContext.current
+ // Same blue URL text, now a tap target that opens the repo. No indication/ripple so the row
+ // looks exactly as before — only its behaviour changes.
+ BasicText(
+ url,
+ style = TextStyle(Color(0xFF0088FF), 11.sp),
+ modifier = Modifier.clickable(
+ interactionSource = remember { MutableInteractionSource() },
+ indication = null
+ ) { openExternalLink(context, url) }
+ )
}
}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/SignaturePadDialog.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/SignaturePadDialog.kt
index 2273656..2f80944 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/SignaturePadDialog.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/SignaturePadDialog.kt
@@ -11,6 +11,9 @@ import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
+import androidx.compose.animation.core.Spring
+import androidx.compose.animation.core.animateDpAsState
+import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
@@ -58,6 +61,7 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.StrokeCap
@@ -81,6 +85,7 @@ import androidx.compose.ui.window.DialogProperties
import com.chethan616.clearpdf.ui.components.LiquidButton
import com.chethan616.clearpdf.ui.components.LiquidIconButton
import com.chethan616.clearpdf.ui.components.LiquidSlider
+import com.chethan616.clearpdf.ui.theme.LocalIsDarkMode
import com.chethan616.clearpdf.ui.utils.rememberUISensor
import com.kyant.backdrop.backdrops.LayerBackdrop
import kotlinx.coroutines.delay
@@ -100,6 +105,23 @@ fun SignaturePadDialog(
val uiSensor = rememberUISensor()
val scope = rememberCoroutineScope()
+ // Theme-adaptive chrome. Everything that sits on the SCREEN background — header, action buttons,
+ // section labels — flips with the app theme: white ink on the dark screen, near-black on the
+ // light one. The signing paper (canvas) and the control tray stay light in both, so dark ink is
+ // always visible while drawing and stamps legibly onto white PDF pages.
+ val isDark = LocalIsDarkMode.current
+ val chrome = if (isDark) Color.White else Color(0xFF15171C)
+ val chromeSoft = chrome.copy(0.55f)
+ val chromeChip = if (isDark) Color.White.copy(0.08f) else Color.Black.copy(0.05f)
+ val screenGradient = if (isDark)
+ listOf(Color(0xFF171A21), Color(0xFF0C0E13), Color(0xFF060709))
+ else
+ listOf(Color(0xFFF3F4F6), Color(0xFFEAECEF), Color(0xFFE2E5E9))
+ // Light control tray: paper-on-dark needs no outline; white-on-light needs a hairline to define
+ // its edge against the near-white screen.
+ val trayColor = if (isDark) Color(0xFFF2F2EE) else Color(0xFFFFFFFF)
+ val cardBorder = if (isDark) Color.Transparent else Color.Black.copy(0.06f)
+
data class StrokeItem(val points: List<Offset>, val color: Color, val width: Float)
val strokes = remember { mutableStateListOf<StrokeItem>() }
var currentStroke by remember { mutableStateOf<List<Offset>>(emptyList()) }
@@ -198,7 +220,13 @@ fun SignaturePadDialog(
enter = fadeIn(tween(200)) + slideInHorizontally(tween(300)) { it / 3 },
exit = fadeOut(tween(200)) + slideOutHorizontally(tween(260)) { it / 3 }
) {
- Box(Modifier.fillMaxSize().background(Color(0xFF0A0A0A))) {
+ Box(
+ Modifier
+ .fillMaxSize()
+ // A soft top-lit gradient (dark or light per theme) gives the screen depth and
+ // lets the light signing cards read as "paper on a desk" rather than floating.
+ .background(Brush.verticalGradient(screenGradient))
+ ) {
Column(
Modifier
.fillMaxSize()
@@ -216,27 +244,33 @@ fun SignaturePadDialog(
LiquidIconButton(
onClick = requestClose,
backdrop = backdrop,
- surfaceColor = Color.White.copy(0.08f),
+ surfaceColor = chromeChip,
modifier = Modifier.size(44.dp)
) {
- Icon(Icons.Rounded.ArrowBackIosNew, stringResource(R.string.back), Modifier.size(18.dp), Color.White)
+ Icon(Icons.Rounded.ArrowBackIosNew, stringResource(R.string.back), Modifier.size(18.dp), chrome)
}
- BasicText(
- stringResource(R.string.sig_draw_title),
- style = TextStyle(Color.White, 18.sp, FontWeight.Bold)
- )
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ Icon(Icons.Rounded.Gesture, null, Modifier.size(19.dp), chromeSoft)
+ BasicText(
+ stringResource(R.string.sig_draw_title),
+ style = TextStyle(chrome, 18.sp, FontWeight.Bold, letterSpacing = 0.2.sp)
+ )
+ }
LiquidIconButton(
onClick = { if (strokes.isNotEmpty()) strokes.removeAt(strokes.lastIndex) },
backdrop = backdrop,
- surfaceColor = Color.White.copy(0.08f),
+ surfaceColor = chromeChip,
modifier = Modifier.size(44.dp)
) {
// Subtle when there's nothing to undo.
Icon(
Icons.Rounded.Undo, stringResource(R.string.undo), Modifier.size(20.dp),
- Color.White.copy(if (strokes.isEmpty()) 0.32f else 1f)
+ chrome.copy(if (strokes.isEmpty()) 0.32f else 1f)
)
}
}
@@ -249,7 +283,8 @@ fun SignaturePadDialog(
Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(22.dp))
- .background(Color(0xFFF2F2EE))
+ .background(trayColor)
+ .border(1.dp, cardBorder, RoundedCornerShape(22.dp))
.padding(horizontal = 18.dp, vertical = 12.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(12.dp)
@@ -262,6 +297,13 @@ fun SignaturePadDialog(
) {
signatureColors.forEach { color ->
val isSelected = selectedColor == color
+ // Springy grow on selection instead of a hard size jump — the bead reads as
+ // a physical thing you press, matching the rest of the liquid chrome.
+ val beadSize by animateDpAsState(
+ if (isSelected) 40.dp else 30.dp,
+ spring(dampingRatio = 0.55f, stiffness = Spring.StiffnessMediumLow),
+ label = "beadSize"
+ )
LiquidIconButton(
onClick = {
selectedColor = color
@@ -273,7 +315,7 @@ fun SignaturePadDialog(
},
backdrop = backdrop,
surfaceColor = color,
- modifier = Modifier.size(if (isSelected) 38.dp else 30.dp)
+ modifier = Modifier.size(beadSize)
) {
if (isSelected) Icon(Icons.Rounded.Check, null, Modifier.size(17.dp), Color.White)
}
@@ -417,7 +459,7 @@ fun SignaturePadDialog(
Spacer(Modifier.height(10.dp))
BasicText(
stringResource(R.string.sig_saved_title),
- style = TextStyle(Color.White.copy(0.7f), 12.sp, FontWeight.SemiBold)
+ style = TextStyle(chrome.copy(0.6f), 12.sp, FontWeight.SemiBold, letterSpacing = 0.3.sp)
)
Row(
Modifier
@@ -454,8 +496,10 @@ fun SignaturePadDialog(
Modifier
.size(84.dp, 50.dp)
.clip(RoundedCornerShape(10.dp))
- .background(Color(0xFFF2F2EE))
- .border(1.dp, Color.White.copy(0.16f), RoundedCornerShape(10.dp)),
+ .background(Color(0xFFF7F7F3))
+ // A dark hairline reads on the light paper tile; the old white
+ // border was invisible against it.
+ .border(1.dp, Color.Black.copy(0.08f), RoundedCornerShape(10.dp)),
contentAlignment = Alignment.Center
) {
androidx.compose.foundation.Image(
@@ -467,7 +511,7 @@ fun SignaturePadDialog(
}
BasicText(
savedBmp.name,
- style = TextStyle(Color.White.copy(0.7f), 10.sp, FontWeight.Medium),
+ style = TextStyle(chrome.copy(0.7f), 10.sp, FontWeight.Medium),
maxLines = 1
)
}
@@ -489,12 +533,12 @@ fun SignaturePadDialog(
LiquidButton(
onClick = { if (hasInk) { strokes.clear(); currentStroke = emptyList() } },
backdrop = backdrop,
- surfaceColor = Color.White.copy(if (hasInk) 0.10f else 0.04f),
+ surfaceColor = chrome.copy(if (hasInk) 0.10f else 0.04f),
modifier = Modifier.weight(1f)
) {
BasicText(
stringResource(R.string.sig_clear),
- style = TextStyle(Color.White.copy(if (hasInk) 0.85f else 0.32f), 15.sp, FontWeight.Medium),
+ style = TextStyle(chrome.copy(if (hasInk) 0.85f else 0.32f), 15.sp, FontWeight.Medium),
modifier = Modifier.padding(vertical = 9.dp)
)
}
@@ -578,18 +622,18 @@ fun SignaturePadDialog(
Modifier
.fillMaxWidth(0.82f)
.clip(RoundedCornerShape(24.dp))
- .background(Color(0xFF1B1E25))
- .border(1.dp, Color.White.copy(0.12f), RoundedCornerShape(24.dp))
+ .background(if (isDark) Color(0xFF1B1E25) else Color.White)
+ .border(1.dp, if (isDark) Color.White.copy(0.12f) else Color.Black.copy(0.08f), RoundedCornerShape(24.dp))
.padding(22.dp),
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
BasicText(
stringResource(R.string.sig_delete_title),
- style = TextStyle(Color.White, 17.sp, FontWeight.Bold)
+ style = TextStyle(chrome, 17.sp, FontWeight.Bold)
)
BasicText(
stringResource(R.string.sig_delete_msg, sig.name),
- style = TextStyle(Color.White.copy(0.72f), 14.sp)
+ style = TextStyle(chrome.copy(0.72f), 14.sp)
)
Row(
Modifier.fillMaxWidth(),
@@ -598,9 +642,9 @@ fun SignaturePadDialog(
LiquidButton(
onClick = { signatureToDelete = null },
backdrop = backdrop,
- surfaceColor = Color.White.copy(0.10f)
+ surfaceColor = chromeChip
) {
- BasicText(stringResource(R.string.cancel), style = TextStyle(Color.White, 13.sp), modifier = Modifier.padding(vertical = 4.dp))
+ BasicText(stringResource(R.string.cancel), style = TextStyle(chrome, 13.sp), modifier = Modifier.padding(vertical = 4.dp))
}
LiquidButton(
onClick = {
@@ -632,6 +676,13 @@ private fun SignatureNameDialog(
onSave: () -> Unit
) {
val canSave = name.trim().isNotEmpty()
+ // Same theme-adaptive chrome as the signing screen so the naming sheet matches it in both modes.
+ val isDark = LocalIsDarkMode.current
+ val chrome = if (isDark) Color.White else Color(0xFF15171C)
+ val cardBg = if (isDark) Color(0xFF1B1E25) else Color.White
+ val cardBorder = if (isDark) Color.White.copy(0.12f) else Color.Black.copy(0.08f)
+ val fieldBg = if (isDark) Color.White.copy(0.12f) else Color.Black.copy(0.05f)
+ val chipBg = if (isDark) Color.White.copy(0.08f) else Color.Black.copy(0.05f)
LaunchedEffect(Unit) {
delay(150)
@@ -643,40 +694,40 @@ private fun SignatureNameDialog(
Modifier
.fillMaxWidth(0.9f)
.clip(RoundedCornerShape(26.dp))
- // Solid dark card (matches the signature screen) instead of sampling
+ // Solid card (matches the signature screen) instead of sampling
// the wallpaper PNG through glass in a separate Dialog window.
- .background(Color(0xFF1B1E25))
- .border(1.dp, Color.White.copy(0.12f), RoundedCornerShape(26.dp))
+ .background(cardBg)
+ .border(1.dp, cardBorder, RoundedCornerShape(26.dp))
.padding(20.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
BasicText(
stringResource(R.string.sig_name_title),
- style = TextStyle(Color.White, 16.sp, FontWeight.Bold)
+ style = TextStyle(chrome, 16.sp, FontWeight.Bold)
)
Row(
Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(12.dp))
- .background(Color.White.copy(0.12f))
+ .background(fieldBg)
.padding(horizontal = 12.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
- Icon(Icons.Rounded.Gesture, null, Modifier.size(18.dp), Color.White.copy(0.6f))
+ Icon(Icons.Rounded.Gesture, null, Modifier.size(18.dp), chrome.copy(0.6f))
Box(Modifier.weight(1f)) {
if (name.isEmpty()) {
BasicText(
stringResource(R.string.sig_name_hint),
- style = TextStyle(Color.White.copy(0.45f), 14.sp)
+ style = TextStyle(chrome.copy(0.45f), 14.sp)
)
}
BasicTextField(
value = name,
onValueChange = onNameChange,
- textStyle = TextStyle(Color.White, 14.sp),
- cursorBrush = SolidColor(Color.White),
+ textStyle = TextStyle(chrome, 14.sp),
+ cursorBrush = SolidColor(chrome),
singleLine = true,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = { if (canSave) onSave() }),
@@ -695,24 +746,24 @@ private fun SignatureNameDialog(
LiquidButton(
onClick = onDismiss,
backdrop = backdrop,
- surfaceColor = Color.White.copy(0.08f),
+ surfaceColor = chipBg,
modifier = Modifier.width(100.dp)
) {
BasicText(
stringResource(R.string.cancel),
- style = TextStyle(Color.White.copy(0.78f), 13.sp, FontWeight.Medium),
+ style = TextStyle(chrome.copy(0.78f), 13.sp, FontWeight.Medium),
modifier = Modifier.padding(vertical = 4.dp)
)
}
LiquidButton(
onClick = { if (canSave) onSave() },
backdrop = backdrop,
- tint = if (canSave) Color(0xFF00C853) else Color.White.copy(0.08f),
+ tint = if (canSave) Color(0xFF00C853) else chipBg,
modifier = Modifier.width(110.dp)
) {
BasicText(
stringResource(R.string.sig_name_save),
- style = TextStyle(Color.White.copy(if (canSave) 1f else 0.45f), 13.sp, FontWeight.SemiBold),
+ style = TextStyle((if (canSave) Color.White else chrome).copy(if (canSave) 1f else 0.45f), 13.sp, FontWeight.SemiBold),
modifier = Modifier.padding(vertical = 4.dp)
)
}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/SpreadsheetViewerScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/SpreadsheetViewerScreen.kt
index 30d93d8..6c46f62 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/SpreadsheetViewerScreen.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/SpreadsheetViewerScreen.kt
@@ -72,6 +72,7 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.pointer.pointerInput
@@ -87,9 +88,11 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.chethan616.clearpdf.R
import com.chethan616.clearpdf.ui.components.GlassScreenScaffold
+import com.chethan616.clearpdf.ui.components.GlassTitlePill
import com.chethan616.clearpdf.ui.components.LiquidButton
import com.chethan616.clearpdf.ui.components.LiquidIconButton
import com.chethan616.clearpdf.ui.components.ShareMorphButton
+import com.chethan616.clearpdf.ui.components.liquidGlassPanel
import com.chethan616.clearpdf.ui.components.viewerChromeGlass
import com.chethan616.clearpdf.ui.components.viewerGlass
import com.chethan616.clearpdf.ui.theme.LiquidGlassColors
@@ -97,10 +100,19 @@ import com.chethan616.clearpdf.ui.theme.LocalIsDarkMode
import com.chethan616.clearpdf.ui.utils.rememberUISensor
import com.chethan616.clearpdf.ui.viewmodel.SpreadsheetViewModel
import com.kyant.backdrop.backdrops.LayerBackdrop
+import com.kyant.shapes.RoundedRectangle
private val CELL_W = 132.dp
private val CELL_H = 38.dp
+/**
+ * `liquidGlassPanel`'s own corner curve, restated so the scrolling grid can be clipped to it.
+ *
+ * The panel is read-only and its radius lives in a default argument, so this is a copy rather than
+ * a reference. Keep the two in step — a clip that disagrees with the paint reads as a chipped edge.
+ */
+private val GlassPanelShape: Shape = RoundedRectangle(28f.dp)
+
/** The cell a tap selected, carried into the value/edit popup. */
private data class CellRef(val row: Int, val col: Int, val value: String)
@@ -183,33 +195,38 @@ fun SpreadsheetViewerScreen(
backdrop = backdrop,
contentHorizontalPadding = 12.dp,
headerHorizontalPadding = 12.dp,
- // Header — the EXACT PDF-viewer top bar: back · centered liquid-glass pill · search.
- // The pill shows "Sheet X / Y" and (for multi-sheet files) opens a sheet picker on tap.
- // It is pinned over the grid and samples the content layer, so rows scroll *under* the
- // chrome and refract through it rather than pushing it down the screen.
+ // Header — Home and Tools' trio, verbatim: back circle · centred [GlassTitlePill] ·
+ // search circle, 10 dp apart. The pill is the same widget carrying "ClearPDF" on Home,
+ // so the two can't drift apart; it shows "Sheet X / Y" and (for multi-sheet files) opens
+ // a sheet picker on tap. It is pinned over the grid and samples the content layer, so
+ // rows scroll *under* the chrome and refract through it rather than pushing it down.
header = { headerBackdrop ->
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth()
) {
- LiquidIconButton(onClick = onBack, backdrop = headerBackdrop, surfaceColor = chromeGlass) {
+ // No `surfaceColor` — Home's circles paint nothing of their own and are pure
+ // refraction. The heavier `chromeGlass` tint that used to be here is still right
+ // for the grid container below, but on floating chrome it read as a grey slab.
+ LiquidIconButton(onClick = onBack, backdrop = headerBackdrop) {
Icon(Icons.Rounded.ArrowBackIosNew, stringResource(R.string.back), Modifier.size(16.dp), text)
}
- Spacer(Modifier.weight(1f))
- LiquidButton(
- onClick = { if (sheets.size > 1) showSheetPicker = true },
- backdrop = headerBackdrop,
- surfaceColor = chromeGlass
- ) {
- BasicText(
- if (currentSheet != null) stringResource(R.string.viewer_sheet_of, idx + 1, sheets.size)
+ // Weighted Box, not two weighted spacers — the two circles are both 40 dp, so
+ // this is what actually centres the pill on the row, the way Home does it.
+ Box(Modifier.weight(1f), contentAlignment = Alignment.Center) {
+ GlassTitlePill(
+ text = if (currentSheet != null) stringResource(R.string.viewer_sheet_of, idx + 1, sheets.size)
else state.fileName.ifBlank { stringResource(R.string.viewer_title) },
- style = TextStyle(text, 13.sp, FontWeight.SemiBold)
+ backdrop = headerBackdrop,
+ // No overrides at all, exactly as Home calls it. Both defaults already
+ // resolve to what this screen was passing by hand — the pill's own tint
+ // is the theme's, and its ink is `LiquidGlassColors.text(isDark)`, which
+ // is what `text` is here.
+ onClick = if (sheets.size > 1) ({ showSheetPicker = true }) else null
)
}
- Spacer(Modifier.weight(1f))
- LiquidIconButton(onClick = { showSearch = true }, backdrop = headerBackdrop, surfaceColor = chromeGlass) {
+ LiquidIconButton(onClick = { showSearch = true }, backdrop = headerBackdrop) {
Icon(Icons.Rounded.Search, stringResource(R.string.viewer_find), Modifier.size(20.dp), text)
}
}
@@ -223,17 +240,39 @@ fun SpreadsheetViewerScreen(
BasicText(state.error ?: "Empty spreadsheet", style = TextStyle(sub, 14.sp))
}
else -> {
- SheetGrid(
- sheet = currentSheet, isDark = isDark, text = text, sub = sub, accent = accent, zoom = zoom,
- listState = gridListState, matchSet = matchSet, currentCell = currentCell,
- onZoom = { z -> zoom = (zoom * z).coerceIn(0.7f, 2f) },
- onCellTap = { r, c, value ->
- selectedCell = CellRef(r, c, value)
- editingCell = false
- draft = value
- },
- modifier = Modifier.fillMaxSize().padding(contentPadding)
- )
+ // The grid used to sit straight on the wallpaper: cells are mostly transparent,
+ // so whatever photo was behind the app showed through the data. It now rides on
+ // the same heavy glass the sheet picker and the page-jump dialog use — blur 8,
+ // a 20x40 depth lens, highlight and inner shadow — which is the one place in
+ // this app that stack is right outside a dialog, because this *is* a reading
+ // surface that has to hold small text over an arbitrary backdrop.
+ //
+ // The tint is pushed well past `liquidGlassPanel`'s 40% default. At 40% a busy
+ // wallpaper still reads through 11 sp cell text. 72% keeps the refraction and
+ // the depth lens plainly visible while giving the type something to sit on.
+ val sheetSurface =
+ if (isDark) Color(0xFF15181E).copy(0.72f) else Color(0xFFF7F8FA).copy(0.72f)
+ Box(
+ Modifier
+ .fillMaxSize()
+ .padding(contentPadding)
+ .liquidGlassPanel(backdrop, uiSensor, containerColorOverride = sheetSurface)
+ // `liquidGlassPanel` paints its shape but does not clip, and the grid
+ // scrolls — without this the rows run out past the rounded corners.
+ .clip(GlassPanelShape)
+ ) {
+ SheetGrid(
+ sheet = currentSheet, isDark = isDark, text = text, sub = sub, accent = accent, zoom = zoom,
+ listState = gridListState, matchSet = matchSet, currentCell = currentCell,
+ onZoom = { z -> zoom = (zoom * z).coerceIn(0.7f, 2f) },
+ onCellTap = { r, c, value ->
+ selectedCell = CellRef(r, c, value)
+ editingCell = false
+ draft = value
+ },
+ modifier = Modifier.fillMaxSize()
+ )
+ }
}
}
}
@@ -468,7 +507,9 @@ private fun SheetGrid(
val colCount = sheet.columnCount.coerceAtLeast(1)
val hScroll = rememberScrollState() // shared → header + all rows scroll horizontally in sync
val gridLine = if (isDark) Color.White.copy(0.10f) else Color.Black.copy(0.10f)
- val headerBg = if (isDark) Color(0xFF23262E) else Color(0xFFF1F3F5)
+ // Translucent now that the grid sits on glass. An opaque header read as a solid slab pasted on
+ // top of the panel and cut the refraction dead across the first row.
+ val headerBg = if (isDark) Color.White.copy(0.07f) else Color.Black.copy(0.05f)
val rowAlt = if (isDark) Color.White.copy(0.03f) else Color.Black.copy(0.02f)
val matchBg = accent.copy(0.20f)
val currentBg = accent.copy(0.48f)
@@ -491,7 +532,9 @@ private fun SheetGrid(
}
Column(
- modifier.fillMaxSize().clip(RoundedCornerShape(12.dp)).border(1.dp, gridLine, RoundedCornerShape(12.dp))
+ // No clip/border of its own any more — the glass panel it now sits inside is the container,
+ // and a 12 dp rounded outline inside a 28 dp glass capsule read as a box within a box.
+ modifier.fillMaxSize()
// Pinch-to-zoom (Apple-HIG). Only two-finger gestures are consumed, so single-finger
// scrolling still passes through to the row/column scroll.
.pointerInput(Unit) {
@@ -515,10 +558,38 @@ private fun SheetGrid(
val fill = if (baseSum > 0.dp && baseSum < available) available / baseSum else 1f
val colWidths = baseWidths.map { it * fill * zoom }
+ // Left edge of every column in dp, with the grid's total width parked at [colCount].
+ val starts = remember(colWidths) {
+ val out = ArrayList<Float>(colCount + 1)
+ var acc = 0f
+ for (w in colWidths) { out.add(acc); acc += w.value }
+ out.add(acc)
+ out
+ }
+ // Horizontal windowing. `LazyColumn` keeps the row count in check, but each row was an
+ // eager `Row` over *every* column — a 150-column workbook is ~3000 cell nodes on screen,
+ // each with its own background, border, click handler and text layout. That does not
+ // throw; it just wedges the frame loop long enough to look like the app has died, and
+ // on a big enough sheet it is an ANR. Only the columns intersecting the viewport are
+ // composed now; the skipped ones on either side become a single spacer each, so the
+ // scroll range and every column's x-position are unchanged.
+ val scrolledDp = with(androidx.compose.ui.platform.LocalDensity.current) { hScroll.value.toDp().value }
+ val window = remember(starts, scrolledDp, available) {
+ val right = scrolledDp + available.value
+ var first = 0
+ while (first < colCount - 1 && starts[first + 1] <= scrolledDp) first++
+ var last = first
+ while (last < colCount - 1 && starts[last + 1] < right) last++
+ first..last
+ }
+ val leadWidth = starts[window.first].dp
+ val tailWidth = (starts[colCount] - starts[window.last + 1]).dp
+
Column(Modifier.fillMaxSize()) {
// Sticky column-letter header.
Row(Modifier.fillMaxWidth().background(headerBg).horizontalScroll(hScroll)) {
- for (c in 0 until colCount) {
+ Spacer(Modifier.width(leadWidth))
+ for (c in window) {
Box(
Modifier.width(colWidths[c]).heightIn(min = cellH).border(0.5.dp, gridLine).padding(horizontal = 8.dp),
contentAlignment = Alignment.CenterStart
@@ -526,11 +597,13 @@ private fun SheetGrid(
BasicText(colLetter(c), style = TextStyle(sub, headerSize, FontWeight.Bold))
}
}
+ Spacer(Modifier.width(tailWidth))
}
LazyColumn(Modifier.fillMaxWidth().weight(1f), state = listState) {
itemsIndexed(sheet.rows) { rIdx, row ->
Row(Modifier.fillMaxWidth().horizontalScroll(hScroll)) {
- for (c in 0 until colCount) {
+ Spacer(Modifier.width(leadWidth).heightIn(min = cellH))
+ for (c in window) {
val v = row.getOrElse(c) { "" }
val isCurrent = currentCell?.first == rIdx && currentCell.second == c
val cellBg = when {
@@ -550,6 +623,7 @@ private fun SheetGrid(
BasicText(v, style = TextStyle(text, cellSize), maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
+ Spacer(Modifier.width(tailWidth))
}
}
}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/CompressPdfViewModel.kt b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/CompressPdfViewModel.kt
index 8d770d1..72d862d 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/CompressPdfViewModel.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/CompressPdfViewModel.kt
@@ -10,6 +10,7 @@ import android.provider.MediaStore
import androidx.core.content.FileProvider
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
+import com.chethan616.clearpdf.data.repository.AppSettingsManager
import com.chethan616.clearpdf.data.repository.GitHubStarPromptManager
import com.chethan616.clearpdf.data.repository.RecentFile
import com.chethan616.clearpdf.data.repository.RecentFilesManager
@@ -52,6 +53,15 @@ class CompressPdfViewModel(private val compressPdfUseCase: CompressPdfUseCase) :
fun onSelectFile(context: Context, uri: Uri) {
viewModelScope.launch {
try {
+ // Honor the user's Default Quality setting instead of always starting on MEDIUM.
+ // Mapped with the same thresholds the slider uses (see onQualitySliderChanged), and
+ // the slider seeds to the raw stored value so its knob lands where the user set it.
+ val defaultQuality = AppSettingsManager.getDefaultQuality(context)
+ val quality = when {
+ defaultQuality < 0.33f -> CompressionQuality.LOW
+ defaultQuality < 0.66f -> CompressionQuality.MEDIUM
+ else -> CompressionQuality.HIGH
+ }
val (name, size, estimate) = withContext(AppDispatchers.pdf) {
try {
context.contentResolver.takePersistableUriPermission(
@@ -62,14 +72,15 @@ class CompressPdfViewModel(private val compressPdfUseCase: CompressPdfUseCase) :
val fileSize = context.contentResolver.openFileDescriptor(uri, "r")
?.use { it.statSize } ?: -1L
val source = PdfDocument(uri = uri, name = fileName, sizeBytes = fileSize)
- val est = compressPdfUseCase.estimateSize(source, CompressionQuality.MEDIUM)
+ val est = compressPdfUseCase.estimateSize(source, quality)
Triple(fileName, fileSize, est)
}
_uiState.value = CompressPdfUiState(
sourceFileName = name,
sourceUri = uri,
originalSizeBytes = size,
- qualitySlider = 0.5f,
+ selectedQuality = quality,
+ qualitySlider = defaultQuality,
estimatedSizeBytes = estimate
)
} catch (e: Exception) {
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 3155ed2..b2d8c14 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
@@ -134,6 +134,10 @@ data class PdfViewerUiState(
val passwordUri: Uri? = null,
val pageBitmaps: List<Bitmap?> = emptyList(),
val document: PdfDocument? = null,
+ // The uri the user actually opened — a plain PDF's own uri, or the ORIGINAL .docx/.pptx for a
+ // converted document (unlike [document].uri, which is the converted temp PDF). Lets Share offer
+ // "export as the original file" vs "export as PDF".
+ val originalUri: Uri? = null,
val sizeBytes: Long = -1,
val ocrBlocksByPage: Map<Int, List<OcrTextBlock>> = emptyMap(),
val ocrPagesInProgress: Set<Int> = emptySet(),
@@ -202,7 +206,7 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
else -> uri
}
}
- val (doc, openedUri) = withContext(Dispatchers.IO) {
+ val (doc, _) = withContext(Dispatchers.IO) {
openDocumentWithFallback(context, sourceUri)
}
val displayName = queryFileName(context, uri) ?: doc.name
@@ -215,6 +219,9 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
passwordAttemptFailed = false,
passwordUri = null,
document = doc,
+ // The original selection, so Share can offer the source file itself. For a
+ // password-opened PDF this is still the encrypted original the user picked.
+ originalUri = uri,
sizeBytes = doc.sizeBytes,
pageBitmaps = List(doc.pageCount) { null },
ocrBlocksByPage = emptyMap(),
@@ -225,9 +232,24 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
exportError = null,
lastExportedUri = null
)
+ // The ORIGINAL uri, deliberately — not `openedUri`.
+ //
+ // `openedUri` is whatever we ended up rendering: for a plain PDF that is the same
+ // file, but for a .docx/.pptx it is the converted temp PDF, and for an unreadable
+ // descriptor it is a timestamped mirror in app storage. Storing that broke recents
+ // three ways at once. The entry carried the original *name* ("report.docx") beside a
+ // converted *uri*, so tapping it re-queried DISPLAY_NAME off the temp file and got
+ // the converter's own name back — the "unknown.pdf" bug. `docKindOf` then read that
+ // name and routed a Word document to the plain PDF path. And because every open
+ // minted a fresh temp file with a fresh uri, `addRecent`'s dedupe never matched, so
+ // opening one file five times left five rows.
+ //
+ // The original uri is the identity of the thing the user opened. Re-opening from
+ // recents re-runs the conversion, which is correct: the converted file is a cache
+ // artifact, not the document.
RecentFilesManager.addRecent(context, RecentFile(
name = displayName,
- uriString = openedUri.toString(),
+ uriString = uri.toString(),
timestamp = System.currentTimeMillis(),
pageCount = doc.pageCount,
sizeBytes = doc.sizeBytes
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/SpreadsheetViewModel.kt b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/SpreadsheetViewModel.kt
index 5bbe405..bb871ab 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/SpreadsheetViewModel.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/SpreadsheetViewModel.kt
@@ -32,11 +32,21 @@ class SpreadsheetViewModel : ViewModel() {
val state = _state.asStateFlow()
private var started = false
+ /**
+ * Opening a spreadsheet must not be able to kill the app. Everything below runs inside
+ * `viewModelScope.launch`, where an escaping exception is uncaught and fatal — and three of the
+ * calls here talk to a `ContentProvider` the app does not own (`query`, `openInputStream`) or
+ * to shared preferences, any of which can throw on a URI whose grant has lapsed. Each step is
+ * therefore individually guarded and degrades to the on-screen error state instead.
+ */
fun load(context: Context, uri: Uri) {
if (started) return
started = true
viewModelScope.launch {
- val name = withContext(Dispatchers.IO) { queryName(context, uri) }
+ val name = withContext(Dispatchers.IO) {
+ runCatching { queryName(context, uri) }.getOrNull()
+ ?: uri.lastPathSegment ?: "Spreadsheet"
+ }
val (sheets, localUri) = withContext(Dispatchers.IO) {
// Mirror to app cache so the file stays readable when reopened from recents (a picked
// content:// URI may lose permission later), then parse from the local copy.
@@ -49,15 +59,22 @@ class SpreadsheetViewModel : ViewModel() {
UiState(fileName = name, fileUri = localUri, sheets = sheets, isLoading = false)
}
if (sheets.isNotEmpty()) withContext(Dispatchers.IO) {
- RecentFilesManager.addRecent(
- context,
- RecentFile(
- name = name,
- uriString = localUri.toString(),
- timestamp = System.currentTimeMillis(),
- pageCount = sheets.size
+ // The picked uri, not `localUri`. The mirror gets a fresh `System.currentTimeMillis()`
+ // filename on every open, so keying recents on it meant `addRecent` could never
+ // recognise a repeat and one spreadsheet accumulated a row per open. The mirror is a
+ // cache artifact; the document's identity is the uri the user chose. Re-opening from
+ // recents re-mirrors, which is what the mirror is for.
+ runCatching {
+ RecentFilesManager.addRecent(
+ context,
+ RecentFile(
+ name = name,
+ uriString = uri.toString(),
+ timestamp = System.currentTimeMillis(),
+ pageCount = sheets.size
+ )
)
- )
+ }
}
}
}
diff --git a/app/src/main/java/com/chethan616/clearpdf/utils/SpreadsheetParser.kt b/app/src/main/java/com/chethan616/clearpdf/utils/SpreadsheetParser.kt
index d5e650d..9f24e9c 100644
--- a/app/src/main/java/com/chethan616/clearpdf/utils/SpreadsheetParser.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/utils/SpreadsheetParser.kt
@@ -16,28 +16,52 @@ import java.util.zip.ZipInputStream
*/
object SpreadsheetParser {
+ /** Widest row this parser will materialise. See the note at the `"c"` end-tag. */
+ private const val MaxColumns = 1024
+
data class Sheet(val name: String, val rows: List<List<String>>) {
/** Widest row → number of columns to render. */
val columnCount: Int get() = rows.maxOfOrNull { it.size } ?: 0
}
- fun parse(context: Context, uri: Uri): List<Sheet> {
+ /**
+ * Never throws. Every failure — no such file, a revoked URI permission, a corrupt archive, a
+ * workbook too large for the heap — comes back as an empty list, which the caller renders as
+ * "Couldn't read this spreadsheet."
+ *
+ * The `runCatching` used to wrap only [parseXlsx]/[parseXls], leaving `openInputStream` and the
+ * whole-file read outside it. Those are the two calls most likely to fail (a `SecurityException`
+ * when a picked URI's grant has lapsed, an `OutOfMemoryError` on a big workbook), and because
+ * the caller invokes this from `viewModelScope.launch`, anything escaping here took the process
+ * down rather than showing the error state.
+ */
+ fun parse(context: Context, uri: Uri): List<Sheet> = runCatching {
val name = queryName(context, uri).lowercase()
- val bytes = context.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: return emptyList()
- return when {
- name.endsWith(".xls") -> runCatching { parseXls(bytes) }.getOrDefault(emptyList())
- else -> runCatching { parseXlsx(bytes) }.getOrDefault(emptyList())
+ if (name.endsWith(".xls")) {
+ // POI's HSSF reader wants the file in hand; there is no streaming path for it.
+ val bytes = context.contentResolver.openInputStream(uri)?.use { it.readBytes() }
+ if (bytes == null) emptyList() else parseXls(bytes)
+ } else {
+ context.contentResolver.openInputStream(uri)?.use { parseXlsx(it) } ?: emptyList()
}
- }
+ }.getOrDefault(emptyList())
// ── XLSX (Office Open XML) ───────────────────────────────────────────────────
- fun parseXlsx(bytes: ByteArray): List<Sheet> {
+ fun parseXlsx(bytes: ByteArray): List<Sheet> = bytes.inputStream().use { parseXlsx(it) }
+
+ fun parseXlsx(source: InputStream): List<Sheet> {
val entries = HashMap<String, ByteArray>()
- ZipInputStream(bytes.inputStream()).use { zip ->
+ ZipInputStream(source).use { zip ->
while (true) {
val entry = zip.nextEntry ?: break
- entries[entry.name] = zip.readBytes()
+ // Only the four things below are ever read again. Keeping the rest was the single
+ // biggest allocation in this parser: `xl/media/*` (embedded images, already the
+ // bulk of many workbooks) and `xl/calcChain.xml` (one node per formula cell, often
+ // larger than the sheets themselves) were being decompressed into the heap in full
+ // and never touched. Skipping them is what keeps a mid-size workbook off the OOM
+ // line, since every entry kept here stays reachable until parsing finishes.
+ if (isNeeded(entry.name)) entries[entry.name] = zip.readBytes()
}
}
val sharedStrings = entries["xl/sharedStrings.xml"]?.let { parseSharedStrings(it.inputStream()) } ?: emptyList()
@@ -150,7 +174,12 @@ object SpreadsheetParser {
"c" -> {
val raw = cellBuf.toString()
val value = if (cellType == "s") sharedStrings.getOrElse(raw.trim().toIntOrNull() ?: -1) { raw } else raw
- if (value.isNotEmpty()) rowCells[cellCol] = value
+ // The column cap is what stops one malformed `r` ref from sizing the whole
+ // sheet: the row is materialised as a dense `0..maxKey` list, so a single
+ // cell claiming to be at XFD would allocate 16384 strings for every row in
+ // the file. Excel's own classic limit is 256; past this a phone grid is not
+ // a usable way to read the data anyway.
+ if (value.isNotEmpty() && cellCol in 0 until MaxColumns) rowCells[cellCol] = value
nextAutoCol = cellCol + 1
inVal = false
}
@@ -183,6 +212,19 @@ object SpreadsheetParser {
// ── helpers ──────────────────────────────────────────────────────────────────
+ /**
+ * The zip entries this parser actually reads. Matched by suffix rather than by exact path
+ * because a few producers write the part names with a leading slash or a non-`xl/` package
+ * root, and a workbook that opens fine in Excel should not come up blank here.
+ */
+ private fun isNeeded(entryName: String): Boolean {
+ val n = entryName.removePrefix("/")
+ return n.endsWith("workbook.xml") ||
+ n.endsWith("workbook.xml.rels") ||
+ n.endsWith("sharedStrings.xml") ||
+ (n.contains("worksheets/") && n.endsWith(".xml"))
+ }
+
private fun newParser(stream: InputStream): XmlPullParser = Xml.newPullParser().apply {
setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)
setInput(stream, "UTF-8")
diff --git a/app/src/main/java/com/chethan616/clearpdf/utils/UniversalDocumentConverter.kt b/app/src/main/java/com/chethan616/clearpdf/utils/UniversalDocumentConverter.kt
index 31e6584..e8c0de6 100644
--- a/app/src/main/java/com/chethan616/clearpdf/utils/UniversalDocumentConverter.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/utils/UniversalDocumentConverter.kt
@@ -145,6 +145,11 @@ object UniversalDocumentConverter {
var headingLevel = 0
var align = Layout.Alignment.ALIGN_NORMAL
+ var justify = false
+ // w:ind / w:spacing are in twips (1/20 pt). -1 = "not specified" so a real 0 still overrides.
+ var leftIndentTwips = 0
+ var spaceBeforeTwips = -1
+ var spaceAfterTwips = -1
var bold = false
var italic = false
var underline = false
@@ -155,15 +160,31 @@ object UniversalDocumentConverter {
var spans = mutableListOf<Span>()
fun flushPara() {
- val text = paraBuf.toString().trim()
+ // trimEnd only — leading indentation and intentional spacing survive (Word carries some
+ // indent as literal runs, and trimming both ends flattened them). Real indent still comes
+ // from w:ind below.
+ val text = paraBuf.toString().trimEnd()
+ val leftIndentPt = leftIndentTwips / 20f
+ val spaceBefore = if (spaceBeforeTwips >= 0) spaceBeforeTwips / 20f else 0f
+ val spaceAfter = when {
+ spaceAfterTwips >= 0 -> spaceAfterTwips / 20f
+ headingLevel > 0 -> 10f
+ else -> 6f
+ }
if (text.isNotEmpty()) {
val ssb = SpannableStringBuilder(text)
if (headingLevel > 0) ssb.setSpan(StyleSpan(Typeface.BOLD), 0, ssb.length, 0)
spans.forEach { s -> ssb.setSpan(s.span, s.start.coerceAtMost(ssb.length), s.end.coerceAtMost(ssb.length), 0) }
- val spaceAfter = if (headingLevel > 0) 10f else 6f
- result.add(DocBlock.Para(ssb, headingLevel = headingLevel, spaceAfter = spaceAfter, alignment = align))
+ result.add(DocBlock.Para(
+ ssb, headingLevel = headingLevel, spaceAfter = spaceAfter, spaceBefore = spaceBefore,
+ alignment = align, leftIndent = leftIndentPt, justify = justify
+ ))
+ } else {
+ // Blank paragraph → a blank line, so vertical spacing between blocks is preserved.
+ result.add(DocBlock.Para(SpannableStringBuilder(""), spaceAfter = 0f))
}
paraBuf.clear(); spans.clear(); headingLevel = 0; align = Layout.Alignment.ALIGN_NORMAL
+ justify = false; leftIndentTwips = 0; spaceBeforeTwips = -1; spaceAfterTwips = -1
bold = false; italic = false; underline = false; runColor = 0; fontHalfPt = 0
}
@@ -196,11 +217,23 @@ object UniversalDocumentConverter {
else -> 0
}
}
- // Paragraph alignment (left / center / right / justify→normal).
- "w:jc" -> if (inParaProps) align = when (parser.getAttributeValue(null, "w:val")?.lowercase()) {
- "center" -> Layout.Alignment.ALIGN_CENTER
- "right", "end" -> Layout.Alignment.ALIGN_OPPOSITE
- else -> Layout.Alignment.ALIGN_NORMAL
+ // Paragraph alignment. "both"/"distribute" = justified — kept left-aligned with the
+ // justify flag so the renderer can space the words out (setJustificationMode).
+ "w:jc" -> if (inParaProps) when (parser.getAttributeValue(null, "w:val")?.lowercase()) {
+ "center" -> { align = Layout.Alignment.ALIGN_CENTER; justify = false }
+ "right", "end" -> { align = Layout.Alignment.ALIGN_OPPOSITE; justify = false }
+ "both", "distribute" -> { align = Layout.Alignment.ALIGN_NORMAL; justify = true }
+ else -> { align = Layout.Alignment.ALIGN_NORMAL; justify = false }
+ }
+ // Paragraph indent (twips). w:start is the LTR alias for w:left in newer files.
+ "w:ind" -> if (inParaProps) {
+ (parser.getAttributeValue(null, "w:left") ?: parser.getAttributeValue(null, "w:start"))
+ ?.toIntOrNull()?.let { leftIndentTwips = it.coerceAtLeast(0) }
+ }
+ // Explicit paragraph spacing before/after (twips) overrides the defaults.
+ "w:spacing" -> if (inParaProps) {
+ parser.getAttributeValue(null, "w:before")?.toIntOrNull()?.let { spaceBeforeTwips = it }
+ parser.getAttributeValue(null, "w:after")?.toIntOrNull()?.let { spaceAfterTwips = it }
}
"w:r" -> if (inPara) { inRun = true; bold = false; italic = false; underline = false; runColor = 0; fontHalfPt = 0 }
"w:rPr" -> if (inRun) inRunProps = true
@@ -599,8 +632,14 @@ object UniversalDocumentConverter {
val text: SpannableStringBuilder,
val headingLevel: Int = 0,
val spaceAfter: Float = 8f,
+ val spaceBefore: Float = 0f,
val lineSpacingMult: Float = 1.25f,
- val alignment: Layout.Alignment = Layout.Alignment.ALIGN_NORMAL
+ val alignment: Layout.Alignment = Layout.Alignment.ALIGN_NORMAL,
+ // Left indent in points (from w:ind) and whether the paragraph is justified (w:jc="both").
+ // These are what let indented / justified Word text keep its shape instead of collapsing
+ // flush-left.
+ val leftIndent: Float = 0f,
+ val justify: Boolean = false
) : DocBlock()
data class Table(val rows: List<List<String>>) : DocBlock()
data class ImageBlock(val bitmap: android.graphics.Bitmap) : DocBlock()
@@ -628,16 +667,28 @@ object UniversalDocumentConverter {
for (block in blocks) {
when (block) {
is DocBlock.Para -> {
- if (block.text.isEmpty()) { y += 8f; continue }
+ // An empty paragraph is a blank line the author put there on purpose — keep it as
+ // one line of vertical space instead of dropping it, so the document's spacing
+ // survives the conversion.
+ if (block.text.isEmpty()) { y += 13f; continue }
+ y += block.spaceBefore
val paint = if (block.headingLevel > 0) headingPaint(block.headingLevel) else defaultPaint
- val layout = StaticLayout.Builder
- .obtain(block.text, 0, block.text.length, paint, TEXT_W)
+ val indent = block.leftIndent.coerceIn(0f, TEXT_W - 40f)
+ val width = (TEXT_W - indent).toInt().coerceAtLeast(40)
+ val builder = StaticLayout.Builder
+ .obtain(block.text, 0, block.text.length, paint, width)
.setAlignment(block.alignment)
.setLineSpacing(2f, block.lineSpacingMult)
.setIncludePad(false)
- .build()
+ // Justified text (Word's "both") — only left-aligned runs can be justified.
+ if (block.justify && block.alignment == Layout.Alignment.ALIGN_NORMAL &&
+ android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O
+ ) {
+ builder.setJustificationMode(Layout.JUSTIFICATION_MODE_INTER_WORD)
+ }
+ val layout = builder.build()
ensureRoom(layout.height.toFloat())
- canvas.save(); canvas.translate(MARGIN, y); layout.draw(canvas); canvas.restore()
+ canvas.save(); canvas.translate(MARGIN + indent, y); layout.draw(canvas); canvas.restore()
y += layout.height + block.spaceAfter
}
is DocBlock.ImageBlock -> {
diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml
index 37202d2..75e35a6 100644
--- a/app/src/main/res/values-pt-rBR/strings.xml
+++ b/app/src/main/res/values-pt-rBR/strings.xml
@@ -18,6 +18,8 @@
<string name="onboarding_language_title">Escolha seu idioma</string>
<string name="onboarding_language_subtitle">Personalize sua experi&#234;ncia</string>
<string name="onboarding_language_label">Idioma</string>
+ <string name="onboarding_appearance_title">Deixe do seu jeito</string>
+ <string name="onboarding_appearance_subtitle">Escolha um tema e um plano de fundo. Mude quando quiser nas Configura&#231;&#245;es.</string>
<string name="onboarding_files_title">Abra qualquer arquivo</string>
<string name="onboarding_files_subtitle">PDFs, documentos, planilhas, apresenta&#231;&#245;es, imagens e muito mais</string>
<string name="onboarding_features_title">Ferramentas poderosas</string>
@@ -28,6 +30,9 @@
<string name="onboarding_cta_continue">Continuar</string>
<string name="onboarding_cta_get_started">Come&#231;ar</string>
<string name="onboarding_step">%1$d de %2$d</string>
+ <string name="onboarding_skip">Pular</string>
+ <string name="settings_replay_onboarding">Ver introdu&#231;&#227;o novamente</string>
+ <string name="settings_replay_onboarding_desc">Repetir o tour de boas-vindas</string>
<!-- Home Screen -->
<string name="home_title">ClearPDF</string>
@@ -292,6 +297,16 @@
<string name="viewer_page_label">P&#225;gina</string>
<string name="viewer_go">Ir</string>
<string name="viewer_ocr">OCR (%1$d)</string>
+
+ <!-- Share / export dialog -->
+ <string name="viewer_share_title">Compartilhar</string>
+ <string name="viewer_share_format">Formato</string>
+ <string name="viewer_share_encrypt">Criptografar com senha</string>
+ <string name="viewer_share_password_hint">Senha</string>
+ <string name="viewer_share_button">Compartilhar</string>
+ <string name="viewer_share_pdf">PDF</string>
+ <string name="viewer_share_normal">Normal</string>
+ <string name="viewer_share_encrypted">Criptografado</string>
<string name="tool_merge_description">Selecione dois ou mais PDFs para mesclar em um</string>
<string name="tool_split_description">Escolha um modo e execute uma a&#231;&#227;o principal clara.</string>
<string name="files_selected">%1$d arquivos selecionados</string>
diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml
index f3ef3cd..7fc6850 100644
--- a/app/src/main/res/values-pt/strings.xml
+++ b/app/src/main/res/values-pt/strings.xml
@@ -18,6 +18,8 @@
<string name="onboarding_language_title">Escolha seu idioma</string>
<string name="onboarding_language_subtitle">Personalize sua experi&#234;ncia</string>
<string name="onboarding_language_label">Idioma</string>
+ <string name="onboarding_appearance_title">Deixe do seu jeito</string>
+ <string name="onboarding_appearance_subtitle">Escolha um tema e um plano de fundo. Mude quando quiser nas Configura&#231;&#245;es.</string>
<string name="onboarding_files_title">Abra qualquer arquivo</string>
<string name="onboarding_files_subtitle">PDFs, documentos, planilhas, apresenta&#231;&#245;es, imagens e muito mais</string>
<string name="onboarding_features_title">Ferramentas poderosas</string>
@@ -28,6 +30,9 @@
<string name="onboarding_cta_continue">Continuar</string>
<string name="onboarding_cta_get_started">Come&#231;ar</string>
<string name="onboarding_step">%1$d de %2$d</string>
+ <string name="onboarding_skip">Pular</string>
+ <string name="settings_replay_onboarding">Ver introdu&#231;&#227;o novamente</string>
+ <string name="settings_replay_onboarding_desc">Repetir o tour de boas-vindas</string>
<!-- Home Screen -->
<string name="home_title">ClearPDF</string>
@@ -292,6 +297,16 @@
<string name="viewer_page_label">P&#225;gina</string>
<string name="viewer_go">Ir</string>
<string name="viewer_ocr">OCR (%1$d)</string>
+
+ <!-- Share / export dialog -->
+ <string name="viewer_share_title">Compartilhar</string>
+ <string name="viewer_share_format">Formato</string>
+ <string name="viewer_share_encrypt">Criptografar com senha</string>
+ <string name="viewer_share_password_hint">Senha</string>
+ <string name="viewer_share_button">Compartilhar</string>
+ <string name="viewer_share_pdf">PDF</string>
+ <string name="viewer_share_normal">Normal</string>
+ <string name="viewer_share_encrypted">Criptografado</string>
<string name="tool_merge_description">Selecione dois ou mais PDFs para mesclar em um</string>
<string name="tool_split_description">Escolha um modo e execute uma a&#231;&#227;o principal clara.</string>
<string name="files_selected">%1$d arquivos selecionados</string>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 417a58c..e9dfd1d 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -18,6 +18,8 @@
<string name="onboarding_language_title">Choose your language</string>
<string name="onboarding_language_subtitle">Personalize your experience</string>
<string name="onboarding_language_label">Language</string>
+ <string name="onboarding_appearance_title">Make it yours</string>
+ <string name="onboarding_appearance_subtitle">Pick a theme and a background. Change both any time in Settings.</string>
<string name="onboarding_files_title">Open anything</string>
<string name="onboarding_files_subtitle">PDFs, docs, sheets, slides, images &amp; more</string>
<string name="onboarding_features_title">Powerful tools</string>
@@ -25,6 +27,9 @@
<string name="onboarding_cta_continue">Continue</string>
<string name="onboarding_cta_get_started">Get Started</string>
<string name="onboarding_step">%1$d of %2$d</string>
+ <string name="onboarding_skip">Skip</string>
+ <string name="settings_replay_onboarding">Watch intro again</string>
+ <string name="settings_replay_onboarding_desc">Replay the welcome tour</string>
<!-- Home Screen -->
<string name="home_title">ClearPDF</string>
@@ -222,6 +227,16 @@
<string name="viewer_go">Go</string>
<string name="viewer_ocr">OCR (%1$d)</string>
+ <!-- Share / export dialog -->
+ <string name="viewer_share_title">Share</string>
+ <string name="viewer_share_format">Format</string>
+ <string name="viewer_share_encrypt">Encrypt with password</string>
+ <string name="viewer_share_password_hint">Password</string>
+ <string name="viewer_share_button">Share</string>
+ <string name="viewer_share_pdf">PDF</string>
+ <string name="viewer_share_normal">Normal</string>
+ <string name="viewer_share_encrypted">Encrypted</string>
+
<!-- Signature Pad -->
<string name="sig_draw_title">Draw your signature</string>
<string name="sig_saved">Saved</string>