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