imgui_impl_sdl2.cpp 59 KB

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