imgui_impl_sdl2.cpp 60 KB

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