os_uwp.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. /*************************************************************************/
  2. /* os_uwp.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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_uwp.h)
  31. #include "drivers/unix/net_socket_posix.h"
  32. #include "os_uwp.h"
  33. #include "core/io/marshalls.h"
  34. #include "core/project_settings.h"
  35. #include "drivers/unix/ip_unix.h"
  36. #include "drivers/windows/dir_access_windows.h"
  37. #include "drivers/windows/file_access_windows.h"
  38. #include "drivers/windows/mutex_windows.h"
  39. #include "drivers/windows/rw_lock_windows.h"
  40. #include "drivers/windows/semaphore_windows.h"
  41. #include "main/main.h"
  42. #include "platform/windows/windows_terminal_logger.h"
  43. #include "servers/audio_server.h"
  44. #include "servers/rendering/rendering_server_raster.h"
  45. #include "servers/rendering/rendering_server_wrap_mt.h"
  46. #include "thread_uwp.h"
  47. #include <ppltasks.h>
  48. #include <wrl.h>
  49. using namespace Windows::ApplicationModel::Core;
  50. using namespace Windows::ApplicationModel::Activation;
  51. using namespace Windows::UI::Core;
  52. using namespace Windows::UI::Input;
  53. using namespace Windows::UI::Popups;
  54. using namespace Windows::Foundation;
  55. using namespace Windows::Graphics::Display;
  56. using namespace Microsoft::WRL;
  57. using namespace Windows::UI::ViewManagement;
  58. using namespace Windows::Devices::Input;
  59. using namespace Windows::Devices::Sensors;
  60. using namespace Windows::ApplicationModel::DataTransfer;
  61. using namespace concurrency;
  62. int OS_UWP::get_video_driver_count() const {
  63. return 2;
  64. }
  65. Size2 OS_UWP::get_window_size() const {
  66. Size2 size;
  67. size.width = video_mode.width;
  68. size.height = video_mode.height;
  69. return size;
  70. }
  71. int OS_UWP::get_current_video_driver() const {
  72. return video_driver_index;
  73. }
  74. void OS_UWP::set_window_size(const Size2 p_size) {
  75. Windows::Foundation::Size new_size;
  76. new_size.Width = p_size.width;
  77. new_size.Height = p_size.height;
  78. ApplicationView ^ view = ApplicationView::GetForCurrentView();
  79. if (view->TryResizeView(new_size)) {
  80. video_mode.width = p_size.width;
  81. video_mode.height = p_size.height;
  82. }
  83. }
  84. void OS_UWP::set_window_fullscreen(bool p_enabled) {
  85. ApplicationView ^ view = ApplicationView::GetForCurrentView();
  86. video_mode.fullscreen = view->IsFullScreenMode;
  87. if (video_mode.fullscreen == p_enabled)
  88. return;
  89. if (p_enabled) {
  90. video_mode.fullscreen = view->TryEnterFullScreenMode();
  91. } else {
  92. view->ExitFullScreenMode();
  93. video_mode.fullscreen = false;
  94. }
  95. }
  96. bool OS_UWP::is_window_fullscreen() const {
  97. return ApplicationView::GetForCurrentView()->IsFullScreenMode;
  98. }
  99. void OS_UWP::set_keep_screen_on(bool p_enabled) {
  100. if (is_keep_screen_on() == p_enabled)
  101. return;
  102. if (p_enabled)
  103. display_request->RequestActive();
  104. else
  105. display_request->RequestRelease();
  106. OS::set_keep_screen_on(p_enabled);
  107. }
  108. void OS_UWP::initialize_core() {
  109. last_button_state = 0;
  110. //RedirectIOToConsole();
  111. ThreadUWP::make_default();
  112. RWLockWindows::make_default();
  113. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_RESOURCES);
  114. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_USERDATA);
  115. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_FILESYSTEM);
  116. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_RESOURCES);
  117. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_USERDATA);
  118. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_FILESYSTEM);
  119. NetSocketPosix::make_default();
  120. // We need to know how often the clock is updated
  121. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second))
  122. ticks_per_second = 1000;
  123. // If timeAtGameStart is 0 then we get the time since
  124. // the start of the computer when we call GetGameTime()
  125. ticks_start = 0;
  126. ticks_start = get_ticks_usec();
  127. IP_Unix::make_default();
  128. cursor_shape = CURSOR_ARROW;
  129. }
  130. bool OS_UWP::can_draw() const {
  131. return !minimized;
  132. };
  133. void OS_UWP::set_window(Windows::UI::Core::CoreWindow ^ p_window) {
  134. window = p_window;
  135. }
  136. void OS_UWP::screen_size_changed() {
  137. gl_context->reset();
  138. };
  139. Error OS_UWP::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  140. main_loop = nullptr;
  141. outside = true;
  142. // FIXME: Hardcoded for now, add Vulkan support.
  143. p_video_driver = VIDEO_DRIVER_GLES2;
  144. ContextEGL_UWP::Driver opengl_api_type = ContextEGL_UWP::GLES_2_0;
  145. bool gl_initialization_error = false;
  146. gl_context = memnew(ContextEGL_UWP(window, opengl_api_type));
  147. if (gl_context->initialize() != OK) {
  148. memdelete(gl_context);
  149. gl_context = nullptr;
  150. gl_initialization_error = true;
  151. }
  152. if (opengl_api_type == ContextEGL_UWP::GLES_2_0) {
  153. if (RasterizerGLES2::is_viable() == OK) {
  154. RasterizerGLES2::register_config();
  155. RasterizerGLES2::make_current();
  156. } else {
  157. gl_initialization_error = true;
  158. }
  159. }
  160. if (gl_initialization_error) {
  161. OS::get_singleton()->alert("Your video card driver does not support any of the supported OpenGL versions.\n"
  162. "Please update your drivers or if you have a very old or integrated GPU upgrade it.",
  163. "Unable to initialize video driver");
  164. return ERR_UNAVAILABLE;
  165. }
  166. video_driver_index = p_video_driver;
  167. gl_context->make_current();
  168. gl_context->set_use_vsync(video_mode.use_vsync);
  169. VideoMode vm;
  170. vm.width = gl_context->get_window_width();
  171. vm.height = gl_context->get_window_height();
  172. vm.resizable = false;
  173. ApplicationView ^ view = ApplicationView::GetForCurrentView();
  174. vm.fullscreen = view->IsFullScreenMode;
  175. view->SetDesiredBoundsMode(ApplicationViewBoundsMode::UseVisible);
  176. view->PreferredLaunchWindowingMode = ApplicationViewWindowingMode::PreferredLaunchViewSize;
  177. if (p_desired.fullscreen != view->IsFullScreenMode) {
  178. if (p_desired.fullscreen) {
  179. vm.fullscreen = view->TryEnterFullScreenMode();
  180. } else {
  181. view->ExitFullScreenMode();
  182. vm.fullscreen = false;
  183. }
  184. }
  185. Windows::Foundation::Size desired;
  186. desired.Width = p_desired.width;
  187. desired.Height = p_desired.height;
  188. view->PreferredLaunchViewSize = desired;
  189. if (view->TryResizeView(desired)) {
  190. vm.width = view->VisibleBounds.Width;
  191. vm.height = view->VisibleBounds.Height;
  192. }
  193. set_video_mode(vm);
  194. rendering_server = memnew(RenderingServerRaster);
  195. // FIXME: Reimplement threaded rendering
  196. if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) {
  197. rendering_server = memnew(RenderingServerWrapMT(rendering_server, false));
  198. }
  199. rendering_server->init();
  200. input = memnew(InputDefault);
  201. joypad = ref new JoypadUWP(input);
  202. joypad->register_events();
  203. AudioDriverManager::initialize(p_audio_driver);
  204. managed_object->update_clipboard();
  205. Clipboard::ContentChanged += ref new EventHandler<Platform::Object ^>(managed_object, &ManagedType::on_clipboard_changed);
  206. accelerometer = Accelerometer::GetDefault();
  207. if (accelerometer != nullptr) {
  208. // 60 FPS
  209. accelerometer->ReportInterval = (1.0f / 60.0f) * 1000;
  210. accelerometer->ReadingChanged +=
  211. ref new TypedEventHandler<Accelerometer ^, AccelerometerReadingChangedEventArgs ^>(managed_object, &ManagedType::on_accelerometer_reading_changed);
  212. }
  213. magnetometer = Magnetometer::GetDefault();
  214. if (magnetometer != nullptr) {
  215. // 60 FPS
  216. magnetometer->ReportInterval = (1.0f / 60.0f) * 1000;
  217. magnetometer->ReadingChanged +=
  218. ref new TypedEventHandler<Magnetometer ^, MagnetometerReadingChangedEventArgs ^>(managed_object, &ManagedType::on_magnetometer_reading_changed);
  219. }
  220. gyrometer = Gyrometer::GetDefault();
  221. if (gyrometer != nullptr) {
  222. // 60 FPS
  223. gyrometer->ReportInterval = (1.0f / 60.0f) * 1000;
  224. gyrometer->ReadingChanged +=
  225. ref new TypedEventHandler<Gyrometer ^, GyrometerReadingChangedEventArgs ^>(managed_object, &ManagedType::on_gyroscope_reading_changed);
  226. }
  227. _ensure_user_data_dir();
  228. if (is_keep_screen_on())
  229. display_request->RequestActive();
  230. set_keep_screen_on(GLOBAL_DEF("display/window/energy_saving/keep_screen_on", true));
  231. return OK;
  232. }
  233. void OS_UWP::set_clipboard(const String &p_text) {
  234. DataPackage ^ clip = ref new DataPackage();
  235. clip->RequestedOperation = DataPackageOperation::Copy;
  236. clip->SetText(ref new Platform::String((const wchar_t *)p_text.c_str()));
  237. Clipboard::SetContent(clip);
  238. };
  239. String OS_UWP::get_clipboard() const {
  240. if (managed_object->clipboard != nullptr)
  241. return managed_object->clipboard->Data();
  242. else
  243. return "";
  244. };
  245. void OS_UWP::input_event(const Ref<InputEvent> &p_event) {
  246. input->parse_input_event(p_event);
  247. };
  248. void OS_UWP::delete_main_loop() {
  249. if (main_loop)
  250. memdelete(main_loop);
  251. main_loop = nullptr;
  252. }
  253. void OS_UWP::set_main_loop(MainLoop *p_main_loop) {
  254. input->set_main_loop(p_main_loop);
  255. main_loop = p_main_loop;
  256. }
  257. void OS_UWP::finalize() {
  258. if (main_loop)
  259. memdelete(main_loop);
  260. main_loop = nullptr;
  261. rendering_server->finish();
  262. memdelete(rendering_server);
  263. #ifdef OPENGL_ENABLED
  264. if (gl_context)
  265. memdelete(gl_context);
  266. #endif
  267. memdelete(input);
  268. joypad = nullptr;
  269. }
  270. void OS_UWP::finalize_core() {
  271. NetSocketPosix::cleanup();
  272. }
  273. void OS_UWP::alert(const String &p_alert, const String &p_title) {
  274. Platform::String ^ alert = ref new Platform::String(p_alert.c_str());
  275. Platform::String ^ title = ref new Platform::String(p_title.c_str());
  276. MessageDialog ^ msg = ref new MessageDialog(alert, title);
  277. UICommand ^ close = ref new UICommand("Close", ref new UICommandInvokedHandler(managed_object, &OS_UWP::ManagedType::alert_close));
  278. msg->Commands->Append(close);
  279. msg->DefaultCommandIndex = 0;
  280. managed_object->alert_close_handle = true;
  281. msg->ShowAsync();
  282. }
  283. void OS_UWP::ManagedType::alert_close(IUICommand ^ command) {
  284. alert_close_handle = false;
  285. }
  286. void OS_UWP::ManagedType::on_clipboard_changed(Platform::Object ^ sender, Platform::Object ^ ev) {
  287. update_clipboard();
  288. }
  289. void OS_UWP::ManagedType::update_clipboard() {
  290. DataPackageView ^ data = Clipboard::GetContent();
  291. if (data->Contains(StandardDataFormats::Text)) {
  292. create_task(data->GetTextAsync()).then([this](Platform::String ^ clipboard_content) {
  293. this->clipboard = clipboard_content;
  294. });
  295. }
  296. }
  297. void OS_UWP::ManagedType::on_accelerometer_reading_changed(Accelerometer ^ sender, AccelerometerReadingChangedEventArgs ^ args) {
  298. AccelerometerReading ^ reading = args->Reading;
  299. os->input->set_accelerometer(Vector3(
  300. reading->AccelerationX,
  301. reading->AccelerationY,
  302. reading->AccelerationZ));
  303. }
  304. void OS_UWP::ManagedType::on_magnetometer_reading_changed(Magnetometer ^ sender, MagnetometerReadingChangedEventArgs ^ args) {
  305. MagnetometerReading ^ reading = args->Reading;
  306. os->input->set_magnetometer(Vector3(
  307. reading->MagneticFieldX,
  308. reading->MagneticFieldY,
  309. reading->MagneticFieldZ));
  310. }
  311. void OS_UWP::ManagedType::on_gyroscope_reading_changed(Gyrometer ^ sender, GyrometerReadingChangedEventArgs ^ args) {
  312. GyrometerReading ^ reading = args->Reading;
  313. os->input->set_magnetometer(Vector3(
  314. reading->AngularVelocityX,
  315. reading->AngularVelocityY,
  316. reading->AngularVelocityZ));
  317. }
  318. void OS_UWP::set_mouse_mode(MouseMode p_mode) {
  319. if (p_mode == MouseMode::MOUSE_MODE_CAPTURED) {
  320. CoreWindow::GetForCurrentThread()->SetPointerCapture();
  321. } else {
  322. CoreWindow::GetForCurrentThread()->ReleasePointerCapture();
  323. }
  324. if (p_mode == MouseMode::MOUSE_MODE_CAPTURED || p_mode == MouseMode::MOUSE_MODE_HIDDEN) {
  325. CoreWindow::GetForCurrentThread()->PointerCursor = nullptr;
  326. } else {
  327. CoreWindow::GetForCurrentThread()->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
  328. }
  329. mouse_mode = p_mode;
  330. SetEvent(mouse_mode_changed);
  331. }
  332. OS_UWP::MouseMode OS_UWP::get_mouse_mode() const {
  333. return mouse_mode;
  334. }
  335. Point2 OS_UWP::get_mouse_position() const {
  336. return Point2(old_x, old_y);
  337. }
  338. int OS_UWP::get_mouse_button_state() const {
  339. return last_button_state;
  340. }
  341. void OS_UWP::set_window_title(const String &p_title) {
  342. }
  343. void OS_UWP::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  344. video_mode = p_video_mode;
  345. }
  346. OS::VideoMode OS_UWP::get_video_mode(int p_screen) const {
  347. return video_mode;
  348. }
  349. void OS_UWP::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  350. }
  351. String OS_UWP::get_name() const {
  352. return "UWP";
  353. }
  354. OS::Date OS_UWP::get_date(bool utc) const {
  355. SYSTEMTIME systemtime;
  356. if (utc)
  357. GetSystemTime(&systemtime);
  358. else
  359. GetLocalTime(&systemtime);
  360. Date date;
  361. date.day = systemtime.wDay;
  362. date.month = Month(systemtime.wMonth);
  363. date.weekday = Weekday(systemtime.wDayOfWeek);
  364. date.year = systemtime.wYear;
  365. date.dst = false;
  366. return date;
  367. }
  368. OS::Time OS_UWP::get_time(bool utc) const {
  369. SYSTEMTIME systemtime;
  370. if (utc)
  371. GetSystemTime(&systemtime);
  372. else
  373. GetLocalTime(&systemtime);
  374. Time time;
  375. time.hour = systemtime.wHour;
  376. time.min = systemtime.wMinute;
  377. time.sec = systemtime.wSecond;
  378. return time;
  379. }
  380. OS::TimeZoneInfo OS_UWP::get_time_zone_info() const {
  381. TIME_ZONE_INFORMATION info;
  382. bool daylight = false;
  383. if (GetTimeZoneInformation(&info) == TIME_ZONE_ID_DAYLIGHT)
  384. daylight = true;
  385. TimeZoneInfo ret;
  386. if (daylight) {
  387. ret.name = info.DaylightName;
  388. } else {
  389. ret.name = info.StandardName;
  390. }
  391. // Bias value returned by GetTimeZoneInformation is inverted of what we expect
  392. // For example on GMT-3 GetTimeZoneInformation return a Bias of 180, so invert the value to get -180
  393. ret.bias = -info.Bias;
  394. return ret;
  395. }
  396. uint64_t OS_UWP::get_unix_time() const {
  397. FILETIME ft;
  398. SYSTEMTIME st;
  399. GetSystemTime(&st);
  400. SystemTimeToFileTime(&st, &ft);
  401. SYSTEMTIME ep;
  402. ep.wYear = 1970;
  403. ep.wMonth = 1;
  404. ep.wDayOfWeek = 4;
  405. ep.wDay = 1;
  406. ep.wHour = 0;
  407. ep.wMinute = 0;
  408. ep.wSecond = 0;
  409. ep.wMilliseconds = 0;
  410. FILETIME fep;
  411. SystemTimeToFileTime(&ep, &fep);
  412. return (*(uint64_t *)&ft - *(uint64_t *)&fep) / 10000000;
  413. };
  414. void OS_UWP::delay_usec(uint32_t p_usec) const {
  415. int msec = p_usec < 1000 ? 1 : p_usec / 1000;
  416. // no Sleep()
  417. WaitForSingleObjectEx(GetCurrentThread(), msec, false);
  418. }
  419. uint64_t OS_UWP::get_ticks_usec() const {
  420. uint64_t ticks;
  421. // This is the number of clock ticks since start
  422. QueryPerformanceCounter((LARGE_INTEGER *)&ticks);
  423. // Divide by frequency to get the time in seconds
  424. // original calculation shown below is subject to overflow
  425. // with high ticks_per_second and a number of days since the last reboot.
  426. // time = ticks * 1000000L / ticks_per_second;
  427. // we can prevent this by either using 128 bit math
  428. // or separating into a calculation for seconds, and the fraction
  429. uint64_t seconds = ticks / ticks_per_second;
  430. // compiler will optimize these two into one divide
  431. uint64_t leftover = ticks % ticks_per_second;
  432. // remainder
  433. uint64_t time = (leftover * 1000000L) / ticks_per_second;
  434. // seconds
  435. time += seconds * 1000000L;
  436. // Subtract the time at game start to get
  437. // the time since the game started
  438. time -= ticks_start;
  439. return time;
  440. }
  441. void OS_UWP::process_events() {
  442. joypad->process_controllers();
  443. process_key_events();
  444. }
  445. void OS_UWP::process_key_events() {
  446. for (int i = 0; i < key_event_pos; i++) {
  447. KeyEvent &kev = key_event_buffer[i];
  448. Ref<InputEventKey> key_event;
  449. key_event.instance();
  450. key_event->set_alt(kev.alt);
  451. key_event->set_shift(kev.shift);
  452. key_event->set_control(kev.control);
  453. key_event->set_echo(kev.echo);
  454. key_event->set_keycode(kev.keycode);
  455. key_event->set_physical_keycode(kev.physical_keycode);
  456. key_event->set_unicode(kev.unicode);
  457. key_event->set_pressed(kev.pressed);
  458. input_event(key_event);
  459. }
  460. key_event_pos = 0;
  461. }
  462. void OS_UWP::queue_key_event(KeyEvent &p_event) {
  463. // This merges Char events with the previous Key event, so
  464. // the unicode can be retrieved without sending duplicate events.
  465. if (p_event.type == KeyEvent::MessageType::CHAR_EVENT_MESSAGE && key_event_pos > 0) {
  466. KeyEvent &old = key_event_buffer[key_event_pos - 1];
  467. ERR_FAIL_COND(old.type != KeyEvent::MessageType::KEY_EVENT_MESSAGE);
  468. key_event_buffer[key_event_pos - 1].unicode = p_event.unicode;
  469. return;
  470. }
  471. ERR_FAIL_COND(key_event_pos >= KEY_EVENT_BUFFER_SIZE);
  472. key_event_buffer[key_event_pos++] = p_event;
  473. }
  474. void OS_UWP::set_cursor_shape(CursorShape p_shape) {
  475. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  476. if (cursor_shape == p_shape)
  477. return;
  478. static const CoreCursorType uwp_cursors[CURSOR_MAX] = {
  479. CoreCursorType::Arrow,
  480. CoreCursorType::IBeam,
  481. CoreCursorType::Hand,
  482. CoreCursorType::Cross,
  483. CoreCursorType::Wait,
  484. CoreCursorType::Wait,
  485. CoreCursorType::Arrow,
  486. CoreCursorType::Arrow,
  487. CoreCursorType::UniversalNo,
  488. CoreCursorType::SizeNorthSouth,
  489. CoreCursorType::SizeWestEast,
  490. CoreCursorType::SizeNortheastSouthwest,
  491. CoreCursorType::SizeNorthwestSoutheast,
  492. CoreCursorType::SizeAll,
  493. CoreCursorType::SizeNorthSouth,
  494. CoreCursorType::SizeWestEast,
  495. CoreCursorType::Help
  496. };
  497. CoreWindow::GetForCurrentThread()->PointerCursor = ref new CoreCursor(uwp_cursors[p_shape], 0);
  498. cursor_shape = p_shape;
  499. }
  500. OS::CursorShape OS_UWP::get_cursor_shape() const {
  501. return cursor_shape;
  502. }
  503. void OS_UWP::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  504. // TODO
  505. }
  506. Error OS_UWP::execute(const String &p_path, const List<String> &p_arguments, bool p_blocking, ProcessID *r_child_id, String *r_pipe, int *r_exitcode, bool read_stderr, Mutex *p_pipe_mutex) {
  507. return FAILED;
  508. };
  509. Error OS_UWP::kill(const ProcessID &p_pid) {
  510. return FAILED;
  511. };
  512. Error OS_UWP::set_cwd(const String &p_cwd) {
  513. return FAILED;
  514. }
  515. String OS_UWP::get_executable_path() const {
  516. return "";
  517. }
  518. void OS_UWP::set_icon(const Ref<Image> &p_icon) {
  519. }
  520. bool OS_UWP::has_environment(const String &p_var) const {
  521. return false;
  522. };
  523. String OS_UWP::get_environment(const String &p_var) const {
  524. return "";
  525. };
  526. bool OS_UWP::set_environment(const String &p_var, const String &p_value) const {
  527. return false;
  528. }
  529. String OS_UWP::get_stdin_string(bool p_block) {
  530. return String();
  531. }
  532. void OS_UWP::move_window_to_foreground() {
  533. }
  534. Error OS_UWP::shell_open(String p_uri) {
  535. return FAILED;
  536. }
  537. String OS_UWP::get_locale() const {
  538. #if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP // this should work on phone 8.1, but it doesn't
  539. return "en";
  540. #else
  541. Platform::String ^ language = Windows::Globalization::Language::CurrentInputMethodLanguageTag;
  542. return String(language->Data()).replace("-", "_");
  543. #endif
  544. }
  545. void OS_UWP::release_rendering_thread() {
  546. gl_context->release_current();
  547. }
  548. void OS_UWP::make_rendering_thread() {
  549. gl_context->make_current();
  550. }
  551. void OS_UWP::swap_buffers() {
  552. gl_context->swap_buffers();
  553. }
  554. bool OS_UWP::has_touchscreen_ui_hint() const {
  555. TouchCapabilities ^ tc = ref new TouchCapabilities();
  556. return tc->TouchPresent != 0 || UIViewSettings::GetForCurrentView()->UserInteractionMode == UserInteractionMode::Touch;
  557. }
  558. bool OS_UWP::has_virtual_keyboard() const {
  559. return UIViewSettings::GetForCurrentView()->UserInteractionMode == UserInteractionMode::Touch;
  560. }
  561. void OS_UWP::show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect, bool p_multiline, int p_max_input_length, int p_cursor_start, int p_cursor_end) {
  562. InputPane ^ pane = InputPane::GetForCurrentView();
  563. pane->TryShow();
  564. }
  565. void OS_UWP::hide_virtual_keyboard() {
  566. InputPane ^ pane = InputPane::GetForCurrentView();
  567. pane->TryHide();
  568. }
  569. static String format_error_message(DWORD id) {
  570. LPWSTR messageBuffer = nullptr;
  571. size_t size = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  572. nullptr, id, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&messageBuffer, 0, nullptr);
  573. String msg = "Error " + itos(id) + ": " + String(messageBuffer, size);
  574. LocalFree(messageBuffer);
  575. return msg;
  576. }
  577. Error OS_UWP::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
  578. String full_path = "game/" + p_path;
  579. p_library_handle = (void *)LoadPackagedLibrary(full_path.c_str(), 0);
  580. ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, "Can't open dynamic library: " + full_path + ", error: " + format_error_message(GetLastError()) + ".");
  581. return OK;
  582. }
  583. Error OS_UWP::close_dynamic_library(void *p_library_handle) {
  584. if (!FreeLibrary((HMODULE)p_library_handle)) {
  585. return FAILED;
  586. }
  587. return OK;
  588. }
  589. Error OS_UWP::get_dynamic_library_symbol_handle(void *p_library_handle, const String p_name, void *&p_symbol_handle, bool p_optional) {
  590. p_symbol_handle = (void *)GetProcAddress((HMODULE)p_library_handle, p_name.utf8().get_data());
  591. if (!p_symbol_handle) {
  592. if (!p_optional) {
  593. ERR_FAIL_V_MSG(ERR_CANT_RESOLVE, "Can't resolve symbol " + p_name + ", error: " + String::num(GetLastError()) + ".");
  594. } else {
  595. return ERR_CANT_RESOLVE;
  596. }
  597. }
  598. return OK;
  599. }
  600. void OS_UWP::run() {
  601. if (!main_loop)
  602. return;
  603. main_loop->init();
  604. uint64_t last_ticks = get_ticks_usec();
  605. int frames = 0;
  606. uint64_t frame = 0;
  607. while (!force_quit) {
  608. CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
  609. if (managed_object->alert_close_handle)
  610. continue;
  611. process_events(); // get rid of pending events
  612. if (Main::iteration())
  613. break;
  614. };
  615. main_loop->finish();
  616. }
  617. MainLoop *OS_UWP::get_main_loop() const {
  618. return main_loop;
  619. }
  620. String OS_UWP::get_user_data_dir() const {
  621. Windows::Storage::StorageFolder ^ data_folder = Windows::Storage::ApplicationData::Current->LocalFolder;
  622. return String(data_folder->Path->Data()).replace("\\", "/");
  623. }
  624. bool OS_UWP::_check_internal_feature_support(const String &p_feature) {
  625. return p_feature == "pc";
  626. }
  627. OS_UWP::OS_UWP() {
  628. key_event_pos = 0;
  629. force_quit = false;
  630. alt_mem = false;
  631. gr_mem = false;
  632. shift_mem = false;
  633. control_mem = false;
  634. meta_mem = false;
  635. minimized = false;
  636. pressrc = 0;
  637. old_invalid = true;
  638. mouse_mode = MOUSE_MODE_VISIBLE;
  639. #ifdef STDOUT_FILE
  640. stdo = fopen("stdout.txt", "wb");
  641. #endif
  642. gl_context = nullptr;
  643. display_request = ref new Windows::System::Display::DisplayRequest();
  644. managed_object = ref new ManagedType;
  645. managed_object->os = this;
  646. mouse_mode_changed = CreateEvent(nullptr, TRUE, FALSE, L"os_mouse_mode_changed");
  647. AudioDriverManager::add_driver(&audio_driver);
  648. Vector<Logger *> loggers;
  649. loggers.push_back(memnew(WindowsTerminalLogger));
  650. _set_logger(memnew(CompositeLogger(loggers)));
  651. }
  652. OS_UWP::~OS_UWP() {
  653. #ifdef STDOUT_FILE
  654. fclose(stdo);
  655. #endif
  656. }