os_javascript.cpp 40 KB

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