imgui_impl_sdl2.cpp 61 KB

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