os_javascript.cpp 39 KB

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