os_uwp.cpp 24 KB

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