Debian Codegraph @

extern/imgui_patched/backends/imgui_impl_sdl2.cpp

raw
1 // dear imgui: Platform Backend for SDL2
2 // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
3 // (Info: SDL2 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.)
4 // (Prefer SDL 2.0.5+ for full feature support.)
5
6 // Implemented features:
7 // [X] Platform: Clipboard support.
8 // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen.
9 // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
10 // [X] Platform: Gamepad support.
11 // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
12 // [X] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!.
13 // [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
14 // Missing features or Issues:
15 // [ ] Platform: Multi-viewport: Minimized windows seems to break mouse wheel events (at least under Windows).
16 // [ ] Platform: Multi-viewport: ParentViewportID not honored, and so io.ConfigViewportsNoDefaultParent has no effect (minor).
17
18 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
19 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
20 // Learn about Dear ImGui:
21 // - FAQ https://dearimgui.com/faq
22 // - Getting Started https://dearimgui.com/getting-started
23 // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
24 // - Introduction, links and more at the top of imgui.cpp
25
26 // CHANGELOG
27 // (minor and older changes stripped away, please see git history for details)
28 // 2025-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
29 // 2025-07-08: Made ImGui_ImplSDL2_GetContentScaleForWindow(), ImGui_ImplSDL2_GetContentScaleForDisplay() helpers return 1.0f on Emscripten and Android platforms, matching macOS logic. (#8742, #8733)
30 // 2025-06-11: Added ImGui_ImplSDL2_GetContentScaleForWindow(SDL_Window* window) and ImGui_ImplSDL2_GetContentScaleForDisplay(int display_index) helper to facilitate making DPI-aware apps.
31 // 2025-05-15: [Docking] Add Platform_GetWindowFramebufferScale() handler, to allow varying Retina display density on multiple monitors.
32 // 2025-04-09: [Docking] Revert update monitors and work areas information every frame. Only do it on Windows. (#8415, #8558)
33 // 2025-04-09: Don't attempt to call SDL_CaptureMouse() on drivers where we don't call SDL_GetGlobalMouseState(). (#8561)
34 // 2025-03-21: Fill gamepad inputs and set ImGuiBackendFlags_HasGamepad regardless of ImGuiConfigFlags_NavEnableGamepad being set.
35 // 2025-03-10: When dealing with OEM keys, use scancodes instead of translated keycodes to choose ImGuiKey values. (#7136, #7201, #7206, #7306, #7670, #7672, #8468)
36 // 2025-02-26: Only start SDL_CaptureMouse() when mouse is being dragged, to mitigate issues with e.g.Linux debuggers not claiming capture back. (#6410, #3650)
37 // 2025-02-25: [Docking] Revert to use SDL_GetDisplayBounds() for WorkPos/WorkRect if SDL_GetDisplayUsableBounds() failed.
38 // 2025-02-24: Avoid calling SDL_GetGlobalMouseState() when mouse is in relative mode.
39 // 2025-02-21: [Docking] Update monitors and work areas information every frame, as the later may change regardless of monitor changes. (#8415)
40 // 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support.
41 // 2025-02-10: Using SDL_OpenURL() in platform_io.Platform_OpenInShellFn handler.
42 // 2025-01-20: Made ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode_Manual) accept an empty array.
43 // 2024-10-24: Emscripten: from SDL 2.30.9, SDL_EVENT_MOUSE_WHEEL event doesn't require dividing by 100.0f.
44 // 2024-09-09: use SDL_Vulkan_GetDrawableSize() when available. (#7967, #3190)
45 // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO:
46 // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn
47 // - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn
48 // - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn
49 // - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn
50 // 2024-08-19: Storing SDL's Uint32 WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*.
51 // 2024-08-19: ImGui_ImplSDL2_ProcessEvent() now ignores events intended for other SDL windows. (#7853)
52 // 2024-07-02: Emscripten: Added io.PlatformOpenInShellFn() handler for Emscripten versions.
53 // 2024-07-02: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() renaming in main library.
54 // 2024-02-14: Inputs: Handle gamepad disconnection. Added ImGui_ImplSDL2_SetGamepadMode().
55 // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys.
56 // 2023-04-06: Inputs: Avoid calling SDL_StartTextInput()/SDL_StopTextInput() as they don't only pertain to IME. It's unclear exactly what their relation is to IME. (#6306)
57 // 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen. (#2702)
58 // 2023-02-23: Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. (#6189, #6114, #3644)
59 // 2023-02-07: Implement IME handler (io.SetPlatformImeDataFn will call SDL_SetTextInputRect()/SDL_StartTextInput()).
60 // 2023-02-07: *BREAKING CHANGE* Renamed this backend file from imgui_impl_sdl.cpp/.h to imgui_impl_sdl2.cpp/.h in prevision for the future release of SDL3.
61 // 2023-02-02: Avoid calling SDL_SetCursor() when cursor has not changed, as the function is surprisingly costly on Mac with latest SDL (may be fixed in next SDL version).
62 // 2023-02-02: Added support for SDL 2.0.18+ preciseX/preciseY mouse wheel data for smooth scrolling + Scaling X value on Emscripten (bug?). (#4019, #6096)
63 // 2023-02-02: Removed SDL_MOUSEWHEEL value clamping, as values seem correct in latest Emscripten. (#4019)
64 // 2023-02-01: Flipping SDL_MOUSEWHEEL 'wheel.x' value to match other backends and offer consistent horizontal scrolling direction. (#4019, #6096, #1463)
65 // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
66 // 2022-09-26: Inputs: Disable SDL 2.0.22 new "auto capture" (SDL_HINT_MOUSE_AUTO_CAPTURE) which prevents drag and drop across windows for multi-viewport support + don't capture when drag and dropping. (#5710)
67 // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported).
68 // 2022-03-22: Inputs: Fix mouse position issues when dragging outside of boundaries. SDL_CaptureMouse() erroneously still gives out LEAVE events when hovering OS decorations.
69 // 2022-03-22: Inputs: Added support for extra mouse buttons (SDL_BUTTON_X1/SDL_BUTTON_X2).
70 // 2022-02-04: Added SDL_Renderer* parameter to ImGui_ImplSDL2_InitForSDLRenderer(), so we can use SDL_GetRendererOutputSize() instead of SDL_GL_GetDrawableSize() when bound to a SDL_Renderer.
71 // 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion.
72 // 2021-01-20: Inputs: calling new io.AddKeyAnalogEvent() for gamepad support, instead of writing directly to io.NavInputs[].
73 // 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+).
74 // 2022-01-17: Inputs: always update key mods next and before key event (not in NewFrame) to fix input queue with very low framerates.
75 // 2022-01-12: Update mouse inputs using SDL_MOUSEMOTION/SDL_WINDOWEVENT_LEAVE + fallback to provide it when focused but not hovered/captured. More standard and will allow us to pass it to future input queue API.
76 // 2022-01-12: Maintain our own copy of MouseButtonsDown mask instead of using ImGui::IsAnyMouseDown() which will be obsoleted.
77 // 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range.
78 // 2021-08-17: Calling io.AddFocusEvent() on SDL_WINDOWEVENT_FOCUS_GAINED/SDL_WINDOWEVENT_FOCUS_LOST.
79 // 2021-07-29: Inputs: MousePos is correctly reported when the host platform window is hovered but not focused (using SDL_GetMouseFocus() + SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, requires SDL 2.0.5+)
80 // 2021-06:29: *BREAKING CHANGE* Removed 'SDL_Window* window' parameter to ImGui_ImplSDL2_NewFrame() which was unnecessary.
81 // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
82 // 2021-03-22: Rework global mouse pos availability check listing supported platforms explicitly, effectively fixing mouse access on Raspberry Pi. (#2837, #3950)
83 // 2020-05-25: Misc: Report a zero display-size when window is minimized, to be consistent with other backends.
84 // 2020-02-20: Inputs: Fixed mapping for ImGuiKey_KeyPadEnter (using SDL_SCANCODE_KP_ENTER instead of SDL_SCANCODE_RETURN2).
85 // 2019-12-17: Inputs: On Wayland, use SDL_GetMouseState (because there is no global mouse state).
86 // 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor.
87 // 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter.
88 // 2019-04-23: Inputs: Added support for SDL_GameController (if ImGuiConfigFlags_NavEnableGamepad is set by user application).
89 // 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized.
90 // 2018-12-21: Inputs: Workaround for Android/iOS which don't seem to handle focus related calls.
91 // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
92 // 2018-11-14: Changed the signature of ImGui_ImplSDL2_ProcessEvent() to take a 'const SDL_Event*'.
93 // 2018-08-01: Inputs: Workaround for Emscripten which doesn't seem to handle focus related calls.
94 // 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor.
95 // 2018-06-08: Misc: Extracted imgui_impl_sdl.cpp/.h away from the old combined SDL2+OpenGL/Vulkan examples.
96 // 2018-06-08: Misc: ImGui_ImplSDL2_InitForOpenGL() now takes a SDL_GLContext parameter.
97 // 2018-05-09: Misc: Fixed clipboard paste memory leak (we didn't call SDL_FreeMemory on the data returned by SDL_GetClipboardText).
98 // 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag.
99 // 2018-02-16: Inputs: Added support for mouse cursors, honoring ImGui::GetMouseCursor() value.
100 // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
101 // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
102 // 2018-02-05: Misc: Using SDL_GetPerformanceCounter() instead of SDL_GetTicks() to be able to handle very high framerate (1000+ FPS).
103 // 2018-02-05: Inputs: Keyboard mapping is using scancodes everywhere instead of a confusing mixture of keycodes and scancodes.
104 // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
105 // 2018-01-19: Inputs: When available (SDL 2.0.4+) using SDL_CaptureMouse() to retrieve coordinates outside of client area when dragging. Otherwise (SDL 2.0.3 and before) testing for SDL_WINDOW_INPUT_FOCUS instead of SDL_WINDOW_MOUSE_FOCUS.
106 // 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert.
107 // 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1).
108 // 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers.
109
110 #include "imgui.h"
111 #ifndef IMGUI_DISABLE
112 #include "imgui_impl_sdl2.h"
113 #include <stdio.h>
114 #include <cmath>
115
116 // Clang warnings with -Weverything
117 #if defined(__clang__)
118 #pragma clang diagnostic push
119 #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast
120 #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
121 #endif
122
123 // SDL
124 // (the multi-viewports feature requires SDL features supported from SDL 2.0.4+. SDL 2.0.5+ is highly recommended)
125 #include <SDL.h>
126 #include <SDL_syswm.h>
127 #include <stdio.h> // for snprintf()
128 #ifdef __APPLE__
129 #include <TargetConditionals.h>
130 extern "C" {
131 #include "../../src/gui/macstuff.h"
132 }
133 #endif
134 #ifdef __EMSCRIPTEN__
135 #include <emscripten/em_js.h>
136 #endif
137 #undef Status // X11 headers are leaking this.
138
139 #if SDL_VERSION_ATLEAST(2,0,4) && !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS) && !defined(__amigaos4__)
140 #define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 1
141 #else
142 #define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 0
143 #endif
144 #define SDL_HAS_WINDOW_ALPHA SDL_VERSION_ATLEAST(2,0,5)
145 #define SDL_HAS_ALWAYS_ON_TOP SDL_VERSION_ATLEAST(2,0,5)
146 #define SDL_HAS_USABLE_DISPLAY_BOUNDS SDL_VERSION_ATLEAST(2,0,5)
147 #define SDL_HAS_PER_MONITOR_DPI SDL_VERSION_ATLEAST(2,0,4)
148 #define SDL_HAS_VULKAN SDL_VERSION_ATLEAST(2,0,6)
149 #define SDL_HAS_DISPLAY_EVENT SDL_VERSION_ATLEAST(2,0,9)
150 #define SDL_HAS_OPEN_URL SDL_VERSION_ATLEAST(2,0,14)
151 #define SDL_HAS_SHOW_WINDOW_ACTIVATION_HINT SDL_VERSION_ATLEAST(2,0,18)
152 #if SDL_HAS_VULKAN
153 #include <SDL_vulkan.h>
154 #else
155 static const Uint32 SDL_WINDOW_VULKAN = 0x10000000;
156 #endif
157
158 // SDL Data
159 struct ImGui_ImplSDL2_Data
160 {
161 SDL_Window* Window;
162 Uint32 WindowID; // Stored in ImGuiViewport::PlatformHandle. Use SDL_GetWindowFromID() to get SDL_Window* from Uint32 WindowID.
163 SDL_Renderer* Renderer;
164 Uint64 Time;
165 char* ClipboardTextData;
166 char BackendPlatformName[48];
167 bool UseVulkan;
168 bool WantUpdateMonitors;
169
170 // Mouse handling
171 Uint32 MouseWindowID;
172 int MouseButtonsDown;
173 SDL_Cursor* MouseCursors[ImGuiMouseCursor_COUNT];
174 SDL_Cursor* MouseLastCursor;
175 int MouseLastLeaveFrame;
176 bool MouseCanUseGlobalState;
177 bool MouseCanUseCapture;
178 bool MouseCanReportHoveredViewport; // This is hard to use/unreliable on SDL so we'll set ImGuiBackendFlags_HasMouseHoveredViewport dynamically based on state.
179
180 // Gamepad handling
181 ImVector<SDL_GameController*> Gamepads;
182 ImGui_ImplSDL2_GamepadMode GamepadMode;
183 bool WantUpdateGamepadsList;
184
185 ImGui_ImplSDL2_Data() { memset((void*)this, 0, sizeof(*this)); }
186 };
187
188 // Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts
189 // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
190 // FIXME: multi-context support is not well tested and probably dysfunctional in this backend.
191 // FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context.
192 static ImGui_ImplSDL2_Data* ImGui_ImplSDL2_GetBackendData()
193 {
194 return ImGui::GetCurrentContext() ? (ImGui_ImplSDL2_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr;
195 }
196
197 // Forward Declarations
198 static void ImGui_ImplSDL2_UpdateMonitors();
199 static void ImGui_ImplSDL2_InitMultiViewportSupport(SDL_Window* window, void* sdl_gl_context);
200 static void ImGui_ImplSDL2_ShutdownMultiViewportSupport();
201
202 // Functions
203 static const char* ImGui_ImplSDL2_GetClipboardText(ImGuiContext*)
204 {
205 ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
206 if (bd->ClipboardTextData)
207 SDL_free(bd->ClipboardTextData);
208 bd->ClipboardTextData = SDL_GetClipboardText();
209 return bd->ClipboardTextData;
210 }
211
212 static void ImGui_ImplSDL2_SetClipboardText(ImGuiContext*, const char* text)
213 {
214 SDL_SetClipboardText(text);
215 }
216
217 // Note: native IME will only display if user calls SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1") _before_ SDL_CreateWindow().
218 static void ImGui_ImplSDL2_PlatformSetImeData(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data)
219 {
220 if (data->WantVisible)
221 {
222 SDL_Rect r;
223 r.x = (int)(data->InputPos.x - viewport->Pos.x);
224 r.y = (int)(data->InputPos.y - viewport->Pos.y + data->InputLineHeight);
225 r.w = 1;
226 r.h = (int)data->InputLineHeight;
227 SDL_SetTextInputRect(&r);
228 }
229 }
230
231 // Not static to allow third-party code to use that if they want to (but undocumented)
232 ImGuiKey ImGui_ImplSDL2_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode);
233 ImGuiKey ImGui_ImplSDL2_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode)
234 {
235 switch (keycode)
236 {
237 case SDLK_TAB: return ImGuiKey_Tab;
238 case SDLK_LEFT: return ImGuiKey_LeftArrow;
239 case SDLK_RIGHT: return ImGuiKey_RightArrow;
240 case SDLK_UP: return ImGuiKey_UpArrow;
241 case SDLK_DOWN: return ImGuiKey_DownArrow;
242 case SDLK_PAGEUP: return ImGuiKey_PageUp;
243 case SDLK_PAGEDOWN: return ImGuiKey_PageDown;
244 case SDLK_HOME: return ImGuiKey_Home;
245 case SDLK_END: return ImGuiKey_End;
246 case SDLK_INSERT: return ImGuiKey_Insert;
247 case SDLK_DELETE: return ImGuiKey_Delete;
248 case SDLK_BACKSPACE: return ImGuiKey_Backspace;
249 case SDLK_SPACE: return ImGuiKey_Space;
250 case SDLK_RETURN: return ImGuiKey_Enter;
251 case SDLK_ESCAPE: return ImGuiKey_Escape;
252 //case SDLK_QUOTE: return ImGuiKey_Apostrophe;
253 case SDLK_COMMA: return ImGuiKey_Comma;
254 //case SDLK_MINUS: return ImGuiKey_Minus;
255 case SDLK_PERIOD: return ImGuiKey_Period;
256 //case SDLK_SLASH: return ImGuiKey_Slash;
257 case SDLK_SEMICOLON: return ImGuiKey_Semicolon;
258 //case SDLK_EQUALS: return ImGuiKey_Equal;
259 //case SDLK_LEFTBRACKET: return ImGuiKey_LeftBracket;
260 //case SDLK_BACKSLASH: return ImGuiKey_Backslash;
261 //case SDLK_RIGHTBRACKET: return ImGuiKey_RightBracket;
262 //case SDLK_BACKQUOTE: return ImGuiKey_GraveAccent;
263 case SDLK_CAPSLOCK: return ImGuiKey_CapsLock;
264 case SDLK_SCROLLLOCK: return ImGuiKey_ScrollLock;
265 case SDLK_NUMLOCKCLEAR: return ImGuiKey_NumLock;
266 case SDLK_PRINTSCREEN: return ImGuiKey_PrintScreen;
267 case SDLK_PAUSE: return ImGuiKey_Pause;
268 case SDLK_KP_0: return ImGuiKey_Keypad0;
269 case SDLK_KP_1: return ImGuiKey_Keypad1;
270 case SDLK_KP_2: return ImGuiKey_Keypad2;
271 case SDLK_KP_3: return ImGuiKey_Keypad3;
272 case SDLK_KP_4: return ImGuiKey_Keypad4;
273 case SDLK_KP_5: return ImGuiKey_Keypad5;
274 case SDLK_KP_6: return ImGuiKey_Keypad6;
275 case SDLK_KP_7: return ImGuiKey_Keypad7;
276 case SDLK_KP_8: return ImGuiKey_Keypad8;
277 case SDLK_KP_9: return ImGuiKey_Keypad9;
278 case SDLK_KP_PERIOD: return ImGuiKey_KeypadDecimal;
279 case SDLK_KP_DIVIDE: return ImGuiKey_KeypadDivide;
280 case SDLK_KP_MULTIPLY: return ImGuiKey_KeypadMultiply;
281 case SDLK_KP_MINUS: return ImGuiKey_KeypadSubtract;
282 case SDLK_KP_PLUS: return ImGuiKey_KeypadAdd;
283 case SDLK_KP_ENTER: return ImGuiKey_KeypadEnter;
284 case SDLK_KP_EQUALS: return ImGuiKey_KeypadEqual;
285 case SDLK_LCTRL: return ImGuiKey_LeftCtrl;
286 case SDLK_LSHIFT: return ImGuiKey_LeftShift;
287 case SDLK_LALT: return ImGuiKey_LeftAlt;
288 case SDLK_LGUI: return ImGuiKey_LeftSuper;
289 case SDLK_RCTRL: return ImGuiKey_RightCtrl;
290 case SDLK_RSHIFT: return ImGuiKey_RightShift;
291 case SDLK_RALT: return ImGuiKey_RightAlt;
292 case SDLK_RGUI: return ImGuiKey_RightSuper;
293 case SDLK_APPLICATION: return ImGuiKey_Menu;
294 case SDLK_0: return ImGuiKey_0;
295 case SDLK_1: return ImGuiKey_1;
296 case SDLK_2: return ImGuiKey_2;
297 case SDLK_3: return ImGuiKey_3;
298 case SDLK_4: return ImGuiKey_4;
299 case SDLK_5: return ImGuiKey_5;
300 case SDLK_6: return ImGuiKey_6;
301 case SDLK_7: return ImGuiKey_7;
302 case SDLK_8: return ImGuiKey_8;
303 case SDLK_9: return ImGuiKey_9;
304 case SDLK_a: return ImGuiKey_A;
305 case SDLK_b: return ImGuiKey_B;
306 case SDLK_c: return ImGuiKey_C;
307 case SDLK_d: return ImGuiKey_D;
308 case SDLK_e: return ImGuiKey_E;
309 case SDLK_f: return ImGuiKey_F;
310 case SDLK_g: return ImGuiKey_G;
311 case SDLK_h: return ImGuiKey_H;
312 case SDLK_i: return ImGuiKey_I;
313 case SDLK_j: return ImGuiKey_J;
314 case SDLK_k: return ImGuiKey_K;
315 case SDLK_l: return ImGuiKey_L;
316 case SDLK_m: return ImGuiKey_M;
317 case SDLK_n: return ImGuiKey_N;
318 case SDLK_o: return ImGuiKey_O;
319 case SDLK_p: return ImGuiKey_P;
320 case SDLK_q: return ImGuiKey_Q;
321 case SDLK_r: return ImGuiKey_R;
322 case SDLK_s: return ImGuiKey_S;
323 case SDLK_t: return ImGuiKey_T;
324 case SDLK_u: return ImGuiKey_U;
325 case SDLK_v: return ImGuiKey_V;
326 case SDLK_w: return ImGuiKey_W;
327 case SDLK_x: return ImGuiKey_X;
328 case SDLK_y: return ImGuiKey_Y;
329 case SDLK_z: return ImGuiKey_Z;
330 case SDLK_F1: return ImGuiKey_F1;
331 case SDLK_F2: return ImGuiKey_F2;
332 case SDLK_F3: return ImGuiKey_F3;
333 case SDLK_F4: return ImGuiKey_F4;
334 case SDLK_F5: return ImGuiKey_F5;
335 case SDLK_F6: return ImGuiKey_F6;
336 case SDLK_F7: return ImGuiKey_F7;
337 case SDLK_F8: return ImGuiKey_F8;
338 case SDLK_F9: return ImGuiKey_F9;
339 case SDLK_F10: return ImGuiKey_F10;
340 case SDLK_F11: return ImGuiKey_F11;
341 case SDLK_F12: return ImGuiKey_F12;
342 case SDLK_F13: return ImGuiKey_F13;
343 case SDLK_F14: return ImGuiKey_F14;
344 case SDLK_F15: return ImGuiKey_F15;
345 case SDLK_F16: return ImGuiKey_F16;
346 case SDLK_F17: return ImGuiKey_F17;
347 case SDLK_F18: return ImGuiKey_F18;
348 case SDLK_F19: return ImGuiKey_F19;
349 case SDLK_F20: return ImGuiKey_F20;
350 case SDLK_F21: return ImGuiKey_F21;
351 case SDLK_F22: return ImGuiKey_F22;
352 case SDLK_F23: return ImGuiKey_F23;
353 case SDLK_F24: return ImGuiKey_F24;
354 case SDLK_AC_BACK: return ImGuiKey_AppBack;
355 case SDLK_AC_FORWARD: return ImGuiKey_AppForward;
356 default: break;
357 }
358
359 // Fallback to scancode
360 switch (scancode)
361 {
362 case SDL_SCANCODE_GRAVE: return ImGuiKey_GraveAccent;
363 case SDL_SCANCODE_MINUS: return ImGuiKey_Minus;
364 case SDL_SCANCODE_EQUALS: return ImGuiKey_Equal;
365 case SDL_SCANCODE_LEFTBRACKET: return ImGuiKey_LeftBracket;
366 case SDL_SCANCODE_RIGHTBRACKET: return ImGuiKey_RightBracket;
367 case SDL_SCANCODE_NONUSBACKSLASH: return ImGuiKey_Oem102;
368 case SDL_SCANCODE_BACKSLASH: return ImGuiKey_Backslash;
369 case SDL_SCANCODE_SEMICOLON: return ImGuiKey_Semicolon;
370 case SDL_SCANCODE_APOSTROPHE: return ImGuiKey_Apostrophe;
371 case SDL_SCANCODE_COMMA: return ImGuiKey_Comma;
372 case SDL_SCANCODE_PERIOD: return ImGuiKey_Period;
373 case SDL_SCANCODE_SLASH: return ImGuiKey_Slash;
374 default: break;
375 }
376 return ImGuiKey_None;
377 }
378
379 static void ImGui_ImplSDL2_UpdateKeyModifiers(SDL_Keymod sdl_key_mods)
380 {
381 ImGuiIO& io = ImGui::GetIO();
382 io.AddKeyEvent(ImGuiMod_Ctrl, (sdl_key_mods & KMOD_CTRL) != 0);
383 io.AddKeyEvent(ImGuiMod_Shift, (sdl_key_mods & KMOD_SHIFT) != 0);
384 io.AddKeyEvent(ImGuiMod_Alt, (sdl_key_mods & KMOD_ALT) != 0);
385 io.AddKeyEvent(ImGuiMod_Super, (sdl_key_mods & KMOD_GUI) != 0);
386 }
387
388 static ImGuiViewport* ImGui_ImplSDL2_GetViewportForWindowID(Uint32 window_id)
389 {
390 return ImGui::FindViewportByPlatformHandle((void*)(intptr_t)window_id);
391 }
392
393 // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
394 // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
395 // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
396 // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
397 bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
398 {
399 ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
400 IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL2_Init()?");
401 ImGuiIO& io = ImGui::GetIO();
402
403 switch (event->type)
404 {
405 case SDL_MOUSEMOTION:
406 {
407 if (ImGui_ImplSDL2_GetViewportForWindowID(event->motion.windowID) == nullptr)
408 return false;
409 ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y);
410 if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
411 {
412 int window_x, window_y;
413 SDL_GetWindowPosition(SDL_GetWindowFromID(event->motion.windowID), &window_x, &window_y);
414 mouse_pos.x += window_x;
415 mouse_pos.y += window_y;
416 }
417 // Fix for high DPI mac/idevice/wayland
418 mouse_pos.x *= io.InputScale;
419 mouse_pos.y *= io.InputScale;
420 io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
421 io.AddMousePosEvent(mouse_pos.x, mouse_pos.y);
422 return true;
423 }
424 case SDL_MOUSEWHEEL:
425 {
426 if (ImGui_ImplSDL2_GetViewportForWindowID(event->wheel.windowID) == nullptr)
427 return false;
428 //IMGUI_DEBUG_LOG("wheel %.2f %.2f, precise %.2f %.2f\n", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY);
429 #if SDL_VERSION_ATLEAST(2,0,18) // If this fails to compile on Emscripten: update to latest Emscripten!
430 float wheel_x = -event->wheel.preciseX;
431 float wheel_y = event->wheel.preciseY;
432 #else
433 float wheel_x = -(float)event->wheel.x;
434 float wheel_y = (float)event->wheel.y;
435 #endif
436 #if defined(__EMSCRIPTEN__) && !SDL_VERSION_ATLEAST(2,31,0)
437 wheel_x /= 100.0f;
438 #endif
439 #ifdef __APPLE__
440 wheel_x = -wheel_x;
441 #endif
442 io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
443 io.AddMouseWheelEvent(wheel_x, wheel_y);
444 return true;
445 }
446 case SDL_MOUSEBUTTONDOWN:
447 case SDL_MOUSEBUTTONUP:
448 {
449 if (ImGui_ImplSDL2_GetViewportForWindowID(event->button.windowID) == nullptr)
450 return false;
451 int mouse_button = -1;
452 if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; }
453 if (event->button.button == SDL_BUTTON_RIGHT) { mouse_button = 1; }
454 if (event->button.button == SDL_BUTTON_MIDDLE) { mouse_button = 2; }
455 if (event->button.button == SDL_BUTTON_X1) { mouse_button = 3; }
456 if (event->button.button == SDL_BUTTON_X2) { mouse_button = 4; }
457 if (mouse_button == -1)
458 break;
459 io.AddMouseSourceEvent(event->button.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
460 io.AddMouseButtonEvent(mouse_button, (event->type == SDL_MOUSEBUTTONDOWN));
461 bd->MouseButtonsDown = (event->type == SDL_MOUSEBUTTONDOWN) ? (bd->MouseButtonsDown | (1 << mouse_button)) : (bd->MouseButtonsDown & ~(1 << mouse_button));
462 return true;
463 }
464 case SDL_TEXTINPUT:
465 {
466 if (ImGui_ImplSDL2_GetViewportForWindowID(event->text.windowID) == nullptr)
467 return false;
468 io.AddInputCharactersUTF8(event->text.text);
469 return true;
470 }
471 case SDL_KEYDOWN:
472 case SDL_KEYUP:
473 {
474 ImGuiViewport* viewport = ImGui_ImplSDL2_GetViewportForWindowID(event->key.windowID);
475 if (viewport == nullptr)
476 return false;
477 //IMGUI_DEBUG_LOG("SDL_KEY%s : key=0x%08X ('%s'), scancode=%d ('%s'), mod=%X, windowID=%d, viewport=%08X\n",
478 // (event->type == SDL_KEYDOWN) ? "DOWN" : "UP ", event->key.keysym.sym, SDL_GetKeyName(event->key.keysym.sym), event->key.keysym.scancode, SDL_GetScancodeName(event->key.keysym.scancode), event->key.keysym.mod, event->key.windowID, viewport ? viewport->ID : 0);
479 ImGui_ImplSDL2_UpdateKeyModifiers((SDL_Keymod)event->key.keysym.mod);
480 ImGuiKey key = ImGui_ImplSDL2_KeyEventToImGuiKey(event->key.keysym.sym, event->key.keysym.scancode);
481 io.AddKeyEvent(key, (event->type == SDL_KEYDOWN));
482 io.SetKeyEventNativeData(key, (int)event->key.keysym.sym, (int)event->key.keysym.scancode, (int)event->key.keysym.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions.
483 return true;
484 }
485 #if SDL_HAS_DISPLAY_EVENT
486 case SDL_DISPLAYEVENT:
487 {
488 // 2.0.26 has SDL_DISPLAYEVENT_CONNECTED/SDL_DISPLAYEVENT_DISCONNECTED/SDL_DISPLAYEVENT_ORIENTATION,
489 // so change of DPI/Scaling are not reflected in this event. (SDL3 has it)
490 bd->WantUpdateMonitors = true;
491 return true;
492 }
493 #endif
494 case SDL_WINDOWEVENT:
495 {
496 ImGuiViewport* viewport = ImGui_ImplSDL2_GetViewportForWindowID(event->window.windowID);
497 if (viewport == NULL)
498 return false;
499
500 // - When capturing mouse, SDL will send a bunch of conflicting LEAVE/ENTER event on every mouse move, but the final ENTER tends to be right.
501 // - However we won't get a correct LEAVE event for a captured window.
502 // - In some cases, when detaching a window from main viewport SDL may send SDL_WINDOWEVENT_ENTER one frame too late,
503 // causing SDL_WINDOWEVENT_LEAVE on previous frame to interrupt drag operation by clear mouse position. This is why
504 // we delay process the SDL_WINDOWEVENT_LEAVE events by one frame. See issue #5012 for details.
505 Uint8 window_event = event->window.event;
506 if (window_event == SDL_WINDOWEVENT_ENTER)
507 {
508 bd->MouseWindowID = event->window.windowID;
509 bd->MouseLastLeaveFrame = 0;
510 }
511 if (window_event == SDL_WINDOWEVENT_LEAVE)
512 bd->MouseLastLeaveFrame = ImGui::GetFrameCount() + 1;
513 //if (window_event == SDL_WINDOWEVENT_FOCUS_GAINED) { IMGUI_DEBUG_LOG("SDL_WINDOWEVENT_FOCUS_GAINED: windowId %d, viewport: %08X\n", event->window.windowID, viewport ? viewport->ID : 0); }
514 //if (window_event == SDL_WINDOWEVENT_FOCUS_LOST) { IMGUI_DEBUG_LOG("SDL_WINDOWEVENT_FOCUS_LOST: windowId %d, viewport: %08X\n", event->window.windowID, viewport ? viewport->ID : 0); }
515 if (window_event == SDL_WINDOWEVENT_FOCUS_GAINED)
516 io.AddFocusEvent(true);
517 if (window_event == SDL_WINDOWEVENT_FOCUS_LOST)
518 io.AddFocusEvent(false);
519 if (window_event == SDL_WINDOWEVENT_CLOSE)
520 viewport->PlatformRequestClose = true;
521 if (window_event == SDL_WINDOWEVENT_MOVED)
522 viewport->PlatformRequestMove = true;
523 if (window_event == SDL_WINDOWEVENT_RESIZED)
524 viewport->PlatformRequestResize = true;
525 return true;
526 }
527 case SDL_CONTROLLERDEVICEADDED:
528 case SDL_CONTROLLERDEVICEREMOVED:
529 {
530 bd->WantUpdateGamepadsList = true;
531 return true;
532 }
533 default:
534 break;
535 }
536 return false;
537 }
538
539 #ifdef __EMSCRIPTEN__
540 EM_JS(void, ImGui_ImplSDL2_EmscriptenOpenURL, (char const* url), { url = url ? UTF8ToString(url) : null; if (url) window.open(url, '_blank'); });
541 #endif
542
543 static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void* sdl_gl_context)
544 {
545 ImGuiIO& io = ImGui::GetIO();
546 IMGUI_CHECKVERSION();
547 IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
548 //SDL_SetHint(SDL_HINT_EVENT_LOGGING, "2");
549
550 // Obtain compiled and runtime versions
551 SDL_version ver_compiled;
552 SDL_version ver_runtime;
553 SDL_VERSION(&ver_compiled);
554 SDL_GetVersion(&ver_runtime);
555
556 // Setup backend capabilities flags
557 ImGui_ImplSDL2_Data* bd = IM_NEW(ImGui_ImplSDL2_Data)();
558 snprintf(bd->BackendPlatformName, sizeof(bd->BackendPlatformName), "imgui_impl_sdl2 (%u.%u.%u, %u.%u.%u)",
559 ver_compiled.major, ver_compiled.minor, ver_compiled.patch, ver_runtime.major, ver_runtime.minor, ver_runtime.patch);
560 io.BackendPlatformUserData = (void*)bd;
561 io.BackendPlatformName = bd->BackendPlatformName;
562 io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
563 io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
564 // (ImGuiBackendFlags_PlatformHasViewports may be set just below)
565
566 bd->Window = window;
567 bd->WindowID = SDL_GetWindowID(window);
568 bd->Renderer = renderer;
569
570 // SDL on Linux/OSX doesn't report events for unfocused windows (see https://github.com/ocornut/imgui/issues/4960)
571 // We will use 'MouseCanReportHoveredViewport' to set 'ImGuiBackendFlags_HasMouseHoveredViewport' dynamically each frame.
572 #ifndef __APPLE__
573 bd->MouseCanReportHoveredViewport = bd->MouseCanUseGlobalState;
574 #else
575 bd->MouseCanReportHoveredViewport = false;
576 #endif
577
578 // Check and store if we are on a SDL backend that supports SDL_GetGlobalMouseState() and SDL_CaptureMouse()
579 // ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list)
580 bd->MouseCanUseGlobalState = false;
581 bd->MouseCanUseCapture = false;
582 #if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE
583 const char* sdl_backend = SDL_GetCurrentVideoDriver();
584 const char* capture_and_global_state_whitelist[] = { "windows", "cocoa", "x11", "DIVE", "VMAN" };
585 for (const char* item : capture_and_global_state_whitelist)
586 if (strncmp(sdl_backend, item, strlen(item)) == 0)
587 bd->MouseCanUseGlobalState = bd->MouseCanUseCapture = true;
588 #endif
589 if (bd->MouseCanUseGlobalState)
590 io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional)
591
592 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
593 platform_io.Platform_SetClipboardTextFn = ImGui_ImplSDL2_SetClipboardText;
594 platform_io.Platform_GetClipboardTextFn = ImGui_ImplSDL2_GetClipboardText;
595 platform_io.Platform_ClipboardUserData = nullptr;
596 platform_io.Platform_SetImeDataFn = ImGui_ImplSDL2_PlatformSetImeData;
597 #ifdef __EMSCRIPTEN__
598 platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplSDL2_EmscriptenOpenURL(url); return true; };
599 #elif SDL_HAS_OPEN_URL
600 platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { return SDL_OpenURL(url) == 0; };
601 #endif
602
603 // Update monitor a first time during init
604 ImGui_ImplSDL2_UpdateMonitors();
605
606 // Gamepad handling
607 bd->GamepadMode = ImGui_ImplSDL2_GamepadMode_AutoFirst;
608 bd->WantUpdateGamepadsList = true;
609
610 // Load mouse cursors
611 bd->MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW);
612 bd->MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM);
613 bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL);
614 bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS);
615 bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE);
616 bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENESW);
617 bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENWSE);
618 bd->MouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_HAND);
619 bd->MouseCursors[ImGuiMouseCursor_Wait] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_WAIT);
620 bd->MouseCursors[ImGuiMouseCursor_Progress] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_WAITARROW);
621 bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NO);
622
623 // Set platform dependent data in viewport
624 // Our mouse update function expect PlatformHandle to be filled for the main viewport
625 ImGuiViewport* main_viewport = ImGui::GetMainViewport();
626 main_viewport->PlatformHandle = (void*)(intptr_t)bd->WindowID;
627 main_viewport->PlatformHandleRaw = nullptr;
628 SDL_SysWMinfo info;
629 SDL_VERSION(&info.version);
630 if (SDL_GetWindowWMInfo(window, &info))
631 {
632 #if defined(SDL_VIDEO_DRIVER_WINDOWS)
633 main_viewport->PlatformHandleRaw = (void*)info.info.win.window;
634 #elif defined(__APPLE__) && defined(SDL_VIDEO_DRIVER_COCOA)
635 main_viewport->PlatformHandleRaw = (void*)info.info.cocoa.window;
636 #endif
637 }
638
639 // From 2.0.5: Set SDL hint to receive mouse click events on window focus, otherwise SDL doesn't emit the event.
640 // Without this, when clicking to gain focus, our widgets wouldn't activate even though they showed as hovered.
641 // (This is unfortunately a global SDL setting, so enabling it might have a side-effect on your application.
642 // It is unlikely to make a difference, but if your app absolutely needs to ignore the initial on-focus click:
643 // you can ignore SDL_MOUSEBUTTONDOWN events coming right after a SDL_WINDOWEVENT_FOCUS_GAINED)
644 #ifdef SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH
645 SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
646 #endif
647
648 // From 2.0.18: Enable native IME.
649 // IMPORTANT: This is used at the time of SDL_CreateWindow() so this will only affects secondary windows, if any.
650 // For the main window to be affected, your application needs to call this manually before calling SDL_CreateWindow().
651 #ifdef SDL_HINT_IME_SHOW_UI
652 SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");
653 #endif
654
655 // From 2.0.22: Disable auto-capture, this is preventing drag and drop across multiple windows (see #5710)
656 #ifdef SDL_HINT_MOUSE_AUTO_CAPTURE
657 SDL_SetHint(SDL_HINT_MOUSE_AUTO_CAPTURE, "0");
658 #endif
659
660 // We need SDL_CaptureMouse(), SDL_GetGlobalMouseState() from SDL 2.0.4+ to support multiple viewports.
661 // We left the call to ImGui_ImplSDL2_InitMultiViewportSupport() outside of #ifdef to avoid unused-function warnings.
662 if (io.BackendFlags & ImGuiBackendFlags_PlatformHasViewports)
663 ImGui_ImplSDL2_InitMultiViewportSupport(window, sdl_gl_context);
664
665 return true;
666 }
667
668 bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context)
669 {
670 return ImGui_ImplSDL2_Init(window, nullptr, sdl_gl_context);
671 }
672
673 bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window)
674 {
675 #if !SDL_HAS_VULKAN
676 IM_ASSERT(0 && "Unsupported");
677 #endif
678 if (!ImGui_ImplSDL2_Init(window, nullptr, nullptr))
679 return false;
680 ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
681 bd->UseVulkan = true;
682 return true;
683 }
684
685 bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window)
686 {
687 #if !defined(_WIN32)
688 IM_ASSERT(0 && "Unsupported");
689 #endif
690 return ImGui_ImplSDL2_Init(window, nullptr, nullptr);
691 }
692
693 bool ImGui_ImplSDL2_InitForMetal(SDL_Window* window)
694 {
695 return ImGui_ImplSDL2_Init(window, nullptr, nullptr);
696 }
697
698 bool ImGui_ImplSDL2_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer)
699 {
700 return ImGui_ImplSDL2_Init(window, renderer, nullptr);
701 }
702
703 bool ImGui_ImplSDL2_InitForOther(SDL_Window* window)
704 {
705 return ImGui_ImplSDL2_Init(window, nullptr, nullptr);
706 }
707
708 static void ImGui_ImplSDL2_CloseGamepads();
709
710 void ImGui_ImplSDL2_Shutdown()
711 {
712 ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
713 IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?");
714 ImGuiIO& io = ImGui::GetIO();
715
716 ImGui_ImplSDL2_ShutdownMultiViewportSupport();
717
718 if (bd->ClipboardTextData)
719 SDL_free(bd->ClipboardTextData);
720 for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
721 SDL_FreeCursor(bd->MouseCursors[cursor_n]);
722 ImGui_ImplSDL2_CloseGamepads();
723
724 io.BackendPlatformName = nullptr;
725 io.BackendPlatformUserData = nullptr;
726 io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad | ImGuiBackendFlags_PlatformHasViewports | ImGuiBackendFlags_HasMouseHoveredViewport);
727 IM_DELETE(bd);
728 }
729
730 // This code is incredibly messy because some of the functions we need for full viewport support are not available in SDL < 2.0.4.
731 static void ImGui_ImplSDL2_UpdateMouseData()
732 {
733 ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
734 ImGuiIO& io = ImGui::GetIO();
735
736 // We forward mouse input when hovered or captured (via SDL_MOUSEMOTION) or when focused (below)
737 #if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE
738 // - SDL_CaptureMouse() let the OS know e.g. that our drags can extend outside of parent boundaries (we want updated position) and shouldn't trigger other operations outside.
739 // - Debuggers under Linux tends to leave captured mouse on break, which may be very inconvenient, so to mitigate the issue we wait until mouse has moved to begin capture.
740 if (bd->MouseCanUseCapture)
741 {
742 bool want_capture = false;
743 for (int button_n = 0; button_n < ImGuiMouseButton_COUNT && !want_capture; button_n++)
744 if (ImGui::IsMouseDragging(button_n, 1.0f))
745 want_capture = true;
746 SDL_CaptureMouse(want_capture ? SDL_TRUE : SDL_FALSE);
747 }
748
749 SDL_Window* focused_window = SDL_GetKeyboardFocus();
750 const bool is_app_focused = (focused_window && (bd->Window == focused_window || ImGui_ImplSDL2_GetViewportForWindowID(SDL_GetWindowID(focused_window)) != NULL));
751 #else
752 SDL_Window* focused_window = bd->Window;
753 const bool is_app_focused = (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_INPUT_FOCUS) != 0; // SDL 2.0.3 and non-windowed systems: single-viewport only
754 #endif
755
756 if (is_app_focused)
757 {
758 // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when io.ConfigNavMoveSetMousePos is enabled by user)
759 if (io.WantSetMousePos)
760 {
761 #if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE
762 if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
763 SDL_WarpMouseGlobal((int)io.MousePos.x, (int)io.MousePos.y);
764 else
765 #endif
766 SDL_WarpMouseInWindow(bd->Window, (int)io.MousePos.x, (int)io.MousePos.y);
767 }
768
769 // (Optional) Fallback to provide mouse position when focused (SDL_MOUSEMOTION already provides this when hovered or captured)
770 const bool is_relative_mouse_mode = SDL_GetRelativeMouseMode() != 0;
771 if (bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0 && !is_relative_mouse_mode)
772 {
773 // Single-viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window)
774 // Multi-viewport mode: mouse position in OS absolute coordinates (io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor)
775 int mouse_x, mouse_y, window_x, window_y;
776 SDL_GetGlobalMouseState(&mouse_x, &mouse_y);
777 if (!(io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable))
778 {
779 SDL_GetWindowPosition(focused_window, &window_x, &window_y);
780 mouse_x -= window_x;
781 mouse_y -= window_y;
782 }
783 // Fix for high DPI mac/idevice/wayland
784 mouse_x *= io.InputScale;
785 mouse_y *= io.InputScale;
786 io.AddMousePosEvent((float)mouse_x, (float)mouse_y);
787 }
788 }
789
790 // (Optional) When using multiple viewports: call io.AddMouseViewportEvent() with the viewport the OS mouse cursor is hovering.
791 // If ImGuiBackendFlags_HasMouseHoveredViewport is not set by the backend, Dear imGui will ignore this field and infer the information using its flawed heuristic.
792 // - [!] SDL backend does NOT correctly ignore viewports with the _NoInputs flag.
793 // Some backend are not able to handle that correctly. If a backend report an hovered viewport that has the _NoInputs flag (e.g. when dragging a window
794 // for docking, the viewport has the _NoInputs flag in order to allow us to find the viewport under), then Dear ImGui is forced to ignore the value reported
795 // by the backend, and use its flawed heuristic to guess the viewport behind.
796 // - [X] SDL backend correctly reports this regardless of another viewport behind focused and dragged from (we need this to find a useful drag and drop target).
797 if (io.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
798 {
799 ImGuiID mouse_viewport_id = 0;
800 if (ImGuiViewport* mouse_viewport = ImGui_ImplSDL2_GetViewportForWindowID(bd->MouseWindowID))
801 mouse_viewport_id = mouse_viewport->ID;
802 io.AddMouseViewportEvent(mouse_viewport_id);
803 }
804 }
805
806 static void ImGui_ImplSDL2_UpdateMouseCursor()
807 {
808 ImGuiIO& io = ImGui::GetIO();
809 if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
810 return;
811 ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
812
813 ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
814 if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None)
815 {
816 // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
817 SDL_ShowCursor(SDL_FALSE);
818 }
819 else
820 {
821 // Show OS mouse cursor
822 SDL_Cursor* expected_cursor = bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow];
823 if (bd->MouseLastCursor != expected_cursor)
824 {
825 SDL_SetCursor(expected_cursor); // SDL function doesn't have an early out (see #6113)
826 bd->MouseLastCursor = expected_cursor;
827 }
828 SDL_ShowCursor(SDL_TRUE);
829 }
830 }
831
832 // - On Windows the process needs to be marked DPI-aware!! SDL2 doesn't do it by default. You can call ::SetProcessDPIAware() or call ImGui_ImplWin32_EnableDpiAwareness() from Win32 backend.
833 // - Apple platforms use FramebufferScale so we always return 1.0f.
834 // - Some accessibility applications are declaring virtual monitors with a DPI of 0.0f, see #7902. We preserve this value for caller to handle.
835 float ImGui_ImplSDL2_GetContentScaleForWindow(SDL_Window* window)
836 {
837 return ImGui_ImplSDL2_GetContentScaleForDisplay(SDL_GetWindowDisplayIndex(window));
838 }
839
840 float ImGui_ImplSDL2_GetContentScaleForDisplay(int display_index)
841 {
842 #if SDL_HAS_PER_MONITOR_DPI
843 #if !defined(__APPLE__) && !defined(__EMSCRIPTEN__) && !defined(__ANDROID__)
844 float dpi = 0.0f;
845 if (SDL_GetDisplayDPI(display_index, &dpi, nullptr, nullptr) == 0)
846 return dpi / 96.0f;
847 #endif
848 #endif
849 IM_UNUSED(display_index);
850 return 1.0f;
851 }
852
853 static void ImGui_ImplSDL2_CloseGamepads()
854 {
855 ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
856 if (bd->GamepadMode != ImGui_ImplSDL2_GamepadMode_Manual)
857 for (SDL_GameController* gamepad : bd->Gamepads)
858 SDL_GameControllerClose(gamepad);
859 bd->Gamepads.resize(0);
860 }
861
862 void ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode mode, struct _SDL_GameController** manual_gamepads_array, int manual_gamepads_count)
863 {
864 ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
865 ImGui_ImplSDL2_CloseGamepads();
866 if (mode == ImGui_ImplSDL2_GamepadMode_Manual)
867 {
868 IM_ASSERT(manual_gamepads_array != nullptr || manual_gamepads_count <= 0);
869 for (int n = 0; n < manual_gamepads_count; n++)
870 bd->Gamepads.push_back(manual_gamepads_array[n]);
871 }
872 else
873 {
874 IM_ASSERT(manual_gamepads_array == nullptr && manual_gamepads_count <= 0);
875 bd->WantUpdateGamepadsList = true;
876 }
877 bd->GamepadMode = mode;
878 }
879
880 static void ImGui_ImplSDL2_UpdateGamepadButton(ImGui_ImplSDL2_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GameControllerButton button_no)
881 {
882 bool merged_value = false;
883 for (SDL_GameController* gamepad : bd->Gamepads)
884 merged_value |= SDL_GameControllerGetButton(gamepad, button_no) != 0;
885 io.AddKeyEvent(key, merged_value);
886 }
887
888 static inline float Saturate(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; }
889 static void ImGui_ImplSDL2_UpdateGamepadAnalog(ImGui_ImplSDL2_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GameControllerAxis axis_no, float v0, float v1)
890 {
891 float merged_value = 0.0f;
892 for (SDL_GameController* gamepad : bd->Gamepads)
893 {
894 float vn = Saturate((float)(SDL_GameControllerGetAxis(gamepad, axis_no) - v0) / (float)(v1 - v0));
895 if (merged_value < vn)
896 merged_value = vn;
897 }
898 io.AddKeyAnalogEvent(key, merged_value > 0.1f, merged_value);
899 }
900
901 static void ImGui_ImplSDL2_UpdateGamepads()
902 {
903 ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
904 ImGuiIO& io = ImGui::GetIO();
905
906 // Update list of controller(s) to use
907 if (bd->WantUpdateGamepadsList && bd->GamepadMode != ImGui_ImplSDL2_GamepadMode_Manual)
908 {
909 ImGui_ImplSDL2_CloseGamepads();
910 int joystick_count = SDL_NumJoysticks();
911 for (int n = 0; n < joystick_count; n++)
912 if (SDL_IsGameController(n))
913 if (SDL_GameController* gamepad = SDL_GameControllerOpen(n))
914 {
915 bd->Gamepads.push_back(gamepad);
916 if (bd->GamepadMode == ImGui_ImplSDL2_GamepadMode_AutoFirst)
917 break;
918 }
919 bd->WantUpdateGamepadsList = false;
920 }
921
922 io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
923 if (bd->Gamepads.Size == 0)
924 return;
925 io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
926
927 // Update gamepad inputs
928 const int thumb_dead_zone = 8000; // SDL_gamecontroller.h suggests using this value.
929 ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadStart, SDL_CONTROLLER_BUTTON_START);
930 ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadBack, SDL_CONTROLLER_BUTTON_BACK);
931 ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceLeft, SDL_CONTROLLER_BUTTON_X); // Xbox X, PS Square
932 ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceRight, SDL_CONTROLLER_BUTTON_B); // Xbox B, PS Circle
933 ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceUp, SDL_CONTROLLER_BUTTON_Y); // Xbox Y, PS Triangle
934 ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceDown, SDL_CONTROLLER_BUTTON_A); // Xbox A, PS Cross
935 ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadLeft, SDL_CONTROLLER_BUTTON_DPAD_LEFT);
936 ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadRight, SDL_CONTROLLER_BUTTON_DPAD_RIGHT);
937 ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadUp, SDL_CONTROLLER_BUTTON_DPAD_UP);
938 ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadDown, SDL_CONTROLLER_BUTTON_DPAD_DOWN);
939 ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL1, SDL_CONTROLLER_BUTTON_LEFTSHOULDER);
940 ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR1, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER);
941 ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadL2, SDL_CONTROLLER_AXIS_TRIGGERLEFT, 0.0f, 32767);
942 ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadR2, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, 0.0f, 32767);
943 ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL3, SDL_CONTROLLER_BUTTON_LEFTSTICK);
944 ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR3, SDL_CONTROLLER_BUTTON_RIGHTSTICK);
945 ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickLeft, SDL_CONTROLLER_AXIS_LEFTX, -thumb_dead_zone, -32768);
946 ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickRight, SDL_CONTROLLER_AXIS_LEFTX, +thumb_dead_zone, +32767);
947 ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickUp, SDL_CONTROLLER_AXIS_LEFTY, -thumb_dead_zone, -32768);
948 ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickDown, SDL_CONTROLLER_AXIS_LEFTY, +thumb_dead_zone, +32767);
949 ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickLeft, SDL_CONTROLLER_AXIS_RIGHTX, -thumb_dead_zone, -32768);
950 ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickRight, SDL_CONTROLLER_AXIS_RIGHTX, +thumb_dead_zone, +32767);
951 ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickUp, SDL_CONTROLLER_AXIS_RIGHTY, -thumb_dead_zone, -32768);
952 ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickDown, SDL_CONTROLLER_AXIS_RIGHTY, +thumb_dead_zone, +32767);
953 }
954
955 // FIXME: Note that doesn't update with DPI/Scaling change only as SDL2 doesn't have an event for it (SDL3 has).
956 static void ImGui_ImplSDL2_UpdateMonitors()
957 {
958 ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
959 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
960 platform_io.Monitors.resize(0);
961 bd->WantUpdateMonitors = false;
962 int display_count = SDL_GetNumVideoDisplays();
963 for (int n = 0; n < display_count; n++)
964 {
965 // Warning: the validity of monitor DPI information on Windows depends on the application DPI awareness settings, which generally needs to be set in the manifest or at runtime.
966 ImGuiPlatformMonitor monitor;
967 SDL_Rect r;
968 SDL_GetDisplayBounds(n, &r);
969 monitor.MainPos = monitor.WorkPos = ImVec2((float)r.x, (float)r.y);
970 monitor.MainSize = monitor.WorkSize = ImVec2((float)r.w, (float)r.h);
971 #if SDL_HAS_USABLE_DISPLAY_BOUNDS
972 if (SDL_GetDisplayUsableBounds(n, &r) == 0 && r.w > 0 && r.h > 0)
973 {
974 monitor.WorkPos = ImVec2((float)r.x, (float)r.y);
975 monitor.WorkSize = ImVec2((float)r.w, (float)r.h);
976 }
977 #endif
978 #if SDL_HAS_PER_MONITOR_DPI
979 monitor.DpiScale = 1.0f;
980 #endif
981 // tildearrow: this is the new code. not sure how well it works.
982 /*
983 float dpi_scale = ImGui_ImplSDL2_GetContentScaleForDisplay(n);
984 if (dpi_scale <= 0.0f)
985 continue; // Some accessibility applications are declaring virtual monitors with a DPI of 0, see #7902.
986 monitor.DpiScale = dpi_scale;
987 */
988 monitor.PlatformHandle = (void*)(intptr_t)n;
989 platform_io.Monitors.push_back(monitor);
990 }
991 }
992
993 static void ImGui_ImplSDL2_GetWindowSizeAndFramebufferScale(SDL_Window* window, SDL_Renderer* renderer, ImVec2* out_size, ImVec2* out_framebuffer_scale, int* out_w, int* out_h, int* out_display_w, int* out_display_h)
994 {
995 int w, h;
996 int display_w, display_h;
997 SDL_GetWindowSize(window, &w, &h);
998 if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED)
999 w = h = 0;
1000 if (renderer != nullptr) {
1001 if (SDL_GetRendererOutputSize(renderer, &display_w, &display_h)!=0) {
1002 display_w=0;
1003 display_h=0;
1004 }
1005 }
1006 #if SDL_HAS_VULKAN
1007 else if (SDL_GetWindowFlags(window) & SDL_WINDOW_VULKAN)
1008 SDL_Vulkan_GetDrawableSize(window, &display_w, &display_h);
1009 #endif
1010 else
1011 SDL_GL_GetDrawableSize(window, &display_w, &display_h);
1012 // tildearrow: don't set the size if it is 0
1013 if (out_size != nullptr && w > 0 && h > 0)
1014 *out_size = ImVec2((float)w, (float)h);
1015 // tildearrow: TODO: good idea?
1016 if (out_framebuffer_scale != nullptr && w > 0 && h > 0)
1017 *out_framebuffer_scale = (w > 0 && h > 0) ? ImVec2((float)display_w / w, (float)display_h / h) : ImVec2(1.0f, 1.0f);
1018
1019 *out_w=w;
1020 *out_h=h;
1021 *out_display_w=display_w;
1022 *out_display_h=display_h;
1023 }
1024
1025 void ImGui_ImplSDL2_NewFrame()
1026 {
1027 ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
1028 IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL2_Init()?");
1029 ImGuiIO& io = ImGui::GetIO();
1030
1031 // tildearrow
1032 int w=0, h=0;
1033 int display_w=0, display_h=0;
1034
1035 // Setup main viewport size (every frame to accommodate for window resizing)
1036 ImGui_ImplSDL2_GetWindowSizeAndFramebufferScale(bd->Window, bd->Renderer, &io.DisplaySize, &io.DisplayFramebufferScale, &w, &h, &display_w, &display_h);
1037
1038 // TODO: is this before, or after?
1039 // Update monitors
1040 #ifdef WIN32
1041 bd->WantUpdateMonitors = true; // Keep polling under Windows to handle changes of work area when resizing task-bar (#8415)
1042 #endif
1043 if (bd->WantUpdateMonitors)
1044 ImGui_ImplSDL2_UpdateMonitors();
1045
1046 // On Apple and Wayland, The window size is reported in Low DPI, even when running in high DPI mode
1047 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
1048 if (!platform_io.Monitors.empty() /*&& platform_io.Monitors[0].DpiScale > 1.0f*/ && display_h != h && w != 0 && display_w != 0)
1049 {
1050 io.DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1051 io.DisplaySize = ImVec2((float)display_w, (float)display_h);
1052 //printf("write %d/%d to DpiScale\n",display_w,w);
1053 io.InputScale=(float)display_w/(float)w;
1054 }
1055
1056 // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution)
1057 // (Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. Happens in VMs and Emscripten, see #6189, #6114, #3644)
1058 static Uint64 frequency = SDL_GetPerformanceFrequency();
1059 Uint64 current_time = SDL_GetPerformanceCounter();
1060 if (current_time <= bd->Time)
1061 current_time = bd->Time + 1;
1062 io.DeltaTime = bd->Time > 0 ? (float)((double)(current_time - bd->Time) / frequency) : (float)(1.0f / 60.0f);
1063 bd->Time = current_time;
1064
1065 if (bd->MouseLastLeaveFrame && bd->MouseLastLeaveFrame >= ImGui::GetFrameCount() && bd->MouseButtonsDown == 0)
1066 {
1067 bd->MouseWindowID = 0;
1068 bd->MouseLastLeaveFrame = 0;
1069 io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
1070 }
1071
1072 // Our io.AddMouseViewportEvent() calls will only be valid when not capturing.
1073 // Technically speaking testing for 'bd->MouseButtonsDown == 0' would be more rigorous, but testing for payload reduces noise and potential side-effects.
1074 if (bd->MouseCanReportHoveredViewport && ImGui::GetDragDropPayload() == nullptr)
1075 io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport;
1076 else
1077 io.BackendFlags &= ~ImGuiBackendFlags_HasMouseHoveredViewport;
1078
1079 ImGui_ImplSDL2_UpdateMouseData();
1080 ImGui_ImplSDL2_UpdateMouseCursor();
1081
1082 // Update game controllers (if enabled and available)
1083 ImGui_ImplSDL2_UpdateGamepads();
1084 }
1085
1086 //--------------------------------------------------------------------------------------------------------
1087 // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
1088 // This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
1089 // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
1090 //--------------------------------------------------------------------------------------------------------
1091
1092 // Helper structure we store in the void* PlatformUserData field of each ImGuiViewport to easily retrieve our backend data.
1093 struct ImGui_ImplSDL2_ViewportData
1094 {
1095 SDL_Window* Window;
1096 Uint32 WindowID; // Stored in ImGuiViewport::PlatformHandle. Use SDL_GetWindowFromID() to get SDL_Window* from Uint32 WindowID.
1097 bool WindowOwned;
1098 SDL_GLContext GLContext;
1099
1100 ImGui_ImplSDL2_ViewportData() { Window = nullptr; WindowID = 0; WindowOwned = false; GLContext = nullptr; }
1101 ~ImGui_ImplSDL2_ViewportData() { IM_ASSERT(Window == nullptr && GLContext == nullptr); }
1102 };
1103
1104 static void ImGui_ImplSDL2_CreateWindow(ImGuiViewport* viewport)
1105 {
1106 ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
1107 ImGui_ImplSDL2_ViewportData* vd = IM_NEW(ImGui_ImplSDL2_ViewportData)();
1108 viewport->PlatformUserData = vd;
1109
1110 ImGuiViewport* main_viewport = ImGui::GetMainViewport();
1111 ImGui_ImplSDL2_ViewportData* main_viewport_data = (ImGui_ImplSDL2_ViewportData*)main_viewport->PlatformUserData;
1112
1113 // Share GL resources with main context
1114 bool use_opengl = (main_viewport_data->GLContext != nullptr);
1115 SDL_GLContext backup_context = nullptr;
1116 if (use_opengl)
1117 {
1118 backup_context = SDL_GL_GetCurrentContext();
1119 SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 1);
1120 SDL_GL_MakeCurrent(main_viewport_data->Window, main_viewport_data->GLContext);
1121 }
1122
1123 Uint32 sdl_flags = 0;
1124 sdl_flags |= use_opengl ? SDL_WINDOW_OPENGL : (bd->UseVulkan ? SDL_WINDOW_VULKAN : 0);
1125 sdl_flags |= SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_ALLOW_HIGHDPI;
1126 sdl_flags |= SDL_WINDOW_HIDDEN;
1127 sdl_flags |= (viewport->Flags & ImGuiViewportFlags_NoDecoration) ? SDL_WINDOW_BORDERLESS : 0;
1128 sdl_flags |= (viewport->Flags & ImGuiViewportFlags_NoDecoration) ? 0 : SDL_WINDOW_RESIZABLE;
1129 #if !defined(_WIN32)
1130 // See SDL hack in ImGui_ImplSDL2_ShowWindow().
1131 sdl_flags |= (viewport->Flags & ImGuiViewportFlags_NoTaskBarIcon) ? SDL_WINDOW_SKIP_TASKBAR : 0;
1132 #endif
1133 #if SDL_HAS_ALWAYS_ON_TOP
1134 sdl_flags |= (viewport->Flags & ImGuiViewportFlags_TopMost) ? SDL_WINDOW_ALWAYS_ON_TOP : 0;
1135 #endif
1136 vd->Window = SDL_CreateWindow("No Title Yet", (int)viewport->Pos.x, (int)viewport->Pos.y, (int)viewport->Size.x, (int)viewport->Size.y, sdl_flags);
1137 vd->WindowOwned = true;
1138 if (use_opengl)
1139 {
1140 vd->GLContext = SDL_GL_CreateContext(vd->Window);
1141 SDL_GL_SetSwapInterval(0);
1142 }
1143 if (use_opengl && backup_context)
1144 SDL_GL_MakeCurrent(vd->Window, backup_context);
1145
1146 viewport->PlatformHandle = (void*)(intptr_t)SDL_GetWindowID(vd->Window);
1147 viewport->PlatformHandleRaw = nullptr;
1148 SDL_SysWMinfo info;
1149 SDL_VERSION(&info.version);
1150 if (SDL_GetWindowWMInfo(vd->Window, &info))
1151 {
1152 #if defined(SDL_VIDEO_DRIVER_WINDOWS)
1153 viewport->PlatformHandleRaw = info.info.win.window;
1154 #elif defined(__APPLE__) && defined(SDL_VIDEO_DRIVER_COCOA)
1155 viewport->PlatformHandleRaw = (void*)info.info.cocoa.window;
1156 #endif
1157 }
1158 }
1159
1160 static void ImGui_ImplSDL2_DestroyWindow(ImGuiViewport* viewport)
1161 {
1162 if (ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData)
1163 {
1164 if (vd->GLContext && vd->WindowOwned)
1165 SDL_GL_DeleteContext(vd->GLContext);
1166 if (vd->Window && vd->WindowOwned)
1167 SDL_DestroyWindow(vd->Window);
1168 vd->GLContext = nullptr;
1169 vd->Window = nullptr;
1170 IM_DELETE(vd);
1171 }
1172 viewport->PlatformUserData = viewport->PlatformHandle = nullptr;
1173 }
1174
1175 static void ImGui_ImplSDL2_ShowWindow(ImGuiViewport* viewport)
1176 {
1177 ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1178 #if defined(_WIN32) && !(defined(WINAPI_FAMILY) && ((defined(WINAPI_FAMILY_APP) && WINAPI_FAMILY == WINAPI_FAMILY_APP) || (defined(WINAPI_FAMILY_GAMES) && WINAPI_FAMILY == WINAPI_FAMILY_GAMES)))
1179 HWND hwnd = (HWND)viewport->PlatformHandleRaw;
1180
1181 // SDL hack: Hide icon from task bar
1182 // Note: SDL 2.0.6+ has a SDL_WINDOW_SKIP_TASKBAR flag which is supported under Windows but the way it create the window breaks our seamless transition.
1183 if (viewport->Flags & ImGuiViewportFlags_NoTaskBarIcon)
1184 {
1185 LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE);
1186 ex_style &= ~WS_EX_APPWINDOW;
1187 ex_style |= WS_EX_TOOLWINDOW;
1188 ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style);
1189 }
1190 #endif
1191
1192 #if SDL_HAS_SHOW_WINDOW_ACTIVATION_HINT
1193 SDL_SetHint(SDL_HINT_WINDOW_NO_ACTIVATION_WHEN_SHOWN, (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing) ? "1" : "0");
1194 #elif defined(_WIN32)
1195 // SDL hack: SDL always activate/focus windows :/
1196 if (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing)
1197 {
1198 ::ShowWindow(hwnd, SW_SHOWNA);
1199 return;
1200 }
1201 #endif
1202 SDL_ShowWindow(vd->Window);
1203 }
1204
1205 static ImVec2 ImGui_ImplSDL2_GetWindowPos(ImGuiViewport* viewport)
1206 {
1207 ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1208 int x = 0, y = 0;
1209 SDL_GetWindowPosition(vd->Window, &x, &y);
1210 return ImVec2((float)x, (float)y);
1211 }
1212
1213 static void ImGui_ImplSDL2_SetWindowPos(ImGuiViewport* viewport, ImVec2 pos)
1214 {
1215 ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1216 SDL_SetWindowPosition(vd->Window, (int)pos.x, (int)pos.y);
1217 }
1218
1219 static ImVec2 ImGui_ImplSDL2_GetWindowSize(ImGuiViewport* viewport)
1220 {
1221 ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1222 int w = 0, h = 0;
1223 SDL_GetWindowSize(vd->Window, &w, &h);
1224 return ImVec2((float)w, (float)h);
1225 }
1226
1227 static void ImGui_ImplSDL2_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
1228 {
1229 ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1230 SDL_SetWindowSize(vd->Window, (int)size.x, (int)size.y);
1231 }
1232
1233 static ImVec2 ImGui_ImplSDL2_GetWindowFramebufferScale(ImGuiViewport* viewport)
1234 {
1235 // tildearrow: not here please.
1236 return ImVec2(1.0f,1.0f);
1237 }
1238
1239 static void ImGui_ImplSDL2_SetWindowTitle(ImGuiViewport* viewport, const char* title)
1240 {
1241 ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1242 SDL_SetWindowTitle(vd->Window, title);
1243 }
1244
1245 #if SDL_HAS_WINDOW_ALPHA
1246 static void ImGui_ImplSDL2_SetWindowAlpha(ImGuiViewport* viewport, float alpha)
1247 {
1248 ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1249 SDL_SetWindowOpacity(vd->Window, alpha);
1250 }
1251 #endif
1252
1253 static void ImGui_ImplSDL2_SetWindowFocus(ImGuiViewport* viewport)
1254 {
1255 ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1256 SDL_RaiseWindow(vd->Window);
1257 }
1258
1259 static bool ImGui_ImplSDL2_GetWindowFocus(ImGuiViewport* viewport)
1260 {
1261 ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1262 return (SDL_GetWindowFlags(vd->Window) & SDL_WINDOW_INPUT_FOCUS) != 0;
1263 }
1264
1265 static bool ImGui_ImplSDL2_GetWindowMinimized(ImGuiViewport* viewport)
1266 {
1267 ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1268 return (SDL_GetWindowFlags(vd->Window) & SDL_WINDOW_MINIMIZED) != 0;
1269 }
1270
1271 static void ImGui_ImplSDL2_RenderWindow(ImGuiViewport* viewport, void*)
1272 {
1273 ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1274 if (vd->GLContext)
1275 SDL_GL_MakeCurrent(vd->Window, vd->GLContext);
1276 }
1277
1278 static void ImGui_ImplSDL2_SwapBuffers(ImGuiViewport* viewport, void*)
1279 {
1280 ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1281 if (vd->GLContext)
1282 {
1283 SDL_GL_MakeCurrent(vd->Window, vd->GLContext);
1284 SDL_GL_SwapWindow(vd->Window);
1285 }
1286 }
1287
1288 // Vulkan support (the Vulkan renderer needs to call a platform-side support function to create the surface)
1289 // SDL is graceful enough to _not_ need <vulkan/vulkan.h> so we can safely include this.
1290 #if SDL_HAS_VULKAN
1291 #include <SDL_vulkan.h>
1292 static int ImGui_ImplSDL2_CreateVkSurface(ImGuiViewport* viewport, ImU64 vk_instance, const void* vk_allocator, ImU64* out_vk_surface)
1293 {
1294 ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1295 (void)vk_allocator;
1296 SDL_bool ret = SDL_Vulkan_CreateSurface(vd->Window, (VkInstance)vk_instance, (VkSurfaceKHR*)out_vk_surface);
1297 return ret ? 0 : 1; // ret ? VK_SUCCESS : VK_NOT_READY
1298 }
1299 #endif // SDL_HAS_VULKAN
1300
1301 static void ImGui_ImplSDL2_InitMultiViewportSupport(SDL_Window* window, void* sdl_gl_context)
1302 {
1303 // Register platform interface (will be coupled with a renderer interface)
1304 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
1305 platform_io.Platform_CreateWindow = ImGui_ImplSDL2_CreateWindow;
1306 platform_io.Platform_DestroyWindow = ImGui_ImplSDL2_DestroyWindow;
1307 platform_io.Platform_ShowWindow = ImGui_ImplSDL2_ShowWindow;
1308 platform_io.Platform_SetWindowPos = ImGui_ImplSDL2_SetWindowPos;
1309 platform_io.Platform_GetWindowPos = ImGui_ImplSDL2_GetWindowPos;
1310 platform_io.Platform_SetWindowSize = ImGui_ImplSDL2_SetWindowSize;
1311 platform_io.Platform_GetWindowSize = ImGui_ImplSDL2_GetWindowSize;
1312 platform_io.Platform_GetWindowFramebufferScale = ImGui_ImplSDL2_GetWindowFramebufferScale;
1313 platform_io.Platform_SetWindowFocus = ImGui_ImplSDL2_SetWindowFocus;
1314 platform_io.Platform_GetWindowFocus = ImGui_ImplSDL2_GetWindowFocus;
1315 platform_io.Platform_GetWindowMinimized = ImGui_ImplSDL2_GetWindowMinimized;
1316 platform_io.Platform_SetWindowTitle = ImGui_ImplSDL2_SetWindowTitle;
1317 platform_io.Platform_RenderWindow = ImGui_ImplSDL2_RenderWindow;
1318 platform_io.Platform_SwapBuffers = ImGui_ImplSDL2_SwapBuffers;
1319 #if SDL_HAS_WINDOW_ALPHA
1320 platform_io.Platform_SetWindowAlpha = ImGui_ImplSDL2_SetWindowAlpha;
1321 #endif
1322 #if SDL_HAS_VULKAN
1323 platform_io.Platform_CreateVkSurface = ImGui_ImplSDL2_CreateVkSurface;
1324 #endif
1325
1326 // Register main window handle (which is owned by the main application, not by us)
1327 // This is mostly for simplicity and consistency, so that our code (e.g. mouse handling etc.) can use same logic for main and secondary viewports.
1328 ImGuiViewport* main_viewport = ImGui::GetMainViewport();
1329 ImGui_ImplSDL2_ViewportData* vd = IM_NEW(ImGui_ImplSDL2_ViewportData)();
1330 vd->Window = window;
1331 vd->WindowID = SDL_GetWindowID(window);
1332 vd->WindowOwned = false;
1333 vd->GLContext = sdl_gl_context;
1334 main_viewport->PlatformUserData = vd;
1335 main_viewport->PlatformHandle = (void*)(intptr_t)vd->WindowID;
1336 }
1337
1338 static void ImGui_ImplSDL2_ShutdownMultiViewportSupport()
1339 {
1340 ImGui::DestroyPlatformWindows();
1341 }
1342
1343 //-----------------------------------------------------------------------------
1344
1345 #if defined(__clang__)
1346 #pragma clang diagnostic pop
1347 #endif
1348
1349 #endif // #ifndef IMGUI_DISABLE