os_windows.cpp 92 KB

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