os_javascript.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254
  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 <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)) {
  117. // This event property is the only reliable data on
  118. // browser fullscreen state.
  119. os->video_mode.fullscreen = p_event->isFullscreen;
  120. if (os->video_mode.fullscreen) {
  121. os->entering_fullscreen = false;
  122. } else {
  123. // Restoring maximized window now will cause issues,
  124. // so delay until main_loop_iterate.
  125. os->just_exited_fullscreen = true;
  126. }
  127. }
  128. return false;
  129. }
  130. void OS_JavaScript::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  131. video_mode = p_video_mode;
  132. }
  133. OS::VideoMode OS_JavaScript::get_video_mode(int p_screen) const {
  134. return video_mode;
  135. }
  136. Size2 OS_JavaScript::get_screen_size(int p_screen) const {
  137. EmscriptenFullscreenChangeEvent ev;
  138. EMSCRIPTEN_RESULT result = emscripten_get_fullscreen_status(&ev);
  139. ERR_FAIL_COND_V(result != EMSCRIPTEN_RESULT_SUCCESS, Size2());
  140. return Size2(ev.screenWidth, ev.screenHeight);
  141. }
  142. void OS_JavaScript::set_window_size(const Size2 p_size) {
  143. windowed_size = p_size;
  144. if (video_mode.fullscreen) {
  145. window_maximized = false;
  146. set_window_fullscreen(false);
  147. } else {
  148. if (window_maximized) {
  149. emscripten_exit_soft_fullscreen();
  150. window_maximized = false;
  151. }
  152. double scale = godot_js_display_pixel_ratio_get();
  153. emscripten_set_canvas_element_size(canvas_id, p_size.x, p_size.y);
  154. emscripten_set_element_css_size(canvas_id, p_size.x / scale, p_size.y / scale);
  155. }
  156. }
  157. Size2 OS_JavaScript::get_window_size() const {
  158. int canvas[2];
  159. emscripten_get_canvas_element_size(canvas_id, canvas, canvas + 1);
  160. return Size2(canvas[0], canvas[1]);
  161. }
  162. void OS_JavaScript::set_window_maximized(bool p_enabled) {
  163. #ifndef TOOLS_ENABLED
  164. if (video_mode.fullscreen) {
  165. window_maximized = p_enabled;
  166. set_window_fullscreen(false);
  167. } else if (!p_enabled) {
  168. emscripten_exit_soft_fullscreen();
  169. window_maximized = false;
  170. } else if (!window_maximized) {
  171. // Prevent calling emscripten_enter_soft_fullscreen mutltiple times,
  172. // this would hide page elements permanently.
  173. EmscriptenFullscreenStrategy strategy;
  174. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  175. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  176. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  177. strategy.canvasResizedCallback = NULL;
  178. emscripten_enter_soft_fullscreen(canvas_id, &strategy);
  179. window_maximized = p_enabled;
  180. }
  181. #endif
  182. }
  183. bool OS_JavaScript::is_window_maximized() const {
  184. return window_maximized;
  185. }
  186. void OS_JavaScript::set_window_fullscreen(bool p_enabled) {
  187. if (p_enabled == video_mode.fullscreen) {
  188. return;
  189. }
  190. // Just request changes here, if successful, logic continues in
  191. // fullscreen_change_callback.
  192. if (p_enabled) {
  193. if (window_maximized) {
  194. // Soft fullsreen during real fullscreen can cause issues, so exit.
  195. // This must be called before requesting full screen.
  196. emscripten_exit_soft_fullscreen();
  197. }
  198. EmscriptenFullscreenStrategy strategy;
  199. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  200. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  201. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  202. strategy.canvasResizedCallback = NULL;
  203. EMSCRIPTEN_RESULT result = emscripten_request_fullscreen_strategy(canvas_id, false, &strategy);
  204. ERR_FAIL_COND_MSG(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED, "Enabling fullscreen is only possible from an input callback for the HTML5 platform.");
  205. ERR_FAIL_COND_MSG(result != EMSCRIPTEN_RESULT_SUCCESS, "Enabling fullscreen is only possible from an input callback for the HTML5 platform.");
  206. // Not fullscreen yet, so prevent "windowed" canvas dimensions from
  207. // being overwritten.
  208. entering_fullscreen = true;
  209. } else {
  210. // No logic allowed here, since exiting w/ ESC key won't use this function.
  211. ERR_FAIL_COND(emscripten_exit_fullscreen() != EMSCRIPTEN_RESULT_SUCCESS);
  212. }
  213. }
  214. bool OS_JavaScript::is_window_fullscreen() const {
  215. return video_mode.fullscreen;
  216. }
  217. void OS_JavaScript::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  218. Size2 screen = get_screen_size();
  219. p_list->push_back(OS::VideoMode(screen.width, screen.height, true));
  220. }
  221. bool OS_JavaScript::get_window_per_pixel_transparency_enabled() const {
  222. if (!is_layered_allowed()) {
  223. return false;
  224. }
  225. return transparency_enabled;
  226. }
  227. void OS_JavaScript::set_window_per_pixel_transparency_enabled(bool p_enabled) {
  228. if (!is_layered_allowed()) {
  229. return;
  230. }
  231. transparency_enabled = p_enabled;
  232. }
  233. // Keys
  234. template <typename T>
  235. static void dom2godot_mod(T *emscripten_event_ptr, Ref<InputEventWithModifiers> godot_event) {
  236. godot_event->set_shift(emscripten_event_ptr->shiftKey);
  237. godot_event->set_alt(emscripten_event_ptr->altKey);
  238. godot_event->set_control(emscripten_event_ptr->ctrlKey);
  239. godot_event->set_metakey(emscripten_event_ptr->metaKey);
  240. }
  241. static Ref<InputEventKey> setup_key_event(const EmscriptenKeyboardEvent *emscripten_event) {
  242. Ref<InputEventKey> ev;
  243. ev.instance();
  244. ev->set_echo(emscripten_event->repeat);
  245. dom2godot_mod(emscripten_event, ev);
  246. ev->set_scancode(dom_code2godot_scancode(emscripten_event->code, emscripten_event->key));
  247. String unicode = String::utf8(emscripten_event->key);
  248. // Check if empty or multi-character (e.g. `CapsLock`).
  249. if (unicode.length() != 1) {
  250. // Might be empty as well, but better than nonsense.
  251. unicode = String::utf8(emscripten_event->charValue);
  252. }
  253. if (unicode.length() == 1) {
  254. ev->set_unicode(unicode[0]);
  255. }
  256. return ev;
  257. }
  258. EM_BOOL OS_JavaScript::keydown_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  259. OS_JavaScript *os = get_singleton();
  260. Ref<InputEventKey> ev = setup_key_event(p_event);
  261. ev->set_pressed(true);
  262. if (ev->get_unicode() == 0 && keycode_has_unicode(ev->get_scancode())) {
  263. // Defer to keypress event for legacy unicode retrieval.
  264. os->deferred_key_event = ev;
  265. // Do not suppress keypress event.
  266. return false;
  267. }
  268. os->input->parse_input_event(ev);
  269. // Resume audio context after input in case autoplay was denied.
  270. os->resume_audio();
  271. return true;
  272. }
  273. EM_BOOL OS_JavaScript::keypress_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  274. OS_JavaScript *os = get_singleton();
  275. os->deferred_key_event->set_unicode(p_event->charCode);
  276. os->input->parse_input_event(os->deferred_key_event);
  277. return true;
  278. }
  279. EM_BOOL OS_JavaScript::keyup_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  280. Ref<InputEventKey> ev = setup_key_event(p_event);
  281. ev->set_pressed(false);
  282. get_singleton()->input->parse_input_event(ev);
  283. return ev->get_scancode() != KEY_UNKNOWN && ev->get_scancode() != 0;
  284. }
  285. // Mouse
  286. Point2 OS_JavaScript::get_mouse_position() const {
  287. return input->get_mouse_position();
  288. }
  289. int OS_JavaScript::get_mouse_button_state() const {
  290. return input->get_mouse_button_mask();
  291. }
  292. EM_BOOL OS_JavaScript::mouse_button_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) {
  293. OS_JavaScript *os = get_singleton();
  294. Ref<InputEventMouseButton> ev;
  295. ev.instance();
  296. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_MOUSEDOWN);
  297. ev->set_position(compute_position_in_canvas(p_event->clientX, p_event->clientY));
  298. ev->set_global_position(ev->get_position());
  299. dom2godot_mod(p_event, ev);
  300. switch (p_event->button) {
  301. case DOM_BUTTON_LEFT: ev->set_button_index(BUTTON_LEFT); break;
  302. case DOM_BUTTON_MIDDLE: ev->set_button_index(BUTTON_MIDDLE); break;
  303. case DOM_BUTTON_RIGHT: ev->set_button_index(BUTTON_RIGHT); break;
  304. case DOM_BUTTON_XBUTTON1: ev->set_button_index(BUTTON_XBUTTON1); break;
  305. case DOM_BUTTON_XBUTTON2: ev->set_button_index(BUTTON_XBUTTON2); break;
  306. default: return false;
  307. }
  308. if (ev->is_pressed()) {
  309. double diff = emscripten_get_now() - os->last_click_ms;
  310. if (ev->get_button_index() == os->last_click_button_index) {
  311. if (diff < 400 && Point2(os->last_click_pos).distance_to(ev->get_position()) < 5) {
  312. os->last_click_ms = 0;
  313. os->last_click_pos = Point2(-100, -100);
  314. os->last_click_button_index = -1;
  315. ev->set_doubleclick(true);
  316. }
  317. } else {
  318. os->last_click_button_index = ev->get_button_index();
  319. }
  320. if (!ev->is_doubleclick()) {
  321. os->last_click_ms += diff;
  322. os->last_click_pos = ev->get_position();
  323. }
  324. }
  325. int mask = os->input->get_mouse_button_mask();
  326. int button_flag = 1 << (ev->get_button_index() - 1);
  327. if (ev->is_pressed()) {
  328. // Since the event is consumed, focus manually. The containing iframe,
  329. // if exists, may not have focus yet, so focus even if already focused.
  330. godot_js_display_canvas_focus();
  331. mask |= button_flag;
  332. } else if (mask & button_flag) {
  333. mask &= ~button_flag;
  334. } else {
  335. // Received release event, but press was outside the canvas, so ignore.
  336. return false;
  337. }
  338. ev->set_button_mask(mask);
  339. os->input->parse_input_event(ev);
  340. // Resume audio context after input in case autoplay was denied.
  341. os->resume_audio();
  342. // Prevent multi-click text selection and wheel-click scrolling anchor.
  343. // Context menu is prevented through contextmenu event.
  344. return true;
  345. }
  346. EM_BOOL OS_JavaScript::mousemove_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) {
  347. OS_JavaScript *os = get_singleton();
  348. int input_mask = os->input->get_mouse_button_mask();
  349. Point2 pos = compute_position_in_canvas(p_event->clientX, p_event->clientY);
  350. // For motion outside the canvas, only read mouse movement if dragging
  351. // started inside the canvas; imitating desktop app behaviour.
  352. if (!os->cursor_inside_canvas && !input_mask)
  353. return false;
  354. Ref<InputEventMouseMotion> ev;
  355. ev.instance();
  356. dom2godot_mod(p_event, ev);
  357. ev->set_button_mask(input_mask);
  358. ev->set_position(pos);
  359. ev->set_global_position(ev->get_position());
  360. ev->set_relative(Vector2(p_event->movementX, p_event->movementY));
  361. os->input->set_mouse_position(ev->get_position());
  362. ev->set_speed(os->input->get_last_mouse_speed());
  363. os->input->parse_input_event(ev);
  364. // Don't suppress mouseover/-leave events.
  365. return false;
  366. }
  367. static const char *godot2dom_cursor(OS::CursorShape p_shape) {
  368. switch (p_shape) {
  369. case OS::CURSOR_ARROW:
  370. default:
  371. return "auto";
  372. case OS::CURSOR_IBEAM: return "text";
  373. case OS::CURSOR_POINTING_HAND: return "pointer";
  374. case OS::CURSOR_CROSS: return "crosshair";
  375. case OS::CURSOR_WAIT: return "progress";
  376. case OS::CURSOR_BUSY: return "wait";
  377. case OS::CURSOR_DRAG: return "grab";
  378. case OS::CURSOR_CAN_DROP: return "grabbing";
  379. case OS::CURSOR_FORBIDDEN: return "no-drop";
  380. case OS::CURSOR_VSIZE: return "ns-resize";
  381. case OS::CURSOR_HSIZE: return "ew-resize";
  382. case OS::CURSOR_BDIAGSIZE: return "nesw-resize";
  383. case OS::CURSOR_FDIAGSIZE: return "nwse-resize";
  384. case OS::CURSOR_MOVE: return "move";
  385. case OS::CURSOR_VSPLIT: return "row-resize";
  386. case OS::CURSOR_HSPLIT: return "col-resize";
  387. case OS::CURSOR_HELP: return "help";
  388. }
  389. }
  390. void OS_JavaScript::set_cursor_shape(CursorShape p_shape) {
  391. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  392. if (cursor_shape == p_shape) {
  393. return;
  394. }
  395. cursor_shape = p_shape;
  396. godot_js_display_cursor_set_shape(godot2dom_cursor(cursor_shape));
  397. }
  398. void OS_JavaScript::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  399. if (p_cursor.is_valid()) {
  400. Ref<Texture> texture = p_cursor;
  401. Ref<AtlasTexture> atlas_texture = p_cursor;
  402. Ref<Image> image;
  403. Size2 texture_size;
  404. Rect2 atlas_rect;
  405. if (texture.is_valid()) {
  406. image = texture->get_data();
  407. if (image.is_valid()) {
  408. image->duplicate();
  409. }
  410. }
  411. if (!image.is_valid() && atlas_texture.is_valid()) {
  412. texture = atlas_texture->get_atlas();
  413. atlas_rect.size.width = texture->get_width();
  414. atlas_rect.size.height = texture->get_height();
  415. atlas_rect.position.x = atlas_texture->get_region().position.x;
  416. atlas_rect.position.y = atlas_texture->get_region().position.y;
  417. texture_size.width = atlas_texture->get_region().size.x;
  418. texture_size.height = atlas_texture->get_region().size.y;
  419. } else if (image.is_valid()) {
  420. texture_size.width = texture->get_width();
  421. texture_size.height = texture->get_height();
  422. }
  423. ERR_FAIL_COND(!texture.is_valid());
  424. ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
  425. ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
  426. ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
  427. image = texture->get_data();
  428. ERR_FAIL_COND(!image.is_valid());
  429. image = image->duplicate();
  430. if (atlas_texture.is_valid())
  431. image->crop_from_point(
  432. atlas_rect.position.x,
  433. atlas_rect.position.y,
  434. texture_size.width,
  435. texture_size.height);
  436. if (image->get_format() != Image::FORMAT_RGBA8) {
  437. image->convert(Image::FORMAT_RGBA8);
  438. }
  439. png_image png_meta;
  440. memset(&png_meta, 0, sizeof png_meta);
  441. png_meta.version = PNG_IMAGE_VERSION;
  442. png_meta.width = texture_size.width;
  443. png_meta.height = texture_size.height;
  444. png_meta.format = PNG_FORMAT_RGBA;
  445. PoolByteArray png;
  446. size_t len;
  447. PoolByteArray::Read r = image->get_data().read();
  448. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, r.ptr(), 0, NULL));
  449. png.resize(len);
  450. PoolByteArray::Write w = png.write();
  451. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, w.ptr(), &len, 0, r.ptr(), 0, NULL));
  452. w = PoolByteArray::Write();
  453. r = png.read();
  454. godot_js_display_cursor_set_custom_shape(godot2dom_cursor(p_shape), r.ptr(), len, p_hotspot.x, p_hotspot.y);
  455. r = PoolByteArray::Read();
  456. } else {
  457. godot_js_display_cursor_set_custom_shape(godot2dom_cursor(p_shape), NULL, 0, 0, 0);
  458. }
  459. }
  460. void OS_JavaScript::set_mouse_mode(OS::MouseMode p_mode) {
  461. ERR_FAIL_COND_MSG(p_mode == MOUSE_MODE_CONFINED, "MOUSE_MODE_CONFINED is not supported for the HTML5 platform.");
  462. if (p_mode == get_mouse_mode())
  463. return;
  464. if (p_mode == MOUSE_MODE_VISIBLE) {
  465. godot_js_display_cursor_set_visible(1);
  466. emscripten_exit_pointerlock();
  467. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  468. godot_js_display_cursor_set_visible(0);
  469. emscripten_exit_pointerlock();
  470. } else if (p_mode == MOUSE_MODE_CAPTURED) {
  471. godot_js_display_cursor_set_visible(1);
  472. EMSCRIPTEN_RESULT result = emscripten_request_pointerlock(canvas_id, false);
  473. ERR_FAIL_COND_MSG(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED, "MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback.");
  474. ERR_FAIL_COND_MSG(result != EMSCRIPTEN_RESULT_SUCCESS, "MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback.");
  475. }
  476. }
  477. OS::MouseMode OS_JavaScript::get_mouse_mode() const {
  478. if (godot_js_display_cursor_is_hidden())
  479. return MOUSE_MODE_HIDDEN;
  480. EmscriptenPointerlockChangeEvent ev;
  481. emscripten_get_pointerlock_status(&ev);
  482. return (ev.isActive && String::utf8(ev.id) == String::utf8(canvas_id)) ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE;
  483. }
  484. // Wheel
  485. EM_BOOL OS_JavaScript::wheel_callback(int p_event_type, const EmscriptenWheelEvent *p_event, void *p_user_data) {
  486. ERR_FAIL_COND_V(p_event_type != EMSCRIPTEN_EVENT_WHEEL, false);
  487. OS_JavaScript *os = get_singleton();
  488. if (!godot_js_display_canvas_is_focused()) {
  489. if (os->cursor_inside_canvas) {
  490. godot_js_display_canvas_focus();
  491. } else {
  492. return false;
  493. }
  494. }
  495. InputDefault *input = os->input;
  496. Ref<InputEventMouseButton> ev;
  497. ev.instance();
  498. ev->set_position(input->get_mouse_position());
  499. ev->set_global_position(ev->get_position());
  500. ev->set_shift(input->is_key_pressed(KEY_SHIFT));
  501. ev->set_alt(input->is_key_pressed(KEY_ALT));
  502. ev->set_control(input->is_key_pressed(KEY_CONTROL));
  503. ev->set_metakey(input->is_key_pressed(KEY_META));
  504. if (p_event->deltaY < 0)
  505. ev->set_button_index(BUTTON_WHEEL_UP);
  506. else if (p_event->deltaY > 0)
  507. ev->set_button_index(BUTTON_WHEEL_DOWN);
  508. else if (p_event->deltaX > 0)
  509. ev->set_button_index(BUTTON_WHEEL_LEFT);
  510. else if (p_event->deltaX < 0)
  511. ev->set_button_index(BUTTON_WHEEL_RIGHT);
  512. else
  513. return false;
  514. // Different browsers give wildly different delta values, and we can't
  515. // interpret deltaMode, so use default value for wheel events' factor.
  516. int button_flag = 1 << (ev->get_button_index() - 1);
  517. ev->set_pressed(true);
  518. ev->set_button_mask(input->get_mouse_button_mask() | button_flag);
  519. input->parse_input_event(ev);
  520. ev->set_pressed(false);
  521. ev->set_button_mask(input->get_mouse_button_mask() & ~button_flag);
  522. input->parse_input_event(ev);
  523. return true;
  524. }
  525. // Touch
  526. bool OS_JavaScript::has_touchscreen_ui_hint() const {
  527. return godot_js_display_touchscreen_is_available();
  528. }
  529. EM_BOOL OS_JavaScript::touch_press_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  530. OS_JavaScript *os = get_singleton();
  531. Ref<InputEventScreenTouch> ev;
  532. ev.instance();
  533. int lowest_id_index = -1;
  534. for (int i = 0; i < p_event->numTouches; ++i) {
  535. const EmscriptenTouchPoint &touch = p_event->touches[i];
  536. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  537. lowest_id_index = i;
  538. if (!touch.isChanged)
  539. continue;
  540. ev->set_index(touch.identifier);
  541. ev->set_position(compute_position_in_canvas(touch.clientX, touch.clientY));
  542. os->touches[i] = ev->get_position();
  543. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_TOUCHSTART);
  544. os->input->parse_input_event(ev);
  545. }
  546. // Resume audio context after input in case autoplay was denied.
  547. os->resume_audio();
  548. return true;
  549. }
  550. EM_BOOL OS_JavaScript::touchmove_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  551. OS_JavaScript *os = get_singleton();
  552. Ref<InputEventScreenDrag> ev;
  553. ev.instance();
  554. int lowest_id_index = -1;
  555. for (int i = 0; i < p_event->numTouches; ++i) {
  556. const EmscriptenTouchPoint &touch = p_event->touches[i];
  557. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  558. lowest_id_index = i;
  559. if (!touch.isChanged)
  560. continue;
  561. ev->set_index(touch.identifier);
  562. ev->set_position(compute_position_in_canvas(touch.clientX, touch.clientY));
  563. Point2 &prev = os->touches[i];
  564. ev->set_relative(ev->get_position() - prev);
  565. prev = ev->get_position();
  566. os->input->parse_input_event(ev);
  567. }
  568. return true;
  569. }
  570. // Gamepad
  571. EM_BOOL OS_JavaScript::gamepad_change_callback(int p_event_type, const EmscriptenGamepadEvent *p_event, void *p_user_data) {
  572. InputDefault *input = get_singleton()->input;
  573. if (p_event_type == EMSCRIPTEN_EVENT_GAMEPADCONNECTED) {
  574. String guid = "";
  575. if (String::utf8(p_event->mapping) == "standard")
  576. guid = "Default HTML5 Gamepad";
  577. input->joy_connection_changed(p_event->index, true, String::utf8(p_event->id), guid);
  578. } else {
  579. input->joy_connection_changed(p_event->index, false, "");
  580. }
  581. return true;
  582. }
  583. void OS_JavaScript::process_joypads() {
  584. int joypad_count = emscripten_get_num_gamepads();
  585. for (int joypad = 0; joypad < joypad_count; joypad++) {
  586. EmscriptenGamepadEvent state;
  587. EMSCRIPTEN_RESULT query_result = emscripten_get_gamepad_status(joypad, &state);
  588. // Chromium reserves gamepads slots, so NO_DATA is an expected result.
  589. ERR_CONTINUE(query_result != EMSCRIPTEN_RESULT_SUCCESS &&
  590. query_result != EMSCRIPTEN_RESULT_NO_DATA);
  591. if (query_result == EMSCRIPTEN_RESULT_SUCCESS && state.connected) {
  592. int button_count = MIN(state.numButtons, 18);
  593. int axis_count = MIN(state.numAxes, 8);
  594. for (int button = 0; button < button_count; button++) {
  595. float value = state.analogButton[button];
  596. if (String::utf8(state.mapping) == "standard" && (button == JOY_ANALOG_L2 || button == JOY_ANALOG_R2)) {
  597. InputDefault::JoyAxis joy_axis;
  598. joy_axis.min = 0;
  599. joy_axis.value = value;
  600. input->joy_axis(joypad, button, joy_axis);
  601. } else {
  602. input->joy_button(joypad, button, value);
  603. }
  604. }
  605. for (int axis = 0; axis < axis_count; axis++) {
  606. InputDefault::JoyAxis joy_axis;
  607. joy_axis.min = -1;
  608. joy_axis.value = state.axis[axis];
  609. input->joy_axis(joypad, axis, joy_axis);
  610. }
  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. FileAccess::make_default<FileAccessBufferedFA<FileAccessUnix> >(FileAccess::ACCESS_RESOURCES);
  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. #ifdef JAVASCRIPT_EVAL_ENABLED
  873. if (p_feature == "JavaScript")
  874. return true;
  875. #endif
  876. return false;
  877. }
  878. void OS_JavaScript::alert(const String &p_alert, const String &p_title) {
  879. godot_js_display_alert(p_alert.utf8().get_data());
  880. }
  881. void OS_JavaScript::set_window_title(const String &p_title) {
  882. godot_js_display_window_title_set(p_title.utf8().get_data());
  883. }
  884. void OS_JavaScript::set_icon(const Ref<Image> &p_icon) {
  885. ERR_FAIL_COND(p_icon.is_null());
  886. Ref<Image> icon = p_icon;
  887. if (icon->is_compressed()) {
  888. icon = icon->duplicate();
  889. ERR_FAIL_COND(icon->decompress() != OK);
  890. }
  891. if (icon->get_format() != Image::FORMAT_RGBA8) {
  892. if (icon == p_icon)
  893. icon = icon->duplicate();
  894. icon->convert(Image::FORMAT_RGBA8);
  895. }
  896. png_image png_meta;
  897. memset(&png_meta, 0, sizeof png_meta);
  898. png_meta.version = PNG_IMAGE_VERSION;
  899. png_meta.width = icon->get_width();
  900. png_meta.height = icon->get_height();
  901. png_meta.format = PNG_FORMAT_RGBA;
  902. PoolByteArray png;
  903. size_t len;
  904. PoolByteArray::Read r = icon->get_data().read();
  905. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, r.ptr(), 0, NULL));
  906. png.resize(len);
  907. PoolByteArray::Write w = png.write();
  908. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, w.ptr(), &len, 0, r.ptr(), 0, NULL));
  909. w = PoolByteArray::Write();
  910. r = png.read();
  911. godot_js_display_window_icon_set(r.ptr(), len);
  912. }
  913. String OS_JavaScript::get_executable_path() const {
  914. return OS::get_executable_path();
  915. }
  916. Error OS_JavaScript::shell_open(String p_uri) {
  917. // Open URI in a new tab, browser will deal with it by protocol.
  918. godot_js_os_shell_open(p_uri.utf8().get_data());
  919. return OK;
  920. }
  921. String OS_JavaScript::get_name() const {
  922. return "HTML5";
  923. }
  924. bool OS_JavaScript::can_draw() const {
  925. return true; // Always?
  926. }
  927. String OS_JavaScript::get_user_data_dir() const {
  928. return "/userfs";
  929. };
  930. String OS_JavaScript::get_cache_path() const {
  931. return "/home/web_user/.cache";
  932. }
  933. String OS_JavaScript::get_config_path() const {
  934. return "/home/web_user/.config";
  935. }
  936. String OS_JavaScript::get_data_path() const {
  937. return "/home/web_user/.local/share";
  938. }
  939. OS::PowerState OS_JavaScript::get_power_state() {
  940. WARN_PRINT_ONCE("Power management is not supported for the HTML5 platform, defaulting to POWERSTATE_UNKNOWN");
  941. return OS::POWERSTATE_UNKNOWN;
  942. }
  943. int OS_JavaScript::get_power_seconds_left() {
  944. WARN_PRINT_ONCE("Power management is not supported for the HTML5 platform, defaulting to -1");
  945. return -1;
  946. }
  947. int OS_JavaScript::get_power_percent_left() {
  948. WARN_PRINT_ONCE("Power management is not supported for the HTML5 platform, defaulting to -1");
  949. return -1;
  950. }
  951. void OS_JavaScript::file_access_close_callback(const String &p_file, int p_flags) {
  952. OS_JavaScript *os = get_singleton();
  953. if (!(os->is_userfs_persistent() && p_flags & FileAccess::WRITE)) {
  954. return; // FS persistence is not working or we are not writing.
  955. }
  956. bool is_file_persistent = p_file.begins_with("/userfs");
  957. #ifdef TOOLS_ENABLED
  958. // Hack for editor persistence (can we track).
  959. is_file_persistent = is_file_persistent || p_file.begins_with("/home/web_user/");
  960. #endif
  961. if (is_file_persistent) {
  962. os->idb_needs_sync = true;
  963. }
  964. }
  965. bool OS_JavaScript::is_userfs_persistent() const {
  966. return idb_available;
  967. }
  968. OS_JavaScript *OS_JavaScript::get_singleton() {
  969. return static_cast<OS_JavaScript *>(OS::get_singleton());
  970. }
  971. OS_JavaScript::OS_JavaScript() {
  972. // Expose method for requesting quit.
  973. godot_js_os_request_quit_cb(&request_quit_callback);
  974. // Set canvas ID
  975. godot_js_config_canvas_id_get(canvas_id, sizeof(canvas_id));
  976. cursor_inside_canvas = true;
  977. cursor_shape = OS::CURSOR_ARROW;
  978. last_click_button_index = -1;
  979. last_click_ms = 0;
  980. last_click_pos = Point2(-100, -100);
  981. last_width = 0;
  982. last_height = 0;
  983. window_maximized = false;
  984. entering_fullscreen = false;
  985. just_exited_fullscreen = false;
  986. transparency_enabled = false;
  987. main_loop = NULL;
  988. visual_server = NULL;
  989. audio_driver_javascript = NULL;
  990. swap_ok_cancel = false;
  991. idb_available = godot_js_os_fs_is_persistent() != 0;
  992. idb_needs_sync = false;
  993. idb_is_syncing = false;
  994. if (AudioDriverJavaScript::is_available()) {
  995. audio_driver_javascript = memnew(AudioDriverJavaScript);
  996. AudioDriverManager::add_driver(audio_driver_javascript);
  997. }
  998. Vector<Logger *> loggers;
  999. loggers.push_back(memnew(StdLogger));
  1000. _set_logger(memnew(CompositeLogger(loggers)));
  1001. FileAccessUnix::close_notification_func = file_access_close_callback;
  1002. }