Move most of net to shared, use AsyncImage for url loaded images
Introduce BuildKonfig to be able to have KMP build config Preparing DialogShells to be moved to shared (not possible to move yet)
This commit is contained in:
@@ -108,8 +108,7 @@ import app.klottr.nearby.scanAndMarkFound
|
||||
import app.klottr.net.Api
|
||||
import app.klottr.net.DigitaltMuseum
|
||||
import app.klottr.net.DigitaltMuseumItem
|
||||
import app.klottr.net.Fornsok
|
||||
import app.klottr.net.FornsokItem
|
||||
import app.klottr.net.FornsokShared
|
||||
import app.klottr.net.Geocache
|
||||
import app.klottr.net.Wikipedia
|
||||
import app.klottr.net.createNoteDoc
|
||||
@@ -146,6 +145,8 @@ import app.klottr.util.buildFoundDetailStrings // Delad formatterare (commonMain
|
||||
import app.klottr.util.formatCoords
|
||||
import app.klottr.util.formatDistance
|
||||
import app.klottr.work.OutboxWorker
|
||||
import coil3.ImageLoader
|
||||
import coil3.compose.setSingletonImageLoaderFactory
|
||||
import com.google.android.gms.auth.api.signin.GoogleSignIn
|
||||
import com.google.android.gms.common.api.ApiException
|
||||
import com.google.android.gms.location.Priority
|
||||
@@ -462,7 +463,7 @@ private fun KlottrAppShell(
|
||||
),
|
||||
fetchWiki = { la, lo, r -> Wikipedia.getNearby(la, lo, radiusMeters = r) },
|
||||
fetchDm = { la, lo, r -> DigitaltMuseum.getNearby(la, lo, radiusMeters = r) },
|
||||
fetchFornsok = { la, lo, r -> Fornsok.getNearby(la, lo, radiusMeters = r) },
|
||||
fetchFornsok = { la, lo, r -> FornsokShared.getNearby(la, lo, radiusMeters = r) },
|
||||
markFound = { layer, id, label, la, lo, now ->
|
||||
FoundStore.markFound(layer, id, label, la, lo, now)
|
||||
},
|
||||
@@ -572,7 +573,7 @@ private fun KlottrAppShell(
|
||||
entry = f,
|
||||
labelOverrides = labelOverrides,
|
||||
fornsokAround = { lat, lon, radius ->
|
||||
try { Fornsok.getNearby(lat, lon, radius) } catch (_: Exception) { emptyList() }
|
||||
try { FornsokShared.getNearby(lat, lon, radius) } catch (_: Exception) { emptyList() }
|
||||
},
|
||||
dmLookupByIdentifier = { id ->
|
||||
try { app.klottr.net.DigitaltMuseum.lookupByIdentifier(id) } catch (_: Exception) { null }
|
||||
@@ -664,7 +665,7 @@ private fun KlottrAppShell(
|
||||
},
|
||||
wikiFetcher = { la, lo, r -> Wikipedia.getNearby(la, lo, radiusMeters = r) },
|
||||
dmFetcher = { la, lo, r -> DigitaltMuseum.getNearby(la, lo, radiusMeters = r) },
|
||||
fornFetcher = { la, lo, r -> Fornsok.getNearby(la, lo, radiusMeters = r) }
|
||||
fornFetcher = { la, lo, r -> FornsokShared.getNearby(la, lo, radiusMeters = r) }
|
||||
)
|
||||
}
|
||||
nearbyBundle = bundle
|
||||
@@ -815,7 +816,7 @@ private fun KlottrAppShell(
|
||||
config = cfg,
|
||||
fetchWiki = { la, lo, r -> Wikipedia.getNearby(la, lo, radiusMeters = r) },
|
||||
fetchDm = { la, lo, r -> DigitaltMuseum.getNearby(la, lo, radiusMeters = r) },
|
||||
fetchFornsok = { la, lo, r -> Fornsok.getNearby(la, lo, radiusMeters = r) },
|
||||
fetchFornsok = { la, lo, r -> FornsokShared.getNearby(la, lo, radiusMeters = r) },
|
||||
markFound = { layer, id, label, la, lo, now ->
|
||||
FoundStore.markFound(layer, id, label, la, lo, now)
|
||||
},
|
||||
@@ -1735,7 +1736,8 @@ private fun KlotterDialog(
|
||||
}
|
||||
}
|
||||
if (showImageViewer && imgBitmap != null) {
|
||||
ImageViewerDialog(bitmap = imgBitmap!!, onClose = { showImageViewer = false })
|
||||
//TODO: Use new platform independent ImageViewerDialog
|
||||
// ImageViewerDialog(bitmap = imgBitmap!!, onClose = { showImageViewer = false })
|
||||
}
|
||||
if (askDelete) {
|
||||
AlertDialog(
|
||||
|
||||
@@ -20,8 +20,8 @@ import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
import app.klottr.net.DigitaltMuseum
|
||||
import app.klottr.net.DigitaltMuseumItem
|
||||
import app.klottr.net.Fornsok
|
||||
import app.klottr.net.FornsokItem
|
||||
import app.klottr.net.FornsokShared
|
||||
import app.klottr.net.Geocache
|
||||
import app.klottr.net.NoteDTO
|
||||
import app.klottr.net.Wikipedia
|
||||
@@ -131,7 +131,7 @@ fun MapDialog(
|
||||
|
||||
if (showFornsok) {
|
||||
forn = withContext(Dispatchers.IO) {
|
||||
Fornsok.getNearby(lat = lat, lon = lon, radiusMeters = fornsokRadius)
|
||||
FornsokShared.getNearby(lat = lat, lon = lon, radiusMeters = fornsokRadius)
|
||||
}
|
||||
} else forn = emptyList()
|
||||
}
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
package app.klottr.net
|
||||
|
||||
import app.klottr.BuildConfig
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* Android-adapter för DigitaltMuseum.
|
||||
* - Läser DM_API_KEY och DM_OWNERS från BuildConfig (hemligheter stannar i :app).
|
||||
* - Delegerar alla anrop till delad KMP-klient (DigitaltMuseumShared) i :shared.
|
||||
* - Ingen nätverkslogik här: endast injicering av nycklar/ägare och tråd (Dispatchers.IO).
|
||||
*/
|
||||
object DigitaltMuseum {
|
||||
|
||||
suspend fun getNearby(
|
||||
lat: Double,
|
||||
lon: Double,
|
||||
radiusMeters: Int
|
||||
): List<DigitaltMuseumItem> = withContext(Dispatchers.IO) {
|
||||
val apiKey = BuildConfig.DM_API_KEY.orEmpty().trim()
|
||||
if (apiKey.isBlank()) return@withContext emptyList()
|
||||
|
||||
val owners = BuildConfig.DM_OWNERS
|
||||
.orEmpty().trim()
|
||||
.split(',', ' ', ';')
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotEmpty() }
|
||||
|
||||
DigitaltMuseumShared.getNearby(
|
||||
apiKey = apiKey,
|
||||
owners = owners,
|
||||
lat = lat,
|
||||
lon = lon,
|
||||
radiusMeters = radiusMeters
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun lookupByIdentifier(identifierId: String): DigitaltMuseumItem? = withContext(Dispatchers.IO) {
|
||||
val apiKey = BuildConfig.DM_API_KEY.orEmpty().trim()
|
||||
if (apiKey.isBlank()) return@withContext null
|
||||
DigitaltMuseumShared.lookupByIdentifier(
|
||||
apiKey = apiKey,
|
||||
identifierId = identifierId
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun getDetailText(uniqueId: String?, owner: String?, identifierId: String): String? = withContext(Dispatchers.IO) {
|
||||
val apiKey = BuildConfig.DM_API_KEY.orEmpty().trim()
|
||||
if (apiKey.isBlank()) return@withContext null
|
||||
DigitaltMuseumShared.getDetailText(
|
||||
apiKey = apiKey,
|
||||
uniqueId = uniqueId,
|
||||
owner = owner,
|
||||
identifierId = identifierId
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,558 +0,0 @@
|
||||
package app.klottr.net
|
||||
|
||||
import app.klottr.util.KLog
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.net.URLEncoder
|
||||
import java.util.Locale
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.cos
|
||||
|
||||
|
||||
object Fornsok {
|
||||
|
||||
private const val TAG = "Fornsok"
|
||||
private const val BASE = "https://kulturarvsdata.se/ksamsok/api"
|
||||
private const val HITS = 200
|
||||
private const val MAX_PAGES_FAST = 3 // presentation-schemat
|
||||
private const val MAX_PAGES_FALLBACK = 3 // fullt schema (tyngre)
|
||||
|
||||
suspend fun getNearby(
|
||||
lat: Double,
|
||||
lon: Double,
|
||||
radiusMeters: Int
|
||||
): List<FornsokItem> = withContext(Dispatchers.IO) {
|
||||
// Delegerar till delad KMP-klient (FornsokShared) – ingen övrig beteendeförändring här.
|
||||
return@withContext FornsokShared.getNearby(lat, lon, radiusMeters)
|
||||
}
|
||||
|
||||
// För detaljrutan från Hittat: hämta titel + desc + coords för ett känt entityUri
|
||||
suspend fun getByEntityUri(entityUri: String): FornsokItem? = withContext(Dispatchers.IO) {
|
||||
val cql = """entityUri="$entityUri""""
|
||||
val url = buildUrl(cql, startRecord = 1, usePresentation = true)
|
||||
KLog.d(TAG) { "Detalj: GET $url"}
|
||||
val root = httpGetJson(url) ?: return@withContext null
|
||||
val result = root.optJSONObject("result") ?: return@withContext null
|
||||
|
||||
val recordsNode = result.opt("records")
|
||||
val recordArr: JSONArray = when (recordsNode) {
|
||||
is JSONObject -> {
|
||||
val r = recordsNode.opt("record")
|
||||
when (r) {
|
||||
is JSONArray -> r
|
||||
is JSONObject -> JSONArray().put(r)
|
||||
else -> JSONArray()
|
||||
}
|
||||
}
|
||||
else -> JSONArray()
|
||||
}
|
||||
if (recordArr.length() == 0) return@withContext null
|
||||
|
||||
// Ta första giltiga posten
|
||||
for (i in 0 until recordArr.length()) {
|
||||
val rec = recordArr.optJSONObject(i) ?: continue
|
||||
|
||||
val svc = (findStringDeep(rec, "serviceName")
|
||||
?: findStringDeep(rec, "pres:service"))
|
||||
?.lowercase()
|
||||
|
||||
val looksFornsok = (svc == "kmr_lamningar" || svc == "fmi") ||
|
||||
entityUri.contains("/raa/lamning/", true) ||
|
||||
entityUri.contains("/raa/fmi/", true) ||
|
||||
entityUri.contains("/raa/fmis/", true) ||
|
||||
entityUri.contains("/raa/fornsok", true)
|
||||
|
||||
val ll = extractLatLonPresentation(rec) ?: extractLatLonGeneric(rec) ?: continue
|
||||
val (latV, lonV) = ll
|
||||
|
||||
val title = findStringDeep(rec, "pres:itemLabel")
|
||||
?: findStringDeep(rec, "pres:title")
|
||||
?: "Fornlämning"
|
||||
|
||||
val desc = findStringDeep(rec, "pres:description")
|
||||
val svcName = svc ?: "fornsok"
|
||||
|
||||
if (looksFornsok) {
|
||||
return@withContext FornsokItem(
|
||||
id = entityUri,
|
||||
title = title,
|
||||
lat = latV,
|
||||
lon = lonV,
|
||||
uri = entityUri,
|
||||
serviceName = svcName,
|
||||
desc = desc
|
||||
)
|
||||
}
|
||||
}
|
||||
return@withContext null
|
||||
}
|
||||
|
||||
// ------------------- HTTP + parse -------------------
|
||||
|
||||
private fun buildUrl(cql: String, startRecord: Int, usePresentation: Boolean): String {
|
||||
val sb = StringBuilder()
|
||||
.append("version=1.1")
|
||||
.append("&method=search")
|
||||
.append("&hitsPerPage=").append(HITS)
|
||||
.append("&startRecord=").append(startRecord)
|
||||
|
||||
if (usePresentation) {
|
||||
val fields =
|
||||
"pres:entityUri,pres:id,pres:itemPosition,pres:coordinates,pres:latitude,pres:longitude,pres:title,pres:itemLabel,pres:service,serviceName,pres:description"
|
||||
sb.append("&recordSchema=presentation")
|
||||
sb.append("&fields=").append(URLEncoder.encode(fields, "UTF-8"))
|
||||
}
|
||||
sb.append("&query=").append(URLEncoder.encode(cql, "UTF-8").replace("+", "%20"))
|
||||
return "$BASE?$sb"
|
||||
}
|
||||
|
||||
private fun httpGetJson(url: String): JSONObject? {
|
||||
val conn = (URL(url).openConnection() as HttpURLConnection).apply {
|
||||
connectTimeout = 10000
|
||||
readTimeout = 20000
|
||||
setRequestProperty("Accept", "application/json")
|
||||
setRequestProperty("User-Agent", "Klottr/0.1.x (Android)")
|
||||
}
|
||||
return try {
|
||||
val code = conn.responseCode
|
||||
val ctype = conn.getHeaderField("Content-Type")
|
||||
KLog.d(TAG) { "HTTP $code Content-Type=$ctype"}
|
||||
if (code !in 200..299) return null
|
||||
val body = conn.inputStream.use { it.readBytes().toString(Charsets.UTF_8) }
|
||||
if (body.isBlank()) return null
|
||||
JSONObject(body)
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
} finally {
|
||||
conn.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
private fun queryAndParse(cql: String, usePresentation: Boolean, maxPages: Int): List<FornsokItem> {
|
||||
val out = LinkedHashMap<String, FornsokItem>()
|
||||
var start = 1
|
||||
var page = 1
|
||||
var totalHitsFromServer = -1
|
||||
|
||||
while (page <= maxPages) {
|
||||
val url = buildUrl(cql, start, usePresentation)
|
||||
KLog.d(TAG) { "Sida $page: GET $url"}
|
||||
val root = httpGetJson(url) ?: break
|
||||
|
||||
val result = root.optJSONObject("result") ?: break
|
||||
if (totalHitsFromServer < 0) {
|
||||
totalHitsFromServer = result.optInt("totalHits", -1)
|
||||
KLog.d(TAG) { "totalHits (server): $totalHitsFromServer"}
|
||||
}
|
||||
|
||||
val recordsNode = result.opt("records")
|
||||
val recordArr: JSONArray = when (recordsNode) {
|
||||
is JSONObject -> {
|
||||
val r = recordsNode.opt("record")
|
||||
when (r) {
|
||||
is JSONArray -> r
|
||||
is JSONObject -> JSONArray().put(r)
|
||||
else -> JSONArray()
|
||||
}
|
||||
}
|
||||
else -> JSONArray()
|
||||
}
|
||||
|
||||
if (recordArr.length() == 0) {
|
||||
KLog.d(TAG) { "Ingen records.record på denna sida."}
|
||||
break
|
||||
}
|
||||
|
||||
var visited = 0
|
||||
var nonKmrFmi = 0
|
||||
var noCoords = 0
|
||||
var added = 0
|
||||
|
||||
for (i in 0 until recordArr.length()) {
|
||||
val rec = recordArr.optJSONObject(i) ?: continue
|
||||
visited++
|
||||
|
||||
val svc = (findStringDeep(rec, "serviceName")
|
||||
?: findStringDeep(rec, "pres:service"))
|
||||
?.lowercase()
|
||||
|
||||
val entityUri = findStringDeep(rec, "pres:entityUri")
|
||||
?: findStringDeep(rec, "entityUri")
|
||||
?: findStringDeep(rec, "item")
|
||||
|
||||
val presId = findStringDeep(rec, "pres:id")
|
||||
|
||||
// --- Koordinater ---
|
||||
val ll = if (usePresentation) {
|
||||
extractLatLonPresentation(rec) ?: extractLatLonGeneric(rec)
|
||||
} else {
|
||||
extractLatLonGeneric(rec)
|
||||
}
|
||||
if (ll == null) {
|
||||
noCoords++
|
||||
continue
|
||||
}
|
||||
val (latV, lonV) = ll
|
||||
|
||||
// Klassificera som Fornsök/FMIS/KMR
|
||||
val looksFornsok = when {
|
||||
svc == "kmr_lamningar" || svc == "fmi" -> true
|
||||
entityUri?.contains("/raa/fmi/", ignoreCase = true) == true -> true
|
||||
entityUri?.contains("/raa/fmis/", ignoreCase = true) == true -> true
|
||||
entityUri?.contains("/raa/lamning/", ignoreCase = true) == true -> true
|
||||
entityUri?.contains("/raa/fornsok", ignoreCase = true) == true -> true
|
||||
else -> false
|
||||
}
|
||||
if (!looksFornsok) {
|
||||
nonKmrFmi++
|
||||
continue
|
||||
}
|
||||
|
||||
// Titel + beskrivning (presentation innehåller ofta description)
|
||||
val title = findStringDeep(rec, "pres:itemLabel")
|
||||
?: findStringDeep(rec, "pres:title")
|
||||
?: findStringDeep(rec, "title")
|
||||
?: findStringDeep(rec, "label")
|
||||
?: "Fornlämning"
|
||||
|
||||
val description = findStringDeep(rec, "pres:description")
|
||||
|
||||
// Stabilt id
|
||||
val id = when {
|
||||
entityUri != null -> entityUri
|
||||
presId != null -> "kmr:$presId"
|
||||
else -> "${title}@${fmt6(latV)},${fmt6(lonV)}"
|
||||
}
|
||||
|
||||
if (!out.containsKey(id)) {
|
||||
out[id] = FornsokItem(
|
||||
id = id,
|
||||
title = title,
|
||||
lat = latV,
|
||||
lon = lonV,
|
||||
uri = entityUri,
|
||||
serviceName = svc,
|
||||
desc = description
|
||||
)
|
||||
added++
|
||||
}
|
||||
}
|
||||
KLog.d(TAG) {"Sida: genomgång visited=$visited, nonKmrFmi=$nonKmrFmi, noCoords=$noCoords, tillagda=$added, ack=${out.size}" }
|
||||
|
||||
// Fler sidor?
|
||||
if (totalHitsFromServer > 0) {
|
||||
val maxByHits = (totalHitsFromServer + HITS - 1) / HITS
|
||||
if (page >= maxByHits) break
|
||||
}
|
||||
start += HITS
|
||||
page++
|
||||
|
||||
if (out.size >= 150) break
|
||||
}
|
||||
|
||||
return out.values.toList()
|
||||
}
|
||||
|
||||
// ------------------- Lat/Lon extraktion -------------------
|
||||
|
||||
/** Presentation-schema – vägar inkl. gml:coordinates.content och gml:pos/posList. */
|
||||
private fun extractLatLonPresentation(rec: JSONObject): Pair<Double, Double>? {
|
||||
// 1) pres:itemPosition = "POINT(lon lat)"
|
||||
val pos = findStringDeep(rec, "pres:itemPosition")
|
||||
if (!pos.isNullOrBlank()) {
|
||||
val lonLat = parseWktPoint(pos)
|
||||
if (lonLat != null) return Pair(lonLat.second, lonLat.first) // lat, lon
|
||||
}
|
||||
|
||||
// 2) pres:coordinates = [{lat:.., lon|lng:..}, ...]
|
||||
val coords = findArrayDeep(rec, "pres:coordinates")
|
||||
if (coords != null && coords.length() > 0) {
|
||||
val c0 = coords.optJSONObject(0)
|
||||
if (c0 != null) {
|
||||
val lat = numOrNull(c0.opt("lat")) ?: numOrNull(c0.opt("latitude"))
|
||||
val lon = numOrNull(c0.opt("lon")) ?: numOrNull(c0.opt("lng")) ?: numOrNull(c0.opt("longitude"))
|
||||
if (lat != null && lon != null) return Pair(lat, lon)
|
||||
}
|
||||
}
|
||||
|
||||
// 3) pres:latitude/pres:longitude
|
||||
val latStr = findStringDeep(rec, "pres:latitude")
|
||||
val lonStr = findStringDeep(rec, "pres:longitude")
|
||||
if (!latStr.isNullOrBlank() && !lonStr.isNullOrBlank()) {
|
||||
val la = latStr.replace(",", ".").toDoubleOrNull()
|
||||
val lo = lonStr.replace(",", ".").toDoubleOrNull()
|
||||
if (la != null && lo != null) return Pair(la, lo)
|
||||
}
|
||||
|
||||
// 4) georss:where -> gml:Point -> gml:coordinates { content: "lon, lat" }
|
||||
val gmlCoordsObj = findObjectDeep(rec, "gml:coordinates")
|
||||
if (gmlCoordsObj != null) {
|
||||
val content = gmlCoordsObj.optString("content")
|
||||
if (!content.isNullOrBlank()) {
|
||||
val lonLat = parseLonLat(content)
|
||||
if (lonLat != null) return Pair(lonLat.second, lonLat.first)
|
||||
}
|
||||
}
|
||||
|
||||
// 5) gml:pos eller gml:posList (sträng med "lon lat [lon lat …]")
|
||||
val gmlPos = findStringDeep(rec, "gml:pos")
|
||||
if (!gmlPos.isNullOrBlank()) {
|
||||
parsePosOrPosList(gmlPos)?.let { return it }
|
||||
}
|
||||
val gmlPosListStr = findStringDeep(rec, "gml:posList")
|
||||
if (!gmlPosListStr.isNullOrBlank()) {
|
||||
parsePosOrPosList(gmlPosListStr)?.let { return it }
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/** Fullt schema – skanna allt efter koordinater (GeoRSS/GML/JSON-LD). */
|
||||
private fun extractLatLonGeneric(node: Any?): Pair<Double, Double>? {
|
||||
return scanForLatLon(node)?.takeIf { isValidLatLon(it.first, it.second) }
|
||||
}
|
||||
|
||||
/** Rekursiv sökning efter lat/lon i godtycklig JSON-struktur. */
|
||||
private fun scanForLatLon(node: Any?): Pair<Double, Double>? {
|
||||
when (node) {
|
||||
is JSONObject -> {
|
||||
val it = node.keys()
|
||||
while (it.hasNext()) {
|
||||
val k = it.next()
|
||||
val v = node.opt(k)
|
||||
|
||||
// WKT POINT(lon lat)
|
||||
if (v is String && v.contains("POINT", ignoreCase = true)) {
|
||||
parseWktPoint(v)?.let { (lon, lat) ->
|
||||
if (isValidLatLon(lat, lon)) return Pair(lat, lon)
|
||||
}
|
||||
}
|
||||
|
||||
// gml:coordinates → objekt med content eller sträng
|
||||
if (k.endsWith("coordinates", true)) {
|
||||
when (v) {
|
||||
is String -> {
|
||||
parseLonLat(v)?.let { (lon, lat) ->
|
||||
if (isValidLatLon(lat, lon)) return Pair(lat, lon)
|
||||
}
|
||||
}
|
||||
is JSONObject -> {
|
||||
val s = v.optString("content")
|
||||
if (!s.isNullOrBlank()) {
|
||||
parseLonLat(s)?.let { (lon, lat) ->
|
||||
if (isValidLatLon(lat, lon)) return Pair(lat, lon)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// gml:pos / gml:posList
|
||||
if (k.endsWith("pos", true) || k.endsWith("posList", true)) {
|
||||
when (v) {
|
||||
is String -> parsePosOrPosList(v)?.let { return it }
|
||||
is JSONObject -> {
|
||||
val s = v.optString("content")
|
||||
if (!s.isNullOrBlank()) parsePosOrPosList(s)?.let { return it }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Objekt med {lat, lon|long|lng} etc.
|
||||
if (v is JSONObject) {
|
||||
val lat = numOrNull(v.opt("lat"))
|
||||
?: numOrNull(v.opt("latitude"))
|
||||
?: numOrNull(v.opt("wgs84_pos:lat"))
|
||||
val lon = numOrNull(v.opt("lon"))
|
||||
?: numOrNull(v.opt("lng"))
|
||||
?: numOrNull(v.opt("long"))
|
||||
?: numOrNull(v.opt("longitude"))
|
||||
?: numOrNull(v.opt("wgs84_pos:long"))
|
||||
if (lat != null && lon != null && isValidLatLon(lat, lon)) {
|
||||
return Pair(lat, lon)
|
||||
}
|
||||
}
|
||||
|
||||
// Array med två tal → [lon, lat] eller [lat, lon]
|
||||
if (v is JSONArray && v.length() == 2) {
|
||||
val a = numOrNull(v.opt(0))
|
||||
val b = numOrNull(v.opt(1))
|
||||
if (a != null && b != null) {
|
||||
if (isValidLatLon(b, a)) return Pair(b, a)
|
||||
if (isValidLatLon(a, b)) return Pair(a, b)
|
||||
}
|
||||
}
|
||||
|
||||
// Rekursion
|
||||
scanForLatLon(v)?.let { return it }
|
||||
}
|
||||
}
|
||||
is JSONArray -> {
|
||||
if (node.length() >= 2) {
|
||||
if (node.length() % 2 == 0) {
|
||||
val a0 = numOrNull(node.opt(0))
|
||||
val a1 = numOrNull(node.opt(1))
|
||||
if (a0 != null && a1 != null) {
|
||||
if (isValidLatLon(a1, a0)) return Pair(a1, a0)
|
||||
if (isValidLatLon(a0, a1)) return Pair(a0, a1)
|
||||
}
|
||||
}
|
||||
for (i in 0 until node.length()) {
|
||||
scanForLatLon(node.opt(i))?.let { return it }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// ------------------- Utils -------------------
|
||||
|
||||
private data class BBox(val w: Double, val s: Double, val e: Double, val n: Double)
|
||||
|
||||
private fun bboxWgs84(lat: Double, lon: Double, rMeters: Int): BBox {
|
||||
val r = rMeters.coerceAtLeast(1)
|
||||
val dLat = r / 111_320.0
|
||||
val dLon = r / (111_320.0 * cos(lat * PI / 180.0)).coerceAtLeast(1e-6)
|
||||
return BBox(
|
||||
w = lon - dLon,
|
||||
s = lat - dLat,
|
||||
e = lon + dLon,
|
||||
n = lat + dLat
|
||||
)
|
||||
}
|
||||
|
||||
private fun findStringDeep(node: Any?, key: String): String? {
|
||||
when (node) {
|
||||
is JSONObject -> {
|
||||
if (node.has(key)) {
|
||||
val v = node.opt(key)
|
||||
if (v is String && v.isNotBlank()) return v
|
||||
}
|
||||
val it = node.keys()
|
||||
while (it.hasNext()) {
|
||||
val k = it.next()
|
||||
val child = node.opt(k)
|
||||
val r = findStringDeep(child, key)
|
||||
if (r != null) return r
|
||||
}
|
||||
}
|
||||
is JSONArray -> {
|
||||
for (i in 0 until node.length()) {
|
||||
val r = findStringDeep(node.opt(i), key)
|
||||
if (r != null) return r
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun findObjectDeep(node: Any?, key: String): JSONObject? {
|
||||
when (node) {
|
||||
is JSONObject -> {
|
||||
if (node.has(key)) {
|
||||
val v = node.opt(key)
|
||||
if (v is JSONObject) return v
|
||||
}
|
||||
val it = node.keys()
|
||||
while (it.hasNext()) {
|
||||
val k = it.next()
|
||||
val child = node.opt(k)
|
||||
val r = findObjectDeep(child, key)
|
||||
if (r != null) return r
|
||||
}
|
||||
}
|
||||
is JSONArray -> {
|
||||
for (i in 0 until node.length()) {
|
||||
val r = findObjectDeep(node.opt(i), key)
|
||||
if (r != null) return r
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun findArrayDeep(node: Any?, key: String): JSONArray? {
|
||||
when (node) {
|
||||
is JSONObject -> {
|
||||
if (node.has(key)) {
|
||||
val v = node.opt(key)
|
||||
if (v is JSONArray) return v
|
||||
}
|
||||
val it = node.keys()
|
||||
while (it.hasNext()) {
|
||||
val k = it.next()
|
||||
val child = node.opt(k)
|
||||
val r = findArrayDeep(child, key)
|
||||
if (r != null) return r
|
||||
}
|
||||
}
|
||||
is JSONArray -> {
|
||||
for (i in 0 until node.length()) {
|
||||
val r = findArrayDeep(node.opt(i), key)
|
||||
if (r != null) return r
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun parseWktPoint(s: String): Pair<Double, Double>? {
|
||||
val idx = s.indexOf("POINT", ignoreCase = true)
|
||||
if (idx < 0) return null
|
||||
val open = s.indexOf('(', idx)
|
||||
val close = s.indexOf(')', open + 1)
|
||||
if (open < 0 || close < 0) return null
|
||||
val inner = s.substring(open + 1, close).trim()
|
||||
val parts = inner.split(Regex("\\s+"))
|
||||
if (parts.size >= 2) {
|
||||
val lon = parts[0].replace(",", ".").toDoubleOrNull()
|
||||
val lat = parts[1].replace(",", ".").toDoubleOrNull()
|
||||
if (lon != null && lat != null) return Pair(lon, lat)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun parseLonLat(txt: String): Pair<Double, Double>? {
|
||||
val cleaned = txt.replace(";", ",").trim()
|
||||
val parts = cleaned.split(",")
|
||||
if (parts.size >= 2) {
|
||||
val lon = parts[0].trim().replace(",", ".").toDoubleOrNull()
|
||||
val lat = parts[1].trim().replace(",", ".").toDoubleOrNull()
|
||||
if (lon != null && lat != null) return Pair(lon, lat)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Tolkar gml:pos/gml:posList (första paret). Hanterar både "lon lat" och "lat lon". */
|
||||
private fun parsePosOrPosList(s: String): Pair<Double, Double>? {
|
||||
val parts = s.trim().split(Regex("\\s+"))
|
||||
if (parts.size >= 2) {
|
||||
val a = parts[0].replace(",", ".").toDoubleOrNull()
|
||||
val b = parts[1].replace(",", ".").toDoubleOrNull()
|
||||
if (a != null && b != null) {
|
||||
if (isValidLatLon(b, a)) return Pair(b, a)
|
||||
if (isValidLatLon(a, b)) return Pair(a, b)
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun isValidLatLon(lat: Double, lon: Double): Boolean {
|
||||
return lat in -90.0..90.0 && lon in -180.0..180.0 && !(abs(lat) < 1e-9 && abs(lon) < 1e-9)
|
||||
}
|
||||
|
||||
private fun numOrNull(any: Any?): Double? = when (any) {
|
||||
is Number -> any.toDouble()
|
||||
is String -> any.replace(",", ".").toDoubleOrNull()
|
||||
else -> null
|
||||
}
|
||||
|
||||
private fun fmt6(d: Double): String = String.format(Locale.US, "%.6f", d)
|
||||
private fun fmt8(d: Double): String = String.format(Locale.US, "%.8f", d)
|
||||
}
|
||||
@@ -3,9 +3,12 @@ package app.klottr.net
|
||||
import app.klottr.util.KLog
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlin.math.floor
|
||||
import kotlin.math.roundToInt
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.ExperimentalTime
|
||||
|
||||
/**
|
||||
* Robust cache och hämtning av närliggande anslag.
|
||||
@@ -25,14 +28,17 @@ object Geocache {
|
||||
val sinceMs: Long
|
||||
)
|
||||
|
||||
// Cache per “ruta” (~0.001 grad ≈ 111 m) + radius-bucket för att separera olika radier
|
||||
private val cache = ConcurrentHashMap<String, Entry>()
|
||||
// KMP-säker cache: MutableMap + Mutex i stället för ConcurrentHashMap.
|
||||
// Nyckel per “ruta” (0.001 grad ≈ 111 m) + radius-bucket (50 m steg)
|
||||
private val cache = mutableMapOf<String, Entry>()
|
||||
private val cacheMutex = Mutex()
|
||||
|
||||
/**
|
||||
* Huvudmetod, kompatibel med v0.0.1.
|
||||
*
|
||||
* @param ttlMs hur länge vi litar på cache innan vi försöker hämta nytt
|
||||
*/
|
||||
@OptIn(ExperimentalTime::class)
|
||||
suspend fun getNearby(
|
||||
lat: Double,
|
||||
lon: Double,
|
||||
@@ -40,17 +46,18 @@ object Geocache {
|
||||
ttlMs: Long
|
||||
): List<NoteDTO> = withContext(Dispatchers.IO) {
|
||||
val key = keyFor(lat, lon, radiusMeters)
|
||||
val now = System.currentTimeMillis()
|
||||
val now = Clock.System.now().toEpochMilliseconds()
|
||||
|
||||
// 1) Snabbträff i giltig cache
|
||||
cache[key]?.let { e ->
|
||||
val cached: Entry? = cacheMutex.withLock { cache[key] }
|
||||
cached?.let { e ->
|
||||
if ((now - e.timeMs) <= ttlMs) {
|
||||
return@withContext e.items
|
||||
}
|
||||
}
|
||||
|
||||
// 2) Försök hämta nytt med ETag/since om vi har det
|
||||
val prev = cache[key]
|
||||
val prev = cached
|
||||
val first = safeFetch(
|
||||
lat = lat,
|
||||
lon = lon,
|
||||
@@ -59,7 +66,7 @@ object Geocache {
|
||||
etag = prev?.etag
|
||||
)
|
||||
if (first.code !in listOf(200, 304)) {
|
||||
KLog.d {"Geocache: first fetch failed code=${first.code} → fallback to cache size=${prev?.items?.size ?: 0}"}
|
||||
KLog.d { "Geocache: first fetch failed code=${first.code} → fallback to cache size=${prev?.items?.size ?: 0}" }
|
||||
}
|
||||
|
||||
// Hantera 304/not-modified och nätfel (kod 599 i fetchNearby)
|
||||
@@ -78,12 +85,14 @@ object Geocache {
|
||||
else
|
||||
(prev?.sinceMs ?: 0L)
|
||||
|
||||
cache[key] = Entry(
|
||||
timeMs = now,
|
||||
items = firstItems,
|
||||
etag = first.etag ?: prev?.etag,
|
||||
sinceMs = firstSince
|
||||
)
|
||||
cacheMutex.withLock {
|
||||
cache[key] = Entry(
|
||||
timeMs = now,
|
||||
items = firstItems,
|
||||
etag = first.etag ?: prev?.etag,
|
||||
sinceMs = firstSince
|
||||
)
|
||||
}
|
||||
|
||||
// 3) Om listan är tom: gör EN omfråga utan cache/since (force refresh)
|
||||
if (firstItems.isEmpty()) {
|
||||
@@ -105,12 +114,14 @@ object Geocache {
|
||||
items.maxOfOrNull { it.c } ?: firstSince
|
||||
else firstSince
|
||||
|
||||
cache[key] = Entry(
|
||||
timeMs = now,
|
||||
items = items,
|
||||
etag = fresh.etag ?: first.etag ?: prev?.etag,
|
||||
sinceMs = since
|
||||
)
|
||||
cacheMutex.withLock {
|
||||
cache[key] = Entry(
|
||||
timeMs = now,
|
||||
items = items,
|
||||
etag = fresh.etag ?: first.etag ?: prev?.etag,
|
||||
sinceMs = since
|
||||
)
|
||||
}
|
||||
|
||||
return@withContext items
|
||||
}
|
||||
@@ -135,7 +146,7 @@ object Geocache {
|
||||
limit = 200
|
||||
)
|
||||
} catch (_: Throwable) {
|
||||
KLog.d { "nearby.php exception → code=599 lat=$lat lon=$lon r=$radiusMeters since=$sinceMs"}
|
||||
KLog.d { "nearby.php exception → code=599 lat=$lat lon=$lon r=$radiusMeters since=$sinceMs" }
|
||||
NearbyResult(code = 599, items = emptyList(), etag = etag)
|
||||
}
|
||||
|
||||
@@ -143,12 +154,11 @@ object Geocache {
|
||||
private fun roundCoord(v: Double): Double = ((v * 1e6).roundToInt() / 1e6)
|
||||
|
||||
// Bygg en nyckel av "ruta" (0.001 grad) + radius bucket (avrundad till närmaste 50 m)
|
||||
// Heltalsbaserad (milligrader) för att undvika String.format (JVM-only).
|
||||
private fun keyFor(lat: Double, lon: Double, radiusMeters: Int): String {
|
||||
val cellLat = floor(lat * 1000.0) / 1000.0
|
||||
val cellLon = floor(lon * 1000.0) / 1000.0
|
||||
val cellLatMilli = floor(lat * 1000.0).toInt()
|
||||
val cellLonMilli = floor(lon * 1000.0).toInt()
|
||||
val r = ((radiusMeters + 25) / 50) * 50 // 0..2000 i steg om 50
|
||||
return "${cellLat.format3()},${cellLon.format3()}|r=$r"
|
||||
return "$cellLatMilli,$cellLonMilli|r=$r"
|
||||
}
|
||||
|
||||
private fun Double.format3(): String = String.format("%.3f", this)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package app.klottr.net
|
||||
import android.os.Build
|
||||
import app.klottr.BuildConfig
|
||||
|
||||
// TODO: OH: Denna verkar ej använd idag. Men om den behövs, lägg i shared som expect med actuals för ios/android
|
||||
object NetHeaders {
|
||||
val userAgent: String by lazy {
|
||||
val os = Build.VERSION.RELEASE ?: "?"
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
package app.klottr.net
|
||||
|
||||
/**
|
||||
* Enkel facade för iOS/Swift (och ev. annan plattform) att anropa delad logik.
|
||||
* Notera: Inga hemligheter ligger här. iOS-appen skickar in nycklar/owners som parametrar.
|
||||
*/
|
||||
class SharedFacade {
|
||||
|
||||
// --- Wikipedia ---
|
||||
suspend fun wikipediaNearby(lat: Double, lon: Double, radiusMeters: Int): List<WikipediaPage> =
|
||||
WikipediaShared.getNearby(lat, lon, radiusMeters)
|
||||
|
||||
suspend fun wikipediaExtract(pageId: Long): WikipediaDetail =
|
||||
WikipediaShared.getExtract(pageId)
|
||||
|
||||
// --- Fornsök ---
|
||||
suspend fun fornsokNearby(lat: Double, lon: Double, radiusMeters: Int): List<FornsokItem> =
|
||||
FornsokShared.getNearby(lat, lon, radiusMeters)
|
||||
|
||||
// --- DigitaltMuseum ---
|
||||
suspend fun digitaltMuseumNearby(
|
||||
apiKey: String,
|
||||
ownersCsv: String?,
|
||||
lat: Double,
|
||||
lon: Double,
|
||||
radiusMeters: Int
|
||||
): List<DigitaltMuseumItem> {
|
||||
val owners = ownersCsv
|
||||
?.split(',', ';', ' ')
|
||||
?.map { it.trim() }
|
||||
?.filter { it.isNotEmpty() }
|
||||
return DigitaltMuseumShared.getNearby(
|
||||
apiKey = apiKey,
|
||||
owners = owners,
|
||||
lat = lat,
|
||||
lon = lon,
|
||||
radiusMeters = radiusMeters
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package app.klottr.net
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.json.JSONObject
|
||||
import java.io.BufferedInputStream
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
// Publik och åtkomlig från dialog-skalet
|
||||
suspend fun fetchWikiThumbBitmap(pageId: Long): Bitmap? = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val api = "https://sv.wikipedia.org/w/api.php?action=query&prop=pageimages&format=json&pithumbsize=400&pageids=$pageId"
|
||||
val conn = (URL(api).openConnection() as HttpURLConnection).apply {
|
||||
connectTimeout = 7000
|
||||
readTimeout = 7000
|
||||
}
|
||||
val json = conn.inputStream.use { ins ->
|
||||
BufferedInputStream(ins).readBytes().toString(Charsets.UTF_8)
|
||||
}
|
||||
val pages = JSONObject(json).getJSONObject("query").getJSONObject("pages")
|
||||
val key = pages.keys().asSequence().firstOrNull() ?: return@withContext null
|
||||
val page = pages.getJSONObject(key)
|
||||
if (!page.has("thumbnail")) return@withContext null
|
||||
val src = page.getJSONObject("thumbnail").getString("source")
|
||||
URL(src).openStream().use { BitmapFactory.decodeStream(it) }
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package app.klottr.net
|
||||
|
||||
/**
|
||||
* Android-adapter som behåller befintligt API men delegerar till delad KMP-klient.
|
||||
* (Stegvis migrering: inga andra anrop behöver ändras.)
|
||||
*/
|
||||
object Wikipedia {
|
||||
|
||||
suspend fun getNearby(lat: Double, lon: Double, radiusMeters: Int): List<WikipediaPage> =
|
||||
WikipediaShared.getNearby(lat, lon, radiusMeters)
|
||||
|
||||
suspend fun getExtract(pageId: Long): WikipediaDetail =
|
||||
WikipediaShared.getExtract(pageId)
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
package app.klottr.ui
|
||||
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.gestures.detectTransformGestures
|
||||
@@ -16,6 +14,8 @@ import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
@@ -36,29 +36,28 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.clipToBounds
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.core.content.pm.PackageInfoCompat
|
||||
import app.klottr.BuildConfig // BuildConfig ligger också i appens paket
|
||||
import app.klottr.R // R ligger i appens paket (applicationId)
|
||||
import app.klottr.nearby.FoundOpenAction
|
||||
import app.klottr.nearby.NearbyEntryShared
|
||||
import app.klottr.net.DigitaltMuseumItem
|
||||
import app.klottr.net.FornsokItem
|
||||
import coil3.PlatformContext
|
||||
import coil3.compose.AsyncImage
|
||||
import coil3.compose.LocalPlatformContext
|
||||
import coil3.request.ImageRequest
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.IO
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
|
||||
/* ---------- Närliggande-dialog (inkl. “Söker …”) ---------- */
|
||||
/* ---------- Nearby (shared) ---------- */
|
||||
|
||||
@Composable
|
||||
fun NearbyDialog(
|
||||
@@ -66,47 +65,58 @@ fun NearbyDialog(
|
||||
error: String?,
|
||||
lat: Double?,
|
||||
lon: Double?,
|
||||
entries: List<NearbyEntryShared>, // Färdigbyggda rader
|
||||
entries: List<NearbyEntryShared>,
|
||||
dm: List<DigitaltMuseumItem>,
|
||||
forn: List<FornsokItem>,
|
||||
onOpenAction: (FoundOpenAction) -> Unit, // Enhetlig callback
|
||||
onClose: () -> Unit
|
||||
onOpenAction: (FoundOpenAction) -> Unit,
|
||||
onClose: () -> Unit,
|
||||
/** Optional max content height; if null, content becomes scrollable. */
|
||||
maxHeight: Dp? = null
|
||||
) {
|
||||
val ctx = LocalContext.current
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = onClose,
|
||||
title = { Text("Närliggande") },
|
||||
text = {
|
||||
val hasLocation = (lat != null && lon != null)
|
||||
val cfg = LocalConfiguration.current
|
||||
val maxDialogHeight = (cfg.screenHeightDp * 0.8f).dp
|
||||
|
||||
NearbyDialogContent(maxHeight = maxDialogHeight) {
|
||||
NearbyContent(
|
||||
loading = loading,
|
||||
error = error,
|
||||
hasLocation = hasLocation,
|
||||
entries = if (hasLocation) entries else emptyList(),
|
||||
dm = dm,
|
||||
forn = forn,
|
||||
onOpenAction = onOpenAction,
|
||||
rowTextStyle = MaterialTheme.typography.bodyMedium.copy(
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
val scroll = rememberScrollState()
|
||||
val container = @Composable { inner: @Composable () -> Unit ->
|
||||
if (maxHeight != null) {
|
||||
Box(Modifier.widthIn(min = 280.dp).height(maxHeight)) {
|
||||
Column(Modifier.fillMaxSize().verticalScroll(scroll)) { inner() }
|
||||
}
|
||||
} else {
|
||||
Column(Modifier.widthIn(min = 280.dp).verticalScroll(scroll)) { inner() }
|
||||
}
|
||||
}
|
||||
//TODO: MaxHeight should be calculated as it was in the original
|
||||
NearbyDialogContent(maxHeight = 580.dp) {
|
||||
container {
|
||||
NearbyContent(
|
||||
loading = loading,
|
||||
error = error,
|
||||
hasLocation = hasLocation,
|
||||
entries = if (hasLocation) entries else emptyList(),
|
||||
dm = dm,
|
||||
forn = forn,
|
||||
onOpenAction = onOpenAction,
|
||||
rowTextStyle = MaterialTheme.typography.bodyMedium.copy(
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { Button(onClick = onClose) { Text("Stäng") } }
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------- Username (shared) ---------- */
|
||||
|
||||
@Composable
|
||||
fun UsernameDialog(
|
||||
onSaved: (String) -> Unit,
|
||||
onLogout: () -> Unit
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
var input by remember { mutableStateOf("") }
|
||||
@@ -216,27 +226,18 @@ fun UsernameDialog(
|
||||
else ->
|
||||
MaterialTheme.typography.bodySmall.copy(color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
},
|
||||
cursorColor = MaterialTheme.colorScheme.primary // Ny: tydlig markör i både ljust/mörkt läge
|
||||
cursorColor = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
// Ingen Avbryt-knapp – blockerat tills sparat
|
||||
Button(
|
||||
onClick = {
|
||||
onLogout()
|
||||
}
|
||||
) {
|
||||
Text("Logga ut")
|
||||
}
|
||||
Button(onClick = onLogout) { Text("Logga ut") }
|
||||
Spacer(Modifier.weight(1f))
|
||||
Button(
|
||||
onClick = {
|
||||
if (saving) return@Button
|
||||
// Sista lokala kollen
|
||||
if (!validateLocal(input)) return@Button
|
||||
if (!okRemote) return@Button
|
||||
saving = true
|
||||
// POST username_set.php (kör i coroutine istället för LaunchedEffect)
|
||||
val disp = app.klottr.net.usernameDisplayClean(input)
|
||||
scope.launch {
|
||||
try {
|
||||
@@ -267,32 +268,17 @@ fun UsernameDialog(
|
||||
Text("Spara")
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- About (shared, platform-fed) ---------- */
|
||||
|
||||
@Composable
|
||||
fun AboutDialog(onDismiss: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val pInfo = remember {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
context.packageManager.getPackageInfo(
|
||||
context.packageName,
|
||||
PackageManager.PackageInfoFlags.of(0)
|
||||
)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
context.packageManager.getPackageInfo(context.packageName, 0)
|
||||
}
|
||||
}
|
||||
val versionCode = remember(pInfo) { PackageInfoCompat.getLongVersionCode(pInfo) }
|
||||
val configuration = LocalConfiguration.current
|
||||
val dialogWidth = (configuration.screenWidthDp.dp * 0.9f) // 90 % av skärmen
|
||||
|
||||
val info = remember { appAboutInfo() } // platform provides
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
@@ -301,22 +287,18 @@ fun AboutDialog(onDismiss: () -> Unit) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.widthIn(max = dialogWidth)
|
||||
.widthIn(max = 520.dp)
|
||||
) {
|
||||
KlottrAboutContent(
|
||||
header = {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.klottr_logo_v2_line),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.height(48.dp)
|
||||
)
|
||||
KlottrLogo(modifier = Modifier.height(48.dp))
|
||||
},
|
||||
lines = listOf(
|
||||
"Version ${BuildConfig.VERSION_NAME} (${BuildConfig.BUILD_TYPE}) • build $versionCode",
|
||||
"Byggd ${BuildConfig.BUILD_TIME_UTC}",
|
||||
"Utvecklad av Fabian Norlin.",
|
||||
"IOS-ansvarig: Olof Hedman.",
|
||||
"Mejlkontakt: utv@ointressant.se"
|
||||
"Version ${info.versionName} (${info.buildType}) • build ${info.buildNumber}",
|
||||
"Byggd ${info.buildTimeUtc}",
|
||||
"Utvecklad av ${info.devBy}.",
|
||||
"IOS-ansvarig: ${info.iosLead}.",
|
||||
"Mejlkontakt: ${info.contactEmail}"
|
||||
),
|
||||
lineStyle = MaterialTheme.typography.bodyMedium.copy(
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
@@ -328,28 +310,32 @@ fun AboutDialog(onDismiss: () -> Unit) {
|
||||
)
|
||||
}
|
||||
|
||||
// Ny: enkel helskärms bildvisare med pinch-zoom/pan
|
||||
/* ---------- Image viewer (shared, byte[] + Coil KMP, pinch/zoom) ---------- */
|
||||
|
||||
@Composable
|
||||
fun ImageViewerDialog(
|
||||
bitmap: android.graphics.Bitmap,
|
||||
bytes: ByteArray,
|
||||
mimeType: String? = null,
|
||||
onClose: () -> Unit
|
||||
) {
|
||||
androidx.compose.ui.window.Dialog(
|
||||
Dialog(
|
||||
onDismissRequest = onClose,
|
||||
properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false)
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false)
|
||||
) {
|
||||
androidx.compose.foundation.layout.Box(
|
||||
modifier = androidx.compose.ui.Modifier
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.background(androidx.compose.ui.graphics.Color.Black)
|
||||
.background(Color.Black)
|
||||
) {
|
||||
var scale by remember { mutableStateOf(1f) }
|
||||
var offset by remember { mutableStateOf(Offset.Zero) }
|
||||
|
||||
androidx.compose.foundation.Image(
|
||||
bitmap = bitmap.asImageBitmap(),
|
||||
AsyncImage(
|
||||
model = ImageRequest.Builder(LocalPlatformContext.current)
|
||||
.data(bytes)
|
||||
.build(),
|
||||
contentDescription = null,
|
||||
modifier = androidx.compose.ui.Modifier
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.clipToBounds()
|
||||
.pointerInput(Unit) {
|
||||
@@ -371,8 +357,8 @@ fun ImageViewerDialog(
|
||||
)
|
||||
)
|
||||
|
||||
androidx.compose.foundation.layout.Box(
|
||||
modifier = androidx.compose.ui.Modifier
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopEnd)
|
||||
.padding(12.dp)
|
||||
) {
|
||||
|
||||
@@ -4,7 +4,6 @@ import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.graphics.Bitmap
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import androidx.compose.foundation.layout.Box
|
||||
@@ -23,7 +22,6 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue // Gör 'by remember { ... }' skrivbart
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
@@ -33,7 +31,6 @@ import app.klottr.net.DigitaltMuseumItem
|
||||
import app.klottr.net.FornsokItem
|
||||
import app.klottr.net.Wikipedia
|
||||
import app.klottr.util.SettingsStore
|
||||
import app.klottr.net.fetchWikiThumbBitmap // Använd publika funktionen
|
||||
import app.klottr.util.formatCoords
|
||||
import app.klottr.util.formatDistance
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -56,7 +53,6 @@ fun WikiArticleDialog(
|
||||
var loading by remember { mutableStateOf(true) }
|
||||
var title by remember { mutableStateOf("") }
|
||||
var extract by remember { mutableStateOf("") }
|
||||
var thumb: Bitmap? by remember { mutableStateOf(null) }
|
||||
|
||||
// Avståndstext som uppdateras när platsen tickar
|
||||
var wikiDistanceText by remember { mutableStateOf("-") }
|
||||
@@ -93,7 +89,6 @@ fun WikiArticleDialog(
|
||||
val detail = withContext(Dispatchers.IO) { Wikipedia.getExtract(pageId) }
|
||||
title = detail.title
|
||||
extract = detail.extract
|
||||
thumb = fetchWikiThumbBitmap(pageId)
|
||||
loading = false
|
||||
}
|
||||
|
||||
@@ -120,7 +115,7 @@ fun WikiArticleDialog(
|
||||
extractText = extract,
|
||||
distanceText = wikiDistanceText, // Oför: redan beräknad
|
||||
coordText = if (showCoords && lat != null && lon != null) formatCoords(lat, lon) else null,
|
||||
thumb = thumb?.asImageBitmap(),
|
||||
pageId = pageId,
|
||||
titleStyle = MaterialTheme.typography.titleLarge.copy(
|
||||
color = MaterialTheme.colorScheme.onSurface // Ny: följer dag/natt
|
||||
),
|
||||
@@ -273,9 +268,7 @@ fun DmDialog(
|
||||
val dialogWidth = (configuration.screenWidthDp.dp * 0.98f)
|
||||
var detailText by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
|
||||
var loading by remember { mutableStateOf(false) }
|
||||
var thumb: Bitmap? by remember { mutableStateOf(null) }
|
||||
|
||||
// Avstånd som tickar
|
||||
var dmDistanceText by remember { mutableStateOf("-") }
|
||||
@@ -320,14 +313,6 @@ fun DmDialog(
|
||||
|
||||
// Hämta miniatyr om vi har bild-URL
|
||||
LaunchedEffect(item.id) {
|
||||
// Bild (om finns)
|
||||
if (!item.url.isNullOrBlank()) {
|
||||
loading = true
|
||||
thumb = withContext(Dispatchers.IO) { app.klottr.net.fetchBitmapFromUrl(item.url!!) } // Fullt kvalificerat namn
|
||||
loading = false
|
||||
} else {
|
||||
thumb = null
|
||||
}
|
||||
// Text (om uniqueId finns)
|
||||
detailText = withContext(Dispatchers.IO) {
|
||||
app.klottr.net.DigitaltMuseum.getDetailText(
|
||||
@@ -402,7 +387,7 @@ fun DmDialog(
|
||||
bodyText = listOfNotNull(firstLine, restText).joinToString("\n\n"),
|
||||
distanceText = dmDistanceText,
|
||||
coordText = if (showCoords) formatCoords(item.lat, item.lon) else null,
|
||||
image = thumb?.asImageBitmap(),
|
||||
imageUrl = item.url,
|
||||
titleStyle = MaterialTheme.typography.titleLarge.copy(
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
),
|
||||
|
||||
Reference in New Issue
Block a user