diff --git a/README.md b/README.md index 78979af..129b11c 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ NavFrame is an experimental Android navigation app that renders its own 480×240 The owner has confirmed static and synthetic NavFrame frames on a Xiaomi 11 Lite 5G NE running Android 14 and a 2026 Yamaha MT-07, and the bundled Asturias map working offline on the phone. On 2026-10-12, the owner reported that the latest version displayed the map on the TFT for about 20 minutes, then showed `Mapa no disponible` in La Corredoria (Oviedo) for the rest of the trip while the phone map continued working. An offline map was installed. The exact installed build, diagnostic code and background state were not recorded; the cause is under investigation. This establishes a successful map display followed by a persistent failure, not sustained TFT reliability. -The current checkout is version 0.13.1. The 0.13 series adds voice/routing language selection for Spanish, English, German, French, and Italian, plus a system-language option; unsupported system locales resolve to English. Speech still depends on the Android TextToSpeech engine and its installed voice data. The app includes offline map and place data for Asturias, plus installable regional packages. Worldwide regions can be discovered and built on demand through the [regional package workflow](docs/GLOBAL_OFFLINE.md); this is not complete worldwide coverage. Installed packages currently provide map and local place/camera data. Offline route calculation, global camera completeness, and complete worldwide font coverage are not provided. +The current checkout is version 0.13.4. The 0.13 series adds voice/routing language selection for Spanish, English, German, French, and Italian, plus a system-language option; unsupported system locales resolve to English. Speech still depends on the Android TextToSpeech engine and its installed voice data. The app includes offline map and place data for Asturias, plus installable regional packages. Worldwide regions can be discovered and built on demand through the [regional package workflow](docs/GLOBAL_OFFLINE.md); this is not complete worldwide coverage. Installed packages currently provide map and local place/camera data. Offline route calculation, global camera completeness, and complete worldwide font coverage are not provided. Route calculation and address search use configurable online services. Spoken output uses the selected language when Android provides voice data; voice availability and offline behavior depend on the device's TextToSpeech engine. Physical validation of route guidance, voice playback, camera alerts, sustained TFT map rendering, and a 30-minute screen-off session remains pending unless a newer test report says otherwise. @@ -39,6 +39,10 @@ Version 0.13.2 automatically saves the latest 100 TFT map failures and recoverie GitHub Actions uploads a debug APK artifact for pushes to `development`. Pushes to `main` publish a signed production APK release after build, tests, lint and signature checks pass. Production signing requires the repository secrets described in [Android builds and releases](docs/ANDROID_RELEASES.md). Pull requests run checks without publishing releases. +## Imported routes + +Choose **☰ → Cargar ruta GPX** to load a standard GPX route or track and start following it once precise GPS is available. Imported traces retain their geometry without online recalculation or invented turn announcements. See [GPX import](docs/IMPORTED_ROUTES.md). + ## Documentation - [Documentation index](docs/README.md) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 7700bbc..3860d60 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -5,8 +5,8 @@ val hasReleaseSigning = releaseSigning.values.all { it.isNotBlank() } if (releaseSigning.values.any { it.isNotBlank() } && !hasReleaseSigning) { throw GradleException("Incomplete release signing configuration. Required variables: ${releaseSigningNames.joinToString()}") } -val navframeVersionCode = providers.gradleProperty("navframeVersionCode").orElse("18").get().toInt() -require(navframeVersionCode in 1..2_100_000_000) { "Android versionCode must be between 1 and 2100000000" } +val navframeVersionCode = providers.gradleProperty("navframeVersionCode").orNull?.toInt() +require(navframeVersionCode == null || navframeVersionCode in 1..2_100_000_000) { "Android versionCode must be between 1 and 2100000000" } android { namespace = "dev.navframe.app" compileSdk = 36 @@ -15,8 +15,8 @@ android { applicationId = "dev.navframe.app" minSdk = 26 targetSdk = 35 - versionName = "0.13.3" - versionCode = navframeVersionCode + versionName = "0.13.4" + versionCode = 20 } if (hasReleaseSigning) { signingConfigs.create("production") { @@ -30,6 +30,7 @@ android { testOptions { unitTests.isIncludeAndroidResources = true } compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 } } +navframeVersionCode?.let { android.defaultConfig.versionCode = it } gradle.taskGraph.whenReady { if (!hasReleaseSigning && allTasks.any { it.path in setOf(":app:assembleRelease", ":app:bundleRelease", ":app:packageRelease") }) { throw GradleException("Production builds require release signing. Configure ${releaseSigningNames.joinToString()}.") diff --git a/app/src/main/java/dev/navframe/app/MainActivity.kt b/app/src/main/java/dev/navframe/app/MainActivity.kt index 24cde0b..b9b6d49 100644 --- a/app/src/main/java/dev/navframe/app/MainActivity.kt +++ b/app/src/main/java/dev/navframe/app/MainActivity.kt @@ -22,6 +22,8 @@ open class MainActivity : Activity() { private var observers: Job? = null private var searchJob: Job? = null private var positionWait: Job? = null + private var importJob: Job? = null + private var pendingImportUri: Uri? = null private var searchGeneration = 0L private var updatingDestination = false private val placeRepository by lazy { OfflinePlaceRepository(applicationContext) } @@ -69,7 +71,7 @@ open class MainActivity : Activity() { 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 enum class Action { POSITION, CALCULATE, ROUTE, PREVIEW, CONNECT, CHANGE_CONNECT, IMPORT_ROUTE } private var pendingAction: Action? = null private val permissionsPreferences by lazy { getSharedPreferences("permissions", MODE_PRIVATE) } private val connection = object : ServiceConnection { @@ -78,6 +80,7 @@ open class MainActivity : Activity() { observeService() refreshPermissions() tryAutoConnect() + pendingImportUri?.let { pendingImportUri = null; importRoute(it) } } override fun onServiceDisconnected(name: ComponentName?) { service = null; connectionInfo.text = "● Yamaha · conectar" } } @@ -102,7 +105,7 @@ open class MainActivity : Activity() { 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))) + toolbar.addView(button("☰") { AlertDialog.Builder(this).setTitle("NavFrame").setItems(arrayOf("Ajustes", "Mapas offline", "Lugares cercanos", "Cargar ruta GPX", "Información y licencias")) { _, item -> when(item) { 0 -> showSettings(); 1 -> showOfflineMaps(); 2 -> showPlaces(); 3 -> chooseRouteFile(); 4 -> 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 { @@ -136,7 +139,7 @@ open class MainActivity : Activity() { 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 + cancelSearch(); importJob?.cancel(); 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()) @@ -210,7 +213,7 @@ open class MainActivity : Activity() { 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" + else -> state.nextManeuver?.instruction ?: if (state.route == null) "GPS listo · elige un destino" else if (state.route?.imported == true) "Sigue el trazado GPX · sin giros anunciados" 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) } ?: "" @@ -223,7 +226,7 @@ open class MainActivity : Activity() { } 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 needsLocation = action == Action.IMPORT_ROUTE || action == Action.POSITION || (action == Action.CALCULATE && origin.selectedItemPosition == 0) || (action == Action.ROUTE && service?.routeUsesGps() == true) val required = mutableListOf() 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 @@ -232,7 +235,7 @@ open class MainActivity : Activity() { 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 ((action == Action.CONNECT || action == Action.CHANGE_CONNECT || ((action == Action.ROUTE || action == Action.IMPORT_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 @@ -246,7 +249,7 @@ open class MainActivity : Activity() { 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 needsFine = action == Action.IMPORT_ROUTE || 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." } @@ -275,6 +278,7 @@ open class MainActivity : Activity() { Action.CONNECT -> if (!connectRemembered(false)) chooseMotorcycle() Action.CHANGE_CONNECT -> chooseMotorcycle() Action.CALCULATE -> calculateRoute() + Action.IMPORT_ROUTE -> startImportedRoute() Action.ROUTE, Action.PREVIEW -> { if (action == Action.ROUTE && service?.hasPreparedRoute() != true) return if (action == Action.ROUTE) startRequested = true @@ -328,8 +332,81 @@ open class MainActivity : Activity() { } 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 chooseRouteFile() { + importJob?.cancel(); positionWait?.cancel() + try { + startActivityForResult(Intent(Intent.ACTION_OPEN_DOCUMENT).apply { + addCategory(Intent.CATEGORY_OPENABLE) + // GPX providers use several MIME types, including application/octet-stream. + type = "*/*" + }, 76) + } catch (_: ActivityNotFoundException) { hint.text = "No hay selector de archivos disponible" } + } + private fun importRoute(uri: Uri) { + importJob?.cancel() + positionWait?.cancel() + hint.text = "Leyendo ruta GPX…" + importJob = scope.launch { + try { + val imported = withContext(Dispatchers.IO) { + contentResolver.openInputStream(uri)?.use(GpxRouteImporter::parse) + ?: throw java.io.IOException("No se puede abrir el archivo") + } + ensureActive() + val current = service ?: run { hint.text = "Servicio no disponible · vuelve a cargar el GPX"; return@launch } + cancelSearch(); routeDialog?.dismiss() + current.prepareImportedRoute(imported) + destination = null; destinationName = "" + hint.text = "Ruta GPX cargada" + showImportedRouteSheet(imported.name) + withPermissions(Action.IMPORT_ROUTE) + } catch (cancelled: CancellationException) { throw cancelled } + catch (error: Exception) { + // Parser messages contain no coordinates, file paths or document contents. + hint.text = if (error is IllegalArgumentException) error.message ?: "GPX no válido" else "No se pudo leer el GPX · revisa el archivo y su acceso" + } + } + } + private fun showImportedRouteSheet(name: String?) { + routeDialog?.dismiss() + (routeInfo.parent as? android.view.ViewGroup)?.removeView(routeInfo) + val box = column().apply { setPadding(dp(20), dp(16), dp(20), dp(16)) } + box.addView(label(name ?: "Ruta GPX", 20f)) + box.addView(routeInfo) + routeLoading = ProgressBar(this).apply { visibility = View.GONE } + box.addView(routeLoading) + retryRouteButton = null + startButton = button("Iniciar navegación") { withPermissions(Action.IMPORT_ROUTE) } + box.addView(startButton) + val dialog = AlertDialog.Builder(this).setView(box).setNegativeButton("Cerrar", null).create() + dialog.setOnDismissListener { positionWait?.cancel(); startRequested = false } + routeDialog = dialog + dialog.show() + } + private fun startImportedRoute() { + val current = service ?: return + if (!current.preparedRouteIsImported()) { hint.text = "Vuelve a cargar la ruta GPX"; return } + positionWait?.cancel() + if (current.hasGuidanceGpsFix()) { perform(Action.ROUTE); return } + current.setPhoneVisible(true) + hint.text = "Esperando GPS preciso para iniciar el GPX…" + routeLoading?.visibility = View.VISIBLE + startButton?.isEnabled = false + positionWait = scope.launch { + try { + withTimeout(60_000) { + // Map readiness stays true while accuracy improves from 100 m to 25 m. + while (!current.hasGuidanceGpsFix()) delay(200) + } + ensureActive() + if (current.preparedRouteIsImported()) perform(Action.ROUTE) + } catch (_: TimeoutCancellationException) { hint.text = "Sin GPS preciso · activa ubicación y pulsa Iniciar navegación de nuevo" } + finally { routeLoading?.visibility = View.GONE; startButton?.isEnabled = current.hasPreparedRoute() } + } + } private fun cancelSearch() { searchGeneration++; searchJob?.cancel(); searchJob = null } private fun searchDestination() { + positionWait?.cancel() 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 @@ -395,7 +472,7 @@ open class MainActivity : Activity() { } 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() + cancelSearch(); importJob?.cancel(); positionWait?.cancel() updatingDestination = true try { searchQuery.setText(name.take(200)) } finally { updatingDestination = false } startRequested = false @@ -784,8 +861,12 @@ open class MainActivity : Activity() { } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) - if (requestCode !in listOf(73, 74) || resultCode != RESULT_OK) return + if (requestCode !in listOf(73, 74, 76) || resultCode != RESULT_OK) return val uri = data?.data ?: return + if (requestCode == 76) { + if (service == null) pendingImportUri = uri else importRoute(uri) + return + } showOfflineMaps() if (requestCode == 74) { if (offlineTask?.isActive == true) { hint.text = "Ya hay una importación en curso"; return } diff --git a/app/src/main/java/dev/navframe/app/MapFrameComposer.kt b/app/src/main/java/dev/navframe/app/MapFrameComposer.kt index 20c8868..7e1ae5e 100644 --- a/app/src/main/java/dev/navframe/app/MapFrameComposer.kt +++ b/app/src/main/java/dev/navframe/app/MapFrameComposer.kt @@ -61,6 +61,7 @@ class MapFrameComposer { if (warning != null) { text(fitted(warning, 16f, 460f), 10f, 39f, 16f, if (state.navigationStatus == NavigationStatus.ARRIVED) accent else Color.YELLOW) } else { + val imported = state.route?.imported == true val maneuver = state.nextManeuver val direction = maneuverDirection(maneuver?.type).name canvas.save() @@ -75,16 +76,16 @@ class MapFrameComposer { else if (direction.contains("UTURN") || direction.contains("U_TURN")) { canvas.drawArc(-12f, -14f, 12f, 11f, 180f, 180f, false, paint) canvas.drawLine(-12f, -2f, -12f, 15f, paint); canvas.drawLine(12f, -2f, 12f, 15f, paint) - } else canvas.drawPath(icon, paint) + } else if (!imported) canvas.drawPath(icon, paint) canvas.restore() paint.strokeCap = Paint.Cap.BUTT - text(fitted(maneuver?.instruction ?: "Continúa por la ruta", 15f, 392f), 48f, 30f, 15f) + text(fitted(maneuver?.instruction ?: if (imported) "Sigue el trazado GPX" else "Continúa por la ruta", 15f, 392f), 48f, 30f, 15f) val next = state.distanceToNextManeuverMeters?.let { if (it >= 1000) "%.1f km".format(java.util.Locale.ROOT, it / 1000.0) else "$it m" } ?: "-- m" - text(next, 48f, 49f, 19f, accent) + text(if (imported) "Sin indicaciones de giro" else next, 48f, 49f, if (imported) 12f else 19f, accent) } } else if (preview) { val route = requireNotNull(state.route) - val summary = "PREVIA · %.1f km · %d min".format(java.util.Locale.ROOT, route.distanceMeters / 1000.0, (route.durationSeconds + 59) / 60) + val summary = if (route.imported) "GPX · %.1f km · seguir trazado".format(java.util.Locale.ROOT, route.distanceMeters / 1000.0) else "PREVIA · %.1f km · %d min".format(java.util.Locale.ROOT, route.distanceMeters / 1000.0, (route.durationSeconds + 59) / 60) text(fitted(summary, 13f, 460f), 8f, 31f, 13f) } diff --git a/app/src/main/java/dev/navframe/app/TftService.kt b/app/src/main/java/dev/navframe/app/TftService.kt index 339611e..168fac5 100644 --- a/app/src/main/java/dev/navframe/app/TftService.kt +++ b/app/src/main/java/dev/navframe/app/TftService.kt @@ -52,7 +52,7 @@ class TftService : Service() { private var latestNavigationState = NavigationState() set(value) { field = value; mutableNavigationState.value = value - if (shownRoute?.demo == false && !routePreview) voice?.update(value) + if (shownRoute?.demo == false && !routePreview && value.route?.imported != true) voice?.update(value) else voice?.reset() } private var voice: NavigationVoiceController? = null @@ -576,6 +576,17 @@ class TftService : Service() { if (generation == preparedGeneration && routePreview) publishFrame(frame) } } + /** Import never contacts a routing server or replaces active guidance before Start. */ + fun prepareImportedRoute(imported: ImportedRoute) { + require(imported.route.imported && imported.route.maneuvers.isEmpty()) + RouteGuidanceTracker(imported.route) // Validate before invalidating an existing plan. + invalidateRoutePlan() + routePlan = RoutePlan(imported.route, imported.route.geometry.first(), false) + preparedDestinationDirty = false + mutableRouteInfo.value = "GPX · %.1f km · %d puntos\nSigue el trazado: sin instrucciones de giro, ETA ni recálculo automático. Revisa el recorrido antes de iniciar.".format(java.util.Locale.ROOT, imported.route.distanceMeters / 1000.0, imported.route.geometry.size) + if (!hasActiveGuidance()) showPreparedPreview() + } + fun preparedRouteIsImported() = hasPreparedRoute() && routePlan?.route?.imported == true fun hasPreparedRoute() = !preparedDestinationDirty && routePlan != null fun routeUsesGps() = !preparedDestinationDirty && routePlan?.demo == false fun startRoute(preview: Boolean = false) { @@ -596,6 +607,10 @@ class TftService : Service() { rerouteFailures = 0 reroutePaused = false if (plan.demo) startDemo(true, preserveRoute = true) else startGps(true, preserveRoute = true) + if (plan.route.imported) { + mutableRouteInfo.value = "GPX iniciado · GPS real · %.1f km\nSigue el trazado · sin giros anunciados, ETA ni recálculo automático.".format(java.util.Locale.ROOT, plan.route.distanceMeters / 1000.0) + return + } 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() { @@ -634,6 +649,10 @@ class TftService : Service() { fun requestReroute(manual: Boolean = true) { val plan = shownRoute ?: return + if (plan.route.imported) { + if (manual) mutableRouteInfo.value = "Ruta GPX · vuelve al trazado; no se modifica ni recalcula la ruta importada." + return + } if (plan.demo || routePreview || rerouteJob?.isActive == true) return val now = SystemClock.elapsedRealtime() val fix = lastGpsFix @@ -704,7 +723,7 @@ class TftService : Service() { fun isGpsSessionActive(): Boolean = gpsRequested fun hasFreshGpsFix(): Boolean = usableGpsFix(AndroidLocationProvider.MAP_ACCURACY_METERS) fun usesCompassHeading(): Boolean = (locationProvider ?: visibleGpsProvider)?.headingFromCompass == true - private fun hasGuidanceGpsFix(): Boolean = usableGpsFix(AndroidLocationProvider.GUIDANCE_ACCURACY_METERS) + fun hasGuidanceGpsFix(): Boolean = usableGpsFix(AndroidLocationProvider.GUIDANCE_ACCURACY_METERS) private fun usableGpsFix(maxAccuracy: Float): Boolean = lastGpsFix?.let { it.accuracyMeters.isFinite() && it.accuracyMeters in 0f..maxAccuracy && SystemClock.elapsedRealtime() - lastGpsElapsed in 0..15_000 && (locationProvider?.providerEnabled?.value == true || (phoneVisible && visibleGpsProvider?.providerEnabled?.value == true)) } == true private fun stopVisibleGps() { visibleGpsJob?.cancel(); visibleGpsJob = null diff --git a/app/src/test/java/dev/navframe/app/ImportedRouteTest.kt b/app/src/test/java/dev/navframe/app/ImportedRouteTest.kt new file mode 100644 index 0000000..037f9f3 --- /dev/null +++ b/app/src/test/java/dev/navframe/app/ImportedRouteTest.kt @@ -0,0 +1,200 @@ +package dev.navframe.app + +import android.Manifest +import android.app.Activity +import android.content.Intent +import android.location.Location +import android.location.LocationManager +import android.os.Bundle +import android.os.Looper +import android.os.SystemClock +import dev.navframe.core.* +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.annotation.LooperMode +import java.time.Duration + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +@LooperMode(LooperMode.Mode.PAUSED) +class ImportedRouteTest { + class PhoneWithoutGpu : MainActivity() { override fun createPhoneMap(savedState: Bundle?): PhoneMapView? = null } + private fun imported() = GpxRouteImporter.parse("""Weekend""".byteInputStream()) + private fun tick() = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(100)) + private fun field(name: String) = MainActivity::class.java.getDeclaredField(name).apply { isAccessible = true } + + @Test fun importedPreviewRequiresGpsAndStartsWithoutRoutingOrRerouting() { + val controller = Robolectric.buildService(TftService::class.java).create() + val service = controller.get() + service.mapRenderOverride = { _, _ -> TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) } + service.routingEngineFactory = { error("Imported routes must not use a server") } + try { + val route = imported() + service.prepareImportedRoute(route); tick() + assertTrue(service.preparedRouteIsImported()) + assertTrue(service.routeUsesGps()) + assertEquals(NavigationStatus.ROUTE_PREVIEW, service.navigationState.value.navigationStatus) + assertSame(route.route, service.navigationState.value.route) + service.startRoute(); tick() + assertFalse(service.hasActiveGuidance()) + assertTrue(service.routeInfo.value.contains("GPS reciente")) + + val application = RuntimeEnvironment.getApplication() + shadowOf(application).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION) + val manager = application.getSystemService(LocationManager::class.java) + shadowOf(manager).setProviderEnabled(LocationManager.GPS_PROVIDER, true) + service.setPhoneVisible(true); tick() + shadowOf(manager).simulateLocation(Location(LocationManager.GPS_PROVIDER).apply { + latitude = 43.36; longitude = -5.85; accuracy = 3f + time = System.currentTimeMillis(); elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos() + }); tick() + assertTrue(service.hasFreshGpsFix()) + service.startRoute(); tick() + assertTrue(service.hasActiveGuidance()) + assertSame(route.route, service.navigationState.value.route) + service.requestReroute(); tick() + assertTrue(service.routeInfo.value.contains("no se modifica")) + assertSame(route.route, service.navigationState.value.route) + assertNull(service.navigationState.value.nextManeuver) + assertNull(service.navigationState.value.etaEpochMillis) + service.stopRoute(); tick() + assertFalse(service.hasActiveGuidance()) + assertFalse(service.hasPreparedRoute()) + assertNull(service.navigationState.value.route) + } finally { controller.destroy() } + } + @Test fun filePickerUsesSafAndCancelKeepsThePreparedRoute() { + val activityController = Robolectric.buildActivity(PhoneWithoutGpu::class.java).create() + val serviceController = Robolectric.buildService(TftService::class.java).create() + val activity = activityController.get() + val service = serviceController.get() + service.mapRenderOverride = { _, _ -> TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) } + try { + field("service").set(activity, service) + service.prepareImportedRoute(imported()); tick() + MainActivity::class.java.getDeclaredMethod("chooseRouteFile").apply { isAccessible = true }.invoke(activity) + val request = shadowOf(activity).nextStartedActivityForResult + assertEquals(Intent.ACTION_OPEN_DOCUMENT, request.intent.action) + assertTrue(request.intent.hasCategory(Intent.CATEGORY_OPENABLE)) + MainActivity::class.java.getDeclaredMethod("onActivityResult", Int::class.javaPrimitiveType, Int::class.javaPrimitiveType, Intent::class.java) + .apply { isAccessible = true }.invoke(activity, 76, Activity.RESULT_CANCELED, null) + assertTrue(service.preparedRouteIsImported()) + assertFalse(service.hasActiveGuidance()) + } finally { activityController.destroy(); serviceController.destroy() } + } + @Test fun importedStartRequestsFineLocationAndDenialNeverStartsNavigation() { + val activityController = Robolectric.buildActivity(PhoneWithoutGpu::class.java).create() + val serviceController = Robolectric.buildService(TftService::class.java).create() + val activity = activityController.get() + val service = serviceController.get() + service.mapRenderOverride = { _, _ -> TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) } + try { + shadowOf(RuntimeEnvironment.getApplication()).denyPermissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION) + field("service").set(activity, service) + service.prepareImportedRoute(imported()); tick() + val actionClass = Class.forName("dev.navframe.app.MainActivity\$Action") + val action = actionClass.enumConstants.first { (it as Enum<*>).name == "IMPORT_ROUTE" } + MainActivity::class.java.getDeclaredMethod("withPermissions", actionClass).apply { isAccessible = true }.invoke(activity, action) + assertNotNull(field("pendingAction").get(activity)) + activity.onRequestPermissionsResult(42, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), intArrayOf(android.content.pm.PackageManager.PERMISSION_DENIED)) + tick() + assertFalse(service.hasActiveGuidance()) + assertTrue(service.preparedRouteIsImported()) + assertTrue((field("hint").get(activity) as android.widget.TextView).text.contains("Permiso denegado")) + } finally { activityController.destroy(); serviceController.destroy() } + } + @Test fun validDocumentAutomaticallyRequestsNavigationPermissionAndInvalidDocumentPreservesTrace() { + val activityController = Robolectric.buildActivity(PhoneWithoutGpu::class.java).create() + val serviceController = Robolectric.buildService(TftService::class.java).create() + val activity = activityController.get() + val service = serviceController.get() + service.mapRenderOverride = { _, _ -> TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) } + fun importDocument(xml: String) { + val uri = android.net.Uri.parse("content://test/route.gpx") + shadowOf(activity.contentResolver).registerInputStream(uri, xml.byteInputStream()) + MainActivity::class.java.getDeclaredMethod("onActivityResult", Int::class.javaPrimitiveType, Int::class.javaPrimitiveType, Intent::class.java) + .apply { isAccessible = true }.invoke(activity, 76, Activity.RESULT_OK, Intent().setData(uri)) + val job = field("importJob").get(activity) as kotlinx.coroutines.Job + for (attempt in 0..200) { if (job.isCompleted) break; Thread.sleep(5); tick() } + assertTrue("Document import should finish", job.isCompleted) + } + try { + shadowOf(RuntimeEnvironment.getApplication()).denyPermissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION) + field("service").set(activity, service) + importDocument("""""") + assertTrue(service.preparedRouteIsImported()) + assertEquals("IMPORT_ROUTE", (field("pendingAction").get(activity) as Enum<*>).name) + assertFalse(service.hasActiveGuidance()) + val oldRoute = service.navigationState.value.route + importDocument("") + assertSame(oldRoute, service.navigationState.value.route) + assertTrue((field("hint").get(activity) as android.widget.TextView).text.contains("coordenadas inválidas")) + } finally { activityController.destroy(); serviceController.destroy() } + } + @Test fun closingImportedPanelCancelsThePendingGpsStart() { + val activityController = Robolectric.buildActivity(PhoneWithoutGpu::class.java).create() + val serviceController = Robolectric.buildService(TftService::class.java).create() + val activity = activityController.get() + val service = serviceController.get() + service.mapRenderOverride = { _, _ -> TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) } + try { + shadowOf(RuntimeEnvironment.getApplication()).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION) + field("service").set(activity, service) + service.prepareImportedRoute(imported()); tick() + MainActivity::class.java.getDeclaredMethod("showImportedRouteSheet", String::class.java).apply { isAccessible = true }.invoke(activity, "Test") + MainActivity::class.java.getDeclaredMethod("startImportedRoute").apply { isAccessible = true }.invoke(activity) + val pending = field("positionWait").get(activity) as kotlinx.coroutines.Job + assertTrue(pending.isActive) + org.robolectric.shadows.ShadowAlertDialog.getLatestAlertDialog().dismiss(); tick() + assertTrue(pending.isCancelled) + assertFalse(service.hasActiveGuidance()) + } finally { activityController.destroy(); serviceController.destroy() } + } + + @Test fun importedStartWaitsForGuidanceAccuracyEvenWhenMapReadinessStaysTrue() { + val activityController = Robolectric.buildActivity(PhoneWithoutGpu::class.java).create() + val serviceController = Robolectric.buildService(TftService::class.java).create() + val activity = activityController.get() + val service = serviceController.get() + service.mapRenderOverride = { _, _ -> TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) } + try { + val application = RuntimeEnvironment.getApplication() + shadowOf(application).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION) + field("service").set(activity, service) + val manager = application.getSystemService(LocationManager::class.java) + shadowOf(manager).setProviderEnabled(LocationManager.GPS_PROVIDER, true) + service.prepareImportedRoute(imported()); tick() + service.setPhoneVisible(true); tick() + fun fix(accuracy: Float) { + shadowOf(manager).simulateLocation(Location(LocationManager.GPS_PROVIDER).apply { + latitude = 43.36; longitude = -5.85; this.accuracy = accuracy + time = System.currentTimeMillis(); elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos() + }) + tick() + } + fix(80f) + assertTrue(service.gpsReady.value) + assertTrue(service.hasFreshGpsFix()) + assertFalse(service.hasGuidanceGpsFix()) + MainActivity::class.java.getDeclaredMethod("startImportedRoute").apply { isAccessible = true }.invoke(activity) + val pending = field("positionWait").get(activity) as kotlinx.coroutines.Job + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(600)) + assertTrue(pending.isActive) + assertNull(shadowOf(activity).nextStartedService) + assertFalse(service.hasActiveGuidance()) + fix(20f) + assertTrue(service.gpsReady.value) + assertTrue(service.hasGuidanceGpsFix()) + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(400)) + assertTrue(pending.isCompleted) + assertEquals(TftService.ACTION_ROUTE_GPS, shadowOf(activity).nextStartedService.action) + } finally { activityController.destroy(); serviceController.destroy() } + } + +} diff --git a/core/src/main/kotlin/dev/navframe/core/Contracts.kt b/core/src/main/kotlin/dev/navframe/core/Contracts.kt index 824b253..759f0df 100644 --- a/core/src/main/kotlin/dev/navframe/core/Contracts.kt +++ b/core/src/main/kotlin/dev/navframe/core/Contracts.kt @@ -44,6 +44,8 @@ data class RouteResult( val hasUnpaved: Boolean? = null, /** Locale of the server-provided maneuver text; retained until this route is replaced. */ val guidanceLanguage: String = "es-ES", + /** Imported geometry has no verified road maneuvers or travel-time estimate. */ + val imported: Boolean = false, ) enum class RouteProfile { FASTEST, AVOID_MOTORWAYS, TOURING, AVOID_UNPAVED } /** Preferences, not guarantees or legal/surface certification. Presets combine with explicit flags. */ diff --git a/core/src/main/kotlin/dev/navframe/core/GpxRouteImporter.kt b/core/src/main/kotlin/dev/navframe/core/GpxRouteImporter.kt new file mode 100644 index 0000000..0733f1e --- /dev/null +++ b/core/src/main/kotlin/dev/navframe/core/GpxRouteImporter.kt @@ -0,0 +1,115 @@ +package dev.navframe.core + +import java.io.ByteArrayInputStream +import java.io.InputStream +import javax.xml.parsers.SAXParserFactory +import org.xml.sax.Attributes +import org.xml.sax.InputSource +import org.xml.sax.SAXException +import org.xml.sax.ext.DefaultHandler2 +import kotlin.math.* + +data class ImportedRoute(val name: String?, val route: RouteResult) + +/** Imports geometry only: GPX points do not establish road turns, speeds or travel time. */ +object GpxRouteImporter { + const val MAX_BYTES = 5 * 1024 * 1024 + const val MAX_POINTS = 10_000 + const val MAX_DEPTH = 64 + private val namespaces = setOf("", "http://www.topografix.com/GPX/1/0", "http://www.topografix.com/GPX/1/1") + + fun parse(input: InputStream): ImportedRoute { + val bytes = java.io.ByteArrayOutputStream() + val buffer = ByteArray(8192) + while (true) { + val read = input.read(buffer) + if (read < 0) break + if (bytes.size() + read > MAX_BYTES) fail("El archivo GPX supera los 5 MiB. Exporta una ruta más pequeña.") + bytes.write(buffer, 0, read) + } + val handler = Handler() + try { + val factory = SAXParserFactory.newInstance().apply { isNamespaceAware = true } + val reader = factory.newSAXParser().xmlReader + // Lexical handling is mandatory: reject DTD before any entity can be expanded. + reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler) + for (feature in listOf("http://xml.org/sax/features/external-general-entities", "http://xml.org/sax/features/external-parameter-entities", "http://apache.org/xml/features/nonvalidating/load-external-dtd")) { + try { reader.setFeature(feature, false) } catch (_: SAXException) { /* The rejecting resolver remains active. */ } + } + reader.contentHandler = handler + reader.entityResolver = handler + reader.errorHandler = handler + reader.parse(InputSource(ByteArrayInputStream(bytes.toByteArray()))) + } catch (error: IllegalArgumentException) { + throw error + } catch (_: Exception) { + fail("No se pudo leer el GPX. Comprueba que sea un archivo GPX válido sin DTD ni entidades externas.") + } + val points = handler.points + if (points.size < 2) fail("El GPX necesita al menos dos puntos de ruta o track.") + val distance = points.zipWithNext().sumOf { (a, b) -> distance(a, b) } + if (!distance.isFinite() || distance <= 0.0) fail("El GPX necesita al menos dos puntos distintos.") + return ImportedRoute(handler.name?.trim()?.takeIf { it.isNotEmpty() }, RouteResult( + geometry = points.toList(), maneuvers = emptyList(), distanceMeters = distance.roundToInt().coerceAtLeast(1), + durationSeconds = 0, destination = points.last(), imported = true, + )) + } + + private class Handler : DefaultHandler2() { + val points = mutableListOf() + var name: String? = null + private val path = mutableListOf() + private var rootNamespace = "" + private var candidates = 0 + private var nonemptySegments = 0 + private var segmentPoints = 0 + private var nameText: StringBuilder? = null + + override fun startDTD(name: String?, publicId: String?, systemId: String?) = fail("El GPX contiene un DTD no permitido.") + override fun resolveEntity(publicId: String?, systemId: String?): InputSource = fail("El GPX contiene entidades externas no permitidas.") + override fun startElement(uri: String, localName: String, qName: String, attributes: Attributes) { + if (path.size >= MAX_DEPTH) fail("El GPX tiene demasiados niveles XML.") + if (path.isEmpty()) { + if (localName != "gpx" || uri !in namespaces) fail("Selecciona un archivo GPX 1.0 o 1.1 válido.") + rootNamespace = uri + } + path.add(if (uri == rootNamespace) localName else "#extension") + val route = path == listOf("gpx", "rte") + val track = path == listOf("gpx", "trk") + if (route || track) { + candidates++ + if (candidates > 1) fail("El GPX contiene varias rutas o tracks. Exporta solo la ruta que quieras seguir.") + } + if (path == listOf("gpx", "trk", "trkseg")) segmentPoints = 0 + if (path == listOf("gpx", "rte", "name") || path == listOf("gpx", "trk", "name")) nameText = StringBuilder() + if (path == listOf("gpx", "rte", "rtept") || path == listOf("gpx", "trk", "trkseg", "trkpt")) { + if (points.size >= MAX_POINTS) fail("El GPX supera los 10000 puntos. Simplifica la ruta antes de importarla.") + val lat = attributes.getValue("lat")?.toDoubleOrNull() + val lon = attributes.getValue("lon")?.toDoubleOrNull() + if (lat == null || lon == null || !lat.isFinite() || !lon.isFinite() || lat !in -90.0..90.0 || lon !in -180.0..180.0) fail("El GPX contiene coordenadas inválidas.") + points.add(GeoPoint(lat, lon)) + if (path[1] == "trk") segmentPoints++ + } + } + override fun characters(ch: CharArray, start: Int, length: Int) { + if (path == listOf("gpx", "rte", "name") || path == listOf("gpx", "trk", "name")) { + nameText?.let { if (it.length < 256) it.append(ch, start, minOf(length, 256 - it.length)) } + } + } + override fun endElement(uri: String, localName: String, qName: String) { + if (path == listOf("gpx", "rte", "name") || path == listOf("gpx", "trk", "name")) { name = nameText?.toString(); nameText = null } + if (path == listOf("gpx", "trk", "trkseg") && segmentPoints > 0) { + nonemptySegments++ + if (nonemptySegments > 1) fail("El GPX contiene varios segmentos separados. Exporta un solo segmento continuo.") + } + path.removeAt(path.lastIndex) + } + } + 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_000.0 * 2 * asin(sqrt(h.coerceIn(0.0, 1.0))) + } + private fun fail(message: String): Nothing = throw IllegalArgumentException(message) +} diff --git a/core/src/main/kotlin/dev/navframe/core/RouteGuidance.kt b/core/src/main/kotlin/dev/navframe/core/RouteGuidance.kt index 4c85b68..4f88552 100644 --- a/core/src/main/kotlin/dev/navframe/core/RouteGuidance.kt +++ b/core/src/main/kotlin/dev/navframe/core/RouteGuidance.kt @@ -52,7 +52,7 @@ class RouteGuidanceTracker(private val route: RouteResult, private val config: G val distinct = lastTimestamp != fix.timestampMs if (!distinct) return lastState ?: base.copy(navigationStatus = NavigationStatus.GPS_LOST) if (arrived) return remember(base.copy(speed = 0f, remainingDistanceMeters = 0, - etaEpochMillis = epochMs, navigationStatus = NavigationStatus.ARRIVED)) + etaEpochMillis = if (route.imported) null else epochMs, navigationStatus = NavigationStatus.ARRIVED)) if (needsRecovery || lastNow?.let { nowMs - it > config.maxFixAgeMs } == true) { outside.reset(); arrival.reset() needsRecovery = false @@ -96,7 +96,7 @@ class RouteGuidanceTracker(private val route: RouteResult, private val config: G earthDistance(fix.position, route.geometry.last()) <= config.arrivalRadiusMeters arrived = arrival.observe(close, distinct, nowMs, config.arrivalFixes, config.arrivalDurationMs) if (arrived) return remember(base.copy(speed = 0f, remainingDistanceMeters = 0, - etaEpochMillis = epochMs, navigationStatus = NavigationStatus.ARRIVED)) + etaEpochMillis = if (route.imported) null else epochMs, navigationStatus = NavigationStatus.ARRIVED)) return remember(line.guidedState(base, progress, epochMs)) } } @@ -131,9 +131,9 @@ class RouteDemo(private val route: RouteResult, private val speedMetersPerSecond val base = NavigationState(position = position, bearing = bearing, speed = speedMetersPerSecond, route = route, accuracyMeters = 3f) if (progress >= line.total) return base.copy(speed = 0f, remainingDistanceMeters = 0, - etaEpochMillis = epochMs, navigationStatus = NavigationStatus.ARRIVED) + etaEpochMillis = if (route.imported) null else epochMs, navigationStatus = NavigationStatus.ARRIVED) val state = line.guidedState(base, progress, epochMs) - return state.copy(etaEpochMillis = saturatedAdd(epochMs, ((line.total - progress) / speedMetersPerSecond * 1000).roundToLong())) + return state.copy(etaEpochMillis = if (route.imported) null else saturatedAdd(epochMs, ((line.total - progress) / speedMetersPerSecond * 1000).roundToLong())) } } @@ -226,7 +226,7 @@ private class RouteLine(private val route: RouteResult) { val etaMs = (route.durationSeconds * 1000.0 * remaining / total).roundToLong() return base.copy(nextManeuver = next?.first, distanceToNextManeuverMeters = next?.let { (it.second - progress).coerceAtLeast(0.0).roundToInt() }, - remainingDistanceMeters = remaining.roundToInt(), etaEpochMillis = saturatedAdd(epochMs, etaMs), + remainingDistanceMeters = remaining.roundToInt(), etaEpochMillis = if (route.imported) null else saturatedAdd(epochMs, etaMs), navigationStatus = NavigationStatus.NAVIGATING) } fun pointAt(progress: Double): Pair { diff --git a/core/src/test/kotlin/dev/navframe/core/GpxRouteImporterTest.kt b/core/src/test/kotlin/dev/navframe/core/GpxRouteImporterTest.kt new file mode 100644 index 0000000..d8f40e5 --- /dev/null +++ b/core/src/test/kotlin/dev/navframe/core/GpxRouteImporterTest.kt @@ -0,0 +1,91 @@ +package dev.navframe.core + +import org.junit.Assert.* +import org.junit.Test +import java.io.ByteArrayInputStream + +class GpxRouteImporterTest { + private val points = "" + private fun parse(xml: String) = GpxRouteImporter.parse(ByteArrayInputStream(xml.toByteArray())) + private fun rejected(xml: String, expected: String? = null) { + try { parse(xml); fail("Expected rejected GPX") } catch (error: IllegalArgumentException) { + expected?.let { assertTrue(error.message.orEmpty(), error.message.orEmpty().contains(it)) } + } + } + @Test fun `imports route geometry without invented guidance`() { + val result = parse(" Asturias & Costa $points") + assertEquals("Asturias & Costa", result.name) + assertEquals(2, result.route.geometry.size) + assertEquals(111, result.route.distanceMeters) + assertEquals(0, result.route.durationSeconds) + assertTrue(result.route.maneuvers.isEmpty()) + assertTrue(result.route.imported) + assertEquals(result.route.geometry.last(), result.route.destination) + } + @Test fun `supports standard namespaces and prefixed GPX`() { + for (version in listOf("1/0", "1/1")) { + assertEquals(2, parse("$points").route.geometry.size) + } + assertEquals(2, parse("").route.geometry.size) + } + @Test fun `imports track and ignores empty segments and waypoints`() { + val trackPoints = points.replace("rtept", "trkpt") + val result = parse("Track$trackPoints") + assertEquals("Track", result.name) + assertEquals(2, result.route.geometry.size) + } + @Test fun `rejects multiple candidates and disconnected segments`() { + rejected("$points$points", "varias") + rejected("$points", "varias") + val segment = "${points.replace("rtept", "trkpt")}" + rejected("$segment$segment", "segmentos") + } + @Test fun `rejects DTD internal and external entities`() { + rejected("]>&name;$points") + rejected("$points") + rejected("]>&x;$points") + } + @Test fun `rejects invalid empty and stationary geometry`() { + for (value in listOf("NaN", "Infinity", "91", "nope")) rejected("$points") + rejected("$points") + rejected("") + rejected("", "distintos") + rejected("$points") + rejected("$points") + rejected("$points") + } + @Test fun `does not import points from extensions`() { + rejected("$points") + rejected("") + } + @Test fun `bounds bytes points and nesting`() { + rejected(" ".repeat(GpxRouteImporter.MAX_BYTES + 1), "5 MiB") + rejected("" + "".repeat(GpxRouteImporter.MAX_POINTS + 1) + "", "10000") + rejected("" + "".repeat(GpxRouteImporter.MAX_DEPTH) + "".repeat(GpxRouteImporter.MAX_DEPTH) + "", "niveles") + } + @Test fun `bounded name and submeter route remain usable`() { + val result = parse("${"x".repeat(1000)}") + assertEquals(256, result.name!!.length) + assertEquals(1, result.route.distanceMeters) + } + @Test fun `imported route tracks progress without turns or ETA and confirms deviation`() { + val route = parse("").route + val tracker = RouteGuidanceTracker(route) + fun fix(lat: Double, time: Long) = LocationFix(GeoPoint(lat, 0.005), 90f, 5f, 5f, time) + val onLine = tracker.update(fix(0.0, 1), 0, 100_000) + assertEquals(NavigationStatus.NAVIGATING, onLine.navigationStatus) + assertEquals(556, onLine.remainingDistanceMeters!!) + assertNull(onLine.etaEpochMillis) + assertNull(onLine.nextManeuver) + assertNull(onLine.distanceToNextManeuverMeters) + // A 56m displacement is believable movement, but clearly outside the route corridor. + assertEquals(NavigationStatus.NAVIGATING, tracker.update(fix(0.0005, 2), 1_000, 101_000).navigationStatus) + assertEquals(NavigationStatus.NAVIGATING, tracker.update(fix(0.0005, 3), 4_000, 104_000).navigationStatus) + val outside = tracker.update(fix(0.0005, 4), 6_000, 106_000) + assertEquals(NavigationStatus.OFF_ROUTE, outside.navigationStatus) + assertNull(outside.nextManeuver) + assertNull(outside.distanceToNextManeuverMeters) + assertNull(outside.etaEpochMillis) + } + +} diff --git a/docs/IMPORTED_ROUTES.md b/docs/IMPORTED_ROUTES.md new file mode 100644 index 0000000..e5b5ff7 --- /dev/null +++ b/docs/IMPORTED_ROUTES.md @@ -0,0 +1,23 @@ +# Importing a GPX route + +Open **☰ → Cargar ruta GPX**, then choose a `.gpx` file using Android's document picker. The app displays the name, distance and point count and previews the trace when no other navigation session is active. After a valid file is selected, navigation starts automatically with real GPS as soon as location permission and a recent accurate fix are available. No destination search is needed. A pending import leaves existing navigation running until the new trace can start. The **Iniciar navegación** button retries after a timeout or permission denial. + +Precise location permission is required to start navigation. If a recent fix with accuracy of 25 metres or better is unavailable, the app waits up to 60 seconds. Close the import panel or stop the route to cancel that wait. When the wait expires, enable location and tap **Iniciar navegación** to retry. Denying permission leaves the trace available for review. + +## Supported files + +GPX 1.0 and 1.1 routes (`rte/rtept`) and tracks (`trk/trkseg/trkpt`) are supported, including GPX files without a namespace. Export exactly one route or one track containing a single nonempty continuous segment. Multiple routes, tracks or nonempty segments are rejected: the app must not create a fictitious connection between separate tracks. Waypoints alone do not define a route. + +Files are limited to 5 MiB, 10,000 trace points and 64 XML nesting levels. Coordinates must be finite and within latitude/longitude bounds, with at least two distinct points. DTD declarations and external entities are rejected. Route names are capped at 256 characters. An invalid or inaccessible file leaves any running navigation untouched. + +## Following a trace + +The original coordinates are retained locally in memory and drawn on the phone and TFT. GPX import does not send the file or its coordinates to a routing server. It works with the installed offline map; online background tiles still require a connection when no offline map is selected. Standard trace points do not establish legal roads, surface quality, reliable turns or travel time. + +The display says **Sigue el trazado GPX**. It shows progress, remaining distance, sustained deviations and arrival using the existing GPS guidance policy. It does not invent turn instructions, speak turn announcements, show an ETA, or automatically reroute away from the imported trace. On a deviation, return to the trace using the map and road signs. Manual recalculation also preserves the trace. + +The imported route is not persisted across process death or device reboot: reload the original document to resume. The document remains in its selected provider; the app does not request long-term file access or copy the GPX into its own storage. Map diagnostics do not include route coordinates, document paths or route names. + +## Validation + +Core tests exercise standard GPX routes/tracks, namespaces, malicious XML, resource limits and trace guidance without invented turns or ETA. Android unit tests exercise the document picker, cancellation, precise-location permission denial, preview/start/stop and prevention of online recalculation with the renderer replaced to avoid device-only JNI.