imgui_impl_win32.cpp 32 KB

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