2
0

os_javascript.cpp 39 KB

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