Debian Codegraph @

platform/web/js/libs/library_godot_input.js

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