os_uwp.cpp 24 KB

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