RmlUi_Backend_Win32_GL2.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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_GL2.h"
  32. #include <RmlUi/Core/Context.h>
  33. #include <RmlUi/Core/Core.h>
  34. #include <RmlUi/Core/Input.h>
  35. #include <RmlUi/Core/Log.h>
  36. #include <RmlUi/Core/Profiling.h>
  37. /**
  38. High DPI support using Windows Per Monitor V2 DPI awareness.
  39. Requires Windows 10, version 1703.
  40. */
  41. #ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
  42. #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ((HANDLE)-4)
  43. #endif
  44. #ifndef WM_DPICHANGED
  45. #define WM_DPICHANGED 0x02E0
  46. #endif
  47. // Declare pointers to the DPI aware Windows API functions.
  48. using ProcSetProcessDpiAwarenessContext = BOOL(WINAPI*)(HANDLE value);
  49. using ProcGetDpiForWindow = UINT(WINAPI*)(HWND hwnd);
  50. using ProcAdjustWindowRectExForDpi = BOOL(WINAPI*)(LPRECT lpRect, DWORD dwStyle, BOOL bMenu, DWORD dwExStyle, UINT dpi);
  51. static bool has_dpi_support = false;
  52. static ProcSetProcessDpiAwarenessContext procSetProcessDpiAwarenessContext = NULL;
  53. static ProcGetDpiForWindow procGetDpiForWindow = NULL;
  54. static ProcAdjustWindowRectExForDpi procAdjustWindowRectExForDpi = NULL;
  55. // Make ourselves DPI aware on supported Windows versions.
  56. static void InitializeDpiSupport()
  57. {
  58. // Cast function pointers to void* first for MinGW not to emit errors.
  59. procSetProcessDpiAwarenessContext =
  60. (ProcSetProcessDpiAwarenessContext)(void*)GetProcAddress(GetModuleHandle(TEXT("User32.dll")), "SetProcessDpiAwarenessContext");
  61. procGetDpiForWindow = (ProcGetDpiForWindow)(void*)GetProcAddress(GetModuleHandle(TEXT("User32.dll")), "GetDpiForWindow");
  62. procAdjustWindowRectExForDpi =
  63. (ProcAdjustWindowRectExForDpi)(void*)GetProcAddress(GetModuleHandle(TEXT("User32.dll")), "AdjustWindowRectExForDpi");
  64. if (!has_dpi_support && procSetProcessDpiAwarenessContext != NULL && procGetDpiForWindow != NULL && procAdjustWindowRectExForDpi != NULL)
  65. {
  66. // Activate Per Monitor V2.
  67. if (procSetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2))
  68. has_dpi_support = true;
  69. }
  70. }
  71. static UINT GetWindowDpi(HWND window_handle)
  72. {
  73. if (has_dpi_support)
  74. {
  75. UINT dpi = procGetDpiForWindow(window_handle);
  76. if (dpi != 0)
  77. return dpi;
  78. }
  79. return USER_DEFAULT_SCREEN_DPI;
  80. }
  81. static float GetDensityIndependentPixelRatio(HWND window_handle)
  82. {
  83. return float(GetWindowDpi(window_handle)) / float(USER_DEFAULT_SCREEN_DPI);
  84. }
  85. // 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.
  86. static HWND InitializeWindow(HINSTANCE instance_handle, const std::wstring& name, int& inout_width, int& inout_height, bool allow_resize);
  87. // Attach the OpenGL context.
  88. static bool AttachToNative(HWND window_handle, HDC& out_device_context, HGLRC& out_render_context);
  89. // Detach the OpenGL context.
  90. static void DetachFromNative(HWND window_handle, HDC device_context, HGLRC render_context);
  91. /**
  92. Global data used by this backend.
  93. Lifetime governed by the calls to Backend::Initialize() and Backend::Shutdown().
  94. */
  95. struct BackendData {
  96. SystemInterface_Win32 system_interface;
  97. RenderInterface_GL2 render_interface;
  98. HINSTANCE instance_handle = nullptr;
  99. std::wstring instance_name;
  100. HWND window_handle = nullptr;
  101. HDC device_context = nullptr;
  102. HGLRC render_context = nullptr;
  103. bool context_dimensions_dirty = true;
  104. Rml::Vector2i window_dimensions;
  105. bool running = true;
  106. // Arguments set during event processing and nulled otherwise.
  107. Rml::Context* context = nullptr;
  108. KeyDownCallback key_down_callback = nullptr;
  109. };
  110. static Rml::UniquePtr<BackendData> data;
  111. bool Backend::Initialize(const char* window_name, int width, int height, bool allow_resize)
  112. {
  113. RMLUI_ASSERT(!data);
  114. const std::wstring name = RmlWin32::ConvertToUTF16(Rml::String(window_name));
  115. data = Rml::MakeUnique<BackendData>();
  116. data->instance_handle = GetModuleHandle(nullptr);
  117. data->instance_name = name;
  118. InitializeDpiSupport();
  119. // Initialize the window but don't show it yet.
  120. HWND window_handle = InitializeWindow(data->instance_handle, name, width, height, allow_resize);
  121. if (!window_handle)
  122. return false;
  123. // Attach the OpenGL context.
  124. if (!AttachToNative(window_handle, data->device_context, data->render_context))
  125. {
  126. ::CloseWindow(window_handle);
  127. return false;
  128. }
  129. data->window_handle = window_handle;
  130. data->system_interface.SetWindow(window_handle);
  131. // Now we are ready to show the window.
  132. ::ShowWindow(window_handle, SW_SHOW);
  133. ::SetForegroundWindow(window_handle);
  134. ::SetFocus(window_handle);
  135. return true;
  136. }
  137. void Backend::Shutdown()
  138. {
  139. RMLUI_ASSERT(data);
  140. DetachFromNative(data->window_handle, data->device_context, data->render_context);
  141. ::DestroyWindow(data->window_handle);
  142. ::UnregisterClassW((LPCWSTR)data->instance_name.data(), data->instance_handle);
  143. data.reset();
  144. }
  145. Rml::SystemInterface* Backend::GetSystemInterface()
  146. {
  147. RMLUI_ASSERT(data);
  148. return &data->system_interface;
  149. }
  150. Rml::RenderInterface* Backend::GetRenderInterface()
  151. {
  152. RMLUI_ASSERT(data);
  153. return &data->render_interface;
  154. }
  155. static bool NextEvent(MSG& message, UINT timeout)
  156. {
  157. if (timeout != 0)
  158. {
  159. UINT_PTR timer_id = SetTimer(NULL, 0, timeout, NULL);
  160. BOOL res = GetMessage(&message, NULL, 0, 0);
  161. KillTimer(NULL, timer_id);
  162. if (message.message != WM_TIMER || message.hwnd != nullptr || message.wParam != timer_id)
  163. return res;
  164. }
  165. return PeekMessage(&message, nullptr, 0, 0, PM_REMOVE);
  166. }
  167. bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_callback, bool power_save)
  168. {
  169. RMLUI_ASSERT(data && context);
  170. // The initial window size may have been affected by system DPI settings, apply the actual pixel size and dp-ratio to the context.
  171. if (data->context_dimensions_dirty)
  172. {
  173. data->context_dimensions_dirty = false;
  174. const float dp_ratio = GetDensityIndependentPixelRatio(data->window_handle);
  175. context->SetDimensions(data->window_dimensions);
  176. context->SetDensityIndependentPixelRatio(dp_ratio);
  177. }
  178. data->context = context;
  179. data->key_down_callback = key_down_callback;
  180. MSG message;
  181. bool has_message = NextEvent(message, power_save ? static_cast<int>(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0) * 1000.0) : 0);
  182. while (has_message)
  183. {
  184. // Dispatch the message to our local event handler below.
  185. TranslateMessage(&message);
  186. DispatchMessage(&message);
  187. has_message = NextEvent(message, 0);
  188. }
  189. data->context = nullptr;
  190. data->key_down_callback = nullptr;
  191. const bool result = data->running;
  192. data->running = true;
  193. return result;
  194. }
  195. void Backend::RequestExit()
  196. {
  197. RMLUI_ASSERT(data);
  198. data->running = false;
  199. }
  200. void Backend::BeginFrame()
  201. {
  202. RMLUI_ASSERT(data);
  203. data->render_interface.BeginFrame();
  204. data->render_interface.Clear();
  205. }
  206. void Backend::PresentFrame()
  207. {
  208. RMLUI_ASSERT(data);
  209. data->render_interface.EndFrame();
  210. // Flips the OpenGL buffers.
  211. SwapBuffers(data->device_context);
  212. // Optional, used to mark frames during performance profiling.
  213. RMLUI_FrameMark;
  214. }
  215. // Local event handler for window and input events.
  216. static LRESULT CALLBACK WindowProcedureHandler(HWND window_handle, UINT message, WPARAM w_param, LPARAM l_param)
  217. {
  218. RMLUI_ASSERT(data);
  219. switch (message)
  220. {
  221. case WM_CLOSE:
  222. {
  223. data->running = false;
  224. return 0;
  225. }
  226. break;
  227. case WM_SIZE:
  228. {
  229. const int width = LOWORD(l_param);
  230. const int height = HIWORD(l_param);
  231. data->window_dimensions.x = width;
  232. data->window_dimensions.y = height;
  233. data->render_interface.SetViewport(width, height);
  234. if (data->context)
  235. data->context->SetDimensions(data->window_dimensions);
  236. return 0;
  237. }
  238. break;
  239. case WM_DPICHANGED:
  240. {
  241. RECT* new_pos = (RECT*)l_param;
  242. SetWindowPos(window_handle, NULL, new_pos->left, new_pos->top, new_pos->right - new_pos->left, new_pos->bottom - new_pos->top,
  243. SWP_NOZORDER | SWP_NOACTIVATE);
  244. if (data->context && has_dpi_support)
  245. data->context->SetDensityIndependentPixelRatio(GetDensityIndependentPixelRatio(window_handle));
  246. return 0;
  247. }
  248. break;
  249. case WM_KEYDOWN:
  250. {
  251. // Override the default key event callback to add global shortcuts for the samples.
  252. Rml::Context* context = data->context;
  253. KeyDownCallback key_down_callback = data->key_down_callback;
  254. const Rml::Input::KeyIdentifier rml_key = RmlWin32::ConvertKey((int)w_param);
  255. const int rml_modifier = RmlWin32::GetKeyModifierState();
  256. const float native_dp_ratio = GetDensityIndependentPixelRatio(window_handle);
  257. // See if we have any global shortcuts that take priority over the context.
  258. if (key_down_callback && !key_down_callback(context, rml_key, rml_modifier, native_dp_ratio, true))
  259. return 0;
  260. // Otherwise, hand the event over to the context by calling the input handler as normal.
  261. if (!RmlWin32::WindowProcedure(context, window_handle, message, w_param, l_param))
  262. return 0;
  263. // The key was not consumed by the context either, try keyboard shortcuts of lower priority.
  264. if (key_down_callback && !key_down_callback(context, rml_key, rml_modifier, native_dp_ratio, false))
  265. return 0;
  266. return 0;
  267. }
  268. break;
  269. default:
  270. {
  271. // Submit it to the platform handler for default input handling.
  272. if (!RmlWin32::WindowProcedure(data->context, window_handle, message, w_param, l_param))
  273. return 0;
  274. }
  275. break;
  276. }
  277. // All unhandled messages go to DefWindowProc.
  278. return DefWindowProc(window_handle, message, w_param, l_param);
  279. }
  280. static HWND InitializeWindow(HINSTANCE instance_handle, const std::wstring& name, int& inout_width, int& inout_height, bool allow_resize)
  281. {
  282. // Fill out the window class struct.
  283. WNDCLASSW window_class;
  284. window_class.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
  285. window_class.lpfnWndProc = &WindowProcedureHandler; // Attach our local event handler.
  286. window_class.cbClsExtra = 0;
  287. window_class.cbWndExtra = 0;
  288. window_class.hInstance = instance_handle;
  289. window_class.hIcon = LoadIcon(nullptr, IDI_WINLOGO);
  290. window_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
  291. window_class.hbrBackground = nullptr;
  292. window_class.lpszMenuName = nullptr;
  293. window_class.lpszClassName = name.data();
  294. if (!RegisterClassW(&window_class))
  295. {
  296. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to register window class");
  297. return nullptr;
  298. }
  299. HWND window_handle = CreateWindowExW(WS_EX_APPWINDOW | WS_EX_WINDOWEDGE,
  300. name.data(), // Window class name.
  301. name.data(), WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW, 0, 0, // Window position.
  302. 0, 0, // Window size.
  303. nullptr, nullptr, instance_handle, nullptr);
  304. if (!window_handle)
  305. {
  306. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to create window");
  307. return nullptr;
  308. }
  309. UINT window_dpi = GetWindowDpi(window_handle);
  310. inout_width = (inout_width * (int)window_dpi) / USER_DEFAULT_SCREEN_DPI;
  311. inout_height = (inout_height * (int)window_dpi) / USER_DEFAULT_SCREEN_DPI;
  312. DWORD style = (allow_resize ? WS_OVERLAPPEDWINDOW : (WS_OVERLAPPEDWINDOW & ~WS_SIZEBOX & ~WS_MAXIMIZEBOX));
  313. DWORD extended_style = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
  314. // Adjust the window size to take the edges into account.
  315. RECT window_rect;
  316. window_rect.top = 0;
  317. window_rect.left = 0;
  318. window_rect.right = inout_width;
  319. window_rect.bottom = inout_height;
  320. if (has_dpi_support)
  321. procAdjustWindowRectExForDpi(&window_rect, style, FALSE, extended_style, window_dpi);
  322. else
  323. AdjustWindowRectEx(&window_rect, style, FALSE, extended_style);
  324. SetWindowLong(window_handle, GWL_EXSTYLE, extended_style);
  325. SetWindowLong(window_handle, GWL_STYLE, style);
  326. // Resize the window.
  327. SetWindowPos(window_handle, HWND_TOP, 0, 0, window_rect.right - window_rect.left, window_rect.bottom - window_rect.top, SWP_NOACTIVATE);
  328. return window_handle;
  329. }
  330. static bool AttachToNative(HWND window_handle, HDC& out_device_context, HGLRC& out_render_context)
  331. {
  332. HDC device_context = GetDC(window_handle);
  333. if (!device_context)
  334. {
  335. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to get device context");
  336. return false;
  337. }
  338. PIXELFORMATDESCRIPTOR pixel_format_descriptor = {};
  339. pixel_format_descriptor.nSize = sizeof(PIXELFORMATDESCRIPTOR);
  340. pixel_format_descriptor.nVersion = 1;
  341. pixel_format_descriptor.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  342. pixel_format_descriptor.iPixelType = PFD_TYPE_RGBA;
  343. pixel_format_descriptor.cColorBits = 32;
  344. pixel_format_descriptor.cRedBits = 8;
  345. pixel_format_descriptor.cGreenBits = 8;
  346. pixel_format_descriptor.cBlueBits = 8;
  347. pixel_format_descriptor.cAlphaBits = 8;
  348. pixel_format_descriptor.cDepthBits = 24;
  349. pixel_format_descriptor.cStencilBits = 8;
  350. int pixel_format = ChoosePixelFormat(device_context, &pixel_format_descriptor);
  351. if (!pixel_format)
  352. {
  353. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to choose 32-bit pixel format");
  354. return false;
  355. }
  356. if (!SetPixelFormat(device_context, pixel_format, &pixel_format_descriptor))
  357. {
  358. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to set pixel format");
  359. return false;
  360. }
  361. HGLRC render_context = wglCreateContext(device_context);
  362. if (!render_context)
  363. {
  364. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to create OpenGL rendering context");
  365. return false;
  366. }
  367. // Activate the rendering context.
  368. if (!wglMakeCurrent(device_context, render_context))
  369. {
  370. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to make rendering context current");
  371. return false;
  372. }
  373. out_device_context = device_context;
  374. out_render_context = render_context;
  375. return true;
  376. }
  377. static void DetachFromNative(HWND window_handle, HDC device_context, HGLRC render_context)
  378. {
  379. // Shutdown OpenGL
  380. if (render_context)
  381. {
  382. wglMakeCurrent(nullptr, nullptr);
  383. wglDeleteContext(render_context);
  384. }
  385. if (device_context)
  386. {
  387. ReleaseDC(window_handle, device_context);
  388. }
  389. }