os_windows.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  1. /*************************************************************************/
  2. /* os_windows.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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. // Must include Winsock before windows.h (included by os_windows.h)
  31. #include "drivers/unix/net_socket_posix.h"
  32. #include "os_windows.h"
  33. #include "core/debugger/engine_debugger.h"
  34. #include "core/debugger/script_debugger.h"
  35. #include "core/io/marshalls.h"
  36. #include "core/version_generated.gen.h"
  37. #include "drivers/windows/dir_access_windows.h"
  38. #include "drivers/windows/file_access_windows.h"
  39. #include "joypad_windows.h"
  40. #include "lang_table.h"
  41. #include "main/main.h"
  42. #include "platform/windows/display_server_windows.h"
  43. #include "servers/audio_server.h"
  44. #include "servers/rendering/rendering_server_default.h"
  45. #include "windows_terminal_logger.h"
  46. #include <avrt.h>
  47. #include <direct.h>
  48. #include <knownfolders.h>
  49. #include <process.h>
  50. #include <regstr.h>
  51. #include <shlobj.h>
  52. static const WORD MAX_CONSOLE_LINES = 1500;
  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. #ifdef DEBUG_ENABLED
  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. #endif // DEBUG_ENABLED
  78. void RedirectIOToConsole() {
  79. int hConHandle;
  80. intptr_t lStdHandle;
  81. CONSOLE_SCREEN_BUFFER_INFO coninfo;
  82. FILE *fp;
  83. // allocate a console for this app
  84. AllocConsole();
  85. // set the screen buffer to be big enough to let us scroll text
  86. GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo);
  87. coninfo.dwSize.Y = MAX_CONSOLE_LINES;
  88. SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize);
  89. // redirect unbuffered STDOUT to the console
  90. lStdHandle = (intptr_t)GetStdHandle(STD_OUTPUT_HANDLE);
  91. hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
  92. fp = _fdopen(hConHandle, "w");
  93. *stdout = *fp;
  94. setvbuf(stdout, nullptr, _IONBF, 0);
  95. // redirect unbuffered STDIN to the console
  96. lStdHandle = (intptr_t)GetStdHandle(STD_INPUT_HANDLE);
  97. hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
  98. fp = _fdopen(hConHandle, "r");
  99. *stdin = *fp;
  100. setvbuf(stdin, nullptr, _IONBF, 0);
  101. // redirect unbuffered STDERR to the console
  102. lStdHandle = (intptr_t)GetStdHandle(STD_ERROR_HANDLE);
  103. hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
  104. fp = _fdopen(hConHandle, "w");
  105. *stderr = *fp;
  106. setvbuf(stderr, nullptr, _IONBF, 0);
  107. // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
  108. // point to console as well
  109. }
  110. BOOL WINAPI HandlerRoutine(_In_ DWORD dwCtrlType) {
  111. if (!EngineDebugger::is_active())
  112. return FALSE;
  113. switch (dwCtrlType) {
  114. case CTRL_C_EVENT:
  115. EngineDebugger::get_script_debugger()->set_depth(-1);
  116. EngineDebugger::get_script_debugger()->set_lines_left(1);
  117. return TRUE;
  118. default:
  119. return FALSE;
  120. }
  121. }
  122. void OS_Windows::initialize_debugging() {
  123. SetConsoleCtrlHandler(HandlerRoutine, TRUE);
  124. }
  125. void OS_Windows::initialize() {
  126. crash_handler.initialize();
  127. //RedirectIOToConsole();
  128. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_RESOURCES);
  129. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_USERDATA);
  130. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_FILESYSTEM);
  131. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_RESOURCES);
  132. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_USERDATA);
  133. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_FILESYSTEM);
  134. NetSocketPosix::make_default();
  135. // We need to know how often the clock is updated
  136. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second))
  137. ticks_per_second = 1000;
  138. // If timeAtGameStart is 0 then we get the time since
  139. // the start of the computer when we call GetGameTime()
  140. ticks_start = 0;
  141. ticks_start = get_ticks_usec();
  142. // set minimum resolution for periodic timers, otherwise Sleep(n) may wait at least as
  143. // long as the windows scheduler resolution (~16-30ms) even for calls like Sleep(1)
  144. timeBeginPeriod(1);
  145. process_map = memnew((Map<ProcessID, ProcessInfo>));
  146. // Add current Godot PID to the list of known PIDs
  147. ProcessInfo current_pi = {};
  148. PROCESS_INFORMATION current_pi_pi = {};
  149. current_pi.pi = current_pi_pi;
  150. current_pi.pi.hProcess = GetCurrentProcess();
  151. process_map->insert(GetCurrentProcessId(), current_pi);
  152. IP_Unix::make_default();
  153. main_loop = nullptr;
  154. }
  155. void OS_Windows::delete_main_loop() {
  156. if (main_loop)
  157. memdelete(main_loop);
  158. main_loop = nullptr;
  159. }
  160. void OS_Windows::set_main_loop(MainLoop *p_main_loop) {
  161. main_loop = p_main_loop;
  162. }
  163. void OS_Windows::finalize() {
  164. #ifdef WINMIDI_ENABLED
  165. driver_midi.close();
  166. #endif
  167. if (main_loop)
  168. memdelete(main_loop);
  169. main_loop = nullptr;
  170. }
  171. void OS_Windows::finalize_core() {
  172. timeEndPeriod(1);
  173. memdelete(process_map);
  174. NetSocketPosix::cleanup();
  175. }
  176. Error OS_Windows::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
  177. String path = p_path.replace("/", "\\");
  178. if (!FileAccess::exists(path)) {
  179. //this code exists so gdnative can load .dll files from within the executable path
  180. path = get_executable_path().get_base_dir().plus_file(p_path.get_file());
  181. }
  182. typedef DLL_DIRECTORY_COOKIE(WINAPI * PAddDllDirectory)(PCWSTR);
  183. typedef BOOL(WINAPI * PRemoveDllDirectory)(DLL_DIRECTORY_COOKIE);
  184. PAddDllDirectory add_dll_directory = (PAddDllDirectory)GetProcAddress(GetModuleHandle("kernel32.dll"), "AddDllDirectory");
  185. PRemoveDllDirectory remove_dll_directory = (PRemoveDllDirectory)GetProcAddress(GetModuleHandle("kernel32.dll"), "RemoveDllDirectory");
  186. bool has_dll_directory_api = ((add_dll_directory != nullptr) && (remove_dll_directory != nullptr));
  187. DLL_DIRECTORY_COOKIE cookie = nullptr;
  188. if (p_also_set_library_path && has_dll_directory_api) {
  189. cookie = add_dll_directory((LPCWSTR)(path.get_base_dir().utf16().get_data()));
  190. }
  191. 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);
  192. ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, "Can't open dynamic library: " + p_path + ", error: " + format_error_message(GetLastError()) + ".");
  193. if (cookie) {
  194. remove_dll_directory(cookie);
  195. }
  196. return OK;
  197. }
  198. Error OS_Windows::close_dynamic_library(void *p_library_handle) {
  199. if (!FreeLibrary((HMODULE)p_library_handle)) {
  200. return FAILED;
  201. }
  202. return OK;
  203. }
  204. Error OS_Windows::get_dynamic_library_symbol_handle(void *p_library_handle, const String p_name, void *&p_symbol_handle, bool p_optional) {
  205. p_symbol_handle = (void *)GetProcAddress((HMODULE)p_library_handle, p_name.utf8().get_data());
  206. if (!p_symbol_handle) {
  207. if (!p_optional) {
  208. ERR_FAIL_V_MSG(ERR_CANT_RESOLVE, "Can't resolve symbol " + p_name + ", error: " + String::num(GetLastError()) + ".");
  209. } else {
  210. return ERR_CANT_RESOLVE;
  211. }
  212. }
  213. return OK;
  214. }
  215. String OS_Windows::get_name() const {
  216. return "Windows";
  217. }
  218. OS::Date OS_Windows::get_date(bool utc) const {
  219. SYSTEMTIME systemtime;
  220. if (utc)
  221. GetSystemTime(&systemtime);
  222. else
  223. GetLocalTime(&systemtime);
  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 = false;
  230. return date;
  231. }
  232. OS::Time OS_Windows::get_time(bool utc) const {
  233. SYSTEMTIME systemtime;
  234. if (utc)
  235. GetSystemTime(&systemtime);
  236. else
  237. GetLocalTime(&systemtime);
  238. Time time;
  239. time.hour = systemtime.wHour;
  240. time.min = systemtime.wMinute;
  241. time.sec = systemtime.wSecond;
  242. return time;
  243. }
  244. OS::TimeZoneInfo OS_Windows::get_time_zone_info() const {
  245. TIME_ZONE_INFORMATION info;
  246. bool daylight = false;
  247. if (GetTimeZoneInformation(&info) == TIME_ZONE_ID_DAYLIGHT)
  248. daylight = true;
  249. TimeZoneInfo ret;
  250. if (daylight) {
  251. ret.name = info.DaylightName;
  252. } else {
  253. ret.name = info.StandardName;
  254. }
  255. // Bias value returned by GetTimeZoneInformation is inverted of what we expect
  256. // For example on GMT-3 GetTimeZoneInformation return a Bias of 180, so invert the value to get -180
  257. ret.bias = -info.Bias;
  258. return ret;
  259. }
  260. double OS_Windows::get_unix_time() const {
  261. // 1 Windows tick is 100ns
  262. const uint64_t WINDOWS_TICKS_PER_SECOND = 10000000;
  263. const uint64_t TICKS_TO_UNIX_EPOCH = 116444736000000000LL;
  264. SYSTEMTIME st;
  265. GetSystemTime(&st);
  266. FILETIME ft;
  267. SystemTimeToFileTime(&st, &ft);
  268. uint64_t ticks_time;
  269. ticks_time = ft.dwHighDateTime;
  270. ticks_time <<= 32;
  271. ticks_time |= ft.dwLowDateTime;
  272. return (double)(ticks_time - TICKS_TO_UNIX_EPOCH) / WINDOWS_TICKS_PER_SECOND;
  273. }
  274. void OS_Windows::delay_usec(uint32_t p_usec) const {
  275. if (p_usec < 1000)
  276. Sleep(1);
  277. else
  278. Sleep(p_usec / 1000);
  279. }
  280. uint64_t OS_Windows::get_ticks_usec() const {
  281. uint64_t ticks;
  282. // This is the number of clock ticks since start
  283. if (!QueryPerformanceCounter((LARGE_INTEGER *)&ticks))
  284. ticks = (UINT64)timeGetTime();
  285. // Divide by frequency to get the time in seconds
  286. // original calculation shown below is subject to overflow
  287. // with high ticks_per_second and a number of days since the last reboot.
  288. // time = ticks * 1000000L / ticks_per_second;
  289. // we can prevent this by either using 128 bit math
  290. // or separating into a calculation for seconds, and the fraction
  291. uint64_t seconds = ticks / ticks_per_second;
  292. // compiler will optimize these two into one divide
  293. uint64_t leftover = ticks % ticks_per_second;
  294. // remainder
  295. uint64_t time = (leftover * 1000000L) / ticks_per_second;
  296. // seconds
  297. time += seconds * 1000000L;
  298. // Subtract the time at game start to get
  299. // the time since the game started
  300. time -= ticks_start;
  301. return time;
  302. }
  303. String OS_Windows::_quote_command_line_argument(const String &p_text) const {
  304. for (int i = 0; i < p_text.size(); i++) {
  305. char32_t c = p_text[i];
  306. if (c == ' ' || c == '&' || c == '(' || c == ')' || c == '[' || c == ']' || c == '{' || c == '}' || c == '^' || c == '=' || c == ';' || c == '!' || c == '\'' || c == '+' || c == ',' || c == '`' || c == '~') {
  307. return "\"" + p_text + "\"";
  308. }
  309. }
  310. return p_text;
  311. }
  312. 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) {
  313. String path = p_path.replace("/", "\\");
  314. String command = _quote_command_line_argument(path);
  315. for (const List<String>::Element *E = p_arguments.front(); E; E = E->next()) {
  316. command += " " + _quote_command_line_argument(E->get());
  317. }
  318. if (r_pipe) {
  319. if (read_stderr) {
  320. command += " 2>&1"; // Include stderr
  321. }
  322. // Add extra quotes around the full command, to prevent it from stripping quotes in the command,
  323. // because _wpopen calls command as "cmd.exe /c command", instead of executing it directly
  324. command = _quote_command_line_argument(command);
  325. FILE *f = _wpopen((LPCWSTR)(command.utf16().get_data()), L"r");
  326. ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, "Cannot create pipe from command: " + command);
  327. char buf[65535];
  328. while (fgets(buf, 65535, f)) {
  329. if (p_pipe_mutex) {
  330. p_pipe_mutex->lock();
  331. }
  332. (*r_pipe) += String::utf8(buf);
  333. if (p_pipe_mutex) {
  334. p_pipe_mutex->unlock();
  335. }
  336. }
  337. int rv = _pclose(f);
  338. if (r_exitcode) {
  339. *r_exitcode = rv;
  340. }
  341. return OK;
  342. }
  343. ProcessInfo pi;
  344. ZeroMemory(&pi.si, sizeof(pi.si));
  345. pi.si.cb = sizeof(pi.si);
  346. ZeroMemory(&pi.pi, sizeof(pi.pi));
  347. LPSTARTUPINFOW si_w = (LPSTARTUPINFOW)&pi.si;
  348. int ret = CreateProcessW(nullptr, (LPWSTR)(command.utf16().ptrw()), nullptr, nullptr, false, NORMAL_PRIORITY_CLASS & CREATE_NO_WINDOW, nullptr, nullptr, si_w, &pi.pi);
  349. ERR_FAIL_COND_V_MSG(ret == 0, ERR_CANT_FORK, "Could not create child process: " + command);
  350. WaitForSingleObject(pi.pi.hProcess, INFINITE);
  351. if (r_exitcode) {
  352. DWORD ret2;
  353. GetExitCodeProcess(pi.pi.hProcess, &ret2);
  354. *r_exitcode = ret2;
  355. }
  356. CloseHandle(pi.pi.hProcess);
  357. CloseHandle(pi.pi.hThread);
  358. return OK;
  359. };
  360. Error OS_Windows::create_process(const String &p_path, const List<String> &p_arguments, ProcessID *r_child_id) {
  361. String path = p_path.replace("/", "\\");
  362. String command = _quote_command_line_argument(path);
  363. for (const List<String>::Element *E = p_arguments.front(); E; E = E->next()) {
  364. command += " " + _quote_command_line_argument(E->get());
  365. }
  366. ProcessInfo pi;
  367. ZeroMemory(&pi.si, sizeof(pi.si));
  368. pi.si.cb = sizeof(pi.si);
  369. ZeroMemory(&pi.pi, sizeof(pi.pi));
  370. LPSTARTUPINFOW si_w = (LPSTARTUPINFOW)&pi.si;
  371. int ret = CreateProcessW(nullptr, (LPWSTR)(command.utf16().ptrw()), nullptr, nullptr, false, NORMAL_PRIORITY_CLASS & CREATE_NO_WINDOW, nullptr, nullptr, si_w, &pi.pi);
  372. ERR_FAIL_COND_V_MSG(ret == 0, ERR_CANT_FORK, "Could not create child process: " + command);
  373. ProcessID pid = pi.pi.dwProcessId;
  374. if (r_child_id) {
  375. *r_child_id = pid;
  376. }
  377. process_map->insert(pid, pi);
  378. return OK;
  379. };
  380. Error OS_Windows::kill(const ProcessID &p_pid) {
  381. ERR_FAIL_COND_V(!process_map->has(p_pid), FAILED);
  382. const PROCESS_INFORMATION pi = (*process_map)[p_pid].pi;
  383. process_map->erase(p_pid);
  384. const int ret = TerminateProcess(pi.hProcess, 0);
  385. CloseHandle(pi.hProcess);
  386. CloseHandle(pi.hThread);
  387. return ret != 0 ? OK : FAILED;
  388. };
  389. int OS_Windows::get_process_id() const {
  390. return _getpid();
  391. }
  392. Error OS_Windows::set_cwd(const String &p_cwd) {
  393. if (_wchdir((LPCWSTR)(p_cwd.utf16().get_data())) != 0)
  394. return ERR_CANT_OPEN;
  395. return OK;
  396. }
  397. String OS_Windows::get_executable_path() const {
  398. WCHAR bufname[4096];
  399. GetModuleFileNameW(nullptr, bufname, 4096);
  400. String s = String::utf16((const char16_t *)bufname).replace("\\", "/");
  401. return s;
  402. }
  403. bool OS_Windows::has_environment(const String &p_var) const {
  404. #ifdef MINGW_ENABLED
  405. return _wgetenv((LPCWSTR)(p_var.utf16().get_data())) != nullptr;
  406. #else
  407. WCHAR *env;
  408. size_t len;
  409. _wdupenv_s(&env, &len, (LPCWSTR)(p_var.utf16().get_data()));
  410. const bool has_env = env != nullptr;
  411. free(env);
  412. return has_env;
  413. #endif
  414. };
  415. String OS_Windows::get_environment(const String &p_var) const {
  416. WCHAR wval[0x7fff]; // MSDN says 32767 char is the maximum
  417. int wlen = GetEnvironmentVariableW((LPCWSTR)(p_var.utf16().get_data()), wval, 0x7fff);
  418. if (wlen > 0) {
  419. return String::utf16((const char16_t *)wval);
  420. }
  421. return "";
  422. }
  423. bool OS_Windows::set_environment(const String &p_var, const String &p_value) const {
  424. return (bool)SetEnvironmentVariableW((LPCWSTR)(p_var.utf16().get_data()), (LPCWSTR)(p_value.utf16().get_data()));
  425. }
  426. String OS_Windows::get_stdin_string(bool p_block) {
  427. if (p_block) {
  428. char buff[1024];
  429. return fgets(buff, 1024, stdin);
  430. };
  431. return String();
  432. }
  433. Error OS_Windows::shell_open(String p_uri) {
  434. ShellExecuteW(nullptr, nullptr, (LPCWSTR)(p_uri.utf16().get_data()), nullptr, nullptr, SW_SHOWNORMAL);
  435. return OK;
  436. }
  437. String OS_Windows::get_locale() const {
  438. const _WinLocale *wl = &_win_locales[0];
  439. LANGID langid = GetUserDefaultUILanguage();
  440. String neutral;
  441. int lang = PRIMARYLANGID(langid);
  442. int sublang = SUBLANGID(langid);
  443. while (wl->locale) {
  444. if (wl->main_lang == lang && wl->sublang == SUBLANG_NEUTRAL)
  445. neutral = wl->locale;
  446. if (lang == wl->main_lang && sublang == wl->sublang)
  447. return String(wl->locale).replace("-", "_");
  448. wl++;
  449. }
  450. if (neutral != "")
  451. return String(neutral).replace("-", "_");
  452. return "en";
  453. }
  454. // We need this because GetSystemInfo() is unreliable on WOW64
  455. // see https://msdn.microsoft.com/en-us/library/windows/desktop/ms724381(v=vs.85).aspx
  456. // Taken from MSDN
  457. typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
  458. LPFN_ISWOW64PROCESS fnIsWow64Process;
  459. BOOL is_wow64() {
  460. BOOL wow64 = FALSE;
  461. fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process");
  462. if (fnIsWow64Process) {
  463. if (!fnIsWow64Process(GetCurrentProcess(), &wow64)) {
  464. wow64 = FALSE;
  465. }
  466. }
  467. return wow64;
  468. }
  469. int OS_Windows::get_processor_count() const {
  470. SYSTEM_INFO sysinfo;
  471. if (is_wow64())
  472. GetNativeSystemInfo(&sysinfo);
  473. else
  474. GetSystemInfo(&sysinfo);
  475. return sysinfo.dwNumberOfProcessors;
  476. }
  477. void OS_Windows::run() {
  478. if (!main_loop)
  479. return;
  480. main_loop->initialize();
  481. while (!force_quit) {
  482. DisplayServer::get_singleton()->process_events(); // get rid of pending events
  483. if (Main::iteration())
  484. break;
  485. };
  486. main_loop->finalize();
  487. }
  488. MainLoop *OS_Windows::get_main_loop() const {
  489. return main_loop;
  490. }
  491. String OS_Windows::get_config_path() const {
  492. if (has_environment("XDG_CONFIG_HOME")) { // unlikely, but after all why not?
  493. return get_environment("XDG_CONFIG_HOME");
  494. } else if (has_environment("APPDATA")) {
  495. return get_environment("APPDATA");
  496. } else {
  497. return ".";
  498. }
  499. }
  500. String OS_Windows::get_data_path() const {
  501. if (has_environment("XDG_DATA_HOME")) {
  502. return get_environment("XDG_DATA_HOME");
  503. } else {
  504. return get_config_path();
  505. }
  506. }
  507. String OS_Windows::get_cache_path() const {
  508. if (has_environment("XDG_CACHE_HOME")) {
  509. return get_environment("XDG_CACHE_HOME");
  510. } else if (has_environment("TEMP")) {
  511. return get_environment("TEMP");
  512. } else {
  513. return get_config_path();
  514. }
  515. }
  516. // Get properly capitalized engine name for system paths
  517. String OS_Windows::get_godot_dir_name() const {
  518. return String(VERSION_SHORT_NAME).capitalize();
  519. }
  520. String OS_Windows::get_system_dir(SystemDir p_dir) const {
  521. KNOWNFOLDERID id;
  522. switch (p_dir) {
  523. case SYSTEM_DIR_DESKTOP: {
  524. id = FOLDERID_Desktop;
  525. } break;
  526. case SYSTEM_DIR_DCIM: {
  527. id = FOLDERID_Pictures;
  528. } break;
  529. case SYSTEM_DIR_DOCUMENTS: {
  530. id = FOLDERID_Documents;
  531. } break;
  532. case SYSTEM_DIR_DOWNLOADS: {
  533. id = FOLDERID_Downloads;
  534. } break;
  535. case SYSTEM_DIR_MOVIES: {
  536. id = FOLDERID_Videos;
  537. } break;
  538. case SYSTEM_DIR_MUSIC: {
  539. id = FOLDERID_Music;
  540. } break;
  541. case SYSTEM_DIR_PICTURES: {
  542. id = FOLDERID_Pictures;
  543. } break;
  544. case SYSTEM_DIR_RINGTONES: {
  545. id = FOLDERID_Music;
  546. } break;
  547. }
  548. PWSTR szPath;
  549. HRESULT res = SHGetKnownFolderPath(id, 0, nullptr, &szPath);
  550. ERR_FAIL_COND_V(res != S_OK, String());
  551. String path = String::utf16((const char16_t *)szPath);
  552. CoTaskMemFree(szPath);
  553. return path;
  554. }
  555. String OS_Windows::get_user_data_dir() const {
  556. String appname = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/name"));
  557. if (appname != "") {
  558. bool use_custom_dir = ProjectSettings::get_singleton()->get("application/config/use_custom_user_dir");
  559. if (use_custom_dir) {
  560. String custom_dir = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/custom_user_dir_name"), true);
  561. if (custom_dir == "") {
  562. custom_dir = appname;
  563. }
  564. return get_data_path().plus_file(custom_dir).replace("\\", "/");
  565. } else {
  566. return get_data_path().plus_file(get_godot_dir_name()).plus_file("app_userdata").plus_file(appname).replace("\\", "/");
  567. }
  568. }
  569. return ProjectSettings::get_singleton()->get_resource_path();
  570. }
  571. String OS_Windows::get_unique_id() const {
  572. HW_PROFILE_INFO HwProfInfo;
  573. ERR_FAIL_COND_V(!GetCurrentHwProfile(&HwProfInfo), "");
  574. return String::utf16((const char16_t *)(HwProfInfo.szHwProfileGuid), HW_PROFILE_GUIDLEN);
  575. }
  576. bool OS_Windows::_check_internal_feature_support(const String &p_feature) {
  577. return p_feature == "pc";
  578. }
  579. void OS_Windows::disable_crash_handler() {
  580. crash_handler.disable();
  581. }
  582. bool OS_Windows::is_disable_crash_handler() const {
  583. return crash_handler.is_disabled();
  584. }
  585. Error OS_Windows::move_to_trash(const String &p_path) {
  586. SHFILEOPSTRUCTW sf;
  587. Char16String utf16 = p_path.utf16();
  588. WCHAR *from = new WCHAR[utf16.length() + 2];
  589. wcscpy_s(from, utf16.length() + 1, (LPCWSTR)(utf16.get_data()));
  590. from[utf16.length() + 1] = 0;
  591. sf.hwnd = main_window;
  592. sf.wFunc = FO_DELETE;
  593. sf.pFrom = from;
  594. sf.pTo = nullptr;
  595. sf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;
  596. sf.fAnyOperationsAborted = FALSE;
  597. sf.hNameMappings = nullptr;
  598. sf.lpszProgressTitle = nullptr;
  599. int ret = SHFileOperationW(&sf);
  600. delete[] from;
  601. if (ret) {
  602. ERR_PRINT("SHFileOperation error: " + itos(ret));
  603. return FAILED;
  604. }
  605. return OK;
  606. }
  607. OS_Windows::OS_Windows(HINSTANCE _hInstance) {
  608. ticks_per_second = 0;
  609. ticks_start = 0;
  610. main_loop = nullptr;
  611. process_map = nullptr;
  612. force_quit = false;
  613. hInstance = _hInstance;
  614. #ifdef STDOUT_FILE
  615. stdo = fopen("stdout.txt", "wb");
  616. #endif
  617. #ifdef WASAPI_ENABLED
  618. AudioDriverManager::add_driver(&driver_wasapi);
  619. #endif
  620. #ifdef XAUDIO2_ENABLED
  621. AudioDriverManager::add_driver(&driver_xaudio2);
  622. #endif
  623. DisplayServerWindows::register_windows_driver();
  624. Vector<Logger *> loggers;
  625. loggers.push_back(memnew(WindowsTerminalLogger));
  626. _set_logger(memnew(CompositeLogger(loggers)));
  627. }
  628. OS_Windows::~OS_Windows() {
  629. #ifdef STDOUT_FILE
  630. fclose(stdo);
  631. #endif
  632. }