Keyboard::physicalHeld() and physicalPressed(): the physical keys as SDL scancodes (where the key is, whatever the layout), what a remote console (VNC / QEMU) needs so the remote machine applies its own layout. Desktop: SDL's keyboard state. Browser: SDL's emscripten port makes its scancodes from the character (AZERTY's "a" key came out as A), so the page sends KeyboardEvent.code itself (jumphp-device.js, JsBridge 'physkey'); physicalPressed() keeps a quick tap that went down and up between two frames. Co-Authored-By: Claude Opus 5.5 <[email protected]>
201 lines
8.8 KiB
JavaScript
201 lines
8.8 KiB
JavaScript
// Page life and phone features for PHP (JumPHP\Device\Lifecycle, JumPHP\Device\Device).
|
|
// - page -> PHP: JsBridge 'page' events (hide, show, blur, focus, online, offline, resize, fullscreen, close)
|
|
// and 'device' events (tilt, motion, battery). 'hide' and 'close' are delivered at once (api.now(): PHP runs
|
|
// between two frames), so the game can save before the tab freezes or goes away.
|
|
// - PHP -> page: JsBridge 'device' messages {do: vibrate | awake | orientation | fullscreen | copy | motion}.
|
|
export function install(api) {
|
|
const orientation = () => (innerWidth >= innerHeight ? 'landscape' : 'portrait');
|
|
const page = (e, extra = {}, key = null) => api.send('page', { e, ...extra }, key);
|
|
|
|
// the state before the first frame (no events)
|
|
api.send('page', {
|
|
e: 'state', visible: !document.hidden, focus: document.hasFocus(), online: navigator.onLine !== false,
|
|
w: innerWidth, h: innerHeight, o: orientation(),
|
|
});
|
|
|
|
document.addEventListener('visibilitychange', () => {
|
|
if (document.hidden) {
|
|
page('hide');
|
|
api.now();
|
|
window.saveUserFiles?.();
|
|
} else {
|
|
page('show');
|
|
if (wantAwake) lockAwake();
|
|
}
|
|
});
|
|
addEventListener('blur', () => { page('blur'); api.send('physkey', { code: '', down: false }); });
|
|
// the physical keys (KeyboardEvent.code: where the key is, whatever the layout) for Keyboard::physicalHeld(): a remote
|
|
// console (VNC) lets the remote machine apply its own layout. SDL's emscripten port makes its scancodes from the character.
|
|
const physical = (down) => (e) => { if (!e.repeat && e.code) api.send('physkey', { code: e.code, down }); };
|
|
addEventListener('keydown', physical(true), true);
|
|
addEventListener('keyup', physical(false), true);
|
|
addEventListener('focus', () => page('focus'));
|
|
addEventListener('online', () => page('online'));
|
|
addEventListener('offline', () => page('offline'));
|
|
addEventListener('resize', () => page('resize', { w: innerWidth, h: innerHeight, o: orientation() }, 'resize'));
|
|
const fullscreenChanged = () => page('fullscreen', { on: !!api.isFullscreen() }, 'fullscreen');
|
|
document.addEventListener('fullscreenchange', fullscreenChanged);
|
|
document.addEventListener('webkitfullscreenchange', fullscreenChanged);
|
|
addEventListener('pagehide', () => {
|
|
page('close');
|
|
api.now();
|
|
window.saveUserFiles?.();
|
|
});
|
|
|
|
// --- screen awake (Wake Lock: lost when the tab is hidden, taken again when it comes back) ---
|
|
let wantAwake = false;
|
|
let sentinel = null;
|
|
function lockAwake() {
|
|
if (!navigator.wakeLock || sentinel) return;
|
|
navigator.wakeLock.request('screen').then((s) => {
|
|
sentinel = s;
|
|
s.addEventListener('release', () => { sentinel = null; });
|
|
}).catch(() => {});
|
|
}
|
|
|
|
// --- sensors ---
|
|
let motionOn = false;
|
|
function startMotion() {
|
|
if (motionOn) return;
|
|
motionOn = true;
|
|
const clamp = (v) => Math.max(-1, Math.min(1, v));
|
|
addEventListener('deviceorientation', (e) => {
|
|
if (e.gamma == null) return;
|
|
// beta: front/back (90 = upright), gamma: left/right; the screen turned: axes turn too
|
|
let x = e.gamma / 45;
|
|
let y = (e.beta - 45) / 45;
|
|
const angle = (screen.orientation && screen.orientation.angle) || window.orientation || 0;
|
|
if (angle === 90) [x, y] = [e.beta / 45, -e.gamma / 45 - 1];
|
|
else if (angle === -90 || angle === 270) [x, y] = [-e.beta / 45, e.gamma / 45 - 1];
|
|
api.send('device', { tilt: [clamp(x), clamp(y)] }, 'tilt');
|
|
});
|
|
addEventListener('devicemotion', (e) => {
|
|
const a = e.accelerationIncludingGravity;
|
|
if (a && a.x != null) api.send('device', { motion: [a.x, a.y, a.z] }, 'motion');
|
|
});
|
|
}
|
|
function requestMotion() {
|
|
const ask = window.DeviceOrientationEvent && DeviceOrientationEvent.requestPermission;
|
|
if (!ask) { startMotion(); return; }
|
|
// iOS: only from a user gesture
|
|
api.gesture(() => {
|
|
DeviceOrientationEvent.requestPermission().then((r) => { if (r === 'granted') startMotion(); }).catch(() => {});
|
|
window.DeviceMotionEvent?.requestPermission?.().catch(() => {});
|
|
});
|
|
}
|
|
|
|
// --- battery (Chromium) ---
|
|
if (navigator.getBattery) {
|
|
navigator.getBattery().then((b) => {
|
|
const send = () => api.send('device', { battery: { level: b.level, charging: b.charging } }, 'battery');
|
|
send();
|
|
b.addEventListener('levelchange', send);
|
|
b.addEventListener('chargingchange', send);
|
|
}).catch(() => {});
|
|
}
|
|
|
|
api.on('device', (msg) => {
|
|
switch (msg.do) {
|
|
case 'vibrate':
|
|
try { navigator.vibrate?.(msg.pattern); } catch (e) { /* not allowed before a gesture */ }
|
|
break;
|
|
case 'awake':
|
|
wantAwake = !!msg.on;
|
|
if (wantAwake) lockAwake();
|
|
else if (sentinel) { sentinel.release().catch(() => {}); sentinel = null; }
|
|
break;
|
|
case 'orientation':
|
|
if (!screen.orientation) break;
|
|
if (msg.o === 'any') { try { screen.orientation.unlock(); } catch (e) { /* not locked */ } } else screen.orientation.lock(msg.o).catch(() => {});
|
|
break;
|
|
case 'fullscreen':
|
|
if (!!msg.on === !!api.isFullscreen()) break;
|
|
// browsers want a user gesture: now if it works, else at the next tap / key
|
|
if (msg.on) api.enterFullscreen().then(() => { if (!api.isFullscreen()) api.gesture(() => api.enterFullscreen()); });
|
|
else api.exitFullscreen();
|
|
break;
|
|
case 'copy':
|
|
if (navigator.clipboard?.writeText) {
|
|
navigator.clipboard.writeText(msg.text).catch(() => api.gesture(() => navigator.clipboard.writeText(msg.text).catch(() => {})));
|
|
}
|
|
break;
|
|
case 'paste':
|
|
// the text of a Ctrl+V that just happened (PHP asked before its event reached it), else the menu's Paste: the clipboard
|
|
// API, which asks a permission
|
|
if (lastPaste !== null && performance.now() - lastPasteAt < 1500) {
|
|
api.send('paste', { text: lastPaste });
|
|
lastPaste = null;
|
|
} else if (navigator.clipboard?.readText) {
|
|
navigator.clipboard.readText().then((text) => api.send('paste', { text })).catch(() => api.send('paste', { text: null }));
|
|
} else api.send('paste', { text: null });
|
|
break;
|
|
case 'motion':
|
|
requestMotion();
|
|
break;
|
|
}
|
|
});
|
|
|
|
// Ctrl+V / the browser's Paste: the text of the event goes to PHP (BrowserProvider::paste), no clipboard permission needed
|
|
let lastPaste = null;
|
|
let lastPasteAt = 0;
|
|
document.addEventListener('paste', (e) => {
|
|
if (e.target && e.target.tagName === 'INPUT') return; // the phone keyboard's hidden input types the text itself
|
|
const text = e.clipboardData ? e.clipboardData.getData('text/plain') : '';
|
|
if (e.target === sink) e.preventDefault(); // nothing stays in the catcher
|
|
if (text === '') return;
|
|
lastPaste = text;
|
|
lastPasteAt = performance.now();
|
|
api.send('paste', { text });
|
|
});
|
|
// SDL cancels every key it reads (preventDefault), Ctrl+V included, and a cancelled Ctrl+V has no paste event: for that key, its
|
|
// cancel does nothing, and a hidden text area takes the focus for the paste (the browser only pastes into something
|
|
// editable), then gives it back to the game; the key still reaches SDL, so the text field knows a paste was asked
|
|
const sink = document.createElement('textarea');
|
|
sink.setAttribute('aria-hidden', 'true');
|
|
sink.tabIndex = -1;
|
|
sink.style.cssText = 'position:fixed;left:-100px;top:0;width:1px;height:1px;opacity:0;border:0;padding:0;';
|
|
(document.body || document.documentElement).appendChild(sink);
|
|
addEventListener('keydown', (e) => {
|
|
const paste = ((e.ctrlKey || e.metaKey) && !e.altKey && (e.key === 'v' || e.key === 'V')) || (e.shiftKey && e.key === 'Insert');
|
|
const t = e.target;
|
|
if (!paste || (t && t !== sink && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable))) return;
|
|
e.preventDefault = () => {};
|
|
const back = document.activeElement;
|
|
sink.value = '';
|
|
sink.focus({ preventScroll: true });
|
|
setTimeout(() => { if (document.activeElement === sink) back && back !== sink && back.focus ? back.focus({ preventScroll: true }) : sink.blur(); }, 0);
|
|
}, true);
|
|
|
|
// the file chooser (JumPHP\Native\FilePicker in the browser): the files chosen are written into the engine's memory, PHP gets their paths.
|
|
// Called from a click handler of the application: the browser still counts it as the user's gesture.
|
|
api.on('filepick', (msg) => {
|
|
const input = document.createElement('input');
|
|
input.type = 'file';
|
|
input.multiple = !!msg.multiple;
|
|
if (msg.accept) input.accept = msg.accept;
|
|
input.style.display = 'none';
|
|
document.body.appendChild(input);
|
|
let done = false;
|
|
const finish = (paths) => {
|
|
if (done) return;
|
|
done = true;
|
|
input.remove();
|
|
api.send('filepick', { id: msg.id, paths });
|
|
};
|
|
input.addEventListener('change', async () => {
|
|
const FS = api.FS();
|
|
try {
|
|
FS.mkdirTree('/tmp/jumphp-picked');
|
|
const paths = [];
|
|
for (const file of input.files) {
|
|
const path = '/tmp/jumphp-picked/' + file.name.replace(/[\\/]/g, '_');
|
|
FS.writeFile(path, new Uint8Array(await file.arrayBuffer()));
|
|
paths.push(path);
|
|
}
|
|
finish(paths);
|
|
} catch (e) { finish(null); }
|
|
});
|
|
input.addEventListener('cancel', () => finish(null));
|
|
input.click();
|
|
});
|
|
}
|