os_javascript.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411
  1. /*************************************************************************/
  2. /* os_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 "os_javascript.h"
  31. #include "core/io/file_access_buffered_fa.h"
  32. #include "core/io/json.h"
  33. #include "drivers/gles2/rasterizer_gles2.h"
  34. #include "drivers/gles3/rasterizer_gles3.h"
  35. #include "drivers/unix/dir_access_unix.h"
  36. #include "drivers/unix/file_access_unix.h"
  37. #include "main/main.h"
  38. #include "servers/visual/visual_server_raster.h"
  39. #ifndef NO_THREADS
  40. #include "servers/visual/visual_server_wrap_mt.h"
  41. #endif
  42. #include <emscripten.h>
  43. #include <png.h>
  44. #include <stdlib.h>
  45. #include "dom_keys.inc"
  46. #define DOM_BUTTON_LEFT 0
  47. #define DOM_BUTTON_MIDDLE 1
  48. #define DOM_BUTTON_RIGHT 2
  49. #define DOM_BUTTON_XBUTTON1 3
  50. #define DOM_BUTTON_XBUTTON2 4
  51. // Window (canvas)
  52. static void focus_canvas() {
  53. /* clang-format off */
  54. EM_ASM({
  55. Module['canvas'].focus();
  56. });
  57. /* clang-format on */
  58. }
  59. static bool is_canvas_focused() {
  60. /* clang-format off */
  61. return EM_ASM_INT({
  62. return document.activeElement == Module['canvas'];
  63. });
  64. /* clang-format on */
  65. }
  66. static Point2 compute_position_in_canvas(int x, int y) {
  67. OS_JavaScript *os = OS_JavaScript::get_singleton();
  68. int canvas_x = EM_ASM_INT({
  69. return Module['canvas'].getBoundingClientRect().x;
  70. });
  71. int canvas_y = EM_ASM_INT({
  72. return Module['canvas'].getBoundingClientRect().y;
  73. });
  74. int canvas_width;
  75. int canvas_height;
  76. emscripten_get_canvas_element_size(os->canvas_id.utf8().get_data(), &canvas_width, &canvas_height);
  77. double element_width;
  78. double element_height;
  79. emscripten_get_element_css_size(os->canvas_id.utf8().get_data(), &element_width, &element_height);
  80. return Point2((int)(canvas_width / element_width * (x - canvas_x)),
  81. (int)(canvas_height / element_height * (y - canvas_y)));
  82. }
  83. static bool cursor_inside_canvas = true;
  84. EM_BOOL OS_JavaScript::fullscreen_change_callback(int p_event_type, const EmscriptenFullscreenChangeEvent *p_event, void *p_user_data) {
  85. OS_JavaScript *os = get_singleton();
  86. // Empty ID is canvas.
  87. String target_id = String::utf8(p_event->id);
  88. if (target_id.empty() || target_id == "canvas") {
  89. // This event property is the only reliable data on
  90. // browser fullscreen state.
  91. os->video_mode.fullscreen = p_event->isFullscreen;
  92. if (os->video_mode.fullscreen) {
  93. os->entering_fullscreen = false;
  94. } else {
  95. // Restoring maximized window now will cause issues,
  96. // so delay until main_loop_iterate.
  97. os->just_exited_fullscreen = true;
  98. }
  99. }
  100. return false;
  101. }
  102. void OS_JavaScript::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  103. video_mode = p_video_mode;
  104. }
  105. OS::VideoMode OS_JavaScript::get_video_mode(int p_screen) const {
  106. return video_mode;
  107. }
  108. Size2 OS_JavaScript::get_screen_size(int p_screen) const {
  109. EmscriptenFullscreenChangeEvent ev;
  110. EMSCRIPTEN_RESULT result = emscripten_get_fullscreen_status(&ev);
  111. ERR_FAIL_COND_V(result != EMSCRIPTEN_RESULT_SUCCESS, Size2());
  112. return Size2(ev.screenWidth, ev.screenHeight);
  113. }
  114. void OS_JavaScript::set_window_size(const Size2 p_size) {
  115. windowed_size = p_size;
  116. if (video_mode.fullscreen) {
  117. window_maximized = false;
  118. set_window_fullscreen(false);
  119. } else {
  120. if (window_maximized) {
  121. emscripten_exit_soft_fullscreen();
  122. window_maximized = false;
  123. }
  124. emscripten_set_canvas_element_size(canvas_id.utf8().get_data(), p_size.x, p_size.y);
  125. }
  126. }
  127. Size2 OS_JavaScript::get_window_size() const {
  128. int canvas[2];
  129. emscripten_get_canvas_element_size(canvas_id.utf8().get_data(), canvas, canvas + 1);
  130. return Size2(canvas[0], canvas[1]);
  131. }
  132. void OS_JavaScript::set_window_maximized(bool p_enabled) {
  133. if (video_mode.fullscreen) {
  134. window_maximized = p_enabled;
  135. set_window_fullscreen(false);
  136. } else if (!p_enabled) {
  137. emscripten_exit_soft_fullscreen();
  138. window_maximized = false;
  139. } else if (!window_maximized) {
  140. // Prevent calling emscripten_enter_soft_fullscreen mutltiple times,
  141. // this would hide page elements permanently.
  142. EmscriptenFullscreenStrategy strategy;
  143. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  144. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  145. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  146. strategy.canvasResizedCallback = NULL;
  147. emscripten_enter_soft_fullscreen(canvas_id.utf8().get_data(), &strategy);
  148. window_maximized = p_enabled;
  149. }
  150. }
  151. bool OS_JavaScript::is_window_maximized() const {
  152. return window_maximized;
  153. }
  154. void OS_JavaScript::set_window_fullscreen(bool p_enabled) {
  155. if (p_enabled == video_mode.fullscreen) {
  156. return;
  157. }
  158. // Just request changes here, if successful, logic continues in
  159. // fullscreen_change_callback.
  160. if (p_enabled) {
  161. if (window_maximized) {
  162. // Soft fullsreen during real fullscreen can cause issues, so exit.
  163. // This must be called before requesting full screen.
  164. emscripten_exit_soft_fullscreen();
  165. }
  166. EmscriptenFullscreenStrategy strategy;
  167. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  168. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  169. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  170. strategy.canvasResizedCallback = NULL;
  171. EMSCRIPTEN_RESULT result = emscripten_request_fullscreen_strategy(canvas_id.utf8().get_data(), false, &strategy);
  172. ERR_FAIL_COND_MSG(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED, "Enabling fullscreen is only possible from an input callback for the HTML5 platform.");
  173. ERR_FAIL_COND_MSG(result != EMSCRIPTEN_RESULT_SUCCESS, "Enabling fullscreen is only possible from an input callback for the HTML5 platform.");
  174. // Not fullscreen yet, so prevent "windowed" canvas dimensions from
  175. // being overwritten.
  176. entering_fullscreen = true;
  177. } else {
  178. // No logic allowed here, since exiting w/ ESC key won't use this function.
  179. ERR_FAIL_COND(emscripten_exit_fullscreen() != EMSCRIPTEN_RESULT_SUCCESS);
  180. }
  181. }
  182. bool OS_JavaScript::is_window_fullscreen() const {
  183. return video_mode.fullscreen;
  184. }
  185. void OS_JavaScript::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  186. Size2 screen = get_screen_size();
  187. p_list->push_back(OS::VideoMode(screen.width, screen.height, true));
  188. }
  189. bool OS_JavaScript::get_window_per_pixel_transparency_enabled() const {
  190. if (!is_layered_allowed()) {
  191. return false;
  192. }
  193. return transparency_enabled;
  194. }
  195. void OS_JavaScript::set_window_per_pixel_transparency_enabled(bool p_enabled) {
  196. if (!is_layered_allowed()) {
  197. return;
  198. }
  199. transparency_enabled = p_enabled;
  200. }
  201. // Keys
  202. template <typename T>
  203. static void dom2godot_mod(T *emscripten_event_ptr, Ref<InputEventWithModifiers> godot_event) {
  204. godot_event->set_shift(emscripten_event_ptr->shiftKey);
  205. godot_event->set_alt(emscripten_event_ptr->altKey);
  206. godot_event->set_control(emscripten_event_ptr->ctrlKey);
  207. godot_event->set_metakey(emscripten_event_ptr->metaKey);
  208. }
  209. static Ref<InputEventKey> setup_key_event(const EmscriptenKeyboardEvent *emscripten_event) {
  210. Ref<InputEventKey> ev;
  211. ev.instance();
  212. ev->set_echo(emscripten_event->repeat);
  213. dom2godot_mod(emscripten_event, ev);
  214. ev->set_scancode(dom_code2godot_scancode(emscripten_event->code, emscripten_event->key));
  215. String unicode = String::utf8(emscripten_event->key);
  216. // Check if empty or multi-character (e.g. `CapsLock`).
  217. if (unicode.length() != 1) {
  218. // Might be empty as well, but better than nonsense.
  219. unicode = String::utf8(emscripten_event->charValue);
  220. }
  221. if (unicode.length() == 1) {
  222. ev->set_unicode(unicode[0]);
  223. }
  224. return ev;
  225. }
  226. EM_BOOL OS_JavaScript::keydown_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  227. OS_JavaScript *os = get_singleton();
  228. Ref<InputEventKey> ev = setup_key_event(p_event);
  229. ev->set_pressed(true);
  230. if (ev->get_unicode() == 0 && keycode_has_unicode(ev->get_scancode())) {
  231. // Defer to keypress event for legacy unicode retrieval.
  232. os->deferred_key_event = ev;
  233. // Do not suppress keypress event.
  234. return false;
  235. }
  236. os->input->parse_input_event(ev);
  237. // Resume audio context after input in case autoplay was denied.
  238. os->audio_driver_javascript.resume();
  239. return true;
  240. }
  241. EM_BOOL OS_JavaScript::keypress_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  242. OS_JavaScript *os = get_singleton();
  243. os->deferred_key_event->set_unicode(p_event->charCode);
  244. os->input->parse_input_event(os->deferred_key_event);
  245. return true;
  246. }
  247. EM_BOOL OS_JavaScript::keyup_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  248. Ref<InputEventKey> ev = setup_key_event(p_event);
  249. ev->set_pressed(false);
  250. get_singleton()->input->parse_input_event(ev);
  251. return ev->get_scancode() != KEY_UNKNOWN && ev->get_scancode() != 0;
  252. }
  253. // Mouse
  254. Point2 OS_JavaScript::get_mouse_position() const {
  255. return input->get_mouse_position();
  256. }
  257. int OS_JavaScript::get_mouse_button_state() const {
  258. return input->get_mouse_button_mask();
  259. }
  260. EM_BOOL OS_JavaScript::mouse_button_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) {
  261. OS_JavaScript *os = get_singleton();
  262. Ref<InputEventMouseButton> ev;
  263. ev.instance();
  264. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_MOUSEDOWN);
  265. ev->set_position(compute_position_in_canvas(p_event->clientX, p_event->clientY));
  266. ev->set_global_position(ev->get_position());
  267. dom2godot_mod(p_event, ev);
  268. switch (p_event->button) {
  269. case DOM_BUTTON_LEFT: ev->set_button_index(BUTTON_LEFT); break;
  270. case DOM_BUTTON_MIDDLE: ev->set_button_index(BUTTON_MIDDLE); break;
  271. case DOM_BUTTON_RIGHT: ev->set_button_index(BUTTON_RIGHT); break;
  272. case DOM_BUTTON_XBUTTON1: ev->set_button_index(BUTTON_XBUTTON1); break;
  273. case DOM_BUTTON_XBUTTON2: ev->set_button_index(BUTTON_XBUTTON2); break;
  274. default: return false;
  275. }
  276. if (ev->is_pressed()) {
  277. double diff = emscripten_get_now() - os->last_click_ms;
  278. if (ev->get_button_index() == os->last_click_button_index) {
  279. if (diff < 400 && Point2(os->last_click_pos).distance_to(ev->get_position()) < 5) {
  280. os->last_click_ms = 0;
  281. os->last_click_pos = Point2(-100, -100);
  282. os->last_click_button_index = -1;
  283. ev->set_doubleclick(true);
  284. }
  285. } else {
  286. os->last_click_button_index = ev->get_button_index();
  287. }
  288. if (!ev->is_doubleclick()) {
  289. os->last_click_ms += diff;
  290. os->last_click_pos = ev->get_position();
  291. }
  292. }
  293. int mask = os->input->get_mouse_button_mask();
  294. int button_flag = 1 << (ev->get_button_index() - 1);
  295. if (ev->is_pressed()) {
  296. // Since the event is consumed, focus manually. The containing iframe,
  297. // if exists, may not have focus yet, so focus even if already focused.
  298. focus_canvas();
  299. mask |= button_flag;
  300. } else if (mask & button_flag) {
  301. mask &= ~button_flag;
  302. } else {
  303. // Received release event, but press was outside the canvas, so ignore.
  304. return false;
  305. }
  306. ev->set_button_mask(mask);
  307. os->input->parse_input_event(ev);
  308. // Resume audio context after input in case autoplay was denied.
  309. os->audio_driver_javascript.resume();
  310. // Prevent multi-click text selection and wheel-click scrolling anchor.
  311. // Context menu is prevented through contextmenu event.
  312. return true;
  313. }
  314. EM_BOOL OS_JavaScript::mousemove_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) {
  315. OS_JavaScript *os = get_singleton();
  316. int input_mask = os->input->get_mouse_button_mask();
  317. Point2 pos = compute_position_in_canvas(p_event->clientX, p_event->clientY);
  318. // For motion outside the canvas, only read mouse movement if dragging
  319. // started inside the canvas; imitating desktop app behaviour.
  320. if (!cursor_inside_canvas && !input_mask)
  321. return false;
  322. Ref<InputEventMouseMotion> ev;
  323. ev.instance();
  324. dom2godot_mod(p_event, ev);
  325. ev->set_button_mask(input_mask);
  326. ev->set_position(pos);
  327. ev->set_global_position(ev->get_position());
  328. ev->set_relative(Vector2(p_event->movementX, p_event->movementY));
  329. os->input->set_mouse_position(ev->get_position());
  330. ev->set_speed(os->input->get_last_mouse_speed());
  331. os->input->parse_input_event(ev);
  332. // Don't suppress mouseover/-leave events.
  333. return false;
  334. }
  335. static const char *godot2dom_cursor(OS::CursorShape p_shape) {
  336. switch (p_shape) {
  337. case OS::CURSOR_ARROW:
  338. default:
  339. return "auto";
  340. case OS::CURSOR_IBEAM: return "text";
  341. case OS::CURSOR_POINTING_HAND: return "pointer";
  342. case OS::CURSOR_CROSS: return "crosshair";
  343. case OS::CURSOR_WAIT: return "progress";
  344. case OS::CURSOR_BUSY: return "wait";
  345. case OS::CURSOR_DRAG: return "grab";
  346. case OS::CURSOR_CAN_DROP: return "grabbing";
  347. case OS::CURSOR_FORBIDDEN: return "no-drop";
  348. case OS::CURSOR_VSIZE: return "ns-resize";
  349. case OS::CURSOR_HSIZE: return "ew-resize";
  350. case OS::CURSOR_BDIAGSIZE: return "nesw-resize";
  351. case OS::CURSOR_FDIAGSIZE: return "nwse-resize";
  352. case OS::CURSOR_MOVE: return "move";
  353. case OS::CURSOR_VSPLIT: return "row-resize";
  354. case OS::CURSOR_HSPLIT: return "col-resize";
  355. case OS::CURSOR_HELP: return "help";
  356. }
  357. }
  358. static void set_css_cursor(const char *p_cursor) {
  359. /* clang-format off */
  360. EM_ASM({
  361. Module['canvas'].style.cursor = UTF8ToString($0);
  362. }, p_cursor);
  363. /* clang-format on */
  364. }
  365. static bool is_css_cursor_hidden() {
  366. /* clang-format off */
  367. return EM_ASM_INT({
  368. return Module['canvas'].style.cursor === 'none';
  369. });
  370. /* clang-format on */
  371. }
  372. void OS_JavaScript::set_cursor_shape(CursorShape p_shape) {
  373. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  374. if (get_mouse_mode() == MOUSE_MODE_VISIBLE) {
  375. if (cursors[p_shape] != "") {
  376. Vector<String> url = cursors[p_shape].split("?");
  377. set_css_cursor(("url(\"" + url[0] + "\") " + url[1] + ", auto").utf8());
  378. } else {
  379. set_css_cursor(godot2dom_cursor(p_shape));
  380. }
  381. }
  382. cursor_shape = p_shape;
  383. }
  384. void OS_JavaScript::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  385. if (p_cursor.is_valid()) {
  386. Map<CursorShape, Vector<Variant> >::Element *cursor_c = cursors_cache.find(p_shape);
  387. if (cursor_c) {
  388. if (cursor_c->get()[0] == p_cursor && cursor_c->get()[1] == p_hotspot) {
  389. set_cursor_shape(p_shape);
  390. return;
  391. }
  392. cursors_cache.erase(p_shape);
  393. }
  394. Ref<Texture> texture = p_cursor;
  395. Ref<AtlasTexture> atlas_texture = p_cursor;
  396. Ref<Image> image;
  397. Size2 texture_size;
  398. Rect2 atlas_rect;
  399. if (texture.is_valid()) {
  400. image = texture->get_data();
  401. if (image.is_valid()) {
  402. image->duplicate();
  403. }
  404. }
  405. if (!image.is_valid() && atlas_texture.is_valid()) {
  406. texture = atlas_texture->get_atlas();
  407. atlas_rect.size.width = texture->get_width();
  408. atlas_rect.size.height = texture->get_height();
  409. atlas_rect.position.x = atlas_texture->get_region().position.x;
  410. atlas_rect.position.y = atlas_texture->get_region().position.y;
  411. texture_size.width = atlas_texture->get_region().size.x;
  412. texture_size.height = atlas_texture->get_region().size.y;
  413. } else if (image.is_valid()) {
  414. texture_size.width = texture->get_width();
  415. texture_size.height = texture->get_height();
  416. }
  417. ERR_FAIL_COND(!texture.is_valid());
  418. ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
  419. ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
  420. ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
  421. image = texture->get_data();
  422. ERR_FAIL_COND(!image.is_valid());
  423. image = image->duplicate();
  424. if (atlas_texture.is_valid())
  425. image->crop_from_point(
  426. atlas_rect.position.x,
  427. atlas_rect.position.y,
  428. texture_size.width,
  429. texture_size.height);
  430. if (image->get_format() != Image::FORMAT_RGBA8) {
  431. image->convert(Image::FORMAT_RGBA8);
  432. }
  433. png_image png_meta;
  434. memset(&png_meta, 0, sizeof png_meta);
  435. png_meta.version = PNG_IMAGE_VERSION;
  436. png_meta.width = texture_size.width;
  437. png_meta.height = texture_size.height;
  438. png_meta.format = PNG_FORMAT_RGBA;
  439. PoolByteArray png;
  440. size_t len;
  441. PoolByteArray::Read r = image->get_data().read();
  442. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, r.ptr(), 0, NULL));
  443. png.resize(len);
  444. PoolByteArray::Write w = png.write();
  445. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, w.ptr(), &len, 0, r.ptr(), 0, NULL));
  446. w = PoolByteArray::Write();
  447. r = png.read();
  448. char *object_url;
  449. /* clang-format off */
  450. EM_ASM({
  451. var PNG_PTR = $0;
  452. var PNG_LEN = $1;
  453. var PTR = $2;
  454. var png = new Blob([HEAPU8.slice(PNG_PTR, PNG_PTR + PNG_LEN)], { type: 'image/png' });
  455. var url = URL.createObjectURL(png);
  456. var length_bytes = lengthBytesUTF8(url) + 1;
  457. var string_on_wasm_heap = _malloc(length_bytes);
  458. setValue(PTR, string_on_wasm_heap, '*');
  459. stringToUTF8(url, string_on_wasm_heap, length_bytes);
  460. }, r.ptr(), len, &object_url);
  461. /* clang-format on */
  462. r = PoolByteArray::Read();
  463. String url = String::utf8(object_url) + "?" + itos(p_hotspot.x) + " " + itos(p_hotspot.y);
  464. /* clang-format off */
  465. EM_ASM({ _free($0); }, object_url);
  466. /* clang-format on */
  467. if (cursors[p_shape] != "") {
  468. /* clang-format off */
  469. EM_ASM({
  470. URL.revokeObjectURL(UTF8ToString($0).split('?')[0]);
  471. }, cursors[p_shape].utf8().get_data());
  472. /* clang-format on */
  473. cursors[p_shape] = "";
  474. }
  475. cursors[p_shape] = url;
  476. Vector<Variant> params;
  477. params.push_back(p_cursor);
  478. params.push_back(p_hotspot);
  479. cursors_cache.insert(p_shape, params);
  480. } else if (cursors[p_shape] != "") {
  481. /* clang-format off */
  482. EM_ASM({
  483. URL.revokeObjectURL(UTF8ToString($0).split('?')[0]);
  484. }, cursors[p_shape].utf8().get_data());
  485. /* clang-format on */
  486. cursors[p_shape] = "";
  487. cursors_cache.erase(p_shape);
  488. }
  489. set_cursor_shape(cursor_shape);
  490. }
  491. void OS_JavaScript::set_mouse_mode(OS::MouseMode p_mode) {
  492. ERR_FAIL_COND_MSG(p_mode == MOUSE_MODE_CONFINED, "MOUSE_MODE_CONFINED is not supported for the HTML5 platform.");
  493. if (p_mode == get_mouse_mode())
  494. return;
  495. if (p_mode == MOUSE_MODE_VISIBLE) {
  496. // set_css_cursor must be called before set_cursor_shape to make the cursor visible
  497. set_css_cursor(godot2dom_cursor(cursor_shape));
  498. set_cursor_shape(cursor_shape);
  499. emscripten_exit_pointerlock();
  500. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  501. set_css_cursor("none");
  502. emscripten_exit_pointerlock();
  503. } else if (p_mode == MOUSE_MODE_CAPTURED) {
  504. EMSCRIPTEN_RESULT result = emscripten_request_pointerlock("canvas", false);
  505. ERR_FAIL_COND_MSG(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED, "MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback.");
  506. ERR_FAIL_COND_MSG(result != EMSCRIPTEN_RESULT_SUCCESS, "MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback.");
  507. // set_css_cursor must be called before set_cursor_shape to make the cursor visible
  508. set_css_cursor(godot2dom_cursor(cursor_shape));
  509. set_cursor_shape(cursor_shape);
  510. }
  511. }
  512. OS::MouseMode OS_JavaScript::get_mouse_mode() const {
  513. if (is_css_cursor_hidden())
  514. return MOUSE_MODE_HIDDEN;
  515. EmscriptenPointerlockChangeEvent ev;
  516. emscripten_get_pointerlock_status(&ev);
  517. return (ev.isActive && String::utf8(ev.id) == "canvas") ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE;
  518. }
  519. // Wheel
  520. EM_BOOL OS_JavaScript::wheel_callback(int p_event_type, const EmscriptenWheelEvent *p_event, void *p_user_data) {
  521. ERR_FAIL_COND_V(p_event_type != EMSCRIPTEN_EVENT_WHEEL, false);
  522. if (!is_canvas_focused()) {
  523. if (cursor_inside_canvas) {
  524. focus_canvas();
  525. } else {
  526. return false;
  527. }
  528. }
  529. InputDefault *input = get_singleton()->input;
  530. Ref<InputEventMouseButton> ev;
  531. ev.instance();
  532. ev->set_position(input->get_mouse_position());
  533. ev->set_global_position(ev->get_position());
  534. ev->set_shift(input->is_key_pressed(KEY_SHIFT));
  535. ev->set_alt(input->is_key_pressed(KEY_ALT));
  536. ev->set_control(input->is_key_pressed(KEY_CONTROL));
  537. ev->set_metakey(input->is_key_pressed(KEY_META));
  538. if (p_event->deltaY < 0)
  539. ev->set_button_index(BUTTON_WHEEL_UP);
  540. else if (p_event->deltaY > 0)
  541. ev->set_button_index(BUTTON_WHEEL_DOWN);
  542. else if (p_event->deltaX > 0)
  543. ev->set_button_index(BUTTON_WHEEL_LEFT);
  544. else if (p_event->deltaX < 0)
  545. ev->set_button_index(BUTTON_WHEEL_RIGHT);
  546. else
  547. return false;
  548. // Different browsers give wildly different delta values, and we can't
  549. // interpret deltaMode, so use default value for wheel events' factor.
  550. int button_flag = 1 << (ev->get_button_index() - 1);
  551. ev->set_pressed(true);
  552. ev->set_button_mask(input->get_mouse_button_mask() | button_flag);
  553. input->parse_input_event(ev);
  554. ev->set_pressed(false);
  555. ev->set_button_mask(input->get_mouse_button_mask() & ~button_flag);
  556. input->parse_input_event(ev);
  557. return true;
  558. }
  559. // Touch
  560. bool OS_JavaScript::has_touchscreen_ui_hint() const {
  561. /* clang-format off */
  562. return EM_ASM_INT({
  563. return 'ontouchstart' in window;
  564. });
  565. /* clang-format on */
  566. }
  567. EM_BOOL OS_JavaScript::touch_press_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  568. OS_JavaScript *os = get_singleton();
  569. Ref<InputEventScreenTouch> ev;
  570. ev.instance();
  571. int lowest_id_index = -1;
  572. for (int i = 0; i < p_event->numTouches; ++i) {
  573. const EmscriptenTouchPoint &touch = p_event->touches[i];
  574. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  575. lowest_id_index = i;
  576. if (!touch.isChanged)
  577. continue;
  578. ev->set_index(touch.identifier);
  579. ev->set_position(compute_position_in_canvas(touch.clientX, touch.clientY));
  580. os->touches[i] = ev->get_position();
  581. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_TOUCHSTART);
  582. os->input->parse_input_event(ev);
  583. }
  584. // Resume audio context after input in case autoplay was denied.
  585. os->audio_driver_javascript.resume();
  586. return true;
  587. }
  588. EM_BOOL OS_JavaScript::touchmove_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  589. OS_JavaScript *os = get_singleton();
  590. Ref<InputEventScreenDrag> ev;
  591. ev.instance();
  592. int lowest_id_index = -1;
  593. for (int i = 0; i < p_event->numTouches; ++i) {
  594. const EmscriptenTouchPoint &touch = p_event->touches[i];
  595. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  596. lowest_id_index = i;
  597. if (!touch.isChanged)
  598. continue;
  599. ev->set_index(touch.identifier);
  600. ev->set_position(compute_position_in_canvas(touch.clientX, touch.clientY));
  601. Point2 &prev = os->touches[i];
  602. ev->set_relative(ev->get_position() - prev);
  603. prev = ev->get_position();
  604. os->input->parse_input_event(ev);
  605. }
  606. return true;
  607. }
  608. // Gamepad
  609. EM_BOOL OS_JavaScript::gamepad_change_callback(int p_event_type, const EmscriptenGamepadEvent *p_event, void *p_user_data) {
  610. InputDefault *input = get_singleton()->input;
  611. if (p_event_type == EMSCRIPTEN_EVENT_GAMEPADCONNECTED) {
  612. String guid = "";
  613. if (String::utf8(p_event->mapping) == "standard")
  614. guid = "Default HTML5 Gamepad";
  615. input->joy_connection_changed(p_event->index, true, String::utf8(p_event->id), guid);
  616. } else {
  617. input->joy_connection_changed(p_event->index, false, "");
  618. }
  619. return true;
  620. }
  621. void OS_JavaScript::process_joypads() {
  622. int joypad_count = emscripten_get_num_gamepads();
  623. for (int joypad = 0; joypad < joypad_count; joypad++) {
  624. EmscriptenGamepadEvent state;
  625. EMSCRIPTEN_RESULT query_result = emscripten_get_gamepad_status(joypad, &state);
  626. // Chromium reserves gamepads slots, so NO_DATA is an expected result.
  627. ERR_CONTINUE(query_result != EMSCRIPTEN_RESULT_SUCCESS &&
  628. query_result != EMSCRIPTEN_RESULT_NO_DATA);
  629. if (query_result == EMSCRIPTEN_RESULT_SUCCESS && state.connected) {
  630. int button_count = MIN(state.numButtons, 18);
  631. int axis_count = MIN(state.numAxes, 8);
  632. for (int button = 0; button < button_count; button++) {
  633. float value = state.analogButton[button];
  634. if (String::utf8(state.mapping) == "standard" && (button == JOY_ANALOG_L2 || button == JOY_ANALOG_R2)) {
  635. InputDefault::JoyAxis joy_axis;
  636. joy_axis.min = 0;
  637. joy_axis.value = value;
  638. input->joy_axis(joypad, button, joy_axis);
  639. } else {
  640. input->joy_button(joypad, button, value);
  641. }
  642. }
  643. for (int axis = 0; axis < axis_count; axis++) {
  644. InputDefault::JoyAxis joy_axis;
  645. joy_axis.min = -1;
  646. joy_axis.value = state.axis[axis];
  647. input->joy_axis(joypad, axis, joy_axis);
  648. }
  649. }
  650. }
  651. }
  652. bool OS_JavaScript::is_joy_known(int p_device) {
  653. return input->is_joy_mapped(p_device);
  654. }
  655. String OS_JavaScript::get_joy_guid(int p_device) const {
  656. return input->get_joy_guid_remapped(p_device);
  657. }
  658. // Video
  659. int OS_JavaScript::get_video_driver_count() const {
  660. return VIDEO_DRIVER_MAX;
  661. }
  662. const char *OS_JavaScript::get_video_driver_name(int p_driver) const {
  663. switch (p_driver) {
  664. case VIDEO_DRIVER_GLES3:
  665. return "GLES3";
  666. case VIDEO_DRIVER_GLES2:
  667. return "GLES2";
  668. }
  669. ERR_FAIL_V_MSG(NULL, "Invalid video driver index: " + itos(p_driver) + ".");
  670. }
  671. // Audio
  672. int OS_JavaScript::get_audio_driver_count() const {
  673. return 1;
  674. }
  675. const char *OS_JavaScript::get_audio_driver_name(int p_driver) const {
  676. return "JavaScript";
  677. }
  678. // Clipboard
  679. extern "C" EMSCRIPTEN_KEEPALIVE void update_clipboard(const char *p_text) {
  680. // Only call set_clipboard from OS (sets local clipboard)
  681. OS::get_singleton()->OS::set_clipboard(p_text);
  682. }
  683. void OS_JavaScript::set_clipboard(const String &p_text) {
  684. OS::set_clipboard(p_text);
  685. /* clang-format off */
  686. int err = EM_ASM_INT({
  687. var text = UTF8ToString($0);
  688. if (!navigator.clipboard || !navigator.clipboard.writeText)
  689. return 1;
  690. navigator.clipboard.writeText(text).catch(function(e) {
  691. // Setting OS clipboard is only possible from an input callback.
  692. console.error("Setting OS clipboard is only possible from an input callback for the HTML5 plafrom. Exception:", e);
  693. });
  694. return 0;
  695. }, p_text.utf8().get_data());
  696. /* clang-format on */
  697. ERR_FAIL_COND_MSG(err, "Clipboard API is not supported.");
  698. }
  699. String OS_JavaScript::get_clipboard() const {
  700. /* clang-format off */
  701. EM_ASM({
  702. try {
  703. navigator.clipboard.readText().then(function (result) {
  704. ccall('update_clipboard', 'void', ['string'], [result]);
  705. }).catch(function (e) {
  706. // Fail graciously.
  707. });
  708. } catch (e) {
  709. // Fail graciously.
  710. }
  711. });
  712. /* clang-format on */
  713. return this->OS::get_clipboard();
  714. }
  715. // Lifecycle
  716. int OS_JavaScript::get_current_video_driver() const {
  717. return video_driver_index;
  718. }
  719. void OS_JavaScript::initialize_core() {
  720. OS_Unix::initialize_core();
  721. FileAccess::make_default<FileAccessBufferedFA<FileAccessUnix> >(FileAccess::ACCESS_RESOURCES);
  722. }
  723. Error OS_JavaScript::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  724. EmscriptenWebGLContextAttributes attributes;
  725. emscripten_webgl_init_context_attributes(&attributes);
  726. attributes.alpha = GLOBAL_GET("display/window/per_pixel_transparency/allowed");
  727. attributes.antialias = false;
  728. attributes.explicitSwapControl = true;
  729. ERR_FAIL_INDEX_V(p_video_driver, VIDEO_DRIVER_MAX, ERR_INVALID_PARAMETER);
  730. if (p_desired.layered) {
  731. set_window_per_pixel_transparency_enabled(true);
  732. }
  733. bool gles3 = true;
  734. if (p_video_driver == VIDEO_DRIVER_GLES2) {
  735. gles3 = false;
  736. }
  737. bool gl_initialization_error = false;
  738. while (true) {
  739. if (gles3) {
  740. if (RasterizerGLES3::is_viable() == OK) {
  741. attributes.majorVersion = 2;
  742. RasterizerGLES3::register_config();
  743. RasterizerGLES3::make_current();
  744. break;
  745. } else {
  746. if (GLOBAL_GET("rendering/quality/driver/fallback_to_gles2")) {
  747. p_video_driver = VIDEO_DRIVER_GLES2;
  748. gles3 = false;
  749. continue;
  750. } else {
  751. gl_initialization_error = true;
  752. break;
  753. }
  754. }
  755. } else {
  756. if (RasterizerGLES2::is_viable() == OK) {
  757. attributes.majorVersion = 1;
  758. RasterizerGLES2::register_config();
  759. RasterizerGLES2::make_current();
  760. break;
  761. } else {
  762. gl_initialization_error = true;
  763. break;
  764. }
  765. }
  766. }
  767. webgl_ctx = emscripten_webgl_create_context(canvas_id.utf8().get_data(), &attributes);
  768. if (emscripten_webgl_make_context_current(webgl_ctx) != EMSCRIPTEN_RESULT_SUCCESS) {
  769. gl_initialization_error = true;
  770. }
  771. if (gl_initialization_error) {
  772. OS::get_singleton()->alert("Your browser does not support any of the supported WebGL versions.\n"
  773. "Please update your browser version.",
  774. "Unable to initialize Video driver");
  775. return ERR_UNAVAILABLE;
  776. }
  777. video_driver_index = p_video_driver;
  778. video_mode = p_desired;
  779. // fullscreen_change_callback will correct this if the request is successful.
  780. video_mode.fullscreen = false;
  781. // Emscripten only attempts fullscreen requests if the user input callback
  782. // was registered through one its own functions, so request manually for
  783. // start-up fullscreen.
  784. if (p_desired.fullscreen) {
  785. /* clang-format off */
  786. EM_ASM({
  787. const canvas = Module['canvas'];
  788. (canvas.requestFullscreen || canvas.msRequestFullscreen ||
  789. canvas.mozRequestFullScreen || canvas.mozRequestFullscreen ||
  790. canvas.webkitRequestFullscreen
  791. ).call(canvas);
  792. });
  793. /* clang-format on */
  794. }
  795. /* clang-format off */
  796. if (EM_ASM_INT({ return Module['resizeCanvasOnStart'] })) {
  797. /* clang-format on */
  798. set_window_size(Size2(video_mode.width, video_mode.height));
  799. } else {
  800. set_window_size(get_window_size());
  801. }
  802. AudioDriverManager::initialize(p_audio_driver);
  803. visual_server = memnew(VisualServerRaster());
  804. #ifndef NO_THREADS
  805. visual_server = memnew(VisualServerWrapMT(visual_server, false));
  806. #endif
  807. input = memnew(InputDefault);
  808. EMSCRIPTEN_RESULT result;
  809. CharString id = canvas_id.utf8().get_data();
  810. #define EM_CHECK(ev) \
  811. if (result != EMSCRIPTEN_RESULT_SUCCESS) \
  812. ERR_PRINTS("Error while setting " #ev " callback: Code " + itos(result))
  813. #define SET_EM_CALLBACK(target, ev, cb) \
  814. result = emscripten_set_##ev##_callback(target, NULL, true, &cb); \
  815. EM_CHECK(ev)
  816. #define SET_EM_CALLBACK_NOTARGET(ev, cb) \
  817. result = emscripten_set_##ev##_callback(NULL, true, &cb); \
  818. EM_CHECK(ev)
  819. // These callbacks from Emscripten's html5.h suffice to access most
  820. // JavaScript APIs. For APIs that are not (sufficiently) exposed, EM_ASM
  821. // is used below.
  822. SET_EM_CALLBACK(EMSCRIPTEN_EVENT_TARGET_WINDOW, mousemove, mousemove_callback)
  823. SET_EM_CALLBACK(id.get_data(), mousedown, mouse_button_callback)
  824. SET_EM_CALLBACK(EMSCRIPTEN_EVENT_TARGET_WINDOW, mouseup, mouse_button_callback)
  825. SET_EM_CALLBACK(id.get_data(), wheel, wheel_callback)
  826. SET_EM_CALLBACK(id.get_data(), touchstart, touch_press_callback)
  827. SET_EM_CALLBACK(id.get_data(), touchmove, touchmove_callback)
  828. SET_EM_CALLBACK(id.get_data(), touchend, touch_press_callback)
  829. SET_EM_CALLBACK(id.get_data(), touchcancel, touch_press_callback)
  830. SET_EM_CALLBACK(id.get_data(), keydown, keydown_callback)
  831. SET_EM_CALLBACK(id.get_data(), keypress, keypress_callback)
  832. SET_EM_CALLBACK(id.get_data(), keyup, keyup_callback)
  833. SET_EM_CALLBACK(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, fullscreenchange, fullscreen_change_callback)
  834. SET_EM_CALLBACK_NOTARGET(gamepadconnected, gamepad_change_callback)
  835. SET_EM_CALLBACK_NOTARGET(gamepaddisconnected, gamepad_change_callback)
  836. #undef SET_EM_CALLBACK_NOTARGET
  837. #undef SET_EM_CALLBACK
  838. #undef EM_CHECK
  839. /* clang-format off */
  840. EM_ASM({
  841. Module.listeners = {};
  842. const canvas = Module['canvas'];
  843. const send_notification = cwrap('send_notification', null, ['number']);
  844. const notifications = arguments;
  845. (['mouseover', 'mouseleave', 'focus', 'blur']).forEach(function(event, index) {
  846. Module.listeners[event] = send_notification.bind(null, notifications[index]);
  847. canvas.addEventListener(event, Module.listeners[event]);
  848. });
  849. // Clipboard
  850. const update_clipboard = cwrap('update_clipboard', null, ['string']);
  851. Module.listeners['paste'] = function(evt) {
  852. update_clipboard(evt.clipboardData.getData('text'));
  853. };
  854. window.addEventListener('paste', Module.listeners['paste'], true);
  855. Module.listeners['dragover'] = function(ev) {
  856. // Prevent default behavior (which would try to open the file(s))
  857. ev.preventDefault();
  858. };
  859. // Drag an drop
  860. Module.listeners['drop'] = Module.drop_handler; // Defined in native/utils.js
  861. canvas.addEventListener('dragover', Module.listeners['dragover'], false);
  862. canvas.addEventListener('drop', Module.listeners['drop'], false);
  863. // Quit request
  864. Module['request_quit'] = function() {
  865. send_notification(notifications[notifications.length - 1]);
  866. };
  867. },
  868. MainLoop::NOTIFICATION_WM_MOUSE_ENTER,
  869. MainLoop::NOTIFICATION_WM_MOUSE_EXIT,
  870. MainLoop::NOTIFICATION_WM_FOCUS_IN,
  871. MainLoop::NOTIFICATION_WM_FOCUS_OUT,
  872. MainLoop::NOTIFICATION_WM_QUIT_REQUEST
  873. );
  874. /* clang-format on */
  875. visual_server->init();
  876. return OK;
  877. }
  878. void OS_JavaScript::swap_buffers() {
  879. emscripten_webgl_commit_frame();
  880. }
  881. void OS_JavaScript::set_main_loop(MainLoop *p_main_loop) {
  882. main_loop = p_main_loop;
  883. input->set_main_loop(p_main_loop);
  884. }
  885. MainLoop *OS_JavaScript::get_main_loop() const {
  886. return main_loop;
  887. }
  888. bool OS_JavaScript::main_loop_iterate() {
  889. if (is_userfs_persistent() && sync_wait_time >= 0) {
  890. int64_t current_time = get_ticks_msec();
  891. int64_t elapsed_time = current_time - last_sync_check_time;
  892. last_sync_check_time = current_time;
  893. sync_wait_time -= elapsed_time;
  894. if (sync_wait_time < 0) {
  895. /* clang-format off */
  896. EM_ASM(
  897. FS.syncfs(function(error) {
  898. if (error) { err('Failed to save IDB file system: ' + error.message); }
  899. });
  900. );
  901. /* clang-format on */
  902. }
  903. }
  904. if (emscripten_sample_gamepad_data() == EMSCRIPTEN_RESULT_SUCCESS)
  905. process_joypads();
  906. if (just_exited_fullscreen) {
  907. if (window_maximized) {
  908. EmscriptenFullscreenStrategy strategy;
  909. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  910. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  911. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  912. strategy.canvasResizedCallback = NULL;
  913. emscripten_enter_soft_fullscreen(canvas_id.utf8().get_data(), &strategy);
  914. } else {
  915. emscripten_set_canvas_element_size(canvas_id.utf8().get_data(), windowed_size.width, windowed_size.height);
  916. }
  917. emscripten_set_canvas_element_size(canvas_id.utf8().get_data(), windowed_size.width, windowed_size.height);
  918. just_exited_fullscreen = false;
  919. }
  920. int canvas[2];
  921. emscripten_get_canvas_element_size(canvas_id.utf8().get_data(), canvas, canvas + 1);
  922. video_mode.width = canvas[0];
  923. video_mode.height = canvas[1];
  924. if (!window_maximized && !video_mode.fullscreen && !just_exited_fullscreen && !entering_fullscreen) {
  925. windowed_size.width = canvas[0];
  926. windowed_size.height = canvas[1];
  927. }
  928. return Main::iteration();
  929. }
  930. void OS_JavaScript::delete_main_loop() {
  931. memdelete(main_loop);
  932. }
  933. void OS_JavaScript::finalize_async() {
  934. EM_ASM({
  935. Object.entries(Module.listeners).forEach(function(kv) {
  936. if (kv[0] == 'paste') {
  937. window.removeEventListener(kv[0], kv[1], true);
  938. } else {
  939. Module['canvas'].removeEventListener(kv[0], kv[1]);
  940. }
  941. });
  942. Module.listeners = {};
  943. });
  944. audio_driver_javascript.finish_async();
  945. }
  946. void OS_JavaScript::finalize() {
  947. memdelete(input);
  948. visual_server->finish();
  949. emscripten_webgl_commit_frame();
  950. memdelete(visual_server);
  951. emscripten_webgl_destroy_context(webgl_ctx);
  952. }
  953. // Miscellaneous
  954. Error OS_JavaScript::execute(const String &p_path, const List<String> &p_arguments, bool p_blocking, ProcessID *r_child_id, String *r_pipe, int *r_exitcode, bool read_stderr, Mutex *p_pipe_mutex) {
  955. Array args;
  956. for (const List<String>::Element *E = p_arguments.front(); E; E = E->next()) {
  957. args.push_back(E->get());
  958. }
  959. String json_args = JSON::print(args);
  960. /* clang-format off */
  961. int failed = EM_ASM_INT({
  962. const json_args = UTF8ToString($0);
  963. const args = JSON.parse(json_args);
  964. if (Module["onExecute"]) {
  965. Module["onExecute"](args);
  966. return 0;
  967. }
  968. return 1;
  969. }, json_args.utf8().get_data());
  970. /* clang-format on */
  971. ERR_FAIL_COND_V_MSG(failed, ERR_UNAVAILABLE, "OS::execute() must be implemented in Javascript via 'engine.setOnExecute' if required.");
  972. return OK;
  973. }
  974. Error OS_JavaScript::kill(const ProcessID &p_pid) {
  975. ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "OS::kill() is not available on the HTML5 platform.");
  976. }
  977. int OS_JavaScript::get_process_id() const {
  978. ERR_FAIL_V_MSG(0, "OS::get_process_id() is not available on the HTML5 platform.");
  979. }
  980. extern "C" EMSCRIPTEN_KEEPALIVE void send_notification(int p_notification) {
  981. if (p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER || p_notification == MainLoop::NOTIFICATION_WM_MOUSE_EXIT) {
  982. cursor_inside_canvas = p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER;
  983. }
  984. MainLoop *loop = OS_JavaScript::get_singleton()->get_main_loop();
  985. if (loop)
  986. loop->notification(p_notification);
  987. }
  988. bool OS_JavaScript::_check_internal_feature_support(const String &p_feature) {
  989. if (p_feature == "HTML5" || p_feature == "web")
  990. return true;
  991. #ifdef JAVASCRIPT_EVAL_ENABLED
  992. if (p_feature == "JavaScript")
  993. return true;
  994. #endif
  995. return false;
  996. }
  997. void OS_JavaScript::alert(const String &p_alert, const String &p_title) {
  998. /* clang-format off */
  999. EM_ASM({
  1000. window.alert(UTF8ToString($0));
  1001. }, p_alert.utf8().get_data());
  1002. /* clang-format on */
  1003. }
  1004. void OS_JavaScript::set_window_title(const String &p_title) {
  1005. /* clang-format off */
  1006. EM_ASM({
  1007. document.title = UTF8ToString($0);
  1008. }, p_title.utf8().get_data());
  1009. /* clang-format on */
  1010. }
  1011. void OS_JavaScript::set_icon(const Ref<Image> &p_icon) {
  1012. ERR_FAIL_COND(p_icon.is_null());
  1013. Ref<Image> icon = p_icon;
  1014. if (icon->is_compressed()) {
  1015. icon = icon->duplicate();
  1016. ERR_FAIL_COND(icon->decompress() != OK);
  1017. }
  1018. if (icon->get_format() != Image::FORMAT_RGBA8) {
  1019. if (icon == p_icon)
  1020. icon = icon->duplicate();
  1021. icon->convert(Image::FORMAT_RGBA8);
  1022. }
  1023. png_image png_meta;
  1024. memset(&png_meta, 0, sizeof png_meta);
  1025. png_meta.version = PNG_IMAGE_VERSION;
  1026. png_meta.width = icon->get_width();
  1027. png_meta.height = icon->get_height();
  1028. png_meta.format = PNG_FORMAT_RGBA;
  1029. PoolByteArray png;
  1030. size_t len;
  1031. PoolByteArray::Read r = icon->get_data().read();
  1032. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, r.ptr(), 0, NULL));
  1033. png.resize(len);
  1034. PoolByteArray::Write w = png.write();
  1035. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, w.ptr(), &len, 0, r.ptr(), 0, NULL));
  1036. w = PoolByteArray::Write();
  1037. r = png.read();
  1038. /* clang-format off */
  1039. EM_ASM({
  1040. var PNG_PTR = $0;
  1041. var PNG_LEN = $1;
  1042. var png = new Blob([HEAPU8.slice(PNG_PTR, PNG_PTR + PNG_LEN)], { type: "image/png" });
  1043. var url = URL.createObjectURL(png);
  1044. var link = document.getElementById('-gd-engine-icon');
  1045. if (link === null) {
  1046. link = document.createElement('link');
  1047. link.rel = 'icon';
  1048. link.id = '-gd-engine-icon';
  1049. document.head.appendChild(link);
  1050. }
  1051. link.href = url;
  1052. }, r.ptr(), len);
  1053. /* clang-format on */
  1054. }
  1055. String OS_JavaScript::get_executable_path() const {
  1056. return OS::get_executable_path();
  1057. }
  1058. Error OS_JavaScript::shell_open(String p_uri) {
  1059. // Open URI in a new tab, browser will deal with it by protocol.
  1060. /* clang-format off */
  1061. EM_ASM({
  1062. window.open(UTF8ToString($0), '_blank');
  1063. }, p_uri.utf8().get_data());
  1064. /* clang-format on */
  1065. return OK;
  1066. }
  1067. String OS_JavaScript::get_name() const {
  1068. return "HTML5";
  1069. }
  1070. bool OS_JavaScript::can_draw() const {
  1071. return true; // Always?
  1072. }
  1073. String OS_JavaScript::get_user_data_dir() const {
  1074. return "/userfs";
  1075. };
  1076. String OS_JavaScript::get_cache_path() const {
  1077. return "/home/web_user/.cache";
  1078. }
  1079. String OS_JavaScript::get_config_path() const {
  1080. return "/home/web_user/.config";
  1081. }
  1082. String OS_JavaScript::get_data_path() const {
  1083. return "/home/web_user/.local/share";
  1084. }
  1085. OS::PowerState OS_JavaScript::get_power_state() {
  1086. WARN_PRINT_ONCE("Power management is not supported for the HTML5 platform, defaulting to POWERSTATE_UNKNOWN");
  1087. return OS::POWERSTATE_UNKNOWN;
  1088. }
  1089. int OS_JavaScript::get_power_seconds_left() {
  1090. WARN_PRINT_ONCE("Power management is not supported for the HTML5 platform, defaulting to -1");
  1091. return -1;
  1092. }
  1093. int OS_JavaScript::get_power_percent_left() {
  1094. WARN_PRINT_ONCE("Power management is not supported for the HTML5 platform, defaulting to -1");
  1095. return -1;
  1096. }
  1097. void OS_JavaScript::file_access_close_callback(const String &p_file, int p_flags) {
  1098. OS_JavaScript *os = get_singleton();
  1099. if (os->is_userfs_persistent() && p_file.begins_with("/userfs") && p_flags & FileAccess::WRITE) {
  1100. os->last_sync_check_time = OS::get_singleton()->get_ticks_msec();
  1101. // Wait five seconds in case more files are about to be closed.
  1102. os->sync_wait_time = 5000;
  1103. }
  1104. }
  1105. void OS_JavaScript::set_idb_available(bool p_idb_available) {
  1106. idb_available = p_idb_available;
  1107. }
  1108. bool OS_JavaScript::is_userfs_persistent() const {
  1109. return idb_available;
  1110. }
  1111. OS_JavaScript *OS_JavaScript::get_singleton() {
  1112. return static_cast<OS_JavaScript *>(OS::get_singleton());
  1113. }
  1114. OS_JavaScript::OS_JavaScript(int p_argc, char *p_argv[]) {
  1115. List<String> arguments;
  1116. for (int i = 1; i < p_argc; i++) {
  1117. arguments.push_back(String::utf8(p_argv[i]));
  1118. }
  1119. set_cmdline(p_argv[0], arguments);
  1120. last_click_button_index = -1;
  1121. last_click_ms = 0;
  1122. last_click_pos = Point2(-100, -100);
  1123. window_maximized = false;
  1124. entering_fullscreen = false;
  1125. just_exited_fullscreen = false;
  1126. transparency_enabled = false;
  1127. main_loop = NULL;
  1128. visual_server = NULL;
  1129. idb_available = false;
  1130. sync_wait_time = -1;
  1131. AudioDriverManager::add_driver(&audio_driver_javascript);
  1132. Vector<Logger *> loggers;
  1133. loggers.push_back(memnew(StdLogger));
  1134. _set_logger(memnew(CompositeLogger(loggers)));
  1135. FileAccessUnix::close_notification_func = file_access_close_callback;
  1136. }