os_javascript.cpp 40 KB

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