os_windows.cpp 75 KB

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