Emulator: fix click->touch mapping under Xwayland

The X server can deliver pointer event coords in a scaled space
(observed: exactly half the true window-relative position), so clicks
mapped to half the intended device coords (e.g. tile 19,11 instead of
39,23 at the map's bottom-right corner). Reconstruct the cursor position
from SDL_GetGlobalMouseState() - SDL_GetWindowPosition() (raw root
coords, unaffected by event scaling) when it lands inside the window,
falling back to the raw event coords otherwise. Also map clicks through
the SDL_RenderSetLogicalSize letterbox viewport instead of scaling
against the full window size.
This commit is contained in:
Dejvino
2026-11-14 16:13:08 +01:00
parent 396731da9b
commit 260a2b3d0d
+37 -2
View File
@@ -220,10 +220,45 @@ int main(int argc, char **argv)
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP: {
// Work out the true window-relative cursor position. Two
// pitfalls to sidestep here:
// 1. SDL_RenderSetLogicalSize letterboxes the 320x240
// surface inside the (resizable) window when it is not
// exactly 4:3, so event coords must be mapped through
// that centered viewport, not scaled against the whole
// window.
// 2. Under Xwayland the X server may deliver pointer event
// coords in a scaled space (observed: exactly half the
// window size on a scaled desktop), so e.button.x/y
// cannot be trusted blindly. Reconstruct the position
// from the global cursor minus the window position
// (raw root coords on X11, unaffected by event scaling)
// and use it when it lands inside the window.
int ww, wh;
SDL_GetWindowSize(win, &ww, &wh);
int wx = (int)((int64_t)e.button.x * emuGfx::W / (ww > 0 ? ww : 1));
int wy = (int)((int64_t)e.button.y * emuGfx::H / (wh > 0 ? wh : 1));
int srcX = e.button.x, srcY = e.button.y;
if (ww > 0 && wh > 0) {
int gx, gy, wpx, wpy;
Uint32 gbtn = SDL_GetGlobalMouseState(&gx, &gy);
SDL_GetWindowPosition(win, &wpx, &wpy);
int relX = gx - wpx, relY = gy - wpy;
if (gbtn && relX >= 0 && relX < ww && relY >= 0 && relY < wh) {
srcX = relX;
srcY = relY;
}
}
int ow, oh;
SDL_GetRendererOutputSize(ren, &ow, &oh);
int wx = 0, wy = 0;
if (ww > 0 && wh > 0) {
float scale = (ww * emuGfx::H <= wh * emuGfx::W)
? (float)ww / emuGfx::W
: (float)wh / emuGfx::H;
float vw = emuGfx::W * scale, vh = emuGfx::H * scale;
float vx = (ww - vw) / 2.0f, vy = (wh - vh) / 2.0f;
wx = (int)((srcX - vx) / scale);
wy = (int)((srcY - vy) / scale);
}
if (wx < 0) wx = 0;
if (wx > emuGfx::W - 1) wx = emuGfx::W - 1;
if (wy < 0) wy = 0;