Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 27 additions & 17 deletions app/src/main/java/com/mattintech/papercase/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 ->
Expand Down Expand Up @@ -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 {
Expand All @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -331,7 +335,7 @@ class AddDocumentActivity : AppCompatActivity() {
captureFromCamera(AttachmentSlot.FRONT)
}
binding.btnCaptureFrontGallery.setOnClickListener {
pickFromGallery(AttachmentSlot.FRONT)
showChooseImageDialog(AttachmentSlot.FRONT)
}
binding.btnRemoveFront.setOnClickListener {
frontAttachment = null
Expand All @@ -343,7 +347,7 @@ class AddDocumentActivity : AppCompatActivity() {
captureFromCamera(AttachmentSlot.BACK)
}
binding.btnCaptureBackGallery.setOnClickListener {
pickFromGallery(AttachmentSlot.BACK)
showChooseImageDialog(AttachmentSlot.BACK)
}
binding.btnRemoveBack.setOnClickListener {
backAttachment = null
Expand Down Expand Up @@ -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() {
Expand All @@ -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() =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
) {

Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
4 changes: 2 additions & 2 deletions app/src/main/res/layout/activity_add_document.xml
Original file line number Diff line number Diff line change
Expand Up @@ -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" />

Expand Down Expand Up @@ -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" />

Expand Down
Loading