os_windows.cpp 64 KB

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