Files
chandra/remote/web/index.html
T
nandiandClaude Opus 5.5 30086562bc
Deploy to the handset / build-and-deploy (push) Successful in 2m10s
CI / test (push) Failing after 2m45s
Remote: right-click opens the desktop's menu, not the browser's
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 18:04:40 -08:00

1073 lines
39 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover">
<meta name="theme-color" content="#0b1020">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<link rel="manifest" href="/manifest.json">
<link rel="icon" href="/icon.svg" type="image/svg+xml">
<title>Chandra Remote</title>
<style>
:root {
--bg: #0b1020;
--panel: rgba(15, 23, 42, 0.88);
--border: rgba(148, 163, 184, 0.24);
--accent: #38bdf8;
--text: #e2e8f0;
--muted: #94a3b8;
--ok: #22c55e;
--warn: #f59e0b;
--err: #ef4444;
}
* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
html, body {
margin: 0; padding: 0; width: 100%; height: 100%;
overflow: hidden; background: var(--bg); color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
overscroll-behavior: none; user-select: none; -webkit-user-select: none;
}
#stage {
position: fixed; inset: 0;
display: flex; align-items: center; justify-content: center;
background: #050814; touch-action: none;
}
#screen {
display: block; max-width: 100%; max-height: 100%;
touch-action: none; image-rendering: auto;
box-shadow: 0 10px 40px rgba(0,0,0,0.65);
}
#cursor {
position: fixed; width: 16px; height: 16px; border-radius: 50%;
border: 2px solid #fff; background: rgba(56, 189, 248, 0.45);
box-shadow: 0 0 6px rgba(0,0,0,0.8);
pointer-events: none; transform: translate(-50%, -50%);
display: none; z-index: 20;
}
#pillWrap {
position: fixed; top: max(8px, env(safe-area-inset-top)); right: max(8px, env(safe-area-inset-right));
z-index: 30; display: flex; flex-direction: column; align-items: flex-end; gap: 6px;
}
#pillBar {
display: flex; align-items: center; gap: 6px; padding: 5px 8px;
background: var(--panel); border: 1px solid var(--border);
border-radius: 999px; backdrop-filter: blur(12px);
box-shadow: 0 6px 20px rgba(0,0,0,0.45);
}
.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--warn); flex: none; }
.dot.ok { background: var(--ok); }
.dot.err { background: var(--err); }
button.btn {
appearance: none; border: 1px solid var(--border);
background: rgba(30, 41, 59, 0.85); color: var(--text);
border-radius: 999px; padding: 5px 10px; font-size: 12px; font-weight: 600;
cursor: pointer; line-height: 1.2;
}
button.btn.active { background: var(--accent); color: #06131f; border-color: var(--accent); }
button.btn:active { transform: scale(0.95); }
#drawer {
display: none; flex-direction: column; gap: 8px; width: min(296px, calc(100vw - 16px));
padding: 12px; border-radius: 16px;
background: var(--panel); border: 1px solid var(--border);
backdrop-filter: blur(14px); box-shadow: 0 12px 32px rgba(0,0,0,0.55);
}
#drawer.open { display: flex; }
.row { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
.row-label { font-size: 11px; color: var(--muted); min-width: 68px; }
input[type=range] { flex: 1; accent-color: var(--accent); }
#kbdBar {
position: fixed; left: 0; right: 0; bottom: 0; z-index: 35;
display: none; gap: 5px; padding: 6px 8px calc(6px + env(safe-area-inset-bottom));
background: rgba(15, 23, 42, 0.96); border-top: 1px solid var(--border);
overflow-x: auto; white-space: nowrap;
}
#kbdBar.open { display: flex; }
#kbdInput {
position: fixed; left: -9999px; top: 0; width: 1px; height: 1px;
opacity: 0; border: 0; padding: 0; font-size: 16px;
}
#pasteSink {
position: fixed; left: -9999px; top: 0; width: 1px; height: 1px;
overflow: hidden; opacity: 0; outline: 0;
user-select: text; -webkit-user-select: text;
}
#toast {
position: fixed; left: 50%; bottom: calc(64px + env(safe-area-inset-bottom));
transform: translateX(-50%); z-index: 40; display: none;
max-width: calc(100vw - 32px); padding: 8px 14px; border-radius: 999px;
background: var(--panel); border: 1px solid var(--border);
font-size: 13px; pointer-events: none;
}
#toast.open { display: block; }
#toast.err { border-color: var(--err); }
#loginMask {
position: fixed; inset: 0; z-index: 50; display: none;
align-items: center; justify-content: center; padding: 20px;
background: rgba(5, 8, 20, 0.92); backdrop-filter: blur(8px);
}
#loginMask.open { display: flex; }
.card {
width: min(340px, 100%); padding: 22px; border-radius: 18px;
background: #0f172a; border: 1px solid var(--border);
box-shadow: 0 20px 50px rgba(0,0,0,0.6);
}
.card h1 { margin: 0 0 6px; font-size: 19px; }
.card p { margin: 0 0 14px; color: var(--muted); font-size: 13px; }
.card input[type=password] {
width: 100%; padding: 11px 12px; border-radius: 10px;
border: 1px solid var(--border); background: #090e1c; color: var(--text);
font-size: 15px; margin-bottom: 12px; outline: none;
}
.card button {
width: 100%; padding: 11px; border: 0; border-radius: 10px;
background: var(--accent); color: #06131f; font-size: 14px; font-weight: 700; cursor: pointer;
}
#loginErr { color: #f87171; font-size: 12px; margin-top: 8px; min-height: 16px; }
</style>
</head>
<body>
<div id="stage">
<canvas id="screen" width="540" height="1170"></canvas>
</div>
<div id="cursor"></div>
<div id="pillWrap">
<div id="pillBar">
<span id="statusDot" class="dot" title="Connecting"></span>
<button id="kbBtn" class="btn">KB</button>
<button id="modeBtn" class="btn">Touch</button>
<button id="menuBtn" class="btn">⋮</button>
</div>
<div id="drawer">
<div class="row">
<button class="btn" data-ctl="rotate cw">Rotate 90°</button>
<button class="btn" data-ctl="rotate flip">Flip 180°</button>
<button id="screenBtn" class="btn" data-ctl="screen toggle">OLED</button>
</div>
<div class="row">
<span class="row-label">Bright <span id="briVal">--</span>%</span>
<input id="briSlider" type="range" min="5" max="100" value="60">
</div>
<div class="row">
<button id="oskBtn" class="btn" data-ctl="osk toggle">Phone OSK</button>
<button class="btn" data-ctl="shortcut launcher">Launcher</button>
<button class="btn" data-ctl="shortcut overview">Overview</button>
</div>
<div class="row">
<button id="clipBtn" class="btn">Send Clipboard</button>
<button id="imgBtn" class="btn">Paste Image…</button>
<button id="fsBtn" class="btn">Fullscreen</button>
<button class="btn" data-ctl="refresh">Redraw</button>
</div>
<div class="row">
<span class="row-label">Quality</span>
<button class="btn qbtn" data-q="55" data-fps="24">Fast</button>
<button class="btn qbtn active" data-q="82" data-fps="30">Balanced</button>
<button class="btn qbtn" data-q="92" data-fps="30">Sharp</button>
</div>
<div id="infoLine" style="font-size:11px;color:var(--muted);">540x1170 · Connecting…</div>
</div>
</div>
<div id="kbdBar">
<button class="btn kspecial" data-code="1">Esc</button>
<button class="btn kspecial" data-code="15">Tab</button>
<button id="modCtrl" class="btn kmod" data-bit="4">Ctrl</button>
<button id="modAlt" class="btn kmod" data-bit="8">Alt</button>
<button class="btn kspecial" data-code="125">Super</button>
<button class="btn kspecial" data-code="105">←</button>
<button class="btn kspecial" data-code="103">↑</button>
<button class="btn kspecial" data-code="108">↓</button>
<button class="btn kspecial" data-code="106">→</button>
<button id="pasteBtn" class="btn">Paste</button>
<button id="kbHideBtn" class="btn">Done</button>
</div>
<input id="kbdInput" type="text" value=" " autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
<div id="pasteSink" contenteditable="true" inputmode="none" tabindex="-1" aria-hidden="true"></div>
<input id="imgInput" type="file" accept="image/*" hidden>
<div id="toast" role="status"></div>
<div id="loginMask">
<form id="loginForm" class="card">
<h1>Chandra Remote</h1>
<p>Enter your remote desktop password</p>
<input id="passInput" type="password" placeholder="Password" autocomplete="current-password">
<button type="submit">Connect</button>
<div id="loginErr"></div>
</form>
</div>
<script>
(() => {
const canvas = document.getElementById('screen');
const ctx = canvas.getContext('2d', { alpha: false });
const stage = document.getElementById('stage');
const dot = document.getElementById('statusDot');
const infoLine = document.getElementById('infoLine');
const drawer = document.getElementById('drawer');
const menuBtn = document.getElementById('menuBtn');
const modeBtn = document.getElementById('modeBtn');
const cursorEl = document.getElementById('cursor');
const kbBtn = document.getElementById('kbBtn');
const kbdBar = document.getElementById('kbdBar');
const kbdInput = document.getElementById('kbdInput');
const screenBtn = document.getElementById('screenBtn');
const oskBtn = document.getElementById('oskBtn');
const briSlider = document.getElementById('briSlider');
const briVal = document.getElementById('briVal');
const loginMask = document.getElementById('loginMask');
const loginForm = document.getElementById('loginForm');
const passInput = document.getElementById('passInput');
const loginErr = document.getElementById('loginErr');
const pasteSink = document.getElementById('pasteSink');
const imgInput = document.getElementById('imgInput');
const toastEl = document.getElementById('toast');
let ws = null;
let token = localStorage.getItem('chandra_remote_token') || '';
let authRequired = false;
let reconnectTimer = null;
let trackpadMode = false;
let cursorX = 270, cursorY = 585;
let stickyMods = 0;
let kbOpen = false;
let keyHandled = false;
let lastPtrSent = 0;
/* While a paste is uploading, typing waits for it, so "Ctrl+V, Enter" arrives in that order. */
const HELD_WHILE_PASTING = new Set(['key', 'ktap', 'text', 'release']);
let pastesInFlight = 0;
let heldMessages = [];
function sendJson(obj) {
if (pastesInFlight > 0 && HELD_WHILE_PASTING.has(obj.t)) {
heldMessages.push(obj);
return;
}
sendNow(obj);
}
function sendNow(obj) {
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(obj));
}
}
function setStatusDot(cls, label) {
dot.className = 'dot ' + cls;
dot.title = label;
}
function layoutCursor() {
if (!trackpadMode) { cursorEl.style.display = 'none'; return; }
const r = canvas.getBoundingClientRect();
if (r.width <= 0 || r.height <= 0) return;
cursorEl.style.display = 'block';
cursorEl.style.left = (r.left + (cursorX / canvas.width) * r.width) + 'px';
cursorEl.style.top = (r.top + (cursorY / canvas.height) * r.height) + 'px';
}
function clientToFb(cx, cy) {
const r = canvas.getBoundingClientRect();
if (r.width <= 0 || r.height <= 0) return [0, 0];
const x = Math.round(((cx - r.left) / r.width) * canvas.width);
const y = Math.round(((cy - r.top) / r.height) * canvas.height);
return [
Math.max(0, Math.min(canvas.width - 1, x)),
Math.max(0, Math.min(canvas.height - 1, y))
];
}
let frameQueue = Promise.resolve();
function handleBinary(buf) {
if (buf.byteLength < 18) return;
const dv = new DataView(buf);
const type = dv.getUint8(0);
if (type !== 1) return;
const x = dv.getUint16(2);
const y = dv.getUint16(4);
const w = dv.getUint16(6);
const h = dv.getUint16(8);
const fbW = dv.getUint16(10);
const fbH = dv.getUint16(12);
const fid = dv.getUint32(14);
const blob = new Blob([buf.slice(18)], { type: 'image/jpeg' });
frameQueue = frameQueue.then(async () => {
try {
const bmp = await createImageBitmap(blob);
if (fbW > 0 && fbH > 0 && (canvas.width !== fbW || canvas.height !== fbH)) {
canvas.width = fbW;
canvas.height = fbH;
cursorX = Math.max(0, Math.min(fbW - 1, cursorX));
cursorY = Math.max(0, Math.min(fbH - 1, cursorY));
layoutCursor();
}
ctx.drawImage(bmp, x, y, w, h);
bmp.close();
} catch (e) {
console.error(e);
} finally {
sendJson({ t: 'ack', id: fid });
}
});
}
function handleText(str) {
try {
const m = JSON.parse(str);
if (m.t === 'status') {
infoLine.textContent = `${m.w}×${m.h} · ${m.rot}° · OLED ${m.screen} · Bright ${m.brightness}%`;
screenBtn.classList.toggle('active', m.screen === 'off');
screenBtn.textContent = m.screen === 'off' ? 'OLED Off' : 'OLED On';
oskBtn.classList.toggle('active', m.osk === 1);
if (m.brightness >= 5) {
briSlider.value = m.brightness;
briVal.textContent = String(m.brightness);
}
}
} catch (_) {}
}
function connectWs() {
if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
if (ws) { try { ws.close(); } catch (_) {} }
setStatusDot('', 'Connecting');
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
const q = token ? ('?token=' + encodeURIComponent(token)) : '';
const sock = new WebSocket(proto + '//' + location.host + '/ws' + q);
sock.binaryType = 'arraybuffer';
ws = sock;
sock.onopen = () => {
setStatusDot('ok', 'Connected');
noteClipboardBase();
loginMask.classList.remove('open');
};
sock.onmessage = (ev) => {
if (typeof ev.data === 'string') handleText(ev.data);
else handleBinary(ev.data);
};
sock.onclose = async () => {
if (ws !== sock) return;
releaseAllKeys();
setStatusDot('err', 'Disconnected');
await bootstrap();
};
}
async function bootstrap() {
try {
const r = await fetch('/api/info', { cache: 'no-store' });
const info = await r.json();
authRequired = !!info.auth_required;
if (!authRequired) {
loginMask.classList.remove('open');
connectWs();
return;
}
if (token) {
connectWs();
return;
}
loginMask.classList.add('open');
passInput.focus();
} catch (_) {
setStatusDot('err', 'Offline');
reconnectTimer = setTimeout(bootstrap, 2000);
}
}
loginForm.addEventListener('submit', async (e) => {
e.preventDefault();
loginErr.textContent = '';
try {
const r = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password: passInput.value })
});
const d = await r.json();
if (!r.ok || !d.ok) {
loginErr.textContent = d.error || 'Invalid password';
return;
}
token = d.token || '';
localStorage.setItem('chandra_remote_token', token);
passInput.value = '';
connectWs();
} catch (_) {
loginErr.textContent = 'Connection failed';
}
});
/* ---- Touch & Trackpad pointer handling ---- */
let pointers = new Map();
let gesture = null;
function clearLongTimer() {
if (gesture && gesture.longTimer) {
clearTimeout(gesture.longTimer);
gesture.longTimer = null;
}
}
stage.addEventListener('pointerdown', (e) => {
if (e.target.closest('#pillWrap') || e.target.closest('#kbdBar') || e.target.closest('#loginMask')) return;
if (document.activeElement && document.activeElement !== document.body && document.activeElement !== kbdInput) {
document.activeElement.blur();
}
e.preventDefault();
if (e.button === 2) { /* a mouse's right button, or a pen's */
const [x, y] = trackpadMode ? [cursorX, cursorY] : clientToFb(e.clientX, e.clientY);
sendJson({ t: 'tap', x, y, b: 3 });
return;
}
stage.setPointerCapture(e.pointerId);
pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
if (pointers.size === 1) {
const [fx, fy] = clientToFb(e.clientX, e.clientY);
gesture = {
mode: 'one',
sx: e.clientX, sy: e.clientY,
lx: e.clientX, ly: e.clientY,
sfx: fx, sfy: fy,
fx, fy, moved: false, dragging: false, longFired: false,
longTimer: setTimeout(() => {
if (!gesture || gesture.mode !== 'one' || gesture.moved) return;
gesture.longFired = true;
if (navigator.vibrate) navigator.vibrate(25);
const rx = trackpadMode ? cursorX : gesture.sfx;
const ry = trackpadMode ? cursorY : gesture.sfy;
sendJson({ t: 'tap', x: rx, y: ry, b: 3 });
}, 450)
};
} else if (pointers.size === 2) {
clearLongTimer();
if (gesture && gesture.dragging) sendJson({ t: 'btn', b: 1, d: 0 });
const pts = [...pointers.values()];
const cx = (pts[0].x + pts[1].x) / 2;
const cy = (pts[0].y + pts[1].y) / 2;
const [fx, fy] = clientToFb(cx, cy);
gesture = { mode: 'two', sx: cx, sy: cy, lx: cx, ly: cy, fx, fy, moved: false };
}
});
stage.addEventListener('pointermove', (e) => {
if (!pointers.has(e.pointerId) || !gesture) return;
e.preventDefault();
pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
if (gesture.mode === 'one' && pointers.size === 1) {
const dist = Math.hypot(e.clientX - gesture.sx, e.clientY - gesture.sy);
if (trackpadMode) {
const dx = (e.clientX - gesture.lx) * 1.45;
const dy = (e.clientY - gesture.ly) * 1.45;
gesture.lx = e.clientX;
gesture.ly = e.clientY;
if (dist > 8) { gesture.moved = true; clearLongTimer(); }
cursorX = Math.max(0, Math.min(canvas.width - 1, Math.round(cursorX + dx)));
cursorY = Math.max(0, Math.min(canvas.height - 1, Math.round(cursorY + dy)));
layoutCursor();
const now = performance.now();
if (now - lastPtrSent >= 16) {
lastPtrSent = now;
sendJson({ t: 'ptr', x: cursorX, y: cursorY });
}
return;
}
const [fx, fy] = clientToFb(e.clientX, e.clientY);
gesture.fx = fx; gesture.fy = fy;
if (!gesture.moved && dist > 14) {
gesture.moved = true;
clearLongTimer();
if (!gesture.longFired) {
gesture.dragging = true;
sendJson({ t: 'ptr', x: gesture.sfx, y: gesture.sfy });
sendJson({ t: 'btn', b: 1, d: 1 });
sendJson({ t: 'ptr', x: fx, y: fy });
}
} else if (gesture.dragging) {
const now = performance.now();
if (now - lastPtrSent >= 16) {
lastPtrSent = now;
sendJson({ t: 'ptr', x: fx, y: fy });
}
}
} else if (gesture.mode === 'two' && pointers.size >= 2) {
const pts = [...pointers.values()];
const cx = (pts[0].x + pts[1].x) / 2;
const cy = (pts[0].y + pts[1].y) / 2;
if (Math.hypot(cx - gesture.sx, cy - gesture.sy) > 8) gesture.moved = true;
const dx = Math.round(gesture.lx - cx);
const dy = Math.round(gesture.ly - cy);
gesture.lx = cx; gesture.ly = cy;
if (dx !== 0 || dy !== 0) {
const sx = trackpadMode ? cursorX : gesture.fx;
const sy = trackpadMode ? cursorY : gesture.fy;
sendJson({ t: 'scroll', x: sx, y: sy, dx, dy });
}
}
});
function onPointerFinish(e) {
if (!pointers.has(e.pointerId)) return;
pointers.delete(e.pointerId);
if (!gesture) return;
clearLongTimer();
if (gesture.mode === 'one' && pointers.size === 0) {
if (gesture.dragging) {
const [fx, fy] = clientToFb(e.clientX, e.clientY);
sendJson({ t: 'ptr', x: fx, y: fy });
sendJson({ t: 'btn', b: 1, d: 0 });
} else if (!gesture.moved && !gesture.longFired) {
const tx = trackpadMode ? cursorX : gesture.sfx;
const ty = trackpadMode ? cursorY : gesture.sfy;
sendJson({ t: 'tap', x: tx, y: ty, b: 1 });
}
gesture = null;
} else if (gesture.mode === 'two' && pointers.size === 0) {
if (!gesture.moved) {
const tx = trackpadMode ? cursorX : gesture.fx;
const ty = trackpadMode ? cursorY : gesture.fy;
sendJson({ t: 'tap', x: tx, y: ty, b: 3 });
}
gesture = null;
}
}
stage.addEventListener('pointerup', onPointerFinish);
stage.addEventListener('pointercancel', onPointerFinish);
/* The desktop's own menu opens on right-click and long-press; keep the browser's off it. */
document.addEventListener('contextmenu', (e) => {
if (e.target !== passInput) e.preventDefault();
});
stage.addEventListener('wheel', (e) => {
e.preventDefault();
const [fx, fy] = trackpadMode ? [cursorX, cursorY] : clientToFb(e.clientX, e.clientY);
sendJson({ t: 'scroll', x: fx, y: fy, dx: Math.round(e.deltaX), dy: Math.round(e.deltaY) });
}, { passive: false });
/* ---- Global desktop physical-keyboard forwarding ---- */
const pressedKeys = new Map();
function eventToKeysym(e) {
switch (e.key) {
case 'Backspace': return 0xFF08;
case 'Tab': return 0xFF09;
case 'Enter': return e.code === 'NumpadEnter' ? 0xFF8D : 0xFF0D;
case 'Escape': return 0xFF1B;
case 'Insert': return 0xFF63;
case 'Delete': return 0xFFFF;
case 'Home': return 0xFF50;
case 'End': return 0xFF57;
case 'PageUp': return 0xFF55;
case 'PageDown': return 0xFF56;
case 'ArrowLeft': return 0xFF51;
case 'ArrowUp': return 0xFF52;
case 'ArrowRight': return 0xFF53;
case 'ArrowDown': return 0xFF54;
case 'Shift': return e.code === 'ShiftRight' ? 0xFFE2 : 0xFFE1;
case 'Control': return e.code === 'ControlRight' ? 0xFFE4 : 0xFFE3;
case 'Alt': return e.code === 'AltRight' ? 0xFFEA : 0xFFE9;
case 'AltGraph': return 0xFE03;
case 'Meta': return e.code === 'MetaRight' ? 0xFFEC : 0xFFEB;
case 'CapsLock': return 0xFFE5;
case 'NumLock': return 0xFF7F;
case 'ContextMenu': return 0xFF67;
case 'PrintScreen': return 0xFF61;
case 'Pause': return 0xFF13;
case 'AudioVolumeDown': return 0x1008FF11;
case 'AudioVolumeMute': return 0x1008FF12;
case 'AudioVolumeUp': return 0x1008FF13;
}
const fm = /^F([1-9]|1[0-2])$/.exec(e.key);
if (fm) return 0xFFBE + (Number(fm[1]) - 1);
if (e.key.length === 1) {
const cp = e.key.codePointAt(0);
if (cp >= 0x20 && cp <= 0x7E) return cp;
}
if ((e.ctrlKey || e.altKey || e.metaKey) && e.code) {
const km = /^Key([A-Z])$/.exec(e.code);
if (km) {
const ch = e.shiftKey ? km[1] : km[1].toLowerCase();
return ch.charCodeAt(0);
}
const dm = /^Digit([0-9])$/.exec(e.code);
if (dm) return dm[1].charCodeAt(0);
}
return null;
}
function releaseAllKeys() {
if (pressedKeys.size > 0) {
for (const sym of [...pressedKeys.values()].reverse()) {
sendJson({ t: 'key', k: sym, d: 0 });
}
pressedKeys.clear();
}
sendJson({ t: 'release' });
}
window.addEventListener('keydown', (e) => {
if (!ws || ws.readyState !== WebSocket.OPEN) return;
if (loginMask.classList.contains('open')) return;
if (e.target === passInput || e.target === briSlider || e.target === kbdInput) return;
if (e.isComposing || e.key === 'Unidentified' || e.key === 'Process' || e.key === 'Dead') return;
if (beginKeyPaste(e)) return;
const sym = eventToKeysym(e);
if (sym !== null) {
e.preventDefault();
const id = e.code || e.key;
if (e.repeat && pressedKeys.has(id)) return;
pressedKeys.set(id, sym);
sendJson({ t: 'key', k: sym, d: 1 });
} else if (e.key.length === 1 && !e.ctrlKey && !e.altKey && !e.metaKey) {
e.preventDefault();
sendJson({ t: 'text', s: e.key });
}
});
window.addEventListener('keyup', (e) => {
if (!ws || ws.readyState !== WebSocket.OPEN) return;
if (loginMask.classList.contains('open')) return;
if (e.target === passInput || e.target === briSlider || e.target === kbdInput) return;
const id = e.code || e.key;
if (pressedKeys.has(id)) {
e.preventDefault();
const sym = pressedKeys.get(id);
pressedKeys.delete(id);
sendJson({ t: 'key', k: sym, d: 0 });
}
});
window.addEventListener('blur', releaseAllKeys);
window.addEventListener('focus', noteClipboardBase);
document.addEventListener('visibilitychange', () => {
if (document.hidden) releaseAllKeys();
else noteClipboardBase();
});
/* ---- Paste: this device's clipboard (text or image) into the phone ----
The paste keys put the local clipboard on the phone's, then send the same keys there. The
clipboard comes from the browser's paste event, which needs no permission and works over
plain HTTP. Something copied on the phone since this page was focused is newer than the
local clipboard, and is pasted as it is. */
const PASTE_MAX = 16 * 1024 * 1024;
const IS_MAC = /Mac|iPhone|iPad/.test(navigator.platform || '');
let clipBase = null; /* phone clipboard serial when this page was last focused */
let clipLastSig = null; /* the local clipboard last sent, or passed over for the phone's */
let pasteChain = Promise.resolve();
let keyPaste = null; /* paste keys pressed, paste event not seen yet */
let keyPasteMissed = 0; /* when the last one was given up on */
let toastTimer = null;
function toast(msg, isErr) {
clearTimeout(toastTimer);
toastEl.textContent = msg;
toastEl.classList.toggle('err', !!isErr);
toastEl.classList.add('open');
toastTimer = setTimeout(() => toastEl.classList.remove('open'), isErr ? 5000 : 1800);
}
async function clipboardApi(method, type, body) {
const headers = { 'X-Chandra-Remote': '1' };
if (token) headers['Authorization'] = 'Bearer ' + token;
if (type) headers['Content-Type'] = type;
const ctl = new AbortController();
const timer = setTimeout(() => ctl.abort(), method === 'GET' ? 4000 : 45000);
try {
const r = await fetch('/api/clipboard', { method, headers, body, cache: 'no-store', signal: ctl.signal });
const d = await r.json();
if (!r.ok || !d.ok) throw new Error(d.error || ('HTTP ' + r.status));
return d.serial;
} finally {
clearTimeout(timer);
}
}
function noteClipboardBase() {
if (!ws || ws.readyState !== WebSocket.OPEN) return;
pasteChain = pasteChain.then(async () => {
try {
const s = await clipboardApi('GET');
if (clipBase !== null && s < clipBase) clipLastSig = null; /* the desktop restarted */
clipBase = s;
} catch (_) {}
});
}
/* {type, blob, text, sig} of some text or an image file; images become PNG. */
async function makePayload(text, image) {
let blob, type;
if (image) {
type = 'image/png';
blob = image;
if (image.type !== 'image/png') {
let bmp;
try {
bmp = await createImageBitmap(image);
} catch (_) {
throw new Error('This image format can\'t be read');
}
const cv = document.createElement('canvas');
cv.width = bmp.width;
cv.height = bmp.height;
cv.getContext('2d').drawImage(bmp, 0, 0);
bmp.close();
blob = await new Promise(res => cv.toBlob(res, 'image/png'));
if (!blob) throw new Error('This image is too big');
}
} else {
type = 'text/plain';
blob = new Blob([text.replace(/\r\n?/g, '\n')], { type });
}
if (blob.size > PASTE_MAX) throw new Error('Too large to paste (16 MB at most)');
const bytes = new Uint8Array(await blob.arrayBuffer());
let h = 0x811c9dc5;
for (let i = 0; i < bytes.length; i++) h = Math.imul(h ^ bytes[i], 0x01000193);
return { type, blob, text, sig: type + ':' + bytes.length + ':' + (h >>> 0) };
}
/* Send it to the phone's clipboard, unless (not `force`) the phone's own is the one to paste. */
async function syncClipboard(p, force) {
if (!force) {
if (p.sig === clipLastSig) return false;
if (clipBase !== null && await clipboardApi('GET') !== clipBase) {
clipLastSig = p.sig;
return false;
}
}
clipBase = await clipboardApi('POST', p.type, p.blob);
clipLastSig = p.sig;
if (p.type === 'image/png') {
const kb = p.blob.size / 1024;
toast('Image sent (' + (kb < 1024 ? Math.ceil(kb) + ' KB' : (kb / 1024).toFixed(1) + ' MB') + ')');
}
return true;
}
function holdTyping() { pastesInFlight++; }
function releaseTyping() {
if (--pastesInFlight > 0) return;
const queue = heldMessages;
heldMessages = [];
queue.forEach(sendNow);
}
/* Paste text or an image. `chord` is {c, m} (evdev code, modifiers), or null for whatever the
focused app uses. Typing must be held by the caller; it is released here. */
function runPaste(text, image, chord, force) {
pasteChain = pasteChain.then(async () => {
let p = null;
try {
if (text || image) {
p = await makePayload(text, image);
await syncClipboard(p, force);
}
sendNow(chord ? { t: 'paste', c: chord.c, m: chord.m } : { t: 'paste' });
} catch (err) {
/* Never paste what was on the phone's clipboard before in its place. */
toast('Paste failed: ' + (err.name === 'AbortError' ? 'timed out' : err.message), true);
} finally {
releaseTyping();
}
});
}
function pasteChord(e) {
if (e.altKey) return null;
const isV = e.key.toLowerCase() === 'v' || (e.code === 'KeyV' && e.key.charCodeAt(0) > 0x7F);
if (isV && (IS_MAC ? e.metaKey && !e.ctrlKey : e.ctrlKey && !e.metaKey)) {
return { c: 47, m: e.shiftKey ? 5 : 4 };
}
if (!IS_MAC && e.key === 'Insert' && e.shiftKey && !e.ctrlKey && !e.metaKey) return { c: 110, m: 1 };
return null;
}
/* A paste key press: let the browser do its paste, into the sink, and pick up the event. */
function beginKeyPaste(e) {
const chord = pasteChord(e);
if (!chord) return false;
if (e.repeat || keyPaste) {
e.preventDefault();
return true;
}
if (IS_MAC) {
/* Command is held on the phone as Super: let go of it, without it counting as a Super tap. */
for (const [id, sym] of [...pressedKeys]) {
if (sym === 0xFFEB || sym === 0xFFEC) {
pressedKeys.delete(id);
sendJson({ t: 'ktap', c: 29, m: 0 });
sendJson({ t: 'key', k: sym, d: 0 });
}
}
}
const back = document.activeElement === kbdInput ? kbdInput : null;
holdTyping();
pasteSink.textContent = '';
pasteSink.focus({ preventScroll: true });
keyPaste = {
chord, back,
timer: setTimeout(() => {
/* No paste event (nothing the browser can paste): the phone's own clipboard then. */
const k = endKeyPaste();
keyPasteMissed = performance.now();
runPaste('', null, k.chord, false);
}, 600)
};
return true;
}
function endKeyPaste() {
const k = keyPaste;
keyPaste = null;
clearTimeout(k.timer);
pasteSink.textContent = '';
if (k.back) k.back.focus();
else pasteSink.blur();
return k;
}
function pickFromTransfer(dt) {
let image = null;
for (const it of dt ? dt.items : []) {
if (it.kind === 'file' && it.type.startsWith('image/')) { image = it.getAsFile(); break; }
}
let text = dt ? dt.getData('text/plain') : '';
/* A copied image file also comes with its name or path as text. */
if (image && text && image.name && text.trim().endsWith(image.name) && !text.trim().includes('\n')) text = '';
return text ? [text, null] : ['', image];
}
document.addEventListener('paste', (e) => {
if (loginMask.classList.contains('open') || e.target === passInput) return;
e.preventDefault();
const [text, image] = pickFromTransfer(e.clipboardData);
if (keyPaste) {
const k = endKeyPaste();
runPaste(text, image, k.chord, false);
} else if (performance.now() - keyPasteMissed > 2000 && (text || image)) {
holdTyping();
runPaste(text, image, null, true); /* the browser's own Paste menu item */
}
});
/* For the buttons: [text, image] from the async clipboard API, or text asked for. */
async function readLocalClipboard(question) {
if (navigator.clipboard && navigator.clipboard.read) {
try {
const items = await navigator.clipboard.read();
for (const it of items) {
if (it.types.includes('text/plain')) {
const t = await (await it.getType('text/plain')).text();
if (t) return [t, null];
}
}
for (const it of items) {
const ty = it.types.find(x => x.startsWith('image/'));
if (ty) return ['', await it.getType(ty)];
}
} catch (_) {}
}
try {
const t = await navigator.clipboard.readText();
if (t) return [t, null];
} catch (_) {}
return [prompt(question) || '', null];
}
/* ---- Android Gboard sentinel-space keyboard bridge ---- */
function setKbOpen(open) {
kbOpen = open;
kbBtn.classList.toggle('active', open);
kbdBar.classList.toggle('open', open);
if (open) {
kbdInput.value = ' ';
kbdInput.focus();
kbdInput.setSelectionRange(1, 1);
} else {
kbdInput.blur();
stickyMods = 0;
document.querySelectorAll('.kmod').forEach(b => b.classList.remove('active'));
}
}
kbBtn.addEventListener('click', () => setKbOpen(!kbOpen));
document.getElementById('kbHideBtn').addEventListener('click', () => setKbOpen(false));
document.querySelectorAll('.kmod').forEach(btn => {
btn.addEventListener('click', () => {
const bit = Number(btn.dataset.bit);
stickyMods ^= bit;
btn.classList.toggle('active', (stickyMods & bit) !== 0);
kbdInput.focus();
});
});
document.querySelectorAll('.kspecial').forEach(btn => {
btn.addEventListener('click', () => {
const code = Number(btn.dataset.code);
sendJson({ t: 'ktap', c: code, m: stickyMods });
stickyMods = 0;
document.querySelectorAll('.kmod').forEach(b => b.classList.remove('active'));
kbdInput.focus();
});
});
function sendTextWithMods(txt) {
if (!txt) return;
if (stickyMods && txt.length === 1 && txt.charCodeAt(0) >= 0x20 && txt.charCodeAt(0) <= 0x7E) {
const m = stickyMods;
if (m & 4) sendJson({ t: 'key', k: 0xFFE3, d: 1 });
if (m & 8) sendJson({ t: 'key', k: 0xFFE9, d: 1 });
sendJson({ t: 'key', k: txt.charCodeAt(0), d: 1 });
sendJson({ t: 'key', k: txt.charCodeAt(0), d: 0 });
if (m & 8) sendJson({ t: 'key', k: 0xFFE9, d: 0 });
if (m & 4) sendJson({ t: 'key', k: 0xFFE3, d: 0 });
stickyMods = 0;
document.querySelectorAll('.kmod').forEach(b => b.classList.remove('active'));
return;
}
sendJson({ t: 'text', s: txt });
}
kbdInput.addEventListener('keydown', (e) => {
keyHandled = false;
if (beginKeyPaste(e)) return;
const map = {
Enter: 28, Backspace: 14, Tab: 15, Escape: 1, Delete: 111,
ArrowLeft: 105, ArrowUp: 103, ArrowRight: 106, ArrowDown: 108,
Home: 102, End: 107, PageUp: 104, PageDown: 109
};
if (e.key in map) {
e.preventDefault();
keyHandled = true;
let m = stickyMods;
if (e.shiftKey) m |= 1;
if (e.ctrlKey) m |= 4;
if (e.altKey) m |= 8;
sendJson({ t: 'ktap', c: map[e.key], m });
stickyMods = 0;
document.querySelectorAll('.kmod').forEach(b => b.classList.remove('active'));
kbdInput.value = ' ';
return;
}
if ((e.ctrlKey || e.altKey || e.metaKey) && e.key.length === 1) {
e.preventDefault();
keyHandled = true;
if (e.ctrlKey) sendJson({ t: 'key', k: 0xFFE3, d: 1 });
if (e.altKey) sendJson({ t: 'key', k: 0xFFE9, d: 1 });
if (e.metaKey) sendJson({ t: 'key', k: 0xFFEB, d: 1 });
sendJson({ t: 'key', k: e.key.charCodeAt(0), d: 1 });
sendJson({ t: 'key', k: e.key.charCodeAt(0), d: 0 });
if (e.metaKey) sendJson({ t: 'key', k: 0xFFEB, d: 0 });
if (e.altKey) sendJson({ t: 'key', k: 0xFFE9, d: 0 });
if (e.ctrlKey) sendJson({ t: 'key', k: 0xFFE3, d: 0 });
}
});
kbdInput.addEventListener('input', (e) => {
if (e.isComposing) return;
if (keyHandled) {
keyHandled = false;
kbdInput.value = ' ';
return;
}
const v = kbdInput.value;
if (e.inputType === 'deleteContentBackward' || v.length === 0) {
sendJson({ t: 'ktap', c: 14, m: 0 });
} else {
const added = v.startsWith(' ') ? v.slice(1) : v;
if (added) sendTextWithMods(added);
}
kbdInput.value = ' ';
kbdInput.setSelectionRange(1, 1);
});
kbdInput.addEventListener('compositionend', (e) => {
if (e.data) sendJson({ t: 'text', s: e.data });
kbdInput.value = ' ';
kbdInput.setSelectionRange(1, 1);
});
/* ---- UI controls ---- */
document.getElementById('pillWrap').addEventListener('click', (e) => {
const btn = e.target.closest('button');
if (btn && btn !== kbBtn) btn.blur();
});
menuBtn.addEventListener('click', () => drawer.classList.toggle('open'));
modeBtn.addEventListener('click', () => {
trackpadMode = !trackpadMode;
modeBtn.textContent = trackpadMode ? 'Pad' : 'Touch';
modeBtn.classList.toggle('active', trackpadMode);
layoutCursor();
});
document.querySelectorAll('[data-ctl]').forEach(btn => {
btn.addEventListener('click', () => {
sendJson({ t: 'ctl', cmd: btn.dataset.ctl });
});
});
briSlider.addEventListener('input', () => {
briVal.textContent = briSlider.value;
});
briSlider.addEventListener('change', () => {
sendJson({ t: 'ctl', cmd: 'brightness ' + briSlider.value });
});
document.querySelectorAll('.qbtn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.qbtn').forEach(x => x.classList.remove('active'));
btn.classList.add('active');
sendJson({ t: 'cfg', q: Number(btn.dataset.q), fps: Number(btn.dataset.fps) });
});
});
document.getElementById('clipBtn').addEventListener('click', async () => {
const [text, image] = await readLocalClipboard('Text to copy to phone clipboard:');
if (!text && !image) return;
try {
const p = await makePayload(text, image);
await syncClipboard(p, true);
if (!image) toast('Clipboard sent');
} catch (err) {
toast('Send failed: ' + err.message, true);
}
});
document.getElementById('imgBtn').addEventListener('click', () => imgInput.click());
imgInput.addEventListener('change', () => {
const f = imgInput.files[0];
imgInput.value = '';
if (!f) return;
drawer.classList.remove('open');
holdTyping();
runPaste('', f, null, true);
});
document.getElementById('pasteBtn').addEventListener('click', async () => {
const [text, image] = await readLocalClipboard('Text to paste on phone:');
if (text || image) {
holdTyping();
runPaste(text, image, null, true);
}
kbdInput.focus();
});
document.getElementById('fsBtn').addEventListener('click', () => {
if (!document.fullscreenElement) document.documentElement.requestFullscreen?.();
else document.exitFullscreen?.();
});
window.addEventListener('resize', layoutCursor);
bootstrap();
})();
</script>
</body>
</html>