From 0acc81c9e2d0e3dd3e893b6f862dafaf3ef3615e Mon Sep 17 00:00:00 2001 From: Olof Hedman Date: Wed, 24 Sep 2025 18:40:17 +0200 Subject: [PATCH] Platform independent image picking --- .../main/java/app/klottr/KlottrAppShell.kt | 37 +++++----- .../main/java/app/klottr/WriteDocDialog.kt | 34 ++++----- shared/build.gradle.kts | 4 + .../images/VisualMediaPicker.android.kt | 36 +++++++++ .../app/klottr/images/VisualMediaPicker.kt | 15 ++++ .../klottr/images/VisualMediaPicker.ios.kt | 74 +++++++++++++++++++ 6 files changed, 161 insertions(+), 39 deletions(-) create mode 100644 shared/src/androidMain/kotlin/app/klottr/images/VisualMediaPicker.android.kt create mode 100644 shared/src/commonMain/kotlin/app/klottr/images/VisualMediaPicker.kt create mode 100644 shared/src/iosMain/kotlin/app/klottr/images/VisualMediaPicker.ios.kt diff --git a/app/src/main/java/app/klottr/KlottrAppShell.kt b/app/src/main/java/app/klottr/KlottrAppShell.kt index 86b8dad..fccd377 100644 --- a/app/src/main/java/app/klottr/KlottrAppShell.kt +++ b/app/src/main/java/app/klottr/KlottrAppShell.kt @@ -685,11 +685,10 @@ fun KlottrAppShell( // Kör delat online-flöde i IO-tråd val outcome = withContext(Dispatchers.IO) { createNoteFlow( - hasImage = draft.imageUri != null, + hasImage = draft.image != null, uploadImage = { // Plattformoberoende läsning via shared ImageReader - val uri = draft.imageUri!! - val read = ImageReader.read(ImageHandle.UriString(uri.toString())) + val read = ImageReader.read(draft.image!!) ?: run { Api.lastUploadError = "Kunde inte läsa bilddata." return@createNoteFlow null @@ -774,7 +773,7 @@ fun KlottrAppShell( val titleText = draft.title.trim() val bodyText = draft.body.trim() - val imgUri = draft.imageUri // Ta en snapshot av den valda bilden + val img = draft.image // Ta en snapshot av den valda bilden val queued = withContext(Dispatchers.IO) { queueNoteDocOutbox( @@ -784,22 +783,22 @@ fun KlottrAppShell( body = bodyText, createdAt = created, radiusM = Config.DEFAULT_KLOTTER_RADIUS_M, - hasImage = (imgUri != null), // Använd snapshotten + hasImage = (img != null), // Använd snapshotten persistImageIfAny = { - val uri = imgUri ?: return@queueNoteDocOutbox null - try { context.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) } catch (_: Exception) {} - val mime = context.contentResolver.getType(uri) ?: "image/jpeg" + val handle = img ?: return@queueNoteDocOutbox null + val read = ImageReader.read(handle) ?: return@queueNoteDocOutbox null + val mime = read.mime val ext = when { mime.equals("image/jpeg", true) || mime.equals("image/jpg", true) -> ".jpg" mime.equals("image/png", true) -> ".png" + mime.equals("image/webp", true) -> ".webp" + mime.equals("image/gif", true) -> ".gif" else -> ".img" } val outDir = File(context.filesDir, "outbox").apply { mkdirs() } val outFile = File(outDir, "img_${created}$ext") try { - context.contentResolver.openInputStream(uri)?.use { ins -> - outFile.outputStream().use { outs -> ins.copyTo(outs, 8 * 1024) } - } + outFile.outputStream().use { outs -> outs.write(read.bytes) } outFile.absolutePath to mime } catch (_: Exception) { null } }, @@ -846,7 +845,7 @@ fun KlottrAppShell( val titleText = draft.title.trim() val bodyText = draft.body.trim() - val imgUri = draft.imageUri // Ta en snapshot av den valda bilden + val img = draft.image // Ta en snapshot av den valda bilden val queued = withContext(Dispatchers.IO) { queueNoteDocOutbox( @@ -856,22 +855,22 @@ fun KlottrAppShell( body = bodyText, createdAt = created, radiusM = Config.DEFAULT_KLOTTER_RADIUS_M, - hasImage = (imgUri != null), // Använd snapshotten + hasImage = (img != null), // Använd snapshotten persistImageIfAny = { - val uri = imgUri ?: return@queueNoteDocOutbox null - try { context.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) } catch (_: Exception) {} - val mime = context.contentResolver.getType(uri) ?: "image/jpeg" + val handle = img ?: return@queueNoteDocOutbox null + val read = ImageReader.read(handle) ?: return@queueNoteDocOutbox null + val mime = read.mime val ext = when { mime.equals("image/jpeg", true) || mime.equals("image/jpg", true) -> ".jpg" mime.equals("image/png", true) -> ".png" + mime.equals("image/webp", true) -> ".webp" + mime.equals("image/gif", true) -> ".gif" else -> ".img" } val outDir = File(context.filesDir, "outbox").apply { mkdirs() } val outFile = File(outDir, "img_${created}$ext") try { - context.contentResolver.openInputStream(uri)?.use { ins -> - outFile.outputStream().use { outs -> ins.copyTo(outs, 8 * 1024) } - } + outFile.outputStream().use { outs -> outs.write(read.bytes) } outFile.absolutePath to mime } catch (_: Exception) { null } }, diff --git a/app/src/main/java/app/klottr/WriteDocDialog.kt b/app/src/main/java/app/klottr/WriteDocDialog.kt index 680bb72..e68f20f 100644 --- a/app/src/main/java/app/klottr/WriteDocDialog.kt +++ b/app/src/main/java/app/klottr/WriteDocDialog.kt @@ -28,7 +28,6 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.focus.FocusRequester -import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import app.klottr.location.LastLocationStore import app.klottr.maps.MapContainer @@ -44,6 +43,7 @@ import app.klottr.util.SettingsStore import androidx.compose.ui.graphics.ImageBitmap import app.klottr.images.loadImageBitmap import app.klottr.net.ImageHandle +import app.klottr.images.rememberVisualMediaPicker import app.klottr.maps.CameraPosition as CrossCameraPosition import app.klottr.maps.LatLng as CrossLatLng import app.klottr.maps.MapType as CrossMapType @@ -52,7 +52,7 @@ import app.klottr.maps.MapType as CrossMapType data class DocumentDraft( val title: String, val body: String, - val imageUri: Uri? + val image: ImageHandle? ) /* ---------- Skrivdialog ---------- */ @@ -66,11 +66,9 @@ fun WriteDocDialog( ) { var title by remember { mutableStateOf("") } var body by remember { mutableStateOf("") } - var imageUri by remember { mutableStateOf(null) } + var image by remember { mutableStateOf(null) } var saving by remember(resetSavingCounter) { mutableStateOf(false) } - val picker = rememberLauncherForActivityResult(PickVisualMedia()) { uri -> - imageUri = uri - } + val picker = rememberVisualMediaPicker() var selectedLat by remember { mutableStateOf(initialLat) } var selectedLon by remember { mutableStateOf(initialLon) } var lastPosUpdateMs by remember { mutableStateOf(System.currentTimeMillis()) } @@ -166,17 +164,13 @@ fun WriteDocDialog( // --- Formdel: scrollbar --- // Beräkna förhandsvisning som ImageBitmap för delad UI - val imgBitmap by produceState(initialValue = null, imageUri) { - if (imageUri == null) { + val imgBitmap by produceState(initialValue = null, image) { + if (image == null) { value = null return@produceState } - // Plattformoberoende bildladdning: - // 1) Läs bytes/mime/filnamn via KMP ImageReader (actual på Android/iOS) - // 2) Dekoda bytes → ImageBitmap via Compose MPP - value = loadImageBitmap( - ImageHandle.UriString(imageUri.toString()) - ) + // Plattformoberoende bildladdning + value = loadImageBitmap(image!!) } WriteDocContent( @@ -188,14 +182,14 @@ fun WriteDocDialog( titleError = titleError, body = body, onBodyChange = { body = it }, - hasImage = (imageUri != null), + hasImage = (image != null), imagePreview = imgBitmap, onPickImage = { - picker.launch( - PickVisualMediaRequest(PickVisualMedia.ImageOnly) - ) + picker.pickImage { picked -> + image = picked + } }, - onRemoveImage = { imageUri = null }, + onRemoveImage = { image = null }, rowTextStyle = MaterialTheme.typography.bodyMedium.copy( color = MaterialTheme.colorScheme.onSurface ) @@ -219,7 +213,7 @@ fun WriteDocDialog( } saving = true onSave( - DocumentDraft(title.trim(), body.trim(), imageUri), + DocumentDraft(title.trim(), body.trim(), image), selectedLat!!, selectedLon!! ) diff --git a/shared/build.gradle.kts b/shared/build.gradle.kts index bf0ffaf..74ba0c1 100644 --- a/shared/build.gradle.kts +++ b/shared/build.gradle.kts @@ -161,6 +161,10 @@ kotlin { // Google Sign-In implementation("com.google.android.gms:play-services-auth:21.4.0") implementation(libs.androidx.work.runtime.ktx) + // rememberLauncherForActivityResult() + implementation("androidx.activity:activity-compose:1.11.0") + // PickVisualMediaRequest + ActivityResultContracts.* + implementation("androidx.activity:activity:1.11.0") } } diff --git a/shared/src/androidMain/kotlin/app/klottr/images/VisualMediaPicker.android.kt b/shared/src/androidMain/kotlin/app/klottr/images/VisualMediaPicker.android.kt new file mode 100644 index 0000000..05c88b6 --- /dev/null +++ b/shared/src/androidMain/kotlin/app/klottr/images/VisualMediaPicker.android.kt @@ -0,0 +1,36 @@ +package app.klottr.images + +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.PickVisualMediaRequest +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.runtime.Composable +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import app.klottr.net.ImageHandle + +@Composable +actual fun rememberVisualMediaPicker(): VisualMediaPicker { + // Holds the in-flight callback across recompositions. + val callbackState = remember { mutableStateOf<((ImageHandle?) -> Unit)?>(null) } + + val launcher = rememberLauncherForActivityResult( + contract = ActivityResultContracts.PickVisualMedia() + ) { uri -> + val cb = callbackState.value + callbackState.value = null + cb?.invoke(uri?.let { ImageHandle.UriString(it.toString()) }) + } + + return remember { + object : VisualMediaPicker { + override fun pickImage(onResult: (ImageHandle?) -> Unit) { + // Prevent overlapping requests. Ignore if one is already active. + if (callbackState.value != null) return + callbackState.value = onResult + launcher.launch( + PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly) + ) + } + } + } +} diff --git a/shared/src/commonMain/kotlin/app/klottr/images/VisualMediaPicker.kt b/shared/src/commonMain/kotlin/app/klottr/images/VisualMediaPicker.kt new file mode 100644 index 0000000..cd4f397 --- /dev/null +++ b/shared/src/commonMain/kotlin/app/klottr/images/VisualMediaPicker.kt @@ -0,0 +1,15 @@ +package app.klottr.images + +import androidx.compose.runtime.Composable +import app.klottr.net.ImageHandle + +/** + * Simple, callback-based image picker. + * Actuals will present native UI and return an ImageHandle (e.g., UriString or Bytes). + */ +interface VisualMediaPicker { + fun pickImage(onResult: (ImageHandle?) -> Unit) +} + +@Composable +expect fun rememberVisualMediaPicker(): VisualMediaPicker diff --git a/shared/src/iosMain/kotlin/app/klottr/images/VisualMediaPicker.ios.kt b/shared/src/iosMain/kotlin/app/klottr/images/VisualMediaPicker.ios.kt new file mode 100644 index 0000000..639c0df --- /dev/null +++ b/shared/src/iosMain/kotlin/app/klottr/images/VisualMediaPicker.ios.kt @@ -0,0 +1,74 @@ +package app.klottr.images + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import app.klottr.net.ImageHandle +import kotlinx.cinterop.memScoped +import kotlinx.cinterop.refTo +import platform.Foundation.NSData +import platform.Foundation.create +import platform.PhotosUI.PHPickerConfiguration +import platform.PhotosUI.PHPickerFilter +import platform.PhotosUI.PHPickerResult +import platform.PhotosUI.PHPickerViewController +import platform.PhotosUI.PHPickerViewControllerDelegateProtocol +import platform.UIKit.UIApplication +import platform.UIKit.UIViewController +import platform.darwin.NSObject +import kotlin.experimental.ExperimentalObjCName + +private fun topViewController(): UIViewController? { + // Simple best-effort presenter; adjust if you have an app-level root controller handy. + val keyWindow = UIApplication.sharedApplication.keyWindow + ?: UIApplication.sharedApplication.connectedScenes.firstOrNull() + ?.valueForKey("delegate") as? NSObject // fallback is intentionally basic + return (UIApplication.sharedApplication.keyWindow?.rootViewController) +} + +private class PickerDelegate( + private val onDone: (ImageHandle?) -> Unit +) : NSObject(), PHPickerViewControllerDelegateProtocol { + + override fun picker(picker: PHPickerViewController, didFinishPicking: kotlin.collections.List<*>) { + // Dismiss immediately; resolve first item (if any) asynchronously via itemProvider. + picker.dismissViewControllerAnimated(true, completion = null) + + val first = didFinishPicking.firstOrNull() as? PHPickerResult ?: return onDone(null) + val provider = first.itemProvider + when { + provider?.hasItemConformingToTypeIdentifier("public.image") == true -> { + provider.loadDataRepresentationForTypeIdentifier("public.image") { data, _ -> + val bytes = (data as? NSData)?.let { ns -> + ByteArray(ns.length.toInt()).also { dest -> + memScoped { + val buffer = dest.refTo(0) + platform.Foundation.NSDataToByteArray(ns, dest) + } + } + } + onDone(bytes?.let { ImageHandle.Bytes(it) }) + } + } + else -> onDone(null) + } + } +} + +@Composable +actual fun rememberVisualMediaPicker(): VisualMediaPicker { + return remember { + object : VisualMediaPicker { + override fun pickImage(onResult: (ImageHandle?) -> Unit) { + val cfg = PHPickerConfiguration().apply { + filter = PHPickerFilter.imagesFilter() + selectionLimit = 1 + } + val controller = PHPickerViewController(configuration = cfg).apply { + delegate = PickerDelegate(onResult) + } + topViewController()?.presentViewController(controller, true, completion = null) + ?: onResult(null) + } + } + } +}