2
0

os_windows.cpp 53 KB

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