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