os_javascript.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  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. double scale = godot_js_display_pixel_ratio_get();
  141. return Size2(ev.screenWidth * scale, ev.screenHeight * scale);
  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[1])) ? 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. void OS_JavaScript::gamepad_callback(int p_index, int p_connected, const char *p_id, const char *p_guid) {
  573. InputDefault *input = get_singleton()->input;
  574. if (p_connected) {
  575. input->joy_connection_changed(p_index, true, String::utf8(p_id), String::utf8(p_guid));
  576. } else {
  577. input->joy_connection_changed(p_index, false, "");
  578. }
  579. }
  580. void OS_JavaScript::process_joypads() {
  581. int32_t pads = godot_js_display_gamepad_sample_count();
  582. int32_t s_btns_num = 0;
  583. int32_t s_axes_num = 0;
  584. int32_t s_standard = 0;
  585. float s_btns[16];
  586. float s_axes[10];
  587. for (int idx = 0; idx < pads; idx++) {
  588. int err = godot_js_display_gamepad_sample_get(idx, s_btns, &s_btns_num, s_axes, &s_axes_num, &s_standard);
  589. if (err) {
  590. continue;
  591. }
  592. for (int b = 0; b < s_btns_num; b++) {
  593. float value = s_btns[b];
  594. // Buttons 6 and 7 in the standard mapping need to be
  595. // axis to be handled as JOY_ANALOG by Godot.
  596. if (s_standard && (b == 6 || b == 7)) {
  597. InputDefault::JoyAxis joy_axis;
  598. joy_axis.min = 0;
  599. joy_axis.value = value;
  600. int a = b == 6 ? JOY_ANALOG_L2 : JOY_ANALOG_R2;
  601. input->joy_axis(idx, a, joy_axis);
  602. } else {
  603. input->joy_button(idx, b, value);
  604. }
  605. }
  606. for (int a = 0; a < s_axes_num; a++) {
  607. InputDefault::JoyAxis joy_axis;
  608. joy_axis.min = -1;
  609. joy_axis.value = s_axes[a];
  610. input->joy_axis(idx, a, joy_axis);
  611. }
  612. }
  613. }
  614. bool OS_JavaScript::is_joy_known(int p_device) {
  615. return input->is_joy_mapped(p_device);
  616. }
  617. String OS_JavaScript::get_joy_guid(int p_device) const {
  618. return input->get_joy_guid_remapped(p_device);
  619. }
  620. // Video
  621. int OS_JavaScript::get_video_driver_count() const {
  622. return VIDEO_DRIVER_MAX;
  623. }
  624. const char *OS_JavaScript::get_video_driver_name(int p_driver) const {
  625. switch (p_driver) {
  626. case VIDEO_DRIVER_GLES3:
  627. return "GLES3";
  628. case VIDEO_DRIVER_GLES2:
  629. return "GLES2";
  630. }
  631. ERR_FAIL_V_MSG(NULL, "Invalid video driver index: " + itos(p_driver) + ".");
  632. }
  633. // Audio
  634. int OS_JavaScript::get_audio_driver_count() const {
  635. return 1;
  636. }
  637. const char *OS_JavaScript::get_audio_driver_name(int p_driver) const {
  638. return "JavaScript";
  639. }
  640. // Clipboard
  641. void OS_JavaScript::update_clipboard_callback(const char *p_text) {
  642. // Only call set_clipboard from OS (sets local clipboard)
  643. get_singleton()->OS::set_clipboard(p_text);
  644. }
  645. void OS_JavaScript::set_clipboard(const String &p_text) {
  646. OS::set_clipboard(p_text);
  647. int err = godot_js_display_clipboard_set(p_text.utf8().get_data());
  648. ERR_FAIL_COND_MSG(err, "Clipboard API is not supported.");
  649. }
  650. String OS_JavaScript::get_clipboard() const {
  651. godot_js_display_clipboard_get(update_clipboard_callback);
  652. return this->OS::get_clipboard();
  653. }
  654. // Lifecycle
  655. int OS_JavaScript::get_current_video_driver() const {
  656. return video_driver_index;
  657. }
  658. void OS_JavaScript::initialize_core() {
  659. OS_Unix::initialize_core();
  660. }
  661. Error OS_JavaScript::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  662. godot_js_display_setup_canvas(); // Handle contextmenu, webglcontextlost
  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_canvas_resize_policy_get() == 1) {
  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. // These callbacks from Emscripten's html5.h suffice to access most
  753. // JavaScript APIs.
  754. SET_EM_CALLBACK(canvas_id, mousedown, mouse_button_callback)
  755. SET_EM_WINDOW_CALLBACK(mousemove, mousemove_callback)
  756. SET_EM_WINDOW_CALLBACK(mouseup, mouse_button_callback)
  757. SET_EM_CALLBACK(canvas_id, wheel, wheel_callback)
  758. SET_EM_CALLBACK(canvas_id, touchstart, touch_press_callback)
  759. SET_EM_CALLBACK(canvas_id, touchmove, touchmove_callback)
  760. SET_EM_CALLBACK(canvas_id, touchend, touch_press_callback)
  761. SET_EM_CALLBACK(canvas_id, touchcancel, touch_press_callback)
  762. SET_EM_CALLBACK(canvas_id, keydown, keydown_callback)
  763. SET_EM_CALLBACK(canvas_id, keypress, keypress_callback)
  764. SET_EM_CALLBACK(canvas_id, keyup, keyup_callback)
  765. SET_EM_CALLBACK(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, fullscreenchange, fullscreen_change_callback)
  766. #undef SET_EM_CALLBACK
  767. #undef EM_CHECK
  768. // For APIs that are not (sufficiently) exposed, a
  769. // library is used below (implemented in library_godot_display.js).
  770. godot_js_display_notification_cb(&OS_JavaScript::send_notification_callback,
  771. MainLoop::NOTIFICATION_WM_MOUSE_ENTER,
  772. MainLoop::NOTIFICATION_WM_MOUSE_EXIT,
  773. MainLoop::NOTIFICATION_WM_FOCUS_IN,
  774. MainLoop::NOTIFICATION_WM_FOCUS_OUT);
  775. godot_js_display_paste_cb(&OS_JavaScript::update_clipboard_callback);
  776. godot_js_display_drop_files_cb(&OS_JavaScript::drop_files_callback);
  777. godot_js_display_gamepad_cb(&OS_JavaScript::gamepad_callback);
  778. visual_server->init();
  779. return OK;
  780. }
  781. bool OS_JavaScript::get_swap_ok_cancel() {
  782. return swap_ok_cancel;
  783. }
  784. void OS_JavaScript::swap_buffers() {
  785. emscripten_webgl_commit_frame();
  786. }
  787. void OS_JavaScript::set_main_loop(MainLoop *p_main_loop) {
  788. main_loop = p_main_loop;
  789. input->set_main_loop(p_main_loop);
  790. }
  791. MainLoop *OS_JavaScript::get_main_loop() const {
  792. return main_loop;
  793. }
  794. void OS_JavaScript::resume_audio() {
  795. if (audio_driver_javascript) {
  796. audio_driver_javascript->resume();
  797. }
  798. }
  799. void OS_JavaScript::fs_sync_callback() {
  800. get_singleton()->idb_is_syncing = false;
  801. }
  802. bool OS_JavaScript::main_loop_iterate() {
  803. if (is_userfs_persistent() && idb_needs_sync && !idb_is_syncing) {
  804. idb_is_syncing = true;
  805. idb_needs_sync = false;
  806. godot_js_os_fs_sync(&OS_JavaScript::fs_sync_callback);
  807. }
  808. if (godot_js_display_gamepad_sample() == OK)
  809. process_joypads();
  810. if (just_exited_fullscreen) {
  811. if (window_maximized) {
  812. EmscriptenFullscreenStrategy strategy;
  813. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  814. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  815. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  816. strategy.canvasResizedCallback = NULL;
  817. emscripten_enter_soft_fullscreen(canvas_id, &strategy);
  818. } else {
  819. set_window_size(Size2(windowed_size.width, windowed_size.height));
  820. }
  821. just_exited_fullscreen = false;
  822. }
  823. int canvas[2];
  824. emscripten_get_canvas_element_size(canvas_id, canvas, canvas + 1);
  825. video_mode.width = canvas[0];
  826. video_mode.height = canvas[1];
  827. if (!window_maximized && !video_mode.fullscreen && !just_exited_fullscreen && !entering_fullscreen) {
  828. windowed_size.width = canvas[0];
  829. windowed_size.height = canvas[1];
  830. }
  831. return Main::iteration();
  832. }
  833. int OS_JavaScript::get_screen_dpi(int p_screen) const {
  834. return godot_js_display_screen_dpi_get();
  835. }
  836. float OS_JavaScript::get_screen_scale(int p_screen) const {
  837. return godot_js_display_pixel_ratio_get();
  838. }
  839. float OS_JavaScript::get_screen_max_scale() const {
  840. return get_screen_scale();
  841. }
  842. void OS_JavaScript::delete_main_loop() {
  843. memdelete(main_loop);
  844. main_loop = NULL;
  845. }
  846. void OS_JavaScript::finalize() {
  847. memdelete(input);
  848. visual_server->finish();
  849. emscripten_webgl_commit_frame();
  850. memdelete(visual_server);
  851. emscripten_webgl_destroy_context(webgl_ctx);
  852. if (audio_driver_javascript) {
  853. memdelete(audio_driver_javascript);
  854. }
  855. }
  856. // Miscellaneous
  857. 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) {
  858. Array args;
  859. for (const List<String>::Element *E = p_arguments.front(); E; E = E->next()) {
  860. args.push_back(E->get());
  861. }
  862. String json_args = JSON::print(args);
  863. int failed = godot_js_os_execute(json_args.utf8().get_data());
  864. ERR_FAIL_COND_V_MSG(failed, ERR_UNAVAILABLE, "OS::execute() must be implemented in Javascript via 'engine.setOnExecute' if required.");
  865. return OK;
  866. }
  867. Error OS_JavaScript::kill(const ProcessID &p_pid) {
  868. ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "OS::kill() is not available on the HTML5 platform.");
  869. }
  870. int OS_JavaScript::get_process_id() const {
  871. ERR_FAIL_V_MSG(0, "OS::get_process_id() is not available on the HTML5 platform.");
  872. }
  873. int OS_JavaScript::get_processor_count() const {
  874. return godot_js_os_hw_concurrency_get();
  875. }
  876. bool OS_JavaScript::_check_internal_feature_support(const String &p_feature) {
  877. if (p_feature == "HTML5" || p_feature == "web") {
  878. return true;
  879. }
  880. #ifdef JAVASCRIPT_EVAL_ENABLED
  881. if (p_feature == "JavaScript") {
  882. return true;
  883. }
  884. #endif
  885. #ifndef NO_THREADS
  886. if (p_feature == "threads") {
  887. return true;
  888. }
  889. #endif
  890. #if WASM_GDNATIVE
  891. if (p_feature == "wasm32") {
  892. return true;
  893. }
  894. #endif
  895. return false;
  896. }
  897. void OS_JavaScript::alert(const String &p_alert, const String &p_title) {
  898. godot_js_display_alert(p_alert.utf8().get_data());
  899. }
  900. void OS_JavaScript::set_window_title(const String &p_title) {
  901. godot_js_display_window_title_set(p_title.utf8().get_data());
  902. }
  903. void OS_JavaScript::set_icon(const Ref<Image> &p_icon) {
  904. ERR_FAIL_COND(p_icon.is_null());
  905. Ref<Image> icon = p_icon;
  906. if (icon->is_compressed()) {
  907. icon = icon->duplicate();
  908. ERR_FAIL_COND(icon->decompress() != OK);
  909. }
  910. if (icon->get_format() != Image::FORMAT_RGBA8) {
  911. if (icon == p_icon)
  912. icon = icon->duplicate();
  913. icon->convert(Image::FORMAT_RGBA8);
  914. }
  915. png_image png_meta;
  916. memset(&png_meta, 0, sizeof png_meta);
  917. png_meta.version = PNG_IMAGE_VERSION;
  918. png_meta.width = icon->get_width();
  919. png_meta.height = icon->get_height();
  920. png_meta.format = PNG_FORMAT_RGBA;
  921. PoolByteArray png;
  922. size_t len;
  923. PoolByteArray::Read r = icon->get_data().read();
  924. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, r.ptr(), 0, NULL));
  925. png.resize(len);
  926. PoolByteArray::Write w = png.write();
  927. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, w.ptr(), &len, 0, r.ptr(), 0, NULL));
  928. w = PoolByteArray::Write();
  929. r = png.read();
  930. godot_js_display_window_icon_set(r.ptr(), len);
  931. }
  932. String OS_JavaScript::get_executable_path() const {
  933. return OS::get_executable_path();
  934. }
  935. Error OS_JavaScript::shell_open(String p_uri) {
  936. // Open URI in a new tab, browser will deal with it by protocol.
  937. godot_js_os_shell_open(p_uri.utf8().get_data());
  938. return OK;
  939. }
  940. String OS_JavaScript::get_name() const {
  941. return "HTML5";
  942. }
  943. bool OS_JavaScript::can_draw() const {
  944. return true; // Always?
  945. }
  946. String OS_JavaScript::get_user_data_dir() const {
  947. return "/userfs";
  948. };
  949. String OS_JavaScript::get_cache_path() const {
  950. return "/home/web_user/.cache";
  951. }
  952. String OS_JavaScript::get_config_path() const {
  953. return "/home/web_user/.config";
  954. }
  955. String OS_JavaScript::get_data_path() const {
  956. return "/home/web_user/.local/share";
  957. }
  958. OS::PowerState OS_JavaScript::get_power_state() {
  959. WARN_PRINT_ONCE("Power management is not supported for the HTML5 platform, defaulting to POWERSTATE_UNKNOWN");
  960. return OS::POWERSTATE_UNKNOWN;
  961. }
  962. int OS_JavaScript::get_power_seconds_left() {
  963. WARN_PRINT_ONCE("Power management is not supported for the HTML5 platform, defaulting to -1");
  964. return -1;
  965. }
  966. int OS_JavaScript::get_power_percent_left() {
  967. WARN_PRINT_ONCE("Power management is not supported for the HTML5 platform, defaulting to -1");
  968. return -1;
  969. }
  970. void OS_JavaScript::file_access_close_callback(const String &p_file, int p_flags) {
  971. OS_JavaScript *os = get_singleton();
  972. if (!(os->is_userfs_persistent() && p_flags & FileAccess::WRITE)) {
  973. return; // FS persistence is not working or we are not writing.
  974. }
  975. bool is_file_persistent = p_file.begins_with("/userfs");
  976. #ifdef TOOLS_ENABLED
  977. // Hack for editor persistence (can we track).
  978. is_file_persistent = is_file_persistent || p_file.begins_with("/home/web_user/");
  979. #endif
  980. if (is_file_persistent) {
  981. os->idb_needs_sync = true;
  982. }
  983. }
  984. bool OS_JavaScript::is_userfs_persistent() const {
  985. return idb_available;
  986. }
  987. Error OS_JavaScript::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
  988. String path = p_path.get_file();
  989. p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
  990. ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, "Can't open dynamic library: " + p_path + ". Error: " + dlerror());
  991. return OK;
  992. }
  993. OS_JavaScript *OS_JavaScript::get_singleton() {
  994. return static_cast<OS_JavaScript *>(OS::get_singleton());
  995. }
  996. OS_JavaScript::OS_JavaScript() {
  997. // Expose method for requesting quit.
  998. godot_js_os_request_quit_cb(&request_quit_callback);
  999. // Set canvas ID
  1000. godot_js_config_canvas_id_get(canvas_id, sizeof(canvas_id));
  1001. cursor_inside_canvas = true;
  1002. cursor_shape = OS::CURSOR_ARROW;
  1003. last_click_button_index = -1;
  1004. last_click_ms = 0;
  1005. last_click_pos = Point2(-100, -100);
  1006. last_width = 0;
  1007. last_height = 0;
  1008. window_maximized = false;
  1009. entering_fullscreen = false;
  1010. just_exited_fullscreen = false;
  1011. transparency_enabled = false;
  1012. main_loop = NULL;
  1013. visual_server = NULL;
  1014. audio_driver_javascript = NULL;
  1015. swap_ok_cancel = false;
  1016. idb_available = godot_js_os_fs_is_persistent() != 0;
  1017. idb_needs_sync = false;
  1018. idb_is_syncing = false;
  1019. if (AudioDriverJavaScript::is_available()) {
  1020. audio_driver_javascript = memnew(AudioDriverJavaScript);
  1021. AudioDriverManager::add_driver(audio_driver_javascript);
  1022. }
  1023. Vector<Logger *> loggers;
  1024. loggers.push_back(memnew(StdLogger));
  1025. _set_logger(memnew(CompositeLogger(loggers)));
  1026. FileAccessUnix::close_notification_func = file_access_close_callback;
  1027. }