os_javascript.cpp 39 KB

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