imgui_impl_sdl.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. // ImGui Platform Binding 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. // Missing features:
  5. // [ ] SDL2 handling of IME under Windows appears to be broken and it explicitly disable the regular Windows IME. You can restore Windows IME by compiling SDL with SDL_DISABLE_WINDOWS_IME.
  6. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
  7. // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
  8. // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
  9. // https://github.com/ocornut/imgui
  10. // CHANGELOG
  11. // (minor and older changes stripped away, please see git history for details)
  12. // 2018-06-08: Misc: Extracted imgui_impl_sdl.cpp/.h away from the old combined SDL2+OpenGL/Vulkan examples.
  13. // 2018-06-08: Misc: ImGui_ImplSDL2_InitForOpenGL() now takes a SDL_GLContext parameter.
  14. // 2018-05-09: Misc: Fixed clipboard paste memory leak (we didn't call SDL_FreeMemory on the data returned by SDL_GetClipboardText).
  15. // 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag.
  16. // 2018-02-16: Inputs: Added support for mouse cursors, honoring ImGui::GetMouseCursor() value.
  17. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
  18. // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
  19. // 2018-02-05: Misc: Using SDL_GetPerformanceCounter() instead of SDL_GetTicks() to be able to handle very high framerate (1000+ FPS).
  20. // 2018-02-05: Inputs: Keyboard mapping is using scancodes everywhere instead of a confusing mixture of keycodes and scancodes.
  21. // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
  22. // 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.
  23. // 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert.
  24. // 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1).
  25. // 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers.
  26. #include "imgui.h"
  27. #include "imgui_impl_sdl.h"
  28. // SDL
  29. // (the multi-viewports feature requires SDL features supported from SDL 2.0.5+)
  30. #include <SDL.h>
  31. #include <SDL_syswm.h>
  32. #define SDL_HAS_WARP_MOUSE_GLOBAL SDL_VERSION_ATLEAST(2,0,4)
  33. #define SDL_HAS_CAPTURE_MOUSE SDL_VERSION_ATLEAST(2,0,4)
  34. #define SDL_HAS_VULKAN SDL_VERSION_ATLEAST(2,0,6)
  35. #define SDL_HAS_MOUSE_FOCUS_CLICKTHROUGH SDL_VERSION_ATLEAST(2,0,5)
  36. #if !SDL_HAS_VULKAN
  37. static const Uint32 SDL_WINDOW_VULKAN = 0x10000000;
  38. #endif
  39. // Data
  40. static SDL_Window* g_Window = NULL;
  41. static Uint64 g_Time = 0;
  42. static bool g_MousePressed[3] = { false, false, false };
  43. static SDL_Cursor* g_MouseCursors[ImGuiMouseCursor_Count_] = { 0 };
  44. static char* g_ClipboardTextData = NULL;
  45. static const char* ImGui_ImplSDL2_GetClipboardText(void*)
  46. {
  47. if (g_ClipboardTextData)
  48. SDL_free(g_ClipboardTextData);
  49. g_ClipboardTextData = SDL_GetClipboardText();
  50. return g_ClipboardTextData;
  51. }
  52. static void ImGui_ImplSDL2_SetClipboardText(void*, const char* text)
  53. {
  54. SDL_SetClipboardText(text);
  55. }
  56. // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
  57. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
  58. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
  59. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
  60. bool ImGui_ImplSDL2_ProcessEvent(SDL_Event* event)
  61. {
  62. ImGuiIO& io = ImGui::GetIO();
  63. switch (event->type)
  64. {
  65. case SDL_MOUSEWHEEL:
  66. {
  67. if (event->wheel.x > 0) io.MouseWheelH += 1;
  68. if (event->wheel.x < 0) io.MouseWheelH -= 1;
  69. if (event->wheel.y > 0) io.MouseWheel += 1;
  70. if (event->wheel.y < 0) io.MouseWheel -= 1;
  71. return true;
  72. }
  73. case SDL_MOUSEBUTTONDOWN:
  74. {
  75. if (event->button.button == SDL_BUTTON_LEFT) g_MousePressed[0] = true;
  76. if (event->button.button == SDL_BUTTON_RIGHT) g_MousePressed[1] = true;
  77. if (event->button.button == SDL_BUTTON_MIDDLE) g_MousePressed[2] = true;
  78. return true;
  79. }
  80. case SDL_TEXTINPUT:
  81. {
  82. io.AddInputCharactersUTF8(event->text.text);
  83. return true;
  84. }
  85. case SDL_KEYDOWN:
  86. case SDL_KEYUP:
  87. {
  88. int key = event->key.keysym.scancode;
  89. IM_ASSERT(key >= 0 && key < IM_ARRAYSIZE(io.KeysDown));
  90. io.KeysDown[key] = (event->type == SDL_KEYDOWN);
  91. io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0);
  92. io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0);
  93. io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0);
  94. io.KeySuper = ((SDL_GetModState() & KMOD_GUI) != 0);
  95. return true;
  96. }
  97. }
  98. return false;
  99. }
  100. static bool ImGui_ImplSDL2_Init(SDL_Window* window)
  101. {
  102. g_Window = window;
  103. // Setup back-end capabilities flags
  104. ImGuiIO& io = ImGui::GetIO();
  105. io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
  106. #if SDL_HAS_WARP_MOUSE_GLOBAL
  107. io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
  108. #endif
  109. // Keyboard mapping. ImGui will use those indices to peek into the io.KeysDown[] array.
  110. io.KeyMap[ImGuiKey_Tab] = SDL_SCANCODE_TAB;
  111. io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT;
  112. io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT;
  113. io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP;
  114. io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN;
  115. io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP;
  116. io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN;
  117. io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME;
  118. io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END;
  119. io.KeyMap[ImGuiKey_Insert] = SDL_SCANCODE_INSERT;
  120. io.KeyMap[ImGuiKey_Delete] = SDL_SCANCODE_DELETE;
  121. io.KeyMap[ImGuiKey_Backspace] = SDL_SCANCODE_BACKSPACE;
  122. io.KeyMap[ImGuiKey_Space] = SDL_SCANCODE_SPACE;
  123. io.KeyMap[ImGuiKey_Enter] = SDL_SCANCODE_RETURN;
  124. io.KeyMap[ImGuiKey_Escape] = SDL_SCANCODE_ESCAPE;
  125. io.KeyMap[ImGuiKey_A] = SDL_SCANCODE_A;
  126. io.KeyMap[ImGuiKey_C] = SDL_SCANCODE_C;
  127. io.KeyMap[ImGuiKey_V] = SDL_SCANCODE_V;
  128. io.KeyMap[ImGuiKey_X] = SDL_SCANCODE_X;
  129. io.KeyMap[ImGuiKey_Y] = SDL_SCANCODE_Y;
  130. io.KeyMap[ImGuiKey_Z] = SDL_SCANCODE_Z;
  131. io.SetClipboardTextFn = ImGui_ImplSDL2_SetClipboardText;
  132. io.GetClipboardTextFn = ImGui_ImplSDL2_GetClipboardText;
  133. io.ClipboardUserData = NULL;
  134. g_MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW);
  135. g_MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM);
  136. g_MouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL);
  137. g_MouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS);
  138. g_MouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE);
  139. g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENESW);
  140. g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENWSE);
  141. #ifdef _WIN32
  142. SDL_SysWMinfo wmInfo;
  143. SDL_VERSION(&wmInfo.version);
  144. SDL_GetWindowWMInfo(window, &wmInfo);
  145. io.ImeWindowHandle = wmInfo.info.win.window;
  146. #else
  147. (void)window;
  148. #endif
  149. return true;
  150. }
  151. bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context)
  152. {
  153. (void)sdl_gl_context; // Viewport branch will need this.
  154. return ImGui_ImplSDL2_Init(window);
  155. }
  156. bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window)
  157. {
  158. #if !SDL_HAS_VULKAN
  159. IM_ASSERT(0 && "Unsupported");
  160. #endif
  161. return ImGui_ImplSDL2_Init(window);
  162. }
  163. void ImGui_ImplSDL2_Shutdown()
  164. {
  165. g_Window = NULL;
  166. // Destroy last known clipboard data
  167. if (g_ClipboardTextData)
  168. SDL_free(g_ClipboardTextData);
  169. // Destroy SDL mouse cursors
  170. for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_Count_; cursor_n++)
  171. SDL_FreeCursor(g_MouseCursors[cursor_n]);
  172. memset(g_MouseCursors, 0, sizeof(g_MouseCursors));
  173. }
  174. static void ImGui_ImplSDL2_UpdateMousePosAndButtons()
  175. {
  176. ImGuiIO& io = ImGui::GetIO();
  177. const ImVec2 mouse_pos_backup = io.MousePos;
  178. io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
  179. // Set OS mouse position if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user)
  180. // (When multi-viewports are enabled, all imgui positions are same as OS positions.)
  181. #if SDL_HAS_WARP_MOUSE_GLOBAL
  182. if (io.WantSetMousePos)
  183. SDL_WarpMouseGlobal((int)mouse_pos_backup.x, (int)mouse_pos_backup.y);
  184. #endif
  185. int mx, my;
  186. Uint32 mouse_buttons = SDL_GetMouseState(&mx, &my);
  187. io.MouseDown[0] = g_MousePressed[0] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame.
  188. io.MouseDown[1] = g_MousePressed[1] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0;
  189. io.MouseDown[2] = g_MousePressed[2] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0;
  190. g_MousePressed[0] = g_MousePressed[1] = g_MousePressed[2] = false;
  191. #if SDL_HAS_CAPTURE_MOUSE
  192. SDL_Window* focused_window = SDL_GetKeyboardFocus();
  193. if (g_Window == focused_window)
  194. {
  195. // SDL_GetMouseState() gives mouse position seemingly based on the last window entered/focused(?)
  196. // The creation of a new windows at runtime and SDL_CaptureMouse both seems to severely mess up with that, so we retrieve that position globally.
  197. int wx, wy;
  198. SDL_GetWindowPosition(focused_window, &wx, &wy);
  199. SDL_GetGlobalMouseState(&mx, &my);
  200. mx -= wx;
  201. my -= wy;
  202. io.MousePos = ImVec2((float)mx, (float)my);
  203. }
  204. // SDL_CaptureMouse() let the OS know e.g. that our imgui drag outside the SDL window boundaries shouldn't e.g. trigger the OS window resize cursor.
  205. // The function is only supported from SDL 2.0.4 (released Jan 2016)
  206. bool any_mouse_button_down = ImGui::IsAnyMouseDown();
  207. SDL_CaptureMouse(any_mouse_button_down ? SDL_TRUE : SDL_FALSE);
  208. #else
  209. if (SDL_GetWindowFlags(g_Window) & SDL_WINDOW_INPUT_FOCUS)
  210. io.MousePos = ImVec2((float)mx, (float)my);
  211. #endif
  212. }
  213. static void ImGui_ImplSDL2_UpdateMouseCursor()
  214. {
  215. ImGuiIO& io = ImGui::GetIO();
  216. if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
  217. return;
  218. ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
  219. if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None)
  220. {
  221. // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
  222. SDL_ShowCursor(SDL_FALSE);
  223. }
  224. else
  225. {
  226. // Show OS mouse cursor
  227. SDL_SetCursor(g_MouseCursors[imgui_cursor] ? g_MouseCursors[imgui_cursor] : g_MouseCursors[ImGuiMouseCursor_Arrow]);
  228. SDL_ShowCursor(SDL_TRUE);
  229. }
  230. }
  231. void ImGui_ImplSDL2_NewFrame(SDL_Window* window)
  232. {
  233. ImGuiIO& io = ImGui::GetIO();
  234. IM_ASSERT(io.Fonts->IsBuilt()); // Font atlas needs to be built, call renderer _NewFrame() function e.g. ImGui_ImplOpenGL3_NewFrame()
  235. // Setup display size (every frame to accommodate for window resizing)
  236. int w, h;
  237. int display_w, display_h;
  238. SDL_GetWindowSize(window, &w, &h);
  239. SDL_GL_GetDrawableSize(window, &display_w, &display_h);
  240. io.DisplaySize = ImVec2((float)w, (float)h);
  241. io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0);
  242. // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution)
  243. static Uint64 frequency = SDL_GetPerformanceFrequency();
  244. Uint64 current_time = SDL_GetPerformanceCounter();
  245. io.DeltaTime = g_Time > 0 ? (float)((double)(current_time - g_Time) / frequency) : (float)(1.0f / 60.0f);
  246. g_Time = current_time;
  247. ImGui_ImplSDL2_UpdateMousePosAndButtons();
  248. ImGui_ImplSDL2_UpdateMouseCursor();
  249. }