os_javascript.cpp 39 KB

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