Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.
Rust androiddocument-scannerdocximage-editorjetpack-composekotlinliquid-glassofflineopen-sourcepdfpdf-compressorpdf-editorpdf-mergerpdf-readerpdf-splitterpdf-toolspdf-viewerpptxspreadsheet-editorxlsx
Recents: iOS-style liquid-glass context menu that grows out of the pressed row
Chethan6162e23ea4fcb15
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.ktindex c94f720..2399615 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@@ -46,7 +46,10 @@ import androidx.compose.foundation.text.BasicTextimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.outlined.PushPinimport androidx.compose.material.icons.rounded.Apps+import androidx.compose.material.icons.rounded.DeleteForeverimport androidx.compose.material.icons.rounded.DeleteOutline+import androidx.compose.material.icons.rounded.RemoveCircleOutline+import androidx.compose.material.icons.automirrored.rounded.OpenInNewimport androidx.compose.material.icons.rounded.Descriptionimport androidx.compose.material.icons.rounded.FileOpenimport androidx.compose.material.icons.rounded.FilterList@@ -99,6 +102,7 @@ import com.chethan616.clearpdf.Rimport com.chethan616.clearpdf.data.repository.RecentFilesManagerimport com.chethan616.clearpdf.ui.components.CloseCrossIconimport com.chethan616.clearpdf.ui.components.GlassCapsuleMenu+import com.chethan616.clearpdf.ui.components.GlassMotionimport com.chethan616.clearpdf.ui.components.GlassMenuActionimport com.chethan616.clearpdf.ui.components.GlassScreenScaffoldimport com.chethan616.clearpdf.ui.components.GlassSearchHeader@@ -154,24 +158,23 @@ fun HomeScreen(// menu. Swipe-to-delete drives its own exit from inside the row; this lets the menu path run the// exact same fade + container spring instead of snapping the row out of existence.var pendingDeleteUri by remember { mutableStateOf<String?>(null) }- // Root-space vertical center of the long-pressed row, so the popup can rise- // from the item instead of floating dead-center.- var selectedRecentAnchorY by remember { mutableStateOf(0f) } // root-space TOP of the pressed row- var selectedRecentRowHeight by remember { mutableStateOf(0f) }- var recentPopupHeightPx by remember { mutableStateOf(0) }+ // Root-space bounds of the long-pressed row: the context menu grows out of it and the scrim+ // leaves a hole over it.+ var selectedRecentBounds by remember { mutableStateOf(androidx.compose.ui.geometry.Rect.Zero) }+ // The last menu target, kept after dismissal so the menu can play its exit with its content.+ var menuRecent by remember { mutableStateOf<com.chethan616.clearpdf.data.repository.RecentFile?>(null) }+ LaunchedEffect(selectedRecent) { selectedRecent?.let { menuRecent = it } }+ // Whether the pressed file itself (not only its recents entry) can be deleted. Asked of the+ // provider off the main thread each time a menu opens.+ var menuCanDelete by remember { mutableStateOf(false) }+ LaunchedEffect(selectedRecent?.uriString) {+ val r = selectedRecent ?: return@LaunchedEffect+ menuCanDelete = false+ menuCanDelete = kotlinx.coroutines.withContext(Dispatchers.IO) { canDeleteDocument(context, r.uri) }+ }var infoRecent by remember { mutableStateOf<com.chethan616.clearpdf.data.repository.RecentFile?>(null) }val lifecycleOwner = LocalLifecycleOwner.current- val popupTransition = updateTransition(- targetState = selectedRecent != null,- label = "recentPopupTransition"- )- val morphProgress by popupTransition.animateFloat(- transitionSpec = { spring(dampingRatio = 0.82f, stiffness = 220f) },- label = "morphProgress"- ) { if (it) 1f else 0f }- // `morphProgress` alone now drives the menu: GlassCapsuleMenu derives each circle's stagger- // from it, so the four per-button springs this used to run are gone.// Category filter for the recents list. Null = show everything.var recentFilter by remember { mutableStateOf<DocKind?>(null) }@@ -457,11 +460,12 @@ fun HomeScreen(// Set by the long-press menu's "Remove". When it matches this row,// the row plays the same exit as a swipe before it is dropped.pendingDelete = pendingDeleteUri == recent.uriString,+ lifted = selectedRecent?.uriString == recent.uriString,onClick = { onRecentFileSelected(recent.uri, recent.name) },- onLongClick = { top, height ->+ onLongClick = { bounds ->+ selectedRecentBounds = bounds+ menuRecent = recentselectedRecent = recent- selectedRecentAnchorY = top- selectedRecentRowHeight = height},onDelete = {// Called once the row has finished fading. Drop it from the@@ -494,100 +498,96 @@ fun HomeScreen(}}- // ── Floating Liquid Glass Chat Bubble Reaction Bar ──- AnimatedVisibility(- visible = selectedRecent != null,- enter = fadeIn(animationSpec = spring(stiffness = Spring.StiffnessHigh)),- exit = fadeOut(animationSpec = spring(stiffness = Spring.StiffnessHigh))- ) {- BoxWithConstraints(- Modifier- .fillMaxSize()- .background(Color.Transparent)- .clickable(- interactionSource = remember { androidx.compose.foundation.interaction.MutableInteractionSource() },- indication = null- ) { selectedRecent = null },- contentAlignment = Alignment.TopCenter- ) {- val maxH = constraints.maxHeight- val padPx = 16f * density- selectedRecent?.let { recent ->- // Float the pill ABOVE the pressed row (WhatsApp-style); flip below only if- // there isn't enough room above.- val gap = 10f * density- val minY = padPx * 3f- val maxY = (maxH - recentPopupHeightPx - padPx * 3f).coerceAtLeast(minY)- val aboveY = selectedRecentAnchorY - recentPopupHeightPx - gap- val belowY = selectedRecentAnchorY + selectedRecentRowHeight + gap- val targetY = (if (aboveY >= minY) aboveY else belowY).coerceIn(minY, maxY)- // One glass capsule with the actions inside it, not five glass buttons floating- // in the air — and one blur pass instead of five. The capsule fades; the- // circles inside carry the morph (see GlassCapsuleMenu).- GlassCapsuleMenu(- actions = listOf(- GlassMenuAction(- Icons.Rounded.FileOpen, stringResource(R.string.recents_open), Color(0xFF0088FF)- ) { 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),- Color(0xFFFF9500)- ) {- RecentFilesManager.togglePin(context, recent.uri)- recents = RecentFilesManager.getRecents(context)- selectedRecent = null- },- GlassMenuAction(- Icons.Rounded.IosShare, stringResource(R.string.recents_share), Color(0xFF34C759)- ) {- selectedRecent = null- val raw = recent.uri- // A file:// URI can't be shared to other apps (FileUriExposedException →- // crash). Convert to a FileProvider content:// URI first, and use the- // file's real MIME type so non-PDF recents (xlsx/images) share correctly.- val shareUri = if (raw.scheme == "file") {- runCatching {- androidx.core.content.FileProvider.getUriForFile(- context, "${context.packageName}.provider", java.io.File(raw.path!!)- )- }.getOrNull() ?: raw- } else raw- val shareIntent = Intent(Intent.ACTION_SEND).apply {- type = context.contentResolver.getType(shareUri) ?: "application/octet-stream"- putExtra(Intent.EXTRA_STREAM, shareUri)- addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)- }- runCatching {- context.startActivity(Intent.createChooser(shareIntent, context.getString(R.string.recents_share_pdf)))- }- },- GlassMenuAction(- Icons.Rounded.Info, stringResource(R.string.recents_details), Color(0xFF8E8E93)- ) { selectedRecent = null; infoRecent = recent },- GlassMenuAction(- Icons.Rounded.DeleteOutline, stringResource(R.string.recents_remove), Color(0xFFE53935)- ) {- // Hand the removal to the row so it fades out and the container springs- // shut, exactly like a swipe — no instant snap. The row calls back to- // `onDelete` when its fade completes.- selectedRecent = null- pendingDeleteUri = recent.uriString- }- ),- backdrop = backdrop,- uiSensor = uiSensor,- progress = morphProgress,- modifier = Modifier- .offset { IntOffset(0, targetY.toInt()) }- .onGloballyPositioned { recentPopupHeightPx = it.size.height }- .clickable(- interactionSource = remember { MutableInteractionSource() },- indication = null- ) { /* Consume inner taps */ }- )+ // ── Recents context menu (long-press) ──+ menuRecent?.let { recent ->+ // A file:// URI can't be handed to other apps (FileUriExposedException -> crash).+ // Convert to a FileProvider content:// URI first, and use the file's real MIME type so+ // non-PDF recents (xlsx/images) share and open correctly.+ fun exportUri(): Uri {+ val raw = recent.uri+ return if (raw.scheme == "file") {+ runCatching {+ androidx.core.content.FileProvider.getUriForFile(+ context, "${context.packageName}.provider", java.io.File(raw.path!!)+ )+ }.getOrNull() ?: raw+ } else raw+ }+ val shareFile: () -> Unit = {+ val shareUri = exportUri()+ val shareIntent = Intent(Intent.ACTION_SEND).apply {+ type = context.contentResolver.getType(shareUri) ?: "application/octet-stream"+ putExtra(Intent.EXTRA_STREAM, shareUri)+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)+ }+ runCatching {+ context.startActivity(Intent.createChooser(shareIntent, context.getString(R.string.recents_share_pdf)))+ }+ }+ val openWith: () -> Unit = {+ val viewUri = exportUri()+ val view = Intent(Intent.ACTION_VIEW).apply {+ setDataAndType(viewUri, context.contentResolver.getType(viewUri) ?: "application/octet-stream")+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)+ }+ runCatching {+ context.startActivity(Intent.createChooser(view, context.getString(R.string.recents_open_with)))}}+ RecentContextMenu(+ visible = selectedRecent != null,+ anchor = selectedRecentBounds,+ title = recent.name,+ backdrop = backdrop,+ primary = listOf(+ RecentMenuAction("open", Icons.Rounded.FileOpen, stringResource(R.string.recents_open), LiquidGlassColors.Blue) {+ selectedRecent = null; onRecentFileSelected(recent.uri, recent.name)+ },+ RecentMenuAction("share", Icons.Rounded.IosShare, stringResource(R.string.recents_share), LiquidGlassColors.Green) {+ selectedRecent = null; shareFile()+ }+ ),+ actions = buildList {+ add(RecentMenuAction(+ "pin",+ if (recent.pinned) Icons.Rounded.PushPin else Icons.Outlined.PushPin,+ stringResource(if (recent.pinned) R.string.recents_unpin else R.string.recents_pin),+ LiquidGlassColors.Orange+ ) {+ RecentFilesManager.togglePin(context, recent.uri)+ recents = RecentFilesManager.getRecents(context)+ selectedRecent = null+ })+ add(RecentMenuAction(+ "openWith", Icons.AutoMirrored.Rounded.OpenInNew, stringResource(R.string.recents_open_with), LiquidGlassColors.Indigo+ ) { selectedRecent = null; openWith() })+ add(RecentMenuAction(+ "info", Icons.Rounded.Info, stringResource(R.string.recents_details), LiquidGlassColors.Teal+ ) { selectedRecent = null; infoRecent = recent })+ add(RecentMenuAction(+ "remove", Icons.Rounded.RemoveCircleOutline, stringResource(R.string.recents_remove_from_list),+ LiquidGlassColors.Red, destructive = true+ ) {+ // Hand the removal to the row so it fades out and the container springs+ // shut, exactly like a swipe. The row calls back to `onDelete` when done.+ selectedRecent = null+ pendingDeleteUri = recent.uriString+ })+ if (menuCanDelete) add(RecentMenuAction(+ "delete", Icons.Rounded.DeleteForever, stringResource(R.string.recents_delete_file),+ LiquidGlassColors.Red, destructive = true,+ confirmLabel = stringResource(R.string.recents_delete_confirm)+ ) {+ selectedRecent = null+ homeScope.launch {+ val ok = kotlinx.coroutines.withContext(Dispatchers.IO) { deleteDocument(context, recent.uri) }+ if (ok) pendingDeleteUri = recent.uriString+ else android.widget.Toast.makeText(context, R.string.recents_delete_failed, android.widget.Toast.LENGTH_SHORT).show()+ }+ })+ },+ onDismiss = { selectedRecent = null }+ )}// ── Category filter menu ──@@ -815,6 +815,7 @@ private fun swipeRed(travel: Float, width: Float): Color {* the drag both read them at gesture time, long after they are set.*/private class RowMetrics {+ var leftX = 0fvar topY = 0fvar height = 0fvar width = 1f@@ -833,16 +834,24 @@ private fun RecentRow(secondaryColor: Color,// True once the long-press menu's "Remove" targets this row: it plays the same exit a swipe does.pendingDelete: Boolean,+ // True while this row's context menu is open: it lifts slightly above the dimmed screen.+ lifted: Boolean,onClick: () -> Unit,- onLongClick: (top: Float, height: Float) -> Unit,+ onLongClick: (bounds: androidx.compose.ui.geometry.Rect) -> Unit,onDelete: () -> Unit) {val metrics = remember { RowMetrics() }val rowInteraction = remember { MutableInteractionSource() }val rowPressed by rowInteraction.collectIsPressedAsState()+ // Held: eases down. Menu opens: springs UP past rest (the iOS context-menu "lift"), so the+ // row reads as picked up out of the list the menu grows from.val rowScale by animateFloatAsState(- if (rowPressed) 0.96f else 1f,- spring(dampingRatio = 0.5f, stiffness = Spring.StiffnessMediumLow),+ when {+ lifted -> 1.025f+ rowPressed -> 0.96f+ else -> 1f+ },+ if (lifted) GlassMotion.morph() else spring(dampingRatio = 0.5f, stiffness = Spring.StiffnessMediumLow),label = "recentPress")// Swipe-to-delete. Left only: a rightward drag has no meaning here, and allowing it would@@ -878,7 +887,9 @@ private fun RecentRow(.graphicsLayer { alpha = exitAlpha.value }.clip(RoundedCornerShape(16.dp)).onGloballyPositioned {- metrics.topY = it.localToRoot(androidx.compose.ui.geometry.Offset.Zero).y+ val pos = it.localToRoot(androidx.compose.ui.geometry.Offset.Zero)+ metrics.leftX = pos.x+ metrics.topY = pos.ymetrics.height = it.size.height.toFloat()metrics.width = it.size.width.toFloat().coerceAtLeast(1f)}@@ -939,7 +950,13 @@ private fun RecentRow(interactionSource = rowInteraction,indication = null,onClick = onClick,- onLongClick = { onLongClick(metrics.topY, metrics.height) }+ onLongClick = {+ onLongClick(+ androidx.compose.ui.geometry.Rect(+ metrics.leftX, metrics.topY, metrics.leftX + metrics.width, metrics.topY + metrics.height+ )+ )+ })// A pinned row is an explicit "keep this" — it doesn't swipe away..then(diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/RecentContextMenu.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/RecentContextMenu.ktnew file mode 100644index 0000000..2177a49--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/RecentContextMenu.kt@@ -0,0 +1,389 @@+package com.chethan616.clearpdf.ui.screen++import android.content.Context+import android.net.Uri+import android.provider.DocumentsContract+import androidx.activity.compose.BackHandler+import androidx.compose.animation.core.Animatable+import androidx.compose.animation.core.animateFloatAsState+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.interaction.MutableInteractionSource+import androidx.compose.foundation.interaction.collectIsPressedAsState+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.WindowInsets+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.navigationBars+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.statusBars+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.text.BasicText+import androidx.compose.material3.Icon+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+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.drawBehind+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.geometry.RoundRect+import androidx.compose.ui.graphics.ClipOp+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.TransformOrigin+import androidx.compose.ui.graphics.drawscope.clipPath+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.hapticfeedback.HapticFeedbackType+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.Layout+import androidx.compose.ui.layout.onPlaced+import androidx.compose.ui.layout.positionInRoot+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.platform.LocalHapticFeedback+import androidx.compose.ui.semantics.Role+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.Constraints+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.compose.ui.util.lerp+import com.chethan616.clearpdf.ui.components.GlassMotion+import com.chethan616.clearpdf.ui.components.LiquidButton+import com.chethan616.clearpdf.ui.components.viewerGlass+import com.chethan616.clearpdf.ui.theme.LiquidGlassColors+import com.chethan616.clearpdf.ui.theme.LocalIsDarkMode+import com.kyant.backdrop.Backdrop+import com.kyant.shapes.RoundedRectangle+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.launch+import kotlin.math.roundToInt++/**+ * One entry of the Recents context menu. [confirmLabel] makes it a two-step destructive action:+ * the first tap arms it (the row turns red and says [confirmLabel]), the second performs it.+ */+internal class RecentMenuAction(+ val key: String,+ val icon: ImageVector,+ val label: String,+ val tint: Color,+ val destructive: Boolean = false,+ val confirmLabel: String? = null,+ val onClick: () -> Unit+)++private val MenuWidth = 264.dp++/** How much of the entrance each successive item is delayed by, as a fraction of `progress`. */+private const val Stagger = 0.06f++/**+ * iOS-style context menu for a long-pressed Recents row.+ *+ * - A blur-free dim scrim with a rounded hole punched where the pressed row sits, so the real row+ * (which lifts itself; see RecentRow's `lifted`) stays bright above the dimmed screen.+ * - ONE glass panel. Opening scales it 0.6 -> 1 around the edge nearest the row, so it visibly+ * grows out of it; the vivid primary buttons and rows cascade in from the same shared progress+ * (no per-item springs). Closing plays it backwards.+ * - Placed below the row when it fits, above otherwise, clamped inside the status bar and the+ * floating tab bar. Dismisses on outside tap, any drag on the scrim (scroll), or back.+ */+@Composable+internal fun RecentContextMenu(+ visible: Boolean,+ anchor: Rect,+ title: String,+ backdrop: Backdrop,+ primary: List<RecentMenuAction>,+ actions: List<RecentMenuAction>,+ onDismiss: () -> Unit+) {+ val progress = remember { Animatable(0f) }+ val fade = remember { Animatable(0f) }+ LaunchedEffect(visible) {+ val target = if (visible) 1f else 0f+ coroutineScope {+ launch { fade.animateTo(target, GlassMotion.fade()) }+ progress.animateTo(target, if (visible) GlassMotion.morph() else GlassMotion.settle())+ }+ }+ BackHandler(enabled = visible, onBack = onDismiss)+ // derivedStateOf: composition only hears about the 0 crossing, not every animation frame.+ val gone by remember { androidx.compose.runtime.derivedStateOf { fade.value <= 0.001f && progress.value <= 0.001f } }+ if (!visible && gone) return++ val isDark = LocalIsDarkMode.current+ val fg = LiquidGlassColors.text(isDark)+ val sub = LiquidGlassColors.secondary(isDark)+ val glass = if (isDark) Color(0xFF1C1D22).copy(alpha = 0.74f) else Color.White.copy(alpha = 0.76f)+ val scrim = Color.Black.copy(alpha = if (isDark) 0.40f else 0.22f)+ val density = LocalDensity.current+ var origin by remember { mutableStateOf(Offset.Zero) }+ val currentDismiss by androidx.compose.runtime.rememberUpdatedState(onDismiss)+ val currentVisible by androidx.compose.runtime.rememberUpdatedState(visible)++ val topSafe = WindowInsets.statusBars.getTop(density) + with(density) { 12.dp.toPx() }+ // The floating tab bar (64 dp + margins) sits over the bottom of Home.+ val bottomSafe = WindowInsets.navigationBars.getBottom(density) + with(density) { 88.dp.toPx() }+ val marginPx = with(density) { 16.dp.toPx() }+ val gapPx = with(density) { 10.dp.toPx() }+ val liftPad = with(density) { 6.dp.toPx() }+ val holeRadius = with(density) { 18.dp.toPx() }++ Layout(+ content = {+ // Scrim. Reads `fade` in draw only; any pointer-down dismisses, so a tap OR the start of+ // a scroll both close the menu (the list underneath never sees the gesture).+ Box(+ Modifier+ .fillMaxSize()+ .drawBehind {+ val a = anchor.translate(-origin)+ val hole = Path().apply {+ addRoundRect(+ RoundRect(+ a.left - liftPad, a.top - liftPad, a.right + liftPad, a.bottom + liftPad,+ CornerRadius(holeRadius)+ )+ )+ }+ clipPath(hole, ClipOp.Difference) {+ drawRect(scrim.copy(alpha = scrim.alpha * fade.value))+ }+ }+ .pointerInputDismiss { if (currentVisible) currentDismiss() }+ )+ MenuPanel(+ title = title, fg = fg, sub = sub, glass = glass, backdrop = backdrop,+ primary = primary, actions = actions, progress = { progress.value }+ )+ },+ modifier = Modifier+ .fillMaxSize()+ .onPlaced { origin = it.positionInRoot() }+ ) { measurables, constraints ->+ val w = constraints.maxWidth+ val h = constraints.maxHeight+ val scrimP = measurables[0].measure(Constraints.fixed(w, h))+ val panelW = MenuWidth.roundToPx().coerceAtMost((w - 2 * marginPx).roundToInt().coerceAtLeast(0))+ val maxPanelH = (h - topSafe - bottomSafe).roundToInt().coerceAtLeast(0)+ val panel = measurables[1].measure(Constraints(minWidth = panelW, maxWidth = panelW, maxHeight = maxPanelH))+ layout(w, h) {+ scrimP.place(0, 0)+ val a = anchor.translate(-origin)+ val ph = panel.height.toFloat()+ val below = a.bottom + gapPx+ val above = a.top - gapPx - ph+ val placeBelow = below + ph <= h - bottomSafe || above < topSafe+ val y = (if (placeBelow) below else above)+ .coerceIn(topSafe, (h - bottomSafe - ph).coerceAtLeast(topSafe))+ // Trailing-aligned with the row, like iOS aligns the menu to the pressed cell.+ val x = (a.right - panelW).coerceIn(marginPx, (w - panelW - marginPx).coerceAtLeast(marginPx))+ val pivotX = ((a.center.x - x) / panelW).coerceIn(0f, 1f)+ val pivotY = if (placeBelow) 0f else 1f+ panel.placeWithLayer(x.roundToInt(), y.roundToInt()) {+ val p = progress.value+ val s = lerp(0.6f, 1f, p)+ scaleX = s; scaleY = s+ alpha = fade.value+ transformOrigin = TransformOrigin(pivotX, pivotY)+ }+ }+ }+}++private fun Modifier.pointerInputDismiss(onDown: () -> Unit): Modifier =+ this.pointerInput(Unit) {+ awaitEachGesture {+ val down = awaitFirstDown(requireUnconsumed = false)+ down.consume()+ onDown()+ }+ }++@Composable+private fun MenuPanel(+ title: String,+ fg: Color,+ sub: Color,+ glass: Color,+ backdrop: Backdrop,+ primary: List<RecentMenuAction>,+ actions: List<RecentMenuAction>,+ progress: () -> Float+) {+ fun local(index: Int): Float {+ val head = index * Stagger+ return ((progress() - head) / (1f - head).coerceAtLeast(0.001f)).coerceIn(0f, 1f)+ }+ Column(+ Modifier+ .width(MenuWidth)+ .viewerGlass(backdrop, glass, shape = { RoundedRectangle(24.dp) })+ // Swallow taps on the panel's padding so they don't fall through to the scrim.+ .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}+ .padding(vertical = 10.dp)+ ) {+ BasicText(+ title,+ style = TextStyle(sub, 12.sp, FontWeight.SemiBold),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier+ .padding(horizontal = 18.dp)+ .padding(bottom = 8.dp)+ .graphicsLayer { alpha = local(0) }+ )+ if (primary.isNotEmpty()) {+ Row(+ Modifier.fillMaxWidth().padding(horizontal = 10.dp),+ horizontalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ primary.forEachIndexed { i, action ->+ LiquidButton(+ onClick = action.onClick,+ backdrop = backdrop,+ tint = action.tint,+ modifier = Modifier+ .weight(1f)+ .graphicsLayer {+ val e = local(1 + i)+ alpha = e+ val s = lerp(0.85f, 1f, e)+ scaleX = s; scaleY = s+ }+ ) {+ Icon(action.icon, null, Modifier.size(18.dp), Color.White)+ BasicText(+ action.label,+ style = TextStyle(Color.White, 15.sp, FontWeight.SemiBold),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ }+ }+ }+ Spacer(Modifier.height(6.dp))+ }+ val base = 1 + primary.size+ actions.forEachIndexed { i, action ->+ if (action.destructive && i > 0) {+ Box(+ Modifier+ .padding(horizontal = 18.dp, vertical = 4.dp)+ .fillMaxWidth()+ .height(0.5.dp)+ .drawBehind { drawRect(fg.copy(alpha = 0.12f)) }+ )+ }+ MenuRow(action, fg, enter = { local(base + i) })+ }+ }+}++@Composable+private fun MenuRow(action: RecentMenuAction, fg: Color, enter: () -> Float) {+ val haptics = LocalHapticFeedback.current+ val interaction = remember { MutableInteractionSource() }+ val pressed by interaction.collectIsPressedAsState()+ var armed by remember { mutableStateOf(false) }+ val press by animateFloatAsState(if (pressed) 0.97f else 1f, GlassMotion.press(), label = "recentMenuPress")+ val wash by animateFloatAsState(+ when {+ armed -> 1f+ pressed -> 0.5f+ else -> 0f+ },+ GlassMotion.fade(), label = "recentMenuWash"+ )+ val ink = if (action.destructive) action.tint else fg+ val label = if (armed && action.confirmLabel != null) action.confirmLabel else action.label+ Row(+ Modifier+ .fillMaxWidth()+ .height(48.dp)+ .graphicsLayer {+ val e = enter()+ alpha = e+ translationY = (1f - e) * 10.dp.toPx()+ scaleX = press; scaleY = press+ }+ .padding(horizontal = 6.dp)+ .drawBehind {+ if (wash > 0f) {+ val c = if (armed || action.destructive) action.tint.copy(alpha = 0.16f * wash)+ else fg.copy(alpha = 0.08f * wash)+ drawRoundRect(c, cornerRadius = CornerRadius(14.dp.toPx()))+ }+ }+ .clickable(interactionSource = interaction, indication = null, role = Role.Button) {+ if (action.confirmLabel != null && !armed) {+ haptics.performHapticFeedback(HapticFeedbackType.LongPress)+ armed = true+ } else {+ haptics.performHapticFeedback(HapticFeedbackType.VirtualKey)+ action.onClick()+ }+ }+ .padding(horizontal = 12.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ // Per-action accent chip: the colour carries the meaning, the label carries the words.+ Box(+ Modifier+ .size(30.dp)+ .drawBehind { drawCircle(action.tint.copy(alpha = if (action.destructive) 0.18f else 0.20f)) },+ contentAlignment = Alignment.Center+ ) {+ Icon(action.icon, null, Modifier.size(17.dp), action.tint)+ }+ BasicText(+ label,+ style = TextStyle(ink, 15.sp, FontWeight.Medium),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.weight(1f)+ )+ }+}++/** True when [uri]'s provider lets us delete the underlying file (not just the recents entry). */+internal fun canDeleteDocument(context: Context, uri: Uri): Boolean = runCatching {+ when (uri.scheme) {+ "file" -> java.io.File(uri.path ?: return false).let { it.isFile && it.parentFile?.canWrite() == true }+ "content" -> {+ if (!DocumentsContract.isDocumentUri(context, uri)) return false+ context.contentResolver.query(+ uri, arrayOf(DocumentsContract.Document.COLUMN_FLAGS), null, null, null+ )?.use { c ->+ c.moveToFirst() && (c.getInt(0) and DocumentsContract.Document.FLAG_SUPPORTS_DELETE) != 0+ } ?: false+ }+ else -> false+ }+}.getOrDefault(false)++/** Deletes the file behind [uri]. Returns false (never throws) when the provider refuses. */+internal fun deleteDocument(context: Context, uri: Uri): Boolean = runCatching {+ when (uri.scheme) {+ "file" -> java.io.File(uri.path!!).delete()+ "content" -> DocumentsContract.deleteDocument(context.contentResolver, uri)+ else -> false+ }+}.getOrDefault(false)diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xmlindex d020f49..48bf88b 100644--- a/app/src/main/res/values-es/strings.xml+++ b/app/src/main/res/values-es/strings.xml@@ -346,6 +346,11 @@<string name="recents_sheets">Hojas</string><string name="recents_pin">Fijar</string><string name="recents_unpin">Dejar de fijar</string>+ <string name="recents_open_with">Abrir con…</string>+ <string name="recents_remove_from_list">Quitar de recientes</string>+ <string name="recents_delete_file">Eliminar archivo</string>+ <string name="recents_delete_confirm">Toca de nuevo para eliminar</string>+ <string name="recents_delete_failed">No se pudo eliminar el archivo</string><string name="recents_filter">Filtrar por tipo</string><string name="recents_filter_all">Todos</string><string name="recents_filter_pdf">PDF</string>diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xmlindex d66ab05..a55dea8 100644--- a/app/src/main/res/values-pt-rBR/strings.xml+++ b/app/src/main/res/values-pt-rBR/strings.xml@@ -253,6 +253,11 @@<string name="recents_sheets">Planilhas</string><string name="recents_pin">Fixar</string><string name="recents_unpin">Desafixar</string>+ <string name="recents_open_with">Abrir com…</string>+ <string name="recents_remove_from_list">Remover dos recentes</string>+ <string name="recents_delete_file">Excluir arquivo</string>+ <string name="recents_delete_confirm">Toque novamente para excluir</string>+ <string name="recents_delete_failed">Não foi possível excluir o arquivo</string><string name="recents_filter">Filtrar por tipo</string><string name="recents_filter_all">Tudo</string><string name="recents_filter_pdf">PDF</string>diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xmlindex 0f5b3a5..e941fe9 100644--- a/app/src/main/res/values-pt/strings.xml+++ b/app/src/main/res/values-pt/strings.xml@@ -253,6 +253,11 @@<string name="recents_sheets">Planilhas</string><string name="recents_pin">Fixar</string><string name="recents_unpin">Desafixar</string>+ <string name="recents_open_with">Abrir com…</string>+ <string name="recents_remove_from_list">Remover dos recentes</string>+ <string name="recents_delete_file">Eliminar ficheiro</string>+ <string name="recents_delete_confirm">Toque novamente para eliminar</string>+ <string name="recents_delete_failed">Não foi possível eliminar o ficheiro</string><string name="recents_filter">Filtrar por tipo</string><string name="recents_filter_all">Tudo</string><string name="recents_filter_pdf">PDF</string>diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex b480d5a..4b644e1 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -356,6 +356,11 @@<string name="recents_sheets">Sheets</string><string name="recents_pin">Pin</string><string name="recents_unpin">Unpin</string>+ <string name="recents_open_with">Open with…</string>+ <string name="recents_remove_from_list">Remove from Recents</string>+ <string name="recents_delete_file">Delete File</string>+ <string name="recents_delete_confirm">Tap again to delete</string>+ <string name="recents_delete_failed">Couldn\'t delete this file</string><string name="recents_filter">Filter by type</string><string name="recents_filter_all">All</string><string name="recents_filter_pdf">PDF</string>