display_server_javascript.cpp 35 KB

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