imgui_impl_win32.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. // ImGui Platform Binding 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 imgui)
  5. // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
  6. // [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
  7. #include "imgui.h"
  8. #include "imgui_impl_win32.h"
  9. #define WIN32_LEAN_AND_MEAN
  10. #include <windows.h>
  11. #include <tchar.h>
  12. // CHANGELOG
  13. // (minor and older changes stripped away, please see git history for details)
  14. // 2018-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
  15. // 2018-06-10: Inputs: Fixed handling of mouse wheel messages to support fine position messages (typically sent by track-pads).
  16. // 2018-06-08: Misc: Extracted imgui_impl_win32.cpp/.h away from the old combined DX9/DX10/DX11/DX12 examples.
  17. // 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors and ImGuiBackendFlags_HasSetMousePos flags + honor ImGuiConfigFlags_NoMouseCursorChange flag.
  18. // 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value and WM_SETCURSOR message handling).
  19. // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
  20. // 2018-02-06: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavMoveMouse is set).
  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-01-20: Inputs: Added Horizontal Mouse Wheel support.
  23. // 2018-01-08: Inputs: Added mapping for ImGuiKey_Insert.
  24. // 2018-01-05: Inputs: Added WM_LBUTTONDBLCLK double-click handlers for window classes with the CS_DBLCLKS flag.
  25. // 2017-10-23: Inputs: Added WM_SYSKEYDOWN / WM_SYSKEYUP handlers so e.g. the VK_MENU key can be read.
  26. // 2017-10-23: Inputs: Using Win32 ::SetCapture/::GetCapture() to retrieve mouse positions outside the client area when dragging.
  27. // 2016-11-12: Inputs: Only call Win32 ::SetCursor(NULL) when io.MouseDrawCursor is set.
  28. // Win32 Data
  29. static HWND g_hWnd = 0;
  30. static INT64 g_Time = 0;
  31. static INT64 g_TicksPerSecond = 0;
  32. static ImGuiMouseCursor g_LastMouseCursor = ImGuiMouseCursor_Count_;
  33. static bool g_WantUpdateMonitors = true;
  34. // Forward Declarations
  35. static void ImGui_ImplWin32_InitPlatformInterface();
  36. static void ImGui_ImplWin32_ShutdownPlatformInterface();
  37. static void ImGui_ImplWin32_UpdateMonitors();
  38. // Functions
  39. bool ImGui_ImplWin32_Init(void* hwnd)
  40. {
  41. if (!::QueryPerformanceFrequency((LARGE_INTEGER *)&g_TicksPerSecond))
  42. return false;
  43. if (!::QueryPerformanceCounter((LARGE_INTEGER *)&g_Time))
  44. return false;
  45. // Setup back-end capabilities flags
  46. ImGuiIO& io = ImGui::GetIO();
  47. io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
  48. io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
  49. io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional)
  50. io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport; // We can set io.MouseHoveredViewport correctly (optional, not easy)
  51. // Our mouse update function expect PlatformHandle to be filled for the main viewport
  52. g_hWnd = (HWND)hwnd;
  53. ImGuiViewport* main_viewport = ImGui::GetMainViewport();
  54. main_viewport->PlatformHandle = (void*)g_hWnd;
  55. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  56. ImGui_ImplWin32_InitPlatformInterface();
  57. // Keyboard mapping. ImGui will use those indices to peek into the io.KeysDown[] array that we will update during the application lifetime.
  58. io.KeyMap[ImGuiKey_Tab] = VK_TAB;
  59. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
  60. io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
  61. io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
  62. io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN;
  63. io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR;
  64. io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
  65. io.KeyMap[ImGuiKey_Home] = VK_HOME;
  66. io.KeyMap[ImGuiKey_End] = VK_END;
  67. io.KeyMap[ImGuiKey_Insert] = VK_INSERT;
  68. io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
  69. io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
  70. io.KeyMap[ImGuiKey_Space] = VK_SPACE;
  71. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  72. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  73. io.KeyMap[ImGuiKey_A] = 'A';
  74. io.KeyMap[ImGuiKey_C] = 'C';
  75. io.KeyMap[ImGuiKey_V] = 'V';
  76. io.KeyMap[ImGuiKey_X] = 'X';
  77. io.KeyMap[ImGuiKey_Y] = 'Y';
  78. io.KeyMap[ImGuiKey_Z] = 'Z';
  79. return true;
  80. }
  81. void ImGui_ImplWin32_Shutdown()
  82. {
  83. ImGui_ImplWin32_ShutdownPlatformInterface();
  84. g_hWnd = (HWND)0;
  85. }
  86. static bool ImGui_ImplWin32_UpdateMouseCursor()
  87. {
  88. ImGuiIO& io = ImGui::GetIO();
  89. if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
  90. return false;
  91. ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
  92. if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor)
  93. {
  94. // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
  95. ::SetCursor(NULL);
  96. }
  97. else
  98. {
  99. // Show OS mouse cursor
  100. LPTSTR win32_cursor = IDC_ARROW;
  101. switch (imgui_cursor)
  102. {
  103. case ImGuiMouseCursor_Arrow: win32_cursor = IDC_ARROW; break;
  104. case ImGuiMouseCursor_TextInput: win32_cursor = IDC_IBEAM; break;
  105. case ImGuiMouseCursor_ResizeAll: win32_cursor = IDC_SIZEALL; break;
  106. case ImGuiMouseCursor_ResizeEW: win32_cursor = IDC_SIZEWE; break;
  107. case ImGuiMouseCursor_ResizeNS: win32_cursor = IDC_SIZENS; break;
  108. case ImGuiMouseCursor_ResizeNESW: win32_cursor = IDC_SIZENESW; break;
  109. case ImGuiMouseCursor_ResizeNWSE: win32_cursor = IDC_SIZENWSE; break;
  110. }
  111. ::SetCursor(::LoadCursor(NULL, win32_cursor));
  112. }
  113. return true;
  114. }
  115. // This code supports multiple OS Windows mapped into different ImGui viewports,
  116. // Because of that, it is a little more complicated than your typical single-viewport binding code.
  117. // A) In Single-viewport mode imgui needs:
  118. // - io.MousePos ............... mouse position, in client window coordinates (what you'd get from GetCursorPos+ScreenToClient() or from WM_MOUSEMOVE)
  119. // io.MousePos is (0,0) when the mouse is on the upper-left corner of the application window.
  120. // B) In Multi-viewport mode imgui needs: (when ImGuiConfigFlags_ViewportsEnable is set)
  121. // - io.MousePos ............... mouse position, in OS absolute coordinates (what you'd get from GetCursorPos(), or from WM_MOUSEMOVE+viewport->Pos).
  122. // io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor.
  123. // - io.MousePosViewport ....... viewport which mouse position is based from (generally the focused/active/capturing viewport)
  124. // - io.MouseHoveredViewport ... [optional] viewport which mouse is hovering, with _very_ specific/strict conditions (Read comments next to io.MouseHoveredViewport. This is _NOT_ easy to provide in many high-level engine because of how we handle the ImGuiViewportFlags_NoInputs flag)
  125. static void ImGui_ImplWin32_UpdateMousePos()
  126. {
  127. ImGuiIO& io = ImGui::GetIO();
  128. // Set OS mouse position if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user)
  129. // (When multi-viewports are enabled, all imgui positions are same as OS positions.)
  130. if (io.WantSetMousePos)
  131. {
  132. POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y };
  133. if ((io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) == 0)
  134. ::ClientToScreen(g_hWnd, &pos);
  135. ::SetCursorPos(pos.x, pos.y);
  136. }
  137. io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
  138. io.MousePosViewport = 0;
  139. io.MouseHoveredViewport = 0;
  140. // Set mouse position and viewport
  141. // (Note that ScreenToClient() and adding +viewport->Pos are mutually cancelling each others when we have multi-viewport enabled. In single-viewport mode, viewport->Pos will be zero)
  142. POINT pos;
  143. if (!::GetCursorPos(&pos))
  144. return;
  145. if (HWND focused_hwnd = ::GetActiveWindow())
  146. if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle((void*)focused_hwnd))
  147. {
  148. POINT client_pos = pos;
  149. ::ScreenToClient(focused_hwnd, &client_pos);
  150. io.MousePos = ImVec2(viewport->Pos.x + (float)client_pos.x, viewport->Pos.y + (float)client_pos.y);
  151. io.MousePosViewport = viewport->ID;
  152. }
  153. // Our back-end can tell which window is under the mouse cursor (not every back-end can), so pass that info to imgui
  154. if (HWND hovered_hwnd = ::WindowFromPoint(pos))
  155. if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle((void*)hovered_hwnd))
  156. io.MouseHoveredViewport = viewport->ID;
  157. }
  158. void ImGui_ImplWin32_NewFrame()
  159. {
  160. ImGuiIO& io = ImGui::GetIO();
  161. // Setup display size (every frame to accommodate for window resizing)
  162. RECT rect;
  163. ::GetClientRect(g_hWnd, &rect);
  164. io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
  165. if (g_WantUpdateMonitors)
  166. ImGui_ImplWin32_UpdateMonitors();
  167. // Setup time step
  168. INT64 current_time;
  169. ::QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
  170. io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond;
  171. g_Time = current_time;
  172. // Read keyboard modifiers inputs
  173. io.KeyCtrl = (::GetKeyState(VK_CONTROL) & 0x8000) != 0;
  174. io.KeyShift = (::GetKeyState(VK_SHIFT) & 0x8000) != 0;
  175. io.KeyAlt = (::GetKeyState(VK_MENU) & 0x8000) != 0;
  176. io.KeySuper = false;
  177. // io.KeysDown[], io.MousePos, io.MouseDown[], io.MouseWheel: filled by the WndProc handler below.
  178. // Update OS mouse position
  179. ImGui_ImplWin32_UpdateMousePos();
  180. // Update OS mouse cursor with the cursor requested by imgui
  181. ImGuiMouseCursor mouse_cursor = io.MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor();
  182. if (g_LastMouseCursor != mouse_cursor)
  183. {
  184. g_LastMouseCursor = mouse_cursor;
  185. ImGui_ImplWin32_UpdateMouseCursor();
  186. }
  187. }
  188. // Allow compilation with old Windows SDK. MinGW doesn't have default _WIN32_WINNT/WINVER versions.
  189. #ifndef WM_MOUSEHWHEEL
  190. #define WM_MOUSEHWHEEL 0x020E
  191. #endif
  192. // Process Win32 mouse/keyboard inputs.
  193. // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
  194. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
  195. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
  196. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
  197. // PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinations when dragging mouse outside of our window bounds.
  198. // 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.
  199. IMGUI_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  200. {
  201. if (ImGui::GetCurrentContext() == NULL)
  202. return 0;
  203. ImGuiIO& io = ImGui::GetIO();
  204. switch (msg)
  205. {
  206. case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK:
  207. case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK:
  208. case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK:
  209. {
  210. int button = 0;
  211. if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) button = 0;
  212. if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) button = 1;
  213. if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) button = 2;
  214. if (!ImGui::IsAnyMouseDown() && ::GetCapture() == NULL)
  215. ::SetCapture(hwnd);
  216. io.MouseDown[button] = true;
  217. return 0;
  218. }
  219. case WM_LBUTTONUP:
  220. case WM_RBUTTONUP:
  221. case WM_MBUTTONUP:
  222. {
  223. int button = 0;
  224. if (msg == WM_LBUTTONUP) button = 0;
  225. if (msg == WM_RBUTTONUP) button = 1;
  226. if (msg == WM_MBUTTONUP) button = 2;
  227. io.MouseDown[button] = false;
  228. if (!ImGui::IsAnyMouseDown() && ::GetCapture() == hwnd)
  229. ::ReleaseCapture();
  230. return 0;
  231. }
  232. case WM_MOUSEWHEEL:
  233. io.MouseWheel += (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA;
  234. return 0;
  235. case WM_MOUSEHWHEEL:
  236. io.MouseWheelH += (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA;
  237. return 0;
  238. case WM_KEYDOWN:
  239. case WM_SYSKEYDOWN:
  240. if (wParam < 256)
  241. io.KeysDown[wParam] = 1;
  242. return 0;
  243. case WM_KEYUP:
  244. case WM_SYSKEYUP:
  245. if (wParam < 256)
  246. io.KeysDown[wParam] = 0;
  247. return 0;
  248. case WM_CHAR:
  249. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  250. if (wParam > 0 && wParam < 0x10000)
  251. io.AddInputCharacter((unsigned short)wParam);
  252. return 0;
  253. case WM_SETCURSOR:
  254. if (LOWORD(lParam) == HTCLIENT && ImGui_ImplWin32_UpdateMouseCursor())
  255. return 1;
  256. return 0;
  257. case WM_DISPLAYCHANGE:
  258. g_WantUpdateMonitors = true;
  259. return 0;
  260. }
  261. return 0;
  262. }
  263. //--------------------------------------------------------------------------------------------------------
  264. // DPI handling
  265. // Those in theory should be simple calls but Windows has multiple ways to handle DPI, and most of them
  266. // require recent Windows versions at runtime or recent Windows SDK at compile-time. Neither we want to depend on.
  267. // So we dynamically select and load those functions to avoid dependencies. This is the scheme successfully
  268. // used by GLFW (from which we borrowed some of the code here) and other applications aiming to be portable.
  269. //---------------------------------------------------------------------------------------------------------
  270. // At this point ImGui_ImplWin32_EnableDpiAwareness() is just a helper called by main.cpp, we don't call it automatically.
  271. //---------------------------------------------------------------------------------------------------------
  272. static BOOL IsWindowsVersionOrGreater(WORD major, WORD minor, WORD sp)
  273. {
  274. OSVERSIONINFOEXW osvi = { sizeof(osvi), major, minor, 0, 0,{ 0 }, sp };
  275. DWORD mask = VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR;
  276. ULONGLONG cond = VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL);
  277. cond = VerSetConditionMask(cond, VER_MINORVERSION, VER_GREATER_EQUAL);
  278. cond = VerSetConditionMask(cond, VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);
  279. return VerifyVersionInfoW(&osvi, mask, cond);
  280. }
  281. #define IsWindows8Point1OrGreater() IsWindowsVersionOrGreater(HIBYTE(0x0602), LOBYTE(0x0602), 0) // _WIN32_WINNT_WINBLUE
  282. #define IsWindows10OrGreater() IsWindowsVersionOrGreater(HIBYTE(0x0A00), LOBYTE(0x0A00), 0) // _WIN32_WINNT_WIN10
  283. #ifndef DPI_ENUMS_DECLARED
  284. typedef enum { PROCESS_DPI_UNAWARE = 0, PROCESS_SYSTEM_DPI_AWARE = 1, PROCESS_PER_MONITOR_DPI_AWARE = 2 } PROCESS_DPI_AWARENESS;
  285. typedef enum { MDT_EFFECTIVE_DPI = 0, MDT_ANGULAR_DPI = 1, MDT_RAW_DPI = 2, MDT_DEFAULT = MDT_EFFECTIVE_DPI } MONITOR_DPI_TYPE;
  286. #endif
  287. #ifndef _DPI_AWARENESS_CONTEXTS_
  288. DECLARE_HANDLE(DPI_AWARENESS_CONTEXT);
  289. #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE (DPI_AWARENESS_CONTEXT)-3
  290. #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 (DPI_AWARENESS_CONTEXT)-4
  291. #endif
  292. typedef HRESULT(WINAPI * PFN_SetProcessDpiAwareness)(PROCESS_DPI_AWARENESS); // Shcore.lib+dll, Windows 8.1
  293. typedef HRESULT(WINAPI * PFN_GetDpiForMonitor)(HMONITOR, MONITOR_DPI_TYPE, UINT*, UINT*); // Shcore.lib+dll, Windows 8.1
  294. typedef DPI_AWARENESS_CONTEXT(WINAPI * PFN_SetThreadDpiAwarenessContext)(DPI_AWARENESS_CONTEXT); // User32.lib+dll, Windows 10 v1607 (Creators Update)
  295. void ImGui_ImplWin32_EnableDpiAwareness()
  296. {
  297. // if (IsWindows10OrGreater()) // FIXME-DPI: This needs a manifest to succeed. Instead we try to grab the function pointer.
  298. {
  299. static HINSTANCE user32_dll = ::LoadLibraryA("user32.dll"); // Reference counted per-process
  300. if (PFN_SetThreadDpiAwarenessContext SetThreadDpiAwarenessContextFn = (PFN_SetThreadDpiAwarenessContext)::GetProcAddress(user32_dll, "SetThreadDpiAwarenessContext"))
  301. {
  302. SetThreadDpiAwarenessContextFn(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
  303. return;
  304. }
  305. }
  306. if (IsWindows8Point1OrGreater())
  307. {
  308. static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process
  309. if (PFN_SetProcessDpiAwareness SetProcessDpiAwarenessFn = (PFN_SetProcessDpiAwareness)::GetProcAddress(shcore_dll, "SetProcessDpiAwareness"))
  310. SetProcessDpiAwarenessFn(PROCESS_PER_MONITOR_DPI_AWARE);
  311. }
  312. else
  313. {
  314. SetProcessDPIAware();
  315. }
  316. }
  317. float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor)
  318. {
  319. UINT xdpi = 96, ydpi = 96;
  320. if (IsWindows8Point1OrGreater())
  321. {
  322. static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process
  323. if (PFN_GetDpiForMonitor GetDpiForMonitorFn = (PFN_GetDpiForMonitor)::GetProcAddress(shcore_dll, "GetDpiForMonitor"))
  324. GetDpiForMonitorFn((HMONITOR)monitor, MDT_EFFECTIVE_DPI, &xdpi, &ydpi);
  325. }
  326. else
  327. {
  328. const HDC dc = ::GetDC(NULL);
  329. xdpi = ::GetDeviceCaps(dc, LOGPIXELSX);
  330. ydpi = ::GetDeviceCaps(dc, LOGPIXELSY);
  331. ::ReleaseDC(NULL, dc);
  332. }
  333. IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert!
  334. return xdpi / 96.0f;
  335. }
  336. float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd)
  337. {
  338. HMONITOR monitor = ::MonitorFromWindow((HWND)hwnd, MONITOR_DEFAULTTONEAREST);
  339. return ImGui_ImplWin32_GetDpiScaleForMonitor(monitor);
  340. }
  341. float ImGui_ImplWin32_GetDpiScaleForRect(int x1, int y1, int x2, int y2)
  342. {
  343. RECT viewport_rect = { (LONG)x1, (LONG)y1, (LONG)x2, (LONG)y2 };
  344. HMONITOR monitor = ::MonitorFromRect(&viewport_rect, MONITOR_DEFAULTTONEAREST);
  345. return ImGui_ImplWin32_GetDpiScaleForMonitor(monitor);
  346. }
  347. //--------------------------------------------------------------------------------------------------------
  348. // IME (Input Method Editor) basic support for e.g. Asian language users
  349. //--------------------------------------------------------------------------------------------------------
  350. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(__GNUC__)
  351. #define HAS_WIN32_IME 1
  352. #include <imm.h>
  353. #ifdef _MSC_VER
  354. #pragma comment(lib, "imm32")
  355. #endif
  356. static void ImGui_ImplWin32_SetImeInputPos(ImGuiViewport* viewport, ImVec2 pos)
  357. {
  358. COMPOSITIONFORM cf = { CFS_FORCE_POSITION,{ (LONG)(pos.x - viewport->Pos.x), (LONG)(pos.y - viewport->Pos.y) },{ 0, 0, 0, 0 } };
  359. if (HWND hwnd = (HWND)viewport->PlatformHandle)
  360. if (HIMC himc = ImmGetContext(hwnd))
  361. ImmSetCompositionWindow(himc, &cf);
  362. }
  363. #else
  364. #define HAS_WIN32_IME 0
  365. #endif
  366. //--------------------------------------------------------------------------------------------------------
  367. // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
  368. // This is an _advanced_ and _optional_ feature, allowing the back-end to create and handle multiple viewports simultaneously.
  369. // 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..
  370. //--------------------------------------------------------------------------------------------------------
  371. struct ImGuiViewportDataWin32
  372. {
  373. HWND Hwnd;
  374. bool HwndOwned;
  375. DWORD DwStyle;
  376. DWORD DwExStyle;
  377. ImGuiViewportDataWin32() { Hwnd = NULL; HwndOwned = false; DwStyle = DwExStyle = 0; }
  378. ~ImGuiViewportDataWin32() { IM_ASSERT(Hwnd == NULL); }
  379. };
  380. static void ImGui_ImplWin32_CreateWindow(ImGuiViewport* viewport)
  381. {
  382. ImGuiViewportDataWin32* data = IM_NEW(ImGuiViewportDataWin32)();
  383. viewport->PlatformUserData = data;
  384. bool no_decoration = (viewport->Flags & ImGuiViewportFlags_NoDecoration) != 0;
  385. bool no_task_bar_icon = (viewport->Flags & ImGuiViewportFlags_NoTaskBarIcon) != 0;
  386. if (no_decoration)
  387. {
  388. data->DwStyle = WS_POPUP;
  389. data->DwExStyle = no_task_bar_icon ? WS_EX_TOOLWINDOW : WS_EX_APPWINDOW;
  390. }
  391. else
  392. {
  393. data->DwStyle = WS_OVERLAPPEDWINDOW;
  394. data->DwExStyle = no_task_bar_icon ? WS_EX_TOOLWINDOW : WS_EX_APPWINDOW;
  395. }
  396. if (viewport->Flags & ImGuiViewportFlags_TopMost)
  397. data->DwExStyle |= WS_EX_TOPMOST;
  398. // Create window
  399. RECT rect = { (LONG)viewport->Pos.x, (LONG)viewport->Pos.y, (LONG)(viewport->Pos.x + viewport->Size.x), (LONG)(viewport->Pos.y + viewport->Size.y) };
  400. ::AdjustWindowRectEx(&rect, data->DwStyle, FALSE, data->DwExStyle);
  401. data->Hwnd = ::CreateWindowEx(
  402. data->DwExStyle, _T("ImGui Platform"), _T("No Title Yet"), data->DwStyle, // Style, class name, window name
  403. rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, // Window area
  404. g_hWnd, NULL, ::GetModuleHandle(NULL), NULL); // Parent window, Menu, Instance, Param
  405. data->HwndOwned = true;
  406. viewport->PlatformRequestResize = false;
  407. viewport->PlatformHandle = data->Hwnd;
  408. }
  409. static void ImGui_ImplWin32_DestroyWindow(ImGuiViewport* viewport)
  410. {
  411. if (ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData)
  412. {
  413. if (::GetCapture() == data->Hwnd)
  414. {
  415. // Transfer capture so if we started dragging from a window that later disappears, we'll still receive the MOUSEUP event.
  416. ::ReleaseCapture();
  417. ::SetCapture(g_hWnd);
  418. }
  419. if (data->Hwnd && data->HwndOwned)
  420. ::DestroyWindow(data->Hwnd);
  421. data->Hwnd = NULL;
  422. IM_DELETE(data);
  423. }
  424. viewport->PlatformUserData = viewport->PlatformHandle = NULL;
  425. }
  426. static void ImGui_ImplWin32_ShowWindow(ImGuiViewport* viewport)
  427. {
  428. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  429. IM_ASSERT(data->Hwnd != 0);
  430. if (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing)
  431. ::ShowWindow(data->Hwnd, SW_SHOWNA);
  432. else
  433. ::ShowWindow(data->Hwnd, SW_SHOW);
  434. }
  435. static ImVec2 ImGui_ImplWin32_GetWindowPos(ImGuiViewport* viewport)
  436. {
  437. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  438. IM_ASSERT(data->Hwnd != 0);
  439. POINT pos = { 0, 0 };
  440. ::ClientToScreen(data->Hwnd, &pos);
  441. return ImVec2((float)pos.x, (float)pos.y);
  442. }
  443. static void ImGui_ImplWin32_SetWindowPos(ImGuiViewport* viewport, ImVec2 pos)
  444. {
  445. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  446. IM_ASSERT(data->Hwnd != 0);
  447. RECT rect = { (LONG)pos.x, (LONG)pos.y, (LONG)pos.x, (LONG)pos.y };
  448. ::AdjustWindowRectEx(&rect, data->DwStyle, FALSE, data->DwExStyle);
  449. ::SetWindowPos(data->Hwnd, NULL, rect.left, rect.top, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
  450. }
  451. static ImVec2 ImGui_ImplWin32_GetWindowSize(ImGuiViewport* viewport)
  452. {
  453. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  454. IM_ASSERT(data->Hwnd != 0);
  455. RECT rect;
  456. ::GetClientRect(data->Hwnd, &rect);
  457. return ImVec2(float(rect.right - rect.left), float(rect.bottom - rect.top));
  458. }
  459. static void ImGui_ImplWin32_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
  460. {
  461. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  462. IM_ASSERT(data->Hwnd != 0);
  463. RECT rect = { 0, 0, (LONG)size.x, (LONG)size.y };
  464. ::AdjustWindowRectEx(&rect, data->DwStyle, FALSE, data->DwExStyle); // Client to Screen
  465. ::SetWindowPos(data->Hwnd, NULL, 0, 0, rect.right - rect.left, rect.bottom - rect.top, SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE);
  466. }
  467. static void ImGui_ImplWin32_SetWindowFocus(ImGuiViewport* viewport)
  468. {
  469. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  470. IM_ASSERT(data->Hwnd != 0);
  471. ::BringWindowToTop(data->Hwnd);
  472. ::SetForegroundWindow(data->Hwnd);
  473. ::SetFocus(data->Hwnd);
  474. }
  475. static bool ImGui_ImplWin32_GetWindowFocus(ImGuiViewport* viewport)
  476. {
  477. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  478. IM_ASSERT(data->Hwnd != 0);
  479. return ::GetActiveWindow() == data->Hwnd;
  480. }
  481. static void ImGui_ImplWin32_SetWindowTitle(ImGuiViewport* viewport, const char* title)
  482. {
  483. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  484. IM_ASSERT(data->Hwnd != 0);
  485. ::SetWindowTextA(data->Hwnd, title);
  486. }
  487. static void ImGui_ImplWin32_SetWindowAlpha(ImGuiViewport* viewport, float alpha)
  488. {
  489. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  490. IM_ASSERT(data->Hwnd != 0);
  491. IM_ASSERT(alpha >= 0.0f && alpha <= 1.0f);
  492. if (alpha < 1.0f)
  493. {
  494. DWORD style = ::GetWindowLongW(data->Hwnd, GWL_EXSTYLE) | WS_EX_LAYERED;
  495. ::SetWindowLongW(data->Hwnd, GWL_EXSTYLE, style);
  496. ::SetLayeredWindowAttributes(data->Hwnd, 0, (BYTE)(255 * alpha), LWA_ALPHA);
  497. }
  498. else
  499. {
  500. DWORD style = ::GetWindowLongW(data->Hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED;
  501. ::SetWindowLongW(data->Hwnd, GWL_EXSTYLE, style);
  502. }
  503. }
  504. static float ImGui_ImplWin32_GetWindowDpiScale(ImGuiViewport* viewport)
  505. {
  506. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  507. if (data && data->Hwnd)
  508. return ImGui_ImplWin32_GetDpiScaleForHwnd(data->Hwnd);
  509. // The first frame a viewport is created we don't have a window yet
  510. return ImGui_ImplWin32_GetDpiScaleForRect(
  511. (int)(viewport->Pos.x), (int)(viewport->Pos.y),
  512. (int)(viewport->Pos.x + viewport->Size.x), (int)(viewport->Pos.y + viewport->Size.y));
  513. }
  514. // FIXME-DPI: Testing DPI related ideas
  515. static void ImGui_ImplWin32_OnChangedViewport(ImGuiViewport* viewport)
  516. {
  517. (void)viewport;
  518. #if 0
  519. ImGuiStyle default_style;
  520. //default_style.WindowPadding = ImVec2(0, 0);
  521. //default_style.WindowBorderSize = 0.0f;
  522. //default_style.ItemSpacing.y = 3.0f;
  523. //default_style.FramePadding = ImVec2(0, 0);
  524. default_style.ScaleAllSizes(viewport->DpiScale);
  525. ImGuiStyle& style = ImGui::GetStyle();
  526. style = default_style;
  527. #endif
  528. }
  529. static LRESULT CALLBACK ImGui_ImplWin32_WndProcHandler_PlatformWindow(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  530. {
  531. if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
  532. return true;
  533. if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle((void*)hWnd))
  534. {
  535. switch (msg)
  536. {
  537. case WM_CLOSE:
  538. viewport->PlatformRequestClose = true;
  539. return 0;
  540. case WM_MOVE:
  541. viewport->PlatformRequestMove = true;
  542. break;
  543. case WM_SIZE:
  544. viewport->PlatformRequestResize = true;
  545. break;
  546. case WM_NCHITTEST:
  547. // Let mouse pass-through the window. This will allow the back-end to set io.MouseHoveredViewport properly (which is OPTIONAL).
  548. // The ImGuiViewportFlags_NoInputs flag is set while dragging a viewport, as want to detect the window behind the one we are dragging.
  549. // If you cannot easily access those viewport flags from your windowing/event code: you may manually synchronize its state e.g. in
  550. // your main loop after calling UpdatePlatformWindows(). Iterate all viewports/platform windows and pass the flag to your windowing system.
  551. if (viewport->Flags & ImGuiViewportFlags_NoInputs)
  552. return HTTRANSPARENT;
  553. break;
  554. }
  555. }
  556. return DefWindowProc(hWnd, msg, wParam, lParam);
  557. }
  558. static BOOL CALLBACK ImGui_ImplWin32_UpdateMonitors_EnumFunc(HMONITOR monitor, HDC, LPRECT, LPARAM)
  559. {
  560. MONITORINFO info = { 0 };
  561. info.cbSize = sizeof(MONITORINFO);
  562. if (!::GetMonitorInfo(monitor, &info))
  563. return TRUE;
  564. ImGuiPlatformMonitor imgui_monitor;
  565. imgui_monitor.MainPos = ImVec2((float)info.rcMonitor.left, (float)info.rcMonitor.top);
  566. imgui_monitor.MainSize = ImVec2((float)(info.rcMonitor.right - info.rcMonitor.left), (float)(info.rcMonitor.bottom - info.rcMonitor.top));
  567. imgui_monitor.WorkPos = ImVec2((float)info.rcWork.left, (float)info.rcWork.top);
  568. imgui_monitor.WorkSize = ImVec2((float)(info.rcWork.right - info.rcWork.left), (float)(info.rcWork.bottom - info.rcWork.top));
  569. imgui_monitor.DpiScale = ImGui_ImplWin32_GetDpiScaleForMonitor(monitor);
  570. ImGuiPlatformIO& io = ImGui::GetPlatformIO();
  571. if (info.dwFlags & MONITORINFOF_PRIMARY)
  572. io.Monitors.push_front(imgui_monitor);
  573. else
  574. io.Monitors.push_back(imgui_monitor);
  575. return TRUE;
  576. }
  577. static void ImGui_ImplWin32_UpdateMonitors()
  578. {
  579. ImGui::GetPlatformIO().Monitors.resize(0);
  580. ::EnumDisplayMonitors(NULL, NULL, ImGui_ImplWin32_UpdateMonitors_EnumFunc, NULL);
  581. g_WantUpdateMonitors = false;
  582. }
  583. static void ImGui_ImplWin32_InitPlatformInterface()
  584. {
  585. WNDCLASSEX wcex;
  586. wcex.cbSize = sizeof(WNDCLASSEX);
  587. wcex.style = CS_HREDRAW | CS_VREDRAW;
  588. wcex.lpfnWndProc = ImGui_ImplWin32_WndProcHandler_PlatformWindow;
  589. wcex.cbClsExtra = 0;
  590. wcex.cbWndExtra = 0;
  591. wcex.hInstance = ::GetModuleHandle(NULL);
  592. wcex.hIcon = NULL;
  593. wcex.hCursor = NULL;
  594. wcex.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1);
  595. wcex.lpszMenuName = NULL;
  596. wcex.lpszClassName = _T("ImGui Platform");
  597. wcex.hIconSm = NULL;
  598. ::RegisterClassEx(&wcex);
  599. ImGui_ImplWin32_UpdateMonitors();
  600. // Register platform interface (will be coupled with a renderer interface)
  601. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  602. platform_io.Platform_CreateWindow = ImGui_ImplWin32_CreateWindow;
  603. platform_io.Platform_DestroyWindow = ImGui_ImplWin32_DestroyWindow;
  604. platform_io.Platform_ShowWindow = ImGui_ImplWin32_ShowWindow;
  605. platform_io.Platform_SetWindowPos = ImGui_ImplWin32_SetWindowPos;
  606. platform_io.Platform_GetWindowPos = ImGui_ImplWin32_GetWindowPos;
  607. platform_io.Platform_SetWindowSize = ImGui_ImplWin32_SetWindowSize;
  608. platform_io.Platform_GetWindowSize = ImGui_ImplWin32_GetWindowSize;
  609. platform_io.Platform_SetWindowFocus = ImGui_ImplWin32_SetWindowFocus;
  610. platform_io.Platform_GetWindowFocus = ImGui_ImplWin32_GetWindowFocus;
  611. platform_io.Platform_SetWindowTitle = ImGui_ImplWin32_SetWindowTitle;
  612. platform_io.Platform_SetWindowAlpha = ImGui_ImplWin32_SetWindowAlpha;
  613. platform_io.Platform_GetWindowDpiScale = ImGui_ImplWin32_GetWindowDpiScale;
  614. platform_io.Platform_OnChangedViewport = ImGui_ImplWin32_OnChangedViewport; // FIXME-DPI
  615. #if HAS_WIN32_IME
  616. platform_io.Platform_SetImeInputPos = ImGui_ImplWin32_SetImeInputPos;
  617. #endif
  618. // Register main window handle (which is owned by the main application, not by us)
  619. ImGuiViewport* main_viewport = ImGui::GetMainViewport();
  620. ImGuiViewportDataWin32* data = IM_NEW(ImGuiViewportDataWin32)();
  621. data->Hwnd = g_hWnd;
  622. data->HwndOwned = false;
  623. main_viewport->PlatformUserData = data;
  624. main_viewport->PlatformHandle = (void*)g_hWnd;
  625. }
  626. static void ImGui_ImplWin32_ShutdownPlatformInterface()
  627. {
  628. ::UnregisterClass(_T("ImGui Platform"), ::GetModuleHandle(NULL));
  629. }