display_server_javascript.cpp 36 KB

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