library_godot_input.js 22 KB

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