Merge branch 'main' into ios-google-signin

This commit is contained in:
Olof Hedman
2025-09-20 16:02:19 +02:00
33 changed files with 1971 additions and 1458 deletions

View File

@@ -98,7 +98,7 @@ class LocationService : Service() {
LastLocationStore.lastKnownLocation = L
// Uppdatera away-flaggor för den position du ska scanna mot
FoundStore.updateAwayFlags(this@LocationService, L.latitude, L.longitude)
FoundStore.updateAwayFlags(L.latitude, L.longitude)
// 1) Tala om att data (ev. away) kan ha ändrats
sendBroadcast(Intent(ACTION_FOUND_UPDATED))
@@ -142,7 +142,7 @@ class LocationService : Service() {
scope.launch {
// Uppdatera away-flaggor för ALLA sparade fynd utifrån aktuell position
FoundStore.updateAwayFlags(this@LocationService, loc.latitude, loc.longitude)
FoundStore.updateAwayFlags(loc.latitude, loc.longitude)
// (UI lyssnar på SharedPreferences, men vi pingar ändå för säkerhets skull)
sendBroadcast(Intent(ACTION_FOUND_UPDATED))
@@ -158,7 +158,7 @@ class LocationService : Service() {
LastLocationStore.lastKnownLocation = refined
sendBroadcast(Intent(ACTION_LOCATION_TICK))
FoundStore.updateAwayFlags(this@LocationService, refined.latitude, refined.longitude)
FoundStore.updateAwayFlags(refined.latitude, refined.longitude)
sendBroadcast(Intent(ACTION_FOUND_UPDATED))
checkMatches(refined.latitude, refined.longitude)
}
@@ -187,7 +187,7 @@ class LocationService : Service() {
private suspend fun checkMatches(lat: Double, lon: Double) {
// Just nu kör vi bara klotter här (20 m). Wikipedia/DigitaltMuseum/Fornsök scannas i UI vid behov.
val showKlotter = SettingsStore.getShowKlotter(this)
val showKlotter = SettingsStore.getShowKlotter()
if (showKlotter) {
val nearby: List<NoteDTO> = try {
Geocache.getNearby(lat, lon, radiusMeters = 120, ttlMs = 0L)
@@ -205,7 +205,7 @@ class LocationService : Service() {
pt = LatLng(n.a, n.o),
distanceM = d,
insideRadiusM = 20,
onlyNew = SettingsStore.getOnlyNewHits(this)
onlyNew = SettingsStore.getOnlyNewHits()
)
}
}
@@ -235,11 +235,11 @@ class LocationService : Service() {
}
// Lagrings-baserad re-arm: om FoundStore flaggat "away=true" och vi nu är inne i radien
val wasAwayStore = FoundStore.isAway(this, layer, id)
val wasAwayStore = FoundStore.isAway(layer, id)
if (distanceM <= insideRadiusM) {
val wasNotifiedThisSession = notifiedWhileInside[k] == true
val alreadyFound = FoundStore.isFound(this, layer, id)
val alreadyFound = FoundStore.isFound(layer, id)
val now = System.currentTimeMillis()
// Markera i FoundStore:
@@ -248,7 +248,7 @@ class LocationService : Service() {
// - (behåller session-reentry för bakåtkompabilitet)
val shouldMark = !alreadyFound || wasAwayStore || (!onlyNew && reenteredSession)
if (shouldMark) {
val marked = FoundStore.markFound(this, layer, id, label, pt.latitude, pt.longitude, now)
val marked = FoundStore.markFound(layer, id, label, pt.latitude, pt.longitude, now)
if (marked) sendBroadcast(Intent(ACTION_FOUND_UPDATED))
}

File diff suppressed because it is too large Load Diff

View File

@@ -68,7 +68,7 @@ class OutboxWorker(
val imgId: Long? = if (p.imagePath != null && p.imageMime != null) {
val f = File(p.imagePath)
if (f.exists()) {
uploadImageFromFile(applicationContext, f, p.imageMime, p.lat, p.lon)
uploadImageFromFile(f, p.imageMime, p.lat, p.lon)
} else null
} else null
@@ -119,7 +119,6 @@ class OutboxWorker(
// Markera som hittad i FoundStore
FoundStore.markFound(
ctx,
FoundStore.LAYER_KLOTTER,
match.i.toString(),
label = label,

View File

@@ -3,8 +3,8 @@ package app.klottr.net
import android.content.Context
import android.net.Uri
import app.klottr.BuildConfig
import app.klottr.net.KlottrApiShared
import app.klottr.util.Auth
import app.klottr.util.KLog
import java.io.File
/**
@@ -108,12 +108,12 @@ suspend fun uploadImageFromUri(
lon = lon
)
} catch (t: Throwable) {
app.klottr.util.AppLog.d { "uploadImage exception: ${t.message}" }
KLog.d { "uploadImage exception: ${t.message}" }
Api.lastUploadError = "Uppladdningen misslyckades."
return null
}
app.klottr.util.AppLog.d { "uploadImage code=200 ok=${res.ok} imageId=${res.imageId} width=${res.width} height=${res.height}" }
KLog.d { "uploadImage code=200 ok=${res.ok} imageId=${res.imageId} width=${res.width} height=${res.height}" }
if (!res.ok || res.imageId == null) {
Api.lastUploadError = res.errorMessage ?: "Uppladdningen misslyckades."
@@ -132,7 +132,6 @@ suspend fun uploadImageFromUri(
* Samma som ovan men startar från File i stället för Uri.
*/
suspend fun uploadImageFromFile(
context: Context,
file: File,
mimeHint: String?,
lat: Double,
@@ -166,12 +165,12 @@ suspend fun uploadImageFromFile(
lon = lon
)
} catch (t: Throwable) {
app.klottr.util.AppLog.d { "uploadImage(file) exception: ${t.message}" }
KLog.d { "uploadImage(file) exception: ${t.message}" }
Api.lastUploadError = "Uppladdningen misslyckades."
return null
}
app.klottr.util.AppLog.d { "uploadImage(file) ok=${res.ok} imageId=${res.imageId}" }
KLog.d { "uploadImage(file) ok=${res.ok} imageId=${res.imageId}" }
if (!res.ok || res.imageId == null) {
Api.lastUploadError = res.errorMessage ?: "Uppladdningen misslyckades."
@@ -262,12 +261,12 @@ suspend fun fetchNoteDetail(id: Long, lat: Double, lon: Double): NoteDetailShare
lon = lon
)
} catch (t: Throwable) {
app.klottr.util.AppLog.d { "get_note exception: ${t.message}" }
KLog.d { "get_note exception: ${t.message}" }
null
}
if (sh == null) {
app.klottr.util.AppLog.d { "get_note FAIL (null)" }
KLog.d { "get_note FAIL (null)" }
return null
}
@@ -301,7 +300,7 @@ suspend fun checkUsernameRemote(input: String): UsernameCheckResp? {
username = disp
)
} catch (t: Throwable) {
app.klottr.util.AppLog.d { "username_check: EXC ${t.message}" }
KLog.d { "username_check: EXC ${t.message}" }
null
}
return sh
@@ -344,7 +343,7 @@ suspend fun fetchImageStreamPost(
lon = lon
)
} catch (t: Throwable) {
app.klottr.util.AppLog.d { "get_image exception: ${t.message}" }
KLog.d { "get_image exception: ${t.message}" }
null
}
}

View File

@@ -1,6 +1,6 @@
package app.klottr.net
import android.util.Log
import app.klottr.util.KLog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONArray
@@ -35,7 +35,7 @@ object Fornsok {
suspend fun getByEntityUri(entityUri: String): FornsokItem? = withContext(Dispatchers.IO) {
val cql = """entityUri="$entityUri""""
val url = buildUrl(cql, startRecord = 1, usePresentation = true)
app.klottr.util.AppLog.d(TAG) { "Detalj: GET $url"}
KLog.d(TAG) { "Detalj: GET $url"}
val root = httpGetJson(url) ?: return@withContext null
val result = root.optJSONObject("result") ?: return@withContext null
@@ -121,7 +121,7 @@ object Fornsok {
return try {
val code = conn.responseCode
val ctype = conn.getHeaderField("Content-Type")
app.klottr.util.AppLog.d(TAG) { "HTTP $code Content-Type=$ctype"}
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
@@ -141,13 +141,13 @@ object Fornsok {
while (page <= maxPages) {
val url = buildUrl(cql, start, usePresentation)
app.klottr.util.AppLog.d(TAG) { "Sida $page: GET $url"}
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)
app.klottr.util.AppLog.d(TAG) { "totalHits (server): $totalHitsFromServer"}
KLog.d(TAG) { "totalHits (server): $totalHitsFromServer"}
}
val recordsNode = result.opt("records")
@@ -164,7 +164,7 @@ object Fornsok {
}
if (recordArr.length() == 0) {
app.klottr.util.AppLog.d(TAG) { "Ingen records.record på denna sida."}
KLog.d(TAG) { "Ingen records.record på denna sida."}
break
}
@@ -242,7 +242,7 @@ object Fornsok {
added++
}
}
app.klottr.util.AppLog.d(TAG) {"Sida: genomgång visited=$visited, nonKmrFmi=$nonKmrFmi, noCoords=$noCoords, tillagda=$added, ack=${out.size}" }
KLog.d(TAG) {"Sida: genomgång visited=$visited, nonKmrFmi=$nonKmrFmi, noCoords=$noCoords, tillagda=$added, ack=${out.size}" }
// Fler sidor?
if (totalHitsFromServer > 0) {

View File

@@ -1,5 +1,6 @@
package app.klottr.net
import app.klottr.util.KLog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.concurrent.ConcurrentHashMap
@@ -58,7 +59,7 @@ object Geocache {
etag = prev?.etag
)
if (first.code !in listOf(200, 304)) {
app.klottr.util.AppLog.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)
@@ -134,7 +135,7 @@ object Geocache {
limit = 200
)
} catch (_: Throwable) {
app.klottr.util.AppLog.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)
}

View File

@@ -0,0 +1,32 @@
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
}
}

View File

@@ -0,0 +1,383 @@
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
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
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.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
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.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.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 kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/* ---------- Närliggande-dialog (inkl. “Söker …”) ---------- */
@Composable
fun NearbyDialog(
loading: Boolean,
error: String?,
lat: Double?,
lon: Double?,
entries: List<NearbyEntryShared>, // Färdigbyggda rader
dm: List<DigitaltMuseumItem>,
forn: List<FornsokItem>,
onOpenAction: (FoundOpenAction) -> Unit, // Enhetlig callback
onClose: () -> Unit
) {
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
)
)
}
},
confirmButton = { Button(onClick = onClose) { Text("Stäng") } }
)
}
@Composable
fun UsernameDialog(
onSaved: (String) -> Unit,
onLogout: () -> Unit
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
var input by remember { mutableStateOf("") }
var display by remember { mutableStateOf("") }
var localErr by remember { mutableStateOf<String?>(null) }
var remoteErr by remember { mutableStateOf<String?>(null) }
var checking by remember { mutableStateOf(false) }
var saving by remember { mutableStateOf(false) }
var okRemote by remember { mutableStateOf(false) }
// Lokal validering speglar servern
fun validateLocal(s: String): Boolean {
val v = app.klottr.net.usernameLocalValidate(s)
display = v.display
localErr = when (v.status) {
app.klottr.net.UsernameLocalStatus.EMPTY -> "Ange ett användarnamn."
app.klottr.net.UsernameLocalStatus.INVALID_CHARS -> "Endast bokstäver, siffror och mellanslag tillåts."
app.klottr.net.UsernameLocalStatus.TOO_FEW_LETTERS -> "Minst två bokstäver krävs."
app.klottr.net.UsernameLocalStatus.OK -> null
}
return localErr == null
}
// Debouncead server-check när display ändras
LaunchedEffect(display) {
remoteErr = null
okRemote = false
if (display.isBlank()) return@LaunchedEffect
if (!validateLocal(display)) return@LaunchedEffect
checking = true
delay(400) // debounce
val resp = withContext(Dispatchers.IO) { app.klottr.net.checkUsernameRemote(display) }
checking = false
if (resp == null) {
remoteErr = "Kunde inte kontrollera namnet (nätfel). Försök igen."
okRemote = false
} else {
if (resp.ok) {
okRemote = true
remoteErr = null
} else {
okRemote = false
remoteErr = when (resp.reason) {
"taken" -> "Upptaget – prova ett annat."
"reserved" -> "Reserverat – välj något annat."
"invalid" -> "Ogiltigt användarnamn."
"too_few_letters" -> "Minst två bokstäver krävs."
"invalid_chars" -> "Endast bokstäver, siffror, bindestreck och mellanslag tillåts."
"already_set" -> {
// Servern säger “du har redan ett namn” – stäng som lyckat
remoteErr = null
onSaved(display)
return@LaunchedEffect
}
else -> "Ogiltigt användarnamn."
}
}
}
}
Dialog(
onDismissRequest = { /* blockera stängning */ },
properties = DialogProperties(
dismissOnBackPress = false,
dismissOnClickOutside = false,
usePlatformDefaultWidth = false
)
) {
Surface(
modifier = Modifier
.fillMaxWidth(0.92f)
.clip(RoundedCornerShape(16.dp)),
tonalElevation = 6.dp
) {
Column(
modifier = Modifier.padding(20.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
UsernameDialogContent(
titleText = "Välj användarnamn",
messageText = "Du måste välja ett användarnamn för att fortsätta.",
input = input,
onInputChange = {
input = it
validateLocal(it) // Uppdaterar även 'display'
},
placeholder = "Användarnamn",
titleStyle = MaterialTheme.typography.titleLarge.copy(
color = MaterialTheme.colorScheme.onSurface
),
messageStyle = MaterialTheme.typography.bodyMedium.copy(
color = MaterialTheme.colorScheme.onSurfaceVariant
),
inputTextStyle = MaterialTheme.typography.bodyMedium.copy(
color = MaterialTheme.colorScheme.onSurface
),
statusText = when {
checking && localErr == null && remoteErr == null -> "Kontrollerar …"
localErr != null -> localErr
remoteErr != null -> remoteErr
okRemote && display.isNotBlank() -> "Namnet är ledigt."
else -> null
},
statusStyle = when {
localErr != null || remoteErr != null ->
MaterialTheme.typography.bodySmall.copy(color = MaterialTheme.colorScheme.error)
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
)
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
// Ingen Avbryt-knapp – blockerat tills sparat
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 {
val resp = withContext(Dispatchers.IO) { app.klottr.net.setUsernameRemote(disp) }
if (resp?.ok == true && !resp.username.isNullOrBlank()) {
onSaved(resp.username!!)
} else {
val r = resp?.reason
remoteErr = when (r) {
"taken" -> "Upptaget – prova ett annat."
"reserved" -> "Reserverat – välj något annat."
"invalid" -> "Ogiltigt användarnamn."
"too_few_letters" -> "Minst två bokstäver krävs."
"invalid_chars" -> "Endast bokstäver, siffror, bindestreck och mellanslag tillåts."
else -> "Kunde inte spara. Försök igen."
}
}
} finally {
saving = false
}
}
},
enabled = !saving && okRemote && localErr == null
) {
if (saving) {
CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
} else {
Text("Spara")
}
}
}
}
}
}
}
@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
AlertDialog(
onDismissRequest = onDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false),
confirmButton = { TextButton(onClick = onDismiss) { Text("Stäng") } },
text = {
Box(
Modifier
.fillMaxWidth()
.widthIn(max = dialogWidth)
) {
KlottrAboutContent(
header = {
Image(
painter = painterResource(R.drawable.klottr_logo_v2_line),
contentDescription = null,
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"
),
lineStyle = MaterialTheme.typography.bodyMedium.copy(
color = MaterialTheme.colorScheme.onSurface
),
spacingDp = 12
)
}
}
)
}
// Ny: enkel helskärms bildvisare med pinch-zoom/pan
@Composable
fun ImageViewerDialog(
bitmap: android.graphics.Bitmap,
onClose: () -> Unit
) {
androidx.compose.ui.window.Dialog(
onDismissRequest = onClose,
properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false)
) {
androidx.compose.foundation.layout.Box(
modifier = androidx.compose.ui.Modifier
.fillMaxSize()
.background(androidx.compose.ui.graphics.Color.Black)
) {
var scale by remember { mutableStateOf(1f) }
var offset by remember { mutableStateOf(Offset.Zero) }
androidx.compose.foundation.Image(
bitmap = bitmap.asImageBitmap(),
contentDescription = null,
modifier = androidx.compose.ui.Modifier
.fillMaxSize()
.clipToBounds()
.pointerInput(Unit) {
detectTransformGestures { _, pan, zoom, _ ->
scale = (scale * zoom).coerceIn(0.5f, 6f)
offset += pan
val clamp = 2000f
offset = Offset(
x = offset.x.coerceIn(-clamp, clamp),
y = offset.y.coerceIn(-clamp, clamp)
)
}
}
.graphicsLayer(
scaleX = scale,
scaleY = scale,
translationX = offset.x,
translationY = offset.y
)
)
androidx.compose.foundation.layout.Box(
modifier = androidx.compose.ui.Modifier
.align(Alignment.TopEnd)
.padding(12.dp)
) {
Button(onClick = onClose) { Text("Stäng") }
}
}
}
}

