display_server_javascript.cpp 37 KB

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