fix(window): check the saved position against the monitors, not their bounding box

Reported from a multi-monitor station: window.json held x=-7680 and the
window opened where nobody could see it, with no way back short of
editing the file — which nobody knows to do.

The guard existed but asked the wrong question. It tested the position
against the VIRTUAL SCREEN, the rectangle spanning every monitor, and
monitors rarely tile that rectangle: a wide screen beside a tall one, or
one mounted higher, leaves gaps inside the box that belong to no monitor.
A window in a gap passes a bounding-box test and is invisible. The test
now walks the monitors themselves, through EnumDisplayMonitors, and uses
each one's WORK area — a title bar under the taskbar cannot be dragged
either.

A position that is genuinely lost is now MOVED onto the nearest monitor,
keeping the window's size. Handing it back to Windows lost the size too
and dropped the window on the primary screen wherever Windows chose.

The arithmetic is in screenclamp.go with no Win32 in it, and tested
against the reporter's four-monitor layout and against a gap between two:
this fault is invisible by definition and cannot be reproduced without
the reporter's screens, so a table test is the only place it can be held.
The layout is also logged at every start, since the first question after
'OpsLog does not open' is what the screens looked like.
This commit is contained in:
2026-08-25 09:53:34 +02:00
parent b2b93e2839
commit 6536d140ba
6 changed files with 271 additions and 19 deletions
+14 -8
View File
@@ -2101,6 +2101,7 @@ func (a *App) restoreWindowPosition() {
if a.ctx == nil { if a.ctx == nil {
return return
} }
logMonitorLayout()
ws, ok := readWindowState(a.dataDir) ws, ok := readWindowState(a.dataDir)
if !ok { if !ok {
applog.Printf("window: no saved geometry — opening where Windows puts it") applog.Printf("window: no saved geometry — opening where Windows puts it")
@@ -2139,10 +2140,21 @@ func (a *App) restoreWindowPosition() {
// forever — with no way back short of deleting window.json, which nobody // forever — with no way back short of deleting window.json, which nobody
// knows to do. Fall back to the default placement instead. // knows to do. Fall back to the default placement instead.
if !onSomeMonitor(ws.X, ws.Y, ws.Width, ws.Height) { if !onSomeMonitor(ws.X, ws.Y, ws.Width, ws.Height) {
applog.Printf("window: saved position %d,%d (%dx%d) is off every monitor — opening at the default placement", // Moved onto the nearest monitor rather than handed back to Windows.
// Giving up lost the size as well as the position and dropped the window
// on the primary screen wherever Windows felt like; clamping keeps the
// window the operator had, somewhere they can see it.
nx, ny, moved := clampToVisible(ws.X, ws.Y, ws.Width, ws.Height)
if !moved {
applog.Printf("window: saved position %d,%d (%dx%d) is off every monitor and no monitor could be read — opening at the default placement",
ws.X, ws.Y, ws.Width, ws.Height) ws.X, ws.Y, ws.Width, ws.Height)
return return
} }
applog.Printf("window: saved position %d,%d is off every monitor (%s) — moved to %d,%d",
ws.X, ws.Y, describeMonitors(monitorRects()), nx, ny)
wruntime.WindowSetPosition(a.ctx, nx, ny)
return
}
wruntime.WindowSetPosition(a.ctx, ws.X, ws.Y) wruntime.WindowSetPosition(a.ctx, ws.X, ws.Y)
} }
@@ -2151,13 +2163,7 @@ func (a *App) restoreWindowPosition() {
// pixel: a window overlapping the screen edge by 2 px is, in practice, as lost // pixel: a window overlapping the screen edge by 2 px is, in practice, as lost
// as one entirely outside it. When the desktop bounds can't be read, it says yes // as one entirely outside it. When the desktop bounds can't be read, it says yes
// — better to honour the operator's saved position than to second-guess it. // — better to honour the operator's saved position than to second-guess it.
func onSomeMonitor(x, y, w, h int) bool { func onSomeMonitor(x, y, w, h int) bool { return onSomeMonitorImpl(x, y, w, h) }
vx, vy, vw, vh, ok := virtualScreenBounds()
if !ok {
return true
}
return overlapsEnough(x, y, w, h, vx, vy, vw, vh)
}
// overlapsEnough is the geometry behind onSomeMonitor, split out so it can be // overlapsEnough is the geometry behind onSomeMonitor, split out so it can be
// tested — the virtual desktop origin is NEGATIVE when a monitor sits left of or // tested — the virtual desktop origin is NEGATIVE when a monitor sits left of or
+4 -2
View File
@@ -5,12 +5,14 @@
"en": [ "en": [
"Elecraft console: the transmit meters are read whenever the RADIO says it is transmitting, not only when OpsLog keyed it. Keying with the front-panel PTT, a footswitch or the mic button left the panel showing a receiver — and the power and SWR bars are read only while transmitting, so for anyone keying by hand they were never read at all.", "Elecraft console: the transmit meters are read whenever the RADIO says it is transmitting, not only when OpsLog keyed it. Keying with the front-panel PTT, a footswitch or the mic button left the panel showing a receiver — and the power and SWR bars are read only while transmitting, so for anyone keying by hand they were never read at all.",
"Cluster: the list holds still while it is being read. Scrolled away from the top it stops redrawing and shows how many spots are waiting; scrolling back to the top, or clicking the notice, releases it. On a busy evening a spot lands every second or two and the callsign under the pointer had moved by the time the click arrived.", "Cluster: the list holds still while it is being read. Scrolled away from the top it stops redrawing and shows how many spots are waiting; scrolling back to the top, or clicking the notice, releases it. On a busy evening a spot lands every second or two and the callsign under the pointer had moved by the time the click arrived.",
"Cluster command buttons take 500 characters instead of 120. A DXSpider filter listing wanted prefixes runs past a hundred easily, and the field simply stopped accepting keystrokes — saving the command truncated, with nothing to say so." "Cluster command buttons take 500 characters instead of 120. A DXSpider filter listing wanted prefixes runs past a hundred easily, and the field simply stopped accepting keystrokes — saving the command truncated, with nothing to say so.",
"Multi-monitor: the saved window position is now checked against the monitors themselves, not the rectangle that spans them. Monitors rarely fill that rectangle, and a window in one of the leftover gaps passed the old test while being invisible. A position that is genuinely lost is moved onto the nearest screen — keeping the window size — instead of being handed back to Windows, and the screen layout is written to the log at every start."
], ],
"fr": [ "fr": [
"Console Elecraft : les mesures d'émission sont lues dès que la RADIO se déclare en émission, et plus seulement quand OpsLog l'a mise en émission. Passer en émission par le PTT de façade, une pédale ou le bouton du micro laissait le panneau croire à une réception — et comme les barres de puissance et de ROS ne sont lues qu'en émission, elles ne l'étaient jamais pour qui manipule à la main.", "Console Elecraft : les mesures d'émission sont lues dès que la RADIO se déclare en émission, et plus seulement quand OpsLog l'a mise en émission. Passer en émission par le PTT de façade, une pédale ou le bouton du micro laissait le panneau croire à une réception — et comme les barres de puissance et de ROS ne sont lues qu'en émission, elles ne l'étaient jamais pour qui manipule à la main.",
"Cluster : la liste se fige pendant qu'on la lit. Dès qu'on quitte le haut, elle cesse de se redessiner et indique combien de spots attendent ; revenir en haut, ou cliquer sur l'avis, la relâche. Un soir chargé, un spot tombe toutes les une ou deux secondes et l'indicatif sous le pointeur avait bougé avant que le clic n'arrive.", "Cluster : la liste se fige pendant qu'on la lit. Dès qu'on quitte le haut, elle cesse de se redessiner et indique combien de spots attendent ; revenir en haut, ou cliquer sur l'avis, la relâche. Un soir chargé, un spot tombe toutes les une ou deux secondes et l'indicatif sous le pointeur avait bougé avant que le clic n'arrive.",
"Les boutons de commande du cluster acceptent 500 caractères au lieu de 120. Un filtre DXSpider qui énumère des préfixes dépasse la centaine sans peine, et le champ cessait simplement d'accepter les frappes — la commande était enregistrée tronquée, sans un mot." "Les boutons de commande du cluster acceptent 500 caractères au lieu de 120. Un filtre DXSpider qui énumère des préfixes dépasse la centaine sans peine, et le champ cessait simplement d'accepter les frappes — la commande était enregistrée tronquée, sans un mot.",
"Multi-écrans : la position enregistrée est désormais vérifiée contre les écrans eux-mêmes, et non contre le rectangle qui les englobe. Les écrans remplissent rarement ce rectangle, et une fenêtre tombée dans un des trous passait l'ancien test tout en étant invisible. Une position réellement perdue est déplacée sur l'écran le plus proche — en conservant la taille de la fenêtre — au lieu d'être rendue à Windows, et la disposition des écrans est écrite dans le journal à chaque démarrage."
] ]
}, },
{ {
+9 -2
View File
@@ -2,6 +2,13 @@
package main package main
// virtualScreenBounds is Windows-only; elsewhere we cannot tell, and the caller // The screen geometry helpers are Windows-only; elsewhere we cannot tell where
// treats "cannot tell" as "trust the saved position". // the monitors are, and the callers treat "cannot tell" as "trust the operator's
// saved position" rather than second-guessing it.
func virtualScreenBounds() (x, y, w, h int, ok bool) { return 0, 0, 0, 0, false } func virtualScreenBounds() (x, y, w, h int, ok bool) { return 0, 0, 0, 0, false }
func onSomeMonitorImpl(x, y, w, h int) bool { return true }
func clampToVisible(x, y, w, h int) (int, int, bool) { return x, y, false }
func logMonitorLayout() {}
+94 -4
View File
@@ -2,12 +2,17 @@
package main package main
import "syscall" import (
"fmt"
"strings"
"syscall"
"unsafe"
"hamlog/internal/applog"
)
// GetSystemMetrics indices for the virtual desktop — the rectangle spanning // GetSystemMetrics indices for the virtual desktop — the rectangle spanning
// every attached monitor. Wails' ScreenGetAll reports each monitor's size but // every attached monitor.
// not its offset, so it cannot answer "is this coordinate on any screen?"; the
// Win32 metrics can.
const ( const (
smXVirtualScreen = 76 smXVirtualScreen = 76
smYVirtualScreen = 77 smYVirtualScreen = 77
@@ -18,6 +23,8 @@ const (
var ( var (
user32Dll = syscall.NewLazyDLL("user32.dll") user32Dll = syscall.NewLazyDLL("user32.dll")
procGetSystemMetrics = user32Dll.NewProc("GetSystemMetrics") procGetSystemMetrics = user32Dll.NewProc("GetSystemMetrics")
procEnumDisplayMonitors = user32Dll.NewProc("EnumDisplayMonitors")
procGetMonitorInfoW = user32Dll.NewProc("GetMonitorInfoW")
) )
func systemMetric(index int) int { func systemMetric(index int) int {
@@ -34,3 +41,86 @@ func virtualScreenBounds() (x, y, w, h int, ok bool) {
} }
return systemMetric(smXVirtualScreen), systemMetric(smYVirtualScreen), w, h, true return systemMetric(smXVirtualScreen), systemMetric(smYVirtualScreen), w, h, true
} }
// winRect is Win32's RECT.
type winRect struct{ Left, Top, Right, Bottom int32 }
// monitorInfo is MONITORINFO: the monitor's whole rectangle and its work area
// (what is left once the taskbar is taken out).
type monitorInfo struct {
CbSize uint32
RcMonitor winRect
RcWork winRect
DwFlags uint32
}
// monitorRects enumerates the attached monitors.
//
// THE BOUNDING BOX IS NOT THE DESKTOP. The virtual screen is the rectangle that
// spans every monitor, and monitors are rarely arranged to fill it: a wide
// screen beside a tall one, or one offset vertically, leaves rectangular HOLES
// inside the box that belong to no monitor at all. A window placed in a hole
// passes a bounding-box test and is invisible — which is exactly what was
// reported from a four-monitor station whose window.json held x=-7680.
//
// So the test has to be against the monitors themselves.
func monitorRects() []screenRect {
var out []screenRect
cb := syscall.NewCallback(func(hMonitor, hdc uintptr, lprc *winRect, data uintptr) uintptr {
var mi monitorInfo
mi.CbSize = uint32(unsafe.Sizeof(mi))
if r, _, _ := procGetMonitorInfoW.Call(hMonitor, uintptr(unsafe.Pointer(&mi))); r != 0 {
// The WORK area, not the full rectangle: a title bar under the
// taskbar is a window that cannot be dragged, which is the fault
// being guarded against in the first place.
out = append(out, screenRect{
X: int(mi.RcWork.Left), Y: int(mi.RcWork.Top),
W: int(mi.RcWork.Right - mi.RcWork.Left),
H: int(mi.RcWork.Bottom - mi.RcWork.Top),
})
}
return 1 // keep enumerating
})
procEnumDisplayMonitors.Call(0, 0, cb, 0)
return out
}
// describeMonitors renders the layout for the log. A window that opens where
// nobody can see it is reported as "OpsLog did not start", and the first
// question is what the screens looked like at that moment.
func describeMonitors(rects []screenRect) string {
if len(rects) == 0 {
return "none detected"
}
parts := make([]string, 0, len(rects))
for _, r := range rects {
parts = append(parts, fmt.Sprintf("%dx%d at %d,%d", r.W, r.H, r.X, r.Y))
}
return strings.Join(parts, " · ")
}
// onSomeMonitorImpl reports whether a window at these coordinates would land
// where it can be seen and grabbed.
func onSomeMonitorImpl(x, y, w, h int) bool {
rects := monitorRects()
if len(rects) == 0 {
// Enumeration failed. Fall back to the bounding box rather than refuse
// the operator's own saved position on the strength of a failed call.
vx, vy, vw, vh, ok := virtualScreenBounds()
if !ok {
return true
}
return overlapsEnough(x, y, w, h, vx, vy, vw, vh)
}
return onAnyScreen(x, y, w, h, rects)
}
// clampToVisible moves a window rectangle onto the monitor it is closest to.
func clampToVisible(x, y, w, h int) (int, int, bool) {
return clampRectToScreens(x, y, w, h, monitorRects())
}
// logMonitorLayout writes the current screen arrangement once at startup.
func logMonitorLayout() {
applog.Printf("window: monitors — %s", describeMonitors(monitorRects()))
}
+75
View File
@@ -0,0 +1,75 @@
package main
// Placing a window on a set of monitors — the arithmetic, with no Win32 in it.
//
// Kept apart from the platform code so it can be tested: the fault it guards
// against (a window that opens where nobody can see it) is reported as "OpsLog
// does not start", is invisible by definition, and cannot be reproduced without
// the reporter's screen layout. A table test can hold that layout.
// screenRect is one monitor's work area, in virtual-desktop coordinates.
type screenRect struct{ X, Y, W, H int }
// screenRectOf is the same shape under the name the helpers below read with.
type screenRectOf = screenRect
// onAnyScreen reports whether a window would land where it can be seen and
// grabbed on ONE of the screens.
//
// One of them, not their bounding box: monitors rarely tile the box they span,
// and the leftover rectangles belong to no screen at all. A window in one of
// those holes passes a bounding-box test and is invisible.
func onAnyScreen(x, y, w, h int, screens []screenRectOf) bool {
for _, r := range screens {
if overlapsEnough(x, y, w, h, r.X, r.Y, r.W, r.H) {
return true
}
}
return false
}
// nearestScreen picks the screen whose centre is closest to the window's.
func nearestScreen(x, y, w, h int, screens []screenRectOf) (screenRectOf, bool) {
if len(screens) == 0 {
return screenRectOf{}, false
}
best, bestDist := screens[0], int64(1)<<62
cx, cy := x+w/2, y+h/2
for _, r := range screens {
rcx, rcy := r.X+r.W/2, r.Y+r.H/2
dx, dy := int64(cx-rcx), int64(cy-rcy)
if d := dx*dx + dy*dy; d < bestDist {
best, bestDist = r, d
}
}
return best, true
}
// clampRectToScreens moves a window onto the nearest screen, keeping its size
// where the screen can hold it. Returns the new position and whether it moved.
func clampRectToScreens(x, y, w, h int, screens []screenRectOf) (int, int, bool) {
best, ok := nearestScreen(x, y, w, h, screens)
if !ok {
return x, y, false
}
if w > best.W {
w = best.W
}
if h > best.H {
h = best.H
}
nx, ny := x, y
if nx < best.X {
nx = best.X
}
if ny < best.Y {
ny = best.Y
}
if nx+w > best.X+best.W {
nx = best.X + best.W - w
}
if ny+h > best.Y+best.H {
ny = best.Y + best.H - h
}
return nx, ny, nx != x || ny != y
}
+72
View File
@@ -0,0 +1,72 @@
package main
import "testing"
// The layout that produced the report: four monitors in a row, the leftmost at
// x=-7680, and a window.json holding exactly that corner.
func fourAcross() []screenRectOf {
return []screenRectOf{
{X: -7680, Y: 0, W: 2560, H: 1392},
{X: -5120, Y: 0, W: 2560, H: 1392},
{X: -2560, Y: 0, W: 2560, H: 1392},
{X: 0, Y: 0, W: 2560, H: 1392},
}
}
func TestSavedCornerOnTheLeftMostMonitorIsAccepted(t *testing.T) {
if !onAnyScreen(-7680, 0, 2272, 1044, fourAcross()) {
t.Fatal("a window on the left-hand monitor was judged off-screen")
}
}
// The fault the bounding box could not see: monitors do not tile the rectangle
// they span, and a window in the leftover space is invisible while passing a
// bounding-box test.
func TestAHoleBetweenMonitorsIsNotAScreen(t *testing.T) {
screens := []screenRectOf{
{X: 0, Y: 0, W: 1920, H: 1040}, // primary
{X: 1920, Y: -1080, W: 1920, H: 1040}, // second, mounted above and to the right
}
// Inside the bounding box (0..3840, -1080..1040), on neither monitor.
if onAnyScreen(2400, 600, 1200, 800, screens) {
t.Fatal("a window in the gap between two monitors was judged visible")
}
}
func TestAWindowInAHoleIsMovedOntoTheNearestScreen(t *testing.T) {
screens := []screenRectOf{
{X: 0, Y: 0, W: 1920, H: 1040},
{X: 1920, Y: -1080, W: 1920, H: 1040},
}
x, y, moved := clampRectToScreens(2400, 600, 1200, 800, screens)
if !moved {
t.Fatal("the window was left where nobody can see it")
}
if !onAnyScreen(x, y, 1200, 800, screens) {
t.Fatalf("moved to %d,%d, which is still not on a screen", x, y)
}
}
// A window wider than the screen it is moved to must still have its top-left
// corner on that screen — clamping the right edge first would push the corner
// off to the left, which is the same fault wearing a different hat.
func TestAWindowTooBigForTheScreenKeepsItsCornerVisible(t *testing.T) {
screens := []screenRectOf{{X: 0, Y: 0, W: 1280, H: 800}}
x, y, _ := clampRectToScreens(-9000, -9000, 2560, 1440, screens)
if x < 0 || y < 0 {
t.Fatalf("corner at %d,%d is off the screen", x, y)
}
}
// The saved position is only refused when it is genuinely lost. The rule is
// overlapsEnough's: a real slab of title bar — 160x32 — has to be visible, so a
// window hanging well over the edge is kept and a sliver is not.
func TestAWindowMostlyOffTheEdgeKeepsEnoughToGrab(t *testing.T) {
screens := []screenRectOf{{X: 0, Y: 0, W: 1920, H: 1040}}
if !onAnyScreen(1700, 900, 1200, 800, screens) { // 220 px still showing
t.Fatal("a window with 220 px on screen was judged off-screen")
}
if onAnyScreen(1850, 900, 1200, 800, screens) { // 70 px: not enough to grab
t.Fatal("a 70 px sliver was judged grabbable")
}
}