display_server_javascript.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  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 "drivers/dummy/rasterizer_dummy.h"
  32. #include "platform/javascript/os_javascript.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. Point2 DisplayServerJavaScript::compute_position_in_canvas(int p_x, int p_y) {
  56. int point[2];
  57. godot_js_display_compute_position(p_x, p_y, point, point + 1);
  58. return Point2(point[0], point[1]);
  59. }
  60. EM_BOOL DisplayServerJavaScript::fullscreen_change_callback(int p_event_type, const EmscriptenFullscreenChangeEvent *p_event, void *p_user_data) {
  61. DisplayServerJavaScript *display = get_singleton();
  62. // Empty ID is canvas.
  63. String target_id = String::utf8(p_event->id);
  64. if (target_id.is_empty() || target_id == String::utf8(&(display->canvas_id[1]))) {
  65. // This event property is the only reliable data on
  66. // browser fullscreen state.
  67. if (p_event->isFullscreen) {
  68. display->window_mode = WINDOW_MODE_FULLSCREEN;
  69. } else {
  70. display->window_mode = WINDOW_MODE_WINDOWED;
  71. }
  72. }
  73. return false;
  74. }
  75. // Drag and drop callback.
  76. void DisplayServerJavaScript::drop_files_js_callback(char **p_filev, int p_filec) {
  77. DisplayServerJavaScript *ds = get_singleton();
  78. if (!ds) {
  79. ERR_FAIL_MSG("Unable to drop files because the DisplayServer is not active");
  80. }
  81. if (ds->drop_files_callback.is_null()) {
  82. return;
  83. }
  84. Vector<String> files;
  85. for (int i = 0; i < p_filec; i++) {
  86. files.push_back(String::utf8(p_filev[i]));
  87. }
  88. Variant v = files;
  89. Variant *vp = &v;
  90. Variant ret;
  91. Callable::CallError ce;
  92. ds->drop_files_callback.call((const Variant **)&vp, 1, ret, ce);
  93. }
  94. // JavaScript quit request callback.
  95. void DisplayServerJavaScript::request_quit_callback() {
  96. DisplayServerJavaScript *ds = get_singleton();
  97. if (ds && !ds->window_event_callback.is_null()) {
  98. Variant event = int(DisplayServer::WINDOW_EVENT_CLOSE_REQUEST);
  99. Variant *eventp = &event;
  100. Variant ret;
  101. Callable::CallError ce;
  102. ds->window_event_callback.call((const Variant **)&eventp, 1, ret, ce);
  103. }
  104. }
  105. // Keys
  106. template <typename T>
  107. void DisplayServerJavaScript::dom2godot_mod(T *emscripten_event_ptr, Ref<InputEventWithModifiers> godot_event) {
  108. godot_event->set_shift(emscripten_event_ptr->shiftKey);
  109. godot_event->set_alt(emscripten_event_ptr->altKey);
  110. godot_event->set_control(emscripten_event_ptr->ctrlKey);
  111. godot_event->set_metakey(emscripten_event_ptr->metaKey);
  112. }
  113. Ref<InputEventKey> DisplayServerJavaScript::setup_key_event(const EmscriptenKeyboardEvent *emscripten_event) {
  114. Ref<InputEventKey> ev;
  115. ev.instance();
  116. ev->set_echo(emscripten_event->repeat);
  117. dom2godot_mod(emscripten_event, ev);
  118. ev->set_keycode(dom_code2godot_scancode(emscripten_event->code, emscripten_event->key, false));
  119. ev->set_physical_keycode(dom_code2godot_scancode(emscripten_event->code, emscripten_event->key, true));
  120. String unicode = String::utf8(emscripten_event->key);
  121. // Check if empty or multi-character (e.g. `CapsLock`).
  122. if (unicode.length() != 1) {
  123. // Might be empty as well, but better than nonsense.
  124. unicode = String::utf8(emscripten_event->charValue);
  125. }
  126. if (unicode.length() == 1) {
  127. ev->set_unicode(unicode[0]);
  128. }
  129. return ev;
  130. }
  131. EM_BOOL DisplayServerJavaScript::keydown_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  132. DisplayServerJavaScript *display = get_singleton();
  133. Ref<InputEventKey> ev = setup_key_event(p_event);
  134. ev->set_pressed(true);
  135. if (ev->get_unicode() == 0 && keycode_has_unicode(ev->get_keycode())) {
  136. // Defer to keypress event for legacy unicode retrieval.
  137. display->deferred_key_event = ev;
  138. // Do not suppress keypress event.
  139. return false;
  140. }
  141. Input::get_singleton()->parse_input_event(ev);
  142. return true;
  143. }
  144. EM_BOOL DisplayServerJavaScript::keypress_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  145. DisplayServerJavaScript *display = get_singleton();
  146. display->deferred_key_event->set_unicode(p_event->charCode);
  147. Input::get_singleton()->parse_input_event(display->deferred_key_event);
  148. return true;
  149. }
  150. EM_BOOL DisplayServerJavaScript::keyup_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  151. Ref<InputEventKey> ev = setup_key_event(p_event);
  152. ev->set_pressed(false);
  153. Input::get_singleton()->parse_input_event(ev);
  154. return ev->get_keycode() != KEY_UNKNOWN && ev->get_keycode() != 0;
  155. }
  156. // Mouse
  157. EM_BOOL DisplayServerJavaScript::mouse_button_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) {
  158. DisplayServerJavaScript *display = get_singleton();
  159. Ref<InputEventMouseButton> ev;
  160. ev.instance();
  161. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_MOUSEDOWN);
  162. ev->set_position(compute_position_in_canvas(p_event->clientX, p_event->clientY));
  163. ev->set_global_position(ev->get_position());
  164. dom2godot_mod(p_event, ev);
  165. switch (p_event->button) {
  166. case DOM_BUTTON_LEFT:
  167. ev->set_button_index(BUTTON_LEFT);
  168. break;
  169. case DOM_BUTTON_MIDDLE:
  170. ev->set_button_index(BUTTON_MIDDLE);
  171. break;
  172. case DOM_BUTTON_RIGHT:
  173. ev->set_button_index(BUTTON_RIGHT);
  174. break;
  175. case DOM_BUTTON_XBUTTON1:
  176. ev->set_button_index(BUTTON_XBUTTON1);
  177. break;
  178. case DOM_BUTTON_XBUTTON2:
  179. ev->set_button_index(BUTTON_XBUTTON2);
  180. break;
  181. default:
  182. return false;
  183. }
  184. if (ev->is_pressed()) {
  185. double diff = emscripten_get_now() - display->last_click_ms;
  186. if (ev->get_button_index() == display->last_click_button_index) {
  187. if (diff < 400 && Point2(display->last_click_pos).distance_to(ev->get_position()) < 5) {
  188. display->last_click_ms = 0;
  189. display->last_click_pos = Point2(-100, -100);
  190. display->last_click_button_index = -1;
  191. ev->set_doubleclick(true);
  192. }
  193. } else {
  194. display->last_click_button_index = ev->get_button_index();
  195. }
  196. if (!ev->is_doubleclick()) {
  197. display->last_click_ms += diff;
  198. display->last_click_pos = ev->get_position();
  199. }
  200. }
  201. Input *input = Input::get_singleton();
  202. int mask = input->get_mouse_button_mask();
  203. int button_flag = 1 << (ev->get_button_index() - 1);
  204. if (ev->is_pressed()) {
  205. // Since the event is consumed, focus manually. The containing iframe,
  206. // if exists, may not have focus yet, so focus even if already focused.
  207. focus_canvas();
  208. mask |= button_flag;
  209. } else if (mask & button_flag) {
  210. mask &= ~button_flag;
  211. } else {
  212. // Received release event, but press was outside the canvas, so ignore.
  213. return false;
  214. }
  215. ev->set_button_mask(mask);
  216. input->parse_input_event(ev);
  217. // Prevent multi-click text selection and wheel-click scrolling anchor.
  218. // Context menu is prevented through contextmenu event.
  219. return true;
  220. }
  221. EM_BOOL DisplayServerJavaScript::mousemove_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) {
  222. DisplayServerJavaScript *ds = get_singleton();
  223. Input *input = Input::get_singleton();
  224. int input_mask = input->get_mouse_button_mask();
  225. Point2 pos = compute_position_in_canvas(p_event->clientX, p_event->clientY);
  226. // For motion outside the canvas, only read mouse movement if dragging
  227. // started inside the canvas; imitating desktop app behaviour.
  228. if (!ds->cursor_inside_canvas && !input_mask)
  229. return false;
  230. Ref<InputEventMouseMotion> ev;
  231. ev.instance();
  232. dom2godot_mod(p_event, ev);
  233. ev->set_button_mask(input_mask);
  234. ev->set_position(pos);
  235. ev->set_global_position(ev->get_position());
  236. ev->set_relative(Vector2(p_event->movementX, p_event->movementY));
  237. input->set_mouse_position(ev->get_position());
  238. ev->set_speed(input->get_last_mouse_speed());
  239. input->parse_input_event(ev);
  240. // Don't suppress mouseover/-leave events.
  241. return false;
  242. }
  243. // Cursor
  244. const char *DisplayServerJavaScript::godot2dom_cursor(DisplayServer::CursorShape p_shape) {
  245. switch (p_shape) {
  246. case DisplayServer::CURSOR_ARROW:
  247. return "auto";
  248. case DisplayServer::CURSOR_IBEAM:
  249. return "text";
  250. case DisplayServer::CURSOR_POINTING_HAND:
  251. return "pointer";
  252. case DisplayServer::CURSOR_CROSS:
  253. return "crosshair";
  254. case DisplayServer::CURSOR_WAIT:
  255. return "progress";
  256. case DisplayServer::CURSOR_BUSY:
  257. return "wait";
  258. case DisplayServer::CURSOR_DRAG:
  259. return "grab";
  260. case DisplayServer::CURSOR_CAN_DROP:
  261. return "grabbing";
  262. case DisplayServer::CURSOR_FORBIDDEN:
  263. return "no-drop";
  264. case DisplayServer::CURSOR_VSIZE:
  265. return "ns-resize";
  266. case DisplayServer::CURSOR_HSIZE:
  267. return "ew-resize";
  268. case DisplayServer::CURSOR_BDIAGSIZE:
  269. return "nesw-resize";
  270. case DisplayServer::CURSOR_FDIAGSIZE:
  271. return "nwse-resize";
  272. case DisplayServer::CURSOR_MOVE:
  273. return "move";
  274. case DisplayServer::CURSOR_VSPLIT:
  275. return "row-resize";
  276. case DisplayServer::CURSOR_HSPLIT:
  277. return "col-resize";
  278. case DisplayServer::CURSOR_HELP:
  279. return "help";
  280. default:
  281. return "auto";
  282. }
  283. }
  284. void DisplayServerJavaScript::cursor_set_shape(CursorShape p_shape) {
  285. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  286. if (cursor_shape == p_shape) {
  287. return;
  288. }
  289. cursor_shape = p_shape;
  290. godot_js_display_cursor_set_shape(godot2dom_cursor(cursor_shape));
  291. }
  292. DisplayServer::CursorShape DisplayServerJavaScript::cursor_get_shape() const {
  293. return cursor_shape;
  294. }
  295. void DisplayServerJavaScript::cursor_set_custom_image(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  296. if (p_cursor.is_valid()) {
  297. Ref<Texture2D> texture = p_cursor;
  298. Ref<AtlasTexture> atlas_texture = p_cursor;
  299. Ref<Image> image;
  300. Size2 texture_size;
  301. Rect2 atlas_rect;
  302. if (texture.is_valid()) {
  303. image = texture->get_data();
  304. }
  305. if (!image.is_valid() && atlas_texture.is_valid()) {
  306. texture = atlas_texture->get_atlas();
  307. atlas_rect.size.width = texture->get_width();
  308. atlas_rect.size.height = texture->get_height();
  309. atlas_rect.position.x = atlas_texture->get_region().position.x;
  310. atlas_rect.position.y = atlas_texture->get_region().position.y;
  311. texture_size.width = atlas_texture->get_region().size.x;
  312. texture_size.height = atlas_texture->get_region().size.y;
  313. } else if (image.is_valid()) {
  314. texture_size.width = texture->get_width();
  315. texture_size.height = texture->get_height();
  316. }
  317. ERR_FAIL_COND(!texture.is_valid());
  318. ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
  319. ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
  320. ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
  321. image = texture->get_data();
  322. ERR_FAIL_COND(!image.is_valid());
  323. image = image->duplicate();
  324. if (atlas_texture.is_valid())
  325. image->crop_from_point(
  326. atlas_rect.position.x,
  327. atlas_rect.position.y,
  328. texture_size.width,
  329. texture_size.height);
  330. if (image->get_format() != Image::FORMAT_RGBA8) {
  331. image->convert(Image::FORMAT_RGBA8);
  332. }
  333. png_image png_meta;
  334. memset(&png_meta, 0, sizeof png_meta);
  335. png_meta.version = PNG_IMAGE_VERSION;
  336. png_meta.width = texture_size.width;
  337. png_meta.height = texture_size.height;
  338. png_meta.format = PNG_FORMAT_RGBA;
  339. PackedByteArray png;
  340. size_t len;
  341. PackedByteArray data = image->get_data();
  342. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, data.ptr(), 0, nullptr));
  343. png.resize(len);
  344. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, png.ptrw(), &len, 0, data.ptr(), 0, nullptr));
  345. godot_js_display_cursor_set_custom_shape(godot2dom_cursor(p_shape), png.ptr(), len, p_hotspot.x, p_hotspot.y);
  346. } else {
  347. godot_js_display_cursor_set_custom_shape(godot2dom_cursor(p_shape), NULL, 0, 0, 0);
  348. }
  349. cursor_set_shape(cursor_shape);
  350. }
  351. // Mouse mode
  352. void DisplayServerJavaScript::mouse_set_mode(MouseMode p_mode) {
  353. ERR_FAIL_COND_MSG(p_mode == MOUSE_MODE_CONFINED, "MOUSE_MODE_CONFINED is not supported for the HTML5 platform.");
  354. if (p_mode == mouse_get_mode())
  355. return;
  356. if (p_mode == MOUSE_MODE_VISIBLE) {
  357. godot_js_display_cursor_set_visible(1);
  358. emscripten_exit_pointerlock();
  359. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  360. godot_js_display_cursor_set_visible(0);
  361. emscripten_exit_pointerlock();
  362. } else if (p_mode == MOUSE_MODE_CAPTURED) {
  363. godot_js_display_cursor_set_visible(1);
  364. EMSCRIPTEN_RESULT result = emscripten_request_pointerlock(canvas_id, false);
  365. ERR_FAIL_COND_MSG(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED, "MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback.");
  366. ERR_FAIL_COND_MSG(result != EMSCRIPTEN_RESULT_SUCCESS, "MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback.");
  367. }
  368. }
  369. DisplayServer::MouseMode DisplayServerJavaScript::mouse_get_mode() const {
  370. if (godot_js_display_cursor_is_hidden()) {
  371. return MOUSE_MODE_HIDDEN;
  372. }
  373. EmscriptenPointerlockChangeEvent ev;
  374. emscripten_get_pointerlock_status(&ev);
  375. return (ev.isActive && String::utf8(ev.id) == String::utf8(&canvas_id[1])) ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE;
  376. }
  377. // Wheel
  378. EM_BOOL DisplayServerJavaScript::wheel_callback(int p_event_type, const EmscriptenWheelEvent *p_event, void *p_user_data) {
  379. ERR_FAIL_COND_V(p_event_type != EMSCRIPTEN_EVENT_WHEEL, false);
  380. DisplayServerJavaScript *ds = get_singleton();
  381. if (!is_canvas_focused()) {
  382. if (ds->cursor_inside_canvas) {
  383. focus_canvas();
  384. } else {
  385. return false;
  386. }
  387. }
  388. Input *input = Input::get_singleton();
  389. Ref<InputEventMouseButton> ev;
  390. ev.instance();
  391. ev->set_position(input->get_mouse_position());
  392. ev->set_global_position(ev->get_position());
  393. ev->set_shift(input->is_key_pressed(KEY_SHIFT));
  394. ev->set_alt(input->is_key_pressed(KEY_ALT));
  395. ev->set_control(input->is_key_pressed(KEY_CONTROL));
  396. ev->set_metakey(input->is_key_pressed(KEY_META));
  397. if (p_event->deltaY < 0)
  398. ev->set_button_index(BUTTON_WHEEL_UP);
  399. else if (p_event->deltaY > 0)
  400. ev->set_button_index(BUTTON_WHEEL_DOWN);
  401. else if (p_event->deltaX > 0)
  402. ev->set_button_index(BUTTON_WHEEL_LEFT);
  403. else if (p_event->deltaX < 0)
  404. ev->set_button_index(BUTTON_WHEEL_RIGHT);
  405. else
  406. return false;
  407. // Different browsers give wildly different delta values, and we can't
  408. // interpret deltaMode, so use default value for wheel events' factor.
  409. int button_flag = 1 << (ev->get_button_index() - 1);
  410. ev->set_pressed(true);
  411. ev->set_button_mask(input->get_mouse_button_mask() | button_flag);
  412. input->parse_input_event(ev);
  413. ev->set_pressed(false);
  414. ev->set_button_mask(input->get_mouse_button_mask() & ~button_flag);
  415. input->parse_input_event(ev);
  416. return true;
  417. }
  418. // Touch
  419. EM_BOOL DisplayServerJavaScript::touch_press_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  420. DisplayServerJavaScript *display = get_singleton();
  421. Ref<InputEventScreenTouch> ev;
  422. ev.instance();
  423. int lowest_id_index = -1;
  424. for (int i = 0; i < p_event->numTouches; ++i) {
  425. const EmscriptenTouchPoint &touch = p_event->touches[i];
  426. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  427. lowest_id_index = i;
  428. if (!touch.isChanged)
  429. continue;
  430. ev->set_index(touch.identifier);
  431. ev->set_position(compute_position_in_canvas(touch.clientX, touch.clientY));
  432. display->touches[i] = ev->get_position();
  433. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_TOUCHSTART);
  434. Input::get_singleton()->parse_input_event(ev);
  435. }
  436. // Resume audio context after input in case autoplay was denied.
  437. return true;
  438. }
  439. EM_BOOL DisplayServerJavaScript::touchmove_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  440. DisplayServerJavaScript *display = get_singleton();
  441. Ref<InputEventScreenDrag> ev;
  442. ev.instance();
  443. int lowest_id_index = -1;
  444. for (int i = 0; i < p_event->numTouches; ++i) {
  445. const EmscriptenTouchPoint &touch = p_event->touches[i];
  446. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  447. lowest_id_index = i;
  448. if (!touch.isChanged)
  449. continue;
  450. ev->set_index(touch.identifier);
  451. ev->set_position(compute_position_in_canvas(touch.clientX, touch.clientY));
  452. Point2 &prev = display->touches[i];
  453. ev->set_relative(ev->get_position() - prev);
  454. prev = ev->get_position();
  455. Input::get_singleton()->parse_input_event(ev);
  456. }
  457. return true;
  458. }
  459. bool DisplayServerJavaScript::screen_is_touchscreen(int p_screen) const {
  460. return godot_js_display_touchscreen_is_available();
  461. }
  462. // Virtual Keybaord
  463. void DisplayServerJavaScript::vk_input_text_callback(const char *p_text, int p_cursor) {
  464. DisplayServerJavaScript *ds = DisplayServerJavaScript::get_singleton();
  465. if (!ds || ds->input_text_callback.is_null()) {
  466. return;
  467. }
  468. // Call input_text
  469. Variant event = String(p_text);
  470. Variant *eventp = &event;
  471. Variant ret;
  472. Callable::CallError ce;
  473. ds->input_text_callback.call((const Variant **)&eventp, 1, ret, ce);
  474. // Insert key right to reach position.
  475. Input *input = Input::get_singleton();
  476. Ref<InputEventKey> k;
  477. for (int i = 0; i < p_cursor; i++) {
  478. k.instance();
  479. k->set_pressed(true);
  480. k->set_echo(false);
  481. k->set_keycode(KEY_RIGHT);
  482. input->parse_input_event(k);
  483. k.instance();
  484. k->set_pressed(false);
  485. k->set_echo(false);
  486. k->set_keycode(KEY_RIGHT);
  487. input->parse_input_event(k);
  488. }
  489. }
  490. 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) {
  491. godot_js_display_vk_show(p_existing_text.utf8().get_data(), p_multiline, p_cursor_start, p_cursor_end);
  492. }
  493. void DisplayServerJavaScript::virtual_keyboard_hide() {
  494. godot_js_display_vk_hide();
  495. }
  496. // Gamepad
  497. void DisplayServerJavaScript::gamepad_callback(int p_index, int p_connected, const char *p_id, const char *p_guid) {
  498. Input *input = Input::get_singleton();
  499. if (p_connected) {
  500. input->joy_connection_changed(p_index, true, String::utf8(p_id), String::utf8(p_guid));
  501. } else {
  502. input->joy_connection_changed(p_index, false, "");
  503. }
  504. }
  505. void DisplayServerJavaScript::process_joypads() {
  506. Input *input = Input::get_singleton();
  507. int32_t pads = godot_js_display_gamepad_sample_count();
  508. int32_t s_btns_num = 0;
  509. int32_t s_axes_num = 0;
  510. int32_t s_standard = 0;
  511. float s_btns[16];
  512. float s_axes[10];
  513. for (int idx = 0; idx < pads; idx++) {
  514. int err = godot_js_display_gamepad_sample_get(idx, s_btns, &s_btns_num, s_axes, &s_axes_num, &s_standard);
  515. if (err) {
  516. continue;
  517. }
  518. for (int b = 0; b < s_btns_num; b++) {
  519. float value = s_btns[b];
  520. // Buttons 6 and 7 in the standard mapping need to be
  521. // axis to be handled as JOY_AXIS_TRIGGER by Godot.
  522. if (s_standard && (b == 6 || b == 7)) {
  523. Input::JoyAxis joy_axis;
  524. joy_axis.min = 0;
  525. joy_axis.value = value;
  526. int a = b == 6 ? JOY_AXIS_TRIGGER_LEFT : JOY_AXIS_TRIGGER_RIGHT;
  527. input->joy_axis(idx, a, joy_axis);
  528. } else {
  529. input->joy_button(idx, b, value);
  530. }
  531. }
  532. for (int a = 0; a < s_axes_num; a++) {
  533. Input::JoyAxis joy_axis;
  534. joy_axis.min = -1;
  535. joy_axis.value = s_axes[a];
  536. input->joy_axis(idx, a, joy_axis);
  537. }
  538. }
  539. }
  540. Vector<String> DisplayServerJavaScript::get_rendering_drivers_func() {
  541. Vector<String> drivers;
  542. drivers.push_back("dummy");
  543. return drivers;
  544. }
  545. // Clipboard
  546. void DisplayServerJavaScript::update_clipboard_callback(const char *p_text) {
  547. get_singleton()->clipboard = p_text;
  548. }
  549. void DisplayServerJavaScript::clipboard_set(const String &p_text) {
  550. clipboard = p_text;
  551. int err = godot_js_display_clipboard_set(p_text.utf8().get_data());
  552. ERR_FAIL_COND_MSG(err, "Clipboard API is not supported.");
  553. }
  554. String DisplayServerJavaScript::clipboard_get() const {
  555. godot_js_display_clipboard_get(update_clipboard_callback);
  556. return clipboard;
  557. }
  558. void DisplayServerJavaScript::send_window_event_callback(int p_notification) {
  559. DisplayServerJavaScript *ds = get_singleton();
  560. if (!ds) {
  561. return;
  562. }
  563. if (p_notification == DisplayServer::WINDOW_EVENT_MOUSE_ENTER || p_notification == DisplayServer::WINDOW_EVENT_MOUSE_EXIT) {
  564. ds->cursor_inside_canvas = p_notification == DisplayServer::WINDOW_EVENT_MOUSE_ENTER;
  565. }
  566. if (!ds->window_event_callback.is_null()) {
  567. Variant event = int(p_notification);
  568. Variant *eventp = &event;
  569. Variant ret;
  570. Callable::CallError ce;
  571. ds->window_event_callback.call((const Variant **)&eventp, 1, ret, ce);
  572. }
  573. }
  574. void DisplayServerJavaScript::alert(const String &p_alert, const String &p_title) {
  575. godot_js_display_alert(p_alert.utf8().get_data());
  576. }
  577. void DisplayServerJavaScript::set_icon(const Ref<Image> &p_icon) {
  578. ERR_FAIL_COND(p_icon.is_null());
  579. Ref<Image> icon = p_icon;
  580. if (icon->is_compressed()) {
  581. icon = icon->duplicate();
  582. ERR_FAIL_COND(icon->decompress() != OK);
  583. }
  584. if (icon->get_format() != Image::FORMAT_RGBA8) {
  585. if (icon == p_icon)
  586. icon = icon->duplicate();
  587. icon->convert(Image::FORMAT_RGBA8);
  588. }
  589. png_image png_meta;
  590. memset(&png_meta, 0, sizeof png_meta);
  591. png_meta.version = PNG_IMAGE_VERSION;
  592. png_meta.width = icon->get_width();
  593. png_meta.height = icon->get_height();
  594. png_meta.format = PNG_FORMAT_RGBA;
  595. PackedByteArray png;
  596. size_t len;
  597. PackedByteArray data = icon->get_data();
  598. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, data.ptr(), 0, nullptr));
  599. png.resize(len);
  600. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, png.ptrw(), &len, 0, data.ptr(), 0, nullptr));
  601. godot_js_display_window_icon_set(png.ptr(), len);
  602. }
  603. void DisplayServerJavaScript::_dispatch_input_event(const Ref<InputEvent> &p_event) {
  604. OS_JavaScript *os = OS_JavaScript::get_singleton();
  605. // Resume audio context after input in case autoplay was denied.
  606. os->resume_audio();
  607. Callable cb = get_singleton()->input_event_callback;
  608. if (!cb.is_null()) {
  609. Variant ev = p_event;
  610. Variant *evp = &ev;
  611. Variant ret;
  612. Callable::CallError ce;
  613. cb.call((const Variant **)&evp, 1, ret, ce);
  614. }
  615. }
  616. DisplayServer *DisplayServerJavaScript::create_func(const String &p_rendering_driver, DisplayServer::WindowMode p_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
  617. return memnew(DisplayServerJavaScript(p_rendering_driver, p_mode, p_flags, p_resolution, r_error));
  618. }
  619. DisplayServerJavaScript::DisplayServerJavaScript(const String &p_rendering_driver, WindowMode p_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
  620. r_error = OK; // Always succeeds for now.
  621. // Ensure the canvas ID.
  622. godot_js_config_canvas_id_get(canvas_id, 256);
  623. // Handle contextmenu, webglcontextlost
  624. godot_js_display_setup_canvas(p_resolution.x, p_resolution.y, p_mode == WINDOW_MODE_FULLSCREEN, OS::get_singleton()->is_hidpi_allowed() ? 1 : 0);
  625. // Check if it's windows.
  626. swap_cancel_ok = godot_js_display_is_swap_ok_cancel() == 1;
  627. // Expose method for requesting quit.
  628. godot_js_os_request_quit_cb(request_quit_callback);
  629. RasterizerDummy::make_current(); // TODO GLES2 in Godot 4.0... or webgpu?
  630. #if 0
  631. EmscriptenWebGLContextAttributes attributes;
  632. emscripten_webgl_init_context_attributes(&attributes);
  633. attributes.alpha = GLOBAL_GET("display/window/per_pixel_transparency/allowed");
  634. attributes.antialias = false;
  635. ERR_FAIL_INDEX_V(p_video_driver, VIDEO_DRIVER_MAX, ERR_INVALID_PARAMETER);
  636. if (p_desired.layered) {
  637. set_window_per_pixel_transparency_enabled(true);
  638. }
  639. bool gl_initialization_error = false;
  640. if (RasterizerGLES2::is_viable() == OK) {
  641. attributes.majorVersion = 1;
  642. RasterizerGLES2::register_config();
  643. RasterizerGLES2::make_current();
  644. } else {
  645. gl_initialization_error = true;
  646. }
  647. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(canvas_id, &attributes);
  648. if (emscripten_webgl_make_context_current(ctx) != EMSCRIPTEN_RESULT_SUCCESS) {
  649. gl_initialization_error = true;
  650. }
  651. if (gl_initialization_error) {
  652. OS::get_singleton()->alert("Your browser does not seem to support WebGL. Please update your browser version.",
  653. "Unable to initialize video driver");
  654. return ERR_UNAVAILABLE;
  655. }
  656. video_driver_index = p_video_driver;
  657. #endif
  658. EMSCRIPTEN_RESULT result;
  659. #define EM_CHECK(ev) \
  660. if (result != EMSCRIPTEN_RESULT_SUCCESS) \
  661. ERR_PRINT("Error while setting " #ev " callback: Code " + itos(result));
  662. #define SET_EM_CALLBACK(target, ev, cb) \
  663. result = emscripten_set_##ev##_callback(target, nullptr, true, &cb); \
  664. EM_CHECK(ev)
  665. #define SET_EM_WINDOW_CALLBACK(ev, cb) \
  666. result = emscripten_set_##ev##_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, false, &cb); \
  667. EM_CHECK(ev)
  668. // These callbacks from Emscripten's html5.h suffice to access most
  669. // JavaScript APIs.
  670. SET_EM_CALLBACK(canvas_id, mousedown, mouse_button_callback)
  671. SET_EM_WINDOW_CALLBACK(mousemove, mousemove_callback)
  672. SET_EM_WINDOW_CALLBACK(mouseup, mouse_button_callback)
  673. SET_EM_CALLBACK(canvas_id, wheel, wheel_callback)
  674. SET_EM_CALLBACK(canvas_id, touchstart, touch_press_callback)
  675. SET_EM_CALLBACK(canvas_id, touchmove, touchmove_callback)
  676. SET_EM_CALLBACK(canvas_id, touchend, touch_press_callback)
  677. SET_EM_CALLBACK(canvas_id, touchcancel, touch_press_callback)
  678. SET_EM_CALLBACK(canvas_id, keydown, keydown_callback)
  679. SET_EM_CALLBACK(canvas_id, keypress, keypress_callback)
  680. SET_EM_CALLBACK(canvas_id, keyup, keyup_callback)
  681. SET_EM_CALLBACK(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, fullscreenchange, fullscreen_change_callback)
  682. #undef SET_EM_CALLBACK
  683. #undef EM_CHECK
  684. // For APIs that are not (sufficiently) exposed, a
  685. // library is used below (implemented in library_godot_display.js).
  686. godot_js_display_notification_cb(&send_window_event_callback,
  687. WINDOW_EVENT_MOUSE_ENTER,
  688. WINDOW_EVENT_MOUSE_EXIT,
  689. WINDOW_EVENT_FOCUS_IN,
  690. WINDOW_EVENT_FOCUS_OUT);
  691. godot_js_display_paste_cb(update_clipboard_callback);
  692. godot_js_display_drop_files_cb(drop_files_js_callback);
  693. godot_js_display_gamepad_cb(&DisplayServerJavaScript::gamepad_callback);
  694. godot_js_display_vk_cb(&vk_input_text_callback);
  695. Input::get_singleton()->set_event_dispatch_function(_dispatch_input_event);
  696. }
  697. DisplayServerJavaScript::~DisplayServerJavaScript() {
  698. //emscripten_webgl_commit_frame();
  699. //emscripten_webgl_destroy_context(webgl_ctx);
  700. }
  701. bool DisplayServerJavaScript::has_feature(Feature p_feature) const {
  702. switch (p_feature) {
  703. //case FEATURE_CONSOLE_WINDOW:
  704. //case FEATURE_GLOBAL_MENU:
  705. //case FEATURE_HIDPI:
  706. //case FEATURE_IME:
  707. case FEATURE_ICON:
  708. case FEATURE_CLIPBOARD:
  709. case FEATURE_CURSOR_SHAPE:
  710. case FEATURE_CUSTOM_CURSOR_SHAPE:
  711. case FEATURE_MOUSE:
  712. case FEATURE_TOUCHSCREEN:
  713. return true;
  714. //case FEATURE_MOUSE_WARP:
  715. //case FEATURE_NATIVE_DIALOG:
  716. //case FEATURE_NATIVE_ICON:
  717. //case FEATURE_NATIVE_VIDEO:
  718. //case FEATURE_WINDOW_TRANSPARENCY:
  719. //case FEATURE_KEEP_SCREEN_ON:
  720. //case FEATURE_ORIENTATION:
  721. case FEATURE_VIRTUAL_KEYBOARD:
  722. return godot_js_display_vk_available() != 0;
  723. default:
  724. return false;
  725. }
  726. }
  727. void DisplayServerJavaScript::register_javascript_driver() {
  728. register_create_function("javascript", create_func, get_rendering_drivers_func);
  729. }
  730. String DisplayServerJavaScript::get_name() const {
  731. return "javascript";
  732. }
  733. int DisplayServerJavaScript::get_screen_count() const {
  734. return 1;
  735. }
  736. Point2i DisplayServerJavaScript::screen_get_position(int p_screen) const {
  737. return Point2i(); // TODO offsetX/Y?
  738. }
  739. Size2i DisplayServerJavaScript::screen_get_size(int p_screen) const {
  740. int size[2];
  741. godot_js_display_screen_size_get(size, size + 1);
  742. return Size2(size[0], size[1]);
  743. }
  744. Rect2i DisplayServerJavaScript::screen_get_usable_rect(int p_screen) const {
  745. int size[2];
  746. godot_js_display_window_size_get(size, size + 1);
  747. return Rect2i(0, 0, size[0], size[1]);
  748. }
  749. int DisplayServerJavaScript::screen_get_dpi(int p_screen) const {
  750. return godot_js_display_screen_dpi_get();
  751. }
  752. float DisplayServerJavaScript::screen_get_scale(int p_screen) const {
  753. return godot_js_display_pixel_ratio_get();
  754. }
  755. Vector<DisplayServer::WindowID> DisplayServerJavaScript::get_window_list() const {
  756. Vector<WindowID> ret;
  757. ret.push_back(MAIN_WINDOW_ID);
  758. return ret;
  759. }
  760. DisplayServerJavaScript::WindowID DisplayServerJavaScript::get_window_at_screen_position(const Point2i &p_position) const {
  761. return MAIN_WINDOW_ID;
  762. }
  763. void DisplayServerJavaScript::window_attach_instance_id(ObjectID p_instance, WindowID p_window) {
  764. window_attached_instance_id = p_instance;
  765. }
  766. ObjectID DisplayServerJavaScript::window_get_attached_instance_id(WindowID p_window) const {
  767. return window_attached_instance_id;
  768. }
  769. void DisplayServerJavaScript::window_set_rect_changed_callback(const Callable &p_callable, WindowID p_window) {
  770. // Not supported.
  771. }
  772. void DisplayServerJavaScript::window_set_window_event_callback(const Callable &p_callable, WindowID p_window) {
  773. window_event_callback = p_callable;
  774. }
  775. void DisplayServerJavaScript::window_set_input_event_callback(const Callable &p_callable, WindowID p_window) {
  776. input_event_callback = p_callable;
  777. }
  778. void DisplayServerJavaScript::window_set_input_text_callback(const Callable &p_callable, WindowID p_window) {
  779. input_text_callback = p_callable;
  780. }
  781. void DisplayServerJavaScript::window_set_drop_files_callback(const Callable &p_callable, WindowID p_window) {
  782. drop_files_callback = p_callable;
  783. }
  784. void DisplayServerJavaScript::window_set_title(const String &p_title, WindowID p_window) {
  785. godot_js_display_window_title_set(p_title.utf8().get_data());
  786. }
  787. int DisplayServerJavaScript::window_get_current_screen(WindowID p_window) const {
  788. return 1;
  789. }
  790. void DisplayServerJavaScript::window_set_current_screen(int p_screen, WindowID p_window) {
  791. // Not implemented.
  792. }
  793. Point2i DisplayServerJavaScript::window_get_position(WindowID p_window) const {
  794. return Point2i(); // TODO Does this need implementation?
  795. }
  796. void DisplayServerJavaScript::window_set_position(const Point2i &p_position, WindowID p_window) {
  797. // Not supported.
  798. }
  799. void DisplayServerJavaScript::window_set_transient(WindowID p_window, WindowID p_parent) {
  800. // Not supported.
  801. }
  802. void DisplayServerJavaScript::window_set_max_size(const Size2i p_size, WindowID p_window) {
  803. // Not supported.
  804. }
  805. Size2i DisplayServerJavaScript::window_get_max_size(WindowID p_window) const {
  806. return Size2i();
  807. }
  808. void DisplayServerJavaScript::window_set_min_size(const Size2i p_size, WindowID p_window) {
  809. // Not supported.
  810. }
  811. Size2i DisplayServerJavaScript::window_get_min_size(WindowID p_window) const {
  812. return Size2i();
  813. }
  814. void DisplayServerJavaScript::window_set_size(const Size2i p_size, WindowID p_window) {
  815. godot_js_display_desired_size_set(p_size.x, p_size.y);
  816. }
  817. Size2i DisplayServerJavaScript::window_get_size(WindowID p_window) const {
  818. int size[2];
  819. godot_js_display_window_size_get(size, size + 1);
  820. return Size2i(size[0], size[1]);
  821. }
  822. Size2i DisplayServerJavaScript::window_get_real_size(WindowID p_window) const {
  823. return window_get_size(p_window);
  824. }
  825. void DisplayServerJavaScript::window_set_mode(WindowMode p_mode, WindowID p_window) {
  826. if (window_mode == p_mode)
  827. return;
  828. switch (p_mode) {
  829. case WINDOW_MODE_WINDOWED: {
  830. if (window_mode == WINDOW_MODE_FULLSCREEN) {
  831. godot_js_display_fullscreen_exit();
  832. }
  833. window_mode = WINDOW_MODE_WINDOWED;
  834. } break;
  835. case WINDOW_MODE_FULLSCREEN: {
  836. int result = godot_js_display_fullscreen_request();
  837. ERR_FAIL_COND_MSG(result, "The request was denied. Remember that enabling fullscreen is only possible from an input callback for the HTML5 platform.");
  838. } break;
  839. case WINDOW_MODE_MAXIMIZED:
  840. case WINDOW_MODE_MINIMIZED:
  841. WARN_PRINT("WindowMode MAXIMIZED and MINIMIZED are not supported in HTML5 platform.");
  842. break;
  843. default:
  844. break;
  845. }
  846. }
  847. DisplayServerJavaScript::WindowMode DisplayServerJavaScript::window_get_mode(WindowID p_window) const {
  848. return window_mode;
  849. }
  850. bool DisplayServerJavaScript::window_is_maximize_allowed(WindowID p_window) const {
  851. return false;
  852. }
  853. void DisplayServerJavaScript::window_set_flag(WindowFlags p_flag, bool p_enabled, WindowID p_window) {
  854. // Not supported.
  855. }
  856. bool DisplayServerJavaScript::window_get_flag(WindowFlags p_flag, WindowID p_window) const {
  857. return false;
  858. }
  859. void DisplayServerJavaScript::window_request_attention(WindowID p_window) {
  860. // Not supported.
  861. }
  862. void DisplayServerJavaScript::window_move_to_foreground(WindowID p_window) {
  863. // Not supported.
  864. }
  865. bool DisplayServerJavaScript::window_can_draw(WindowID p_window) const {
  866. return true;
  867. }
  868. bool DisplayServerJavaScript::can_any_window_draw() const {
  869. return true;
  870. }
  871. void DisplayServerJavaScript::process_events() {
  872. if (godot_js_display_gamepad_sample() == OK) {
  873. process_joypads();
  874. }
  875. }
  876. int DisplayServerJavaScript::get_current_video_driver() const {
  877. return 1;
  878. }
  879. bool DisplayServerJavaScript::get_swap_cancel_ok() {
  880. return swap_cancel_ok;
  881. }
  882. void DisplayServerJavaScript::swap_buffers() {
  883. //emscripten_webgl_commit_frame();
  884. }