os_javascript.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259
  1. /*************************************************************************/
  2. /* os_javascript.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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/json.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. #ifndef NO_THREADS
  39. #include "servers/visual/visual_server_wrap_mt.h"
  40. #endif
  41. #include <dlfcn.h>
  42. #include <emscripten.h>
  43. #include <png.h>
  44. #include <stdlib.h>
  45. #include "dom_keys.inc"
  46. #include "godot_js.h"
  47. #define DOM_BUTTON_LEFT 0
  48. #define DOM_BUTTON_MIDDLE 1
  49. #define DOM_BUTTON_RIGHT 2
  50. #define DOM_BUTTON_XBUTTON1 3
  51. #define DOM_BUTTON_XBUTTON2 4
  52. // Quit
  53. void OS_JavaScript::request_quit_callback() {
  54. OS_JavaScript *os = get_singleton();
  55. if (os && os->get_main_loop()) {
  56. os->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
  57. }
  58. }
  59. // Files drop (implemented in JS for now).
  60. void OS_JavaScript::drop_files_callback(char **p_filev, int p_filec) {
  61. OS_JavaScript *os = get_singleton();
  62. if (!os || !os->get_main_loop()) {
  63. return;
  64. }
  65. Vector<String> files;
  66. for (int i = 0; i < p_filec; i++) {
  67. files.push_back(String::utf8(p_filev[i]));
  68. }
  69. os->get_main_loop()->drop_files(files);
  70. }
  71. void OS_JavaScript::send_notification_callback(int p_notification) {
  72. OS_JavaScript *os = get_singleton();
  73. if (!os) {
  74. return;
  75. }
  76. if (p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER || p_notification == MainLoop::NOTIFICATION_WM_MOUSE_EXIT) {
  77. os->cursor_inside_canvas = p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER;
  78. }
  79. MainLoop *loop = os->get_main_loop();
  80. if (loop) {
  81. loop->notification(p_notification);
  82. }
  83. }
  84. // Window (canvas)
  85. Point2 OS_JavaScript::compute_position_in_canvas(int p_x, int p_y) {
  86. int point[2];
  87. godot_js_display_compute_position(p_x, p_y, point, point + 1);
  88. return Point2(point[0], point[1]);
  89. }
  90. bool OS_JavaScript::check_size_force_redraw() {
  91. return godot_js_display_size_update() != 0;
  92. }
  93. EM_BOOL OS_JavaScript::fullscreen_change_callback(int p_event_type, const EmscriptenFullscreenChangeEvent *p_event, void *p_user_data) {
  94. OS_JavaScript *os = get_singleton();
  95. // Empty ID is canvas.
  96. String target_id = String::utf8(p_event->id);
  97. if (target_id.empty() || target_id == String::utf8(&(os->canvas_id[1]))) {
  98. // This event property is the only reliable data on
  99. // browser fullscreen state.
  100. os->video_mode.fullscreen = p_event->isFullscreen;
  101. if (os->video_mode.fullscreen) {
  102. os->entering_fullscreen = false;
  103. } else {
  104. // Restoring maximized window now will cause issues,
  105. // so delay until main_loop_iterate.
  106. os->just_exited_fullscreen = true;
  107. }
  108. }
  109. return false;
  110. }
  111. EM_BOOL OS_JavaScript::blur_callback(int p_event_type, const EmscriptenFocusEvent *p_event, void *p_user_data) {
  112. get_singleton()->input->release_pressed_events();
  113. return false;
  114. }
  115. void OS_JavaScript::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  116. video_mode = p_video_mode;
  117. }
  118. OS::VideoMode OS_JavaScript::get_video_mode(int p_screen) const {
  119. return video_mode;
  120. }
  121. Size2 OS_JavaScript::get_screen_size(int p_screen) const {
  122. int size[2];
  123. godot_js_display_screen_size_get(size, size + 1);
  124. return Size2(size[0], size[1]);
  125. }
  126. void OS_JavaScript::set_window_size(const Size2 p_size) {
  127. if (video_mode.fullscreen) {
  128. window_maximized = false;
  129. set_window_fullscreen(false);
  130. } else {
  131. if (window_maximized) {
  132. emscripten_exit_soft_fullscreen();
  133. window_maximized = false;
  134. }
  135. godot_js_display_desired_size_set(p_size.x, p_size.y);
  136. }
  137. }
  138. Size2 OS_JavaScript::get_window_size() const {
  139. int size[2];
  140. godot_js_display_window_size_get(size, size + 1);
  141. return Size2(size[0], size[1]);
  142. }
  143. void OS_JavaScript::set_window_maximized(bool p_enabled) {
  144. #ifndef TOOLS_ENABLED
  145. if (video_mode.fullscreen) {
  146. window_maximized = p_enabled;
  147. set_window_fullscreen(false);
  148. } else if (!p_enabled) {
  149. emscripten_exit_soft_fullscreen();
  150. window_maximized = false;
  151. } else if (!window_maximized) {
  152. // Prevent calling emscripten_enter_soft_fullscreen mutltiple times,
  153. // this would hide page elements permanently.
  154. EmscriptenFullscreenStrategy strategy;
  155. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  156. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  157. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  158. strategy.canvasResizedCallback = NULL;
  159. emscripten_enter_soft_fullscreen(canvas_id, &strategy);
  160. window_maximized = p_enabled;
  161. }
  162. #endif
  163. }
  164. bool OS_JavaScript::is_window_maximized() const {
  165. return window_maximized;
  166. }
  167. void OS_JavaScript::set_window_fullscreen(bool p_enabled) {
  168. if (p_enabled == video_mode.fullscreen) {
  169. return;
  170. }
  171. // Just request changes here, if successful, logic continues in
  172. // fullscreen_change_callback.
  173. if (p_enabled) {
  174. if (window_maximized) {
  175. // Soft fullsreen during real fullscreen can cause issues, so exit.
  176. // This must be called before requesting full screen.
  177. emscripten_exit_soft_fullscreen();
  178. }
  179. int result = godot_js_display_fullscreen_request();
  180. ERR_FAIL_COND_MSG(result, "The request was denied. Remember that enabling fullscreen is only possible from an input callback for the HTML5 platform.");
  181. entering_fullscreen = true;
  182. } else {
  183. // No logic allowed here, since exiting w/ ESC key won't use this function.
  184. ERR_FAIL_COND(godot_js_display_fullscreen_exit());
  185. }
  186. }
  187. bool OS_JavaScript::is_window_fullscreen() const {
  188. return video_mode.fullscreen;
  189. }
  190. void OS_JavaScript::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  191. Size2 screen = get_screen_size();
  192. p_list->push_back(OS::VideoMode(screen.width, screen.height, true));
  193. }
  194. bool OS_JavaScript::get_window_per_pixel_transparency_enabled() const {
  195. if (!is_layered_allowed()) {
  196. return false;
  197. }
  198. return transparency_enabled;
  199. }
  200. void OS_JavaScript::set_window_per_pixel_transparency_enabled(bool p_enabled) {
  201. if (!is_layered_allowed()) {
  202. return;
  203. }
  204. transparency_enabled = p_enabled;
  205. }
  206. // Keys
  207. template <typename T>
  208. static void dom2godot_mod(T *emscripten_event_ptr, Ref<InputEventWithModifiers> godot_event) {
  209. godot_event->set_shift(emscripten_event_ptr->shiftKey);
  210. godot_event->set_alt(emscripten_event_ptr->altKey);
  211. godot_event->set_control(emscripten_event_ptr->ctrlKey);
  212. godot_event->set_metakey(emscripten_event_ptr->metaKey);
  213. }
  214. static Ref<InputEventKey> setup_key_event(const EmscriptenKeyboardEvent *emscripten_event) {
  215. Ref<InputEventKey> ev;
  216. ev.instance();
  217. ev->set_echo(emscripten_event->repeat);
  218. dom2godot_mod(emscripten_event, ev);
  219. ev->set_scancode(dom_code2godot_scancode(emscripten_event->code, emscripten_event->key));
  220. String unicode = String::utf8(emscripten_event->key);
  221. // Check if empty or multi-character (e.g. `CapsLock`).
  222. if (unicode.length() != 1) {
  223. // Might be empty as well, but better than nonsense.
  224. unicode = String::utf8(emscripten_event->charValue);
  225. }
  226. if (unicode.length() == 1) {
  227. ev->set_unicode(unicode[0]);
  228. }
  229. return ev;
  230. }
  231. EM_BOOL OS_JavaScript::keydown_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  232. OS_JavaScript *os = get_singleton();
  233. Ref<InputEventKey> ev = setup_key_event(p_event);
  234. ev->set_pressed(true);
  235. if (ev->get_unicode() == 0 && keycode_has_unicode(ev->get_scancode())) {
  236. // Defer to keypress event for legacy unicode retrieval.
  237. os->deferred_key_event = ev;
  238. // Do not suppress keypress event.
  239. return false;
  240. }
  241. os->input->parse_input_event(ev);
  242. // Resume audio context after input in case autoplay was denied.
  243. os->resume_audio();
  244. return true;
  245. }
  246. EM_BOOL OS_JavaScript::keypress_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  247. OS_JavaScript *os = get_singleton();
  248. os->deferred_key_event->set_unicode(p_event->charCode);
  249. os->input->parse_input_event(os->deferred_key_event);
  250. return true;
  251. }
  252. EM_BOOL OS_JavaScript::keyup_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  253. Ref<InputEventKey> ev = setup_key_event(p_event);
  254. ev->set_pressed(false);
  255. get_singleton()->input->parse_input_event(ev);
  256. return ev->get_scancode() != KEY_UNKNOWN && ev->get_scancode() != 0;
  257. }
  258. // Mouse
  259. Point2 OS_JavaScript::get_mouse_position() const {
  260. return input->get_mouse_position();
  261. }
  262. int OS_JavaScript::get_mouse_button_state() const {
  263. return input->get_mouse_button_mask();
  264. }
  265. EM_BOOL OS_JavaScript::mouse_button_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) {
  266. OS_JavaScript *os = get_singleton();
  267. Ref<InputEventMouseButton> ev;
  268. ev.instance();
  269. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_MOUSEDOWN);
  270. ev->set_position(compute_position_in_canvas(p_event->clientX, p_event->clientY));
  271. ev->set_global_position(ev->get_position());
  272. dom2godot_mod(p_event, ev);
  273. switch (p_event->button) {
  274. case DOM_BUTTON_LEFT: ev->set_button_index(BUTTON_LEFT); break;
  275. case DOM_BUTTON_MIDDLE: ev->set_button_index(BUTTON_MIDDLE); break;
  276. case DOM_BUTTON_RIGHT: ev->set_button_index(BUTTON_RIGHT); break;
  277. case DOM_BUTTON_XBUTTON1: ev->set_button_index(BUTTON_XBUTTON1); break;
  278. case DOM_BUTTON_XBUTTON2: ev->set_button_index(BUTTON_XBUTTON2); break;
  279. default: return false;
  280. }
  281. if (ev->is_pressed()) {
  282. double diff = emscripten_get_now() - os->last_click_ms;
  283. if (ev->get_button_index() == os->last_click_button_index) {
  284. if (diff < 400 && Point2(os->last_click_pos).distance_to(ev->get_position()) < 5) {
  285. os->last_click_ms = 0;
  286. os->last_click_pos = Point2(-100, -100);
  287. os->last_click_button_index = -1;
  288. ev->set_doubleclick(true);
  289. }
  290. } else {
  291. os->last_click_button_index = ev->get_button_index();
  292. }
  293. if (!ev->is_doubleclick()) {
  294. os->last_click_ms += diff;
  295. os->last_click_pos = ev->get_position();
  296. }
  297. }
  298. int mask = os->input->get_mouse_button_mask();
  299. int button_flag = 1 << (ev->get_button_index() - 1);
  300. if (ev->is_pressed()) {
  301. // Since the event is consumed, focus manually. The containing iframe,
  302. // if exists, may not have focus yet, so focus even if already focused.
  303. godot_js_display_canvas_focus();
  304. mask |= button_flag;
  305. } else if (mask & button_flag) {
  306. mask &= ~button_flag;
  307. } else {
  308. // Received release event, but press was outside the canvas, so ignore.
  309. return false;
  310. }
  311. ev->set_button_mask(mask);
  312. os->input->parse_input_event(ev);
  313. // Resume audio context after input in case autoplay was denied.
  314. os->resume_audio();
  315. // Prevent multi-click text selection and wheel-click scrolling anchor.
  316. // Context menu is prevented through contextmenu event.
  317. return true;
  318. }
  319. EM_BOOL OS_JavaScript::mousemove_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) {
  320. OS_JavaScript *os = get_singleton();
  321. int input_mask = os->input->get_mouse_button_mask();
  322. Point2 pos = compute_position_in_canvas(p_event->clientX, p_event->clientY);
  323. // For motion outside the canvas, only read mouse movement if dragging
  324. // started inside the canvas; imitating desktop app behaviour.
  325. if (!os->cursor_inside_canvas && !input_mask)
  326. return false;
  327. Ref<InputEventMouseMotion> ev;
  328. ev.instance();
  329. dom2godot_mod(p_event, ev);
  330. ev->set_button_mask(input_mask);
  331. ev->set_position(pos);
  332. ev->set_global_position(ev->get_position());
  333. ev->set_relative(Vector2(p_event->movementX, p_event->movementY));
  334. os->input->set_mouse_position(ev->get_position());
  335. ev->set_speed(os->input->get_last_mouse_speed());
  336. os->input->parse_input_event(ev);
  337. // Don't suppress mouseover/-leave events.
  338. return false;
  339. }
  340. static const char *godot2dom_cursor(OS::CursorShape p_shape) {
  341. switch (p_shape) {
  342. case OS::CURSOR_ARROW:
  343. default:
  344. return "auto";
  345. case OS::CURSOR_IBEAM: return "text";
  346. case OS::CURSOR_POINTING_HAND: return "pointer";
  347. case OS::CURSOR_CROSS: return "crosshair";
  348. case OS::CURSOR_WAIT: return "progress";
  349. case OS::CURSOR_BUSY: return "wait";
  350. case OS::CURSOR_DRAG: return "grab";
  351. case OS::CURSOR_CAN_DROP: return "grabbing";
  352. case OS::CURSOR_FORBIDDEN: return "no-drop";
  353. case OS::CURSOR_VSIZE: return "ns-resize";
  354. case OS::CURSOR_HSIZE: return "ew-resize";
  355. case OS::CURSOR_BDIAGSIZE: return "nesw-resize";
  356. case OS::CURSOR_FDIAGSIZE: return "nwse-resize";
  357. case OS::CURSOR_MOVE: return "move";
  358. case OS::CURSOR_VSPLIT: return "row-resize";
  359. case OS::CURSOR_HSPLIT: return "col-resize";
  360. case OS::CURSOR_HELP: return "help";
  361. }
  362. }
  363. void OS_JavaScript::set_cursor_shape(CursorShape p_shape) {
  364. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  365. if (cursor_shape == p_shape) {
  366. return;
  367. }
  368. cursor_shape = p_shape;
  369. godot_js_display_cursor_set_shape(godot2dom_cursor(cursor_shape));
  370. }
  371. void OS_JavaScript::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  372. if (p_cursor.is_valid()) {
  373. Ref<Texture> texture = p_cursor;
  374. Ref<AtlasTexture> atlas_texture = p_cursor;
  375. Ref<Image> image;
  376. Size2 texture_size;
  377. Rect2 atlas_rect;
  378. if (texture.is_valid()) {
  379. image = texture->get_data();
  380. if (image.is_valid()) {
  381. image->duplicate();
  382. }
  383. }
  384. if (!image.is_valid() && atlas_texture.is_valid()) {
  385. texture = atlas_texture->get_atlas();
  386. atlas_rect.size.width = texture->get_width();
  387. atlas_rect.size.height = texture->get_height();
  388. atlas_rect.position.x = atlas_texture->get_region().position.x;
  389. atlas_rect.position.y = atlas_texture->get_region().position.y;
  390. texture_size.width = atlas_texture->get_region().size.x;
  391. texture_size.height = atlas_texture->get_region().size.y;
  392. } else if (image.is_valid()) {
  393. texture_size.width = texture->get_width();
  394. texture_size.height = texture->get_height();
  395. }
  396. ERR_FAIL_COND(!texture.is_valid());
  397. ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
  398. ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
  399. ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
  400. image = texture->get_data();
  401. ERR_FAIL_COND(!image.is_valid());
  402. image = image->duplicate();
  403. if (atlas_texture.is_valid())
  404. image->crop_from_point(
  405. atlas_rect.position.x,
  406. atlas_rect.position.y,
  407. texture_size.width,
  408. texture_size.height);
  409. if (image->get_format() != Image::FORMAT_RGBA8) {
  410. image->convert(Image::FORMAT_RGBA8);
  411. }
  412. png_image png_meta;
  413. memset(&png_meta, 0, sizeof png_meta);
  414. png_meta.version = PNG_IMAGE_VERSION;
  415. png_meta.width = texture_size.width;
  416. png_meta.height = texture_size.height;
  417. png_meta.format = PNG_FORMAT_RGBA;
  418. PoolByteArray png;
  419. size_t len;
  420. PoolByteArray::Read r = image->get_data().read();
  421. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, r.ptr(), 0, NULL));
  422. png.resize(len);
  423. PoolByteArray::Write w = png.write();
  424. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, w.ptr(), &len, 0, r.ptr(), 0, NULL));
  425. w = PoolByteArray::Write();
  426. r = png.read();
  427. godot_js_display_cursor_set_custom_shape(godot2dom_cursor(p_shape), r.ptr(), len, p_hotspot.x, p_hotspot.y);
  428. r = PoolByteArray::Read();
  429. } else {
  430. godot_js_display_cursor_set_custom_shape(godot2dom_cursor(p_shape), NULL, 0, 0, 0);
  431. }
  432. }
  433. void OS_JavaScript::set_mouse_mode(OS::MouseMode p_mode) {
  434. ERR_FAIL_COND_MSG(p_mode == MOUSE_MODE_CONFINED, "MOUSE_MODE_CONFINED is not supported for the HTML5 platform.");
  435. if (p_mode == get_mouse_mode())
  436. return;
  437. if (p_mode == MOUSE_MODE_VISIBLE) {
  438. godot_js_display_cursor_set_visible(1);
  439. emscripten_exit_pointerlock();
  440. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  441. godot_js_display_cursor_set_visible(0);
  442. emscripten_exit_pointerlock();
  443. } else if (p_mode == MOUSE_MODE_CAPTURED) {
  444. godot_js_display_cursor_set_visible(1);
  445. EMSCRIPTEN_RESULT result = emscripten_request_pointerlock(canvas_id, false);
  446. ERR_FAIL_COND_MSG(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED, "MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback.");
  447. ERR_FAIL_COND_MSG(result != EMSCRIPTEN_RESULT_SUCCESS, "MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback.");
  448. }
  449. }
  450. OS::MouseMode OS_JavaScript::get_mouse_mode() const {
  451. if (godot_js_display_cursor_is_hidden())
  452. return MOUSE_MODE_HIDDEN;
  453. EmscriptenPointerlockChangeEvent ev;
  454. emscripten_get_pointerlock_status(&ev);
  455. return (ev.isActive && String::utf8(ev.id) == String::utf8(&canvas_id[1])) ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE;
  456. }
  457. // Wheel
  458. EM_BOOL OS_JavaScript::wheel_callback(int p_event_type, const EmscriptenWheelEvent *p_event, void *p_user_data) {
  459. ERR_FAIL_COND_V(p_event_type != EMSCRIPTEN_EVENT_WHEEL, false);
  460. OS_JavaScript *os = get_singleton();
  461. if (!godot_js_display_canvas_is_focused()) {
  462. if (os->cursor_inside_canvas) {
  463. godot_js_display_canvas_focus();
  464. } else {
  465. return false;
  466. }
  467. }
  468. InputDefault *input = os->input;
  469. Ref<InputEventMouseButton> ev;
  470. ev.instance();
  471. ev->set_position(input->get_mouse_position());
  472. ev->set_global_position(ev->get_position());
  473. ev->set_shift(input->is_key_pressed(KEY_SHIFT));
  474. ev->set_alt(input->is_key_pressed(KEY_ALT));
  475. ev->set_control(input->is_key_pressed(KEY_CONTROL));
  476. ev->set_metakey(input->is_key_pressed(KEY_META));
  477. if (p_event->deltaY < 0)
  478. ev->set_button_index(BUTTON_WHEEL_UP);
  479. else if (p_event->deltaY > 0)
  480. ev->set_button_index(BUTTON_WHEEL_DOWN);
  481. else if (p_event->deltaX > 0)
  482. ev->set_button_index(BUTTON_WHEEL_LEFT);
  483. else if (p_event->deltaX < 0)
  484. ev->set_button_index(BUTTON_WHEEL_RIGHT);
  485. else
  486. return false;
  487. // Different browsers give wildly different delta values, and we can't
  488. // interpret deltaMode, so use default value for wheel events' factor.
  489. int button_flag = 1 << (ev->get_button_index() - 1);
  490. ev->set_pressed(true);
  491. ev->set_button_mask(input->get_mouse_button_mask() | button_flag);
  492. input->parse_input_event(ev);
  493. ev->set_pressed(false);
  494. ev->set_button_mask(input->get_mouse_button_mask() & ~button_flag);
  495. input->parse_input_event(ev);
  496. return true;
  497. }
  498. // Touch
  499. bool OS_JavaScript::has_touchscreen_ui_hint() const {
  500. return godot_js_display_touchscreen_is_available();
  501. }
  502. EM_BOOL OS_JavaScript::touch_press_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  503. OS_JavaScript *os = get_singleton();
  504. Ref<InputEventScreenTouch> ev;
  505. ev.instance();
  506. int lowest_id_index = -1;
  507. for (int i = 0; i < p_event->numTouches; ++i) {
  508. const EmscriptenTouchPoint &touch = p_event->touches[i];
  509. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  510. lowest_id_index = i;
  511. if (!touch.isChanged)
  512. continue;
  513. ev->set_index(touch.identifier);
  514. ev->set_position(compute_position_in_canvas(touch.clientX, touch.clientY));
  515. os->touches[i] = ev->get_position();
  516. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_TOUCHSTART);
  517. os->input->parse_input_event(ev);
  518. }
  519. // Resume audio context after input in case autoplay was denied.
  520. os->resume_audio();
  521. return true;
  522. }
  523. EM_BOOL OS_JavaScript::touchmove_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  524. OS_JavaScript *os = get_singleton();
  525. Ref<InputEventScreenDrag> ev;
  526. ev.instance();
  527. int lowest_id_index = -1;
  528. for (int i = 0; i < p_event->numTouches; ++i) {
  529. const EmscriptenTouchPoint &touch = p_event->touches[i];
  530. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  531. lowest_id_index = i;
  532. if (!touch.isChanged)
  533. continue;
  534. ev->set_index(touch.identifier);
  535. ev->set_position(compute_position_in_canvas(touch.clientX, touch.clientY));
  536. Point2 &prev = os->touches[i];
  537. ev->set_relative(ev->get_position() - prev);
  538. prev = ev->get_position();
  539. os->input->parse_input_event(ev);
  540. }
  541. return true;
  542. }
  543. // Gamepad
  544. void OS_JavaScript::gamepad_callback(int p_index, int p_connected, const char *p_id, const char *p_guid) {
  545. InputDefault *input = get_singleton()->input;
  546. if (p_connected) {
  547. input->joy_connection_changed(p_index, true, String::utf8(p_id), String::utf8(p_guid));
  548. } else {
  549. input->joy_connection_changed(p_index, false, "");
  550. }
  551. }
  552. void OS_JavaScript::process_joypads() {
  553. int32_t pads = godot_js_display_gamepad_sample_count();
  554. int32_t s_btns_num = 0;
  555. int32_t s_axes_num = 0;
  556. int32_t s_standard = 0;
  557. float s_btns[16];
  558. float s_axes[10];
  559. for (int idx = 0; idx < pads; idx++) {
  560. int err = godot_js_display_gamepad_sample_get(idx, s_btns, &s_btns_num, s_axes, &s_axes_num, &s_standard);
  561. if (err) {
  562. continue;
  563. }
  564. for (int b = 0; b < s_btns_num; b++) {
  565. float value = s_btns[b];
  566. // Buttons 6 and 7 in the standard mapping need to be
  567. // axis to be handled as JOY_ANALOG by Godot.
  568. if (s_standard && (b == 6 || b == 7)) {
  569. InputDefault::JoyAxis joy_axis;
  570. joy_axis.min = 0;
  571. joy_axis.value = value;
  572. int a = b == 6 ? JOY_ANALOG_L2 : JOY_ANALOG_R2;
  573. input->joy_axis(idx, a, joy_axis);
  574. } else {
  575. input->joy_button(idx, b, value);
  576. }
  577. }
  578. for (int a = 0; a < s_axes_num; a++) {
  579. InputDefault::JoyAxis joy_axis;
  580. joy_axis.min = -1;
  581. joy_axis.value = s_axes[a];
  582. input->joy_axis(idx, a, joy_axis);
  583. }
  584. }
  585. }
  586. bool OS_JavaScript::is_joy_known(int p_device) {
  587. return input->is_joy_mapped(p_device);
  588. }
  589. String OS_JavaScript::get_joy_guid(int p_device) const {
  590. return input->get_joy_guid_remapped(p_device);
  591. }
  592. // Video
  593. int OS_JavaScript::get_video_driver_count() const {
  594. return VIDEO_DRIVER_MAX;
  595. }
  596. const char *OS_JavaScript::get_video_driver_name(int p_driver) const {
  597. switch (p_driver) {
  598. case VIDEO_DRIVER_GLES3:
  599. return "GLES3";
  600. case VIDEO_DRIVER_GLES2:
  601. return "GLES2";
  602. }
  603. ERR_FAIL_V_MSG(NULL, "Invalid video driver index: " + itos(p_driver) + ".");
  604. }
  605. // Audio
  606. int OS_JavaScript::get_audio_driver_count() const {
  607. return 1;
  608. }
  609. const char *OS_JavaScript::get_audio_driver_name(int p_driver) const {
  610. return "JavaScript";
  611. }
  612. // Clipboard
  613. void OS_JavaScript::update_clipboard_callback(const char *p_text) {
  614. // Only call set_clipboard from OS (sets local clipboard)
  615. get_singleton()->OS::set_clipboard(p_text);
  616. }
  617. void OS_JavaScript::set_clipboard(const String &p_text) {
  618. OS::set_clipboard(p_text);
  619. int err = godot_js_display_clipboard_set(p_text.utf8().get_data());
  620. ERR_FAIL_COND_MSG(err, "Clipboard API is not supported.");
  621. }
  622. String OS_JavaScript::get_clipboard() const {
  623. godot_js_display_clipboard_get(update_clipboard_callback);
  624. return this->OS::get_clipboard();
  625. }
  626. // Lifecycle
  627. int OS_JavaScript::get_current_video_driver() const {
  628. return video_driver_index;
  629. }
  630. void OS_JavaScript::initialize_core() {
  631. OS_Unix::initialize_core();
  632. }
  633. Error OS_JavaScript::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  634. video_mode = p_desired;
  635. // fullscreen_change_callback will correct this if the request is successful.
  636. video_mode.fullscreen = false;
  637. // Handle contextmenu, webglcontextlost, initial canvas setup.
  638. godot_js_display_setup_canvas(video_mode.width, video_mode.height, video_mode.fullscreen, is_hidpi_allowed() ? 1 : 0);
  639. swap_ok_cancel = godot_js_display_is_swap_ok_cancel() == 1;
  640. EmscriptenWebGLContextAttributes attributes;
  641. emscripten_webgl_init_context_attributes(&attributes);
  642. attributes.alpha = GLOBAL_GET("display/window/per_pixel_transparency/allowed");
  643. attributes.antialias = false;
  644. attributes.explicitSwapControl = true;
  645. ERR_FAIL_INDEX_V(p_video_driver, VIDEO_DRIVER_MAX, ERR_INVALID_PARAMETER);
  646. if (p_desired.layered) {
  647. set_window_per_pixel_transparency_enabled(true);
  648. }
  649. #ifdef TOOLS_ENABLED
  650. bool gles3 = false;
  651. #else
  652. bool gles3 = true;
  653. if (p_video_driver == VIDEO_DRIVER_GLES2) {
  654. gles3 = false;
  655. }
  656. #endif
  657. bool gl_initialization_error = false;
  658. while (true) {
  659. if (gles3) {
  660. if (godot_js_display_has_webgl(2) && RasterizerGLES3::is_viable() == OK) {
  661. attributes.majorVersion = 2;
  662. RasterizerGLES3::register_config();
  663. RasterizerGLES3::make_current();
  664. break;
  665. } else {
  666. if (GLOBAL_GET("rendering/quality/driver/fallback_to_gles2")) {
  667. p_video_driver = VIDEO_DRIVER_GLES2;
  668. gles3 = false;
  669. continue;
  670. } else {
  671. gl_initialization_error = true;
  672. break;
  673. }
  674. }
  675. } else {
  676. if (godot_js_display_has_webgl(1) && RasterizerGLES2::is_viable() == OK) {
  677. attributes.majorVersion = 1;
  678. RasterizerGLES2::register_config();
  679. RasterizerGLES2::make_current();
  680. break;
  681. } else {
  682. gl_initialization_error = true;
  683. break;
  684. }
  685. }
  686. }
  687. webgl_ctx = emscripten_webgl_create_context(canvas_id, &attributes);
  688. if (emscripten_webgl_make_context_current(webgl_ctx) != EMSCRIPTEN_RESULT_SUCCESS) {
  689. gl_initialization_error = true;
  690. }
  691. if (gl_initialization_error) {
  692. OS::get_singleton()->alert("Your browser does not support any of the supported WebGL versions.\n"
  693. "Please update your browser version.",
  694. "Unable to initialize Video driver");
  695. return ERR_UNAVAILABLE;
  696. }
  697. video_driver_index = p_video_driver;
  698. AudioDriverManager::initialize(p_audio_driver);
  699. visual_server = memnew(VisualServerRaster());
  700. #ifndef NO_THREADS
  701. visual_server = memnew(VisualServerWrapMT(visual_server, false));
  702. #endif
  703. input = memnew(InputDefault);
  704. EMSCRIPTEN_RESULT result;
  705. #define EM_CHECK(ev) \
  706. if (result != EMSCRIPTEN_RESULT_SUCCESS) \
  707. ERR_PRINTS("Error while setting " #ev " callback: Code " + itos(result))
  708. #define SET_EM_CALLBACK(target, ev, cb) \
  709. result = emscripten_set_##ev##_callback(target, NULL, true, &cb); \
  710. EM_CHECK(ev)
  711. #define SET_EM_WINDOW_CALLBACK(ev, cb) \
  712. result = emscripten_set_##ev##_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, false, &cb); \
  713. EM_CHECK(ev)
  714. // These callbacks from Emscripten's html5.h suffice to access most
  715. // JavaScript APIs.
  716. SET_EM_CALLBACK(canvas_id, mousedown, mouse_button_callback)
  717. SET_EM_WINDOW_CALLBACK(mousemove, mousemove_callback)
  718. SET_EM_WINDOW_CALLBACK(mouseup, mouse_button_callback)
  719. SET_EM_WINDOW_CALLBACK(blur, blur_callback)
  720. SET_EM_CALLBACK(canvas_id, wheel, wheel_callback)
  721. SET_EM_CALLBACK(canvas_id, touchstart, touch_press_callback)
  722. SET_EM_CALLBACK(canvas_id, touchmove, touchmove_callback)
  723. SET_EM_CALLBACK(canvas_id, touchend, touch_press_callback)
  724. SET_EM_CALLBACK(canvas_id, touchcancel, touch_press_callback)
  725. SET_EM_CALLBACK(canvas_id, keydown, keydown_callback)
  726. SET_EM_CALLBACK(canvas_id, keypress, keypress_callback)
  727. SET_EM_CALLBACK(canvas_id, keyup, keyup_callback)
  728. SET_EM_CALLBACK(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, fullscreenchange, fullscreen_change_callback)
  729. #undef SET_EM_CALLBACK
  730. #undef EM_CHECK
  731. // For APIs that are not (sufficiently) exposed, a
  732. // library is used below (implemented in library_godot_display.js).
  733. godot_js_display_notification_cb(&OS_JavaScript::send_notification_callback,
  734. MainLoop::NOTIFICATION_WM_MOUSE_ENTER,
  735. MainLoop::NOTIFICATION_WM_MOUSE_EXIT,
  736. MainLoop::NOTIFICATION_WM_FOCUS_IN,
  737. MainLoop::NOTIFICATION_WM_FOCUS_OUT);
  738. godot_js_display_paste_cb(&OS_JavaScript::update_clipboard_callback);
  739. godot_js_display_drop_files_cb(&OS_JavaScript::drop_files_callback);
  740. godot_js_display_gamepad_cb(&OS_JavaScript::gamepad_callback);
  741. godot_js_display_vk_cb(&input_text_callback);
  742. visual_server->init();
  743. return OK;
  744. }
  745. void OS_JavaScript::input_text_callback(const char *p_text, int p_cursor) {
  746. OS_JavaScript *os = OS_JavaScript::get_singleton();
  747. if (!os || !os->get_main_loop()) {
  748. return;
  749. }
  750. os->get_main_loop()->input_text(String::utf8(p_text));
  751. Ref<InputEventKey> k;
  752. for (int i = 0; i < p_cursor; i++) {
  753. k.instance();
  754. k->set_pressed(true);
  755. k->set_echo(false);
  756. k->set_scancode(KEY_RIGHT);
  757. os->input->parse_input_event(k);
  758. k.instance();
  759. k->set_pressed(false);
  760. k->set_echo(false);
  761. k->set_scancode(KEY_RIGHT);
  762. os->input->parse_input_event(k);
  763. }
  764. }
  765. bool OS_JavaScript::has_virtual_keyboard() const {
  766. return godot_js_display_vk_available() != 0;
  767. }
  768. void OS_JavaScript::show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect, bool p_multiline, int p_max_input_length, int p_cursor_start, int p_cursor_end) {
  769. godot_js_display_vk_show(p_existing_text.utf8().get_data(), p_multiline, p_cursor_start, p_cursor_end);
  770. }
  771. void OS_JavaScript::hide_virtual_keyboard() {
  772. godot_js_display_vk_hide();
  773. }
  774. bool OS_JavaScript::get_swap_ok_cancel() {
  775. return swap_ok_cancel;
  776. }
  777. void OS_JavaScript::swap_buffers() {
  778. emscripten_webgl_commit_frame();
  779. }
  780. void OS_JavaScript::set_main_loop(MainLoop *p_main_loop) {
  781. main_loop = p_main_loop;
  782. input->set_main_loop(p_main_loop);
  783. }
  784. MainLoop *OS_JavaScript::get_main_loop() const {
  785. return main_loop;
  786. }
  787. void OS_JavaScript::resume_audio() {
  788. if (audio_driver_javascript) {
  789. audio_driver_javascript->resume();
  790. }
  791. }
  792. void OS_JavaScript::fs_sync_callback() {
  793. get_singleton()->idb_is_syncing = false;
  794. }
  795. bool OS_JavaScript::main_loop_iterate() {
  796. if (is_userfs_persistent() && idb_needs_sync && !idb_is_syncing) {
  797. idb_is_syncing = true;
  798. idb_needs_sync = false;
  799. godot_js_os_fs_sync(&OS_JavaScript::fs_sync_callback);
  800. }
  801. if (godot_js_display_gamepad_sample() == OK)
  802. process_joypads();
  803. if (just_exited_fullscreen) {
  804. if (window_maximized) {
  805. EmscriptenFullscreenStrategy strategy;
  806. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  807. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  808. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  809. strategy.canvasResizedCallback = NULL;
  810. emscripten_enter_soft_fullscreen(canvas_id, &strategy);
  811. } else {
  812. godot_js_display_size_update();
  813. }
  814. just_exited_fullscreen = false;
  815. }
  816. return Main::iteration();
  817. }
  818. int OS_JavaScript::get_screen_dpi(int p_screen) const {
  819. return godot_js_display_screen_dpi_get();
  820. }
  821. float OS_JavaScript::get_screen_scale(int p_screen) const {
  822. return godot_js_display_pixel_ratio_get();
  823. }
  824. float OS_JavaScript::get_screen_max_scale() const {
  825. return get_screen_scale();
  826. }
  827. void OS_JavaScript::delete_main_loop() {
  828. memdelete(main_loop);
  829. main_loop = NULL;
  830. }
  831. void OS_JavaScript::finalize() {
  832. memdelete(input);
  833. visual_server->finish();
  834. emscripten_webgl_commit_frame();
  835. memdelete(visual_server);
  836. emscripten_webgl_destroy_context(webgl_ctx);
  837. if (audio_driver_javascript) {
  838. memdelete(audio_driver_javascript);
  839. }
  840. }
  841. // Miscellaneous
  842. 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) {
  843. Array args;
  844. for (const List<String>::Element *E = p_arguments.front(); E; E = E->next()) {
  845. args.push_back(E->get());
  846. }
  847. String json_args = JSON::print(args);
  848. int failed = godot_js_os_execute(json_args.utf8().get_data());
  849. ERR_FAIL_COND_V_MSG(failed, ERR_UNAVAILABLE, "OS::execute() must be implemented in Javascript via 'engine.setOnExecute' if required.");
  850. return OK;
  851. }
  852. Error OS_JavaScript::kill(const ProcessID &p_pid) {
  853. ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "OS::kill() is not available on the HTML5 platform.");
  854. }
  855. int OS_JavaScript::get_process_id() const {
  856. ERR_FAIL_V_MSG(0, "OS::get_process_id() is not available on the HTML5 platform.");
  857. }
  858. int OS_JavaScript::get_processor_count() const {
  859. return godot_js_os_hw_concurrency_get();
  860. }
  861. bool OS_JavaScript::_check_internal_feature_support(const String &p_feature) {
  862. if (p_feature == "HTML5" || p_feature == "web") {
  863. return true;
  864. }
  865. #ifdef JAVASCRIPT_EVAL_ENABLED
  866. if (p_feature == "JavaScript") {
  867. return true;
  868. }
  869. #endif
  870. #ifndef NO_THREADS
  871. if (p_feature == "threads") {
  872. return true;
  873. }
  874. #endif
  875. #if WASM_GDNATIVE
  876. if (p_feature == "wasm32") {
  877. return true;
  878. }
  879. #endif
  880. return false;
  881. }
  882. void OS_JavaScript::alert(const String &p_alert, const String &p_title) {
  883. godot_js_display_alert(p_alert.utf8().get_data());
  884. }
  885. void OS_JavaScript::set_window_title(const String &p_title) {
  886. godot_js_display_window_title_set(p_title.utf8().get_data());
  887. }
  888. void OS_JavaScript::set_icon(const Ref<Image> &p_icon) {
  889. ERR_FAIL_COND(p_icon.is_null());
  890. Ref<Image> icon = p_icon;
  891. if (icon->is_compressed()) {
  892. icon = icon->duplicate();
  893. ERR_FAIL_COND(icon->decompress() != OK);
  894. }
  895. if (icon->get_format() != Image::FORMAT_RGBA8) {
  896. if (icon == p_icon)
  897. icon = icon->duplicate();
  898. icon->convert(Image::FORMAT_RGBA8);
  899. }
  900. png_image png_meta;
  901. memset(&png_meta, 0, sizeof png_meta);
  902. png_meta.version = PNG_IMAGE_VERSION;
  903. png_meta.width = icon->get_width();
  904. png_meta.height = icon->get_height();
  905. png_meta.format = PNG_FORMAT_RGBA;
  906. PoolByteArray png;
  907. size_t len;
  908. PoolByteArray::Read r = icon->get_data().read();
  909. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, r.ptr(), 0, NULL));
  910. png.resize(len);
  911. PoolByteArray::Write w = png.write();
  912. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, w.ptr(), &len, 0, r.ptr(), 0, NULL));
  913. w = PoolByteArray::Write();
  914. r = png.read();
  915. godot_js_display_window_icon_set(r.ptr(), len);
  916. }
  917. String OS_JavaScript::get_executable_path() const {
  918. return OS::get_executable_path();
  919. }
  920. Error OS_JavaScript::shell_open(String p_uri) {
  921. // Open URI in a new tab, browser will deal with it by protocol.
  922. godot_js_os_shell_open(p_uri.utf8().get_data());
  923. return OK;
  924. }
  925. String OS_JavaScript::get_name() const {
  926. return "HTML5";
  927. }
  928. bool OS_JavaScript::can_draw() const {
  929. return true; // Always?
  930. }
  931. String OS_JavaScript::get_user_data_dir() const {
  932. return "/userfs";
  933. };
  934. String OS_JavaScript::get_cache_path() const {
  935. return "/home/web_user/.cache";
  936. }
  937. String OS_JavaScript::get_config_path() const {
  938. return "/home/web_user/.config";
  939. }
  940. String OS_JavaScript::get_data_path() const {
  941. return "/home/web_user/.local/share";
  942. }
  943. OS::PowerState OS_JavaScript::get_power_state() {
  944. WARN_PRINT_ONCE("Power management is not supported for the HTML5 platform, defaulting to POWERSTATE_UNKNOWN");
  945. return OS::POWERSTATE_UNKNOWN;
  946. }
  947. int OS_JavaScript::get_power_seconds_left() {
  948. WARN_PRINT_ONCE("Power management is not supported for the HTML5 platform, defaulting to -1");
  949. return -1;
  950. }
  951. int OS_JavaScript::get_power_percent_left() {
  952. WARN_PRINT_ONCE("Power management is not supported for the HTML5 platform, defaulting to -1");
  953. return -1;
  954. }
  955. void OS_JavaScript::file_access_close_callback(const String &p_file, int p_flags) {
  956. OS_JavaScript *os = get_singleton();
  957. if (!(os->is_userfs_persistent() && p_flags & FileAccess::WRITE)) {
  958. return; // FS persistence is not working or we are not writing.
  959. }
  960. bool is_file_persistent = p_file.begins_with("/userfs");
  961. #ifdef TOOLS_ENABLED
  962. // Hack for editor persistence (can we track).
  963. is_file_persistent = is_file_persistent || p_file.begins_with("/home/web_user/");
  964. #endif
  965. if (is_file_persistent) {
  966. os->idb_needs_sync = true;
  967. }
  968. }
  969. bool OS_JavaScript::is_userfs_persistent() const {
  970. return idb_available;
  971. }
  972. Error OS_JavaScript::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
  973. String path = p_path.get_file();
  974. p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
  975. ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, "Can't open dynamic library: " + p_path + ". Error: " + dlerror());
  976. return OK;
  977. }
  978. OS_JavaScript *OS_JavaScript::get_singleton() {
  979. return static_cast<OS_JavaScript *>(OS::get_singleton());
  980. }
  981. OS_JavaScript::OS_JavaScript() {
  982. // Expose method for requesting quit.
  983. godot_js_os_request_quit_cb(&request_quit_callback);
  984. // Set canvas ID
  985. godot_js_config_canvas_id_get(canvas_id, sizeof(canvas_id));
  986. cursor_inside_canvas = true;
  987. cursor_shape = OS::CURSOR_ARROW;
  988. last_click_button_index = -1;
  989. last_click_ms = 0;
  990. last_click_pos = Point2(-100, -100);
  991. window_maximized = false;
  992. entering_fullscreen = false;
  993. just_exited_fullscreen = false;
  994. transparency_enabled = false;
  995. main_loop = NULL;
  996. visual_server = NULL;
  997. audio_driver_javascript = NULL;
  998. swap_ok_cancel = false;
  999. idb_available = godot_js_os_fs_is_persistent() != 0;
  1000. idb_needs_sync = false;
  1001. idb_is_syncing = false;
  1002. if (AudioDriverJavaScript::is_available()) {
  1003. audio_driver_javascript = memnew(AudioDriverJavaScript);
  1004. AudioDriverManager::add_driver(audio_driver_javascript);
  1005. }
  1006. Vector<Logger *> loggers;
  1007. loggers.push_back(memnew(StdLogger));
  1008. _set_logger(memnew(CompositeLogger(loggers)));
  1009. FileAccessUnix::close_notification_func = file_access_close_callback;
  1010. }