Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/platform/windows/os_windows.cpp
20892 views
1
/**************************************************************************/
2
/* os_windows.cpp */
3
/**************************************************************************/
4
/* This file is part of: */
5
/* GODOT ENGINE */
6
/* https://godotengine.org */
7
/**************************************************************************/
8
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10
/* */
11
/* Permission is hereby granted, free of charge, to any person obtaining */
12
/* a copy of this software and associated documentation files (the */
13
/* "Software"), to deal in the Software without restriction, including */
14
/* without limitation the rights to use, copy, modify, merge, publish, */
15
/* distribute, sublicense, and/or sell copies of the Software, and to */
16
/* permit persons to whom the Software is furnished to do so, subject to */
17
/* the following conditions: */
18
/* */
19
/* The above copyright notice and this permission notice shall be */
20
/* included in all copies or substantial portions of the Software. */
21
/* */
22
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29
/**************************************************************************/
30
31
#include "os_windows.h"
32
33
#include "display_server_windows.h"
34
#include "lang_table.h"
35
#include "windows_terminal_logger.h"
36
#include "windows_utils.h"
37
38
#include "core/debugger/engine_debugger.h"
39
#include "core/debugger/script_debugger.h"
40
#include "core/io/marshalls.h"
41
#include "core/os/main_loop.h"
42
#include "core/profiling/profiling.h"
43
#include "core/version_generated.gen.h"
44
#include "drivers/windows/dir_access_windows.h"
45
#include "drivers/windows/file_access_windows.h"
46
#include "drivers/windows/file_access_windows_pipe.h"
47
#include "drivers/windows/ip_windows.h"
48
#include "drivers/windows/net_socket_winsock.h"
49
#include "drivers/windows/thread_windows.h"
50
#include "main/main.h"
51
#include "servers/audio/audio_server.h"
52
#include "servers/rendering/rendering_server_default.h"
53
#include "servers/text/text_server.h"
54
55
#include <avrt.h>
56
#include <bcrypt.h>
57
#include <direct.h>
58
#include <knownfolders.h>
59
#include <process.h>
60
#include <psapi.h>
61
#include <regstr.h>
62
#include <shlobj.h>
63
#include <wbemcli.h>
64
#include <wincrypt.h>
65
#include <winternl.h>
66
67
// Workaround missing `extern "C"` in MinGW-w64 < 12.0.0.
68
#if defined(__MINGW32__) && (!defined(__MINGW64_VERSION_MAJOR) || __MINGW64_VERSION_MAJOR < 12)
69
extern "C" {
70
#include <hidsdi.h>
71
}
72
#else
73
#include <hidsdi.h>
74
#endif
75
76
#if defined(RD_ENABLED)
77
#include "servers/rendering/rendering_device.h"
78
#endif
79
80
#if defined(GLES3_ENABLED)
81
#include "gl_manager_windows_native.h"
82
#endif
83
84
#if defined(VULKAN_ENABLED)
85
#include "rendering_context_driver_vulkan_windows.h"
86
#endif
87
#if defined(D3D12_ENABLED)
88
#include "drivers/d3d12/rendering_context_driver_d3d12.h"
89
#endif
90
#if defined(GLES3_ENABLED)
91
#include "drivers/gles3/rasterizer_gles3.h"
92
#endif
93
94
#ifdef DEBUG_ENABLED
95
#pragma pack(push, before_imagehlp, 8)
96
#include <imagehlp.h>
97
#pragma pack(pop, before_imagehlp)
98
#endif
99
100
extern "C" {
101
__declspec(dllexport) DWORD NvOptimusEnablement = 1;
102
__declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
103
__declspec(dllexport) void NoHotPatch() {} // Disable Nahimic code injection.
104
}
105
106
// Workaround mingw-w64 < 4.0 bug
107
#ifndef WM_TOUCH
108
#define WM_TOUCH 576
109
#endif
110
111
#ifndef WM_POINTERUPDATE
112
#define WM_POINTERUPDATE 0x0245
113
#endif
114
115
// Missing in MinGW headers before 8.0.
116
#ifndef DWRITE_FONT_WEIGHT_SEMI_LIGHT
117
#define DWRITE_FONT_WEIGHT_SEMI_LIGHT (DWRITE_FONT_WEIGHT)350
118
#endif
119
120
static String fix_path(const String &p_path) {
121
String path = p_path;
122
if (p_path.is_relative_path()) {
123
Char16String current_dir_name;
124
size_t str_len = GetCurrentDirectoryW(0, nullptr);
125
current_dir_name.resize_uninitialized(str_len + 1);
126
GetCurrentDirectoryW(current_dir_name.size(), (LPWSTR)current_dir_name.ptrw());
127
path = String::utf16((const char16_t *)current_dir_name.get_data()).trim_prefix(R"(\\?\)").replace_char('\\', '/').path_join(path);
128
}
129
path = path.simplify_path();
130
path = path.replace_char('/', '\\');
131
if (path.size() >= MAX_PATH && !path.is_network_share_path() && !path.begins_with(R"(\\?\)")) {
132
path = R"(\\?\)" + path;
133
}
134
return path;
135
}
136
137
static String format_error_message(DWORD id) {
138
LPWSTR messageBuffer = nullptr;
139
size_t size = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
140
nullptr, id, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&messageBuffer, 0, nullptr);
141
142
String msg = "Error " + itos(id) + ": " + String::utf16((const char16_t *)messageBuffer, size);
143
144
LocalFree(messageBuffer);
145
146
return msg.remove_chars("\r\n");
147
}
148
149
void RedirectStream(const char *p_file_name, const char *p_mode, FILE *p_cpp_stream, const DWORD p_std_handle) {
150
const HANDLE h_existing = GetStdHandle(p_std_handle);
151
if (h_existing != INVALID_HANDLE_VALUE) { // Redirect only if attached console have a valid handle.
152
const HANDLE h_cpp = reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(p_cpp_stream)));
153
if (h_cpp == INVALID_HANDLE_VALUE) { // Redirect only if it's not already redirected to the pipe or file.
154
FILE *fp = p_cpp_stream;
155
freopen_s(&fp, p_file_name, p_mode, p_cpp_stream); // Redirect stream.
156
setvbuf(p_cpp_stream, nullptr, _IONBF, 0); // Disable stream buffering.
157
}
158
}
159
}
160
161
void RedirectIOToConsole() {
162
// Save current handles.
163
HANDLE h_stdin = GetStdHandle(STD_INPUT_HANDLE);
164
HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
165
HANDLE h_stderr = GetStdHandle(STD_ERROR_HANDLE);
166
167
if (AttachConsole(ATTACH_PARENT_PROCESS)) {
168
// Restore redirection (Note: if not redirected it's NULL handles not INVALID_HANDLE_VALUE).
169
if (h_stdin != nullptr) {
170
SetStdHandle(STD_INPUT_HANDLE, h_stdin);
171
}
172
if (h_stdout != nullptr) {
173
SetStdHandle(STD_OUTPUT_HANDLE, h_stdout);
174
}
175
if (h_stderr != nullptr) {
176
SetStdHandle(STD_ERROR_HANDLE, h_stderr);
177
}
178
179
// Update file handles.
180
RedirectStream("CONIN$", "r", stdin, STD_INPUT_HANDLE);
181
RedirectStream("CONOUT$", "w", stdout, STD_OUTPUT_HANDLE);
182
RedirectStream("CONOUT$", "w", stderr, STD_ERROR_HANDLE);
183
}
184
}
185
186
bool OS_Windows::is_using_con_wrapper() const {
187
static String exe_renames[] = {
188
".console.exe",
189
"_console.exe",
190
" console.exe",
191
"console.exe",
192
String(),
193
};
194
195
bool found_exe = false;
196
bool found_conwrap_exe = false;
197
String exe_name = get_executable_path().to_lower();
198
String exe_dir = exe_name.get_base_dir();
199
String exe_fname = exe_name.get_file().get_basename();
200
201
DWORD pids[256];
202
DWORD count = GetConsoleProcessList(&pids[0], 256);
203
for (DWORD i = 0; i < count; i++) {
204
HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pids[i]);
205
if (process != NULL) {
206
WCHAR proc_name[MAX_PATH];
207
DWORD len = MAX_PATH;
208
if (QueryFullProcessImageNameW(process, 0, &proc_name[0], &len)) {
209
String name = String::utf16((const char16_t *)&proc_name[0], len).replace_char('\\', '/').to_lower();
210
if (name == exe_name) {
211
found_exe = true;
212
}
213
for (int j = 0; !exe_renames[j].is_empty(); j++) {
214
if (name == exe_dir.path_join(exe_fname + exe_renames[j])) {
215
found_conwrap_exe = true;
216
}
217
}
218
}
219
CloseHandle(process);
220
if (found_conwrap_exe && found_exe) {
221
break;
222
}
223
}
224
}
225
if (!found_exe) {
226
return true; // Unable to read console info, assume true.
227
}
228
229
return found_conwrap_exe;
230
}
231
232
BOOL WINAPI HandlerRoutine(_In_ DWORD dwCtrlType) {
233
if (!EngineDebugger::is_active()) {
234
return FALSE;
235
}
236
237
switch (dwCtrlType) {
238
case CTRL_C_EVENT:
239
EngineDebugger::get_script_debugger()->set_depth(-1);
240
EngineDebugger::get_script_debugger()->set_lines_left(1);
241
return TRUE;
242
default:
243
return FALSE;
244
}
245
}
246
247
void OS_Windows::alert(const String &p_alert, const String &p_title) {
248
MessageBoxW(nullptr, (LPCWSTR)(p_alert.utf16().get_data()), (LPCWSTR)(p_title.utf16().get_data()), MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
249
}
250
251
void OS_Windows::initialize_debugging() {
252
SetConsoleCtrlHandler(HandlerRoutine, TRUE);
253
}
254
255
#ifdef WINDOWS_DEBUG_OUTPUT_ENABLED
256
static void _error_handler(void *p_self, const char *p_func, const char *p_file, int p_line, const char *p_error, const char *p_errorexp, bool p_editor_notify, ErrorHandlerType p_type) {
257
String err_str;
258
if (p_errorexp && p_errorexp[0]) {
259
err_str = String::utf8(p_errorexp) + "\n";
260
} else {
261
err_str = String::utf8(p_file) + ":" + itos(p_line) + " - " + String::utf8(p_error) + "\n";
262
}
263
264
OutputDebugStringW((LPCWSTR)err_str.utf16().ptr());
265
}
266
#endif
267
268
void OS_Windows::initialize() {
269
crash_handler.initialize();
270
271
#ifdef WINDOWS_DEBUG_OUTPUT_ENABLED
272
error_handlers.errfunc = _error_handler;
273
error_handlers.userdata = this;
274
add_error_handler(&error_handlers);
275
#endif
276
277
#ifdef THREADS_ENABLED
278
init_thread_win();
279
#endif
280
281
FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_RESOURCES);
282
FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_USERDATA);
283
FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_FILESYSTEM);
284
FileAccess::make_default<FileAccessWindowsPipe>(FileAccess::ACCESS_PIPE);
285
DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_RESOURCES);
286
DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_USERDATA);
287
DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_FILESYSTEM);
288
289
NetSocketWinSock::make_default();
290
291
// We need to know how often the clock is updated
292
QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second);
293
QueryPerformanceCounter((LARGE_INTEGER *)&ticks_start);
294
295
#if WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP
296
// set minimum resolution for periodic timers, otherwise Sleep(n) may wait at least as
297
// long as the windows scheduler resolution (~16-30ms) even for calls like Sleep(1)
298
TIMECAPS time_caps;
299
if (timeGetDevCaps(&time_caps, sizeof(time_caps)) == MMSYSERR_NOERROR) {
300
delay_resolution = time_caps.wPeriodMin * 1000;
301
timeBeginPeriod(time_caps.wPeriodMin);
302
} else {
303
ERR_PRINT("Unable to detect sleep timer resolution.");
304
delay_resolution = 1000;
305
timeBeginPeriod(1);
306
}
307
#else
308
delay_resolution = 1000;
309
#endif
310
311
process_map = memnew((HashMap<ProcessID, ProcessInfo>));
312
313
// Add current Godot PID to the list of known PIDs
314
ProcessInfo current_pi = {};
315
PROCESS_INFORMATION current_pi_pi = {};
316
current_pi.pi = current_pi_pi;
317
current_pi.pi.hProcess = GetCurrentProcess();
318
process_map->insert(GetCurrentProcessId(), current_pi);
319
320
IPWindows::make_default();
321
main_loop = nullptr;
322
323
HRESULT hr = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), reinterpret_cast<IUnknown **>(&dwrite_factory));
324
if (SUCCEEDED(hr)) {
325
hr = dwrite_factory->GetSystemFontCollection(&font_collection, false);
326
if (SUCCEEDED(hr)) {
327
dwrite_init = true;
328
hr = dwrite_factory->QueryInterface(&dwrite_factory2);
329
if (SUCCEEDED(hr)) {
330
hr = dwrite_factory2->GetSystemFontFallback(&system_font_fallback);
331
if (SUCCEEDED(hr)) {
332
dwrite2_init = true;
333
}
334
}
335
}
336
}
337
if (!dwrite_init) {
338
print_verbose("Unable to load IDWriteFactory, system font support is disabled.");
339
} else if (!dwrite2_init) {
340
print_verbose("Unable to load IDWriteFactory2, automatic system font fallback is disabled.");
341
}
342
343
FileAccessWindows::initialize();
344
}
345
346
void OS_Windows::delete_main_loop() {
347
if (main_loop) {
348
memdelete(main_loop);
349
}
350
main_loop = nullptr;
351
}
352
353
void OS_Windows::set_main_loop(MainLoop *p_main_loop) {
354
main_loop = p_main_loop;
355
}
356
357
void OS_Windows::finalize() {
358
if (dwrite_factory2) {
359
dwrite_factory2->Release();
360
dwrite_factory2 = nullptr;
361
}
362
if (font_collection) {
363
font_collection->Release();
364
font_collection = nullptr;
365
}
366
if (system_font_fallback) {
367
system_font_fallback->Release();
368
system_font_fallback = nullptr;
369
}
370
if (dwrite_factory) {
371
dwrite_factory->Release();
372
dwrite_factory = nullptr;
373
}
374
#ifdef WINMIDI_ENABLED
375
driver_midi.close();
376
#endif
377
378
if (main_loop) {
379
memdelete(main_loop);
380
}
381
382
main_loop = nullptr;
383
}
384
385
void OS_Windows::finalize_core() {
386
while (!temp_libraries.is_empty()) {
387
_remove_temp_library(temp_libraries.last()->key);
388
}
389
390
FileAccessWindows::finalize();
391
392
#if WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP
393
timeEndPeriod(1);
394
#endif
395
396
memdelete(process_map);
397
NetSocketWinSock::cleanup();
398
399
#ifdef WINDOWS_DEBUG_OUTPUT_ENABLED
400
remove_error_handler(&error_handlers);
401
#endif
402
}
403
404
Error OS_Windows::get_entropy(uint8_t *r_buffer, int p_bytes) {
405
NTSTATUS status = BCryptGenRandom(nullptr, r_buffer, p_bytes, BCRYPT_USE_SYSTEM_PREFERRED_RNG);
406
ERR_FAIL_COND_V(status, FAILED);
407
return OK;
408
}
409
410
#ifdef DEBUG_ENABLED
411
void debug_dynamic_library_check_dependencies(const String &p_path, HashSet<String> &r_checked, HashSet<String> &r_missing) {
412
if (r_checked.has(p_path)) {
413
return;
414
}
415
r_checked.insert(p_path);
416
417
LOADED_IMAGE loaded_image;
418
HANDLE file = CreateFileW((LPCWSTR)p_path.utf16().get_data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
419
if (file != INVALID_HANDLE_VALUE) {
420
HANDLE file_mapping = CreateFileMappingW(file, nullptr, PAGE_READONLY | SEC_COMMIT, 0, 0, nullptr);
421
if (file_mapping != INVALID_HANDLE_VALUE) {
422
PVOID mapping = MapViewOfFile(file_mapping, FILE_MAP_READ, 0, 0, 0);
423
if (mapping) {
424
PIMAGE_DOS_HEADER dos_header = (PIMAGE_DOS_HEADER)mapping;
425
PIMAGE_NT_HEADERS nt_header = nullptr;
426
if (dos_header->e_magic == IMAGE_DOS_SIGNATURE) {
427
PCHAR nt_header_ptr;
428
nt_header_ptr = ((PCHAR)mapping) + dos_header->e_lfanew;
429
nt_header = (PIMAGE_NT_HEADERS)nt_header_ptr;
430
if (nt_header->Signature != IMAGE_NT_SIGNATURE) {
431
nt_header = nullptr;
432
}
433
}
434
if (nt_header) {
435
loaded_image.ModuleName = nullptr;
436
loaded_image.hFile = file;
437
loaded_image.MappedAddress = (PUCHAR)mapping;
438
loaded_image.FileHeader = nt_header;
439
loaded_image.Sections = (PIMAGE_SECTION_HEADER)((LPBYTE)&nt_header->OptionalHeader + nt_header->FileHeader.SizeOfOptionalHeader);
440
loaded_image.NumberOfSections = nt_header->FileHeader.NumberOfSections;
441
loaded_image.SizeOfImage = GetFileSize(file, nullptr);
442
loaded_image.Characteristics = nt_header->FileHeader.Characteristics;
443
loaded_image.LastRvaSection = loaded_image.Sections;
444
loaded_image.fSystemImage = false;
445
loaded_image.fDOSImage = false;
446
loaded_image.Links.Flink = &loaded_image.Links;
447
loaded_image.Links.Blink = &loaded_image.Links;
448
449
ULONG size = 0;
450
const IMAGE_IMPORT_DESCRIPTOR *import_desc = (const IMAGE_IMPORT_DESCRIPTOR *)ImageDirectoryEntryToData((HMODULE)loaded_image.MappedAddress, false, IMAGE_DIRECTORY_ENTRY_IMPORT, &size);
451
if (import_desc) {
452
for (; import_desc->Name && import_desc->FirstThunk; import_desc++) {
453
char16_t full_name_wc[32767];
454
const char *name_cs = (const char *)ImageRvaToVa(loaded_image.FileHeader, loaded_image.MappedAddress, import_desc->Name, nullptr);
455
String name = String(name_cs);
456
if (name.begins_with("api-ms-win-")) {
457
r_checked.insert(name);
458
} else if (SearchPathW(nullptr, (LPCWSTR)name.utf16().get_data(), nullptr, 32767, (LPWSTR)full_name_wc, nullptr)) {
459
debug_dynamic_library_check_dependencies(String::utf16(full_name_wc), r_checked, r_missing);
460
} else if (SearchPathW((LPCWSTR)(p_path.get_base_dir().utf16().get_data()), (LPCWSTR)name.utf16().get_data(), nullptr, 32767, (LPWSTR)full_name_wc, nullptr)) {
461
debug_dynamic_library_check_dependencies(String::utf16(full_name_wc), r_checked, r_missing);
462
} else {
463
r_missing.insert(name);
464
}
465
}
466
}
467
}
468
UnmapViewOfFile(mapping);
469
}
470
CloseHandle(file_mapping);
471
}
472
CloseHandle(file);
473
}
474
}
475
#endif
476
477
Error OS_Windows::open_dynamic_library(const String &p_path, void *&p_library_handle, GDExtensionData *p_data) {
478
String path = p_path;
479
480
if (!FileAccess::exists(path)) {
481
//this code exists so gdextension can load .dll files from within the executable path
482
path = get_executable_path().get_base_dir().path_join(p_path.get_file());
483
}
484
// Path to load from may be different from original if we make copies.
485
String load_path = path;
486
487
ERR_FAIL_COND_V(!FileAccess::exists(path), ERR_FILE_NOT_FOUND);
488
489
// Here we want a copy to be loaded.
490
// This is so the original file isn't locked and can be updated by a compiler.
491
if (p_data != nullptr && p_data->generate_temp_files) {
492
// Copy the file to the same directory as the original with a prefix in the name.
493
// This is so relative path to dependencies are satisfied.
494
load_path = path.get_base_dir().path_join("~" + path.get_file());
495
496
// If there's a left-over copy (possibly from a crash) then delete it first.
497
if (FileAccess::exists(load_path)) {
498
DirAccess::remove_absolute(load_path);
499
}
500
501
Error copy_err = DirAccess::copy_absolute(path, load_path);
502
if (copy_err) {
503
ERR_PRINT("Error copying library: " + path);
504
return ERR_CANT_CREATE;
505
}
506
507
FileAccess::set_hidden_attribute(load_path, true);
508
509
Error pdb_err = WindowsUtils::copy_and_rename_pdb(load_path);
510
if (pdb_err != OK && pdb_err != ERR_SKIP) {
511
WARN_PRINT(vformat("Failed to rename the PDB file. The original PDB file for '%s' will be loaded.", path));
512
}
513
}
514
515
DLL_DIRECTORY_COOKIE cookie = nullptr;
516
517
String dll_path = fix_path(load_path);
518
String dll_dir = fix_path(ProjectSettings::get_singleton()->globalize_path(load_path.get_base_dir()));
519
if (p_data != nullptr && p_data->also_set_library_path) {
520
cookie = AddDllDirectory((LPCWSTR)(dll_dir.utf16().get_data()));
521
}
522
523
p_library_handle = (void *)LoadLibraryExW((LPCWSTR)(dll_path.utf16().get_data()), nullptr, (p_data != nullptr && p_data->also_set_library_path) ? LOAD_LIBRARY_SEARCH_DEFAULT_DIRS : 0);
524
if (!p_library_handle) {
525
if (p_data != nullptr && p_data->generate_temp_files) {
526
DirAccess::remove_absolute(load_path);
527
}
528
529
#ifdef DEBUG_ENABLED
530
DWORD err_code = GetLastError();
531
532
HashSet<String> checked_libs;
533
HashSet<String> missing_libs;
534
debug_dynamic_library_check_dependencies(dll_path, checked_libs, missing_libs);
535
if (!missing_libs.is_empty()) {
536
String missing;
537
for (const String &E : missing_libs) {
538
if (!missing.is_empty()) {
539
missing += ", ";
540
}
541
missing += E;
542
}
543
ERR_FAIL_V_MSG(ERR_CANT_OPEN, vformat("Can't open dynamic library: %s. Missing dependencies: %s. Error: %s.", p_path, missing, format_error_message(err_code)));
544
} else {
545
ERR_FAIL_V_MSG(ERR_CANT_OPEN, vformat("Can't open dynamic library: %s. Error: %s.", p_path, format_error_message(err_code)));
546
}
547
#endif
548
}
549
550
#ifndef DEBUG_ENABLED
551
ERR_FAIL_NULL_V_MSG(p_library_handle, ERR_CANT_OPEN, vformat("Can't open dynamic library: %s. Error: %s.", p_path, format_error_message(GetLastError())));
552
#endif
553
554
if (cookie) {
555
RemoveDllDirectory(cookie);
556
}
557
558
if (p_data != nullptr && p_data->r_resolved_path != nullptr) {
559
*p_data->r_resolved_path = path;
560
}
561
562
if (p_data != nullptr && p_data->generate_temp_files) {
563
// Save the copied path so it can be deleted later.
564
temp_libraries[p_library_handle] = load_path;
565
}
566
567
return OK;
568
}
569
570
Error OS_Windows::close_dynamic_library(void *p_library_handle) {
571
if (!FreeLibrary((HMODULE)p_library_handle)) {
572
return FAILED;
573
}
574
575
// Delete temporary copy of library if it exists.
576
_remove_temp_library(p_library_handle);
577
578
return OK;
579
}
580
581
void OS_Windows::_remove_temp_library(void *p_library_handle) {
582
if (temp_libraries.has(p_library_handle)) {
583
String path = temp_libraries[p_library_handle];
584
DirAccess::remove_absolute(path);
585
WindowsUtils::remove_temp_pdbs(path);
586
temp_libraries.erase(p_library_handle);
587
}
588
}
589
590
Error OS_Windows::get_dynamic_library_symbol_handle(void *p_library_handle, const String &p_name, void *&p_symbol_handle, bool p_optional) {
591
p_symbol_handle = (void *)GetProcAddress((HMODULE)p_library_handle, p_name.utf8().get_data());
592
if (!p_symbol_handle) {
593
if (!p_optional) {
594
ERR_FAIL_V_MSG(ERR_CANT_RESOLVE, vformat("Can't resolve symbol %s, error: \"%s\".", p_name, format_error_message(GetLastError())));
595
} else {
596
return ERR_CANT_RESOLVE;
597
}
598
}
599
return OK;
600
}
601
602
String OS_Windows::get_name() const {
603
return "Windows";
604
}
605
606
String OS_Windows::get_distribution_name() const {
607
return get_name();
608
}
609
610
String OS_Windows::get_version() const {
611
RtlGetVersionPtr version_ptr = (RtlGetVersionPtr)(void *)GetProcAddress(GetModuleHandle("ntdll.dll"), "RtlGetVersion");
612
if (version_ptr != nullptr) {
613
RTL_OSVERSIONINFOEXW fow;
614
ZeroMemory(&fow, sizeof(fow));
615
fow.dwOSVersionInfoSize = sizeof(fow);
616
if (version_ptr(&fow) == 0x00000000) {
617
return vformat("%d.%d.%d", (int64_t)fow.dwMajorVersion, (int64_t)fow.dwMinorVersion, (int64_t)fow.dwBuildNumber);
618
}
619
}
620
return "";
621
}
622
623
String OS_Windows::get_version_alias() const {
624
RtlGetVersionPtr version_ptr = (RtlGetVersionPtr)(void *)GetProcAddress(GetModuleHandle("ntdll.dll"), "RtlGetVersion");
625
if (version_ptr != nullptr) {
626
RTL_OSVERSIONINFOEXW fow;
627
ZeroMemory(&fow, sizeof(fow));
628
fow.dwOSVersionInfoSize = sizeof(fow);
629
if (version_ptr(&fow) == 0x00000000) {
630
String windows_string;
631
if (fow.wProductType != VER_NT_WORKSTATION && fow.dwMajorVersion == 10 && fow.dwBuildNumber >= 26100) {
632
windows_string = "Server 2025";
633
} else if (fow.dwMajorVersion == 10 && fow.dwBuildNumber >= 20348) {
634
// Builds above 20348 correspond to Windows 11 / Windows Server 2022.
635
// Their major version numbers are still 10 though, not 11.
636
if (fow.wProductType != VER_NT_WORKSTATION) {
637
windows_string += "Server 2022";
638
} else {
639
windows_string += "11";
640
}
641
} else if (fow.dwMajorVersion == 10) {
642
if (fow.wProductType != VER_NT_WORKSTATION && fow.dwBuildNumber >= 17763) {
643
windows_string += "Server 2019";
644
} else {
645
if (fow.wProductType != VER_NT_WORKSTATION) {
646
windows_string += "Server 2016";
647
} else {
648
windows_string += "10";
649
}
650
}
651
} else {
652
windows_string += "Unknown";
653
}
654
// Windows versions older than 10 cannot run Godot.
655
656
return vformat("%s (build %d)", windows_string, (int64_t)fow.dwBuildNumber);
657
}
658
}
659
660
return "";
661
}
662
663
Vector<String> OS_Windows::_get_video_adapter_driver_info_reg(const String &p_name) const {
664
Vector<String> info;
665
666
String subkey = "SYSTEM\\CurrentControlSet\\Control\\Class\\{4d36e968-e325-11ce-bfc1-08002be10318}";
667
HKEY hkey = nullptr;
668
LSTATUS result = RegOpenKeyExW(HKEY_LOCAL_MACHINE, (LPCWSTR)subkey.utf16().get_data(), 0, KEY_READ, &hkey);
669
if (result != ERROR_SUCCESS) {
670
return Vector<String>();
671
}
672
673
DWORD subkeys = 0;
674
result = RegQueryInfoKeyW(hkey, nullptr, nullptr, nullptr, &subkeys, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
675
if (result != ERROR_SUCCESS) {
676
RegCloseKey(hkey);
677
return Vector<String>();
678
}
679
for (DWORD i = 0; i < subkeys; i++) {
680
WCHAR key_name[MAX_PATH] = L"";
681
DWORD key_name_size = MAX_PATH;
682
result = RegEnumKeyExW(hkey, i, key_name, &key_name_size, nullptr, nullptr, nullptr, nullptr);
683
if (result != ERROR_SUCCESS) {
684
continue;
685
}
686
String id = String::utf16((const char16_t *)key_name, key_name_size);
687
if (!id.is_empty()) {
688
HKEY sub_hkey = nullptr;
689
result = RegOpenKeyExW(HKEY_LOCAL_MACHINE, (LPCWSTR)(subkey + "\\" + id).utf16().get_data(), 0, KEY_QUERY_VALUE, &sub_hkey);
690
if (result != ERROR_SUCCESS) {
691
continue;
692
}
693
694
WCHAR buffer[4096];
695
DWORD buffer_len = 4096;
696
DWORD vtype = REG_SZ;
697
if (RegQueryValueExW(sub_hkey, L"DriverDesc", nullptr, &vtype, (LPBYTE)buffer, &buffer_len) != ERROR_SUCCESS || buffer_len == 0) {
698
buffer_len = 4096;
699
if (RegQueryValueExW(sub_hkey, L"HardwareInformation.AdapterString", nullptr, &vtype, (LPBYTE)buffer, &buffer_len) != ERROR_SUCCESS || buffer_len == 0) {
700
RegCloseKey(sub_hkey);
701
continue;
702
}
703
}
704
705
String driver_name = String::utf16((const char16_t *)buffer, buffer_len).strip_edges();
706
if (driver_name == p_name) {
707
String driver_provider = driver_name;
708
String driver_version;
709
710
buffer_len = 4096;
711
if (RegQueryValueExW(sub_hkey, L"ProviderName", nullptr, &vtype, (LPBYTE)buffer, &buffer_len) == ERROR_SUCCESS && buffer_len != 0) {
712
driver_provider = String::utf16((const char16_t *)buffer, buffer_len).strip_edges();
713
}
714
buffer_len = 4096;
715
if (RegQueryValueExW(sub_hkey, L"DriverVersion", nullptr, &vtype, (LPBYTE)buffer, &buffer_len) == ERROR_SUCCESS && buffer_len != 0) {
716
driver_version = String::utf16((const char16_t *)buffer, buffer_len).strip_edges();
717
}
718
if (!driver_version.is_empty()) {
719
info.push_back(driver_provider);
720
info.push_back(driver_version);
721
722
RegCloseKey(sub_hkey);
723
break;
724
}
725
}
726
RegCloseKey(sub_hkey);
727
}
728
}
729
RegCloseKey(hkey);
730
return info;
731
}
732
733
Vector<String> OS_Windows::_get_video_adapter_driver_info_wmi(const String &p_name) const {
734
Vector<String> info;
735
736
REFCLSID clsid = CLSID_WbemLocator; // Unmarshaler CLSID
737
REFIID uuid = IID_IWbemLocator; // Interface UUID
738
IWbemLocator *wbemLocator = nullptr; // to get the services
739
IWbemServices *wbemServices = nullptr; // to get the class
740
IEnumWbemClassObject *iter = nullptr;
741
IWbemClassObject *pnpSDriverObject[1]; // contains driver name, version, etc.
742
String driver_name;
743
String driver_version;
744
745
HRESULT hr = CoCreateInstance(clsid, nullptr, CLSCTX_INPROC_SERVER, uuid, (LPVOID *)&wbemLocator);
746
if (hr != S_OK) {
747
return Vector<String>();
748
}
749
BSTR resource_name = SysAllocString(L"root\\CIMV2");
750
hr = wbemLocator->ConnectServer(resource_name, nullptr, nullptr, nullptr, 0, nullptr, nullptr, &wbemServices);
751
SysFreeString(resource_name);
752
753
SAFE_RELEASE(wbemLocator) // from now on, use `wbemServices`
754
if (hr != S_OK) {
755
SAFE_RELEASE(wbemServices)
756
return Vector<String>();
757
}
758
759
const String gpu_device_class_query = vformat("SELECT * FROM Win32_PnPSignedDriver WHERE DeviceName = \"%s\"", p_name);
760
BSTR query = SysAllocString((const WCHAR *)gpu_device_class_query.utf16().get_data());
761
BSTR query_lang = SysAllocString(L"WQL");
762
hr = wbemServices->ExecQuery(query_lang, query, WBEM_FLAG_RETURN_IMMEDIATELY | WBEM_FLAG_FORWARD_ONLY, nullptr, &iter);
763
SysFreeString(query_lang);
764
SysFreeString(query);
765
if (hr == S_OK) {
766
ULONG resultCount;
767
hr = iter->Next(5000, 1, pnpSDriverObject, &resultCount); // Get exactly 1. Wait max 5 seconds.
768
769
if (hr == S_OK && resultCount > 0) {
770
VARIANT dn;
771
VariantInit(&dn);
772
773
BSTR object_name = SysAllocString(L"DriverName");
774
hr = pnpSDriverObject[0]->Get(object_name, 0, &dn, nullptr, nullptr);
775
SysFreeString(object_name);
776
if (hr == S_OK && dn.vt == VT_BSTR) {
777
String d_name = String(V_BSTR(&dn));
778
if (d_name.is_empty()) {
779
object_name = SysAllocString(L"DriverProviderName");
780
hr = pnpSDriverObject[0]->Get(object_name, 0, &dn, nullptr, nullptr);
781
SysFreeString(object_name);
782
if (hr == S_OK) {
783
driver_name = String(V_BSTR(&dn));
784
}
785
} else {
786
driver_name = d_name;
787
}
788
} else {
789
object_name = SysAllocString(L"DriverProviderName");
790
hr = pnpSDriverObject[0]->Get(object_name, 0, &dn, nullptr, nullptr);
791
SysFreeString(object_name);
792
if (hr == S_OK && dn.vt == VT_BSTR) {
793
driver_name = String(V_BSTR(&dn));
794
} else {
795
driver_name = "Unknown";
796
}
797
}
798
799
VARIANT dv;
800
VariantInit(&dv);
801
object_name = SysAllocString(L"DriverVersion");
802
hr = pnpSDriverObject[0]->Get(object_name, 0, &dv, nullptr, nullptr);
803
SysFreeString(object_name);
804
if (hr == S_OK && dv.vt == VT_BSTR) {
805
driver_version = String(V_BSTR(&dv));
806
} else {
807
driver_version = "Unknown";
808
}
809
for (ULONG i = 0; i < resultCount; i++) {
810
SAFE_RELEASE(pnpSDriverObject[i])
811
}
812
}
813
}
814
815
SAFE_RELEASE(wbemServices)
816
SAFE_RELEASE(iter)
817
818
info.push_back(driver_name);
819
info.push_back(driver_version);
820
821
return info;
822
}
823
824
Vector<String> OS_Windows::get_video_adapter_driver_info() const {
825
if (RenderingServer::get_singleton() == nullptr) {
826
return Vector<String>();
827
}
828
829
static Vector<String> info;
830
if (!info.is_empty()) {
831
return info;
832
}
833
834
const String device_name = RenderingServer::get_singleton()->get_video_adapter_name();
835
if (device_name.is_empty()) {
836
return Vector<String>();
837
}
838
839
info = _get_video_adapter_driver_info_reg(device_name);
840
if (info.is_empty()) {
841
info = _get_video_adapter_driver_info_wmi(device_name);
842
}
843
return info;
844
}
845
846
bool OS_Windows::get_user_prefers_integrated_gpu() const {
847
// On Windows 10, the preferred GPU configured in Windows Settings is
848
// stored in the registry under the key
849
// `HKEY_CURRENT_USER\SOFTWARE\Microsoft\DirectX\UserGpuPreferences`
850
// with the name being the app ID or EXE path. The value is in the form of
851
// `GpuPreference=1;`, with the value being 1 for integrated GPU and 2
852
// for discrete GPU. On Windows 11, there may be more flags, separated
853
// by semicolons.
854
855
// If this is a packaged app, use the "application user model ID".
856
// Otherwise, use the EXE path.
857
WCHAR value_name[32768];
858
bool is_packaged = false;
859
{
860
HMODULE kernel32 = GetModuleHandleW(L"kernel32.dll");
861
if (kernel32) {
862
using GetCurrentApplicationUserModelIdPtr = LONG(WINAPI *)(UINT32 * length, PWSTR id);
863
GetCurrentApplicationUserModelIdPtr GetCurrentApplicationUserModelId = (GetCurrentApplicationUserModelIdPtr)(void *)GetProcAddress(kernel32, "GetCurrentApplicationUserModelId");
864
865
if (GetCurrentApplicationUserModelId) {
866
UINT32 length = std_size(value_name);
867
LONG result = GetCurrentApplicationUserModelId(&length, value_name);
868
if (result == ERROR_SUCCESS) {
869
is_packaged = true;
870
}
871
}
872
}
873
}
874
if (!is_packaged && GetModuleFileNameW(nullptr, value_name, sizeof(value_name) / sizeof(value_name[0])) >= sizeof(value_name) / sizeof(value_name[0])) {
875
// Paths should never be longer than 32767, but just in case.
876
return false;
877
}
878
879
LPCWSTR subkey = L"SOFTWARE\\Microsoft\\DirectX\\UserGpuPreferences";
880
HKEY hkey = nullptr;
881
LSTATUS result = RegOpenKeyExW(HKEY_CURRENT_USER, subkey, 0, KEY_READ, &hkey);
882
if (result != ERROR_SUCCESS) {
883
return false;
884
}
885
886
DWORD size = 0;
887
result = RegGetValueW(hkey, nullptr, value_name, RRF_RT_REG_SZ, nullptr, nullptr, &size);
888
if (result != ERROR_SUCCESS || size == 0) {
889
RegCloseKey(hkey);
890
return false;
891
}
892
893
Vector<WCHAR> buffer;
894
buffer.resize(size / sizeof(WCHAR));
895
result = RegGetValueW(hkey, nullptr, value_name, RRF_RT_REG_SZ, nullptr, (LPBYTE)buffer.ptrw(), &size);
896
if (result != ERROR_SUCCESS) {
897
RegCloseKey(hkey);
898
return false;
899
}
900
901
RegCloseKey(hkey);
902
const String flags = String::utf16((const char16_t *)buffer.ptr(), size / sizeof(WCHAR));
903
904
for (const String &flag : flags.split(";", false)) {
905
if (flag == "GpuPreference=1") {
906
return true;
907
}
908
}
909
return false;
910
}
911
912
OS::DateTime OS_Windows::get_datetime(bool p_utc) const {
913
SYSTEMTIME systemtime;
914
if (p_utc) {
915
GetSystemTime(&systemtime);
916
} else {
917
GetLocalTime(&systemtime);
918
}
919
920
//Get DST information from Windows, but only if p_utc is false.
921
TIME_ZONE_INFORMATION info;
922
bool is_daylight = false;
923
if (!p_utc && GetTimeZoneInformation(&info) == TIME_ZONE_ID_DAYLIGHT) {
924
is_daylight = true;
925
}
926
927
DateTime dt;
928
dt.year = systemtime.wYear;
929
dt.month = Month(systemtime.wMonth);
930
dt.day = systemtime.wDay;
931
dt.weekday = Weekday(systemtime.wDayOfWeek);
932
dt.hour = systemtime.wHour;
933
dt.minute = systemtime.wMinute;
934
dt.second = systemtime.wSecond;
935
dt.dst = is_daylight;
936
return dt;
937
}
938
939
OS::TimeZoneInfo OS_Windows::get_time_zone_info() const {
940
TIME_ZONE_INFORMATION info;
941
bool is_daylight = false;
942
if (GetTimeZoneInformation(&info) == TIME_ZONE_ID_DAYLIGHT) {
943
is_daylight = true;
944
}
945
946
// Daylight Bias needs to be added to the bias if DST is in effect, or else it will not properly update.
947
TimeZoneInfo ret;
948
if (is_daylight) {
949
ret.name = info.DaylightName;
950
ret.bias = info.Bias + info.DaylightBias;
951
} else {
952
ret.name = info.StandardName;
953
ret.bias = info.Bias + info.StandardBias;
954
}
955
956
// Bias value returned by GetTimeZoneInformation is inverted of what we expect
957
// For example, on GMT-3 GetTimeZoneInformation return a Bias of 180, so invert the value to get -180
958
ret.bias = -ret.bias;
959
return ret;
960
}
961
962
double OS_Windows::get_unix_time() const {
963
// 1 Windows tick is 100ns
964
const uint64_t WINDOWS_TICKS_PER_SECOND = 10000000;
965
const uint64_t TICKS_TO_UNIX_EPOCH = 116444736000000000LL;
966
967
SYSTEMTIME st;
968
GetSystemTime(&st);
969
FILETIME ft;
970
SystemTimeToFileTime(&st, &ft);
971
uint64_t ticks_time;
972
ticks_time = ft.dwHighDateTime;
973
ticks_time <<= 32;
974
ticks_time |= ft.dwLowDateTime;
975
976
return (double)(ticks_time - TICKS_TO_UNIX_EPOCH) / WINDOWS_TICKS_PER_SECOND;
977
}
978
979
void OS_Windows::delay_usec(uint32_t p_usec) const {
980
if (p_usec < 1000) {
981
Sleep(1);
982
} else {
983
Sleep(p_usec / 1000);
984
}
985
}
986
987
uint64_t OS_Windows::get_ticks_usec() const {
988
uint64_t ticks;
989
990
// This is the number of clock ticks since start
991
QueryPerformanceCounter((LARGE_INTEGER *)&ticks);
992
// Subtract the ticks at game start to get
993
// the ticks since the game started
994
ticks -= ticks_start;
995
996
// Divide by frequency to get the time in seconds
997
// original calculation shown below is subject to overflow
998
// with high ticks_per_second and a number of days since the last reboot.
999
// time = ticks * 1000000L / ticks_per_second;
1000
1001
// we can prevent this by either using 128 bit math
1002
// or separating into a calculation for seconds, and the fraction
1003
uint64_t seconds = ticks / ticks_per_second;
1004
1005
// compiler will optimize these two into one divide
1006
uint64_t leftover = ticks % ticks_per_second;
1007
1008
// remainder
1009
uint64_t time = (leftover * 1000000L) / ticks_per_second;
1010
1011
// seconds
1012
time += seconds * 1000000L;
1013
1014
return time;
1015
}
1016
1017
String OS_Windows::_quote_command_line_argument(const String &p_text) const {
1018
for (int i = 0; i < p_text.size(); i++) {
1019
char32_t c = p_text[i];
1020
if (c == ' ' || c == '&' || c == '(' || c == ')' || c == '[' || c == ']' || c == '{' || c == '}' || c == '^' || c == '=' || c == ';' || c == '!' || c == '\'' || c == '+' || c == ',' || c == '`' || c == '~') {
1021
return "\"" + p_text + "\"";
1022
}
1023
}
1024
return p_text;
1025
}
1026
1027
static void _append_to_pipe(char *p_bytes, int p_size, String *r_pipe, Mutex *p_pipe_mutex) {
1028
// Try to convert from default ANSI code page to Unicode.
1029
LocalVector<wchar_t> wchars;
1030
int total_wchars = MultiByteToWideChar(CP_ACP, 0, p_bytes, p_size, nullptr, 0);
1031
if (total_wchars > 0) {
1032
wchars.resize(total_wchars);
1033
if (MultiByteToWideChar(CP_ACP, 0, p_bytes, p_size, wchars.ptr(), total_wchars) == 0) {
1034
wchars.clear();
1035
}
1036
}
1037
1038
if (p_pipe_mutex) {
1039
p_pipe_mutex->lock();
1040
}
1041
if (wchars.is_empty()) {
1042
// Let's hope it's compatible with UTF-8.
1043
(*r_pipe) += String::utf8(p_bytes, p_size);
1044
} else {
1045
(*r_pipe) += String::utf16((char16_t *)wchars.ptr(), total_wchars);
1046
}
1047
if (p_pipe_mutex) {
1048
p_pipe_mutex->unlock();
1049
}
1050
}
1051
1052
void OS_Windows::_init_encodings() {
1053
encodings[""] = 0;
1054
encodings["CP_ACP"] = 0;
1055
encodings["CP_OEMCP"] = 1;
1056
encodings["CP_MACCP"] = 2;
1057
encodings["CP_THREAD_ACP"] = 3;
1058
encodings["CP_SYMBOL"] = 42;
1059
encodings["IBM037"] = 37;
1060
encodings["IBM437"] = 437;
1061
encodings["IBM500"] = 500;
1062
encodings["ASMO-708"] = 708;
1063
encodings["ASMO-449"] = 709;
1064
encodings["DOS-710"] = 710;
1065
encodings["DOS-720"] = 720;
1066
encodings["IBM737"] = 737;
1067
encodings["IBM775"] = 775;
1068
encodings["IBM850"] = 850;
1069
encodings["IBM852"] = 852;
1070
encodings["IBM855"] = 855;
1071
encodings["IBM857"] = 857;
1072
encodings["IBM00858"] = 858;
1073
encodings["IBM860"] = 860;
1074
encodings["IBM861"] = 861;
1075
encodings["DOS-862"] = 862;
1076
encodings["IBM863"] = 863;
1077
encodings["IBM864"] = 864;
1078
encodings["IBM865"] = 865;
1079
encodings["CP866"] = 866;
1080
encodings["IBM869"] = 869;
1081
encodings["IBM870"] = 870;
1082
encodings["WINDOWS-874"] = 874;
1083
encodings["CP875"] = 875;
1084
encodings["SHIFT_JIS"] = 932;
1085
encodings["GB2312"] = 936;
1086
encodings["KS_C_5601-1987"] = 949;
1087
encodings["BIG5"] = 950;
1088
encodings["IBM1026"] = 1026;
1089
encodings["IBM01047"] = 1047;
1090
encodings["IBM01140"] = 1140;
1091
encodings["IBM01141"] = 1141;
1092
encodings["IBM01142"] = 1142;
1093
encodings["IBM01143"] = 1143;
1094
encodings["IBM01144"] = 1144;
1095
encodings["IBM01145"] = 1145;
1096
encodings["IBM01146"] = 1146;
1097
encodings["IBM01147"] = 1147;
1098
encodings["IBM01148"] = 1148;
1099
encodings["IBM01149"] = 1149;
1100
encodings["UTF-16"] = 1200;
1101
encodings["UNICODEFFFE"] = 1201;
1102
encodings["WINDOWS-1250"] = 1250;
1103
encodings["WINDOWS-1251"] = 1251;
1104
encodings["WINDOWS-1252"] = 1252;
1105
encodings["WINDOWS-1253"] = 1253;
1106
encodings["WINDOWS-1254"] = 1254;
1107
encodings["WINDOWS-1255"] = 1255;
1108
encodings["WINDOWS-1256"] = 1256;
1109
encodings["WINDOWS-1257"] = 1257;
1110
encodings["WINDOWS-1258"] = 1258;
1111
encodings["JOHAB"] = 1361;
1112
encodings["MACINTOSH"] = 10000;
1113
encodings["X-MAC-JAPANESE"] = 10001;
1114
encodings["X-MAC-CHINESETRAD"] = 10002;
1115
encodings["X-MAC-KOREAN"] = 10003;
1116
encodings["X-MAC-ARABIC"] = 10004;
1117
encodings["X-MAC-HEBREW"] = 10005;
1118
encodings["X-MAC-GREEK"] = 10006;
1119
encodings["X-MAC-CYRILLIC"] = 10007;
1120
encodings["X-MAC-CHINESESIMP"] = 10008;
1121
encodings["X-MAC-ROMANIAN"] = 10010;
1122
encodings["X-MAC-UKRAINIAN"] = 10017;
1123
encodings["X-MAC-THAI"] = 10021;
1124
encodings["X-MAC-CE"] = 10029;
1125
encodings["X-MAC-ICELANDIC"] = 10079;
1126
encodings["X-MAC-TURKISH"] = 10081;
1127
encodings["X-MAC-CROATIAN"] = 10082;
1128
encodings["UTF-32"] = 12000;
1129
encodings["UTF-32BE"] = 12001;
1130
encodings["X-CHINESE_CNS"] = 20000;
1131
encodings["X-CP20001"] = 20001;
1132
encodings["X_CHINESE-ETEN"] = 20002;
1133
encodings["X-CP20003"] = 20003;
1134
encodings["X-CP20004"] = 20004;
1135
encodings["X-CP20005"] = 20005;
1136
encodings["X-IA5"] = 20105;
1137
encodings["X-IA5-GERMAN"] = 20106;
1138
encodings["X-IA5-SWEDISH"] = 20107;
1139
encodings["X-IA5-NORWEGIAN"] = 20108;
1140
encodings["US-ASCII"] = 20127;
1141
encodings["X-CP20261"] = 20261;
1142
encodings["X-CP20269"] = 20269;
1143
encodings["IBM273"] = 20273;
1144
encodings["IBM277"] = 20277;
1145
encodings["IBM278"] = 20278;
1146
encodings["IBM280"] = 20280;
1147
encodings["IBM284"] = 20284;
1148
encodings["IBM285"] = 20285;
1149
encodings["IBM290"] = 20290;
1150
encodings["IBM297"] = 20297;
1151
encodings["IBM420"] = 20420;
1152
encodings["IBM423"] = 20423;
1153
encodings["IBM424"] = 20424;
1154
encodings["X-EBCDIC-KOREANEXTENDED"] = 20833;
1155
encodings["IBM-THAI"] = 20838;
1156
encodings["KOI8-R"] = 20866;
1157
encodings["IBM871"] = 20871;
1158
encodings["IBM880"] = 20880;
1159
encodings["IBM905"] = 20905;
1160
encodings["IBM00924"] = 20924;
1161
encodings["EUC-JP"] = 20932;
1162
encodings["X-CP20936"] = 20936;
1163
encodings["X-CP20949"] = 20949;
1164
encodings["CP1025"] = 21025;
1165
encodings["KOI8-U"] = 21866;
1166
encodings["ISO-8859-1"] = 28591;
1167
encodings["ISO-8859-2"] = 28592;
1168
encodings["ISO-8859-3"] = 28593;
1169
encodings["ISO-8859-4"] = 28594;
1170
encodings["ISO-8859-5"] = 28595;
1171
encodings["ISO-8859-6"] = 28596;
1172
encodings["ISO-8859-7"] = 28597;
1173
encodings["ISO-8859-8"] = 28598;
1174
encodings["ISO-8859-9"] = 28599;
1175
encodings["ISO-8859-13"] = 28603;
1176
encodings["ISO-8859-15"] = 28605;
1177
encodings["X-EUROPA"] = 29001;
1178
encodings["ISO-8859-8-I"] = 38598;
1179
encodings["ISO-2022-JP"] = 50220;
1180
encodings["CSISO2022JP"] = 50221;
1181
encodings["ISO-2022-JP"] = 50222;
1182
encodings["ISO-2022-KR"] = 50225;
1183
encodings["X-CP50227"] = 50227;
1184
encodings["EBCDIC-JP"] = 50930;
1185
encodings["EBCDIC-US-JP"] = 50931;
1186
encodings["EBCDIC-KR"] = 50933;
1187
encodings["EBCDIC-CN-eXT"] = 50935;
1188
encodings["EBCDIC-CN"] = 50936;
1189
encodings["EBCDIC-US-CN"] = 50937;
1190
encodings["EBCDIC-JP-EXT"] = 50939;
1191
encodings["EUC-JP"] = 51932;
1192
encodings["EUC-CN"] = 51936;
1193
encodings["EUC-KR"] = 51949;
1194
encodings["HZ-GB-2312"] = 52936;
1195
encodings["GB18030"] = 54936;
1196
encodings["X-ISCII-DE"] = 57002;
1197
encodings["X-ISCII-BE"] = 57003;
1198
encodings["X-ISCII-TA"] = 57004;
1199
encodings["X-ISCII-TE"] = 57005;
1200
encodings["X-ISCII-AS"] = 57006;
1201
encodings["X-ISCII-OR"] = 57007;
1202
encodings["X-ISCII-KA"] = 57008;
1203
encodings["X-ISCII-MA"] = 57009;
1204
encodings["X-ISCII-GU"] = 57010;
1205
encodings["X-ISCII-PA"] = 57011;
1206
encodings["UTF-7"] = 65000;
1207
encodings["UTF-8"] = 65001;
1208
}
1209
1210
String OS_Windows::multibyte_to_string(const String &p_encoding, const PackedByteArray &p_array) const {
1211
const int *encoding = encodings.getptr(p_encoding.to_upper());
1212
ERR_FAIL_NULL_V_MSG(encoding, String(), "Conversion failed: Unknown encoding");
1213
1214
LocalVector<wchar_t> wchars;
1215
int total_wchars = MultiByteToWideChar(*encoding, 0, (const char *)p_array.ptr(), p_array.size(), nullptr, 0);
1216
if (total_wchars == 0) {
1217
DWORD err_code = GetLastError();
1218
ERR_FAIL_V_MSG(String(), vformat("Conversion failed: %s", format_error_message(err_code)));
1219
}
1220
wchars.resize(total_wchars);
1221
if (MultiByteToWideChar(*encoding, 0, (const char *)p_array.ptr(), p_array.size(), wchars.ptr(), total_wchars) == 0) {
1222
DWORD err_code = GetLastError();
1223
ERR_FAIL_V_MSG(String(), vformat("Conversion failed: %s", format_error_message(err_code)));
1224
}
1225
1226
return String::utf16((const char16_t *)wchars.ptr(), wchars.size());
1227
}
1228
1229
PackedByteArray OS_Windows::string_to_multibyte(const String &p_encoding, const String &p_string) const {
1230
const int *encoding = encodings.getptr(p_encoding.to_upper());
1231
ERR_FAIL_NULL_V_MSG(encoding, PackedByteArray(), "Conversion failed: Unknown encoding");
1232
1233
Char16String charstr = p_string.utf16();
1234
PackedByteArray ret;
1235
int total_mbchars = WideCharToMultiByte(*encoding, 0, (const wchar_t *)charstr.ptr(), charstr.size(), nullptr, 0, nullptr, nullptr);
1236
if (total_mbchars == 0) {
1237
DWORD err_code = GetLastError();
1238
ERR_FAIL_V_MSG(PackedByteArray(), vformat("Conversion failed: %s", format_error_message(err_code)));
1239
}
1240
1241
ret.resize(total_mbchars);
1242
if (WideCharToMultiByte(*encoding, 0, (const wchar_t *)charstr.ptr(), charstr.size(), (char *)ret.ptrw(), ret.size(), nullptr, nullptr) == 0) {
1243
DWORD err_code = GetLastError();
1244
ERR_FAIL_V_MSG(PackedByteArray(), vformat("Conversion failed: %s", format_error_message(err_code)));
1245
}
1246
1247
return ret;
1248
}
1249
1250
Dictionary OS_Windows::get_memory_info() const {
1251
Dictionary meminfo;
1252
1253
meminfo["physical"] = -1;
1254
meminfo["free"] = -1;
1255
meminfo["available"] = -1;
1256
meminfo["stack"] = -1;
1257
1258
PERFORMANCE_INFORMATION pref_info;
1259
pref_info.cb = sizeof(pref_info);
1260
GetPerformanceInfo(&pref_info, sizeof(pref_info));
1261
1262
typedef void(WINAPI * PGetCurrentThreadStackLimits)(PULONG_PTR, PULONG_PTR);
1263
PGetCurrentThreadStackLimits GetCurrentThreadStackLimits = (PGetCurrentThreadStackLimits)(void *)GetProcAddress(GetModuleHandleA("kernel32.dll"), "GetCurrentThreadStackLimits");
1264
1265
ULONG_PTR LowLimit = 0;
1266
ULONG_PTR HighLimit = 0;
1267
if (GetCurrentThreadStackLimits) {
1268
GetCurrentThreadStackLimits(&LowLimit, &HighLimit);
1269
}
1270
1271
if (pref_info.PhysicalTotal * pref_info.PageSize != 0) {
1272
meminfo["physical"] = static_cast<int64_t>(pref_info.PhysicalTotal * pref_info.PageSize);
1273
}
1274
if (pref_info.PhysicalAvailable * pref_info.PageSize != 0) {
1275
meminfo["free"] = static_cast<int64_t>(pref_info.PhysicalAvailable * pref_info.PageSize);
1276
}
1277
if (pref_info.CommitLimit * pref_info.PageSize != 0) {
1278
meminfo["available"] = static_cast<int64_t>(pref_info.CommitLimit * pref_info.PageSize);
1279
}
1280
if (HighLimit - LowLimit != 0) {
1281
meminfo["stack"] = static_cast<int64_t>(HighLimit - LowLimit);
1282
}
1283
1284
return meminfo;
1285
}
1286
1287
Dictionary OS_Windows::execute_with_pipe(const String &p_path, const List<String> &p_arguments, bool p_blocking) {
1288
#define CLEAN_PIPES \
1289
if (pipe_in[0] != 0) { \
1290
CloseHandle(pipe_in[0]); \
1291
} \
1292
if (pipe_in[1] != 0) { \
1293
CloseHandle(pipe_in[1]); \
1294
} \
1295
if (pipe_out[0] != 0) { \
1296
CloseHandle(pipe_out[0]); \
1297
} \
1298
if (pipe_out[1] != 0) { \
1299
CloseHandle(pipe_out[1]); \
1300
} \
1301
if (pipe_err[0] != 0) { \
1302
CloseHandle(pipe_err[0]); \
1303
} \
1304
if (pipe_err[1] != 0) { \
1305
CloseHandle(pipe_err[1]); \
1306
}
1307
1308
Dictionary ret;
1309
1310
String path = p_path.is_absolute_path() ? fix_path(p_path) : p_path;
1311
String command = _quote_command_line_argument(path);
1312
for (const String &E : p_arguments) {
1313
command += " " + _quote_command_line_argument(E);
1314
}
1315
1316
// Create pipes.
1317
HANDLE pipe_in[2] = { nullptr, nullptr };
1318
HANDLE pipe_out[2] = { nullptr, nullptr };
1319
HANDLE pipe_err[2] = { nullptr, nullptr };
1320
1321
SECURITY_ATTRIBUTES sa;
1322
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
1323
sa.bInheritHandle = true;
1324
sa.lpSecurityDescriptor = nullptr;
1325
1326
ERR_FAIL_COND_V(!CreatePipe(&pipe_in[0], &pipe_in[1], &sa, 0), ret);
1327
if (!CreatePipe(&pipe_out[0], &pipe_out[1], &sa, 0)) {
1328
CLEAN_PIPES
1329
ERR_FAIL_V(ret);
1330
}
1331
if (!CreatePipe(&pipe_err[0], &pipe_err[1], &sa, 0)) {
1332
CLEAN_PIPES
1333
ERR_FAIL_V(ret);
1334
}
1335
ERR_FAIL_COND_V(!SetHandleInformation(pipe_err[0], HANDLE_FLAG_INHERIT, 0), ret);
1336
1337
// Create process.
1338
ProcessInfo pi;
1339
ZeroMemory(&pi.si, sizeof(pi.si));
1340
pi.si.StartupInfo.cb = sizeof(pi.si);
1341
ZeroMemory(&pi.pi, sizeof(pi.pi));
1342
LPSTARTUPINFOW si_w = (LPSTARTUPINFOW)&pi.si.StartupInfo;
1343
1344
pi.si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
1345
pi.si.StartupInfo.hStdInput = pipe_in[0];
1346
pi.si.StartupInfo.hStdOutput = pipe_out[1];
1347
pi.si.StartupInfo.hStdError = pipe_err[1];
1348
1349
SIZE_T attr_list_size = 0;
1350
InitializeProcThreadAttributeList(nullptr, 1, 0, &attr_list_size);
1351
pi.si.lpAttributeList = (LPPROC_THREAD_ATTRIBUTE_LIST)alloca(attr_list_size);
1352
if (!InitializeProcThreadAttributeList(pi.si.lpAttributeList, 1, 0, &attr_list_size)) {
1353
CLEAN_PIPES
1354
ERR_FAIL_V(ret);
1355
}
1356
HANDLE handles_to_inherit[] = { pipe_in[0], pipe_out[1], pipe_err[1] };
1357
if (!UpdateProcThreadAttribute(
1358
pi.si.lpAttributeList,
1359
0,
1360
PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
1361
handles_to_inherit,
1362
sizeof(handles_to_inherit),
1363
nullptr,
1364
nullptr)) {
1365
CLEAN_PIPES
1366
DeleteProcThreadAttributeList(pi.si.lpAttributeList);
1367
ERR_FAIL_V(ret);
1368
}
1369
1370
DWORD creation_flags = NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW | EXTENDED_STARTUPINFO_PRESENT;
1371
1372
Char16String current_dir_name;
1373
size_t str_len = GetCurrentDirectoryW(0, nullptr);
1374
current_dir_name.resize_uninitialized(str_len + 1);
1375
GetCurrentDirectoryW(current_dir_name.size(), (LPWSTR)current_dir_name.ptrw());
1376
if (current_dir_name.size() >= MAX_PATH) {
1377
Char16String current_short_dir_name;
1378
str_len = GetShortPathNameW((LPCWSTR)current_dir_name.ptr(), nullptr, 0);
1379
current_short_dir_name.resize_uninitialized(str_len);
1380
GetShortPathNameW((LPCWSTR)current_dir_name.ptr(), (LPWSTR)current_short_dir_name.ptrw(), current_short_dir_name.size());
1381
current_dir_name = current_short_dir_name;
1382
}
1383
1384
if (!CreateProcessW(nullptr, (LPWSTR)(command.utf16().ptrw()), nullptr, nullptr, true, creation_flags, nullptr, (LPWSTR)current_dir_name.ptr(), si_w, &pi.pi)) {
1385
CLEAN_PIPES
1386
DeleteProcThreadAttributeList(pi.si.lpAttributeList);
1387
ERR_FAIL_V_MSG(ret, "Could not create child process: " + command);
1388
}
1389
CloseHandle(pipe_in[0]);
1390
CloseHandle(pipe_out[1]);
1391
CloseHandle(pipe_err[1]);
1392
DeleteProcThreadAttributeList(pi.si.lpAttributeList);
1393
1394
ProcessID pid = pi.pi.dwProcessId;
1395
process_map_mutex.lock();
1396
process_map->insert(pid, pi);
1397
process_map_mutex.unlock();
1398
1399
Ref<FileAccessWindowsPipe> main_pipe;
1400
main_pipe.instantiate();
1401
main_pipe->open_existing(pipe_out[0], pipe_in[1], p_blocking);
1402
1403
Ref<FileAccessWindowsPipe> err_pipe;
1404
err_pipe.instantiate();
1405
err_pipe->open_existing(pipe_err[0], nullptr, p_blocking);
1406
1407
ret["stdio"] = main_pipe;
1408
ret["stderr"] = err_pipe;
1409
ret["pid"] = pid;
1410
1411
#undef CLEAN_PIPES
1412
return ret;
1413
}
1414
1415
Error OS_Windows::execute(const String &p_path, const List<String> &p_arguments, String *r_pipe, int *r_exitcode, bool read_stderr, Mutex *p_pipe_mutex, bool p_open_console) {
1416
String path = p_path.is_absolute_path() ? fix_path(p_path) : p_path;
1417
String command = _quote_command_line_argument(path);
1418
for (const String &E : p_arguments) {
1419
command += " " + _quote_command_line_argument(E);
1420
}
1421
1422
ProcessInfo pi;
1423
ZeroMemory(&pi.si, sizeof(pi.si));
1424
pi.si.StartupInfo.cb = sizeof(pi.si);
1425
ZeroMemory(&pi.pi, sizeof(pi.pi));
1426
LPSTARTUPINFOW si_w = (LPSTARTUPINFOW)&pi.si.StartupInfo;
1427
1428
bool inherit_handles = false;
1429
HANDLE pipe[2] = { nullptr, nullptr };
1430
if (r_pipe) {
1431
// Create pipe for StdOut and StdErr.
1432
SECURITY_ATTRIBUTES sa;
1433
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
1434
sa.bInheritHandle = true;
1435
sa.lpSecurityDescriptor = nullptr;
1436
1437
ERR_FAIL_COND_V(!CreatePipe(&pipe[0], &pipe[1], &sa, 0), ERR_CANT_FORK);
1438
1439
pi.si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
1440
pi.si.StartupInfo.hStdOutput = pipe[1];
1441
if (read_stderr) {
1442
pi.si.StartupInfo.hStdError = pipe[1];
1443
}
1444
1445
SIZE_T attr_list_size = 0;
1446
InitializeProcThreadAttributeList(nullptr, 1, 0, &attr_list_size);
1447
pi.si.lpAttributeList = (LPPROC_THREAD_ATTRIBUTE_LIST)alloca(attr_list_size);
1448
if (!InitializeProcThreadAttributeList(pi.si.lpAttributeList, 1, 0, &attr_list_size)) {
1449
CloseHandle(pipe[0]); // Cleanup pipe handles.
1450
CloseHandle(pipe[1]);
1451
ERR_FAIL_V(ERR_CANT_FORK);
1452
}
1453
if (!UpdateProcThreadAttribute(
1454
pi.si.lpAttributeList,
1455
0,
1456
PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
1457
&pipe[1],
1458
sizeof(HANDLE),
1459
nullptr,
1460
nullptr)) {
1461
CloseHandle(pipe[0]); // Cleanup pipe handles.
1462
CloseHandle(pipe[1]);
1463
DeleteProcThreadAttributeList(pi.si.lpAttributeList);
1464
ERR_FAIL_V(ERR_CANT_FORK);
1465
}
1466
inherit_handles = true;
1467
}
1468
DWORD creation_flags = NORMAL_PRIORITY_CLASS;
1469
if (inherit_handles) {
1470
creation_flags |= EXTENDED_STARTUPINFO_PRESENT;
1471
}
1472
if (p_open_console) {
1473
creation_flags |= CREATE_NEW_CONSOLE;
1474
} else {
1475
creation_flags |= CREATE_NO_WINDOW;
1476
}
1477
1478
Char16String current_dir_name;
1479
size_t str_len = GetCurrentDirectoryW(0, nullptr);
1480
current_dir_name.resize_uninitialized(str_len + 1);
1481
GetCurrentDirectoryW(current_dir_name.size(), (LPWSTR)current_dir_name.ptrw());
1482
if (current_dir_name.size() >= MAX_PATH) {
1483
Char16String current_short_dir_name;
1484
str_len = GetShortPathNameW((LPCWSTR)current_dir_name.ptr(), nullptr, 0);
1485
current_short_dir_name.resize_uninitialized(str_len);
1486
GetShortPathNameW((LPCWSTR)current_dir_name.ptr(), (LPWSTR)current_short_dir_name.ptrw(), current_short_dir_name.size());
1487
current_dir_name = current_short_dir_name;
1488
}
1489
1490
int ret = CreateProcessW(nullptr, (LPWSTR)(command.utf16().ptrw()), nullptr, nullptr, inherit_handles, creation_flags, nullptr, (LPWSTR)current_dir_name.ptr(), si_w, &pi.pi);
1491
if (!ret && r_pipe) {
1492
CloseHandle(pipe[0]); // Cleanup pipe handles.
1493
CloseHandle(pipe[1]);
1494
DeleteProcThreadAttributeList(pi.si.lpAttributeList);
1495
}
1496
ERR_FAIL_COND_V_MSG(ret == 0, ERR_CANT_FORK, "Could not create child process: " + command);
1497
1498
if (r_pipe) {
1499
CloseHandle(pipe[1]); // Close pipe write handle (only child process is writing).
1500
1501
LocalVector<char> bytes;
1502
int bytes_in_buffer = 0;
1503
1504
const int CHUNK_SIZE = 4096;
1505
DWORD read = 0;
1506
for (;;) { // Read StdOut and StdErr from pipe.
1507
bytes.resize(bytes_in_buffer + CHUNK_SIZE);
1508
const bool success = ReadFile(pipe[0], bytes.ptr() + bytes_in_buffer, CHUNK_SIZE, &read, nullptr);
1509
if (!success || read == 0) {
1510
break;
1511
}
1512
1513
// Assume that all possible encodings are ASCII-compatible.
1514
// Break at newline to allow receiving long output in portions.
1515
int newline_index = -1;
1516
for (int i = read - 1; i >= 0; i--) {
1517
if (bytes[bytes_in_buffer + i] == '\n') {
1518
newline_index = i;
1519
break;
1520
}
1521
}
1522
if (newline_index == -1) {
1523
bytes_in_buffer += read;
1524
continue;
1525
}
1526
1527
const int bytes_to_convert = bytes_in_buffer + (newline_index + 1);
1528
_append_to_pipe(bytes.ptr(), bytes_to_convert, r_pipe, p_pipe_mutex);
1529
1530
bytes_in_buffer = read - (newline_index + 1);
1531
memmove(bytes.ptr(), bytes.ptr() + bytes_to_convert, bytes_in_buffer);
1532
}
1533
1534
if (bytes_in_buffer > 0) {
1535
_append_to_pipe(bytes.ptr(), bytes_in_buffer, r_pipe, p_pipe_mutex);
1536
}
1537
1538
CloseHandle(pipe[0]); // Close pipe read handle.
1539
}
1540
WaitForSingleObject(pi.pi.hProcess, INFINITE);
1541
1542
if (r_exitcode) {
1543
DWORD ret2;
1544
GetExitCodeProcess(pi.pi.hProcess, &ret2);
1545
*r_exitcode = ret2;
1546
}
1547
1548
CloseHandle(pi.pi.hProcess);
1549
CloseHandle(pi.pi.hThread);
1550
if (r_pipe) {
1551
DeleteProcThreadAttributeList(pi.si.lpAttributeList);
1552
}
1553
1554
return OK;
1555
}
1556
1557
Error OS_Windows::create_process(const String &p_path, const List<String> &p_arguments, ProcessID *r_child_id, bool p_open_console) {
1558
String path = p_path.is_absolute_path() ? fix_path(p_path) : p_path;
1559
String command = _quote_command_line_argument(path);
1560
for (const String &E : p_arguments) {
1561
command += " " + _quote_command_line_argument(E);
1562
}
1563
1564
ProcessInfo pi;
1565
ZeroMemory(&pi.si, sizeof(pi.si));
1566
pi.si.StartupInfo.cb = sizeof(pi.si.StartupInfo);
1567
ZeroMemory(&pi.pi, sizeof(pi.pi));
1568
LPSTARTUPINFOW si_w = (LPSTARTUPINFOW)&pi.si.StartupInfo;
1569
1570
DWORD creation_flags = NORMAL_PRIORITY_CLASS;
1571
if (p_open_console) {
1572
creation_flags |= CREATE_NEW_CONSOLE;
1573
} else {
1574
creation_flags |= CREATE_NO_WINDOW;
1575
}
1576
1577
Char16String current_dir_name;
1578
size_t str_len = GetCurrentDirectoryW(0, nullptr);
1579
current_dir_name.resize_uninitialized(str_len + 1);
1580
GetCurrentDirectoryW(current_dir_name.size(), (LPWSTR)current_dir_name.ptrw());
1581
if (current_dir_name.size() >= MAX_PATH) {
1582
Char16String current_short_dir_name;
1583
str_len = GetShortPathNameW((LPCWSTR)current_dir_name.ptr(), nullptr, 0);
1584
current_short_dir_name.resize_uninitialized(str_len);
1585
GetShortPathNameW((LPCWSTR)current_dir_name.ptr(), (LPWSTR)current_short_dir_name.ptrw(), current_short_dir_name.size());
1586
current_dir_name = current_short_dir_name;
1587
}
1588
1589
int ret = CreateProcessW(nullptr, (LPWSTR)(command.utf16().ptrw()), nullptr, nullptr, false, creation_flags, nullptr, (LPWSTR)current_dir_name.ptr(), si_w, &pi.pi);
1590
ERR_FAIL_COND_V_MSG(ret == 0, ERR_CANT_FORK, "Could not create child process: " + command);
1591
1592
ProcessID pid = pi.pi.dwProcessId;
1593
if (r_child_id) {
1594
*r_child_id = pid;
1595
}
1596
process_map_mutex.lock();
1597
process_map->insert(pid, pi);
1598
process_map_mutex.unlock();
1599
1600
return OK;
1601
}
1602
1603
Error OS_Windows::kill(const ProcessID &p_pid) {
1604
int ret = 0;
1605
MutexLock lock(process_map_mutex);
1606
if (process_map->has(p_pid)) {
1607
const PROCESS_INFORMATION pi = (*process_map)[p_pid].pi;
1608
process_map->erase(p_pid);
1609
1610
ret = TerminateProcess(pi.hProcess, 0);
1611
1612
CloseHandle(pi.hProcess);
1613
CloseHandle(pi.hThread);
1614
} else {
1615
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, false, (DWORD)p_pid);
1616
if (hProcess != nullptr) {
1617
ret = TerminateProcess(hProcess, 0);
1618
1619
CloseHandle(hProcess);
1620
}
1621
}
1622
1623
return ret != 0 ? OK : FAILED;
1624
}
1625
1626
int OS_Windows::get_process_id() const {
1627
return _getpid();
1628
}
1629
1630
bool OS_Windows::is_process_running(const ProcessID &p_pid) const {
1631
MutexLock lock(process_map_mutex);
1632
if (!process_map->has(p_pid)) {
1633
return false;
1634
}
1635
1636
const ProcessInfo &info = (*process_map)[p_pid];
1637
if (!info.is_running) {
1638
return false;
1639
}
1640
1641
const PROCESS_INFORMATION &pi = info.pi;
1642
DWORD dw_exit_code = 0;
1643
if (!GetExitCodeProcess(pi.hProcess, &dw_exit_code)) {
1644
return false;
1645
}
1646
1647
if (dw_exit_code != STILL_ACTIVE) {
1648
info.is_running = false;
1649
info.exit_code = dw_exit_code;
1650
return false;
1651
}
1652
1653
return true;
1654
}
1655
1656
int OS_Windows::get_process_exit_code(const ProcessID &p_pid) const {
1657
MutexLock lock(process_map_mutex);
1658
if (!process_map->has(p_pid)) {
1659
return -1;
1660
}
1661
1662
const ProcessInfo &info = (*process_map)[p_pid];
1663
if (!info.is_running) {
1664
return info.exit_code;
1665
}
1666
1667
const PROCESS_INFORMATION &pi = info.pi;
1668
1669
DWORD dw_exit_code = 0;
1670
if (!GetExitCodeProcess(pi.hProcess, &dw_exit_code)) {
1671
return -1;
1672
}
1673
1674
if (dw_exit_code == STILL_ACTIVE) {
1675
return -1;
1676
}
1677
1678
info.is_running = false;
1679
info.exit_code = dw_exit_code;
1680
return dw_exit_code;
1681
}
1682
1683
Error OS_Windows::set_cwd(const String &p_cwd) {
1684
if (_wchdir((LPCWSTR)(p_cwd.utf16().get_data())) != 0) {
1685
return ERR_CANT_OPEN;
1686
}
1687
1688
return OK;
1689
}
1690
1691
String OS_Windows::get_cwd() const {
1692
Char16String real_current_dir_name;
1693
size_t str_len = GetCurrentDirectoryW(0, nullptr);
1694
real_current_dir_name.resize_uninitialized(str_len + 1);
1695
GetCurrentDirectoryW(real_current_dir_name.size(), (LPWSTR)real_current_dir_name.ptrw());
1696
return String::utf16((const char16_t *)real_current_dir_name.get_data()).trim_prefix(R"(\\?\)").replace_char('\\', '/');
1697
}
1698
1699
Vector<String> OS_Windows::get_system_fonts() const {
1700
if (!dwrite_init) {
1701
return Vector<String>();
1702
}
1703
1704
Vector<String> ret;
1705
HashSet<String> font_names;
1706
1707
UINT32 family_count = font_collection->GetFontFamilyCount();
1708
for (UINT32 i = 0; i < family_count; i++) {
1709
ComAutoreleaseRef<IDWriteFontFamily> family;
1710
HRESULT hr = font_collection->GetFontFamily(i, &family.reference);
1711
ERR_CONTINUE(FAILED(hr) || family.is_null());
1712
1713
ComAutoreleaseRef<IDWriteLocalizedStrings> family_names;
1714
hr = family->GetFamilyNames(&family_names.reference);
1715
ERR_CONTINUE(FAILED(hr) || family_names.is_null());
1716
1717
UINT32 index = 0;
1718
BOOL exists = false;
1719
UINT32 length = 0;
1720
Char16String name;
1721
1722
hr = family_names->FindLocaleName(L"en-us", &index, &exists);
1723
ERR_CONTINUE(FAILED(hr));
1724
1725
hr = family_names->GetStringLength(index, &length);
1726
ERR_CONTINUE(FAILED(hr));
1727
1728
name.resize_uninitialized(length + 1);
1729
hr = family_names->GetString(index, (WCHAR *)name.ptrw(), length + 1);
1730
ERR_CONTINUE(FAILED(hr));
1731
1732
font_names.insert(String::utf16(name.ptr(), length));
1733
}
1734
1735
for (const String &E : font_names) {
1736
ret.push_back(E);
1737
}
1738
return ret;
1739
}
1740
1741
GODOT_GCC_WARNING_PUSH_AND_IGNORE("-Wnon-virtual-dtor") // Silence warning due to a COM API weirdness.
1742
1743
class FallbackTextAnalysisSource : public IDWriteTextAnalysisSource {
1744
LONG _cRef = 1;
1745
1746
bool rtl = false;
1747
Char16String string;
1748
Char16String locale;
1749
IDWriteNumberSubstitution *n_sub = nullptr;
1750
1751
public:
1752
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID **ppvInterface) override {
1753
if (IID_IUnknown == riid) {
1754
AddRef();
1755
*ppvInterface = (IUnknown *)this;
1756
} else if (__uuidof(IMMNotificationClient) == riid) {
1757
AddRef();
1758
*ppvInterface = (IMMNotificationClient *)this;
1759
} else {
1760
*ppvInterface = nullptr;
1761
return E_NOINTERFACE;
1762
}
1763
return S_OK;
1764
}
1765
1766
ULONG STDMETHODCALLTYPE AddRef() override {
1767
return InterlockedIncrement(&_cRef);
1768
}
1769
1770
ULONG STDMETHODCALLTYPE Release() override {
1771
ULONG ulRef = InterlockedDecrement(&_cRef);
1772
if (0 == ulRef) {
1773
delete this;
1774
}
1775
return ulRef;
1776
}
1777
1778
HRESULT STDMETHODCALLTYPE GetTextAtPosition(UINT32 p_text_position, WCHAR const **r_text_string, UINT32 *r_text_length) override {
1779
if (p_text_position >= (UINT32)string.length()) {
1780
*r_text_string = nullptr;
1781
*r_text_length = 0;
1782
return S_OK;
1783
}
1784
*r_text_string = reinterpret_cast<const wchar_t *>(string.get_data()) + p_text_position;
1785
*r_text_length = string.length() - p_text_position;
1786
return S_OK;
1787
}
1788
1789
HRESULT STDMETHODCALLTYPE GetTextBeforePosition(UINT32 p_text_position, WCHAR const **r_text_string, UINT32 *r_text_length) override {
1790
if (p_text_position < 1 || p_text_position >= (UINT32)string.length()) {
1791
*r_text_string = nullptr;
1792
*r_text_length = 0;
1793
return S_OK;
1794
}
1795
*r_text_string = reinterpret_cast<const wchar_t *>(string.get_data());
1796
*r_text_length = p_text_position;
1797
return S_OK;
1798
}
1799
1800
DWRITE_READING_DIRECTION STDMETHODCALLTYPE GetParagraphReadingDirection() override {
1801
return (rtl) ? DWRITE_READING_DIRECTION_RIGHT_TO_LEFT : DWRITE_READING_DIRECTION_LEFT_TO_RIGHT;
1802
}
1803
1804
HRESULT STDMETHODCALLTYPE GetLocaleName(UINT32 p_text_position, UINT32 *r_text_length, WCHAR const **r_locale_name) override {
1805
*r_locale_name = reinterpret_cast<const wchar_t *>(locale.get_data());
1806
return S_OK;
1807
}
1808
1809
HRESULT STDMETHODCALLTYPE GetNumberSubstitution(UINT32 p_text_position, UINT32 *r_text_length, IDWriteNumberSubstitution **r_number_substitution) override {
1810
*r_number_substitution = n_sub;
1811
return S_OK;
1812
}
1813
1814
FallbackTextAnalysisSource(const Char16String &p_text, const Char16String &p_locale, bool p_rtl, IDWriteNumberSubstitution *p_nsub) {
1815
_cRef = 1;
1816
string = p_text;
1817
locale = p_locale;
1818
n_sub = p_nsub;
1819
rtl = p_rtl;
1820
}
1821
1822
virtual ~FallbackTextAnalysisSource() {}
1823
};
1824
1825
GODOT_GCC_WARNING_POP
1826
1827
String OS_Windows::_get_default_fontname(const String &p_font_name) const {
1828
String font_name = p_font_name;
1829
if (font_name.to_lower() == "sans-serif") {
1830
font_name = "Arial";
1831
} else if (font_name.to_lower() == "serif") {
1832
font_name = "Times New Roman";
1833
} else if (font_name.to_lower() == "monospace") {
1834
font_name = "Courier New";
1835
} else if (font_name.to_lower() == "cursive") {
1836
font_name = "Comic Sans MS";
1837
} else if (font_name.to_lower() == "fantasy") {
1838
font_name = "Gabriola";
1839
}
1840
return font_name;
1841
}
1842
1843
DWRITE_FONT_WEIGHT OS_Windows::_weight_to_dw(int p_weight) const {
1844
if (p_weight < 150) {
1845
return DWRITE_FONT_WEIGHT_THIN;
1846
} else if (p_weight < 250) {
1847
return DWRITE_FONT_WEIGHT_EXTRA_LIGHT;
1848
} else if (p_weight < 325) {
1849
return DWRITE_FONT_WEIGHT_LIGHT;
1850
} else if (p_weight < 375) {
1851
return DWRITE_FONT_WEIGHT_SEMI_LIGHT;
1852
} else if (p_weight < 450) {
1853
return DWRITE_FONT_WEIGHT_NORMAL;
1854
} else if (p_weight < 550) {
1855
return DWRITE_FONT_WEIGHT_MEDIUM;
1856
} else if (p_weight < 650) {
1857
return DWRITE_FONT_WEIGHT_DEMI_BOLD;
1858
} else if (p_weight < 750) {
1859
return DWRITE_FONT_WEIGHT_BOLD;
1860
} else if (p_weight < 850) {
1861
return DWRITE_FONT_WEIGHT_EXTRA_BOLD;
1862
} else if (p_weight < 925) {
1863
return DWRITE_FONT_WEIGHT_BLACK;
1864
} else {
1865
return DWRITE_FONT_WEIGHT_EXTRA_BLACK;
1866
}
1867
}
1868
1869
DWRITE_FONT_STRETCH OS_Windows::_stretch_to_dw(int p_stretch) const {
1870
if (p_stretch < 56) {
1871
return DWRITE_FONT_STRETCH_ULTRA_CONDENSED;
1872
} else if (p_stretch < 69) {
1873
return DWRITE_FONT_STRETCH_EXTRA_CONDENSED;
1874
} else if (p_stretch < 81) {
1875
return DWRITE_FONT_STRETCH_CONDENSED;
1876
} else if (p_stretch < 93) {
1877
return DWRITE_FONT_STRETCH_SEMI_CONDENSED;
1878
} else if (p_stretch < 106) {
1879
return DWRITE_FONT_STRETCH_NORMAL;
1880
} else if (p_stretch < 137) {
1881
return DWRITE_FONT_STRETCH_SEMI_EXPANDED;
1882
} else if (p_stretch < 144) {
1883
return DWRITE_FONT_STRETCH_EXPANDED;
1884
} else if (p_stretch < 162) {
1885
return DWRITE_FONT_STRETCH_EXTRA_EXPANDED;
1886
} else {
1887
return DWRITE_FONT_STRETCH_ULTRA_EXPANDED;
1888
}
1889
}
1890
1891
Vector<String> OS_Windows::get_system_font_path_for_text(const String &p_font_name, const String &p_text, const String &p_locale, const String &p_script, int p_weight, int p_stretch, bool p_italic) const {
1892
// This may be called before TextServerManager has been created, which would cause a crash downstream if we do not check here
1893
if (!dwrite2_init || !TextServerManager::get_singleton()) {
1894
return Vector<String>();
1895
}
1896
1897
String font_name = _get_default_fontname(p_font_name);
1898
1899
bool rtl = TS->is_locale_right_to_left(p_locale);
1900
Char16String text = p_text.utf16();
1901
Char16String locale = p_locale.utf16();
1902
1903
ComAutoreleaseRef<IDWriteNumberSubstitution> number_substitution;
1904
HRESULT hr = dwrite_factory->CreateNumberSubstitution(DWRITE_NUMBER_SUBSTITUTION_METHOD_NONE, reinterpret_cast<const wchar_t *>(locale.get_data()), true, &number_substitution.reference);
1905
ERR_FAIL_COND_V(FAILED(hr) || number_substitution.is_null(), Vector<String>());
1906
1907
FallbackTextAnalysisSource fs = FallbackTextAnalysisSource(text, locale, rtl, number_substitution.reference);
1908
UINT32 mapped_length = 0;
1909
FLOAT scale = 0.0;
1910
ComAutoreleaseRef<IDWriteFont> dwrite_font;
1911
hr = system_font_fallback->MapCharacters(
1912
&fs,
1913
0,
1914
(UINT32)text.length(),
1915
font_collection,
1916
reinterpret_cast<const wchar_t *>(font_name.utf16().get_data()),
1917
_weight_to_dw(p_weight),
1918
p_italic ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL,
1919
_stretch_to_dw(p_stretch),
1920
&mapped_length,
1921
&dwrite_font.reference,
1922
&scale);
1923
1924
if (FAILED(hr) || dwrite_font.is_null()) {
1925
return Vector<String>();
1926
}
1927
1928
ComAutoreleaseRef<IDWriteFontFace> dwrite_face;
1929
hr = dwrite_font->CreateFontFace(&dwrite_face.reference);
1930
if (FAILED(hr) || dwrite_face.is_null()) {
1931
return Vector<String>();
1932
}
1933
1934
UINT32 number_of_files = 0;
1935
hr = dwrite_face->GetFiles(&number_of_files, nullptr);
1936
if (FAILED(hr)) {
1937
return Vector<String>();
1938
}
1939
Vector<ComAutoreleaseRef<IDWriteFontFile>> files;
1940
files.resize(number_of_files);
1941
hr = dwrite_face->GetFiles(&number_of_files, (IDWriteFontFile **)files.ptrw());
1942
if (FAILED(hr)) {
1943
return Vector<String>();
1944
}
1945
1946
Vector<String> ret;
1947
for (UINT32 i = 0; i < number_of_files; i++) {
1948
void const *reference_key = nullptr;
1949
UINT32 reference_key_size = 0;
1950
ComAutoreleaseRef<IDWriteLocalFontFileLoader> loader;
1951
1952
hr = files.write[i]->GetLoader((IDWriteFontFileLoader **)&loader.reference);
1953
if (FAILED(hr) || loader.is_null()) {
1954
continue;
1955
}
1956
hr = files.write[i]->GetReferenceKey(&reference_key, &reference_key_size);
1957
if (FAILED(hr)) {
1958
continue;
1959
}
1960
1961
WCHAR file_path[32767];
1962
hr = loader->GetFilePathFromKey(reference_key, reference_key_size, &file_path[0], 32767);
1963
if (FAILED(hr)) {
1964
continue;
1965
}
1966
String fpath = String::utf16((const char16_t *)&file_path[0]).replace_char('\\', '/');
1967
1968
WIN32_FIND_DATAW d;
1969
HANDLE fnd = FindFirstFileW((LPCWSTR)&file_path[0], &d);
1970
if (fnd != INVALID_HANDLE_VALUE) {
1971
String fname = String::utf16((const char16_t *)d.cFileName);
1972
if (!fname.is_empty()) {
1973
fpath = fpath.get_base_dir().path_join(fname);
1974
}
1975
FindClose(fnd);
1976
}
1977
ret.push_back(fpath);
1978
}
1979
return ret;
1980
}
1981
1982
String OS_Windows::get_system_font_path(const String &p_font_name, int p_weight, int p_stretch, bool p_italic) const {
1983
if (!dwrite_init) {
1984
return String();
1985
}
1986
1987
String font_name = _get_default_fontname(p_font_name);
1988
1989
UINT32 index = 0;
1990
BOOL exists = false;
1991
HRESULT hr = font_collection->FindFamilyName((const WCHAR *)font_name.utf16().get_data(), &index, &exists);
1992
if (FAILED(hr) || !exists) {
1993
return String();
1994
}
1995
1996
ComAutoreleaseRef<IDWriteFontFamily> family;
1997
hr = font_collection->GetFontFamily(index, &family.reference);
1998
if (FAILED(hr) || family.is_null()) {
1999
return String();
2000
}
2001
2002
ComAutoreleaseRef<IDWriteFont> dwrite_font;
2003
hr = family->GetFirstMatchingFont(_weight_to_dw(p_weight), _stretch_to_dw(p_stretch), p_italic ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL, &dwrite_font.reference);
2004
if (FAILED(hr) || dwrite_font.is_null()) {
2005
return String();
2006
}
2007
2008
ComAutoreleaseRef<IDWriteFontFace> dwrite_face;
2009
hr = dwrite_font->CreateFontFace(&dwrite_face.reference);
2010
if (FAILED(hr) || dwrite_face.is_null()) {
2011
return String();
2012
}
2013
2014
UINT32 number_of_files = 0;
2015
hr = dwrite_face->GetFiles(&number_of_files, nullptr);
2016
if (FAILED(hr)) {
2017
return String();
2018
}
2019
Vector<ComAutoreleaseRef<IDWriteFontFile>> files;
2020
files.resize(number_of_files);
2021
hr = dwrite_face->GetFiles(&number_of_files, (IDWriteFontFile **)files.ptrw());
2022
if (FAILED(hr)) {
2023
return String();
2024
}
2025
2026
for (UINT32 i = 0; i < number_of_files; i++) {
2027
void const *reference_key = nullptr;
2028
UINT32 reference_key_size = 0;
2029
ComAutoreleaseRef<IDWriteLocalFontFileLoader> loader;
2030
2031
hr = files.write[i]->GetLoader((IDWriteFontFileLoader **)&loader.reference);
2032
if (FAILED(hr) || loader.is_null()) {
2033
continue;
2034
}
2035
hr = files.write[i]->GetReferenceKey(&reference_key, &reference_key_size);
2036
if (FAILED(hr)) {
2037
continue;
2038
}
2039
2040
WCHAR file_path[32767];
2041
hr = loader->GetFilePathFromKey(reference_key, reference_key_size, &file_path[0], 32767);
2042
if (FAILED(hr)) {
2043
continue;
2044
}
2045
String fpath = String::utf16((const char16_t *)&file_path[0]).replace_char('\\', '/');
2046
2047
WIN32_FIND_DATAW d;
2048
HANDLE fnd = FindFirstFileW((LPCWSTR)&file_path[0], &d);
2049
if (fnd != INVALID_HANDLE_VALUE) {
2050
String fname = String::utf16((const char16_t *)d.cFileName);
2051
if (!fname.is_empty()) {
2052
fpath = fpath.get_base_dir().path_join(fname);
2053
}
2054
FindClose(fnd);
2055
}
2056
2057
return fpath;
2058
}
2059
return String();
2060
}
2061
2062
String OS_Windows::get_executable_path() const {
2063
WCHAR bufname[4096];
2064
GetModuleFileNameW(nullptr, bufname, 4096);
2065
String s = String::utf16((const char16_t *)bufname).replace_char('\\', '/');
2066
return s;
2067
}
2068
2069
bool OS_Windows::has_environment(const String &p_var) const {
2070
return GetEnvironmentVariableW((LPCWSTR)(p_var.utf16().get_data()), nullptr, 0) > 0;
2071
}
2072
2073
String OS_Windows::get_environment(const String &p_var) const {
2074
WCHAR wval[0x7fff]; // MSDN says 32767 char is the maximum
2075
int wlen = GetEnvironmentVariableW((LPCWSTR)(p_var.utf16().get_data()), wval, 0x7fff);
2076
if (wlen > 0) {
2077
return String::utf16((const char16_t *)wval);
2078
}
2079
return "";
2080
}
2081
2082
void OS_Windows::set_environment(const String &p_var, const String &p_value) const {
2083
ERR_FAIL_COND_MSG(p_var.is_empty() || p_var.contains_char('='), vformat("Invalid environment variable name '%s', cannot be empty or include '='.", p_var));
2084
Char16String var = p_var.utf16();
2085
Char16String value = p_value.utf16();
2086
ERR_FAIL_COND_MSG(var.length() + value.length() + 2 > 32767, vformat("Invalid definition for environment variable '%s', cannot exceed 32767 characters.", p_var));
2087
SetEnvironmentVariableW((LPCWSTR)(var.get_data()), (LPCWSTR)(value.get_data()));
2088
}
2089
2090
void OS_Windows::unset_environment(const String &p_var) const {
2091
ERR_FAIL_COND_MSG(p_var.is_empty() || p_var.contains_char('='), vformat("Invalid environment variable name '%s', cannot be empty or include '='.", p_var));
2092
SetEnvironmentVariableW((LPCWSTR)(p_var.utf16().get_data()), nullptr); // Null to delete.
2093
}
2094
2095
String OS_Windows::get_stdin_string(int64_t p_buffer_size) {
2096
if (get_stdin_type() == STD_HANDLE_INVALID) {
2097
return String();
2098
}
2099
2100
Vector<uint8_t> data;
2101
data.resize(p_buffer_size);
2102
DWORD count = 0;
2103
if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), data.ptrw(), data.size(), &count, nullptr)) {
2104
return String::utf8((const char *)data.ptr(), count).replace("\r\n", "\n").rstrip("\n");
2105
}
2106
2107
return String();
2108
}
2109
2110
PackedByteArray OS_Windows::get_stdin_buffer(int64_t p_buffer_size) {
2111
Vector<uint8_t> data;
2112
data.resize(p_buffer_size);
2113
DWORD count = 0;
2114
if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), data.ptrw(), data.size(), &count, nullptr)) {
2115
return data;
2116
}
2117
2118
return PackedByteArray();
2119
}
2120
2121
OS_Windows::StdHandleType OS_Windows::get_stdin_type() const {
2122
HANDLE h = GetStdHandle(STD_INPUT_HANDLE);
2123
if (h == 0 || h == INVALID_HANDLE_VALUE) {
2124
return STD_HANDLE_INVALID;
2125
}
2126
DWORD ftype = GetFileType(h);
2127
if (ftype == FILE_TYPE_UNKNOWN && GetLastError() != ERROR_SUCCESS) {
2128
return STD_HANDLE_UNKNOWN;
2129
}
2130
ftype &= ~(FILE_TYPE_REMOTE);
2131
2132
if (ftype == FILE_TYPE_DISK) {
2133
return STD_HANDLE_FILE;
2134
} else if (ftype == FILE_TYPE_PIPE) {
2135
return STD_HANDLE_PIPE;
2136
} else {
2137
DWORD conmode = 0;
2138
BOOL res = GetConsoleMode(h, &conmode);
2139
if (!res && (GetLastError() == ERROR_INVALID_HANDLE)) {
2140
return STD_HANDLE_UNKNOWN; // Unknown character device.
2141
} else {
2142
#ifndef WINDOWS_SUBSYSTEM_CONSOLE
2143
if (!is_using_con_wrapper()) {
2144
return STD_HANDLE_INVALID; // Window app can't read stdin input without werapper.
2145
}
2146
#endif
2147
return STD_HANDLE_CONSOLE;
2148
}
2149
}
2150
}
2151
2152
OS_Windows::StdHandleType OS_Windows::get_stdout_type() const {
2153
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
2154
if (h == 0 || h == INVALID_HANDLE_VALUE) {
2155
return STD_HANDLE_INVALID;
2156
}
2157
DWORD ftype = GetFileType(h);
2158
if (ftype == FILE_TYPE_UNKNOWN && GetLastError() != ERROR_SUCCESS) {
2159
return STD_HANDLE_UNKNOWN;
2160
}
2161
ftype &= ~(FILE_TYPE_REMOTE);
2162
2163
if (ftype == FILE_TYPE_DISK) {
2164
return STD_HANDLE_FILE;
2165
} else if (ftype == FILE_TYPE_PIPE) {
2166
return STD_HANDLE_PIPE;
2167
} else {
2168
DWORD conmode = 0;
2169
BOOL res = GetConsoleMode(h, &conmode);
2170
if (!res && (GetLastError() == ERROR_INVALID_HANDLE)) {
2171
return STD_HANDLE_UNKNOWN; // Unknown character device.
2172
} else {
2173
return STD_HANDLE_CONSOLE;
2174
}
2175
}
2176
}
2177
2178
OS_Windows::StdHandleType OS_Windows::get_stderr_type() const {
2179
HANDLE h = GetStdHandle(STD_ERROR_HANDLE);
2180
if (h == 0 || h == INVALID_HANDLE_VALUE) {
2181
return STD_HANDLE_INVALID;
2182
}
2183
DWORD ftype = GetFileType(h);
2184
if (ftype == FILE_TYPE_UNKNOWN && GetLastError() != ERROR_SUCCESS) {
2185
return STD_HANDLE_UNKNOWN;
2186
}
2187
ftype &= ~(FILE_TYPE_REMOTE);
2188
2189
if (ftype == FILE_TYPE_DISK) {
2190
return STD_HANDLE_FILE;
2191
} else if (ftype == FILE_TYPE_PIPE) {
2192
return STD_HANDLE_PIPE;
2193
} else {
2194
DWORD conmode = 0;
2195
BOOL res = GetConsoleMode(h, &conmode);
2196
if (!res && (GetLastError() == ERROR_INVALID_HANDLE)) {
2197
return STD_HANDLE_UNKNOWN; // Unknown character device.
2198
} else {
2199
return STD_HANDLE_CONSOLE;
2200
}
2201
}
2202
}
2203
2204
Error OS_Windows::shell_open(const String &p_uri) {
2205
INT_PTR ret = (INT_PTR)ShellExecuteW(nullptr, nullptr, (LPCWSTR)(p_uri.utf16().get_data()), nullptr, nullptr, SW_SHOWNORMAL);
2206
if (ret > 32) {
2207
return OK;
2208
} else {
2209
switch (ret) {
2210
case ERROR_FILE_NOT_FOUND:
2211
case SE_ERR_DLLNOTFOUND:
2212
return ERR_FILE_NOT_FOUND;
2213
case ERROR_PATH_NOT_FOUND:
2214
return ERR_FILE_BAD_PATH;
2215
case ERROR_BAD_FORMAT:
2216
return ERR_FILE_CORRUPT;
2217
case SE_ERR_ACCESSDENIED:
2218
return ERR_UNAUTHORIZED;
2219
case 0:
2220
case SE_ERR_OOM:
2221
return ERR_OUT_OF_MEMORY;
2222
default:
2223
return FAILED;
2224
}
2225
}
2226
}
2227
2228
Error OS_Windows::shell_show_in_file_manager(String p_path, bool p_open_folder) {
2229
bool open_folder = false;
2230
if (DirAccess::dir_exists_absolute(p_path) && p_open_folder) {
2231
open_folder = true;
2232
}
2233
2234
if (!p_path.is_quoted()) {
2235
p_path = p_path.quote();
2236
}
2237
p_path = fix_path(p_path);
2238
2239
INT_PTR ret = OK;
2240
if (open_folder) {
2241
ret = (INT_PTR)ShellExecuteW(nullptr, nullptr, L"explorer.exe", LPCWSTR(p_path.utf16().get_data()), nullptr, SW_SHOWNORMAL);
2242
} else {
2243
ret = (INT_PTR)ShellExecuteW(nullptr, nullptr, L"explorer.exe", LPCWSTR((String("/select,") + p_path).utf16().get_data()), nullptr, SW_SHOWNORMAL);
2244
}
2245
2246
if (ret > 32) {
2247
return OK;
2248
} else {
2249
switch (ret) {
2250
case ERROR_FILE_NOT_FOUND:
2251
case SE_ERR_DLLNOTFOUND:
2252
return ERR_FILE_NOT_FOUND;
2253
case ERROR_PATH_NOT_FOUND:
2254
return ERR_FILE_BAD_PATH;
2255
case ERROR_BAD_FORMAT:
2256
return ERR_FILE_CORRUPT;
2257
case SE_ERR_ACCESSDENIED:
2258
return ERR_UNAUTHORIZED;
2259
case 0:
2260
case SE_ERR_OOM:
2261
return ERR_OUT_OF_MEMORY;
2262
default:
2263
return FAILED;
2264
}
2265
}
2266
}
2267
2268
String OS_Windows::get_locale() const {
2269
const _WinLocale *wl = &_win_locales[0];
2270
2271
LANGID langid = GetUserDefaultUILanguage();
2272
String neutral;
2273
int lang = PRIMARYLANGID(langid);
2274
int sublang = SUBLANGID(langid);
2275
2276
while (wl->locale) {
2277
if (wl->main_lang == lang && wl->sublang == SUBLANG_NEUTRAL) {
2278
neutral = wl->locale;
2279
}
2280
2281
if (lang == wl->main_lang && sublang == wl->sublang) {
2282
return String(wl->locale).replace_char('-', '_');
2283
}
2284
2285
wl++;
2286
}
2287
2288
if (!neutral.is_empty()) {
2289
return String(neutral).replace_char('-', '_');
2290
}
2291
2292
return "en";
2293
}
2294
2295
String OS_Windows::get_model_name() const {
2296
HKEY hkey;
2297
if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"Hardware\\Description\\System\\BIOS", 0, KEY_QUERY_VALUE, &hkey) != ERROR_SUCCESS) {
2298
return OS::get_model_name();
2299
}
2300
2301
String sys_name;
2302
String board_name;
2303
WCHAR buffer[256];
2304
DWORD buffer_len = 256;
2305
DWORD vtype = REG_SZ;
2306
if (RegQueryValueExW(hkey, L"SystemProductName", nullptr, &vtype, (LPBYTE)buffer, &buffer_len) == ERROR_SUCCESS && buffer_len != 0) {
2307
sys_name = String::utf16((const char16_t *)buffer, buffer_len).strip_edges();
2308
}
2309
buffer_len = 256;
2310
if (RegQueryValueExW(hkey, L"BaseBoardProduct", nullptr, &vtype, (LPBYTE)buffer, &buffer_len) == ERROR_SUCCESS && buffer_len != 0) {
2311
board_name = String::utf16((const char16_t *)buffer, buffer_len).strip_edges();
2312
}
2313
RegCloseKey(hkey);
2314
if (!sys_name.is_empty() && sys_name.to_lower() != "system product name") {
2315
return sys_name;
2316
}
2317
if (!board_name.is_empty() && board_name.to_lower() != "base board product") {
2318
return board_name;
2319
}
2320
return OS::get_model_name();
2321
}
2322
2323
String OS_Windows::get_processor_name() const {
2324
const String id = "Hardware\\Description\\System\\CentralProcessor\\0";
2325
2326
HKEY hkey;
2327
if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, (LPCWSTR)(id.utf16().get_data()), 0, KEY_QUERY_VALUE, &hkey) != ERROR_SUCCESS) {
2328
ERR_FAIL_V_MSG("", String("Couldn't get the CPU model name. Returning an empty string."));
2329
}
2330
2331
WCHAR buffer[256];
2332
DWORD buffer_len = 256;
2333
DWORD vtype = REG_SZ;
2334
if (RegQueryValueExW(hkey, L"ProcessorNameString", nullptr, &vtype, (LPBYTE)buffer, &buffer_len) == ERROR_SUCCESS) {
2335
RegCloseKey(hkey);
2336
return String::utf16((const char16_t *)buffer, buffer_len).strip_edges();
2337
} else {
2338
RegCloseKey(hkey);
2339
ERR_FAIL_V_MSG("", String("Couldn't get the CPU model name. Returning an empty string."));
2340
}
2341
}
2342
2343
void OS_Windows::run() {
2344
if (!main_loop) {
2345
return;
2346
}
2347
2348
main_loop->initialize();
2349
2350
while (true) {
2351
GodotProfileFrameMark;
2352
GodotProfileZone("OS_Windows::run");
2353
DisplayServer::get_singleton()->process_events(); // get rid of pending events
2354
if (Main::iteration()) {
2355
break;
2356
}
2357
}
2358
2359
main_loop->finalize();
2360
}
2361
2362
MainLoop *OS_Windows::get_main_loop() const {
2363
return main_loop;
2364
}
2365
2366
uint64_t OS_Windows::get_embedded_pck_offset() const {
2367
Ref<FileAccess> f = FileAccess::open(get_executable_path(), FileAccess::READ);
2368
if (f.is_null()) {
2369
return 0;
2370
}
2371
2372
// Process header.
2373
{
2374
f->seek(0x3c);
2375
uint32_t pe_pos = f->get_32();
2376
2377
f->seek(pe_pos);
2378
uint32_t magic = f->get_32();
2379
if (magic != 0x00004550) {
2380
return 0;
2381
}
2382
}
2383
2384
int num_sections;
2385
{
2386
int64_t header_pos = f->get_position();
2387
2388
f->seek(header_pos + 2);
2389
num_sections = f->get_16();
2390
f->seek(header_pos + 16);
2391
uint16_t opt_header_size = f->get_16();
2392
2393
// Skip rest of header + optional header to go to the section headers.
2394
f->seek(f->get_position() + 2 + opt_header_size);
2395
}
2396
int64_t section_table_pos = f->get_position();
2397
2398
// Search for the "pck" section.
2399
int64_t off = 0;
2400
for (int i = 0; i < num_sections; ++i) {
2401
int64_t section_header_pos = section_table_pos + i * 40;
2402
f->seek(section_header_pos);
2403
2404
uint8_t section_name[9];
2405
f->get_buffer(section_name, 8);
2406
section_name[8] = '\0';
2407
2408
if (strcmp((char *)section_name, "pck") == 0) {
2409
f->seek(section_header_pos + 20);
2410
off = f->get_32();
2411
break;
2412
}
2413
}
2414
2415
return off;
2416
}
2417
2418
String OS_Windows::get_config_path() const {
2419
if (has_environment("APPDATA")) {
2420
return get_environment("APPDATA").replace_char('\\', '/');
2421
}
2422
return ".";
2423
}
2424
2425
String OS_Windows::get_data_path() const {
2426
return get_config_path();
2427
}
2428
2429
String OS_Windows::get_cache_path() const {
2430
static String cache_path_cache;
2431
if (cache_path_cache.is_empty()) {
2432
if (has_environment("LOCALAPPDATA")) {
2433
cache_path_cache = get_environment("LOCALAPPDATA").replace_char('\\', '/');
2434
}
2435
if (cache_path_cache.is_empty()) {
2436
cache_path_cache = get_temp_path();
2437
}
2438
}
2439
return cache_path_cache;
2440
}
2441
2442
String OS_Windows::get_temp_path() const {
2443
static String temp_path_cache;
2444
if (temp_path_cache.is_empty()) {
2445
{
2446
Vector<WCHAR> temp_path;
2447
// The maximum possible size is MAX_PATH+1 (261) + terminating null character.
2448
temp_path.resize(MAX_PATH + 2);
2449
DWORD temp_path_length = GetTempPathW(temp_path.size(), temp_path.ptrw());
2450
if (temp_path_length > 0 && temp_path_length < temp_path.size()) {
2451
temp_path_cache = String::utf16((const char16_t *)temp_path.ptr());
2452
// Let's try to get the long path instead of the short path (with tildes ~).
2453
DWORD temp_path_long_length = GetLongPathNameW(temp_path.ptr(), temp_path.ptrw(), temp_path.size());
2454
if (temp_path_long_length > 0 && temp_path_long_length < temp_path.size()) {
2455
temp_path_cache = String::utf16((const char16_t *)temp_path.ptr());
2456
}
2457
}
2458
}
2459
if (temp_path_cache.is_empty()) {
2460
temp_path_cache = get_config_path();
2461
}
2462
}
2463
return temp_path_cache.replace_char('\\', '/').trim_suffix("/");
2464
}
2465
2466
// Get properly capitalized engine name for system paths
2467
String OS_Windows::get_godot_dir_name() const {
2468
return String(GODOT_VERSION_SHORT_NAME).capitalize();
2469
}
2470
2471
String OS_Windows::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
2472
KNOWNFOLDERID id;
2473
2474
switch (p_dir) {
2475
case SYSTEM_DIR_DESKTOP: {
2476
id = FOLDERID_Desktop;
2477
} break;
2478
case SYSTEM_DIR_DCIM: {
2479
id = FOLDERID_Pictures;
2480
} break;
2481
case SYSTEM_DIR_DOCUMENTS: {
2482
id = FOLDERID_Documents;
2483
} break;
2484
case SYSTEM_DIR_DOWNLOADS: {
2485
id = FOLDERID_Downloads;
2486
} break;
2487
case SYSTEM_DIR_MOVIES: {
2488
id = FOLDERID_Videos;
2489
} break;
2490
case SYSTEM_DIR_MUSIC: {
2491
id = FOLDERID_Music;
2492
} break;
2493
case SYSTEM_DIR_PICTURES: {
2494
id = FOLDERID_Pictures;
2495
} break;
2496
case SYSTEM_DIR_RINGTONES: {
2497
id = FOLDERID_Music;
2498
} break;
2499
}
2500
2501
PWSTR szPath;
2502
HRESULT res = SHGetKnownFolderPath(id, 0, nullptr, &szPath);
2503
ERR_FAIL_COND_V(res != S_OK, String());
2504
String path = String::utf16((const char16_t *)szPath).replace_char('\\', '/');
2505
CoTaskMemFree(szPath);
2506
return path;
2507
}
2508
2509
String OS_Windows::get_user_data_dir(const String &p_user_dir) const {
2510
return get_data_path().path_join(p_user_dir).replace_char('\\', '/');
2511
}
2512
2513
String OS_Windows::get_unique_id() const {
2514
HW_PROFILE_INFOA HwProfInfo;
2515
ERR_FAIL_COND_V(!GetCurrentHwProfileA(&HwProfInfo), "");
2516
2517
// Note: Windows API returns a GUID with null termination.
2518
return String::ascii(Span<char>(HwProfInfo.szHwProfileGuid, strnlen(HwProfInfo.szHwProfileGuid, HW_PROFILE_GUIDLEN)));
2519
}
2520
2521
bool OS_Windows::_check_internal_feature_support(const String &p_feature) {
2522
if (p_feature == "system_fonts") {
2523
return dwrite_init;
2524
}
2525
if (p_feature == "pc") {
2526
return true;
2527
}
2528
2529
return false;
2530
}
2531
2532
void OS_Windows::disable_crash_handler() {
2533
crash_handler.disable();
2534
}
2535
2536
bool OS_Windows::is_disable_crash_handler() const {
2537
return crash_handler.is_disabled();
2538
}
2539
2540
Error OS_Windows::move_to_trash(const String &p_path) {
2541
SHFILEOPSTRUCTW sf;
2542
2543
Char16String utf16 = p_path.utf16();
2544
WCHAR *from = new WCHAR[utf16.length() + 2];
2545
wcscpy_s(from, utf16.length() + 1, (LPCWSTR)(utf16.get_data()));
2546
from[utf16.length() + 1] = 0;
2547
2548
sf.hwnd = main_window;
2549
sf.wFunc = FO_DELETE;
2550
sf.pFrom = from;
2551
sf.pTo = nullptr;
2552
sf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;
2553
sf.fAnyOperationsAborted = FALSE;
2554
sf.hNameMappings = nullptr;
2555
sf.lpszProgressTitle = nullptr;
2556
2557
int ret = SHFileOperationW(&sf);
2558
delete[] from;
2559
2560
if (ret) {
2561
ERR_PRINT("SHFileOperation error: " + itos(ret));
2562
return FAILED;
2563
}
2564
2565
return OK;
2566
}
2567
2568
String OS_Windows::get_system_ca_certificates() {
2569
HCERTSTORE cert_store = CertOpenSystemStoreA(0, "ROOT");
2570
ERR_FAIL_NULL_V_MSG(cert_store, "", "Failed to read the root certificate store.");
2571
2572
FILETIME curr_time;
2573
GetSystemTimeAsFileTime(&curr_time);
2574
2575
String certs;
2576
PCCERT_CONTEXT curr = CertEnumCertificatesInStore(cert_store, nullptr);
2577
while (curr) {
2578
FILETIME ft;
2579
DWORD size = sizeof(ft);
2580
// Check if the certificate is disallowed.
2581
if (CertGetCertificateContextProperty(curr, CERT_DISALLOWED_FILETIME_PROP_ID, &ft, &size) && CompareFileTime(&curr_time, &ft) != -1) {
2582
curr = CertEnumCertificatesInStore(cert_store, curr);
2583
continue;
2584
}
2585
// Encode and add to certificate list.
2586
bool success = CryptBinaryToStringA(curr->pbCertEncoded, curr->cbCertEncoded, CRYPT_STRING_BASE64HEADER | CRYPT_STRING_NOCR, nullptr, &size);
2587
ERR_CONTINUE(!success);
2588
PackedByteArray pba;
2589
pba.resize(size + 1);
2590
CryptBinaryToStringA(curr->pbCertEncoded, curr->cbCertEncoded, CRYPT_STRING_BASE64HEADER | CRYPT_STRING_NOCR, (char *)pba.ptrw(), &size);
2591
pba.write[size] = 0;
2592
certs += String::ascii(Span((const char *)pba.ptr(), strlen((const char *)pba.ptr())));
2593
curr = CertEnumCertificatesInStore(cert_store, curr);
2594
}
2595
CertCloseStore(cert_store, 0);
2596
return certs;
2597
}
2598
2599
void OS_Windows::add_frame_delay(bool p_can_draw, bool p_wake_for_events) {
2600
if (p_wake_for_events) {
2601
uint64_t delay = get_frame_delay(p_can_draw);
2602
if (delay == 0) {
2603
return;
2604
}
2605
2606
DisplayServer *ds = DisplayServer::get_singleton();
2607
DisplayServerWindows *ds_win = Object::cast_to<DisplayServerWindows>(ds);
2608
if (ds_win) {
2609
MsgWaitForMultipleObjects(0, nullptr, false, Math::floor(double(delay) / 1000.0), QS_ALLINPUT);
2610
return;
2611
}
2612
}
2613
2614
const uint32_t frame_delay = Engine::get_singleton()->get_frame_delay();
2615
if (frame_delay) {
2616
// Add fixed frame delay to decrease CPU/GPU usage. This doesn't take
2617
// the actual frame time into account.
2618
// Due to the high fluctuation of the actual sleep duration, it's not recommended
2619
// to use this as a FPS limiter.
2620
delay_usec(frame_delay * 1000);
2621
}
2622
2623
// Add a dynamic frame delay to decrease CPU/GPU usage. This takes the
2624
// previous frame time into account for a smoother result.
2625
uint64_t dynamic_delay = 0;
2626
if (is_in_low_processor_usage_mode() || !p_can_draw) {
2627
dynamic_delay = get_low_processor_usage_mode_sleep_usec();
2628
}
2629
const int max_fps = Engine::get_singleton()->get_max_fps();
2630
if (max_fps > 0 && !Engine::get_singleton()->is_editor_hint()) {
2631
// Override the low processor usage mode sleep delay if the target FPS is lower.
2632
dynamic_delay = MAX(dynamic_delay, (uint64_t)(1000000 / max_fps));
2633
}
2634
2635
if (dynamic_delay > 0) {
2636
target_ticks += dynamic_delay;
2637
uint64_t current_ticks = get_ticks_usec();
2638
2639
if (!is_in_low_processor_usage_mode()) {
2640
if (target_ticks > current_ticks + delay_resolution) {
2641
uint64_t delay_time = target_ticks - current_ticks - delay_resolution;
2642
// Make sure we always sleep for a multiple of delay_resolution to avoid overshooting.
2643
// Refer to: https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-sleep#remarks
2644
delay_time = (delay_time / delay_resolution) * delay_resolution;
2645
if (delay_time > 0) {
2646
delay_usec(delay_time);
2647
}
2648
}
2649
// Busy wait for the remainder of time.
2650
while (get_ticks_usec() < target_ticks) {
2651
YieldProcessor();
2652
}
2653
} else {
2654
// Use a more relaxed approach for low processor usage mode.
2655
// This has worse frame pacing but is more power efficient.
2656
if (current_ticks < target_ticks) {
2657
delay_usec(target_ticks - current_ticks);
2658
}
2659
}
2660
2661
current_ticks = get_ticks_usec();
2662
target_ticks = MIN(MAX(target_ticks, current_ticks - dynamic_delay), current_ticks + dynamic_delay);
2663
}
2664
}
2665
2666
#ifdef TOOLS_ENABLED
2667
bool OS_Windows::_test_create_rendering_device(const String &p_display_driver) const {
2668
// Tests Rendering Device creation.
2669
2670
bool ok = false;
2671
#if defined(RD_ENABLED)
2672
Error err;
2673
RenderingContextDriver *rcd = nullptr;
2674
2675
#if defined(VULKAN_ENABLED)
2676
rcd = memnew(RenderingContextDriverVulkan);
2677
#endif
2678
#ifdef D3D12_ENABLED
2679
if (rcd == nullptr) {
2680
rcd = memnew(RenderingContextDriverD3D12);
2681
}
2682
#endif
2683
if (rcd != nullptr) {
2684
err = rcd->initialize();
2685
if (err == OK) {
2686
RenderingDevice *rd = memnew(RenderingDevice);
2687
err = rd->initialize(rcd);
2688
memdelete(rd);
2689
rd = nullptr;
2690
if (err == OK) {
2691
ok = true;
2692
}
2693
}
2694
memdelete(rcd);
2695
rcd = nullptr;
2696
}
2697
#endif
2698
2699
return ok;
2700
}
2701
2702
bool OS_Windows::_test_create_rendering_device_and_gl(const String &p_display_driver) const {
2703
// Tests OpenGL context and Rendering Device simultaneous creation. This function is expected to crash on some NVIDIA drivers.
2704
2705
WNDCLASSEXW wc_probe;
2706
memset(&wc_probe, 0, sizeof(WNDCLASSEXW));
2707
wc_probe.cbSize = sizeof(WNDCLASSEXW);
2708
wc_probe.style = CS_OWNDC | CS_DBLCLKS;
2709
wc_probe.lpfnWndProc = (WNDPROC)::DefWindowProcW;
2710
wc_probe.cbClsExtra = 0;
2711
wc_probe.cbWndExtra = 0;
2712
wc_probe.hInstance = GetModuleHandle(nullptr);
2713
wc_probe.hIcon = LoadIcon(nullptr, IDI_WINLOGO);
2714
wc_probe.hCursor = nullptr;
2715
wc_probe.hbrBackground = nullptr;
2716
wc_probe.lpszMenuName = nullptr;
2717
wc_probe.lpszClassName = L"Engine probe window";
2718
2719
if (!RegisterClassExW(&wc_probe)) {
2720
return false;
2721
}
2722
2723
HWND hWnd = CreateWindowExW(WS_EX_WINDOWEDGE, L"Engine probe window", L"", WS_OVERLAPPEDWINDOW, 0, 0, 800, 600, nullptr, nullptr, GetModuleHandle(nullptr), nullptr);
2724
if (!hWnd) {
2725
UnregisterClassW(L"Engine probe window", GetModuleHandle(nullptr));
2726
return false;
2727
}
2728
2729
bool ok = true;
2730
#ifdef GLES3_ENABLED
2731
GLManagerNative_Windows *test_gl_manager_native = memnew(GLManagerNative_Windows);
2732
if (test_gl_manager_native->window_create(DisplayServer::MAIN_WINDOW_ID, hWnd, GetModuleHandle(nullptr), 800, 600) == OK) {
2733
RasterizerGLES3::make_current(true);
2734
} else {
2735
ok = false;
2736
}
2737
#endif
2738
2739
MSG msg = {};
2740
while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) {
2741
TranslateMessage(&msg);
2742
DispatchMessageW(&msg);
2743
}
2744
2745
if (ok) {
2746
ok = _test_create_rendering_device(p_display_driver);
2747
}
2748
2749
#ifdef GLES3_ENABLED
2750
if (test_gl_manager_native) {
2751
memdelete(test_gl_manager_native);
2752
}
2753
#endif
2754
2755
DestroyWindow(hWnd);
2756
UnregisterClassW(L"Engine probe window", GetModuleHandle(nullptr));
2757
return ok;
2758
}
2759
#endif
2760
2761
#ifdef _MSC_VER
2762
#define IAT_HOOK_CALL __declspec(guard(nocf))
2763
#else
2764
#define IAT_HOOK_CALL
2765
#endif
2766
2767
using GetProcAddressType = FARPROC(__stdcall *)(HMODULE, LPCSTR);
2768
GetProcAddressType Original_GetProcAddress = nullptr;
2769
2770
using HidD_GetProductStringType = BOOLEAN(__stdcall *)(HANDLE, void *, ULONG);
2771
HidD_GetProductStringType Original_HidD_GetProductString = nullptr;
2772
2773
#ifndef HID_USAGE_GENERIC_MULTI_AXIS_CONTROLLER
2774
#define HID_USAGE_GENERIC_MULTI_AXIS_CONTROLLER 0x08
2775
#endif
2776
2777
bool _hid_is_controller(HANDLE p_hid_handle) {
2778
PHIDP_PREPARSED_DATA hid_preparsed = nullptr;
2779
BOOLEAN preparsed_res = HidD_GetPreparsedData(p_hid_handle, &hid_preparsed);
2780
if (!preparsed_res) {
2781
return false;
2782
}
2783
2784
HIDP_CAPS hid_caps = {};
2785
NTSTATUS caps_res = HidP_GetCaps(hid_preparsed, &hid_caps);
2786
HidD_FreePreparsedData(hid_preparsed);
2787
if (caps_res != HIDP_STATUS_SUCCESS) {
2788
return false;
2789
}
2790
2791
if (hid_caps.UsagePage != HID_USAGE_PAGE_GENERIC) {
2792
return false;
2793
}
2794
2795
if (hid_caps.Usage == HID_USAGE_GENERIC_JOYSTICK || hid_caps.Usage == HID_USAGE_GENERIC_GAMEPAD || hid_caps.Usage == HID_USAGE_GENERIC_MULTI_AXIS_CONTROLLER) {
2796
return true;
2797
}
2798
2799
return false;
2800
}
2801
2802
IAT_HOOK_CALL BOOLEAN __stdcall Hook_HidD_GetProductString(HANDLE p_object, void *p_buffer, ULONG p_buffer_length) {
2803
constexpr const wchar_t unknown_product_string[] = L"Unknown HID Device";
2804
constexpr size_t unknown_product_length = sizeof(unknown_product_string);
2805
2806
if (_hid_is_controller(p_object)) {
2807
return HidD_GetProductString(p_object, p_buffer, p_buffer_length);
2808
}
2809
2810
// The HID is (probably) not a controller, so we don't care about returning its actual product string.
2811
// This avoids stalls on `EnumDevices` because DirectInput attempts to enumerate all HIDs, including some DACs
2812
// and other devices which take too long to respond to those requests, added to the lack of a shorter timeout.
2813
if (p_buffer_length >= unknown_product_length) {
2814
memcpy(p_buffer, unknown_product_string, unknown_product_length);
2815
return TRUE;
2816
}
2817
return FALSE;
2818
}
2819
2820
IAT_HOOK_CALL FARPROC __stdcall Hook_GetProcAddress(HMODULE p_module, LPCSTR p_name) {
2821
if (String(p_name) == "HidD_GetProductString") {
2822
return (FARPROC)(LPVOID)Hook_HidD_GetProductString;
2823
}
2824
if (Original_GetProcAddress) {
2825
return Original_GetProcAddress(p_module, p_name);
2826
}
2827
return nullptr;
2828
}
2829
2830
LPVOID install_iat_hook(const String &p_target, const String &p_module, const String &p_symbol, LPVOID p_hook_func) {
2831
LPVOID image_base = LoadLibraryA(p_target.ascii().get_data());
2832
if (image_base) {
2833
PIMAGE_NT_HEADERS nt_headers = (PIMAGE_NT_HEADERS)((DWORD_PTR)image_base + ((PIMAGE_DOS_HEADER)image_base)->e_lfanew);
2834
PIMAGE_IMPORT_DESCRIPTOR import_descriptor = (PIMAGE_IMPORT_DESCRIPTOR)((DWORD_PTR)image_base + nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);
2835
while (import_descriptor->Name != 0) {
2836
LPCSTR library_name = (LPCSTR)((DWORD_PTR)image_base + import_descriptor->Name);
2837
if (String(library_name).to_lower() == p_module) {
2838
PIMAGE_THUNK_DATA original_first_thunk = (PIMAGE_THUNK_DATA)((DWORD_PTR)image_base + import_descriptor->OriginalFirstThunk);
2839
PIMAGE_THUNK_DATA first_thunk = (PIMAGE_THUNK_DATA)((DWORD_PTR)image_base + import_descriptor->FirstThunk);
2840
2841
while ((LPVOID)original_first_thunk->u1.AddressOfData != nullptr) {
2842
PIMAGE_IMPORT_BY_NAME function_import = (PIMAGE_IMPORT_BY_NAME)((DWORD_PTR)image_base + original_first_thunk->u1.AddressOfData);
2843
if (String(function_import->Name).to_lower() == p_symbol.to_lower()) {
2844
DWORD old_protect = 0;
2845
VirtualProtect((LPVOID)(&first_thunk->u1.Function), 8, PAGE_READWRITE, &old_protect);
2846
2847
LPVOID old_func = (LPVOID)first_thunk->u1.Function;
2848
first_thunk->u1.Function = (DWORD_PTR)p_hook_func;
2849
2850
VirtualProtect((LPVOID)(&first_thunk->u1.Function), 8, old_protect, nullptr);
2851
return old_func;
2852
}
2853
original_first_thunk++;
2854
first_thunk++;
2855
}
2856
}
2857
import_descriptor++;
2858
}
2859
}
2860
return nullptr;
2861
}
2862
2863
OS_Windows::OS_Windows(HINSTANCE _hInstance) {
2864
hInstance = _hInstance;
2865
2866
Original_GetProcAddress = (GetProcAddressType)install_iat_hook("dinput8.dll", "kernel32.dll", "GetProcAddress", (LPVOID)Hook_GetProcAddress);
2867
Original_HidD_GetProductString = (HidD_GetProductStringType)install_iat_hook("dinput8.dll", "hid.dll", "HidD_GetProductString", (LPVOID)Hook_HidD_GetProductString);
2868
2869
_init_encodings();
2870
2871
// Reset CWD to ensure long path is used.
2872
Char16String current_dir_name;
2873
size_t str_len = GetCurrentDirectoryW(0, nullptr);
2874
current_dir_name.resize_uninitialized(str_len + 1);
2875
GetCurrentDirectoryW(current_dir_name.size(), (LPWSTR)current_dir_name.ptrw());
2876
2877
Char16String new_current_dir_name;
2878
str_len = GetLongPathNameW((LPCWSTR)current_dir_name.get_data(), nullptr, 0);
2879
new_current_dir_name.resize_uninitialized(str_len + 1);
2880
GetLongPathNameW((LPCWSTR)current_dir_name.get_data(), (LPWSTR)new_current_dir_name.ptrw(), new_current_dir_name.size());
2881
2882
SetCurrentDirectoryW((LPCWSTR)new_current_dir_name.get_data());
2883
2884
#ifndef WINDOWS_SUBSYSTEM_CONSOLE
2885
RedirectIOToConsole();
2886
#endif
2887
2888
SetConsoleOutputCP(CP_UTF8);
2889
SetConsoleCP(CP_UTF8);
2890
2891
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
2892
2893
#ifdef WASAPI_ENABLED
2894
AudioDriverManager::add_driver(&driver_wasapi);
2895
#endif
2896
#ifdef XAUDIO2_ENABLED
2897
AudioDriverManager::add_driver(&driver_xaudio2);
2898
#endif
2899
2900
DisplayServerWindows::register_windows_driver();
2901
2902
// Enable ANSI escape code support on Windows 10 v1607 (Anniversary Update) and later.
2903
// This lets the engine and projects use ANSI escape codes to color text just like on macOS and Linux.
2904
//
2905
// NOTE: The engine does not use ANSI escape codes to color error/warning messages; it uses Windows API calls instead.
2906
// Therefore, error/warning messages are still colored on Windows versions older than 10.
2907
HANDLE stdoutHandle = GetStdHandle(STD_OUTPUT_HANDLE);
2908
DWORD outMode = 0;
2909
GetConsoleMode(stdoutHandle, &outMode);
2910
outMode |= ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING;
2911
if (!SetConsoleMode(stdoutHandle, outMode)) {
2912
// Windows 10 prior to Anniversary Update.
2913
print_verbose("Can't set the ENABLE_VIRTUAL_TERMINAL_PROCESSING Windows console mode. `print_rich()` will not work as expected.");
2914
}
2915
2916
Vector<Logger *> loggers;
2917
loggers.push_back(memnew(WindowsTerminalLogger));
2918
_set_logger(memnew(CompositeLogger(loggers)));
2919
}
2920
2921
OS_Windows::~OS_Windows() {
2922
CoUninitialize();
2923
}
2924
2925