imgui_impl_win32.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  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 multi-viewports (multiple OS Windows mapped into different Dear ImGui viewports)
  125. // Because of that, it is a little more complicated than your typical single-viewport binding code!
  126. static void ImGui_ImplWin32_UpdateMousePos()
  127. {
  128. ImGuiIO& io = ImGui::GetIO();
  129. // Set OS mouse position if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user)
  130. // (When multi-viewports are enabled, all imgui positions are same as OS positions)
  131. if (io.WantSetMousePos)
  132. {
  133. POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y };
  134. if ((io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) == 0)
  135. ::ClientToScreen(g_hWnd, &pos);
  136. ::SetCursorPos(pos.x, pos.y);
  137. }
  138. io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
  139. io.MouseHoveredViewport = 0;
  140. // Set imgui mouse position
  141. POINT mouse_screen_pos;
  142. if (!::GetCursorPos(&mouse_screen_pos))
  143. return;
  144. if (HWND focused_hwnd = ::GetActiveWindow())
  145. {
  146. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  147. {
  148. // Multi-viewport mode: mouse position in OS absolute coordinates (io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor)
  149. // This is the position you can get with GetCursorPos(). In theory adding viewport->Pos is also the reverse operation of doing ScreenToClient().
  150. if (ImGui::FindViewportByPlatformHandle((void*)focused_hwnd) != NULL)
  151. io.MousePos = ImVec2((float)mouse_screen_pos.x, (float)mouse_screen_pos.y);
  152. }
  153. else
  154. {
  155. // Single viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window.)
  156. // This is the position you can get with GetCursorPos() + ScreenToClient() or from WM_MOUSEMOVE.
  157. if (focused_hwnd == g_hWnd)
  158. {
  159. POINT mouse_client_pos = mouse_screen_pos;
  160. ::ScreenToClient(focused_hwnd, &mouse_client_pos);
  161. io.MousePos = ImVec2((float)mouse_client_pos.x, (float)mouse_client_pos.y);
  162. }
  163. }
  164. }
  165. // (Optional) When using multiple viewports: set io.MouseHoveredViewport to the viewport the OS mouse cursor is hovering.
  166. // Important: this information is not easy to provide and many high-level windowing library won't be able to provide it correctly, because
  167. // - This is _ignoring_ viewports with the ImGuiViewportFlags_NoInputs flag (pass-through windows).
  168. // - This is _regardless_ of whether another viewport is focused or being dragged from.
  169. // If ImGuiBackendFlags_HasMouseHoveredViewport is not set by the back-end, imgui will ignore this field and infer the information by relying on the
  170. // rectangles and last focused time of every viewports it knows about. It will be unaware of foreign windows that may be sitting between or over your windows.
  171. if (HWND hovered_hwnd = ::WindowFromPoint(mouse_screen_pos))
  172. if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle((void*)hovered_hwnd))
  173. if ((viewport->Flags & ImGuiViewportFlags_NoInputs) == 0) // FIXME: We still get our NoInputs window with WM_NCHITTEST/HTTRANSPARENT code when decorated?
  174. io.MouseHoveredViewport = viewport->ID;
  175. }
  176. void ImGui_ImplWin32_NewFrame()
  177. {
  178. ImGuiIO& io = ImGui::GetIO();
  179. IM_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built! It is generally built by the renderer back-end. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame().");
  180. // Setup display size (every frame to accommodate for window resizing)
  181. RECT rect;
  182. ::GetClientRect(g_hWnd, &rect);
  183. io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
  184. if (g_WantUpdateMonitors)
  185. ImGui_ImplWin32_UpdateMonitors();
  186. // Setup time step
  187. INT64 current_time;
  188. ::QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
  189. io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond;
  190. g_Time = current_time;
  191. // Read keyboard modifiers inputs
  192. io.KeyCtrl = (::GetKeyState(VK_CONTROL) & 0x8000) != 0;
  193. io.KeyShift = (::GetKeyState(VK_SHIFT) & 0x8000) != 0;
  194. io.KeyAlt = (::GetKeyState(VK_MENU) & 0x8000) != 0;
  195. io.KeySuper = false;
  196. // io.KeysDown[], io.MousePos, io.MouseDown[], io.MouseWheel: filled by the WndProc handler below.
  197. // Update OS mouse position
  198. ImGui_ImplWin32_UpdateMousePos();
  199. // Update OS mouse cursor with the cursor requested by imgui
  200. ImGuiMouseCursor mouse_cursor = io.MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor();
  201. if (g_LastMouseCursor != mouse_cursor)
  202. {
  203. g_LastMouseCursor = mouse_cursor;
  204. ImGui_ImplWin32_UpdateMouseCursor();
  205. }
  206. }
  207. // Allow compilation with old Windows SDK. MinGW doesn't have default _WIN32_WINNT/WINVER versions.
  208. #ifndef WM_MOUSEHWHEEL
  209. #define WM_MOUSEHWHEEL 0x020E
  210. #endif
  211. // Process Win32 mouse/keyboard inputs.
  212. // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
  213. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
  214. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
  215. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
  216. // 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.
  217. // 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.
  218. IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  219. {
  220. if (ImGui::GetCurrentContext() == NULL)
  221. return 0;
  222. ImGuiIO& io = ImGui::GetIO();
  223. switch (msg)
  224. {
  225. case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK:
  226. case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK:
  227. case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK:
  228. {
  229. int button = 0;
  230. if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) button = 0;
  231. if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) button = 1;
  232. if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) button = 2;
  233. if (!ImGui::IsAnyMouseDown() && ::GetCapture() == NULL)
  234. ::SetCapture(hwnd);
  235. io.MouseDown[button] = true;
  236. return 0;
  237. }
  238. case WM_LBUTTONUP:
  239. case WM_RBUTTONUP:
  240. case WM_MBUTTONUP:
  241. {
  242. int button = 0;
  243. if (msg == WM_LBUTTONUP) button = 0;
  244. if (msg == WM_RBUTTONUP) button = 1;
  245. if (msg == WM_MBUTTONUP) button = 2;
  246. io.MouseDown[button] = false;
  247. if (!ImGui::IsAnyMouseDown() && ::GetCapture() == hwnd)
  248. ::ReleaseCapture();
  249. return 0;
  250. }
  251. case WM_MOUSEWHEEL:
  252. io.MouseWheel += (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA;
  253. return 0;
  254. case WM_MOUSEHWHEEL:
  255. io.MouseWheelH += (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA;
  256. return 0;
  257. case WM_KEYDOWN:
  258. case WM_SYSKEYDOWN:
  259. if (wParam < 256)
  260. io.KeysDown[wParam] = 1;
  261. return 0;
  262. case WM_KEYUP:
  263. case WM_SYSKEYUP:
  264. if (wParam < 256)
  265. io.KeysDown[wParam] = 0;
  266. return 0;
  267. case WM_CHAR:
  268. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  269. if (wParam > 0 && wParam < 0x10000)
  270. io.AddInputCharacter((unsigned short)wParam);
  271. return 0;
  272. case WM_SETCURSOR:
  273. if (LOWORD(lParam) == HTCLIENT && ImGui_ImplWin32_UpdateMouseCursor())
  274. return 1;
  275. return 0;
  276. case WM_DISPLAYCHANGE:
  277. g_WantUpdateMonitors = true;
  278. return 0;
  279. }
  280. return 0;
  281. }
  282. //--------------------------------------------------------------------------------------------------------
  283. // DPI handling
  284. // Those in theory should be simple calls but Windows has multiple ways to handle DPI, and most of them
  285. // require recent Windows versions at runtime or recent Windows SDK at compile-time. Neither we want to depend on.
  286. // So we dynamically select and load those functions to avoid dependencies. This is the scheme successfully
  287. // used by GLFW (from which we borrowed some of the code here) and other applications aiming to be portable.
  288. //---------------------------------------------------------------------------------------------------------
  289. // At this point ImGui_ImplWin32_EnableDpiAwareness() is just a helper called by main.cpp, we don't call it automatically.
  290. //---------------------------------------------------------------------------------------------------------
  291. static BOOL IsWindowsVersionOrGreater(WORD major, WORD minor, WORD sp)
  292. {
  293. OSVERSIONINFOEXW osvi = { sizeof(osvi), major, minor, 0, 0,{ 0 }, sp };
  294. DWORD mask = VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR;
  295. ULONGLONG cond = VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL);
  296. cond = VerSetConditionMask(cond, VER_MINORVERSION, VER_GREATER_EQUAL);
  297. cond = VerSetConditionMask(cond, VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);
  298. return VerifyVersionInfoW(&osvi, mask, cond);
  299. }
  300. #define IsWindows8Point1OrGreater() IsWindowsVersionOrGreater(HIBYTE(0x0602), LOBYTE(0x0602), 0) // _WIN32_WINNT_WINBLUE
  301. #define IsWindows10OrGreater() IsWindowsVersionOrGreater(HIBYTE(0x0A00), LOBYTE(0x0A00), 0) // _WIN32_WINNT_WIN10
  302. #ifndef DPI_ENUMS_DECLARED
  303. typedef enum { PROCESS_DPI_UNAWARE = 0, PROCESS_SYSTEM_DPI_AWARE = 1, PROCESS_PER_MONITOR_DPI_AWARE = 2 } PROCESS_DPI_AWARENESS;
  304. typedef enum { MDT_EFFECTIVE_DPI = 0, MDT_ANGULAR_DPI = 1, MDT_RAW_DPI = 2, MDT_DEFAULT = MDT_EFFECTIVE_DPI } MONITOR_DPI_TYPE;
  305. #endif
  306. #ifndef _DPI_AWARENESS_CONTEXTS_
  307. DECLARE_HANDLE(DPI_AWARENESS_CONTEXT);
  308. #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE (DPI_AWARENESS_CONTEXT)-3
  309. #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 (DPI_AWARENESS_CONTEXT)-4
  310. #endif
  311. typedef HRESULT(WINAPI * PFN_SetProcessDpiAwareness)(PROCESS_DPI_AWARENESS); // Shcore.lib+dll, Windows 8.1
  312. typedef HRESULT(WINAPI * PFN_GetDpiForMonitor)(HMONITOR, MONITOR_DPI_TYPE, UINT*, UINT*); // Shcore.lib+dll, Windows 8.1
  313. typedef DPI_AWARENESS_CONTEXT(WINAPI * PFN_SetThreadDpiAwarenessContext)(DPI_AWARENESS_CONTEXT); // User32.lib+dll, Windows 10 v1607 (Creators Update)
  314. void ImGui_ImplWin32_EnableDpiAwareness()
  315. {
  316. // if (IsWindows10OrGreater()) // FIXME-DPI: This needs a manifest to succeed. Instead we try to grab the function pointer.
  317. {
  318. static HINSTANCE user32_dll = ::LoadLibraryA("user32.dll"); // Reference counted per-process
  319. if (PFN_SetThreadDpiAwarenessContext SetThreadDpiAwarenessContextFn = (PFN_SetThreadDpiAwarenessContext)::GetProcAddress(user32_dll, "SetThreadDpiAwarenessContext"))
  320. {
  321. SetThreadDpiAwarenessContextFn(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
  322. return;
  323. }
  324. }
  325. if (IsWindows8Point1OrGreater())
  326. {
  327. static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process
  328. if (PFN_SetProcessDpiAwareness SetProcessDpiAwarenessFn = (PFN_SetProcessDpiAwareness)::GetProcAddress(shcore_dll, "SetProcessDpiAwareness"))
  329. SetProcessDpiAwarenessFn(PROCESS_PER_MONITOR_DPI_AWARE);
  330. }
  331. else
  332. {
  333. SetProcessDPIAware();
  334. }
  335. }
  336. float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor)
  337. {
  338. UINT xdpi = 96, ydpi = 96;
  339. if (::IsWindows8Point1OrGreater())
  340. {
  341. static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process
  342. if (PFN_GetDpiForMonitor GetDpiForMonitorFn = (PFN_GetDpiForMonitor)::GetProcAddress(shcore_dll, "GetDpiForMonitor"))
  343. GetDpiForMonitorFn((HMONITOR)monitor, MDT_EFFECTIVE_DPI, &xdpi, &ydpi);
  344. }
  345. else
  346. {
  347. const HDC dc = ::GetDC(NULL);
  348. xdpi = ::GetDeviceCaps(dc, LOGPIXELSX);
  349. ydpi = ::GetDeviceCaps(dc, LOGPIXELSY);
  350. ::ReleaseDC(NULL, dc);
  351. }
  352. IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert!
  353. return xdpi / 96.0f;
  354. }
  355. float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd)
  356. {
  357. HMONITOR monitor = ::MonitorFromWindow((HWND)hwnd, MONITOR_DEFAULTTONEAREST);
  358. return ImGui_ImplWin32_GetDpiScaleForMonitor(monitor);
  359. }
  360. //--------------------------------------------------------------------------------------------------------
  361. // IME (Input Method Editor) basic support for e.g. Asian language users
  362. //--------------------------------------------------------------------------------------------------------
  363. #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(__GNUC__)
  364. #define HAS_WIN32_IME 1
  365. #include <imm.h>
  366. #ifdef _MSC_VER
  367. #pragma comment(lib, "imm32")
  368. #endif
  369. static void ImGui_ImplWin32_SetImeInputPos(ImGuiViewport* viewport, ImVec2 pos)
  370. {
  371. COMPOSITIONFORM cf = { CFS_FORCE_POSITION,{ (LONG)(pos.x - viewport->Pos.x), (LONG)(pos.y - viewport->Pos.y) },{ 0, 0, 0, 0 } };
  372. if (HWND hwnd = (HWND)viewport->PlatformHandle)
  373. if (HIMC himc = ::ImmGetContext(hwnd))
  374. {
  375. ::ImmSetCompositionWindow(himc, &cf);
  376. ::ImmReleaseContext(hwnd, himc);
  377. }
  378. }
  379. #else
  380. #define HAS_WIN32_IME 0
  381. #endif
  382. //--------------------------------------------------------------------------------------------------------
  383. // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
  384. // This is an _advanced_ and _optional_ feature, allowing the back-end to create and handle multiple viewports simultaneously.
  385. // 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..
  386. //--------------------------------------------------------------------------------------------------------
  387. struct ImGuiViewportDataWin32
  388. {
  389. HWND Hwnd;
  390. bool HwndOwned;
  391. DWORD DwStyle;
  392. DWORD DwExStyle;
  393. ImGuiViewportDataWin32() { Hwnd = NULL; HwndOwned = false; DwStyle = DwExStyle = 0; }
  394. ~ImGuiViewportDataWin32() { IM_ASSERT(Hwnd == NULL); }
  395. };
  396. static void ImGui_ImplWin32_GetWin32StyleFromViewportFlags(ImGuiViewportFlags flags, DWORD* out_style, DWORD* out_ex_style)
  397. {
  398. if (flags & ImGuiViewportFlags_NoDecoration)
  399. *out_style = WS_POPUP;
  400. else
  401. *out_style = WS_OVERLAPPEDWINDOW;
  402. if (flags & ImGuiViewportFlags_NoTaskBarIcon)
  403. *out_ex_style = WS_EX_TOOLWINDOW;
  404. else
  405. *out_ex_style = WS_EX_APPWINDOW;
  406. if (flags & ImGuiViewportFlags_TopMost)
  407. *out_ex_style |= WS_EX_TOPMOST;
  408. }
  409. static void ImGui_ImplWin32_CreateWindow(ImGuiViewport* viewport)
  410. {
  411. ImGuiViewportDataWin32* data = IM_NEW(ImGuiViewportDataWin32)();
  412. viewport->PlatformUserData = data;
  413. // Select style and parent window
  414. ImGui_ImplWin32_GetWin32StyleFromViewportFlags(viewport->Flags, &data->DwStyle, &data->DwExStyle);
  415. HWND parent_window = NULL;
  416. if (viewport->ParentViewportId != 0)
  417. if (ImGuiViewport* parent_viewport = ImGui::FindViewportByID(viewport->ParentViewportId))
  418. parent_window = (HWND)parent_viewport->PlatformHandle;
  419. // Create window
  420. RECT rect = { (LONG)viewport->Pos.x, (LONG)viewport->Pos.y, (LONG)(viewport->Pos.x + viewport->Size.x), (LONG)(viewport->Pos.y + viewport->Size.y) };
  421. ::AdjustWindowRectEx(&rect, data->DwStyle, FALSE, data->DwExStyle);
  422. data->Hwnd = ::CreateWindowEx(
  423. data->DwExStyle, _T("ImGui Platform"), _T("Untitled"), data->DwStyle, // Style, class name, window name
  424. rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, // Window area
  425. parent_window, NULL, ::GetModuleHandle(NULL), NULL); // Parent window, Menu, Instance, Param
  426. data->HwndOwned = true;
  427. viewport->PlatformRequestResize = false;
  428. viewport->PlatformHandle = data->Hwnd;
  429. }
  430. static void ImGui_ImplWin32_DestroyWindow(ImGuiViewport* viewport)
  431. {
  432. if (ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData)
  433. {
  434. if (::GetCapture() == data->Hwnd)
  435. {
  436. // Transfer capture so if we started dragging from a window that later disappears, we'll still receive the MOUSEUP event.
  437. ::ReleaseCapture();
  438. ::SetCapture(g_hWnd);
  439. }
  440. if (data->Hwnd && data->HwndOwned)
  441. ::DestroyWindow(data->Hwnd);
  442. data->Hwnd = NULL;
  443. IM_DELETE(data);
  444. }
  445. viewport->PlatformUserData = viewport->PlatformHandle = NULL;
  446. }
  447. static void ImGui_ImplWin32_ShowWindow(ImGuiViewport* viewport)
  448. {
  449. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  450. IM_ASSERT(data->Hwnd != 0);
  451. if (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing)
  452. ::ShowWindow(data->Hwnd, SW_SHOWNA);
  453. else
  454. ::ShowWindow(data->Hwnd, SW_SHOW);
  455. }
  456. static void ImGui_ImplWin32_UpdateWindow(ImGuiViewport* viewport)
  457. {
  458. // (Optional) Update Win32 style if it changed _after_ creation.
  459. // Generally they won't change unless configuration flags are changed, but advanced uses (such as manually rewriting viewport flags) make this useful.
  460. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  461. IM_ASSERT(data->Hwnd != 0);
  462. DWORD new_style;
  463. DWORD new_ex_style;
  464. ImGui_ImplWin32_GetWin32StyleFromViewportFlags(viewport->Flags, &new_style, &new_ex_style);
  465. // Only reapply the flags that have been changed from our point of view (as other flags are being modified by Windows)
  466. if (data->DwStyle != new_style || data->DwExStyle != new_ex_style)
  467. {
  468. data->DwStyle = new_style;
  469. data->DwExStyle = new_ex_style;
  470. ::SetWindowLong(data->Hwnd, GWL_STYLE, data->DwStyle);
  471. ::SetWindowLong(data->Hwnd, GWL_EXSTYLE, data->DwExStyle);
  472. RECT rect = { (LONG)viewport->Pos.x, (LONG)viewport->Pos.y, (LONG)(viewport->Pos.x + viewport->Size.x), (LONG)(viewport->Pos.y + viewport->Size.y) };
  473. ::AdjustWindowRectEx(&rect, data->DwStyle, FALSE, data->DwExStyle); // Client to Screen
  474. ::SetWindowPos(data->Hwnd, NULL, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
  475. ::ShowWindow(data->Hwnd, SW_SHOWNA); // This is necessary when we alter the style
  476. viewport->PlatformRequestMove = viewport->PlatformRequestResize = true;
  477. }
  478. }
  479. static ImVec2 ImGui_ImplWin32_GetWindowPos(ImGuiViewport* viewport)
  480. {
  481. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  482. IM_ASSERT(data->Hwnd != 0);
  483. POINT pos = { 0, 0 };
  484. ::ClientToScreen(data->Hwnd, &pos);
  485. return ImVec2((float)pos.x, (float)pos.y);
  486. }
  487. static void ImGui_ImplWin32_SetWindowPos(ImGuiViewport* viewport, ImVec2 pos)
  488. {
  489. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  490. IM_ASSERT(data->Hwnd != 0);
  491. RECT rect = { (LONG)pos.x, (LONG)pos.y, (LONG)pos.x, (LONG)pos.y };
  492. ::AdjustWindowRectEx(&rect, data->DwStyle, FALSE, data->DwExStyle);
  493. ::SetWindowPos(data->Hwnd, NULL, rect.left, rect.top, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
  494. }
  495. static ImVec2 ImGui_ImplWin32_GetWindowSize(ImGuiViewport* viewport)
  496. {
  497. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  498. IM_ASSERT(data->Hwnd != 0);
  499. RECT rect;
  500. ::GetClientRect(data->Hwnd, &rect);
  501. return ImVec2(float(rect.right - rect.left), float(rect.bottom - rect.top));
  502. }
  503. static void ImGui_ImplWin32_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
  504. {
  505. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  506. IM_ASSERT(data->Hwnd != 0);
  507. RECT rect = { 0, 0, (LONG)size.x, (LONG)size.y };
  508. ::AdjustWindowRectEx(&rect, data->DwStyle, FALSE, data->DwExStyle); // Client to Screen
  509. ::SetWindowPos(data->Hwnd, NULL, 0, 0, rect.right - rect.left, rect.bottom - rect.top, SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE);
  510. }
  511. static void ImGui_ImplWin32_SetWindowFocus(ImGuiViewport* viewport)
  512. {
  513. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  514. IM_ASSERT(data->Hwnd != 0);
  515. ::BringWindowToTop(data->Hwnd);
  516. ::SetForegroundWindow(data->Hwnd);
  517. ::SetFocus(data->Hwnd);
  518. }
  519. static bool ImGui_ImplWin32_GetWindowFocus(ImGuiViewport* viewport)
  520. {
  521. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  522. IM_ASSERT(data->Hwnd != 0);
  523. return ::GetActiveWindow() == data->Hwnd;
  524. }
  525. static bool ImGui_ImplWin32_GetWindowMinimized(ImGuiViewport* viewport)
  526. {
  527. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  528. IM_ASSERT(data->Hwnd != 0);
  529. return ::IsIconic(data->Hwnd) != 0;
  530. }
  531. static void ImGui_ImplWin32_SetWindowTitle(ImGuiViewport* viewport, const char* title)
  532. {
  533. // ::SetWindowTextA() doesn't properly handle UTF-8 so we explicitely convert our string.
  534. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  535. IM_ASSERT(data->Hwnd != 0);
  536. int n = ::MultiByteToWideChar(CP_UTF8, 0, title, -1, NULL, 0);
  537. ImVector<wchar_t> title_w;
  538. title_w.resize(n);
  539. ::MultiByteToWideChar(CP_UTF8, 0, title, -1, title_w.Data, n);
  540. ::SetWindowTextW(data->Hwnd, title_w.Data);
  541. }
  542. static void ImGui_ImplWin32_SetWindowAlpha(ImGuiViewport* viewport, float alpha)
  543. {
  544. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  545. IM_ASSERT(data->Hwnd != 0);
  546. IM_ASSERT(alpha >= 0.0f && alpha <= 1.0f);
  547. if (alpha < 1.0f)
  548. {
  549. DWORD style = ::GetWindowLongW(data->Hwnd, GWL_EXSTYLE) | WS_EX_LAYERED;
  550. ::SetWindowLongW(data->Hwnd, GWL_EXSTYLE, style);
  551. ::SetLayeredWindowAttributes(data->Hwnd, 0, (BYTE)(255 * alpha), LWA_ALPHA);
  552. }
  553. else
  554. {
  555. DWORD style = ::GetWindowLongW(data->Hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED;
  556. ::SetWindowLongW(data->Hwnd, GWL_EXSTYLE, style);
  557. }
  558. }
  559. static float ImGui_ImplWin32_GetWindowDpiScale(ImGuiViewport* viewport)
  560. {
  561. ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
  562. IM_ASSERT(data->Hwnd != 0);
  563. return ImGui_ImplWin32_GetDpiScaleForHwnd(data->Hwnd);
  564. }
  565. // FIXME-DPI: Testing DPI related ideas
  566. static void ImGui_ImplWin32_OnChangedViewport(ImGuiViewport* viewport)
  567. {
  568. (void)viewport;
  569. #if 0
  570. ImGuiStyle default_style;
  571. //default_style.WindowPadding = ImVec2(0, 0);
  572. //default_style.WindowBorderSize = 0.0f;
  573. //default_style.ItemSpacing.y = 3.0f;
  574. //default_style.FramePadding = ImVec2(0, 0);
  575. default_style.ScaleAllSizes(viewport->DpiScale);
  576. ImGuiStyle& style = ImGui::GetStyle();
  577. style = default_style;
  578. #endif
  579. }
  580. static LRESULT CALLBACK ImGui_ImplWin32_WndProcHandler_PlatformWindow(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  581. {
  582. if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
  583. return true;
  584. if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle((void*)hWnd))
  585. {
  586. switch (msg)
  587. {
  588. case WM_CLOSE:
  589. viewport->PlatformRequestClose = true;
  590. return 0;
  591. case WM_MOVE:
  592. viewport->PlatformRequestMove = true;
  593. break;
  594. case WM_SIZE:
  595. viewport->PlatformRequestResize = true;
  596. break;
  597. case WM_NCHITTEST:
  598. // Let mouse pass-through the window. This will allow the back-end to set io.MouseHoveredViewport properly (which is OPTIONAL).
  599. // The ImGuiViewportFlags_NoInputs flag is set while dragging a viewport, as want to detect the window behind the one we are dragging.
  600. // If you cannot easily access those viewport flags from your windowing/event code: you may manually synchronize its state e.g. in
  601. // your main loop after calling UpdatePlatformWindows(). Iterate all viewports/platform windows and pass the flag to your windowing system.
  602. if (viewport->Flags & ImGuiViewportFlags_NoInputs)
  603. return HTTRANSPARENT;
  604. break;
  605. }
  606. }
  607. return DefWindowProc(hWnd, msg, wParam, lParam);
  608. }
  609. static BOOL CALLBACK ImGui_ImplWin32_UpdateMonitors_EnumFunc(HMONITOR monitor, HDC, LPRECT, LPARAM)
  610. {
  611. MONITORINFO info = { 0 };
  612. info.cbSize = sizeof(MONITORINFO);
  613. if (!::GetMonitorInfo(monitor, &info))
  614. return TRUE;
  615. ImGuiPlatformMonitor imgui_monitor;
  616. imgui_monitor.MainPos = ImVec2((float)info.rcMonitor.left, (float)info.rcMonitor.top);
  617. imgui_monitor.MainSize = ImVec2((float)(info.rcMonitor.right - info.rcMonitor.left), (float)(info.rcMonitor.bottom - info.rcMonitor.top));
  618. imgui_monitor.WorkPos = ImVec2((float)info.rcWork.left, (float)info.rcWork.top);
  619. imgui_monitor.WorkSize = ImVec2((float)(info.rcWork.right - info.rcWork.left), (float)(info.rcWork.bottom - info.rcWork.top));
  620. imgui_monitor.DpiScale = ImGui_ImplWin32_GetDpiScaleForMonitor(monitor);
  621. ImGuiPlatformIO& io = ImGui::GetPlatformIO();
  622. if (info.dwFlags & MONITORINFOF_PRIMARY)
  623. io.Monitors.push_front(imgui_monitor);
  624. else
  625. io.Monitors.push_back(imgui_monitor);
  626. return TRUE;
  627. }
  628. static void ImGui_ImplWin32_UpdateMonitors()
  629. {
  630. ImGui::GetPlatformIO().Monitors.resize(0);
  631. ::EnumDisplayMonitors(NULL, NULL, ImGui_ImplWin32_UpdateMonitors_EnumFunc, NULL);
  632. g_WantUpdateMonitors = false;
  633. }
  634. static void ImGui_ImplWin32_InitPlatformInterface()
  635. {
  636. WNDCLASSEX wcex;
  637. wcex.cbSize = sizeof(WNDCLASSEX);
  638. wcex.style = CS_HREDRAW | CS_VREDRAW;
  639. wcex.lpfnWndProc = ImGui_ImplWin32_WndProcHandler_PlatformWindow;
  640. wcex.cbClsExtra = 0;
  641. wcex.cbWndExtra = 0;
  642. wcex.hInstance = ::GetModuleHandle(NULL);
  643. wcex.hIcon = NULL;
  644. wcex.hCursor = NULL;
  645. wcex.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1);
  646. wcex.lpszMenuName = NULL;
  647. wcex.lpszClassName = _T("ImGui Platform");
  648. wcex.hIconSm = NULL;
  649. ::RegisterClassEx(&wcex);
  650. ImGui_ImplWin32_UpdateMonitors();
  651. // Register platform interface (will be coupled with a renderer interface)
  652. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  653. platform_io.Platform_CreateWindow = ImGui_ImplWin32_CreateWindow;
  654. platform_io.Platform_DestroyWindow = ImGui_ImplWin32_DestroyWindow;
  655. platform_io.Platform_ShowWindow = ImGui_ImplWin32_ShowWindow;
  656. platform_io.Platform_SetWindowPos = ImGui_ImplWin32_SetWindowPos;
  657. platform_io.Platform_GetWindowPos = ImGui_ImplWin32_GetWindowPos;
  658. platform_io.Platform_SetWindowSize = ImGui_ImplWin32_SetWindowSize;
  659. platform_io.Platform_GetWindowSize = ImGui_ImplWin32_GetWindowSize;
  660. platform_io.Platform_SetWindowFocus = ImGui_ImplWin32_SetWindowFocus;
  661. platform_io.Platform_GetWindowFocus = ImGui_ImplWin32_GetWindowFocus;
  662. platform_io.Platform_GetWindowMinimized = ImGui_ImplWin32_GetWindowMinimized;
  663. platform_io.Platform_SetWindowTitle = ImGui_ImplWin32_SetWindowTitle;
  664. platform_io.Platform_SetWindowAlpha = ImGui_ImplWin32_SetWindowAlpha;
  665. platform_io.Platform_UpdateWindow = ImGui_ImplWin32_UpdateWindow;
  666. platform_io.Platform_GetWindowDpiScale = ImGui_ImplWin32_GetWindowDpiScale; // FIXME-DPI
  667. platform_io.Platform_OnChangedViewport = ImGui_ImplWin32_OnChangedViewport; // FIXME-DPI
  668. #if HAS_WIN32_IME
  669. platform_io.Platform_SetImeInputPos = ImGui_ImplWin32_SetImeInputPos;
  670. #endif
  671. // Register main window handle (which is owned by the main application, not by us)
  672. ImGuiViewport* main_viewport = ImGui::GetMainViewport();
  673. ImGuiViewportDataWin32* data = IM_NEW(ImGuiViewportDataWin32)();
  674. data->Hwnd = g_hWnd;
  675. data->HwndOwned = false;
  676. main_viewport->PlatformUserData = data;
  677. main_viewport->PlatformHandle = (void*)g_hWnd;
  678. }
  679. static void ImGui_ImplWin32_ShutdownPlatformInterface()
  680. {
  681. ::UnregisterClass(_T("ImGui Platform"), ::GetModuleHandle(NULL));
  682. }