os_windows.cpp 85 KB

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