os_windows.cpp 78 KB

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