display_server_javascript.cpp 37 KB

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