View File

@@ -0,0 +1,452 @@
package app.klottr.ui
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
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.widthIn
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue // Gör 'by remember { ... }' läsbart
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
import androidx.compose.ui.window.DialogProperties
import app.klottr.LocationService
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
import kotlinx.coroutines.withContext
import kotlin.math.roundToInt
// Lämna imports tomma. Android Studio lägger in exakt vad som behövs när du klistrar in funktionerna.
@Composable
fun WikiArticleDialog(
pageId: Long,
lat: Double?,
lon: Double?,
onClose: () -> Unit
) {
val context = LocalContext.current
val configuration = LocalConfiguration.current
val dialogWidth = (configuration.screenWidthDp.dp * 0.98f)
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("-") }
val showCoords = remember { app.klottr.util.SettingsStore.getShowCoordinates() }
fun recalcWikiDistance() {
val my = app.klottr.util.LastLocationStore.lastKnownLocation
val d = if (lat != null && lon != null && my != null)
app.klottr.util.distanceMeters(my.latitude, my.longitude, lat, lon).roundToInt()
else null
wikiDistanceText = d?.let { "$it\u00A0m" } ?: "-"
}
// Beräkna direkt
LaunchedEffect(lat, lon) { recalcWikiDistance() }
// Lyssna på plats-tick för att uppdatera avståndet live
DisposableEffect(Unit) {
val filter = IntentFilter(LocationService.ACTION_LOCATION_TICK)
val receiver = object : BroadcastReceiver() {
override fun onReceive(ctx: Context?, intent: Intent?) { recalcWikiDistance() }
}
if (Build.VERSION.SDK_INT >= 33) {
context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
} else {
@Suppress("DEPRECATION")
context.registerReceiver(receiver, filter)
}
onDispose { try { context.unregisterReceiver(receiver) } catch (_: Exception) {} }
}
LaunchedEffect(pageId) {
loading = true
val detail = withContext(Dispatchers.IO) { Wikipedia.getExtract(pageId) }
title = detail.title
extract = detail.extract
thumb = fetchWikiThumbBitmap(pageId)
loading = false
}
AlertDialog(
onDismissRequest = onClose,
properties = DialogProperties(usePlatformDefaultWidth = false),
title = {
Box(Modifier.fillMaxWidth().widthIn(max = dialogWidth)) {
Text(if (title.isNotBlank()) title else "Wikipedia")
}
},
text = {
Box(
Modifier
.fillMaxWidth()
.widthIn(max = dialogWidth)
.heightIn(max = 520.dp)
) {
if (loading) {
Text("Söker …")
} else {
WikiDetailContent(
titleText = title,
extractText = extract,
distanceText = wikiDistanceText, // Oför: redan beräknad
coordText = if (showCoords && lat != null && lon != null) formatCoords(lat, lon) else null,
thumb = thumb?.asImageBitmap(),
titleStyle = MaterialTheme.typography.titleLarge.copy(
color = MaterialTheme.colorScheme.onSurface // Ny: följer dag/natt
),
bodyStyle = MaterialTheme.typography.bodyMedium.copy(
color = MaterialTheme.colorScheme.onSurface // Ny
),
captionStyle = MaterialTheme.typography.bodySmall.copy(
color = MaterialTheme.colorScheme.onSurfaceVariant // Ny
),
actions = {
Button(onClick = {
val url = "https://sv.m.wikipedia.org/?curid=$pageId"
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
}) { Text("Läs mer") }
Button(
onClick = {
if (lat != null && lon != null) {
val label = if (title.isNullOrBlank()) "Wikipedia-plats" else title // Ny: hantera null/blank
val uri = Uri.parse("geo:$lat,$lon?q=$lat,$lon(${Uri.encode(label)})") // Ändrad: använd label
val intent = Intent(Intent.ACTION_VIEW, uri).apply { setPackage("com.google.android.apps.maps") }
try { context.startActivity(intent) } catch (_: Exception) {
context.startActivity(Intent(Intent.ACTION_VIEW, uri))
}
}
},
enabled = lat != null && lon != null
) { Text("Maps") }
}
)
}
}
},
confirmButton = { Button(onClick = onClose) { Text("Stäng") } }
)
}
@Composable
fun FornsokDialog(
item: FornsokItem,
onClose: () -> Unit
) {
val context = LocalContext.current
val configuration = LocalConfiguration.current
val dialogWidth = (configuration.screenWidthDp.dp * 0.98f)
// Vi använder fälten från FornsokItem; om desc/uri saknas visar vi "saknas"-text.
val title = remember(item.id) { item.title.ifBlank { "Fornlämning" } }
val desc = remember(item.id) { item.desc ?: "" }
val link = remember(item.id) { item.uri ?: (if (item.id.startsWith("http")) item.id else null) }
val platLat = item.lat
val platLon = item.lon
// Avståndstext som uppdateras på plats-tick
var fornDistanceText by remember { mutableStateOf("-") }
val showCoords = remember { app.klottr.util.SettingsStore.getShowCoordinates() }
fun recalcFornDistance() {
val my = app.klottr.util.LastLocationStore.lastKnownLocation
val d = if (my != null)
app.klottr.util.distanceMeters(my.latitude, my.longitude, platLat, platLon).roundToInt()
else null
fornDistanceText = d?.let { "$it\u00A0m" } ?: "-"
}
// Beräkna direkt
LaunchedEffect(platLat, platLon) { recalcFornDistance() }
// Lyssna på plats-tick
DisposableEffect(Unit) {
val filter = IntentFilter(LocationService.ACTION_LOCATION_TICK)
val receiver = object : BroadcastReceiver() {
override fun onReceive(ctx: Context?, intent: Intent?) { recalcFornDistance() }
}
if (Build.VERSION.SDK_INT >= 33) {
context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
} else {
@Suppress("DEPRECATION")
context.registerReceiver(receiver, filter)
}
onDispose { try { context.unregisterReceiver(receiver) } catch (_: Exception) {} }
}
AlertDialog(
onDismissRequest = onClose,
properties = DialogProperties(usePlatformDefaultWidth = false),
title = {
Box(Modifier.fillMaxWidth().widthIn(max = dialogWidth)) {
Text(title)
}
},
text = {
Box(
Modifier
.fillMaxWidth()
.widthIn(max = dialogWidth)
.heightIn(max = 520.dp)
) {
FornsokDetailContent(
titleText = title,
descText = desc,
distanceText = fornDistanceText,
coordText = if (showCoords) formatCoords(platLat, platLon) else null,
titleStyle = MaterialTheme.typography.titleLarge.copy(
color = MaterialTheme.colorScheme.onSurface
),
bodyStyle = MaterialTheme.typography.bodyMedium.copy(
color = MaterialTheme.colorScheme.onSurface
),
captionStyle = MaterialTheme.typography.bodySmall.copy(
color = MaterialTheme.colorScheme.onSurfaceVariant
),
actions = {
Button(
onClick = {
val geoTitle = Uri.encode(title)
val geo = Uri.parse("geo:$platLat,$platLon?q=$platLat,$platLon($geoTitle)")
val intent = Intent(Intent.ACTION_VIEW, geo).apply { setPackage("com.google.android.apps.maps") }
try { context.startActivity(intent) } catch (_: Exception) {
context.startActivity(Intent(Intent.ACTION_VIEW, geo))
}
}
) { Text("Maps") }
Button(
onClick = {
val u = link ?: return@Button
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(u)))
},
enabled = link != null
) { Text("Läs mer") }
}
)
}
},
confirmButton = { Button(onClick = onClose) { Text("Stäng") } }
)
}
@Composable
fun DmDialog(
item: DigitaltMuseumItem,
onClose: () -> Unit
) {
val context = LocalContext.current
val configuration = LocalConfiguration.current
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("-") }
val showCoords = remember { SettingsStore.getShowCoordinates() }
fun recalcDmDistance() {
val my = app.klottr.location.LastLocationStore.lastKnown // Använd delad LastLocationStore.lastKnown
val d = my?.let { // Null-säker hantering
app.klottr.util.distanceMeters(
it.lat, // GeoPoint.lat
it.lon, // GeoPoint.lon
item.lat,
item.lon
).roundToInt()
}
dmDistanceText = d?.let { formatDistance(it) } ?: "-"
}
LaunchedEffect(item.lat, item.lon) { recalcDmDistance() }
DisposableEffect(Unit) {
val filter = IntentFilter(LocationService.ACTION_LOCATION_TICK)
val receiver = object : BroadcastReceiver() {
override fun onReceive(ctx: Context?, intent: Intent?) {
recalcDmDistance()
}
}
if (Build.VERSION.SDK_INT >= 33) {
context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
} else {
@Suppress("DEPRECATION")
context.registerReceiver(receiver, filter)
}
onDispose {
try {
context.unregisterReceiver(receiver)
} catch (_: Exception) {
}
}
}
// Hämta miniatyr om vi har bild-URL
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(
uniqueId = item.uniqueId,
owner = item.owner,
identifierId = item.id
)
}
}
// Post-process: om text saknas eller är samma som titel, försök stycka titeln i meningar.
val originalTitle = item.title.ifBlank { "DigitaltMuseum" }.trim()
val bodyFromApi = detailText?.trim()
fun splitSentences(s: String): Pair<String, String?> {
// Enkel men robust meningdelning: dela på . ! ? följt av mellanslag och stor bokstav/siffra
val regex = Regex("(?<=[.!?])\\s+(?=[A-ZÅÄÖ0-9])")
val parts = s.split(regex).map { it.trim() }.filter { it.isNotEmpty() }
return if (parts.size >= 2) {
val first = parts.first()
val rest = parts.drop(1).joinToString(" ").take(4000).trim().ifEmpty { null }
first to rest
} else s to null
}
val (displayTitle, displayBody) = run {
val noBody = bodyFromApi.isNullOrBlank()
val sameAsTitle =
!bodyFromApi.isNullOrBlank() && bodyFromApi.equals(originalTitle, ignoreCase = true)
if (noBody || sameAsTitle) {
val (t, rest) = splitSentences(originalTitle)
t to rest
} else {
originalTitle to bodyFromApi
}
}
AlertDialog(
onDismissRequest = onClose,
properties = DialogProperties(usePlatformDefaultWidth = false),
title = {
Box(Modifier.fillMaxWidth().widthIn(max = dialogWidth)) {
Text(displayTitle)
}
},
text = {
Box(
Modifier
.fillMaxWidth()
.widthIn(max = dialogWidth)
.heightIn(max = 520.dp)
) {
val displayTitle = remember(item.id, detailText) {
val t = item.title.ifBlank { "DigitaltMuseum" }.trim()
t
}
// Samma heuristik som du hade: splitta ev. text
val (firstLine, restText) = remember(item.id, detailText) {
val body = detailText?.trim().orEmpty()
if (body.isBlank()) "" to null
else {
val idx = body.indexOfFirst { it == '.' || it == '!' || it == '?' }
if (idx >= 0 && idx + 1 < body.length) {
val first = body.substring(0, idx + 1).trim()
val rest = body.substring(idx + 1).trim().ifEmpty { null }
first to rest
} else body to null
}
}
DmDetailContent(
titleText = displayTitle,
bodyText = listOfNotNull(firstLine, restText).joinToString("\n\n"),
distanceText = dmDistanceText,
coordText = if (showCoords) formatCoords(item.lat, item.lon) else null,
image = thumb?.asImageBitmap(),
titleStyle = MaterialTheme.typography.titleLarge.copy(
color = MaterialTheme.colorScheme.onSurface
),
bodyStyle = MaterialTheme.typography.bodyMedium.copy(
color = MaterialTheme.colorScheme.onSurface
),
captionStyle = MaterialTheme.typography.bodySmall.copy(
color = MaterialTheme.colorScheme.onSurfaceVariant
),
actions = {
Button(
onClick = {
val labelEnc = Uri.encode(displayTitle)
val uri =
Uri.parse("geo:${item.lat},${item.lon}?q=${item.lat},${item.lon}($labelEnc)")
val intent = Intent(
Intent.ACTION_VIEW,
uri
).apply { setPackage("com.google.android.apps.maps") }
try {
context.startActivity(intent)
} catch (_: Exception) {
context.startActivity(Intent(Intent.ACTION_VIEW, uri))
}
}
) { Text("Maps") }
Button(
onClick = {
val u = item.webUrl // Ändrad: objectUrl -> webUrl
if (!u.isNullOrBlank()) {
val i = Intent(Intent.ACTION_VIEW, Uri.parse(u))
try {
context.startActivity(i)
} catch (_: Exception) {
}
}
},
enabled = !item.webUrl.isNullOrBlank() // Ändrad: objectUrl -> webUrl
) { Text("Läs mer") }
}
)
}
},
confirmButton = { Button(onClick = onClose) { Text("Stäng") } }
)
}

