os_javascript.cpp 37 KB

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