reduce app sizes
- Commit
258d619f176b4a12942968f512823ee24ee3a715- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-25 03:22 UTC (4 months ago)
- Parents
c56d667
Diff
camera/build.gradle.kts
diff --git a/camera/build.gradle.kts b/camera/build.gradle.ktsindex 73c305f0c3..a091dc2aec 100644--- a/camera/build.gradle.kts+++ b/camera/build.gradle.kts@@ -13,6 +13,12 @@ android { defaultConfig { applicationId = "com.vayunmathur.camera" }+ androidResources {+ // The ncnn-android AAR is generalist and also bundles the PP-OCRv5 OCR+ // models. Camera only uses PortraitSegmenter, so strip the OCR assets it+ // never loads (~8MB) from this APK.+ ignoreAssetsPattern = "!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~:PP_OCRv5_mobile_*"+ } // The Rust stitcher drops <abi>/libcamera_stitch.so under this dir; register // it as a jniLibs source so AGP packages the native lib. sourceSets["main"].jniLibs.directories.add(layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath)@@ -122,5 +128,7 @@ dependencies { implementation(libs.androidx.camera.extensions) implementation(libs.androidx.exifinterface) implementation(libs.zxing.core)- implementation(libs.mediapipe.tasks.vision)+ // On-device portrait segmentation via ncnn (Tencent, BSD-3, CPU-only). Forked+ // and published as an AAR through JitPack, same pattern as Stockfish-Library.+ implementation("com.github.vayun-mathur:ncnn-android:1.0.0") }
camera/src/main/AndroidManifest.xml
diff --git a/camera/src/main/AndroidManifest.xml b/camera/src/main/AndroidManifest.xmlindex 7a8806b25d..6dd6998c66 100644--- a/camera/src/main/AndroidManifest.xml+++ b/camera/src/main/AndroidManifest.xml@@ -5,7 +5,8 @@ <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />- <!-- MediaPipe's tasks-vision AAR merges INTERNET; vision runs on-device, so strip it. -->+ <!-- Camera vision runs fully on-device; strip any INTERNET/network permission a+ transitive dependency might merge in. --> <uses-permission android:name="android.permission.INTERNET" tools:node="remove" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" tools:node="remove" />
camera/src/main/assets/deeplabv3.tflite
diff --git a/camera/src/main/assets/deeplabv3.tflite b/camera/src/main/assets/deeplabv3.tflitedeleted file mode 100644index 420a934fdb..0000000000Binary files a/camera/src/main/assets/deeplabv3.tflite and /dev/null differ
camera/src/main/assets/selfie_segmenter.tflite
diff --git a/camera/src/main/assets/selfie_segmenter.tflite b/camera/src/main/assets/selfie_segmenter.tflitedeleted file mode 100644index a4ebd4777e..0000000000Binary files a/camera/src/main/assets/selfie_segmenter.tflite and /dev/null differ
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.ktindex 6e4ec34cf2..2ebea87863 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt@@ -19,6 +19,7 @@ import android.view.OrientationEventListener import android.view.Surface import androidx.camera.compose.CameraXViewfinder import androidx.camera.core.FocusMeteringAction+import androidx.camera.core.CameraSelector import androidx.camera.core.ImageAnalysis import androidx.camera.core.SurfaceOrientedMeteringPointFactory import androidx.camera.viewfinder.compose.MutableCoordinateTransformer@@ -401,10 +402,14 @@ fun CameraScreen( } // Owns the PORTRAIT bokeh segmenter so it is closed (and its mask recycled) on mode change.- // Also keyed on photoSessionActive so the analyzer re-attaches after a rebind.- DisposableEffect(cameraMode, photoSessionActive) {+ // Keyed on photoSessionActive (re-attach after a rebind) and lensFacing (front/back changes+ // the frame orientation/mirroring the analyzer must apply).+ DisposableEffect(cameraMode, photoSessionActive, lensFacing) { val analyzer = if (cameraMode == CameraMode.PORTRAIT) {- BokehAnalyzer(context) { mask ->+ BokehAnalyzer(+ context,+ isFrontFacing = lensFacing == CameraSelector.LENS_FACING_FRONT+ ) { mask -> maskBitmap?.recycle() maskBitmap = mask }.also {
camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt b/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.ktindex 752d0bb5f4..23005825f2 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt@@ -3,86 +3,83 @@ package com.vayunmathur.camera.util import android.content.Context import android.graphics.Bitmap import android.graphics.Color+import android.graphics.Matrix+import android.util.Log import androidx.camera.core.ImageAnalysis import androidx.camera.core.ImageProxy-import com.google.mediapipe.framework.image.BitmapImageBuilder-import com.google.mediapipe.framework.image.ByteBufferExtractor-import com.google.mediapipe.tasks.core.BaseOptions-import com.google.mediapipe.tasks.vision.core.RunningMode-import com.google.mediapipe.tasks.vision.imagesegmenter.ImageSegmenter+import com.vayunmathur.ncnn.PortraitSegmenter -private const val PERSON_CLASS = 15 // "person" in DeepLabV3's 21-class Pascal VOC labels private const val TEMPORAL_WEIGHT = 0.35f class BokehAnalyzer( context: Context,+ private val isFrontFacing: Boolean = false, private val onMaskGenerated: (Bitmap) -> Unit ) : ImageAnalysis.Analyzer { private var prevMask: FloatArray? = null- private val imageSegmenter: ImageSegmenter+ private val segmenter = PortraitSegmenter(context) - init {- val baseOptions = BaseOptions.builder()- .setModelAssetPath("deeplabv3.tflite")- .build()-- val options = ImageSegmenter.ImageSegmenterOptions.builder()- .setBaseOptions(baseOptions)- .setRunningMode(RunningMode.LIVE_STREAM)- .setOutputCategoryMask(true)- .setOutputConfidenceMasks(false)- .setResultListener { result, _ ->- val catMask = result.categoryMask()- if (!catMask.isPresent) return@setResultListener+ @androidx.annotation.OptIn(androidx.camera.core.ExperimentalGetImage::class)+ override fun analyze(imageProxy: ImageProxy) {+ try {+ // toBitmap() returns the raw sensor-oriented buffer; the preview is+ // shown in display orientation (and mirrored for the front camera).+ // Rotate/mirror the frame to match so the mask lines up instead of+ // coming out rotated 90°.+ val raw = imageProxy.toBitmap()+ val bitmap = orientToDisplay(raw, imageProxy.imageInfo.rotationDegrees) - val mpImage = catMask.get()- val w = mpImage.width- val h = mpImage.height- val buffer = ByteBufferExtractor.extract(mpImage)- buffer.rewind()+ // Synchronous forward pass; the analyzer runs on a background executor+ // with KEEP_ONLY_LATEST backpressure so blocking here is fine.+ val result = segmenter.segment(bitmap)+ if (bitmap !== raw) bitmap.recycle()+ raw.recycle()+ val w = result.width+ val h = result.height+ val current = result.mask // foreground probability in [0,1], row-major - val current = FloatArray(w * h)- for (i in current.indices) {- val label = buffer.get().toInt() and 0xFF- current[i] = if (label == PERSON_CLASS) 1f else 0f+ // Temporal smoothing: blend with previous frame.+ val prev = prevMask+ val smoothed = if (prev != null && prev.size == current.size) {+ FloatArray(current.size) { i ->+ current[i] * (1f - TEMPORAL_WEIGHT) + prev[i] * TEMPORAL_WEIGHT }+ } else current+ prevMask = smoothed - // Temporal smoothing: blend with previous frame- val prev = prevMask- val smoothed = if (prev != null && prev.size == current.size) {- FloatArray(current.size) { i ->- current[i] * (1f - TEMPORAL_WEIGHT) + prev[i] * TEMPORAL_WEIGHT- }- } else current- prevMask = smoothed+ // Gaussian blur the mask for soft edges.+ val blurred = blurMask(smoothed, w, h) - // Gaussian blur the mask for soft edges- val blurred = blurMask(smoothed, w, h)-- val pixels = IntArray(w * h)- for (i in pixels.indices) {- val alpha = (blurred[i].coerceIn(0f, 1f) * 255).toInt()- pixels[i] = Color.argb(alpha, 255, 255, 255)- }- val maskBitmap = Bitmap.createBitmap(pixels, w, h, Bitmap.Config.ARGB_8888)- onMaskGenerated(maskBitmap)+ val pixels = IntArray(w * h)+ for (i in pixels.indices) {+ val alpha = (blurred[i].coerceIn(0f, 1f) * 255).toInt()+ pixels[i] = Color.argb(alpha, 255, 255, 255) }- .build()-- imageSegmenter = ImageSegmenter.createFromOptions(context, options)+ val maskBitmap = Bitmap.createBitmap(pixels, w, h, Bitmap.Config.ARGB_8888)+ onMaskGenerated(maskBitmap)+ } catch (e: Throwable) {+ Log.e("BokehAnalyzer", "segmentation failed", e)+ } finally {+ imageProxy.close()+ } } - @androidx.annotation.OptIn(androidx.camera.core.ExperimentalGetImage::class)- override fun analyze(imageProxy: ImageProxy) {- val bitmap = imageProxy.toBitmap()- val mpImage = BitmapImageBuilder(bitmap).build()- imageSegmenter.segmentAsync(mpImage, imageProxy.imageInfo.timestamp)- imageProxy.close()+ fun close() {+ segmenter.close() } - fun close() {- imageSegmenter.close()+ /**+ * Rotate the sensor-oriented frame into display orientation (and mirror it+ * horizontally for the front camera) so the produced mask aligns with the+ * preview, which CameraX renders with that same transform.+ */+ private fun orientToDisplay(src: Bitmap, rotationDegrees: Int): Bitmap {+ if (rotationDegrees == 0 && !isFrontFacing) return src+ val matrix = Matrix()+ matrix.postRotate(rotationDegrees.toFloat())+ if (isFrontFacing) matrix.postScale(-1f, 1f) // preview mirrors the front lens+ return Bitmap.createBitmap(src, 0, 0, src.width, src.height, matrix, true) } private fun blurMask(src: FloatArray, w: Int, h: Int): FloatArray {
findfamily/build.gradle.kts
diff --git a/findfamily/build.gradle.kts b/findfamily/build.gradle.ktsindex a76d91e84a..d2d6c2f45a 100644--- a/findfamily/build.gradle.kts+++ b/findfamily/build.gradle.kts@@ -28,8 +28,8 @@ dependencies { implementation(libs.coil.compose) - // maplibre- implementation(libs.maplibre.compose)+ // Compose-native raster map (replaces maplibre; keeps spatialk coordinate types).+ implementation(project(":library:map")) // Public AOSP ranging API (android.ranging.*) is part of the framework // on Android 15+ — no third-party library needed. We intentionally avoid
findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.ktindex 636562436d..5db66add22 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt@@ -54,7 +54,6 @@ import com.vayunmathur.library.ui.Switch import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.ToggleFloatingActionButton import com.vayunmathur.library.ui.TopAppBar-import com.vayunmathur.library.ui.TopAppBarDefaults import com.vayunmathur.library.ui.dynamicLightColorScheme import com.vayunmathur.library.ui.rememberBottomSheetScaffoldState import com.vayunmathur.library.ui.rememberSliderState@@ -229,10 +228,9 @@ fun MainPage( sheetSwipeEnabled = !historyMode, sheetDragHandle = if (historyMode) null else { { BottomSheetDefaults.DragHandle() } }, sheetContainerColor = MaterialTheme.colorScheme.surfaceContainerLow,- // Transparent app bar so the map shows through behind it.+ // Default (solid) app bar so the map stays cut off beneath it while panning. topBar = { TopAppBar(- colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Transparent), title = { if (historyMode) { val historyUser by ffViewModel.userByIdState(selectedUserId!!)
findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.ktindex 66023d2ded..15b1505b43 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt@@ -49,14 +49,10 @@ import com.vayunmathur.findfamily.util.FindFamilyViewModel import com.vayunmathur.library.ui.invisibleClickable import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext-import org.maplibre.compose.camera.CameraPosition-import org.maplibre.compose.camera.CameraState-import org.maplibre.compose.map.GestureOptions-import org.maplibre.compose.map.MapOptions-import org.maplibre.compose.map.MaplibreMap-import org.maplibre.compose.map.OrnamentOptions-import org.maplibre.compose.style.BaseStyle-import org.maplibre.compose.util.ClickResult+import com.vayunmathur.library.map.CameraPosition+import com.vayunmathur.library.map.CameraState+import com.vayunmathur.library.map.RasterMap+import com.vayunmathur.library.map.TileSource import org.maplibre.spatialk.geojson.Position import kotlin.io.encoding.Base64 import kotlin.math.abs@@ -106,24 +102,11 @@ fun MapView( ) } }) {- MaplibreMap(- Modifier,- BaseStyle.Uri("https://tiles.openfreemap.org/styles/liberty"),- camera,- 0f..20f,- options = MapOptions(- gestureOptions = GestureOptions(- isRotateEnabled = false,- isScrollEnabled = true,- isTiltEnabled = false,- isZoomEnabled = true- ),- ornamentOptions = OrnamentOptions.AllDisabled- ),- onMapClick = { _, _ ->- onMapClick()- ClickResult.Pass- },+ RasterMap(+ cameraState = camera,+ tileSource = TileSource.CartoVoyager,+ zoomRange = 0f..20f,+ onMapClick = { onMapClick() }, ) if (initialized) {
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 3d9caf1c20..f17f9d1f57 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -73,6 +73,9 @@ cryptographyCore = "0.6.0" libphonenumber = "9.0.34" material3AdaptiveNavigationSuite = "1.5.0-alpha23" maplibre = "0.13.0"+# spatialk geojson types (pure-Kotlin Position/BoundingBox) — previously resolved+# transitively via maplibre-compose; pinned as a direct dep for :library:map.+spatialk = "0.7.0" foundation = "1.12.0-beta02" ink = "1.1.0-alpha04" protobuf = "4.36.0-RC1"@@ -80,7 +83,6 @@ keepassJava2 = "2.2.4" zxing = "3.5.4" bouncycastle = "1.85" onnxruntimeAndroid = "1.27.0"-tasksVision = "0.10.35" jakartaMail = "2.0.3" angusActivation = "2.0.2" jakartaActivationApi = "2.1.3"@@ -157,9 +159,9 @@ kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-t # Maps maplibre-compose = { module = "org.maplibre.compose:maplibre-compose", version.ref = "maplibre" }+spatialk-geojson = { module = "org.maplibre.spatialk:geojson", version.ref = "spatialk" } -# On-device ML segmentation (MediaPipe Tasks — standalone, no Play Services)-mediapipe-tasks-vision = { module = "com.google.mediapipe:tasks-vision", version.ref = "tasksVision" }+# On-device OCR # On-device OCR via ONNX Runtime (MIT, FOSS, no Play Services / no ML Kit). Runs # the PaddleOCR PP-OCR mobile detection + recognition models shipped as assets.
library/map/build.gradle.kts
diff --git a/library/map/build.gradle.kts b/library/map/build.gradle.ktsnew file mode 100644index 0000000000..0d10cc7e77--- /dev/null+++ b/library/map/build.gradle.kts@@ -0,0 +1,15 @@+plugins {+ id("common-conventions-library")+}++dependencies {+ implementation(libs.androidx.compose.foundation)++ // Tile fetching + memory/disk cache.+ implementation(libs.coil.compose)++ // Pure-Kotlin coordinate types (Position / BoundingBox) shared with the apps.+ api(libs.spatialk.geojson)++ testImplementation("junit:junit:4.13.2")+}
library/map/src/main/AndroidManifest.xml
diff --git a/library/map/src/main/AndroidManifest.xml b/library/map/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..d4d0c709a9--- /dev/null+++ b/library/map/src/main/AndroidManifest.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++ <!-- Raster tiles are fetched over HTTPS via Coil. -->+ <uses-permission android:name="android.permission.INTERNET" />+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />++</manifest>
library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt b/library/map/src/main/java/com/vayunmathur/library/map/CameraState.ktnew file mode 100644index 0000000000..17a6dc19aa--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt@@ -0,0 +1,138 @@+package com.vayunmathur.library.map++import androidx.compose.animation.core.Animatable+import androidx.compose.animation.core.tween+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.runtime.snapshotFlow+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import kotlinx.coroutines.flow.filterNotNull+import kotlinx.coroutines.flow.first+import org.maplibre.spatialk.geojson.Position+import kotlin.math.log2++/**+ * North-up camera position. Bearing/tilt are intentionally unsupported (the+ * three migrated apps only ever used a north-up basemap), so the axis-aligned+ * overlays and image quad stay correct.+ */+data class CameraPosition(+ val target: Position = Position(0.0, 0.0),+ val zoom: Double = 0.0,+)++/**+ * Holds the live [CameraPosition] (as Compose state so gestures/animations+ * drive recomposition) and derives a [Projection] once the viewport is+ * measured. Mirrors maplibre-compose's `CameraState` surface used by the apps:+ * [position], [projection], [awaitProjection], [animateTo].+ */+class CameraState(initial: CameraPosition = CameraPosition()) {+ var position: CameraPosition by mutableStateOf(initial)++ /** Viewport size in logical (dp) units; null until first layout. */+ internal var viewportDp: Size? by mutableStateOf(null)++ /**+ * Sets the measured viewport and enforces the minimum "fill" zoom so the map+ * always covers the viewport (no blank margins when zoomed all the way out),+ * matching maplibre's behavior.+ */+ internal fun setViewport(size: Size) {+ viewportDp = size+ val floor = fillZoom(size)+ if (position.zoom < floor) position = position.copy(zoom = floor)+ }++ /** Smallest zoom at which the world fills [vp]'s larger dimension. */+ private fun fillZoom(vp: Size): Double {+ val dim = maxOf(vp.width, vp.height).toDouble()+ if (dim <= 0.0) return 0.0+ return log2(dim / Mercator.TILE_SIZE).coerceAtLeast(0.0)+ }++ /** Current projection, or null before the viewport has been measured. */+ val projection: Projection?+ get() = viewportDp?.let { vp ->+ Projection(position.target, position.zoom, vp.width, vp.height)+ }++ /** Suspends until the viewport is measured, then returns the projection. */+ suspend fun awaitProjection(): Projection =+ snapshotFlow { projection }.filterNotNull().first()++ /** Linearly interpolate center + zoom to [target] over [durationMs]. */+ suspend fun animateTo(target: CameraPosition, durationMs: Int = 500) {+ val start = position+ Animatable(0f).animateTo(1f, tween(durationMs)) {+ val t = value.toDouble()+ position = CameraPosition(+ target = Position(+ lerp(start.target.longitude, target.target.longitude, t),+ lerp(start.target.latitude, target.target.latitude, t),+ ),+ zoom = lerp(start.zoom, target.zoom, t),+ )+ }+ }++ /**+ * Applies a transform gesture, anchoring the geographic point under+ * [centroidDp] so pinch-zoom keeps that point fixed. Deltas are in logical+ * (dp) units.+ */+ internal fun onGesture(+ centroidDp: Offset,+ panDp: Offset,+ zoomChange: Float,+ minZoom: Double,+ maxZoom: Double,+ scrollEnabled: Boolean,+ zoomEnabled: Boolean,+ ) {+ val vp = viewportDp ?: return+ val halfW = vp.width / 2.0+ val halfH = vp.height / 2.0+ // Never zoom out past a full-screen world.+ val effectiveMinZoom = maxOf(minZoom, fillZoom(vp))+ var zoom = position.zoom++ // Pan: dragging content one way shifts the world the same way, so the+ // center moves opposite to the pan.+ val cWorld = Mercator.project(position.target.longitude, position.target.latitude, zoom)+ var cx = cWorld.x+ var cy = cWorld.y+ if (scrollEnabled) {+ cx -= panDp.x+ cy -= panDp.y+ }+ var center = Mercator.unproject(cx, cy, zoom)++ // Zoom about the centroid: keep the geo point under the fingers fixed.+ if (zoomEnabled && zoomChange != 1f && zoomChange > 0f) {+ val newZoom = (zoom + log2(zoomChange.toDouble())).coerceIn(effectiveMinZoom, maxZoom)+ if (newZoom != zoom) {+ val cw = Mercator.project(center.longitude, center.latitude, zoom)+ val underX = cw.x + (centroidDp.x - halfW)+ val underY = cw.y + (centroidDp.y - halfH)+ val geo = Mercator.unproject(underX, underY, zoom)+ val gw = Mercator.project(geo.longitude, geo.latitude, newZoom)+ center = Mercator.unproject(gw.x - (centroidDp.x - halfW), gw.y - (centroidDp.y - halfH), newZoom)+ zoom = newZoom+ }+ }++ position = CameraPosition(center, zoom)+ }+}++private fun lerp(start: Double, end: Double, t: Double): Double = start + (end - start) * t++/** Remembers a [CameraState] seeded with [initial]. */+@Composable+fun rememberCameraState(initial: CameraPosition = CameraPosition()): CameraState =+ remember { CameraState(initial) }
library/map/src/main/java/com/vayunmathur/library/map/ImageOverlay.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/ImageOverlay.kt b/library/map/src/main/java/com/vayunmathur/library/map/ImageOverlay.ktnew file mode 100644index 0000000000..67bf6b8f5e--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/ImageOverlay.kt@@ -0,0 +1,16 @@+package com.vayunmathur.library.map++import androidx.compose.ui.graphics.ImageBitmap+import org.maplibre.spatialk.geojson.BoundingBox++/**+ * A georeferenced translucent image drawn over the basemap. Because the map is+ * north-up and axis-aligned, the [bitmap] is stretched into the screen rect of+ * [bounds]'s corners (see [RasterMap]). Replaces maplibre's+ * `RasterLayer` + `rememberImageSource` + `PositionQuad`.+ */+data class ImageOverlay(+ val bitmap: ImageBitmap,+ val bounds: BoundingBox,+ val opacity: Float = 1f,+)
library/map/src/main/java/com/vayunmathur/library/map/MapOptions.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapOptions.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapOptions.ktnew file mode 100644index 0000000000..d755004532--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapOptions.kt@@ -0,0 +1,36 @@+package com.vayunmathur.library.map++/**+ * Which pan/zoom gestures are enabled. Rotation and tilt are unsupported (the+ * map is always north-up), so there are no toggles for them.+ */+data class GestureOptions(+ val isScrollEnabled: Boolean = true,+ val isZoomEnabled: Boolean = true,+) {+ companion object {+ /** Pan + zoom enabled; rotation/tilt unsupported anyway. */+ val RotationLocked = GestureOptions(isScrollEnabled = true, isZoomEnabled = true)++ /** All gestures disabled (static map). */+ val AllDisabled = GestureOptions(isScrollEnabled = false, isZoomEnabled = false)+ }+}++/**+ * Map ornaments. Only the attribution label is supported. CARTO/OSM terms+ * require visible attribution, so leave it enabled unless the host renders its+ * own (e.g. weather shows attribution in its bottom panel).+ */+data class OrnamentOptions(+ val isAttributionEnabled: Boolean = true,+) {+ companion object {+ val AllDisabled = OrnamentOptions(isAttributionEnabled = false)+ }+}++data class MapOptions(+ val gestureOptions: GestureOptions = GestureOptions(),+ val ornamentOptions: OrnamentOptions = OrnamentOptions(),+)
library/map/src/main/java/com/vayunmathur/library/map/Mercator.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/Mercator.kt b/library/map/src/main/java/com/vayunmathur/library/map/Mercator.ktnew file mode 100644index 0000000000..d6819ea463--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/Mercator.kt@@ -0,0 +1,45 @@+package com.vayunmathur.library.map++import org.maplibre.spatialk.geojson.Position+import kotlin.math.PI+import kotlin.math.atan+import kotlin.math.ln+import kotlin.math.pow+import kotlin.math.sin+import kotlin.math.sinh++/** A point in Web-Mercator world pixels (logical, 256 px/tile). */+internal data class WorldPx(val x: Double, val y: Double)++/**+ * Standard Web Mercator with a 256-logical-px tile grid. All values are in+ * density-independent ("logical") pixels so callers can work in `Dp` and only+ * convert to device pixels when drawing. The projection is internally+ * consistent with [RasterMap]'s tile rendering (both use this object), so+ * overlays pin exactly to the basemap regardless of device density.+ */+internal object Mercator {+ const val TILE_SIZE = 256.0++ /** Total map width/height in logical px at [zoom]. */+ fun worldSize(zoom: Double): Double = TILE_SIZE * 2.0.pow(zoom)++ /** Project lon/lat (degrees) to world px at [zoom]. */+ fun project(longitude: Double, latitude: Double, zoom: Double): WorldPx {+ val ws = worldSize(zoom)+ val lat = latitude.coerceIn(-85.05112878, 85.05112878)+ val x = (longitude + 180.0) / 360.0 * ws+ val sinLat = sin(lat * PI / 180.0)+ val y = (0.5 - ln((1 + sinLat) / (1 - sinLat)) / (4 * PI)) * ws+ return WorldPx(x, y)+ }++ /** Inverse of [project]: world px at [zoom] back to lon/lat degrees. */+ fun unproject(x: Double, y: Double, zoom: Double): Position {+ val ws = worldSize(zoom)+ val longitude = x / ws * 360.0 - 180.0+ val n = PI - 2 * PI * y / ws+ val latitude = atan(sinh(n)) * 180.0 / PI+ return Position(longitude, latitude)+ }+}
library/map/src/main/java/com/vayunmathur/library/map/Projection.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/Projection.kt b/library/map/src/main/java/com/vayunmathur/library/map/Projection.ktnew file mode 100644index 0000000000..086797916a--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/Projection.kt@@ -0,0 +1,51 @@+package com.vayunmathur.library.map++import androidx.compose.ui.unit.DpOffset+import androidx.compose.ui.unit.dp+import org.maplibre.spatialk.geojson.BoundingBox+import org.maplibre.spatialk.geojson.Position++/**+ * Immutable snapshot of the camera (center + zoom) and viewport used to map+ * between geographic [Position]s and on-screen [DpOffset]s. Mirrors the subset+ * of maplibre-compose's projection API the apps call, so migration is an+ * import swap.+ *+ * The map center projects to the viewport center; offsets are density+ * independent (`Dp`) and measured from the viewport's top-left corner.+ */+class Projection internal constructor(+ private val center: Position,+ private val zoom: Double,+ private val widthDp: Float,+ private val heightDp: Float,+) {+ /** Screen location (from the viewport top-left) of a geographic [position]. */+ fun screenLocationFromPosition(position: Position): DpOffset {+ val c = Mercator.project(center.longitude, center.latitude, zoom)+ val p = Mercator.project(position.longitude, position.latitude, zoom)+ val x = (p.x - c.x) + widthDp / 2.0+ val y = (p.y - c.y) + heightDp / 2.0+ return DpOffset(x.toFloat().dp, y.toFloat().dp)+ }++ /** Geographic position under a screen [offset] (from the viewport top-left). */+ fun positionFromScreenLocation(offset: DpOffset): Position {+ val c = Mercator.project(center.longitude, center.latitude, zoom)+ val x = c.x + (offset.x.value - widthDp / 2.0)+ val y = c.y + (offset.y.value - heightDp / 2.0)+ return Mercator.unproject(x, y, zoom)+ }++ /** The lon/lat bounds of the currently visible viewport. */+ fun queryVisibleBoundingBox(): BoundingBox {+ val topLeft = positionFromScreenLocation(DpOffset(0.dp, 0.dp))+ val bottomRight = positionFromScreenLocation(DpOffset(widthDp.dp, heightDp.dp))+ return BoundingBox(+ west = topLeft.longitude,+ south = bottomRight.latitude,+ east = bottomRight.longitude,+ north = topLeft.latitude,+ )+ }+}
library/map/src/main/java/com/vayunmathur/library/map/RasterMap.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/RasterMap.kt b/library/map/src/main/java/com/vayunmathur/library/map/RasterMap.ktnew file mode 100644index 0000000000..29bdaa16b3--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/RasterMap.kt@@ -0,0 +1,251 @@+package com.vayunmathur.library.map++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.background+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.gestures.detectTransformGestures+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.onSizeChanged+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.unit.DpOffset+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import coil.ImageLoader+import org.maplibre.spatialk.geojson.Position+import kotlin.math.floor+import kotlin.math.pow+import kotlin.math.roundToInt++/** Placement of one tile in the viewport, in logical (dp) coordinates. */+private data class TileBox(+ val key: TileKey,+ val leftDp: Float,+ val topDp: Float,+ val sizeDp: Float,+)++/** Background shown behind tiles before/if they load. */+private val MapBackground = Color(0xFFE9E7E2)++/**+ * A Compose-native Web-Mercator raster tile viewer. Renders XYZ tiles from+ * [tileSource] on a Canvas with parent-tile fallback (no blank flashes while+ * panning/zooming), exposes a maplibre-compatible camera/projection via+ * [cameraState], and draws an optional georeferenced [imageOverlay] plus a+ * composable [content] overlay above the tiles.+ */+@Composable+fun RasterMap(+ cameraState: CameraState,+ modifier: Modifier = Modifier,+ tileSource: TileSource = TileSource.CartoVoyager,+ zoomRange: ClosedFloatingPointRange<Float> = 0f..20f,+ options: MapOptions = MapOptions(),+ imageOverlay: ImageOverlay? = null,+ onMapClick: (Position) -> Unit = {},+ onFrame: () -> Unit = {},+ content: @Composable () -> Unit = {},+) {+ val context = LocalContext.current+ val density = LocalDensity.current.density+ val scope = rememberCoroutineScope()++ val loader = remember(context) { ImageLoader(context) }+ val cache = remember(tileSource, loader) { TileCache(context, loader, tileSource) }++ val minZoom = tileSource.minZoom+ val maxZoom = tileSource.maxZoom+ val gestures = options.gestureOptions++ // Fire onFrame whenever the camera moves (drives per-frame reprojection).+ LaunchedEffect(cameraState.position, cameraState.viewportDp) {+ if (cameraState.viewportDp != null) onFrame()+ }++ // Compute the currently visible tiles (recomputed on move) and prefetch them.+ val position = cameraState.position+ val viewport = cameraState.viewportDp+ val visible: List<TileBox> = remember(position, viewport, tileSource) {+ if (viewport == null) emptyList() else computeVisibleTiles(position, viewport, minZoom, maxZoom)+ }+ LaunchedEffect(visible) { visible.forEach { cache.request(scope, it.key) } }++ Box(+ modifier+ .fillMaxSize()+ .background(MapBackground)+ .onSizeChanged {+ cameraState.setViewport(Size(it.width / density, it.height / density))+ }+ .pointerInput(cameraState, gestures, zoomRange) {+ detectTransformGestures { centroid, pan, zoom, _ ->+ if (!gestures.isScrollEnabled && !gestures.isZoomEnabled) return@detectTransformGestures+ cameraState.onGesture(+ centroidDp = Offset(centroid.x / density, centroid.y / density),+ panDp = Offset(pan.x / density, pan.y / density),+ zoomChange = zoom,+ minZoom = zoomRange.start.toDouble(),+ maxZoom = zoomRange.endInclusive.toDouble(),+ scrollEnabled = gestures.isScrollEnabled,+ zoomEnabled = gestures.isZoomEnabled,+ )+ }+ }+ .pointerInput(cameraState) {+ detectTapGestures { offset ->+ val proj = cameraState.projection ?: return@detectTapGestures+ onMapClick(proj.positionFromScreenLocation(DpOffset((offset.x / density).dp, (offset.y / density).dp)))+ }+ },+ ) {+ // Read cache.tiles inside the draw lambda so tile arrival recomposes.+ val tiles = cache.tiles+ Canvas(Modifier.fillMaxSize()) {+ for (box in visible) {+ drawTile(box, tiles, density, minZoom)+ }+ imageOverlay?.let { drawOverlay(it, cameraState) }+ }++ content()++ if (options.ornamentOptions.isAttributionEnabled) {+ Attribution(tileSource.attribution, Modifier.align(Alignment.BottomStart))+ }+ }+}++/** Draws one tile, falling back to a scaled ancestor when the exact tile is missing. */+private fun DrawScope.drawTile(+ box: TileBox,+ tiles: Map<TileKey, ImageBitmap>,+ density: Float,+ minZoom: Int,+) {+ val left = (box.leftDp * density).roundToInt()+ val top = (box.topDp * density).roundToInt()+ val right = ((box.leftDp + box.sizeDp) * density).roundToInt()+ val bottom = ((box.topDp + box.sizeDp) * density).roundToInt()+ val dstOffset = IntOffset(left, top)+ val dstSize = IntSize(right - left, bottom - top)++ val exact = tiles[box.key]+ if (exact != null) {+ drawImage(+ image = exact,+ srcOffset = IntOffset.Zero,+ srcSize = IntSize(exact.width, exact.height),+ dstOffset = dstOffset,+ dstSize = dstSize,+ )+ return+ }+ // Walk up the pyramid for a cached ancestor and draw its matching sub-region.+ var d = 1+ while (box.key.z - d >= minZoom) {+ val f = 1 shl d+ val pkey = TileKey(box.key.z - d, box.key.x / f, box.key.y / f)+ val ancestor = tiles[pkey]+ if (ancestor != null) {+ val subW = ancestor.width / f+ val subH = ancestor.height / f+ drawImage(+ image = ancestor,+ srcOffset = IntOffset((box.key.x % f) * subW, (box.key.y % f) * subH),+ srcSize = IntSize(subW, subH),+ dstOffset = dstOffset,+ dstSize = dstSize,+ )+ return+ }+ d+++ }+}++/** Stretches the overlay image into its bbox's screen rect (north-up, axis-aligned). */+private fun DrawScope.drawOverlay(overlay: ImageOverlay, cameraState: CameraState) {+ val proj = cameraState.projection ?: return+ val bbox = overlay.bounds+ val nw = proj.screenLocationFromPosition(Position(bbox.west, bbox.north))+ val se = proj.screenLocationFromPosition(Position(bbox.east, bbox.south))+ val left = nw.x.toPx().roundToInt()+ val top = nw.y.toPx().roundToInt()+ val right = se.x.toPx().roundToInt()+ val bottom = se.y.toPx().roundToInt()+ drawImage(+ image = overlay.bitmap,+ srcOffset = IntOffset.Zero,+ srcSize = IntSize(overlay.bitmap.width, overlay.bitmap.height),+ dstOffset = IntOffset(left, top),+ dstSize = IntSize((right - left).coerceAtLeast(1), (bottom - top).coerceAtLeast(1)),+ alpha = overlay.opacity,+ )+}++@Composable+private fun Attribution(text: String, modifier: Modifier = Modifier) {+ androidx.compose.foundation.text.BasicText(+ text = text,+ modifier = modifier+ .padding(2.dp)+ .background(Color(0xB3FFFFFF))+ .padding(horizontal = 4.dp, vertical = 1.dp),+ style = TextStyle(color = Color(0xFF444444), fontSize = 9.sp, fontFamily = FontFamily.SansSerif),+ )+}++/** Visible tiles for [position] within [viewport] (dp), at `floor(zoom)` clamped to source range. */+private fun computeVisibleTiles(+ position: CameraPosition,+ viewport: Size,+ minZoom: Int,+ maxZoom: Int,+): List<TileBox> {+ val zoom = position.zoom+ val z = floor(zoom).toInt().coerceIn(minZoom, maxZoom)+ val n = 1 shl z+ val tileSpanDp = Mercator.TILE_SIZE * 2.0.pow(zoom - z)+ val center = Mercator.project(position.target.longitude, position.target.latitude, zoom)+ val originX = center.x - viewport.width / 2.0+ val originY = center.y - viewport.height / 2.0++ val minTx = floor(originX / tileSpanDp).toInt()+ val maxTx = floor((originX + viewport.width) / tileSpanDp).toInt()+ val minTy = floor(originY / tileSpanDp).toInt()+ val maxTy = floor((originY + viewport.height) / tileSpanDp).toInt()++ val result = ArrayList<TileBox>()+ for (ty in minTy..maxTy) {+ if (ty < 0 || ty >= n) continue+ for (tx in minTx..maxTx) {+ val wrappedX = ((tx % n) + n) % n+ result += TileBox(+ key = TileKey(z, wrappedX, ty),+ leftDp = (tx * tileSpanDp - originX).toFloat(),+ topDp = (ty * tileSpanDp - originY).toFloat(),+ sizeDp = tileSpanDp.toFloat(),+ )+ }+ }+ return result+}
library/map/src/main/java/com/vayunmathur/library/map/TileCache.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/TileCache.kt b/library/map/src/main/java/com/vayunmathur/library/map/TileCache.ktnew file mode 100644index 0000000000..e9c88c8a93--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/TileCache.kt@@ -0,0 +1,55 @@+package com.vayunmathur.library.map++import android.content.Context+import android.graphics.drawable.BitmapDrawable+import androidx.compose.runtime.mutableStateMapOf+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.asImageBitmap+import coil.ImageLoader+import coil.request.ImageRequest+import coil.request.SuccessResult+import coil.size.Size+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.launch++/** Identifies a single XYZ tile. */+internal data class TileKey(val z: Int, val x: Int, val y: Int)++/**+ * Fetches raster tiles through a Coil [ImageLoader] (which handles memory + disk+ * caching) and holds decoded [ImageBitmap]s in a snapshot-state map so tile+ * arrival recomposes the map canvas. In-flight keys are tracked to avoid+ * duplicate requests.+ */+internal class TileCache(+ private val context: Context,+ private val loader: ImageLoader,+ private val source: TileSource,+) {+ val tiles = mutableStateMapOf<TileKey, ImageBitmap>()+ private val inFlight = HashSet<TileKey>()++ fun get(key: TileKey): ImageBitmap? = tiles[key]++ /** Requests [key] if not already loaded or loading. */+ fun request(scope: CoroutineScope, key: TileKey) {+ if (key in tiles || key in inFlight) return+ inFlight += key+ scope.launch {+ val bitmap = runCatching {+ val request = ImageRequest.Builder(context)+ .data(source.url(key.z, key.x, key.y))+ .size(Size(source.tileSizePx, source.tileSizePx))+ .allowHardware(false)+ .build()+ val result = loader.execute(request)+ (result as? SuccessResult)?.drawable+ ?.let { it as? BitmapDrawable }+ ?.bitmap+ ?.asImageBitmap()+ }.getOrNull()+ inFlight -= key+ if (bitmap != null) tiles[key] = bitmap+ }+ }+}
library/map/src/main/java/com/vayunmathur/library/map/TileSource.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/TileSource.kt b/library/map/src/main/java/com/vayunmathur/library/map/TileSource.ktnew file mode 100644index 0000000000..3b8f48acbd--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/TileSource.kt@@ -0,0 +1,36 @@+package com.vayunmathur.library.map++/**+ * An XYZ raster tile source: a `{z}/{x}/{y}` URL template plus attribution and+ * a zoom range. Uses retina (`@2x`) tiles for crispness — [tileSizePx] is the+ * pixel size of the fetched image (512 for `@2x`).+ */+data class TileSource(+ val urlTemplate: String,+ val attribution: String,+ val minZoom: Int = 0,+ val maxZoom: Int = 20,+ val tileSizePx: Int = 512,+) {+ fun url(z: Int, x: Int, y: Int): String =+ urlTemplate+ .replace("{z}", z.toString())+ .replace("{x}", x.toString())+ .replace("{y}", y.toString())++ companion object {+ private const val ATTRIBUTION = "© OpenStreetMap © CARTO"++ /** CARTO Voyager — colorful general-purpose basemap (findfamily/photos). */+ val CartoVoyager = TileSource(+ urlTemplate = "https://basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}@2x.png",+ attribution = ATTRIBUTION,+ )++ /** CARTO Positron (light_all) — muted basemap for data overlays (weather). */+ val CartoPositron = TileSource(+ urlTemplate = "https://basemaps.cartocdn.com/light_all/{z}/{x}/{y}@2x.png",+ attribution = ATTRIBUTION,+ )+ }+}
library/ocr/build.gradle.kts
diff --git a/library/ocr/build.gradle.kts b/library/ocr/build.gradle.ktsindex 42dee362d9..1508ad331a 100644--- a/library/ocr/build.gradle.kts+++ b/library/ocr/build.gradle.kts@@ -2,16 +2,10 @@ plugins { id("common-conventions-library") } -android {- androidResources {- // The PP-OCR .onnx models are already compressed; storing them- // uncompressed keeps the APK asset directly readable.- noCompress += "onnx"- }-}- dependencies {- // On-device OCR via ONNX Runtime (MIT, FOSS, no Play Services / no ML Kit).- // This module owns the dependency; consumers only see the OcrEngine API.- implementation(libs.onnxruntime.android)+ // On-device OCR via PP-OCRv5 on ncnn (BSD-3, FOSS, no Play Services / no ML+ // Kit). The models + native pipeline ship inside this AAR; consumers only+ // see the OcrEngine API.+ implementation("com.github.vayun-mathur:ncnn-android:1.0.0")+ implementation(libs.kotlinx.coroutines.android) }
library/ocr/src/main/assets/ocr/det.onnx
diff --git a/library/ocr/src/main/assets/ocr/det.onnx b/library/ocr/src/main/assets/ocr/det.onnxdeleted file mode 100644index 6550f4e49a..0000000000Binary files a/library/ocr/src/main/assets/ocr/det.onnx and /dev/null differ
library/ocr/src/main/assets/ocr/en_dict.txt
diff --git a/library/ocr/src/main/assets/ocr/en_dict.txt b/library/ocr/src/main/assets/ocr/en_dict.txtdeleted file mode 100644index 7677d31b9d..0000000000--- a/library/ocr/src/main/assets/ocr/en_dict.txt+++ /dev/null@@ -1,95 +0,0 @@-0-1-2-3-4-5-6-7-8-9-:-;-<-=->-?-@-A-B-C-D-E-F-G-H-I-J-K-L-M-N-O-P-Q-R-S-T-U-V-W-X-Y-Z-[-\-]-^-_-`-a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-z-{-|-}-~-!-"-#-$-%-&-'-(-)-*-+-,---.-/-
library/ocr/src/main/assets/ocr/rec.onnx
diff --git a/library/ocr/src/main/assets/ocr/rec.onnx b/library/ocr/src/main/assets/ocr/rec.onnxdeleted file mode 100644index 37f0162b0b..0000000000Binary files a/library/ocr/src/main/assets/ocr/rec.onnx and /dev/null differ
library/ocr/src/main/java/com/vayunmathur/library/ocr/OcrEngine.kt
diff --git a/library/ocr/src/main/java/com/vayunmathur/library/ocr/OcrEngine.kt b/library/ocr/src/main/java/com/vayunmathur/library/ocr/OcrEngine.ktindex 2404a2c91f..dd7e06d21f 100644--- a/library/ocr/src/main/java/com/vayunmathur/library/ocr/OcrEngine.kt+++ b/library/ocr/src/main/java/com/vayunmathur/library/ocr/OcrEngine.kt@@ -1,58 +1,29 @@ package com.vayunmathur.library.ocr -import ai.onnxruntime.OnnxTensor-import ai.onnxruntime.OrtEnvironment-import ai.onnxruntime.OrtSession import android.content.Context import android.graphics.Bitmap import android.util.Log-import java.nio.FloatBuffer-import kotlin.math.ceil-import kotlin.math.max-import kotlin.math.min-import kotlin.math.roundToInt+import com.vayunmathur.ncnn.PpOcr import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext /**- * Shared on-device OCR engine using PaddleOCR (PP-OCR mobile) models on ONNX- * Runtime (`com.microsoft.onnxruntime:onnxruntime-android`, MIT — no Google Play- * Services, no ML Kit). Everything runs locally; the models ship as assets of- * this module (assets are unrestricted for F-Droid). Both the Photos and PDF- * apps depend on this one module so they share the models and code.+ * Shared on-device OCR engine using Baidu **PP-OCRv5 mobile** running on+ * **ncnn** (Tencent, BSD-3, CPU-only — no Google Play Services, no ML Kit). The+ * detection (DBNet) + recognition (CTC, full ~18k-char dictionary covering+ * Latin/CJK/digits/symbols) pipeline and its models live entirely inside the+ * `com.github.vayun-mathur:ncnn-android` AAR, which also bundles OpenCV for the+ * detection post-processing. Both the Photos and PDF apps depend on this one+ * module so they share the engine. *- * Pipeline (classic PP-OCR, dependency-free):- * 1. Text detection with the DB (Differentiable Binarization) model: the image- * is downscaled (long side ~[DET_LIMIT], both sides a multiple of 32),- * normalised with the PaddleOCR ImageNet mean/std, and run to a probability- * map. The map is thresholded and split into text regions via connected- * components; each region becomes an (axis-aligned) crop.- * 2. Text recognition with the CRNN/SVTR model: each crop is resized to height- * [REC_H], normalised to [-1, 1], run, then CTC-decoded against the- * character dictionary.- * Recognised lines are concatenated top-to-bottom into the returned text.+ * The whole detect+recognize pass runs natively in one call; this class adapts+ * the result to the [OcrResult]/[TextBox] shape consumers expect and orders the+ * lines top-to-bottom for readable output. *- * Angle classification (the optional PP-OCR "cls" step) is intentionally skipped- * to keep this lighter; scanned pages and gallery photos are almost always- * upright. Drop a `cls.onnx` beside the others and extend [recognize] if needed.- *- * Assets (see [ASSET_DET], [ASSET_REC], [ASSET_DICT]) are sourced from the- * RapidOCR project (https://github.com/RapidAI/RapidOCR, Apache-2.0), which- * publishes ready-to-use PP-OCR detection/recognition ONNX models plus the- * PaddleOCR character dictionary:- * - ocr/det.onnx = PP-OCR English mobile text-detection model- * - ocr/rec.onnx = PP-OCR English mobile text-recognition model- * - ocr/en_dict.txt = PaddleOCR `ppocr/utils/en_dict.txt` (recognition charset)- * To swap in different PP-OCR ONNX models (e.g. multilingual), drop replacements- * at these asset paths; the recognizer adapts to the model's output class count- * automatically. If any asset is missing the engine is inert (returns empty- * text, never crashes) — call [isAvailable] to check up front.- *- * Low-power by design: single-threaded ONNX sessions, inputs are downscaled- * before detection, and one image is processed at a time. Sessions are created- * lazily on first use and reused across calls; release them with [close].+ * If the native library/models are unavailable the engine is inert (returns+ * empty text, never crashes) — call [isAvailable] to check up front. * * All heavy work runs off the main thread (Dispatchers.Default). Instances are * safe to reuse sequentially; concurrent calls are serialised internally.@@ -78,22 +49,17 @@ class OcrEngine(private val context: Context) { /** Full result: the joined [text] plus the individual [boxes] it came from. */ data class OcrResult(val text: String, val boxes: List<TextBox>) - private val env: OrtEnvironment = OrtEnvironment.getEnvironment() private val lock = Mutex()-- private var detSession: OrtSession? = null- private var recSession: OrtSession? = null- private var dict: List<String> = emptyList()- private var recChars: Array<String>? = null+ private var ocr: PpOcr? = null private var initTried = false - /** True if the model + dictionary assets are present and could be loaded. */+ /** True if the native library + models are present and could be loaded. */ suspend fun isAvailable(): Boolean = lock.withLock { ensureInit() } /** * Recognise all text in [bitmap] and return it as a single string (lines- * joined by newlines), or an empty string if nothing is found or the models- * are unavailable. The caller's [bitmap] is not recycled.+ * joined by newlines), or an empty string if nothing is found or the engine+ * is unavailable. The caller's [bitmap] is not recycled. */ suspend fun recognize(bitmap: Bitmap): String = recognizeDetailed(bitmap).text @@ -101,331 +67,47 @@ class OcrEngine(private val context: Context) { suspend fun recognizeDetailed(bitmap: Bitmap): OcrResult = withContext(Dispatchers.Default) { lock.withLock { if (!ensureInit()) return@withContext OcrResult("", emptyList())- val src = bitmap.toSoftwareRgb()+ val engine = ocr ?: return@withContext OcrResult("", emptyList()) try {- val boxes = detect(src)- val results = ArrayList<TextBox>(boxes.size)- for (box in boxes) {- val crop = cropSafely(src, box) ?: continue- val line = try {- recognizeCrop(crop)- } finally {- if (crop != src) crop.recycle()- }- if (!line.isNullOrBlank()) {- results.add(TextBox(line.trim(), box.left, box.top, box.right, box.bottom))- }- }- OcrResult(results.joinToString("\n") { it.text }.trim(), results)+ val boxes = engine.recognize(bitmap)+ .asSequence()+ .filter { it.text.isNotBlank() && it.right > it.left && it.bottom > it.top }+ // Reading order: top-to-bottom, then left-to-right within a row band.+ .sortedWith(compareBy({ it.top / READING_ROW_BAND }, { it.left }))+ .map { TextBox(it.text.trim(), it.left, it.top, it.right, it.bottom) }+ .toList()+ OcrResult(boxes.joinToString("\n") { it.text }.trim(), boxes) } catch (e: Exception) { Log.e(TAG, "OCR failed", e) OcrResult("", emptyList())- } finally {- if (src != bitmap) src.recycle() } } } - /** Release the ONNX sessions. The shared [OrtEnvironment] is left open. */+ /** Release the native models. */ fun close() {- try { detSession?.close() } catch (_: Exception) {}- try { recSession?.close() } catch (_: Exception) {}- detSession = null- recSession = null- recChars = null+ try { ocr?.close() } catch (_: Exception) {}+ ocr = null initTried = false } - // ---- Initialisation ------ /** Load models + dictionary and create the ONNX sessions once. */+ /** Create the native PP-OCRv5 engine once. */ private fun ensureInit(): Boolean {- if (detSession != null && recSession != null) return true+ if (ocr != null) return true if (initTried) return false initTried = true return try {- val detBytes = readAsset(ASSET_DET) ?: run {- Log.w(TAG, "Missing OCR asset $ASSET_DET"); return false- }- val recBytes = readAsset(ASSET_REC) ?: run {- Log.w(TAG, "Missing OCR asset $ASSET_REC"); return false- }- val dictLines = readDict(ASSET_DICT) ?: run {- Log.w(TAG, "Missing OCR asset $ASSET_DICT"); return false- }- val opts = OrtSession.SessionOptions().apply {- // Single-threaded keeps sustained CPU/battery use low.- setIntraOpNumThreads(1)- setInterOpNumThreads(1)- }- detSession = env.createSession(detBytes, opts)- recSession = env.createSession(recBytes, opts)- dict = dictLines+ ocr = PpOcr(context) true- } catch (e: Exception) {- Log.e(TAG, "Failed to initialise ONNX OCR", e)- close()- initTried = true+ } catch (e: Throwable) {+ Log.e(TAG, "Failed to initialise ncnn PP-OCRv5", e)+ ocr = null false } } - // ---- Detection (DB) ------ private data class Box(val left: Int, val top: Int, val right: Int, val bottom: Int)-- private fun detect(src: Bitmap): List<Box> {- val session = detSession ?: return emptyList()- val (rw, rh) = detTargetSize(src.width, src.height)- val resized = Bitmap.createScaledBitmap(src, rw, rh, true)- val input = try {- normalize(resized, rw, rh, MEAN_IMAGENET, STD_IMAGENET)- } finally {- if (resized != src) resized.recycle()- }-- val inputName = session.inputNames.iterator().next()- var prob = FloatArray(0)- var pw = 0- var ph = 0- OnnxTensor.createTensor(env, FloatBuffer.wrap(input), longArrayOf(1, 3, rh.toLong(), rw.toLong())).use { tensor ->- session.run(mapOf(inputName to tensor)).use { result ->- val out = result.get(0) as OnnxTensor- val shape = out.info.shape // [1, 1, H, W]- ph = shape[shape.size - 2].toInt()- pw = shape[shape.size - 1].toInt()- prob = FloatArray(ph * pw)- out.floatBuffer.get(prob)- }- }- if (pw == 0 || ph == 0) return emptyList()-- val boxes = boxesFromProbMap(prob, pw, ph)- // Map from probability-map space back to the source bitmap.- val sx = src.width.toFloat() / pw- val sy = src.height.toFloat() / ph- return boxes.map {- Box(- left = (it.left * sx).toInt(),- top = (it.top * sy).toInt(),- right = (it.right * sx).roundToInt(),- bottom = (it.bottom * sy).roundToInt(),- )- }- }-- private fun detTargetSize(w: Int, h: Int): Pair<Int, Int> {- var ratio = 1f- val maxSide = max(w, h)- if (maxSide > DET_LIMIT) ratio = DET_LIMIT.toFloat() / maxSide- fun toMul32(v: Int) = max(32, (v / 32.0).roundToInt() * 32)- return toMul32((w * ratio).roundToInt()) to toMul32((h * ratio).roundToInt())- }-- /**- * Threshold the probability map and turn each connected text region into an- * axis-aligned box. This is a dependency-free stand-in for PaddleOCR's- * contour/min-area-rect + unclip step (which needs OpenCV); axis-aligned- * boxes handle the horizontal text typical of documents and photos well.- */- private fun boxesFromProbMap(prob: FloatArray, w: Int, h: Int): List<Box> {- val n = w * h- val fg = BooleanArray(n) { prob[it] > DET_THRESH }- val visited = BooleanArray(n)- val stack = IntArray(n)- val boxes = ArrayList<Box>()-- for (seed in 0 until n) {- if (!fg[seed] || visited[seed]) continue- var sp = 0- stack[sp++] = seed- visited[seed] = true- var minX = Int.MAX_VALUE- var minY = Int.MAX_VALUE- var maxX = 0- var maxY = 0- var count = 0- var probSum = 0f- while (sp > 0) {- val idx = stack[--sp]- val x = idx % w- val y = idx / w- count++- probSum += prob[idx]- if (x < minX) minX = x- if (x > maxX) maxX = x- if (y < minY) minY = y- if (y > maxY) maxY = y- if (x > 0) { val nb = idx - 1; if (fg[nb] && !visited[nb]) { visited[nb] = true; stack[sp++] = nb } }- if (x < w - 1) { val nb = idx + 1; if (fg[nb] && !visited[nb]) { visited[nb] = true; stack[sp++] = nb } }- if (y > 0) { val nb = idx - w; if (fg[nb] && !visited[nb]) { visited[nb] = true; stack[sp++] = nb } }- if (y < h - 1) { val nb = idx + w; if (fg[nb] && !visited[nb]) { visited[nb] = true; stack[sp++] = nb } }- }- if (count < DET_MIN_PIXELS) continue- val bw = maxX - minX + 1- val bh = maxY - minY + 1- if (bw < DET_MIN_SIDE || bh < DET_MIN_SIDE) continue- if (probSum / count < DET_BOX_THRESH) continue- // Approximate PaddleOCR's "unclip": grow the box a little to recover- // characters clipped by the tight probability mask.- val exp = (min(bw, bh) * DET_UNCLIP).roundToInt()- boxes.add(- Box(- left = (minX - exp).coerceAtLeast(0),- top = (minY - exp).coerceAtLeast(0),- right = (maxX + exp).coerceAtMost(w - 1),- bottom = (maxY + exp).coerceAtMost(h - 1),- )- )- if (boxes.size >= DET_MAX_BOXES) break- }- // Reading order: top-to-bottom, then left-to-right within a row band.- return boxes.sortedWith(compareBy({ it.top / READING_ROW_BAND }, { it.left }))- }-- private fun cropSafely(src: Bitmap, box: Box): Bitmap? {- val l = box.left.coerceIn(0, src.width - 1)- val t = box.top.coerceIn(0, src.height - 1)- val r = box.right.coerceIn(l + 1, src.width)- val b = box.bottom.coerceIn(t + 1, src.height)- val cw = r - l- val ch = b - t- if (cw < 2 || ch < 2) return null- return try {- Bitmap.createBitmap(src, l, t, cw, ch)- } catch (e: Exception) {- null- }- }-- // ---- Recognition (CRNN + CTC) ------ private fun recognizeCrop(crop: Bitmap): String? {- val session = recSession ?: return null- val ratio = crop.width.toFloat() / crop.height- val tw = ceil(REC_H * ratio).toInt().coerceIn(REC_MIN_W, REC_MAX_W)- val resized = Bitmap.createScaledBitmap(crop, tw, REC_H, true)- val input = try {- normalize(resized, tw, REC_H, MEAN_HALF, STD_HALF)- } finally {- if (resized != crop) resized.recycle()- }-- val inputName = session.inputNames.iterator().next()- var text: String? = null- OnnxTensor.createTensor(env, FloatBuffer.wrap(input), longArrayOf(1, 3, REC_H.toLong(), tw.toLong())).use { tensor ->- session.run(mapOf(inputName to tensor)).use { result ->- val out = result.get(0) as OnnxTensor- val shape = out.info.shape // [1, T, C]- val timeSteps = shape[1].toInt()- val classes = shape[2].toInt()- val data = FloatArray(timeSteps * classes)- out.floatBuffer.get(data)- text = ctcDecode(data, timeSteps, classes)- }- }- return text- }-- private fun ctcDecode(data: FloatArray, timeSteps: Int, classes: Int): String {- val chars = recChars ?: buildChars(classes).also { recChars = it }- val sb = StringBuilder()- var last = -1- for (t in 0 until timeSteps) {- val base = t * classes- var best = 0- var bestVal = data[base]- for (k in 1 until classes) {- val v = data[base + k]- if (v > bestVal) { bestVal = v; best = k }- }- if (best != last) {- if (best != 0 && best < chars.size) sb.append(chars[best])- last = best- }- }- return sb.toString()- }-- /**- * Build the CTC index→char table. Index 0 is the CTC blank; indices 1..N map- * to the dictionary. If the model has more classes than the dictionary (some- * PP-OCR builds append a space class), the extras become spaces.- */- private fun buildChars(classes: Int): Array<String> = Array(classes) { i ->- when {- i == 0 -> ""- i - 1 < dict.size -> dict[i - 1]- else -> " "- }- }-- // ---- Shared helpers ------ /** Ensure a readable ARGB bitmap: hardware bitmaps can't be read via getPixels. */- private fun Bitmap.toSoftwareRgb(): Bitmap {- return if (config == Bitmap.Config.HARDWARE || config == null) {- copy(Bitmap.Config.ARGB_8888, false)- } else {- this- }- }-- /** Convert a bitmap to a normalised NCHW float array: (pixel/255 - mean)/std, RGB order. */- private fun normalize(bmp: Bitmap, w: Int, h: Int, mean: FloatArray, std: FloatArray): FloatArray {- val px = IntArray(w * h)- bmp.getPixels(px, 0, w, 0, 0, w, h)- val area = w * h- val out = FloatArray(3 * area)- for (i in 0 until area) {- val p = px[i]- val r = ((p shr 16) and 0xFF) / 255f- val g = ((p shr 8) and 0xFF) / 255f- val b = (p and 0xFF) / 255f- out[i] = (r - mean[0]) / std[0]- out[area + i] = (g - mean[1]) / std[1]- out[2 * area + i] = (b - mean[2]) / std[2]- }- return out- }-- private fun readAsset(path: String): ByteArray? = try {- context.assets.open(path).use { it.readBytes() }- } catch (e: Exception) {- null- }-- private fun readDict(path: String): List<String>? = try {- context.assets.open(path).bufferedReader().use { it.readLines() }- } catch (e: Exception) {- null- }- companion object { private const val TAG = "OcrEngine"-- private const val ASSET_DET = "ocr/det.onnx"- private const val ASSET_REC = "ocr/rec.onnx"- private const val ASSET_DICT = "ocr/en_dict.txt"-- // Detection.- private const val DET_LIMIT = 960- private const val DET_THRESH = 0.3f- private const val DET_BOX_THRESH = 0.5f- private const val DET_MIN_PIXELS = 16- private const val DET_MIN_SIDE = 3- private const val DET_UNCLIP = 0.4f- private const val DET_MAX_BOXES = 256- private const val READING_ROW_BAND = 8-- // Recognition.- private const val REC_H = 48- private const val REC_MIN_W = 16- private const val REC_MAX_W = 1024-- private val MEAN_IMAGENET = floatArrayOf(0.485f, 0.456f, 0.406f)- private val STD_IMAGENET = floatArrayOf(0.229f, 0.224f, 0.225f)- private val MEAN_HALF = floatArrayOf(0.5f, 0.5f, 0.5f)- private val STD_HALF = floatArrayOf(0.5f, 0.5f, 0.5f)+ private const val READING_ROW_BAND = 16 } }
pdf/build.gradle.kts
diff --git a/pdf/build.gradle.kts b/pdf/build.gradle.ktsindex 8df7ddee1a..567fbf8645 100644--- a/pdf/build.gradle.kts+++ b/pdf/build.gradle.kts@@ -13,6 +13,11 @@ android { defaultConfig { applicationId = "com.vayunmathur.pdf" }+ androidResources {+ // ncnn-android is generalist; pdf only uses PpOcr (OCR), so strip the+ // portrait (erdnet) model it never loads.+ ignoreAssetsPattern = "!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~:erdnet.*"+ } // The Rust build drops <abi>/libpdf_render.so under this dir; register it as // a jniLibs source so AGP packages the native lib. sourceSets["main"].jniLibs.directories.add(layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath)
pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.ktindex f9a4b7c1c5..df80b8dfee 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt@@ -2208,9 +2208,29 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) { } when (prim) { is PdfPrimitive.FillPath -> {- val path = prim.points.toPath(::map) ?: continue- if (prim.evenOdd) path.fillType = androidx.compose.ui.graphics.PathFillType.EvenOdd- drawPath(path, Color(prim.color), style = Fill, blendMode = prim.blend.toCompose())+ val path = Path()+ var any = false+ for (contour in prim.contours) {+ if (contour.size < 2) continue+ val first = map(contour[0])+ path.moveTo(first.x, first.y)+ for (i in 1 until contour.size) {+ val p = map(contour[i])+ path.lineTo(p.x, p.y)+ }+ path.close()+ any = true+ }+ if (any) {+ // All contours in one path so interior contours (holes/glyph+ // counters) are cut out by the winding rule.+ path.fillType = if (prim.evenOdd) {+ androidx.compose.ui.graphics.PathFillType.EvenOdd+ } else {+ androidx.compose.ui.graphics.PathFillType.NonZero+ }+ drawPath(path, Color(prim.color), style = Fill, blendMode = prim.blend.toCompose())+ } } is PdfPrimitive.StrokePath -> {
pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.ktindex 714a8a5d71..ea244cc5a8 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.kt@@ -40,11 +40,15 @@ sealed interface PdfPrimitive { val blend: BlendMode = BlendMode.Normal, ) : PdfPrimitive - /** A filled polygon (one subpath). */+ /**+ * A filled region made of one or more closed [contours]. Interior contours+ * (glyph counters / holes) are cut out by the even-odd or nonzero winding+ * rule when all contours are filled as a single path.+ */ data class FillPath( val color: Int, val evenOdd: Boolean,- val points: List<Offset>,+ val contours: List<List<Offset>>, val blend: BlendMode = BlendMode.Normal, ) : PdfPrimitive
pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.ktindex 5589ea1d72..69472966ff 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt@@ -8,14 +8,14 @@ import java.nio.ByteOrder * Decodes the compact little-endian primitive buffer produced by the native * renderer ([PdfNative.renderPage]) into a [SafePdfPage]. *- * Wire format v5 (must stay in sync with `pdf/rust/src/wire.rs`):+ * Wire format v6 (must stay in sync with `pdf/rust/src/wire.rs`): * ```- * header: u32 MAGIC=0x50444657, u32 VERSION=5, f32 pageWidth, f32 pageHeight, u32 primitiveCount+ * header: u32 MAGIC=0x50444657, u32 VERSION=6, f32 pageWidth, f32 pageHeight, u32 primitiveCount * Legacy v1 fallback: header is f32 W,H,u32 count (no magic)- * v2/v3/v4 fallbacks: same layout with fewer trailing per-primitive fields+ * v2..v5 fallbacks: same layout with fewer trailing per-primitive fields * per primitive: u8 tag, then payload * 1 Text: f32 x, f32 y, f32 size, u32 argb, u16 len, [utf8 bytes], u8 hasStroke, u32 strokeArgb, f32 strokeWidth, u8 renderMode (v4), u8 blend (v5)- * 2 Fill: u32 argb, u8 evenOdd, u16 nPts, [f32 x, f32 y]..., u8 blend (v5)+ * 2 Fill: u32 argb, u8 evenOdd, u16 nContours, [u16 nPts, [f32 x,y]...]... (v6), u8 blend (v5) * 3 Stroke: u32 argb, f32 width, u8 nDash, [f32 dash]..., f32 phase, u8 cap, u8 join, f32 miter, u16 nPts, [f32 x, f32 y]..., u8 blend (v5) * 4 Image: 6*f32 ctm, u32 w, u32 h, u8 format, u32 len, [bytes] * 5 ClipPush: u8 evenOdd, u16 nPts, [f32 x,y]..., u16 nPathOps, [...] (v4)@@ -51,10 +51,11 @@ object SafePdfParser { private const val PATHOP_CLOSE = 3 const val WIRE_MAGIC: Int = 0x50444657 // 'PDFW' little-endian as u32- const val WIRE_VERSION: Int = 5+ const val WIRE_VERSION: Int = 6 private const val WIRE_VERSION_V2 = 2 private const val WIRE_VERSION_V4 = 4 private const val WIRE_VERSION_V5 = 5+ private const val WIRE_VERSION_V6 = 6 const val MAX_PRIMITIVES = 50000 const val MAX_ANNOTATIONS = 10000 @@ -93,6 +94,7 @@ object SafePdfParser { val isV2OrV3 = wireVersion >= WIRE_VERSION_V2 val isV4 = wireVersion >= WIRE_VERSION_V4 val isV5 = wireVersion >= WIRE_VERSION_V5+ val isV6 = wireVersion >= WIRE_VERSION_V6 // Accept v1 (legacy), v2, v3 and v4. Newer versions are tolerated via // forward-compat parsing as long as the tags are known. if (wireVersion !in 1..WIRE_VERSION) {@@ -164,12 +166,19 @@ object SafePdfParser { TAG_FILL -> { val argb = buf.int val evenOdd = buf.get().toInt() != 0- val points = readPoints(buf)+ val contours = if (isV6) {+ val n = buf.short.toInt() and 0xFFFF+ if (n > MAX_PRIMITIVES) throw IllegalArgumentException("Fill contour count out of bounds $n")+ (0 until n).map { readPoints(buf) }+ } else {+ // v5 and earlier: a single polygon per fill.+ listOf(readPoints(buf))+ } val blend = if (isV5) { if (buf.remaining() < 1) throw IllegalArgumentException("Fill v5 blend truncated") BlendMode.fromCode(buf.get().toInt() and 0xFF) } else BlendMode.Normal- primitives.add(PdfPrimitive.FillPath(argb, evenOdd, points, blend))+ primitives.add(PdfPrimitive.FillPath(argb, evenOdd, contours, blend)) } TAG_STROKE -> {
pdf/src/main/res/values-cs/strings.xml
diff --git a/pdf/src/main/res/values-cs/strings.xml b/pdf/src/main/res/values-cs/strings.xmlindex bc0993b329..6056def5c3 100644--- a/pdf/src/main/res/values-cs/strings.xml+++ b/pdf/src/main/res/values-cs/strings.xml@@ -9,7 +9,6 @@ <string name="crop_image">Oříznout obrázek</string> <string name="continue_label">Pokračovat</string> <string name="safe_pdf_viewer_title">Prohlížeč PDF (bezpečný)</string>- <string name="safe_pdf_error">Toto PDF nešlo otevřít v bezpečném prohlížeči. Může být šifrovaný nebo používat nepodporované funkce.</string> <string name="capture_pdf">Zachytit PDF</string> <string name="capture_pdf_title">Zachytit PDF</string> <string name="request_camera_permission">Vyžádat oprávnění ke kameře\"</string>
pdf/src/main/res/values-et/strings.xml
diff --git a/pdf/src/main/res/values-et/strings.xml b/pdf/src/main/res/values-et/strings.xmlindex eb7d919c84..96a52abd92 100644--- a/pdf/src/main/res/values-et/strings.xml+++ b/pdf/src/main/res/values-et/strings.xml@@ -17,5 +17,4 @@ <string name="pdf_save">Salvesta</string> <string name="pdf_save_as_copy">Salvesta koopiana</string> <string name="safe_pdf_viewer_title">PDF-failide kuvaja (ohutult)</string>- <string name="safe_pdf_error">Selle PDF-faili avamine ohutus režiimis polnud võimalik. Ta võib olla krüptitud või on kasutusel mõni mittetoetatud funktsionaalsus.</string> </resources>
pdf/src/main/res/values-fr/strings.xml
diff --git a/pdf/src/main/res/values-fr/strings.xml b/pdf/src/main/res/values-fr/strings.xmlindex 74c9334737..a5006609f2 100644--- a/pdf/src/main/res/values-fr/strings.xml+++ b/pdf/src/main/res/values-fr/strings.xml@@ -1,7 +1,6 @@ <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">PDF</string>- <string name="safe_pdf_error">Ce PDF n\'a pas pu être ouvert par la visionneuse sécurisée. Il est peut-être chiffré ou utilise des fonctionnalités non prises en charge.</string> <string name="open_pdf">Ouvrir le PDF</string> <string name="share_pdf">Partager le PDF</string> <string name="unsupported_version">Cette application nécessite soit Android 15, soit une version entièrement mise à jour des services Google Play. Si vous ne pouvez satisfaire à aucune de ces conditions, votre appareil n\'est malheureusement pas pris en charge.</string>
pdf/src/main/res/values-it/strings.xml
diff --git a/pdf/src/main/res/values-it/strings.xml b/pdf/src/main/res/values-it/strings.xmlindex dba3d793b8..16c784177b 100644--- a/pdf/src/main/res/values-it/strings.xml+++ b/pdf/src/main/res/values-it/strings.xml@@ -17,5 +17,5 @@ <string name="pdf_save">Salva</string> <string name="pdf_save_as_copy">Salva come copia</string> <string name="safe_pdf_viewer_title">Visualizzatore PDF (sicuro)</string>- <string name="safe_pdf_error">Impossibile aprire questo PDF con il visualizzatore sicuro. Potrebbe essere crittografato o utilizzare funzionalità non supportate.</string>+ <string name="safe_pdf_error">Impossibile aprire questo PDF con il visualizzatore sicuro. Potrebbe essere danneggiato o utilizzare funzionalità non supportate.</string> </resources>
pdf/src/main/res/values-pl/strings.xml
diff --git a/pdf/src/main/res/values-pl/strings.xml b/pdf/src/main/res/values-pl/strings.xmlindex ad069e35bf..978507d0be 100644--- a/pdf/src/main/res/values-pl/strings.xml+++ b/pdf/src/main/res/values-pl/strings.xml@@ -17,5 +17,5 @@ <string name="pdf_save_as_copy">Zapisz kopię</string> <string name="auto_detect">Automatyczne wykrywanie</string> <string name="safe_pdf_viewer_title">Przeglądarka PDF (bezpieczna)</string>- <string name="safe_pdf_error">Tego pliku PDF nie można otworzyć za pomocą bezpiecznej przeglądarki. Możliwe, że jest zaszyfrowany lub korzysta z nieobsługiwanych funkcji.</string>+ <string name="safe_pdf_error">Tego pliku PDF nie można otworzyć za pomocą bezpiecznej przeglądarki. Możliwe, że jest uszkodzony lub korzysta z nieobsługiwanych funkcji.</string> </resources>
pdf/src/main/res/values-zh-rCN/strings.xml
diff --git a/pdf/src/main/res/values-zh-rCN/strings.xml b/pdf/src/main/res/values-zh-rCN/strings.xmlindex 3cdfee6444..0764fb3b7d 100644--- a/pdf/src/main/res/values-zh-rCN/strings.xml+++ b/pdf/src/main/res/values-zh-rCN/strings.xml@@ -16,6 +16,6 @@ <string name="auto_detect">自动检测</string> <string name="pdf_save">保存</string> <string name="pdf_save_as_copy">另存为副本</string>- <string name="safe_pdf_error">安全查看器无法打开此 PDF。它可能已加密或使用不支持的功能。</string>+ <string name="safe_pdf_error">安全查看器无法打开此 PDF。它可能已损坏或使用不支持的功能。</string> <string name="safe_pdf_viewer_title">PDF 查看器(安全)</string> </resources>
pdf/src/main/res/values/strings.xml
diff --git a/pdf/src/main/res/values/strings.xml b/pdf/src/main/res/values/strings.xmlindex 8cddcf6131..9ae66d15fd 100644--- a/pdf/src/main/res/values/strings.xml+++ b/pdf/src/main/res/values/strings.xml@@ -3,7 +3,7 @@ <string name="search_label">Find</string> <string name="open_pdf">Open PDF</string> <string name="safe_pdf_viewer_title">PDF Viewer (safe)</string>- <string name="safe_pdf_error">This PDF could not be opened by the safe viewer. It may be encrypted or use unsupported features.</string>+ <string name="safe_pdf_error">This PDF could not be opened by the safe viewer. It may be damaged or use unsupported features.</string> <string name="capture_pdf">Capture PDF</string> <string name="capture_pdf_title">Capture PDF</string> <string name="request_camera_permission">Request Camera Permission</string>
photos/build.gradle.kts
diff --git a/photos/build.gradle.kts b/photos/build.gradle.ktsindex d6bf50cfad..d550bce503 100644--- a/photos/build.gradle.kts+++ b/photos/build.gradle.kts@@ -18,6 +18,9 @@ android { // compressed; store it uncompressed so ONNX Runtime can read it directly // from assets. (SigLIP2 semantic search now lives in OpenAssistant.) noCompress += "onnx"+ // ncnn-android is generalist; photos only uses PpOcr (OCR), so strip the+ // portrait (erdnet) model it never loads.+ ignoreAssetsPattern = "!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~:erdnet.*" } packaging { jniLibs {@@ -39,14 +42,14 @@ dependencies { implementation(libs.androidx.compose.foundation) implementation("androidx.compose.material:material-icons-extended") implementation(libs.androidx.fragment.ktx)- implementation(libs.maplibre.compose)+ implementation(project(":library:map")) implementation(libs.coil.compose) implementation(libs.coil.video) implementation(libs.androidx.exifinterface) // Face detection (BlazeFace), face embedding (EdgeFace), and subject // segmentation (U²-Net) all run on ONNX Runtime (MIT, FOSS, no Play- // Services / no MediaPipe). The native .so ships via :library:ocr, but this- // module needs its own compile dependency to call the ORT API directly.+ // Services / no MediaPipe). Photos owns this dependency directly (it is no+ // longer pulled in transitively via :library:ocr, which now uses ncnn). implementation(libs.onnxruntime.android) implementRoom(libs)
photos/src/main/java/com/vayunmathur/photos/ui/MapPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/MapPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/MapPage.ktindex e9790bd6ed..144ce84f2f 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/MapPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/MapPage.kt@@ -43,10 +43,9 @@ import com.vayunmathur.photos.util.GalleryViewModel import com.vayunmathur.photos.util.ImageLoader import com.vayunmathur.photos.util.PhotoMapViewModel import kotlinx.coroutines.delay-import org.maplibre.compose.camera.rememberCameraState-import org.maplibre.compose.map.MaplibreMap-import org.maplibre.compose.style.BaseStyle-import org.maplibre.compose.util.ClickResult+import com.vayunmathur.library.map.RasterMap+import com.vayunmathur.library.map.TileSource+import com.vayunmathur.library.map.rememberCameraState import org.maplibre.spatialk.geojson.Position // Helper class to hold cluster data@@ -105,12 +104,11 @@ fun MapPage( Scaffold(bottomBar = { NavigationBar(Route.Map, backStack) }) { paddingValues -> Box(Modifier.padding(paddingValues).fillMaxSize()) {- MaplibreMap(- baseStyle = BaseStyle.Uri("https://tiles.openfreemap.org/styles/liberty"),+ RasterMap( cameraState = cameraState,- onMapClick = { _, _ ->+ tileSource = TileSource.CartoVoyager,+ onMapClick = { selectedCluster = null- ClickResult.Pass }, onFrame = { val projection = cameraState.projection
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex a23fe90158..8c2901d246 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -37,6 +37,7 @@ include(":library:e2ee-p2p") include(":library:widgets") include(":library:work") include(":library:ocr")+include(":library:map") include(":calendar") include(":contacts") include(":pdf")
weather/build.gradle.kts
diff --git a/weather/build.gradle.kts b/weather/build.gradle.ktsindex 4b609495a2..1682b0b971 100644--- a/weather/build.gradle.kts+++ b/weather/build.gradle.kts@@ -15,8 +15,8 @@ android { applicationId = "com.vayunmathur.weather" } // The Rust build drops <abi>/libweather_om.so under this dir; register it as- // a jniLibs source so AGP packages the native lib like the existing- // libmaplibre.so.+ // a jniLibs source so AGP packages the native lib alongside the app's other+ // native libraries. sourceSets["main"].jniLibs.directories.add(layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath) } @@ -142,7 +142,7 @@ dependencies { implementation(project(":library:network")) implementation(project(":library:widgets")) implementation(libs.androidx.datastore.preferences)- implementation(libs.maplibre.compose)+ implementation(project(":library:map")) implementRoom(libs) implementation(project(":library:room")) }
weather/src/main/java/com/vayunmathur/weather/ui/WeatherMapPage.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/ui/WeatherMapPage.kt b/weather/src/main/java/com/vayunmathur/weather/ui/WeatherMapPage.ktindex 727d20657e..b6dc6d09b5 100644--- a/weather/src/main/java/com/vayunmathur/weather/ui/WeatherMapPage.kt+++ b/weather/src/main/java/com/vayunmathur/weather/ui/WeatherMapPage.kt@@ -69,18 +69,14 @@ import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.withContext import kotlinx.datetime.TimeZone-import org.maplibre.compose.camera.CameraPosition-import org.maplibre.compose.camera.rememberCameraState-import org.maplibre.compose.expressions.dsl.const-import org.maplibre.compose.layers.RasterLayer-import org.maplibre.compose.map.GestureOptions-import org.maplibre.compose.map.MapOptions-import org.maplibre.compose.map.MaplibreMap-import org.maplibre.compose.map.OrnamentOptions-import org.maplibre.compose.map.RenderOptions-import org.maplibre.compose.sources.rememberImageSource-import org.maplibre.compose.style.BaseStyle-import org.maplibre.compose.util.PositionQuad+import com.vayunmathur.library.map.CameraPosition+import com.vayunmathur.library.map.GestureOptions+import com.vayunmathur.library.map.ImageOverlay+import com.vayunmathur.library.map.MapOptions+import com.vayunmathur.library.map.OrnamentOptions+import com.vayunmathur.library.map.RasterMap+import com.vayunmathur.library.map.TileSource+import com.vayunmathur.library.map.rememberCameraState import org.maplibre.spatialk.geojson.BoundingBox import org.maplibre.spatialk.geojson.Position @@ -104,27 +100,6 @@ private const val RASTER_MAX_DIM = 512 */ private const val MIN_ZOOM_FOR_REGION_TZ = 7.0 -/** Muted, keyless raster basemap. Isolated here so the provider is swappable. */-private const val BASEMAP_TILE_URL =- "https://a.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png"--private fun rasterStyleJson(): String = """-{- "version": 8,- "sources": {- "carto-light": {- "type": "raster",- "tiles": ["$BASEMAP_TILE_URL"],- "tileSize": 256,- "attribution": "© OpenStreetMap © CARTO"- }- },- "layers": [- { "id": "carto-light", "type": "raster", "source": "carto-light" }- ]-}-""".trimIndent()- /** A decoded + geolocated weather field ready to colorize into a bitmap. */ private data class DecodedRegion( val values: FloatArray,@@ -168,7 +143,7 @@ fun WeatherMapPage( // north-up, no tilt so the axis-aligned image quad stays correct. val camera = rememberCameraState(- CameraPosition(target = Position(longitude, latitude), zoom = 7.0, bearing = 0.0, tilt = 0.0),+ CameraPosition(target = Position(longitude, latitude), zoom = 7.0), ) var metadata by remember { mutableStateOf<OmMapMetadata?>(null) }@@ -176,9 +151,8 @@ fun WeatherMapPage( var userScrubbed by remember { mutableStateOf(false) } var visibleBbox by remember { mutableStateOf<BoundingBox?>(null) } var overlay by remember { mutableStateOf<ImageBitmap?>(null) }- var overlayQuad by remember { mutableStateOf<PositionQuad?>(null) }+ var overlayBounds by remember { mutableStateOf<BoundingBox?>(null) } var loading by remember { mutableStateOf(false) }- // The viewer's own zone: the primary time label is always shown in it. val userZone = remember { TimeZone.currentSystemDefault() } // The zone of the map center, resolved only when sufficiently zoomed in.@@ -190,8 +164,6 @@ fun WeatherMapPage( // back and forth (or re-selecting a measure/time) doesn't re-fetch. val cache = remember { mutableMapOf<String, DecodedRegion>() } - val styleJson = remember { rasterStyleJson() }- val supportedMetrics = remember(metadata) { metadata?.let { m -> mapMetrics.filter { m.supports(it) } } ?: mapMetrics }@@ -306,7 +278,7 @@ fun WeatherMapPage( if (region != null) { overlay = colorizeToBitmap(region.values, region.width, region.height, req.metric.colorRamp)- overlayQuad = quadFor(region.bbox)+ overlayBounds = region.bbox } } }@@ -315,28 +287,20 @@ fun WeatherMapPage( val valueFormatter = metricValueFormatter(selectedMetric, tempUnit, windUnit, pressureUnit) Box(modifier = Modifier.fillMaxSize()) {- MaplibreMap(+ RasterMap( modifier = Modifier.fillMaxSize(),- baseStyle = BaseStyle.Json(styleJson), cameraState = camera,+ tileSource = TileSource.CartoPositron, options = MapOptions(- RenderOptions(), // Lock rotation/tilt so the north-up image quad stays aligned.- GestureOptions.RotationLocked,- OrnamentOptions.AllDisabled,+ gestureOptions = GestureOptions.RotationLocked,+ // Weather shows its own attribution in the bottom panel.+ ornamentOptions = OrnamentOptions.AllDisabled, ),- ) {- val bitmap = overlay- val quad = overlayQuad- if (bitmap != null && quad != null) {- val source = rememberImageSource(position = quad, bitmap = bitmap)- RasterLayer(- id = "weather-om",- source = source,- opacity = const(0.7f),- )- }- }+ imageOverlay = overlay?.let { bmp ->+ overlayBounds?.let { bounds -> ImageOverlay(bmp, bounds, 0.7f) }+ },+ ) // Top bar: back + title + measure selector. Column(@@ -485,14 +449,6 @@ private fun Legend(metric: WeatherMetric, minLabel: String, maxLabel: String) { } } -/** Axis-aligned [PositionQuad] over [bbox] corners (north-up map). */-private fun quadFor(bbox: BoundingBox): PositionQuad = PositionQuad(- topLeft = Position(bbox.west, bbox.north),- topRight = Position(bbox.east, bbox.north),- bottomRight = Position(bbox.east, bbox.south),- bottomLeft = Position(bbox.west, bbox.south),-)- /** Overlay raster size for [bbox], longest side [RASTER_MAX_DIM], aspect-matched. */ private fun rasterSize(bbox: BoundingBox): Pair<Int, Int> { val lonSpan = abs(bbox.east - bbox.west).coerceAtLeast(1e-6)