Don't confuse the window size and the viewport size.
If you zoom in or out, or scale using the 'fullscreen' options, the window size does not change. Instead, the viewport changes.
So where you use WindowWidth, you probably mean to use (ViewportRight("layer") - ViewportLeft("layer")).