display_server_javascript.cpp 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  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. 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.instantiate();
  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(MOUSE_BUTTON_LEFT);
  168. break;
  169. case DOM_BUTTON_MIDDLE:
  170. ev->set_button_index(MOUSE_BUTTON_MIDDLE);
  171. break;
  172. case DOM_BUTTON_RIGHT:
  173. ev->set_button_index(MOUSE_BUTTON_RIGHT);
  174. break;
  175. case DOM_BUTTON_XBUTTON1:
  176. ev->set_button_index(MOUSE_BUTTON_XBUTTON1);
  177. break;
  178. case DOM_BUTTON_XBUTTON2:
  179. ev->set_button_index(MOUSE_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_double_click(true);
  192. }
  193. } else {
  194. display->last_click_button_index = ev->get_button_index();
  195. }
  196. if (!ev->is_double_click()) {
  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. MouseButton button_flag = MouseButton(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.instantiate();
  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_image();
  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_image();
  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), nullptr, 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 || p_mode == MOUSE_MODE_CONFINED_HIDDEN, "MOUSE_MODE_CONFINED is not supported for the HTML5 platform.");
  354. if (p_mode == mouse_get_mode()) {
  355. return;
  356. }
  357. if (p_mode == MOUSE_MODE_VISIBLE) {
  358. godot_js_display_cursor_set_visible(1);
  359. emscripten_exit_pointerlock();
  360. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  361. godot_js_display_cursor_set_visible(0);
  362. emscripten_exit_pointerlock();
  363. } else if (p_mode == MOUSE_MODE_CAPTURED) {
  364. godot_js_display_cursor_set_visible(1);
  365. EMSCRIPTEN_RESULT result = emscripten_request_pointerlock(canvas_id, false);
  366. ERR_FAIL_COND_MSG(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED, "MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback.");
  367. ERR_FAIL_COND_MSG(result != EMSCRIPTEN_RESULT_SUCCESS, "MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback.");
  368. }
  369. }
  370. DisplayServer::MouseMode DisplayServerJavaScript::mouse_get_mode() const {
  371. if (godot_js_display_cursor_is_hidden()) {
  372. return MOUSE_MODE_HIDDEN;
  373. }
  374. EmscriptenPointerlockChangeEvent ev;
  375. emscripten_get_pointerlock_status(&ev);
  376. return (ev.isActive && String::utf8(ev.id) == String::utf8(&canvas_id[1])) ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE;
  377. }
  378. // Wheel
  379. EM_BOOL DisplayServerJavaScript::wheel_callback(int p_event_type, const EmscriptenWheelEvent *p_event, void *p_user_data) {
  380. ERR_FAIL_COND_V(p_event_type != EMSCRIPTEN_EVENT_WHEEL, false);
  381. DisplayServerJavaScript *ds = get_singleton();
  382. if (!is_canvas_focused()) {
  383. if (ds->cursor_inside_canvas) {
  384. focus_canvas();
  385. } else {
  386. return false;
  387. }
  388. }
  389. Input *input = Input::get_singleton();
  390. Ref<InputEventMouseButton> ev;
  391. ev.instantiate();
  392. ev->set_position(input->get_mouse_position());
  393. ev->set_global_position(ev->get_position());
  394. ev->set_shift_pressed(input->is_key_pressed(KEY_SHIFT));
  395. ev->set_alt_pressed(input->is_key_pressed(KEY_ALT));
  396. ev->set_ctrl_pressed(input->is_key_pressed(KEY_CTRL));
  397. ev->set_meta_pressed(input->is_key_pressed(KEY_META));
  398. if (p_event->deltaY < 0)
  399. ev->set_button_index(MOUSE_BUTTON_WHEEL_UP);
  400. else if (p_event->deltaY > 0)
  401. ev->set_button_index(MOUSE_BUTTON_WHEEL_DOWN);
  402. else if (p_event->deltaX > 0)
  403. ev->set_button_index(MOUSE_BUTTON_WHEEL_LEFT);
  404. else if (p_event->deltaX < 0)
  405. ev->set_button_index(MOUSE_BUTTON_WHEEL_RIGHT);
  406. else
  407. return false;
  408. // Different browsers give wildly different delta values, and we can't
  409. // interpret deltaMode, so use default value for wheel events' factor.
  410. int button_flag = 1 << (ev->get_button_index() - 1);
  411. ev->set_pressed(true);
  412. ev->set_button_mask(MouseButton(input->get_mouse_button_mask() | button_flag));
  413. input->parse_input_event(ev);
  414. ev->set_pressed(false);
  415. ev->set_button_mask(MouseButton(input->get_mouse_button_mask() & ~button_flag));
  416. input->parse_input_event(ev);
  417. return true;
  418. }
  419. // Touch
  420. EM_BOOL DisplayServerJavaScript::touch_press_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  421. DisplayServerJavaScript *display = get_singleton();
  422. Ref<InputEventScreenTouch> ev;
  423. ev.instantiate();
  424. int lowest_id_index = -1;
  425. for (int i = 0; i < p_event->numTouches; ++i) {
  426. const EmscriptenTouchPoint &touch = p_event->touches[i];
  427. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  428. lowest_id_index = i;
  429. if (!touch.isChanged)
  430. continue;
  431. ev->set_index(touch.identifier);
  432. ev->set_position(compute_position_in_canvas(touch.clientX, touch.clientY));
  433. display->touches[i] = ev->get_position();
  434. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_TOUCHSTART);
  435. Input::get_singleton()->parse_input_event(ev);
  436. }
  437. // Resume audio context after input in case autoplay was denied.
  438. return true;
  439. }
  440. EM_BOOL DisplayServerJavaScript::touchmove_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  441. DisplayServerJavaScript *display = get_singleton();
  442. Ref<InputEventScreenDrag> ev;
  443. ev.instantiate();
  444. int lowest_id_index = -1;
  445. for (int i = 0; i < p_event->numTouches; ++i) {
  446. const EmscriptenTouchPoint &touch = p_event->touches[i];
  447. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  448. lowest_id_index = i;
  449. if (!touch.isChanged)
  450. continue;
  451. ev->set_index(touch.identifier);
  452. ev->set_position(compute_position_in_canvas(touch.clientX, touch.clientY));
  453. Point2 &prev = display->touches[i];
  454. ev->set_relative(ev->get_position() - prev);
  455. prev = ev->get_position();
  456. Input::get_singleton()->parse_input_event(ev);
  457. }
  458. return true;
  459. }
  460. bool DisplayServerJavaScript::screen_is_touchscreen(int p_screen) const {
  461. return godot_js_display_touchscreen_is_available();
  462. }
  463. // Virtual Keyboard
  464. void DisplayServerJavaScript::vk_input_text_callback(const char *p_text, int p_cursor) {
  465. DisplayServerJavaScript *ds = DisplayServerJavaScript::get_singleton();
  466. if (!ds || ds->input_text_callback.is_null()) {
  467. return;
  468. }
  469. // Call input_text
  470. Variant event = String(p_text);
  471. Variant *eventp = &event;
  472. Variant ret;
  473. Callable::CallError ce;
  474. ds->input_text_callback.call((const Variant **)&eventp, 1, ret, ce);
  475. // Insert key right to reach position.
  476. Input *input = Input::get_singleton();
  477. Ref<InputEventKey> k;
  478. for (int i = 0; i < p_cursor; i++) {
  479. k.instantiate();
  480. k->set_pressed(true);
  481. k->set_echo(false);
  482. k->set_keycode(KEY_RIGHT);
  483. input->parse_input_event(k);
  484. k.instantiate();
  485. k->set_pressed(false);
  486. k->set_echo(false);
  487. k->set_keycode(KEY_RIGHT);
  488. input->parse_input_event(k);
  489. }
  490. }
  491. 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) {
  492. godot_js_display_vk_show(p_existing_text.utf8().get_data(), p_multiline, p_cursor_start, p_cursor_end);
  493. }
  494. void DisplayServerJavaScript::virtual_keyboard_hide() {
  495. godot_js_display_vk_hide();
  496. }
  497. // Gamepad
  498. void DisplayServerJavaScript::gamepad_callback(int p_index, int p_connected, const char *p_id, const char *p_guid) {
  499. Input *input = Input::get_singleton();
  500. if (p_connected) {
  501. input->joy_connection_changed(p_index, true, String::utf8(p_id), String::utf8(p_guid));
  502. } else {
  503. input->joy_connection_changed(p_index, false, "");
  504. }
  505. }
  506. void DisplayServerJavaScript::process_joypads() {
  507. Input *input = Input::get_singleton();
  508. int32_t pads = godot_js_display_gamepad_sample_count();
  509. int32_t s_btns_num = 0;
  510. int32_t s_axes_num = 0;
  511. int32_t s_standard = 0;
  512. float s_btns[16];
  513. float s_axes[10];
  514. for (int idx = 0; idx < pads; idx++) {
  515. int err = godot_js_display_gamepad_sample_get(idx, s_btns, &s_btns_num, s_axes, &s_axes_num, &s_standard);
  516. if (err) {
  517. continue;
  518. }
  519. for (int b = 0; b < s_btns_num; b++) {
  520. float value = s_btns[b];
  521. // Buttons 6 and 7 in the standard mapping need to be
  522. // axis to be handled as JOY_AXIS_TRIGGER by Godot.
  523. if (s_standard && (b == 6 || b == 7)) {
  524. Input::JoyAxisValue joy_axis;
  525. joy_axis.min = 0;
  526. joy_axis.value = value;
  527. JoyAxis a = b == 6 ? JOY_AXIS_TRIGGER_LEFT : JOY_AXIS_TRIGGER_RIGHT;
  528. input->joy_axis(idx, a, joy_axis);
  529. } else {
  530. input->joy_button(idx, (JoyButton)b, value);
  531. }
  532. }
  533. for (int a = 0; a < s_axes_num; a++) {
  534. Input::JoyAxisValue joy_axis;
  535. joy_axis.min = -1;
  536. joy_axis.value = s_axes[a];
  537. input->joy_axis(idx, (JoyAxis)a, joy_axis);
  538. }
  539. }
  540. }
  541. Vector<String> DisplayServerJavaScript::get_rendering_drivers_func() {
  542. Vector<String> drivers;
  543. drivers.push_back("dummy");
  544. return drivers;
  545. }
  546. // Clipboard
  547. void DisplayServerJavaScript::update_clipboard_callback(const char *p_text) {
  548. get_singleton()->clipboard = p_text;
  549. }
  550. void DisplayServerJavaScript::clipboard_set(const String &p_text) {
  551. clipboard = p_text;
  552. int err = godot_js_display_clipboard_set(p_text.utf8().get_data());
  553. ERR_FAIL_COND_MSG(err, "Clipboard API is not supported.");
  554. }
  555. String DisplayServerJavaScript::clipboard_get() const {
  556. godot_js_display_clipboard_get(update_clipboard_callback);
  557. return clipboard;
  558. }
  559. void DisplayServerJavaScript::send_window_event_callback(int p_notification) {
  560. DisplayServerJavaScript *ds = get_singleton();
  561. if (!ds) {
  562. return;
  563. }
  564. if (p_notification == DisplayServer::WINDOW_EVENT_MOUSE_ENTER || p_notification == DisplayServer::WINDOW_EVENT_MOUSE_EXIT) {
  565. ds->cursor_inside_canvas = p_notification == DisplayServer::WINDOW_EVENT_MOUSE_ENTER;
  566. }
  567. if (!ds->window_event_callback.is_null()) {
  568. Variant event = int(p_notification);
  569. Variant *eventp = &event;
  570. Variant ret;
  571. Callable::CallError ce;
  572. ds->window_event_callback.call((const Variant **)&eventp, 1, ret, ce);
  573. }
  574. }
  575. void DisplayServerJavaScript::set_icon(const Ref<Image> &p_icon) {
  576. ERR_FAIL_COND(p_icon.is_null());
  577. Ref<Image> icon = p_icon;
  578. if (icon->is_compressed()) {
  579. icon = icon->duplicate();
  580. ERR_FAIL_COND(icon->decompress() != OK);
  581. }
  582. if (icon->get_format() != Image::FORMAT_RGBA8) {
  583. if (icon == p_icon)
  584. icon = icon->duplicate();
  585. icon->convert(Image::FORMAT_RGBA8);
  586. }
  587. png_image png_meta;
  588. memset(&png_meta, 0, sizeof png_meta);
  589. png_meta.version = PNG_IMAGE_VERSION;
  590. png_meta.width = icon->get_width();
  591. png_meta.height = icon->get_height();
  592. png_meta.format = PNG_FORMAT_RGBA;
  593. PackedByteArray png;
  594. size_t len;
  595. PackedByteArray data = icon->get_data();
  596. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, data.ptr(), 0, nullptr));
  597. png.resize(len);
  598. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, png.ptrw(), &len, 0, data.ptr(), 0, nullptr));
  599. godot_js_display_window_icon_set(png.ptr(), len);
  600. }
  601. void DisplayServerJavaScript::_dispatch_input_event(const Ref<InputEvent> &p_event) {
  602. OS_JavaScript *os = OS_JavaScript::get_singleton();
  603. // Resume audio context after input in case autoplay was denied.
  604. os->resume_audio();
  605. Callable cb = get_singleton()->input_event_callback;
  606. if (!cb.is_null()) {
  607. Variant ev = p_event;
  608. Variant *evp = &ev;
  609. Variant ret;
  610. Callable::CallError ce;
  611. cb.call((const Variant **)&evp, 1, ret, ce);
  612. }
  613. }
  614. 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) {
  615. return memnew(DisplayServerJavaScript(p_rendering_driver, p_window_mode, p_vsync_mode, p_flags, p_resolution, r_error));
  616. }
  617. 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) {
  618. r_error = OK; // Always succeeds for now.
  619. // Ensure the canvas ID.
  620. godot_js_config_canvas_id_get(canvas_id, 256);
  621. // Handle contextmenu, webglcontextlost
  622. 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);
  623. // Check if it's windows.
  624. swap_cancel_ok = godot_js_display_is_swap_ok_cancel() == 1;
  625. // Expose method for requesting quit.
  626. godot_js_os_request_quit_cb(request_quit_callback);
  627. RasterizerDummy::make_current(); // TODO GLES2 in Godot 4.0... or webgpu?
  628. #if 0
  629. EmscriptenWebGLContextAttributes attributes;
  630. emscripten_webgl_init_context_attributes(&attributes);
  631. attributes.alpha = GLOBAL_GET("display/window/per_pixel_transparency/allowed");
  632. attributes.antialias = false;
  633. ERR_FAIL_INDEX_V(p_video_driver, VIDEO_DRIVER_MAX, ERR_INVALID_PARAMETER);
  634. if (p_desired.layered) {
  635. set_window_per_pixel_transparency_enabled(true);
  636. }
  637. bool gl_initialization_error = false;
  638. if (RasterizerGLES2::is_viable() == OK) {
  639. attributes.majorVersion = 1;
  640. RasterizerGLES2::register_config();
  641. RasterizerGLES2::make_current();
  642. } else {
  643. gl_initialization_error = true;
  644. }
  645. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(canvas_id, &attributes);
  646. if (emscripten_webgl_make_context_current(ctx) != EMSCRIPTEN_RESULT_SUCCESS) {
  647. gl_initialization_error = true;
  648. }
  649. if (gl_initialization_error) {
  650. OS::get_singleton()->alert("Your browser does not seem to support WebGL. Please update your browser version.",
  651. "Unable to initialize video driver");
  652. return ERR_UNAVAILABLE;
  653. }
  654. video_driver_index = p_video_driver;
  655. #endif
  656. EMSCRIPTEN_RESULT result;
  657. #define EM_CHECK(ev) \
  658. if (result != EMSCRIPTEN_RESULT_SUCCESS) \
  659. ERR_PRINT("Error while setting " #ev " callback: Code " + itos(result));
  660. #define SET_EM_CALLBACK(target, ev, cb) \
  661. result = emscripten_set_##ev##_callback(target, nullptr, true, &cb); \
  662. EM_CHECK(ev)
  663. #define SET_EM_WINDOW_CALLBACK(ev, cb) \
  664. result = emscripten_set_##ev##_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, nullptr, false, &cb); \
  665. EM_CHECK(ev)
  666. // These callbacks from Emscripten's html5.h suffice to access most
  667. // JavaScript APIs.
  668. SET_EM_CALLBACK(canvas_id, mousedown, mouse_button_callback)
  669. SET_EM_WINDOW_CALLBACK(mousemove, mousemove_callback)
  670. SET_EM_WINDOW_CALLBACK(mouseup, mouse_button_callback)
  671. SET_EM_CALLBACK(canvas_id, wheel, wheel_callback)
  672. SET_EM_CALLBACK(canvas_id, touchstart, touch_press_callback)
  673. SET_EM_CALLBACK(canvas_id, touchmove, touchmove_callback)
  674. SET_EM_CALLBACK(canvas_id, touchend, touch_press_callback)
  675. SET_EM_CALLBACK(canvas_id, touchcancel, touch_press_callback)
  676. SET_EM_CALLBACK(canvas_id, keydown, keydown_callback)
  677. SET_EM_CALLBACK(canvas_id, keypress, keypress_callback)
  678. SET_EM_CALLBACK(canvas_id, keyup, keyup_callback)
  679. SET_EM_CALLBACK(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, fullscreenchange, fullscreen_change_callback)
  680. #undef SET_EM_CALLBACK
  681. #undef EM_CHECK
  682. // For APIs that are not (sufficiently) exposed, a
  683. // library is used below (implemented in library_godot_display.js).
  684. godot_js_display_notification_cb(&send_window_event_callback,
  685. WINDOW_EVENT_MOUSE_ENTER,
  686. WINDOW_EVENT_MOUSE_EXIT,
  687. WINDOW_EVENT_FOCUS_IN,
  688. WINDOW_EVENT_FOCUS_OUT);
  689. godot_js_display_paste_cb(update_clipboard_callback);
  690. godot_js_display_drop_files_cb(drop_files_js_callback);
  691. godot_js_display_gamepad_cb(&DisplayServerJavaScript::gamepad_callback);
  692. godot_js_display_vk_cb(&vk_input_text_callback);
  693. Input::get_singleton()->set_event_dispatch_function(_dispatch_input_event);
  694. }
  695. DisplayServerJavaScript::~DisplayServerJavaScript() {
  696. //emscripten_webgl_commit_frame();
  697. //emscripten_webgl_destroy_context(webgl_ctx);
  698. }
  699. bool DisplayServerJavaScript::has_feature(Feature p_feature) const {
  700. switch (p_feature) {
  701. //case FEATURE_CONSOLE_WINDOW:
  702. //case FEATURE_GLOBAL_MENU:
  703. //case FEATURE_HIDPI:
  704. //case FEATURE_IME:
  705. case FEATURE_ICON:
  706. case FEATURE_CLIPBOARD:
  707. case FEATURE_CURSOR_SHAPE:
  708. case FEATURE_CUSTOM_CURSOR_SHAPE:
  709. case FEATURE_MOUSE:
  710. case FEATURE_TOUCHSCREEN:
  711. return true;
  712. //case FEATURE_MOUSE_WARP:
  713. //case FEATURE_NATIVE_DIALOG:
  714. //case FEATURE_NATIVE_ICON:
  715. //case FEATURE_WINDOW_TRANSPARENCY:
  716. //case FEATURE_KEEP_SCREEN_ON:
  717. //case FEATURE_ORIENTATION:
  718. case FEATURE_VIRTUAL_KEYBOARD:
  719. return godot_js_display_vk_available() != 0;
  720. default:
  721. return false;
  722. }
  723. }
  724. void DisplayServerJavaScript::register_javascript_driver() {
  725. register_create_function("javascript", create_func, get_rendering_drivers_func);
  726. }
  727. String DisplayServerJavaScript::get_name() const {
  728. return "javascript";
  729. }
  730. int DisplayServerJavaScript::get_screen_count() const {
  731. return 1;
  732. }
  733. Point2i DisplayServerJavaScript::screen_get_position(int p_screen) const {
  734. return Point2i(); // TODO offsetX/Y?
  735. }
  736. Size2i DisplayServerJavaScript::screen_get_size(int p_screen) const {
  737. int size[2];
  738. godot_js_display_screen_size_get(size, size + 1);
  739. return Size2(size[0], size[1]);
  740. }
  741. Rect2i DisplayServerJavaScript::screen_get_usable_rect(int p_screen) const {
  742. int size[2];
  743. godot_js_display_window_size_get(size, size + 1);
  744. return Rect2i(0, 0, size[0], size[1]);
  745. }
  746. int DisplayServerJavaScript::screen_get_dpi(int p_screen) const {
  747. return godot_js_display_screen_dpi_get();
  748. }
  749. float DisplayServerJavaScript::screen_get_scale(int p_screen) const {
  750. return godot_js_display_pixel_ratio_get();
  751. }
  752. Vector<DisplayServer::WindowID> DisplayServerJavaScript::get_window_list() const {
  753. Vector<WindowID> ret;
  754. ret.push_back(MAIN_WINDOW_ID);
  755. return ret;
  756. }
  757. DisplayServerJavaScript::WindowID DisplayServerJavaScript::get_window_at_screen_position(const Point2i &p_position) const {
  758. return MAIN_WINDOW_ID;
  759. }
  760. void DisplayServerJavaScript::window_attach_instance_id(ObjectID p_instance, WindowID p_window) {
  761. window_attached_instance_id = p_instance;
  762. }
  763. ObjectID DisplayServerJavaScript::window_get_attached_instance_id(WindowID p_window) const {
  764. return window_attached_instance_id;
  765. }
  766. void DisplayServerJavaScript::window_set_rect_changed_callback(const Callable &p_callable, WindowID p_window) {
  767. // Not supported.
  768. }
  769. void DisplayServerJavaScript::window_set_window_event_callback(const Callable &p_callable, WindowID p_window) {
  770. window_event_callback = p_callable;
  771. }
  772. void DisplayServerJavaScript::window_set_input_event_callback(const Callable &p_callable, WindowID p_window) {
  773. input_event_callback = p_callable;
  774. }
  775. void DisplayServerJavaScript::window_set_input_text_callback(const Callable &p_callable, WindowID p_window) {
  776. input_text_callback = p_callable;
  777. }
  778. void DisplayServerJavaScript::window_set_drop_files_callback(const Callable &p_callable, WindowID p_window) {
  779. drop_files_callback = p_callable;
  780. }
  781. void DisplayServerJavaScript::window_set_title(const String &p_title, WindowID p_window) {
  782. godot_js_display_window_title_set(p_title.utf8().get_data());
  783. }
  784. int DisplayServerJavaScript::window_get_current_screen(WindowID p_window) const {
  785. return 1;
  786. }
  787. void DisplayServerJavaScript::window_set_current_screen(int p_screen, WindowID p_window) {
  788. // Not implemented.
  789. }
  790. Point2i DisplayServerJavaScript::window_get_position(WindowID p_window) const {
  791. return Point2i(); // TODO Does this need implementation?
  792. }
  793. void DisplayServerJavaScript::window_set_position(const Point2i &p_position, WindowID p_window) {
  794. // Not supported.
  795. }
  796. void DisplayServerJavaScript::window_set_transient(WindowID p_window, WindowID p_parent) {
  797. // Not supported.
  798. }
  799. void DisplayServerJavaScript::window_set_max_size(const Size2i p_size, WindowID p_window) {
  800. // Not supported.
  801. }
  802. Size2i DisplayServerJavaScript::window_get_max_size(WindowID p_window) const {
  803. return Size2i();
  804. }
  805. void DisplayServerJavaScript::window_set_min_size(const Size2i p_size, WindowID p_window) {
  806. // Not supported.
  807. }
  808. Size2i DisplayServerJavaScript::window_get_min_size(WindowID p_window) const {
  809. return Size2i();
  810. }
  811. void DisplayServerJavaScript::window_set_size(const Size2i p_size, WindowID p_window) {
  812. godot_js_display_desired_size_set(p_size.x, p_size.y);
  813. }
  814. Size2i DisplayServerJavaScript::window_get_size(WindowID p_window) const {
  815. int size[2];
  816. godot_js_display_window_size_get(size, size + 1);
  817. return Size2i(size[0], size[1]);
  818. }
  819. Size2i DisplayServerJavaScript::window_get_real_size(WindowID p_window) const {
  820. return window_get_size(p_window);
  821. }
  822. void DisplayServerJavaScript::window_set_mode(WindowMode p_mode, WindowID p_window) {
  823. if (window_mode == p_mode)
  824. return;
  825. switch (p_mode) {
  826. case WINDOW_MODE_WINDOWED: {
  827. if (window_mode == WINDOW_MODE_FULLSCREEN) {
  828. godot_js_display_fullscreen_exit();
  829. }
  830. window_mode = WINDOW_MODE_WINDOWED;
  831. } break;
  832. case WINDOW_MODE_FULLSCREEN: {
  833. int result = godot_js_display_fullscreen_request();
  834. ERR_FAIL_COND_MSG(result, "The request was denied. Remember that enabling fullscreen is only possible from an input callback for the HTML5 platform.");
  835. } break;
  836. case WINDOW_MODE_MAXIMIZED:
  837. case WINDOW_MODE_MINIMIZED:
  838. WARN_PRINT("WindowMode MAXIMIZED and MINIMIZED are not supported in HTML5 platform.");
  839. break;
  840. default:
  841. break;
  842. }
  843. }
  844. DisplayServerJavaScript::WindowMode DisplayServerJavaScript::window_get_mode(WindowID p_window) const {
  845. return window_mode;
  846. }
  847. bool DisplayServerJavaScript::window_is_maximize_allowed(WindowID p_window) const {
  848. return false;
  849. }
  850. void DisplayServerJavaScript::window_set_flag(WindowFlags p_flag, bool p_enabled, WindowID p_window) {
  851. // Not supported.
  852. }
  853. bool DisplayServerJavaScript::window_get_flag(WindowFlags p_flag, WindowID p_window) const {
  854. return false;
  855. }
  856. void DisplayServerJavaScript::window_request_attention(WindowID p_window) {
  857. // Not supported.
  858. }
  859. void DisplayServerJavaScript::window_move_to_foreground(WindowID p_window) {
  860. // Not supported.
  861. }
  862. bool DisplayServerJavaScript::window_can_draw(WindowID p_window) const {
  863. return true;
  864. }
  865. bool DisplayServerJavaScript::can_any_window_draw() const {
  866. return true;
  867. }
  868. void DisplayServerJavaScript::process_events() {
  869. if (godot_js_display_gamepad_sample() == OK) {
  870. process_joypads();
  871. }
  872. }
  873. int DisplayServerJavaScript::get_current_video_driver() const {
  874. return 1;
  875. }
  876. bool DisplayServerJavaScript::get_swap_cancel_ok() {
  877. return swap_cancel_ok;
  878. }
  879. void DisplayServerJavaScript::swap_buffers() {
  880. //emscripten_webgl_commit_frame();
  881. }