os_javascript.cpp 39 KB

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