os_windows.cpp 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747
  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. #include "os_windows.h"
  31. #include "display_server_windows.h"
  32. #include "joypad_windows.h"
  33. #include "lang_table.h"
  34. #include "windows_terminal_logger.h"
  35. #include "core/debugger/engine_debugger.h"
  36. #include "core/debugger/script_debugger.h"
  37. #include "core/io/marshalls.h"
  38. #include "core/version_generated.gen.h"
  39. #include "drivers/unix/net_socket_posix.h"
  40. #include "drivers/windows/dir_access_windows.h"
  41. #include "drivers/windows/file_access_windows.h"
  42. #include "main/main.h"
  43. #include "servers/audio_server.h"
  44. #include "servers/rendering/rendering_server_default.h"
  45. #include "servers/text_server.h"
  46. #include <avrt.h>
  47. #include <bcrypt.h>
  48. #include <direct.h>
  49. #include <knownfolders.h>
  50. #include <process.h>
  51. #include <psapi.h>
  52. #include <regstr.h>
  53. #include <shlobj.h>
  54. #include <wbemcli.h>
  55. #include <wincrypt.h>
  56. #ifdef DEBUG_ENABLED
  57. #pragma pack(push, before_imagehlp, 8)
  58. #include <imagehlp.h>
  59. #pragma pack(pop, before_imagehlp)
  60. #endif
  61. extern "C" {
  62. __declspec(dllexport) DWORD NvOptimusEnablement = 1;
  63. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  64. }
  65. // Workaround mingw-w64 < 4.0 bug
  66. #ifndef WM_TOUCH
  67. #define WM_TOUCH 576
  68. #endif
  69. #ifndef WM_POINTERUPDATE
  70. #define WM_POINTERUPDATE 0x0245
  71. #endif
  72. // Missing in MinGW headers before 8.0.
  73. #ifndef DWRITE_FONT_WEIGHT_SEMI_LIGHT
  74. #define DWRITE_FONT_WEIGHT_SEMI_LIGHT (DWRITE_FONT_WEIGHT)350
  75. #endif
  76. #if defined(__GNUC__)
  77. // Workaround GCC warning from -Wcast-function-type.
  78. #define GetProcAddress (void *)GetProcAddress
  79. #endif
  80. static String format_error_message(DWORD id) {
  81. LPWSTR messageBuffer = nullptr;
  82. size_t size = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  83. nullptr, id, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&messageBuffer, 0, nullptr);
  84. String msg = "Error " + itos(id) + ": " + String::utf16((const char16_t *)messageBuffer, size);
  85. LocalFree(messageBuffer);
  86. return msg.replace("\r", "").replace("\n", "");
  87. }
  88. void RedirectStream(const char *p_file_name, const char *p_mode, FILE *p_cpp_stream, const DWORD p_std_handle) {
  89. const HANDLE h_existing = GetStdHandle(p_std_handle);
  90. if (h_existing != INVALID_HANDLE_VALUE) { // Redirect only if attached console have a valid handle.
  91. const HANDLE h_cpp = reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(p_cpp_stream)));
  92. if (h_cpp == INVALID_HANDLE_VALUE) { // Redirect only if it's not already redirected to the pipe or file.
  93. FILE *fp = p_cpp_stream;
  94. freopen_s(&fp, p_file_name, p_mode, p_cpp_stream); // Redirect stream.
  95. setvbuf(p_cpp_stream, nullptr, _IONBF, 0); // Disable stream buffering.
  96. }
  97. }
  98. }
  99. void RedirectIOToConsole() {
  100. if (AttachConsole(ATTACH_PARENT_PROCESS)) {
  101. RedirectStream("CONIN$", "r", stdin, STD_INPUT_HANDLE);
  102. RedirectStream("CONOUT$", "w", stdout, STD_OUTPUT_HANDLE);
  103. RedirectStream("CONOUT$", "w", stderr, STD_ERROR_HANDLE);
  104. }
  105. }
  106. BOOL WINAPI HandlerRoutine(_In_ DWORD dwCtrlType) {
  107. if (!EngineDebugger::is_active()) {
  108. return FALSE;
  109. }
  110. switch (dwCtrlType) {
  111. case CTRL_C_EVENT:
  112. EngineDebugger::get_script_debugger()->set_depth(-1);
  113. EngineDebugger::get_script_debugger()->set_lines_left(1);
  114. return TRUE;
  115. default:
  116. return FALSE;
  117. }
  118. }
  119. void OS_Windows::alert(const String &p_alert, const String &p_title) {
  120. MessageBoxW(nullptr, (LPCWSTR)(p_alert.utf16().get_data()), (LPCWSTR)(p_title.utf16().get_data()), MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
  121. }
  122. void OS_Windows::initialize_debugging() {
  123. SetConsoleCtrlHandler(HandlerRoutine, TRUE);
  124. }
  125. #ifdef WINDOWS_DEBUG_OUTPUT_ENABLED
  126. 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) {
  127. String err_str;
  128. if (p_errorexp && p_errorexp[0]) {
  129. err_str = String::utf8(p_errorexp);
  130. } else {
  131. err_str = String::utf8(p_file) + ":" + itos(p_line) + " - " + String::utf8(p_error);
  132. }
  133. if (p_editor_notify) {
  134. err_str += " (User)\n";
  135. } else {
  136. err_str += "\n";
  137. }
  138. OutputDebugStringW((LPCWSTR)err_str.utf16().ptr());
  139. }
  140. #endif
  141. void OS_Windows::initialize() {
  142. crash_handler.initialize();
  143. #ifdef WINDOWS_DEBUG_OUTPUT_ENABLED
  144. error_handlers.errfunc = _error_handler;
  145. error_handlers.userdata = this;
  146. add_error_handler(&error_handlers);
  147. #endif
  148. #ifndef WINDOWS_SUBSYSTEM_CONSOLE
  149. RedirectIOToConsole();
  150. #endif
  151. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_RESOURCES);
  152. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_USERDATA);
  153. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_FILESYSTEM);
  154. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_RESOURCES);
  155. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_USERDATA);
  156. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_FILESYSTEM);
  157. NetSocketPosix::make_default();
  158. // We need to know how often the clock is updated
  159. QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second);
  160. QueryPerformanceCounter((LARGE_INTEGER *)&ticks_start);
  161. // set minimum resolution for periodic timers, otherwise Sleep(n) may wait at least as
  162. // long as the windows scheduler resolution (~16-30ms) even for calls like Sleep(1)
  163. timeBeginPeriod(1);
  164. process_map = memnew((HashMap<ProcessID, ProcessInfo>));
  165. // Add current Godot PID to the list of known PIDs
  166. ProcessInfo current_pi = {};
  167. PROCESS_INFORMATION current_pi_pi = {};
  168. current_pi.pi = current_pi_pi;
  169. current_pi.pi.hProcess = GetCurrentProcess();
  170. process_map->insert(GetCurrentProcessId(), current_pi);
  171. IPUnix::make_default();
  172. main_loop = nullptr;
  173. HRESULT hr = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), reinterpret_cast<IUnknown **>(&dwrite_factory));
  174. if (SUCCEEDED(hr)) {
  175. hr = dwrite_factory->GetSystemFontCollection(&font_collection, false);
  176. if (SUCCEEDED(hr)) {
  177. dwrite_init = true;
  178. hr = dwrite_factory->QueryInterface(&dwrite_factory2);
  179. if (SUCCEEDED(hr)) {
  180. hr = dwrite_factory2->GetSystemFontFallback(&system_font_fallback);
  181. if (SUCCEEDED(hr)) {
  182. dwrite2_init = true;
  183. }
  184. }
  185. }
  186. }
  187. if (!dwrite_init) {
  188. print_verbose("Unable to load IDWriteFactory, system font support is disabled.");
  189. } else if (!dwrite2_init) {
  190. print_verbose("Unable to load IDWriteFactory2, automatic system font fallback is disabled.");
  191. }
  192. FileAccessWindows::initialize();
  193. }
  194. void OS_Windows::delete_main_loop() {
  195. if (main_loop) {
  196. memdelete(main_loop);
  197. }
  198. main_loop = nullptr;
  199. }
  200. void OS_Windows::set_main_loop(MainLoop *p_main_loop) {
  201. main_loop = p_main_loop;
  202. }
  203. void OS_Windows::finalize() {
  204. if (dwrite_factory2) {
  205. dwrite_factory2->Release();
  206. dwrite_factory2 = nullptr;
  207. }
  208. if (font_collection) {
  209. font_collection->Release();
  210. font_collection = nullptr;
  211. }
  212. if (system_font_fallback) {
  213. system_font_fallback->Release();
  214. system_font_fallback = nullptr;
  215. }
  216. if (dwrite_factory) {
  217. dwrite_factory->Release();
  218. dwrite_factory = nullptr;
  219. }
  220. #ifdef WINMIDI_ENABLED
  221. driver_midi.close();
  222. #endif
  223. if (main_loop) {
  224. memdelete(main_loop);
  225. }
  226. main_loop = nullptr;
  227. }
  228. void OS_Windows::finalize_core() {
  229. FileAccessWindows::finalize();
  230. timeEndPeriod(1);
  231. memdelete(process_map);
  232. NetSocketPosix::cleanup();
  233. #ifdef WINDOWS_DEBUG_OUTPUT_ENABLED
  234. remove_error_handler(&error_handlers);
  235. #endif
  236. }
  237. Error OS_Windows::get_entropy(uint8_t *r_buffer, int p_bytes) {
  238. NTSTATUS status = BCryptGenRandom(nullptr, r_buffer, p_bytes, BCRYPT_USE_SYSTEM_PREFERRED_RNG);
  239. ERR_FAIL_COND_V(status, FAILED);
  240. return OK;
  241. }
  242. #ifdef DEBUG_ENABLED
  243. void debug_dynamic_library_check_dependencies(const String &p_root_path, const String &p_path, HashSet<String> &r_checked, HashSet<String> &r_missing) {
  244. if (r_checked.has(p_path)) {
  245. return;
  246. }
  247. r_checked.insert(p_path);
  248. LOADED_IMAGE loaded_image;
  249. HANDLE file = CreateFileW((LPCWSTR)p_path.utf16().get_data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
  250. if (file != INVALID_HANDLE_VALUE) {
  251. HANDLE file_mapping = CreateFileMappingW(file, nullptr, PAGE_READONLY | SEC_COMMIT, 0, 0, nullptr);
  252. if (file_mapping != INVALID_HANDLE_VALUE) {
  253. PVOID mapping = MapViewOfFile(file_mapping, FILE_MAP_READ, 0, 0, 0);
  254. if (mapping) {
  255. PIMAGE_DOS_HEADER dos_header = (PIMAGE_DOS_HEADER)mapping;
  256. PIMAGE_NT_HEADERS nt_header = nullptr;
  257. if (dos_header->e_magic == IMAGE_DOS_SIGNATURE) {
  258. PCHAR nt_header_ptr;
  259. nt_header_ptr = ((PCHAR)mapping) + dos_header->e_lfanew;
  260. nt_header = (PIMAGE_NT_HEADERS)nt_header_ptr;
  261. if (nt_header->Signature != IMAGE_NT_SIGNATURE) {
  262. nt_header = nullptr;
  263. }
  264. }
  265. if (nt_header) {
  266. loaded_image.ModuleName = nullptr;
  267. loaded_image.hFile = file;
  268. loaded_image.MappedAddress = (PUCHAR)mapping;
  269. loaded_image.FileHeader = nt_header;
  270. loaded_image.Sections = (PIMAGE_SECTION_HEADER)((LPBYTE)&nt_header->OptionalHeader + nt_header->FileHeader.SizeOfOptionalHeader);
  271. loaded_image.NumberOfSections = nt_header->FileHeader.NumberOfSections;
  272. loaded_image.SizeOfImage = GetFileSize(file, nullptr);
  273. loaded_image.Characteristics = nt_header->FileHeader.Characteristics;
  274. loaded_image.LastRvaSection = loaded_image.Sections;
  275. loaded_image.fSystemImage = false;
  276. loaded_image.fDOSImage = false;
  277. loaded_image.Links.Flink = &loaded_image.Links;
  278. loaded_image.Links.Blink = &loaded_image.Links;
  279. ULONG size = 0;
  280. const IMAGE_IMPORT_DESCRIPTOR *import_desc = (const IMAGE_IMPORT_DESCRIPTOR *)ImageDirectoryEntryToData((HMODULE)loaded_image.MappedAddress, false, IMAGE_DIRECTORY_ENTRY_IMPORT, &size);
  281. if (import_desc) {
  282. for (; import_desc->Name && import_desc->FirstThunk; import_desc++) {
  283. char16_t full_name_wc[MAX_PATH];
  284. const char *name_cs = (const char *)ImageRvaToVa(loaded_image.FileHeader, loaded_image.MappedAddress, import_desc->Name, 0);
  285. String name = String(name_cs);
  286. if (name.begins_with("api-ms-win-")) {
  287. r_checked.insert(name);
  288. } else if (SearchPathW(nullptr, (LPCWSTR)name.utf16().get_data(), nullptr, MAX_PATH, (LPWSTR)full_name_wc, nullptr)) {
  289. debug_dynamic_library_check_dependencies(p_root_path, String::utf16(full_name_wc), r_checked, r_missing);
  290. } else if (SearchPathW((LPCWSTR)(p_path.get_base_dir().utf16().get_data()), (LPCWSTR)name.utf16().get_data(), nullptr, MAX_PATH, (LPWSTR)full_name_wc, nullptr)) {
  291. debug_dynamic_library_check_dependencies(p_root_path, String::utf16(full_name_wc), r_checked, r_missing);
  292. } else {
  293. r_missing.insert(name);
  294. }
  295. }
  296. }
  297. }
  298. UnmapViewOfFile(mapping);
  299. }
  300. CloseHandle(file_mapping);
  301. }
  302. CloseHandle(file);
  303. }
  304. }
  305. #endif
  306. Error OS_Windows::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path, String *r_resolved_path) {
  307. String path = p_path.replace("/", "\\");
  308. if (!FileAccess::exists(path)) {
  309. //this code exists so gdextension can load .dll files from within the executable path
  310. path = get_executable_path().get_base_dir().path_join(p_path.get_file());
  311. }
  312. typedef DLL_DIRECTORY_COOKIE(WINAPI * PAddDllDirectory)(PCWSTR);
  313. typedef BOOL(WINAPI * PRemoveDllDirectory)(DLL_DIRECTORY_COOKIE);
  314. PAddDllDirectory add_dll_directory = (PAddDllDirectory)GetProcAddress(GetModuleHandle("kernel32.dll"), "AddDllDirectory");
  315. PRemoveDllDirectory remove_dll_directory = (PRemoveDllDirectory)GetProcAddress(GetModuleHandle("kernel32.dll"), "RemoveDllDirectory");
  316. bool has_dll_directory_api = ((add_dll_directory != nullptr) && (remove_dll_directory != nullptr));
  317. DLL_DIRECTORY_COOKIE cookie = nullptr;
  318. if (p_also_set_library_path && has_dll_directory_api) {
  319. cookie = add_dll_directory((LPCWSTR)(path.get_base_dir().utf16().get_data()));
  320. }
  321. p_library_handle = (void *)LoadLibraryExW((LPCWSTR)(path.utf16().get_data()), nullptr, (p_also_set_library_path && has_dll_directory_api) ? LOAD_LIBRARY_SEARCH_DEFAULT_DIRS : 0);
  322. #ifdef DEBUG_ENABLED
  323. if (!p_library_handle) {
  324. DWORD err_code = GetLastError();
  325. HashSet<String> checekd_libs;
  326. HashSet<String> missing_libs;
  327. debug_dynamic_library_check_dependencies(path, path, checekd_libs, missing_libs);
  328. if (!missing_libs.is_empty()) {
  329. String missing;
  330. for (const String &E : missing_libs) {
  331. if (!missing.is_empty()) {
  332. missing += ", ";
  333. }
  334. missing += E;
  335. }
  336. 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)));
  337. } else {
  338. ERR_FAIL_V_MSG(ERR_CANT_OPEN, vformat("Can't open dynamic library: %s. Error: %s.", p_path, format_error_message(err_code)));
  339. }
  340. }
  341. #else
  342. ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, vformat("Can't open dynamic library: %s. Error: %s.", p_path, format_error_message(GetLastError())));
  343. #endif
  344. if (cookie) {
  345. remove_dll_directory(cookie);
  346. }
  347. if (r_resolved_path != nullptr) {
  348. *r_resolved_path = path;
  349. }
  350. return OK;
  351. }
  352. Error OS_Windows::close_dynamic_library(void *p_library_handle) {
  353. if (!FreeLibrary((HMODULE)p_library_handle)) {
  354. return FAILED;
  355. }
  356. return OK;
  357. }
  358. Error OS_Windows::get_dynamic_library_symbol_handle(void *p_library_handle, const String p_name, void *&p_symbol_handle, bool p_optional) {
  359. p_symbol_handle = (void *)GetProcAddress((HMODULE)p_library_handle, p_name.utf8().get_data());
  360. if (!p_symbol_handle) {
  361. if (!p_optional) {
  362. ERR_FAIL_V_MSG(ERR_CANT_RESOLVE, vformat("Can't resolve symbol %s, error: \"%s\".", p_name, format_error_message(GetLastError())));
  363. } else {
  364. return ERR_CANT_RESOLVE;
  365. }
  366. }
  367. return OK;
  368. }
  369. String OS_Windows::get_name() const {
  370. return "Windows";
  371. }
  372. String OS_Windows::get_distribution_name() const {
  373. return get_name();
  374. }
  375. String OS_Windows::get_version() const {
  376. RtlGetVersionPtr version_ptr = (RtlGetVersionPtr)GetProcAddress(GetModuleHandle("ntdll.dll"), "RtlGetVersion");
  377. if (version_ptr != nullptr) {
  378. RTL_OSVERSIONINFOW fow;
  379. ZeroMemory(&fow, sizeof(fow));
  380. fow.dwOSVersionInfoSize = sizeof(fow);
  381. if (version_ptr(&fow) == 0x00000000) {
  382. return vformat("%d.%d.%d", (int64_t)fow.dwMajorVersion, (int64_t)fow.dwMinorVersion, (int64_t)fow.dwBuildNumber);
  383. }
  384. }
  385. return "";
  386. }
  387. Vector<String> OS_Windows::get_video_adapter_driver_info() const {
  388. if (RenderingServer::get_singleton() == nullptr) {
  389. return Vector<String>();
  390. }
  391. static Vector<String> info;
  392. if (!info.is_empty()) {
  393. return info;
  394. }
  395. REFCLSID clsid = CLSID_WbemLocator; // Unmarshaler CLSID
  396. REFIID uuid = IID_IWbemLocator; // Interface UUID
  397. IWbemLocator *wbemLocator = NULL; // to get the services
  398. IWbemServices *wbemServices = NULL; // to get the class
  399. IEnumWbemClassObject *iter = NULL;
  400. IWbemClassObject *pnpSDriverObject[1]; // contains driver name, version, etc.
  401. String driver_name;
  402. String driver_version;
  403. const String device_name = RenderingServer::get_singleton()->get_video_adapter_name();
  404. if (device_name.is_empty()) {
  405. return Vector<String>();
  406. }
  407. HRESULT hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER, uuid, (LPVOID *)&wbemLocator);
  408. if (hr != S_OK) {
  409. return Vector<String>();
  410. }
  411. BSTR resource_name = SysAllocString(L"root\\CIMV2");
  412. hr = wbemLocator->ConnectServer(resource_name, NULL, NULL, NULL, 0, NULL, NULL, &wbemServices);
  413. SysFreeString(resource_name);
  414. SAFE_RELEASE(wbemLocator) // from now on, use `wbemServices`
  415. if (hr != S_OK) {
  416. SAFE_RELEASE(wbemServices)
  417. return Vector<String>();
  418. }
  419. const String gpu_device_class_query = vformat("SELECT * FROM Win32_PnPSignedDriver WHERE DeviceName = \"%s\"", device_name);
  420. BSTR query = SysAllocString((const WCHAR *)gpu_device_class_query.utf16().get_data());
  421. BSTR query_lang = SysAllocString(L"WQL");
  422. hr = wbemServices->ExecQuery(query_lang, query, WBEM_FLAG_RETURN_IMMEDIATELY | WBEM_FLAG_FORWARD_ONLY, NULL, &iter);
  423. SysFreeString(query_lang);
  424. SysFreeString(query);
  425. if (hr == S_OK) {
  426. ULONG resultCount;
  427. hr = iter->Next(5000, 1, pnpSDriverObject, &resultCount); // Get exactly 1. Wait max 5 seconds.
  428. if (hr == S_OK && resultCount > 0) {
  429. VARIANT dn;
  430. VariantInit(&dn);
  431. BSTR object_name = SysAllocString(L"DriverName");
  432. hr = pnpSDriverObject[0]->Get(object_name, 0, &dn, NULL, NULL);
  433. SysFreeString(object_name);
  434. if (hr == S_OK) {
  435. String d_name = String(V_BSTR(&dn));
  436. if (d_name.is_empty()) {
  437. object_name = SysAllocString(L"DriverProviderName");
  438. hr = pnpSDriverObject[0]->Get(object_name, 0, &dn, NULL, NULL);
  439. SysFreeString(object_name);
  440. if (hr == S_OK) {
  441. driver_name = String(V_BSTR(&dn));
  442. }
  443. } else {
  444. driver_name = d_name;
  445. }
  446. } else {
  447. object_name = SysAllocString(L"DriverProviderName");
  448. hr = pnpSDriverObject[0]->Get(object_name, 0, &dn, NULL, NULL);
  449. SysFreeString(object_name);
  450. if (hr == S_OK) {
  451. driver_name = String(V_BSTR(&dn));
  452. }
  453. }
  454. VARIANT dv;
  455. VariantInit(&dv);
  456. object_name = SysAllocString(L"DriverVersion");
  457. hr = pnpSDriverObject[0]->Get(object_name, 0, &dv, NULL, NULL);
  458. SysFreeString(object_name);
  459. if (hr == S_OK) {
  460. driver_version = String(V_BSTR(&dv));
  461. }
  462. for (ULONG i = 0; i < resultCount; i++) {
  463. SAFE_RELEASE(pnpSDriverObject[i])
  464. }
  465. }
  466. }
  467. SAFE_RELEASE(wbemServices)
  468. SAFE_RELEASE(iter)
  469. info.push_back(driver_name);
  470. info.push_back(driver_version);
  471. return info;
  472. }
  473. OS::DateTime OS_Windows::get_datetime(bool p_utc) const {
  474. SYSTEMTIME systemtime;
  475. if (p_utc) {
  476. GetSystemTime(&systemtime);
  477. } else {
  478. GetLocalTime(&systemtime);
  479. }
  480. //Get DST information from Windows, but only if p_utc is false.
  481. TIME_ZONE_INFORMATION info;
  482. bool is_daylight = false;
  483. if (!p_utc && GetTimeZoneInformation(&info) == TIME_ZONE_ID_DAYLIGHT) {
  484. is_daylight = true;
  485. }
  486. DateTime dt;
  487. dt.year = systemtime.wYear;
  488. dt.month = Month(systemtime.wMonth);
  489. dt.day = systemtime.wDay;
  490. dt.weekday = Weekday(systemtime.wDayOfWeek);
  491. dt.hour = systemtime.wHour;
  492. dt.minute = systemtime.wMinute;
  493. dt.second = systemtime.wSecond;
  494. dt.dst = is_daylight;
  495. return dt;
  496. }
  497. OS::TimeZoneInfo OS_Windows::get_time_zone_info() const {
  498. TIME_ZONE_INFORMATION info;
  499. bool is_daylight = false;
  500. if (GetTimeZoneInformation(&info) == TIME_ZONE_ID_DAYLIGHT) {
  501. is_daylight = true;
  502. }
  503. // Daylight Bias needs to be added to the bias if DST is in effect, or else it will not properly update.
  504. TimeZoneInfo ret;
  505. if (is_daylight) {
  506. ret.name = info.DaylightName;
  507. ret.bias = info.Bias + info.DaylightBias;
  508. } else {
  509. ret.name = info.StandardName;
  510. ret.bias = info.Bias + info.StandardBias;
  511. }
  512. // Bias value returned by GetTimeZoneInformation is inverted of what we expect
  513. // For example, on GMT-3 GetTimeZoneInformation return a Bias of 180, so invert the value to get -180
  514. ret.bias = -ret.bias;
  515. return ret;
  516. }
  517. double OS_Windows::get_unix_time() const {
  518. // 1 Windows tick is 100ns
  519. const uint64_t WINDOWS_TICKS_PER_SECOND = 10000000;
  520. const uint64_t TICKS_TO_UNIX_EPOCH = 116444736000000000LL;
  521. SYSTEMTIME st;
  522. GetSystemTime(&st);
  523. FILETIME ft;
  524. SystemTimeToFileTime(&st, &ft);
  525. uint64_t ticks_time;
  526. ticks_time = ft.dwHighDateTime;
  527. ticks_time <<= 32;
  528. ticks_time |= ft.dwLowDateTime;
  529. return (double)(ticks_time - TICKS_TO_UNIX_EPOCH) / WINDOWS_TICKS_PER_SECOND;
  530. }
  531. void OS_Windows::delay_usec(uint32_t p_usec) const {
  532. if (p_usec < 1000) {
  533. Sleep(1);
  534. } else {
  535. Sleep(p_usec / 1000);
  536. }
  537. }
  538. uint64_t OS_Windows::get_ticks_usec() const {
  539. uint64_t ticks;
  540. // This is the number of clock ticks since start
  541. QueryPerformanceCounter((LARGE_INTEGER *)&ticks);
  542. // Subtract the ticks at game start to get
  543. // the ticks since the game started
  544. ticks -= ticks_start;
  545. // Divide by frequency to get the time in seconds
  546. // original calculation shown below is subject to overflow
  547. // with high ticks_per_second and a number of days since the last reboot.
  548. // time = ticks * 1000000L / ticks_per_second;
  549. // we can prevent this by either using 128 bit math
  550. // or separating into a calculation for seconds, and the fraction
  551. uint64_t seconds = ticks / ticks_per_second;
  552. // compiler will optimize these two into one divide
  553. uint64_t leftover = ticks % ticks_per_second;
  554. // remainder
  555. uint64_t time = (leftover * 1000000L) / ticks_per_second;
  556. // seconds
  557. time += seconds * 1000000L;
  558. return time;
  559. }
  560. String OS_Windows::_quote_command_line_argument(const String &p_text) const {
  561. for (int i = 0; i < p_text.size(); i++) {
  562. char32_t c = p_text[i];
  563. if (c == ' ' || c == '&' || c == '(' || c == ')' || c == '[' || c == ']' || c == '{' || c == '}' || c == '^' || c == '=' || c == ';' || c == '!' || c == '\'' || c == '+' || c == ',' || c == '`' || c == '~') {
  564. return "\"" + p_text + "\"";
  565. }
  566. }
  567. return p_text;
  568. }
  569. static void _append_to_pipe(char *p_bytes, int p_size, String *r_pipe, Mutex *p_pipe_mutex) {
  570. // Try to convert from default ANSI code page to Unicode.
  571. LocalVector<wchar_t> wchars;
  572. int total_wchars = MultiByteToWideChar(CP_ACP, 0, p_bytes, p_size, nullptr, 0);
  573. if (total_wchars > 0) {
  574. wchars.resize(total_wchars);
  575. if (MultiByteToWideChar(CP_ACP, 0, p_bytes, p_size, wchars.ptr(), total_wchars) == 0) {
  576. wchars.clear();
  577. }
  578. }
  579. if (p_pipe_mutex) {
  580. p_pipe_mutex->lock();
  581. }
  582. if (wchars.is_empty()) {
  583. // Let's hope it's compatible with UTF-8.
  584. (*r_pipe) += String::utf8(p_bytes, p_size);
  585. } else {
  586. (*r_pipe) += String(wchars.ptr(), total_wchars);
  587. }
  588. if (p_pipe_mutex) {
  589. p_pipe_mutex->unlock();
  590. }
  591. }
  592. Dictionary OS_Windows::get_memory_info() const {
  593. Dictionary meminfo;
  594. meminfo["physical"] = -1;
  595. meminfo["free"] = -1;
  596. meminfo["available"] = -1;
  597. meminfo["stack"] = -1;
  598. PERFORMANCE_INFORMATION pref_info;
  599. pref_info.cb = sizeof(pref_info);
  600. GetPerformanceInfo(&pref_info, sizeof(pref_info));
  601. typedef void(WINAPI * PGetCurrentThreadStackLimits)(PULONG_PTR, PULONG_PTR);
  602. PGetCurrentThreadStackLimits GetCurrentThreadStackLimits = (PGetCurrentThreadStackLimits)GetProcAddress(GetModuleHandleA("kernel32.dll"), "GetCurrentThreadStackLimits");
  603. ULONG_PTR LowLimit = 0;
  604. ULONG_PTR HighLimit = 0;
  605. if (GetCurrentThreadStackLimits) {
  606. GetCurrentThreadStackLimits(&LowLimit, &HighLimit);
  607. }
  608. if (pref_info.PhysicalTotal * pref_info.PageSize != 0) {
  609. meminfo["physical"] = static_cast<int64_t>(pref_info.PhysicalTotal * pref_info.PageSize);
  610. }
  611. if (pref_info.PhysicalAvailable * pref_info.PageSize != 0) {
  612. meminfo["free"] = static_cast<int64_t>(pref_info.PhysicalAvailable * pref_info.PageSize);
  613. }
  614. if (pref_info.CommitLimit * pref_info.PageSize != 0) {
  615. meminfo["available"] = static_cast<int64_t>(pref_info.CommitLimit * pref_info.PageSize);
  616. }
  617. if (HighLimit - LowLimit != 0) {
  618. meminfo["stack"] = static_cast<int64_t>(HighLimit - LowLimit);
  619. }
  620. return meminfo;
  621. }
  622. 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) {
  623. String path = p_path.replace("/", "\\");
  624. String command = _quote_command_line_argument(path);
  625. for (const String &E : p_arguments) {
  626. command += " " + _quote_command_line_argument(E);
  627. }
  628. ProcessInfo pi;
  629. ZeroMemory(&pi.si, sizeof(pi.si));
  630. pi.si.cb = sizeof(pi.si);
  631. ZeroMemory(&pi.pi, sizeof(pi.pi));
  632. LPSTARTUPINFOW si_w = (LPSTARTUPINFOW)&pi.si;
  633. bool inherit_handles = false;
  634. HANDLE pipe[2] = { nullptr, nullptr };
  635. if (r_pipe) {
  636. // Create pipe for StdOut and StdErr.
  637. SECURITY_ATTRIBUTES sa;
  638. sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  639. sa.bInheritHandle = true;
  640. sa.lpSecurityDescriptor = nullptr;
  641. ERR_FAIL_COND_V(!CreatePipe(&pipe[0], &pipe[1], &sa, 0), ERR_CANT_FORK);
  642. ERR_FAIL_COND_V(!SetHandleInformation(pipe[0], HANDLE_FLAG_INHERIT, 0), ERR_CANT_FORK); // Read handle is for host process only and should not be inherited.
  643. pi.si.dwFlags |= STARTF_USESTDHANDLES;
  644. pi.si.hStdOutput = pipe[1];
  645. if (read_stderr) {
  646. pi.si.hStdError = pipe[1];
  647. }
  648. inherit_handles = true;
  649. }
  650. DWORD creation_flags = NORMAL_PRIORITY_CLASS;
  651. if (p_open_console) {
  652. creation_flags |= CREATE_NEW_CONSOLE;
  653. } else {
  654. creation_flags |= CREATE_NO_WINDOW;
  655. }
  656. int ret = CreateProcessW(nullptr, (LPWSTR)(command.utf16().ptrw()), nullptr, nullptr, inherit_handles, creation_flags, nullptr, nullptr, si_w, &pi.pi);
  657. if (!ret && r_pipe) {
  658. CloseHandle(pipe[0]); // Cleanup pipe handles.
  659. CloseHandle(pipe[1]);
  660. }
  661. ERR_FAIL_COND_V_MSG(ret == 0, ERR_CANT_FORK, "Could not create child process: " + command);
  662. if (r_pipe) {
  663. CloseHandle(pipe[1]); // Close pipe write handle (only child process is writing).
  664. LocalVector<char> bytes;
  665. int bytes_in_buffer = 0;
  666. const int CHUNK_SIZE = 4096;
  667. DWORD read = 0;
  668. for (;;) { // Read StdOut and StdErr from pipe.
  669. bytes.resize(bytes_in_buffer + CHUNK_SIZE);
  670. const bool success = ReadFile(pipe[0], bytes.ptr() + bytes_in_buffer, CHUNK_SIZE, &read, NULL);
  671. if (!success || read == 0) {
  672. break;
  673. }
  674. // Assume that all possible encodings are ASCII-compatible.
  675. // Break at newline to allow receiving long output in portions.
  676. int newline_index = -1;
  677. for (int i = read - 1; i >= 0; i--) {
  678. if (bytes[bytes_in_buffer + i] == '\n') {
  679. newline_index = i;
  680. break;
  681. }
  682. }
  683. if (newline_index == -1) {
  684. bytes_in_buffer += read;
  685. continue;
  686. }
  687. const int bytes_to_convert = bytes_in_buffer + (newline_index + 1);
  688. _append_to_pipe(bytes.ptr(), bytes_to_convert, r_pipe, p_pipe_mutex);
  689. bytes_in_buffer = read - (newline_index + 1);
  690. memmove(bytes.ptr(), bytes.ptr() + bytes_to_convert, bytes_in_buffer);
  691. }
  692. if (bytes_in_buffer > 0) {
  693. _append_to_pipe(bytes.ptr(), bytes_in_buffer, r_pipe, p_pipe_mutex);
  694. }
  695. CloseHandle(pipe[0]); // Close pipe read handle.
  696. }
  697. WaitForSingleObject(pi.pi.hProcess, INFINITE);
  698. if (r_exitcode) {
  699. DWORD ret2;
  700. GetExitCodeProcess(pi.pi.hProcess, &ret2);
  701. *r_exitcode = ret2;
  702. }
  703. CloseHandle(pi.pi.hProcess);
  704. CloseHandle(pi.pi.hThread);
  705. return OK;
  706. }
  707. Error OS_Windows::create_process(const String &p_path, const List<String> &p_arguments, ProcessID *r_child_id, bool p_open_console) {
  708. String path = p_path.replace("/", "\\");
  709. String command = _quote_command_line_argument(path);
  710. for (const String &E : p_arguments) {
  711. command += " " + _quote_command_line_argument(E);
  712. }
  713. ProcessInfo pi;
  714. ZeroMemory(&pi.si, sizeof(pi.si));
  715. pi.si.cb = sizeof(pi.si);
  716. ZeroMemory(&pi.pi, sizeof(pi.pi));
  717. LPSTARTUPINFOW si_w = (LPSTARTUPINFOW)&pi.si;
  718. DWORD creation_flags = NORMAL_PRIORITY_CLASS;
  719. if (p_open_console) {
  720. creation_flags |= CREATE_NEW_CONSOLE;
  721. } else {
  722. creation_flags |= CREATE_NO_WINDOW;
  723. }
  724. int ret = CreateProcessW(nullptr, (LPWSTR)(command.utf16().ptrw()), nullptr, nullptr, false, creation_flags, nullptr, nullptr, si_w, &pi.pi);
  725. ERR_FAIL_COND_V_MSG(ret == 0, ERR_CANT_FORK, "Could not create child process: " + command);
  726. ProcessID pid = pi.pi.dwProcessId;
  727. if (r_child_id) {
  728. *r_child_id = pid;
  729. }
  730. process_map->insert(pid, pi);
  731. return OK;
  732. }
  733. Error OS_Windows::kill(const ProcessID &p_pid) {
  734. int ret = 0;
  735. if (process_map->has(p_pid)) {
  736. const PROCESS_INFORMATION pi = (*process_map)[p_pid].pi;
  737. process_map->erase(p_pid);
  738. ret = TerminateProcess(pi.hProcess, 0);
  739. CloseHandle(pi.hProcess);
  740. CloseHandle(pi.hThread);
  741. } else {
  742. HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, false, (DWORD)p_pid);
  743. if (hProcess != NULL) {
  744. ret = TerminateProcess(hProcess, 0);
  745. CloseHandle(hProcess);
  746. }
  747. }
  748. return ret != 0 ? OK : FAILED;
  749. }
  750. int OS_Windows::get_process_id() const {
  751. return _getpid();
  752. }
  753. bool OS_Windows::is_process_running(const ProcessID &p_pid) const {
  754. if (!process_map->has(p_pid)) {
  755. return false;
  756. }
  757. const PROCESS_INFORMATION &pi = (*process_map)[p_pid].pi;
  758. DWORD dw_exit_code = 0;
  759. if (!GetExitCodeProcess(pi.hProcess, &dw_exit_code)) {
  760. return false;
  761. }
  762. if (dw_exit_code != STILL_ACTIVE) {
  763. return false;
  764. }
  765. return true;
  766. }
  767. Error OS_Windows::set_cwd(const String &p_cwd) {
  768. if (_wchdir((LPCWSTR)(p_cwd.utf16().get_data())) != 0) {
  769. return ERR_CANT_OPEN;
  770. }
  771. return OK;
  772. }
  773. Vector<String> OS_Windows::get_system_fonts() const {
  774. if (!dwrite_init) {
  775. return Vector<String>();
  776. }
  777. Vector<String> ret;
  778. HashSet<String> font_names;
  779. UINT32 family_count = font_collection->GetFontFamilyCount();
  780. for (UINT32 i = 0; i < family_count; i++) {
  781. ComAutoreleaseRef<IDWriteFontFamily> family;
  782. HRESULT hr = font_collection->GetFontFamily(i, &family.reference);
  783. ERR_CONTINUE(FAILED(hr) || family.is_null());
  784. ComAutoreleaseRef<IDWriteLocalizedStrings> family_names;
  785. hr = family->GetFamilyNames(&family_names.reference);
  786. ERR_CONTINUE(FAILED(hr) || family_names.is_null());
  787. UINT32 index = 0;
  788. BOOL exists = false;
  789. UINT32 length = 0;
  790. Char16String name;
  791. hr = family_names->FindLocaleName(L"en-us", &index, &exists);
  792. ERR_CONTINUE(FAILED(hr));
  793. hr = family_names->GetStringLength(index, &length);
  794. ERR_CONTINUE(FAILED(hr));
  795. name.resize(length + 1);
  796. hr = family_names->GetString(index, (WCHAR *)name.ptrw(), length + 1);
  797. ERR_CONTINUE(FAILED(hr));
  798. font_names.insert(String::utf16(name.ptr(), length));
  799. }
  800. for (const String &E : font_names) {
  801. ret.push_back(E);
  802. }
  803. return ret;
  804. }
  805. #if defined(__GNUC__) && !defined(__clang__)
  806. #pragma GCC diagnostic push
  807. #pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
  808. #endif
  809. class FallbackTextAnalysisSource : public IDWriteTextAnalysisSource {
  810. LONG _cRef = 1;
  811. bool rtl = false;
  812. Char16String string;
  813. Char16String locale;
  814. IDWriteNumberSubstitution *n_sub = nullptr;
  815. public:
  816. HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID **ppvInterface) override {
  817. if (IID_IUnknown == riid) {
  818. AddRef();
  819. *ppvInterface = (IUnknown *)this;
  820. } else if (__uuidof(IMMNotificationClient) == riid) {
  821. AddRef();
  822. *ppvInterface = (IMMNotificationClient *)this;
  823. } else {
  824. *ppvInterface = nullptr;
  825. return E_NOINTERFACE;
  826. }
  827. return S_OK;
  828. }
  829. ULONG STDMETHODCALLTYPE AddRef() override {
  830. return InterlockedIncrement(&_cRef);
  831. }
  832. ULONG STDMETHODCALLTYPE Release() override {
  833. ULONG ulRef = InterlockedDecrement(&_cRef);
  834. if (0 == ulRef) {
  835. delete this;
  836. }
  837. return ulRef;
  838. }
  839. HRESULT STDMETHODCALLTYPE GetTextAtPosition(UINT32 p_text_position, WCHAR const **r_text_string, UINT32 *r_text_length) override {
  840. if (p_text_position >= (UINT32)string.length()) {
  841. *r_text_string = nullptr;
  842. *r_text_length = 0;
  843. return S_OK;
  844. }
  845. *r_text_string = reinterpret_cast<const wchar_t *>(string.get_data()) + p_text_position;
  846. *r_text_length = string.length() - p_text_position;
  847. return S_OK;
  848. }
  849. HRESULT STDMETHODCALLTYPE GetTextBeforePosition(UINT32 p_text_position, WCHAR const **r_text_string, UINT32 *r_text_length) override {
  850. if (p_text_position < 1 || p_text_position >= (UINT32)string.length()) {
  851. *r_text_string = nullptr;
  852. *r_text_length = 0;
  853. return S_OK;
  854. }
  855. *r_text_string = reinterpret_cast<const wchar_t *>(string.get_data());
  856. *r_text_length = p_text_position;
  857. return S_OK;
  858. }
  859. DWRITE_READING_DIRECTION STDMETHODCALLTYPE GetParagraphReadingDirection() override {
  860. return (rtl) ? DWRITE_READING_DIRECTION_RIGHT_TO_LEFT : DWRITE_READING_DIRECTION_LEFT_TO_RIGHT;
  861. }
  862. HRESULT STDMETHODCALLTYPE GetLocaleName(UINT32 p_text_position, UINT32 *r_text_length, WCHAR const **r_locale_name) override {
  863. *r_locale_name = reinterpret_cast<const wchar_t *>(locale.get_data());
  864. return S_OK;
  865. }
  866. HRESULT STDMETHODCALLTYPE GetNumberSubstitution(UINT32 p_text_position, UINT32 *r_text_length, IDWriteNumberSubstitution **r_number_substitution) override {
  867. *r_number_substitution = n_sub;
  868. return S_OK;
  869. }
  870. FallbackTextAnalysisSource(const Char16String &p_text, const Char16String &p_locale, bool p_rtl, IDWriteNumberSubstitution *p_nsub) {
  871. _cRef = 1;
  872. string = p_text;
  873. locale = p_locale;
  874. n_sub = p_nsub;
  875. rtl = p_rtl;
  876. };
  877. virtual ~FallbackTextAnalysisSource() {}
  878. };
  879. #if defined(__GNUC__) && !defined(__clang__)
  880. #pragma GCC diagnostic pop
  881. #endif
  882. String OS_Windows::_get_default_fontname(const String &p_font_name) const {
  883. String font_name = p_font_name;
  884. if (font_name.to_lower() == "sans-serif") {
  885. font_name = "Arial";
  886. } else if (font_name.to_lower() == "serif") {
  887. font_name = "Times New Roman";
  888. } else if (font_name.to_lower() == "monospace") {
  889. font_name = "Courier New";
  890. } else if (font_name.to_lower() == "cursive") {
  891. font_name = "Comic Sans MS";
  892. } else if (font_name.to_lower() == "fantasy") {
  893. font_name = "Gabriola";
  894. }
  895. return font_name;
  896. }
  897. DWRITE_FONT_WEIGHT OS_Windows::_weight_to_dw(int p_weight) const {
  898. if (p_weight < 150) {
  899. return DWRITE_FONT_WEIGHT_THIN;
  900. } else if (p_weight < 250) {
  901. return DWRITE_FONT_WEIGHT_EXTRA_LIGHT;
  902. } else if (p_weight < 325) {
  903. return DWRITE_FONT_WEIGHT_LIGHT;
  904. } else if (p_weight < 375) {
  905. return DWRITE_FONT_WEIGHT_SEMI_LIGHT;
  906. } else if (p_weight < 450) {
  907. return DWRITE_FONT_WEIGHT_NORMAL;
  908. } else if (p_weight < 550) {
  909. return DWRITE_FONT_WEIGHT_MEDIUM;
  910. } else if (p_weight < 650) {
  911. return DWRITE_FONT_WEIGHT_DEMI_BOLD;
  912. } else if (p_weight < 750) {
  913. return DWRITE_FONT_WEIGHT_BOLD;
  914. } else if (p_weight < 850) {
  915. return DWRITE_FONT_WEIGHT_EXTRA_BOLD;
  916. } else if (p_weight < 925) {
  917. return DWRITE_FONT_WEIGHT_BLACK;
  918. } else {
  919. return DWRITE_FONT_WEIGHT_EXTRA_BLACK;
  920. }
  921. }
  922. DWRITE_FONT_STRETCH OS_Windows::_stretch_to_dw(int p_stretch) const {
  923. if (p_stretch < 56) {
  924. return DWRITE_FONT_STRETCH_ULTRA_CONDENSED;
  925. } else if (p_stretch < 69) {
  926. return DWRITE_FONT_STRETCH_EXTRA_CONDENSED;
  927. } else if (p_stretch < 81) {
  928. return DWRITE_FONT_STRETCH_CONDENSED;
  929. } else if (p_stretch < 93) {
  930. return DWRITE_FONT_STRETCH_SEMI_CONDENSED;
  931. } else if (p_stretch < 106) {
  932. return DWRITE_FONT_STRETCH_NORMAL;
  933. } else if (p_stretch < 137) {
  934. return DWRITE_FONT_STRETCH_SEMI_EXPANDED;
  935. } else if (p_stretch < 144) {
  936. return DWRITE_FONT_STRETCH_EXPANDED;
  937. } else if (p_stretch < 162) {
  938. return DWRITE_FONT_STRETCH_EXTRA_EXPANDED;
  939. } else {
  940. return DWRITE_FONT_STRETCH_ULTRA_EXPANDED;
  941. }
  942. }
  943. 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 {
  944. if (!dwrite2_init) {
  945. return Vector<String>();
  946. }
  947. String font_name = _get_default_fontname(p_font_name);
  948. bool rtl = TS->is_locale_right_to_left(p_locale);
  949. Char16String text = p_text.utf16();
  950. Char16String locale = p_locale.utf16();
  951. ComAutoreleaseRef<IDWriteNumberSubstitution> number_substitution;
  952. HRESULT hr = dwrite_factory->CreateNumberSubstitution(DWRITE_NUMBER_SUBSTITUTION_METHOD_NONE, reinterpret_cast<const wchar_t *>(locale.get_data()), true, &number_substitution.reference);
  953. ERR_FAIL_COND_V(FAILED(hr) || number_substitution.is_null(), Vector<String>());
  954. FallbackTextAnalysisSource fs = FallbackTextAnalysisSource(text, locale, rtl, number_substitution.reference);
  955. UINT32 mapped_length = 0;
  956. FLOAT scale = 0.0;
  957. ComAutoreleaseRef<IDWriteFont> dwrite_font;
  958. hr = system_font_fallback->MapCharacters(
  959. &fs,
  960. 0,
  961. (UINT32)text.length(),
  962. font_collection,
  963. reinterpret_cast<const wchar_t *>(font_name.utf16().get_data()),
  964. _weight_to_dw(p_weight),
  965. p_italic ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL,
  966. _stretch_to_dw(p_stretch),
  967. &mapped_length,
  968. &dwrite_font.reference,
  969. &scale);
  970. if (FAILED(hr) || dwrite_font.is_null()) {
  971. return Vector<String>();
  972. }
  973. ComAutoreleaseRef<IDWriteFontFace> dwrite_face;
  974. hr = dwrite_font->CreateFontFace(&dwrite_face.reference);
  975. if (FAILED(hr) || dwrite_face.is_null()) {
  976. return Vector<String>();
  977. }
  978. UINT32 number_of_files = 0;
  979. hr = dwrite_face->GetFiles(&number_of_files, nullptr);
  980. if (FAILED(hr)) {
  981. return Vector<String>();
  982. }
  983. Vector<ComAutoreleaseRef<IDWriteFontFile>> files;
  984. files.resize(number_of_files);
  985. hr = dwrite_face->GetFiles(&number_of_files, (IDWriteFontFile **)files.ptrw());
  986. if (FAILED(hr)) {
  987. return Vector<String>();
  988. }
  989. Vector<String> ret;
  990. for (UINT32 i = 0; i < number_of_files; i++) {
  991. void const *reference_key = nullptr;
  992. UINT32 reference_key_size = 0;
  993. ComAutoreleaseRef<IDWriteLocalFontFileLoader> loader;
  994. hr = files.write[i]->GetLoader((IDWriteFontFileLoader **)&loader.reference);
  995. if (FAILED(hr) || loader.is_null()) {
  996. continue;
  997. }
  998. hr = files.write[i]->GetReferenceKey(&reference_key, &reference_key_size);
  999. if (FAILED(hr)) {
  1000. continue;
  1001. }
  1002. WCHAR file_path[MAX_PATH];
  1003. hr = loader->GetFilePathFromKey(reference_key, reference_key_size, &file_path[0], MAX_PATH);
  1004. if (FAILED(hr)) {
  1005. continue;
  1006. }
  1007. String fpath = String::utf16((const char16_t *)&file_path[0]);
  1008. WIN32_FIND_DATAW d;
  1009. HANDLE fnd = FindFirstFileW((LPCWSTR)&file_path[0], &d);
  1010. if (fnd != INVALID_HANDLE_VALUE) {
  1011. String fname = String::utf16((const char16_t *)d.cFileName);
  1012. if (!fname.is_empty()) {
  1013. fpath = fpath.get_base_dir().path_join(fname);
  1014. }
  1015. FindClose(fnd);
  1016. }
  1017. ret.push_back(fpath);
  1018. }
  1019. return ret;
  1020. }
  1021. String OS_Windows::get_system_font_path(const String &p_font_name, int p_weight, int p_stretch, bool p_italic) const {
  1022. if (!dwrite_init) {
  1023. return String();
  1024. }
  1025. String font_name = _get_default_fontname(p_font_name);
  1026. UINT32 index = 0;
  1027. BOOL exists = false;
  1028. HRESULT hr = font_collection->FindFamilyName((const WCHAR *)font_name.utf16().get_data(), &index, &exists);
  1029. if (FAILED(hr) || !exists) {
  1030. return String();
  1031. }
  1032. ComAutoreleaseRef<IDWriteFontFamily> family;
  1033. hr = font_collection->GetFontFamily(index, &family.reference);
  1034. if (FAILED(hr) || family.is_null()) {
  1035. return String();
  1036. }
  1037. ComAutoreleaseRef<IDWriteFont> dwrite_font;
  1038. 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);
  1039. if (FAILED(hr) || dwrite_font.is_null()) {
  1040. return String();
  1041. }
  1042. ComAutoreleaseRef<IDWriteFontFace> dwrite_face;
  1043. hr = dwrite_font->CreateFontFace(&dwrite_face.reference);
  1044. if (FAILED(hr) || dwrite_face.is_null()) {
  1045. return String();
  1046. }
  1047. UINT32 number_of_files = 0;
  1048. hr = dwrite_face->GetFiles(&number_of_files, nullptr);
  1049. if (FAILED(hr)) {
  1050. return String();
  1051. }
  1052. Vector<ComAutoreleaseRef<IDWriteFontFile>> files;
  1053. files.resize(number_of_files);
  1054. hr = dwrite_face->GetFiles(&number_of_files, (IDWriteFontFile **)files.ptrw());
  1055. if (FAILED(hr)) {
  1056. return String();
  1057. }
  1058. for (UINT32 i = 0; i < number_of_files; i++) {
  1059. void const *reference_key = nullptr;
  1060. UINT32 reference_key_size = 0;
  1061. ComAutoreleaseRef<IDWriteLocalFontFileLoader> loader;
  1062. hr = files.write[i]->GetLoader((IDWriteFontFileLoader **)&loader.reference);
  1063. if (FAILED(hr) || loader.is_null()) {
  1064. continue;
  1065. }
  1066. hr = files.write[i]->GetReferenceKey(&reference_key, &reference_key_size);
  1067. if (FAILED(hr)) {
  1068. continue;
  1069. }
  1070. WCHAR file_path[MAX_PATH];
  1071. hr = loader->GetFilePathFromKey(reference_key, reference_key_size, &file_path[0], MAX_PATH);
  1072. if (FAILED(hr)) {
  1073. continue;
  1074. }
  1075. String fpath = String::utf16((const char16_t *)&file_path[0]);
  1076. WIN32_FIND_DATAW d;
  1077. HANDLE fnd = FindFirstFileW((LPCWSTR)&file_path[0], &d);
  1078. if (fnd != INVALID_HANDLE_VALUE) {
  1079. String fname = String::utf16((const char16_t *)d.cFileName);
  1080. if (!fname.is_empty()) {
  1081. fpath = fpath.get_base_dir().path_join(fname);
  1082. }
  1083. FindClose(fnd);
  1084. }
  1085. return fpath;
  1086. }
  1087. return String();
  1088. }
  1089. String OS_Windows::get_executable_path() const {
  1090. WCHAR bufname[4096];
  1091. GetModuleFileNameW(nullptr, bufname, 4096);
  1092. String s = String::utf16((const char16_t *)bufname).replace("\\", "/");
  1093. return s;
  1094. }
  1095. bool OS_Windows::has_environment(const String &p_var) const {
  1096. #ifdef MINGW_ENABLED
  1097. return _wgetenv((LPCWSTR)(p_var.utf16().get_data())) != nullptr;
  1098. #else
  1099. WCHAR *env;
  1100. size_t len;
  1101. _wdupenv_s(&env, &len, (LPCWSTR)(p_var.utf16().get_data()));
  1102. const bool has_env = env != nullptr;
  1103. free(env);
  1104. return has_env;
  1105. #endif
  1106. }
  1107. String OS_Windows::get_environment(const String &p_var) const {
  1108. WCHAR wval[0x7fff]; // MSDN says 32767 char is the maximum
  1109. int wlen = GetEnvironmentVariableW((LPCWSTR)(p_var.utf16().get_data()), wval, 0x7fff);
  1110. if (wlen > 0) {
  1111. return String::utf16((const char16_t *)wval);
  1112. }
  1113. return "";
  1114. }
  1115. void OS_Windows::set_environment(const String &p_var, const String &p_value) const {
  1116. ERR_FAIL_COND_MSG(p_var.is_empty() || p_var.contains("="), vformat("Invalid environment variable name '%s', cannot be empty or include '='.", p_var));
  1117. Char16String var = p_var.utf16();
  1118. Char16String value = p_value.utf16();
  1119. ERR_FAIL_COND_MSG(var.length() + value.length() + 2 > 32767, vformat("Invalid definition for environment variable '%s', cannot exceed 32767 characters.", p_var));
  1120. SetEnvironmentVariableW((LPCWSTR)(var.get_data()), (LPCWSTR)(value.get_data()));
  1121. }
  1122. void OS_Windows::unset_environment(const String &p_var) const {
  1123. ERR_FAIL_COND_MSG(p_var.is_empty() || p_var.contains("="), vformat("Invalid environment variable name '%s', cannot be empty or include '='.", p_var));
  1124. SetEnvironmentVariableW((LPCWSTR)(p_var.utf16().get_data()), nullptr); // Null to delete.
  1125. }
  1126. String OS_Windows::get_stdin_string() {
  1127. WCHAR buff[1024];
  1128. DWORD count = 0;
  1129. if (ReadConsoleW(GetStdHandle(STD_INPUT_HANDLE), buff, 1024, &count, nullptr)) {
  1130. return String::utf16((const char16_t *)buff, count);
  1131. }
  1132. return String();
  1133. }
  1134. Error OS_Windows::shell_open(String p_uri) {
  1135. INT_PTR ret = (INT_PTR)ShellExecuteW(nullptr, nullptr, (LPCWSTR)(p_uri.utf16().get_data()), nullptr, nullptr, SW_SHOWNORMAL);
  1136. if (ret > 32) {
  1137. return OK;
  1138. } else {
  1139. switch (ret) {
  1140. case ERROR_FILE_NOT_FOUND:
  1141. case SE_ERR_DLLNOTFOUND:
  1142. return ERR_FILE_NOT_FOUND;
  1143. case ERROR_PATH_NOT_FOUND:
  1144. return ERR_FILE_BAD_PATH;
  1145. case ERROR_BAD_FORMAT:
  1146. return ERR_FILE_CORRUPT;
  1147. case SE_ERR_ACCESSDENIED:
  1148. return ERR_UNAUTHORIZED;
  1149. case 0:
  1150. case SE_ERR_OOM:
  1151. return ERR_OUT_OF_MEMORY;
  1152. default:
  1153. return FAILED;
  1154. }
  1155. }
  1156. }
  1157. Error OS_Windows::shell_show_in_file_manager(String p_path, bool p_open_folder) {
  1158. p_path = p_path.trim_suffix("file://");
  1159. bool open_folder = false;
  1160. if (DirAccess::dir_exists_absolute(p_path) && p_open_folder) {
  1161. open_folder = true;
  1162. }
  1163. if (p_path.begins_with("\"")) {
  1164. p_path = String("\"") + p_path;
  1165. }
  1166. if (p_path.ends_with("\"")) {
  1167. p_path = p_path + String("\"");
  1168. }
  1169. p_path = p_path.replace("/", "\\");
  1170. INT_PTR ret = OK;
  1171. if (open_folder) {
  1172. ret = (INT_PTR)ShellExecuteW(nullptr, nullptr, L"explorer.exe", LPCWSTR(p_path.utf16().get_data()), nullptr, SW_SHOWNORMAL);
  1173. } else {
  1174. ret = (INT_PTR)ShellExecuteW(nullptr, nullptr, L"explorer.exe", LPCWSTR((String("/select,") + p_path).utf16().get_data()), nullptr, SW_SHOWNORMAL);
  1175. }
  1176. if (ret > 32) {
  1177. return OK;
  1178. } else {
  1179. switch (ret) {
  1180. case ERROR_FILE_NOT_FOUND:
  1181. case SE_ERR_DLLNOTFOUND:
  1182. return ERR_FILE_NOT_FOUND;
  1183. case ERROR_PATH_NOT_FOUND:
  1184. return ERR_FILE_BAD_PATH;
  1185. case ERROR_BAD_FORMAT:
  1186. return ERR_FILE_CORRUPT;
  1187. case SE_ERR_ACCESSDENIED:
  1188. return ERR_UNAUTHORIZED;
  1189. case 0:
  1190. case SE_ERR_OOM:
  1191. return ERR_OUT_OF_MEMORY;
  1192. default:
  1193. return FAILED;
  1194. }
  1195. }
  1196. }
  1197. String OS_Windows::get_locale() const {
  1198. const _WinLocale *wl = &_win_locales[0];
  1199. LANGID langid = GetUserDefaultUILanguage();
  1200. String neutral;
  1201. int lang = PRIMARYLANGID(langid);
  1202. int sublang = SUBLANGID(langid);
  1203. while (wl->locale) {
  1204. if (wl->main_lang == lang && wl->sublang == SUBLANG_NEUTRAL) {
  1205. neutral = wl->locale;
  1206. }
  1207. if (lang == wl->main_lang && sublang == wl->sublang) {
  1208. return String(wl->locale).replace("-", "_");
  1209. }
  1210. wl++;
  1211. }
  1212. if (!neutral.is_empty()) {
  1213. return String(neutral).replace("-", "_");
  1214. }
  1215. return "en";
  1216. }
  1217. // We need this because GetSystemInfo() is unreliable on WOW64
  1218. // see https://msdn.microsoft.com/en-us/library/windows/desktop/ms724381(v=vs.85).aspx
  1219. // Taken from MSDN
  1220. typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
  1221. LPFN_ISWOW64PROCESS fnIsWow64Process;
  1222. BOOL is_wow64() {
  1223. BOOL wow64 = FALSE;
  1224. fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process");
  1225. if (fnIsWow64Process) {
  1226. if (!fnIsWow64Process(GetCurrentProcess(), &wow64)) {
  1227. wow64 = FALSE;
  1228. }
  1229. }
  1230. return wow64;
  1231. }
  1232. String OS_Windows::get_processor_name() const {
  1233. const String id = "Hardware\\Description\\System\\CentralProcessor\\0";
  1234. HKEY hkey;
  1235. if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, (LPCWSTR)(id.utf16().get_data()), 0, KEY_QUERY_VALUE, &hkey) != ERROR_SUCCESS) {
  1236. ERR_FAIL_V_MSG("", String("Couldn't get the CPU model name. Returning an empty string."));
  1237. }
  1238. WCHAR buffer[256];
  1239. DWORD buffer_len = 256;
  1240. DWORD vtype = REG_SZ;
  1241. if (RegQueryValueExW(hkey, L"ProcessorNameString", NULL, &vtype, (LPBYTE)buffer, &buffer_len) == ERROR_SUCCESS) {
  1242. RegCloseKey(hkey);
  1243. return String::utf16((const char16_t *)buffer, buffer_len).strip_edges();
  1244. } else {
  1245. RegCloseKey(hkey);
  1246. ERR_FAIL_V_MSG("", String("Couldn't get the CPU model name. Returning an empty string."));
  1247. }
  1248. }
  1249. void OS_Windows::run() {
  1250. if (!main_loop) {
  1251. return;
  1252. }
  1253. main_loop->initialize();
  1254. while (true) {
  1255. DisplayServer::get_singleton()->process_events(); // get rid of pending events
  1256. if (Main::iteration()) {
  1257. break;
  1258. }
  1259. }
  1260. main_loop->finalize();
  1261. }
  1262. MainLoop *OS_Windows::get_main_loop() const {
  1263. return main_loop;
  1264. }
  1265. uint64_t OS_Windows::get_embedded_pck_offset() const {
  1266. Ref<FileAccess> f = FileAccess::open(get_executable_path(), FileAccess::READ);
  1267. if (f.is_null()) {
  1268. return 0;
  1269. }
  1270. // Process header.
  1271. {
  1272. f->seek(0x3c);
  1273. uint32_t pe_pos = f->get_32();
  1274. f->seek(pe_pos);
  1275. uint32_t magic = f->get_32();
  1276. if (magic != 0x00004550) {
  1277. return 0;
  1278. }
  1279. }
  1280. int num_sections;
  1281. {
  1282. int64_t header_pos = f->get_position();
  1283. f->seek(header_pos + 2);
  1284. num_sections = f->get_16();
  1285. f->seek(header_pos + 16);
  1286. uint16_t opt_header_size = f->get_16();
  1287. // Skip rest of header + optional header to go to the section headers.
  1288. f->seek(f->get_position() + 2 + opt_header_size);
  1289. }
  1290. int64_t section_table_pos = f->get_position();
  1291. // Search for the "pck" section.
  1292. int64_t off = 0;
  1293. for (int i = 0; i < num_sections; ++i) {
  1294. int64_t section_header_pos = section_table_pos + i * 40;
  1295. f->seek(section_header_pos);
  1296. uint8_t section_name[9];
  1297. f->get_buffer(section_name, 8);
  1298. section_name[8] = '\0';
  1299. if (strcmp((char *)section_name, "pck") == 0) {
  1300. f->seek(section_header_pos + 20);
  1301. off = f->get_32();
  1302. break;
  1303. }
  1304. }
  1305. return off;
  1306. }
  1307. String OS_Windows::get_config_path() const {
  1308. if (has_environment("APPDATA")) {
  1309. return get_environment("APPDATA").replace("\\", "/");
  1310. }
  1311. return ".";
  1312. }
  1313. String OS_Windows::get_data_path() const {
  1314. return get_config_path();
  1315. }
  1316. String OS_Windows::get_cache_path() const {
  1317. static String cache_path_cache;
  1318. if (cache_path_cache.is_empty()) {
  1319. if (has_environment("LOCALAPPDATA")) {
  1320. cache_path_cache = get_environment("LOCALAPPDATA").replace("\\", "/");
  1321. }
  1322. if (cache_path_cache.is_empty() && has_environment("TEMP")) {
  1323. cache_path_cache = get_environment("TEMP").replace("\\", "/");
  1324. }
  1325. if (cache_path_cache.is_empty()) {
  1326. cache_path_cache = get_config_path();
  1327. }
  1328. }
  1329. return cache_path_cache;
  1330. }
  1331. // Get properly capitalized engine name for system paths
  1332. String OS_Windows::get_godot_dir_name() const {
  1333. return String(VERSION_SHORT_NAME).capitalize();
  1334. }
  1335. String OS_Windows::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  1336. KNOWNFOLDERID id;
  1337. switch (p_dir) {
  1338. case SYSTEM_DIR_DESKTOP: {
  1339. id = FOLDERID_Desktop;
  1340. } break;
  1341. case SYSTEM_DIR_DCIM: {
  1342. id = FOLDERID_Pictures;
  1343. } break;
  1344. case SYSTEM_DIR_DOCUMENTS: {
  1345. id = FOLDERID_Documents;
  1346. } break;
  1347. case SYSTEM_DIR_DOWNLOADS: {
  1348. id = FOLDERID_Downloads;
  1349. } break;
  1350. case SYSTEM_DIR_MOVIES: {
  1351. id = FOLDERID_Videos;
  1352. } break;
  1353. case SYSTEM_DIR_MUSIC: {
  1354. id = FOLDERID_Music;
  1355. } break;
  1356. case SYSTEM_DIR_PICTURES: {
  1357. id = FOLDERID_Pictures;
  1358. } break;
  1359. case SYSTEM_DIR_RINGTONES: {
  1360. id = FOLDERID_Music;
  1361. } break;
  1362. }
  1363. PWSTR szPath;
  1364. HRESULT res = SHGetKnownFolderPath(id, 0, nullptr, &szPath);
  1365. ERR_FAIL_COND_V(res != S_OK, String());
  1366. String path = String::utf16((const char16_t *)szPath).replace("\\", "/");
  1367. CoTaskMemFree(szPath);
  1368. return path;
  1369. }
  1370. String OS_Windows::get_user_data_dir() const {
  1371. String appname = get_safe_dir_name(GLOBAL_GET("application/config/name"));
  1372. if (!appname.is_empty()) {
  1373. bool use_custom_dir = GLOBAL_GET("application/config/use_custom_user_dir");
  1374. if (use_custom_dir) {
  1375. String custom_dir = get_safe_dir_name(GLOBAL_GET("application/config/custom_user_dir_name"), true);
  1376. if (custom_dir.is_empty()) {
  1377. custom_dir = appname;
  1378. }
  1379. return get_data_path().path_join(custom_dir).replace("\\", "/");
  1380. } else {
  1381. return get_data_path().path_join(get_godot_dir_name()).path_join("app_userdata").path_join(appname).replace("\\", "/");
  1382. }
  1383. }
  1384. return get_data_path().path_join(get_godot_dir_name()).path_join("app_userdata").path_join("[unnamed project]");
  1385. }
  1386. String OS_Windows::get_unique_id() const {
  1387. HW_PROFILE_INFOA HwProfInfo;
  1388. ERR_FAIL_COND_V(!GetCurrentHwProfileA(&HwProfInfo), "");
  1389. return String((HwProfInfo.szHwProfileGuid), HW_PROFILE_GUIDLEN);
  1390. }
  1391. bool OS_Windows::_check_internal_feature_support(const String &p_feature) {
  1392. if (p_feature == "system_fonts") {
  1393. return dwrite_init;
  1394. }
  1395. if (p_feature == "pc") {
  1396. return true;
  1397. }
  1398. return false;
  1399. }
  1400. void OS_Windows::disable_crash_handler() {
  1401. crash_handler.disable();
  1402. }
  1403. bool OS_Windows::is_disable_crash_handler() const {
  1404. return crash_handler.is_disabled();
  1405. }
  1406. Error OS_Windows::move_to_trash(const String &p_path) {
  1407. SHFILEOPSTRUCTW sf;
  1408. Char16String utf16 = p_path.utf16();
  1409. WCHAR *from = new WCHAR[utf16.length() + 2];
  1410. wcscpy_s(from, utf16.length() + 1, (LPCWSTR)(utf16.get_data()));
  1411. from[utf16.length() + 1] = 0;
  1412. sf.hwnd = main_window;
  1413. sf.wFunc = FO_DELETE;
  1414. sf.pFrom = from;
  1415. sf.pTo = nullptr;
  1416. sf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;
  1417. sf.fAnyOperationsAborted = FALSE;
  1418. sf.hNameMappings = nullptr;
  1419. sf.lpszProgressTitle = nullptr;
  1420. int ret = SHFileOperationW(&sf);
  1421. delete[] from;
  1422. if (ret) {
  1423. ERR_PRINT("SHFileOperation error: " + itos(ret));
  1424. return FAILED;
  1425. }
  1426. return OK;
  1427. }
  1428. String OS_Windows::get_system_ca_certificates() {
  1429. HCERTSTORE cert_store = CertOpenSystemStoreA(0, "ROOT");
  1430. ERR_FAIL_COND_V_MSG(!cert_store, "", "Failed to read the root certificate store.");
  1431. FILETIME curr_time;
  1432. GetSystemTimeAsFileTime(&curr_time);
  1433. String certs;
  1434. PCCERT_CONTEXT curr = CertEnumCertificatesInStore(cert_store, nullptr);
  1435. while (curr) {
  1436. FILETIME ft;
  1437. DWORD size = sizeof(ft);
  1438. // Check if the certificate is disallowed.
  1439. if (CertGetCertificateContextProperty(curr, CERT_DISALLOWED_FILETIME_PROP_ID, &ft, &size) && CompareFileTime(&curr_time, &ft) != -1) {
  1440. curr = CertEnumCertificatesInStore(cert_store, curr);
  1441. continue;
  1442. }
  1443. // Encode and add to certificate list.
  1444. bool success = CryptBinaryToStringA(curr->pbCertEncoded, curr->cbCertEncoded, CRYPT_STRING_BASE64HEADER | CRYPT_STRING_NOCR, nullptr, &size);
  1445. ERR_CONTINUE(!success);
  1446. PackedByteArray pba;
  1447. pba.resize(size);
  1448. CryptBinaryToStringA(curr->pbCertEncoded, curr->cbCertEncoded, CRYPT_STRING_BASE64HEADER | CRYPT_STRING_NOCR, (char *)pba.ptrw(), &size);
  1449. certs += String((char *)pba.ptr(), size);
  1450. curr = CertEnumCertificatesInStore(cert_store, curr);
  1451. }
  1452. CertCloseStore(cert_store, 0);
  1453. return certs;
  1454. }
  1455. OS_Windows::OS_Windows(HINSTANCE _hInstance) {
  1456. hInstance = _hInstance;
  1457. CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
  1458. #ifdef WASAPI_ENABLED
  1459. AudioDriverManager::add_driver(&driver_wasapi);
  1460. #endif
  1461. #ifdef XAUDIO2_ENABLED
  1462. AudioDriverManager::add_driver(&driver_xaudio2);
  1463. #endif
  1464. DisplayServerWindows::register_windows_driver();
  1465. // Enable ANSI escape code support on Windows 10 v1607 (Anniversary Update) and later.
  1466. // This lets the engine and projects use ANSI escape codes to color text just like on macOS and Linux.
  1467. //
  1468. // NOTE: The engine does not use ANSI escape codes to color error/warning messages; it uses Windows API calls instead.
  1469. // Therefore, error/warning messages are still colored on Windows versions older than 10.
  1470. HANDLE stdoutHandle = GetStdHandle(STD_OUTPUT_HANDLE);
  1471. DWORD outMode = ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING;
  1472. if (!SetConsoleMode(stdoutHandle, outMode)) {
  1473. // Windows 8.1 or below, or Windows 10 prior to Anniversary Update.
  1474. print_verbose("Can't set the ENABLE_VIRTUAL_TERMINAL_PROCESSING Windows console mode. `print_rich()` will not work as expected.");
  1475. }
  1476. Vector<Logger *> loggers;
  1477. loggers.push_back(memnew(WindowsTerminalLogger));
  1478. _set_logger(memnew(CompositeLogger(loggers)));
  1479. }
  1480. OS_Windows::~OS_Windows() {
  1481. CoUninitialize();
  1482. }