diff --git a/emulator/src/main.cpp b/emulator/src/main.cpp index e81719f..1bc5bf6 100644 --- a/emulator/src/main.cpp +++ b/emulator/src/main.cpp @@ -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;