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:
@@ -120,6 +120,16 @@ dependencies {
|
||||
|
||||
// WorkManager (valfritt, ej nödvändigt här)
|
||||
implementation("androidx.work:work-runtime-ktx:2.9.1")
|
||||
|
||||
|
||||
// Dessa kommer så småningom bara behövas i shared, men lägger dem här för att förenkla portning
|
||||
// Coil 3 (KMP) — image loading + caching for Compose Multiplatform
|
||||
implementation("io.coil-kt.coil3:coil-compose:3.3.0")
|
||||
// Use Ktor-based multiplatform networking backend for Coil
|
||||
implementation("io.coil-kt.coil3:coil-network-ktor3:3.3.0")
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
androidComponents {
|
||||
|
||||
@@ -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)
|
||||
|
||||
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
|
||||
|
||||
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,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,23 +65,32 @@ 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) {
|
||||
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,
|
||||
@@ -96,17 +104,19 @@ fun NearbyDialog(
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
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
|
||||
),
|
||||
|
||||
@@ -8,4 +8,5 @@ plugins {
|
||||
alias(libs.plugins.android.lint) apply false
|
||||
alias(libs.plugins.kotlin.serialization) apply false
|
||||
alias(libs.plugins.ksp) apply false
|
||||
alias(libs.plugins.compose) apply false
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
[versions]
|
||||
agp = "8.12.3"
|
||||
kotlin = "2.2.10"
|
||||
compose = "1.9.0"
|
||||
coreKtx = "1.16.0"
|
||||
junit = "4.13.2"
|
||||
junitVersion = "1.3.0"
|
||||
@@ -57,4 +58,5 @@ android-kotlin-multiplatform-library = { id = "com.android.kotlin.multiplatform.
|
||||
android-lint = { id = "com.android.lint", version.ref = "agp" }
|
||||
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
|
||||
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
|
||||
compose = { id = "org.jetbrains.compose", version.ref = "compose" }
|
||||
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import org.jetbrains.kotlin.gradle.plugin.mpp.apple.XCFramework
|
||||
import java.util.Properties
|
||||
import com.codingfeline.buildkonfig.compiler.FieldSpec.Type.STRING
|
||||
import com.codingfeline.buildkonfig.compiler.FieldSpec.Type.BOOLEAN
|
||||
import java.time.Instant
|
||||
|
||||
plugins {
|
||||
alias(libs.plugins.android.kotlin.multiplatform.library)
|
||||
@@ -14,7 +18,8 @@ plugins {
|
||||
// JetBrains Compose Multiplatform för UI i :shared/commonMain.
|
||||
// Viktigt: detta är *inte* AndroidX Compose BOM. Vi använder compose.*-aliasen
|
||||
// (org.jetbrains.compose) vilket gör att :shared förblir plattformsneutral.
|
||||
id("org.jetbrains.compose") version "1.8.2"
|
||||
id("org.jetbrains.compose") version "1.9.0"
|
||||
id("com.codingfeline.buildkonfig") version "0.17.1"
|
||||
}
|
||||
|
||||
kotlin {
|
||||
@@ -98,6 +103,14 @@ kotlin {
|
||||
implementation(compose.material3)
|
||||
// Material Icons (Icons.Filled.*, Icons.Outlined.*)
|
||||
implementation(compose.materialIconsExtended)
|
||||
implementation(compose.components.resources)
|
||||
|
||||
// Coil 3 (KMP) — image loading + caching for Compose Multiplatform
|
||||
implementation("io.coil-kt.coil3:coil-compose:3.3.0")
|
||||
// Use Ktor-based multiplatform networking backend for Coil
|
||||
implementation("io.coil-kt.coil3:coil-network-ktor3:3.3.0")
|
||||
|
||||
|
||||
|
||||
// för Compose i :shared (Android-del)
|
||||
// OBS: Dessa AndroidX Compose-rader ska förbli utkommenterade i :shared.
|
||||
@@ -106,6 +119,10 @@ kotlin {
|
||||
//implementation(libs.androidx.ui)
|
||||
//implementation(libs.androidx.material3)
|
||||
}
|
||||
// resources.srcDirs(
|
||||
// "src/commonMain/composeResources",
|
||||
// "src/commonMain/resources"
|
||||
// )
|
||||
}
|
||||
|
||||
commonTest {
|
||||
@@ -146,3 +163,43 @@ kotlin {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// ------------------- BuildKonfig (shared constants) -------------------
|
||||
// Read local.properties (or override via -PKEY=VALUE)
|
||||
val localProps = Properties().apply {
|
||||
val f = rootProject.file("local.properties")
|
||||
if (f.exists()) f.inputStream().use { load(it) }
|
||||
}
|
||||
|
||||
fun prop(name: String): String? =
|
||||
providers.gradleProperty(name).orNull ?: localProps.getProperty(name)
|
||||
|
||||
fun propOr(name: String, default: String) = prop(name) ?: default
|
||||
|
||||
val buildTimeUtc: String = Instant.now().toString()
|
||||
|
||||
// Infer build type from tasks (Debug/Release), but allow override via -PBUILD_TYPE=...
|
||||
val inferredBuildType: String = providers.gradleProperty("BUILD_TYPE").orNull
|
||||
?: if (gradle.startParameter.taskNames.any { it.contains("release", ignoreCase = true) }) "release" else "debug"
|
||||
|
||||
|
||||
buildkonfig {
|
||||
packageName = "app.klottr"
|
||||
|
||||
defaultConfigs {
|
||||
buildConfigField(STRING, "BUILD_TYPE", inferredBuildType )
|
||||
|
||||
buildConfigField(STRING, "APP_NAME", "Klottr")
|
||||
buildConfigField(STRING, "BUILD_TIME_UTC", buildTimeUtc)
|
||||
|
||||
buildConfigField(STRING, "SERVER_API_BASE_URL", propOr("SERVER_API_BASE_URL", ""))
|
||||
buildConfigField(STRING, "SERVER_API_KEY", propOr("SERVER_API_KEY", ""))
|
||||
buildConfigField(STRING, "WEB_CLIENT_ID", propOr("WEB_CLIENT_ID", ""))
|
||||
|
||||
buildConfigField(STRING, "DM_API_KEY", propOr("DM_API_KEY", ""))
|
||||
buildConfigField(STRING, "DM_OWNERS", propOr("DM_OWNERS", ""))
|
||||
|
||||
buildConfigField(BOOLEAN, "KLLOG_DEBUG", propOr("KLLOG_DEBUG", "false"))
|
||||
buildConfigField(BOOLEAN, "KLLOG_HTTP_DEBUG", propOr("KLLOG_HTTP_DEBUG", "false"))
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package app.klottr.net
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import java.io.BufferedInputStream
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
// Enkel (blockerande) hämtning av bitmap från URL. Kör detta på Dispatchers.IO i anroparen.
|
||||
suspend fun fetchBitmapFromUrl(url: String): Bitmap? {
|
||||
return try {
|
||||
val conn = (URL(url).openConnection() as HttpURLConnection).apply {
|
||||
connectTimeout = 7000
|
||||
readTimeout = 7000
|
||||
}
|
||||
conn.inputStream.use { ins ->
|
||||
BufferedInputStream(ins).use { bis ->
|
||||
BitmapFactory.decodeStream(bis)
|
||||
}
|
||||
}
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package app.klottr.ui
|
||||
|
||||
import android.content.pm.PackageManager
|
||||
import androidx.core.content.pm.PackageInfoCompat
|
||||
import app.klottr.BuildKonfig
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.TimeZone
|
||||
|
||||
// Provide your app context via a singleton or DI.
|
||||
// If you already have LocalPlatformContext.current as Context, you can reuse it here.
|
||||
|
||||
//TODO: OH: Handle this app context instance.
|
||||
//private val appContext get() = app.klottr.App.instance // adjust to your app
|
||||
|
||||
actual fun appAboutInfo(): AboutInfo {
|
||||
// val pm = appContext.packageManager
|
||||
// val pi = pm.getPackageInfo(appContext.packageName, 0)
|
||||
// val versionName = pi.versionName ?: "0.0"
|
||||
// val versionCode = PackageInfoCompat.getLongVersionCode(pi)
|
||||
val versionName = "Fix Me"
|
||||
val versionCode = 0L
|
||||
val buildType = BuildKonfig.BUILD_TYPE
|
||||
val buildTime = try {
|
||||
// If you expose BUILD_TIME_UTC in BuildConfig (recommended), use it directly
|
||||
BuildKonfig.BUILD_TIME_UTC
|
||||
} catch (_: Throwable) {
|
||||
// Fallback: unreadable, leave empty or format current
|
||||
SimpleDateFormat("yyyy-MM-dd HH:mm 'UTC'").apply {
|
||||
timeZone = TimeZone.getTimeZone("UTC")
|
||||
}.format(System.currentTimeMillis())
|
||||
}
|
||||
return AboutInfo(
|
||||
versionName = versionName,
|
||||
buildType = buildType,
|
||||
buildNumber = versionCode,
|
||||
buildTimeUtc = buildTime,
|
||||
devBy = "Fabian Norlin",
|
||||
iosLead = "Olof Hedman",
|
||||
contactEmail = "utv@ointressant.se"
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,10 @@
|
||||
package app.klottr.net
|
||||
|
||||
import app.klottr.BuildKonfig
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.IO
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
data class DigitaltMuseumItem(
|
||||
val id: String,
|
||||
val title: String,
|
||||
@@ -10,3 +15,55 @@ data class DigitaltMuseumItem(
|
||||
val webUrl: String? = null, // publika objektsidan
|
||||
val owner: String? = null // identifier.owner
|
||||
)
|
||||
|
||||
/**
|
||||
* 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 = BuildKonfig.DM_API_KEY.orEmpty().trim()
|
||||
if (apiKey.isBlank()) return@withContext emptyList()
|
||||
|
||||
val owners = BuildKonfig.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 = BuildKonfig.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 = BuildKonfig.DM_API_KEY.orEmpty().trim()
|
||||
if (apiKey.isBlank()) return@withContext null
|
||||
DigitaltMuseumShared.getDetailText(
|
||||
apiKey = apiKey,
|
||||
uniqueId = uniqueId,
|
||||
owner = owner,
|
||||
identifierId = identifierId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
92
shared/src/commonMain/kotlin/app/klottr/net/WikiThumb.kt
Normal file
92
shared/src/commonMain/kotlin/app/klottr/net/WikiThumb.kt
Normal file
@@ -0,0 +1,92 @@
|
||||
// File: WikiThumb.kt
|
||||
package app.klottr.net
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.ui.Modifier
|
||||
import coil3.Image
|
||||
import coil3.ImageLoader
|
||||
import coil3.PlatformContext
|
||||
import coil3.compose.AsyncImage
|
||||
import coil3.request.ImageRequest
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.request.get
|
||||
import io.ktor.client.statement.bodyAsText
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.IO
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.contentOrNull
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
|
||||
private val json = Json { ignoreUnknownKeys = true }
|
||||
|
||||
/**
|
||||
* Composable WikiThumb directly usable in Compose UI
|
||||
*
|
||||
* Use this in UI code.
|
||||
*/
|
||||
@Composable
|
||||
fun WikiThumb(pageId: Long, modifier: Modifier = Modifier) {
|
||||
val url by produceState<String?>(initialValue = null, pageId) {
|
||||
value = fetchWikiThumbUrl(pageId)
|
||||
}
|
||||
AsyncImage(model = url, contentDescription = null, modifier = modifier)
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the Wikipedia thumbnail URL for a page.
|
||||
* Multiplatform-safe (Ktor + kotlinx.serialization).
|
||||
*
|
||||
* @param pageId Wikipedia page id
|
||||
* @param http Ktor HttpClient (provide per platform)
|
||||
* @param thumbSize Requested thumbnail width in px (Wikipedia scales server-side)
|
||||
* @return Direct URL to the thumbnail, or null if none exists.
|
||||
*/
|
||||
suspend fun fetchWikiThumbUrl(
|
||||
pageId: Long,
|
||||
thumbSize: Int = 400,
|
||||
): String? = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val api =
|
||||
"https://sv.wikipedia.org/w/api.php?action=query&prop=pageimages&format=json&pithumbsize=$thumbSize&pageids=$pageId"
|
||||
val text = WikipediaShared.client.get(api).bodyAsText()
|
||||
val root = json.parseToJsonElement(text).jsonObject
|
||||
val pages = root["query"]?.jsonObject?.get("pages")?.jsonObject ?: return@withContext null
|
||||
val first = pages.values.firstOrNull()?.jsonObject ?: return@withContext null
|
||||
first["thumbnail"]?.jsonObject
|
||||
?.get("source")
|
||||
?.jsonPrimitive
|
||||
?.contentOrNull
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the thumbnail as a multiplatform [coil3.Image] using Coil 3.
|
||||
*
|
||||
* Use this if an coil3.Image is needed, but prefer to use WikiThumb.
|
||||
*
|
||||
* Pass an [ImageLoader] (recommended: keep a singleton in app code)
|
||||
* and a [PlatformContext] (from Compose via LocalPlatformContext or a platform-provided instance).
|
||||
*/
|
||||
suspend fun fetchWikiThumbImage(
|
||||
pageId: Long,
|
||||
imageLoader: ImageLoader,
|
||||
context: PlatformContext,
|
||||
thumbSize: Int = 400,
|
||||
): Image? = withContext(Dispatchers.IO) {
|
||||
val url = fetchWikiThumbUrl(pageId, thumbSize) ?: return@withContext null
|
||||
val request = ImageRequest.Builder(context)
|
||||
.data(url)
|
||||
.build()
|
||||
try {
|
||||
imageLoader.execute(request).image
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ 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.)
|
||||
*/
|
||||
|
||||
// TODO: OH: Denna klass är helt onödig och kan tas bort.
|
||||
object Wikipedia {
|
||||
|
||||
suspend fun getNearby(lat: Double, lon: Double, radiusMeters: Int): List<WikipediaPage> =
|
||||
@@ -24,7 +24,7 @@ import kotlinx.serialization.json.Json
|
||||
object WikipediaShared {
|
||||
|
||||
// En HttpClient per process – återanvänds (lazy).
|
||||
private val client by lazy {
|
||||
val client by lazy {
|
||||
HttpClient(platformEngine()) {
|
||||
// JSON-konfiguration: tolerant och ignorera okända fält
|
||||
install(ContentNegotiation) {
|
||||
|
||||
@@ -10,6 +10,7 @@ import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.foundation.text.BasicText
|
||||
import coil3.compose.AsyncImage
|
||||
|
||||
@Composable
|
||||
fun DmDetailContent(
|
||||
@@ -17,7 +18,7 @@ fun DmDetailContent(
|
||||
bodyText: String?,
|
||||
distanceText: String,
|
||||
coordText: String?, // Förifylld av Android (t.ex. formatCoords)
|
||||
image: ImageBitmap?, // Miniatyr om finns
|
||||
imageUrl: String?, // Miniatyr om finns
|
||||
titleStyle: TextStyle,
|
||||
bodyStyle: TextStyle,
|
||||
captionStyle: TextStyle,
|
||||
@@ -29,8 +30,8 @@ fun DmDetailContent(
|
||||
.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
if (image != null) {
|
||||
Image(bitmap = image, contentDescription = null, modifier = Modifier.fillMaxWidth())
|
||||
if (imageUrl != null) {
|
||||
AsyncImage(model = imageUrl, contentDescription = null, modifier = Modifier.fillMaxWidth())
|
||||
}
|
||||
BasicText(titleText, style = titleStyle)
|
||||
if (!bodyText.isNullOrBlank()) {
|
||||
|
||||
36
shared/src/commonMain/kotlin/app/klottr/ui/Logo.kt
Normal file
36
shared/src/commonMain/kotlin/app/klottr/ui/Logo.kt
Normal file
@@ -0,0 +1,36 @@
|
||||
package app.klottr.ui
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.foundation.Image
|
||||
import org.jetbrains.compose.resources.painterResource
|
||||
//import klottr.shared.generated.resources.Res
|
||||
//import klottr.shared.generated.resources.klottr_logo_v2_line // ← import the symbol too
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Size
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
|
||||
@Composable
|
||||
fun KlottrLogo(modifier: Modifier = Modifier) {
|
||||
// Image(
|
||||
// painter = painterResource(Res.drawable.klottr_logo_v2_line),
|
||||
// contentDescription = null,
|
||||
// modifier = modifier
|
||||
// )
|
||||
|
||||
//TODO: OH: Resource loading currently does not work, just use a pink square for now.
|
||||
Canvas(modifier = modifier) {
|
||||
val side = minOf(size.width, size.height)
|
||||
val topLeft = Offset(
|
||||
x = (size.width - side) / 2f,
|
||||
y = (size.height - side) / 2f
|
||||
)
|
||||
drawRect(
|
||||
color = Color(0xFFFF2D55), // pink
|
||||
topLeft = topLeft,
|
||||
size = Size(side, side)
|
||||
)
|
||||
}
|
||||
}
|
||||
25
shared/src/commonMain/kotlin/app/klottr/ui/PlatformExpect.kt
Normal file
25
shared/src/commonMain/kotlin/app/klottr/ui/PlatformExpect.kt
Normal file
@@ -0,0 +1,25 @@
|
||||
package app.klottr.ui
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
|
||||
// TODO: Samla all platformsintegration på ett och samma ställe.
|
||||
|
||||
/* ----- already introduced earlier ----- */
|
||||
// expect object LocalPlatformContext { val current: Any }
|
||||
// expect fun updateToCurrentLocation(onResult: (Double, Double) -> Unit)
|
||||
// expect interface PlatformIntegration { ... } // unchanged here
|
||||
|
||||
/* ----- new expect surface for About + logo ----- */
|
||||
|
||||
data class AboutInfo(
|
||||
val versionName: String,
|
||||
val buildType: String,
|
||||
val buildNumber: Long,
|
||||
val buildTimeUtc: String,
|
||||
val devBy: String,
|
||||
val iosLead: String,
|
||||
val contactEmail: String
|
||||
)
|
||||
|
||||
/** Platform provides app/build metadata for About dialog. */
|
||||
expect fun appAboutInfo(): AboutInfo
|
||||
@@ -10,6 +10,7 @@ import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.foundation.text.BasicText
|
||||
import app.klottr.net.WikiThumb
|
||||
|
||||
@Composable
|
||||
fun WikiDetailContent(
|
||||
@@ -17,7 +18,7 @@ fun WikiDetailContent(
|
||||
extractText: String,
|
||||
distanceText: String,
|
||||
coordText: String?,
|
||||
thumb: ImageBitmap?,
|
||||
pageId: Long?,
|
||||
titleStyle: TextStyle,
|
||||
bodyStyle: TextStyle,
|
||||
captionStyle: TextStyle,
|
||||
@@ -29,8 +30,8 @@ fun WikiDetailContent(
|
||||
.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
if (thumb != null) {
|
||||
Image(bitmap = thumb, contentDescription = null, modifier = Modifier.fillMaxWidth())
|
||||
if (pageId != null) {
|
||||
WikiThumb(pageId = pageId, modifier = Modifier.fillMaxWidth())
|
||||
}
|
||||
BasicText(if (titleText.isNotBlank()) titleText else "Wikipedia", style = titleStyle)
|
||||
if (extractText.isNotBlank()) {
|
||||
|
||||
Reference in New Issue
Block a user