os_javascript.cpp 38 KB

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