imgui_impl_sdl.cpp 13 KB

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