os_javascript.cpp 39 KB

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