Initial public NavFrame release with global regional package pipeline

This commit is contained in:
dasemu committed 2026-09-30 17:34:58 +02:00
commit d863f2b940
143 files changed
+17906

No files matched your search

@@ -0,0 +1,66 @@
package dev.navframe.app
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.Looper
import android.os.SystemClock
import dev.navframe.core.*
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
/** Android GPS only. Locations stay in memory and are never written to logs. */
class AndroidLocationProvider(context: Context) : LocationProvider {
private val context = context.applicationContext
private val manager = this.context.getSystemService(LocationManager::class.java)
private val fixes = MutableSharedFlow<LocationFix>(replay = 1, extraBufferCapacity = 1)
override val locations = fixes.asSharedFlow()
private val enabled = MutableStateFlow(false)
val providerEnabled = enabled.asStateFlow()
var lastFixElapsedMs: Long = 0
private set
private var listening = false
private val listener = object : LocationListener {
override fun onLocationChanged(location: Location) {
val ageMs = (SystemClock.elapsedRealtimeNanos() - location.elapsedRealtimeNanos) / 1_000_000
if (ageMs !in 0..15_000 || !location.latitude.isFinite() || !location.longitude.isFinite()) return
lastFixElapsedMs = location.elapsedRealtimeNanos / 1_000_000
enabled.value = true
fixes.tryEmit(LocationFix(
GeoPoint(location.latitude, location.longitude),
if (location.hasBearing()) location.bearing else Float.NaN,
if (location.hasSpeed() && location.speed.isFinite()) location.speed.coerceAtLeast(0f) else 0f,
if (location.hasAccuracy()) location.accuracy else Float.POSITIVE_INFINITY,
location.time,
))
}
override fun onProviderEnabled(provider: String) { enabled.value = true }
override fun onProviderDisabled(provider: String) { enabled.value = false; lastFixElapsedMs = 0 }
@Deprecated("Legacy Android callback")
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) { }
}
override suspend fun start() {
check(context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
"Autoriza ubicación precisa para usar el GPS"
}
check(LocationManager.GPS_PROVIDER in manager.allProviders) { "GPS no disponible en este dispositivo" }
if (listening) return
lastFixElapsedMs = 0
enabled.value = manager.isProviderEnabled(LocationManager.GPS_PROVIDER)
try {
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500L, 0f, listener, Looper.getMainLooper())
listening = true
} catch (error: Exception) { manager.removeUpdates(listener); throw error }
}
override suspend fun stop() { close() }
fun close() {
try { if (listening) manager.removeUpdates(listener) }
finally { listening = false; enabled.value = false; lastFixElapsedMs = 0 }
}
}
@@ -0,0 +1,26 @@
package dev.navframe.app
import dev.navframe.core.*
import java.net.URI
/** The boundary supplies a style endpoint rather than binding navigation to a particular provider. */
@Suppress("UNUSED_PARAMETER")
class ConfiguredMapDataSource(styleUrl: String = "", attribution: String = DEFAULT_ATTRIBUTION, context: android.content.Context? = null) : MapDataSource {
private val source: TileSource
init {
val value = styleUrl.trim()
if (value.isNotEmpty()) {
val parsed = URI(value)
val local = parsed.scheme == "file" && context != null && OfflineMapManager.isApprovedSource(context, value)
require(local || (parsed.scheme == "https" && !parsed.host.isNullOrBlank() && parsed.userInfo == null)) { "Usa HTTPS o un paquete offline instalado por NavFrame" }
require(parsed.host != "tile.openstreetmap.org") { "Usa un proveedor de teselas vectoriales" }
}
val credits = when { value.isEmpty() -> DEFAULT_ATTRIBUTION; value.startsWith("file:") -> OfflineMapManager.ATTRIBUTION; else -> BASE_ATTRIBUTION }
source = TileSource(value.ifEmpty { "asset://map/tft-style.json" }, credits)
}
override fun tileSource() = source
override suspend fun prepareRegion(region: MapRegion) {
throw UnsupportedOperationException("Instala o importa un paquete PMTiles desde Configuración · Mapas offline")
}
companion object { const val BASE_ATTRIBUTION = "Fuente sin atribución declarada"; const val DEFAULT_ATTRIBUTION = "OpenFreeMap · © OpenMapTiles · © OpenStreetMap contributors" }
}
@@ -0,0 +1,21 @@
package dev.navframe.app
import dev.navframe.core.ConnectionState
import dev.navframe.core.TftFrame
import dev.navframe.core.TftTransport
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
/** Publishes the same JPEG bytes that a real CCU receives, without Bluetooth. */
class FakeTftTransport : TftTransport {
private val state = MutableStateFlow(ConnectionState.DISCONNECTED)
override val connectionState = state.asStateFlow()
private val frame = MutableStateFlow<TftFrame?>(null)
val lastFrame = frame.asStateFlow()
override suspend fun connect() { state.value = ConnectionState.CONNECTED }
override suspend fun disconnect() { state.value = ConnectionState.DISCONNECTED }
override suspend fun sendFrame(frame: TftFrame) {
check(state.value == ConnectionState.CONNECTED) { "Fake transport is disconnected" }
this.frame.value = frame.copy(encodedBytes = frame.encodedBytes.copyOf())
}
}
@@ -0,0 +1,809 @@
package dev.navframe.app
import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.bluetooth.BluetoothManager
import android.content.*
import android.content.pm.PackageManager
import android.graphics.Color
import android.net.Uri
import android.os.*
import android.provider.Settings
import android.view.View
import android.widget.*
import dev.navframe.core.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.first
/** Navigation-first phone UI. MapView renders service state; the TFT has its own native target. */
open class MainActivity : Activity() {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
private var observers: Job? = null
private var searchJob: Job? = null
private var positionWait: Job? = null
private var searchGeneration = 0L
private var updatingDestination = false
private val placeRepository by lazy { OfflinePlaceRepository(applicationContext) }
private var placesJob: Job? = null
private var placesGeneration = 0L
private var placesDialog: AlertDialog? = null
private var displayedPlaces: List<OfflinePlace> = emptyList()
private var service: TftService? = null
private var bound = false
private var phoneMap: PhoneMapView? = null
private var uiStarted = false
private var uiResumed = false
private val regionalManager by lazy { RegionalPackManager(applicationContext) }
private val DEFAULT_REGIONAL_CATALOG = "https://github.com/Dasemu/NavFrame/releases/download/offline-catalog/regional-catalog.json"
private val regionalDownloads by lazy { RegionalDownloadManager(regionalManager) }
private val offlineManager by lazy { OfflineMapManager(applicationContext) }
private var offlineTask: Job? = null
private var offlineDialog: AlertDialog? = null
private var routeDialog: AlertDialog? = null
private var positionNotice: TextView? = null
private var positionNoticeHide: Runnable? = null
private var startButton: Button? = null
private var routeLoading: ProgressBar? = null
private var retryRouteButton: Button? = null
private var startRequested = false
private val unifiedSearch by lazy { UnifiedPlaceSearch(placeRepository) }
private val viewportPlaces by lazy { OfflineViewportController(scope, placeRepository, { displayedPlaces = it; phoneMap?.setPlaces(it) }) }
private lateinit var stopButton: Button
private lateinit var mapHost: FrameLayout
private lateinit var searchQuery: EditText
private lateinit var results: LinearLayout
private lateinit var resultScroll: ScrollView
private lateinit var hint: TextView
private lateinit var guidance: TextView
private lateinit var progress: TextView
private lateinit var routeInfo: TextView
private lateinit var connectionInfo: TextView
private lateinit var permissionInfo: TextView
private lateinit var credits: TextView
private lateinit var origin: Spinner
private lateinit var profileButton: Button
private val motorcyclePreferences by lazy { getSharedPreferences("yamaha", MODE_PRIVATE) }
private val routePreferences by lazy { getSharedPreferences("route_preferences", MODE_PRIVATE) }
private var routeOptions = RouteOptions()
private val visibleProfiles = listOf(RouteProfile.FASTEST, RouteProfile.AVOID_MOTORWAYS, RouteProfile.AVOID_UNPAVED)
private var destination: GeoPoint? = null
private var destinationName = ""
private enum class Action { POSITION, CALCULATE, ROUTE, PREVIEW, CONNECT, CHANGE_CONNECT }
private var pendingAction: Action? = null
private val permissionsPreferences by lazy { getSharedPreferences("permissions", MODE_PRIVATE) }
private val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {
service = (binder as TftService.LocalBinder).service
observeService()
refreshPermissions()
tryAutoConnect()
}
override fun onServiceDisconnected(name: ComponentName?) { service = null; connectionInfo.text = "● Yamaha · conectar" }
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
pendingAction = savedInstanceState?.getString("pending_action")?.let { value -> Action.entries.firstOrNull { it.name == value } }
routeOptions = RouteOptions(profile = visibleProfiles.firstOrNull { it.name == routePreferences.getString("profile", "AVOID_UNPAVED") } ?: RouteProfile.AVOID_UNPAVED, avoidUnpaved = routePreferences.getBoolean("asphalt", true), avoidMotorways = routePreferences.getBoolean("highways", false))
val root = FrameLayout(this).apply { setBackgroundColor(Color.rgb(13, 19, 25)) }
mapHost = FrameLayout(this)
root.addView(mapHost, FrameLayout.LayoutParams(-1, -1))
credits = label("© OpenStreetMap", 10f).apply {
setPadding(dp(8), dp(3), dp(8), dp(3)); setBackgroundColor(0xCC17212D.toInt())
contentDescription = "Créditos del mapa. Abrir información y licencias"
setOnClickListener { showInfo() }
}
try { phoneMap = createPhoneMap(savedInstanceState?.getBundle("phone_map"))?.also { mapHost.addView(it.view, FrameLayout.LayoutParams(-1, -1)) } }
catch (_: Exception) { mapHost.addView(label("Mapa no disponible en este dispositivo", 18f)) }
val top = column().apply { setPadding(dp(12), dp(8), dp(12), 0) }
val toolbar = row()
connectionInfo = label("● Yamaha · conectar", 14f).apply {
gravity = android.view.Gravity.CENTER_VERTICAL; minHeight = dp(48); setPadding(dp(14), 0, dp(10), 0); background = rounded(0xEE17212D.toInt(), 24); setTextColor(0xFFB5EADA.toInt())
setOnClickListener { withPermissions(Action.CONNECT) }; contentDescription = "Estado Yamaha. Tocar para conectar"
}
toolbar.addView(connectionInfo, LinearLayout.LayoutParams(0, dp(48), 1f))
toolbar.addView(button("☰") { AlertDialog.Builder(this).setTitle("NavFrame").setItems(arrayOf("Ajustes", "Mapas offline", "Lugares cercanos", "Información y licencias")) { _, item -> when(item) { 0 -> showSettings(); 1 -> showOfflineMaps(); 2 -> showPlaces(); 3 -> showInfo() } }.show() }.apply { contentDescription = "Abrir menú" }, LinearLayout.LayoutParams(dp(56), dp(48)))
top.addView(toolbar, LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = dp(8) })
val searchRow = row().apply { background = rounded(0xF217212D.toInt(), 18); elevation = dp(6).toFloat(); setPadding(dp(8), 0, dp(4), 0) }
searchQuery = edit("Buscar calles y lugares").apply {
background = null; setPadding(dp(8), 0, dp(4), 0); isSaveEnabled = false; imeOptions = android.view.inputmethod.EditorInfo.IME_ACTION_SEARCH
setOnEditorActionListener { _, action, _ -> if (action == android.view.inputmethod.EditorInfo.IME_ACTION_SEARCH) { searchDestination(); true } else false }
}
searchRow.addView(searchQuery, LinearLayout.LayoutParams(0, dp(56), 1f))
searchRow.addView(button("⌕") { searchDestination() }.apply { contentDescription = "Buscar destino" }, LinearLayout.LayoutParams(dp(56), dp(56)))
top.addView(searchRow)
hint = label("", 13f).apply {
maxLines = 2; visibility = View.GONE; background = rounded(0xEE17212D.toInt(), 12)
addTextChangedListener(object : android.text.TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { }
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { visibility = if (s.isNullOrEmpty()) View.GONE else View.VISIBLE }
override fun afterTextChanged(s: android.text.Editable?) { }
})
}
top.addView(hint)
val radarNotice = label("", 14f).apply {
visibility = View.GONE; maxLines = 2; setPadding(dp(10), dp(6), dp(10), dp(6))
background = rounded(0xEE17212D.toInt(), 12)
setTextColor(0xFFFFD180.toInt())
}
radarBanner = radarNotice
top.addView(radarNotice)
results = column().apply { setBackgroundColor(0xF217212D.toInt()) }
resultScroll = ScrollView(this).apply { addView(results); visibility = View.GONE }
top.addView(resultScroll, LinearLayout.LayoutParams(-1, dp(180)))
root.addView(top, FrameLayout.LayoutParams(-1, -2, android.view.Gravity.TOP))
searchQuery.addTextChangedListener(object : android.text.TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { }
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (updatingDestination) return
cancelSearch(); positionWait?.cancel(); destination = null; destinationName = ""; routeDialog?.dismiss(); startButton?.isEnabled = false
if (service?.hasActiveGuidance() != true) service?.selectSearchDestination()
results.removeAllViews(); resultScroll.visibility = View.GONE; hint.text = ""
searchOfflineSuggestions(s?.toString().orEmpty())
}
override fun afterTextChanged(s: android.text.Editable?) { }
})
guidance = label("", 20f); progress = label("", 14f); routeInfo = label("", 14f)
permissionInfo = label("", 12f)
origin = Spinner(this).apply { adapter = ArrayAdapter(this@MainActivity, android.R.layout.simple_spinner_dropdown_item, listOf("GPS real", "DEMO · posición simulada")) }
profileButton = button(profileLabel()) { chooseProfile() }
stopButton = button("STOP · Detener ruta") { positionWait?.cancel(); service?.stopRoute(); routeDialog?.dismiss(); hint.text = ""; stopButton.visibility = View.GONE }.apply { visibility = View.GONE; setTextColor(Color.WHITE); background = rounded(0xEEA83939.toInt(), 18) }
root.addView(stopButton, FrameLayout.LayoutParams(-1, dp(56), android.view.Gravity.BOTTOM).apply { setMargins(dp(16), 0, dp(16), dp(28)) })
root.addView(button("◎") { withPermissions(Action.POSITION) }.apply { contentDescription = "Centrar en mi posición y seguir el mapa"; background = rounded(0xFF50D5B6.toInt(), 28); setTextColor(0xFF0D191C.toInt()); elevation = dp(8).toFloat() }, FrameLayout.LayoutParams(dp(56), dp(56), android.view.Gravity.BOTTOM or android.view.Gravity.END).apply { setMargins(0, 0, dp(16), dp(104)) })
positionNotice = label("", 13f).apply {
gravity = android.view.Gravity.CENTER
setPadding(dp(14), dp(9), dp(14), dp(9))
background = rounded(0xDD17212D.toInt(), 16)
alpha = 0f; visibility = View.GONE
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_YES
if (Build.VERSION.SDK_INT >= 19) accessibilityLiveRegion = View.ACCESSIBILITY_LIVE_REGION_POLITE
}
root.addView(positionNotice, FrameLayout.LayoutParams(-2, -2, android.view.Gravity.BOTTOM or android.view.Gravity.CENTER_HORIZONTAL).apply { setMargins(dp(24), 0, dp(24), dp(96)) })
root.addView(credits, FrameLayout.LayoutParams(-2, -2, android.view.Gravity.BOTTOM or android.view.Gravity.START).apply { setMargins(dp(8), 0, dp(8), dp(2)) })
root.setOnApplyWindowInsetsListener { view, insets ->
if (Build.VERSION.SDK_INT >= 30) {
val bars = insets.getInsets(android.view.WindowInsets.Type.systemBars() or android.view.WindowInsets.Type.ime())
view.setPadding(bars.left, bars.top, bars.right, bars.bottom)
}
insets
}
setContentView(root)
}
/** Allows UI behavior tests to run real Views without invoking the device-only JNI renderer. */
protected open fun createPhoneMap(savedState: Bundle?): PhoneMapView? = PhoneMapView(this, savedState,
onAttribution = { if (::credits.isInitialized) credits.text = compactAttribution(it) },
onPlaceSelected = { chooseDestination(it.position, it.name, "© OpenStreetMap contributors") },
onError = { hint.text = "Mapa no disponible · revisa Internet o el paquete offline" },
onViewportChanged = { viewportPlaces.refresh(it) })
protected open fun hasReliablePosition(): Boolean = service?.hasFreshGpsFix() == true
protected open fun recenterPhoneMap() { phoneMap?.recenter() }
override fun onStart() { super.onStart(); uiStarted = true; phoneMap?.onStart(); bound = bindService(Intent(this, TftService::class.java), connection, Context.BIND_AUTO_CREATE) }
override fun onResume() { super.onResume(); uiResumed = true; phoneMap?.onResume(); refreshPermissions(); tryAutoConnect() }
override fun onPause() { uiResumed = false; phoneMap?.onPause(); super.onPause() }
override fun onStop() { uiStarted = false; hidePositionNotice(); placesDialog?.dismiss(); placesJob?.cancel(); placesGeneration++; viewportPlaces.cancel(); service?.setPhoneVisible(false); cancelSearch(); positionWait?.cancel(); observers?.cancel(); if (bound) unbindService(connection); bound = false; service = null; phoneMap?.onStop(); super.onStop() }
override fun onDestroy() { hidePositionNotice(); routeDialog?.dismiss(); viewportPlaces.cancel(); scope.cancel(); phoneMap?.onDestroy(); phoneMap = null; super.onDestroy() }
override fun onLowMemory() { super.onLowMemory(); phoneMap?.onLowMemory() }
override fun onSaveInstanceState(outState: Bundle) { val map = Bundle(); phoneMap?.onSaveInstanceState(map); outState.putBundle("phone_map", map); pendingAction?.let { outState.putString("pending_action", it.name) }; super.onSaveInstanceState(outState) }
private var radarBanner: TextView? = null
private fun observeService() {
observers?.cancel()
val current = service ?: return
phoneMap?.loadStyle(current.mapSource()); phoneMap?.refreshPlaces(); credits.text = compactAttribution(current.mapSource().attribution)
observers = scope.launch {
launch { current.radarAlert.collect { alert ->
radarBanner?.text = alert.orEmpty()
radarBanner?.visibility = if (alert == null) View.GONE else View.VISIBLE
} }
launch { current.connectionState.collect { connectionInfo.text = "● Yamaha · " + when(it) { ConnectionState.CONNECTED -> "conectada"; ConnectionState.CONNECTING, ConnectionState.HANDSHAKING -> "conectando"; ConnectionState.ERROR -> "reintentar"; else -> "conectar" } } }
launch { current.routeInfo.collect { routeInfo.text = it; startButton?.isEnabled = current.hasPreparedRoute(); routeLoading?.visibility = if (it.startsWith("Calculando")) View.VISIBLE else View.GONE; retryRouteButton?.visibility = if (it.startsWith("No se pudo") || it.startsWith("Tiempo de espera")) View.VISIBLE else View.GONE } }
launch { current.navigationState.collect { state ->
phoneMap?.update(state)
stopButton.visibility = if (current.hasActiveGuidance()) View.VISIBLE else View.GONE
if (startRequested && current.hasActiveGuidance()) { routeDialog?.dismiss(); startRequested = false }
val demo = current.navigationMode.value == NavigationMode.MAP_DEMO || current.navigationMode.value == NavigationMode.DEMO
guidance.text = when (state.navigationStatus) {
NavigationStatus.GPS_LOST -> "Sin GPS reciente y preciso"
NavigationStatus.REROUTING -> "Recalculando ruta…"
NavigationStatus.OFF_ROUTE -> "Fuera de ruta"
NavigationStatus.ARRIVED -> "Has llegado al destino"
NavigationStatus.ROUTE_PREVIEW -> "Vista previa de ruta"
NavigationStatus.IDLE -> "Listo para navegar"
else -> state.nextManeuver?.instruction ?: if (state.route == null) "GPS listo · elige un destino" else "Continúa por la ruta"
}.let { if (demo) "DEMO · $it" else it }
val next = state.distanceToNextManeuverMeters?.let { "$it m" } ?: ""
val remaining = state.remainingDistanceMeters?.let { "%.1f km restantes".format(java.util.Locale.ROOT, it / 1000.0) } ?: ""
val eta = state.etaEpochMillis?.let { "ETA " + java.text.SimpleDateFormat("HH:mm", java.util.Locale.ROOT).format(java.util.Date(it)) } ?: ""
val accuracy = state.accuracyMeters?.takeIf { it.isFinite() }?.let { "GPS ±${it.toInt()} m" } ?: ""
progress.text = listOf(next, remaining, eta, accuracy).filter { it.isNotEmpty() }.joinToString(" · ")
} }
}
}
private fun withPermissions(action: Action) {
if (service == null) { hint.text = "Espera la conexión con el servicio"; return }
val needsLocation = action == Action.POSITION || (action == Action.CALCULATE && origin.selectedItemPosition == 0) || (action == Action.ROUTE && service?.routeUsesGps() == true)
val required = mutableListOf<String>()
if ((action == Action.CONNECT || action == Action.CHANGE_CONNECT) && Build.VERSION.SDK_INT >= 31) required += Manifest.permission.BLUETOOTH_CONNECT
if (needsLocation) required += Manifest.permission.ACCESS_FINE_LOCATION
val missing = required.filter { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
val blocked = missing.any { permissionsPreferences.getBoolean(it, false) && !shouldShowRequestPermissionRationale(it) }
if (blocked) { AlertDialog.Builder(this).setTitle("Permiso necesario").setMessage("Activa ubicación precisa o dispositivos cercanos para esta función. Puedes seguir explorando mapas y usando la demo.").setPositiveButton("Abrir ajustes") { _, _ -> openAppSettings() }.setNegativeButton("Cancelar", null).show(); return }
val request = missing.toMutableList()
if (missing.contains(Manifest.permission.ACCESS_FINE_LOCATION)) request += Manifest.permission.ACCESS_COARSE_LOCATION
if ((action == Action.CONNECT || action == Action.CHANGE_CONNECT || (action == Action.ROUTE && service?.routeUsesGps() == true)) && Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED && !permissionsPreferences.getBoolean(Manifest.permission.POST_NOTIFICATIONS, false)) request += Manifest.permission.POST_NOTIFICATIONS
if (request.isEmpty()) { perform(action); return }
val ask = {
pendingAction = action
request.forEach { permissionsPreferences.edit().putBoolean(it, true).apply() }
requestPermissions(request.distinct().toTypedArray(), 42)
}
if (missing.any { shouldShowRequestPermissionRationale(it) }) AlertDialog.Builder(this).setTitle("Permisos de navegación").setMessage("GPS precisa tu posición para guiarte; Bluetooth conecta la Yamaha. La sesión usa una notificación mientras navegas.").setPositiveButton("Continuar") { _, _ -> ask() }.setNegativeButton("Cancelar", null).show() else ask()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode != 42) return
val action = pendingAction; pendingAction = null
refreshPermissions()
val needsFine = action == Action.POSITION || (action == Action.CALCULATE && origin.selectedItemPosition == 0) || (action == Action.ROUTE && service?.routeUsesGps() == true)
val allowed = (!needsFine || checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) && ((action != Action.CONNECT && action != Action.CHANGE_CONNECT) || Build.VERSION.SDK_INT < 31 || checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED)
if (action != null && allowed) perform(action) else hint.text = "Permiso denegado · puedes usar la demo. Toca el aviso de permisos para abrir ajustes."
}
private fun refreshPermissions() {
if (!::permissionInfo.isInitialized) return
val missing = mutableListOf<String>()
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) missing += "GPS preciso"
if (Build.VERSION.SDK_INT >= 31 && checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) missing += "Bluetooth"
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) missing += "notificaciones"
permissionInfo.text = if (missing.isEmpty()) "Permisos listos" else "Falta ${missing.joinToString(", ")} · tocar para ajustes"
service?.recheckPermissions()
service?.setPhoneVisible(uiStarted && checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
}
private fun perform(action: Action) {
when (action) {
Action.POSITION -> {
val current = service
current?.setPhoneVisible(true)
if (hasReliablePosition()) { hidePositionNotice(); recenterPhoneMap() }
else showPositionNotice(when {
current == null || !current.isGpsSessionActive() && current.navigationState.value.accuracyMeters == null -> "Buscando señal GPS…"
current.navigationState.value.accuracyMeters?.let { !it.isFinite() || it > 25f } == true -> "Señal GPS poco precisa"
else -> "Esperando una posición GPS reciente"
})
}
Action.CONNECT -> if (!connectRemembered(false)) chooseMotorcycle()
Action.CHANGE_CONNECT -> chooseMotorcycle()
Action.CALCULATE -> calculateRoute()
Action.ROUTE, Action.PREVIEW -> {
if (action == Action.ROUTE && service?.hasPreparedRoute() != true) return
if (action == Action.ROUTE) startRequested = true
if (action == Action.PREVIEW) service?.previewPreparedRoute()
else if (service?.routeUsesGps() == true) try { startForegroundService(Intent(this, TftService::class.java).setAction(TftService.ACTION_ROUTE_GPS).putExtra(TftService.EXTRA_PREVIEW, action == Action.PREVIEW)) } catch (_: RuntimeException) { hint.text = "No se pudo iniciar · revisa permisos de ubicación" }
else service?.startRoute(action == Action.PREVIEW)
if (action == Action.ROUTE && service?.hasActiveGuidance() == true) routeDialog?.dismiss()
}
}
}
private fun showPositionNotice(message: String) {
val notice = positionNotice ?: return
positionNoticeHide?.let(notice::removeCallbacks)
positionNoticeHide = null
notice.text = message
notice.visibility = View.VISIBLE
notice.animate().cancel(); notice.alpha = 0f
notice.animate().alpha(1f).setDuration(140).start()
val hide = Runnable {
notice.animate().alpha(0f).setDuration(220).withEndAction { if (notice.alpha == 0f) notice.visibility = View.GONE }.start()
positionNoticeHide = null
}
positionNoticeHide = hide
notice.postDelayed(hide, 2600)
}
private fun hidePositionNotice() {
positionNotice?.let { notice ->
positionNoticeHide?.let(notice::removeCallbacks)
positionNoticeHide = null
notice.animate().cancel(); notice.alpha = 0f; notice.visibility = View.GONE
}
}
private fun startGps() {
try { startForegroundService(Intent(this, TftService::class.java).setAction(TftService.ACTION_MAP_GPS)) }
catch (_: RuntimeException) { hint.text = "No se pudo iniciar GPS · revisa permisos y ajustes de ubicación" }
}
private fun calculateRoute() {
positionWait?.cancel()
val target = destination ?: run { hint.text = "Elige primero un resultado de búsqueda"; return }
val current = service ?: return
startButton?.isEnabled = false
if (origin.selectedItemPosition == 1) { current.calculateRoute(target, true, current.routingEndpoint(), routeOptions); return }
if (current.hasFreshGpsFix()) { current.calculateRoute(target, false, current.routingEndpoint(), routeOptions); return }
current.setPhoneVisible(true); hint.text = "Esperando una posición GPS reciente…"; routeInfo.text = "Esperando una posición GPS reciente…"; routeLoading?.visibility = View.VISIBLE
positionWait?.cancel()
positionWait = scope.launch {
try {
withTimeout(20_000) { current.gpsReady.first { it && current.hasFreshGpsFix() } }
ensureActive()
current.calculateRoute(target, false, current.routingEndpoint(), routeOptions)
} catch (cancelled: CancellationException) { currentCoroutineContext().ensureActive(); hint.text = "Sin GPS · activa ubicación y prueba de nuevo"; routeInfo.text = hint.text; routeLoading?.visibility = View.GONE; retryRouteButton?.visibility = View.VISIBLE }
}
}
private fun cancelSearch() { searchGeneration++; searchJob?.cancel(); searchJob = null }
private fun searchDestination() {
cancelSearch(); results.removeAllViews(); resultScroll.visibility = View.GONE
val query = searchQuery.text.toString(); val generation = searchGeneration
val endpoint = getSharedPreferences("geocoder", MODE_PRIVATE).getString("endpoint", NominatimGeocoder.DEFAULT_ENDPOINT) ?: NominatimGeocoder.DEFAULT_ENDPOINT
hint.text = "Buscando…"
searchJob = scope.launch {
try {
val response = unifiedSearch.searchExplicit(searchCenter(), query, NominatimGeocoder(endpoint))
val found = response.results
ensureActive(); if (generation != searchGeneration) return@launch
hint.text = if (found.isEmpty()) "Sin resultados · añade ciudad o dirección" else "Elige un destino · © OpenStreetMap contributors"
resultScroll.visibility = if (found.isEmpty()) View.GONE else View.VISIBLE
found.forEach { result -> results.addView(button("${result.name}\n${result.sourceLabel}") {
chooseDestination(result.position, result.name, result.attribution)
}.apply { maxLines = 3 }) }
} catch (cancelled: CancellationException) { currentCoroutineContext().ensureActive(); hint.text = "Búsqueda sin respuesta · vuelve a pulsar Buscar" }
catch (error: Exception) { if (generation == searchGeneration) hint.text = if (error is java.io.IOException && error.message?.startsWith("Proveedor") == true) error.message else "No se pudo buscar · revisa consulta, Internet y proveedor" }
}
}
private fun searchCenter() = phoneMap?.center() ?: service?.navigationState?.value?.position?.takeIf { it != GeoPoint(0.0, 0.0) } ?: GeoPoint(43.36, -5.85)
private fun searchOfflineSuggestions(query: String) {
if (query.trim().length < 2) return
val generation = searchGeneration
searchJob = scope.launch {
delay(250)
val found = try { unifiedSearch.searchOffline(searchCenter(), query).take(20) } catch (cancelled: CancellationException) { throw cancelled } catch (_: Exception) { emptyList() }
ensureActive(); if (generation != searchGeneration) return@launch
results.removeAllViews(); resultScroll.visibility = if (found.isEmpty()) View.GONE else View.VISIBLE
found.forEach { result -> results.addView(button("${result.name}\n${result.sourceLabel}") { chooseDestination(result.position, result.name, result.attribution) }) }
}
}
override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus); if (hasFocus && uiResumed) tryAutoConnect() }
private fun tryAutoConnect() {
if (!uiResumed || service?.isRealSessionRequested() != false || !motorcyclePreferences.getBoolean("auto", true) || motorcyclePreferences.getBoolean("paused", false)) return
connectRemembered(true)
}
private fun connectRemembered(automatic: Boolean, replace: Boolean = false): Boolean {
if (Build.VERSION.SDK_INT >= 31 && checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) return false
val address = motorcyclePreferences.getString("address", null) ?: return false
try {
val adapter = getSystemService(BluetoothManager::class.java).adapter ?: return false
if (!adapter.isEnabled || adapter.bondedDevices.none { it.address == address }) return false
if (service?.isRealSessionRequested() == true && !replace) return true
if (!automatic) motorcyclePreferences.edit().putBoolean("paused", false).apply()
startForegroundService(Intent(this, TftService::class.java).setAction(TftService.ACTION_REAL).putExtra(TftService.EXTRA_ADDRESS, address).putExtra(TftService.EXTRA_AUTO, automatic))
return true
} catch (_: RuntimeException) { hint.text = "No se pudo conectar Yamaha · revisa Bluetooth y permisos"; return false }
}
private fun profileLabel(): String = when (routeOptions.profile) { RouteProfile.FASTEST -> "Rápido"; RouteProfile.AVOID_MOTORWAYS -> "Evitar autopistas"; RouteProfile.TOURING -> "Paseo"; RouteProfile.AVOID_UNPAVED -> "Preferir asfalto" } + if (routeOptions.avoidUnpaved && routeOptions.profile != RouteProfile.AVOID_UNPAVED) " · asfalto" else ""
private fun chooseProfile() {
val box = column().apply { setPadding(dp(16), 0, dp(16), 0) }
val select = Spinner(this).apply { adapter = ArrayAdapter(this@MainActivity, android.R.layout.simple_spinner_dropdown_item, listOf("Rápido", "Evitar autopistas", "Preferir asfalto")); setSelection(visibleProfiles.indexOf(routeOptions.profile).coerceAtLeast(0)) }
val asphalt = CheckBox(this).apply { text = "Priorizar asfalto"; isChecked = routeOptions.avoidUnpaved }
val highways = CheckBox(this).apply { text = "Preferir menos autopistas"; isChecked = routeOptions.avoidMotorways }
box.addView(select); box.addView(asphalt); box.addView(highways); box.addView(label("Son preferencias del servidor: no garantizan excluir autopistas o tierra. Revisa la ruta y las señales.", 14f))
AlertDialog.Builder(this).setTitle("Perfil de ruta en moto").setView(box).setPositiveButton("Aplicar") { _, _ ->
routeOptions = RouteOptions(visibleProfiles[select.selectedItemPosition], avoidUnpaved = asphalt.isChecked, avoidMotorways = highways.isChecked)
routePreferences.edit().putString("profile", routeOptions.profile.name).putBoolean("asphalt", routeOptions.avoidUnpaved).putBoolean("highways", routeOptions.avoidMotorways).apply()
profileButton.text = profileLabel()
startButton?.isEnabled = false
service?.invalidateRoutePlan()
if (destination != null) withPermissions(Action.CALCULATE)
}.setNegativeButton("Cancelar", null).show()
}
private fun chooseDestination(point: GeoPoint, name: String, attribution: String) {
val current = service ?: run { hint.text = "Espera la conexión con el servicio"; return }
cancelSearch(); positionWait?.cancel()
updatingDestination = true
try { searchQuery.setText(name.take(200)) } finally { updatingDestination = false }
startRequested = false
current.selectSearchDestination(); startButton?.isEnabled = false; destination = point; destinationName = name
hint.text = "Destino: $name · $attribution"
results.removeAllViews(); resultScroll.visibility = View.GONE
showRouteSheet()
withPermissions(Action.CALCULATE)
}
private fun compactAttribution(value: String): String = value.replace(" contributors", "").replace("Fuente online predeterminada incluida: ", "").take(150)
private fun showRouteSheet() {
routeDialog?.dismiss()
(origin.parent as? android.view.ViewGroup)?.removeView(origin)
(profileButton.parent as? android.view.ViewGroup)?.removeView(profileButton)
(routeInfo.parent as? android.view.ViewGroup)?.removeView(routeInfo)
val box = column().apply { setPadding(dp(16), dp(8), dp(16), dp(12)) }
box.addView(label(destinationName, 22f))
box.addView(label("Perfil de ruta", 14f)); box.addView(profileButton)
box.addView(label("Origen", 14f)); box.addView(origin)
var previousOrigin = origin.selectedItemPosition
origin.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
if (previousOrigin == position) return
previousOrigin = position; startButton?.isEnabled = false; service?.invalidateRoutePlan(); withPermissions(Action.CALCULATE)
}
override fun onNothingSelected(parent: AdapterView<*>?) { }
}
routeLoading = ProgressBar(this).apply { visibility = View.GONE; contentDescription = "Calculando ruta" }; box.addView(routeLoading)
box.addView(routeInfo)
retryRouteButton = button("Reintentar cálculo") { withPermissions(Action.CALCULATE) }.apply { visibility = View.GONE }; box.addView(retryRouteButton)
startButton = button("Iniciar") { withPermissions(Action.ROUTE) }.apply { background = rounded(0xFF50D5B6.toInt(), 16); setTextColor(0xFF0D191C.toInt()); isEnabled = service?.hasPreparedRoute() == true }; box.addView(startButton)
val dialog = AlertDialog.Builder(this).setView(ScrollView(this).apply { addView(box) }).setNegativeButton("Cerrar", null).create()
routeDialog = dialog; dialog.show()
dialog.window?.apply { setBackgroundDrawable(rounded(0xFF17212D.toInt(), 24)); setGravity(android.view.Gravity.BOTTOM); setLayout(-1, -2); setSoftInputMode(android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) }
(getSystemService(INPUT_METHOD_SERVICE) as android.view.inputmethod.InputMethodManager).hideSoftInputFromWindow(searchQuery.windowToken, 0)
searchQuery.clearFocus()
}
private fun showPlaces() {
placesDialog?.dismiss()
val center = phoneMap?.center() ?: service?.navigationState?.value?.position?.takeIf { it != GeoPoint(0.0, 0.0) } ?: GeoPoint(43.36, -5.85)
val box = column().apply { setPadding(dp(16), 0, dp(16), 0) }
box.addView(label("Lugares offline OSM · Asturias incluido y regiones instaladas. Distancia en línea recta desde el centro del mapa. Elegir destino calcula la ruta por Internet.", 13f))
val category = Spinner(this).apply { adapter = ArrayAdapter(this@MainActivity, android.R.layout.simple_spinner_dropdown_item, listOf("Todos") + PlaceCategory.entries.map { it.labelSpanish }) }
val query = edit("Nombre del lugar o negocio").apply { isSaveEnabled = false }
val status = label("Buscando en el catálogo local…", 13f)
val list = column()
box.addView(category); box.addView(query); box.addView(status)
box.addView(button("Ocultar marcadores") { placesGeneration++; placesJob?.cancel(); displayedPlaces = emptyList(); phoneMap?.setPlaces(emptyList()) })
box.addView(list)
val scroll = ScrollView(this).apply { addView(box) }
val dialog = AlertDialog.Builder(this).setTitle("Lugares cerca del mapa").setView(scroll).setPositiveButton("Cerrar", null).create()
placesDialog = dialog
fun refresh(debounce: Boolean) {
placesJob?.cancel(); val generation = ++placesGeneration
val text = query.text.toString()
val selected = PlaceCategory.entries.getOrNull(category.selectedItemPosition - 1)
placesJob = scope.launch {
try {
if (debounce) delay(250)
status.text = "Consultando catálogo offline…"
val found = placeRepository.search(center, selected, text)
ensureActive(); if (generation != placesGeneration) return@launch
displayedPlaces = found; phoneMap?.setPlaces(found)
list.removeAllViews()
status.text = when {
!placeRepository.covers(center) -> "Sin catálogo instalado para este centro del mapa"
found.isEmpty() -> "Sin resultados en los datos OSM incluidos"
else -> "${found.size} lugares · ${if (text.isBlank()) "hasta 50 km" else "regiones instaladas"} · © OpenStreetMap contributors"
}
found.forEach { place ->
val distance = placeDistance(place)
list.addView(button("${place.name}\n${place.category.labelSpanish} · $distance${place.address?.let { " · $it" } ?: ""}") { showPlaceDetails(place) }.apply { maxLines = 3 })
}
} catch (cancelled: CancellationException) { throw cancelled }
catch (_: Exception) { if (generation == placesGeneration) status.text = "No se pudo leer el catálogo local · abre Lugares de nuevo" }
}
}
category.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { refresh(false) }
override fun onNothingSelected(parent: AdapterView<*>?) { }
}
query.addTextChangedListener(object : android.text.TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { }
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { refresh(true) }
override fun afterTextChanged(s: android.text.Editable?) { }
})
dialog.setOnDismissListener { placesGeneration++; placesJob?.cancel(); if (placesDialog === dialog) placesDialog = null }
dialog.show(); refresh(false)
}
private fun placeDistance(place: OfflinePlace): String = place.distanceMeters?.let { if (it < 1000) "${it.toInt()} m" else "%.1f km".format(java.util.Locale.ROOT, it / 1000) } ?: "distancia no disponible"
private fun showPlaceDetails(place: OfflinePlace) {
val text = listOfNotNull(place.category.labelSpanish + " · " + placeDistance(place) + " en línea recta", place.address?.let { "Dirección OSM: $it" }, place.openingHours?.let { "Horario OSM: $it\nNo se comprueba si está abierto ahora." }, place.website?.let { "Web OSM: $it" }, place.phone?.let { "Teléfono OSM: $it" }, "© OpenStreetMap contributors · extracto 28/09/2026. Los datos pueden faltar o haber cambiado.").joinToString("\n\n")
val box = column().apply { setPadding(dp(16), 0, dp(16), 0); addView(label(text, 14f)) }
place.website?.let { value ->
val uri = runCatching { Uri.parse(value.trim()) }.getOrNull()
if (uri?.scheme?.lowercase() in listOf("http", "https") && !uri?.host.isNullOrBlank()) box.addView(button("Abrir web") { try { startActivity(Intent(Intent.ACTION_VIEW, uri)) } catch (_: ActivityNotFoundException) { hint.text = "No hay navegador disponible" } })
}
place.phone?.takeIf { it.length <= 100 && it.matches(Regex("[+0-9() .;/-]+")) }?.let { value -> box.addView(button("Marcar teléfono") { try { startActivity(Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", value, null))) } catch (_: ActivityNotFoundException) { hint.text = "No hay aplicación de teléfono" } }) }
AlertDialog.Builder(this).setTitle(place.name).setView(ScrollView(this).apply { addView(box) }).setPositiveButton("Elegir destino") { _, _ ->
placesDialog?.dismiss()
chooseDestination(place.position, place.name, "© OpenStreetMap contributors")
}.setNegativeButton("Cerrar", null).show()
}
private fun chooseMotorcycle() {
try {
val adapter = getSystemService(BluetoothManager::class.java).adapter
if (adapter == null || !adapter.isEnabled) { hint.text = "Activa Bluetooth para conectar Yamaha"; startActivity(Intent(Settings.ACTION_BLUETOOTH_SETTINGS)); return }
val paired = adapter.bondedDevices.sortedBy { it.name ?: "" }
if (paired.isEmpty()) { hint.text = "Empareja Yamaha en los ajustes Bluetooth"; startActivity(Intent(Settings.ACTION_BLUETOOTH_SETTINGS)); return }
AlertDialog.Builder(this).setTitle("Conectar Yamaha").setItems(paired.map { it.name ?: "Dispositivo emparejado" }.toTypedArray()) { _, which ->
motorcyclePreferences.edit().putString("address", paired[which].address).putString("name", paired[which].name ?: "Yamaha").putBoolean("auto", true).putBoolean("paused", false).apply()
connectRemembered(false, replace = true)
}.setNegativeButton("Cerrar", null).setNeutralButton("Desconectar TFT") { _, _ -> service?.disconnect() }.show()
} catch (_: SecurityException) { refreshPermissions(); hint.text = "Bluetooth necesita permiso de dispositivos cercanos" }
}
private fun showSettings() {
val current = service ?: return
val content = column().apply { setPadding(dp(16), 0, dp(16), 0) }
fun entry(title: String, initial: String): EditText { content.addView(label(title, 14f)); return edit(title).apply { setText(initial); content.addView(this) } }
content.addView(Switch(this).apply {
text = "Indicaciones de voz"
isChecked = current.voiceEnabled.value
setOnCheckedChangeListener { _, enabled -> current.setVoiceEnabled(enabled) }
})
content.addView(button("Idioma de voz y ruta · ${current.voiceLanguageSelection()}") {
val selections = listOf(NavigationVoicePreferences.SYSTEM) + GuidanceLanguage.entries.map { it.tag }
val names = listOf("Idioma del sistema / System language") + GuidanceLanguage.entries.map { it.nativeName }
AlertDialog.Builder(this).setTitle("Idioma de navegación / Navigation language")
.setSingleChoiceItems(names.toTypedArray(), selections.indexOf(current.voiceLanguageSelection())) { dialog, index ->
current.setVoiceLanguage(selections[index])
hint.text = "Idioma guardado · se aplicará a la próxima ruta / Applies to the next route"
dialog.dismiss()
}.setNegativeButton("Cerrar", null).show()
})
val voiceStatusLabel = label(current.voiceStatus.value, 13f)
content.addView(voiceStatusLabel)
content.addView(button("Configurar voz de Android") {
try { startActivity(Intent("com.android.settings.TTS_SETTINGS")) }
catch (_: ActivityNotFoundException) { openAppSettings() }
})
val routeEndpoint = entry("Servidor Valhalla HTTPS", current.routingEndpoint())
val geocoderEndpoint = entry("Servidor búsqueda HTTPS", getSharedPreferences("geocoder", MODE_PRIVATE).getString("endpoint", NominatimGeocoder.DEFAULT_ENDPOINT) ?: NominatimGeocoder.DEFAULT_ENDPOINT)
val catalogPreferences = getSharedPreferences("regional_downloads", MODE_PRIVATE)
val catalogUrl = entry("Catálogo de regiones HTTPS · repositorio de confianza", catalogPreferences.getString("url", DEFAULT_REGIONAL_CATALOG) ?: DEFAULT_REGIONAL_CATALOG)
content.addView(button("Guardar catálogo de regiones") {
try {
val address = catalogUrl.text.toString().trim()
if (address.isNotEmpty()) RegionalDownloadManager.validateAddress(address)
catalogPreferences.edit().putString("url", address).apply()
hint.text = "Catálogo guardado"
} catch (_: Exception) { hint.text = "Revisa la URL HTTPS del catálogo" }
})
val source = current.mapSource()
val style = entry("Estilo de mapa HTTPS · vacío para predeterminado", if (source.uri.startsWith("asset://")) "" else source.uri)
content.addView(label("Créditos obligatorios del proveedor: ${source.attribution} (no editables)", 13f))
content.addView(button("Guardar servidores y mapa") {
try {
ValhallaRoutingEngine.validateEndpoint(routeEndpoint.text.toString()); NominatimGeocoder.validateEndpoint(geocoderEndpoint.text.toString())
getSharedPreferences("routing", MODE_PRIVATE).edit().putString("endpoint", routeEndpoint.text.toString().trim()).apply()
getSharedPreferences("geocoder", MODE_PRIVATE).edit().putString("endpoint", geocoderEndpoint.text.toString().trim()).apply()
current.saveMapSource(style.text.toString(), source.attribution); phoneMap?.loadStyle(current.mapSource()); phoneMap?.refreshPlaces(); credits.text = compactAttribution(current.mapSource().attribution)
hint.text = "Configuración guardada"
} catch (_: Exception) { hint.text = "Revisa endpoints y estilo HTTPS" }
})
content.addView(label("Yamaha: ${motorcyclePreferences.getString("name", "sin seleccionar")}", 14f))
content.addView(Switch(this).apply { text = "Conectar Yamaha automáticamente"; isChecked = motorcyclePreferences.getBoolean("auto", true); setOnCheckedChangeListener { _, enabled -> motorcyclePreferences.edit().putBoolean("auto", enabled).apply(); if (enabled) { motorcyclePreferences.edit().putBoolean("paused", false).apply(); tryAutoConnect() } } })
content.addView(button("Cambiar Yamaha") { withPermissions(Action.CHANGE_CONNECT) })
content.addView(button("Olvidar Yamaha") { service?.disconnect(); motorcyclePreferences.edit().remove("address").remove("name").apply(); hint.text = "Yamaha olvidada" })
content.addView(button("Desconectar Yamaha") { service?.disconnect() })
content.addView(button("Mapas offline") { showOfflineMaps() })
content.addView(button("Permisos de NavFrame") { openAppSettings() })
val alertPreferences = getSharedPreferences("navigation_alerts", MODE_PRIVATE)
content.addView(Switch(this).apply {
text = "Avisos de posibles radares fijos"
isChecked = alertPreferences.getBoolean("radars_enabled", false)
setOnCheckedChangeListener { _, enabled -> alertPreferences.edit().putBoolean("radars_enabled", enabled).apply() }
})
content.addView(label("Datos comunitarios OSM, incompletos. Distancia aproximada; comprueba la normativa del país y respeta siempre las señales. © OpenStreetMap contributors · ODbL", 12f))
content.addView(button("Ajustes de ubicación") { startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)) })
content.addView(button("Batería · optimización") { try { startActivity(Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)) } catch (_: ActivityNotFoundException) { openAppSettings() } })
content.addView(label("Para pantalla apagada en Xiaomi, permite batería sin restricciones. La app no cambia estos ajustes.", 13f))
content.addView(button("Opciones avanzadas") { showAdvanced() })
val scroll = ScrollView(this).apply { addView(content) }
val dialog = AlertDialog.Builder(this).setTitle("Configuración").setView(scroll).setPositiveButton("Cerrar", null).create()
val voiceObserver = scope.launch { current.voiceStatus.collect { voiceStatusLabel.text = it } }
dialog.setOnDismissListener { voiceObserver.cancel() }
dialog.show()
}
private fun showAdvanced() {
val choices = arrayOf("Conectar simulador TFT", "Prueba TFT nativa", "Navegación sintética", "Mapa DEMO sin ruta", "Recalcular ruta GPS", "Detener toda navegación", "Keepalive TFT 0,5 s", "Keepalive TFT 1 s", "Keepalive TFT 2 s", "Introducir destino por coordenadas", "Ver imagen TFT")
AlertDialog.Builder(this).setTitle("Opciones avanzadas").setItems(choices) { _, index -> when(index) {
0 -> service?.connectFake(); 1 -> service?.sendTestFrame(false); 2 -> service?.startDemo(); 3 -> service?.startDemo(true); 4 -> service?.requestReroute(); 5 -> service?.stopNavigation(); 6 -> service?.setInterval(500); 7 -> service?.setInterval(1_000); 8 -> service?.setInterval(2_000); 9 -> coordinates(); 10 -> {
val preview = TftPreviewView(this); service?.lastFrame?.value?.let { preview.showFrame(it) }
AlertDialog.Builder(this).setTitle("Imagen TFT 480 × 240").setView(preview).setPositiveButton("Cerrar", null).show()
}
} }.setNegativeButton("Cerrar", null).show()
}
private fun coordinates() {
val box = column(); val latitude = edit("Latitud"); val longitude = edit("Longitud"); box.addView(latitude); box.addView(longitude)
AlertDialog.Builder(this).setTitle("Destino por coordenadas").setView(box).setPositiveButton("Elegir") { _, _ ->
try { val point = GeoPoint(latitude.text.toString().replace(',', '.').toDouble(), longitude.text.toString().replace(',', '.').toDouble()); ValhallaRoutingEngine.validatePoint(point); positionWait?.cancel(); service?.selectSearchDestination(); destination = point; destinationName = "Destino por coordenadas"; hint.text = destinationName; showRouteSheet(); withPermissions(Action.CALCULATE) }
catch (_: Exception) { hint.text = "Coordenadas fuera de rango" }
}.setNegativeButton("Cancelar", null).show()
}
private fun showInfo() {
val text = "NavFrame 0.11.0 · mapas OpenStreetMap. Móvil y Yamaha comparten estado; el TFT se renderiza directamente a 480 × 240, sin captura de pantalla.\n\nDEMO es ficticia. GPS/ETA/guiado deben probarse en condiciones reales. Rutas y búsqueda necesitan conexión; los mapas y lugares incluidos de Asturias se consultan offline. Calcular rutas sigue necesitando Internet.\n\nNominatim recibe el texto de búsqueda, no tu GPS. No envíes información personal/confidencial. Prototipo con máximo 1 petición/s agregado y caché.\n\nNaviLite adaptado de Pillion · PolyForm Noncommercial 1.0.0\nRequired Notice: Copyright 2026 the Pillion authors\n\nFuente online predeterminada incluida: OpenFreeMap · © OpenMapTiles · © OpenStreetMap contributors.\n\nAsturias offline: datos © OpenStreetMap contributors, extracto Geofabrik 28/09/2026, licencia ODbL. Límites 42,9–43,75 N / 7,2–4,45 O; zoom 6–14. Tipografía Noto Sans, SIL OFL 1.1."
val box = column().apply { setPadding(dp(16), 0, dp(16), 0); addView(label(text + "\n\nFuente activa: ${service?.mapSource()?.attribution ?: ConfiguredMapDataSource.DEFAULT_ATTRIBUTION}\nSi una fuente personalizada no declara atribución, corrige el estilo en Ajustes.", 14f)); addView(button("Diagnóstico del mapa TFT") { showMapDiagnostic() }) }
AlertDialog.Builder(this).setTitle("Información y licencias").setView(ScrollView(this).apply { addView(box) }).setPositiveButton("Cerrar", null).setNeutralButton("Licencias") { _, _ -> showLicenses() }.setNegativeButton("Política búsqueda") { _, _ -> openUrl("https://operations.osmfoundation.org/policies/nominatim/") }.show()
}
private fun showMapDiagnostic() {
val report = service?.diagnosticReport() ?: "Servicio no disponible"
AlertDialog.Builder(this).setTitle("Diagnóstico TFT").setMessage(report).setPositiveButton("Cerrar", null)
.setNeutralButton("Compartir") { _, _ -> startActivity(Intent.createChooser(Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, report), "Compartir diagnóstico")) }.show()
}
private fun showLicenses() {
val files = arrayOf("PILLION_LICENSE.md", "MAPLIBRE_LICENSE.md", "GSON_LICENSE.md", "OFFLINE_FONT_LICENSE.md", "OFFLINE_DATA_LICENSE.md")
AlertDialog.Builder(this).setTitle("Licencias").setItems(arrayOf("Pillion", "MapLibre", "Gson", "Noto Sans · SIL OFL", "Datos Asturias · ODbL")) { _, which ->
val text = assets.open(files[which]).bufferedReader().use { it.readText() }
AlertDialog.Builder(this).setTitle(files[which]).setMessage(text).setPositiveButton("Cerrar", null).setNeutralButton("Créditos OSM") { _, _ -> openUrl("https://www.openstreetmap.org/copyright") }.show()
}.show()
}
private fun showOfflineMaps() {
offlineDialog?.dismiss()
val box = column().apply { setPadding(dp(16), 0, dp(16), 0) }
box.addView(label("Paquetes regionales locales: mapa y lugares OSM juntos. Importa un archivo .navframe para instalar o añadir una actualización; las versiones anteriores se conservan. Rutas y búsqueda de direcciones necesitan Internet. Límite total: 1 GiB.", 14f))
box.addView(button("Descargar regiones por país") { showRegionalCatalog() })
box.addView(button("Importar/actualizar región (.navframe)") { startActivityForResult(Intent(Intent.ACTION_OPEN_DOCUMENT).setType("*/*").addCategory(Intent.CATEGORY_OPENABLE), 74) })
box.addView(button("Instalar Asturias incluido") { importOffline { offlineManager.installBundledAsturias() } })
box.addView(button("Importar PMTiles NavFrame") { startActivityForResult(Intent(Intent.ACTION_OPEN_DOCUMENT).setType("*/*").addCategory(Intent.CATEGORY_OPENABLE), 73) })
box.addView(button("Cancelar instalación/importación") { offlineTask?.cancel(); hint.text = "Importación cancelada" })
box.addView(button("Usar mapa online predeterminado") { selectMapSource(TileSource("asset://map/tft-style.json", ConfiguredMapDataSource.DEFAULT_ATTRIBUTION)) })
val regionalPacks = column(); box.addView(regionalPacks)
val installProgress = label("", 13f); box.addView(installProgress)
val packs = column(); box.addView(packs)
val scroll = ScrollView(this).apply { addView(box) }
val dialog = AlertDialog.Builder(this).setTitle("Mapas offline").setView(scroll).setPositiveButton("Cerrar", null).create()
offlineDialog = dialog
val collector = scope.launch {
offlineManager.packs.collect { regions ->
packs.removeAllViews()
regions.forEach { pack ->
val size = "%.1f MiB".format(java.util.Locale.ROOT, pack.completedBytes / 1048576.0)
packs.addView(label("${pack.name} · $size · ${if (pack.state == OfflinePackState.READY) "listo" else "copiando…"}", 14f))
if (pack.state == OfflinePackState.READY) {
packs.addView(button("Usar ${pack.name}") { selectMapSource(pack.source) })
packs.addView(button("Borrar ${pack.name}") {
scope.launch {
try {
if (service?.mapSource()?.uri == pack.source.uri) {
check(selectMapSource(TileSource("asset://map/tft-style.json", ConfiguredMapDataSource.DEFAULT_ATTRIBUTION)))
rebuildPhoneMap() // Release native readers before removing an active private archive.
}
offlineManager.delete(pack.id)
hint.text = "Paquete offline borrado"
} catch (_: Exception) { hint.text = "No se pudo borrar el paquete" }
}
})
}
}
}
}
val regionalCollector = scope.launch {
regionalManager.regions.collect { regions ->
regionalPacks.removeAllViews()
regions.forEach { region ->
regionalPacks.addView(label("${region.manifest.name} · ${region.manifest.version} · OSM ${region.manifest.osmTimestamp.take(10)} · %.1f MiB · mapa y lugares".format(java.util.Locale.ROOT, region.bytes / 1048576.0), 14f))
regionalPacks.addView(button("Usar ${region.manifest.name} ${region.manifest.version}") { selectMapSource(region.source) })
regionalPacks.addView(button("Borrar ${region.manifest.name} ${region.manifest.version}") {
scope.launch {
try {
if (service?.mapSource()?.uri == region.source.uri) {
check(selectMapSource(TileSource("asset://map/tft-style.json", ConfiguredMapDataSource.DEFAULT_ATTRIBUTION)))
rebuildPhoneMap()
}
regionalManager.delete(region.folderId)
displayedPlaces = emptyList(); phoneMap?.setPlaces(emptyList())
hint.text = "Región borrada"
} catch (_: Exception) { hint.text = "No se pudo borrar la región" }
}
})
}
}
}
val progressCollector = scope.launch {
regionalManager.progress.collect { value -> installProgress.text = value?.let { "${it.stage} · ${it.completed / 1048576} MiB${it.total?.let { total -> " / ${total / 1048576} MiB" } ?: ""}" } ?: "" }
}
dialog.setOnDismissListener { regionalCollector.cancel(); progressCollector.cancel(); collector.cancel(); if (offlineDialog === dialog) offlineDialog = null }
dialog.show()
scope.launch { offlineManager.refresh(); regionalManager.refresh() }
}
private fun showRegionalCatalog() {
val address = getSharedPreferences("regional_downloads", MODE_PRIVATE).getString("url", DEFAULT_REGIONAL_CATALOG).orEmpty()
val box = column().apply { setPadding(dp(16), 0, dp(16), 0) }
val query = edit("Buscar país o región")
box.addView(query)
val status = label("Cargando catálogo…", 14f); box.addView(status)
val rows = column(); box.addView(rows)
val progress = label("", 13f); box.addView(progress)
box.addView(button("Cancelar descarga") { offlineTask?.cancel() })
box.addView(label("Mantén NavFrame abierto durante la descarga. Se comprueba el archivo antes de instalarlo. Rutas y direcciones necesitan Internet.", 13f))
val dialog = AlertDialog.Builder(this).setTitle("Regiones del mundo").setView(ScrollView(this).apply { addView(box) }).setPositiveButton("Cerrar", null).create()
var entries = emptyList<RegionalCatalogEntry>()
fun render() {
rows.removeAllViews()
val search = query.text.toString().trim()
val filtered = entries.filter { "${it.manifest.name} ${it.country.orEmpty()} ${it.countryCode.orEmpty()} ${it.region.orEmpty()}".contains(search, ignoreCase = true) }
status.text = if (entries.isEmpty()) "No hay regiones publicadas" else "${filtered.size} regiones · ${entries.size} en catálogo"
filtered.take(100).forEach { item ->
val m = item.manifest
val size = "%.1f MiB".format(java.util.Locale.ROOT, item.archive.bytes / 1048576.0)
val cameras = item.cameraCount?.let { " · $it cámaras OSM" }.orEmpty()
rows.addView(label("${item.country.orEmpty()} · ${m.name} · $size$cameras\nCobertura: ${m.bounds.south}, ${m.bounds.west} a ${m.bounds.north}, ${m.bounds.east} · OSM ${m.osmTimestamp.take(10)}", 13f))
rows.addView(button("Instalar ${m.name}") {
if (offlineTask?.isActive == true) { hint.text = "Espera o cancela la instalación actual"; return@button }
offlineTask = scope.launch {
try {
val installed = regionalDownloads.install(address, item)
selectMapSource(installed.source)
phoneMap?.refreshPlaces()
status.text = "${m.name} instalado"
} catch (cancelled: CancellationException) { status.text = "Descarga cancelada"; throw cancelled }
catch (_: Exception) { status.text = "No se pudo instalar: revisa conexión, espacio y catálogo" }
}
})
}
if (filtered.size > 100) rows.addView(label("Afina la búsqueda para ver más regiones", 13f))
}
query.addTextChangedListener(object : android.text.TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { render() }
override fun afterTextChanged(s: android.text.Editable?) = Unit
})
val loading = scope.launch {
try {
require(address.isNotBlank())
entries = regionalDownloads.fetchCatalog(address).regions.sortedWith(compareBy({ it.country.orEmpty() }, { it.manifest.name }))
render()
} catch (cancelled: CancellationException) { throw cancelled }
catch (_: Exception) { status.text = "Catálogo no disponible. Configura su URL en Ajustes o espera a que el repositorio publique regiones." }
}
val observing = scope.launch { regionalManager.progress.collect { p -> progress.text = p?.let { "${it.stage} · ${it.completed / 1048576} / ${(it.total ?: 0) / 1048576} MiB" }.orEmpty() } }
dialog.setOnDismissListener { loading.cancel(); observing.cancel() }
dialog.show()
}
private fun selectMapSource(source: TileSource): Boolean {
try {
val current = service ?: return false
current.saveMapSource(if (source.uri.startsWith("asset://")) "" else source.uri, source.attribution)
phoneMap?.loadStyle(current.mapSource()); phoneMap?.refreshPlaces(); credits.text = compactAttribution(current.mapSource().attribution)
hint.text = if (source.uri.startsWith("file://")) "Mapa offline activo · búsqueda y rutas necesitan Internet" else "Mapa online activo"
return true
} catch (_: Exception) { hint.text = "No se pudo activar la fuente de mapa"; return false }
}
private fun rebuildPhoneMap() {
phoneMap?.let { old -> if (uiResumed) old.onPause(); if (uiStarted) old.onStop(); old.onDestroy() }
mapHost.removeAllViews()
phoneMap = createPhoneMap(null)?.also {
mapHost.addView(it.view, FrameLayout.LayoutParams(-1, -1))
it.setPlaces(displayedPlaces)
if (uiStarted) it.onStart(); if (uiResumed) it.onResume()
service?.let { current -> it.loadStyle(current.mapSource()); it.update(current.navigationState.value) }
}
}
private fun importOffline(action: suspend () -> OfflineMapPack) {
if (offlineTask?.isActive == true) { hint.text = "Ya hay una importación en curso"; return }
offlineTask = scope.launch {
try { val pack = action(); hint.text = "${pack.name} listo · pulsa Usar en Mapas offline" }
catch (cancelled: CancellationException) { throw cancelled }
catch (error: Exception) { hint.text = error.message?.takeIf { error is IllegalArgumentException } ?: "No se pudo importar el mapa offline" }
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode !in listOf(73, 74) || resultCode != RESULT_OK) return
val uri = data?.data ?: return
showOfflineMaps()
if (requestCode == 74) {
if (offlineTask?.isActive == true) { hint.text = "Ya hay una importación en curso"; return }
offlineTask = scope.launch {
try {
val input = contentResolver.openInputStream(uri) ?: throw IllegalArgumentException("No se pudo abrir el archivo")
val region = regionalManager.importPackage(input)
hint.text = "${region.manifest.name} ${region.manifest.version} listo · pulsa Usar en Mapas offline"
} catch (cancelled: CancellationException) { throw cancelled }
catch (error: Exception) { hint.text = error.message?.takeIf { error is IllegalArgumentException } ?: "No se pudo importar la región" }
}
return
}
importOffline {
val input = contentResolver.openInputStream(uri) ?: throw IllegalArgumentException("No se pudo abrir el archivo")
offlineManager.importArchive(input, "Paquete importado")
}
}
private fun openAppSettings() { startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName"))) }
private fun openUrl(url: String) { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) }
private fun column() = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
private fun row() = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL }
private fun label(value: String, size: Float) = TextView(this).apply { text = value; textSize = size; setTextColor(Color.WHITE); setPadding(0, dp(3), 0, dp(3)) }
private fun edit(value: String) = EditText(this).apply { hint = value; setSingleLine(true); setTextColor(Color.WHITE); setHintTextColor(Color.LTGRAY) }
private fun rounded(color: Int, radius: Int) = android.graphics.drawable.GradientDrawable().apply { setColor(color); cornerRadius = dp(radius).toFloat() }
private fun button(title: String, action: () -> Unit) = Button(this).apply {
text = title; textSize = if (title.length == 1) 22f else 13f; isAllCaps = false; minHeight = dp(48); setTextColor(Color.WHITE)
background = android.graphics.drawable.StateListDrawable().apply {
addState(intArrayOf(-android.R.attr.state_enabled), rounded(0xFF31413F.toInt(), 16))
addState(intArrayOf(android.R.attr.state_pressed), rounded(0xFF365A56.toInt(), 16))
addState(intArrayOf(), rounded(0xEE24333F.toInt(), 16))
}
setPadding(dp(12), dp(8), dp(12), dp(8)); setOnClickListener { action() }
}
private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt()
}
@@ -0,0 +1,113 @@
package dev.navframe.app
import android.graphics.*
import dev.navframe.core.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
import kotlin.math.roundToInt
/** Native JPEG overlay, independent of a map SDK so its layout can be verified without GPU access. */
class MapFrameComposer {
suspend fun compose(map: Bitmap?, marker: PointF?, state: NavigationState, mode: NavigationMode, attribution: String, unavailable: Boolean = false, failureCode: String? = null): TftFrame = withContext(Dispatchers.Default) {
require(map == null || (map.width == 480 && map.height == 240)) { "Bitmap dimensions invalid" }
val bitmap = Bitmap.createBitmap(480, 240, Bitmap.Config.ARGB_8888)
try {
val canvas = Canvas(bitmap)
canvas.drawColor(Color.rgb(13, 19, 25))
map?.let { canvas.drawBitmap(it, 0f, 0f, null) } // Same dimensions: no phone-resolution render or downscale.
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
fun text(value: String, x: Float, y: Float, size: Float, color: Int = Color.WHITE) {
paint.apply { this.color = color; textSize = size; style = Paint.Style.FILL; typeface = Typeface.create("sans-serif", Typeface.BOLD) }
canvas.drawText(value, x, y, paint)
}
val lost = state.navigationStatus == NavigationStatus.GPS_LOST
val accent = Color.rgb(80, 227, 194)
paint.color = Color.rgb(7, 12, 17)
canvas.drawRect(0f, 0f, 480f, 27f, paint)
text(if (mode == NavigationMode.MAP_DEMO) "MAPA · DEMO${if (state.route != null) " · RUTA" else " SIMULADO"}" else if (lost) "MAPA GPS · SIN SEÑAL" else if (state.route != null) "MAPA GPS · RUTA CALCULADA" else "MAPA GPS · SIN RUTA", 9f, 20f, 17f, if (lost) Color.YELLOW else accent)
if (map != null && marker != null) {
val x = marker.x
val y = marker.y
val arrow = Path().apply { moveTo(x, y - 19); lineTo(x + 14, y + 16); lineTo(x, y + 8); lineTo(x - 14, y + 16); close() }
paint.apply { color = if (lost) Color.GRAY else Color.WHITE; style = Paint.Style.FILL }
canvas.drawPath(arrow, paint)
paint.apply { color = if (lost) Color.YELLOW else accent; style = Paint.Style.STROKE; strokeWidth = 3f }
canvas.drawPath(arrow, paint)
}
if (unavailable || map == null) {
text(if (unavailable) "MAPA NO DISPONIBLE" else "ESPERANDO GPS", 60f, 109f, 27f)
text(if (unavailable) "TFT: ${failureCode ?: "SDK"} · ${if (lost) "SIN GPS" else "Info"}" else "No se usa una posición ficticia", 52f, 149f, 20f)
}
val guidanceVisible = state.route != null && state.navigationStatus != NavigationStatus.ROUTE_PREVIEW
state.route?.let { route ->
paint.style = Paint.Style.FILL
paint.color = Color.rgb(7, 12, 17)
canvas.drawRect(0f, 28f, 480f, if (guidanceVisible) 88f else 51f, paint)
if (!guidanceVisible) text("PREVIA · %.1f km · %d min".format(java.util.Locale.ROOT, route.distanceMeters / 1000.0, (route.durationSeconds + 59) / 60), 9f, 45f, 16f)
else {
val statusText = when {
unavailable || map == null -> "GUIADO EN ESPERA · SIN MAPA"
lost -> "SIN GPS · esperando posición precisa"
state.navigationStatus == NavigationStatus.REROUTING -> "RECALCULANDO · espera nueva ruta"
state.navigationStatus == NavigationStatus.OFF_ROUTE -> "FUERA DE RUTA · revisa el recorrido"
state.navigationStatus == NavigationStatus.ARRIVED -> "HAS LLEGADO AL DESTINO"
else -> null
}
if (statusText != null) text(statusText, 9f, 64f, 20f, if (state.navigationStatus == NavigationStatus.ARRIVED) accent else Color.YELLOW)
else {
val maneuver = state.nextManeuver
val direction = maneuverDirection(maneuver?.type).name
canvas.save()
canvas.translate(40f, 61f)
canvas.rotate(if (direction.contains("LEFT")) -90f else if (direction.contains("RIGHT")) 90f else 0f)
paint.apply { style = Paint.Style.STROKE; color = accent; strokeWidth = 7f; strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND }
val icon = Path().apply { moveTo(0f, 19f); lineTo(0f, -18f); moveTo(-13f, -5f); lineTo(0f, -18f); lineTo(13f, -5f) }
if (direction == "ARRIVAL") { canvas.drawLine(-10f, 20f, -10f, -20f, paint); val flag = Path().apply { moveTo(-10f, -20f); lineTo(17f, -12f); lineTo(-10f, -3f) }; canvas.drawPath(flag, paint) }
else if (direction.contains("ROUNDABOUT")) canvas.drawCircle(0f, 1f, 16f, paint)
else if (direction.contains("UTURN") || direction.contains("U_TURN")) { canvas.drawArc(-15f, -17f, 15f, 13f, 180f, 180f, false, paint); canvas.drawLine(-15f, -2f, -15f, 19f, paint); canvas.drawLine(15f, -2f, 15f, 19f, paint) }
else canvas.drawPath(icon, paint)
canvas.restore()
paint.strokeCap = Paint.Cap.BUTT
var instruction = maneuver?.instruction ?: "Continúa por la ruta"
paint.textSize = 18f
while (instruction.isNotEmpty() && paint.measureText(instruction) > 384f) instruction = instruction.dropLast(1)
text(instruction, 81f, 49f, 18f)
val next = state.distanceToNextManeuverMeters?.let { if (it >= 1000) "%.1f km".format(java.util.Locale.ROOT, it / 1000.0) else "$it m" } ?: "-- m"
text(next, 81f, 79f, 28f, accent)
}
}
}
// Wrap rather than clipping a custom provider's mandatory credits.
paint.typeface = Typeface.DEFAULT
paint.textSize = 12f
val lines = mutableListOf<String>()
var line = ""
for (character in attribution.trim().replace(Regex("\\s+"), " ")) {
val next = line + character
if (line.isNotEmpty() && paint.measureText(next) > 464f) { lines += line.trim(); line = character.toString() }
else line = next
}
if (line.isNotEmpty()) lines += line
val footer = (240f - lines.size * 15f - if (guidanceVisible) 55f else 34f).coerceAtLeast(27f)
paint.apply { color = Color.rgb(7, 12, 17); style = Paint.Style.FILL }
canvas.drawRect(0f, footer, 480f, 240f, paint)
val speed = if (lost || unavailable || map == null) "-- km/h" else "${(state.speed * 3.6f).roundToInt()} km/h"
text(speed, 9f, footer + 24f, 23f)
val heading = if (lost || unavailable || map == null || !state.bearing.isFinite()) "--" else state.bearing.roundToInt().toString()
text("Rumbo $heading°", 182f, footer + 24f, 20f)
text(if (mode == NavigationMode.MAP_DEMO) "DEMO" else "GPS", 393f, footer + 24f, 19f, accent)
if (guidanceVisible) {
val valid = !lost && !unavailable && map != null && state.navigationStatus in setOf(NavigationStatus.NAVIGATING, NavigationStatus.ARRIVED)
val remaining = if (valid) state.remainingDistanceMeters?.let { "%.1f km restantes".format(java.util.Locale.ROOT, it / 1000.0) } ?: "Restante --" else "Restante --"
val eta = if (valid) state.etaEpochMillis?.let { java.text.SimpleDateFormat("HH:mm", java.util.Locale.ROOT).format(java.util.Date(it)) } ?: "--:--" else "--:--"
text(remaining, 9f, footer + 44f, 17f)
text("ETA $eta", 285f, footer + 44f, 17f)
}
paint.apply { textSize = 12f; typeface = Typeface.DEFAULT; color = Color.WHITE }
lines.forEachIndexed { index, credit -> canvas.drawText(credit, 8f, footer + (if (guidanceVisible) 67f else 46f) + index * 15f, paint) }
val bytes = ByteArrayOutputStream().use { out -> check(bitmap.compress(Bitmap.CompressFormat.JPEG, 70, out)); out.toByteArray() }
TftFrame(encodedBytes = bytes, timestampMs = System.currentTimeMillis())
} finally { bitmap.recycle() }
}
}
@@ -0,0 +1,124 @@
package dev.navframe.app
import android.content.Context
import android.graphics.Bitmap
import android.graphics.PointF
import android.os.Handler
import android.os.Looper
import android.text.Html
import dev.navframe.core.*
import kotlinx.coroutines.*
import org.maplibre.android.MapLibre
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.Style
import org.maplibre.android.style.sources.GeoJsonSource
import org.maplibre.android.style.layers.LineLayer
import org.maplibre.android.style.layers.PropertyFactory.*
import org.maplibre.geojson.FeatureCollection
import org.maplibre.geojson.Feature
import org.maplibre.geojson.LineString
import org.maplibre.geojson.Point
import org.maplibre.android.snapshotter.MapSnapshotter
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
/** The service owns this dedicated 480×240 GPU snapshot target, not a phone MapView or Activity. */
class MapLibreTftRenderer(context: Context, private val source: MapDataSource, private val reportStage: (MapRenderStage) -> Unit = {}) : TftRenderer {
private val context = context.applicationContext
private val main = Handler(Looper.getMainLooper())
private val composer = MapFrameComposer()
private var snapshotter: MapSnapshotter? = null
private var closed = false
private var stage = MapRenderStage.INITIALIZE
private var capturedOnce = false
private fun phase(value: MapRenderStage) { stage = value; reportStage(value) }
private data class Raster(val bitmap: Bitmap, val marker: PointF, val attribution: String)
override suspend fun render(state: NavigationState) = render(state, NavigationMode.MAP_GPS)
suspend fun render(state: NavigationState, mode: NavigationMode): TftFrame = withContext(Dispatchers.Main.immediate) {
check(!closed)
val raster = try { withTimeout(if (capturedOnce) 10_000 else 30_000) { capture(state) } }
catch (cancelled: CancellationException) { currentCoroutineContext().ensureActive(); throw MapRenderException(MapRenderFailure.TIMEOUT, stage, MapErrorDetail(errorClass = "TimeoutCancellationException")) }
catch (error: Exception) { throw if (error is MapRenderException) error else MapRenderException(classifyMapRenderFailure(error.message), stage, mapErrorDetail(error.message, error.javaClass.simpleName)) }
capturedOnce = true
phase(MapRenderStage.COMPOSE)
try { composer.compose(raster.bitmap, raster.marker, state, mode, raster.attribution) }
finally { raster.bitmap.recycle() }
}
private suspend fun capture(state: NavigationState): Raster = suspendCancellableCoroutine { continuation ->
phase(MapRenderStage.INITIALIZE)
MapLibre.getInstance(context)
val position = LatLng(state.position.latitude, state.position.longitude)
val camera = TftCameraPolicy().parameters(state)
val cameraPosition = CameraPosition.Builder().target(position).zoom(camera.zoom)
.bearing(camera.bearingDegrees.toDouble()).padding(0.0, 70.0, 0.0, 0.0).build()
val current = snapshotter ?: run {
val tile = source.tileSource()
val builder = if (tile.uri.startsWith("asset://")) Style.Builder().fromJson(context.assets.open(tile.uri.removePrefix("asset://")).bufferedReader().use { it.readText() })
else Style.Builder().fromUri(tile.uri)
builder.withSources(GeoJsonSource("navframe-route", routeGeoJson(state.route)))
.withLayers(LineLayer("navframe-route-casing", "navframe-route").withProperties(lineColor("#071017"), lineWidth(11f)),
LineLayer("navframe-route-line", "navframe-route").withProperties(lineColor("#50e3c2"), lineWidth(7f)))
object : MapSnapshotter(context, MapSnapshotter.Options(480, 240).withPixelRatio(1f)
.withLogo(false).withAttribution(false).withStyleBuilder(builder).withCameraPosition(cameraPosition)) {
// SDK otherwise measures Android Views/logo even when both flags are false.
// Our native composer supplies all attribution, without density/theme-dependent SDK overlays.
override fun addOverlay(mapSnapshot: org.maplibre.android.snapshotter.MapSnapshot) = Unit
}.also {
snapshotter = it
it.setObserver(object : MapSnapshotter.Observer {
override fun onDidFinishLoadingStyle() { if (!closed && snapshotter === it) phase(MapRenderStage.STYLE_READY) }
override fun onStyleImageMissing(imageName: String) = Unit
})
}
}
current.setCameraPosition(cameraPosition)
(current.getSource("navframe-route") as? GeoJsonSource)?.setGeoJson(routeGeoJson(state.route))
continuation.invokeOnCancellation {
// An old callback must not be delivered into a new capture: discard after cancellation/error.
val cancel = { current.cancel(); if (snapshotter === current) snapshotter = null }
if (Looper.myLooper() == Looper.getMainLooper()) cancel() else main.post { cancel() }
}
try {
phase(if (current.getSource("navframe-route") == null) MapRenderStage.STYLE_LOADING else MapRenderStage.STYLE_READY)
current.start({ snapshot ->
if (continuation.isActive && !closed && snapshotter === current) phase(MapRenderStage.SNAPSHOT_READY)
val bitmap = snapshot.bitmap
val marker = snapshot.pixelForLatLng(position)
// SDK invokes ready BEFORE resetting its active flag; defer resume until reset finishes.
main.post {
if (continuation.isActive) {
val credits = snapshot.attributions.map { Html.fromHtml(it, Html.FROM_HTML_MODE_LEGACY).toString().trim() }.filter { it.isNotEmpty() }
val configured = source.tileSource().attribution
val attribution = if (source.tileSource().uri.startsWith("asset://")) configured else if (credits.isNotEmpty()) credits.distinct().joinToString(" · ") else configured
continuation.resume(Raster(bitmap, marker, attribution), onCancellation = { _, returned, _ -> returned.bitmap.recycle() })
} else bitmap.recycle()
}
}, { reason ->
main.post {
current.cancel()
if (snapshotter === current) snapshotter = null
if (continuation.isActive) continuation.resumeWithException(MapRenderException(classifyMapRenderFailure(reason), stage, mapErrorDetail(reason)))
}
})
} catch (error: Exception) {
current.cancel()
if (snapshotter === current) snapshotter = null
if (continuation.isActive) continuation.resumeWithException(error)
}
}
private fun routeGeoJson(route: RouteResult?): FeatureCollection =
if (route == null || route.geometry.size < 2) FeatureCollection.fromFeatures(emptyArray<Feature>())
else FeatureCollection.fromFeatures(arrayOf(Feature.fromGeometry(LineString.fromLngLats(route.geometry.map { Point.fromLngLat(it.longitude, it.latitude) }))))
/** Must be called on Main, just as the snapshotter was created there. */
fun close() {
check(Looper.myLooper() == Looper.getMainLooper())
closed = true
snapshotter?.cancel()
snapshotter = null
}
}
@@ -0,0 +1,46 @@
package dev.navframe.app
/** Only fixed labels cross this boundary; SDK messages can contain coordinates, URLs and access tokens. */
enum class MapRenderStage { INITIALIZE, STYLE_LOADING, STYLE_READY, SNAPSHOT_READY, COMPOSE }
enum class MapRenderFailure { TIMEOUT, NETWORK, STYLE, GPU, BITMAP, SDK }
enum class MapResourceKind { GLYPH, SPRITE, TILE, GEOJSON, STYLE, BITMAP, UNKNOWN }
enum class MapFailureReason { DNS, FORBIDDEN, NOT_FOUND, CONTEXT_LOST, EGL, MEMORY, PARSE, CONNECTION, UNKNOWN }
data class MapErrorDetail(val resource: MapResourceKind = MapResourceKind.UNKNOWN, val reason: MapFailureReason = MapFailureReason.UNKNOWN, val httpStatus: Int? = null, val errorClass: String = "SDK_CALLBACK") {
fun safeText(): String = "${resource.name}/${reason.name}${httpStatus?.let { "/HTTP_$it" } ?: ""}/${errorClass.takeIf { it.matches(Regex("[A-Za-z0-9_$]{1,80}")) } ?: "OTHER"}"
}
class MapRenderException(val failure: MapRenderFailure, val stage: MapRenderStage, val detail: MapErrorDetail = MapErrorDetail()) : Exception("${failure.name}:${stage.name}:${detail.safeText()}")
internal fun mapErrorDetail(message: String?, errorClass: String = "SDK_CALLBACK"): MapErrorDetail {
val text = message.orEmpty().lowercase(java.util.Locale.ROOT)
val status = Regex("\\b(?:http(?: status| error)?|status(?: code)?|server returned)\\D{0,12}([45]\\d{2})\\b").find(text)?.groupValues?.get(1)?.toIntOrNull()
val resource = when {
listOf("glyph", "font").any(text::contains) -> MapResourceKind.GLYPH
text.contains("sprite") -> MapResourceKind.SPRITE
text.contains("geojson") -> MapResourceKind.GEOJSON
text.contains("tile") || text.contains(".pbf") -> MapResourceKind.TILE
text.contains("style") || text.contains("json") -> MapResourceKind.STYLE
text.contains("bitmap") || text.contains("canvas") -> MapResourceKind.BITMAP
else -> MapResourceKind.UNKNOWN
}
val reason = when {
text.contains("dns") || text.contains("resolve") -> MapFailureReason.DNS
status == 403 || text.contains("forbidden") -> MapFailureReason.FORBIDDEN
status == 404 || text.contains("not found") -> MapFailureReason.NOT_FOUND
text.contains("context lost") -> MapFailureReason.CONTEXT_LOST
text.contains("egl") -> MapFailureReason.EGL
text.contains("memory") -> MapFailureReason.MEMORY
text.contains("parse") -> MapFailureReason.PARSE
text.contains("connection") || text.contains("socket") -> MapFailureReason.CONNECTION
else -> MapFailureReason.UNKNOWN
}
return MapErrorDetail(resource, reason, status, errorClass)
}
internal fun classifyMapRenderFailure(message: String?): MapRenderFailure {
val text = message.orEmpty().lowercase(java.util.Locale.ROOT)
return when {
listOf("egl", "opengl", "framebuffer", "shader", "gl context", "gl_context", "graphics context", "gpu").any(text::contains) -> MapRenderFailure.GPU
mapErrorDetail(message).httpStatus != null || listOf("resolve", "dns", "network", "connection", "socket", "server returned", "request failed", "failed to load resource", "failed to load tile", "failed to load glyph", "download").any(text::contains) -> MapRenderFailure.NETWORK
listOf("parse", "json", "style", "layer", "geojson").any(text::contains) -> MapRenderFailure.STYLE
listOf("bitmap", "canvas", "image size", "dimensions").any(text::contains) -> MapRenderFailure.BITMAP
else -> MapRenderFailure.SDK
}
}
@@ -0,0 +1,145 @@
package dev.navframe.app
import android.content.Context
import android.media.AudioAttributes
import android.media.AudioFocusRequest
import android.media.AudioManager
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.speech.tts.TextToSpeech
import android.speech.tts.UtteranceProgressListener
import dev.navframe.core.NavigationState
import dev.navframe.core.VoiceGuidancePolicy
import dev.navframe.core.GuidanceLanguage
import java.util.Locale
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
/** Owned by the navigation service, so activity closure and screen-off do not stop speech. */
internal class NavigationVoiceController(context: Context) {
private val context = context.applicationContext
private val preferences = context.getSharedPreferences("navigation_voice", Context.MODE_PRIVATE)
private val mutableEnabled = MutableStateFlow(preferences.getBoolean("enabled", true))
val enabled = mutableEnabled.asStateFlow()
private val mutableStatus = MutableStateFlow("Voz: preparando motor / Preparing speech engine")
val status = mutableStatus.asStateFlow()
private val main = Handler(Looper.getMainLooper())
private val audio = context.getSystemService(AudioManager::class.java)
private val attributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ASSISTANCE_NAVIGATION_GUIDANCE)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build()
private val focus = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK)
.setAudioAttributes(attributes).setOnAudioFocusChangeListener({ change ->
if (change < 0) stopSpeech()
}, main).build()
private var language = NavigationVoicePreferences.language(context)
private var policy = VoiceGuidancePolicy(language)
private var initialized = false
private var engine: TextToSpeech? = null
private var ready = false
private var closed = false
private var currentId: String? = null
private var serial = 0L
private var latest: NavigationState? = null
private val timeout = Runnable { stopSpeech() }
init {
engine = TextToSpeech(context.applicationContext) { result -> main.post {
if (closed) return@post
val tts = engine ?: return@post
initialized = result == TextToSpeech.SUCCESS
if (initialized) {
configure(language)
tts.setAudioAttributes(attributes)
tts.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
override fun onStart(id: String?) = Unit
override fun onDone(id: String?) { finish(id) }
@Deprecated("Legacy callback") override fun onError(id: String?) { finish(id) }
override fun onError(id: String?, code: Int) { finish(id) }
override fun onStop(id: String?, interrupted: Boolean) { finish(id) }
})
latest?.let(::update)
} else mutableStatus.value = "Motor de voz no disponible / Speech engine unavailable"
} }
}
private fun configure(selected: GuidanceLanguage) {
language = selected
val tts = engine ?: return
if (!initialized) return
val locale = Locale.forLanguageTag(selected.tag)
val available = tts.setLanguage(locale)
ready = available >= TextToSpeech.LANG_AVAILABLE
val spanish = selected == GuidanceLanguage.SPANISH
if (!ready) {
mutableStatus.value = if (spanish) "Voz ${selected.nativeName} no disponible: instala datos de voz en Android" else "${selected.nativeName} voice unavailable: install Android voice data"
return
}
tts.voices?.filter { it.locale.language == locale.language && !it.isNetworkConnectionRequired && it.features?.contains(TextToSpeech.Engine.KEY_FEATURE_NOT_INSTALLED) != true }
?.sortedByDescending { it.locale.country == locale.country }?.firstOrNull()?.let { tts.setVoice(it) }
if (tts.voice?.features?.contains(TextToSpeech.Engine.KEY_FEATURE_NOT_INSTALLED) == true) {
ready = false
mutableStatus.value = if (spanish) "Voz ${selected.nativeName}: instala datos de voz en Android" else "${selected.nativeName}: install Android voice data"
return
}
val network = tts.voice?.isNetworkConnectionRequired != false
mutableStatus.value = if (spanish) "Voz ${selected.nativeName} lista · ${if (network) "requiere Internet" else "sin Internet"}" else "${selected.nativeName} voice ready · ${if (network) "Internet required" else "offline"}"
}
fun languageChanged() {
stopSpeech()
val selected = latest?.route?.let { GuidanceLanguage.resolve(it.guidanceLanguage) } ?: NavigationVoicePreferences.language(context)
if (selected != language) policy = VoiceGuidancePolicy(selected)
configure(selected)
}
fun speakCameraAlert(distance: Int) { speakAlert(language.camera(distance)) }
fun setEnabled(enabled: Boolean) {
mutableEnabled.value = enabled
preferences.edit().putBoolean("enabled", enabled).apply()
if (!enabled) stopSpeech() else latest?.let(::update)
}
fun update(state: NavigationState) {
latest = state
val selected = state.route?.let { GuidanceLanguage.resolve(it.guidanceLanguage) } ?: NavigationVoicePreferences.language(context)
if (selected != language) { stopSpeech(); policy = VoiceGuidancePolicy(selected); configure(selected) }
if (state.route == null || state.navigationStatus == dev.navframe.core.NavigationStatus.ROUTE_PREVIEW) {
stopSpeech(); policy.reset(); return
}
// While muted, consume checkpoints so unmuting does not replay old instructions.
if (!ready && enabled.value) return
policy.announcement(state)?.let { speak(it) }
}
fun speak(text: String) {
if (closed || !ready || !enabled.value || text.isBlank()) return
if (audio.requestAudioFocus(focus) != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) return
val id = "nav-${++serial}-${SystemClock.elapsedRealtime()}"
currentId = id
main.removeCallbacks(timeout)
main.postDelayed(timeout, 20_000)
if (engine?.speak(text.take(1000), TextToSpeech.QUEUE_FLUSH, null, id) != TextToSpeech.SUCCESS) stopSpeech()
}
fun speakAlert(text: String) {
// A maneuver already being spoken takes priority over advisory alerts.
if (currentId == null) speak(text)
}
private fun finish(id: String?) { main.post { if (id != null && id == currentId) stopSpeech() } }
private fun stopSpeech() {
currentId = null
main.removeCallbacks(timeout)
engine?.stop()
audio.abandonAudioFocusRequest(focus)
}
fun reset() {
latest = null; policy.reset(); stopSpeech()
if (!closed) {
val selected = NavigationVoicePreferences.language(context)
if (selected != language) { policy = VoiceGuidancePolicy(selected); configure(selected) }
}
}
fun close() { closed = true; reset(); engine?.shutdown(); engine = null }
}
@@ -0,0 +1,16 @@
package dev.navframe.app
import android.content.Context
import dev.navframe.core.GuidanceLanguage
import java.util.Locale
internal object NavigationVoicePreferences {
const val SYSTEM = "system"
fun selection(context: Context): String = context.getSharedPreferences("navigation_voice", Context.MODE_PRIVATE).getString("language", "es-ES") ?: "es-ES"
fun language(context: Context): GuidanceLanguage = resolve(selection(context), Locale.getDefault().toLanguageTag())
fun resolve(selection: String, systemTag: String): GuidanceLanguage = GuidanceLanguage.resolve(if (selection == SYSTEM) systemTag else selection)
fun save(context: Context, selection: String) {
require(selection == SYSTEM || GuidanceLanguage.entries.any { it.tag == selection })
context.getSharedPreferences("navigation_voice", Context.MODE_PRIVATE).edit().putString("language", selection).apply()
}
}
@@ -0,0 +1,115 @@
package dev.navframe.app
import dev.navframe.core.*
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URI
import java.net.URLEncoder
import java.util.concurrent.atomic.AtomicReference
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
/** Button-triggered prototype search only: no autocomplete, GPS, viewbox or persisted query history. */
class NominatimGeocoder(
private val endpoint: String = DEFAULT_ENDPOINT,
private val openConnection: (String) -> HttpURLConnection = { URI(it).toURL().openConnection() as HttpURLConnection },
) : Geocoder {
init { validateEndpoint(endpoint) }
override suspend fun search(query: String): List<SearchResult> {
val parameters = nominatimSearchParameters(query)
val encoded = parameters.entries.joinToString("&") { (key, value) -> "${encode(key)}=${encode(value)}" }
val key = endpoint.trim() + "|" + encoded
cached(key)?.let { return it }
return withTimeout(20_000) {
gate.withLock {
cached(key)?.let { return@withLock it }
val now = clockMs()
if (now < (blockedUntil[endpoint.trim()] ?: 0L)) throw IOException("Proveedor en pausa: espera antes de buscar de nuevo")
val wait = 1_000 - (now - lastRequestMs)
if (wait > 0) delay(wait)
val response = request(endpoint.trim() + (if (endpoint.contains('?')) "&" else "?") + encoded)
val results = withContext(Dispatchers.Default) { parseNominatimResults(response) }
synchronized(cache) {
cache[key] = CacheEntry(clockMs(), results)
while (cache.size > 100) cache.remove(cache.keys.first())
}
results
}
}
}
private suspend fun request(url: String): String = coroutineScope {
suspendCancellableCoroutine { continuation ->
val connection = AtomicReference<HttpURLConnection?>()
val worker = launch(Dispatchers.IO) {
try {
ensureActive()
lastRequestMs = clockMs()
val http = openConnection(url)
connection.set(http)
ensureActive()
try {
http.requestMethod = "GET"
http.connectTimeout = 8_000; http.readTimeout = 12_000
http.instanceFollowRedirects = false
http.setRequestProperty("User-Agent", "NavFrame/0.6 (Android navigation prototype)")
http.setRequestProperty("Accept", "application/json")
val status = http.responseCode
if (status != 200) {
if (status == 429) {
val waitMs = retryAfterDelayMs(http.getHeaderField("Retry-After"))
val now = clockMs()
blockedUntil[endpoint.trim()] = if (waitMs > Long.MAX_VALUE - now) Long.MAX_VALUE else now + waitMs
}
throw IOException(if (status == 429) "Proveedor ocupado (HTTP429): espera antes de buscar de nuevo" else "Búsqueda no disponible (HTTP$status)")
}
val bytes = http.inputStream.use { input ->
val output = java.io.ByteArrayOutputStream()
val buffer = ByteArray(8192)
while (true) {
ensureActive()
val count = input.read(buffer)
if (count < 0) break
require(output.size() + count <= 1_000_000) { "Respuesta de búsqueda demasiado grande" }
output.write(buffer, 0, count)
}
output.toByteArray()
}
if (continuation.isActive) continuation.resume(bytes.toString(Charsets.UTF_8))
} finally { http.disconnect(); connection.set(null) }
} catch (error: Exception) {
if (continuation.isActive) continuation.resumeWithException(error)
}
}
continuation.invokeOnCancellation { connection.getAndSet(null)?.disconnect(); worker.cancel() }
}
}
companion object {
const val DEFAULT_ENDPOINT = "https://nominatim.openstreetmap.org/search"
private data class CacheEntry(val storedMs: Long, val results: List<SearchResult>)
private val cache = LinkedHashMap<String, CacheEntry>()
private val gate = Mutex()
private var lastRequestMs = 0L
private val blockedUntil = java.util.concurrent.ConcurrentHashMap<String, Long>()
private fun clockMs() = System.nanoTime() / 1_000_000
private fun cached(key: String): List<SearchResult>? = synchronized(cache) {
cache[key]?.takeIf { clockMs() - it.storedMs < 86_400_000 }?.results
}
private fun encode(value: String) = URLEncoder.encode(value, "UTF-8")
internal fun retryAfterDelayMs(header: String?, epochMs: Long = System.currentTimeMillis()): Long {
val normalized = header?.trim()
normalized?.toLongOrNull()?.takeIf { it >= 0 }?.let {
return if (it > Long.MAX_VALUE / 1_000) Long.MAX_VALUE else (it * 1_000).coerceAtLeast(1_000)
}
return try {
(java.time.ZonedDateTime.parse(normalized, java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME).toInstant().toEpochMilli() - epochMs).coerceAtLeast(1_000)
} catch (_: Exception) { 60_000 }
}
fun validateEndpoint(value: String) {
val uri = URI(value.trim())
require(uri.scheme == "https" && !uri.host.isNullOrBlank() && uri.userInfo == null && uri.fragment == null) { "Endpoint HTTPS inválido" }
}
}
}
@@ -0,0 +1,165 @@
package dev.navframe.app
import android.content.Context
import dev.navframe.core.TileSource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.io.File
import java.io.InputStream
import java.net.URI
import java.util.UUID
/** Private, persistent PMTiles packs; no tile scraping and no offline routing database. */
class OfflineMapManager(context: Context) {
private val context = context.applicationContext
private val root = File(this.context.filesDir, "offline")
private val mutablePacks = MutableStateFlow<List<OfflineMapPack>>(emptyList())
val packs: StateFlow<List<OfflineMapPack>> = mutablePacks.asStateFlow()
suspend fun refresh() = withContext(Dispatchers.IO) { gate.withLock { refreshLocked() } }
suspend fun installBundledAsturias(): OfflineMapPack {
val input = context.assets.open("offline/asturias.pmtiles")
return importArchive(input, "Asturias · OSM 2026-09-28", BUNDLED_ASTURIAS_BYTES)
}
/** Owns and closes input, including validation errors and cancellation. Cancellation removes partial copies. */
suspend fun importArchive(input: InputStream, name: String, totalBytes: Long? = null): OfflineMapPack = input.use { stream ->
require(name.isNotBlank() && name.length <= 100 && name.none { it.isISOControl() }) { "Nombre offline inválido" }
require(totalBytes == null || totalBytes in 127..MAX_ARCHIVE_BYTES) { "Archivo offline demasiado grande o vacío" }
withContext(Dispatchers.IO) {
gate.withLock {
refreshLocked()
require(mutablePacks.value.size < MAX_PACKS) { "Elimina una región antes de importar otra (máximo 3)" }
val existingBytes = root.walkTopDown().filter { it.isFile }.sumOf { it.length() }
val remainingBudget = minOf(MAX_ARCHIVE_BYTES, MAX_TOTAL_BYTES - existingBytes)
require(totalBytes == null || totalBytes <= remainingBudget) { "Límite de almacenamiento offline: 1 GiB" }
root.mkdirs()
require(root.usableSpace >= (totalBytes ?: MAX_ARCHIVE_BYTES) + 50L * 1024 * 1024) { "Espacio libre insuficiente para el mapa" }
val id = UUID.randomUUID().toString()
val folder = File(root, id)
check(folder.mkdir()) { "No se pudo crear la región offline" }
val archive = File(folder, "map.pmtiles")
val progress = OfflineMapPack(id, name.trim(), TileSource(localUri(File(folder, "style.json")), ATTRIBUTION),
0, OfflineBounds.ASTURIAS, 6, 14, OfflinePackState.IMPORTING, 0, totalBytes)
fun publish(bytes: Long) {
mutablePacks.value = mutablePacks.value.filterNot { it.id == id } + progress.copy(bytes = bytes, completedBytes = bytes)
}
publish(0)
var committed = false
try {
var bytes = 0L
var published = 0L
archive.outputStream().buffered().use { output ->
val buffer = ByteArray(64 * 1024)
while (true) {
currentCoroutineContext().ensureActive()
val count = stream.read(buffer)
if (count < 0) break
bytes += count
require(bytes <= remainingBudget) { "Límite de almacenamiento offline excedido" }
output.write(buffer, 0, count)
if (bytes - published >= 1024 * 1024) { publish(bytes); published = bytes }
}
}
currentCoroutineContext().ensureActive()
if (totalBytes != null) require(bytes == totalBytes) { "Copia offline incompleta" }
val info = PmtilesInfo.read(archive)
val style = OfflineMapStyle.create(localUri(archive))
File(folder, "style.json").writeText(style)
val metadata = JSONObject().put("version", 1).put("name", name.trim()).put("bytes", bytes)
File(folder, "pack.json").writeText(metadata.toString()) // Commit marker written after validation/resources.
committed = true
refreshLocked()
mutablePacks.value.first { it.id == id }.also {
check(it.bounds == info.bounds) { "Metadatos offline inconsistentes" }
}
} finally {
if (!committed) {
folder.deleteRecursively()
mutablePacks.value = mutablePacks.value.filterNot { it.id == id }
}
}
}
}
}
/** Caller must deselect this source and release renderers/MapView before deleting an active pack. */
suspend fun delete(id: String) = withContext(Dispatchers.IO) {
gate.withLock {
require(ID_PATTERN.matches(id)) { "Identificador offline inválido" }
val folder = File(root, id)
require(folder.canonicalFile.parentFile == root.canonicalFile) { "Región offline inválida" }
check(!folder.exists() || folder.deleteRecursively()) { "No se pudo eliminar la región offline" }
refreshLocked()
}
}
fun approvedSource(uri: String): Boolean = isApprovedSource(context, uri)
private fun refreshLocked() {
root.mkdirs()
mutablePacks.value = root.listFiles().orEmpty().filter { it.isDirectory && ID_PATTERN.matches(it.name) }.mapNotNull { folder ->
try {
if (File(folder, "region.json").isFile) return@mapNotNull null
val marker = File(folder, "pack.json")
if (!marker.isFile) {
folder.deleteRecursively() // Recover an interrupted copy; the shared gate excludes active imports.
return@mapNotNull null
}
if (marker.length() > 4096) return@mapNotNull null
val metadata = JSONObject(marker.readText())
if (metadata.getInt("version") != 1 || !File(folder, "style.json").isFile) return@mapNotNull null
val archive = File(folder, "map.pmtiles")
val info = PmtilesInfo.read(archive)
OfflineMapPack(folder.name, metadata.getString("name").take(100),
TileSource(localUri(File(folder, "style.json")), ATTRIBUTION), archive.length(), info.bounds,
info.minZoom, info.maxZoom, OfflinePackState.READY, archive.length(), archive.length())
} catch (_: Exception) { null } // Incomplete/invalid packs are never selectable.
}.sortedBy { it.name }
}
companion object {
const val ATTRIBUTION = "© OpenStreetMap contributors"
const val BUNDLED_ASTURIAS_BYTES = 34_617_483L
const val MAX_ARCHIVE_BYTES = 500L * 1024 * 1024
const val MAX_TOTAL_BYTES = 1024L * 1024 * 1024
const val MAX_PACKS = 3
private val ID_PATTERN = Regex("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
internal val gate = Mutex()
fun isApprovedSource(context: Context, uri: String): Boolean = try {
val value = URI(uri)
if (value.scheme != "file" || value.authority != null || value.query != null || value.fragment != null) false else {
val file = File(value).canonicalFile
val root = File(context.applicationContext.filesDir, "offline").canonicalFile
val folder = file.parentFile
file.name == "style.json" && file.isFile && folder != null && ID_PATTERN.matches(folder.name) &&
folder.parentFile == root && File(folder, "pack.json").isFile
}
} catch (_: Exception) { false }
}
}
enum class OfflinePackState { IMPORTING, READY }
data class OfflineBounds(val south: Double, val west: Double, val north: Double, val east: Double) {
init {
require(listOf(south, west, north, east).all { it.isFinite() })
require(south >= -85.051129 && north <= 85.051129 && south < north && west >= -180 && east <= 180 && west < east)
require(north - south <= 5 && east - west <= 10) { "Importa una región acotada, no el planeta" }
}
fun contains(latitude: Double, longitude: Double): Boolean = latitude in south..north && longitude in west..east
companion object { val ASTURIAS = OfflineBounds(42.9, -7.2, 43.75, -4.45) }
}
data class OfflineMapPack(val id: String, val name: String, val source: TileSource, val bytes: Long,
val bounds: OfflineBounds, val minZoom: Int, val maxZoom: Int, val state: OfflinePackState,
val completedBytes: Long, val totalBytes: Long?)
private fun localUri(file: File): String = file.toURI().toASCIIString().replaceFirst("file:/", "file:///")
@@ -0,0 +1,43 @@
package dev.navframe.app
import org.json.JSONArray
import org.json.JSONObject
/** Original local style for the original NavFrame MVT schema; no network resources. */
object OfflineMapStyle {
fun create(archiveFileUri: String): String {
require(archiveFileUri.startsWith("file:///")) { "Archivo offline local inválido" }
val layers = JSONArray()
fun layer(id: String, type: String, sourceLayer: String?, paint: JSONObject, layout: JSONObject? = null, minZoom: Int? = null) {
val item = JSONObject().put("id", id).put("type", type).put("paint", paint)
if (sourceLayer != null) item.put("source", "offline").put("source-layer", sourceLayer)
if (layout != null) item.put("layout", layout)
if (minZoom != null) item.put("minzoom", minZoom)
layers.put(item)
}
layer("background", "background", null, JSONObject().put("background-color", "#101820"))
layer("green", "fill", "landuse", JSONObject().put("fill-color", "#172d26"))
layer("water", "fill", "water", JSONObject().put("fill-color", "#173b57"))
layer("rivers", "line", "waterway", JSONObject().put("line-color", "#245777").put("line-width", 1.5))
layer("buildings", "fill", "building", JSONObject().put("fill-color", "#283039"), minZoom = 14)
layer("roads-case", "line", "roads", JSONObject().put("line-color", "#0a0e14")
.put("line-width", JSONArray("[\"interpolate\",[\"linear\"],[\"zoom\"],6,1.5,14,6,18,13]")),
JSONObject().put("line-cap", "round").put("line-join", "round"))
layer("roads", "line", "roads", JSONObject()
.put("line-color", JSONArray("[\"match\",[\"get\",\"class\"],[\"motorway\",\"motorway_link\",\"trunk\",\"trunk_link\"],\"#e6a34c\",[\"primary\",\"primary_link\",\"secondary\",\"secondary_link\"],\"#d6cba8\",[\"path\",\"footway\",\"cycleway\",\"steps\",\"track\"],\"#6e8187\",\"#aabac3\"]"))
.put("line-width", JSONArray("[\"interpolate\",[\"linear\"],[\"zoom\"],6,0.5,14,3,18,9]")),
JSONObject().put("line-cap", "round").put("line-join", "round"))
val textPaint = JSONObject().put("text-color", "#ecf1f4").put("text-halo-color", "#101820").put("text-halo-width", 1.5)
layer("road-labels", "symbol", "roads", textPaint, JSONObject().put("symbol-placement", "line")
.put("text-field", JSONArray("[\"coalesce\",[\"get\",\"name\"],[\"get\",\"ref\"],\"\"]"))
.put("text-font", JSONArray().put("Noto Sans Regular")).put("text-size", 11).put("text-max-angle", 30), 14)
layer("places", "symbol", "place", textPaint, JSONObject().put("text-field", JSONArray("[\"get\",\"name\"]"))
.put("text-font", JSONArray().put("Noto Sans Regular")).put("text-size", 13)
.put("text-max-width", 9).put("text-padding", 3))
return JSONObject().put("version", 8).put("name", "NavFrame offline TFT")
.put("glyphs", "asset://offline/fonts/{fontstack}/{range}.pbf")
.put("sources", JSONObject().put("offline", JSONObject().put("type", "vector")
.put("url", "pmtiles://$archiveFileUri").put("attribution", "© OpenStreetMap contributors")))
.put("layers", layers).toString()
}
}
@@ -0,0 +1,165 @@
package dev.navframe.app
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import dev.navframe.core.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import java.io.File
import java.io.IOException
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.security.MessageDigest
import kotlin.math.*
/** Bundled POIs are an independent regional catalog: installing it never replaces an installed map pack. */
class OfflinePlaceRepository(context: Context) {
private val context = context.applicationContext
private val file = File(this.context.filesDir, "places/asturias.sqlite")
private val regional = RegionalPackManager(this.context)
private var ready = false
private fun database() = SQLiteDatabase.openDatabase(file.path, null, SQLiteDatabase.OPEN_READONLY or SQLiteDatabase.NO_LOCALIZED_COLLATORS)
suspend fun install() = withContext(Dispatchers.IO) {
gate.withLock {
if (ready && file.isFile) return@withLock
file.parentFile?.mkdirs()
if (!file.isFile || digest(file) != BUNDLED_SHA256) {
val pending = File(file.path + ".part")
try {
context.assets.open(ASSET).use { input -> pending.outputStream().use { output ->
val buffer = ByteArray(64 * 1024)
while (true) {
currentCoroutineContext().ensureActive()
val count = input.read(buffer); if (count < 0) break
output.write(buffer, 0, count)
}
output.fd.sync()
} }
require(pending.length() == BUNDLED_BYTES && digest(pending) == BUNDLED_SHA256) { "Catálogo de lugares inválido" }
currentCoroutineContext().ensureActive()
Files.move(pending.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING)
} finally { pending.delete() }
}
database().use { db -> require(db.version == 1) { "Catálogo de lugares incompatible" } }
ready = true
}
}
/** Name/category text queries span installed catalogs; empty category browsing stays within 50 km. */
suspend fun search(center: GeoPoint, category: PlaceCategory? = null, query: String = "", limit: Int = 100): List<OfflinePlace> = withContext(Dispatchers.IO) {
require(center.latitude.isFinite() && center.longitude.isFinite())
require(query.length <= 200) { "Busca un nombre de hasta 200 caracteres" }
require(limit in 1..100)
val normalized = normalizePlaceSearch(query)
if (normalized.isNotEmpty() || OfflineBounds.ASTURIAS.contains(center.latitude, center.longitude)) install()
regional.withCatalogs { installed ->
val catalogs = RegionalPackManager.latest(installed)
val sources = catalogs.map { it.catalogFile to it.manifest } + if (file.isFile) listOf(file to null) else emptyList()
val radius = if (normalized.isEmpty()) 50_000.0 else Double.POSITIVE_INFINITY
val latDelta = 50_000.0 / 111_000
val lonDelta = latDelta / cos(Math.toRadians(center.latitude))
val where = if (normalized.isEmpty()) mutableListOf("latitude BETWEEN ? AND ?", "longitude BETWEEN ? AND ?") else mutableListOf()
val args = if (normalized.isEmpty()) mutableListOf((center.latitude - latDelta).toString(), (center.latitude + latDelta).toString(), (center.longitude - lonDelta).toString(), (center.longitude + lonDelta).toString()) else mutableListOf()
if (category != null) { where += "category = ?"; args += category.name }
if (normalized.isNotEmpty()) {
val matchingCategories = PlaceCategory.entries.filter { normalizePlaceSearch(it.labelSpanish).contains(normalized) || normalizePlaceSearch(it.name).contains(normalized) }
where += "(search_name LIKE ? ESCAPE '\\'" + matchingCategories.joinToString("") { " OR category = ?" } + ")"
args += "%${escapePlaceLike(normalized)}%"
args += matchingCategories.map { it.name }
}
val weight = cos(Math.toRadians(center.latitude)).pow(2)
args += listOf(center.latitude, center.latitude, center.longitude, center.longitude, weight).map { it.toString() }
val sql = "SELECT id,name,category,latitude,longitude,address,opening_hours,website,phone FROM places WHERE ${where.joinToString(" AND ")} ORDER BY (latitude-?)*(latitude-?)+(longitude-?)*(longitude-?)*? LIMIT 500"
try {
val found = mutableListOf<OfflinePlace>()
for ((source, manifest) in sources) {
SQLiteDatabase.openDatabase(source.path, null, SQLiteDatabase.OPEN_READONLY or SQLiteDatabase.NO_LOCALIZED_COLLATORS).use { db -> db.rawQuery(sql, args.toTypedArray()).use { cursor ->
while (cursor.moveToNext()) {
currentCoroutineContext().ensureActive()
val point = GeoPoint(cursor.getDouble(3), cursor.getDouble(4))
val distance = distance(center, point)
if (distance > radius || (manifest != null && !manifest.covers(point)) ||
(manifest == null && !OfflineBounds.ASTURIAS.contains(point.latitude, point.longitude))) continue
fun optional(column: Int): String? = if (cursor.isNull(column)) null else cursor.getString(column)
found += OfflinePlace(cursor.getString(0), cursor.getString(1), PlaceCategory.valueOf(cursor.getString(2)), point, optional(5), optional(6), optional(7), optional(8), distance)
}
} }
}
found.sortedBy { it.distanceMeters }.distinctBy { it.id }.take(limit)
} catch (error: android.database.SQLException) { ready = false; throw IOException("No se pudo leer el catálogo de lugares") }
}
}
/** Camera-only local query: never obtains location or contacts a network provider. */
suspend fun visible(viewport: PlaceViewport, limit: Int = 300): List<OfflinePlace> = withContext(Dispatchers.IO) {
require(limit in 1..500)
install()
regional.withCatalogs { installed ->
val sources = RegionalPackManager.latest(installed).map { it.catalogFile to it.manifest } + listOf(file to null)
val longitude = if (viewport.west <= viewport.east) "longitude BETWEEN ? AND ?" else "(longitude >= ? OR longitude <= ?)"
val sql = "SELECT id,name,category,latitude,longitude,address,opening_hours,website,phone FROM places WHERE latitude BETWEEN ? AND ? AND $longitude LIMIT 500"
val args = arrayOf(viewport.south.toString(), viewport.north.toString(), viewport.west.toString(), viewport.east.toString())
val found = mutableListOf<OfflinePlace>()
for ((source, manifest) in sources) {
currentCoroutineContext().ensureActive()
SQLiteDatabase.openDatabase(source.path, null, SQLiteDatabase.OPEN_READONLY or SQLiteDatabase.NO_LOCALIZED_COLLATORS).use { db ->
db.rawQuery(sql, args).use { cursor ->
while (cursor.moveToNext()) {
currentCoroutineContext().ensureActive()
val point = GeoPoint(cursor.getDouble(3), cursor.getDouble(4))
if (manifest != null && !manifest.covers(point) || manifest == null && !OfflineBounds.ASTURIAS.contains(point.latitude, point.longitude)) continue
fun optional(column: Int): String? = if (cursor.isNull(column)) null else cursor.getString(column)
found += OfflinePlace(cursor.getString(0), cursor.getString(1), PlaceCategory.valueOf(cursor.getString(2)), point, optional(5), optional(6), optional(7), optional(8))
}
}
}
}
found.distinctBy { it.id }.take(limit)
}
}
/** Optional additive table: older regional packs continue to work without camera data. */
suspend fun speedCameras(center: GeoPoint): List<SpeedCamera> = withContext(Dispatchers.IO) {
require(center.latitude.isFinite() && center.longitude.isFinite() && center.latitude in -90.0..90.0 && center.longitude in -180.0..180.0)
install()
regional.withCatalogs { installed ->
val sources = RegionalPackManager.latest(installed).map { it.catalogFile to it.manifest } + listOf(file to null)
val found = mutableListOf<SpeedCamera>()
val delta = 700.0 / 111_000
val longitudeDelta = delta / cos(Math.toRadians(center.latitude)).coerceAtLeast(0.01)
for ((source, manifest) in sources) {
currentCoroutineContext().ensureActive()
SQLiteDatabase.openDatabase(source.path, null, SQLiteDatabase.OPEN_READONLY or SQLiteDatabase.NO_LOCALIZED_COLLATORS).use { db ->
val hasCameras = db.rawQuery("SELECT 1 FROM sqlite_master WHERE type='table' AND name='speed_cameras'", null).use { it.moveToFirst() }
if (hasCameras) db.rawQuery("SELECT id,latitude,longitude,direction FROM speed_cameras WHERE latitude BETWEEN ? AND ? AND longitude BETWEEN ? AND ? LIMIT 500", arrayOf(
(center.latitude-delta).toString(), (center.latitude+delta).toString(), (center.longitude-longitudeDelta).toString(), (center.longitude+longitudeDelta).toString())).use { cursor ->
while (cursor.moveToNext()) {
val point = GeoPoint(cursor.getDouble(1), cursor.getDouble(2))
if (cameraDistance(center, point) <= 700 && (manifest?.covers(point) ?: OfflineBounds.ASTURIAS.contains(point.latitude, point.longitude)))
found += SpeedCamera(cursor.getString(0), point, if (cursor.isNull(3)) null else cursor.getString(3))
}
}
}
}
found.distinctBy { it.id }.sortedBy { cameraDistance(center, it.position) }
}
}
suspend fun covers(center: GeoPoint): Boolean = OfflineBounds.ASTURIAS.contains(center.latitude, center.longitude) || regional.withCatalogs { regions -> regions.any { it.manifest.covers(center) } }
private fun digest(value: File): String {
val digest = MessageDigest.getInstance("SHA-256")
value.inputStream().use { input -> val buffer = ByteArray(64 * 1024); while (true) { val count = input.read(buffer); if (count < 0) break; digest.update(buffer, 0, count) } }
return digest.digest().joinToString("") { "%02x".format(it.toInt() and 255) }
}
companion object {
const val ASSET = "offline/asturias-pois.sqlite"
const val BUNDLED_BYTES = 2347008L
const val BUNDLED_SHA256 = "c5d8413f260b0b3e5bdc3da4c9b5e33f8e66f5acd80cc284a7e8668f039798f9"
private val gate = Mutex()
private fun distance(a: GeoPoint, b: GeoPoint): Double {
val lat = Math.toRadians(b.latitude - a.latitude); val lon = Math.toRadians(b.longitude - a.longitude)
val h = sin(lat / 2).pow(2) + cos(Math.toRadians(a.latitude)) * cos(Math.toRadians(b.latitude)) * sin(lon / 2).pow(2)
return 6_371_008.8 * 2 * asin(sqrt(h.coerceIn(0.0, 1.0)))
}
}
}
@@ -0,0 +1,134 @@
package dev.navframe.app
import android.content.Context
import android.os.Bundle
import android.os.SystemClock
import android.view.MotionEvent
import dev.navframe.core.*
import org.maplibre.android.MapLibre
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.geometry.LatLngBounds
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.Style
import org.maplibre.android.style.layers.CircleLayer
import org.maplibre.android.style.layers.LineLayer
import org.maplibre.android.style.layers.SymbolLayer
import org.maplibre.android.style.expressions.Expression as Expr
import org.maplibre.android.style.sources.GeoJsonOptions
import org.maplibre.android.style.layers.PropertyFactory.*
import org.maplibre.android.style.sources.GeoJsonSource
import org.maplibre.geojson.*
/** Phone rendering consumes service state directly; it never supplies a screenshot to the TFT. */
class PhoneMapView(context: Context, savedState: Bundle?, private val onAttribution: (String) -> Unit = {}, private val onPlaceSelected: (OfflinePlace) -> Unit = {}, private val onError: () -> Unit, private val onViewportChanged: (PlaceViewport) -> Unit = {}) {
val view: MapView
private var map: MapLibreMap? = null
private var source: TileSource? = null
private var style: Style? = null
private var state = NavigationState()
private var renderedAt = 0L
private var followed = true
private var destroyed = false
private var styleGeneration = 0L
private var reportedCredits = ""
private var places: List<OfflinePlace> = emptyList()
init {
MapLibre.getInstance(context.applicationContext)
view = MapView(context)
view.onCreate(savedState)
view.addOnDidFinishRenderingFrameListener { _, _, _ -> updateAttribution() }
view.addOnDidFailLoadingMapListener { if (!destroyed) onError() }
view.setOnTouchListener { _, event -> if (event.action == MotionEvent.ACTION_DOWN) followed = false; false }
view.getMapAsync { current ->
if (destroyed) return@getMapAsync
map = current
current.cameraPosition = CameraPosition.Builder().target(LatLng(43.36, -5.85)).zoom(12.0).build()
current.addOnMapClickListener { point ->
val hit = current.queryRenderedFeatures(current.projection.toScreenLocation(point), "phone-places-single", "phone-places-clusters").firstOrNull()
if (hit == null) false else {
followed = false
if (hit.hasProperty("point_count")) current.moveCamera(CameraUpdateFactory.newLatLngZoom(point, current.cameraPosition.zoom + 1.5))
else places.firstOrNull { it.id == hit.getStringProperty("place_id") }?.let(onPlaceSelected)
true
}
}
current.addOnCameraMoveListener { reportViewport() }
current.addOnCameraIdleListener { reportViewport() }
reportViewport()
source?.let { loadStyle(it) }
}
}
fun loadStyle(value: TileSource) {
if (destroyed || (source == value && style != null)) return
source = value
styleGeneration++
val generation = styleGeneration
style = null
val current = map ?: return
val builder = if (value.uri.startsWith("asset://")) Style.Builder().fromJson(view.context.assets.open(value.uri.removePrefix("asset://")).bufferedReader().use { it.readText() }) else Style.Builder().fromUri(value.uri)
builder.withSources(GeoJsonSource("phone-route", empty()), GeoJsonSource("phone-rider", empty()), GeoJsonSource("phone-places", empty(), GeoJsonOptions().withCluster(true).withClusterRadius(36).withClusterMaxZoom(14)))
.withLayers(LineLayer("phone-route-casing", "phone-route").withProperties(lineColor("#071017"), lineWidth(11f)),
LineLayer("phone-route-line", "phone-route").withProperties(lineColor("#50e3c2"), lineWidth(6f)),
CircleLayer("phone-places-clusters", "phone-places").withFilter(Expr.has("point_count")).withProperties(circleRadius(15f), circleColor("#ffcf56"), circleStrokeColor("#071017"), circleStrokeWidth(2f)),
SymbolLayer("phone-places-count", "phone-places").withFilter(Expr.has("point_count")).withProperties(textField(Expr.toString(Expr.get("point_count"))), textFont(arrayOf("Noto Sans Regular")), textSize(11f), textColor("#071017"), textAllowOverlap(true)),
CircleLayer("phone-places-single", "phone-places").withFilter(Expr.not(Expr.has("point_count"))).withProperties(circleRadius(7f), circleColor(Expr.match(Expr.get("category"), Expr.literal("FUEL"), Expr.literal("#ffcf56"), Expr.literal("WORKSHOP"), Expr.literal("#ff8a65"), Expr.literal("FOOD"), Expr.literal("#81c784"), Expr.literal("LODGING"), Expr.literal("#90caf9"), Expr.literal("SHOPPING"), Expr.literal("#ce93d8"), Expr.literal("#ffcf56"))), circleStrokeColor("#071017"), circleStrokeWidth(2f)),
CircleLayer("phone-rider-circle", "phone-rider").withProperties(circleRadius(9f), circleColor("#ffffff"), circleStrokeColor("#50e3c2"), circleStrokeWidth(4f)))
current.setStyle(builder) { loaded ->
if (!destroyed && source == value && generation == styleGeneration) { style = loaded; renderedAt = 0; applyPlaces(); updateAttribution(); update(state, true) }
}
}
fun update(value: NavigationState, force: Boolean = false) {
if (destroyed) return
val changedRoute = state.route != value.route || state.navigationStatus != value.navigationStatus
state = value
val now = SystemClock.elapsedRealtime()
if (!force && !changedRoute && now - renderedAt < 200) return
renderedAt = now
val current = map ?: return
val loaded = style ?: return
val route = value.route
val routeData = if (route != null && route.geometry.size >= 2) FeatureCollection.fromFeatures(arrayOf(Feature.fromGeometry(LineString.fromLngLats(route.geometry.map { Point.fromLngLat(it.longitude, it.latitude) })))) else empty()
loaded.getSourceAs<GeoJsonSource>("phone-route")?.setGeoJson(routeData)
val positionKnown = value.navigationStatus != NavigationStatus.IDLE && value.position != GeoPoint(0.0, 0.0)
loaded.getSourceAs<GeoJsonSource>("phone-rider")?.setGeoJson(if (positionKnown) FeatureCollection.fromFeatures(arrayOf(Feature.fromGeometry(Point.fromLngLat(value.position.longitude, value.position.latitude)))) else empty())
loaded.getLayerAs<CircleLayer>("phone-rider-circle")?.setProperties(circleColor(if (value.navigationStatus == NavigationStatus.GPS_LOST) "#89919c" else "#ffffff"), circleStrokeColor(if (value.navigationStatus == NavigationStatus.GPS_LOST) "#ffcf56" else "#50e3c2"))
if (followed && value.navigationStatus == NavigationStatus.ROUTE_PREVIEW && route != null && (changedRoute || force)) {
current.moveCamera(CameraUpdateFactory.newLatLngBounds(LatLngBounds.Builder().includes(route.geometry.map { LatLng(it.latitude, it.longitude) }).build(), 36))
} else if (followed && positionKnown) {
val camera = TftCameraPolicy().parameters(value)
current.moveCamera(CameraUpdateFactory.newCameraPosition(CameraPosition.Builder().target(LatLng(value.position.latitude, value.position.longitude)).zoom(camera.zoom - .8).bearing(camera.bearingDegrees.toDouble()).build()))
}
}
private fun updateAttribution() {
if (destroyed) return
val configured = source?.attribution ?: return
val native = style?.sources.orEmpty().mapNotNull { it.attribution }.map { android.text.Html.fromHtml(it, android.text.Html.FROM_HTML_MODE_LEGACY).toString().trim() }.filter { it.isNotEmpty() }
val base = if (source?.uri?.startsWith("https:") == true && native.isNotEmpty()) native.distinct().joinToString(" · ") else configured
val text = if (places.isNotEmpty() && !base.contains("OpenStreetMap")) "$base · © OpenStreetMap contributors" else base
if (reportedCredits != text) { reportedCredits = text; onAttribution(text) }
}
private fun reportViewport() {
if (destroyed) return
val bounds = map?.projection?.visibleRegion?.latLngBounds ?: return
onViewportChanged(PlaceViewport(bounds.latitudeSouth, bounds.longitudeWest, bounds.latitudeNorth, bounds.longitudeEast))
}
fun refreshPlaces() = reportViewport()
fun center(): GeoPoint? = map?.cameraPosition?.target?.let { GeoPoint(it.latitude, it.longitude) }
fun setPlaces(value: List<OfflinePlace>) { places = value.take(300).toList(); applyPlaces(); updateAttribution() }
private fun applyPlaces() {
val features = places.map { place -> Feature.fromGeometry(Point.fromLngLat(place.position.longitude, place.position.latitude)).apply { addStringProperty("place_id", place.id); addStringProperty("category", place.category.name) } }
style?.getSourceAs<GeoJsonSource>("phone-places")?.setGeoJson(FeatureCollection.fromFeatures(features))
}
fun recenter() { followed = true; update(state, true) }
fun onStart() = view.onStart()
fun onResume() = view.onResume()
fun onPause() = view.onPause()
fun onStop() = view.onStop()
fun onSaveInstanceState(bundle: Bundle) = view.onSaveInstanceState(bundle)
fun onLowMemory() = view.onLowMemory()
fun onDestroy() { destroyed = true; style = null; map = null; view.onDestroy() }
private fun empty() = FeatureCollection.fromFeatures(emptyArray<Feature>())
}
@@ -0,0 +1,59 @@
package dev.navframe.app
import org.json.JSONObject
import java.io.ByteArrayInputStream
import java.io.File
import java.io.RandomAccessFile
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.zip.GZIPInputStream
/** Bounded v3 archive/header validation. Native MapLibre owns actual PMTiles directory/tile decoding. */
data class PmtilesInfo(val bounds: OfflineBounds, val minZoom: Int, val maxZoom: Int) {
companion object {
fun read(file: File): PmtilesInfo = RandomAccessFile(file, "r").use { input ->
val length = input.length()
require(length in 127..OfflineMapManager.MAX_ARCHIVE_BYTES) { "Tamaño PMTiles inválido" }
val bytes = ByteArray(127); input.readFully(bytes)
require(bytes.copyOfRange(0, 7).toString(Charsets.US_ASCII) == "PMTiles" && bytes[7].toInt() == 3) { "Se requiere PMTiles v3" }
val header = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
fun section(offsetIndex: Int, sizeIndex: Int): Pair<Long, Long> {
val offset = header.getLong(offsetIndex); val size = header.getLong(sizeIndex)
require(offset >= 127 && size >= 0 && offset <= length && size <= length - offset) { "Sección PMTiles fuera del archivo" }
return offset to size
}
val root = section(8, 16)
val metadata = section(24, 32)
val leaves = section(40, 48)
val tiles = section(56, 64)
require(root.second > 0 && metadata.second in 1..1024 * 1024 && tiles.second > 0) { "Archivo PMTiles incompleto" }
val sections = listOf(root, metadata, leaves, tiles).filter { it.second > 0 }.sortedBy { it.first }
sections.zipWithNext().forEach { (a, b) -> require(a.first + a.second <= b.first) { "Secciones PMTiles solapadas" } }
require(bytes[97].toInt() in 1..2 && bytes[98].toInt() in 1..2 && bytes[99].toInt() == 1) { "Se requiere PMTiles vectorial MVT con gzip/none" }
val minZoom = bytes[100].toInt() and 255; val maxZoom = bytes[101].toInt() and 255
require(minZoom in 0..16 && maxZoom in minZoom..16) { "Rango zoom offline no admitido" }
val bounds = OfflineBounds(header.getInt(106) / 1e7, header.getInt(102) / 1e7,
header.getInt(114) / 1e7, header.getInt(110) / 1e7)
input.seek(metadata.first)
val compressed = ByteArray(metadata.second.toInt()); input.readFully(compressed)
val source = ByteArrayInputStream(compressed)
val data = (if (bytes[97].toInt() == 2) GZIPInputStream(source) else source).use { stream ->
val output = java.io.ByteArrayOutputStream()
val chunk = ByteArray(8192)
while (true) {
val count = stream.read(chunk)
if (count < 0) break
require(output.size() + count <= 1024 * 1024) { "Metadatos PMTiles demasiado grandes" }
output.write(chunk, 0, count)
}
output.toByteArray()
}
val info = JSONObject(data.toString(Charsets.UTF_8))
require(info.optString("name") == "NavFrame Offline" && info.optString("version") == "1.0.0") { "Importa un pack del esquema NavFrame Offline 1.0.0" }
val layers = info.getJSONArray("vector_layers")
val names = (0 until layers.length()).map { layers.getJSONObject(it).getString("id") }.toSet()
require(names.containsAll(listOf("roads", "place"))) { "Faltan capas de carreteras/etiquetas offline" }
PmtilesInfo(bounds, minZoom, maxZoom)
}
}
}
@@ -0,0 +1,104 @@
package dev.navframe.app
import dev.navframe.core.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import java.net.HttpURLConnection
import java.net.URI
import java.security.MessageDigest
import java.io.FilterInputStream
import java.io.InputStream
/** User-configured HTTPS catalogs only. Downloads live with the activity and cancel on destruction. */
class RegionalDownloadManager(private val packs: RegionalPackManager) {
suspend fun fetchCatalog(address: String): RegionalCatalog = withContext(Dispatchers.IO) {
withTimeout(60_000) { withConnection(address) { connection ->
require(connection.contentLengthLong <= MAX_CATALOG_BYTES) { "Catálogo demasiado grande" }
connection.inputStream.use { input ->
val output = java.io.ByteArrayOutputStream()
val buffer = ByteArray(8192)
while (true) {
currentCoroutineContext().ensureActive()
val count = input.read(buffer)
if (count < 0) break
require(output.size() + count <= MAX_CATALOG_BYTES) { "Catálogo demasiado grande" }
output.write(buffer, 0, count)
}
parseRegionalCatalog(output.toString("UTF-8"))
}
} }
}
suspend fun install(catalogAddress: String, entry: RegionalCatalogEntry): InstalledRegion = withContext(Dispatchers.IO) {
require(entry.archive.bytes <= MAX_PACKAGE_BYTES) { "Región demasiado grande para este dispositivo" }
val address = entry.archive.url ?: validateAddress(catalogAddress).resolve(entry.archive.path).toString()
withTimeout(30 * 60_000L) { withConnection(address) { connection ->
require(connection.contentLengthLong < 0 || connection.contentLengthLong == entry.archive.bytes) { "Tamaño de descarga incorrecto" }
connection.inputStream.use { input ->
val verified = VerifiedArchiveStream(input, entry.archive.bytes, entry.archive.sha256)
packs.importPackage(verified, entry.archive.bytes, entry)
}
} }
}
private suspend fun <T> withConnection(address: String, action: suspend (HttpURLConnection) -> T): T {
var uri = validateAddress(address)
repeat(6) { hop ->
currentCoroutineContext().ensureActive()
val connection = uri.toURL().openConnection() as HttpURLConnection
connection.instanceFollowRedirects = false
connection.connectTimeout = 15_000
connection.readTimeout = 15_000
connection.setRequestProperty("Accept-Encoding", "identity")
try {
val status = connection.responseCode
if (status in listOf(301, 302, 303, 307, 308)) {
require(hop < 5) { "Demasiadas redirecciones" }
val location = connection.getHeaderField("Location") ?: error("Redirección incompleta")
uri = validateAddress(uri.resolve(location).toString())
} else {
require(status == 200) { "Servidor de regiones no disponible" }
return action(connection)
}
} finally { connection.disconnect() }
}
error("Demasiadas redirecciones")
}
companion object {
const val MAX_CATALOG_BYTES = 32 * 1024 * 1024
const val MAX_PACKAGE_BYTES = 600L * 1024 * 1024
fun validateAddress(address: String): URI {
require(address.length in 1..2048) { "URL de catálogo inválida" }
val uri = URI(address.trim())
require(uri.scheme == "https" && !uri.host.isNullOrBlank() && uri.userInfo == null && uri.fragment == null && (uri.port == -1 || uri.port == 443)) { "Se requiere una URL HTTPS sin credenciales" }
return uri
}
}
}
/** Checks the archive before the importer is allowed to validate and commit its extracted contents. */
internal class VerifiedArchiveStream(input: InputStream, private val expected: Long, private val checksum: String) : FilterInputStream(input) {
private val digest = MessageDigest.getInstance("SHA-256")
private var count = 0L
private var verified = false
override fun read(): Int {
val value = `in`.read()
if (value < 0) finish() else { count++; require(count <= expected) { "Descarga demasiado grande" }; digest.update(value.toByte()) }
return value
}
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
val size = `in`.read(buffer, offset, length)
if (size < 0) finish() else { count += size; require(count <= expected) { "Descarga demasiado grande" }; digest.update(buffer, offset, size) }
return size
}
private fun finish() {
if (verified) return
require(count == expected) { "Descarga incompleta" }
require(digest.digest().joinToString("") { "%02x".format(it.toInt() and 255) } == checksum) { "Checksum de descarga incorrecto" }
verified = true
}
}
@@ -0,0 +1,216 @@
package dev.navframe.app
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import dev.navframe.core.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import org.json.JSONObject
import java.io.*
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.security.MessageDigest
import java.util.UUID
import java.util.zip.ZipFile
import kotlin.math.abs
data class InstalledRegion(val folderId: String, val manifest: RegionalManifest, val source: TileSource, val bytes: Long, val catalogFile: File)
data class RegionInstallProgress(val completed: Long, val total: Long?, val stage: String)
/** Local unified packs. A new immutable directory is committed only after both resources validate. */
class RegionalPackManager(context: Context) {
private val context = context.applicationContext
private val root = File(this.context.filesDir, "offline")
private val mutableRegions = MutableStateFlow<List<InstalledRegion>>(emptyList())
val regions = mutableRegions.asStateFlow()
private val mutableProgress = MutableStateFlow<RegionInstallProgress?>(null)
val progress = mutableProgress.asStateFlow()
suspend fun refresh() = withContext(Dispatchers.IO) { gate.withLock { scan().also { mutableRegions.value = it } } }
/** Holds the same lock as deletion until callers have closed every SQLite cursor/connection. */
suspend fun <T> withCatalogs(block: suspend (List<InstalledRegion>) -> T): T = withContext(Dispatchers.IO) {
gate.withLock { block(scan().also { mutableRegions.value = it }) }
}
fun storageBytes(): Long = root.walkTopDown().filter { it.isFile }.sumOf { it.length() }
suspend fun importPackage(input: InputStream, totalBytes: Long? = null, expectedEntry: RegionalCatalogEntry? = null): InstalledRegion = input.use { stream -> withContext(Dispatchers.IO) {
require(totalBytes == null || totalBytes in 1..MAX_PACKAGE_BYTES) { "Tamaño de paquete regional inválido" }
root.mkdirs()
require(root.usableSpace >= (totalBytes ?: 0) * 2 + RESERVE_BYTES) { "Espacio libre insuficiente" }
val id = UUID.randomUUID().toString()
val stage = File(root, ".region-$id")
activeStages.add(stage.absolutePath)
check(stage.mkdir())
val archive = File(stage, "package.navframe")
val folder = File(stage, "contents").apply { check(mkdir()) }
val committed = File(root, id)
var installed = false
try {
mutableProgress.value = RegionInstallProgress(0, totalBytes, "Copiando paquete")
archive.outputStream().use { output -> copyBounded(stream, output, totalBytes, MAX_PACKAGE_BYTES) { bytes -> mutableProgress.value = RegionInstallProgress(bytes, totalBytes, "Copiando paquete") } }
val manifestText: String
val manifest: RegionalManifest
ZipFile(archive).use { zip ->
val entries = mutableListOf<java.util.zip.ZipEntry>()
val enumeration = zip.entries()
while (enumeration.hasMoreElements()) {
require(entries.size < 3) { "Paquete regional: demasiados archivos" }
entries += enumeration.nextElement()
}
require(entries.size == 3 && entries.map { it.name }.toSet() == setOf("manifest.json", "map.pmtiles", "pois.sqlite") && entries.none { it.isDirectory }) { "Paquete regional: se requieren manifest.json, map.pmtiles y pois.sqlite" }
val entry = zip.getEntry("manifest.json")
require(entry.size in 1..MAX_MANIFEST_BYTES) { "Manifest regional demasiado grande" }
manifestText = zip.getInputStream(entry).use { readBounded(it, MAX_MANIFEST_BYTES.toInt()).toString(Charsets.UTF_8) }
manifest = parseRegionalManifest(manifestText)
require(manifest.totalBytes <= MAX_PACKAGE_BYTES) { "Región demasiado grande" }
require(root.usableSpace >= manifest.totalBytes + RESERVE_BYTES) { "Espacio libre insuficiente" }
for (resource in listOf(manifest.map, manifest.pois)) {
currentCoroutineContext().ensureActive()
val item = zip.getEntry(resource.path)
require(item.size == resource.bytes) { "Tamaño de recurso regional incorrecto" }
mutableProgress.value = RegionInstallProgress(0, resource.bytes, "Verificando ${resource.path}")
val target = File(folder, resource.path)
val hash = MessageDigest.getInstance("SHA-256")
zip.getInputStream(item).use { source -> target.outputStream().use { output ->
copyBounded(source, output, resource.bytes, resource.bytes, hash) { bytes -> mutableProgress.value = RegionInstallProgress(bytes, resource.bytes, "Verificando ${resource.path}") }
output.fd.sync()
} }
require(hex(hash.digest()) == resource.sha256) { "Checksum regional incorrecto" }
}
}
val map = PmtilesInfo.read(File(folder, "map.pmtiles"))
require(map.minZoom == manifest.minZoom && map.maxZoom == manifest.maxZoom &&
abs(map.bounds.south - manifest.bounds.south) < 1e-6 && abs(map.bounds.north - manifest.bounds.north) < 1e-6 &&
abs(map.bounds.west - manifest.bounds.west) < 1e-6 && abs(map.bounds.east - manifest.bounds.east) < 1e-6) { "Cobertura/zoom del mapa no coincide con manifest" }
validatePois(File(folder, "pois.sqlite"), manifest)
require(expectedEntry == null || manifest == expectedEntry.manifest) { "Manifest no coincide con el catálogo remoto" }
val listed = expectedEntry ?: catalog()?.regions?.firstOrNull { it.manifest.id == manifest.id && it.manifest.version == manifest.version }
if (listed != null) {
require(archive.length() == listed.archive.bytes && digest(archive) == listed.archive.sha256 && manifest.map == listed.manifest.map && manifest.pois == listed.manifest.pois) { "Paquete no coincide con el catálogo local" }
}
gate.withLock {
currentCoroutineContext().ensureActive()
require(storageBytes() - archive.length() <= OfflineMapManager.MAX_TOTAL_BYTES) { "Límite de almacenamiento offline: 1 GiB" }
val current = scan()
current.firstOrNull { it.manifest.id == manifest.id && it.manifest.version == manifest.version }?.let { old ->
require(old.manifest.map == manifest.map && old.manifest.pois == manifest.pois) { "La versión instalada tiene otro checksum" }
return@withLock old
}
require(current.size < 12) { "Elimina versiones antiguas antes de importar más regiones" }
val style = OfflineMapStyle.create(localUri(File(committed, "map.pmtiles")))
File(folder, "style.json").writeText(style)
File(folder, "region.json").writeText(manifestText)
File(folder, "pack.json").writeText(JSONObject().put("version", 1).put("name", "${manifest.name} · ${manifest.version}").put("bytes", manifest.map.bytes).toString())
Files.move(folder.toPath(), committed.toPath(), StandardCopyOption.ATOMIC_MOVE)
installed = true
scan().also { mutableRegions.value = it }.first { it.folderId == id }
}
} finally {
stage.deleteRecursively()
activeStages.remove(stage.absolutePath)
if (!installed) committed.deleteRecursively()
mutableProgress.value = null
}
} }
/** UI must release an active MapView/Snapshotter source before calling this. */
suspend fun delete(folderId: String) = withContext(Dispatchers.IO) {
gate.withLock {
require(ID.matches(folderId)) { "Identificador regional inválido" }
val folder = File(root, folderId)
require(File(folder, "region.json").isFile) { "Región no instalada" }
check(folder.deleteRecursively()) { "No se pudo borrar la región" }
mutableRegions.value = scan()
}
}
suspend fun importCatalog(input: InputStream) = input.use { withContext(Dispatchers.IO) {
val text = readBounded(it, MAX_MANIFEST_BYTES.toInt()).toString(Charsets.UTF_8)
parseRegionalCatalog(text)
val file = File(context.filesDir, "regional-catalog.json")
val part = File(file.path + ".part")
try { part.writeText(text); Files.move(part.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING) } finally { part.delete() }
} }
suspend fun catalog(): RegionalCatalog? = withContext(Dispatchers.IO) {
val stored = File(context.filesDir, "regional-catalog.json")
try {
if (stored.isFile) parseRegionalCatalog(stored.inputStream().use { readBounded(it, MAX_MANIFEST_BYTES.toInt()).toString(Charsets.UTF_8) })
else context.assets.open("offline/regional-catalog.json").use { parseRegionalCatalog(readBounded(it, MAX_MANIFEST_BYTES.toInt()).toString(Charsets.UTF_8)) }
} catch (_: Exception) { null }
}
private fun scan(): List<InstalledRegion> {
root.listFiles().orEmpty().filter { it.isDirectory && it.name.startsWith(".region-") && it.absolutePath !in activeStages }.forEach { it.deleteRecursively() }
return root.listFiles().orEmpty().filter { it.isDirectory && ID.matches(it.name) }.mapNotNull { folder ->
try {
val file = File(folder, "region.json")
if (!file.isFile || file.length() !in 1..MAX_MANIFEST_BYTES || !File(folder, "pack.json").isFile) return@mapNotNull null
val manifest = parseRegionalManifest(file.readText())
if (File(folder, "map.pmtiles").length() != manifest.map.bytes || File(folder, "pois.sqlite").length() != manifest.pois.bytes || !File(folder, "style.json").isFile) return@mapNotNull null
InstalledRegion(folder.name, manifest, TileSource(localUri(File(folder, "style.json")), manifest.attribution), manifest.totalBytes, File(folder, "pois.sqlite"))
} catch (_: Exception) { null }
}.sortedBy { it.manifest.name }
}
private fun validatePois(file: File, manifest: RegionalManifest) {
SQLiteDatabase.openDatabase(file.path, null, SQLiteDatabase.OPEN_READONLY or SQLiteDatabase.NO_LOCALIZED_COLLATORS).use { db ->
require(db.version == manifest.poiSchema) { "Esquema de lugares incompatible" }
db.rawQuery("PRAGMA quick_check", null).use { require(it.moveToFirst() && it.getString(0) == "ok") { "Catálogo SQLite inválido" } }
db.rawQuery("SELECT id,name,search_name,category,latitude,longitude,address,opening_hours,website,phone FROM places LIMIT 0", null).close()
val hasCameras = db.rawQuery("SELECT 1 FROM sqlite_master WHERE type='table' AND name='speed_cameras'", null).use { it.moveToFirst() }
if (hasCameras) {
db.rawQuery("SELECT id,latitude,longitude,direction FROM speed_cameras LIMIT 0", null).close()
db.rawQuery("SELECT COUNT(*) FROM speed_cameras WHERE id IS NULL OR length(id) NOT BETWEEN 1 AND 80 OR latitude IS NULL OR longitude IS NULL OR latitude NOT BETWEEN ? AND ? OR longitude NOT BETWEEN ? AND ? OR length(direction) > 40", arrayOf(manifest.bounds.south,manifest.bounds.north,manifest.bounds.west,manifest.bounds.east).map { it.toString() }.toTypedArray()).use {
require(it.moveToFirst() && it.getLong(0) == 0L) { "Cámaras fuera de cobertura o inválidas" }
}
}
db.rawQuery("SELECT COUNT(*) FROM places WHERE latitude IS NULL OR longitude IS NULL OR latitude NOT BETWEEN ? AND ? OR longitude NOT BETWEEN ? AND ? OR category NOT IN ('FUEL','WORKSHOP','FOOD','LODGING','SHOPPING') OR name IS NULL OR length(name) NOT BETWEEN 1 AND 2048", arrayOf(manifest.bounds.south,manifest.bounds.north,manifest.bounds.west,manifest.bounds.east).map { it.toString() }.toTypedArray()).use { require(it.moveToFirst() && it.getLong(0) == 0L) { "Lugares fuera de cobertura o inválidos" } }
}
}
private suspend fun copyBounded(input: InputStream, output: OutputStream, expected: Long?, maximum: Long, digest: MessageDigest? = null, progress: (Long) -> Unit) {
var bytes = 0L; var published = 0L
val buffer = ByteArray(64 * 1024)
while (true) {
currentCoroutineContext().ensureActive()
val count = input.read(buffer); if (count < 0) break
bytes += count; require(bytes <= maximum) { "Paquete regional demasiado grande" }
output.write(buffer, 0, count); digest?.update(buffer, 0, count)
if (bytes - published >= 1024 * 1024) { progress(bytes); published = bytes }
}
require(expected == null || bytes == expected) { "Paquete regional incompleto" }
progress(bytes)
}
private fun digest(file: File): String {
val hash = MessageDigest.getInstance("SHA-256")
file.inputStream().use { input -> val buffer = ByteArray(65536); while (true) { val n = input.read(buffer); if (n < 0) break; hash.update(buffer, 0, n) } }
return hex(hash.digest())
}
private fun readBounded(input: InputStream, limit: Int): ByteArray {
val output = ByteArrayOutputStream(); val buffer = ByteArray(8192)
while (true) { val count = input.read(buffer); if (count < 0) break; require(output.size() + count <= limit) { "Manifest demasiado grande" }; output.write(buffer,0,count) }
return output.toByteArray()
}
companion object {
private val gate get() = OfflineMapManager.gate
private val activeStages = java.util.concurrent.ConcurrentHashMap.newKeySet<String>()
private val ID = Regex("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
fun latest(regions: List<InstalledRegion>): List<InstalledRegion> = regions.groupBy { it.manifest.id }.values.map { versions ->
versions.maxWith(compareBy<InstalledRegion> { it.manifest.osmTimestamp }.thenComparator { a, b -> compareVersions(a.manifest.version, b.manifest.version) })
}
fun compareVersions(a: String, b: String): Int {
val parts = Regex("[0-9]+|[^0-9]+")
val left = parts.findAll(a).map { it.value }.toList(); val right = parts.findAll(b).map { it.value }.toList()
for (i in 0 until minOf(left.size, right.size)) {
val x = left[i].toBigIntegerOrNull(); val y = right[i].toBigIntegerOrNull()
val result = if (x != null && y != null) x.compareTo(y) else left[i].compareTo(right[i])
if (result != 0) return result
}
return left.size.compareTo(right.size)
}
private const val MAX_PACKAGE_BYTES = 600L * 1024 * 1024
private const val MAX_MANIFEST_BYTES = 2L * 1024 * 1024
private const val RESERVE_BYTES = 50L * 1024 * 1024
fun localUri(file: File) = file.toURI().toASCIIString().replaceFirst("file:/", "file:///")
private fun hex(bytes: ByteArray) = bytes.joinToString("") { "%02x".format(it.toInt() and 255) }
}
}
@@ -0,0 +1,105 @@
package dev.navframe.app
import android.graphics.*
import dev.navframe.core.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
import java.text.SimpleDateFormat
import java.util.*
import kotlin.math.*
enum class NavigationMode { IDLE, DEMO, GPS, MAP_DEMO, MAP_GPS }
/** Native 480×240 framebuffer. Roads and turns in DEMO are illustrations, never real map data. */
class SyntheticTftRenderer : TftRenderer {
override suspend fun render(state: NavigationState) = render(state, NavigationMode.DEMO, null)
suspend fun render(state: NavigationState, mode: NavigationMode, accuracyMeters: Float?): TftFrame = withContext(Dispatchers.Default) {
val start = System.nanoTime()
val bitmap = Bitmap.createBitmap(480, 240, Bitmap.Config.ARGB_8888)
try {
val canvas = Canvas(bitmap)
canvas.drawColor(Color.rgb(13, 19, 25))
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
fun text(label: String, x: Float, y: Float, size: Float, color: Int = Color.WHITE) {
paint.apply { this.color = color; textSize = size; style = Paint.Style.FILL; textAlign = Paint.Align.LEFT; typeface = Typeface.create("sans-serif", Typeface.BOLD) }
canvas.drawText(label, x, y, paint)
}
fun stroke(path: Path, color: Int, width: Float) {
paint.apply { this.color = color; style = Paint.Style.STROKE; strokeWidth = width; strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND }
canvas.drawPath(path, paint)
}
val accent = Color.rgb(80, 227, 194)
val camera = TftCameraPolicy().parameters(state)
val gpsLost = mode == NavigationMode.IDLE || state.navigationStatus == NavigationStatus.GPS_LOST
if (mode == NavigationMode.DEMO) {
// Curve and perspective respond to the simulated heading and approach to a turn.
val left = state.nextManeuver?.instruction?.contains("izquierda") == true
val bend = sin(Math.toRadians(state.bearing.toDouble())).toFloat() * 70f * (if (left) -1f else 1f)
val closeness = (1f - ((state.distanceToNextManeuverMeters ?: 350) / 500f)).coerceIn(0f, 1f)
val road = Path().apply {
moveTo(170f, 230f)
cubicTo(170f, 190f, 170f, 166f, 170f, camera.riderAnchorY * 200f)
cubicTo(170f, 108f, 215f + bend * closeness, 80f, 150f + bend, -20f)
}
stroke(Path().apply { moveTo(0f, 108f); lineTo(300f, 85f) }, Color.rgb(41, 50, 58), 13f)
stroke(Path().apply { moveTo(60f, 0f); lineTo(96f, 210f) }, Color.rgb(35, 44, 52), 11f)
stroke(road, Color.rgb(55, 65, 75), (40f + (camera.zoom - 16.0).toFloat() * 4f))
stroke(road, Color.rgb(25, 34, 43), 32f)
stroke(road, accent, 10f)
text("DEMO · RUTA FICTICIA", 10f, 23f, 17f, accent)
paint.color = Color.rgb(27, 38, 49); paint.style = Paint.Style.FILL
canvas.drawRoundRect(300f, 35f, 474f, 151f, 12f, 12f, paint)
val arrow = if (left) Path().apply { moveTo(366f, 82f); lineTo(366f, 57f); lineTo(324f, 57f); moveTo(340f, 43f); lineTo(324f, 57f); lineTo(340f, 71f) }
else Path().apply { moveTo(328f, 82f); lineTo(328f, 57f); lineTo(370f, 57f); moveTo(354f, 43f); lineTo(370f, 57f); lineTo(354f, 71f) }
stroke(arrow, accent, 7f)
text("${state.distanceToNextManeuverMeters ?: 0} m", 313f, 116f, 30f)
text(if (left) "IZQUIERDA" else "DERECHA", 311f, 141f, 15f)
text("${(state.speed * 3.6f).roundToInt()} km/h", 320f, 185f, 26f)
} else {
// Local meter grid makes actual motion visible while explicitly showing no map.
val northMeters = state.position.latitude * 111_320.0
val eastMeters = state.position.longitude * 111_320.0 * cos(Math.toRadians(state.position.latitude))
val offsetX = ((eastMeters % 40.0) + 40.0).toFloat() % 40f
val offsetY = ((northMeters % 40.0) + 40.0).toFloat() % 40f
paint.apply { color = Color.rgb(39, 49, 59); style = Paint.Style.STROKE; strokeWidth = 1f }
for (n in -1..7) {
canvas.drawLine(n * 40f - offsetX, 30f, n * 40f - offsetX, 198f, paint)
canvas.drawLine(0f, n * 40f + offsetY, 292f, n * 40f + offsetY, paint)
}
text(if (mode == NavigationMode.IDLE) "NAVEGACIÓN DETENIDA" else "GPS · SIN MAPA/RUTA", 10f, 23f, 18f, accent)
text(if (mode == NavigationMode.IDLE) "DETENIDO" else if (gpsLost) "SIN SEÑAL" else "GPS ACTIVO", 306f, 65f, 21f, if (gpsLost) Color.YELLOW else accent)
text(if (gpsLost) "-- km/h" else "${(state.speed * 3.6f).roundToInt()} km/h", 306f, 105f, 30f)
text(if (gpsLost || !state.bearing.isFinite()) "Rumbo --" else "Rumbo ${state.bearing.roundToInt()}°", 306f, 143f, 22f)
val accuracy = accuracyMeters?.takeIf { it.isFinite() }?.roundToInt()?.toString() ?: "--"
text(if (gpsLost) "Precisión --" else "± $accuracy m", 306f, 181f, 22f)
text("N", 278f, 53f, 20f)
}
// Rider remains in lower third; GPS heading is actual (no synthetic turn instructions).
val centerX = 170f
val centerY = camera.riderAnchorY * 200f
canvas.save()
canvas.rotate(if (mode == NavigationMode.GPS && !gpsLost && state.bearing.isFinite()) state.bearing else 0f, centerX, centerY)
val marker = Path().apply { moveTo(centerX, centerY - 21); lineTo(centerX + 15, centerY + 17); lineTo(centerX, centerY + 9); lineTo(centerX - 15, centerY + 17); close() }
paint.apply { color = if (gpsLost) Color.GRAY else Color.WHITE; style = Paint.Style.FILL }
canvas.drawPath(marker, paint)
stroke(marker, Color.rgb(8, 15, 21), 3f)
canvas.restore()
paint.apply { color = Color.rgb(7, 12, 17); style = Paint.Style.FILL }
canvas.drawRect(0f, 200f, 480f, 240f, paint)
if (mode == NavigationMode.DEMO) {
val remaining = (state.remainingDistanceMeters ?: 0) / 1000.0
text(String.format(Locale.ROOT, "%.1f km", remaining), 12f, 228f, 23f)
val eta = state.etaEpochMillis?.let { SimpleDateFormat("HH:mm", Locale.ROOT).format(Date(it)) } ?: "--:--"
text("ETA $eta · DEMO", 270f, 228f, 22f)
} else text(if (mode == NavigationMode.IDLE) "Última navegación finalizada" else if (gpsLost) "Esperando una posición GPS reciente" else "Movimiento real · cuadrícula de prueba", 12f, 227f, 20f)
val bytes = ByteArrayOutputStream().use { output ->
check(bitmap.compress(Bitmap.CompressFormat.JPEG, 70, output))
output.toByteArray()
}
android.util.Log.i("NavFrame", "FRAME_RENDER mode=$mode bytes=${bytes.size} elapsedMs=${(System.nanoTime()-start)/1_000_000}")
TftFrame(encodedBytes = bytes, timestampMs = System.currentTimeMillis())
} finally { bitmap.recycle() }
}
}
@@ -0,0 +1,50 @@
package dev.navframe.app
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import dev.navframe.core.NavigationState
import dev.navframe.core.TftFrame
import dev.navframe.core.TftRenderer
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
/** Draws at native TFT size; no phone view is captured or scaled. */
class TestTftRenderer : TftRenderer {
override suspend fun render(state: NavigationState): TftFrame = renderTest(false)
suspend fun renderTest(synthetic: Boolean): TftFrame = withContext(Dispatchers.Default) {
val started = System.nanoTime()
val bitmap = Bitmap.createBitmap(480, 240, Bitmap.Config.ARGB_8888)
try {
val canvas = Canvas(bitmap)
canvas.drawColor(Color.BLACK)
val text = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.WHITE; textAlign = Paint.Align.CENTER }
if (synthetic) {
text.textSize = 32f
canvas.drawText("YAMAHA TFT NAV", 240f, 48f, text)
text.textSize = 24f
canvas.drawText("480 × 240", 240f, 84f, text)
text.color = Color.rgb(80, 227, 194)
text.textSize = 32f
canvas.drawText("NEXT TURN → 350 m", 240f, 144f, text)
text.color = Color.WHITE
text.textSize = 28f
canvas.drawText("23 km ETA 17:42", 240f, 204f, text)
} else {
text.textSize = 38f
canvas.drawText("YAMAHA TFT TEST", 240f, 112f, text)
text.textSize = 32f
canvas.drawText("480 × 240", 240f, 164f, text)
}
val encoded = ByteArrayOutputStream().use { bytes ->
check(bitmap.compress(Bitmap.CompressFormat.JPEG, 70, bytes))
bytes.toByteArray()
}
android.util.Log.i("NavFrame", "FRAME_ENCODE width=480 height=240 bytes=${encoded.size} elapsedMs=${(System.nanoTime()-started)/1_000_000}")
TftFrame(encodedBytes = encoded, timestampMs = System.currentTimeMillis())
} finally { bitmap.recycle() }
}
}
@@ -0,0 +1,36 @@
package dev.navframe.app
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.view.View
import dev.navframe.core.TftFrame
/** Decode the transmitted JPEG. Scaling affects only the phone preview. */
class TftPreviewView(context: Context) : View(context) {
private var bitmap: Bitmap? = null
private val destination = Rect()
private val paint = Paint(Paint.FILTER_BITMAP_FLAG)
fun showFrame(frame: TftFrame) {
val next = BitmapFactory.decodeByteArray(frame.encodedBytes, 0, frame.encodedBytes.size) ?: return
require(next.width == 480 && next.height == 240)
bitmap?.recycle()
bitmap = next
contentDescription = "Vista TFT, imagen JPEG nativa de 480 por 240 píxeles"
invalidate()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val width = MeasureSpec.getSize(widthMeasureSpec)
setMeasuredDimension(width, width / 2)
}
override fun onDraw(canvas: Canvas) {
canvas.drawColor(Color.BLACK)
destination.set(0, 0, width, height)
bitmap?.let { canvas.drawBitmap(it, null, destination, paint) }
}
override fun onDetachedFromWindow() { bitmap?.recycle(); bitmap = null; super.onDetachedFromWindow() }
}
@@ -0,0 +1,844 @@
package dev.navframe.app
import android.app.*
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.*
import dev.navframe.core.*
import dev.navframe.navilite.NaviLiteTransport
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
/** The started foreground service owns real sessions independently of activity bindings. */
class TftService : Service() {
inner class LocalBinder : Binder() { val service get() = this@TftService }
private val binder = LocalBinder()
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
private val renderer = TestTftRenderer()
private val navigationRenderer = SyntheticTftRenderer()
private var routeJob: Job? = null
private var routeGeneration = 0L
private var preparedGeneration = 0L
internal var routingEngineFactory: (String) -> RoutingEngine = { ValhallaRoutingEngine(it, "dev.navframe.app/0.6-prototype", language = { NavigationVoicePreferences.language(this).tag }) }
internal var mapRenderOverride: (suspend (NavigationState, NavigationMode) -> TftFrame)? = null
private var routePlan: RoutePlan? = null
private var preparedDestinationDirty = false
private var shownRoute: RoutePlan? = null
private var routePreview = true
private var guidance: RouteGuidanceTracker? = null
private var routeDemo: RouteDemo? = null
private var routeDemoStartedMs = 0L
private var rerouteJob: Job? = null
private val reroutePolicy = ReroutePolicy()
private var rerouteFailures = 0
private var reroutePaused = false
private var lastGpsFix: LocationFix? = null
private var lastGpsElapsed = 0L
private val mutableRouteInfo = MutableStateFlow("Sin ruta calculada")
val routeInfo = mutableRouteInfo.asStateFlow()
private data class RoutePlan(val route: RouteResult, val origin: GeoPoint, val demo: Boolean, val options: RouteOptions = RouteOptions())
private var navigationJob: Job? = null
private var locationProvider: AndroidLocationProvider? = null
private var gpsRequested = false
private val mutableGpsReady = MutableStateFlow(false)
val gpsReady = mutableGpsReady.asStateFlow()
private var phoneVisible = false
private var visibleGpsJob: Job? = null
private var visibleGpsProvider: AndroidLocationProvider? = null
private var previewJob: Job? = null
private var navigationEpoch = 0L
private val mutableNavigationState = MutableStateFlow(NavigationState())
val navigationState = mutableNavigationState.asStateFlow()
private var latestNavigationState = NavigationState()
set(value) {
field = value; mutableNavigationState.value = value
if (shownRoute?.demo == false && !routePreview) voice?.update(value)
else voice?.reset()
}
private var voice: NavigationVoiceController? = null
private val speedCameraAlerts = SpeedCameraAlertEngine()
private val speedCameraRepository by lazy { OfflinePlaceRepository(applicationContext) }
private var cameraJob: Job? = null
private var radarAlertExpiryJob: Job? = null
private var cameraCheckAt = 0L
private val mutableRadarAlert = MutableStateFlow<String?>(null)
val radarAlert = mutableRadarAlert.asStateFlow()
private val mutableVoiceEnabled = MutableStateFlow(true)
val voiceEnabled = mutableVoiceEnabled.asStateFlow()
private val mutableVoiceStatus = MutableStateFlow("Voz: preparando motor español")
val voiceStatus = mutableVoiceStatus.asStateFlow()
private var mapRenderer: MapLibreTftRenderer? = null
private val mutableMapDiagnostic = MutableStateFlow("TFT MAP · sin captura")
val mapDiagnostic = mutableMapDiagnostic.asStateFlow()
private var lastMapFailureDiagnostic = "sin fallo registrado"
private var mapRenderStarted = 0L
private var mapRenderStage = MapRenderStage.INITIALIZE
private var mapRetryAt = 0L
private var mapFailures = 0
private var unavailableMapFrame: TftFrame? = null
private val mutableMode = MutableStateFlow(NavigationMode.IDLE)
val navigationMode = mutableMode.asStateFlow()
private val mutableNavigationInfo = MutableStateFlow("Navegación detenida")
val navigationInfo = mutableNavigationInfo.asStateFlow()
private var sessionJob: Job? = null
private var fakeTransport: FakeTftTransport? = null
private var realRequested = false
private var wakeLock: PowerManager.WakeLock? = null
private val mutableState = MutableStateFlow(ConnectionState.DISCONNECTED)
val connectionState = mutableState.asStateFlow()
private val mutableFrame = MutableStateFlow<TftFrame?>(null)
val lastFrame = mutableFrame.asStateFlow()
private val mutableMessage = MutableStateFlow("Listo para prueba TFT")
val message = mutableMessage.asStateFlow()
private val mutableInterval = MutableStateFlow(1_000L)
val intervalMs = mutableInterval.asStateFlow()
private var notificationText = "Conectando con Yamaha…"
override fun onCreate() {
super.onCreate()
mutableInterval.value = getSharedPreferences("tft", MODE_PRIVATE).getLong("interval_ms", 1_000).coerceIn(500, 3_000)
voice = NavigationVoiceController(this).also { controller ->
mutableVoiceEnabled.value = controller.enabled.value
scope.launch { controller.status.collect { mutableVoiceStatus.value = it } }
}
}
fun setVoiceEnabled(enabled: Boolean) { mutableVoiceEnabled.value = enabled; voice?.setEnabled(enabled) }
fun voiceLanguageSelection(): String = NavigationVoicePreferences.selection(this)
fun setVoiceLanguage(selection: String) { NavigationVoicePreferences.save(this, selection); voice?.languageChanged() }
fun speakNavigationAlert(text: String) { voice?.speakAlert(text) }
private fun checkSpeedCameras(state: NavigationState, now: Long) {
if (!getSharedPreferences("navigation_alerts", MODE_PRIVATE).getBoolean("radars_enabled", false) ||
shownRoute?.demo != false || routePreview || state.navigationStatus != NavigationStatus.NAVIGATING || state.route == null) {
cameraJob?.cancel(); cameraJob = null
radarAlertExpiryJob?.cancel(); radarAlertExpiryJob = null
speedCameraAlerts.reset(); mutableRadarAlert.value = null
return
}
if (cameraJob?.isActive == true || now < cameraCheckAt) return
val fix = lastGpsFix ?: return
val fixElapsed = lastGpsElapsed
val epoch = navigationEpoch
val route = state.route
cameraCheckAt = now + 2_000
cameraJob = scope.launch {
try {
val cameras = speedCameraRepository.speedCameras(fix.position)
ensureActive()
if (epoch != navigationEpoch || latestNavigationState.route !== route ||
latestNavigationState.navigationStatus != NavigationStatus.NAVIGATING ||
!getSharedPreferences("navigation_alerts", MODE_PRIVATE).getBoolean("radars_enabled", false)) return@launch
val elapsed = SystemClock.elapsedRealtime()
speedCameraAlerts.update(fix, cameras, elapsed, elapsed - fixElapsed, route)?.let { alert ->
mutableRadarAlert.value = alert.label
radarAlertExpiryJob?.cancel()
radarAlertExpiryJob = scope.launch {
delay(5_000)
mutableRadarAlert.value = null
}
voice?.speakCameraAlert(alert.distanceMeters)
}
} catch (cancelled: CancellationException) { throw cancelled }
catch (error: Exception) { android.util.Log.w("NavFrame", "RADAR_LOOKUP_FAILED type=${error.javaClass.simpleName}") }
}
}
override fun onBind(intent: Intent): IBinder = binder
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action) {
ACTION_REAL -> {
val address = intent.getStringExtra(EXTRA_ADDRESS)
if (address == null) { stopSelf(); return START_NOT_STICKY }
if (intent.getBooleanExtra(EXTRA_AUTO, false) && realRequested) return START_NOT_STICKY
if (intent.getBooleanExtra(EXTRA_AUTO, false) && getSharedPreferences("yamaha", MODE_PRIVATE).getBoolean("paused", false)) return START_NOT_STICKY
if (Build.VERSION.SDK_INT >= 31 && checkSelfPermission(android.Manifest.permission.BLUETOOTH_CONNECT) != android.content.pm.PackageManager.PERMISSION_GRANTED) return START_NOT_STICKY
getSharedPreferences("yamaha", MODE_PRIVATE).edit().putBoolean("paused", false).apply()
realRequested = true
notificationText = "Conectando con Yamaha…"
try { refreshForeground() } catch (_: RuntimeException) { realRequested = false; mutableState.value = ConnectionState.ERROR; return START_NOT_STICKY }
replaceSession {
try { runReal(address) }
catch (cancelled: CancellationException) { throw cancelled }
catch (error: Exception) {
realRequested = false
mutableState.value = ConnectionState.ERROR
mutableMessage.value = "No se pudo iniciar la sesión: ${error.message}"
android.util.Log.e("NavFrame", "TFT_SESSION_FAILED", error)
refreshForeground()
}
}
}
ACTION_GPS -> startGps()
ACTION_MAP_GPS -> startGps(true)
ACTION_ROUTE_GPS -> startRoute(intent.getBooleanExtra(EXTRA_PREVIEW, false))
ACTION_STOP_NAVIGATION -> stopNavigation()
ACTION_STOP -> { stopNavigation(); disconnect() }
}
// Explicit user sessions are not silently resumed after process death or force-stop.
return START_NOT_STICKY
}
/** Waiting non-cancellably for cleanup also handles several rapid connect/stop requests. */
private fun replaceSession(action: suspend () -> Unit) {
val previous = sessionJob
previous?.cancel()
sessionJob = scope.launch {
withContext(NonCancellable) { previous?.join() }
ensureActive()
fakeTransport?.disconnect()
fakeTransport = null
action()
}
}
fun connectFake() {
getSharedPreferences("yamaha", MODE_PRIVATE).edit().putBoolean("paused", true).apply()
realRequested = false
replaceSession {
refreshForeground()
val fake = FakeTftTransport().also { fakeTransport = it }
fake.connect()
mutableState.value = ConnectionState.CONNECTED
fake.sendFrame(ensureFrame())
mutableMessage.value = "Simulador conectado · sin sesión Bluetooth continua"
}
}
private suspend fun ensureFrame(): TftFrame {
return mutableFrame.value ?: renderer.renderTest(false).also { mutableFrame.value = it }
}
private suspend fun runReal(address: String): Nothing = coroutineScope {
val lock = getSystemService(PowerManager::class.java).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "NavFrame:TftSession").apply {
setReferenceCounted(false)
}
wakeLock = lock
var renewal: Job? = null
try {
ensureFrame()
lock.acquire(120_000)
renewal = launch {
while (isActive) { delay(30_000); lock.acquire(120_000) }
}
TftSessionRunner(
transportFactory = { NaviLiteTransport(applicationContext, address) },
latestFrame = { requireNotNull(mutableFrame.value) },
policy = { TftSessionPolicy(effectiveInterval()) },
clockMs = { SystemClock.elapsedRealtime() },
onState = { state ->
mutableState.value = state
if (state == ConnectionState.CONNECTING || state == ConnectionState.HANDSHAKING) {
updateNotification(if (state == ConnectionState.CONNECTING) "Conectando con Yamaha…" else "Preparando sesión TFT…")
}
},
onSent = { frame, elapsed ->
mutableMessage.value = "Sesión continua · ${effectiveInterval()} ms · ${frame.encodedBytes.size} bytes · ACK ${elapsed} ms"
updateNotification("Conectado · envío cada ${effectiveInterval()} ms")
android.util.Log.i("NavFrame", "FRAME_SENT bytes=${frame.encodedBytes.size} ackMs=$elapsed")
},
onRetry = { error, wait ->
mutableMessage.value = "Conexión interrumpida: ${error.message ?: error.javaClass.simpleName} · reintento en ${wait / 1_000} s"
updateNotification("Reconectando en ${wait / 1_000} s · Desconectar para detener")
android.util.Log.w("NavFrame", "TFT_RETRY delayMs=$wait", error)
},
).run()
} finally {
renewal?.cancel()
if (lock.isHeld) lock.release()
if (wakeLock === lock) wakeLock = null
}
}
/** Manual changes replace cached JPEG; only the real session loop writes to Bluetooth. */
fun sendTestFrame(useSynthetic: Boolean) {
if (!realRequested && fakeTransport == null) { mutableMessage.value = "Conecta primero el simulador o la Yamaha."; return }
stopNavigation(false)
val epoch = navigationEpoch
scope.launch {
val frame = renderer.renderTest(useSynthetic)
if (epoch == navigationEpoch) publishFrame(frame)
if (realRequested) mutableMessage.value = "Imagen preparada para el siguiente envío continuo."
}
}
fun setInterval(interval: Long) {
require(interval in 500..3_000)
mutableInterval.value = interval
getSharedPreferences("tft", MODE_PRIVATE).edit().putLong("interval_ms", interval).apply()
}
fun disconnect(manual: Boolean = true) {
if (manual) getSharedPreferences("yamaha", MODE_PRIVATE).edit().putBoolean("paused", true).apply()
realRequested = false
replaceSession {
mutableState.value = ConnectionState.DISCONNECTED
mutableMessage.value = "Desconectado · envío y reconexión detenidos"
refreshForeground()
}
}
private fun effectiveInterval(): Long =
if (isMapMode(mutableMode.value)) mutableInterval.value
else if (mutableMode.value != NavigationMode.IDLE && latestNavigationState.navigationStatus == NavigationStatus.NAVIGATING && latestNavigationState.speed >= 0.7f) 200L
else mutableInterval.value
private fun refreshForeground() {
if (!realRequested && !gpsRequested) { stopForeground(STOP_FOREGROUND_REMOVE); stopSelf(); return }
if (Build.VERSION.SDK_INT >= 29) {
val types = (if (realRequested) ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE else 0) or
(if (gpsRequested) ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION else 0)
startForeground(1, notification(), types)
} else startForeground(1, notification())
}
private suspend fun publishFrame(frame: TftFrame) {
currentCoroutineContext().ensureActive()
mutableFrame.value = frame
fakeTransport?.sendFrame(frame)
}
private fun clearNavigation() {
voice?.reset()
cameraJob?.cancel(); cameraJob = null; cameraCheckAt = 0L
radarAlertExpiryJob?.cancel(); radarAlertExpiryJob = null
speedCameraAlerts.reset(); mutableRadarAlert.value = null
previewJob?.cancel(); previewJob = null
if (rerouteJob?.isActive == true) reroutePolicy.markFinished(SystemClock.elapsedRealtime())
rerouteJob?.cancel()
rerouteJob = null
navigationEpoch++
latestNavigationState = NavigationState()
navigationJob?.cancel()
navigationJob = null
mapRenderer?.close()
mapRenderer = null
mapRetryAt = 0L
mapFailures = 0
unavailableMapFrame = null
try { locationProvider?.close() } catch (_: SecurityException) { }
locationProvider = null
gpsRequested = false
}
fun stopNavigation(clearFrame: Boolean = true) {
previewJob?.cancel()
cancelRouteRequest()
shownRoute = null
routePlan = null
mutableRouteInfo.value = "Ruta detenida"
guidance = null
routeDemo = null
clearNavigation()
mutableMode.value = NavigationMode.IDLE
mutableNavigationInfo.value = "Navegación detenida · conexión TFT conservada"
refreshForeground()
if (clearFrame) {
val epoch = navigationEpoch
scope.launch {
val frame = navigationRenderer.render(NavigationState(), NavigationMode.IDLE, null)
if (epoch == navigationEpoch) publishFrame(frame)
}
}
}
fun startDemo(map: Boolean = false, preserveRoute: Boolean = false) {
if (!preserveRoute) {
cancelRouteRequest()
shownRoute = null
routePlan = null
guidance = null
routeDemo = null
mutableRouteInfo.value = "Sin ruta · cambio de modo"
}
clearNavigation()
val mode = if (map) NavigationMode.MAP_DEMO else NavigationMode.DEMO
mutableMode.value = mode
mutableNavigationInfo.value = if (map) "MAPA · posición simulada · sin ruta" else "DEMO · carretera, ruta y maniobras ficticias"
refreshForeground()
navigationJob = scope.launch {
val scheduler = createScheduler(mode)
val start = SystemClock.elapsedRealtime()
val startEpoch = System.currentTimeMillis()
try {
while (isActive) {
val now = SystemClock.elapsedRealtime()
val simulated = if (map && !routePreview && shownRoute?.demo == true) requireNotNull(routeDemo).stateAt(now - routeDemoStartedMs, System.currentTimeMillis())
else if (map && shownRoute?.demo == true) NavigationState(position = requireNotNull(shownRoute).origin, bearing = 0f, accuracyMeters = 2f)
else DemoNavigation.stateAt(now - start, startEpoch)
latestNavigationState = if (map) withRoute(simulated, true) else simulated
scheduler.offer(latestNavigationState)
val ready = scheduler.takeIfDue(now) ?: if (map && mapRetryAt > 0 && now >= mapRetryAt) latestNavigationState else null
if (ready != null) {
publishFrame(renderNavigationFrame(ready, mode))
scheduler.markRendered(ready, SystemClock.elapsedRealtime())
}
delay(50)
}
} catch (cancelled: CancellationException) { throw cancelled }
catch (error: Exception) {
latestNavigationState = NavigationState()
mutableMode.value = NavigationMode.IDLE
mutableNavigationInfo.value = "Demo detenida: ${error.javaClass.simpleName}"
android.util.Log.w("NavFrame", "DEMO_FAILED type=${error.javaClass.simpleName}")
try { publishFrame(navigationRenderer.render(NavigationState(), NavigationMode.IDLE, null)) }
catch (cancelled: CancellationException) { throw cancelled }
catch (_: Exception) { }
}
}
}
private fun startGps(map: Boolean = false, preserveRoute: Boolean = false) {
stopVisibleGps()
if (!preserveRoute) {
cancelRouteRequest()
shownRoute = null
routePlan = null
guidance = null
routeDemo = null
mutableRouteInfo.value = "Sin ruta · cambio de modo"
}
if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
mutableNavigationInfo.value = "GPS requiere ubicación precisa; actívala desde la pantalla de NavFrame."
if (!realRequested && !gpsRequested) stopSelf()
return
}
val manager = getSystemService(android.location.LocationManager::class.java)
if (!manager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
mutableNavigationInfo.value = "Activa GPS en los ajustes de ubicación y pulsa GPS de nuevo."
if (!realRequested && !gpsRequested) stopSelf()
return
}
clearNavigation()
gpsRequested = true
val mode = if (map) NavigationMode.MAP_GPS else NavigationMode.GPS
mutableMode.value = mode
mutableNavigationInfo.value = if (map) "MAPA GPS · esperando posición · sin ruta" else "GPS · SIN MAPA/RUTA · esperando posición"
try { refreshForeground() }
catch (error: RuntimeException) {
gpsRequested = false
mutableMode.value = NavigationMode.IDLE
mutableNavigationInfo.value = "No se pudo iniciar GPS: ${error.javaClass.simpleName}"
refreshForeground()
return
}
navigationJob = scope.launch {
val provider = AndroidLocationProvider(applicationContext).also { locationProvider = it }
val scheduler = createScheduler(mode)
var state = NavigationState(navigationStatus = NavigationStatus.GPS_LOST, bearing = Float.NaN)
try {
coroutineScope {
launch {
provider.locations.collect { fix ->
lastGpsFix = fix
lastGpsElapsed = provider.lastFixElapsedMs
mutableGpsReady.value = hasFreshGpsFix()
state = NavigationState(position = fix.position, bearing = fix.bearing, speed = fix.speedMetersPerSecond, navigationStatus = NavigationStatus.NAVIGATING, accuracyMeters = fix.accuracyMeters)
scheduler.offer(state)
}
}
provider.start()
while (isActive) {
val now = SystemClock.elapsedRealtime()
mutableGpsReady.value = hasFreshGpsFix()
val lost = !provider.providerEnabled.value || provider.lastFixElapsedMs == 0L || now - provider.lastFixElapsedMs > 15_000
if (lost && state.navigationStatus != NavigationStatus.GPS_LOST) {
state = state.copy(speed = 0f, bearing = Float.NaN, navigationStatus = NavigationStatus.GPS_LOST, accuracyMeters = null)
}
state = withRoute(state, false)
latestNavigationState = state
checkSpeedCameras(state, now)
if (state.navigationStatus == NavigationStatus.OFF_ROUTE && reroutePolicy.shouldRequest(state, now)) requestReroute(false)
scheduler.offer(state)
val ready = scheduler.takeIfDue(now) ?: if (map && mapRetryAt > 0 && now >= mapRetryAt) latestNavigationState else null
if (ready != null) {
publishFrame(renderNavigationFrame(ready, mode))
scheduler.markRendered(ready, SystemClock.elapsedRealtime())
if (!map || mapFailures == 0) mutableNavigationInfo.value = if (state.navigationStatus == NavigationStatus.GPS_LOST || lost) "GPS_LOST · esperando señal reciente (máximo 15 s)" else {
val heading = ready.bearing.takeIf { it.isFinite() }?.toInt()?.toString() ?: "--"
val precision = ready.accuracyMeters?.takeIf { it.isFinite() }?.toInt()?.toString() ?: "--"
"${if (map && shownRoute != null) "MAPA GPS · ${ready.navigationStatus}" else if (map) "MAPA GPS · SIN RUTA" else "GPS · SIN MAPA/RUTA"} · ${(ready.speed * 3.6f).toInt()} km/h · $heading° · ± $precision m"
}
}
delay(100)
}
}
} catch (cancelled: CancellationException) { throw cancelled }
catch (error: Exception) {
rerouteJob?.cancel()
rerouteJob = null
navigationEpoch++
gpsRequested = false
mutableMode.value = NavigationMode.IDLE
latestNavigationState = NavigationState()
mutableNavigationInfo.value = "GPS detenido: ${error.javaClass.simpleName} · pulsa GPS para reintentar"
try { publishFrame(navigationRenderer.render(NavigationState(), NavigationMode.IDLE, null)) }
catch (cancelled: CancellationException) { throw cancelled }
catch (_: Exception) { }
// Avoid logging error objects that might contain a location payload.
android.util.Log.w("NavFrame", "GPS_FAILED type=${error.javaClass.simpleName}")
refreshForeground()
} finally {
try { provider.close() } catch (_: SecurityException) { }
if (locationProvider === provider) locationProvider = null
}
}
}
fun routingEndpoint(): String = getSharedPreferences("routing", MODE_PRIVATE).getString("endpoint", ValhallaRoutingEngine.DEFAULT_ENDPOINT) ?: ValhallaRoutingEngine.DEFAULT_ENDPOINT
/** A chosen search result invalidates a prepared plan while retaining ongoing guidance. */
fun selectSearchDestination() {
invalidateRoutePlan()
mutableRouteInfo.value = "Destino cambiado · calcula una nueva ruta. El guiado actual continúa."
}
/** Prepared requests never clear the active route/tracker; Start/Stop are the explicit swap points. */
fun invalidateRoutePlan() {
previewJob?.cancel()
if (routePreview && shownRoute != null) {
shownRoute = null
latestNavigationState = latestNavigationState.copy(route = null, nextManeuver = null, distanceToNextManeuverMeters = null, remainingDistanceMeters = null, etaEpochMillis = null, navigationStatus = NavigationStatus.IDLE)
}
preparedGeneration++
routeJob?.cancel()
routeJob = null
routePlan = null
preparedDestinationDirty = true
mutableRouteInfo.value = "Sin plan preparado · el guiado actual continúa"
}
fun calculateRoute(destination: GeoPoint, demoOrigin: Boolean, endpoint: String, options: RouteOptions = RouteOptions()) {
invalidateRoutePlan()
ValhallaRoutingEngine.validatePoint(destination)
ValhallaRoutingEngine.validateEndpoint(endpoint)
val origin = if (demoOrigin) DemoNavigation.stateAt(0).position else {
val fix = lastGpsFix
if (fix == null || !hasFreshGpsFix()) {
mutableRouteInfo.value = "Origen GPS no disponible: inicia GPS y espera una posición reciente."
return
}
fix.position
}
val generation = preparedGeneration
val preferences = getSharedPreferences("routing", MODE_PRIVATE)
preferences.edit().putString("endpoint", endpoint.trim()).apply()
mutableRouteInfo.value = "Calculando ruta · origen ${if (demoOrigin) "DEMO simulado" else "GPS real"}…"
routeJob = scope.launch {
try {
val result = routingEngineFactory(endpoint.trim()).calculateRoute(origin, destination, options)
ensureActive()
if (generation != preparedGeneration) return@launch
routePlan = RoutePlan(result, origin, demoOrigin, options)
preparedDestinationDirty = false
mutableRouteInfo.value = "Vista previa · ${if (demoOrigin) "origen DEMO" else "origen GPS"} · %.1f km · %d min estimados · %d maniobras\nRevisa la ruta en el mapa e inicia el guiado cuando estés listo. DEMO recorre la geometría calculada; GPS permite recálculo por desvío.".format(java.util.Locale.ROOT, result.distanceMeters / 1000.0, (result.durationSeconds + 59) / 60, result.maneuvers.size)
if (result.hasUnpaved == true) mutableRouteInfo.value += "\nEl servidor indica tramos sin asfaltar."
showPreparedPreview()
} catch (cancelled: CancellationException) {
currentCoroutineContext().ensureActive()
mutableRouteInfo.value = "Tiempo de espera agotado · solicita la ruta de nuevo."
} catch (error: Exception) {
if (generation == preparedGeneration) mutableRouteInfo.value = "No se pudo calcular: ${if (error is java.io.IOException && error.message?.startsWith("Servidor de rutas: HTTP") == true) error.message else "revisa Internet, endpoint y coordenadas"}"
}
}
}
fun cancelRouteRequest() {
preparedGeneration++
if (rerouteJob?.isActive == true) {
rerouteJob?.cancel()
rerouteJob = null
reroutePolicy.markFinished(SystemClock.elapsedRealtime())
reroutePaused = true
}
routeGeneration++
routeJob?.cancel()
routeJob = null
}
fun previewPreparedRoute() {
if (hasActiveGuidance()) { mutableRouteInfo.value = "El guiado actual continúa · Iniciar reemplaza la ruta, Detener permite ver la previa"; return }
showPreparedPreview()
}
fun hasActiveGuidance(): Boolean = shownRoute != null && !routePreview
private fun showPreparedPreview() {
val plan = routePlan ?: return
if (hasActiveGuidance()) return
previewJob?.cancel()
clearNavigation()
mutableMode.value = if (plan.demo) NavigationMode.MAP_DEMO else NavigationMode.MAP_GPS
refreshForeground()
shownRoute = plan
routePreview = true
val state = NavigationState(position = plan.origin, route = plan.route, navigationStatus = NavigationStatus.ROUTE_PREVIEW, accuracyMeters = if (plan.demo) null else lastGpsFix?.accuracyMeters)
latestNavigationState = state
val mode = if (plan.demo) NavigationMode.MAP_DEMO else NavigationMode.MAP_GPS
val generation = preparedGeneration
previewJob = scope.launch {
val frame = renderNavigationFrame(state, mode)
ensureActive()
if (generation == preparedGeneration && routePreview) publishFrame(frame)
}
}
fun hasPreparedRoute() = !preparedDestinationDirty && routePlan != null
fun routeUsesGps() = !preparedDestinationDirty && routePlan?.demo == false
fun startRoute(preview: Boolean = false) {
previewJob?.cancel()
if (preview && shownRoute != null && !routePreview) {
mutableRouteInfo.value = "Detén el guiado para ver la vista previa, o inicia la nueva ruta. El guiado actual continúa."
return
}
if (preparedDestinationDirty) { mutableRouteInfo.value = "Destino cambiado · calcula una nueva ruta primero."; return }
val plan = routePlan ?: run { mutableRouteInfo.value = "Calcula una ruta primero."; return }
if (!preview && !plan.demo && !hasFreshGpsFix()) { mutableRouteInfo.value = "Espera GPS reciente y preciso antes de iniciar guiado"; return }
shownRoute = plan
routePreview = preview
guidance = RouteGuidanceTracker(plan.route)
routeDemo = RouteDemo(plan.route)
routeDemoStartedMs = SystemClock.elapsedRealtime()
reroutePolicy.reset()
rerouteFailures = 0
reroutePaused = false
if (plan.demo) startDemo(true, preserveRoute = true) else startGps(true, preserveRoute = true)
mutableRouteInfo.value = "${if (preview) "Vista previa" else "Guiado iniciado"} · ${if (plan.demo) "posición DEMO simulada" else "GPS real"} · %.1f km · %d min planificados\nGuiado por geometría · ETA estimada. ${if (plan.demo) "Recorrido DEMO ficticio, sin GPS real ni recálculo automático." else "Recálculo por desvío sostenido; no sustituye señales viales."}".format(java.util.Locale.ROOT, plan.route.distanceMeters / 1000.0, (plan.route.durationSeconds + 59) / 60)
}
fun stopRoute() {
cameraJob?.cancel(); cameraJob = null
radarAlertExpiryJob?.cancel(); radarAlertExpiryJob = null
speedCameraAlerts.reset(); mutableRadarAlert.value = null
previewJob?.cancel()
rerouteJob?.cancel()
rerouteJob = null
guidance = null
routeDemo = null
cancelRouteRequest()
shownRoute = null
routePlan = null
mutableRouteInfo.value = "Ruta detenida · GPS/mapa y conexión TFT conservados"
latestNavigationState = latestNavigationState.copy(route = null, nextManeuver = null, remainingDistanceMeters = null, distanceToNextManeuverMeters = null, etaEpochMillis = null, navigationStatus = if (hasFreshGpsFix()) NavigationStatus.NAVIGATING else NavigationStatus.GPS_LOST)
if (navigationJob?.isActive != true) {
val epoch = navigationEpoch
scope.launch {
val frame = navigationRenderer.render(NavigationState(), NavigationMode.IDLE, null)
if (epoch == navigationEpoch && shownRoute == null) publishFrame(frame)
}
}
}
private fun withRoute(state: NavigationState, demo: Boolean): NavigationState {
val plan = shownRoute?.takeIf { it.demo == demo }
if (plan == null) return state.copy(route = null, nextManeuver = null, distanceToNextManeuverMeters = null, remainingDistanceMeters = null, etaEpochMillis = null)
if (state.navigationStatus == NavigationStatus.GPS_LOST) return state.copy(route = plan.route, nextManeuver = null, distanceToNextManeuverMeters = null, remainingDistanceMeters = null, etaEpochMillis = null)
if (routePreview) return state.copy(route = plan.route, nextManeuver = null, distanceToNextManeuverMeters = null, navigationStatus = NavigationStatus.ROUTE_PREVIEW)
val guided = if (demo) state.copy(route = plan.route) else {
val fix = lastGpsFix ?: return state.copy(route = plan.route, navigationStatus = NavigationStatus.GPS_LOST)
requireNotNull(guidance).update(fix, SystemClock.elapsedRealtime(), System.currentTimeMillis(), SystemClock.elapsedRealtime() - lastGpsElapsed)
}
return if (rerouteJob?.isActive == true && guided.navigationStatus != NavigationStatus.GPS_LOST) guided.copy(navigationStatus = NavigationStatus.REROUTING, nextManeuver = null, distanceToNextManeuverMeters = null, remainingDistanceMeters = null, etaEpochMillis = null) else guided
}
fun requestReroute(manual: Boolean = true) {
val plan = shownRoute ?: return
if (plan.demo || routePreview || rerouteJob?.isActive == true) return
val now = SystemClock.elapsedRealtime()
val fix = lastGpsFix
if (fix == null || now - lastGpsElapsed > 15_000 || !fix.accuracyMeters.isFinite() || fix.accuracyMeters > 25f || locationProvider?.providerEnabled?.value != true) {
mutableRouteInfo.value = "Recálculo espera GPS reciente y precisión ≤25 m"
return
}
if (!manual && (reroutePaused || rerouteFailures >= 3)) return
if (manual && !reroutePolicy.shouldRequest(latestNavigationState.copy(navigationStatus = NavigationStatus.OFF_ROUTE), now)) {
mutableRouteInfo.value = "Recálculo en espera · deja al menos 30 s entre intentos"
return
}
if (manual) { reroutePaused = false; rerouteFailures = 0 }
reroutePolicy.markRequested(now)
val epoch = navigationEpoch
val generation = routeGeneration
mutableRouteInfo.value = "RECALCULANDO · ruta anterior conservada hasta recibir una nueva"
rerouteJob = scope.launch {
var retryAfterMs = 0L
try {
val result = routingEngineFactory(routingEndpoint()).calculateRoute(fix.position, plan.route.destination ?: plan.route.geometry.last(), plan.options)
ensureActive()
if (epoch != navigationEpoch || generation != routeGeneration || shownRoute !== plan) return@launch
val replacement = RoutePlan(result, fix.position, false, plan.options)
shownRoute = replacement
if (!preparedDestinationDirty && routePlan === plan) routePlan = replacement
guidance = RouteGuidanceTracker(result)
rerouteFailures = 0
mutableRouteInfo.value = "Ruta recalculada · guiado GPS activo"
} catch (cancelled: CancellationException) {
currentCoroutineContext().ensureActive()
rerouteFailures++
mutableRouteInfo.value = "Recálculo sin respuesta · ruta anterior conservada · próximo intento tras 30 s"
} catch (error: Exception) {
if (epoch != navigationEpoch || generation != routeGeneration) return@launch
rerouteFailures++
if (error is RoutingHttpException && error.status == 429) { reroutePaused = true; retryAfterMs = error.retryAfterMs }
mutableRouteInfo.value = if (reroutePaused || rerouteFailures >= 3) "Recálculo automático pausado · pulsa Recalcular ahora para reintentar" else "Recálculo fallido · ruta anterior conservada · espera ≥30 s"
} finally {
if (epoch == navigationEpoch && generation == routeGeneration) reroutePolicy.markFinished(SystemClock.elapsedRealtime(), retryAfterMs)
}
}
}
private fun isMapMode(mode: NavigationMode) = mode == NavigationMode.MAP_DEMO || mode == NavigationMode.MAP_GPS
private fun createScheduler(mode: NavigationMode) = if (isMapMode(mode)) RenderScheduler(RenderScheduleConfig(stoppedMaxFps = .5, movingMaxFps = 1.0, turningMaxFps = 1.0, positionDeltaMeters = 5.0, bearingDeltaDegrees = 5f)) else RenderScheduler()
fun mapSource(): TileSource {
val preferences = getSharedPreferences("map", MODE_PRIVATE)
if (preferences.contains("attribution")) preferences.edit().remove("attribution").apply() // Provider credits are derived, never user editable.
return try {
ConfiguredMapDataSource(preferences.getString("style", "") ?: "", preferences.getString("attribution", ConfiguredMapDataSource.DEFAULT_ATTRIBUTION) ?: ConfiguredMapDataSource.DEFAULT_ATTRIBUTION, applicationContext).tileSource()
} catch (_: Exception) {
preferences.edit().remove("style").remove("attribution").apply()
ConfiguredMapDataSource().tileSource()
}
}
fun diagnosticReport(): String {
val origin = if (mapSource().uri.startsWith("file:")) "LOCAL PMTiles" else "ONLINE"
val fix = lastGpsFix
val accuracy = when { fix == null -> "SIN FIX"; !fix.accuracyMeters.isFinite() -> "DESCONOCIDA"; fix.accuracyMeters <= 5 -> "0–5 m"; fix.accuracyMeters <= 15 -> "6–15 m"; fix.accuracyMeters <= 25 -> "16–25 m"; else -> ">25 m" }
val age = if (fix == null) "SIN FIX" else if (SystemClock.elapsedRealtime() - lastGpsElapsed <= 15_000) "RECIENTE" else "CADUCADO"
return "NavFrame 0.13.0 · Android ${Build.VERSION.SDK_INT} · ${Build.MANUFACTURER} ${Build.MODEL}\nMapLibre OpenGL 13.5.2 · TFT nativo 480×240\nOrigen del mapa: $origin\n${mutableMapDiagnostic.value}\nÚltimo fallo: $lastMapFailureDiagnostic\nGPS: $age · precisión $accuracy · ${mutableNavigationState.value.navigationStatus}\nTFT: ${mutableState.value} · modo ${mutableMode.value}\nSin coordenadas, consultas, direcciones ni URLs."
}
fun isRealSessionRequested(): Boolean = realRequested
fun isGpsSessionActive(): Boolean = gpsRequested
fun hasFreshGpsFix(): Boolean = lastGpsFix?.let { it.accuracyMeters.isFinite() && it.accuracyMeters <= 25 && SystemClock.elapsedRealtime() - lastGpsElapsed in 0..15_000 && (locationProvider?.providerEnabled?.value == true || (phoneVisible && visibleGpsProvider?.providerEnabled?.value == true)) } == true
private fun stopVisibleGps() {
visibleGpsJob?.cancel(); visibleGpsJob = null
try { visibleGpsProvider?.close() } catch (_: SecurityException) { }
visibleGpsProvider = null
}
fun setPhoneVisible(visible: Boolean) {
phoneVisible = visible
if (!visible || checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
stopVisibleGps()
if (!gpsRequested) mutableGpsReady.value = false
return
}
if (gpsRequested || visibleGpsJob?.isActive == true) return
visibleGpsJob = scope.launch {
val provider = AndroidLocationProvider(applicationContext)
visibleGpsProvider = provider
try {
coroutineScope {
launch { provider.locations.collect { fix ->
lastGpsFix = fix; lastGpsElapsed = provider.lastFixElapsedMs
mutableGpsReady.value = hasFreshGpsFix()
if (!gpsRequested && mutableMode.value !in listOf(NavigationMode.MAP_DEMO, NavigationMode.DEMO)) {
latestNavigationState = latestNavigationState.copy(position = fix.position, bearing = fix.bearing, speed = fix.speedMetersPerSecond, accuracyMeters = fix.accuracyMeters, navigationStatus = if (routePreview && shownRoute != null) NavigationStatus.ROUTE_PREVIEW else if (fix.accuracyMeters <= 25) NavigationStatus.NAVIGATING else NavigationStatus.GPS_LOST)
}
} }
provider.start()
while (isActive) {
mutableGpsReady.value = hasFreshGpsFix()
if (!gpsRequested && (!provider.providerEnabled.value || SystemClock.elapsedRealtime() - provider.lastFixElapsedMs > 15_000) && mutableMode.value !in listOf(NavigationMode.MAP_DEMO, NavigationMode.DEMO)) latestNavigationState = latestNavigationState.copy(speed = 0f, bearing = Float.NaN, navigationStatus = NavigationStatus.GPS_LOST)
delay(1_000)
}
}
} catch (cancelled: CancellationException) { throw cancelled }
catch (_: Exception) { mutableNavigationInfo.value = "GPS visible no disponible · revisa ubicación y permisos" }
finally { try { provider.close() } catch (_: SecurityException) { }; if (visibleGpsProvider === provider) visibleGpsProvider = null }
}
}
fun recheckPermissions() {
if (realRequested && Build.VERSION.SDK_INT >= 31 && checkSelfPermission(android.Manifest.permission.BLUETOOTH_CONNECT) != android.content.pm.PackageManager.PERMISSION_GRANTED) disconnect(manual = false)
if (gpsRequested && checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) != android.content.pm.PackageManager.PERMISSION_GRANTED) stopNavigation()
}
fun saveMapSource(styleUrl: String, attribution: String) {
val next = ConfiguredMapDataSource(styleUrl, attribution, applicationContext).tileSource()
val previous = mapSource()
getSharedPreferences("map", MODE_PRIVATE).edit().putString("style", styleUrl.trim()).remove("attribution").apply()
if (next == previous) return
// Release the previous local archive even if restarting GPS fails permission/provider checks.
mapRenderer?.close(); mapRenderer = null
when (mutableMode.value) {
NavigationMode.MAP_DEMO -> if (routePreview && shownRoute != null) showPreparedPreview() else startDemo(true, preserveRoute = true)
NavigationMode.MAP_GPS -> if (routePreview && !gpsRequested && shownRoute != null) showPreparedPreview() else startGps(true, preserveRoute = true)
else -> { mapRenderer?.close(); mapRenderer = null }
}
}
private suspend fun renderNavigationFrame(state: NavigationState, mode: NavigationMode): TftFrame {
if (!isMapMode(mode)) return navigationRenderer.render(state, mode, state.accuracyMeters)
val source = mapSource()
if (state.navigationStatus == NavigationStatus.GPS_LOST && state.position == GeoPoint(0.0, 0.0)) {
return MapFrameComposer().compose(null, null, state, mode, source.attribution)
}
val now = SystemClock.elapsedRealtime()
if (mapRetryAt > now) return MapFrameComposer().compose(null, null, state, mode, source.attribution, unavailable = true, failureCode = mutableMapDiagnostic.value.split(" · ").getOrNull(1)).also { unavailableMapFrame = it }
mapRenderStarted = SystemClock.elapsedRealtime()
mapRenderStage = MapRenderStage.INITIALIZE
try {
mapRenderOverride?.let { return it(state, mode) }
val current = mapRenderer ?: MapLibreTftRenderer(applicationContext, ConfiguredMapDataSource(if (source.uri.startsWith("asset://")) "" else source.uri, source.attribution, applicationContext)) { stage ->
mapRenderStage = stage
mutableMapDiagnostic.value = "TFT MAP · ${stage.name} · ${if (source.uri.startsWith("file:")) "LOCAL" else "ONLINE"}"
}.also { mapRenderer = it }
val frame = current.render(state, mode)
mutableMapDiagnostic.value = "TFT MAP · OK · ${SystemClock.elapsedRealtime() - mapRenderStarted} ms · 480×240"
mapFailures = 0
mapRetryAt = 0
unavailableMapFrame = null
if (mode == NavigationMode.MAP_DEMO) mutableNavigationInfo.value = if (shownRoute == null) "MAPA · posición simulada · sin ruta · OpenStreetMap" else "DEMO FICTICIA · ${state.navigationStatus} · ${state.distanceToNextManeuverMeters?.let { "$it m" } ?: "--"} · geometría calculada"
return frame
} catch (cancelled: CancellationException) {
currentCoroutineContext().ensureActive() // A local map timeout is recoverable; STOP is not.
return mapUnavailable(state, mode, source.attribution, MapRenderException(MapRenderFailure.TIMEOUT, mapRenderStage))
} catch (error: Exception) {
return mapUnavailable(state, mode, source.attribution, error as? MapRenderException ?: MapRenderException(classifyMapRenderFailure(error.message), mapRenderStage, mapErrorDetail(error.message, error.javaClass.simpleName)))
}
}
private suspend fun mapUnavailable(state: NavigationState, mode: NavigationMode, attribution: String, error: MapRenderException): TftFrame {
mapRenderer?.close()
mapRenderer = null
mapFailures = (mapFailures + 1).coerceAtMost(4)
val retryMs = (2_000L shl (mapFailures - 1)).coerceAtMost(15_000)
mapRetryAt = SystemClock.elapsedRealtime() + retryMs
mutableMapDiagnostic.value = "TFT MAP · ${error.failure.name} · ${error.stage.name} · ${SystemClock.elapsedRealtime() - mapRenderStarted} ms · ${error.detail.safeText()} · intento $mapFailures · reintento ${retryMs / 1000} s"
lastMapFailureDiagnostic = mutableMapDiagnostic.value + " · " + if (mapSource().uri.startsWith("file:")) "LOCAL" else "ONLINE"
mutableNavigationInfo.value = "MAPA TFT NO DISPONIBLE · ${error.failure.name} · reintento ${retryMs / 1000} s"
android.util.Log.w("NavFrame", "MAP_UNAVAILABLE code=${error.failure.name} stage=${error.stage.name} retryMs=$retryMs") // No URLs, API tokens or coordinates.
return MapFrameComposer().compose(null, null, state, mode, attribution, unavailable = true, failureCode = error.failure.name).also { unavailableMapFrame = it }
}
private fun updateNotification(text: String) {
if (!realRequested || notificationText == text) return
notificationText = text
getSystemService(NotificationManager::class.java).notify(1, notification())
}
private fun notification(): Notification {
val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(NotificationChannel("tft", "Conexión Yamaha TFT", NotificationManager.IMPORTANCE_LOW))
val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE)
val stop = PendingIntent.getService(this, 1, Intent(this, TftService::class.java).setAction(ACTION_STOP), PendingIntent.FLAG_IMMUTABLE)
return Notification.Builder(this, "tft")
.setSmallIcon(android.R.drawable.ic_menu_compass)
.setContentTitle("NavFrame · Yamaha TFT")
.setContentText(if (realRequested) "$notificationText · ${mutableMode.value}" else "GPS activo · sin conexión TFT")
.setContentIntent(open).setOngoing(true).setOnlyAlertOnce(true)
.addAction(Notification.Action.Builder(null, "Detener todo", stop).build()).build()
}
override fun onDestroy() {
radarAlertExpiryJob?.cancel(); radarAlertExpiryJob = null; mutableRadarAlert.value = null
voice?.close(); voice = null
stopVisibleGps()
realRequested = false
cancelRouteRequest()
rerouteJob?.cancel()
navigationJob?.cancel()
mapRenderer?.close()
mapRenderer = null
try { locationProvider?.close() } catch (_: SecurityException) { }
locationProvider = null
scope.cancel() // Cancelling runner closes its socket in NonCancellable cleanup.
wakeLock?.let { if (it.isHeld) it.release() }
wakeLock = null
super.onDestroy()
}
companion object {
const val ACTION_REAL = "dev.navframe.CONNECT_REAL"
const val ACTION_GPS = "dev.navframe.START_GPS"
const val ACTION_MAP_GPS = "dev.navframe.START_MAP_GPS"
const val ACTION_ROUTE_GPS = "dev.navframe.START_ROUTE_GPS"
const val ACTION_STOP_NAVIGATION = "dev.navframe.STOP_NAVIGATION"
const val ACTION_STOP = "dev.navframe.DISCONNECT"
const val EXTRA_AUTO = "auto_connection"
const val EXTRA_ADDRESS = "device_address"
const val EXTRA_PREVIEW = "route_preview"
}
}
@@ -0,0 +1,71 @@
package dev.navframe.app
import dev.navframe.core.*
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.launch
/** Both result sources share the same route-sheet selection contract. */
data class PlaceSelection(
val name: String,
val position: GeoPoint,
val sourceLabel: String,
val attribution: String,
val offlinePlace: OfflinePlace? = null,
) {
companion object {
fun offline(place: OfflinePlace) = PlaceSelection(place.name, place.position, "Offline · ${place.category.labelSpanish}", "© OpenStreetMap contributors · ODbL", place)
fun online(place: SearchResult) = PlaceSelection(place.name, place.position, "Online · Nominatim", place.attribution)
}
}
data class UnifiedSearchResults(val results: List<PlaceSelection>, val onlineError: String? = null)
data class PlaceViewport(val south: Double, val west: Double, val north: Double, val east: Double) {
val center: GeoPoint get() = GeoPoint((south + north) / 2, if (west <= east) (west + east) / 2 else ((west + east + 360) / 2).let { if (it > 180) it - 360 else it })
}
class UnifiedPlaceSearch(private val repository: OfflinePlaceRepository) {
suspend fun searchOffline(center: GeoPoint, query: String, category: PlaceCategory? = null): List<PlaceSelection> =
repository.search(center, category, query).map(PlaceSelection::offline)
/** Invoke only from a deliberate search button or IME action. Never from a camera/text listener. */
suspend fun searchExplicit(center: GeoPoint, query: String, geocoder: Geocoder): UnifiedSearchResults {
val local = searchOffline(center, query)
return try {
UnifiedSearchResults(merge(local, geocoder.search(query).map(PlaceSelection::online)))
} catch (cancelled: CancellationException) { throw cancelled }
catch (error: Exception) { UnifiedSearchResults(local, error.message ?: "No se pudo buscar online") }
}
companion object {
internal fun merge(local: List<PlaceSelection>, online: List<PlaceSelection>): List<PlaceSelection> =
(local + online).distinctBy { Triple(normalizePlaceSearch(it.name), (it.position.latitude * 100000).toLong(), (it.position.longitude * 100000).toLong()) }
}
}
/** Cancelled camera queries cannot repaint a newer viewport. No GPS/network dependencies. */
class OfflineViewportController(
private val scope: CoroutineScope,
private val repository: OfflinePlaceRepository,
private val onPlaces: (List<OfflinePlace>) -> Unit,
private val onError: (Exception) -> Unit = {},
) {
private var job: Job? = null
private var generation = 0L
fun refresh(viewport: PlaceViewport) {
val request = ++generation
job?.cancel()
job = scope.launch {
delay(300)
try {
val places = repository.visible(viewport)
ensureActive()
if (request == generation) onPlaces(places)
} catch (cancelled: CancellationException) { throw cancelled }
catch (error: Exception) { if (request == generation) onError(error) }
}
}
fun cancel() { generation++; job?.cancel(); job = null }
}
@@ -0,0 +1,95 @@
package dev.navframe.app
import dev.navframe.core.*
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URI
import java.util.concurrent.atomic.AtomicReference
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
class RoutingHttpException(val status: Int, val retryAfterMs: Long) : IOException("Servidor de rutas: HTTP $status")
/** Explicit prototype requests only. No automatic recalc, request retry or location history. */
class ValhallaRoutingEngine(private val endpoint: String, private val clientId: String, private val language: () -> String = { "es-ES" }, private val openConnection: (String) -> HttpURLConnection = { URI(it).toURL().openConnection() as HttpURLConnection }) : RoutingEngine {
init { validateEndpoint(endpoint) }
override suspend fun calculateRoute(origin: GeoPoint, destination: GeoPoint, options: RouteOptions): RouteResult {
validatePoint(origin); validatePoint(destination)
val locale = GuidanceLanguage.resolve(language()).tag
val body = buildValhallaRequest(origin, destination, options, locale)
val response = withTimeout(25_000) {
rateGate.withLock {
val wait = 1_000 - (System.nanoTime() / 1_000_000 - lastRequestMs)
if (wait > 0) delay(wait)
lastRequestMs = System.nanoTime() / 1_000_000
}
request(body)
}
return withContext(Dispatchers.Default) { parseValhallaRoute(response, destination).copy(guidanceLanguage = locale) }
}
override suspend fun recalculateRoute(origin: GeoPoint, previousRoute: RouteResult, options: RouteOptions): RouteResult =
calculateRoute(origin, requireNotNull(previousRoute.destination) { "La ruta no tiene destino" }, options)
private suspend fun request(body: String): String = coroutineScope {
suspendCancellableCoroutine { continuation ->
val connection = AtomicReference<HttpURLConnection?>()
val worker = launch(Dispatchers.IO) {
try {
val http = openConnection(endpoint.trim())
connection.set(http)
ensureActive()
try {
http.requestMethod = "POST"; http.doOutput = true
http.connectTimeout = 10_000; http.readTimeout = 15_000
http.instanceFollowRedirects = false
http.setRequestProperty("Content-Type", "application/json; charset=utf-8")
http.setRequestProperty("User-Agent", "NavFrame/0.5 (Android prototype)")
http.setRequestProperty("X-Client-Id", clientId)
http.outputStream.use { it.write(body.toByteArray(Charsets.UTF_8)) }
val status = http.responseCode
if (status != 200) {
val retryAfter = http.getHeaderField("Retry-After")?.trim()
val waitMs = retryAfter?.toLongOrNull()?.coerceIn(0, 86_400)?.times(1_000) ?: run {
try { (java.time.ZonedDateTime.parse(retryAfter, java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME).toInstant().toEpochMilli() - System.currentTimeMillis()).coerceIn(0, 86_400_000) }
catch (_: Exception) { 0L }
}
throw RoutingHttpException(status, waitMs)
}
val bytes = http.inputStream.use { input ->
val output = java.io.ByteArrayOutputStream()
val buffer = ByteArray(8192)
while (true) {
ensureActive()
val count = input.read(buffer)
if (count < 0) break
require(output.size() + count <= 2_000_000) { "Respuesta de ruta demasiado grande" }
output.write(buffer, 0, count)
}
output.toByteArray()
}
require(bytes.size <= 2_000_000) { "Respuesta de ruta demasiado grande" }
if (continuation.isActive) continuation.resume(bytes.toString(Charsets.UTF_8))
} finally { http.disconnect(); connection.set(null) }
} catch (error: Exception) {
if (continuation.isActive) continuation.resumeWithException(error)
}
}
continuation.invokeOnCancellation { connection.getAndSet(null)?.disconnect(); worker.cancel() }
}
}
companion object {
const val DEFAULT_ENDPOINT = "https://valhalla1.openstreetmap.de/route"
private val rateGate = Mutex()
private var lastRequestMs = 0L
fun validatePoint(point: GeoPoint) {
require(point.latitude.isFinite() && point.latitude in -90.0..90.0 && point.longitude.isFinite() && point.longitude in -180.0..180.0) { "Coordenadas fuera de rango" }
}
fun validateEndpoint(value: String) {
val uri = URI(value.trim())
require(uri.scheme == "https" && !uri.host.isNullOrBlank() && uri.userInfo == null && uri.fragment == null) { "Endpoint HTTPS inválido" }
}
}
}