os_windows.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  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. extern "C" {
  54. __declspec(dllexport) DWORD NvOptimusEnablement = 1;
  55. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  56. }
  57. // Workaround mingw-w64 < 4.0 bug
  58. #ifndef WM_TOUCH
  59. #define WM_TOUCH 576
  60. #endif
  61. #ifndef WM_POINTERUPDATE
  62. #define WM_POINTERUPDATE 0x0245
  63. #endif
  64. #if defined(__GNUC__)
  65. // Workaround GCC warning from -Wcast-function-type.
  66. #define GetProcAddress (void *)GetProcAddress
  67. #endif
  68. static String format_error_message(DWORD id) {
  69. LPWSTR messageBuffer = nullptr;
  70. size_t size = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  71. nullptr, id, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&messageBuffer, 0, nullptr);
  72. String msg = "Error " + itos(id) + ": " + String::utf16((const char16_t *)messageBuffer, size);
  73. LocalFree(messageBuffer);
  74. return msg;
  75. }
  76. void RedirectStream(const char *p_file_name, const char *p_mode, FILE *p_cpp_stream, const DWORD p_std_handle) {
  77. const HANDLE h_existing = GetStdHandle(p_std_handle);
  78. if (h_existing != INVALID_HANDLE_VALUE) { // Redirect only if attached console have a valid handle.
  79. const HANDLE h_cpp = reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(p_cpp_stream)));
  80. if (h_cpp == INVALID_HANDLE_VALUE) { // Redirect only if it's not already redirected to the pipe or file.
  81. FILE *fp = p_cpp_stream;
  82. freopen_s(&fp, p_file_name, p_mode, p_cpp_stream); // Redirect stream.
  83. setvbuf(p_cpp_stream, nullptr, _IONBF, 0); // Disable stream buffering.
  84. }
  85. }
  86. }
  87. void RedirectIOToConsole() {
  88. if (AttachConsole(ATTACH_PARENT_PROCESS)) {
  89. RedirectStream("CONIN$", "r", stdin, STD_INPUT_HANDLE);
  90. RedirectStream("CONOUT$", "w", stdout, STD_OUTPUT_HANDLE);
  91. RedirectStream("CONOUT$", "w", stderr, STD_ERROR_HANDLE);
  92. printf("\n"); // Make sure our output is starting from the new line.
  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. OS::Date OS_Windows::get_date(bool p_utc) const {
  240. SYSTEMTIME systemtime;
  241. if (p_utc) {
  242. GetSystemTime(&systemtime);
  243. } else {
  244. GetLocalTime(&systemtime);
  245. }
  246. //Get DST information from Windows, but only if p_utc is false.
  247. TIME_ZONE_INFORMATION info;
  248. bool daylight = false;
  249. if (!p_utc && GetTimeZoneInformation(&info) == TIME_ZONE_ID_DAYLIGHT) {
  250. daylight = true;
  251. }
  252. Date date;
  253. date.day = systemtime.wDay;
  254. date.month = Month(systemtime.wMonth);
  255. date.weekday = Weekday(systemtime.wDayOfWeek);
  256. date.year = systemtime.wYear;
  257. date.dst = daylight;
  258. return date;
  259. }
  260. OS::Time OS_Windows::get_time(bool p_utc) const {
  261. SYSTEMTIME systemtime;
  262. if (p_utc) {
  263. GetSystemTime(&systemtime);
  264. } else {
  265. GetLocalTime(&systemtime);
  266. }
  267. Time time;
  268. time.hour = systemtime.wHour;
  269. time.minute = systemtime.wMinute;
  270. time.second = systemtime.wSecond;
  271. return time;
  272. }
  273. OS::TimeZoneInfo OS_Windows::get_time_zone_info() const {
  274. TIME_ZONE_INFORMATION info;
  275. bool daylight = false;
  276. if (GetTimeZoneInformation(&info) == TIME_ZONE_ID_DAYLIGHT) {
  277. daylight = true;
  278. }
  279. // Daylight Bias needs to be added to the bias if DST is in effect, or else it will not properly update.
  280. TimeZoneInfo ret;
  281. if (daylight) {
  282. ret.name = info.DaylightName;
  283. ret.bias = info.Bias + info.DaylightBias;
  284. } else {
  285. ret.name = info.StandardName;
  286. ret.bias = info.Bias + info.StandardBias;
  287. }
  288. // Bias value returned by GetTimeZoneInformation is inverted of what we expect
  289. // For example, on GMT-3 GetTimeZoneInformation return a Bias of 180, so invert the value to get -180
  290. ret.bias = -ret.bias;
  291. return ret;
  292. }
  293. double OS_Windows::get_unix_time() const {
  294. // 1 Windows tick is 100ns
  295. const uint64_t WINDOWS_TICKS_PER_SECOND = 10000000;
  296. const uint64_t TICKS_TO_UNIX_EPOCH = 116444736000000000LL;
  297. SYSTEMTIME st;
  298. GetSystemTime(&st);
  299. FILETIME ft;
  300. SystemTimeToFileTime(&st, &ft);
  301. uint64_t ticks_time;
  302. ticks_time = ft.dwHighDateTime;
  303. ticks_time <<= 32;
  304. ticks_time |= ft.dwLowDateTime;
  305. return (double)(ticks_time - TICKS_TO_UNIX_EPOCH) / WINDOWS_TICKS_PER_SECOND;
  306. }
  307. void OS_Windows::delay_usec(uint32_t p_usec) const {
  308. if (p_usec < 1000) {
  309. Sleep(1);
  310. } else {
  311. Sleep(p_usec / 1000);
  312. }
  313. }
  314. uint64_t OS_Windows::get_ticks_usec() const {
  315. uint64_t ticks;
  316. // This is the number of clock ticks since start
  317. QueryPerformanceCounter((LARGE_INTEGER *)&ticks);
  318. // Subtract the ticks at game start to get
  319. // the ticks since the game started
  320. ticks -= ticks_start;
  321. // Divide by frequency to get the time in seconds
  322. // original calculation shown below is subject to overflow
  323. // with high ticks_per_second and a number of days since the last reboot.
  324. // time = ticks * 1000000L / ticks_per_second;
  325. // we can prevent this by either using 128 bit math
  326. // or separating into a calculation for seconds, and the fraction
  327. uint64_t seconds = ticks / ticks_per_second;
  328. // compiler will optimize these two into one divide
  329. uint64_t leftover = ticks % ticks_per_second;
  330. // remainder
  331. uint64_t time = (leftover * 1000000L) / ticks_per_second;
  332. // seconds
  333. time += seconds * 1000000L;
  334. return time;
  335. }
  336. String OS_Windows::_quote_command_line_argument(const String &p_text) const {
  337. for (int i = 0; i < p_text.size(); i++) {
  338. char32_t c = p_text[i];
  339. if (c == ' ' || c == '&' || c == '(' || c == ')' || c == '[' || c == ']' || c == '{' || c == '}' || c == '^' || c == '=' || c == ';' || c == '!' || c == '\'' || c == '+' || c == ',' || c == '`' || c == '~') {
  340. return "\"" + p_text + "\"";
  341. }
  342. }
  343. return p_text;
  344. }
  345. static void _append_to_pipe(char *p_bytes, int p_size, String *r_pipe, Mutex *p_pipe_mutex) {
  346. // Try to convert from default ANSI code page to Unicode.
  347. LocalVector<wchar_t> wchars;
  348. int total_wchars = MultiByteToWideChar(CP_ACP, 0, p_bytes, p_size, nullptr, 0);
  349. if (total_wchars > 0) {
  350. wchars.resize(total_wchars);
  351. if (MultiByteToWideChar(CP_ACP, 0, p_bytes, p_size, wchars.ptr(), total_wchars) == 0) {
  352. wchars.clear();
  353. }
  354. }
  355. if (p_pipe_mutex) {
  356. p_pipe_mutex->lock();
  357. }
  358. if (wchars.is_empty()) {
  359. // Let's hope it's compatible with UTF-8.
  360. (*r_pipe) += String::utf8(p_bytes, p_size);
  361. } else {
  362. (*r_pipe) += String(wchars.ptr(), total_wchars);
  363. }
  364. if (p_pipe_mutex) {
  365. p_pipe_mutex->unlock();
  366. }
  367. }
  368. 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) {
  369. String path = p_path.replace("/", "\\");
  370. String command = _quote_command_line_argument(path);
  371. for (const String &E : p_arguments) {
  372. command += " " + _quote_command_line_argument(E);
  373. }
  374. ProcessInfo pi;
  375. ZeroMemory(&pi.si, sizeof(pi.si));
  376. pi.si.cb = sizeof(pi.si);
  377. ZeroMemory(&pi.pi, sizeof(pi.pi));
  378. LPSTARTUPINFOW si_w = (LPSTARTUPINFOW)&pi.si;
  379. bool inherit_handles = false;
  380. HANDLE pipe[2] = { nullptr, nullptr };
  381. if (r_pipe) {
  382. // Create pipe for StdOut and StdErr.
  383. SECURITY_ATTRIBUTES sa;
  384. sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  385. sa.bInheritHandle = true;
  386. sa.lpSecurityDescriptor = nullptr;
  387. ERR_FAIL_COND_V(!CreatePipe(&pipe[0], &pipe[1], &sa, 0), ERR_CANT_FORK);
  388. 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.
  389. pi.si.dwFlags |= STARTF_USESTDHANDLES;
  390. pi.si.hStdOutput = pipe[1];
  391. if (read_stderr) {
  392. pi.si.hStdError = pipe[1];
  393. }
  394. inherit_handles = true;
  395. }
  396. DWORD creation_flags = NORMAL_PRIORITY_CLASS;
  397. if (p_open_console) {
  398. creation_flags |= CREATE_NEW_CONSOLE;
  399. } else {
  400. creation_flags |= CREATE_NO_WINDOW;
  401. }
  402. int ret = CreateProcessW(nullptr, (LPWSTR)(command.utf16().ptrw()), nullptr, nullptr, inherit_handles, creation_flags, nullptr, nullptr, si_w, &pi.pi);
  403. if (!ret && r_pipe) {
  404. CloseHandle(pipe[0]); // Cleanup pipe handles.
  405. CloseHandle(pipe[1]);
  406. }
  407. ERR_FAIL_COND_V_MSG(ret == 0, ERR_CANT_FORK, "Could not create child process: " + command);
  408. if (r_pipe) {
  409. CloseHandle(pipe[1]); // Close pipe write handle (only child process is writing).
  410. LocalVector<char> bytes;
  411. int bytes_in_buffer = 0;
  412. const int CHUNK_SIZE = 4096;
  413. DWORD read = 0;
  414. for (;;) { // Read StdOut and StdErr from pipe.
  415. bytes.resize(bytes_in_buffer + CHUNK_SIZE);
  416. const bool success = ReadFile(pipe[0], bytes.ptr() + bytes_in_buffer, CHUNK_SIZE, &read, NULL);
  417. if (!success || read == 0) {
  418. break;
  419. }
  420. // Assume that all possible encodings are ASCII-compatible.
  421. // Break at newline to allow receiving long output in portions.
  422. int newline_index = -1;
  423. for (int i = read - 1; i >= 0; i--) {
  424. if (bytes[bytes_in_buffer + i] == '\n') {
  425. newline_index = i;
  426. break;
  427. }
  428. }
  429. if (newline_index == -1) {
  430. bytes_in_buffer += read;
  431. continue;
  432. }
  433. const int bytes_to_convert = bytes_in_buffer + (newline_index + 1);
  434. _append_to_pipe(bytes.ptr(), bytes_to_convert, r_pipe, p_pipe_mutex);
  435. bytes_in_buffer = read - (newline_index + 1);
  436. memmove(bytes.ptr(), bytes.ptr() + bytes_to_convert, bytes_in_buffer);
  437. }
  438. if (bytes_in_buffer > 0) {
  439. _append_to_pipe(bytes.ptr(), bytes_in_buffer, r_pipe, p_pipe_mutex);
  440. }
  441. CloseHandle(pipe[0]); // Close pipe read handle.
  442. } else {
  443. WaitForSingleObject(pi.pi.hProcess, INFINITE);
  444. }
  445. if (r_exitcode) {
  446. DWORD ret2;
  447. GetExitCodeProcess(pi.pi.hProcess, &ret2);
  448. *r_exitcode = ret2;
  449. }
  450. CloseHandle(pi.pi.hProcess);
  451. CloseHandle(pi.pi.hThread);
  452. return OK;
  453. }
  454. Error OS_Windows::create_process(const String &p_path, const List<String> &p_arguments, ProcessID *r_child_id, bool p_open_console) {
  455. String path = p_path.replace("/", "\\");
  456. String command = _quote_command_line_argument(path);
  457. for (const String &E : p_arguments) {
  458. command += " " + _quote_command_line_argument(E);
  459. }
  460. ProcessInfo pi;
  461. ZeroMemory(&pi.si, sizeof(pi.si));
  462. pi.si.cb = sizeof(pi.si);
  463. ZeroMemory(&pi.pi, sizeof(pi.pi));
  464. LPSTARTUPINFOW si_w = (LPSTARTUPINFOW)&pi.si;
  465. DWORD creation_flags = NORMAL_PRIORITY_CLASS;
  466. if (p_open_console) {
  467. creation_flags |= CREATE_NEW_CONSOLE;
  468. } else {
  469. creation_flags |= CREATE_NO_WINDOW;
  470. }
  471. int ret = CreateProcessW(nullptr, (LPWSTR)(command.utf16().ptrw()), nullptr, nullptr, false, creation_flags, nullptr, nullptr, si_w, &pi.pi);
  472. ERR_FAIL_COND_V_MSG(ret == 0, ERR_CANT_FORK, "Could not create child process: " + command);
  473. ProcessID pid = pi.pi.dwProcessId;
  474. if (r_child_id) {
  475. *r_child_id = pid;
  476. }
  477. process_map->insert(pid, pi);
  478. return OK;
  479. }
  480. Error OS_Windows::kill(const ProcessID &p_pid) {
  481. ERR_FAIL_COND_V(!process_map->has(p_pid), FAILED);
  482. const PROCESS_INFORMATION pi = (*process_map)[p_pid].pi;
  483. process_map->erase(p_pid);
  484. const int ret = TerminateProcess(pi.hProcess, 0);
  485. CloseHandle(pi.hProcess);
  486. CloseHandle(pi.hThread);
  487. return ret != 0 ? OK : FAILED;
  488. }
  489. int OS_Windows::get_process_id() const {
  490. return _getpid();
  491. }
  492. bool OS_Windows::is_process_running(const ProcessID &p_pid) const {
  493. if (!process_map->has(p_pid)) {
  494. return false;
  495. }
  496. const PROCESS_INFORMATION &pi = (*process_map)[p_pid].pi;
  497. DWORD dw_exit_code = 0;
  498. if (!GetExitCodeProcess(pi.hProcess, &dw_exit_code)) {
  499. return false;
  500. }
  501. if (dw_exit_code != STILL_ACTIVE) {
  502. return false;
  503. }
  504. return true;
  505. }
  506. Error OS_Windows::set_cwd(const String &p_cwd) {
  507. if (_wchdir((LPCWSTR)(p_cwd.utf16().get_data())) != 0) {
  508. return ERR_CANT_OPEN;
  509. }
  510. return OK;
  511. }
  512. Vector<String> OS_Windows::get_system_fonts() const {
  513. Vector<String> ret;
  514. HashSet<String> font_names;
  515. ComAutoreleaseRef<IDWriteFactory> dwrite_factory;
  516. HRESULT hr = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), reinterpret_cast<IUnknown **>(&dwrite_factory.reference));
  517. ERR_FAIL_COND_V(FAILED(hr) || dwrite_factory.is_null(), ret);
  518. ComAutoreleaseRef<IDWriteFontCollection> font_collection;
  519. hr = dwrite_factory->GetSystemFontCollection(&font_collection.reference, false);
  520. ERR_FAIL_COND_V(FAILED(hr) || font_collection.is_null(), ret);
  521. UINT32 family_count = font_collection->GetFontFamilyCount();
  522. for (UINT32 i = 0; i < family_count; i++) {
  523. ComAutoreleaseRef<IDWriteFontFamily> family;
  524. hr = font_collection->GetFontFamily(i, &family.reference);
  525. ERR_CONTINUE(FAILED(hr) || family.is_null());
  526. ComAutoreleaseRef<IDWriteLocalizedStrings> family_names;
  527. hr = family->GetFamilyNames(&family_names.reference);
  528. ERR_CONTINUE(FAILED(hr) || family_names.is_null());
  529. UINT32 index = 0;
  530. BOOL exists = false;
  531. UINT32 length = 0;
  532. Char16String name;
  533. hr = family_names->FindLocaleName(L"en-us", &index, &exists);
  534. ERR_CONTINUE(FAILED(hr));
  535. hr = family_names->GetStringLength(index, &length);
  536. ERR_CONTINUE(FAILED(hr));
  537. name.resize(length + 1);
  538. hr = family_names->GetString(index, (WCHAR *)name.ptrw(), length + 1);
  539. ERR_CONTINUE(FAILED(hr));
  540. font_names.insert(String::utf16(name.ptr(), length));
  541. }
  542. for (const String &E : font_names) {
  543. ret.push_back(E);
  544. }
  545. return ret;
  546. }
  547. String OS_Windows::get_system_font_path(const String &p_font_name, bool p_bold, bool p_italic) const {
  548. String font_name = p_font_name;
  549. if (font_name.to_lower() == "sans-serif") {
  550. font_name = "Arial";
  551. } else if (font_name.to_lower() == "serif") {
  552. font_name = "Times New Roman";
  553. } else if (font_name.to_lower() == "monospace") {
  554. font_name = "Courier New";
  555. } else if (font_name.to_lower() == "cursive") {
  556. font_name = "Comic Sans MS";
  557. } else if (font_name.to_lower() == "fantasy") {
  558. font_name = "Gabriola";
  559. }
  560. ComAutoreleaseRef<IDWriteFactory> dwrite_factory;
  561. HRESULT hr = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), reinterpret_cast<IUnknown **>(&dwrite_factory.reference));
  562. ERR_FAIL_COND_V(FAILED(hr) || dwrite_factory.is_null(), String());
  563. ComAutoreleaseRef<IDWriteFontCollection> font_collection;
  564. hr = dwrite_factory->GetSystemFontCollection(&font_collection.reference, false);
  565. ERR_FAIL_COND_V(FAILED(hr) || font_collection.is_null(), String());
  566. UINT32 index = 0;
  567. BOOL exists = false;
  568. font_collection->FindFamilyName((const WCHAR *)font_name.utf16().get_data(), &index, &exists);
  569. if (FAILED(hr)) {
  570. return String();
  571. }
  572. ComAutoreleaseRef<IDWriteFontFamily> family;
  573. hr = font_collection->GetFontFamily(index, &family.reference);
  574. if (FAILED(hr) || family.is_null()) {
  575. return String();
  576. }
  577. ComAutoreleaseRef<IDWriteFont> dwrite_font;
  578. 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);
  579. if (FAILED(hr) || dwrite_font.is_null()) {
  580. return String();
  581. }
  582. ComAutoreleaseRef<IDWriteFontFace> dwrite_face;
  583. hr = dwrite_font->CreateFontFace(&dwrite_face.reference);
  584. if (FAILED(hr) || dwrite_face.is_null()) {
  585. return String();
  586. }
  587. UINT32 number_of_files = 0;
  588. hr = dwrite_face->GetFiles(&number_of_files, nullptr);
  589. if (FAILED(hr)) {
  590. return String();
  591. }
  592. Vector<ComAutoreleaseRef<IDWriteFontFile>> files;
  593. files.resize(number_of_files);
  594. hr = dwrite_face->GetFiles(&number_of_files, (IDWriteFontFile **)files.ptrw());
  595. if (FAILED(hr)) {
  596. return String();
  597. }
  598. for (UINT32 i = 0; i < number_of_files; i++) {
  599. void const *reference_key = nullptr;
  600. UINT32 reference_key_size = 0;
  601. ComAutoreleaseRef<IDWriteLocalFontFileLoader> loader;
  602. hr = files.write[i]->GetLoader((IDWriteFontFileLoader **)&loader.reference);
  603. if (FAILED(hr) || loader.is_null()) {
  604. continue;
  605. }
  606. hr = files.write[i]->GetReferenceKey(&reference_key, &reference_key_size);
  607. if (FAILED(hr)) {
  608. continue;
  609. }
  610. WCHAR file_path[MAX_PATH];
  611. hr = loader->GetFilePathFromKey(reference_key, reference_key_size, &file_path[0], MAX_PATH);
  612. if (FAILED(hr)) {
  613. continue;
  614. }
  615. return String::utf16((const char16_t *)&file_path[0]);
  616. }
  617. return String();
  618. }
  619. String OS_Windows::get_executable_path() const {
  620. WCHAR bufname[4096];
  621. GetModuleFileNameW(nullptr, bufname, 4096);
  622. String s = String::utf16((const char16_t *)bufname).replace("\\", "/");
  623. return s;
  624. }
  625. bool OS_Windows::has_environment(const String &p_var) const {
  626. #ifdef MINGW_ENABLED
  627. return _wgetenv((LPCWSTR)(p_var.utf16().get_data())) != nullptr;
  628. #else
  629. WCHAR *env;
  630. size_t len;
  631. _wdupenv_s(&env, &len, (LPCWSTR)(p_var.utf16().get_data()));
  632. const bool has_env = env != nullptr;
  633. free(env);
  634. return has_env;
  635. #endif
  636. }
  637. String OS_Windows::get_environment(const String &p_var) const {
  638. WCHAR wval[0x7fff]; // MSDN says 32767 char is the maximum
  639. int wlen = GetEnvironmentVariableW((LPCWSTR)(p_var.utf16().get_data()), wval, 0x7fff);
  640. if (wlen > 0) {
  641. return String::utf16((const char16_t *)wval);
  642. }
  643. return "";
  644. }
  645. bool OS_Windows::set_environment(const String &p_var, const String &p_value) const {
  646. return (bool)SetEnvironmentVariableW((LPCWSTR)(p_var.utf16().get_data()), (LPCWSTR)(p_value.utf16().get_data()));
  647. }
  648. String OS_Windows::get_stdin_string(bool p_block) {
  649. if (p_block) {
  650. char buff[1024];
  651. return fgets(buff, 1024, stdin);
  652. }
  653. return String();
  654. }
  655. Error OS_Windows::shell_open(String p_uri) {
  656. INT_PTR ret = (INT_PTR)ShellExecuteW(nullptr, nullptr, (LPCWSTR)(p_uri.utf16().get_data()), nullptr, nullptr, SW_SHOWNORMAL);
  657. if (ret > 32) {
  658. return OK;
  659. } else {
  660. switch (ret) {
  661. case ERROR_FILE_NOT_FOUND:
  662. case SE_ERR_DLLNOTFOUND:
  663. return ERR_FILE_NOT_FOUND;
  664. case ERROR_PATH_NOT_FOUND:
  665. return ERR_FILE_BAD_PATH;
  666. case ERROR_BAD_FORMAT:
  667. return ERR_FILE_CORRUPT;
  668. case SE_ERR_ACCESSDENIED:
  669. return ERR_UNAUTHORIZED;
  670. case 0:
  671. case SE_ERR_OOM:
  672. return ERR_OUT_OF_MEMORY;
  673. default:
  674. return FAILED;
  675. }
  676. }
  677. }
  678. String OS_Windows::get_locale() const {
  679. const _WinLocale *wl = &_win_locales[0];
  680. LANGID langid = GetUserDefaultUILanguage();
  681. String neutral;
  682. int lang = PRIMARYLANGID(langid);
  683. int sublang = SUBLANGID(langid);
  684. while (wl->locale) {
  685. if (wl->main_lang == lang && wl->sublang == SUBLANG_NEUTRAL) {
  686. neutral = wl->locale;
  687. }
  688. if (lang == wl->main_lang && sublang == wl->sublang) {
  689. return String(wl->locale).replace("-", "_");
  690. }
  691. wl++;
  692. }
  693. if (!neutral.is_empty()) {
  694. return String(neutral).replace("-", "_");
  695. }
  696. return "en";
  697. }
  698. // We need this because GetSystemInfo() is unreliable on WOW64
  699. // see https://msdn.microsoft.com/en-us/library/windows/desktop/ms724381(v=vs.85).aspx
  700. // Taken from MSDN
  701. typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
  702. LPFN_ISWOW64PROCESS fnIsWow64Process;
  703. BOOL is_wow64() {
  704. BOOL wow64 = FALSE;
  705. fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process");
  706. if (fnIsWow64Process) {
  707. if (!fnIsWow64Process(GetCurrentProcess(), &wow64)) {
  708. wow64 = FALSE;
  709. }
  710. }
  711. return wow64;
  712. }
  713. int OS_Windows::get_processor_count() const {
  714. SYSTEM_INFO sysinfo;
  715. if (is_wow64()) {
  716. GetNativeSystemInfo(&sysinfo);
  717. } else {
  718. GetSystemInfo(&sysinfo);
  719. }
  720. return sysinfo.dwNumberOfProcessors;
  721. }
  722. String OS_Windows::get_processor_name() const {
  723. const String id = "Hardware\\Description\\System\\CentralProcessor\\0";
  724. HKEY hkey;
  725. if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, (LPCWSTR)(id.utf16().get_data()), 0, KEY_QUERY_VALUE, &hkey) != ERROR_SUCCESS) {
  726. ERR_FAIL_V_MSG("", String("Couldn't get the CPU model name. Returning an empty string."));
  727. }
  728. WCHAR buffer[256];
  729. DWORD buffer_len = 256;
  730. DWORD vtype = REG_SZ;
  731. if (RegQueryValueExW(hkey, L"ProcessorNameString", NULL, &vtype, (LPBYTE)buffer, &buffer_len) == ERROR_SUCCESS) {
  732. RegCloseKey(hkey);
  733. return String::utf16((const char16_t *)buffer, buffer_len).strip_edges();
  734. } else {
  735. RegCloseKey(hkey);
  736. ERR_FAIL_V_MSG("", String("Couldn't get the CPU model name. Returning an empty string."));
  737. }
  738. }
  739. void OS_Windows::run() {
  740. if (!main_loop) {
  741. return;
  742. }
  743. main_loop->initialize();
  744. while (true) {
  745. DisplayServer::get_singleton()->process_events(); // get rid of pending events
  746. if (Main::iteration()) {
  747. break;
  748. }
  749. }
  750. main_loop->finalize();
  751. }
  752. MainLoop *OS_Windows::get_main_loop() const {
  753. return main_loop;
  754. }
  755. uint64_t OS_Windows::get_embedded_pck_offset() const {
  756. Ref<FileAccess> f = FileAccess::open(get_executable_path(), FileAccess::READ);
  757. if (f.is_null()) {
  758. return 0;
  759. }
  760. // Process header.
  761. {
  762. f->seek(0x3c);
  763. uint32_t pe_pos = f->get_32();
  764. f->seek(pe_pos);
  765. uint32_t magic = f->get_32();
  766. if (magic != 0x00004550) {
  767. return 0;
  768. }
  769. }
  770. int num_sections;
  771. {
  772. int64_t header_pos = f->get_position();
  773. f->seek(header_pos + 2);
  774. num_sections = f->get_16();
  775. f->seek(header_pos + 16);
  776. uint16_t opt_header_size = f->get_16();
  777. // Skip rest of header + optional header to go to the section headers.
  778. f->seek(f->get_position() + 2 + opt_header_size);
  779. }
  780. int64_t section_table_pos = f->get_position();
  781. // Search for the "pck" section.
  782. int64_t off = 0;
  783. for (int i = 0; i < num_sections; ++i) {
  784. int64_t section_header_pos = section_table_pos + i * 40;
  785. f->seek(section_header_pos);
  786. uint8_t section_name[9];
  787. f->get_buffer(section_name, 8);
  788. section_name[8] = '\0';
  789. if (strcmp((char *)section_name, "pck") == 0) {
  790. f->seek(section_header_pos + 20);
  791. off = f->get_32();
  792. break;
  793. }
  794. }
  795. return off;
  796. }
  797. String OS_Windows::get_config_path() const {
  798. // The XDG Base Directory specification technically only applies on Linux/*BSD, but it doesn't hurt to support it on Windows as well.
  799. if (has_environment("XDG_CONFIG_HOME")) {
  800. if (get_environment("XDG_CONFIG_HOME").is_absolute_path()) {
  801. return get_environment("XDG_CONFIG_HOME").replace("\\", "/");
  802. } else {
  803. 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.");
  804. }
  805. }
  806. if (has_environment("APPDATA")) {
  807. return get_environment("APPDATA").replace("\\", "/");
  808. }
  809. return ".";
  810. }
  811. String OS_Windows::get_data_path() const {
  812. // The XDG Base Directory specification technically only applies on Linux/*BSD, but it doesn't hurt to support it on Windows as well.
  813. if (has_environment("XDG_DATA_HOME")) {
  814. if (get_environment("XDG_DATA_HOME").is_absolute_path()) {
  815. return get_environment("XDG_DATA_HOME").replace("\\", "/");
  816. } else {
  817. 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.");
  818. }
  819. }
  820. return get_config_path();
  821. }
  822. String OS_Windows::get_cache_path() const {
  823. static String cache_path_cache;
  824. if (cache_path_cache.is_empty()) {
  825. // The XDG Base Directory specification technically only applies on Linux/*BSD, but it doesn't hurt to support it on Windows as well.
  826. if (has_environment("XDG_CACHE_HOME")) {
  827. if (get_environment("XDG_CACHE_HOME").is_absolute_path()) {
  828. cache_path_cache = get_environment("XDG_CACHE_HOME").replace("\\", "/");
  829. } else {
  830. 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.");
  831. }
  832. }
  833. if (cache_path_cache.is_empty() && has_environment("LOCALAPPDATA")) {
  834. cache_path_cache = get_environment("LOCALAPPDATA").replace("\\", "/");
  835. }
  836. if (cache_path_cache.is_empty() && has_environment("TEMP")) {
  837. cache_path_cache = get_environment("TEMP").replace("\\", "/");
  838. }
  839. if (cache_path_cache.is_empty()) {
  840. cache_path_cache = get_config_path();
  841. }
  842. }
  843. return cache_path_cache;
  844. }
  845. // Get properly capitalized engine name for system paths
  846. String OS_Windows::get_godot_dir_name() const {
  847. return String(VERSION_SHORT_NAME).capitalize();
  848. }
  849. String OS_Windows::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  850. KNOWNFOLDERID id;
  851. switch (p_dir) {
  852. case SYSTEM_DIR_DESKTOP: {
  853. id = FOLDERID_Desktop;
  854. } break;
  855. case SYSTEM_DIR_DCIM: {
  856. id = FOLDERID_Pictures;
  857. } break;
  858. case SYSTEM_DIR_DOCUMENTS: {
  859. id = FOLDERID_Documents;
  860. } break;
  861. case SYSTEM_DIR_DOWNLOADS: {
  862. id = FOLDERID_Downloads;
  863. } break;
  864. case SYSTEM_DIR_MOVIES: {
  865. id = FOLDERID_Videos;
  866. } break;
  867. case SYSTEM_DIR_MUSIC: {
  868. id = FOLDERID_Music;
  869. } break;
  870. case SYSTEM_DIR_PICTURES: {
  871. id = FOLDERID_Pictures;
  872. } break;
  873. case SYSTEM_DIR_RINGTONES: {
  874. id = FOLDERID_Music;
  875. } break;
  876. }
  877. PWSTR szPath;
  878. HRESULT res = SHGetKnownFolderPath(id, 0, nullptr, &szPath);
  879. ERR_FAIL_COND_V(res != S_OK, String());
  880. String path = String::utf16((const char16_t *)szPath).replace("\\", "/");
  881. CoTaskMemFree(szPath);
  882. return path;
  883. }
  884. String OS_Windows::get_user_data_dir() const {
  885. String appname = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/name"));
  886. if (!appname.is_empty()) {
  887. bool use_custom_dir = ProjectSettings::get_singleton()->get("application/config/use_custom_user_dir");
  888. if (use_custom_dir) {
  889. String custom_dir = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/custom_user_dir_name"), true);
  890. if (custom_dir.is_empty()) {
  891. custom_dir = appname;
  892. }
  893. return get_data_path().path_join(custom_dir).replace("\\", "/");
  894. } else {
  895. return get_data_path().path_join(get_godot_dir_name()).path_join("app_userdata").path_join(appname).replace("\\", "/");
  896. }
  897. }
  898. return get_data_path().path_join(get_godot_dir_name()).path_join("app_userdata").path_join("[unnamed project]");
  899. }
  900. String OS_Windows::get_unique_id() const {
  901. HW_PROFILE_INFOA HwProfInfo;
  902. ERR_FAIL_COND_V(!GetCurrentHwProfileA(&HwProfInfo), "");
  903. return String((HwProfInfo.szHwProfileGuid), HW_PROFILE_GUIDLEN);
  904. }
  905. bool OS_Windows::_check_internal_feature_support(const String &p_feature) {
  906. return p_feature == "pc";
  907. }
  908. void OS_Windows::disable_crash_handler() {
  909. crash_handler.disable();
  910. }
  911. bool OS_Windows::is_disable_crash_handler() const {
  912. return crash_handler.is_disabled();
  913. }
  914. Error OS_Windows::move_to_trash(const String &p_path) {
  915. SHFILEOPSTRUCTW sf;
  916. Char16String utf16 = p_path.utf16();
  917. WCHAR *from = new WCHAR[utf16.length() + 2];
  918. wcscpy_s(from, utf16.length() + 1, (LPCWSTR)(utf16.get_data()));
  919. from[utf16.length() + 1] = 0;
  920. sf.hwnd = main_window;
  921. sf.wFunc = FO_DELETE;
  922. sf.pFrom = from;
  923. sf.pTo = nullptr;
  924. sf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;
  925. sf.fAnyOperationsAborted = FALSE;
  926. sf.hNameMappings = nullptr;
  927. sf.lpszProgressTitle = nullptr;
  928. int ret = SHFileOperationW(&sf);
  929. delete[] from;
  930. if (ret) {
  931. ERR_PRINT("SHFileOperation error: " + itos(ret));
  932. return FAILED;
  933. }
  934. return OK;
  935. }
  936. OS_Windows::OS_Windows(HINSTANCE _hInstance) {
  937. ticks_per_second = 0;
  938. ticks_start = 0;
  939. main_loop = nullptr;
  940. process_map = nullptr;
  941. hInstance = _hInstance;
  942. #ifdef STDOUT_FILE
  943. stdo = fopen("stdout.txt", "wb");
  944. #endif
  945. #ifdef WASAPI_ENABLED
  946. AudioDriverManager::add_driver(&driver_wasapi);
  947. #endif
  948. #ifdef XAUDIO2_ENABLED
  949. AudioDriverManager::add_driver(&driver_xaudio2);
  950. #endif
  951. DisplayServerWindows::register_windows_driver();
  952. Vector<Logger *> loggers;
  953. loggers.push_back(memnew(WindowsTerminalLogger));
  954. _set_logger(memnew(CompositeLogger(loggers)));
  955. }
  956. OS_Windows::~OS_Windows() {
  957. #ifdef STDOUT_FILE
  958. fclose(stdo);
  959. #endif
  960. }