r = r.getIntersection (screen);
This seems wrong to me, as unless there’s some cleverness elsewhere, it’ll collapse any window that lies outside of the viewport. I.E. if a secondary screen is removed, then screen will address the single desktop area, but if r might still be referencing the second display. The intersection then would be zero. Even in the best case scenario, the window will be shrunk, rather than relocated.
Wouldn’t it be better to just brute force it with something like:
Here, I’m assuming the screen is pre-constrained for taksbar/dock etc.