imgui_impl_win32.cpp 29 KB

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