library_godot_input.js 22 KB

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