2
0

os_windows.cpp 46 KB

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