os_javascript.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325
  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 "drivers/gles2/rasterizer_gles2.h"
  33. #include "drivers/gles3/rasterizer_gles3.h"
  34. #include "drivers/unix/dir_access_unix.h"
  35. #include "drivers/unix/file_access_unix.h"
  36. #include "main/main.h"
  37. #include "servers/visual/visual_server_raster.h"
  38. #include <emscripten.h>
  39. #include <png.h>
  40. #include <stdlib.h>
  41. #include "dom_keys.inc"
  42. #define DOM_BUTTON_LEFT 0
  43. #define DOM_BUTTON_MIDDLE 1
  44. #define DOM_BUTTON_RIGHT 2
  45. #define DOM_BUTTON_XBUTTON1 3
  46. #define DOM_BUTTON_XBUTTON2 4
  47. // Window (canvas)
  48. static void focus_canvas() {
  49. /* clang-format off */
  50. EM_ASM(
  51. Module.canvas.focus();
  52. );
  53. /* clang-format on */
  54. }
  55. static bool is_canvas_focused() {
  56. /* clang-format off */
  57. return EM_ASM_INT_V(
  58. return document.activeElement == Module.canvas;
  59. );
  60. /* clang-format on */
  61. }
  62. static Point2 correct_canvas_position(int x, int y) {
  63. int canvas_width;
  64. int canvas_height;
  65. emscripten_get_canvas_element_size(NULL, &canvas_width, &canvas_height);
  66. double element_width;
  67. double element_height;
  68. emscripten_get_element_css_size(NULL, &element_width, &element_height);
  69. x = (int)(canvas_width / element_width * x);
  70. y = (int)(canvas_height / element_height * y);
  71. return Point2(x, y);
  72. }
  73. static bool cursor_inside_canvas = true;
  74. EM_BOOL OS_JavaScript::fullscreen_change_callback(int p_event_type, const EmscriptenFullscreenChangeEvent *p_event, void *p_user_data) {
  75. OS_JavaScript *os = get_singleton();
  76. // Empty ID is canvas.
  77. String target_id = String::utf8(p_event->id);
  78. if (target_id.empty() || target_id == "canvas") {
  79. // This event property is the only reliable data on
  80. // browser fullscreen state.
  81. os->video_mode.fullscreen = p_event->isFullscreen;
  82. if (os->video_mode.fullscreen) {
  83. os->entering_fullscreen = false;
  84. } else {
  85. // Restoring maximized window now will cause issues,
  86. // so delay until main_loop_iterate.
  87. os->just_exited_fullscreen = true;
  88. }
  89. }
  90. return false;
  91. }
  92. void OS_JavaScript::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  93. video_mode = p_video_mode;
  94. }
  95. OS::VideoMode OS_JavaScript::get_video_mode(int p_screen) const {
  96. return video_mode;
  97. }
  98. Size2 OS_JavaScript::get_screen_size(int p_screen) const {
  99. EmscriptenFullscreenChangeEvent ev;
  100. EMSCRIPTEN_RESULT result = emscripten_get_fullscreen_status(&ev);
  101. ERR_FAIL_COND_V(result != EMSCRIPTEN_RESULT_SUCCESS, Size2());
  102. return Size2(ev.screenWidth, ev.screenHeight);
  103. }
  104. void OS_JavaScript::set_window_size(const Size2 p_size) {
  105. windowed_size = p_size;
  106. if (video_mode.fullscreen) {
  107. window_maximized = false;
  108. set_window_fullscreen(false);
  109. } else {
  110. if (window_maximized) {
  111. emscripten_exit_soft_fullscreen();
  112. window_maximized = false;
  113. }
  114. emscripten_set_canvas_element_size(NULL, p_size.x, p_size.y);
  115. }
  116. }
  117. Size2 OS_JavaScript::get_window_size() const {
  118. int canvas[2];
  119. emscripten_get_canvas_element_size(NULL, canvas, canvas + 1);
  120. return Size2(canvas[0], canvas[1]);
  121. }
  122. void OS_JavaScript::set_window_maximized(bool p_enabled) {
  123. if (video_mode.fullscreen) {
  124. window_maximized = p_enabled;
  125. set_window_fullscreen(false);
  126. } else if (!p_enabled) {
  127. emscripten_exit_soft_fullscreen();
  128. window_maximized = false;
  129. } else if (!window_maximized) {
  130. // Prevent calling emscripten_enter_soft_fullscreen mutltiple times,
  131. // this would hide page elements permanently.
  132. EmscriptenFullscreenStrategy strategy;
  133. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  134. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  135. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  136. strategy.canvasResizedCallback = NULL;
  137. emscripten_enter_soft_fullscreen(NULL, &strategy);
  138. window_maximized = p_enabled;
  139. }
  140. }
  141. bool OS_JavaScript::is_window_maximized() const {
  142. return window_maximized;
  143. }
  144. void OS_JavaScript::set_window_fullscreen(bool p_enabled) {
  145. if (p_enabled == video_mode.fullscreen) {
  146. return;
  147. }
  148. // Just request changes here, if successful, logic continues in
  149. // fullscreen_change_callback.
  150. if (p_enabled) {
  151. if (window_maximized) {
  152. // Soft fullsreen during real fullscreen can cause issues, so exit.
  153. // This must be called before requesting full screen.
  154. emscripten_exit_soft_fullscreen();
  155. }
  156. EmscriptenFullscreenStrategy strategy;
  157. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  158. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  159. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  160. strategy.canvasResizedCallback = NULL;
  161. EMSCRIPTEN_RESULT result = emscripten_request_fullscreen_strategy(NULL, false, &strategy);
  162. ERR_FAIL_COND_MSG(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED, "Enabling fullscreen is only possible from an input callback for the HTML5 platform.");
  163. ERR_FAIL_COND_MSG(result != EMSCRIPTEN_RESULT_SUCCESS, "Enabling fullscreen is only possible from an input callback for the HTML5 platform.");
  164. // Not fullscreen yet, so prevent "windowed" canvas dimensions from
  165. // being overwritten.
  166. entering_fullscreen = true;
  167. } else {
  168. // No logic allowed here, since exiting w/ ESC key won't use this function.
  169. ERR_FAIL_COND(emscripten_exit_fullscreen() != EMSCRIPTEN_RESULT_SUCCESS);
  170. }
  171. }
  172. bool OS_JavaScript::is_window_fullscreen() const {
  173. return video_mode.fullscreen;
  174. }
  175. void OS_JavaScript::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  176. Size2 screen = get_screen_size();
  177. p_list->push_back(OS::VideoMode(screen.width, screen.height, true));
  178. }
  179. // Keys
  180. template <typename T>
  181. static void dom2godot_mod(T *emscripten_event_ptr, Ref<InputEventWithModifiers> godot_event) {
  182. godot_event->set_shift(emscripten_event_ptr->shiftKey);
  183. godot_event->set_alt(emscripten_event_ptr->altKey);
  184. godot_event->set_control(emscripten_event_ptr->ctrlKey);
  185. godot_event->set_metakey(emscripten_event_ptr->metaKey);
  186. }
  187. static Ref<InputEventKey> setup_key_event(const EmscriptenKeyboardEvent *emscripten_event) {
  188. Ref<InputEventKey> ev;
  189. ev.instance();
  190. ev->set_echo(emscripten_event->repeat);
  191. dom2godot_mod(emscripten_event, ev);
  192. ev->set_scancode(dom2godot_scancode(emscripten_event->keyCode));
  193. String unicode = String::utf8(emscripten_event->key);
  194. // Check if empty or multi-character (e.g. `CapsLock`).
  195. if (unicode.length() != 1) {
  196. // Might be empty as well, but better than nonsense.
  197. unicode = String::utf8(emscripten_event->charValue);
  198. }
  199. if (unicode.length() == 1) {
  200. ev->set_unicode(unicode[0]);
  201. }
  202. return ev;
  203. }
  204. EM_BOOL OS_JavaScript::keydown_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  205. OS_JavaScript *os = get_singleton();
  206. Ref<InputEventKey> ev = setup_key_event(p_event);
  207. ev->set_pressed(true);
  208. if (ev->get_unicode() == 0 && keycode_has_unicode(ev->get_scancode())) {
  209. // Defer to keypress event for legacy unicode retrieval.
  210. os->deferred_key_event = ev;
  211. // Do not suppress keypress event.
  212. return false;
  213. }
  214. os->input->parse_input_event(ev);
  215. // Resume audio context after input in case autoplay was denied.
  216. os->audio_driver_javascript.resume();
  217. return true;
  218. }
  219. EM_BOOL OS_JavaScript::keypress_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  220. OS_JavaScript *os = get_singleton();
  221. os->deferred_key_event->set_unicode(p_event->charCode);
  222. os->input->parse_input_event(os->deferred_key_event);
  223. return true;
  224. }
  225. EM_BOOL OS_JavaScript::keyup_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  226. Ref<InputEventKey> ev = setup_key_event(p_event);
  227. ev->set_pressed(false);
  228. get_singleton()->input->parse_input_event(ev);
  229. return ev->get_scancode() != KEY_UNKNOWN && ev->get_scancode() != 0;
  230. }
  231. // Mouse
  232. Point2 OS_JavaScript::get_mouse_position() const {
  233. return input->get_mouse_position();
  234. }
  235. int OS_JavaScript::get_mouse_button_state() const {
  236. return input->get_mouse_button_mask();
  237. }
  238. EM_BOOL OS_JavaScript::mouse_button_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) {
  239. OS_JavaScript *os = get_singleton();
  240. Ref<InputEventMouseButton> ev;
  241. ev.instance();
  242. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_MOUSEDOWN);
  243. ev->set_position(correct_canvas_position(p_event->canvasX, p_event->canvasY));
  244. ev->set_global_position(ev->get_position());
  245. dom2godot_mod(p_event, ev);
  246. switch (p_event->button) {
  247. case DOM_BUTTON_LEFT: ev->set_button_index(BUTTON_LEFT); break;
  248. case DOM_BUTTON_MIDDLE: ev->set_button_index(BUTTON_MIDDLE); break;
  249. case DOM_BUTTON_RIGHT: ev->set_button_index(BUTTON_RIGHT); break;
  250. case DOM_BUTTON_XBUTTON1: ev->set_button_index(BUTTON_XBUTTON1); break;
  251. case DOM_BUTTON_XBUTTON2: ev->set_button_index(BUTTON_XBUTTON2); break;
  252. default: return false;
  253. }
  254. if (ev->is_pressed()) {
  255. double diff = emscripten_get_now() - os->last_click_ms;
  256. if (ev->get_button_index() == os->last_click_button_index) {
  257. if (diff < 400 && Point2(os->last_click_pos).distance_to(ev->get_position()) < 5) {
  258. os->last_click_ms = 0;
  259. os->last_click_pos = Point2(-100, -100);
  260. os->last_click_button_index = -1;
  261. ev->set_doubleclick(true);
  262. }
  263. } else {
  264. os->last_click_button_index = ev->get_button_index();
  265. }
  266. if (!ev->is_doubleclick()) {
  267. os->last_click_ms += diff;
  268. os->last_click_pos = ev->get_position();
  269. }
  270. }
  271. int mask = os->input->get_mouse_button_mask();
  272. int button_flag = 1 << (ev->get_button_index() - 1);
  273. if (ev->is_pressed()) {
  274. // Since the event is consumed, focus manually. The containing iframe,
  275. // if exists, may not have focus yet, so focus even if already focused.
  276. focus_canvas();
  277. mask |= button_flag;
  278. } else if (mask & button_flag) {
  279. mask &= ~button_flag;
  280. } else {
  281. // Received release event, but press was outside the canvas, so ignore.
  282. return false;
  283. }
  284. ev->set_button_mask(mask);
  285. os->input->parse_input_event(ev);
  286. // Resume audio context after input in case autoplay was denied.
  287. os->audio_driver_javascript.resume();
  288. // Prevent multi-click text selection and wheel-click scrolling anchor.
  289. // Context menu is prevented through contextmenu event.
  290. return true;
  291. }
  292. EM_BOOL OS_JavaScript::mousemove_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) {
  293. OS_JavaScript *os = get_singleton();
  294. int input_mask = os->input->get_mouse_button_mask();
  295. Point2 pos = correct_canvas_position(p_event->canvasX, p_event->canvasY);
  296. // For motion outside the canvas, only read mouse movement if dragging
  297. // started inside the canvas; imitating desktop app behaviour.
  298. if (!cursor_inside_canvas && !input_mask)
  299. return false;
  300. Ref<InputEventMouseMotion> ev;
  301. ev.instance();
  302. dom2godot_mod(p_event, ev);
  303. ev->set_button_mask(input_mask);
  304. ev->set_position(pos);
  305. ev->set_global_position(ev->get_position());
  306. ev->set_relative(Vector2(p_event->movementX, p_event->movementY));
  307. os->input->set_mouse_position(ev->get_position());
  308. ev->set_speed(os->input->get_last_mouse_speed());
  309. os->input->parse_input_event(ev);
  310. // Don't suppress mouseover/-leave events.
  311. return false;
  312. }
  313. static const char *godot2dom_cursor(OS::CursorShape p_shape) {
  314. switch (p_shape) {
  315. case OS::CURSOR_ARROW:
  316. default:
  317. return "auto";
  318. case OS::CURSOR_IBEAM: return "text";
  319. case OS::CURSOR_POINTING_HAND: return "pointer";
  320. case OS::CURSOR_CROSS: return "crosshair";
  321. case OS::CURSOR_WAIT: return "progress";
  322. case OS::CURSOR_BUSY: return "wait";
  323. case OS::CURSOR_DRAG: return "grab";
  324. case OS::CURSOR_CAN_DROP: return "grabbing";
  325. case OS::CURSOR_FORBIDDEN: return "no-drop";
  326. case OS::CURSOR_VSIZE: return "ns-resize";
  327. case OS::CURSOR_HSIZE: return "ew-resize";
  328. case OS::CURSOR_BDIAGSIZE: return "nesw-resize";
  329. case OS::CURSOR_FDIAGSIZE: return "nwse-resize";
  330. case OS::CURSOR_MOVE: return "move";
  331. case OS::CURSOR_VSPLIT: return "row-resize";
  332. case OS::CURSOR_HSPLIT: return "col-resize";
  333. case OS::CURSOR_HELP: return "help";
  334. }
  335. }
  336. static void set_css_cursor(const char *p_cursor) {
  337. /* clang-format off */
  338. EM_ASM_({
  339. Module.canvas.style.cursor = UTF8ToString($0);
  340. }, p_cursor);
  341. /* clang-format on */
  342. }
  343. static bool is_css_cursor_hidden() {
  344. /* clang-format off */
  345. return EM_ASM_INT({
  346. return Module.canvas.style.cursor === 'none';
  347. });
  348. /* clang-format on */
  349. }
  350. void OS_JavaScript::set_cursor_shape(CursorShape p_shape) {
  351. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  352. if (get_mouse_mode() == MOUSE_MODE_VISIBLE) {
  353. if (cursors[p_shape] != "") {
  354. Vector<String> url = cursors[p_shape].split("?");
  355. set_css_cursor(("url(\"" + url[0] + "\") " + url[1] + ", auto").utf8());
  356. } else {
  357. set_css_cursor(godot2dom_cursor(p_shape));
  358. }
  359. }
  360. cursor_shape = p_shape;
  361. }
  362. void OS_JavaScript::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  363. if (p_cursor.is_valid()) {
  364. Map<CursorShape, Vector<Variant> >::Element *cursor_c = cursors_cache.find(p_shape);
  365. if (cursor_c) {
  366. if (cursor_c->get()[0] == p_cursor && cursor_c->get()[1] == p_hotspot) {
  367. set_cursor_shape(p_shape);
  368. return;
  369. }
  370. cursors_cache.erase(p_shape);
  371. }
  372. Ref<Texture> texture = p_cursor;
  373. Ref<AtlasTexture> atlas_texture = p_cursor;
  374. Ref<Image> image;
  375. Size2 texture_size;
  376. Rect2 atlas_rect;
  377. if (texture.is_valid()) {
  378. image = texture->get_data();
  379. if (image.is_valid()) {
  380. image->duplicate();
  381. }
  382. }
  383. if (!image.is_valid() && atlas_texture.is_valid()) {
  384. texture = atlas_texture->get_atlas();
  385. atlas_rect.size.width = texture->get_width();
  386. atlas_rect.size.height = texture->get_height();
  387. atlas_rect.position.x = atlas_texture->get_region().position.x;
  388. atlas_rect.position.y = atlas_texture->get_region().position.y;
  389. texture_size.width = atlas_texture->get_region().size.x;
  390. texture_size.height = atlas_texture->get_region().size.y;
  391. } else if (image.is_valid()) {
  392. texture_size.width = texture->get_width();
  393. texture_size.height = texture->get_height();
  394. }
  395. ERR_FAIL_COND(!texture.is_valid());
  396. ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
  397. ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
  398. ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
  399. image = texture->get_data();
  400. ERR_FAIL_COND(!image.is_valid());
  401. image = image->duplicate();
  402. if (atlas_texture.is_valid())
  403. image->crop_from_point(
  404. atlas_rect.position.x,
  405. atlas_rect.position.y,
  406. texture_size.width,
  407. texture_size.height);
  408. if (image->get_format() != Image::FORMAT_RGBA8) {
  409. image->convert(Image::FORMAT_RGBA8);
  410. }
  411. png_image png_meta;
  412. memset(&png_meta, 0, sizeof png_meta);
  413. png_meta.version = PNG_IMAGE_VERSION;
  414. png_meta.width = texture_size.width;
  415. png_meta.height = texture_size.height;
  416. png_meta.format = PNG_FORMAT_RGBA;
  417. PoolByteArray png;
  418. size_t len;
  419. PoolByteArray::Read r = image->get_data().read();
  420. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, r.ptr(), 0, NULL));
  421. png.resize(len);
  422. PoolByteArray::Write w = png.write();
  423. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, w.ptr(), &len, 0, r.ptr(), 0, NULL));
  424. w = PoolByteArray::Write();
  425. r = png.read();
  426. char *object_url;
  427. /* clang-format off */
  428. EM_ASM({
  429. var PNG_PTR = $0;
  430. var PNG_LEN = $1;
  431. var PTR = $2;
  432. var png = new Blob([HEAPU8.slice(PNG_PTR, PNG_PTR + PNG_LEN)], { type: 'image/png' });
  433. var url = URL.createObjectURL(png);
  434. var length_bytes = lengthBytesUTF8(url) + 1;
  435. var string_on_wasm_heap = _malloc(length_bytes);
  436. setValue(PTR, string_on_wasm_heap, '*');
  437. stringToUTF8(url, string_on_wasm_heap, length_bytes);
  438. }, r.ptr(), len, &object_url);
  439. /* clang-format on */
  440. r = PoolByteArray::Read();
  441. String url = String::utf8(object_url) + "?" + itos(p_hotspot.x) + " " + itos(p_hotspot.y);
  442. /* clang-format off */
  443. EM_ASM({ _free($0); }, object_url);
  444. /* clang-format on */
  445. if (cursors[p_shape] != "") {
  446. /* clang-format off */
  447. EM_ASM({
  448. URL.revokeObjectURL(UTF8ToString($0).split('?')[0]);
  449. }, cursors[p_shape].utf8().get_data());
  450. /* clang-format on */
  451. cursors[p_shape] = "";
  452. }
  453. cursors[p_shape] = url;
  454. Vector<Variant> params;
  455. params.push_back(p_cursor);
  456. params.push_back(p_hotspot);
  457. cursors_cache.insert(p_shape, params);
  458. } else if (cursors[p_shape] != "") {
  459. /* clang-format off */
  460. EM_ASM({
  461. URL.revokeObjectURL(UTF8ToString($0).split('?')[0]);
  462. }, cursors[p_shape].utf8().get_data());
  463. /* clang-format on */
  464. cursors[p_shape] = "";
  465. cursors_cache.erase(p_shape);
  466. }
  467. set_cursor_shape(cursor_shape);
  468. }
  469. void OS_JavaScript::set_mouse_mode(OS::MouseMode p_mode) {
  470. ERR_FAIL_COND_MSG(p_mode == MOUSE_MODE_CONFINED, "MOUSE_MODE_CONFINED is not supported for the HTML5 platform.");
  471. if (p_mode == get_mouse_mode())
  472. return;
  473. if (p_mode == MOUSE_MODE_VISIBLE) {
  474. // set_css_cursor must be called before set_cursor_shape to make the cursor visible
  475. set_css_cursor(godot2dom_cursor(cursor_shape));
  476. set_cursor_shape(cursor_shape);
  477. emscripten_exit_pointerlock();
  478. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  479. set_css_cursor("none");
  480. emscripten_exit_pointerlock();
  481. } else if (p_mode == MOUSE_MODE_CAPTURED) {
  482. EMSCRIPTEN_RESULT result = emscripten_request_pointerlock("canvas", false);
  483. ERR_FAIL_COND_MSG(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED, "MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback.");
  484. ERR_FAIL_COND_MSG(result != EMSCRIPTEN_RESULT_SUCCESS, "MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback.");
  485. // set_css_cursor must be called before set_cursor_shape to make the cursor visible
  486. set_css_cursor(godot2dom_cursor(cursor_shape));
  487. set_cursor_shape(cursor_shape);
  488. }
  489. }
  490. OS::MouseMode OS_JavaScript::get_mouse_mode() const {
  491. if (is_css_cursor_hidden())
  492. return MOUSE_MODE_HIDDEN;
  493. EmscriptenPointerlockChangeEvent ev;
  494. emscripten_get_pointerlock_status(&ev);
  495. return (ev.isActive && String::utf8(ev.id) == "canvas") ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE;
  496. }
  497. // Wheel
  498. EM_BOOL OS_JavaScript::wheel_callback(int p_event_type, const EmscriptenWheelEvent *p_event, void *p_user_data) {
  499. ERR_FAIL_COND_V(p_event_type != EMSCRIPTEN_EVENT_WHEEL, false);
  500. if (!is_canvas_focused()) {
  501. if (cursor_inside_canvas) {
  502. focus_canvas();
  503. } else {
  504. return false;
  505. }
  506. }
  507. InputDefault *input = get_singleton()->input;
  508. Ref<InputEventMouseButton> ev;
  509. ev.instance();
  510. ev->set_position(input->get_mouse_position());
  511. ev->set_global_position(ev->get_position());
  512. ev->set_shift(input->is_key_pressed(KEY_SHIFT));
  513. ev->set_alt(input->is_key_pressed(KEY_ALT));
  514. ev->set_control(input->is_key_pressed(KEY_CONTROL));
  515. ev->set_metakey(input->is_key_pressed(KEY_META));
  516. if (p_event->deltaY < 0)
  517. ev->set_button_index(BUTTON_WHEEL_UP);
  518. else if (p_event->deltaY > 0)
  519. ev->set_button_index(BUTTON_WHEEL_DOWN);
  520. else if (p_event->deltaX > 0)
  521. ev->set_button_index(BUTTON_WHEEL_LEFT);
  522. else if (p_event->deltaX < 0)
  523. ev->set_button_index(BUTTON_WHEEL_RIGHT);
  524. else
  525. return false;
  526. // Different browsers give wildly different delta values, and we can't
  527. // interpret deltaMode, so use default value for wheel events' factor.
  528. int button_flag = 1 << (ev->get_button_index() - 1);
  529. ev->set_pressed(true);
  530. ev->set_button_mask(input->get_mouse_button_mask() | button_flag);
  531. input->parse_input_event(ev);
  532. ev->set_pressed(false);
  533. ev->set_button_mask(input->get_mouse_button_mask() & ~button_flag);
  534. input->parse_input_event(ev);
  535. return true;
  536. }
  537. // Touch
  538. bool OS_JavaScript::has_touchscreen_ui_hint() const {
  539. /* clang-format off */
  540. return EM_ASM_INT_V(
  541. return 'ontouchstart' in window;
  542. );
  543. /* clang-format on */
  544. }
  545. EM_BOOL OS_JavaScript::touch_press_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  546. OS_JavaScript *os = get_singleton();
  547. Ref<InputEventScreenTouch> ev;
  548. ev.instance();
  549. int lowest_id_index = -1;
  550. for (int i = 0; i < p_event->numTouches; ++i) {
  551. const EmscriptenTouchPoint &touch = p_event->touches[i];
  552. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  553. lowest_id_index = i;
  554. if (!touch.isChanged)
  555. continue;
  556. ev->set_index(touch.identifier);
  557. ev->set_position(correct_canvas_position(touch.canvasX, touch.canvasY));
  558. os->touches[i] = ev->get_position();
  559. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_TOUCHSTART);
  560. os->input->parse_input_event(ev);
  561. }
  562. // Resume audio context after input in case autoplay was denied.
  563. os->audio_driver_javascript.resume();
  564. return true;
  565. }
  566. EM_BOOL OS_JavaScript::touchmove_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  567. OS_JavaScript *os = get_singleton();
  568. Ref<InputEventScreenDrag> ev;
  569. ev.instance();
  570. int lowest_id_index = -1;
  571. for (int i = 0; i < p_event->numTouches; ++i) {
  572. const EmscriptenTouchPoint &touch = p_event->touches[i];
  573. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  574. lowest_id_index = i;
  575. if (!touch.isChanged)
  576. continue;
  577. ev->set_index(touch.identifier);
  578. ev->set_position(correct_canvas_position(touch.canvasX, touch.canvasY));
  579. Point2 &prev = os->touches[i];
  580. ev->set_relative(ev->get_position() - prev);
  581. prev = ev->get_position();
  582. os->input->parse_input_event(ev);
  583. }
  584. return true;
  585. }
  586. // Gamepad
  587. EM_BOOL OS_JavaScript::gamepad_change_callback(int p_event_type, const EmscriptenGamepadEvent *p_event, void *p_user_data) {
  588. InputDefault *input = get_singleton()->input;
  589. if (p_event_type == EMSCRIPTEN_EVENT_GAMEPADCONNECTED) {
  590. String guid = "";
  591. if (String::utf8(p_event->mapping) == "standard")
  592. guid = "Default HTML5 Gamepad";
  593. input->joy_connection_changed(p_event->index, true, String::utf8(p_event->id), guid);
  594. } else {
  595. input->joy_connection_changed(p_event->index, false, "");
  596. }
  597. return true;
  598. }
  599. void OS_JavaScript::process_joypads() {
  600. int joypad_count = emscripten_get_num_gamepads();
  601. for (int joypad = 0; joypad < joypad_count; joypad++) {
  602. EmscriptenGamepadEvent state;
  603. EMSCRIPTEN_RESULT query_result = emscripten_get_gamepad_status(joypad, &state);
  604. // Chromium reserves gamepads slots, so NO_DATA is an expected result.
  605. ERR_CONTINUE(query_result != EMSCRIPTEN_RESULT_SUCCESS &&
  606. query_result != EMSCRIPTEN_RESULT_NO_DATA);
  607. if (query_result == EMSCRIPTEN_RESULT_SUCCESS && state.connected) {
  608. int button_count = MIN(state.numButtons, 18);
  609. int axis_count = MIN(state.numAxes, 8);
  610. for (int button = 0; button < button_count; button++) {
  611. float value = state.analogButton[button];
  612. if (String::utf8(state.mapping) == "standard" && (button == JOY_ANALOG_L2 || button == JOY_ANALOG_R2)) {
  613. InputDefault::JoyAxis joy_axis;
  614. joy_axis.min = 0;
  615. joy_axis.value = value;
  616. input->joy_axis(joypad, button, joy_axis);
  617. } else {
  618. input->joy_button(joypad, button, value);
  619. }
  620. }
  621. for (int axis = 0; axis < axis_count; axis++) {
  622. InputDefault::JoyAxis joy_axis;
  623. joy_axis.min = -1;
  624. joy_axis.value = state.axis[axis];
  625. input->joy_axis(joypad, axis, joy_axis);
  626. }
  627. }
  628. }
  629. }
  630. bool OS_JavaScript::is_joy_known(int p_device) {
  631. return input->is_joy_mapped(p_device);
  632. }
  633. String OS_JavaScript::get_joy_guid(int p_device) const {
  634. return input->get_joy_guid_remapped(p_device);
  635. }
  636. // Video
  637. int OS_JavaScript::get_video_driver_count() const {
  638. return VIDEO_DRIVER_MAX;
  639. }
  640. const char *OS_JavaScript::get_video_driver_name(int p_driver) const {
  641. switch (p_driver) {
  642. case VIDEO_DRIVER_GLES3:
  643. return "GLES3";
  644. case VIDEO_DRIVER_GLES2:
  645. return "GLES2";
  646. }
  647. ERR_FAIL_V_MSG(NULL, "Invalid video driver index: " + itos(p_driver) + ".");
  648. }
  649. // Audio
  650. int OS_JavaScript::get_audio_driver_count() const {
  651. return 1;
  652. }
  653. const char *OS_JavaScript::get_audio_driver_name(int p_driver) const {
  654. return "JavaScript";
  655. }
  656. // Clipboard
  657. extern "C" EMSCRIPTEN_KEEPALIVE void update_clipboard(const char *p_text) {
  658. // Only call set_clipboard from OS (sets local clipboard)
  659. OS::get_singleton()->OS::set_clipboard(p_text);
  660. }
  661. void OS_JavaScript::set_clipboard(const String &p_text) {
  662. OS::set_clipboard(p_text);
  663. /* clang-format off */
  664. int err = EM_ASM_INT({
  665. var text = UTF8ToString($0);
  666. if (!navigator.clipboard || !navigator.clipboard.writeText)
  667. return 1;
  668. navigator.clipboard.writeText(text).catch(function(e) {
  669. // Setting OS clipboard is only possible from an input callback.
  670. console.error("Setting OS clipboard is only possible from an input callback for the HTML5 plafrom. Exception:", e);
  671. });
  672. return 0;
  673. }, p_text.utf8().get_data());
  674. /* clang-format on */
  675. ERR_FAIL_COND_MSG(err, "Clipboard API is not supported.");
  676. }
  677. String OS_JavaScript::get_clipboard() const {
  678. /* clang-format off */
  679. EM_ASM({
  680. try {
  681. navigator.clipboard.readText().then(function (result) {
  682. ccall('update_clipboard', 'void', ['string'], [result]);
  683. }).catch(function (e) {
  684. // Fail graciously.
  685. });
  686. } catch (e) {
  687. // Fail graciously.
  688. }
  689. });
  690. /* clang-format on */
  691. return this->OS::get_clipboard();
  692. }
  693. // Lifecycle
  694. int OS_JavaScript::get_current_video_driver() const {
  695. return video_driver_index;
  696. }
  697. void OS_JavaScript::initialize_core() {
  698. OS_Unix::initialize_core();
  699. FileAccess::make_default<FileAccessBufferedFA<FileAccessUnix> >(FileAccess::ACCESS_RESOURCES);
  700. }
  701. Error OS_JavaScript::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  702. EmscriptenWebGLContextAttributes attributes;
  703. emscripten_webgl_init_context_attributes(&attributes);
  704. attributes.alpha = false;
  705. attributes.antialias = false;
  706. ERR_FAIL_INDEX_V(p_video_driver, VIDEO_DRIVER_MAX, ERR_INVALID_PARAMETER);
  707. bool gles3 = true;
  708. if (p_video_driver == VIDEO_DRIVER_GLES2) {
  709. gles3 = false;
  710. }
  711. bool gl_initialization_error = false;
  712. while (true) {
  713. if (gles3) {
  714. if (RasterizerGLES3::is_viable() == OK) {
  715. attributes.majorVersion = 2;
  716. RasterizerGLES3::register_config();
  717. RasterizerGLES3::make_current();
  718. break;
  719. } else {
  720. if (GLOBAL_GET("rendering/quality/driver/fallback_to_gles2")) {
  721. p_video_driver = VIDEO_DRIVER_GLES2;
  722. gles3 = false;
  723. continue;
  724. } else {
  725. gl_initialization_error = true;
  726. break;
  727. }
  728. }
  729. } else {
  730. if (RasterizerGLES2::is_viable() == OK) {
  731. attributes.majorVersion = 1;
  732. RasterizerGLES2::register_config();
  733. RasterizerGLES2::make_current();
  734. break;
  735. } else {
  736. gl_initialization_error = true;
  737. break;
  738. }
  739. }
  740. }
  741. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(NULL, &attributes);
  742. if (emscripten_webgl_make_context_current(ctx) != EMSCRIPTEN_RESULT_SUCCESS) {
  743. gl_initialization_error = true;
  744. }
  745. if (gl_initialization_error) {
  746. OS::get_singleton()->alert("Your browser does not support any of the supported WebGL versions.\n"
  747. "Please update your browser version.",
  748. "Unable to initialize Video driver");
  749. return ERR_UNAVAILABLE;
  750. }
  751. video_driver_index = p_video_driver;
  752. video_mode = p_desired;
  753. // fullscreen_change_callback will correct this if the request is successful.
  754. video_mode.fullscreen = false;
  755. // Emscripten only attempts fullscreen requests if the user input callback
  756. // was registered through one its own functions, so request manually for
  757. // start-up fullscreen.
  758. if (p_desired.fullscreen) {
  759. /* clang-format off */
  760. EM_ASM({
  761. (canvas.requestFullscreen || canvas.msRequestFullscreen ||
  762. canvas.mozRequestFullScreen || canvas.mozRequestFullscreen ||
  763. canvas.webkitRequestFullscreen
  764. ).call(canvas);
  765. });
  766. /* clang-format on */
  767. }
  768. /* clang-format off */
  769. if (EM_ASM_INT_V({ return Module.resizeCanvasOnStart })) {
  770. /* clang-format on */
  771. set_window_size(Size2(video_mode.width, video_mode.height));
  772. } else {
  773. set_window_size(get_window_size());
  774. }
  775. char locale_ptr[16];
  776. /* clang-format off */
  777. EM_ASM_ARGS({
  778. stringToUTF8(Module.locale, $0, 16);
  779. }, locale_ptr);
  780. /* clang-format on */
  781. setenv("LANG", locale_ptr, true);
  782. AudioDriverManager::initialize(p_audio_driver);
  783. VisualServer *visual_server = memnew(VisualServerRaster());
  784. input = memnew(InputDefault);
  785. EMSCRIPTEN_RESULT result;
  786. #define EM_CHECK(ev) \
  787. if (result != EMSCRIPTEN_RESULT_SUCCESS) \
  788. ERR_PRINTS("Error while setting " #ev " callback: Code " + itos(result))
  789. #define SET_EM_CALLBACK(target, ev, cb) \
  790. result = emscripten_set_##ev##_callback(target, NULL, true, &cb); \
  791. EM_CHECK(ev)
  792. #define SET_EM_CALLBACK_NOTARGET(ev, cb) \
  793. result = emscripten_set_##ev##_callback(NULL, true, &cb); \
  794. EM_CHECK(ev)
  795. // These callbacks from Emscripten's html5.h suffice to access most
  796. // JavaScript APIs. For APIs that are not (sufficiently) exposed, EM_ASM
  797. // is used below.
  798. SET_EM_CALLBACK("#window", mousemove, mousemove_callback)
  799. SET_EM_CALLBACK("#canvas", mousedown, mouse_button_callback)
  800. SET_EM_CALLBACK("#window", mouseup, mouse_button_callback)
  801. SET_EM_CALLBACK("#window", wheel, wheel_callback)
  802. SET_EM_CALLBACK("#window", touchstart, touch_press_callback)
  803. SET_EM_CALLBACK("#window", touchmove, touchmove_callback)
  804. SET_EM_CALLBACK("#window", touchend, touch_press_callback)
  805. SET_EM_CALLBACK("#window", touchcancel, touch_press_callback)
  806. SET_EM_CALLBACK("#canvas", keydown, keydown_callback)
  807. SET_EM_CALLBACK("#canvas", keypress, keypress_callback)
  808. SET_EM_CALLBACK("#canvas", keyup, keyup_callback)
  809. SET_EM_CALLBACK(NULL, fullscreenchange, fullscreen_change_callback)
  810. SET_EM_CALLBACK_NOTARGET(gamepadconnected, gamepad_change_callback)
  811. SET_EM_CALLBACK_NOTARGET(gamepaddisconnected, gamepad_change_callback)
  812. #undef SET_EM_CALLBACK_NODATA
  813. #undef SET_EM_CALLBACK
  814. #undef EM_CHECK
  815. /* clang-format off */
  816. EM_ASM_ARGS({
  817. const send_notification = cwrap('send_notification', null, ['number']);
  818. const notifications = arguments;
  819. (['mouseover', 'mouseleave', 'focus', 'blur']).forEach(function(event, index) {
  820. Module.canvas.addEventListener(event, send_notification.bind(null, notifications[index]));
  821. });
  822. // Clipboard
  823. const update_clipboard = cwrap('update_clipboard', null, ['string']);
  824. window.addEventListener('paste', function(evt) {
  825. update_clipboard(evt.clipboardData.getData('text'));
  826. }, true);
  827. },
  828. MainLoop::NOTIFICATION_WM_MOUSE_ENTER,
  829. MainLoop::NOTIFICATION_WM_MOUSE_EXIT,
  830. MainLoop::NOTIFICATION_WM_FOCUS_IN,
  831. MainLoop::NOTIFICATION_WM_FOCUS_OUT
  832. );
  833. /* clang-format on */
  834. visual_server->init();
  835. return OK;
  836. }
  837. void OS_JavaScript::set_main_loop(MainLoop *p_main_loop) {
  838. main_loop = p_main_loop;
  839. input->set_main_loop(p_main_loop);
  840. }
  841. MainLoop *OS_JavaScript::get_main_loop() const {
  842. return main_loop;
  843. }
  844. void OS_JavaScript::run_async() {
  845. main_loop->init();
  846. emscripten_set_main_loop(main_loop_callback, -1, false);
  847. }
  848. void OS_JavaScript::main_loop_callback() {
  849. get_singleton()->main_loop_iterate();
  850. }
  851. bool OS_JavaScript::main_loop_iterate() {
  852. if (is_userfs_persistent() && sync_wait_time >= 0) {
  853. int64_t current_time = get_ticks_msec();
  854. int64_t elapsed_time = current_time - last_sync_check_time;
  855. last_sync_check_time = current_time;
  856. sync_wait_time -= elapsed_time;
  857. if (sync_wait_time < 0) {
  858. /* clang-format off */
  859. EM_ASM(
  860. FS.syncfs(function(error) {
  861. if (error) { err('Failed to save IDB file system: ' + error.message); }
  862. });
  863. );
  864. /* clang-format on */
  865. }
  866. }
  867. if (emscripten_sample_gamepad_data() == EMSCRIPTEN_RESULT_SUCCESS)
  868. process_joypads();
  869. if (just_exited_fullscreen) {
  870. if (window_maximized) {
  871. EmscriptenFullscreenStrategy strategy;
  872. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  873. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  874. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  875. strategy.canvasResizedCallback = NULL;
  876. emscripten_enter_soft_fullscreen(NULL, &strategy);
  877. } else {
  878. emscripten_set_canvas_element_size(NULL, windowed_size.width, windowed_size.height);
  879. }
  880. just_exited_fullscreen = false;
  881. }
  882. int canvas[2];
  883. emscripten_get_canvas_element_size(NULL, canvas, canvas + 1);
  884. video_mode.width = canvas[0];
  885. video_mode.height = canvas[1];
  886. if (!window_maximized && !video_mode.fullscreen && !just_exited_fullscreen && !entering_fullscreen) {
  887. windowed_size.width = canvas[0];
  888. windowed_size.height = canvas[1];
  889. }
  890. return Main::iteration();
  891. }
  892. void OS_JavaScript::delete_main_loop() {
  893. memdelete(main_loop);
  894. }
  895. void OS_JavaScript::finalize() {
  896. memdelete(input);
  897. }
  898. // Miscellaneous
  899. 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) {
  900. ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "OS::execute() is not available on the HTML5 platform.");
  901. }
  902. Error OS_JavaScript::kill(const ProcessID &p_pid) {
  903. ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "OS::kill() is not available on the HTML5 platform.");
  904. }
  905. int OS_JavaScript::get_process_id() const {
  906. ERR_FAIL_V_MSG(0, "OS::get_process_id() is not available on the HTML5 platform.");
  907. }
  908. extern "C" EMSCRIPTEN_KEEPALIVE void send_notification(int p_notification) {
  909. if (p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER || p_notification == MainLoop::NOTIFICATION_WM_MOUSE_EXIT) {
  910. cursor_inside_canvas = p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER;
  911. }
  912. OS_JavaScript::get_singleton()->get_main_loop()->notification(p_notification);
  913. }
  914. bool OS_JavaScript::_check_internal_feature_support(const String &p_feature) {
  915. if (p_feature == "HTML5" || p_feature == "web")
  916. return true;
  917. #ifdef JAVASCRIPT_EVAL_ENABLED
  918. if (p_feature == "JavaScript")
  919. return true;
  920. #endif
  921. return false;
  922. }
  923. void OS_JavaScript::alert(const String &p_alert, const String &p_title) {
  924. /* clang-format off */
  925. EM_ASM_({
  926. window.alert(UTF8ToString($0));
  927. }, p_alert.utf8().get_data());
  928. /* clang-format on */
  929. }
  930. void OS_JavaScript::set_window_title(const String &p_title) {
  931. /* clang-format off */
  932. EM_ASM_({
  933. document.title = UTF8ToString($0);
  934. }, p_title.utf8().get_data());
  935. /* clang-format on */
  936. }
  937. void OS_JavaScript::set_icon(const Ref<Image> &p_icon) {
  938. ERR_FAIL_COND(p_icon.is_null());
  939. Ref<Image> icon = p_icon;
  940. if (icon->is_compressed()) {
  941. icon = icon->duplicate();
  942. ERR_FAIL_COND(icon->decompress() != OK);
  943. }
  944. if (icon->get_format() != Image::FORMAT_RGBA8) {
  945. if (icon == p_icon)
  946. icon = icon->duplicate();
  947. icon->convert(Image::FORMAT_RGBA8);
  948. }
  949. png_image png_meta;
  950. memset(&png_meta, 0, sizeof png_meta);
  951. png_meta.version = PNG_IMAGE_VERSION;
  952. png_meta.width = icon->get_width();
  953. png_meta.height = icon->get_height();
  954. png_meta.format = PNG_FORMAT_RGBA;
  955. PoolByteArray png;
  956. size_t len;
  957. PoolByteArray::Read r = icon->get_data().read();
  958. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, r.ptr(), 0, NULL));
  959. png.resize(len);
  960. PoolByteArray::Write w = png.write();
  961. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, w.ptr(), &len, 0, r.ptr(), 0, NULL));
  962. w = PoolByteArray::Write();
  963. r = png.read();
  964. /* clang-format off */
  965. EM_ASM_ARGS({
  966. var PNG_PTR = $0;
  967. var PNG_LEN = $1;
  968. var png = new Blob([HEAPU8.slice(PNG_PTR, PNG_PTR + PNG_LEN)], { type: "image/png" });
  969. var url = URL.createObjectURL(png);
  970. var link = document.getElementById('-gd-engine-icon');
  971. if (link === null) {
  972. link = document.createElement('link');
  973. link.rel = 'icon';
  974. link.id = '-gd-engine-icon';
  975. document.head.appendChild(link);
  976. }
  977. link.href = url;
  978. }, r.ptr(), len);
  979. /* clang-format on */
  980. }
  981. String OS_JavaScript::get_executable_path() const {
  982. return OS::get_executable_path();
  983. }
  984. Error OS_JavaScript::shell_open(String p_uri) {
  985. // Open URI in a new tab, browser will deal with it by protocol.
  986. /* clang-format off */
  987. EM_ASM_({
  988. window.open(UTF8ToString($0), '_blank');
  989. }, p_uri.utf8().get_data());
  990. /* clang-format on */
  991. return OK;
  992. }
  993. String OS_JavaScript::get_name() const {
  994. return "HTML5";
  995. }
  996. bool OS_JavaScript::can_draw() const {
  997. return true; // Always?
  998. }
  999. String OS_JavaScript::get_user_data_dir() const {
  1000. return "/userfs";
  1001. };
  1002. String OS_JavaScript::get_resource_dir() const {
  1003. return "/";
  1004. }
  1005. OS::PowerState OS_JavaScript::get_power_state() {
  1006. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to POWERSTATE_UNKNOWN");
  1007. return OS::POWERSTATE_UNKNOWN;
  1008. }
  1009. int OS_JavaScript::get_power_seconds_left() {
  1010. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to -1");
  1011. return -1;
  1012. }
  1013. int OS_JavaScript::get_power_percent_left() {
  1014. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to -1");
  1015. return -1;
  1016. }
  1017. void OS_JavaScript::file_access_close_callback(const String &p_file, int p_flags) {
  1018. OS_JavaScript *os = get_singleton();
  1019. if (os->is_userfs_persistent() && p_file.begins_with("/userfs") && p_flags & FileAccess::WRITE) {
  1020. os->last_sync_check_time = OS::get_singleton()->get_ticks_msec();
  1021. // Wait five seconds in case more files are about to be closed.
  1022. os->sync_wait_time = 5000;
  1023. }
  1024. }
  1025. void OS_JavaScript::set_idb_available(bool p_idb_available) {
  1026. idb_available = p_idb_available;
  1027. }
  1028. bool OS_JavaScript::is_userfs_persistent() const {
  1029. return idb_available;
  1030. }
  1031. OS_JavaScript *OS_JavaScript::get_singleton() {
  1032. return static_cast<OS_JavaScript *>(OS::get_singleton());
  1033. }
  1034. OS_JavaScript::OS_JavaScript(int p_argc, char *p_argv[]) {
  1035. List<String> arguments;
  1036. for (int i = 1; i < p_argc; i++) {
  1037. arguments.push_back(String::utf8(p_argv[i]));
  1038. }
  1039. set_cmdline(p_argv[0], arguments);
  1040. last_click_button_index = -1;
  1041. last_click_ms = 0;
  1042. last_click_pos = Point2(-100, -100);
  1043. window_maximized = false;
  1044. entering_fullscreen = false;
  1045. just_exited_fullscreen = false;
  1046. main_loop = NULL;
  1047. idb_available = false;
  1048. sync_wait_time = -1;
  1049. AudioDriverManager::add_driver(&audio_driver_javascript);
  1050. Vector<Logger *> loggers;
  1051. loggers.push_back(memnew(StdLogger));
  1052. _set_logger(memnew(CompositeLogger(loggers)));
  1053. FileAccessUnix::close_notification_func = file_access_close_callback;
  1054. }