os_windows.cpp 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293
  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 "windows_utils.h"
  36. #include "core/debugger/engine_debugger.h"
  37. #include "core/debugger/script_debugger.h"
  38. #include "core/io/marshalls.h"
  39. #include "core/version_generated.gen.h"
  40. #include "drivers/windows/dir_access_windows.h"
  41. #include "drivers/windows/file_access_windows.h"
  42. #include "drivers/windows/file_access_windows_pipe.h"
  43. #include "drivers/windows/ip_windows.h"
  44. #include "drivers/windows/net_socket_winsock.h"
  45. #include "main/main.h"
  46. #include "servers/audio_server.h"
  47. #include "servers/rendering/rendering_server_default.h"
  48. #include "servers/text_server.h"
  49. #include <avrt.h>
  50. #include <bcrypt.h>
  51. #include <direct.h>
  52. #include <knownfolders.h>
  53. #include <process.h>
  54. #include <psapi.h>
  55. #include <regstr.h>
  56. #include <shlobj.h>
  57. #include <wbemcli.h>
  58. #include <wincrypt.h>
  59. #ifdef DEBUG_ENABLED
  60. #pragma pack(push, before_imagehlp, 8)
  61. #include <imagehlp.h>
  62. #pragma pack(pop, before_imagehlp)
  63. #endif
  64. extern "C" {
  65. __declspec(dllexport) DWORD NvOptimusEnablement = 1;
  66. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  67. __declspec(dllexport) void NoHotPatch() {} // Disable Nahimic code injection.
  68. }
  69. // Workaround mingw-w64 < 4.0 bug
  70. #ifndef WM_TOUCH
  71. #define WM_TOUCH 576
  72. #endif
  73. #ifndef WM_POINTERUPDATE
  74. #define WM_POINTERUPDATE 0x0245
  75. #endif
  76. // Missing in MinGW headers before 8.0.
  77. #ifndef DWRITE_FONT_WEIGHT_SEMI_LIGHT
  78. #define DWRITE_FONT_WEIGHT_SEMI_LIGHT (DWRITE_FONT_WEIGHT)350
  79. #endif
  80. #if defined(__GNUC__)
  81. // Workaround GCC warning from -Wcast-function-type.
  82. #define GetProcAddress (void *)GetProcAddress
  83. #endif
  84. static String fix_path(const String &p_path) {
  85. String path = p_path;
  86. if (p_path.is_relative_path()) {
  87. Char16String current_dir_name;
  88. size_t str_len = GetCurrentDirectoryW(0, nullptr);
  89. current_dir_name.resize(str_len + 1);
  90. GetCurrentDirectoryW(current_dir_name.size(), (LPWSTR)current_dir_name.ptrw());
  91. path = String::utf16((const char16_t *)current_dir_name.get_data()).trim_prefix(R"(\\?\)").replace("\\", "/").path_join(path);
  92. }
  93. path = path.simplify_path();
  94. path = path.replace("/", "\\");
  95. if (path.size() >= MAX_PATH && !path.is_network_share_path() && !path.begins_with(R"(\\?\)")) {
  96. path = R"(\\?\)" + path;
  97. }
  98. return path;
  99. }
  100. static String format_error_message(DWORD id) {
  101. LPWSTR messageBuffer = nullptr;
  102. size_t size = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  103. nullptr, id, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&messageBuffer, 0, nullptr);
  104. String msg = "Error " + itos(id) + ": " + String::utf16((const char16_t *)messageBuffer, size);
  105. LocalFree(messageBuffer);
  106. return msg.replace("\r", "").replace("\n", "");
  107. }
  108. void RedirectStream(const char *p_file_name, const char *p_mode, FILE *p_cpp_stream, const DWORD p_std_handle) {
  109. const HANDLE h_existing = GetStdHandle(p_std_handle);
  110. if (h_existing != INVALID_HANDLE_VALUE) { // Redirect only if attached console have a valid handle.
  111. const HANDLE h_cpp = reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(p_cpp_stream)));
  112. if (h_cpp == INVALID_HANDLE_VALUE) { // Redirect only if it's not already redirected to the pipe or file.
  113. FILE *fp = p_cpp_stream;
  114. freopen_s(&fp, p_file_name, p_mode, p_cpp_stream); // Redirect stream.
  115. setvbuf(p_cpp_stream, nullptr, _IONBF, 0); // Disable stream buffering.
  116. }
  117. }
  118. }
  119. void RedirectIOToConsole() {
  120. // Save current handles.
  121. HANDLE h_stdin = GetStdHandle(STD_INPUT_HANDLE);
  122. HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
  123. HANDLE h_stderr = GetStdHandle(STD_ERROR_HANDLE);
  124. if (AttachConsole(ATTACH_PARENT_PROCESS)) {
  125. // Restore redirection (Note: if not redirected it's NULL handles not INVALID_HANDLE_VALUE).
  126. if (h_stdin != nullptr) {
  127. SetStdHandle(STD_INPUT_HANDLE, h_stdin);
  128. }
  129. if (h_stdout != nullptr) {
  130. SetStdHandle(STD_OUTPUT_HANDLE, h_stdout);
  131. }
  132. if (h_stderr != nullptr) {
  133. SetStdHandle(STD_ERROR_HANDLE, h_stderr);
  134. }
  135. // Update file handles.
  136. RedirectStream("CONIN$", "r", stdin, STD_INPUT_HANDLE);
  137. RedirectStream("CONOUT$", "w", stdout, STD_OUTPUT_HANDLE);
  138. RedirectStream("CONOUT$", "w", stderr, STD_ERROR_HANDLE);
  139. }
  140. }
  141. bool OS_Windows::is_using_con_wrapper() const {
  142. static String exe_renames[] = {
  143. ".console.exe",
  144. "_console.exe",
  145. " console.exe",
  146. "console.exe",
  147. String(),
  148. };
  149. bool found_exe = false;
  150. bool found_conwrap_exe = false;
  151. String exe_name = get_executable_path().to_lower();
  152. String exe_dir = exe_name.get_base_dir();
  153. String exe_fname = exe_name.get_file().get_basename();
  154. DWORD pids[256];
  155. DWORD count = GetConsoleProcessList(&pids[0], 256);
  156. for (DWORD i = 0; i < count; i++) {
  157. HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pids[i]);
  158. if (process != NULL) {
  159. WCHAR proc_name[MAX_PATH];
  160. DWORD len = MAX_PATH;
  161. if (QueryFullProcessImageNameW(process, 0, &proc_name[0], &len)) {
  162. String name = String::utf16((const char16_t *)&proc_name[0], len).replace("\\", "/").to_lower();
  163. if (name == exe_name) {
  164. found_exe = true;
  165. }
  166. for (int j = 0; !exe_renames[j].is_empty(); j++) {
  167. if (name == exe_dir.path_join(exe_fname + exe_renames[j])) {
  168. found_conwrap_exe = true;
  169. }
  170. }
  171. }
  172. CloseHandle(process);
  173. if (found_conwrap_exe && found_exe) {
  174. break;
  175. }
  176. }
  177. }
  178. if (!found_exe) {
  179. return true; // Unable to read console info, assume true.
  180. }
  181. return found_conwrap_exe;
  182. }
  183. BOOL WINAPI HandlerRoutine(_In_ DWORD dwCtrlType) {
  184. if (!EngineDebugger::is_active()) {
  185. return FALSE;
  186. }
  187. switch (dwCtrlType) {
  188. case CTRL_C_EVENT:
  189. EngineDebugger::get_script_debugger()->set_depth(-1);
  190. EngineDebugger::get_script_debugger()->set_lines_left(1);
  191. return TRUE;
  192. default:
  193. return FALSE;
  194. }
  195. }
  196. void OS_Windows::alert(const String &p_alert, const String &p_title) {
  197. MessageBoxW(nullptr, (LPCWSTR)(p_alert.utf16().get_data()), (LPCWSTR)(p_title.utf16().get_data()), MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
  198. }
  199. void OS_Windows::initialize_debugging() {
  200. SetConsoleCtrlHandler(HandlerRoutine, TRUE);
  201. }
  202. #ifdef WINDOWS_DEBUG_OUTPUT_ENABLED
  203. 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) {
  204. String err_str;
  205. if (p_errorexp && p_errorexp[0]) {
  206. err_str = String::utf8(p_errorexp) + "\n";
  207. } else {
  208. err_str = String::utf8(p_file) + ":" + itos(p_line) + " - " + String::utf8(p_error) + "\n";
  209. }
  210. OutputDebugStringW((LPCWSTR)err_str.utf16().ptr());
  211. }
  212. #endif
  213. void OS_Windows::initialize() {
  214. crash_handler.initialize();
  215. #ifdef WINDOWS_DEBUG_OUTPUT_ENABLED
  216. error_handlers.errfunc = _error_handler;
  217. error_handlers.userdata = this;
  218. add_error_handler(&error_handlers);
  219. #endif
  220. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_RESOURCES);
  221. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_USERDATA);
  222. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_FILESYSTEM);
  223. FileAccess::make_default<FileAccessWindowsPipe>(FileAccess::ACCESS_PIPE);
  224. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_RESOURCES);
  225. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_USERDATA);
  226. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_FILESYSTEM);
  227. NetSocketWinSock::make_default();
  228. // We need to know how often the clock is updated
  229. QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second);
  230. QueryPerformanceCounter((LARGE_INTEGER *)&ticks_start);
  231. // set minimum resolution for periodic timers, otherwise Sleep(n) may wait at least as
  232. // long as the windows scheduler resolution (~16-30ms) even for calls like Sleep(1)
  233. timeBeginPeriod(1);
  234. process_map = memnew((HashMap<ProcessID, ProcessInfo>));
  235. // Add current Godot PID to the list of known PIDs
  236. ProcessInfo current_pi = {};
  237. PROCESS_INFORMATION current_pi_pi = {};
  238. current_pi.pi = current_pi_pi;
  239. current_pi.pi.hProcess = GetCurrentProcess();
  240. process_map->insert(GetCurrentProcessId(), current_pi);
  241. IPWindows::make_default();
  242. main_loop = nullptr;
  243. HRESULT hr = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), reinterpret_cast<IUnknown **>(&dwrite_factory));
  244. if (SUCCEEDED(hr)) {
  245. hr = dwrite_factory->GetSystemFontCollection(&font_collection, false);
  246. if (SUCCEEDED(hr)) {
  247. dwrite_init = true;
  248. hr = dwrite_factory->QueryInterface(&dwrite_factory2);
  249. if (SUCCEEDED(hr)) {
  250. hr = dwrite_factory2->GetSystemFontFallback(&system_font_fallback);
  251. if (SUCCEEDED(hr)) {
  252. dwrite2_init = true;
  253. }
  254. }
  255. }
  256. }
  257. if (!dwrite_init) {
  258. print_verbose("Unable to load IDWriteFactory, system font support is disabled.");
  259. } else if (!dwrite2_init) {
  260. print_verbose("Unable to load IDWriteFactory2, automatic system font fallback is disabled.");
  261. }
  262. FileAccessWindows::initialize();
  263. }
  264. void OS_Windows::delete_main_loop() {
  265. if (main_loop) {
  266. memdelete(main_loop);
  267. }
  268. main_loop = nullptr;
  269. }
  270. void OS_Windows::set_main_loop(MainLoop *p_main_loop) {
  271. main_loop = p_main_loop;
  272. }
  273. void OS_Windows::finalize() {
  274. if (dwrite_factory2) {
  275. dwrite_factory2->Release();
  276. dwrite_factory2 = nullptr;
  277. }
  278. if (font_collection) {
  279. font_collection->Release();
  280. font_collection = nullptr;
  281. }
  282. if (system_font_fallback) {
  283. system_font_fallback->Release();
  284. system_font_fallback = nullptr;
  285. }
  286. if (dwrite_factory) {
  287. dwrite_factory->Release();
  288. dwrite_factory = nullptr;
  289. }
  290. #ifdef WINMIDI_ENABLED
  291. driver_midi.close();
  292. #endif
  293. if (main_loop) {
  294. memdelete(main_loop);
  295. }
  296. main_loop = nullptr;
  297. }
  298. void OS_Windows::finalize_core() {
  299. while (!temp_libraries.is_empty()) {
  300. _remove_temp_library(temp_libraries.last()->key);
  301. }
  302. FileAccessWindows::finalize();
  303. timeEndPeriod(1);
  304. memdelete(process_map);
  305. NetSocketWinSock::cleanup();
  306. #ifdef WINDOWS_DEBUG_OUTPUT_ENABLED
  307. remove_error_handler(&error_handlers);
  308. #endif
  309. }
  310. Error OS_Windows::get_entropy(uint8_t *r_buffer, int p_bytes) {
  311. NTSTATUS status = BCryptGenRandom(nullptr, r_buffer, p_bytes, BCRYPT_USE_SYSTEM_PREFERRED_RNG);
  312. ERR_FAIL_COND_V(status, FAILED);
  313. return OK;
  314. }
  315. #ifdef DEBUG_ENABLED
  316. void debug_dynamic_library_check_dependencies(const String &p_path, HashSet<String> &r_checked, HashSet<String> &r_missing) {
  317. if (r_checked.has(p_path)) {
  318. return;
  319. }
  320. r_checked.insert(p_path);
  321. LOADED_IMAGE loaded_image;
  322. HANDLE file = CreateFileW((LPCWSTR)p_path.utf16().get_data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
  323. if (file != INVALID_HANDLE_VALUE) {
  324. HANDLE file_mapping = CreateFileMappingW(file, nullptr, PAGE_READONLY | SEC_COMMIT, 0, 0, nullptr);
  325. if (file_mapping != INVALID_HANDLE_VALUE) {
  326. PVOID mapping = MapViewOfFile(file_mapping, FILE_MAP_READ, 0, 0, 0);
  327. if (mapping) {
  328. PIMAGE_DOS_HEADER dos_header = (PIMAGE_DOS_HEADER)mapping;
  329. PIMAGE_NT_HEADERS nt_header = nullptr;
  330. if (dos_header->e_magic == IMAGE_DOS_SIGNATURE) {
  331. PCHAR nt_header_ptr;
  332. nt_header_ptr = ((PCHAR)mapping) + dos_header->e_lfanew;
  333. nt_header = (PIMAGE_NT_HEADERS)nt_header_ptr;
  334. if (nt_header->Signature != IMAGE_NT_SIGNATURE) {
  335. nt_header = nullptr;
  336. }
  337. }
  338. if (nt_header) {
  339. loaded_image.ModuleName = nullptr;
  340. loaded_image.hFile = file;
  341. loaded_image.MappedAddress = (PUCHAR)mapping;
  342. loaded_image.FileHeader = nt_header;
  343. loaded_image.Sections = (PIMAGE_SECTION_HEADER)((LPBYTE)&nt_header->OptionalHeader + nt_header->FileHeader.SizeOfOptionalHeader);
  344. loaded_image.NumberOfSections = nt_header->FileHeader.NumberOfSections;
  345. loaded_image.SizeOfImage = GetFileSize(file, nullptr);
  346. loaded_image.Characteristics = nt_header->FileHeader.Characteristics;
  347. loaded_image.LastRvaSection = loaded_image.Sections;
  348. loaded_image.fSystemImage = false;
  349. loaded_image.fDOSImage = false;
  350. loaded_image.Links.Flink = &loaded_image.Links;
  351. loaded_image.Links.Blink = &loaded_image.Links;
  352. ULONG size = 0;
  353. const IMAGE_IMPORT_DESCRIPTOR *import_desc = (const IMAGE_IMPORT_DESCRIPTOR *)ImageDirectoryEntryToData((HMODULE)loaded_image.MappedAddress, false, IMAGE_DIRECTORY_ENTRY_IMPORT, &size);
  354. if (import_desc) {
  355. for (; import_desc->Name && import_desc->FirstThunk; import_desc++) {
  356. char16_t full_name_wc[32767];
  357. const char *name_cs = (const char *)ImageRvaToVa(loaded_image.FileHeader, loaded_image.MappedAddress, import_desc->Name, nullptr);
  358. String name = String(name_cs);
  359. if (name.begins_with("api-ms-win-")) {
  360. r_checked.insert(name);
  361. } else if (SearchPathW(nullptr, (LPCWSTR)name.utf16().get_data(), nullptr, 32767, (LPWSTR)full_name_wc, nullptr)) {
  362. debug_dynamic_library_check_dependencies(String::utf16(full_name_wc), r_checked, r_missing);
  363. } else if (SearchPathW((LPCWSTR)(p_path.get_base_dir().utf16().get_data()), (LPCWSTR)name.utf16().get_data(), nullptr, 32767, (LPWSTR)full_name_wc, nullptr)) {
  364. debug_dynamic_library_check_dependencies(String::utf16(full_name_wc), r_checked, r_missing);
  365. } else {
  366. r_missing.insert(name);
  367. }
  368. }
  369. }
  370. }
  371. UnmapViewOfFile(mapping);
  372. }
  373. CloseHandle(file_mapping);
  374. }
  375. CloseHandle(file);
  376. }
  377. }
  378. #endif
  379. Error OS_Windows::open_dynamic_library(const String &p_path, void *&p_library_handle, GDExtensionData *p_data) {
  380. String path = p_path;
  381. if (!FileAccess::exists(path)) {
  382. //this code exists so gdextension can load .dll files from within the executable path
  383. path = get_executable_path().get_base_dir().path_join(p_path.get_file());
  384. }
  385. // Path to load from may be different from original if we make copies.
  386. String load_path = path;
  387. ERR_FAIL_COND_V(!FileAccess::exists(path), ERR_FILE_NOT_FOUND);
  388. // Here we want a copy to be loaded.
  389. // This is so the original file isn't locked and can be updated by a compiler.
  390. if (p_data != nullptr && p_data->generate_temp_files) {
  391. // Copy the file to the same directory as the original with a prefix in the name.
  392. // This is so relative path to dependencies are satisfied.
  393. load_path = path.get_base_dir().path_join("~" + path.get_file());
  394. // If there's a left-over copy (possibly from a crash) then delete it first.
  395. if (FileAccess::exists(load_path)) {
  396. DirAccess::remove_absolute(load_path);
  397. }
  398. Error copy_err = DirAccess::copy_absolute(path, load_path);
  399. if (copy_err) {
  400. ERR_PRINT("Error copying library: " + path);
  401. return ERR_CANT_CREATE;
  402. }
  403. FileAccess::set_hidden_attribute(load_path, true);
  404. Error pdb_err = WindowsUtils::copy_and_rename_pdb(load_path);
  405. if (pdb_err != OK && pdb_err != ERR_SKIP) {
  406. WARN_PRINT(vformat("Failed to rename the PDB file. The original PDB file for '%s' will be loaded.", path));
  407. }
  408. }
  409. typedef DLL_DIRECTORY_COOKIE(WINAPI * PAddDllDirectory)(PCWSTR);
  410. typedef BOOL(WINAPI * PRemoveDllDirectory)(DLL_DIRECTORY_COOKIE);
  411. PAddDllDirectory add_dll_directory = (PAddDllDirectory)GetProcAddress(GetModuleHandle("kernel32.dll"), "AddDllDirectory");
  412. PRemoveDllDirectory remove_dll_directory = (PRemoveDllDirectory)GetProcAddress(GetModuleHandle("kernel32.dll"), "RemoveDllDirectory");
  413. bool has_dll_directory_api = ((add_dll_directory != nullptr) && (remove_dll_directory != nullptr));
  414. DLL_DIRECTORY_COOKIE cookie = nullptr;
  415. String dll_path = fix_path(load_path);
  416. String dll_dir = fix_path(ProjectSettings::get_singleton()->globalize_path(load_path.get_base_dir()));
  417. if (p_data != nullptr && p_data->also_set_library_path && has_dll_directory_api) {
  418. cookie = add_dll_directory((LPCWSTR)(dll_dir.utf16().get_data()));
  419. }
  420. p_library_handle = (void *)LoadLibraryExW((LPCWSTR)(dll_path.utf16().get_data()), nullptr, (p_data != nullptr && p_data->also_set_library_path && has_dll_directory_api) ? LOAD_LIBRARY_SEARCH_DEFAULT_DIRS : 0);
  421. if (!p_library_handle) {
  422. if (p_data != nullptr && p_data->generate_temp_files) {
  423. DirAccess::remove_absolute(load_path);
  424. }
  425. #ifdef DEBUG_ENABLED
  426. DWORD err_code = GetLastError();
  427. HashSet<String> checked_libs;
  428. HashSet<String> missing_libs;
  429. debug_dynamic_library_check_dependencies(dll_path, checked_libs, missing_libs);
  430. if (!missing_libs.is_empty()) {
  431. String missing;
  432. for (const String &E : missing_libs) {
  433. if (!missing.is_empty()) {
  434. missing += ", ";
  435. }
  436. missing += E;
  437. }
  438. 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)));
  439. } else {
  440. ERR_FAIL_V_MSG(ERR_CANT_OPEN, vformat("Can't open dynamic library: %s. Error: %s.", p_path, format_error_message(err_code)));
  441. }
  442. #endif
  443. }
  444. #ifndef DEBUG_ENABLED
  445. 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())));
  446. #endif
  447. if (cookie) {
  448. remove_dll_directory(cookie);
  449. }
  450. if (p_data != nullptr && p_data->r_resolved_path != nullptr) {
  451. *p_data->r_resolved_path = path;
  452. }
  453. if (p_data != nullptr && p_data->generate_temp_files) {
  454. // Save the copied path so it can be deleted later.
  455. temp_libraries[p_library_handle] = load_path;
  456. }
  457. return OK;
  458. }
  459. Error OS_Windows::close_dynamic_library(void *p_library_handle) {
  460. if (!FreeLibrary((HMODULE)p_library_handle)) {
  461. return FAILED;
  462. }
  463. // Delete temporary copy of library if it exists.
  464. _remove_temp_library(p_library_handle);
  465. return OK;
  466. }
  467. void OS_Windows::_remove_temp_library(void *p_library_handle) {
  468. if (temp_libraries.has(p_library_handle)) {
  469. String path = temp_libraries[p_library_handle];
  470. DirAccess::remove_absolute(path);
  471. WindowsUtils::remove_temp_pdbs(path);
  472. temp_libraries.erase(p_library_handle);
  473. }
  474. }
  475. Error OS_Windows::get_dynamic_library_symbol_handle(void *p_library_handle, const String &p_name, void *&p_symbol_handle, bool p_optional) {
  476. p_symbol_handle = (void *)GetProcAddress((HMODULE)p_library_handle, p_name.utf8().get_data());
  477. if (!p_symbol_handle) {
  478. if (!p_optional) {
  479. ERR_FAIL_V_MSG(ERR_CANT_RESOLVE, vformat("Can't resolve symbol %s, error: \"%s\".", p_name, format_error_message(GetLastError())));
  480. } else {
  481. return ERR_CANT_RESOLVE;
  482. }
  483. }
  484. return OK;
  485. }
  486. String OS_Windows::get_name() const {
  487. return "Windows";
  488. }
  489. String OS_Windows::get_distribution_name() const {
  490. return get_name();
  491. }
  492. String OS_Windows::get_version() const {
  493. RtlGetVersionPtr version_ptr = (RtlGetVersionPtr)GetProcAddress(GetModuleHandle("ntdll.dll"), "RtlGetVersion");
  494. if (version_ptr != nullptr) {
  495. RTL_OSVERSIONINFOW fow;
  496. ZeroMemory(&fow, sizeof(fow));
  497. fow.dwOSVersionInfoSize = sizeof(fow);
  498. if (version_ptr(&fow) == 0x00000000) {
  499. return vformat("%d.%d.%d", (int64_t)fow.dwMajorVersion, (int64_t)fow.dwMinorVersion, (int64_t)fow.dwBuildNumber);
  500. }
  501. }
  502. return "";
  503. }
  504. Vector<String> OS_Windows::get_video_adapter_driver_info() const {
  505. if (RenderingServer::get_singleton() == nullptr) {
  506. return Vector<String>();
  507. }
  508. static Vector<String> info;
  509. if (!info.is_empty()) {
  510. return info;
  511. }
  512. REFCLSID clsid = CLSID_WbemLocator; // Unmarshaler CLSID
  513. REFIID uuid = IID_IWbemLocator; // Interface UUID
  514. IWbemLocator *wbemLocator = nullptr; // to get the services
  515. IWbemServices *wbemServices = nullptr; // to get the class
  516. IEnumWbemClassObject *iter = nullptr;
  517. IWbemClassObject *pnpSDriverObject[1]; // contains driver name, version, etc.
  518. String driver_name;
  519. String driver_version;
  520. const String device_name = RenderingServer::get_singleton()->get_video_adapter_name();
  521. if (device_name.is_empty()) {
  522. return Vector<String>();
  523. }
  524. HRESULT hr = CoCreateInstance(clsid, nullptr, CLSCTX_INPROC_SERVER, uuid, (LPVOID *)&wbemLocator);
  525. if (hr != S_OK) {
  526. return Vector<String>();
  527. }
  528. BSTR resource_name = SysAllocString(L"root\\CIMV2");
  529. hr = wbemLocator->ConnectServer(resource_name, nullptr, nullptr, nullptr, 0, nullptr, nullptr, &wbemServices);
  530. SysFreeString(resource_name);
  531. SAFE_RELEASE(wbemLocator) // from now on, use `wbemServices`
  532. if (hr != S_OK) {
  533. SAFE_RELEASE(wbemServices)
  534. return Vector<String>();
  535. }
  536. const String gpu_device_class_query = vformat("SELECT * FROM Win32_PnPSignedDriver WHERE DeviceName = \"%s\"", device_name);
  537. BSTR query = SysAllocString((const WCHAR *)gpu_device_class_query.utf16().get_data());
  538. BSTR query_lang = SysAllocString(L"WQL");
  539. hr = wbemServices->ExecQuery(query_lang, query, WBEM_FLAG_RETURN_IMMEDIATELY | WBEM_FLAG_FORWARD_ONLY, nullptr, &iter);
  540. SysFreeString(query_lang);
  541. SysFreeString(query);
  542. if (hr == S_OK) {
  543. ULONG resultCount;
  544. hr = iter->Next(5000, 1, pnpSDriverObject, &resultCount); // Get exactly 1. Wait max 5 seconds.
  545. if (hr == S_OK && resultCount > 0) {
  546. VARIANT dn;
  547. VariantInit(&dn);
  548. BSTR object_name = SysAllocString(L"DriverName");
  549. hr = pnpSDriverObject[0]->Get(object_name, 0, &dn, nullptr, nullptr);
  550. SysFreeString(object_name);
  551. if (hr == S_OK) {
  552. String d_name = String(V_BSTR(&dn));
  553. if (d_name.is_empty()) {
  554. object_name = SysAllocString(L"DriverProviderName");
  555. hr = pnpSDriverObject[0]->Get(object_name, 0, &dn, nullptr, nullptr);
  556. SysFreeString(object_name);
  557. if (hr == S_OK) {
  558. driver_name = String(V_BSTR(&dn));
  559. }
  560. } else {
  561. driver_name = d_name;
  562. }
  563. } else {
  564. object_name = SysAllocString(L"DriverProviderName");
  565. hr = pnpSDriverObject[0]->Get(object_name, 0, &dn, nullptr, nullptr);
  566. SysFreeString(object_name);
  567. if (hr == S_OK) {
  568. driver_name = String(V_BSTR(&dn));
  569. }
  570. }
  571. VARIANT dv;
  572. VariantInit(&dv);
  573. object_name = SysAllocString(L"DriverVersion");
  574. hr = pnpSDriverObject[0]->Get(object_name, 0, &dv, nullptr, nullptr);
  575. SysFreeString(object_name);
  576. if (hr == S_OK) {
  577. driver_version = String(V_BSTR(&dv));
  578. }
  579. for (ULONG i = 0; i < resultCount; i++) {
  580. SAFE_RELEASE(pnpSDriverObject[i])
  581. }
  582. }
  583. }
  584. SAFE_RELEASE(wbemServices)
  585. SAFE_RELEASE(iter)
  586. info.push_back(driver_name);
  587. info.push_back(driver_version);
  588. return info;
  589. }
  590. bool OS_Windows::get_user_prefers_integrated_gpu() const {
  591. // On Windows 10, the preferred GPU configured in Windows Settings is
  592. // stored in the registry under the key
  593. // `HKEY_CURRENT_USER\SOFTWARE\Microsoft\DirectX\UserGpuPreferences`
  594. // with the name being the app ID or EXE path. The value is in the form of
  595. // `GpuPreference=1;`, with the value being 1 for integrated GPU and 2
  596. // for discrete GPU. On Windows 11, there may be more flags, separated
  597. // by semicolons.
  598. // If this is a packaged app, use the "application user model ID".
  599. // Otherwise, use the EXE path.
  600. WCHAR value_name[32768];
  601. bool is_packaged = false;
  602. {
  603. HMODULE kernel32 = GetModuleHandleW(L"kernel32.dll");
  604. if (kernel32) {
  605. using GetCurrentApplicationUserModelIdPtr = LONG(WINAPI *)(UINT32 * length, PWSTR id);
  606. GetCurrentApplicationUserModelIdPtr GetCurrentApplicationUserModelId = (GetCurrentApplicationUserModelIdPtr)GetProcAddress(kernel32, "GetCurrentApplicationUserModelId");
  607. if (GetCurrentApplicationUserModelId) {
  608. UINT32 length = sizeof(value_name) / sizeof(value_name[0]);
  609. LONG result = GetCurrentApplicationUserModelId(&length, value_name);
  610. if (result == ERROR_SUCCESS) {
  611. is_packaged = true;
  612. }
  613. }
  614. }
  615. }
  616. if (!is_packaged && GetModuleFileNameW(nullptr, value_name, sizeof(value_name) / sizeof(value_name[0])) >= sizeof(value_name) / sizeof(value_name[0])) {
  617. // Paths should never be longer than 32767, but just in case.
  618. return false;
  619. }
  620. LPCWSTR subkey = L"SOFTWARE\\Microsoft\\DirectX\\UserGpuPreferences";
  621. HKEY hkey = nullptr;
  622. LSTATUS result = RegOpenKeyExW(HKEY_CURRENT_USER, subkey, 0, KEY_READ, &hkey);
  623. if (result != ERROR_SUCCESS) {
  624. return false;
  625. }
  626. DWORD size = 0;
  627. result = RegGetValueW(hkey, nullptr, value_name, RRF_RT_REG_SZ, nullptr, nullptr, &size);
  628. if (result != ERROR_SUCCESS || size == 0) {
  629. RegCloseKey(hkey);
  630. return false;
  631. }
  632. Vector<WCHAR> buffer;
  633. buffer.resize(size / sizeof(WCHAR));
  634. result = RegGetValueW(hkey, nullptr, value_name, RRF_RT_REG_SZ, nullptr, (LPBYTE)buffer.ptrw(), &size);
  635. if (result != ERROR_SUCCESS) {
  636. RegCloseKey(hkey);
  637. return false;
  638. }
  639. RegCloseKey(hkey);
  640. const String flags = String::utf16((const char16_t *)buffer.ptr(), size / sizeof(WCHAR));
  641. for (const String &flag : flags.split(";", false)) {
  642. if (flag == "GpuPreference=1") {
  643. return true;
  644. }
  645. }
  646. return false;
  647. }
  648. OS::DateTime OS_Windows::get_datetime(bool p_utc) const {
  649. SYSTEMTIME systemtime;
  650. if (p_utc) {
  651. GetSystemTime(&systemtime);
  652. } else {
  653. GetLocalTime(&systemtime);
  654. }
  655. //Get DST information from Windows, but only if p_utc is false.
  656. TIME_ZONE_INFORMATION info;
  657. bool is_daylight = false;
  658. if (!p_utc && GetTimeZoneInformation(&info) == TIME_ZONE_ID_DAYLIGHT) {
  659. is_daylight = true;
  660. }
  661. DateTime dt;
  662. dt.year = systemtime.wYear;
  663. dt.month = Month(systemtime.wMonth);
  664. dt.day = systemtime.wDay;
  665. dt.weekday = Weekday(systemtime.wDayOfWeek);
  666. dt.hour = systemtime.wHour;
  667. dt.minute = systemtime.wMinute;
  668. dt.second = systemtime.wSecond;
  669. dt.dst = is_daylight;
  670. return dt;
  671. }
  672. OS::TimeZoneInfo OS_Windows::get_time_zone_info() const {
  673. TIME_ZONE_INFORMATION info;
  674. bool is_daylight = false;
  675. if (GetTimeZoneInformation(&info) == TIME_ZONE_ID_DAYLIGHT) {
  676. is_daylight = true;
  677. }
  678. // Daylight Bias needs to be added to the bias if DST is in effect, or else it will not properly update.
  679. TimeZoneInfo ret;
  680. if (is_daylight) {
  681. ret.name = info.DaylightName;
  682. ret.bias = info.Bias + info.DaylightBias;
  683. } else {
  684. ret.name = info.StandardName;
  685. ret.bias = info.Bias + info.StandardBias;
  686. }
  687. // Bias value returned by GetTimeZoneInformation is inverted of what we expect
  688. // For example, on GMT-3 GetTimeZoneInformation return a Bias of 180, so invert the value to get -180
  689. ret.bias = -ret.bias;
  690. return ret;
  691. }
  692. double OS_Windows::get_unix_time() const {
  693. // 1 Windows tick is 100ns
  694. const uint64_t WINDOWS_TICKS_PER_SECOND = 10000000;
  695. const uint64_t TICKS_TO_UNIX_EPOCH = 116444736000000000LL;
  696. SYSTEMTIME st;
  697. GetSystemTime(&st);
  698. FILETIME ft;
  699. SystemTimeToFileTime(&st, &ft);
  700. uint64_t ticks_time;
  701. ticks_time = ft.dwHighDateTime;
  702. ticks_time <<= 32;
  703. ticks_time |= ft.dwLowDateTime;
  704. return (double)(ticks_time - TICKS_TO_UNIX_EPOCH) / WINDOWS_TICKS_PER_SECOND;
  705. }
  706. void OS_Windows::delay_usec(uint32_t p_usec) const {
  707. constexpr uint32_t tolerance = 1000 + 20;
  708. uint64_t t0 = get_ticks_usec();
  709. uint64_t target_time = t0 + p_usec;
  710. // Calculate sleep duration with a tolerance for fine-tuning.
  711. if (p_usec > tolerance) {
  712. uint32_t coarse_sleep_usec = p_usec - tolerance;
  713. if (coarse_sleep_usec >= 1000) {
  714. Sleep(coarse_sleep_usec / 1000);
  715. }
  716. }
  717. // Spin-wait until we reach the precise target time.
  718. while (get_ticks_usec() < target_time) {
  719. YieldProcessor();
  720. }
  721. }
  722. uint64_t OS_Windows::get_ticks_usec() const {
  723. uint64_t ticks;
  724. // This is the number of clock ticks since start
  725. QueryPerformanceCounter((LARGE_INTEGER *)&ticks);
  726. // Subtract the ticks at game start to get
  727. // the ticks since the game started
  728. ticks -= ticks_start;
  729. // Divide by frequency to get the time in seconds
  730. // original calculation shown below is subject to overflow
  731. // with high ticks_per_second and a number of days since the last reboot.
  732. // time = ticks * 1000000L / ticks_per_second;
  733. // we can prevent this by either using 128 bit math
  734. // or separating into a calculation for seconds, and the fraction
  735. uint64_t seconds = ticks / ticks_per_second;
  736. // compiler will optimize these two into one divide
  737. uint64_t leftover = ticks % ticks_per_second;
  738. // remainder
  739. uint64_t time = (leftover * 1000000L) / ticks_per_second;
  740. // seconds
  741. time += seconds * 1000000L;
  742. return time;
  743. }
  744. String OS_Windows::_quote_command_line_argument(const String &p_text) const {
  745. for (int i = 0; i < p_text.size(); i++) {
  746. char32_t c = p_text[i];
  747. if (c == ' ' || c == '&' || c == '(' || c == ')' || c == '[' || c == ']' || c == '{' || c == '}' || c == '^' || c == '=' || c == ';' || c == '!' || c == '\'' || c == '+' || c == ',' || c == '`' || c == '~') {
  748. return "\"" + p_text + "\"";
  749. }
  750. }
  751. return p_text;
  752. }
  753. static void _append_to_pipe(char *p_bytes, int p_size, String *r_pipe, Mutex *p_pipe_mutex) {
  754. // Try to convert from default ANSI code page to Unicode.
  755. LocalVector<wchar_t> wchars;
  756. int total_wchars = MultiByteToWideChar(CP_ACP, 0, p_bytes, p_size, nullptr, 0);
  757. if (total_wchars > 0) {
  758. wchars.resize(total_wchars);
  759. if (MultiByteToWideChar(CP_ACP, 0, p_bytes, p_size, wchars.ptr(), total_wchars) == 0) {
  760. wchars.clear();
  761. }
  762. }
  763. if (p_pipe_mutex) {
  764. p_pipe_mutex->lock();
  765. }
  766. if (wchars.is_empty()) {
  767. // Let's hope it's compatible with UTF-8.
  768. (*r_pipe) += String::utf8(p_bytes, p_size);
  769. } else {
  770. (*r_pipe) += String(wchars.ptr(), total_wchars);
  771. }
  772. if (p_pipe_mutex) {
  773. p_pipe_mutex->unlock();
  774. }
  775. }
  776. Dictionary OS_Windows::get_memory_info() const {
  777. Dictionary meminfo;
  778. meminfo["physical"] = -1;
  779. meminfo["free"] = -1;
  780. meminfo["available"] = -1;
  781. meminfo["stack"] = -1;
  782. PERFORMANCE_INFORMATION pref_info;
  783. pref_info.cb = sizeof(pref_info);
  784. GetPerformanceInfo(&pref_info, sizeof(pref_info));
  785. typedef void(WINAPI * PGetCurrentThreadStackLimits)(PULONG_PTR, PULONG_PTR);
  786. PGetCurrentThreadStackLimits GetCurrentThreadStackLimits = (PGetCurrentThreadStackLimits)GetProcAddress(GetModuleHandleA("kernel32.dll"), "GetCurrentThreadStackLimits");
  787. ULONG_PTR LowLimit = 0;
  788. ULONG_PTR HighLimit = 0;
  789. if (GetCurrentThreadStackLimits) {
  790. GetCurrentThreadStackLimits(&LowLimit, &HighLimit);
  791. }
  792. if (pref_info.PhysicalTotal * pref_info.PageSize != 0) {
  793. meminfo["physical"] = static_cast<int64_t>(pref_info.PhysicalTotal * pref_info.PageSize);
  794. }
  795. if (pref_info.PhysicalAvailable * pref_info.PageSize != 0) {
  796. meminfo["free"] = static_cast<int64_t>(pref_info.PhysicalAvailable * pref_info.PageSize);
  797. }
  798. if (pref_info.CommitLimit * pref_info.PageSize != 0) {
  799. meminfo["available"] = static_cast<int64_t>(pref_info.CommitLimit * pref_info.PageSize);
  800. }
  801. if (HighLimit - LowLimit != 0) {
  802. meminfo["stack"] = static_cast<int64_t>(HighLimit - LowLimit);
  803. }
  804. return meminfo;
  805. }
  806. Dictionary OS_Windows::execute_with_pipe(const String &p_path, const List<String> &p_arguments, bool p_blocking) {
  807. #define CLEAN_PIPES \
  808. if (pipe_in[0] != 0) { \
  809. CloseHandle(pipe_in[0]); \
  810. } \
  811. if (pipe_in[1] != 0) { \
  812. CloseHandle(pipe_in[1]); \
  813. } \
  814. if (pipe_out[0] != 0) { \
  815. CloseHandle(pipe_out[0]); \
  816. } \
  817. if (pipe_out[1] != 0) { \
  818. CloseHandle(pipe_out[1]); \
  819. } \
  820. if (pipe_err[0] != 0) { \
  821. CloseHandle(pipe_err[0]); \
  822. } \
  823. if (pipe_err[1] != 0) { \
  824. CloseHandle(pipe_err[1]); \
  825. }
  826. Dictionary ret;
  827. String path = p_path.is_absolute_path() ? fix_path(p_path) : p_path;
  828. String command = _quote_command_line_argument(path);
  829. for (const String &E : p_arguments) {
  830. command += " " + _quote_command_line_argument(E);
  831. }
  832. // Create pipes.
  833. HANDLE pipe_in[2] = { nullptr, nullptr };
  834. HANDLE pipe_out[2] = { nullptr, nullptr };
  835. HANDLE pipe_err[2] = { nullptr, nullptr };
  836. SECURITY_ATTRIBUTES sa;
  837. sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  838. sa.bInheritHandle = true;
  839. sa.lpSecurityDescriptor = nullptr;
  840. ERR_FAIL_COND_V(!CreatePipe(&pipe_in[0], &pipe_in[1], &sa, 0), ret);
  841. if (!CreatePipe(&pipe_out[0], &pipe_out[1], &sa, 0)) {
  842. CLEAN_PIPES
  843. ERR_FAIL_V(ret);
  844. }
  845. if (!CreatePipe(&pipe_err[0], &pipe_err[1], &sa, 0)) {
  846. CLEAN_PIPES
  847. ERR_FAIL_V(ret);
  848. }
  849. ERR_FAIL_COND_V(!SetHandleInformation(pipe_err[0], HANDLE_FLAG_INHERIT, 0), ret);
  850. // Create process.
  851. ProcessInfo pi;
  852. ZeroMemory(&pi.si, sizeof(pi.si));
  853. pi.si.StartupInfo.cb = sizeof(pi.si);
  854. ZeroMemory(&pi.pi, sizeof(pi.pi));
  855. LPSTARTUPINFOW si_w = (LPSTARTUPINFOW)&pi.si.StartupInfo;
  856. pi.si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
  857. pi.si.StartupInfo.hStdInput = pipe_in[0];
  858. pi.si.StartupInfo.hStdOutput = pipe_out[1];
  859. pi.si.StartupInfo.hStdError = pipe_err[1];
  860. SIZE_T attr_list_size = 0;
  861. InitializeProcThreadAttributeList(nullptr, 1, 0, &attr_list_size);
  862. pi.si.lpAttributeList = (LPPROC_THREAD_ATTRIBUTE_LIST)alloca(attr_list_size);
  863. if (!InitializeProcThreadAttributeList(pi.si.lpAttributeList, 1, 0, &attr_list_size)) {
  864. CLEAN_PIPES
  865. ERR_FAIL_V(ret);
  866. }
  867. HANDLE handles_to_inherit[] = { pipe_in[0], pipe_out[1], pipe_err[1] };
  868. if (!UpdateProcThreadAttribute(
  869. pi.si.lpAttributeList,
  870. 0,
  871. PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
  872. handles_to_inherit,
  873. sizeof(handles_to_inherit),
  874. nullptr,
  875. nullptr)) {
  876. CLEAN_PIPES
  877. DeleteProcThreadAttributeList(pi.si.lpAttributeList);
  878. ERR_FAIL_V(ret);
  879. }
  880. DWORD creation_flags = NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW | EXTENDED_STARTUPINFO_PRESENT;
  881. Char16String current_dir_name;
  882. size_t str_len = GetCurrentDirectoryW(0, nullptr);
  883. current_dir_name.resize(str_len + 1);
  884. GetCurrentDirectoryW(current_dir_name.size(), (LPWSTR)current_dir_name.ptrw());
  885. if (current_dir_name.size() >= MAX_PATH) {
  886. Char16String current_short_dir_name;
  887. str_len = GetShortPathNameW((LPCWSTR)current_dir_name.ptr(), nullptr, 0);
  888. current_short_dir_name.resize(str_len);
  889. GetShortPathNameW((LPCWSTR)current_dir_name.ptr(), (LPWSTR)current_short_dir_name.ptrw(), current_short_dir_name.size());
  890. current_dir_name = current_short_dir_name;
  891. }
  892. if (!CreateProcessW(nullptr, (LPWSTR)(command.utf16().ptrw()), nullptr, nullptr, true, creation_flags, nullptr, (LPWSTR)current_dir_name.ptr(), si_w, &pi.pi)) {
  893. CLEAN_PIPES
  894. DeleteProcThreadAttributeList(pi.si.lpAttributeList);
  895. ERR_FAIL_V_MSG(ret, "Could not create child process: " + command);
  896. }
  897. CloseHandle(pipe_in[0]);
  898. CloseHandle(pipe_out[1]);
  899. CloseHandle(pipe_err[1]);
  900. DeleteProcThreadAttributeList(pi.si.lpAttributeList);
  901. ProcessID pid = pi.pi.dwProcessId;
  902. process_map_mutex.lock();
  903. process_map->insert(pid, pi);
  904. process_map_mutex.unlock();
  905. Ref<FileAccessWindowsPipe> main_pipe;
  906. main_pipe.instantiate();
  907. main_pipe->open_existing(pipe_out[0], pipe_in[1], p_blocking);
  908. Ref<FileAccessWindowsPipe> err_pipe;
  909. err_pipe.instantiate();
  910. err_pipe->open_existing(pipe_err[0], nullptr, p_blocking);
  911. ret["stdio"] = main_pipe;
  912. ret["stderr"] = err_pipe;
  913. ret["pid"] = pid;
  914. #undef CLEAN_PIPES
  915. return ret;
  916. }
  917. 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) {
  918. String path = p_path.is_absolute_path() ? fix_path(p_path) : p_path;
  919. String command = _quote_command_line_argument(path);
  920. for (const String &E : p_arguments) {
  921. command += " " + _quote_command_line_argument(E);
  922. }
  923. ProcessInfo pi;
  924. ZeroMemory(&pi.si, sizeof(pi.si));
  925. pi.si.StartupInfo.cb = sizeof(pi.si);
  926. ZeroMemory(&pi.pi, sizeof(pi.pi));
  927. LPSTARTUPINFOW si_w = (LPSTARTUPINFOW)&pi.si.StartupInfo;
  928. bool inherit_handles = false;
  929. HANDLE pipe[2] = { nullptr, nullptr };
  930. if (r_pipe) {
  931. // Create pipe for StdOut and StdErr.
  932. SECURITY_ATTRIBUTES sa;
  933. sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  934. sa.bInheritHandle = true;
  935. sa.lpSecurityDescriptor = nullptr;
  936. ERR_FAIL_COND_V(!CreatePipe(&pipe[0], &pipe[1], &sa, 0), ERR_CANT_FORK);
  937. pi.si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
  938. pi.si.StartupInfo.hStdOutput = pipe[1];
  939. if (read_stderr) {
  940. pi.si.StartupInfo.hStdError = pipe[1];
  941. }
  942. SIZE_T attr_list_size = 0;
  943. InitializeProcThreadAttributeList(nullptr, 1, 0, &attr_list_size);
  944. pi.si.lpAttributeList = (LPPROC_THREAD_ATTRIBUTE_LIST)alloca(attr_list_size);
  945. if (!InitializeProcThreadAttributeList(pi.si.lpAttributeList, 1, 0, &attr_list_size)) {
  946. CloseHandle(pipe[0]); // Cleanup pipe handles.
  947. CloseHandle(pipe[1]);
  948. ERR_FAIL_V(ERR_CANT_FORK);
  949. }
  950. if (!UpdateProcThreadAttribute(
  951. pi.si.lpAttributeList,
  952. 0,
  953. PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
  954. &pipe[1],
  955. sizeof(HANDLE),
  956. nullptr,
  957. nullptr)) {
  958. CloseHandle(pipe[0]); // Cleanup pipe handles.
  959. CloseHandle(pipe[1]);
  960. DeleteProcThreadAttributeList(pi.si.lpAttributeList);
  961. ERR_FAIL_V(ERR_CANT_FORK);
  962. }
  963. inherit_handles = true;
  964. }
  965. DWORD creation_flags = NORMAL_PRIORITY_CLASS;
  966. if (inherit_handles) {
  967. creation_flags |= EXTENDED_STARTUPINFO_PRESENT;
  968. }
  969. if (p_open_console) {
  970. creation_flags |= CREATE_NEW_CONSOLE;
  971. } else {
  972. creation_flags |= CREATE_NO_WINDOW;
  973. }
  974. Char16String current_dir_name;
  975. size_t str_len = GetCurrentDirectoryW(0, nullptr);
  976. current_dir_name.resize(str_len + 1);
  977. GetCurrentDirectoryW(current_dir_name.size(), (LPWSTR)current_dir_name.ptrw());
  978. if (current_dir_name.size() >= MAX_PATH) {
  979. Char16String current_short_dir_name;
  980. str_len = GetShortPathNameW((LPCWSTR)current_dir_name.ptr(), nullptr, 0);
  981. current_short_dir_name.resize(str_len);
  982. GetShortPathNameW((LPCWSTR)current_dir_name.ptr(), (LPWSTR)current_short_dir_name.ptrw(), current_short_dir_name.size());
  983. current_dir_name = current_short_dir_name;
  984. }
  985. int ret = CreateProcessW(nullptr, (LPWSTR)(command.utf16().ptrw()), nullptr, nullptr, inherit_handles, creation_flags, nullptr, (LPWSTR)current_dir_name.ptr(), si_w, &pi.pi);
  986. if (!ret && r_pipe) {
  987. CloseHandle(pipe[0]); // Cleanup pipe handles.
  988. CloseHandle(pipe[1]);
  989. DeleteProcThreadAttributeList(pi.si.lpAttributeList);
  990. }
  991. ERR_FAIL_COND_V_MSG(ret == 0, ERR_CANT_FORK, "Could not create child process: " + command);
  992. if (r_pipe) {
  993. CloseHandle(pipe[1]); // Close pipe write handle (only child process is writing).
  994. LocalVector<char> bytes;
  995. int bytes_in_buffer = 0;
  996. const int CHUNK_SIZE = 4096;
  997. DWORD read = 0;
  998. for (;;) { // Read StdOut and StdErr from pipe.
  999. bytes.resize(bytes_in_buffer + CHUNK_SIZE);
  1000. const bool success = ReadFile(pipe[0], bytes.ptr() + bytes_in_buffer, CHUNK_SIZE, &read, nullptr);
  1001. if (!success || read == 0) {
  1002. break;
  1003. }
  1004. // Assume that all possible encodings are ASCII-compatible.
  1005. // Break at newline to allow receiving long output in portions.
  1006. int newline_index = -1;
  1007. for (int i = read - 1; i >= 0; i--) {
  1008. if (bytes[bytes_in_buffer + i] == '\n') {
  1009. newline_index = i;
  1010. break;
  1011. }
  1012. }
  1013. if (newline_index == -1) {
  1014. bytes_in_buffer += read;
  1015. continue;
  1016. }
  1017. const int bytes_to_convert = bytes_in_buffer + (newline_index + 1);
  1018. _append_to_pipe(bytes.ptr(), bytes_to_convert, r_pipe, p_pipe_mutex);
  1019. bytes_in_buffer = read - (newline_index + 1);
  1020. memmove(bytes.ptr(), bytes.ptr() + bytes_to_convert, bytes_in_buffer);
  1021. }
  1022. if (bytes_in_buffer > 0) {
  1023. _append_to_pipe(bytes.ptr(), bytes_in_buffer, r_pipe, p_pipe_mutex);
  1024. }
  1025. CloseHandle(pipe[0]); // Close pipe read handle.
  1026. }
  1027. WaitForSingleObject(pi.pi.hProcess, INFINITE);
  1028. if (r_exitcode) {
  1029. DWORD ret2;
  1030. GetExitCodeProcess(pi.pi.hProcess, &ret2);
  1031. *r_exitcode = ret2;
  1032. }
  1033. CloseHandle(pi.pi.hProcess);
  1034. CloseHandle(pi.pi.hThread);
  1035. if (r_pipe) {
  1036. DeleteProcThreadAttributeList(pi.si.lpAttributeList);
  1037. }
  1038. return OK;
  1039. }
  1040. Error OS_Windows::create_process(const String &p_path, const List<String> &p_arguments, ProcessID *r_child_id, bool p_open_console) {
  1041. String path = p_path.is_absolute_path() ? fix_path(p_path) : p_path;
  1042. String command = _quote_command_line_argument(path);
  1043. for (const String &E : p_arguments) {
  1044. command += " " + _quote_command_line_argument(E);
  1045. }
  1046. ProcessInfo pi;
  1047. ZeroMemory(&pi.si, sizeof(pi.si));
  1048. pi.si.StartupInfo.cb = sizeof(pi.si.StartupInfo);
  1049. ZeroMemory(&pi.pi, sizeof(pi.pi));
  1050. LPSTARTUPINFOW si_w = (LPSTARTUPINFOW)&pi.si.StartupInfo;
  1051. DWORD creation_flags = NORMAL_PRIORITY_CLASS;
  1052. if (p_open_console) {
  1053. creation_flags |= CREATE_NEW_CONSOLE;
  1054. } else {
  1055. creation_flags |= CREATE_NO_WINDOW;
  1056. }
  1057. Char16String current_dir_name;
  1058. size_t str_len = GetCurrentDirectoryW(0, nullptr);
  1059. current_dir_name.resize(str_len + 1);
  1060. GetCurrentDirectoryW(current_dir_name.size(), (LPWSTR)current_dir_name.ptrw());
  1061. if (current_dir_name.size() >= MAX_PATH) {
  1062. Char16String current_short_dir_name;
  1063. str_len = GetShortPathNameW((LPCWSTR)current_dir_name.ptr(), nullptr, 0);
  1064. current_short_dir_name.resize(str_len);
  1065. GetShortPathNameW((LPCWSTR)current_dir_name.ptr(), (LPWSTR)current_short_dir_name.ptrw(), current_short_dir_name.size());
  1066. current_dir_name = current_short_dir_name;
  1067. }
  1068. int ret = CreateProcessW(nullptr, (LPWSTR)(command.utf16().ptrw()), nullptr, nullptr, false, creation_flags, nullptr, (LPWSTR)current_dir_name.ptr(), si_w, &pi.pi);
  1069. ERR_FAIL_COND_V_MSG(ret == 0, ERR_CANT_FORK, "Could not create child process: " + command);
  1070. ProcessID pid = pi.pi.dwProcessId;
  1071. if (r_child_id) {
  1072. *r_child_id = pid;
  1073. }
  1074. process_map_mutex.lock();
  1075. process_map->insert(pid, pi);
  1076. process_map_mutex.unlock();
  1077. return OK;
  1078. }
  1079. Error OS_Windows::kill(const ProcessID &p_pid) {
  1080. int ret = 0;
  1081. MutexLock lock(process_map_mutex);
  1082. if (process_map->has(p_pid)) {
  1083. const PROCESS_INFORMATION pi = (*process_map)[p_pid].pi;
  1084. process_map->erase(p_pid);
  1085. ret = TerminateProcess(pi.hProcess, 0);
  1086. CloseHandle(pi.hProcess);
  1087. CloseHandle(pi.hThread);
  1088. } else {
  1089. HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, false, (DWORD)p_pid);
  1090. if (hProcess != nullptr) {
  1091. ret = TerminateProcess(hProcess, 0);
  1092. CloseHandle(hProcess);
  1093. }
  1094. }
  1095. return ret != 0 ? OK : FAILED;
  1096. }
  1097. int OS_Windows::get_process_id() const {
  1098. return _getpid();
  1099. }
  1100. bool OS_Windows::is_process_running(const ProcessID &p_pid) const {
  1101. MutexLock lock(process_map_mutex);
  1102. if (!process_map->has(p_pid)) {
  1103. return false;
  1104. }
  1105. const ProcessInfo &info = (*process_map)[p_pid];
  1106. if (!info.is_running) {
  1107. return false;
  1108. }
  1109. const PROCESS_INFORMATION &pi = info.pi;
  1110. DWORD dw_exit_code = 0;
  1111. if (!GetExitCodeProcess(pi.hProcess, &dw_exit_code)) {
  1112. return false;
  1113. }
  1114. if (dw_exit_code != STILL_ACTIVE) {
  1115. info.is_running = false;
  1116. info.exit_code = dw_exit_code;
  1117. return false;
  1118. }
  1119. return true;
  1120. }
  1121. int OS_Windows::get_process_exit_code(const ProcessID &p_pid) const {
  1122. MutexLock lock(process_map_mutex);
  1123. if (!process_map->has(p_pid)) {
  1124. return -1;
  1125. }
  1126. const ProcessInfo &info = (*process_map)[p_pid];
  1127. if (!info.is_running) {
  1128. return info.exit_code;
  1129. }
  1130. const PROCESS_INFORMATION &pi = info.pi;
  1131. DWORD dw_exit_code = 0;
  1132. if (!GetExitCodeProcess(pi.hProcess, &dw_exit_code)) {
  1133. return -1;
  1134. }
  1135. if (dw_exit_code == STILL_ACTIVE) {
  1136. return -1;
  1137. }
  1138. info.is_running = false;
  1139. info.exit_code = dw_exit_code;
  1140. return dw_exit_code;
  1141. }
  1142. Error OS_Windows::set_cwd(const String &p_cwd) {
  1143. if (_wchdir((LPCWSTR)(p_cwd.utf16().get_data())) != 0) {
  1144. return ERR_CANT_OPEN;
  1145. }
  1146. return OK;
  1147. }
  1148. Vector<String> OS_Windows::get_system_fonts() const {
  1149. if (!dwrite_init) {
  1150. return Vector<String>();
  1151. }
  1152. Vector<String> ret;
  1153. HashSet<String> font_names;
  1154. UINT32 family_count = font_collection->GetFontFamilyCount();
  1155. for (UINT32 i = 0; i < family_count; i++) {
  1156. ComAutoreleaseRef<IDWriteFontFamily> family;
  1157. HRESULT hr = font_collection->GetFontFamily(i, &family.reference);
  1158. ERR_CONTINUE(FAILED(hr) || family.is_null());
  1159. ComAutoreleaseRef<IDWriteLocalizedStrings> family_names;
  1160. hr = family->GetFamilyNames(&family_names.reference);
  1161. ERR_CONTINUE(FAILED(hr) || family_names.is_null());
  1162. UINT32 index = 0;
  1163. BOOL exists = false;
  1164. UINT32 length = 0;
  1165. Char16String name;
  1166. hr = family_names->FindLocaleName(L"en-us", &index, &exists);
  1167. ERR_CONTINUE(FAILED(hr));
  1168. hr = family_names->GetStringLength(index, &length);
  1169. ERR_CONTINUE(FAILED(hr));
  1170. name.resize(length + 1);
  1171. hr = family_names->GetString(index, (WCHAR *)name.ptrw(), length + 1);
  1172. ERR_CONTINUE(FAILED(hr));
  1173. font_names.insert(String::utf16(name.ptr(), length));
  1174. }
  1175. for (const String &E : font_names) {
  1176. ret.push_back(E);
  1177. }
  1178. return ret;
  1179. }
  1180. #if defined(__GNUC__) && !defined(__clang__)
  1181. #pragma GCC diagnostic push
  1182. #pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
  1183. #endif
  1184. class FallbackTextAnalysisSource : public IDWriteTextAnalysisSource {
  1185. LONG _cRef = 1;
  1186. bool rtl = false;
  1187. Char16String string;
  1188. Char16String locale;
  1189. IDWriteNumberSubstitution *n_sub = nullptr;
  1190. public:
  1191. HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID **ppvInterface) override {
  1192. if (IID_IUnknown == riid) {
  1193. AddRef();
  1194. *ppvInterface = (IUnknown *)this;
  1195. } else if (__uuidof(IMMNotificationClient) == riid) {
  1196. AddRef();
  1197. *ppvInterface = (IMMNotificationClient *)this;
  1198. } else {
  1199. *ppvInterface = nullptr;
  1200. return E_NOINTERFACE;
  1201. }
  1202. return S_OK;
  1203. }
  1204. ULONG STDMETHODCALLTYPE AddRef() override {
  1205. return InterlockedIncrement(&_cRef);
  1206. }
  1207. ULONG STDMETHODCALLTYPE Release() override {
  1208. ULONG ulRef = InterlockedDecrement(&_cRef);
  1209. if (0 == ulRef) {
  1210. delete this;
  1211. }
  1212. return ulRef;
  1213. }
  1214. HRESULT STDMETHODCALLTYPE GetTextAtPosition(UINT32 p_text_position, WCHAR const **r_text_string, UINT32 *r_text_length) override {
  1215. if (p_text_position >= (UINT32)string.length()) {
  1216. *r_text_string = nullptr;
  1217. *r_text_length = 0;
  1218. return S_OK;
  1219. }
  1220. *r_text_string = reinterpret_cast<const wchar_t *>(string.get_data()) + p_text_position;
  1221. *r_text_length = string.length() - p_text_position;
  1222. return S_OK;
  1223. }
  1224. HRESULT STDMETHODCALLTYPE GetTextBeforePosition(UINT32 p_text_position, WCHAR const **r_text_string, UINT32 *r_text_length) override {
  1225. if (p_text_position < 1 || p_text_position >= (UINT32)string.length()) {
  1226. *r_text_string = nullptr;
  1227. *r_text_length = 0;
  1228. return S_OK;
  1229. }
  1230. *r_text_string = reinterpret_cast<const wchar_t *>(string.get_data());
  1231. *r_text_length = p_text_position;
  1232. return S_OK;
  1233. }
  1234. DWRITE_READING_DIRECTION STDMETHODCALLTYPE GetParagraphReadingDirection() override {
  1235. return (rtl) ? DWRITE_READING_DIRECTION_RIGHT_TO_LEFT : DWRITE_READING_DIRECTION_LEFT_TO_RIGHT;
  1236. }
  1237. HRESULT STDMETHODCALLTYPE GetLocaleName(UINT32 p_text_position, UINT32 *r_text_length, WCHAR const **r_locale_name) override {
  1238. *r_locale_name = reinterpret_cast<const wchar_t *>(locale.get_data());
  1239. return S_OK;
  1240. }
  1241. HRESULT STDMETHODCALLTYPE GetNumberSubstitution(UINT32 p_text_position, UINT32 *r_text_length, IDWriteNumberSubstitution **r_number_substitution) override {
  1242. *r_number_substitution = n_sub;
  1243. return S_OK;
  1244. }
  1245. FallbackTextAnalysisSource(const Char16String &p_text, const Char16String &p_locale, bool p_rtl, IDWriteNumberSubstitution *p_nsub) {
  1246. _cRef = 1;
  1247. string = p_text;
  1248. locale = p_locale;
  1249. n_sub = p_nsub;
  1250. rtl = p_rtl;
  1251. }
  1252. virtual ~FallbackTextAnalysisSource() {}
  1253. };
  1254. #if defined(__GNUC__) && !defined(__clang__)
  1255. #pragma GCC diagnostic pop
  1256. #endif
  1257. String OS_Windows::_get_default_fontname(const String &p_font_name) const {
  1258. String font_name = p_font_name;
  1259. if (font_name.to_lower() == "sans-serif") {
  1260. font_name = "Arial";
  1261. } else if (font_name.to_lower() == "serif") {
  1262. font_name = "Times New Roman";
  1263. } else if (font_name.to_lower() == "monospace") {
  1264. font_name = "Courier New";
  1265. } else if (font_name.to_lower() == "cursive") {
  1266. font_name = "Comic Sans MS";
  1267. } else if (font_name.to_lower() == "fantasy") {
  1268. font_name = "Gabriola";
  1269. }
  1270. return font_name;
  1271. }
  1272. DWRITE_FONT_WEIGHT OS_Windows::_weight_to_dw(int p_weight) const {
  1273. if (p_weight < 150) {
  1274. return DWRITE_FONT_WEIGHT_THIN;
  1275. } else if (p_weight < 250) {
  1276. return DWRITE_FONT_WEIGHT_EXTRA_LIGHT;
  1277. } else if (p_weight < 325) {
  1278. return DWRITE_FONT_WEIGHT_LIGHT;
  1279. } else if (p_weight < 375) {
  1280. return DWRITE_FONT_WEIGHT_SEMI_LIGHT;
  1281. } else if (p_weight < 450) {
  1282. return DWRITE_FONT_WEIGHT_NORMAL;
  1283. } else if (p_weight < 550) {
  1284. return DWRITE_FONT_WEIGHT_MEDIUM;
  1285. } else if (p_weight < 650) {
  1286. return DWRITE_FONT_WEIGHT_DEMI_BOLD;
  1287. } else if (p_weight < 750) {
  1288. return DWRITE_FONT_WEIGHT_BOLD;
  1289. } else if (p_weight < 850) {
  1290. return DWRITE_FONT_WEIGHT_EXTRA_BOLD;
  1291. } else if (p_weight < 925) {
  1292. return DWRITE_FONT_WEIGHT_BLACK;
  1293. } else {
  1294. return DWRITE_FONT_WEIGHT_EXTRA_BLACK;
  1295. }
  1296. }
  1297. DWRITE_FONT_STRETCH OS_Windows::_stretch_to_dw(int p_stretch) const {
  1298. if (p_stretch < 56) {
  1299. return DWRITE_FONT_STRETCH_ULTRA_CONDENSED;
  1300. } else if (p_stretch < 69) {
  1301. return DWRITE_FONT_STRETCH_EXTRA_CONDENSED;
  1302. } else if (p_stretch < 81) {
  1303. return DWRITE_FONT_STRETCH_CONDENSED;
  1304. } else if (p_stretch < 93) {
  1305. return DWRITE_FONT_STRETCH_SEMI_CONDENSED;
  1306. } else if (p_stretch < 106) {
  1307. return DWRITE_FONT_STRETCH_NORMAL;
  1308. } else if (p_stretch < 137) {
  1309. return DWRITE_FONT_STRETCH_SEMI_EXPANDED;
  1310. } else if (p_stretch < 144) {
  1311. return DWRITE_FONT_STRETCH_EXPANDED;
  1312. } else if (p_stretch < 162) {
  1313. return DWRITE_FONT_STRETCH_EXTRA_EXPANDED;
  1314. } else {
  1315. return DWRITE_FONT_STRETCH_ULTRA_EXPANDED;
  1316. }
  1317. }
  1318. 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 {
  1319. if (!dwrite2_init) {
  1320. return Vector<String>();
  1321. }
  1322. String font_name = _get_default_fontname(p_font_name);
  1323. bool rtl = TS->is_locale_right_to_left(p_locale);
  1324. Char16String text = p_text.utf16();
  1325. Char16String locale = p_locale.utf16();
  1326. ComAutoreleaseRef<IDWriteNumberSubstitution> number_substitution;
  1327. HRESULT hr = dwrite_factory->CreateNumberSubstitution(DWRITE_NUMBER_SUBSTITUTION_METHOD_NONE, reinterpret_cast<const wchar_t *>(locale.get_data()), true, &number_substitution.reference);
  1328. ERR_FAIL_COND_V(FAILED(hr) || number_substitution.is_null(), Vector<String>());
  1329. FallbackTextAnalysisSource fs = FallbackTextAnalysisSource(text, locale, rtl, number_substitution.reference);
  1330. UINT32 mapped_length = 0;
  1331. FLOAT scale = 0.0;
  1332. ComAutoreleaseRef<IDWriteFont> dwrite_font;
  1333. hr = system_font_fallback->MapCharacters(
  1334. &fs,
  1335. 0,
  1336. (UINT32)text.length(),
  1337. font_collection,
  1338. reinterpret_cast<const wchar_t *>(font_name.utf16().get_data()),
  1339. _weight_to_dw(p_weight),
  1340. p_italic ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL,
  1341. _stretch_to_dw(p_stretch),
  1342. &mapped_length,
  1343. &dwrite_font.reference,
  1344. &scale);
  1345. if (FAILED(hr) || dwrite_font.is_null()) {
  1346. return Vector<String>();
  1347. }
  1348. ComAutoreleaseRef<IDWriteFontFace> dwrite_face;
  1349. hr = dwrite_font->CreateFontFace(&dwrite_face.reference);
  1350. if (FAILED(hr) || dwrite_face.is_null()) {
  1351. return Vector<String>();
  1352. }
  1353. UINT32 number_of_files = 0;
  1354. hr = dwrite_face->GetFiles(&number_of_files, nullptr);
  1355. if (FAILED(hr)) {
  1356. return Vector<String>();
  1357. }
  1358. Vector<ComAutoreleaseRef<IDWriteFontFile>> files;
  1359. files.resize(number_of_files);
  1360. hr = dwrite_face->GetFiles(&number_of_files, (IDWriteFontFile **)files.ptrw());
  1361. if (FAILED(hr)) {
  1362. return Vector<String>();
  1363. }
  1364. Vector<String> ret;
  1365. for (UINT32 i = 0; i < number_of_files; i++) {
  1366. void const *reference_key = nullptr;
  1367. UINT32 reference_key_size = 0;
  1368. ComAutoreleaseRef<IDWriteLocalFontFileLoader> loader;
  1369. hr = files.write[i]->GetLoader((IDWriteFontFileLoader **)&loader.reference);
  1370. if (FAILED(hr) || loader.is_null()) {
  1371. continue;
  1372. }
  1373. hr = files.write[i]->GetReferenceKey(&reference_key, &reference_key_size);
  1374. if (FAILED(hr)) {
  1375. continue;
  1376. }
  1377. WCHAR file_path[32767];
  1378. hr = loader->GetFilePathFromKey(reference_key, reference_key_size, &file_path[0], 32767);
  1379. if (FAILED(hr)) {
  1380. continue;
  1381. }
  1382. String fpath = String::utf16((const char16_t *)&file_path[0]).replace("\\", "/");
  1383. WIN32_FIND_DATAW d;
  1384. HANDLE fnd = FindFirstFileW((LPCWSTR)&file_path[0], &d);
  1385. if (fnd != INVALID_HANDLE_VALUE) {
  1386. String fname = String::utf16((const char16_t *)d.cFileName);
  1387. if (!fname.is_empty()) {
  1388. fpath = fpath.get_base_dir().path_join(fname);
  1389. }
  1390. FindClose(fnd);
  1391. }
  1392. ret.push_back(fpath);
  1393. }
  1394. return ret;
  1395. }
  1396. String OS_Windows::get_system_font_path(const String &p_font_name, int p_weight, int p_stretch, bool p_italic) const {
  1397. if (!dwrite_init) {
  1398. return String();
  1399. }
  1400. String font_name = _get_default_fontname(p_font_name);
  1401. UINT32 index = 0;
  1402. BOOL exists = false;
  1403. HRESULT hr = font_collection->FindFamilyName((const WCHAR *)font_name.utf16().get_data(), &index, &exists);
  1404. if (FAILED(hr) || !exists) {
  1405. return String();
  1406. }
  1407. ComAutoreleaseRef<IDWriteFontFamily> family;
  1408. hr = font_collection->GetFontFamily(index, &family.reference);
  1409. if (FAILED(hr) || family.is_null()) {
  1410. return String();
  1411. }
  1412. ComAutoreleaseRef<IDWriteFont> dwrite_font;
  1413. 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);
  1414. if (FAILED(hr) || dwrite_font.is_null()) {
  1415. return String();
  1416. }
  1417. ComAutoreleaseRef<IDWriteFontFace> dwrite_face;
  1418. hr = dwrite_font->CreateFontFace(&dwrite_face.reference);
  1419. if (FAILED(hr) || dwrite_face.is_null()) {
  1420. return String();
  1421. }
  1422. UINT32 number_of_files = 0;
  1423. hr = dwrite_face->GetFiles(&number_of_files, nullptr);
  1424. if (FAILED(hr)) {
  1425. return String();
  1426. }
  1427. Vector<ComAutoreleaseRef<IDWriteFontFile>> files;
  1428. files.resize(number_of_files);
  1429. hr = dwrite_face->GetFiles(&number_of_files, (IDWriteFontFile **)files.ptrw());
  1430. if (FAILED(hr)) {
  1431. return String();
  1432. }
  1433. for (UINT32 i = 0; i < number_of_files; i++) {
  1434. void const *reference_key = nullptr;
  1435. UINT32 reference_key_size = 0;
  1436. ComAutoreleaseRef<IDWriteLocalFontFileLoader> loader;
  1437. hr = files.write[i]->GetLoader((IDWriteFontFileLoader **)&loader.reference);
  1438. if (FAILED(hr) || loader.is_null()) {
  1439. continue;
  1440. }
  1441. hr = files.write[i]->GetReferenceKey(&reference_key, &reference_key_size);
  1442. if (FAILED(hr)) {
  1443. continue;
  1444. }
  1445. WCHAR file_path[32767];
  1446. hr = loader->GetFilePathFromKey(reference_key, reference_key_size, &file_path[0], 32767);
  1447. if (FAILED(hr)) {
  1448. continue;
  1449. }
  1450. String fpath = String::utf16((const char16_t *)&file_path[0]).replace("\\", "/");
  1451. WIN32_FIND_DATAW d;
  1452. HANDLE fnd = FindFirstFileW((LPCWSTR)&file_path[0], &d);
  1453. if (fnd != INVALID_HANDLE_VALUE) {
  1454. String fname = String::utf16((const char16_t *)d.cFileName);
  1455. if (!fname.is_empty()) {
  1456. fpath = fpath.get_base_dir().path_join(fname);
  1457. }
  1458. FindClose(fnd);
  1459. }
  1460. return fpath;
  1461. }
  1462. return String();
  1463. }
  1464. String OS_Windows::get_executable_path() const {
  1465. WCHAR bufname[4096];
  1466. GetModuleFileNameW(nullptr, bufname, 4096);
  1467. String s = String::utf16((const char16_t *)bufname).replace("\\", "/");
  1468. return s;
  1469. }
  1470. bool OS_Windows::has_environment(const String &p_var) const {
  1471. return GetEnvironmentVariableW((LPCWSTR)(p_var.utf16().get_data()), nullptr, 0) > 0;
  1472. }
  1473. String OS_Windows::get_environment(const String &p_var) const {
  1474. WCHAR wval[0x7fff]; // MSDN says 32767 char is the maximum
  1475. int wlen = GetEnvironmentVariableW((LPCWSTR)(p_var.utf16().get_data()), wval, 0x7fff);
  1476. if (wlen > 0) {
  1477. return String::utf16((const char16_t *)wval);
  1478. }
  1479. return "";
  1480. }
  1481. void OS_Windows::set_environment(const String &p_var, const String &p_value) const {
  1482. ERR_FAIL_COND_MSG(p_var.is_empty() || p_var.contains("="), vformat("Invalid environment variable name '%s', cannot be empty or include '='.", p_var));
  1483. Char16String var = p_var.utf16();
  1484. Char16String value = p_value.utf16();
  1485. ERR_FAIL_COND_MSG(var.length() + value.length() + 2 > 32767, vformat("Invalid definition for environment variable '%s', cannot exceed 32767 characters.", p_var));
  1486. SetEnvironmentVariableW((LPCWSTR)(var.get_data()), (LPCWSTR)(value.get_data()));
  1487. }
  1488. void OS_Windows::unset_environment(const String &p_var) const {
  1489. ERR_FAIL_COND_MSG(p_var.is_empty() || p_var.contains("="), vformat("Invalid environment variable name '%s', cannot be empty or include '='.", p_var));
  1490. SetEnvironmentVariableW((LPCWSTR)(p_var.utf16().get_data()), nullptr); // Null to delete.
  1491. }
  1492. String OS_Windows::get_stdin_string(int64_t p_buffer_size) {
  1493. if (get_stdin_type() == STD_HANDLE_INVALID) {
  1494. return String();
  1495. }
  1496. Vector<uint8_t> data;
  1497. data.resize(p_buffer_size);
  1498. DWORD count = 0;
  1499. if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), data.ptrw(), data.size(), &count, nullptr)) {
  1500. return String::utf8((const char *)data.ptr(), count);
  1501. }
  1502. return String();
  1503. }
  1504. PackedByteArray OS_Windows::get_stdin_buffer(int64_t p_buffer_size) {
  1505. Vector<uint8_t> data;
  1506. data.resize(p_buffer_size);
  1507. DWORD count = 0;
  1508. if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), data.ptrw(), data.size(), &count, nullptr)) {
  1509. return data;
  1510. }
  1511. return PackedByteArray();
  1512. }
  1513. OS_Windows::StdHandleType OS_Windows::get_stdin_type() const {
  1514. HANDLE h = GetStdHandle(STD_INPUT_HANDLE);
  1515. if (h == 0 || h == INVALID_HANDLE_VALUE) {
  1516. return STD_HANDLE_INVALID;
  1517. }
  1518. DWORD ftype = GetFileType(h);
  1519. if (ftype == FILE_TYPE_UNKNOWN && GetLastError() != ERROR_SUCCESS) {
  1520. return STD_HANDLE_UNKNOWN;
  1521. }
  1522. ftype &= ~(FILE_TYPE_REMOTE);
  1523. if (ftype == FILE_TYPE_DISK) {
  1524. return STD_HANDLE_FILE;
  1525. } else if (ftype == FILE_TYPE_PIPE) {
  1526. return STD_HANDLE_PIPE;
  1527. } else {
  1528. DWORD conmode = 0;
  1529. BOOL res = GetConsoleMode(h, &conmode);
  1530. if (!res && (GetLastError() == ERROR_INVALID_HANDLE)) {
  1531. return STD_HANDLE_UNKNOWN; // Unknown character device.
  1532. } else {
  1533. #ifndef WINDOWS_SUBSYSTEM_CONSOLE
  1534. if (!is_using_con_wrapper()) {
  1535. return STD_HANDLE_INVALID; // Window app can't read stdin input without werapper.
  1536. }
  1537. #endif
  1538. return STD_HANDLE_CONSOLE;
  1539. }
  1540. }
  1541. }
  1542. OS_Windows::StdHandleType OS_Windows::get_stdout_type() const {
  1543. HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
  1544. if (h == 0 || h == INVALID_HANDLE_VALUE) {
  1545. return STD_HANDLE_INVALID;
  1546. }
  1547. DWORD ftype = GetFileType(h);
  1548. if (ftype == FILE_TYPE_UNKNOWN && GetLastError() != ERROR_SUCCESS) {
  1549. return STD_HANDLE_UNKNOWN;
  1550. }
  1551. ftype &= ~(FILE_TYPE_REMOTE);
  1552. if (ftype == FILE_TYPE_DISK) {
  1553. return STD_HANDLE_FILE;
  1554. } else if (ftype == FILE_TYPE_PIPE) {
  1555. return STD_HANDLE_PIPE;
  1556. } else {
  1557. DWORD conmode = 0;
  1558. BOOL res = GetConsoleMode(h, &conmode);
  1559. if (!res && (GetLastError() == ERROR_INVALID_HANDLE)) {
  1560. return STD_HANDLE_UNKNOWN; // Unknown character device.
  1561. } else {
  1562. return STD_HANDLE_CONSOLE;
  1563. }
  1564. }
  1565. }
  1566. OS_Windows::StdHandleType OS_Windows::get_stderr_type() const {
  1567. HANDLE h = GetStdHandle(STD_ERROR_HANDLE);
  1568. if (h == 0 || h == INVALID_HANDLE_VALUE) {
  1569. return STD_HANDLE_INVALID;
  1570. }
  1571. DWORD ftype = GetFileType(h);
  1572. if (ftype == FILE_TYPE_UNKNOWN && GetLastError() != ERROR_SUCCESS) {
  1573. return STD_HANDLE_UNKNOWN;
  1574. }
  1575. ftype &= ~(FILE_TYPE_REMOTE);
  1576. if (ftype == FILE_TYPE_DISK) {
  1577. return STD_HANDLE_FILE;
  1578. } else if (ftype == FILE_TYPE_PIPE) {
  1579. return STD_HANDLE_PIPE;
  1580. } else {
  1581. DWORD conmode = 0;
  1582. BOOL res = GetConsoleMode(h, &conmode);
  1583. if (!res && (GetLastError() == ERROR_INVALID_HANDLE)) {
  1584. return STD_HANDLE_UNKNOWN; // Unknown character device.
  1585. } else {
  1586. return STD_HANDLE_CONSOLE;
  1587. }
  1588. }
  1589. }
  1590. Error OS_Windows::shell_open(const String &p_uri) {
  1591. INT_PTR ret = (INT_PTR)ShellExecuteW(nullptr, nullptr, (LPCWSTR)(p_uri.utf16().get_data()), nullptr, nullptr, SW_SHOWNORMAL);
  1592. if (ret > 32) {
  1593. return OK;
  1594. } else {
  1595. switch (ret) {
  1596. case ERROR_FILE_NOT_FOUND:
  1597. case SE_ERR_DLLNOTFOUND:
  1598. return ERR_FILE_NOT_FOUND;
  1599. case ERROR_PATH_NOT_FOUND:
  1600. return ERR_FILE_BAD_PATH;
  1601. case ERROR_BAD_FORMAT:
  1602. return ERR_FILE_CORRUPT;
  1603. case SE_ERR_ACCESSDENIED:
  1604. return ERR_UNAUTHORIZED;
  1605. case 0:
  1606. case SE_ERR_OOM:
  1607. return ERR_OUT_OF_MEMORY;
  1608. default:
  1609. return FAILED;
  1610. }
  1611. }
  1612. }
  1613. Error OS_Windows::shell_show_in_file_manager(String p_path, bool p_open_folder) {
  1614. bool open_folder = false;
  1615. if (DirAccess::dir_exists_absolute(p_path) && p_open_folder) {
  1616. open_folder = true;
  1617. }
  1618. if (!p_path.is_quoted()) {
  1619. p_path = p_path.quote();
  1620. }
  1621. p_path = fix_path(p_path);
  1622. INT_PTR ret = OK;
  1623. if (open_folder) {
  1624. ret = (INT_PTR)ShellExecuteW(nullptr, nullptr, L"explorer.exe", LPCWSTR(p_path.utf16().get_data()), nullptr, SW_SHOWNORMAL);
  1625. } else {
  1626. ret = (INT_PTR)ShellExecuteW(nullptr, nullptr, L"explorer.exe", LPCWSTR((String("/select,") + p_path).utf16().get_data()), nullptr, SW_SHOWNORMAL);
  1627. }
  1628. if (ret > 32) {
  1629. return OK;
  1630. } else {
  1631. switch (ret) {
  1632. case ERROR_FILE_NOT_FOUND:
  1633. case SE_ERR_DLLNOTFOUND:
  1634. return ERR_FILE_NOT_FOUND;
  1635. case ERROR_PATH_NOT_FOUND:
  1636. return ERR_FILE_BAD_PATH;
  1637. case ERROR_BAD_FORMAT:
  1638. return ERR_FILE_CORRUPT;
  1639. case SE_ERR_ACCESSDENIED:
  1640. return ERR_UNAUTHORIZED;
  1641. case 0:
  1642. case SE_ERR_OOM:
  1643. return ERR_OUT_OF_MEMORY;
  1644. default:
  1645. return FAILED;
  1646. }
  1647. }
  1648. }
  1649. String OS_Windows::get_locale() const {
  1650. const _WinLocale *wl = &_win_locales[0];
  1651. LANGID langid = GetUserDefaultUILanguage();
  1652. String neutral;
  1653. int lang = PRIMARYLANGID(langid);
  1654. int sublang = SUBLANGID(langid);
  1655. while (wl->locale) {
  1656. if (wl->main_lang == lang && wl->sublang == SUBLANG_NEUTRAL) {
  1657. neutral = wl->locale;
  1658. }
  1659. if (lang == wl->main_lang && sublang == wl->sublang) {
  1660. return String(wl->locale).replace("-", "_");
  1661. }
  1662. wl++;
  1663. }
  1664. if (!neutral.is_empty()) {
  1665. return String(neutral).replace("-", "_");
  1666. }
  1667. return "en";
  1668. }
  1669. String OS_Windows::get_model_name() const {
  1670. HKEY hkey;
  1671. if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"Hardware\\Description\\System\\BIOS", 0, KEY_QUERY_VALUE, &hkey) != ERROR_SUCCESS) {
  1672. return OS::get_model_name();
  1673. }
  1674. String sys_name;
  1675. String board_name;
  1676. WCHAR buffer[256];
  1677. DWORD buffer_len = 256;
  1678. DWORD vtype = REG_SZ;
  1679. if (RegQueryValueExW(hkey, L"SystemProductName", nullptr, &vtype, (LPBYTE)buffer, &buffer_len) == ERROR_SUCCESS && buffer_len != 0) {
  1680. sys_name = String::utf16((const char16_t *)buffer, buffer_len).strip_edges();
  1681. }
  1682. buffer_len = 256;
  1683. if (RegQueryValueExW(hkey, L"BaseBoardProduct", nullptr, &vtype, (LPBYTE)buffer, &buffer_len) == ERROR_SUCCESS && buffer_len != 0) {
  1684. board_name = String::utf16((const char16_t *)buffer, buffer_len).strip_edges();
  1685. }
  1686. RegCloseKey(hkey);
  1687. if (!sys_name.is_empty() && sys_name.to_lower() != "system product name") {
  1688. return sys_name;
  1689. }
  1690. if (!board_name.is_empty() && board_name.to_lower() != "base board product") {
  1691. return board_name;
  1692. }
  1693. return OS::get_model_name();
  1694. }
  1695. String OS_Windows::get_processor_name() const {
  1696. const String id = "Hardware\\Description\\System\\CentralProcessor\\0";
  1697. HKEY hkey;
  1698. if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, (LPCWSTR)(id.utf16().get_data()), 0, KEY_QUERY_VALUE, &hkey) != ERROR_SUCCESS) {
  1699. ERR_FAIL_V_MSG("", String("Couldn't get the CPU model name. Returning an empty string."));
  1700. }
  1701. WCHAR buffer[256];
  1702. DWORD buffer_len = 256;
  1703. DWORD vtype = REG_SZ;
  1704. if (RegQueryValueExW(hkey, L"ProcessorNameString", nullptr, &vtype, (LPBYTE)buffer, &buffer_len) == ERROR_SUCCESS) {
  1705. RegCloseKey(hkey);
  1706. return String::utf16((const char16_t *)buffer, buffer_len).strip_edges();
  1707. } else {
  1708. RegCloseKey(hkey);
  1709. ERR_FAIL_V_MSG("", String("Couldn't get the CPU model name. Returning an empty string."));
  1710. }
  1711. }
  1712. void OS_Windows::run() {
  1713. if (!main_loop) {
  1714. return;
  1715. }
  1716. main_loop->initialize();
  1717. while (true) {
  1718. DisplayServer::get_singleton()->process_events(); // get rid of pending events
  1719. if (Main::iteration()) {
  1720. break;
  1721. }
  1722. }
  1723. main_loop->finalize();
  1724. }
  1725. MainLoop *OS_Windows::get_main_loop() const {
  1726. return main_loop;
  1727. }
  1728. uint64_t OS_Windows::get_embedded_pck_offset() const {
  1729. Ref<FileAccess> f = FileAccess::open(get_executable_path(), FileAccess::READ);
  1730. if (f.is_null()) {
  1731. return 0;
  1732. }
  1733. // Process header.
  1734. {
  1735. f->seek(0x3c);
  1736. uint32_t pe_pos = f->get_32();
  1737. f->seek(pe_pos);
  1738. uint32_t magic = f->get_32();
  1739. if (magic != 0x00004550) {
  1740. return 0;
  1741. }
  1742. }
  1743. int num_sections;
  1744. {
  1745. int64_t header_pos = f->get_position();
  1746. f->seek(header_pos + 2);
  1747. num_sections = f->get_16();
  1748. f->seek(header_pos + 16);
  1749. uint16_t opt_header_size = f->get_16();
  1750. // Skip rest of header + optional header to go to the section headers.
  1751. f->seek(f->get_position() + 2 + opt_header_size);
  1752. }
  1753. int64_t section_table_pos = f->get_position();
  1754. // Search for the "pck" section.
  1755. int64_t off = 0;
  1756. for (int i = 0; i < num_sections; ++i) {
  1757. int64_t section_header_pos = section_table_pos + i * 40;
  1758. f->seek(section_header_pos);
  1759. uint8_t section_name[9];
  1760. f->get_buffer(section_name, 8);
  1761. section_name[8] = '\0';
  1762. if (strcmp((char *)section_name, "pck") == 0) {
  1763. f->seek(section_header_pos + 20);
  1764. off = f->get_32();
  1765. break;
  1766. }
  1767. }
  1768. return off;
  1769. }
  1770. String OS_Windows::get_config_path() const {
  1771. if (has_environment("APPDATA")) {
  1772. return get_environment("APPDATA").replace("\\", "/");
  1773. }
  1774. return ".";
  1775. }
  1776. String OS_Windows::get_data_path() const {
  1777. return get_config_path();
  1778. }
  1779. String OS_Windows::get_cache_path() const {
  1780. static String cache_path_cache;
  1781. if (cache_path_cache.is_empty()) {
  1782. if (has_environment("LOCALAPPDATA")) {
  1783. cache_path_cache = get_environment("LOCALAPPDATA").replace("\\", "/");
  1784. }
  1785. if (cache_path_cache.is_empty() && has_environment("TEMP")) {
  1786. cache_path_cache = get_environment("TEMP").replace("\\", "/");
  1787. }
  1788. if (cache_path_cache.is_empty()) {
  1789. cache_path_cache = get_config_path();
  1790. }
  1791. }
  1792. return cache_path_cache;
  1793. }
  1794. // Get properly capitalized engine name for system paths
  1795. String OS_Windows::get_godot_dir_name() const {
  1796. return String(VERSION_SHORT_NAME).capitalize();
  1797. }
  1798. String OS_Windows::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  1799. KNOWNFOLDERID id;
  1800. switch (p_dir) {
  1801. case SYSTEM_DIR_DESKTOP: {
  1802. id = FOLDERID_Desktop;
  1803. } break;
  1804. case SYSTEM_DIR_DCIM: {
  1805. id = FOLDERID_Pictures;
  1806. } break;
  1807. case SYSTEM_DIR_DOCUMENTS: {
  1808. id = FOLDERID_Documents;
  1809. } break;
  1810. case SYSTEM_DIR_DOWNLOADS: {
  1811. id = FOLDERID_Downloads;
  1812. } break;
  1813. case SYSTEM_DIR_MOVIES: {
  1814. id = FOLDERID_Videos;
  1815. } break;
  1816. case SYSTEM_DIR_MUSIC: {
  1817. id = FOLDERID_Music;
  1818. } break;
  1819. case SYSTEM_DIR_PICTURES: {
  1820. id = FOLDERID_Pictures;
  1821. } break;
  1822. case SYSTEM_DIR_RINGTONES: {
  1823. id = FOLDERID_Music;
  1824. } break;
  1825. }
  1826. PWSTR szPath;
  1827. HRESULT res = SHGetKnownFolderPath(id, 0, nullptr, &szPath);
  1828. ERR_FAIL_COND_V(res != S_OK, String());
  1829. String path = String::utf16((const char16_t *)szPath).replace("\\", "/");
  1830. CoTaskMemFree(szPath);
  1831. return path;
  1832. }
  1833. String OS_Windows::get_user_data_dir() const {
  1834. String appname = get_safe_dir_name(GLOBAL_GET("application/config/name"));
  1835. if (!appname.is_empty()) {
  1836. bool use_custom_dir = GLOBAL_GET("application/config/use_custom_user_dir");
  1837. if (use_custom_dir) {
  1838. String custom_dir = get_safe_dir_name(GLOBAL_GET("application/config/custom_user_dir_name"), true);
  1839. if (custom_dir.is_empty()) {
  1840. custom_dir = appname;
  1841. }
  1842. return get_data_path().path_join(custom_dir).replace("\\", "/");
  1843. } else {
  1844. return get_data_path().path_join(get_godot_dir_name()).path_join("app_userdata").path_join(appname).replace("\\", "/");
  1845. }
  1846. }
  1847. return get_data_path().path_join(get_godot_dir_name()).path_join("app_userdata").path_join("[unnamed project]");
  1848. }
  1849. String OS_Windows::get_unique_id() const {
  1850. HW_PROFILE_INFOA HwProfInfo;
  1851. ERR_FAIL_COND_V(!GetCurrentHwProfileA(&HwProfInfo), "");
  1852. return String((HwProfInfo.szHwProfileGuid), HW_PROFILE_GUIDLEN);
  1853. }
  1854. bool OS_Windows::_check_internal_feature_support(const String &p_feature) {
  1855. if (p_feature == "system_fonts") {
  1856. return dwrite_init;
  1857. }
  1858. if (p_feature == "pc") {
  1859. return true;
  1860. }
  1861. return false;
  1862. }
  1863. void OS_Windows::disable_crash_handler() {
  1864. crash_handler.disable();
  1865. }
  1866. bool OS_Windows::is_disable_crash_handler() const {
  1867. return crash_handler.is_disabled();
  1868. }
  1869. Error OS_Windows::move_to_trash(const String &p_path) {
  1870. SHFILEOPSTRUCTW sf;
  1871. Char16String utf16 = p_path.utf16();
  1872. WCHAR *from = new WCHAR[utf16.length() + 2];
  1873. wcscpy_s(from, utf16.length() + 1, (LPCWSTR)(utf16.get_data()));
  1874. from[utf16.length() + 1] = 0;
  1875. sf.hwnd = main_window;
  1876. sf.wFunc = FO_DELETE;
  1877. sf.pFrom = from;
  1878. sf.pTo = nullptr;
  1879. sf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;
  1880. sf.fAnyOperationsAborted = FALSE;
  1881. sf.hNameMappings = nullptr;
  1882. sf.lpszProgressTitle = nullptr;
  1883. int ret = SHFileOperationW(&sf);
  1884. delete[] from;
  1885. if (ret) {
  1886. ERR_PRINT("SHFileOperation error: " + itos(ret));
  1887. return FAILED;
  1888. }
  1889. return OK;
  1890. }
  1891. String OS_Windows::get_system_ca_certificates() {
  1892. HCERTSTORE cert_store = CertOpenSystemStoreA(0, "ROOT");
  1893. ERR_FAIL_NULL_V_MSG(cert_store, "", "Failed to read the root certificate store.");
  1894. FILETIME curr_time;
  1895. GetSystemTimeAsFileTime(&curr_time);
  1896. String certs;
  1897. PCCERT_CONTEXT curr = CertEnumCertificatesInStore(cert_store, nullptr);
  1898. while (curr) {
  1899. FILETIME ft;
  1900. DWORD size = sizeof(ft);
  1901. // Check if the certificate is disallowed.
  1902. if (CertGetCertificateContextProperty(curr, CERT_DISALLOWED_FILETIME_PROP_ID, &ft, &size) && CompareFileTime(&curr_time, &ft) != -1) {
  1903. curr = CertEnumCertificatesInStore(cert_store, curr);
  1904. continue;
  1905. }
  1906. // Encode and add to certificate list.
  1907. bool success = CryptBinaryToStringA(curr->pbCertEncoded, curr->cbCertEncoded, CRYPT_STRING_BASE64HEADER | CRYPT_STRING_NOCR, nullptr, &size);
  1908. ERR_CONTINUE(!success);
  1909. PackedByteArray pba;
  1910. pba.resize(size);
  1911. CryptBinaryToStringA(curr->pbCertEncoded, curr->cbCertEncoded, CRYPT_STRING_BASE64HEADER | CRYPT_STRING_NOCR, (char *)pba.ptrw(), &size);
  1912. certs += String((char *)pba.ptr(), size);
  1913. curr = CertEnumCertificatesInStore(cert_store, curr);
  1914. }
  1915. CertCloseStore(cert_store, 0);
  1916. return certs;
  1917. }
  1918. OS_Windows::OS_Windows(HINSTANCE _hInstance) {
  1919. hInstance = _hInstance;
  1920. // Reset CWD to ensure long path is used.
  1921. Char16String current_dir_name;
  1922. size_t str_len = GetCurrentDirectoryW(0, nullptr);
  1923. current_dir_name.resize(str_len + 1);
  1924. GetCurrentDirectoryW(current_dir_name.size(), (LPWSTR)current_dir_name.ptrw());
  1925. Char16String new_current_dir_name;
  1926. str_len = GetLongPathNameW((LPCWSTR)current_dir_name.get_data(), nullptr, 0);
  1927. new_current_dir_name.resize(str_len + 1);
  1928. GetLongPathNameW((LPCWSTR)current_dir_name.get_data(), (LPWSTR)new_current_dir_name.ptrw(), new_current_dir_name.size());
  1929. SetCurrentDirectoryW((LPCWSTR)new_current_dir_name.get_data());
  1930. #ifndef WINDOWS_SUBSYSTEM_CONSOLE
  1931. RedirectIOToConsole();
  1932. #endif
  1933. SetConsoleOutputCP(CP_UTF8);
  1934. SetConsoleCP(CP_UTF8);
  1935. CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
  1936. #ifdef WASAPI_ENABLED
  1937. AudioDriverManager::add_driver(&driver_wasapi);
  1938. #endif
  1939. #ifdef XAUDIO2_ENABLED
  1940. AudioDriverManager::add_driver(&driver_xaudio2);
  1941. #endif
  1942. DisplayServerWindows::register_windows_driver();
  1943. // Enable ANSI escape code support on Windows 10 v1607 (Anniversary Update) and later.
  1944. // This lets the engine and projects use ANSI escape codes to color text just like on macOS and Linux.
  1945. //
  1946. // NOTE: The engine does not use ANSI escape codes to color error/warning messages; it uses Windows API calls instead.
  1947. // Therefore, error/warning messages are still colored on Windows versions older than 10.
  1948. HANDLE stdoutHandle = GetStdHandle(STD_OUTPUT_HANDLE);
  1949. DWORD outMode = 0;
  1950. GetConsoleMode(stdoutHandle, &outMode);
  1951. outMode |= ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING;
  1952. if (!SetConsoleMode(stdoutHandle, outMode)) {
  1953. // Windows 8.1 or below, or Windows 10 prior to Anniversary Update.
  1954. print_verbose("Can't set the ENABLE_VIRTUAL_TERMINAL_PROCESSING Windows console mode. `print_rich()` will not work as expected.");
  1955. }
  1956. Vector<Logger *> loggers;
  1957. loggers.push_back(memnew(WindowsTerminalLogger));
  1958. _set_logger(memnew(CompositeLogger(loggers)));
  1959. }
  1960. OS_Windows::~OS_Windows() {
  1961. CoUninitialize();
  1962. }