Merge pull request 'Remote: copy from the phone to this device's clipboard' (#4) from gpu-rendering into main
This commit was merged in pull request #4.
This commit is contained in:
commit
3c7e6800f3
11 files changed
+552
-19
No files matched your search
@@ -1113,6 +1113,7 @@ pub fn ChandraCompositor::has_timed_work(self : ChandraCompositor) -> Bool {
|
||||
self.shot_toast is Some(_) ||
|
||||
self.auth_animating() ||
|
||||
self.thumbs_pending() ||
|
||||
self.server.pending_transfers() > 0 ||
|
||||
self.overview_animating() ||
|
||||
self.shell.animating() ||
|
||||
self.shell.face_busy() ||
|
||||
@@ -2252,6 +2253,16 @@ pub fn ChandraCompositor::remote_paste(
|
||||
false
|
||||
}
|
||||
|
||||
///| Press the focused window's copy keys: Ctrl+C, or Ctrl+Shift+C in terminals, where Ctrl+C
|
||||
/// interrupts. False where there is nothing to copy from: a dialog or popup of the shell's own.
|
||||
pub fn ChandraCompositor::remote_copy(self : ChandraCompositor) -> Bool {
|
||||
if self.locked || self.auth is Some(_) || self.shell.popup_open() || self.kbd_win is None {
|
||||
return false
|
||||
}
|
||||
self.remote_key_tap(46U, if self.terminal_focused() { 5U } else { 4U }, @sys.monotonic_ms().to_uint())
|
||||
true
|
||||
}
|
||||
|
||||
///| Whether the window with keyboard focus looks like a terminal, by its app id.
|
||||
fn ChandraCompositor::terminal_focused(self : ChandraCompositor) -> Bool {
|
||||
match self.kbd_win {
|
||||
|
||||
@@ -191,6 +191,9 @@ fn ChandraCompositor::control_tick(self : ChandraCompositor) -> Unit {
|
||||
let line = @utf8.decode_lossy(Bytes::from_array(cl.pending))
|
||||
cl.pending.clear()
|
||||
let (out, _) = self.control_command(line, file=cl.file)
|
||||
if cl.file >= 0 && self.server.is_transfer(cl.file) {
|
||||
cl.file = -1 // the clipboard is still being written into it
|
||||
}
|
||||
cl.drop_file()
|
||||
let reply = StringBuilder::new()
|
||||
for l in out {
|
||||
@@ -908,6 +911,30 @@ pub fn ChandraCompositor::control_command(
|
||||
}
|
||||
"clipboard-status" =>
|
||||
(["ok serial=" + self.server.selection_serial.to_string()], true)
|
||||
// chandra-remote: write the clipboard into `file`, a pipe, and say what it is.
|
||||
"clipboard-get-fd" => {
|
||||
if words.length() != 1 || file < 0 {
|
||||
return (["error usage: clipboard-get-fd, with a pipe sent along"], false)
|
||||
}
|
||||
if self.locked {
|
||||
return (["error locked"], false)
|
||||
}
|
||||
match self.server.send_clipboard_to(file) {
|
||||
Some(mime) =>
|
||||
(["ok serial=" + self.server.selection_serial.to_string() + " type=" + mime], true)
|
||||
None => (["error empty"], false)
|
||||
}
|
||||
}
|
||||
"input-copy" => {
|
||||
if words.length() != 1 {
|
||||
return (["error usage: input-copy"], false)
|
||||
}
|
||||
if self.remote_copy() {
|
||||
(["ok keys"], true)
|
||||
} else {
|
||||
(["ok nothing"], true)
|
||||
}
|
||||
}
|
||||
"input-paste" => {
|
||||
let chord = if words.length() == 3 {
|
||||
match (parse_uint_opt(words[1]), parse_uint_opt(words[2])) {
|
||||
|
||||
@@ -322,3 +322,78 @@ test "a paste still being written keeps its data when the clipboard changes" {
|
||||
@sys.unlink(sink_path)
|
||||
comp.close()
|
||||
}
|
||||
|
||||
///|
|
||||
test "the clipboard written into a pipe sent along: the compositor's own, a client's, none, locked" {
|
||||
let (comp, path) = control_comp("clipget")
|
||||
let fd = @sys.memfd_create("out", 0)
|
||||
assert_eq(ask_with_file(comp, path, "clipboard-get-fd", fd), "error empty")
|
||||
assert_true(ask(comp, path, "clipboard-get-fd")[0].has_prefix("error usage"))
|
||||
// The compositor's own: more than fits at once, so it is written over several turns.
|
||||
let sink_path = path + ".sink"
|
||||
let listener = @sys.unix_listen(sink_path)
|
||||
let reader = @sys.unix_connect(sink_path)
|
||||
let writer = @sys.unix_accept(listener)
|
||||
let data = Bytes::makei(3000000, i => (i * 7 % 251).to_byte())
|
||||
comp.server.set_own_selection(["image/png"], data)
|
||||
assert_eq(ask_with_file(comp, path, "clipboard-get-fd", writer), "ok serial=1 type=image/png")
|
||||
@sys.close_fd(writer)
|
||||
assert_true(comp.has_timed_work())
|
||||
let buf : FixedArray[Byte] = FixedArray::make(65536, b'\x00')
|
||||
let mut got = 0
|
||||
let mut same = true
|
||||
let mut eof = false
|
||||
for _i = 0; _i < 2000 && !eof; _i = _i + 1 {
|
||||
comp.step()
|
||||
if @sys.poll_read(reader, 5) > 0 {
|
||||
let (n, _) = @sys.recvmsg_fd(reader, buf, 65536)
|
||||
if n == 0 {
|
||||
eof = true
|
||||
}
|
||||
for j = 0; j < n; j = j + 1 {
|
||||
same = same && buf[j] == data[got + j]
|
||||
}
|
||||
if n > 0 {
|
||||
got = got + n
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_true(eof) // the compositor closed its end
|
||||
assert_true(same)
|
||||
assert_eq(got, data.length())
|
||||
@sys.close_fd(reader)
|
||||
@sys.close_fd(listener)
|
||||
@sys.unlink(sink_path)
|
||||
// A client's: it is asked to write, as text when there is any.
|
||||
let (a, _, _, _, _, _) = open_and_configure_client(comp, comp.server.socket_path, "A", "foot")
|
||||
let (mgr, dev) = data_device_for(a)
|
||||
let src = a.alloc_id()
|
||||
let w1 = @wayland.WireWriter::new()
|
||||
w1.u32(src)
|
||||
a.send(w1.finish_msg(mgr, 0U))
|
||||
for m in ["image/png", "UTF8_STRING"] {
|
||||
let w = @wayland.WireWriter::new()
|
||||
w.str(m)
|
||||
a.send(w.finish_msg(src, 0U))
|
||||
}
|
||||
let w2 = @wayland.WireWriter::new()
|
||||
w2.u32(src)
|
||||
w2.u32(1U)
|
||||
a.send(w2.finish_msg(dev, 1U))
|
||||
for _i = 0; _i < 5; _i = _i + 1 {
|
||||
comp.step()
|
||||
@sys.sleep_ms(2)
|
||||
}
|
||||
ignore(drain_args(a))
|
||||
assert_eq(ask_with_file(comp, path, "clipboard-get-fd", fd), "ok serial=2 type=text/plain")
|
||||
assert_true(has_msg(drain_args(a).map(m => (m.0, m.1)), src, 1U)) // send(mime, fd)
|
||||
// Copy keys: to the focused window, never into the shell's own popups.
|
||||
assert_eq(ask(comp, path, "input-copy"), ["ok keys"])
|
||||
assert_eq(ask(comp, path, "shortcut launcher"), ["ok launcher"])
|
||||
assert_eq(ask(comp, path, "input-copy"), ["ok nothing"])
|
||||
assert_eq(ask(comp, path, "shortcut launcher"), ["ok launcher"])
|
||||
comp.locked = true
|
||||
assert_eq(ask_with_file(comp, path, "clipboard-get-fd", fd), "error locked")
|
||||
@sys.close_fd(fd)
|
||||
comp.close()
|
||||
}
|
||||
@@ -2638,6 +2638,59 @@ pub fn WaylandServer::own_selection_text(self : WaylandServer) -> Bytes? {
|
||||
}
|
||||
}
|
||||
|
||||
///| Have the clipboard written into `fd` (a pipe), as text when it has any, else as a PNG image.
|
||||
/// What it is: "text/plain" or "image/png", or None when it holds neither. The compositor's own
|
||||
/// data is written by `pump_transfers`, which then owns `fd` (see `is_transfer`); a client's is
|
||||
/// written by that client, and `fd` stays the caller's.
|
||||
pub fn WaylandServer::send_clipboard_to(self : WaylandServer, fd : Int) -> String? {
|
||||
let mimes : Array[String] = match self.selection {
|
||||
Some((0U, 0U)) => self.own_mimes
|
||||
Some((ocid, osid)) =>
|
||||
match self.find_client(ocid) {
|
||||
Some(oc) if oc.alive => oc.data_sources.get(osid).unwrap_or([])
|
||||
_ => []
|
||||
}
|
||||
None => []
|
||||
}
|
||||
let (mime, kind) = match
|
||||
clipboard_text_mimes.iter().find_first(m => mimes.contains(m)) {
|
||||
Some(m) => (m, "text/plain")
|
||||
None =>
|
||||
if mimes.contains("image/png") {
|
||||
("image/png", "image/png")
|
||||
} else {
|
||||
return None
|
||||
}
|
||||
}
|
||||
match self.selection {
|
||||
Some((0U, 0U)) =>
|
||||
self.transfers.push((fd, self.own_data, 0, @sys.monotonic_ms() + 10000UL))
|
||||
Some((ocid, osid)) =>
|
||||
match self.find_client(ocid) {
|
||||
Some(oc) => {
|
||||
let w = WireWriter::new()
|
||||
w.str(mime)
|
||||
if @sys.sendmsg_fd(oc.fd, w.finish_msg(osid, 1U), fd) < 0 {
|
||||
return None
|
||||
}
|
||||
}
|
||||
None => return None
|
||||
}
|
||||
None => return None
|
||||
}
|
||||
Some(kind)
|
||||
}
|
||||
|
||||
///| The types UTF-8 text goes by on the clipboard, best first.
|
||||
let clipboard_text_mimes : Array[String] = [
|
||||
"text/plain;charset=utf-8", "text/plain;charset=UTF-8", "UTF8_STRING", "text/plain",
|
||||
]
|
||||
|
||||
///| Whether `fd` is a paste of the compositor's clipboard still being written (and closed) here.
|
||||
pub fn WaylandServer::is_transfer(self : WaylandServer, fd : Int) -> Bool {
|
||||
self.transfers.iter().any(t => t.0 == fd)
|
||||
}
|
||||
|
||||
///| Write what the pipes of pending pastes can take without blocking; close the finished ones
|
||||
/// and any a reader stopped taking for ten seconds.
|
||||
pub fn WaylandServer::pump_transfers(self : WaylandServer) -> Unit {
|
||||
|
||||
@@ -75,6 +75,7 @@ Chandra includes KMS/libinput/compositor adaptations tailored for mainline Linux
|
||||
- **VNC (RFB 3.8, port `5900`)** with Tight-JPEG (`libturbojpeg`), Zlib, Raw, dynamic rotation resize (`ExtendedDesktopSize`), clipboard sync, and 1:1 pointer/touch/keyboard input (tested for Android **AVNC**).
|
||||
- **Mobile Web UI / PWA (HTTP + WebSocket, port `6080`)** with 1:1 touch gestures (tap, drag, long-press right-click, two-finger scroll/right-click), mouse right-click, optional trackpad mode, Android keyboard bridge, live rotation/brightness/OLED-off toggles, and adaptive JPEG streaming.
|
||||
- **Paste (web UI):** `Ctrl+V`, `Ctrl+Shift+V`, `Shift+Insert` (`Cmd+V` on a Mac) put this device's clipboard, text or an image (up to 16 MB, sent as PNG), on the phone's and then press the same keys there. This works over plain HTTP. If something was copied on the phone since the page was last focused, that is pasted instead. The **Paste** button (`KB` bar) and **Paste Image…** (menu) do the same, with `Ctrl+Shift+V` for text in terminals. In the launcher and the password dialog the text is typed in. The browser uploads to `POST /api/clipboard`; the compositor gets the data as a memfd over the control socket (`clipboard-set-fd`, `input-paste`). VNC clients can send text only.
|
||||
- **Copy (web UI):** `Ctrl+C`, `Ctrl+X`, `Ctrl+Shift+C` (`Cmd+C` on a Mac) go to the phone as ever, and what they copied there, text or a PNG image (up to 16 MB), is put on this device's clipboard too. The **Copy** button (`KB` bar; **Copy Selection** in the menu) presses them, with `Ctrl+Shift+C` in terminals, where `Ctrl+C` interrupts. **Copy Clipboard** (menu) takes what is already on the phone's clipboard. Text works over plain HTTP; images need the HTTPS address. When the browser wants a fresh tap first, the page asks for one. The browser reads `GET /api/clipboard/data`; the compositor has the clipboard's owner write it into a pipe sent over the control socket (`clipboard-get-fd`, `input-copy`), and refuses while the session is locked. Nothing is sent to VNC clients.
|
||||
- `https://chandra-6t.tail.site.latha.org/` serves the web UI over HTTPS, tailnet only, from the `chandra-remote` chart in `nandi/cluster` (Caddy on the phone node, proxying to loopback `6080`).
|
||||
- By default (`~/.config/chandra/remote.conf`), `bind=tailscale`, `bind_loopback=1`, and `auth=none`, binding strictly to the Tailscale `100.64.0.0/10` interface + `127.0.0.1` so any device on the same Tailscale tailnet can connect directly with zero password prompt (`http://<tailscale-dns>:6080/` or `<tailscale-dns>:5900`), even while the handset's physical OLED screen is turned off (`chandra-ctl screen off`). Run `chandra-remote status` to inspect endpoints or `chandra-remote passwd [PASS|--none]` to configure optional password auth.
|
||||
|
||||
|
||||
@@ -24,6 +24,8 @@ out=$(curl -fsS -m 30 -H Expect: -H 'X-Chandra-Remote: 1' -H 'Content-Type: imag
|
||||
--data-binary "@$R/p.png" http://127.0.0.1:6080/api/clipboard)
|
||||
echo "$out"
|
||||
[ "$out" = '{"ok":true,"serial":1}' ]
|
||||
# The same image comes back out.
|
||||
curl -fsS -m 30 -H 'X-Chandra-Remote: 1' http://127.0.0.1:6080/api/clipboard/data | cmp - "$R/p.png"
|
||||
# It restarts in place, and answers again.
|
||||
kill -USR2 $remote
|
||||
sleep 2
|
||||
|
||||
@@ -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