Needed to generate debug symbols for both release and debug builds and explicitly set the format so all arches actually generate the dSYMs.
This allows distributing an SDL3 app to the AppStore without the need to generate the dSYMs via script when using either the xcFramework or embedding the SDL3 Xcode project.
Fixes#13573
clang doesn't support -mcrc32 until version 14.0, therefore drop -mcrc32
use in sse 4.2 test, and change it to check _mm_cmpgt_epi64() instead of
_mm_crc32_u32(). without this, sse4.2 check was failing with clang <= 13
Fixes https://github.com/libsdl-org/SDL/pull/12223
Found when running in valgrind looking at another issue.
- RenderPass' depth_stencil_target
Tripped in SDL_BindGPUFragmentSamplers when not binding a DS target
- VulkanCommandBuffer's swapchainRequested
Tripped in VULKAN_Submit for the end transition barrier when
creating an image. The field is only reset when reused, not on first
use
When attaching a renderer (GL based specifically) to a window that was not created with the appropriate flags, the window would be destroyed and recreated to configure it for the desired rendering backend. While most of the issues with this have been mitigated over time, there can still be some undesirable side effects from doing so on certain platforms.
If the window was just created and was never configured for any graphics context, it is possible that the reconfiguration can be done without destroying the window first.
The Wayland implementation fixes an issue when creating a window with the fullscreen flag on wlroots based Wayland compositors, and can likely be extended to other platforms to avoid unnecessarily destroying/recreating a window in the very common case where a window is created, followed immediately by attaching a renderer.
This is a dirty hack, but it currently works for our purposes. We just refuse
to link an eligible string (like, say...`SDL_shadercross`), if there's a '['
character right before it.
This WILL NOT WORK if the string is in the middle of a link! For example, if
you had `[please refer to SDL_shadercross](https://example.com/)`, this will
still fail in the usual ways, but we're not building out a robust parser here
at the moment, and this catches the most common problem.
Fixes#13160.
Fixes https://github.com/libsdl-org/sdlwiki/issues/752
Closes https://github.com/libsdl-org/sdlwiki/pull/725
If a bound keymap is being destroyed, unbind it to ensure that the keyboard state won't be left pointing to an invalid keymap. Backends now no longer need to manually do this when destroying keymaps during keyboard removal and shutdown.
The dongle appears to stop sending input reports with some combination of rumble patterns, easily reproduced with Forza Horizon 5. We'll disable rumble temporarily until @8BitDo can investigate.
This correctly sets the xdg portal fields for targeting a specific
new filename or existing file.
"current_name" sets the dialogs placeholder name.
"current_file" targets an existing file.
"current_folder" for when the target is a folder.
We previously thought this wasn't possible because constant buffer offsets and
partial updates were unavailable, but we were reading the wrong table - this is
only the case for D3D11...
https://learn.microsoft.com/en-us/windows/win32/direct3d11/overviews-direct3d-11-devices-downlevel-intro
... while 12 doesn't list this feature at all:
https://learn.microsoft.com/en-us/windows/win32/direct3d12/hardware-feature-levels
We double checked and Jesse Natalie confirmed that this feature is required for
D3D12 even for 11_0 drivers. (Thanks Jesse!)
Additionally, D3D12 requires that UAVs are accessible from all shader stages,
meaning Tier 2 is enough to support the number of UAVs we need. Tier 1 could be
a property to lower the requirements, but that can be done later.
The X server maintains the desktop, but XRandR sends disconnect notifications for all displays. In this case fall back to the generic X11 desktop as a display.
- In previous firmwares for my gamepads, the buttons were sent in a static order for ABXY.
- To better be 'transparent' to the driver and save myself from future fragmentation, I am updating the mappings to be consistent, where the HID report should always expect to receive the button inputs based on cardinal button directions rather than button labels.
- This better aligns with the existing 'fallback' behavior of a generic device.
- Coincides with firmware library update: https://github.com/HandHeldLegend/HOJA-LIB-RP2040/pull/30
* Update NDK version to 28 and add 16kb page size linker flags to x86_64
* Remove Android Linker Options
16kb page size is now the default since NDK r28c
* Update Android CI to use NDK 28
SDL has been building on GNU/Hurd for a long time, using either drivers
based on external libraries (e.g. X11, pulseaudio, sndio, etc) or dummy
drivers. This commit introduces it explicitly as platform, so it can be
recognized, and tweaked as needed. In particular:
- introduce the SDL_PLATFORM_HURD define
- tighten/improve the platform detection in cmake, and use "Hurd" as
identifier
- return the platform name in SDL_GetPlatform()
- tweak the CFLAGS/LDFLAGS so pthreads can be used properly
- implement SDL_GetExeName(), using /proc/self/exe as provided by the
basic Linux-like procfs
- enable GLES 2 in tests (mostly for consistency with Linux)
In certain cases when moving fullscreen windows in scaled desktop configurations, the window origin might overlap two displays at once. Check if the window is at the origin of a specific display before falling back to the generic window rectangle check.
Fixes rare fullscreen window misplacement when moving fullscreen windows via a desktop shortcut while using the Wayland scale-to-display mode.
Use the existing SDL_GetExeName(), available for all the UNIX
platforms, in the internal GetAppName(); this has few advantanges:
- SDL_GetExeName() (and SDL_GetAppID() that builds on top of it) are
used in various places already; since it caches the executable name,
this may remove one extra read of the application name
- SDL_GetExeName() has a non-dummy implementation in more OSes than
GetAppName(), thus providing a small improvement for this IME
As drive-by change: since SDL_GetExeName() provides a constant string,
there is no more need to allocate a new string in GetAppName(), which
is used as constant string anyway. Hence, return a constant string in
GetAppName() too.
I assume the demoninator is a typo, rather than an indication that
someone has been playing too much Doom :-)
Signed-off-by: Simon McVittie <smcv@collabora.com>
"This thing allows to do something" is not really grammatically correct.
The closest rephrasing would be "allows one to do something" or "allows
the user to do something", but I think the passive voice reads more
naturally here.
Detected by Debian's lintian QA tool.
Signed-off-by: Simon McVittie <smcv@collabora.com>
This reverts commit dc2c83c383
If you need to support the Google Play 16 kiB page size requirement, the recommendation is to use NDK r28c or newer, which automatically aligns binaries correctly.
Trying to determine where a window should be made fullscreen from the size and position can be unreliable if the window exceeds the display bounds. Add additional checks with the following priority:
- If the window was positioned with a macro that explicitly passes a display ID, store and use the requested display as the explicit fullscreen target.
- Check if the window position is an exact match for any display origins, and use that display if found, as positioning a fullscreen window by moving it to the origin of the destination display is common behavior.
- Fall back to the existing center point check if the previous checks were not successful, as it is known behavior, and won't risk breaking existing clients that rely on it.
The currently used way to determine the endianness (i.e. include
<endian.h> and use the __BYTE_ORDER macro) is provided in general by
GNU libc. Thus, extend that to any platform/OS based on GNU libc.
- Use modern Xkb functions where appropriate and cleanly separate the modern and legacy paths.
- Remove the deprecated XKeycodeToKeysym function in favor of directly querying the keymap on the legacy path.
- Look up virtual modifiers by name on the Xkb path to better handle remapping (equivalent to the modifier handling under Wayland).
- Optimize keymap creation on the Xkb path to cut keymap build times and enable fast group switching (equivalent to keymap handling on Wayland).
- Enable and handle Xkb events to handle changes to the group, mapping, and modifier states. This is more reliable than using the legacy events (group changes may not arrive if the window lacks pointer focus), and better handles cases where modifiers are latched, locked, or activated externally rather than physically pressed.
Prefer axes with the 'Rel X'/'Rel Y' labels, followed by 'Abs X'/'Abs Y', and only fall back to the old behavior of using the first two enumerated axes if no others are found.
Fixes a FIXME when determining which axes to use for relative motion.
- Removed GTK signal handler in x11settings. XSettings events are now properly dispatched to X11_XsettingsNotify.
Previously events were not being passed to xsettings-client as no SDL xsettings_window was created. Now all events
are filtered through xsettings_client_process_event allowing it to process the external window events that are selected.
Global content scale is updated for changes to any recognized dpi settings.
- X11_GetGlobalContent now reads the current RESOURCE_MANAGER prop off of the root window to ensure it sees the
current value. XResourceManagerString is now only used if getting the current prop fails as it caches the current resource
manager value per-display connection.
- Clean up some warnings in SDL_gtk.
In addition to hiding the border on bordered windows that will immediately become fullscreen, The combination of flags used in STYLE_BORDERLESS_WINDOWED will still show the borders on borderless windows if the initial window size exactly matches the desktop, so STYLE_BORDERLESS must be used instead.
If attempting to switch to an exclusive mode while a fullscreen spaces transition is active, wait until the transition is complete before trying to apply the changes, or the window can wind up in a weird, broken state if a mode switch occurs while in a fullscreen space.
This reverts commit ee8f2861e7.
It turns out that the problem is elsewhere, related to needing to block mode changes until spaces transitions are complete.
- Removed gtk-xft-dpi read from GetGlobalContentScale. Xrm either returns either the same value as gtk-xft-dpi or the integer
scale value in cases where gtk-xft-dpi is 1.
- Refactor SDL_x11settings handlers to defer to GetGlobalContentScale
- GetGlobalContentScale is now exported and the XSettings and Gtk signal handlers now use it for consistency. This involves
a bit of extra work reading from Xrm rather than the setting notification but ensures consistent handling based on signal
origin and hints enabled.
- Hook both gtk-xft-dpi in SDL_x11settings. This should generally result in only one being called based on which is updated.
Since both signal handlers defer to X11_GetGlobalContentScale this will cause the same content scale to be applied multiple
times. The gtk-xft-dpi signal is now only used to trigger content scale updates when the XSettings notification does not occur.
This reverts commit 47d8bdd1c3.
There are runtime reasons why creating a tray can fail, so the correct approach is not to assume that just because a platform supports a tray that trays are available. Instead, you should create a tray at application startup, for the lifetime of the application, and handle failures at that point.
Closes https://github.com/libsdl-org/SDL/pull/13632
ABXY Face Style Application
- The abxy face style extraction now applies to any SInput device.
- The use-case here is that gamepads that allow for changing styles can dynamically adjust the button labels firmware-side to have the physical location better represent the actual button being pressed.
SInput Sub-Type Clarification
- The code has been updated to better reflect the intention behind the sub-type field of the GUID byte 15.
- Any SInput device may utilize the Sub-Type field to indicate variants of the same device (Same device that has rear paddles or additional physical features but is otherwise identical, etc.).
"Firebird" Company Name Clarification
- "Bonjiri" was a wrong translation. Got clarification from the company and official PID registration for the official English spelling (See 0c5234cd92).
- Fixed this spelling for all references (official mapping strings still pending and this will return NULL until this is provided).
Code Notes
- Various notes have been updated to have more clear indications.
- I have moved the face-type and sub-type debug messages to be paired with the extraction for easier location.
- I've removed an incorrect note left-over from a previous commit regarding command response information.
When skipping presentation due to the window being hidden, presentDataCount is not incremented on the command buffer, and subsequently the submitted command buffers will not be cleaned up as long as the window is hidden. This results in a lag spike when showing the window due to all previously submitted command buffers suddenly being cleaned up at once, and lag at shutdown due to an equivalent number of fences needing to be destroyed.
Instead of relying on presentDataCount to determine whether a command buffer should be cleaned up, use a flag, which is set under the appropriate circumstances.
- gtk_init_check claims it will not terminate the program on failure, however this is does
not apply to the internal check it performs to see whether another GTK library is already
loaded, the detection of which triggers a g_error which glib treats as fatal.
- gtk_progress_get_type and gtk_misc_get_type are checked to match the checks done
by _gtk_module_has_mixed_deps.
- Clean up gtk/gdk loading. There are no library fallbacks so the one option available can
be loaded rather than iterating through a list of one item.
There is a bug where SInput checks for player led capability before
setting RGB. This means that if a controller does not have a player led,
RGB commands are not sent.
There may have been a reason for not attaching a null buffer when destroying a popup at some point in the past, but that is unnecessary now, as is the comment about ShowWindow crashing, as ShowWindow assures that a null buffer is attached before (re)creating the window.
The previous calculation could result in a window whose original position was positioned exactly corner-to-corner with the parent not being adjusted to be adjoining, and thus subject to spurious closure.
- Android defines SDL_PLATFORM_UNIX but does not compile core/unix sources
so add checks for SDL_PLATFORM_ANDROID where SDL_gtk is used.
- Fix missing void parameter list in SDL_Gtk_EnterContext.
- Remove unneeded SDL_gtk.h include in SDL_events.c
- This is to support dynamic updates of content scale when running in XWayland. The GTK signal is
preferred over the XSettings watcher and Xrm database if supported as it will trigger and update
for both native X11 and XWayland on changes to Xft.dpi.
- SDL creates and requires usage of a specific glib context. This context is set as the global
glib context with SDL_Gtk_EnterContext and the previous context is restored with
SDL_Gtk_ExitContext.
- To avoid changing the behavior of SDL_tray, which is the only consumer of SDL_gtk currently,
the SDL_UpdateTray function now unconditionally runs a single glib frame iteration and is
responsible for dispatching glib events for all consumers in SDL_PumpEvents.
- Cleaned up some error handling in SDL_tray.
The current implementation uses the returned address of the `dlsym` function
directly to load the `environ` symbol. But this function doesn't return the
address to the symbol itself, instead it returns the address to the location
where the actual address is stored, i.e. it's an additional indirection.
Consequently, the implementation fails to load and process the environment
variables successfully.
One example where this error shows up is in the `Dialog API`: in an `X11`
environment, the `zenity` driver requires access to the user's `DISPLAY` and
`XAUTHORITY` environment variables. Because these variables aren't transfered
to the `zenity` process, no dialogs are shown. This can be exercised in the
`test/testdialog.c` testprogram.
The fix changes the indirection level of the `dlsym` call from `char **` to
`char ***`, does a `NULL`-check in case the call failed, and returns the
dereferenced actual adress to the `environ` symbol.
xpad has a series of questionable design choices when it comes to button
mapping. Notably, BTN_TRIGGER_HAPPY1-4 are used for the D-pad on dance mats
instead of the typical BTN_DPAD_*, and maps the paddles to
BTN_TRIGGER_HAPPY5-8. This commit plumbs through driver detection for a udev
device and adds special exceptions for xpad's quirks.
Newer kernels (6.17+) add the BTN_GRIP* mappings for paddles on controllers. We
should prefer that if available, as its meaning and mapping is unambiguous.
However, since it's only in new kernels, we need to maintain the older mappings
where we know they exist.
It also exposes KEY_RECORD as the share button regardless of vendor, which had
previously been gated behind being a Microsoft controller. All Xbox Series
controllers can include this button, and many third party ones do.
- Implements 'handheld' flag to indicate whether the SInput device is a gamepad or handheld (ROG Ally etc)
- Implements generic mapping fallback along with face style setting ability
Building SDL for armeabi-v7a gives this warning:
```
SDL/src/audio/SDL_audiotypecvt.c:541:14: warning: '#pragma FENV_ACCESS' is not supported on this target - ignored [-Wignored-pragmas]
541 | #pragma STDC FENV_ACCESS ON
```
This reverts commit 608f706a95.
Didn't end up using this in SDL3_mixer, and it's a super-awkward API if we
don't need it.
I _might_ bite the bullet and let people lock a physical audio device, though,
as I could see that being useful but less awkward for the same reasons I
originally wanted it.
Keymap construction is an expensive process, so keymaps are cached to facilitate fast switching, as they are static after initial construction, and do not need to be rebuilt every time.
This still logs backend choices, but we might use it for other things. For
example, what Android device is being used, or all the devices we enumerated,
etc.
Ideally this eventually logs all the stuff we often have to ask followup
questions about.
...so the backends don't have to do it.
Also added a stern warning about `org` being omitted, but leaving it as
allowed so as not to break existing apps (more than they are already broken,
at least).
Fixes#13322.
Only use the specified output if an exclusive mode is being used, or a position was explicitly requested before entering fullscreen desktop. Otherwise, let the compositor handle placement, as it has more information about where the window is and where it should go, especially if fullscreen was requested before the window was fully mapped, or the window spans multiple outputs.
When changing the text input mode on a window, only update the seats that currently hold keyboard focus on that window, otherwise, text input might be inadvertently enabled or disabled on a seat focused on another window.
Build all the available keyboard layouts at once; this adds a negligible bit of overhead when initially handling the keymap (which was already significantly lowered by previous commits), but reduces the later cost of changing layouts to just swapping a pointer.
Additionally, handling of unknown keysyms, particularly when dealing with virtual keyboards, is improved, as keys generating valid Unicode values with no corresponding scancode will be dynamically added to the keymap with reserved scancodes, allowing for proper round-trip lookup behavior.
Initializing the compose table is a very expensive operation, and only necessary if the locale envvar changed, which is often not the case when just changing the keymap, so don't destroy and recreate it whenever the keymap changes. The state only needs to be reset in this case.
Older Android phones have a kernel bug where time is not properly calculated
when calling `clock_gettime(CLOCK_MONOTONIC_RAW, ...)`. The returned time
either has nanoseconds out of range (outside of [0, 999999999]) or the returned
time is not monotonic in regards to previous call or both.
The issue is reproducible in Android Studio on arm64 emulators from at least
Android 7.0 (didn't try older versions) up to including Android 8.1 (kernel
3.18.94). The issue is in the kernel, these are just the versions of Android
emulator with buggy kernels.
The kernel commit that fixed this is [1]. Because this fix was backported to
various LTS releases of kernels it's hard to find out exactly which kernels are
buggy and which not. Therefore always use `CLOCK_MONOTONIC` on Android.
The `CLOCK_MONOTONIC` is slowly adjusted in case of NTP changes but not for
more than 0.5ms per second [2]. So it should be good enough for measuring
elapsed time.
---
An option would be to dynamically select
`CLOCK_MONOTONIC_RAW`/`CLOCK_MONOTONIC` at runtime by checking at init time
that `clock_gettime(CLOCK_MONOTONIC_RAW, ...)` returns nanoseconds in range.
Testing showed that nanosecons are out of range for 999/1000 cases. I guess
this could be good enough for support on older phones.
But because this would introduce a small perf hit by always reading a global
variable for first argument to `clock_gettime` and because `CLOCK_MONOTONIC`
does not have that high time deviation, this commit uses `CLOCK_MONOTONIC` on
Android always. It is also less burden to maintain.
---
[1] dbb236c1ce
[2] https://github.com/torvalds/linux/blob/master/include/linux/timex.h#L136
It _must_ have the format set for the opposite side from the device (so
playback needs the src format set, and recording needs the dst format set),
since the stream gets mangled by the device thread if not. So if it has never
been set (stream created with NULL audiospec), just set it to match the device.
If the stream is just meant to buffer and not convert, this is desired
behavior, even if it didn't also fix a bug.
Binding the audio stream will always set the device side's format, as usual;
this does not need to be set by the caller at all.
Fixes#13363.
This allows us to avoid browser mouse emulation for touches, since we provide
our own anyhow.
The other option is to "prevent default" in the legacy touch event handlers we
historically used, to tell the browser not to supply emulation, but we can't
currently tell Emscripten to mark those handlers as not "passive," so as it
stands they are unable to prevent default. Using Pointer Events bypasses this
problem entirely.
Fixes#13161.
macOS sends a focus loss event when the dialog is created, which causes SDL
to try to minimize the window, which confuses the entire system. So in this
special case, don't do the minimization.
Fixes#13168.
This specifically affects SDL_EnumerateDirectory and SDL_GetPathInfo. Android
assets are read-only, so no need to do this for things like
SDL_CreateDirectory, etc, and the POSIX SDL_CopyFile() uses SDL_IOStream
behind the scenes, which already supports Android assets.
Fixes#13050.
It apparently works better (or can work better?) on multimonitor setups
than SwapBuffers.
This should be available back to Windows 95, but just in case, it falls
back to standard SwapBuffers if not available.
Fixes#13269.
Wayland previously didn't specify that the seat name preceded the capabilities, but it is now specified that the name event must always come first. Remove the 'SDL_Set<device>Name()' functions that were only added to accommodate the case of compositors sending the name after the seat capabilities, as this clarification means that they are no longer needed.
The internal key repeat mechanism already disables itself if the key repeat interval is 0, and SDL tracks and handles the flagging of repeated keys itself, so just map the 'repeated' event to 'pressed'.
The spec states that xdg_surface must have seen an initial configure event before attaching a buffer, however, this was only being done when initially showing the window, and not after show->hide->show cycle.
Always wait for the initial configure event when (re)creating an xdg_surface as part of the show window sequence.
- Re-enable FPS counter, which is hidden by default anyway - but essential while working on an actual project.
- Fix link in the platform's README.
- Re-order list of supported platforms (alphabetical order to maintain consistency).
If the pointer should be confined, keep trying until a confine/lock signal is received. This considerably improves locking/confinement reliability on compositors where confining can be a racy operation, or may not take effect until the pointer is actually in the confinement region.
A pointer lock is used to special-case 1x1 confinement regions, as otherwise, the pointer can still exhibit jitter at the subpixel level, particularly on scaled desktops.
Pointer events in seat version 5 and higher should be grouped and sent together when a pointer frame event occurs. Store pending pointer motion events and dispatch them together when a frame event is received.
This helps avoid spurious pointer motion events that some compositors generate with no associated frame (e.g. from some tablet events).
This adds several minor changes to the gyro instruments.
* The HID Sensor Time display is now throttled to 10hz.
* Calibration for the gyro is now time based, not sample count based. Different polling rates will have drift calibrated over the same space of time.
* Pitch/Yaw/Roll readout: Yaw is prioritized, and then pitch, and then roll. This gives a more human-readable pitch/yaw/roll display, closely matching game engines.
* Pitch/Yaw/Roll text is colorized to match the axes in the 3D gizmo.
* Added set of axes to the 3D gizmo to show the "Left Hand Space" positive axis directions.
On newer systems, the trick isn't necessary, and if you do it, if the user is
moving the mouse when launching the app, it'll show a hidden Dock.
Fixes#10340.
Always update the border sizes on frame extent events, or they can incorrectly still be zero if followed by a PropertyNotify event when leaving fullscreen.
Fixes sending the correct restored window size when leaving fullscreen in fvwm.
The Xbox Adaptive Controller reports the pressed guide button state as 2
instead of 1. This is contrary to the spec, but it's needed for the guide
button to work.
This also adds a bit more documentation on observed-but-not-known GUIDs.
This is a special-case piece of functionality, generally these are expected
to go away during shutdown, but maybe someone is switching between audio
subsystems or something...
SDL2 would set a high bit in the mouse button flags to indicate when raw input had been read from, without this, if you hold down a mouse button and left raw input mode (leaving relative mode) the button would remain partially stuck, and would require two clicks to start producing mouse down events again.
SDL3's raw input code was refactored to not use the mouse button flags, but forgot to invalidate the flags, causing this bug to manifest.
- Check for specific availability instead of waiting for "device ready."
- Don't use snd_pcm_wait, just use a simple SDL_Delay (nothing to recover).
- Fixed SDL_max call that should have been SDL_min (now using SDL_clamp).
- ALSA_RecordDevice() now returns 0 if no availability, which kicks us back
to WaitDevice to try again, as an extra safety check.
Also made accelerometer threshold for drift calibration more lenient for very noisy accelerometers.
The testcontroller tool could eventually be used to come up with a better way to profile an IMU's "stationary" noise so that this threshold can be as tight as necessary for the sake of automatic drift calibration.
(thanks @HilariousCow!)
Flydigi IMU rate now matches observed rate of packets in both dongle and wired connection.
Flydigi Vader 4 Pro IMU rate correction was set at a fixed 125hz. In actuality rate is 1000hz over dongle and 500hz when wired.
Gathered correct IMU polling rate in wired mode for good gyro synchronization.
Wireless: different models had different amounts of Bluetooth packet loss.
USB_PRODUCT_8BITDO_ULTIMATE2_WIRELESS: Solid 120hz over bluetooth (note: only appears via).
USB_PRODUCT_8BITDO_PRO_2_BT: Lossy - 80-90hz registered.
SB_PRODUCT_8BITDO_SN30_PRO_BT & USB_PRODUCT_8BITDO_SN30_PRO_BT: Very Lossy - 60-90hz registered
* Added tools to Test Controller for evaluating gyroscope accuracy and IMU polling rates.
This adds a visual suite to the testcontroller tool to help validate IMU data from new gamepad drivers and HID implementations.
The 3D gizmo renders accumulated rotation using quaternion integration of gyroscope packets. If a controller is rotated 90° in real space, the gizmo should reflect a 90° change, allowing quick detection of incorrect sensitivity or misaligned axes.
Also includes:
- Euler angle readout (pitch, yaw, roll)
- Real-time drift calibration display with noise gating and progress
- Accelerometer vector overlay
- Live polling rate estimation to verify update frequency
Intended for developers working on controller firmware or SDL backend support to confirm correctness of IMU data processing.
The pointer warp protocol allows us to warp the pointer to a different position on
the surface, without any hacks like locking and unlocking the pointer.
XMonad ignores size hints and shrinks the client area to overlay borders on fixed-size windows, even if no borders were requested, resulting in the window client area being smaller than requested. Calling XResizeWindow after mapping seems to fix it, even though resizing fixed-size windows in this manner doesn't work on any other window manager.
When querying the keycode produced by a scancode with a certain set of modifiers, it would fall back to defaults if a key hash value with the exact set of modifiers wasn't found, which resulted in certain modifier combination returning incorrect keycodes on non-ANSI keyboard layouts. For example, querying SDL_SCANCODE_Y with the alt modifier on a QWERTZ layout returns SDLK_Y instead of SDLK_Z on most platforms, as the backends don't generate a specific entry for this key + modifier combo, so the lookup would fall back to the default ANSI layout.
Adding additional key+modifier combinations when building the keymap is one solution, but it makes an already expensive operation even more so, pushing the time needed to build the keymap into double-digit milliseconds in some cases due to the large amount of key combos that need to be queried, most of which are redundant.
Instead, falling back to searching through the shift levels for the given modifier state when querying the keymap will ensure that the most appropriate keycode is returned. This does add some overhead to lookups if the key doesn't have an entry with the exact set of modifiers, but it is minimal as hash table lookups are an inexpensive operation, and unnecessary lookups are avoided. In my own testing of an optimized build, the difference between best-case and worst-case performance (the latter of which is highly unlikely in real-world usage) is only a few hundred nanoseconds. Additionally, the unmodified keys are queried when pumping events, so there is no additional overhead in that case.
Windows seems to implicitly enable IME text input on windows created while an IME is active, which causes the IME suggestion window to pop up when keys are pressed, even if a client never explicitly enabled it. Ensure that IME support is initially disabled on new windows; SDL will enable it at a later time, if required.
Previously, all transparent pixels were rendered as opaque due to the limitations of the 4K color mode. Replaced Gc()->BitBlt() with Gc()->BitBltMasked() and updated the mask during copy operations to correctly respect the alpha channel of textures, while maintaining good performance.
The first public beta that had a corresponding arm64 version has now
been promoted to stable, and subsequent releases will be for both
x86_64 and arm64.
Signed-off-by: Simon McVittie <smcv@collabora.com>
This makes sure we get reliable mouse enter/exit events from the system on
older macOS releases.
Newer releases don't have this problem--my assumption is that Cocoa has a
more aggressive default tracking area installed for some newer UI feature.
For 3.2.16, we'll use the explicit tracking area on older macOSes only, but
I'll remove that check in revision control for newer OSes and see what
happens.
Fixes#12725.
Use the proper types for xkb mod masks and layout indices, rename the mod masks to reflect that they are bitmasks and not indices, and use the 'layout' nomenclature instead of the deprecated 'group' nomenclature.
xkbcommon 1.10.0 declared certain modifier names to be deprecated, and the current plan is to remove them in 1.12.0. Use the new recommended names and modifier mask retrieval function when building against version 1.10.0 and higher.
Windows can get in a state when it stops reporting raw input events for game controllers until reboot.
The downside of this change is that we lose support for trigger rumble and are limited to 4 controllers again, but if that's important for your application you can use SDL_SetHint(SDL_HINT_JOYSTICK_RAWINPUT, true) to enable this functionality.
Fixes https://github.com/libsdl-org/SDL/issues/13047
Using processed timestamps can result in anomalies that cause excessive repeat events, and hard caps can cause issues.
In the key event handler, use the raw elapsed time to calculate any remaining repeat events to avoid the artifacts that can result from using processed timestamps.
The Wayland key repeat rate ranges from 0 to 1000 per second, so millisecond resolution doesn't lose any precision.
More non-compositing window managers than just openbox seem to need this, so always force sending the window position and dimensions when entering/leaving fullscreen. If they are wrong, they will be immediately overwritten by the correct dimensions from a subsequent ConfigureNotify event.
This is disabled on XWayland, as it seems to cause hitching on some compositors.
This mostly fixes stylistic issues, but also fixes an issue with some
controllers where an erroneous check would clear the DLI flag, offsetting the
share button index so it wouldn't work.
Cap the elapsed time to something sane in case the compositor sends a bad timestamp, which can result it in it looking like the key has been pressed for a *very* long time, bringing everything to a halt while it tries to enqueue all the repeat events.
The function SDL_GetCurrentKeymap() would return null instead of the actual bound keymap for non-latin layouts if certain mapping options were set. Add a parameter to ignore the keymap options and always return the actual bound keymap, which is needed in the Wayland backend to avoid spamming keymap changed events on every keystroke with certain layouts.
The text input cursor should reflect the cursor position, not the entire text input rect. Set it correctly so that IME chooser dialogs appear in the correct location.
SDL_PrivateJoystickAdded was called before setting the InstanceId in the adapters ctx->joysticks array. This would eventually broadcast the SDL_EVENT_JOYSTICK_ADDED event with the new InstanceId, if your program listens for the added events and opens joysticks at that point it would always fail because there would be no matching InstanceId in the ctx->joysticks array.
This can be toggled per-window, so use the individual window flags instead of the global toggle to selectively enable it only for the relevant window in a multi-seat scenario, as is already done with keyboard and pointer grabs.
The main view always reflects the size of the output, so don't use the dimensions of the currently bound render target texture when updating it, or it will reflect an incorrect size when the render target texture is unbound.
This and its related commits introduced some bugs and quirks such as duplicated and delayed/missed key events that can't be easily worked around, so revert this for now.
This reverts commit 47162a4168.
The keys and values of device_hash are pairs
`(SDL_AudioDeviceID devid, void *dev)` where dev can be either a
`SDL_AudioDevice *` or a `SDL_LogicalAudioDevice *`, depending on
bit 1 of devid.
We can confirm that we have got this right by looking at the
instance_id member, because logical audio devices happen to start with
the devid, whereas physical devices start with a pointer which is
unlikely to match the devid by chance.
Signed-off-by: Simon McVittie <smcv@collabora.com>
Compositors typically send keyboard, pointer, touch, and tablet leave events when a window is destroyed, however, this is not guaranteed behavior, and at least one compositor in widespread use doesn't always send pointer leave events immediately upon destroying a window. Ensure that all references held by seats to a focused window are removed before the underlying window surface and structs are destroyed to prevent potential segfaults if the seats are immediately destroyed after the window.
This loop breakout was originally from an attempt to parse coalesced packets.
Breaking out early does more harm than good, and no devices coalesce packets,
so this is unnecessary.
By moving the message sending onto the main thread and adding a small timeout
we can now ensure the ACKs are sent fast enough to avoid the firmware bugs in
these controllers.
At the moment, only the ThrustMaster T.Flight Hotas One has full support. The
documentation says you can query the extra buttons via a specific command, but
the stick appears to reject the command. Further investigation is needed for
automatically querying this state.
This is needed for future work bringing up things like the chatpad.
This commit also fixes a few minor things, such as still sending motor packets
to devices that don't support it, enabling quirks that hide trigger rumble on
devices that are marked as not having it, and fixing #12942.
The surrounding code in all of these instances expects the Unicode
variants. Previously, this code mixed Unicode and ANSI/ASCII calls if
`UNICODE` was undefined, which caused type and logic errors. Explicitly
spelling out the W removes any reliance on that macro.
IME text events can result in sending duplicate key press events, which will result in undesired repeated key presses. Since the events are exact duplicates, compare the serials to filter out redundant key down events.
The Module interface is the one used by the outside world. This code
is inside the module itself so can use the internal name, avoiding the
need to export this function on the Module at all.
See https://github.com/emscripten-core/emscripten/pull/24269
You can't have two sections with the same name (so it can generate unique
page anchors), so fix one of these, and tweak another thing that _isn't_ a
header but wikiheader's quick-and-dirty parser thinks is one.
Using a 0 sequence number is always allowed and avoids having to synchronize sequence numbers with the controller (and potentially confusing other things talking to the controller)
Also fixes occasional long running rumble at controller connection.
The xserver will still send EnterNotify events while the pointer is captured, and the grab shouldn't be updated in these cases, as it will cause the capture to be lost.
Otherwise, the message box thread goes back to blocking, but the app's main
thread progresses to SDL_WaitThread and won't pump the event queue anymore.
On iOS, this means the messagebox won't pop back up (because it uses
SDL_RunOnMainThread, which needs the event loop to pump), but it's just bad
practice on any platform to stop pumping the event queue for indefinite
lengths of time.
If it is known that the window will immediately enter fullscreen upon being shown, set the borderless style when showing the window to hide the borders, or they may linger in the background if the client takes some time to draw the first frame.
Unnecessarily calling ShowWindow with SW_RESTORE when applying the window flags must be suppressed in this case, or the borders can reappear in a weird, partial state.
Otherwise the window won't have focus until you click on it again. Calling
makeKeyAndOrderFront isn't enough to fix it, either.
This trick comes from a similar problem we solve in our
applicationDidFinishLaunching implementation: activate (give app focus to) the
system Dock, as something that definitely exists that isn't us and is harmless
to activate, and then activate us right afterwards. This unconfuses whatever
is getting confused inside Cocoa.
Fixes#12684.
So something like "index.pb" will now accept any file with a ".pb" extension,
to make macOS happy. This seems like a reasonable tradeoff.
Other minor cleanups.
Fixes#12778.
sdl2-compat will call SDL_GetDisplayForWindow() when querying the display to use for fullscreen, which won't always be correct if the backend can't actually reposition the window. When calling this function, get the ideal fullscreen display and store it in a property for retrieval by sdl2-compat.
This new driver is based on official documentation released by Microsoft in
September, though it still lacks several important features, notably the
Security handshake for wireless dongles and audio support. It is, however, more
reliable and extensible than the old driver.
This is for internal use to signal that a mapping uses positional GameCube buttons. It's set so we know whether a mapping uses the older style labeled buttons or the newer style positional buttons. If a positional mapping is used with SDL2, then it will be ignored, since the hint is marked as defaulting true and the mapping conditional is that the hint is false.
Mouse button events that trigger a hit test are not passed to the client, but the client may still query the global mouse button state from within the hit test handler, so the reported buttons need to be accurate. Query the buttons directly from the seat instead of the higher global mouse state to match the behavior of other platforms.
The low 16-bits of the message extra info is an event sequence number when using the Wacom tablet with Windows Ink disabled. The high bits of normal mouse motion when using touch input match the touch signature, 0xFF515700. The high bits of raw input mouse motion when using touch input do not match that signature, so we have to check for the touch bit in that case.
Fixes https://github.com/libsdl-org/SDL/issues/12927
The problems are two-fold. When this happens a WM_POINTERDOWN event is sent with IS_POINTER_INCONTACT_WPARAM() evaluating as true. So when SDL_SendPenButton() is sent for the barrel button, there is no pen in contact yet, so the right mouse button is sent. Then SDL_SendPenTouch() is sent, which generates a left button press event.
Fixes https://github.com/libsdl-org/SDL/issues/12926
These events fire for other things, such as pressing a barrel button while
the pen is hovering.
The correct thing to do is check IS_POINTER_INCONTACT_WPARAM in the event.
If the pen is already touching or not, SDL_SendPenTouch() will do the right
thing, so it's safe to call it even if we're already in the right state.
By default, popups are automatically constrained to be completely within display bounds, so as not to cut off information and result in an unusable menu, or unreadable tooltip. In some cases, however, this is not wanted, so a property to toggle this behavior is added.
There are also cases where the client may not want a popup menu to implicitly grab the keyboard focus, as is the default behavior, so popup menus now respect the focusable flag/property, as well as being able to toggle focus grabbing via SDL_SetWindowFocusable().
The GameCube controller has a different face button layout than the Xbox or Nintendo Switch style controllers. It has the B button on the left and the X button on the right, so we should map those to SDL_GAMEPAD_BUTTON_WEST with SDL_GAMEPAD_BUTTON_LABEL_B and SDL_GAMEPAD_BUTTON_EAST with SDL_GAMEPAD_BUTTON_LABEL_X respectively.
Fixes https://github.com/libsdl-org/SDL/issues/12847
When showing or hiding a popup menu, manually check and set the focus if the new topmost window under the cursor is an SDL window. Otherwise, the focus won't be updated until the cursor is actually moved.
There is a quirk with XInput2 mouse capture that causes a leave event to be sent if the pointer moves out->in->out, which breaks mouse tracking outside the window. If the mouse leaves the window with buttons pressed, continue tracking it until the buttons are released.
- IsIconic/IsZoomed must be checked after sending SDL_EVENT_WINDOW_SHOWN as that may trigger window operations if any are pending from when
the window was hidden. e.g. the window may be shown, which triggers SDL_MaximizeWindow and a new WM_WINDOWPOSCHANGED where
SDL_EVENT_WINDOW_MAXIMIZED is sent, then control returns to the original WM_WINDOWPOSCHANGED which would not think the window is zoomed
and send SDL_EVENT_WINDOW_RESTORED.
This info shows up in `pw-top` ...Gnome's sound preferences (etc) would
already show something more app-specific, but this command line tool shows
specific stream names.
Previously, we would WaitDevice first, but that would feed a silent buffer
to AAudio upfront, introducing latency. When this change was made, the
semaphore count should have been adjusted, since we're waiting on one less
buffer.
Fixes#12882.
This variable is always defined when targeting Android:
- when using the toolchain file shipped along the ndk
(using -DCMAKE_TOOLCHAIN_FILE=$ENV{ANDROID_NDK_HOME}/build/cmake/android.toolchain.cmake)
- when using the toolchain file provided by CMake
(using -DCMAKE_SYSTEM_NAME=Android)
- Add checks that ObtainPhysicalAudioDevice() was previously doing
(is subsystem initialized, is device valid).
- Remove optimizations that copy string to stack to release device_hash_lock
before SDL_GetPersistentString is called. Probably not necessary, and made
the code more complex.
Previously, touchpad events were not reported to the application.
This patch exposes two touchpads and forwards x/y/pressure information
from the HIDAPI packet.
This fixes issue #12855
According to the documentation and testing the `emscripten_webgl_create_context` function returns `0` on error as oppposed to a negative number. This was causing the error message to be empty when the later `emscripten_webgl_make_context_current` call fails given the invalid context.
See https://emscripten.org/docs/api_reference/html5.h.html#c.emscripten_webgl_create_context
Xfce, unlike every other window manager in existence, sends ConfigureNotify events before PropertyNotify events when toggling the fullscreen and maximized window state. Check the window state when handling ConfigureNotify events, and defer emitting SDL size/position events until the corresponding PropertyNotify event arrives, since SDL and clients expect to get the window state before the new size and position.
This warning is actually wrong, as the variable is only used if the string pointer is valid, in which case it was initialized, but this is needed to quiet MSVC.
This was already present for regular rumble to ensure that controllers would
continue rumbling for extended periods, but was missing for trigger rumble. I
don't know if this affects any controllers at the moment, but it's helpful for
future-proofing.
For a depth buffer in D3D12 that is also going to be used in a texture sampler, the creation (on an Intel HD 5500 igpu) fails. e.g. SDL_GPUTextureCreateInfo type = TEXTURE_2D, format = D32_FLOAT, usage = DEPTH_STENCIL_TARGET | SAMPLER
The error messages are:
D32_FLOAT
D3D12 ERROR: ID3D12Device::CreateShaderResourceView: The Format (0x29, R32_FLOAT) is invalid when creating a View; the
Resource was already created with a fully qualified Format, which is not castable (0x28, D32_FLOAT).
D24_UNORM
D3D12 ERROR: ID3D12Device::CreateShaderResourceView: For the resource format D24_UNORM_S8_UINT, when making a D3D view, the format name for the view can't be R24_UNORM_X8_TYPELESS.
I found this is because the texture format needs to be created as _TYPELESS, then the views (depth stencil view, shader resource view) should then be created as their respective types - e.g. texture = R32_TYPELESS, dsv = D32_FLOAT, srv = R32_FLOAT
Tested and working on:
NVidia RTX 3050 (D3D12 feature set 12_2)
Intel HD 5500 (D3D12 feature set 11_1)
Wayland compositors may send recursive clipboard offers to the client, which need to be filtered out to avoid clearing local data. Previously this was worked around with a hack, but this caused the ownership flag to be set incorrectly, which broke some clients.
This introduces a metadata MIME type of application/x-sdl3-source-id to be sent with SDL3 selection offers, which contains a string that is a unique identifier for the instance, and can be used to detect if a received selection offer is originating from the same instance that generated it.
If DBus is available, the unique identifier string is the unique name of the connection, otherwise, the process ID is used.
If a window isn't resizable from specific directions, the compositor can inform clients of the current edge constraints, so they don't display resize cursors for non-resizable edges.
Wayland environments can expose more than one seat for multiple collections of input devices, which can include multiple, simultaneously active, desktop pointers and keyboards with independent layouts. The Wayland input backend previously presumed that only one seat could exist, which caused broken behavior if the compositor exposed more than one, which is possible on wlroots based compositors such as Sway. This introduces support for handling multiple seats, including proper handling of dynamically added and removed seats and capabilities at run time.
The SDL Wayland input system was accreted over time, and the assumption that only one seat will ever exist resulted in state and related objects not always being tied to their most appropriate owner in a multi-seat scenario, so refactoring was required to manage several bits of state per-seat, instead of per-window or globally.
As Wayland keyboards can have per-seat layouts, fast keymap switching is required when multiplexing input from multiple seats to the global SDL keyboard device. A parameter was added to the keymap creation function to specify if the keymap lifetime should be externally managed to facilitate keymap reuse, and some layout info was moved from the global keyboard state to the keymap state to avoid unnecessarily redetermining it whenever a reused keymap is bound. This reduces the overhead of switching keymaps to setting a single pointer.
Multiple seats also means that multiple windows can have keyboard and/or mouse focus at the same time on some compositors, but this is not currently a well-handled case in SDL, and will require more work to support, if necessary.
Fix IMU timing stamp - simulate the timing stamp from the controller hardware's perspective, as opposed to the receiving computer's perspective. Do this by advancing a time stamp by a fixed rate, based on observation of average rate over bluetooth.
This reverts commit 5a59b5f321.
The strong ABI guarantee only applies if bool is a byte (we repurposed a Uint8 field as a bool in SDL_gpu.h), and 32-bit PPC isn't a platform we support, so I'm going to back this patch out.
The window may be initially maximized or made fullscreen by the window manager for various reasons, such as automatically declaring a window that precisely fills the usable desktop space as maximized, or a "kiosk-mode" automatically making the window fullscreen.
Don't redundantly make restored or unset fullscreen calls when initially showing a window, or the expected state can be unset.
These callbacks run in a thread we don't control, but might call SDL_SetError,
which will claim a TLS slot that never gets otherwise deallocated. To prevent
the leak, finish each callback by explicitly freeing any thread-local data.
Fixes#12732.
It doesn't work well with Vulkan, and Vulkan windows may not have the Vulkan flag set in all circumstances, so only enable it if we explicitly know that OpenGL is being requested instead.
Moved the event handlers from SDL_CreateWindow to SDL_VideoInit
emscripten_set_mouseup_callback
emscripten_set_focus_callback
emscripten_set_blur_callback
emscripten_set_pointerlockchange_callback
emscripten_set_fullscreenchange_callback
emscripten_set_resize_callback
We may want to extend this with additional properties in the future.
Also removed SDL_PROP_GPU_DEVICE_DEBUG_VULKAN_CONFORMANCE_STRING. If we need feature level queries we can add them in the future.
On non-compositing window managers, XIconifyWindow can trigger map/unmap events, which would toggle the window hidden/shown state. This should not be done, as a hidden window in SDL is equivalent to a withdrawn window in X, and SDL will try to set/reset state when it is shown again.
Unless the window is explicitly being withdrawn via X11_HideWindow(), set unmapped windows to the minimized/occluded state, and send a restored event when mapped again.
This hint needs to persist outside of the normal application flow, so use the environment to set the initial value, and then save the value set via SDL_SetHint() after that.
Fixes https://github.com/libsdl-org/SDL/issues/12677
This fixes the feature detection in cases where linking the final executable would fail.
This is fine since SDL only opens these libraries using dlopen as well.
The taskbar list is invalid after OleUninitialize(), so make sure we clean it up first.
Also don't bother creating the taskbar list if we don't have any progress state
this was causing problems when i was specifying non-zero buffer slots in
`SDL_BindGPUVertexBuffers`, `SDL_GPUVertexAttribute` and
`SDL_GPUVertexBufferDescription`.
`firstSlot + 1` is simply copied over from metal and d3d12 backends.
We'll default this off for now, since we don't detect whether the controller is running firmware v1.03 and don't have a fallback for controllers running firmware v1.02 (the out-of-box firmware)
For some reason this locks up the Windows compositor when called by Steam. I'm disabling it for now until we understand why and whether this can cause issues for other applications as well.
The window failing to enter/exit fullscreen notifications don't necessarily imply anything about the actual state of the window. On failure, dump pending events, and don't presume anything about the current window state, as it will be handled by subsequent enter/leave notifications.
SDL still manages hotplug and default device management here, but if a user
wants to use an external tool, such as `pactl move-sink-input`, to put it
onto a different device, they probably know what they're doing and we
shouldn't stop them.
If this turns out to have some unexpected consequences, though, we can revisit
the change.
Fixes https://github.com/libsdl-org/sdl2-compat/issues/367
GNOME requires this to allow keyboard grabs on XWayland. Otherwise, XGrabKeyboard will still report success, but shortcuts won't be inhibited.
See 5f132f3975
Otherwise, in the time it takes the thread to start and other init tasks to
complete, we tend to get an underrun on some systems, which ALSA logs to
stderr.
So this is moved to an InitThread implementation, which runs from the device
thread, right before it begins its main loop.
Reference PR #12632.
The accelerated relative coordinates are always relative to the desktop resolution, and need to be scaled with emulated fullscreen resolutions for mouse movement to remain stable. Otherwise, pointer speeds will be too fast on emulated resolutions below the desktop resolution, and too slow on those above.
The GPU API doesn't currently support transparent windows (transparent swapchain effects doesn't seem possible on D3D12) so we should explicitly fail so users don't expect transparency and then not get it.
Fixes https://github.com/libsdl-org/SDL/issues/12410
If the window is flagged with SDL_WINDOW_TRANSPARENT, create the associated swapchain with a composite alpha value that supports blending, if available.
Fixes transparent windows on the Vulkan backend, and prevents possible validation errors by ensuring that the composite alpha value is always a valid bit in VkSurfaceCapabilitiesKHR::supportedCompositeAlpha.
* Allow custom message boxes with colors and multiple buttons to work if Asyncify is enabled
* Keep old functionality of using alert when Asyncify is not available
* Update testmessage to allow for setting random colors as the color scheme of the message box
We can't use keyboard input as a signal about whether a keyboard is attached. There might be keyboard input from any number of generated inputs or non-keyboard devices.
The tm_gmtoff field of the broken-down time 'tm' struct wasn't formally standardized until POSIX.1-2024, but practically it has been available on desktop *nix platforms such as Linux/glibc, FreeBSD, OpenBSD, NetBSD, OSX/macOS (NextStep before that), and others since the 1990s. The notable exception is SunOS/Solaris, where the timezone offset must still be retrieved in the strictly POSIX.1-2008 compliant way.
SDL_IsGamepad() calls SDL_GetJoystickTypeForID(), which will call SDL_IsGamepad() if it's not a known controller type. The new code which is breaking was added to prevent Logitech FFB wheels from showing up as gamepads, which we check for separately.
On Windows 11, apparently HidD_GetManufacturerString() and HidD_GetProductString() can return TRUE without actually filling in any string data.
Fixes https://github.com/libsdl-org/SDL/issues/12566
These changes enable the Logitech G29 wheel to run on hidapi with both SDL_Joystick and SDL_Haptic interfaces.
While it is already possible to use the wheel on Linux in WINE + SDL2 thanks to the in-tree evdev driver as well as new-lg4ff, these set of changes allow the G29 to be used with WINE under MacOS and FreeBSD
These wheels should also be supported, but I can only test them from G29's compat modes: G27, G25, DFGT, DFP, DFEX
Haptic and led support are ported from https://github.com/berarma/new-lg4ff
SDL 2.0.18 added preciseX/Y to mouse wheel events, which we cannot
emulate in sdl2-compat without a mechanism to control integer position
and scroll deltas separately.
The existing behavior helps clients that don't expect exclusive fullscreen windows to move by maintaining a consistent size and mode, however, some are aware that this can occur and want to handle mode selection themselves.
Add a hint to disable auto mode switching when an exclusive fullscreen window moves to accommodate this use case, and don't override fullscreen changes that may occur in an event watcher between the display changed event being posted and SDL running the display changed handler, as the mode switch may have already been handled there by the client.
Move hints used by Emscripten to window properties. This change will be necessary if multiple windows for Emscripten will be supported in the future.
- Added Window Create Property SDL_PROP_WINDOW_CREATE_EMSCRIPTEN_CANVAS_ID
- Added Window Create Property SDL_PROP_WINDOW_CREATE_EMSCRIPTEN_KEYBOARD_ELEMENT
- Use hint SDL_HINT_EMSCRIPTEN_CANVAS_SELECTOR as override to SDL_PROP_WINDOW_CREATE_EMSCRIPTEN_CANVAS_ID
- Use hint SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT as override to SDL_PROP_WINDOW_CREATE_EMSCRIPTEN_KEYBOARD_ELEMENT
- WIN_SetWindowAlwaysOnTop is always called as part of window creation (normally setting HWND_NOTOPMOST) which also set the z-order for the parent
window when child windows are created. Since HWND_NOTOPMOST is above all non-topmost windows this had the effect of reordering but not focusing
the parent window.
With ASAN enabled the existing code triggered null-pointer-dereference
in the strcmp since EMSCRIPTEN_EVENT_TARGET_WINDOW is a "fake" pointer
with the value ((const char*)2). In fixing this it was also noticed
that using the #window/#document/#screen targets as mentioned in the
docs fails since document.querySelector() returns null for them and we
should instead be mapping them to the special HTML targets provided.
External windows may call this to update the renderer size, but not pump SDL events, either by syncing or running an event loop, so the size event always needs to be synthesized for external windows. If it is wrong, the true size will be sent if/when events are processed.
The bug this appeared to fix turned out to be randomly occurring and has other causes, and the read pipe is already polled for readiness, so this extra overhead isn't necessary.
The platforms that needed this (Windows Phone and Windows RT) are no longer supported, and if this is needed in the future it should be done at the renderer level, not here.
Fixes https://github.com/libsdl-org/SDL/issues/12475
External windows often handle their own events, and SDL implicitly processing events during synchronization can be unexpected and cause issues. For requests that don't change the window state beyond size or position, use the legacy synchronization method that synthesizes events from the window attributes without processing events.
This reverts commit 0c8ddc1f0a.
The real bug here is that XWayland isn't sending us a display disconnected event, which will be handled in the next commit.
Openbox doesn't send size events when entering fullscreen, so they must be synthesized. This is not desirable on any other window manager, as it can break fullscreen positioning on multi-monitor configurations.
People are adding present calls while rendering to render targets, not understanding that this doesn't make sense, and wondering why they get flicker on some systems. If there are programs that relied on the previous behavior we can add a hint to control this.
Fixes https://github.com/libsdl-org/SDL/issues/12432
This is true if fullscreen is pending or currently active. This is a better check in SDL_SetDesktopDisplayMode() because a fullscreen mode may be pending and complete asynchronously and the window hasn't been set to fullscreen yet.
The Debian 12 'bookworm' stable release only has 0.3.65, which is earlier
than the introduction of that symbol. Similarly, Steam Runtime 3 'sniper'
and Steam Runtime 2 'soldier' have a backport of 0.3.65 from Debian 12,
so they have the same limitation.
steamrt/tasks#686
Signed-off-by: Simon McVittie <smcv@collabora.com>
This helps the Pipewire camera driver to access cameras
in a sandboxed environment without host Pipewire socket access.
Unlike other platforms, no event is sent when the user rejects
camera access. This is because there is no mechanism to query
cameras through the portal, and we only obtain access to the
Pipewire fd if the user accepts the request. The Pipewire driver
will attempt to open the host socket instead.
Changing the mode triggers a display reconfiguration event, which will overwrite the desktop mode with the set fullscreen mode, preventing proper restoration when leaving fullscreen. Don't overwrite the desktop mode if the reconfiguration is due to a fullscreen mode switch.
Fullscreen spaces and miniaturization will always give us some notification that they succeeded or failed, so the timeout isn't required. This prevents errant timeouts when live-resize is active.
"steamrt-sniper":JobSpec(name="Steam Linux Runtime (Sniper)",os=JobOs.UbuntuLatest,platform=SdlPlatform.Linux,artifact="SDL-slrsniper",container="registry.gitlab.steamos.cloud/steamrt/sniper/sdk:beta",),
"steamrt3":JobSpec(name="Steam Linux Runtime 3.0 (x86_64)",os=JobOs.UbuntuLatest,platform=SdlPlatform.Linux,artifact="SDL-steamrt3",container="registry.gitlab.steamos.cloud/steamrt/sniper/sdk:latest",),
"steamrt3-arm64":JobSpec(name="Steam Linux Runtime 3.0 (arm64)",os=JobOs.Ubuntu24_04_arm,platform=SdlPlatform.Linux,artifact="SDL-steamrt3-arm64",container="registry.gitlab.steamos.cloud/steamrt/sniper/sdk/arm64:latest",),
"vita-pvr":JobSpec(name="Sony PlayStation Vita (GLES w/ PVR_PSP2)",os=JobOs.UbuntuLatest,platform=SdlPlatform.Vita,artifact="SDL-vita-pvr",container="vitasdk/vitasdk:latest",vita_gles=VitaGLES.Pvr,),
envvardesc = SDL3 can be controlled by the user, externally, with environment variables. They are all operate exactly like the [hints you can get and set programmatically](CategoryHints), but named without the `_HINT` part (so `"SDL_HINT_A"` would be environment variable `"SDL_A"`).\n\nThis list matches the latest in SDL3's revision control.
- On Windows the executable is in the build Debug directory:
```sh
cd build/Debug
./hello
```
- On other platforms the executable is in the build directory:
# Run:
The executable should be in the `build` directory:
```sh
cd build
./hello
```
If there wasn't an executable there despite the above Build section running successfully, it's likely because you're following this guide using the Visual Studio toolchain, it should instead be in the `build/Debug` directory:
Without getting deep into the history, MinGW is a long running project that aims to bring gcc to Windows. That said, there's many distributions, versions, and forks floating around. We recommend installing [MSYS2](https://www.msys2.org/), as it's the easiest way to get a modern toolchain with a package manager to help with dependency management. This would allow you to follow the MSYS2 section below.
Otherwise you'll want to follow the "Other Distributions" section below.
We'll start by creating a simple project to build and run [hello.c](hello.c).
# MSYS2
Open the `MSYS2 UCRT64` prompt and then ensure you've installed the following packages. This will get you working toolchain, CMake, Ninja, and of course SDL3.
Things can get quite complicated with other distributions of MinGW. If you can't follow [the cmake intro](INTRO-cmake.md), perhaps due to issues getting cmake to understand your toolchain, this section should work.
## Acquire SDL
Download the `SDL3-devel-<version>-mingw.zip` asset from [the latest release.](https://github.com/libsdl-org/SDL/releases/latest) Then extract it inside your project folder such that the output of `ls SDL3-<version>` looks like `INSTALL.md LICENSE.txt Makefile README.md cmake i686-w64-mingw32 x86_64-w64-mingw32`.
## Know your Target Architecture
It is not uncommon for folks to not realize their distribution is targeting 32bit Windows despite things like the name of the toolchain, or the fact that they're running on a 64bit system. We'll ensure we know up front what we need:
Create a file named `arch.c` with the following contents:
This should print out which library directory we'll need to use when compiling, keep this value in mind, you'll need to use it when compiling in the next section as `<arch>`. If you get "Unknown Architecture" please [report a bug](https://github.com/libsdl-org/SDL/issues).
## Build and Run
Now we should have everything needed to compile and run our program. You'll need to ensure to replace `<version>` with the version of the release of SDL3 you downloaded, as well as use the `<arch>` we learned in the previous section.
@@ -5,10 +5,12 @@ The easiest way to use SDL is to include it as a subproject in your project.
We'll start by creating a simple project to build and run [hello.c](hello.c)
- Get a copy of the SDL source, you can clone the repo, or download the "Source Code" asset from [the latest release.](https://github.com/libsdl-org/SDL/releases/latest)
- If you've downloaded a release, make sure to extract the contents somewhere you can find it.
- Create a new project in Visual Studio, using the C++ Empty Project template
- Add hello.c to the Source Files
- Right click the solution, select add an existing project, navigate to VisualC/SDL and add SDL.vcxproj
- Select your main project and go to Project -> Add Reference and select SDL3
- Select your main project and go to Project -> Properties, set the filter at the top to "All Configurations" and "All Platforms", select VC++ Directories and add the SDL include directory to "Include Directories"
- Right click the solution, select add an existing project, navigate to `VisualC/SDL` from within the source you cloned or downloaded above and add SDL.vcxproj
- Select your main project and go to Project -> Add -> Reference and select SDL3
- Select your main project and go to Project -> Properties, set the filter at the top to "All Configurations" and "All Platforms", select C/C++ -> General and add the SDL include directory to "Additional Include Directories"
- Use [`CMAKE_EXE_LINKER_FLAGS`](https://cmake.org/cmake/help/latest/variable/CMAKE_EXE_LINKER_FLAGS.html) to pass extra option to the linker for executables.
- Use [`CMAKE_SHARED_LINKER_FLAGS`](https://cmake.org/cmake/help/latest/variable/CMAKE_SHARED_LINKER_FLAGS.html) to pass extra options to the linker for shared libraries.
#### Examples
#### Compile Options Examples
- build a SDL library optimized for (more) modern x64 microprocessor architectures.
@@ -240,7 +240,7 @@ Append with a version number to target a specific SDK revision: e.g. `iphoneos12
SDL 3.0 has new support for high DPI displays. Interfaces provided by SDL uses the platform's native coordinates unless otherwise specified.
To reconcile platform differences in their approach to high-density scaling, SDL provides the following interfaces:
-`SDL_GetWindowSize()` retrieves the window dimensions in native coordinates.
-`SDL_GetWindowSizeInPixels()` retrieves the window dimensions in pixels-addressable.
-`SDL_GetDisplayContentScale()` retrieves the suggested amplification factor when drawing in native coordinates.
-`SDL_GetWindowDisplayScale()` retrieves the suggested amplification factor when drawing in pixels-addressable.
-`SDL_GetWindowPixelDensity()` retrieves how many addressable pixels correspond to one unit of native coordinates.
-`SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED` is emitted when the value retrievable from `SDL_GetWindowSizeInPixels()` changes.
-`SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED` is emitted when the value retrievable from `SDL_GetWindowDisplayScale()` changes.
- Windows created with `SDL_WINDOW_HIGH_PIXEL_DENSITY` will ask the platform to display addressable pixels at their natural scale.
## Numeric example
Given a fullscreen window spanning a 3840x2160 monitor set to 2x display or 200% scaling, the following tabulates the effect of creating a window with or without `SDL_WINDOW_HIGH_PIXEL_DENSITY` on MacOS and Win32:
Observe the philosophical difference between the approaches taken by MacOS and Win32:
- Win32 coordinate system always deals in physical device pixels, high DPI support is achieved by providing an advisory hint for the developer to enlarge drawn objects. Ignoring the advisory scale factor results in graphics appearing tiny.
- MacOS coordinate system always deals in physical content sizes, high DPI support is achieved by providing an optional flag for the developer to request finer granularity. Omitting the granularity request results in graphics appearing coarse.
## Explanation
Displays now have a content display scale, which is the expected scale for content based on the DPI settings of the display. For example, a 4K display might have a 2.0 (200%) display scale, which means that the user expects UI elements to be twice as big on this display, to aid in readability. You can query the display content scale using `SDL_GetDisplayContentScale()`, and when this changes you get an `SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED` event.
@@ -34,3 +8,33 @@ Displays now have a content display scale, which is the expected scale for conte
The window size is now distinct from the window pixel size, and the ratio between the two is the window pixel density. If the window is created with the `SDL_WINDOW_HIGH_PIXEL_DENSITY` flag, SDL will try to match the native pixel density for the display, otherwise it will try to have the pixel size match the window size. You can query the window pixel density using `SDL_GetWindowPixelDensity()`. You can query the window pixel size using `SDL_GetWindowSizeInPixels()`, and when this changes you get an `SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED` event. You are guaranteed to get a `SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED` event when a window is created and resized, and you can use this event to create and resize your graphics context for the window.
The window has a display scale, which is the scale from the pixel resolution to the desired content size, e.g. the combination of the pixel density and the content scale. For example, a 3840x2160 window displayed at 200% on Windows, and a 1920x1080 window with the high density flag on a 2x display on macOS will both have a pixel size of 3840x2160 and a display scale of 2.0. You can query the window display scale using `SDL_GetWindowDisplayScale()`, and when this changes you get an `SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED` event.
## Numeric example
Given a window spanning a 3840x2160 monitor set to 2x display or 200% scaling, the following tabulates the effect of creating a window with or without `SDL_WINDOW_HIGH_PIXEL_DENSITY` on macOS and Windows:
| Value | macOS (Default) | macOS (HD) | Windows (Default & HD) |
Observe the difference between the approaches taken by macOS and Windows:
- The Windows and Android coordinate system always deals in physical device pixels, high DPI support is achieved by providing a content scale that tells the developer to draw objects larger. Ignoring this scale factor results in graphics appearing tiny.
- The macOS and iOS coordinate system always deals in window coordinates, high DPI support is achieved by providing an optional flag for the developer to request more pixels. Omitting this flag results in graphics having low detail.
- On Linux, X11 uses a similar approach to Windows and Wayland uses a similar approach to macOS.
## Solution
Proper high DPI support takes into account both the content scale and the pixel density.
First, you'd create your window with the `SDL_WINDOW_HIGH_PIXEL_DENSITY` flag, assuming you want the highest detail possible. Then you'd get the window display scale to see how much your UI elements should be enlarged to be readable.
If you're using the SDL 2D renderer, SDL provides the function `SDL_ConvertEventToRenderCoordinates()` to convert mouse coordinates between window coordinates and rendering coordinates, and the more general functions `SDL_RenderCoordinatesFromWindow()` and `SDL_RenderCoordinatesToWindow()` to do other conversion between them.
If you're not using the 2D renderer, you can implement this yourself using `SDL_GetWindowPixelDensity()` as scale factor to convert from window coordinates to pixels.
Finally you'll want to test on both Windows and macOS if possible to make sure your high DPI support works in all environments.
The recommended way to use SDL for iOS is by including the SDL3.xcframework which is now a build target of the SDL.xcodeproj file. An xcframework is a new (Xcode 11) uber-framework which can handle any combination of processor type and target OS platform.
You can either build the SDL3.xcframework yourself or download the latest release disk image asset (*.dmg).
In the past, iOS devices were always an ARM variant processor, and the simulator was always i386 or x86_64, and thus libraries could be combined into a single framework for both simulator and device. With the introduction of the Apple Silicon ARM-based machines, regular frameworks would collide as CPU type was no longer sufficient to differentiate the platform. So Apple created the new xcframework library package.
The xcframework target builds into a Products directory alongside the SDL.xcodeproj file, as SDL3.xcframework. This can be brought in to any iOS project and will function properly for both simulator and device, no matter their CPUs. Note that Intel Macs cannot cross-compile for Apple Silicon Macs. If you need AS compatibility, perform this build on an Apple Silicon Mac.
This target requires Xcode 11 or later. The target will simply fail to build if attempted on older Xcodes.
In addition, on Apple platforms, main() cannot be in a dynamically loaded library.
However, unlike in SDL2, in SDL3 SDL_main is implemented inline in SDL_main.h, so you don't need to link against a static libSDL3main.lib, and you don't need to copy a .c file from the SDL3 source either.
This means that iOS apps which used the statically-linked libSDL3.lib and now link with the xcframwork can just `#include <SDL3/SDL_main.h>` in the source file that contains their standard `int main(int argc, char *argv[])` function to get a header-only SDL_main implementation that calls the `SDL_RunApp()` with your standard main function.
To use the SDL3.xcframework follow these steps:
1. Run Xcode and create a new project using the iOS Game template, selecting the Objective C language and Metal game technology.
2. In the main view, delete all files except for Assets and LaunchScreen
3. Select the project in the main view, go to the "General" tab, scroll down to "Frameworks, Libraries, and Embedded Content", and drag and drop the SDL3.xcframework
4. Still in "Frameworks, Libraries, and Embedded Content", select "Embed & Sign" for the SDL3.xcframework.
5. Add the source files that you would normally have for an SDL program, making sure to have #include<SDL3/SDL_main.h> at the top of the file containing your main() function.
6. Add any assets that your application needs.
7. Enjoy!
Using an xcFramework is similar to using a regular framework. However, issues have been seen with the build system not seeing the headers in the xcFramework. To remedy this, add the path to the xcFramework in your app's target ==> Build Settings ==> Framework Search Paths and mark it recursive (this is critical). Also critical is to remove "*.framework" from Build Settings ==> Sub-Directories to Exclude in Recursive Searches. Clean the build folder, and on your next build the build system should be able to see any of these in your code, as expected:
#include "SDL3/SDL_main.h"
#include <SDL3/SDL.h>
#include <SDL3/SDL_main.h>
Using the Simple DirectMedia Layer for iOS by adding the SDL3 Xcode project
To maintain compatibility with older Xcode versions than version 11 you can add the SDL3 Xcode project file to your project:
1. Run Xcode and create a new project using the iOS Game template, selecting the Objective C language and Metal game technology.
2. In the main view, delete all files except for Assets and LaunchScreen
3. Right click the project in the main view, select "Add Files...", and add the SDL project, Xcode/SDL/SDL.xcodeproj
@@ -26,6 +61,18 @@ Using the Simple DirectMedia Layer for iOS
9. Add any assets that your application needs.
10. Enjoy!
Notes for distributing your iOS app on the AppStore when using the embedded SDL3 Xcode project:
Embedding the SDL3 Xcode project makes SDL3.framework a target of your app, so it will be included in the archive created during the "Archive" step required for App Store submission. As this prevents successful distribution, remove the framework via a script in the Build Phase after the "Embed & Sign" step.
1. Select the project in the main view, go to the "Build Phases" tab, click on the big '+' in this tab and click "New Run Script Phase".
2. Scroll down to "Run Script" (after the "Embed SDL3 Framework") and enter the following script:
```
if [ -d "$INSTALL_ROOT/Library" ]; then
echo "Removing SDL3.framework from INSTALL_ROOT for archiving"
rm -rf "$INSTALL_ROOT/Library"
fi
```
3. Below the script entry uncheck the "Run Script:" options "For install builds only" and "Based on dependency analysis"
TODO: Add information regarding App Store requirements such as icons, etc.
@@ -65,7 +112,7 @@ not give you any processing time after the events are delivered.
e.g.
int HandleAppEvents(void *userdata, SDL_Event *event)
The SDL.xcodeproj file now includes a target to build SDL3.xcframework. An xcframework is a new (Xcode 11) uber-framework which can handle any combination of processor type and target OS platform.
In the past, iOS devices were always an ARM variant processor, and the simulator was always i386 or x86_64, and thus libraries could be combined into a single framework for both simulator and device. With the introduction of the Apple Silicon ARM-based machines, regular frameworks would collide as CPU type was no longer sufficient to differentiate the platform. So Apple created the new xcframework library package.
The xcframework target builds into a Products directory alongside the SDL.xcodeproj file, as SDL3.xcframework. This can be brought in to any iOS project and will function properly for both simulator and device, no matter their CPUs. Note that Intel Macs cannot cross-compile for Apple Silicon Macs. If you need AS compatibility, perform this build on an Apple Silicon Mac.
This target requires Xcode 11 or later. The target will simply fail to build if attempted on older Xcodes.
In addition, on Apple platforms, main() cannot be in a dynamically loaded library.
However, unlike in SDL2, in SDL3 SDL_main is implemented inline in SDL_main.h, so you don't need to link against a static libSDL3main.lib, and you don't need to copy a .c file from the SDL3 source either.
This means that iOS apps which used the statically-linked libSDL3.lib and now link with the xcframwork can just `#include <SDL3/SDL_main.h>` in the source file that contains their standard `int main(int argc, char *argv[])` function to get a header-only SDL_main implementation that calls the `SDL_RunApp()` with your standard main function.
Using an xcFramework is similar to using a regular framework. However, issues have been seen with the build system not seeing the headers in the xcFramework. To remedy this, add the path to the xcFramework in your app's target ==> Build Settings ==> Framework Search Paths and mark it recursive (this is critical). Also critical is to remove "*.framework" from Build Settings ==> Sub-Directories to Exclude in Recursive Searches. Clean the build folder, and on your next build the build system should be able to see any of these in your code, as expected:
@@ -1459,7 +1459,7 @@ The following symbols have been removed:
* SDL_RENDERER_PRESENTVSYNC - replaced with SDL_PROP_RENDERER_CREATE_PRESENT_VSYNC_NUMBER during renderer creation and SDL_PROP_RENDERER_VSYNC_NUMBER after renderer creation
* SDL_RENDERER_SOFTWARE - you can check whether the name of the renderer is `SDL_SOFTWARE_RENDERER`
* SDL_RENDERER_TARGETTEXTURE - all renderers support target texture functionality
* SDL_ScaleModeBest = use SDL_SCALEMODE_LINEAR instead
* SDL_ScaleModeBest - use SDL_SCALEMODE_LINEAR instead
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.