os_windows.cpp 38 KB

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