Platform independent image picking
This commit is contained in:
@@ -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 }
|
||||
},
|
||||
|
||||
@@ -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<Uri?>(null) }
|
||||
var image by remember { mutableStateOf<ImageHandle?>(null) }
|
||||
var saving by remember(resetSavingCounter) { mutableStateOf(false) }
|
||||
val picker = rememberLauncherForActivityResult(PickVisualMedia()) { uri ->
|
||||
imageUri = uri
|
||||
}
|
||||
val picker = rememberVisualMediaPicker()
|
||||
var selectedLat by remember { mutableStateOf<Double?>(initialLat) }
|
||||
var selectedLon by remember { mutableStateOf<Double?>(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<ImageBitmap?>(initialValue = null, imageUri) {
|
||||
if (imageUri == null) {
|
||||
val imgBitmap by produceState<ImageBitmap?>(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!!
|
||||
)
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user