display_server_javascript.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193
  1. /*************************************************************************/
  2. /* display_server_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 "platform/javascript/display_server_javascript.h"
  31. #include "drivers/dummy/rasterizer_dummy.h"
  32. #include "platform/javascript/os_javascript.h"
  33. #include <emscripten.h>
  34. #include <png.h>
  35. #include "dom_keys.inc"
  36. #define DOM_BUTTON_LEFT 0
  37. #define DOM_BUTTON_MIDDLE 1
  38. #define DOM_BUTTON_RIGHT 2
  39. #define DOM_BUTTON_XBUTTON1 3
  40. #define DOM_BUTTON_XBUTTON2 4
  41. DisplayServerJavaScript *DisplayServerJavaScript::get_singleton() {
  42. return static_cast<DisplayServerJavaScript *>(DisplayServer::get_singleton());
  43. }
  44. // Window (canvas)
  45. extern "C" EMSCRIPTEN_KEEPALIVE void _set_canvas_id(uint8_t *p_data, int p_data_size) {
  46. DisplayServerJavaScript *display = DisplayServerJavaScript::get_singleton();
  47. display->canvas_id.parse_utf8((const char *)p_data, p_data_size);
  48. display->canvas_id = "#" + display->canvas_id;
  49. }
  50. static void focus_canvas() {
  51. /* clang-format off */
  52. EM_ASM(
  53. Module['canvas'].focus();
  54. );
  55. /* clang-format on */
  56. }
  57. static bool is_canvas_focused() {
  58. /* clang-format off */
  59. return EM_ASM_INT_V(
  60. return document.activeElement == Module['canvas'];
  61. );
  62. /* clang-format on */
  63. }
  64. static Point2 compute_position_in_canvas(int x, int y) {
  65. DisplayServerJavaScript *display = DisplayServerJavaScript::get_singleton();
  66. int canvas_x = EM_ASM_INT({
  67. return Module['canvas'].getBoundingClientRect().x;
  68. });
  69. int canvas_y = EM_ASM_INT({
  70. return Module['canvas'].getBoundingClientRect().y;
  71. });
  72. int canvas_width;
  73. int canvas_height;
  74. emscripten_get_canvas_element_size(display->canvas_id.utf8().get_data(), &canvas_width, &canvas_height);
  75. double element_width;
  76. double element_height;
  77. emscripten_get_element_css_size(display->canvas_id.utf8().get_data(), &element_width, &element_height);
  78. return Point2((int)(canvas_width / element_width * (x - canvas_x)),
  79. (int)(canvas_height / element_height * (y - canvas_y)));
  80. }
  81. static bool cursor_inside_canvas = true;
  82. EM_BOOL DisplayServerJavaScript::fullscreen_change_callback(int p_event_type, const EmscriptenFullscreenChangeEvent *p_event, void *p_user_data) {
  83. DisplayServerJavaScript *display = get_singleton();
  84. // Empty ID is canvas.
  85. String target_id = String::utf8(p_event->id);
  86. if (target_id.empty() || "#" + target_id == display->canvas_id) {
  87. // This event property is the only reliable data on
  88. // browser fullscreen state.
  89. if (p_event->isFullscreen) {
  90. display->window_mode = WINDOW_MODE_FULLSCREEN;
  91. } else {
  92. display->window_mode = WINDOW_MODE_WINDOWED;
  93. }
  94. }
  95. return false;
  96. }
  97. // Drag and drop callback (see native/utils.js).
  98. extern "C" EMSCRIPTEN_KEEPALIVE void _drop_files_callback(char *p_filev[], int p_filec) {
  99. DisplayServerJavaScript *ds = DisplayServerJavaScript::get_singleton();
  100. if (!ds) {
  101. ERR_FAIL_MSG("Unable to drop files because the DisplayServer is not active");
  102. }
  103. if (ds->drop_files_callback.is_null())
  104. return;
  105. Vector<String> files;
  106. for (int i = 0; i < p_filec; i++) {
  107. files.push_back(String::utf8(p_filev[i]));
  108. }
  109. Variant v = files;
  110. Variant *vp = &v;
  111. Variant ret;
  112. Callable::CallError ce;
  113. ds->drop_files_callback.call((const Variant **)&vp, 1, ret, ce);
  114. }
  115. // Keys
  116. template <typename T>
  117. static void dom2godot_mod(T *emscripten_event_ptr, Ref<InputEventWithModifiers> godot_event) {
  118. godot_event->set_shift(emscripten_event_ptr->shiftKey);
  119. godot_event->set_alt(emscripten_event_ptr->altKey);
  120. godot_event->set_control(emscripten_event_ptr->ctrlKey);
  121. godot_event->set_metakey(emscripten_event_ptr->metaKey);
  122. }
  123. static Ref<InputEventKey> setup_key_event(const EmscriptenKeyboardEvent *emscripten_event) {
  124. Ref<InputEventKey> ev;
  125. ev.instance();
  126. ev->set_echo(emscripten_event->repeat);
  127. dom2godot_mod(emscripten_event, ev);
  128. ev->set_keycode(dom_code2godot_scancode(emscripten_event->code, emscripten_event->key, false));
  129. ev->set_physical_keycode(dom_code2godot_scancode(emscripten_event->code, emscripten_event->key, true));
  130. String unicode = String::utf8(emscripten_event->key);
  131. // Check if empty or multi-character (e.g. `CapsLock`).
  132. if (unicode.length() != 1) {
  133. // Might be empty as well, but better than nonsense.
  134. unicode = String::utf8(emscripten_event->charValue);
  135. }
  136. if (unicode.length() == 1) {
  137. ev->set_unicode(unicode[0]);
  138. }
  139. return ev;
  140. }
  141. EM_BOOL DisplayServerJavaScript::keydown_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  142. DisplayServerJavaScript *display = get_singleton();
  143. Ref<InputEventKey> ev = setup_key_event(p_event);
  144. ev->set_pressed(true);
  145. if (ev->get_unicode() == 0 && keycode_has_unicode(ev->get_keycode())) {
  146. // Defer to keypress event for legacy unicode retrieval.
  147. display->deferred_key_event = ev;
  148. // Do not suppress keypress event.
  149. return false;
  150. }
  151. Input::get_singleton()->parse_input_event(ev);
  152. return true;
  153. }
  154. EM_BOOL DisplayServerJavaScript::keypress_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  155. DisplayServerJavaScript *display = get_singleton();
  156. display->deferred_key_event->set_unicode(p_event->charCode);
  157. Input::get_singleton()->parse_input_event(display->deferred_key_event);
  158. return true;
  159. }
  160. EM_BOOL DisplayServerJavaScript::keyup_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  161. Ref<InputEventKey> ev = setup_key_event(p_event);
  162. ev->set_pressed(false);
  163. Input::get_singleton()->parse_input_event(ev);
  164. return ev->get_keycode() != KEY_UNKNOWN && ev->get_keycode() != 0;
  165. }
  166. // Mouse
  167. EM_BOOL DisplayServerJavaScript::mouse_button_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) {
  168. DisplayServerJavaScript *display = get_singleton();
  169. Ref<InputEventMouseButton> ev;
  170. ev.instance();
  171. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_MOUSEDOWN);
  172. ev->set_position(compute_position_in_canvas(p_event->clientX, p_event->clientY));
  173. ev->set_global_position(ev->get_position());
  174. dom2godot_mod(p_event, ev);
  175. switch (p_event->button) {
  176. case DOM_BUTTON_LEFT:
  177. ev->set_button_index(BUTTON_LEFT);
  178. break;
  179. case DOM_BUTTON_MIDDLE:
  180. ev->set_button_index(BUTTON_MIDDLE);
  181. break;
  182. case DOM_BUTTON_RIGHT:
  183. ev->set_button_index(BUTTON_RIGHT);
  184. break;
  185. case DOM_BUTTON_XBUTTON1:
  186. ev->set_button_index(BUTTON_XBUTTON1);
  187. break;
  188. case DOM_BUTTON_XBUTTON2:
  189. ev->set_button_index(BUTTON_XBUTTON2);
  190. break;
  191. default:
  192. return false;
  193. }
  194. if (ev->is_pressed()) {
  195. double diff = emscripten_get_now() - display->last_click_ms;
  196. if (ev->get_button_index() == display->last_click_button_index) {
  197. if (diff < 400 && Point2(display->last_click_pos).distance_to(ev->get_position()) < 5) {
  198. display->last_click_ms = 0;
  199. display->last_click_pos = Point2(-100, -100);
  200. display->last_click_button_index = -1;
  201. ev->set_doubleclick(true);
  202. }
  203. } else {
  204. display->last_click_button_index = ev->get_button_index();
  205. }
  206. if (!ev->is_doubleclick()) {
  207. display->last_click_ms += diff;
  208. display->last_click_pos = ev->get_position();
  209. }
  210. }
  211. Input *input = Input::get_singleton();
  212. int mask = input->get_mouse_button_mask();
  213. int button_flag = 1 << (ev->get_button_index() - 1);
  214. if (ev->is_pressed()) {
  215. // Since the event is consumed, focus manually. The containing iframe,
  216. // if exists, may not have focus yet, so focus even if already focused.
  217. focus_canvas();
  218. mask |= button_flag;
  219. } else if (mask & button_flag) {
  220. mask &= ~button_flag;
  221. } else {
  222. // Received release event, but press was outside the canvas, so ignore.
  223. return false;
  224. }
  225. ev->set_button_mask(mask);
  226. input->parse_input_event(ev);
  227. // Prevent multi-click text selection and wheel-click scrolling anchor.
  228. // Context menu is prevented through contextmenu event.
  229. return true;
  230. }
  231. EM_BOOL DisplayServerJavaScript::mousemove_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) {
  232. Input *input = Input::get_singleton();
  233. int input_mask = input->get_mouse_button_mask();
  234. Point2 pos = compute_position_in_canvas(p_event->clientX, p_event->clientY);
  235. // For motion outside the canvas, only read mouse movement if dragging
  236. // started inside the canvas; imitating desktop app behaviour.
  237. if (!cursor_inside_canvas && !input_mask)
  238. return false;
  239. Ref<InputEventMouseMotion> ev;
  240. ev.instance();
  241. dom2godot_mod(p_event, ev);
  242. ev->set_button_mask(input_mask);
  243. ev->set_position(pos);
  244. ev->set_global_position(ev->get_position());
  245. ev->set_relative(Vector2(p_event->movementX, p_event->movementY));
  246. input->set_mouse_position(ev->get_position());
  247. ev->set_speed(input->get_last_mouse_speed());
  248. input->parse_input_event(ev);
  249. // Don't suppress mouseover/-leave events.
  250. return false;
  251. }
  252. // Cursor
  253. static const char *godot2dom_cursor(DisplayServer::CursorShape p_shape) {
  254. switch (p_shape) {
  255. case DisplayServer::CURSOR_ARROW:
  256. return "auto";
  257. case DisplayServer::CURSOR_IBEAM:
  258. return "text";
  259. case DisplayServer::CURSOR_POINTING_HAND:
  260. return "pointer";
  261. case DisplayServer::CURSOR_CROSS:
  262. return "crosshair";
  263. case DisplayServer::CURSOR_WAIT:
  264. return "progress";
  265. case DisplayServer::CURSOR_BUSY:
  266. return "wait";
  267. case DisplayServer::CURSOR_DRAG:
  268. return "grab";
  269. case DisplayServer::CURSOR_CAN_DROP:
  270. return "grabbing";
  271. case DisplayServer::CURSOR_FORBIDDEN:
  272. return "no-drop";
  273. case DisplayServer::CURSOR_VSIZE:
  274. return "ns-resize";
  275. case DisplayServer::CURSOR_HSIZE:
  276. return "ew-resize";
  277. case DisplayServer::CURSOR_BDIAGSIZE:
  278. return "nesw-resize";
  279. case DisplayServer::CURSOR_FDIAGSIZE:
  280. return "nwse-resize";
  281. case DisplayServer::CURSOR_MOVE:
  282. return "move";
  283. case DisplayServer::CURSOR_VSPLIT:
  284. return "row-resize";
  285. case DisplayServer::CURSOR_HSPLIT:
  286. return "col-resize";
  287. case DisplayServer::CURSOR_HELP:
  288. return "help";
  289. default:
  290. return "auto";
  291. }
  292. }
  293. static void set_css_cursor(const char *p_cursor) {
  294. /* clang-format off */
  295. EM_ASM_({
  296. Module['canvas'].style.cursor = UTF8ToString($0);
  297. }, p_cursor);
  298. /* clang-format on */
  299. }
  300. static bool is_css_cursor_hidden() {
  301. /* clang-format off */
  302. return EM_ASM_INT({
  303. return Module['canvas'].style.cursor === 'none';
  304. });
  305. /* clang-format on */
  306. }
  307. void DisplayServerJavaScript::cursor_set_shape(CursorShape p_shape) {
  308. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  309. if (mouse_get_mode() == MOUSE_MODE_VISIBLE) {
  310. if (cursors[p_shape] != "") {
  311. Vector<String> url = cursors[p_shape].split("?");
  312. set_css_cursor(("url(\"" + url[0] + "\") " + url[1] + ", auto").utf8());
  313. } else {
  314. set_css_cursor(godot2dom_cursor(p_shape));
  315. }
  316. }
  317. cursor_shape = p_shape;
  318. }
  319. DisplayServer::CursorShape DisplayServerJavaScript::cursor_get_shape() const {
  320. return cursor_shape;
  321. }
  322. void DisplayServerJavaScript::cursor_set_custom_image(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  323. if (p_cursor.is_valid()) {
  324. Map<CursorShape, Vector<Variant>>::Element *cursor_c = cursors_cache.find(p_shape);
  325. if (cursor_c) {
  326. if (cursor_c->get()[0] == p_cursor && cursor_c->get()[1] == p_hotspot) {
  327. cursor_set_shape(p_shape);
  328. return;
  329. }
  330. cursors_cache.erase(p_shape);
  331. }
  332. Ref<Texture2D> texture = p_cursor;
  333. Ref<AtlasTexture> atlas_texture = p_cursor;
  334. Ref<Image> image;
  335. Size2 texture_size;
  336. Rect2 atlas_rect;
  337. if (texture.is_valid()) {
  338. image = texture->get_data();
  339. }
  340. if (!image.is_valid() && atlas_texture.is_valid()) {
  341. texture = atlas_texture->get_atlas();
  342. atlas_rect.size.width = texture->get_width();
  343. atlas_rect.size.height = texture->get_height();
  344. atlas_rect.position.x = atlas_texture->get_region().position.x;
  345. atlas_rect.position.y = atlas_texture->get_region().position.y;
  346. texture_size.width = atlas_texture->get_region().size.x;
  347. texture_size.height = atlas_texture->get_region().size.y;
  348. } else if (image.is_valid()) {
  349. texture_size.width = texture->get_width();
  350. texture_size.height = texture->get_height();
  351. }
  352. ERR_FAIL_COND(!texture.is_valid());
  353. ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
  354. ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
  355. ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
  356. image = texture->get_data();
  357. ERR_FAIL_COND(!image.is_valid());
  358. image = image->duplicate();
  359. if (atlas_texture.is_valid())
  360. image->crop_from_point(
  361. atlas_rect.position.x,
  362. atlas_rect.position.y,
  363. texture_size.width,
  364. texture_size.height);
  365. if (image->get_format() != Image::FORMAT_RGBA8) {
  366. image->convert(Image::FORMAT_RGBA8);
  367. }
  368. png_image png_meta;
  369. memset(&png_meta, 0, sizeof png_meta);
  370. png_meta.version = PNG_IMAGE_VERSION;
  371. png_meta.width = texture_size.width;
  372. png_meta.height = texture_size.height;
  373. png_meta.format = PNG_FORMAT_RGBA;
  374. PackedByteArray png;
  375. size_t len;
  376. PackedByteArray data = image->get_data();
  377. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, data.ptr(), 0, nullptr));
  378. png.resize(len);
  379. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, png.ptrw(), &len, 0, data.ptr(), 0, nullptr));
  380. char *object_url;
  381. /* clang-format off */
  382. EM_ASM({
  383. var PNG_PTR = $0;
  384. var PNG_LEN = $1;
  385. var PTR = $2;
  386. var png = new Blob([HEAPU8.slice(PNG_PTR, PNG_PTR + PNG_LEN)], { type: 'image/png' });
  387. var url = URL.createObjectURL(png);
  388. var length_bytes = lengthBytesUTF8(url) + 1;
  389. var string_on_wasm_heap = _malloc(length_bytes);
  390. setValue(PTR, string_on_wasm_heap, '*');
  391. stringToUTF8(url, string_on_wasm_heap, length_bytes);
  392. }, png.ptr(), len, &object_url);
  393. /* clang-format on */
  394. String url = String::utf8(object_url) + "?" + itos(p_hotspot.x) + " " + itos(p_hotspot.y);
  395. /* clang-format off */
  396. EM_ASM({ _free($0); }, object_url);
  397. /* clang-format on */
  398. if (cursors[p_shape] != "") {
  399. /* clang-format off */
  400. EM_ASM({
  401. URL.revokeObjectURL(UTF8ToString($0).split('?')[0]);
  402. }, cursors[p_shape].utf8().get_data());
  403. /* clang-format on */
  404. cursors[p_shape] = "";
  405. }
  406. cursors[p_shape] = url;
  407. Vector<Variant> params;
  408. params.push_back(p_cursor);
  409. params.push_back(p_hotspot);
  410. cursors_cache.insert(p_shape, params);
  411. } else if (cursors[p_shape] != "") {
  412. /* clang-format off */
  413. EM_ASM({
  414. URL.revokeObjectURL(UTF8ToString($0).split('?')[0]);
  415. }, cursors[p_shape].utf8().get_data());
  416. /* clang-format on */
  417. cursors[p_shape] = "";
  418. cursors_cache.erase(p_shape);
  419. }
  420. cursor_set_shape(cursor_shape);
  421. }
  422. // Mouse mode
  423. void DisplayServerJavaScript::mouse_set_mode(MouseMode p_mode) {
  424. ERR_FAIL_COND_MSG(p_mode == MOUSE_MODE_CONFINED, "MOUSE_MODE_CONFINED is not supported for the HTML5 platform.");
  425. if (p_mode == mouse_get_mode())
  426. return;
  427. if (p_mode == MOUSE_MODE_VISIBLE) {
  428. // set_css_cursor must be called before set_cursor_shape to make the cursor visible
  429. set_css_cursor(godot2dom_cursor(cursor_shape));
  430. cursor_set_shape(cursor_shape);
  431. emscripten_exit_pointerlock();
  432. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  433. set_css_cursor("none");
  434. emscripten_exit_pointerlock();
  435. } else if (p_mode == MOUSE_MODE_CAPTURED) {
  436. EMSCRIPTEN_RESULT result = emscripten_request_pointerlock("canvas", false);
  437. ERR_FAIL_COND_MSG(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED, "MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback.");
  438. ERR_FAIL_COND_MSG(result != EMSCRIPTEN_RESULT_SUCCESS, "MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback.");
  439. // set_css_cursor must be called before cursor_set_shape to make the cursor visible
  440. set_css_cursor(godot2dom_cursor(cursor_shape));
  441. cursor_set_shape(cursor_shape);
  442. }
  443. }
  444. DisplayServer::MouseMode DisplayServerJavaScript::mouse_get_mode() const {
  445. if (is_css_cursor_hidden())
  446. return MOUSE_MODE_HIDDEN;
  447. EmscriptenPointerlockChangeEvent ev;
  448. emscripten_get_pointerlock_status(&ev);
  449. return (ev.isActive && String::utf8(ev.id) == "canvas") ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE;
  450. }
  451. // Wheel
  452. EM_BOOL DisplayServerJavaScript::wheel_callback(int p_event_type, const EmscriptenWheelEvent *p_event, void *p_user_data) {
  453. ERR_FAIL_COND_V(p_event_type != EMSCRIPTEN_EVENT_WHEEL, false);
  454. if (!is_canvas_focused()) {
  455. if (cursor_inside_canvas) {
  456. focus_canvas();
  457. } else {
  458. return false;
  459. }
  460. }
  461. Input *input = Input::get_singleton();
  462. Ref<InputEventMouseButton> ev;
  463. ev.instance();
  464. ev->set_position(input->get_mouse_position());
  465. ev->set_global_position(ev->get_position());
  466. ev->set_shift(input->is_key_pressed(KEY_SHIFT));
  467. ev->set_alt(input->is_key_pressed(KEY_ALT));
  468. ev->set_control(input->is_key_pressed(KEY_CONTROL));
  469. ev->set_metakey(input->is_key_pressed(KEY_META));
  470. if (p_event->deltaY < 0)
  471. ev->set_button_index(BUTTON_WHEEL_UP);
  472. else if (p_event->deltaY > 0)
  473. ev->set_button_index(BUTTON_WHEEL_DOWN);
  474. else if (p_event->deltaX > 0)
  475. ev->set_button_index(BUTTON_WHEEL_LEFT);
  476. else if (p_event->deltaX < 0)
  477. ev->set_button_index(BUTTON_WHEEL_RIGHT);
  478. else
  479. return false;
  480. // Different browsers give wildly different delta values, and we can't
  481. // interpret deltaMode, so use default value for wheel events' factor.
  482. int button_flag = 1 << (ev->get_button_index() - 1);
  483. ev->set_pressed(true);
  484. ev->set_button_mask(input->get_mouse_button_mask() | button_flag);
  485. input->parse_input_event(ev);
  486. ev->set_pressed(false);
  487. ev->set_button_mask(input->get_mouse_button_mask() & ~button_flag);
  488. input->parse_input_event(ev);
  489. return true;
  490. }
  491. // Touch
  492. EM_BOOL DisplayServerJavaScript::touch_press_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  493. DisplayServerJavaScript *display = get_singleton();
  494. Ref<InputEventScreenTouch> ev;
  495. ev.instance();
  496. int lowest_id_index = -1;
  497. for (int i = 0; i < p_event->numTouches; ++i) {
  498. const EmscriptenTouchPoint &touch = p_event->touches[i];
  499. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  500. lowest_id_index = i;
  501. if (!touch.isChanged)
  502. continue;
  503. ev->set_index(touch.identifier);
  504. ev->set_position(compute_position_in_canvas(touch.clientX, touch.clientY));
  505. display->touches[i] = ev->get_position();
  506. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_TOUCHSTART);
  507. Input::get_singleton()->parse_input_event(ev);
  508. }
  509. // Resume audio context after input in case autoplay was denied.
  510. return true;
  511. }
  512. EM_BOOL DisplayServerJavaScript::touchmove_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  513. DisplayServerJavaScript *display = get_singleton();
  514. Ref<InputEventScreenDrag> ev;
  515. ev.instance();
  516. int lowest_id_index = -1;
  517. for (int i = 0; i < p_event->numTouches; ++i) {
  518. const EmscriptenTouchPoint &touch = p_event->touches[i];
  519. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  520. lowest_id_index = i;
  521. if (!touch.isChanged)
  522. continue;
  523. ev->set_index(touch.identifier);
  524. ev->set_position(compute_position_in_canvas(touch.clientX, touch.clientY));
  525. Point2 &prev = display->touches[i];
  526. ev->set_relative(ev->get_position() - prev);
  527. prev = ev->get_position();
  528. Input::get_singleton()->parse_input_event(ev);
  529. }
  530. return true;
  531. }
  532. bool DisplayServerJavaScript::screen_is_touchscreen(int p_screen) const {
  533. return EM_ASM_INT({ return 'ontouchstart' in window; });
  534. }
  535. // Gamepad
  536. EM_BOOL DisplayServerJavaScript::gamepad_change_callback(int p_event_type, const EmscriptenGamepadEvent *p_event, void *p_user_data) {
  537. Input *input = Input::get_singleton();
  538. if (p_event_type == EMSCRIPTEN_EVENT_GAMEPADCONNECTED) {
  539. String guid = "";
  540. if (String::utf8(p_event->mapping) == "standard")
  541. guid = "Default HTML5 Gamepad";
  542. input->joy_connection_changed(p_event->index, true, String::utf8(p_event->id), guid);
  543. } else {
  544. input->joy_connection_changed(p_event->index, false, "");
  545. }
  546. return true;
  547. }
  548. void DisplayServerJavaScript::process_joypads() {
  549. int joypad_count = emscripten_get_num_gamepads();
  550. Input *input = Input::get_singleton();
  551. for (int joypad = 0; joypad < joypad_count; joypad++) {
  552. EmscriptenGamepadEvent state;
  553. EMSCRIPTEN_RESULT query_result = emscripten_get_gamepad_status(joypad, &state);
  554. // Chromium reserves gamepads slots, so NO_DATA is an expected result.
  555. ERR_CONTINUE(query_result != EMSCRIPTEN_RESULT_SUCCESS &&
  556. query_result != EMSCRIPTEN_RESULT_NO_DATA);
  557. if (query_result == EMSCRIPTEN_RESULT_SUCCESS && state.connected) {
  558. int button_count = MIN(state.numButtons, 18);
  559. int axis_count = MIN(state.numAxes, 8);
  560. for (int button = 0; button < button_count; button++) {
  561. float value = state.analogButton[button];
  562. input->joy_button(joypad, button, value);
  563. }
  564. for (int axis = 0; axis < axis_count; axis++) {
  565. Input::JoyAxis joy_axis;
  566. joy_axis.min = -1;
  567. joy_axis.value = state.axis[axis];
  568. input->joy_axis(joypad, axis, joy_axis);
  569. }
  570. }
  571. }
  572. }
  573. #if 0
  574. bool DisplayServerJavaScript::is_joy_known(int p_device) {
  575. return Input::get_singleton()->is_joy_mapped(p_device);
  576. }
  577. String DisplayServerJavaScript::get_joy_guid(int p_device) const {
  578. return Input::get_singleton()->get_joy_guid_remapped(p_device);
  579. }
  580. #endif
  581. Vector<String> DisplayServerJavaScript::get_rendering_drivers_func() {
  582. Vector<String> drivers;
  583. drivers.push_back("dummy");
  584. return drivers;
  585. }
  586. // Clipboard
  587. extern "C" EMSCRIPTEN_KEEPALIVE void update_clipboard(const char *p_text) {
  588. // Only call set_clipboard from OS (sets local clipboard)
  589. DisplayServerJavaScript::get_singleton()->clipboard = p_text;
  590. }
  591. void DisplayServerJavaScript::clipboard_set(const String &p_text) {
  592. /* clang-format off */
  593. int err = EM_ASM_INT({
  594. var text = UTF8ToString($0);
  595. if (!navigator.clipboard || !navigator.clipboard.writeText)
  596. return 1;
  597. navigator.clipboard.writeText(text).catch(function(e) {
  598. // Setting OS clipboard is only possible from an input callback.
  599. console.error("Setting OS clipboard is only possible from an input callback for the HTML5 plafrom. Exception:", e);
  600. });
  601. return 0;
  602. }, p_text.utf8().get_data());
  603. /* clang-format on */
  604. ERR_FAIL_COND_MSG(err, "Clipboard API is not supported.");
  605. }
  606. String DisplayServerJavaScript::clipboard_get() const {
  607. /* clang-format off */
  608. EM_ASM({
  609. try {
  610. navigator.clipboard.readText().then(function (result) {
  611. ccall('update_clipboard', 'void', ['string'], [result]);
  612. }).catch(function (e) {
  613. // Fail graciously.
  614. });
  615. } catch (e) {
  616. // Fail graciously.
  617. }
  618. });
  619. /* clang-format on */
  620. return clipboard;
  621. }
  622. extern "C" EMSCRIPTEN_KEEPALIVE void send_window_event(int p_notification) {
  623. if (p_notification == DisplayServer::WINDOW_EVENT_MOUSE_ENTER || p_notification == DisplayServer::WINDOW_EVENT_MOUSE_EXIT) {
  624. cursor_inside_canvas = p_notification == DisplayServer::WINDOW_EVENT_MOUSE_ENTER;
  625. }
  626. OS_JavaScript *os = OS_JavaScript::get_singleton();
  627. if (os->is_finalizing())
  628. return; // We don't want events anymore.
  629. DisplayServerJavaScript *ds = DisplayServerJavaScript::get_singleton();
  630. if (ds && !ds->window_event_callback.is_null()) {
  631. Variant event = int(p_notification);
  632. Variant *eventp = &event;
  633. Variant ret;
  634. Callable::CallError ce;
  635. ds->window_event_callback.call((const Variant **)&eventp, 1, ret, ce);
  636. }
  637. }
  638. void DisplayServerJavaScript::alert(const String &p_alert, const String &p_title) {
  639. /* clang-format off */
  640. EM_ASM_({
  641. window.alert(UTF8ToString($0));
  642. }, p_alert.utf8().get_data());
  643. /* clang-format on */
  644. }
  645. void DisplayServerJavaScript::set_icon(const Ref<Image> &p_icon) {
  646. ERR_FAIL_COND(p_icon.is_null());
  647. Ref<Image> icon = p_icon;
  648. if (icon->is_compressed()) {
  649. icon = icon->duplicate();
  650. ERR_FAIL_COND(icon->decompress() != OK);
  651. }
  652. if (icon->get_format() != Image::FORMAT_RGBA8) {
  653. if (icon == p_icon)
  654. icon = icon->duplicate();
  655. icon->convert(Image::FORMAT_RGBA8);
  656. }
  657. png_image png_meta;
  658. memset(&png_meta, 0, sizeof png_meta);
  659. png_meta.version = PNG_IMAGE_VERSION;
  660. png_meta.width = icon->get_width();
  661. png_meta.height = icon->get_height();
  662. png_meta.format = PNG_FORMAT_RGBA;
  663. PackedByteArray png;
  664. size_t len;
  665. PackedByteArray data = icon->get_data();
  666. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, data.ptr(), 0, nullptr));
  667. png.resize(len);
  668. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, png.ptrw(), &len, 0, data.ptr(), 0, nullptr));
  669. /* clang-format off */
  670. EM_ASM({
  671. var PNG_PTR = $0;
  672. var PNG_LEN = $1;
  673. var png = new Blob([HEAPU8.slice(PNG_PTR, PNG_PTR + PNG_LEN)], { type: "image/png" });
  674. var url = URL.createObjectURL(png);
  675. var link = document.getElementById('-gd-engine-icon');
  676. if (link === null) {
  677. link = document.createElement('link');
  678. link.rel = 'icon';
  679. link.id = '-gd-engine-icon';
  680. document.head.appendChild(link);
  681. }
  682. link.href = url;
  683. }, png.ptr(), len);
  684. /* clang-format on */
  685. }
  686. void DisplayServerJavaScript::_dispatch_input_event(const Ref<InputEvent> &p_event) {
  687. OS_JavaScript *os = OS_JavaScript::get_singleton();
  688. if (os->is_finalizing())
  689. return; // We don't want events anymore.
  690. // Resume audio context after input in case autoplay was denied.
  691. os->resume_audio();
  692. Callable cb = get_singleton()->input_event_callback;
  693. if (!cb.is_null()) {
  694. Variant ev = p_event;
  695. Variant *evp = &ev;
  696. Variant ret;
  697. Callable::CallError ce;
  698. cb.call((const Variant **)&evp, 1, ret, ce);
  699. }
  700. }
  701. DisplayServer *DisplayServerJavaScript::create_func(const String &p_rendering_driver, DisplayServer::WindowMode p_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
  702. return memnew(DisplayServerJavaScript(p_rendering_driver, p_mode, p_flags, p_resolution, r_error));
  703. }
  704. DisplayServerJavaScript::DisplayServerJavaScript(const String &p_rendering_driver, WindowMode p_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
  705. /* clang-format off */
  706. EM_ASM({
  707. const canvas = Module['canvas'];
  708. var enc = new TextEncoder("utf-8");
  709. var buffer = new Uint8Array(enc.encode(canvas.id));
  710. var len = buffer.byteLength;
  711. var out = _malloc(len);
  712. HEAPU8.set(buffer, out);
  713. ccall("_set_canvas_id",
  714. "void",
  715. ["number", "number"],
  716. [out, len]
  717. );
  718. _free(out);
  719. });
  720. /* clang-format on */
  721. RasterizerDummy::make_current(); // TODO GLES2 in Godot 4.0... or webgpu?
  722. #if 0
  723. EmscriptenWebGLContextAttributes attributes;
  724. emscripten_webgl_init_context_attributes(&attributes);
  725. attributes.alpha = GLOBAL_GET("display/window/per_pixel_transparency/allowed");
  726. attributes.antialias = false;
  727. ERR_FAIL_INDEX_V(p_video_driver, VIDEO_DRIVER_MAX, ERR_INVALID_PARAMETER);
  728. if (p_desired.layered) {
  729. set_window_per_pixel_transparency_enabled(true);
  730. }
  731. bool gl_initialization_error = false;
  732. if (RasterizerGLES2::is_viable() == OK) {
  733. attributes.majorVersion = 1;
  734. RasterizerGLES2::register_config();
  735. RasterizerGLES2::make_current();
  736. } else {
  737. gl_initialization_error = true;
  738. }
  739. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(canvas_id.utf8().get_data(), &attributes);
  740. if (emscripten_webgl_make_context_current(ctx) != EMSCRIPTEN_RESULT_SUCCESS) {
  741. gl_initialization_error = true;
  742. }
  743. if (gl_initialization_error) {
  744. OS::get_singleton()->alert("Your browser does not seem to support WebGL. Please update your browser version.",
  745. "Unable to initialize video driver");
  746. return ERR_UNAVAILABLE;
  747. }
  748. video_driver_index = p_video_driver;
  749. #endif
  750. /* clang-format off */
  751. window_set_mode(p_mode);
  752. if (EM_ASM_INT_V({ return Module['resizeCanvasOnStart'] })) {
  753. /* clang-format on */
  754. window_set_size(p_resolution);
  755. }
  756. EMSCRIPTEN_RESULT result;
  757. CharString id = canvas_id.utf8();
  758. #define EM_CHECK(ev) \
  759. if (result != EMSCRIPTEN_RESULT_SUCCESS) \
  760. ERR_PRINT("Error while setting " #ev " callback: Code " + itos(result));
  761. #define SET_EM_CALLBACK(target, ev, cb) \
  762. result = emscripten_set_##ev##_callback(target, nullptr, true, &cb); \
  763. EM_CHECK(ev)
  764. #define SET_EM_CALLBACK_NOTARGET(ev, cb) \
  765. result = emscripten_set_##ev##_callback(nullptr, true, &cb); \
  766. EM_CHECK(ev)
  767. // These callbacks from Emscripten's html5.h suffice to access most
  768. // JavaScript APIs. For APIs that are not (sufficiently) exposed, EM_ASM
  769. // is used below.
  770. SET_EM_CALLBACK(EMSCRIPTEN_EVENT_TARGET_WINDOW, mousemove, mousemove_callback)
  771. SET_EM_CALLBACK(id.get_data(), mousedown, mouse_button_callback)
  772. SET_EM_CALLBACK(EMSCRIPTEN_EVENT_TARGET_WINDOW, mouseup, mouse_button_callback)
  773. SET_EM_CALLBACK(id.get_data(), wheel, wheel_callback)
  774. SET_EM_CALLBACK(id.get_data(), touchstart, touch_press_callback)
  775. SET_EM_CALLBACK(id.get_data(), touchmove, touchmove_callback)
  776. SET_EM_CALLBACK(id.get_data(), touchend, touch_press_callback)
  777. SET_EM_CALLBACK(id.get_data(), touchcancel, touch_press_callback)
  778. SET_EM_CALLBACK(id.get_data(), keydown, keydown_callback)
  779. SET_EM_CALLBACK(id.get_data(), keypress, keypress_callback)
  780. SET_EM_CALLBACK(id.get_data(), keyup, keyup_callback)
  781. SET_EM_CALLBACK(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, fullscreenchange, fullscreen_change_callback)
  782. SET_EM_CALLBACK_NOTARGET(gamepadconnected, gamepad_change_callback)
  783. SET_EM_CALLBACK_NOTARGET(gamepaddisconnected, gamepad_change_callback)
  784. #undef SET_EM_CALLBACK_NOTARGET
  785. #undef SET_EM_CALLBACK
  786. #undef EM_CHECK
  787. /* clang-format off */
  788. EM_ASM_ARGS({
  789. Module.listeners = {};
  790. const canvas = Module['canvas'];
  791. const send_window_event = cwrap('send_window_event', null, ['number']);
  792. const notifications = arguments;
  793. (['mouseover', 'mouseleave', 'focus', 'blur']).forEach(function(event, index) {
  794. Module.listeners[event] = send_window_event.bind(null, notifications[index]);
  795. canvas.addEventListener(event, Module.listeners[event]);
  796. });
  797. // Clipboard
  798. const update_clipboard = cwrap('update_clipboard', null, ['string']);
  799. Module.listeners['paste'] = function(evt) {
  800. update_clipboard(evt.clipboardData.getData('text'));
  801. };
  802. window.addEventListener('paste', Module.listeners['paste'], false);
  803. Module.listeners['dragover'] = function(ev) {
  804. // Prevent default behavior (which would try to open the file(s))
  805. ev.preventDefault();
  806. };
  807. Module.listeners['drop'] = Module.drop_handler; // Defined in native/utils.js
  808. canvas.addEventListener('dragover', Module.listeners['dragover'], false);
  809. canvas.addEventListener('drop', Module.listeners['drop'], false);
  810. },
  811. WINDOW_EVENT_MOUSE_ENTER,
  812. WINDOW_EVENT_MOUSE_EXIT,
  813. WINDOW_EVENT_FOCUS_IN,
  814. WINDOW_EVENT_FOCUS_OUT
  815. );
  816. /* clang-format on */
  817. Input::get_singleton()->set_event_dispatch_function(_dispatch_input_event);
  818. }
  819. DisplayServerJavaScript::~DisplayServerJavaScript() {
  820. EM_ASM({
  821. Object.entries(Module.listeners).forEach(function(kv) {
  822. if (kv[0] == 'paste') {
  823. window.removeEventListener(kv[0], kv[1], true);
  824. } else {
  825. Module['canvas'].removeEventListener(kv[0], kv[1]);
  826. }
  827. });
  828. Module.listeners = {};
  829. });
  830. //emscripten_webgl_commit_frame();
  831. //emscripten_webgl_destroy_context(webgl_ctx);
  832. }
  833. bool DisplayServerJavaScript::has_feature(Feature p_feature) const {
  834. switch (p_feature) {
  835. //case FEATURE_CONSOLE_WINDOW:
  836. //case FEATURE_GLOBAL_MENU:
  837. //case FEATURE_HIDPI:
  838. //case FEATURE_IME:
  839. case FEATURE_ICON:
  840. case FEATURE_CLIPBOARD:
  841. case FEATURE_CURSOR_SHAPE:
  842. case FEATURE_CUSTOM_CURSOR_SHAPE:
  843. case FEATURE_MOUSE:
  844. case FEATURE_TOUCHSCREEN:
  845. return true;
  846. //case FEATURE_MOUSE_WARP:
  847. //case FEATURE_NATIVE_DIALOG:
  848. //case FEATURE_NATIVE_ICON:
  849. //case FEATURE_NATIVE_VIDEO:
  850. //case FEATURE_WINDOW_TRANSPARENCY:
  851. //case FEATURE_KEEP_SCREEN_ON:
  852. //case FEATURE_ORIENTATION:
  853. //case FEATURE_VIRTUAL_KEYBOARD:
  854. default:
  855. return false;
  856. }
  857. }
  858. void DisplayServerJavaScript::register_javascript_driver() {
  859. register_create_function("javascript", create_func, get_rendering_drivers_func);
  860. }
  861. String DisplayServerJavaScript::get_name() const {
  862. return "javascript";
  863. }
  864. int DisplayServerJavaScript::get_screen_count() const {
  865. return 1;
  866. }
  867. Point2i DisplayServerJavaScript::screen_get_position(int p_screen) const {
  868. return Point2i(); // TODO offsetX/Y?
  869. }
  870. Size2i DisplayServerJavaScript::screen_get_size(int p_screen) const {
  871. EmscriptenFullscreenChangeEvent ev;
  872. EMSCRIPTEN_RESULT result = emscripten_get_fullscreen_status(&ev);
  873. ERR_FAIL_COND_V(result != EMSCRIPTEN_RESULT_SUCCESS, Size2i());
  874. return Size2i(ev.screenWidth, ev.screenHeight);
  875. }
  876. Rect2i DisplayServerJavaScript::screen_get_usable_rect(int p_screen) const {
  877. int canvas[2];
  878. emscripten_get_canvas_element_size(canvas_id.utf8().get_data(), canvas, canvas + 1);
  879. return Rect2i(0, 0, canvas[0], canvas[1]);
  880. }
  881. int DisplayServerJavaScript::screen_get_dpi(int p_screen) const {
  882. return 96; // TODO maybe check pixel ratio via window.devicePixelRatio * 96? Inexact.
  883. }
  884. Vector<DisplayServer::WindowID> DisplayServerJavaScript::get_window_list() const {
  885. Vector<WindowID> ret;
  886. ret.push_back(MAIN_WINDOW_ID);
  887. return ret;
  888. }
  889. DisplayServerJavaScript::WindowID DisplayServerJavaScript::get_window_at_screen_position(const Point2i &p_position) const {
  890. return MAIN_WINDOW_ID;
  891. }
  892. void DisplayServerJavaScript::window_attach_instance_id(ObjectID p_instance, WindowID p_window) {
  893. window_attached_instance_id = p_instance;
  894. }
  895. ObjectID DisplayServerJavaScript::window_get_attached_instance_id(WindowID p_window) const {
  896. return window_attached_instance_id;
  897. }
  898. void DisplayServerJavaScript::window_set_rect_changed_callback(const Callable &p_callable, WindowID p_window) {
  899. // Not supported.
  900. }
  901. void DisplayServerJavaScript::window_set_window_event_callback(const Callable &p_callable, WindowID p_window) {
  902. window_event_callback = p_callable;
  903. }
  904. void DisplayServerJavaScript::window_set_input_event_callback(const Callable &p_callable, WindowID p_window) {
  905. input_event_callback = p_callable;
  906. }
  907. void DisplayServerJavaScript::window_set_input_text_callback(const Callable &p_callable, WindowID p_window) {
  908. input_text_callback = p_callable; // TODO unused... do I need this?
  909. }
  910. void DisplayServerJavaScript::window_set_drop_files_callback(const Callable &p_callable, WindowID p_window) {
  911. drop_files_callback = p_callable;
  912. }
  913. void DisplayServerJavaScript::window_set_title(const String &p_title, WindowID p_window) {
  914. /* clang-format off */
  915. EM_ASM_({
  916. document.title = UTF8ToString($0);
  917. }, p_title.utf8().get_data());
  918. /* clang-format on */
  919. }
  920. int DisplayServerJavaScript::window_get_current_screen(WindowID p_window) const {
  921. return 1;
  922. }
  923. void DisplayServerJavaScript::window_set_current_screen(int p_screen, WindowID p_window) {
  924. // Not implemented.
  925. }
  926. Point2i DisplayServerJavaScript::window_get_position(WindowID p_window) const {
  927. return Point2i(); // TODO Does this need implementation?
  928. }
  929. void DisplayServerJavaScript::window_set_position(const Point2i &p_position, WindowID p_window) {
  930. // Not supported.
  931. }
  932. void DisplayServerJavaScript::window_set_transient(WindowID p_window, WindowID p_parent) {
  933. // Not supported.
  934. }
  935. void DisplayServerJavaScript::window_set_max_size(const Size2i p_size, WindowID p_window) {
  936. // Not supported.
  937. }
  938. Size2i DisplayServerJavaScript::window_get_max_size(WindowID p_window) const {
  939. return Size2i();
  940. }
  941. void DisplayServerJavaScript::window_set_min_size(const Size2i p_size, WindowID p_window) {
  942. // Not supported.
  943. }
  944. Size2i DisplayServerJavaScript::window_get_min_size(WindowID p_window) const {
  945. return Size2i();
  946. }
  947. void DisplayServerJavaScript::window_set_size(const Size2i p_size, WindowID p_window) {
  948. emscripten_set_canvas_element_size(canvas_id.utf8().get_data(), p_size.x, p_size.y);
  949. }
  950. Size2i DisplayServerJavaScript::window_get_size(WindowID p_window) const {
  951. int canvas[2];
  952. emscripten_get_canvas_element_size(canvas_id.utf8().get_data(), canvas, canvas + 1);
  953. return Size2(canvas[0], canvas[1]);
  954. }
  955. Size2i DisplayServerJavaScript::window_get_real_size(WindowID p_window) const {
  956. return window_get_size(p_window);
  957. }
  958. void DisplayServerJavaScript::window_set_mode(WindowMode p_mode, WindowID p_window) {
  959. if (window_mode == p_mode)
  960. return;
  961. switch (p_mode) {
  962. case WINDOW_MODE_WINDOWED: {
  963. if (window_mode == WINDOW_MODE_FULLSCREEN) {
  964. emscripten_exit_fullscreen();
  965. }
  966. window_mode = WINDOW_MODE_WINDOWED;
  967. window_set_size(windowed_size);
  968. } break;
  969. case WINDOW_MODE_FULLSCREEN: {
  970. EmscriptenFullscreenStrategy strategy;
  971. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  972. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  973. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  974. strategy.canvasResizedCallback = nullptr;
  975. EMSCRIPTEN_RESULT result = emscripten_request_fullscreen_strategy(canvas_id.utf8().get_data(), false, &strategy);
  976. ERR_FAIL_COND_MSG(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED, "Enabling fullscreen is only possible from an input callback for the HTML5 platform.");
  977. ERR_FAIL_COND_MSG(result != EMSCRIPTEN_RESULT_SUCCESS, "Enabling fullscreen is only possible from an input callback for the HTML5 platform.");
  978. } break;
  979. case WINDOW_MODE_MAXIMIZED:
  980. case WINDOW_MODE_MINIMIZED:
  981. WARN_PRINT("WindowMode MAXIMIZED and MINIMIZED are not supported in HTML5 platform.");
  982. break;
  983. default:
  984. break;
  985. }
  986. }
  987. DisplayServerJavaScript::WindowMode DisplayServerJavaScript::window_get_mode(WindowID p_window) const {
  988. return window_mode;
  989. }
  990. bool DisplayServerJavaScript::window_is_maximize_allowed(WindowID p_window) const {
  991. return false;
  992. }
  993. void DisplayServerJavaScript::window_set_flag(WindowFlags p_flag, bool p_enabled, WindowID p_window) {
  994. // Not supported.
  995. }
  996. bool DisplayServerJavaScript::window_get_flag(WindowFlags p_flag, WindowID p_window) const {
  997. return false;
  998. }
  999. void DisplayServerJavaScript::window_request_attention(WindowID p_window) {
  1000. // Not supported.
  1001. }
  1002. void DisplayServerJavaScript::window_move_to_foreground(WindowID p_window) {
  1003. // Not supported.
  1004. }
  1005. bool DisplayServerJavaScript::window_can_draw(WindowID p_window) const {
  1006. return true;
  1007. }
  1008. bool DisplayServerJavaScript::can_any_window_draw() const {
  1009. return true;
  1010. }
  1011. void DisplayServerJavaScript::process_events() {
  1012. if (emscripten_sample_gamepad_data() == EMSCRIPTEN_RESULT_SUCCESS)
  1013. process_joypads();
  1014. }
  1015. int DisplayServerJavaScript::get_current_video_driver() const {
  1016. return 1;
  1017. }
  1018. void DisplayServerJavaScript::swap_buffers() {
  1019. //emscripten_webgl_commit_frame();
  1020. }