OpenTTD Source 20250524-master-gc366e6a48e
win32_v.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
7
10#include "../stdafx.h"
11#include "../openttd.h"
12#include "../error_func.h"
13#include "../gfx_func.h"
14#include "../os/windows/win32.h"
15#include "../blitter/factory.hpp"
16#include "../core/geometry_func.hpp"
17#include "../core/math_func.hpp"
18#include "../core/random_func.hpp"
19#include "../texteff.hpp"
20#include "../thread.h"
21#include "../progress.h"
22#include "../window_gui.h"
23#include "../window_func.h"
24#include "../framerate_type.h"
25#include "../library_loader.h"
26#include "../core/utf8.hpp"
27#include "win32_v.h"
28#include <windows.h>
29#include <imm.h>
30#include <versionhelpers.h>
31#if defined(_MSC_VER) && defined(NTDDI_WIN10_RS4)
32#include <winrt/Windows.UI.ViewManagement.h>
33#endif
34
35#include "../safeguards.h"
36
37/* Missing define in MinGW headers. */
38#ifndef MAPVK_VK_TO_CHAR
39#define MAPVK_VK_TO_CHAR (2)
40#endif
41
42#ifndef PM_QS_INPUT
43#define PM_QS_INPUT 0x20000
44#endif
45
46#ifndef WM_DPICHANGED
47#define WM_DPICHANGED 0x02E0
48#endif
49
50bool _window_maximize;
51static Dimension _bck_resolution;
52DWORD _imm_props;
53
55
56bool VideoDriver_Win32Base::ClaimMousePointer()
57{
58 MyShowCursor(false, true);
59 return true;
60}
61
63 uint8_t vk_from;
64 uint8_t vk_count;
65 uint8_t map_to;
66};
67
68#define AS(x, z) {x, 1, z}
69#define AM(x, y, z, w) {x, y - x + 1, z}
70
71static const Win32VkMapping _vk_mapping[] = {
72 /* Pageup stuff + up/down */
73 AM(VK_PRIOR, VK_DOWN, WKC_PAGEUP, WKC_DOWN),
74 /* Map letters & digits */
75 AM('A', 'Z', 'A', 'Z'),
76 AM('0', '9', '0', '9'),
77
78 AS(VK_ESCAPE, WKC_ESC),
79 AS(VK_PAUSE, WKC_PAUSE),
80 AS(VK_BACK, WKC_BACKSPACE),
81 AM(VK_INSERT, VK_DELETE, WKC_INSERT, WKC_DELETE),
82
83 AS(VK_SPACE, WKC_SPACE),
84 AS(VK_RETURN, WKC_RETURN),
85 AS(VK_TAB, WKC_TAB),
86
87 /* Function keys */
88 AM(VK_F1, VK_F12, WKC_F1, WKC_F12),
89
90 /* Numeric part */
91 AM(VK_NUMPAD0, VK_NUMPAD9, '0', '9'),
92 AS(VK_DIVIDE, WKC_NUM_DIV),
93 AS(VK_MULTIPLY, WKC_NUM_MUL),
94 AS(VK_SUBTRACT, WKC_NUM_MINUS),
95 AS(VK_ADD, WKC_NUM_PLUS),
96 AS(VK_DECIMAL, WKC_NUM_DECIMAL),
97
98 /* Other non-letter keys */
99 AS(0xBF, WKC_SLASH),
100 AS(0xBA, WKC_SEMICOLON),
101 AS(0xBB, WKC_EQUALS),
102 AS(0xDB, WKC_L_BRACKET),
103 AS(0xDC, WKC_BACKSLASH),
104 AS(0xDD, WKC_R_BRACKET),
105
106 AS(0xDE, WKC_SINGLEQUOTE),
107 AS(0xBC, WKC_COMMA),
108 AS(0xBD, WKC_MINUS),
109 AS(0xBE, WKC_PERIOD)
110};
111
112static uint MapWindowsKey(uint sym)
113{
114 uint key = 0;
115
116 for (const auto &map : _vk_mapping) {
117 if (IsInsideBS(sym, map.vk_from, map.vk_count)) {
118 key = sym - map.vk_from + map.map_to;
119 break;
120 }
121 }
122
123 if (GetAsyncKeyState(VK_SHIFT) < 0) key |= WKC_SHIFT;
124 if (GetAsyncKeyState(VK_CONTROL) < 0) key |= WKC_CTRL;
125 if (GetAsyncKeyState(VK_MENU) < 0) key |= WKC_ALT;
126 return key;
127}
128
131{
132 /* Check modes for the relevant fullscreen bpp */
133 return _support8bpp != S8BPP_HARDWARE ? 32 : BlitterFactory::GetCurrentBlitter()->GetScreenDepth();
134}
135
142bool VideoDriver_Win32Base::MakeWindow(bool full_screen, bool resize)
143{
144 /* full_screen is whether the new window should be fullscreen,
145 * _wnd.fullscreen is whether the current window is. */
146 _fullscreen = full_screen;
147
148 /* recreate window? */
149 if ((full_screen != this->fullscreen) && this->main_wnd) {
150 DestroyWindow(this->main_wnd);
151 this->main_wnd = 0;
152 }
153
154 if (full_screen) {
155 DEVMODE settings{};
156 settings.dmSize = sizeof(settings);
157 settings.dmFields =
158 DM_BITSPERPEL |
159 DM_PELSWIDTH |
160 DM_PELSHEIGHT;
161 settings.dmBitsPerPel = this->GetFullscreenBpp();
162 settings.dmPelsWidth = this->width_org;
163 settings.dmPelsHeight = this->height_org;
164
165 /* Check for 8 bpp support. */
166 if (settings.dmBitsPerPel == 8 && ChangeDisplaySettings(&settings, CDS_FULLSCREEN | CDS_TEST) != DISP_CHANGE_SUCCESSFUL) {
167 settings.dmBitsPerPel = 32;
168 }
169
170 /* Test fullscreen with current resolution, if it fails use desktop resolution. */
171 if (ChangeDisplaySettings(&settings, CDS_FULLSCREEN | CDS_TEST) != DISP_CHANGE_SUCCESSFUL) {
172 RECT r;
173 GetWindowRect(GetDesktopWindow(), &r);
174 /* Guard against recursion. If we already failed here once, just fall through to
175 * the next ChangeDisplaySettings call which will fail and error out appropriately. */
176 if ((int)settings.dmPelsWidth != r.right - r.left || (int)settings.dmPelsHeight != r.bottom - r.top) {
177 return this->ChangeResolution(r.right - r.left, r.bottom - r.top);
178 }
179 }
180
181 if (ChangeDisplaySettings(&settings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) {
182 this->MakeWindow(false, resize); // don't care about the result
183 return false; // the request failed
184 }
185 } else if (this->fullscreen) {
186 /* restore display? */
187 ChangeDisplaySettings(nullptr, 0);
188 /* restore the resolution */
189 this->width = _bck_resolution.width;
190 this->height = _bck_resolution.height;
191 }
192
193 {
194 RECT r;
195 DWORD style, showstyle;
196 int w, h;
197
198 showstyle = SW_SHOWNORMAL;
199 this->fullscreen = full_screen;
200 if (this->fullscreen) {
201 style = WS_POPUP;
202 SetRect(&r, 0, 0, this->width_org, this->height_org);
203 } else {
204 style = WS_OVERLAPPEDWINDOW;
205 /* On window creation, check if we were in maximize mode before */
206 if (_window_maximize) showstyle = SW_SHOWMAXIMIZED;
207 SetRect(&r, 0, 0, this->width, this->height);
208 }
209
210 AdjustWindowRect(&r, style, FALSE);
211 w = r.right - r.left;
212 h = r.bottom - r.top;
213
214 if (this->main_wnd != nullptr) {
215 if (!_window_maximize && resize) SetWindowPos(this->main_wnd, 0, 0, 0, w, h, SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOMOVE);
216 } else {
217 int x = 0;
218 int y = 0;
219
220 /* For windowed mode, center on the workspace of the primary display. */
221 if (!this->fullscreen) {
222 MONITORINFO mi;
223 mi.cbSize = sizeof(mi);
224 GetMonitorInfo(MonitorFromWindow(0, MONITOR_DEFAULTTOPRIMARY), &mi);
225
226 x = (mi.rcWork.right - mi.rcWork.left - w) / 2;
227 y = (mi.rcWork.bottom - mi.rcWork.top - h) / 2;
228 }
229
230 std::string caption = VideoDriver::GetCaption();
231 this->main_wnd = CreateWindow(L"OTTD", OTTD2FS(caption).c_str(), style, x, y, w, h, 0, 0, GetModuleHandle(nullptr), this);
232 if (this->main_wnd == nullptr) UserError("CreateWindow failed");
233 ShowWindow(this->main_wnd, showstyle);
234 }
235 }
236
238
240 return true;
241}
242
244static LRESULT HandleCharMsg(uint keycode, char32_t charcode)
245{
246 static char32_t prev_char = 0;
247
248 /* Did we get a lead surrogate? If yes, store and exit. */
249 if (Utf16IsLeadSurrogate(charcode)) {
250 if (prev_char != 0) Debug(driver, 1, "Got two UTF-16 lead surrogates, dropping the first one");
251 prev_char = charcode;
252 return 0;
253 }
254
255 /* Stored lead surrogate and incoming trail surrogate? Combine and forward to input handling. */
256 if (prev_char != 0) {
257 if (Utf16IsTrailSurrogate(charcode)) {
258 charcode = Utf16DecodeSurrogate(prev_char, charcode);
259 } else {
260 Debug(driver, 1, "Got an UTF-16 lead surrogate without a trail surrogate, dropping the lead surrogate");
261 }
262 }
263 prev_char = 0;
264
265 HandleKeypress(keycode, charcode);
266
267 return 0;
268}
269
272{
273 return (_imm_props & IME_PROP_AT_CARET) && !(_imm_props & IME_PROP_SPECIAL_UI);
274}
275
277static void SetCompositionPos(HWND hwnd)
278{
279 HIMC hIMC = ImmGetContext(hwnd);
280 if (hIMC != nullptr) {
281 COMPOSITIONFORM cf;
282 cf.dwStyle = CFS_POINT;
283
284 if (EditBoxInGlobalFocus()) {
285 /* Get caret position. */
286 Point pt = _focused_window->GetCaretPosition();
287 cf.ptCurrentPos.x = _focused_window->left + pt.x;
288 cf.ptCurrentPos.y = _focused_window->top + pt.y;
289 } else {
290 cf.ptCurrentPos.x = 0;
291 cf.ptCurrentPos.y = 0;
292 }
293 ImmSetCompositionWindow(hIMC, &cf);
294 }
295 ImmReleaseContext(hwnd, hIMC);
296}
297
299static void SetCandidatePos(HWND hwnd)
300{
301 HIMC hIMC = ImmGetContext(hwnd);
302 if (hIMC != nullptr) {
303 CANDIDATEFORM cf;
304 cf.dwIndex = 0;
305 cf.dwStyle = CFS_EXCLUDE;
306
307 if (EditBoxInGlobalFocus()) {
308 Point pt = _focused_window->GetCaretPosition();
309 cf.ptCurrentPos.x = _focused_window->left + pt.x;
310 cf.ptCurrentPos.y = _focused_window->top + pt.y;
311 if (_focused_window->window_class == WC_CONSOLE) {
312 cf.rcArea.left = _focused_window->left;
313 cf.rcArea.top = _focused_window->top;
314 cf.rcArea.right = _focused_window->left + _focused_window->width;
315 cf.rcArea.bottom = _focused_window->top + _focused_window->height;
316 } else {
317 cf.rcArea.left = _focused_window->left + _focused_window->nested_focus->pos_x;
318 cf.rcArea.top = _focused_window->top + _focused_window->nested_focus->pos_y;
319 cf.rcArea.right = cf.rcArea.left + _focused_window->nested_focus->current_x;
320 cf.rcArea.bottom = cf.rcArea.top + _focused_window->nested_focus->current_y;
321 }
322 } else {
323 cf.ptCurrentPos.x = 0;
324 cf.ptCurrentPos.y = 0;
325 SetRectEmpty(&cf.rcArea);
326 }
327 ImmSetCandidateWindow(hIMC, &cf);
328 }
329 ImmReleaseContext(hwnd, hIMC);
330}
331
333static LRESULT HandleIMEComposition(HWND hwnd, WPARAM wParam, LPARAM lParam)
334{
335 HIMC hIMC = ImmGetContext(hwnd);
336
337 if (hIMC != nullptr) {
338 if (lParam & GCS_RESULTSTR) {
339 /* Read result string from the IME. */
340 LONG len = ImmGetCompositionString(hIMC, GCS_RESULTSTR, nullptr, 0); // Length is always in bytes, even in UNICODE build.
341 std::wstring str(len + 1, L'\0');
342 len = ImmGetCompositionString(hIMC, GCS_RESULTSTR, str.data(), len);
343 str[len / sizeof(wchar_t)] = L'\0';
344
345 /* Transmit text to windowing system. */
346 if (len > 0) {
347 HandleTextInput({}, true); // Clear marked string.
349 }
350 SetCompositionPos(hwnd);
351
352 /* Don't pass the result string on to the default window proc. */
353 lParam &= ~(GCS_RESULTSTR | GCS_RESULTCLAUSE | GCS_RESULTREADCLAUSE | GCS_RESULTREADSTR);
354 }
355
356 if ((lParam & GCS_COMPSTR) && DrawIMECompositionString()) {
357 /* Read composition string from the IME. */
358 LONG len = ImmGetCompositionString(hIMC, GCS_COMPSTR, nullptr, 0); // Length is always in bytes, even in UNICODE build.
359 std::wstring str(len + 1, L'\0');
360 len = ImmGetCompositionString(hIMC, GCS_COMPSTR, str.data(), len);
361 str[len / sizeof(wchar_t)] = L'\0';
362
363 if (len > 0) {
364 static char utf8_buf[1024];
365 convert_from_fs(str, utf8_buf);
366
367 /* Convert caret position from bytes in the input string to a position in the UTF-8 encoded string. */
368 LONG caret_bytes = ImmGetCompositionString(hIMC, GCS_CURSORPOS, nullptr, 0);
369 Utf8View view(utf8_buf);
370 auto caret = view.begin();
371 const auto end = view.end();
372 for (const wchar_t *c = str.c_str(); *c != '\0' && caret != end && caret_bytes > 0; c++, caret_bytes--) {
373 /* Skip DBCS lead bytes or leading surrogates. */
374 if (Utf16IsLeadSurrogate(*c)) {
375 c++;
376 caret_bytes--;
377 }
378 ++caret;
379 }
380
381 HandleTextInput(utf8_buf, true, caret.GetByteOffset());
382 } else {
383 HandleTextInput({}, true);
384 }
385
386 lParam &= ~(GCS_COMPSTR | GCS_COMPATTR | GCS_COMPCLAUSE | GCS_CURSORPOS | GCS_DELTASTART);
387 }
388 }
389 ImmReleaseContext(hwnd, hIMC);
390
391 return lParam != 0 ? DefWindowProc(hwnd, WM_IME_COMPOSITION, wParam, lParam) : 0;
392}
393
395static void CancelIMEComposition(HWND hwnd)
396{
397 HIMC hIMC = ImmGetContext(hwnd);
398 if (hIMC != nullptr) ImmNotifyIME(hIMC, NI_COMPOSITIONSTR, CPS_CANCEL, 0);
399 ImmReleaseContext(hwnd, hIMC);
400 /* Clear any marked string from the current edit box. */
401 HandleTextInput({}, true);
402}
403
404static bool IsDarkModeEnabled()
405{
406 /* Only build if SDK is Windows 10 1803 or later. */
407#if defined(_MSC_VER) && defined(NTDDI_WIN10_RS4)
408 if (IsWindows10OrGreater()) {
409 try {
410 /*
411 * The official documented way to find out if the system is running in dark mode is to
412 * check the brightness of the current theme's colour.
413 * See: https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/ui/apply-windows-themes#know-when-dark-mode-is-enabled
414 *
415 * There are other variants floating around on the Internet, but they all rely on internal,
416 * undocumented Windows functions that may or may not work in the future.
417 */
418 winrt::Windows::UI::ViewManagement::UISettings settings;
419 auto foreground = settings.GetColorValue(winrt::Windows::UI::ViewManagement::UIColorType::Foreground);
420
421 /* If the Foreground colour is a light colour, the system is running in dark mode. */
422 return ((5 * foreground.G) + (2 * foreground.R) + foreground.B) > (8 * 128);
423 } catch (...) {
424 /* Some kind of error, like a too old Windows version. Just return false. */
425 return false;
426 }
427 }
428#endif /* defined(_MSC_VER) && defined(NTDDI_WIN10_RS4) */
429
430 return false;
431}
432
433static void SetDarkModeForWindow(HWND hWnd, bool dark_mode)
434{
435 /* Only build if SDK is Windows 10+. */
436#if defined(NTDDI_WIN10)
437 if (!IsWindows10OrGreater()) return;
438
439 /* This function is documented, but not supported on all Windows 10/11 SDK builds. For this
440 * reason, the code uses dynamic loading and ignores any errors for a best-effort result. */
441 static LibraryLoader _dwmapi("dwmapi.dll");
442 typedef HRESULT(WINAPI *PFNDWMSETWINDOWATTRIBUTE)(HWND, DWORD, LPCVOID, DWORD);
443 static const PFNDWMSETWINDOWATTRIBUTE DwmSetWindowAttribute = _dwmapi.GetFunction("DwmSetWindowAttribute");
444
445 if (DwmSetWindowAttribute != nullptr) {
446 /* Contrary to the published documentation, DWMWA_USE_IMMERSIVE_DARK_MODE does not change the
447 * window chrome according to the current theme, but forces it to either light or dark mode.
448 * As such, the set value has to depend on the current theming mode.*/
449 BOOL value = dark_mode ? TRUE : FALSE;
450 if (DwmSetWindowAttribute(hWnd, 20 /* DWMWA_USE_IMMERSIVE_DARK_MODE */, &value, sizeof(value)) != S_OK) {
451 DwmSetWindowAttribute(hWnd, 19 /* DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 */, &value, sizeof(value)); // Ignore errors. It works or it doesn't.
452 }
453 }
454#endif /* defined(NTDDI_WIN10) */
455}
456
457LRESULT CALLBACK WndProcGdi(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
458{
459 static uint32_t keycode = 0;
460 static bool console = false;
461
462 const float SCROLL_BUILTIN_MULTIPLIER = 14.0f / WHEEL_DELTA;
463
464 VideoDriver_Win32Base *video_driver = (VideoDriver_Win32Base *)GetWindowLongPtr(hwnd, GWLP_USERDATA);
465
466 switch (msg) {
467 case WM_CREATE:
468 SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)((LPCREATESTRUCT)lParam)->lpCreateParams);
469 _cursor.in_window = false; // Win32 has mouse tracking.
470 SetCompositionPos(hwnd);
471 _imm_props = ImmGetProperty(GetKeyboardLayout(0), IGP_PROPERTY);
472
473 /* Enable dark mode theming for window chrome. */
474 SetDarkModeForWindow(hwnd, IsDarkModeEnabled());
475 break;
476
477 case WM_SETTINGCHANGE:
478 /* Synchronize dark mode theming state. */
479 SetDarkModeForWindow(hwnd, IsDarkModeEnabled());
480 break;
481
482 case WM_PAINT: {
483 RECT r;
484 GetUpdateRect(hwnd, &r, FALSE);
485 video_driver->MakeDirty(r.left, r.top, r.right - r.left, r.bottom - r.top);
486
487 ValidateRect(hwnd, nullptr);
488 return 0;
489 }
490
491 case WM_PALETTECHANGED:
492 if ((HWND)wParam == hwnd) return 0;
493 [[fallthrough]];
494
495 case WM_QUERYNEWPALETTE:
496 video_driver->PaletteChanged(hwnd);
497 return 0;
498
499 case WM_CLOSE:
500 HandleExitGameRequest();
501 return 0;
502
503 case WM_DESTROY:
504 if (_window_maximize) _cur_resolution = _bck_resolution;
505 return 0;
506
507 case WM_LBUTTONDOWN:
508 SetCapture(hwnd);
509 _left_button_down = true;
511 return 0;
512
513 case WM_LBUTTONUP:
514 ReleaseCapture();
515 _left_button_down = false;
516 _left_button_clicked = false;
518 return 0;
519
520 case WM_RBUTTONDOWN:
521 SetCapture(hwnd);
522 _right_button_down = true;
525 return 0;
526
527 case WM_RBUTTONUP:
528 ReleaseCapture();
529 _right_button_down = false;
531 return 0;
532
533 case WM_MOUSELEAVE:
534 UndrawMouseCursor();
535 _cursor.in_window = false;
536
537 if (!_left_button_down && !_right_button_down) MyShowCursor(true);
538 return 0;
539
540 case WM_MOUSEMOVE: {
541 int x = (int16_t)LOWORD(lParam);
542 int y = (int16_t)HIWORD(lParam);
543
544 /* If the mouse was not in the window and it has moved it means it has
545 * come into the window, so start drawing the mouse. Also start
546 * tracking the mouse for exiting the window */
547 if (!_cursor.in_window) {
548 _cursor.in_window = true;
549 TRACKMOUSEEVENT tme;
550 tme.cbSize = sizeof(tme);
551 tme.dwFlags = TME_LEAVE;
552 tme.hwndTrack = hwnd;
553
554 TrackMouseEvent(&tme);
555 }
556
557 if (_cursor.fix_at) {
558 /* Get all queued mouse events now in case we have to warp the cursor. In the
559 * end, we only care about the current mouse position and not bygone events. */
560 MSG m;
561 while (PeekMessage(&m, hwnd, WM_MOUSEMOVE, WM_MOUSEMOVE, PM_REMOVE | PM_NOYIELD | PM_QS_INPUT)) {
562 x = (int16_t)LOWORD(m.lParam);
563 y = (int16_t)HIWORD(m.lParam);
564 }
565 }
566
567 if (_cursor.UpdateCursorPosition(x, y)) {
568 POINT pt;
569 pt.x = _cursor.pos.x;
570 pt.y = _cursor.pos.y;
571 ClientToScreen(hwnd, &pt);
572 SetCursorPos(pt.x, pt.y);
573 }
574 MyShowCursor(false);
576 return 0;
577 }
578
579 case WM_INPUTLANGCHANGE:
580 _imm_props = ImmGetProperty(GetKeyboardLayout(0), IGP_PROPERTY);
581 break;
582
583 case WM_IME_SETCONTEXT:
584 /* Don't show the composition window if we draw the string ourself. */
585 if (DrawIMECompositionString()) lParam &= ~ISC_SHOWUICOMPOSITIONWINDOW;
586 break;
587
588 case WM_IME_STARTCOMPOSITION:
589 SetCompositionPos(hwnd);
590 if (DrawIMECompositionString()) return 0;
591 break;
592
593 case WM_IME_COMPOSITION:
594 return HandleIMEComposition(hwnd, wParam, lParam);
595
596 case WM_IME_ENDCOMPOSITION:
597 /* Clear any pending composition string. */
598 HandleTextInput({}, true);
599 if (DrawIMECompositionString()) return 0;
600 break;
601
602 case WM_IME_NOTIFY:
603 if (wParam == IMN_OPENCANDIDATE) SetCandidatePos(hwnd);
604 break;
605
606 case WM_DEADCHAR:
607 console = GB(lParam, 16, 8) == 41;
608 return 0;
609
610 case WM_CHAR: {
611 uint scancode = GB(lParam, 16, 8);
612 uint charcode = wParam;
613
614 /* If the console key is a dead-key, we need to press it twice to get a WM_CHAR message.
615 * But we then get two WM_CHAR messages, so ignore the first one */
616 if (console && scancode == 41) {
617 console = false;
618 return 0;
619 }
620
621 /* IMEs and other input methods sometimes send a WM_CHAR without a WM_KEYDOWN,
622 * clear the keycode so a previous WM_KEYDOWN doesn't become 'stuck'. */
623 uint cur_keycode = keycode;
624 keycode = 0;
625
626 return HandleCharMsg(cur_keycode, charcode);
627 }
628
629 case WM_KEYDOWN: {
630 /* No matter the keyboard layout, we will map the '~' to the console. */
631 uint scancode = GB(lParam, 16, 8);
632 keycode = scancode == 41 ? (uint)WKC_BACKQUOTE : MapWindowsKey(wParam);
633
634 uint charcode = MapVirtualKey(wParam, MAPVK_VK_TO_CHAR);
635
636 /* No character translation? */
637 if (charcode == 0) {
638 HandleKeypress(keycode, 0);
639 return 0;
640 }
641
642 /* If an edit box is in focus, wait for the corresponding WM_CHAR message. */
643 if (!EditBoxInGlobalFocus()) {
644 /* Is the console key a dead key? If yes, ignore the first key down event. */
645 if (HasBit(charcode, 31) && !console) {
646 if (scancode == 41) {
647 console = true;
648 return 0;
649 }
650 }
651 console = false;
652
653 /* IMEs and other input methods sometimes send a WM_CHAR without a WM_KEYDOWN,
654 * clear the keycode so a previous WM_KEYDOWN doesn't become 'stuck'. */
655 uint cur_keycode = keycode;
656 keycode = 0;
657
658 return HandleCharMsg(cur_keycode, LOWORD(charcode));
659 }
660
661 return 0;
662 }
663
664 case WM_SYSKEYDOWN: // user presses F10 or Alt, both activating the title-menu
665 switch (wParam) {
666 case VK_RETURN:
667 case 'F': // Full Screen on ALT + ENTER/F
668 ToggleFullScreen(!video_driver->fullscreen);
669 return 0;
670
671 case VK_MENU: // Just ALT
672 return 0; // do nothing
673
674 case VK_F10: // F10, ignore activation of menu
675 HandleKeypress(MapWindowsKey(wParam), 0);
676 return 0;
677
678 default: // ALT in combination with something else
679 HandleKeypress(MapWindowsKey(wParam), 0);
680 break;
681 }
682 break;
683
684 case WM_SIZE:
685 if (wParam != SIZE_MINIMIZED) {
686 /* Set maximized flag when we maximize (obviously), but also when we
687 * switched to fullscreen from a maximized state */
688 _window_maximize = (wParam == SIZE_MAXIMIZED || (_window_maximize && _fullscreen));
689 if (_window_maximize || _fullscreen) _bck_resolution = _cur_resolution;
690 video_driver->ClientSizeChanged(LOWORD(lParam), HIWORD(lParam));
691 }
692 return 0;
693
694 case WM_SIZING: {
695 RECT *r = (RECT*)lParam;
696 RECT r2;
697 int w, h;
698
699 SetRect(&r2, 0, 0, 0, 0);
700 AdjustWindowRect(&r2, GetWindowLong(hwnd, GWL_STYLE), FALSE);
701
702 w = r->right - r->left - (r2.right - r2.left);
703 h = r->bottom - r->top - (r2.bottom - r2.top);
704 w = std::max(w, 64);
705 h = std::max(h, 64);
706 SetRect(&r2, 0, 0, w, h);
707
708 AdjustWindowRect(&r2, GetWindowLong(hwnd, GWL_STYLE), FALSE);
709 w = r2.right - r2.left;
710 h = r2.bottom - r2.top;
711
712 switch (wParam) {
713 case WMSZ_BOTTOM:
714 r->bottom = r->top + h;
715 break;
716
717 case WMSZ_BOTTOMLEFT:
718 r->bottom = r->top + h;
719 r->left = r->right - w;
720 break;
721
722 case WMSZ_BOTTOMRIGHT:
723 r->bottom = r->top + h;
724 r->right = r->left + w;
725 break;
726
727 case WMSZ_LEFT:
728 r->left = r->right - w;
729 break;
730
731 case WMSZ_RIGHT:
732 r->right = r->left + w;
733 break;
734
735 case WMSZ_TOP:
736 r->top = r->bottom - h;
737 break;
738
739 case WMSZ_TOPLEFT:
740 r->top = r->bottom - h;
741 r->left = r->right - w;
742 break;
743
744 case WMSZ_TOPRIGHT:
745 r->top = r->bottom - h;
746 r->right = r->left + w;
747 break;
748 }
749 return TRUE;
750 }
751
752 case WM_DPICHANGED: {
753 auto did_adjust = AdjustGUIZoom(true);
754
755 /* Resize the window to match the new DPI setting. */
756 RECT *prcNewWindow = (RECT *)lParam;
757 SetWindowPos(hwnd,
758 nullptr,
759 prcNewWindow->left,
760 prcNewWindow->top,
761 prcNewWindow->right - prcNewWindow->left,
762 prcNewWindow->bottom - prcNewWindow->top,
763 SWP_NOZORDER | SWP_NOACTIVATE);
764
765 if (did_adjust) ReInitAllWindows(true);
766
767 return 0;
768 }
769
770/* needed for wheel */
771#if !defined(WM_MOUSEWHEEL)
772# define WM_MOUSEWHEEL 0x020A
773#endif /* WM_MOUSEWHEEL */
774#if !defined(WM_MOUSEHWHEEL)
775# define WM_MOUSEHWHEEL 0x020E
776#endif /* WM_MOUSEHWHEEL */
777#if !defined(GET_WHEEL_DELTA_WPARAM)
778# define GET_WHEEL_DELTA_WPARAM(wparam) ((short)HIWORD(wparam))
779#endif /* GET_WHEEL_DELTA_WPARAM */
780
781 case WM_MOUSEWHEEL: {
782 int delta = GET_WHEEL_DELTA_WPARAM(wParam);
783
784 if (delta < 0) {
785 _cursor.wheel++;
786 } else if (delta > 0) {
787 _cursor.wheel--;
788 }
789
790 _cursor.v_wheel -= static_cast<float>(delta) * SCROLL_BUILTIN_MULTIPLIER * _settings_client.gui.scrollwheel_multiplier;
791 _cursor.wheel_moved = true;
793 return 0;
794 }
795
796 case WM_MOUSEHWHEEL: {
797 int delta = GET_WHEEL_DELTA_WPARAM(wParam);
798
799 _cursor.h_wheel += static_cast<float>(delta) * SCROLL_BUILTIN_MULTIPLIER * _settings_client.gui.scrollwheel_multiplier;
800 _cursor.wheel_moved = true;
802 return 0;
803 }
804
805 case WM_SETFOCUS:
806 video_driver->has_focus = true;
807 SetCompositionPos(hwnd);
808 break;
809
810 case WM_KILLFOCUS:
811 video_driver->has_focus = false;
812 break;
813
814 case WM_ACTIVATE: {
815 /* Don't do anything if we are closing openttd */
816 if (_exit_game) break;
817
818 bool active = (LOWORD(wParam) != WA_INACTIVE);
819 bool minimized = (HIWORD(wParam) != 0);
820 if (video_driver->fullscreen) {
821 if (active && minimized) {
822 /* Restore the game window */
823 Dimension d = _bck_resolution; // Save current non-fullscreen window size as it will be overwritten by ShowWindow.
824 ShowWindow(hwnd, SW_RESTORE);
825 _bck_resolution = d;
826 video_driver->MakeWindow(true);
827 } else if (!active && !minimized) {
828 /* Minimise the window and restore desktop */
829 ShowWindow(hwnd, SW_MINIMIZE);
830 ChangeDisplaySettings(nullptr, 0);
831 }
832 }
833 break;
834 }
835 }
836
837 return DefWindowProc(hwnd, msg, wParam, lParam);
838}
839
840static void RegisterWndClass()
841{
842 static bool registered = false;
843
844 if (registered) return;
845
846 HINSTANCE hinst = GetModuleHandle(nullptr);
847 WNDCLASS wnd = {
848 CS_OWNDC,
849 WndProcGdi,
850 0,
851 0,
852 hinst,
853 LoadIcon(hinst, MAKEINTRESOURCE(100)),
854 LoadCursor(nullptr, IDC_ARROW),
855 0,
856 0,
857 L"OTTD"
858 };
859
860 registered = true;
861 if (!RegisterClass(&wnd)) UserError("RegisterClass failed");
862}
863
864static const Dimension default_resolutions[] = {
865 { 640, 480 },
866 { 800, 600 },
867 { 1024, 768 },
868 { 1152, 864 },
869 { 1280, 800 },
870 { 1280, 960 },
871 { 1280, 1024 },
872 { 1400, 1050 },
873 { 1600, 1200 },
874 { 1680, 1050 },
875 { 1920, 1200 }
876};
877
878static void FindResolutions(uint8_t bpp)
879{
880 _resolutions.clear();
881
882 DEVMODE dm;
883 for (uint i = 0; EnumDisplaySettings(nullptr, i, &dm) != 0; i++) {
884 if (dm.dmBitsPerPel != bpp || dm.dmPelsWidth < 640 || dm.dmPelsHeight < 480) continue;
885 if (std::ranges::find(_resolutions, Dimension(dm.dmPelsWidth, dm.dmPelsHeight)) != _resolutions.end()) continue;
886 _resolutions.emplace_back(dm.dmPelsWidth, dm.dmPelsHeight);
887 }
888
889 /* We have found no resolutions, show the default list */
890 if (_resolutions.empty()) {
891 _resolutions.assign(std::begin(default_resolutions), std::end(default_resolutions));
892 }
893
894 SortResolutions();
895}
896
897void VideoDriver_Win32Base::Initialize()
898{
899 this->UpdateAutoResolution();
900
901 RegisterWndClass();
902 FindResolutions(this->GetFullscreenBpp());
903
904 /* fullscreen uses those */
905 this->width = this->width_org = _cur_resolution.width;
906 this->height = this->height_org = _cur_resolution.height;
907
908 Debug(driver, 2, "Resolution for display: {}x{}", _cur_resolution.width, _cur_resolution.height);
909}
910
912{
913 DestroyWindow(this->main_wnd);
914
915 if (this->fullscreen) ChangeDisplaySettings(nullptr, 0);
916 MyShowCursor(true);
917}
918void VideoDriver_Win32Base::MakeDirty(int left, int top, int width, int height)
919{
920 Rect r = {left, top, left + width, top + height};
921 this->dirty_rect = BoundingRect(this->dirty_rect, r);
922}
923
925{
926 if (!CopyPalette(_local_palette)) return;
927 this->MakeDirty(0, 0, _screen.width, _screen.height);
928}
929
931{
932 bool old_ctrl_pressed = _ctrl_pressed;
933
934 _ctrl_pressed = this->has_focus && GetAsyncKeyState(VK_CONTROL) < 0;
935 _shift_pressed = this->has_focus && GetAsyncKeyState(VK_SHIFT) < 0;
936
937 /* Speedup when pressing tab, except when using ALT+TAB
938 * to switch to another application. */
939 this->fast_forward_key_pressed = this->has_focus && GetAsyncKeyState(VK_TAB) < 0 && GetAsyncKeyState(VK_MENU) >= 0;
940
941 /* Determine which directional keys are down. */
942 if (this->has_focus) {
943 _dirkeys =
944 (GetAsyncKeyState(VK_LEFT) < 0 ? 1 : 0) +
945 (GetAsyncKeyState(VK_UP) < 0 ? 2 : 0) +
946 (GetAsyncKeyState(VK_RIGHT) < 0 ? 4 : 0) +
947 (GetAsyncKeyState(VK_DOWN) < 0 ? 8 : 0);
948 } else {
949 _dirkeys = 0;
950 }
951
952 if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
953}
954
956{
957 MSG mesg;
958
959 if (!PeekMessage(&mesg, nullptr, 0, 0, PM_REMOVE)) return false;
960
961 /* Convert key messages to char messages if we want text input. */
962 if (EditBoxInGlobalFocus()) TranslateMessage(&mesg);
963 DispatchMessage(&mesg);
964
965 return true;
966}
967
969{
970 this->StartGameThread();
971
972 for (;;) {
973 if (_exit_game) break;
974
975 this->Tick();
976 this->SleepTillNextTick();
977 }
978
979 this->StopGameThread();
980}
981
982void VideoDriver_Win32Base::ClientSizeChanged(int w, int h, bool force)
983{
984 /* Allocate backing store of the new size. */
985 if (this->AllocateBackingStore(w, h, force)) {
987
989
991 }
992}
993
995{
996 if (_window_maximize) ShowWindow(this->main_wnd, SW_SHOWNORMAL);
997
998 this->width = this->width_org = w;
999 this->height = this->height_org = h;
1000
1001 return this->MakeWindow(_fullscreen); // _wnd.fullscreen screws up ingame resolution switching
1002}
1003
1005{
1006 bool res = this->MakeWindow(full_screen);
1007
1009 return res;
1010}
1011
1018
1019static BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC, LPRECT, LPARAM data)
1020{
1021 auto &list = *reinterpret_cast<std::vector<int>*>(data);
1022
1023 MONITORINFOEX monitorInfo = {};
1024 monitorInfo.cbSize = sizeof(MONITORINFOEX);
1025 GetMonitorInfo(hMonitor, &monitorInfo);
1026
1027 DEVMODE devMode = {};
1028 devMode.dmSize = sizeof(DEVMODE);
1029 devMode.dmDriverExtra = 0;
1030 EnumDisplaySettings(monitorInfo.szDevice, ENUM_CURRENT_SETTINGS, &devMode);
1031
1032 if (devMode.dmDisplayFrequency != 0) list.push_back(devMode.dmDisplayFrequency);
1033 return true;
1034}
1035
1037{
1038 std::vector<int> rates = {};
1039 EnumDisplayMonitors(nullptr, nullptr, MonitorEnumProc, reinterpret_cast<LPARAM>(&rates));
1040 return rates;
1041}
1042
1044{
1045 return { static_cast<uint>(GetSystemMetrics(SM_CXSCREEN)), static_cast<uint>(GetSystemMetrics(SM_CYSCREEN)) };
1046}
1047
1049{
1050 typedef UINT (WINAPI *PFNGETDPIFORWINDOW)(HWND hwnd);
1051 typedef UINT (WINAPI *PFNGETDPIFORSYSTEM)(VOID);
1052 typedef HRESULT (WINAPI *PFNGETDPIFORMONITOR)(HMONITOR hMonitor, int dpiType, UINT *dpiX, UINT *dpiY);
1053
1054 static PFNGETDPIFORWINDOW _GetDpiForWindow = nullptr;
1055 static PFNGETDPIFORSYSTEM _GetDpiForSystem = nullptr;
1056 static PFNGETDPIFORMONITOR _GetDpiForMonitor = nullptr;
1057
1058 static bool init_done = false;
1059 if (!init_done) {
1060 init_done = true;
1061 static LibraryLoader _user32("user32.dll");
1062 static LibraryLoader _shcore("shcore.dll");
1063 _GetDpiForWindow = _user32.GetFunction("GetDpiForWindow");
1064 _GetDpiForSystem = _user32.GetFunction("GetDpiForSystem");
1065 _GetDpiForMonitor = _shcore.GetFunction("GetDpiForMonitor");
1066 }
1067
1068 UINT cur_dpi = 0;
1069
1070 if (cur_dpi == 0 && _GetDpiForWindow != nullptr && this->main_wnd != nullptr) {
1071 /* Per window DPI is supported since Windows 10 Ver 1607. */
1072 cur_dpi = _GetDpiForWindow(this->main_wnd);
1073 }
1074 if (cur_dpi == 0 && _GetDpiForMonitor != nullptr && this->main_wnd != nullptr) {
1075 /* Per monitor is supported since Windows 8.1. */
1076 UINT dpiX, dpiY;
1077 if (SUCCEEDED(_GetDpiForMonitor(MonitorFromWindow(this->main_wnd, MONITOR_DEFAULTTOPRIMARY), 0 /* MDT_EFFECTIVE_DPI */, &dpiX, &dpiY))) {
1078 cur_dpi = dpiX; // X and Y are always identical.
1079 }
1080 }
1081 if (cur_dpi == 0 && _GetDpiForSystem != nullptr) {
1082 /* Fall back to system DPI. */
1083 cur_dpi = _GetDpiForSystem();
1084 }
1085
1086 return cur_dpi > 0 ? cur_dpi / 96.0f : 1.0f; // Default Windows DPI value is 96.
1087}
1088
1090{
1091 if (this->buffer_locked) return false;
1092 this->buffer_locked = true;
1093
1094 _screen.dst_ptr = this->GetVideoPointer();
1095 assert(_screen.dst_ptr != nullptr);
1096
1097 return true;
1098}
1099
1101{
1102 assert(_screen.dst_ptr != nullptr);
1103 if (_screen.dst_ptr != nullptr) {
1104 /* Hand video buffer back to the drawing backend. */
1105 this->ReleaseVideoPointer();
1106 _screen.dst_ptr = nullptr;
1107 }
1108
1109 this->buffer_locked = false;
1110}
1111
1112
1113static FVideoDriver_Win32GDI iFVideoDriver_Win32GDI;
1114
1115std::optional<std::string_view> VideoDriver_Win32GDI::Start(const StringList &param)
1116{
1117 if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 0) return "Only real blitters supported";
1118
1119 this->Initialize();
1120
1121 this->MakePalette();
1123 this->MakeWindow(_fullscreen);
1124
1126
1127 this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread");
1128
1129 return std::nullopt;
1130}
1131
1133{
1134 DeleteObject(this->gdi_palette);
1135 DeleteObject(this->dib_sect);
1136
1138}
1139
1141{
1143
1144 w = std::max(w, 64);
1145 h = std::max(h, 64);
1146
1147 if (!force && w == _screen.width && h == _screen.height) return false;
1148
1149 BITMAPINFO *bi = (BITMAPINFO *)new char[sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 256]();
1150 bi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
1151
1152 bi->bmiHeader.biWidth = this->width = w;
1153 bi->bmiHeader.biHeight = -(this->height = h);
1154
1155 bi->bmiHeader.biPlanes = 1;
1156 bi->bmiHeader.biBitCount = bpp;
1157 bi->bmiHeader.biCompression = BI_RGB;
1158
1159 if (this->dib_sect) DeleteObject(this->dib_sect);
1160
1161 HDC dc = GetDC(0);
1162 this->dib_sect = CreateDIBSection(dc, bi, DIB_RGB_COLORS, (VOID **)&this->buffer_bits, nullptr, 0);
1163 if (this->dib_sect == nullptr) {
1164 delete[] bi;
1165 UserError("CreateDIBSection failed");
1166 }
1167 ReleaseDC(0, dc);
1168
1169 _screen.width = w;
1170 _screen.pitch = (bpp == 8) ? Align(w, 4) : w;
1171 _screen.height = h;
1172 _screen.dst_ptr = this->GetVideoPointer();
1173
1174 delete[] bi;
1175 return true;
1176}
1177
1179{
1180 assert(BlitterFactory::GetCurrentBlitter()->GetScreenDepth() != 0);
1181 return this->AllocateBackingStore(_screen.width, _screen.height, true) && this->MakeWindow(_fullscreen, false);
1182}
1183
1184void VideoDriver_Win32GDI::MakePalette()
1185{
1187
1188 LOGPALETTE *pal = (LOGPALETTE *)new char[sizeof(LOGPALETTE) + (256 - 1) * sizeof(PALETTEENTRY)]();
1189
1190 pal->palVersion = 0x300;
1191 pal->palNumEntries = 256;
1192
1193 for (uint i = 0; i != 256; i++) {
1194 pal->palPalEntry[i].peRed = _local_palette.palette[i].r;
1195 pal->palPalEntry[i].peGreen = _local_palette.palette[i].g;
1196 pal->palPalEntry[i].peBlue = _local_palette.palette[i].b;
1197 pal->palPalEntry[i].peFlags = 0;
1198
1199 }
1200 this->gdi_palette = CreatePalette(pal);
1201 delete[] pal;
1202 if (this->gdi_palette == nullptr) UserError("CreatePalette failed!\n");
1203}
1204
1205void VideoDriver_Win32GDI::UpdatePalette(HDC dc, uint start, uint count)
1206{
1207 RGBQUAD rgb[256];
1208
1209 for (uint i = 0; i != count; i++) {
1210 rgb[i].rgbRed = _local_palette.palette[start + i].r;
1211 rgb[i].rgbGreen = _local_palette.palette[start + i].g;
1212 rgb[i].rgbBlue = _local_palette.palette[start + i].b;
1213 rgb[i].rgbReserved = 0;
1214 }
1215
1216 SetDIBColorTable(dc, start, count, rgb);
1217}
1218
1220{
1221 HDC hDC = GetWindowDC(hWnd);
1222 HPALETTE hOldPalette = SelectPalette(hDC, this->gdi_palette, FALSE);
1223 UINT nChanged = RealizePalette(hDC);
1224
1225 SelectPalette(hDC, hOldPalette, TRUE);
1226 ReleaseDC(hWnd, hDC);
1227 if (nChanged != 0) this->MakeDirty(0, 0, _screen.width, _screen.height);
1228}
1229
1231{
1232 PerformanceMeasurer framerate(PFE_VIDEO);
1233
1234 if (IsEmptyRect(this->dirty_rect)) return;
1235
1236 HDC dc = GetDC(this->main_wnd);
1237 HDC dc2 = CreateCompatibleDC(dc);
1238
1239 HBITMAP old_bmp = (HBITMAP)SelectObject(dc2, this->dib_sect);
1240 HPALETTE old_palette = SelectPalette(dc, this->gdi_palette, FALSE);
1241
1242 if (_local_palette.count_dirty != 0) {
1244
1245 switch (blitter->UsePaletteAnimation()) {
1247 this->UpdatePalette(dc2, _local_palette.first_dirty, _local_palette.count_dirty);
1248 break;
1249
1252 break;
1253 }
1254
1256 break;
1257
1258 default:
1259 NOT_REACHED();
1260 }
1262 }
1263
1264 BitBlt(dc, 0, 0, this->width, this->height, dc2, 0, 0, SRCCOPY);
1265 SelectPalette(dc, old_palette, TRUE);
1266 SelectObject(dc2, old_bmp);
1267 DeleteDC(dc2);
1268
1269 ReleaseDC(this->main_wnd, dc);
1270
1271 this->dirty_rect = {};
1272}
1273
1274#ifdef _DEBUG
1275/* Keep this function here..
1276 * It allows you to redraw the screen from within the MSVC debugger */
1277/* static */ int VideoDriver_Win32GDI::RedrawScreenDebug()
1278{
1279 static int _fooctr;
1280
1282
1283 _screen.dst_ptr = drv->GetVideoPointer();
1284 UpdateWindows();
1285
1286 drv->Paint();
1287 GdiFlush();
1288
1289 return _fooctr++;
1290}
1291#endif
1292
1293#ifdef WITH_OPENGL
1294
1295#include <GL/gl.h>
1296#include "../3rdparty/opengl/glext.h"
1297#include "../3rdparty/opengl/wglext.h"
1298#include "opengl.h"
1299
1300#ifndef PFD_SUPPORT_COMPOSITION
1301# define PFD_SUPPORT_COMPOSITION 0x00008000
1302#endif
1303
1304static PFNWGLCREATECONTEXTATTRIBSARBPROC _wglCreateContextAttribsARB = nullptr;
1305static PFNWGLSWAPINTERVALEXTPROC _wglSwapIntervalEXT = nullptr;
1306static bool _hasWGLARBCreateContextProfile = false;
1307
1309static OGLProc GetOGLProcAddressCallback(const char *proc)
1310{
1311 OGLProc ret = reinterpret_cast<OGLProc>(wglGetProcAddress(proc));
1312 if (ret == nullptr) {
1313 /* Non-extension GL function? Try normal loading. */
1314 ret = reinterpret_cast<OGLProc>(GetProcAddress(GetModuleHandle(L"opengl32"), proc));
1315 }
1316 return ret;
1317}
1318
1324static std::optional<std::string_view> SelectPixelFormat(HDC dc)
1325{
1326 PIXELFORMATDESCRIPTOR pfd = {
1327 sizeof(PIXELFORMATDESCRIPTOR), // Size of this struct.
1328 1, // Version of this struct.
1329 PFD_DRAW_TO_WINDOW | // Require window support.
1330 PFD_SUPPORT_OPENGL | // Require OpenGL support.
1331 PFD_DOUBLEBUFFER | // Use double buffering.
1332 PFD_DEPTH_DONTCARE,
1333 PFD_TYPE_RGBA, // Request RGBA format.
1334 24, // 24 bpp (excluding alpha).
1335 0, 0, 0, 0, 0, 0, 0, 0, // Colour bits and shift ignored.
1336 0, 0, 0, 0, 0, // No accumulation buffer.
1337 0, 0, // No depth/stencil buffer.
1338 0, // No aux buffers.
1339 PFD_MAIN_PLANE, // Main layer.
1340 0, 0, 0, 0 // Ignored/reserved.
1341 };
1342
1343 pfd.dwFlags |= PFD_SUPPORT_COMPOSITION; // Make OpenTTD compatible with Aero.
1344
1345 /* Choose a suitable pixel format. */
1346 int format = ChoosePixelFormat(dc, &pfd);
1347 if (format == 0) return "No suitable pixel format found";
1348 if (!SetPixelFormat(dc, format, &pfd)) return "Can't set pixel format";
1349
1350 return std::nullopt;
1351}
1352
1354static void LoadWGLExtensions()
1355{
1356 /* Querying the supported WGL extensions and loading the matching
1357 * functions requires a valid context, even for the extensions
1358 * regarding context creation. To get around this, we create
1359 * a dummy window with a dummy context. The extension functions
1360 * remain valid even after this context is destroyed. */
1361 HWND wnd = CreateWindow(L"STATIC", L"dummy", WS_OVERLAPPEDWINDOW, 0, 0, 0, 0, nullptr, nullptr, GetModuleHandle(nullptr), nullptr);
1362 HDC dc = GetDC(wnd);
1363
1364 /* Set pixel format of the window. */
1365 if (SelectPixelFormat(dc) == std::nullopt) {
1366 /* Create rendering context. */
1367 HGLRC rc = wglCreateContext(dc);
1368 if (rc != nullptr) {
1369 wglMakeCurrent(dc, rc);
1370
1371#ifdef __MINGW32__
1372 /* GCC doesn't understand the expected usage of wglGetProcAddress(). */
1373#pragma GCC diagnostic push
1374#pragma GCC diagnostic ignored "-Wcast-function-type"
1375#endif /* __MINGW32__ */
1376
1377 /* Get list of WGL extensions. */
1378 PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsStringARB");
1379 if (wglGetExtensionsStringARB != nullptr) {
1380 std::string_view wgl_exts = wglGetExtensionsStringARB(dc);
1381 /* Bind supported functions. */
1382 if (HasStringInExtensionList(wgl_exts, "WGL_ARB_create_context")) {
1383 _wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB");
1384 }
1385 _hasWGLARBCreateContextProfile = HasStringInExtensionList(wgl_exts, "WGL_ARB_create_context_profile");
1386 if (HasStringInExtensionList(wgl_exts, "WGL_EXT_swap_control")) {
1387 _wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT");
1388 }
1389 }
1390
1391#ifdef __MINGW32__
1392#pragma GCC diagnostic pop
1393#endif
1394 wglMakeCurrent(nullptr, nullptr);
1395 wglDeleteContext(rc);
1396 }
1397 }
1398
1399 ReleaseDC(wnd, dc);
1400 DestroyWindow(wnd);
1401}
1402
1403static FVideoDriver_Win32OpenGL iFVideoDriver_Win32OpenGL;
1404
1405std::optional<std::string_view> VideoDriver_Win32OpenGL::Start(const StringList &param)
1406{
1407 if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 0) return "Only real blitters supported";
1408
1409 Dimension old_res = _cur_resolution; // Save current screen resolution in case of errors, as MakeWindow invalidates it.
1410
1411 LoadWGLExtensions();
1412
1413 this->Initialize();
1414 this->MakeWindow(_fullscreen);
1415
1416 /* Create and initialize OpenGL context. */
1417 auto err = this->AllocateContext();
1418 if (err) {
1419 this->Stop();
1420 _cur_resolution = old_res;
1421 return err;
1422 }
1423
1424 this->driver_info = GetName();
1425 this->driver_info += " (";
1426 this->driver_info += OpenGLBackend::Get()->GetDriverName();
1427 this->driver_info += ")";
1428
1429 this->ClientSizeChanged(this->width, this->height, true);
1430 /* We should have a valid screen buffer now. If not, something went wrong and we should abort. */
1431 if (_screen.dst_ptr == nullptr) {
1432 this->Stop();
1433 _cur_resolution = old_res;
1434 return "Can't get pointer to screen buffer";
1435 }
1436 /* Main loop expects to start with the buffer unmapped. */
1437 this->ReleaseVideoPointer();
1438
1440
1441 this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread");
1442
1443 return std::nullopt;
1444}
1445
1446void VideoDriver_Win32OpenGL::Stop()
1447{
1448 this->DestroyContext();
1450}
1451
1452void VideoDriver_Win32OpenGL::DestroyContext()
1453{
1455
1456 wglMakeCurrent(nullptr, nullptr);
1457 if (this->gl_rc != nullptr) {
1458 wglDeleteContext(this->gl_rc);
1459 this->gl_rc = nullptr;
1460 }
1461 if (this->dc != nullptr) {
1462 ReleaseDC(this->main_wnd, this->dc);
1463 this->dc = nullptr;
1464 }
1465}
1466
1467void VideoDriver_Win32OpenGL::ToggleVsync(bool vsync)
1468{
1469 if (_wglSwapIntervalEXT != nullptr) {
1470 _wglSwapIntervalEXT(vsync);
1471 } else if (vsync) {
1472 Debug(driver, 0, "OpenGL: Vsync requested, but not supported by driver");
1473 }
1474}
1475
1476std::optional<std::string_view> VideoDriver_Win32OpenGL::AllocateContext()
1477{
1478 this->dc = GetDC(this->main_wnd);
1479
1480 auto err = SelectPixelFormat(this->dc);
1481 if (err) return err;
1482
1483 HGLRC rc = nullptr;
1484
1485 /* Create OpenGL device context. Try to get an 3.2+ context if possible. */
1486 if (_wglCreateContextAttribsARB != nullptr) {
1487 /* Try for OpenGL 4.5 first. */
1488 int attribs[] = {
1489 WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
1490 WGL_CONTEXT_MINOR_VERSION_ARB, 5,
1491 WGL_CONTEXT_FLAGS_ARB, _debug_driver_level >= 8 ? WGL_CONTEXT_DEBUG_BIT_ARB : 0,
1492 _hasWGLARBCreateContextProfile ? WGL_CONTEXT_PROFILE_MASK_ARB : 0, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, // Terminate list if WGL_ARB_create_context_profile isn't supported.
1493 0
1494 };
1495 rc = _wglCreateContextAttribsARB(this->dc, nullptr, attribs);
1496
1497 if (rc == nullptr) {
1498 /* Try again for a 3.2 context. */
1499 attribs[1] = 3;
1500 attribs[3] = 2;
1501 rc = _wglCreateContextAttribsARB(this->dc, nullptr, attribs);
1502 }
1503 }
1504
1505 if (rc == nullptr) {
1506 /* Old OpenGL or old driver, let's hope for the best. */
1507 rc = wglCreateContext(this->dc);
1508 if (rc == nullptr) return "Can't create OpenGL context";
1509 }
1510 if (!wglMakeCurrent(this->dc, rc)) return "Can't active GL context";
1511
1512 this->ToggleVsync(_video_vsync);
1513
1514 this->gl_rc = rc;
1515 return OpenGLBackend::Create(&GetOGLProcAddressCallback, this->GetScreenSize());
1516}
1517
1518bool VideoDriver_Win32OpenGL::ToggleFullscreen(bool full_screen)
1519{
1520 if (_screen.dst_ptr != nullptr) this->ReleaseVideoPointer();
1521 this->DestroyContext();
1522 bool res = this->VideoDriver_Win32Base::ToggleFullscreen(full_screen);
1523 res &= this->AllocateContext() == std::nullopt;
1524 this->ClientSizeChanged(this->width, this->height, true);
1525 return res;
1526}
1527
1528bool VideoDriver_Win32OpenGL::AfterBlitterChange()
1529{
1530 assert(BlitterFactory::GetCurrentBlitter()->GetScreenDepth() != 0);
1531 this->ClientSizeChanged(this->width, this->height, true);
1532 return true;
1533}
1534
1535void VideoDriver_Win32OpenGL::PopulateSystemSprites()
1536{
1537 OpenGLBackend::Get()->PopulateCursorCache();
1538}
1539
1540void VideoDriver_Win32OpenGL::ClearSystemSprites()
1541{
1543}
1544
1545bool VideoDriver_Win32OpenGL::AllocateBackingStore(int w, int h, bool force)
1546{
1547 if (!force && w == _screen.width && h == _screen.height) return false;
1548
1549 this->width = w = std::max(w, 64);
1550 this->height = h = std::max(h, 64);
1551
1552 if (this->gl_rc == nullptr) return false;
1553
1554 if (_screen.dst_ptr != nullptr) this->ReleaseVideoPointer();
1555
1556 this->dirty_rect = {};
1557 bool res = OpenGLBackend::Get()->Resize(w, h, force);
1558 SwapBuffers(this->dc);
1559 _screen.dst_ptr = this->GetVideoPointer();
1560
1561 return res;
1562}
1563
1564void *VideoDriver_Win32OpenGL::GetVideoPointer()
1565{
1566 if (BlitterFactory::GetCurrentBlitter()->NeedsAnimationBuffer()) {
1567 this->anim_buffer = OpenGLBackend::Get()->GetAnimBuffer();
1568 }
1570}
1571
1572void VideoDriver_Win32OpenGL::ReleaseVideoPointer()
1573{
1574 if (this->anim_buffer != nullptr) OpenGLBackend::Get()->ReleaseAnimBuffer(this->dirty_rect);
1575 OpenGLBackend::Get()->ReleaseVideoBuffer(this->dirty_rect);
1576 this->dirty_rect = {};
1577 _screen.dst_ptr = nullptr;
1578 this->anim_buffer = nullptr;
1579}
1580
1581void VideoDriver_Win32OpenGL::Paint()
1582{
1583 PerformanceMeasurer framerate(PFE_VIDEO);
1584
1585 if (_local_palette.count_dirty != 0) {
1587
1588 /* Always push a changed palette to OpenGL. */
1592 }
1593
1595 }
1596
1599
1600 SwapBuffers(this->dc);
1601}
1602
1603#endif /* WITH_OPENGL */
#define AS(ap_name, size_x, size_y, min_year, max_year, catchment, noise, maint_cost, ttdpatch_type, class_id, name, preview)
AirportSpec definition for airports with at least one depot.
debug_inline constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
debug_inline static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition factory.hpp:136
How all blitters should look like.
Definition base.hpp:29
virtual uint8_t GetScreenDepth()=0
Get the screen depth this blitter works for.
virtual Blitter::PaletteAnimation UsePaletteAnimation()=0
Check if the blitter uses palette animation at all.
virtual void PaletteAnimate(const Palette &palette)=0
Called when the 8bpp palette is changed; you should redraw all pixels on the screen that are equal to...
@ None
No palette animation.
@ Blitter
The blitter takes care of the palette animation.
@ VideoBackend
Palette animation should be done by video backend (8bpp only!)
virtual void PostResize()
Post resize event.
Definition base.hpp:205
The factory for Windows' video driver.
Definition win32_v.h:110
Function GetFunction(const std::string &symbol_name)
Get a function from a loaded library.
uint current_x
Current horizontal size (after resizing).
int pos_y
Vertical position of top-left corner of the widget in the window.
int pos_x
Horizontal position of top-left corner of the widget in the window.
uint current_y
Current vertical size (after resizing).
void Paint()
Render video buffer to the screen.
Definition opengl.cpp:1039
uint8_t * GetAnimBuffer()
Get a pointer to the memory for the separate animation buffer.
Definition opengl.cpp:1170
void * GetVideoBuffer()
Get a pointer to the memory for the video driver to draw to.
Definition opengl.cpp:1148
bool Resize(int w, int h, bool force=false)
Change the size of the drawing window and allocate matching resources.
Definition opengl.cpp:913
static std::optional< std::string_view > Create(GetOGLProcAddressProc get_proc, const Dimension &screen_res)
Create and initialize the singleton back-end class.
Definition opengl.cpp:464
void UpdatePalette(const Colour *pal, uint first, uint length)
Update the stored palette.
Definition opengl.cpp:1025
void ReleaseAnimBuffer(const Rect &update_rect)
Update animation buffer texture after the animation buffer was filled.
Definition opengl.cpp:1231
void ClearCursorCache()
Queue a request for cursor cache clear.
Definition opengl.cpp:1135
static OpenGLBackend * Get()
Get singleton instance of this class.
Definition opengl.h:83
void DrawMouseCursor()
Draw mouse cursor on screen.
Definition opengl.cpp:1071
void ReleaseVideoBuffer(const Rect &update_rect)
Update video buffer texture after the video buffer was filled.
Definition opengl.cpp:1193
static void Destroy()
Free resources and destroy singleton back-end class.
Definition opengl.cpp:477
RAII class for measuring simple elements of performance.
Constant span of UTF-8 encoded data.
Definition utf8.hpp:30
Base class for Windows video drivers.
Definition win32_v.h:19
int height
Height in pixels of our display surface.
Definition win32_v.h:45
bool has_focus
Does our window have system focus?
Definition win32_v.h:42
void EditBoxLostFocus() override
An edit box lost the input focus.
Definition win32_v.cpp:1012
void CheckPaletteAnim() override
Process any pending palette animation.
Definition win32_v.cpp:924
void Stop() override
Stop this driver.
Definition win32_v.cpp:911
int height_org
Original monitor resolution height, before we changed it.
Definition win32_v.h:47
HWND main_wnd
Handle to system window.
Definition win32_v.h:40
bool fullscreen
Whether to use (true) fullscreen mode.
Definition win32_v.h:41
int width_org
Original monitor resolution width, before we changed it.
Definition win32_v.h:46
bool MakeWindow(bool full_screen, bool resize=true)
Instantiate a new window.
Definition win32_v.cpp:142
bool buffer_locked
Video buffer was locked by the main thread.
Definition win32_v.h:49
virtual void * GetVideoPointer()=0
Get a pointer to the video buffer.
void MakeDirty(int left, int top, int width, int height) override
Mark a particular area dirty.
Definition win32_v.cpp:918
bool PollEvent() override
Process a single system event.
Definition win32_v.cpp:955
virtual void PaletteChanged(HWND hWnd)=0
Palette of the window has changed.
bool LockVideoBuffer() override
Make sure the video buffer is ready for drawing.
Definition win32_v.cpp:1089
std::vector< int > GetListOfMonitorRefreshRates() override
Get a list of refresh rates of each available monitor.
Definition win32_v.cpp:1036
virtual bool AllocateBackingStore(int w, int h, bool force=false)=0
(Re-)create the backing store.
int width
Width in pixels of our display surface.
Definition win32_v.h:44
void InputLoop() override
Handle input logic, is CTRL pressed, should we fast-forward, etc.
Definition win32_v.cpp:930
virtual uint8_t GetFullscreenBpp()
Get screen depth to use for fullscreen mode.
Definition win32_v.cpp:130
Dimension GetScreenSize() const override
Get the resolution of the main screen.
Definition win32_v.cpp:1043
virtual void ReleaseVideoPointer()
Hand video buffer back to the painting backend.
Definition win32_v.h:70
void UnlockVideoBuffer() override
Unlock a previously locked video buffer.
Definition win32_v.cpp:1100
void MainLoop() override
Perform the actual drawing.
Definition win32_v.cpp:968
Rect dirty_rect
Region of the screen that needs redrawing.
Definition win32_v.h:43
float GetDPIScale() override
Get DPI scaling factor of the screen OTTD is displayed on.
Definition win32_v.cpp:1048
bool ToggleFullscreen(bool fullscreen) override
Change the full screen setting.
Definition win32_v.cpp:1004
bool ChangeResolution(int w, int h) override
Change the resolution of the window.
Definition win32_v.cpp:994
The GDI video driver for windows.
Definition win32_v.h:78
void * buffer_bits
Internal rendering buffer.
Definition win32_v.h:93
HBITMAP dib_sect
System bitmap object referencing our rendering buffer.
Definition win32_v.h:91
void PaletteChanged(HWND hWnd) override
Palette of the window has changed.
Definition win32_v.cpp:1219
std::optional< std::string_view > Start(const StringList &param) override
Start this driver.
Definition win32_v.cpp:1115
void * GetVideoPointer() override
Get a pointer to the video buffer.
Definition win32_v.h:96
HPALETTE gdi_palette
Palette object for 8bpp blitter.
Definition win32_v.h:92
bool AllocateBackingStore(int w, int h, bool force=false) override
(Re-)create the backing store.
Definition win32_v.cpp:1140
void Paint() override
Paint the window.
Definition win32_v.cpp:1230
bool AfterBlitterChange() override
Callback invoked after the blitter was changed.
Definition win32_v.cpp:1178
void Stop() override
Stop this driver.
Definition win32_v.cpp:1132
bool fast_forward_key_pressed
The fast-forward key is being pressed.
void Tick()
Give the video-driver a tick.
void SleepTillNextTick()
Sleep till the next tick is about to happen.
void StartGameThread()
Start the loop for game-tick.
static std::string GetCaption()
Get the caption to use for the game's title bar.
void StopGameThread()
Stop the loop for the game-tick.
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
void UpdateAutoResolution()
Apply resolution auto-detection and clamp to sensible defaults.
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
bool GetDriverParamBool(const StringList &parm, std::string_view name)
Get a boolean parameter the list of parameters.
Definition driver.cpp:67
std::vector< Dimension > _resolutions
List of resolutions.
Definition driver.cpp:28
Dimension _cur_resolution
The current resolution.
Definition driver.cpp:29
fluid_settings_t * settings
FluidSynth settings handle.
@ PFE_VIDEO
Speed of painting drawn video buffer.
Rect BoundingRect(const Rect &r1, const Rect &r2)
Compute the bounding rectangle around two rectangles.
bool IsEmptyRect(const Rect &r)
Check if a rectangle is empty.
bool _shift_pressed
Is Shift pressed?
Definition gfx.cpp:39
bool _left_button_down
Is left mouse button pressed?
Definition gfx.cpp:41
bool _ctrl_pressed
Is Ctrl pressed?
Definition gfx.cpp:38
uint8_t _dirkeys
1 = left, 2 = up, 4 = right, 8 = down
Definition gfx.cpp:34
bool _left_button_clicked
Is left mouse button clicked?
Definition gfx.cpp:42
bool _right_button_clicked
Is right mouse button clicked?
Definition gfx.cpp:44
bool _right_button_down
Is right mouse button pressed?
Definition gfx.cpp:43
bool AdjustGUIZoom(bool automatic)
Resolve GUI zoom level and adjust GUI to new zoom, if auto-suggestion is requested.
Definition gfx.cpp:1799
void HandleCtrlChanged()
State of CONTROL key has changed.
Definition window.cpp:2677
void UpdateWindows()
Update the continuously changing contents of the windows, such as the viewports.
Definition window.cpp:3095
void GameSizeChanged()
Size of the application screen changed.
Definition main_gui.cpp:596
void HandleMouseEvents()
Handle a mouse event from the video driver.
Definition window.cpp:2934
void HandleKeypress(uint keycode, char32_t key)
Handle keyboard input.
Definition window.cpp:2621
void HandleTextInput(std::string_view str, bool marked=false, std::optional< size_t > caret=std::nullopt, std::optional< size_t > insert_location=std::nullopt, std::optional< size_t > replacement_end=std::nullopt)
Handle text input.
Definition window.cpp:2707
@ S8BPP_HARDWARE
Full 8bpp support by OS and hardware.
Definition gfx_type.h:378
@ WKC_BACKSLASH
\ Backslash
Definition gfx_type.h:101
@ WKC_MINUS
Definition gfx_type.h:106
@ WKC_COMMA
, Comma
Definition gfx_type.h:104
@ WKC_PERIOD
. Period
Definition gfx_type.h:105
@ WKC_EQUALS
= Equals
Definition gfx_type.h:99
@ WKC_SLASH
/ Forward slash
Definition gfx_type.h:97
@ WKC_SINGLEQUOTE
' Single quote
Definition gfx_type.h:103
@ WKC_R_BRACKET
] Right square bracket
Definition gfx_type.h:102
@ WKC_L_BRACKET
[ Left square bracket
Definition gfx_type.h:100
@ WKC_SEMICOLON
; Semicolon
Definition gfx_type.h:98
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1535
constexpr bool IsInsideBS(const T x, const size_t base, const size_t size)
Checks if a value is between a window started at some base point.
constexpr T Align(const T x, uint n)
Return the smallest multiple of n equal or greater than x.
Definition math_func.hpp:37
OpenGL video driver support.
void GetKeyboardLayout()
Retrieve keyboard layout from language string or (if set) config file.
Definition osk_gui.cpp:352
bool CopyPalette(Palette &local_palette, bool force_copy)
Copy the current palette if the palette was updated.
Definition palette.cpp:225
static OGLProc GetOGLProcAddressCallback(const char *proc)
Platform-specific callback to get an OpenGL function pointer.
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:59
char32_t Utf16DecodeSurrogate(uint lead, uint trail)
Convert an UTF-16 surrogate pair to the corresponding Unicode character.
Definition string_func.h:87
bool Utf16IsLeadSurrogate(uint c)
Is the given character a lead surrogate code point?
Definition string_func.h:66
bool Utf16IsTrailSurrogate(uint c)
Is the given character a lead surrogate code point?
Definition string_func.h:76
std::vector< std::string > StringList
Type for a list of strings.
Definition string_type.h:60
GUISettings gui
settings related to the GUI
bool UpdateCursorPosition(int x, int y)
Update cursor position on mouse movement.
Definition gfx.cpp:1734
bool fix_at
mouse is moving, but cursor is not (used for scrolling)
Definition gfx_type.h:129
Point pos
logical mouse position
Definition gfx_type.h:126
bool in_window
mouse inside this window, determines drawing logic
Definition gfx_type.h:148
int wheel
mouse wheel movement
Definition gfx_type.h:128
Dimensions (a width and height) of a rectangle in 2D.
uint8_t scrollwheel_multiplier
how much 'wheel' per incoming event from the OS?
Information about the currently used palette.
Definition gfx_type.h:368
int first_dirty
The first dirty element.
Definition gfx_type.h:370
int count_dirty
The number of dirty elements.
Definition gfx_type.h:371
Colour palette[256]
Current palette. Entry 0 has to be always fully transparent!
Definition gfx_type.h:369
Coordinates of a point in 2D.
Specification of a rectangle with absolute coordinates of all edges.
WindowClass window_class
Window class.
Definition window_gui.h:301
virtual Point GetCaretPosition() const
Get the current caret position if an edit box has the focus.
Definition window.cpp:376
int left
x position of left edge of the window
Definition window_gui.h:309
const NWidgetCore * nested_focus
Currently focused nested widget, or nullptr if no nested widget has focus.
Definition window_gui.h:319
int top
y position of top edge of the window
Definition window_gui.h:310
int height
Height of the window (number of pixels down in y direction)
Definition window_gui.h:312
int width
width of the window (number of pixels to the right in x direction)
Definition window_gui.h:311
bool _video_vsync
Whether we should use vsync (only if active video driver supports HW acceleration).
std::string_view convert_from_fs(const std::wstring_view src, std::span< char > dst_buf)
Convert to OpenTTD's encoding from that of the environment in UNICODE.
Definition win32.cpp:372
std::wstring OTTD2FS(std::string_view name)
Convert from OpenTTD's encoding to a wide string.
Definition win32.cpp:354
std::string FS2OTTD(std::wstring_view name)
Convert to OpenTTD's encoding from a wide string.
Definition win32.cpp:337
static Palette _local_palette
Current palette to use for drawing.
Definition win32_v.cpp:54
static LRESULT HandleCharMsg(uint keycode, char32_t charcode)
Forward key presses to the window system.
Definition win32_v.cpp:244
static bool DrawIMECompositionString()
Should we draw the composition string ourself, i.e is this a normal IME?
Definition win32_v.cpp:271
static LRESULT HandleIMEComposition(HWND hwnd, WPARAM wParam, LPARAM lParam)
Handle WM_IME_COMPOSITION messages.
Definition win32_v.cpp:333
static void SetCandidatePos(HWND hwnd)
Set the position of the candidate window.
Definition win32_v.cpp:299
static void CancelIMEComposition(HWND hwnd)
Clear the current composition string.
Definition win32_v.cpp:395
static void SetCompositionPos(HWND hwnd)
Set position of the composition window to the caret position.
Definition win32_v.cpp:277
Base of the Windows video driver.
void ReInitAllWindows(bool zoom_changed)
Re-initialize all windows.
Definition window.cpp:3381
bool EditBoxInGlobalFocus()
Check if an edit box is in global focus.
Definition window.cpp:446
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Definition window.cpp:3282
@ WC_CONSOLE
Console; Window numbers:
@ WC_GAME_OPTIONS
Game options window; Window numbers: