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.

2.1.1: sharp zoom, own document window, PPTX titles, glass form fields, F-Droid flavor

chethan616646e33b515ef
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 05985c0..c27c693 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -38,8 +38,8 @@ android {
applicationId = "com.chethan616.clearpdf"
minSdk = 23
targetSdk = 36
- versionCode = 5
- versionName = "2.1.0"
+ versionCode = 6
+ versionName = "2.1.1"
// Keep every locale declared by the app. Filtering this to English
// removes values-pt-rBR from the packaged APK, so the language picker
// can appear to work while the app continues to resolve English.
@@ -95,6 +95,18 @@ android {
create("foss") {
dimension = "distribution"
}
+ // F-Droid: free software only. No Google Play services / ML Kit (the document scanner
+ // falls back to the camera app, OCR to Tesseract, background removal is not offered) and
+ // no downloaded Office engine. Same applicationId, so it updates like the GitHub build.
+ create("fdroid") {
+ dimension = "distribution"
+ }
+ }
+ // Code that needs Google's libraries lives in src/gms, shared by the play and foss builds;
+ // the fdroid build has its own free implementations in src/fdroid.
+ sourceSets {
+ getByName("play").kotlin.srcDir("src/gms/java")
+ getByName("foss").kotlin.srcDir("src/gms/java")
}
// AGP can't link a dynamic feature against ABI-split APK outputs, and the feature is only
// ever delivered through a Play bundle anyway — so register it for bundle builds only.
@@ -110,7 +122,8 @@ android {
// APK builds/installs (`assembleDebug`/`assembleRelease`, `installDebug`, sideloading).
splits {
abi {
- isEnable = true
+ // F-Droid builds and signs one APK per version itself, so its builds skip the split.
+ isEnable = gradle.startParameter.taskNames.none { it.contains("fdroid", ignoreCase = true) }
reset()
include("armeabi-v7a", "arm64-v8a", "x86", "x86_64")
isUniversalApk = true
@@ -155,6 +168,9 @@ kotlin {
dependencies {
testImplementation("junit:junit:4.13.2")
implementation(libs.androidx.core.ktx)
+ // Per-app language (LocaleHelper). Declared directly: the play / foss builds used to get it
+ // only transitively through Google's libraries, which the F-Droid build doesn't have.
+ implementation("androidx.appcompat:appcompat:1.7.0")
implementation(libs.androidx.activity.compose)
implementation(libs.androidx.compose.foundation)
implementation(libs.androidx.compose.ui)
@@ -179,7 +195,8 @@ dependencies {
implementation(libs.pdfbox.android)
// ML Kit Document Scanner & Camera
- implementation(libs.play.services.mlkit.scanner)
+ "playImplementation"(libs.play.services.mlkit.scanner)
+ "fossImplementation"(libs.play.services.mlkit.scanner)
implementation(libs.camerax.core)
implementation(libs.camerax.camera2)
implementation(libs.camerax.lifecycle)
@@ -194,7 +211,10 @@ dependencies {
// isolated behind BackgroundRemover so a FOSS flavor can swap it out).
implementation(libs.gpuimage)
implementation(libs.androidx.exifinterface)
- implementation(libs.mlkit.subject.segmentation)
+ "playImplementation"(libs.mlkit.subject.segmentation)
+ "fossImplementation"(libs.mlkit.subject.segmentation)
+ "playImplementation"(libs.mlkit.text.recognition)
+ "fossImplementation"(libs.mlkit.text.recognition)
// A real XmlPullParser for JVM tests; android.jar only carries stubs of it.
testImplementation("net.sf.kxml:kxml2:2.3.0")
diff --git a/app/src/fdroid/AndroidManifest.xml b/app/src/fdroid/AndroidManifest.xml
new file mode 100644
index 0000000..44fe7d1
--- /dev/null
+++ b/app/src/fdroid/AndroidManifest.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ F-Droid flavor. Network access is used for one user-initiated feature only: converting a web
+ address the user types to PDF. Documents are never uploaded, and no code is downloaded.
+-->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+</manifest>
diff --git a/app/src/fdroid/java/com/chethan616/clearpdf/imageeditor/engine/BackgroundRemoverFlavor.kt b/app/src/fdroid/java/com/chethan616/clearpdf/imageeditor/engine/BackgroundRemoverFlavor.kt
new file mode 100644
index 0000000..ddf432e
--- /dev/null
+++ b/app/src/fdroid/java/com/chethan616/clearpdf/imageeditor/engine/BackgroundRemoverFlavor.kt
@@ -0,0 +1,16 @@
+package com.chethan616.clearpdf.imageeditor.engine
+
+import android.content.Context
+import android.graphics.Bitmap
+
+/**
+ * F-Droid build: automatic background removal needs Google's ML Kit, which isn't free software,
+ * so it's simply not offered (the editor hides it when [BackgroundRemover.isAvailable] is false).
+ */
+internal object BackgroundRemoverFlavor {
+ fun create(context: Context): BackgroundRemover = object : BackgroundRemover {
+ override val isAvailable: Boolean = false
+ override suspend fun segment(image: Bitmap): Result<Bitmap> =
+ Result.failure(UnsupportedOperationException("Background removal isn't available in this build."))
+ }
+}
diff --git a/app/src/fdroid/java/com/chethan616/clearpdf/ocr/OcrFlavor.kt b/app/src/fdroid/java/com/chethan616/clearpdf/ocr/OcrFlavor.kt
new file mode 100644
index 0000000..f29a710
--- /dev/null
+++ b/app/src/fdroid/java/com/chethan616/clearpdf/ocr/OcrFlavor.kt
@@ -0,0 +1,9 @@
+package com.chethan616.clearpdf.ocr
+
+import android.graphics.Bitmap
+import com.kyant.ocrcore.OcrPageResult
+
+/** F-Droid build: free software only, so OCR is Tesseract4Android alone. */
+internal object OcrFlavor {
+ val primaryEngine: (suspend (Bitmap) -> OcrPageResult)? = null
+}
diff --git a/app/src/fdroid/java/com/chethan616/clearpdf/office/OfficeEngineFlavor.kt b/app/src/fdroid/java/com/chethan616/clearpdf/office/OfficeEngineFlavor.kt
new file mode 100644
index 0000000..4f27040
--- /dev/null
+++ b/app/src/fdroid/java/com/chethan616/clearpdf/office/OfficeEngineFlavor.kt
@@ -0,0 +1,26 @@
+package com.chethan616.clearpdf.office
+
+import android.content.Context
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+
+/**
+ * F-Droid build: the optional Office engine is a downloaded native binary, which F-Droid's
+ * inclusion policy doesn't allow, so it is never offered here and the built-in Office renderers
+ * are used instead.
+ */
+internal object OfficeEngineFlavor {
+ const val available: Boolean = false
+ fun createInstaller(context: Context): OfficeEngineInstaller = UnavailableOfficeEngineInstaller
+}
+
+private object UnavailableOfficeEngineInstaller : OfficeEngineInstaller {
+ private val _state = MutableStateFlow<OfficeEngineState>(OfficeEngineState.Unsupported)
+ override val state: StateFlow<OfficeEngineState> = _state.asStateFlow()
+ override val usesNotification: Boolean = false
+ override fun install() = Unit
+ override fun cancel() = Unit
+ override fun uninstall() = Unit
+ override fun refresh() = Unit
+}
diff --git a/app/src/fdroid/java/com/chethan616/clearpdf/scan/DocumentScanner.kt b/app/src/fdroid/java/com/chethan616/clearpdf/scan/DocumentScanner.kt
new file mode 100644
index 0000000..373e7c2
--- /dev/null
+++ b/app/src/fdroid/java/com/chethan616/clearpdf/scan/DocumentScanner.kt
@@ -0,0 +1,53 @@
+package com.chethan616.clearpdf.scan
+
+import android.Manifest
+import android.content.pm.PackageManager
+import android.net.Uri
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberUpdatedState
+import androidx.compose.ui.platform.LocalContext
+import androidx.core.content.ContextCompat
+import androidx.core.content.FileProvider
+import java.io.File
+
+/**
+ * F-Droid build: Google's scanner isn't free software, so a scan is a photo from the phone's own
+ * camera app, one page per shot (each shot is added to the scan, and the app's own filters clean
+ * it up). Same contract as the play / foss scanner.
+ */
+@Composable
+internal fun rememberDocumentScanner(
+ onPages: (List<Uri>) -> Unit,
+ onFinished: () -> Unit,
+ onError: () -> Unit
+): () -> Unit {
+ val context = LocalContext.current
+ val pages by rememberUpdatedState(onPages)
+ val finished by rememberUpdatedState(onFinished)
+ val error by rememberUpdatedState(onError)
+ val pending = remember { arrayOfNulls<Uri>(1) }
+ val camera = rememberLauncherForActivityResult(ActivityResultContracts.TakePicture()) { ok ->
+ val uri = pending[0]
+ if (ok && uri != null) pages(listOf(uri))
+ finished()
+ }
+ fun shoot() {
+ val dir = File(context.cacheDir, "scans").apply { mkdirs() }
+ val file = File(dir, "scan_${System.currentTimeMillis()}.jpg")
+ val uri = FileProvider.getUriForFile(context, "${context.packageName}.provider", file)
+ pending[0] = uri
+ runCatching { camera.launch(uri) }.onFailure { error(); finished() }
+ }
+ // The app declares CAMERA, so Android requires it granted before handing off to a camera app.
+ val permission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
+ if (granted) shoot() else finished()
+ }
+ return {
+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) shoot()
+ else permission.launch(Manifest.permission.CAMERA)
+ }
+}
diff --git a/app/src/foss/java/com/chethan616/clearpdf/office/OfficeEngineFlavor.kt b/app/src/foss/java/com/chethan616/clearpdf/office/OfficeEngineFlavor.kt
index 2bc58e6..f6e98ec 100644
--- a/app/src/foss/java/com/chethan616/clearpdf/office/OfficeEngineFlavor.kt
+++ b/app/src/foss/java/com/chethan616/clearpdf/office/OfficeEngineFlavor.kt
@@ -17,6 +17,7 @@ import kotlinx.coroutines.launch
/** foss flavor: the engine is downloaded from the pinned release by [OfficeEngineDownloadWorker]. */
internal object OfficeEngineFlavor {
+ const val available: Boolean = true
fun createInstaller(context: Context): OfficeEngineInstaller = DownloadOfficeEngineInstaller(context)
}
diff --git a/app/src/gms/java/com/chethan616/clearpdf/imageeditor/engine/BackgroundRemoverFlavor.kt b/app/src/gms/java/com/chethan616/clearpdf/imageeditor/engine/BackgroundRemoverFlavor.kt
new file mode 100644
index 0000000..3f4b725
--- /dev/null
+++ b/app/src/gms/java/com/chethan616/clearpdf/imageeditor/engine/BackgroundRemoverFlavor.kt
@@ -0,0 +1,69 @@
+package com.chethan616.clearpdf.imageeditor.engine
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.os.Build
+import com.google.mlkit.vision.common.InputImage
+import com.google.mlkit.vision.segmentation.subject.SubjectSegmentation
+import com.google.mlkit.vision.segmentation.subject.SubjectSegmenterOptions
+import kotlinx.coroutines.suspendCancellableCoroutine
+import kotlin.coroutines.resume
+
+/** play / foss builds: subject segmentation by Google Play services ML Kit. */
+internal object BackgroundRemoverFlavor {
+ fun create(context: Context): BackgroundRemover = MlKitBackgroundRemover(context)
+}
+
+/** Google Play services ML Kit subject segmentation (model is fetched by Play services). */
+private class MlKitBackgroundRemover(private val context: Context) : BackgroundRemover {
+
+ override val isAvailable: Boolean
+ get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && hasPlayServices()
+
+ private fun hasPlayServices(): Boolean = runCatching {
+ context.packageManager.getPackageInfo("com.google.android.gms", 0); true
+ }.getOrDefault(false)
+
+ override suspend fun segment(image: Bitmap): Result<Bitmap> {
+ if (!isAvailable) return Result.failure(IllegalStateException("Background removal isn't available on this device."))
+ return runCatching { segmentImpl(image) }
+ }
+
+ private suspend fun segmentImpl(image: Bitmap): Bitmap {
+ val options = SubjectSegmenterOptions.Builder()
+ .enableForegroundConfidenceMask()
+ .build()
+ val client = SubjectSegmentation.getClient(options)
+ try {
+ val input = InputImage.fromBitmap(image, 0)
+ val result = suspendCancellableCoroutine { cont ->
+ client.process(input)
+ .addOnSuccessListener { cont.resume(Result.success(it)) }
+ .addOnFailureListener { cont.resume(Result.failure(it)) }
+ }.getOrElse { e ->
+ val msg = e.message.orEmpty()
+ throw IllegalStateException(
+ if (msg.contains("download", true) || msg.contains("module", true))
+ "The background-removal model is still downloading. Try again in a moment."
+ else "Couldn't detect a subject in this image."
+ )
+ }
+ val buffer = result.foregroundConfidenceMask
+ ?: throw IllegalStateException("Couldn't detect a subject in this image.")
+ val w = image.width
+ val h = image.height
+ buffer.rewind()
+ val pixels = IntArray(w * h)
+ for (i in 0 until w * h) {
+ val c = buffer.get().coerceIn(0f, 1f)
+ pixels[i] = ((c * 255f).toInt() shl 24)
+ }
+ val argb = Bitmap.createBitmap(pixels, w, h, Bitmap.Config.ARGB_8888)
+ val mask = argb.extractAlpha()
+ argb.recycle()
+ return mask
+ } finally {
+ client.close()
+ }
+ }
+}
diff --git a/ocr-core/src/main/java/com/kyant/ocrcore/MlKitOcrEngine.kt b/app/src/gms/java/com/chethan616/clearpdf/ocr/MlKitOcrEngine.kt
similarity index 95%
rename from ocr-core/src/main/java/com/kyant/ocrcore/MlKitOcrEngine.kt
rename to app/src/gms/java/com/chethan616/clearpdf/ocr/MlKitOcrEngine.kt
index 011d248..bfa598e 100644
--- a/ocr-core/src/main/java/com/kyant/ocrcore/MlKitOcrEngine.kt
+++ b/app/src/gms/java/com/chethan616/clearpdf/ocr/MlKitOcrEngine.kt
@@ -1,4 +1,7 @@
-package com.kyant.ocrcore
+package com.chethan616.clearpdf.ocr
+
+import com.kyant.ocrcore.OcrPageResult
+import com.kyant.ocrcore.OcrWord
import android.graphics.Bitmap
import com.google.mlkit.vision.common.InputImage
diff --git a/app/src/gms/java/com/chethan616/clearpdf/ocr/OcrFlavor.kt b/app/src/gms/java/com/chethan616/clearpdf/ocr/OcrFlavor.kt
new file mode 100644
index 0000000..27eb932
--- /dev/null
+++ b/app/src/gms/java/com/chethan616/clearpdf/ocr/OcrFlavor.kt
@@ -0,0 +1,9 @@
+package com.chethan616.clearpdf.ocr
+
+import android.graphics.Bitmap
+import com.kyant.ocrcore.OcrPageResult
+
+/** play / foss builds: the bundled ML Kit recognizer first, Tesseract as the fallback. */
+internal object OcrFlavor {
+ val primaryEngine: (suspend (Bitmap) -> OcrPageResult)? = { MlKitOcrEngine.recognize(it) }
+}
diff --git a/app/src/gms/java/com/chethan616/clearpdf/scan/DocumentScanner.kt b/app/src/gms/java/com/chethan616/clearpdf/scan/DocumentScanner.kt
new file mode 100644
index 0000000..1437239
--- /dev/null
+++ b/app/src/gms/java/com/chethan616/clearpdf/scan/DocumentScanner.kt
@@ -0,0 +1,59 @@
+package com.chethan616.clearpdf.scan
+
+import android.app.Activity
+import android.content.Context
+import android.content.ContextWrapper
+import android.net.Uri
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.IntentSenderRequest
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.rememberUpdatedState
+import androidx.compose.ui.platform.LocalContext
+import com.google.mlkit.vision.documentscanner.GmsDocumentScannerOptions
+import com.google.mlkit.vision.documentscanner.GmsDocumentScanning
+import com.google.mlkit.vision.documentscanner.GmsDocumentScanningResult
+
+/**
+ * play / foss builds: Google's document scanner (edge detection, perspective fix, multi-page).
+ * Returns the function that starts a scan; [onPages] gets the scanned page images, [onFinished]
+ * runs once the scanner closes (scanned or not), [onError] if it couldn't start.
+ */
+@Composable
+internal fun rememberDocumentScanner(
+ onPages: (List<Uri>) -> Unit,
+ onFinished: () -> Unit,
+ onError: () -> Unit
+): () -> Unit {
+ val context = LocalContext.current
+ val pages by rememberUpdatedState(onPages)
+ val finished by rememberUpdatedState(onFinished)
+ val error by rememberUpdatedState(onError)
+ val launcher = rememberLauncherForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
+ if (result.resultCode == Activity.RESULT_OK) {
+ val uris = GmsDocumentScanningResult.fromActivityResultIntent(result.data)?.pages?.mapNotNull { it.imageUri }.orEmpty()
+ if (uris.isNotEmpty()) pages(uris)
+ }
+ finished()
+ }
+ return start@{
+ val activity = context.findActivity() ?: run { error(); finished(); return@start }
+ val options = GmsDocumentScannerOptions.Builder()
+ .setGalleryImportAllowed(true)
+ .setPageLimit(100)
+ .setResultFormats(GmsDocumentScannerOptions.RESULT_FORMAT_JPEG)
+ .setScannerMode(GmsDocumentScannerOptions.SCANNER_MODE_FULL)
+ .build()
+ GmsDocumentScanning.getClient(options)
+ .getStartScanIntent(activity)
+ .addOnSuccessListener { launcher.launch(IntentSenderRequest.Builder(it).build()) }
+ .addOnFailureListener { error(); finished() }
+ }
+}
+
+private tailrec fun Context.findActivity(): Activity? = when (this) {
+ is Activity -> this
+ is ContextWrapper -> baseContext.findActivity()
+ else -> null
+}
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index df798ee..43f2c8f 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -39,6 +39,17 @@
android:theme="@style/Theme.ClearPDF"
android:localeConfig="@xml/locales_config"
tools:targetApi="33">
+ <!-- A document opened from another app gets its own window (task + Recents entry);
+ MainActivity forwards every VIEW / SEND here. -->
+ <activity
+ android:name=".DocumentActivity"
+ android:exported="false"
+ android:documentLaunchMode="intoExisting"
+ android:autoRemoveFromRecents="true"
+ android:hardwareAccelerated="true"
+ android:windowSoftInputMode="adjustResize"
+ android:configChanges="orientation|screenSize|screenLayout|keyboardHidden" />
+
<activity
android:name=".MainActivity"
android:exported="true"
diff --git a/app/src/main/java/com/chethan616/clearpdf/DocumentActivity.kt b/app/src/main/java/com/chethan616/clearpdf/DocumentActivity.kt
new file mode 100644
index 0000000..7161d45
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/DocumentActivity.kt
@@ -0,0 +1,11 @@
+package com.chethan616.clearpdf
+
+/**
+ * A document opened from another app, in its own window: its own task and Recents entry (named
+ * after the file), separate from the app's main window and from the app that opened it. Started by
+ * [MainActivity] for every VIEW / SEND; leaving the document closes the window and returns to
+ * whatever opened it (#29).
+ */
+class DocumentActivity : MainActivity() {
+ override val isDocumentWindow: Boolean = true
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt b/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt
index c74be0e..c62f6cb 100644
--- a/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt
@@ -14,7 +14,10 @@ import androidx.compose.ui.graphics.Color
import androidx.core.view.WindowCompat
import com.chethan616.clearpdf.ui.DocsApp
-class MainActivity : ComponentActivity() {
+open class MainActivity : ComponentActivity() {
+
+ /** True for [DocumentActivity]: a document opened from another app, in its own window. */
+ protected open val isDocumentWindow: Boolean = false
override fun attachBaseContext(newBase: android.content.Context) {
val savedLang = com.chethan616.clearpdf.data.repository.OnboardingManager.getSelectedLocale(newBase)
@@ -28,6 +31,22 @@ class MainActivity : ComponentActivity() {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
+
+ // A file opened from another app (a file manager, a chat) gets its own window, like a
+ // document in any desktop-class app (#29), instead of running inside the caller's task.
+ // The launcher entry and shortcuts stay here.
+ if (!isDocumentWindow && savedInstanceState == null && isExternalDocument(intent)) {
+ runCatching {
+ startActivity(
+ Intent(intent)
+ .setClass(this, DocumentActivity::class.java)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ )
+ finish()
+ @Suppress("DEPRECATION") overridePendingTransition(0, 0)
+ return
+ }
+ }
WindowCompat.setDecorFitsSystemWindows(window, false)
// Belt-and-suspenders against the translucent scrim Android can draw behind the nav bar
// (API 29-34; reported as a "grey band" around it on some OEM skins/Android versions even
@@ -77,8 +96,28 @@ class MainActivity : ComponentActivity() {
}
} else shortcutRoute
+ if (isDocumentWindow && incomingPdfUri != null) {
+ // Recents shows the document's name for its window.
+ val label = queryDisplayName(incomingPdfUri)
+ if (label != null) runCatching {
+ @Suppress("DEPRECATION")
+ setTaskDescription(android.app.ActivityManager.TaskDescription(label))
+ }
+ }
+
setContent {
- DocsApp(shortcutRoute = effectiveRoute, incomingPdfUri = incomingPdfUri)
+ DocsApp(shortcutRoute = effectiveRoute, incomingPdfUri = incomingPdfUri, documentWindow = isDocumentWindow)
+ }
+ }
+
+ /** A VIEW / SEND of a file (not our own `clearpdf://` shortcuts). */
+ private fun isExternalDocument(intent: Intent?): Boolean {
+ intent ?: return false
+ return when (intent.action) {
+ Intent.ACTION_VIEW -> intent.data?.scheme.let { it == "content" || it == "file" } &&
+ isSupportedDocumentIntent(intent.type, intent.data.toString())
+ Intent.ACTION_SEND -> true
+ else -> false
}
}
diff --git a/app/src/main/java/com/chethan616/clearpdf/data/repository/PdfServiceLocator.kt b/app/src/main/java/com/chethan616/clearpdf/data/repository/PdfServiceLocator.kt
index 373e363..1c92b25 100644
--- a/app/src/main/java/com/chethan616/clearpdf/data/repository/PdfServiceLocator.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/data/repository/PdfServiceLocator.kt
@@ -29,5 +29,5 @@ object PdfServiceLocator {
val pdfConverter: PdfConverter by lazy { PdfConverterImpl() }
val pdfTextService: PdfTextService by lazy { PdfTextServiceImpl() }
/** Fully on-device OCR — ML Kit primary, Tesseract4Android fallback. No network access. */
- val ocrService: OcrService by lazy { OcrServiceImpl() }
+ val ocrService: OcrService by lazy { OcrServiceImpl(com.chethan616.clearpdf.ocr.OcrFlavor.primaryEngine) }
}
diff --git a/app/src/main/java/com/chethan616/clearpdf/domain/usecase/OpenPdfUseCase.kt b/app/src/main/java/com/chethan616/clearpdf/domain/usecase/OpenPdfUseCase.kt
index 440c5c2..594fd40 100644
--- a/app/src/main/java/com/chethan616/clearpdf/domain/usecase/OpenPdfUseCase.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/domain/usecase/OpenPdfUseCase.kt
@@ -13,6 +13,9 @@ class OpenPdfUseCase(private val viewer: PdfViewer) {
fun renderPage(document: PdfDocument, pageIndex: Int, width: Int, rotationDegrees: Int = 0): Bitmap? =
viewer.renderPage(document, pageIndex, width, rotationDegrees)
+ fun renderRegion(document: PdfDocument, pageIndex: Int, region: android.graphics.RectF, pageWidthPx: Float, outWidth: Int, outHeight: Int): Bitmap? =
+ viewer.renderRegion(document, pageIndex, region, pageWidthPx, outWidth, outHeight)
+
fun pageSize(document: PdfDocument, pageIndex: Int): Size? = viewer.pageSize(document, pageIndex)
fun close(document: PdfDocument) = viewer.close(document)
diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/BackgroundRemover.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/BackgroundRemover.kt
index f6be5b7..57e9040 100644
--- a/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/BackgroundRemover.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/engine/BackgroundRemover.kt
@@ -2,12 +2,6 @@ package com.chethan616.clearpdf.imageeditor.engine
import android.content.Context
import android.graphics.Bitmap
-import android.os.Build
-import com.google.mlkit.vision.common.InputImage
-import com.google.mlkit.vision.segmentation.subject.SubjectSegmentation
-import com.google.mlkit.vision.segmentation.subject.SubjectSegmenterOptions
-import kotlinx.coroutines.suspendCancellableCoroutine
-import kotlin.coroutines.resume
/**
* Produces a subject mask for automatic background removal. Kept behind an interface so a FOSS
@@ -24,60 +18,6 @@ interface BackgroundRemover {
suspend fun segment(image: Bitmap): Result<Bitmap>
companion object {
- fun create(context: Context): BackgroundRemover = MlKitBackgroundRemover(context.applicationContext)
- }
-}
-
-/** Google Play services ML Kit subject segmentation (model is fetched by Play services). */
-private class MlKitBackgroundRemover(private val context: Context) : BackgroundRemover {
-
- override val isAvailable: Boolean
- get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && hasPlayServices()
-
- private fun hasPlayServices(): Boolean = runCatching {
- context.packageManager.getPackageInfo("com.google.android.gms", 0); true
- }.getOrDefault(false)
-
- override suspend fun segment(image: Bitmap): Result<Bitmap> {
- if (!isAvailable) return Result.failure(IllegalStateException("Background removal isn't available on this device."))
- return runCatching { segmentImpl(image) }
- }
-
- private suspend fun segmentImpl(image: Bitmap): Bitmap {
- val options = SubjectSegmenterOptions.Builder()
- .enableForegroundConfidenceMask()
- .build()
- val client = SubjectSegmentation.getClient(options)
- try {
- val input = InputImage.fromBitmap(image, 0)
- val result = suspendCancellableCoroutine { cont ->
- client.process(input)
- .addOnSuccessListener { cont.resume(Result.success(it)) }
- .addOnFailureListener { cont.resume(Result.failure(it)) }
- }.getOrElse { e ->
- val msg = e.message.orEmpty()
- throw IllegalStateException(
- if (msg.contains("download", true) || msg.contains("module", true))
- "The background-removal model is still downloading. Try again in a moment."
- else "Couldn't detect a subject in this image."
- )
- }
- val buffer = result.foregroundConfidenceMask
- ?: throw IllegalStateException("Couldn't detect a subject in this image.")
- val w = image.width
- val h = image.height
- buffer.rewind()
- val pixels = IntArray(w * h)
- for (i in 0 until w * h) {
- val c = buffer.get().coerceIn(0f, 1f)
- pixels[i] = ((c * 255f).toInt() shl 24)
- }
- val argb = Bitmap.createBitmap(pixels, w, h, Bitmap.Config.ARGB_8888)
- val mask = argb.extractAlpha()
- argb.recycle()
- return mask
- } finally {
- client.close()
- }
+ fun create(context: Context): BackgroundRemover = BackgroundRemoverFlavor.create(context.applicationContext)
}
}
diff --git a/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngine.kt b/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngine.kt
index 614f051..90ebca9 100644
--- a/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngine.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngine.kt
@@ -35,7 +35,7 @@ object OfficeEngine {
installerInstance ?: OfficeEngineFlavor.createInstaller(context.applicationContext).also { installerInstance = it }
}
- fun isSupported(): Boolean = OfficeEngineManifest.bundleForDevice() != null
+ fun isSupported(): Boolean = OfficeEngineFlavor.available && OfficeEngineManifest.bundleForDevice() != null
fun isOfficeFile(fileName: String): Boolean =
fileName.substringAfterLast('.', "").lowercase() in OFFICE_EXTENSIONS
diff --git a/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineClient.kt b/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineClient.kt
index 0b9153d..e38ff9a 100644
--- a/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineClient.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/office/OfficeEngineClient.kt
@@ -83,7 +83,10 @@ object OfficeEngineClient {
}
}
} ?: return Result(null, "Cannot open file")
- digest.update("$ext|${OfficeEngineStore.installedVersion(app)}|fonts2".toByteArray())
+ // LibreOffice drops what orphan placeholders inherit from the master (#29): make it
+ // explicit first. Part of the cache key, so decks converted before the fix re-render.
+ if (ext == "pptx") runCatching { PptxPlaceholderFix.apply(input) }
+ digest.update("$ext|${OfficeEngineStore.installedVersion(app)}|fonts2|ph1".toByteArray())
val key = digest.digest().joinToString("") { "%02x".format(it) }.take(40)
// Password-protected output is never cached: the PDF is unencrypted.
val cached = File(cacheDir, "$key.pdf")
diff --git a/app/src/main/java/com/chethan616/clearpdf/office/PptxPlaceholderFix.kt b/app/src/main/java/com/chethan616/clearpdf/office/PptxPlaceholderFix.kt
new file mode 100644
index 0000000..78e7871
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/office/PptxPlaceholderFix.kt
@@ -0,0 +1,207 @@
+package com.chethan616.clearpdf.office
+
+import org.w3c.dom.Document
+import org.w3c.dom.Element
+import java.io.ByteArrayOutputStream
+import java.io.File
+import java.util.zip.ZipEntry
+import java.util.zip.ZipFile
+import java.util.zip.ZipOutputStream
+import javax.xml.parsers.DocumentBuilderFactory
+import javax.xml.transform.OutputKeys
+import javax.xml.transform.TransformerFactory
+import javax.xml.transform.dom.DOMSource
+import javax.xml.transform.stream.StreamResult
+
+/**
+ * Makes inherited text formatting explicit on "orphan" placeholders before a deck is handed to
+ * LibreOffice (#29).
+ *
+ * A slide placeholder normally inherits its text-box behaviour from the matching placeholder on
+ * its layout, and from the master behind that. Decks that were pasted between templates often keep
+ * placeholders the layout no longer has (a title on a Blank layout, typically with
+ * `idx="4294967295"`). PowerPoint and OnlyOffice then inherit from the master by type; LibreOffice
+ * doesn't, so such a title loses the master's vertical centring and title style. When its box
+ * starts above the slide, the title is drawn pinned to that top edge and cut off.
+ *
+ * For each orphan, this copies onto the slide what PowerPoint would inherit from the master:
+ * - missing body properties (anchor, insets, wrap…);
+ * - list-style levels (size, caps, colour, font) the slide doesn't set itself;
+ * - the box, when the slide has none.
+ * Everything the slide does say still wins, so the rendered result matches PowerPoint.
+ */
+internal object PptxPlaceholderFix {
+
+ private const val P = "http://schemas.openxmlformats.org/presentationml/2006/main"
+ private const val A = "http://schemas.openxmlformats.org/drawingml/2006/main"
+ private const val R = "http://schemas.openxmlformats.org/package/2006/relationships"
+ private const val NoIndex = "4294967295"
+
+ /** Rewrites [file] in place when it has orphan placeholders; returns whether it changed. */
+ fun apply(file: File): Boolean {
+ val patched = runCatching { patch(file) }.getOrNull() ?: return false
+ if (patched.isEmpty()) return false
+ val tmp = File(file.parentFile, file.name + ".fix")
+ return runCatching {
+ ZipFile(file).use { zip ->
+ ZipOutputStream(tmp.outputStream().buffered()).use { out ->
+ for (entry in zip.entries()) {
+ out.putNextEntry(ZipEntry(entry.name))
+ val replacement = patched[entry.name]
+ if (replacement != null) out.write(replacement)
+ else zip.getInputStream(entry).use { it.copyTo(out) }
+ out.closeEntry()
+ }
+ }
+ }
+ file.delete() && tmp.renameTo(file)
+ }.getOrElse { tmp.delete(); false }
+ }
+
+ /** Slide part path → rewritten XML, for the slides that needed it. */
+ private fun patch(file: File): Map<String, ByteArray> = ZipFile(file).use { zip ->
+ fun read(path: String): ByteArray? = zip.getEntry(path)?.let { e -> zip.getInputStream(e).use { it.readBytes() } }
+ val docs = HashMap<String, Document?>()
+ fun dom(path: String): Document? = docs.getOrPut(path) { read(path)?.let { parse(it) } }
+ fun relTargets(path: String): List<String> {
+ val dir = path.substringBeforeLast('/', "")
+ val rels = dom("$dir/_rels/${path.substringAfterLast('/')}.rels") ?: return emptyList()
+ return rels.getElementsByTagNameNS(R, "Relationship").elements().mapNotNull { it.getAttribute("Target").takeIf { t -> t.isNotEmpty() } }
+ .map { resolve(dir, it) }
+ }
+
+ val out = HashMap<String, ByteArray>()
+ val slides = zip.entries().toList().map { it.name }
+ .filter { it.startsWith("ppt/slides/slide") && it.endsWith(".xml") }
+ for (slidePath in slides) {
+ val layoutPath = relTargets(slidePath).firstOrNull { it.startsWith("ppt/slideLayouts/") } ?: continue
+ val masterPath = relTargets(layoutPath).firstOrNull { it.startsWith("ppt/slideMasters/") } ?: continue
+ val slide = dom(slidePath) ?: continue
+ val layout = dom(layoutPath) ?: continue
+ val master = dom(masterPath) ?: continue
+ var changed = false
+ for (sp in slide.getElementsByTagNameNS(P, "sp").elements()) {
+ val ph = sp.firstDescendant(P, "ph") ?: continue
+ val type = ph.getAttribute("type").ifEmpty { "obj" }
+ val idx = ph.getAttribute("idx").takeIf { it.isNotEmpty() && it != NoIndex }
+ if (findPlaceholder(layout, type, idx, byTypeOnly = false) != null) continue
+ val masterType = when (type) {
+ "title", "ctrTitle" -> "title"
+ "body", "obj", "subTitle" -> "body"
+ else -> type
+ }
+ val masterSp = findPlaceholder(master, masterType, null, byTypeOnly = true) ?: continue
+ if (inherit(slide, sp, masterSp, master, masterType)) changed = true
+ }
+ if (changed) out[slidePath] = serialize(slide)
+ }
+ out
+ }
+
+ /** The placeholder shape on a layout / master that [type] / [idx] refers to. */
+ private fun findPlaceholder(part: Document, type: String, idx: String?, byTypeOnly: Boolean): Element? {
+ val shapes = part.getElementsByTagNameNS(P, "sp").elements()
+ fun phOf(sp: Element) = sp.firstDescendant(P, "ph")
+ if (!byTypeOnly && idx != null) {
+ shapes.firstOrNull { phOf(it)?.getAttribute("idx") == idx }?.let { return it }
+ }
+ val wanted = if (type == "ctrTitle") setOf("ctrTitle", "title") else if (type == "title") setOf("title", "ctrTitle") else setOf(type)
+ return shapes.firstOrNull { sp ->
+ val ph = phOf(sp) ?: return@firstOrNull false
+ ph.getAttribute("type").ifEmpty { "obj" } in wanted && (byTypeOnly || idx == null)
+ }
+ }
+
+ private fun inherit(slide: Document, sp: Element, masterSp: Element, master: Document, masterType: String): Boolean {
+ var changed = false
+ val txBody = sp.firstChild(P, "txBody") ?: return false
+ val masterBody = masterSp.firstChild(P, "txBody")
+
+ // Body properties: anchor, insets, wrap… whatever the slide leaves unsaid.
+ val bodyPr = txBody.firstChild(A, "bodyPr") ?: slide.createElementNS(A, "a:bodyPr").also {
+ txBody.insertBefore(it, txBody.firstChild)
+ }
+ masterBody?.firstChild(A, "bodyPr")?.let { mb ->
+ val attrs = mb.attributes
+ for (i in 0 until attrs.length) {
+ val a = attrs.item(i)
+ if (a.nodeName.startsWith("xmlns")) continue
+ if (!bodyPr.hasAttribute(a.nodeName)) { bodyPr.setAttribute(a.nodeName, a.nodeValue); changed = true }
+ }
+ }
+
+ // List-style levels: the master placeholder's own, else the master's title/body/other style.
+ val txStyles = master.getElementsByTagNameNS(P, "txStyles").elements().firstOrNull()
+ val styleName = when (masterType) { "title" -> "titleStyle"; "body" -> "bodyStyle"; else -> "otherStyle" }
+ val base = txStyles?.firstChild(P, styleName)
+ val masterLst = masterBody?.firstChild(A, "lstStyle")
+ val lst = txBody.firstChild(A, "lstStyle") ?: slide.createElementNS(A, "a:lstStyle").also {
+ txBody.insertBefore(it, bodyPr.nextSibling)
+ }
+ for (level in 1..9) {
+ val name = "lvl${level}pPr"
+ if (lst.firstChild(A, name) != null) continue
+ val source = masterLst?.firstChild(A, name) ?: base?.firstChild(A, name) ?: continue
+ val copy = slide.importNode(source, true) as Element
+ // Keep level order: insert before the first higher level (or the extLst).
+ val after = lst.childElements().firstOrNull { el ->
+ val n = el.localName ?: ""
+ n == "extLst" || (n.startsWith("lvl") && (n.removePrefix("lvl").removeSuffix("pPr").toIntOrNull() ?: 0) > level)
+ }
+ lst.insertBefore(copy, after)
+ changed = true
+ }
+
+ // A placeholder with no box of its own sits where the master puts it.
+ val spPr = sp.firstChild(P, "spPr")
+ if (spPr != null && spPr.firstChild(A, "xfrm") == null) {
+ masterSp.firstChild(P, "spPr")?.firstChild(A, "xfrm")?.let {
+ spPr.insertBefore(slide.importNode(it, true), spPr.firstChild)
+ changed = true
+ }
+ }
+ return changed
+ }
+
+ // ── DOM helpers ─────────────────────────────────────────────────────────────
+
+ private fun parse(bytes: ByteArray): Document? = runCatching {
+ DocumentBuilderFactory.newInstance().apply { isNamespaceAware = true }
+ .newDocumentBuilder().parse(bytes.inputStream())
+ }.getOrNull()
+
+ private fun serialize(doc: Document): ByteArray {
+ val out = ByteArrayOutputStream()
+ TransformerFactory.newInstance().newTransformer().apply {
+ setOutputProperty(OutputKeys.ENCODING, "UTF-8")
+ setOutputProperty(OutputKeys.STANDALONE, "yes")
+ }.transform(DOMSource(doc), StreamResult(out))
+ return out.toByteArray()
+ }
+
+ private fun resolve(baseDir: String, target: String): String {
+ if (target.startsWith("/")) return target.removePrefix("/")
+ val stack = ArrayDeque(baseDir.split('/').filter { it.isNotEmpty() })
+ for (segment in target.split('/')) when (segment) {
+ "", "." -> Unit
+ ".." -> stack.removeLastOrNull()
+ else -> stack.addLast(segment)
+ }
+ return stack.joinToString("/")
+ }
+
+ private fun org.w3c.dom.NodeList.elements(): List<Element> =
+ (0 until length).mapNotNull { item(it) as? Element }
+
+ private fun Element.childElements(): List<Element> =
+ (0 until childNodes.length).mapNotNull { childNodes.item(it) as? Element }
+
+ private fun Element.firstChild(ns: String, local: String): Element? =
+ childElements().firstOrNull { it.namespaceURI == ns && it.localName == local }
+
+ private fun Element.firstDescendant(ns: String, local: String): Element? {
+ val list = getElementsByTagNameNS(ns, local)
+ return if (list.length > 0) list.item(0) as? Element else null
+ }
+
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/DocsApp.kt b/app/src/main/java/com/chethan616/clearpdf/ui/DocsApp.kt
index 6a429c6..196103d 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/DocsApp.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/DocsApp.kt
@@ -89,7 +89,7 @@ private tailrec fun android.content.Context.findActivity(): android.app.Activity
* Provides the wallpaper backdrop, floating bottom tabs, and navigation host.
*/
@Composable
-fun DocsApp(shortcutRoute: String? = null, incomingPdfUri: android.net.Uri? = null) {
+fun DocsApp(shortcutRoute: String? = null, incomingPdfUri: android.net.Uri? = null, documentWindow: Boolean = false) {
val context = LocalContext.current
var selectedLocale by rememberSaveable { mutableStateOf<String>(OnboardingManager.getSelectedLocale(context)) }
val localizedContext = remember(context, selectedLocale) {
@@ -209,6 +209,20 @@ fun DocsApp(shortcutRoute: String? = null, incomingPdfUri: android.net.Uri? = nu
) {
val backdrop = rememberLayerBackdrop()
val navController = rememberNavController()
+ // A document window (#29) closes once its document does: back from the viewer lands on
+ // Home, and instead of showing Home inside the document's window we close the window,
+ // returning to the app that opened the file.
+ if (documentWindow) {
+ val activity = LocalContext.current as? android.app.Activity
+ LaunchedEffect(navController) {
+ var shownDocument = false
+ navController.currentBackStackEntryFlow.collect { entry ->
+ val route = entry.destination.route
+ if (route != null && route != "home") shownDocument = true
+ else if (route == "home" && shownDocument) activity?.finishAndRemoveTask()
+ }
+ }
+ }
val backToLibrary: () -> Unit = remember(navController) {
{
if (!navController.popBackStack("home", inclusive = false)) {
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/CreatePdfScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/CreatePdfScreen.kt
index 7338b3b..abb6006 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/CreatePdfScreen.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/CreatePdfScreen.kt
@@ -76,11 +76,6 @@ import com.chethan616.clearpdf.ui.theme.LocalIsDarkMode
import com.chethan616.clearpdf.ui.utils.rememberUISensor
import com.chethan616.clearpdf.ui.viewmodel.CreateMode
import com.chethan616.clearpdf.ui.viewmodel.CreatePdfViewModel
-import com.google.mlkit.vision.documentscanner.GmsDocumentScannerOptions
-import com.google.mlkit.vision.documentscanner.GmsDocumentScannerOptions.RESULT_FORMAT_JPEG
-import com.google.mlkit.vision.documentscanner.GmsDocumentScannerOptions.SCANNER_MODE_FULL
-import com.google.mlkit.vision.documentscanner.GmsDocumentScanning
-import com.google.mlkit.vision.documentscanner.GmsDocumentScanningResult
import com.kyant.backdrop.backdrops.LayerBackdrop
import kotlinx.coroutines.delay
@@ -114,40 +109,16 @@ fun CreatePdfScreen(
}
}
- val scannerLauncher = rememberLauncherForActivityResult(
- contract = ActivityResultContracts.StartIntentSenderForResult()
- ) { result ->
- if (result.resultCode == Activity.RESULT_OK) {
- val scanResult = GmsDocumentScanningResult.fromActivityResultIntent(result.data)
- val uris = scanResult?.pages?.mapNotNull { it.imageUri }.orEmpty()
- if (uris.isNotEmpty()) {
- viewModel.onModeSelected(CreateMode.FROM_IMAGES)
- viewModel.onImagesSelected(uris)
- }
- }
- }
-
- fun launchScanner() {
- if (activity == null) {
- viewModel.setError(context.getString(R.string.scanner_unavailable))
- return
- }
- val options = GmsDocumentScannerOptions.Builder()
- .setGalleryImportAllowed(true)
- .setPageLimit(100)
- .setResultFormats(RESULT_FORMAT_JPEG)
- .setScannerMode(SCANNER_MODE_FULL)
- .build()
+ val startScanner = com.chethan616.clearpdf.scan.rememberDocumentScanner(
+ onPages = { uris ->
+ viewModel.onModeSelected(CreateMode.FROM_IMAGES)
+ viewModel.onImagesSelected(uris)
+ },
+ onFinished = {},
+ onError = { viewModel.setError(context.getString(R.string.scanner_start_failed)) }
+ )
- GmsDocumentScanning.getClient(options)
- .getStartScanIntent(activity)
- .addOnSuccessListener { intentSender ->
- scannerLauncher.launch(IntentSenderRequest.Builder(intentSender).build())
- }
- .addOnFailureListener { error ->
- viewModel.setError(context.getString(R.string.scanner_start_failed))
- }
- }
+ fun launchScanner() = startScanner()
LaunchedEffect(state.resultMessage, state.errorMessage) {
if (!state.resultMessage.isNullOrBlank() || !state.errorMessage.isNullOrBlank()) {
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 a50c5a2..6c12085 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
@@ -128,6 +128,8 @@ internal fun PdfContinuousPage(
marks: MutableList<PdfMarkup>,
/** Exact renders of this page's in-place text edits, by markup id (see PdfTextEditPreview). */
textEditPatches: Map<Long, TextEditPatch> = emptyMap(),
+ /** While zoomed in: the visible part of this page at screen resolution, drawn over the bitmap. */
+ detailTile: PageDetailTile? = null,
/**
* The PDF's own fillable boxes on this page (#68) and the values filled so far, by field name.
* In Edit mode ([formEditing]) the boxes are outlined and a tap fills them in place.
@@ -136,7 +138,8 @@ internal fun PdfContinuousPage(
formValues: Map<String, String> = emptyMap(),
formEditing: Boolean = false,
focusedFormKey: String? = null,
- onTapFormWidget: (com.kyant.pdfcore.form.PdfFormWidget) -> Unit = {},
+ /** A field was tapped; the rect is its box in window coordinates (for a dropdown's menu). */
+ onTapFormWidget: (com.kyant.pdfcore.form.PdfFormWidget, Rect) -> Unit = { _, _ -> },
onFormTextChange: (com.kyant.pdfcore.form.PdfFormWidget, String) -> Unit = { _, _ -> },
onFormImeNext: (com.kyant.pdfcore.form.PdfFormWidget) -> Unit = {},
ocrBlocks: List<OcrTextBlock>,
@@ -184,8 +187,13 @@ internal fun PdfContinuousPage(
val latestSelectedMarkupIndices by rememberUpdatedState(selectedMarkupIndices)
val latestOcrBlocks by rememberUpdatedState(ocrBlocks)
val latestFormWidgets by rememberUpdatedState(formWidgets)
- val latestFormEditing by rememberUpdatedState(formEditing)
+ val latestFormValues by rememberUpdatedState(formValues)
val latestOnTapFormWidget by rememberUpdatedState(onTapFormWidget)
+ val latestOnFormValue by rememberUpdatedState(onFormTextChange)
+ // List boxes scroll inside their own box; offsets in rows, per field box.
+ val formListScroll = remember { androidx.compose.runtime.mutableStateMapOf<String, Float>() }
+ // This page's coordinates, to place a dropdown's menu under the field in window space.
+ val pageLayout = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
DisposableEffect(page, textSelection) { onDispose { textSelection.unregisterPage(page, null) } }
// Accessibility: expose the page's extracted text to TalkBack, plus a "select page text" action.
val selectPageLabel = stringResource(R.string.selection_select_page_text)
@@ -231,7 +239,7 @@ internal fun PdfContinuousPage(
.then(if (bitmap == null) Modifier.aspectRatio(placeholderAspect ?: (1f / 1.414f)) else Modifier)
.background(Color(0xFF15181E))
// Page-local coordinates for the text selection's screen mapping (see PdfViewportTransform).
- .onGloballyPositioned { textSelection.registerPage(page, it) }
+ .onGloballyPositioned { textSelection.registerPage(page, it); pageLayout[0] = it }
.then(pageTextSemantics)
.onSizeChanged { sz ->
pageCanvasSizes[page] = Size(sz.width.toFloat(), sz.height.toFloat())
@@ -271,6 +279,25 @@ internal fun PdfContinuousPage(
Canvas(Modifier.matchParentSize()) {
val frame = Rect(0f, 0f, size.width, size.height)
+ // Sharp zoom: the visible part of the page at screen resolution, over the page bitmap.
+ detailTile?.takeIf { !it.bitmap.isRecycled }?.let { tile ->
+ val g = tile.region
+ val left = (g.left * size.width).roundToInt()
+ val top = (g.top * size.height).roundToInt()
+ drawImage(
+ image = tile.bitmap.asImageBitmap(),
+ srcOffset = IntOffset.Zero,
+ srcSize = androidx.compose.ui.unit.IntSize(tile.bitmap.width, tile.bitmap.height),
+ dstOffset = IntOffset(left, top),
+ dstSize = androidx.compose.ui.unit.IntSize(
+ ((g.right * size.width).roundToInt() - left).coerceAtLeast(1),
+ ((g.bottom * size.height).roundToInt() - top).coerceAtLeast(1)
+ ),
+ filterQuality = androidx.compose.ui.graphics.FilterQuality.High,
+ colorFilter = if (darkPageAppearance) InvertColorFilter else null
+ )
+ }
+
// Edited lines first, so highlights and other markups still draw on top: the band of
// the page around each edit, rendered from the edited PDF itself.
marks.forEach { m ->
@@ -294,7 +321,7 @@ internal fun PdfContinuousPage(
}
// The PDF's own form boxes: filled values in place, and the Edit-mode outline.
- if (formWidgets.isNotEmpty()) drawFormWidgets(formWidgets, formValues, formEditing, focusedFormKey, darkPageAppearance)
+ if (formWidgets.isNotEmpty()) drawFormWidgets(formWidgets, formValues, formEditing, focusedFormKey, darkPageAppearance, formListScroll)
// Text selection highlight — the platform selection colour, one band per line fragment.
// Drawn inside the zoom layer so it scales with the page, exactly like the glyphs.
@@ -552,8 +579,9 @@ internal fun PdfContinuousPage(
val selBounds = sel?.movableBounds()
if (selBounds != null && selBounds.inflate(30f).contains(down.position)) return@awaitEachGesture
- // Edit mode: a tap on one of the PDF's own form boxes fills it (#68).
- if (latestFormEditing && latestFormWidgets.isNotEmpty()) {
+ // The PDF's own form fields fill right where they are printed (#68): a tap
+ // types / ticks / opens the dropdown; a list box scrolls and picks in place.
+ if (latestFormWidgets.isNotEmpty()) {
val nx = down.position.x / size.width.toFloat()
val ny = down.position.y / size.height.toFloat()
val slop = 6f / size.width.toFloat()
@@ -561,10 +589,41 @@ internal fun PdfContinuousPage(
!w.readOnly && nx >= w.left - slop && nx <= w.right + slop && ny >= w.top - slop && ny <= w.bottom + slop
}
if (box != null) {
+ val sz = Size(size.width.toFloat(), size.height.toFloat())
+ if (box.type == com.kyant.pdfcore.form.PdfFormWidget.Type.LIST) {
+ val current = latestFormValues[box.fieldName] ?: box.value
+ val start = formListScroll[box.key] ?: box.listInitialScroll(sz, current)
+ val rowH = box.listRowPx(sz)
+ val maxScroll = (box.options.size - box.listVisibleRows(sz)).coerceAtLeast(0).toFloat()
+ var dragged = false
+ while (true) {
+ val ev = awaitPointerEvent()
+ val ch = ev.changes.firstOrNull { it.id == down.id } ?: break
+ val dy = ch.position.y - down.position.y
+ if (!dragged && kotlin.math.abs(dy) > viewConfiguration.touchSlop) dragged = true
+ if (dragged) {
+ formListScroll[box.key] = (start - dy / rowH).coerceIn(0f, maxScroll)
+ ch.consume()
+ }
+ if (!ch.pressed) {
+ if (!dragged) {
+ ch.consume()
+ val i = box.listIndexAt(sz, down.position.y, start)
+ if (i >= 0) latestOnFormValue(box, box.optionValues.getOrElse(i) { box.options[i] })
+ }
+ break
+ }
+ }
+ onInteraction()
+ return@awaitEachGesture
+ }
val up = waitForUpOrCancellation()
if (up != null) {
up.consume()
- latestOnTapFormWidget(box)
+ val r = box.rectIn(sz)
+ val lc = pageLayout[0]?.takeIf { it.isAttached }
+ val windowRect = if (lc != null) Rect(lc.localToWindow(r.topLeft), lc.localToWindow(r.bottomRight)) else r
+ latestOnTapFormWidget(box, windowRect)
onShowControls()
onInteraction()
}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfFormFill.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfFormFill.kt
index d8af612..7db000d 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfFormFill.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfFormFill.kt
@@ -1,24 +1,34 @@
package com.chethan616.clearpdf.ui.screen
-import androidx.compose.foundation.background
-import androidx.compose.foundation.border
-import androidx.compose.foundation.horizontalScroll
+import androidx.activity.compose.BackHandler
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.EnterExitState
+import androidx.compose.animation.core.animateFloat
+import androidx.compose.animation.core.tween
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.foundation.gestures.awaitEachGesture
+import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.heightIn
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.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.rounded.Check
import androidx.compose.material.icons.rounded.KeyboardArrowDown
import androidx.compose.material.icons.rounded.KeyboardArrowUp
import androidx.compose.material3.Icon
@@ -36,18 +46,24 @@ import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
+import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.CompositingStrategy
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeJoin
+import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.clipRect
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
+import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.graphics.toArgb
+import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
@@ -61,16 +77,24 @@ import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.chethan616.clearpdf.R
+import com.chethan616.clearpdf.ui.components.GlassMotion
+import com.chethan616.clearpdf.ui.components.GlassOverlay
import com.chethan616.clearpdf.ui.components.LiquidButton
import com.chethan616.clearpdf.ui.components.LiquidIconButton
+import com.chethan616.clearpdf.ui.components.glassMenu
+import com.chethan616.clearpdf.ui.components.liquidRowClick
import com.chethan616.clearpdf.ui.components.viewerGlass
+import com.chethan616.clearpdf.ui.theme.LiquidGlassColors
import com.kyant.backdrop.backdrops.LayerBackdrop
import com.kyant.pdfcore.form.PdfFormWidget
+import com.kyant.shapes.RoundedRectangle
import kotlinx.coroutines.delay
+import kotlin.math.floor
+import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
-/** The tint form boxes wear in Edit mode: the system's "fillable" blue. */
+/** The tint form boxes wear: the system's "fillable" blue. */
internal val FormTint = Color(0xFF0A84FF)
/** A widget's box in this page's content px. */
@@ -88,7 +112,7 @@ internal fun PdfFormWidget.ptPx(size: Size): Float = size.height / pageHeightPt.
internal fun PdfFormWidget.textPx(size: Size, text: String): Float {
if (fontSizeNorm > 0f) return fontSizeNorm * size.height
val pt = ptPx(size)
- if (multiline) return 12f * pt
+ if (multiline || type == PdfFormWidget.Type.LIST) return 12f * pt
val r = rectIn(size)
val byHeight = (r.height - 4f * pt).coerceAtLeast(1f) / 0.925f
if (text.isEmpty()) return byHeight
@@ -104,99 +128,220 @@ private val AutoSizePaint = android.graphics.Paint(android.graphics.Paint.ANTI_A
private fun invert(c: Color) = Color(1f - c.red, 1f - c.green, 1f - c.blue, c.alpha)
+// ── List boxes ──────────────────────────────────────────────────────────────────────────────
+
+/** A list box row's height in content px. */
+internal fun PdfFormWidget.listRowPx(size: Size): Float = textPx(size, "") * 1.36f
+
+/** How many list rows fit in the box. */
+internal fun PdfFormWidget.listVisibleRows(size: Size): Int =
+ max(1, floor((rectIn(size).height - 4f * ptPx(size)) / listRowPx(size)).toInt())
+
+/** The first-row scroll that shows the selected option (in rows), like a PDF viewer opens it. */
+internal fun PdfFormWidget.listInitialScroll(size: Size, value: String): Float {
+ val visible = listVisibleRows(size)
+ val maxScroll = max(0, options.size - visible).toFloat()
+ val selected = optionValues.indexOf(value)
+ if (selected < 0) return 0f
+ return (selected - visible + 1).toFloat().coerceIn(0f, maxScroll)
+}
+
+/** The list option at content y [y] for scroll [scroll], or -1. */
+internal fun PdfFormWidget.listIndexAt(size: Size, y: Float, scroll: Float): Int {
+ val r = rectIn(size)
+ val i = floor((y - r.top - 2f * ptPx(size)) / listRowPx(size) + scroll).toInt()
+ return if (i in options.indices) i else -1
+}
+
+// ── Drawing ─────────────────────────────────────────────────────────────────────────────────
+
+/** Liquid-glass form controls, drawn flat (no backdrop pass) so a dense form stays cheap. */
+private class FormPalette(dark: Boolean) {
+ val paper = if (dark) Color.Black else Color.White
+ val fieldTop = if (dark) Color(0xFF2C323C) else Color(0xFFFCFDFF)
+ val fieldBottom = if (dark) Color(0xFF1F242C) else Color(0xFFE8F1FC)
+ val rim = if (dark) Color(0xFF56657A) else Color(0xFFA9C1DD)
+ val highlight = if (dark) Color.White.copy(alpha = 0.14f) else Color.White.copy(alpha = 0.95f)
+ val vividTop = Color(0xFF5AAEFF)
+ val vividBottom = FormTint
+ val subtle = if (dark) Color.White.copy(alpha = 0.10f) else Color.Black.copy(alpha = 0.06f)
+}
+
+private fun DrawScope.glassBody(r: Rect, radius: Float, p: FormPalette, focused: Boolean, editing: Boolean, alpha: Float = 1f) {
+ val cr = CornerRadius(radius)
+ drawRoundRect(Brush.verticalGradient(listOf(p.fieldTop, p.fieldBottom), r.top, r.bottom), r.topLeft, r.size, cr, alpha = alpha)
+ // Specular rim along the top edge: what makes a flat fill read as a pane of glass.
+ if (r.width > radius * 2f) {
+ drawLine(p.highlight, Offset(r.left + radius, r.top + 1.2f), Offset(r.right - radius, r.top + 1.2f), 1.4f, alpha = alpha)
+ }
+ drawRoundRect(p.rim, r.topLeft, r.size, cr, style = Stroke(1.2f), alpha = alpha)
+ if (focused) {
+ drawRoundRect(FormTint.copy(alpha = 0.20f), Offset(r.left - 3f, r.top - 3f), Size(r.width + 6f, r.height + 6f), CornerRadius(radius + 3f), style = Stroke(5f))
+ drawRoundRect(FormTint, r.topLeft, r.size, cr, style = Stroke(2.2f))
+ } else if (editing) {
+ drawRoundRect(FormTint.copy(alpha = 0.5f), r.topLeft, r.size, cr, style = Stroke(1.4f))
+ }
+}
+
+/** The glossy filled pill / bead of a ticked checkbox or chosen radio. */
+private fun DrawScope.vividBody(r: Rect, radius: Float, p: FormPalette) {
+ val cr = CornerRadius(radius)
+ drawRoundRect(Brush.verticalGradient(listOf(p.vividTop, p.vividBottom), r.top, r.bottom), r.topLeft, r.size, cr)
+ drawRoundRect(
+ Brush.verticalGradient(listOf(Color.White.copy(alpha = 0.42f), Color.Transparent), r.top, r.top + r.height * 0.55f),
+ Offset(r.left + r.width * 0.08f, r.top + r.height * 0.06f), Size(r.width * 0.84f, r.height * 0.48f), CornerRadius(radius * 0.8f)
+ )
+ drawRoundRect(Color(0xFF0060D0).copy(alpha = 0.6f), r.topLeft, r.size, cr, style = Stroke(1.1f))
+}
+
/**
- * Draws this page's form boxes: in Edit mode a soft blue wash and rim on every box (stronger on the
- * one being filled), and every value filled in this session inside its box, in the field's own
- * size, alignment and colour, so the page shows exactly what will be saved. [dark] is the dark
- * reader, which inverts the page, so paper and ink invert with it.
+ * Draws this page's form fields as liquid-glass controls over the PDF's own boxes: frosted text
+ * fields, glossy checkboxes and radios, a dropdown with its chevron, and scrolling list boxes with
+ * the chosen row lit. Values are the ones filled in this session ([values]) or the PDF's own, in
+ * the field's size, alignment and colour. [dark] is the dark reader, which inverts the page.
*/
internal fun DrawScope.drawFormWidgets(
widgets: List<PdfFormWidget>,
values: Map<String, String>,
editing: Boolean,
focusedKey: String?,
- dark: Boolean
+ dark: Boolean,
+ listScroll: Map<String, Float>
) {
- val paper = if (dark) Color.Black else Color.White
+ val pal = FormPalette(dark)
widgets.forEach { w ->
val r = w.rectIn(size)
+ if (r.width < 2f || r.height < 2f) return@forEach
val focused = w.key == focusedKey
val ink = Color(w.textArgb).let { if (dark) invert(it) else it }
- val v = values[w.fieldName]
- // The live editor draws the focused text box itself.
- if (v != null && !(focused && w.type == PdfFormWidget.Type.TEXT)) drawFormValue(w, v, r, paper, ink)
- if (editing || focused) {
- val cr = CornerRadius(min(r.width, r.height) * 0.14f)
- drawRoundRect(FormTint.copy(alpha = if (focused) 0.16f else 0.09f), r.topLeft, r.size, cr)
- drawRoundRect(
- FormTint.copy(alpha = if (focused) 0.95f else 0.5f), r.topLeft, r.size, cr,
- style = Stroke(if (focused) 2.4f else 1.3f)
- )
+ val value = values[w.fieldName] ?: w.value
+ val alpha = if (w.readOnly) 0.7f else 1f
+ // Hide the PDF's own appearance of the box; the glass control stands in for it. A field's
+ // border is stroked on its edge, so half of it lies outside the box: cover that too, or
+ // its square corners show around the rounded glass.
+ val bleed = 1.5f * w.ptPx(size)
+ drawRect(pal.paper, Offset(r.left - bleed, r.top - bleed), Size(r.width + bleed * 2f, r.height + bleed * 2f))
+ when (w.type) {
+ PdfFormWidget.Type.CHECKBOX, PdfFormWidget.Type.RADIO -> {
+ val s = r.minDimension * 0.84f
+ val box = Rect(r.center.x - s / 2f, r.center.y - s / 2f, r.center.x + s / 2f, r.center.y + s / 2f)
+ val radius = if (w.type == PdfFormWidget.Type.RADIO) s / 2f else s * 0.26f
+ val on = if (w.type == PdfFormWidget.Type.RADIO) value == w.onValue else value == "true"
+ if (on) {
+ vividBody(box, radius, pal)
+ if (w.type == PdfFormWidget.Type.RADIO) {
+ drawCircle(Color.White, s * 0.18f, box.center)
+ } else {
+ val check = Path().apply {
+ moveTo(box.left + s * 0.25f, box.top + s * 0.53f)
+ lineTo(box.left + s * 0.43f, box.top + s * 0.70f)
+ lineTo(box.left + s * 0.76f, box.top + s * 0.31f)
+ }
+ drawPath(check, Color.White, style = Stroke(s * 0.12f, cap = StrokeCap.Round, join = StrokeJoin.Round))
+ }
+ } else {
+ glassBody(box, radius, pal, focused = false, editing = editing, alpha = alpha)
+ }
+ }
+ PdfFormWidget.Type.TEXT -> {
+ glassBody(r, min(r.height * 0.22f, 9f), pal, focused, editing, alpha)
+ // The live editor draws the focused field's text itself.
+ if (!focused && value.isNotEmpty()) drawFieldText(w, value, r, ink)
+ }
+ PdfFormWidget.Type.CHOICE -> {
+ glassBody(r, min(r.height * 0.3f, 10f), pal, focused, editing, alpha)
+ val chevronRoom = r.height * 0.9f
+ val textRect = Rect(r.left, r.top, r.right - chevronRoom * 0.7f, r.bottom)
+ if (value.isNotEmpty()) drawFieldText(w, w.displayOf(value), textRect, ink)
+ val c = r.height * 0.13f
+ val cx = r.right - chevronRoom / 2f
+ val cy = r.center.y
+ val chevron = Path().apply {
+ moveTo(cx - c, cy - c * 0.45f); lineTo(cx, cy + c * 0.55f); lineTo(cx + c, cy - c * 0.45f)
+ }
+ drawPath(chevron, ink.copy(alpha = 0.7f), style = Stroke(max(1.4f, c * 0.32f), cap = StrokeCap.Round, join = StrokeJoin.Round))
+ }
+ PdfFormWidget.Type.LIST -> {
+ glassBody(r, min(r.height * 0.08f, 10f), pal, focused, editing, alpha)
+ drawListRows(w, value, r, ink, pal, listScroll[w.key] ?: w.listInitialScroll(size, value))
+ }
}
}
}
-private fun DrawScope.drawFormValue(w: PdfFormWidget, v: String, r: Rect, paper: Color, ink: Color) {
- when (w.type) {
- PdfFormWidget.Type.CHECKBOX -> {
- val inset = r.minDimension * 0.14f
- drawRect(paper, Offset(r.left + inset, r.top + inset), Size(r.width - inset * 2, r.height - inset * 2))
- if (v == "true") {
- val s = r.minDimension
- val ox = r.center.x - s / 2f
- val oy = r.center.y - s / 2f
- val check = Path().apply {
- moveTo(ox + s * 0.24f, oy + s * 0.53f)
- lineTo(ox + s * 0.43f, oy + s * 0.71f)
- lineTo(ox + s * 0.77f, oy + s * 0.30f)
+private fun DrawScope.drawListRows(w: PdfFormWidget, value: String, r: Rect, ink: Color, pal: FormPalette, scroll: Float) {
+ val pt = w.ptPx(size)
+ val rowH = w.listRowPx(size)
+ val textPx = w.textPx(size, "")
+ val pad = 2f * pt
+ val inner = Rect(r.left + 1.5f, r.top + 1.5f, r.right - 1.5f, r.bottom - 1.5f)
+ val selected = w.optionValues.indexOf(value)
+ val visible = w.listVisibleRows(size)
+ val overflow = w.options.size > visible
+ val textRight = if (overflow) inner.right - 6f else inner.right
+ clipRect(inner.left, inner.top, inner.right, inner.bottom) {
+ drawIntoCanvas { cv ->
+ val paint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply {
+ textSize = textPx
+ typeface = android.graphics.Typeface.SANS_SERIF
+ }
+ w.options.forEachIndexed { i, label ->
+ val top = r.top + pad + (i - scroll) * rowH
+ if (top > r.bottom || top + rowH < r.top) return@forEachIndexed
+ if (i == selected) {
+ drawRoundRect(
+ Brush.verticalGradient(listOf(pal.vividTop, pal.vividBottom), top, top + rowH),
+ Offset(inner.left + 2f, top + 1f), Size(textRight - inner.left - 4f, rowH - 2f), CornerRadius(rowH * 0.3f)
+ )
}
- drawPath(check, ink, style = Stroke(s * 0.11f, cap = StrokeCap.Round, join = StrokeJoin.Round))
+ paint.color = (if (i == selected) Color.White else ink).toArgb()
+ cv.nativeCanvas.drawText(label, inner.left + pad + 2f, top + rowH / 2f + textPx * 0.35f, paint)
}
}
- PdfFormWidget.Type.RADIO -> {
- val radius = r.minDimension / 2f
- drawCircle(paper, radius * 0.74f, r.center)
- if (v == w.onValue) drawCircle(ink, radius * 0.38f, r.center)
- }
- PdfFormWidget.Type.TEXT, PdfFormWidget.Type.CHOICE -> {
- val inset = min(r.height * 0.06f, 3f)
- drawRect(paper, Offset(r.left + inset, r.top + inset), Size(r.width - inset * 2, r.height - inset * 2))
- if (v.isEmpty()) return
- val shown = if (w.password) "•".repeat(v.length) else v
- val textPx = w.textPx(size, shown)
- val pad = 2f * w.ptPx(size)
- clipRect(r.left, r.top, r.right, r.bottom) {
- drawIntoCanvas { cv ->
- val paint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply {
- textSize = textPx
- color = ink.toArgb()
- typeface = android.graphics.Typeface.SANS_SERIF
+ }
+ if (overflow) {
+ // A slim glass scroll indicator, like the platform list's.
+ val trackTop = inner.top + 3f
+ val trackH = inner.height - 6f
+ val maxScroll = (w.options.size - visible).toFloat().coerceAtLeast(1f)
+ val thumbH = (trackH * visible / w.options.size).coerceAtLeast(10f)
+ val thumbTop = trackTop + (trackH - thumbH) * (scroll / maxScroll).coerceIn(0f, 1f)
+ drawRoundRect(pal.subtle, Offset(inner.right - 5f, trackTop), Size(3f, trackH), CornerRadius(1.5f))
+ drawRoundRect(FormTint.copy(alpha = 0.55f), Offset(inner.right - 5f, thumbTop), Size(3f, thumbH), CornerRadius(1.5f))
+ }
+}
+
+/** A text / choice value inside its box, in the field's own size, alignment and colour. */
+private fun DrawScope.drawFieldText(w: PdfFormWidget, v: String, r: Rect, ink: Color) {
+ val shown = if (w.password) "•".repeat(v.length) else v
+ val textPx = w.textPx(size, shown)
+ val pad = 2f * w.ptPx(size)
+ clipRect(r.left, r.top, r.right, r.bottom) {
+ drawIntoCanvas { cv ->
+ val paint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply {
+ textSize = textPx
+ color = ink.toArgb()
+ typeface = android.graphics.Typeface.SANS_SERIF
+ }
+ val nc = cv.nativeCanvas
+ when {
+ w.comb && w.maxLength > 0 -> {
+ val cell = r.width / w.maxLength
+ val y = r.center.y + textPx * 0.35f
+ shown.take(w.maxLength).forEachIndexed { i, ch ->
+ val s = ch.toString()
+ nc.drawText(s, r.left + cell * i + (cell - paint.measureText(s)) / 2f, y, paint)
}
- val nc = cv.nativeCanvas
- when {
- w.comb && w.maxLength > 0 -> {
- val cell = r.width / w.maxLength
- val y = r.center.y + textPx * 0.35f
- shown.take(w.maxLength).forEachIndexed { i, ch ->
- val s = ch.toString()
- nc.drawText(s, r.left + cell * i + (cell - paint.measureText(s)) / 2f, y, paint)
- }
- }
- w.multiline -> {
- val maxW = r.width - pad * 2
- var y = r.top + pad + textPx
- for (line in wrap(shown, paint, maxW)) {
- if (y > r.bottom + textPx) break
- nc.drawText(line, alignedX(w.alignment, r, pad, paint.measureText(line)), y, paint)
- y += textPx * 1.16f
- }
- }
- else -> {
- val y = r.center.y + textPx * 0.35f
- nc.drawText(shown, alignedX(w.alignment, r, pad, paint.measureText(shown)), y, paint)
- }
+ }
+ w.multiline -> {
+ var y = r.top + pad + textPx
+ for (line in wrap(shown, paint, r.width - pad * 2)) {
+ if (y > r.bottom + textPx) break
+ nc.drawText(line, alignedX(w.alignment, r, pad, paint.measureText(line)), y, paint)
+ y += textPx * 1.16f
}
}
+ else -> nc.drawText(shown, alignedX(w.alignment, r, pad, paint.measureText(shown)), r.center.y + textPx * 0.35f, paint)
}
}
}
@@ -222,10 +367,13 @@ private fun wrap(text: String, paint: android.graphics.Paint, maxW: Float): List
return out
}
+// ── Typing in place ─────────────────────────────────────────────────────────────────────────
+
/**
* Typing straight into a text field on the page: a real text field laid exactly over the box, in
* the field's size, alignment and colour (and dot-masked for password fields), so what is typed is
- * what the saved form shows. It lives inside the page's zoom layer, so it zooms with the page.
+ * what the saved form shows. It lives inside the page's zoom layer, so it zooms with the page; the
+ * glass body under it is drawn by [drawFormWidgets].
*/
@Composable
internal fun PdfFormInlineEditor(
@@ -247,7 +395,6 @@ internal fun PdfFormInlineEditor(
if (value != field.text) field = TextFieldValue(value, TextRange(value.length))
}
LaunchedEffect(widget.key) { delay(80); runCatching { focus.requestFocus() } }
- val paper = if (dark) Color.Black else Color.White
val ink = Color(widget.textArgb).let { if (dark) invert(it) else it }
val pad = with(density) { (2f * widget.ptPx(canvas)).toDp() }
val comb = widget.comb && widget.maxLength > 0
@@ -273,8 +420,6 @@ internal fun PdfFormInlineEditor(
modifier = Modifier
.offset { IntOffset(r.left.roundToInt(), r.top.roundToInt()) }
.size(with(density) { r.width.toDp() }, with(density) { r.height.toDp() })
- .background(paper, RoundedCornerShape(3.dp))
- .border(1.5.dp, FormTint, RoundedCornerShape(3.dp))
.padding(horizontal = pad)
.focusRequester(focus),
decorationBox = { inner ->
@@ -298,13 +443,12 @@ internal fun humanFieldName(name: String): String =
.ifEmpty { name }
/**
- * The iOS-style form accessory, floating above the keyboard: previous / next field, the field's
- * name, Done, and, for a choice field (which has no keyboard), its options as glass chips.
+ * The iOS-style form accessory, floating above the keyboard while a text field is being filled:
+ * previous / next field, the field's name, and Done.
*/
@Composable
internal fun PdfFormAccessoryBar(
widget: PdfFormWidget,
- value: String,
backdrop: LayerBackdrop,
ink: Color,
glass: Color,
@@ -313,57 +457,139 @@ internal fun PdfFormAccessoryBar(
onPrevious: () -> Unit,
onNext: () -> Unit,
onDone: () -> Unit,
- onPick: (String) -> Unit,
modifier: Modifier = Modifier
) {
- Column(
+ Row(
modifier
.fillMaxWidth()
.viewerGlass(backdrop, glass, shape = { RoundedCornerShape(26.dp) })
.padding(horizontal = 8.dp, vertical = 8.dp),
- verticalArrangement = Arrangement.spacedBy(8.dp)
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(6.dp)
) {
- Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
- LiquidIconButton(
- onClick = onPrevious, backdrop = backdrop, isInteractive = canPrevious,
- surfaceColor = glass, modifier = Modifier.size(38.dp)
- ) { Icon(Icons.Rounded.KeyboardArrowUp, androidx.compose.ui.res.stringResource(R.string.form_fill_previous), Modifier.size(22.dp), ink.copy(if (canPrevious) 1f else 0.35f)) }
- LiquidIconButton(
- onClick = onNext, backdrop = backdrop, isInteractive = canNext,
- surfaceColor = glass, modifier = Modifier.size(38.dp)
- ) { Icon(Icons.Rounded.KeyboardArrowDown, androidx.compose.ui.res.stringResource(R.string.form_fill_next), Modifier.size(22.dp), ink.copy(if (canNext) 1f else 0.35f)) }
- BasicText(
- humanFieldName(widget.fieldName),
- style = TextStyle(ink.copy(0.75f), 13.sp, FontWeight.Medium),
- maxLines = 1,
- overflow = TextOverflow.Ellipsis,
- modifier = Modifier.weight(1f).padding(horizontal = 4.dp)
- )
- LiquidButton(onClick = onDone, backdrop = backdrop, tint = FormTint, modifier = Modifier.padding(end = 2.dp)) {
- BasicText(androidx.compose.ui.res.stringResource(R.string.viewer_done), style = TextStyle(Color.White, 14.sp, FontWeight.SemiBold))
- }
+ LiquidIconButton(
+ onClick = onPrevious, backdrop = backdrop, isInteractive = canPrevious,
+ surfaceColor = glass, modifier = Modifier.size(38.dp)
+ ) { Icon(Icons.Rounded.KeyboardArrowUp, stringResource(R.string.form_fill_previous), Modifier.size(22.dp), ink.copy(if (canPrevious) 1f else 0.35f)) }
+ LiquidIconButton(
+ onClick = onNext, backdrop = backdrop, isInteractive = canNext,
+ surfaceColor = glass, modifier = Modifier.size(38.dp)
+ ) { Icon(Icons.Rounded.KeyboardArrowDown, stringResource(R.string.form_fill_next), Modifier.size(22.dp), ink.copy(if (canNext) 1f else 0.35f)) }
+ BasicText(
+ humanFieldName(widget.fieldName),
+ style = TextStyle(ink.copy(0.75f), 13.sp, FontWeight.Medium),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.weight(1f).padding(horizontal = 4.dp)
+ )
+ LiquidButton(onClick = onDone, backdrop = backdrop, tint = FormTint, modifier = Modifier.padding(end = 2.dp)) {
+ BasicText(stringResource(R.string.viewer_done), style = TextStyle(Color.White, 14.sp, FontWeight.SemiBold))
}
- if (widget.type == PdfFormWidget.Type.CHOICE && widget.options.isNotEmpty()) {
- Row(
- Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 2.dp),
- horizontalArrangement = Arrangement.spacedBy(6.dp)
+ }
+}
+
+// ── Dropdown menu ───────────────────────────────────────────────────────────────────────────
+
+/**
+ * A dropdown field's options, in the app's glass menu, unfolding from the field it belongs to
+ * ([anchor] is the field's box in window coordinates). Back or a tap outside closes it.
+ */
+@Composable
+internal fun PdfFormChoiceMenu(
+ widget: PdfFormWidget?,
+ anchor: Rect,
+ value: String,
+ dark: Boolean,
+ onPick: (String) -> Unit,
+ onDismiss: () -> Unit
+) {
+ val open = widget != null
+ // The last widget shown, so the menu can play its fold animation after it's dismissed.
+ var shown by remember { mutableStateOf<PdfFormWidget?>(null) }
+ if (widget != null) shown = widget
+ BackHandler(enabled = open, onBack = onDismiss)
+ val fg = LiquidGlassColors.text(dark)
+ GlassOverlay {
+ val density = LocalDensity.current
+ Box(Modifier.fillMaxSize()) {
+ if (open) {
+ Box(
+ Modifier
+ .fillMaxSize()
+ .pointerInput(Unit) {
+ awaitEachGesture {
+ awaitFirstDown(requireUnconsumed = false).consume()
+ onDismiss()
+ }
+ }
+ )
+ }
+ val w = shown ?: return@Box
+ val local = windowToLocal(anchor.topLeft)
+ val menuWidth = with(density) { max(anchor.width, 200.dp.toPx()).toDp() }
+ val gap = with(density) { 6.dp.toPx() }
+ val maxMenuH = with(density) { 320.dp.toPx() }
+ val below = local.y + anchor.height + gap
+ val fitsBelow = below + maxMenuH <= layerSize.height || local.y < maxMenuH
+ AnimatedVisibility(
+ visible = open,
+ enter = fadeIn(tween(110)),
+ exit = fadeOut(tween(90)),
+ modifier = Modifier.offset {
+ IntOffset(
+ local.x.roundToInt().coerceIn(0, (layerSize.width - with(density) { menuWidth.roundToPx() }).coerceAtLeast(0)),
+ if (fitsBelow) below.roundToInt() else (local.y - gap - maxMenuH).roundToInt().coerceAtLeast(0)
+ )
+ }
) {
- widget.options.forEach { option ->
- val selected = option == value
- LiquidButton(
- onClick = { onPick(option) },
- backdrop = backdrop,
- tint = if (selected) FormTint else Color.Unspecified,
- surfaceColor = if (selected) Color.Unspecified else glass
- ) {
- BasicText(
- option,
- style = TextStyle(if (selected) Color.White else ink, 14.sp, if (selected) FontWeight.SemiBold else FontWeight.Medium),
- maxLines = 1
- )
+ val reveal by transition.animateFloat(
+ transitionSpec = { if (targetState == EnterExitState.Visible) GlassMotion.unfold() else GlassMotion.fold() },
+ label = "formMenuReveal"
+ ) { if (it == EnterExitState.Visible) 1f else 0f }
+ val revealY by transition.animateFloat(
+ transitionSpec = { if (targetState == EnterExitState.Visible) GlassMotion.unfoldLag() else GlassMotion.fold() },
+ label = "formMenuRevealY"
+ ) { if (it == EnterExitState.Visible) 1f else 0f }
+ Column(
+ Modifier
+ .width(menuWidth)
+ .heightIn(max = with(density) { maxMenuH.toDp() })
+ .graphicsLayer {
+ alpha = reveal.coerceIn(0f, 1f)
+ scaleX = 0.9f + 0.1f * reveal
+ scaleY = 0.55f + 0.45f * revealY
+ transformOrigin = TransformOrigin(0.5f, if (fitsBelow) 0f else 1f)
+ compositingStrategy = CompositingStrategy.ModulateAlpha
+ }
+ .glassMenu(backdrop, dark, shape = { RoundedRectangle(20.dp) }, surfaceAlpha = 0.78f)
+ .verticalScroll(rememberScrollState())
+ .padding(5.dp),
+ verticalArrangement = Arrangement.spacedBy(1.dp)
+ ) {
+ w.options.forEachIndexed { i, label ->
+ val optionValue = w.optionValues.getOrElse(i) { label }
+ val selected = optionValue == value
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .liquidRowClick(corner = 12.dp) { onPick(optionValue) }
+ .padding(horizontal = 14.dp, vertical = 11.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.SpaceBetween
+ ) {
+ BasicText(
+ label,
+ style = TextStyle(fg, 14.sp, if (selected) FontWeight.SemiBold else FontWeight.Medium),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.weight(1f)
+ )
+ if (selected) Icon(Icons.Rounded.Check, null, Modifier.size(16.dp), FormTint)
+ }
}
}
}
}
}
}
+
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 c53d716..fe318ad 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
@@ -880,6 +880,9 @@ internal fun PdfMarkup.TextEditMarkup.toTextReplace(frameW: Float, frameH: Float
* An exact preview of a page's text edits: [bitmap] is the edited page rendered by the PDF engine
* over the normalized horizontal [band] around the line, valid while the markup's text is [text].
*/
+/** A sharp, screen-resolution render of the normalized [region] of a page, shown while zoomed in. */
+internal class PageDetailTile(val region: android.graphics.RectF, val bitmap: Bitmap)
+
internal class TextEditPatch(val text: String, val band: android.graphics.RectF, val bitmap: Bitmap)
/** The band an edited line's preview covers: full page width, the line plus room for ascenders. */
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 73ef74e..a16ed7f 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
@@ -297,6 +297,8 @@ fun PdfViewerScreen(
// ── Page annotation state ──────────────────────────────────────────────
val annotationsByPage = remember { mutableStateMapOf<Int, MutableList<PdfMarkup>>() }
+ // Screen-resolution renders of the visible part of each page while zoomed in (sharp zoom, #29).
+ val detailTiles = remember { mutableStateMapOf<Int, PageDetailTile>() }
val pageCanvasSizes = remember { mutableStateMapOf<Int, Size>() }
val pageBitmapSizes = remember { mutableStateMapOf<Int, Size>() }
@@ -404,6 +406,8 @@ fun PdfViewerScreen(
val markupBarHost = remember { MarkupBarHost() }
textSelection.blocksProvider = { p -> viewModel.uiState.value.ocrBlocksByPage[p].orEmpty() }
var containerWidthPx by remember { mutableIntStateOf(0) }
+
+
textSelection.transformProvider = { PdfViewportTransform(containerWidthPx.toFloat(), scale, offsetX) }
val selectionAutoScroller = rememberSelectionAutoScroller(listState, textSelection)
selectionAutoScroller.panBy = { dx ->
@@ -819,7 +823,7 @@ fun PdfViewerScreen(
val formEditing = editorToolsOpen && state.formWidgetsByPage.isNotEmpty()
val formOrder = remember(state.formWidgetsByPage) {
state.formWidgetsByPage.values.flatten()
- .filter { !it.readOnly && (it.type == com.kyant.pdfcore.form.PdfFormWidget.Type.TEXT || it.type == com.kyant.pdfcore.form.PdfFormWidget.Type.CHOICE) }
+ .filter { !it.readOnly && it.type == com.kyant.pdfcore.form.PdfFormWidget.Type.TEXT }
.sortedWith(compareBy({ it.pageIndex }, { it.top }, { it.left }))
}
var showFormTour by remember { mutableStateOf(!OnboardingManager.hasSeenFormFillTour(context)) }
@@ -834,10 +838,20 @@ fun PdfViewerScreen(
val offset = if (canvas != null) (w.top * canvas.height - viewport * 0.22f).toInt() else 0
runCatching { listState.animateScrollToItem(w.pageIndex, offset.coerceAtLeast(0)) }
}
- val onTapFormWidget: (com.kyant.pdfcore.form.PdfFormWidget) -> Unit = { w ->
+ // A dropdown field's open menu, and its field's box in window space.
+ var formMenu by remember { mutableStateOf<com.kyant.pdfcore.form.PdfFormWidget?>(null) }
+ var formMenuAnchor by remember { mutableStateOf(androidx.compose.ui.geometry.Rect.Zero) }
+ val onTapFormWidget: (com.kyant.pdfcore.form.PdfFormWidget, androidx.compose.ui.geometry.Rect) -> Unit = { w, anchor ->
if (showFormTour) { showFormTour = false; OnboardingManager.markFormFillTourSeen(context) }
when (w.type) {
- com.kyant.pdfcore.form.PdfFormWidget.Type.TEXT, com.kyant.pdfcore.form.PdfFormWidget.Type.CHOICE -> focusedForm = w
+ com.kyant.pdfcore.form.PdfFormWidget.Type.TEXT -> focusedForm = w
+ com.kyant.pdfcore.form.PdfFormWidget.Type.LIST -> Unit
+ com.kyant.pdfcore.form.PdfFormWidget.Type.CHOICE -> {
+ focusedForm = null
+ keyboard?.hide()
+ formMenuAnchor = anchor
+ formMenu = w
+ }
com.kyant.pdfcore.form.PdfFormWidget.Type.CHECKBOX -> {
focusedForm = null
haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.SegmentTick)
@@ -1010,6 +1024,46 @@ fun PdfViewerScreen(
var containerHeightPx by remember { mutableStateOf(0) }
+ // Sharp zoom (#29): once a zoom / pan settles, the visible part of each on-screen page is
+ // rendered at exact screen resolution and laid over the page, so text and fine diagrams stay
+ // crisp at any zoom instead of being a stretched page bitmap. Cleared again near 1x.
+ LaunchedEffect(state.document?.uri) {
+ detailTiles.clear()
+ snapshotFlow { Triple(scale, offsetX, listState.firstVisibleItemIndex to listState.firstVisibleItemScrollOffset) }
+ .distinctUntilChanged()
+ .debounce(160)
+ .collectLatest { (s, ox, _) ->
+ if (s < 1.15f) { detailTiles.clear(); return@collectLatest }
+ val cw = containerWidthPx.toFloat()
+ val ch = containerHeightPx.toFloat()
+ if (cw <= 0f || ch <= 0f) return@collectLatest
+ // The viewport in the zoom layer's own (unscaled) space: the layer scales about
+ // its top-centre and is shifted by `offsetX`.
+ val lx0 = (-cw / 2f - ox) / s + cw / 2f
+ val lx1 = (cw / 2f - ox) / s + cw / 2f
+ val ly1 = ch / s
+ val keep = HashSet<Int>()
+ for (item in listState.layoutInfo.visibleItemsInfo) {
+ val p = item.index
+ val o = textSelection.pageOrigin(p) ?: continue
+ val sz = textSelection.pageSize(p) ?: continue
+ if (sz.width <= 0f || sz.height <= 0f) continue
+ val l = maxOf(lx0, o.x); val r = minOf(lx1, o.x + sz.width)
+ val t = maxOf(0f, o.y); val b = minOf(ly1, o.y + sz.height)
+ if (r <= l || b <= t) continue
+ val region = android.graphics.RectF(
+ (l - o.x) / sz.width, (t - o.y) / sz.height, (r - o.x) / sz.width, (b - o.y) / sz.height
+ )
+ val w = ((r - l) * s).roundToInt().coerceIn(1, 4096)
+ val h = ((b - t) * s).roundToInt().coerceIn(1, 4096)
+ val bmp = viewModel.renderRegion(p, region, sz.width * s, w, h) ?: continue
+ detailTiles[p] = PageDetailTile(region, bmp)
+ keep += p
+ }
+ detailTiles.keys.retainAll(keep)
+ }
+ }
+
// ── Adaptive control ink, sampled per bar (Apple-style) ──────────────────────────────
// Each bar reads the luminance of the content *directly behind it*, so on a page that is a
// dark image up top and a white canvas below, the top bar goes white while the bottom toolbar
@@ -1236,12 +1290,18 @@ fun PdfViewerScreen(
darkPageAppearance = darkPageAppearance,
marks = getPageMarks(page),
textEditPatches = textEditPatches,
+ detailTile = detailTiles[page],
formWidgets = state.formWidgetsByPage[page].orEmpty(),
formValues = formValues,
formEditing = formEditing,
focusedFormKey = focusedForm?.key,
onTapFormWidget = onTapFormWidget,
- onFormTextChange = { w, v -> setFormValue(w, v) },
+ onFormTextChange = { w, v ->
+ if (w.type == com.kyant.pdfcore.form.PdfFormWidget.Type.LIST) {
+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.SegmentTick)
+ }
+ setFormValue(w, v)
+ },
onFormImeNext = { w ->
val i = formOrder.indexOfFirst { it.key == w.key }
focusedForm = formOrder.getOrNull(i + 1)
@@ -1987,7 +2047,6 @@ fun PdfViewerScreen(
val imeUp = androidx.compose.foundation.layout.WindowInsets.ime.getBottom(LocalDensity.current) > 0
PdfFormAccessoryBar(
widget = w,
- value = formValueOf(w),
backdrop = contentBackdrop,
ink = panelFg,
glass = chromePanel,
@@ -1996,10 +2055,6 @@ fun PdfViewerScreen(
onPrevious = { formOrder.getOrNull(i - 1)?.let { focusedForm = it } },
onNext = { formOrder.getOrNull(i + 1)?.let { focusedForm = it } },
onDone = { keyboard?.hide(); focusedForm = null },
- onPick = { option ->
- haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.SegmentTick)
- setFormValue(w, option)
- },
modifier = Modifier
.align(Alignment.BottomCenter)
.imePadding()
@@ -2008,8 +2063,23 @@ fun PdfViewerScreen(
.padding(bottom = if (imeUp) 8.dp else 104.dp)
)
}
+ PdfFormChoiceMenu(
+ widget = formMenu,
+ anchor = formMenuAnchor,
+ value = formMenu?.let { formValueOf(it) }.orEmpty(),
+ // The menu belongs to the page, so dark reader makes it dark too, whatever the app theme.
+ dark = darkPageAppearance || com.chethan616.clearpdf.ui.theme.LocalIsDarkMode.current,
+ onPick = { option ->
+ formMenu?.let { w ->
+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.SegmentTick)
+ setFormValue(w, option)
+ }
+ formMenu = null
+ },
+ onDismiss = { formMenu = null }
+ )
com.chethan616.clearpdf.ui.components.GlassGuideCallout(
- visible = showFormTour && formEditing && focusedForm == null,
+ visible = showFormTour && state.formWidgetsByPage.isNotEmpty() && focusedForm == null && formMenu == null,
title = stringResource(R.string.tour_form_title),
message = stringResource(R.string.tour_form_message),
backdrop = contentBackdrop,
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/ScanDocumentScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/ScanDocumentScreen.kt
index b17efe0..8937e04 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/ScanDocumentScreen.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/ScanDocumentScreen.kt
@@ -90,11 +90,6 @@ import com.chethan616.clearpdf.ui.theme.LocalIsDarkMode
import com.chethan616.clearpdf.ui.utils.StarPromptEventBus
import com.chethan616.clearpdf.ui.utils.rememberUISensor
import com.chethan616.clearpdf.ui.viewmodel.ScanViewModel
-import com.google.mlkit.vision.documentscanner.GmsDocumentScannerOptions
-import com.google.mlkit.vision.documentscanner.GmsDocumentScannerOptions.RESULT_FORMAT_JPEG
-import com.google.mlkit.vision.documentscanner.GmsDocumentScannerOptions.SCANNER_MODE_FULL
-import com.google.mlkit.vision.documentscanner.GmsDocumentScanning
-import com.google.mlkit.vision.documentscanner.GmsDocumentScanningResult
import com.kyant.backdrop.backdrops.LayerBackdrop
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@@ -153,21 +148,12 @@ fun ScanDocumentScreen(
label = "scanContentOffsetY"
)
- // ── ML Kit Document Scanner (created lazily to avoid composition crash) ──
- val scannerLauncher = rememberLauncherForActivityResult(
- contract = ActivityResultContracts.StartIntentSenderForResult()
- ) { result ->
- if (result.resultCode == Activity.RESULT_OK) {
- val scanResult = GmsDocumentScanningResult.fromActivityResultIntent(result.data)
- scanResult?.pages?.let { pages ->
- val uris = pages.mapNotNull { it.imageUri }
- if (uris.isNotEmpty()) {
- viewModel.onScanComplete(uris, ScanFilter.ORIGINAL)
- }
- }
- }
- viewModel.cancelScanning()
- }
+ // ── Document scanner (Google's in play / foss builds, the camera app in F-Droid) ──
+ val startScanner = com.chethan616.clearpdf.scan.rememberDocumentScanner(
+ onPages = { uris -> viewModel.onScanComplete(uris, ScanFilter.ORIGINAL) },
+ onFinished = { viewModel.cancelScanning() },
+ onError = { viewModel.setError(context.getString(R.string.scanner_start_failed)) }
+ )
// Gallery picker (multiple images)
val galleryLauncher = rememberLauncherForActivityResult(
@@ -181,23 +167,7 @@ fun ScanDocumentScreen(
fun launchDocumentScanner() {
viewModel.startScanning()
- val options = GmsDocumentScannerOptions.Builder()
- .setGalleryImportAllowed(true)
- .setPageLimit(100)
- .setResultFormats(RESULT_FORMAT_JPEG)
- .setScannerMode(SCANNER_MODE_FULL)
- .build()
- val scanner = GmsDocumentScanning.getClient(options)
- scanner.getStartScanIntent(activity)
- .addOnSuccessListener { intentSender ->
- scannerLauncher.launch(
- IntentSenderRequest.Builder(intentSender).build()
- )
- }
- .addOnFailureListener { e ->
- viewModel.setError(context.getString(R.string.scanner_start_failed))
- viewModel.cancelScanning()
- }
+ startScanner()
}
GlassScreenScaffold(
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/WhatsNewScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/WhatsNewScreen.kt
index 6ecd7ac..4974501 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/WhatsNewScreen.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/WhatsNewScreen.kt
@@ -20,6 +20,8 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.AutoAwesome
import androidx.compose.material.icons.rounded.BugReport
import androidx.compose.material.icons.rounded.CheckBox
+import androidx.compose.material.icons.rounded.Layers
+import androidx.compose.material.icons.rounded.ZoomIn
import androidx.compose.material.icons.rounded.EditNote
import androidx.compose.material.icons.rounded.IosShare
import androidx.compose.material.icons.rounded.TableChart
@@ -58,6 +60,8 @@ private class WhatsNewItem(val icon: ImageVector, val accent: Color, val title:
private val WhatsNewItems = listOf(
WhatsNewItem(Icons.Rounded.EditNote, LiquidGlassColors.Blue, R.string.whats_new_edit_title, R.string.whats_new_edit_desc),
WhatsNewItem(Icons.Rounded.CheckBox, LiquidGlassColors.Indigo, R.string.whats_new_forms_title, R.string.whats_new_forms_desc),
+ WhatsNewItem(Icons.Rounded.ZoomIn, LiquidGlassColors.Teal, R.string.whats_new_zoom_title, R.string.whats_new_zoom_desc),
+ WhatsNewItem(Icons.Rounded.Layers, LiquidGlassColors.Blue, R.string.whats_new_window_title, R.string.whats_new_window_desc),
WhatsNewItem(Icons.Rounded.AutoAwesome, LiquidGlassColors.Teal, R.string.whats_new_glass_title, R.string.whats_new_glass_desc),
WhatsNewItem(Icons.Rounded.IosShare, LiquidGlassColors.Green, R.string.whats_new_share_title, R.string.whats_new_share_desc),
WhatsNewItem(Icons.Rounded.Vibration, LiquidGlassColors.Purple, R.string.whats_new_feel_title, R.string.whats_new_feel_desc),
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 3b317a5..00c85b9 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
@@ -452,6 +452,17 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
return FileProvider.getUriForFile(context, "${context.packageName}.provider", targetFile)
}
+ /**
+ * The visible [region] of [pageIndex] at screen resolution for a zoomed-in view (see
+ * PdfViewer.renderRegion). Null if the document changed or rendering failed.
+ */
+ suspend fun renderRegion(pageIndex: Int, region: android.graphics.RectF, pageWidthPx: Float, outWidth: Int, outHeight: Int): Bitmap? {
+ val doc = _uiState.value.document ?: return null
+ return withContext(AppDispatchers.pdf) {
+ runCatching { openPdfUseCase.renderRegion(doc, pageIndex, region, pageWidthPx, outWidth, outHeight) }.getOrNull()
+ }?.takeIf { _uiState.value.document?.uri == doc.uri }
+ }
+
fun renderPage(context: Context, pageIndex: Int, targetWidthPx: Int = DEFAULT_RENDER_WIDTH) {
val state = _uiState.value
val doc = state.document ?: return
diff --git a/app/src/main/java/com/chethan616/clearpdf/utils/PptxRenderer.kt b/app/src/main/java/com/chethan616/clearpdf/utils/PptxRenderer.kt
index 20ed77a..c546a37 100644
--- a/app/src/main/java/com/chethan616/clearpdf/utils/PptxRenderer.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/utils/PptxRenderer.kt
@@ -158,27 +158,34 @@ internal object PptxRenderer {
// ── Theme colours ───────────────────────────────────────────────────────
- /** Scheme name (`accent1`, `tx1`, …) → ARGB, from the master's theme. */
- private fun themeColors(masterPath: String?): Map<String, Int> {
- val themePath = masterPath?.let { m -> rels(m).values.firstOrNull { it.startsWith("ppt/theme/") } }
+ private fun themePath(masterPath: String?): String? =
+ masterPath?.let { m -> rels(m).values.firstOrNull { it.startsWith("ppt/theme/") } }
?: entries.keys.firstOrNull { it.startsWith("ppt/theme/theme") }
- ?: return emptyMap()
- val scheme = part(themePath)?.find("a:clrScheme") ?: return emptyMap()
- val out = HashMap<String, Int>()
+
+ /**
+ * Scheme name (`accent1`, `tx1`, …) → ARGB, from the master's theme. The slide-level names
+ * (`tx1`, `bg1`, …) go through the master's colour map (a layout may override it): a dark
+ * template maps text to `lt1`, which is why its text is white, not the theme's `dk1`.
+ */
+ private fun themeColors(masterPath: String?, layoutPath: String?): Map<String, Int> {
+ val path = themePath(masterPath) ?: return emptyMap()
+ val scheme = part(path)?.find("a:clrScheme") ?: return emptyMap()
+ val raw = HashMap<String, Int>()
for (entry in scheme.children) {
// `<a:dk1><a:sysClr lastClr="000000"/></a:dk1>` or `<a:srgbClr val="4472C4"/>`
val key = entry.name.substringAfter(':')
val srgb = entry.child("a:srgbClr")?.attr("val")
?: entry.child("a:sysClr")?.attr("lastClr")
val color = parseSrgb(srgb) ?: continue
- out[key] = color
- // PowerPoint's slide-level names are one indirection off the theme's own.
- when (key) {
- "dk1" -> out["tx1"] = color
- "lt1" -> out["bg1"] = color
- "dk2" -> out["tx2"] = color
- "lt2" -> out["bg2"] = color
- }
+ raw[key] = color
+ }
+ val map = layoutPath?.let { part(it) }?.find("a:overrideClrMapping")
+ ?: masterPath?.let { part(it) }?.find("p:clrMap")
+ val out = HashMap<String, Int>(raw)
+ val defaults = mapOf("bg1" to "lt1", "tx1" to "dk1", "bg2" to "lt2", "tx2" to "dk2")
+ for (name in listOf("bg1", "tx1", "bg2", "tx2", "accent1", "accent2", "accent3", "accent4", "accent5", "accent6", "hlink", "folHlink")) {
+ val target = map?.attr(name) ?: defaults[name] ?: name
+ raw[target]?.let { out[name] = it }
}
return out
}
@@ -189,32 +196,85 @@ internal object PptxRenderer {
val slide = part(slidePath) ?: return
val layoutPath = rels(slidePath).values.firstOrNull { it.startsWith("ppt/slideLayouts/") }
val masterPath = layoutPath?.let { rels(it).values.firstOrNull { p -> p.startsWith("ppt/slideMasters/") } }
- val theme = themeColors(masterPath)
+ val theme = themeColors(masterPath, layoutPath)
val ctx = SlideContext(
theme = theme,
slidePath = slidePath,
slideNumber = slideNumber,
+ layout = layoutPath?.let { part(it) },
+ master = masterPath?.let { part(it) },
// A placeholder without its own `<a:xfrm>` inherits the layout's box, and the layout
// may in turn inherit the master's. Looking that up is what keeps titles and body
// text on the slide instead of stacked in the top-left corner.
placeholders = placeholderBoxes(masterPath) + placeholderBoxes(layoutPath)
)
- canvas.drawColor(
- background(slide, theme)
- ?: layoutPath?.let { background(part(it), theme) }
- ?: masterPath?.let { background(part(it), theme) }
- ?: Color.WHITE
- )
+ canvas.drawColor(Color.WHITE)
+ val w = canvas.width.toFloat()
+ val h = canvas.height.toFloat()
+ drawBackground(canvas, slide, theme, masterPath, w, h) ||
+ (layoutPath != null && drawBackground(canvas, part(layoutPath), theme, masterPath, w, h)) ||
+ (masterPath != null && drawBackground(canvas, part(masterPath), theme, masterPath, w, h))
val tree = slide.find("p:spTree") ?: return
drawShapeTree(canvas, tree, ctx, identityTransform())
}
- private fun background(part: OoxmlNode?, theme: Map<String, Int>): Int? {
- val fill = part?.find("p:bg")?.find("a:solidFill") ?: return null
- return solidFillColor(fill, theme)
+ /**
+ * Paints a part's `<p:bg>`: its own fill (`p:bgPr`: solid or gradient), or a reference into
+ * the theme's background fills (`p:bgRef`), whose placeholder colour is the referenced
+ * scheme colour. False when the part doesn't set a background.
+ */
+ private fun drawBackground(
+ canvas: Canvas, part: OoxmlNode?, theme: Map<String, Int>, masterPath: String?, w: Float, h: Float
+ ): Boolean {
+ val bg = part?.find("p:bg") ?: return false
+ bg.child("p:bgPr")?.let { return paintFill(canvas, it, theme, null, w, h) }
+ val ref = bg.child("p:bgRef") ?: return false
+ val idx = ref.attr("idx")?.toIntOrNull() ?: return false
+ val color = solidFillColor(ref, theme)
+ val list = themePath(masterPath)?.let { part(it) }?.find("a:bgFillStyleLst")?.children.orEmpty()
+ val chosen = (if (idx >= 1001) list.getOrNull(idx - 1001) else null)
+ if (chosen == null) {
+ color?.let { canvas.drawColor(it); return true }
+ return false
+ }
+ return paintFill(canvas, chosen, theme, color, w, h)
+ }
+
+ /** A solid or linear-gradient fill over the whole canvas; [phClr] stands in for `phClr`. */
+ private fun paintFill(canvas: Canvas, fill: OoxmlNode, theme: Map<String, Int>, phClr: Int?, w: Float, h: Float): Boolean {
+ val node = if (fill.name == "a:solidFill" || fill.name == "a:gradFill") fill
+ else fill.child("a:solidFill") ?: fill.child("a:gradFill") ?: return false
+ fun colorOf(holder: OoxmlNode): Int? {
+ holder.child("a:schemeClr")?.let { sc -> if (sc.attr("val") == "phClr" && phClr != null) return withMods(phClr, sc) }
+ return solidFillColor(holder, theme)
+ }
+ when (node.name) {
+ "a:solidFill" -> { canvas.drawColor(colorOf(node) ?: return false); return true }
+ "a:gradFill" -> {
+ val stops = node.find("a:gsLst")?.childrenNamed("a:gs").orEmpty().mapNotNull { gs ->
+ val c = colorOf(gs) ?: return@mapNotNull null
+ ((gs.attr("pos")?.toFloatOrNull() ?: 0f) / 100000f).coerceIn(0f, 1f) to c
+ }.sortedBy { it.first }
+ if (stops.isEmpty()) return false
+ if (stops.size == 1) { canvas.drawColor(stops[0].second); return true }
+ // `<a:lin ang>` is in 60000ths of a degree, clockwise from left → right.
+ val angle = Math.toRadians(((node.child("a:lin")?.attr("ang")?.toFloatOrNull() ?: 5400000f) / 60000f).toDouble())
+ val half = (kotlin.math.abs(w * kotlin.math.cos(angle)) + kotlin.math.abs(h * kotlin.math.sin(angle))).toFloat() / 2f
+ val dx = (kotlin.math.cos(angle) * half).toFloat()
+ val dy = (kotlin.math.sin(angle) * half).toFloat()
+ val shader = android.graphics.LinearGradient(
+ w / 2f - dx, h / 2f - dy, w / 2f + dx, h / 2f + dy,
+ stops.map { it.second }.toIntArray(), stops.map { it.first }.toFloatArray(),
+ android.graphics.Shader.TileMode.CLAMP
+ )
+ canvas.drawRect(0f, 0f, w, h, Paint().apply { this.shader = shader })
+ return true
+ }
+ }
+ return false
}
/** `"type|idx"` → box, from a layout or master part. */
@@ -278,7 +338,7 @@ internal object PptxRenderer {
})
}
- shape.child("p:txBody")?.let { drawTextBody(canvas, it, box, ctx, placeholderType(shape), fill) }
+ shape.child("p:txBody")?.let { drawTextBody(canvas, it, box, ctx, placeholderType(shape), fill, inheritanceOf(shape, ctx)) }
canvas.restore()
}
@@ -330,6 +390,45 @@ internal object PptxRenderer {
private fun placeholderType(shape: OoxmlNode): String? = shape.find("p:ph")?.attr("type")
+ /**
+ * What a placeholder's text inherits, lowest priority first: the master's text style for
+ * its kind, then the master placeholder, then the layout placeholder. Orphan placeholders
+ * (no counterpart on the layout) inherit from the master by type, as PowerPoint does.
+ */
+ private fun inheritanceOf(shape: OoxmlNode, ctx: SlideContext): TextInheritance {
+ val ph = shape.find("p:ph") ?: return TextInheritance(emptyList(), emptyList())
+ val type = ph.attr("type") ?: "obj"
+ val layoutSp = inheritedPlaceholder(ctx.layout, shape, byTypeOnly = false)
+ val masterSp = inheritedPlaceholder(ctx.master, shape, byTypeOnly = true)
+ val txStyles = ctx.master?.find("p:txStyles")
+ val style = when (type) {
+ "title", "ctrTitle" -> txStyles?.child("p:titleStyle")
+ "dt", "ftr", "sldNum", "hdr" -> txStyles?.child("p:otherStyle")
+ else -> txStyles?.child("p:bodyStyle")
+ }
+ return TextInheritance(
+ bodies = listOfNotNull(masterSp?.find("a:bodyPr"), layoutSp?.find("a:bodyPr")),
+ lists = listOfNotNull(style, masterSp?.find("a:lstStyle"), layoutSp?.find("a:lstStyle"))
+ )
+ }
+
+ /** The layout/master placeholder shape [shape] inherits from, by idx then by type. */
+ private fun inheritedPlaceholder(part: OoxmlNode?, shape: OoxmlNode, byTypeOnly: Boolean): OoxmlNode? {
+ val ph = shape.find("p:ph") ?: return null
+ val tree = part?.find("p:spTree") ?: return null
+ val type = ph.attr("type") ?: "obj"
+ val idx = ph.attr("idx")?.takeIf { it != "4294967295" }
+ val shapes = tree.childrenNamed("p:sp")
+ if (!byTypeOnly && idx != null) shapes.firstOrNull { it.find("p:ph")?.attr("idx") == idx }?.let { return it }
+ val wanted = when (type) {
+ "title", "ctrTitle" -> setOf("title", "ctrTitle")
+ "body", "obj", "subTitle" -> if (byTypeOnly) setOf("body") else setOf(type)
+ else -> setOf(type)
+ }
+ if (!byTypeOnly && idx != null) return null
+ return shapes.firstOrNull { (it.find("p:ph")?.attr("type") ?: "obj") in wanted }
+ }
+
/** A shape's own `<a:xfrm>`, else the box its placeholder inherits from layout/master. */
private fun resolveBox(shape: OoxmlNode, ctx: SlideContext): Rect? {
shapeBox(shape)?.let { return it }
@@ -366,9 +465,19 @@ internal object PptxRenderer {
val theme: Map<String, Int>,
val slidePath: String,
val slideNumber: Int,
+ val layout: OoxmlNode?,
+ val master: OoxmlNode?,
val placeholders: Map<String, Rect>
)
+ /** Inherited text-box properties ([bodies]) and list styles ([lists]), lowest priority first. */
+ private class TextInheritance(val bodies: List<OoxmlNode>, val lists: List<OoxmlNode>) {
+ fun body(attr: String): String? = bodies.asReversed().firstNotNullOfOrNull { it.attr(attr) }
+ fun runAttr(level: Int, attr: String): String? = lists.asReversed().firstNotNullOfOrNull {
+ it.child("a:lvl${level + 1}pPr")?.child("a:defRPr")?.attr(attr)
+ }
+ }
+
/** Default point size when neither the run nor the placeholder says. */
private fun defaultSize(placeholder: String?): Float = when (placeholder) {
"title", "ctrTitle" -> 36f
@@ -383,24 +492,31 @@ internal object PptxRenderer {
box: Rect,
ctx: SlideContext,
placeholder: String?,
- behindColor: Int?
+ behindColor: Int?,
+ inherited: TextInheritance = TextInheritance(emptyList(), emptyList())
) {
val paragraphs = txBody.childrenNamed("a:p")
if (paragraphs.isEmpty()) return
+ val bodyPr = txBody.child("a:bodyPr")
+ fun bodyAttr(name: String) = bodyPr?.attr(name) ?: inherited.body(name)
+ fun insetPt(name: String, defaultEmu: Float) = (bodyAttr(name)?.toFloatOrNull() ?: defaultEmu) / EmuPerPoint
+ val lIns = insetPt("lIns", 91440f)
+ val rIns = insetPt("rIns", 91440f)
+ val tIns = insetPt("tIns", 45720f)
+ val bIns = insetPt("bIns", 45720f)
// Text over a filled shape has to stay legible against that fill, not against the slide.
val defaultInk = behindColor?.let { if (isLight(it)) Color.BLACK else Color.WHITE }
?: ctx.theme["tx1"] ?: Color.BLACK
- val inset = 6f
- val width = (box.width() - inset * 2).toInt().coerceAtLeast(24)
+ val width = (box.width() - lIns - rIns).toInt().coerceAtLeast(24)
val layouts = mutableListOf<Pair<StaticLayout, Float>>() // layout + its left indent
var totalHeight = 0f
for (paragraph in paragraphs) {
val level = paragraph.child("a:pPr")?.attr("lvl")?.toIntOrNull() ?: 0
val indent = level * 16f
- val (spanned, size) = buildParagraph(paragraph, ctx, defaultInk, placeholder)
+ val (spanned, size) = buildParagraph(paragraph, ctx, defaultInk, placeholder, inherited.runAttr(level, "cap"))
if (spanned.isEmpty()) { totalHeight += size * 0.6f; continue }
val paint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
@@ -419,26 +535,26 @@ internal object PptxRenderer {
}
if (layouts.isEmpty()) return
- // Vertical anchor. PowerPoint centres title placeholders by default, which is why an
- // uncentred render of a title slide looks subtly wrong even when every word is right.
- val anchor = txBody.child("a:bodyPr")?.attr("anchor")
+ // Vertical anchor, inherited from the layout/master placeholder when the slide doesn't say
+ // (a master's title is usually centred). Text that outgrows its box overflows it, as in
+ // PowerPoint, instead of being clipped: a box starting above the slide still shows its text.
+ val anchor = bodyAttr("anchor")
?: if (placeholder == "title" || placeholder == "ctrTitle") "ctr" else "t"
+ val innerTop = box.top + tIns
+ val innerHeight = box.height() - tIns - bIns
var y = when (anchor) {
- "ctr" -> box.top + (box.height() - totalHeight) / 2f
- "b" -> box.bottom - totalHeight
- else -> box.top + inset
- }.coerceAtLeast(box.top)
+ "ctr" -> innerTop + (innerHeight - totalHeight) / 2f
+ "b" -> box.bottom - bIns - totalHeight
+ else -> innerTop
+ }
- canvas.save()
- canvas.clipRect(box.left, box.top, box.right, box.bottom)
for ((layout, indent) in layouts) {
canvas.save()
- canvas.translate(box.left + inset + indent, y)
+ canvas.translate(box.left + lIns + indent, y)
layout.draw(canvas)
canvas.restore()
y += layout.height + layout.paint.textSize * 0.25f
}
- canvas.restore()
}
/** One `<a:p>` → styled text plus the size its first run asked for (used for spacing). */
@@ -446,7 +562,8 @@ internal object PptxRenderer {
paragraph: OoxmlNode,
ctx: SlideContext,
defaultInk: Int,
- placeholder: String?
+ placeholder: String?,
+ inheritedCap: String? = null
): Pair<SpannableStringBuilder, Float> {
val out = SpannableStringBuilder()
var firstSize = 0f
@@ -473,9 +590,12 @@ internal object PptxRenderer {
ctx.slideNumber.toString()
} else raw
if (value.isEmpty()) continue
+ // `cap="all"` (often inherited from the master's title style) shows capitals.
+ val cap = node.child("a:rPr")?.attr("cap") ?: inheritedCap
+ val shown = if (cap == "all" || cap == "small") value.uppercase() else value
val start = out.length
- out.append(value)
+ out.append(shown)
val end = out.length
val size = rPr?.attr("sz")?.toFloatOrNull()?.div(100f)?.coerceIn(4f, 200f)
@@ -609,6 +729,21 @@ internal object PptxRenderer {
var g = Color.green(base) / 255f
var b = Color.blue(base) / 255f
+ node.child("a:tint")?.attr("val")?.toFloatOrNull()?.let { v ->
+ val t = v / 100000f
+ r = r * t + (1f - t); g = g * t + (1f - t); b = b * t + (1f - t)
+ }
+ node.child("a:shade")?.attr("val")?.toFloatOrNull()?.let { v ->
+ val f = v / 100000f
+ r *= f; g *= f; b *= f
+ }
+ node.child("a:satMod")?.attr("val")?.toFloatOrNull()?.let { v ->
+ val hsv = FloatArray(3)
+ Color.RGBToHSV(Math.round(r.coerceIn(0f, 1f) * 255), Math.round(g.coerceIn(0f, 1f) * 255), Math.round(b.coerceIn(0f, 1f) * 255), hsv)
+ hsv[1] = (hsv[1] * v / 100000f).coerceIn(0f, 1f)
+ val c = Color.HSVToColor(hsv)
+ r = Color.red(c) / 255f; g = Color.green(c) / 255f; b = Color.blue(c) / 255f
+ }
node.child("a:lumMod")?.attr("val")?.toFloatOrNull()?.let { v ->
val f = v / 100000f
r *= f; g *= f; b *= f
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index f60a5a9..c3aaafd 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -330,7 +330,7 @@
<string name="form_fill_previous">Previous field</string>
<string name="form_fill_next">Next field</string>
<string name="tour_form_title">Fill the form on the page</string>
- <string name="tour_form_message">Tap a highlighted field to type, tick or choose. It saves in the form\'s own style.</string>
+ <string name="tour_form_message">Tap any field to type, tick or choose, right on the page. It saves in the form\'s own style.</string>
<string name="text_edit_hint_selection">Only the selected text changes, in the document\'s own font. The rest of the line moves to fit.</string>
<string name="text_edit_original">Original: %1$s</string>
<string name="not_now">Not now</string>
@@ -784,7 +784,11 @@
<string name="whats_new_edit_title">Edit PDF text</string>
<string name="whats_new_edit_desc">Select words and tap Edit text, or tap a line with the Text tool. Only what you change is rewritten, in the document\'s own font.</string>
<string name="whats_new_forms_title">Fill forms on the page</string>
- <string name="whats_new_forms_desc">In Edit mode, tap a form field to type, tick or choose right where it\'s printed.</string>
+ <string name="whats_new_forms_desc">Tap any form field to type, tick or choose right where it\'s printed, with Liquid Glass fields, dropdowns and list boxes.</string>
+ <string name="whats_new_zoom_title">Sharp at any zoom</string>
+ <string name="whats_new_zoom_desc">PDFs, Word and PowerPoint files stay crisp when you zoom in.</string>
+ <string name="whats_new_window_title">Its own window</string>
+ <string name="whats_new_window_desc">Files opened from WhatsApp or a file manager open in a separate ClearPDF window.</string>
<string name="whats_new_glass_title">Liquid Glass settings</string>
<string name="whats_new_glass_desc">Tune blur, refraction and tint, or pick a preset.</string>
<string name="whats_new_share_title">Share in more formats</string>
@@ -794,7 +798,7 @@
<string name="whats_new_sheets_title">Hindi and Indic spreadsheets</string>
<string name="whats_new_sheets_desc">Every script displays, edits and saves correctly.</string>
<string name="whats_new_fixes_title">Fixes</string>
- <string name="whats_new_fixes_desc">Images open reliably, and resized text stays where you put it.</string>
+ <string name="whats_new_fixes_desc">PowerPoint titles no longer get cut off, images open reliably, and resized text stays where you put it.</string>
<string name="whats_new_continue">Continue</string>
<string name="tour_edit_text_title">Edit the PDF\'s own text</string>
<string name="tour_edit_text_message">Tap the edit icon and pick Text, then tap any line to rewrite it in its own font. Or long-press a word and tap Edit text.</string>
diff --git a/app/src/play/java/com/chethan616/clearpdf/office/OfficeEngineFlavor.kt b/app/src/play/java/com/chethan616/clearpdf/office/OfficeEngineFlavor.kt
index 70b490c..c0d4226 100644
--- a/app/src/play/java/com/chethan616/clearpdf/office/OfficeEngineFlavor.kt
+++ b/app/src/play/java/com/chethan616/clearpdf/office/OfficeEngineFlavor.kt
@@ -28,6 +28,7 @@ import java.util.zip.ZipFile
* ~190 MB library is not kept twice.
*/
internal object OfficeEngineFlavor {
+ const val available: Boolean = true
fun createInstaller(context: Context): OfficeEngineInstaller = PlayOfficeEngineInstaller(context)
}
diff --git a/app/src/test/java/com/chethan616/clearpdf/office/PptxPlaceholderFixTest.kt b/app/src/test/java/com/chethan616/clearpdf/office/PptxPlaceholderFixTest.kt
new file mode 100644
index 0000000..9e51115
--- /dev/null
+++ b/app/src/test/java/com/chethan616/clearpdf/office/PptxPlaceholderFixTest.kt
@@ -0,0 +1,82 @@
+package com.chethan616.clearpdf.office
+
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.io.File
+import java.util.zip.ZipEntry
+import java.util.zip.ZipFile
+import java.util.zip.ZipOutputStream
+
+/**
+ * #29: a title placeholder the slide's layout doesn't have (a title on a Blank layout) must carry
+ * the master's anchor and title style before LibreOffice sees it, or LibreOffice pins it to the top
+ * of a box that starts above the slide and the title is cut off.
+ */
+class PptxPlaceholderFixTest {
+
+ private val ns = """xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships""""
+
+ private val master = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<p:sldMaster $ns><p:cSld><p:spTree>
+<p:sp><p:nvSpPr><p:cNvPr id="2" name="Title"/><p:cNvSpPr/><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr>
+<p:spPr><a:xfrm><a:off x="684212" y="4487332"/><a:ext cx="8534400" cy="1507067"/></a:xfrm></p:spPr>
+<p:txBody><a:bodyPr lIns="91440" tIns="45720" anchor="ctr"/><a:lstStyle/><a:p><a:r><a:t>Title</a:t></a:r></a:p></p:txBody></p:sp>
+</p:spTree></p:cSld>
+<p:txStyles><p:titleStyle><a:lvl1pPr algn="l"><a:defRPr sz="3600" cap="all"/></a:lvl1pPr></p:titleStyle><p:bodyStyle/><p:otherStyle/></p:txStyles>
+</p:sldMaster>"""
+
+ private val blankLayout = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<p:sldLayout $ns><p:cSld name="Blank"><p:spTree/></p:cSld></p:sldLayout>"""
+
+ private fun slide(withLayoutTitle: Boolean) = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<p:sld $ns><p:cSld><p:spTree>
+<p:sp><p:nvSpPr><p:cNvPr id="3" name="Rectangle 2"/><p:cNvSpPr/><p:nvPr><p:ph type="title" idx="4294967295"/></p:nvPr></p:nvSpPr>
+<p:spPr><a:xfrm><a:off x="1809130" y="-339928"/><a:ext cx="7766050" cy="1177926"/></a:xfrm></p:spPr>
+<p:txBody><a:bodyPr><a:normAutofit/></a:bodyPr><a:lstStyle/><a:p><a:r><a:rPr sz="3200"/><a:t>Pregled relevantnih standarda</a:t></a:r></a:p></p:txBody></p:sp>
+</p:spTree></p:cSld></p:sld>""".let { if (withLayoutTitle) it else it }
+
+ private fun rels(target: String) = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="x" Target="$target"/></Relationships>"""
+
+ private fun deck(layout: String): File {
+ val f = File.createTempFile("deck", ".pptx")
+ ZipOutputStream(f.outputStream()).use { z ->
+ fun put(n: String, s: String) { z.putNextEntry(ZipEntry(n)); z.write(s.toByteArray()); z.closeEntry() }
+ put("ppt/slides/slide1.xml", slide(false))
+ put("ppt/slides/_rels/slide1.xml.rels", rels("../slideLayouts/slideLayout1.xml"))
+ put("ppt/slideLayouts/slideLayout1.xml", layout)
+ put("ppt/slideLayouts/_rels/slideLayout1.xml.rels", rels("../slideMasters/slideMaster1.xml"))
+ put("ppt/slideMasters/slideMaster1.xml", master)
+ put("ppt/media/image1.png", "not really a png")
+ }
+ return f
+ }
+
+ private fun slideXml(f: File) = ZipFile(f).use { z -> z.getInputStream(z.getEntry("ppt/slides/slide1.xml")).readBytes().decodeToString() }
+
+ @Test fun orphanTitleInheritsTheMastersAnchorAndTitleStyle() {
+ val f = deck(blankLayout)
+ assertTrue(PptxPlaceholderFix.apply(f))
+ val xml = slideXml(f)
+ assertTrue(xml, Regex("""<a:bodyPr[^>]*anchor="ctr"""").containsMatchIn(xml))
+ assertTrue(xml, xml.contains("tIns=\"45720\""))
+ assertTrue(xml, Regex("""<a:lvl1pPr[^>]*><a:defRPr[^>]*cap="all"""").containsMatchIn(xml))
+ // The slide's own size and box still win.
+ assertTrue(xml.contains("sz=\"3200\""))
+ assertTrue(xml.contains("y=\"-339928\""))
+ // Untouched parts are copied through byte for byte.
+ ZipFile(f).use { z -> assertTrue(z.getInputStream(z.getEntry("ppt/media/image1.png")).readBytes().decodeToString() == "not really a png") }
+ f.delete()
+ }
+
+ @Test fun placeholderTheLayoutHasIsLeftAlone() {
+ val layoutWithTitle = blankLayout.replace(
+ "<p:spTree/>",
+ """<p:spTree><p:sp><p:nvSpPr><p:cNvPr id="2" name="T"/><p:cNvSpPr/><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p/></p:txBody></p:sp></p:spTree>"""
+ )
+ val f = deck(layoutWithTitle)
+ assertFalse(PptxPlaceholderFix.apply(f))
+ f.delete()
+ }
+}
diff --git a/fastlane/metadata/android/en-US/changelogs/6.txt b/fastlane/metadata/android/en-US/changelogs/6.txt
new file mode 100644
index 0000000..6340fb0
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/6.txt
@@ -0,0 +1,6 @@
+• Fill PDF forms right on the page with Liquid Glass fields, checkboxes, dropdowns and list boxes
+• Edit only the text you select, in the document's own font
+• Sharp text at any zoom in PDFs, Word and PowerPoint files
+• Files opened from other apps open in their own window
+• PowerPoint titles no longer cut off at the top
+• Springier buttons and menus, and a What's New screen
diff --git a/fastlane/metadata/android/en-US/full_description.txt b/fastlane/metadata/android/en-US/full_description.txt
new file mode 100644
index 0000000..d19b566
--- /dev/null
+++ b/fastlane/metadata/android/en-US/full_description.txt
@@ -0,0 +1,32 @@
+<p><b>ClearPDF</b> is a free, open-source PDF reader and editor for Android with a Liquid Glass interface. Your documents are processed on your device: there are no ads, no accounts and no uploads.</p>
+
+<p><b>Read and edit PDFs</b></p>
+<ul>
+<li>Fast continuous reading, search, page bookmarks, auto-scroll and a dark mode for pages</li>
+<li>Sharp text at any zoom level</li>
+<li>Edit a PDF's own text in place, in its original font</li>
+<li>Fill PDF forms right on the page: text fields, checkboxes, radio buttons, dropdowns and list boxes</li>
+<li>Highlight, underline, strike through, draw, add shapes, text boxes, notes, images and signatures</li>
+<li>Select and copy text, with a loupe; OCR for scanned pages</li>
+</ul>
+
+<p><b>PDF tools</b></p>
+<ul>
+<li>Merge, split, extract and organize pages; compress; add page numbers and watermarks</li>
+<li>Encrypt and decrypt; flatten forms; export pages as images or text</li>
+<li>Create PDFs from images, text, web pages and scans</li>
+</ul>
+
+<p><b>Office and images</b></p>
+<ul>
+<li>Open Word, PowerPoint and text documents; edit Excel (XLSX) spreadsheets and save them back</li>
+<li>Image editor: crop, adjust, filters and drawing</li>
+</ul>
+
+<p><b>Make it yours</b></p>
+<ul>
+<li>Tune the Liquid Glass look (blur, refraction, tint and more) or pick a preset</li>
+<li>Haptics you can switch off; English, Spanish, Italian, Portuguese and Russian</li>
+</ul>
+
+<p>Files opened from other apps open in their own ClearPDF window. The only network use is converting a web address you enter to PDF.</p>
diff --git a/fastlane/metadata/android/en-US/images/featureGraphic.png b/fastlane/metadata/android/en-US/images/featureGraphic.png
new file mode 100644
index 0000000..be0f2ab
Binary files /dev/null and b/fastlane/metadata/android/en-US/images/featureGraphic.png differ
diff --git a/fastlane/metadata/android/en-US/images/icon.png b/fastlane/metadata/android/en-US/images/icon.png
new file mode 100644
index 0000000..242a025
Binary files /dev/null and b/fastlane/metadata/android/en-US/images/icon.png differ
diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/1.jpg b/fastlane/metadata/android/en-US/images/phoneScreenshots/1.jpg
new file mode 100644
index 0000000..8bc444c
Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/1.jpg differ
diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/2.jpg b/fastlane/metadata/android/en-US/images/phoneScreenshots/2.jpg
new file mode 100644
index 0000000..3f9dc27
Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/2.jpg differ
diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/3.jpg b/fastlane/metadata/android/en-US/images/phoneScreenshots/3.jpg
new file mode 100644
index 0000000..ccc4ecb
Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/3.jpg differ
diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/4.jpg b/fastlane/metadata/android/en-US/images/phoneScreenshots/4.jpg
new file mode 100644
index 0000000..71dcf7e
Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/4.jpg differ
diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/5.jpg b/fastlane/metadata/android/en-US/images/phoneScreenshots/5.jpg
new file mode 100644
index 0000000..2fd5073
Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/5.jpg differ
diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/6.jpg b/fastlane/metadata/android/en-US/images/phoneScreenshots/6.jpg
new file mode 100644
index 0000000..1e1fc7b
Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/6.jpg differ
diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/7.jpg b/fastlane/metadata/android/en-US/images/phoneScreenshots/7.jpg
new file mode 100644
index 0000000..a73f1c4
Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/7.jpg differ
diff --git a/fastlane/metadata/android/en-US/short_description.txt b/fastlane/metadata/android/en-US/short_description.txt
new file mode 100644
index 0000000..e35f0cc
--- /dev/null
+++ b/fastlane/metadata/android/en-US/short_description.txt
@@ -0,0 +1 @@
+Open-source PDF reader and editor: edit text, fill forms, sign, scan, convert
diff --git a/fastlane/metadata/android/en-US/title.txt b/fastlane/metadata/android/en-US/title.txt
new file mode 100644
index 0000000..a9d709d
--- /dev/null
+++ b/fastlane/metadata/android/en-US/title.txt
@@ -0,0 +1 @@
+ClearPDF
diff --git a/fdroid/com.chethan616.clearpdf.yml b/fdroid/com.chethan616.clearpdf.yml
new file mode 100644
index 0000000..d70d549
--- /dev/null
+++ b/fdroid/com.chethan616.clearpdf.yml
@@ -0,0 +1,48 @@
+Categories:
+ - Reading
+ - Writing
+License: MIT
+AuthorName: Chethan616
+SourceCode: https://github.com/Chethan616/ClearPDF
+IssueTracker: https://github.com/Chethan616/ClearPDF/issues
+Changelog: https://github.com/Chethan616/ClearPDF/releases
+
+AutoName: ClearPDF
+
+RepoType: git
+Repo: https://github.com/Chethan616/ClearPDF.git
+
+# The `fdroid` product flavor is free software only: no Google Play services / ML Kit (the
+# document scanner uses the camera app, OCR uses Tesseract4Android, background removal is not
+# offered) and no downloaded Office engine. Network is used only to convert a web address the
+# user enters to PDF. Store text and images come from fastlane/metadata/android.
+#
+# Tesseract4Android (Apache-2.0) is built from source (srclib) and published to mavenLocal in
+# place of the JitPack artifact. pdf-core and ocr-core use a JDK 21 toolchain.
+
+Builds:
+ - versionName: 2.1.1
+ versionCode: 6
+ commit: v5.1
+ subdir: app
+ sudo:
+ - apt-get update
+ - apt-get install -y -t bookworm-backports openjdk-21-jdk-headless
+ - update-java-alternatives -a
+ gradle:
+ - fdroid
+ srclibs:
+ prebuild:
+ - sed -i -e '/jitpack.io/d' -e 's/mavenCentral()/mavenCentral()\n mavenLocal()/'
+ ../settings.gradle.kts
+ - sed -i -e 's/group = "cz.adaptech.tesseract4android"/group = "cz.adaptech"/' ../gradle/libs.versions.toml
+ - pushd $$tesseract4android$$
+ - gradle publishToMavenLocal -x test -x lint
+ - popd
+ ndk: r27c
+
+AutoUpdateMode: Version
+UpdateCheckMode: Tags ^v[\d.]+$
+CurrentVersion: 2.1.1
+CurrentVersionCode: 6
diff --git a/ocr-core/build.gradle.kts b/ocr-core/build.gradle.kts
index 8a3927f..a951a0a 100644
--- a/ocr-core/build.gradle.kts
+++ b/ocr-core/build.gradle.kts
@@ -38,9 +38,8 @@ dependencies {
implementation(libs.androidx.core.ktx)
implementation(libs.kotlinx.coroutines.core)
- // Bundled (no Play Services / no network) on-device OCR — primary engine.
- // See THIRD_PARTY_NOTICES.md.
- implementation(libs.mlkit.text.recognition)
+ // The bundled ML Kit engine is supplied by the app's play / foss builds (OcrServiceImpl's
+ // `primary`); this module stays free software so the F-Droid build can use it as is.
// Fully open-source (Apache-2.0) offline OCR fallback for devices where the
// bundled ML Kit model fails to initialize. See THIRD_PARTY_NOTICES.md.
diff --git a/ocr-core/src/main/java/com/kyant/ocrcore/OcrServiceImpl.kt b/ocr-core/src/main/java/com/kyant/ocrcore/OcrServiceImpl.kt
index 6826584..12e624a 100644
--- a/ocr-core/src/main/java/com/kyant/ocrcore/OcrServiceImpl.kt
+++ b/ocr-core/src/main/java/com/kyant/ocrcore/OcrServiceImpl.kt
@@ -5,23 +5,27 @@ import android.graphics.Bitmap
import android.util.Log
/**
- * Prefers the bundled ML Kit engine (higher real-world accuracy, small footprint);
- * transparently falls back to the fully open-source Tesseract4Android engine if ML Kit
- * fails to initialize or throws during recognition (e.g. on a device whose OEM image is
- * missing pieces ML Kit's TFLite runtime needs). Both engines are 100% on-device.
+ * Uses [primary] when the build supplies one (the play / foss builds pass the bundled ML Kit
+ * engine: higher real-world accuracy, small footprint) and transparently falls back to the fully
+ * open-source Tesseract4Android engine if it fails to initialize or throws during recognition
+ * (e.g. on a device whose OEM image is missing pieces ML Kit's TFLite runtime needs). The F-Droid
+ * build passes none and uses Tesseract only. Every engine is 100% on-device.
*/
-class OcrServiceImpl : OcrService {
+class OcrServiceImpl(
+ private val primary: (suspend (Bitmap) -> OcrPageResult)? = null
+) : OcrService {
- /** Sticky per-process: once ML Kit is confirmed broken on this device, stop retrying it. */
- @Volatile private var mlKitKnownBroken = false
+ /** Sticky per-process: once the primary engine is confirmed broken on this device, stop retrying it. */
+ @Volatile private var primaryKnownBroken = false
override suspend fun recognize(context: Context, bitmap: Bitmap): OcrPageResult {
- if (!mlKitKnownBroken) {
- runCatching { MlKitOcrEngine.recognize(bitmap) }
+ val engine = primary
+ if (engine != null && !primaryKnownBroken) {
+ runCatching { engine(bitmap) }
.onSuccess { return it }
.onFailure { e ->
- Log.w(TAG, "ML Kit OCR unavailable, falling back to Tesseract4Android", e)
- mlKitKnownBroken = true
+ Log.w(TAG, "Primary OCR engine unavailable, falling back to Tesseract4Android", e)
+ primaryKnownBroken = true
}
}
return TesseractOcrEngine.recognize(context, bitmap)
diff --git a/pdf-core/src/main/java/com/kyant/pdfcore/form/PdfFormWidgets.kt b/pdf-core/src/main/java/com/kyant/pdfcore/form/PdfFormWidgets.kt
index 09ec53a..5a5404c 100644
--- a/pdf-core/src/main/java/com/kyant/pdfcore/form/PdfFormWidgets.kt
+++ b/pdf-core/src/main/java/com/kyant/pdfcore/form/PdfFormWidgets.kt
@@ -11,6 +11,7 @@ import com.tom_roush.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDCheckBox
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDChoice
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDField
+import com.tom_roush.pdfbox.pdmodel.interactive.form.PDListBox
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDNonTerminalField
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDRadioButton
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDTextField
@@ -30,8 +31,9 @@ data class PdfFormWidget(
val right: Float,
val bottom: Float,
val value: String,
- /** Choice fields: what the list shows. */
+ /** Choice fields: what the list shows, and the value each option saves ([optionValues]). */
val options: List<String> = emptyList(),
+ val optionValues: List<String> = emptyList(),
/** Checkbox / radio: the value this box sets when on. */
val onValue: String = "",
/** From the field's default appearance: points (0 = auto-size) and as a fraction of page height. */
@@ -48,7 +50,14 @@ data class PdfFormWidget(
/** The page's display height in points, to turn point sizes and paddings into pixels. */
val pageHeightPt: Float = 792f
) {
- enum class Type { TEXT, CHECKBOX, RADIO, CHOICE }
+ /** CHOICE is a dropdown (combo box); LIST is a scrolling list box. */
+ enum class Type { TEXT, CHECKBOX, RADIO, CHOICE, LIST }
+
+ /** What the box shows for a saved [v]alue (an option's label, for choice fields). */
+ fun displayOf(v: String): String {
+ val i = optionValues.indexOf(v)
+ return if (i >= 0) options.getOrElse(i) { v } else v
+ }
/** Unique per box: radio groups and repeated fields share a name. */
val key: String get() = "$fieldName#$pageIndex#${(left * 10000).toInt()}#${(top * 10000).toInt()}"
@@ -98,10 +107,13 @@ object PdfFormWidgets {
?.let { out += it.copy(onValue = on) }
}
is PDChoice -> field.widgets.forEach { w ->
- val options = runCatching { field.optionsDisplayValues }.getOrNull().orEmpty()
- .ifEmpty { runCatching { field.optionsExportValues }.getOrNull().orEmpty() }
- widget(doc, w, pageOf, field.fullyQualifiedName, PdfFormWidget.Type.CHOICE, field.valueAsString.orEmpty().trim('[', ']'), field)
- ?.let { out += it.copy(options = options) }
+ val exports = runCatching { field.optionsExportValues }.getOrNull().orEmpty()
+ val labels = runCatching { field.optionsDisplayValues }.getOrNull().orEmpty().ifEmpty { exports }
+ val values = exports.ifEmpty { labels }
+ val type = if (field is PDListBox) PdfFormWidget.Type.LIST else PdfFormWidget.Type.CHOICE
+ val current = runCatching { field.value }.getOrNull()?.firstOrNull().orEmpty()
+ widget(doc, w, pageOf, field.fullyQualifiedName, type, current, field)
+ ?.let { out += it.copy(options = labels, optionValues = values) }
}
else -> Unit // push buttons, signatures
}
diff --git a/pdf-core/src/main/java/com/kyant/pdfcore/viewer/PdfViewer.kt b/pdf-core/src/main/java/com/kyant/pdfcore/viewer/PdfViewer.kt
index 25cf588..ffb3ad1 100644
--- a/pdf-core/src/main/java/com/kyant/pdfcore/viewer/PdfViewer.kt
+++ b/pdf-core/src/main/java/com/kyant/pdfcore/viewer/PdfViewer.kt
@@ -33,6 +33,21 @@ interface PdfViewer {
*/
fun renderPage(document: PdfDocument, pageIndex: Int, width: Int, rotationDegrees: Int = 0): Bitmap?
+ /**
+ * Render only [region] (normalized 0..1 of the page) of [pageIndex] into a [outWidth] x
+ * [outHeight] bitmap, as if the whole page were [pageWidthPx] wide. This is how a zoomed-in
+ * viewer stays sharp: the visible part of the page at exact screen resolution, instead of a
+ * whole-page bitmap stretched (or a whole page at 5x, which no phone has the memory for).
+ */
+ fun renderRegion(
+ document: PdfDocument,
+ pageIndex: Int,
+ region: android.graphics.RectF,
+ pageWidthPx: Float,
+ outWidth: Int,
+ outHeight: Int
+ ): Bitmap? = null
+
/**
* Return the natural size (in PDF points) of [pageIndex], or `null` on failure.
*/
@@ -134,6 +149,39 @@ class PdfViewerImpl : PdfViewer {
}
}
+ override fun renderRegion(
+ document: PdfDocument,
+ pageIndex: Int,
+ region: android.graphics.RectF,
+ pageWidthPx: Float,
+ outWidth: Int,
+ outHeight: Int
+ ): Bitmap? = lock.withLock {
+ val renderer = renderers[document.uri] ?: return null
+ if (pageIndex < 0 || pageIndex >= renderer.pageCount || outWidth <= 0 || outHeight <= 0) return null
+ val page = try { renderer.openPage(pageIndex) } catch (t: Throwable) { return@withLock null }
+ var bitmap: Bitmap? = null
+ try {
+ val srcW = page.width.toFloat().coerceAtLeast(1f)
+ val srcH = page.height.toFloat().coerceAtLeast(1f)
+ val s = pageWidthPx / srcW
+ val pageHeightPx = srcH * s
+ bitmap = Bitmap.createBitmap(outWidth, outHeight, Bitmap.Config.ARGB_8888)
+ bitmap.eraseColor(android.graphics.Color.WHITE)
+ val matrix = Matrix().apply {
+ postScale(s, s)
+ postTranslate(-region.left * pageWidthPx, -region.top * pageHeightPx)
+ }
+ page.render(bitmap, null, matrix, android.graphics.pdf.PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
+ bitmap
+ } catch (t: Throwable) {
+ bitmap?.recycle()
+ null
+ } finally {
+ runCatching { page.close() }
+ }
+ }
+
override fun pageSize(document: PdfDocument, pageIndex: Int): Size? = lock.withLock {
val renderer = renderers[document.uri] ?: return null
if (pageIndex < 0 || pageIndex >= renderer.pageCount) return null