commit d863f2b940068e5af071f25b7014751d6ab6db92 Author: Dasemu Date: Wed Sep 30 17:34:58 2026 +0200 Initial public NavFrame release with global regional package pipeline diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml new file mode 100644 index 0000000..d6c2c84 --- /dev/null +++ b/.github/workflows/android.yml @@ -0,0 +1,36 @@ +name: Android build and checks +on: + push: + pull_request: +permissions: + contents: read +concurrency: + group: android-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true +jobs: + verify: + runs-on: ubuntu-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + - uses: android-actions/setup-android@v3 + - name: Install Android compile SDK + run: sdkmanager "platforms;android-36" "build-tools;35.0.0" + - uses: gradle/actions/setup-gradle@v4 + - name: Build, unit tests and lint + run: ./gradlew --no-daemon :app:assembleDebug :app:testDebugUnitTest :app:lintDebug :core:test :navilite:testDebugUnitTest + - name: Preserve check reports + if: always() + uses: actions/upload-artifact@v4 + with: + name: android-check-reports + path: | + app/build/reports/ + core/build/reports/ + navilite/build/reports/ + if-no-files-found: ignore + retention-days: 7 diff --git a/.github/workflows/offline-regions.yml b/.github/workflows/offline-regions.yml new file mode 100644 index 0000000..7d936cd --- /dev/null +++ b/.github/workflows/offline-regions.yml @@ -0,0 +1,92 @@ +name: Build worldwide offline regions +on: + push: + tags: ['offline-bootstrap-andorra'] + workflow_dispatch: + inputs: + regions: + description: 'Geofabrik IDs, comma separated (e.g. andorra,act,cantabria); max 32' + required: true + default: andorra + publish: + description: Publish immutable regional releases and update catalog + type: boolean + default: false +permissions: + contents: read +jobs: + plan: + runs-on: ubuntu-latest + outputs: + matrix: ${{ steps.matrix.outputs.value }} + steps: + - uses: actions/checkout@v4 + - id: matrix + env: + REGION_IDS: ${{ github.event_name == 'push' && 'andorra' || inputs.regions }} + run: | + value=$(python3 tools/offline/global-regions.py matrix "$REGION_IDS") + echo "value=$value" >> "$GITHUB_OUTPUT" + build: + needs: plan + runs-on: ubuntu-latest + timeout-minutes: 330 + permissions: + contents: write + strategy: + fail-fast: false + max-parallel: 2 + matrix: ${{ fromJSON(needs.plan.outputs.matrix) }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - name: Install pinned builders + run: | + pip install -r tools/offline/poi-requirements.txt + curl --fail --location --retry 3 --output planetiler.jar https://github.com/onthegomap/planetiler/releases/download/v0.10.2/planetiler.jar + - name: Build bounded regional package + env: + REGION_ID: ${{ matrix.region }} + PACK_VERSION: ${{ github.run_id }}.${{ github.run_attempt }} + run: | + python3 tools/offline/global-regions.py build --region "$REGION_ID" --version "$PACK_VERSION" --planetiler-jar planetiler.jar --output output + - uses: actions/upload-artifact@v4 + if: ${{ github.event_name != 'push' && !inputs.publish }} + with: + name: offline-${{ strategy.job-index }} + path: | + output/*.navframe + output/regional-catalog.json + retention-days: 7 + - name: Publish one immutable release per region + if: ${{ github.event_name == 'push' || inputs.publish }} + env: + GH_TOKEN: ${{ github.token }} + REGION_ID: ${{ matrix.region }} + PACK_VERSION: ${{ github.run_id }}.${{ github.run_attempt }} + run: | + region_slug="${REGION_ID//\//-}" + tag="offline-gf-$region_slug-$PACK_VERSION" + gh release create "$tag" output/*.navframe output/regional-catalog.json --draft --target "$GITHUB_SHA" --title "Offline $REGION_ID $PACK_VERSION" --notes "OpenStreetMap contributors / ODbL-1.0. Geofabrik extract; source timestamps and SHA-256 provenance included. Community camera data is incomplete." + gh release edit "$tag" --draft=false --latest=false + catalog: + needs: build + if: ${{ always() && (github.event_name == 'push' || inputs.publish) && !cancelled() }} + runs-on: ubuntu-latest + permissions: + contents: write + concurrency: + group: offline-catalog-publication + cancel-in-progress: false + steps: + - uses: actions/checkout@v4 + - name: Rebuild index from all published regional releases + env: + GH_TOKEN: ${{ github.token }} + run: python3 tools/offline/publish-catalog.py diff --git a/.github/workflows/offline-tests.yml b/.github/workflows/offline-tests.yml new file mode 100644 index 0000000..888ea3f --- /dev/null +++ b/.github/workflows/offline-tests.yml @@ -0,0 +1,18 @@ +name: Offline builder checks +on: + push: + paths: ['tools/offline/**', '.github/workflows/offline-*.yml'] + pull_request: + paths: ['tools/offline/**', '.github/workflows/offline-*.yml'] +permissions: + contents: read +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: pip install -r tools/offline/poi-requirements.txt + - run: python3 -m unittest discover -s tools/offline -p 'test_*.py' diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ca4091c --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +.gradle/ +.kotlin/ +**/build/ +local.properties +*.iml +.idea/ +__pycache__/ +*.py[cod] +.env +.env.* +*.jks +*.keystore +*.p12 +*.pfx +dist/.es-cantabria-build/ +planetiler.jar diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..6dd8be6 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,29 @@ +# Contributing + +Contributions are welcome. NavFrame is experimental software for motorcycle navigation displays, so clear boundaries between simulation, online services, offline data, and physical device results matter. + +## Before making a change + +- Open an issue or discussion for a substantial feature or protocol change. +- Keep user-visible claims aligned with verified app behavior. Label simulated route/location data as demo data. +- Do not add copied OsmAnd code, assets, or databases. Do not use public map, geocoder, or routing services for bulk harvesting or unapproved load tests. +- Preserve OSM attribution and source dates/hashes for derived data. Check third-party licenses before adding code, fonts, images, or data. +- Keep endpoints configurable where appropriate. Never commit API keys, signing keys, personal coordinates, Bluetooth identifiers, or local machine configuration. + +## Build and checks + +Use JDK 17 and an Android SDK with API 36. The Gradle wrapper pins the Gradle version. + +```sh +./gradlew :app:assembleDebug +./gradlew :app:testDebugUnitTest :app:lintDebug :navilite:testDebugUnitTest :core:test +python3 -m unittest discover -s tools/offline -p 'test_*.py' +``` + +Run checks relevant to the change and include the results in the pull request. Tests do not exercise Android MapLibre JNI/OpenGL, Bluetooth hardware, a Yamaha TFT, motorcycle route suitability, or audible TTS behavior. Describe those as unverified unless tested on physical hardware, with model and software versions and without sharing precise location or device identifiers. + +## Pull requests + +Explain the user-visible behavior and the problem it addresses. Include relevant tests and any validation limits. For data or package changes, include the source URL, source timestamp, checksums, license/attribution, and reproducible build inputs. Do not put generated regional datasets or APKs in Git history; use the documented release workflow. + +The worldwide package workflow is documented in [GLOBAL_OFFLINE.md](docs/GLOBAL_OFFLINE.md). It publishes public release assets, so changes to that workflow need particular care around permissions, immutable package versions, and catalog integrity. diff --git a/README.md b/README.md new file mode 100644 index 0000000..a9c3cf4 --- /dev/null +++ b/README.md @@ -0,0 +1,45 @@ +# NavFrame + +NavFrame is an experimental Android navigation app that renders its own 480×240 images for compatible Yamaha motorcycle TFTs through NaviLite over Bluetooth. It does not capture StreetCross, Google Maps, Waze, or another app's screen. + +## Current status + +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. The owner has also confirmed that the bundled Asturias map works offline on the phone. These results do not validate the current MapLibre map renderer on the motorcycle TFT: the last reported TFT map attempt showed `MAPA NO DISPONIBLE`, and no later physical map-render result is recorded. + +Version 0.13.0 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, TFT map rendering, and a 30-minute screen-off session remains pending unless a newer test report says otherwise. + +## Build + +Requirements: JDK 17, Android SDK with API 36, and the Android SDK components requested by Gradle. Gradle is provided by the wrapper. + +```sh +./gradlew :app:assembleDebug +``` + +The debug APK is written to `app/build/outputs/apk/debug/app-debug.apk`. To run the automated checks: + +```sh +./gradlew :app:testDebugUnitTest :app:lintDebug :navilite:testDebugUnitTest :core:test +python3 -m unittest discover -s tools/offline -p 'test_*.py' +``` + +Set up `local.properties` for your own Android SDK when needed. It is excluded from Git. See [Contributing](CONTRIBUTING.md) for the development and review process. + +## Documentation + +- [Documentation index](docs/README.md) +- [Architecture and data flow](docs/ARCHITECTURE.md) +- [Offline maps and regional packages](docs/OFFLINE.md) +- [Worldwide region build and publication](docs/GLOBAL_OFFLINE.md) +- [Routing and geocoding service limits](docs/ROUTING.md) and [search policy](docs/GEOCODING.md) +- [Voice directions](docs/VOICE.md) and [fixed camera advisories](docs/RADARS.md) +- [Licenses and attribution](docs/LICENSING.md) +- [Testing and physical validation record](docs/TESTING.md) +- [English summary of original product brief](docs/PRODUCT_BRIEF_EN.md) +- [Security reporting](SECURITY.md) + +## License notes + +There is no single permissive license covering every part of this repository. In particular, NaviLite contains code adapted from Pillion under PolyForm Noncommercial 1.0.0, which restricts commercial use. Other code, datasets, fonts, and dependencies have their own terms and notices. Review [Licensing](docs/LICENSING.md) and the included notices before copying, redistributing, or using any part of this project. OpenStreetMap-derived offline data is distributed under ODbL 1.0 with attribution. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..0a72047 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,19 @@ +# Security policy + +NavFrame is experimental software. Do not rely on it as the sole source of directions, speed information, or road safety decisions. + +## Reporting a vulnerability + +Please report security issues privately. If GitHub private vulnerability reporting is enabled for this repository, use the **Security → Advisories** flow. Otherwise contact the maintainers using the private contact channel listed on the repository profile. Do not publish exploit details or sensitive data in a public issue. + +Include the affected version or commit, Android version/device where relevant, steps to reproduce, and the impact. Remove personal data, exact coordinates, Bluetooth addresses, credentials, and access tokens from logs or screenshots. + +## Scope and data handling + +The app can send search text to the configured geocoder, origin and destination coordinates to the configured routing service, and map-resource requests for the visible region to the configured style provider. Regional package catalogs and archives are fetched over HTTPS and checked against catalog sizes and SHA-256 values before package installation. A hash detects accidental or malicious content changes relative to the catalog; it does not authenticate a catalog whose source the user has changed. + +Please do not send production traffic or large-scale automated requests to public demo services as part of vulnerability research. Use a local service or a provider explicitly authorizing the test. + +## Supported versions + +There is no formal long-term support policy yet. Report issues against the latest public release and include the exact version/build when known. diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..1f43d5d --- /dev/null +++ b/app/build.gradle.kts @@ -0,0 +1,28 @@ +plugins { id("com.android.application"); kotlin("android") } +android { + namespace = "dev.navframe.app" + compileSdk = 36 + defaultConfig { + applicationId = "dev.navframe.app" + minSdk = 26 + targetSdk = 35 + versionCode = 16 + versionName = "0.13.0" + } + testOptions { unitTests.isIncludeAndroidResources = true } + compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 } +} +kotlin { jvmToolchain(17) } +dependencies { + implementation(project(":core")) + implementation("org.maplibre.gl:android-sdk-opengl:13.5.2") + implementation(project(":navilite")) + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2") + testImplementation("junit:junit:4.13.2") + testImplementation("org.robolectric:robolectric:4.16.1") +} + +tasks.withType().configureEach { + systemProperty("robolectric.dependency.repo.url", "https://repo.maven.apache.org/maven2") + systemProperty("navframe.previewDir", layout.buildDirectory.dir("outputs/preview").get().asFile.absolutePath) +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..1502318 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/assets/GSON_LICENSE.md b/app/src/main/assets/GSON_LICENSE.md new file mode 100644 index 0000000..ee4cea5 --- /dev/null +++ b/app/src/main/assets/GSON_LICENSE.md @@ -0,0 +1,217 @@ +# Gson 2.11.0 + +NavFrame includes the unmodified Gson runtime library for strict JSON parsing. +Copyright (C) 2008 Google Inc. (copyright notice in Gson.java at this release). + +Upstream source: https://github.com/google/gson/tree/gson-parent-2.11.0 +License source: https://github.com/google/gson/blob/gson-parent-2.11.0/LICENSE +Copyright source: https://github.com/google/gson/blob/gson-parent-2.11.0/gson/src/main/java/com/google/gson/Gson.java + +Gson is distributed under the Apache License, Version 2.0. The complete upstream +license follows unchanged. This license applies to Gson, not the entire NavFrame project. + +```text + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +``` diff --git a/app/src/main/assets/MAPLIBRE_LICENSE.md b/app/src/main/assets/MAPLIBRE_LICENSE.md new file mode 100644 index 0000000..3b7caec --- /dev/null +++ b/app/src/main/assets/MAPLIBRE_LICENSE.md @@ -0,0 +1,30 @@ +BSD 2-Clause License + +Copyright (c) 2021 MapLibre contributors + +Copyright (c) 2018-2021 MapTiler.com + +Copyright (c) 2014-2020 Mapbox + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/app/src/main/assets/OFFLINE_DATA_LICENSE.md b/app/src/main/assets/OFFLINE_DATA_LICENSE.md new file mode 100644 index 0000000..2d87860 --- /dev/null +++ b/app/src/main/assets/OFFLINE_DATA_LICENSE.md @@ -0,0 +1,568 @@ +# Asturias offline map data + +© OpenStreetMap contributors — https://www.openstreetmap.org/copyright +Data licensed under the Open Database License (ODbL) 1.0. +Regional extract supplied by Geofabrik: https://download.geofabrik.de/europe/spain/asturias.html +Original data timestamp: 2026-09-28T20:23:05Z. + +This APK distributes a derived database, offline/asturias.pmtiles, under ODbL 1.0. +The complete derived database is available inside this APK (ZIP entry assets/offline/asturias.pmtiles). +The original NavFrame transformation recipe is supplied in tools/offline/navframe.yaml +and tools/offline/build-asturias.sh in the accompanying project source. +No additional restriction is imposed on these map data. ODbL applies to the database, +not automatically to the application code. + +PMTiles SHA-256: f63f65f9c2bc7e169371d3da8c01125f15f3d6ae0caae0d7d7d47aad43f4df9e +Size: 34,617,483 bytes. + +## Catálogo de negocios Asturias (0.9) + +La base derivada adicional assets/offline/asturias-pois.sqlite se distribuye completa +en el APK bajo ODbL 1.0, con la misma fuente y fecha OSM indicadas arriba. +Receta original suministrada: tools/offline/build-pois.py y poi-requirements.txt. +11.457 lugares y 83 posibles radares fijos OSM; 2.347.008 bytes; schema SQLite1. +SHA-256: c5d8413f260b0b3e5bdc3da4c9b5e33f8e66f5acd80cc284a7e8668f039798f9 +No certifica horario, disponibilidad ni que un taller general repare motos. + +Full license, obtained from https://opendatacommons.org/licenses/odbl/odbl-10.txt: + +## ODC Open Database License (ODbL) + +### Preamble + +The Open Database License (ODbL) is a license agreement intended to +allow users to freely share, modify, and use this Database while +maintaining this same freedom for others. Many databases are covered by +copyright, and therefore this document licenses these rights. Some +jurisdictions, mainly in the European Union, have specific rights that +cover databases, and so the ODbL addresses these rights, too. Finally, +the ODbL is also an agreement in contract for users of this Database to +act in certain ways in return for accessing this Database. + +Databases can contain a wide variety of types of content (images, +audiovisual material, and sounds all in the same database, for example), +and so the ODbL only governs the rights over the Database, and not the +contents of the Database individually. Licensors should use the ODbL +together with another license for the contents, if the contents have a +single set of rights that uniformly covers all of the contents. If the +contents have multiple sets of different rights, Licensors should +describe what rights govern what contents together in the individual +record or in some other way that clarifies what rights apply. + +Sometimes the contents of a database, or the database itself, can be +covered by other rights not addressed here (such as private contracts, +trade mark over the name, or privacy rights / data protection rights +over information in the contents), and so you are advised that you may +have to consult other documents or clear other rights before doing +activities not covered by this License. + +------ + +The Licensor (as defined below) + +and + +You (as defined below) + +agree as follows: + +### 1.0 Definitions of Capitalised Words + +"Collective Database" - Means this Database in unmodified form as part +of a collection of independent databases in themselves that together are +assembled into a collective whole. A work that constitutes a Collective +Database will not be considered a Derivative Database. + +"Convey" - As a verb, means Using the Database, a Derivative Database, +or the Database as part of a Collective Database in any way that enables +a Person to make or receive copies of the Database or a Derivative +Database. Conveying does not include interaction with a user through a +computer network, or creating and Using a Produced Work, where no +transfer of a copy of the Database or a Derivative Database occurs. +"Contents" - The contents of this Database, which includes the +information, independent works, or other material collected into the +Database. For example, the contents of the Database could be factual +data or works such as images, audiovisual material, text, or sounds. + +"Database" - A collection of material (the Contents) arranged in a +systematic or methodical way and individually accessible by electronic +or other means offered under the terms of this License. + +"Database Directive" - Means Directive 96/9/EC of the European +Parliament and of the Council of 11 March 1996 on the legal protection +of databases, as amended or succeeded. + +"Database Right" - Means rights resulting from the Chapter III ("sui +generis") rights in the Database Directive (as amended and as transposed +by member states), which includes the Extraction and Re-utilisation of +the whole or a Substantial part of the Contents, as well as any similar +rights available in the relevant jurisdiction under Section 10.4. + +"Derivative Database" - Means a database based upon the Database, and +includes any translation, adaptation, arrangement, modification, or any +other alteration of the Database or of a Substantial part of the +Contents. This includes, but is not limited to, Extracting or +Re-utilising the whole or a Substantial part of the Contents in a new +Database. + +"Extraction" - Means the permanent or temporary transfer of all or a +Substantial part of the Contents to another medium by any means or in +any form. + +"License" - Means this license agreement and is both a license of rights +such as copyright and Database Rights and an agreement in contract. + +"Licensor" - Means the Person that offers the Database under the terms +of this License. + +"Person" - Means a natural or legal person or a body of persons +corporate or incorporate. + +"Produced Work" - a work (such as an image, audiovisual material, text, +or sounds) resulting from using the whole or a Substantial part of the +Contents (via a search or other query) from this Database, a Derivative +Database, or this Database as part of a Collective Database. + +"Publicly" - means to Persons other than You or under Your control by +either more than 50% ownership or by the power to direct their +activities (such as contracting with an independent consultant). + +"Re-utilisation" - means any form of making available to the public all +or a Substantial part of the Contents by the distribution of copies, by +renting, by online or other forms of transmission. + +"Substantial" - Means substantial in terms of quantity or quality or a +combination of both. The repeated and systematic Extraction or +Re-utilisation of insubstantial parts of the Contents may amount to the +Extraction or Re-utilisation of a Substantial part of the Contents. + +"Use" - As a verb, means doing any act that is restricted by copyright +or Database Rights whether in the original medium or any other; and +includes without limitation distributing, copying, publicly performing, +publicly displaying, and preparing derivative works of the Database, as +well as modifying the Database as may be technically necessary to use it +in a different mode or format. + +"You" - Means a Person exercising rights under this License who has not +previously violated the terms of this License with respect to the +Database, or who has received express permission from the Licensor to +exercise rights under this License despite a previous violation. + +Words in the singular include the plural and vice versa. + +### 2.0 What this License covers + +2.1. Legal effect of this document. This License is: + + a. A license of applicable copyright and neighbouring rights; + + b. A license of the Database Right; and + + c. An agreement in contract between You and the Licensor. + +2.2 Legal rights covered. This License covers the legal rights in the +Database, including: + + a. Copyright. Any copyright or neighbouring rights in the Database. + The copyright licensed includes any individual elements of the + Database, but does not cover the copyright over the Contents + independent of this Database. See Section 2.4 for details. Copyright + law varies between jurisdictions, but is likely to cover: the Database + model or schema, which is the structure, arrangement, and organisation + of the Database, and can also include the Database tables and table + indexes; the data entry and output sheets; and the Field names of + Contents stored in the Database; + + b. Database Rights. Database Rights only extend to the Extraction and + Re-utilisation of the whole or a Substantial part of the Contents. + Database Rights can apply even when there is no copyright over the + Database. Database Rights can also apply when the Contents are removed + from the Database and are selected and arranged in a way that would + not infringe any applicable copyright; and + + c. Contract. This is an agreement between You and the Licensor for + access to the Database. In return you agree to certain conditions of + use on this access as outlined in this License. + +2.3 Rights not covered. + + a. This License does not apply to computer programs used in the making + or operation of the Database; + + b. This License does not cover any patents over the Contents or the + Database; and + + c. This License does not cover any trademarks associated with the + Database. + +2.4 Relationship to Contents in the Database. The individual items of +the Contents contained in this Database may be covered by other rights, +including copyright, patent, data protection, privacy, or personality +rights, and this License does not cover any rights (other than Database +Rights or in contract) in individual Contents contained in the Database. +For example, if used on a Database of images (the Contents), this +License would not apply to copyright over individual images, which could +have their own separate licenses, or one single license covering all of +the rights over the images. + +### 3.0 Rights granted + +3.1 Subject to the terms and conditions of this License, the Licensor +grants to You a worldwide, royalty-free, non-exclusive, terminable (but +only under Section 9) license to Use the Database for the duration of +any applicable copyright and Database Rights. These rights explicitly +include commercial use, and do not exclude any field of endeavour. To +the extent possible in the relevant jurisdiction, these rights may be +exercised in all media and formats whether now known or created in the +future. + +The rights granted cover, for example: + + a. Extraction and Re-utilisation of the whole or a Substantial part of + the Contents; + + b. Creation of Derivative Databases; + + c. Creation of Collective Databases; + + d. Creation of temporary or permanent reproductions by any means and + in any form, in whole or in part, including of any Derivative + Databases or as a part of Collective Databases; and + + e. Distribution, communication, display, lending, making available, or + performance to the public by any means and in any form, in whole or in + part, including of any Derivative Database or as a part of Collective + Databases. + +3.2 Compulsory license schemes. For the avoidance of doubt: + + a. Non-waivable compulsory license schemes. In those jurisdictions in + which the right to collect royalties through any statutory or + compulsory licensing scheme cannot be waived, the Licensor reserves + the exclusive right to collect such royalties for any exercise by You + of the rights granted under this License; + + b. Waivable compulsory license schemes. In those jurisdictions in + which the right to collect royalties through any statutory or + compulsory licensing scheme can be waived, the Licensor waives the + exclusive right to collect such royalties for any exercise by You of + the rights granted under this License; and, + + c. Voluntary license schemes. The Licensor waives the right to collect + royalties, whether individually or, in the event that the Licensor is + a member of a collecting society that administers voluntary licensing + schemes, via that society, from any exercise by You of the rights + granted under this License. + +3.3 The right to release the Database under different terms, or to stop +distributing or making available the Database, is reserved. Note that +this Database may be multiple-licensed, and so You may have the choice +of using alternative licenses for this Database. Subject to Section +10.4, all other rights not expressly granted by Licensor are reserved. + +### 4.0 Conditions of Use + +4.1 The rights granted in Section 3 above are expressly made subject to +Your complying with the following conditions of use. These are important +conditions of this License, and if You fail to follow them, You will be +in material breach of its terms. + +4.2 Notices. If You Publicly Convey this Database, any Derivative +Database, or the Database as part of a Collective Database, then You +must: + + a. Do so only under the terms of this License or another license + permitted under Section 4.4; + + b. Include a copy of this License (or, as applicable, a license + permitted under Section 4.4) or its Uniform Resource Identifier (URI) + with the Database or Derivative Database, including both in the + Database or Derivative Database and in any relevant documentation; and + + c. Keep intact any copyright or Database Right notices and notices + that refer to this License. + + d. If it is not possible to put the required notices in a particular + file due to its structure, then You must include the notices in a + location (such as a relevant directory) where users would be likely to + look for it. + +4.3 Notice for using output (Contents). Creating and Using a Produced +Work does not require the notice in Section 4.2. However, if you +Publicly Use a Produced Work, You must include a notice associated with +the Produced Work reasonably calculated to make any Person that uses, +views, accesses, interacts with, or is otherwise exposed to the Produced +Work aware that Content was obtained from the Database, Derivative +Database, or the Database as part of a Collective Database, and that it +is available under this License. + + a. Example notice. The following text will satisfy notice under + Section 4.3: + + Contains information from DATABASE NAME, which is made available + here under the Open Database License (ODbL). + +DATABASE NAME should be replaced with the name of the Database and a +hyperlink to the URI of the Database. "Open Database License" should +contain a hyperlink to the URI of the text of this License. If +hyperlinks are not possible, You should include the plain text of the +required URI's with the above notice. + +4.4 Share alike. + + a. Any Derivative Database that You Publicly Use must be only under + the terms of: + + i. This License; + + ii. A later version of this License similar in spirit to this + License; or + + iii. A compatible license. + + If You license the Derivative Database under one of the licenses + mentioned in (iii), You must comply with the terms of that license. + + b. For the avoidance of doubt, Extraction or Re-utilisation of the + whole or a Substantial part of the Contents into a new database is a + Derivative Database and must comply with Section 4.4. + + c. Derivative Databases and Produced Works. A Derivative Database is + Publicly Used and so must comply with Section 4.4. if a Produced Work + created from the Derivative Database is Publicly Used. + + d. Share Alike and additional Contents. For the avoidance of doubt, + You must not add Contents to Derivative Databases under Section 4.4 a + that are incompatible with the rights granted under this License. + + e. Compatible licenses. Licensors may authorise a proxy to determine + compatible licenses under Section 4.4 a iii. If they do so, the + authorised proxy's public statement of acceptance of a compatible + license grants You permission to use the compatible license. + + +4.5 Limits of Share Alike. The requirements of Section 4.4 do not apply +in the following: + + a. For the avoidance of doubt, You are not required to license + Collective Databases under this License if You incorporate this + Database or a Derivative Database in the collection, but this License + still applies to this Database or a Derivative Database as a part of + the Collective Database; + + b. Using this Database, a Derivative Database, or this Database as + part of a Collective Database to create a Produced Work does not + create a Derivative Database for purposes of Section 4.4; and + + c. Use of a Derivative Database internally within an organisation is + not to the public and therefore does not fall under the requirements + of Section 4.4. + +4.6 Access to Derivative Databases. If You Publicly Use a Derivative +Database or a Produced Work from a Derivative Database, You must also +offer to recipients of the Derivative Database or Produced Work a copy +in a machine readable form of: + + a. The entire Derivative Database; or + + b. A file containing all of the alterations made to the Database or + the method of making the alterations to the Database (such as an + algorithm), including any additional Contents, that make up all the + differences between the Database and the Derivative Database. + +The Derivative Database (under a.) or alteration file (under b.) must be +available at no more than a reasonable production cost for physical +distributions and free of charge if distributed over the internet. + +4.7 Technological measures and additional terms + + a. This License does not allow You to impose (except subject to + Section 4.7 b.) any terms or any technological measures on the + Database, a Derivative Database, or the whole or a Substantial part of + the Contents that alter or restrict the terms of this License, or any + rights granted under it, or have the effect or intent of restricting + the ability of any person to exercise those rights. + + b. Parallel distribution. You may impose terms or technological + measures on the Database, a Derivative Database, or the whole or a + Substantial part of the Contents (a "Restricted Database") in + contravention of Section 4.7 a. only if You also make a copy of the + Database or a Derivative Database available to the recipient of the + Restricted Database: + + i. That is available without additional fee; + + ii. That is available in a medium that does not alter or restrict + the terms of this License, or any rights granted under it, or have + the effect or intent of restricting the ability of any person to + exercise those rights (an "Unrestricted Database"); and + + iii. The Unrestricted Database is at least as accessible to the + recipient as a practical matter as the Restricted Database. + + c. For the avoidance of doubt, You may place this Database or a + Derivative Database in an authenticated environment, behind a + password, or within a similar access control scheme provided that You + do not alter or restrict the terms of this License or any rights + granted under it or have the effect or intent of restricting the + ability of any person to exercise those rights. + +4.8 Licensing of others. You may not sublicense the Database. Each time +You communicate the Database, the whole or Substantial part of the +Contents, or any Derivative Database to anyone else in any way, the +Licensor offers to the recipient a license to the Database on the same +terms and conditions as this License. You are not responsible for +enforcing compliance by third parties with this License, but You may +enforce any rights that You have over a Derivative Database. You are +solely responsible for any modifications of a Derivative Database made +by You or another Person at Your direction. You may not impose any +further restrictions on the exercise of the rights granted or affirmed +under this License. + +### 5.0 Moral rights + +5.1 Moral rights. This section covers moral rights, including any rights +to be identified as the author of the Database or to object to treatment +that would otherwise prejudice the author's honour and reputation, or +any other derogatory treatment: + + a. For jurisdictions allowing waiver of moral rights, Licensor waives + all moral rights that Licensor may have in the Database to the fullest + extent possible by the law of the relevant jurisdiction under Section + 10.4; + + b. If waiver of moral rights under Section 5.1 a in the relevant + jurisdiction is not possible, Licensor agrees not to assert any moral + rights over the Database and waives all claims in moral rights to the + fullest extent possible by the law of the relevant jurisdiction under + Section 10.4; and + + c. For jurisdictions not allowing waiver or an agreement not to assert + moral rights under Section 5.1 a and b, the author may retain their + moral rights over certain aspects of the Database. + +Please note that some jurisdictions do not allow for the waiver of moral +rights, and so moral rights may still subsist over the Database in some +jurisdictions. + +### 6.0 Fair dealing, Database exceptions, and other rights not affected + +6.1 This License does not affect any rights that You or anyone else may +independently have under any applicable law to make any use of this +Database, including without limitation: + + a. Exceptions to the Database Right including: Extraction of Contents + from non-electronic Databases for private purposes, Extraction for + purposes of illustration for teaching or scientific research, and + Extraction or Re-utilisation for public security or an administrative + or judicial procedure. + + b. Fair dealing, fair use, or any other legally recognised limitation + or exception to infringement of copyright or other applicable laws. + +6.2 This License does not affect any rights of lawful users to Extract +and Re-utilise insubstantial parts of the Contents, evaluated +quantitatively or qualitatively, for any purposes whatsoever, including +creating a Derivative Database (subject to other rights over the +Contents, see Section 2.4). The repeated and systematic Extraction or +Re-utilisation of insubstantial parts of the Contents may however amount +to the Extraction or Re-utilisation of a Substantial part of the +Contents. + +### 7.0 Warranties and Disclaimer + +7.1 The Database is licensed by the Licensor "as is" and without any +warranty of any kind, either express, implied, or arising by statute, +custom, course of dealing, or trade usage. Licensor specifically +disclaims any and all implied warranties or conditions of title, +non-infringement, accuracy or completeness, the presence or absence of +errors, fitness for a particular purpose, merchantability, or otherwise. +Some jurisdictions do not allow the exclusion of implied warranties, so +this exclusion may not apply to You. + +### 8.0 Limitation of liability + +8.1 Subject to any liability that may not be excluded or limited by law, +the Licensor is not liable for, and expressly excludes, all liability +for loss or damage however and whenever caused to anyone by any use +under this License, whether by You or by anyone else, and whether caused +by any fault on the part of the Licensor or not. This exclusion of +liability includes, but is not limited to, any special, incidental, +consequential, punitive, or exemplary damages such as loss of revenue, +data, anticipated profits, and lost business. This exclusion applies +even if the Licensor has been advised of the possibility of such +damages. + +8.2 If liability may not be excluded by law, it is limited to actual and +direct financial loss to the extent it is caused by proved negligence on +the part of the Licensor. + +### 9.0 Termination of Your rights under this License + +9.1 Any breach by You of the terms and conditions of this License +automatically terminates this License with immediate effect and without +notice to You. For the avoidance of doubt, Persons who have received the +Database, the whole or a Substantial part of the Contents, Derivative +Databases, or the Database as part of a Collective Database from You +under this License will not have their licenses terminated provided +their use is in full compliance with this License or a license granted +under Section 4.8 of this License. Sections 1, 2, 7, 8, 9 and 10 will +survive any termination of this License. + +9.2 If You are not in breach of the terms of this License, the Licensor +will not terminate Your rights under it. + +9.3 Unless terminated under Section 9.1, this License is granted to You +for the duration of applicable rights in the Database. + +9.4 Reinstatement of rights. If you cease any breach of the terms and +conditions of this License, then your full rights under this License +will be reinstated: + + a. Provisionally and subject to permanent termination until the 60th + day after cessation of breach; + + b. Permanently on the 60th day after cessation of breach unless + otherwise reasonably notified by the Licensor; or + + c. Permanently if reasonably notified by the Licensor of the + violation, this is the first time You have received notice of + violation of this License from the Licensor, and You cure the + violation prior to 30 days after your receipt of the notice. + +Persons subject to permanent termination of rights are not eligible to +be a recipient and receive a license under Section 4.8. + +9.5 Notwithstanding the above, Licensor reserves the right to release +the Database under different license terms or to stop distributing or +making available the Database. Releasing the Database under different +license terms or stopping the distribution of the Database will not +withdraw this License (or any other license that has been, or is +required to be, granted under the terms of this License), and this +License will continue in full force and effect unless terminated as +stated above. + +### 10.0 General + +10.1 If any provision of this License is held to be invalid or +unenforceable, that must not affect the validity or enforceability of +the remainder of the terms and conditions of this License and each +remaining provision of this License shall be valid and enforced to the +fullest extent permitted by law. + +10.2 This License is the entire agreement between the parties with +respect to the rights granted here over the Database. It replaces any +earlier understandings, agreements or representations with respect to +the Database. + +10.3 If You are in breach of the terms of this License, You will not be +entitled to rely on the terms of this License or to complain of any +breach by the Licensor. + +10.4 Choice of law. This License takes effect in and will be governed by +the laws of the relevant jurisdiction in which the License terms are +sought to be enforced. If the standard suite of rights granted under +applicable copyright law and Database Rights in the relevant +jurisdiction includes additional rights not granted under this License, +these additional rights are granted in this License in order to meet the +terms of this License. diff --git a/app/src/main/assets/OFFLINE_FONT_LICENSE.md b/app/src/main/assets/OFFLINE_FONT_LICENSE.md new file mode 100644 index 0000000..9d8e5ba --- /dev/null +++ b/app/src/main/assets/OFFLINE_FONT_LICENSE.md @@ -0,0 +1,98 @@ +# Noto Sans Regular offline glyphs + +Unmodified glyph PBF files supplied by MapLibre demotiles, font/Noto Sans Regular. +Source: https://github.com/maplibre/demotiles/tree/gh-pages/font/Noto%20Sans%20Regular +Unicode ranges 0–2047. The license below is reproduced unchanged from that font directory. + +This Font Software is licensed under the SIL Open Font License, +Version 1.1. + +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font +creation efforts of academic and linguistic communities, and to +provide a free and open framework in which fonts may be shared and +improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply to +any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software +components as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, +deleting, or substituting -- in part or in whole -- any of the +components of the Original Version, by changing formats or by porting +the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, +modify, redistribute, and sell modified and unmodified copies of the +Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in +Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the +corresponding Copyright Holder. This restriction only applies to the +primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created using +the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. \ No newline at end of file diff --git a/app/src/main/assets/PILLION_LICENSE.md b/app/src/main/assets/PILLION_LICENSE.md new file mode 100644 index 0000000..de70744 --- /dev/null +++ b/app/src/main/assets/PILLION_LICENSE.md @@ -0,0 +1,84 @@ +# Pillion License + +Pillion is licensed under the **PolyForm Noncommercial License 1.0.0**. + +You may use, modify, and share it **for non-commercial purposes only**. Commercial use requires a +separate license from the copyright holder. + +Required Notice: Copyright 2026 the Pillion authors + +--- + +# PolyForm Noncommercial License 1.0.0 + + + +## Acceptance + +In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses. + +## Copyright License + +The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license). + +## Distribution License + +The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license). + +## Notices + +You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example: + +> Required Notice: Copyright Yoyodyne, Inc. (http://example.com) + +## Changes and New Works License + +The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose. + +## Patent License + +The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software. + +## Noncommercial Purposes + +Any noncommercial purpose is a permitted purpose. + +## Personal Uses + +Personal use for research, experiment, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, amateur pursuits, or religious observance, without any anticipated commercial application, is use for a permitted purpose. + +## Noncommercial Organizations + +Use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization, or government institution is use for a permitted purpose regardless of the source of funding or obligations resulting from the funding. + +## Fair Use + +You may have "fair use" rights for the software under the law. These terms do not limit them. + +## No Other Rights + +These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses. + +## Patent Defense + +If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company. + +## Violations + +The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately. + +## No Liability + +***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.*** + +## Definitions + +The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms. + +**You** refers to the individual or entity agreeing to these terms. + +**Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect. + +**Your licenses** are all the licenses granted to you for the software under these terms. + +**Use** means anything you do with the software requiring one of your licenses. diff --git a/app/src/main/assets/PILLION_NOTICE.md b/app/src/main/assets/PILLION_NOTICE.md new file mode 100644 index 0000000..fb0caaa --- /dev/null +++ b/app/src/main/assets/PILLION_NOTICE.md @@ -0,0 +1,10 @@ +# Pillion provenance + +Required Notice: Copyright 2026 the Pillion authors + +Source: https://github.com/alexandrevega/pillion +Inspected/adapted commit: 6647af22f035ad74dc98f0e2a29e0c8a769a1caa +License: PolyForm Noncommercial 1.0.0 (see LICENSE.md) +https://polyformproject.org/licenses/noncommercial/1.0.0 + +NavFrame's navilite module adapts packet framing, CRC, authentication, setup values, RFCOMM service and image stop-and-wait sequencing from composeApp/src/commonMain/kotlin/app/pillion/{protocol,core} and composeApp/src/androidMain/kotlin/app/pillion/android/RfcommByteChannel.kt. Captured authentication test vectors are adapted from composeApp/src/commonTest/kotlin/app/pillion/ProtocolTest.kt. It adds bounded validated receiving, input validation, explicit device selection and timeout/cancellation handling. It does not reuse screen-capture functionality. See docs/NAVILITE_RESEARCH.md for the file-level inventory. Preserve this notice and license/URL when distributing these derived parts. diff --git a/app/src/main/assets/map/tft-style.json b/app/src/main/assets/map/tft-style.json new file mode 100644 index 0000000..0c1e323 --- /dev/null +++ b/app/src/main/assets/map/tft-style.json @@ -0,0 +1,13 @@ +{ + "version": 8, + "name": "NavFrame TFT vector", + "glyphs": "https://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf", + "sources": {"osm": {"type": "vector", "url": "https://tiles.openfreemap.org/planet", "attribution": "OpenFreeMap © OpenMapTiles © OpenStreetMap contributors"}}, + "layers": [ + {"id":"background","type":"background","paint":{"background-color":"#0d1319"}}, + {"id":"water","type":"fill","source":"osm","source-layer":"water","paint":{"fill-color":"#142c40"}}, + {"id":"roads-minor","type":"line","source":"osm","source-layer":"transportation","filter":["in","class","minor","service","tertiary"],"paint":{"line-color":"#495563","line-width":["interpolate",["linear"],["zoom"],12,1,18,7]},"layout":{"line-cap":"round","line-join":"round"}}, + {"id":"roads-major","type":"line","source":"osm","source-layer":"transportation","filter":["in","class","primary","secondary","trunk","motorway"],"paint":{"line-color":"#b4c2ce","line-width":["interpolate",["linear"],["zoom"],10,1,18,10]},"layout":{"line-cap":"round","line-join":"round"}}, + {"id":"road-names","type":"symbol","source":"osm","source-layer":"transportation_name","minzoom":14,"filter":["in","class","primary","secondary","trunk","motorway"],"layout":{"symbol-placement":"line","text-field":"{name}","text-font":["Noto Sans Regular"],"text-size":16,"text-max-angle":30,"symbol-spacing":220},"paint":{"text-color":"#e5eef5","text-halo-color":"#0d1319","text-halo-width":2}} + ] +} diff --git a/app/src/main/assets/offline/asturias-pois.sqlite b/app/src/main/assets/offline/asturias-pois.sqlite new file mode 100644 index 0000000..b254a77 Binary files /dev/null and b/app/src/main/assets/offline/asturias-pois.sqlite differ diff --git a/app/src/main/assets/offline/asturias.pmtiles b/app/src/main/assets/offline/asturias.pmtiles new file mode 100644 index 0000000..b202bbf Binary files /dev/null and b/app/src/main/assets/offline/asturias.pmtiles differ diff --git a/app/src/main/assets/offline/fonts/Noto Sans Regular/0-255.pbf b/app/src/main/assets/offline/fonts/Noto Sans Regular/0-255.pbf new file mode 100644 index 0000000..736ba4a Binary files /dev/null and b/app/src/main/assets/offline/fonts/Noto Sans Regular/0-255.pbf differ diff --git a/app/src/main/assets/offline/fonts/Noto Sans Regular/1024-1279.pbf b/app/src/main/assets/offline/fonts/Noto Sans Regular/1024-1279.pbf new file mode 100644 index 0000000..99627a3 Binary files /dev/null and b/app/src/main/assets/offline/fonts/Noto Sans Regular/1024-1279.pbf differ diff --git a/app/src/main/assets/offline/fonts/Noto Sans Regular/1280-1535.pbf b/app/src/main/assets/offline/fonts/Noto Sans Regular/1280-1535.pbf new file mode 100644 index 0000000..1e2a7b7 Binary files /dev/null and b/app/src/main/assets/offline/fonts/Noto Sans Regular/1280-1535.pbf differ diff --git a/app/src/main/assets/offline/fonts/Noto Sans Regular/1536-1791.pbf b/app/src/main/assets/offline/fonts/Noto Sans Regular/1536-1791.pbf new file mode 100644 index 0000000..aa254d6 Binary files /dev/null and b/app/src/main/assets/offline/fonts/Noto Sans Regular/1536-1791.pbf differ diff --git a/app/src/main/assets/offline/fonts/Noto Sans Regular/1792-2047.pbf b/app/src/main/assets/offline/fonts/Noto Sans Regular/1792-2047.pbf new file mode 100644 index 0000000..15e9f72 Binary files /dev/null and b/app/src/main/assets/offline/fonts/Noto Sans Regular/1792-2047.pbf differ diff --git a/app/src/main/assets/offline/fonts/Noto Sans Regular/256-511.pbf b/app/src/main/assets/offline/fonts/Noto Sans Regular/256-511.pbf new file mode 100644 index 0000000..6cc6850 Binary files /dev/null and b/app/src/main/assets/offline/fonts/Noto Sans Regular/256-511.pbf differ diff --git a/app/src/main/assets/offline/fonts/Noto Sans Regular/512-767.pbf b/app/src/main/assets/offline/fonts/Noto Sans Regular/512-767.pbf new file mode 100644 index 0000000..659826e Binary files /dev/null and b/app/src/main/assets/offline/fonts/Noto Sans Regular/512-767.pbf differ diff --git a/app/src/main/assets/offline/fonts/Noto Sans Regular/768-1023.pbf b/app/src/main/assets/offline/fonts/Noto Sans Regular/768-1023.pbf new file mode 100644 index 0000000..660c89e Binary files /dev/null and b/app/src/main/assets/offline/fonts/Noto Sans Regular/768-1023.pbf differ diff --git a/app/src/main/java/dev/navframe/app/AndroidLocationProvider.kt b/app/src/main/java/dev/navframe/app/AndroidLocationProvider.kt new file mode 100644 index 0000000..82a181b --- /dev/null +++ b/app/src/main/java/dev/navframe/app/AndroidLocationProvider.kt @@ -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(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 } + } +} diff --git a/app/src/main/java/dev/navframe/app/ConfiguredMapDataSource.kt b/app/src/main/java/dev/navframe/app/ConfiguredMapDataSource.kt new file mode 100644 index 0000000..e6348de --- /dev/null +++ b/app/src/main/java/dev/navframe/app/ConfiguredMapDataSource.kt @@ -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" } +} diff --git a/app/src/main/java/dev/navframe/app/FakeTftTransport.kt b/app/src/main/java/dev/navframe/app/FakeTftTransport.kt new file mode 100644 index 0000000..c63a13e --- /dev/null +++ b/app/src/main/java/dev/navframe/app/FakeTftTransport.kt @@ -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(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()) + } +} diff --git a/app/src/main/java/dev/navframe/app/MainActivity.kt b/app/src/main/java/dev/navframe/app/MainActivity.kt new file mode 100644 index 0000000..51425ce --- /dev/null +++ b/app/src/main/java/dev/navframe/app/MainActivity.kt @@ -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 = 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() + 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, 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() + 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() + 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() +} diff --git a/app/src/main/java/dev/navframe/app/MapFrameComposer.kt b/app/src/main/java/dev/navframe/app/MapFrameComposer.kt new file mode 100644 index 0000000..e39cc0b --- /dev/null +++ b/app/src/main/java/dev/navframe/app/MapFrameComposer.kt @@ -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() + 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() } + } +} diff --git a/app/src/main/java/dev/navframe/app/MapLibreTftRenderer.kt b/app/src/main/java/dev/navframe/app/MapLibreTftRenderer.kt new file mode 100644 index 0000000..b1964d0 --- /dev/null +++ b/app/src/main/java/dev/navframe/app/MapLibreTftRenderer.kt @@ -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()) + 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 + } +} diff --git a/app/src/main/java/dev/navframe/app/MapRenderDiagnostics.kt b/app/src/main/java/dev/navframe/app/MapRenderDiagnostics.kt new file mode 100644 index 0000000..3618df9 --- /dev/null +++ b/app/src/main/java/dev/navframe/app/MapRenderDiagnostics.kt @@ -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 + } +} diff --git a/app/src/main/java/dev/navframe/app/NavigationVoiceController.kt b/app/src/main/java/dev/navframe/app/NavigationVoiceController.kt new file mode 100644 index 0000000..55527dc --- /dev/null +++ b/app/src/main/java/dev/navframe/app/NavigationVoiceController.kt @@ -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 } +} diff --git a/app/src/main/java/dev/navframe/app/NavigationVoicePreferences.kt b/app/src/main/java/dev/navframe/app/NavigationVoicePreferences.kt new file mode 100644 index 0000000..80394d9 --- /dev/null +++ b/app/src/main/java/dev/navframe/app/NavigationVoicePreferences.kt @@ -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() + } +} diff --git a/app/src/main/java/dev/navframe/app/NominatimGeocoder.kt b/app/src/main/java/dev/navframe/app/NominatimGeocoder.kt new file mode 100644 index 0000000..e5f7c9f --- /dev/null +++ b/app/src/main/java/dev/navframe/app/NominatimGeocoder.kt @@ -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 { + 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() + 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) + private val cache = LinkedHashMap() + private val gate = Mutex() + private var lastRequestMs = 0L + private val blockedUntil = java.util.concurrent.ConcurrentHashMap() + private fun clockMs() = System.nanoTime() / 1_000_000 + private fun cached(key: String): List? = 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" } + } + } +} diff --git a/app/src/main/java/dev/navframe/app/OfflineMapManager.kt b/app/src/main/java/dev/navframe/app/OfflineMapManager.kt new file mode 100644 index 0000000..870d1b0 --- /dev/null +++ b/app/src/main/java/dev/navframe/app/OfflineMapManager.kt @@ -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>(emptyList()) + val packs: StateFlow> = 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:///") diff --git a/app/src/main/java/dev/navframe/app/OfflineMapStyle.kt b/app/src/main/java/dev/navframe/app/OfflineMapStyle.kt new file mode 100644 index 0000000..426eb50 --- /dev/null +++ b/app/src/main/java/dev/navframe/app/OfflineMapStyle.kt @@ -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() + } +} diff --git a/app/src/main/java/dev/navframe/app/OfflinePlaceRepository.kt b/app/src/main/java/dev/navframe/app/OfflinePlaceRepository.kt new file mode 100644 index 0000000..3c30e7f --- /dev/null +++ b/app/src/main/java/dev/navframe/app/OfflinePlaceRepository.kt @@ -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 = 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() + 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 = 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() + 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 = 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() + 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))) + } + } +} diff --git a/app/src/main/java/dev/navframe/app/PhoneMapView.kt b/app/src/main/java/dev/navframe/app/PhoneMapView.kt new file mode 100644 index 0000000..c059740 --- /dev/null +++ b/app/src/main/java/dev/navframe/app/PhoneMapView.kt @@ -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 = 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("phone-route")?.setGeoJson(routeData) + val positionKnown = value.navigationStatus != NavigationStatus.IDLE && value.position != GeoPoint(0.0, 0.0) + loaded.getSourceAs("phone-rider")?.setGeoJson(if (positionKnown) FeatureCollection.fromFeatures(arrayOf(Feature.fromGeometry(Point.fromLngLat(value.position.longitude, value.position.latitude)))) else empty()) + loaded.getLayerAs("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) { 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("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()) +} diff --git a/app/src/main/java/dev/navframe/app/PmtilesInfo.kt b/app/src/main/java/dev/navframe/app/PmtilesInfo.kt new file mode 100644 index 0000000..af3a2a1 --- /dev/null +++ b/app/src/main/java/dev/navframe/app/PmtilesInfo.kt @@ -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 { + 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) + } + } +} diff --git a/app/src/main/java/dev/navframe/app/RegionalDownloadManager.kt b/app/src/main/java/dev/navframe/app/RegionalDownloadManager.kt new file mode 100644 index 0000000..46f2efa --- /dev/null +++ b/app/src/main/java/dev/navframe/app/RegionalDownloadManager.kt @@ -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 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 + } +} diff --git a/app/src/main/java/dev/navframe/app/RegionalPackManager.kt b/app/src/main/java/dev/navframe/app/RegionalPackManager.kt new file mode 100644 index 0000000..d52f9b9 --- /dev/null +++ b/app/src/main/java/dev/navframe/app/RegionalPackManager.kt @@ -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>(emptyList()) + val regions = mutableRegions.asStateFlow() + private val mutableProgress = MutableStateFlow(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 withCatalogs(block: suspend (List) -> 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() + 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 { + 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() + 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): List = regions.groupBy { it.manifest.id }.values.map { versions -> + versions.maxWith(compareBy { 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) } + } +} diff --git a/app/src/main/java/dev/navframe/app/SyntheticTftRenderer.kt b/app/src/main/java/dev/navframe/app/SyntheticTftRenderer.kt new file mode 100644 index 0000000..f4739e6 --- /dev/null +++ b/app/src/main/java/dev/navframe/app/SyntheticTftRenderer.kt @@ -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() } + } +} diff --git a/app/src/main/java/dev/navframe/app/TestTftRenderer.kt b/app/src/main/java/dev/navframe/app/TestTftRenderer.kt new file mode 100644 index 0000000..ef6910a --- /dev/null +++ b/app/src/main/java/dev/navframe/app/TestTftRenderer.kt @@ -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() } + } +} diff --git a/app/src/main/java/dev/navframe/app/TftPreviewView.kt b/app/src/main/java/dev/navframe/app/TftPreviewView.kt new file mode 100644 index 0000000..64080c7 --- /dev/null +++ b/app/src/main/java/dev/navframe/app/TftPreviewView.kt @@ -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() } +} diff --git a/app/src/main/java/dev/navframe/app/TftService.kt b/app/src/main/java/dev/navframe/app/TftService.kt new file mode 100644 index 0000000..98d68bb --- /dev/null +++ b/app/src/main/java/dev/navframe/app/TftService.kt @@ -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(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(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" + } +} diff --git a/app/src/main/java/dev/navframe/app/UnifiedPlaceSearch.kt b/app/src/main/java/dev/navframe/app/UnifiedPlaceSearch.kt new file mode 100644 index 0000000..7e736b6 --- /dev/null +++ b/app/src/main/java/dev/navframe/app/UnifiedPlaceSearch.kt @@ -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, 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 = + 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, online: List): List = + (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) -> 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 } +} diff --git a/app/src/main/java/dev/navframe/app/ValhallaRoutingEngine.kt b/app/src/main/java/dev/navframe/app/ValhallaRoutingEngine.kt new file mode 100644 index 0000000..6edd671 --- /dev/null +++ b/app/src/main/java/dev/navframe/app/ValhallaRoutingEngine.kt @@ -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() + 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" } + } + } +} diff --git a/app/src/main/res/drawable/ic_navframe.xml b/app/src/main/res/drawable/ic_navframe.xml new file mode 100644 index 0000000..fb8a91a --- /dev/null +++ b/app/src/main/res/drawable/ic_navframe.xml @@ -0,0 +1,4 @@ + + + + diff --git a/app/src/main/res/values/styles.xml b/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..fdb27b7 --- /dev/null +++ b/app/src/main/res/values/styles.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/xml/data_extraction_rules.xml b/app/src/main/res/xml/data_extraction_rules.xml new file mode 100644 index 0000000..173e172 --- /dev/null +++ b/app/src/main/res/xml/data_extraction_rules.xml @@ -0,0 +1,4 @@ + + + + diff --git a/app/src/test/java/dev/navframe/app/ConfiguredMapDataSourceTest.kt b/app/src/test/java/dev/navframe/app/ConfiguredMapDataSourceTest.kt new file mode 100644 index 0000000..79433c7 --- /dev/null +++ b/app/src/test/java/dev/navframe/app/ConfiguredMapDataSourceTest.kt @@ -0,0 +1,31 @@ +package dev.navframe.app + +import org.junit.Assert.* +import org.junit.Test + +class ConfiguredMapDataSourceTest { + @Test fun defaultUsesBundledVectorStyleAndRequiredProviderCredits() { + val source = ConfiguredMapDataSource().tileSource() + assertEquals("asset://map/tft-style.json", source.uri) + assertTrue(source.attribution.contains("OpenFreeMap")) + assertTrue(source.attribution.contains("OpenStreetMap")) + } + @Test fun remoteStyleMustUseHttpsWithoutEmbeddedUserCredentials() { + for (url in listOf("http://example.com/map.json", "https://user:secret@example.com/style.json", "file:///map.json", "https://tile.openstreetmap.org/style.json")) { + assertThrows(IllegalArgumentException::class.java) { ConfiguredMapDataSource(url) } + } + } + @Test fun privateQueryTokenRemainsButCustomStyleCannotImpersonateDefaultProvider() { + val uri = "https://maps.example.com/style.json?key=private-user-key" + val source = ConfiguredMapDataSource(uri, "© Example · © OpenStreetMap contributors").tileSource() + assertEquals(uri, source.uri) + assertEquals(ConfiguredMapDataSource.BASE_ATTRIBUTION, source.attribution) + assertFalse(source.attribution.contains("OpenFreeMap")) + assertFalse(source.attribution.contains("Example")) + assertFalse(source.attribution.contains("OpenStreetMap")) + } + @Test fun userOverrideCannotEraseMandatoryProviderCredits() { + assertEquals(ConfiguredMapDataSource.DEFAULT_ATTRIBUTION, ConfiguredMapDataSource("", " ").tileSource().attribution) + assertEquals(ConfiguredMapDataSource.BASE_ATTRIBUTION, ConfiguredMapDataSource("https://example.com/style.json", "fake").tileSource().attribution) + } +} diff --git a/app/src/test/java/dev/navframe/app/MainActivityDestinationTest.kt b/app/src/test/java/dev/navframe/app/MainActivityDestinationTest.kt new file mode 100644 index 0000000..daeabe0 --- /dev/null +++ b/app/src/test/java/dev/navframe/app/MainActivityDestinationTest.kt @@ -0,0 +1,177 @@ +package dev.navframe.app + +import android.os.Bundle +import android.os.Looper +import android.widget.Button +import android.widget.EditText +import android.widget.Spinner +import android.view.View +import android.view.ViewGroup +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.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 MainActivityDestinationTest { + class PhoneWithoutGpu : MainActivity() { override fun createPhoneMap(savedState: Bundle?): PhoneMapView? = null } + class RecenterTestActivity : MainActivity() { + var reliable = false + var recenterCalls = 0 + override fun createPhoneMap(savedState: Bundle?): PhoneMapView? = null + override fun hasReliablePosition() = reliable + override fun recenterPhoneMap() { recenterCalls++ } + } + @org.robolectric.annotation.GraphicsMode(org.robolectric.annotation.GraphicsMode.Mode.NATIVE) + @Config(sdk = [34], qualifiers = "w360dp-h720dp-mdpi") + @Test fun exportsCompactPhoneLayoutWithPlaceholderMap() { + val controller = Robolectric.buildActivity(PhoneWithoutGpu::class.java).create() + try { + val activity = controller.get() + val view = activity.findViewById(android.R.id.content) + view.measure(View.MeasureSpec.makeMeasureSpec(360, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(720, View.MeasureSpec.EXACTLY)) + view.layout(0, 0, 360, 720) + val bitmap = android.graphics.Bitmap.createBitmap(360, 720, android.graphics.Bitmap.Config.ARGB_8888) + view.draw(android.graphics.Canvas(bitmap)) + val directory = java.io.File(requireNotNull(System.getProperty("navframe.previewDir"))).apply { mkdirs() } + java.io.File(directory, "phone-layout-placeholder.png").outputStream().use { bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, it) } + assertTrue(view.height > 0) + fun field(name: String) = MainActivity::class.java.getDeclaredField(name).apply { isAccessible = true } + field("destinationName").set(activity, "Destino de ejemplo") + (field("routeInfo").get(activity) as android.widget.TextView).text = "Vista previa · 12,4 km · 18 min estimados" + MainActivity::class.java.getDeclaredMethod("showRouteSheet").apply { isAccessible = true }.invoke(activity) + val dialogView = org.robolectric.shadows.ShadowAlertDialog.getLatestAlertDialog().window!!.decorView + dialogView.measure(View.MeasureSpec.makeMeasureSpec(360, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(440, View.MeasureSpec.AT_MOST)) + dialogView.layout(0, 0, 360, dialogView.measuredHeight) + val canvas = android.graphics.Canvas(bitmap) + canvas.save(); canvas.translate(0f, (720 - dialogView.height).toFloat()); dialogView.draw(canvas); canvas.restore() + java.io.File(directory, "phone-route-sheet-placeholder.png").outputStream().use { bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, it) } + } finally { controller.destroy() } + } + @Test fun editingQueryClearsChosenCoordinatesAndCannotRecalculateOldDestination() { + val activityController = Robolectric.buildActivity(PhoneWithoutGpu::class.java).create() + val serviceController = Robolectric.buildService(TftService::class.java).create() + val activity = activityController.get() + val service = serviceController.get() + val route = RouteResult(listOf(GeoPoint(43.36, -5.85), GeoPoint(43.37, -5.85)), emptyList(), 1112, 120) + var requests = 0 + service.routingEngineFactory = { object : RoutingEngine { + override suspend fun calculateRoute(origin: GeoPoint, destination: GeoPoint, options: RouteOptions): RouteResult { requests++; return route } + override suspend fun recalculateRoute(origin: GeoPoint, previousRoute: RouteResult, options: RouteOptions) = route + } } + service.mapRenderOverride = { _, _ -> TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) } + fun field(name: String) = MainActivity::class.java.getDeclaredField(name).apply { isAccessible = true } + fun children(view: View): List = listOf(view) + if (view is ViewGroup) (0 until view.childCount).flatMap { children(view.getChildAt(it)) } else emptyList() + try { + field("service").set(activity, service) + MainActivity::class.java.getDeclaredMethod("observeService").apply { isAccessible = true }.invoke(activity) + field("destination").set(activity, route.geometry.last()) + service.calculateRoute(route.geometry.last(), true, "https://example.test/route") + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(100)) + assertEquals(1, requests) + (field("searchQuery").get(activity) as EditText).setText("Una dirección nueva") + assertNull(field("destination").get(activity)) + (field("origin").get(activity) as Spinner).setSelection(1) + MainActivity::class.java.getDeclaredMethod("calculateRoute").apply { isAccessible = true }.invoke(activity) + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(100)) + assertEquals(1, requests) + assertNull(service.navigationState.value.route) + } finally { activityController.destroy(); serviceController.destroy() } + } + @Test fun recenterButtonRequiresFreshGpsAndRepeatedNoticeReplacesItsTimer() { + val activityController = Robolectric.buildActivity(RecenterTestActivity::class.java).create() + val serviceController = Robolectric.buildService(TftService::class.java).create() + val activity = activityController.get() + val service = serviceController.get() + shadowOf(org.robolectric.RuntimeEnvironment.getApplication()).grantPermissions(android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION) + fun field(name: String) = MainActivity::class.java.getDeclaredField(name).apply { isAccessible = true } + // Locate through its accessible label, as a UI test would. + fun children(view: View): List = listOf(view) + if (view is ViewGroup) (0 until view.childCount).flatMap { children(view.getChildAt(it)) } else emptyList() + val recenter = children(activity.window.decorView).first { it.contentDescription == "Centrar en mi posición y seguir el mapa" } + try { + field("service").set(activity, service) + recenter.performClick() + val notice = field("positionNotice").get(activity) as android.widget.TextView + assertEquals(0, activity.recenterCalls) + assertEquals(View.VISIBLE, notice.visibility) + assertTrue(notice.text.toString().contains("GPS")) + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(1500)) + recenter.performClick() + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(1200)) + assertEquals(View.VISIBLE, notice.visibility) + // The first tap's timer would have expired now; the second tap replaced it. + activity.reliable = true + recenter.performClick() + assertEquals(1, activity.recenterCalls) + assertEquals(View.GONE, notice.visibility) + } finally { activityController.destroy(); serviceController.destroy() } + } + @Test fun choosingLocalPlaceFromItsRealDetailDialogCalculatesPreviewWithoutStartingGuidance() { + val activityController = Robolectric.buildActivity(PhoneWithoutGpu::class.java).create() + val serviceController = Robolectric.buildService(TftService::class.java).create() + val activity = activityController.get() + val service = serviceController.get() + val place = OfflinePlace("n/123", "Taller de prueba", PlaceCategory.WORKSHOP, GeoPoint(43.37, -5.85), openingHours = "Mo-Fr 09:00-18:00") + var requested: GeoPoint? = null + service.routingEngineFactory = { object : RoutingEngine { + override suspend fun calculateRoute(origin: GeoPoint, destination: GeoPoint, options: RouteOptions): RouteResult { + requested = destination + kotlinx.coroutines.delay(50) + return RouteResult(listOf(origin, destination), emptyList(), 1000, 120) + } + override suspend fun recalculateRoute(origin: GeoPoint, previousRoute: RouteResult, options: RouteOptions) = previousRoute + } } + service.mapRenderOverride = { _, _ -> TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) } + fun field(name: String) = MainActivity::class.java.getDeclaredField(name).apply { isAccessible = true } + try { + field("service").set(activity, service) + MainActivity::class.java.getDeclaredMethod("observeService").apply { isAccessible = true }.invoke(activity) + (field("origin").get(activity) as Spinner).setSelection(1) + MainActivity::class.java.getDeclaredMethod("showPlaceDetails", OfflinePlace::class.java).apply { isAccessible = true }.invoke(activity, place) + val dialog = org.robolectric.shadows.ShadowAlertDialog.getLatestAlertDialog() + assertNull(requested) + dialog.getButton(android.content.DialogInterface.BUTTON_POSITIVE).performClick() + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(500)) + assertEquals(place.position, requested) + assertEquals(place.position, field("destination").get(activity)) + assertEquals(place.name, (field("searchQuery").get(activity) as EditText).text.toString()) + assertTrue(service.routeInfo.value.contains("Vista previa")) + assertFalse(service.hasActiveGuidance()) + val sheet = org.robolectric.shadows.ShadowAlertDialog.getLatestAlertDialog() + assertTrue(sheet.isShowing) + fun children(view: View): List = listOf(view) + if (view is ViewGroup) (0 until view.childCount).flatMap { children(view.getChildAt(it)) } else emptyList() + val start = children(sheet.window!!.decorView).filterIsInstance