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. // Implemented features:
  5. // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
  6. // [X] Platform: Clipboard support.
  7. // [X] Platform: Keyboard arrays indexed using SDL_SCANCODE_* codes, e.g. ImGui::IsKeyPressed(SDL_SCANCODE_SPACE).
  8. // Missing features:
  9. // [ ] 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.
  10. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
  11. // If you are new to dear imgui, read examples/README.txt and read the 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-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor.
  16. // 2018-06-08: Misc: Extracted imgui_impl_sdl.cpp/.h away from the old combined SDL2+OpenGL/Vulkan examples.
  17. // 2018-06-08: Misc: ImGui_ImplSDL2_InitForOpenGL() now takes a SDL_GLContext parameter.
  18. // 2018-05-09: Misc: Fixed clipboard paste memory leak (we didn't call SDL_FreeMemory on the data returned by SDL_GetClipboardText).
  19. // 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag.
  20. // 2018-02-16: Inputs: Added support for mouse cursors, honoring ImGui::GetMouseCursor() value.
  21. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
  22. // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
  23. // 2018-02-05: Misc: Using SDL_GetPerformanceCounter() instead of SDL_GetTicks() to be able to handle very high framerate (1000+ FPS).
  24. // 2018-02-05: Inputs: Keyboard mapping is using scancodes everywhere instead of a confusing mixture of keycodes and scancodes.
  25. // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
  26. // 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.
  27. // 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert.
  28. // 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1).
  29. // 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers.
  30. #include "imgui.h"
  31. #include "imgui_impl_sdl.h"
  32. // SDL
  33. // (the multi-viewports feature requires SDL features supported from SDL 2.0.5+)
  34. #include <SDL.h>
  35. #include <SDL_syswm.h>
  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. io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
  110. // Keyboard mapping. ImGui will use those indices to peek into the io.KeysDown[] array.
  111. io.KeyMap[ImGuiKey_Tab] = SDL_SCANCODE_TAB;
  112. io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT;
  113. io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT;
  114. io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP;
  115. io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN;
  116. io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP;
  117. io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN;
  118. io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME;
  119. io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END;
  120. io.KeyMap[ImGuiKey_Insert] = SDL_SCANCODE_INSERT;
  121. io.KeyMap[ImGuiKey_Delete] = SDL_SCANCODE_DELETE;
  122. io.KeyMap[ImGuiKey_Backspace] = SDL_SCANCODE_BACKSPACE;
  123. io.KeyMap[ImGuiKey_Space] = SDL_SCANCODE_SPACE;
  124. io.KeyMap[ImGuiKey_Enter] = SDL_SCANCODE_RETURN;
  125. io.KeyMap[ImGuiKey_Escape] = SDL_SCANCODE_ESCAPE;
  126. io.KeyMap[ImGuiKey_A] = SDL_SCANCODE_A;
  127. io.KeyMap[ImGuiKey_C] = SDL_SCANCODE_C;
  128. io.KeyMap[ImGuiKey_V] = SDL_SCANCODE_V;
  129. io.KeyMap[ImGuiKey_X] = SDL_SCANCODE_X;
  130. io.KeyMap[ImGuiKey_Y] = SDL_SCANCODE_Y;
  131. io.KeyMap[ImGuiKey_Z] = SDL_SCANCODE_Z;
  132. io.SetClipboardTextFn = ImGui_ImplSDL2_SetClipboardText;
  133. io.GetClipboardTextFn = ImGui_ImplSDL2_GetClipboardText;
  134. io.ClipboardUserData = NULL;
  135. g_MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW);
  136. g_MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM);
  137. g_MouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL);
  138. g_MouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS);
  139. g_MouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE);
  140. g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENESW);
  141. g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENWSE);
  142. g_MouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_HAND);
  143. #ifdef _WIN32
  144. SDL_SysWMinfo wmInfo;
  145. SDL_VERSION(&wmInfo.version);
  146. SDL_GetWindowWMInfo(window, &wmInfo);
  147. io.ImeWindowHandle = wmInfo.info.win.window;
  148. #else
  149. (void)window;
  150. #endif
  151. return true;
  152. }
  153. bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context)
  154. {
  155. (void)sdl_gl_context; // Viewport branch will need this.
  156. return ImGui_ImplSDL2_Init(window);
  157. }
  158. bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window)
  159. {
  160. #if !SDL_HAS_VULKAN
  161. IM_ASSERT(0 && "Unsupported");
  162. #endif
  163. return ImGui_ImplSDL2_Init(window);
  164. }
  165. void ImGui_ImplSDL2_Shutdown()
  166. {
  167. g_Window = NULL;
  168. // Destroy last known clipboard data
  169. if (g_ClipboardTextData)
  170. SDL_free(g_ClipboardTextData);
  171. g_ClipboardTextData = NULL;
  172. // Destroy SDL mouse cursors
  173. for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
  174. SDL_FreeCursor(g_MouseCursors[cursor_n]);
  175. memset(g_MouseCursors, 0, sizeof(g_MouseCursors));
  176. }
  177. static void ImGui_ImplSDL2_UpdateMousePosAndButtons()
  178. {
  179. ImGuiIO& io = ImGui::GetIO();
  180. // Set OS mouse position if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user)
  181. if (io.WantSetMousePos)
  182. SDL_WarpMouseInWindow(g_Window, (int)io.MousePos.x, (int)io.MousePos.y);
  183. else
  184. io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
  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. }