os_javascript.cpp 43 KB

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