os_javascript.cpp 43 KB

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