os_uwp.cpp 24 KB

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