2
0

display_server_javascript.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  1. /*************************************************************************/
  2. /* display_server_javascript.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "platform/javascript/display_server_javascript.h"
  31. #include "platform/javascript/os_javascript.h"
  32. #include "servers/rendering/rasterizer_dummy.h"
  33. #include <emscripten.h>
  34. #include <png.h>
  35. #include "dom_keys.inc"
  36. #include "godot_js.h"
  37. #define DOM_BUTTON_LEFT 0
  38. #define DOM_BUTTON_MIDDLE 1
  39. #define DOM_BUTTON_RIGHT 2
  40. #define DOM_BUTTON_XBUTTON1 3
  41. #define DOM_BUTTON_XBUTTON2 4
  42. DisplayServerJavaScript *DisplayServerJavaScript::get_singleton() {
  43. return static_cast<DisplayServerJavaScript *>(DisplayServer::get_singleton());
  44. }
  45. // Window (canvas)
  46. void DisplayServerJavaScript::focus_canvas() {
  47. godot_js_display_canvas_focus();
  48. }
  49. bool DisplayServerJavaScript::is_canvas_focused() {
  50. return godot_js_display_canvas_is_focused() != 0;
  51. }
  52. bool DisplayServerJavaScript::check_size_force_redraw() {
  53. return godot_js_display_size_update() != 0;
  54. }
  55. EM_BOOL DisplayServerJavaScript::fullscreen_change_callback(int p_event_type, const EmscriptenFullscreenChangeEvent *p_event, void *p_user_data) {
  56. DisplayServerJavaScript *display = get_singleton();
  57. // Empty ID is canvas.
  58. String target_id = String::utf8(p_event->id);
  59. if (target_id.is_empty() || target_id == String::utf8(&(display->canvas_id[1]))) {
  60. // This event property is the only reliable data on
  61. // browser fullscreen state.
  62. if (p_event->isFullscreen) {
  63. display->window_mode = WINDOW_MODE_FULLSCREEN;
  64. } else {
  65. display->window_mode = WINDOW_MODE_WINDOWED;
  66. }
  67. }
  68. return false;
  69. }
  70. // Drag and drop callback.
  71. void DisplayServerJavaScript::drop_files_js_callback(char **p_filev, int p_filec) {
  72. DisplayServerJavaScript *ds = get_singleton();
  73. if (!ds) {
  74. ERR_FAIL_MSG("Unable to drop files because the DisplayServer is not active");
  75. }
  76. if (ds->drop_files_callback.is_null()) {
  77. return;
  78. }
  79. Vector<String> files;
  80. for (int i = 0; i < p_filec; i++) {
  81. files.push_back(String::utf8(p_filev[i]));
  82. }
  83. Variant v = files;
  84. Variant *vp = &v;
  85. Variant ret;
  86. Callable::CallError ce;
  87. ds->drop_files_callback.call((const Variant **)&vp, 1, ret, ce);
  88. }
  89. // JavaScript quit request callback.
  90. void DisplayServerJavaScript::request_quit_callback() {
  91. DisplayServerJavaScript *ds = get_singleton();
  92. if (ds && !ds->window_event_callback.is_null()) {
  93. Variant event = int(DisplayServer::WINDOW_EVENT_CLOSE_REQUEST);
  94. Variant *eventp = &event;
  95. Variant ret;
  96. Callable::CallError ce;
  97. ds->window_event_callback.call((const Variant **)&eventp, 1, ret, ce);
  98. }
  99. }
  100. // Keys
  101. void DisplayServerJavaScript::dom2godot_mod(Ref<InputEventWithModifiers> ev, int p_mod) {
  102. ev->set_shift_pressed(p_mod & 1);
  103. ev->set_alt_pressed(p_mod & 2);
  104. ev->set_ctrl_pressed(p_mod & 4);
  105. ev->set_meta_pressed(p_mod & 8);
  106. }
  107. void DisplayServerJavaScript::key_callback(int p_pressed, int p_repeat, int p_modifiers) {
  108. DisplayServerJavaScript *ds = get_singleton();
  109. JSKeyEvent &key_event = ds->key_event;
  110. // Resume audio context after input in case autoplay was denied.
  111. OS_JavaScript::get_singleton()->resume_audio();
  112. Ref<InputEventKey> ev;
  113. ev.instantiate();
  114. ev->set_echo(p_repeat);
  115. ev->set_keycode(dom_code2godot_scancode(key_event.code, key_event.key, false));
  116. ev->set_physical_keycode(dom_code2godot_scancode(key_event.code, key_event.key, true));
  117. ev->set_pressed(p_pressed);
  118. dom2godot_mod(ev, p_modifiers);
  119. String unicode = String::utf8(key_event.key);
  120. if (unicode.length() == 1) {
  121. ev->set_unicode(unicode[0]);
  122. }
  123. Input::get_singleton()->parse_input_event(ev);
  124. // Make sure to flush all events so we can call restricted APIs inside the event.
  125. Input::get_singleton()->flush_buffered_events();
  126. }
  127. // Mouse
  128. int DisplayServerJavaScript::mouse_button_callback(int p_pressed, int p_button, double p_x, double p_y, int p_modifiers) {
  129. DisplayServerJavaScript *ds = get_singleton();
  130. Ref<InputEventMouseButton> ev;
  131. ev.instantiate();
  132. ev->set_pressed(p_pressed);
  133. ev->set_position(Point2(p_x, p_y));
  134. ev->set_global_position(ev->get_position());
  135. ev->set_pressed(p_pressed);
  136. dom2godot_mod(ev, p_modifiers);
  137. switch (p_button) {
  138. case DOM_BUTTON_LEFT:
  139. ev->set_button_index(MOUSE_BUTTON_LEFT);
  140. break;
  141. case DOM_BUTTON_MIDDLE:
  142. ev->set_button_index(MOUSE_BUTTON_MIDDLE);
  143. break;
  144. case DOM_BUTTON_RIGHT:
  145. ev->set_button_index(MOUSE_BUTTON_RIGHT);
  146. break;
  147. case DOM_BUTTON_XBUTTON1:
  148. ev->set_button_index(MOUSE_BUTTON_XBUTTON1);
  149. break;
  150. case DOM_BUTTON_XBUTTON2:
  151. ev->set_button_index(MOUSE_BUTTON_XBUTTON2);
  152. break;
  153. default:
  154. return false;
  155. }
  156. if (p_pressed) {
  157. uint64_t diff = (OS::get_singleton()->get_ticks_usec() / 1000) - ds->last_click_ms;
  158. if (ev->get_button_index() == ds->last_click_button_index) {
  159. if (diff < 400 && Point2(ds->last_click_pos).distance_to(ev->get_position()) < 5) {
  160. ds->last_click_ms = 0;
  161. ds->last_click_pos = Point2(-100, -100);
  162. ds->last_click_button_index = -1;
  163. ev->set_double_click(true);
  164. }
  165. } else {
  166. ds->last_click_button_index = ev->get_button_index();
  167. }
  168. if (!ev->is_double_click()) {
  169. ds->last_click_ms += diff;
  170. ds->last_click_pos = ev->get_position();
  171. }
  172. }
  173. int mask = Input::get_singleton()->get_mouse_button_mask();
  174. int button_flag = 1 << (ev->get_button_index() - 1);
  175. if (ev->is_pressed()) {
  176. mask |= button_flag;
  177. } else if (mask & button_flag) {
  178. mask &= ~button_flag;
  179. } else {
  180. // Received release event, but press was outside the canvas, so ignore.
  181. return false;
  182. }
  183. ev->set_button_mask(mask);
  184. Input::get_singleton()->parse_input_event(ev);
  185. // Resume audio context after input in case autoplay was denied.
  186. OS_JavaScript::get_singleton()->resume_audio();
  187. // Make sure to flush all events so we can call restricted APIs inside the event.
  188. Input::get_singleton()->flush_buffered_events();
  189. // Prevent multi-click text selection and wheel-click scrolling anchor.
  190. // Context menu is prevented through contextmenu event.
  191. return true;
  192. }
  193. void DisplayServerJavaScript::mouse_move_callback(double p_x, double p_y, double p_rel_x, double p_rel_y, int p_modifiers) {
  194. int input_mask = Input::get_singleton()->get_mouse_button_mask();
  195. // For motion outside the canvas, only read mouse movement if dragging
  196. // started inside the canvas; imitating desktop app behaviour.
  197. if (!get_singleton()->cursor_inside_canvas && !input_mask)
  198. return;
  199. Ref<InputEventMouseMotion> ev;
  200. ev.instantiate();
  201. dom2godot_mod(ev, p_modifiers);
  202. ev->set_button_mask(input_mask);
  203. ev->set_position(Point2(p_x, p_y));
  204. ev->set_global_position(ev->get_position());
  205. ev->set_relative(Vector2(p_rel_x, p_rel_y));
  206. Input::get_singleton()->set_mouse_position(ev->get_position());
  207. ev->set_speed(Input::get_singleton()->get_last_mouse_speed());
  208. Input::get_singleton()->parse_input_event(ev);
  209. }
  210. // Cursor
  211. const char *DisplayServerJavaScript::godot2dom_cursor(DisplayServer::CursorShape p_shape) {
  212. switch (p_shape) {
  213. case DisplayServer::CURSOR_ARROW:
  214. return "auto";
  215. case DisplayServer::CURSOR_IBEAM:
  216. return "text";
  217. case DisplayServer::CURSOR_POINTING_HAND:
  218. return "pointer";
  219. case DisplayServer::CURSOR_CROSS:
  220. return "crosshair";
  221. case DisplayServer::CURSOR_WAIT:
  222. return "progress";
  223. case DisplayServer::CURSOR_BUSY:
  224. return "wait";
  225. case DisplayServer::CURSOR_DRAG:
  226. return "grab";
  227. case DisplayServer::CURSOR_CAN_DROP:
  228. return "grabbing";
  229. case DisplayServer::CURSOR_FORBIDDEN:
  230. return "no-drop";
  231. case DisplayServer::CURSOR_VSIZE:
  232. return "ns-resize";
  233. case DisplayServer::CURSOR_HSIZE:
  234. return "ew-resize";
  235. case DisplayServer::CURSOR_BDIAGSIZE:
  236. return "nesw-resize";
  237. case DisplayServer::CURSOR_FDIAGSIZE:
  238. return "nwse-resize";
  239. case DisplayServer::CURSOR_MOVE:
  240. return "move";
  241. case DisplayServer::CURSOR_VSPLIT:
  242. return "row-resize";
  243. case DisplayServer::CURSOR_HSPLIT:
  244. return "col-resize";
  245. case DisplayServer::CURSOR_HELP:
  246. return "help";
  247. default:
  248. return "auto";
  249. }
  250. }
  251. void DisplayServerJavaScript::cursor_set_shape(CursorShape p_shape) {
  252. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  253. if (cursor_shape == p_shape) {
  254. return;
  255. }
  256. cursor_shape = p_shape;
  257. godot_js_display_cursor_set_shape(godot2dom_cursor(cursor_shape));
  258. }
  259. DisplayServer::CursorShape DisplayServerJavaScript::cursor_get_shape() const {
  260. return cursor_shape;
  261. }
  262. void DisplayServerJavaScript::cursor_set_custom_image(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  263. if (p_cursor.is_valid()) {
  264. Ref<Texture2D> texture = p_cursor;
  265. Ref<AtlasTexture> atlas_texture = p_cursor;
  266. Ref<Image> image;
  267. Size2 texture_size;
  268. Rect2 atlas_rect;
  269. if (texture.is_valid()) {
  270. image = texture->get_image();
  271. }
  272. if (!image.is_valid() && atlas_texture.is_valid()) {
  273. texture = atlas_texture->get_atlas();
  274. atlas_rect.size.width = texture->get_width();
  275. atlas_rect.size.height = texture->get_height();
  276. atlas_rect.position.x = atlas_texture->get_region().position.x;
  277. atlas_rect.position.y = atlas_texture->get_region().position.y;
  278. texture_size.width = atlas_texture->get_region().size.x;
  279. texture_size.height = atlas_texture->get_region().size.y;
  280. } else if (image.is_valid()) {
  281. texture_size.width = texture->get_width();
  282. texture_size.height = texture->get_height();
  283. }
  284. ERR_FAIL_COND(!texture.is_valid());
  285. ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
  286. ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
  287. ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
  288. image = texture->get_image();
  289. ERR_FAIL_COND(!image.is_valid());
  290. image = image->duplicate();
  291. if (atlas_texture.is_valid())
  292. image->crop_from_point(
  293. atlas_rect.position.x,
  294. atlas_rect.position.y,
  295. texture_size.width,
  296. texture_size.height);
  297. if (image->get_format() != Image::FORMAT_RGBA8) {
  298. image->convert(Image::FORMAT_RGBA8);
  299. }
  300. png_image png_meta;
  301. memset(&png_meta, 0, sizeof png_meta);
  302. png_meta.version = PNG_IMAGE_VERSION;
  303. png_meta.width = texture_size.width;
  304. png_meta.height = texture_size.height;
  305. png_meta.format = PNG_FORMAT_RGBA;
  306. PackedByteArray png;
  307. size_t len;
  308. PackedByteArray data = image->get_data();
  309. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, data.ptr(), 0, nullptr));
  310. png.resize(len);
  311. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, png.ptrw(), &len, 0, data.ptr(), 0, nullptr));
  312. godot_js_display_cursor_set_custom_shape(godot2dom_cursor(p_shape), png.ptr(), len, p_hotspot.x, p_hotspot.y);
  313. } else {
  314. godot_js_display_cursor_set_custom_shape(godot2dom_cursor(p_shape), nullptr, 0, 0, 0);
  315. }
  316. cursor_set_shape(cursor_shape);
  317. }
  318. // Mouse mode
  319. void DisplayServerJavaScript::mouse_set_mode(MouseMode p_mode) {
  320. ERR_FAIL_COND_MSG(p_mode == MOUSE_MODE_CONFINED || p_mode == MOUSE_MODE_CONFINED_HIDDEN, "MOUSE_MODE_CONFINED is not supported for the HTML5 platform.");
  321. if (p_mode == mouse_get_mode()) {
  322. return;
  323. }
  324. if (p_mode == MOUSE_MODE_VISIBLE) {
  325. godot_js_display_cursor_set_visible(1);
  326. emscripten_exit_pointerlock();
  327. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  328. godot_js_display_cursor_set_visible(0);
  329. emscripten_exit_pointerlock();
  330. } else if (p_mode == MOUSE_MODE_CAPTURED) {
  331. godot_js_display_cursor_set_visible(1);
  332. EMSCRIPTEN_RESULT result = emscripten_request_pointerlock(canvas_id, false);
  333. ERR_FAIL_COND_MSG(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED, "MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback.");
  334. ERR_FAIL_COND_MSG(result != EMSCRIPTEN_RESULT_SUCCESS, "MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback.");
  335. }
  336. }
  337. DisplayServer::MouseMode DisplayServerJavaScript::mouse_get_mode() const {
  338. if (godot_js_display_cursor_is_hidden()) {
  339. return MOUSE_MODE_HIDDEN;
  340. }
  341. EmscriptenPointerlockChangeEvent ev;
  342. emscripten_get_pointerlock_status(&ev);
  343. return (ev.isActive && String::utf8(ev.id) == String::utf8(&canvas_id[1])) ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE;
  344. }
  345. // Wheel
  346. int DisplayServerJavaScript::mouse_wheel_callback(double p_delta_x, double p_delta_y) {
  347. if (!godot_js_display_canvas_is_focused()) {
  348. if (get_singleton()->cursor_inside_canvas) {
  349. godot_js_display_canvas_focus();
  350. } else {
  351. return false;
  352. }
  353. }
  354. Input *input = Input::get_singleton();
  355. Ref<InputEventMouseButton> ev;
  356. ev.instantiate();
  357. ev->set_position(input->get_mouse_position());
  358. ev->set_global_position(ev->get_position());
  359. ev->set_shift_pressed(input->is_key_pressed(KEY_SHIFT));
  360. ev->set_alt_pressed(input->is_key_pressed(KEY_ALT));
  361. ev->set_ctrl_pressed(input->is_key_pressed(KEY_CTRL));
  362. ev->set_meta_pressed(input->is_key_pressed(KEY_META));
  363. if (p_delta_y < 0) {
  364. ev->set_button_index(MOUSE_BUTTON_WHEEL_UP);
  365. } else if (p_delta_y > 0) {
  366. ev->set_button_index(MOUSE_BUTTON_WHEEL_DOWN);
  367. } else if (p_delta_x > 0) {
  368. ev->set_button_index(MOUSE_BUTTON_WHEEL_LEFT);
  369. } else if (p_delta_x < 0) {
  370. ev->set_button_index(MOUSE_BUTTON_WHEEL_RIGHT);
  371. } else {
  372. return false;
  373. }
  374. // Different browsers give wildly different delta values, and we can't
  375. // interpret deltaMode, so use default value for wheel events' factor.
  376. int button_flag = 1 << (ev->get_button_index() - 1);
  377. ev->set_pressed(true);
  378. ev->set_button_mask(input->get_mouse_button_mask() | button_flag);
  379. input->parse_input_event(ev);
  380. Ref<InputEventMouseButton> release = ev->duplicate();
  381. release->set_pressed(false);
  382. release->set_button_mask(MouseButton(input->get_mouse_button_mask() & ~button_flag));
  383. input->parse_input_event(release);
  384. return true;
  385. }
  386. // Touch
  387. void DisplayServerJavaScript::touch_callback(int p_type, int p_count) {
  388. DisplayServerJavaScript *ds = get_singleton();
  389. const JSTouchEvent &touch_event = ds->touch_event;
  390. for (int i = 0; i < p_count; i++) {
  391. Point2 point(touch_event.coords[i * 2], touch_event.coords[i * 2 + 1]);
  392. if (p_type == 2) {
  393. // touchmove
  394. Ref<InputEventScreenDrag> ev;
  395. ev.instantiate();
  396. ev->set_index(touch_event.identifier[i]);
  397. ev->set_position(point);
  398. Point2 &prev = ds->touches[i];
  399. ev->set_relative(ev->get_position() - prev);
  400. prev = ev->get_position();
  401. Input::get_singleton()->parse_input_event(ev);
  402. } else {
  403. // touchstart/touchend
  404. Ref<InputEventScreenTouch> ev;
  405. // Resume audio context after input in case autoplay was denied.
  406. OS_JavaScript::get_singleton()->resume_audio();
  407. ev.instantiate();
  408. ev->set_index(touch_event.identifier[i]);
  409. ev->set_position(point);
  410. ev->set_pressed(p_type == 0);
  411. ds->touches[i] = point;
  412. Input::get_singleton()->parse_input_event(ev);
  413. // Make sure to flush all events so we can call restricted APIs inside the event.
  414. Input::get_singleton()->flush_buffered_events();
  415. }
  416. }
  417. }
  418. bool DisplayServerJavaScript::screen_is_touchscreen(int p_screen) const {
  419. return godot_js_display_touchscreen_is_available();
  420. }
  421. // Virtual Keyboard
  422. void DisplayServerJavaScript::vk_input_text_callback(const char *p_text, int p_cursor) {
  423. DisplayServerJavaScript *ds = DisplayServerJavaScript::get_singleton();
  424. if (!ds || ds->input_text_callback.is_null()) {
  425. return;
  426. }
  427. // Call input_text
  428. Variant event = String(p_text);
  429. Variant *eventp = &event;
  430. Variant ret;
  431. Callable::CallError ce;
  432. ds->input_text_callback.call((const Variant **)&eventp, 1, ret, ce);
  433. // Insert key right to reach position.
  434. Input *input = Input::get_singleton();
  435. Ref<InputEventKey> k;
  436. for (int i = 0; i < p_cursor; i++) {
  437. k.instantiate();
  438. k->set_pressed(true);
  439. k->set_echo(false);
  440. k->set_keycode(KEY_RIGHT);
  441. input->parse_input_event(k);
  442. k.instantiate();
  443. k->set_pressed(false);
  444. k->set_echo(false);
  445. k->set_keycode(KEY_RIGHT);
  446. input->parse_input_event(k);
  447. }
  448. }
  449. void DisplayServerJavaScript::virtual_keyboard_show(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) {
  450. godot_js_display_vk_show(p_existing_text.utf8().get_data(), p_multiline, p_cursor_start, p_cursor_end);
  451. }
  452. void DisplayServerJavaScript::virtual_keyboard_hide() {
  453. godot_js_display_vk_hide();
  454. }
  455. // Window blur callback
  456. EM_BOOL DisplayServerJavaScript::blur_callback(int p_event_type, const EmscriptenFocusEvent *p_event, void *p_user_data) {
  457. Input::get_singleton()->release_pressed_events();
  458. return false;
  459. }
  460. // Gamepad
  461. void DisplayServerJavaScript::gamepad_callback(int p_index, int p_connected, const char *p_id, const char *p_guid) {
  462. Input *input = Input::get_singleton();
  463. if (p_connected) {
  464. input->joy_connection_changed(p_index, true, String::utf8(p_id), String::utf8(p_guid));
  465. } else {
  466. input->joy_connection_changed(p_index, false, "");
  467. }
  468. }
  469. void DisplayServerJavaScript::process_joypads() {
  470. Input *input = Input::get_singleton();
  471. int32_t pads = godot_js_display_gamepad_sample_count();
  472. int32_t s_btns_num = 0;
  473. int32_t s_axes_num = 0;
  474. int32_t s_standard = 0;
  475. float s_btns[16];
  476. float s_axes[10];
  477. for (int idx = 0; idx < pads; idx++) {
  478. int err = godot_js_display_gamepad_sample_get(idx, s_btns, &s_btns_num, s_axes, &s_axes_num, &s_standard);
  479. if (err) {
  480. continue;
  481. }
  482. for (int b = 0; b < s_btns_num; b++) {
  483. float value = s_btns[b];
  484. // Buttons 6 and 7 in the standard mapping need to be
  485. // axis to be handled as JOY_AXIS_TRIGGER by Godot.
  486. if (s_standard && (b == 6 || b == 7)) {
  487. Input::JoyAxisValue joy_axis;
  488. joy_axis.min = 0;
  489. joy_axis.value = value;
  490. JoyAxis a = b == 6 ? JOY_AXIS_TRIGGER_LEFT : JOY_AXIS_TRIGGER_RIGHT;
  491. input->joy_axis(idx, a, joy_axis);
  492. } else {
  493. input->joy_button(idx, (JoyButton)b, value);
  494. }
  495. }
  496. for (int a = 0; a < s_axes_num; a++) {
  497. Input::JoyAxisValue joy_axis;
  498. joy_axis.min = -1;
  499. joy_axis.value = s_axes[a];
  500. input->joy_axis(idx, (JoyAxis)a, joy_axis);
  501. }
  502. }
  503. }
  504. Vector<String> DisplayServerJavaScript::get_rendering_drivers_func() {
  505. Vector<String> drivers;
  506. drivers.push_back("dummy");
  507. return drivers;
  508. }
  509. // Clipboard
  510. void DisplayServerJavaScript::update_clipboard_callback(const char *p_text) {
  511. get_singleton()->clipboard = p_text;
  512. }
  513. void DisplayServerJavaScript::clipboard_set(const String &p_text) {
  514. clipboard = p_text;
  515. int err = godot_js_display_clipboard_set(p_text.utf8().get_data());
  516. ERR_FAIL_COND_MSG(err, "Clipboard API is not supported.");
  517. }
  518. String DisplayServerJavaScript::clipboard_get() const {
  519. godot_js_display_clipboard_get(update_clipboard_callback);
  520. return clipboard;
  521. }
  522. void DisplayServerJavaScript::send_window_event_callback(int p_notification) {
  523. DisplayServerJavaScript *ds = get_singleton();
  524. if (!ds) {
  525. return;
  526. }
  527. if (p_notification == DisplayServer::WINDOW_EVENT_MOUSE_ENTER || p_notification == DisplayServer::WINDOW_EVENT_MOUSE_EXIT) {
  528. ds->cursor_inside_canvas = p_notification == DisplayServer::WINDOW_EVENT_MOUSE_ENTER;
  529. }
  530. if (!ds->window_event_callback.is_null()) {
  531. Variant event = int(p_notification);
  532. Variant *eventp = &event;
  533. Variant ret;
  534. Callable::CallError ce;
  535. ds->window_event_callback.call((const Variant **)&eventp, 1, ret, ce);
  536. }
  537. }
  538. void DisplayServerJavaScript::set_icon(const Ref<Image> &p_icon) {
  539. ERR_FAIL_COND(p_icon.is_null());
  540. Ref<Image> icon = p_icon;
  541. if (icon->is_compressed()) {
  542. icon = icon->duplicate();
  543. ERR_FAIL_COND(icon->decompress() != OK);
  544. }
  545. if (icon->get_format() != Image::FORMAT_RGBA8) {
  546. if (icon == p_icon)
  547. icon = icon->duplicate();
  548. icon->convert(Image::FORMAT_RGBA8);
  549. }
  550. png_image png_meta;
  551. memset(&png_meta, 0, sizeof png_meta);
  552. png_meta.version = PNG_IMAGE_VERSION;
  553. png_meta.width = icon->get_width();
  554. png_meta.height = icon->get_height();
  555. png_meta.format = PNG_FORMAT_RGBA;
  556. PackedByteArray png;
  557. size_t len;
  558. PackedByteArray data = icon->get_data();
  559. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, data.ptr(), 0, nullptr));
  560. png.resize(len);
  561. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, png.ptrw(), &len, 0, data.ptr(), 0, nullptr));
  562. godot_js_display_window_icon_set(png.ptr(), len);
  563. }
  564. void DisplayServerJavaScript::_dispatch_input_event(const Ref<InputEvent> &p_event) {
  565. Callable cb = get_singleton()->input_event_callback;
  566. if (!cb.is_null()) {
  567. Variant ev = p_event;
  568. Variant *evp = &ev;
  569. Variant ret;
  570. Callable::CallError ce;
  571. cb.call((const Variant **)&evp, 1, ret, ce);
  572. }
  573. }
  574. DisplayServer *DisplayServerJavaScript::create_func(const String &p_rendering_driver, WindowMode p_window_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Size2i &p_resolution, Error &r_error) {
  575. return memnew(DisplayServerJavaScript(p_rendering_driver, p_window_mode, p_vsync_mode, p_flags, p_resolution, r_error));
  576. }
  577. DisplayServerJavaScript::DisplayServerJavaScript(const String &p_rendering_driver, WindowMode p_window_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Size2i &p_resolution, Error &r_error) {
  578. r_error = OK; // Always succeeds for now.
  579. // Ensure the canvas ID.
  580. godot_js_config_canvas_id_get(canvas_id, 256);
  581. // Handle contextmenu, webglcontextlost
  582. godot_js_display_setup_canvas(p_resolution.x, p_resolution.y, p_window_mode == WINDOW_MODE_FULLSCREEN, OS::get_singleton()->is_hidpi_allowed() ? 1 : 0);
  583. // Check if it's windows.
  584. swap_cancel_ok = godot_js_display_is_swap_ok_cancel() == 1;
  585. // Expose method for requesting quit.
  586. godot_js_os_request_quit_cb(request_quit_callback);
  587. RasterizerDummy::make_current(); // TODO GLES2 in Godot 4.0... or webgpu?
  588. #if 0
  589. EmscriptenWebGLContextAttributes attributes;
  590. emscripten_webgl_init_context_attributes(&attributes);
  591. attributes.alpha = GLOBAL_GET("display/window/per_pixel_transparency/allowed");
  592. attributes.antialias = false;
  593. ERR_FAIL_INDEX_V(p_video_driver, VIDEO_DRIVER_MAX, ERR_INVALID_PARAMETER);
  594. if (p_desired.layered) {
  595. set_window_per_pixel_transparency_enabled(true);
  596. }
  597. bool gl_initialization_error = false;
  598. if (RasterizerGLES2::is_viable() == OK) {
  599. attributes.majorVersion = 1;
  600. RasterizerGLES2::register_config();
  601. RasterizerGLES2::make_current();
  602. } else {
  603. gl_initialization_error = true;
  604. }
  605. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(canvas_id, &attributes);
  606. if (emscripten_webgl_make_context_current(ctx) != EMSCRIPTEN_RESULT_SUCCESS) {
  607. gl_initialization_error = true;
  608. }
  609. if (gl_initialization_error) {
  610. OS::get_singleton()->alert("Your browser does not seem to support WebGL. Please update your browser version.",
  611. "Unable to initialize video driver");
  612. return ERR_UNAVAILABLE;
  613. }
  614. video_driver_index = p_video_driver;
  615. #endif
  616. EMSCRIPTEN_RESULT result;
  617. #define EM_CHECK(ev) \
  618. if (result != EMSCRIPTEN_RESULT_SUCCESS) \
  619. ERR_PRINT("Error while setting " #ev " callback: Code " + itos(result));
  620. #define SET_EM_CALLBACK(target, ev, cb) \
  621. result = emscripten_set_##ev##_callback(target, nullptr, true, &cb); \
  622. EM_CHECK(ev)
  623. #define SET_EM_WINDOW_CALLBACK(ev, cb) \
  624. result = emscripten_set_##ev##_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, nullptr, false, &cb); \
  625. EM_CHECK(ev)
  626. // These callbacks from Emscripten's html5.h suffice to access most
  627. // JavaScript APIs.
  628. SET_EM_WINDOW_CALLBACK(blur, blur_callback)
  629. SET_EM_CALLBACK(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, fullscreenchange, fullscreen_change_callback)
  630. #undef SET_EM_CALLBACK
  631. #undef EM_CHECK
  632. godot_js_display_mouse_button_cb(&DisplayServerJavaScript::mouse_button_callback);
  633. godot_js_display_mouse_move_cb(&DisplayServerJavaScript::mouse_move_callback);
  634. godot_js_display_mouse_wheel_cb(&DisplayServerJavaScript::mouse_wheel_callback);
  635. godot_js_display_touch_cb(&DisplayServerJavaScript::touch_callback, touch_event.identifier, touch_event.coords);
  636. godot_js_display_key_cb(&DisplayServerJavaScript::key_callback, key_event.code, key_event.key);
  637. // For APIs that are not (sufficiently) exposed, a
  638. // library is used below (implemented in library_godot_display.js).
  639. godot_js_display_notification_cb(&send_window_event_callback,
  640. WINDOW_EVENT_MOUSE_ENTER,
  641. WINDOW_EVENT_MOUSE_EXIT,
  642. WINDOW_EVENT_FOCUS_IN,
  643. WINDOW_EVENT_FOCUS_OUT);
  644. godot_js_display_paste_cb(update_clipboard_callback);
  645. godot_js_display_drop_files_cb(drop_files_js_callback);
  646. godot_js_display_gamepad_cb(&DisplayServerJavaScript::gamepad_callback);
  647. godot_js_display_vk_cb(&vk_input_text_callback);
  648. Input::get_singleton()->set_event_dispatch_function(_dispatch_input_event);
  649. }
  650. DisplayServerJavaScript::~DisplayServerJavaScript() {
  651. //emscripten_webgl_commit_frame();
  652. //emscripten_webgl_destroy_context(webgl_ctx);
  653. }
  654. bool DisplayServerJavaScript::has_feature(Feature p_feature) const {
  655. switch (p_feature) {
  656. //case FEATURE_CONSOLE_WINDOW:
  657. //case FEATURE_GLOBAL_MENU:
  658. //case FEATURE_HIDPI:
  659. //case FEATURE_IME:
  660. case FEATURE_ICON:
  661. case FEATURE_CLIPBOARD:
  662. case FEATURE_CURSOR_SHAPE:
  663. case FEATURE_CUSTOM_CURSOR_SHAPE:
  664. case FEATURE_MOUSE:
  665. case FEATURE_TOUCHSCREEN:
  666. return true;
  667. //case FEATURE_MOUSE_WARP:
  668. //case FEATURE_NATIVE_DIALOG:
  669. //case FEATURE_NATIVE_ICON:
  670. //case FEATURE_WINDOW_TRANSPARENCY:
  671. //case FEATURE_KEEP_SCREEN_ON:
  672. //case FEATURE_ORIENTATION:
  673. case FEATURE_VIRTUAL_KEYBOARD:
  674. return godot_js_display_vk_available() != 0;
  675. default:
  676. return false;
  677. }
  678. }
  679. void DisplayServerJavaScript::register_javascript_driver() {
  680. register_create_function("javascript", create_func, get_rendering_drivers_func);
  681. }
  682. String DisplayServerJavaScript::get_name() const {
  683. return "javascript";
  684. }
  685. int DisplayServerJavaScript::get_screen_count() const {
  686. return 1;
  687. }
  688. Point2i DisplayServerJavaScript::screen_get_position(int p_screen) const {
  689. return Point2i(); // TODO offsetX/Y?
  690. }
  691. Size2i DisplayServerJavaScript::screen_get_size(int p_screen) const {
  692. int size[2];
  693. godot_js_display_screen_size_get(size, size + 1);
  694. return Size2(size[0], size[1]);
  695. }
  696. Rect2i DisplayServerJavaScript::screen_get_usable_rect(int p_screen) const {
  697. int size[2];
  698. godot_js_display_window_size_get(size, size + 1);
  699. return Rect2i(0, 0, size[0], size[1]);
  700. }
  701. int DisplayServerJavaScript::screen_get_dpi(int p_screen) const {
  702. return godot_js_display_screen_dpi_get();
  703. }
  704. float DisplayServerJavaScript::screen_get_scale(int p_screen) const {
  705. return godot_js_display_pixel_ratio_get();
  706. }
  707. Vector<DisplayServer::WindowID> DisplayServerJavaScript::get_window_list() const {
  708. Vector<WindowID> ret;
  709. ret.push_back(MAIN_WINDOW_ID);
  710. return ret;
  711. }
  712. DisplayServerJavaScript::WindowID DisplayServerJavaScript::get_window_at_screen_position(const Point2i &p_position) const {
  713. return MAIN_WINDOW_ID;
  714. }
  715. void DisplayServerJavaScript::window_attach_instance_id(ObjectID p_instance, WindowID p_window) {
  716. window_attached_instance_id = p_instance;
  717. }
  718. ObjectID DisplayServerJavaScript::window_get_attached_instance_id(WindowID p_window) const {
  719. return window_attached_instance_id;
  720. }
  721. void DisplayServerJavaScript::window_set_rect_changed_callback(const Callable &p_callable, WindowID p_window) {
  722. // Not supported.
  723. }
  724. void DisplayServerJavaScript::window_set_window_event_callback(const Callable &p_callable, WindowID p_window) {
  725. window_event_callback = p_callable;
  726. }
  727. void DisplayServerJavaScript::window_set_input_event_callback(const Callable &p_callable, WindowID p_window) {
  728. input_event_callback = p_callable;
  729. }
  730. void DisplayServerJavaScript::window_set_input_text_callback(const Callable &p_callable, WindowID p_window) {
  731. input_text_callback = p_callable;
  732. }
  733. void DisplayServerJavaScript::window_set_drop_files_callback(const Callable &p_callable, WindowID p_window) {
  734. drop_files_callback = p_callable;
  735. }
  736. void DisplayServerJavaScript::window_set_title(const String &p_title, WindowID p_window) {
  737. godot_js_display_window_title_set(p_title.utf8().get_data());
  738. }
  739. int DisplayServerJavaScript::window_get_current_screen(WindowID p_window) const {
  740. return 1;
  741. }
  742. void DisplayServerJavaScript::window_set_current_screen(int p_screen, WindowID p_window) {
  743. // Not implemented.
  744. }
  745. Point2i DisplayServerJavaScript::window_get_position(WindowID p_window) const {
  746. return Point2i(); // TODO Does this need implementation?
  747. }
  748. void DisplayServerJavaScript::window_set_position(const Point2i &p_position, WindowID p_window) {
  749. // Not supported.
  750. }
  751. void DisplayServerJavaScript::window_set_transient(WindowID p_window, WindowID p_parent) {
  752. // Not supported.
  753. }
  754. void DisplayServerJavaScript::window_set_max_size(const Size2i p_size, WindowID p_window) {
  755. // Not supported.
  756. }
  757. Size2i DisplayServerJavaScript::window_get_max_size(WindowID p_window) const {
  758. return Size2i();
  759. }
  760. void DisplayServerJavaScript::window_set_min_size(const Size2i p_size, WindowID p_window) {
  761. // Not supported.
  762. }
  763. Size2i DisplayServerJavaScript::window_get_min_size(WindowID p_window) const {
  764. return Size2i();
  765. }
  766. void DisplayServerJavaScript::window_set_size(const Size2i p_size, WindowID p_window) {
  767. godot_js_display_desired_size_set(p_size.x, p_size.y);
  768. }
  769. Size2i DisplayServerJavaScript::window_get_size(WindowID p_window) const {
  770. int size[2];
  771. godot_js_display_window_size_get(size, size + 1);
  772. return Size2i(size[0], size[1]);
  773. }
  774. Size2i DisplayServerJavaScript::window_get_real_size(WindowID p_window) const {
  775. return window_get_size(p_window);
  776. }
  777. void DisplayServerJavaScript::window_set_mode(WindowMode p_mode, WindowID p_window) {
  778. if (window_mode == p_mode)
  779. return;
  780. switch (p_mode) {
  781. case WINDOW_MODE_WINDOWED: {
  782. if (window_mode == WINDOW_MODE_FULLSCREEN) {
  783. godot_js_display_fullscreen_exit();
  784. }
  785. window_mode = WINDOW_MODE_WINDOWED;
  786. } break;
  787. case WINDOW_MODE_FULLSCREEN: {
  788. int result = godot_js_display_fullscreen_request();
  789. ERR_FAIL_COND_MSG(result, "The request was denied. Remember that enabling fullscreen is only possible from an input callback for the HTML5 platform.");
  790. } break;
  791. case WINDOW_MODE_MAXIMIZED:
  792. case WINDOW_MODE_MINIMIZED:
  793. WARN_PRINT("WindowMode MAXIMIZED and MINIMIZED are not supported in HTML5 platform.");
  794. break;
  795. default:
  796. break;
  797. }
  798. }
  799. DisplayServerJavaScript::WindowMode DisplayServerJavaScript::window_get_mode(WindowID p_window) const {
  800. return window_mode;
  801. }
  802. bool DisplayServerJavaScript::window_is_maximize_allowed(WindowID p_window) const {
  803. return false;
  804. }
  805. void DisplayServerJavaScript::window_set_flag(WindowFlags p_flag, bool p_enabled, WindowID p_window) {
  806. // Not supported.
  807. }
  808. bool DisplayServerJavaScript::window_get_flag(WindowFlags p_flag, WindowID p_window) const {
  809. return false;
  810. }
  811. void DisplayServerJavaScript::window_request_attention(WindowID p_window) {
  812. // Not supported.
  813. }
  814. void DisplayServerJavaScript::window_move_to_foreground(WindowID p_window) {
  815. // Not supported.
  816. }
  817. bool DisplayServerJavaScript::window_can_draw(WindowID p_window) const {
  818. return true;
  819. }
  820. bool DisplayServerJavaScript::can_any_window_draw() const {
  821. return true;
  822. }
  823. void DisplayServerJavaScript::process_events() {
  824. Input::get_singleton()->flush_buffered_events();
  825. if (godot_js_display_gamepad_sample() == OK) {
  826. process_joypads();
  827. }
  828. }
  829. int DisplayServerJavaScript::get_current_video_driver() const {
  830. return 1;
  831. }
  832. bool DisplayServerJavaScript::get_swap_cancel_ok() {
  833. return swap_cancel_ok;
  834. }
  835. void DisplayServerJavaScript::swap_buffers() {
  836. //emscripten_webgl_commit_frame();
  837. }