library_godot_display.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. /*************************************************************************/
  2. /* library_godot_display.js */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. /*
  31. * Display Server listeners.
  32. * Keeps track of registered event listeners so it can remove them on shutdown.
  33. */
  34. const GodotDisplayListeners = {
  35. $GodotDisplayListeners__deps: ['$GodotOS'],
  36. $GodotDisplayListeners__postset: 'GodotOS.atexit(function(resolve, reject) { GodotDisplayListeners.clear(); resolve(); });',
  37. $GodotDisplayListeners: {
  38. handlers: [],
  39. has: function (target, event, method, capture) {
  40. return GodotDisplayListeners.handlers.findIndex(function (e) {
  41. return e.target === target && e.event === event && e.method === method && e.capture === capture;
  42. }) !== -1;
  43. },
  44. add: function (target, event, method, capture) {
  45. if (GodotDisplayListeners.has(target, event, method, capture)) {
  46. return;
  47. }
  48. function Handler(p_target, p_event, p_method, p_capture) {
  49. this.target = p_target;
  50. this.event = p_event;
  51. this.method = p_method;
  52. this.capture = p_capture;
  53. }
  54. GodotDisplayListeners.handlers.push(new Handler(target, event, method, capture));
  55. target.addEventListener(event, method, capture);
  56. },
  57. clear: function () {
  58. GodotDisplayListeners.handlers.forEach(function (h) {
  59. h.target.removeEventListener(h.event, h.method, h.capture);
  60. });
  61. GodotDisplayListeners.handlers.length = 0;
  62. },
  63. },
  64. };
  65. mergeInto(LibraryManager.library, GodotDisplayListeners);
  66. /*
  67. * Drag and drop handler.
  68. * This is pretty big, but basically detect dropped files on GodotConfig.canvas,
  69. * process them one by one (recursively for directories), and copies them to
  70. * the temporary FS path '/tmp/drop-[random]/' so it can be emitted as a godot
  71. * event (that requires a string array of paths).
  72. *
  73. * NOTE: The temporary files are removed after the callback. This means that
  74. * deferred callbacks won't be able to access the files.
  75. */
  76. const GodotDisplayDragDrop = {
  77. $GodotDisplayDragDrop__deps: ['$FS', '$GodotFS'],
  78. $GodotDisplayDragDrop: {
  79. promises: [],
  80. pending_files: [],
  81. add_entry: function (entry) {
  82. if (entry.isDirectory) {
  83. GodotDisplayDragDrop.add_dir(entry);
  84. } else if (entry.isFile) {
  85. GodotDisplayDragDrop.add_file(entry);
  86. } else {
  87. GodotRuntime.error('Unrecognized entry...', entry);
  88. }
  89. },
  90. add_dir: function (entry) {
  91. GodotDisplayDragDrop.promises.push(new Promise(function (resolve, reject) {
  92. const reader = entry.createReader();
  93. reader.readEntries(function (entries) {
  94. for (let i = 0; i < entries.length; i++) {
  95. GodotDisplayDragDrop.add_entry(entries[i]);
  96. }
  97. resolve();
  98. });
  99. }));
  100. },
  101. add_file: function (entry) {
  102. GodotDisplayDragDrop.promises.push(new Promise(function (resolve, reject) {
  103. entry.file(function (file) {
  104. const reader = new FileReader();
  105. reader.onload = function () {
  106. const f = {
  107. 'path': file.relativePath || file.webkitRelativePath,
  108. 'name': file.name,
  109. 'type': file.type,
  110. 'size': file.size,
  111. 'data': reader.result,
  112. };
  113. if (!f['path']) {
  114. f['path'] = f['name'];
  115. }
  116. GodotDisplayDragDrop.pending_files.push(f);
  117. resolve();
  118. };
  119. reader.onerror = function () {
  120. GodotRuntime.print('Error reading file');
  121. reject();
  122. };
  123. reader.readAsArrayBuffer(file);
  124. }, function (err) {
  125. GodotRuntime.print('Error!');
  126. reject();
  127. });
  128. }));
  129. },
  130. process: function (resolve, reject) {
  131. if (GodotDisplayDragDrop.promises.length === 0) {
  132. resolve();
  133. return;
  134. }
  135. GodotDisplayDragDrop.promises.pop().then(function () {
  136. setTimeout(function () {
  137. GodotDisplayDragDrop.process(resolve, reject);
  138. }, 0);
  139. });
  140. },
  141. _process_event: function (ev, callback) {
  142. ev.preventDefault();
  143. if (ev.dataTransfer.items) {
  144. // Use DataTransferItemList interface to access the file(s)
  145. for (let i = 0; i < ev.dataTransfer.items.length; i++) {
  146. const item = ev.dataTransfer.items[i];
  147. let entry = null;
  148. if ('getAsEntry' in item) {
  149. entry = item.getAsEntry();
  150. } else if ('webkitGetAsEntry' in item) {
  151. entry = item.webkitGetAsEntry();
  152. }
  153. if (entry) {
  154. GodotDisplayDragDrop.add_entry(entry);
  155. }
  156. }
  157. } else {
  158. GodotRuntime.error('File upload not supported');
  159. }
  160. new Promise(GodotDisplayDragDrop.process).then(function () {
  161. const DROP = `/tmp/drop-${parseInt(Math.random() * (1 << 30), 10)}/`;
  162. const drops = [];
  163. const files = [];
  164. FS.mkdir(DROP);
  165. GodotDisplayDragDrop.pending_files.forEach((elem) => {
  166. const path = elem['path'];
  167. GodotFS.copy_to_fs(DROP + path, elem['data']);
  168. let idx = path.indexOf('/');
  169. if (idx === -1) {
  170. // Root file
  171. drops.push(DROP + path);
  172. } else {
  173. // Subdir
  174. const sub = path.substr(0, idx);
  175. idx = sub.indexOf('/');
  176. if (idx < 0 && drops.indexOf(DROP + sub) === -1) {
  177. drops.push(DROP + sub);
  178. }
  179. }
  180. files.push(DROP + path);
  181. });
  182. GodotDisplayDragDrop.promises = [];
  183. GodotDisplayDragDrop.pending_files = [];
  184. callback(drops);
  185. const dirs = [DROP.substr(0, DROP.length - 1)];
  186. // Remove temporary files
  187. files.forEach(function (file) {
  188. FS.unlink(file);
  189. let dir = file.replace(DROP, '');
  190. let idx = dir.lastIndexOf('/');
  191. while (idx > 0) {
  192. dir = dir.substr(0, idx);
  193. if (dirs.indexOf(DROP + dir) === -1) {
  194. dirs.push(DROP + dir);
  195. }
  196. idx = dir.lastIndexOf('/');
  197. }
  198. });
  199. // Remove dirs.
  200. dirs.sort(function (a, b) {
  201. const al = (a.match(/\//g) || []).length;
  202. const bl = (b.match(/\//g) || []).length;
  203. if (al > bl) {
  204. return -1;
  205. } else if (al < bl) {
  206. return 1;
  207. }
  208. return 0;
  209. }).forEach(function (dir) {
  210. FS.rmdir(dir);
  211. });
  212. });
  213. },
  214. handler: function (callback) {
  215. return function (ev) {
  216. GodotDisplayDragDrop._process_event(ev, callback);
  217. };
  218. },
  219. },
  220. };
  221. mergeInto(LibraryManager.library, GodotDisplayDragDrop);
  222. /*
  223. * Display server cursor helper.
  224. * Keeps track of cursor status and custom shapes.
  225. */
  226. const GodotDisplayCursor = {
  227. $GodotDisplayCursor__deps: ['$GodotOS', '$GodotConfig'],
  228. $GodotDisplayCursor__postset: 'GodotOS.atexit(function(resolve, reject) { GodotDisplayCursor.clear(); resolve(); });',
  229. $GodotDisplayCursor: {
  230. shape: 'auto',
  231. visible: true,
  232. cursors: {},
  233. set_style: function (style) {
  234. GodotConfig.canvas.style.cursor = style;
  235. },
  236. set_shape: function (shape) {
  237. GodotDisplayCursor.shape = shape;
  238. let css = shape;
  239. if (shape in GodotDisplayCursor.cursors) {
  240. const c = GodotDisplayCursor.cursors[shape];
  241. css = `url("${c.url}") ${c.x} ${c.y}, auto`;
  242. }
  243. if (GodotDisplayCursor.visible) {
  244. GodotDisplayCursor.set_style(css);
  245. }
  246. },
  247. clear: function () {
  248. GodotDisplayCursor.set_style('');
  249. GodotDisplayCursor.shape = 'auto';
  250. GodotDisplayCursor.visible = true;
  251. Object.keys(GodotDisplayCursor.cursors).forEach(function (key) {
  252. URL.revokeObjectURL(GodotDisplayCursor.cursors[key]);
  253. delete GodotDisplayCursor.cursors[key];
  254. });
  255. },
  256. },
  257. };
  258. mergeInto(LibraryManager.library, GodotDisplayCursor);
  259. /*
  260. * Display Gamepad API helper.
  261. */
  262. const GodotDisplayGamepads = {
  263. $GodotDisplayGamepads__deps: ['$GodotRuntime', '$GodotDisplayListeners'],
  264. $GodotDisplayGamepads: {
  265. samples: [],
  266. get_pads: function () {
  267. try {
  268. // Will throw in iframe when permission is denied.
  269. // Will throw/warn in the future for insecure contexts.
  270. // See https://github.com/w3c/gamepad/pull/120
  271. const pads = navigator.getGamepads();
  272. if (pads) {
  273. return pads;
  274. }
  275. return [];
  276. } catch (e) {
  277. return [];
  278. }
  279. },
  280. get_samples: function () {
  281. return GodotDisplayGamepads.samples;
  282. },
  283. get_sample: function (index) {
  284. const samples = GodotDisplayGamepads.samples;
  285. return index < samples.length ? samples[index] : null;
  286. },
  287. sample: function () {
  288. const pads = GodotDisplayGamepads.get_pads();
  289. const samples = [];
  290. for (let i = 0; i < pads.length; i++) {
  291. const pad = pads[i];
  292. if (!pad) {
  293. samples.push(null);
  294. continue;
  295. }
  296. const s = {
  297. standard: pad.mapping === 'standard',
  298. buttons: [],
  299. axes: [],
  300. connected: pad.connected,
  301. };
  302. for (let b = 0; b < pad.buttons.length; b++) {
  303. s.buttons.push(pad.buttons[b].value);
  304. }
  305. for (let a = 0; a < pad.axes.length; a++) {
  306. s.axes.push(pad.axes[a]);
  307. }
  308. samples.push(s);
  309. }
  310. GodotDisplayGamepads.samples = samples;
  311. },
  312. init: function (onchange) {
  313. GodotDisplayListeners.samples = [];
  314. function add(pad) {
  315. const guid = GodotDisplayGamepads.get_guid(pad);
  316. const c_id = GodotRuntime.allocString(pad.id);
  317. const c_guid = GodotRuntime.allocString(guid);
  318. onchange(pad.index, 1, c_id, c_guid);
  319. GodotRuntime.free(c_id);
  320. GodotRuntime.free(c_guid);
  321. }
  322. const pads = GodotDisplayGamepads.get_pads();
  323. for (let i = 0; i < pads.length; i++) {
  324. // Might be reserved space.
  325. if (pads[i]) {
  326. add(pads[i]);
  327. }
  328. }
  329. GodotDisplayListeners.add(window, 'gamepadconnected', function (evt) {
  330. add(evt.gamepad);
  331. }, false);
  332. GodotDisplayListeners.add(window, 'gamepaddisconnected', function (evt) {
  333. onchange(evt.gamepad.index, 0);
  334. }, false);
  335. },
  336. get_guid: function (pad) {
  337. if (pad.mapping) {
  338. return pad.mapping;
  339. }
  340. const ua = navigator.userAgent;
  341. let os = 'Unknown';
  342. if (ua.indexOf('Android') >= 0) {
  343. os = 'Android';
  344. } else if (ua.indexOf('Linux') >= 0) {
  345. os = 'Linux';
  346. } else if (ua.indexOf('iPhone') >= 0) {
  347. os = 'iOS';
  348. } else if (ua.indexOf('Macintosh') >= 0) {
  349. // Updated iPads will fall into this category.
  350. os = 'MacOSX';
  351. } else if (ua.indexOf('Windows') >= 0) {
  352. os = 'Windows';
  353. }
  354. const id = pad.id;
  355. // Chrom* style: NAME (Vendor: xxxx Product: xxxx)
  356. const exp1 = /vendor: ([0-9a-f]{4}) product: ([0-9a-f]{4})/i;
  357. // Firefox/Safari style (safari may remove leading zeores)
  358. const exp2 = /^([0-9a-f]+)-([0-9a-f]+)-/i;
  359. let vendor = '';
  360. let product = '';
  361. if (exp1.test(id)) {
  362. const match = exp1.exec(id);
  363. vendor = match[1].padStart(4, '0');
  364. product = match[2].padStart(4, '0');
  365. } else if (exp2.test(id)) {
  366. const match = exp2.exec(id);
  367. vendor = match[1].padStart(4, '0');
  368. product = match[2].padStart(4, '0');
  369. }
  370. if (!vendor || !product) {
  371. return `${os}Unknown`;
  372. }
  373. return os + vendor + product;
  374. },
  375. },
  376. };
  377. mergeInto(LibraryManager.library, GodotDisplayGamepads);
  378. /**
  379. * Display server interface.
  380. *
  381. * Exposes all the functions needed by DisplayServer implementation.
  382. */
  383. const GodotDisplay = {
  384. $GodotDisplay__deps: ['$GodotConfig', '$GodotRuntime', '$GodotDisplayCursor', '$GodotDisplayListeners', '$GodotDisplayDragDrop', '$GodotDisplayGamepads'],
  385. $GodotDisplay: {
  386. window_icon: '',
  387. },
  388. godot_js_display_is_swap_ok_cancel__sig: 'i',
  389. godot_js_display_is_swap_ok_cancel: function () {
  390. const win = (['Windows', 'Win64', 'Win32', 'WinCE']);
  391. const plat = navigator.platform || '';
  392. if (win.indexOf(plat) !== -1) {
  393. return 1;
  394. }
  395. return 0;
  396. },
  397. godot_js_display_alert__sig: 'vi',
  398. godot_js_display_alert: function (p_text) {
  399. window.alert(GodotRuntime.parseString(p_text)); // eslint-disable-line no-alert
  400. },
  401. godot_js_display_pixel_ratio_get__sig: 'f',
  402. godot_js_display_pixel_ratio_get: function () {
  403. return window.devicePixelRatio || 1;
  404. },
  405. /*
  406. * Canvas
  407. */
  408. godot_js_display_canvas_focus__sig: 'v',
  409. godot_js_display_canvas_focus: function () {
  410. GodotConfig.canvas.focus();
  411. },
  412. godot_js_display_canvas_is_focused__sig: 'i',
  413. godot_js_display_canvas_is_focused: function () {
  414. return document.activeElement === GodotConfig.canvas;
  415. },
  416. godot_js_display_canvas_bounding_rect_position_get__sig: 'vii',
  417. godot_js_display_canvas_bounding_rect_position_get: function (r_x, r_y) {
  418. const brect = GodotConfig.canvas.getBoundingClientRect();
  419. GodotRuntime.setHeapValue(r_x, brect.x, 'i32');
  420. GodotRuntime.setHeapValue(r_y, brect.y, 'i32');
  421. },
  422. /*
  423. * Touchscreen
  424. */
  425. godot_js_display_touchscreen_is_available__sig: 'i',
  426. godot_js_display_touchscreen_is_available: function () {
  427. return 'ontouchstart' in window;
  428. },
  429. /*
  430. * Clipboard
  431. */
  432. godot_js_display_clipboard_set__sig: 'ii',
  433. godot_js_display_clipboard_set: function (p_text) {
  434. const text = GodotRuntime.parseString(p_text);
  435. if (!navigator.clipboard || !navigator.clipboard.writeText) {
  436. return 1;
  437. }
  438. navigator.clipboard.writeText(text).catch(function (e) {
  439. // Setting OS clipboard is only possible from an input callback.
  440. GodotRuntime.error('Setting OS clipboard is only possible from an input callback for the HTML5 plafrom. Exception:', e);
  441. });
  442. return 0;
  443. },
  444. godot_js_display_clipboard_get__sig: 'ii',
  445. godot_js_display_clipboard_get: function (callback) {
  446. const func = GodotRuntime.get_func(callback);
  447. try {
  448. navigator.clipboard.readText().then(function (result) {
  449. const ptr = GodotRuntime.allocString(result);
  450. func(ptr);
  451. GodotRuntime.free(ptr);
  452. }).catch(function (e) {
  453. // Fail graciously.
  454. });
  455. } catch (e) {
  456. // Fail graciously.
  457. }
  458. },
  459. /*
  460. * Window
  461. */
  462. godot_js_display_window_request_fullscreen__sig: 'v',
  463. godot_js_display_window_request_fullscreen: function () {
  464. const canvas = GodotConfig.canvas;
  465. (canvas.requestFullscreen || canvas.msRequestFullscreen
  466. || canvas.mozRequestFullScreen || canvas.mozRequestFullscreen
  467. || canvas.webkitRequestFullscreen
  468. ).call(canvas);
  469. },
  470. godot_js_display_window_title_set__sig: 'vi',
  471. godot_js_display_window_title_set: function (p_data) {
  472. document.title = GodotRuntime.parseString(p_data);
  473. },
  474. godot_js_display_window_icon_set__sig: 'vii',
  475. godot_js_display_window_icon_set: function (p_ptr, p_len) {
  476. let link = document.getElementById('-gd-engine-icon');
  477. if (link === null) {
  478. link = document.createElement('link');
  479. link.rel = 'icon';
  480. link.id = '-gd-engine-icon';
  481. document.head.appendChild(link);
  482. }
  483. const old_icon = GodotDisplay.window_icon;
  484. const png = new Blob([GodotRuntime.heapCopy(HEAPU8, p_ptr, p_len)], { type: 'image/png' });
  485. GodotDisplay.window_icon = URL.createObjectURL(png);
  486. link.href = GodotDisplay.window_icon;
  487. if (old_icon) {
  488. URL.revokeObjectURL(old_icon);
  489. }
  490. },
  491. /*
  492. * Cursor
  493. */
  494. godot_js_display_cursor_set_visible__sig: 'vi',
  495. godot_js_display_cursor_set_visible: function (p_visible) {
  496. const visible = p_visible !== 0;
  497. if (visible === GodotDisplayCursor.visible) {
  498. return;
  499. }
  500. GodotDisplayCursor.visible = visible;
  501. if (visible) {
  502. GodotDisplayCursor.set_shape(GodotDisplayCursor.shape);
  503. } else {
  504. GodotDisplayCursor.set_style('none');
  505. }
  506. },
  507. godot_js_display_cursor_is_hidden__sig: 'i',
  508. godot_js_display_cursor_is_hidden: function () {
  509. return !GodotDisplayCursor.visible;
  510. },
  511. godot_js_display_cursor_set_shape__sig: 'vi',
  512. godot_js_display_cursor_set_shape: function (p_string) {
  513. GodotDisplayCursor.set_shape(GodotRuntime.parseString(p_string));
  514. },
  515. godot_js_display_cursor_set_custom_shape__sig: 'viiiii',
  516. godot_js_display_cursor_set_custom_shape: function (p_shape, p_ptr, p_len, p_hotspot_x, p_hotspot_y) {
  517. const shape = GodotRuntime.parseString(p_shape);
  518. const old_shape = GodotDisplayCursor.cursors[shape];
  519. if (p_len > 0) {
  520. const png = new Blob([GodotRuntime.heapCopy(HEAPU8, p_ptr, p_len)], { type: 'image/png' });
  521. const url = URL.createObjectURL(png);
  522. GodotDisplayCursor.cursors[shape] = {
  523. url: url,
  524. x: p_hotspot_x,
  525. y: p_hotspot_y,
  526. };
  527. } else {
  528. delete GodotDisplayCursor.cursors[shape];
  529. }
  530. if (shape === GodotDisplayCursor.shape) {
  531. GodotDisplayCursor.set_shape(GodotDisplayCursor.shape);
  532. }
  533. if (old_shape) {
  534. URL.revokeObjectURL(old_shape.url);
  535. }
  536. },
  537. /*
  538. * Listeners
  539. */
  540. godot_js_display_notification_cb__sig: 'viiiii',
  541. godot_js_display_notification_cb: function (callback, p_enter, p_exit, p_in, p_out) {
  542. const canvas = GodotConfig.canvas;
  543. const func = GodotRuntime.get_func(callback);
  544. const notif = [p_enter, p_exit, p_in, p_out];
  545. ['mouseover', 'mouseleave', 'focus', 'blur'].forEach(function (evt_name, idx) {
  546. GodotDisplayListeners.add(canvas, evt_name, function () {
  547. func.bind(null, notif[idx]);
  548. }, true);
  549. });
  550. },
  551. godot_js_display_paste_cb__sig: 'vi',
  552. godot_js_display_paste_cb: function (callback) {
  553. const func = GodotRuntime.get_func(callback);
  554. GodotDisplayListeners.add(window, 'paste', function (evt) {
  555. const text = evt.clipboardData.getData('text');
  556. const ptr = GodotRuntime.allocString(text);
  557. func(ptr);
  558. GodotRuntime.free(ptr);
  559. }, false);
  560. },
  561. godot_js_display_drop_files_cb__sig: 'vi',
  562. godot_js_display_drop_files_cb: function (callback) {
  563. const func = GodotRuntime.get_func(callback);
  564. const dropFiles = function (files) {
  565. const args = files || [];
  566. if (!args.length) {
  567. return;
  568. }
  569. const argc = args.length;
  570. const argv = GodotRuntime.allocStringArray(args);
  571. func(argv, argc);
  572. GodotRuntime.freeStringArray(argv, argc);
  573. };
  574. const canvas = GodotConfig.canvas;
  575. GodotDisplayListeners.add(canvas, 'dragover', function (ev) {
  576. // Prevent default behavior (which would try to open the file(s))
  577. ev.preventDefault();
  578. }, false);
  579. GodotDisplayListeners.add(canvas, 'drop', GodotDisplayDragDrop.handler(dropFiles));
  580. },
  581. godot_js_display_setup_canvas__sig: 'v',
  582. godot_js_display_setup_canvas: function () {
  583. const canvas = GodotConfig.canvas;
  584. GodotDisplayListeners.add(canvas, 'contextmenu', function (ev) {
  585. ev.preventDefault();
  586. }, false);
  587. GodotDisplayListeners.add(canvas, 'webglcontextlost', function (ev) {
  588. alert('WebGL context lost, please reload the page'); // eslint-disable-line no-alert
  589. ev.preventDefault();
  590. }, false);
  591. },
  592. /*
  593. * Gamepads
  594. */
  595. godot_js_display_gamepad_cb__sig: 'vi',
  596. godot_js_display_gamepad_cb: function (change_cb) {
  597. const onchange = GodotRuntime.get_func(change_cb);
  598. GodotDisplayGamepads.init(onchange);
  599. },
  600. godot_js_display_gamepad_sample_count__sig: 'i',
  601. godot_js_display_gamepad_sample_count: function () {
  602. return GodotDisplayGamepads.get_samples().length;
  603. },
  604. godot_js_display_gamepad_sample__sig: 'i',
  605. godot_js_display_gamepad_sample: function () {
  606. GodotDisplayGamepads.sample();
  607. return 0;
  608. },
  609. godot_js_display_gamepad_sample_get__sig: 'iiiiiii',
  610. godot_js_display_gamepad_sample_get: function (p_index, r_btns, r_btns_num, r_axes, r_axes_num, r_standard) {
  611. const sample = GodotDisplayGamepads.get_sample(p_index);
  612. if (!sample || !sample.connected) {
  613. return 1;
  614. }
  615. const btns = sample.buttons;
  616. const btns_len = btns.length < 16 ? btns.length : 16;
  617. for (let i = 0; i < btns_len; i++) {
  618. GodotRuntime.setHeapValue(r_btns + (i << 2), btns[i], 'float');
  619. }
  620. GodotRuntime.setHeapValue(r_btns_num, btns_len, 'i32');
  621. const axes = sample.axes;
  622. const axes_len = axes.length < 10 ? axes.length : 10;
  623. for (let i = 0; i < axes_len; i++) {
  624. GodotRuntime.setHeapValue(r_axes + (i << 2), axes[i], 'float');
  625. }
  626. GodotRuntime.setHeapValue(r_axes_num, axes_len, 'i32');
  627. const is_standard = sample.standard ? 1 : 0;
  628. GodotRuntime.setHeapValue(r_standard, is_standard, 'i32');
  629. return 0;
  630. },
  631. };
  632. autoAddDeps(GodotDisplay, '$GodotDisplay');
  633. mergeInto(LibraryManager.library, GodotDisplay);