os_windows.cpp 85 KB

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