display_server_javascript.cpp 39 KB

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