pdf: add auto-framing with document edge detection
- Commit
7a531630856ff86a4971dbe3e0389dc615103bdf- Author
- Vayun Mathur <[email protected]>
- When
- 2026-06-11 20:45 UTC (5 months ago)
- Parents
2cff136
Diff
FEATURE_IDEAS.md
diff --git a/FEATURE_IDEAS.md b/FEATURE_IDEAS.mdnew file mode 100644index 0000000000..6ecd151f00--- /dev/null+++ b/FEATURE_IDEAS.md@@ -0,0 +1,178 @@+# Modern-Apps Ecosystem — Feature Ideas++> Synthesized from deep-dive research across all 20+ apps in the ecosystem.++---++## 1. Per-App Feature Ideas++### Communication & Social++#### Messages+- **Unified Message Search** — Full-text search across all 7 messaging platforms from a single search bar. Users currently have no way to find old messages without scrolling through individual conversations.+- **Scheduled Send** — Compose a message now and schedule it for delivery at a specific date/time. Ideal for reaching people in different time zones or sending reminders without forgetting.+- **Conversation Pinning** — Pin important conversations to the top of the inbox across all sources. Keeps high-priority threads accessible without hunting through a multi-source unified inbox.++#### Contacts+- **Smart Merge & Deduplicate** — Detect duplicate contacts across accounts using fuzzy matching on name, phone, and email, then offer one-tap merge. Eliminates the mess of having 3 entries for the same person from Google, Exchange, and local storage.+- **Linked Contact Cards** — Link the same person's entries across different accounts into a single unified card, showing all their phone numbers, emails, and addresses in one view. Saves time when you know a person but not which account has their info.+- **Contact Cloud Backup** — One-tap encrypted backup/restore of all contacts to local storage or cloud. Prevents data loss when switching devices.++#### Email+- **Smart Drafts & Offline Compose** — Full offline drafting with auto-save, syncing to outbox when connectivity returns. Currently there's no draft support, so users lose unsent emails.+- **Folder Management & Move-to** — Create, rename, delete IMAP folders and move emails between them with swipe gestures. Without this, users can't organize email at all.+- **Contact Name Resolution** — Resolve sender email addresses to names from the Contacts app, showing "Mom" instead of "[email protected]" in the inbox. Makes the inbox instantly more readable.++#### OpenAssistant+- **Multi-Model Support** — Allow swapping between different on-device models (Gemma variants, Phi, etc.) with a model picker, letting users trade speed for quality. Currently locked to a single Gemma 4 2B model.+- **Conversation Export & Share** — Export a conversation as Markdown, PDF, or share a specific AI response to Notes, Email, or Messages. Makes AI-generated content actionable beyond the chat window.+- **Conversation Search** — Full-text search across all past AI conversations and memories. With no search, valuable past interactions become impossible to find.++---++### Media & Entertainment++#### Camera+- **Night Mode** — Multi-frame low-light capture with noise reduction and frame alignment, producing bright, clear photos in dark environments. This is the single most requested camera feature gap.+- **Manual Pro Controls** — Expose ISO, shutter speed, white balance, and focus distance sliders for photography enthusiasts. Enables creative shots impossible with auto mode.+- **Rear Portrait Mode** — Extend MediaPipe bokeh depth estimation to the rear camera, not just front. Currently portrait mode is front-camera-only, which misses the most common portrait use case.++#### Photos+- **AI Auto-Categorization** — Use on-device ML to tag photos by detected faces, objects, scenes, and locations, creating smart albums automatically. Currently photos have no organization beyond timeline.+- **Quick Share** — Share photos/albums to Messages, Email, or any installed app via Android Sharesheet with batch selection. There are currently no sharing features at all.+- **Standalone OCR** — Run OCR directly within Photos without requiring OpenAssistant to be installed, using a bundled lightweight model. Removes the external dependency that currently gates text-from-image functionality.++#### Music+- **Queue Manager** — A visible, reorderable play queue UI where users can add songs, drag to reorder, and see what's coming next. Currently there's no way to manage upcoming playback.+- **Built-in Equalizer** — 10-band EQ with presets (Rock, Jazz, Classical, Bass Boost, etc.) using Android's AudioEffect API. Lets users tailor sound to their headphones and preferences.+- **Lyrics Display** — Fetch and display synced lyrics from embedded metadata or online sources, scrolling in time with playback. One of the most desired music player features.++#### YouPipe+- **Playlist Management** — Create, edit, and save local playlists of YouTube videos for organized viewing. Currently there's no playlist support despite being a full YouTube client.+- **Live Stream Support** — Play live streams with chat overlay, extending coverage beyond VOD content. Live content is a major gap.+- **Persistent Tabs** — Save and restore open tabs across app restarts so users don't lose their browsing context. Currently all state is lost on close.++#### Games+- **Cross-Game Leaderboards** — A unified leaderboard showing friends' scores across all 6 games, fostering friendly competition. The existing AchievementsManager and GameCenterScreen provide the foundation.+- **Daily Challenges** — Auto-generated daily puzzle challenges across Chess, Pipes, Unblock Jam, and Word Maker with streak tracking. Drives daily engagement with fresh content.+- **Cloud Save Sync** — Backup and restore game progress, achievements, and stats across devices. Currently all progress is device-local and easily lost.++---++### Productivity++#### Calendar+- **Smart Search** — Search events by title, location, attendees, or description across all calendars with instant results. Currently there's no search at all.+- **Event Reminders & Notifications** — Configurable pre-event notifications (5m, 15m, 30m, 1h, 1d) with snooze support. A calendar without reminders defeats its core purpose.+- **Drag-to-Create** — Long-press and drag on Day/Week views to create events with pre-filled time ranges. Much faster than the current tap-and-fill flow.++#### Clock+- **Snooze Support** — Add configurable snooze intervals (5/10/15 min) to alarms with a snooze limit. The absence of snooze is a critical gap for an alarm app.+- **Custom Alarm Tones** — Pick alarm sounds from device media or bundled tones instead of the system default. Personalization is table-stakes for alarm apps.+- **Persistent Stopwatch** — Save stopwatch state to Room DB so it survives app kills and device reboots. Currently state is in-memory only and easily lost during timed activities.++#### Notes+- **Folders & Tags** — Organize notes into folders and apply color-coded tags for filtering. With no organization system, notes become an unsearchable pile.+- **Image Attachments** — Embed photos and sketches inline within notes using markdown image syntax. Text-only notes are limiting for visual information.+- **Trash & Undo** — Soft-delete notes to a 30-day trash bin and add undo/redo to the editor. Currently deletes are permanent and edits are irreversible.++#### PDF+- **Annotations & Highlighting** — Draw, highlight text, and add sticky notes on PDFs with save support. The viewer currently has no markup capability.+- **Text Selection & Copy** — Select and copy text from rendered PDF pages. Basic utility that's currently missing.+- **Bookmarks & Page Thumbnails** — Bookmark important pages and show a thumbnail strip for fast navigation in long documents.++#### Files+- **File Search** — Recursive search by filename with optional content search across the filesystem. Currently users must manually browse to find files.+- **New Folder & Copy** — Create new directories and copy files/folders (not just move). These are fundamental file operations that are missing.+- **Storage Visualization** — Treemap or sunburst chart showing disk usage by directory, helping users find and clean up space hogs.++---++### Utility & Location++#### Maps+- **Saved Places & Favorites** — Star locations, name them ("Home", "Office", "Gym"), and access them from a favorites drawer for one-tap navigation. Currently there's no way to save frequently visited places.+- **Route Alternatives** — Show 2-3 route options with time/distance comparisons when planning navigation. Currently only one route is computed.+- **Offline Geocoding** — Resolve addresses to coordinates without internet using a local geocoding index. Complements the existing offline routing.++#### FindFamily+- **In-App Quick Messages** — Send preset quick messages ("On my way", "Running late", "Arrived") to family members without leaving the app. Currently requires switching to Messages.+- **Route & ETA to Family** — Tap a family member's location to get turn-by-turn directions and live ETA via Maps integration. Location is shown but not actionable.+- **Offline Location Cache** — Cache the last known locations and waypoint geofences locally so the app remains useful when connectivity drops.++#### Health+- **Goals & Achievements** — Set daily/weekly targets for steps, water, exercise, and sleep, with streak tracking and milestone badges. Data without goals lacks motivation.+- **Health Data Export** — Export records as CSV, JSON, or Apple Health/Google Fit compatible format for sharing with doctors or other apps.+- **Wearable Companion Sync** — Direct BLE sync with popular fitness bands/watches for real-time heart rate, step, and sleep data without requiring Health Connect intermediary.++#### Weather+- **Severe Weather Alerts** — Push notifications for NWS/NOAA severe weather warnings (thunderstorm, tornado, flood) based on current and saved locations. Safety-critical feature.+- **Precipitation Timeline** — Minute-by-minute rain/snow probability for the next 2 hours with a visual timeline bar. Answers "do I need an umbrella right now?"+- **Weather Radar Map** — Animated radar/satellite overlay showing precipitation movement. Helps users see what's coming, not just current conditions.++#### Passwords+- **Password Generator** — Built-in generator with configurable length, character types, and pronounceability for creating strong passwords at the point of need.+- **Breach Detection** — Check stored passwords against HaveIBeenPwned or similar databases and flag compromised credentials. Security hygiene without leaving the app.+- **Password Strength Audit** — Score all saved passwords on strength and flag weak, reused, or old passwords with actionable upgrade prompts.++#### Web+- **Bookmarks** — Save, organize, and sync bookmarks with folders and tags. Currently there's no way to save pages for later.+- **Tab Persistence** — Restore open tabs after app restart so browsing sessions aren't lost. Currently all tabs vanish on close.+- **Reader Mode** — Strip ads, navigation, and clutter from articles for distraction-free reading with adjustable font size and dark mode.++---++## 2. Cross-App Integration Ideas++### 1. Calendar + Maps: **Smart Departure Alerts**+When a calendar event has a location, automatically calculate driving/walking/transit time via Maps' offline routing engine and send a "time to leave" notification with the optimal departure time. Accounts for the user's current location, chosen transport mode, and live traffic data.++### 2. Health + Weather: **Outdoor Activity Advisor**+Combine Weather's current conditions, air quality index, and pollen data with Health's exercise records to recommend whether it's a good time for an outdoor workout. Warns asthmatics when pollen is high, suggests indoor alternatives during poor AQI, and highlights ideal weather windows.++### 3. Contacts + Messages + Email: **Unified Person Timeline**+Tap any contact to see a chronological timeline of all interactions — texts across 7 platforms, emails, and call history — in a single scrollable view. Uses Contacts as the identity anchor and pulls from Messages and Email data stores.++### 4. FindFamily + Maps + Calendar: **Family Coordination Hub**+See family members' real-time locations on the Maps view alongside today's calendar events. When a family member has an event with a location, show their ETA automatically. Enable "pick up" workflows: tap a family member → get routing → arrive at their pin.++### 5. Camera + Photos + Notes: **Scan to Note**+Capture a whiteboard, document, or handwritten page with Camera, auto-crop via PDF's perspective correction, run OCR via Photos/OpenAssistant, and insert the extracted text directly into a new or existing Note. One flow, three apps, zero friction.++### 6. OpenAssistant + Calendar + Health + Weather: **Morning Briefing**+A daily AI-generated briefing that summarizes today's calendar events, current weather with outfit suggestions, health stats from yesterday (steps, sleep score), and any pending reminders. Delivered as a notification or spoken aloud via TTS on alarm dismiss.++### 7. Music + Clock + Health: **Sleep Soundscape**+Clock's bedtime alarm (once built) triggers a Music playlist of ambient/sleep sounds, then uses Health's sleep tracking to detect when the user falls asleep and auto-fade the audio. Morning alarm gradually increases music volume for a gentle wake-up.++### 8. Web + Passwords + Email: **Secure Account Flow**+When signing up on a website in Web, auto-detect the registration form, offer to generate a strong password via Passwords, auto-fill it, save the credential, and if an email verification is needed, surface the verification email from Email as an in-browser notification for one-tap confirm.++### 9. Photos + Maps + Weather: **Memory Context Cards**+When viewing a photo in Photos, show a context card with the location on a Map tile (using offline maps), the weather conditions at that time/place (from Weather's cached data), and nearby photos from the same trip. Turns flat photo browsing into rich memory reliving.++### 10. Messages + OpenAssistant + Contacts: **Smart Reply Suggestions**+OpenAssistant analyzes incoming messages and suggests contextual quick replies based on conversation history, contact relationship, and time of day. "Your mom texted 'what time is dinner?' — suggest: 'Around 7pm!', 'Not sure yet, I'll let you know', 'Can we do 6:30?'"++---++## 3. Ecosystem-Wide Ideas++### 1. **Universal Search**+A single search bar (accessible via a persistent gesture or widget) that searches across ALL apps simultaneously — messages, emails, notes, contacts, calendar events, photos (via OCR/AI descriptions), files, browsing history, passwords, music, and map locations. Results are grouped by app with deep-links to the exact item. Built on each app's existing FTS/Room indexes.++### 2. **Shared Identity Layer**+A unified "Person" entity that links a contact's information across Contacts, Messages (across all 7 platforms), Email, FindFamily, Calendar (attendees), and Health (shared data). Every app that deals with people references this shared identity, eliminating the "which app has this person's info?" problem. Enables features like the Unified Person Timeline and Smart Reply.++### 3. **Cross-App Backup & Sync Engine**+A single backup/restore system that handles all apps' data — contacts, notes, passwords, game progress, calendar events, email accounts, message history, health records, map favorites, and app preferences. Encrypted, incremental, and restorable to a new device. Individual apps already have Room databases; this layer orchestrates them all with a unified backup format and schedule.++### 4. **Ecosystem-Wide Glance Dashboard**+A single home screen widget (building on the existing Glance widgets for Email, Calendar, Weather, and Photos) that shows a personalized daily dashboard: next calendar event, current weather, unread messages/emails count, today's step progress, and a daily photo memory. Tapping any section deep-links into the relevant app. Configurable to show/hide sections.++### 5. **OpenAssistant as System Intelligence Layer**+Elevate OpenAssistant from a standalone chat app to a system-wide AI service that any app can invoke. It already has 15+ tool integrations and an intent inference service — formalize this into an SDK. Any app can request: summarization (Email, Notes, Web), smart suggestions (Messages, Calendar), content generation (Notes, Email), image understanding (Photos, Camera), and natural language queries ("show me photos from last Christmas", "what's my next meeting?"). The AI becomes the connective tissue of the entire ecosystem.++---++*Generated by the feature-research team — June 2026*
build-logic/src/main/kotlin/RoomExtension.kt
diff --git a/build-logic/src/main/kotlin/RoomExtension.kt b/build-logic/src/main/kotlin/RoomExtension.ktindex 1b2189ea81..4fcaf5a322 100644--- a/build-logic/src/main/kotlin/RoomExtension.kt+++ b/build-logic/src/main/kotlin/RoomExtension.kt@@ -1,9 +1,7 @@-import gradle.kotlin.dsl.accessors._b19cf9d93fc61995065701c774b7d1db.implementation-import gradle.kotlin.dsl.accessors._b19cf9d93fc61995065701c774b7d1db.ksp import org.gradle.kotlin.dsl.DependencyHandlerScope fun DependencyHandlerScope.implementRoom(libs: org.gradle.accessors.dm.LibrariesForLibs) {- implementation(libs.androidx.room.runtime)- implementation(libs.androidx.room.ktx)- ksp(libs.androidx.room.compiler)+ add("implementation", libs.androidx.room.runtime)+ add("implementation", libs.androidx.room.ktx)+ add("ksp", libs.androidx.room.compiler) }
games/app/src/main/java/com/vayunmathur/games/MainActivity.kt
diff --git a/games/app/src/main/java/com/vayunmathur/games/MainActivity.kt b/games/app/src/main/java/com/vayunmathur/games/MainActivity.ktindex a1a8445cb3..dd53f29582 100644--- a/games/app/src/main/java/com/vayunmathur/games/MainActivity.kt+++ b/games/app/src/main/java/com/vayunmathur/games/MainActivity.kt@@ -177,7 +177,7 @@ fun AchievementsView(modifier: Modifier = Modifier) { LaunchedEffect(selectedGame) { withContext(Dispatchers.IO) {- val db = buildDatabase<GameHubDatabase>(context)+ val db = context.buildDatabase<GameHubDatabase>() achievements = if (selectedGame != null) { db.achievementDao().getByGame(selectedGame!!) } else {@@ -261,7 +261,7 @@ fun StatsView(modifier: Modifier = Modifier) { LaunchedEffect(Unit) { withContext(Dispatchers.IO) {- val db = buildDatabase<GameHubDatabase>(context)+ val db = context.buildDatabase<GameHubDatabase>() val all = db.achievementDao().getAll() totalAchievements = all.size unlockedAchievements = all.count { it.unlocked }
games/app/src/main/java/com/vayunmathur/games/data/GameHubProvider.kt
diff --git a/games/app/src/main/java/com/vayunmathur/games/data/GameHubProvider.kt b/games/app/src/main/java/com/vayunmathur/games/data/GameHubProvider.ktindex cef3f14f08..01d7db751b 100644--- a/games/app/src/main/java/com/vayunmathur/games/data/GameHubProvider.kt+++ b/games/app/src/main/java/com/vayunmathur/games/data/GameHubProvider.kt@@ -24,7 +24,7 @@ class GameHubProvider : ContentProvider() { } } - private val db by lazy { buildDatabase<GameHubDatabase>(context!!) }+ private val db by lazy { context!!.buildDatabase<GameHubDatabase>() } private val achievementDao by lazy { db.achievementDao() } private val scoreDao by lazy { db.scoreDao() } @@ -40,7 +40,7 @@ class GameHubProvider : ContentProvider() { val entities = runBlocking { achievementDao.getByGame(gameId) } val cursor = MatrixCursor(arrayOf("achievement_id", "game_id", "name", "description", "icon_res_name", "unlocked", "unlocked_at")) for (e in entities) {- cursor.addRow(arrayOf(e.achievementId, e.gameId, e.name, e.description, e.iconResName, if (e.unlocked) 1 else 0, e.unlockedAt ?: 0L))+ cursor.addRow(arrayOf<Any?>(e.achievementId, e.gameId, e.name, e.description, e.iconResName, if (e.unlocked) 1 else 0, e.unlockedAt ?: 0L)) } cursor }@@ -56,7 +56,7 @@ class GameHubProvider : ContentProvider() { } val cursor = MatrixCursor(arrayOf("game_id", "category", "score", "timestamp")) for (e in entities) {- cursor.addRow(arrayOf(e.gameId, e.category, e.score, e.timestamp))+ cursor.addRow(arrayOf<Any>(e.gameId, e.category, e.score, e.timestamp)) } cursor }
games/app/src/main/res/drawable/ic_launcher_foreground.xml
diff --git a/games/app/src/main/res/drawable/ic_launcher_foreground.xml b/games/app/src/main/res/drawable/ic_launcher_foreground.xmlnew file mode 100644index 0000000000..43e92bb272--- /dev/null+++ b/games/app/src/main/res/drawable/ic_launcher_foreground.xml@@ -0,0 +1,30 @@+<!--+ ~ Copyright (C) 2026 The Android Open Source Project+ ~+ ~ Licensed under the Apache License, Version 2.0 (the "License");+ ~ you may not use this file except in compliance with the License.+ ~ You may obtain a copy of the License at+ ~+ ~ http://www.apache.org/licenses/LICENSE-2.0+ ~+ ~ Unless required by applicable law or agreed to in writing, software+ ~ distributed under the License is distributed on an "AS IS" BASIS,+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ ~ See the License for the specific language governing permissions and+ ~ limitations under the License.+ -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="108dp"+ android:height="108dp"+ android:viewportWidth="960"+ android:viewportHeight="960"+ android:tint="#000000">+ <group android:scaleX="0.58"+ android:scaleY="0.58"+ android:translateX="201.6"+ android:translateY="201.6">+ <path+ android:fillColor="@android:color/white"+ android:pathData="M608,592L654,426L512,328L466,494L608,592ZM160,753L127,737Q96,724 85,692.5Q74,661 88,630L160,474L160,753ZM320,840Q287,840 263.5,816Q240,792 240,759L240,520L347,814Q350,821 352,827.5Q354,834 359,840L320,840ZM526,835Q495,846 464,832Q433,818 422,787L245,298Q234,267 248,236.5Q262,206 293,195L594,85Q625,74 655.5,88Q686,102 697,133L875,622Q886,653 872,683.5Q858,714 827,725L526,835ZM498,760L800,650Q800,650 800,650Q800,650 800,650L621,160Q621,160 621,160Q621,160 621,160L320,270Q320,270 320,270Q320,270 320,270L498,760Q498,760 498,760Q498,760 498,760ZM560,460Q560,460 560,460Q560,460 560,460L560,460Q560,460 560,460Q560,460 560,460L560,460Q560,460 560,460Q560,460 560,460L560,460Q560,460 560,460Q560,460 560,460Z"/>+ </group>+</vector>
games/app/src/main/res/mipmap-anydpi/ic_launcher.xml
diff --git a/games/app/src/main/res/mipmap-anydpi/ic_launcher.xml b/games/app/src/main/res/mipmap-anydpi/ic_launcher.xmlnew file mode 100644index 0000000000..0b0d585e42--- /dev/null+++ b/games/app/src/main/res/mipmap-anydpi/ic_launcher.xml@@ -0,0 +1,6 @@+<?xml version="1.0" encoding="utf-8"?>+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">+ <background android:drawable="@color/ic_launcher_background"/>+ <foreground android:drawable="@drawable/ic_launcher_foreground"/>+ <monochrome android:drawable="@drawable/ic_launcher_foreground"/>+</adaptive-icon>
games/app/src/main/res/resources.properties
diff --git a/games/app/src/main/res/resources.properties b/games/app/src/main/res/resources.propertiesnew file mode 100644index 0000000000..467b3efec9--- /dev/null+++ b/games/app/src/main/res/resources.properties@@ -0,0 +1 @@+unqualifiedResLocale=en-US
launcher/src/main/java/com/vayunmathur/launcher/LauncherViewModel.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/LauncherViewModel.kt b/launcher/src/main/java/com/vayunmathur/launcher/LauncherViewModel.ktindex e1f3913a35..4174f80429 100644--- a/launcher/src/main/java/com/vayunmathur/launcher/LauncherViewModel.kt+++ b/launcher/src/main/java/com/vayunmathur/launcher/LauncherViewModel.kt@@ -3,6 +3,7 @@ package com.vayunmathur.launcher import android.app.Application import android.content.Intent import android.content.pm.PackageManager+import android.content.pm.ResolveInfo import android.graphics.drawable.Drawable import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope
pdf/src/main/java/com/vayunmathur/pdf/ui/CropScreen.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/CropScreen.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/CropScreen.ktindex 2f4acfdc79..033c88625f 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/CropScreen.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/CropScreen.kt@@ -16,6 +16,7 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExtendedFloatingActionButton+import androidx.compose.material3.IconButton import androidx.compose.material3.FabPosition import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold@@ -27,6 +28,7 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment@@ -52,7 +54,9 @@ import com.vayunmathur.library.ui.IconNavigation import com.vayunmathur.library.ui.IconSave import com.vayunmathur.pdf.R import com.vayunmathur.pdf.model.Quadrilateral+import com.vayunmathur.pdf.util.AutoFrameDetector import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlin.math.roundToInt @@ -70,18 +74,28 @@ fun CropScreen( } var originalSize by remember { mutableStateOf<IntSize?>(null) } var decodedBitmap by remember { mutableStateOf<Bitmap?>(null) }+ val scope = rememberCoroutineScope() LaunchedEffect(uri) {- withContext(Dispatchers.IO) {+ val bitmap = withContext(Dispatchers.IO) { try { val source = android.graphics.ImageDecoder.createSource(context.contentResolver, uri)- val bitmap = android.graphics.ImageDecoder.decodeBitmap(source) { decoder, _, _ ->+ android.graphics.ImageDecoder.decodeBitmap(source) { decoder, _, _ -> decoder.allocator = android.graphics.ImageDecoder.ALLOCATOR_SOFTWARE decoder.isMutableRequired = false }- originalSize = IntSize(bitmap.width, bitmap.height)- decodedBitmap = bitmap- } catch (e: Exception) {+ } catch (_: Exception) { null }+ }+ if (bitmap != null) {+ originalSize = IntSize(bitmap.width, bitmap.height)+ decodedBitmap = bitmap+ if (initialQuadrilateral == null) {+ withContext(Dispatchers.Default) {+ AutoFrameDetector.detect(bitmap)+ }?.let { quadrilateral = it }+ }+ } else {+ withContext(Dispatchers.IO) { val options = BitmapFactory.Options().apply { inJustDecodeBounds = true } context.contentResolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, options)@@ -101,6 +115,22 @@ fun CropScreen( title = { Text(stringResource(R.string.crop_image)) }, navigationIcon = { IconNavigation(navBack = onBack)+ },+ actions = {+ IconButton(+ onClick = {+ decodedBitmap?.let { bmp ->+ scope.launch {+ withContext(Dispatchers.Default) {+ AutoFrameDetector.detect(bmp)+ }?.let { quadrilateral = it }+ }+ }+ },+ enabled = decodedBitmap != null+ ) {+ Text(stringResource(R.string.auto_detect))+ } } ) },
pdf/src/main/java/com/vayunmathur/pdf/util/AutoFrameDetector.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/AutoFrameDetector.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/AutoFrameDetector.ktnew file mode 100644index 0000000000..8e56490e1a--- /dev/null+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/AutoFrameDetector.kt@@ -0,0 +1,221 @@+package com.vayunmathur.pdf.util++import android.graphics.Bitmap+import androidx.compose.ui.geometry.Offset+import com.vayunmathur.pdf.model.Quadrilateral+import kotlin.math.abs+import kotlin.math.acos+import kotlin.math.max+import kotlin.math.min+import kotlin.math.roundToInt+import kotlin.math.sqrt++object AutoFrameDetector {++ private const val MAX_DIM = 500+ private const val MIN_AREA_FRACTION = 0.05f+ private const val MIN_COMPONENT_FRACTION = 0.005f++ fun detect(bitmap: Bitmap): Quadrilateral? {+ val maxDim = max(bitmap.width, bitmap.height)+ val scale = if (maxDim > MAX_DIM) MAX_DIM.toFloat() / maxDim else 1f+ val w = (bitmap.width * scale).roundToInt().coerceAtLeast(10)+ val h = (bitmap.height * scale).roundToInt().coerceAtLeast(10)+ val scaled = if (scale < 1f) Bitmap.createScaledBitmap(bitmap, w, h, true) else bitmap++ return try {+ val pixels = IntArray(w * h)+ scaled.getPixels(pixels, 0, w, 0, 0, w, h)+ val gray = grayscale(pixels)+ val blurred = gaussianBlur(gray, w, h)+ val edges = sobelMagnitude(blurred, w, h)+ val thresh = otsuThreshold(edges)+ val binary = BooleanArray(w * h) { edges[it] > thresh }+ val dilated = dilate(binary, w, h)+ findQuadFromComponents(dilated, w, h)+ } catch (_: Exception) {+ null+ } finally {+ if (scaled !== bitmap) scaled.recycle()+ }+ }++ private fun grayscale(pixels: IntArray): IntArray =+ IntArray(pixels.size) { i ->+ val p = pixels[i]+ ((p shr 16 and 0xFF) * 77 + (p shr 8 and 0xFF) * 150 + (p and 0xFF) * 29) shr 8+ }++ private fun gaussianBlur(src: IntArray, w: Int, h: Int): IntArray {+ val k = intArrayOf(2,4,5,4,2, 4,9,12,9,4, 5,12,15,12,5, 4,9,12,9,4, 2,4,5,4,2)+ val kSum = 159+ val dst = IntArray(w * h)+ for (y in 2 until h - 2) {+ for (x in 2 until w - 2) {+ var sum = 0; var ki = 0+ for (ky in -2..2) for (kx in -2..2) {+ sum += src[(y + ky) * w + (x + kx)] * k[ki++]+ }+ dst[y * w + x] = sum / kSum+ }+ }+ return dst+ }++ private fun sobelMagnitude(gray: IntArray, w: Int, h: Int): IntArray {+ val mag = IntArray(w * h)+ for (y in 1 until h - 1) {+ for (x in 1 until w - 1) {+ val gx = -gray[(y-1)*w+(x-1)] - 2*gray[y*w+(x-1)] - gray[(y+1)*w+(x-1)] ++ gray[(y-1)*w+(x+1)] + 2*gray[y*w+(x+1)] + gray[(y+1)*w+(x+1)]+ val gy = -gray[(y-1)*w+(x-1)] - 2*gray[(y-1)*w+x] - gray[(y-1)*w+(x+1)] ++ gray[(y+1)*w+(x-1)] + 2*gray[(y+1)*w+x] + gray[(y+1)*w+(x+1)]+ mag[y*w+x] = min(255, sqrt((gx.toLong()*gx + gy.toLong()*gy).toFloat()).roundToInt())+ }+ }+ return mag+ }++ private fun otsuThreshold(data: IntArray): Int {+ val hist = IntArray(256)+ for (v in data) hist[v.coerceIn(0, 255)]+++ val total = data.size+ var sumAll = 0L+ for (i in 0..255) sumAll += i.toLong() * hist[i]+ var sumB = 0L; var wB = 0; var best = 0; var maxVar = 0.0+ for (t in 0..255) {+ wB += hist[t]; if (wB == 0) continue+ val wF = total - wB; if (wF == 0) break+ sumB += t.toLong() * hist[t]+ val diff = sumB.toDouble() / wB - (sumAll - sumB).toDouble() / wF+ val v = wB.toDouble() * wF * diff * diff+ if (v > maxVar) { maxVar = v; best = t }+ }+ return best+ }++ private fun dilate(src: BooleanArray, w: Int, h: Int): BooleanArray {+ val dst = BooleanArray(w * h)+ for (y in 1 until h - 1) for (x in 1 until w - 1) {+ if (src[y*w+x] || src[(y-1)*w+x] || src[(y+1)*w+x] ||+ src[y*w+(x-1)] || src[y*w+(x+1)]) dst[y*w+x] = true+ }+ return dst+ }++ private fun findQuadFromComponents(binary: BooleanArray, w: Int, h: Int): Quadrilateral? {+ val labels = IntArray(w * h) { -1 }+ val parent = mutableListOf<Int>()++ fun find(x: Int): Int {+ var r = x; while (parent[r] != r) r = parent[r]+ var c = x; while (c != r) { val n = parent[c]; parent[c] = r; c = n }+ return r+ }+ fun union(a: Int, b: Int) { val ra = find(a); val rb = find(b); if (ra != rb) parent[ra] = rb }++ for (y in 0 until h) for (x in 0 until w) {+ if (!binary[y * w + x]) continue+ val neighbors = mutableListOf<Int>()+ if (y > 0 && binary[(y-1)*w+x]) neighbors.add(labels[(y-1)*w+x])+ if (x > 0 && binary[y*w+(x-1)]) neighbors.add(labels[y*w+(x-1)])+ if (y > 0 && x > 0 && binary[(y-1)*w+(x-1)]) neighbors.add(labels[(y-1)*w+(x-1)])+ if (y > 0 && x < w-1 && binary[(y-1)*w+(x+1)]) neighbors.add(labels[(y-1)*w+(x+1)])++ if (neighbors.isEmpty()) {+ labels[y*w+x] = parent.size; parent.add(parent.size)+ } else {+ val minL = neighbors.min()+ labels[y*w+x] = minL+ for (n in neighbors) union(n, minL)+ }+ }++ val sizes = mutableMapOf<Int, Int>()+ for (i in labels.indices) {+ if (labels[i] >= 0) { labels[i] = find(labels[i]); sizes[labels[i]] = (sizes[labels[i]] ?: 0) + 1 }+ }++ val minSize = (w * h * MIN_COMPONENT_FRACTION).toInt()+ val candidates = sizes.filter { it.value >= minSize }.entries.sortedByDescending { it.value }++ for ((label, _) in candidates) {+ val points = mutableListOf<Pair<Int, Int>>()+ for (y in 0 until h) for (x in 0 until w) {+ if (labels[y*w+x] == label) points.add(x to y)+ }+ val hull = convexHull(points)+ if (hull.size < 4) continue+ val corners = best4Corners(hull) ?: continue+ val area = polyArea(corners)+ if (area < w * h * MIN_AREA_FRACTION) continue+ val sorted = sortCorners(corners)+ return Quadrilateral(+ topLeft = Offset(sorted[0].first.toFloat() / w, sorted[0].second.toFloat() / h),+ topRight = Offset(sorted[1].first.toFloat() / w, sorted[1].second.toFloat() / h),+ bottomRight = Offset(sorted[2].first.toFloat() / w, sorted[2].second.toFloat() / h),+ bottomLeft = Offset(sorted[3].first.toFloat() / w, sorted[3].second.toFloat() / h)+ )+ }+ return null+ }++ private fun convexHull(points: List<Pair<Int, Int>>): List<Pair<Int, Int>> {+ val sorted = points.sortedWith(compareBy({ it.first }, { it.second }))+ if (sorted.size < 3) return sorted+ val lower = mutableListOf<Pair<Int, Int>>()+ for (p in sorted) {+ while (lower.size >= 2 && cross(lower[lower.size-2], lower.last(), p) <= 0) lower.removeAt(lower.size-1)+ lower.add(p)+ }+ val upper = mutableListOf<Pair<Int, Int>>()+ for (p in sorted.reversed()) {+ while (upper.size >= 2 && cross(upper[upper.size-2], upper.last(), p) <= 0) upper.removeAt(upper.size-1)+ upper.add(p)+ }+ lower.removeAt(lower.size - 1); upper.removeAt(upper.size - 1)+ return lower + upper+ }++ private fun cross(o: Pair<Int, Int>, a: Pair<Int, Int>, b: Pair<Int, Int>): Long =+ (a.first - o.first).toLong() * (b.second - o.second) -+ (a.second - o.second).toLong() * (b.first - o.first)++ private fun best4Corners(hull: List<Pair<Int, Int>>): List<Pair<Int, Int>>? {+ val n = hull.size+ if (n < 4) return null+ if (n == 4) return hull+ val angles = (0 until n).map { i ->+ val prev = hull[(i - 1 + n) % n]; val curr = hull[i]; val next = hull[(i + 1) % n]+ val v1x = (prev.first - curr.first).toDouble(); val v1y = (prev.second - curr.second).toDouble()+ val v2x = (next.first - curr.first).toDouble(); val v2y = (next.second - curr.second).toDouble()+ val len1 = sqrt(v1x*v1x + v1y*v1y); val len2 = sqrt(v2x*v2x + v2y*v2y)+ if (len1 < 1e-6 || len2 < 1e-6) Math.PI+ else acos(((v1x*v2x + v1y*v2y) / (len1 * len2)).coerceIn(-1.0, 1.0))+ }+ val indexed = angles.mapIndexed { idx, angle -> idx to angle }.sortedBy { it.second }+ val minSep = max(1, n / 6)+ val sel = mutableListOf<Int>()+ for ((idx, _) in indexed) {+ if (sel.all { e -> val d = abs(idx - e); min(d, n - d) >= minSep }) {+ sel.add(idx); if (sel.size == 4) break+ }+ }+ if (sel.size < 4) { sel.clear(); val step = n / 4; for (i in 0 until 4) sel.add(i * step) }+ return sel.sorted().map { hull[it] }+ }++ private fun polyArea(pts: List<Pair<Int, Int>>): Float {+ var area = 0f; val n = pts.size+ for (i in 0 until n) { val j = (i+1) % n; area += pts[i].first.toFloat()*pts[j].second - pts[j].first.toFloat()*pts[i].second }+ return abs(area) / 2f+ }++ private fun sortCorners(corners: List<Pair<Int, Int>>): List<Pair<Int, Int>> {+ val bySum = corners.sortedBy { it.first + it.second }+ val tl = bySum.first(); val br = bySum.last()+ val remaining = corners.toMutableList(); remaining.remove(tl); remaining.remove(br)+ val byDiff = remaining.sortedBy { it.first - it.second }+ return listOf(tl, byDiff.last(), br, byDiff.first())+ }+}
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 a6786fc929..f192076cf0 100644--- a/pdf/src/main/res/values/strings.xml+++ b/pdf/src/main/res/values/strings.xml@@ -18,5 +18,6 @@ <string name="share_pdf">Share PDF</string> <string name="crop_image">Crop Image</string> <string name="continue_label">Continue</string>+ <string name="auto_detect">Auto Detect</string> <string name="unsupported_version">This app requires either Android 15 or Google Play Services to be fully updated. If you are unable to do either of these, your device is unfortunately unsupported.</string> </resources>\ No newline at end of file