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: annotation editing/placement overhaul + move-resize for shapes

Chethan616b8d39fd06ae2
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidSaveDialog.kt b/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidSaveDialog.kt
index 8643c17..2165374 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidSaveDialog.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidSaveDialog.kt
@@ -3,8 +3,17 @@ package com.chethan616.clearpdf.ui.components
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.core.Spring
+import androidx.compose.animation.core.spring
+import androidx.compose.animation.core.tween
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.scaleIn
+import androidx.compose.animation.scaleOut
import androidx.compose.foundation.background
import androidx.compose.foundation.border
+import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
@@ -19,10 +28,12 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
+import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
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.window.Dialog
@@ -33,6 +44,11 @@ import com.chethan616.clearpdf.ui.theme.LocalIsDarkMode
import com.chethan616.clearpdf.ui.utils.UISensor
import com.kyant.backdrop.Backdrop
+/**
+ * Solid modal presentation — used on the tool screens (they sit over the wallpaper, and a
+ * Dialog is a separate window that cannot sample the page anyway, so a clean themed card
+ * beats a wallpaper-PNG "glass" look).
+ */
@Composable
fun LiquidSaveDialog(
initialFileName: String,
@@ -40,25 +56,116 @@ fun LiquidSaveDialog(
uiSensor: UISensor,
onDismiss: () -> Unit,
onSave: (fileName: String, locationUri: Uri?) -> Unit
+) {
+ val isLight = !LocalIsDarkMode.current
+ // Same adaptive palette the in-window sheet uses, derived from the theme (tool screens
+ // sit over the wallpaper, so we can't sample a live page — a solid card matches the theme).
+ val fg = if (isLight) Color(0xFF15171C) else Color.White
+ val fgSoft = if (isLight) Color(0xFF15171C).copy(0.62f) else Color.White.copy(0.62f)
+ val field = if (isLight) Color.Black.copy(0.06f) else Color.White.copy(0.10f)
+ Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) {
+ SaveDocumentBody(
+ surface = Modifier
+ .fillMaxWidth(0.9f)
+ .widthIn(max = 440.dp)
+ .clip(RoundedCornerShape(28.dp))
+ .background(if (isLight) Color(0xFFF5F6F8) else Color(0xFF1B1E25))
+ .border(1.dp, if (isLight) Color.Black.copy(0.06f) else Color.White.copy(0.12f), RoundedCornerShape(28.dp)),
+ initialFileName = initialFileName,
+ backdrop = backdrop,
+ fg = fg,
+ fgSoft = fgSoft,
+ field = field,
+ onDismiss = onDismiss,
+ onSave = onSave
+ )
+ }
+}
+
+/**
+ * Real, in-window Liquid-Glass sheet. Rendered inside the screen (NOT a Dialog window) so the
+ * glass panel samples the actual content behind it (e.g. the live PDF page) — no PNG, no solid
+ * slab. Enters with a scrim + gentle glass "pop".
+ */
+@Composable
+fun LiquidSaveSheet(
+ visible: Boolean,
+ initialFileName: String,
+ backdrop: Backdrop,
+ uiSensor: UISensor,
+ // Adaptive chrome palette from the viewer (matches the Insert Text dialog exactly).
+ fg: Color,
+ fgSoft: Color,
+ surface: Color,
+ field: Color,
+ onDismiss: () -> Unit,
+ onSave: (fileName: String, locationUri: Uri?) -> Unit
+) {
+ Box(Modifier.fillMaxSize()) {
+ // Fade-only (like AnnotationEditorDialog) — glass never re-blurs mid-transition.
+ AnimatedVisibility(visible, enter = fadeIn(tween(200)), exit = fadeOut(tween(160)), modifier = Modifier.fillMaxSize()) {
+ Box(
+ Modifier
+ .fillMaxSize()
+ .background(Color.Black.copy(0.45f))
+ .pointerInput(Unit) { detectTapGestures { onDismiss() } }
+ )
+ }
+ AnimatedVisibility(
+ visible = visible,
+ enter = fadeIn(tween(200)),
+ exit = fadeOut(tween(140)),
+ modifier = Modifier.align(Alignment.Center).imePadding()
+ ) {
+ Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
+ SaveDocumentBody(
+ surface = Modifier
+ .fillMaxWidth(0.9f)
+ .widthIn(max = 440.dp)
+ .liquidGlassPanel(backdrop, uiSensor, surface),
+ initialFileName = initialFileName,
+ backdrop = backdrop,
+ fg = fg,
+ fgSoft = fgSoft,
+ field = field,
+ onDismiss = onDismiss,
+ onSave = onSave
+ )
+ }
+ }
+ }
+}
+
+/**
+ * Shared save UI — visually a member of the same dialog family as the Insert Text editor
+ * ([AnnotationEditorDialog]): same 18dp padding, 14dp spacing, 16sp Bold title, field boxes
+ * (heightIn 54 / radius 12 / [field] bg / 12×10 padding), and LiquidButton footer. The
+ * presentation (solid card vs glass panel) is passed in via [surface]; colours via [fg]/[fgSoft]/[field].
+ */
+@Composable
+private fun SaveDocumentBody(
+ surface: Modifier,
+ initialFileName: String,
+ backdrop: Backdrop,
+ fg: Color,
+ fgSoft: Color,
+ field: Color,
+ onDismiss: () -> Unit,
+ onSave: (fileName: String, locationUri: Uri?) -> Unit
) {
val context = LocalContext.current
- val isDarkMode = LocalIsDarkMode.current
- val isLight = !isDarkMode
- val text = if (isLight) Color(0xFF222222) else Color(0xFFF0F0F0)
- val sub = if (isLight) Color(0xFF888888) else Color(0xFFAAAAAA)
val accent = Color(0xFF1976D2)
+ // Soft violet accent for the "choose location" affordance — a contextual, important action.
+ val folderAccent = Color(0xFF7C5CFF)
var fileName by remember { mutableStateOf(initialFileName) }
var locationUri by remember { mutableStateOf(SaveLocationManager.getSaveUri(context)) }
var locationDisplay by remember { mutableStateOf(SaveLocationManager.getSavePathDisplay(context)) }
- val folderPicker = rememberLauncherForActivityResult(
- contract = ActivityResultContracts.OpenDocumentTree()
- ) { uri: Uri? ->
+ val folderPicker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri: Uri? ->
if (uri != null) {
try {
- val flags = android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION or
- android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
+ val flags = android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION or android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
context.contentResolver.takePersistableUriPermission(uri, flags)
} catch (_: Exception) {}
locationUri = uri
@@ -66,97 +173,66 @@ fun LiquidSaveDialog(
}
}
- Dialog(
- onDismissRequest = onDismiss,
- properties = DialogProperties(usePlatformDefaultWidth = false)
- ) {
- Column(
- modifier = Modifier
- .fillMaxWidth(0.9f)
- .clip(RoundedCornerShape(28.dp))
- // Solid modal card — a Dialog is a separate window and can't sample the
- // page, so a themed surface reads far cleaner than the wallpaper PNG.
- .background(if (isLight) Color(0xFFF5F6F8) else Color(0xFF1B1E25))
- .border(1.dp, if (isLight) Color.Black.copy(0.06f) else Color.White.copy(0.12f), RoundedCornerShape(28.dp))
- .padding(24.dp),
- verticalArrangement = Arrangement.spacedBy(20.dp)
- ) {
- BasicText(
- stringResource(R.string.save_document),
- style = TextStyle(color = text, fontSize = 20.sp, fontWeight = FontWeight.SemiBold)
- )
+ Column(surface.padding(18.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) {
+ BasicText(stringResource(R.string.save_document), style = TextStyle(fg, 16.sp, FontWeight.Bold))
- // File Name Input
- Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
- BasicText(stringResource(R.string.file_name), style = TextStyle(color = sub, fontSize = 13.sp, fontWeight = FontWeight.Medium))
+ // File name — same field treatment as the Insert Text dialog's text box.
+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ BasicText(stringResource(R.string.file_name), style = TextStyle(fgSoft, 12.sp, FontWeight.Medium))
+ Box(
+ Modifier
+ .fillMaxWidth()
+ .heightIn(min = 54.dp)
+ .clip(RoundedCornerShape(12.dp))
+ .background(field)
+ .padding(horizontal = 12.dp, vertical = 10.dp),
+ contentAlignment = Alignment.CenterStart
+ ) {
+ if (fileName.isEmpty()) BasicText(stringResource(R.string.document_pdf), style = TextStyle(fgSoft, 14.sp))
BasicTextField(
value = fileName,
onValueChange = { fileName = it },
- textStyle = TextStyle(color = text, fontSize = 16.sp),
+ textStyle = TextStyle(fg, 14.sp),
cursorBrush = SolidColor(accent),
- modifier = Modifier
- .fillMaxWidth()
- .clip(RoundedCornerShape(10.dp))
- .background(if (isLight) Color.Black.copy(0.04f) else Color.White.copy(0.08f))
- .padding(14.dp),
- decorationBox = { inner ->
- if (fileName.isEmpty()) {
- BasicText(stringResource(R.string.document_pdf), style = TextStyle(color = sub.copy(0.5f), fontSize = 16.sp))
- }
- inner()
- }
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth()
)
}
+ }
- // Save Location Picker
- Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
- BasicText(stringResource(R.string.settings_save_location), style = TextStyle(color = sub, fontSize = 13.sp, fontWeight = FontWeight.Medium))
- LiquidButton(
- onClick = { folderPicker.launch(null) },
- backdrop = backdrop,
- surfaceColor = if (isLight) Color.Black.copy(0.04f) else Color.White.copy(0.08f),
- modifier = Modifier.fillMaxWidth()
- ) {
- Row(
- modifier = Modifier.padding(vertical = 4.dp).fillMaxWidth(),
- horizontalArrangement = Arrangement.SpaceBetween,
- verticalAlignment = Alignment.CenterVertically
- ) {
- Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
- BasicText(locationDisplay, style = TextStyle(color = text, fontSize = 14.sp), maxLines = 1)
- }
- Spacer(Modifier.width(8.dp))
- Icon(Icons.Rounded.FolderOpen, stringResource(R.string.change_folder), Modifier.size(20.dp), accent)
+ // Save location — a stronger, violet-tinted contextual action card.
+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ BasicText(stringResource(R.string.settings_save_location), style = TextStyle(fgSoft, 12.sp, FontWeight.Medium))
+ LiquidButton(onClick = { folderPicker.launch(null) }, backdrop = backdrop, surfaceColor = folderAccent.copy(0.16f), modifier = Modifier.fillMaxWidth()) {
+ Row(Modifier.fillMaxWidth().padding(vertical = 2.dp), horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) {
+ Box(
+ Modifier.size(34.dp).clip(RoundedCornerShape(10.dp)).background(folderAccent.copy(0.22f)),
+ contentAlignment = Alignment.Center
+ ) { Icon(Icons.Rounded.FolderOpen, null, Modifier.size(18.dp), folderAccent) }
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(1.dp)) {
+ BasicText(stringResource(R.string.change_folder), style = TextStyle(fgSoft, 11.sp, FontWeight.Medium), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ BasicText(locationDisplay, style = TextStyle(fg, 14.sp, FontWeight.SemiBold), maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
}
+ }
- // Actions
- Row(
- modifier = Modifier.fillMaxWidth(),
- horizontalArrangement = Arrangement.End,
- verticalAlignment = Alignment.CenterVertically
+ // Actions — same footer as the Insert Text dialog (field Cancel + blue Save).
+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End), verticalAlignment = Alignment.CenterVertically) {
+ LiquidButton(onClick = onDismiss, backdrop = backdrop, surfaceColor = field) {
+ BasicText(stringResource(R.string.cancel), style = TextStyle(fg, 13.sp, FontWeight.Medium))
+ }
+ LiquidButton(
+ onClick = {
+ val finalName = fileName.ifBlank { "Document" }.let { if (!it.lowercase().endsWith(".pdf")) "$it.pdf" else it }
+ onSave(finalName, locationUri)
+ },
+ backdrop = backdrop,
+ tint = accent
) {
- LiquidButton(
- onClick = onDismiss,
- backdrop = backdrop,
- surfaceColor = Color.Transparent
- ) {
- BasicText(stringResource(R.string.cancel), style = TextStyle(color = sub, fontSize = 14.sp, fontWeight = FontWeight.Medium))
- }
- Spacer(Modifier.width(8.dp))
- LiquidButton(
- onClick = {
- val finalName = fileName.ifBlank { "Document" }.let { if (!it.lowercase().endsWith(".pdf")) "$it.pdf" else it }
- onSave(finalName, locationUri)
- },
- backdrop = backdrop,
- tint = accent
- ) {
- Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {
- Icon(Icons.Rounded.Save, stringResource(R.string.save), Modifier.size(16.dp), Color.White)
- BasicText(stringResource(R.string.save), style = TextStyle(color = Color.White, fontSize = 14.sp, fontWeight = FontWeight.SemiBold))
- }
+ Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {
+ Icon(Icons.Rounded.Save, null, Modifier.size(15.dp), Color.White)
+ BasicText(stringResource(R.string.save), style = TextStyle(Color.White, 13.sp, FontWeight.Bold), maxLines = 1)
}
}
}
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 d6ffb5e..297d697 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
@@ -4,6 +4,8 @@ import android.graphics.Bitmap
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.detectDragGestures
@@ -11,9 +13,17 @@ import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.waitForUpOrCancellation
import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.text.BasicText
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
@@ -23,6 +33,7 @@ import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateMap
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.geometry.Rect
import androidx.compose.ui.geometry.Size
@@ -39,7 +50,13 @@ import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onSizeChanged
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import kotlin.math.roundToInt
import com.chethan616.clearpdf.ui.viewmodel.FindMatch
import com.chethan616.clearpdf.ui.viewmodel.OcrTextBlock
import kotlin.math.max
@@ -81,7 +98,14 @@ internal fun PdfContinuousPage(
onSelectOcrRange: (Set<String>) -> Unit,
onPlaceText: (Offset) -> Unit,
onPlaceNote: (Offset) -> Unit,
- onEditAnnotation: (Long) -> Unit
+ onEditAnnotation: (Long) -> Unit,
+ onEditShape: (Int) -> Unit = {},
+ // Generic markup selection (shapes / text / notes) for move + resize.
+ selectedMarkupIndex: Int = -1,
+ onSelectMarkup: (Int) -> Unit = {},
+ onDeleteMarkup: (Int) -> Unit = {},
+ onCopySelection: () -> Unit = {},
+ onHighlightSelection: () -> Unit = {}
) {
var draftPoints by remember(page, activeTool) { mutableStateOf<List<Offset>>(emptyList()) }
var draftRectStart by remember(page, activeTool) { mutableStateOf<Offset?>(null) }
@@ -171,9 +195,20 @@ internal fun PdfContinuousPage(
)
}
if (activeTool == PdfEditTool.Image && markup.id == activeImageId) {
- drawRect(Color(0xFF1976D2), r.topLeft, r.size, style = Stroke(2f))
- drawCircle(Color(0xFF1976D2), 14f, Offset(r.right, r.bottom))
- drawCircle(Color.White, 7f, Offset(r.right, r.bottom))
+ val accent = Color(0xFF0A84FF)
+ // Rounded selection frame.
+ drawRoundRect(accent, r.topLeft, r.size, CornerRadius(10f, 10f), style = Stroke(2.5f))
+ // Passive corner dots (visual anchors).
+ listOf(r.topLeft, Offset(r.right, r.top), Offset(r.left, r.bottom)).forEach { c ->
+ drawCircle(Color.White, 8f, c)
+ drawCircle(accent, 8f, c, style = Stroke(2f))
+ }
+ // Prominent bottom-right RESIZE handle with a diagonal glyph.
+ val br = Offset(r.right, r.bottom)
+ drawCircle(Color.White, 22f, br)
+ drawCircle(accent, 22f, br, style = Stroke(3f))
+ drawLine(accent, Offset(br.x - 7f, br.y + 1f), Offset(br.x + 1f, br.y - 7f), 3f)
+ drawLine(accent, Offset(br.x - 1f, br.y + 7f), Offset(br.x + 7f, br.y - 1f), 3f)
}
}
is PdfMarkup.TextBoxMarkup -> {
@@ -200,6 +235,28 @@ internal fun PdfContinuousPage(
}
}
+ // Selection frame + handles for the selected shape / text / note.
+ if (activeTool == PdfEditTool.None) {
+ marks.getOrNull(selectedMarkupIndex)?.takeIf { it.isTransformable() }?.let { selM ->
+ selM.movableBounds()?.let { b ->
+ val accent = Color(0xFF0A84FF)
+ val fr = Rect(b.left - 6f, b.top - 6f, b.right + 6f, b.bottom + 6f)
+ drawRoundRect(accent, fr.topLeft, fr.size, CornerRadius(10f, 10f), style = Stroke(2.5f))
+ // Passive anchor dots.
+ listOf(fr.topLeft, Offset(fr.right, fr.top), Offset(fr.left, fr.bottom)).forEach { c ->
+ drawCircle(Color.White, 7f, c); drawCircle(accent, 7f, c, style = Stroke(2f))
+ }
+ // Bottom-right resize handle (hidden for fixed-size notes).
+ if (selM.isResizable()) {
+ val br = Offset(fr.right, fr.bottom)
+ drawCircle(Color.White, 20f, br); drawCircle(accent, 20f, br, style = Stroke(3f))
+ drawLine(accent, Offset(br.x - 6f, br.y + 1f), Offset(br.x + 1f, br.y - 6f), 3f)
+ drawLine(accent, Offset(br.x - 1f, br.y + 6f), Offset(br.x + 6f, br.y - 1f), 3f)
+ }
+ }
+ }
+ }
+
// In-progress drafts
if (draftPoints.size > 1) {
val isHl = activeTool == PdfEditTool.Highlight
@@ -225,16 +282,33 @@ internal fun PdfContinuousPage(
}
if (showFindBar && findMatches.isNotEmpty()) {
+ val activeMatch = findMatches.getOrNull(currentMatchIndex)
findMatches.filter { it.pageIndex == page }.forEach { match ->
- ocrBlocks.firstOrNull { it.id == match.blockId }?.let { block ->
- val r = ocrBlockToRect(block, frame)
- if (findMatches.getOrNull(currentMatchIndex) == match) {
- drawRect(Color(0xFFFF9800).copy(0.60f), r.topLeft, r.size)
- drawRect(Color(0xFFE65100), r.topLeft, r.size, style = Stroke(3.5f))
- } else {
- drawRect(Color(0xFFFFEB3B).copy(0.40f), r.topLeft, r.size)
- drawRect(Color(0xFFFBC02D), r.topLeft, r.size, style = Stroke(1.5f))
- }
+ // Highlight the exact matched WORD (normalized rect), not the whole line.
+ val r = Rect(
+ frame.left + match.left * frame.width,
+ frame.top + match.top * frame.height,
+ frame.left + match.right * frame.width,
+ frame.top + match.bottom * frame.height
+ )
+ // Hug the glyphs tightly: minimal horizontal bleed, corners scaled to the
+ // match height so the pill matches the text size (never a fixed slab).
+ val padX = 2f
+ val padY = 1.5f
+ val hl = Rect(r.left - padX, r.top - padY, r.right + padX, r.bottom + padY)
+ // Fully rounded "pill" — corner radius near half the height for a soft, modern look.
+ val cr = (hl.height * 0.42f).coerceIn(4f, 10f)
+ if (match == activeMatch) {
+ // Current result: a warm outer glow, a rich translucent fill, and a crisp
+ // accent outline so it reads clearly as the focused match.
+ val glow = hl.inflate(5f)
+ drawRoundRect(Color(0xFFFF7A00).copy(0.16f), glow.topLeft, glow.size, CornerRadius(cr + 4f, cr + 4f))
+ drawRoundRect(Color(0xFFFF9500).copy(0.42f), hl.topLeft, hl.size, CornerRadius(cr, cr))
+ drawRoundRect(Color(0xFFFF7A00), hl.topLeft, hl.size, CornerRadius(cr, cr), style = Stroke(1.75f))
+ } else {
+ // Secondary results: a single soft translucent amber pill — discoverable,
+ // low-emphasis, no harsh border.
+ drawRoundRect(Color(0xFFFFC24D).copy(0.30f), hl.topLeft, hl.size, CornerRadius(cr, cr))
}
}
}
@@ -245,30 +319,97 @@ internal fun PdfContinuousPage(
PdfEditTool.Draw, PdfEditTool.Highlight, PdfEditTool.Rect, PdfEditTool.Ellipse, PdfEditTool.Line, PdfEditTool.Arrow
)
- // Reading mode: a plain tap on a placed image/signature re-selects it (shows its
- // recolour/replace/delete controls). Only consumes the tap when it actually hits
- // an image — otherwise the tap falls through to the container (toggle chrome / zoom).
+ // Reading mode: a plain tap on a placed markup selects it. Images jump to their
+ // dedicated toolbar (replace/recolour/delete); shapes/text/notes get a selection
+ // frame with move + resize handles and a small Edit/Delete bar. A tap that misses
+ // every markup deselects and falls through to the container (chrome toggle / zoom).
if (activeTool == PdfEditTool.None) {
Box(Modifier.matchParentSize().pointerInput(page, marks.size) {
awaitEachGesture {
val down = awaitFirstDown(requireUnconsumed = false)
- val hit = marks.lastOrNull { it is PdfMarkup.ImageMarkup && it.hitTest(down.position) } as? PdfMarkup.ImageMarkup
- if (hit != null) {
+ // If a markup is already selected, let its transform layer handle touches
+ // inside its frame (don't steal them here).
+ val sel = marks.getOrNull(selectedMarkupIndex)?.takeIf { it.isTransformable() }
+ val selBounds = sel?.movableBounds()
+ if (selBounds != null && selBounds.inflate(30f).contains(down.position)) return@awaitEachGesture
+
+ val idx = marks.indexOfLast { it.hitTest(down.position) }
+ if (idx >= 0) {
+ val hit = marks[idx]
val up = waitForUpOrCancellation()
if (up != null) {
up.consume()
- onActiveImageIdChanged(hit.id)
- onActiveToolChanged(PdfEditTool.Image)
+ when (hit) {
+ is PdfMarkup.ImageMarkup -> {
+ onSelectMarkup(-1)
+ onActiveImageIdChanged(hit.id)
+ onActiveToolChanged(PdfEditTool.Image)
+ }
+ is PdfMarkup.TextBoxMarkup,
+ is PdfMarkup.NoteMarkup,
+ is PdfMarkup.RectMarkup,
+ is PdfMarkup.OvalMarkup,
+ is PdfMarkup.LineMarkup,
+ is PdfMarkup.StrokeMarkup -> onSelectMarkup(idx)
+ else -> Unit
+ }
onShowControls()
onInteraction()
}
+ } else {
+ // Missed everything → clear any selection (tap propagates to container).
+ if (selectedMarkupIndex >= 0) onSelectMarkup(-1)
}
}
})
}
+ // ── Transform layer: move + resize the selected shape / text / note ──────
+ val selForXf = marks.getOrNull(selectedMarkupIndex)?.takeIf { activeTool == PdfEditTool.None && it.isTransformable() }
+ val selXfBounds = selForXf?.movableBounds()
+ if (selForXf != null && selXfBounds != null) {
+ val density2 = LocalDensity.current
+ val pad = 30f
+ val boxL = selXfBounds.left - pad
+ val boxT = selXfBounds.top - pad
+ val boxW = selXfBounds.width + pad * 2
+ val boxH = selXfBounds.height + pad * 2
+ Box(
+ Modifier
+ .offset { IntOffset(boxL.roundToInt(), boxT.roundToInt()) }
+ .size(with(density2) { boxW.toDp() }, with(density2) { boxH.toDp() })
+ .pointerInput(page, selectedMarkupIndex) {
+ var mode = 0 // 1 = move, 2 = resize
+ detectDragGestures(
+ onDragStart = { local ->
+ val cur = marks.getOrNull(selectedMarkupIndex)
+ val bb = cur?.movableBounds()
+ // Convert the box-local touch back to page space.
+ val pPage = Offset(local.x + boxL, local.y + boxT)
+ mode = if (bb != null && cur.isResizable() && (pPage - bb.bottomRight).getDistance() <= 60f) 2 else 1
+ onInteraction()
+ },
+ onDrag = { ch, drag ->
+ if (mode == 0) return@detectDragGestures
+ ch.consume()
+ val cur = marks.getOrNull(selectedMarkupIndex) ?: return@detectDragGestures
+ val bb = cur.movableBounds() ?: return@detectDragGestures
+ marks[selectedMarkupIndex] = if (mode == 2) cur.resizedBy(drag, bb) else cur.translated(drag)
+ onInteraction()
+ },
+ onDragEnd = { mode = 0 },
+ onDragCancel = { mode = 0 }
+ )
+ }
+ )
+ }
+
if (drawingToolActive) {
- Box(Modifier.matchParentSize().pointerInput(page, activeTool) {
+ // NOTE: currentColor/currentStrokeWidth are part of the key so the gesture
+ // detector restarts and re-captures them whenever they change. Without this
+ // the onDragEnd closure keeps the color/width captured when the tool was first
+ // selected — so changing color mid-tool wouldn't apply until you switched tools.
+ Box(Modifier.matchParentSize().pointerInput(page, activeTool, currentColor, currentStrokeWidth) {
val freehand = activeTool == PdfEditTool.Draw || activeTool == PdfEditTool.Highlight
detectDragGestures(
onDragStart = { p -> onInteraction(); if (freehand) draftPoints = listOf(p) else { draftRectStart = p; draftRectEnd = p } },
@@ -319,14 +460,28 @@ internal fun PdfContinuousPage(
onDragStart = { p ->
val idx = marks.indexOfLast { it is PdfMarkup.ImageMarkup && it.id == activeImageId }
val img = marks.getOrNull(idx) as? PdfMarkup.ImageMarkup
- resizing = img != null && (p - img.end).getDistance() <= 40f; onInteraction()
+ // Generous grab radius around the bottom-right handle (Apple-style
+ // touch target much larger than the visual handle).
+ resizing = img != null && (p - img.end).getDistance() <= 64f; onInteraction()
},
onDrag = { ch, drag ->
ch.consume()
val idx = marks.indexOfLast { it is PdfMarkup.ImageMarkup && it.id == activeImageId }
val img = marks.getOrNull(idx) as? PdfMarkup.ImageMarkup ?: return@detectDragGestures
- marks[idx] = if (resizing) img.copy(end = Offset((img.end.x + drag.x).coerceAtLeast(img.start.x + 24f), (img.end.y + drag.y).coerceAtLeast(img.start.y + 24f)))
- else img.copy(start = img.start + drag, end = img.end + drag)
+ // Clamp to the page bounds so the image can never be dragged past the
+ // page edge (where it would be clipped and hidden behind the next page).
+ val pw = size.width.toFloat(); val ph = size.height.toFloat()
+ marks[idx] = if (resizing) {
+ img.copy(end = Offset(
+ (img.end.x + drag.x).coerceIn(img.start.x + 24f, pw),
+ (img.end.y + drag.y).coerceIn(img.start.y + 24f, ph)
+ ))
+ } else {
+ val iw = img.end.x - img.start.x; val ih = img.end.y - img.start.y
+ val nx = (img.start.x + drag.x).coerceIn(0f, (pw - iw).coerceAtLeast(0f))
+ val ny = (img.start.y + drag.y).coerceIn(0f, (ph - ih).coerceAtLeast(0f))
+ img.copy(start = Offset(nx, ny), end = Offset(nx + iw, ny + ih))
+ }
onInteraction()
}
)
@@ -361,5 +516,104 @@ internal fun PdfContinuousPage(
)
}
+ // ── Contextual selection bubble (Copy / Highlight), smart-positioned ──────
+ val csz = pageCanvasSizes[page]
+ if (activeTool == PdfEditTool.SelectText && selectedOcrIds.isNotEmpty() && csz != null && csz.width > 0f) {
+ val frame = Rect(0f, 0f, csz.width, csz.height)
+ val selRects = selectedOcrIds.mapNotNull { id -> ocrBlocks.firstOrNull { it.id == id }?.let { ocrBlockToRect(it, frame) } }
+ if (selRects.isNotEmpty()) {
+ val density = LocalDensity.current
+ val selLeft = selRects.minOf { it.left }
+ val selTop = selRects.minOf { it.top }
+ val selRight = selRects.maxOf { it.right }
+ val selBottom = selRects.maxOf { it.bottom }
+ val gapPx = with(density) { 8.dp.toPx() }
+ val bubbleHpx = with(density) { 44.dp.toPx() }
+ val bubbleWpx = with(density) { 150.dp.toPx() }
+ // Flip below the selection when it's too close to the page top.
+ val placeBelow = selTop < bubbleHpx + gapPx
+ val by = (if (placeBelow) selBottom + gapPx else selTop - bubbleHpx - gapPx).coerceIn(0f, (csz.height - bubbleHpx).coerceAtLeast(0f))
+ val bx = ((selLeft + selRight) / 2f - bubbleWpx / 2f).coerceIn(0f, (csz.width - bubbleWpx).coerceAtLeast(0f))
+
+ Row(
+ Modifier
+ .offset { IntOffset(bx.roundToInt(), by.roundToInt()) }
+ .clip(RoundedCornerShape(22.dp))
+ .background(Color(0xFF1C1F26).copy(0.97f))
+ .border(1.dp, Color.White.copy(0.14f), RoundedCornerShape(22.dp))
+ .padding(horizontal = 4.dp, vertical = 3.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ BasicText(
+ "Copy",
+ style = TextStyle(Color.White, 13.sp, FontWeight.SemiBold),
+ modifier = Modifier
+ .clip(RoundedCornerShape(18.dp))
+ .clickable { onCopySelection(); onClearOcrSelection() }
+ .padding(horizontal = 16.dp, vertical = 9.dp)
+ )
+ Box(Modifier.width(1.dp).height(20.dp).background(Color.White.copy(0.14f)))
+ BasicText(
+ "Highlight",
+ style = TextStyle(Color(0xFFFFCC33), 13.sp, FontWeight.SemiBold),
+ modifier = Modifier
+ .clip(RoundedCornerShape(18.dp))
+ .clickable { onHighlightSelection() }
+ .padding(horizontal = 16.dp, vertical = 9.dp)
+ )
+ }
+ }
+ }
+
+ // ── Contextual Edit / Delete bar for the selected shape / text / note ──────
+ if (activeTool == PdfEditTool.None && csz != null && csz.width > 0f) {
+ marks.getOrNull(selectedMarkupIndex)?.takeIf { it.isTransformable() }?.let { selM ->
+ selM.movableBounds()?.let { b ->
+ val density = LocalDensity.current
+ val gapPx = with(density) { 12.dp.toPx() }
+ val barHpx = with(density) { 44.dp.toPx() }
+ val barWpx = with(density) { 132.dp.toPx() }
+ val placeBelow = b.top < barHpx + gapPx
+ val by = (if (placeBelow) b.bottom + gapPx else b.top - barHpx - gapPx)
+ .coerceIn(0f, (csz.height - barHpx).coerceAtLeast(0f))
+ val bx = ((b.left + b.right) / 2f - barWpx / 2f)
+ .coerceIn(0f, (csz.width - barWpx).coerceAtLeast(0f))
+
+ Row(
+ Modifier
+ .offset { IntOffset(bx.roundToInt(), by.roundToInt()) }
+ .clip(RoundedCornerShape(22.dp))
+ .background(Color(0xFF1C1F26).copy(0.97f))
+ .border(1.dp, Color.White.copy(0.14f), RoundedCornerShape(22.dp))
+ .padding(horizontal = 4.dp, vertical = 3.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ BasicText(
+ "Edit",
+ style = TextStyle(Color.White, 13.sp, FontWeight.SemiBold),
+ modifier = Modifier
+ .clip(RoundedCornerShape(18.dp))
+ .clickable {
+ when (selM) {
+ is PdfMarkup.TextBoxMarkup -> onEditAnnotation(selM.id)
+ is PdfMarkup.NoteMarkup -> onEditAnnotation(selM.id)
+ else -> onEditShape(selectedMarkupIndex)
+ }
+ }
+ .padding(horizontal = 16.dp, vertical = 9.dp)
+ )
+ Box(Modifier.width(1.dp).height(20.dp).background(Color.White.copy(0.14f)))
+ BasicText(
+ "Delete",
+ style = TextStyle(Color(0xFFFF6B6B), 13.sp, FontWeight.SemiBold),
+ modifier = Modifier
+ .clip(RoundedCornerShape(18.dp))
+ .clickable { onDeleteMarkup(selectedMarkupIndex) }
+ .padding(horizontal = 16.dp, vertical = 9.dp)
+ )
+ }
+ }
+ }
+ }
}
}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfPageCanvas.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfPageCanvas.kt
index 85fc8b8..f6f6560 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfPageCanvas.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfPageCanvas.kt
@@ -535,22 +535,23 @@ internal fun PdfPageCanvas(
if (cs != Size.Zero && bs != Size.Zero && ocrBlocks.isNotEmpty()) {
val frame = fitBitmapRect(cs, bs.width, bs.height)
pageMatches.forEach { match ->
- val block = ocrBlocks.firstOrNull { it.id == match.blockId }
- if (block != null) {
- val r = Rect(
- frame.left + block.left * frame.width,
- frame.top + block.top * frame.height,
- frame.left + block.right * frame.width,
- frame.top + block.bottom * frame.height
- )
- val isCurrent = (findMatches.getOrNull(currentMatchIndex) == match)
- if (isCurrent) {
- drawRect(Color(0xFFFF9800).copy(0.60f), r.topLeft, r.size)
- drawRect(Color(0xFFE65100), r.topLeft, r.size, style = Stroke(3.5f))
- } else {
- drawRect(Color(0xFFFFEB3B).copy(0.40f), r.topLeft, r.size)
- drawRect(Color(0xFFFBC02D), r.topLeft, r.size, style = Stroke(1.5f))
- }
+ val r = Rect(
+ frame.left + match.left * frame.width,
+ frame.top + match.top * frame.height,
+ frame.left + match.right * frame.width,
+ frame.top + match.bottom * frame.height
+ )
+ val isCurrent = (findMatches.getOrNull(currentMatchIndex) == match)
+ val hl = Rect(r.left - 1.5f, r.top - 1f, r.right + 1.5f, r.bottom + 1f)
+ val cr = (hl.height * 0.28f).coerceIn(3f, 7f)
+ if (isCurrent) {
+ val glow = hl.inflate(4f)
+ drawRoundRect(Color(0xFFFF6D00).copy(0.22f), glow.topLeft, glow.size, CornerRadius(cr + 3f, cr + 3f))
+ drawRoundRect(Color(0xFFFFA726).copy(0.55f), hl.topLeft, hl.size, CornerRadius(cr, cr))
+ drawRoundRect(Color(0xFFE65100), hl.topLeft, hl.size, CornerRadius(cr, cr), style = Stroke(1.75f))
+ } else {
+ drawRoundRect(Color(0xFFFFC107).copy(0.26f), hl.topLeft, hl.size, CornerRadius(cr, cr))
+ drawRoundRect(Color(0xFFFFA000).copy(0.5f), hl.topLeft, hl.size, CornerRadius(cr, cr), style = Stroke(1f))
}
}
}
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 c9b4686..d4867b8 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
@@ -10,6 +10,7 @@ import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
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.layout.Arrangement
import androidx.compose.foundation.layout.Box
@@ -19,9 +20,11 @@ import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.imePadding
+import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
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.text.BasicText
import androidx.compose.foundation.text.BasicTextField
@@ -173,6 +176,7 @@ internal fun LiquidPageJumpPopup(
internal fun AnnotationEditorDialog(
isNote: Boolean,
initialText: String,
+ initialColor: Color,
backdrop: LayerBackdrop,
uiSensor: UISensor,
fg: Color,
@@ -181,9 +185,10 @@ internal fun AnnotationEditorDialog(
field: Color,
onDismiss: () -> Unit,
onDelete: () -> Unit,
- onSave: (String) -> Unit
+ onSave: (String, Color) -> Unit
) {
var text by remember { mutableStateOf(initialText) }
+ var color by remember { mutableStateOf(initialColor) }
val focus = remember { FocusRequester() }
var shown by remember { mutableStateOf(false) }
LaunchedEffect(Unit) { shown = true; delay(160); runCatching { focus.requestFocus() } }
@@ -246,6 +251,9 @@ internal fun AnnotationEditorDialog(
)
}
+ // Colour picker — recolour the text / sticky note.
+ AnnotationColorRow(selected = color, fgSoft = fgSoft, onPick = { color = it })
+
Row(
Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End),
@@ -257,7 +265,7 @@ internal fun AnnotationEditorDialog(
LiquidButton(onClick = onDismiss, backdrop = backdrop, surfaceColor = field) {
BasicText(stringResource(R.string.cancel), style = TextStyle(fg, 13.sp))
}
- LiquidButton(onClick = { onSave(text) }, backdrop = backdrop, tint = Color(0xFF1976D2)) {
+ LiquidButton(onClick = { onSave(text, color) }, backdrop = backdrop, tint = Color(0xFF1976D2)) {
BasicText(stringResource(R.string.anno_save), style = TextStyle(Color.White, 13.sp, FontWeight.Bold))
}
}
@@ -266,3 +274,122 @@ internal fun AnnotationEditorDialog(
}
}
}
+
+// 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(
+ Color(0xFF1A1A1A), // near-black ink
+ Color(0xFF1976D2), // blue
+ Color(0xFFE53935), // red
+ Color(0xFF43A047), // green
+ Color(0xFFFB8C00), // orange
+ Color(0xFF8E24AA), // purple
+ Color(0xFF00ACC1), // teal
+ Color(0xFFFFC107) // amber (notes)
+)
+
+/** A horizontal row of tappable colour beads; the selected one gets a ring. */
+@Composable
+internal fun AnnotationColorRow(
+ selected: Color,
+ fgSoft: Color,
+ onPick: (Color) -> Unit
+) {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ BasicText(stringResource(R.string.viewer_color), style = TextStyle(fgSoft, 12.sp, FontWeight.Medium))
+ Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) {
+ editorPalette.forEach { c ->
+ val isSel = c.value == selected.value
+ Box(
+ Modifier
+ .size(if (isSel) 30.dp else 26.dp)
+ .clip(CircleShape)
+ .background(c)
+ .border(
+ width = if (isSel) 2.5.dp else 1.dp,
+ color = if (isSel) Color.White else Color.White.copy(0.25f),
+ shape = CircleShape
+ )
+ .clickable { onPick(c) }
+ )
+ }
+ }
+ }
+}
+
+/**
+ * Contextual editor for a placed shape (rect / oval / line / arrow / stroke). Rendered
+ * IN-WINDOW so its glass panel samples the real page. Recolours live as the user taps a
+ * bead, and offers Delete / Done. Same visual family as [AnnotationEditorDialog].
+ */
+@Composable
+internal fun ShapeEditorPopup(
+ initialColor: Color,
+ backdrop: LayerBackdrop,
+ uiSensor: UISensor,
+ fg: Color,
+ fgSoft: Color,
+ surface: Color,
+ field: Color,
+ onColorChange: (Color) -> Unit,
+ onDelete: () -> Unit,
+ onDismiss: () -> Unit
+) {
+ var color by remember { mutableStateOf(initialColor) }
+ var shown by remember { mutableStateOf(false) }
+ LaunchedEffect(Unit) { shown = true }
+
+ Box(Modifier.fillMaxSize()) {
+ AnimatedVisibility(
+ visible = shown,
+ enter = fadeIn(tween(180)),
+ exit = fadeOut(tween(140)),
+ modifier = Modifier.fillMaxSize()
+ ) {
+ Box(
+ Modifier
+ .fillMaxSize()
+ .background(Color.Black.copy(0.45f))
+ .pointerInput(Unit) { detectTapGestures { onDismiss() } }
+ )
+ }
+
+ AnimatedVisibility(
+ visible = shown,
+ enter = fadeIn(tween(200)),
+ exit = fadeOut(tween(140)),
+ modifier = Modifier.align(Alignment.Center).fillMaxWidth().imePadding()
+ ) {
+ Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
+ Column(
+ Modifier
+ .fillMaxWidth(0.9f)
+ .widthIn(max = 440.dp)
+ .liquidGlassPanel(backdrop, uiSensor, surface)
+ .padding(18.dp),
+ verticalArrangement = Arrangement.spacedBy(16.dp)
+ ) {
+ BasicText(
+ stringResource(R.string.viewer_edit_shape),
+ style = TextStyle(fg, 16.sp, fontWeight = FontWeight.Bold)
+ )
+
+ AnnotationColorRow(selected = color, fgSoft = fgSoft, onPick = { color = it; onColorChange(it) })
+
+ Row(
+ Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ LiquidButton(onClick = onDelete, backdrop = backdrop, surfaceColor = Color(0xFFEF5350).copy(0.22f)) {
+ BasicText(stringResource(R.string.delete), style = TextStyle(Color.White, 13.sp))
+ }
+ LiquidButton(onClick = onDismiss, backdrop = backdrop, tint = Color(0xFF1976D2)) {
+ BasicText(stringResource(R.string.viewer_done), style = TextStyle(Color.White, 13.sp, FontWeight.Bold))
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerInternals.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerInternals.kt
index 000608a..543d3a6 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerInternals.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerInternals.kt
@@ -137,6 +137,99 @@ internal sealed class PdfMarkup {
}
}
+/** Recolourable free-form shapes (as opposed to images / OCR-anchored / text markups). */
+internal fun PdfMarkup.isShape(): Boolean = this is PdfMarkup.StrokeMarkup ||
+ this is PdfMarkup.RectMarkup || this is PdfMarkup.OvalMarkup || this is PdfMarkup.LineMarkup
+
+/** Markups that support the generic select → move / resize transform (everything the user
+ * places freely, except images which have their own dedicated toolbar path). */
+internal fun PdfMarkup.isTransformable(): Boolean = this is PdfMarkup.StrokeMarkup ||
+ this is PdfMarkup.RectMarkup || this is PdfMarkup.OvalMarkup || this is PdfMarkup.LineMarkup ||
+ this is PdfMarkup.TextBoxMarkup || this is PdfMarkup.NoteMarkup
+
+/** Whether a bottom-right resize handle applies (notes are a fixed-size icon → move only). */
+internal fun PdfMarkup.isResizable(): Boolean = isTransformable() && this !is PdfMarkup.NoteMarkup
+
+/** Content-space bounding box used for the selection frame + hit-testing during transform. */
+internal fun PdfMarkup.movableBounds(): Rect? = when (this) {
+ is PdfMarkup.StrokeMarkup -> {
+ if (points.isEmpty()) null else {
+ var l = points[0].x; var t = points[0].y; var r = l; var b = t
+ points.forEach { l = min(l, it.x); t = min(t, it.y); r = max(r, it.x); b = max(b, it.y) }
+ Rect(l, t, max(r, l + 1f), max(b, t + 1f))
+ }
+ }
+ is PdfMarkup.RectMarkup -> Rect(min(start.x, end.x), min(start.y, end.y), max(start.x, end.x), max(start.y, end.y))
+ is PdfMarkup.OvalMarkup -> Rect(min(start.x, end.x), min(start.y, end.y), max(start.x, end.x), max(start.y, end.y))
+ is PdfMarkup.LineMarkup -> Rect(min(start.x, end.x), min(start.y, end.y), max(start.x, end.x) + 1f, max(start.y, end.y) + 1f)
+ is PdfMarkup.ImageMarkup -> Rect(min(start.x, end.x), min(start.y, end.y), max(start.x, end.x), max(start.y, end.y))
+ is PdfMarkup.TextBoxMarkup -> {
+ val lines = if (text.isEmpty()) 1 else text.split("\n").size
+ val w = ((text.split("\n").maxOfOrNull { it.length } ?: 1).coerceAtLeast(3)) * fontSize * 0.6f
+ Rect(position.x, position.y, position.x + w, position.y + fontSize * 1.2f * lines)
+ }
+ is PdfMarkup.NoteMarkup -> Rect(anchor.x, anchor.y, anchor.x + 30f, anchor.y + 30f)
+ else -> null
+}
+
+/** Translate a markup by [d] (move). */
+internal fun PdfMarkup.translated(d: Offset): PdfMarkup = when (this) {
+ is PdfMarkup.StrokeMarkup -> copy(points = points.map { it + d })
+ is PdfMarkup.RectMarkup -> copy(start = start + d, end = end + d)
+ is PdfMarkup.OvalMarkup -> copy(start = start + d, end = end + d)
+ is PdfMarkup.LineMarkup -> copy(start = start + d, end = end + d)
+ is PdfMarkup.ImageMarkup -> copy(start = start + d, end = end + d)
+ is PdfMarkup.TextBoxMarkup -> copy(position = position + d)
+ is PdfMarkup.NoteMarkup -> copy(anchor = anchor + d)
+ else -> this
+}
+
+/** Resize a markup by dragging its bottom-right handle [drag], given its current [bounds]. */
+internal fun PdfMarkup.resizedBy(drag: Offset, bounds: Rect): PdfMarkup = when (this) {
+ is PdfMarkup.RectMarkup -> copy(
+ start = bounds.topLeft,
+ end = Offset((bounds.right + drag.x).coerceAtLeast(bounds.left + 8f), (bounds.bottom + drag.y).coerceAtLeast(bounds.top + 8f))
+ )
+ is PdfMarkup.OvalMarkup -> copy(
+ start = bounds.topLeft,
+ end = Offset((bounds.right + drag.x).coerceAtLeast(bounds.left + 8f), (bounds.bottom + drag.y).coerceAtLeast(bounds.top + 8f))
+ )
+ is PdfMarkup.LineMarkup -> {
+ // Move whichever endpoint sits nearer the bottom-right handle.
+ val br = bounds.bottomRight
+ if ((end - br).getDistance() <= (start - br).getDistance()) copy(end = end + drag) else copy(start = start + drag)
+ }
+ is PdfMarkup.StrokeMarkup -> {
+ // Uniform scale about the top-left so the stroke keeps its shape.
+ val pivot = bounds.topLeft
+ val fx = ((bounds.width + drag.x) / bounds.width.coerceAtLeast(1f)).coerceIn(0.2f, 8f)
+ val fy = ((bounds.height + drag.y) / bounds.height.coerceAtLeast(1f)).coerceIn(0.2f, 8f)
+ val f = (fx + fy) / 2f
+ copy(points = points.map { pivot + (it - pivot) * f })
+ }
+ is PdfMarkup.TextBoxMarkup -> {
+ val factor = ((bounds.height + drag.y) / bounds.height.coerceAtLeast(1f)).coerceIn(0.3f, 6f)
+ copy(fontSize = (fontSize * factor).coerceIn(10f, 400f))
+ }
+ else -> this
+}
+
+internal fun PdfMarkup.shapeColor(): Color = when (this) {
+ is PdfMarkup.StrokeMarkup -> color
+ is PdfMarkup.RectMarkup -> color
+ is PdfMarkup.OvalMarkup -> color
+ is PdfMarkup.LineMarkup -> color
+ else -> Color(0xFF1976D2)
+}
+
+internal fun PdfMarkup.recolored(c: Color): PdfMarkup = when (this) {
+ is PdfMarkup.StrokeMarkup -> copy(color = c)
+ is PdfMarkup.RectMarkup -> copy(color = c)
+ is PdfMarkup.OvalMarkup -> copy(color = c)
+ is PdfMarkup.LineMarkup -> copy(color = c)
+ else -> this
+}
+
// ── Geometry helpers ──────────────────────────────────────────────────────────
internal fun fitBitmapRect(canvasSize: Size, bitmapW: Float, bitmapH: Float): Rect {
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 86c5713..c1f3410 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
@@ -111,7 +111,7 @@ import com.chethan616.clearpdf.ui.components.LiquidButton
import com.chethan616.clearpdf.ui.components.LiquidGlassTopBar
import com.chethan616.clearpdf.ui.components.LiquidIconButton
import com.chethan616.clearpdf.ui.components.ViewerChromeGlass
-import com.chethan616.clearpdf.ui.components.LiquidSaveDialog
+import com.chethan616.clearpdf.ui.components.LiquidSaveSheet
import com.chethan616.clearpdf.ui.components.liquidGlassPanel
import com.chethan616.clearpdf.ui.theme.LocalIsDarkMode
import com.chethan616.clearpdf.ui.utils.rememberUISensor
@@ -170,6 +170,14 @@ fun PdfViewerScreen(
var editingAnnoPage by remember { mutableStateOf(0) }
var editingAnnoIsNote by remember { mutableStateOf(false) }
var annotationDraft by remember { mutableStateOf("") }
+ var editingAnnoColor by remember { mutableStateOf(Color(0xFF1976D2)) }
+ // Shape (rect / oval / line / arrow / stroke) editing — identified by page + list index.
+ var editingShapePage by remember { mutableStateOf<Int?>(null) }
+ var editingShapeIndex by remember { mutableStateOf(-1) }
+ // Generic markup selection (move + resize of shapes / text / notes).
+ var selectedAnnoPage by remember { mutableStateOf<Int?>(null) }
+ var selectedAnnoIndex by remember { mutableStateOf(-1) }
+ val density = LocalDensity.current
// ── Zoom / pan state ───────────────────────────────────────────────────
// Ported from Pdf_Tools (Karna14314): document-level zoom/pan is plain float
@@ -192,6 +200,64 @@ fun PdfViewerScreen(
fun getPageMarks(page: Int): MutableList<PdfMarkup> =
annotationsByPage.getOrPut(page) { mutableStateListOf() }
+ // 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()
+
+ // The page + on-screen position where a newly placed image/signature should land: the
+ // page occupying the vertical centre of the viewport, at the point the user is looking
+ // at (so a sign never silently lands off-screen on page 1). Returns a null offset when
+ // the page isn't measured yet → callers fall back to that page's frame centre.
+ fun viewportPlacementTarget(): Pair<Int, Offset?> {
+ val info = listState.layoutInfo
+ val visible = info.visibleItemsInfo
+ if (visible.isEmpty()) return state.currentPage to null
+ val centerY = (info.viewportStartOffset + info.viewportEndOffset) / 2
+ val item = visible.firstOrNull { centerY >= it.offset && centerY < it.offset + it.size }
+ ?: visible.minByOrNull { kotlin.math.abs((it.offset + it.size / 2) - centerY) }!!
+ val page = item.index
+ val cs = pageCanvasSizes[page] ?: return page to null
+ if (cs.width < 50f || cs.height < 50f) return page to null
+ val topPadPx = with(density) { 6.dp.toPx() }
+ val localY = (centerY - item.offset - topPadPx).coerceIn(0f, cs.height)
+ val bs = pageBitmapSizes[page] ?: cs
+ val frame = fitBitmapRect(cs, bs.width, bs.height)
+ return page to Offset(frame.center.x, localY)
+ }
+
+ // 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) {
+ val (page, target) = viewportPlacementTarget()
+ val marks = getPageMarks(page)
+ val rawCs = pageCanvasSizes[page]
+ val cs = if (rawCs != null && rawCs.width > 50f && rawCs.height > 50f) rawCs else Size(1000f, 1400f)
+ val bs = pageBitmapSizes[page] ?: cs
+ val frame = fitBitmapRect(cs, bs.width, bs.height)
+ val maxW = (if (frame.width > 50f) frame.width else cs.width) * (if (isSignature) 0.45f else 0.5f)
+ val ratio = bmp.height.toFloat() / bmp.width.toFloat().coerceAtLeast(1f)
+ val w = maxW.coerceAtLeast(100f)
+ val h = w * ratio
+ val fallbackCenter = if (frame.width > 50f) frame.center else Offset(cs.width / 2f, cs.height / 2f)
+ val center = target ?: fallbackCenter
+ val cx = center.x.coerceIn(w / 2f, (cs.width - w / 2f).coerceAtLeast(w / 2f))
+ 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))
+ activeImageId = id; activeTool = PdfEditTool.Image; controlsVisible = true
+ }
+
+ // Locate the currently selected image across ALL pages (it may live on a page other
+ // than firstVisibleItemIndex, since placement targets the viewport-centre page).
+ fun activeImageLoc(): Triple<Int, Int, PdfMarkup.ImageMarkup>? {
+ val id = activeImageId ?: return null
+ annotationsByPage.forEach { (pg, m) ->
+ val i = m.indexOfLast { it is PdfMarkup.ImageMarkup && it.id == id }
+ if (i >= 0) return Triple(pg, i, m[i] as PdfMarkup.ImageMarkup)
+ }
+ return null
+ }
+
// ── Launchers ─────────────────────────────────────────────────────────
val pdfPickerLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
uri?.let { viewModel.openPdf(context, it) }
@@ -204,25 +270,18 @@ fun PdfViewerScreen(
android.graphics.BitmapFactory.decodeStream(it)
}
}.getOrNull() ?: return@rememberLauncherForActivityResult
- val page = state.currentPage
- val marks = getPageMarks(page)
- val existingIdx = marks.indexOfLast { it is PdfMarkup.ImageMarkup && it.id == activeImageId }
- if (existingIdx >= 0) {
+ // If an image is currently selected, replace its bitmap in place; otherwise place a
+ // new one on the page under the viewport (never silently on page 1).
+ val existingPage = annotationsByPage.entries.firstOrNull { (_, m) -> m.any { it is PdfMarkup.ImageMarkup && it.id == activeImageId } }?.key
+ val existingIdx = existingPage?.let { getPageMarks(it).indexOfLast { m -> m is PdfMarkup.ImageMarkup && m.id == activeImageId } } ?: -1
+ if (existingPage != null && existingIdx >= 0) {
+ val marks = getPageMarks(existingPage)
val existing = marks[existingIdx] as PdfMarkup.ImageMarkup
val ratio = bmp.height.toFloat() / bmp.width.toFloat().coerceAtLeast(1f)
val currentW = kotlin.math.abs(existing.end.x - existing.start.x).coerceAtLeast(20f)
marks[existingIdx] = existing.copy(bitmap = bmp, end = Offset(existing.end.x, existing.start.y + currentW * ratio), isSignature = false)
} else {
- val cs = pageCanvasSizes[page] ?: Size(bmp.width.toFloat(), bmp.height.toFloat())
- val frame = fitBitmapRect(cs, (pageBitmapSizes[page]?.width ?: cs.width), (pageBitmapSizes[page]?.height ?: cs.height))
- val maxW = (if (frame.width > 0f) frame.width else cs.width) * 0.5f
- val ratio = bmp.height.toFloat() / bmp.width.toFloat().coerceAtLeast(1f)
- val w = maxW.coerceAtLeast(1f)
- val center = if (frame.width > 0f) frame.center else Offset(cs.width / 2f, cs.height / 2f)
- val id = System.nanoTime()
- marks.add(PdfMarkup.ImageMarkup(id, bmp, Offset(center.x - w / 2f, center.y - w * ratio / 2f), Offset(center.x + w / 2f, center.y + w * ratio / 2f), false))
- activeImageId = id
- activeTool = PdfEditTool.Image
+ placeImageMarkup(bmp, isSignature = false)
}
}
@@ -242,6 +301,7 @@ fun PdfViewerScreen(
lastInteractionAtMs = System.currentTimeMillis()
scale = 1f; offsetX = 0f
activeTool = PdfEditTool.None
+ selectedAnnoPage = null; selectedAnnoIndex = -1
annotationsByPage.clear(); pageCanvasSizes.clear(); pageBitmapSizes.clear()
viewModel.clearOcrSelection(state.currentPage); viewModel.clearExportFeedback()
showFindBar = false; findQuery = ""; viewModel.clearSearch()
@@ -250,7 +310,9 @@ fun PdfViewerScreen(
LaunchedEffect(state.document, controlsVisible, controlsPinned, activeTool, lastInteractionAtMs) {
if (state.document != null && controlsVisible && !controlsPinned && scale <= 1.01f && activeTool == PdfEditTool.None) {
val snap = lastInteractionAtMs
- delay(3500)
+ // Comfortable auto-hide window; any interaction bumps lastInteractionAtMs and
+ // restarts this, and it never fires while a tool is active (activeTool != None).
+ delay(5000)
if (controlsVisible && !controlsPinned && scale <= 1.01f && activeTool == PdfEditTool.None && snap == lastInteractionAtMs)
controlsVisible = false
}
@@ -271,8 +333,8 @@ fun PdfViewerScreen(
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
- LiquidButton(onClick = onBack, backdrop = backdrop, surfaceColor = Color.White.copy(0.08f)) {
- Icon(Icons.Rounded.ArrowBackIosNew, stringResource(R.string.back), Modifier.size(18.dp), text)
+ LiquidIconButton(onClick = onBack, backdrop = backdrop, surfaceColor = Color.White.copy(0.08f)) {
+ Icon(Icons.Rounded.ArrowBackIosNew, stringResource(R.string.back), Modifier.size(16.dp), text)
}
LiquidGlassTopBar(stringResource(R.string.viewer_title), backdrop, uiSensor, Modifier.weight(1f))
}
@@ -340,7 +402,6 @@ fun PdfViewerScreen(
// ── PDF viewer (continuous vertical scroll, Adobe-style) ─────────────────
val safePageCount = state.pageCount.coerceAtLeast(1)
- val listState = rememberLazyListState()
val viewerScope = rememberCoroutineScope()
val currentPageIndex = listState.firstVisibleItemIndex.coerceIn(0, safePageCount - 1)
@@ -560,7 +621,37 @@ fun PdfViewerScreen(
is PdfMarkup.NoteMarkup -> m.text
else -> ""
}
+ editingAnnoColor = when (m) {
+ is PdfMarkup.TextBoxMarkup -> m.color
+ is PdfMarkup.NoteMarkup -> m.color
+ else -> Color(0xFF1976D2)
+ }
controlsVisible = true
+ },
+ onEditShape = { idx ->
+ editingShapePage = page; editingShapeIndex = idx; controlsVisible = true
+ },
+ selectedMarkupIndex = if (page == selectedAnnoPage) selectedAnnoIndex else -1,
+ onSelectMarkup = { idx ->
+ if (idx < 0) { selectedAnnoPage = null; selectedAnnoIndex = -1 }
+ else { selectedAnnoPage = page; selectedAnnoIndex = idx }
+ },
+ onDeleteMarkup = { idx ->
+ val m = getPageMarks(page); if (idx in m.indices) m.removeAt(idx)
+ selectedAnnoPage = null; selectedAnnoIndex = -1
+ },
+ onCopySelection = {
+ viewModel.getSelectedOcrText(page).takeIf { it.isNotBlank() }
+ ?.let { clipboard.setText(AnnotatedString(it)) }
+ lastInteractionAtMs = System.currentTimeMillis()
+ },
+ onHighlightSelection = {
+ val m = getPageMarks(page)
+ state.selectedOcrBlockIdsByPage[page].orEmpty().forEach { id ->
+ if (!m.any { it is PdfMarkup.TextBlockHighlightMarkup && it.blockId == id })
+ m.add(PdfMarkup.TextBlockHighlightMarkup(id, Color(currentColorLong), 0.30f))
+ }
+ viewModel.clearOcrSelection(page)
}
)
}
@@ -644,8 +735,7 @@ fun PdfViewerScreen(
exit = fadeOut(tween(150)) + slideOutVertically { it / 2 },
modifier = Modifier.align(Alignment.BottomCenter)
) {
- val activeItem = getPageMarks(state.currentPage)
- .firstOrNull { it is PdfMarkup.ImageMarkup && it.id == activeImageId } as? PdfMarkup.ImageMarkup
+ val activeItem = activeImageLoc()?.third
PdfViewerBottomToolbar(
activeTool = activeTool,
@@ -666,14 +756,14 @@ fun PdfViewerScreen(
currentSelectedIds = state.selectedOcrBlockIdsByPage[state.currentPage].orEmpty(),
activeIsSignature = activeItem?.isSignature == true,
currentPageMarks = getPageMarks(state.currentPage),
- onSetActiveTool = { activeTool = it; if (it == PdfEditTool.None) activeImageId = null; viewModel.clearOcrSelection(state.currentPage) },
+ onSetActiveTool = { activeTool = it; if (it == PdfEditTool.None) activeImageId = null; selectedAnnoPage = null; selectedAnnoIndex = -1; viewModel.clearOcrSelection(state.currentPage) },
onToggleFindBar = {
showFindBar = !showFindBar
if (showFindBar) viewModel.triggerOcrForAllPages(context)
else { focusManager.clearFocus(); viewModel.clearSearch(); findQuery = "" }
},
onShowSignaturePad = { showSignaturePad = true },
- onPickImage = { imagePickerLauncher.launch("image/*") },
+ onPickImage = { activeImageId = null; imagePickerLauncher.launch("image/*") },
onResetZoom = { scope.launch { animateZoomPan(1f, Offset.Zero) }
lastInteractionAtMs = System.currentTimeMillis() },
onShowSaveDialog = { showSaveDialog = true },
@@ -683,9 +773,7 @@ fun PdfViewerScreen(
else imagePickerLauncher.launch("image/*")
},
onDeleteImage = {
- val m = getPageMarks(state.currentPage)
- val idx = m.indexOfLast { it is PdfMarkup.ImageMarkup && it.id == activeImageId }
- if (idx >= 0) m.removeAt(idx)
+ activeImageLoc()?.let { (pg, idx, _) -> getPageMarks(pg).removeAt(idx) }
activeImageId = null; activeTool = PdfEditTool.None
},
onSelectAllText = {
@@ -724,10 +812,9 @@ fun PdfViewerScreen(
onOpenExportedFile = { state.lastExportedUri?.let { viewModel.openPdf(context, it) } },
onOpenAnotherPdf = { pdfPickerLauncher.launch(arrayOf("*/*")) },
onRecolorSignature = { cl ->
- val m = getPageMarks(state.currentPage)
- val idx = m.indexOfLast { it is PdfMarkup.ImageMarkup && it.id == activeImageId && it.isSignature }
- val sig = m.getOrNull(idx) as? PdfMarkup.ImageMarkup
- if (sig != null) m[idx] = sig.copy(bitmap = recolorSignatureBitmap(sig.bitmap, Color(cl).toArgb()))
+ activeImageLoc()?.let { (pg, idx, sig) ->
+ if (sig.isSignature) getPageMarks(pg)[idx] = sig.copy(bitmap = recolorSignatureBitmap(sig.bitmap, Color(cl).toArgb()))
+ }
},
backdrop = contentBackdrop,
uiSensor = uiSensor,
@@ -790,6 +877,7 @@ fun PdfViewerScreen(
AnnotationEditorDialog(
isNote = editingAnnoIsNote,
initialText = annotationDraft,
+ initialColor = editingAnnoColor,
backdrop = contentBackdrop,
uiSensor = uiSensor,
fg = chromeFg,
@@ -805,14 +893,14 @@ fun PdfViewerScreen(
getPageMarks(editingAnnoPage).removeAll { matches(it) }
editingAnnoId = null
},
- onSave = { newText ->
+ onSave = { newText, newColor ->
val list = getPageMarks(editingAnnoPage)
val idx = list.indexOfFirst { matches(it) }
if (idx >= 0) {
- if (newText.isBlank()) list.removeAt(idx)
+ if (newText.isBlank() && list[idx] is PdfMarkup.TextBoxMarkup) list.removeAt(idx)
else list[idx] = when (val m = list[idx]) {
- is PdfMarkup.TextBoxMarkup -> m.copy(text = newText)
- is PdfMarkup.NoteMarkup -> m.copy(text = newText)
+ is PdfMarkup.TextBoxMarkup -> m.copy(text = newText, color = newColor)
+ is PdfMarkup.NoteMarkup -> m.copy(text = newText, color = newColor)
else -> m
}
}
@@ -820,14 +908,46 @@ fun PdfViewerScreen(
}
)
}
- }
- // ── Dialogs ───────────────────────────────────────────────────────────
- if (showSaveDialog) {
- LiquidSaveDialog(
+ // ── Shape editor (recolour / delete a placed rect / oval / line / arrow / stroke) ──
+ editingShapePage?.let { shapePage ->
+ val list = getPageMarks(shapePage)
+ val shape = list.getOrNull(editingShapeIndex)
+ if (shape != null && shape.isShape()) {
+ ShapeEditorPopup(
+ initialColor = shape.shapeColor(),
+ backdrop = contentBackdrop,
+ uiSensor = uiSensor,
+ fg = chromeFg,
+ fgSoft = chromeFgSoft,
+ surface = chromeGlass,
+ field = chromeField,
+ onColorChange = { c ->
+ val cur = list.getOrNull(editingShapeIndex)
+ if (cur != null && cur.isShape()) list[editingShapeIndex] = cur.recolored(c)
+ lastInteractionAtMs = System.currentTimeMillis()
+ },
+ onDelete = {
+ if (editingShapeIndex in list.indices) list.removeAt(editingShapeIndex)
+ editingShapePage = null; editingShapeIndex = -1
+ },
+ onDismiss = { editingShapePage = null; editingShapeIndex = -1 }
+ )
+ } else {
+ editingShapePage = null; editingShapeIndex = -1
+ }
+ }
+
+ // ── Save Document — REAL in-window glass (samples the live page) ──
+ LiquidSaveSheet(
+ visible = showSaveDialog,
initialFileName = state.document?.name?.substringBeforeLast('.')?.let { "${it}_Edited" } ?: "Document",
- backdrop = backdrop,
+ backdrop = contentBackdrop,
uiSensor = uiSensor,
+ fg = chromeFg,
+ fgSoft = chromeFgSoft,
+ surface = chromeGlass,
+ field = chromeField,
onDismiss = { showSaveDialog = false },
onSave = { fileName, overrideUri ->
showSaveDialog = false
@@ -837,6 +957,8 @@ fun PdfViewerScreen(
)
}
+ // ── Dialogs ───────────────────────────────────────────────────────────
+
if (showSignaturePad) {
SignaturePadDialog(
backdrop = backdrop,
@@ -850,27 +972,7 @@ fun PdfViewerScreen(
else -> bmp
}
if (safeBmp != null && safeBmp.width > 0 && safeBmp.height > 0) {
- val page = state.currentPage
- val marks = getPageMarks(page)
- val existingIdx = marks.indexOfLast { it is PdfMarkup.ImageMarkup && it.id == activeImageId }
- if (existingIdx >= 0 && (marks[existingIdx] as PdfMarkup.ImageMarkup).isSignature) {
- val existing = marks[existingIdx] as PdfMarkup.ImageMarkup
- val ratio = safeBmp.height.toFloat() / safeBmp.width.toFloat().coerceAtLeast(1f)
- val currentW = kotlin.math.abs(existing.end.x - existing.start.x).coerceAtLeast(20f)
- marks[existingIdx] = existing.copy(bitmap = safeBmp, end = Offset(existing.end.x, existing.start.y + currentW * ratio), isSignature = true)
- } else {
- val rawCs = pageCanvasSizes[page]
- val cs = if (rawCs != null && rawCs.width > 50f && rawCs.height > 50f) rawCs else Size(1000f, 1400f)
- val bs = pageBitmapSizes[page] ?: cs
- val frame = fitBitmapRect(cs, bs.width, bs.height)
- val maxW = (if (frame.width > 50f) frame.width else cs.width) * 0.45f
- val ratio = safeBmp.height.toFloat() / safeBmp.width.toFloat().coerceAtLeast(1f)
- val w = maxW.coerceAtLeast(100f)
- val center = if (frame.width > 50f) frame.center else Offset(cs.width / 2f, cs.height / 2f)
- val id = System.nanoTime()
- marks.add(PdfMarkup.ImageMarkup(id, safeBmp, Offset(center.x - w / 2f, center.y - w * ratio / 2f), Offset(center.x + w / 2f, center.y + w * ratio / 2f), true))
- activeImageId = id; activeTool = PdfEditTool.Image
- }
+ placeImageMarkup(safeBmp, isSignature = true)
}
}
}
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 a657820..b5d4c8e 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
@@ -61,6 +61,7 @@ import androidx.compose.ui.platform.LocalContext
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.res.stringResource
@@ -274,12 +275,13 @@ fun SettingsScreen(
modifier = Modifier.weight(1f)
) {
Row(
+ Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.spacedBy(6.dp)
+ horizontalArrangement = Arrangement.spacedBy(5.dp, Alignment.CenterHorizontally)
) {
Icon(
option.icon, null,
- Modifier.size(17.dp),
+ Modifier.size(16.dp),
itemContentColor
)
BasicText(
@@ -288,7 +290,10 @@ fun SettingsScreen(
itemContentColor,
13.sp,
fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Medium
- )
+ ),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.weight(1f, fill = false)
)
}
}
@@ -349,17 +354,21 @@ fun SettingsScreen(
modifier = Modifier.weight(1f)
) {
Row(
+ Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.spacedBy(6.dp)
+ horizontalArrangement = Arrangement.spacedBy(5.dp, Alignment.CenterHorizontally)
) {
- Icon(Icons.Rounded.Download, null, Modifier.size(17.dp), defContentColor)
+ Icon(Icons.Rounded.Download, null, Modifier.size(16.dp), defContentColor)
BasicText(
stringResource(R.string.settings_save_downloads),
style = TextStyle(
defContentColor,
13.sp,
fontWeight = if (isDefault) FontWeight.Bold else FontWeight.Medium
- )
+ ),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.weight(1f, fill = false)
)
}
}
@@ -375,17 +384,21 @@ fun SettingsScreen(
modifier = Modifier.weight(1f)
) {
Row(
+ Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.spacedBy(6.dp)
+ horizontalArrangement = Arrangement.spacedBy(5.dp, Alignment.CenterHorizontally)
) {
- Icon(Icons.Rounded.FolderSpecial, null, Modifier.size(17.dp), customContentColor)
+ Icon(Icons.Rounded.FolderSpecial, null, Modifier.size(16.dp), customContentColor)
BasicText(
stringResource(R.string.settings_save_custom),
style = TextStyle(
customContentColor,
13.sp,
fontWeight = if (isCustom) FontWeight.Bold else FontWeight.Medium
- )
+ ),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.weight(1f, fill = false)
)
}
}
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 0e880ac..3155ed2 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
@@ -52,12 +52,18 @@ data class OcrTextBlock(
val left: Float,
val top: Float,
val right: Float,
- val bottom: Float
+ val bottom: Float,
+ val charLefts: FloatArray = FloatArray(0),
+ val charRights: FloatArray = FloatArray(0)
)
+/** A search hit as a normalized rect around the EXACT matched word(s), not the whole line. */
data class FindMatch(
val pageIndex: Int,
- val blockId: String
+ val left: Float,
+ val top: Float,
+ val right: Float,
+ val bottom: Float
)
data class NormalizedPoint(val x: Float, val y: Float)
@@ -486,14 +492,12 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
return
}
val lower = query.trim().lowercase()
- // Fast path: search already-extracted blocks in memory
+ // Fast path: search already-extracted blocks in memory, highlighting the exact word.
val inMemoryMatches = _uiState.value.ocrBlocksByPage
.entries
.sortedBy { it.key }
.flatMap { (page, blocks) ->
- blocks.filter { it.text.lowercase().contains(lower) }
- .sortedBy { it.top }
- .map { FindMatch(page, it.id) }
+ blocks.sortedBy { it.top }.flatMap { it.findMatches(lower, page) }
}
_uiState.value = _uiState.value.copy(
@@ -532,13 +536,11 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
val matches = withContext(Dispatchers.IO) {
runCatching {
textService.searchAll(context, doc.uri, query, doc.pageCount)
- .map { FindMatch(it.pageIndex, it.blockId) }
+ .map { FindMatch(it.pageIndex, it.left, it.top, it.right, it.bottom) }
}.getOrElse {
- // Fallback: search in-memory extracted blocks
+ // Fallback: search in-memory extracted blocks (word-precise).
_uiState.value.ocrBlocksByPage.entries.sortedBy { it.key }.flatMap { (page, blocks) ->
- blocks.filter { it.text.lowercase().contains(lower) }
- .sortedBy { it.top }
- .map { FindMatch(page, it.id) }
+ blocks.sortedBy { it.top }.flatMap { it.findMatches(lower, page) }
}
}
}
@@ -892,5 +894,26 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
}
private fun PdfTextBlock.toOcrBlock() = OcrTextBlock(
- id = id, text = text, left = left, top = top, right = right, bottom = bottom
+ id = id, text = text, left = left, top = top, right = right, bottom = bottom,
+ charLefts = charLefts, charRights = charRights
)
+
+/** All occurrences of [lower] in this block as tight normalized word rects (fallback: block rect). */
+private fun OcrTextBlock.findMatches(lower: String, page: Int): List<FindMatch> {
+ if (lower.isEmpty()) return emptyList()
+ val bt = text.lowercase()
+ val out = ArrayList<FindMatch>()
+ var from = 0
+ while (true) {
+ val idx = bt.indexOf(lower, from)
+ if (idx < 0) break
+ val endC = idx + lower.length - 1
+ if (charLefts.isNotEmpty() && idx < charLefts.size && endC < charRights.size) {
+ out.add(FindMatch(page, charLefts[idx], top, charRights[endC], bottom))
+ } else {
+ out.add(FindMatch(page, left, top, right, bottom))
+ }
+ from = idx + lower.length
+ }
+ return out
+}
diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml
index f4e4beb..4db120e 100644
--- a/app/src/main/res/values-pt-rBR/strings.xml
+++ b/app/src/main/res/values-pt-rBR/strings.xml
@@ -74,7 +74,7 @@
<string name="settings_theme_dark_desc">Sempre usar tema escuro</string>
<string name="settings_save_location">Local de Salvamento</string>
<string name="settings_save_downloads">Downloads</string>
- <string name="settings_save_custom">Pasta Personalizada</string>
+ <string name="settings_save_custom">Personalizada</string>
<string name="settings_file_handling">Gerenciamento de Arquivos</string>
<string name="settings_auto_compress">Comprimir Automaticamente</string>
<string name="settings_auto_compress_desc">Comprimir PDFs automaticamente ao importar</string>
@@ -131,6 +131,8 @@
<string name="viewer_underline">Sublinhado</string>
<string name="viewer_strike">Tachado</string>
<string name="viewer_done">Conclu&#237;do</string>
+ <string name="viewer_color">Cor</string>
+ <string name="viewer_edit_shape">Editar forma</string>
<string name="viewer_new_sign">Nova Assinatura</string>
<string name="viewer_replace">Substituir</string>
<string name="viewer_saving">Salvando PDF editado&#8230;</string>
diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml
index cbfb477..5c7fa8f 100644
--- a/app/src/main/res/values-pt/strings.xml
+++ b/app/src/main/res/values-pt/strings.xml
@@ -74,7 +74,7 @@
<string name="settings_theme_dark_desc">Sempre usar tema escuro</string>
<string name="settings_save_location">Local de Salvamento</string>
<string name="settings_save_downloads">Downloads</string>
- <string name="settings_save_custom">Pasta Personalizada</string>
+ <string name="settings_save_custom">Personalizada</string>
<string name="settings_file_handling">Gerenciamento de Arquivos</string>
<string name="settings_auto_compress">Comprimir Automaticamente</string>
<string name="settings_auto_compress_desc">Comprimir PDFs automaticamente ao importar</string>
@@ -131,6 +131,8 @@
<string name="viewer_underline">Sublinhado</string>
<string name="viewer_strike">Tachado</string>
<string name="viewer_done">Conclu&#237;do</string>
+ <string name="viewer_color">Cor</string>
+ <string name="viewer_edit_shape">Editar forma</string>
<string name="viewer_new_sign">Nova Assinatura</string>
<string name="viewer_replace">Substituir</string>
<string name="viewer_saving">Salvando PDF editado&#8230;</string>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 9399acc..fa7bdf3 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -132,6 +132,8 @@
<string name="viewer_underline">Underline</string>
<string name="viewer_strike">Strike</string>
<string name="viewer_done">Done</string>
+ <string name="viewer_color">Color</string>
+ <string name="viewer_edit_shape">Edit Shape</string>
<string name="viewer_new_sign">New Sign</string>
<string name="viewer_replace">Replace</string>
<string name="viewer_saving">Saving edited PDF&#8230;</string>
diff --git a/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextService.kt b/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextService.kt
index 02295fc..e51763e 100644
--- a/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextService.kt
+++ b/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextService.kt
@@ -15,12 +15,20 @@ data class PdfTextBlock(
val left: Float,
val top: Float,
val right: Float,
- val bottom: Float
+ val bottom: Float,
+ // Per-text-character normalized x bounds, parallel to [text]. Enable word-precise
+ // highlighting of a matched substring instead of the whole line.
+ val charLefts: FloatArray = FloatArray(0),
+ val charRights: FloatArray = FloatArray(0)
)
+/** A search hit as a normalized rect around the exact matched word(s), not the whole line. */
data class PdfSearchMatch(
val pageIndex: Int,
- val blockId: String
+ val left: Float,
+ val top: Float,
+ val right: Float,
+ val bottom: Float
)
interface PdfTextService {
@@ -57,9 +65,7 @@ class PdfTextServiceImpl : PdfTextService {
buildList {
for (pageIdx in 0 until min(doc.numberOfPages, pageCount)) {
extractPageBlocks(doc, pageIdx).forEach { block ->
- if (block.text.lowercase().contains(lower)) {
- add(PdfSearchMatch(pageIdx, block.id))
- }
+ addAll(block.matchRects(lower, pageIdx))
}
}
}
@@ -117,17 +123,33 @@ class PdfTextServiceImpl : PdfTextService {
return lines.mapIndexedNotNull { lineIdx, linePositions ->
val byX = linePositions.sortedBy { it.x }
- val text = buildString {
- var lastRight = -Float.MAX_VALUE
- byX.forEach { tp ->
- val gap = tp.x - lastRight
- if (lastRight > -Float.MAX_VALUE && gap > tp.width * 0.4f) append(' ')
- append(tp.unicode ?: "")
- lastRight = tp.x + tp.width
+ // Build the line text AND per-character x bounds together so indices stay aligned.
+ val sb = StringBuilder()
+ val cl = ArrayList<Float>()
+ val cr = ArrayList<Float>()
+ var lastRight = -Float.MAX_VALUE
+ byX.forEach { tp ->
+ val u = tp.unicode ?: ""
+ if (u.isEmpty()) return@forEach
+ val gap = tp.x - lastRight
+ if (lastRight > -Float.MAX_VALUE && gap > tp.width * 0.4f) {
+ sb.append(' '); cl.add(lastRight); cr.add(tp.x)
}
- }.trim()
-
- if (text.isBlank()) return@mapIndexedNotNull null
+ val x0 = tp.x; val x1 = tp.x + tp.width; val n = u.length
+ for (i in u.indices) {
+ sb.append(u[i])
+ cl.add(x0 + (x1 - x0) * i / n)
+ cr.add(x0 + (x1 - x0) * (i + 1) / n)
+ }
+ lastRight = x1
+ }
+ val raw = sb.toString()
+ val startI = raw.indexOfFirst { !it.isWhitespace() }
+ val endI = raw.indexOfLast { !it.isWhitespace() }
+ if (startI < 0) return@mapIndexedNotNull null
+ val text = raw.substring(startI, endI + 1)
+ val charLefts = FloatArray(endI - startI + 1) { (cl[startI + it] / pageWidth).coerceIn(0f, 1f) }
+ val charRights = FloatArray(endI - startI + 1) { (cr[startI + it] / pageWidth).coerceIn(0f, 1f) }
val minX = byX.minOf { it.x }
val maxX = byX.maxOf { it.x + it.width }
@@ -140,12 +162,34 @@ class PdfTextServiceImpl : PdfTextService {
left = (minX / pageWidth).coerceIn(0f, 1f),
top = (minY / pageHeight).coerceIn(0f, 1f),
right = (maxX / pageWidth).coerceIn(0f, 1f),
- bottom = (maxY / pageHeight).coerceIn(0f, 1f)
+ bottom = (maxY / pageHeight).coerceIn(0f, 1f),
+ charLefts = charLefts,
+ charRights = charRights
)
}
}
}
+/** All occurrences of [lower] (already lower-cased) in this line, as tight word rects. */
+fun PdfTextBlock.matchRects(lower: String, pageIndex: Int): List<PdfSearchMatch> {
+ if (lower.isEmpty() || charLefts.isEmpty()) return emptyList()
+ val bt = text.lowercase()
+ val out = ArrayList<PdfSearchMatch>()
+ var from = 0
+ while (true) {
+ val idx = bt.indexOf(lower, from)
+ if (idx < 0) break
+ val endC = idx + lower.length - 1
+ if (idx < charLefts.size && endC < charRights.size) {
+ out.add(PdfSearchMatch(pageIndex, charLefts[idx], top, charRights[endC], bottom))
+ } else {
+ out.add(PdfSearchMatch(pageIndex, left, top, right, bottom))
+ }
+ from = idx + lower.length
+ }
+ return out
+}
+
private class PositionCapturingStripper : PDFTextStripper() {
val positions = mutableListOf<TextPosition>()
diff --git a/plan.txt b/plan.txt
new file mode 100644
index 0000000..b49fbab
--- /dev/null
+++ b/plan.txt
@@ -0,0 +1,104 @@
+# ClearPDF — UI/UX + Feature Completion Plan (temporary)
+# Work through these ONE BY ONE, patiently, verifying each compiles + doesn't break existing flows.
+# Mark [x] when done. Keep the PDF/document content readable and dominant. Liquid-glass ONLY for floating UI.
+
+=====================================================================
+ITEM 1 — SAVE DOCUMENT → REAL IN-WINDOW GLASS [x] DONE (viewer). Tool screens keep solid Dialog.
+---------------------------------------------------------------------
+- LiquidSaveDialog is currently a SOLID themed card in a Dialog window (can't sample the page).
+- Convert to an IN-WINDOW overlay (like LiquidPageJumpPopup) rendered inside the viewer's
+ BoxWithConstraints so liquidGlassPanel samples the real content backdrop (contentBackdrop).
+- Real glass: translucent + blur + subtle border/highlight/shadow. NO png, NO solid slab.
+- Keep: filename field, folder picker launcher, save location display. imePadding for keyboard.
+- Redesign the save-location section: current location obvious, compact rows, rounded cards,
+ M3 rounded icons (Downloads / Documents / custom folder / create-new-folder).
+- Also used by the tool screens (Merge/Split/etc.) → those stay as-is (over wallpaper) OR
+ give a solid card fallback when no contentBackdrop. Decide cleanly, don't break them.
+
+=====================================================================
+ITEM 2 — TEXT SELECTION + FIND OVERHAUL [x] DONE
+ [x] FIND now highlights the exact matched WORD (not the whole sentence/line). Studied Pdf_Tools
+ (PDFTextStripper per-char TextPosition). We already captured char TextPositions in
+ PdfTextService but collapsed to line blocks; now carry per-char normalized x-bounds
+ (charLefts/charRights) up: PdfTextBlock + OcrTextBlock, and FindMatch is now a normalized
+ WORD rect (was blockId). Search (searchText + searchTextInDocument + PdfTextService.searchAll)
+ computes tight per-occurrence rects; PdfContinuousPage/PdfPageCanvas draw the word rect
+ (rounded, padded). Multiple matches per line supported.
+ [x] Contextual selection bubble added in PdfContinuousPage: when text is selected (SelectText),
+ a compact glass bubble (Copy | Highlight) appears just above the selection's bounding rect,
+ flipping BELOW when near the page top and clamped to page bounds. Wired onCopySelection /
+ onHighlightSelection callbacks from PdfViewerScreen (copy selected OCR text to clipboard;
+ add TextBlockHighlightMarkup for selected ids). NOTE: bubble lives inside the page's zoom
+ layer so it scales with zoom — fine for text-selection (done at ~1x); could counter-scale later.
+ (Kept Search/Share/Annotate out for now to stay compact; can add if wanted.)
+---------------------------------------------------------------------
+- Study Pdf_Tools text selection/search approach (char-position based selection, handles).
+- Selection: clear handles, subtle highlight, contextual action bubble near selection
+ (Copy / Select All / Search / Share / Highlight / Annotate), smart-positioned so it never
+ goes off-screen (flip above/below near edges).
+- Find: compact floating search toolbar, "n / total", prev/next, scroll-to-match, smooth
+ transitions between matches, clean close, never obscures a large part of the doc.
+- Feature-rich + quality-rich. Keep our OCR-block model; adapt Pdf_Tools ideas, don't copy code.
+
+=====================================================================
+ITEM 3 — SETTINGS FULL REDESIGN [ ]
+---------------------------------------------------------------------
+- Rebuild hierarchy (only real settings, no fake ones):
+ Appearance: Theme, (Accent/Dynamic if they exist),
+ Files: Default save location, File naming (if exists), Recent files (if exists)
+ Editor: selection/drawing/highlight defaults (only if they exist)
+ About: Version, Licenses (AndroidLiquidGlass + Pdf_Tools credit), Open source, Privacy
+- Preserve ALL existing functionality/toggles/pickers.
+- Fix every typography/overflow/dark-mode issue (audit each row: long text, pt, small screens,
+ font scaling, multiline, icon collisions). Use constraints, not hardcoded widths.
+- M3 rounded icons, consistent spacing/corner-radii/typography tokens.
+
+=====================================================================
+ITEM 4 — LIQUID GLASS DESIGN SYSTEM EXTRACTION [ ]
+---------------------------------------------------------------------
+- One consistent set of reusable primitives (reuse existing LiquidButton/LiquidIconButton/
+ liquidGlassPanel; add GlassCard/GlassSection/GlassSheet/GlassChip as thin wrappers).
+- Centralize spacing / corner radii / typography / glass tint tokens.
+- Do NOT make everything glass. Document/page stays solid + readable.
+- De-duplicate copy-pasted glass styling across screens.
+
+=====================================================================
+ITEM 5 — PDF_TOOLS FEATURE-GAP PORTING [ ]
+---------------------------------------------------------------------
+- Feature-gap analysis first: what exists / missing / portable / conflicts-with-architecture.
+- Implement highest-value MISSING features (candidates: form fill/flatten, watermark,
+ page extract-to-new-pdf, image tools, HTML->PDF, better OCR) — adapt to our PDFBox/PdfRenderer
+ + PdfMarkup/ExportOverlay model. No unnecessary deps. No blind code copy. Credit already given.
+
+=====================================================================
+BUGS TO FIX (from user) — do alongside the items above [ ]
+---------------------------------------------------------------------
+BUG A — UNDO first-attempt failure:
+ "sometimes on first attempt the undo doesnt work at all for anything any modification unless i
+ come back to homescreen and reopen the pdf."
+ → Undo (per-page currentPageMarks.removeAt(lastIndex)) sometimes no-ops until the PDF is
+ reopened. Investigate: annotationsByPage state / getPageMarks keying / whether the first
+ edit's mark list is a different instance than what undo mutates / recomposition not observing
+ the SnapshotStateList. Likely getPageMarks returns a fresh list vs the one the page edited,
+ or mutableStateListOf identity issue across recompositions. Fix so undo works on first try.
+
+BUG B — Signature resize [x] DONE: PdfContinuousPage image selection redesigned — rounded
+ accent frame, 3 passive corner dots, and a large (22px) bottom-right resize handle with a
+ diagonal glyph; grab radius 40f→64f. (Apple-style: touch target >> visual handle.)
+
+BUG B (original text) — Signature resize is fiddly:
+ "difficult to resize the signature by dragging that small thing/line — improve it, follow Apple HIG,
+ unique sweet UI, best approach."
+ → The image/signature resize handle is a tiny corner dot with a 36-40px hit slop. Redesign:
+ larger, clearer Apple-style corner handles (visible rounded handles at corners), bigger touch
+ target (44dp+), maybe a bounding frame with grab handles, smooth. Keep aspect for signatures.
+ Consider a dedicated resize affordance + move handle. Touch target >= visual size.
+
+=====================================================================
+GLOBAL RULES
+---------------------------------------------------------------------
+- Compile (:app:compileDebugKotlin) after each item; don't break opening/render/nav/zoom/scroll/
+ select/search/annotate/draw/highlight/sign/saved-sigs/save/export/file-picker/settings/darkmode.
+- Apple-quality: hierarchy, spacing, typography, restraint, depth, contextual controls, subtle motion.
+- pt labels ~1.3x longer than EN → width-constrained buttons need maxLines=1.
+- Keep memory (session-work-status.md) updated per item.