os_javascript.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  1. /*************************************************************************/
  2. /* os_javascript.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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/json.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. #ifndef NO_THREADS
  39. #include "servers/visual/visual_server_wrap_mt.h"
  40. #endif
  41. #include <dlfcn.h>
  42. #include <emscripten.h>
  43. #include <png.h>
  44. #include <stdlib.h>
  45. #include "dom_keys.inc"
  46. #include "godot_js.h"
  47. #define DOM_BUTTON_LEFT 0
  48. #define DOM_BUTTON_MIDDLE 1
  49. #define DOM_BUTTON_RIGHT 2
  50. #define DOM_BUTTON_XBUTTON1 3
  51. #define DOM_BUTTON_XBUTTON2 4
  52. // Quit
  53. void OS_JavaScript::request_quit_callback() {
  54. OS_JavaScript *os = get_singleton();
  55. if (os && os->get_main_loop()) {
  56. os->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
  57. }
  58. }
  59. // Files drop (implemented in JS for now).
  60. void OS_JavaScript::drop_files_callback(char **p_filev, int p_filec) {
  61. OS_JavaScript *os = get_singleton();
  62. if (!os || !os->get_main_loop()) {
  63. return;
  64. }
  65. Vector<String> files;
  66. for (int i = 0; i < p_filec; i++) {
  67. files.push_back(String::utf8(p_filev[i]));
  68. }
  69. os->get_main_loop()->drop_files(files);
  70. }
  71. void OS_JavaScript::send_notification_callback(int p_notification) {
  72. OS_JavaScript *os = get_singleton();
  73. if (!os) {
  74. return;
  75. }
  76. if (p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER || p_notification == MainLoop::NOTIFICATION_WM_MOUSE_EXIT) {
  77. os->cursor_inside_canvas = p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER;
  78. }
  79. MainLoop *loop = os->get_main_loop();
  80. if (loop) {
  81. loop->notification(p_notification);
  82. }
  83. }
  84. // Window (canvas)
  85. Point2 OS_JavaScript::compute_position_in_canvas(int p_x, int p_y) {
  86. int point[2];
  87. godot_js_display_compute_position(p_x, p_y, point, point + 1);
  88. return Point2(point[0], point[1]);
  89. }
  90. bool OS_JavaScript::check_size_force_redraw() {
  91. return godot_js_display_size_update() != 0;
  92. }
  93. EM_BOOL OS_JavaScript::fullscreen_change_callback(int p_event_type, const EmscriptenFullscreenChangeEvent *p_event, void *p_user_data) {
  94. OS_JavaScript *os = get_singleton();
  95. // Empty ID is canvas.
  96. String target_id = String::utf8(p_event->id);
  97. if (target_id.empty() || target_id == String::utf8(&(os->canvas_id[1]))) {
  98. // This event property is the only reliable data on
  99. // browser fullscreen state.
  100. os->video_mode.fullscreen = p_event->isFullscreen;
  101. if (os->video_mode.fullscreen) {
  102. os->entering_fullscreen = false;
  103. } else {
  104. // Restoring maximized window now will cause issues,
  105. // so delay until main_loop_iterate.
  106. os->just_exited_fullscreen = true;
  107. }
  108. }
  109. return false;
  110. }
  111. EM_BOOL OS_JavaScript::blur_callback(int p_event_type, const EmscriptenFocusEvent *p_event, void *p_user_data) {
  112. get_singleton()->input->release_pressed_events();
  113. return false;
  114. }
  115. void OS_JavaScript::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  116. video_mode = p_video_mode;
  117. }
  118. OS::VideoMode OS_JavaScript::get_video_mode(int p_screen) const {
  119. return video_mode;
  120. }
  121. Size2 OS_JavaScript::get_screen_size(int p_screen) const {
  122. int size[2];
  123. godot_js_display_screen_size_get(size, size + 1);
  124. return Size2(size[0], size[1]);
  125. }
  126. void OS_JavaScript::set_window_size(const Size2 p_size) {
  127. if (video_mode.fullscreen) {
  128. window_maximized = false;
  129. set_window_fullscreen(false);
  130. } else {
  131. if (window_maximized) {
  132. emscripten_exit_soft_fullscreen();
  133. window_maximized = false;
  134. }
  135. godot_js_display_desired_size_set(p_size.x, p_size.y);
  136. }
  137. }
  138. Size2 OS_JavaScript::get_window_size() const {
  139. int size[2];
  140. godot_js_display_window_size_get(size, size + 1);
  141. return Size2(size[0], size[1]);
  142. }
  143. void OS_JavaScript::set_window_maximized(bool p_enabled) {
  144. #ifndef TOOLS_ENABLED
  145. if (video_mode.fullscreen) {
  146. window_maximized = p_enabled;
  147. set_window_fullscreen(false);
  148. } else if (!p_enabled) {
  149. emscripten_exit_soft_fullscreen();
  150. window_maximized = false;
  151. } else if (!window_maximized) {
  152. // Prevent calling emscripten_enter_soft_fullscreen mutltiple times,
  153. // this would hide page elements permanently.
  154. EmscriptenFullscreenStrategy strategy;
  155. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  156. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  157. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  158. strategy.canvasResizedCallback = NULL;
  159. emscripten_enter_soft_fullscreen(canvas_id, &strategy);
  160. window_maximized = p_enabled;
  161. }
  162. #endif
  163. }
  164. bool OS_JavaScript::is_window_maximized() const {
  165. return window_maximized;
  166. }
  167. void OS_JavaScript::set_window_fullscreen(bool p_enabled) {
  168. if (p_enabled == video_mode.fullscreen) {
  169. return;
  170. }
  171. // Just request changes here, if successful, logic continues in
  172. // fullscreen_change_callback.
  173. if (p_enabled) {
  174. if (window_maximized) {
  175. // Soft fullsreen during real fullscreen can cause issues, so exit.
  176. // This must be called before requesting full screen.
  177. emscripten_exit_soft_fullscreen();
  178. }
  179. int result = godot_js_display_fullscreen_request();
  180. ERR_FAIL_COND_MSG(result, "The request was denied. Remember that enabling fullscreen is only possible from an input callback for the HTML5 platform.");
  181. entering_fullscreen = true;
  182. } else {
  183. // No logic allowed here, since exiting w/ ESC key won't use this function.
  184. ERR_FAIL_COND(godot_js_display_fullscreen_exit());
  185. }
  186. }
  187. bool OS_JavaScript::is_window_fullscreen() const {
  188. return video_mode.fullscreen;
  189. }
  190. void OS_JavaScript::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  191. Size2 screen = get_screen_size();
  192. p_list->push_back(OS::VideoMode(screen.width, screen.height, true));
  193. }
  194. bool OS_JavaScript::get_window_per_pixel_transparency_enabled() const {
  195. if (!is_layered_allowed()) {
  196. return false;
  197. }
  198. return transparency_enabled;
  199. }
  200. void OS_JavaScript::set_window_per_pixel_transparency_enabled(bool p_enabled) {
  201. if (!is_layered_allowed()) {
  202. return;
  203. }
  204. transparency_enabled = p_enabled;
  205. }
  206. // Keys
  207. template <typename T>
  208. static void dom2godot_mod(T *emscripten_event_ptr, Ref<InputEventWithModifiers> godot_event) {
  209. godot_event->set_shift(emscripten_event_ptr->shiftKey);
  210. godot_event->set_alt(emscripten_event_ptr->altKey);
  211. godot_event->set_control(emscripten_event_ptr->ctrlKey);
  212. godot_event->set_metakey(emscripten_event_ptr->metaKey);
  213. }
  214. static Ref<InputEventKey> setup_key_event(const EmscriptenKeyboardEvent *emscripten_event) {
  215. Ref<InputEventKey> ev;
  216. ev.instance();
  217. ev->set_echo(emscripten_event->repeat);
  218. dom2godot_mod(emscripten_event, ev);
  219. ev->set_scancode(dom_code2godot_scancode(emscripten_event->code, emscripten_event->key, false));
  220. ev->set_physical_scancode(dom_code2godot_scancode(emscripten_event->code, emscripten_event->key, true));
  221. String unicode = String::utf8(emscripten_event->key);
  222. // Check if empty or multi-character (e.g. `CapsLock`).
  223. if (unicode.length() != 1) {
  224. // Might be empty as well, but better than nonsense.
  225. unicode = String::utf8(emscripten_event->charValue);
  226. }
  227. if (unicode.length() == 1) {
  228. ev->set_unicode(unicode[0]);
  229. }
  230. return ev;
  231. }
  232. EM_BOOL OS_JavaScript::keydown_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  233. OS_JavaScript *os = get_singleton();
  234. Ref<InputEventKey> ev = setup_key_event(p_event);
  235. ev->set_pressed(true);
  236. if (ev->get_unicode() == 0 && keycode_has_unicode(ev->get_scancode())) {
  237. // Defer to keypress event for legacy unicode retrieval.
  238. os->deferred_key_event = ev;
  239. // Do not suppress keypress event.
  240. return false;
  241. }
  242. os->input->parse_input_event(ev);
  243. // Make sure to flush all events so we can call restricted APIs inside the event.
  244. os->input->flush_buffered_events();
  245. // Resume audio context after input in case autoplay was denied.
  246. os->resume_audio();
  247. return true;
  248. }
  249. EM_BOOL OS_JavaScript::keypress_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  250. OS_JavaScript *os = get_singleton();
  251. os->deferred_key_event->set_unicode(p_event->charCode);
  252. os->input->parse_input_event(os->deferred_key_event);
  253. // Make sure to flush all events so we can call restricted APIs inside the event.
  254. os->input->flush_buffered_events();
  255. return true;
  256. }
  257. EM_BOOL OS_JavaScript::keyup_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  258. OS_JavaScript *os = get_singleton();
  259. Ref<InputEventKey> ev = setup_key_event(p_event);
  260. ev->set_pressed(false);
  261. os->input->parse_input_event(ev);
  262. // Make sure to flush all events so we can call restricted APIs inside the event.
  263. os->input->flush_buffered_events();
  264. return ev->get_scancode() != KEY_UNKNOWN && ev->get_scancode() != 0;
  265. }
  266. // Mouse
  267. Point2 OS_JavaScript::get_mouse_position() const {
  268. return input->get_mouse_position();
  269. }
  270. int OS_JavaScript::get_mouse_button_state() const {
  271. return input->get_mouse_button_mask();
  272. }
  273. EM_BOOL OS_JavaScript::mouse_button_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) {
  274. OS_JavaScript *os = get_singleton();
  275. Ref<InputEventMouseButton> ev;
  276. ev.instance();
  277. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_MOUSEDOWN);
  278. ev->set_position(compute_position_in_canvas(p_event->clientX, p_event->clientY));
  279. ev->set_global_position(ev->get_position());
  280. dom2godot_mod(p_event, ev);
  281. switch (p_event->button) {
  282. case DOM_BUTTON_LEFT:
  283. ev->set_button_index(BUTTON_LEFT);
  284. break;
  285. case DOM_BUTTON_MIDDLE:
  286. ev->set_button_index(BUTTON_MIDDLE);
  287. break;
  288. case DOM_BUTTON_RIGHT:
  289. ev->set_button_index(BUTTON_RIGHT);
  290. break;
  291. case DOM_BUTTON_XBUTTON1:
  292. ev->set_button_index(BUTTON_XBUTTON1);
  293. break;
  294. case DOM_BUTTON_XBUTTON2:
  295. ev->set_button_index(BUTTON_XBUTTON2);
  296. break;
  297. default:
  298. return false;
  299. }
  300. if (ev->is_pressed()) {
  301. double diff = emscripten_get_now() - os->last_click_ms;
  302. if (ev->get_button_index() == os->last_click_button_index) {
  303. if (diff < 400 && Point2(os->last_click_pos).distance_to(ev->get_position()) < 5) {
  304. os->last_click_ms = 0;
  305. os->last_click_pos = Point2(-100, -100);
  306. os->last_click_button_index = -1;
  307. ev->set_doubleclick(true);
  308. }
  309. } else {
  310. os->last_click_button_index = ev->get_button_index();
  311. }
  312. if (!ev->is_doubleclick()) {
  313. os->last_click_ms += diff;
  314. os->last_click_pos = ev->get_position();
  315. }
  316. }
  317. int mask = os->input->get_mouse_button_mask();
  318. int button_flag = 1 << (ev->get_button_index() - 1);
  319. if (ev->is_pressed()) {
  320. // Since the event is consumed, focus manually. The containing iframe,
  321. // if exists, may not have focus yet, so focus even if already focused.
  322. godot_js_display_canvas_focus();
  323. mask |= button_flag;
  324. } else if (mask & button_flag) {
  325. mask &= ~button_flag;
  326. } else {
  327. // Received release event, but press was outside the canvas, so ignore.
  328. return false;
  329. }
  330. ev->set_button_mask(mask);
  331. os->input->parse_input_event(ev);
  332. // Make sure to flush all events so we can call restricted APIs inside the event.
  333. os->input->flush_buffered_events();
  334. // Resume audio context after input in case autoplay was denied.
  335. os->resume_audio();
  336. // Prevent multi-click text selection and wheel-click scrolling anchor.
  337. // Context menu is prevented through contextmenu event.
  338. return true;
  339. }
  340. EM_BOOL OS_JavaScript::mousemove_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) {
  341. OS_JavaScript *os = get_singleton();
  342. int input_mask = os->input->get_mouse_button_mask();
  343. Point2 pos = compute_position_in_canvas(p_event->clientX, p_event->clientY);
  344. // For motion outside the canvas, only read mouse movement if dragging
  345. // started inside the canvas; imitating desktop app behaviour.
  346. if (!os->cursor_inside_canvas && !input_mask)
  347. return false;
  348. Ref<InputEventMouseMotion> ev;
  349. ev.instance();
  350. dom2godot_mod(p_event, ev);
  351. ev->set_button_mask(input_mask);
  352. ev->set_position(pos);
  353. ev->set_global_position(ev->get_position());
  354. ev->set_relative(Vector2(p_event->movementX, p_event->movementY));
  355. os->input->set_mouse_position(ev->get_position());
  356. ev->set_speed(os->input->get_last_mouse_speed());
  357. os->input->parse_input_event(ev);
  358. // Don't suppress mouseover/-leave events.
  359. return false;
  360. }
  361. static const char *godot2dom_cursor(OS::CursorShape p_shape) {
  362. switch (p_shape) {
  363. case OS::CURSOR_ARROW:
  364. default:
  365. return "auto";
  366. case OS::CURSOR_IBEAM:
  367. return "text";
  368. case OS::CURSOR_POINTING_HAND:
  369. return "pointer";
  370. case OS::CURSOR_CROSS:
  371. return "crosshair";
  372. case OS::CURSOR_WAIT:
  373. return "progress";
  374. case OS::CURSOR_BUSY:
  375. return "wait";
  376. case OS::CURSOR_DRAG:
  377. return "grab";
  378. case OS::CURSOR_CAN_DROP:
  379. return "grabbing";
  380. case OS::CURSOR_FORBIDDEN:
  381. return "no-drop";
  382. case OS::CURSOR_VSIZE:
  383. return "ns-resize";
  384. case OS::CURSOR_HSIZE:
  385. return "ew-resize";
  386. case OS::CURSOR_BDIAGSIZE:
  387. return "nesw-resize";
  388. case OS::CURSOR_FDIAGSIZE:
  389. return "nwse-resize";
  390. case OS::CURSOR_MOVE:
  391. return "move";
  392. case OS::CURSOR_VSPLIT:
  393. return "row-resize";
  394. case OS::CURSOR_HSPLIT:
  395. return "col-resize";
  396. case OS::CURSOR_HELP:
  397. return "help";
  398. }
  399. }
  400. void OS_JavaScript::set_cursor_shape(CursorShape p_shape) {
  401. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  402. if (cursor_shape == p_shape) {
  403. return;
  404. }
  405. cursor_shape = p_shape;
  406. godot_js_display_cursor_set_shape(godot2dom_cursor(cursor_shape));
  407. }
  408. void OS_JavaScript::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  409. if (p_cursor.is_valid()) {
  410. Ref<Texture> texture = p_cursor;
  411. Ref<AtlasTexture> atlas_texture = p_cursor;
  412. Ref<Image> image;
  413. Size2 texture_size;
  414. Rect2 atlas_rect;
  415. if (texture.is_valid()) {
  416. image = texture->get_data();
  417. if (image.is_valid()) {
  418. image->duplicate();
  419. }
  420. }
  421. if (!image.is_valid() && atlas_texture.is_valid()) {
  422. texture = atlas_texture->get_atlas();
  423. atlas_rect.size.width = texture->get_width();
  424. atlas_rect.size.height = texture->get_height();
  425. atlas_rect.position.x = atlas_texture->get_region().position.x;
  426. atlas_rect.position.y = atlas_texture->get_region().position.y;
  427. texture_size.width = atlas_texture->get_region().size.x;
  428. texture_size.height = atlas_texture->get_region().size.y;
  429. } else if (image.is_valid()) {
  430. texture_size.width = texture->get_width();
  431. texture_size.height = texture->get_height();
  432. }
  433. ERR_FAIL_COND(!texture.is_valid());
  434. ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
  435. ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
  436. ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
  437. image = texture->get_data();
  438. ERR_FAIL_COND(!image.is_valid());
  439. image = image->duplicate();
  440. if (atlas_texture.is_valid())
  441. image->crop_from_point(
  442. atlas_rect.position.x,
  443. atlas_rect.position.y,
  444. texture_size.width,
  445. texture_size.height);
  446. if (image->get_format() != Image::FORMAT_RGBA8) {
  447. image->convert(Image::FORMAT_RGBA8);
  448. }
  449. png_image png_meta;
  450. memset(&png_meta, 0, sizeof png_meta);
  451. png_meta.version = PNG_IMAGE_VERSION;
  452. png_meta.width = texture_size.width;
  453. png_meta.height = texture_size.height;
  454. png_meta.format = PNG_FORMAT_RGBA;
  455. PoolByteArray png;
  456. size_t len;
  457. PoolByteArray::Read r = image->get_data().read();
  458. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, r.ptr(), 0, NULL));
  459. png.resize(len);
  460. PoolByteArray::Write w = png.write();
  461. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, w.ptr(), &len, 0, r.ptr(), 0, NULL));
  462. w = PoolByteArray::Write();
  463. r = png.read();
  464. godot_js_display_cursor_set_custom_shape(godot2dom_cursor(p_shape), r.ptr(), len, p_hotspot.x, p_hotspot.y);
  465. r = PoolByteArray::Read();
  466. } else {
  467. godot_js_display_cursor_set_custom_shape(godot2dom_cursor(p_shape), NULL, 0, 0, 0);
  468. }
  469. }
  470. void OS_JavaScript::set_mouse_mode(OS::MouseMode p_mode) {
  471. ERR_FAIL_COND_MSG(p_mode == MOUSE_MODE_CONFINED, "MOUSE_MODE_CONFINED is not supported for the HTML5 platform.");
  472. if (p_mode == get_mouse_mode())
  473. return;
  474. if (p_mode == MOUSE_MODE_VISIBLE) {
  475. godot_js_display_cursor_set_visible(1);
  476. emscripten_exit_pointerlock();
  477. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  478. godot_js_display_cursor_set_visible(0);
  479. emscripten_exit_pointerlock();
  480. } else if (p_mode == MOUSE_MODE_CAPTURED) {
  481. godot_js_display_cursor_set_visible(1);
  482. EMSCRIPTEN_RESULT result = emscripten_request_pointerlock(canvas_id, false);
  483. ERR_FAIL_COND_MSG(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED, "MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback.");
  484. ERR_FAIL_COND_MSG(result != EMSCRIPTEN_RESULT_SUCCESS, "MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback.");
  485. }
  486. }
  487. OS::MouseMode OS_JavaScript::get_mouse_mode() const {
  488. if (godot_js_display_cursor_is_hidden())
  489. return MOUSE_MODE_HIDDEN;
  490. EmscriptenPointerlockChangeEvent ev;
  491. emscripten_get_pointerlock_status(&ev);
  492. return (ev.isActive && String::utf8(ev.id) == String::utf8(&canvas_id[1])) ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE;
  493. }
  494. // Wheel
  495. EM_BOOL OS_JavaScript::wheel_callback(int p_event_type, const EmscriptenWheelEvent *p_event, void *p_user_data) {
  496. ERR_FAIL_COND_V(p_event_type != EMSCRIPTEN_EVENT_WHEEL, false);
  497. OS_JavaScript *os = get_singleton();
  498. if (!godot_js_display_canvas_is_focused()) {
  499. if (os->cursor_inside_canvas) {
  500. godot_js_display_canvas_focus();
  501. } else {
  502. return false;
  503. }
  504. }
  505. InputDefault *input = os->input;
  506. Ref<InputEventMouseButton> ev;
  507. ev.instance();
  508. ev->set_position(input->get_mouse_position());
  509. ev->set_global_position(ev->get_position());
  510. ev->set_shift(input->is_key_pressed(KEY_SHIFT));
  511. ev->set_alt(input->is_key_pressed(KEY_ALT));
  512. ev->set_control(input->is_key_pressed(KEY_CONTROL));
  513. ev->set_metakey(input->is_key_pressed(KEY_META));
  514. if (p_event->deltaY < 0)
  515. ev->set_button_index(BUTTON_WHEEL_UP);
  516. else if (p_event->deltaY > 0)
  517. ev->set_button_index(BUTTON_WHEEL_DOWN);
  518. else if (p_event->deltaX > 0)
  519. ev->set_button_index(BUTTON_WHEEL_LEFT);
  520. else if (p_event->deltaX < 0)
  521. ev->set_button_index(BUTTON_WHEEL_RIGHT);
  522. else
  523. return false;
  524. // Different browsers give wildly different delta values, and we can't
  525. // interpret deltaMode, so use default value for wheel events' factor.
  526. int button_flag = 1 << (ev->get_button_index() - 1);
  527. ev->set_pressed(true);
  528. ev->set_button_mask(input->get_mouse_button_mask() | button_flag);
  529. input->parse_input_event(ev);
  530. Ref<InputEventMouseButton> release = ev->duplicate();
  531. release->set_pressed(false);
  532. release->set_button_mask(input->get_mouse_button_mask() & ~button_flag);
  533. input->parse_input_event(release);
  534. return true;
  535. }
  536. // Touch
  537. bool OS_JavaScript::has_touchscreen_ui_hint() const {
  538. return godot_js_display_touchscreen_is_available();
  539. }
  540. EM_BOOL OS_JavaScript::touch_press_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  541. OS_JavaScript *os = get_singleton();
  542. Ref<InputEventScreenTouch> ev;
  543. int lowest_id_index = -1;
  544. for (int i = 0; i < p_event->numTouches; ++i) {
  545. const EmscriptenTouchPoint &touch = p_event->touches[i];
  546. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  547. lowest_id_index = i;
  548. if (!touch.isChanged)
  549. continue;
  550. ev.instance();
  551. ev->set_index(touch.identifier);
  552. ev->set_position(compute_position_in_canvas(touch.clientX, touch.clientY));
  553. os->touches[i] = ev->get_position();
  554. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_TOUCHSTART);
  555. os->input->parse_input_event(ev);
  556. }
  557. // Make sure to flush all events so we can call restricted APIs inside the event.
  558. os->input->flush_buffered_events();
  559. // Resume audio context after input in case autoplay was denied.
  560. os->resume_audio();
  561. return true;
  562. }
  563. EM_BOOL OS_JavaScript::touchmove_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  564. OS_JavaScript *os = get_singleton();
  565. Ref<InputEventScreenDrag> ev;
  566. int lowest_id_index = -1;
  567. for (int i = 0; i < p_event->numTouches; ++i) {
  568. const EmscriptenTouchPoint &touch = p_event->touches[i];
  569. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  570. lowest_id_index = i;
  571. if (!touch.isChanged)
  572. continue;
  573. ev.instance();
  574. ev->set_index(touch.identifier);
  575. ev->set_position(compute_position_in_canvas(touch.clientX, touch.clientY));
  576. Point2 &prev = os->touches[i];
  577. ev->set_relative(ev->get_position() - prev);
  578. prev = ev->get_position();
  579. os->input->parse_input_event(ev);
  580. }
  581. return true;
  582. }
  583. // Gamepad
  584. void OS_JavaScript::gamepad_callback(int p_index, int p_connected, const char *p_id, const char *p_guid) {
  585. InputDefault *input = get_singleton()->input;
  586. if (p_connected) {
  587. input->joy_connection_changed(p_index, true, String::utf8(p_id), String::utf8(p_guid));
  588. } else {
  589. input->joy_connection_changed(p_index, false, "");
  590. }
  591. }
  592. void OS_JavaScript::process_joypads() {
  593. int32_t pads = godot_js_display_gamepad_sample_count();
  594. int32_t s_btns_num = 0;
  595. int32_t s_axes_num = 0;
  596. int32_t s_standard = 0;
  597. float s_btns[16];
  598. float s_axes[10];
  599. for (int idx = 0; idx < pads; idx++) {
  600. int err = godot_js_display_gamepad_sample_get(idx, s_btns, &s_btns_num, s_axes, &s_axes_num, &s_standard);
  601. if (err) {
  602. continue;
  603. }
  604. for (int b = 0; b < s_btns_num; b++) {
  605. float value = s_btns[b];
  606. // Buttons 6 and 7 in the standard mapping need to be
  607. // axis to be handled as JOY_ANALOG by Godot.
  608. if (s_standard && (b == 6 || b == 7)) {
  609. InputDefault::JoyAxis joy_axis;
  610. joy_axis.min = 0;
  611. joy_axis.value = value;
  612. int a = b == 6 ? JOY_ANALOG_L2 : JOY_ANALOG_R2;
  613. input->joy_axis(idx, a, joy_axis);
  614. } else {
  615. input->joy_button(idx, b, value);
  616. }
  617. }
  618. for (int a = 0; a < s_axes_num; a++) {
  619. InputDefault::JoyAxis joy_axis;
  620. joy_axis.min = -1;
  621. joy_axis.value = s_axes[a];
  622. input->joy_axis(idx, a, joy_axis);
  623. }
  624. }
  625. }
  626. bool OS_JavaScript::is_joy_known(int p_device) {
  627. return input->is_joy_mapped(p_device);
  628. }
  629. String OS_JavaScript::get_joy_guid(int p_device) const {
  630. return input->get_joy_guid_remapped(p_device);
  631. }
  632. // Video
  633. int OS_JavaScript::get_video_driver_count() const {
  634. return VIDEO_DRIVER_MAX;
  635. }
  636. const char *OS_JavaScript::get_video_driver_name(int p_driver) const {
  637. switch (p_driver) {
  638. case VIDEO_DRIVER_GLES3:
  639. return "GLES3";
  640. case VIDEO_DRIVER_GLES2:
  641. return "GLES2";
  642. }
  643. ERR_FAIL_V_MSG(NULL, "Invalid video driver index: " + itos(p_driver) + ".");
  644. }
  645. // Audio
  646. int OS_JavaScript::get_audio_driver_count() const {
  647. return audio_drivers.size();
  648. }
  649. const char *OS_JavaScript::get_audio_driver_name(int p_driver) const {
  650. if (audio_drivers.size() <= p_driver) {
  651. return "Unknown";
  652. }
  653. return audio_drivers[p_driver]->get_name();
  654. }
  655. // Clipboard
  656. void OS_JavaScript::update_clipboard_callback(const char *p_text) {
  657. // Only call set_clipboard from OS (sets local clipboard)
  658. get_singleton()->OS::set_clipboard(p_text);
  659. }
  660. void OS_JavaScript::set_clipboard(const String &p_text) {
  661. OS::set_clipboard(p_text);
  662. int err = godot_js_display_clipboard_set(p_text.utf8().get_data());
  663. ERR_FAIL_COND_MSG(err, "Clipboard API is not supported.");
  664. }
  665. String OS_JavaScript::get_clipboard() const {
  666. godot_js_display_clipboard_get(update_clipboard_callback);
  667. return this->OS::get_clipboard();
  668. }
  669. // Lifecycle
  670. int OS_JavaScript::get_current_video_driver() const {
  671. return video_driver_index;
  672. }
  673. void OS_JavaScript::initialize_core() {
  674. OS_Unix::initialize_core();
  675. }
  676. Error OS_JavaScript::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  677. video_mode = p_desired;
  678. // fullscreen_change_callback will correct this if the request is successful.
  679. video_mode.fullscreen = false;
  680. // Handle contextmenu, webglcontextlost, initial canvas setup.
  681. godot_js_display_setup_canvas(video_mode.width, video_mode.height, video_mode.fullscreen, is_hidpi_allowed() ? 1 : 0);
  682. swap_ok_cancel = godot_js_display_is_swap_ok_cancel() == 1;
  683. EmscriptenWebGLContextAttributes attributes;
  684. emscripten_webgl_init_context_attributes(&attributes);
  685. attributes.alpha = GLOBAL_GET("display/window/per_pixel_transparency/allowed");
  686. attributes.antialias = false;
  687. attributes.explicitSwapControl = true;
  688. ERR_FAIL_INDEX_V(p_video_driver, VIDEO_DRIVER_MAX, ERR_INVALID_PARAMETER);
  689. if (p_desired.layered) {
  690. set_window_per_pixel_transparency_enabled(true);
  691. }
  692. #ifdef TOOLS_ENABLED
  693. bool gles3 = false;
  694. #else
  695. bool gles3 = true;
  696. if (p_video_driver == VIDEO_DRIVER_GLES2) {
  697. gles3 = false;
  698. }
  699. #endif
  700. bool gl_initialization_error = false;
  701. while (true) {
  702. if (gles3) {
  703. if (godot_js_display_has_webgl(2) && RasterizerGLES3::is_viable() == OK) {
  704. attributes.majorVersion = 2;
  705. RasterizerGLES3::register_config();
  706. RasterizerGLES3::make_current();
  707. break;
  708. } else {
  709. if (GLOBAL_GET("rendering/quality/driver/fallback_to_gles2")) {
  710. p_video_driver = VIDEO_DRIVER_GLES2;
  711. gles3 = false;
  712. continue;
  713. } else {
  714. gl_initialization_error = true;
  715. break;
  716. }
  717. }
  718. } else {
  719. if (godot_js_display_has_webgl(1) && RasterizerGLES2::is_viable() == OK) {
  720. attributes.majorVersion = 1;
  721. RasterizerGLES2::register_config();
  722. RasterizerGLES2::make_current();
  723. break;
  724. } else {
  725. gl_initialization_error = true;
  726. break;
  727. }
  728. }
  729. }
  730. webgl_ctx = emscripten_webgl_create_context(canvas_id, &attributes);
  731. if (emscripten_webgl_make_context_current(webgl_ctx) != EMSCRIPTEN_RESULT_SUCCESS) {
  732. gl_initialization_error = true;
  733. }
  734. if (gl_initialization_error) {
  735. OS::get_singleton()->alert("Your browser does not support any of the supported WebGL versions.\n"
  736. "Please update your browser version.",
  737. "Unable to initialize Video driver");
  738. return ERR_UNAVAILABLE;
  739. }
  740. video_driver_index = p_video_driver;
  741. AudioDriverManager::initialize(p_audio_driver);
  742. visual_server = memnew(VisualServerRaster());
  743. #ifndef NO_THREADS
  744. visual_server = memnew(VisualServerWrapMT(visual_server, false));
  745. #endif
  746. input = memnew(InputDefault);
  747. EMSCRIPTEN_RESULT result;
  748. #define EM_CHECK(ev) \
  749. if (result != EMSCRIPTEN_RESULT_SUCCESS) \
  750. ERR_PRINT("Error while setting " #ev " callback: Code " + itos(result));
  751. #define SET_EM_CALLBACK(target, ev, cb) \
  752. result = emscripten_set_##ev##_callback(target, NULL, true, &cb); \
  753. EM_CHECK(ev)
  754. #define SET_EM_WINDOW_CALLBACK(ev, cb) \
  755. result = emscripten_set_##ev##_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, false, &cb); \
  756. EM_CHECK(ev)
  757. // These callbacks from Emscripten's html5.h suffice to access most
  758. // JavaScript APIs.
  759. SET_EM_CALLBACK(canvas_id, mousedown, mouse_button_callback)
  760. SET_EM_WINDOW_CALLBACK(mousemove, mousemove_callback)
  761. SET_EM_WINDOW_CALLBACK(mouseup, mouse_button_callback)
  762. SET_EM_WINDOW_CALLBACK(blur, blur_callback)
  763. SET_EM_CALLBACK(canvas_id, wheel, wheel_callback)
  764. SET_EM_CALLBACK(canvas_id, touchstart, touch_press_callback)
  765. SET_EM_CALLBACK(canvas_id, touchmove, touchmove_callback)
  766. SET_EM_CALLBACK(canvas_id, touchend, touch_press_callback)
  767. SET_EM_CALLBACK(canvas_id, touchcancel, touch_press_callback)
  768. SET_EM_CALLBACK(canvas_id, keydown, keydown_callback)
  769. SET_EM_CALLBACK(canvas_id, keypress, keypress_callback)
  770. SET_EM_CALLBACK(canvas_id, keyup, keyup_callback)
  771. SET_EM_CALLBACK(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, fullscreenchange, fullscreen_change_callback)
  772. #undef SET_EM_CALLBACK
  773. #undef EM_CHECK
  774. // For APIs that are not (sufficiently) exposed, a
  775. // library is used below (implemented in library_godot_display.js).
  776. godot_js_display_notification_cb(&OS_JavaScript::send_notification_callback,
  777. MainLoop::NOTIFICATION_WM_MOUSE_ENTER,
  778. MainLoop::NOTIFICATION_WM_MOUSE_EXIT,
  779. MainLoop::NOTIFICATION_WM_FOCUS_IN,
  780. MainLoop::NOTIFICATION_WM_FOCUS_OUT);
  781. godot_js_display_paste_cb(&OS_JavaScript::update_clipboard_callback);
  782. godot_js_display_drop_files_cb(&OS_JavaScript::drop_files_callback);
  783. godot_js_display_gamepad_cb(&OS_JavaScript::gamepad_callback);
  784. godot_js_display_vk_cb(&input_text_callback);
  785. visual_server->init();
  786. return OK;
  787. }
  788. void OS_JavaScript::input_text_callback(const char *p_text, int p_cursor) {
  789. OS_JavaScript *os = OS_JavaScript::get_singleton();
  790. if (!os || !os->get_main_loop()) {
  791. return;
  792. }
  793. os->get_main_loop()->input_text(String::utf8(p_text));
  794. Ref<InputEventKey> k;
  795. for (int i = 0; i < p_cursor; i++) {
  796. k.instance();
  797. k->set_pressed(true);
  798. k->set_echo(false);
  799. k->set_scancode(KEY_RIGHT);
  800. os->input->parse_input_event(k);
  801. k.instance();
  802. k->set_pressed(false);
  803. k->set_echo(false);
  804. k->set_scancode(KEY_RIGHT);
  805. os->input->parse_input_event(k);
  806. }
  807. }
  808. bool OS_JavaScript::has_virtual_keyboard() const {
  809. return godot_js_display_vk_available() != 0;
  810. }
  811. void OS_JavaScript::show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect, bool p_multiline, int p_max_input_length, int p_cursor_start, int p_cursor_end) {
  812. godot_js_display_vk_show(p_existing_text.utf8().get_data(), p_multiline, p_cursor_start, p_cursor_end);
  813. }
  814. void OS_JavaScript::hide_virtual_keyboard() {
  815. godot_js_display_vk_hide();
  816. }
  817. bool OS_JavaScript::get_swap_ok_cancel() {
  818. return swap_ok_cancel;
  819. }
  820. void OS_JavaScript::swap_buffers() {
  821. emscripten_webgl_commit_frame();
  822. }
  823. void OS_JavaScript::set_main_loop(MainLoop *p_main_loop) {
  824. main_loop = p_main_loop;
  825. input->set_main_loop(p_main_loop);
  826. }
  827. MainLoop *OS_JavaScript::get_main_loop() const {
  828. return main_loop;
  829. }
  830. void OS_JavaScript::resume_audio() {
  831. AudioDriverJavaScript::resume();
  832. }
  833. void OS_JavaScript::fs_sync_callback() {
  834. get_singleton()->idb_is_syncing = false;
  835. }
  836. bool OS_JavaScript::main_loop_iterate() {
  837. if (is_userfs_persistent() && idb_needs_sync && !idb_is_syncing) {
  838. idb_is_syncing = true;
  839. idb_needs_sync = false;
  840. godot_js_os_fs_sync(&OS_JavaScript::fs_sync_callback);
  841. }
  842. input->flush_buffered_events();
  843. if (godot_js_display_gamepad_sample() == OK)
  844. process_joypads();
  845. if (just_exited_fullscreen) {
  846. if (window_maximized) {
  847. EmscriptenFullscreenStrategy strategy;
  848. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  849. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  850. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  851. strategy.canvasResizedCallback = NULL;
  852. emscripten_enter_soft_fullscreen(canvas_id, &strategy);
  853. } else {
  854. godot_js_display_size_update();
  855. }
  856. just_exited_fullscreen = false;
  857. }
  858. return Main::iteration();
  859. }
  860. int OS_JavaScript::get_screen_dpi(int p_screen) const {
  861. return godot_js_display_screen_dpi_get();
  862. }
  863. float OS_JavaScript::get_screen_scale(int p_screen) const {
  864. return godot_js_display_pixel_ratio_get();
  865. }
  866. float OS_JavaScript::get_screen_max_scale() const {
  867. return get_screen_scale();
  868. }
  869. void OS_JavaScript::delete_main_loop() {
  870. memdelete(main_loop);
  871. main_loop = NULL;
  872. }
  873. void OS_JavaScript::finalize() {
  874. memdelete(input);
  875. visual_server->finish();
  876. emscripten_webgl_commit_frame();
  877. memdelete(visual_server);
  878. emscripten_webgl_destroy_context(webgl_ctx);
  879. for (int i = 0; i < audio_drivers.size(); i++) {
  880. memdelete(audio_drivers[i]);
  881. }
  882. audio_drivers.clear();
  883. }
  884. // Miscellaneous
  885. 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) {
  886. Array args;
  887. for (const List<String>::Element *E = p_arguments.front(); E; E = E->next()) {
  888. args.push_back(E->get());
  889. }
  890. String json_args = JSON::print(args);
  891. int failed = godot_js_os_execute(json_args.utf8().get_data());
  892. ERR_FAIL_COND_V_MSG(failed, ERR_UNAVAILABLE, "OS::execute() must be implemented in Javascript via 'engine.setOnExecute' if required.");
  893. return OK;
  894. }
  895. Error OS_JavaScript::kill(const ProcessID &p_pid) {
  896. ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "OS::kill() is not available on the HTML5 platform.");
  897. }
  898. int OS_JavaScript::get_process_id() const {
  899. ERR_FAIL_V_MSG(0, "OS::get_process_id() is not available on the HTML5 platform.");
  900. }
  901. int OS_JavaScript::get_processor_count() const {
  902. return godot_js_os_hw_concurrency_get();
  903. }
  904. bool OS_JavaScript::_check_internal_feature_support(const String &p_feature) {
  905. if (p_feature == "HTML5" || p_feature == "web") {
  906. return true;
  907. }
  908. #ifdef JAVASCRIPT_EVAL_ENABLED
  909. if (p_feature == "JavaScript") {
  910. return true;
  911. }
  912. #endif
  913. #ifndef NO_THREADS
  914. if (p_feature == "threads") {
  915. return true;
  916. }
  917. #endif
  918. #if WASM_GDNATIVE
  919. if (p_feature == "wasm32") {
  920. return true;
  921. }
  922. #endif
  923. return false;
  924. }
  925. void OS_JavaScript::alert(const String &p_alert, const String &p_title) {
  926. godot_js_display_alert(p_alert.utf8().get_data());
  927. }
  928. void OS_JavaScript::set_window_title(const String &p_title) {
  929. godot_js_display_window_title_set(p_title.utf8().get_data());
  930. }
  931. void OS_JavaScript::set_icon(const Ref<Image> &p_icon) {
  932. ERR_FAIL_COND(p_icon.is_null());
  933. Ref<Image> icon = p_icon;
  934. if (icon->is_compressed()) {
  935. icon = icon->duplicate();
  936. ERR_FAIL_COND(icon->decompress() != OK);
  937. }
  938. if (icon->get_format() != Image::FORMAT_RGBA8) {
  939. if (icon == p_icon)
  940. icon = icon->duplicate();
  941. icon->convert(Image::FORMAT_RGBA8);
  942. }
  943. png_image png_meta;
  944. memset(&png_meta, 0, sizeof png_meta);
  945. png_meta.version = PNG_IMAGE_VERSION;
  946. png_meta.width = icon->get_width();
  947. png_meta.height = icon->get_height();
  948. png_meta.format = PNG_FORMAT_RGBA;
  949. PoolByteArray png;
  950. size_t len;
  951. PoolByteArray::Read r = icon->get_data().read();
  952. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, r.ptr(), 0, NULL));
  953. png.resize(len);
  954. PoolByteArray::Write w = png.write();
  955. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, w.ptr(), &len, 0, r.ptr(), 0, NULL));
  956. w = PoolByteArray::Write();
  957. r = png.read();
  958. godot_js_display_window_icon_set(r.ptr(), len);
  959. }
  960. String OS_JavaScript::get_executable_path() const {
  961. return OS::get_executable_path();
  962. }
  963. Error OS_JavaScript::shell_open(String p_uri) {
  964. // Open URI in a new tab, browser will deal with it by protocol.
  965. godot_js_os_shell_open(p_uri.utf8().get_data());
  966. return OK;
  967. }
  968. String OS_JavaScript::get_name() const {
  969. return "HTML5";
  970. }
  971. bool OS_JavaScript::can_draw() const {
  972. return true; // Always?
  973. }
  974. String OS_JavaScript::get_user_data_dir() const {
  975. return "/userfs";
  976. };
  977. String OS_JavaScript::get_cache_path() const {
  978. return "/home/web_user/.cache";
  979. }
  980. String OS_JavaScript::get_config_path() const {
  981. return "/home/web_user/.config";
  982. }
  983. String OS_JavaScript::get_data_path() const {
  984. return "/home/web_user/.local/share";
  985. }
  986. OS::PowerState OS_JavaScript::get_power_state() {
  987. WARN_PRINT_ONCE("Power management is not supported for the HTML5 platform, defaulting to POWERSTATE_UNKNOWN");
  988. return OS::POWERSTATE_UNKNOWN;
  989. }
  990. int OS_JavaScript::get_power_seconds_left() {
  991. WARN_PRINT_ONCE("Power management is not supported for the HTML5 platform, defaulting to -1");
  992. return -1;
  993. }
  994. int OS_JavaScript::get_power_percent_left() {
  995. WARN_PRINT_ONCE("Power management is not supported for the HTML5 platform, defaulting to -1");
  996. return -1;
  997. }
  998. void OS_JavaScript::file_access_close_callback(const String &p_file, int p_flags) {
  999. OS_JavaScript *os = get_singleton();
  1000. if (!(os->is_userfs_persistent() && p_flags & FileAccess::WRITE)) {
  1001. return; // FS persistence is not working or we are not writing.
  1002. }
  1003. bool is_file_persistent = p_file.begins_with("/userfs");
  1004. #ifdef TOOLS_ENABLED
  1005. // Hack for editor persistence (can we track).
  1006. is_file_persistent = is_file_persistent || p_file.begins_with("/home/web_user/");
  1007. #endif
  1008. if (is_file_persistent) {
  1009. os->idb_needs_sync = true;
  1010. }
  1011. }
  1012. bool OS_JavaScript::is_userfs_persistent() const {
  1013. return idb_available;
  1014. }
  1015. Error OS_JavaScript::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
  1016. String path = p_path.get_file();
  1017. p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
  1018. ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, "Can't open dynamic library: " + p_path + ". Error: " + dlerror());
  1019. return OK;
  1020. }
  1021. OS_JavaScript *OS_JavaScript::get_singleton() {
  1022. return static_cast<OS_JavaScript *>(OS::get_singleton());
  1023. }
  1024. OS_JavaScript::OS_JavaScript() {
  1025. // Expose method for requesting quit.
  1026. godot_js_os_request_quit_cb(&request_quit_callback);
  1027. // Set canvas ID
  1028. godot_js_config_canvas_id_get(canvas_id, sizeof(canvas_id));
  1029. cursor_inside_canvas = true;
  1030. cursor_shape = OS::CURSOR_ARROW;
  1031. last_click_button_index = -1;
  1032. last_click_ms = 0;
  1033. last_click_pos = Point2(-100, -100);
  1034. window_maximized = false;
  1035. entering_fullscreen = false;
  1036. just_exited_fullscreen = false;
  1037. transparency_enabled = false;
  1038. main_loop = NULL;
  1039. visual_server = NULL;
  1040. swap_ok_cancel = false;
  1041. idb_available = godot_js_os_fs_is_persistent() != 0;
  1042. idb_needs_sync = false;
  1043. idb_is_syncing = false;
  1044. if (AudioDriverJavaScript::is_available()) {
  1045. #ifdef NO_THREADS
  1046. audio_drivers.push_back(memnew(AudioDriverScriptProcessor));
  1047. #endif
  1048. audio_drivers.push_back(memnew(AudioDriverWorklet));
  1049. }
  1050. for (int i = 0; i < audio_drivers.size(); i++) {
  1051. AudioDriverManager::add_driver(audio_drivers[i]);
  1052. }
  1053. Vector<Logger *> loggers;
  1054. loggers.push_back(memnew(StdLogger));
  1055. _set_logger(memnew(CompositeLogger(loggers)));
  1056. FileAccessUnix::close_notification_func = file_access_close_callback;
  1057. }