I found a script to maintain the window's aspect ratio. How do I fix this final bug?

Godot Version

4.3.2

Question

I want to allow the user to resize the window without seeing black bars or stretching the viewport, maintaining a constant aspect ratio. I found an old Godot 3.x script here and I ALMOST got it updated to 4.3, but it looks like there’s a flaw in the logic for the width handling.

I’ve posted a simplified+udpated version here that cuts out some of the irrelevant logic

To explain what is going on, it compares the window size to the previous window size on every frame. If the width changes, it changes the height by a proportional amount. If ONLY the height changes, the width is changed by a proportional amount. But for some reason, only the height change behaves as expected. If you change the width, the height is changed for one frame, but not for any subsequent passes until you click again to resize it. What is going on here? Something must be off about how the first block is checked, because if I swap the sections that handle the X and Y axes, then the Y axis is the one that messes up

If it helps illustrate what I’m talking about, I have a video here https://youtu.be/XJuqJfKCk6s

I have stared at this script for hours and I have not managed to figure out what the bug is, but I took some time to rewrite it without running the script every frame. Now it mostly works as expected. It’s not perfect, but it does the job.
Strangely this is not a thing I see many people trying to do. I thought it would be a more common issue, so if anyone comes looking for this in the future, I saved my initial working script here WIP Godot4 Window Aspect Ratio Script - Pastebin.com

Out of curiosity, why do you need to resize the window without black bars? This kind of behavior can mess with fullscreen support (e.g. ultrawide monitor users can no longer use fullscreen), so it can be discouraged at times.

Fair question. I want it because the black bars are unsightly and I didn’t want images to be distorted. I’m not making anything that significantly benefits from fullscreen.
But since you bring it up, it probably would be useful to add a bit to disable the script if the user attempts to go fullscreen. It could be improved a lot actually.