imgui_impl_win32.cpp 30 KB

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