diff --git a/Apps/Maps/CHANGELOG.md b/Apps/Maps/CHANGELOG.md index 9097929..83e4eb8 100644 --- a/Apps/Maps/CHANGELOG.md +++ b/Apps/Maps/CHANGELOG.md @@ -1,6 +1,10 @@ # Changelog -## 0.11.0 (in work) +## 0.11.1 (in work) + +- Maps: fixes that weren't pushed after a round of feedback in the previous pull request + +## 0.11.0 **Downloaded maps** - Maps with the same name (for example several areas named "Slovakia") are one row of the list, with their size @@ -87,7 +91,8 @@ - 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. + most half of what is theirs. Prepared tiles of originals from 256 KB that were made before are made again, and + their drawings in the SD cache (also the magnified ones) are deleted. - 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. diff --git a/Apps/Maps/main/Source/app/Debug.cpp b/Apps/Maps/main/Source/app/Debug.cpp index 3d85ce5..188da2a 100644 --- a/Apps/Maps/main/Source/app/Debug.cpp +++ b/Apps/Maps/main/Source/app/Debug.cpp @@ -124,6 +124,12 @@ DebugScript::Step DebugScript::next(uint32_t now) { } return step; } + if (strcmp(command, "menu") == 0) { + // values[0]: the row or tile, -1 for back + step.action = Action::Menu; + step.values[0] = strcmp(argument, "back") == 0 ? -1.0f : static_cast(atoi(argument)); + return step; + } if (strcmp(command, "shot") == 0) { step.action = Action::Shot; snprintf(step.name, sizeof(step.name), "%s", argument); diff --git a/Apps/Maps/main/Source/app/Debug.h b/Apps/Maps/main/Source/app/Debug.h index 9be35ea..e733c60 100644 --- a/Apps/Maps/main/Source/app/Debug.h +++ b/Apps/Maps/main/Source/app/Debug.h @@ -66,7 +66,12 @@ class DebugScript { /** "waittrails": waits until a trails query runs (at most 3 minutes). */ WaitTrails, /** "followgpx ": follows the track of a GPX file in the app's folder. */ - FollowGpx + FollowGpx, + /** + * "menu " chooses tile or row n of the LVGL menu or page that is shown (a main menu tile: its MenuAction + * number), "menu back" goes back. LVGL reads keys and the pointer itself, so "key" and "pointer" don't reach it. + */ + Menu }; enum class TouchKind : uint8_t { Tap, Hold, Drag, Pinch, Twist }; diff --git a/Apps/Maps/main/Source/app/Downloader.cpp b/Apps/Maps/main/Source/app/Downloader.cpp index 4c53ae1..df1af81 100644 --- a/Apps/Maps/main/Source/app/Downloader.cpp +++ b/Apps/Maps/main/Source/app/Downloader.cpp @@ -38,8 +38,6 @@ constexpr uint32_t CONNECTION_STACK = 6144; constexpr UBaseType_t TASK_PRIORITY = 3; /** Tiles at this zoom level and below are downloaded one at a time. */ constexpr int ALONE_MAX_ZOOM = 7; -/** Idle keep-alive connections are closed after this long, a new one costs a full TLS handshake. */ -constexpr uint32_t IDLE_CLOSE_MS = 60000; /** After heights failed in idle time, the next try waits this long. */ constexpr uint32_t TERRAIN_RETRY_MS = 120000; /** Idle-time heights start only with an internal RAM block this large free (they worked with 10 KB, failed with 2.9 KB). */ @@ -125,8 +123,12 @@ class HttpBodyInput final : public ByteInput { private: void fill() { - if (aheadSize == 0 && !error && !ended) { - aheadSize = static_cast(std::max(0, account(http_client_read(client, ahead, sizeof(ahead))))); + // A read can return a single byte while more follow: read on until the two of the gzip signature are in + while (aheadSize < 2 && !error && !ended) { + const int got = account(http_client_read(client, ahead + aheadSize, sizeof(ahead) - aheadSize)); + if (got > 0) { + aheadSize += static_cast(got); + } } } @@ -205,6 +207,11 @@ constexpr size_t READ_PIECE_BYTES = 1024; } // namespace std::atomic Downloader::handshakes = 0; +std::atomic Downloader::handshakeStartMs = 0; + +bool Downloader::isHandshaking() { + return handshakes.load() > 0 && nowMs() - handshakeStartMs.load() < HANDSHAKE_MS; +} const char* Downloader::resultName(HttpResult result) { switch (result) { @@ -239,6 +246,7 @@ void Downloader::beginHandshake(Connection& connection) { // Not taken in time (another handshake hangs): go on without it, and do not give it back connection.handshakeLocked = xSemaphoreTake(handshakeLock, pdMS_TO_TICKS(HTTP_TIMEOUT_MS)) == pdTRUE; connection.handshaking = true; + handshakeStartMs = nowMs(); handshakes++; } @@ -255,7 +263,7 @@ void Downloader::endHandshake(Connection& connection) { 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); + auto* client = 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. @@ -293,9 +301,8 @@ void Downloader::setActive(HttpClient* client, bool active) { } 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; + setActive(connection.client, false); + http_client_close(connection.client); if (transferLocked) { xSemaphoreGive(transferLock); } @@ -309,7 +316,7 @@ void Downloader::closeRequest(Connection& connection, const char* method, HttpRe 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); + auto* client = connection.client; bool transferLocked = false; HttpResult result = openRequest(connection, method, url, status, transferLocked, body, bodySize); if (result == HttpResult::Ok) { @@ -355,75 +362,16 @@ void Downloader::cancelWaitingQuery(bool onlyQuiet) { } void Downloader::takeClient(Connection& connection) { - if (connection.client != nullptr) { - return; - } - xSemaphoreTake(mutex, portMAX_DELAY); - if (idleCount > 0) { - // The most recently used one, the least likely to have been closed by the server - idleCount--; - connection.client = idleClients[idleCount].client; - connection.connected = true; - } - xSemaphoreGive(mutex); if (connection.client == nullptr) { connection.client = createClient(ROOT_CERTIFICATES, HTTP_TIMEOUT_MS); - connection.connected = false; } } void Downloader::dropClient(Connection& connection) { if (connection.client != nullptr) { - http_client_free(static_cast(connection.client)); + http_client_free(connection.client); connection.client = nullptr; } - connection.connected = false; -} - -void Downloader::giveClient(Connection& connection) { - if (connection.client == nullptr) { - return; - } - if (!connection.connected) { - dropClient(connection); - return; - } - xSemaphoreTake(mutex, portMAX_DELAY); - void* surplus = nullptr; - if (idleCount < IDLE_CLIENTS) { - idleClients[idleCount++] = { connection.client, nowMs() }; - } else { - surplus = connection.client; - } - xSemaphoreGive(mutex); - if (surplus != nullptr) { - http_client_free(static_cast(surplus)); - } - connection.client = nullptr; - connection.connected = false; -} - -void Downloader::closeIdleClients(uint32_t maxIdleMs) { - void* closing[IDLE_CLIENTS] {}; - int closingCount = 0; - xSemaphoreTake(mutex, portMAX_DELAY); - const uint32_t now = nowMs(); - int kept = 0; - for (int i = 0; i < idleCount; i++) { - if (now - idleClients[i].sinceMs >= maxIdleMs) { - closing[closingCount++] = idleClients[i].client; - } else { - idleClients[kept++] = idleClients[i]; - } - } - idleCount = kept; - xSemaphoreGive(mutex); - for (int i = 0; i < closingCount; i++) { - http_client_free(static_cast(closing[i])); - } - if (closingCount > 0) { - logInfo("TLS: closed %d idle connection(s)", closingCount); - } } namespace { @@ -705,9 +653,6 @@ void Downloader::stop() { endNetworkTask(browseTask); browseTask = nullptr; } - if (mutex != nullptr) { - closeIdleClients(0); - } for (SemaphoreHandle_t* handle : { &mutex, &wake, &stopped, &connectionsDone, &tileJsonLock, &browseMetaLock, &browseWake, &browseStopped, &handshakeLock, &transferLock }) { if (*handle != nullptr) { @@ -957,7 +902,6 @@ void Downloader::controlLoop() { continue; } if (!woken) { - closeIdleClients(IDLE_CLOSE_MS); if (!stopRequested && terrainWithDownloads) { runPendingTerrain(); } @@ -1041,9 +985,9 @@ bool Downloader::fetchTileJson(Connection& connection) { http_client_free(plain); } } - // Through a pooled keep-alive connection, which the tile requests after it then reuse + // A client of its own, freed when done (no connection is kept between requests) takeClient(connection); - auto* client = static_cast(connection.client); + auto* client = connection.client; if (client == nullptr || connection.body == nullptr) { return false; } @@ -1350,7 +1294,7 @@ void Downloader::connectionLoop(Connection& connection) { } } // Kept open for the next download, browsing or an update - giveClient(connection); + dropClient(connection); } void Downloader::runDownload() { @@ -1377,7 +1321,7 @@ void Downloader::runDownload() { connections[0].index = 0; connections[0].body = &bodies[0]; const bool tileJson = ensureTileJson(connections[0]); - giveClient(connections[0]); + dropClient(connections[0]); bodies[0].release(); if (!tileJson) { setStatus(State::Failed, "OpenFreeMap is not reachable"); @@ -1730,16 +1674,24 @@ bool Downloader::runTrailsArea(const char* regionName, const BoundingBox& box, b int status = 0; size_t received = 0; if (connection.client != nullptr) { - auto* client = static_cast(connection.client); + auto* client = connection.client; http_client_set_header(client, "Content-Type", "application/x-www-form-urlencoded"); xSemaphoreTake(mutex, portMAX_DELAY); - waitingQuery = client; + // A tile queued since runPendingTrails looked would not cancel a query that isn't published yet: a quiet one + // gives way now, before it holds the connection for the server's 30-40 s + const bool yieldNow = quiet && (browsing || browseCount > 0); + waitingQuery = yieldNow ? nullptr : client; waitingQueryQuiet = quiet; + waitingQueryYielded = yieldNow; 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++) { + if (yieldNow) { + trailsYielded = true; + logInfo("Trails for %s: gave way to browsing before asking", regionName); + } + for (int attempt = 1; attempt <= attempts && !yieldNow && !fetched && !cancelRequested && !stopRequested; attempt++) { const uint32_t asked = nowMs(); bool transferLocked = false; HttpResult result = openRequest(connection, "POST", OVERPASS_URL, status, transferLocked, post, strlen(post)); @@ -1779,6 +1731,16 @@ bool Downloader::runTrailsArea(const char* regionName, const BoundingBox& box, b } } } + if (ok && gzip) { + // The inflater stops at the end of the deflate stream, and also on a damaged or cut-short one: only + // a whole stream counts. The rest of the body (the gzip trailer) is read too, within the size limit. + if (inflater->failed()) { + ok = false; + } else { + while (input.read(piece, 4096) > 0) { + } + } + } received = input.received(); cancelled = input.cancelled(); tooLarge = input.tooLarge(); @@ -1801,7 +1763,11 @@ bool Downloader::runTrailsArea(const char* regionName, const BoundingBox& box, b } } closeRequest(connection, "POST", result, transferLocked); - if (cancelled && quiet && (browsing || browseCount > 0)) { + // Whether browsing cancelled it, as browse() recorded: the browse queue may be empty again by now + xSemaphoreTake(mutex, portMAX_DELAY); + const bool yielded = waitingQueryYielded; + xSemaphoreGive(mutex); + if (cancelled && quiet && yielded) { trailsYielded = true; logInfo("Trails for %s: gave way to browsing after %u ms", regionName, static_cast(nowMs() - asked)); break; @@ -2061,7 +2027,7 @@ 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 = connection.client; connection.body->clear(); HttpResult result = HttpResult::Failed; bool pieceYielded = false; @@ -2310,6 +2276,7 @@ void Downloader::browse(const TileKey* tiles, int count) { 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); + waitingQueryYielded = true; } xSemaphoreGive(mutex); if (added) { @@ -2483,7 +2450,6 @@ void Downloader::browseLoop() { browseConnection = { this, CONNECTIONS, nullptr, &browseBody, 0, nullptr, "" }; while (!stopRequested) { if (xSemaphoreTake(browseWake, SWEEP_TICKS) != pdTRUE) { - closeIdleClients(IDLE_CLOSE_MS); continue; } if (warmUp.exchange(false) && wifiConnected()) { @@ -2529,7 +2495,7 @@ void Downloader::browseLoop() { if (terrainWithDownloads || trailsWithDownloads) { xSemaphoreGive(wake); } - giveClient(browseConnection); + dropClient(browseConnection); browseBody.release(); if (browseUnsaved > 0) { browseUnsaved = 0; @@ -2690,9 +2656,6 @@ void Downloader::runPendingTerrain() { if (!browsedWaiting && !(terrainSweep && updatesAllowed)) { return; } - // The kept OpenFreeMap connections give their TLS memory back first: kept open, the two sessions took internal RAM - // down to 6 KB during a terrain transfer and its AES buffers failed (16 Nov). The next browsed tile pays a handshake. - closeIdleClients(0); if (heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) < TERRAIN_INTERNAL_BLOCK) { return; } @@ -2865,8 +2828,6 @@ void Downloader::runPendingTrails() { if (!found && !sweepDue) { return; } - // The kept OpenFreeMap connections give their TLS memory back first (as for heights) - closeIdleClients(0); const bool roomy = heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) >= TERRAIN_INTERNAL_BLOCK; if (found) { if (!roomy || !claimIdle()) { @@ -3082,12 +3043,12 @@ void Downloader::runUpdate(bool manual) { connection.received = 0; connection.lastFolder[0] = '\0'; if (!ensureTileJson(connection)) { - giveClient(connection); + dropClient(connection); setStatus(State::Failed, "OpenFreeMap is not reachable"); return; } if (strcmp(target.version, version) == 0) { - giveClient(connection); + dropClient(connection); setStatus(State::Done, "Region is up to date"); return; } @@ -3097,7 +3058,7 @@ void Downloader::runUpdate(bool manual) { progress.total = target.total; progress.bits = static_cast(largeAlloc(progress.bitBytes())); if (progress.bits == nullptr) { - giveClient(connection); + dropClient(connection); setStatus(State::Failed, "Out of memory"); return; } @@ -3123,7 +3084,7 @@ void Downloader::runUpdate(bool manual) { const DownloadPlan plan = target.plan(); if (!loadOutlineTiles(target)) { largeFree(progress.bits); - giveClient(connection); + dropClient(connection); setStatus(State::Failed, outlineNoMemory ? "Not enough memory for the region list" : "Region outline is missing"); return; } @@ -3193,7 +3154,7 @@ void Downloader::runUpdate(bool manual) { for (int64_t index = 0; index < progress.total && !stopNow() && !failedTile; index++) { failedTile = !updateOne(index); } - giveClient(connection); + dropClient(connection); bodies[0].release(); freeOutlineTiles(); diff --git a/Apps/Maps/main/Source/app/Downloader.h b/Apps/Maps/main/Source/app/Downloader.h index e0b867f..73e42c4 100644 --- a/Apps/Maps/main/Source/app/Downloader.h +++ b/Apps/Maps/main/Source/app/Downloader.h @@ -50,8 +50,13 @@ class Downloader { * lane there made no progress for its whole length (docs/upstream/https-stall.md). */ static constexpr BaseType_t NETWORK_CORE = 1; - /** Whether a TLS handshake is running on the network core now; the render lane there waits for it. */ - static bool isHandshaking() { return handshakes.load() > 0; } + /** + * Whether a TLS handshake is running on the network core now; the render lane there waits for it. The HTTP client + * doesn't tell when TLS is done and only the response headers are left to wait for (Overpass takes up to a minute + * for them): a request counts as handshaking for HANDSHAKE_MS from its start, the longest a handshake takes. + */ + static bool isHandshaking(); + static constexpr uint32_t HANDSHAKE_MS = 4000; enum class State : uint8_t { Idle, @@ -201,18 +206,16 @@ class Downloader { struct Connection { Downloader* owner; int index; - void* client; + HttpClient* client; ChunkedBody* body; uint64_t received; TaskHandle_t task; char lastFolder[PATH_MAX_LENGTH]; - /** When the request now running started, and how long its TCP and TLS connect took (0: reused). */ + /** When the request now running started, and how long its TCP and TLS connect took. */ uint32_t requestStartMs = 0; uint32_t connectMs = 0; /** The largest answer taken (0: MAX_TILE_BYTES). */ size_t maxBytes = 0; - /** Whether the client has an open connection the next request can reuse. */ - bool connected = false; /** Whether this connection holds the handshake lock. */ bool handshaking = false; /** This connection holds the handshake lock (taking it can time out). */ @@ -233,11 +236,6 @@ class Downloader { /** Takes the bytes of moved and removed tiles off the browsed region's meta.json. */ void settleBrowsed(uint64_t removedBytes); - struct IdleClient { - void* client; - uint32_t sinceMs; - }; - /** How a request went. */ enum class HttpResult : uint8_t { Ok, @@ -267,12 +265,13 @@ class Downloader { void cancelWaitingQuery(bool onlyQuiet); void beginHandshake(Connection& connection); void endHandshake(Connection& connection); - /** Gives connection an open pooled client, or a new one. */ - void takeClient(Connection& connection); - /** Returns connection's client to the pool when it is still connected, otherwise closes it. */ - void giveClient(Connection& connection); + /** + * Gives connection a client when it has none. Every request opens its own connection and closes it when done + * ("Connection: close"), so a client is never kept open between requests. + */ + static void takeClient(Connection& connection); + /** Frees connection's client. */ static void dropClient(Connection& connection); - void closeIdleClients(uint32_t maxIdleMs); bool queue(Job next, const char* region); static void controlMain(void* context); static void connectionMain(void* context); @@ -457,14 +456,18 @@ class Downloader { int64_t activeIndex[CONNECTIONS] {}; int64_t sinceSave = 0; std::atomic failed = false; - static constexpr int IDLE_CLIENTS = CONNECTIONS + 1; - IdleClient idleClients[IDLE_CLIENTS] {}; - int idleCount = 0; SemaphoreHandle_t handshakeLock = nullptr; static std::atomic handshakes; + /** When the latest handshake began. */ + static std::atomic handshakeStartMs; /** The trails query waiting for its answer (under mutex), so that browsing and cancelling can break it off. */ HttpClient* waitingQuery = nullptr; bool waitingQueryQuiet = false; + /** + * Browsing cancelled the waiting query (under mutex): it gave way, no failure. Kept apart from the browse queue, + * which the browse task may have emptied by the time the query sees its cancellation. + */ + bool waitingQueryYielded = 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] {}; diff --git a/Apps/Maps/main/Source/app/LvglMenu.cpp b/Apps/Maps/main/Source/app/LvglMenu.cpp index 0688a6b..a683f4e 100644 --- a/Apps/Maps/main/Source/app/LvglMenu.cpp +++ b/Apps/Maps/main/Source/app/LvglMenu.cpp @@ -20,14 +20,33 @@ namespace maps { namespace { +/** Copies text, cut at a character boundary when it doesn't fit, so the copy stays valid UTF-8 */ void copyText(char* out, size_t size, const char* text) { - snprintf(out, size, "%s", text != nullptr ? text : ""); + if (size == 0) { + return; + } + const char* source = text != nullptr ? text : ""; + size_t length = strlen(source); + if (length >= size) { + length = size - 1; + // Back to the first byte of the character that was cut, which goes too + while (length > 0 && (static_cast(source[length]) & 0xC0) == 0x80) { + length--; + } + } + memcpy(out, source, length); + out[length] = '\0'; } bool isBackKey(uint32_t key) { return key == LV_KEY_ESC || key == LV_KEY_BACKSPACE; } +/** M opens the main menu on the map, and closes it again */ +bool isMenuKey(uint32_t key) { + return key == 'm' || key == 'M'; +} + /** The widgets are built for the app's focus group, as the window manager does for a window's own widgets. */ class AppGroupScope { public: @@ -112,6 +131,10 @@ void LvglMenu::buildToastLocked() { 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; + if (!update) { + // Events of the view this replaces mean nothing for the menu + queueCount = 0; + } newButtonCount = std::min(newButtonCount, MAX_BUTTONS); bool sameButtons = newButtonCount == buttonCount; for (int i = 0; sameButtons && i < newButtonCount; i++) { @@ -149,20 +172,26 @@ uint16_t LvglMenu::focusedTileLocked() const { 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) { +bool LvglMenu::showList(const char* titleText, const char* const* labels, const char* const* details, const char* const* descriptions, + int count, int focus, bool newView) { if (rowText == nullptr) { - rowText = static_cast(largeAlloc(static_cast(2 * MAX_ROWS) * TEXT_LENGTH)); + rowText = static_cast(largeAlloc(static_cast(3 * MAX_ROWS) * TEXT_LENGTH)); if (rowText == nullptr) { logError("LVGL menu: no memory for the rows"); - return; + return false; } } lvgl_lock(); + if (newView) { + // Events of the view this replaces would act on the wrong rows; the new rows' own come after this + queueCount = 0; + } 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); + copyText(rowDescription(i), TEXT_LENGTH, descriptions != nullptr ? descriptions[i] : nullptr); } focusRow = focus; kind = Kind::List; @@ -170,36 +199,42 @@ void LvglMenu::showList(const char* titleText, const char* const* labels, const focusPending = true; buildLocked(); lvgl_unlock(); + return true; } -void LvglMenu::showText(const char* titleText, const char* const* paragraphs, int count) { +bool LvglMenu::showText(const char* titleText, const char* const* paragraphs, int count, bool newView) { 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; - } + // The new text is made first: the shown text stays valid for a rebuild (the window can come back any time) + char* replacement = static_cast(largeAlloc(size > 0 ? size : 1)); + if (replacement == nullptr) { + logError("LVGL menu: no memory for the text"); + return false; } - lvgl_lock(); - copyText(title, sizeof(title), titleText); - char* at = text; + char* at = replacement; for (int i = 0; i < count; i++) { const size_t length = strlen(paragraphs[i]); memcpy(at, paragraphs[i], length + 1); at += length + 1; } + lvgl_lock(); + if (newView) { + queueCount = 0; + } + char* old = text; + text = replacement; + textSize = size; + copyText(title, sizeof(title), titleText); paragraphCount = count; kind = Kind::Text; shown = true; focusPending = true; buildLocked(); lvgl_unlock(); + largeFree(old); + return true; } void LvglMenu::hide() { @@ -281,7 +316,7 @@ void LvglMenu::buildLocked() { 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); + lv_obj_add_event_cb(button, onGridToolbarKey, LV_EVENT_KEY, this); buttonObjects[i] = button; } } @@ -321,6 +356,19 @@ void LvglMenu::buildLocked() { lv_label_set_text(detail, rowDetail(i)); lv_obj_set_style_text_color(detail, lv_theme_get_color_secondary(detail), LV_STATE_DEFAULT); } + if (rowDescription(i)[0] != '\0') { + // What the row does, on a line of its own under the label and the detail + lv_obj_set_flex_flow(button, LV_FLEX_FLOW_ROW_WRAP); + if (lv_obj_t* label = lv_obj_get_child(button, 0)) { + lv_obj_set_flex_grow(label, 1); + } + lv_obj_t* description = lv_label_create(button); + lv_obj_set_width(description, LV_PCT(100)); + lv_label_set_long_mode(description, LV_LABEL_LONG_MODE_WRAP); + lv_label_set_text(description, rowDescription(i)); + lv_obj_set_style_text_font(description, lvgl_get_text_font(FONT_SIZE_SMALL), LV_STATE_DEFAULT); + lv_obj_set_style_text_color(description, lv_theme_get_color_secondary(description), LV_STATE_DEFAULT); + } if (focused == nullptr || i == focusRow) { focused = button; } @@ -405,11 +453,18 @@ void LvglMenu::onTileClicked(lv_obj_t*, const LvglTileGridItem* item, void* user } void LvglMenu::onTileKey(lv_obj_t*, const LvglTileGridItem*, uint32_t key, void* userData) { - if (isBackKey(key)) { + if (isBackKey(key) || isMenuKey(key)) { static_cast(userData)->push(LvglMenuEvent::Kind::Back, 0); } } +void LvglMenu::onGridToolbarKey(lv_event_t* event) { + const uint32_t key = lv_event_get_key(event); + if (isBackKey(key) || isMenuKey(key)) { + static_cast(lv_event_get_user_data(event))->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); } diff --git a/Apps/Maps/main/Source/app/LvglMenu.h b/Apps/Maps/main/Source/app/LvglMenu.h index 336c8cd..e9417c2 100644 --- a/Apps/Maps/main/Source/app/LvglMenu.h +++ b/Apps/Maps/main/Source/app/LvglMenu.h @@ -54,7 +54,8 @@ class LvglMenu { 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; + /** As long as a ListView's texts (63 bytes and the terminator) */ + static constexpr int TEXT_LENGTH = 64; static constexpr uint16_t NO_ACTION = 0xFFFF; ~LvglMenu(); @@ -69,10 +70,20 @@ class LvglMenu { * 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); + /** + * Shows a list of rows, each a label, an optional detail and an optional description under the label, with the + * focus on focusRow. Replaces what is shown. newView: it replaces another page or menu, whose queued events are + * dropped; otherwise the same page is filled again and its events stay. + * @return false when there was no memory for the rows: what was shown stays + */ + bool showList(const char* title, const char* const* labels, const char* const* details, const char* const* descriptions, int count, + int focusRow, bool newView); + /** + * Shows paragraphs of text under a toolbar; a paragraph that starts with '#' is a heading. Replaces what is shown. + * newView as for showList(). + * @return false when there was no memory for the text: what was shown stays + */ + bool showText(const char* title, const char* const* paragraphs, int count, bool newView); void hide(); bool isShown() const { return shown; } /** A short message over whatever is shown, until it is set to null or empty. */ @@ -95,6 +106,8 @@ class LvglMenu { uint16_t focusedTileLocked() const; static void onRowClicked(lv_event_t* event); static void onKey(lv_event_t* event); + /** The keys of the main menu's toolbar buttons: the back keys and M close the menu */ + static void onGridToolbarKey(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); @@ -117,10 +130,11 @@ class LvglMenu { 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. */ + /** MAX_ROWS labels, MAX_ROWS details, then MAX_ROWS descriptions, 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; } + char* rowDescription(int row) { return rowText + static_cast(2 * MAX_ROWS + row) * TEXT_LENGTH; } int rowCount = 0; int focusRow = 0; /** The text page: paragraphs one after the other, each ended by a NUL. */ diff --git a/Apps/Maps/main/Source/app/LvglOutput.cpp b/Apps/Maps/main/Source/app/LvglOutput.cpp index d0f8e34..5bebf41 100644 --- a/Apps/Maps/main/Source/app/LvglOutput.cpp +++ b/Apps/Maps/main/Source/app/LvglOutput.cpp @@ -5,6 +5,8 @@ #include #include +// For lv_indev_t::enabled: LVGL has no getter for it +#include #include #include #include @@ -220,7 +222,10 @@ void LvglOutput::present() { } 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]); + if (!scaleUp(buffers[1 - shown])) { + // That buffer holds an old or no frame: the shown one stays + return; + } } lvgl_lock(); // LVGL draws under this lock, so once the source changed it never reads the other buffer again @@ -357,6 +362,19 @@ int LvglInput::readKeys(KeyEvent* events, int maxEvents) { void LvglInput::takeLvglDevices() { lastTakeMs = nowMs(); + // Devices that are gone (a trackball that switched modes deletes its old one) are forgotten: their address can + // come back as another device, and their slot is free again + int kept = 0; + for (int i = 0; i < takenCount; i++) { + bool live = false; + for (lv_indev_t* indev = lv_indev_get_next(nullptr); indev != nullptr && !live; indev = lv_indev_get_next(indev)) { + live = indev == taken[i]; + } + if (live) { + taken[kept++] = taken[i]; + } + } + takenCount = kept; 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 @@ -364,11 +382,19 @@ void LvglInput::takeLvglDevices() { 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) { + // Disabled: taken already, or by someone else, whose choice stays. An enabled device in the list is a new + // device at an old one's address: it is disabled again. + if (!indev->enabled) { + continue; + } + const bool known = std::find(taken, taken + takenCount, indev) != taken + takenCount; + if (!known && takenCount >= MAX_TAKEN) { continue; } lv_indev_enable(indev, false); - taken[takenCount++] = indev; + if (!known) { + taken[takenCount++] = indev; + } } } diff --git a/Apps/Maps/main/Source/app/MapDebug.cpp b/Apps/Maps/main/Source/app/MapDebug.cpp index 009263d..20909f6 100644 --- a/Apps/Maps/main/Source/app/MapDebug.cpp +++ b/Apps/Maps/main/Source/app/MapDebug.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-or-later // The debug script's steps (Debug.h): the app driven from a file on the card, for tests on the device. +#include "LvglMenu.h" #include "MapView.h" #include "MapViewInternal.h" @@ -139,6 +140,17 @@ void MapView::runDebugStep(const DebugScript::Step& step, uint32_t now) { logError("Off route: no value named %s", step.name); } break; + case DebugScript::Action::Menu: + markInput(now); + if (lvglView == LvglView::None) { + logError("debug: menu, but no LVGL menu or page is shown"); + } else { + LvglMenuEvent event; + event.kind = step.values[0] < 0 ? LvglMenuEvent::Kind::Back : LvglMenuEvent::Kind::Chosen; + event.value = step.values[0] < 0 ? 0 : static_cast(step.values[0]); + dispatchLvglEvent(event); + } + break; case DebugScript::Action::Pointer: cursorX = std::clamp(static_cast(step.values[0]), 0, width - 1); cursorY = std::clamp(static_cast(step.values[1]), 0, height - 1); diff --git a/Apps/Maps/main/Source/app/MapLabels.cpp b/Apps/Maps/main/Source/app/MapLabels.cpp index e06b24a..d345282 100644 --- a/Apps/Maps/main/Source/app/MapLabels.cpp +++ b/Apps/Maps/main/Source/app/MapLabels.cpp @@ -5,6 +5,8 @@ #include "../render/PoiIconData.h" #include "../render/PoiTypes.h" +#include + #include #include #include @@ -167,6 +169,10 @@ bool MapView::openFrameFonts(const char* root) { fonts[i]->close(); if (!fonts[i]->openFile(path)) { logError("Frame font %s does not open", path); + // None of them then, not a mix: the caller falls back to the system's fonts + for (BinFontText* font : fonts) { + font->close(); + } return false; } } @@ -194,11 +200,17 @@ void MapView::pollLabelFonts() { return true; }; runOnCard(io, openWritten); - if (output->isScaledUp() && written == (1u << LabelFontMaker::COUNT) - 1) { + // Something new was made: with the ones made on an earlier run they can be all three (openFrameFonts checks) + if (output->isScaledUp() && written != 0) { // 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); + if (!runOnCard(io, openFonts)) { + // A frame font didn't open, and openFrameFonts closed them: the system's again + normalFont.borrow(FONT_SIZE_DEFAULT); + smallFont.borrow(FONT_SIZE_SMALL); + largeFont.borrow(FONT_SIZE_LARGE); + } + overlay.setFonts(&normalFont, smallFont.isOpen() ? &smallFont : &normalFont); layoutControls(); dirty = true; } diff --git a/Apps/Maps/main/Source/app/MapNavigation.cpp b/Apps/Maps/main/Source/app/MapNavigation.cpp index de5d2c1..3b7fbed 100644 --- a/Apps/Maps/main/Source/app/MapNavigation.cpp +++ b/Apps/Maps/main/Source/app/MapNavigation.cpp @@ -382,8 +382,9 @@ void MapView::fitRoute() { // The largest zoom at which the route's box fits between the mode bar and the card, north up const int cardTop = routeCard.isOpen() ? routeCard.bounds().y : height; const int barBottom = routeCard.isOpen() ? routeCard.modeBounds().y + routeCard.modeBounds().height : 0; - const double availableWidth = std::max(40, width - 32); - const double availableHeight = std::max(40, cardTop - barBottom - 24); + // In world pixels, which are magnify screen pixels wide + const double availableWidth = std::max(40, width - 32) / magnify; + const double availableHeight = std::max(40, cardTop - barBottom - 24) / magnify; int fit = 3; for (int z = 18; z >= 3; z--) { if (worldOfUnits(maxX - minX, z) <= availableWidth && worldOfUnits(maxY - minY, z) <= availableHeight) { @@ -399,7 +400,7 @@ void MapView::fitRoute() { routePointTo({ (minX + maxX) / 2, (minY + maxY) / 2 }, lat, lon); centerOn(lat, lon, fit); // Moved so the route is in the middle of the space between the bar and the card - centerY += (height - cardTop - barBottom) / 2.0; + centerY += (height - cardTop - barBottom) / 2.0 / magnify; updateWanted(); dirty = true; } diff --git a/Apps/Maps/main/Source/app/MapPlaces.cpp b/Apps/Maps/main/Source/app/MapPlaces.cpp index 9c38a9f..6b9c0fb 100644 --- a/Apps/Maps/main/Source/app/MapPlaces.cpp +++ b/Apps/Maps/main/Source/app/MapPlaces.cpp @@ -685,13 +685,15 @@ void MapView::drawRecording() { } Font& font = overlay.font(); const int textWidth = font.textWidth(text); - const int boxWidth = textWidth + 24; + // Room for the dot left of the text, which scales with the screen + const int textInset = metrics::px(18); + const int boxWidth = textWidth + textInset + metrics::px(6); const int boxHeight = font.lineHeight() + 6; 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 + 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); + font.drawText(canvas, x + textInset, y + 3, text, theme.text); } void MapView::openTrackMenu() { diff --git a/Apps/Maps/main/Source/app/MapScreens.cpp b/Apps/Maps/main/Source/app/MapScreens.cpp index 13ac697..33ef18e 100644 --- a/Apps/Maps/main/Source/app/MapScreens.cpp +++ b/Apps/Maps/main/Source/app/MapScreens.cpp @@ -174,18 +174,21 @@ void MapView::layoutPopup() { lvglDirty = true; } -void MapView::showLvglPage(ListView& list) { +bool MapView::showLvglPage(ListView& list, bool newView) { // 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]; + static const char* descriptions[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); + descriptions[i] = list.description(i); } - lvglMenu->showList(list.titleText(), labels, details, count, list.selected()); + return lvglMenu->showList(list.titleText(), labels, details, descriptions, count, list.selected(), newView); } -void MapView::showLvglAbout() { + +bool MapView::showLvglAbout(bool newView) { 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"); @@ -198,7 +201,7 @@ void MapView::showLvglAbout() { } paragraphs[count++] = paragraph; } - lvglMenu->showText("About and licences", paragraphs, count); + return lvglMenu->showText("About and licences", paragraphs, count, newView); } MapView::LvglView MapView::wantedLvglView() { @@ -251,22 +254,29 @@ void MapView::syncLvgl() { if (wanted == lvglView && !lvglDirty && signature == lvglSignature) { return; } + // Another view, or another page in the same view: events queued for the one that goes are dropped + const bool newView = wanted != lvglView || signature != lvglSignature; + bool shownNow = true; switch (wanted) { case LvglView::MainMenu: showLvglMainMenu(); break; case LvglView::Popup: - showLvglPage(menu); + shownNow = showLvglPage(menu, newView || lvglDirty); break; case LvglView::Page: - showLvglPage(*activeList()); + shownNow = showLvglPage(*activeList(), newView); break; case LvglView::About: - showLvglAbout(); + shownNow = showLvglAbout(newView); break; default: break; } + if (!shownNow) { + // What was shown stays, and so does its state: input still goes to what is on screen. Tried again next pass. + return; + } lvglView = wanted; lvglSignature = signature; lvglDirty = false; @@ -275,7 +285,15 @@ void MapView::syncLvgl() { void MapView::pollLvglMenu() { LvglMenuEvent event; while (lvglView != LvglView::None && lvglMenu->takeEvent(event)) { + dispatchLvglEvent(event); + } +} + +void MapView::dispatchLvglEvent(const LvglMenuEvent& event) { + { dirty = true; + // The user did something: an idle region update waits, as for keys and touch on the map + markInput(nowMs()); const LvglView view = lvglView; if (view == LvglView::MainMenu) { if (event.kind == LvglMenuEvent::Kind::Chosen) { @@ -310,14 +328,9 @@ void MapView::pollLvglMenu() { } } } + // A view that replaces this one drops the events queued for it (LvglMenu does, under the same lock that + // builds the new widgets): what is left in the queue is for what is shown now syncLvgl(); - if (lvglView != view || lvglDirty) { - // The rest was meant for the view that went - LvglMenuEvent stale; - while (lvglMenu->takeEvent(stale)) { - } - break; - } } } @@ -1142,7 +1155,8 @@ void MapView::showRegion(const RegionMeta& meta) { while (fitZoom > 0) { const double regionWidth = lonToWorldX(meta.box.east, fitZoom) - lonToWorldX(meta.box.west, fitZoom); const double regionHeight = latToWorldY(meta.box.south, fitZoom) - latToWorldY(meta.box.north, fitZoom); - if (regionWidth <= width && regionHeight <= height) { + // World pixels are magnify screen pixels wide + if (regionWidth <= width / magnify && regionHeight <= height / magnify) { break; } fitZoom--; @@ -1366,7 +1380,7 @@ void MapView::drawAbout() { // Download area BoundingBox MapView::frameBox() const { - return screenBounds(downloadView.frame, centerX, centerY, zoom, width, height); + return screenBounds(downloadView.frame, centerX, centerY, zoom, width, height, magnify); } void MapView::drawDownloadFrame() { diff --git a/Apps/Maps/main/Source/app/MapView.h b/Apps/Maps/main/Source/app/MapView.h index a05c49e..77b851e 100644 --- a/Apps/Maps/main/Source/app/MapView.h +++ b/Apps/Maps/main/Source/app/MapView.h @@ -60,6 +60,7 @@ namespace maps { class LvglMenu; +struct LvglMenuEvent; struct AffineScratch; @@ -403,8 +404,11 @@ class MapView { */ void syncLvgl(); LvglView wantedLvglView(); - void showLvglPage(ListView& list); - void showLvglAbout(); + /** newView: it replaces another view, not the same one filled again. Returns false when it couldn't be shown. */ + bool showLvglPage(ListView& list, bool newView); + bool showLvglAbout(bool newView); + /** Acts on what the user did in the LVGL view that is shown; debug scripts use it too ("menu"). */ + void dispatchLvglEvent(const LvglMenuEvent& event); /** Back one level from a list, the popup or About: Swipe right, < or Esc. */ void goBack(); void openRegions(); diff --git a/Apps/Maps/main/Source/app/TileWorker.cpp b/Apps/Maps/main/Source/app/TileWorker.cpp index 88b159e..9061945 100644 --- a/Apps/Maps/main/Source/app/TileWorker.cpp +++ b/Apps/Maps/main/Source/app/TileWorker.cpp @@ -30,12 +30,17 @@ void deleteLaneTask(TaskHandle_t task) { if (task == nullptr) { return; } + // Deleted only once it is suspended: before that it may still run on the other core, on the stack this frees. + // It gave the stopped signal and has only its suspend left, so this is short; a lane that takes long is logged. TaskStatus_t status {}; - for (int i = 0; i < 100; i++) { + for (int i = 0;; i++) { vTaskGetInfo(task, &status, pdFALSE, eInvalid); if (status.eCurrentState == eSuspended) { break; } + if (i == 100) { + logError("Tile worker: a stopped lane hasn't suspended after 500 ms, waiting on"); + } vTaskDelay(pdMS_TO_TICKS(5)); } vTaskDeleteWithCaps(task); @@ -1481,6 +1486,11 @@ bool TileWorker::convertOne(Lane& lane) { changed = true; unlock(); } + // A large tile may have been drawn from a copy (or the original, by an older version) that lost roads or + // water to full pools: what the SD cache has of it goes. Small tiles never did, and keep theirs. + if (writeGeometry != nullptr && read.size >= PREPARED_POOL_RISK_SIZE) { + dropRendered(job.tile); + } } } // A read or write that gave way to tiles on screen is tried again later @@ -1615,6 +1625,60 @@ void TileWorker::saveCacheIndex() { indexSaving = false; } +void TileWorker::dropRendered(const TileKey& source) { + if (!sdCache) { + return; + } + const auto within = [&source](const TileKey& tile) { + const int shift = tile.z - source.z; + return shift >= 0 && (tile.x >> shift) == source.x && (tile.y >> shift) == source.y; + }; + lock(); + // Waiting writes of it would put the old drawings back + int kept = 0; + for (int i = 0; i < pendingWriteCount; i++) { + if (!within(pendingWrites[i])) { + pendingSourceZoom[kept] = pendingSourceZoom[i]; + pendingWrites[kept++] = pendingWrites[i]; + } + } + pendingWriteCount = kept; + const bool complete = cacheIndex.isComplete(); + unlock(); + static constexpr int BATCH = 16; + TileKey tiles[BATCH]; + int dropped = 0; + while (true) { + lock(); + const int count = cacheIndex.takeWithin(source, tiles, BATCH); + unlock(); + for (int i = 0; i < count; i++) { + EvictJob job { root, styleId, tiles[i] }; + io->run(IoPriority::Background, evictJob, &job); + } + dropped += count; + if (count < BATCH) { + break; + } + } + if (!complete) { + // The index doesn't know every file yet, and a load reads files it doesn't know: the tile and the two levels + // under it go by name (deeper ones are seldom drawn before the index is complete) + for (int dz = 0; dz <= 2; dz++) { + const int side = 1 << dz; + for (int dy = 0; dy < side; dy++) { + for (int dx = 0; dx < side; dx++) { + EvictJob job { root, styleId, { source.z + dz, (source.x << dz) + dx, (source.y << dz) + dy } }; + io->run(IoPriority::Background, evictJob, &job); + } + } + } + } + if (dropped > 0) { + logInfo("Tile %d/%d/%d made again: %d drawings of it dropped from the SD cache", source.z, source.x, source.y, dropped); + } +} + bool TileWorker::tidyCache() { lock(); TileKey tile {}; @@ -1840,6 +1904,7 @@ bool TileWorker::loadJob(IoTask& io, void* context) { (held == Found::Original && lane.heldGeneration == worker->preparedGeneration.load()))) { job->found = held; job->olderPrepared = lane.heldOlder; + job->staleGeometry = lane.heldStale; job->splitPrepared = lane.heldSplit; return true; } @@ -1852,10 +1917,13 @@ bool TileWorker::loadJob(IoTask& io, void* context) { io.readFile(path, buffer) && readPreparedHeader(buffer.bytes(), buffer.size(), header) && isPreparedReadable(header, job->source.tile, job->source.size)) { job->found = Found::Prepared; - job->olderPrepared = preparedPartsNeeded(&header, job->source.tile, job->source.size) != 0; + const uint8_t parts = preparedPartsNeeded(&header, job->source.tile, job->source.size); + job->olderPrepared = parts != 0; + job->staleGeometry = (parts & PART_GEOMETRY) != 0; job->splitPrepared = header.version >= PREPARED_SPLIT_VERSION; lane.heldKind = static_cast(Found::Prepared); lane.heldOlder = job->olderPrepared; + lane.heldStale = job->staleGeometry; lane.heldSplit = job->splitPrepared; return true; } @@ -1863,6 +1931,7 @@ bool TileWorker::loadJob(IoTask& io, void* context) { job->found = Found::Original; lane.heldKind = static_cast(Found::Original); lane.heldOlder = false; + lane.heldStale = false; return true; } job->yielded = io.yielded(); @@ -2092,7 +2161,8 @@ bool TileWorker::produce(Lane& lane, const TileKey& tile, uint16_t* pixels, bool unlock(); } lane.fileBuffer.trim(KEEP_FILE_BUFFER); - if (rendered) { + // A drawing from geometry that is made again is not kept on the card: it is drawn again once that is done + if (rendered && !(job.found == Found::Prepared && job.staleGeometry)) { lock(); if (pendingWriteCount < MAX_PENDING_WRITES) { pendingSourceZoom[pendingWriteCount] = job.source.tile.z; diff --git a/Apps/Maps/main/Source/app/TileWorker.h b/Apps/Maps/main/Source/app/TileWorker.h index 219d4f2..36e8de6 100644 --- a/Apps/Maps/main/Source/app/TileWorker.h +++ b/Apps/Maps/main/Source/app/TileWorker.h @@ -201,6 +201,7 @@ class TileWorker { TileKey heldTile; int heldRegion; bool heldOlder; + bool heldStale; bool heldSplit; uint32_t heldGeneration; TaskHandle_t task; @@ -288,6 +289,8 @@ class TileWorker { bool skipPrepared; /** The prepared copy is of an older format: drawn as it is, made again soon. */ bool olderPrepared; + /** Its geometry is made again: a drawing of it is not written to the SD cache, it may miss roads or water. */ + bool staleGeometry; /** The prepared copy has no labels inside (version 5 on): they are read from its .prl file. */ bool splitPrepared; Found found; @@ -359,6 +362,11 @@ class TileWorker { int failedRetries = 0; int wantedZoom = -1; static constexpr uint32_t MEMORY_RETRY_MS = 5000; + /** + * The tile's geometry was made again: its drawings on the SD card, also those magnified from it, and the ones + * waiting to be written are dropped. They may be from a copy that lost roads or water. + */ + void dropRendered(const TileKey& source); static constexpr int MAX_PENDING_WRITES = 32; TileKey pendingWrites[MAX_PENDING_WRITES] {}; int pendingSourceZoom[MAX_PENDING_WRITES] {}; diff --git a/Apps/Maps/main/Source/render/CacheIndex.cpp b/Apps/Maps/main/Source/render/CacheIndex.cpp index 6b4dc05..181634d 100644 --- a/Apps/Maps/main/Source/render/CacheIndex.cpp +++ b/Apps/Maps/main/Source/render/CacheIndex.cpp @@ -90,6 +90,24 @@ void CacheIndex::erase(const TileKey& tile) { dirty = true; } +int CacheIndex::takeWithin(const TileKey& tile, TileKey* out, int max) { + int taken = 0; + for (int i = 0; i < count && taken < max;) { + const TileKey& entry = entries[i].tile; + const int shift = entry.z - tile.z; + if (shift >= 0 && (entry.x >> shift) == tile.x && (entry.y >> shift) == tile.y) { + out[taken++] = entry; + total -= entries[i].size; + // The last entry moves here and is looked at next + entries[i] = entries[--count]; + dirty = true; + } else { + i++; + } + } + return taken; +} + bool CacheIndex::nextEviction(TileKey& tile) { const uint64_t lowWater = cap * LOW_WATER_PERCENT / 100; const int lowEntries = capacity * LOW_WATER_PERCENT / 100; diff --git a/Apps/Maps/main/Source/render/CacheIndex.h b/Apps/Maps/main/Source/render/CacheIndex.h index 8ac4758..3b9f87a 100644 --- a/Apps/Maps/main/Source/render/CacheIndex.h +++ b/Apps/Maps/main/Source/render/CacheIndex.h @@ -32,6 +32,11 @@ class CacheIndex { void put(const TileKey& tile, uint32_t size); void touch(const TileKey& tile); void erase(const TileKey& tile); + /** + * Removes up to max tiles that are the tile itself or under it (higher zoom levels inside its area) and puts them + * in out. Returns how many: call again while it returns max. + */ + int takeWithin(const TileKey& tile, TileKey* out, int max); bool contains(const TileKey& tile) const; uint64_t totalBytes() const { return total; } diff --git a/Apps/Maps/main/Source/render/LabelLayout.cpp b/Apps/Maps/main/Source/render/LabelLayout.cpp index 83c4794..c635ebf 100644 --- a/Apps/Maps/main/Source/render/LabelLayout.cpp +++ b/Apps/Maps/main/Source/render/LabelLayout.cpp @@ -953,17 +953,17 @@ int LabelLayout::placeLine(const Candidate& candidate) { // A name that was on screen keeps its stretch while that is still good: otherwise it slid along its street with // every pan, to the first stretch on screen, and pushed other labels away if (candidate.sticky) { - const double scale = std::ldexp(1.0, zoom - WORLD_ZOOM); + const double worldToZoom = std::ldexp(1.0, zoom - WORLD_ZOOM); for (int k = 0; k < keptCount && placedCount < MAX_LABELS; k++) { if (kept[k].id != candidate.order) { continue; } double screenX; double screenY; - mapToScreen(kept[k].worldX * scale, kept[k].worldY * scale, screenX, screenY); + mapToScreen(kept[k].worldX * worldToZoom, kept[k].worldY * worldToZoom, 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 * scale) { + for (float start = tryFrom; start + needed <= tryTo + needed && start + needed <= total; start += 16.0f * this->scale) { if (tryAt(start, &nearX, &nearY)) { placedHere++; break; diff --git a/Apps/Maps/main/Source/ui/DownloadFrame.cpp b/Apps/Maps/main/Source/ui/DownloadFrame.cpp index 8c6135b..72b0e10 100644 --- a/Apps/Maps/main/Source/ui/DownloadFrame.cpp +++ b/Apps/Maps/main/Source/ui/DownloadFrame.cpp @@ -29,11 +29,12 @@ DownloadLayout downloadLayout(int width, int height, int lineHeight) { return layout; } -BoundingBox screenBounds(const Rect& rect, double centerX, double centerY, int zoom, int width, int height) { - const double left = centerX + (rect.x - width / 2.0); - const double right = left + rect.width; - const double top = centerY + (rect.y - height / 2.0); - const double bottom = top + rect.height; +BoundingBox screenBounds(const Rect& rect, double centerX, double centerY, int zoom, int width, int height, double magnify) { + // Screen pixels to world pixels, which are magnify screen pixels wide + const double left = centerX + (rect.x - width / 2.0) / magnify; + const double right = left + rect.width / magnify; + const double top = centerY + (rect.y - height / 2.0) / magnify; + const double bottom = top + rect.height / magnify; return { worldXToLon(left, zoom), worldYToLat(bottom, zoom), worldXToLon(right, zoom), worldYToLat(top, zoom) }; } diff --git a/Apps/Maps/main/Source/ui/DownloadFrame.h b/Apps/Maps/main/Source/ui/DownloadFrame.h index b475af0..6cfca64 100644 --- a/Apps/Maps/main/Source/ui/DownloadFrame.h +++ b/Apps/Maps/main/Source/ui/DownloadFrame.h @@ -28,7 +28,7 @@ struct DownloadLayout { DownloadLayout downloadLayout(int width, int height, int lineHeight); /** The ground under a screen rectangle, for a view centred on centerX, centerY (world pixels at zoom). */ -BoundingBox screenBounds(const Rect& rect, double centerX, double centerY, int zoom, int width, int height); +BoundingBox screenBounds(const Rect& rect, double centerX, double centerY, int zoom, int width, int height, double magnify = 1.0); /** The two lines of the info bar for a plan. */ /** diff --git a/Apps/Maps/main/Source/ui/Widgets.h b/Apps/Maps/main/Source/ui/Widgets.h index 296ec61..3cc7936 100644 --- a/Apps/Maps/main/Source/ui/Widgets.h +++ b/Apps/Maps/main/Source/ui/Widgets.h @@ -88,6 +88,10 @@ class ListView { /** A row's texts (for tests). */ const char* label(int index) const { return items[index].label; } const char* detail(int index) const { return items[index].detail; } + /** A row's description (setDescriptions), null when it has none. */ + const char* description(int index) const { + return descriptions != nullptr && index < descriptionCount ? descriptions[index] : nullptr; + } int selected() const { return selection; } const char* titleText() const { return title; } /** Moves the selection without showing the highlight. */ diff --git a/Apps/Maps/manifest.properties b/Apps/Maps/manifest.properties index 037b912..63129bc 100644 --- a/Apps/Maps/manifest.properties +++ b/Apps/Maps/manifest.properties @@ -2,13 +2,13 @@ manifest.version=0.3 target.sdk=0.8.0-dev target.platforms=esp32s3,esp32p4,esp32s31 id=tactility.maps -version.name=0.11.0 -version.code=15 +version.name=0.11.1 +version.code=16 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. +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, ESP32-P4 or ESP32-S31 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. requires.ram=8M