imgui_impl_win32.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  1. // dear imgui: Platform Backend for Windows (standard windows API for 32 and 64 bits applications)
  2. // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
  3. // Implemented features:
  4. // [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui)
  5. // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
  6. // [X] Platform: Keyboard arrays indexed using VK_* Virtual Key Codes, e.g. ImGui::IsKeyPressed(VK_SPACE).
  7. // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
  8. // [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
  9. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
  10. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
  11. // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
  12. // Read online: https://github.com/ocornut/imgui/tree/master/docs
  13. #include "imgui.h"
  14. #include "imgui_impl_win32.h"
  15. #ifndef WIN32_LEAN_AND_MEAN
  16. #define WIN32_LEAN_AND_MEAN
  17. #endif
  18. #include <windows.h>
  19. #include <tchar.h>
  20. #include <dwmapi.h>
  21. // Configuration flags to add in your imconfig.h file:
  22. //#define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD // Disable gamepad support (this used to be meaningful before <1.81) but we know load XInput dynamically so the option is less relevant now.
  23. // Using XInput for gamepad (will load DLL dynamically)
  24. #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
  25. #include <xinput.h>
  26. typedef DWORD (WINAPI *PFN_XInputGetCapabilities)(DWORD, DWORD, XINPUT_CAPABILITIES*);
  27. typedef DWORD (WINAPI *PFN_XInputGetState)(DWORD, XINPUT_STATE*);
  28. #endif
  29. // CHANGELOG
  30. // (minor and older changes stripped away, please see git history for details)
  31. // 2021-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
  32. // 2021-03-23: Inputs: Clearing keyboard down array when losing focus (WM_KILLFOCUS).
  33. // 2021-02-18: Added ImGui_ImplWin32_EnableAlphaCompositing(). Non Visual Studio users will need to link with dwmapi.lib (MinGW/gcc: use -ldwmapi).
  34. // 2021-02-17: Fixed ImGui_ImplWin32_EnableDpiAwareness() attempting to get SetProcessDpiAwareness from shcore.dll on Windows 8 whereas it is only supported on Windows 8.1.
  35. // 2021-01-25: Inputs: Dynamically loading XInput DLL.
  36. // 2020-12-04: Misc: Fixed setting of io.DisplaySize to invalid/uninitialized data when after hwnd has been closed.
  37. // 2020-03-03: Inputs: Calling AddInputCharacterUTF16() to support surrogate pairs leading to codepoint >= 0x10000 (for more complete CJK inputs)
  38. // 2020-02-17: Added ImGui_ImplWin32_EnableDpiAwareness(), ImGui_ImplWin32_GetDpiScaleForHwnd(), ImGui_ImplWin32_GetDpiScaleForMonitor() helper functions.
  39. // 2020-01-14: Inputs: Added support for #define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD/IMGUI_IMPL_WIN32_DISABLE_LINKING_XINPUT.
  40. // 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor.
  41. // 2019-05-11: Inputs: Don't filter value from WM_CHAR before calling AddInputCharacter().
  42. // 2019-01-17: Misc: Using GetForegroundWindow()+IsChild() instead of GetActiveWindow() to be compatible with windows created in a different thread or parent.
  43. // 2019-01-17: Inputs: Added support for mouse buttons 4 and 5 via WM_XBUTTON* messages.
  44. // 2019-01-15: Inputs: Added support for XInput gamepads (if ImGuiConfigFlags_NavEnableGamepad is set by user application).
  45. // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
  46. // 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor.
  47. // 2018-06-10: Inputs: Fixed handling of mouse wheel messages to support fine position messages (typically sent by track-pads).
  48. // 2018-06-08: Misc: Extracted imgui_impl_win32.cpp/.h away from the old combined DX9/DX10/DX11/DX12 examples.
  49. // 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors and ImGuiBackendFlags_HasSetMousePos flags + honor ImGuiConfigFlags_NoMouseCursorChange flag.
  50. // 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value and WM_SETCURSOR message handling).
  51. // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
  52. // 2018-02-06: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavMoveMouse is set).
  53. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
  54. // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
  55. // 2018-01-08: Inputs: Added mapping for ImGuiKey_Insert.
  56. // 2018-01-05: Inputs: Added WM_LBUTTONDBLCLK double-click handlers for window classes with the CS_DBLCLKS flag.
  57. // 2017-10-23: Inputs: Added WM_SYSKEYDOWN / WM_SYSKEYUP handlers so e.g. the VK_MENU key can be read.
  58. // 2017-10-23: Inputs: Using Win32 ::SetCapture/::GetCapture() to retrieve mouse positions outside the client area when dragging.
  59. // 2016-11-12: Inputs: Only call Win32 ::SetCursor(NULL) when io.MouseDrawCursor is set.
  60. // Win32 Data
  61. static HWND g_hWnd = NULL;
  62. static INT64 g_Time = 0;
  63. static INT64 g_TicksPerSecond = 0;
  64. static ImGuiMouseCursor g_LastMouseCursor = ImGuiMouseCursor_COUNT;
  65. static bool g_HasGamepad = false;
  66. static bool g_WantUpdateHasGamepad = true;
  67. static bool g_WantUpdateMonitors = true;
  68. // Forward Declarations
  69. static void ImGui_ImplWin32_InitPlatformInterface();
  70. static void ImGui_ImplWin32_ShutdownPlatformInterface();
  71. static void ImGui_ImplWin32_UpdateMonitors();
  72. // XInput DLL and functions
  73. #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
  74. static HMODULE g_XInputDLL = NULL;
  75. static PFN_XInputGetCapabilities g_XInputGetCapabilities = NULL;
  76. static PFN_XInputGetState g_XInputGetState = NULL;
  77. #endif
  78. // Functions
  79. bool ImGui_ImplWin32_Init(void* hwnd)
  80. {
  81. if (!::QueryPerformanceFrequency((LARGE_INTEGER*)&g_TicksPerSecond))
  82. return false;
  83. if (!::QueryPerformanceCounter((LARGE_INTEGER*)&g_Time))
  84. return false;
  85. // Setup backend capabilities flags
  86. ImGuiIO& io = ImGui::GetIO();
  87. io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
  88. io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
  89. io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional)
  90. io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport; // We can set io.MouseHoveredViewport correctly (optional, not easy)
  91. io.BackendPlatformName = "imgui_impl_win32";
  92. // Our mouse update function expect PlatformHandle to be filled for the main viewport
  93. g_hWnd = (HWND)hwnd;
  94. ImGuiViewport* main_viewport = ImGui::GetMainViewport();
  95. main_viewport->PlatformHandle = main_viewport->PlatformHandleRaw = (void*)g_hWnd;
  96. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  97. ImGui_ImplWin32_InitPlatformInterface();
  98. // Keyboard mapping. Dear ImGui will use those indices to peek into the io.KeysDown[] array that we will update during the application lifetime.
  99. io.KeyMap[ImGuiKey_Tab] = VK_TAB;
  100. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
  101. io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
  102. io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
  103. io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN;
  104. io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR;
  105. io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
  106. io.KeyMap[ImGuiKey_Home] = VK_HOME;
  107. io.KeyMap[ImGuiKey_End] = VK_END;
  108. io.KeyMap[ImGuiKey_Insert] = VK_INSERT;
  109. io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
  110. io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
  111. io.KeyMap[ImGuiKey_Space] = VK_SPACE;
  112. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  113. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  114. io.KeyMap[ImGuiKey_KeyPadEnter] = VK_RETURN;
  115. io.KeyMap[ImGuiKey_A] = 'A';
  116. io.KeyMap[ImGuiKey_C] = 'C';
  117. io.KeyMap[ImGuiKey_V] = 'V';
  118. io.KeyMap[ImGuiKey_X] = 'X';
  119. io.KeyMap[ImGuiKey_Y] = 'Y';
  120. io.KeyMap[ImGuiKey_Z] = 'Z';
  121. // Dynamically load XInput library
  122. #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
  123. const char* xinput_dll_names[] =
  124. {
  125. "xinput1_4.dll", // Windows 8+
  126. "xinput1_3.dll", // DirectX SDK
  127. "xinput9_1_0.dll", // Windows Vista, Windows 7
  128. "xinput1_2.dll", // DirectX SDK
  129. "xinput1_1.dll" // DirectX SDK
  130. };
  131. for (int n = 0; n < IM_ARRAYSIZE(xinput_dll_names); n++)
  132. if (HMODULE dll = ::LoadLibraryA(xinput_dll_names[n]))
  133. {
  134. g_XInputDLL = dll;
  135. g_XInputGetCapabilities = (PFN_XInputGetCapabilities)::GetProcAddress(dll, "XInputGetCapabilities");
  136. g_XInputGetState = (PFN_XInputGetState)::GetProcAddress(dll, "XInputGetState");
  137. break;
  138. }
  139. #endif // IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
  140. return true;
  141. }
  142. void ImGui_ImplWin32_Shutdown()
  143. {
  144. ImGui_ImplWin32_ShutdownPlatformInterface();
  145. // Unload XInput library
  146. #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
  147. if (g_XInputDLL)
  148. ::FreeLibrary(g_XInputDLL);
  149. g_XInputDLL = NULL;
  150. g_XInputGetCapabilities = NULL;
  151. g_XInputGetState = NULL;
  152. #endif // IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
  153. g_hWnd = NULL;
  154. g_Time = 0;
  155. g_TicksPerSecond = 0;
  156. g_LastMouseCursor = ImGuiMouseCursor_COUNT;
  157. g_HasGamepad = false;
  158. g_WantUpdateHasGamepad = true;
  159. }
  160. static bool ImGui_ImplWin32_UpdateMouseCursor()
  161. {
  162. ImGuiIO& io = ImGui::GetIO();
  163. if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
  164. return false;
  165. ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
  166. if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor)
  167. {
  168. // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
  169. ::SetCursor(NULL);
  170. }
  171. else
  172. {
  173. // Show OS mouse cursor
  174. LPTSTR win32_cursor = IDC_ARROW;
  175. switch (imgui_cursor)
  176. {
  177. case ImGuiMouseCursor_Arrow: win32_cursor = IDC_ARROW; break;
  178. case ImGuiMouseCursor_TextInput: win32_cursor = IDC_IBEAM; break;
  179. case ImGuiMouseCursor_ResizeAll: win32_cursor = IDC_SIZEALL; break;
  180. case ImGuiMouseCursor_ResizeEW: win32_cursor = IDC_SIZEWE; break;
  181. case ImGuiMouseCursor_ResizeNS: win32_cursor = IDC_SIZENS; break;
  182. case ImGuiMouseCursor_ResizeNESW: win32_cursor = IDC_SIZENESW; break;
  183. case ImGuiMouseCursor_ResizeNWSE: win32_cursor = IDC_SIZENWSE; break;
  184. case ImGuiMouseCursor_Hand: win32_cursor = IDC_HAND; break;
  185. case ImGuiMouseCursor_NotAllowed: win32_cursor = IDC_NO; break;
  186. }
  187. ::SetCursor(::LoadCursor(NULL, win32_cursor));
  188. }
  189. return true;
  190. }
  191. // This code supports multi-viewports (multiple OS Windows mapped into different Dear ImGui viewports)
  192. // Because of that, it is a little more complicated than your typical single-viewport binding code!
  193. static void ImGui_ImplWin32_UpdateMousePos()
  194. {
  195. ImGuiIO& io = ImGui::GetIO();
  196. IM_ASSERT(g_hWnd != 0);
  197. // Set OS mouse position if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user)
  198. // (When multi-viewports are enabled, all imgui positions are same as OS positions)
  199. if (io.WantSetMousePos)
  200. {
  201. POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y };
  202. if ((io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) == 0)
  203. ::ClientToScreen(g_hWnd, &pos);
  204. ::SetCursorPos(pos.x, pos.y);
  205. }
  206. io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
  207. io.MouseHoveredViewport = 0;
  208. // Set imgui mouse position
  209. POINT mouse_screen_pos;
  210. if (!::GetCursorPos(&mouse_screen_pos))
  211. return;
  212. if (HWND focused_hwnd = ::GetForegroundWindow())
  213. {
  214. if (::IsChild(focused_hwnd, g_hWnd))
  215. focused_hwnd = g_hWnd;
  216. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  217. {
  218. // 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)
  219. // This is the position you can get with GetCursorPos(). In theory adding viewport->Pos is also the reverse operation of doing ScreenToClient().
  220. if (ImGui::FindViewportByPlatformHandle((void*)focused_hwnd) != NULL)
  221. io.MousePos = ImVec2((float)mouse_screen_pos.x, (float)mouse_screen_pos.y);
  222. }
  223. else
  224. {
  225. // 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.)
  226. // This is the position you can get with GetCursorPos() + ScreenToClient() or from WM_MOUSEMOVE.
  227. if (focused_hwnd == g_hWnd)
  228. {
  229. POINT mouse_client_pos = mouse_screen_pos;
  230. ::ScreenToClient(focused_hwnd, &mouse_client_pos);
  231. io.MousePos = ImVec2((float)mouse_client_pos.x, (float)mouse_client_pos.y);
  232. }
  233. }
  234. }
  235. // (Optional) When using multiple viewports: set io.MouseHoveredViewport to the viewport the OS mouse cursor is hovering.
  236. // Important: this information is not easy to provide and many high-level windowing library won't be able to provide it correctly, because
  237. // - This is _ignoring_ viewports with the ImGuiViewportFlags_NoInputs flag (pass-through windows).
  238. // - This is _regardless_ of whether another viewport is focused or being dragged from.
  239. // If ImGuiBackendFlags_HasMouseHoveredViewport is not set by the backend, imgui will ignore this field and infer the information by relying on the
  240. // rectangles and last focused time of every viewports it knows about. It will be unaware of foreign windows that may be sitting between or over your windows.
  241. if (HWND hovered_hwnd = ::WindowFromPoint(mouse_screen_pos))
  242. if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle((void*)hovered_hwnd))
  243. if ((viewport->Flags & ImGuiViewportFlags_NoInputs) == 0) // FIXME: We still get our NoInputs window with WM_NCHITTEST/HTTRANSPARENT code when decorated?
  244. io.MouseHoveredViewport = viewport->ID;
  245. }
  246. // Gamepad navigation mapping
  247. static void ImGui_ImplWin32_UpdateGamepads()
  248. {
  249. #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
  250. ImGuiIO& io = ImGui::GetIO();
  251. memset(io.NavInputs, 0, sizeof(io.NavInputs));
  252. if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0)
  253. return;
  254. // Calling XInputGetState() every frame on disconnected gamepads is unfortunately too slow.
  255. // Instead we refresh gamepad availability by calling XInputGetCapabilities() _only_ after receiving WM_DEVICECHANGE.
  256. if (g_WantUpdateHasGamepad)
  257. {
  258. XINPUT_CAPABILITIES caps;
  259. g_HasGamepad = g_XInputGetCapabilities ? (g_XInputGetCapabilities(0, XINPUT_FLAG_GAMEPAD, &caps) == ERROR_SUCCESS) : false;
  260. g_WantUpdateHasGamepad = false;
  261. }
  262. io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
  263. XINPUT_STATE xinput_state;
  264. if (g_HasGamepad && g_XInputGetState && g_XInputGetState(0, &xinput_state) == ERROR_SUCCESS)
  265. {
  266. const XINPUT_GAMEPAD& gamepad = xinput_state.Gamepad;
  267. io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
  268. #define MAP_BUTTON(NAV_NO, BUTTON_ENUM) { io.NavInputs[NAV_NO] = (gamepad.wButtons & BUTTON_ENUM) ? 1.0f : 0.0f; }
  269. #define MAP_ANALOG(NAV_NO, VALUE, V0, V1) { float vn = (float)(VALUE - V0) / (float)(V1 - V0); if (vn > 1.0f) vn = 1.0f; if (vn > 0.0f && io.NavInputs[NAV_NO] < vn) io.NavInputs[NAV_NO] = vn; }
  270. MAP_BUTTON(ImGuiNavInput_Activate, XINPUT_GAMEPAD_A); // Cross / A
  271. MAP_BUTTON(ImGuiNavInput_Cancel, XINPUT_GAMEPAD_B); // Circle / B
  272. MAP_BUTTON(ImGuiNavInput_Menu, XINPUT_GAMEPAD_X); // Square / X
  273. MAP_BUTTON(ImGuiNavInput_Input, XINPUT_GAMEPAD_Y); // Triangle / Y
  274. MAP_BUTTON(ImGuiNavInput_DpadLeft, XINPUT_GAMEPAD_DPAD_LEFT); // D-Pad Left
  275. MAP_BUTTON(ImGuiNavInput_DpadRight, XINPUT_GAMEPAD_DPAD_RIGHT); // D-Pad Right
  276. MAP_BUTTON(ImGuiNavInput_DpadUp, XINPUT_GAMEPAD_DPAD_UP); // D-Pad Up
  277. MAP_BUTTON(ImGuiNavInput_DpadDown, XINPUT_GAMEPAD_DPAD_DOWN); // D-Pad Down
  278. MAP_BUTTON(ImGuiNavInput_FocusPrev, XINPUT_GAMEPAD_LEFT_SHOULDER); // L1 / LB
  279. MAP_BUTTON(ImGuiNavInput_FocusNext, XINPUT_GAMEPAD_RIGHT_SHOULDER); // R1 / RB
  280. MAP_BUTTON(ImGuiNavInput_TweakSlow, XINPUT_GAMEPAD_LEFT_SHOULDER); // L1 / LB
  281. MAP_BUTTON(ImGuiNavInput_TweakFast, XINPUT_GAMEPAD_RIGHT_SHOULDER); // R1 / RB
  282. MAP_ANALOG(ImGuiNavInput_LStickLeft, gamepad.sThumbLX, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768);
  283. MAP_ANALOG(ImGuiNavInput_LStickRight, gamepad.sThumbLX, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767);
  284. MAP_ANALOG(ImGuiNavInput_LStickUp, gamepad.sThumbLY, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767);
  285. MAP_ANALOG(ImGuiNavInput_LStickDown, gamepad.sThumbLY, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32767);
  286. #undef MAP_BUTTON
  287. #undef MAP_ANALOG
  288. }
  289. #endif // #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
  290. }
  291. static BOOL CALLBACK ImGui_ImplWin32_UpdateMonitors_EnumFunc(HMONITOR monitor, HDC, LPRECT, LPARAM)
  292. {
  293. MONITORINFO info = {};
  294. info.cbSize = sizeof(MONITORINFO);
  295. if (!::GetMonitorInfo(monitor, &info))
  296. return TRUE;
  297. ImGuiPlatformMonitor imgui_monitor;
  298. imgui_monitor.MainPos = ImVec2((float)info.rcMonitor.left, (float)info.rcMonitor.top);
  299. imgui_monitor.MainSize = ImVec2((float)(info.rcMonitor.right - info.rcMonitor.left), (float)(info.rcMonitor.bottom - info.rcMonitor.top));
  300. imgui_monitor.WorkPos = ImVec2((float)info.rcWork.left, (float)info.rcWork.top);
  301. imgui_monitor.WorkSize = ImVec2((float)(info.rcWork.right - info.rcWork.left), (float)(info.rcWork.bottom - info.rcWork.top));
  302. imgui_monitor.DpiScale = ImGui_ImplWin32_GetDpiScaleForMonitor(monitor);
  303. ImGuiPlatformIO& io = ImGui::GetPlatformIO();
  304. if (info.dwFlags & MONITORINFOF_PRIMARY)
  305. io.Monitors.push_front(imgui_monitor);
  306. else
  307. io.Monitors.push_back(imgui_monitor);
  308. return TRUE;
  309. }
  310. static void ImGui_ImplWin32_UpdateMonitors()
  311. {
  312. ImGui::GetPlatformIO().Monitors.resize(0);
  313. ::EnumDisplayMonitors(NULL, NULL, ImGui_ImplWin32_UpdateMonitors_EnumFunc, 0);
  314. g_WantUpdateMonitors = false;
  315. }
  316. void ImGui_ImplWin32_NewFrame()
  317. {
  318. ImGuiIO& io = ImGui::GetIO();
  319. IM_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built! It is generally built by the renderer backend. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame().");
  320. // Setup display size (every frame to accommodate for window resizing)
  321. RECT rect = { 0, 0, 0, 0 };
  322. ::GetClientRect(g_hWnd, &rect);
  323. io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
  324. if (g_WantUpdateMonitors)
  325. ImGui_ImplWin32_UpdateMonitors();
  326. // Setup time step
  327. INT64 current_time = 0;
  328. ::QueryPerformanceCounter((LARGE_INTEGER*)&current_time);
  329. io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond;
  330. g_Time = current_time;
  331. // Read keyboard modifiers inputs
  332. io.KeyCtrl = (::GetKeyState(VK_CONTROL) & 0x8000) != 0;
  333. io.KeyShift = (::GetKeyState(VK_SHIFT) & 0x8000) != 0;
  334. io.KeyAlt = (::GetKeyState(VK_MENU) & 0x8000) != 0;
  335. io.KeySuper = false;
  336. // io.KeysDown[], io.MousePos, io.MouseDown[], io.MouseWheel: filled by the WndProc handler below.
  337. // Update OS mouse position
  338. ImGui_ImplWin32_UpdateMousePos();
  339. // Update OS mouse cursor with the cursor requested by imgui
  340. ImGuiMouseCursor mouse_cursor = io.MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor();
  341. if (g_LastMouseCursor != mouse_cursor)
  342. {
  343. g_LastMouseCursor = mouse_cursor;
  344. ImGui_ImplWin32_UpdateMouseCursor();
  345. }
  346. // Update game controllers (if enabled and available)
  347. ImGui_ImplWin32_UpdateGamepads();
  348. }
  349. // Allow compilation with old Windows SDK. MinGW doesn't have default _WIN32_WINNT/WINVER versions.
  350. #ifndef WM_MOUSEHWHEEL
  351. #define WM_MOUSEHWHEEL 0x020E
  352. #endif
  353. #ifndef DBT_DEVNODES_CHANGED
  354. #define DBT_DEVNODES_CHANGED 0x0007
  355. #endif
  356. // Win32 message handler (process Win32 mouse/keyboard inputs, etc.)
  357. // Call from your application's message handler.
  358. // When implementing your own backend, you can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if Dear ImGui wants to use your inputs.
  359. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
  360. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
  361. // Generally you may always pass all inputs to Dear ImGui, and hide them from your application based on those two flags.
  362. // PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinates when dragging mouse outside of our window bounds.
  363. // PS: We treat DBLCLK messages as regular mouse down messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code doesn't set this flag.
  364. #if 0
  365. // Copy this line into your .cpp file to forward declare the function.
  366. extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
  367. #endif
  368. IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  369. {
  370. if (ImGui::GetCurrentContext() == NULL)
  371. return 0;
  372. ImGuiIO& io = ImGui::GetIO();
  373. switch (msg)
  374. {
  375. case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK:
  376. case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK:
  377. case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK:
  378. case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK:
  379. {
  380. int button = 0;
  381. if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) { button = 0; }
  382. if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) { button = 1; }
  383. if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) { button = 2; }
  384. if (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONDBLCLK) { button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; }
  385. if (!ImGui::IsAnyMouseDown() && ::GetCapture() == NULL)
  386. ::SetCapture(hwnd);
  387. io.MouseDown[button] = true;
  388. return 0;
  389. }
  390. case WM_LBUTTONUP:
  391. case WM_RBUTTONUP:
  392. case WM_MBUTTONUP:
  393. case WM_XBUTTONUP:
  394. {
  395. int button = 0;
  396. if (msg == WM_LBUTTONUP) { button = 0; }
  397. if (msg == WM_RBUTTONUP) { button = 1; }
  398. if (msg == WM_MBUTTONUP) { button = 2; }
  399. if (msg == WM_XBUTTONUP) { button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; }
  400. io.MouseDown[button] = false;
  401. if (!ImGui::IsAnyMouseDown() && ::GetCapture() == hwnd)
  402. ::ReleaseCapture();
  403. return 0;
  404. }
  405. case WM_MOUSEWHEEL:
  406. io.MouseWheel += (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA;
  407. return 0;
  408. case WM_MOUSEHWHEEL:
  409. io.MouseWheelH += (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA;
  410. return 0;
  411. case WM_KEYDOWN:
  412. case WM_SYSKEYDOWN:
  413. if (wParam < 256)
  414. io.KeysDown[wParam] = 1;
  415. return 0;
  416. case WM_KEYUP:
  417. case WM_SYSKEYUP:
  418. if (wParam < 256)
  419. io.KeysDown[wParam] = 0;
  420. return 0;
  421. case WM_KILLFOCUS:
  422. memset(io.KeysDown, 0, sizeof(io.KeysDown));
  423. return 0;
  424. case WM_CHAR:
  425. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  426. if (wParam > 0 && wParam < 0x10000)
  427. io.AddInputCharacterUTF16((unsigned short)wParam);
  428. return 0;
  429. case WM_SETCURSOR:
  430. if (LOWORD(lParam) == HTCLIENT && ImGui_ImplWin32_UpdateMouseCursor())
  431. return 1;
  432. return 0;
  433. case WM_DEVICECHANGE:
  434. if ((UINT)wParam == DBT_DEVNODES_CHANGED)
  435. g_WantUpdateHasGamepad = true;
  436. return 0;
  437. case WM_DISPLAYCHANGE:
  438. g_WantUpdateMonitors = true;
  439. return 0;
  440. }
  441. return 0;
  442. }
  443. //--------------------------------------------------------------------------------------------------------
  444. // DPI-related helpers (optional)
  445. //--------------------------------------------------------------------------------------------------------
  446. // - Use to enable DPI awareness without having to create an application manifest.
  447. // - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps.
  448. // - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc.
  449. // but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime,
  450. // neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies.
  451. //---------------------------------------------------------------------------------------------------------
  452. // This is the scheme successfully used by GLFW (from which we borrowed some of the code) and other apps aiming to be highly portable.
  453. // ImGui_ImplWin32_EnableDpiAwareness() is just a helper called by main.cpp, we don't call it automatically.
  454. // If you are trying to implement your own backend for your own engine, you may ignore that noise.
  455. //---------------------------------------------------------------------------------------------------------
  456. // Implement some of the functions and types normally declared in recent Windows SDK.
  457. #if !defined(_versionhelpers_H_INCLUDED_) && !defined(_INC_VERSIONHELPERS)
  458. static BOOL IsWindowsVersionOrGreater(WORD major, WORD minor, WORD sp)
  459. {
  460. OSVERSIONINFOEXW osvi = { sizeof(osvi), major, minor, 0, 0, { 0 }, sp, 0, 0, 0, 0 };
  461. DWORD mask = VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR;
  462. ULONGLONG cond = ::VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL);
  463. cond = ::VerSetConditionMask(cond, VER_MINORVERSION, VER_GREATER_EQUAL);
  464. cond = ::VerSetConditionMask(cond, VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);
  465. return ::VerifyVersionInfoW(&osvi, mask, cond);
  466. }
  467. #define IsWindowsVistaOrGreater() IsWindowsVersionOrGreater(HIBYTE(0x0600), LOBYTE(0x0600), 0) // _WIN32_WINNT_VISTA
  468. #define IsWindows8OrGreater() IsWindowsVersionOrGreater(HIBYTE(0x0602), LOBYTE(0x0602), 0) // _WIN32_WINNT_WIN8
  469. #define IsWindows8Point1OrGreater() IsWindowsVersionOrGreater(HIBYTE(0x0603), LOBYTE(0x0603), 0) // _WIN32_WINNT_WINBLUE
  470. #endif
  471. #ifndef DPI_ENUMS_DECLARED
  472. typedef enum { PROCESS_DPI_UNAWARE = 0, PROCESS_SYSTEM_DPI_AWARE = 1, PROCESS_PER_MONITOR_DPI_AWARE = 2 } PROCESS_DPI_AWARENESS;
  473. typedef enum { MDT_EFFECTIVE_DPI = 0, MDT_ANGULAR_DPI = 1, MDT_RAW_DPI = 2, MDT_DEFAULT = MDT_EFFECTIVE_DPI } MONITOR_DPI_TYPE;
  474. #endif
  475. #ifndef _DPI_AWARENESS_CONTEXTS_
  476. DECLARE_HANDLE(DPI_AWARENESS_CONTEXT);
  477. #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE (DPI_AWARENESS_CONTEXT)-3
  478. #endif
  479. #ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
  480. #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 (DPI_AWARENESS_CONTEXT)-4
  481. #endif
  482. typedef HRESULT(WINAPI* PFN_SetProcessDpiAwareness)(PROCESS_DPI_AWARENESS); // Shcore.lib + dll, Windows 8.1+
  483. typedef HRESULT(WINAPI* PFN_GetDpiForMonitor)(HMONITOR, MONITOR_DPI_TYPE, UINT*, UINT*); // Shcore.lib + dll, Windows 8.1+
  484. typedef DPI_AWARENESS_CONTEXT(WINAPI* PFN_SetThreadDpiAwarenessContext)(DPI_AWARENESS_CONTEXT); // User32.lib + dll, Windows 10 v1607+ (Creators Update)
  485. // Helper function to enable DPI awareness without setting up a manifest
  486. void ImGui_ImplWin32_EnableDpiAwareness()
  487. {
  488. // Make sure monitors will be updated with latest correct scaling
  489. g_WantUpdateMonitors = true;
  490. // if (IsWindows10OrGreater()) // This needs a manifest to succeed. Instead we try to grab the function pointer!
  491. {
  492. static HINSTANCE user32_dll = ::LoadLibraryA("user32.dll"); // Reference counted per-process
  493. if (PFN_SetThreadDpiAwarenessContext SetThreadDpiAwarenessContextFn = (PFN_SetThreadDpiAwarenessContext)::GetProcAddress(user32_dll, "SetThreadDpiAwarenessContext"))
  494. {
  495. SetThreadDpiAwarenessContextFn(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
  496. return;
  497. }
  498. }
  499. if (IsWindows8Point1OrGreater())
  500. {
  501. static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process
  502. if (PFN_SetProcessDpiAwareness SetProcessDpiAwarenessFn = (PFN_SetProcessDpiAwareness)::GetProcAddress(shcore_dll, "SetProcessDpiAwareness"))
  503. {
  504. SetProcessDpiAwarenessFn(PROCESS_PER_MONITOR_DPI_AWARE);
  505. return;
  506. }
  507. }
  508. #if _WIN32_WINNT >= 0x0600
  509. ::SetProcessDPIAware();
  510. #endif
  511. }
  512. #if defined(_MSC_VER) && !defined(NOGDI)
  513. #pragma comment(lib, "gdi32") // Link with gdi32.lib for GetDeviceCaps(). MinGW will require linking with '-lgdi32'
  514. #endif
  515. float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor)
  516. {
  517. UINT xdpi = 96, ydpi = 96;
  518. static BOOL bIsWindows8Point1OrGreater = IsWindows8Point1OrGreater();
  519. if (bIsWindows8Point1OrGreater)
  520. {
  521. static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process
  522. if (PFN_GetDpiForMonitor GetDpiForMonitorFn = (PFN_GetDpiForMonitor)::GetProcAddress(shcore_dll, "GetDpiForMonitor"))
  523. GetDpiForMonitorFn((HMONITOR)monitor, MDT_EFFECTIVE_DPI, &xdpi, &ydpi);
  524. }
  525. #ifndef NOGDI
  526. else
  527. {
  528. const HDC dc = ::GetDC(NULL);
  529. xdpi = ::GetDeviceCaps(dc, LOGPIXELSX);
  530. ydpi = ::GetDeviceCaps(dc, LOGPIXELSY);
  531. ::ReleaseDC(NULL, dc);
  532. }
  533. #endif
  534. IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert!
  535. return xdpi / 96.0f;
  536. }
  537. float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd)
  538. {
  539. HMONITOR monitor = ::MonitorFromWindow((HWND)hwnd, MONITOR_DEFAULTTONEAREST);
  540. return ImGui_ImplWin32_GetDpiScaleForMonitor(monitor);
  541. }
  542. //--------------------------------------------------------------------------------------------------------
  543. // IME (Input Method Editor) basic support for e.g. Asian language users
  544. //--------------------------------------------------------------------------------------------------------
  545. #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have Win32 functions
  546. #define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
  547. #endif
  548. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
  549. #define HAS_WIN32_IME 1
  550. #include <imm.h>
  551. #ifdef _MSC_VER
  552. #pragma comment(lib, "imm32")
  553. #endif
  554. static void ImGui_ImplWin32_SetImeInputPos(ImGuiViewport* viewport, ImVec2 pos)
  555. {
  556. COMPOSITIONFORM cf = { CFS_FORCE_POSITION,{ (LONG)(pos.x - viewport->Pos.x), (LONG)(pos.y - viewport->Pos.y) },{ 0, 0, 0, 0 } };
  557. if (HWND hwnd = (HWND)viewport->PlatformHandle)
  558. if (HIMC himc = ::ImmGetContext(hwnd))
  559. {
  560. ::ImmSetCompositionWindow(himc, &cf);
  561. ::ImmReleaseContext(hwnd, himc);
  562. }
  563. }
  564. #else
  565. #define HAS_WIN32_IME 0
  566. #endif
  567. //--------------------------------------------------------------------------------------------------------
  568. // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
  569. // This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
  570. // 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..
  571. //--------------------------------------------------------------------------------------------------------
  572. // Helper structure we store in the void* RenderUserData field of each ImGuiViewport to easily retrieve our backend data.
  573. struct ImGuiViewportDataWin32
  574. {
  575. HWND Hwnd;
  576. bool HwndOwned;
  577. DWORD DwStyle;
  578. DWORD DwExStyle;
  579. ImGuiViewportDataWin32() { Hwnd = NULL; HwndOwned = false; DwStyle = DwExStyle = 0; }
  580. ~ImGuiViewportDataWin32() { IM_ASSERT(Hwnd == NULL); }
  581. };
  582. static void ImGui_ImplWin32_GetWin32StyleFromViewportFlags(ImGuiViewportFlags flags, DWORD* out_style, DWORD* out_ex_style)
  583. {
  584. if (flags & ImGuiViewportFlags_NoDecoration)
  585. *out_style = WS_POPUP;
  586. else
  587. *out_style = WS_OVERLAPPEDWINDOW;
  588. if (flags & ImGuiViewportFlags_NoTaskBarIcon)
  589. *out_ex_style = WS_EX_TOOLWINDOW;
  590. else
  591. *out_ex_style = WS_EX_APPWINDOW;
  592. if (flags & ImGuiViewportFlags_TopMost)
  593. *out_ex_style |= WS_EX_TOPMOST;
  594. }
  595. static void ImGui_ImplWin32_CreateWindow(ImGuiViewport* viewport)
  596. {
  597. ImGuiViewportDataWin32* data = IM_NEW(ImGuiViewportDataWin32)();
  598. viewport->PlatformUserData = data;
  599. // Select style and parent window
  600. ImGui_ImplWin32_GetWin32StyleFromViewportFlags(viewport->Flags, &data->DwStyle, &data->DwExStyle);
  601. HWND parent_window = NULL;
  602. if (viewport->ParentViewportId != 0)
  603. if (ImGuiViewport* parent_viewport = ImGui::FindViewportByID(viewport->ParentViewportId))
  604. parent_window = (HWND)parent_viewport->PlatformHandle;
  605. // Create window
  606. RECT rect = { (LONG)viewport->Pos.x, (LONG)viewport->Pos.y, (LONG)(viewport->Pos.x + viewport->Size.x), (LONG)(viewport->Pos.y + viewport->Size.y) };
  607. ::AdjustWindowRectEx(&rect, data->DwStyle, FALSE, data->DwExStyle);
  608. data->Hwnd = ::CreateWindowEx(
  609. data->DwExStyle, _T("ImGui Platform"), _T("Untitled"), data->DwStyle, // Style, class name, window name
  610. rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, // Window area
  611. parent_window, NULL, ::GetModuleHandle(NULL), NULL); // Parent window, Menu, Instance, Param
  612. data->HwndOwned = true;
  613. viewport->PlatformRequestResize = false;
  614. viewport->PlatformHandle = viewport->PlatformHandleRaw = data->Hwnd;
  615. }
  616. static void ImGui_ImplWin32_DestroyWindow(ImGuiViewport* viewport)
  617. {
  618. if (ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData)
  619. {
  620. if (::GetCapture() == data->Hwnd)
  621. {
  622. // Transfer capture so if we started dragging from a window that later disappears, we'll still receive the MOUSEUP event.
  623. ::ReleaseCapture();
  624. ::SetCapture(g_hWnd);
  625. }
  626. if (data->Hwnd && data->HwndOwned)
  627. ::DestroyWindow(data->Hwnd);
  628. data->Hwnd = NULL;
  629. IM_DELETE(data);
  630. }
  631. viewport->PlatformUserData = viewport->PlatformHandle = NULL;
  632. }
  633. static void ImGui_ImplWin32_ShowWindow(ImGuiViewport* viewport)
  634. {
  635. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  636. IM_ASSERT(data->Hwnd != 0);
  637. if (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing)
  638. ::ShowWindow(data->Hwnd, SW_SHOWNA);
  639. else
  640. ::ShowWindow(data->Hwnd, SW_SHOW);
  641. }
  642. static void ImGui_ImplWin32_UpdateWindow(ImGuiViewport* viewport)
  643. {
  644. // (Optional) Update Win32 style if it changed _after_ creation.
  645. // Generally they won't change unless configuration flags are changed, but advanced uses (such as manually rewriting viewport flags) make this useful.
  646. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  647. IM_ASSERT(data->Hwnd != 0);
  648. DWORD new_style;
  649. DWORD new_ex_style;
  650. ImGui_ImplWin32_GetWin32StyleFromViewportFlags(viewport->Flags, &new_style, &new_ex_style);
  651. // Only reapply the flags that have been changed from our point of view (as other flags are being modified by Windows)
  652. if (data->DwStyle != new_style || data->DwExStyle != new_ex_style)
  653. {
  654. // (Optional) Update TopMost state if it changed _after_ creation
  655. bool top_most_changed = (data->DwExStyle & WS_EX_TOPMOST) != (new_ex_style & WS_EX_TOPMOST);
  656. HWND insert_after = top_most_changed ? ((viewport->Flags & ImGuiViewportFlags_TopMost) ? HWND_TOPMOST : HWND_NOTOPMOST) : 0;
  657. UINT swp_flag = top_most_changed ? 0 : SWP_NOZORDER;
  658. // Apply flags and position (since it is affected by flags)
  659. data->DwStyle = new_style;
  660. data->DwExStyle = new_ex_style;
  661. ::SetWindowLong(data->Hwnd, GWL_STYLE, data->DwStyle);
  662. ::SetWindowLong(data->Hwnd, GWL_EXSTYLE, data->DwExStyle);
  663. RECT rect = { (LONG)viewport->Pos.x, (LONG)viewport->Pos.y, (LONG)(viewport->Pos.x + viewport->Size.x), (LONG)(viewport->Pos.y + viewport->Size.y) };
  664. ::AdjustWindowRectEx(&rect, data->DwStyle, FALSE, data->DwExStyle); // Client to Screen
  665. ::SetWindowPos(data->Hwnd, insert_after, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, swp_flag | SWP_NOACTIVATE | SWP_FRAMECHANGED);
  666. ::ShowWindow(data->Hwnd, SW_SHOWNA); // This is necessary when we alter the style
  667. viewport->PlatformRequestMove = viewport->PlatformRequestResize = true;
  668. }
  669. }
  670. static ImVec2 ImGui_ImplWin32_GetWindowPos(ImGuiViewport* viewport)
  671. {
  672. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  673. IM_ASSERT(data->Hwnd != 0);
  674. POINT pos = { 0, 0 };
  675. ::ClientToScreen(data->Hwnd, &pos);
  676. return ImVec2((float)pos.x, (float)pos.y);
  677. }
  678. static void ImGui_ImplWin32_SetWindowPos(ImGuiViewport* viewport, ImVec2 pos)
  679. {
  680. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  681. IM_ASSERT(data->Hwnd != 0);
  682. RECT rect = { (LONG)pos.x, (LONG)pos.y, (LONG)pos.x, (LONG)pos.y };
  683. ::AdjustWindowRectEx(&rect, data->DwStyle, FALSE, data->DwExStyle);
  684. ::SetWindowPos(data->Hwnd, NULL, rect.left, rect.top, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
  685. }
  686. static ImVec2 ImGui_ImplWin32_GetWindowSize(ImGuiViewport* viewport)
  687. {
  688. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  689. IM_ASSERT(data->Hwnd != 0);
  690. RECT rect;
  691. ::GetClientRect(data->Hwnd, &rect);
  692. return ImVec2(float(rect.right - rect.left), float(rect.bottom - rect.top));
  693. }
  694. static void ImGui_ImplWin32_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
  695. {
  696. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  697. IM_ASSERT(data->Hwnd != 0);
  698. RECT rect = { 0, 0, (LONG)size.x, (LONG)size.y };
  699. ::AdjustWindowRectEx(&rect, data->DwStyle, FALSE, data->DwExStyle); // Client to Screen
  700. ::SetWindowPos(data->Hwnd, NULL, 0, 0, rect.right - rect.left, rect.bottom - rect.top, SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE);
  701. }
  702. static void ImGui_ImplWin32_SetWindowFocus(ImGuiViewport* viewport)
  703. {
  704. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  705. IM_ASSERT(data->Hwnd != 0);
  706. ::BringWindowToTop(data->Hwnd);
  707. ::SetForegroundWindow(data->Hwnd);
  708. ::SetFocus(data->Hwnd);
  709. }
  710. static bool ImGui_ImplWin32_GetWindowFocus(ImGuiViewport* viewport)
  711. {
  712. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  713. IM_ASSERT(data->Hwnd != 0);
  714. return ::GetForegroundWindow() == data->Hwnd;
  715. }
  716. static bool ImGui_ImplWin32_GetWindowMinimized(ImGuiViewport* viewport)
  717. {
  718. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  719. IM_ASSERT(data->Hwnd != 0);
  720. return ::IsIconic(data->Hwnd) != 0;
  721. }
  722. static void ImGui_ImplWin32_SetWindowTitle(ImGuiViewport* viewport, const char* title)
  723. {
  724. // ::SetWindowTextA() doesn't properly handle UTF-8 so we explicitely convert our string.
  725. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  726. IM_ASSERT(data->Hwnd != 0);
  727. int n = ::MultiByteToWideChar(CP_UTF8, 0, title, -1, NULL, 0);
  728. ImVector<wchar_t> title_w;
  729. title_w.resize(n);
  730. ::MultiByteToWideChar(CP_UTF8, 0, title, -1, title_w.Data, n);
  731. ::SetWindowTextW(data->Hwnd, title_w.Data);
  732. }
  733. static void ImGui_ImplWin32_SetWindowAlpha(ImGuiViewport* viewport, float alpha)
  734. {
  735. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  736. IM_ASSERT(data->Hwnd != 0);
  737. IM_ASSERT(alpha >= 0.0f && alpha <= 1.0f);
  738. if (alpha < 1.0f)
  739. {
  740. DWORD style = ::GetWindowLongW(data->Hwnd, GWL_EXSTYLE) | WS_EX_LAYERED;
  741. ::SetWindowLongW(data->Hwnd, GWL_EXSTYLE, style);
  742. ::SetLayeredWindowAttributes(data->Hwnd, 0, (BYTE)(255 * alpha), LWA_ALPHA);
  743. }
  744. else
  745. {
  746. DWORD style = ::GetWindowLongW(data->Hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED;
  747. ::SetWindowLongW(data->Hwnd, GWL_EXSTYLE, style);
  748. }
  749. }
  750. static float ImGui_ImplWin32_GetWindowDpiScale(ImGuiViewport* viewport)
  751. {
  752. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  753. IM_ASSERT(data->Hwnd != 0);
  754. return ImGui_ImplWin32_GetDpiScaleForHwnd(data->Hwnd);
  755. }
  756. // FIXME-DPI: Testing DPI related ideas
  757. static void ImGui_ImplWin32_OnChangedViewport(ImGuiViewport* viewport)
  758. {
  759. (void)viewport;
  760. #if 0
  761. ImGuiStyle default_style;
  762. //default_style.WindowPadding = ImVec2(0, 0);
  763. //default_style.WindowBorderSize = 0.0f;
  764. //default_style.ItemSpacing.y = 3.0f;
  765. //default_style.FramePadding = ImVec2(0, 0);
  766. default_style.ScaleAllSizes(viewport->DpiScale);
  767. ImGuiStyle& style = ImGui::GetStyle();
  768. style = default_style;
  769. #endif
  770. }
  771. static LRESULT CALLBACK ImGui_ImplWin32_WndProcHandler_PlatformWindow(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  772. {
  773. if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
  774. return true;
  775. if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle((void*)hWnd))
  776. {
  777. switch (msg)
  778. {
  779. case WM_CLOSE:
  780. viewport->PlatformRequestClose = true;
  781. return 0;
  782. case WM_MOVE:
  783. viewport->PlatformRequestMove = true;
  784. break;
  785. case WM_SIZE:
  786. viewport->PlatformRequestResize = true;
  787. break;
  788. case WM_MOUSEACTIVATE:
  789. if (viewport->Flags & ImGuiViewportFlags_NoFocusOnClick)
  790. return MA_NOACTIVATE;
  791. break;
  792. case WM_NCHITTEST:
  793. // Let mouse pass-through the window. This will allow the backend to set io.MouseHoveredViewport properly (which is OPTIONAL).
  794. // The ImGuiViewportFlags_NoInputs flag is set while dragging a viewport, as want to detect the window behind the one we are dragging.
  795. // If you cannot easily access those viewport flags from your windowing/event code: you may manually synchronize its state e.g. in
  796. // your main loop after calling UpdatePlatformWindows(). Iterate all viewports/platform windows and pass the flag to your windowing system.
  797. if (viewport->Flags & ImGuiViewportFlags_NoInputs)
  798. return HTTRANSPARENT;
  799. break;
  800. }
  801. }
  802. return DefWindowProc(hWnd, msg, wParam, lParam);
  803. }
  804. static void ImGui_ImplWin32_InitPlatformInterface()
  805. {
  806. WNDCLASSEX wcex;
  807. wcex.cbSize = sizeof(WNDCLASSEX);
  808. wcex.style = CS_HREDRAW | CS_VREDRAW;
  809. wcex.lpfnWndProc = ImGui_ImplWin32_WndProcHandler_PlatformWindow;
  810. wcex.cbClsExtra = 0;
  811. wcex.cbWndExtra = 0;
  812. wcex.hInstance = ::GetModuleHandle(NULL);
  813. wcex.hIcon = NULL;
  814. wcex.hCursor = NULL;
  815. wcex.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1);
  816. wcex.lpszMenuName = NULL;
  817. wcex.lpszClassName = _T("ImGui Platform");
  818. wcex.hIconSm = NULL;
  819. ::RegisterClassEx(&wcex);
  820. ImGui_ImplWin32_UpdateMonitors();
  821. // Register platform interface (will be coupled with a renderer interface)
  822. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  823. platform_io.Platform_CreateWindow = ImGui_ImplWin32_CreateWindow;
  824. platform_io.Platform_DestroyWindow = ImGui_ImplWin32_DestroyWindow;
  825. platform_io.Platform_ShowWindow = ImGui_ImplWin32_ShowWindow;
  826. platform_io.Platform_SetWindowPos = ImGui_ImplWin32_SetWindowPos;
  827. platform_io.Platform_GetWindowPos = ImGui_ImplWin32_GetWindowPos;
  828. platform_io.Platform_SetWindowSize = ImGui_ImplWin32_SetWindowSize;
  829. platform_io.Platform_GetWindowSize = ImGui_ImplWin32_GetWindowSize;
  830. platform_io.Platform_SetWindowFocus = ImGui_ImplWin32_SetWindowFocus;
  831. platform_io.Platform_GetWindowFocus = ImGui_ImplWin32_GetWindowFocus;
  832. platform_io.Platform_GetWindowMinimized = ImGui_ImplWin32_GetWindowMinimized;
  833. platform_io.Platform_SetWindowTitle = ImGui_ImplWin32_SetWindowTitle;
  834. platform_io.Platform_SetWindowAlpha = ImGui_ImplWin32_SetWindowAlpha;
  835. platform_io.Platform_UpdateWindow = ImGui_ImplWin32_UpdateWindow;
  836. platform_io.Platform_GetWindowDpiScale = ImGui_ImplWin32_GetWindowDpiScale; // FIXME-DPI
  837. platform_io.Platform_OnChangedViewport = ImGui_ImplWin32_OnChangedViewport; // FIXME-DPI
  838. #if HAS_WIN32_IME
  839. platform_io.Platform_SetImeInputPos = ImGui_ImplWin32_SetImeInputPos;
  840. #endif
  841. // Register main window handle (which is owned by the main application, not by us)
  842. // 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.
  843. ImGuiViewport* main_viewport = ImGui::GetMainViewport();
  844. ImGuiViewportDataWin32* data = IM_NEW(ImGuiViewportDataWin32)();
  845. data->Hwnd = g_hWnd;
  846. data->HwndOwned = false;
  847. main_viewport->PlatformUserData = data;
  848. main_viewport->PlatformHandle = (void*)g_hWnd;
  849. }
  850. static void ImGui_ImplWin32_ShutdownPlatformInterface()
  851. {
  852. ::UnregisterClass(_T("ImGui Platform"), ::GetModuleHandle(NULL));
  853. }
  854. //---------------------------------------------------------------------------------------------------------
  855. // Transparency related helpers (optional)
  856. //--------------------------------------------------------------------------------------------------------
  857. #if defined(_MSC_VER)
  858. #pragma comment(lib, "dwmapi") // Link with dwmapi.lib. MinGW will require linking with '-ldwmapi'
  859. #endif
  860. // [experimental]
  861. // Borrowed from GLFW's function updateFramebufferTransparency() in src/win32_window.c
  862. // (the Dwm* functions are Vista era functions but we are borrowing logic from GLFW)
  863. void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd)
  864. {
  865. if (!IsWindowsVistaOrGreater())
  866. return;
  867. BOOL composition;
  868. if (FAILED(::DwmIsCompositionEnabled(&composition)) || !composition)
  869. return;
  870. BOOL opaque;
  871. DWORD color;
  872. if (IsWindows8OrGreater() || (SUCCEEDED(::DwmGetColorizationColor(&color, &opaque)) && !opaque))
  873. {
  874. HRGN region = ::CreateRectRgn(0, 0, -1, -1);
  875. DWM_BLURBEHIND bb = {};
  876. bb.dwFlags = DWM_BB_ENABLE | DWM_BB_BLURREGION;
  877. bb.hRgnBlur = region;
  878. bb.fEnable = TRUE;
  879. ::DwmEnableBlurBehindWindow((HWND)hwnd, &bb);
  880. ::DeleteObject(region);
  881. }
  882. else
  883. {
  884. DWM_BLURBEHIND bb = {};
  885. bb.dwFlags = DWM_BB_ENABLE;
  886. ::DwmEnableBlurBehindWindow((HWND)hwnd, &bb);
  887. }
  888. }
  889. //---------------------------------------------------------------------------------------------------------