View File

@@ -1,19 +0,0 @@
package app.klottr.util
import android.util.Log
import app.klottr.BuildConfig
object AppLog {
inline fun d(tag: String = "Klottr", msg: () -> String) {
if (BuildConfig.KLLOG_DEBUG) Log.d(tag, msg())
}
inline fun i(tag: String = "Klottr", msg: () -> String) {
if (BuildConfig.KLLOG_DEBUG) Log.i(tag, msg())
}
inline fun w(tag: String = "Klottr", msg: () -> String) {
if (BuildConfig.KLLOG_DEBUG) Log.w(tag, msg())
}
inline fun e(tag: String = "Klottr", msg: () -> String, tr: Throwable? = null) {
if (BuildConfig.KLLOG_DEBUG) Log.e(tag, msg(), tr)
}
}

View File

@@ -53,6 +53,6 @@ object Notifications {
}
// Enkel in‑app “toast”
fun showInAppNotification(msg: String) {
fun showInAppNotification() {
// Lämnad minimal; i en riktig app kan du använda SnackbarHostState.
}

View File

@@ -1,68 +0,0 @@
package app.klottr.util
import java.util.*
import java.util.Locale
import kotlin.math.abs
fun formatRelativeOrTime(ms: Long): String {
val now = System.currentTimeMillis()
val calNow = Calendar.getInstance()
val calTime = Calendar.getInstance().apply { timeInMillis = ms }
val sameYear = calNow.get(Calendar.YEAR) == calTime.get(Calendar.YEAR)
val sameDay = sameYear &&
calNow.get(Calendar.DAY_OF_YEAR) == calTime.get(Calendar.DAY_OF_YEAR)
val yesterday = sameYear &&
calNow.get(Calendar.DAY_OF_YEAR) - calTime.get(Calendar.DAY_OF_YEAR) == 1
return when {
sameDay -> {
"idag " + android.text.format.DateFormat.format("HH:mm", ms).toString()
}
yesterday -> {
"igår " + android.text.format.DateFormat.format("HH:mm", ms).toString()
}
else -> {
val pattern = if (sameYear) "d MMM HH:mm" else "yyyy-MM-dd HH:mm"
android.text.format.DateFormat.format(pattern, ms).toString()
}
}
}
fun formatCoords(lat: Double, lon: Double): String {
val latDir = if (lat >= 0) "N" else "S"
val lonDir = if (lon >= 0) "E" else "W"
// format med punkt först (Locale.US → garanterar punkt)
val latStr = String.format(Locale.US, "%.5f", abs(lat))
val lonStr = String.format(Locale.US, "%.5f", abs(lon))
// byt punkt till komma för svenskt skrivsätt
val latComma = latStr.replace('.', ',')
val lonComma = lonStr.replace('.', ',')
return "$latComma° $latDir, $lonComma° $lonDir"
}
fun formatDistance(meters: Int): String = when {
meters < 1000 -> "$meters\u00A0m"
meters < 10_000 -> {
val km = meters / 1000.0
if (km % 1.0 == 0.0) // heltal?
String.format(Locale("sv"), "%.0f\u00A0km", km)
else
String.format(Locale("sv"), "%.1f\u00A0km", km)
}
else -> {
val mil = meters / 10_000.0
if (mil % 1.0 == 0.0)
String.format(Locale("sv"), "%.0f\u00A0mil", mil)
else
String.format(Locale("sv"), "%.1f\u00A0mil", mil)
}
}