- Web UI: Ctrl+C, Ctrl+X, Ctrl+Shift+C (Cmd+C on Mac) also put what they copied, text or PNG, on this device's clipboard; Copy, Copy Selection and Copy Clipboard buttons - chandra-remote: GET /api/clipboard/data, with the same authorization as the upload - Compositor: clipboard-get-fd has the clipboard's owner write into a pipe, refused while locked; input-copy presses Ctrl+Shift+C in terminals, Ctrl+C elsewhere - Pending clipboard transfers keep the main loop awake Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c5dbe028e6
commit
589d167f79
11 files changed
+552
-19
No files matched your search
@@ -271,6 +271,62 @@ int remote_clipboard_set(CtlConn *c, const char *mime, const void *data, size_t
|
||||
return parse_serial(reply, serial);
|
||||
}
|
||||
|
||||
int remote_clipboard_get(CtlConn *c, const char **mime, uint8_t **data, size_t *len,
|
||||
unsigned long *serial) {
|
||||
*data = NULL;
|
||||
*len = 0;
|
||||
int p[2];
|
||||
if (pipe2(p, O_CLOEXEC) != 0) return REMOTE_CLIP_FAILED;
|
||||
fcntl(p[1], F_SETPIPE_SZ, 1 << 20); /* an image in fewer turns; the default works too */
|
||||
char reply[160] = {0}, type[64] = {0};
|
||||
int r = ctl_cmd_fd(c, "clipboard-get-fd", p[1], reply, sizeof reply);
|
||||
close(p[1]);
|
||||
int res = REMOTE_CLIP_FAILED;
|
||||
if (r != 0) {
|
||||
if (strcmp(reply, "error empty") == 0) res = REMOTE_CLIP_EMPTY;
|
||||
else if (strcmp(reply, "error locked") == 0) res = REMOTE_CLIP_LOCKED;
|
||||
else if (strstr(reply, "unknown command")) res = REMOTE_CLIP_OLD;
|
||||
goto out;
|
||||
}
|
||||
if (sscanf(reply, "ok serial=%lu type=%63s", serial, type) != 2) goto out;
|
||||
if (strcmp(type, "text/plain") == 0) *mime = "text/plain; charset=utf-8";
|
||||
else if (strcmp(type, "image/png") == 0) *mime = "image/png";
|
||||
else goto out;
|
||||
/* The app that owns the clipboard writes it, and may be slow, stuck or endless. */
|
||||
size_t cap = 0;
|
||||
uint64_t deadline = remote_now_ms() + 10000;
|
||||
for (;;) {
|
||||
if (*len == cap) {
|
||||
size_t ncap = cap ? cap * 2 : 65536;
|
||||
if (ncap > REMOTE_CLIPBOARD_MAX + 1) ncap = REMOTE_CLIPBOARD_MAX + 1;
|
||||
uint8_t *nd = realloc(*data, ncap);
|
||||
if (!nd) goto out;
|
||||
*data = nd;
|
||||
cap = ncap;
|
||||
}
|
||||
uint64_t now = remote_now_ms();
|
||||
struct pollfd pfd = { .fd = p[0], .events = POLLIN };
|
||||
int pr = now >= deadline ? 0 : poll(&pfd, 1, (int)(deadline - now));
|
||||
if (pr < 0 && errno == EINTR) continue;
|
||||
if (pr <= 0) goto out;
|
||||
ssize_t n = read(p[0], *data + *len, cap - *len);
|
||||
if (n < 0 && errno == EINTR) continue;
|
||||
if (n < 0) goto out;
|
||||
if (n == 0) break;
|
||||
*len += (size_t)n;
|
||||
if (*len > REMOTE_CLIPBOARD_MAX) { res = REMOTE_CLIP_TOO_LARGE; goto out; }
|
||||
}
|
||||
res = *len > 0 ? REMOTE_CLIP_OK : REMOTE_CLIP_EMPTY;
|
||||
out:
|
||||
close(p[0]);
|
||||
if (res != REMOTE_CLIP_OK) {
|
||||
free(*data);
|
||||
*data = NULL;
|
||||
*len = 0;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
void remote_osk_suppress_acquire(RemoteApp *app, int *client_flag) {
|
||||
if (*client_flag) return;
|
||||
pthread_mutex_lock(&app->osk_mu);
|
||||
|
||||
@@ -84,6 +84,13 @@ int ctl_fire(CtlConn *c, const char *line);
|
||||
clipboard serial goes to `serial` (may be NULL). 0, or -1 when the compositor refused. */
|
||||
int remote_clipboard_set(CtlConn *c, const char *mime, const void *data, size_t len,
|
||||
unsigned long *serial);
|
||||
enum {
|
||||
REMOTE_CLIP_OK, REMOTE_CLIP_FAILED, REMOTE_CLIP_EMPTY, REMOTE_CLIP_LOCKED, REMOTE_CLIP_OLD,
|
||||
REMOTE_CLIP_TOO_LARGE
|
||||
};
|
||||
/* The phone's clipboard: its Content-Type (static), bytes (the caller frees) and serial. */
|
||||
int remote_clipboard_get(CtlConn *c, const char **mime, uint8_t **data, size_t *len,
|
||||
unsigned long *serial);
|
||||
/* Current clipboard serial: it changes whenever something is put on the clipboard. */
|
||||
int remote_clipboard_serial(CtlConn *c, unsigned long *serial);
|
||||
void remote_osk_suppress_acquire(RemoteApp *app, int *client_flag);
|
||||
|
||||
@@ -201,6 +201,7 @@ class MockCtlServer:
|
||||
self.brightness = 75
|
||||
self.osk = 1
|
||||
self.clip_serial = 0
|
||||
self.clip_get = None # (mime, bytes) clipboard-get-fd writes, or its error
|
||||
self.clips = [] # (mime, bytes) put on the clipboard
|
||||
self.th = threading.Thread(target=self._serve, daemon=True)
|
||||
self.th.start()
|
||||
@@ -258,6 +259,25 @@ class MockCtlServer:
|
||||
os.close(fd)
|
||||
self.clip_serial += 1
|
||||
rep = f"ok serial={self.clip_serial}\n"
|
||||
elif cmd == "clipboard-get-fd":
|
||||
fd = files.pop(0)
|
||||
if self.clip_get is None:
|
||||
rep = "error empty\n"
|
||||
elif isinstance(self.clip_get, str):
|
||||
rep = self.clip_get + "\n"
|
||||
else:
|
||||
mime, data = self.clip_get
|
||||
rep = f"ok serial={self.clip_serial} type={mime}\n"
|
||||
|
||||
def write(out=os.dup(fd), data=data):
|
||||
try:
|
||||
with os.fdopen(out, "wb") as f:
|
||||
f.write(data)
|
||||
except BrokenPipeError:
|
||||
pass
|
||||
|
||||
threading.Thread(target=write, daemon=True).start()
|
||||
os.close(fd)
|
||||
elif cmd == "osk toggle":
|
||||
self.osk = 0 if self.osk else 1
|
||||
rep = f"ok {'on' if self.osk else 'off'}\n"
|
||||
@@ -832,6 +852,58 @@ class RemoteTests(unittest.TestCase):
|
||||
self.assertEqual(self.clip_request("POST", b"y", {**hdr, "Cookie": "chandra_remote=" + tok})[0], 200)
|
||||
self.assertEqual(self.ctl.clips, [("text/plain", b"x"), ("text/plain", b"y")])
|
||||
|
||||
def clip_data(self, headers):
|
||||
c = http.client.HTTPConnection("127.0.0.1", self.web_port, timeout=15)
|
||||
c.request("GET", "/api/clipboard/data", headers=headers)
|
||||
r = c.getresponse()
|
||||
out = r.status, r.getheader("Content-Type"), r.read(), r.getheader("X-Clipboard-Serial")
|
||||
c.close()
|
||||
return out
|
||||
|
||||
def test_10_copy_from_the_desktop(self):
|
||||
self.shm.write_frame(64, 48, lambda x, y: (1, 2, 3))
|
||||
self.start_daemon(auth="none")
|
||||
own = {"X-Chandra-Remote": "1"}
|
||||
self.ctl.clip_serial = 7
|
||||
self.assertEqual(self.clip_data(own)[0], 404) # nothing there
|
||||
text = "líne 1\nline 2 \"q\"\n".encode() * 20000
|
||||
self.ctl.clip_get = ("text/plain", text)
|
||||
self.assertEqual(self.clip_data(own), (200, "text/plain; charset=utf-8", text, "7"))
|
||||
png = b"\x89PNG\r\n\x1a\n" + os.urandom(3 * 1024 * 1024)
|
||||
self.ctl.clip_get = ("image/png", png)
|
||||
self.assertEqual(self.clip_data(own), (200, "image/png", png, "7"))
|
||||
# Refused: no own-page header, too large, locked, a compositor from before.
|
||||
self.assertEqual(self.clip_data({})[0], 403)
|
||||
self.ctl.clip_get = ("image/png", bytes(16 * 1024 * 1024 + 1))
|
||||
self.assertEqual(self.clip_data(own)[0], 502)
|
||||
self.ctl.clip_get = "error locked"
|
||||
self.assertEqual(self.clip_data(own)[0], 403)
|
||||
self.ctl.clip_get = "error unknown command 'clipboard-get-fd' (try: help)"
|
||||
st, _, body, _ = self.clip_data(own)
|
||||
self.assertEqual(st, 502)
|
||||
self.assertIn("restart", json.loads(body)["error"])
|
||||
|
||||
ws, status_line, _, extra = ws_connect("127.0.0.1", self.web_port)
|
||||
self.assertIn("101", status_line)
|
||||
buf = bytearray(extra)
|
||||
ws_send_text(ws, json.dumps({"t": "clipmark", "id": 3}))
|
||||
ws_send_text(ws, json.dumps({"t": "copy"}))
|
||||
while True:
|
||||
op, payload = ws_read_frame(ws, buf)
|
||||
if op == 1 and json.loads(payload)["t"] == "clipmark":
|
||||
break
|
||||
self.assertEqual(json.loads(payload), {"t": "clipmark", "id": 3, "serial": 7})
|
||||
deadline = time.time() + 3.0
|
||||
while time.time() < deadline and "input-copy" not in self.ctl.commands:
|
||||
time.sleep(0.02)
|
||||
self.assertIn("input-copy", self.ctl.commands)
|
||||
ws.close()
|
||||
|
||||
def test_11_copy_needs_login(self):
|
||||
self.start_daemon(auth="password", password="TestPass99")
|
||||
self.ctl.clip_get = ("text/plain", b"secret")
|
||||
self.assertEqual(self.clip_data({"X-Chandra-Remote": "1"})[0], 401)
|
||||
|
||||
def test_09_sigusr2_restarts_in_place(self):
|
||||
self.start_daemon(auth="none")
|
||||
ws, status_line, _, _ = ws_connect("127.0.0.1", self.web_port)
|
||||
|
||||
@@ -512,6 +512,22 @@ static void ws_handle_text(WsState *ws, const char *msg) {
|
||||
free(txt);
|
||||
return;
|
||||
}
|
||||
if (strcmp(type, "clipmark") == 0) { /* the clipboard serial, before keys that may copy something */
|
||||
unsigned long serial = 0;
|
||||
char js[64];
|
||||
long id = 0;
|
||||
json_get_int(msg, "id", &id);
|
||||
if (remote_clipboard_serial(&ws->app->ctl, &serial) == 0) {
|
||||
snprintf(js, sizeof js, "{\"t\":\"clipmark\",\"id\":%ld,\"serial\":%lu}", id, serial);
|
||||
ws_send_text(ws->fd, js);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (strcmp(type, "copy") == 0) { /* press the focused app's copy keys */
|
||||
ws_note_key_activity(ws);
|
||||
ctl_fire(&ws->app->ctl, "input-copy");
|
||||
return;
|
||||
}
|
||||
if (strcmp(type, "paste") == 0) { /* paste the phone's clipboard, by the given chord or the app's usual one */
|
||||
long code = 0, mods = 0;
|
||||
char cmd[64] = "input-paste";
|
||||
@@ -621,6 +637,45 @@ fail:
|
||||
http_send(fd, status, "application/json", NULL, js, strlen(js));
|
||||
}
|
||||
|
||||
/* GET /api/clipboard/data: what is on the phone's clipboard, text or a PNG image, with its serial
|
||||
in X-Clipboard-Serial. */
|
||||
static void web_clipboard_data(RemoteApp *app, int fd, const char *hdrs) {
|
||||
char val[16] = {0}, out[160];
|
||||
const char *status = "502 Bad Gateway", *err = "The desktop did not give its clipboard", *mime = NULL;
|
||||
uint8_t *data = NULL;
|
||||
size_t len = 0;
|
||||
unsigned long serial = 0;
|
||||
/* As in web_clipboard: only the page itself can set this. */
|
||||
if (!find_header(hdrs, "X-Chandra-Remote", val, sizeof val)) {
|
||||
status = "403 Forbidden";
|
||||
err = "Forbidden";
|
||||
} else {
|
||||
switch (remote_clipboard_get(&app->ctl, &mime, &data, &len, &serial)) {
|
||||
case REMOTE_CLIP_OK:
|
||||
snprintf(out, sizeof out, "X-Clipboard-Serial: %lu\r\nX-Content-Type-Options: nosniff\r\n", serial);
|
||||
http_send(fd, "200 OK", mime, out, data, len);
|
||||
free(data);
|
||||
return;
|
||||
case REMOTE_CLIP_EMPTY:
|
||||
status = "404 Not Found";
|
||||
err = "No text or image on the phone's clipboard";
|
||||
break;
|
||||
case REMOTE_CLIP_LOCKED:
|
||||
status = "403 Forbidden";
|
||||
err = "The phone is locked";
|
||||
break;
|
||||
case REMOTE_CLIP_OLD:
|
||||
err = "The phone's session needs a restart for this (updated since)";
|
||||
break;
|
||||
case REMOTE_CLIP_TOO_LARGE:
|
||||
err = "Too large (16 MB at most)";
|
||||
break;
|
||||
}
|
||||
}
|
||||
snprintf(out, sizeof out, "{\"ok\":false,\"error\":\"%s\"}", err);
|
||||
http_send(fd, status, "application/json", NULL, out, strlen(out));
|
||||
}
|
||||
|
||||
static void ws_loop(RemoteApp *app, int fd) {
|
||||
WsState ws;
|
||||
memset(&ws, 0, sizeof ws);
|
||||
@@ -924,6 +979,16 @@ void web_handle_client(RemoteApp *app, int fd) {
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
if (strcmp(path, "/api/clipboard/data") == 0 && !strcmp(method, "GET")) {
|
||||
if (!web_authorized(app, &cfg, target, buf)) {
|
||||
const char *m = "{\"ok\":false,\"error\":\"Unauthorized\"}";
|
||||
http_send(fd, "401 Unauthorized", "application/json", NULL, m, strlen(m));
|
||||
} else {
|
||||
web_clipboard_data(app, fd, buf);
|
||||
}
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
if (strcmp(method, "GET") == 0 && strcmp(path, "/ws") == 0) {
|
||||
if (!web_authorized(app, &cfg, target, buf)) {
|
||||
const char *m = "Unauthorized";
|
||||
|
||||
+183
-19
@@ -87,7 +87,7 @@
|
||||
position: fixed; left: -9999px; top: 0; width: 1px; height: 1px;
|
||||
opacity: 0; border: 0; padding: 0; font-size: 16px;
|
||||
}
|
||||
#pasteSink {
|
||||
#pasteSink, #copySource {
|
||||
position: fixed; left: -9999px; top: 0; width: 1px; height: 1px;
|
||||
overflow: hidden; opacity: 0; outline: 0;
|
||||
user-select: text; -webkit-user-select: text;
|
||||
@@ -100,6 +100,7 @@
|
||||
font-size: 13px; pointer-events: none;
|
||||
}
|
||||
#toast.open { display: block; }
|
||||
#toast.tap { pointer-events: auto; cursor: pointer; border-color: var(--accent); }
|
||||
#toast.err { border-color: var(--err); }
|
||||
#loginMask {
|
||||
position: fixed; inset: 0; z-index: 50; display: none;
|
||||
@@ -155,7 +156,9 @@
|
||||
<button class="btn" data-ctl="shortcut overview">Overview</button>
|
||||
</div>
|
||||
<div class="row">
|
||||
<button id="clipBtn" class="btn">Send Clipboard</button>
|
||||
<button class="btn copyBtn" title="Copy what is selected on the phone to this device">Copy Selection</button>
|
||||
<button id="getClipBtn" class="btn" title="Copy the phone's clipboard to this device">Copy Clipboard</button>
|
||||
<button id="clipBtn" class="btn" title="Put this device's clipboard on the phone's">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>
|
||||
@@ -180,11 +183,13 @@
|
||||
<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 class="btn copyBtn">Copy</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>
|
||||
<textarea id="copySource" readonly inputmode="none" tabindex="-1" aria-hidden="true"></textarea>
|
||||
<input id="imgInput" type="file" accept="image/*" hidden>
|
||||
<div id="toast" role="status"></div>
|
||||
|
||||
@@ -236,7 +241,7 @@
|
||||
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']);
|
||||
const HELD_WHILE_PASTING = new Set(['key', 'ktap', 'text', 'release', 'clipmark', 'copy']);
|
||||
let pastesInFlight = 0;
|
||||
let heldMessages = [];
|
||||
|
||||
@@ -317,6 +322,7 @@
|
||||
function handleText(str) {
|
||||
try {
|
||||
const m = JSON.parse(str);
|
||||
if (m.t === 'clipmark') followCopy(m.id, m.serial);
|
||||
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');
|
||||
@@ -618,6 +624,7 @@
|
||||
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;
|
||||
if (beginKeyCopy(e)) return;
|
||||
const sym = eventToKeysym(e);
|
||||
if (sym !== null) {
|
||||
e.preventDefault();
|
||||
@@ -665,17 +672,24 @@
|
||||
let keyPasteMissed = 0; /* when the last one was given up on */
|
||||
let toastTimer = null;
|
||||
|
||||
function toast(msg, isErr) {
|
||||
function toast(msg, isErr, onTap) {
|
||||
clearTimeout(toastTimer);
|
||||
toastEl.onclick = onTap || null;
|
||||
toastEl.classList.toggle('tap', !!onTap);
|
||||
toastEl.textContent = msg;
|
||||
toastEl.classList.toggle('err', !!isErr);
|
||||
toastEl.classList.add('open');
|
||||
toastTimer = setTimeout(() => toastEl.classList.remove('open'), isErr ? 5000 : 1800);
|
||||
toastTimer = setTimeout(() => toastEl.classList.remove('open'), onTap ? 15000 : isErr ? 5000 : 1800);
|
||||
}
|
||||
|
||||
function apiHeaders() {
|
||||
const headers = { 'X-Chandra-Remote': '1' };
|
||||
if (token) headers['Authorization'] = 'Bearer ' + token;
|
||||
return headers;
|
||||
}
|
||||
|
||||
async function clipboardApi(method, type, body) {
|
||||
const headers = { 'X-Chandra-Remote': '1' };
|
||||
if (token) headers['Authorization'] = 'Bearer ' + token;
|
||||
const headers = apiHeaders();
|
||||
if (type) headers['Content-Type'] = type;
|
||||
const ctl = new AbortController();
|
||||
const timer = setTimeout(() => ctl.abort(), method === 'GET' ? 4000 : 45000);
|
||||
@@ -733,8 +747,10 @@
|
||||
}
|
||||
|
||||
/* Send it to the phone's clipboard, unless (not `force`) the phone's own is the one to paste. */
|
||||
async function syncClipboard(p, force) {
|
||||
async function syncClipboard(p, force, gen) {
|
||||
if (!force) {
|
||||
/* Copied from the phone since the paste keys were pressed: `p` is what was there before. */
|
||||
if (gen !== copyGen) return false;
|
||||
if (p.sig === clipLastSig) return false;
|
||||
if (clipBase !== null && await clipboardApi('GET') !== clipBase) {
|
||||
clipLastSig = p.sig;
|
||||
@@ -761,12 +777,13 @@
|
||||
/* 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) {
|
||||
const gen = copyGen;
|
||||
pasteChain = pasteChain.then(async () => {
|
||||
let p = null;
|
||||
try {
|
||||
if (text || image) {
|
||||
p = await makePayload(text, image);
|
||||
await syncClipboard(p, force);
|
||||
await syncClipboard(p, force, gen);
|
||||
}
|
||||
sendNow(chord ? { t: 'paste', c: chord.c, m: chord.m } : { t: 'paste' });
|
||||
} catch (err) {
|
||||
@@ -788,6 +805,17 @@
|
||||
return null;
|
||||
}
|
||||
|
||||
/* Command is held on the phone as Super: let go of it, without it counting as a Super tap. */
|
||||
function releaseCommand() {
|
||||
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 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 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);
|
||||
@@ -796,16 +824,7 @@
|
||||
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 });
|
||||
}
|
||||
}
|
||||
}
|
||||
if (IS_MAC) releaseCommand();
|
||||
const back = document.activeElement === kbdInput ? kbdInput : null;
|
||||
holdTyping();
|
||||
pasteSink.textContent = '';
|
||||
@@ -880,6 +899,133 @@
|
||||
return [prompt(question) || '', null];
|
||||
}
|
||||
|
||||
/* ---- Copy: the phone's clipboard (text or image) onto this device's ----
|
||||
The copy keys go to the phone as ever, after a message that answers with its clipboard's
|
||||
serial. When that changes, the app there copied something, and it is put on this device's
|
||||
clipboard too. Ctrl+C that copies nothing (an interrupt in a terminal) changes nothing. */
|
||||
const copySource = document.getElementById('copySource');
|
||||
let copySeq = 0; /* the latest copy; earlier ones give up */
|
||||
let copyAsked = false; /* it was a button, so say when there was nothing to copy */
|
||||
let copyGen = 0; /* counts what was put on this device's clipboard */
|
||||
|
||||
function startCopy(asked) {
|
||||
copyAsked = asked;
|
||||
sendJson({ t: 'clipmark', id: ++copySeq });
|
||||
}
|
||||
|
||||
async function followCopy(id, serial) {
|
||||
const asked = copyAsked;
|
||||
try {
|
||||
for (const wait of [40, 60, 100, 150, 250, 400, 500]) {
|
||||
await new Promise(res => setTimeout(res, wait));
|
||||
if (id !== copySeq) return;
|
||||
if (await clipboardApi('GET') !== serial) {
|
||||
if (id === copySeq) await takeClipboard(id, asked);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (asked && id === copySeq) toast('Nothing was copied on the phone', true);
|
||||
} catch (err) {
|
||||
copyFailed(err);
|
||||
}
|
||||
}
|
||||
|
||||
function copyFailed(err) {
|
||||
toast('Copy failed: ' + (err.name === 'AbortError' ? 'timed out' : err.message), true);
|
||||
}
|
||||
|
||||
/* Put the phone's clipboard on this device's. */
|
||||
async function takeClipboard(id, asked) {
|
||||
const ctl = new AbortController();
|
||||
const timer = setTimeout(() => ctl.abort(), 45000);
|
||||
let text = '', image = null, serial;
|
||||
try {
|
||||
const r = await fetch('/api/clipboard/data', { headers: apiHeaders(), cache: 'no-store', signal: ctl.signal });
|
||||
if (r.status === 404 && !asked) return; /* something else was copied, such as files */
|
||||
if (!r.ok) throw new Error((await r.json()).error || ('HTTP ' + r.status));
|
||||
serial = Number(r.headers.get('X-Clipboard-Serial'));
|
||||
if ((r.headers.get('Content-Type') || '').startsWith('image/')) image = await r.blob();
|
||||
else text = await r.text();
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
if (id !== copySeq) return;
|
||||
const p = await makePayload(text, image);
|
||||
const done = () => {
|
||||
copyGen++;
|
||||
clipBase = serial;
|
||||
clipLastSig = p.sig;
|
||||
toast(image ? 'Image copied to this device' : 'Copied to this device');
|
||||
};
|
||||
try {
|
||||
await writeLocalClipboard(text, image);
|
||||
} catch (err) {
|
||||
if (image && !canWriteImages()) throw new Error('images need the HTTPS address');
|
||||
/* The browser wants a fresh tap for it. */
|
||||
toast('Tap to copy to this device', false, async () => {
|
||||
try {
|
||||
await writeLocalClipboard(text, image);
|
||||
done();
|
||||
} catch (e) {
|
||||
copyFailed(e);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
done();
|
||||
}
|
||||
|
||||
function canWriteImages() {
|
||||
return !!(navigator.clipboard && navigator.clipboard.write && window.ClipboardItem);
|
||||
}
|
||||
|
||||
async function writeLocalClipboard(text, image) {
|
||||
if (image) {
|
||||
await navigator.clipboard.write([new ClipboardItem({ 'image/png': image })]);
|
||||
return;
|
||||
}
|
||||
if (navigator.clipboard && navigator.clipboard.writeText) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
return;
|
||||
} catch (_) {}
|
||||
}
|
||||
/* Plain HTTP. */
|
||||
const back = document.activeElement;
|
||||
copySource.value = text;
|
||||
copySource.focus({ preventScroll: true });
|
||||
copySource.select();
|
||||
let ok = false;
|
||||
try { ok = document.execCommand('copy'); } catch (_) {}
|
||||
copySource.value = '';
|
||||
copySource.blur();
|
||||
if (back && back !== document.body) back.focus({ preventScroll: true });
|
||||
if (!ok) throw new Error('the browser refused');
|
||||
}
|
||||
|
||||
/* Copy or cut keys; on a Mac with Command, as the Ctrl keys (evdev code, modifiers) to press. */
|
||||
function copyChord(e) {
|
||||
if (e.altKey) return null;
|
||||
const key = (k, code) => e.key.toLowerCase() === k || (e.code === code && e.key.charCodeAt(0) > 0x7F);
|
||||
const c = key('c', 'KeyC'), x = key('x', 'KeyX') && !e.shiftKey;
|
||||
if (IS_MAC && e.metaKey && !e.ctrlKey && (c || x)) return { c: c ? 46 : 45, m: e.shiftKey ? 5 : 4 };
|
||||
if (e.ctrlKey && !e.metaKey && (c || x || (e.key === 'Insert' && !e.shiftKey))) return {};
|
||||
return null;
|
||||
}
|
||||
|
||||
/* Watch for what the copy keys copy. True when the keys were sent here. */
|
||||
function beginKeyCopy(e) {
|
||||
const chord = copyChord(e);
|
||||
if (!chord) return false;
|
||||
if (chord.c) releaseCommand();
|
||||
if (!e.repeat) {
|
||||
startCopy(false);
|
||||
if (chord.c) sendJson({ t: 'ktap', c: chord.c, m: chord.m });
|
||||
}
|
||||
if (chord.c) e.preventDefault();
|
||||
return !!chord.c;
|
||||
}
|
||||
|
||||
/* ---- Android Gboard sentinel-space keyboard bridge ---- */
|
||||
function setKbOpen(open) {
|
||||
kbOpen = open;
|
||||
@@ -922,6 +1068,7 @@
|
||||
if (!txt) return;
|
||||
if (stickyMods && txt.length === 1 && txt.charCodeAt(0) >= 0x20 && txt.charCodeAt(0) <= 0x7E) {
|
||||
const m = stickyMods;
|
||||
if ((m & 4) && /[cx]/i.test(txt)) startCopy(false);
|
||||
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 });
|
||||
@@ -938,6 +1085,7 @@
|
||||
kbdInput.addEventListener('keydown', (e) => {
|
||||
keyHandled = false;
|
||||
if (beginKeyPaste(e)) return;
|
||||
if (beginKeyCopy(e)) return;
|
||||
const map = {
|
||||
Enter: 28, Backspace: 14, Tab: 15, Escape: 1, Delete: 111,
|
||||
ArrowLeft: 105, ArrowUp: 103, ArrowRight: 106, ArrowDown: 108,
|
||||
@@ -1040,6 +1188,22 @@
|
||||
}
|
||||
});
|
||||
|
||||
document.querySelectorAll('.copyBtn').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
startCopy(true);
|
||||
sendJson({ t: 'copy' });
|
||||
if (kbOpen) kbdInput.focus();
|
||||
});
|
||||
});
|
||||
|
||||
document.getElementById('getClipBtn').addEventListener('click', async () => {
|
||||
try {
|
||||
await takeClipboard(++copySeq, true);
|
||||
} catch (err) {
|
||||
copyFailed(err);
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('imgBtn').addEventListener('click', () => imgInput.click());
|
||||
imgInput.addEventListener('change', () => {
|
||||
const f = imgInput.files[0];
|
||||
|
||||
Reference in new issue
Block a user