Location refactor compiles and seemingly works

Location updates now handled in a more compose friendly way via StateFlow
Lots of small changed in MainActivity and DetailDialogShell to make them platform independent
Add new platform apis for openUrl, openMap (AppNavigator)
Add Platform independent OutboxScheduler
Try to clean up event handling of FoundEvents and location updates (need more cleanup)
New wrapper for handling App Context in shared (could be used to clean up integration further)
This commit is contained in:
Olof Hedman
2025-09-24 16:23:38 +02:00
parent 0d1e54fcd8
commit 642e546a09
20 changed files with 317 additions and 230 deletions

View File

@@ -137,6 +137,7 @@ import app.klottr.ui.UsernameDialog
import app.klottr.ui.WikiArticleDialog // Ny: dialogskalet ligger nu i ui-paketet
import app.klottr.ui.WriteDocContent // Använd delad, material-fri formulär-UI
import app.klottr.auth.AuthPlatform
import app.klottr.events.FoundEvents
import app.klottr.util.AuthShared
import app.klottr.util.PlatformAuthStorage
import app.klottr.util.AuthStorageDelegate
@@ -145,7 +146,7 @@ import app.klottr.util.FoundStore
import app.klottr.util.FoundStore.LAYER_KLOTTER
import app.klottr.util.ImageBitmapCache
import app.klottr.util.KLog
import app.klottr.util.LastLocationStore
import app.klottr.location.LastLocationStore
import app.klottr.util.NoteDetailCache
import app.klottr.util.OutboxStore
import app.klottr.util.SettingsStore
@@ -172,6 +173,11 @@ import app.klottr.maps.MapContainer
import app.klottr.maps.MapFeature
import app.klottr.maps.MapState
import app.klottr.maps.MapUiSettings
import app.klottr.platform.AndroidAppContext
import app.klottr.platform.AppNavigator
import app.klottr.platform.OutboxScheduler
import app.klottr.platform.UiFeedback
import app.klottr.platform.UiFeedbackDuration
import app.klottr.maps.MapType as CrossMapType
class MainActivity : ComponentActivity() {
@@ -186,6 +192,7 @@ class MainActivity : ComponentActivity() {
KLog.setEnabled(BuildConfig.KLLOG_DEBUG) // Styr loggnivå via buildflagga
app.klottr.prefs.KvPrefs.init(applicationContext)
LocationServiceProvider.init(applicationContext)
AndroidAppContext.install(applicationContext)
// FG + (ev) BG platstillstånd
fgPermissionLauncher =
@@ -391,58 +398,40 @@ private fun KlottrAppShell(
LaunchedEffect(Unit) {
val gp = LocationServiceProvider.get().current(highAccuracy = false)
if (gp != null) {
LastLocationStore.lastKnownLocation = android.location.Location("kmp").apply {
latitude = gp.lat
longitude = gp.lon
time = gp.timeMillis ?: System.currentTimeMillis()
accuracy = (gp.accuracyMeters ?: 0.0).toFloat()
}
// LastLocationStore.lastKnownLocation = android.location.Location("kmp").apply {
// latitude = gp.lat
// longitude = gp.lon
// time = gp.timeMillis ?: System.currentTimeMillis()
// accuracy = (gp.accuracyMeters ?: 0.0).toFloat()
// }
FoundStore.updateAwayFlags(gp.lat, gp.lon)
locationTick++
}
}
// Direkt UI-uppdatering från LocationService
DisposableEffect(Unit) {
val filter = IntentFilter(LocationService.ACTION_FOUND_UPDATED)
val receiver = object : BroadcastReceiver() {
override fun onReceive(ctx: Context?, intent: Intent?) {
forceEmptyFound = false
refreshFound()
}
}
if (Build.VERSION.SDK_INT >= 33) {
context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
} else {
@Suppress("DEPRECATION")
context.registerReceiver(receiver, filter)
}
onDispose { try { context.unregisterReceiver(receiver) } catch (_: Exception) {} }
}
// Direkt UI-uppdatering när FoundStore/KvPrefs ändras (oavsett broadcast)
DisposableEffect(Unit) {
val handler = android.os.Handler(android.os.Looper.getMainLooper())
val kvListener: (String?) -> Unit = {
handler.post {
forceEmptyFound = false
refreshFound() // trigga recomposition av “Senaste”
}
}
app.klottr.prefs.KvPrefs.addListener(kvListener)
onDispose { app.klottr.prefs.KvPrefs.removeListener(kvListener) }
}
// TODO: OH: Detta ska inte behövas
// DisposableEffect(Unit) {
// val handler = android.os.Handler(android.os.Looper.getMainLooper())
// val kvListener: (String?) -> Unit = {
// handler.post {
// forceEmptyFound = false
// refreshFound() // trigga recomposition av “Senaste”
// }
// }
// app.klottr.prefs.KvPrefs.addListener(kvListener)
// onDispose { app.klottr.prefs.KvPrefs.removeListener(kvListener) }
// }
// Lyssna på KMP LocationService-flöde istället för broadcast
LaunchedEffect(currentLoc.value?.lat, currentLoc.value?.lon) {
currentLoc.value?.let { gp ->
LastLocationStore.lastKnownLocation = android.location.Location("kmp").apply {
latitude = gp.lat
longitude = gp.lon
time = gp.timeMillis ?: System.currentTimeMillis()
accuracy = (gp.accuracyMeters ?: 0.0).toFloat()
}
// LastLocationStore.lastKnownLocation = android.location.Location("kmp").apply {
// latitude = gp.lat
// longitude = gp.lon
// time = gp.timeMillis ?: System.currentTimeMillis()
// accuracy = (gp.accuracyMeters ?: 0.0).toFloat()
// }
FoundStore.updateAwayFlags(gp.lat, gp.lon)
locationTick++
}
@@ -450,15 +439,13 @@ private fun KlottrAppShell(
// 🔴 NYTT: Omedelbar UI-uppdatering när FoundStore ändras (SharedPreferences)
DisposableEffect(Unit) {
val prefs = context.getSharedPreferences("klottr_found_store", Context.MODE_PRIVATE)
val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, _ ->
// Found updates via shared event bus (no broadcasts)
LaunchedEffect(Unit) {
FoundEvents.foundUpdated.collect {
// Trigga omritning varje gång FoundStore uppdateras
forceEmptyFound = false
refreshFound()
}
prefs.registerOnSharedPreferenceChangeListener(listener)
onDispose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }
}
LaunchedEffect(showWiki, wikiRadius, showDm, dmRadius, showFornsok, fornsokRadius) {
@@ -525,8 +512,8 @@ private fun KlottrAppShell(
// Förladdning av etiketter/bilder (oförändrad logik, flyttad hit)
LaunchedEffect(foundKey) {
val my = LastLocationStore.lastKnownLocation
val myLat = my?.latitude
val myLon = my?.longitude
val myLat = my.value?.lat
val myLon = my.value?.lon
labelOverrides.clear()
foundList.forEach { f ->
if (f.layer == LAYER_KLOTTER) {
@@ -581,8 +568,7 @@ private fun KlottrAppShell(
KlottrHomeContent(
contentPadding = padding,
entries = foundList,
currentLat = LastLocationStore.lastKnownLocation?.latitude,
currentLon = LastLocationStore.lastKnownLocation?.longitude,
location = LastLocationStore.lastKnownLocation.collectAsState(),
showCoords = showCoords,
labelOverrides = labelOverrides,
isClickable = { f ->
@@ -653,7 +639,6 @@ private fun KlottrAppShell(
nearbyLoading = true
nearbyError = null
showNearby = true
val ctx = context
scope.launch {
val gp = LocationServiceProvider.get().current(highAccuracy = false)
if (gp == null) {
@@ -697,7 +682,6 @@ private fun KlottrAppShell(
val nowMillis = System.currentTimeMillis()
app.klottr.nearby.markNewFinds(
ctx = ctx,
entries = bundle.entries, // Använd direkt från bundle
nowMillis = nowMillis,
onMarked = { refreshFound() }
@@ -760,10 +744,7 @@ private fun KlottrAppShell(
onKlotterClick = { id, la, lo, label ->
openKlotter = OpenKlotter(id = id, lat = la, lon = lo, label = label)
},
onOpenUrl = { _, url ->
val i = Intent(Intent.ACTION_VIEW, Uri.parse(url))
try { context.startActivity(i) } catch (_: Exception) {}
},
onOpenUrl = { _, url -> AppNavigator.openUrl(url) },
isKnownNote = { noteId ->
// Känd = finns i Hittat (FoundStore) → ska alltid visa titel
FoundStore
@@ -807,14 +788,17 @@ private fun KlottrAppShell(
forceEmptyFound = true // Visa tomt direkt
refreshFound() // Tvinga omritning
// 1) Nollställ sessions-gates inne i tjänsten
context.startService(
Intent(context, LocationService::class.java)
.setAction(LocationService.ACTION_CLEAR_FOUND_SESSION)
)
// 2) Pinga UI:t att rita om (nollat läge)
context.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED))
// Clear session + notify via shared events (handled in platform location impl)
FoundStore.clearAll();
FoundEvents.notifyFoundUpdated()
// // 1) Nollställ sessions-gates inne i tjänsten
// context.startService(
// Intent(context, LocationService::class.java)
// .setAction(LocationService.ACTION_CLEAR_FOUND_SESSION)
// )
//
// // 2) Pinga UI:t att rita om (nollat läge)
// context.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED))
// 3) Be tjänsten göra en rescan
// old Android service call removed (handled in shared layer)
@@ -907,9 +891,9 @@ private fun KlottrAppShell(
var isSavingDoc by remember { mutableStateOf(false) }
if (showWrite) {
// Lagra positionen när man klickat Klottra:
val initial = LastLocationStore.lastKnownLocation
val initialLat = initial?.latitude
val initialLon = initial?.longitude
val initial = LastLocationStore.lastKnownLocation.collectAsState()
val initialLat = initial.value?.lat
val initialLon = initial.value?.lon
WriteDocDialog(
onClose = { showWrite = false },
@@ -967,7 +951,7 @@ private fun KlottrAppShell(
when (outcome) {
is CreateNoteOutcome.Success -> {
Toast.makeText(context, "Sparat.", Toast.LENGTH_SHORT).show()
UiFeedback.showMessage("Sparat.")
// Markera nyskapad notis som "hittad" och uppdatera UI direkt
scope.launch(Dispatchers.IO) {
@@ -997,16 +981,18 @@ private fun KlottrAppShell(
timeMillis = System.currentTimeMillis()
)
withContext(Dispatchers.Main) {
context.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED))
// TODO: OH: Nog renare om foundstore är ansvarig för att skicka FoundEvents.
FoundEvents.notifyFoundUpdated()
}
// Tysta avisering för just detta klotter under 60s (slipper “pling” på eget klotter)
context.startService(
Intent(context, LocationService::class.java)
.setAction(LocationService.ACTION_SUPPRESS_NOTIFY)
.putExtra("layer", LAYER_KLOTTER)
.putExtra("id", match.i.toString())
.putExtra("ttlMs", 60_000L) // Valfri – hur länge det ska vara tyst
)
// TODO: OH: How to implement? Via foundstore?
// context.startService(
// Intent(context, LocationService::class.java)
// .setAction(LocationService.ACTION_SUPPRESS_NOTIFY)
// .putExtra("layer", LAYER_KLOTTER)
// .putExtra("id", match.i.toString())
// .putExtra("ttlMs", 60_000L) // Valfri – hur länge det ska vara tyst
// )
}
} catch (_: Throwable) { /* no-op */ }
}
@@ -1060,24 +1046,26 @@ private fun KlottrAppShell(
)
},
scheduleUpload = {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val req = OneTimeWorkRequestBuilder<OutboxWorker>()
.setConstraints(constraints).build()
WorkManager.getInstance(context).enqueue(req)
//TODO: OH: Make sure sheduleUpload adhere to connected constraint.
OutboxScheduler.scheduleUpload();
// val constraints = Constraints.Builder()
// .setRequiredNetworkType(NetworkType.CONNECTED)
// .build()
// val req = OneTimeWorkRequestBuilder<OutboxWorker>()
// .setConstraints(constraints).build()
// WorkManager.getInstance(context).enqueue(req)
}
)
}
when (queued) {
QueueOutboxOutcome.Queued -> {
Toast.makeText(context, "Offline. Sparas i utkorgen.", Toast.LENGTH_LONG).show()
UiFeedback.showMessage( "Offline. Sparas i utkorgen.")
showWrite = false
}
QueueOutboxOutcome.ImagePersistFailed -> {
val msg = outcome.message ?: "Bilduppladdning misslyckades."
Toast.makeText(context, "$msg\nKunde inte spara bilden lokalt.", Toast.LENGTH_LONG).show()
UiFeedback.showMessage("$msg\nKunde inte spara bilden lokalt.")
// Stanna kvar i dialogen
}
}
@@ -1130,12 +1118,14 @@ private fun KlottrAppShell(
)
},
scheduleUpload = {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val req = OneTimeWorkRequestBuilder<OutboxWorker>()
.setConstraints(constraints).build()
WorkManager.getInstance(context).enqueue(req)
//TODO: OH: Make sure sheduleUpload adhere to connected constraint.
OutboxScheduler.scheduleUpload()
// val constraints = Constraints.Builder()
// .setRequiredNetworkType(NetworkType.CONNECTED)
// .build()
// val req = OneTimeWorkRequestBuilder<OutboxWorker>()
// .setConstraints(constraints).build()
// WorkManager.getInstance(context).enqueue(req)
}
)
}
@@ -1143,11 +1133,11 @@ private fun KlottrAppShell(
when (queued) {
QueueOutboxOutcome.Queued -> {
Toast.makeText(context, "Offline. Sparas i utkorgen.", Toast.LENGTH_LONG).show()
UiFeedback.showMessage( "Offline. Sparas i utkorgen.")
showWrite = false
}
QueueOutboxOutcome.ImagePersistFailed -> {
Toast.makeText(context, "Kunde inte spara bilden lokalt.", Toast.LENGTH_LONG).show()
UiFeedback.showMessage("Kunde inte spara bilden lokalt.")
// Stanna kvar i dialogen, låt användaren försöka igen eller spara utan bild
}
}
@@ -1197,7 +1187,8 @@ private fun KlottrAppShell(
scope.launch {
me = withContext(Dispatchers.IO) { app.klottr.net.fetchMe() }
}
Toast.makeText(context, "Användarnamn satt till ”$chosen”.", Toast.LENGTH_SHORT).show()
// Should be short message.
UiFeedback.showMessage("Användarnamn satt till ”$chosen”.", UiFeedbackDuration.SHORT)
},
onLogout = {
onLogout() // ← samma onLogout som du redan skickar in till KlottrApp
@@ -1296,16 +1287,16 @@ private fun WriteDocDialog(
) {
Button(
onClick = {
val L = LastLocationStore.lastKnownLocation
val L = LastLocationStore.lastKnownLocation.value
if (L == null) {
Toast.makeText(context, "Ingen plats ännu – försök igen.", Toast.LENGTH_SHORT).show()
} else {
selectedLat = L.latitude
selectedLon = L.longitude
selectedLat = L.lat
selectedLon = L.lon
lastPosUpdateMs = System.currentTimeMillis()
// update marker + camera
val la = L.latitude
val lo = L.longitude
val la = L.lat
val lo = L.lon
mapState.features = listOf(
MapFeature.Marker(id = "sel", position = CrossLatLng(la, lo))
)
@@ -1444,22 +1435,22 @@ private fun SettingsDialog(
properties = DialogProperties(usePlatformDefaultWidth = false),
title = { Text("Inställningar") },
text = {
val context = LocalContext.current
// Version-info (Android-only) → skickas som rena strängar till delad UI
val pInfo = remember {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.packageManager.getPackageInfo(
context.packageName,
PackageManager.PackageInfoFlags.of(0)
)
} else {
@Suppress("DEPRECATION")
context.packageManager.getPackageInfo(context.packageName, 0)
}
}
val versionCode = PackageInfoCompat.getLongVersionCode(pInfo)
val versionLine = "Klottr v${BuildConfig.VERSION_NAME} (${BuildConfig.BUILD_TYPE}) • build $versionCode"
val buildTimeLine = "Byggd ${BuildConfig.BUILD_TIME_UTC}"
// val context = LocalContext.current
// // Version-info (Android-only) → skickas som rena strängar till delad UI
// val pInfo = remember {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
// context.packageManager.getPackageInfo(
// context.packageName,
// PackageManager.PackageInfoFlags.of(0)
// )
// } else {
// @Suppress("DEPRECATION")
// context.packageManager.getPackageInfo(context.packageName, 0)
// }
// }
// val versionCode = PackageInfoCompat.getLongVersionCode(pInfo)
// val versionLine = "Klottr v${BuildConfig.VERSION_NAME} (${BuildConfig.BUILD_TYPE}) • build $versionCode"
// val buildTimeLine = "Byggd ${BuildConfig.BUILD_TIME_UTC}"
Box(
Modifier
@@ -1467,8 +1458,8 @@ private fun SettingsDialog(
.height(maxDialogHeight)
) {
SettingsContent(
versionLine = versionLine,
buildTimeLine = buildTimeLine,
versionLine = "FIXME_VERSIONLINE", // TODO: OH: Do this platform independenlty
buildTimeLine = "FIXME_BUILDTIME",
onlyNew = onlyNew,
onOnlyNewChanged = onOnlyNewChanged,
showCoords = showCoords,
@@ -1565,27 +1556,22 @@ private fun KlotterDialog(
var distanceText by remember { mutableStateOf("-") }
fun recalcDistance() {
val my = app.klottr.util.LastLocationStore.lastKnownLocation
val d = my?.let { app.klottr.util.distanceMeters(it.latitude, it.longitude, lat, lon).roundToInt() }
val my = LastLocationStore.lastKnownLocation.value
val d = my?.let { app.klottr.util.distanceMeters(it.lat, it.lon, lat, lon).roundToInt() }
distanceText = d?.let { "$it\u00A0m" } ?: "-" // hårt mellanslag
}
// Räkna ut direkt vid öppning
LaunchedEffect(Unit) { recalcDistance() }
// Lyssna på plats-tick så avståndet uppdateras live
val locService = remember { LocationServiceProvider.get() }
DisposableEffect(Unit) {
val filter = IntentFilter(LocationService.ACTION_LOCATION_TICK)
val receiver = object : BroadcastReceiver() {
override fun onReceive(ctx: Context?, intent: Intent?) { recalcDistance() }
}
if (Build.VERSION.SDK_INT >= 33) {
context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
} else {
@Suppress("DEPRECATION")
context.registerReceiver(receiver, filter)
}
onDispose { try { context.unregisterReceiver(receiver) } catch (_: Exception) {} }
locService.start()
onDispose { locService.stop() }
}
val currentLocation = locService.location.collectAsState(initial = null)
LaunchedEffect(currentLocation.value?.lat, currentLocation.value?.lon, lat, lon) {
recalcDistance()
}
// Snabb hydrering från cache om vi redan har detalj/bild
@@ -1664,6 +1650,7 @@ private fun KlotterDialog(
updatedMs = detail.updatedAt
// Bild: hämta via POST (GDPR-fix), tunga saker i IO — uppdatera UI på huvudtråden.
// TODO: OH: Fix image decoding platform independently
val imgMeta = detail.image
if (imgMeta != null && imgMeta.id > 0) {
// 1) Nätverk + bitmap-dekodning i IO
@@ -1755,14 +1742,7 @@ private fun KlotterDialog(
) {
Button(
onClick = {
val labelEnc = Uri.encode(titleText.ifBlank { "Plats" })
val uri = Uri.parse("geo:$lat,$lon?q=$lat,$lon($labelEnc)")
val intent = Intent(Intent.ACTION_VIEW, uri).apply {
setPackage("com.google.android.apps.maps")
}
try { context.startActivity(intent) } catch (_: Exception) {
context.startActivity(Intent(Intent.ACTION_VIEW, uri))
}
AppNavigator.openMap(lat, lon, titleText.ifBlank { "Plats" })
}
) { Text("Maps") }
@@ -1804,7 +1784,7 @@ private fun KlotterDialog(
if (deleting) return@Button
val idL = id.toLongOrNull()
if (idL == null) {
Toast.makeText(context, "Ogiltigt id.", Toast.LENGTH_SHORT).show()
UiFeedback.showMessage( "Ogiltigt id.", UiFeedbackDuration.SHORT)
askDelete = false
return@Button
}
@@ -1813,20 +1793,15 @@ private fun KlotterDialog(
try {
val ok = withContext(Dispatchers.IO) { deleteNote(idL) }
if (ok) {
Toast.makeText(context, "Klottret raderat.", Toast.LENGTH_SHORT).show()
// 0) Ta bort ev. detaljer ur cachen (om remove finns – annars hoppar try{} över)
try { NoteDetailCache.remove(idL) } catch (_: Throwable) {}
UiFeedback.showMessage("Klottret raderat.", UiFeedbackDuration.SHORT)
FoundStore.remove(LAYER_KLOTTER, id) // id är din String i KlotterDialog
// Pinga UI:t (din DisposableEffect lyssnar på ACTION_FOUND_UPDATED och kör refreshFound())
context.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED))
FoundEvents.notifyFoundUpdated();
askDelete = false
onClose()
} else {
Toast.makeText(context, "Kunde inte radera (behörighet/nät).", Toast.LENGTH_SHORT).show()
UiFeedback.showMessage("Kunde inte radera (behörighet/nät).", UiFeedbackDuration.SHORT)
}
} finally {

View File

@@ -1,160 +0,0 @@
package app.klottr.work
import android.content.Context
import android.content.Intent
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import app.klottr.net.Geocache
import app.klottr.net.createNote
import app.klottr.net.createNoteDoc
import app.klottr.net.ImageHandle
import app.klottr.net.ImageReader
import app.klottr.net.uploadImage
import app.klottr.util.FoundStore
import app.klottr.util.OutboxStore
import java.io.File
import java.security.MessageDigest
import kotlin.math.abs
/**
* Försöker skicka allt som ligger i utkorgen (offline-klotter).
* Körs när nät finns (OneTimeWork med NetworkType.CONNECTED).
*/
class OutboxWorker(
appContext: Context,
params: WorkerParameters
) : CoroutineWorker(appContext, params) {
private fun sha256Hex(s: String): String {
val md = MessageDigest.getInstance("SHA-256")
val bytes = md.digest(s.toByteArray(Charsets.UTF_8))
val sb = StringBuilder(bytes.size * 2)
for (b in bytes) {
val i = b.toInt() and 0xff
if (i < 16) sb.append('0')
sb.append(i.toString(16))
}
return sb.toString()
}
override suspend fun doWork(): Result {
val ctx = applicationContext
// Ensure shared ImageReader has Android application context available.
ImageReader.init(applicationContext)
val pending = OutboxStore.all()
if (pending.isEmpty()) return Result.success()
val keep = mutableListOf<OutboxStore.PendingNote>()
for (p in pending) {
val ok = try {
// Stabil nyckel per pending-post (idempotens)
val sig = buildString {
append(p.createdAt).append(':')
append(p.lat).append(':')
append(p.lon).append(':')
// säkerställ att vi skiljer på text- och doc-varianten i signaturen
when {
p.title != null || p.body != null -> {
append(p.title ?: "")
append('#')
append(p.body ?: "")
}
else -> append(p.text ?: "")
}
}
val reqId = "obx-" + sha256Hex(sig).take(48)
when {
// DOC med ev. bild
(p.title != null || p.body != null) -> {
val imgId: Long? = if (p.imagePath != null && p.imageMime != null) {
val f = File(p.imagePath)
if (f.exists()) {
val read = ImageReader.read(
ImageHandle.FilePath(
path = f.path,
mimeHint = p.imageMime,
displayName = f.name
)
)
if (read != null) uploadImage(
data = read.bytes,
filename = read.filename,
mime = read.mime,
lat = p.lat,
lon = p.lon
) else null
} else null
} else null
createNoteDoc(
lat = p.lat,
lon = p.lon,
title = p.title ?: "",
body = p.body ?: (p.text ?: ""),
imageId = imgId,
radiusM = p.radiusM,
createdAt = p.createdAt,
clientRequestId = reqId
)
}
// TEXT-variant (som tidigare)
else -> {
createNote(
lat = p.lat,
lon = p.lon,
text = p.text ?: "",
createdAt = p.createdAt,
clientRequestId = reqId
)
}
}
} catch (_: Throwable) {
false
}
if (ok) {
try {
// Hämta närliggande från servern för att få rätt id/koordinater
val nearby = Geocache.getNearby(
lat = p.lat, lon = p.lon, radiusMeters = 120, ttlMs = 0L
)
// Välj bästa kandidat: nära i både tid och rum
val match = nearby
.filter { app.klottr.util.distanceMeters(p.lat, p.lon, it.a, it.o) <= 80.0 }
.minByOrNull { abs(it.c - p.createdAt) }
if (match != null) {
// Sätt label på ett rimligt sätt (titel + ev. brödtext, annars fallback)
val label = when {
!p.title.isNullOrBlank() -> p.title!!.trim()
else -> (match.t ?: "Klotter")
}
// Markera som hittad i FoundStore
FoundStore.markFound(
FoundStore.LAYER_KLOTTER,
match.i.toString(),
label = label,
lat = match.a,
lon = match.o,
timeMillis = System.currentTimeMillis()
)
// Pinga UI så “Senaste” uppdateras direkt
// ctx.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED))
}
} catch (_: Throwable) {
// Tyst fallback – Workern ska inte krascha pga visuell uppdatering
}
}
if (!ok) keep.add(p)
}
OutboxStore.replaceAll( keep)
return if (keep.isEmpty()) Result.success() else Result.retry()
}
}

View File

@@ -1,11 +1,5 @@
package app.klottr.ui
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import android.os.Build
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
@@ -31,6 +25,7 @@ import app.klottr.net.DigitaltMuseumItem
import app.klottr.net.FornsokItem
import app.klottr.net.Wikipedia
import app.klottr.location.LocationServiceProvider
import app.klottr.platform.AppNavigator
import app.klottr.util.SettingsStore
import app.klottr.util.formatCoords
import app.klottr.util.formatDistance
@@ -47,7 +42,6 @@ fun WikiArticleDialog(
lon: Double?,
onClose: () -> Unit
) {
val context = LocalContext.current
val configuration = LocalConfiguration.current
val dialogWidth = (configuration.screenWidthDp.dp * 0.98f)
@@ -59,7 +53,10 @@ fun WikiArticleDialog(
var wikiDistanceText by remember { mutableStateOf("-") }
val showCoords = remember { app.klottr.util.SettingsStore.getShowCoordinates() }
val locService = remember { LocationServiceProvider.get() }
LaunchedEffect(Unit) { locService.start() }
DisposableEffect(Unit) {
locService.start()
onDispose { locService.stop() }
}
val current = locService.location.collectAsState(initial = null)
LaunchedEffect(current.value?.lat, current.value?.lon, lat, lon) {
val gp = current.value
@@ -113,18 +110,14 @@ fun WikiArticleDialog(
actions = {
Button(onClick = {
val url = "https://sv.m.wikipedia.org/?curid=$pageId"
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
AppNavigator.openUrl(url);
}) { Text("Läs mer") }
Button(
onClick = {
if (lat != null && lon != null) {
val label = if (title.isNullOrBlank()) "Wikipedia-plats" else title // Ny: hantera null/blank
val uri = Uri.parse("geo:$lat,$lon?q=$lat,$lon(${Uri.encode(label)})") // Ändrad: använd label
val intent = Intent(Intent.ACTION_VIEW, uri).apply { setPackage("com.google.android.apps.maps") }
try { context.startActivity(intent) } catch (_: Exception) {
context.startActivity(Intent(Intent.ACTION_VIEW, uri))
}
AppNavigator.openMap(lat, lon, label)
}
},
enabled = lat != null && lon != null
@@ -201,19 +194,14 @@ fun FornsokDialog(
actions = {
Button(
onClick = {
val geoTitle = Uri.encode(title)
val geo = Uri.parse("geo:$platLat,$platLon?q=$platLat,$platLon($geoTitle)")
val intent = Intent(Intent.ACTION_VIEW, geo).apply { setPackage("com.google.android.apps.maps") }
try { context.startActivity(intent) } catch (_: Exception) {
context.startActivity(Intent(Intent.ACTION_VIEW, geo))
}
AppNavigator.openMap(platLat, platLon, title)
}
) { Text("Maps") }
Button(
onClick = {
val u = link ?: return@Button
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(u)))
AppNavigator.openUrl(u)
},
enabled = link != null
) { Text("Läs mer") }
@@ -243,7 +231,7 @@ fun DmDialog(
val showCoords = remember { SettingsStore.getShowCoordinates() }
fun recalcDmDistance() {
val my = app.klottr.location.LastLocationStore.lastKnown.value
val my = app.klottr.location.LastLocationStore.lastKnownLocation.value
val d = my?.let {
app.klottr.util.distanceMeters(it.lat, it.lon, item.lat, item.lon).roundToInt()
}
@@ -341,18 +329,7 @@ fun DmDialog(
actions = {
Button(
onClick = {
val labelEnc = Uri.encode(displayTitle)
val uri =
Uri.parse("geo:${item.lat},${item.lon}?q=${item.lat},${item.lon}($labelEnc)")
val intent = Intent(
Intent.ACTION_VIEW,
uri
).apply { setPackage("com.google.android.apps.maps") }
try {
context.startActivity(intent)
} catch (_: Exception) {
context.startActivity(Intent(Intent.ACTION_VIEW, uri))
}
AppNavigator.openMap(item.lat, item.lon, displayTitle)
}
) { Text("Maps") }
@@ -360,11 +337,7 @@ fun DmDialog(
onClick = {
val u = item.webUrl // Ändrad: objectUrl -> webUrl
if (!u.isNullOrBlank()) {
val i = Intent(Intent.ACTION_VIEW, Uri.parse(u))
try {
context.startActivity(i)
} catch (_: Exception) {
}
AppNavigator.openUrl(u)
}
},
enabled = !item.webUrl.isNullOrBlank() // Ändrad: objectUrl -> webUrl

View File

@@ -1,6 +1,6 @@
package app.klottr.util
import android.location.Location
//import android.location.Location
import app.klottr.data.NoteEntity
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlin.math.*
@@ -17,27 +17,27 @@ import kotlin.math.*
// return 2 * R * atan2(sqrt(a), sqrt(1 - a))
//}
fun roundCoord(v: Double): Double = (v * 1e5).roundToInt() / 1e5
//fun roundCoord(v: Double): Double = (v * 1e5).roundToInt() / 1e5
//
//object MatchBus {
// val match = MutableSharedFlow<NoteEntity?>(extraBufferCapacity = 1)
// fun emit(n: NoteEntity) { match.tryEmit(n) }
//}
object MatchBus {
val match = MutableSharedFlow<NoteEntity?>(extraBufferCapacity = 1)
fun emit(n: NoteEntity) { match.tryEmit(n) }
}
object LastLocationStore {
// Adapter som låter befintlig Android-kod använda android.location.Location,
// men under huven lagras värdet i KMP-store (GeoPoint) i :shared.
var lastKnownLocation: Location?
get() {
val gp = app.klottr.location.LastLocationStore.lastKnown // Hämta från delad store
return gp?.let {
Location("klottr").apply { latitude = it.lat; longitude = it.lon }
}
}
set(value) {
app.klottr.location.LastLocationStore.lastKnown = value?.let {
app.klottr.location.GeoPoint(it.latitude, it.longitude)
}
}
}
//object LastLocationStore {
// // Adapter som låter befintlig Android-kod använda android.location.Location,
// // men under huven lagras värdet i KMP-store (GeoPoint) i :shared.
// var lastKnownLocation: Location?
// get() {
// val gp = app.klottr.location.LastLocationStore.lastKnownLocation // Hämta från delad store
// return gp?.let {
// Location("klottr").apply { latitude = it.lat; longitude = it.lon }
// }
// }
// set(value) {
// app.klottr.location.LastLocationStore.lastKnownLocation = value?.let {
// app.klottr.location.GeoPoint(it.latitude, it.longitude)
// }
// }
//}