Split dialog shells into ui/; move image fetchers to app.net; use shared LastLocationStore; clean imports
- Move Nearby/Username/About shells to app.klottr.ui.CommonDialogsShell - Move Wiki/Fornsok/DM shells to app.klottr.ui.DetailDialogsShell - Extract fetchWikiThumbBitmap to app.klottr.net.WikiThumb - Add app.klottr.net.HttpImage (fetchBitmapFromUrl) and use it from DM dialog - Switch detail dialogs to LastLocationStore.lastKnown (GeoPoint) from shared API - Remove unused imports from MainActivity
This commit is contained in:
@@ -55,7 +55,6 @@ import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
@@ -77,7 +76,6 @@ import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
@@ -120,17 +118,17 @@ import app.klottr.net.fetchNoteDetail
|
||||
import app.klottr.net.uploadImageFromUri
|
||||
import app.klottr.shared.SharedPing
|
||||
import app.klottr.theme.KlottrTheme
|
||||
import app.klottr.ui.DmDetailContent // Ny: delad DM-layout
|
||||
import app.klottr.ui.AboutDialog
|
||||
import app.klottr.ui.DmDialog
|
||||
import app.klottr.ui.FornsokDetailContent // Ny: delad Fornsök-layout
|
||||
import app.klottr.ui.FornsokDialog
|
||||
import app.klottr.ui.FoundDetailContent // Delad detalj-UI (CMP)
|
||||
import app.klottr.ui.KlottrAboutContent
|
||||
import app.klottr.ui.KlottrHomeContent // Ny: delat mittinnehåll
|
||||
import app.klottr.ui.LoginRequiredContent
|
||||
import app.klottr.ui.NearbyContent // Delat material-fritt innehåll för Närliggande
|
||||
import app.klottr.ui.NearbyDialogContent
|
||||
import app.klottr.ui.NearbyDialog
|
||||
import app.klottr.ui.SettingsContent // Delad material-fri UI för inställningar
|
||||
import app.klottr.ui.UsernameDialogContent
|
||||
import app.klottr.ui.WikiDetailContent // Ny: delad Wiki-layout
|
||||
import app.klottr.ui.UsernameDialog
|
||||
import app.klottr.ui.WikiArticleDialog // Ny: dialogskalet ligger nu i ui-paketet
|
||||
import app.klottr.ui.WriteDocContent // Använd delad, material-fri formulär-UI
|
||||
import app.klottr.util.Auth
|
||||
import app.klottr.util.Config
|
||||
@@ -160,15 +158,10 @@ import com.google.maps.android.compose.Marker
|
||||
import com.google.maps.android.compose.MarkerState
|
||||
import com.google.maps.android.compose.rememberCameraPositionState
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.tasks.await
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.json.JSONObject
|
||||
import java.io.BufferedInputStream
|
||||
import java.io.File
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.util.UUID
|
||||
import kotlin.math.roundToInt
|
||||
import com.google.android.gms.location.LocationServices as GmsLocationServices
|
||||
@@ -277,59 +270,6 @@ private data class DocumentDraft(
|
||||
val imageUri: Uri?
|
||||
)
|
||||
|
||||
@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
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun KlottrAppShell(
|
||||
@@ -377,7 +317,6 @@ private fun KlottrAppShell(
|
||||
val currentUserId by remember { derivedStateOf { me?.id } }
|
||||
|
||||
var showUsernameDialog by remember { mutableStateOf(false) }
|
||||
var loadingMe by remember { mutableStateOf(false) }
|
||||
|
||||
// Nearby-data
|
||||
var nearbyBundle by remember {
|
||||
@@ -409,9 +348,7 @@ private fun KlottrAppShell(
|
||||
me = null
|
||||
return@LaunchedEffect
|
||||
}
|
||||
loadingMe = true
|
||||
val m = withContext(Dispatchers.IO) { app.klottr.net.fetchMe() }
|
||||
loadingMe = false
|
||||
|
||||
if (m != null) {
|
||||
me = m
|
||||
@@ -1217,9 +1154,7 @@ private fun KlottrAppShell(
|
||||
onSaved = { chosen ->
|
||||
showUsernameDialog = false
|
||||
scope.launch {
|
||||
loadingMe = true
|
||||
me = withContext(Dispatchers.IO) { app.klottr.net.fetchMe() }
|
||||
loadingMe = false
|
||||
}
|
||||
Toast.makeText(context, "Användarnamn satt till ”$chosen”.", Toast.LENGTH_SHORT).show()
|
||||
},
|
||||
@@ -1230,48 +1165,6 @@ private fun KlottrAppShell(
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- Närliggande-dialog (inkl. “Söker …”) ---------- */
|
||||
|
||||
@Composable
|
||||
private 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") } }
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------- Skrivdialog ---------- */
|
||||
@Composable
|
||||
@@ -1445,179 +1338,6 @@ private fun WriteDocDialog(
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private 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")
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* ---------- Inställningar (scroll + “Stäng” synlig) ---------- */
|
||||
|
||||
@@ -1658,9 +1378,6 @@ private fun SettingsDialog(
|
||||
|
||||
var askClear by remember { mutableStateOf(false) }
|
||||
|
||||
//fun formatDistance(m: Int): String =
|
||||
// if (m >= 1000 && m % 1000 == 0) "${m / 1000} km" else "$m meter"
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = onClose,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
@@ -1738,26 +1455,6 @@ private fun SettingsDialog(
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------- Wiki-detalj (med miniatyr) ---------- */
|
||||
|
||||
private 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 }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun KlotterDialog(
|
||||
id: String,
|
||||
@@ -2142,121 +1839,6 @@ private fun ImageViewerDialog(bitmap: Bitmap, onClose: () -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private 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 uri = Uri.parse("geo:$lat,$lon?q=$lat,$lon(${Uri.encode(title.ifBlank { "Wikipedia-plats" })})")
|
||||
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
|
||||
private fun FornsokDialog(
|
||||
item: FornsokItem,
|
||||
@@ -2382,7 +1964,12 @@ private fun DmDialog(
|
||||
|
||||
fun recalcDmDistance() {
|
||||
val my = LastLocationStore.lastKnownLocation
|
||||
val d = if (my != null) app.klottr.util.distanceMeters(my.latitude, my.longitude, item.lat, item.lon).roundToInt() else null
|
||||
val d = if (my != null) app.klottr.util.distanceMeters(
|
||||
my.latitude,
|
||||
my.longitude,
|
||||
item.lat,
|
||||
item.lon
|
||||
).roundToInt() else null
|
||||
dmDistanceText = d?.let { formatDistance(it) } ?: "-"
|
||||
}
|
||||
|
||||
@@ -2391,7 +1978,9 @@ private fun DmDialog(
|
||||
DisposableEffect(Unit) {
|
||||
val filter = IntentFilter(LocationService.ACTION_LOCATION_TICK)
|
||||
val receiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(ctx: Context?, intent: Intent?) { recalcDmDistance() }
|
||||
override fun onReceive(ctx: Context?, intent: Intent?) {
|
||||
recalcDmDistance()
|
||||
}
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= 33) {
|
||||
context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
|
||||
@@ -2399,7 +1988,12 @@ private fun DmDialog(
|
||||
@Suppress("DEPRECATION")
|
||||
context.registerReceiver(receiver, filter)
|
||||
}
|
||||
onDispose { try { context.unregisterReceiver(receiver) } catch (_: Exception) {} }
|
||||
onDispose {
|
||||
try {
|
||||
context.unregisterReceiver(receiver)
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Hämta miniatyr om vi har bild-URL
|
||||
@@ -2412,7 +2006,7 @@ private fun DmDialog(
|
||||
} else {
|
||||
thumb = null
|
||||
}
|
||||
// Text (om uniqueId finns)
|
||||
// Text (om uniqueId finns)
|
||||
detailText = withContext(Dispatchers.IO) {
|
||||
app.klottr.net.DigitaltMuseum.getDetailText(
|
||||
uniqueId = item.uniqueId,
|
||||
@@ -2421,108 +2015,6 @@ private fun DmDialog(
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 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") } }
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
|
||||
32
app/src/main/java/app/klottr/net/WikiThumb.kt
Normal file
32
app/src/main/java/app/klottr/net/WikiThumb.kt
Normal 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
|
||||
}
|
||||
}
|
||||
320
app/src/main/java/app/klottr/ui/CommonDialogsShell.kt
Normal file
320
app/src/main/java/app/klottr/ui/CommonDialogsShell.kt
Normal file
@@ -0,0 +1,320 @@
|
||||
package app.klottr.ui
|
||||
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import androidx.compose.foundation.Image
|
||||
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.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.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
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
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
452
app/src/main/java/app/klottr/ui/DetailDialogsShell.kt
Normal file
452
app/src/main/java/app/klottr/ui/DetailDialogsShell.kt
Normal 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") } }
|
||||
)
|
||||
}
|
||||
24
shared/src/androidMain/kotlin/app/klottr/net/HttpImage.kt
Normal file
24
shared/src/androidMain/kotlin/app/klottr/net/HttpImage.kt
Normal file
@@ -0,0 +1,24 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user