library_godot_input.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. /**************************************************************************/
  2. /* library_godot_input.js */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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. * IME API helper.
  32. */
  33. const GodotIME = {
  34. $GodotIME__deps: ['$GodotRuntime', '$GodotEventListeners'],
  35. $GodotIME__postset: 'GodotOS.atexit(function(resolve, reject) { GodotIME.clear(); resolve(); });',
  36. $GodotIME: {
  37. ime: null,
  38. active: false,
  39. getModifiers: function (evt) {
  40. return (evt.shiftKey + 0) + ((evt.altKey + 0) << 1) + ((evt.ctrlKey + 0) << 2) + ((evt.metaKey + 0) << 3);
  41. },
  42. ime_active: function (active) {
  43. function focus_timer() {
  44. GodotIME.active = true;
  45. GodotIME.ime.focus();
  46. }
  47. if (GodotIME.ime) {
  48. if (active) {
  49. GodotIME.ime.style.display = 'block';
  50. setInterval(focus_timer, 100);
  51. } else {
  52. GodotIME.ime.style.display = 'none';
  53. GodotConfig.canvas.focus();
  54. GodotIME.active = false;
  55. }
  56. }
  57. },
  58. ime_position: function (x, y) {
  59. if (GodotIME.ime) {
  60. const canvas = GodotConfig.canvas;
  61. const rect = canvas.getBoundingClientRect();
  62. const rw = canvas.width / rect.width;
  63. const rh = canvas.height / rect.height;
  64. const clx = (x / rw) + rect.x;
  65. const cly = (y / rh) + rect.y;
  66. GodotIME.ime.style.left = `${clx}px`;
  67. GodotIME.ime.style.top = `${cly}px`;
  68. }
  69. },
  70. init: function (ime_cb, key_cb, code, key) {
  71. function key_event_cb(pressed, evt) {
  72. const modifiers = GodotIME.getModifiers(evt);
  73. GodotRuntime.stringToHeap(evt.code, code, 32);
  74. GodotRuntime.stringToHeap(evt.key, key, 32);
  75. key_cb(pressed, evt.repeat, modifiers);
  76. evt.preventDefault();
  77. }
  78. function ime_event_cb(event) {
  79. if (GodotIME.ime) {
  80. if (event.type === 'compositionstart') {
  81. ime_cb(0, null);
  82. GodotIME.ime.innerHTML = '';
  83. } else if (event.type === 'compositionupdate') {
  84. const ptr = GodotRuntime.allocString(event.data);
  85. ime_cb(1, ptr);
  86. GodotRuntime.free(ptr);
  87. } else if (event.type === 'compositionend') {
  88. const ptr = GodotRuntime.allocString(event.data);
  89. ime_cb(2, ptr);
  90. GodotRuntime.free(ptr);
  91. GodotIME.ime.innerHTML = '';
  92. }
  93. }
  94. }
  95. const ime = document.createElement('div');
  96. ime.className = 'ime';
  97. ime.style.background = 'none';
  98. ime.style.opacity = 0.0;
  99. ime.style.position = 'fixed';
  100. ime.style.textAlign = 'left';
  101. ime.style.fontSize = '1px';
  102. ime.style.left = '0px';
  103. ime.style.top = '0px';
  104. ime.style.width = '100%';
  105. ime.style.height = '40px';
  106. ime.style.display = 'none';
  107. ime.contentEditable = 'true';
  108. GodotEventListeners.add(ime, 'compositionstart', ime_event_cb, false);
  109. GodotEventListeners.add(ime, 'compositionupdate', ime_event_cb, false);
  110. GodotEventListeners.add(ime, 'compositionend', ime_event_cb, false);
  111. GodotEventListeners.add(ime, 'keydown', key_event_cb.bind(null, 1), false);
  112. GodotEventListeners.add(ime, 'keyup', key_event_cb.bind(null, 0), false);
  113. ime.onblur = function () {
  114. this.style.display = 'none';
  115. GodotConfig.canvas.focus();
  116. GodotIME.active = false;
  117. };
  118. GodotConfig.canvas.parentElement.appendChild(ime);
  119. GodotIME.ime = ime;
  120. },
  121. clear: function () {
  122. if (GodotIME.ime) {
  123. GodotIME.ime.remove();
  124. GodotIME.ime = null;
  125. }
  126. },
  127. },
  128. };
  129. mergeInto(LibraryManager.library, GodotIME);
  130. /*
  131. * Gamepad API helper.
  132. */
  133. const GodotInputGamepads = {
  134. $GodotInputGamepads__deps: ['$GodotRuntime', '$GodotEventListeners'],
  135. $GodotInputGamepads: {
  136. samples: [],
  137. get_pads: function () {
  138. try {
  139. // Will throw in iframe when permission is denied.
  140. // Will throw/warn in the future for insecure contexts.
  141. // See https://github.com/w3c/gamepad/pull/120
  142. const pads = navigator.getGamepads();
  143. if (pads) {
  144. return pads;
  145. }
  146. return [];
  147. } catch (e) {
  148. return [];
  149. }
  150. },
  151. get_samples: function () {
  152. return GodotInputGamepads.samples;
  153. },
  154. get_sample: function (index) {
  155. const samples = GodotInputGamepads.samples;
  156. return index < samples.length ? samples[index] : null;
  157. },
  158. sample: function () {
  159. const pads = GodotInputGamepads.get_pads();
  160. const samples = [];
  161. for (let i = 0; i < pads.length; i++) {
  162. const pad = pads[i];
  163. if (!pad) {
  164. samples.push(null);
  165. continue;
  166. }
  167. const s = {
  168. standard: pad.mapping === 'standard',
  169. buttons: [],
  170. axes: [],
  171. connected: pad.connected,
  172. };
  173. for (let b = 0; b < pad.buttons.length; b++) {
  174. s.buttons.push(pad.buttons[b].value);
  175. }
  176. for (let a = 0; a < pad.axes.length; a++) {
  177. s.axes.push(pad.axes[a]);
  178. }
  179. samples.push(s);
  180. }
  181. GodotInputGamepads.samples = samples;
  182. },
  183. init: function (onchange) {
  184. GodotInputGamepads.samples = [];
  185. function add(pad) {
  186. const guid = GodotInputGamepads.get_guid(pad);
  187. const c_id = GodotRuntime.allocString(pad.id);
  188. const c_guid = GodotRuntime.allocString(guid);
  189. onchange(pad.index, 1, c_id, c_guid);
  190. GodotRuntime.free(c_id);
  191. GodotRuntime.free(c_guid);
  192. }
  193. const pads = GodotInputGamepads.get_pads();
  194. for (let i = 0; i < pads.length; i++) {
  195. // Might be reserved space.
  196. if (pads[i]) {
  197. add(pads[i]);
  198. }
  199. }
  200. GodotEventListeners.add(window, 'gamepadconnected', function (evt) {
  201. if (evt.gamepad) {
  202. add(evt.gamepad);
  203. }
  204. }, false);
  205. GodotEventListeners.add(window, 'gamepaddisconnected', function (evt) {
  206. if (evt.gamepad) {
  207. onchange(evt.gamepad.index, 0);
  208. }
  209. }, false);
  210. },
  211. get_guid: function (pad) {
  212. if (pad.mapping) {
  213. return pad.mapping;
  214. }
  215. const ua = navigator.userAgent;
  216. let os = 'Unknown';
  217. if (ua.indexOf('Android') >= 0) {
  218. os = 'Android';
  219. } else if (ua.indexOf('Linux') >= 0) {
  220. os = 'Linux';
  221. } else if (ua.indexOf('iPhone') >= 0) {
  222. os = 'iOS';
  223. } else if (ua.indexOf('Macintosh') >= 0) {
  224. // Updated iPads will fall into this category.
  225. os = 'MacOSX';
  226. } else if (ua.indexOf('Windows') >= 0) {
  227. os = 'Windows';
  228. }
  229. const id = pad.id;
  230. // Chrom* style: NAME (Vendor: xxxx Product: xxxx)
  231. const exp1 = /vendor: ([0-9a-f]{4}) product: ([0-9a-f]{4})/i;
  232. // Firefox/Safari style (safari may remove leading zeores)
  233. const exp2 = /^([0-9a-f]+)-([0-9a-f]+)-/i;
  234. let vendor = '';
  235. let product = '';
  236. if (exp1.test(id)) {
  237. const match = exp1.exec(id);
  238. vendor = match[1].padStart(4, '0');
  239. product = match[2].padStart(4, '0');
  240. } else if (exp2.test(id)) {
  241. const match = exp2.exec(id);
  242. vendor = match[1].padStart(4, '0');
  243. product = match[2].padStart(4, '0');
  244. }
  245. if (!vendor || !product) {
  246. return `${os}Unknown`;
  247. }
  248. return os + vendor + product;
  249. },
  250. },
  251. };
  252. mergeInto(LibraryManager.library, GodotInputGamepads);
  253. /*
  254. * Drag and drop helper.
  255. * This is pretty big, but basically detect dropped files on GodotConfig.canvas,
  256. * process them one by one (recursively for directories), and copies them to
  257. * the temporary FS path '/tmp/drop-[random]/' so it can be emitted as a godot
  258. * event (that requires a string array of paths).
  259. *
  260. * NOTE: The temporary files are removed after the callback. This means that
  261. * deferred callbacks won't be able to access the files.
  262. */
  263. const GodotInputDragDrop = {
  264. $GodotInputDragDrop__deps: ['$FS', '$GodotFS'],
  265. $GodotInputDragDrop: {
  266. promises: [],
  267. pending_files: [],
  268. add_entry: function (entry) {
  269. if (entry.isDirectory) {
  270. GodotInputDragDrop.add_dir(entry);
  271. } else if (entry.isFile) {
  272. GodotInputDragDrop.add_file(entry);
  273. } else {
  274. GodotRuntime.error('Unrecognized entry...', entry);
  275. }
  276. },
  277. add_dir: function (entry) {
  278. GodotInputDragDrop.promises.push(new Promise(function (resolve, reject) {
  279. const reader = entry.createReader();
  280. reader.readEntries(function (entries) {
  281. for (let i = 0; i < entries.length; i++) {
  282. GodotInputDragDrop.add_entry(entries[i]);
  283. }
  284. resolve();
  285. });
  286. }));
  287. },
  288. add_file: function (entry) {
  289. GodotInputDragDrop.promises.push(new Promise(function (resolve, reject) {
  290. entry.file(function (file) {
  291. const reader = new FileReader();
  292. reader.onload = function () {
  293. const f = {
  294. 'path': file.relativePath || file.webkitRelativePath,
  295. 'name': file.name,
  296. 'type': file.type,
  297. 'size': file.size,
  298. 'data': reader.result,
  299. };
  300. if (!f['path']) {
  301. f['path'] = f['name'];
  302. }
  303. GodotInputDragDrop.pending_files.push(f);
  304. resolve();
  305. };
  306. reader.onerror = function () {
  307. GodotRuntime.print('Error reading file');
  308. reject();
  309. };
  310. reader.readAsArrayBuffer(file);
  311. }, function (err) {
  312. GodotRuntime.print('Error!');
  313. reject();
  314. });
  315. }));
  316. },
  317. process: function (resolve, reject) {
  318. if (GodotInputDragDrop.promises.length === 0) {
  319. resolve();
  320. return;
  321. }
  322. GodotInputDragDrop.promises.pop().then(function () {
  323. setTimeout(function () {
  324. GodotInputDragDrop.process(resolve, reject);
  325. }, 0);
  326. });
  327. },
  328. _process_event: function (ev, callback) {
  329. ev.preventDefault();
  330. if (ev.dataTransfer.items) {
  331. // Use DataTransferItemList interface to access the file(s)
  332. for (let i = 0; i < ev.dataTransfer.items.length; i++) {
  333. const item = ev.dataTransfer.items[i];
  334. let entry = null;
  335. if ('getAsEntry' in item) {
  336. entry = item.getAsEntry();
  337. } else if ('webkitGetAsEntry' in item) {
  338. entry = item.webkitGetAsEntry();
  339. }
  340. if (entry) {
  341. GodotInputDragDrop.add_entry(entry);
  342. }
  343. }
  344. } else {
  345. GodotRuntime.error('File upload not supported');
  346. }
  347. new Promise(GodotInputDragDrop.process).then(function () {
  348. const DROP = `/tmp/drop-${parseInt(Math.random() * (1 << 30), 10)}/`;
  349. const drops = [];
  350. const files = [];
  351. FS.mkdir(DROP.slice(0, -1)); // Without trailing slash
  352. GodotInputDragDrop.pending_files.forEach((elem) => {
  353. const path = elem['path'];
  354. GodotFS.copy_to_fs(DROP + path, elem['data']);
  355. let idx = path.indexOf('/');
  356. if (idx === -1) {
  357. // Root file
  358. drops.push(DROP + path);
  359. } else {
  360. // Subdir
  361. const sub = path.substr(0, idx);
  362. idx = sub.indexOf('/');
  363. if (idx < 0 && drops.indexOf(DROP + sub) === -1) {
  364. drops.push(DROP + sub);
  365. }
  366. }
  367. files.push(DROP + path);
  368. });
  369. GodotInputDragDrop.promises = [];
  370. GodotInputDragDrop.pending_files = [];
  371. callback(drops);
  372. if (GodotConfig.persistent_drops) {
  373. // Delay removal at exit.
  374. GodotOS.atexit(function (resolve, reject) {
  375. GodotInputDragDrop.remove_drop(files, DROP);
  376. resolve();
  377. });
  378. } else {
  379. GodotInputDragDrop.remove_drop(files, DROP);
  380. }
  381. });
  382. },
  383. remove_drop: function (files, drop_path) {
  384. const dirs = [drop_path.substr(0, drop_path.length - 1)];
  385. // Remove temporary files
  386. files.forEach(function (file) {
  387. FS.unlink(file);
  388. let dir = file.replace(drop_path, '');
  389. let idx = dir.lastIndexOf('/');
  390. while (idx > 0) {
  391. dir = dir.substr(0, idx);
  392. if (dirs.indexOf(drop_path + dir) === -1) {
  393. dirs.push(drop_path + dir);
  394. }
  395. idx = dir.lastIndexOf('/');
  396. }
  397. });
  398. // Remove dirs.
  399. dirs.sort(function (a, b) {
  400. const al = (a.match(/\//g) || []).length;
  401. const bl = (b.match(/\//g) || []).length;
  402. if (al > bl) {
  403. return -1;
  404. } else if (al < bl) {
  405. return 1;
  406. }
  407. return 0;
  408. }).forEach(function (dir) {
  409. FS.rmdir(dir);
  410. });
  411. },
  412. handler: function (callback) {
  413. return function (ev) {
  414. GodotInputDragDrop._process_event(ev, callback);
  415. };
  416. },
  417. },
  418. };
  419. mergeInto(LibraryManager.library, GodotInputDragDrop);
  420. /*
  421. * Godot exposed input functions.
  422. */
  423. const GodotInput = {
  424. $GodotInput__deps: ['$GodotRuntime', '$GodotConfig', '$GodotEventListeners', '$GodotInputGamepads', '$GodotInputDragDrop', '$GodotIME'],
  425. $GodotInput: {
  426. getModifiers: function (evt) {
  427. return (evt.shiftKey + 0) + ((evt.altKey + 0) << 1) + ((evt.ctrlKey + 0) << 2) + ((evt.metaKey + 0) << 3);
  428. },
  429. computePosition: function (evt, rect) {
  430. const canvas = GodotConfig.canvas;
  431. const rw = canvas.width / rect.width;
  432. const rh = canvas.height / rect.height;
  433. const x = (evt.clientX - rect.x) * rw;
  434. const y = (evt.clientY - rect.y) * rh;
  435. return [x, y];
  436. },
  437. },
  438. /*
  439. * Mouse API
  440. */
  441. godot_js_input_mouse_move_cb__sig: 'vi',
  442. godot_js_input_mouse_move_cb: function (callback) {
  443. const func = GodotRuntime.get_func(callback);
  444. const canvas = GodotConfig.canvas;
  445. function move_cb(evt) {
  446. const rect = canvas.getBoundingClientRect();
  447. const pos = GodotInput.computePosition(evt, rect);
  448. // Scale movement
  449. const rw = canvas.width / rect.width;
  450. const rh = canvas.height / rect.height;
  451. const rel_pos_x = evt.movementX * rw;
  452. const rel_pos_y = evt.movementY * rh;
  453. const modifiers = GodotInput.getModifiers(evt);
  454. func(pos[0], pos[1], rel_pos_x, rel_pos_y, modifiers);
  455. }
  456. GodotEventListeners.add(window, 'mousemove', move_cb, false);
  457. },
  458. godot_js_input_mouse_wheel_cb__sig: 'vi',
  459. godot_js_input_mouse_wheel_cb: function (callback) {
  460. const func = GodotRuntime.get_func(callback);
  461. function wheel_cb(evt) {
  462. if (func(evt['deltaX'] || 0, evt['deltaY'] || 0)) {
  463. evt.preventDefault();
  464. }
  465. }
  466. GodotEventListeners.add(GodotConfig.canvas, 'wheel', wheel_cb, false);
  467. },
  468. godot_js_input_mouse_button_cb__sig: 'vi',
  469. godot_js_input_mouse_button_cb: function (callback) {
  470. const func = GodotRuntime.get_func(callback);
  471. const canvas = GodotConfig.canvas;
  472. function button_cb(p_pressed, evt) {
  473. const rect = canvas.getBoundingClientRect();
  474. const pos = GodotInput.computePosition(evt, rect);
  475. const modifiers = GodotInput.getModifiers(evt);
  476. // Since the event is consumed, focus manually.
  477. // NOTE: The iframe container may not have focus yet, so focus even when already active.
  478. if (p_pressed) {
  479. GodotConfig.canvas.focus();
  480. }
  481. if (func(p_pressed, evt.button, pos[0], pos[1], modifiers)) {
  482. evt.preventDefault();
  483. }
  484. }
  485. GodotEventListeners.add(canvas, 'mousedown', button_cb.bind(null, 1), false);
  486. GodotEventListeners.add(window, 'mouseup', button_cb.bind(null, 0), false);
  487. },
  488. /*
  489. * Touch API
  490. */
  491. godot_js_input_touch_cb__sig: 'viii',
  492. godot_js_input_touch_cb: function (callback, ids, coords) {
  493. const func = GodotRuntime.get_func(callback);
  494. const canvas = GodotConfig.canvas;
  495. function touch_cb(type, evt) {
  496. // Since the event is consumed, focus manually.
  497. // NOTE: The iframe container may not have focus yet, so focus even when already active.
  498. if (type === 0) {
  499. GodotConfig.canvas.focus();
  500. }
  501. const rect = canvas.getBoundingClientRect();
  502. const touches = evt.changedTouches;
  503. for (let i = 0; i < touches.length; i++) {
  504. const touch = touches[i];
  505. const pos = GodotInput.computePosition(touch, rect);
  506. GodotRuntime.setHeapValue(coords + (i * 2) * 8, pos[0], 'double');
  507. GodotRuntime.setHeapValue(coords + (i * 2 + 1) * 8, pos[1], 'double');
  508. GodotRuntime.setHeapValue(ids + i * 4, touch.identifier, 'i32');
  509. }
  510. func(type, touches.length);
  511. if (evt.cancelable) {
  512. evt.preventDefault();
  513. }
  514. }
  515. GodotEventListeners.add(canvas, 'touchstart', touch_cb.bind(null, 0), false);
  516. GodotEventListeners.add(canvas, 'touchend', touch_cb.bind(null, 1), false);
  517. GodotEventListeners.add(canvas, 'touchcancel', touch_cb.bind(null, 1), false);
  518. GodotEventListeners.add(canvas, 'touchmove', touch_cb.bind(null, 2), false);
  519. },
  520. /*
  521. * Key API
  522. */
  523. godot_js_input_key_cb__sig: 'viii',
  524. godot_js_input_key_cb: function (callback, code, key) {
  525. const func = GodotRuntime.get_func(callback);
  526. function key_cb(pressed, evt) {
  527. const modifiers = GodotInput.getModifiers(evt);
  528. GodotRuntime.stringToHeap(evt.code, code, 32);
  529. GodotRuntime.stringToHeap(evt.key, key, 32);
  530. func(pressed, evt.repeat, modifiers);
  531. evt.preventDefault();
  532. }
  533. GodotEventListeners.add(GodotConfig.canvas, 'keydown', key_cb.bind(null, 1), false);
  534. GodotEventListeners.add(GodotConfig.canvas, 'keyup', key_cb.bind(null, 0), false);
  535. },
  536. /*
  537. * IME API
  538. */
  539. godot_js_set_ime_active__proxy: 'sync',
  540. godot_js_set_ime_active__sig: 'vi',
  541. godot_js_set_ime_active: function (p_active) {
  542. GodotIME.ime_active(p_active);
  543. },
  544. godot_js_set_ime_position__proxy: 'sync',
  545. godot_js_set_ime_position__sig: 'vii',
  546. godot_js_set_ime_position: function (p_x, p_y) {
  547. GodotIME.ime_position(p_x, p_y);
  548. },
  549. godot_js_set_ime_cb__proxy: 'sync',
  550. godot_js_set_ime_cb__sig: 'viiii',
  551. godot_js_set_ime_cb: function (p_ime_cb, p_key_cb, code, key) {
  552. const ime_cb = GodotRuntime.get_func(p_ime_cb);
  553. const key_cb = GodotRuntime.get_func(p_key_cb);
  554. GodotIME.init(ime_cb, key_cb, code, key);
  555. },
  556. godot_js_is_ime_focused__proxy: 'sync',
  557. godot_js_is_ime_focused__sig: 'i',
  558. godot_js_is_ime_focused: function () {
  559. return GodotIME.active;
  560. },
  561. /*
  562. * Gamepad API
  563. */
  564. godot_js_input_gamepad_cb__sig: 'vi',
  565. godot_js_input_gamepad_cb: function (change_cb) {
  566. const onchange = GodotRuntime.get_func(change_cb);
  567. GodotInputGamepads.init(onchange);
  568. },
  569. godot_js_input_gamepad_sample_count__sig: 'i',
  570. godot_js_input_gamepad_sample_count: function () {
  571. return GodotInputGamepads.get_samples().length;
  572. },
  573. godot_js_input_gamepad_sample__sig: 'i',
  574. godot_js_input_gamepad_sample: function () {
  575. GodotInputGamepads.sample();
  576. return 0;
  577. },
  578. godot_js_input_gamepad_sample_get__sig: 'iiiiiii',
  579. godot_js_input_gamepad_sample_get: function (p_index, r_btns, r_btns_num, r_axes, r_axes_num, r_standard) {
  580. const sample = GodotInputGamepads.get_sample(p_index);
  581. if (!sample || !sample.connected) {
  582. return 1;
  583. }
  584. const btns = sample.buttons;
  585. const btns_len = btns.length < 16 ? btns.length : 16;
  586. for (let i = 0; i < btns_len; i++) {
  587. GodotRuntime.setHeapValue(r_btns + (i << 2), btns[i], 'float');
  588. }
  589. GodotRuntime.setHeapValue(r_btns_num, btns_len, 'i32');
  590. const axes = sample.axes;
  591. const axes_len = axes.length < 10 ? axes.length : 10;
  592. for (let i = 0; i < axes_len; i++) {
  593. GodotRuntime.setHeapValue(r_axes + (i << 2), axes[i], 'float');
  594. }
  595. GodotRuntime.setHeapValue(r_axes_num, axes_len, 'i32');
  596. const is_standard = sample.standard ? 1 : 0;
  597. GodotRuntime.setHeapValue(r_standard, is_standard, 'i32');
  598. return 0;
  599. },
  600. /*
  601. * Drag/Drop API
  602. */
  603. godot_js_input_drop_files_cb__sig: 'vi',
  604. godot_js_input_drop_files_cb: function (callback) {
  605. const func = GodotRuntime.get_func(callback);
  606. const dropFiles = function (files) {
  607. const args = files || [];
  608. if (!args.length) {
  609. return;
  610. }
  611. const argc = args.length;
  612. const argv = GodotRuntime.allocStringArray(args);
  613. func(argv, argc);
  614. GodotRuntime.freeStringArray(argv, argc);
  615. };
  616. const canvas = GodotConfig.canvas;
  617. GodotEventListeners.add(canvas, 'dragover', function (ev) {
  618. // Prevent default behavior (which would try to open the file(s))
  619. ev.preventDefault();
  620. }, false);
  621. GodotEventListeners.add(canvas, 'drop', GodotInputDragDrop.handler(dropFiles));
  622. },
  623. /* Paste API */
  624. godot_js_input_paste_cb__sig: 'vi',
  625. godot_js_input_paste_cb: function (callback) {
  626. const func = GodotRuntime.get_func(callback);
  627. GodotEventListeners.add(window, 'paste', function (evt) {
  628. const text = evt.clipboardData.getData('text');
  629. const ptr = GodotRuntime.allocString(text);
  630. func(ptr);
  631. GodotRuntime.free(ptr);
  632. }, false);
  633. },
  634. godot_js_input_vibrate_handheld__sig: 'vi',
  635. godot_js_input_vibrate_handheld: function (p_duration_ms) {
  636. if (typeof navigator.vibrate !== 'function') {
  637. GodotRuntime.print('This browser does not support vibration.');
  638. } else {
  639. navigator.vibrate(p_duration_ms);
  640. }
  641. },
  642. };
  643. autoAddDeps(GodotInput, '$GodotInput');
  644. mergeInto(LibraryManager.library, GodotInput);