RmlUi_Backend_Win32_VK.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019-2023 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "RmlUi_Backend.h"
  29. #include "RmlUi_Include_Windows.h"
  30. #include "RmlUi_Platform_Win32.h"
  31. #include "RmlUi_Renderer_VK.h"
  32. #include <RmlUi/Config/Config.h>
  33. #include <RmlUi/Core/Context.h>
  34. #include <RmlUi/Core/Core.h>
  35. #include <RmlUi/Core/Input.h>
  36. #include <RmlUi/Core/Log.h>
  37. #include <RmlUi/Core/Profiling.h>
  38. /**
  39. High DPI support using Windows Per Monitor V2 DPI awareness.
  40. Requires Windows 10, version 1703.
  41. */
  42. #ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
  43. #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ((HANDLE)-4)
  44. #endif
  45. #ifndef WM_DPICHANGED
  46. #define WM_DPICHANGED 0x02E0
  47. #endif
  48. // Declare pointers to the DPI aware Windows API functions.
  49. using ProcSetProcessDpiAwarenessContext = BOOL(WINAPI*)(HANDLE value);
  50. using ProcGetDpiForWindow = UINT(WINAPI*)(HWND hwnd);
  51. using ProcAdjustWindowRectExForDpi = BOOL(WINAPI*)(LPRECT lpRect, DWORD dwStyle, BOOL bMenu, DWORD dwExStyle, UINT dpi);
  52. static bool has_dpi_support = false;
  53. static ProcSetProcessDpiAwarenessContext procSetProcessDpiAwarenessContext = NULL;
  54. static ProcGetDpiForWindow procGetDpiForWindow = NULL;
  55. static ProcAdjustWindowRectExForDpi procAdjustWindowRectExForDpi = NULL;
  56. // Make ourselves DPI aware on supported Windows versions.
  57. static void InitializeDpiSupport()
  58. {
  59. // Cast function pointers to void* first for MinGW not to emit errors.
  60. procSetProcessDpiAwarenessContext =
  61. (ProcSetProcessDpiAwarenessContext)(void*)GetProcAddress(GetModuleHandle(TEXT("User32.dll")), "SetProcessDpiAwarenessContext");
  62. procGetDpiForWindow = (ProcGetDpiForWindow)(void*)GetProcAddress(GetModuleHandle(TEXT("User32.dll")), "GetDpiForWindow");
  63. procAdjustWindowRectExForDpi =
  64. (ProcAdjustWindowRectExForDpi)(void*)GetProcAddress(GetModuleHandle(TEXT("User32.dll")), "AdjustWindowRectExForDpi");
  65. if (!has_dpi_support && procSetProcessDpiAwarenessContext != NULL && procGetDpiForWindow != NULL && procAdjustWindowRectExForDpi != NULL)
  66. {
  67. // Activate Per Monitor V2.
  68. if (procSetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2))
  69. has_dpi_support = true;
  70. }
  71. }
  72. static UINT GetWindowDpi(HWND window_handle)
  73. {
  74. if (has_dpi_support)
  75. {
  76. UINT dpi = procGetDpiForWindow(window_handle);
  77. if (dpi != 0)
  78. return dpi;
  79. }
  80. return USER_DEFAULT_SCREEN_DPI;
  81. }
  82. static float GetDensityIndependentPixelRatio(HWND window_handle)
  83. {
  84. return float(GetWindowDpi(window_handle)) / float(USER_DEFAULT_SCREEN_DPI);
  85. }
  86. // Create the window but don't show it yet. Returns the pixel size of the window, which may be different than the passed size due to DPI settings.
  87. static HWND InitializeWindow(HINSTANCE instance_handle, const std::wstring& name, int& inout_width, int& inout_height, bool allow_resize);
  88. // Create the Win32 Vulkan surface.
  89. static bool CreateVulkanSurface(VkInstance instance, VkSurfaceKHR* out_surface);
  90. /**
  91. Global data used by this backend.
  92. Lifetime governed by the calls to Backend::Initialize() and Backend::Shutdown().
  93. */
  94. struct BackendData {
  95. SystemInterface_Win32 system_interface;
  96. RenderInterface_VK render_interface;
  97. TextInputMethodEditor_Win32 text_input_method_editor;
  98. HINSTANCE instance_handle = nullptr;
  99. std::wstring instance_name;
  100. HWND window_handle = nullptr;
  101. bool context_dimensions_dirty = true;
  102. Rml::Vector2i window_dimensions;
  103. bool running = true;
  104. // Arguments set during event processing and nulled otherwise.
  105. Rml::Context* context = nullptr;
  106. KeyDownCallback key_down_callback = nullptr;
  107. };
  108. static Rml::UniquePtr<BackendData> data;
  109. bool Backend::Initialize(const char* window_name, int width, int height, bool allow_resize)
  110. {
  111. RMLUI_ASSERT(!data);
  112. const std::wstring name = RmlWin32::ConvertToUTF16(Rml::String(window_name));
  113. data = Rml::MakeUnique<BackendData>();
  114. data->instance_handle = GetModuleHandle(nullptr);
  115. data->instance_name = name;
  116. InitializeDpiSupport();
  117. // Initialize the window but don't show it yet.
  118. HWND window_handle = InitializeWindow(data->instance_handle, name, width, height, allow_resize);
  119. if (!window_handle)
  120. return false;
  121. data->window_handle = window_handle;
  122. Rml::Vector<const char*> extensions;
  123. extensions.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
  124. extensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
  125. if (!data->render_interface.Initialize(std::move(extensions), CreateVulkanSurface))
  126. {
  127. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to initialize Vulkan render interface");
  128. ::CloseWindow(window_handle);
  129. data.reset();
  130. return false;
  131. }
  132. data->system_interface.SetWindow(window_handle);
  133. data->render_interface.SetViewport(width, height);
  134. // Now we are ready to show the window.
  135. ::ShowWindow(window_handle, SW_SHOW);
  136. ::SetForegroundWindow(window_handle);
  137. ::SetFocus(window_handle);
  138. // Provide a backend-specific text input handler to manage the IME.
  139. Rml::SetTextInputHandler(&data->text_input_method_editor);
  140. return true;
  141. }
  142. void Backend::Shutdown()
  143. {
  144. RMLUI_ASSERT(data);
  145. // As we forcefully override the global text input handler, we must reset it before the data is destroyed to avoid any potential use-after-free.
  146. if (Rml::GetTextInputHandler() == &data->text_input_method_editor)
  147. Rml::SetTextInputHandler(nullptr);
  148. data->render_interface.Shutdown();
  149. ::DestroyWindow(data->window_handle);
  150. ::UnregisterClassW((LPCWSTR)data->instance_name.data(), data->instance_handle);
  151. data.reset();
  152. }
  153. Rml::SystemInterface* Backend::GetSystemInterface()
  154. {
  155. RMLUI_ASSERT(data);
  156. return &data->system_interface;
  157. }
  158. Rml::RenderInterface* Backend::GetRenderInterface()
  159. {
  160. RMLUI_ASSERT(data);
  161. return &data->render_interface;
  162. }
  163. static bool NextEvent(MSG& message, UINT timeout)
  164. {
  165. if (timeout != 0)
  166. {
  167. UINT_PTR timer_id = SetTimer(NULL, 0, timeout, NULL);
  168. BOOL res = GetMessage(&message, NULL, 0, 0);
  169. KillTimer(NULL, timer_id);
  170. if (message.message != WM_TIMER || message.hwnd != nullptr || message.wParam != timer_id)
  171. return res;
  172. }
  173. return PeekMessage(&message, nullptr, 0, 0, PM_REMOVE);
  174. }
  175. bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_callback, bool power_save)
  176. {
  177. RMLUI_ASSERT(data && context);
  178. // The initial window size may have been affected by system DPI settings, apply the actual pixel size and dp-ratio to the context.
  179. if (data->context_dimensions_dirty)
  180. {
  181. data->context_dimensions_dirty = false;
  182. const float dp_ratio = GetDensityIndependentPixelRatio(data->window_handle);
  183. context->SetDimensions(data->window_dimensions);
  184. context->SetDensityIndependentPixelRatio(dp_ratio);
  185. }
  186. data->context = context;
  187. data->key_down_callback = key_down_callback;
  188. MSG message;
  189. // Process events.
  190. bool has_message = NextEvent(message, power_save ? static_cast<int>(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0) * 1000.0) : 0);
  191. while (has_message || !data->render_interface.IsSwapchainValid())
  192. {
  193. if (has_message)
  194. {
  195. // Dispatch the message to our local event handler below.
  196. TranslateMessage(&message);
  197. DispatchMessage(&message);
  198. }
  199. // In some situations the swapchain may become invalid, such as when the window is minimized. In this state the renderer cannot accept any
  200. // render calls. Since we don't have full control over the main loop here we may risk calls to Context::Render if we were to return. Instead,
  201. // we trap the application inside this loop until we are able to recreate the swapchain and render again.
  202. if (!data->render_interface.IsSwapchainValid())
  203. data->render_interface.RecreateSwapchain();
  204. has_message = NextEvent(message, 0);
  205. }
  206. data->context = nullptr;
  207. data->key_down_callback = nullptr;
  208. return data->running;
  209. }
  210. void Backend::RequestExit()
  211. {
  212. RMLUI_ASSERT(data);
  213. data->running = false;
  214. }
  215. void Backend::BeginFrame()
  216. {
  217. RMLUI_ASSERT(data);
  218. data->render_interface.BeginFrame();
  219. }
  220. void Backend::PresentFrame()
  221. {
  222. RMLUI_ASSERT(data);
  223. data->render_interface.EndFrame();
  224. // Optional, used to mark frames during performance profiling.
  225. RMLUI_FrameMark;
  226. }
  227. // Local event handler for window and input events.
  228. static LRESULT CALLBACK WindowProcedureHandler(HWND window_handle, UINT message, WPARAM w_param, LPARAM l_param)
  229. {
  230. RMLUI_ASSERT(data);
  231. switch (message)
  232. {
  233. case WM_CLOSE:
  234. {
  235. data->running = false;
  236. return 0;
  237. }
  238. break;
  239. case WM_SIZE:
  240. {
  241. const int width = LOWORD(l_param);
  242. const int height = HIWORD(l_param);
  243. data->window_dimensions.x = width;
  244. data->window_dimensions.y = height;
  245. if (data->context)
  246. {
  247. data->render_interface.SetViewport(width, height);
  248. data->context->SetDimensions(data->window_dimensions);
  249. }
  250. return 0;
  251. }
  252. break;
  253. case WM_DPICHANGED:
  254. {
  255. RECT* new_pos = (RECT*)l_param;
  256. SetWindowPos(window_handle, NULL, new_pos->left, new_pos->top, new_pos->right - new_pos->left, new_pos->bottom - new_pos->top,
  257. SWP_NOZORDER | SWP_NOACTIVATE);
  258. if (data->context && has_dpi_support)
  259. data->context->SetDensityIndependentPixelRatio(GetDensityIndependentPixelRatio(window_handle));
  260. return 0;
  261. }
  262. break;
  263. case WM_KEYDOWN:
  264. {
  265. // Override the default key event callback to add global shortcuts for the samples.
  266. Rml::Context* context = data->context;
  267. KeyDownCallback key_down_callback = data->key_down_callback;
  268. const Rml::Input::KeyIdentifier rml_key = RmlWin32::ConvertKey((int)w_param);
  269. const int rml_modifier = RmlWin32::GetKeyModifierState();
  270. const float native_dp_ratio = GetDensityIndependentPixelRatio(window_handle);
  271. // See if we have any global shortcuts that take priority over the context.
  272. if (key_down_callback && !key_down_callback(context, rml_key, rml_modifier, native_dp_ratio, true))
  273. return 0;
  274. // Otherwise, hand the event over to the context by calling the input handler as normal.
  275. if (!RmlWin32::WindowProcedure(context, data->text_input_method_editor, window_handle, message, w_param, l_param))
  276. return 0;
  277. // The key was not consumed by the context either, try keyboard shortcuts of lower priority.
  278. if (key_down_callback && !key_down_callback(context, rml_key, rml_modifier, native_dp_ratio, false))
  279. return 0;
  280. return 0;
  281. }
  282. break;
  283. default:
  284. {
  285. // Submit it to the platform handler for default input handling.
  286. if (!RmlWin32::WindowProcedure(data->context, data->text_input_method_editor, window_handle, message, w_param, l_param))
  287. return 0;
  288. }
  289. break;
  290. }
  291. // All unhandled messages go to DefWindowProc.
  292. return DefWindowProc(window_handle, message, w_param, l_param);
  293. }
  294. static HWND InitializeWindow(HINSTANCE instance_handle, const std::wstring& name, int& inout_width, int& inout_height, bool allow_resize)
  295. {
  296. // Fill out the window class struct.
  297. WNDCLASSW window_class;
  298. window_class.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
  299. window_class.lpfnWndProc = &WindowProcedureHandler; // Attach our local event handler.
  300. window_class.cbClsExtra = 0;
  301. window_class.cbWndExtra = 0;
  302. window_class.hInstance = instance_handle;
  303. window_class.hIcon = LoadIcon(nullptr, IDI_WINLOGO);
  304. window_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
  305. window_class.hbrBackground = nullptr;
  306. window_class.lpszMenuName = nullptr;
  307. window_class.lpszClassName = name.data();
  308. if (!RegisterClassW(&window_class))
  309. {
  310. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to register window class");
  311. return nullptr;
  312. }
  313. HWND window_handle = CreateWindowExW(WS_EX_APPWINDOW | WS_EX_WINDOWEDGE,
  314. name.data(), // Window class name.
  315. name.data(), WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW, 0, 0, // Window position.
  316. 0, 0, // Window size.
  317. nullptr, nullptr, instance_handle, nullptr);
  318. if (!window_handle)
  319. {
  320. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to create window");
  321. return nullptr;
  322. }
  323. UINT window_dpi = GetWindowDpi(window_handle);
  324. inout_width = (inout_width * (int)window_dpi) / USER_DEFAULT_SCREEN_DPI;
  325. inout_height = (inout_height * (int)window_dpi) / USER_DEFAULT_SCREEN_DPI;
  326. DWORD style = (allow_resize ? WS_OVERLAPPEDWINDOW : (WS_OVERLAPPEDWINDOW & ~WS_SIZEBOX & ~WS_MAXIMIZEBOX));
  327. DWORD extended_style = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
  328. // Adjust the window size to take the edges into account.
  329. RECT window_rect;
  330. window_rect.top = 0;
  331. window_rect.left = 0;
  332. window_rect.right = inout_width;
  333. window_rect.bottom = inout_height;
  334. if (has_dpi_support)
  335. procAdjustWindowRectExForDpi(&window_rect, style, FALSE, extended_style, window_dpi);
  336. else
  337. AdjustWindowRectEx(&window_rect, style, FALSE, extended_style);
  338. SetWindowLong(window_handle, GWL_EXSTYLE, extended_style);
  339. SetWindowLong(window_handle, GWL_STYLE, style);
  340. // Resize the window and center it on the screen.
  341. Rml::Vector2i screen_size = {GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)};
  342. Rml::Vector2i window_size = {int(window_rect.right - window_rect.left), int(window_rect.bottom - window_rect.top)};
  343. Rml::Vector2i window_pos = Rml::Math::Max((screen_size - window_size) / 2, Rml::Vector2i(0));
  344. SetWindowPos(window_handle, HWND_TOP, window_pos.x, window_pos.y, window_size.x, window_size.y, SWP_NOACTIVATE);
  345. return window_handle;
  346. }
  347. bool CreateVulkanSurface(VkInstance instance, VkSurfaceKHR* out_surface)
  348. {
  349. VkWin32SurfaceCreateInfoKHR info = {};
  350. info.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
  351. info.hinstance = GetModuleHandle(NULL);
  352. info.hwnd = data->window_handle;
  353. VkResult status = vkCreateWin32SurfaceKHR(instance, &info, nullptr, out_surface);
  354. bool result = (status == VK_SUCCESS);
  355. RMLUI_VK_ASSERTMSG(result, "Failed to create Win32 Vulkan surface");
  356. return result;
  357. }