imgui_impl_sdl2.cpp 61 KB

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