diff --git a/Apps/Maps/CHANGELOG.md b/Apps/Maps/CHANGELOG.md index c8c7ab98..90979298 100644 --- a/Apps/Maps/CHANGELOG.md +++ b/Apps/Maps/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## 0.10.1 (in work) +## 0.11.0 (in work) **Downloaded maps** - Maps with the same name (for example several areas named "Slovakia") are one row of the list, with their size @@ -32,9 +32,62 @@ - Queries asked for in a region's menu also start at least 10 s after the last one. - A tile that comes on screen from the cache (drawn earlier around the screen) looks for its trails too. +**LVGL** +- The map is an image in an LVGL window below the statusbar, and LVGL keeps running; keys and the trackball are still + read by the map, touch comes through LVGL (all fingers, for pinch and turn). Needs Tactility with + `lvgl_pointer_get_touches`. The native output, which stopped LVGL and drew straight to the panel, is gone, and so are + the Display output setting and the main menu the map drew itself. +- The app task has a 12 KB stack (was the default 8 KB): building the LVGL menu overflowed it. +- The menu and its pages are Tactility's own widgets, one at a time over the map: the main menu is a tile + grid under a toolbar (< back, an X at its right to exit; a running download is the title, "Update 79 %", with a + download button for its card, and a navigation button holds the route's actions, so the grid stays one page of + nine; a paused recording shows the pause sign), the smaller menus (Download, Track, a row's actions) and the pages + Maps, Settings, Waypoints, GPX files, Tracks and the region catalog are lists, About is scrolling text. R renames and + Delete or X deletes on a row, as before. LVGL reads the keys, the trackball and touch while one is shown; toasts + show over it. Confirm and name dialogs, the download card and the buttons over the map are still drawn by the map + (a page steps aside while a dialog is open). + +**Screen density** +- The map follows the display's dpi (Tactility's `display.dpi`): the T-Deck's 143 dpi is its own size, a denser + screen magnifies it in quarter steps up to 3x (2x on a 294 dpi Tab5). Tiles are still drawn at 256 pixels and shown + magnified, so a dense screen shows the same area and detail at the same physical size, and draws a quarter of the + tiles (faster frames, a smaller tile cache). Label fonts are made at the magnified size (22, 28 and 36 px at 2x), + POI icons are resampled once, and the spacing between labels, the position marker, pins, route and track lines, the + compass, the cursor, the scale bar and the panels' padding and touch sizes grow with it. A magnified view that is + not a whole multiple is drawn bilinear once it stands still, like a turned one. +- Settings → Render scale (ESP32-P4 and ESP32-S31, which have a PPA): Auto (default), 100 %, 75 % or 50 %, applied when Maps starts + again. Auto is 50 % when the map's shorter side is 720 px or more, 75 % from 480 px, else 100 %. + The map is drawn into a smaller frame (602 x 360 at 50 % on a 1204 x 720 window) and the PPA scales it up into the + LVGL image, so a quarter of the pixels are drawn at 50 %. The frame counts as a screen of lower density (the map's + magnification drops with it), touches are mapped into it, and its text takes the label fonts made for that density + instead of the system's (which are sized for the screen and came out twice as large). 75 % is 21/16 (the PPA scales + in sixteenths). Without a PPA the setting shows 100 % and stays there. + +**Closing** +- Closing the app cancels every request that runs, not only a waiting trails query, and a trails answer stops being + read. When closing takes 1 s or more, the log says which part took how long ("Closing took ..."). + +**Memory** +- About 1 MB more PSRAM left on the T-Deck (map ready 1.9 → 2.8 MB free, view complete 1.1 → 2.1 MB): + - the tile cache is sized for the screen: every tile a view turned any way can show, the spare slots for + magnified ancestors, and a few around the screen (17 on 320 x 240, was a fixed 20; 35 on 800 x 480, which + the fixed 20 could not even show whole); at most 40 % of the free PSRAM; + - the SD cache's write and encode buffers (256 KB a render lane) exist only while the SD cache is on; + - the trails answer goes into the parser as it arrives instead of being held whole first (it could be up to 6 MB). + Parsing pauses for a tick every 100 ms (a dense browsed block kept a core busy past the task watchdog), and the + tile cache gives room while the lines grow, not only before the answer. +- About 50 KB more internal RAM left (T-Deck, map ready: 64 KB → 115 KB free): the render lanes' stacks (10 KB each) + and the inflaters' state and input buffers are in PSRAM now. Tile rendering takes about as long as before. +- Downloads go through Tactility's HTTP client (`esp_http_client` is no longer in the firmware). It closes the + connection after each request, so every tile is a new TLS handshake for now. + ## 0.9.0 **Map** +- Dense city tiles kept no roads, street names or water: in tiles with their layers in alphabetical order, the house + numbers and POIs (14,000 values in Amsterdam's centre) came first and filled the decoder's table, so the layers + after them were dropped. The POI and house number layers now leave room for the others, and house numbers take at + most half of what is theirs. Prepared tiles of originals from 256 KB that were made before are made again. - Outdoor map style (Settings, Map style): paths in red, tracks in brown and cycleways in blue from zoom 12, unpaved ways lighter, stronger woods and meadows. The tiles of zoom 12 and 13 are prepared again once for it. - Peaks show with their height ("Vysoká 754 m") from zoom 10, by importance. @@ -107,6 +160,9 @@ - The download pill sits under the navigation bar while navigating instead of on it. **Other** +- Arguments `--lat --lon [--zoom <0-19>]` open the map there, with a pin on the place for the + session (`--zoom` also works alone). Tactility's Mesh app uses them for "Show on map" in a contact's details. +- Built for the ESP32-S31 too. - About in sections. The app's version is shown everywhere as in its manifest (it said 0.6.0 and sent 0.2.0 in the User-Agent). - A prepared tile whose label or graph file went missing is prepared again. diff --git a/Apps/Maps/README.md b/Apps/Maps/README.md index 3e3feb2a..5a0f1b32 100644 --- a/Apps/Maps/README.md +++ b/Apps/Maps/README.md @@ -9,7 +9,7 @@ Version 0.5.0, tested on a LilyGO T-Deck (ESP32-S3, 8 MB PSRAM); it also runs on ## Install -Needs Tactility 0.8.0 or newer on an ESP32-S3 or ESP32-P4 board with 8 MB PSRAM, a FAT-formatted SD card, and Wi-Fi +Needs Tactility 0.8.0 or newer on an ESP32-S3, ESP32-P4 or ESP32-S31 board with 8 MB PSRAM, a FAT-formatted SD card, and Wi-Fi for downloading maps. Tested on Tactility 0.8.0-dev (main, November 2026) on a LilyGO T-Deck. 1. Install "Maps" from Tactility's App Hub. Or copy the `.app` file to the SD card, open it in the Files app and @@ -20,7 +20,8 @@ for downloading maps. Tested on Tactility 0.8.0-dev (main, November 2026) on a L ## How it works - Vector tiles (OpenMapTiles schema) are stored one file per tile in `maps////.pbf` on the SD card. -- The map stops LVGL and draws with Tactility's `pixel_buffer` API, like the built-in Terminal app. +- The map draws its frames into an LVGL image below the statusbar, with LVGL running. The menu and its pages are + LVGL widgets over it. - Tiles are inflated and decoded as a stream, never held whole in memory, and drawn with an exact-area anti-aliasing rasteriser. Two render tasks (one per core) fill a PSRAM cache. Rendered tiles can also be cached on the SD card (a setting, off by default). @@ -268,6 +269,17 @@ as small dots. A file is read once and a compact copy (`.gpc`) is kept next to i next time. Files that are not GPX show an error and are skipped. Large tracks were tested on the PC (50,000 points read in about 40 ms there), not yet on the device. +### Opening a place from another app + +Another app can start Maps (`tactility.maps`) with arguments to open the map at a place, marked with a pin: + +``` +--lat 52.3731 --lon 4.8922 --zoom 16 +``` + +Latitude and longitude in decimal degrees, both or neither. `--zoom` (0-19) is optional and also works alone. Without +arguments the map opens where it was left. + ## OpenFreeMap's rules OpenFreeMap is free and needs no key. Its [terms of service](https://openfreemap.org/tos/) for offline downloads diff --git a/Apps/Maps/main/CMakeLists.txt b/Apps/Maps/main/CMakeLists.txt index be906b26..ebfb0a66 100644 --- a/Apps/Maps/main/CMakeLists.txt +++ b/Apps/Maps/main/CMakeLists.txt @@ -3,7 +3,7 @@ include("$ENV{TACTILITY_SDK_PATH}/TactilitySDK.cmake") file(GLOB_RECURSE SOURCE_FILES Source/*.c*) tactility_component_register( SRCS ${SOURCE_FILES} - REQUIRES graphics-module binfont-module location-module http-module esp_http_client esp_rom mbedtls + REQUIRES graphics-module binfont-module location-module http-module esp_rom esp_driver_ppa ) target_compile_options(${COMPONENT_LIB} PRIVATE -O2 -Wno-format-truncation) # The search index must match the PC's byte for byte (M6): no fused multiply-add in its float maths (MSVC on the PC diff --git a/Apps/Maps/main/Source/app/DisplayOutput.cpp b/Apps/Maps/main/Source/app/DisplayOutput.cpp deleted file mode 100644 index 6cc16b25..00000000 --- a/Apps/Maps/main/Source/app/DisplayOutput.cpp +++ /dev/null @@ -1,115 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-or-later -#include "DisplayOutput.h" - -#include "../platform/Platform.h" - -#include -#include - -#include - -namespace maps { - -namespace { - -/** - * Strips are in internal DMA memory. In PSRAM the SPI driver copied every strip into a new internal DMA buffer of the - * same size, which failed while a download used most of the internal RAM, and the map flickered. - */ -constexpr int STRIP_ROWS = 12; - -} // namespace - -DisplayOutput::~DisplayOutput() { - end(); -} - -bool DisplayOutput::begin(Device* displayDevice) { - display = displayDevice; - panelWidth = display_get_resolution_x(display); - panelHeight = display_get_resolution_y(display); - format = display_get_color_format(display); - monochrome = format == DISPLAY_COLOR_FORMAT_MONOCHROME || format == DISPLAY_COLOR_FORMAT_GRAYSCALE8; - fullFrame = format == DISPLAY_COLOR_FORMAT_MONOCHROME || display_has_capability(display, DISPLAY_CAPABILITY_REQUIRES_FULL_FRAME); - - if (display_get_frame_buffer_count(display) == 2) { - void* first = nullptr; - void* second = nullptr; - display_get_frame_buffer(display, 0, &first); - display_get_frame_buffer(display, 1, &second); - if (first != nullptr && second != nullptr) { - hwBuffers[0] = pixel_buffer_wrap(first, format, panelWidth, panelHeight, 0); - hwBuffers[1] = pixel_buffer_wrap(second, format, panelWidth, panelHeight, 0); - } - if (hwBuffers[0] != nullptr && hwBuffers[1] != nullptr) { - logInfo("Display %dx%d format %d, hardware double buffer", panelWidth, panelHeight, format); - return true; - } - pixel_buffer_free(hwBuffers[0]); - pixel_buffer_free(hwBuffers[1]); - hwBuffers[0] = nullptr; - hwBuffers[1] = nullptr; - } - - if (fullFrame) { - frameBuffer = pixel_buffer_create(format, panelWidth, panelHeight); - logInfo("Display %dx%d format %d, full frames", panelWidth, panelHeight, format); - return frameBuffer != nullptr; - } - - const MemoryPolicy stripPolicy = { .required = MEMORY_CAPABILITY_INTERNAL | MEMORY_CAPABILITY_DMA, .desired = 0, .alignment = 64 }; - strips[0] = pixel_buffer_create_with_policy(format, panelWidth, STRIP_ROWS, &stripPolicy); - strips[1] = pixel_buffer_create_with_policy(format, panelWidth, STRIP_ROWS, &stripPolicy); - logInfo("Display %dx%d format %d, strips of %d rows", panelWidth, panelHeight, format, STRIP_ROWS); - return strips[0] != nullptr && strips[1] != nullptr; -} - -void DisplayOutput::end() { - for (auto*& buffer : hwBuffers) { - pixel_buffer_free(buffer); - buffer = nullptr; - } - for (auto*& buffer : strips) { - pixel_buffer_free(buffer); - buffer = nullptr; - } - pixel_buffer_free(frameBuffer); - frameBuffer = nullptr; - display = nullptr; -} - -void DisplayOutput::present(uint16_t* frame, int y, int height) { - if (display == nullptr) { - return; - } - PixelBuffer* source = pixel_buffer_wrap(frame, DISPLAY_COLOR_FORMAT_RGB565, panelWidth, panelHeight, 0); - if (source == nullptr) { - return; - } - const auto conversion = monochrome ? PIXEL_BUFFER_CONVERSION_LUMA_THRESHOLD : PIXEL_BUFFER_CONVERSION_AVERAGE; - - if (hwBuffers[0] != nullptr) { - // The whole frame goes to the back buffer, so it never shows an older frame in the other region - PixelBuffer* back = hwBuffers[backBuffer]; - pixel_buffer_blit(back, 0, 0, source, 0, 0, panelWidth, panelHeight, conversion); - pixel_buffer_msync(back, 0, 0, panelWidth, panelHeight); - display_draw_bitmap(display, 0, 0, panelWidth, panelHeight, pixel_buffer_get_data(back)); - backBuffer = 1 - backBuffer; - } else if (frameBuffer != nullptr) { - pixel_buffer_blit(frameBuffer, 0, y, source, 0, y, panelWidth, height, conversion); - pixel_buffer_msync(frameBuffer, 0, 0, panelWidth, panelHeight); - display_draw_bitmap(display, 0, 0, panelWidth, panelHeight, pixel_buffer_get_data(frameBuffer)); - } else { - for (int row = y; row < y + height; row += STRIP_ROWS) { - const int rows = std::min(STRIP_ROWS, y + height - row); - PixelBuffer* strip = strips[nextStrip]; - nextStrip = 1 - nextStrip; - pixel_buffer_blit(strip, 0, 0, source, 0, row, panelWidth, rows, conversion); - pixel_buffer_msync(strip, 0, 0, panelWidth, rows); - display_draw_bitmap(display, 0, row, panelWidth, row + rows, pixel_buffer_get_data(strip)); - } - } - pixel_buffer_free(source); -} - -} // namespace maps diff --git a/Apps/Maps/main/Source/app/DisplayOutput.h b/Apps/Maps/main/Source/app/DisplayOutput.h deleted file mode 100644 index eddfdef1..00000000 --- a/Apps/Maps/main/Source/app/DisplayOutput.h +++ /dev/null @@ -1,45 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-or-later -#pragma once - -#include -#include - -#include - -struct PixelBuffer; - -namespace maps { - -/** - * Sends an RGB565 frame to the panel in its own colour format. Uses the hardware double buffer when the driver - * has one, a full frame buffer when the panel needs full frames, and otherwise small strips. - */ -class DisplayOutput { -public: - ~DisplayOutput(); - - bool begin(Device* displayDevice); - void end(); - - /** Sends rows y to y + height of a frame of width() x height() RGB565 pixels. */ - void present(uint16_t* frame, int y, int height); - - int width() const { return panelWidth; } - int height() const { return panelHeight; } - bool isMonochrome() const { return monochrome; } - -private: - Device* display = nullptr; - int panelWidth = 0; - int panelHeight = 0; - DisplayColorFormat format = DISPLAY_COLOR_FORMAT_RGB565; - bool monochrome = false; - bool fullFrame = false; - PixelBuffer* hwBuffers[2] = { nullptr, nullptr }; - int backBuffer = 1; - PixelBuffer* frameBuffer = nullptr; - PixelBuffer* strips[2] = { nullptr, nullptr }; - int nextStrip = 0; -}; - -} // namespace maps diff --git a/Apps/Maps/main/Source/app/Downloader.cpp b/Apps/Maps/main/Source/app/Downloader.cpp index 844654b3..4c53ae11 100644 --- a/Apps/Maps/main/Source/app/Downloader.cpp +++ b/Apps/Maps/main/Source/app/Downloader.cpp @@ -5,14 +5,15 @@ #include "../platform/Platform.h" #include "../render/TerrainOverlay.h" #include "../render/Trails.h" +#include "../mvt/ByteInput.h" #include "../mvt/PlaceFinder.h" #include "../tiles/BrowsedMove.h" #include "../tiles/RegionCatalog.h" #include "../tiles/TileJson.h" #include -#include #include +#include #include #include #include @@ -55,13 +56,6 @@ constexpr TickType_t TERRAIN_POLL_TICKS = pdMS_TO_TICKS(500); constexpr uint32_t TRAILS_AFTER_BROWSE_MS = 4000; constexpr uint32_t TRAILS_RETRY_MS = 5 * 60 * 1000; constexpr uint32_t TRAILS_BLOCK_RETRY_MS = 60 * 1000; -/** - * A quiet trails query waits for its answer in steps of this length, looking for browsing in between. It is the - * client's timeout from the start: esp-tls makes it the socket's receive timeout, the only one mbedTLS obeys (with - * TLS 1.3 the server's session tickets make the socket readable, and mbedTLS then blocked in its read until the answer - * came, 30-40 s, 23 Nov). The handshake goes on across such timeouts. - */ -constexpr int TRAILS_STEP_MS = 1000; constexpr uint32_t TRAILS_GAP_MS = 10000; /** Browsed trails are asked for in blocks of this zoom level: 4 z12 tiles, about 20 km across in Central Europe. */ constexpr int TRAIL_BLOCK_ZOOM = 11; @@ -69,6 +63,12 @@ constexpr int TRAIL_BLOCK_ZOOM = 11; constexpr uint32_t BROWSE_FAILED_MS = 30000; /** PSRAM block the trail parsing wants free before it starts (else the map's tile cache gives some). */ constexpr size_t TRAILS_PARSE_BLOCK = 512 * 1024; +/** Parsing a trails answer pauses for a tick this often, so the core's idle task runs (task watchdog). */ +constexpr uint32_t TRAILS_PARSE_SLICE_MS = 100; +/** While a trails answer is parsed, every this many bytes of it the largest free PSRAM block is checked... */ +constexpr size_t TRAILS_MEMORY_CHECK_BYTES = 64 * 1024; +/** ...and the map's tile cache makes room when it is smaller than this (the lines double their arrays as they grow). */ +constexpr size_t TRAILS_PARSE_HEADROOM = 256 * 1024; /** The largest Overpass answer taken: a region's trails with their geometry, compressed. */ constexpr size_t MAX_TRAILS_BYTES = 6 * 1024 * 1024; @@ -81,6 +81,84 @@ bool startNetworkTask(TaskFunction_t function, const char* name, uint32_t stack, return xTaskCreatePinnedToCoreWithCaps(function, name, stack, context, TASK_PRIORITY, task, Downloader::NETWORK_CORE, MALLOC_CAP_SPIRAM) == pdPASS; } +/** + * The answer of an open request, read as it comes: the trails parser reads it straight from the connection, so the + * answer (up to MAX_TRAILS_BYTES) is never held whole. The first bytes are read ahead, so gzip can be told from JSON. + */ +class HttpBodyInput final : public ByteInput { +public: + HttpBodyInput(HttpClient* client, size_t maxBytes) : client(client), maxBytes(maxBytes) {} + + /** Reads the first bytes: whether the answer is gzip. False also for an empty or broken answer (failed() tells). */ + bool startsWithGzip() { + fill(); + return aheadSize >= 2 && ahead[0] == 0x1F && ahead[1] == 0x8B; + } + + int read(uint8_t* buffer, size_t size) override { + if (aheadPosition < aheadSize) { + const size_t count = std::min(size, aheadSize - aheadPosition); + memcpy(buffer, ahead + aheadPosition, count); + aheadPosition += count; + return static_cast(count); + } + if (error || ended) { + return error ? -1 : 0; + } + const int got = http_client_read(client, buffer, size); + return account(got); + } + + /** Back to the first byte while only the bytes read ahead were taken (InflateReader rewinds before it starts). */ + bool rewind() override { + if (total > aheadSize) { + return false; + } + aheadPosition = 0; + return true; + } + + bool failed() const { return error; } + bool cancelled() const { return wasCancelled; } + bool tooLarge() const { return overflow; } + size_t received() const { return total; } + +private: + void fill() { + if (aheadSize == 0 && !error && !ended) { + aheadSize = static_cast(std::max(0, account(http_client_read(client, ahead, sizeof(ahead))))); + } + } + + int account(int got) { + if (got == 0) { + ended = true; + } else if (got < 0) { + error = true; + wasCancelled = http_client_get_failure(client) == HTTP_CLIENT_FAILURE_CANCELLED; + } else { + total += static_cast(got); + if (total > maxBytes) { + error = true; + overflow = true; + return -1; + } + } + return got; + } + + HttpClient* client; + size_t maxBytes; + size_t total = 0; + uint8_t ahead[64] {}; + size_t aheadSize = 0; + size_t aheadPosition = 0; + bool ended = false; + bool error = false; + bool wasCancelled = false; + bool overflow = false; +}; + void endNetworkTask(TaskHandle_t task) { // It signalled before suspending itself, wait until it got there TaskStatus_t status {}; @@ -113,80 +191,45 @@ bool wifiConnected() { /** Larger responses are refused, no real tile comes close. */ constexpr size_t MAX_TILE_BYTES = 4 * 1024 * 1024; -/** - * When the last connection was established (TCP and TLS done), in ms since boot, for the timing log. 32 bits: - * 64-bit atomics are not exported to apps on the ESP32-S3. - */ -std::atomic connectedAtMs = 0; - uint32_t msSince(int64_t startUs, int64_t endUs) { return static_cast((endUs - startUs) / 1000); } -/** TLS connections opened in this app session and the time they took, for the log. */ -std::atomic handshakeCount = 0; -std::atomic handshakeTotalMs = 0; +/** Requests sent in this app session and the time until their answers began, for the log. */ +std::atomic requestCount = 0; +std::atomic requestTotalMs = 0; + +/** Read from the client into the body in pieces of this size, on the stack of the task that downloads. */ +constexpr size_t READ_PIECE_BYTES = 1024; } // namespace std::atomic Downloader::handshakes = 0; -esp_err_t Downloader::onHttpEvent(esp_http_client_event_t* event) { - auto* connection = static_cast(event->user_data); - if (event->event_id == HTTP_EVENT_ON_CONNECTED) { - connectedAtMs = static_cast(esp_timer_get_time() / 1000); - if (connection != nullptr) { - connection->connectMs = connectedAtMs - connection->requestStartMs; - connection->connected = true; - if (connection->owner != nullptr) { - connection->owner->endHandshake(*connection); - } - if (connection->shortReadMs > 0) { - esp_http_client_set_timeout_ms(event->client, connection->shortReadMs); - } - } - } - if (event->event_id == HTTP_EVENT_DISCONNECTED && connection != nullptr) { - connection->connected = false; - } - ChunkedBody* body = connection != nullptr ? connection->body : nullptr; - // Low-zoom tiles are up to about 1.2 MB, kept in 64 KB pieces: late in a session PSRAM has the room, but not in - // one block - if (event->event_id == HTTP_EVENT_ON_DATA && body != nullptr) { - const size_t total = body->size() + static_cast(event->data_len); - if (total > (connection->maxBytes != 0 ? connection->maxBytes : MAX_TILE_BYTES)) { - body->fail(); - } else { - Downloader* owner = connection->owner; - if (!body->failed() && !body->ensure(total) && owner != nullptr && owner->memoryRelief != nullptr) { - // No room even for a piece: the map gives some of its tile cache for it - owner->memoryRelief(owner->memoryReliefContext, ChunkedBody::CHUNK_BYTES); - } - body->putBytes(event->data, static_cast(event->data_len)); - } +const char* Downloader::resultName(HttpResult result) { + switch (result) { + case HttpResult::Ok: + return "ok"; + case HttpResult::NoConnection: + return "no connection"; + case HttpResult::Cancelled: + return "cancelled"; + case HttpResult::Failed: + break; } - return ESP_OK; + return "failed"; } -void* Downloader::createClient(Connection* connection) { - esp_http_client_config_t config = {}; - config.url = TILEJSON_URL; - config.user_agent = USER_AGENT; - config.timeout_ms = HTTP_TIMEOUT_MS; - config.keep_alive_enable = true; - config.cert_pem = ROOT_CERTIFICATES; - config.cert_len = sizeof(ROOT_CERTIFICATES); - config.event_handler = onHttpEvent; - config.user_data = connection; - config.buffer_size = 4096; - esp_http_client_handle_t client = esp_http_client_init(&config); - if (client != nullptr) { - // Tiles are stored as the server compressed them - esp_http_client_set_header(client, "Accept-Encoding", "gzip"); - } - if (connection != nullptr) { - connection->connected = false; +HttpClient* Downloader::createClient(const char* certificates, uint32_t timeoutMs) { + HttpClient* client = http_client_alloc(); + if (client == nullptr) { + return nullptr; } + http_client_set_certificate(client, certificates); + http_client_set_timeout(client, timeoutMs); + http_client_set_header(client, "User-Agent", USER_AGENT); + // Tiles are stored as the server compressed them + http_client_set_header(client, "Accept-Encoding", "gzip"); return client; } @@ -210,31 +253,107 @@ void Downloader::endHandshake(Connection& connection) { } } -esp_err_t Downloader::perform(Connection& connection) { - auto* client = static_cast(connection.client); +Downloader::HttpResult Downloader::openRequest(Connection& connection, const char* method, const char* url, int& status, bool& transferLocked, + const void* body, size_t bodySize) { + auto* client = static_cast(connection.client); + status = 0; // One HTTPS transfer at a time (tiles, browsing, heights): two at once found no internal RAM for the AES buffers // on the T-Deck and both broke off ("esp-aes: Failed to allocate memory"). Not taken in time: go on without it. - const bool transferLocked = xSemaphoreTake(transferLock, pdMS_TO_TICKS(HTTP_TIMEOUT_MS)) == pdTRUE; - const bool wasConnected = connection.connected; - if (!wasConnected) { - beginHandshake(connection); - } - connection.requestStartMs = static_cast(esp_timer_get_time() / 1000); - connection.connectMs = 0; - const esp_err_t result = esp_http_client_perform(client); + transferLocked = xSemaphoreTake(transferLock, pdMS_TO_TICKS(HTTP_TIMEOUT_MS)) == pdTRUE; + setActive(client, true); + if (stopRequested) { + // The app is closing: no new request (one that started is cancelled by stop()) + http_client_cancel(client); + } + // Every request opens its own connection (the client sends "Connection: close") + beginHandshake(connection); + connection.requestStartMs = nowMs(); + const error_t sent = http_client_send(client, method, url, body, bodySize); + connection.connectMs = nowMs() - connection.requestStartMs; endHandshake(connection); + if (sent != ERROR_NONE) { + const HttpClientFailure failure = http_client_get_failure(client); + return failure == HTTP_CLIENT_FAILURE_CANCELLED ? HttpResult::Cancelled : + failure == HTTP_CLIENT_FAILURE_CONNECT || failure == HTTP_CLIENT_FAILURE_CERTIFICATE ? HttpResult::NoConnection : + HttpResult::Failed; + } + status = http_client_get_status_code(client); + return HttpResult::Ok; +} + +void Downloader::setActive(HttpClient* client, bool active) { + xSemaphoreTake(mutex, portMAX_DELAY); + for (HttpClient*& slot : activeClients) { + if (active ? slot == nullptr : slot == client) { + slot = active ? client : nullptr; + break; + } + } + xSemaphoreGive(mutex); +} + +void Downloader::closeRequest(Connection& connection, const char* method, HttpResult result, bool transferLocked) { + setActive(static_cast(connection.client), false); + http_client_close(static_cast(connection.client)); + connection.connected = false; if (transferLocked) { xSemaphoreGive(transferLock); } - if (connection.connectMs > 0) { - const uint32_t count = ++handshakeCount; - const uint32_t total = handshakeTotalMs += connection.connectMs; - logInfo("TLS: [%d] new connection in %u ms (session: %u connections, %u ms)", connection.index, - static_cast(connection.connectMs), static_cast(count), static_cast(total)); + const uint32_t count = ++requestCount; + const uint32_t total = requestTotalMs += connection.connectMs; + if (timing || result != HttpResult::Ok) { + logInfo("HTTP: [%d] %s answer began after %u ms (%s; session: %u requests, %u ms)", connection.index, method, + static_cast(connection.connectMs), resultName(result), static_cast(count), static_cast(total)); + } +} + +Downloader::HttpResult Downloader::perform(Connection& connection, const char* method, const char* url, int& status, const void* body, + size_t bodySize) { + auto* client = static_cast(connection.client); + bool transferLocked = false; + HttpResult result = openRequest(connection, method, url, status, transferLocked, body, bodySize); + if (result == HttpResult::Ok) { + ChunkedBody* answer = connection.body; + const size_t maxBytes = connection.maxBytes != 0 ? connection.maxBytes : MAX_TILE_BYTES; + uint8_t piece[READ_PIECE_BYTES]; + while (true) { + const int read = http_client_read(client, piece, sizeof(piece)); + if (read == 0) { + break; + } + if (read < 0) { + result = http_client_get_failure(client) == HTTP_CLIENT_FAILURE_CANCELLED ? HttpResult::Cancelled : HttpResult::Failed; + break; + } + if (answer == nullptr) { + continue; + } + // Low-zoom tiles are up to about 1.2 MB, kept in 64 KB pieces: late in a session PSRAM has the room, but + // not in one block + const size_t total = answer->size() + static_cast(read); + if (total > maxBytes) { + answer->fail(); + break; + } + if (!answer->failed() && !answer->ensure(total) && memoryRelief != nullptr) { + // No room even for a piece: the map gives some of its tile cache for it + memoryRelief(memoryReliefContext, ChunkedBody::CHUNK_BYTES); + } + answer->putBytes(piece, static_cast(read)); + } } + closeRequest(connection, method, result, transferLocked); return result; } +void Downloader::cancelWaitingQuery(bool onlyQuiet) { + xSemaphoreTake(mutex, portMAX_DELAY); + if (waitingQuery != nullptr && (waitingQueryQuiet || !onlyQuiet)) { + http_client_cancel(waitingQuery); + } + xSemaphoreGive(mutex); +} + void Downloader::takeClient(Connection& connection) { if (connection.client != nullptr) { return; @@ -247,16 +366,15 @@ void Downloader::takeClient(Connection& connection) { connection.connected = true; } xSemaphoreGive(mutex); - if (connection.client != nullptr) { - esp_http_client_set_user_data(static_cast(connection.client), &connection); - } else { - connection.client = createClient(&connection); + if (connection.client == nullptr) { + connection.client = createClient(ROOT_CERTIFICATES, HTTP_TIMEOUT_MS); + connection.connected = false; } } void Downloader::dropClient(Connection& connection) { if (connection.client != nullptr) { - esp_http_client_cleanup(static_cast(connection.client)); + http_client_free(static_cast(connection.client)); connection.client = nullptr; } connection.connected = false; @@ -270,7 +388,6 @@ void Downloader::giveClient(Connection& connection) { dropClient(connection); return; } - esp_http_client_set_user_data(static_cast(connection.client), nullptr); xSemaphoreTake(mutex, portMAX_DELAY); void* surplus = nullptr; if (idleCount < IDLE_CLIENTS) { @@ -280,7 +397,7 @@ void Downloader::giveClient(Connection& connection) { } xSemaphoreGive(mutex); if (surplus != nullptr) { - esp_http_client_cleanup(static_cast(surplus)); + http_client_free(static_cast(surplus)); } connection.client = nullptr; connection.connected = false; @@ -302,7 +419,7 @@ void Downloader::closeIdleClients(uint32_t maxIdleMs) { idleCount = kept; xSemaphoreGive(mutex); for (int i = 0; i < closingCount; i++) { - esp_http_client_cleanup(static_cast(closing[i])); + http_client_free(static_cast(closing[i])); } if (closingCount > 0) { logInfo("TLS: closed %d idle connection(s)", closingCount); @@ -559,9 +676,23 @@ bool Downloader::start(const char* root, TileStore* tileStore, IoTask* ioTask) { } void Downloader::stop() { + if (mutex != nullptr) { + // Every running request fails at its next step (the HTTP client cannot break off a read that waits for the + // server: that one returns when data comes or its timeout passes) + stopRequested = true; + cancelRequested = true; + xSemaphoreTake(mutex, portMAX_DELAY); + for (HttpClient* client : activeClients) { + if (client != nullptr) { + http_client_cancel(client); + } + } + xSemaphoreGive(mutex); + } if (controlTask != nullptr) { stopRequested = true; cancelRequested = true; + cancelWaitingQuery(false); xSemaphoreGive(wake); xSemaphoreTake(stopped, portMAX_DELAY); endNetworkTask(controlTask); @@ -586,6 +717,13 @@ void Downloader::stop() { } } +void Downloader::cancel() { + cancelRequested = true; + if (mutex != nullptr) { + cancelWaitingQuery(false); + } +} + bool Downloader::queue(Job next, const char* region) { xSemaphoreTake(mutex, portMAX_DELAY); job = next; @@ -594,6 +732,7 @@ bool Downloader::queue(Job next, const char* region) { // A running download is paused, it continues from its meta.json later if (busy) { cancelRequested = true; + cancelWaitingQuery(false); } busy = true; xSemaphoreGive(wake); @@ -890,49 +1029,40 @@ void Downloader::controlLoop() { bool Downloader::fetchTileJson(Connection& connection) { if (timing) { // Plain HTTP first: name lookup and TCP without TLS. The HTTPS request after it then finds the name cached. - esp_http_client_config_t config = {}; - config.url = "http://tiles.openfreemap.org/planet"; - config.user_agent = USER_AGENT; - config.timeout_ms = HTTP_TIMEOUT_MS; - config.event_handler = onHttpEvent; - esp_http_client_handle_t plain = esp_http_client_init(&config); + HttpClient* plain = http_client_alloc(); if (plain != nullptr) { + http_client_set_timeout(plain, HTTP_TIMEOUT_MS); + http_client_set_header(plain, "User-Agent", USER_AGENT); const int64_t startUs = esp_timer_get_time(); - connectedAtMs = 0; - const esp_err_t opened = esp_http_client_open(plain, 0); - const int64_t openedUs = esp_timer_get_time(); - const int64_t headers = opened == ESP_OK ? esp_http_client_fetch_headers(plain) : -1; + const error_t opened = http_client_open(plain, "http://tiles.openfreemap.org/planet"); const int64_t headersUs = esp_timer_get_time(); - logInfo("Timing http: start t=%u ms, connected +%u ms (DNS and TCP), open +%u, headers +%u (%d, HTTP %d)", - static_cast(startUs / 1000), connectedAtMs > 0 ? connectedAtMs - static_cast(startUs / 1000) : 0, msSince(startUs, openedUs), - msSince(startUs, headersUs), static_cast(headers), esp_http_client_get_status_code(plain)); - esp_http_client_close(plain); - esp_http_client_cleanup(plain); + logInfo("Timing http: start t=%u ms, headers +%u ms (DNS, TCP and the answer; %s, HTTP %d)", static_cast(startUs / 1000), + msSince(startUs, headersUs), opened == ERROR_NONE ? "ok" : "failed", http_client_get_status_code(plain)); + http_client_free(plain); } } // Through a pooled keep-alive connection, which the tile requests after it then reuse takeClient(connection); - auto* client = static_cast(connection.client); + auto* client = static_cast(connection.client); if (client == nullptr || connection.body == nullptr) { return false; } // The TileJSON is read as plain text - esp_http_client_delete_header(client, "Accept-Encoding"); - esp_http_client_set_url(client, TILEJSON_URL); + http_client_set_header(client, "Accept-Encoding", "identity"); connection.body->clear(); const int64_t startUs = esp_timer_get_time(); - const esp_err_t result = perform(connection); + int status = 0; + const HttpResult result = perform(connection, "GET", TILEJSON_URL, status); const int64_t doneUs = esp_timer_get_time(); - esp_http_client_set_header(client, "Accept-Encoding", "gzip"); - const int status = esp_http_client_get_status_code(client); + http_client_set_header(client, "Accept-Encoding", "gzip"); ChunkedBody& text = *connection.body; bool ok = false; - if (result != ESP_OK || status != 200 || text.failed()) { - logError("TileJSON request failed: %s, HTTP %d", esp_err_to_name(result), status); + if (result != HttpResult::Ok || status != 200 || text.failed()) { + logError("TileJSON request failed: %s, HTTP %d", resultName(result), status); dropClient(connection); } else { if (timing) { - logInfo("Timing https: start t=%u ms, connect %u ms (DNS, TCP, TLS), whole request %u ms (%u bytes)", + logInfo("Timing https: start t=%u ms, answer began after %u ms (DNS, TCP, TLS), whole request %u ms (%u bytes)", static_cast(startUs / 1000), static_cast(connection.connectMs), msSince(startUs, doneUs), static_cast(text.size())); } @@ -1033,16 +1163,13 @@ bool Downloader::downloadTile(Connection& connection, const char* region, const return false; } connection.body->clear(); - auto* client = static_cast(connection.client); - esp_http_client_set_url(client, url); - const esp_err_t result = perform(connection); - status = esp_http_client_get_status_code(client); + const HttpResult result = perform(connection, "GET", url, status); const size_t size = connection.body->size(); - if (result != ESP_OK || connection.body->failed() || size > MAX_TILE_BYTES || (status != 200 && status != 204 && status != 404)) { + if (result != HttpResult::Ok || connection.body->failed() || size > MAX_TILE_BYTES || (status != 200 && status != 204 && status != 404)) { if (connection.body->failed()) { logError("Tile %d/%d/%d: no memory for %u bytes", tile.z, tile.x, tile.y, static_cast(size)); } else if (!waitForIdle) { - logError("Tile %d/%d/%d: %s after %u bytes", tile.z, tile.x, tile.y, esp_err_to_name(result), static_cast(size)); + logError("Tile %d/%d/%d: %s after %u bytes", tile.z, tile.x, tile.y, resultName(result), static_cast(size)); } connection.body->trim(); return false; @@ -1249,7 +1376,6 @@ void Downloader::runDownload() { connections[0].owner = this; connections[0].index = 0; connections[0].body = &bodies[0]; - connections[0].shortReadMs = 0; const bool tileJson = ensureTileJson(connections[0]); giveClient(connections[0]); bodies[0].release(); @@ -1578,72 +1704,136 @@ bool Downloader::runTrailsArea(const char* regionName, const BoundingBox& box, b logMemory("trails start"); const uint32_t start = nowMs(); Connection& connection = connections[0]; - connection = { this, 0, nullptr, &bodies[0], 0, nullptr, "" }; - connection.maxBytes = MAX_TRAILS_BYTES; - // The server takes 30-40 s to answer even a small box (23 Nov), all that time one HTTPS transfer: a quiet query - // reads in short steps (TRAILS_STEP_MS) and gives the connection to browsing the moment a tile is wanted - connection.shortReadMs = quiet ? TRAILS_STEP_MS : 0; - esp_http_client_config_t config = {}; - config.url = OVERPASS_URL; - config.user_agent = USER_AGENT; - config.timeout_ms = quiet ? TRAILS_STEP_MS : OVERPASS_TIMEOUT_MS; - config.method = HTTP_METHOD_POST; - config.cert_pem = ROOT_CERTIFICATES; - config.cert_len = sizeof(ROOT_CERTIFICATES); - config.event_handler = onHttpEvent; - config.user_data = &connection; - config.buffer_size = 4096; - connection.client = esp_http_client_init(&config); + // No body: the answer goes into the parser as it comes (HttpBodyInput), it is never held whole + connection = { this, 0, nullptr, nullptr, 0, nullptr, "" }; + // The parser and the tiler first: the tiler grows to a few hundred KB (two of them at once while an array doubles), + // the map's tile cache makes room when PSRAM has no such block (a browsed block failed on 23 Nov with 250 KB the + // largest) + if (memoryRelief != nullptr && heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) < TRAILS_PARSE_BLOCK) { + memoryRelief(memoryReliefContext, TRAILS_PARSE_BLOCK); + } + void* tilerPlace = largeAlloc(sizeof(TrailTiler)); + void* parserPlace = largeAlloc(sizeof(TrailParser)); + void* inflaterPlace = largeAlloc(sizeof(InflateReader)); + auto* piece = static_cast(largeAlloc(4096)); + TrailTiler* tiler = tilerPlace != nullptr ? new (tilerPlace) TrailTiler() : nullptr; + TrailParser* parser = parserPlace != nullptr ? new (parserPlace) TrailParser() : nullptr; + InflateReader* inflater = inflaterPlace != nullptr ? new (inflaterPlace) InflateReader() : nullptr; + const bool ready = tiler != nullptr && parser != nullptr && inflater != nullptr && piece != nullptr && inflater->init(); + // The server takes 30-40 s to answer even a small box (23 Nov), all that time one HTTPS transfer: a new browsed tile + // cancels a quiet query (cancelWaitingQuery), so the connection goes to browsing at once + connection.client = ready ? createClient(ROOT_CERTIFICATES, OVERPASS_TIMEOUT_MS) : nullptr; bool fetched = false; + bool parsed = false; bool noTls = false; + bool tooLarge = false; int status = 0; + size_t received = 0; if (connection.client != nullptr) { - auto* client = static_cast(connection.client); - esp_http_client_set_header(client, "Content-Type", "application/x-www-form-urlencoded"); - esp_http_client_set_header(client, "Accept-Encoding", "gzip"); - esp_http_client_set_post_field(client, post, static_cast(strlen(post))); + auto* client = static_cast(connection.client); + http_client_set_header(client, "Content-Type", "application/x-www-form-urlencoded"); + xSemaphoreTake(mutex, portMAX_DELAY); + waitingQuery = client; + waitingQueryQuiet = quiet; + xSemaphoreGive(mutex); // One query at a time; when the server is busy (429, 504) it is asked again after 30 s, twice at most. Quiet // runs ask once: the next idle-time try comes TRAILS_RETRY_MS later. const int attempts = quiet ? 1 : 3; for (int attempt = 1; attempt <= attempts && !fetched && !cancelRequested && !stopRequested; attempt++) { - connection.body->clear(); const uint32_t asked = nowMs(); - esp_err_t result = ESP_FAIL; - int steps = 0; - while ((result = perform(connection)) == ESP_ERR_HTTP_EAGAIN) { - steps++; - if (quiet && (browsing || browseCount > 0)) { - trailsYielded = true; - break; + bool transferLocked = false; + HttpResult result = openRequest(connection, "POST", OVERPASS_URL, status, transferLocked, post, strlen(post)); + bool cancelled = result == HttpResult::Cancelled; + if (result == HttpResult::Ok && status == 200) { + // Read and parsed as it comes, gzip or plain JSON; the lines collected per z12 tile + if (!quiet) { + setStatus(State::Downloading, "Receiving the trails"); } - if (cancelRequested || stopRequested || nowMs() - asked >= static_cast(OVERPASS_TIMEOUT_MS)) { - break; + HttpBodyInput input(client, MAX_TRAILS_BYTES); + bool ok = tiler->begin(box) && parser->begin(tiler); + const bool gzip = ok && input.startsWithGzip(); + if (gzip) { + ok = inflater->begin(&input); + } + uint32_t lastPause = nowMs(); + size_t sinceCheck = 0; + while (ok) { + const int got = gzip ? static_cast(inflater->read(piece, 4096)) : input.read(piece, 4096); + if (got <= 0) { + break; + } + ok = parser->feed(piece, static_cast(got)) && !stopRequested && !cancelRequested; + // A large answer arrives faster than it parses: inflating and parsing would hold this core for + // seconds (the task watchdog saw IDLE1 starve, 5 Dec), so the core's other tasks get a tick + if (nowMs() - lastPause >= TRAILS_PARSE_SLICE_MS) { + vTaskDelay(1); + lastPause = nowMs(); + } + // The lines grow to several hundred KB in a dense area (531 KB for a browsed block, 5 Dec): the map + // gives tile cache slots while there is room left, not only once before the answer + sinceCheck += static_cast(got); + if (sinceCheck >= TRAILS_MEMORY_CHECK_BYTES && memoryRelief != nullptr) { + sinceCheck = 0; + if (heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) < TRAILS_PARSE_HEADROOM) { + memoryRelief(memoryReliefContext, TRAILS_PARSE_HEADROOM); + } + } + } + received = input.received(); + cancelled = input.cancelled(); + tooLarge = input.tooLarge(); + fetched = ok && !input.failed(); + const bool finished = fetched && parser->finish(); + parsed = finished && !tiler->failed(); + if (!input.failed() && !parsed) { + // The answer came whole but did not parse, or there was no memory for its lines: asking again + // would end the same way + fetched = true; + } + logInfo("Trails for %s: %d routes, %d lines, %d points, %d tiles, %u KB held%s", regionName, parser->routeCount(), + parser->lineCount(), parser->pointCount(), tiler->tileCount(), static_cast(tiler->memoryBytes() / 1024), + parsed ? "" : (tiler->failed() ? " - no memory for the lines" : (input.failed() ? " - the answer broke off" : " - the answer did not parse"))); + if (!parsed) { + logMemory("trails parse failed"); + } + if (input.failed()) { + result = cancelled ? HttpResult::Cancelled : HttpResult::Failed; } } - if (quiet) { - logInfo("Trails for %s: %d waiting steps, %s", regionName, steps, esp_err_to_name(result)); - } - if (trailsYielded) { + closeRequest(connection, "POST", result, transferLocked); + if (cancelled && quiet && (browsing || browseCount > 0)) { + trailsYielded = true; logInfo("Trails for %s: gave way to browsing after %u ms", regionName, static_cast(nowMs() - asked)); break; } - status = esp_http_client_get_status_code(client); - fetched = result == ESP_OK && status == 200 && !connection.body->failed(); - if (!fetched && result == ESP_ERR_HTTP_CONNECT && !connection.connected) { + if (result == HttpResult::NoConnection) { // No secure connection at all (the firmware's TLS): trying again would only fail again noTls = true; logError("Trails: no TLS connection to %s (it needs TLS 1.3)", OVERPASS_URL); break; } if (!fetched) { - logError("Trails for %s: HTTP %d (%s), attempt %d%s", regionName, status, esp_err_to_name(result), attempt, - connection.body->failed() ? ", answer too large" : ""); + // An answer with another status (502: the server is busy) is no transfer failure: only the status then + if (result == HttpResult::Ok) { + logError("Trails for %s: HTTP %d, attempt %d%s", regionName, status, attempt, tooLarge ? ", answer too large" : ""); + } else { + logError("Trails for %s: HTTP %d (%s), attempt %d%s", regionName, status, resultName(result), attempt, + tooLarge ? ", answer too large" : ""); + } + if (tooLarge) { + break; + } const uint32_t waitMs = overpassBusy(status) ? OVERPASS_BUSY_WAIT_MS : 5000; for (uint32_t waited = 0; attempt < attempts && waited < waitMs && !cancelRequested && !stopRequested; waited += 100) { vTaskDelay(pdMS_TO_TICKS(100)); } } } + xSemaphoreTake(mutex, portMAX_DELAY); + waitingQuery = nullptr; + xSemaphoreGive(mutex); + } else if (!ready) { + logError("Trails for %s: no memory for the parser", regionName); } trailsStatus = status; if (noTls) { @@ -1652,25 +1842,8 @@ bool Downloader::runTrailsArea(const char* regionName, const BoundingBox& box, b largeFree(post); dropClient(connection); trailsQueryMs = nowMs(); - // The short read steps are this query's only: downloads and updates use connections[0] next - connection.shortReadMs = 0; - const size_t received = connection.body->size(); logInfo("Trails for %s: %u bytes in %u ms (HTTP %d)", regionName, static_cast(received), static_cast(nowMs() - start), status); - // The answer, gzip or plain JSON, read in pieces into the parser; the lines collected per z12 tile. The tiler grows - // to a few hundred KB (two of them at once while an array doubles): the map's tile cache makes room first when - // PSRAM has no such block (a browsed block failed on 23 Nov with 250 KB the largest) - if (fetched && memoryRelief != nullptr && heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) < TRAILS_PARSE_BLOCK) { - memoryRelief(memoryReliefContext, TRAILS_PARSE_BLOCK); - } - void* tilerPlace = largeAlloc(sizeof(TrailTiler)); - void* parserPlace = largeAlloc(sizeof(TrailParser)); - void* inflaterPlace = largeAlloc(sizeof(InflateReader)); - auto* piece = static_cast(largeAlloc(4096)); - TrailTiler* tiler = tilerPlace != nullptr ? new (tilerPlace) TrailTiler() : nullptr; - TrailParser* parser = parserPlace != nullptr ? new (parserPlace) TrailParser() : nullptr; - InflateReader* inflater = inflaterPlace != nullptr ? new (inflaterPlace) InflateReader() : nullptr; - bool ok = fetched && tiler != nullptr && parser != nullptr && inflater != nullptr && piece != nullptr && tiler->begin(box) && - parser->begin(tiler); + bool ok = fetched && parsed; int stored = 0; int withTrails = 0; if (ok) { @@ -1681,36 +1854,6 @@ bool Downloader::runTrailsArea(const char* regionName, const BoundingBox& box, b current.done = 1; current.bytes = received; xSemaphoreGive(mutex); - ChunkedInput input(*connection.body); - const bool gzip = received >= 2 && connection.body->chunk(0)[0] == 0x1F && connection.body->chunk(0)[1] == 0x8B; - if (gzip) { - ok = inflater->init() && inflater->begin(&input); - while (ok) { - const size_t got = inflater->read(piece, 4096); - if (got == 0) { - break; - } - ok = parser->feed(piece, got); - } - } else { - while (ok) { - const int got = input.read(piece, 4096); - if (got <= 0) { - break; - } - ok = parser->feed(piece, static_cast(got)); - } - } - const bool fed = ok; - const bool finished = fed && parser->finish(); - ok = finished && !tiler->failed(); - logInfo("Trails for %s: %d routes, %d lines, %d points, %d tiles, %u KB held%s", regionName, parser->routeCount(), parser->lineCount(), - parser->pointCount(), tiler->tileCount(), static_cast(tiler->memoryBytes() / 1024), - ok ? "" : (tiler->failed() ? " - no memory for the lines" : (!fed ? " - the answer did not read" : " - the answer ended early"))); - if (!ok) { - logMemory("trails parse failed"); - } - connection.body->trim(); GrowArray file; for (int i = 0; ok && i < tiler->tileCount() && !cancelRequested && !stopRequested; i++) { file.clear(); @@ -1869,17 +2012,7 @@ bool Downloader::runTerrainTiles(const char* regionName, TileKey* tiles, int lis // Its own client: the pooled ones belong to OpenFreeMap and trust other roots Connection& connection = connections[0]; connection = { this, 0, nullptr, &bodies[0], 0, nullptr, "" }; - esp_http_client_config_t config = {}; - config.url = "https://s3.amazonaws.com/elevation-tiles-prod/"; - config.user_agent = USER_AGENT; - config.timeout_ms = HTTP_TIMEOUT_MS; - config.keep_alive_enable = true; - config.cert_pem = TERRAIN_ROOT_CERTIFICATES; - config.cert_len = sizeof(TERRAIN_ROOT_CERTIFICATES); - config.event_handler = onHttpEvent; - config.user_data = &connection; - config.buffer_size = 4096; - connection.client = esp_http_client_init(&config); + connection.client = createClient(TERRAIN_ROOT_CERTIFICATES, HTTP_TIMEOUT_MS); auto* file = static_cast(largeAlloc(TERRAIN_FILE_BYTES)); auto* rows = static_cast(largeAlloc(2048)); void* inflaterPlace = largeAlloc(sizeof(InflateReader)); @@ -1928,21 +2061,19 @@ bool Downloader::runTerrainTiles(const char* regionName, TileKey* tiles, int lis } // In pieces (HTTP ranges): at 25 KB/s a whole file took 4-5 s, and tiles for the screen waited for it (one // transfer at a time). Between pieces a quiet run gives way to browsing, so they wait at most one piece. - auto* client = static_cast(connection.client); + auto* client = static_cast(connection.client); connection.body->clear(); - esp_http_client_set_url(client, url); - esp_err_t result = ESP_FAIL; + HttpResult result = HttpResult::Failed; bool pieceYielded = false; fetched = false; for (size_t from = 0;; from += TERRAIN_PIECE_BYTES) { char range[48]; snprintf(range, sizeof(range), "bytes=%u-%u", static_cast(from), static_cast(from + TERRAIN_PIECE_BYTES - 1)); - esp_http_client_set_header(client, "Range", range); + http_client_set_header(client, "Range", range); const size_t before = connection.body->size(); - result = perform(connection); - status = esp_http_client_get_status_code(client); + result = perform(connection, "GET", url, status); const size_t got = connection.body->size() - before; - if (result != ESP_OK || connection.body->failed() || connection.body->size() > MAX_TERRAIN_BYTES) { + if (result != HttpResult::Ok || connection.body->failed() || connection.body->size() > MAX_TERRAIN_BYTES) { break; } if (status == 200 || status == 404) { @@ -1969,7 +2100,6 @@ bool Downloader::runTerrainTiles(const char* regionName, TileKey* tiles, int lis break; } } - esp_http_client_delete_header(client, "Range"); if (pieceYielded) { terrainYielded = true; break; @@ -2177,6 +2307,10 @@ void Downloader::browse(const TileKey* tiles, int count) { browseTotal++; added = true; } + if (added && waitingQuery != nullptr && waitingQueryQuiet) { + // An idle-time trails query gives the connection to browsing (cancelWaitingQuery, under the mutex already held) + http_client_cancel(waitingQuery); + } xSemaphoreGive(mutex); if (added) { xSemaphoreGive(browseWake); @@ -2947,7 +3081,6 @@ void Downloader::runUpdate(bool manual) { connection.body = &bodies[0]; connection.received = 0; connection.lastFolder[0] = '\0'; - connection.shortReadMs = 0; if (!ensureTileJson(connection)) { giveClient(connection); setStatus(State::Failed, "OpenFreeMap is not reachable"); diff --git a/Apps/Maps/main/Source/app/Downloader.h b/Apps/Maps/main/Source/app/Downloader.h index 1c491480..e0b867fc 100644 --- a/Apps/Maps/main/Source/app/Downloader.h +++ b/Apps/Maps/main/Source/app/Downloader.h @@ -9,7 +9,6 @@ #include "../tiles/RegionMeta.h" #include "../tiles/TileStore.h" -#include #include #include #include @@ -17,6 +16,8 @@ #include #include +struct HttpClient; + namespace maps { /** @@ -138,7 +139,7 @@ class Downloader { memoryRelief = relief; memoryReliefContext = context; } - void cancel() { cancelRequested = true; } + void cancel(); Status status(); bool isBusy() const { return busy.load(); } @@ -210,11 +211,6 @@ class Downloader { uint32_t connectMs = 0; /** The largest answer taken (0: MAX_TILE_BYTES). */ size_t maxBytes = 0; - /** - * Once connected, reads wait at most this long (0: the client's timeout): perform() then returns - * ESP_ERR_HTTP_EAGAIN and goes on where it stopped when called again, so a long wait can give way. - */ - int shortReadMs = 0; /** Whether the client has an open connection the next request can reuse. */ bool connected = false; /** Whether this connection holds the handshake lock. */ @@ -242,11 +238,33 @@ class Downloader { uint32_t sinceMs; }; - static esp_err_t onHttpEvent(esp_http_client_event_t* event); - /** A keep-alive HTTPS client for OpenFreeMap whose events go to connection. */ - static void* createClient(Connection* connection); - /** Runs the request set up on connection's client, and logs the TLS connection if it had to open one. */ - esp_err_t perform(Connection& connection); + /** How a request went. */ + enum class HttpResult : uint8_t { + Ok, + /** No connection: name lookup, TCP or TLS failed. */ + NoConnection, + Failed, + /** Cancelled from another task (cancelWaitingQuery). */ + Cancelled + }; + static const char* resultName(HttpResult result); + /** An HTTPS client that trusts certificates (PEM, one or more), with the app's user agent and gzip accepted. */ + static HttpClient* createClient(const char* certificates, uint32_t timeoutMs); + /** + * Sends a request on connection's client and receives the answer into connection.body, up to connection.maxBytes. + * status: the HTTP status, 0 without an answer. + */ + HttpResult perform(Connection& connection, const char* method, const char* url, int& status, const void* body = nullptr, size_t bodySize = 0); + /** + * The parts of perform(), for an answer read as it comes (trails): sends the request and reads the status, then + * the answer is read from the client (HttpBodyInput), then closeRequest() ends it. closeRequest() is always called, + * also when openRequest() failed. transferLocked tells closeRequest() to let go of the transfer lock. + */ + HttpResult openRequest(Connection& connection, const char* method, const char* url, int& status, bool& transferLocked, + const void* body = nullptr, size_t bodySize = 0); + void closeRequest(Connection& connection, const char* method, HttpResult result, bool transferLocked); + /** Cancels the trails query that is waiting for its answer, when there is one; onlyQuiet: an idle-time one only. */ + void cancelWaitingQuery(bool onlyQuiet); void beginHandshake(Connection& connection); void endHandshake(Connection& connection); /** Gives connection an open pooled client, or a new one. */ @@ -444,6 +462,13 @@ class Downloader { int idleCount = 0; SemaphoreHandle_t handshakeLock = nullptr; static std::atomic handshakes; + /** The trails query waiting for its answer (under mutex), so that browsing and cancelling can break it off. */ + HttpClient* waitingQuery = nullptr; + bool waitingQueryQuiet = false; + /** The clients with a request running (openRequest to closeRequest), cancelled by stop(). Under mutex. */ + static constexpr int MAX_ACTIVE = 8; + HttpClient* activeClients[MAX_ACTIVE] {}; + void setActive(HttpClient* client, bool active); std::atomic updatesAllowed = false; BoundingBox viewBox {}; bool viewKnown = false; diff --git a/Apps/Maps/main/Source/app/FrameOutput.h b/Apps/Maps/main/Source/app/FrameOutput.h new file mode 100644 index 00000000..74da02c5 --- /dev/null +++ b/Apps/Maps/main/Source/app/FrameOutput.h @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once + +#include + +namespace maps { + +class LvglMenu; + +/** + * Where the map's frames go: into an LVGL image (LvglOutput). The output owns the frame buffers: the map draws a whole frame of width() x height() RGB565 pixels + * into drawBuffer() and hands it to present(). + */ +class FrameOutput { +public: + virtual ~FrameOutput() = default; + + virtual void end() = 0; + + /** The buffer to draw the next frame into. */ + virtual uint16_t* drawBuffer() = 0; + /** The last frame that was presented, for screenshots. */ + virtual const uint16_t* shownBuffer() const = 0; + /** + * Shows the frame in drawBuffer(). Afterwards drawBuffer() can be another buffer: every frame is drawn whole, + * so the map never reads back what it drew before. + */ + virtual void present() = 0; + + virtual int width() const = 0; + virtual int height() const = 0; + virtual bool isMonochrome() const = 0; + /** For the log and the About page. */ + virtual const char* name() const = 0; + /** The menus as LVGL widgets, when the output has them; otherwise the map draws its own. */ + virtual LvglMenu* lvglMenu() { return nullptr; } + /** Dots per inch of the frame (lower than the display's when it is drawn smaller and scaled up), 0 when unknown. */ + virtual int dpi() const { return 0; } + /** Whether the frame can be drawn below the screen's resolution and scaled up (Settings::renderScale). */ + virtual bool canScale() const { return false; } + /** The render scale in percent when Settings::renderScale is 0 (the default). */ + virtual int defaultRenderPercent() const { return 100; } + /** Whether this frame is drawn smaller than the screen and scaled up: the system's fonts are then too large for it. */ + virtual bool isScaledUp() const { return false; } +}; + +} // namespace maps diff --git a/Apps/Maps/main/Source/app/Input.cpp b/Apps/Maps/main/Source/app/Input.cpp index 03aa4acf..8427bb6f 100644 --- a/Apps/Maps/main/Source/app/Input.cpp +++ b/Apps/Maps/main/Source/app/Input.cpp @@ -104,10 +104,12 @@ void Input::rescan() { } } -void Input::refreshIfDue() { +bool Input::refreshIfDue() { if (nowMs() - lastScanMs > RESCAN_INTERVAL_MS) { rescan(); + return true; } + return false; } bool Input::takeDevicesChanged() { diff --git a/Apps/Maps/main/Source/app/Input.h b/Apps/Maps/main/Source/app/Input.h index 91bad544..504e3857 100644 --- a/Apps/Maps/main/Source/app/Input.h +++ b/Apps/Maps/main/Source/app/Input.h @@ -30,16 +30,18 @@ class Input { public: static constexpr int MAX_DEVICES = 4; - ~Input(); + virtual ~Input(); - void begin(); - void end(); + virtual void begin(); + virtual void end(); /** Returns the number of key events written to events. */ - int readKeys(KeyEvent* events, int maxEvents); + virtual int readKeys(KeyEvent* events, int maxEvents); /** Sums the movement of all mice since the last call. Returns true while a mouse button is held. */ bool readMouse(int32_t& dx, int32_t& dy); - bool readTouch(TouchState& state); + virtual bool readTouch(TouchState& state); + /** LVGL widgets over the map (a menu) take the keys and pointers while active, the map reads none. */ + virtual void setUiActive(bool) {} bool hasTouch() const { return touch != nullptr; } /** * A keyboard that types text, so key hints make sense. Keys are read from every keyboard device, but buttons @@ -55,9 +57,12 @@ class Input { /** True once after a keyboard or mouse came or went, so the overlay can adapt. */ bool takeDevicesChanged(); +protected: + /** Takes the devices that came, lets go of the ones that stopped. Returns true when it rescanned. */ + bool refreshIfDue(); + private: void rescan(); - void refreshIfDue(); /** Lets go of devices that stopped. Returns how many. */ static int dropStopped(Device** devices, int& count); diff --git a/Apps/Maps/main/Source/app/LabelFontMaker.cpp b/Apps/Maps/main/Source/app/LabelFontMaker.cpp index 0060b5f6..c8393f8e 100644 --- a/Apps/Maps/main/Source/app/LabelFontMaker.cpp +++ b/Apps/Maps/main/Source/app/LabelFontMaker.cpp @@ -54,8 +54,8 @@ bool writeJob(IoTask& io, void* context) { } // namespace -void LabelFontMaker::cachePath(const char* root, int i, char* out, size_t size) { - snprintf(out, size, "%s/fonts/lbl%d%c.bin", root, EM_SIZES[i], FONT_VERSION); +void LabelFontMaker::cachePath(const char* root, int i, float magnify, char* out, size_t size) { + snprintf(out, size, "%s/fonts/lbl%d%c.bin", root, emSize(i, magnify), FONT_VERSION); } namespace { @@ -79,8 +79,9 @@ bool removeOldJob(IoTask& io, void* context) { } // namespace -void LabelFontMaker::configure(IoTask& ioTask, const char* root, const char* ttf) { +void LabelFontMaker::configure(IoTask& ioTask, const char* root, const char* ttf, float scale) { io = &ioTask; + magnify = scale; snprintf(rootPath, sizeof(rootPath), "%s", root); snprintf(ttfPath, sizeof(ttfPath), "%s", ttf); } @@ -137,28 +138,28 @@ void LabelFontMaker::run() { BinFontGeneratorConfig config {}; config.ttf_data = ttf.bytes(); config.ttf_size = ttf.size(); - config.size = static_cast(EM_SIZES[i]); + config.size = static_cast(emSize(i, magnify)); config.bpp = 4; uint8_t* data = nullptr; size_t size = 0; const error_t error = binfont_generate(&config, &data, &size); if (error != ERROR_NONE || data == nullptr) { - logError("Label font %d px: generator failed with error %d, the map keeps the system font", EM_SIZES[i], static_cast(error)); + logError("Label font %d px: generator failed with error %d, the map keeps the system font", emSize(i, magnify), static_cast(error)); memory_free(data); continue; } const uint32_t generated = nowMs(); char path[200]; - cachePath(rootPath, i, path, sizeof(path)); + cachePath(rootPath, i, magnify, path, sizeof(path)); WriteJob write { folder, path, data, size }; const bool ok = io->run(IoPriority::Background, writeJob, &write); memory_free(data); if (ok) { written = written.load() | (1u << i); - RemoveOldJob old { rootPath, EM_SIZES[i] }; + RemoveOldJob old { rootPath, emSize(i, magnify) }; io->run(IoPriority::Background, removeOldJob, &old); } - logInfo("Label font %d px: %u bytes, generated in %u ms, %s in %u ms", EM_SIZES[i], static_cast(size), + logInfo("Label font %d px: %u bytes, generated in %u ms, %s in %u ms", emSize(i, magnify), static_cast(size), static_cast(generated - fontStart), ok ? "written" : "NOT written", static_cast(nowMs() - generated)); // Gives the render lanes and the UI their turn between two fonts vTaskDelay(pdMS_TO_TICKS(20)); diff --git a/Apps/Maps/main/Source/app/LabelFontMaker.h b/Apps/Maps/main/Source/app/LabelFontMaker.h index 725b2aef..762a117e 100644 --- a/Apps/Maps/main/Source/app/LabelFontMaker.h +++ b/Apps/Maps/main/Source/app/LabelFontMaker.h @@ -31,10 +31,12 @@ class LabelFontMaker { ~LabelFontMaker() { stop(); } - /** The cache file of font i. */ - static void cachePath(const char* root, int i, char* out, size_t size); + /** The em size of font i on a screen that magnifies the map by magnify (MapView::magnify). */ + static int emSize(int i, float magnify) { return static_cast(EM_SIZES[i] * magnify + 0.5f); } + /** The cache file of font i at that magnification. */ + static void cachePath(const char* root, int i, float magnify, char* out, size_t size); /** Whether the cache folder, the ttf and the paths are set up; call before start(). */ - void configure(IoTask& ioTask, const char* root, const char* ttfPath); + void configure(IoTask& ioTask, const char* root, const char* ttfPath, float magnify); /** Starts making the fonts in the mask (bit i for font i); false when the task could not be started. */ bool start(unsigned missingMask); /** True once the task is done, whether or not it succeeded; it never starts again. */ @@ -52,6 +54,7 @@ class LabelFontMaker { IoTask* io = nullptr; char rootPath[160] = ""; char ttfPath[260] = ""; + float magnify = 1.0f; unsigned wanted = 0; TaskHandle_t task = nullptr; std::atomic finished = false; diff --git a/Apps/Maps/main/Source/app/LvglMenu.cpp b/Apps/Maps/main/Source/app/LvglMenu.cpp new file mode 100644 index 00000000..0688a6b7 --- /dev/null +++ b/Apps/Maps/main/Source/app/LvglMenu.cpp @@ -0,0 +1,489 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#include "LvglMenu.h" + +#include "../platform/Platform.h" +#include "../ui/Canvas.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace maps { + +namespace { + +void copyText(char* out, size_t size, const char* text) { + snprintf(out, size, "%s", text != nullptr ? text : ""); +} + +bool isBackKey(uint32_t key) { + return key == LV_KEY_ESC || key == LV_KEY_BACKSPACE; +} + +/** The widgets are built for the app's focus group, as the window manager does for a window's own widgets. */ +class AppGroupScope { +public: + AppGroupScope() : previous(lv_group_get_default()) { lv_group_set_default(lvgl_keyboard_get_app_group()); } + ~AppGroupScope() { lv_group_set_default(previous); } + +private: + lv_group_t* previous; +}; + +} // namespace + +LvglMenu::~LvglMenu() { + hide(); + largeFree(rowText); + rowText = nullptr; + largeFree(text); + text = nullptr; + for (uint8_t*& pixels : iconPixels) { + largeFree(pixels); + pixels = nullptr; + } +} + +void LvglMenu::attach(lv_obj_t* parent) { + root = parent; + panel = nullptr; + grid = nullptr; + textBox = nullptr; + toast = nullptr; + if (shown) { + focusPending = true; + buildLocked(); + } + buildToastLocked(); +} + +void LvglMenu::detach() { + root = nullptr; + panel = nullptr; + grid = nullptr; + textBox = nullptr; + toast = nullptr; + toolbar = nullptr; + for (lv_obj_t*& button : buttonObjects) { + button = nullptr; + } +} + +void LvglMenu::setToast(const char* message) { + const char* wanted = message != nullptr ? message : ""; + if (strcmp(wanted, toastText) == 0) { + return; + } + lvgl_lock(); + copyText(toastText, sizeof(toastText), wanted); + buildToastLocked(); + lvgl_unlock(); +} + +void LvglMenu::buildToastLocked() { + if (toast != nullptr) { + lv_obj_delete(toast); + toast = nullptr; + } + if (root == nullptr || toastText[0] == '\0') { + return; + } + // A pill at the bottom, over the page; it takes no input + toast = lv_label_create(root); + lv_label_set_text(toast, toastText); + lv_obj_set_style_bg_color(toast, lv_color_hex(0x202020), LV_STATE_DEFAULT); + lv_obj_set_style_bg_opa(toast, LV_OPA_90, LV_STATE_DEFAULT); + lv_obj_set_style_text_color(toast, lv_color_white(), LV_STATE_DEFAULT); + lv_obj_set_style_radius(toast, LV_RADIUS_CIRCLE, LV_STATE_DEFAULT); + lv_obj_set_style_pad_hor(toast, 12, LV_STATE_DEFAULT); + lv_obj_set_style_pad_ver(toast, 6, LV_STATE_DEFAULT); + lv_obj_set_clickable(toast, false); + lv_obj_align(toast, LV_ALIGN_BOTTOM_MID, 0, -8); +} + +void LvglMenu::showGrid(const char* text, const LvglMenuTile* items, int count, uint16_t focus, const LvglMenuButton* newButtons, int newButtonCount) { + lvgl_lock(); + const bool update = shown && kind == Kind::Grid && grid != nullptr; + newButtonCount = std::min(newButtonCount, MAX_BUTTONS); + bool sameButtons = newButtonCount == buttonCount; + for (int i = 0; sameButtons && i < newButtonCount; i++) { + sameButtons = newButtons[i].action == buttons[i].action; + } + copyText(title, sizeof(title), text); + tileCount = std::min(count, MAX_TILES); + memcpy(tiles, items, sizeof(LvglMenuTile) * tileCount); + memcpy(buttons, newButtons, sizeof(LvglMenuButton) * newButtonCount); + buttonCount = newButtonCount; + kind = Kind::Grid; + shown = true; + if (update && sameButtons) { + // A download's percentage in the title, location on or off: the selection stays + if (toolbar != nullptr) { + lvgl_toolbar_set_title(toolbar, title); + } + lvgl_tile_grid_request_repopulate(grid, true); + } else { + // A new menu, or a button came or went: built again, on the tile that had the focus + const uint16_t focused = update ? focusedTileLocked() : NO_ACTION; + focusAction = focused != NO_ACTION ? focused : focus; + focusPending = true; + buildLocked(); + } + lvgl_unlock(); +} + +uint16_t LvglMenu::focusedTileLocked() const { + lv_obj_t* focused = lv_group_get_focused(lvgl_keyboard_get_app_group()); + if (grid == nullptr || focused == nullptr) { + return NO_ACTION; + } + const LvglTileGridItem* item = lvgl_tile_grid_get_tile_item(grid, focused); + return item != nullptr ? static_cast(reinterpret_cast(item->user_data)) : NO_ACTION; +} + +void LvglMenu::showList(const char* titleText, const char* const* labels, const char* const* details, int count, int focus) { + if (rowText == nullptr) { + rowText = static_cast(largeAlloc(static_cast(2 * MAX_ROWS) * TEXT_LENGTH)); + if (rowText == nullptr) { + logError("LVGL menu: no memory for the rows"); + return; + } + } + lvgl_lock(); + copyText(title, sizeof(title), titleText); + rowCount = std::min(count, MAX_ROWS); + for (int i = 0; i < rowCount; i++) { + copyText(rowLabel(i), TEXT_LENGTH, labels[i]); + copyText(rowDetail(i), TEXT_LENGTH, details != nullptr ? details[i] : nullptr); + } + focusRow = focus; + kind = Kind::List; + shown = true; + focusPending = true; + buildLocked(); + lvgl_unlock(); +} + +void LvglMenu::showText(const char* titleText, const char* const* paragraphs, int count) { + size_t size = 0; + for (int i = 0; i < count; i++) { + size += strlen(paragraphs[i]) + 1; + } + if (size > textSize) { + largeFree(text); + text = static_cast(largeAlloc(size)); + textSize = text != nullptr ? size : 0; + if (text == nullptr) { + logError("LVGL menu: no memory for the text"); + return; + } + } + lvgl_lock(); + copyText(title, sizeof(title), titleText); + char* at = text; + for (int i = 0; i < count; i++) { + const size_t length = strlen(paragraphs[i]); + memcpy(at, paragraphs[i], length + 1); + at += length + 1; + } + paragraphCount = count; + kind = Kind::Text; + shown = true; + focusPending = true; + buildLocked(); + lvgl_unlock(); +} + +void LvglMenu::hide() { + if (!shown) { + return; + } + lvgl_lock(); + shown = false; + kind = Kind::None; + deleteLocked(); + // Events of a menu that is gone mean nothing anymore + queueCount = 0; + lvgl_unlock(); +} + +bool LvglMenu::takeEvent(LvglMenuEvent& event) { + // Not waiting while LVGL draws (a full screen takes long): an event waits for the next pass + if (queueCount == 0 || !lvgl_try_lock(0)) { + return false; + } + const bool any = queueCount > 0; + if (any) { + event = queue[0]; + queueCount--; + memmove(queue, queue + 1, sizeof(LvglMenuEvent) * queueCount); + } + lvgl_unlock(); + return any; +} + +void LvglMenu::push(LvglMenuEvent::Kind eventKind, uint16_t value, int16_t row) { + if (queueCount < QUEUE_SIZE) { + queue[queueCount++] = { eventKind, value, row }; + } +} + +void LvglMenu::deleteLocked() { + if (panel != nullptr) { + lv_obj_delete(panel); + } + panel = nullptr; + grid = nullptr; + textBox = nullptr; + toolbar = nullptr; + for (lv_obj_t*& button : buttonObjects) { + button = nullptr; + } +} + +void LvglMenu::buildLocked() { + deleteLocked(); + if (root == nullptr || kind == Kind::None) { + return; + } + AppGroupScope scope; + // A plain panel over the map image, in the theme's background + panel = lv_obj_create(root); + lv_obj_set_size(panel, LV_PCT(100), LV_PCT(100)); + lv_obj_set_style_pad_all(panel, 0, LV_STATE_DEFAULT); + lv_obj_set_style_pad_row(panel, 0, LV_STATE_DEFAULT); + lv_obj_set_style_border_width(panel, 0, LV_STATE_DEFAULT); + lv_obj_set_style_radius(panel, 0, LV_STATE_DEFAULT); + lv_obj_set_scrollable(panel, false); + lv_obj_set_flex_flow(panel, LV_FLEX_FLOW_COLUMN); + // The panel is newer than a toast that is shown: the toast goes back on top + if (toast != nullptr) { + lv_obj_move_foreground(toast); + } + + toolbar = lvgl_toolbar_create(panel, title); + lvgl_toolbar_set_nav_action(toolbar, LV_SYMBOL_LEFT, onBack, this); + for (int i = 0; i < MAX_BUTTONS; i++) { + buttonObjects[i] = nullptr; + if (kind == Kind::Grid && i < buttonCount) { + // Toolbar actions are square: an icon, as the toolbar's own back button has + lv_obj_t* button = lvgl_toolbar_add_text_button_action(toolbar, buttons[i].icon, onToolbarButton, this); + lv_obj_t* glyph = lv_obj_get_child(button, 0); + if (glyph != nullptr) { + lv_obj_set_style_text_font(glyph, lvgl_get_shared_icon_default_font(), LV_STATE_DEFAULT); + } + lv_obj_set_user_data(button, reinterpret_cast(static_cast(buttons[i].action))); + lv_obj_add_event_cb(button, onKey, LV_EVENT_KEY, this); + buttonObjects[i] = button; + } + } + + if (kind == Kind::Grid) { + LvglTileGridConfig config {}; + config.style = LVGL_TILE_GRID_STYLE_TILE; + config.icon_color = LVGL_TILE_GRID_ICON_COLOR_DEFAULT; + config.swipe_navigation = true; + config.callbacks.collect = collectTiles; + config.callbacks.on_clicked = onTileClicked; + config.callbacks.on_key = onTileKey; + config.callbacks.user_data = this; + grid = lvgl_tile_grid_create(panel, &config); + if (grid != nullptr && focusPending && focusAction != NO_ACTION) { + char id[8]; + snprintf(id, sizeof(id), "%u", focusAction); + lv_obj_t* tile = lvgl_tile_grid_find_tile(grid, id); + if (tile != nullptr) { + lv_group_focus_obj(tile); + } + } + } else if (kind == Kind::Text) { + buildText(panel); + } else { + lv_obj_t* list = lvgl_list_create(panel); + lv_obj_set_width(list, LV_PCT(100)); + lv_obj_set_flex_grow(list, 1); + lv_obj_t* focused = nullptr; + for (int i = 0; i < rowCount; i++) { + lv_obj_t* button = lvgl_list_add_button(list, nullptr, rowLabel(i)); + lv_obj_set_user_data(button, reinterpret_cast(static_cast(i))); + lv_obj_add_event_cb(button, onRowClicked, LV_EVENT_CLICKED, this); + lv_obj_add_event_cb(button, onKey, LV_EVENT_KEY, this); + if (rowDetail(i)[0] != '\0') { + lv_obj_t* detail = lv_label_create(button); + lv_label_set_text(detail, rowDetail(i)); + lv_obj_set_style_text_color(detail, lv_theme_get_color_secondary(detail), LV_STATE_DEFAULT); + } + if (focused == nullptr || i == focusRow) { + focused = button; + } + } + lvgl_list_hide_last_divider(list); + if (focused != nullptr && focusPending) { + lv_group_focus_obj(focused); + lv_obj_scroll_to_view(focused, LV_ANIM_OFF); + } + } + focusPending = false; +} + +const lv_image_dsc_t* LvglMenu::iconImage(MenuIcon icon) { + const int index = static_cast(icon); + if (icon == MenuIcon::None || index >= ICON_KINDS) { + return nullptr; + } + const int size = static_cast(lvgl_tile_grid_get_tile_icon_size()); + if (size != iconSize) { + // Another theme scale: every icon is drawn again + for (uint8_t*& pixels : iconPixels) { + largeFree(pixels); + pixels = nullptr; + } + iconSize = size; + } + if (iconPixels[index] == nullptr && size > 0) { + const size_t count = static_cast(size) * size; + auto* rgb = static_cast(largeAlloc(count * sizeof(uint16_t))); + auto* alpha = static_cast(largeAlloc(count)); + if (rgb == nullptr || alpha == nullptr) { + largeFree(rgb); + largeFree(alpha); + return nullptr; + } + memset(rgb, 0, count * sizeof(uint16_t)); + Canvas canvas; + canvas.pixels = rgb; + canvas.width = size; + canvas.height = size; + // Drawn white on black, the brightness is the coverage: the tile paints it in its icon colour + drawMenuIcon(canvas, icon, size / 2, size / 2, size, 0xFFFF); + for (size_t i = 0; i < count; i++) { + alpha[i] = static_cast(((rgb[i] >> 5) & 0x3F) * 255 / 63); + } + largeFree(rgb); + iconPixels[index] = alpha; + lv_image_dsc_t& image = icons[index]; + image = {}; + image.header.magic = LV_IMAGE_HEADER_MAGIC; + image.header.cf = LV_COLOR_FORMAT_A8; + image.header.w = static_cast(size); + image.header.h = static_cast(size); + image.header.stride = static_cast(size); + image.data = alpha; + image.data_size = static_cast(count); + } + return iconPixels[index] != nullptr ? &icons[index] : nullptr; +} + +void LvglMenu::collectTiles(lv_obj_t* grid, void* userData) { + auto* self = static_cast(userData); + for (int i = 0; i < self->tileCount; i++) { + const LvglMenuTile& tile = self->tiles[i]; + char id[8]; + snprintf(id, sizeof(id), "%u", tile.action); + LvglTileGridItem item {}; + item.id = id; + item.name = tile.label; + item.highlighted = tile.highlighted; + item.image = self->iconImage(tile.icon); + item.image_recolor = true; + item.user_data = reinterpret_cast(static_cast(tile.action)); + lvgl_tile_grid_add_item(grid, &item); + } +} + +void LvglMenu::onTileClicked(lv_obj_t*, const LvglTileGridItem* item, void* userData) { + auto* self = static_cast(userData); + self->push(LvglMenuEvent::Kind::Chosen, static_cast(reinterpret_cast(item->user_data))); +} + +void LvglMenu::onTileKey(lv_obj_t*, const LvglTileGridItem*, uint32_t key, void* userData) { + if (isBackKey(key)) { + static_cast(userData)->push(LvglMenuEvent::Kind::Back, 0); + } +} + +void LvglMenu::onBack(lv_event_t* event) { + static_cast(lv_event_get_user_data(event))->push(LvglMenuEvent::Kind::Back, 0); +} + +void LvglMenu::onToolbarButton(lv_event_t* event) { + auto* self = static_cast(lv_event_get_user_data(event)); + const void* data = lv_obj_get_user_data(lv_event_get_current_target_obj(event)); + self->push(LvglMenuEvent::Kind::Chosen, static_cast(reinterpret_cast(data))); +} + +void LvglMenu::onRowClicked(lv_event_t* event) { + auto* self = static_cast(lv_event_get_user_data(event)); + const auto row = static_cast(reinterpret_cast(lv_obj_get_user_data(lv_event_get_current_target_obj(event)))); + self->push(LvglMenuEvent::Kind::Chosen, row); +} + +void LvglMenu::onKey(lv_event_t* event) { + auto* self = static_cast(lv_event_get_user_data(event)); + const uint32_t key = lv_event_get_key(event); + if (isBackKey(key)) { + self->push(LvglMenuEvent::Kind::Back, 0); + return; + } + // Keys a page may use on its rows: Delete and X delete, R renames + if (key == LV_KEY_DEL || key == 'x' || key == 'X' || key == 'r' || key == 'R') { + lv_obj_t* target = lv_event_get_current_target_obj(event); + const void* data = lv_obj_get_user_data(target); + const auto row = static_cast(reinterpret_cast(data)); + self->push(LvglMenuEvent::Kind::Key, static_cast(key == LV_KEY_DEL ? 0x7F : key), row); + } +} + +void LvglMenu::buildText(lv_obj_t* parent) { + // One scrolling box with a label per paragraph; the box takes the keys, so W/S and the arrows scroll it + textBox = lv_obj_create(parent); + lv_obj_set_width(textBox, LV_PCT(100)); + lv_obj_set_flex_grow(textBox, 1); + lv_obj_set_style_border_width(textBox, 0, LV_STATE_DEFAULT); + lv_obj_set_style_radius(textBox, 0, LV_STATE_DEFAULT); + lv_obj_set_flex_flow(textBox, LV_FLEX_FLOW_COLUMN); + lv_obj_set_scroll_dir(textBox, LV_DIR_VER); + const char* at = text; + for (int i = 0; i < paragraphCount; i++) { + const bool heading = at[0] == '#'; + lv_obj_t* label = lv_label_create(textBox); + lv_obj_set_width(label, LV_PCT(100)); + lv_label_set_long_mode(label, LV_LABEL_LONG_MODE_WRAP); + lv_label_set_text(label, heading ? at + 1 : (at[0] == '\0' ? " " : at)); + if (heading) { + lv_obj_set_style_text_color(label, lv_theme_get_color_primary(label), LV_STATE_DEFAULT); + } + at += strlen(at) + 1; + } + lv_group_add_obj(lv_group_get_default(), textBox); + lv_obj_add_event_cb(textBox, onTextKey, LV_EVENT_KEY, this); + if (focusPending) { + lv_group_focus_obj(textBox); + } +} + +void LvglMenu::onTextKey(lv_event_t* event) { + auto* self = static_cast(lv_event_get_user_data(event)); + const uint32_t key = lv_event_get_key(event); + if (self->textBox == nullptr) { + return; + } + const int32_t step = lv_font_get_line_height(lv_obj_get_style_text_font(self->textBox, LV_PART_MAIN)) * 3; + if (key == LV_KEY_UP || key == LV_KEY_LEFT || key == LV_KEY_PREV || key == 'w' || key == 'W') { + lv_obj_scroll_by_bounded(self->textBox, 0, step, LV_ANIM_ON); + } else if (key == LV_KEY_DOWN || key == LV_KEY_RIGHT || key == LV_KEY_NEXT || key == 's' || key == 'S') { + lv_obj_scroll_by_bounded(self->textBox, 0, -step, LV_ANIM_ON); + } else if (isBackKey(key) || key == LV_KEY_ENTER || key == ' ') { + self->push(LvglMenuEvent::Kind::Back, 0); + } +} + +} // namespace maps diff --git a/Apps/Maps/main/Source/app/LvglMenu.h b/Apps/Maps/main/Source/app/LvglMenu.h new file mode 100644 index 00000000..336c8cd2 --- /dev/null +++ b/Apps/Maps/main/Source/app/LvglMenu.h @@ -0,0 +1,146 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once + +#include "../ui/MenuIcons.h" + +#include +#include + +#include +#include + +namespace maps { + +/** A tile of the LVGL main menu. */ +struct LvglMenuTile { + uint16_t action; + MenuIcon icon; + char label[28]; + /** Shown in the theme's secondary colour: something is on (location, a recording). */ + bool highlighted; +}; + +/** An icon button in the main menu's toolbar, right of the title: a glyph of the shared icon font (lvgl/icons/shared.h). */ +struct LvglMenuButton { + uint16_t action; + const char* icon; +}; + +/** + * What the user did in the LVGL menu: chose a tile (value: its action) or a list row (value: its index), went back, or + * pressed a key on a list row that the page may use (value: the key, row: the row). + */ +struct LvglMenuEvent { + enum class Kind : uint8_t { None, Chosen, Back, Key }; + Kind kind = Kind::None; + uint16_t value = 0; + int16_t row = -1; +}; + +/** + * The map's menus and pages as LVGL widgets, over the map image, one at a time: the main menu as Tactility's tile + * grid under a toolbar, lists (the smaller menus, and the pages Maps, Settings, Waypoints...) under a toolbar, and a + * page of text (About). Only with the LVGL output. + * + * The map task calls show and hide under no lock: they take the LVGL lock. The widgets' events come on the LVGL task + * and are queued; the map task takes them with takeEvent(). While a menu is shown, LVGL reads the keys, the trackball + * and touch, so the map must not read them (MapView skips its input then). + * + * The window manager deletes the window's widgets while another window covers the map: attach() and detach() follow + * it, and a menu that was shown is built again when the window returns. + */ +class LvglMenu { +public: + static constexpr int MAX_TILES = 16; + /** As many as a ListView holds (the region catalog is the longest). */ + static constexpr int MAX_ROWS = 72; + static constexpr int TEXT_LENGTH = 48; + static constexpr uint16_t NO_ACTION = 0xFFFF; + + ~LvglMenu(); + + /** The window's widgets were built: the menu goes on root. Under the LVGL lock. */ + void attach(lv_obj_t* root); + /** The window's widgets are gone. Under the LVGL lock. */ + void detach(); + + /** + * Shows the main menu, or updates it when it is shown (the selection stays). The focus goes to the tile of + * focusAction when it is a new menu. The buttons go in the toolbar, in this order. + */ + void showGrid(const char* title, const LvglMenuTile* tiles, int count, uint16_t focusAction, const LvglMenuButton* buttons, int buttonCount); + /** Shows a list of rows, each a label and an optional detail, with the focus on focusRow. Replaces what is shown. */ + void showList(const char* title, const char* const* labels, const char* const* details, int count, int focusRow); + /** Shows paragraphs of text under a toolbar; a paragraph that starts with '#' is a heading. Replaces what is shown. */ + void showText(const char* title, const char* const* paragraphs, int count); + void hide(); + bool isShown() const { return shown; } + /** A short message over whatever is shown, until it is set to null or empty. */ + void setToast(const char* text); + bool takeEvent(LvglMenuEvent& event); + +private: + enum class Kind : uint8_t { None, Grid, List, Text }; + + void buildLocked(); + void deleteLocked(); + void push(LvglMenuEvent::Kind kind, uint16_t value, int16_t row = -1); + void buildText(lv_obj_t* parent); + void buildToastLocked(); + const lv_image_dsc_t* iconImage(MenuIcon icon); + + static void onBack(lv_event_t* event); + static void onToolbarButton(lv_event_t* event); + /** The action of the focused tile, NO_ACTION when the focus is elsewhere. Under the LVGL lock. */ + uint16_t focusedTileLocked() const; + static void onRowClicked(lv_event_t* event); + static void onKey(lv_event_t* event); + static void onTextKey(lv_event_t* event); + static void collectTiles(lv_obj_t* grid, void* userData); + static void onTileClicked(lv_obj_t* grid, const LvglTileGridItem* item, void* userData); + static void onTileKey(lv_obj_t* grid, const LvglTileGridItem* item, uint32_t key, void* userData); + + lv_obj_t* root = nullptr; + lv_obj_t* panel = nullptr; + lv_obj_t* grid = nullptr; + std::atomic shown = false; + Kind kind = Kind::None; + /** Set when the next build should focus focusAction. */ + bool focusPending = false; + + char title[TEXT_LENGTH] = ""; + LvglMenuTile tiles[MAX_TILES] {}; + int tileCount = 0; + uint16_t focusAction = NO_ACTION; + static constexpr int MAX_BUTTONS = 3; + LvglMenuButton buttons[MAX_BUTTONS] {}; + int buttonCount = 0; + lv_obj_t* buttonObjects[MAX_BUTTONS] {}; + lv_obj_t* toolbar = nullptr; + /** MAX_ROWS labels then MAX_ROWS details, in PSRAM: the output that owns the menu is on the app task's stack. */ + char* rowText = nullptr; + char* rowLabel(int row) { return rowText + static_cast(row) * TEXT_LENGTH; } + char* rowDetail(int row) { return rowText + static_cast(MAX_ROWS + row) * TEXT_LENGTH; } + int rowCount = 0; + int focusRow = 0; + /** The text page: paragraphs one after the other, each ended by a NUL. */ + char* text = nullptr; + size_t textSize = 0; + int paragraphCount = 0; + lv_obj_t* textBox = nullptr; + char toastText[TEXT_LENGTH] = ""; + lv_obj_t* toast = nullptr; + + /** A8 masks of the icons, drawn on first use at the tile grid's icon size, painted in the theme's icon colour. */ + static constexpr int ICON_KINDS = 16; + lv_image_dsc_t icons[ICON_KINDS] {}; + uint8_t* iconPixels[ICON_KINDS] {}; + int iconSize = 0; + + /** Filled by the LVGL task, emptied by the map task, both under the LVGL lock. */ + static constexpr int QUEUE_SIZE = 8; + LvglMenuEvent queue[QUEUE_SIZE] {}; + std::atomic queueCount = 0; +}; + +} // namespace maps diff --git a/Apps/Maps/main/Source/app/LvglOutput.cpp b/Apps/Maps/main/Source/app/LvglOutput.cpp new file mode 100644 index 00000000..d0f8e34c --- /dev/null +++ b/Apps/Maps/main/Source/app/LvglOutput.cpp @@ -0,0 +1,375 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#include "LvglOutput.h" + +#include "../platform/Platform.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#if defined(SOC_PPA_SUPPORTED) && SOC_PPA_SUPPORTED +#include +#define MAPS_HAS_PPA 1 +#else +#define MAPS_HAS_PPA 0 +#endif + +#include +#include + +namespace maps { + +namespace { + +/** How long readTouch waits for the LVGL lock before it keeps the last touch state. */ +constexpr uint32_t TOUCH_LOCK_TICKS = pdMS_TO_TICKS(5); +/** How often LvglInput looks for new LVGL keyboards and mice (a trackball switched between its modes). */ +constexpr uint32_t TAKE_INTERVAL_MS = 500; +/** The PPA writes whole cache lines of external memory (L1 and L2): its target buffers start and end on these. */ +constexpr size_t PPA_ALIGNMENT = 128; + +/** The image is the map: no scrolling, no focus, no gestures for the screen behind it. */ +void configureMapImage(lv_obj_t* image) { + lv_obj_set_clickable(image, true); + lv_obj_set_scrollable(image, false); + lv_obj_set_scroll_chain(image, false); + lv_obj_set_click_focusable(image, false); + lv_obj_set_gesture_bubble(image, false); + lv_obj_set_scroll_on_focus(image, false); +} + +} // namespace + +LvglOutput::~LvglOutput() { + end(); +} + +bool LvglOutput::begin(Device* displayDevice, AppInstanceId app, int renderPercent) { + const DisplayColorFormat format = display_get_color_format(displayDevice); + monochrome = format == DISPLAY_COLOR_FORMAT_MONOCHROME || format == DISPLAY_COLOR_FORMAT_GRAYSCALE8; + window = window_manager_create_ext(app, createWidgets, destroyWidgets, this); + if (window == 0) { + logError("LVGL window not created"); + return false; + } + lvgl_lock(); + if (image != nullptr) { + lv_obj_update_layout(lv_screen_active()); + frameWidth = lv_obj_get_content_width(lv_obj_get_parent(image)); + frameHeight = lv_obj_get_content_height(lv_obj_get_parent(image)); + displayDpi = static_cast(lv_display_get_dpi(lv_obj_get_display(image))); + } + lvgl_unlock(); + if (frameWidth <= 0 || frameHeight <= 0) { + logError("LVGL window has no size"); + return false; + } + renderWidth = frameWidth; + renderHeight = frameHeight; + ppaSupported = MAPS_HAS_PPA && lvgl_ppa_is_supported() && !monochrome; + if (renderPercent <= 0) { + renderPercent = defaultRenderPercent(); + } + const bool scaled = ppaSupported && renderPercent < 100 && startPpa(renderPercent); + const size_t bytes = static_cast(frameWidth) * frameHeight * sizeof(uint16_t); + for (int i = 0; i < 2; i++) { + // The PPA writes into these when it scales the map up: whole cache lines + buffers[i] = static_cast(scaled ? heap_caps_aligned_alloc(PPA_ALIGNMENT, (bytes + PPA_ALIGNMENT - 1) / PPA_ALIGNMENT * PPA_ALIGNMENT, + MALLOC_CAP_SPIRAM) + : largeAlloc(bytes)); + if (buffers[i] == nullptr) { + logError("No memory for the LVGL frames"); + return false; + } + memset(buffers[i], 0, bytes); + lv_image_dsc_t& descriptor = descriptors[i]; + descriptor.header.magic = LV_IMAGE_HEADER_MAGIC; + descriptor.header.cf = LV_COLOR_FORMAT_RGB565; + descriptor.header.w = static_cast(frameWidth); + descriptor.header.h = static_cast(frameHeight); + descriptor.header.stride = static_cast(frameWidth) * sizeof(uint16_t); + descriptor.data = reinterpret_cast(buffers[i]); + descriptor.data_size = static_cast(bytes); + } + lvgl_lock(); + setSource(); + lvgl_unlock(); + if (scaled) { + logInfo("Display %dx%d at %d dpi, map drawn at %dx%d and scaled up %.4gx by the PPA", frameWidth, frameHeight, displayDpi, renderWidth, + renderHeight, static_cast(ppaScale)); + } else { + logInfo("Display %dx%d at %d dpi, LVGL image with 2 frames", frameWidth, frameHeight, displayDpi); + } + return true; +} + +void LvglOutput::end() { + menu.hide(); + if (window != 0) { + window_manager_remove(window); + window = 0; + } + const bool scaled = renderBuffer != nullptr; + for (auto*& buffer : buffers) { + if (scaled) { + heap_caps_free(buffer); + } else { + largeFree(buffer); + } + buffer = nullptr; + } + stopPpa(); +} + +int LvglOutput::defaultRenderPercent() const { + if (!ppaSupported) { + return 100; + } + const int shorter = frameWidth < frameHeight ? frameWidth : frameHeight; + return shorter >= 720 ? 50 : (shorter >= 480 ? 75 : 100); +} + +bool LvglOutput::startPpa(int renderPercent) { +#if MAPS_HAS_PPA + // The PPA scales by sixteenths: 50 % is 2x, 75 % is 21/16 (the nearest), and the frame is as large as that fills + ppaScale = renderPercent <= 50 ? 2.0f : 21.0f / 16.0f; + renderWidth = static_cast(frameWidth / ppaScale); + renderHeight = static_cast(frameHeight / ppaScale); + renderBuffer = static_cast(heap_caps_malloc(static_cast(renderWidth) * renderHeight * sizeof(uint16_t), MALLOC_CAP_SPIRAM)); + ppa_client_config_t config {}; + config.oper_type = PPA_OPERATION_SRM; + config.max_pending_trans_num = 1; + config.data_burst_length = PPA_DATA_BURST_LENGTH_128; + ppa_client_handle_t client = nullptr; + if (renderBuffer == nullptr || ppa_register_client(&config, &client) != ESP_OK) { + logError("Render scale %d %%: no PPA or memory, the map is drawn at full size", renderPercent); + stopPpa(); + return false; + } + ppaClient = client; + memset(renderBuffer, 0, static_cast(renderWidth) * renderHeight * sizeof(uint16_t)); + return true; +#else + (void)renderPercent; + return false; +#endif +} + +void LvglOutput::stopPpa() { +#if MAPS_HAS_PPA + if (ppaClient != nullptr) { + ppa_unregister_client(static_cast(ppaClient)); + ppaClient = nullptr; + } +#endif + heap_caps_free(renderBuffer); + renderBuffer = nullptr; + renderWidth = frameWidth; + renderHeight = frameHeight; + ppaScale = 1.0f; +} + +bool LvglOutput::scaleUp(uint16_t* target) { +#if MAPS_HAS_PPA + // The scaled frame lands centred; the strip of a pixel or two it cannot fill stays as it was (black) + const auto outWidth = static_cast(renderWidth * ppaScale); + const auto outHeight = static_cast(renderHeight * ppaScale); + ppa_srm_oper_config_t config {}; + config.in.buffer = renderBuffer; + config.in.pic_w = static_cast(renderWidth); + config.in.pic_h = static_cast(renderHeight); + config.in.block_w = static_cast(renderWidth); + config.in.block_h = static_cast(renderHeight); + config.in.srm_cm = PPA_SRM_COLOR_MODE_RGB565; + config.out.buffer = target; + config.out.buffer_size = static_cast((static_cast(frameWidth) * frameHeight * sizeof(uint16_t) + PPA_ALIGNMENT - 1) / + PPA_ALIGNMENT * PPA_ALIGNMENT); + config.out.pic_w = static_cast(frameWidth); + config.out.pic_h = static_cast(frameHeight); + config.out.block_offset_x = (static_cast(frameWidth) - std::min(outWidth, static_cast(frameWidth))) / 2; + config.out.block_offset_y = (static_cast(frameHeight) - std::min(outHeight, static_cast(frameHeight))) / 2; + config.out.srm_cm = PPA_SRM_COLOR_MODE_RGB565; + config.rotation_angle = PPA_SRM_ROTATION_ANGLE_0; + config.scale_x = ppaScale; + config.scale_y = ppaScale; + config.mode = PPA_TRANS_MODE_BLOCKING; + const esp_err_t result = ppa_do_scale_rotate_mirror(static_cast(ppaClient), &config); + if (result != ESP_OK) { + static bool logged = false; + if (!logged) { + logged = true; + logError("PPA scale failed: %d", static_cast(result)); + } + return false; + } + return true; +#else + (void)target; + return false; +#endif +} + +void LvglOutput::present() { + if (buffers[0] == nullptr) { + return; + } + if (renderBuffer != nullptr) { + // Into the image buffer LVGL is not showing, outside the LVGL lock: the PPA works while LVGL draws + scaleUp(buffers[1 - shown]); + } + lvgl_lock(); + // LVGL draws under this lock, so once the source changed it never reads the other buffer again + shown = 1 - shown; + setSource(); + lvgl_unlock(); +} + +void LvglOutput::setSource() { + if (image == nullptr || buffers[0] == nullptr) { + return; + } + lv_image_set_src(image, &descriptors[shown]); + lv_obj_invalidate(image); +} + +bool LvglOutput::readTouch(TouchState& state) { + if (lvgl_try_lock(TOUCH_LOCK_TICKS)) { + lastTouch.count = 0; + lv_indev_t* pointer = lvgl_pointer_get_default(); + if (image != nullptr && pointer != nullptr && mapSlots != 0) { + lv_area_t area; + lv_obj_get_coords(image, &area); + LvglPointerTouch touches[LVGL_POINTER_MAX_SLOTS]; + const uint8_t count = lvgl_pointer_get_touches(pointer, touches, LVGL_POINTER_MAX_SLOTS); + for (uint8_t i = 0; i < count && lastTouch.count < 2; i++) { + if ((mapSlots & (1u << touches[i].slot)) == 0) { + continue; + } + // In the map's frame, which is smaller than the image when the PPA scales it up + const int offsetX = (frameWidth - static_cast(renderWidth * ppaScale)) / 2; + const int offsetY = (frameHeight - static_cast(renderHeight * ppaScale)) / 2; + const int x = std::clamp(static_cast((touches[i].point.x - area.x1 - offsetX) / ppaScale), 0, renderWidth - 1); + const int y = std::clamp(static_cast((touches[i].point.y - area.y1 - offsetY) / ppaScale), 0, renderHeight - 1); + lastTouch.x[lastTouch.count] = static_cast(x); + lastTouch.y[lastTouch.count] = static_cast(y); + lastTouch.count++; + } + } + lvgl_unlock(); + } + state = lastTouch; + return state.count > 0; +} + +void LvglOutput::createWidgets(lv_obj_t* root, void* userData) { + static_cast(userData)->build(root); +} + +void LvglOutput::build(lv_obj_t* root) { + lv_obj_set_style_pad_all(root, 0, LV_PART_MAIN); + lv_obj_set_style_border_width(root, 0, LV_PART_MAIN); + lv_obj_set_scrollable(root, false); + image = lv_image_create(root); + lv_obj_set_size(image, LV_PCT(100), LV_PCT(100)); + configureMapImage(image); + lv_obj_add_event_cb(image, onPointerEvent, LV_EVENT_PRESSED, this); + lv_obj_add_event_cb(image, onPointerEvent, LV_EVENT_RELEASED, this); + lv_obj_add_event_cb(image, onPointerEvent, LV_EVENT_PRESS_LOST, this); + mapSlots = 0; + setSource(); + menu.attach(root); +} + +void LvglOutput::destroyWidgets(void* userData) { + auto* self = static_cast(userData); + self->menu.detach(); + self->image = nullptr; + self->mapSlots = 0; +} + +void LvglOutput::onPointerEvent(lv_event_t* event) { + auto* self = static_cast(lv_event_get_user_data(event)); + const int8_t slot = lvgl_pointer_get_slot_index(lv_event_get_indev(event)); + if (slot < 0) { + return; + } + const uint32_t bit = 1u << slot; + if (lv_event_get_code(event) == LV_EVENT_PRESSED) { + self->mapSlots |= bit; + } else { + self->mapSlots &= ~bit; + } +} + +// --------------------------------------------------------------------------------------------------------------- + +void LvglInput::begin() { + Input::begin(); + lvgl_lock(); + takeLvglDevices(); + lvgl_unlock(); +} + +void LvglInput::end() { + lvgl_lock(); + releaseLvglDevices(); + lvgl_unlock(); + Input::end(); +} + +void LvglInput::releaseLvglDevices() { + // Only the devices that still exist: a trackball that switched modes deleted its old one + for (lv_indev_t* indev = lv_indev_get_next(nullptr); indev != nullptr; indev = lv_indev_get_next(indev)) { + if (std::find(taken, taken + takenCount, indev) != taken + takenCount) { + lv_indev_enable(indev, true); + } + } + takenCount = 0; +} + +void LvglInput::setUiActive(bool active) { + if (active == uiActive) { + return; + } + uiActive = active; + lvgl_lock(); + if (active) { + releaseLvglDevices(); + } else { + takeLvglDevices(); + } + lvgl_unlock(); +} + +int LvglInput::readKeys(KeyEvent* events, int maxEvents) { + // Not waiting for LVGL while it draws: the keys are read every loop pass, the next pass tries again + if (!uiActive && nowMs() - lastTakeMs >= TAKE_INTERVAL_MS && lvgl_try_lock(0)) { + takeLvglDevices(); + lvgl_unlock(); + } + return Input::readKeys(events, maxEvents); +} + +void LvglInput::takeLvglDevices() { + lastTakeMs = nowMs(); + for (lv_indev_t* indev = lv_indev_get_next(nullptr); indev != nullptr; indev = lv_indev_get_next(indev)) { + const lv_indev_type_t type = lv_indev_get_type(indev); + // Touch slots stay: the map's touches come through them + const bool mouse = type == LV_INDEV_TYPE_POINTER && lvgl_pointer_get_slot_index(indev) < 0; + if (!mouse && type != LV_INDEV_TYPE_KEYPAD && type != LV_INDEV_TYPE_ENCODER) { + continue; + } + if (std::find(taken, taken + takenCount, indev) != taken + takenCount || takenCount >= MAX_TAKEN) { + continue; + } + lv_indev_enable(indev, false); + taken[takenCount++] = indev; + } +} + +} // namespace maps diff --git a/Apps/Maps/main/Source/app/LvglOutput.h b/Apps/Maps/main/Source/app/LvglOutput.h new file mode 100644 index 00000000..5094c660 --- /dev/null +++ b/Apps/Maps/main/Source/app/LvglOutput.h @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once + +#include "FrameOutput.h" +#include "Input.h" +#include "LvglMenu.h" + +#include +#include +#include + +#include + +namespace maps { + +/** + * Shows the map in an LVGL window, with LVGL running: an image below the statusbar, filling the window, whose source flips + * between two frame buffers. The map draws the next frame into one while LVGL reads the other. Fingers pressed on the + * image are the map's touches; fingers on widgets above it are not. + * + * The window manager deletes the widgets while another window covers the map and builds them again when it + * returns, possibly from another task: every widget access is under the LVGL lock and checks that the image exists. + */ +class LvglOutput final : public FrameOutput { +public: + ~LvglOutput() override; + + /** + * renderPercent: 100, or 75 or 50 to draw the map smaller and have the PPA scale it up to the screen (only where + * there is one; otherwise 100), or 0 for defaultRenderPercent(). + */ + bool begin(Device* displayDevice, AppInstanceId app, int renderPercent); + void end() override; + + uint16_t* drawBuffer() override { return renderBuffer != nullptr ? renderBuffer : buffers[1 - shown]; } + const uint16_t* shownBuffer() const override { return renderBuffer != nullptr ? renderBuffer : buffers[shown]; } + void present() override; + + int width() const override { return renderWidth; } + int height() const override { return renderHeight; } + bool isMonochrome() const override { return monochrome; } + const char* name() const override { return "LVGL"; } + LvglMenu* lvglMenu() override { return &menu; } + int dpi() const override { return frameWidth > 0 ? displayDpi * renderWidth / frameWidth : displayDpi; } + bool canScale() const override { return ppaSupported; } + /** With a PPA: 50 when the frame's shorter side is 720 px or more, 75 from 480 px, else 100. */ + int defaultRenderPercent() const override; + bool isScaledUp() const override { return renderBuffer != nullptr; } + + /** The fingers that pressed the map, in map coordinates. Keeps the last state when LVGL is busy. */ + bool readTouch(TouchState& state); + +private: + static void createWidgets(lv_obj_t* root, void* userData); + static void destroyWidgets(void* userData); + static void onPointerEvent(lv_event_t* event); + void build(lv_obj_t* root); + void setSource(); + + uint32_t window = 0; + lv_obj_t* image = nullptr; + lv_image_dsc_t descriptors[2] {}; + uint16_t* buffers[2] = { nullptr, nullptr }; + int shown = 0; + int frameWidth = 0; + int frameHeight = 0; + bool monochrome = false; + int displayDpi = 0; + /** The map's frame: the image's size, or smaller when the PPA scales it up (renderBuffer). */ + int renderWidth = 0; + int renderHeight = 0; + /** The smaller frame the map draws into; null when it draws into the image buffers directly. */ + uint16_t* renderBuffer = nullptr; + /** Scale factor from the render frame to the image, a multiple of 1/16 (what the PPA does). */ + float ppaScale = 1.0f; + void* ppaClient = nullptr; + bool ppaSupported = false; + bool startPpa(int renderPercent); + void stopPpa(); + bool scaleUp(uint16_t* target); + /** Bit per touch slot: the fingers that went down on the image. Changed by events, under the LVGL lock. */ + uint32_t mapSlots = 0; + TouchState lastTouch {}; + /** After the image, so its widgets are deleted before the window goes. */ + LvglMenu menu; +}; + +/** + * Input for the LVGL output. Keys and mice are read from their drivers as with LVGL stopped, so the map keeps its own + * key handling, pointer and acceleration: their LVGL input devices are disabled while the map runs, and enabled again + * at the end. Touch comes from LVGL, so the screen's widgets work with it. + */ +class LvglInput final : public Input { +public: + explicit LvglInput(LvglOutput& output) : output(output) {} + ~LvglInput() override { end(); } + + void begin() override; + void end() override; + int readKeys(KeyEvent* events, int maxEvents) override; + bool readTouch(TouchState& state) override { return output.readTouch(state); } + void setUiActive(bool active) override; + +private: + /** Disables the LVGL keyboards and mice that are enabled, including ones that came since the last call. Under the LVGL lock. */ + void takeLvglDevices(); + /** Enables the LVGL devices that were taken. Under the LVGL lock. */ + void releaseLvglDevices(); + + static constexpr int MAX_TAKEN = 8; + LvglOutput& output; + lv_indev_t* taken[MAX_TAKEN] {}; + int takenCount = 0; + uint32_t lastTakeMs = 0; + bool uiActive = false; +}; + +} // namespace maps diff --git a/Apps/Maps/main/Source/app/MapApp.cpp b/Apps/Maps/main/Source/app/MapApp.cpp index 31bcad0d..1086eca7 100644 --- a/Apps/Maps/main/Source/app/MapApp.cpp +++ b/Apps/Maps/main/Source/app/MapApp.cpp @@ -1,9 +1,14 @@ // SPDX-License-Identifier: GPL-3.0-or-later +#include "Input.h" +#include "LvglOutput.h" #include "MapView.h" +#include "../ui/Settings.h" + #include "../platform/Platform.h" #include +#include #include #include #include @@ -17,7 +22,9 @@ #include #include +#include #include +#include #include #include @@ -61,24 +68,106 @@ void logSession(const char* root, uint32_t startPsram, uint32_t startInternal) { } -void runFullscreen(Device* display, const char* root, const char* dataPath) { - const bool lvglActive = module_is_started(&lvgl_module); - if (lvglActive) { - const uint32_t start = nowMs(); - module_stop(&lvgl_module); - logInfo("LVGL stopped in %u ms", nowMs() - start); +/** Runs the map until it exits. The view is large: it lives in external RAM where the device has it. */ +/** Where the command line asks the map to open (--lat, --lon, --zoom). */ +struct StartView { + bool hasPosition = false; + double lat = 0.0; + double lon = 0.0; + int zoom = -1; +}; + +bool parseNumber(const char* text, double& out) { + if (text == nullptr || *text == '\0') { + return false; + } + char* end = nullptr; + out = strtod(text, &end); + return end != text && *end == '\0' && std::isfinite(out); +} + +/** + * Reads --lat --lon [--zoom <0-19>] (also as --lat=52.37). Both coordinates or neither; --zoom + * also works alone. Anything else is reported and ignored: the map then opens where it was. + */ +StartView parseStartView(int argc, char* argv[]) { + StartView view; + double lat = 0.0; + double lon = 0.0; + bool hasLat = false; + bool hasLon = false; + // Apps started from the shell get their name in argv[0], apps started by app_start_context_set_arguments() don't + const int first = argc > 0 && argv[0] != nullptr && strncmp(argv[0], "--", 2) != 0 ? 1 : 0; + for (int i = first; i < argc; i++) { + const char* arg = argv[i]; + const char* value = nullptr; + const char* name = arg; + char key[16]; + if (const char* equals = strchr(arg, '='); equals != nullptr && static_cast(equals - arg) < sizeof(key)) { + memcpy(key, arg, equals - arg); + key[equals - arg] = '\0'; + name = key; + value = equals + 1; + } else if (i + 1 < argc) { + value = argv[i + 1]; + } + const bool separate = name == arg; + double number = 0.0; + if (strcmp(name, "--lat") == 0 || strcmp(name, "--lon") == 0 || strcmp(name, "--zoom") == 0) { + if (!parseNumber(value, number)) { + logError("Command line: %s needs a number", name); + return {}; + } + if (separate) { + i++; + } + if (strcmp(name, "--lat") == 0) { + if (number < -90.0 || number > 90.0) { + logError("Command line: latitude %f is not between -90 and 90", number); + return {}; + } + lat = number; + hasLat = true; + } else if (strcmp(name, "--lon") == 0) { + if (number < -180.0 || number > 180.0) { + logError("Command line: longitude %f is not between -180 and 180", number); + return {}; + } + lon = number; + hasLon = true; + } else { + if (number < 0.0 || number > MAX_VIEW_ZOOM) { + logError("Command line: zoom %f is not between 0 and %d", number, MAX_VIEW_ZOOM); + return {}; + } + view.zoom = static_cast(number + 0.5); + } + } else { + logError("Command line: unknown argument %s (use --lat, --lon and --zoom)", arg); + return {}; + } } + if (hasLat != hasLon) { + logError("Command line: --lat and --lon go together"); + return {}; + } + view.hasPosition = hasLat; + view.lat = lat; + view.lon = lon; + return view; +} +void runView(FrameOutput& output, Input& input, const char* root, const char* dataPath, const StartView& start) { // Above the render lanes and the I/O task (4): the loop sleeps between frames, so it only takes the CPU to // answer input and draw. At the same priority frames took 150-270 ms while tiles were loading. const UBaseType_t appPriority = uxTaskPriorityGet(nullptr); vTaskPrioritySet(nullptr, appPriority + 1); - - // The view is large, it lives in external RAM where the device has it void* memory = largeAlloc(sizeof(MapView)); if (memory != nullptr) { auto* view = new (memory) MapView(); - if (view->begin(display, root, dataPath)) { + logInfo("Display output: %s", output.name()); + view->setStartView(start.hasPosition, start.lat, start.lon, start.zoom); + if (view->begin(output, input, root, dataPath)) { view->run(); } view->end(); @@ -88,13 +177,28 @@ void runFullscreen(Device* display, const char* root, const char* dataPath) { logError("Out of memory"); } vTaskPrioritySet(nullptr, appPriority); +} + +/** The render scale settings.txt asks for, read before the view starts (which reads the settings again). */ +int renderPercent(const char* root) { + char path[PATH_MAX_LENGTH]; + snprintf(path, sizeof(path), "%s/settings.txt", root); + Settings settings; + readSettings(path, settings); + return settings.renderScale; +} - // LVGL comes back on every exit path, also after errors - if (lvglActive && !module_is_started(&lvgl_module)) { - const uint32_t start = nowMs(); - module_start(&lvgl_module); - logInfo("LVGL started in %u ms", nowMs() - start); +/** Draws into an LVGL window, with LVGL running. */ +void runLvgl(Device* display, const char* root, const char* dataPath, const StartView& start) { + LvglOutput output; + LvglInput input(output); + if (output.begin(display, app_scheduler_current_app_id(), renderPercent(root))) { + runView(output, input, root, dataPath, start); + } else { + logError("LVGL output failed"); } + input.end(); + output.end(); } bool pathExists(const char* path) { @@ -169,8 +273,7 @@ void migrateLegacyData(const char* dataPath, const char* root) { } // namespace maps extern "C" int main(int argc, char* argv[]) { - (void)argc; - (void)argv; + const maps::StartView start = maps::parseStartView(argc, argv); maps::logMemory("start"); char root[maps::PATH_MAX_LENGTH]; if (app_paths_get_user_data_directory(maps::APP_ID, root, sizeof(root)) != ERROR_NONE) { @@ -192,7 +295,11 @@ extern "C" int main(int argc, char* argv[]) { } const auto startPsram = static_cast(heap_caps_get_free_size(MALLOC_CAP_SPIRAM)); const auto startInternal = static_cast(heap_caps_get_free_size(MALLOC_CAP_INTERNAL)); - maps::runFullscreen(display, root, dataPath); + if (module_is_started(&lvgl_module)) { + maps::runLvgl(display, root, dataPath, start); + } else { + maps::logError("LVGL is not running"); + } device_put(display); maps::logMemory("exit"); maps::logSession(root, startPsram, startInternal); diff --git a/Apps/Maps/main/Source/app/MapCamera.cpp b/Apps/Maps/main/Source/app/MapCamera.cpp index 9b250f44..50a4954d 100644 --- a/Apps/Maps/main/Source/app/MapCamera.cpp +++ b/Apps/Maps/main/Source/app/MapCamera.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-or-later #include "MapView.h" +#include "../ui/Metrics.h" #include "MapViewInternal.h" #include "../platform/Platform.h" @@ -110,19 +111,19 @@ void MapView::zoomBy(int steps, int anchorX, int anchorY) { } void MapView::screenToWorldOffset(double sx, double sy, double& wx, double& wy) const { - wx = bearingCos * sx - bearingSin * sy; - wy = bearingSin * sx + bearingCos * sy; + wx = (bearingCos * sx - bearingSin * sy) / magnify; + wy = (bearingSin * sx + bearingCos * sy) / magnify; } void MapView::worldToScreenOffset(double wx, double wy, double& sx, double& sy) const { - sx = bearingCos * wx + bearingSin * wy; - sy = -bearingSin * wx + bearingCos * wy; + sx = (bearingCos * wx + bearingSin * wy) * magnify; + sy = (-bearingSin * wx + bearingCos * wy) * magnify; } void MapView::viewBounds(double& left, double& top, double& right, double& bottom) const { // The world box around the four turned screen corners - const double halfWidth = width / 2.0; - const double halfHeight = height / 2.0; + const double halfWidth = width / 2.0 / magnify; + const double halfHeight = height / 2.0 / magnify; const double spanX = std::fabs(bearingCos) * halfWidth + std::fabs(bearingSin) * halfHeight; const double spanY = std::fabs(bearingSin) * halfWidth + std::fabs(bearingCos) * halfHeight; left = centerX - spanX; @@ -151,7 +152,7 @@ void MapView::applyBearing(float degrees, bool want) { } Rect MapView::compassRect() const { - return { width - 6 - 30, 6, 30, 30 }; + return { width - metrics::px(6) - metrics::px(30), metrics::px(6), metrics::px(30), metrics::px(30) }; } void MapView::drawCompass() { @@ -168,11 +169,11 @@ void MapView::drawCompass() { // North on screen is the world's up turned back by the bearing const float northX = -std::sin(radians); const float northY = -std::cos(radians); - canvas.fillCircle(cx, cy, 14.0f, theme.panel); - canvas.ring(cx, cy, 14.0f, 1.5f, theme.text); - canvas.line(cx, cy, cx + northX * 10.0f, cy + northY * 10.0f, 3.0f, monochrome ? theme.text : static_cast(0xD8A3)); - canvas.line(cx, cy, cx - northX * 10.0f, cy - northY * 10.0f, 3.0f, monochrome ? theme.panel : theme.text); - canvas.fillCircle(cx, cy, 2.0f, theme.text); + canvas.fillCircle(cx, cy, metrics::px(14.0f), theme.panel); + canvas.ring(cx, cy, metrics::px(14.0f), metrics::px(1.5f), theme.text); + canvas.line(cx, cy, cx + northX * metrics::px(10.0f), cy + northY * metrics::px(10.0f), metrics::px(3.0f), monochrome ? theme.text : static_cast(0xD8A3)); + canvas.line(cx, cy, cx - northX * metrics::px(10.0f), cy - northY * metrics::px(10.0f), metrics::px(3.0f), monochrome ? theme.panel : theme.text); + canvas.fillCircle(cx, cy, metrics::px(2.0f), theme.text); } void MapView::setBearing(float degrees, bool animate) { @@ -229,7 +230,7 @@ bool MapView::isSmoothView() const { } void MapView::updateSmooth(uint32_t now) { - if (!isRotated() || isSmoothView() || animation.active || turn.active || pinching || isFullScreen() || now - lastInputAt < 250 || + if ((!isRotated() && magnify == std::floor(magnify)) || isSmoothView() || animation.active || turn.active || pinching || isFullScreen() || now - lastInputAt < 250 || !isViewComplete()) { return; } diff --git a/Apps/Maps/main/Source/app/MapDebug.cpp b/Apps/Maps/main/Source/app/MapDebug.cpp index 372cf172..009263d0 100644 --- a/Apps/Maps/main/Source/app/MapDebug.cpp +++ b/Apps/Maps/main/Source/app/MapDebug.cpp @@ -144,9 +144,6 @@ void MapView::runDebugStep(const DebugScript::Step& step, uint32_t now) { cursorY = std::clamp(static_cast(step.values[1]), 0, height - 1); cursorShown = true; cursorMovedAt = nowMs(); - if (mainMenuOpen()) { - menuGrid.hover(cursorX, cursorY); - } dirty = true; break; case DebugScript::Action::FollowGpx: { @@ -202,10 +199,10 @@ void MapView::runDebugStep(const DebugScript::Step& step, uint32_t now) { break; } case DebugScript::Action::TouchOnly: - input.setTouchOnly(true); + input->setTouchOnly(true); cursorShown = false; - controls.setInputs({ input.hasKeyboard(), input.hasTouch(), input.hasPointer() }); - metrics::setKeyboard(input.hasKeyboard()); + controls.setInputs({ input->hasKeyboard(), input->hasTouch(), input->hasPointer() }); + metrics::setKeyboard(input->hasKeyboard()); if (downloadCard.isOpen()) { fillDownloadCard(); } diff --git a/Apps/Maps/main/Source/app/MapInput.cpp b/Apps/Maps/main/Source/app/MapInput.cpp index a0e8aa30..d0a1e961 100644 --- a/Apps/Maps/main/Source/app/MapInput.cpp +++ b/Apps/Maps/main/Source/app/MapInput.cpp @@ -89,9 +89,7 @@ void MapView::handleKey(uint32_t key) { return; } if (mainMenuOpen()) { - // The tile grid knows Enter and Esc, the board's yes and no keys are the same - const uint32_t gridKey = key == keys::YES ? keys::ENTER : (key == keys::NO ? keys::ESCAPE : key); - handleMainMenuEvent(menuGrid.handleKey(gridKey)); + // The main menu is an LVGL widget, which reads its own keys return; } handleListAction(menu.handleKey(key)); @@ -340,7 +338,7 @@ void MapView::pointerClick() { void MapView::click(bool fromPointer) { dirty = true; - if (fromPointer && input.hasPointer()) { + if (fromPointer && input->hasPointer()) { pointerClick(); return; } @@ -419,7 +417,7 @@ void MapView::handleEnter(bool pressed, uint32_t now) { void MapView::handleMouse(uint32_t now) { int32_t rawX; int32_t rawY; - const bool pressed = input.readMouse(rawX, rawY); + const bool pressed = input->readMouse(rawX, rawY); if (pressed || rawX != 0 || rawY != 0) { markInput(now); } @@ -449,9 +447,6 @@ void MapView::handleMouse(uint32_t now) { } else if (onMap && (overflowX != 0 || overflowY != 0)) { // Pushing against a screen edge moves the map that way pan(overflowX, overflowY); - } else if (mainMenuOpen() && !dialog.isOpen() && !prompt.isOpen()) { - // The tile under the pointer gets the focus - menuGrid.hover(cursorX, cursorY); } else if (list != nullptr && !dialog.isOpen() && !prompt.isOpen()) { // The row under the pointer is the highlighted one; pushing against the top or bottom scrolls the list const int row = list->rowAt(cursorX, cursorY); @@ -567,7 +562,7 @@ void MapView::handleTouch(uint32_t now) { if (syntheticTouchActive) { syntheticTouchState(now, state); } else { - input.readTouch(state); + input->readTouch(state); } if (state.count > 0) { markInput(now); @@ -630,9 +625,7 @@ void MapView::handleTap(int x, int y) { gestures.consumeTap(); return; case InputLayer::Menu: - if (mainMenuOpen()) { - handleMainMenuEvent(menuGrid.handleTap(x, y)); - } else { + if (!mainMenuOpen()) { handleListAction(menu.handleTap(x, y)); } gestures.consumeTap(); @@ -800,17 +793,7 @@ void MapView::handleGesture(const Gesture& gesture) { } else if (onMap) { pan(-gesture.dx, -gesture.dy); } else if (mainMenuOpen()) { - // A horizontal drag turns the pages of the tile grid, which has one page as long as the menu is this size - if (!dialog.isOpen() && !prompt.isOpen() && std::abs(gesture.dx) > std::abs(gesture.dy)) { - dragRowAccumulator -= gesture.dx; - const int pageWidth = std::max(1, width / 3); - while (std::abs(dragRowAccumulator) >= pageWidth) { - if (menuGrid.swipe(dragRowAccumulator > 0 ? 1 : -1)) { - dirty = true; - } - dragRowAccumulator -= (dragRowAccumulator > 0 ? 1 : -1) * pageWidth; - } - } + // The main menu is an LVGL widget: it scrolls itself } else if (!dialog.isOpen() && !prompt.isOpen() && std::abs(gesture.dy) >= std::abs(gesture.dx)) { // Lists follow the finger pixel by pixel, the About page a line at a time; the highlight stays where it is ListView* list = menuOpen ? &menu : activeList(); diff --git a/Apps/Maps/main/Source/app/MapLabels.cpp b/Apps/Maps/main/Source/app/MapLabels.cpp index f4d51762..e06b24a2 100644 --- a/Apps/Maps/main/Source/app/MapLabels.cpp +++ b/Apps/Maps/main/Source/app/MapLabels.cpp @@ -17,6 +17,32 @@ namespace { const uint8_t* poiIcons[256] {}; bool poiMonochrome = false; uint16_t poiMonochromeColor = 0; +/** The masks at the screen's size (POI_ICON_SIZE magnified), all icons one after the other; null at 1x. */ +uint8_t* scaledMasks = nullptr; +int poiIconSize = POI_ICON_SIZE; + +/** Resamples a POI_ICON_SIZE mask to size x size, bilinear, pixel centre onto pixel centre. */ +void resampleMask(const uint8_t* source, uint8_t* target, int size) { + const float step = static_cast(POI_ICON_SIZE) / size; + auto at = [&](int x, int y) -> float { + x = std::clamp(x, 0, POI_ICON_SIZE - 1); + y = std::clamp(y, 0, POI_ICON_SIZE - 1); + return source[y * POI_ICON_SIZE + x]; + }; + for (int y = 0; y < size; y++) { + const float sy = (y + 0.5f) * step - 0.5f; + const int y0 = static_cast(std::floor(sy)); + const float fy = sy - y0; + for (int x = 0; x < size; x++) { + const float sx = (x + 0.5f) * step - 0.5f; + const int x0 = static_cast(std::floor(sx)); + const float fx = sx - x0; + const float top = at(x0, y0) * (1.0f - fx) + at(x0 + 1, y0) * fx; + const float bottom = at(x0, y0 + 1) * (1.0f - fx) + at(x0 + 1, y0 + 1) * fx; + target[y * size + x] = static_cast(std::clamp(top * (1.0f - fy) + bottom * fy + 0.5f, 0.0f, 255.0f)); + } + } +} const uint8_t* iconMask(const char* name) { int low = 0; @@ -53,12 +79,40 @@ uint16_t groupColor(PoiGroup group) { } } -void preparePoiIcons(bool monochrome, uint16_t monochromeColor) { +void releasePoiIcons() { + largeFree(scaledMasks); + scaledMasks = nullptr; + poiIconSize = POI_ICON_SIZE; +} + +void preparePoiIcons(bool monochrome, uint16_t monochromeColor, float magnify) { poiMonochrome = monochrome; poiMonochromeColor = monochromeColor; - const uint8_t* fallback = iconMask("marker"); + // On a dense screen the icons grow with the map, resampled once (about 900 bytes an icon at 2x) + const int size = std::min(255, static_cast(POI_ICON_SIZE * magnify + 0.5f)); + if (size != poiIconSize || (size != POI_ICON_SIZE && scaledMasks == nullptr)) { + releasePoiIcons(); + if (size != POI_ICON_SIZE) { + const size_t bytes = static_cast(size) * size; + scaledMasks = static_cast(largeAlloc(bytes * POI_ICON_COUNT)); + if (scaledMasks != nullptr) { + for (int i = 0; i < POI_ICON_COUNT; i++) { + resampleMask(POI_ICON_MASKS[i].alpha, scaledMasks + bytes * i, size); + } + poiIconSize = size; + } + } + } + auto shown = [](const uint8_t* mask) -> const uint8_t* { + if (mask == nullptr || scaledMasks == nullptr) { + return mask; + } + const auto index = static_cast((mask - POI_ICON_MASKS[0].alpha) / static_cast(sizeof(PoiIconMask))); + return scaledMasks + index * poiIconSize * poiIconSize; + }; + const uint8_t* fallback = shown(iconMask("marker")); for (int id = 1; id <= poiTypeCount() && id < 256; id++) { - const uint8_t* mask = iconMask(poiIconName(poiType(static_cast(id)).icon)); + const uint8_t* mask = shown(iconMask(poiIconName(poiType(static_cast(id)).icon))); poiIcons[id] = mask != nullptr ? mask : fallback; } } @@ -68,12 +122,16 @@ bool lookupPoi(uint8_t id, PoiAppearance& out) { return false; } const PoiType& type = poiType(id); - out = { poiIcons[id], POI_ICON_SIZE, poiMonochrome ? poiMonochromeColor : groupColor(type.group), type.minZoom }; + out = { poiIcons[id], poiIconSize, poiMonochrome ? poiMonochromeColor : groupColor(type.group), type.minZoom }; return true; } } // namespace +void MapView::releaseLabelIcons() { + releasePoiIcons(); +} + void MapView::applyLabelFonts() { LabelFont* small = labelFonts[0].isOpen() ? &labelFonts[0] : (smallFont.isOpen() ? &smallFont : &normalFont); LabelFont* normal = labelFonts[1].isOpen() ? &labelFonts[1] : static_cast(&normalFont); @@ -91,6 +149,32 @@ void MapView::applyLabelFonts() { logInfo("Label glyphs ready in %u ms", static_cast(nowMs() - start)); } +bool MapView::openFrameFonts(const char* root) { + if (!output->isScaledUp()) { + return false; + } + BinFontText* fonts[LabelFontMaker::COUNT] = { &smallFont, &normalFont, &largeFont }; + for (int i = 0; i < LabelFontMaker::COUNT; i++) { + char path[200]; + LabelFontMaker::cachePath(root, i, magnify, path, sizeof(path)); + if (!fileExists(path)) { + return false; + } + } + for (int i = 0; i < LabelFontMaker::COUNT; i++) { + char path[200]; + LabelFontMaker::cachePath(root, i, magnify, path, sizeof(path)); + fonts[i]->close(); + if (!fonts[i]->openFile(path)) { + logError("Frame font %s does not open", path); + return false; + } + } + logInfo("Frame fonts: the label fonts (%d, %d, %d px), the frame is scaled up", LabelFontMaker::emSize(0, magnify), LabelFontMaker::emSize(1, magnify), + LabelFontMaker::emSize(2, magnify)); + return true; +} + void MapView::pollLabelFonts() { // Only the map loop touches the label layout: the maker's task just reports, and the files are opened here if (labelFontsApplied || !fontMaker.isFinished()) { @@ -102,7 +186,7 @@ void MapView::pollLabelFonts() { auto openWritten = [&] { for (int i = 0; i < LabelFontMaker::COUNT; i++) { char fontPath[200]; - LabelFontMaker::cachePath(rootPath, i, fontPath, sizeof(fontPath)); + LabelFontMaker::cachePath(rootPath, i, magnify, fontPath, sizeof(fontPath)); if ((written & (1u << i)) != 0 && !labelFonts[i].openFile(fontPath)) { logError("Label font %s does not open, the map keeps the system font", fontPath); } @@ -110,13 +194,22 @@ void MapView::pollLabelFonts() { return true; }; runOnCard(io, openWritten); + if (output->isScaledUp() && written == (1u << LabelFontMaker::COUNT) - 1) { + // The first run of a scaled frame: its text gets the new fonts too, the panels are laid out again + auto openFonts = [&] { return openFrameFonts(rootPath); }; + runOnCard(io, openFonts); + overlay.setFonts(&normalFont, &smallFont); + layoutControls(); + dirty = true; + } applyLabelFonts(); labelZoom = -1; } void MapView::applyLabelSettings() { labels.setDensity(static_cast(std::clamp(settings.labels, 0, 2))); - preparePoiIcons(monochrome, palette->text); + preparePoiIcons(monochrome, palette->text, magnify); + labels.setScale(magnify); labels.setPoiLookup(lookupPoi); labels.setPreferLatin(settings.latinNames); const bool binary = palette->binary; @@ -167,7 +260,7 @@ void MapView::placeLabels() { double screenX; double screenY; worldToScreenOffset(cornerX, cornerY, screenX, screenY); - const auto scale = static_cast(size / PREPARED_EXTENT); + const auto scale = static_cast(size / PREPARED_EXTENT) * magnify; const LabelTransform transform { scale * bearingCos, scale * bearingSin, -scale * bearingSin, scale * bearingCos, static_cast(width / 2.0 + screenX), static_cast(height / 2.0 + screenY) }; const bool found = labelStore.with(source, [&](const uint8_t* bytes, size_t size, int count, const LabelCells* cells) { diff --git a/Apps/Maps/main/Source/app/MapNavigation.cpp b/Apps/Maps/main/Source/app/MapNavigation.cpp index bb1f3b0d..de5d2c1b 100644 --- a/Apps/Maps/main/Source/app/MapNavigation.cpp +++ b/Apps/Maps/main/Source/app/MapNavigation.cpp @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-3.0-or-later // Navigation on the map (M5c-3, M5c-4): asking for a route, its preview, drawing it and following it. #include "MapView.h" +#include "../ui/Metrics.h" #include "../platform/Platform.h" @@ -212,7 +213,7 @@ constexpr int START_POSITION = 2; void MapView::openRouteStartChoice() { // No GPS fix: where does the route start beginPopup(Popup::RouteStart, "Route from"); - menu.add("Choose on the map", input.hasTouch() ? "tap it" : "crosshair"); + menu.add("Choose on the map", input->hasTouch() ? "tap it" : "crosshair"); popupActions[popupActionCount++] = START_ON_MAP; menu.add("Screen centre"); popupActions[popupActionCount++] = START_CENTRE; @@ -253,8 +254,8 @@ void MapView::beginPickStart() { controls.hide(); // Short: the bar has room for about 35 characters a line on the T-Deck pickBar.set(Turn::Arrive, "Where does the route start?", - input.hasTouch() && input.hasKeyboard() ? "Tap it, or Enter for the +" : - input.hasTouch() ? "Tap it on the map" : + input->hasTouch() && input->hasKeyboard() ? "Tap it, or Enter for the +" : + input->hasTouch() ? "Tap it on the map" : "Move the map, then Enter"); dirty = true; } @@ -271,10 +272,10 @@ void MapView::drawPickStart() { // The crosshair the start is taken from, and the bar saying what to do const auto x = static_cast(width / 2); const auto y = static_cast(height / 2); - canvas.line(x - 9.0f, y, x + 9.0f, y, 4.0f, theme.panel); - canvas.line(x, y - 9.0f, x, y + 9.0f, 4.0f, theme.panel); - canvas.line(x - 8.0f, y, x + 8.0f, y, 2.0f, theme.text); - canvas.line(x, y - 8.0f, x, y + 8.0f, 2.0f, theme.text); + canvas.line(x - metrics::px(9.0f), y, x + metrics::px(9.0f), y, metrics::px(4.0f), theme.panel); + canvas.line(x, y - metrics::px(9.0f), x, y + metrics::px(9.0f), metrics::px(4.0f), theme.panel); + canvas.line(x - metrics::px(8.0f), y, x + metrics::px(8.0f), y, metrics::px(2.0f), theme.text); + canvas.line(x, y - metrics::px(8.0f), x, y + metrics::px(8.0f), metrics::px(2.0f), theme.text); pickBar.draw(canvas, sheetFont(), theme, width); } @@ -719,8 +720,8 @@ void MapView::drawRoute() { const uint16_t casing = monochrome ? palette->halo : ROUTE_CASING; const uint16_t fill = monochrome ? palette->text : ROUTE_COLOR; const uint16_t done = monochrome ? palette->halo : ROUTE_PASSED; - const float fillWidth = binary ? 6.0f : ROUTE_WIDTH; - const float casingWidth = binary ? 9.0f : ROUTE_CASING_WIDTH; + const float fillWidth = binary ? metrics::px(6.0f) : metrics::px(ROUTE_WIDTH); + const float casingWidth = binary ? metrics::px(9.0f) : metrics::px(ROUTE_CASING_WIDTH); auto project = [&](const RoutePoint& point, float& x, float& y) { double sx; double sy; @@ -749,7 +750,7 @@ void MapView::drawRoute() { canvas.line(lastX, lastY, x, y, casingWidth, casing); } else { const bool isPassed = passed >= 0.0f && route.distances[i] <= passed; - canvas.line(lastX, lastY, x, y, isPassed && !monochrome ? fillWidth - 1.0f : fillWidth, isPassed ? done : fill); + canvas.line(lastX, lastY, x, y, isPassed && !monochrome ? fillWidth - metrics::px(1.0f) : fillWidth, isPassed ? done : fill); } } lastX = x; @@ -761,9 +762,9 @@ void MapView::drawRoute() { float goalY; project(route.points[route.points.size() - 1], goalX, goalY); navigator.unlock(); - canvas.fillCircle(goalX, goalY, 6.0f, casing); - canvas.fillCircle(goalX, goalY, 4.0f, fill); - canvas.fillCircle(goalX, goalY, 1.5f, casing); + canvas.fillCircle(goalX, goalY, metrics::px(6.0f), casing); + canvas.fillCircle(goalX, goalY, metrics::px(4.0f), fill); + canvas.fillCircle(goalX, goalY, metrics::px(1.5f), casing); } } // namespace maps diff --git a/Apps/Maps/main/Source/app/MapPlaces.cpp b/Apps/Maps/main/Source/app/MapPlaces.cpp index fa305af1..9c38a9fb 100644 --- a/Apps/Maps/main/Source/app/MapPlaces.cpp +++ b/Apps/Maps/main/Source/app/MapPlaces.cpp @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-3.0-or-later // Waypoints, track recording and GPX files on the map. #include "MapView.h" +#include "../ui/Metrics.h" #include "../platform/SafeFile.h" @@ -366,7 +367,8 @@ void MapView::selectNextPlace() { int MapView::waypointAt(int x, int y) const { int best = -1; - float bestDistance = static_cast(PIN_HIT * PIN_HIT); + const float hit = metrics::px(static_cast(PIN_HIT)); + float bestDistance = hit * hit; for (int i = 0; i < waypoints.count(); i++) { float px; float py; @@ -375,7 +377,7 @@ int MapView::waypointAt(int x, int y) const { } // The pin's head is above its point const float dx = px - static_cast(x); - const float dy = py - PIN_HEAD_OFFSET - static_cast(y); + const float dy = py - metrics::px(PIN_HEAD_OFFSET) - static_cast(y); if (dx * dx + dy * dy < bestDistance) { bestDistance = dx * dx + dy * dy; best = i; @@ -599,7 +601,7 @@ void MapView::drawPlaces() { } const bool visible = !((lastX < 0 && x < 0) || (lastY < 0 && y < 0) || (lastX > width && x > width) || (lastY > height && y > height)); if (visible) { - canvas.line(lastX, lastY, x, y, 3.0f, color); + canvas.line(lastX, lastY, x, y, metrics::px(3.0f), color); } lastX = x; lastY = y; @@ -610,8 +612,8 @@ void MapView::drawPlaces() { float y; project(layer->pin(p).x, layer->pin(p).y, x, y); if (x > -8 && y > -8 && x < width + 8 && y < height + 8) { - canvas.fillCircle(x, y, 4.0f, palette->halo); - canvas.fillCircle(x, y, 2.5f, pinColor); + canvas.fillCircle(x, y, metrics::px(4.0f), palette->halo); + canvas.fillCircle(x, y, metrics::px(2.5f), pinColor); } } } @@ -632,7 +634,7 @@ void MapView::drawPlaces() { continue; } if (!recorder.segmentStartsAt(i)) { - canvas.line(lastX, lastY, x, y, 3.0f, color); + canvas.line(lastX, lastY, x, y, metrics::px(3.0f), color); } lastX = x; lastY = y; @@ -648,9 +650,13 @@ void MapView::drawPlaces() { } drawPin(canvas, x, y, style, sheet.isOpen() && i == selectedWaypoint); } - // The point a new waypoint is being made for + // The place the app was started for (--lat, --lon) float x; float y; + if (launchPinShown && worldToScreen(launchLat, launchLon, x, y)) { + drawPin(canvas, x, y, style, false); + } + // The point a new waypoint is being made for if (sheet.isOpen() && sheet.mode() == WaypointSheet::Mode::New && worldToScreen(sheetLat, sheetLon, x, y)) { drawPin(canvas, x, y, style, true); } @@ -684,7 +690,7 @@ void MapView::drawRecording() { const int x = width - boxWidth - 4; const int y = 4; canvas.fillRoundRect(x, y, boxWidth, boxHeight, boxHeight / 2, theme.panel, theme.panelOpacity); - canvas.fillCircle(static_cast(x + 10), static_cast(y + boxHeight / 2), 4.0f, monochrome ? palette->text : 0xF800); + canvas.fillCircle(static_cast(x + metrics::px(10)), static_cast(y + boxHeight / 2), metrics::px(4.0f), monochrome ? palette->text : 0xF800); font.drawText(canvas, x + 18, y + 3, text, theme.text); } diff --git a/Apps/Maps/main/Source/app/MapScreens.cpp b/Apps/Maps/main/Source/app/MapScreens.cpp index 78707d2a..13ac6972 100644 --- a/Apps/Maps/main/Source/app/MapScreens.cpp +++ b/Apps/Maps/main/Source/app/MapScreens.cpp @@ -1,5 +1,8 @@ // SPDX-License-Identifier: GPL-3.0-or-later #include "MapView.h" +#include "LvglMenu.h" + +#include #include "../platform/Platform.h" @@ -102,8 +105,8 @@ enum RegionAction : int { void MapView::setListHint(ListView& list, const char* keyHint, const char* touchHint) { // One line per input the board has, keys first char text[128]; - const bool touch = input.hasTouch(); - const bool keys = input.hasKeyboard() || !touch; + const bool touch = input->hasTouch(); + const bool keys = input->hasKeyboard() || !touch; snprintf(text, sizeof(text), "%s%s%s", keys ? keyHint : "", keys && touch ? "\n" : "", touch ? touchHint : ""); list.setHint(text); } @@ -168,8 +171,157 @@ void MapView::layoutPopup() { menu.layoutPopup(width, height, overlay.font(), std::min(MENU_WIDTH, width - 16)); menuOpen = true; dirty = true; + lvglDirty = true; +} + +void MapView::showLvglPage(ListView& list) { + // Not on the stack: the app task also builds the LVGL widgets, which go deep + static const char* labels[LvglMenu::MAX_ROWS]; + static const char* details[LvglMenu::MAX_ROWS]; + const int count = std::min(list.count(), LvglMenu::MAX_ROWS); + for (int i = 0; i < count; i++) { + labels[i] = list.label(i); + details[i] = list.detail(i); + } + lvglMenu->showList(list.titleText(), labels, details, count, list.selected()); +} +void MapView::showLvglAbout() { + static const char* paragraphs[sizeof(ABOUT_PARAGRAPHS) / sizeof(ABOUT_PARAGRAPHS[0])]; + static char boardLine[ABOUT_LINE_LENGTH]; + snprintf(boardLine, sizeof(boardLine), "Screen %d x %d, %s", width, height, input->hasKeyboard() ? "with a keyboard" : "touch only"); + int count = 0; + for (const char* paragraph : ABOUT_PARAGRAPHS) { + if (paragraph == nullptr) { + paragraph = boardLine; + } else if (paragraph == ABOUT_SCROLL_HINT) { + paragraph = input->hasKeyboard() ? "W/S or drag to scroll. Esc, Backspace or < go back." : "Drag to scroll. < goes back."; + } + paragraphs[count++] = paragraph; + } + lvglMenu->showText("About and licences", paragraphs, count); +} + +MapView::LvglView MapView::wantedLvglView() { + if (dialog.isOpen() || prompt.isOpen() || workCard.isOpen() || downloadCard.isOpen()) { + return LvglView::None; + } + if (menuOpen) { + return mainMenuOpen() ? LvglView::MainMenu : LvglView::Popup; + } + if (screen == Screen::About) { + return LvglView::About; + } + return activeList() != nullptr ? LvglView::Page : LvglView::None; +} + +namespace { + +/** FNV-1a over a list's title, rows and selection: a page that was filled again shows again. */ +uint32_t listSignature(const ListView& list) { + uint32_t hash = 2166136261u; + auto mix = [&hash](const char* text) { + for (const char* at = text; *at != '\0'; at++) { + hash = (hash ^ static_cast(*at)) * 16777619u; + } + hash = (hash ^ 0xFFu) * 16777619u; + }; + mix(list.titleText()); + for (int i = 0; i < list.count(); i++) { + mix(list.label(i)); + mix(list.detail(i)); + } + return hash; +} + +} // namespace + +void MapView::syncLvgl() { + // The map's toast is under an LVGL page: it shows over it too + lvglMenu->setToast(toastUntil != 0 && lvglMenu->isShown() ? toastText : nullptr); + const LvglView wanted = wantedLvglView(); + if (wanted == LvglView::None) { + if (lvglView != LvglView::None) { + lvglMenu->hide(); + lvglView = LvglView::None; + } + lvglDirty = false; + return; + } + const uint32_t signature = wanted == LvglView::Page ? listSignature(*activeList()) : 0; + if (wanted == lvglView && !lvglDirty && signature == lvglSignature) { + return; + } + switch (wanted) { + case LvglView::MainMenu: + showLvglMainMenu(); + break; + case LvglView::Popup: + showLvglPage(menu); + break; + case LvglView::Page: + showLvglPage(*activeList()); + break; + case LvglView::About: + showLvglAbout(); + break; + default: + break; + } + lvglView = wanted; + lvglSignature = signature; + lvglDirty = false; +} + +void MapView::pollLvglMenu() { + LvglMenuEvent event; + while (lvglView != LvglView::None && lvglMenu->takeEvent(event)) { + dirty = true; + const LvglView view = lvglView; + if (view == LvglView::MainMenu) { + if (event.kind == LvglMenuEvent::Kind::Chosen) { + chooseMenuAction(static_cast(event.value)); + } else if (event.kind == LvglMenuEvent::Kind::Back) { + closeMenu(); + } + } else if (view == LvglView::Popup) { + if (event.kind == LvglMenuEvent::Kind::Chosen) { + menu.select(event.value); + handlePopupAction(UiAction::Chosen); + } else if (event.kind == LvglMenuEvent::Kind::Back) { + handlePopupAction(UiAction::Back); + } + } else if (view == LvglView::About) { + if (event.kind == LvglMenuEvent::Kind::Back) { + closeScreen(); + } + } else if (ListView* list = activeList()) { + if (event.kind == LvglMenuEvent::Kind::Chosen) { + list->select(event.value); + handleListAction(UiAction::Chosen); + } else if (event.kind == LvglMenuEvent::Kind::Back) { + handleListAction(UiAction::Back); + } else if (event.kind == LvglMenuEvent::Kind::Key && event.row >= 0) { + list->select(event.row); + if (event.value == 'r' || event.value == 'R') { + // Rename, where the page has it (maps, waypoints) + handleKey(event.value); + } else { + handleListAction(UiAction::Delete); + } + } + } + syncLvgl(); + if (lvglView != view || lvglDirty) { + // The rest was meant for the view that went + LvglMenuEvent stale; + while (lvglMenu->takeEvent(stale)) { + } + break; + } + } } + void MapView::readMainMenuState(MainMenuState& state) { state = {}; // While a download runs or is paused its details come first, so every input reaches Pause and Cancel @@ -178,7 +330,10 @@ void MapView::readMainMenuState(MainMenuState& state) { status.state == Downloader::State::Connecting; if (running || pausedRegion[0] != '\0') { const char* what = status.state == Downloader::State::Updating ? "Update" : "Download"; - if (running && status.total > 0) { + if (running && status.trails) { + // A trails query has no tiles to count: the server takes up to a minute + snprintf(state.download, sizeof(state.download), "Downloading trails"); + } else if (running && status.total > 0) { snprintf(state.download, sizeof(state.download), "%s %d %%", what, static_cast(status.done * 100 / status.total)); } else { snprintf(state.download, sizeof(state.download), "%s %s", what, running ? "starting" : "paused"); @@ -195,37 +350,48 @@ void MapView::readMainMenuState(MainMenuState& state) { } void MapView::buildMainMenu() { - const uint16_t focus = menuGrid.focusAction(); - const bool shown = menuGrid.focusShown(); readMainMenuState(menuShown); - menuGrid.clear(); - menuGrid.setTitle("Menu"); - menuGrid.setGrid(3, 3); - menuGrid.setCorner(static_cast(MenuAction::Exit), "Exit"); - // Only a board with a typing keyboard has keys to tell about; touch and trackball need no explanation - menuGrid.setHint(input.hasKeyboard() ? "WASD: move Enter: open Esc: close" : nullptr); + lvglDirty = true; +} + +void MapView::showLvglMainMenu() { + // The nine tiles as on the tile grid, always one page; what is going on (a download, the route) goes in the toolbar + static LvglMenuTile tiles[LvglMenu::MAX_TILES]; + int count = 0; for (const MenuEntry& entry : MENU_ENTRIES) { - const char* detail = nullptr; - if (entry.action == MenuAction::Location) { - detail = menuShown.locationOn ? "On" : "Off"; - } else if (entry.action == MenuAction::Track && menuShown.track != 0) { - detail = menuShown.track == 2 ? "Paused" : "Recording"; - } - menuGrid.addTile(static_cast(entry.action), entry.icon, entry.label, detail); - } + LvglMenuTile& tile = tiles[count++]; + tile.action = static_cast(entry.action); + // A paused recording shows the pause sign. Location on or off says a toast when it is toggled + tile.icon = entry.action == MenuAction::Track && menuShown.track == 2 ? MenuIcon::Pause : entry.icon; + snprintf(tile.label, sizeof(tile.label), "%s", entry.label); + tile.highlighted = false; + } + // A running download is the title ("Update 79 %"), its button opens the download card + const char* title = menuShown.download[0] != '\0' ? menuShown.download : "Menu"; + LvglMenuButton buttons[3]; + int buttonCount = 0; if (menuShown.download[0] != '\0') { - menuGrid.addStatus(static_cast(MenuAction::DownloadDetails), MenuIcon::Download, menuShown.download); - } - if (menuShown.route == 2) { - menuGrid.addStatus(static_cast(MenuAction::RouteStop), MenuIcon::Stop, "Stop"); - } else if (menuShown.route == 1) { - menuGrid.addStatus(static_cast(MenuAction::RouteShow), MenuIcon::Route, "Show route"); + buttons[buttonCount++] = { static_cast(MenuAction::DownloadDetails), LVGL_ICON_SHARED_DOWNLOAD }; } if (menuShown.route != 0) { - menuGrid.addStatus(static_cast(MenuAction::RouteClear), MenuIcon::Clear, "Clear route"); + buttons[buttonCount++] = { static_cast(MenuAction::RouteMenu), LVGL_ICON_SHARED_NAVIGATION }; } - menuGrid.layout(width, height, overlay.font(), &overlay.smallFont()); - menuGrid.setFocusAction(focus, shown); + buttons[buttonCount++] = { static_cast(MenuAction::Exit), LVGL_ICON_SHARED_CLOSE }; + lvglMenu->showGrid(title, tiles, count, lastMenuFocus, buttons, buttonCount); +} + +void MapView::openRouteActions() { + beginPopup(Popup::RouteActions, "Route"); + if (menuShown.route == 2) { + menu.add("Stop navigation"); + popupActions[popupActionCount++] = static_cast(MenuAction::RouteStop); + } else { + menu.add("Show route"); + popupActions[popupActionCount++] = static_cast(MenuAction::RouteShow); + } + menu.add("Clear route"); + popupActions[popupActionCount++] = static_cast(MenuAction::RouteClear); + layoutPopup(); } void MapView::refreshMainMenu() { @@ -239,17 +405,12 @@ void MapView::refreshMainMenu() { void MapView::openMenu() { buildMainMenu(); - // It opens where it was left, without a highlight until the first key or trackball step - menuGrid.setFocusAction(lastMenuFocus, false); popup = Popup::Main; menuOpen = true; dirty = true; } void MapView::closeMenu() { - if (mainMenuOpen()) { - lastMenuFocus = menuGrid.focusAction(); - } menuOpen = false; dirty = true; } @@ -263,15 +424,6 @@ void MapView::openDownloadChoice() { layoutPopup(); } -void MapView::handleMainMenuEvent(const GridEvent& event) { - dirty = true; - if (event.result == GridResult::Chosen) { - chooseMenuAction(static_cast(event.action)); - } else if (event.result == GridResult::Back) { - closeMenu(); - } -} - void MapView::chooseMenuAction(MenuAction action) { dirty = true; if (action == MenuAction::Location) { @@ -331,6 +483,9 @@ void MapView::chooseMenuAction(MenuAction action) { returnToMenu = false; openSearch(); break; + case MenuAction::RouteMenu: + openRouteActions(); + break; case MenuAction::Exit: // The only way out by trackball or touch, LVGL's swipe back does not run while the map has the screen exitRequested = true; @@ -349,7 +504,7 @@ void MapView::handlePopupAction(UiAction action) { if (action == UiAction::Back) { // Sub-menus go back to the menu, the actions of a row back to their list, the menu closes closeMenu(); - if (kind == Popup::DownloadChoice || kind == Popup::Track) { + if (kind == Popup::DownloadChoice || kind == Popup::Track || kind == Popup::RouteActions) { openMenu(); } return; @@ -401,6 +556,10 @@ void MapView::handlePopupAction(UiAction action) { closeMenu(); chooseRouteStart(chosen); break; + case Popup::RouteActions: + closeMenu(); + chooseMenuAction(static_cast(chosen)); + break; } } @@ -1007,7 +1166,7 @@ void MapView::fillSettingList() { const int selected = settingList.selected(); // Filled again after each change: the list stays where it was scrolled to const int scrolled = settingList.scrollTop(); - fillSettingsList(settingList, settings, monochrome); + fillSettingsList(settingList, settings, monochrome, renderScaleAvailable(), defaultRenderPercent()); setListHint(settingList, "Enter: change Esc: back", "Tap: change Swipe right: back"); settingList.layoutFullScreen(width, height, overlay.font()); settingList.restoreScroll(scrolled); @@ -1074,6 +1233,16 @@ void MapView::toggleSetting(SettingItem item) { worker.setTerrain(settings.terrain); downloader.setTerrainWithDownloads(settings.terrain); break; + case SettingItem::RenderScale: + if (!renderScaleAvailable()) { + showToast("Needs a PPA (ESP32-P4, S31)"); + dirty = true; + return; + } + // Default, 100, 75, 50, default...; the frame size is chosen when the app starts + settings.renderScale = settings.renderScale <= 0 ? 100 : (settings.renderScale > 75 ? 75 : (settings.renderScale > 50 ? 50 : 0)); + showToast("Restart Maps to apply"); + break; case SettingItem::PointerSpeed: settings.pointerSpeed = (settings.pointerSpeed + 1) % PointerAcceleration::SPEEDS; pointerAcceleration.setSpeed(settings.pointerSpeed); @@ -1141,11 +1310,11 @@ void MapView::drawAbout() { if (aboutLines == 0) { // Wrapped once when the page opens char boardLine[ABOUT_LINE_LENGTH]; - snprintf(boardLine, sizeof(boardLine), "Screen %d x %d, %s", width, height, input.hasKeyboard() ? "with a keyboard" : "touch only"); + snprintf(boardLine, sizeof(boardLine), "Screen %d x %d, %s", width, height, input->hasKeyboard() ? "with a keyboard" : "touch only"); for (const char* paragraph : ABOUT_PARAGRAPHS) { if (paragraph == nullptr) { paragraph = boardLine; - } else if (paragraph == ABOUT_SCROLL_HINT && !input.hasKeyboard()) { + } else if (paragraph == ABOUT_SCROLL_HINT && !input->hasKeyboard()) { paragraph = "Drag to scroll. < or a swipe to the right goes back."; } if (aboutLines >= ABOUT_LINES) { diff --git a/Apps/Maps/main/Source/app/MapSearch.cpp b/Apps/Maps/main/Source/app/MapSearch.cpp index 1829ee57..cfa52a75 100644 --- a/Apps/Maps/main/Source/app/MapSearch.cpp +++ b/Apps/Maps/main/Source/app/MapSearch.cpp @@ -291,9 +291,9 @@ void MapView::openSearch() { return; } searchSheet.open(); - searchSheet.setTypingKeyboard(input.hasKeyboard()); + searchSheet.setTypingKeyboard(input->hasKeyboard()); // "Roll" only where there is a trackball to roll (a keyboard-only board moves with Tab) - searchSheet.setTrackball(input.hasTrackball()); + searchSheet.setTrackball(input->hasTrackball()); int count = 0; const SearchCategory* categories = SearchEngine::categories(&count); const char* names[SearchSheet::MAX_CATEGORIES]; @@ -495,7 +495,7 @@ void MapView::openSearchResult(const char* name, const char* type, int32_t x, in if (box != nullptr) { // A street: zoomed so its box fits the screen const double metres = std::max(box[2] - box[0], box[3] - box[1]) * routeMetresPerUnit(y); - const double metresPerPixel = metres / (std::min(width, height) * 0.8); + const double metresPerPixel = metres / (std::min(width, height) * 0.8 / magnify); targetZoom = static_cast(std::floor(std::log(156543.03 * std::cos(lat * 3.14159265358979 / 180.0) / std::max(0.3, metresPerPixel)) / std::log(2.0))); targetZoom = std::clamp(targetZoom, 12, 18); } diff --git a/Apps/Maps/main/Source/app/MapView.cpp b/Apps/Maps/main/Source/app/MapView.cpp index cb03b998..87128ac4 100644 --- a/Apps/Maps/main/Source/app/MapView.cpp +++ b/Apps/Maps/main/Source/app/MapView.cpp @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-3.0-or-later #include "MapView.h" #include "MapViewInternal.h" +#include "LvglMenu.h" #include "../ui/Metrics.h" @@ -31,11 +32,30 @@ namespace maps { namespace { +/** The tile cache takes at most this share of the PSRAM that is free when the map starts. */ +constexpr size_t TILE_CACHE_MAX_SHARE_PERCENT = 40; + +/** The density the map's pixel sizes were made for: the T-Deck's display. */ +constexpr float REFERENCE_DPI = 143.0f; + /** - * 2.5 MB of rendered tiles in PSRAM, enough for a screen and its neighbours at two zoom levels. With 28 a download of - * low-zoom tiles (up to 1.2 MB each) started with only 0.5 MB of PSRAM free and failed. + * Rendered tiles (128 KB each) for this screen: every tile that a view turned any way can show (the box around the + * screen's diagonal, tiles not aligned with it), the spare slots for the magnified ancestors while tiles render, and a + * few of the ring around the screen, for panning. 17 on the T-Deck (was a fixed 20: 2.5 MB), 35 on 800 x 480, 47 on 1024 x 600. + * Limited by the PSRAM that is free, but never below what the screen shows, or tiles are drawn again and again. */ -constexpr int TILE_CACHE_SLOTS = 20; +int tileCacheSlots(int width, int height, size_t freePsram) { + const double diagonal = std::sqrt(static_cast(width) * width + static_cast(height) * height); + const int span = static_cast(std::ceil(diagonal / TILE_SIZE)) + 1; + const int visible = span * span; + const int wanted = std::max(TileWorker::MIN_CACHE_SLOTS, visible + TileWorker::CACHE_SPARE_SLOTS + span - 1); + const int affordable = static_cast(freePsram / 100 * TILE_CACHE_MAX_SHARE_PERCENT / TileCache::TILE_BYTES); + const int floor = std::max(TileWorker::MIN_CACHE_SLOTS, visible + TileWorker::CACHE_SPARE_SLOTS); + if (affordable < floor) { + logError("Tile cache: %d slots wanted for %dx%d, PSRAM allows %d", floor, width, height, affordable); + } + return std::max(floor, std::min(wanted, affordable)); +} constexpr uint32_t LOOP_INTERVAL_MS = 15; constexpr uint32_t POINTER_HIDE_MS = 3000; /** Idle-time updates start after this long without input, on Wi-Fi, charging or above UPDATE_MIN_BATTERY percent. */ @@ -61,11 +81,21 @@ constexpr int MIN_LINE_HEIGHT = 15; } // namespace -bool MapView::begin(Device* display, const char* root, const char* dataPath) { +void MapView::setStartView(bool hasPosition, double lat, double lon, int zoomLevel) { + hasStartPosition = hasPosition; + launchLat = std::clamp(lat, -MAX_LATITUDE, MAX_LATITUDE); + launchLon = std::clamp(lon, -180.0, 180.0); + startZoom = zoomLevel < 0 ? -1 : std::min(zoomLevel, MAX_VIEW_ZOOM); +} + +bool MapView::begin(FrameOutput& frameOutput, Input& inputSource, const char* root, const char* dataPath) { // Idle time is counted from the start, not from boot lastInputAt = nowMs(); snprintf(rootPath, sizeof(rootPath), "%s", root); - if (!openDisplay(display)) { + output = &frameOutput; + input = &inputSource; + lvglMenu = output->lvglMenu(); + if (!openDisplay()) { return false; } // From here on only the I/O task touches the SD card @@ -88,15 +118,30 @@ bool MapView::begin(Device* display, const char* root, const char* dataPath) { // Marked trails are drawn in the outdoor style only (decided 23 Nov 2026) worker.setTrails(palette->outdoor); startLabels(root); - if (!worker.start(&store, &io, palette, TILE_CACHE_SLOTS, root)) { + // The cache holds the tiles of the screen in map pixels + const int mapWidth = static_cast(std::ceil(width / magnify)); + const int mapHeight = static_cast(std::ceil(height / magnify)); + if (!worker.start(&store, &io, palette, tileCacheSlots(mapWidth, mapHeight, heap_caps_get_free_size(MALLOC_CAP_SPIRAM)), root)) { return false; } startServices(root); - if (hasSavedView) { - centerOn(savedView.lat, savedView.lon, savedView.zoom); - } else { - centerOn(DEFAULT_LAT, DEFAULT_LON, DEFAULT_ZOOM); + { + double lat = hasSavedView ? savedView.lat : DEFAULT_LAT; + double lon = hasSavedView ? savedView.lon : DEFAULT_LON; + int viewZoom = hasSavedView ? savedView.zoom : DEFAULT_ZOOM; + if (hasStartPosition) { + lat = launchLat; + lon = launchLon; + launchPinShown = true; + } + if (startZoom >= 0) { + viewZoom = startZoom; + } + if (hasStartPosition || startZoom >= 0) { + logInfo("Opening at %.6f, %.6f, zoom %d (command line)", lat, lon, viewZoom); + } + centerOn(lat, lon, viewZoom); } viewReady = true; @@ -110,17 +155,20 @@ bool MapView::begin(Device* display, const char* root, const char* dataPath) { return true; } -bool MapView::openDisplay(Device* display) { - if (!output.begin(display)) { - logError("Display output failed"); - return false; - } - width = output.width(); - height = output.height(); - monochrome = output.isMonochrome(); +bool MapView::openDisplay() { + width = output->width(); + height = output->height(); + // The T-Deck's 143 dpi is the map's own size; denser screens magnify it in quarter steps, up to three times + if (output->dpi() > 0) { + const float steps = std::floor(output->dpi() / REFERENCE_DPI * 4.0f + 0.5f); + magnify = std::clamp(steps / 4.0f, 1.0f, 3.0f); + } + logInfo("Magnify %.2f (%d dpi)", static_cast(magnify), output->dpi()); + metrics::setScale(magnify); + monochrome = output->isMonochrome(); palette = monochrome ? &monochromePalette() : &colorPalette(); theme = uiTheme(*palette, monochrome); - frame = static_cast(largeAlloc(static_cast(width) * height * sizeof(uint16_t))); + frame = output->drawBuffer(); preview = static_cast(largeAlloc(TileCache::TILE_BYTES)); scratch = static_cast(largeAlloc(sizeof(AffineScratch))); if (frame == nullptr || preview == nullptr || scratch == nullptr) { @@ -153,17 +201,21 @@ void MapView::loadSavedState(const char* root, const char* dataPath) { regionsFound = store.scanRegions(); char folder[160]; snprintf(folder, sizeof(folder), "%s/cache/fonts", dataPath); - if (!normalFont.borrow(FONT_SIZE_DEFAULT) && !normalFont.open(folder, NORMAL_FONTS, 3)) { - logError("No font from the system or in %s, the map shows no text", folder); - } - if (!smallFont.borrow(FONT_SIZE_SMALL)) { - smallFont.open(folder, SMALL_FONTS, 1); + // A frame the PPA scales up would show the system's fonts (sized for the screen) too large: it takes the + // label fonts made for its own density instead, once they exist + if (!openFrameFonts(root)) { + if (!normalFont.borrow(FONT_SIZE_DEFAULT) && !normalFont.open(folder, NORMAL_FONTS, 3)) { + logError("No font from the system or in %s, the map shows no text", folder); + } + if (!smallFont.borrow(FONT_SIZE_SMALL)) { + smallFont.open(folder, SMALL_FONTS, 1); + } + largeFont.borrow(FONT_SIZE_LARGE); } - largeFont.borrow(FONT_SIZE_LARGE); // The label fonts made on an earlier run; the ones missing are made in the background after the labels start for (int i = 0; i < LabelFontMaker::COUNT; i++) { char fontPath[200]; - LabelFontMaker::cachePath(root, i, fontPath, sizeof(fontPath)); + LabelFontMaker::cachePath(root, i, magnify, fontPath, sizeof(fontPath)); if (!fileExists(fontPath) || !labelFonts[i].openFile(fontPath)) { missingLabelFonts |= 1u << i; } @@ -201,21 +253,21 @@ void MapView::startLabels(const char* root) { if (labelsReady && missingLabelFonts != 0) { char ttfPath[260]; app_paths_get_assets_path(APP_ID, "fonts/LabelSans.ttf", ttfPath, sizeof(ttfPath)); - fontMaker.configure(io, root, ttfPath); + fontMaker.configure(io, root, ttfPath, magnify); fontMaker.start(missingLabelFonts); } } void MapView::startServices(const char* root) { - input.begin(); + input->begin(); haptic.begin(); pointerAcceleration.setSpeed(settings.pointerSpeed); cursorX = width / 2; cursorY = height / 2; // The overlay adapts to the inputs the board has: key hints with a keyboard, focus without touch or pointer controls.setStyleButton(!monochrome); - controls.setInputs({ input.hasKeyboard(), input.hasTouch(), input.hasPointer() }); - metrics::setKeyboard(input.hasKeyboard()); + controls.setInputs({ input->hasKeyboard(), input->hasTouch(), input->hasPointer() }); + metrics::setKeyboard(input->hasKeyboard()); layoutControls(); downloadView = downloadLayout(width, height, overlay.font().lineHeight()); downloader.setTiming(settings.devProbe); @@ -245,8 +297,21 @@ void MapView::startServices(const char* root) { } void MapView::end() { + // Closing can take long (a request that waits for the server): the log says which part, when it does + uint32_t stepStart = nowMs(); + const uint32_t endStart = stepStart; + char slowSteps[160] = ""; + auto step = [&](const char* name) { + const uint32_t now = nowMs(); + if (now - stepStart >= 200) { + const size_t used = strlen(slowSteps); + snprintf(slowSteps + used, sizeof(slowSteps) - used, "%s%s %u ms", used > 0 ? ", " : "", name, static_cast(now - stepStart)); + } + stepStart = now; + }; // The index build stops first (its scratch files are removed), while the I/O task still runs searchIndexJob.stop(); + step("search index"); searchIndexJob.acknowledge(); releaseSearch(); if (searchEngine != nullptr) { @@ -260,12 +325,14 @@ void MapView::end() { recentSearches = nullptr; } searchTask.stop(); + step("search"); if (viewReady) { saveView(); viewReady = false; } // The track file gets its end tags; recording only runs while the app is open recorder.stop(io, nowMs()); + step("track"); for (int wait = 0; gpxImport.state() == GpxImport::State::Busy && wait < 500; wait++) { vTaskDelay(pdMS_TO_TICKS(10)); } @@ -278,16 +345,21 @@ void MapView::end() { } } fontMaker.stop(); + step("fonts"); // The probe first: it reads the state of the download, browse, I/O and render tasks, which are deleted below probe.stop(); browsedCounter.stop(); + step("browsed counter"); downloader.stop(); + step("downloader"); if (navigatorStarted) { navigator.stop(); navigatorStarted = false; } worker.stop(); + step("render lanes"); io.stop(); + step("I/O"); location.unsubscribe(); if (subscribed) { app_event_unsubscribe(&appEvents); @@ -297,9 +369,13 @@ void MapView::end() { task_event_group_destruct(&eventGroup); eventGroupReady = false; } - input.end(); + if (nowMs() - endStart >= 1000) { + logInfo("Closing took %u ms: %s", static_cast(nowMs() - endStart), slowSteps); + } + input->end(); haptic.end(); labels.end(); + releaseLabelIcons(); labelStore.end(); normalFont.close(); smallFont.close(); @@ -307,8 +383,6 @@ void MapView::end() { for (BinFontText& font : labelFonts) { font.close(); } - output.end(); - largeFree(frame); frame = nullptr; largeFree(preview); preview = nullptr; @@ -363,15 +437,16 @@ void MapView::updateWanted() { const int firstY = static_cast(std::floor(top / TILE_SIZE)) - 1; const int lastX = static_cast(std::floor((right - 1) / TILE_SIZE)) + 1; const int lastY = static_cast(std::floor((bottom - 1) / TILE_SIZE)) + 1; - TileKey tiles[TileWorker::MAX_WANTED]; - double distances[TileWorker::MAX_WANTED]; + // Not on the stack (1 KB): the app task's is tight + static TileKey tiles[TileWorker::MAX_WANTED]; + static double distances[TileWorker::MAX_WANTED]; int count = 0; const int tileCount = 1 << zoom; for (int y = firstY; y <= lastY; y++) { if (y < 0 || y >= tileCount) { continue; } - for (int x = firstX; x <= lastX && count < TileWorker::MAX_WANTED; x++) { + for (int x = firstX; x <= lastX; x++) { const double tileCenterX = (x + 0.5) * TILE_SIZE; const double tileCenterY = (y + 0.5) * TILE_SIZE; const bool visible = x > firstX && x < lastX && y > firstY && y < lastY; @@ -379,6 +454,13 @@ void MapView::updateWanted() { if (!visible) { distance += 1e6; } + if (count == TileWorker::MAX_WANTED) { + // Full (a very large screen): the farthest goes, so no visible tile of a later row is left out + if (distance >= distances[count - 1]) { + continue; + } + count--; + } int slot = count; while (slot > 0 && distances[slot - 1] > distance) { tiles[slot] = tiles[slot - 1]; @@ -589,11 +671,11 @@ void MapView::drawMap() { worker.lock(); const uint32_t locked = nowMs(); probe.phase("compose"); - if (isRotated()) { - // Turned: every pixel through the transform, tiles not ready stood in for by cached ancestors or children; - // nearest pixel while it moves, bilinear once it settled + if (isRotated() || magnify != 1.0f) { + // Turned or magnified: every pixel through the transform, tiles not ready stood in for by cached ancestors or + // children; nearest pixel while it moves, bilinear once it settled const bool bilinear = isSmoothView(); - composeAffine(frame, width, height, scaledView(centerX, centerY, zoom, 1.0f, width / 2.0f, height / 2.0f, width, height, bearingCos, bearingSin), + composeAffine(frame, width, height, scaledView(centerX, centerY, zoom, magnify, width / 2.0f, height / 2.0f, width, height, bearingCos, bearingSin), lookupCached, this, palette->placeholder, *scratch, bilinear); if (bilinear && !smooth.logged) { smooth.logged = true; @@ -624,7 +706,7 @@ void MapView::drawMap() { if (position.state() == PositionState::Approximate) { overlay.drawApproximateMarker(canvas, markerX, markerY, position.fix().accuracy, *palette); } else { - const float radius = position.accuracyRadius(metresPerPixel(position.fix().latitude, zoom)); + const float radius = position.accuracyRadius(metresPerPixel(position.fix().latitude, zoom) / magnify); overlay.drawAccuracyCircle(canvas, markerX, markerY, radius, *palette); overlay.drawMarker(canvas, markerX, markerY, position.showsArrow(), position.fix().course - bearing, *palette); } @@ -705,7 +787,7 @@ void MapView::drawWorkDot() { } bool MapView::wantsTouchKeyboard() const { - if (input.hasKeyboard() || !input.hasTouch()) { + if (input->hasKeyboard() || !input->hasTouch()) { return false; } return prompt.isOpen() || searchSheet.isOpen() || (sheet.isOpen() && sheet.mode() == WaypointSheet::Mode::New && sheet.isEditable()); @@ -752,13 +834,13 @@ void MapView::drawScaledMap() { worldY = pinchWorldY * factor; anchorX = static_cast(pinchX); anchorY = static_cast(pinchY); - view = scaledView(worldX, worldY, base, scale, anchorX, anchorY, width, height, bearingCos, bearingSin); + view = scaledView(worldX, worldY, base, scale * magnify, anchorX, anchorY, width, height, bearingCos, bearingSin); } else if (turn.active) { // Turning around the screen centre at the current zoom const float t = std::min(1.0f, static_cast(start - turn.startMs) / TURN_ANIMATION_MS); const float eased = 1.0f - (1.0f - t) * (1.0f - t); const float radians = (turn.from + (turn.to - turn.from) * eased) * 0.017453292f; - view = scaledView(centerX, centerY, zoom, 1.0f, width / 2.0f, height / 2.0f, width, height, std::cos(radians), std::sin(radians)); + view = scaledView(centerX, centerY, zoom, magnify, width / 2.0f, height / 2.0f, width, height, std::cos(radians), std::sin(radians)); } else { const float t = std::min(1.0f, static_cast(start - animation.startMs) / ZOOM_ANIMATION_MS); const float eased = 1.0f - (1.0f - t) * (1.0f - t); @@ -767,7 +849,7 @@ void MapView::drawScaledMap() { worldY = animation.worldY; anchorX = animation.anchorX; anchorY = animation.anchorY; - view = scaledView(worldX, worldY, zoom, scale, anchorX, anchorY, width, height, bearingCos, bearingSin); + view = scaledView(worldX, worldY, zoom, scale * magnify, anchorX, anchorY, width, height, bearingCos, bearingSin); } worker.lock(); const uint32_t locked = nowMs(); @@ -817,7 +899,7 @@ void MapView::render() { overlay.setBottomInset(screen == Screen::Download ? downloadView.bar.height : 0); if (screen == Screen::Map) { const double lat = worldYToLat(centerY, zoom); - overlay.drawScaleBar(canvas, metresPerPixel(lat, zoom), *palette); + overlay.drawScaleBar(canvas, metresPerPixel(lat, zoom) / magnify, *palette); } // The full attribution shows for a few seconds, then collapses into a mark that opens it again if (screen == Screen::Download) { @@ -846,7 +928,7 @@ void MapView::render() { drawOverlays(); const uint32_t presentStart = nowMs(); probe.phase("display"); - output.present(frame, 0, height); + presentFrame(); probe.phase("after display"); dirty = false; const uint32_t frameEnd = nowMs(); @@ -859,6 +941,13 @@ void MapView::render() { noteViewComplete(start); } +void MapView::presentFrame() { + output->present(); + // The output can hand out another buffer for the next frame + frame = output->drawBuffer(); + canvas.pixels = frame; +} + void MapView::endAnimations(uint32_t start) { if (animation.active && (pinching || isFullScreen() || start - animation.startMs >= ZOOM_ANIMATION_MS)) { animation.active = false; @@ -889,7 +978,7 @@ void MapView::drawAnimationFrame(uint32_t start) { overlay.setBottomInset(0); } overlay.drawAttributionMark(canvas, *palette); - output.present(frame, 0, height); + presentFrame(); if (animation.active || turn.active) { if (animation.active && nowMs() - start > animation.slowestFrameMs) { animation.slowestFrameMs = nowMs() - start; @@ -912,10 +1001,10 @@ void MapView::drawMapUi() { // The crosshair Enter picks places from: dark with a light rim, like the pointer const auto x = static_cast(width / 2); const auto y = static_cast(height / 2); - canvas.line(x - 7.0f, y, x + 7.0f, y, 3.0f, theme.panel); - canvas.line(x, y - 7.0f, x, y + 7.0f, 3.0f, theme.panel); - canvas.line(x - 6.0f, y, x + 6.0f, y, 1.5f, theme.text); - canvas.line(x, y - 6.0f, x, y + 6.0f, 1.5f, theme.text); + canvas.line(x - metrics::px(7.0f), y, x + metrics::px(7.0f), y, metrics::px(3.0f), theme.panel); + canvas.line(x, y - metrics::px(7.0f), x, y + metrics::px(7.0f), metrics::px(3.0f), theme.panel); + canvas.line(x - metrics::px(6.0f), y, x + metrics::px(6.0f), y, metrics::px(1.5f), theme.text); + canvas.line(x, y - metrics::px(6.0f), x, y + metrics::px(6.0f), metrics::px(1.5f), theme.text); } if (sheet.isOpen() && searchPinShown) { // The place of the chosen search result @@ -924,8 +1013,8 @@ void MapView::drawMapUi() { worldToScreenOffset(lonToWorldX(searchPinLon, zoom) - centerX, latToWorldY(searchPinLat, zoom) - centerY, sx, sy); const auto px = static_cast(sx + width / 2.0); const auto py = static_cast(sy + height / 2.0); - canvas.fillCircle(px, py, 7.0f, theme.panel); - canvas.fillCircle(px, py, 5.0f, theme.danger); + canvas.fillCircle(px, py, metrics::px(7.0f), theme.panel); + canvas.fillCircle(px, py, metrics::px(5.0f), theme.danger); } if (sheet.isOpen()) { sheet.draw(canvas, sheetFont(), theme); @@ -942,13 +1031,6 @@ void MapView::drawMapUi() { } void MapView::drawOverlays() { - if (menuOpen) { - if (mainMenuOpen()) { - menuGrid.draw(canvas, overlay.font(), theme); - } else { - menu.draw(canvas, overlay.font(), theme); - } - } if (dialog.isOpen()) { dialog.draw(canvas, overlay.font(), theme); } @@ -970,14 +1052,14 @@ void MapView::drawOverlays() { if (static_cast(nowMs() - toastUntil) < 0) { overlay.drawToast(canvas, toastText, theme); } - if (cursorShown && input.hasPointer()) { + if (cursorShown && input->hasPointer()) { // An arrow pointer, dark with a light rim so it shows on any map and screen const auto x = static_cast(cursorX); const auto y = static_cast(cursorY); - canvas.line(x, y, x, y + 13.0f, 4.0f, theme.panel); - canvas.line(x, y, x + 9.0f, y + 9.0f, 4.0f, theme.panel); - canvas.line(x, y, x, y + 13.0f, 2.0f, theme.text); - canvas.line(x, y, x + 9.0f, y + 9.0f, 2.0f, theme.text); + canvas.line(x, y, x, y + metrics::px(13.0f), metrics::px(4.0f), theme.panel); + canvas.line(x, y, x + metrics::px(9.0f), y + metrics::px(9.0f), metrics::px(4.0f), theme.panel); + canvas.line(x, y, x, y + metrics::px(13.0f), metrics::px(2.0f), theme.text); + canvas.line(x, y, x + metrics::px(9.0f), y + metrics::px(9.0f), metrics::px(2.0f), theme.text); } } @@ -1077,7 +1159,8 @@ void MapView::saveView() { void MapView::saveShot(const char* name) { char path[PATH_MAX_LENGTH]; snprintf(path, sizeof(path), "%s/%s.bmp", rootPath, name); - auto save = [&] { return saveBmp(path, frame, width, height); }; + const uint16_t* shown = output->shownBuffer(); + auto save = [&] { return saveBmp(path, shown, width, height); }; logInfo("Screenshot %s: %s", path, runOnCard(io, save) ? "saved" : "failed"); } @@ -1086,7 +1169,7 @@ void MapView::saveShot(const char* name) { void MapView::pollKeys(uint32_t now) { KeyEvent events[8]; - const int count = input.readKeys(events, 8); + const int count = input->readKeys(events, 8); bool enterThisPoll = false; if (count > 0) { markInput(now); @@ -1106,10 +1189,10 @@ void MapView::pollKeys(uint32_t now) { enterLong = true; longClick(); } - if (input.takeDevicesChanged()) { + if (input->takeDevicesChanged()) { // The trackball was switched between keyboard and mouse mode - controls.setInputs({ input.hasKeyboard(), input.hasTouch(), input.hasPointer() }); - metrics::setKeyboard(input.hasKeyboard()); + controls.setInputs({ input->hasKeyboard(), input->hasTouch(), input->hasPointer() }); + metrics::setKeyboard(input->hasKeyboard()); cursorShown = false; pointerAcceleration.reset(); // The download card's key hint comes or goes: laid out again so it does not overlap the buttons @@ -1223,11 +1306,20 @@ void MapView::run() { const uint32_t now = nowMs(); probe.heartbeat(now); probe.phase("keys"); - pollKeys(now); + syncLvgl(); + const bool lvglMenuInput = lvglMenu->isShown(); + input->setUiActive(lvglMenuInput); + if (lvglMenuInput) { + pollLvglMenu(); + } else { + pollKeys(now); + } const uint32_t afterKeys = nowMs(); probe.phase("pointer"); - handleMouse(now); - handleTouch(now); + if (!lvglMenuInput) { + handleMouse(now); + handleTouch(now); + } const uint32_t afterInput = nowMs(); updateIdle(now); const uint32_t afterLocation = nowMs(); diff --git a/Apps/Maps/main/Source/app/MapView.h b/Apps/Maps/main/Source/app/MapView.h index 6ed37d85..a05c49eb 100644 --- a/Apps/Maps/main/Source/app/MapView.h +++ b/Apps/Maps/main/Source/app/MapView.h @@ -4,7 +4,7 @@ #include "../platform/Version.h" #include "BinFontText.h" #include "Debug.h" -#include "DisplayOutput.h" +#include "FrameOutput.h" #include "Downloader.h" #include "Haptic.h" #include "ElevationJob.h" @@ -49,7 +49,6 @@ #include "../ui/Settings.h" #include "../ui/GpxLayer.h" #include "../ui/Waypoints.h" -#include "../ui/TileGrid.h" #include "../ui/Widgets.h" #include @@ -60,6 +59,8 @@ namespace maps { +class LvglMenu; + struct AffineScratch; constexpr const char* APP_ID = "tactility.maps"; @@ -110,12 +111,20 @@ enum class MenuAction : uint16_t { DownloadDetails, RouteShow, RouteStop, - RouteClear + RouteClear, + /** The LVGL menu's Route button: a popup with the route's actions. */ + RouteMenu }; class MapView { public: - bool begin(Device* display, const char* root, const char* dataPath); + /** The output and the input are the caller's, and outlive the view. */ + bool begin(FrameOutput& frameOutput, Input& inputSource, const char* root, const char* dataPath); + /** + * Where the map opens instead of the view it showed last: set before begin() (the command line's --lat, --lon, + * --zoom), marked with a pin. Without a position only the zoom changes; a negative zoom keeps the last one. + */ + void setStartView(bool hasPosition, double lat, double lon, int startZoom); void run(); void end(); @@ -134,7 +143,7 @@ class MapView { /** What the main menu shows apart from the fixed labels, to tell whether it has to be built again. */ struct MainMenuState { - char download[TileGrid::STATUS_LENGTH]; + char download[28]; /** 0: no route, 1: Show route, 2: Stop. */ uint8_t route; bool locationOn; @@ -145,6 +154,9 @@ class MapView { } }; + /** What the LVGL menu shows (LVGL output only). */ + enum class LvglView : uint8_t { None, MainMenu, Popup, Page, About }; + enum class Popup : uint8_t { Main, DownloadChoice, @@ -154,7 +166,9 @@ class MapView { /** A GPX file: show or hide it, follow it. */ GpxActions, /** Where a route starts when there is no GPS fix (M5c). */ - RouteStart + RouteStart, + /** The route's actions (LVGL menu): show it, stop following it, clear it. */ + RouteActions }; @@ -238,7 +252,7 @@ class MapView { void drawCompass(); void render(); /** The steps of begin(). */ - bool openDisplay(Device* display); + bool openDisplay(); /** Settings, saved view, regions, fonts and the debug script, read on the I/O task. */ void loadSavedState(const char* root, const char* dataPath); /** gpx/ at the top of the data volume (the SD card), where users drop their files. */ @@ -262,6 +276,8 @@ class MapView { InputLayer inputLayer() const; /** The parts of a frame (render). */ void endAnimations(uint32_t start); + /** Shows the frame, and takes the buffer for the next one. */ + void presentFrame(); /** While pinching, zooming or turning: the cached tiles scaled live, with the frame of the download screen. */ void drawAnimationFrame(uint32_t start); /** On the map screen: compass, buttons, crosshair, search pin, sheet, route card, navigation bar, start picking. */ @@ -295,6 +311,13 @@ class MapView { /** Gives the labels the fonts of the app where they opened, else the system's. */ void applyLabelFonts(); void applyLabelSettings(); + /** Frees the POI icons resampled for the screen. */ + void releaseLabelIcons(); + /** Opens the label fonts as the UI's fonts when the frame is scaled up (see FrameOutput::isScaledUp); false otherwise. */ + bool openFrameFonts(const char* root); + /** Whether the map can be drawn smaller and scaled up (Settings::renderScale). */ + bool renderScaleAvailable() const { return output != nullptr && output->canScale(); } + int defaultRenderPercent() const { return output != nullptr ? output->defaultRenderPercent() : 100; } void drawStatus(); /** Opens the details of the running download, from a tap on the progress pill or Menu, Download. */ void openDownloadCard(); @@ -355,10 +378,12 @@ class MapView { bool mainMenuOpen() const { return menuOpen && popup == Popup::Main; } /** Fills the grid from the current state (tiles, details, status strip), keeping the focus. */ void buildMainMenu(); + /** The main menu as LVGL tiles, from menuShown. */ + void showLvglMainMenu(); + void openRouteActions(); /** While the grid is open: builds it again when what it shows has changed. */ void refreshMainMenu(); void readMainMenuState(MainMenuState& state); - void handleMainMenuEvent(const GridEvent& event); void chooseMenuAction(MenuAction action); /** Adds a waypoint at the map centre, from the first row of the waypoint list. */ void addWaypointHere(); @@ -370,6 +395,16 @@ class MapView { /** Opens a popup of kind with a title; rows are added to menu by the caller before layoutPopup(). */ void beginPopup(Popup kind, const char* title); void layoutPopup(); + /** The LVGL menu follows menuOpen, and while it is shown it has the input: its events come here. */ + void pollLvglMenu(); + /** + * Makes the LVGL menu show what the map's state says, one view at a time: the main menu or a popup while menuOpen, + * otherwise a list page or About. Nothing while a dialog, prompt or card is open: the map draws those. + */ + void syncLvgl(); + LvglView wantedLvglView(); + void showLvglPage(ListView& list); + void showLvglAbout(); /** Back one level from a list, the popup or About: Swipe right, < or Esc. */ void goBack(); void openRegions(); @@ -508,9 +543,17 @@ class MapView { /** Sets a list's hint for the inputs this board has. */ void setListHint(ListView& list, const char* keyHint, const char* touchHint); - DisplayOutput output; + FrameOutput* output = nullptr; IoTask io; - Input input; + Input* input = nullptr; + /** The menus as LVGL widgets (LVGL output only); null when the map draws them. */ + LvglMenu* lvglMenu = nullptr; + /** What the LVGL menu shows, as syncLvgl() last made it. */ + LvglView lvglView = LvglView::None; + /** The menu or popup was filled again: syncLvgl() shows it again. */ + bool lvglDirty = false; + /** The shown page's content, to see when it was filled again. */ + uint32_t lvglSignature = 0; /** The vibration motor, on boards that have one: a pulse before each turn, two when off the route or arrived. */ Haptic haptic; /** The step whose turn was felt already (-2: none). */ @@ -614,9 +657,8 @@ class MapView { /** The popup over the screen: the menu, its sub-menus, or the actions of a row in a list. */ ListView menu; /** The main menu: open when menuOpen and popup is Main. */ - TileGrid menuGrid; /** The action focused when the main menu was left, so it opens there again. */ - uint16_t lastMenuFocus = TileGrid::NO_ACTION; + uint16_t lastMenuFocus = 0xFFFF; MainMenuState menuShown {}; bool menuOpen = false; Popup popup = Popup::Main; @@ -781,6 +823,12 @@ class MapView { StallProbe probe; SavedView savedView; bool hasSavedView = false; + bool hasStartPosition = false; + double launchLat = 0.0; + double launchLon = 0.0; + int startZoom = -1; + /** The command line's position, marked with a pin for the whole session. */ + bool launchPinShown = false; bool viewReady = false; LocationSource location; PositionTracker position; @@ -795,6 +843,15 @@ class MapView { float bearing = 0.0f; float bearingCos = 1.0f; float bearingSin = 0.0f; + /** + * Screen pixels per map pixel, from the display's density: tiles are drawn at 256 pixels as on the T-Deck (143 dpi) + * and shown magnified, so a dense screen shows the same map, as large, instead of more of it smaller. Text, icons + * and lines drawn over the map are sized by it too (ui()). + */ + float magnify = 1.0f; + /** A size in pixels as on the T-Deck, for this screen. */ + float ui(float pixels) const { return pixels * magnify; } + int ui(int pixels) const { return static_cast(pixels * magnify + 0.5f); } /** Turning to a new bearing over TURN_ANIMATION_MS, drawn from cached tiles like the zoom animation. */ struct TurnAnimation { bool active; @@ -820,7 +877,7 @@ class MapView { SmoothView smooth {}; bool isSmoothView() const; /** Text can be typed: on a keyboard, or on the on-screen keyboard of a touch screen. */ - bool canType() const { return input.hasKeyboard() || input.hasTouch(); } + bool canType() const { return input->hasKeyboard() || input->hasTouch(); } /** The on-screen keyboard shows while a text field is open on a board with a touch screen and no keyboard. */ bool wantsTouchKeyboard() const; void syncTouchKeyboard(); diff --git a/Apps/Maps/main/Source/app/TileWorker.cpp b/Apps/Maps/main/Source/app/TileWorker.cpp index aee6649f..88b159e4 100644 --- a/Apps/Maps/main/Source/app/TileWorker.cpp +++ b/Apps/Maps/main/Source/app/TileWorker.cpp @@ -6,6 +6,7 @@ #include "../render/TileCodec.h" #include +#include #include #include @@ -20,11 +21,25 @@ namespace { /** Rendering, and conversions, where ROM tdefl alone needs about 3-4 KB of stack. */ /** tdefl, which deflates prepared tiles, keeps about 6 KB of Huffman tables on the stack: 8 KB left 600 bytes. */ constexpr uint32_t TASK_STACK = 10240; -/** Cache slots kept free of wanted tiles, for the ancestors magnified while a tile renders. */ -constexpr int CACHE_SPARE_SLOTS = 6; /** Lanes keep a file buffer this large between tiles, larger ones (dense z14 or low-zoom tiles) are freed after use. */ constexpr size_t KEEP_FILE_BUFFER = 256 * 1024; constexpr UBaseType_t TASK_PRIORITY = 4; + +/** Deletes a lane task that stopped, once it suspended itself (taskMain). */ +void deleteLaneTask(TaskHandle_t task) { + if (task == nullptr) { + return; + } + TaskStatus_t status {}; + for (int i = 0; i < 100; i++) { + vTaskGetInfo(task, &status, pdFALSE, eInvalid); + if (status.eCurrentState == eSuspended) { + break; + } + vTaskDelay(pdMS_TO_TICKS(5)); + } + vTaskDeleteWithCaps(task); +} constexpr uint32_t IDLE_WAIT_MS = 30; /** A conversion starts only with a PSRAM block this large free (the compressor needs 320 KB in one block), and this * much PSRAM free in all for the original, the features and the labels. */ @@ -931,15 +946,18 @@ bool TileWorker::start(TileStore* tileStore, IoTask* ioTask, const Palette* tile static_cast(context)->put(source, section, size, count); }, labelStore); } - lane.writeBuffer = static_cast(largeAlloc(TileCache::TILE_BYTES)); - lane.encodeBuffer = static_cast(largeAlloc(ENCODE_CAPACITY * sizeof(uint16_t) + CACHE_HEADER_BYTES)); - if (lane.writeBuffer == nullptr || lane.encodeBuffer == nullptr || !lane.renderer.init()) { + // The SD cache's write and encode buffers come with the first write (writeOne): without the cache, none + lane.writeBuffer = nullptr; + lane.encodeBuffer = nullptr; + if (!lane.renderer.init()) { logError("Tile worker: no memory for render lane %d", i); break; } char name[16]; snprintf(name, sizeof(name), "maps-render%d", i); - if (xTaskCreatePinnedToCore(taskMain, name, TASK_STACK, &lane, TASK_PRIORITY, &lane.task, i) != pdPASS) { + // The stack in PSRAM: 10 KB twice was the largest share of the app's internal RAM + if (xTaskCreatePinnedToCoreWithCaps(taskMain, name, TASK_STACK, &lane, TASK_PRIORITY, &lane.task, i, MALLOC_CAP_SPIRAM) != pdPASS) { + lane.task = nullptr; logError("Tile worker: task %d not started", i); break; } @@ -954,6 +972,10 @@ void TileWorker::stop() { for (int i = 0; i < laneCount; i++) { xSemaphoreTake(stopped, portMAX_DELAY); } + for (int i = 0; i < laneCount; i++) { + deleteLaneTask(lanes[i].task); + lanes[i].task = nullptr; + } if (laneCount > 0) { saveCacheIndex(); } @@ -979,7 +1001,8 @@ void TileWorker::taskMain(void* context) { TileWorker* worker = lane->worker; worker->loop(*lane); xSemaphoreGive(worker->stopped); - vTaskDelete(nullptr); + // A task with its stack in PSRAM cannot delete itself: stop() deletes it once it is suspended + vTaskSuspend(nullptr); } void TileWorker::want(const TileKey* tiles, int count, int visibleCount) { @@ -1663,6 +1686,27 @@ bool TileWorker::claimNext(Lane& lane, bool visible, TileKey& tile, uint16_t*& p bool TileWorker::writeOne(Lane& lane) { if (!sdCache) { + // Turned off in Settings: the 256 KB of buffers go back + largeFree(lane.writeBuffer); + lane.writeBuffer = nullptr; + largeFree(lane.encodeBuffer); + lane.encodeBuffer = nullptr; + return false; + } + lock(); + const bool any = pendingWriteCount > 0; + unlock(); + if (!any) { + return false; + } + if (lane.writeBuffer == nullptr) { + lane.writeBuffer = static_cast(largeAlloc(TileCache::TILE_BYTES)); + } + if (lane.encodeBuffer == nullptr) { + lane.encodeBuffer = static_cast(largeAlloc(ENCODE_CAPACITY * sizeof(uint16_t) + CACHE_HEADER_BYTES)); + } + if (lane.writeBuffer == nullptr || lane.encodeBuffer == nullptr) { + // Short of memory: the tile stays pending, a later pass tries again return false; } lock(); diff --git a/Apps/Maps/main/Source/app/TileWorker.h b/Apps/Maps/main/Source/app/TileWorker.h index e07eeb23..219d4f25 100644 --- a/Apps/Maps/main/Source/app/TileWorker.h +++ b/Apps/Maps/main/Source/app/TileWorker.h @@ -40,7 +40,10 @@ namespace maps { */ class TileWorker { public: - static constexpr int MAX_WANTED = 32; + /** Enough for the visible tiles and a ring around them of an 1024 x 600 screen turned any way (8 x 8). */ + static constexpr int MAX_WANTED = 64; + /** Cache slots kept free of wanted tiles, for the ancestors magnified while a tile renders. */ + static constexpr int CACHE_SPARE_SLOTS = 6; static constexpr int LANES = 2; bool start(TileStore* store, IoTask* io, const Palette* palette, int cacheSlots, const char* cacheRoot); diff --git a/Apps/Maps/main/Source/mvt/InflateReader.cpp b/Apps/Maps/main/Source/mvt/InflateReader.cpp index 1793f42e..37e1a209 100644 --- a/Apps/Maps/main/Source/mvt/InflateReader.cpp +++ b/Apps/Maps/main/Source/mvt/InflateReader.cpp @@ -32,14 +32,15 @@ InflateReader::~InflateReader() { } bool InflateReader::init() { + // In PSRAM, like the window: inflating is a small part of a tile's render time, internal RAM is scarce (TLS, drawing) if (decompressor == nullptr) { - decompressor = fastAlloc(sizeof(tinfl_decompressor)); + decompressor = largeAlloc(sizeof(tinfl_decompressor)); } if (window == nullptr) { window = static_cast(largeAlloc(WINDOW_SIZE)); } if (inputBuffer == nullptr) { - inputBuffer = static_cast(fastAlloc(INPUT_BUFFER_SIZE)); + inputBuffer = static_cast(largeAlloc(INPUT_BUFFER_SIZE)); } return decompressor != nullptr && window != nullptr && inputBuffer != nullptr; } diff --git a/Apps/Maps/main/Source/mvt/MvtDecoder.cpp b/Apps/Maps/main/Source/mvt/MvtDecoder.cpp index b9fd22e5..ba216c56 100644 --- a/Apps/Maps/main/Source/mvt/MvtDecoder.cpp +++ b/Apps/Maps/main/Source/mvt/MvtDecoder.cpp @@ -216,7 +216,7 @@ bool MvtDecoder::scanValue(size_t valueEnd, ValueEntry& entry) { } } code = static_cast(valueFromString(text, stored)); - if (stored > 0 && namePool != nullptr && namePoolUsed + stored <= namePoolCapacity) { + if (stored > 0 && namePool != nullptr && namePoolUsed + stored <= nameLimit) { memcpy(namePool + namePoolUsed, text, stored); textOffset = namePoolUsed; textLength = static_cast(stored); @@ -258,9 +258,30 @@ bool MvtDecoder::scanValue(size_t valueEnd, ValueEntry& entry) { return true; } +namespace { + +/** + * How far a layer may fill a pool of the given capacity, of which used is taken: the poi and housenumber layers leave + * the reserve (at most a quarter of the pool) to the others, and the house numbers take at most half of the rest. + */ +uint32_t poolLimit(Layer layer, uint32_t capacity, uint32_t used, uint32_t reserve) { + if (layer != Layer::Poi && layer != Layer::Housenumber) { + return capacity; + } + const uint32_t kept = reserve < capacity / 4 ? reserve : capacity / 4; + const uint32_t budget = capacity - kept; + if (layer == Layer::Poi || used >= budget) { + return budget; + } + return used + (budget - used) / 2; +} + +} // namespace + bool MvtDecoder::scanLayer(size_t layerEnd, LayerTable& table, Layer layer) { - (void)layer; uint32_t keyIndex = 0; + valueLimit = poolLimit(layer, valuePoolCapacity, valuePoolUsed, VALUE_RESERVE); + nameLimit = poolLimit(layer, namePoolCapacity, namePoolUsed, NAME_RESERVE); table.valueOffset = valuePoolUsed; table.valueCount = 0; while (reader.tell() < layerEnd) { @@ -330,7 +351,7 @@ bool MvtDecoder::scanLayer(size_t layerEnd, LayerTable& table, Layer layer) { if (!scanValue(reader.tell() + static_cast(length), entry)) { return false; } - if (valuePoolUsed < valuePoolCapacity) { + if (valuePoolUsed < valueLimit) { valuePool[valuePoolUsed++] = entry; table.valueCount++; } diff --git a/Apps/Maps/main/Source/mvt/MvtDecoder.h b/Apps/Maps/main/Source/mvt/MvtDecoder.h index bff00155..e28b8f69 100644 --- a/Apps/Maps/main/Source/mvt/MvtDecoder.h +++ b/Apps/Maps/main/Source/mvt/MvtDecoder.h @@ -42,14 +42,20 @@ class MvtDecoder { static constexpr int VALUE_POOL_SIZE = 8192; static constexpr int NAME_POOL_SIZE = 24576; /** - * The pools are this big when the poi and housenumber layers are scanned: every tag value of them counts. Those - * layers come last in OpenMapTiles tiles, so in the densest tiles only some of their strings miss the pools (those - * POIs lose their names), never a place or street name. 96 KB + 160 KB, given back after each conversion: a - * 384 KB name pool took the T-Deck's largest free PSRAM block and the label section could not grow (device test, - * 10 Nov 2026). + * The pools are this big when the poi and housenumber layers are scanned: every tag value of them counts. 128 KB + + * 160 KB, given back after each conversion: a 384 KB name pool took the T-Deck's largest free PSRAM block and the + * label section could not grow (device test, 10 Nov 2026). */ - static constexpr int POI_VALUE_POOL_SIZE = 12288; + static constexpr int POI_VALUE_POOL_SIZE = 16384; static constexpr int POI_NAME_POOL_SIZE = 163840; + /** + * What the poi and housenumber layers leave of the pools for the other layers. Tiles may have their layers in + * alphabetical order, with housenumber and poi before transportation and water: in a dense city tile (Amsterdam + * centre, 14/8414/5384: 8143 house number and 5569 POI values) they filled the pool, and every road of the tile was + * dropped. The house numbers get at most half of what is left for the two. + */ + static constexpr uint32_t VALUE_RESERVE = 2048; + static constexpr uint32_t NAME_RESERVE = 16384; MvtDecoder() = default; ~MvtDecoder(); @@ -135,6 +141,9 @@ class MvtDecoder { char* namePool = nullptr; uint32_t namePoolUsed = 0; uint32_t namePoolCapacity = 0; + /** How far the layer being scanned may fill the pools. */ + uint32_t valueLimit = 0; + uint32_t nameLimit = 0; TilePoint* chunk = nullptr; size_t totalSize = 0; }; diff --git a/Apps/Maps/main/Source/render/Compose.h b/Apps/Maps/main/Source/render/Compose.h index 780adffa..05a60b33 100644 --- a/Apps/Maps/main/Source/render/Compose.h +++ b/Apps/Maps/main/Source/render/Compose.h @@ -51,7 +51,7 @@ AffineView scaledView(double worldX, double worldY, int zoom, float scale, float /** Working memory of composeAffine, about 6 KB: too much for a task stack, so the caller keeps one (in PSRAM). */ struct AffineScratch { static constexpr int MAX_GRID = 12; - static constexpr int MAX_WIDTH = 1024; + static constexpr int MAX_WIDTH = 2048; /** How the pixels of one tile of the view are found: in the tile itself, in an ancestor, or in its four children. */ struct Cell { diff --git a/Apps/Maps/main/Source/render/LabelLayout.cpp b/Apps/Maps/main/Source/render/LabelLayout.cpp index 72346832..83c47948 100644 --- a/Apps/Maps/main/Source/render/LabelLayout.cpp +++ b/Apps/Maps/main/Source/render/LabelLayout.cpp @@ -684,7 +684,7 @@ bool LabelLayout::alreadyPlaced(const Candidate& candidate, float x, float y) co // The same name from a neighbouring tile, or the same street again too soon const char* name = texts + candidate.textOffset; // House numbers repeat in every street: only the same number at the same spot (two tiles' copies) is one - const float reach = candidate.line ? static_cast(LINE_REPEAT_PIXELS) : (candidate.kind == LabelKind::HouseNumber ? 6.0f : 120.0f); + const float reach = scale * (candidate.line ? static_cast(LINE_REPEAT_PIXELS) : (candidate.kind == LabelKind::HouseNumber ? 6.0f : 120.0f)); for (int i = 0; i < placedCount; i++) { const Placed& other = placed[i]; if (other.line != candidate.line || other.kind != candidate.kind || strcmp(texts + other.textOffset, name) != 0) { @@ -751,7 +751,7 @@ bool LabelLayout::placePoiIcon(Candidate& candidate) { // Where every POI is drawn only the same spot is a copy (the neighbour tile's own record of it): two waste baskets // or bicycle racks a few pixels apart are two. const char* name = texts + candidate.textOffset; - const float same = zoom >= POI_ALL_ZOOM && density == LabelDensity::Normal ? 1.5f : 6.0f; + const float same = scale * (zoom >= POI_ALL_ZOOM && density == LabelDensity::Normal ? 1.5f : 6.0f); for (int i = 0; i < pendingCount; i++) { const Candidate& other = candidates[pending[i]]; if (other.poiType == candidate.poiType && strcmp(texts + other.textOffset, name) == 0 && std::fabs(other.x - candidate.x) < same && @@ -776,7 +776,7 @@ bool LabelLayout::placePoiIcon(Candidate& candidate) { for (int ring = 2; ring <= ICON_MOVE_PIXELS; ring += 2) { for (const auto& direction : DIRECTIONS) { // The diagonals are as far from the point as the straight ones - const float reach = direction[0] != 0 && direction[1] != 0 ? ring * 0.7071f : static_cast(ring); + const float reach = scale * (direction[0] != 0 && direction[1] != 0 ? ring * 0.7071f : static_cast(ring)); const float x = candidate.x + direction[0] * reach; const float y = candidate.y + direction[1] * reach; if (gridFree(x, y, iconHalf, iconHalf, 0.0f)) { @@ -963,7 +963,7 @@ int LabelLayout::placeLine(const Candidate& candidate) { mapToScreen(kept[k].worldX * scale, kept[k].worldY * scale, screenX, screenY); const auto nearX = static_cast(screenX); const auto nearY = static_cast(screenY); - for (float start = tryFrom; start + needed <= tryTo + needed && start + needed <= total; start += 16.0f) { + for (float start = tryFrom; start + needed <= tryTo + needed && start + needed <= total; start += 16.0f * scale) { if (tryAt(start, &nearX, &nearY)) { placedHere++; break; @@ -974,9 +974,9 @@ int LabelLayout::placeLine(const Candidate& candidate) { for (float start = tryFrom; start <= tryTo && start + needed <= total && placedCount < MAX_LABELS;) { if (tryAt(start, nullptr, nullptr)) { placedHere++; - start += needed + LINE_REPEAT_PIXELS; + start += needed + LINE_REPEAT_PIXELS * scale; } else { - start += 16.0f; + start += 16.0f * scale; } } return placedHere; diff --git a/Apps/Maps/main/Source/render/LabelLayout.h b/Apps/Maps/main/Source/render/LabelLayout.h index c0ff0295..6b987777 100644 --- a/Apps/Maps/main/Source/render/LabelLayout.h +++ b/Apps/Maps/main/Source/render/LabelLayout.h @@ -138,6 +138,8 @@ class LabelLayout { void setFonts(LabelFont* small, LabelFont* normal, LabelFont* large); void setStyle(const LabelStyle& value) { style = value; } void setDensity(LabelDensity value) { density = value; } + /** Screen pixels per map pixel (MapView::magnify): the distances between labels grow with it. */ + void setScale(float value) { scale = value; } void setPreferLatin(bool value) { preferLatin = value; } /** Without a lookup no POIs are shown. */ void setPoiLookup(PoiLookup value) { poiLookup = value; } @@ -326,6 +328,7 @@ class LabelLayout { LabelFont* fonts[3] {}; LabelStyle style {}; LabelDensity density = LabelDensity::Normal; + float scale = 1.0f; bool preferLatin = false; PoiLookup poiLookup = nullptr; uint32_t (*clock)() = nullptr; diff --git a/Apps/Maps/main/Source/render/PreparedTile.cpp b/Apps/Maps/main/Source/render/PreparedTile.cpp index e9a79fda..24dd3935 100644 --- a/Apps/Maps/main/Source/render/PreparedTile.cpp +++ b/Apps/Maps/main/Source/render/PreparedTile.cpp @@ -190,6 +190,11 @@ uint8_t preparedPartsNeeded(const PreparedHeader* header, const TileKey& tile, u if (header->version != PREPARED_FORMAT_VERSION && !keptOlder) { parts |= PART_GEOMETRY; } + // Made before the pools kept room for the drawn layers: a big tile may have lost them, and its labels and graph too + if (header->version >= PREPARED_SPLIT_VERSION && (header->flags & PREPARED_FLAG_RESERVED_POOLS) == 0 && + sourceSize >= PREPARED_POOL_RISK_SIZE) { + return PART_GEOMETRY | PART_LABELS | graph; + } if (header->version < PREPARED_SPLIT_VERSION || header->labelVersion != PREPARED_LABEL_FORMAT_VERSION) { parts |= PART_LABELS; } @@ -654,7 +659,7 @@ bool TileConverter::writeGeometry(const char* sourceVersion, uint32_t sourceSize out.putU16(withLabels ? PREPARED_SPLIT_VERSION - 1 : PREPARED_FORMAT_VERSION); // The companion versions this tile was made with (version 5 on) const auto graphVersion = static_cast(withLabels || !tileHasGraph(tile.z) ? 0 : PREPARED_GRAPH_FORMAT_VERSION); - out.putU16(static_cast((deflate ? PREPARED_FLAG_DEFLATED : 0) | (graphVersion << 8))); + out.putU16(static_cast((deflate ? PREPARED_FLAG_DEFLATED : 0) | PREPARED_FLAG_RESERVED_POOLS | (graphVersion << 8))); out.put(static_cast(tile.z)); out.put(withLabels ? 0 : PREPARED_LABEL_FORMAT_VERSION); out.putU16(PREPARED_EXTENT); diff --git a/Apps/Maps/main/Source/render/PreparedTile.h b/Apps/Maps/main/Source/render/PreparedTile.h index 514a9894..035d625b 100644 --- a/Apps/Maps/main/Source/render/PreparedTile.h +++ b/Apps/Maps/main/Source/render/PreparedTile.h @@ -58,6 +58,13 @@ constexpr size_t PREPARED_VERSION_LENGTH = 32; /** No section of a prepared file is larger (inflated or stored): a header with more is damaged. */ constexpr uint32_t PREPARED_MAX_SECTION = 16u * 1024u * 1024u; constexpr uint16_t PREPARED_FLAG_DEFLATED = 1; +/** + * Set in .prt files made with room kept in the decoder's pools for the drawn layers (MvtDecoder::VALUE_RESERVE). + * Without it, a tile from a big original may lack its roads and water: it is made again, with its companions. + */ +constexpr uint16_t PREPARED_FLAG_RESERVED_POOLS = 2; +/** Originals smaller than this never filled the pools (about 26 values per KB, 8192 values in the smallest pool). */ +constexpr uint32_t PREPARED_POOL_RISK_SIZE = 256u * 1024u; /** * The label file .prl (little endian): an 80-byte header, the cell index (LABEL_INDEX_SIZE bytes, PreparedLabels.h), diff --git a/Apps/Maps/main/Source/ui/MapOverlay.cpp b/Apps/Maps/main/Source/ui/MapOverlay.cpp index 26c5edeb..87bff0a8 100644 --- a/Apps/Maps/main/Source/ui/MapOverlay.cpp +++ b/Apps/Maps/main/Source/ui/MapOverlay.cpp @@ -75,7 +75,7 @@ bool MapOverlay::hitsAttributionMark(const Canvas& canvas, int x, int y) const { } int MapOverlay::scaleBarTop(const Canvas& canvas) const { - return canvas.height - bottomInset - normal->lineHeight() - 8; + return canvas.height - bottomInset - normal->lineHeight() - metrics::px(8); } int MapOverlay::markSize() const { @@ -107,14 +107,16 @@ Rect MapOverlay::drawScaleBar(Canvas& canvas, double metresPerPixel, const Palet const int boxWidth = (barPixels > labelWidth ? barPixels : labelWidth) + 2 * MARGIN; const int boxX = canvas.width - boxWidth - 1; const int boxY = scaleBarTop(canvas); - canvas.fillRect(boxX, boxY, boxWidth, height + 7, palette.halo, 190); + const int boxHeight = height + metrics::px(7); + canvas.fillRect(boxX, boxY, boxWidth, boxHeight, palette.halo, 190); normal->drawText(canvas, boxX + (boxWidth - labelWidth) / 2, boxY, label, palette.text); const int barX = boxX + (boxWidth - barPixels) / 2; - const int barY = boxY + height + 3; - canvas.fillRect(barX, barY, barPixels, 2, palette.text); - canvas.fillRect(barX, barY - 3, 1, 5, palette.text); - canvas.fillRect(barX + barPixels - 1, barY - 3, 1, 5, palette.text); - return { boxX, boxY, boxWidth, height + 7 }; + const int barY = boxY + height + metrics::px(3); + const int thick = metrics::px(1); + canvas.fillRect(barX, barY, barPixels, 2 * thick, palette.text); + canvas.fillRect(barX, barY - 3 * thick, thick, 5 * thick, palette.text); + canvas.fillRect(barX + barPixels - thick, barY - 3 * thick, thick, 5 * thick, palette.text); + return { boxX, boxY, boxWidth, boxHeight }; } Rect MapOverlay::drawPill(Canvas& canvas, const char* text, const Palette& palette, int top) { @@ -130,7 +132,7 @@ Rect MapOverlay::drawPill(Canvas& canvas, const char* text, const Palette& palet } Rect MapOverlay::drawToast(Canvas& canvas, const char* text, const UiTheme& theme) { - constexpr int padding = metrics::PADDING; + const int padding = metrics::PADDING; char lines[2][80]; const int maxWidth = canvas.width - 4 * padding; const int count = wrapText(*normal, text, maxWidth, &lines[0][0], sizeof(lines[0]), 2); @@ -182,10 +184,10 @@ void MapOverlay::drawAccuracyCircle(Canvas& canvas, int x, int y, float radius, void MapOverlay::drawApproximateMarker(Canvas& canvas, int x, int y, float accuracyMetres, const Palette& palette) { const float cx = static_cast(x) + 0.5f; const float cy = static_cast(y) + 0.5f; - canvas.fillCircle(cx, cy, 7.5f, palette.text, 70); - canvas.fillCircle(cx, cy, 6.5f, palette.halo); - canvas.fillCircle(cx, cy, 4.5f, palette.marker); - canvas.fillCircle(cx, cy, 2.5f, palette.halo); + canvas.fillCircle(cx, cy, metrics::px(7.5f), palette.text, 70); + canvas.fillCircle(cx, cy, metrics::px(6.5f), palette.halo); + canvas.fillCircle(cx, cy, metrics::px(4.5f), palette.marker); + canvas.fillCircle(cx, cy, metrics::px(2.5f), palette.halo); if (std::isnan(accuracyMetres) || accuracyMetres <= 0.0f) { return; } @@ -198,9 +200,9 @@ void MapOverlay::drawApproximateMarker(Canvas& canvas, int x, int y, float accur // Right of the ring, or left of it near the right edge const int width = small->textWidth(label) + 2 * MARGIN; const int height = small->lineHeight(); - int boxX = x + 10; + int boxX = x + metrics::px(10); if (boxX + width > canvas.width) { - boxX = x - 10 - width; + boxX = x - metrics::px(10) - width; } const int boxY = y - height / 2; canvas.fillRoundRect(boxX, boxY, width, height, 4, palette.halo, 190); @@ -210,9 +212,9 @@ void MapOverlay::drawApproximateMarker(Canvas& canvas, int x, int y, float accur void MapOverlay::drawMarker(Canvas& canvas, int x, int y, bool hasCourse, float courseDegrees, const Palette& palette) { const float cx = static_cast(x) + 0.5f; const float cy = static_cast(y) + 0.5f; - canvas.fillCircle(cx, cy, 7.5f, palette.text, 70); - canvas.fillCircle(cx, cy, 6.5f, palette.halo); - canvas.fillCircle(cx, cy, 4.5f, palette.marker); + canvas.fillCircle(cx, cy, metrics::px(7.5f), palette.text, 70); + canvas.fillCircle(cx, cy, metrics::px(6.5f), palette.halo); + canvas.fillCircle(cx, cy, metrics::px(4.5f), palette.marker); if (!hasCourse) { return; } @@ -220,12 +222,12 @@ void MapOverlay::drawMarker(Canvas& canvas, int x, int y, bool hasCourse, float const float radians = courseDegrees * 3.14159265f / 180.0f; const float sx = std::sin(radians); const float sy = -std::cos(radians); - const float tipX = cx + sx * 14.0f; - const float tipY = cy + sy * 14.0f; - const float baseX = cx + sx * 8.0f; - const float baseY = cy + sy * 8.0f; - canvas.line(baseX - sy * 4.0f, baseY + sx * 4.0f, tipX, tipY, 2.5f, palette.marker); - canvas.line(baseX + sy * 4.0f, baseY - sx * 4.0f, tipX, tipY, 2.5f, palette.marker); + const float tipX = cx + sx * metrics::px(14.0f); + const float tipY = cy + sy * metrics::px(14.0f); + const float baseX = cx + sx * metrics::px(8.0f); + const float baseY = cy + sy * metrics::px(8.0f); + canvas.line(baseX - sy * metrics::px(4.0f), baseY + sx * metrics::px(4.0f), tipX, tipY, metrics::px(2.5f), palette.marker); + canvas.line(baseX + sy * metrics::px(4.0f), baseY - sx * metrics::px(4.0f), tipX, tipY, metrics::px(2.5f), palette.marker); } } // namespace maps diff --git a/Apps/Maps/main/Source/ui/Metrics.h b/Apps/Maps/main/Source/ui/Metrics.h index 34f4b2cb..6508f7c2 100644 --- a/Apps/Maps/main/Source/ui/Metrics.h +++ b/Apps/Maps/main/Source/ui/Metrics.h @@ -13,23 +13,36 @@ namespace maps { */ namespace metrics { +/** + * Screen pixels per T-Deck pixel (MapView::magnify, from the display's density). The sizes below are the T-Deck's; + * setScale() multiplies them once at the start, so a dense screen gets the same physical sizes. + */ +inline float& scaleValue() { + static float value = 1.0f; + return value; +} +inline float scale() { return scaleValue(); } +/** A T-Deck size in pixels on this screen. */ +inline float px(float pixels) { return pixels * scaleValue(); } +inline int px(int pixels) { return static_cast(pixels * scaleValue() + 0.5f); } + /** Space between a panel's edge and its content, and between neighbouring buttons. */ -constexpr int PADDING = 8; +inline int PADDING = 8; /** Extra height of a list row on top of the font's line height. */ -constexpr int ROW_PADDING = 10; +inline int ROW_PADDING = 10; /** Corner radius of panels (sheets, cards, dialogs, popups). */ -constexpr int PANEL_RADIUS = 8; +inline int PANEL_RADIUS = 8; /** Corner radius of buttons; their border takes 1 px. */ -constexpr int BUTTON_RADIUS = 6; +inline int BUTTON_RADIUS = 6; /** Corner radius of text fields, outer edge; the inside is one less. */ -constexpr int FIELD_RADIUS = 4; +inline int FIELD_RADIUS = 4; /** How much the map is dimmed behind a popup, dialog, card or search sheet. */ constexpr uint8_t SCRIM_ALPHA = 100; /** Minimum sizes on boards without a typing keyboard, where a finger is the main input. */ -constexpr int TOUCH_ROW_HEIGHT = 36; -constexpr int TOUCH_BUTTON_HEIGHT = 36; -constexpr int TOUCH_BACK_WIDTH = 40; +inline int TOUCH_ROW_HEIGHT = 36; +inline int TOUCH_BUTTON_HEIGHT = 36; +inline int TOUCH_BACK_WIDTH = 40; /** * Whether the board has a typing keyboard. Without one a finger is the main input: rows, buttons and the back area get @@ -73,7 +86,21 @@ inline int cardWidth(int screenWidth, int screenHeight, int margin, int base, in } /** The height of a header bar: the font's line height plus 10, at least TOUCH_HEADER_HEIGHT on touch boards (screens 240 px high or more). */ -constexpr int TOUCH_HEADER_HEIGHT = 40; +inline int TOUCH_HEADER_HEIGHT = 40; + +/** Sets the scale and sizes the metrics for it; call once, before any widget is laid out. */ +inline void setScale(float value) { + scaleValue() = value; + PADDING = px(8); + ROW_PADDING = px(10); + PANEL_RADIUS = px(8); + BUTTON_RADIUS = px(6); + FIELD_RADIUS = px(4); + TOUCH_ROW_HEIGHT = px(36); + TOUCH_BUTTON_HEIGHT = px(36); + TOUCH_BACK_WIDTH = px(40); + TOUCH_HEADER_HEIGHT = px(40); +} inline int headerHeight(int lineHeight, int extra = 10, int screenHeight = 1000) { // Not on a low screen, where the finger-sized header would take a third of it return touchTargets() && screenHeight >= 240 ? std::max(lineHeight + extra, TOUCH_HEADER_HEIGHT) : lineHeight + extra; @@ -86,6 +113,8 @@ inline int backWidth(int natural) { /** The < of a back button, drawn from lines so it needs no glyph in the font. cx, cy: the centre. */ inline void drawBackChevron(Canvas& canvas, float cx, float cy, uint16_t color, float reach = 6.0f, float width = 2.0f) { + reach = px(reach); + width = px(width); canvas.line(cx + reach / 2.0f, cy - reach, cx - reach / 2.0f, cy, width, color); canvas.line(cx - reach / 2.0f, cy, cx + reach / 2.0f, cy + reach, width, color); } @@ -98,9 +127,9 @@ inline void drawScrollbar(Canvas& canvas, int right, int trackTop, int trackHeig if (totalRows <= visibleRows || visibleRows <= 0) { return; } - const int barHeight = std::max(8, trackHeight * visibleRows / totalRows); + const int barHeight = std::max(px(8), trackHeight * visibleRows / totalRows); const int barTop = trackTop + (trackHeight - barHeight) * firstRow / std::max(1, totalRows - visibleRows); - canvas.fillRect(right - 3, barTop, 2, barHeight, color); + canvas.fillRect(right - px(3), barTop, px(2), barHeight, color); } } // namespace metrics diff --git a/Apps/Maps/main/Source/ui/Pins.cpp b/Apps/Maps/main/Source/ui/Pins.cpp index 8ce6fc7e..6fdccdcb 100644 --- a/Apps/Maps/main/Source/ui/Pins.cpp +++ b/Apps/Maps/main/Source/ui/Pins.cpp @@ -1,13 +1,14 @@ // SPDX-License-Identifier: GPL-3.0-or-later #include "Pins.h" +#include "Metrics.h" namespace maps { void drawPin(Canvas& canvas, float x, float y, const PinStyle& style, bool highlighted) { - const float headY = y - PIN_HEAD_OFFSET; - canvas.line(x, y, x, headY, 2.0f, style.stem); - canvas.fillCircle(x, headY, PIN_RADIUS + 1.5f, style.halo); - canvas.fillCircle(x, headY, PIN_RADIUS, highlighted ? style.highlight : style.fill); + const float headY = y - metrics::px(PIN_HEAD_OFFSET); + canvas.line(x, y, x, headY, metrics::px(2.0f), style.stem); + canvas.fillCircle(x, headY, metrics::px(PIN_RADIUS + 1.5f), style.halo); + canvas.fillCircle(x, headY, metrics::px(PIN_RADIUS), highlighted ? style.highlight : style.fill); } } // namespace maps diff --git a/Apps/Maps/main/Source/ui/Settings.cpp b/Apps/Maps/main/Source/ui/Settings.cpp index 45074d07..7c3cb977 100644 --- a/Apps/Maps/main/Source/ui/Settings.cpp +++ b/Apps/Maps/main/Source/ui/Settings.cpp @@ -42,6 +42,7 @@ struct NumberEntry { constexpr NumberEntry NUMBER_ENTRIES[] = { { "pointer_speed", &Settings::pointerSpeed, 0, 2 }, { "labels", &Settings::labels, 0, 2 }, + { "render_scale", &Settings::renderScale, 0, 100 }, { "route_profile", &Settings::routeProfile, 0, 2 }, }; diff --git a/Apps/Maps/main/Source/ui/Settings.h b/Apps/Maps/main/Source/ui/Settings.h index a8a83ce7..3de6c47f 100644 --- a/Apps/Maps/main/Source/ui/Settings.h +++ b/Apps/Maps/main/Source/ui/Settings.h @@ -26,6 +26,12 @@ struct Settings { int pointerSpeed = 1; /** Map labels: 0 off, 1 few, 2 normal (LabelDensity). */ int labels = 2; + /** + * Percent of the screen's resolution the map is drawn at: 100, 75 or 50, scaled up by the PPA (ESP32-P4, ESP32-S31), + * or 0 for the screen's default (FrameOutput::defaultRenderPercent). Fewer pixels draw faster; applied when the app + * starts. 100 without a PPA. + */ + int renderScale = 0; /** Show OpenMapTiles' Latin-script name where a place has one, instead of the local name. */ bool latinNames = false; /** The mode new routes start with (Settings, "Route mode"): 0 walk, 1 bike, 2 car (RouteProfile). */ diff --git a/Apps/Maps/main/Source/ui/SettingsList.cpp b/Apps/Maps/main/Source/ui/SettingsList.cpp index 6989b517..8d7cead4 100644 --- a/Apps/Maps/main/Source/ui/SettingsList.cpp +++ b/Apps/Maps/main/Source/ui/SettingsList.cpp @@ -5,10 +5,11 @@ #include #include +#include namespace maps { -void fillSettingsList(ListView& list, const Settings& settings, bool monochrome) { +void fillSettingsList(ListView& list, const Settings& settings, bool monochrome, bool renderScaleAvailable, int defaultRenderPercent) { list.clear(); list.setTitle("Settings"); list.add("SD card cache", settings.sdCache ? "On" : "Off"); @@ -23,6 +24,13 @@ void fillSettingsList(ListView& list, const Settings& settings, bool monochrome) list.add("Route mode", routeProfileName(static_cast(std::clamp(settings.routeProfile, 0, 2)))); list.add("Walk prefers paths", settings.walkTrails ? "On" : "Off"); list.add("Terrain", settings.terrain ? "On" : "Off"); + char renderScale[24]; + if (settings.renderScale <= 0) { + snprintf(renderScale, sizeof(renderScale), "Auto (%d %%)", defaultRenderPercent); + } else { + snprintf(renderScale, sizeof(renderScale), "%d %%", settings.renderScale); + } + list.add("Render scale", renderScaleAvailable ? renderScale : "100 % (no PPA)"); // In the order of SettingItem: what each does and when to change it, under its name static const char* const DESCRIPTIONS[] = { "Keeps drawn tiles: faster revisits, uses card", @@ -35,6 +43,7 @@ void fillSettingsList(ListView& list, const Settings& settings, bool monochrome) "The mode new routes start with", "On for hikes, Off for the shortest way", "Shading, contours; downloads terrain", + "Below 100 % draws faster; after a restart", }; static_assert(sizeof(DESCRIPTIONS) / sizeof(DESCRIPTIONS[0]) == static_cast(SettingItem::Count)); list.setDescriptions(DESCRIPTIONS, static_cast(SettingItem::Count)); diff --git a/Apps/Maps/main/Source/ui/SettingsList.h b/Apps/Maps/main/Source/ui/SettingsList.h index 2bc37c24..a77c5eec 100644 --- a/Apps/Maps/main/Source/ui/SettingsList.h +++ b/Apps/Maps/main/Source/ui/SettingsList.h @@ -20,6 +20,7 @@ enum class SettingItem : uint8_t { RouteMode, WalkTrails, Terrain, + RenderScale, Count }; @@ -27,6 +28,6 @@ enum class SettingItem : uint8_t { * Fills the Settings list: each row with its value and a line saying what it does and when to change it. monochrome: * a display with one map style and no live pinch (Smooth zoom shows as off). The caller sets the hint and lays it out. */ -void fillSettingsList(ListView& list, const Settings& settings, bool monochrome); +void fillSettingsList(ListView& list, const Settings& settings, bool monochrome, bool renderScaleAvailable, int defaultRenderPercent); } // namespace maps diff --git a/Apps/Maps/main/Source/ui/TileGrid.cpp b/Apps/Maps/main/Source/ui/TileGrid.cpp deleted file mode 100644 index 6a2579be..00000000 --- a/Apps/Maps/main/Source/ui/TileGrid.cpp +++ /dev/null @@ -1,627 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-or-later -#include "TileGrid.h" - -#include "Metrics.h" - -#include -#include -#include -#include - -namespace maps { - -namespace { - -constexpr int MARGIN = 6; -constexpr int GAP = 4; -constexpr int TILE_RADIUS = 8; -constexpr int DOT_SPACING = 12; - -/** Text centred in a width, cut with ".." when it does not fit. */ -void drawCentredText(Canvas& canvas, Font& font, int x, int y, int width, const char* text, uint16_t color) { - const int textWidth = font.textWidth(text); - if (textWidth > width) { - drawClippedText(canvas, font, x, y, text, width, color); - } else { - font.drawText(canvas, x + (width - textWidth) / 2, y, text, color); - } -} - -/** The outline of a tile or status item: a border and a panel inside, or a solid accent when focused. */ -void drawFrame(Canvas& canvas, const Rect& r, bool focused, int radius, const UiTheme& theme) { - if (focused) { - canvas.fillRoundRect(r.x, r.y, r.width, r.height, radius, theme.accent); - return; - } - canvas.fillRoundRect(r.x, r.y, r.width, r.height, radius, theme.border); - canvas.fillRoundRect(r.x + 1, r.y + 1, r.width - 2, r.height - 2, radius - 1, theme.panel); -} - -} // namespace - -void TileGrid::clear() { - tiles = 0; - statuses = 0; - corner.label[0] = '\0'; - zone = Zone::Tile; - focusIndex = 0; - currentPage = 0; -} - -void TileGrid::setTitle(const char* text) { - snprintf(title, sizeof(title), "%s", text != nullptr ? text : ""); -} - -void TileGrid::setGrid(int columnCount, int rowCount) { - columns = std::clamp(columnCount, 1, 6); - rows = std::clamp(rowCount, 1, 6); - usedRows = rows; - currentPage = 0; - keepFocusValid(); -} - -int TileGrid::addTile(uint16_t action, MenuIcon icon, const char* label, const char* detail) { - if (tiles >= MAX_TILES) { - return -1; - } - Tile& tile = tileList[tiles]; - tile.action = action; - tile.icon = icon; - snprintf(tile.label, LABEL_LENGTH, "%s", label != nullptr ? label : ""); - snprintf(tile.detail, LABEL_LENGTH, "%s", detail != nullptr ? detail : ""); - return tiles++; -} - -void TileGrid::setDetail(uint16_t action, const char* detail) { - for (int i = 0; i < tiles; i++) { - if (tileList[i].action == action) { - snprintf(tileList[i].detail, LABEL_LENGTH, "%s", detail != nullptr ? detail : ""); - return; - } - } -} - -void TileGrid::addStatus(uint16_t action, MenuIcon icon, const char* text) { - if (statuses >= MAX_STATUS) { - return; - } - Status& status = statusList[statuses++]; - status.action = action; - status.icon = icon; - snprintf(status.text, STATUS_LENGTH, "%s", text != nullptr ? text : ""); -} - -void TileGrid::setCorner(uint16_t action, const char* label) { - corner.action = action; - snprintf(corner.label, LABEL_LENGTH, "%s", label != nullptr ? label : ""); -} - -void TileGrid::setHint(const char* text) { - snprintf(hint, sizeof(hint), "%s", text != nullptr ? text : ""); -} - -int TileGrid::pageCount() const { - return tiles > 0 ? (tiles + perPage() - 1) / perPage() : 1; -} - -// --------------------------------------------------------------------------------------------------------------- - -void TileGrid::layout(int width, int height, Font& font, Font* smallFont) { - Font& small = smallFont != nullptr ? *smallFont : font; - mainFont = &font; - smallFontPtr = &small; - screenWidth = width; - screenHeight = height; - const int line = font.lineHeight(); - - // The header is the one of ListView's full screen lists - header = headerLayout(0, 0, width, metrics::headerHeight(line, 10, height)); - if (hasCorner()) { - const int buttonHeight = metrics::touchTargets() && height >= 240 ? std::max(header.bar.height - 8, metrics::TOUCH_BUTTON_HEIGHT) : header.bar.height - 8; - const int buttonWidth = small.textWidth(corner.label) + 16; - cornerBox = { width - MARGIN - buttonWidth, (header.bar.height - 1 - buttonHeight) / 2, buttonWidth, buttonHeight }; - } else { - cornerBox = { 0, 0, 0, 0 }; - } - - int top = header.bar.height + MARGIN; - int stripHeight = 0; - if (statuses > 0) { - stripHeight = metrics::touchTargets() && height >= 240 ? std::max(line + 12, metrics::TOUCH_BUTTON_HEIGHT) : line + 12; - top += stripHeight + GAP; - } - - // From the bottom up: hint line, page dots, then the grid takes what is left - int bottom = height - 3; - hintY = 0; - if (hint[0] != '\0') { - hintY = height - small.lineHeight() - 3; - bottom = hintY - 1; - } - - // Tiles never get lower than a label with an icon needs; a lower screen shows fewer rows per page - const int minTile = line + 14; - auto fitRows = [&](int room) { - int fit = rows; - while (fit > 1 && (room - GAP * (fit - 1)) / fit < minTile) { - fit--; - } - return fit; - }; - dotsY = 0; - usedRows = fitRows(bottom - 3 - top); - if (pageCount() > 1) { - dotsY = bottom - 5; - bottom -= 10; - usedRows = fitRows(bottom - 3 - top); - } - const int gridBottom = bottom - 3; - const int availableHeight = gridBottom - top; - - // A tile is at most 8 x 7 line heights: more would be a slab with a small icon in it - const int availableWidth = width - 2 * MARGIN; - const int fullWidth = std::max(8, (availableWidth - GAP * (columns - 1)) / columns); - const int fullHeight = std::max(8, (availableHeight - GAP * (usedRows - 1)) / usedRows); - tileWidth = std::min(fullWidth, 8 * line); - tileHeight = std::min(fullHeight, 7 * line); - const bool capped = tileWidth < fullWidth || tileHeight < fullHeight; - gridLeft = MARGIN + (availableWidth - columns * tileWidth - GAP * (columns - 1)) / 2; - int gridTop = top; - if (tileHeight < fullHeight) { - gridTop += (availableHeight - (usedRows * tileHeight + GAP * (usedRows - 1))) / 2; - } - gridBox = { gridLeft, gridTop, columns * tileWidth + GAP * (columns - 1), usedRows * tileHeight + GAP * (usedRows - 1) }; - if (statuses > 0) { - // The strip is as wide as the grid under it - const int stripLeft = capped ? gridBox.x : MARGIN; - stripBox = { stripLeft, header.bar.height + MARGIN, capped ? gridBox.width : width - 2 * MARGIN, stripHeight }; - } else { - stripBox = { 0, 0, 0, 0 }; - } - keepFocusValid(); -} - -Rect TileGrid::tileRect(int index) const { - if (index < 0 || index >= tiles) { - return { 0, 0, 0, 0 }; - } - const int local = index % perPage(); - return { gridLeft + (local % columns) * (tileWidth + GAP), gridBox.y + (local / columns) * (tileHeight + GAP), tileWidth, tileHeight }; -} - -Rect TileGrid::statusRect(int index) const { - if (index < 0 || index >= statuses) { - return { 0, 0, 0, 0 }; - } - const int width = (stripBox.width - GAP * (statuses - 1)) / statuses; - return { stripBox.x + index * (width + GAP), stripBox.y, width, stripBox.height }; -} - -void TileGrid::draw(Canvas& canvas, Font& font, const UiTheme& theme) const { - Font& small = smallFontPtr != nullptr ? *smallFontPtr : font; - - // Opaque: the map's scale bar and labels showed through between the tiles and under the hint - canvas.fillRect(0, 0, canvas.width, canvas.height, theme.panel, 255); - - // The title stops before the corner button; the line under the header runs the full width - HeaderLayout bar = header; - if (hasCorner()) { - bar.bar.width = cornerBox.x - 2; - canvas.fillRect(bar.bar.width, header.bar.height - 1, canvas.width - bar.bar.width, 1, theme.border); - } - drawHeader(canvas, font, theme, bar, title, false); - if (hasCorner()) { - drawButton(canvas, small, theme, cornerBox, corner.label, shown && zone == Zone::Corner); - } - - for (int i = 0; i < statuses; i++) { - const Rect r = statusRect(i); - const bool focused = shown && zone == Zone::Status && focusIndex == i; - const uint16_t color = focused ? theme.accentText : theme.text; - drawFrame(canvas, r, focused, 7, theme); - const int statusIcon = std::min(18 * std::max(16, font.lineHeight()) / 16, r.height - 6); - drawMenuIcon(canvas, statusList[i].icon, r.x + 5 + statusIcon / 2, r.y + r.height / 2, statusIcon, color); - const int textX = r.x + 5 + statusIcon + 4; - drawClippedText(canvas, small, textX, r.y + (r.height - small.lineHeight()) / 2, statusList[i].text, r.x + r.width - 4 - textX, color); - } - - // A detail slot is kept free on every tile when any tile has a detail, so icons in a row line up - bool anyDetail = false; - for (int i = 0; i < tiles; i++) { - anyDetail = anyDetail || tileList[i].detail[0] != '\0'; - } - // The icon grows with the font, and shrinks when the tile is too low for it and a label - int iconSize = (tileHeight < 52 ? 18 : 24) * std::max(16, font.lineHeight()) / 16; - iconSize = std::max(10, std::min(iconSize, tileHeight - 4 - 2 - font.lineHeight())); - const int withDetail = iconSize + 2 + font.lineHeight() + 1 + small.lineHeight(); - const bool reserve = anyDetail && withDetail <= tileHeight - 4; - const int content = reserve ? withDetail : iconSize + 2 + font.lineHeight(); - - const int first = currentPage * perPage(); - const int last = std::min(tiles, first + perPage()); - for (int i = first; i < last; i++) { - const Rect r = tileRect(i); - const Tile& tile = tileList[i]; - const bool focused = shown && zone == Zone::Tile && focusIndex == i; - const uint16_t color = focused ? theme.accentText : theme.text; - drawFrame(canvas, r, focused, TILE_RADIUS, theme); - const int top = r.y + (r.height - content) / 2; - const int labelY = top + iconSize + 2; - const uint16_t detailColor = focused ? theme.accentText : theme.muted; - if (!reserve && tile.detail[0] != '\0') { - // Too low for a third line: the detail goes beside the icon, the pair centred - const int room = r.width - 6 - iconSize - 4; - const int detailWidth = std::min(small.textWidth(tile.detail), room); - const int left = r.x + (r.width - (iconSize + 4 + detailWidth)) / 2; - drawMenuIcon(canvas, tile.icon, left + iconSize / 2, top + iconSize / 2, iconSize, color); - drawClippedText(canvas, small, left + iconSize + 4, top + (iconSize - small.lineHeight()) / 2, tile.detail, detailWidth, detailColor); - } else { - drawMenuIcon(canvas, tile.icon, r.x + r.width / 2, top + iconSize / 2, iconSize, color); - } - // A label too wide for the tile takes the small font before it is cut - Font& labelFont = font.textWidth(tile.label) > r.width - 6 && small.textWidth(tile.label) <= r.width - 6 ? small : font; - drawCentredText(canvas, labelFont, r.x + 3, labelY + (font.lineHeight() - labelFont.lineHeight()) / 2, r.width - 6, tile.label, color); - if (reserve && tile.detail[0] != '\0') { - drawCentredText(canvas, small, r.x + 3, labelY + font.lineHeight() + 1, r.width - 6, tile.detail, detailColor); - } - } - - if (dotsY > 0) { - const int count = pageCount(); - const int left = canvas.width / 2 - (count - 1) * DOT_SPACING / 2; - for (int i = 0; i < count; i++) { - const auto x = static_cast(left + i * DOT_SPACING); - if (i == currentPage) { - canvas.fillCircle(x, static_cast(dotsY), 3.0f, theme.text); - } else { - canvas.ring(x, static_cast(dotsY), 2.5f, 1.2f, theme.muted); - } - } - } - if (hintY > 0) { - drawCentredText(canvas, small, MARGIN, hintY, canvas.width - 2 * MARGIN, hint, theme.muted); - } -} - -// --------------------------------------------------------------------------------------------------------------- - -void TileGrid::keepFocusValid() { - currentPage = std::clamp(currentPage, 0, pageCount() - 1); - const bool valid = (zone == Zone::Corner && hasCorner()) || (zone == Zone::Status && focusIndex < statuses) || - (zone == Zone::Tile && focusIndex < tiles); - if (!valid) { - if (tiles > 0) { - zone = Zone::Tile; - focusIndex = std::min(focusIndex, tiles - 1); - } else if (statuses > 0) { - zone = Zone::Status; - focusIndex = 0; - } else { - zone = hasCorner() ? Zone::Corner : Zone::Tile; - focusIndex = 0; - } - } - if (zone == Zone::Tile && tiles > 0) { - // Keep the page the focus is on, a grid refilled with fewer tiles may have lost its page - focusIndex = std::clamp(focusIndex, 0, tiles - 1); - currentPage = focusIndex / perPage(); - } -} - -uint16_t TileGrid::focusAction() const { - switch (zone) { - case Zone::Corner: - return hasCorner() ? corner.action : NO_ACTION; - case Zone::Status: - return focusIndex < statuses ? statusList[focusIndex].action : NO_ACTION; - case Zone::Tile: - return focusIndex < tiles ? tileList[focusIndex].action : NO_ACTION; - } - return NO_ACTION; -} - -void TileGrid::setFocusAction(uint16_t action, bool show) { - shown = show; - for (int i = 0; i < tiles; i++) { - if (tileList[i].action == action) { - moveFocusTo(Zone::Tile, i); - return; - } - } - for (int i = 0; i < statuses; i++) { - if (statusList[i].action == action) { - moveFocusTo(Zone::Status, i); - return; - } - } - if (hasCorner() && corner.action == action) { - moveFocusTo(Zone::Corner, 0); - } -} - -bool TileGrid::moveFocusTo(Zone newZone, int index) { - const bool changed = newZone != zone || index != focusIndex; - zone = newZone; - focusIndex = index; - if (zone == Zone::Tile) { - currentPage = index / perPage(); - } - return changed; -} - -void TileGrid::focusNearestTile(int centreX) { - const int first = currentPage * perPage(); - int best = first; - int bestDistance = 1 << 30; - for (int c = 0; c < columns && first + c < tiles; c++) { - const Rect r = tileRect(first + c); - const int distance = std::abs(r.x + r.width / 2 - centreX); - if (distance < bestDistance) { - bestDistance = distance; - best = first + c; - } - } - moveFocusTo(Zone::Tile, best); -} - -void TileGrid::focusNearestStatus(int centreX) { - int best = 0; - int bestDistance = 1 << 30; - for (int i = 0; i < statuses; i++) { - const Rect r = statusRect(i); - const int distance = std::abs(r.x + r.width / 2 - centreX); - if (distance < bestDistance) { - bestDistance = distance; - best = i; - } - } - moveFocusTo(Zone::Status, best); -} - -bool TileGrid::stepTile(int dx, int dy) { - const int pp = perPage(); - const int i = focusIndex; - const int page = i / pp; - const int row = (i % pp) / columns; - const int column = i % columns; - if (dx > 0) { - if (column < columns - 1 && i + 1 < tiles) { - return moveFocusTo(Zone::Tile, i + 1); - } - if ((page + 1) * pp < tiles) { - // Next page, same row, first column (or the last tile when that row is not filled) - return moveFocusTo(Zone::Tile, std::min((page + 1) * pp + row * columns, tiles - 1)); - } - return false; - } - if (dx < 0) { - if (column > 0) { - return moveFocusTo(Zone::Tile, i - 1); - } - if (page > 0) { - return moveFocusTo(Zone::Tile, (page - 1) * pp + row * columns + columns - 1); - } - return false; - } - if (dy > 0) { - if (row < usedRows - 1) { - const int below = std::min(i + columns, tiles - 1); - return below > i && moveFocusTo(Zone::Tile, below); - } - return false; - } - if (row > 0) { - return moveFocusTo(Zone::Tile, i - columns); - } - const Rect r = tileRect(i); - if (statuses > 0) { - focusNearestStatus(r.x + r.width / 2); - return true; - } - if (hasCorner()) { - return moveFocusTo(Zone::Corner, 0); - } - return false; -} - -bool TileGrid::step(int dx, int dy) { - switch (zone) { - case Zone::Tile: - return stepTile(dx, dy); - case Zone::Status: - if (dx != 0) { - const int next = std::clamp(focusIndex + dx, 0, statuses - 1); - return moveFocusTo(Zone::Status, next); - } - if (dy < 0) { - return hasCorner() && moveFocusTo(Zone::Corner, 0); - } - if (tiles > 0) { - const Rect r = statusRect(focusIndex); - focusNearestTile(r.x + r.width / 2); - return true; - } - return false; - case Zone::Corner: - if (dy > 0) { - if (statuses > 0) { - focusNearestStatus(cornerBox.x + cornerBox.width / 2); - return true; - } - if (tiles > 0) { - focusNearestTile(cornerBox.x + cornerBox.width / 2); - return true; - } - } - return false; - } - return false; -} - -bool TileGrid::move(int dx, int dy) { - if (dx == 0 && dy == 0) { - return false; - } - keepFocusValid(); - if (!shown) { - // The first step shows the highlight where the focus is, it does not move yet - shown = true; - return true; - } - return step(dx, dy); -} - -int TileGrid::ordinalCount() const { - return (hasCorner() ? 1 : 0) + statuses + tiles; -} - -int TileGrid::ordinalOf(Zone z, int index) const { - const int cornerCount = hasCorner() ? 1 : 0; - switch (z) { - case Zone::Corner: - return 0; - case Zone::Status: - return cornerCount + index; - case Zone::Tile: - return cornerCount + statuses + index; - } - return 0; -} - -void TileGrid::focusOrdinal(int ordinal) { - const int cornerCount = hasCorner() ? 1 : 0; - if (ordinal < cornerCount) { - moveFocusTo(Zone::Corner, 0); - } else if (ordinal < cornerCount + statuses) { - moveFocusTo(Zone::Status, ordinal - cornerCount); - } else { - moveFocusTo(Zone::Tile, ordinal - cornerCount - statuses); - } -} - -GridEvent TileGrid::chosen() const { - const uint16_t action = focusAction(); - if (action == NO_ACTION) { - return { GridResult::None, 0 }; - } - return { GridResult::Chosen, action }; -} - -GridEvent TileGrid::handleKey(uint32_t key) { - const GridEvent none { GridResult::None, 0 }; - switch (key) { - case 'w': - case 'W': - case keys::UP: - move(0, -1); - return none; - case 's': - case 'S': - case keys::DOWN: - move(0, 1); - return none; - case 'a': - case 'A': - case keys::LEFT: - move(-1, 0); - return none; - case 'd': - case 'D': - case keys::RIGHT: - move(1, 0); - return none; - case keys::TAB: - case keys::FOCUS_NEXT: - case keys::FOCUS_PREVIOUS: { - keepFocusValid(); - const int count = ordinalCount(); - if (!shown) { - shown = true; - } else if (count > 0) { - const int direction = key == keys::FOCUS_PREVIOUS ? count - 1 : 1; - focusOrdinal((ordinalOf(zone, focusIndex) + direction) % count); - } - return none; - } - case keys::ENTER: - case ' ': - case keys::YES: - if (!shown) { - shown = true; - return none; - } - return chosen(); - case keys::ESCAPE: - case keys::BACKSPACE: - case keys::NO: - case 'm': - case 'M': - return { GridResult::Back, 0 }; - default: - return none; - } -} - -bool TileGrid::pick(int x, int y, Zone& pickedZone, int& index) const { - if (hasCorner() && cornerBox.contains(x, y)) { - pickedZone = Zone::Corner; - index = 0; - return true; - } - for (int i = 0; i < statuses; i++) { - if (statusRect(i).contains(x, y)) { - pickedZone = Zone::Status; - index = i; - return true; - } - } - const int first = currentPage * perPage(); - const int last = std::min(tiles, first + perPage()); - for (int i = first; i < last; i++) { - if (tileRect(i).contains(x, y)) { - pickedZone = Zone::Tile; - index = i; - return true; - } - } - return false; -} - -GridEvent TileGrid::handleTap(int x, int y) { - if (header.back.contains(x, y)) { - return { GridResult::Back, 0 }; - } - Zone pickedZone; - int index; - if (!pick(x, y, pickedZone, index)) { - return { GridResult::None, 0 }; - } - // The focus follows the tap without showing the highlight, as ListView::select does - moveFocusTo(pickedZone, index); - return chosen(); -} - -void TileGrid::hover(int x, int y) { - Zone pickedZone; - int index; - if (pick(x, y, pickedZone, index)) { - moveFocusTo(pickedZone, index); - shown = true; - } -} - -bool TileGrid::swipe(int direction) { - const int target = std::clamp(currentPage + (direction < 0 ? -1 : 1), 0, pageCount() - 1); - if (target == currentPage || direction == 0) { - return false; - } - currentPage = target; - if (zone == Zone::Tile) { - // The focus stays in the same place of the new page - const int local = focusIndex % perPage(); - focusIndex = std::min(target * perPage() + local, tiles - 1); - } - return true; -} - -} // namespace maps diff --git a/Apps/Maps/main/Source/ui/TileGrid.h b/Apps/Maps/main/Source/ui/TileGrid.h deleted file mode 100644 index e720c716..00000000 --- a/Apps/Maps/main/Source/ui/TileGrid.h +++ /dev/null @@ -1,169 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-or-later -#pragma once - -#include "Canvas.h" -#include "MenuIcons.h" -#include "Widgets.h" - -#include - -namespace maps { - -/** What an input did to a tile grid. */ -enum class GridResult : uint8_t { - None, - Chosen, - Back -}; - -struct GridEvent { - GridResult result; - /** The action of the chosen tile, status item or corner button; only set when result is Chosen. */ - uint16_t action; -}; - -/** - * A full screen menu of tiles (an icon with a label under it) in a grid, a 2-D neighbour of ListView. Under the header - * with its back chevron and an optional corner button it can show a strip of up to three status items (a running - * download, the route), then the tiles, page dots when the tiles need more than one page, and a hint line. - * - * Tiles are at most about 8 x 7 line heights and the grid is centred, so a big screen shows a compact menu rather than - * slabs; on a screen too low for readable tiles a page shows fewer rows and the rest moves to more pages. - * - * One focus moves over three zones: the corner button, the status strip and the tiles. As in ListView the highlight - * stays hidden until the first key or trackball step, and touch never shows it. - */ -class TileGrid { -public: - static constexpr int MAX_TILES = 24; - static constexpr int MAX_STATUS = 3; - static constexpr int LABEL_LENGTH = 16; - static constexpr int STATUS_LENGTH = 28; - static constexpr int TITLE_LENGTH = 32; - static constexpr int HINT_LENGTH = 64; - /** What focusAction() returns when nothing can be focused. */ - static constexpr uint16_t NO_ACTION = 0xFFFF; - - /** - * Removes the tiles, status items and the corner button and puts the focus on the first tile. The title, hint, grid - * size and the shown highlight stay, so a menu filled again keeps them. - */ - void clear(); - void setTitle(const char* text); - void setGrid(int columns, int rows); - /** Returns the tile's index, -1 when full. */ - int addTile(uint16_t action, MenuIcon icon, const char* label, const char* detail = nullptr); - /** Changes the small text of the tile with this action. An empty or null text removes it. */ - void setDetail(uint16_t action, const char* detail); - /** Adds a status item to the strip (up to three). Without any, the strip is not shown. */ - void addStatus(uint16_t action, MenuIcon icon, const char* text); - /** A button at the right end of the header; a null label removes it. */ - void setCorner(uint16_t action, const char* label); - /** A line at the very bottom; a null or empty text removes it. */ - void setHint(const char* hint); - - /** Computes the rectangles. The small font is for details, the hint and the corner button (default: font). */ - void layout(int width, int height, Font& font, Font* smallFont = nullptr); - /** Uses the fonts given to layout(), which must still exist. */ - void draw(Canvas& canvas, Font& font, const UiTheme& theme) const; - - /** Arrows and WASD move, Tab goes through everything in reading order, Enter and Space choose, Esc, Backspace and M go back. */ - GridEvent handleKey(uint32_t key); - /** A tap on a tile, status item or the corner button chooses it, the back chevron goes back. */ - GridEvent handleTap(int x, int y); - /** Pointer mode: the item under the pointer gets the focus and shows as hovered. */ - void hover(int x, int y); - /** Moves the focus one step (trackball). The first step only shows the highlight. Returns whether anything changed. */ - bool move(int dx, int dy); - /** Shows the previous (-1) or next (+1) page, for touch drags. Returns whether the page changed. */ - bool swipe(int direction); - - /** The action under the focus, NO_ACTION when there is nothing. */ - uint16_t focusAction() const; - /** Puts the focus on the item with this action, to remember the last one; the page follows. */ - void setFocusAction(uint16_t action, bool shown); - bool focusShown() const { return shown; } - - Rect tileRect(int index) const; - Rect statusRect(int index) const; - Rect cornerRect() const { return cornerBox; } - /** For tests: the header's back area, the rows a page shows after layout(), the columns, and the grid's box. */ - const Rect& backRect() const { return header.back; } - int shownRows() const { return usedRows; } - int shownColumns() const { return columns; } - const Rect& gridBounds() const { return gridBox; } - const Rect& stripBounds() const { return stripBox; } - int tileCount() const { return tiles; } - int statusCount() const { return statuses; } - int page() const { return currentPage; } - int pageCount() const; - -private: - enum class Zone : uint8_t { Corner, Status, Tile }; - - struct Tile { - uint16_t action; - MenuIcon icon; - char label[LABEL_LENGTH]; - char detail[LABEL_LENGTH]; - }; - - struct Status { - uint16_t action; - MenuIcon icon; - char text[STATUS_LENGTH]; - }; - - int perPage() const { return columns * usedRows; } - bool hasCorner() const { return corner.label[0] != '\0'; } - int ordinalCount() const; - int ordinalOf(Zone zone, int index) const; - void focusOrdinal(int ordinal); - void keepFocusValid(); - void focusNearestTile(int centreX); - void focusNearestStatus(int centreX); - bool step(int dx, int dy); - bool stepTile(int dx, int dy); - bool moveFocusTo(Zone zone, int index); - bool pick(int x, int y, Zone& zone, int& index) const; - GridEvent chosen() const; - - struct Corner { - uint16_t action = 0; - char label[LABEL_LENGTH] = ""; - }; - - Tile tileList[MAX_TILES] {}; - Status statusList[MAX_STATUS] {}; - Corner corner {}; - int tiles = 0; - int statuses = 0; - int columns = 3; - int rows = 3; - /** The rows a page really shows: rows, fewer when the screen is too low for readable tiles (more pages then). */ - int usedRows = 3; - char title[TITLE_LENGTH] = ""; - char hint[HINT_LENGTH] = ""; - - Zone zone = Zone::Tile; - int focusIndex = 0; - int currentPage = 0; - bool shown = false; - - // Set by layout() - int screenWidth = 0; - int screenHeight = 0; - HeaderLayout header {}; - Rect cornerBox {}; - Rect stripBox {}; - Rect gridBox {}; - int tileWidth = 0; - int tileHeight = 0; - int gridLeft = 0; - int dotsY = 0; - int hintY = 0; - Font* mainFont = nullptr; - Font* smallFontPtr = nullptr; -}; - -} // namespace maps diff --git a/Apps/Maps/main/Source/ui/Widgets.h b/Apps/Maps/main/Source/ui/Widgets.h index 3b9e2b42..296ec61d 100644 --- a/Apps/Maps/main/Source/ui/Widgets.h +++ b/Apps/Maps/main/Source/ui/Widgets.h @@ -89,6 +89,7 @@ class ListView { const char* label(int index) const { return items[index].label; } const char* detail(int index) const { return items[index].detail; } int selected() const { return selection; } + const char* titleText() const { return title; } /** Moves the selection without showing the highlight. */ void select(int index); /** diff --git a/Apps/Maps/manifest.properties b/Apps/Maps/manifest.properties index 53dd7c6f..037b9124 100644 --- a/Apps/Maps/manifest.properties +++ b/Apps/Maps/manifest.properties @@ -1,12 +1,13 @@ manifest.version=0.3 target.sdk=0.8.0-dev -target.platforms=esp32s3,esp32p4 +target.platforms=esp32s3,esp32p4,esp32s31 id=tactility.maps -version.name=0.10.1 -version.code=14 +version.name=0.11.0 +version.code=15 app.0.id=tactility.maps app.0.name=Maps app.0.binary=maps +app.0.stack.depth=12288 name=Maps description.short=Offline vector maps description=High-detail vector maps: get live maps via Wi-Fi, or download them to your SD card before your trip.\n\nFeatures terrain with hillshade and contour lines, an outdoor style for hiking, offline search, and navigation for walking, cycling, and driving with elevation profiles. Waypoints and GPX tracks can be shown or navigated to.\n\nWorks with keyboard, trackball, or touch only. Requires an ESP32-S3 or ESP32-P4 device with at least 8 MB PSRAM.\n\nTested on the LilyGO T-Deck and SeeedStudio Wio Tracker L2 Pro.\n\nMap data provided by OpenFreeMap & OpenStreetMap.