os_windows.cpp 84 KB

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