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
UnsavedChangesDialog everywhere edits can be lost
Chethan6165f5a8212a33d
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassPrimitives.kt b/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassPrimitives.ktindex 7221f9d..69e1988 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassPrimitives.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassPrimitives.kt@@ -165,8 +165,15 @@ fun ToolScaffold(/** Retained for source compatibility; the title pill has a fixed 13 sp label like the viewer's. */@Suppress("UNUSED_PARAMETER") titleFontSize: TextUnit = 18.sp,headerTrailing: (@Composable RowScope.() -> Unit)? = null,+ /**+ * Floating layer drawn above header + body (dialogs such as [UnsavedChangesDialog]). It gets the+ * screen's live glass backdrop — wallpaper + the scrolling body — and sits outside the captured+ * layer, so there is no feedback loop.+ */+ overlay: (@Composable (screenGlass: Backdrop) -> Unit)? = null,content: @Composable ColumnScope.() -> Unit) {+ val screenBackdrop = rememberScreenBackdrop(backdrop)val isLight = !LocalIsDarkMode.currentval text = if (isLight) Color(0xFF222222) else Color(0xFFF0F0F0)val density = LocalDensity.current.density@@ -184,9 +191,10 @@ fun ToolScaffold(// Column above it, so cards pass under the glass instead of stopping at its edge — and the// header samples wallpaper + live content, so its refraction is finally of something real. It// used to sample a layer captured *below* it, which meant it refracted nothing at all.+ Box(modifier.fillMaxSize()) {GlassScreenScaffold(backdrop = backdrop,- modifier = modifier,+ screenBackdrop = screenBackdrop,contentBottomPadding = GlassDimens.ScreenPadding,header = { headerBackdrop ->// Same header trio as the PDF/spreadsheet viewers: back circle · centered title pill ·@@ -233,4 +241,6 @@ fun ToolScaffold(content = content)}+ overlay?.invoke(screenBackdrop.glass)+ }}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/FillFormScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/FillFormScreen.ktindex 4cba302..8f0f1b4 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/FillFormScreen.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/FillFormScreen.kt@@ -1,5 +1,9 @@package com.chethan616.clearpdf.ui.screen+import androidx.compose.runtime.setValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.activity.compose.BackHandlerimport android.net.Uriimport androidx.activity.compose.rememberLauncherForActivityResultimport androidx.activity.result.contract.ActivityResultContracts@@ -42,6 +46,7 @@ import com.chethan616.clearpdf.ui.components.LiquidButtonimport com.chethan616.clearpdf.ui.components.LiquidGlassErrorCardimport com.chethan616.clearpdf.ui.components.LiquidToggleimport com.chethan616.clearpdf.ui.components.ToolScaffold+import com.chethan616.clearpdf.ui.components.UnsavedChangesDialogimport com.chethan616.clearpdf.ui.components.liquidGlassPanelimport com.chethan616.clearpdf.ui.theme.LocalIsDarkModeimport com.chethan616.clearpdf.ui.utils.rememberUISensor@@ -75,10 +80,24 @@ fun FillFormScreen(contract = ActivityResultContracts.OpenDocument()) { uri -> if (uri != null) viewModel.onSelectFile(context, uri) }+ var confirmExit by remember { mutableStateOf(false) }+ val requestBack = { if (state.dirty && !state.isProcessing) confirmExit = true else onBack() }+ BackHandler(enabled = state.dirty && !confirmExit) { requestBack() }+ToolScaffold(title = stringResource(R.string.tool_fill_form),backdrop = backdrop,- onBack = onBack+ onBack = requestBack,+ overlay = { screenGlass ->+ UnsavedChangesDialog(+ visible = confirmExit,+ onDiscard = { confirmExit = false; onBack() },+ onCancel = { confirmExit = false },+ onSave = { confirmExit = false; viewModel.save(context, onSaved = onBack) },+ backdrop = screenGlass,+ accent = FormAccent+ )+ }) {Column(Modifier.fillMaxWidth().liquidGlassPanel(backdrop, uiSensor).padding(28.dp),diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/ImageEditorScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/ImageEditorScreen.ktindex 2fca877..05523b3 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/ImageEditorScreen.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/ImageEditorScreen.kt@@ -75,8 +75,7 @@ import androidx.compose.ui.unit.spimport com.chethan616.clearpdf.Rimport com.chethan616.clearpdf.ui.components.GlassBottomSheetimport com.chethan616.clearpdf.ui.components.GlassColorPicker-import com.chethan616.clearpdf.ui.components.GlassDialog-import com.chethan616.clearpdf.ui.components.GlassDialogAction+import com.chethan616.clearpdf.ui.components.UnsavedChangesDialogimport com.chethan616.clearpdf.ui.components.GlassHeaderHeightimport com.chethan616.clearpdf.ui.components.GlassProgressBarimport com.chethan616.clearpdf.ui.components.GlassScreenHeaderRow@@ -402,18 +401,15 @@ fun ImageEditorScreen()}- GlassDialog(+ // Same "Save changes?" card as every editor; Save publishes to the gallery, then leaves.+ UnsavedChangesDialog(visible = showDiscard,- onDismiss = { showDiscard = false },+ onDiscard = { showDiscard = false; onBack() },+ onCancel = { showDiscard = false },+ onSave = { showDiscard = false; viewModel.saveToGallery(onSaved = onBack) },backdrop = glass,- title = stringResource(R.string.ie_discard_title),- actions = {- GlassDialogAction(stringResource(R.string.ie_keep_editing), { showDiscard = false })- GlassDialogAction(stringResource(R.string.ie_discard), { showDiscard = false; onBack() }, destructive = true)- }- ) {- BasicText(stringResource(R.string.ie_discard_body), style = TextStyle(sub, 14.sp))- }+ body = stringResource(R.string.unsaved_body_image)+ )}}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PageOrganizerScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PageOrganizerScreen.ktindex ea890fb..c87f491 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PageOrganizerScreen.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PageOrganizerScreen.kt@@ -69,6 +69,8 @@ import com.chethan616.clearpdf.ui.components.GlassScreenHeaderRowimport com.chethan616.clearpdf.ui.components.GlassScreenScaffoldimport com.chethan616.clearpdf.ui.components.LiquidIconButtonimport com.chethan616.clearpdf.ui.components.LiquidSaveDialog+import com.chethan616.clearpdf.ui.components.UnsavedChangesDialog+import com.chethan616.clearpdf.ui.components.rememberScreenBackdropimport com.chethan616.clearpdf.ui.components.liquidGlassPanelimport com.chethan616.clearpdf.ui.theme.LocalIsDarkModeimport com.chethan616.clearpdf.ui.utils.rememberUISensor@@ -96,6 +98,11 @@ fun PageOrganizerScreen(val density = LocalDensity.currentvar showSaveDialog by remember { mutableStateOf(false) }+ var confirmExit by remember { mutableStateOf(false) }+ var exitAfterSave by remember { mutableStateOf(false) }+ val requestBack = { if (state.dirty && !state.isSaving) confirmExit = true else onBack() }+ androidx.activity.compose.BackHandler(enabled = state.dirty && !confirmExit && !showSaveDialog) { requestBack() }+ val screenBackdrop = rememberScreenBackdrop(backdrop)var isVisible by remember { mutableStateOf(false) }androidx.compose.runtime.LaunchedEffect(Unit) { isVisible = true }@@ -144,15 +151,17 @@ fun PageOrganizerScreen(uri?.let { viewModel.onSelectFile(context, it) }}+ Box(Modifier.fillMaxSize()) {GlassScreenScaffold(backdrop = backdrop,+ screenBackdrop = screenBackdrop,contentBottomPadding = 16.dp,header = { headerBackdrop ->// Fade only — the header is glass, and translating glass re-runs its blur+lens.GlassScreenHeaderRow(title = stringResource(R.string.organize_screen_title),backdrop = headerBackdrop,- onBack = onBack,+ onBack = requestBack,modifier = Modifier.graphicsLayer { alpha = topBarAlpha })}@@ -404,15 +413,28 @@ fun PageOrganizerScreen(}}+ // Leaving with a reordered / rotated layout that was never written out.+ UnsavedChangesDialog(+ visible = confirmExit,+ onDiscard = { confirmExit = false; onBack() },+ onCancel = { confirmExit = false },+ onSave = { confirmExit = false; exitAfterSave = true; showSaveDialog = true },+ backdrop = screenBackdrop.glass,+ accent = accent+ )+ }+if (showSaveDialog) {LiquidSaveDialog(initialFileName = state.sourceFileName.substringBeforeLast('.').ifBlank { "Document" } + "_Organized",backdrop = backdrop,uiSensor = uiSensor,- onDismiss = { showSaveDialog = false },+ onDismiss = { showSaveDialog = false; exitAfterSave = false },onSave = { fileName, overrideUri ->showSaveDialog = false- viewModel.save(context, fileName, overrideUri)+ val leave = exitAfterSave+ exitAfterSave = false+ viewModel.save(context, fileName, overrideUri, onSaved = if (leave) onBack else null)})}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.ktindex b065bf9..af8b8d8 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@@ -118,6 +118,7 @@ import androidx.core.view.WindowInsetsCompatimport androidx.core.view.WindowInsetsControllerCompatimport com.chethan616.clearpdf.Rimport com.chethan616.clearpdf.data.repository.AppSettingsManager+import com.chethan616.clearpdf.ui.components.UnsavedChangesDialogimport com.chethan616.clearpdf.ui.components.DecryptingAnimationimport com.chethan616.clearpdf.ui.components.LiquidButtonimport com.chethan616.clearpdf.ui.components.GlassTitlePill@@ -246,6 +247,19 @@ fun PdfViewerScreen(fun getPageMarks(page: Int): MutableList<PdfMarkup> =annotationsByPage.getOrPut(page) { mutableStateListOf() }+ // ── Unsaved-edit tracking ──────────────────────────────────────────────+ // Markups live here (not in the ViewModel), so "dirty" is: the current markups differ from what+ // was last exported. PdfMarkup variants are data classes, so a structural compare of a per-page+ // copy is exact — drawing, erasing, moving, retyping a note all flip it, undoing back to the+ // saved state clears it. Covers PDFs and Office documents alike (both render through here).+ fun markupSnapshot(): Map<Int, List<PdfMarkup>> =+ annotationsByPage.filterValues { it.isNotEmpty() }.mapValues { it.value.toList() }+ var savedMarkups by remember { mutableStateOf<Map<Int, List<PdfMarkup>>>(emptyMap()) }+ var pendingSaveMarkups by remember { mutableStateOf<Map<Int, List<PdfMarkup>>?>(null) }+ var exitAfterSave by remember { mutableStateOf(false) }+ var showUnsavedDialog by remember { mutableStateOf(false) }+ val hasUnsavedEdits by remember { derivedStateOf { markupSnapshot() != savedMarkups } }+// Undo history: the page each added markup landed on, newest last. Undo pops the most recent// entry and removes THAT page's last mark, so "undo" means the last thing the user actually// did. The old behaviour removed the last mark of `listState.firstVisibleItemIndex`, which is@@ -426,6 +440,7 @@ fun PdfViewerScreen(activeTool = PdfEditTool.NoneselectedAnnoPage = null; selectedAnnoIndex = -1annotationsByPage.clear(); undoStack.clear(); pageCanvasSizes.clear(); pageBitmapSizes.clear()+ savedMarkups = emptyMap(); pendingSaveMarkups = null; exitAfterSave = false; showUnsavedDialog = falsetextSelection.resetDocument(); viewModel.clearExportFeedback()showFindBar = false; findQuery = ""; viewModel.clearSearch()}@@ -448,8 +463,26 @@ fun PdfViewerScreen(if (state.passwordUri != null) { passwordText = ""; delay(120); passwordFocusRequester.requestFocus() }}+ /** Leave the viewer — via the "Save changes?" card when there are unexported markups. */+ fun requestExit() {+ if (state.document != null && hasUnsavedEdits) { controlsVisible = true; showUnsavedDialog = true }+ else onBack()+ }++ // An export started from the unsaved-changes card (or any Save) settles here: success marks the+ // exported markups as saved and, if the card asked for it, leaves; failure keeps the user here.+ LaunchedEffect(state.exportMessage, state.exportError) {+ val pending = pendingSaveMarkups ?: return@LaunchedEffect+ if (state.exportMessage != null) {+ savedMarkups = pending; pendingSaveMarkups = null+ if (exitAfterSave) { exitAfterSave = false; onBack() }+ } else if (state.exportError != null) {+ pendingSaveMarkups = null; exitAfterSave = false+ }+ }+BackHandler(enabled = state.document != null) {- if (!controlsVisible) controlsVisible = true else onBack()+ if (!controlsVisible) controlsVisible = true else requestExit()}// ── No-document state ─────────────────────────────────────────────────@@ -1058,7 +1091,7 @@ fun PdfViewerScreen() {// No `surfaceColor`, exactly as Home calls it: the circle paints nothing of its own// and is pure refraction. Only the icon's colour adapts to the page.- LiquidIconButton(onClick = onBack, backdrop = contentBackdrop) {+ LiquidIconButton(onClick = { requestExit() }, backdrop = contentBackdrop) {Icon(Icons.Rounded.ArrowBackIosNew, stringResource(R.string.back), Modifier.size(16.dp), topFg)}// A weighted Box rather than two weighted spacers: the back circle and the@@ -1458,14 +1491,33 @@ fun PdfViewerScreen(fgSoft = panelFgSoft,surface = chromePanel,field = chromeField,- onDismiss = { showSaveDialog = false },+ onDismiss = { showSaveDialog = false; exitAfterSave = false },onSave = { fileName, overrideUri ->showSaveDialog = false+ val snapshot = markupSnapshot()val overlays = buildExportOverlays(annotationsByPage, state.ocrBlocksByPage, pageCanvasSizes, pageBitmapSizes)- if (overlays.isNotEmpty()) viewModel.exportEditedPdf(context, overlays, fileName, overrideUri)+ if (overlays.isNotEmpty()) {+ pendingSaveMarkups = snapshot+ viewModel.exportEditedPdf(context, overlays, fileName, overrideUri)+ } else {+ // Nothing exportable (e.g. only empty text boxes) — nothing to lose either.+ savedMarkups = snapshot+ if (exitAfterSave) { exitAfterSave = false; onBack() }+ }})+ // ── Unsaved changes — same card as the spreadsheet, refracting the live page ──+ // Save routes through the normal Save sheet (file name / location), then leaves once the+ // export succeeds (see the exportMessage effect above).+ UnsavedChangesDialog(+ visible = showUnsavedDialog,+ onDiscard = { showUnsavedDialog = false; onBack() },+ onCancel = { showUnsavedDialog = false },+ onSave = { showUnsavedDialog = false; exitAfterSave = true; showSaveDialog = true },+ backdrop = contentBackdrop+ )+// ── Share / export chooser ──// Original vs PDF (with optional encryption). `originalExt` is null for a plain PDF, which// collapses the dialog to just the encrypt toggle.diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/FillFormViewModel.kt b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/FillFormViewModel.ktindex 9c48c9c..a962d85 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/FillFormViewModel.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/FillFormViewModel.kt@@ -34,7 +34,9 @@ data class FillFormUiState(val isProcessing: Boolean = false,val lastOutputUri: Uri? = null,val resultMessage: String? = null,- val errorMessage: String? = null+ val errorMessage: String? = null,+ /** Field values edited since the file was opened / last successfully saved. */+ val dirty: Boolean = false)class FillFormViewModel : ViewModel() {@@ -46,7 +48,7 @@ class FillFormViewModel : ViewModel() {try {context.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)} catch (_: Exception) {}- _uiState.update { it.copy(sourceUri = uri, sourceName = queryName(context, uri), fields = emptyList(), loaded = false, lastOutputUri = null, resultMessage = null, errorMessage = null) }+ _uiState.update { it.copy(sourceUri = uri, sourceName = queryName(context, uri), fields = emptyList(), loaded = false, lastOutputUri = null, resultMessage = null, errorMessage = null, dirty = false) }viewModelScope.launch {val fields = withContext(Dispatchers.IO) { runCatching { PdfFormService.readFields(context, uri) }.getOrDefault(emptyList()) }_uiState.update {@@ -60,13 +62,14 @@ class FillFormViewModel : ViewModel() {fun onFieldChange(name: String, value: String) {_uiState.update { st ->- st.copy(fields = st.fields.map { if (it.name == name) it.copy(value = value) else it })+ st.copy(fields = st.fields.map { if (it.name == name) it.copy(value = value) else it }, dirty = true)}}fun onFlattenChange(value: Boolean) = _uiState.update { it.copy(flatten = value) }- fun save(context: Context) {+ /** [onSaved] runs only after the filled copy was actually written. */+ fun save(context: Context, onSaved: (() -> Unit)? = null) {val src = _uiState.value.sourceUri ?: returnif (_uiState.value.isProcessing || _uiState.value.fields.isEmpty()) return_uiState.update { it.copy(isProcessing = true, errorMessage = null, resultMessage = null, lastOutputUri = null) }@@ -83,7 +86,8 @@ class FillFormViewModel : ViewModel() {name = fileName, uriString = outUri.toString(),timestamp = System.currentTimeMillis(), sizeBytes = 0))- _uiState.update { it.copy(isProcessing = false, lastOutputUri = outUri, resultMessage = "Filled $written field${if (written == 1) "" else "s"} · saved to $saveLabel") }+ _uiState.update { it.copy(isProcessing = false, lastOutputUri = outUri, resultMessage = "Filled $written field${if (written == 1) "" else "s"} · saved to $saveLabel", dirty = false) }+ onSaved?.invoke()} catch (t: Throwable) {_uiState.update { it.copy(isProcessing = false, errorMessage = t.message ?: "Couldn't fill the form") }}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/ImageEditorViewModel.kt b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/ImageEditorViewModel.ktindex 382b98d..9cc7ace 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/ImageEditorViewModel.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/ImageEditorViewModel.kt@@ -537,8 +537,10 @@ class ImageEditorViewModel(app: Application) : AndroidViewModel(app) {}}- fun saveToGallery() = export { file ->+ /** [onSaved] runs (main thread) only when the image actually landed in the gallery. */+ fun saveToGallery(onSaved: (() -> Unit)? = null) = export { file ->val uri = withContext(Dispatchers.IO) { ImageIo.publishToGallery(context, file, _state.value.export.format) }+ if (uri != null && onSaved != null) withContext(Dispatchers.Main) { onSaved() }if (uri != null) "Saved to Pictures/ClearPDF" else "Couldn't save image"}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PageOrganizerViewModel.kt b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PageOrganizerViewModel.ktindex d18a5e6..fdc30bb 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PageOrganizerViewModel.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PageOrganizerViewModel.kt@@ -47,8 +47,15 @@ data class PageOrganizerUiState(val resultMessage: String? = null,val errorMessage: String? = null,val lastOutputUri: Uri? = null,- val saveLocationLabel: String = "Downloads (default)"-)+ val saveLocationLabel: String = "Downloads (default)",+ /** (originalIndex, rotation) of every page as last loaded / saved — the "clean" layout. */+ val savedLayout: List<Pair<Int, Int>> = emptyList()+) {+ /** Reordered, rotated or deleted pages that haven't been written to a PDF yet. */+ val dirty: Boolean get() = pages.isNotEmpty() && layoutOf(pages) != savedLayout+}++internal fun layoutOf(pages: List<OrganizerPage>) = pages.map { it.originalIndex to Math.floorMod(it.rotation, 360) }class PageOrganizerViewModel(private val editor: PdfEditor) : ViewModel() {private val _uiState = MutableStateFlow(PageOrganizerUiState())@@ -68,7 +75,8 @@ class PageOrganizerViewModel(private val editor: PdfEditor) : ViewModel() {_uiState.value = PageOrganizerUiState(sourceFileName = name,sourceUri = uri,- pages = pages.mapIndexed { i, bmp -> OrganizerPage(originalIndex = i, thumbnail = bmp) }+ pages = pages.mapIndexed { i, bmp -> OrganizerPage(originalIndex = i, thumbnail = bmp) },+ savedLayout = List(pages.size) { i -> i to 0 })} catch (e: Exception) {_uiState.value = PageOrganizerUiState(errorMessage = context.getString(R.string.organize_open_failed))@@ -150,7 +158,8 @@ class PageOrganizerViewModel(private val editor: PdfEditor) : ViewModel() {_uiState.value = _uiState.value.copy(pages = result, resultMessage = null)}- fun save(context: Context, fileName: String, overrideUri: Uri? = null) {+ /** [onSaved] runs only after the new PDF was written. */+ fun save(context: Context, fileName: String, overrideUri: Uri? = null, onSaved: (() -> Unit)? = null) {val src = _uiState.value.sourceUri ?: returnval pages = _uiState.value.pagesif (pages.isEmpty()) return@@ -177,8 +186,10 @@ class PageOrganizerViewModel(private val editor: PdfEditor) : ViewModel() {isSaving = false,lastOutputUri = outUri,saveLocationLabel = saveLabel,- resultMessage = context.getString(R.string.organize_success, pages.size, saveLabel)+ resultMessage = context.getString(R.string.organize_success, pages.size, saveLabel),+ savedLayout = layoutOf(pages))+ onSaved?.invoke()val shouldPrompt = withContext(Dispatchers.IO) { GitHubStarPromptManager.recordPdfInteraction(context) }if (shouldPrompt) StarPromptEventBus.requestPrompt()} catch (e: Exception) {