floooh / sokol

minimal cross-platform standalone C headers
https://floooh.github.io/sokol-html5
zlib License
6.54k stars 469 forks source link

Sokol app focus steal #982

Closed zoo-3d closed 5 months ago

zoo-3d commented 5 months ago

Hi, this pr solves the issue sometimes, on luanch an executable file could not get window focus.

it has a time interval between app launch and the app fully activated. the time interval becomes longer when init_cb is slower.

if there are mouse events(e.g. mouse move) during the interval, then app can not be activated and focus will lost even when app launched and order front. I read some Apple documents and found nothing about this situation.I think maybe it's a bug in Cocoa Appkit. By the way, GTK also has this problem. And GTK solved it even though they are not 100% sure about the root cause. see: https://gitlab.gnome.org/GNOME/gtk/-/issues/2342

As a walkaround, we send a focus event in front of event queue.

floooh commented 5 months ago

Interesting fix and thanks for the investigation! I'll try to have a closer look and do some testing within the next couple of days.

floooh commented 5 months ago

Btw, I think I can reproduce the issue on my M1 Mac with Sonoma, but not sure if it's such a big issue. I simulated a long init callback by putting a sleep(5) into the init function of the clear-sapp sample.

During those 5 seconds, the window is unfocused:

Screenshot 2024-01-31 at 14 55 14

...but as soon as the first frame is rendered, the window becomes focused automatically (also if I moved the moused etc...)

Screenshot 2024-01-31 at 14 55 22

With your fix the window seems to be focused immediately (but can't be interacted with anyway).

In any case, I guess the fix doesn't do any harm either...

floooh commented 5 months ago

...ah wait the original issue was about cmdline apps, not app bundles... I'll test that too...

PS: works the same as cmdline app without the fix (e.g. the app start unfocused, but then focuses automatically at the first rendered frame).

I remember that this had issues in the past though... I guess Apple keeps fixing (and breaking) such things randomly in OS updates...

Anyway... I'll merge your fix since it doesn't seem to have any undesired side effects either :)

floooh commented 5 months ago

PS: are you actually on the latest Sonoma macOS or an older version?

floooh commented 5 months ago

And merged! I shortened your comment a bit (basically replaced it with a link to this PR), and updated the changelog.

Many thanks for the PR!

floooh commented 5 months ago

PPS: whether the window starts focused or unfocused when there's a long delay between window creation and the first random frame seems to be fairly random, but with and without the focusEvent fix. E.g. not sure if the fix is actually redundant in Sonoma, but if it helps with older macOS versions then it's fine.