Merge branch 'location-service-refactor'
This commit is contained in:
@@ -1,348 +0,0 @@
|
|||||||
package app.klottr
|
|
||||||
|
|
||||||
import android.Manifest
|
|
||||||
import android.app.Notification
|
|
||||||
import android.app.NotificationChannel
|
|
||||||
import android.app.NotificationManager
|
|
||||||
import android.app.Service
|
|
||||||
import android.content.Intent
|
|
||||||
import android.content.pm.PackageManager
|
|
||||||
import android.os.Build
|
|
||||||
import android.os.IBinder
|
|
||||||
import androidx.core.app.NotificationCompat
|
|
||||||
import androidx.core.app.NotificationManagerCompat
|
|
||||||
import androidx.core.content.ContextCompat
|
|
||||||
import app.klottr.net.Geocache
|
|
||||||
import app.klottr.net.NoteDTO
|
|
||||||
import app.klottr.util.FoundStore
|
|
||||||
import app.klottr.util.LastLocationStore
|
|
||||||
import app.klottr.util.SettingsStore
|
|
||||||
// import app.klottr.util.distanceMeters
|
|
||||||
import com.google.android.gms.location.LocationCallback
|
|
||||||
import com.google.android.gms.location.LocationRequest
|
|
||||||
import com.google.android.gms.location.LocationResult
|
|
||||||
import com.google.android.gms.location.LocationServices
|
|
||||||
import com.google.android.gms.location.Priority
|
|
||||||
import com.google.android.gms.maps.model.LatLng
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.Job
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import kotlinx.coroutines.tasks.await
|
|
||||||
import kotlin.math.roundToInt
|
|
||||||
|
|
||||||
|
|
||||||
class LocationService : Service() {
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
private const val CHANNEL_LOCATION_ID = "Klottr_location" // för foreground, tyst
|
|
||||||
private const val CHANNEL_HITS_ID = "Klottr_hits" // NY kanal för fynd-notiser
|
|
||||||
|
|
||||||
const val ACTION_FOUND_UPDATED = "app.klottr.ACTION_FOUND_UPDATED"
|
|
||||||
const val ACTION_CLEAR_FOUND_SESSION = "app.klottr.ACTION_CLEAR_FOUND_SESSION"
|
|
||||||
const val ACTION_RESCAN_NOW = "app.klottr.ACTION_RESCAN_NOW"
|
|
||||||
const val ACTION_LOCATION_TICK = "app.klottr.ACTION_LOCATION_TICK"
|
|
||||||
const val ACTION_SUPPRESS_NOTIFY = "app.klottr.ACTION_SUPPRESS_NOTIFY" // Tysta notiser för ett id
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
private val scope = CoroutineScope(Dispatchers.IO + Job())
|
|
||||||
private val fused by lazy { LocationServices.getFusedLocationProviderClient(this) }
|
|
||||||
|
|
||||||
// Sessiontillstånd – används för “gå utanför ~200 m → tillåt om-avisering”
|
|
||||||
private val notifiedWhileInside = mutableMapOf<String, Boolean>() // key(layer:id) -> om vi redan aviserat denna session.
|
|
||||||
private val lastKnownDistance = mutableMapOf<String, Int>() // senaste uppmätta avståndet (meter).
|
|
||||||
private val suppressedUntil = mutableMapOf<String, Long>() // key(layer:id) -> tyst till tidsstämpel
|
|
||||||
|
|
||||||
|
|
||||||
private lateinit var callback: LocationCallback
|
|
||||||
|
|
||||||
override fun onBind(intent: Intent?): IBinder? = null
|
|
||||||
|
|
||||||
override fun onCreate() {
|
|
||||||
super.onCreate()
|
|
||||||
ensureChannel()
|
|
||||||
startForeground(1, persistentNotification())
|
|
||||||
startLocation()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onDestroy() {
|
|
||||||
try { fused.removeLocationUpdates(callback) } catch (_: Exception) {}
|
|
||||||
super.onDestroy()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
|
||||||
when (intent?.action) {
|
|
||||||
ACTION_CLEAR_FOUND_SESSION -> {
|
|
||||||
notifiedWhileInside.clear()
|
|
||||||
lastKnownDistance.clear()
|
|
||||||
}
|
|
||||||
ACTION_SUPPRESS_NOTIFY -> {
|
|
||||||
val layer = intent.getStringExtra("layer")
|
|
||||||
val id = intent.getStringExtra("id")
|
|
||||||
val ttl = intent.getLongExtra("ttlMs", 60_000L) // default 60s
|
|
||||||
if (layer != null && id != null) {
|
|
||||||
suppressedUntil[key(layer, id)] = System.currentTimeMillis() + ttl // Lägg in tystnad
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ACTION_RESCAN_NOW -> {
|
|
||||||
scope.launch {
|
|
||||||
val loc = try {
|
|
||||||
fused.lastLocation.await()
|
|
||||||
?: fused.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
|
|
||||||
} catch (_: Exception) { null }
|
|
||||||
val L = loc ?: LastLocationStore.lastKnownLocation
|
|
||||||
if (L != null) {
|
|
||||||
// Håll last known i sync om vi faktiskt fick en färsk position
|
|
||||||
LastLocationStore.lastKnownLocation = L
|
|
||||||
|
|
||||||
// Uppdatera away-flaggor för den position du ska scanna mot
|
|
||||||
FoundStore.updateAwayFlags(L.latitude, L.longitude)
|
|
||||||
|
|
||||||
// 1) Tala om att data (ev. away) kan ha ändrats
|
|
||||||
sendBroadcast(Intent(ACTION_FOUND_UPDATED))
|
|
||||||
|
|
||||||
// 2) Tvinga omritning av “Hittat” så avstånd/fetstil uppdateras direkt
|
|
||||||
sendBroadcast(Intent(ACTION_LOCATION_TICK))
|
|
||||||
|
|
||||||
// 3) Kör matchningen
|
|
||||||
checkMatches(L.latitude, L.longitude)
|
|
||||||
|
|
||||||
// Skicka ett tick så hittat uppdaterar avstånd/fet stil.
|
|
||||||
sendBroadcast(Intent(ACTION_LOCATION_TICK))
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return START_STICKY
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- Platsuppdateringar ----
|
|
||||||
|
|
||||||
private fun startLocation() {
|
|
||||||
if (!hasLocationPerms()) return
|
|
||||||
|
|
||||||
val req = LocationRequest.create().apply {
|
|
||||||
interval = 4_000L
|
|
||||||
fastestInterval = 2_000L
|
|
||||||
smallestDisplacement = 3f
|
|
||||||
priority = Priority.PRIORITY_HIGH_ACCURACY
|
|
||||||
maxWaitTime = 5_000L
|
|
||||||
}
|
|
||||||
|
|
||||||
callback = object : LocationCallback() {
|
|
||||||
override fun onLocationResult(result: LocationResult) {
|
|
||||||
val loc = result.lastLocation ?: return
|
|
||||||
LastLocationStore.lastKnownLocation = loc
|
|
||||||
sendBroadcast(Intent(ACTION_LOCATION_TICK))
|
|
||||||
|
|
||||||
scope.launch {
|
|
||||||
|
|
||||||
// Uppdatera away-flaggor för ALLA sparade fynd utifrån aktuell position
|
|
||||||
FoundStore.updateAwayFlags(loc.latitude, loc.longitude)
|
|
||||||
// (UI lyssnar på SharedPreferences, men vi pingar ändå för säkerhets skull)
|
|
||||||
sendBroadcast(Intent(ACTION_FOUND_UPDATED))
|
|
||||||
|
|
||||||
// Matcha på senaste
|
|
||||||
checkMatches(loc.latitude, loc.longitude)
|
|
||||||
|
|
||||||
// Försök förfina om noggrannheten är sämre än ~30 m
|
|
||||||
val acc = loc.accuracy
|
|
||||||
if (acc.isFinite() && acc > 30f) {
|
|
||||||
try {
|
|
||||||
val refined = fused.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
|
|
||||||
if (refined != null) {
|
|
||||||
LastLocationStore.lastKnownLocation = refined
|
|
||||||
sendBroadcast(Intent(ACTION_LOCATION_TICK))
|
|
||||||
|
|
||||||
FoundStore.updateAwayFlags(refined.latitude, refined.longitude)
|
|
||||||
sendBroadcast(Intent(ACTION_FOUND_UPDATED))
|
|
||||||
checkMatches(refined.latitude, refined.longitude)
|
|
||||||
}
|
|
||||||
} catch (_: Exception) {
|
|
||||||
// ignore
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
fused.requestLocationUpdates(req, callback, mainLooper)
|
|
||||||
} catch (_: SecurityException) {
|
|
||||||
// saknar tillstånd
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun hasLocationPerms(): Boolean {
|
|
||||||
val fine = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|
|
||||||
val coarse = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
|
|
||||||
return fine || coarse
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- Matchning ----
|
|
||||||
|
|
||||||
private suspend fun checkMatches(lat: Double, lon: Double) {
|
|
||||||
// Just nu kör vi bara klotter här (20 m). Wikipedia/DigitaltMuseum/Fornsök scannas i UI vid behov.
|
|
||||||
val showKlotter = SettingsStore.getShowKlotter()
|
|
||||||
if (showKlotter) {
|
|
||||||
val nearby: List<NoteDTO> = try {
|
|
||||||
Geocache.getNearby(lat, lon, radiusMeters = 120, ttlMs = 0L)
|
|
||||||
} catch (_: Exception) {
|
|
||||||
emptyList()
|
|
||||||
}
|
|
||||||
|
|
||||||
for (n in nearby) {
|
|
||||||
// Använder FQN för att säkert länka den delade distanceMeters från :shared.
|
|
||||||
val d = app.klottr.util.distanceMeters(lat, lon, n.a, n.o).roundToInt()
|
|
||||||
handleCandidate(
|
|
||||||
layer = FoundStore.LAYER_KLOTTER,
|
|
||||||
id = n.i.toString(),
|
|
||||||
label = n.t.orEmpty(),
|
|
||||||
pt = LatLng(n.a, n.o),
|
|
||||||
distanceM = d,
|
|
||||||
insideRadiusM = 20,
|
|
||||||
onlyNew = SettingsStore.getOnlyNewHits()
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun key(layer: String, id: String) = "$layer:$id"
|
|
||||||
|
|
||||||
private suspend fun handleCandidate(
|
|
||||||
layer: String,
|
|
||||||
id: String,
|
|
||||||
label: String,
|
|
||||||
pt: LatLng,
|
|
||||||
distanceM: Int,
|
|
||||||
insideRadiusM: Int,
|
|
||||||
onlyNew: Boolean
|
|
||||||
) {
|
|
||||||
val k = key(layer, id)
|
|
||||||
|
|
||||||
// Session-baserad återinträdesdetektion (för att slå av påminnelse tills man gått utanför ~200 m)
|
|
||||||
val OUTSIDE_RESET_M = 200
|
|
||||||
val lastD = lastKnownDistance[k]
|
|
||||||
lastKnownDistance[k] = distanceM
|
|
||||||
val reenteredSession = (lastD != null && lastD > OUTSIDE_RESET_M && distanceM <= insideRadiusM)
|
|
||||||
if (reenteredSession) {
|
|
||||||
// tillåt ny notis denna session
|
|
||||||
notifiedWhileInside[k] = false
|
|
||||||
}
|
|
||||||
|
|
||||||
// Lagrings-baserad re-arm: om FoundStore flaggat "away=true" och vi nu är inne i radien
|
|
||||||
val wasAwayStore = FoundStore.isAway(layer, id)
|
|
||||||
|
|
||||||
if (distanceM <= insideRadiusM) {
|
|
||||||
val wasNotifiedThisSession = notifiedWhileInside[k] == true
|
|
||||||
val alreadyFound = FoundStore.isFound(layer, id)
|
|
||||||
val now = System.currentTimeMillis()
|
|
||||||
|
|
||||||
// Markera i FoundStore:
|
|
||||||
// - alltid vid första fyndet
|
|
||||||
// - även vid återinträde (wasAwayStore), oavsett onlyNew, så last_visit uppdateras
|
|
||||||
// - (behåller session-reentry för bakåtkompabilitet)
|
|
||||||
val shouldMark = !alreadyFound || wasAwayStore || (!onlyNew && reenteredSession)
|
|
||||||
if (shouldMark) {
|
|
||||||
val marked = FoundStore.markFound(layer, id, label, pt.latitude, pt.longitude, now)
|
|
||||||
if (marked) sendBroadcast(Intent(ACTION_FOUND_UPDATED))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Notiser:
|
|
||||||
// - onlyNew=true → bara för helt nya (inte för återinträde)
|
|
||||||
// - onlyNew=false → en gång per session ELLER om re-arm via FoundStore (wasAwayStore) eller session-reentry
|
|
||||||
|
|
||||||
val nowMs = System.currentTimeMillis() // Nu
|
|
||||||
val suppressed = (suppressedUntil[k] ?: 0L) > nowMs // Är tystnad aktiv?
|
|
||||||
|
|
||||||
val shouldNotify = if (onlyNew) {
|
|
||||||
!alreadyFound && !wasNotifiedThisSession && !suppressed
|
|
||||||
} else {
|
|
||||||
(!wasNotifiedThisSession || wasAwayStore || reenteredSession) && !suppressed
|
|
||||||
}
|
|
||||||
if (suppressed) {
|
|
||||||
notifiedWhileInside[k] = true // Blockera fler notiser denna session
|
|
||||||
}
|
|
||||||
if (shouldNotify) {
|
|
||||||
val (title, text) = notificationTitleAndText(layer, label, distanceM)
|
|
||||||
postNotification(k, title, text)
|
|
||||||
}
|
|
||||||
|
|
||||||
// markera att vi nu befinner oss "inne"
|
|
||||||
notifiedWhileInside[k] = true
|
|
||||||
} else {
|
|
||||||
if (distanceM > OUTSIDE_RESET_M) {
|
|
||||||
// lämnat området tillräckligt långt → tillåt ny notis när vi kommer in igen
|
|
||||||
notifiedWhileInside[k] = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private fun notificationTitleAndText(layer: String, label: String, distanceM: Int): Pair<String, String> {
|
|
||||||
val dist = "≈ ${distanceM} m"
|
|
||||||
val shown = label.ifBlank {
|
|
||||||
when (layer) {
|
|
||||||
FoundStore.LAYER_KLOTTER -> "Okänt klotter"
|
|
||||||
FoundStore.LAYER_WIKI -> "Wikipedia"
|
|
||||||
FoundStore.LAYER_DM -> "DigitaltMuseum"
|
|
||||||
else -> "Plats"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
val title = when (layer) {
|
|
||||||
FoundStore.LAYER_KLOTTER -> "Funnet klotter"
|
|
||||||
FoundStore.LAYER_WIKI -> "Funnen Wikipediaplats"
|
|
||||||
FoundStore.LAYER_DM -> "Funnen DigitaltMuseum-plats"
|
|
||||||
else -> "Funnen plats"
|
|
||||||
}
|
|
||||||
return title to "$shown • $dist"
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun postNotification(tag: String, title: String, text: String) {
|
|
||||||
val builder = NotificationCompat.Builder(this, CHANNEL_HITS_ID)
|
|
||||||
.setSmallIcon(R.mipmap.ic_launcher)
|
|
||||||
.setContentTitle(title)
|
|
||||||
.setContentText(text)
|
|
||||||
.setPriority(NotificationCompat.PRIORITY_DEFAULT) // har ingen effekt på 8+, men ok
|
|
||||||
.setAutoCancel(true)
|
|
||||||
|
|
||||||
NotificationManagerCompat.from(this).notify(tag, 1001, builder.build())
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- Foreground-notis & kanal ----
|
|
||||||
|
|
||||||
private fun ensureChannel() {
|
|
||||||
if (Build.VERSION.SDK_INT >= 26) {
|
|
||||||
val mgr = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
|
|
||||||
|
|
||||||
// Foreground-kanal (tyst)
|
|
||||||
val loc = NotificationChannel(
|
|
||||||
CHANNEL_LOCATION_ID,
|
|
||||||
"Klottr plats",
|
|
||||||
NotificationManager.IMPORTANCE_MIN
|
|
||||||
).apply { description = "Bakgrundspositionering" }
|
|
||||||
mgr.createNotificationChannel(loc)
|
|
||||||
|
|
||||||
// Fynd-notiser (synliga)
|
|
||||||
val hits = NotificationChannel(
|
|
||||||
CHANNEL_HITS_ID,
|
|
||||||
"Klottr fynd",
|
|
||||||
NotificationManager.IMPORTANCE_HIGH // vill du ha pling: HIGH
|
|
||||||
).apply { description = "Aviseringar för nya/återkommande fynd" }
|
|
||||||
mgr.createNotificationChannel(hits)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun persistentNotification(): Notification {
|
|
||||||
return NotificationCompat.Builder(this, CHANNEL_LOCATION_ID)
|
|
||||||
.setSmallIcon(R.mipmap.ic_launcher)
|
|
||||||
.setContentTitle("Klottr")
|
|
||||||
.setContentText("Platsaktivering pågår")
|
|
||||||
.setOngoing(true)
|
|
||||||
.build()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -11,7 +11,6 @@ import android.net.Uri
|
|||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import android.widget.Toast
|
|
||||||
import androidx.activity.ComponentActivity
|
import androidx.activity.ComponentActivity
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
import androidx.activity.compose.setContent
|
import androidx.activity.compose.setContent
|
||||||
@@ -95,7 +94,6 @@ import app.klottr.create.createNoteFlow
|
|||||||
import app.klottr.create.queueNoteDocOutbox
|
import app.klottr.create.queueNoteDocOutbox
|
||||||
import app.klottr.data.AppDatabase
|
import app.klottr.data.AppDatabase
|
||||||
import app.klottr.data.NoteRepository
|
import app.klottr.data.NoteRepository
|
||||||
import app.klottr.location.AndroidLocationProvider
|
|
||||||
import app.klottr.nearby.FoundOpenAction // Delat åtgärds-ADT
|
import app.klottr.nearby.FoundOpenAction // Delat åtgärds-ADT
|
||||||
import app.klottr.nearby.NearbyBundleShared
|
import app.klottr.nearby.NearbyBundleShared
|
||||||
import app.klottr.nearby.NearbyEntryShared // Delad radmodell
|
import app.klottr.nearby.NearbyEntryShared // Delad radmodell
|
||||||
@@ -138,6 +136,7 @@ import app.klottr.ui.UsernameDialog
|
|||||||
import app.klottr.ui.WikiArticleDialog // Ny: dialogskalet ligger nu i ui-paketet
|
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.ui.WriteDocContent // Använd delad, material-fri formulär-UI
|
||||||
import app.klottr.auth.AuthPlatform
|
import app.klottr.auth.AuthPlatform
|
||||||
|
import app.klottr.events.FoundEvents
|
||||||
import app.klottr.util.AuthShared
|
import app.klottr.util.AuthShared
|
||||||
import app.klottr.util.PlatformAuthStorage
|
import app.klottr.util.PlatformAuthStorage
|
||||||
import app.klottr.util.AuthStorageDelegate
|
import app.klottr.util.AuthStorageDelegate
|
||||||
@@ -146,20 +145,18 @@ import app.klottr.util.FoundStore
|
|||||||
import app.klottr.util.FoundStore.LAYER_KLOTTER
|
import app.klottr.util.FoundStore.LAYER_KLOTTER
|
||||||
import app.klottr.util.ImageBitmapCache
|
import app.klottr.util.ImageBitmapCache
|
||||||
import app.klottr.util.KLog
|
import app.klottr.util.KLog
|
||||||
import app.klottr.util.LastLocationStore
|
import app.klottr.location.LastLocationStore
|
||||||
import app.klottr.util.NoteDetailCache
|
import app.klottr.util.NoteDetailCache
|
||||||
import app.klottr.util.OutboxStore
|
import app.klottr.util.OutboxStore
|
||||||
import app.klottr.util.SettingsStore
|
import app.klottr.util.SettingsStore
|
||||||
import app.klottr.util.buildFoundDetailStrings // Delad formatterare (commonMain)
|
import app.klottr.util.buildFoundDetailStrings // Delad formatterare (commonMain)
|
||||||
import androidx.compose.ui.graphics.asImageBitmap
|
import app.klottr.location.LocationServiceProvider
|
||||||
import app.klottr.util.formatCoords
|
import app.klottr.util.formatCoords
|
||||||
import app.klottr.util.formatDistance
|
import app.klottr.util.formatDistance
|
||||||
import app.klottr.work.OutboxWorker
|
import app.klottr.work.OutboxWorker
|
||||||
import coil3.ImageLoader
|
import coil3.ImageLoader
|
||||||
import coil3.compose.setSingletonImageLoaderFactory
|
import coil3.compose.setSingletonImageLoaderFactory
|
||||||
import coil3.toBitmap
|
import coil3.toBitmap
|
||||||
import com.google.android.gms.common.api.ApiException
|
|
||||||
import com.google.android.gms.location.Priority
|
|
||||||
// Maps replaced by platform-independent MapContainer
|
// Maps replaced by platform-independent MapContainer
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
@@ -168,7 +165,6 @@ import kotlinx.coroutines.withContext
|
|||||||
import java.io.File
|
import java.io.File
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
import kotlin.math.roundToInt
|
import kotlin.math.roundToInt
|
||||||
import com.google.android.gms.location.LocationServices as GmsLocationServices
|
|
||||||
import app.klottr.maps.CameraPosition as CrossCameraPosition
|
import app.klottr.maps.CameraPosition as CrossCameraPosition
|
||||||
import app.klottr.maps.LatLng as CrossLatLng
|
import app.klottr.maps.LatLng as CrossLatLng
|
||||||
import app.klottr.maps.MapController
|
import app.klottr.maps.MapController
|
||||||
@@ -176,6 +172,11 @@ import app.klottr.maps.MapContainer
|
|||||||
import app.klottr.maps.MapFeature
|
import app.klottr.maps.MapFeature
|
||||||
import app.klottr.maps.MapState
|
import app.klottr.maps.MapState
|
||||||
import app.klottr.maps.MapUiSettings
|
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
|
import app.klottr.maps.MapType as CrossMapType
|
||||||
|
|
||||||
class MainActivity : ComponentActivity() {
|
class MainActivity : ComponentActivity() {
|
||||||
@@ -189,13 +190,15 @@ class MainActivity : ComponentActivity() {
|
|||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
KLog.setEnabled(BuildConfig.KLLOG_DEBUG) // Styr loggnivå via buildflagga
|
KLog.setEnabled(BuildConfig.KLLOG_DEBUG) // Styr loggnivå via buildflagga
|
||||||
app.klottr.prefs.KvPrefs.init(applicationContext)
|
app.klottr.prefs.KvPrefs.init(applicationContext)
|
||||||
|
LocationServiceProvider.init(applicationContext)
|
||||||
|
AndroidAppContext.install(applicationContext)
|
||||||
|
|
||||||
// FG + (ev) BG platstillstånd
|
// FG + (ev) BG platstillstånd
|
||||||
fgPermissionLauncher =
|
fgPermissionLauncher =
|
||||||
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
|
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
|
||||||
val fgOk = hasFgLocationPerms(this)
|
val fgOk = hasFgLocationPerms(this)
|
||||||
if (fgOk) {
|
if (fgOk) {
|
||||||
startService(Intent(this, LocationService::class.java))
|
LocationServiceProvider.get().start()
|
||||||
if (Build.VERSION.SDK_INT >= 29 && !hasBgLocationPerm(this) && pendingBgRequest) {
|
if (Build.VERSION.SDK_INT >= 29 && !hasBgLocationPerm(this) && pendingBgRequest) {
|
||||||
bgPermissionLauncher.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
|
bgPermissionLauncher.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
|
||||||
}
|
}
|
||||||
@@ -231,7 +234,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
|
|
||||||
// Starta LocationService direkt om vi redan har FG-platstillstånd
|
// Starta LocationService direkt om vi redan har FG-platstillstånd
|
||||||
if (hasFgLocationPerms(this)) {
|
if (hasFgLocationPerms(this)) {
|
||||||
startService(Intent(this, LocationService::class.java))
|
LocationServiceProvider.get().start()
|
||||||
}
|
}
|
||||||
|
|
||||||
setContent {
|
setContent {
|
||||||
@@ -301,6 +304,9 @@ private fun KlottrAppShell(
|
|||||||
onLogin: () -> Unit,
|
onLogin: () -> Unit,
|
||||||
onLogout: () -> Unit
|
onLogout: () -> Unit
|
||||||
) {
|
) {
|
||||||
|
val locService = remember { LocationServiceProvider.get() }
|
||||||
|
LaunchedEffect(Unit) { locService.start() }
|
||||||
|
val currentLoc = locService.location.collectAsState(initial = null)
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
|
|
||||||
@@ -387,88 +393,64 @@ private fun KlottrAppShell(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Kickstarta avstånd direkt vid appstart
|
// Kickstarta avstånd direkt vid appstart (via KMP LocationService)
|
||||||
LaunchedEffect(Unit) {
|
LaunchedEffect(Unit) {
|
||||||
val gp = AndroidLocationProvider.currentOrLastKnown(context) // Nytt: centraliserad plats
|
val gp = LocationServiceProvider.get().current(highAccuracy = false)
|
||||||
if (gp != null) {
|
if (gp != null) {
|
||||||
// Spara som "senaste kända" och uppdatera away-flaggor
|
// LastLocationStore.lastKnownLocation = android.location.Location("kmp").apply {
|
||||||
LastLocationStore.lastKnownLocation = android.location.Location("klottr").apply {
|
// latitude = gp.lat
|
||||||
latitude = gp.lat; longitude = gp.lon
|
// longitude = gp.lon
|
||||||
} // Nytt: spegla in i din befintliga store
|
// time = gp.timeMillis ?: System.currentTimeMillis()
|
||||||
FoundStore.updateAwayFlags(gp.lat, gp.lon) // Oför: men nu med delad modell
|
// accuracy = (gp.accuracyMeters ?: 0.0).toFloat()
|
||||||
|
// }
|
||||||
// Tvinga omritning så att avstånd visas utan scroll
|
FoundStore.updateAwayFlags(gp.lat, gp.lon)
|
||||||
locationTick++
|
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)
|
// Direkt UI-uppdatering när FoundStore/KvPrefs ändras (oavsett broadcast)
|
||||||
DisposableEffect(Unit) {
|
// TODO: OH: Detta ska inte behövas
|
||||||
val handler = android.os.Handler(android.os.Looper.getMainLooper())
|
// DisposableEffect(Unit) {
|
||||||
val kvListener: (String?) -> Unit = {
|
// val handler = android.os.Handler(android.os.Looper.getMainLooper())
|
||||||
handler.post {
|
// val kvListener: (String?) -> Unit = {
|
||||||
forceEmptyFound = false
|
// handler.post {
|
||||||
refreshFound() // trigga recomposition av “Senaste”
|
// forceEmptyFound = false
|
||||||
}
|
// refreshFound() // trigga recomposition av “Senaste”
|
||||||
}
|
// }
|
||||||
app.klottr.prefs.KvPrefs.addListener(kvListener)
|
// }
|
||||||
onDispose { app.klottr.prefs.KvPrefs.removeListener(kvListener) }
|
// app.klottr.prefs.KvPrefs.addListener(kvListener)
|
||||||
}
|
// onDispose { app.klottr.prefs.KvPrefs.removeListener(kvListener) }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// Lyssna på KMP LocationService-flöde istället för broadcast
|
||||||
// Lyssna efter ACTION_LOCATION_TICK
|
LaunchedEffect(currentLoc.value?.lat, currentLoc.value?.lon) {
|
||||||
DisposableEffect(Unit) {
|
currentLoc.value?.let { gp ->
|
||||||
val filter = IntentFilter(LocationService.ACTION_LOCATION_TICK)
|
// LastLocationStore.lastKnownLocation = android.location.Location("kmp").apply {
|
||||||
val receiver = object : BroadcastReceiver() {
|
// latitude = gp.lat
|
||||||
override fun onReceive(ctx: Context?, intent: Intent?) {
|
// longitude = gp.lon
|
||||||
locationTick++ // tvinga Compose att rita om där vi läser detta värde
|
// time = gp.timeMillis ?: System.currentTimeMillis()
|
||||||
|
// accuracy = (gp.accuracyMeters ?: 0.0).toFloat()
|
||||||
|
// }
|
||||||
|
FoundStore.updateAwayFlags(gp.lat, gp.lon)
|
||||||
|
locationTick++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
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) {} }
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// 🔴 NYTT: Omedelbar UI-uppdatering när FoundStore ändras (SharedPreferences)
|
// 🔴 NYTT: Omedelbar UI-uppdatering när FoundStore ändras (SharedPreferences)
|
||||||
DisposableEffect(Unit) {
|
// Found updates via shared event bus (no broadcasts)
|
||||||
val prefs = context.getSharedPreferences("klottr_found_store", Context.MODE_PRIVATE)
|
LaunchedEffect(Unit) {
|
||||||
val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, _ ->
|
FoundEvents.foundUpdated.collect {
|
||||||
// Trigga omritning varje gång FoundStore uppdateras
|
// Trigga omritning varje gång FoundStore uppdateras
|
||||||
forceEmptyFound = false
|
forceEmptyFound = false
|
||||||
refreshFound()
|
refreshFound()
|
||||||
}
|
}
|
||||||
prefs.registerOnSharedPreferenceChangeListener(listener)
|
|
||||||
onDispose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
LaunchedEffect(showWiki, wikiRadius, showDm, dmRadius, showFornsok, fornsokRadius) {
|
LaunchedEffect(showWiki, wikiRadius, showDm, dmRadius, showFornsok, fornsokRadius) {
|
||||||
if (!showWiki && !showDm && !showFornsok) return@LaunchedEffect
|
if (!showWiki && !showDm && !showFornsok) return@LaunchedEffect
|
||||||
|
|
||||||
val gp = AndroidLocationProvider.currentOrLastKnown(context)
|
val gp = LocationServiceProvider.get().current(highAccuracy = false)
|
||||||
if (gp != null) {
|
if (gp != null) {
|
||||||
val anyNew = withContext(Dispatchers.IO) {
|
val anyNew = withContext(Dispatchers.IO) {
|
||||||
scanAndMarkFound(
|
scanAndMarkFound(
|
||||||
@@ -496,7 +478,7 @@ private fun KlottrAppShell(
|
|||||||
if (anyNew) {
|
if (anyNew) {
|
||||||
forceEmptyFound = false // Sätt tillbaka visning efter “Glöm alla fynd”
|
forceEmptyFound = false // Sätt tillbaka visning efter “Glöm alla fynd”
|
||||||
refreshFound() // Tvinga omritning av “Senaste”
|
refreshFound() // Tvinga omritning av “Senaste”
|
||||||
context.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED)) // Pinga övriga lyssnare (som tidigare)
|
/* notify listeners inline: refreshFound() already called */
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -529,8 +511,8 @@ private fun KlottrAppShell(
|
|||||||
// Förladdning av etiketter/bilder (oförändrad logik, flyttad hit)
|
// Förladdning av etiketter/bilder (oförändrad logik, flyttad hit)
|
||||||
LaunchedEffect(foundKey) {
|
LaunchedEffect(foundKey) {
|
||||||
val my = LastLocationStore.lastKnownLocation
|
val my = LastLocationStore.lastKnownLocation
|
||||||
val myLat = my?.latitude
|
val myLat = my.value?.lat
|
||||||
val myLon = my?.longitude
|
val myLon = my.value?.lon
|
||||||
labelOverrides.clear()
|
labelOverrides.clear()
|
||||||
foundList.forEach { f ->
|
foundList.forEach { f ->
|
||||||
if (f.layer == LAYER_KLOTTER) {
|
if (f.layer == LAYER_KLOTTER) {
|
||||||
@@ -585,8 +567,7 @@ private fun KlottrAppShell(
|
|||||||
KlottrHomeContent(
|
KlottrHomeContent(
|
||||||
contentPadding = padding,
|
contentPadding = padding,
|
||||||
entries = foundList,
|
entries = foundList,
|
||||||
currentLat = LastLocationStore.lastKnownLocation?.latitude,
|
location = LastLocationStore.lastKnownLocation.collectAsState(),
|
||||||
currentLon = LastLocationStore.lastKnownLocation?.longitude,
|
|
||||||
showCoords = showCoords,
|
showCoords = showCoords,
|
||||||
labelOverrides = labelOverrides,
|
labelOverrides = labelOverrides,
|
||||||
isClickable = { f ->
|
isClickable = { f ->
|
||||||
@@ -657,9 +638,8 @@ private fun KlottrAppShell(
|
|||||||
nearbyLoading = true
|
nearbyLoading = true
|
||||||
nearbyError = null
|
nearbyError = null
|
||||||
showNearby = true
|
showNearby = true
|
||||||
val ctx = context
|
|
||||||
scope.launch {
|
scope.launch {
|
||||||
val gp = AndroidLocationProvider.currentOrLastKnown(ctx)
|
val gp = LocationServiceProvider.get().current(highAccuracy = false)
|
||||||
if (gp == null) {
|
if (gp == null) {
|
||||||
nearbyLoading = false
|
nearbyLoading = false
|
||||||
nearbyError = "Ingen plats ännu – prova igen."
|
nearbyError = "Ingen plats ännu – prova igen."
|
||||||
@@ -701,7 +681,6 @@ private fun KlottrAppShell(
|
|||||||
|
|
||||||
val nowMillis = System.currentTimeMillis()
|
val nowMillis = System.currentTimeMillis()
|
||||||
app.klottr.nearby.markNewFinds(
|
app.klottr.nearby.markNewFinds(
|
||||||
ctx = ctx,
|
|
||||||
entries = bundle.entries, // Använd direkt från bundle
|
entries = bundle.entries, // Använd direkt från bundle
|
||||||
nowMillis = nowMillis,
|
nowMillis = nowMillis,
|
||||||
onMarked = { refreshFound() }
|
onMarked = { refreshFound() }
|
||||||
@@ -764,10 +743,7 @@ private fun KlottrAppShell(
|
|||||||
onKlotterClick = { id, la, lo, label ->
|
onKlotterClick = { id, la, lo, label ->
|
||||||
openKlotter = OpenKlotter(id = id, lat = la, lon = lo, label = label)
|
openKlotter = OpenKlotter(id = id, lat = la, lon = lo, label = label)
|
||||||
},
|
},
|
||||||
onOpenUrl = { _, url ->
|
onOpenUrl = { _, url -> AppNavigator.openUrl(url) },
|
||||||
val i = Intent(Intent.ACTION_VIEW, Uri.parse(url))
|
|
||||||
try { context.startActivity(i) } catch (_: Exception) {}
|
|
||||||
},
|
|
||||||
isKnownNote = { noteId ->
|
isKnownNote = { noteId ->
|
||||||
// Känd = finns i Hittat (FoundStore) → ska alltid visa titel
|
// Känd = finns i Hittat (FoundStore) → ska alltid visa titel
|
||||||
FoundStore
|
FoundStore
|
||||||
@@ -811,20 +787,20 @@ private fun KlottrAppShell(
|
|||||||
forceEmptyFound = true // Visa tomt direkt
|
forceEmptyFound = true // Visa tomt direkt
|
||||||
refreshFound() // Tvinga omritning
|
refreshFound() // Tvinga omritning
|
||||||
|
|
||||||
// 1) Nollställ sessions-gates inne i tjänsten
|
// Clear session + notify via shared events (handled in platform location impl)
|
||||||
context.startService(
|
FoundStore.clearAll();
|
||||||
Intent(context, LocationService::class.java)
|
FoundEvents.notifyFoundUpdated()
|
||||||
.setAction(LocationService.ACTION_CLEAR_FOUND_SESSION)
|
// // 1) Nollställ sessions-gates inne i tjänsten
|
||||||
)
|
// context.startService(
|
||||||
|
// Intent(context, LocationService::class.java)
|
||||||
// 2) Pinga UI:t att rita om (nollat läge)
|
// .setAction(LocationService.ACTION_CLEAR_FOUND_SESSION)
|
||||||
context.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED))
|
// )
|
||||||
|
//
|
||||||
|
// // 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
|
// 3) Be tjänsten göra en rescan
|
||||||
context.startService(
|
// old Android service call removed (handled in shared layer)
|
||||||
Intent(context, LocationService::class.java)
|
|
||||||
.setAction(LocationService.ACTION_RESCAN_NOW)
|
|
||||||
)
|
|
||||||
|
|
||||||
// 4) Gör även en direkt lokal scan nu (parallellt) → snabb UI-återfyllnad
|
// 4) Gör även en direkt lokal scan nu (parallellt) → snabb UI-återfyllnad
|
||||||
// Använder vår delade scanAndMarkFound så listan fylls utan att vänta på tjänsten.
|
// Använder vår delade scanAndMarkFound så listan fylls utan att vänta på tjänsten.
|
||||||
@@ -837,7 +813,7 @@ private fun KlottrAppShell(
|
|||||||
fornsokRadius = fornsokRadius
|
fornsokRadius = fornsokRadius
|
||||||
)
|
)
|
||||||
scope.launch {
|
scope.launch {
|
||||||
val gp = AndroidLocationProvider.currentOrLastKnown(context)
|
val gp = LocationServiceProvider.get().current(highAccuracy = false)
|
||||||
if (gp != null) {
|
if (gp != null) {
|
||||||
val anyNew = withContext(Dispatchers.IO) {
|
val anyNew = withContext(Dispatchers.IO) {
|
||||||
scanAndMarkFound(
|
scanAndMarkFound(
|
||||||
@@ -857,11 +833,11 @@ private fun KlottrAppShell(
|
|||||||
if (anyNew) {
|
if (anyNew) {
|
||||||
forceEmptyFound = false // Tillåt visning igen
|
forceEmptyFound = false // Tillåt visning igen
|
||||||
refreshFound() // Rita om “Senaste”
|
refreshFound() // Rita om “Senaste”
|
||||||
context.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED)) // Informera andra lyssnare
|
/* notify listeners inline: refreshFound() already called */
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Toast.makeText(context, "Alla fynd rensade.", Toast.LENGTH_SHORT).show()
|
UiFeedback.showMessage( "Alla fynd rensade.", UiFeedbackDuration.SHORT)
|
||||||
},
|
},
|
||||||
onClose = { showSettings = false }
|
onClose = { showSettings = false }
|
||||||
)
|
)
|
||||||
@@ -914,15 +890,15 @@ private fun KlottrAppShell(
|
|||||||
var isSavingDoc by remember { mutableStateOf(false) }
|
var isSavingDoc by remember { mutableStateOf(false) }
|
||||||
if (showWrite) {
|
if (showWrite) {
|
||||||
// Lagra positionen när man klickat Klottra:
|
// Lagra positionen när man klickat Klottra:
|
||||||
val initial = LastLocationStore.lastKnownLocation
|
val initial = LastLocationStore.lastKnownLocation.collectAsState()
|
||||||
val initialLat = initial?.latitude
|
val initialLat = initial.value?.lat
|
||||||
val initialLon = initial?.longitude
|
val initialLon = initial.value?.lon
|
||||||
|
|
||||||
WriteDocDialog(
|
WriteDocDialog(
|
||||||
onClose = { showWrite = false },
|
onClose = { showWrite = false },
|
||||||
onSave = { draft, selLat, selLon ->
|
onSave = { draft, selLat, selLon ->
|
||||||
if (!loggedIn) {
|
if (!loggedIn) {
|
||||||
Toast.makeText(context, "Du måste logga in för att kunna klottra.", Toast.LENGTH_SHORT).show()
|
UiFeedback.showMessage("Du måste logga in för att kunna klottra.", UiFeedbackDuration.SHORT)
|
||||||
return@WriteDocDialog
|
return@WriteDocDialog
|
||||||
}
|
}
|
||||||
val created = System.currentTimeMillis()
|
val created = System.currentTimeMillis()
|
||||||
@@ -974,7 +950,7 @@ private fun KlottrAppShell(
|
|||||||
|
|
||||||
when (outcome) {
|
when (outcome) {
|
||||||
is CreateNoteOutcome.Success -> {
|
is CreateNoteOutcome.Success -> {
|
||||||
Toast.makeText(context, "Sparat.", Toast.LENGTH_SHORT).show()
|
UiFeedback.showMessage("Sparat.")
|
||||||
|
|
||||||
// Markera nyskapad notis som "hittad" och uppdatera UI direkt
|
// Markera nyskapad notis som "hittad" och uppdatera UI direkt
|
||||||
scope.launch(Dispatchers.IO) {
|
scope.launch(Dispatchers.IO) {
|
||||||
@@ -1004,16 +980,18 @@ private fun KlottrAppShell(
|
|||||||
timeMillis = System.currentTimeMillis()
|
timeMillis = System.currentTimeMillis()
|
||||||
)
|
)
|
||||||
withContext(Dispatchers.Main) {
|
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)
|
// Tysta avisering för just detta klotter under 60s (slipper “pling” på eget klotter)
|
||||||
context.startService(
|
// TODO: OH: How to implement? Via foundstore?
|
||||||
Intent(context, LocationService::class.java)
|
// context.startService(
|
||||||
.setAction(LocationService.ACTION_SUPPRESS_NOTIFY)
|
// Intent(context, LocationService::class.java)
|
||||||
.putExtra("layer", LAYER_KLOTTER)
|
// .setAction(LocationService.ACTION_SUPPRESS_NOTIFY)
|
||||||
.putExtra("id", match.i.toString())
|
// .putExtra("layer", LAYER_KLOTTER)
|
||||||
.putExtra("ttlMs", 60_000L) // Valfri – hur länge det ska vara tyst
|
// .putExtra("id", match.i.toString())
|
||||||
)
|
// .putExtra("ttlMs", 60_000L) // Valfri – hur länge det ska vara tyst
|
||||||
|
// )
|
||||||
}
|
}
|
||||||
} catch (_: Throwable) { /* no-op */ }
|
} catch (_: Throwable) { /* no-op */ }
|
||||||
}
|
}
|
||||||
@@ -1067,24 +1045,26 @@ private fun KlottrAppShell(
|
|||||||
)
|
)
|
||||||
},
|
},
|
||||||
scheduleUpload = {
|
scheduleUpload = {
|
||||||
val constraints = Constraints.Builder()
|
//TODO: OH: Make sure sheduleUpload adhere to connected constraint.
|
||||||
.setRequiredNetworkType(NetworkType.CONNECTED)
|
OutboxScheduler.scheduleUpload();
|
||||||
.build()
|
// val constraints = Constraints.Builder()
|
||||||
val req = OneTimeWorkRequestBuilder<OutboxWorker>()
|
// .setRequiredNetworkType(NetworkType.CONNECTED)
|
||||||
.setConstraints(constraints).build()
|
// .build()
|
||||||
WorkManager.getInstance(context).enqueue(req)
|
// val req = OneTimeWorkRequestBuilder<OutboxWorker>()
|
||||||
|
// .setConstraints(constraints).build()
|
||||||
|
// WorkManager.getInstance(context).enqueue(req)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
when (queued) {
|
when (queued) {
|
||||||
QueueOutboxOutcome.Queued -> {
|
QueueOutboxOutcome.Queued -> {
|
||||||
Toast.makeText(context, "Offline. Sparas i utkorgen.", Toast.LENGTH_LONG).show()
|
UiFeedback.showMessage( "Offline. Sparas i utkorgen.")
|
||||||
showWrite = false
|
showWrite = false
|
||||||
}
|
}
|
||||||
QueueOutboxOutcome.ImagePersistFailed -> {
|
QueueOutboxOutcome.ImagePersistFailed -> {
|
||||||
val msg = outcome.message ?: "Bilduppladdning misslyckades."
|
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
|
// Stanna kvar i dialogen
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1137,12 +1117,14 @@ private fun KlottrAppShell(
|
|||||||
)
|
)
|
||||||
},
|
},
|
||||||
scheduleUpload = {
|
scheduleUpload = {
|
||||||
val constraints = Constraints.Builder()
|
//TODO: OH: Make sure sheduleUpload adhere to connected constraint.
|
||||||
.setRequiredNetworkType(NetworkType.CONNECTED)
|
OutboxScheduler.scheduleUpload()
|
||||||
.build()
|
// val constraints = Constraints.Builder()
|
||||||
val req = OneTimeWorkRequestBuilder<OutboxWorker>()
|
// .setRequiredNetworkType(NetworkType.CONNECTED)
|
||||||
.setConstraints(constraints).build()
|
// .build()
|
||||||
WorkManager.getInstance(context).enqueue(req)
|
// val req = OneTimeWorkRequestBuilder<OutboxWorker>()
|
||||||
|
// .setConstraints(constraints).build()
|
||||||
|
// WorkManager.getInstance(context).enqueue(req)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1150,11 +1132,11 @@ private fun KlottrAppShell(
|
|||||||
|
|
||||||
when (queued) {
|
when (queued) {
|
||||||
QueueOutboxOutcome.Queued -> {
|
QueueOutboxOutcome.Queued -> {
|
||||||
Toast.makeText(context, "Offline. Sparas i utkorgen.", Toast.LENGTH_LONG).show()
|
UiFeedback.showMessage( "Offline. Sparas i utkorgen.")
|
||||||
showWrite = false
|
showWrite = false
|
||||||
}
|
}
|
||||||
QueueOutboxOutcome.ImagePersistFailed -> {
|
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
|
// Stanna kvar i dialogen, låt användaren försöka igen eller spara utan bild
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1204,7 +1186,8 @@ private fun KlottrAppShell(
|
|||||||
scope.launch {
|
scope.launch {
|
||||||
me = withContext(Dispatchers.IO) { app.klottr.net.fetchMe() }
|
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 = {
|
||||||
onLogout() // ← samma onLogout som du redan skickar in till KlottrApp
|
onLogout() // ← samma onLogout som du redan skickar in till KlottrApp
|
||||||
@@ -1303,16 +1286,16 @@ private fun WriteDocDialog(
|
|||||||
) {
|
) {
|
||||||
Button(
|
Button(
|
||||||
onClick = {
|
onClick = {
|
||||||
val L = LastLocationStore.lastKnownLocation
|
val L = LastLocationStore.lastKnownLocation.value
|
||||||
if (L == null) {
|
if (L == null) {
|
||||||
Toast.makeText(context, "Ingen plats ännu – försök igen.", Toast.LENGTH_SHORT).show()
|
UiFeedback.showMessage("Ingen plats ännu – försök igen.", UiFeedbackDuration.SHORT)
|
||||||
} else {
|
} else {
|
||||||
selectedLat = L.latitude
|
selectedLat = L.lat
|
||||||
selectedLon = L.longitude
|
selectedLon = L.lon
|
||||||
lastPosUpdateMs = System.currentTimeMillis()
|
lastPosUpdateMs = System.currentTimeMillis()
|
||||||
// update marker + camera
|
// update marker + camera
|
||||||
val la = L.latitude
|
val la = L.lat
|
||||||
val lo = L.longitude
|
val lo = L.lon
|
||||||
mapState.features = listOf(
|
mapState.features = listOf(
|
||||||
MapFeature.Marker(id = "sel", position = CrossLatLng(la, lo))
|
MapFeature.Marker(id = "sel", position = CrossLatLng(la, lo))
|
||||||
)
|
)
|
||||||
@@ -1378,12 +1361,12 @@ private fun WriteDocDialog(
|
|||||||
val titleText = title.trim()
|
val titleText = title.trim()
|
||||||
if (titleText.isEmpty()) {
|
if (titleText.isEmpty()) {
|
||||||
titleError = "Rubrik får inte vara tom"
|
titleError = "Rubrik får inte vara tom"
|
||||||
Toast.makeText(context, "Rubrik får inte vara tom", Toast.LENGTH_SHORT).show()
|
UiFeedback.showMessage( "Rubrik får inte vara tom", UiFeedbackDuration.SHORT)
|
||||||
return@Button
|
return@Button
|
||||||
}
|
}
|
||||||
|
|
||||||
if (selectedLat == null || selectedLon == null) {
|
if (selectedLat == null || selectedLon == null) {
|
||||||
Toast.makeText(context, "Ingen plats ännu – klicka ”Uppdatera position”.", Toast.LENGTH_SHORT).show()
|
UiFeedback.showMessage("Ingen plats ännu – klicka ”Uppdatera position”.", UiFeedbackDuration.SHORT)
|
||||||
return@Button
|
return@Button
|
||||||
}
|
}
|
||||||
saving = true
|
saving = true
|
||||||
@@ -1451,22 +1434,22 @@ private fun SettingsDialog(
|
|||||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||||
title = { Text("Inställningar") },
|
title = { Text("Inställningar") },
|
||||||
text = {
|
text = {
|
||||||
val context = LocalContext.current
|
// val context = LocalContext.current
|
||||||
// Version-info (Android-only) → skickas som rena strängar till delad UI
|
// // Version-info (Android-only) → skickas som rena strängar till delad UI
|
||||||
val pInfo = remember {
|
// val pInfo = remember {
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||||
context.packageManager.getPackageInfo(
|
// context.packageManager.getPackageInfo(
|
||||||
context.packageName,
|
// context.packageName,
|
||||||
PackageManager.PackageInfoFlags.of(0)
|
// PackageManager.PackageInfoFlags.of(0)
|
||||||
)
|
// )
|
||||||
} else {
|
// } else {
|
||||||
@Suppress("DEPRECATION")
|
// @Suppress("DEPRECATION")
|
||||||
context.packageManager.getPackageInfo(context.packageName, 0)
|
// context.packageManager.getPackageInfo(context.packageName, 0)
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
val versionCode = PackageInfoCompat.getLongVersionCode(pInfo)
|
// val versionCode = PackageInfoCompat.getLongVersionCode(pInfo)
|
||||||
val versionLine = "Klottr v${BuildConfig.VERSION_NAME} (${BuildConfig.BUILD_TYPE}) • build $versionCode"
|
// val versionLine = "Klottr v${BuildConfig.VERSION_NAME} (${BuildConfig.BUILD_TYPE}) • build $versionCode"
|
||||||
val buildTimeLine = "Byggd ${BuildConfig.BUILD_TIME_UTC}"
|
// val buildTimeLine = "Byggd ${BuildConfig.BUILD_TIME_UTC}"
|
||||||
|
|
||||||
Box(
|
Box(
|
||||||
Modifier
|
Modifier
|
||||||
@@ -1474,8 +1457,8 @@ private fun SettingsDialog(
|
|||||||
.height(maxDialogHeight)
|
.height(maxDialogHeight)
|
||||||
) {
|
) {
|
||||||
SettingsContent(
|
SettingsContent(
|
||||||
versionLine = versionLine,
|
versionLine = "FIXME_VERSIONLINE", // TODO: OH: Do this platform independenlty
|
||||||
buildTimeLine = buildTimeLine,
|
buildTimeLine = "FIXME_BUILDTIME",
|
||||||
onlyNew = onlyNew,
|
onlyNew = onlyNew,
|
||||||
onOnlyNewChanged = onOnlyNewChanged,
|
onOnlyNewChanged = onOnlyNewChanged,
|
||||||
showCoords = showCoords,
|
showCoords = showCoords,
|
||||||
@@ -1572,27 +1555,22 @@ private fun KlotterDialog(
|
|||||||
var distanceText by remember { mutableStateOf("-") }
|
var distanceText by remember { mutableStateOf("-") }
|
||||||
|
|
||||||
fun recalcDistance() {
|
fun recalcDistance() {
|
||||||
val my = app.klottr.util.LastLocationStore.lastKnownLocation
|
val my = LastLocationStore.lastKnownLocation.value
|
||||||
val d = my?.let { app.klottr.util.distanceMeters(it.latitude, it.longitude, lat, lon).roundToInt() }
|
val d = my?.let { app.klottr.util.distanceMeters(it.lat, it.lon, lat, lon).roundToInt() }
|
||||||
distanceText = d?.let { "$it\u00A0m" } ?: "-" // hårt mellanslag
|
distanceText = d?.let { "$it\u00A0m" } ?: "-" // hårt mellanslag
|
||||||
}
|
}
|
||||||
|
|
||||||
// Räkna ut direkt vid öppning
|
// Räkna ut direkt vid öppning
|
||||||
LaunchedEffect(Unit) { recalcDistance() }
|
LaunchedEffect(Unit) { recalcDistance() }
|
||||||
|
|
||||||
// Lyssna på plats-tick så avståndet uppdateras live
|
val locService = remember { LocationServiceProvider.get() }
|
||||||
DisposableEffect(Unit) {
|
DisposableEffect(Unit) {
|
||||||
val filter = IntentFilter(LocationService.ACTION_LOCATION_TICK)
|
locService.start()
|
||||||
val receiver = object : BroadcastReceiver() {
|
onDispose { locService.stop() }
|
||||||
override fun onReceive(ctx: Context?, intent: Intent?) { recalcDistance() }
|
|
||||||
}
|
}
|
||||||
if (Build.VERSION.SDK_INT >= 33) {
|
val currentLocation = locService.location.collectAsState(initial = null)
|
||||||
context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
|
LaunchedEffect(currentLocation.value?.lat, currentLocation.value?.lon, lat, lon) {
|
||||||
} else {
|
recalcDistance()
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
context.registerReceiver(receiver, filter)
|
|
||||||
}
|
|
||||||
onDispose { try { context.unregisterReceiver(receiver) } catch (_: Exception) {} }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Snabb hydrering från cache om vi redan har detalj/bild
|
// Snabb hydrering från cache om vi redan har detalj/bild
|
||||||
@@ -1622,18 +1600,11 @@ private fun KlotterDialog(
|
|||||||
LaunchedEffect(id, lat, lon, label) {
|
LaunchedEffect(id, lat, lon, label) {
|
||||||
loading = !prefilledFromCache
|
loading = !prefilledFromCache
|
||||||
|
|
||||||
// Hämta ev. färsk plats (fallback LastLocationStore)
|
// Hämta ev. färsk plats
|
||||||
val my = LastLocationStore.lastKnownLocation
|
val my = LocationServiceProvider.get().current(highAccuracy = false)
|
||||||
val fused = GmsLocationServices.getFusedLocationProviderClient(context)
|
|
||||||
val current = try {
|
|
||||||
fused.lastLocation.await()
|
|
||||||
?: fused.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
|
|
||||||
} catch (_: Exception) {
|
|
||||||
null
|
|
||||||
}
|
|
||||||
|
|
||||||
val qLat = current?.latitude ?: my?.latitude
|
val qLat = my?.lat
|
||||||
val qLon = current?.longitude ?: my?.longitude
|
val qLon = my?.lon
|
||||||
|
|
||||||
// --- Delad beslutsregel: ersätter withinRadius/canAttempt/reqLat/reqLon --------------------
|
// --- Delad beslutsregel: ersätter withinRadius/canAttempt/reqLat/reqLon --------------------
|
||||||
val access = decideDetailAccess( // Ny: Beräkna om vi får hämta + vilka coords som ska skickas
|
val access = decideDetailAccess( // Ny: Beräkna om vi får hämta + vilka coords som ska skickas
|
||||||
@@ -1678,6 +1649,7 @@ private fun KlotterDialog(
|
|||||||
updatedMs = detail.updatedAt
|
updatedMs = detail.updatedAt
|
||||||
|
|
||||||
// Bild: hämta via POST (GDPR-fix), tunga saker i IO — uppdatera UI på huvudtråden.
|
// 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
|
val imgMeta = detail.image
|
||||||
if (imgMeta != null && imgMeta.id > 0) {
|
if (imgMeta != null && imgMeta.id > 0) {
|
||||||
// 1) Nätverk + bitmap-dekodning i IO
|
// 1) Nätverk + bitmap-dekodning i IO
|
||||||
@@ -1769,14 +1741,7 @@ private fun KlotterDialog(
|
|||||||
) {
|
) {
|
||||||
Button(
|
Button(
|
||||||
onClick = {
|
onClick = {
|
||||||
val labelEnc = Uri.encode(titleText.ifBlank { "Plats" })
|
AppNavigator.openMap(lat, lon, 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))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
) { Text("Maps") }
|
) { Text("Maps") }
|
||||||
|
|
||||||
@@ -1818,7 +1783,7 @@ private fun KlotterDialog(
|
|||||||
if (deleting) return@Button
|
if (deleting) return@Button
|
||||||
val idL = id.toLongOrNull()
|
val idL = id.toLongOrNull()
|
||||||
if (idL == null) {
|
if (idL == null) {
|
||||||
Toast.makeText(context, "Ogiltigt id.", Toast.LENGTH_SHORT).show()
|
UiFeedback.showMessage( "Ogiltigt id.", UiFeedbackDuration.SHORT)
|
||||||
askDelete = false
|
askDelete = false
|
||||||
return@Button
|
return@Button
|
||||||
}
|
}
|
||||||
@@ -1827,20 +1792,15 @@ private fun KlotterDialog(
|
|||||||
try {
|
try {
|
||||||
val ok = withContext(Dispatchers.IO) { deleteNote(idL) }
|
val ok = withContext(Dispatchers.IO) { deleteNote(idL) }
|
||||||
if (ok) {
|
if (ok) {
|
||||||
Toast.makeText(context, "Klottret raderat.", Toast.LENGTH_SHORT).show()
|
UiFeedback.showMessage("Klottret raderat.", UiFeedbackDuration.SHORT)
|
||||||
|
|
||||||
// 0) Ta bort ev. detaljer ur cachen (om remove finns – annars hoppar try{} över)
|
|
||||||
try { NoteDetailCache.remove(idL) } catch (_: Throwable) {}
|
|
||||||
|
|
||||||
FoundStore.remove(LAYER_KLOTTER, id) // id är din String i KlotterDialog
|
FoundStore.remove(LAYER_KLOTTER, id) // id är din String i KlotterDialog
|
||||||
|
FoundEvents.notifyFoundUpdated();
|
||||||
// Pinga UI:t (din DisposableEffect lyssnar på ACTION_FOUND_UPDATED och kör refreshFound())
|
|
||||||
context.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED))
|
|
||||||
|
|
||||||
askDelete = false
|
askDelete = false
|
||||||
onClose()
|
onClose()
|
||||||
} else {
|
} 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 {
|
} finally {
|
||||||
|
|||||||
@@ -1,43 +0,0 @@
|
|||||||
package app.klottr.util
|
|
||||||
|
|
||||||
import android.location.Location
|
|
||||||
import app.klottr.data.NoteEntity
|
|
||||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
|
||||||
import kotlin.math.*
|
|
||||||
|
|
||||||
// OBS: distanceMeters ligger numera i :shared (app.klottr.util.distanceMeters).
|
|
||||||
// Den lokala dubbletten är borttagen för att undvika divergens mellan plattformar.
|
|
||||||
|
|
||||||
|
|
||||||
//fun distanceMeters(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
|
|
||||||
//val R = 6371000.0
|
|
||||||
//val dLat = Math.toRadians(lat2 - lat1)
|
|
||||||
//val dLon = Math.toRadians(lon2 - lon1)
|
|
||||||
//val a = sin(dLat/2).pow(2.0) + cos(Math.toRadians(lat1)) * cos(Math.toRadians(lat2)) * sin(dLon/2).pow(2.0)
|
|
||||||
// return 2 * R * atan2(sqrt(a), sqrt(1 - a))
|
|
||||||
//}
|
|
||||||
|
|
||||||
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 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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -16,6 +16,7 @@ core = "1.5.0"
|
|||||||
ktor = "3.2.3"
|
ktor = "3.2.3"
|
||||||
kotlinxSerialization = "1.7.3"
|
kotlinxSerialization = "1.7.3"
|
||||||
ksp = "2.2.10-2.0.2"
|
ksp = "2.2.10-2.0.2"
|
||||||
|
workRuntimeKtx = "2.10.4"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -47,6 +48,7 @@ ktor-client-okhttp = { group = "io.ktor", name = "ktor-client-okhttp", version.r
|
|||||||
ktor-client-darwin = { group = "io.ktor", name = "ktor-client-darwin", version.ref = "ktor" }
|
ktor-client-darwin = { group = "io.ktor", name = "ktor-client-darwin", version.ref = "ktor" }
|
||||||
|
|
||||||
kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinxSerialization" }
|
kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinxSerialization" }
|
||||||
|
androidx-work-runtime-ktx = { group = "androidx.work", name = "work-runtime-ktx", version.ref = "workRuntimeKtx" }
|
||||||
|
|
||||||
|
|
||||||
[plugins]
|
[plugins]
|
||||||
|
|||||||
@@ -160,6 +160,7 @@ kotlin {
|
|||||||
implementation("com.google.maps.android:maps-compose:6.10.0") // Sep 9, 2025
|
implementation("com.google.maps.android:maps-compose:6.10.0") // Sep 9, 2025
|
||||||
// Google Sign-In
|
// Google Sign-In
|
||||||
implementation("com.google.android.gms:play-services-auth:21.4.0")
|
implementation("com.google.android.gms:play-services-auth:21.4.0")
|
||||||
|
implementation(libs.androidx.work.runtime.ktx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
package app.klottr.work
|
package app.klottr.work
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
|
||||||
import androidx.work.CoroutineWorker
|
import androidx.work.CoroutineWorker
|
||||||
import androidx.work.WorkerParameters
|
import androidx.work.WorkerParameters
|
||||||
import app.klottr.LocationService
|
import app.klottr.events.FoundEvents
|
||||||
import app.klottr.net.Geocache
|
import app.klottr.net.Geocache
|
||||||
import app.klottr.net.createNote
|
import app.klottr.net.createNote
|
||||||
import app.klottr.net.createNoteDoc
|
import app.klottr.net.createNoteDoc
|
||||||
@@ -146,7 +145,7 @@ class OutboxWorker(
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Pinga UI så “Senaste” uppdateras direkt
|
// Pinga UI så “Senaste” uppdateras direkt
|
||||||
ctx.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED))
|
FoundEvents.notifyFoundUpdated()
|
||||||
}
|
}
|
||||||
} catch (_: Throwable) {
|
} catch (_: Throwable) {
|
||||||
// Tyst fallback – Workern ska inte krascha pga visuell uppdatering
|
// Tyst fallback – Workern ska inte krascha pga visuell uppdatering
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
package app.klottr.location
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import com.google.android.gms.location.LocationServices
|
|
||||||
import com.google.android.gms.location.Priority
|
|
||||||
import kotlinx.coroutines.tasks.await
|
|
||||||
|
|
||||||
/** Android-implementation som använder FusedLocationProvider. */
|
|
||||||
object AndroidLocationProvider : LocationProvider {
|
|
||||||
|
|
||||||
/** Hämtar lastLocation och faller tillbaka till getCurrentLocation. */
|
|
||||||
suspend fun currentOrLastKnown(context: Context): GeoPoint? {
|
|
||||||
val client = LocationServices.getFusedLocationProviderClient(context)
|
|
||||||
return try {
|
|
||||||
val last = client.lastLocation.await()
|
|
||||||
val loc = last ?: client.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
|
|
||||||
loc?.let { GeoPoint(it.latitude, it.longitude) }
|
|
||||||
} catch (_: Exception) {
|
|
||||||
null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Interface-override finns för framtida DI utan Context (används ej av :app idag).
|
|
||||||
override suspend fun currentOrLastKnown(): GeoPoint? = null
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
package app.klottr.location
|
|
||||||
|
|
||||||
/** Android-implementationen håller bara ett volatilt fält. */
|
|
||||||
actual object LastLocationStore {
|
|
||||||
@Volatile
|
|
||||||
actual var lastKnown: GeoPoint? = null
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
package app.klottr.location
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
import android.content.Context
|
||||||
|
import android.location.LocationManager
|
||||||
|
import android.os.Looper
|
||||||
|
import androidx.core.content.ContextCompat
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import com.google.android.gms.location.*
|
||||||
|
import kotlinx.coroutines.*
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.tasks.await
|
||||||
|
|
||||||
|
private class AndroidLocationService(
|
||||||
|
private val appContext: Context,
|
||||||
|
private val scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||||
|
) : LocationService {
|
||||||
|
|
||||||
|
private val fused by lazy { LocationServices.getFusedLocationProviderClient(appContext) }
|
||||||
|
private var callback: LocationCallback? = null
|
||||||
|
|
||||||
|
private val _location = MutableStateFlow<GeoPoint?>(null)
|
||||||
|
override val location: StateFlow<GeoPoint?> = _location
|
||||||
|
|
||||||
|
private fun hasPermission(): Boolean {
|
||||||
|
val fine = ContextCompat.checkSelfPermission(
|
||||||
|
appContext, android.Manifest.permission.ACCESS_FINE_LOCATION
|
||||||
|
) == PackageManager.PERMISSION_GRANTED
|
||||||
|
val coarse = ContextCompat.checkSelfPermission(
|
||||||
|
appContext, android.Manifest.permission.ACCESS_COARSE_LOCATION
|
||||||
|
) == PackageManager.PERMISSION_GRANTED
|
||||||
|
return fine || coarse
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun start(updates: LocationUpdates) {
|
||||||
|
if (callback != null) return
|
||||||
|
if (!hasPermission()) return
|
||||||
|
|
||||||
|
val req = LocationRequest.Builder(
|
||||||
|
if (updates.highAccuracy) Priority.PRIORITY_HIGH_ACCURACY else Priority.PRIORITY_BALANCED_POWER_ACCURACY,
|
||||||
|
updates.desiredIntervalMillis
|
||||||
|
)
|
||||||
|
.setMinUpdateIntervalMillis(updates.fastestIntervalMillis)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
callback = object : LocationCallback() {
|
||||||
|
override fun onLocationResult(result: LocationResult) {
|
||||||
|
val l = result.lastLocation ?: return
|
||||||
|
val p = GeoPoint(
|
||||||
|
lat = l.latitude,
|
||||||
|
lon = l.longitude,
|
||||||
|
accuracyMeters = l.accuracy.toDouble(),
|
||||||
|
timeMillis = l.time
|
||||||
|
)
|
||||||
|
_location.value = p
|
||||||
|
LastLocationStore.update(p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//noinspection MissingPermission
|
||||||
|
fused.requestLocationUpdates(req, callback!!, Looper.getMainLooper())
|
||||||
|
scope.launch { _location.value ?: run { _location.value = lastKnownImmediate() } }
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun stop() {
|
||||||
|
callback?.let { fused.removeLocationUpdates(it) }
|
||||||
|
callback = null
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("MissingPermission")
|
||||||
|
private suspend fun lastKnownImmediate(): GeoPoint? {
|
||||||
|
if (!hasPermission()) return null
|
||||||
|
return try {
|
||||||
|
val l = fused.lastLocation.await() ?: return null
|
||||||
|
GeoPoint(l.latitude, l.longitude, l.accuracy.toDouble(), l.time).also { LastLocationStore.update(it) }
|
||||||
|
} catch (_: Throwable) { null }
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("MissingPermission")
|
||||||
|
override suspend fun current(highAccuracy: Boolean, timeoutMillis: Long): GeoPoint? {
|
||||||
|
if (!hasPermission()) return _location.value ?: LastLocationStore.lastKnownLocation.value
|
||||||
|
// Try current quick, with fallback to last known
|
||||||
|
return try {
|
||||||
|
withTimeout(timeoutMillis) {
|
||||||
|
val loc = fused.getCurrentLocation(
|
||||||
|
if (highAccuracy) Priority.PRIORITY_HIGH_ACCURACY else Priority.PRIORITY_BALANCED_POWER_ACCURACY,
|
||||||
|
null
|
||||||
|
).await()
|
||||||
|
loc?.let {
|
||||||
|
GeoPoint(it.latitude, it.longitude, it.accuracy.toDouble(), it.time).also { p ->
|
||||||
|
_location.value = p
|
||||||
|
LastLocationStore.update(p)
|
||||||
|
}
|
||||||
|
} ?: lastKnownImmediate()
|
||||||
|
}
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
_location.value ?: LastLocationStore.lastKnownLocation.value ?: lastKnownImmediate()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun isLocationEnabled(): Boolean {
|
||||||
|
val lm = appContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
|
||||||
|
return lm.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
|
||||||
|
lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
actual object LocationServiceProvider {
|
||||||
|
private var instance: LocationService? = null
|
||||||
|
|
||||||
|
fun init(appContext: Context) { // optional: call once from Application.onCreate()
|
||||||
|
if (instance == null) instance = AndroidLocationService(appContext.applicationContext)
|
||||||
|
}
|
||||||
|
|
||||||
|
actual fun get(): LocationService {
|
||||||
|
return instance ?: error("LocationServiceProvider not initialized. Call LocationServiceProvider.init(context).")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package app.klottr.platform
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import java.util.concurrent.atomic.AtomicReference
|
||||||
|
|
||||||
|
/**
|
||||||
|
* App-internal way to expose applicationContext to platform actuals
|
||||||
|
* without referencing it from app UI files.
|
||||||
|
*/
|
||||||
|
object AndroidAppContext {
|
||||||
|
private val ref = AtomicReference<Context?>()
|
||||||
|
fun install(appContext: Context) { ref.set(appContext.applicationContext) }
|
||||||
|
fun get(): Context? = ref.get()
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package app.klottr.platform
|
||||||
|
|
||||||
|
import android.content.Intent
|
||||||
|
import android.net.Uri
|
||||||
|
import android.widget.Toast
|
||||||
|
|
||||||
|
actual object AppNavigator {
|
||||||
|
actual fun openUrl(url: String) {
|
||||||
|
val c = AndroidAppContext.get() ?: return
|
||||||
|
val i = Intent(Intent.ACTION_VIEW, Uri.parse(url))
|
||||||
|
try { c.startActivity(i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } catch (_: Exception) {}
|
||||||
|
}
|
||||||
|
actual fun openMap(lat: Double, lon: Double, label: String?) {
|
||||||
|
val c = AndroidAppContext.get() ?: return
|
||||||
|
val enc = Uri.encode(label ?: "Plats")
|
||||||
|
val geo = Uri.parse("geo:$lat,$lon?q=$lat,$lon($enc)")
|
||||||
|
val intent = Intent(Intent.ACTION_VIEW, geo).setPackage("com.google.android.apps.maps")
|
||||||
|
try { c.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } catch (_: Exception) {
|
||||||
|
try { c.startActivity(Intent(Intent.ACTION_VIEW, geo).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } catch (_: Exception) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
actual object UiFeedback {
|
||||||
|
actual fun showMessage(text: String, duration: UiFeedbackDuration) {
|
||||||
|
val toastDuration = if (duration == UiFeedbackDuration.SHORT) Toast.LENGTH_SHORT else Toast.LENGTH_LONG
|
||||||
|
AndroidAppContext.get()?.let { Toast.makeText(it, text, toastDuration).show() }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package app.klottr.platform
|
||||||
|
|
||||||
|
import androidx.work.Constraints
|
||||||
|
import androidx.work.NetworkType
|
||||||
|
import androidx.work.OneTimeWorkRequestBuilder
|
||||||
|
import androidx.work.WorkManager
|
||||||
|
import app.klottr.platform.AndroidAppContext
|
||||||
|
import app.klottr.work.OutboxWorker
|
||||||
|
|
||||||
|
actual object OutboxScheduler {
|
||||||
|
actual fun scheduleUpload() {
|
||||||
|
val c = AndroidAppContext.get() ?: return
|
||||||
|
val constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
|
||||||
|
val req = OneTimeWorkRequestBuilder<OutboxWorker>().setConstraints(constraints).build()
|
||||||
|
WorkManager.getInstance(c).enqueue(req)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,3 +12,10 @@ actual fun platformScreenHeightDp(): Dp {
|
|||||||
return conf.screenHeightDp.dp
|
return conf.screenHeightDp.dp
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
actual fun platformScreenWidthDp(): Dp {
|
||||||
|
val conf = LocalConfiguration.current
|
||||||
|
// screenHeightDp is in dp units already
|
||||||
|
return conf.screenWidthDp.dp
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package app.klottr.events
|
||||||
|
|
||||||
|
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||||
|
import kotlinx.coroutines.flow.SharedFlow
|
||||||
|
|
||||||
|
object FoundEvents {
|
||||||
|
private val _foundUpdated = MutableSharedFlow<Unit>(extraBufferCapacity = 8)
|
||||||
|
val foundUpdated: SharedFlow<Unit> = _foundUpdated
|
||||||
|
|
||||||
|
private val _locationTick = MutableSharedFlow<Unit>(extraBufferCapacity = 8)
|
||||||
|
val locationTick: SharedFlow<Unit> = _locationTick
|
||||||
|
|
||||||
|
fun notifyFoundUpdated() { _foundUpdated.tryEmit(Unit) }
|
||||||
|
fun notifyLocationTick() { _locationTick.tryEmit(Unit) }
|
||||||
|
}
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
package app.klottr.location
|
|
||||||
|
|
||||||
/** Delad platsstore: senaste kända position som enkel GeoPoint. */
|
|
||||||
expect object LastLocationStore {
|
|
||||||
var lastKnown: GeoPoint?
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
package app.klottr.location
|
|
||||||
|
|
||||||
/** Enkel delad platsmodell för KMP. */
|
|
||||||
data class GeoPoint(val lat: Double, val lon: Double)
|
|
||||||
|
|
||||||
/** Gränssnitt för plattforms-specifik platsinhämtning. */
|
|
||||||
interface LocationProvider {
|
|
||||||
/** Returnerar aktuell plats eller senaste kända, eller null vid fel/tidsutlöpning. */
|
|
||||||
suspend fun currentOrLastKnown(): GeoPoint?
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package app.klottr.location
|
||||||
|
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Platform-independent, Flow-based location API.
|
||||||
|
* Everything used by UI/Workers should depend on this interface.
|
||||||
|
*/
|
||||||
|
interface LocationService {
|
||||||
|
/** Last known or most recent location (null until the first fix). */
|
||||||
|
val location: StateFlow<GeoPoint?>
|
||||||
|
|
||||||
|
/** Start continuous updates (idempotent). */
|
||||||
|
fun start(updates: LocationUpdates = LocationUpdates())
|
||||||
|
|
||||||
|
/** Stop updates (idempotent). */
|
||||||
|
fun stop()
|
||||||
|
|
||||||
|
/** Try to get a fresh fix (falls back to last known). */
|
||||||
|
suspend fun current(highAccuracy: Boolean = true, timeoutMillis: Long = 10_000): GeoPoint?
|
||||||
|
|
||||||
|
/** Whether platform indicates location services are enabled. */
|
||||||
|
suspend fun isLocationEnabled(): Boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Minimal, platform-agnostic location model for UI/worker. */
|
||||||
|
data class GeoPoint(
|
||||||
|
val lat: Double,
|
||||||
|
val lon: Double,
|
||||||
|
val accuracyMeters: Double? = null,
|
||||||
|
val timeMillis: Long? = null,
|
||||||
|
)
|
||||||
|
|
||||||
|
data class LocationUpdates(
|
||||||
|
val desiredIntervalMillis: Long = 5_000,
|
||||||
|
val fastestIntervalMillis: Long = 2_000,
|
||||||
|
val highAccuracy: Boolean = true,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Simple, common store (replaces various platform stores). */
|
||||||
|
object LastLocationStore {
|
||||||
|
private val _lastKnown = MutableStateFlow<GeoPoint?>(null)
|
||||||
|
val lastKnownLocation: StateFlow<GeoPoint?> = _lastKnown.asStateFlow()
|
||||||
|
|
||||||
|
fun update(p: GeoPoint?) { _lastKnown.value = p }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Accessor to a shared instance (can be replaced via DI if you like). */
|
||||||
|
expect object LocationServiceProvider {
|
||||||
|
fun get(): LocationService
|
||||||
|
}
|
||||||
@@ -19,7 +19,6 @@ fun isClickable( //
|
|||||||
|
|
||||||
//Markera nya fynd i FoundStore baserat på delade entries (plattformneutral hjälpare)
|
//Markera nya fynd i FoundStore baserat på delade entries (plattformneutral hjälpare)
|
||||||
fun markNewFinds( //
|
fun markNewFinds( //
|
||||||
ctx: Any?, //Context-parameter hålls som Any? i KMP
|
|
||||||
entries: List<NearbyEntryShared>, //Delade “Närliggande”-rader
|
entries: List<NearbyEntryShared>, //Delade “Närliggande”-rader
|
||||||
nowMillis: Long, //Tidpunkt för markering
|
nowMillis: Long, //Tidpunkt för markering
|
||||||
onMarked: () -> Unit //Callback om något faktiskt markerats nytt
|
onMarked: () -> Unit //Callback om något faktiskt markerats nytt
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package app.klottr.platform
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Platform-independent navigation helpers used from common UI.
|
||||||
|
* Android uses Intents; iOS opens via UIApplication.
|
||||||
|
*/
|
||||||
|
expect object AppNavigator {
|
||||||
|
fun openUrl(url: String)
|
||||||
|
fun openMap(lat: Double, lon: Double, label: String? = null)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
enum class UiFeedbackDuration {
|
||||||
|
SHORT,
|
||||||
|
LONG
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lightweight user feedback facade (e.g. toast / banner).
|
||||||
|
* On iOS this can no-op or present a subtle HUD, implementation-defined.
|
||||||
|
*/
|
||||||
|
expect object UiFeedback {
|
||||||
|
fun showMessage(text: String, duration: UiFeedbackDuration = UiFeedbackDuration.LONG)
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package app.klottr.platform
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Schedule a one-shot upload job when network is connected.
|
||||||
|
*/
|
||||||
|
expect object OutboxScheduler {
|
||||||
|
fun scheduleUpload()
|
||||||
|
}
|
||||||
@@ -3,7 +3,12 @@ package app.klottr.platform
|
|||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.ui.unit.Dp
|
import androidx.compose.ui.unit.Dp
|
||||||
|
|
||||||
|
|
||||||
|
//TODO: OH: Verkar som vi inte borde bero på dessa, utan använda compose api:et LocalWindowInfo.containerSize istället
|
||||||
|
// som redan är platformsoberoende
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Platform-agnostic screen height in dp for sizing dialogs proportionally.
|
* Platform-agnostic screen height in dp for sizing dialogs proportionally.
|
||||||
*/
|
*/
|
||||||
@Composable expect fun platformScreenHeightDp(): Dp
|
@Composable expect fun platformScreenHeightDp(): Dp
|
||||||
|
@Composable expect fun platformScreenWidthDp(): Dp
|
||||||
|
|||||||
@@ -1,11 +1,5 @@
|
|||||||
package app.klottr.ui
|
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.Box
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
import androidx.compose.foundation.layout.heightIn
|
import androidx.compose.foundation.layout.heightIn
|
||||||
@@ -17,23 +11,25 @@ import androidx.compose.material3.Text
|
|||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.DisposableEffect
|
import androidx.compose.runtime.DisposableEffect
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.collectAsState
|
||||||
import androidx.compose.runtime.getValue // Gör 'by remember { ... }' läsbart
|
import androidx.compose.runtime.getValue // Gör 'by remember { ... }' läsbart
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.setValue // Gör 'by remember { ... }' skrivbart
|
import androidx.compose.runtime.setValue // Gör 'by remember { ... }' skrivbart
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.platform.LocalConfiguration
|
|
||||||
import androidx.compose.ui.platform.LocalContext
|
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.window.DialogProperties
|
import androidx.compose.ui.window.DialogProperties
|
||||||
import app.klottr.LocationService
|
|
||||||
import app.klottr.net.DigitaltMuseumItem
|
import app.klottr.net.DigitaltMuseumItem
|
||||||
import app.klottr.net.FornsokItem
|
import app.klottr.net.FornsokItem
|
||||||
import app.klottr.net.Wikipedia
|
import app.klottr.net.Wikipedia
|
||||||
|
import app.klottr.location.LocationServiceProvider
|
||||||
|
import app.klottr.platform.AppNavigator
|
||||||
|
import app.klottr.platform.platformScreenWidthDp
|
||||||
import app.klottr.util.SettingsStore
|
import app.klottr.util.SettingsStore
|
||||||
import app.klottr.util.formatCoords
|
import app.klottr.util.formatCoords
|
||||||
import app.klottr.util.formatDistance
|
import app.klottr.util.formatDistance
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.IO
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import kotlin.math.roundToInt
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
@@ -46,42 +42,27 @@ fun WikiArticleDialog(
|
|||||||
lon: Double?,
|
lon: Double?,
|
||||||
onClose: () -> Unit
|
onClose: () -> Unit
|
||||||
) {
|
) {
|
||||||
val context = LocalContext.current
|
val dialogWidth = (platformScreenWidthDp() * 0.98f)
|
||||||
val configuration = LocalConfiguration.current
|
|
||||||
val dialogWidth = (configuration.screenWidthDp.dp * 0.98f)
|
|
||||||
|
|
||||||
var loading by remember { mutableStateOf(true) }
|
var loading by remember { mutableStateOf(true) }
|
||||||
var title by remember { mutableStateOf("") }
|
var title by remember { mutableStateOf("") }
|
||||||
var extract by remember { mutableStateOf("") }
|
var extract by remember { mutableStateOf("") }
|
||||||
|
|
||||||
// Avståndstext som uppdateras när platsen tickar
|
// Avståndstext uppdateras via KMP LocationService
|
||||||
var wikiDistanceText by remember { mutableStateOf("-") }
|
var wikiDistanceText by remember { mutableStateOf("-") }
|
||||||
val showCoords = remember { app.klottr.util.SettingsStore.getShowCoordinates() }
|
val showCoords = remember { app.klottr.util.SettingsStore.getShowCoordinates() }
|
||||||
|
val locService = remember { LocationServiceProvider.get() }
|
||||||
fun recalcWikiDistance() {
|
|
||||||
val my = app.klottr.util.LastLocationStore.lastKnownLocation
|
|
||||||
val d = if (lat != null && lon != null && my != null)
|
|
||||||
app.klottr.util.distanceMeters(my.latitude, my.longitude, lat, lon).roundToInt()
|
|
||||||
else null
|
|
||||||
wikiDistanceText = d?.let { "$it\u00A0m" } ?: "-"
|
|
||||||
}
|
|
||||||
|
|
||||||
// Beräkna direkt
|
|
||||||
LaunchedEffect(lat, lon) { recalcWikiDistance() }
|
|
||||||
|
|
||||||
// Lyssna på plats-tick för att uppdatera avståndet live
|
|
||||||
DisposableEffect(Unit) {
|
DisposableEffect(Unit) {
|
||||||
val filter = IntentFilter(LocationService.ACTION_LOCATION_TICK)
|
locService.start()
|
||||||
val receiver = object : BroadcastReceiver() {
|
onDispose { locService.stop() }
|
||||||
override fun onReceive(ctx: Context?, intent: Intent?) { recalcWikiDistance() }
|
|
||||||
}
|
}
|
||||||
if (Build.VERSION.SDK_INT >= 33) {
|
val current = locService.location.collectAsState(initial = null)
|
||||||
context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
|
LaunchedEffect(current.value?.lat, current.value?.lon, lat, lon) {
|
||||||
} else {
|
val gp = current.value
|
||||||
@Suppress("DEPRECATION")
|
val d = if (lat != null && lon != null && gp != null)
|
||||||
context.registerReceiver(receiver, filter)
|
app.klottr.util.distanceMeters(gp.lat, gp.lon, lat, lon).roundToInt()
|
||||||
}
|
else null
|
||||||
onDispose { try { context.unregisterReceiver(receiver) } catch (_: Exception) {} }
|
wikiDistanceText = d?.let { f -> "${f}\u00A0m" } ?: "-"
|
||||||
}
|
}
|
||||||
|
|
||||||
LaunchedEffect(pageId) {
|
LaunchedEffect(pageId) {
|
||||||
@@ -128,18 +109,14 @@ fun WikiArticleDialog(
|
|||||||
actions = {
|
actions = {
|
||||||
Button(onClick = {
|
Button(onClick = {
|
||||||
val url = "https://sv.m.wikipedia.org/?curid=$pageId"
|
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") }
|
}) { Text("Läs mer") }
|
||||||
|
|
||||||
Button(
|
Button(
|
||||||
onClick = {
|
onClick = {
|
||||||
if (lat != null && lon != null) {
|
if (lat != null && lon != null) {
|
||||||
val label = if (title.isNullOrBlank()) "Wikipedia-plats" else title // Ny: hantera null/blank
|
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
|
AppNavigator.openMap(lat, lon, 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))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
enabled = lat != null && lon != null
|
enabled = lat != null && lon != null
|
||||||
@@ -158,9 +135,7 @@ fun FornsokDialog(
|
|||||||
item: FornsokItem,
|
item: FornsokItem,
|
||||||
onClose: () -> Unit
|
onClose: () -> Unit
|
||||||
) {
|
) {
|
||||||
val context = LocalContext.current
|
val dialogWidth = (platformScreenWidthDp() * 0.98f)
|
||||||
val configuration = LocalConfiguration.current
|
|
||||||
val dialogWidth = (configuration.screenWidthDp.dp * 0.98f)
|
|
||||||
|
|
||||||
// Vi använder fälten från FornsokItem; om desc/uri saknas visar vi "saknas"-text.
|
// Vi använder fälten från FornsokItem; om desc/uri saknas visar vi "saknas"-text.
|
||||||
val title = remember(item.id) { item.title.ifBlank { "Fornlämning" } }
|
val title = remember(item.id) { item.title.ifBlank { "Fornlämning" } }
|
||||||
@@ -169,35 +144,18 @@ fun FornsokDialog(
|
|||||||
val platLat = item.lat
|
val platLat = item.lat
|
||||||
val platLon = item.lon
|
val platLon = item.lon
|
||||||
|
|
||||||
// Avståndstext som uppdateras på plats-tick
|
// Avståndstext uppdateras via KMP LocationService
|
||||||
var fornDistanceText by remember { mutableStateOf("-") }
|
var fornDistanceText by remember { mutableStateOf("-") }
|
||||||
val showCoords = remember { app.klottr.util.SettingsStore.getShowCoordinates() }
|
val showCoords = remember { app.klottr.util.SettingsStore.getShowCoordinates() }
|
||||||
|
val locService = remember { LocationServiceProvider.get() }
|
||||||
|
LaunchedEffect(Unit) { locService.start() }
|
||||||
fun recalcFornDistance() {
|
val current = locService.location.collectAsState(initial = null)
|
||||||
val my = app.klottr.util.LastLocationStore.lastKnownLocation
|
LaunchedEffect(current.value?.lat, current.value?.lon, platLat, platLon) {
|
||||||
val d = if (my != null)
|
val gp = current.value
|
||||||
app.klottr.util.distanceMeters(my.latitude, my.longitude, platLat, platLon).roundToInt()
|
val d = if (gp != null)
|
||||||
|
app.klottr.util.distanceMeters(gp.lat, gp.lon, platLat, platLon).roundToInt()
|
||||||
else null
|
else null
|
||||||
fornDistanceText = d?.let { "$it\u00A0m" } ?: "-"
|
fornDistanceText = d?.let { f -> "${f}\u00A0m" } ?: "-"
|
||||||
}
|
|
||||||
|
|
||||||
// Beräkna direkt
|
|
||||||
LaunchedEffect(platLat, platLon) { recalcFornDistance() }
|
|
||||||
|
|
||||||
// Lyssna på plats-tick
|
|
||||||
DisposableEffect(Unit) {
|
|
||||||
val filter = IntentFilter(LocationService.ACTION_LOCATION_TICK)
|
|
||||||
val receiver = object : BroadcastReceiver() {
|
|
||||||
override fun onReceive(ctx: Context?, intent: Intent?) { recalcFornDistance() }
|
|
||||||
}
|
|
||||||
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) {} }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -233,19 +191,14 @@ fun FornsokDialog(
|
|||||||
actions = {
|
actions = {
|
||||||
Button(
|
Button(
|
||||||
onClick = {
|
onClick = {
|
||||||
val geoTitle = Uri.encode(title)
|
AppNavigator.openMap(platLat, platLon, 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))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
) { Text("Maps") }
|
) { Text("Maps") }
|
||||||
|
|
||||||
Button(
|
Button(
|
||||||
onClick = {
|
onClick = {
|
||||||
val u = link ?: return@Button
|
val u = link ?: return@Button
|
||||||
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(u)))
|
AppNavigator.openUrl(u)
|
||||||
},
|
},
|
||||||
enabled = link != null
|
enabled = link != null
|
||||||
) { Text("Läs mer") }
|
) { Text("Läs mer") }
|
||||||
@@ -263,9 +216,8 @@ fun DmDialog(
|
|||||||
item: DigitaltMuseumItem,
|
item: DigitaltMuseumItem,
|
||||||
onClose: () -> Unit
|
onClose: () -> Unit
|
||||||
) {
|
) {
|
||||||
val context = LocalContext.current
|
val dialogWidth = (platformScreenWidthDp() * 0.98f)
|
||||||
val configuration = LocalConfiguration.current
|
|
||||||
val dialogWidth = (configuration.screenWidthDp.dp * 0.98f)
|
|
||||||
var detailText by remember { mutableStateOf<String?>(null) }
|
var detailText by remember { mutableStateOf<String?>(null) }
|
||||||
|
|
||||||
var loading by remember { mutableStateOf(false) }
|
var loading by remember { mutableStateOf(false) }
|
||||||
@@ -275,42 +227,15 @@ fun DmDialog(
|
|||||||
val showCoords = remember { SettingsStore.getShowCoordinates() }
|
val showCoords = remember { SettingsStore.getShowCoordinates() }
|
||||||
|
|
||||||
fun recalcDmDistance() {
|
fun recalcDmDistance() {
|
||||||
val my = app.klottr.location.LastLocationStore.lastKnown // Använd delad LastLocationStore.lastKnown
|
val my = app.klottr.location.LastLocationStore.lastKnownLocation.value
|
||||||
val d = my?.let { // Null-säker hantering
|
val d = my?.let {
|
||||||
app.klottr.util.distanceMeters(
|
app.klottr.util.distanceMeters(it.lat, it.lon, item.lat, item.lon).roundToInt()
|
||||||
it.lat, // GeoPoint.lat
|
|
||||||
it.lon, // GeoPoint.lon
|
|
||||||
item.lat,
|
|
||||||
item.lon
|
|
||||||
).roundToInt()
|
|
||||||
}
|
}
|
||||||
dmDistanceText = d?.let { formatDistance(it) } ?: "-"
|
dmDistanceText = d?.let { formatDistance(it) } ?: "-"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
LaunchedEffect(item.lat, item.lon) { recalcDmDistance() }
|
LaunchedEffect(item.lat, item.lon) { recalcDmDistance() }
|
||||||
|
|
||||||
DisposableEffect(Unit) {
|
|
||||||
val filter = IntentFilter(LocationService.ACTION_LOCATION_TICK)
|
|
||||||
val receiver = object : BroadcastReceiver() {
|
|
||||||
override fun onReceive(ctx: Context?, intent: Intent?) {
|
|
||||||
recalcDmDistance()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Hämta miniatyr om vi har bild-URL
|
// Hämta miniatyr om vi har bild-URL
|
||||||
LaunchedEffect(item.id) {
|
LaunchedEffect(item.id) {
|
||||||
// Text (om uniqueId finns)
|
// Text (om uniqueId finns)
|
||||||
@@ -400,18 +325,7 @@ fun DmDialog(
|
|||||||
actions = {
|
actions = {
|
||||||
Button(
|
Button(
|
||||||
onClick = {
|
onClick = {
|
||||||
val labelEnc = Uri.encode(displayTitle)
|
AppNavigator.openMap(item.lat, item.lon, 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))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
) { Text("Maps") }
|
) { Text("Maps") }
|
||||||
|
|
||||||
@@ -419,11 +333,7 @@ fun DmDialog(
|
|||||||
onClick = {
|
onClick = {
|
||||||
val u = item.webUrl // Ändrad: objectUrl -> webUrl
|
val u = item.webUrl // Ändrad: objectUrl -> webUrl
|
||||||
if (!u.isNullOrBlank()) {
|
if (!u.isNullOrBlank()) {
|
||||||
val i = Intent(Intent.ACTION_VIEW, Uri.parse(u))
|
AppNavigator.openUrl(u)
|
||||||
try {
|
|
||||||
context.startActivity(i)
|
|
||||||
} catch (_: Exception) {
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
enabled = !item.webUrl.isNullOrBlank() // Ändrad: objectUrl -> webUrl
|
enabled = !item.webUrl.isNullOrBlank() // Ändrad: objectUrl -> webUrl
|
||||||
@@ -3,12 +3,15 @@ package app.klottr.ui
|
|||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
import androidx.compose.foundation.layout.fillMaxSize // Vi fyller ytan
|
import androidx.compose.foundation.layout.fillMaxSize // Vi fyller ytan
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.State
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.text.TextStyle
|
import androidx.compose.ui.text.TextStyle
|
||||||
import androidx.compose.foundation.text.BasicText
|
import androidx.compose.foundation.text.BasicText
|
||||||
|
import app.klottr.location.GeoPoint
|
||||||
import app.klottr.util.FoundEntry
|
import app.klottr.util.FoundEntry
|
||||||
import app.klottr.nearby.foundSubtitle
|
import app.klottr.nearby.foundSubtitle
|
||||||
import app.klottr.nearby.layerDisplayName
|
import app.klottr.nearby.layerDisplayName
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Material-fritt innehåll för "Hittat".
|
* Material-fritt innehåll för "Hittat".
|
||||||
@@ -18,8 +21,7 @@ import app.klottr.nearby.layerDisplayName
|
|||||||
@Composable
|
@Composable
|
||||||
fun FoundContent(
|
fun FoundContent(
|
||||||
entries: List<FoundEntry>,
|
entries: List<FoundEntry>,
|
||||||
currentLat: Double?,
|
location: State<GeoPoint?>,
|
||||||
currentLon: Double?,
|
|
||||||
showCoords: Boolean,
|
showCoords: Boolean,
|
||||||
// Förbättrade etiketter (klotter): nyckel = "layer|id"
|
// Förbättrade etiketter (klotter): nyckel = "layer|id"
|
||||||
labelOverrides: Map<String, String>,
|
labelOverrides: Map<String, String>,
|
||||||
@@ -55,8 +57,8 @@ fun FoundContent(
|
|||||||
subtitleFor = { f ->
|
subtitleFor = { f ->
|
||||||
foundSubtitle(
|
foundSubtitle(
|
||||||
entry = f,
|
entry = f,
|
||||||
currentLat = currentLat,
|
currentLat = location.value?.lat,
|
||||||
currentLon = currentLon,
|
currentLon = location.value?.lon,
|
||||||
showCoords = showCoords,
|
showCoords = showCoords,
|
||||||
distanceFormatter = distanceFormatter,
|
distanceFormatter = distanceFormatter,
|
||||||
coordsFormatter = coordsFormatter
|
coordsFormatter = coordsFormatter
|
||||||
|
|||||||
@@ -2,9 +2,11 @@ package app.klottr.ui
|
|||||||
|
|
||||||
import androidx.compose.foundation.layout.*
|
import androidx.compose.foundation.layout.*
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.State
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.text.TextStyle
|
import androidx.compose.ui.text.TextStyle
|
||||||
import androidx.compose.ui.unit.dp // För .dp i padding/spacedBy
|
import androidx.compose.ui.unit.dp // För .dp i padding/spacedBy
|
||||||
|
import app.klottr.location.GeoPoint
|
||||||
import app.klottr.util.FoundEntry
|
import app.klottr.util.FoundEntry
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
@@ -12,8 +14,7 @@ fun KlottrHomeContent(
|
|||||||
contentPadding: PaddingValues,
|
contentPadding: PaddingValues,
|
||||||
// FoundContent-parametrar (delat)
|
// FoundContent-parametrar (delat)
|
||||||
entries: List<FoundEntry>,
|
entries: List<FoundEntry>,
|
||||||
currentLat: Double?,
|
location: State<GeoPoint?>,
|
||||||
currentLon: Double?,
|
|
||||||
showCoords: Boolean,
|
showCoords: Boolean,
|
||||||
labelOverrides: Map<String, String>,
|
labelOverrides: Map<String, String>,
|
||||||
isClickable: (FoundEntry) -> Boolean,
|
isClickable: (FoundEntry) -> Boolean,
|
||||||
@@ -41,8 +42,7 @@ fun KlottrHomeContent(
|
|||||||
) {
|
) {
|
||||||
FoundContent(
|
FoundContent(
|
||||||
entries = entries,
|
entries = entries,
|
||||||
currentLat = currentLat,
|
location = location,
|
||||||
currentLon = currentLon,
|
|
||||||
showCoords = showCoords,
|
showCoords = showCoords,
|
||||||
labelOverrides = labelOverrides,
|
labelOverrides = labelOverrides,
|
||||||
isClickable = isClickable,
|
isClickable = isClickable,
|
||||||
|
|||||||
@@ -1,6 +0,0 @@
|
|||||||
package app.klottr.location
|
|
||||||
|
|
||||||
/** iOS-stub tills riktig plats läggs till. */
|
|
||||||
object IosLocationProvider : LocationProvider {
|
|
||||||
override suspend fun currentOrLastKnown(): GeoPoint? = null
|
|
||||||
}
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
package app.klottr.location
|
|
||||||
|
|
||||||
/** iOS implementation keeps the last known point in memory. */
|
|
||||||
actual object LastLocationStore {
|
|
||||||
actual var lastKnown: GeoPoint? = null
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
package app.klottr.location
|
||||||
|
|
||||||
|
import kotlinx.cinterop.ExperimentalForeignApi
|
||||||
|
import kotlinx.cinterop.useContents
|
||||||
|
import kotlinx.coroutines.*
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import platform.CoreLocation.*
|
||||||
|
import platform.Foundation.NSError
|
||||||
|
import platform.Foundation.timeIntervalSince1970
|
||||||
|
import platform.darwin.NSObject
|
||||||
|
|
||||||
|
private class IOSLocationService(
|
||||||
|
private val scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||||
|
) : NSObject(), LocationService, CLLocationManagerDelegateProtocol {
|
||||||
|
|
||||||
|
private val manager = CLLocationManager()
|
||||||
|
private val _location = MutableStateFlow<GeoPoint?>(null)
|
||||||
|
override val location: StateFlow<GeoPoint?> = _location
|
||||||
|
|
||||||
|
private var started = false
|
||||||
|
private var highAccuracy = true
|
||||||
|
|
||||||
|
init {
|
||||||
|
manager.delegate = this
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun start(updates: LocationUpdates) {
|
||||||
|
if (started) return
|
||||||
|
started = true
|
||||||
|
highAccuracy = updates.highAccuracy
|
||||||
|
manager.desiredAccuracy = if (updates.highAccuracy) kCLLocationAccuracyBest else kCLLocationAccuracyHundredMeters
|
||||||
|
manager.distanceFilter = kCLDistanceFilterNone
|
||||||
|
when (CLLocationManager.authorizationStatus()) {
|
||||||
|
kCLAuthorizationStatusNotDetermined -> manager.requestWhenInUseAuthorization()
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
manager.startUpdatingLocation()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun stop() {
|
||||||
|
if (!started) return
|
||||||
|
manager.stopUpdatingLocation()
|
||||||
|
started = false
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun current(highAccuracy: Boolean, timeoutMillis: Long): GeoPoint? {
|
||||||
|
// On iOS, startUpdatingLocation yields callbacks; just return latest within timeout.
|
||||||
|
if (!started) start(LocationUpdates(highAccuracy = highAccuracy))
|
||||||
|
return try {
|
||||||
|
withTimeout(timeoutMillis) {
|
||||||
|
while (_location.value == null) delay(50)
|
||||||
|
_location.value
|
||||||
|
}
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
_location.value ?: LastLocationStore.lastKnownLocation.value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun isLocationEnabled(): Boolean {
|
||||||
|
return CLLocationManager.locationServicesEnabled()
|
||||||
|
}
|
||||||
|
|
||||||
|
// CLLocationManagerDelegate
|
||||||
|
@OptIn(ExperimentalForeignApi::class)
|
||||||
|
override fun locationManager(manager: CLLocationManager, didUpdateLocations: List<*>) {
|
||||||
|
val last = (didUpdateLocations.lastOrNull() as? CLLocation) ?: return
|
||||||
|
val ts = last.timestamp.timeIntervalSince1970() * 1000.0
|
||||||
|
last.coordinate.useContents {
|
||||||
|
val lat = latitude
|
||||||
|
val lon = longitude
|
||||||
|
val p = GeoPoint(
|
||||||
|
lat = lat,
|
||||||
|
lon = lon,
|
||||||
|
accuracyMeters = last.horizontalAccuracy,
|
||||||
|
timeMillis = ts.toLong()
|
||||||
|
)
|
||||||
|
_location.value = p
|
||||||
|
LastLocationStore.update(p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override fun locationManager(manager: CLLocationManager, didFailWithError: NSError) { /* ignore */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
actual object LocationServiceProvider {
|
||||||
|
private val instance: LocationService by lazy { IOSLocationService() }
|
||||||
|
actual fun get(): LocationService = instance
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package app.klottr.platform
|
||||||
|
|
||||||
|
import platform.Foundation.NSURL
|
||||||
|
import platform.UIKit.UIApplication
|
||||||
|
import platform.UIKit.UIApplicationOpenSettingsURLString
|
||||||
|
import platform.UIKit.UIApplicationSharedApplication
|
||||||
|
|
||||||
|
actual object AppNavigator {
|
||||||
|
actual fun openUrl(url: String) {
|
||||||
|
val nsUrl = NSURL.URLWithString(url) ?: return
|
||||||
|
UIApplication.sharedApplication.openURL(nsUrl)
|
||||||
|
}
|
||||||
|
actual fun openMap(lat: Double, lon: Double, label: String?) {
|
||||||
|
// Use Apple Maps URL scheme
|
||||||
|
val encoded = label?.let { it } ?: "Place"
|
||||||
|
val url = "http://maps.apple.com/?ll=$lat,$lon&q=$encoded"
|
||||||
|
openUrl(url)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
actual object UiFeedback {
|
||||||
|
actual fun showMessage(text: String, duration: UiFeedbackDuration) {
|
||||||
|
// No-op or implement a lightweight HUD; keeping no-op by default.
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package app.klottr.platform
|
||||||
|
|
||||||
|
actual object OutboxScheduler {
|
||||||
|
actual fun scheduleUpload() {
|
||||||
|
// iOS can use BGTaskScheduler / background URLSession; left as future hook.
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,9 +4,11 @@ import androidx.compose.runtime.Composable
|
|||||||
import androidx.compose.ui.platform.LocalDensity
|
import androidx.compose.ui.platform.LocalDensity
|
||||||
import androidx.compose.ui.unit.Dp
|
import androidx.compose.ui.unit.Dp
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
|
import kotlinx.cinterop.ExperimentalForeignApi
|
||||||
import platform.UIKit.UIScreen
|
import platform.UIKit.UIScreen
|
||||||
import platform.CoreGraphics.CGRectGetHeight
|
import platform.CoreGraphics.CGRectGetHeight
|
||||||
|
|
||||||
|
@OptIn(ExperimentalForeignApi::class)
|
||||||
@Composable
|
@Composable
|
||||||
actual fun platformScreenHeightDp(): Dp {
|
actual fun platformScreenHeightDp(): Dp {
|
||||||
// UIKit gives points; convert to Compose dp via LocalDensity for safety.
|
// UIKit gives points; convert to Compose dp via LocalDensity for safety.
|
||||||
@@ -16,3 +18,12 @@ actual fun platformScreenHeightDp(): Dp {
|
|||||||
return with(density) { heightPoints.toFloat().dp }
|
return with(density) { heightPoints.toFloat().dp }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@OptIn(ExperimentalForeignApi::class)
|
||||||
|
@Composable
|
||||||
|
actual fun platformScreenWidthDp(): Dp {
|
||||||
|
// UIKit gives points; convert to Compose dp via LocalDensity for safety.
|
||||||
|
val heightPoints: Double = CGRectGetHeight(UIScreen.mainScreen.bounds)
|
||||||
|
val density = LocalDensity.current
|
||||||
|
// Compose dp ~= iOS points; still convert explicitly.
|
||||||
|
return with(density) { heightPoints.toFloat().dp }
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user