library_godot_input.js 22 KB

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