os_javascript.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  1. /**************************************************************************/
  2. /* os_javascript.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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 "core/project_settings.h"
  33. #include "drivers/gles2/rasterizer_gles2.h"
  34. #include "drivers/gles3/rasterizer_gles3.h"
  35. #include "drivers/unix/dir_access_unix.h"
  36. #include "drivers/unix/file_access_unix.h"
  37. #include "main/main.h"
  38. #include "servers/visual/visual_server_raster.h"
  39. #ifndef NO_THREADS
  40. #include "servers/visual/visual_server_wrap_mt.h"
  41. #endif
  42. #include <dlfcn.h>
  43. #include <emscripten.h>
  44. #include <png.h>
  45. #include <stdlib.h>
  46. #include "api/javascript_singleton.h"
  47. #include "dom_keys.inc"
  48. #include "godot_js.h"
  49. #define DOM_BUTTON_LEFT 0
  50. #define DOM_BUTTON_MIDDLE 1
  51. #define DOM_BUTTON_RIGHT 2
  52. #define DOM_BUTTON_XBUTTON1 3
  53. #define DOM_BUTTON_XBUTTON2 4
  54. // Quit
  55. void OS_JavaScript::request_quit_callback() {
  56. OS_JavaScript *os = get_singleton();
  57. if (os && os->get_main_loop()) {
  58. os->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
  59. }
  60. }
  61. bool OS_JavaScript::tts_is_speaking() const {
  62. ERR_FAIL_COND_V_MSG(!tts, false, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
  63. return godot_js_tts_is_speaking();
  64. }
  65. bool OS_JavaScript::tts_is_paused() const {
  66. ERR_FAIL_COND_V_MSG(!tts, false, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
  67. return godot_js_tts_is_paused();
  68. }
  69. void OS_JavaScript::update_voices_callback(int p_size, const char **p_voice) {
  70. get_singleton()->voices.clear();
  71. for (int i = 0; i < p_size; i++) {
  72. Vector<String> tokens = String::utf8(p_voice[i]).split(";", true, 2);
  73. if (tokens.size() == 2) {
  74. Dictionary voice_d;
  75. voice_d["name"] = tokens[1];
  76. voice_d["id"] = tokens[1];
  77. voice_d["language"] = tokens[0];
  78. get_singleton()->voices.push_back(voice_d);
  79. }
  80. }
  81. }
  82. Array OS_JavaScript::tts_get_voices() const {
  83. ERR_FAIL_COND_V_MSG(!tts, Array(), "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
  84. godot_js_tts_get_voices(update_voices_callback);
  85. return voices;
  86. }
  87. void OS_JavaScript::tts_speak(const String &p_text, const String &p_voice, int p_volume, float p_pitch, float p_rate, int p_utterance_id, bool p_interrupt) {
  88. ERR_FAIL_COND_MSG(!tts, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
  89. if (p_interrupt) {
  90. tts_stop();
  91. }
  92. if (p_text.empty()) {
  93. tts_post_utterance_event(OS::TTS_UTTERANCE_CANCELED, p_utterance_id);
  94. return;
  95. }
  96. CharString string = p_text.utf8();
  97. utterance_ids[p_utterance_id] = string;
  98. godot_js_tts_speak(string.get_data(), p_voice.utf8().get_data(), CLAMP(p_volume, 0, 100), CLAMP(p_pitch, 0.f, 2.f), CLAMP(p_rate, 0.1f, 10.f), p_utterance_id, OS_JavaScript::_js_utterance_callback);
  99. }
  100. void OS_JavaScript::tts_pause() {
  101. ERR_FAIL_COND_MSG(!tts, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
  102. godot_js_tts_pause();
  103. }
  104. void OS_JavaScript::tts_resume() {
  105. ERR_FAIL_COND_MSG(!tts, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
  106. godot_js_tts_resume();
  107. }
  108. void OS_JavaScript::tts_stop() {
  109. ERR_FAIL_COND_MSG(!tts, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
  110. for (Map<int, CharString>::Element *E = utterance_ids.front(); E; E = E->next()) {
  111. tts_post_utterance_event(OS::TTS_UTTERANCE_CANCELED, E->key());
  112. }
  113. utterance_ids.clear();
  114. godot_js_tts_stop();
  115. }
  116. void OS_JavaScript::_js_utterance_callback(int p_event, int p_id, int p_pos) {
  117. OS_JavaScript *ds = (OS_JavaScript *)OS::get_singleton();
  118. if (ds->utterance_ids.has(p_id)) {
  119. int pos = 0;
  120. if ((TTSUtteranceEvent)p_event == OS::TTS_UTTERANCE_BOUNDARY) {
  121. // Convert position from UTF-8 to UTF-32.
  122. const CharString &string = ds->utterance_ids[p_id];
  123. for (int i = 0; i < MIN(p_pos, string.length()); i++) {
  124. uint8_t c = string[i];
  125. if ((c & 0xe0) == 0xc0) {
  126. i += 1;
  127. } else if ((c & 0xf0) == 0xe0) {
  128. i += 2;
  129. } else if ((c & 0xf8) == 0xf0) {
  130. i += 3;
  131. }
  132. pos++;
  133. }
  134. } else if ((TTSUtteranceEvent)p_event != OS::TTS_UTTERANCE_STARTED) {
  135. ds->utterance_ids.erase(p_id);
  136. }
  137. ds->tts_post_utterance_event((TTSUtteranceEvent)p_event, p_id, pos);
  138. }
  139. }
  140. // Files drop (implemented in JS for now).
  141. void OS_JavaScript::drop_files_callback(char **p_filev, int p_filec) {
  142. OS_JavaScript *os = get_singleton();
  143. if (!os || !os->get_main_loop()) {
  144. return;
  145. }
  146. Vector<String> files;
  147. for (int i = 0; i < p_filec; i++) {
  148. files.push_back(String::utf8(p_filev[i]));
  149. }
  150. os->get_main_loop()->drop_files(files);
  151. }
  152. void OS_JavaScript::send_notification_callback(int p_notification) {
  153. OS_JavaScript *os = get_singleton();
  154. if (!os) {
  155. return;
  156. }
  157. if (p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER || p_notification == MainLoop::NOTIFICATION_WM_MOUSE_EXIT) {
  158. os->cursor_inside_canvas = p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER;
  159. }
  160. if (godot_js_is_ime_focused() && (p_notification == MainLoop::NOTIFICATION_WM_FOCUS_IN || p_notification == MainLoop::NOTIFICATION_WM_FOCUS_OUT)) {
  161. return;
  162. }
  163. MainLoop *loop = os->get_main_loop();
  164. if (loop) {
  165. loop->notification(p_notification);
  166. }
  167. }
  168. // Window (canvas)
  169. bool OS_JavaScript::check_size_force_redraw() {
  170. return godot_js_display_size_update() != 0;
  171. }
  172. void OS_JavaScript::fullscreen_change_callback(int p_fullscreen) {
  173. OS_JavaScript *os = get_singleton();
  174. os->video_mode.fullscreen = p_fullscreen;
  175. }
  176. void OS_JavaScript::window_blur_callback() {
  177. get_singleton()->input->release_pressed_events();
  178. }
  179. void OS_JavaScript::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  180. video_mode = p_video_mode;
  181. }
  182. OS::VideoMode OS_JavaScript::get_video_mode(int p_screen) const {
  183. return video_mode;
  184. }
  185. Size2 OS_JavaScript::get_screen_size(int p_screen) const {
  186. int size[2];
  187. godot_js_display_screen_size_get(size, size + 1);
  188. return Size2(size[0], size[1]);
  189. }
  190. void OS_JavaScript::set_window_size(const Size2 p_size) {
  191. if (video_mode.fullscreen) {
  192. set_window_fullscreen(false);
  193. }
  194. godot_js_display_desired_size_set(p_size.x, p_size.y);
  195. }
  196. Size2 OS_JavaScript::get_window_size() const {
  197. int size[2];
  198. godot_js_display_window_size_get(size, size + 1);
  199. return Size2(size[0], size[1]);
  200. }
  201. void OS_JavaScript::set_window_maximized(bool p_enabled) {
  202. }
  203. bool OS_JavaScript::is_window_maximized() const {
  204. return false;
  205. }
  206. void OS_JavaScript::set_window_fullscreen(bool p_enabled) {
  207. if (p_enabled == video_mode.fullscreen) {
  208. return;
  209. }
  210. // Just request changes here, if successful, logic continues in
  211. // fullscreen_change_callback.
  212. if (p_enabled) {
  213. int result = godot_js_display_fullscreen_request();
  214. ERR_FAIL_COND_MSG(result, "The request was denied. Remember that enabling fullscreen is only possible from an input callback for the HTML5 platform.");
  215. } else {
  216. // No logic allowed here, since exiting w/ ESC key won't use this function.
  217. ERR_FAIL_COND(godot_js_display_fullscreen_exit());
  218. }
  219. }
  220. bool OS_JavaScript::is_window_fullscreen() const {
  221. return video_mode.fullscreen;
  222. }
  223. void OS_JavaScript::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  224. Size2 screen = get_screen_size();
  225. p_list->push_back(OS::VideoMode(screen.width, screen.height, true));
  226. }
  227. bool OS_JavaScript::get_window_per_pixel_transparency_enabled() const {
  228. if (!is_layered_allowed()) {
  229. return false;
  230. }
  231. return transparency_enabled;
  232. }
  233. void OS_JavaScript::set_window_per_pixel_transparency_enabled(bool p_enabled) {
  234. if (!is_layered_allowed()) {
  235. return;
  236. }
  237. transparency_enabled = p_enabled;
  238. }
  239. // Keys
  240. static void dom2godot_mod(Ref<InputEventWithModifiers> ev, int p_mod) {
  241. ev->set_shift(p_mod & 1);
  242. ev->set_alt(p_mod & 2);
  243. ev->set_control(p_mod & 4);
  244. ev->set_metakey(p_mod & 8);
  245. }
  246. void OS_JavaScript::key_callback(int p_pressed, int p_repeat, int p_modifiers) {
  247. OS_JavaScript *os = get_singleton();
  248. JSKeyEvent &key_event = os->key_event;
  249. const String code = String::utf8(key_event.code);
  250. const String key = String::utf8(key_event.key);
  251. // Resume audio context after input in case autoplay was denied.
  252. os->resume_audio();
  253. if (os->ime_started) {
  254. return;
  255. }
  256. wchar_t c = 0x00;
  257. String unicode = key;
  258. if (unicode.length() == 1) {
  259. c = unicode[0];
  260. }
  261. uint32_t keycode = dom_code2godot_scancode(code.utf8().get_data(), key.utf8().get_data(), false);
  262. uint32_t scancode = dom_code2godot_scancode(code.utf8().get_data(), key.utf8().get_data(), true);
  263. OS_JavaScript::KeyEvent ke;
  264. ke.pressed = p_pressed;
  265. ke.echo = p_repeat;
  266. ke.raw = true;
  267. ke.keycode = keycode;
  268. ke.physical_keycode = scancode;
  269. ke.unicode = c;
  270. ke.mod = p_modifiers;
  271. if (os->key_event_pos >= os->key_event_buffer.size()) {
  272. os->key_event_buffer.resize(1 + os->key_event_pos);
  273. }
  274. os->key_event_buffer.write[os->key_event_pos++] = ke;
  275. // Make sure to flush all events so we can call restricted APIs inside the event.
  276. os->input->flush_buffered_events();
  277. }
  278. // Mouse
  279. Point2 OS_JavaScript::get_mouse_position() const {
  280. return input->get_mouse_position();
  281. }
  282. int OS_JavaScript::get_mouse_button_state() const {
  283. return input->get_mouse_button_mask();
  284. }
  285. int OS_JavaScript::mouse_button_callback(int p_pressed, int p_button, double p_x, double p_y, int p_modifiers) {
  286. OS_JavaScript *os = get_singleton();
  287. Ref<InputEventMouseButton> ev;
  288. ev.instance();
  289. ev->set_pressed(p_pressed);
  290. ev->set_position(Point2(p_x, p_y));
  291. ev->set_global_position(ev->get_position());
  292. ev->set_pressed(p_pressed);
  293. dom2godot_mod(ev, p_modifiers);
  294. switch (p_button) {
  295. case DOM_BUTTON_LEFT:
  296. ev->set_button_index(BUTTON_LEFT);
  297. break;
  298. case DOM_BUTTON_MIDDLE:
  299. ev->set_button_index(BUTTON_MIDDLE);
  300. break;
  301. case DOM_BUTTON_RIGHT:
  302. ev->set_button_index(BUTTON_RIGHT);
  303. break;
  304. case DOM_BUTTON_XBUTTON1:
  305. ev->set_button_index(BUTTON_XBUTTON1);
  306. break;
  307. case DOM_BUTTON_XBUTTON2:
  308. ev->set_button_index(BUTTON_XBUTTON2);
  309. break;
  310. default:
  311. return false;
  312. }
  313. if (p_pressed) {
  314. uint64_t diff = (OS::get_singleton()->get_ticks_usec() / 1000) - os->last_click_ms;
  315. if (ev->get_button_index() == os->last_click_button_index) {
  316. if (diff < 400 && Point2(os->last_click_pos).distance_to(ev->get_position()) < 5) {
  317. os->last_click_ms = 0;
  318. os->last_click_pos = Point2(-100, -100);
  319. os->last_click_button_index = -1;
  320. ev->set_doubleclick(true);
  321. }
  322. } else {
  323. os->last_click_button_index = ev->get_button_index();
  324. }
  325. if (!ev->is_doubleclick()) {
  326. os->last_click_ms += diff;
  327. os->last_click_pos = ev->get_position();
  328. }
  329. }
  330. int mask = os->input->get_mouse_button_mask();
  331. int button_flag = 1 << (ev->get_button_index() - 1);
  332. if (ev->is_pressed()) {
  333. mask |= button_flag;
  334. } else if (mask & button_flag) {
  335. mask &= ~button_flag;
  336. } else {
  337. // Received release event, but press was outside the canvas, so ignore.
  338. return false;
  339. }
  340. ev->set_button_mask(mask);
  341. os->input->parse_input_event(ev);
  342. // Resume audio context after input in case autoplay was denied.
  343. os->resume_audio();
  344. // Make sure to flush all events so we can call restricted APIs inside the event.
  345. os->input->flush_buffered_events();
  346. // Prevent multi-click text selection and wheel-click scrolling anchor.
  347. // Context menu is prevented through contextmenu event.
  348. return true;
  349. }
  350. void OS_JavaScript::mouse_move_callback(double p_x, double p_y, double p_rel_x, double p_rel_y, int p_modifiers) {
  351. OS_JavaScript *os = get_singleton();
  352. int input_mask = os->input->get_mouse_button_mask();
  353. // For motion outside the canvas, only read mouse movement if dragging
  354. // started inside the canvas; imitating desktop app behaviour.
  355. if (!os->cursor_inside_canvas && !input_mask)
  356. return;
  357. Ref<InputEventMouseMotion> ev;
  358. ev.instance();
  359. dom2godot_mod(ev, p_modifiers);
  360. ev->set_button_mask(input_mask);
  361. ev->set_position(Point2(p_x, p_y));
  362. ev->set_global_position(ev->get_position());
  363. ev->set_relative(Vector2(p_rel_x, p_rel_y));
  364. ev->set_speed(os->input->get_last_mouse_speed());
  365. os->input->parse_input_event(ev);
  366. }
  367. static const char *godot2dom_cursor(OS::CursorShape p_shape) {
  368. switch (p_shape) {
  369. case OS::CURSOR_ARROW:
  370. default:
  371. return "default";
  372. case OS::CURSOR_IBEAM:
  373. return "text";
  374. case OS::CURSOR_POINTING_HAND:
  375. return "pointer";
  376. case OS::CURSOR_CROSS:
  377. return "crosshair";
  378. case OS::CURSOR_WAIT:
  379. return "wait";
  380. case OS::CURSOR_BUSY:
  381. return "progress";
  382. case OS::CURSOR_DRAG:
  383. return "grab";
  384. case OS::CURSOR_CAN_DROP:
  385. return "grabbing";
  386. case OS::CURSOR_FORBIDDEN:
  387. return "no-drop";
  388. case OS::CURSOR_VSIZE:
  389. return "ns-resize";
  390. case OS::CURSOR_HSIZE:
  391. return "ew-resize";
  392. case OS::CURSOR_BDIAGSIZE:
  393. return "nesw-resize";
  394. case OS::CURSOR_FDIAGSIZE:
  395. return "nwse-resize";
  396. case OS::CURSOR_MOVE:
  397. return "move";
  398. case OS::CURSOR_VSPLIT:
  399. return "row-resize";
  400. case OS::CURSOR_HSPLIT:
  401. return "col-resize";
  402. case OS::CURSOR_HELP:
  403. return "help";
  404. }
  405. }
  406. void OS_JavaScript::set_cursor_shape(CursorShape p_shape) {
  407. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  408. if (cursor_shape == p_shape) {
  409. return;
  410. }
  411. cursor_shape = p_shape;
  412. godot_js_display_cursor_set_shape(godot2dom_cursor(cursor_shape));
  413. }
  414. OS::CursorShape OS_JavaScript::get_cursor_shape() const {
  415. return cursor_shape;
  416. }
  417. void OS_JavaScript::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  418. if (p_cursor.is_valid()) {
  419. Ref<Texture> texture = p_cursor;
  420. Ref<AtlasTexture> atlas_texture = p_cursor;
  421. Ref<Image> image;
  422. Size2 texture_size;
  423. Rect2 atlas_rect;
  424. if (texture.is_valid()) {
  425. image = texture->get_data();
  426. if (image.is_valid()) {
  427. image->duplicate();
  428. }
  429. }
  430. if (!image.is_valid() && atlas_texture.is_valid()) {
  431. texture = atlas_texture->get_atlas();
  432. atlas_rect.size.width = texture->get_width();
  433. atlas_rect.size.height = texture->get_height();
  434. atlas_rect.position.x = atlas_texture->get_region().position.x;
  435. atlas_rect.position.y = atlas_texture->get_region().position.y;
  436. texture_size.width = atlas_texture->get_region().size.x;
  437. texture_size.height = atlas_texture->get_region().size.y;
  438. } else if (image.is_valid()) {
  439. texture_size.width = texture->get_width();
  440. texture_size.height = texture->get_height();
  441. }
  442. ERR_FAIL_COND(!texture.is_valid());
  443. ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
  444. ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
  445. ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
  446. image = texture->get_data();
  447. ERR_FAIL_COND(!image.is_valid());
  448. image = image->duplicate();
  449. if (atlas_texture.is_valid())
  450. image->crop_from_point(
  451. atlas_rect.position.x,
  452. atlas_rect.position.y,
  453. texture_size.width,
  454. texture_size.height);
  455. if (image->get_format() != Image::FORMAT_RGBA8) {
  456. image->convert(Image::FORMAT_RGBA8);
  457. }
  458. png_image png_meta;
  459. memset(&png_meta, 0, sizeof png_meta);
  460. png_meta.version = PNG_IMAGE_VERSION;
  461. png_meta.width = texture_size.width;
  462. png_meta.height = texture_size.height;
  463. png_meta.format = PNG_FORMAT_RGBA;
  464. PoolByteArray png;
  465. size_t len;
  466. PoolByteArray::Read r = image->get_data().read();
  467. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, r.ptr(), 0, NULL));
  468. png.resize(len);
  469. PoolByteArray::Write w = png.write();
  470. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, w.ptr(), &len, 0, r.ptr(), 0, NULL));
  471. w = PoolByteArray::Write();
  472. r = png.read();
  473. godot_js_display_cursor_set_custom_shape(godot2dom_cursor(p_shape), r.ptr(), len, p_hotspot.x, p_hotspot.y);
  474. r = PoolByteArray::Read();
  475. } else {
  476. godot_js_display_cursor_set_custom_shape(godot2dom_cursor(p_shape), NULL, 0, 0, 0);
  477. }
  478. }
  479. void OS_JavaScript::set_mouse_mode(OS::MouseMode p_mode) {
  480. ERR_FAIL_COND_MSG(p_mode == MOUSE_MODE_CONFINED || p_mode == MOUSE_MODE_CONFINED_HIDDEN, "MOUSE_MODE_CONFINED is not supported for the HTML5 platform.");
  481. if (p_mode == get_mouse_mode()) {
  482. return;
  483. }
  484. if (p_mode == MOUSE_MODE_VISIBLE) {
  485. godot_js_display_cursor_set_visible(1);
  486. godot_js_display_cursor_lock_set(false);
  487. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  488. godot_js_display_cursor_set_visible(0);
  489. godot_js_display_cursor_lock_set(false);
  490. } else if (p_mode == MOUSE_MODE_CAPTURED) {
  491. godot_js_display_cursor_set_visible(1);
  492. godot_js_display_cursor_lock_set(true);
  493. }
  494. }
  495. OS::MouseMode OS_JavaScript::get_mouse_mode() const {
  496. if (godot_js_display_cursor_is_hidden()) {
  497. return MOUSE_MODE_HIDDEN;
  498. }
  499. if (godot_js_display_cursor_is_locked()) {
  500. return MOUSE_MODE_CAPTURED;
  501. }
  502. return MOUSE_MODE_VISIBLE;
  503. }
  504. // Wheel
  505. int OS_JavaScript::mouse_wheel_callback(double p_delta_x, double p_delta_y) {
  506. OS_JavaScript *os = get_singleton();
  507. if (!godot_js_display_canvas_is_focused() && !godot_js_is_ime_focused()) {
  508. if (os->cursor_inside_canvas) {
  509. godot_js_display_canvas_focus();
  510. } else {
  511. return false;
  512. }
  513. }
  514. InputDefault *input = os->input;
  515. Ref<InputEventMouseButton> ev;
  516. ev.instance();
  517. ev->set_position(input->get_mouse_position());
  518. ev->set_global_position(ev->get_position());
  519. ev->set_shift(input->is_key_pressed(KEY_SHIFT));
  520. ev->set_alt(input->is_key_pressed(KEY_ALT));
  521. ev->set_control(input->is_key_pressed(KEY_CONTROL));
  522. ev->set_metakey(input->is_key_pressed(KEY_META));
  523. if (p_delta_y < 0) {
  524. ev->set_button_index(BUTTON_WHEEL_UP);
  525. } else if (p_delta_y > 0) {
  526. ev->set_button_index(BUTTON_WHEEL_DOWN);
  527. } else if (p_delta_x > 0) {
  528. ev->set_button_index(BUTTON_WHEEL_LEFT);
  529. } else if (p_delta_x < 0) {
  530. ev->set_button_index(BUTTON_WHEEL_RIGHT);
  531. } else {
  532. return false;
  533. }
  534. // Different browsers give wildly different delta values, and we can't
  535. // interpret deltaMode, so use default value for wheel events' factor.
  536. int button_flag = 1 << (ev->get_button_index() - 1);
  537. ev->set_pressed(true);
  538. ev->set_button_mask(input->get_mouse_button_mask() | button_flag);
  539. input->parse_input_event(ev);
  540. Ref<InputEventMouseButton> release = ev->duplicate();
  541. release->set_pressed(false);
  542. release->set_button_mask(input->get_mouse_button_mask() & ~button_flag);
  543. input->parse_input_event(release);
  544. return true;
  545. }
  546. // Touch
  547. bool OS_JavaScript::has_touchscreen_ui_hint() const {
  548. return godot_js_display_touchscreen_is_available();
  549. }
  550. void OS_JavaScript::touch_callback(int p_type, int p_count) {
  551. OS_JavaScript *os = get_singleton();
  552. // Resume audio context after input in case autoplay was denied.
  553. os->resume_audio();
  554. const JSTouchEvent &touch_event = os->touch_event;
  555. for (int i = 0; i < p_count; i++) {
  556. Point2 point(touch_event.coords[i * 2], touch_event.coords[i * 2 + 1]);
  557. if (p_type == 2) {
  558. // touchmove
  559. Ref<InputEventScreenDrag> ev;
  560. ev.instance();
  561. ev->set_index(touch_event.identifier[i]);
  562. ev->set_position(point);
  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. } else {
  568. // touchstart/touchend
  569. Ref<InputEventScreenTouch> ev;
  570. ev.instance();
  571. ev->set_index(touch_event.identifier[i]);
  572. ev->set_position(point);
  573. ev->set_pressed(p_type == 0);
  574. os->touches[i] = point;
  575. os->input->parse_input_event(ev);
  576. // Make sure to flush all events so we can call restricted APIs inside the event.
  577. os->input->flush_buffered_events();
  578. }
  579. }
  580. }
  581. // IME.
  582. void OS_JavaScript::ime_callback(int p_type, const char *p_text) {
  583. OS_JavaScript *os = get_singleton();
  584. // Resume audio context after input in case autoplay was denied.
  585. os->resume_audio();
  586. switch (p_type) {
  587. case 0: {
  588. // IME start.
  589. os->ime_text = String();
  590. os->ime_selection = Vector2i();
  591. for (int i = os->key_event_pos - 1; i >= 0; i--) {
  592. // Delete last raw keydown event from query.
  593. if (os->key_event_buffer[i].pressed && os->key_event_buffer[i].raw) {
  594. os->key_event_buffer.remove(i);
  595. os->key_event_pos--;
  596. break;
  597. }
  598. }
  599. os->get_main_loop()->notification(MainLoop::NOTIFICATION_OS_IME_UPDATE);
  600. os->ime_started = true;
  601. } break;
  602. case 1: {
  603. // IME update.
  604. if (os->ime_active && os->ime_started) {
  605. os->ime_text = String::utf8(p_text);
  606. os->ime_selection = Vector2i(os->ime_text.length(), os->ime_text.length());
  607. os->get_main_loop()->notification(MainLoop::NOTIFICATION_OS_IME_UPDATE);
  608. }
  609. } break;
  610. case 2: {
  611. // IME commit.
  612. if (os->ime_active && os->ime_started) {
  613. os->ime_started = false;
  614. os->ime_text = String();
  615. os->ime_selection = Vector2i();
  616. os->get_main_loop()->notification(MainLoop::NOTIFICATION_OS_IME_UPDATE);
  617. String text = String::utf8(p_text);
  618. for (int i = 0; i < text.length(); i++) {
  619. OS_JavaScript::KeyEvent ke;
  620. ke.pressed = true;
  621. ke.echo = false;
  622. ke.raw = false;
  623. ke.keycode = 0;
  624. ke.physical_keycode = 0;
  625. ke.unicode = text[i];
  626. ke.mod = 0;
  627. if (os->key_event_pos >= os->key_event_buffer.size()) {
  628. os->key_event_buffer.resize(1 + os->key_event_pos);
  629. }
  630. os->key_event_buffer.write[os->key_event_pos++] = ke;
  631. }
  632. }
  633. } break;
  634. default:
  635. break;
  636. }
  637. os->process_keys();
  638. os->input->flush_buffered_events();
  639. }
  640. void OS_JavaScript::set_ime_active(const bool p_active) {
  641. ime_active = p_active;
  642. godot_js_set_ime_active(p_active);
  643. }
  644. void OS_JavaScript::set_ime_position(const Point2 &p_pos) {
  645. godot_js_set_ime_position(p_pos.x, p_pos.y);
  646. }
  647. Point2 OS_JavaScript::get_ime_selection() const {
  648. return ime_selection;
  649. }
  650. String OS_JavaScript::get_ime_text() const {
  651. return ime_text;
  652. }
  653. // Gamepad
  654. void OS_JavaScript::gamepad_callback(int p_index, int p_connected, const char *p_id, const char *p_guid) {
  655. InputDefault *input = get_singleton()->input;
  656. if (p_connected) {
  657. input->joy_connection_changed(p_index, true, String::utf8(p_id), String::utf8(p_guid));
  658. } else {
  659. input->joy_connection_changed(p_index, false, "");
  660. }
  661. }
  662. void OS_JavaScript::process_joypads() {
  663. int32_t pads = godot_js_input_gamepad_sample_count();
  664. int32_t s_btns_num = 0;
  665. int32_t s_axes_num = 0;
  666. int32_t s_standard = 0;
  667. float s_btns[16];
  668. float s_axes[10];
  669. for (int idx = 0; idx < pads; idx++) {
  670. int err = godot_js_input_gamepad_sample_get(idx, s_btns, &s_btns_num, s_axes, &s_axes_num, &s_standard);
  671. if (err) {
  672. continue;
  673. }
  674. for (int b = 0; b < s_btns_num; b++) {
  675. // Buttons 6 and 7 in the standard mapping need to be
  676. // axis to be handled as JOY_ANALOG by Godot.
  677. if (s_standard && (b == 6 || b == 7)) {
  678. input->joy_axis(idx, b, s_btns[b]);
  679. } else {
  680. input->joy_button(idx, b, s_btns[b]);
  681. }
  682. }
  683. for (int a = 0; a < s_axes_num; a++) {
  684. input->joy_axis(idx, a, s_axes[a]);
  685. }
  686. }
  687. }
  688. void OS_JavaScript::process_keys() {
  689. for (int i = 0; i < key_event_pos; i++) {
  690. const OS_JavaScript::KeyEvent &ke = key_event_buffer[i];
  691. Ref<InputEventKey> ev;
  692. ev.instance();
  693. ev->set_pressed(ke.pressed);
  694. ev->set_echo(ke.echo);
  695. ev->set_scancode(ke.keycode);
  696. ev->set_physical_scancode(ke.physical_keycode);
  697. ev->set_unicode(ke.unicode);
  698. if (ke.raw) {
  699. dom2godot_mod(ev, ke.mod);
  700. }
  701. input->parse_input_event(ev);
  702. }
  703. key_event_pos = 0;
  704. }
  705. bool OS_JavaScript::is_joy_known(int p_device) {
  706. return input->is_joy_mapped(p_device);
  707. }
  708. String OS_JavaScript::get_joy_guid(int p_device) const {
  709. return input->get_joy_guid_remapped(p_device);
  710. }
  711. // Video
  712. int OS_JavaScript::get_video_driver_count() const {
  713. return VIDEO_DRIVER_MAX;
  714. }
  715. const char *OS_JavaScript::get_video_driver_name(int p_driver) const {
  716. switch (p_driver) {
  717. case VIDEO_DRIVER_GLES3:
  718. return "GLES3";
  719. case VIDEO_DRIVER_GLES2:
  720. return "GLES2";
  721. }
  722. ERR_FAIL_V_MSG(NULL, "Invalid video driver index: " + itos(p_driver) + ".");
  723. }
  724. // Audio
  725. int OS_JavaScript::get_audio_driver_count() const {
  726. return audio_drivers.size();
  727. }
  728. const char *OS_JavaScript::get_audio_driver_name(int p_driver) const {
  729. if (audio_drivers.size() <= p_driver) {
  730. return "Unknown";
  731. }
  732. return audio_drivers[p_driver]->get_name();
  733. }
  734. // Clipboard
  735. void OS_JavaScript::update_clipboard_callback(const char *p_text) {
  736. // Only call set_clipboard from OS (sets local clipboard)
  737. get_singleton()->OS::set_clipboard(String::utf8(p_text));
  738. }
  739. void OS_JavaScript::set_clipboard(const String &p_text) {
  740. OS::set_clipboard(p_text);
  741. int err = godot_js_display_clipboard_set(p_text.utf8().get_data());
  742. ERR_FAIL_COND_MSG(err, "Clipboard API is not supported.");
  743. }
  744. String OS_JavaScript::get_clipboard() const {
  745. godot_js_display_clipboard_get(update_clipboard_callback);
  746. return this->OS::get_clipboard();
  747. }
  748. // Lifecycle
  749. int OS_JavaScript::get_current_video_driver() const {
  750. return video_driver_index;
  751. }
  752. void OS_JavaScript::initialize_core() {
  753. OS_Unix::initialize_core();
  754. }
  755. Error OS_JavaScript::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  756. video_mode = p_desired;
  757. // fullscreen_change_callback will correct this if the request is successful.
  758. video_mode.fullscreen = false;
  759. // Handle contextmenu, webglcontextlost, initial canvas setup.
  760. godot_js_display_setup_canvas(video_mode.width, video_mode.height, video_mode.fullscreen, is_hidpi_allowed() ? 1 : 0);
  761. swap_ok_cancel = godot_js_display_is_swap_ok_cancel() == 1;
  762. tts = GLOBAL_GET("audio/general/text_to_speech");
  763. EmscriptenWebGLContextAttributes attributes;
  764. emscripten_webgl_init_context_attributes(&attributes);
  765. attributes.alpha = GLOBAL_GET("display/window/per_pixel_transparency/allowed");
  766. attributes.antialias = false;
  767. attributes.explicitSwapControl = true;
  768. ERR_FAIL_INDEX_V(p_video_driver, VIDEO_DRIVER_MAX, ERR_INVALID_PARAMETER);
  769. if (p_desired.layered) {
  770. set_window_per_pixel_transparency_enabled(true);
  771. }
  772. bool gles3 = true;
  773. if (p_video_driver == VIDEO_DRIVER_GLES2) {
  774. gles3 = false;
  775. }
  776. bool gl_initialization_error = false;
  777. while (true) {
  778. if (gles3) {
  779. if (godot_js_display_has_webgl(2) && RasterizerGLES3::is_viable() == OK) {
  780. attributes.majorVersion = 2;
  781. RasterizerGLES3::register_config();
  782. RasterizerGLES3::make_current();
  783. break;
  784. } else {
  785. if (GLOBAL_GET("rendering/quality/driver/fallback_to_gles2")) {
  786. p_video_driver = VIDEO_DRIVER_GLES2;
  787. gles3 = false;
  788. continue;
  789. } else {
  790. gl_initialization_error = true;
  791. break;
  792. }
  793. }
  794. } else {
  795. if (godot_js_display_has_webgl(1) && RasterizerGLES2::is_viable() == OK) {
  796. attributes.majorVersion = 1;
  797. RasterizerGLES2::register_config();
  798. RasterizerGLES2::make_current();
  799. break;
  800. } else {
  801. gl_initialization_error = true;
  802. break;
  803. }
  804. }
  805. }
  806. webgl_ctx = emscripten_webgl_create_context(canvas_id, &attributes);
  807. if (emscripten_webgl_make_context_current(webgl_ctx) != EMSCRIPTEN_RESULT_SUCCESS) {
  808. gl_initialization_error = true;
  809. }
  810. if (gl_initialization_error) {
  811. OS::get_singleton()->alert("Your browser does not support any of the supported WebGL versions.\n"
  812. "Please update your browser version.",
  813. "Unable to initialize Video driver");
  814. return ERR_UNAVAILABLE;
  815. }
  816. video_driver_index = p_video_driver;
  817. AudioDriverManager::initialize(p_audio_driver);
  818. visual_server = memnew(VisualServerRaster());
  819. #ifndef NO_THREADS
  820. visual_server = memnew(VisualServerWrapMT(visual_server, false));
  821. #endif
  822. input = memnew(InputDefault);
  823. // JS Input interface (js/libs/library_godot_input.js)
  824. godot_js_input_mouse_button_cb(&OS_JavaScript::mouse_button_callback);
  825. godot_js_input_mouse_move_cb(&OS_JavaScript::mouse_move_callback);
  826. godot_js_input_mouse_wheel_cb(&OS_JavaScript::mouse_wheel_callback);
  827. godot_js_input_touch_cb(&OS_JavaScript::touch_callback, touch_event.identifier, touch_event.coords);
  828. godot_js_input_key_cb(&OS_JavaScript::key_callback, key_event.code, key_event.key);
  829. godot_js_input_gamepad_cb(&OS_JavaScript::gamepad_callback);
  830. godot_js_input_paste_cb(&OS_JavaScript::update_clipboard_callback);
  831. godot_js_input_drop_files_cb(&OS_JavaScript::drop_files_callback);
  832. godot_js_set_ime_cb(&OS_JavaScript::ime_callback, &OS_JavaScript::key_callback, key_event.code, key_event.key);
  833. // JS Display interface (js/libs/library_godot_display.js)
  834. godot_js_display_fullscreen_cb(&OS_JavaScript::fullscreen_change_callback);
  835. godot_js_display_window_blur_cb(&window_blur_callback);
  836. godot_js_display_notification_cb(&OS_JavaScript::send_notification_callback,
  837. MainLoop::NOTIFICATION_WM_MOUSE_ENTER,
  838. MainLoop::NOTIFICATION_WM_MOUSE_EXIT,
  839. MainLoop::NOTIFICATION_WM_FOCUS_IN,
  840. MainLoop::NOTIFICATION_WM_FOCUS_OUT);
  841. godot_js_display_vk_cb(&input_text_callback);
  842. visual_server->init();
  843. return OK;
  844. }
  845. void OS_JavaScript::input_text_callback(const char *p_text, int p_cursor) {
  846. OS_JavaScript *os = OS_JavaScript::get_singleton();
  847. if (!os || !os->get_main_loop()) {
  848. return;
  849. }
  850. os->get_main_loop()->input_text(String::utf8(p_text));
  851. Ref<InputEventKey> k;
  852. for (int i = 0; i < p_cursor; i++) {
  853. k.instance();
  854. k->set_pressed(true);
  855. k->set_echo(false);
  856. k->set_scancode(KEY_RIGHT);
  857. os->input->parse_input_event(k);
  858. k.instance();
  859. k->set_pressed(false);
  860. k->set_echo(false);
  861. k->set_scancode(KEY_RIGHT);
  862. os->input->parse_input_event(k);
  863. }
  864. }
  865. bool OS_JavaScript::has_virtual_keyboard() const {
  866. return godot_js_display_vk_available() != 0;
  867. }
  868. void OS_JavaScript::show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect, VirtualKeyboardType p_type, int p_max_input_length, int p_cursor_start, int p_cursor_end) {
  869. godot_js_display_vk_show(p_existing_text.utf8().get_data(), p_type, p_cursor_start, p_cursor_end);
  870. }
  871. void OS_JavaScript::hide_virtual_keyboard() {
  872. godot_js_display_vk_hide();
  873. }
  874. bool OS_JavaScript::get_swap_ok_cancel() {
  875. return swap_ok_cancel;
  876. }
  877. void OS_JavaScript::swap_buffers() {
  878. emscripten_webgl_commit_frame();
  879. }
  880. void OS_JavaScript::set_main_loop(MainLoop *p_main_loop) {
  881. main_loop = p_main_loop;
  882. input->set_main_loop(p_main_loop);
  883. }
  884. MainLoop *OS_JavaScript::get_main_loop() const {
  885. return main_loop;
  886. }
  887. void OS_JavaScript::resume_audio() {
  888. AudioDriverJavaScript::resume();
  889. }
  890. void OS_JavaScript::fs_sync_callback() {
  891. get_singleton()->idb_is_syncing = false;
  892. }
  893. bool OS_JavaScript::main_loop_iterate() {
  894. if (is_userfs_persistent() && idb_needs_sync && !idb_is_syncing) {
  895. idb_is_syncing = true;
  896. idb_needs_sync = false;
  897. godot_js_os_fs_sync(&OS_JavaScript::fs_sync_callback);
  898. }
  899. process_keys();
  900. input->flush_buffered_events();
  901. if (godot_js_input_gamepad_sample() == OK) {
  902. process_joypads();
  903. }
  904. return Main::iteration();
  905. }
  906. int OS_JavaScript::get_screen_dpi(int p_screen) const {
  907. return godot_js_display_screen_dpi_get();
  908. }
  909. float OS_JavaScript::get_screen_scale(int p_screen) const {
  910. return godot_js_display_pixel_ratio_get();
  911. }
  912. float OS_JavaScript::get_screen_max_scale() const {
  913. return get_screen_scale();
  914. }
  915. void OS_JavaScript::delete_main_loop() {
  916. memdelete(main_loop);
  917. main_loop = NULL;
  918. }
  919. void OS_JavaScript::finalize() {
  920. memdelete(input);
  921. visual_server->finish();
  922. emscripten_webgl_commit_frame();
  923. memdelete(visual_server);
  924. emscripten_webgl_destroy_context(webgl_ctx);
  925. for (int i = 0; i < audio_drivers.size(); i++) {
  926. memdelete(audio_drivers[i]);
  927. }
  928. audio_drivers.clear();
  929. }
  930. // Miscellaneous
  931. 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, bool p_open_console) {
  932. Array args;
  933. for (const List<String>::Element *E = p_arguments.front(); E; E = E->next()) {
  934. args.push_back(E->get());
  935. }
  936. String json_args = JSON::print(args);
  937. int failed = godot_js_os_execute(json_args.utf8().get_data());
  938. ERR_FAIL_COND_V_MSG(failed, ERR_UNAVAILABLE, "OS::execute() must be implemented in Javascript via 'engine.setOnExecute' if required.");
  939. return OK;
  940. }
  941. Error OS_JavaScript::kill(const ProcessID &p_pid) {
  942. ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "OS::kill() is not available on the HTML5 platform.");
  943. }
  944. int OS_JavaScript::get_process_id() const {
  945. ERR_FAIL_V_MSG(0, "OS::get_process_id() is not available on the HTML5 platform.");
  946. }
  947. bool OS_JavaScript::is_process_running(const ProcessID &p_pid) const {
  948. return false;
  949. }
  950. int OS_JavaScript::get_processor_count() const {
  951. return godot_js_os_hw_concurrency_get();
  952. }
  953. String OS_JavaScript::get_unique_id() const {
  954. ERR_FAIL_V_MSG("", "OS::get_unique_id() is not available on the HTML5 platform.");
  955. }
  956. bool OS_JavaScript::_check_internal_feature_support(const String &p_feature) {
  957. if (p_feature == "HTML5" || p_feature == "web") {
  958. return true;
  959. }
  960. #ifdef JAVASCRIPT_EVAL_ENABLED
  961. if (p_feature == "JavaScript") {
  962. return true;
  963. }
  964. #endif
  965. #ifndef NO_THREADS
  966. if (p_feature == "threads") {
  967. return true;
  968. }
  969. #endif
  970. #if WASM_GDNATIVE
  971. if (p_feature == "wasm32") {
  972. return true;
  973. }
  974. #endif
  975. return false;
  976. }
  977. void OS_JavaScript::alert(const String &p_alert, const String &p_title) {
  978. godot_js_display_alert(p_alert.utf8().get_data());
  979. }
  980. void OS_JavaScript::set_window_title(const String &p_title) {
  981. godot_js_display_window_title_set(p_title.utf8().get_data());
  982. }
  983. void OS_JavaScript::set_icon(const Ref<Image> &p_icon) {
  984. ERR_FAIL_COND(p_icon.is_null());
  985. Ref<Image> icon = p_icon;
  986. if (icon->is_compressed()) {
  987. icon = icon->duplicate();
  988. ERR_FAIL_COND(icon->decompress() != OK);
  989. }
  990. if (icon->get_format() != Image::FORMAT_RGBA8) {
  991. if (icon == p_icon)
  992. icon = icon->duplicate();
  993. icon->convert(Image::FORMAT_RGBA8);
  994. }
  995. png_image png_meta;
  996. memset(&png_meta, 0, sizeof png_meta);
  997. png_meta.version = PNG_IMAGE_VERSION;
  998. png_meta.width = icon->get_width();
  999. png_meta.height = icon->get_height();
  1000. png_meta.format = PNG_FORMAT_RGBA;
  1001. PoolByteArray png;
  1002. size_t len;
  1003. PoolByteArray::Read r = icon->get_data().read();
  1004. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, r.ptr(), 0, NULL));
  1005. png.resize(len);
  1006. PoolByteArray::Write w = png.write();
  1007. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, w.ptr(), &len, 0, r.ptr(), 0, NULL));
  1008. w = PoolByteArray::Write();
  1009. r = png.read();
  1010. godot_js_display_window_icon_set(r.ptr(), len);
  1011. }
  1012. String OS_JavaScript::get_executable_path() const {
  1013. return OS::get_executable_path();
  1014. }
  1015. Error OS_JavaScript::shell_open(String p_uri) {
  1016. // Open URI in a new tab, browser will deal with it by protocol.
  1017. godot_js_os_shell_open(p_uri.utf8().get_data());
  1018. return OK;
  1019. }
  1020. String OS_JavaScript::get_name() const {
  1021. return "HTML5";
  1022. }
  1023. bool OS_JavaScript::can_draw() const {
  1024. return true; // Always?
  1025. }
  1026. void OS_JavaScript::vibrate_handheld(int p_duration_ms) {
  1027. godot_js_input_vibrate_handheld(p_duration_ms);
  1028. }
  1029. String OS_JavaScript::get_user_data_dir() const {
  1030. return "/userfs";
  1031. };
  1032. String OS_JavaScript::get_cache_path() const {
  1033. return "/home/web_user/.cache";
  1034. }
  1035. String OS_JavaScript::get_config_path() const {
  1036. return "/home/web_user/.config";
  1037. }
  1038. String OS_JavaScript::get_data_path() const {
  1039. return "/home/web_user/.local/share";
  1040. }
  1041. OS::PowerState OS_JavaScript::get_power_state() {
  1042. WARN_PRINT_ONCE("Power management is not supported for the HTML5 platform, defaulting to POWERSTATE_UNKNOWN");
  1043. return OS::POWERSTATE_UNKNOWN;
  1044. }
  1045. int OS_JavaScript::get_power_seconds_left() {
  1046. WARN_PRINT_ONCE("Power management is not supported for the HTML5 platform, defaulting to -1");
  1047. return -1;
  1048. }
  1049. int OS_JavaScript::get_power_percent_left() {
  1050. WARN_PRINT_ONCE("Power management is not supported for the HTML5 platform, defaulting to -1");
  1051. return -1;
  1052. }
  1053. void OS_JavaScript::file_access_close_callback(const String &p_file, int p_flags) {
  1054. OS_JavaScript *os = get_singleton();
  1055. if (!(os->is_userfs_persistent() && p_flags & FileAccess::WRITE)) {
  1056. return; // FS persistence is not working or we are not writing.
  1057. }
  1058. bool is_file_persistent = p_file.begins_with("/userfs");
  1059. #ifdef TOOLS_ENABLED
  1060. // Hack for editor persistence (can we track).
  1061. is_file_persistent = is_file_persistent || p_file.begins_with("/home/web_user/");
  1062. #endif
  1063. if (is_file_persistent) {
  1064. os->idb_needs_sync = true;
  1065. }
  1066. }
  1067. void OS_JavaScript::update_pwa_state_callback() {
  1068. if (OS_JavaScript::get_singleton()) {
  1069. OS_JavaScript::get_singleton()->pwa_is_waiting = true;
  1070. }
  1071. if (JavaScript::get_singleton()) {
  1072. JavaScript::get_singleton()->emit_signal("pwa_update_available");
  1073. }
  1074. }
  1075. Error OS_JavaScript::pwa_update() {
  1076. return godot_js_pwa_update() ? FAILED : OK;
  1077. }
  1078. void OS_JavaScript::force_fs_sync() {
  1079. if (is_userfs_persistent()) {
  1080. idb_needs_sync = true;
  1081. }
  1082. }
  1083. bool OS_JavaScript::is_userfs_persistent() const {
  1084. return idb_available;
  1085. }
  1086. Error OS_JavaScript::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
  1087. String path = p_path.get_file();
  1088. p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
  1089. ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, "Can't open dynamic library: " + p_path + ". Error: " + dlerror());
  1090. return OK;
  1091. }
  1092. OS_JavaScript *OS_JavaScript::get_singleton() {
  1093. return static_cast<OS_JavaScript *>(OS::get_singleton());
  1094. }
  1095. OS_JavaScript::OS_JavaScript() {
  1096. // Expose method for requesting quit.
  1097. godot_js_os_request_quit_cb(&request_quit_callback);
  1098. // Set canvas ID
  1099. godot_js_config_canvas_id_get(canvas_id, sizeof(canvas_id));
  1100. cursor_inside_canvas = true;
  1101. cursor_shape = OS::CURSOR_ARROW;
  1102. last_click_button_index = -1;
  1103. last_click_ms = 0;
  1104. last_click_pos = Point2(-100, -100);
  1105. transparency_enabled = false;
  1106. main_loop = NULL;
  1107. visual_server = NULL;
  1108. tts = false;
  1109. swap_ok_cancel = false;
  1110. idb_available = godot_js_os_fs_is_persistent() != 0;
  1111. idb_needs_sync = false;
  1112. idb_is_syncing = false;
  1113. pwa_is_waiting = false;
  1114. godot_js_pwa_cb(&OS_JavaScript::update_pwa_state_callback);
  1115. if (AudioDriverJavaScript::is_available()) {
  1116. #ifdef NO_THREADS
  1117. audio_drivers.push_back(memnew(AudioDriverScriptProcessor));
  1118. #endif
  1119. audio_drivers.push_back(memnew(AudioDriverWorklet));
  1120. }
  1121. for (int i = 0; i < audio_drivers.size(); i++) {
  1122. AudioDriverManager::add_driver(audio_drivers[i]);
  1123. }
  1124. Vector<Logger *> loggers;
  1125. loggers.push_back(memnew(StdLogger));
  1126. _set_logger(memnew(CompositeLogger(loggers)));
  1127. FileAccessUnix::close_notification_func = file_access_close_callback;
  1128. }