From 73858928431d14f617043062d264af53facaf0e3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 16:31:20 +0000 Subject: [PATCH 1/2] Draw the starter UI's map page as the app's own map A script's mapper shown much larger than its window, as the starter UI's Map page is on a phone, was laid out in the window's own pixels and magnified: Mudlet's outlines, line weights and the room size below which a room's border fades and then goes are in pixels, so its rooms lost their borders, the levels above and below became filled dots and the exits grew thin, unlike the map button's map of the same area. setMapScale takes the screen's density as an optional density, and the engine lays such a mapper out in the app's dp and draws it scaled down to the window (renderMap()'s layoutScale, Mudlet patch 0045), so its rooms are drawn as on the app's own map. The window's size, the zoom, the view and the points stay what the script set and sees. An engine without it ignores the field and a UI without it sends none, so the protocol keeps its version. Part of Mudlet/Mudlet#9011 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016ujaeFyaqXXDx8xjoThE6J --- .../org/mudlet/android/ui/ScriptMapTest.kt | 10 +- .../mudlet/android/ui/ScriptWindowsClient.kt | 27 +- .../org/mudlet/android/ui/game/ScriptMap.kt | 7 +- docs/architecture.md | 7 + docs/divergences.md | 3 + docs/phase-f.md | 3 +- docs/protocol.md | 12 +- native/api/IEngine.h | 6 +- native/enginehost/MudletEngine.h | 1 + native/enginehost/MudletProfile.cpp | 13 +- native/enginehost/MudletProfile.h | 5 +- native/enginehost/SocketBridge.cpp | 22 +- native/enginehost/SocketBridge.h | 1 + native/tests/test_mudlet_engine.py | 129 ++++++++- .../org/mudlet/android/protocol/Protocol.kt | 5 +- .../mudlet/android/protocol/ProtocolTest.kt | 2 +- .../0045-headless-map-layout-scale.patch | 244 ++++++++++++++++++ 17 files changed, 458 insertions(+), 39 deletions(-) create mode 100644 scripts/mudlet-patches/0045-headless-map-layout-scale.patch diff --git a/app/src/androidTest/kotlin/org/mudlet/android/ui/ScriptMapTest.kt b/app/src/androidTest/kotlin/org/mudlet/android/ui/ScriptMapTest.kt index 18960710..49424b0b 100644 --- a/app/src/androidTest/kotlin/org/mudlet/android/ui/ScriptMapTest.kt +++ b/app/src/androidTest/kotlin/org/mudlet/android/ui/ScriptMapTest.kt @@ -987,13 +987,19 @@ class ScriptMapTest { return Offset(left + (x * scale).toFloat(), top + (y * scale).toFloat()) } - /** The engine was last asked to draw the map at the scale a [w] by [h] frame is shown at in [bounds], at most the engine's 8. */ + /** + * The engine was last asked to draw the map at the scale a [w] by [h] frame is shown at in [bounds], at most the + * engine's 8, laid out at the screen's density, as the app's own map is. + */ private fun assertScaleAsked(bounds: Rect, w: Int, h: Int) { val shown = min(bounds.width / w, bounds.height / h).toDouble() assertTrue("the map is shown at $shown, not larger than Mudlet's pixels", shown > 1.1) - val asked = session.receiveLast("setMapScale", readPast = true).getDouble("scale") + val request = session.receiveLast("setMapScale", readPast = true) + val asked = request.getDouble("scale") // Hundredths, down, of a box that rounds to the screen's pixels assertEquals("the map shown at $shown is asked for at $asked", shown.coerceAtMost(8.0), asked, 0.02) + val density = compose.activity.resources.displayMetrics.density.toDouble().coerceIn(1.0, 4.0) + assertEquals("the map is laid out at the screen's density: $request", density, request.optDouble("density"), 0.001) } private fun assertPoint(x: Double, y: Double, event: JSONObject, within: Double = POINTS) { diff --git a/app/src/main/kotlin/org/mudlet/android/ui/ScriptWindowsClient.kt b/app/src/main/kotlin/org/mudlet/android/ui/ScriptWindowsClient.kt index 19c59602..90f2671b 100644 --- a/app/src/main/kotlin/org/mudlet/android/ui/ScriptWindowsClient.kt +++ b/app/src/main/kotlin/org/mudlet/android/ui/ScriptWindowsClient.kt @@ -90,10 +90,10 @@ class ScriptWindowsClient internal constructor(private val session: ProfileSessi private var wantedSize: MudletSize? = null private var sentSize: MudletSize? = null - // The scale the mapper window's map is shown at, and the one the engine draws it at since the UI attached: 1 until - // asked, as the engine goes back to 1 when a UI goes; null when it could not be sent - private var wantedMapScale = 1.0 - private var sentMapScale: Double? = 1.0 + // The scale and density the mapper window's map is shown at, and those the engine draws it at since the UI attached: + // 1 until asked, as the engine goes back to 1 when a UI goes; null when they could not be sent + private var wantedMapScale = MapScale(1.0, 1.0) + private var sentMapScale: MapScale? = MapScale(1.0, 1.0) // Where this engine instance was last told each user window is private val sentPlacements = HashMap() @@ -287,7 +287,7 @@ class ScriptWindowsClient internal constructor(private val session: ProfileSessi // Also a size that could not be sent while the link was down wantedSize?.let(::setMainWindowSize) mapRooms.onAttached(sameInstance) - sentMapScale = 1.0 + sentMapScale = MapScale(1.0, 1.0) setMapScale(wantedMapScale) session.appMap.onAttached(sameInstance) } @@ -299,13 +299,20 @@ class ScriptWindowsClient internal constructor(private val session: ProfileSessi sentSize = if (session.send(Requests.setMainWindowSize(size.w, size.h))) size else null } - /** Has the engine draw [map] at [scale] device pixels to each of the mapper window's, unless it does already. */ - fun setMapScale(scale: Double) { - wantedMapScale = scale - if (scale == sentMapScale) return - sentMapScale = if (session.send(Requests.setMapScale(scale))) scale else null + /** + * Has the engine draw [map] at [scale] device pixels to each of the mapper window's, laid out as the app's own map + * is at [density] device pixels to the dp, unless it does already. + */ + fun setMapScale(scale: Double, density: Float) = setMapScale(MapScale(scale, density.toDouble().coerceIn(1.0, AppMapClient.MAX_SCALE))) + + private fun setMapScale(wanted: MapScale) { + wantedMapScale = wanted + if (wanted == sentMapScale) return + sentMapScale = if (session.send(Requests.setMapScale(wanted.scale, wanted.density))) wanted else null } + private data class MapScale(val scale: Double, val density: Double) + /** Tells the engine where the user window [name] is, unless it was told already. */ fun placeUserWindow(name: String, placement: Placement) { if (sentPlacements[name] == placement) return diff --git a/app/src/main/kotlin/org/mudlet/android/ui/game/ScriptMap.kt b/app/src/main/kotlin/org/mudlet/android/ui/game/ScriptMap.kt index 656edf45..2175cfbc 100644 --- a/app/src/main/kotlin/org/mudlet/android/ui/game/ScriptMap.kt +++ b/app/src/main/kotlin/org/mudlet/android/ui/game/ScriptMap.kt @@ -240,8 +240,9 @@ internal fun ScriptMap(placed: PlacedWindow, corner: MapCorner?, density: Densit if (corner != null) { val mapRect = corner.map.from(corner.bounds) val fit = remember(window.w, window.h, placed, mapRect) { MapFit(window.w, window.h, placed.wholeIn(PxRect(0f, 0f, mapRect.w, mapRect.h))) } - // Drawn at the window's pixels and scaled up to the screen's, the map would be blurred - LaunchedEffect(fit.renderScale) { EngineClient.front.windows.setMapScale(fit.renderScale) } + // Drawn at the window's pixels and scaled up to the screen's, the map would be blurred, and laid out in them its + // rooms would be tiny ones magnified, not drawn as the app's own map draws them + LaunchedEffect(fit.renderScale, density.density) { EngineClient.front.windows.setMapScale(fit.renderScale, density.density) } val infoHeight = with(density) { (corner.map.h * INFO_FRACTION).toDp() } CornerMap( corner, @@ -260,7 +261,7 @@ internal fun ScriptMap(placed: PlacedWindow, corner: MapCorner?, density: Densit BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) { val box = PxRect(0f, 0f, constraints.maxWidth.toFloat(), constraints.maxHeight.toFloat()) val fit = remember(window.w, window.h, placed, box) { MapFit(window.w, window.h, placed.wholeIn(box)) } - LaunchedEffect(fit.renderScale) { EngineClient.front.windows.setMapScale(fit.renderScale) } + LaunchedEffect(fit.renderScale, density.density) { EngineClient.front.windows.setMapScale(fit.renderScale, density.density) } MapView(MapperWindow, frame, fit, viewOnly, drawn, Modifier.fillMaxSize().background(CONSOLE_BACKGROUND).readAsOne(0f), panel = true) } } diff --git a/docs/architecture.md b/docs/architecture.md index 2386bbd7..18d295ff 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -717,6 +717,10 @@ The game screen draws `map` in the mapper window (`ui/game/ScriptMap.kt`, fitted - The engine is asked (`setMapScale`) to draw it at the scale it is shown at, `MapFit.renderScale`, as Mudlet's pixels are scaled to the screen's, several times over for a small mapper that fills a page's pane: its PNG has that many more pixels, so the map is as sharp as the screen, and its `w`, `h` and points stay the window's. +- It is asked with the screen's density too, `setMapScale`'s `density`, so a mapper shown larger than the app's own + map's dp is laid out in dp and drawn scaled down to the window (libmudlet's `layoutScale` of `renderMap()`): its rooms + get the outlines, line weights and borders the app's own map gives a room as large on the screen, where laid out in + the window's pixels they would be tiny ones magnified, with filled dots for the levels above and below and no borders. - A tap sends a `mapPointer` press with the left button on the finger's lift, so a pinch selects nothing, at the middle of the room nearest it within 24 dp or its own cell (from the frame's `view.rooms`), so a room smaller than a finger at a low zoom is still hit, or else at the point itself; a second tap near it within the double-tap timeout @@ -1385,6 +1389,9 @@ Android options (`scripts/build-libmudlet-desktop.sh`) to run it. It checks: `sysMapWindowMousePressEvent`, a double-click walking to a room through `doSpeedWalk()`, a wheel turn zooming and less than half a notch refused; `setMapViewOnly` raising `mapModeChangeEvent`; `pointer` on the window `mapper`; the map to a UI that attaches, and none while the mapper hides; +- the map laid out as the app's: a 100 by 100 mapper at `setMapScale` 4 and `density` 1 drawing a room, its outline and + its exit as the app's 400 by 400 map at a scale of 1 does, its view and a press still in the window's pixels, and + laid out in its own pixels with no `density`; - the app's map, with no script mapper: `setAppMapSize` drawing it as `appMap` at the size and scale asked, an empty one with no profile or no rooms, and one larger than a PNG may be refused; `appMapPointer` walking with a double-click and raising no `sysMapWindowMousePressEvent`; `findRooms` by name, ignoring case, and by number; `showRoom` centring diff --git a/docs/divergences.md b/docs/divergences.md index fdf12df8..d42e2949 100644 --- a/docs/divergences.md +++ b/docs/divergences.md @@ -33,6 +33,9 @@ panel beside it rather than over it (`docs/architecture.md`, "The map"). The win the engine draws the map at, stay what the script set. A desktop's mapper is laid out for a screen many times a phone's: scaled to fit, a 200 pixel mapper is a few dp across, too small to read a room or touch one, and controls drawn over it hide most of it. +Its map is laid out in the dp it is shown at, as the app's own map is, and drawn scaled down to the window's pixels +(`setMapScale`'s `density`): laid out in those and magnified, its rooms would get the outlines, exits and levels above +and below desktop draws for a room a few pixels across, not those of a room the size the player sees. The panel shows only once a small button over the map's top corner is pressed, and Back or a touch elsewhere hides it again. Desktop's mapper shows its panel until the player hides it with the thin button between the two; beside a map that small on a phone, a panel left showing covers the game's text, so it shows only while the player wants it. diff --git a/docs/phase-f.md b/docs/phase-f.md index 01256882..928a71ae 100644 --- a/docs/phase-f.md +++ b/docs/phase-f.md @@ -465,7 +465,8 @@ rules and bare declarations apply, are read as a label's ("Labels"). What else i `map` is an `Image` at the `mapper` window's place. Taps go back as `mapPointer` presses, a double tap speedwalks, and pinch and zoom buttons send wheel turns. The image is laid out at the window's size in Mudlet's pixels, so the pointer lands where `renderMap()` drew, and drawn at the scale the app shows it at (`setMapScale`), so it is as sharp -as the screen. +as the screen. Shown larger than the app's own map's dp, it is laid out in those and scaled down to the window, so its +rooms look as on that map. ## Touch and TalkBack diff --git a/docs/protocol.md b/docs/protocol.md index 7bbc6c93..c9ead0d2 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -89,7 +89,7 @@ message, in backquotes, with `?` after an optional one, and the fields of the ob | `activateCommand` | `command` | A click on the command of `commands` whose `id` is `command`, a whole number (`THeadlessSession::activateAddonCommand()`): a checkable command is ticked or unticked, then the event `sysCommandClicked` is raised with its id. Refused for a disabled command. | | `mapPointer` | `type`, `x`, `y`, `button`?, `modifiers`?, `wheelY`? | What the UI's pointer did on the map at `x`, `y`, in the pixels of the last `map` from its top left (`THeadlessSession::mapPointer()`, "The map" below). `type` is `press`, `doubleClick` or `wheel`; `button`, `modifiers` and `wheelY` are as for `pointer`, and 0 when absent. | | `setMapViewOnly` | `viewOnly` | `true` to only view the map, `false` to edit it, as the GUI's mapper menu does (`THeadlessSession::setMapViewOnly()`): the event `mapModeChangeEvent` is raised with `viewing` or `editing`. | -| `setMapScale` | `scale` | Draws `map` from now on with `scale` device pixels to each of the mapper window's, a number from 1 to 8, so that it is as sharp as the UI shows it ("The map" below). libmudlet keeps it until the UI that asked goes, and draws at most 4096 pixels a side, at a smaller scale where that one would be larger. | +| `setMapScale` | `scale`, `density`? | Draws `map` from now on with `scale` device pixels to each of the mapper window's, a number from 1 to 8, so that it is as sharp as the UI shows it ("The map" below). `density` is the device pixels to each of the units the UI lays its own map out in, as `setAppMapSize`'s `scale`, a number from 1 to 4: a `scale` above it lays the map out in those units, so its rooms are drawn as on that map; absent, the map is laid out in the window's pixels, as an engine without it does, so it needs no new version. libmudlet keeps both until the UI that asked goes, and draws at most 4096 pixels a side, at a smaller scale where that one would be larger. | | `setAppMapSize` | `w`, `h`, `scale` | Asks for the app's own map, drawn at `w` by `h` of the map's pixels with `scale` device pixels to each, and sent as `appMap` whenever it changes ("The app's map" below); `w` and `h` 0 stop it. `w` and `h` are whole numbers, both above 0 or both 0; `scale` a number from 1 to 4. libmudlet keeps it for each profile that loads later, until the UI that asked goes, and refuses a map of more than 4096 device pixels a side. | | `appMapPointer` | `type`, `x`, `y`, `button`?, `modifiers`?, `wheelY`? | As `mapPointer`, at `x`, `y` in the map's pixels of the last `appMap` (`THeadlessSession::appMapPointer()`). | | `findRooms` | `text`, `id`? | Looks for the rooms of the map whose name holds `text`, ignoring case, as `searchRoom()` matches, and the room whose id `text` is (`THeadlessSession::findRooms()`), answered by `rooms`, best first. `text` must not be blank. | @@ -179,7 +179,8 @@ and the app's map is not open (no `setAppMapSize` above 0 by 0 since the profile gone since), and `mapPointer` as `THeadlessSession::mapPointer()` does: before the map has been drawn, for a double-click of another button than the left, and for a wheel turn of less than half a notch or with no area to zoom. -`setMapScale` is answered only when refused, for a `scale` that is not a number from 1 to 8. +`setMapScale` is answered only when refused, for a `scale` that is not a number from 1 to 8, or a `density` that is not a +number from 1 to 4. `setAppMapSize`, `appMapPointer` and `showRoom` too are answered only when refused, and `findRooms` by `rooms` or `error`, as above. libmudlet refuses all but `setAppMapSize` while no profile is open, `appMapPointer` before the @@ -539,6 +540,13 @@ map is the same point of that window, so the UI draws the PNG over it, and sends Mudlet's main window's scaled to the screen, and a mapper that is a page fills its pane. A scale that would make the PNG larger than 4096 pixels a side is lowered to fit. A mapper smaller than 10 pixels a side or larger than 4096, or a map too large for a frame, gives none. +- Mudlet's outlines, line weights and the room size below which a room's border fades and then goes are in pixels, so + a small mapper shown enlarged, as a page of the starter UI's dock is, laid out in its own pixels has tiny rooms + magnified: filled dots for the levels above and below, rooms without borders, thinner exits. With a `density` below + the `scale`, the map is laid out instead at the window's size times `scale` over `density`, in the units the app + lays its own map out in, and drawn scaled down to the window (libmudlet's `layoutScale` of `renderMap()`, a Mudlet + patch the app carries until Mudlet has it), so a room as large on the screen as on `appMap` is drawn as there. The + zoom is still the area's, rooms across the narrow side, and `w`, `h`, `view` and the points still the window's. ### The app's map diff --git a/native/api/IEngine.h b/native/api/IEngine.h index 77953f08..6696eeb0 100644 --- a/native/api/IEngine.h +++ b/native/api/IEngine.h @@ -109,9 +109,11 @@ class IEngine virtual QString setMapViewOnly(bool viewOnly) = 0; // The mapper window's map drawn from now on at scale device pixels to each of the window's, so that it is as // sharp as the UI shows it, though never more than PngImage::maxSide a side; 1 again when the UI goes, as - // SocketBridge asks. Scale is from 1 to maxMapScale. + // SocketBridge asks. Scale is from 1 to maxMapScale. Density is the device pixels to each of the units the UI lays + // its own map out in, from 1 to maxAppMapScale: a scale above it lays the map out in those units, so its rooms + // are drawn as on that map; one at or above scale lays it out in the window's pixels. static constexpr double maxMapScale = 8.0; - virtual QString setMapScale(double scale) = 0; + virtual QString setMapScale(double scale, double density) = 0; // The app's own map, apart from the mapper window, drawn for IFrontend::appMap() at size, in the map's pixels, with // scale device pixels to each, from now on and for the next profile too; an empty size stops it, as SocketBridge // asks when the UI goes. Scale is from 1 to maxAppMapScale. diff --git a/native/enginehost/MudletEngine.h b/native/enginehost/MudletEngine.h index f6f43574..0715985a 100644 --- a/native/enginehost/MudletEngine.h +++ b/native/enginehost/MudletEngine.h @@ -52,6 +52,7 @@ class MudletEngine : public QObject, public IEngineControl QSize screen; QSize mainWindow{0, 0}; double mapScale = 1; + double mapDensity = 1; QSize appMap{0, 0}; double appMapScale = 1; }; diff --git a/native/enginehost/MudletProfile.cpp b/native/enginehost/MudletProfile.cpp index f115c20d..0fc3fd5f 100644 --- a/native/enginehost/MudletProfile.cpp +++ b/native/enginehost/MudletProfile.cpp @@ -1029,6 +1029,7 @@ void MudletProfile::start(const QString& host, quint16 port, bool connect, std:: mScreenSize = ui.screen; mMainWindowSize = ui.mainWindow; mMapScale = ui.mapScale; + mMapDensity = ui.mapDensity; mAppMapSize = ui.appMap; mAppMapScale = ui.appMapScale; // The new profile counts its links from 1 again @@ -1694,7 +1695,9 @@ std::optional MudletProfile::drawMap(const QSize& size) qWarning("MudletEngine: the mapper, %dx%d, is larger than %d pixels a side, so the map is not drawn", size.width(), size.height(), PngImage::maxSide); return std::nullopt; } - // Drawn in the window's pixels onto an image of the device's, so the lines and names are as sharp as the screen + // Drawn in the window's pixels onto an image of the device's, so the lines and names are as sharp as the screen, + // and laid out in the UI's own map's units where it shows the window larger than those, so the rooms look as there; + // by the scale the image is drawn at, so the layout, which a double-click paints, is never larger than the image const double scale = std::max(1.0, std::min({mMapScale, double(PngImage::maxSide) / size.width(), double(PngImage::maxSide) / size.height()})); QImage image(size * scale, QImage::Format_ARGB32_Premultiplied); if (image.isNull()) { @@ -1704,7 +1707,7 @@ std::optional MudletProfile::drawMap(const QSize& size) image.setDevicePixelRatio(scale); image.fill(Qt::transparent); QPainter painter(&image); - const bool drawn = mSession->renderMap(painter, size); + const bool drawn = mSession->renderMap(painter, size, std::max(1.0, scale / mMapDensity)); painter.end(); if (!drawn) { qWarning("MudletEngine: the map was not drawn: %s", qPrintable(mSession->errorString())); @@ -2026,13 +2029,15 @@ QString MudletProfile::setMapViewOnly(bool viewOnly) return mSession->setMapViewOnly(viewOnly) ? QString() : mSession->errorString(); } -QString MudletProfile::setMapScale(double scale) +QString MudletProfile::setMapScale(double scale, double density) { mEngine.mUi.mapScale = scale; - if (scale == mMapScale) { + mEngine.mUi.mapDensity = density; + if (scale == mMapScale && density == mMapDensity) { return {}; } mMapScale = scale; + mMapDensity = density; if (mMapSize && loaded()) { pushMap(mMapSize); } diff --git a/native/enginehost/MudletProfile.h b/native/enginehost/MudletProfile.h index fdaae41c..287e6297 100644 --- a/native/enginehost/MudletProfile.h +++ b/native/enginehost/MudletProfile.h @@ -75,7 +75,7 @@ class MudletProfile : public QObject, public IEngine std::variant pressKey(int key, int modifiers, const std::optional& text) override; QString mapPointer(const PointerEvent& event) override; QString setMapViewOnly(bool viewOnly) override; - QString setMapScale(double scale) override; + QString setMapScale(double scale, double density) override; QString setAppMapSize(const QSize& size, double scale) override; QString appMapPointer(const PointerEvent& event) override; std::variant findRooms(const QString& text) const override; @@ -299,8 +299,9 @@ class MudletProfile : public QObject, public IEngine QSize mMainWindowSize{0, 0}; // The size of the mapper window as pushMap() last had it: none while it did not show std::optional mMapSize; - // Device pixels to each of the mapper window's, as setMapScale() asked + // Device pixels to each of the mapper window's, and to each of the UI's own map's units, as setMapScale() asked double mMapScale = 1; + double mMapDensity = 1; // The mapper's and the app's map as last drawn MapPicture mMapPicture; MapPicture mAppMapPicture; diff --git a/native/enginehost/SocketBridge.cpp b/native/enginehost/SocketBridge.cpp index 45d86a2c..73c4d8f4 100644 --- a/native/enginehost/SocketBridge.cpp +++ b/native/enginehost/SocketBridge.cpp @@ -462,7 +462,7 @@ void SocketBridge::forgetClient() { if (mEngine && mProfileOutput) { mEngine->setAppMapSize(QSize(0, 0), 1); - mEngine->setMapScale(1); + mEngine->setMapScale(1, 1); } mAppMap = {}; } @@ -794,9 +794,7 @@ void SocketBridge::handleMessage(const QJsonObject& message) const QJsonValue viewOnly = message.value(QLatin1String("viewOnly")); refuse(type, viewOnly.isBool() ? mEngine->setMapViewOnly(viewOnly.toBool()) : QStringLiteral("viewOnly must be true or false")); } else if (type == QLatin1String("setMapScale")) { - const QJsonValue scale = message.value(QLatin1String("scale")); - const bool valid = scale.isDouble() && scale.toDouble() >= 1 && scale.toDouble() <= IEngine::maxMapScale; - refuse(type, valid ? mEngine->setMapScale(scale.toDouble()) : QStringLiteral("scale must be a number from 1 to %1").arg(IEngine::maxMapScale)); + refuse(type, setMapScale(message)); } else if (type == QLatin1String("setAppMapSize")) { refuse(type, setAppMapSize(message)); } else if (type == QLatin1String("appMapPointer")) { @@ -1146,6 +1144,22 @@ QString SocketBridge::moveMap(const QJsonObject& message) return mEngine->moveMap(*map, QPointF(numbers[0].toDouble(), numbers[1].toDouble()), numbers[2].toDouble(), QPointF(numbers[3].toDouble(), numbers[4].toDouble()), *seq); } +QString SocketBridge::setMapScale(const QJsonObject& message) +{ + const QJsonValue scale = message.value(QLatin1String("scale")); + if (!scale.isDouble() || scale.toDouble() < 1 || scale.toDouble() > IEngine::maxMapScale) { + return QStringLiteral("scale must be a number from 1 to %1").arg(IEngine::maxMapScale); + } + const QJsonValue density = message.value(QLatin1String("density")); + if (density.isUndefined()) { + return mEngine->setMapScale(scale.toDouble(), scale.toDouble()); + } + if (!density.isDouble() || density.toDouble() < 1 || density.toDouble() > IEngine::maxAppMapScale) { + return QStringLiteral("density must be a number from 1 to %1").arg(IEngine::maxAppMapScale); + } + return mEngine->setMapScale(scale.toDouble(), density.toDouble()); +} + QString SocketBridge::setAppMapSize(const QJsonObject& message) { const std::optional width = wholeNumber(message.value(QLatin1String("w"))); diff --git a/native/enginehost/SocketBridge.h b/native/enginehost/SocketBridge.h index 5a773ada..ccea5207 100644 --- a/native/enginehost/SocketBridge.h +++ b/native/enginehost/SocketBridge.h @@ -158,6 +158,7 @@ class SocketBridge : public QObject, public IFrontend QString pointer(const QJsonObject& message); void setTextBoxText(const QJsonObject& message); QString mapPointer(const QJsonObject& message); + QString setMapScale(const QJsonObject& message); QString setAppMapSize(const QJsonObject& message); QString moveMap(const QJsonObject& message); void findRooms(const QJsonObject& message); diff --git a/native/tests/test_mudlet_engine.py b/native/tests/test_mudlet_engine.py index b18ee882..b9414f93 100644 --- a/native/tests/test_mudlet_engine.py +++ b/native/tests/test_mudlet_engine.py @@ -123,7 +123,7 @@ def main(): for checks in (bridge_refusals, input_line, console, screen_and_main_window, start_sizes, starter_ui_welcome, links, app_state, script_windows, window_links, script_labels, label_links, script_text_boxes, frame_tabs, button_bars, map_view, app_map, - map_info, map_moves, map_rooms, map_edits, map_download, map_files, profile_settings, script_items, variables, sounds, + map_layout, map_info, map_moves, map_rooms, map_edits, map_download, map_files, profile_settings, script_items, variables, sounds, clipboard, file_dialog, web_pages, packages, error_console, default_packages, key_bindings, scripts_stopped, replay_recording, time_stamps, line_updates, replay_playback): checks() @@ -1231,6 +1231,9 @@ def bridge_refusals(): ({"t": "setMapScale", "scale": 0.5}, "scale must be a number from 1 to 8"), ({"t": "setMapScale", "scale": 8.5}, "scale must be a number from 1 to 8"), ({"t": "setMapScale", "scale": "2"}, "scale must be a number from 1 to 8"), + ({"t": "setMapScale", "scale": 2, "density": 0.5}, "density must be a number from 1 to 4"), + ({"t": "setMapScale", "scale": 2, "density": 4.5}, "density must be a number from 1 to 4"), + ({"t": "setMapScale", "scale": 2, "density": "2"}, "density must be a number from 1 to 4"), ({"t": "editRoom", "room": 1, "weight": "2"}, "weight must be a whole number"), ({"t": "editRoom", "room": 1, "x": 1, "y": 2}, "x, y and z go together"), ({"t": "editRoom", "room": 1, "locked": 1}, "locked must be true or false"), @@ -2952,6 +2955,14 @@ def map_writers_png(data): def png_pixel(data, x, y): """The (r, g, b, a) of a pixel of an 8-bit RGB or RGBA PNG with no interlace, as Qt saves one.""" + rows, channels = png_rows(data, y + 1) + pixel = tuple(rows[y][x * channels:(x + 1) * channels]) + return pixel if channels == 4 else pixel + (255,) + + +def png_rows(data, count=None): + """The first count rows (all by default) of an 8-bit RGB or RGBA PNG with no interlace, unfiltered, and its + channels a pixel.""" width, height = png_size(data) chunks = png_chunks(data) depth, colour, interlace = chunks[b"IHDR"][0][8], chunks[b"IHDR"][0][9], chunks[b"IHDR"][0][12] @@ -2959,10 +2970,10 @@ def png_pixel(data, x, y): raise ValueError(f"a PNG of depth {depth}, colour type {colour}, interlace {interlace}") channels = 4 if colour == 6 else 3 raw, stride = zlib.decompress(b"".join(chunks[b"IDAT"])), width * channels - previous = bytearray(stride) - for row in range(y + 1): + previous, rows = bytearray(stride), [] + for row in range(height if count is None else count): kind, line = raw[row * (stride + 1)], bytearray(raw[row * (stride + 1) + 1:(row + 1) * (stride + 1)]) - for i in range(stride): + for i in range(stride if kind else 0): left = line[i - channels] if i >= channels else 0 up, corner = previous[i], previous[i - channels] if i >= channels else 0 if kind == 1: @@ -2975,9 +2986,9 @@ def png_pixel(data, x, y): guess = left + up - corner nearest = min((abs(guess - left), 0, left), (abs(guess - up), 1, up), (abs(guess - corner), 2, corner))[2] line[i] = (line[i] + nearest) & 0xFF + rows.append(line) previous = line - pixel = tuple(previous[x * channels:(x + 1) * channels]) - return pixel if channels == 4 else pixel + (255,) + return rows, channels def map_view(): @@ -3145,6 +3156,112 @@ def attach(): check(code == 0, f"the engine exits cleanly on SIGTERM: {code}") +def map_layout(): + """A small mapper shown enlarged drawn as the app's own map is: setMapScale with a density lays the map out in the + UI's own units, so the room the app's map draws at 400 by 400 at a scale of 1 is drawn alike in a 100 by 100 mapper + at a scale of 4 and a density of 1, its view, a press, a drag and a pinch still in the window's pixels; with no + density, laid out in the window's pixels, it is not.""" + profile = "Map Layout Test" + proc, c = start_engine(profile) + seen = [] + c.wait_for(lambda m: m["t"] == "synced", collect=seen) + c.send({"t": "setMainWindowSize", "w": 1000, "h": 800}) + m = c.ask({"t": "saveProfile", "name": profile, "host": "127.0.0.1", "port": 23, "tls": False, "login": "", + "autoReconnect": False}, collect=seen) + check(m["t"] == "profiles", f"the map layout's profile is made: {m}") + c.send({"t": "openProfile", "name": profile, "connect": False}) + wait_status(c, "profile", lambda v: v == f"{profile} loaded", seen) + + # As in map_view(), rooms 1 and 2 two apart, the player in 1, at a zoom of 10: 40 of the app's pixels a room both on + # the app's map and laid out in the mapper, so room 2 is 80 to the right of the middle of each PNG, and 20 of the + # mapper's 100 pixels to the right of its middle + room2, window_room2 = (280, 200), (70, 50) + since = len(seen) + c.send({"t": "setAppMapSize", "w": 400, "h": 400, "scale": 1}) + c.send({"t": "setMapScale", "scale": 4, "density": 1}) + c.send({"t": "runLua", "code": "\n".join([ + 'local area = addAreaName("Map Layout Area")', + "setCustomEnvColor(301, 200, 30, 30, 255)", + "for id, x in pairs({[1] = 0, [2] = 2}) do", + " addRoom(id)", + " setRoomArea(id, area)", + " setRoomCoordinates(id, x, 0, 0)", + "end", + "setRoomEnv(2, 301)", + 'setExit(1, 2, "e")', + 'setExit(2, 1, "w")', + 'testMapper = Geyser.Mapper:new({name = "map", x = 0, y = 0, width = 100, height = 100})', + "setMapZoom(10, area)", + "centerview(1)", + "function selected() local rooms = getMapSelection().rooms or {} table.sort(rooms) echo(\"selected \" .. table.concat(rooms, \",\") .. \"\\n\") end", + ])}) + + def drawn(kind, w, h): + def test(m): + if m["t"] != kind or (m["w"], m["h"]) != (w, h): + return False + png = base64.b64decode(m["png"]) + return png_size(png) == (400, 400) and png_pixel(png, *room2)[:3] == (200, 30, 30) + return test + + def box(m): + """The pixels of room 2 and the box around it, outline and exit in it, of a frame's PNG.""" + rows, channels = png_rows(base64.b64decode(m["png"]), 221) + return [tuple(rows[y][x * channels:(x + 1) * channels]) for y in range(180, 221) for x in range(260, 301)] + + def differing(a, b): + return sum(1 for p, q in zip(box(a), box(b)) if max(abs(i - j) for i, j in zip(p, q)) > 8) + + def places(m): + return {r["id"]: (round(r["x"]), round(r["y"])) for r in m.get("view", {}).get("rooms", [])} + + try: + mapper = seen_or_next(c, drawn("map", 100, 100), seen, since, timeout=15) + app = seen_or_next(c, drawn("appMap", 400, 400), seen, since, timeout=15) + except TimeoutError as e: + check(False, f"the 100 by 100 mapper at a scale of 4 and the app's map at 400 by 400 draw room 2 at 280, 200: {e}") + stop_engine(proc) + return + view = mapper.get("view", {}) + check(abs(view.get("roomSize", 0) - 10) < 0.01 and places(mapper).get(2) == window_room2, + f"the mapper's view is in its window's pixels, rooms 10 of them and room 2 at 70, 50: {view}") + count = differing(mapper, app) + check(count <= 2 * 41 * 41 // 100, + f"room 2, its outline and its exit are drawn in the mapper as on the app's map: {count} of {41 * 41} pixels differ") + + since = len(seen) + c.send({"t": "mapPointer", "type": "press", "x": window_room2[0], "y": window_room2[1], "button": 1}) + c.send({"t": "runLua", "code": "selected()"}) + got = seen_or_next(c, lambda m: m["t"] in ("line", "tail") and m["text"].startswith("selected "), seen, since)["text"] + check(got == "selected 2", f"a press at room 2's point of the window selects it: {got}") + + # Without a density, as an engine before it, the map is laid out in the window's pixels: tiny rooms, magnified + since = len(seen) + c.send({"t": "setMapScale", "scale": 4}) + try: + m = seen_or_next(c, lambda m: m["t"] == "map" and m["png"] != mapper["png"] and drawn("map", 100, 100)(m), seen, since) + count = differing(m, app) + check(count > 10 * 41 * 41 // 100, + f"with no density the mapper is laid out in its own pixels, unlike the app's map: {count} of {41 * 41} pixels differ") + except TimeoutError as e: + check(False, f"setMapScale with no density draws the mapper again, laid out in its own pixels: {e}") + + # A drag and a pinch in the window's pixels: room 2 20 to the left, then twice the size about room 1 + c.send({"t": "setMapScale", "scale": 4, "density": 1}) + for seq, move, want in ((1, {"dx": -20, "dy": 0, "zoom": 1, "x": 50, "y": 50}, {1: (30, 50), 2: (50, 50)}), + (2, {"dx": 0, "dy": 0, "zoom": 2, "x": 30, "y": 50}, {1: (30, 50), 2: (70, 50)})): + since = len(seen) + c.send({"t": "moveMap", "map": "mapper", "seq": seq, **move}) + try: + m = seen_or_next(c, lambda m: m["t"] == "map" and m.get("view", {}).get("moved") == seq, seen, since) + got = places(m) + check(got == want, f"moveMap {move} moves the laid out map by the window's pixels: {got}") + except TimeoutError as e: + check(False, f"moveMap {move} draws the mapper again: {e}") + code = stop_engine(proc) + check(code == 0, f"the engine exits cleanly on SIGTERM: {code}") + + def app_map(): """The app's own map, with no script mapper: setAppMapSize drawing the profile's map as appMap frames at the size and scale asked for, with nothing to draw before a profile or rooms; appMapPointer selecting and walking without the diff --git a/protocol/src/main/kotlin/org/mudlet/android/protocol/Protocol.kt b/protocol/src/main/kotlin/org/mudlet/android/protocol/Protocol.kt index ec7a704e..0919e536 100644 --- a/protocol/src/main/kotlin/org/mudlet/android/protocol/Protocol.kt +++ b/protocol/src/main/kotlin/org/mudlet/android/protocol/Protocol.kt @@ -1253,9 +1253,10 @@ object Requests { /** * The mapper window's [EngineMessage.Map] drawn from now on at [scale] device pixels to each of the window's (1 to - * [MapFit.MAX_RENDER_SCALE]), its `w` and `h` still the window's. Answered only by an Error, when refused. + * [MapFit.MAX_RENDER_SCALE]), its `w` and `h` still the window's, and laid out in the app's own map's units at + * [density] device pixels to each (1 to 4) where [scale] is above it. Answered only by an Error, when refused. */ - fun setMapScale(scale: Double): JSONObject = JSONObject().put("t", "setMapScale").put("scale", scale) + fun setMapScale(scale: Double, density: Double): JSONObject = JSONObject().put("t", "setMapScale").put("scale", scale).put("density", density) /** * The app's own map, apart from any a script opened, drawn at [w] by [h] of its pixels with [scale] device pixels diff --git a/protocol/src/test/kotlin/org/mudlet/android/protocol/ProtocolTest.kt b/protocol/src/test/kotlin/org/mudlet/android/protocol/ProtocolTest.kt index 26739b94..1d9c575f 100644 --- a/protocol/src/test/kotlin/org/mudlet/android/protocol/ProtocolTest.kt +++ b/protocol/src/test/kotlin/org/mudlet/android/protocol/ProtocolTest.kt @@ -1105,7 +1105,7 @@ class ProtocolTest { @Test fun theMapScaleRequestCarriesWhatTheEngineReads() { - assertEquals(mapOf("t" to "setMapScale", "scale" to 2.75), Requests.setMapScale(2.75).toMap()) + assertEquals(mapOf("t" to "setMapScale", "scale" to 2.75, "density" to 2.625), Requests.setMapScale(2.75, 2.625).toMap()) } @Test diff --git a/scripts/mudlet-patches/0045-headless-map-layout-scale.patch b/scripts/mudlet-patches/0045-headless-map-layout-scale.patch new file mode 100644 index 00000000..4065a568 --- /dev/null +++ b/scripts/mudlet-patches/0045-headless-map-layout-scale.patch @@ -0,0 +1,244 @@ +Let a frontend with no window lay a small map window out at the size it shows it + +T2DMap's outlines, line weights and the room size below which a room's border fades (12 pixels) and then goes (4) +are in pixels. An app that draws a small mapper window onto a much larger part of its screen, as a page of the +starter UI's dock is on a phone, so lays its rooms out tiny and magnifies them: the levels above and below become +filled dots, the rooms lose their borders and the exits grow thin, unlike the app's own map of the same area. + +- THeadlessSession::renderMap() takes a layoutScale, from 1 to 16 and 1 by default: the map is laid out at the size + times that, its rooms as large in those units as they are shown, and drawn scaled down to the size, so it looks as + a map laid out at that larger size does. Cosmetic pens stay their width in device pixels either way. +- TNullMapView keeps the size and scale of the last render(): mapPointer(), moveMapView(), mapView() and the rooms it + lists stay in the size's pixels, and are carried to the layout's for TMapPainter. +- The zoom, the rooms across the narrow side, is the area's as before. +- docs/headless.md describes it. + +Tested by Mudlet/android's native/tests/test_mudlet_engine.py (map_layout: a 100 by 100 mapper shown four times as +large drawn as the app's 400 by 400 map of the same rooms, its view and a press on a room still in the window's +pixels, and laid out in its own pixels again without it). The desktop is unchanged. + +Carried by Mudlet/android's scripts/apply-mudlet-patches.sh until Mudlet/Mudlet has it. +Upstream: not opened yet + +diff --git a/docs/headless.md b/docs/headless.md +index 37fbfa520..18ca792e6 100644 +--- a/docs/headless.md ++++ b/docs/headless.md +@@ -1159,6 +1159,15 @@ As the GUI's does, a draw that moves to another area raises `sysMapAreaChanged`. + the profile's Lua, so the call is refused where `submit()` is, from a handler of `outputLine` and the + other signals sent in the middle of a write. + ++The map's outlines, line weights and the room size below which a room's border fades and then goes are ++in pixels, so a small window an app shows enlarged would have its rooms drawn as tiny rooms magnified: ++filled dots for the levels above and below, rooms without borders, thinner exits. Such an app passes ++`renderMap()` a `layoutScale`, how many of the units it lays its own maps out in make one of the ++window's pixels, from 1 to 16: the map is laid out at the size times that and drawn scaled down to the ++size, so its rooms look as on a map laid out at that larger size. The zoom, the rooms across the narrow ++side, is the area's as before, and `mapPointer()`, `moveMapView()` and `mapView()` keep to the size's ++pixels. ++ + `mapRepaintRequested` says when the GUI would draw the map again: a script opened the map, showed it + again or replaced it with an embedded mapper, the player moved or a script centred the map, the map + loaded or changed, or its zoom, colours, settings or info box did. It comes once a turn +diff --git a/src/TNullMapView.cpp b/src/TNullMapView.cpp +index 1052ccc5c..ef9ee2680 100644 +--- a/src/TNullMapView.cpp ++++ b/src/TNullMapView.cpp +@@ -227,10 +227,10 @@ bool TNullMapView::move(const QPointF& pan, const qreal zoom, const QPointF& abo + const qreal side = qMin(mView.mSize.width(), mView.mSize.height()); + PendingZoom pending = mPendingZoom.value_or(PendingZoom{mView.xyzoom, mView.mMapCenterX, mView.mMapCenterY}); + const qreal roomSize = side / pending.xyzoom; +- pending.centreX -= pan.x() / roomSize; +- pending.centreY -= pan.y() / roomSize; ++ pending.centreX -= laidOut(pan).x() / roomSize; ++ pending.centreY -= laidOut(pan).y() / roomSize; + const qreal newZoom = qBound(TMap::scmMinXYZoom, pending.xyzoom / zoom, maxZoom()); +- const QPointF fromMiddle = about - QPointF(mView.mSize.width() / 2.0, mView.mSize.height() / 2.0); ++ const QPointF fromMiddle = laidOut(about - QPointF(mRenderedSize.width() / 2.0, mRenderedSize.height() / 2.0)); + const bool zoomed = !qFuzzyCompare(newZoom, pending.xyzoom); + if (zoomed) { + const qreal newRoomSize = side / newZoom; +@@ -274,13 +274,13 @@ void TNullMapView::collectDrawnRooms() + } + const QPointF position(pRoom->x() * mView.mRoomWidth + fx, -pRoom->y() * mView.mRoomHeight + fy); + if (frame.contains(position)) { +- mDrawnRooms.append(DrawnRoom{.id = roomId, .position = position, .name = pRoom->name}); ++ mDrawnRooms.append(DrawnRoom{.id = roomId, .position = position / mLayoutScale, .name = pRoom->name}); + } + } + if (mDrawnRooms.size() <= maxDrawnRooms) { + return; + } +- const QPointF middle(mView.mSize.width() / 2.0, mView.mSize.height() / 2.0); ++ const QPointF middle(mRenderedSize.width() / 2.0, mRenderedSize.height() / 2.0); + const auto fromMiddle = [&middle](const DrawnRoom& room) { + const QPointF offset = room.position - middle; + return QPointF::dotProduct(offset, offset); +@@ -307,16 +307,17 @@ void TNullMapView::raiseAreaChanged(const int areaId, const int lastViewedAreaId + } + + // With the settings T2DMap::init() and dlgMapper take from the profile and the main window +-void TNullMapView::render(QPainter& painter, const QSize& size) ++void TNullMapView::render(QPainter& painter, const QSize& size, const qreal layoutScale) + { + // The repaint a player's move asks for can come before the paint() it schedules, and TMapPainter would then + // centre on the player itself, leaving paint() nothing to follow + paint(); + TMap* pMap = mpHost->mpMap.data(); ++ const qreal scale = qIsFinite(layoutScale) ? qBound(1.0, layoutScale, 16.0) : 1.0; + TMapPainter::View view = mView; + view.mpMap = pMap; + view.mpHost = mpHost; +- view.mSize = size; ++ view.mSize = (QSizeF(size) * scale).toSize(); + view.eSize = mpHost->mLineSize; + view.mBSize = mpHost->mRoomBorderSize; + view.rSize = mpHost->mRoomSize; +@@ -341,11 +342,16 @@ void TNullMapView::render(QPainter& painter, const QSize& size) + // Set again only by a frame that lays the rooms out + view.mRoomWidth = 0.0f; + TMapPainter::PaintResult result; ++ painter.save(); ++ painter.scale(1.0 / scale, 1.0 / scale); + // A map info contributor's Lua reads the area shown, as getMapZoom() does, so finds the one this frame shows + mPainter.paintView(painter, view, result, [this](const TMapPainter::View& frame) { + mView = frame; + }); ++ painter.restore(); + mView = result.view; ++ mRenderedSize = size; ++ mLayoutScale = scale; + mMapInfo = result.mapInfo; + mLaidOut = mView.mRoomWidth > 0.0f; + collectDrawnRooms(); +@@ -501,8 +507,8 @@ void TNullMapView::press(const QPoint& position, const Qt::MouseButton button, c + mView.mMultiSelectionSet.clear(); + } + bool multiSelection = false; +- TMapPainter::addRoomsToSelection( +- mpHost->mpMap.data(), mView.mMultiSelectionSet, multiSelection, mView.mMultiSelectionHighlightRoomId, TMapPainter::roomsAtPoint(mView, *pArea, position), modifiers); ++ const QList rooms = TMapPainter::roomsAtPoint(mView, *pArea, laidOut(position).toPoint()); ++ TMapPainter::addRoomsToSelection(mpHost->mpMap.data(), mView.mMultiSelectionSet, multiSelection, mView.mMultiSelectionHighlightRoomId, rooms, modifiers); + } + } + if (mRaisesEvents) { +@@ -517,7 +523,7 @@ void TNullMapView::doubleClick(const QPoint& position) + { + TMapPainter::View view = mView; + view.mIsSecondaryView = true; +- view.mPHighlight = position; ++ view.mPHighlight = laidOut(position).toPoint(); + view.mPick = true; + view.mStartSpeedWalk = true; + view.mKeepZoom = mLaidOut; +@@ -543,7 +549,7 @@ bool TNullMapView::wheel(const QPointF& position, const QPoint& angleDelta, cons + // The main window reads this once at its start; with none, it is read where it is used + const bool invertZoom = MudletApp::getQSettings()->value(qsl("invertMapZoom"), false).toBool(); + PendingZoom pending = mPendingZoom.value_or(PendingZoom{mView.xyzoom, mView.mMapCenterX, mView.mMapCenterY}); +- const std::optional zoomed = TMapPainter::zoomAtPoint(*pArea, pending.xyzoom, pending.centreX, pending.centreY, mView.mSize, position, angleDelta, modifiers, invertZoom); ++ const std::optional zoomed = TMapPainter::zoomAtPoint(*pArea, pending.xyzoom, pending.centreX, pending.centreY, mView.mSize, laidOut(position), angleDelta, modifiers, invertZoom); + if (!zoomed) { + return false; + } +@@ -551,7 +557,7 @@ bool TNullMapView::wheel(const QPointF& position, const QPoint& angleDelta, cons + if (*zoomed) { + // zoomAtPoint() keeps the point under the pointer, so a turn off the middle leaves the player, unless the + // player's move has asked for a centring the next render() does +- if (!mRecentre && position != QPointF(mView.mSize.width() / 2.0, mView.mSize.height() / 2.0)) { ++ if (!mRecentre && position != QPointF(mRenderedSize.width() / 2.0, mRenderedSize.height() / 2.0)) { + mFollowing = false; + } + mPendingZoom = pending; +diff --git a/src/TNullMapView.h b/src/TNullMapView.h +index aef0f275c..73bdfb2b9 100644 +--- a/src/TNullMapView.h ++++ b/src/TNullMapView.h +@@ -43,8 +43,11 @@ public: + explicit TNullMapView(Host* pHost, QObject* parent = nullptr, bool raisesEvents = true); + // A hidden mapper does not paint + void setShown(bool shown); +- // What T2DMap would draw at that size, whether or not the mapper is shown, raising sysMapAreaChanged as it does +- void render(QPainter&, const QSize&); ++ // What T2DMap would draw at that size, whether or not the mapper is shown, raising sysMapAreaChanged as it does. ++ // T2DMap's line weights, outlines and the room size below which it fades or leaves out borders are in pixels, so ++ // a window shown enlarged is laid out at size times layoutScale, from 1 to 16, and drawn scaled down to size; the ++ // positions given to and taken from this view stay in size's pixels ++ void render(QPainter&, const QSize&, qreal layoutScale = 1.0); + // What a mouse press, the second press of a double-click and a wheel turn at that point of the last render() do + // to T2DMap, menus and dragging aside + // Cleared for an app that shows the map info box itself: render() then leaves the box out and mapInfo() holds +@@ -53,7 +56,7 @@ public: + // The map info box the last render() left out, a contributor's part each; empty where it painted the box + const QList& mapInfo() const { return mMapInfo; } + bool rendered() const { return !mView.mSize.isEmpty(); } +- QSize renderedSize() const { return mView.mSize; } ++ QSize renderedSize() const { return mRenderedSize; } + // Whether the last render() laid out an area's rooms, which a press and a wheel turn act on + bool showsArea() const; + void press(const QPoint&, Qt::MouseButton, Qt::KeyboardModifiers); +@@ -103,7 +106,7 @@ public: + // The levels of the area the last render() laid out that have rooms, lowest first + QList drawnLevels() const; + qreal drawnZoom() const { return mView.xyzoom; } +- qreal drawnRoomSize() const { return mView.mRoomWidth; } ++ qreal drawnRoomSize() const { return mView.mRoomWidth / mLayoutScale; } + // The room the map takes as the player's: paint() and TMapPainter take the first room where the player's is gone + int playerRoomId() const; + // As T2DMap::slot_toggleMapViewOnly(), which raises mapModeChangeEvent +@@ -150,6 +153,8 @@ private: + // What paint() does once the player is in another room, or follow() asks: the next render() centres on it + void followRoom(int roomId, int areaId); + void collectDrawnRooms(); ++ // A point of the last render(), in its size's pixels, where its layout has it ++ QPointF laidOut(const QPointF& point) const { return point * mLayoutScale; } + int centredRoomId() const { return mRecentre ? mFollowedRoomId : mView.mRoomID; } + + Host* mpHost = nullptr; +@@ -159,6 +164,9 @@ private: + // What T2DMap keeps between frames: the view last drawn, as the pointer and the selection have changed it since, + // and the area last raised for + TMapPainter::View mView; ++ // What the last render() was given: mView.mSize is that size times the layout scale ++ QSize mRenderedSize; ++ qreal mLayoutScale = 1.0; + // paint() followed the player to this room and area, which the next render() centres on as T2DMap would, and + // for a small area may centre on the area + bool mRecentre = false; +diff --git a/src/headless/THeadlessSession.h b/src/headless/THeadlessSession.h +index b57db0613..44dae104e 100644 +--- a/src/headless/THeadlessSession.h ++++ b/src/headless/THeadlessSession.h +@@ -795,7 +795,10 @@ public: + // a draw that moves to another area raises sysMapAreaChanged. A script opens the map first, as with + // openMapWidget(). The map info box runs the profile's Lua, so this is refused where submit() is. False, with + // errorString() saying why, with no map open, a painter that is not active or a size under 10 by 10 pixels. +- bool renderMap(QPainter& painter, const QSize& size); ++ // A layoutScale above 1 lays it out at size times that, drawn scaled down to size, for a window shown enlarged, as ++ // the outlines, line weights and border fading are in pixels; mapPointer(), moveMapView() and mapView() keep to ++ // size's pixels. ++ bool renderMap(QPainter& painter, const QSize& size, qreal layoutScale = 1.0); + // The pointer, at a position in what renderMap() last drew + struct MapPointerEvent + { +diff --git a/src/headless/THeadlessSessionMap.cpp b/src/headless/THeadlessSessionMap.cpp +index 3a30bd6b4..802c3ce4c 100644 +--- a/src/headless/THeadlessSessionMap.cpp ++++ b/src/headless/THeadlessSessionMap.cpp +@@ -82,7 +82,7 @@ QHash stepsFrom(TRoomDB* pRoomDB, const int fromId) + + } // namespace + +-bool THeadlessSession::renderMap(QPainter& painter, const QSize& size) ++bool THeadlessSession::renderMap(QPainter& painter, const QSize& size, const qreal layoutScale) + { + if (!usable()) { + return false; +@@ -105,7 +105,7 @@ bool THeadlessSession::renderMap(QPainter& painter, const QSize& size) + return false; + } + pView->setMapInfoPainted(mMapInfoPainted); +- pView->render(painter, size); ++ pView->render(painter, size, layoutScale); + return true; + } + From 75cb0e4afc958c64a18166d27d724c1e9532d159 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 22:43:50 +0000 Subject: [PATCH 2/2] Compare the mapper with no density before a press selects room 2 Mudlet's painter tints a selected room, so a frame drawn after the press can never show room 2 in its own colour. Part of Mudlet/Mudlet#9011 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016ujaeFyaqXXDx8xjoThE6J --- native/tests/test_mudlet_engine.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/native/tests/test_mudlet_engine.py b/native/tests/test_mudlet_engine.py index b9414f93..d265f331 100644 --- a/native/tests/test_mudlet_engine.py +++ b/native/tests/test_mudlet_engine.py @@ -3229,12 +3229,6 @@ def places(m): check(count <= 2 * 41 * 41 // 100, f"room 2, its outline and its exit are drawn in the mapper as on the app's map: {count} of {41 * 41} pixels differ") - since = len(seen) - c.send({"t": "mapPointer", "type": "press", "x": window_room2[0], "y": window_room2[1], "button": 1}) - c.send({"t": "runLua", "code": "selected()"}) - got = seen_or_next(c, lambda m: m["t"] in ("line", "tail") and m["text"].startswith("selected "), seen, since)["text"] - check(got == "selected 2", f"a press at room 2's point of the window selects it: {got}") - # Without a density, as an engine before it, the map is laid out in the window's pixels: tiny rooms, magnified since = len(seen) c.send({"t": "setMapScale", "scale": 4}) @@ -3246,8 +3240,15 @@ def places(m): except TimeoutError as e: check(False, f"setMapScale with no density draws the mapper again, laid out in its own pixels: {e}") - # A drag and a pinch in the window's pixels: room 2 20 to the left, then twice the size about room 1 + # Selecting it tints room 2, so after the comparisons c.send({"t": "setMapScale", "scale": 4, "density": 1}) + since = len(seen) + c.send({"t": "mapPointer", "type": "press", "x": window_room2[0], "y": window_room2[1], "button": 1}) + c.send({"t": "runLua", "code": "selected()"}) + got = seen_or_next(c, lambda m: m["t"] in ("line", "tail") and m["text"].startswith("selected "), seen, since)["text"] + check(got == "selected 2", f"a press at room 2's point of the window selects it: {got}") + + # A drag and a pinch in the window's pixels: room 2 20 to the left, then twice the size about room 1 for seq, move, want in ((1, {"dx": -20, "dy": 0, "zoom": 1, "x": 50, "y": 50}, {1: (30, 50), 2: (50, 50)}), (2, {"dx": 0, "dy": 0, "zoom": 2, "x": 30, "y": 50}, {1: (30, 50), 2: (70, 50)})): since = len(seen)