library_godot_input.js 22 KB

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