| 1 | export async function copyGuestText({ request, sendCopy, valid }) { |
| 2 | const before = await request({ phase: "prepare" }); |
| 3 | if (!valid() || typeof before.revision !== "number" || typeof before.session !== "string") throw new Error("复制窗口已变化,请重新选择文本。"); |
| 4 | await sendCopy(); |
| 5 | if (!valid()) throw new Error("复制窗口已变化,请重新选择文本。"); |
| 6 | const result = await request({ phase: "read", revision: before.revision, session: before.session }); |
| 7 | if (!valid() || result.session !== before.session || result.revision === before.revision || typeof result.text !== "string") { |
| 8 | throw new Error("未收到新的选中文本,请重新选择后复制。"); |
| 9 | } |
| 10 | return { text: result.text }; |
| 11 | } |
| 12 | |
| 13 | |
| 14 | |
| 15 | export function shareClipboard({ connect, native, onStatus, setActive, interval = 300 }) { |
| 16 | let socket, timer, retry, disposed = false, revision, generation = 0, guestReady = false, guestSession; |
| 17 | let polling, writes = Promise.resolve(), lastPayload = "", serial = 0, errorShown = false, acknowledgedRevision; |
| 18 | let sessionGeneration = 0; |
| 19 | let sessionController = new AbortController(); |
| 20 | const acknowledgements = new Map(); |
| 21 | const fileReferences = new Map(); |
| 22 | const retainFiles = value => { |
| 23 | const id = value?.files; |
| 24 | if (typeof id !== "string") return () => {}; |
| 25 | fileReferences.set(id, (fileReferences.get(id) || 0) + 1); |
| 26 | return () => { |
| 27 | const remaining = fileReferences.get(id) - 1; |
| 28 | if (remaining) { fileReferences.set(id, remaining); return; } |
| 29 | fileReferences.delete(id); |
| 30 | void native("clipboardSyncRelease", { files: id }).catch(() => {}); |
| 31 | }; |
| 32 | }; |
| 33 | const disconnected = () => new Error("剪贴板连接已变化,请确认客机已连接后重新粘贴。"); |
| 34 | const invalidateSession = () => { |
| 35 | generation++; sessionGeneration++; |
| 36 | sessionController.abort(); sessionController = new AbortController(); |
| 37 | guestReady = false; revision = undefined; acknowledgedRevision = undefined; lastPayload = ""; |
| 38 | polling = undefined; writes = Promise.resolve(); |
| 39 | for (const pending of acknowledgements.values()) pending.reject(); |
| 40 | acknowledgements.clear(); |
| 41 | setActive(false); |
| 42 | void native("clipboardSyncCancel").catch(() => {}); |
| 43 | }; |
| 44 | const requireSession = signal => { |
| 45 | if (disposed || signal.aborted || !guestReady || socket?.readyState !== 1) throw disconnected(); |
| 46 | }; |
| 47 | const waitForSession = (work, signal) => new Promise((resolve, reject) => { |
| 48 | const abort = () => { signal.removeEventListener("abort", abort); reject(disconnected()); }; |
| 49 | Promise.resolve(work).then(resolve, reject).finally(() => signal.removeEventListener("abort", abort)); |
| 50 | if (signal.aborted) abort(); |
| 51 | else signal.addEventListener("abort", abort, { once: true }); |
| 52 | }); |
| 53 | const warn = () => { if (!disposed && !errorShown) { errorShown = true; onStatus("剪贴板共享暂未完成,请检查文件是否仍存在及大小限制。"); } }; |
| 54 | const send = (connection, content) => new Promise((resolve, reject) => { |
| 55 | const id = ++serial; |
| 56 | const timeout = setTimeout(() => { acknowledgements.delete(id); reject(new Error("Clipboard acknowledgement timed out")); }, 8000); |
| 57 | acknowledgements.set(id, { resolve: () => { clearTimeout(timeout); resolve(); }, reject: () => { clearTimeout(timeout); reject(new Error("Clipboard disconnected")); } }); |
| 58 | try { connection.send(JSON.stringify({ ...content, serial: id })); } |
| 59 | catch { acknowledgements.get(id)?.reject(); acknowledgements.delete(id); } |
| 60 | }); |
| 61 | const payload = value => typeof value.text === "string" ? { text: value.text } |
| 62 | : typeof value.png === "string" ? { png: value.png } |
| 63 | : typeof value.files === "string" ? { files: value.files } : null; |
| 64 | const readHost = async (initial = false) => { |
| 65 | if (disposed || !guestReady || socket?.readyState !== 1) return; |
| 66 | const currentSocket = socket, currentGeneration = generation, session = sessionGeneration; |
| 67 | let releaseFiles = () => {}; |
| 68 | try { |
| 69 | const current = await native("clipboardRevision"); |
| 70 | if (typeof current !== "number") throw new Error("Clipboard revision unavailable"); |
| 71 | if (!initial && current === revision && current === acknowledgedRevision) return; |
| 72 | const value = await native("clipboardSyncRead"); |
| 73 | releaseFiles = retainFiles(value); |
| 74 | const content = payload(value); |
| 75 | const finalRevision = await native("clipboardRevision"); |
| 76 | if (disposed || !guestReady || socket !== currentSocket || currentGeneration !== generation || |
| 77 | value.revision !== finalRevision) return; |
| 78 | revision = value.revision; |
| 79 | if (!content) throw new Error("Clipboard content unavailable"); |
| 80 | const encoded = JSON.stringify(content); |
| 81 | if (initial || value.revision !== acknowledgedRevision || encoded !== lastPayload) await send(currentSocket, content); |
| 82 | if (disposed || !guestReady || socket !== currentSocket || currentGeneration !== generation) return; |
| 83 | acknowledgedRevision = value.revision; |
| 84 | lastPayload = encoded; |
| 85 | setActive(true); |
| 86 | errorShown = false; |
| 87 | } catch { |
| 88 | if (disposed || socket !== currentSocket || session !== sessionGeneration) return; |
| 89 | warn(); |
| 90 | setActive(false); |
| 91 | revision = undefined; lastPayload = ""; |
| 92 | currentSocket.close(); |
| 93 | throw new Error("Clipboard synchronization failed"); |
| 94 | } finally { releaseFiles(); } |
| 95 | }; |
| 96 | const poll = (initial = false) => { |
| 97 | if (!polling) { |
| 98 | const current = readHost(initial).finally(() => { if (polling === current) polling = undefined; }); |
| 99 | polling = current; |
| 100 | } |
| 101 | return polling; |
| 102 | }; |
| 103 | const receive = (value) => { |
| 104 | if (value.hello) { |
| 105 | const hello = value.hello; |
| 106 | const supported = hello.version === 1 && ["linux", "windows", "darwin"].includes(hello.os) && |
| 107 | typeof hello.session === "string" && hello.session.length > 0 && |
| 108 | ["text", "png", "files"].every(format => hello.formats?.includes(format)); |
| 109 | const previouslyReady = guestReady; |
| 110 | if (previouslyReady && (guestSession !== hello.session || !supported || !hello.available)) invalidateSession(); |
| 111 | guestSession = hello.session; |
| 112 | guestReady = supported && hello.available === true; |
| 113 | if (!guestReady) setActive(false); |
| 114 | if (guestReady && (!previouslyReady || revision === undefined)) void poll(true).catch(warn); |
| 115 | return; |
| 116 | } |
| 117 | if (value.ack) { |
| 118 | acknowledgements.get(value.ack)?.resolve(); acknowledgements.delete(value.ack); return; |
| 119 | } |
| 120 | if (value.error) { warn(); socket?.close(); return; } |
| 121 | const content = payload(value), sequence = ++generation, currentSocket = socket, session = sessionGeneration; |
| 122 | if (!content) return; |
| 123 | const releaseFiles = retainFiles(content); |
| 124 | writes = writes.then(async () => { |
| 125 | if (disposed || !guestReady || socket !== currentSocket || sequence !== generation) return; |
| 126 | const current = await native("clipboardRevision"); |
| 127 | if (disposed || !guestReady || socket !== currentSocket || sequence !== generation) return; |
| 128 | if (revision === undefined || current !== revision) { |
| 129 | |
| 130 | void poll().catch(warn); |
| 131 | return; |
| 132 | } |
| 133 | if (JSON.stringify(content) === lastPayload) return; |
| 134 | const result = await native("clipboardSyncWrite", { ...content, revision }); |
| 135 | if (disposed || socket !== currentSocket || session !== sessionGeneration) return; |
| 136 | if (result.superseded) { void poll().catch(warn); return; } |
| 137 | revision = result.revision; |
| 138 | acknowledgedRevision = result.revision; |
| 139 | lastPayload = JSON.stringify(content); |
| 140 | onStatus(content.files ? "文件已复制到本机,可在本机粘贴" : "已复制到本机"); |
| 141 | }).catch(() => { |
| 142 | if (session === sessionGeneration) warn(); |
| 143 | }).finally(releaseFiles); |
| 144 | }; |
| 145 | const open = () => { |
| 146 | if (disposed) return; |
| 147 | revision = undefined; lastPayload = ""; guestReady = false; |
| 148 | socket = connect(); |
| 149 | const connection = socket; |
| 150 | socket.onopen = () => { |
| 151 | if (disposed || socket !== connection) return; |
| 152 | timer = setInterval(() => void poll().catch(warn), interval); |
| 153 | }; |
| 154 | socket.onmessage = event => { |
| 155 | if (disposed || socket !== connection) return; |
| 156 | try { receive(JSON.parse(event.data)); } catch { } |
| 157 | }; |
| 158 | socket.onclose = () => { |
| 159 | if (disposed || socket !== connection) return; |
| 160 | invalidateSession(); clearInterval(timer); |
| 161 | retry = setTimeout(open, 1500); |
| 162 | }; |
| 163 | socket.onerror = () => { }; |
| 164 | }; |
| 165 | open(); |
| 166 | return { poll, async sync() { |
| 167 | const signal = sessionController.signal; |
| 168 | requireSession(signal); |
| 169 | for (;;) { |
| 170 | await waitForSession(poll(), signal); |
| 171 | const pendingWrites = writes; |
| 172 | await waitForSession(pendingWrites, signal); |
| 173 | const sequence = generation; |
| 174 | const current = await waitForSession(native("clipboardRevision"), signal); |
| 175 | requireSession(signal); |
| 176 | if (typeof current !== "number") throw new Error("无法确认当前剪贴板版本,请重新粘贴。"); |
| 177 | if (current === acknowledgedRevision && sequence === generation && pendingWrites === writes) return; |
| 178 | } |
| 179 | }, dispose() { |
| 180 | disposed = true; invalidateSession(); clearInterval(timer); clearTimeout(retry); |
| 181 | socket?.close(); |
| 182 | } }; |
| 183 | } |