os_windows.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  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 <knownfolders.h>
  49. #include <process.h>
  50. #include <regstr.h>
  51. #include <shlobj.h>
  52. extern "C" {
  53. __declspec(dllexport) DWORD NvOptimusEnablement = 1;
  54. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  55. }
  56. // Workaround mingw-w64 < 4.0 bug
  57. #ifndef WM_TOUCH
  58. #define WM_TOUCH 576
  59. #endif
  60. #ifndef WM_POINTERUPDATE
  61. #define WM_POINTERUPDATE 0x0245
  62. #endif
  63. #if defined(__GNUC__)
  64. // Workaround GCC warning from -Wcast-function-type.
  65. #define GetProcAddress (void *)GetProcAddress
  66. #endif
  67. static String format_error_message(DWORD id) {
  68. LPWSTR messageBuffer = nullptr;
  69. size_t size = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  70. nullptr, id, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&messageBuffer, 0, nullptr);
  71. String msg = "Error " + itos(id) + ": " + String::utf16((const char16_t *)messageBuffer, size);
  72. LocalFree(messageBuffer);
  73. return msg;
  74. }
  75. void RedirectStream(const char *p_file_name, const char *p_mode, FILE *p_cpp_stream, const DWORD p_std_handle) {
  76. const HANDLE h_existing = GetStdHandle(p_std_handle);
  77. if (h_existing != INVALID_HANDLE_VALUE) { // Redirect only if attached console have a valid handle.
  78. const HANDLE h_cpp = reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(p_cpp_stream)));
  79. if (h_cpp == INVALID_HANDLE_VALUE) { // Redirect only if it's not already redirected to the pipe or file.
  80. FILE *fp = p_cpp_stream;
  81. freopen_s(&fp, p_file_name, p_mode, p_cpp_stream); // Redirect stream.
  82. setvbuf(p_cpp_stream, nullptr, _IONBF, 0); // Disable stream buffering.
  83. }
  84. }
  85. }
  86. void RedirectIOToConsole() {
  87. if (AttachConsole(ATTACH_PARENT_PROCESS)) {
  88. RedirectStream("CONIN$", "r", stdin, STD_INPUT_HANDLE);
  89. RedirectStream("CONOUT$", "w", stdout, STD_OUTPUT_HANDLE);
  90. RedirectStream("CONOUT$", "w", stderr, STD_ERROR_HANDLE);
  91. printf("\n"); // Make sure our output is starting from the new line.
  92. }
  93. }
  94. BOOL WINAPI HandlerRoutine(_In_ DWORD dwCtrlType) {
  95. if (!EngineDebugger::is_active()) {
  96. return FALSE;
  97. }
  98. switch (dwCtrlType) {
  99. case CTRL_C_EVENT:
  100. EngineDebugger::get_script_debugger()->set_depth(-1);
  101. EngineDebugger::get_script_debugger()->set_lines_left(1);
  102. return TRUE;
  103. default:
  104. return FALSE;
  105. }
  106. }
  107. void OS_Windows::alert(const String &p_alert, const String &p_title) {
  108. MessageBoxW(nullptr, (LPCWSTR)(p_alert.utf16().get_data()), (LPCWSTR)(p_title.utf16().get_data()), MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
  109. }
  110. void OS_Windows::initialize_debugging() {
  111. SetConsoleCtrlHandler(HandlerRoutine, TRUE);
  112. }
  113. void OS_Windows::initialize() {
  114. crash_handler.initialize();
  115. #ifndef WINDOWS_SUBSYSTEM_CONSOLE
  116. RedirectIOToConsole();
  117. #endif
  118. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_RESOURCES);
  119. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_USERDATA);
  120. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_FILESYSTEM);
  121. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_RESOURCES);
  122. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_USERDATA);
  123. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_FILESYSTEM);
  124. NetSocketPosix::make_default();
  125. // We need to know how often the clock is updated
  126. QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second);
  127. QueryPerformanceCounter((LARGE_INTEGER *)&ticks_start);
  128. // set minimum resolution for periodic timers, otherwise Sleep(n) may wait at least as
  129. // long as the windows scheduler resolution (~16-30ms) even for calls like Sleep(1)
  130. timeBeginPeriod(1);
  131. process_map = memnew((Map<ProcessID, ProcessInfo>));
  132. // Add current Godot PID to the list of known PIDs
  133. ProcessInfo current_pi = {};
  134. PROCESS_INFORMATION current_pi_pi = {};
  135. current_pi.pi = current_pi_pi;
  136. current_pi.pi.hProcess = GetCurrentProcess();
  137. process_map->insert(GetCurrentProcessId(), current_pi);
  138. IPUnix::make_default();
  139. main_loop = nullptr;
  140. }
  141. void OS_Windows::delete_main_loop() {
  142. if (main_loop) {
  143. memdelete(main_loop);
  144. }
  145. main_loop = nullptr;
  146. }
  147. void OS_Windows::set_main_loop(MainLoop *p_main_loop) {
  148. main_loop = p_main_loop;
  149. }
  150. void OS_Windows::finalize() {
  151. #ifdef WINMIDI_ENABLED
  152. driver_midi.close();
  153. #endif
  154. if (main_loop) {
  155. memdelete(main_loop);
  156. }
  157. main_loop = nullptr;
  158. }
  159. void OS_Windows::finalize_core() {
  160. timeEndPeriod(1);
  161. memdelete(process_map);
  162. NetSocketPosix::cleanup();
  163. }
  164. Error OS_Windows::get_entropy(uint8_t *r_buffer, int p_bytes) {
  165. NTSTATUS status = BCryptGenRandom(nullptr, r_buffer, p_bytes, BCRYPT_USE_SYSTEM_PREFERRED_RNG);
  166. ERR_FAIL_COND_V(status, FAILED);
  167. return OK;
  168. }
  169. Error OS_Windows::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
  170. String path = p_path.replace("/", "\\");
  171. if (!FileAccess::exists(path)) {
  172. //this code exists so gdnative can load .dll files from within the executable path
  173. path = get_executable_path().get_base_dir().plus_file(p_path.get_file());
  174. }
  175. typedef DLL_DIRECTORY_COOKIE(WINAPI * PAddDllDirectory)(PCWSTR);
  176. typedef BOOL(WINAPI * PRemoveDllDirectory)(DLL_DIRECTORY_COOKIE);
  177. PAddDllDirectory add_dll_directory = (PAddDllDirectory)GetProcAddress(GetModuleHandle("kernel32.dll"), "AddDllDirectory");
  178. PRemoveDllDirectory remove_dll_directory = (PRemoveDllDirectory)GetProcAddress(GetModuleHandle("kernel32.dll"), "RemoveDllDirectory");
  179. bool has_dll_directory_api = ((add_dll_directory != nullptr) && (remove_dll_directory != nullptr));
  180. DLL_DIRECTORY_COOKIE cookie = nullptr;
  181. if (p_also_set_library_path && has_dll_directory_api) {
  182. cookie = add_dll_directory((LPCWSTR)(path.get_base_dir().utf16().get_data()));
  183. }
  184. 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);
  185. ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, "Can't open dynamic library: " + p_path + ", error: " + format_error_message(GetLastError()) + ".");
  186. if (cookie) {
  187. remove_dll_directory(cookie);
  188. }
  189. return OK;
  190. }
  191. Error OS_Windows::close_dynamic_library(void *p_library_handle) {
  192. if (!FreeLibrary((HMODULE)p_library_handle)) {
  193. return FAILED;
  194. }
  195. return OK;
  196. }
  197. Error OS_Windows::get_dynamic_library_symbol_handle(void *p_library_handle, const String p_name, void *&p_symbol_handle, bool p_optional) {
  198. p_symbol_handle = (void *)GetProcAddress((HMODULE)p_library_handle, p_name.utf8().get_data());
  199. if (!p_symbol_handle) {
  200. if (!p_optional) {
  201. ERR_FAIL_V_MSG(ERR_CANT_RESOLVE, "Can't resolve symbol " + p_name + ", error: " + String::num(GetLastError()) + ".");
  202. } else {
  203. return ERR_CANT_RESOLVE;
  204. }
  205. }
  206. return OK;
  207. }
  208. String OS_Windows::get_name() const {
  209. return "Windows";
  210. }
  211. OS::Date OS_Windows::get_date(bool p_utc) const {
  212. SYSTEMTIME systemtime;
  213. if (p_utc) {
  214. GetSystemTime(&systemtime);
  215. } else {
  216. GetLocalTime(&systemtime);
  217. }
  218. //Get DST information from Windows, but only if p_utc is false.
  219. TIME_ZONE_INFORMATION info;
  220. bool daylight = false;
  221. if (!p_utc && GetTimeZoneInformation(&info) == TIME_ZONE_ID_DAYLIGHT) {
  222. daylight = true;
  223. }
  224. Date date;
  225. date.day = systemtime.wDay;
  226. date.month = Month(systemtime.wMonth);
  227. date.weekday = Weekday(systemtime.wDayOfWeek);
  228. date.year = systemtime.wYear;
  229. date.dst = daylight;
  230. return date;
  231. }
  232. OS::Time OS_Windows::get_time(bool p_utc) const {
  233. SYSTEMTIME systemtime;
  234. if (p_utc) {
  235. GetSystemTime(&systemtime);
  236. } else {
  237. GetLocalTime(&systemtime);
  238. }
  239. Time time;
  240. time.hour = systemtime.wHour;
  241. time.minute = systemtime.wMinute;
  242. time.second = systemtime.wSecond;
  243. return time;
  244. }
  245. OS::TimeZoneInfo OS_Windows::get_time_zone_info() const {
  246. TIME_ZONE_INFORMATION info;
  247. bool daylight = false;
  248. if (GetTimeZoneInformation(&info) == TIME_ZONE_ID_DAYLIGHT) {
  249. daylight = true;
  250. }
  251. // Daylight Bias needs to be added to the bias if DST is in effect, or else it will not properly update.
  252. TimeZoneInfo ret;
  253. if (daylight) {
  254. ret.name = info.DaylightName;
  255. ret.bias = info.Bias + info.DaylightBias;
  256. } else {
  257. ret.name = info.StandardName;
  258. ret.bias = info.Bias + info.StandardBias;
  259. }
  260. // Bias value returned by GetTimeZoneInformation is inverted of what we expect
  261. // For example, on GMT-3 GetTimeZoneInformation return a Bias of 180, so invert the value to get -180
  262. ret.bias = -ret.bias;
  263. return ret;
  264. }
  265. double OS_Windows::get_unix_time() const {
  266. // 1 Windows tick is 100ns
  267. const uint64_t WINDOWS_TICKS_PER_SECOND = 10000000;
  268. const uint64_t TICKS_TO_UNIX_EPOCH = 116444736000000000LL;
  269. SYSTEMTIME st;
  270. GetSystemTime(&st);
  271. FILETIME ft;
  272. SystemTimeToFileTime(&st, &ft);
  273. uint64_t ticks_time;
  274. ticks_time = ft.dwHighDateTime;
  275. ticks_time <<= 32;
  276. ticks_time |= ft.dwLowDateTime;
  277. return (double)(ticks_time - TICKS_TO_UNIX_EPOCH) / WINDOWS_TICKS_PER_SECOND;
  278. }
  279. void OS_Windows::delay_usec(uint32_t p_usec) const {
  280. if (p_usec < 1000) {
  281. Sleep(1);
  282. } else {
  283. Sleep(p_usec / 1000);
  284. }
  285. }
  286. uint64_t OS_Windows::get_ticks_usec() const {
  287. uint64_t ticks;
  288. // This is the number of clock ticks since start
  289. QueryPerformanceCounter((LARGE_INTEGER *)&ticks);
  290. // Subtract the ticks at game start to get
  291. // the ticks since the game started
  292. ticks -= ticks_start;
  293. // Divide by frequency to get the time in seconds
  294. // original calculation shown below is subject to overflow
  295. // with high ticks_per_second and a number of days since the last reboot.
  296. // time = ticks * 1000000L / ticks_per_second;
  297. // we can prevent this by either using 128 bit math
  298. // or separating into a calculation for seconds, and the fraction
  299. uint64_t seconds = ticks / ticks_per_second;
  300. // compiler will optimize these two into one divide
  301. uint64_t leftover = ticks % ticks_per_second;
  302. // remainder
  303. uint64_t time = (leftover * 1000000L) / ticks_per_second;
  304. // seconds
  305. time += seconds * 1000000L;
  306. return time;
  307. }
  308. String OS_Windows::_quote_command_line_argument(const String &p_text) const {
  309. for (int i = 0; i < p_text.size(); i++) {
  310. char32_t c = p_text[i];
  311. if (c == ' ' || c == '&' || c == '(' || c == ')' || c == '[' || c == ']' || c == '{' || c == '}' || c == '^' || c == '=' || c == ';' || c == '!' || c == '\'' || c == '+' || c == ',' || c == '`' || c == '~') {
  312. return "\"" + p_text + "\"";
  313. }
  314. }
  315. return p_text;
  316. }
  317. 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) {
  318. String path = p_path.replace("/", "\\");
  319. String command = _quote_command_line_argument(path);
  320. for (const String &E : p_arguments) {
  321. command += " " + _quote_command_line_argument(E);
  322. }
  323. ProcessInfo pi;
  324. ZeroMemory(&pi.si, sizeof(pi.si));
  325. pi.si.cb = sizeof(pi.si);
  326. ZeroMemory(&pi.pi, sizeof(pi.pi));
  327. LPSTARTUPINFOW si_w = (LPSTARTUPINFOW)&pi.si;
  328. bool inherit_handles = false;
  329. HANDLE pipe[2] = { nullptr, nullptr };
  330. if (r_pipe) {
  331. // Create pipe for StdOut and StdErr.
  332. SECURITY_ATTRIBUTES sa;
  333. sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  334. sa.bInheritHandle = true;
  335. sa.lpSecurityDescriptor = nullptr;
  336. ERR_FAIL_COND_V(!CreatePipe(&pipe[0], &pipe[1], &sa, 0), ERR_CANT_FORK);
  337. 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.
  338. pi.si.dwFlags |= STARTF_USESTDHANDLES;
  339. pi.si.hStdOutput = pipe[1];
  340. if (read_stderr) {
  341. pi.si.hStdError = pipe[1];
  342. }
  343. inherit_handles = true;
  344. }
  345. DWORD creation_flags = NORMAL_PRIORITY_CLASS;
  346. if (p_open_console) {
  347. creation_flags |= CREATE_NEW_CONSOLE;
  348. } else {
  349. creation_flags |= CREATE_NO_WINDOW;
  350. }
  351. int ret = CreateProcessW(nullptr, (LPWSTR)(command.utf16().ptrw()), nullptr, nullptr, inherit_handles, creation_flags, nullptr, nullptr, si_w, &pi.pi);
  352. if (!ret && r_pipe) {
  353. CloseHandle(pipe[0]); // Cleanup pipe handles.
  354. CloseHandle(pipe[1]);
  355. }
  356. ERR_FAIL_COND_V_MSG(ret == 0, ERR_CANT_FORK, "Could not create child process: " + command);
  357. if (r_pipe) {
  358. CloseHandle(pipe[1]); // Close pipe write handle (only child process is writing).
  359. char buf[4096];
  360. DWORD read = 0;
  361. for (;;) { // Read StdOut and StdErr from pipe.
  362. bool success = ReadFile(pipe[0], buf, 4096, &read, NULL);
  363. if (!success || read == 0) {
  364. break;
  365. }
  366. if (p_pipe_mutex) {
  367. p_pipe_mutex->lock();
  368. }
  369. (*r_pipe) += String::utf8(buf, read);
  370. if (p_pipe_mutex) {
  371. p_pipe_mutex->unlock();
  372. }
  373. }
  374. CloseHandle(pipe[0]); // Close pipe read handle.
  375. } else {
  376. WaitForSingleObject(pi.pi.hProcess, INFINITE);
  377. }
  378. if (r_exitcode) {
  379. DWORD ret2;
  380. GetExitCodeProcess(pi.pi.hProcess, &ret2);
  381. *r_exitcode = ret2;
  382. }
  383. CloseHandle(pi.pi.hProcess);
  384. CloseHandle(pi.pi.hThread);
  385. return OK;
  386. }
  387. Error OS_Windows::create_process(const String &p_path, const List<String> &p_arguments, ProcessID *r_child_id, bool p_open_console) {
  388. String path = p_path.replace("/", "\\");
  389. String command = _quote_command_line_argument(path);
  390. for (const String &E : p_arguments) {
  391. command += " " + _quote_command_line_argument(E);
  392. }
  393. ProcessInfo pi;
  394. ZeroMemory(&pi.si, sizeof(pi.si));
  395. pi.si.cb = sizeof(pi.si);
  396. ZeroMemory(&pi.pi, sizeof(pi.pi));
  397. LPSTARTUPINFOW si_w = (LPSTARTUPINFOW)&pi.si;
  398. DWORD creation_flags = NORMAL_PRIORITY_CLASS;
  399. if (p_open_console) {
  400. creation_flags |= CREATE_NEW_CONSOLE;
  401. } else {
  402. creation_flags |= CREATE_NO_WINDOW;
  403. }
  404. int ret = CreateProcessW(nullptr, (LPWSTR)(command.utf16().ptrw()), nullptr, nullptr, false, creation_flags, nullptr, nullptr, si_w, &pi.pi);
  405. ERR_FAIL_COND_V_MSG(ret == 0, ERR_CANT_FORK, "Could not create child process: " + command);
  406. ProcessID pid = pi.pi.dwProcessId;
  407. if (r_child_id) {
  408. *r_child_id = pid;
  409. }
  410. process_map->insert(pid, pi);
  411. return OK;
  412. }
  413. Error OS_Windows::kill(const ProcessID &p_pid) {
  414. ERR_FAIL_COND_V(!process_map->has(p_pid), FAILED);
  415. const PROCESS_INFORMATION pi = (*process_map)[p_pid].pi;
  416. process_map->erase(p_pid);
  417. const int ret = TerminateProcess(pi.hProcess, 0);
  418. CloseHandle(pi.hProcess);
  419. CloseHandle(pi.hThread);
  420. return ret != 0 ? OK : FAILED;
  421. }
  422. int OS_Windows::get_process_id() const {
  423. return _getpid();
  424. }
  425. Error OS_Windows::set_cwd(const String &p_cwd) {
  426. if (_wchdir((LPCWSTR)(p_cwd.utf16().get_data())) != 0) {
  427. return ERR_CANT_OPEN;
  428. }
  429. return OK;
  430. }
  431. String OS_Windows::get_executable_path() const {
  432. WCHAR bufname[4096];
  433. GetModuleFileNameW(nullptr, bufname, 4096);
  434. String s = String::utf16((const char16_t *)bufname).replace("\\", "/");
  435. return s;
  436. }
  437. bool OS_Windows::has_environment(const String &p_var) const {
  438. #ifdef MINGW_ENABLED
  439. return _wgetenv((LPCWSTR)(p_var.utf16().get_data())) != nullptr;
  440. #else
  441. WCHAR *env;
  442. size_t len;
  443. _wdupenv_s(&env, &len, (LPCWSTR)(p_var.utf16().get_data()));
  444. const bool has_env = env != nullptr;
  445. free(env);
  446. return has_env;
  447. #endif
  448. }
  449. String OS_Windows::get_environment(const String &p_var) const {
  450. WCHAR wval[0x7fff]; // MSDN says 32767 char is the maximum
  451. int wlen = GetEnvironmentVariableW((LPCWSTR)(p_var.utf16().get_data()), wval, 0x7fff);
  452. if (wlen > 0) {
  453. return String::utf16((const char16_t *)wval);
  454. }
  455. return "";
  456. }
  457. bool OS_Windows::set_environment(const String &p_var, const String &p_value) const {
  458. return (bool)SetEnvironmentVariableW((LPCWSTR)(p_var.utf16().get_data()), (LPCWSTR)(p_value.utf16().get_data()));
  459. }
  460. String OS_Windows::get_stdin_string(bool p_block) {
  461. if (p_block) {
  462. char buff[1024];
  463. return fgets(buff, 1024, stdin);
  464. }
  465. return String();
  466. }
  467. Error OS_Windows::shell_open(String p_uri) {
  468. INT_PTR ret = (INT_PTR)ShellExecuteW(nullptr, nullptr, (LPCWSTR)(p_uri.utf16().get_data()), nullptr, nullptr, SW_SHOWNORMAL);
  469. if (ret > 32) {
  470. return OK;
  471. } else {
  472. switch (ret) {
  473. case ERROR_FILE_NOT_FOUND:
  474. case SE_ERR_DLLNOTFOUND:
  475. return ERR_FILE_NOT_FOUND;
  476. case ERROR_PATH_NOT_FOUND:
  477. return ERR_FILE_BAD_PATH;
  478. case ERROR_BAD_FORMAT:
  479. return ERR_FILE_CORRUPT;
  480. case SE_ERR_ACCESSDENIED:
  481. return ERR_UNAUTHORIZED;
  482. case 0:
  483. case SE_ERR_OOM:
  484. return ERR_OUT_OF_MEMORY;
  485. default:
  486. return FAILED;
  487. }
  488. }
  489. }
  490. String OS_Windows::get_locale() const {
  491. const _WinLocale *wl = &_win_locales[0];
  492. LANGID langid = GetUserDefaultUILanguage();
  493. String neutral;
  494. int lang = PRIMARYLANGID(langid);
  495. int sublang = SUBLANGID(langid);
  496. while (wl->locale) {
  497. if (wl->main_lang == lang && wl->sublang == SUBLANG_NEUTRAL) {
  498. neutral = wl->locale;
  499. }
  500. if (lang == wl->main_lang && sublang == wl->sublang) {
  501. return String(wl->locale).replace("-", "_");
  502. }
  503. wl++;
  504. }
  505. if (!neutral.is_empty()) {
  506. return String(neutral).replace("-", "_");
  507. }
  508. return "en";
  509. }
  510. // We need this because GetSystemInfo() is unreliable on WOW64
  511. // see https://msdn.microsoft.com/en-us/library/windows/desktop/ms724381(v=vs.85).aspx
  512. // Taken from MSDN
  513. typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
  514. LPFN_ISWOW64PROCESS fnIsWow64Process;
  515. BOOL is_wow64() {
  516. BOOL wow64 = FALSE;
  517. fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process");
  518. if (fnIsWow64Process) {
  519. if (!fnIsWow64Process(GetCurrentProcess(), &wow64)) {
  520. wow64 = FALSE;
  521. }
  522. }
  523. return wow64;
  524. }
  525. int OS_Windows::get_processor_count() const {
  526. SYSTEM_INFO sysinfo;
  527. if (is_wow64()) {
  528. GetNativeSystemInfo(&sysinfo);
  529. } else {
  530. GetSystemInfo(&sysinfo);
  531. }
  532. return sysinfo.dwNumberOfProcessors;
  533. }
  534. String OS_Windows::get_processor_name() const {
  535. const String id = "Hardware\\Description\\System\\CentralProcessor\\0";
  536. HKEY hkey;
  537. if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, (LPCWSTR)(id.utf16().get_data()), 0, KEY_QUERY_VALUE, &hkey) != ERROR_SUCCESS) {
  538. ERR_FAIL_V_MSG("", String("Couldn't get the CPU model name. Returning an empty string."));
  539. }
  540. WCHAR buffer[256];
  541. DWORD buffer_len = 256;
  542. DWORD vtype = REG_SZ;
  543. if (RegQueryValueExW(hkey, L"ProcessorNameString", NULL, &vtype, (LPBYTE)buffer, &buffer_len) == ERROR_SUCCESS) {
  544. RegCloseKey(hkey);
  545. return String::utf16((const char16_t *)buffer, buffer_len).strip_edges();
  546. } else {
  547. RegCloseKey(hkey);
  548. ERR_FAIL_V_MSG("", String("Couldn't get the CPU model name. Returning an empty string."));
  549. }
  550. }
  551. void OS_Windows::run() {
  552. if (!main_loop) {
  553. return;
  554. }
  555. main_loop->initialize();
  556. while (!force_quit) {
  557. DisplayServer::get_singleton()->process_events(); // get rid of pending events
  558. if (Main::iteration()) {
  559. break;
  560. }
  561. }
  562. main_loop->finalize();
  563. }
  564. MainLoop *OS_Windows::get_main_loop() const {
  565. return main_loop;
  566. }
  567. uint64_t OS_Windows::get_embedded_pck_offset() const {
  568. Ref<FileAccess> f = FileAccess::open(get_executable_path(), FileAccess::READ);
  569. if (f.is_null()) {
  570. return 0;
  571. }
  572. // Process header.
  573. {
  574. f->seek(0x3c);
  575. uint32_t pe_pos = f->get_32();
  576. f->seek(pe_pos);
  577. uint32_t magic = f->get_32();
  578. if (magic != 0x00004550) {
  579. return 0;
  580. }
  581. }
  582. int num_sections;
  583. {
  584. int64_t header_pos = f->get_position();
  585. f->seek(header_pos + 2);
  586. num_sections = f->get_16();
  587. f->seek(header_pos + 16);
  588. uint16_t opt_header_size = f->get_16();
  589. // Skip rest of header + optional header to go to the section headers.
  590. f->seek(f->get_position() + 2 + opt_header_size);
  591. }
  592. int64_t section_table_pos = f->get_position();
  593. // Search for the "pck" section.
  594. int64_t off = 0;
  595. for (int i = 0; i < num_sections; ++i) {
  596. int64_t section_header_pos = section_table_pos + i * 40;
  597. f->seek(section_header_pos);
  598. uint8_t section_name[9];
  599. f->get_buffer(section_name, 8);
  600. section_name[8] = '\0';
  601. if (strcmp((char *)section_name, "pck") == 0) {
  602. f->seek(section_header_pos + 20);
  603. off = f->get_32();
  604. break;
  605. }
  606. }
  607. return off;
  608. }
  609. String OS_Windows::get_config_path() const {
  610. // The XDG Base Directory specification technically only applies on Linux/*BSD, but it doesn't hurt to support it on Windows as well.
  611. if (has_environment("XDG_CONFIG_HOME")) {
  612. if (get_environment("XDG_CONFIG_HOME").is_absolute_path()) {
  613. return get_environment("XDG_CONFIG_HOME").replace("\\", "/");
  614. } else {
  615. 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.");
  616. }
  617. }
  618. if (has_environment("APPDATA")) {
  619. return get_environment("APPDATA").replace("\\", "/");
  620. }
  621. return ".";
  622. }
  623. String OS_Windows::get_data_path() const {
  624. // The XDG Base Directory specification technically only applies on Linux/*BSD, but it doesn't hurt to support it on Windows as well.
  625. if (has_environment("XDG_DATA_HOME")) {
  626. if (get_environment("XDG_DATA_HOME").is_absolute_path()) {
  627. return get_environment("XDG_DATA_HOME").replace("\\", "/");
  628. } else {
  629. 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.");
  630. }
  631. }
  632. return get_config_path();
  633. }
  634. String OS_Windows::get_cache_path() const {
  635. static String cache_path_cache;
  636. if (cache_path_cache.is_empty()) {
  637. // The XDG Base Directory specification technically only applies on Linux/*BSD, but it doesn't hurt to support it on Windows as well.
  638. if (has_environment("XDG_CACHE_HOME")) {
  639. if (get_environment("XDG_CACHE_HOME").is_absolute_path()) {
  640. cache_path_cache = get_environment("XDG_CACHE_HOME").replace("\\", "/");
  641. } else {
  642. 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.");
  643. }
  644. }
  645. if (cache_path_cache.is_empty() && has_environment("LOCALAPPDATA")) {
  646. cache_path_cache = get_environment("LOCALAPPDATA").replace("\\", "/");
  647. }
  648. if (cache_path_cache.is_empty() && has_environment("TEMP")) {
  649. cache_path_cache = get_environment("TEMP").replace("\\", "/");
  650. }
  651. if (cache_path_cache.is_empty()) {
  652. cache_path_cache = get_config_path();
  653. }
  654. }
  655. return cache_path_cache;
  656. }
  657. // Get properly capitalized engine name for system paths
  658. String OS_Windows::get_godot_dir_name() const {
  659. return String(VERSION_SHORT_NAME).capitalize();
  660. }
  661. String OS_Windows::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  662. KNOWNFOLDERID id;
  663. switch (p_dir) {
  664. case SYSTEM_DIR_DESKTOP: {
  665. id = FOLDERID_Desktop;
  666. } break;
  667. case SYSTEM_DIR_DCIM: {
  668. id = FOLDERID_Pictures;
  669. } break;
  670. case SYSTEM_DIR_DOCUMENTS: {
  671. id = FOLDERID_Documents;
  672. } break;
  673. case SYSTEM_DIR_DOWNLOADS: {
  674. id = FOLDERID_Downloads;
  675. } break;
  676. case SYSTEM_DIR_MOVIES: {
  677. id = FOLDERID_Videos;
  678. } break;
  679. case SYSTEM_DIR_MUSIC: {
  680. id = FOLDERID_Music;
  681. } break;
  682. case SYSTEM_DIR_PICTURES: {
  683. id = FOLDERID_Pictures;
  684. } break;
  685. case SYSTEM_DIR_RINGTONES: {
  686. id = FOLDERID_Music;
  687. } break;
  688. }
  689. PWSTR szPath;
  690. HRESULT res = SHGetKnownFolderPath(id, 0, nullptr, &szPath);
  691. ERR_FAIL_COND_V(res != S_OK, String());
  692. String path = String::utf16((const char16_t *)szPath).replace("\\", "/");
  693. CoTaskMemFree(szPath);
  694. return path;
  695. }
  696. String OS_Windows::get_user_data_dir() const {
  697. String appname = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/name"));
  698. if (!appname.is_empty()) {
  699. bool use_custom_dir = ProjectSettings::get_singleton()->get("application/config/use_custom_user_dir");
  700. if (use_custom_dir) {
  701. String custom_dir = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/custom_user_dir_name"), true);
  702. if (custom_dir.is_empty()) {
  703. custom_dir = appname;
  704. }
  705. return get_data_path().plus_file(custom_dir).replace("\\", "/");
  706. } else {
  707. return get_data_path().plus_file(get_godot_dir_name()).plus_file("app_userdata").plus_file(appname).replace("\\", "/");
  708. }
  709. }
  710. return get_data_path().plus_file(get_godot_dir_name()).plus_file("app_userdata").plus_file("[unnamed project]");
  711. }
  712. String OS_Windows::get_unique_id() const {
  713. HW_PROFILE_INFO HwProfInfo;
  714. ERR_FAIL_COND_V(!GetCurrentHwProfile(&HwProfInfo), "");
  715. return String::utf16((const char16_t *)(HwProfInfo.szHwProfileGuid), HW_PROFILE_GUIDLEN);
  716. }
  717. bool OS_Windows::_check_internal_feature_support(const String &p_feature) {
  718. return p_feature == "pc";
  719. }
  720. void OS_Windows::disable_crash_handler() {
  721. crash_handler.disable();
  722. }
  723. bool OS_Windows::is_disable_crash_handler() const {
  724. return crash_handler.is_disabled();
  725. }
  726. Error OS_Windows::move_to_trash(const String &p_path) {
  727. SHFILEOPSTRUCTW sf;
  728. Char16String utf16 = p_path.utf16();
  729. WCHAR *from = new WCHAR[utf16.length() + 2];
  730. wcscpy_s(from, utf16.length() + 1, (LPCWSTR)(utf16.get_data()));
  731. from[utf16.length() + 1] = 0;
  732. sf.hwnd = main_window;
  733. sf.wFunc = FO_DELETE;
  734. sf.pFrom = from;
  735. sf.pTo = nullptr;
  736. sf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;
  737. sf.fAnyOperationsAborted = FALSE;
  738. sf.hNameMappings = nullptr;
  739. sf.lpszProgressTitle = nullptr;
  740. int ret = SHFileOperationW(&sf);
  741. delete[] from;
  742. if (ret) {
  743. ERR_PRINT("SHFileOperation error: " + itos(ret));
  744. return FAILED;
  745. }
  746. return OK;
  747. }
  748. OS_Windows::OS_Windows(HINSTANCE _hInstance) {
  749. ticks_per_second = 0;
  750. ticks_start = 0;
  751. main_loop = nullptr;
  752. process_map = nullptr;
  753. force_quit = false;
  754. hInstance = _hInstance;
  755. #ifdef STDOUT_FILE
  756. stdo = fopen("stdout.txt", "wb");
  757. #endif
  758. #ifdef WASAPI_ENABLED
  759. AudioDriverManager::add_driver(&driver_wasapi);
  760. #endif
  761. #ifdef XAUDIO2_ENABLED
  762. AudioDriverManager::add_driver(&driver_xaudio2);
  763. #endif
  764. DisplayServerWindows::register_windows_driver();
  765. Vector<Logger *> loggers;
  766. loggers.push_back(memnew(WindowsTerminalLogger));
  767. _set_logger(memnew(CompositeLogger(loggers)));
  768. }
  769. OS_Windows::~OS_Windows() {
  770. #ifdef STDOUT_FILE
  771. fclose(stdo);
  772. #endif
  773. }