From 812db55f35161ea29e268065f38907d3d889fb1e Mon Sep 17 00:00:00 2001 From: Matt Hills Date: Sat, 31 Oct 2026 22:09:32 -0400 Subject: [PATCH] Choose photos with the system file picker, and decode large photos at a safe size Photos can now come from Android's file picker as well as the gallery: front and back cards, visas, extra pages and folder photos. + PDF uses the file picker filtered to PDFs. Gallery photos were decoded at full resolution before being scaled down; a 200 MP photo needs about 800 MB. They're now decoded at about the size that's kept. --- .../com/mattintech/papercase/MainActivity.kt | 44 +++++--- .../locker/ui/AddDocumentActivity.kt | 105 +++++++++++------- .../papercase/locker/ui/IconPickerSheet.kt | 4 +- .../locker/ui/ImageMetadataStripper.kt | 2 +- .../papercase/locker/ui/LockerActions.kt | 6 +- .../papercase/locker/ui/OrientedBitmap.kt | 14 +++ .../main/res/layout/activity_add_document.xml | 4 +- 7 files changed, 113 insertions(+), 66 deletions(-) diff --git a/app/src/main/java/com/mattintech/papercase/MainActivity.kt b/app/src/main/java/com/mattintech/papercase/MainActivity.kt index 0a929ad..9d40edf 100644 --- a/app/src/main/java/com/mattintech/papercase/MainActivity.kt +++ b/app/src/main/java/com/mattintech/papercase/MainActivity.kt @@ -66,6 +66,7 @@ import com.mattintech.papercase.locker.transfer.VaultConflictReport import com.mattintech.papercase.locker.transfer.VaultExportImportManager import com.mattintech.papercase.locker.ui.AddDocumentActivity import com.mattintech.papercase.locker.ui.DocumentViewerActivity +import com.mattintech.papercase.locker.ui.IconPickerSheet import com.mattintech.papercase.locker.ui.ImageMetadataStripper import com.mattintech.papercase.locker.ui.LockerActions import com.mattintech.papercase.locker.ui.LockerAdapter @@ -148,23 +149,28 @@ class MainActivity : AppCompatActivity() { } private val folderPhotoGalleryLauncher = - registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri -> - SessionManager.isExternalOperationActive = false - SessionManager.keepAlive() - if (uri == null) { - onFolderPhotoPicked = null - return@registerForActivityResult + registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri -> onFolderPhotoUri(uri) } + + private val folderPhotoFileLauncher = + registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> onFolderPhotoUri(uri) } + + private fun onFolderPhotoUri(uri: android.net.Uri?) { + SessionManager.isExternalOperationActive = false + SessionManager.keepAlive() + if (uri == null) { + onFolderPhotoPicked = null + return + } + lifecycleScope.launch { + val bytes = withContext(Dispatchers.IO) { + runCatching { contentResolver.openInputStream(uri)?.use { it.readBytes() } }.getOrNull() } - lifecycleScope.launch { - val bytes = withContext(Dispatchers.IO) { - runCatching { contentResolver.openInputStream(uri)?.use { it.readBytes() } }.getOrNull() - } - if (bytes != null) cropFolderPhoto(bytes) else { - onFolderPhotoPicked = null - Toast.makeText(this@MainActivity, "Couldn't read that photo", Toast.LENGTH_SHORT).show() - } + if (bytes != null) cropFolderPhoto(bytes) else { + onFolderPhotoPicked = null + Toast.makeText(this@MainActivity, "Couldn't read that photo", Toast.LENGTH_SHORT).show() } } + } private val folderPhotoCropLauncher = registerForActivityResult(CropActivity.Contract()) { bitmap -> @@ -670,7 +676,7 @@ class MainActivity : AppCompatActivity() { /** Decodes a photo upright and at a manageable size, then opens the crop screen to frame it. */ private suspend fun cropFolderPhoto(bytes: ByteArray) { - val bitmap = withContext(Dispatchers.Default) { OrientedBitmap.decode(bytes)?.let(ImageMetadataStripper::shrink) } + val bitmap = withContext(Dispatchers.Default) { OrientedBitmap.decodeForEdge(bytes, ImageMetadataStripper.MAX_EDGE)?.let(ImageMetadataStripper::shrink) } if (bitmap != null) { folderPhotoCropLauncher.launch(bitmap) } else { @@ -689,15 +695,19 @@ class MainActivity : AppCompatActivity() { SessionManager.isExternalOperationActive = true pickSaveFolderLauncher.launch(null) }, - pickPhoto = { camera, onPicked -> + pickPhoto = { source, onPicked -> onFolderPhotoPicked = onPicked when { - !camera -> { + source == IconPickerSheet.PhotoAction.CHOOSE -> { SessionManager.isExternalOperationActive = true folderPhotoGalleryLauncher.launch( androidx.activity.result.PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly) ) } + source == IconPickerSheet.PhotoAction.FILES -> { + SessionManager.isExternalOperationActive = true + folderPhotoFileLauncher.launch(arrayOf("image/*")) + } ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED -> launchFolderPhotoCamera() else -> folderPhotoCameraPermissionLauncher.launch(Manifest.permission.CAMERA) diff --git a/app/src/main/java/com/mattintech/papercase/locker/ui/AddDocumentActivity.kt b/app/src/main/java/com/mattintech/papercase/locker/ui/AddDocumentActivity.kt index c395f57..f5c9281 100644 --- a/app/src/main/java/com/mattintech/papercase/locker/ui/AddDocumentActivity.kt +++ b/app/src/main/java/com/mattintech/papercase/locker/ui/AddDocumentActivity.kt @@ -127,20 +127,24 @@ class AddDocumentActivity : AppCompatActivity() { private var tempPhotoUri: Uri? = null private var tempPhotoFile: File? = null - // Gallery picker: photos go through the crop screen + // Gallery and file pickers: photos go through the crop screen private val pickImageLauncher = - registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri -> - SessionManager.isExternalOperationActive = false - SessionManager.keepAlive() - if (uri != null) { - lifecycleScope.launch(Dispatchers.IO) { - val bytes = runCatching { contentResolver.openInputStream(uri)?.use { it.readBytes() } }.getOrNull() - withContext(Dispatchers.Main) { - if (bytes != null) openCrop(bytes) else handleSelectedUri(uri) - } - } + registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri -> onImagePicked(uri) } + + private val pickImageFileLauncher = + registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> onImagePicked(uri) } + + private fun onImagePicked(uri: Uri?) { + SessionManager.isExternalOperationActive = false + SessionManager.keepAlive() + if (uri == null) return + lifecycleScope.launch(Dispatchers.IO) { + val bytes = runCatching { contentResolver.openInputStream(uri)?.use { it.readBytes() } }.getOrNull() + withContext(Dispatchers.Main) { + if (bytes != null) openCrop(bytes) else handleSelectedUri(uri) } } + } // Crop screen: trims a photo to just the document private val cropLauncher = @@ -149,9 +153,9 @@ class AddDocumentActivity : AppCompatActivity() { if (bitmap != null) addPhotoBitmap(bitmap) } - // PDF / generic file picker + // PDF picker (the system file picker) private val pickDocumentLauncher = - registerForActivityResult(ActivityResultContracts.GetContent()) { uri -> + registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> SessionManager.isExternalOperationActive = false SessionManager.keepAlive() if (uri != null) handleSelectedUri(uri) @@ -199,7 +203,7 @@ class AddDocumentActivity : AppCompatActivity() { /** Decodes a photo (upright, at a manageable size) and opens the crop screen. */ private fun openCrop(bytes: ByteArray) { lifecycleScope.launch(Dispatchers.IO) { - val bitmap = OrientedBitmap.decode(bytes)?.let(::limitSize) + val bitmap = OrientedBitmap.decodeForEdge(bytes, MAX_PHOTO_EDGE)?.let(::limitSize) withContext(Dispatchers.Main) { if (bitmap != null) { cropLauncher.launch(bitmap) @@ -331,7 +335,7 @@ class AddDocumentActivity : AppCompatActivity() { captureFromCamera(AttachmentSlot.FRONT) } binding.btnCaptureFrontGallery.setOnClickListener { - pickFromGallery(AttachmentSlot.FRONT) + showChooseImageDialog(AttachmentSlot.FRONT) } binding.btnRemoveFront.setOnClickListener { frontAttachment = null @@ -343,7 +347,7 @@ class AddDocumentActivity : AppCompatActivity() { captureFromCamera(AttachmentSlot.BACK) } binding.btnCaptureBackGallery.setOnClickListener { - pickFromGallery(AttachmentSlot.BACK) + showChooseImageDialog(AttachmentSlot.BACK) } binding.btnRemoveBack.setOnClickListener { backAttachment = null @@ -620,11 +624,50 @@ class AddDocumentActivity : AppCompatActivity() { ) } + /** The system file picker, for photos that aren't in the gallery (Downloads, Drive, a USB stick). */ + private fun pickFromFiles(slot: AttachmentSlot, visaTitle: String = "") { + activeCaptureSlot = slot + activeVisaTitle = visaTitle + SessionManager.isExternalOperationActive = true + pickImageFileLauncher.launch(arrayOf("image/*")) + } + private fun pickPdf(slot: AttachmentSlot = AttachmentSlot.OTHER) { activeCaptureSlot = slot activeVisaTitle = "" SessionManager.isExternalOperationActive = true - pickDocumentLauncher.launch("*/*") + pickDocumentLauncher.launch(arrayOf("application/pdf")) + } + + /** Camera, gallery or files. [dismissLabel] closes the dialog without adding anything. */ + private fun showImageSourceDialog( + title: String, + slot: AttachmentSlot, + visaTitle: String = "", + dismissLabel: String = "Cancel" + ) { + SecureAlertDialogBuilder(this) + .setTitle(title) + .setItems(arrayOf("Take photo", "Choose from gallery", "Choose from files")) { _, which -> + when (which) { + 0 -> captureFromCamera(slot, visaTitle) + 1 -> pickFromGallery(slot, visaTitle) + else -> pickFromFiles(slot, visaTitle) + } + } + .setNegativeButton(dismissLabel, null) + .show() + } + + /** The front/back cards only have room for a camera and a "choose" button. */ + private fun showChooseImageDialog(slot: AttachmentSlot) { + SecureAlertDialogBuilder(this) + .setTitle("Choose a photo") + .setItems(arrayOf("From gallery", "From files")) { _, which -> + if (which == 0) pickFromGallery(slot) else pickFromFiles(slot) + } + .setNegativeButton("Cancel", null) + .show() } private fun showAddVisaDialog() { @@ -636,41 +679,21 @@ class AddDocumentActivity : AppCompatActivity() { .setTitle("Add Passport Visa") .setMessage("Enter a label for this visa or travel permit:") .setView(input.view) - .setPositiveButton("Camera") { _, _ -> + .setPositiveButton("Next") { _, _ -> val title = input.text.trim().ifBlank { "Visa ${visaAttachments.size + 1}" } - captureFromCamera(AttachmentSlot.VISA, title) - } - .setNeutralButton("Gallery") { _, _ -> - val title = input.text.trim().ifBlank { "Visa ${visaAttachments.size + 1}" } - pickFromGallery(AttachmentSlot.VISA, title) + showImageSourceDialog("Add $title", AttachmentSlot.VISA, title) } .setNegativeButton("Cancel", null) .show() } private fun showAddOtherPhotoDialog() { - SecureAlertDialogBuilder(this) - .setTitle("Add page ${pageCount() + 1}") - .setItems(arrayOf("Take photo", "Choose from gallery")) { _, which -> - if (which == 0) { - captureFromCamera(AttachmentSlot.OTHER) - } else { - pickFromGallery(AttachmentSlot.OTHER) - } - } - .setNegativeButton("Cancel", null) - .show() + showImageSourceDialog("Add page ${pageCount() + 1}", AttachmentSlot.OTHER) } /** After each page: keep going for multi-page documents. */ private fun promptNextPage() { - SecureAlertDialogBuilder(this) - .setTitle("Page ${pageCount()} added") - .setMessage("Add the next page of this document?") - .setPositiveButton("Take photo") { _, _ -> captureFromCamera(AttachmentSlot.OTHER) } - .setNeutralButton("Gallery") { _, _ -> pickFromGallery(AttachmentSlot.OTHER) } - .setNegativeButton("Done", null) - .show() + showImageSourceDialog("Page ${pageCount()} added. Add page ${pageCount() + 1}?", AttachmentSlot.OTHER, dismissLabel = "Done") } private fun AttachmentItem.isPdfItem() = diff --git a/app/src/main/java/com/mattintech/papercase/locker/ui/IconPickerSheet.kt b/app/src/main/java/com/mattintech/papercase/locker/ui/IconPickerSheet.kt index 07a2062..d521d41 100644 --- a/app/src/main/java/com/mattintech/papercase/locker/ui/IconPickerSheet.kt +++ b/app/src/main/java/com/mattintech/papercase/locker/ui/IconPickerSheet.kt @@ -32,7 +32,7 @@ class IconPickerSheet( private val onPhoto: ((PhotoAction) -> Unit)? = null, private val onChanged: (iconKey: String, colourKey: String) -> Unit = { _, _ -> } ) { - enum class PhotoAction { TAKE, CHOOSE, REMOVE } + enum class PhotoAction { TAKE, CHOOSE, FILES, REMOVE } private var photoAction: PhotoAction? = null private val dialog = SecureBottomSheetDialog(context) @@ -107,7 +107,7 @@ class IconPickerSheet( private fun photoRow() = LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL - val actions = listOf(PhotoAction.TAKE to "Camera", PhotoAction.CHOOSE to "Gallery") + + val actions = listOf(PhotoAction.TAKE to "Camera", PhotoAction.CHOOSE to "Gallery", PhotoAction.FILES to "Files") + if (hasPhoto) listOf(PhotoAction.REMOVE to "Remove") else emptyList() actions.forEachIndexed { i, (action, label) -> addView(MaterialButton(context, null, com.google.android.material.R.attr.materialButtonTonalStyle).apply { diff --git a/app/src/main/java/com/mattintech/papercase/locker/ui/ImageMetadataStripper.kt b/app/src/main/java/com/mattintech/papercase/locker/ui/ImageMetadataStripper.kt index 4b50f83..221cfb4 100644 --- a/app/src/main/java/com/mattintech/papercase/locker/ui/ImageMetadataStripper.kt +++ b/app/src/main/java/com/mattintech/papercase/locker/ui/ImageMetadataStripper.kt @@ -28,7 +28,7 @@ object ImageMetadataStripper { fun strip(bytes: ByteArray, mimeType: String, fileName: String): Result { if (!mimeType.startsWith("image/")) return Result(bytes, mimeType, fileName) - val bitmap = OrientedBitmap.decode(bytes)?.let(::shrink) ?: return Result(bytes, mimeType, fileName) + val bitmap = OrientedBitmap.decodeForEdge(bytes, MAX_EDGE)?.let(::shrink) ?: return Result(bytes, mimeType, fileName) val keepPng = mimeType == "image/png" val out = ByteArrayOutputStream() diff --git a/app/src/main/java/com/mattintech/papercase/locker/ui/LockerActions.kt b/app/src/main/java/com/mattintech/papercase/locker/ui/LockerActions.kt index fb7167d..ff7613d 100644 --- a/app/src/main/java/com/mattintech/papercase/locker/ui/LockerActions.kt +++ b/app/src/main/java/com/mattintech/papercase/locker/ui/LockerActions.kt @@ -36,13 +36,13 @@ import javax.crypto.SecretKey * device, move, edit, delete), folder options, and the folder picker. * * [pickSaveFolder] opens the system folder picker and calls back with the chosen folder. - * [pickPhoto] opens the camera (or the gallery), then the crop screen, and calls back with the photo. + * [pickPhoto] opens the camera, gallery or file picker, then the crop screen, and calls back with the photo. */ class LockerActions( private val activity: AppCompatActivity, private val repository: SecureLockerRepository, private val pickSaveFolder: (onPicked: (Uri) -> Unit) -> Unit, - private val pickPhoto: (camera: Boolean, onPicked: (Bitmap) -> Unit) -> Unit, + private val pickPhoto: (source: IconPickerSheet.PhotoAction, onPicked: (Bitmap) -> Unit) -> Unit, private val onChanged: () -> Unit ) { @@ -275,7 +275,7 @@ class LockerActions( launch { repository.saveFolder(folder.copy(photo = "")) } return } - pickPhoto(action == IconPickerSheet.PhotoAction.TAKE) { bitmap -> + pickPhoto(action) { bitmap -> launch { val photo = withContext(Dispatchers.Default) { FolderPhoto.encode(bitmap) } // Re-read so a change made while the camera was open isn't lost diff --git a/app/src/main/java/com/mattintech/papercase/locker/ui/OrientedBitmap.kt b/app/src/main/java/com/mattintech/papercase/locker/ui/OrientedBitmap.kt index 8e26d88..b753f01 100644 --- a/app/src/main/java/com/mattintech/papercase/locker/ui/OrientedBitmap.kt +++ b/app/src/main/java/com/mattintech/papercase/locker/ui/OrientedBitmap.kt @@ -12,6 +12,20 @@ import java.io.ByteArrayInputStream */ object OrientedBitmap { + /** + * Like [decode], but skips pixels while decoding so the result isn't much bigger than [maxEdge]. + * Decoding a 200 MP photo at full size needs about 800 MB, more than Android gives an app. + */ + fun decodeForEdge(bytes: ByteArray, maxEdge: Int): Bitmap? { + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) + val longest = maxOf(bounds.outWidth, bounds.outHeight) + if (longest <= 0) return null + var sample = 1 + while (longest / (sample * 2) >= maxEdge) sample *= 2 + return decode(bytes, sample) + } + /** [sampleSize] > 1 decodes a smaller image (e.g. 4 = a quarter of the width and height). */ fun decode(bytes: ByteArray, sampleSize: Int = 1): Bitmap? { val options = BitmapFactory.Options().apply { inSampleSize = sampleSize } diff --git a/app/src/main/res/layout/activity_add_document.xml b/app/src/main/res/layout/activity_add_document.xml index 6ecb5e9..2539a52 100644 --- a/app/src/main/res/layout/activity_add_document.xml +++ b/app/src/main/res/layout/activity_add_document.xml @@ -484,7 +484,7 @@ android:layout_width="48dp" android:layout_height="48dp" android:layout_marginStart="6dp" - android:contentDescription="Choose from Gallery" + android:contentDescription="Choose a photo" app:icon="@drawable/ic_image" app:iconSize="22dp" /> @@ -620,7 +620,7 @@ android:layout_width="48dp" android:layout_height="48dp" android:layout_marginStart="6dp" - android:contentDescription="Choose from Gallery" + android:contentDescription="Choose a photo" app:icon="@drawable/ic_image" app:iconSize="22dp" />