PasteFerry (隔空贴): clipboard and file sync across macOS, Windows and Linux. Direct-first, end-to-end encrypted. Optional official access: no server to host. Independent self-hosting remains available.
Dart airdrop-alternativeclipboardclipboard-sharingclipboard-synccopy-pastecross-platformend-to-end-encryptionfile-syncfile-transferfluttergolanglinuxmacosnat-traversalp2pself-hostedtailscaleuniversal-clipboardwebrtcwindows
CopySync 1.0.0
baiyuzed9044a650712
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlnew file mode 100644index 0000000..0216422--- /dev/null+++ b/.github/workflows/ci.yml@@ -0,0 +1,44 @@+name: CI++on:+ push:+ branches: [main]+ pull_request:++jobs:+ server:+ name: 服务器+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-go@v5+ with:+ go-version-file: server/go.mod+ cache-dependency-path: server/go.sum+ - run: go vet ./... && go test ./...+ working-directory: server++ client-core:+ name: 后台服务+ # 剪贴板部分是 cgo + AppKit,只能在 macOS 上编译+ runs-on: macos-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-go@v5+ with:+ go-version-file: client-core/go.mod+ cache-dependency-path: client-core/go.sum+ - run: go vet ./... && go test ./...+ working-directory: client-core++ ui:+ name: 界面+ runs-on: macos-latest+ steps:+ - uses: actions/checkout@v4+ - uses: subosito/flutter-action@v2+ with:+ channel: stable+ cache: true+ - run: flutter pub get && flutter analyze && flutter test+ working-directory: uidiff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..672cd43--- /dev/null+++ b/.gitignore@@ -0,0 +1,17 @@+# 构建产物+/dist/+/release/+/spikes/build/+ui/tool/screenshots/out/++# Go+*.test+*.out++# macOS / 编辑器+.DS_Store+.idea/+.vscode/++# 本地工具配置+.claude/diff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 0000000..51b9a6c--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,27 @@+# 更新记录 / Changelog++## 1.0.0 — 2026-10-08++第一个正式版本。 First public release.++**Mac 客户端 / Mac app**++- 同步文本、带格式的文本、图片、文件与文件夹;50 MB 以内复制即推送,更大的按需拉取。+ Syncs text, rich text, images, files and folders; items under 50 MB are pushed on copy, larger ones are pulled on demand.+- 复制记录:查看最近 3 天所有设备上复制过的内容,随时放回剪贴板。+ History of everything copied on any of your Macs in the last 3 days.+- 6 位配对码 + 安全指纹核对。 Pairing with a 6-character code and fingerprint check.+- DMG 拖拽安装;首次打开时由 App 自己启用后台同步,不需要终端。+ Drag-to-install DMG; the app enables background sync itself on first launch, no Terminal needed.+- 覆盖安装新版、或移动 App 位置后,自动校正后台服务。+ After an in-place update or moving the app, the background service is re-pointed and restarted automatically.+- 带格式的文本同时写入纯文本,粘贴到只认纯文本的输入框不再出现 HTML 标签。+ Rich text is also written as plain text, so no HTML markup leaks into plain-text fields.+- 界面在信令连接与对端上下线时实时刷新。 Connection status updates live.+- Intel 与 Apple 芯片通用;支持深色外观。 Universal binary; dark appearance.++**服务器 / Server**++- 信令 + 自带 STUN + TURN 中转,单个静态二进制。 Signaling, built-in STUN and TURN relay in one static binary.+- 提供 systemd 一键安装脚本与 Docker Compose 配置。 One-step systemd installer and Docker Compose setup.+- 新增 `-version` 参数。 Added the `-version` flag.diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..280ddfc--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 baiyuze++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.en.md b/README.en.mdnew file mode 100644index 0000000..c32914c--- /dev/null+++ b/README.en.md@@ -0,0 +1,252 @@+<p align="center">+ <img src="docs/assets/icon.png" width="112" height="112" alt="CopySync icon">+</p>++<h1 align="center">CopySync</h1>++<p align="center">+ Copy on one Mac, paste on the other.<br>+ Text, images, files and whole folders — across Apple IDs and across networks.+</p>++<p align="center">+ <a href="https://github.com/baiyuze/copysync/releases/latest"><strong>Download for macOS</strong></a>+ ·+ <a href="https://baiyuze.github.io/copysync/en/">Website</a>+ ·+ <a href="README.md">简体中文</a>+</p>++<p align="center">+ <img src="https://img.shields.io/github/v/release/baiyuze/copysync?color=0A66D8" alt="Release">+ <img src="https://img.shields.io/badge/macOS-13%2B-1D1D1F" alt="macOS 13+">+ <img src="https://img.shields.io/badge/Intel%20%2B%20Apple%20silicon-universal-1D1D1F" alt="Universal binary">+ <img src="https://img.shields.io/github/license/baiyuze/copysync?color=6E6E73" alt="MIT License">+</p>++<p align="center">+ <img src="docs/assets/screenshots/history.png" alt="CopySync's history view: files, images and text arriving from other Macs">+</p>++> The app's interface is in Simplified Chinese for now. The screenshots below are annotated in the alt text.++## Why++If you work on two Macs, you move things between them all day: a snippet of text, a screenshot, a file.++The built-in options each get in the way:++- **Universal Clipboard** needs both Macs on the same Apple ID, close to each other, with Bluetooth and Wi‑Fi on. A work Mac and a personal Mac rarely share an Apple ID, and large files often fail halfway.+- **AirDrop** makes you pick a device and accept on the other side every time, and it only moves files, not the clipboard.+- **Messaging yourself** through a chat app means manual downloads, recompressed images, and your files sitting on someone else's server.++With CopySync you pair two Macs once. After that, `⌘C` on one and `⌘V` on the other. Data goes directly between the devices; when a direct connection can't be made, it is relayed through a server you run yourself. Everything is end-to-end encrypted and the server cannot read it.++| | CopySync | Universal Clipboard | AirDrop | Chat apps |+|---|:-:|:-:|:-:|:-:|+| Different Apple IDs | ✓ | — | Needs accepting | ✓ |+| Different networks (home ↔ office) | ✓ | — | — | ✓ |+| Paste right away, nothing to accept | ✓ | ✓ | — | — |+| Files and whole folders | ✓ | Unreliable | ✓ | Zipped |+| History of what you copied | ✓ | — | — | Scroll back |+| Content stays off third-party servers | ✓ | ✓ | ✓ | — |++## Features++- **Text, rich text, images, files and folders.** What you copy is what comes out on the other side.+- **Size-aware transfer.** Anything under 50 MB (adjustable) is pushed as soon as you copy, so the other Mac can paste immediately. Larger files sync as a record you can pull when you need them.+- **History.** Everything copied on any of your Macs in the last 3 days (adjustable), ready to put back on the clipboard.+- **Direct first, relay as fallback.** Devices connect peer-to-peer; behind symmetric NAT or a strict firewall, traffic switches to the TURN relay on your server automatically.+- **Fingerprint check when pairing**, so neither the server nor anyone on the network can impersonate your device.+- **Runs in the background.** Keeps syncing with the window closed, starts at login, recovers from crashes.+- **Native on Intel and Apple silicon**, light and dark appearance.++<table>+ <tr>+ <td><img src="docs/assets/screenshots/devices.png" alt="Devices: paired Macs and whether each is connected directly or through the relay"></td>+ <td><img src="docs/assets/screenshots/verify.png" alt="Pairing: compare the fingerprint shown on both Macs before confirming"></td>+ </tr>+ <tr>+ <td><img src="docs/assets/screenshots/settings.png" alt="Settings: server address, auto-sync size limit, content types"></td>+ <td><img src="docs/assets/screenshots/history-dark.png" alt="History in dark appearance"></td>+ </tr>+</table>++## Supported systems++| | Requirement |+|---|---|+| **Mac app** | macOS 13 Ventura or later; universal binary for Intel and Apple silicon, no Rosetta needed |+| **Server** | Any Linux on x86_64 or ARM64 with systemd or Docker; it can also run on one of your Macs |+| **Windows** | Planned |+| **iPhone / iPad** | Not supported. iOS does not let apps watch the clipboard in the background, so copy-and-it's-there can't work the way it does on the Mac |++## Install++There are two parts: **the app on each Mac**, and **a server both Macs can reach**. If both Macs are on the same LAN, the server can run on one of them.++### 1. Deploy the server++On a Linux server, as root:++```bash+curl -LO https://github.com/baiyuze/copysync/releases/latest/download/copysync-server-1.0.0-linux-amd64.tar.gz+tar xzf copysync-server-1.0.0-linux-amd64.tar.gz+cd copysync-server-1.0.0-linux-amd64+sudo ./install.sh <public IP of the server>+```++The script registers a systemd service that starts on boot and prints the address to enter in the app. Use the `linux-arm64` package on ARM servers.++Open these ports in your firewall or cloud security group:++| Port | Protocol | Purpose |+|---|---|---|+| 8787 | TCP | Signaling (WebSocket) |+| 3478 | UDP | STUN / TURN |+| 32768–60999 | UDP | TURN relay ports, assigned by the OS |++For Docker, or for LAN-only use, see the [server deployment guide](server/deploy/README.md).++### 2. Install the app on each Mac++1. Download [CopySync-1.0.0.dmg](https://github.com/baiyuze/copysync/releases/latest), open it and drag CopySync into Applications.+2. Open CopySync from Applications.++ The first time, macOS says it can't verify the developer: CopySync isn't notarized by Apple yet (that requires a paid developer account). Go to **System Settings → Privacy & Security**, scroll down and click **Open Anyway**. You only need to do this once.++3. Click **启用后台同步** (Enable background sync).+4. In **设置 → 信令服务器地址** (Settings → Signaling server), enter `ws://<server address>:8787/signal` and press Return.+5. Recent versions of macOS ask whether CopySync Daemon may read the clipboard. Allow it; you can switch it to always allow under **System Settings → Privacy & Security → Paste from Other Apps**.++### 3. Pair++1. On one Mac: **设备 → 添加设备 → 生成配对码** (Devices → Add device → Generate code).+2. On the other: **添加设备 → 输入配对码** (Add device → Enter code), and type the 6 characters.+3. Each screen shows a fingerprint. **Confirm only if they match character for character.**++From then on, copy on either Mac and paste on the other.++## How it works++```mermaid+flowchart LR+ subgraph A["Mac A"]+ UA["CopySync app"] <-- "gRPC" --> DA["Background service"]+ end+ subgraph B["Mac B"]+ DB["Background service"] <-- "gRPC" --> UB["CopySync app"]+ end+ S[("Your server\nsignaling + TURN")]+ DA -- "Signaling (WebSocket)" --> S+ DB -- "Signaling (WebSocket)" --> S+ DA <== "WebRTC direct (DTLS)" ==> DB+ DA <-. "Relayed via TURN when direct fails" .-> S+ S <-.-> DB+```++| Component | Role | Built with |+|---|---|---|+| Background service `copysyncd` | Watches the clipboard, connects to peers, sends, receives and stores | Go, with cgo calling AppKit for the clipboard |+| App `CopySync.app` | History, pairing, settings | Flutter, talks to the service over local gRPC |+| Server `copysync-server` | Device discovery, pairing codes, signaling, TURN relay | Go, a single static binary using about 15 MB of RAM |+| Protocol `proto/` | Messages shared by all three | Protocol Buffers |++**What happens when you copy:**++1. The service checks the clipboard's change count at short intervals. Reading the count and types needs no permission and never triggers a prompt.+2. On a change it reads the content and picks a transport: text is inlined in the message; images and files under 50 MB are streamed right away (tar + zstd); anything larger is announced as a record only.+3. The receiving Mac writes the data to a local cache and then onto its clipboard, so `⌘V` pastes real local files.++**How the connection is made:** devices connect to the signaling server over WebSocket and use WebRTC ICE to try a direct path (LAN addresses, then public addresses discovered via STUN), falling back to a TURN relay address. Data flows over WebRTC data channels, encrypted with DTLS.++### Security model++- **The server keeps no accounts.** A device's identity is an Ed25519 key, and its ID is derived from the public key, so the server can verify that an ID belongs to a key without a user table.+- **Fingerprints are compared by a person when pairing.** Each Mac shows a fingerprint of the other's public key (the first 60 bits of its SHA-256, like `R8NF-2WTC-QL5J`). The server could swap keys in transit, but it cannot make both screens show the same fingerprint — this step is what stops a man in the middle.+- **Every signaling message after that is signed**, so the server cannot forge a device. The DTLS certificate fingerprint of the direct channel is also sent signed and checked against the actual certificate after the handshake; a mismatch drops the connection.+- **The relay can't read anything either.** TURN only forwards encrypted UDP packets. Relay credentials are issued per device and expire after 12 hours.+- **No App Sandbox**, because CopySync needs to read files at whatever path you copy them from.++### Fallbacks++| Situation | What happens |+|---|---|+| No direct path (symmetric NAT, corporate firewall) | Switches to the TURN relay on your server, still encrypted; the app shows "relay" |+| Public STUN servers unreliable (common in mainland China) | The server runs its own STUN and clients prefer it |+| Signaling connection drops | Reconnects with exponential backoff (1 s up to 30 s, with jitter); status is shown live |+| Pairing confirmed on one side before the other | Early handshake messages are held and replayed once the other side confirms; the direct link is up within tens of milliseconds |+| Large files | Above the limit only a record is synced; if the source file is gone when you pull, you get a clear message |+| Apps that only accept plain text | Rich text is written as both HTML and plain text, so no markup leaks into the paste |+| Clipboard access not granted yet | Content isn't read (it would block on a prompt a background process can't show); the app asks you to grant access |+| Background service crashes | launchd restarts it, throttled to once every 10 seconds |+| App updated in place, or moved | On launch the app re-points the login item and restarts the service on the new version |+| History and cache grow | Expired items are removed automatically; 3 days by default |++### Lessons learned++Each of these was found by testing and has a regression test. The full investigation is in [spikes/results.md](spikes/results.md) (Chinese).++- **macOS clipboard calls must run on the main thread.** With the privacy features on, the clipboard API talks to a system UI service through the run loop; calling it from a plain thread crashes. The service locks the main thread at startup and dedicates it to the clipboard.+- **"Transfer only when the other side pastes" isn't possible on macOS.** The system resolves promised clipboard data about 0.1 s after it's written and caches it, and there is no notification that the clipboard was read. That's why small items are pushed ahead of time and large files are pulled on demand.+- **Three pitfalls in the pion WebRTC library:** `DetachDataChannels()` is a global switch that breaks regular send/receive on every channel; `OnMessage` doesn't buffer, so messages arriving before the handler is set are dropped (202 bytes sent, 0 received); `OnBufferedAmountLow` is edge-triggered, so a waiter that arrives late never wakes up (a 20 MB transfer stalled at 786 KB).++Measured on a LAN with a direct connection: a 20 MB file transfers in about 330 ms with matching checksums.++## Limitations++- **Not notarized by Apple**, so the first launch needs one manual approval.+- **Both Macs need to be online at the same time.** The server stores nothing, so there's no store-and-forward.+- **Relayed transfers are limited by your server's bandwidth.** Direct connections aren't.+- macOS only for now. The interface is in Simplified Chinese.++## Build from source++Requires Go 1.26, Flutter 3.44 and Xcode.++```bash+./scripts/build.sh # build everything into dist/+./scripts/package.sh # build the DMG and server packages into release/+```++During development:++```bash+cd client-core && go test ./... # service tests+cd ui && flutter test # app tests+./scripts/install-macos.sh # install the service from dist/ as a login item+./dist/copysync-cli status # service status+./dist/copysync-cli watch # live event stream+```++After changing a `.proto` file, run `./scripts/gen-proto.sh` (uses buf; install with `go install`, no protoc needed). After changing the UI, run `./tools/screenshots/render.sh` to regenerate the screenshots from demo data.++```+client-core/ background service (Go)+ internal/clipboard clipboard (cgo + Objective-C, main thread only)+ internal/transport signaling (WebSocket) and P2P (WebRTC)+ internal/sync sync engine: routing, packing, transfer, storage+ui/ app (Flutter)+server/ signaling + TURN relay server (Go); deployment files in server/deploy/+proto/ message definitions and device ID derivation, shared by all three+docs/ website (GitHub Pages)+spikes/ technical validation done before development+```++## Troubleshooting++**Nothing comes off the clipboard, and `pbpaste` is empty too**+The system pasteboard service may be stuck: an app declared clipboard content and then crashed, leaving types without data. Run `killall pboard` and copy again.++**A device stays offline**+Check **设置 → 连接状态** (Settings → Connection) on both Macs. If it isn't connected, verify the server address and that port 8787 is reachable.++**Always "relay", never "direct"**+NAT traversal didn't succeed, which is common with symmetric NAT or strict firewalls. Everything still works; speed is limited by the server's bandwidth.++**Logs**+The background service logs to `~/Library/Logs/CopySync/daemon.log`. On the server, use `journalctl -u copysync-server -f`.++## License++[MIT](LICENSE)diff --git a/README.md b/README.mdnew file mode 100644index 0000000..ab361d0--- /dev/null+++ b/README.md@@ -0,0 +1,250 @@+<p align="center">+ <img src="docs/assets/icon.png" width="112" height="112" alt="CopySync 图标">+</p>++<h1 align="center">CopySync</h1>++<p align="center">+ 在这台 Mac 复制,到那台 Mac 粘贴。<br>+ 文本、图片、文件、整个文件夹都可以,不限 Apple ID,不限是否在同一个网络。+</p>++<p align="center">+ <a href="https://github.com/baiyuze/copysync/releases/latest"><strong>下载 macOS 版</strong></a>+ ·+ <a href="https://baiyuze.github.io/copysync/">项目主页</a>+ ·+ <a href="README.en.md">English</a>+</p>++<p align="center">+ <img src="https://img.shields.io/github/v/release/baiyuze/copysync?label=%E7%89%88%E6%9C%AC&color=0A66D8" alt="版本">+ <img src="https://img.shields.io/badge/macOS-13%2B-1D1D1F" alt="macOS 13+">+ <img src="https://img.shields.io/badge/Intel%20%2B%20Apple%20%E8%8A%AF%E7%89%87-%E9%80%9A%E7%94%A8-1D1D1F" alt="Intel 与 Apple 芯片通用">+ <img src="https://img.shields.io/github/license/baiyuze/copysync?color=6E6E73" alt="MIT 许可">+</p>++<p align="center">+ <img src="docs/assets/screenshots/history.png" alt="CopySync 的复制记录界面:来自其他 Mac 的文件、图片和文字">+</p>++## 它解决什么问题++手边有两台 Mac 的人,每天都在做同一件事:这台上复制了一段文字、一张截图、一个文件,要拿到那台上用。++现有的办法各有各的不顺手:++- **系统自带的「通用剪贴板」**要求两台设备登录同一个 Apple ID、离得足够近、蓝牙和 Wi‑Fi 都开着。公司电脑和自己的电脑通常不是同一个 Apple ID;大文件经常复制到一半就没了。+- **隔空投送**每次都要选设备、在另一台上点接收,而且只传文件,不管剪贴板。+- **用聊天软件发给自己**要手动下载、图片会被压缩,文件还会留在第三方的服务器上。++CopySync 的做法是:两台 Mac 配对一次,之后在一台上 `⌘C`,另一台上直接 `⌘V`。数据在两台设备之间直接传输,打不通直连时经过你自己部署的服务器中转,全程端到端加密,服务器看不到内容。++| | CopySync | 通用剪贴板 | 隔空投送 | 聊天软件 |+|---|:-:|:-:|:-:|:-:|+| 不同 Apple ID 之间 | ✓ | — | 需对方接收 | ✓ |+| 不在同一个网络(家里 ↔ 公司) | ✓ | — | — | ✓ |+| 复制后直接粘贴,不用点接收 | ✓ | ✓ | — | — |+| 文件与整个文件夹 | ✓ | 不稳定 | ✓ | 打包后可以 |+| 复制历史,可以找回之前的内容 | ✓ | — | — | 翻聊天记录 |+| 内容不经过第三方服务器 | ✓ | ✓ | ✓ | — |++## 功能++- **文本、带格式的文本、图片、文件、文件夹**都能同步。复制什么,对面粘贴出来就是什么。+- **按大小分流**:50 MB 以内(可调)的内容复制时直接推送,对面立刻能粘贴;更大的文件只同步一条记录,需要时点「拉取到本机」,不会无谓地占用带宽和磁盘。+- **复制记录**:最近 3 天(可调)在所有设备上复制过的内容都在这里,随时可以放回剪贴板。+- **直连优先,自动中转**:先尝试设备之间直连;在对称 NAT、公司防火墙后面打不通时,自动改走你服务器上的 TURN 中转。+- **配对时核对安全指纹**:防止服务器或网络上的第三方冒充你的设备。+- **后台常驻**:关掉窗口照常同步,开机自动启动,崩溃后自动恢复。+- **Intel 与 Apple 芯片原生运行**,支持浅色与深色外观。++<table>+ <tr>+ <td><img src="docs/assets/screenshots/devices.png" alt="设备页:已配对的设备、直连或中转状态"></td>+ <td><img src="docs/assets/screenshots/verify.png" alt="配对时核对两台设备上显示的安全指纹"></td>+ </tr>+ <tr>+ <td><img src="docs/assets/screenshots/settings.png" alt="设置页:服务器地址、同步上限、同步的内容类型"></td>+ <td><img src="docs/assets/screenshots/history-dark.png" alt="深色外观下的复制记录"></td>+ </tr>+</table>++## 支持哪些电脑++| | 要求 |+|---|---|+| **Mac 客户端** | macOS 13 Ventura 及以上;Intel 与 Apple 芯片(M1–M4 等)通用,不需要 Rosetta |+| **服务器** | 任意 Linux(x86_64 或 ARM64),systemd 或 Docker 均可;也可以直接跑在其中一台 Mac 上 |+| **Windows** | 计划中 |+| **iPhone / iPad** | 暂不支持。iOS 不允许 App 在后台监听剪贴板,做不到 Mac 上这种复制即同步的体验 |++## 安装++整套东西由两部分组成:**每台 Mac 装一个 App**,再加**一台两端都能访问到的服务器**。两台 Mac 在同一个局域网时,服务器直接放在其中一台上就行。++### 1. 部署服务器++在 Linux 服务器上(需要 root):++```bash+curl -LO https://github.com/baiyuze/copysync/releases/latest/download/copysync-server-1.0.0-linux-amd64.tar.gz+tar xzf copysync-server-1.0.0-linux-amd64.tar.gz+cd copysync-server-1.0.0-linux-amd64+sudo ./install.sh <服务器公网IP>+```++脚本会注册一个开机自启的 systemd 服务,并在最后打印出客户端要填的地址。ARM 服务器下载 `linux-arm64` 版本。++云服务器的安全组或防火墙需要放行:++| 端口 | 协议 | 用途 |+|---|---|---|+| 8787 | TCP | 信令(WebSocket) |+| 3478 | UDP | STUN / TURN |+| 32768–60999 | UDP | TURN 中转端口,系统随机分配 |++用 Docker 部署、或者只在局域网里用,见[服务器部署说明](server/deploy/README.md)。++### 2. 在每台 Mac 上安装 App++1. 下载 [CopySync-1.0.0.dmg](https://github.com/baiyuze/copysync/releases/latest),打开后把 CopySync 拖进「应用程序」。+2. 从「应用程序」里打开 CopySync。++ 第一次打开时 macOS 会提示「无法验证开发者」:CopySync 还没有经过 Apple 公证(需要付费开发者账号)。到 **系统设置 → 隐私与安全性**,在页面下方点 **仍要打开**。只需要这一次。++3. 点 **启用后台同步**。+4. 在 **设置 → 信令服务器地址** 填入 `ws://<服务器地址>:8787/signal`,按回车。+5. 较新的 macOS 会询问是否允许 CopySync Daemon 读取剪贴板,选择允许。之后可以在 **系统设置 → 隐私与安全性 → 从其他 App 粘贴** 里改为始终允许,App 里也有直达按钮。++### 3. 配对++1. 在一台 Mac 上点 **设备 → 添加设备 → 生成配对码**。+2. 在另一台上点 **添加设备 → 输入配对码**,输入那 6 位字符。+3. 两台屏幕上会各自显示一串安全指纹,**逐字核对一致后**再点确认。++之后在任意一台上复制,另一台就能直接粘贴。++## 工作原理++```mermaid+flowchart LR+ subgraph A["Mac A"]+ UA["CopySync 界面"] <-- "gRPC" --> DA["后台服务"]+ end+ subgraph B["Mac B"]+ DB["后台服务"] <-- "gRPC" --> UB["CopySync 界面"]+ end+ S[("你的服务器\n信令 + TURN")]+ DA -- "信令(WebSocket)" --> S+ DB -- "信令(WebSocket)" --> S+ DA <== "WebRTC 直连(DTLS 加密)" ==> DB+ DA <-. "打不通时经 TURN 中转" .-> S+ S <-.-> DB+```++| 组件 | 做什么 | 技术 |+|---|---|---|+| 后台服务 `copysyncd` | 监听剪贴板、与对端建立连接、收发与落盘 | Go,剪贴板部分用 cgo 调用 AppKit |+| 界面 `CopySync.app` | 复制记录、设备配对、设置 | Flutter,经本机 gRPC 与后台服务通信 |+| 服务器 `copysync-server` | 设备发现、转达配对码、转发信令、TURN 中转 | Go,单个静态二进制,约 15 MB 内存 |+| 协议 `proto/` | 三方共用的消息定义 | Protocol Buffers |++**一次复制的经过:**++1. 后台服务每隔一小段时间检查剪贴板的变更计数。只看计数和类型不需要授权,也不会触发系统提示。+2. 发现变化后读取内容,按类型和大小决定怎么传:文本直接内联在消息里;50 MB 以内的图片与文件打包成流(tar + zstd)立即推送;更大的只发一条记录。+3. 对端收到后先写入本地缓存,再写入剪贴板。在那台 Mac 上 `⌘V` 粘贴出来的,就是本地的真实文件。++**连接是怎么建立的:**设备通过 WebSocket 连上信令服务器,用 WebRTC 的 ICE 尝试直连(局域网地址、经 STUN 探测到的公网地址),都失败时使用 TURN 中转地址。数据走 WebRTC 数据通道,DTLS 加密。++### 安全模型++- **服务器不存账号**。设备身份是一把 Ed25519 密钥,设备 ID 由公钥派生,服务器据此就能验证"这个 ID 确实属于这把公钥",无需用户表。+- **配对时人工核对指纹**。两台设备各自显示对方公钥的指纹(SHA-256 的前 60 位,形如 `R8NF-2WTC-QL5J`)。服务器可以在配对时替换转发中的公钥,但没法让两边显示出相同的指纹,这一步就是防中间人的闸门。+- **之后的每条信令都带签名**,服务器无法伪造设备。直连通道的 DTLS 证书指纹也经签名传递,握手后比对实际证书,不一致立即断开。+- **中转也看不到内容**。TURN 只转发加密后的 UDP 包。中转凭证按设备单独签发,12 小时过期。+- **不启用 App 沙盒**:需要访问你复制的任意路径下的文件。++### 兜底:出问题时会发生什么++| 情况 | 处理方式 |+|---|---|+| 两端打不通直连(对称 NAT、公司防火墙) | 自动改走服务器的 TURN 中转,内容依然加密;界面上显示「中转」 |+| 公共 STUN 在国内时通时断 | 服务器自带 STUN,客户端优先用它 |+| 信令服务器断开 | 指数退避自动重连(1 秒起,最长 30 秒,带随机抖动),界面实时显示连接状态 |+| 配对时两端确认有先后 | 先确认一方发来的握手消息会被暂存,另一方确认后重放,配对完成几十毫秒内即可直连 |+| 大文件 | 超过阈值只同步记录,按需拉取;拉取时源文件已被删除会明确提示,而不是失败得不明不白 |+| 只认纯文本的输入框 | 带格式的文本同时写入 HTML 与纯文本两份,粘贴到哪里都不会出现标签 |+| 还没有授权读取剪贴板 | 不去读内容(否则会卡在一个后台进程看不见的系统弹窗上),界面上提示去授权 |+| 后台服务崩溃 | 由 launchd 自动拉起;10 秒节流,不会疯狂重启 |+| 覆盖安装了新版、或 App 换了位置 | 打开 App 时自动校正登录项,并重启到新版本 |+| 记录和缓存越来越多 | 到期自动清理,默认保留 3 天 |++### 踩过的坑++这些都是实测撞出来的,各自对应一个回归测试。完整的验证过程见 [spikes/results.md](spikes/results.md)。++- **macOS 的剪贴板调用必须在主线程。**开启隐私机制后,剪贴板 API 要经系统 UI 服务通信,依赖 run loop,在普通线程上调用会直接崩溃。后台服务启动时就把主线程锁住,专门留给剪贴板,业务逻辑投递过去执行。+- **"对方按下粘贴键才传输"在 macOS 上做不到。**系统在写入剪贴板后约 0.1 秒就会把延迟提供的数据兑现并缓存,真正按下 `⌘V` 时不再回调,也没有"剪贴板被读取"的通知。所以小文件是预先推送的,大文件改为手动拉取。+- **WebRTC 库(pion)的三个坑**:`DetachDataChannels()` 是全局开关,开了以后所有通道的普通收发都失效;`OnMessage` 不缓冲,回调设置之前到达的消息直接丢弃(实测发 202 字节,收到 0 字节);`OnBufferedAmountLow` 是边沿触发,等待方晚一步进入等待就再也等不到唤醒(20 MB 传到 786 KB 卡死)。++局域网直连实测:20 MB 文件约 330 毫秒传完,校验和一致。++## 已知限制++- **没有经过 Apple 公证**,第一次打开需要手动放行一次。+- **两台设备需要同时在线**。服务器不存数据,所以没有"离线时先存着、上线再取"。+- **中转模式的速度取决于服务器带宽**。直连时不受影响。+- 目前只有 macOS 客户端。++## 从源码构建++需要 Go 1.26、Flutter 3.44 和 Xcode。++```bash+./scripts/build.sh # 构建全部到 dist/+./scripts/package.sh # 打出 DMG 与服务器发布包到 release/+```++开发时可以单独运行各部分:++```bash+cd client-core && go test ./... # 后台服务的测试+cd ui && flutter test # 界面的测试+./scripts/install-macos.sh # 把 dist/ 里的后台服务装成登录项+./dist/copysync-cli status # 查看后台服务状态+./dist/copysync-cli watch # 实时事件流+```++改了 `.proto` 之后运行 `./scripts/gen-proto.sh` 重新生成代码(用 buf,`go install` 即可安装,无需 protoc)。改了界面之后运行 `./tools/screenshots/render.sh` 重新生成截图,截图用演示数据渲染,不会带出本机的真实内容。++```+client-core/ 后台服务(Go)+ internal/clipboard 剪贴板(cgo + Objective-C,必须跑在主线程)+ internal/transport 信令(WebSocket)与 P2P(WebRTC)+ internal/sync 同步引擎:分流、打包、传输、落盘+ui/ 界面(Flutter)+server/ 信令 + TURN 中转服务器(Go),部署文件在 server/deploy/+proto/ 消息定义与设备 ID 派生规则,三方共用+docs/ 项目主页(GitHub Pages)+spikes/ 开工前的技术验证+```++## 排障++**剪贴板读不到内容,`pbpaste` 也是空的**+系统的剪贴板服务可能卡住了:某个程序声明了剪贴板内容后异常退出,会留下一个"有类型声明、没有数据"的空壳。执行 `killall pboard`,再复制一次即可。++**设备一直显示「离线」**+检查两台 Mac 的 **设置 → 连接状态** 是否都是「已连接」。不是的话,确认服务器地址正确、8787 端口可以访问。++**一直显示「中转」而不是「直连」**+NAT 打洞没成功,常见于对称 NAT 或严格的防火墙。功能不受影响,只是速度受服务器带宽限制。++**查看日志**+后台服务的日志在 `~/Library/Logs/CopySync/daemon.log`,服务器的日志用 `journalctl -u copysync-server -f` 查看。++## 许可++[MIT](LICENSE)diff --git a/assets/brand/AppIcon.icns b/assets/brand/AppIcon.icnsnew file mode 100644index 0000000..f96c847Binary files /dev/null and b/assets/brand/AppIcon.icns differdiff --git a/assets/brand/favicon.svg b/assets/brand/favicon.svgnew file mode 100644index 0000000..47e1bac--- /dev/null+++ b/assets/brand/favicon.svg@@ -0,0 +1,16 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="100 100 824 824">+ <!-- 浏览器标签页里尺寸很小:裁掉图标网格的留白与投影,只保留主体 -->+ <rect x="100" y="100" width="824" height="824" rx="184" fill="#F2F2F1"/>+ <rect x="230" y="220" width="340" height="420" rx="44" fill="#F5F5F4" stroke="#2C2C2E" stroke-width="32"/>+ <g fill="#2C2C2E">+ <rect x="290" y="310" width="200" height="36" rx="18"/>+ <rect x="290" y="390" width="150" height="36" rx="18"/>+ <rect x="290" y="470" width="104" height="36" rx="18"/>+ </g>+ <rect x="454" y="384" width="340" height="420" rx="44" fill="#0A66D8"/>+ <g fill="#FFFFFF">+ <rect x="514" y="474" width="200" height="36" rx="18"/>+ <rect x="514" y="554" width="150" height="36" rx="18"/>+ <rect x="514" y="634" width="104" height="36" rx="18"/>+ </g>+</svg>diff --git a/assets/brand/icon-1024.png b/assets/brand/icon-1024.pngnew file mode 100644index 0000000..d2f4ba2Binary files /dev/null and b/assets/brand/icon-1024.png differdiff --git a/assets/brand/icon.svg b/assets/brand/icon.svgnew file mode 100644index 0000000..67f31c8--- /dev/null+++ b/assets/brand/icon.svg@@ -0,0 +1,28 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" role="img" aria-label="CopySync">+ <!-- 几何与 tools/icon/render.swift 一一对应,改动时两边同步 -->+ <defs>+ <linearGradient id="body" x1="0" y1="100" x2="0" y2="924" gradientUnits="userSpaceOnUse">+ <stop offset="0" stop-color="#FBFBFA"/>+ <stop offset="1" stop-color="#E8E8E6"/>+ </linearGradient>+ <filter id="bodyShadow" x="-20%" y="-20%" width="140%" height="140%">+ <feDropShadow dx="0" dy="12" stdDeviation="14" flood-color="#000" flood-opacity="0.28"/>+ </filter>+ <filter id="sheetShadow" x="-20%" y="-20%" width="140%" height="140%">+ <feDropShadow dx="0" dy="10" stdDeviation="12" flood-color="#000" flood-opacity="0.22"/>+ </filter>+ </defs>+ <rect x="100" y="100" width="824" height="824" rx="184" fill="url(#body)" filter="url(#bodyShadow)"/>+ <rect x="230" y="220" width="340" height="420" rx="44" fill="#F5F5F4" stroke="#2C2C2E" stroke-width="28"/>+ <g fill="#2C2C2E" fill-opacity="0.85">+ <rect x="290" y="310" width="200" height="30" rx="15"/>+ <rect x="290" y="390" width="150" height="30" rx="15"/>+ <rect x="290" y="470" width="104" height="30" rx="15"/>+ </g>+ <rect x="454" y="384" width="340" height="420" rx="44" fill="#0A66D8" filter="url(#sheetShadow)"/>+ <g fill="#FFFFFF" fill-opacity="0.95">+ <rect x="514" y="474" width="200" height="30" rx="15"/>+ <rect x="514" y="554" width="150" height="30" rx="15"/>+ <rect x="514" y="634" width="104" height="30" rx="15"/>+ </g>+</svg>diff --git a/buf.gen.yaml b/buf.gen.yamlnew file mode 100644index 0000000..b78eb76--- /dev/null+++ b/buf.gen.yaml@@ -0,0 +1,23 @@+# 代码生成配置。+#+# 用 buf 而非 protoc:这台机器访问不到 GitHub releases(下载预编译 protoc 超时),+# 而 Homebrew 在 Intel Mac 上没有 protobuf 的预编译包、要从源码编译十几分钟。+# buf 是纯 Go 实现,可经 goproxy.cn 用 go install 装上,且自带 protobuf 编译器。+#+# 生成:./scripts/gen-proto.sh++version: v2++plugins:+ - local: protoc-gen-go+ out: proto/gen+ opt: paths=source_relative++ - local: protoc-gen-go-grpc+ out: proto/gen+ opt: paths=source_relative++ # Flutter UI 侧。grpc 选项让插件同时产出 service stub。+ - local: protoc-gen-dart+ out: ui/lib/gen+ opt: grpcdiff --git a/client-core/cmd/copysync-cli/main.go b/client-core/cmd/copysync-cli/main.gonew file mode 100644index 0000000..eaecbec--- /dev/null+++ b/client-core/cmd/copysync-cli/main.go@@ -0,0 +1,382 @@+// copysync-cli 是开发调试用的命令行客户端。+//+// 它走与 Flutter UI 完全相同的 gRPC 接口,因此既能在 UI 就绪前验证 daemon,+// 也能在之后用来区分「是 daemon 的问题还是 UI 的问题」。+//+// copysync-cli status 查看 daemon 状态+// copysync-cli watch 订阅事件流+// copysync-cli history 列出历史记录+// copysync-cli config 查看配置+package main++import (+ "context"+ "errors"+ "flag"+ "fmt"+ "io"+ "os"+ "path/filepath"+ "time"++ "google.golang.org/grpc"+ "google.golang.org/grpc/credentials/insecure"+ "google.golang.org/grpc/metadata"++ "github.com/baiyuze/copysync/client-core/internal/config"+ "github.com/baiyuze/copysync/client-core/internal/rpc"+ pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"+)++func main() {+ dataDir := flag.String("data-dir", "", "数据目录(默认为系统标准位置)")+ flag.Parse()++ cmd := flag.Arg(0)+ if cmd == "" {+ fmt.Fprintln(os.Stderr,+ "用法: copysync-cli [-data-dir DIR] <status|watch|history|config|devices|pair|join CODE>")+ os.Exit(2)+ }++ if err := run(cmd, *dataDir); err != nil {+ fmt.Fprintln(os.Stderr, "错误:", err)+ os.Exit(1)+ }+}++func run(cmd, dataDir string) error {+ paths, err := resolvePaths(dataDir)+ if err != nil {+ return err+ }++ ep, err := rpc.ReadEndpoint(paths.Endpoint)+ if err != nil {+ if os.IsNotExist(err) {+ return fmt.Errorf("daemon 未运行(找不到 %s)", paths.Endpoint)+ }+ return err+ }++ conn, err := grpc.NewClient(fmt.Sprintf("127.0.0.1:%d", ep.Port),+ grpc.WithTransportCredentials(insecure.NewCredentials()))+ if err != nil {+ return fmt.Errorf("连接 daemon: %w", err)+ }+ defer conn.Close()++ client := pb.NewDaemonServiceClient(conn)+ // token 随每次调用发送,daemon 侧用常数时间比较校验+ ctx := metadata.AppendToOutgoingContext(context.Background(), "x-copysync-token", ep.Token)++ switch cmd {+ case "status":+ return showStatus(ctx, client, ep)+ case "watch":+ return watch(ctx, client)+ case "history":+ return showHistory(ctx, client)+ case "config":+ return showConfig(ctx, client)+ case "devices":+ return showDevices(ctx, client)+ case "pair":+ return createPairing(ctx, client)+ case "join":+ return joinPairing(ctx, client, flag.Arg(1))+ default:+ return fmt.Errorf("未知命令 %q", cmd)+ }+}++func showDevices(ctx context.Context, c pb.DaemonServiceClient) error {+ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)+ defer cancel()++ resp, err := c.ListDevices(ctx, &pb.Empty{})+ if err != nil {+ return err+ }+ self := resp.GetSelf()+ fmt.Printf("本机 %s %s\n", self.GetName(), self.GetPublicKeyFingerprint())+ fmt.Printf(" %s\n\n", self.GetId())++ if len(resp.GetPeers()) == 0 {+ fmt.Println("(尚未配对任何设备,用 pair / join 建立配对)")+ return nil+ }+ for _, p := range resp.GetPeers() {+ fmt.Printf("%-16s %-10s %-8s %s\n",+ p.GetName(), p.GetPlatform(),+ connectionLabel(p), p.GetPublicKeyFingerprint())+ }+ return nil+}++// connectionLabel 区分直连与中转,便于排查网络问题:+// 一直显示「中转」说明 NAT 打洞没成功,走的是服务器带宽。+func connectionLabel(d *pb.Device) string {+ if !d.GetOnline() {+ return "离线"+ }+ switch d.GetConnection() {+ case pb.ConnectionKind_CONNECTION_KIND_DIRECT:+ return "直连"+ case pb.ConnectionKind_CONNECTION_KIND_RELAY:+ return "中转"+ default:+ return "在线"+ }+}++// createPairing 生成配对码并等待对方兑换。+func createPairing(ctx context.Context, c pb.DaemonServiceClient) error {+ // 先订阅事件流,才能在对方兑换后收到设备变化通知+ streamCtx, cancel := context.WithCancel(ctx)+ defer cancel()+ stream, err := c.Subscribe(streamCtx, &pb.SubscribeRequest{})+ if err != nil {+ return err+ }++ createCtx, createCancel := context.WithTimeout(ctx, 15*time.Second)+ resp, err := c.CreatePairingCode(createCtx, &pb.Empty{})+ createCancel()+ if err != nil {+ return err+ }++ fmt.Printf("\n 配对码:%s\n", resp.GetCode())+ fmt.Printf(" 有效期至 %s\n\n",+ time.Unix(resp.GetExpiresAtUnix(), 0).Format("15:04:05"))+ fmt.Println(" 在另一台设备上运行:copysync-cli join " + resp.GetCode())+ fmt.Println(" 等待对方兑换…(Ctrl+C 取消)")++ for {+ ev, err := stream.Recv()+ if err != nil {+ return err+ }+ d := ev.GetDeviceChanged()+ if d == nil || d.GetPairingSession() == "" {+ continue // 非待确认的配对事件(普通的在线状态变化)+ }+ fmt.Printf("\n 对方已兑换:%s(%s)\n", d.GetName(), d.GetPlatform())+ fmt.Printf(" 指纹:%s\n\n", d.GetPublicKeyFingerprint())+ fmt.Println(" ⚠️ 请与对方屏幕上的指纹逐字核对,一致才继续。")+ fmt.Print(" 确认配对?[y/N] ")++ var answer string+ fmt.Scanln(&answer)+ accept := answer == "y" || answer == "Y"++ confirmCtx, confirmCancel := context.WithTimeout(ctx, 10*time.Second)+ _, confirmErr := c.ConfirmPairing(confirmCtx, &pb.ConfirmPairingRequest{+ PairingSession: d.GetPairingSession(),+ Accept: accept,+ })+ confirmCancel()+ if confirmErr != nil {+ return confirmErr+ }+ if accept {+ fmt.Println("\n ✓ 配对成功")+ } else {+ fmt.Println("\n 已取消")+ }+ return nil+ }+}++func joinPairing(ctx context.Context, c pb.DaemonServiceClient, code string) error {+ if code == "" {+ return errors.New("用法: copysync-cli join <配对码>")+ }+ ctx, cancel := context.WithTimeout(ctx, 20*time.Second)+ defer cancel()++ resp, err := c.RedeemPairingCode(ctx, &pb.RedeemPairingCodeRequest{Code: code})+ if err != nil {+ return err+ }+ peer := resp.GetPeer()+ fmt.Printf("\n 找到设备:%s(%s)\n", peer.GetName(), peer.GetPlatform())+ fmt.Printf(" 指纹:%s\n\n", peer.GetPublicKeyFingerprint())+ fmt.Println(" ⚠️ 请与对方屏幕上的指纹逐字核对,一致才继续。")+ fmt.Print(" 确认配对?[y/N] ")++ var answer string+ fmt.Scanln(&answer)+ accept := answer == "y" || answer == "Y"++ if _, err := c.ConfirmPairing(ctx, &pb.ConfirmPairingRequest{+ PairingSession: resp.GetPairingSession(),+ Accept: accept,+ }); err != nil {+ return err+ }+ if accept {+ fmt.Println("\n ✓ 配对成功")+ } else {+ fmt.Println("\n 已取消")+ }+ return nil+}++func resolvePaths(dataDir string) (config.Paths, error) {+ if dataDir != "" {+ abs, err := filepath.Abs(dataDir)+ if err != nil {+ return config.Paths{}, err+ }+ return config.PathsUnder(abs), nil+ }+ return config.DefaultPaths()+}++func showStatus(ctx context.Context, c pb.DaemonServiceClient, ep rpc.Endpoint) error {+ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)+ defer cancel()++ st, err := c.GetStatus(ctx, &pb.Empty{})+ if err != nil {+ return err+ }+ fmt.Printf("daemon PID %d 端口 %d 版本 %s\n", ep.PID, ep.Port, st.GetVersion())+ fmt.Printf("设备 %s\n", st.GetDeviceName())+ fmt.Printf("设备 ID %s\n", st.GetDeviceId())+ fmt.Printf("信令 %s\n", boolText(st.GetSignalingConnected(), "已连接", "未连接"))+ fmt.Printf("在线对端 %d\n", st.GetPeersOnline())+ fmt.Printf("剪贴板授权 %s\n", st.GetClipboardPermission())+ fmt.Printf("缓存占用 %s\n", humanBytes(st.GetCacheBytesUsed()))+ return nil+}++func watch(ctx context.Context, c pb.DaemonServiceClient) error {+ stream, err := c.Subscribe(ctx, &pb.SubscribeRequest{})+ if err != nil {+ return err+ }+ fmt.Println("已订阅事件流,Ctrl+C 退出")+ for {+ ev, err := stream.Recv()+ if errors.Is(err, io.EOF) {+ fmt.Println("流已结束")+ return nil+ }+ if err != nil {+ return err+ }+ printEvent(ev)+ }+}++func printEvent(ev *pb.Event) {+ ts := time.Now().Format("15:04:05")+ switch p := ev.GetPayload().(type) {+ case *pb.Event_ClipAdded:+ r := p.ClipAdded+ fmt.Printf("[%s] + 新记录 %s %s %s %q\n", ts,+ r.GetKind(), r.GetStatus(), humanBytes(r.GetTotalSize()), r.GetTextPreview())+ case *pb.Event_ClipUpdated:+ r := p.ClipUpdated+ fmt.Printf("[%s] ~ 更新 %s %s\n", ts, r.GetId(), r.GetStatus())+ case *pb.Event_ClipRemoved:+ fmt.Printf("[%s] - 删除 %s\n", ts, p.ClipRemoved)+ case *pb.Event_Progress:+ pr := p.Progress+ fmt.Printf("[%s] ↓ 进度 %s %s/%s\n", ts, pr.GetClipId(),+ humanBytes(pr.GetTransferred()), humanBytes(pr.GetTotal()))+ case *pb.Event_DeviceChanged:+ d := p.DeviceChanged+ fmt.Printf("[%s] ⇄ 设备 %s %s %s\n", ts,+ d.GetName(), boolText(d.GetOnline(), "在线", "离线"), d.GetConnection())+ case *pb.Event_PermissionChanged:+ fmt.Printf("[%s] ! 授权 %s\n", ts, p.PermissionChanged)+ case *pb.Event_StatusChanged:+ s := p.StatusChanged+ fmt.Printf("[%s] i 状态 信令=%v 对端=%d 授权=%s\n", ts,+ s.GetSignalingConnected(), s.GetPeersOnline(), s.GetClipboardPermission())+ default:+ fmt.Printf("[%s] ? 未知事件 %T\n", ts, p)+ }+}++func showHistory(ctx context.Context, c pb.DaemonServiceClient) error {+ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)+ defer cancel()++ resp, err := c.ListHistory(ctx, &pb.ListHistoryRequest{Limit: 20})+ if err != nil {+ return err+ }+ if len(resp.GetRecords()) == 0 {+ fmt.Println("(暂无记录)")+ return nil+ }+ for _, r := range resp.GetRecords() {+ dir := "←收到"+ if r.GetOutgoing() {+ dir = "→本机"+ }+ fmt.Printf("%s %s %-6s %-14s %8s %s\n",+ time.Unix(r.GetCreatedAtUnix(), 0).Format("01-02 15:04:05"),+ dir, r.GetKind(), r.GetStatus(),+ humanBytes(r.GetTotalSize()), preview(r))+ }+ return nil+}++func preview(r *pb.ClipRecord) string {+ if t := r.GetTextPreview(); t != "" {+ return fmt.Sprintf("%q", t)+ }+ switch n := len(r.GetItems()); n {+ case 0:+ return ""+ case 1:+ return r.GetItems()[0].GetName()+ default:+ return fmt.Sprintf("%s 等 %d 项", r.GetItems()[0].GetName(), n)+ }+}++func showConfig(ctx context.Context, c pb.DaemonServiceClient) error {+ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)+ defer cancel()++ cfg, err := c.GetConfig(ctx, &pb.Empty{})+ if err != nil {+ return err+ }+ fmt.Printf("设备名称 %s\n", cfg.GetDeviceName())+ fmt.Printf("信令地址 %s\n", cfg.GetSignalingUrl())+ fmt.Printf("自动同步阈值 %s\n", humanBytes(cfg.GetAutoSyncThresholdBytes()))+ fmt.Printf("历史保留 %s\n", time.Duration(cfg.GetHistoryTtlSeconds())*time.Second)+ fmt.Printf("缓存保留 %s\n", time.Duration(cfg.GetCacheTtlSeconds())*time.Second)+ fmt.Printf("同步类型 文本=%v HTML=%v 图片=%v 文件=%v\n",+ cfg.GetSyncText(), cfg.GetSyncHtml(), cfg.GetSyncImage(), cfg.GetSyncFile())+ fmt.Printf("自动写剪贴板 %v\n", cfg.GetAutoApplyToClipboard())+ return nil+}++func boolText(b bool, yes, no string) string {+ if b {+ return yes+ }+ return no+}++func humanBytes(n int64) string {+ const unit = 1024+ if n < unit {+ return fmt.Sprintf("%d B", n)+ }+ div, exp := int64(unit), 0+ for v := n / unit; v >= unit; v /= unit {+ div *= unit+ exp+++ }+ return fmt.Sprintf("%.1f %ciB", float64(n)/float64(div), "KMGTPE"[exp])+}diff --git a/client-core/cmd/copysyncd/main.go b/client-core/cmd/copysyncd/main.gonew file mode 100644index 0000000..3193866--- /dev/null+++ b/client-core/cmd/copysyncd/main.go@@ -0,0 +1,374 @@+// copysyncd 是 CopySync 的常驻后台进程,承载全部核心逻辑:+// 剪贴板监听、设备配对、P2P 传输、本地缓存与回收。+//+// Flutter UI 只是控制台——关掉 UI 不影响后台同步。UI 通过+// 本地 gRPC(127.0.0.1 随机端口 + 一次性 token)连接本进程。+package main++import (+ "context"+ "flag"+ "fmt"+ "log/slog"+ "os"+ "os/signal"+ "path/filepath"+ "runtime"+ "sync"+ "syscall"+ "time"++ "github.com/baiyuze/copysync/client-core/internal/cache"+ "github.com/baiyuze/copysync/client-core/internal/clipboard"+ "github.com/baiyuze/copysync/client-core/internal/config"+ "github.com/baiyuze/copysync/client-core/internal/gc"+ "github.com/baiyuze/copysync/client-core/internal/identity"+ "github.com/baiyuze/copysync/client-core/internal/peers"+ "github.com/baiyuze/copysync/client-core/internal/rpc"+ "github.com/baiyuze/copysync/client-core/internal/store"+ syncengine "github.com/baiyuze/copysync/client-core/internal/sync"+ "github.com/baiyuze/copysync/client-core/internal/transport/p2p"+ pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"+)++var version = "0.1.0-dev"++func main() {+ // 必须在任何其他 goroutine 启动前锁定主线程。+ //+ // macOS 的剪贴板 API 在隐私机制开启时会经 ViewBridge 与系统 UI 服务通信,+ // 其内部 NSCFRunLoopSemaphore 依赖 run loop;在非主线程调用会直接+ // SIGSEGV(M-1 实测,见 spikes/results.md)。所以主线程被专门留出来+ // 跑 MainLoop,业务逻辑一律在其他 goroutine 里,通过 Post/Call 投递。+ runtime.LockOSThread()++ var (+ dataDir = flag.String("data-dir", "", "数据目录(默认为系统标准位置)")+ verbose = flag.Bool("v", false, "输出调试日志")+ probe = flag.Bool("probe-clipboard", false,+ "诊断用:在主线程直接读一次剪贴板并打印结果后退出")+ )+ flag.Parse()++ level := slog.LevelInfo+ if *verbose {+ level = slog.LevelDebug+ }+ slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: level})))++ if *probe {+ probeClipboard()+ return+ }++ if err := run(*dataDir); err != nil {+ slog.Error("daemon 退出", "err", err)+ os.Exit(1)+ }+}++// probeClipboard 在主线程直接走一遍探测与读取,用来把剪贴板问题+// 与 daemon 的其余部分隔离开。+func probeClipboard() {+ clipboard.InitPlatform()+ cb := clipboard.New()++ fmt.Println("授权状态:", cb.Permission())++ snap, err := cb.Peek()+ if err != nil {+ fmt.Println("Peek 失败:", err)+ return+ }+ fmt.Printf("changeCount: %d\n分类: %v\ncontentType: %q\ntypes: %v\n",+ snap.ChangeCount, snap.Kind, snap.ContentType, snap.Types)++ content, err := cb.Read()+ if err != nil {+ fmt.Println("Read 失败:", err)+ return+ }+ fmt.Printf("读取结果: kind=%v 文本=%d字符 HTML=%d字符 图片=%d字节 文件=%v\n",+ content.Kind, len([]rune(content.Text)), len(content.HTML),+ len(content.Image), content.Files)+ if content.Text != "" {+ fmt.Printf("文本内容: %q\n", content.Text)+ }+}++func run(dataDir string) error {+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)+ defer stop()++ // ── 路径与配置 ──+ paths, err := resolvePaths(dataDir)+ if err != nil {+ return err+ }+ if err := paths.EnsureDirs(); err != nil {+ return err+ }+ cfg, err := config.Load(paths)+ if err != nil {+ return err+ }++ // ── 设备身份 ──+ id, err := identity.LoadOrCreate(filepath.Join(paths.Root, "identity.json"))+ if err != nil {+ return err+ }+ if cfg.DeviceID != id.DeviceID {+ cfg.DeviceID = id.DeviceID+ if err := config.Save(paths, cfg); err != nil {+ return err+ }+ }+ slog.Info("设备身份就绪",+ "device_id", id.DeviceID, "name", cfg.DeviceName, "fingerprint", id.Fingerprint())++ // ── 存储与缓存 ──+ db, err := store.Open(paths.DB)+ if err != nil {+ return err+ }+ defer db.Close()++ blobs, err := cache.New(paths.Cache)+ if err != nil {+ return err+ }+ // 上次异常退出可能留下半截的临时文件+ if err := blobs.CleanTemp(); err != nil {+ slog.Debug("清理临时文件失败", "err", err)+ }++ // ── 配置的并发安全读写 ──+ var cfgMu sync.RWMutex+ loadCfg := func() config.Config {+ cfgMu.RLock()+ defer cfgMu.RUnlock()+ return cfg+ }+ saveCfg := func(c config.Config) error {+ cfgMu.Lock()+ defer cfgMu.Unlock()+ if err := config.Save(paths, c); err != nil {+ return err+ }+ cfg = c+ return nil+ }++ hub := rpc.NewHub()++ // ── 剪贴板(必须在主线程使用)──+ clipboard.InitPlatform()+ loop := clipboard.NewMainLoop()+ watcher := clipboard.NewWatcher(clipboard.WatcherOptions{+ Clipboard: clipboard.New(),+ MainLoop: loop,+ OnPermission: func(p clipboard.Permission) {+ hub.Publish(rpc.EventPermissionChanged(permissionToProto(p)))+ },+ })++ // ── 设备配对与信令(引擎稍后注入)──+ var engine *syncengine.Engine++ // 状态快照要由 gRPC 服务组装,而它晚于 peerMgr 创建,这里先记下"状态变了",+ // 等服务就绪后统一推送。容量 1 让连续的变化合并成一次刷新。+ statusDirty := make(chan struct{}, 1)++ peerMgr, err := peers.NewManager(peers.Options{+ Identity: id,+ Store: db,+ LoadConfig: loadCfg,+ OnDeviceChanged: func(d *pb.Device) {+ hub.Publish(rpc.EventDeviceChanged(d))+ },+ OnStatusChanged: func() {+ select {+ case statusDirty <- struct{}{}:+ default:+ }+ },+ OnPeerMessage: func(deviceID string, msg *pb.PeerMessage) {+ if engine != nil {+ engine.HandlePeerMessage(ctx, deviceID, msg)+ }+ },+ OnPeerStream: func(deviceID, label string, stream *p2p.Stream) {+ if engine != nil {+ engine.HandlePeerStream(deviceID, label, stream)+ }+ },+ })+ if err != nil {+ return err+ }++ // ── 同步引擎 ──+ engine = syncengine.New(syncengine.Options{+ Store: db,+ Cache: blobs,+ Watcher: watcher,+ DeviceID: id.DeviceID,+ DeviceName: func() string { return loadCfg().DeviceName },+ LoadConfig: loadCfg,+ Send: peerMgr.P2P().Send,+ Broadcast: peerMgr.P2P().Broadcast,+ OpenStream: peerMgr.P2P().OpenStream,+ OnlinePeers: func() []string {+ _, list := peerMgr.Devices()+ var online []string+ for _, d := range list {+ if d.GetOnline() {+ online = append(online, d.GetId())+ }+ }+ return online+ },+ OnRecord: func(r *pb.ClipRecord) {+ hub.Publish(rpc.EventClipAdded(r))+ },+ OnProgress: func(p *pb.TransferProgress) {+ hub.Publish(rpc.EventProgress(p))+ },+ })++ // 剪贴板变化在独立 goroutine 里处理:读内容可能耗时,+ // 不能拖住轮询循环,更不能占着主线程。+ watcher.SetOnChange(func(snap clipboard.Snapshot) {+ go engine.HandleClipboardChange(ctx, snap)+ })++ go peerMgr.Run(ctx)+ go watcher.Run(ctx)++ // ── 过期回收 ──+ collector := gc.New(gc.Options{+ Store: db,+ Cache: blobs,+ LoadConfig: loadCfg,+ OnRemoved: func(ids []string) {+ for _, cid := range ids {+ hub.Publish(rpc.EventClipRemoved(cid))+ }+ },+ })+ go collector.Run(ctx)++ // 改了服务器地址要立即重连,否则用户得重启 daemon 才生效+ saveCfgAndApply := func(c config.Config) error {+ prev := loadCfg()+ if err := saveCfg(c); err != nil {+ return err+ }+ if c.SignalingURL != prev.SignalingURL {+ slog.Info("信令服务器地址已变更", "from", prev.SignalingURL, "to", c.SignalingURL)+ peerMgr.SetSignalingURL(c.SignalingURL)+ }+ return nil+ }++ // ── gRPC 服务 ──+ token, err := rpc.NewToken()+ if err != nil {+ return err+ }+ srv := rpc.NewServer(rpc.Deps{+ Store: db,+ Paths: paths,+ Version: version,+ DeviceID: id.DeviceID,+ LoadConfig: loadCfg,+ SaveConfig: saveCfgAndApply,+ Devices: peerMgr.Devices,+ CreatePairingCode: peerMgr.CreatePairingCode,+ RedeemPairingCode: peerMgr.RedeemPairingCode,+ ConfirmPairing: peerMgr.ConfirmPairing,+ Unpair: peerMgr.Unpair,+ SignalingConnected: peerMgr.Connected,+ Fetch: engine.Fetch,+ ApplyToClipboard: engine.ApplyToClipboard,+ CacheBytesUsed: blobs.Size,+ Permission: func() clipboard.Permission {+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)+ defer cancel()+ return watcher.Permission(ctx)+ },+ OpenPermissionSettings: func() error {+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ return watcher.OpenPermissionSettings(ctx)+ },+ }, hub, token)++ // 信令连接与在线对端数的变化推给 UI。Subscribe 只在建立订阅时推一次状态,+ // 没有这里的话,UI 会一直停留在它打开那一刻的连接状态。+ go func() {+ for {+ select {+ case <-ctx.Done():+ return+ case <-statusDirty:+ if st, err := srv.GetStatus(ctx, &pb.Empty{}); err == nil {+ hub.Publish(rpc.EventStatusChanged(st))+ }+ }+ }+ }()++ port, grpcServer, err := srv.Serve(ctx)+ if err != nil {+ return err+ }+ defer grpcServer.GracefulStop()++ // UI 靠这个文件发现 daemon+ if err := rpc.WriteEndpoint(paths.Endpoint, rpc.Endpoint{+ Port: port, Token: token, PID: os.Getpid(), Version: version,+ }); err != nil {+ return err+ }+ defer rpc.RemoveEndpoint(paths.Endpoint)++ slog.Info("daemon 已就绪",+ "port", port, "endpoint", paths.Endpoint, "cache", paths.Cache)++ // ── 主线程交给 MainLoop ──+ // 剪贴板相关的一切都在这条线程上执行,同时驱动 macOS run loop。+ loop.Run(ctx)++ slog.Info("正在退出")+ return nil+}++func resolvePaths(dataDir string) (config.Paths, error) {+ if dataDir != "" {+ abs, err := filepath.Abs(dataDir)+ if err != nil {+ return config.Paths{}, err+ }+ return config.PathsUnder(abs), nil+ }+ return config.DefaultPaths()+}++func permissionToProto(p clipboard.Permission) pb.ClipboardPermission {+ switch p {+ case clipboard.PermissionNotApplicable:+ return pb.ClipboardPermission_CLIPBOARD_PERMISSION_NOT_APPLICABLE+ case clipboard.PermissionDefault:+ return pb.ClipboardPermission_CLIPBOARD_PERMISSION_DEFAULT+ case clipboard.PermissionAsk:+ return pb.ClipboardPermission_CLIPBOARD_PERMISSION_ASK+ case clipboard.PermissionAlwaysAllow:+ return pb.ClipboardPermission_CLIPBOARD_PERMISSION_ALWAYS_ALLOW+ case clipboard.PermissionAlwaysDeny:+ return pb.ClipboardPermission_CLIPBOARD_PERMISSION_ALWAYS_DENY+ default:+ return pb.ClipboardPermission_CLIPBOARD_PERMISSION_UNSPECIFIED+ }+}diff --git a/client-core/go.mod b/client-core/go.modnew file mode 100644index 0000000..959514f--- /dev/null+++ b/client-core/go.mod@@ -0,0 +1,58 @@+module github.com/baiyuze/copysync/client-core++go 1.26.3++require modernc.org/sqlite v1.59.0++require (+ github.com/dustin/go-humanize v1.0.1 // indirect+ github.com/google/uuid v1.6.0 // indirect+ github.com/mattn/go-isatty v0.0.24 // indirect+ github.com/ncruces/go-strftime v1.0.0 // indirect+ github.com/pion/datachannel v1.6.2 // indirect+ github.com/pion/dtls/v3 v3.1.8 // indirect+ github.com/pion/ice/v4 v4.4.2 // indirect+ github.com/pion/interceptor v0.1.48 // indirect+ github.com/pion/logging v0.2.4 // indirect+ github.com/pion/mdns/v2 v2.2.0 // indirect+ github.com/pion/randutil v0.1.0 // indirect+ github.com/pion/rtcp v1.2.17 // indirect+ github.com/pion/rtp v1.10.5 // indirect+ github.com/pion/sctp v1.11.1 // indirect+ github.com/pion/sdp/v3 v3.0.19 // indirect+ github.com/pion/srtp/v3 v3.0.13 // indirect+ github.com/pion/stun/v3 v3.0.1 // indirect+ github.com/pion/stun/v4 v4.0.0 // indirect+ github.com/pion/transport/v3 v3.0.8 // indirect+ github.com/pion/transport/v4 v4.1.0 // indirect+ github.com/pion/turn/v4 v4.1.4 // indirect+ github.com/pion/turn/v5 v5.1.0 // indirect+ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect+ github.com/wlynxg/anet v0.0.5 // indirect+ golang.org/x/crypto v0.54.0 // indirect+ golang.org/x/sys v0.47.0 // indirect+ golang.org/x/text v0.40.0 // indirect+ golang.org/x/time v0.14.0 // indirect+ google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800 // indirect+ modernc.org/libc v1.75.7 // indirect+ modernc.org/mathutil v1.7.1 // indirect+ modernc.org/memory v1.12.1 // indirect+)++require (+ github.com/baiyuze/copysync/proto v0.0.0+ github.com/coder/websocket v1.8.15+ google.golang.org/grpc v1.84.0+ google.golang.org/protobuf v1.36.12+)++replace github.com/baiyuze/copysync/proto => ../proto++require (+ github.com/baiyuze/copysync/server v0.0.0+ github.com/klauspost/compress v1.20.0+ github.com/pion/webrtc/v4 v4.2.20+ golang.org/x/net v0.57.0+)++replace github.com/baiyuze/copysync/server => ../serverdiff --git a/client-core/go.sum b/client-core/go.sumnew file mode 100644index 0000000..f04b13d--- /dev/null+++ b/client-core/go.sum@@ -0,0 +1,118 @@+github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=+github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=+github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=+github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=+github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=+github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=+github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=+github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=+github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=+github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=+github.com/klauspost/compress v1.20.0 h1:a3C1ke2ohxFymNlb2HWAHjDeKCI90scRskErZkR0ezA=+github.com/klauspost/compress v1.20.0/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=+github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=+github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=+github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=+github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=+github.com/pion/datachannel v1.6.2 h1:7EXQ8TH3vTouBUdRWYbcX2edSx9Yj6k5zl5P+qyxEPc=+github.com/pion/datachannel v1.6.2/go.mod h1:pzbdAZvyGtXbcHM1hBbsFaOTf40lZizU/dNlvVOak6E=+github.com/pion/dtls/v3 v3.1.8 h1:aLcgjZqzrYn5AbjSds4LvK2WI5VzJc1PencExyDjYis=+github.com/pion/dtls/v3 v3.1.8/go.mod h1:gz1K4jg6c+fq86oQMH4pilpCEOEPwmEr2jY+VcF/mkU=+github.com/pion/ice/v4 v4.4.2 h1:asS17nbHJrzlVQl8fiSJaipxrxSY3Dq6DWgmB+0VwpI=+github.com/pion/ice/v4 v4.4.2/go.mod h1:YZgNFOyJWXpLpLj0mb4ccqNAWRo9C2RtqKwuVTEz0Sc=+github.com/pion/interceptor v0.1.48 h1:FF4gZ6Yh+N75gKMYpC7rYR8DdkiMBFtA7V2OBUKo7XQ=+github.com/pion/interceptor v0.1.48/go.mod h1:5mg/N5xXMAa4codCUdrJYY9I1y4tVQhlpd7rfwAJpvI=+github.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8=+github.com/pion/logging v0.2.4/go.mod h1:DffhXTKYdNZU+KtJ5pyQDjvOAh/GsNSyv1lbkFbe3so=+github.com/pion/mdns/v2 v2.2.0 h1:AlAZ9MTUKtWgO+4itk35JdNak4sk5k7G/X4xnIBWHyA=+github.com/pion/mdns/v2 v2.2.0/go.mod h1:IJddx58QMlojqhQYjHcOUmvuBQ5MnLNetkb80VMvk2Y=+github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=+github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=+github.com/pion/rtcp v1.2.17 h1:PxiT6L79yPZKtXIsXdG1eakBl6dtBj4x+4oVEL0DlSw=+github.com/pion/rtcp v1.2.17/go.mod h1:7kBpuBJaWwax4hzc/pgexY8vkOpvh8atgYDbaKZq0iU=+github.com/pion/rtp v1.10.5 h1:ip0HhO/wYZqQ4bKS+R99KnZh/GRCmIT0jDXikub7vlE=+github.com/pion/rtp v1.10.5/go.mod h1:Au8fc6cEByy8RLTwKTQTEeQqDB/SJDxwL4mZuxYA5Pk=+github.com/pion/sctp v1.11.1 h1:O4dIFyURw1KTST7w+gtD4gLeYXkhPa0xXLHMMoe/OSA=+github.com/pion/sctp v1.11.1/go.mod h1:7KFmTwLcoYgJs/Z+99nJvsWL0qDpuyloSI0RbAqlrz0=+github.com/pion/sdp/v3 v3.0.19 h1:1VMKs3gIkTQV5M3hNKfTAPrDXSNrYtOlmOD8+mSZUGQ=+github.com/pion/sdp/v3 v3.0.19/go.mod h1:dE5WOSlzXrtiE/iuZqe9n+AcEbOjtAd3k5m5NtlV/qU=+github.com/pion/srtp/v3 v3.0.13 h1:FmQaqgNbN1vUtMhEsmj8trldc3lNZr1xmN7nl8CyX+Q=+github.com/pion/srtp/v3 v3.0.13/go.mod h1:7qR3L69t8RX0EPVQwGNwCa1Gy9keKKNDpWwQzZbeXDY=+github.com/pion/stun/v3 v3.0.1 h1:jx1uUq6BdPihF0yF33Jj2mh+C9p0atY94IkdnW174kA=+github.com/pion/stun/v3 v3.0.1/go.mod h1:RHnvlKFg+qHgoKIqtQWMOJF52wsImCAf/Jh5GjX+4Tw=+github.com/pion/stun/v4 v4.0.0 h1:UuQy2q6iZR4EnMl/+G8kAtaWhf7jx/u8ZyN9oD4+YEQ=+github.com/pion/stun/v4 v4.0.0/go.mod h1:JAojPsPtDH4iPeNQb7kvxBdzypmkWAROxy0coApKH2E=+github.com/pion/transport/v3 v3.0.8 h1:oI3myyYnTKUSTthu/NZZ8eu2I5sHbxbUNNFW62olaYc=+github.com/pion/transport/v3 v3.0.8/go.mod h1:+c2eewC5WJQHiAA46fkMMzoYZSuGzA/7E2FPrOYHctQ=+github.com/pion/transport/v4 v4.1.0 h1:8S+nF2reM2cJuqC6g78OVy2BBgmbdns+acx3jA97BvQ=+github.com/pion/transport/v4 v4.1.0/go.mod h1:06hFI+jCFcok2X2MekVufNZ/uzNZXivGBPfviSVcjgM=+github.com/pion/turn/v4 v4.1.4 h1:EU11yMXKIsK43FhcUnjLlrhE4nboHZq+TXBIi3QpcxQ=+github.com/pion/turn/v4 v4.1.4/go.mod h1:ES1DXVFKnOhuDkqn9hn5VJlSWmZPaRJLyBXoOeO/BmQ=+github.com/pion/turn/v5 v5.1.0 h1:OSzLub7q4GssG1P4BEVrz39MnnJlxLy1LOvEkP9f46o=+github.com/pion/turn/v5 v5.1.0/go.mod h1:6HJQO7UAe7pEPMrTtBrmj+tTfp+Ai8KAV2+GXHFi1nQ=+github.com/pion/webrtc/v4 v4.2.20 h1:NYiNhBTFArA8aoP18a30y4LN0dyqSrF65HxU7KnhNOo=+github.com/pion/webrtc/v4 v4.2.20/go.mod h1:aLGXbekuN0tHOu7IPX1o9Y/uN29Ovfjaaz4bL2P9ND8=+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=+github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=+github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=+github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU=+github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=+go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=+go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=+golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=+golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=+golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=+golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=+golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=+golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=+golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=+golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=+golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=+golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=+golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=+golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=+golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=+golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=+golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=+golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=+gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=+gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=+google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800 h1:qEHAMpSaUhtD0p3NbEEI83HwNGFxEwaSJ1G9PLnCBZE=+google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=+google.golang.org/grpc v1.84.0 h1:soMyaPJ8pAak5PIQ0DGBUir0XRo2fRoMqhNWMLlLxO0=+google.golang.org/grpc v1.84.0/go.mod h1:ljCht0DrxQrXBDRTZp52Qxh3Ffk8CdYm2sj4O2QN2C0=+google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=+google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=+modernc.org/cc/v4 v4.29.2 h1:h6+9ciCnPKutf4I03CvheAvDLX7+IHlqR6Iy6J+cgd8=+modernc.org/cc/v4 v4.29.2/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=+modernc.org/ccgo/v4 v4.35.0 h1:F+TUsmw09QxLzmi3aeYYGxjAXarmZaKgj3mKQHNaA8w=+modernc.org/ccgo/v4 v4.35.0/go.mod h1:qrVGs9S3Sr2Ztcg9ve+kTAYMp5a3YvWjo+SoN06kJ5I=+modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=+modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=+modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=+modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=+modernc.org/gc/v3 v3.1.5 h1:21ldfPfRYE31Tb7B3mwAK8gy1AxP4+dKjrOQPfqakoc=+modernc.org/gc/v3 v3.1.5/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=+modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=+modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=+modernc.org/libc v1.75.7 h1:o3DTP9/0p9pKmY2WCKQaySW6wIiZhNM7wc2lUoyhfew=+modernc.org/libc v1.75.7/go.mod h1:bO5o2ztHxBb2rjz0PgdHN0sSMw57CgxGFLZ3Qd/QpVQ=+modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=+modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=+modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=+modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=+modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=+modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=+modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=+modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=+modernc.org/sqlite v1.59.0 h1:X1es1GpqBlS/5T+vbM4HLUdaa8OtQx468DF2vrx+38A=+modernc.org/sqlite v1.59.0/go.mod h1:+paeT2A3iPRHkQDwG7oA6Tk0zQd5woMEI8q7orfry8k=+modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=+modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=+modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=+modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=diff --git a/client-core/internal/cache/cache.go b/client-core/internal/cache/cache.gonew file mode 100644index 0000000..0417d09--- /dev/null+++ b/client-core/internal/cache/cache.go@@ -0,0 +1,189 @@+// Package cache 管理落盘内容的存放与回收。+package cache++import (+ "crypto/rand"+ "encoding/hex"+ "fmt"+ "io"+ "os"+ "path/filepath"+ "strings"+)++// Cache 是缓存目录的封装。+//+// 每条记录占一个子目录,目录名即 clip id 派生的短标识。+// 用目录而非单文件,是因为一次复制可能包含多个文件或整个文件夹。+type Cache struct {+ root string+}++func New(root string) (*Cache, error) {+ if err := os.MkdirAll(root, 0o700); err != nil {+ return nil, fmt.Errorf("创建缓存目录: %w", err)+ }+ return &Cache{root: root}, nil+}++func (c *Cache) Root() string { return c.root }++// Dir 返回某条记录的缓存目录(相对路径),必要时创建。+func (c *Cache) Dir(clipID string) (rel, abs string, err error) {+ rel = safeName(clipID)+ abs = filepath.Join(c.root, rel)+ if err := os.MkdirAll(abs, 0o700); err != nil {+ return "", "", fmt.Errorf("创建缓存子目录: %w", err)+ }+ return rel, abs, nil+}++func (c *Cache) Abs(rel string) string {+ if rel == "" {+ return ""+ }+ return filepath.Join(c.root, rel)+}++// Exists 判断某条记录的缓存是否还在。+// 用户可能手动清理过目录,所以每次使用前都该确认。+func (c *Cache) Exists(rel string) bool {+ if rel == "" {+ return false+ }+ _, err := os.Stat(c.Abs(rel))+ return err == nil+}++// Entries 列出某条记录缓存目录下的顶层条目的绝对路径。+// 写入剪贴板时需要这些路径。+func (c *Cache) Entries(rel string) ([]string, error) {+ abs := c.Abs(rel)+ items, err := os.ReadDir(abs)+ if err != nil {+ return nil, err+ }+ out := make([]string, 0, len(items))+ for _, it := range items {+ out = append(out, filepath.Join(abs, it.Name()))+ }+ return out, nil+}++// Remove 删除某条记录的缓存。+func (c *Cache) Remove(rel string) error {+ if rel == "" {+ return nil+ }+ abs := c.Abs(rel)+ // 防御路径逃逸:rel 理论上都是自己生成的,但删除操作值得多一道保险+ if !strings.HasPrefix(filepath.Clean(abs), filepath.Clean(c.root)) {+ return fmt.Errorf("拒绝删除缓存目录之外的路径: %s", abs)+ }+ return os.RemoveAll(abs)+}++// Orphans 找出磁盘上存在、但已无记录引用的目录。+//+// 记录与文件分别存储,进程崩溃或数据库回滚都可能让两者失配,+// 因此 GC 需要双向对账,而不只是按记录删文件。+func (c *Cache) Orphans(referenced map[string]struct{}) ([]string, error) {+ items, err := os.ReadDir(c.root)+ if err != nil {+ return nil, err+ }+ var out []string+ for _, it := range items {+ if !it.IsDir() {+ continue+ }+ if _, ok := referenced[it.Name()]; !ok {+ out = append(out, it.Name())+ }+ }+ return out, nil+}++// Size 统计缓存总占用。+func (c *Cache) Size() int64 {+ var total int64+ _ = filepath.Walk(c.root, func(_ string, info os.FileInfo, err error) error {+ if err != nil {+ return nil // 单个文件读不到不影响整体统计+ }+ if !info.IsDir() {+ total += info.Size()+ }+ return nil+ })+ return total+}++// TempFile 在缓存目录下创建临时文件,用于边下边写。+// 与最终位置同盘,完成后可以原子改名。+func (c *Cache) TempFile(prefix string) (*os.File, error) {+ dir := filepath.Join(c.root, ".tmp")+ if err := os.MkdirAll(dir, 0o700); err != nil {+ return nil, err+ }+ return os.CreateTemp(dir, prefix+"-*")+}++// CleanTemp 清掉上次异常退出残留的临时文件。+func (c *Cache) CleanTemp() error {+ return os.RemoveAll(filepath.Join(c.root, ".tmp"))+}++// safeName 把 clip id 转成安全的目录名。+// clip id 是本地生成的,但仍然过滤一遍,避免路径分隔符带来的意外。+func safeName(id string) string {+ var b strings.Builder+ for _, r := range id {+ switch {+ case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9',+ r == '-', r == '_':+ b.WriteRune(r)+ default:+ b.WriteByte('_')+ }+ }+ if b.Len() == 0 {+ return randomName()+ }+ return b.String()+}++func randomName() string {+ buf := make([]byte, 8)+ if _, err := rand.Read(buf); err != nil {+ return "unnamed"+ }+ return hex.EncodeToString(buf)+}++// WriteAtomic 先写临时文件再改名,避免中断留下半截文件。+func WriteAtomic(path string, r io.Reader, perm os.FileMode) (int64, error) {+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {+ return 0, err+ }+ tmp, err := os.CreateTemp(filepath.Dir(path), ".partial-*")+ if err != nil {+ return 0, err+ }+ tmpName := tmp.Name()+ defer os.Remove(tmpName) // 成功改名后这里是空操作++ n, err := io.Copy(tmp, r)+ if err != nil {+ tmp.Close()+ return n, err+ }+ if err := tmp.Chmod(perm); err != nil {+ tmp.Close()+ return n, err+ }+ if err := tmp.Close(); err != nil {+ return n, err+ }+ return n, os.Rename(tmpName, path)+}diff --git a/client-core/internal/clipboard/clipboard.go b/client-core/internal/clipboard/clipboard.gonew file mode 100644index 0000000..cdfd1a9--- /dev/null+++ b/client-core/internal/clipboard/clipboard.go@@ -0,0 +1,219 @@+// Package clipboard 是跨平台剪贴板访问层。+//+// ⚠️ 线程约束(M-1 实测,见 spikes/results.md)+//+// macOS 的剪贴板隐私机制开启后,剪贴板 API 会经 ViewBridge 与系统 UI 服务+// 通信以便显示授权弹窗,其内部 NSCFRunLoopSemaphore 依赖 run loop。+// 在裸 dispatch queue / 非主线程上调用会直接 SIGSEGV:+//+// reportAccessBehavior → AppKit → ViewBridge -[NSCFRunLoopSemaphore wait]+// → NSException raise → EXC_BAD_ACCESS+//+// 因此本包的所有方法**必须**在主线程调用。用 MainLoop 来保证这一点:+// main() 里 runtime.LockOSThread() 锁住主线程跑 MainLoop,+// 业务 goroutine 通过 Post/Call 把操作投递过去。+package clipboard++import (+ "context"+ "errors"+ "fmt"+)++// Kind 是剪贴板内容的粗分类。+type Kind int++const (+ KindUnknown Kind = iota+ KindText+ KindHTML+ KindImage+ KindFile // 一个或多个文件/文件夹+)++func (k Kind) String() string {+ switch k {+ case KindText:+ return "text"+ case KindHTML:+ return "html"+ case KindImage:+ return "image"+ case KindFile:+ return "file"+ default:+ return "unknown"+ }+}++// Permission 对应 macOS 的 NSPasteboardAccessBehavior。+// 其他平台恒为 PermissionNotApplicable。+type Permission int++const (+ PermissionNotApplicable Permission = iota // 系统无此机制+ PermissionDefault // 尚未触发过授权弹窗+ PermissionAsk // 每次程序化读取都询问+ PermissionAlwaysAllow // 永久放行+ PermissionAlwaysDeny // 永久拒绝+)++// CanReadSilently 表示此刻读取内容是否不会弹窗阻塞。+//+// 只有 AlwaysAllow 才安全。其余状态下 daemon 不应贸然读取——+// 后台进程的授权弹窗可能根本不可见,一旦读取就会无限阻塞。+// 正确做法是上报状态给 UI,由 UI 引导用户去系统设置授权。+func (p Permission) CanReadSilently() bool {+ return p == PermissionNotApplicable || p == PermissionAlwaysAllow+}++func (p Permission) String() string {+ switch p {+ case PermissionNotApplicable:+ return "not_applicable"+ case PermissionDefault:+ return "default"+ case PermissionAsk:+ return "ask"+ case PermissionAlwaysAllow:+ return "always_allow"+ case PermissionAlwaysDeny:+ return "always_deny"+ default:+ return "unknown"+ }+}++// Snapshot 是对剪贴板的**免提示**探测结果。+//+// 只含类型信息,不含任何内容。M-1 实测这些操作全部免授权且耗时 < 0.03s:+// changeCount / types / detectMetadataForTypes。+type Snapshot struct {+ ChangeCount int64+ Kind Kind+ ContentType string // UTType 标识符,如 public.plain-text+ Types []string // 原始类型列表,排障用+}++// Content 是剪贴板的实际内容。读取它可能触发授权弹窗。+type Content struct {+ Kind Kind+ Text string // KindText / KindHTML 的纯文本形式+ HTML string // KindHTML 的原始标记+ Image []byte // KindImage 的 PNG 字节+ Files []string // KindFile 的绝对路径+}++// Clipboard 是平台实现要满足的接口。所有方法必须在主线程调用。+type Clipboard interface {+ // Peek 免提示地探测剪贴板类型。可安全地高频调用。+ Peek() (Snapshot, error)++ // Read 读取实际内容。调用前务必先检查 Permission().CanReadSilently(),+ // 否则可能阻塞在不可见的授权弹窗上。+ Read() (Content, error)++ // Write 覆盖本机剪贴板。文件类型要求路径已真实存在于本地磁盘。+ Write(Content) error++ // Permission 返回当前授权状态,本身免提示。+ Permission() Permission++ // OpenPermissionSettings 打开系统设置中对应的隐私面板,引导用户授权。+ OpenPermissionSettings() error+}++var (+ ErrUnsupported = errors.New("当前平台不支持该剪贴板操作")+ // ErrPermissionRequired 表示用户尚未授予剪贴板读取权限。+ // daemon 遇到它应当上报给界面去引导授权,而不是反复重试。+ ErrPermissionRequired = errors.New("需要授予剪贴板访问权限")+)++// ─────────────────────── 主线程调度 ───────────────────────++// MainLoop 在主线程上运行平台的事件循环,并执行投递进来的任务。+//+// 用法(main 函数):+//+// func main() {+// runtime.LockOSThread()+// loop := clipboard.NewMainLoop()+// go daemon.Run(loop) // 业务逻辑跑在别的 goroutine+// loop.Run(ctx) // 主线程在此阻塞+// }+type MainLoop struct {+ tasks chan func()+}++func NewMainLoop() *MainLoop {+ // 带缓冲,避免投递方在主线程忙时阻塞+ return &MainLoop{tasks: make(chan func(), 64)}+}++// Post 异步投递任务到主线程,不等待结果。+func (l *MainLoop) Post(fn func()) {+ select {+ case l.tasks <- fn:+ default:+ // 队列满说明主线程卡住了(很可能阻塞在授权弹窗上)。+ // 丢弃而非阻塞调用方——剪贴板轮询丢一次无所谓,卡死业务则不可接受。+ }+}++// Call 投递任务并等待其在主线程执行完毕。+//+// 注意:若主线程正阻塞在授权弹窗上,这里会一直等到 ctx 取消。+// 所以调用方必须带一个有超时的 ctx。+func (l *MainLoop) Call(ctx context.Context, fn func()) error {+ done := make(chan struct{})+ wrapped := func() {+ defer close(done)+ fn()+ }+ select {+ case l.tasks <- wrapped:+ case <-ctx.Done():+ return ctx.Err()+ }+ select {+ case <-done:+ return nil+ case <-ctx.Done():+ return ctx.Err()+ }+}++// Run 在当前线程(必须是已 LockOSThread 的主线程)处理投递进来的任务,+// 直到 ctx 取消。+//+// 等待任务的间隙会驱动平台事件循环:macOS 上剪贴板 API 的跨进程回调与+// 授权弹窗都依赖 run loop 转动,只 select 等 channel 会让它们永远得不到处理。+func (l *MainLoop) Run(ctx context.Context) {+ const pumpInterval = 0.05 // 秒。足够跟手,又不会空转烧 CPU++ for {+ select {+ case <-ctx.Done():+ return+ case fn := <-l.tasks:+ fn()+ default:+ // 没有待办任务时转动一小段 run loop,然后回来再看队列+ pumpRunLoop(pumpInterval)+ }+ }+}++// CallResult 是 Call 的泛型版本,用于需要返回值的场景。+func CallResult[T any](ctx context.Context, l *MainLoop, fn func() (T, error)) (T, error) {+ var (+ val T+ err error+ )+ if cerr := l.Call(ctx, func() { val, err = fn() }); cerr != nil {+ var zero T+ return zero, fmt.Errorf("投递到主线程失败: %w", cerr)+ }+ return val, err+}diff --git a/client-core/internal/clipboard/darwin.go b/client-core/internal/clipboard/darwin.gonew file mode 100644index 0000000..2603c5c--- /dev/null+++ b/client-core/internal/clipboard/darwin.go@@ -0,0 +1,239 @@+//go:build darwin++package clipboard++/*+#cgo CFLAGS: -x objective-c -fobjc-arc+#cgo LDFLAGS: -framework Cocoa -framework UniformTypeIdentifiers++#include <stdlib.h>++long cs_change_count(void);+int cs_access_behavior(void);+char *cs_types_json(void);+char *cs_detect_content_type(void);+char *cs_read_text(void);+char *cs_read_html(void);+char *cs_read_file_urls_json(void);+int cs_read_image_png(void **out, int *outLen);+int cs_write_text(const char *utf8);+int cs_write_html(const char *html, const char *plain);+int cs_write_image_png(const void *data, int len);+int cs_write_files_json(const char *pathsJSON);+void cs_open_permission_settings(void);+void cs_run_loop_once(double seconds);+void cs_init_app(void);+*/+import "C"++import (+ "encoding/json"+ "errors"+ "fmt"+ "strings"+ "unsafe"+)++// darwinClipboard 是 macOS 的实现。所有方法必须在主线程调用。+type darwinClipboard struct{}++// New 返回当前平台的剪贴板实现。+func New() Clipboard { return darwinClipboard{} }++// InitPlatform 初始化 NSApplication。必须在主线程、进入 MainLoop 之前调用。+func InitPlatform() { C.cs_init_app() }++// goString 接管 C 侧 strdup 出来的字符串并释放它。+func goString(c *C.char) string {+ if c == nil {+ return ""+ }+ defer C.free(unsafe.Pointer(c))+ return C.GoString(c)+}++func goStringSlice(c *C.char) []string {+ raw := goString(c)+ if raw == "" {+ return nil+ }+ var out []string+ if err := json.Unmarshal([]byte(raw), &out); err != nil {+ return nil+ }+ return out+}++func (darwinClipboard) Permission() Permission {+ switch C.cs_access_behavior() {+ case -1:+ return PermissionNotApplicable+ case 0:+ return PermissionDefault+ case 1:+ return PermissionAsk+ case 2:+ return PermissionAlwaysAllow+ case 3:+ return PermissionAlwaysDeny+ default:+ return PermissionNotApplicable+ }+}++// Peek 只做免授权的探测:变更计数、类型列表、内容类型。+//+// M-1 实测这三项在隐私机制开启时合计耗时不到 0.03 秒且不触发弹窗,+// 因此可以按 300ms 的频率安全地轮询。+func (c darwinClipboard) Peek() (Snapshot, error) {+ s := Snapshot{+ ChangeCount: int64(C.cs_change_count()),+ Types: goStringSlice(C.cs_types_json()),+ ContentType: goString(C.cs_detect_content_type()),+ }+ s.Kind = classify(s.Types, s.ContentType)+ return s, nil+}++// classify 由类型列表和 UTType 推断内容分类。+//+// 顺序有讲究:文件优先于文本——Finder 复制文件时剪贴板里往往同时带着+// 文件名的纯文本表示,先判文本会把文件误判成文本。+func classify(types []string, contentType string) Kind {+ has := func(t string) bool {+ for _, v := range types {+ if v == t {+ return true+ }+ }+ return false+ }++ switch {+ case has("public.file-url"), has("NSFilenamesPboardType"):+ return KindFile+ case has("public.png"), has("public.tiff"):+ return KindImage+ case has("public.html"):+ return KindHTML+ case has("public.utf8-plain-text"), has("NSStringPboardType"):+ return KindText+ }++ // 类型列表没命中时退回 detectMetadata 拿到的 UTType+ switch {+ case strings.HasPrefix(contentType, "public.image"),+ strings.HasSuffix(contentType, ".png"),+ strings.HasSuffix(contentType, ".jpeg"):+ return KindImage+ case contentType == "public.html":+ return KindHTML+ case contentType != "":+ return KindFile // 有具体 UTType 通常意味着这是个文件引用+ }+ return KindUnknown+}++// Read 读取剪贴板实际内容。+//+// 调用前务必确认 Permission().CanReadSilently(),否则在隐私机制开启且+// 未授权时会阻塞在授权弹窗上——而 daemon 是后台进程,弹窗未必可见。+func (c darwinClipboard) Read() (Content, error) {+ snap, err := c.Peek()+ if err != nil {+ return Content{}, err+ }++ out := Content{Kind: snap.Kind}+ switch snap.Kind {+ case KindFile:+ out.Files = goStringSlice(C.cs_read_file_urls_json())+ if len(out.Files) == 0 {+ return Content{}, errors.New("剪贴板中没有可读取的文件路径")+ }++ case KindText:+ out.Text = goString(C.cs_read_text())++ case KindHTML:+ out.HTML = goString(C.cs_read_html())+ out.Text = goString(C.cs_read_text())++ case KindImage:+ var buf unsafe.Pointer+ var n C.int+ if C.cs_read_image_png(&buf, &n) == 0 || buf == nil {+ return Content{}, errors.New("读取剪贴板图片失败")+ }+ defer C.free(buf)+ out.Image = C.GoBytes(buf, n)++ default:+ return Content{}, fmt.Errorf("不支持的剪贴板类型:%v", snap.Types)+ }+ return out, nil+}++// Write 覆盖本机剪贴板。+//+// 文件类型要求路径已真实存在——M-1 验证过延迟渲染在 macOS 的粘贴路径上+// 不成立,所以内容必须先落盘再写剪贴板。+func (c darwinClipboard) Write(content Content) error {+ switch content.Kind {+ case KindFile:+ if len(content.Files) == 0 {+ return errors.New("没有要写入的文件路径")+ }+ data, err := json.Marshal(content.Files)+ if err != nil {+ return err+ }+ cs := C.CString(string(data))+ defer C.free(unsafe.Pointer(cs))+ if C.cs_write_files_json(cs) == 0 {+ return errors.New("写入文件到剪贴板失败(路径可能不存在)")+ }++ case KindText:+ cs := C.CString(content.Text)+ defer C.free(unsafe.Pointer(cs))+ if C.cs_write_text(cs) == 0 {+ return errors.New("写入文本到剪贴板失败")+ }++ case KindHTML:+ chtml := C.CString(content.HTML)+ defer C.free(unsafe.Pointer(chtml))+ cplain := C.CString(content.Text)+ defer C.free(unsafe.Pointer(cplain))+ if C.cs_write_html(chtml, cplain) == 0 {+ return errors.New("写入 HTML 到剪贴板失败")+ }++ case KindImage:+ if len(content.Image) == 0 {+ return errors.New("没有要写入的图片数据")+ }+ if C.cs_write_image_png(+ unsafe.Pointer(&content.Image[0]), C.int(len(content.Image))) == 0 {+ return errors.New("写入图片到剪贴板失败")+ }++ default:+ return fmt.Errorf("不支持写入的类型:%v", content.Kind)+ }+ return nil+}++func (darwinClipboard) OpenPermissionSettings() error {+ C.cs_open_permission_settings()+ return nil+}++// pumpRunLoop 驱动 macOS 主 run loop。+//+// 剪贴板 API 的跨进程回调与授权弹窗都依赖 run loop 转动,+// 所以 MainLoop 在等待任务的间隙必须调用它。+func pumpRunLoop(seconds float64) {+ C.cs_run_loop_once(C.double(seconds))+}diff --git a/client-core/internal/clipboard/darwin.m b/client-core/internal/clipboard/darwin.mnew file mode 100644index 0000000..63fbbc3--- /dev/null+++ b/client-core/internal/clipboard/darwin.m@@ -0,0 +1,260 @@+//go:build darwin++// macOS 剪贴板的原生实现。+//+// ⚠️ 本文件所有函数都必须在主线程调用(见 clipboard.go 的线程约束说明)。+// 隐私机制开启后,剪贴板 API 经 ViewBridge 与系统 UI 服务通信,+// 其内部 NSCFRunLoopSemaphore 依赖 run loop,在裸线程上调用会直接 SIGSEGV。++#import <Cocoa/Cocoa.h>+#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>++#include <stdlib.h>+#include <string.h>++// 返回给 Go 的字符串统一用 strdup 分配,由 Go 侧 C.free 释放。+static char *copyCString(NSString *s) {+ if (s == nil) return NULL;+ const char *utf8 = s.UTF8String;+ if (utf8 == NULL) return NULL;+ return strdup(utf8);+}++static char *copyJSON(id obj) {+ if (obj == nil) return NULL;+ NSError *err = nil;+ NSData *data = [NSJSONSerialization dataWithJSONObject:obj options:0 error:&err];+ if (err != nil || data == nil) return NULL;+ return copyCString([[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);+}++// 在主线程等待异步回调:spin run loop 而不是阻塞。+//+// 直接阻塞会有两个问题:completionHandler 若投递到主队列则死锁;+// 且系统授权弹窗依赖主 run loop 才能显示和响应。+static BOOL waitSpinning(dispatch_semaphore_t sem, NSTimeInterval timeout) {+ NSDate *deadline = [NSDate dateWithTimeIntervalSinceNow:timeout];+ while (dispatch_semaphore_wait(sem, DISPATCH_TIME_NOW) != 0) {+ if (deadline.timeIntervalSinceNow < 0) return NO;+ [NSRunLoop.currentRunLoop runMode:NSDefaultRunLoopMode+ beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.01]];+ }+ return YES;+}++#pragma mark - 免提示探测++long cs_change_count(void) {+ return (long)NSPasteboard.generalPasteboard.changeCount;+}++// 返回值对应 Go 侧的 Permission 常量:+// -1 = 系统无此机制,0 = default,1 = ask,2 = alwaysAllow,3 = alwaysDeny+int cs_access_behavior(void) {+ if (@available(macOS 15.4, *)) {+ return (int)NSPasteboard.generalPasteboard.accessBehavior;+ }+ return -1;+}++// 类型列表。实测免授权,隐私机制开启时耗时约 0.003s。+char *cs_types_json(void) {+ NSArray<NSPasteboardType> *types = NSPasteboard.generalPasteboard.types;+ return copyJSON(types ?: @[]);+}++// 用 detectMetadataForTypes 探测内容类型。+//+// Apple 明确保证此方法不会通知用户,实测隐私机制开启时耗时 0.021s 且无弹窗。+// CopySync 靠它在不触发授权的前提下完成"复制的是文件还是文本"的分类。+char *cs_detect_content_type(void) {+ if (@available(macOS 15.4, *)) {+ __block char *result = NULL;+ dispatch_semaphore_t sem = dispatch_semaphore_create(0);++ [NSPasteboard.generalPasteboard+ detectMetadataForTypes:[NSSet setWithObject:NSPasteboardMetadataTypeContentType]+ completionHandler:^(NSDictionary<NSPasteboardMetadataType, id> *md, NSError *err) {+ if (err == nil) {+ UTType *ct = md[NSPasteboardMetadataTypeContentType];+ if (ct != nil) result = copyCString(ct.identifier);+ }+ dispatch_semaphore_signal(sem);+ }];++ waitSpinning(sem, 5.0);+ return result;+ }+ return NULL;+}++#pragma mark - 读取内容(可能触发授权)++char *cs_read_text(void) {+ NSPasteboard *pb = NSPasteboard.generalPasteboard;++ // 依次尝试多种取法。+ //+ // stringForType: 对某些写入方(例如只声明了旧式 NSStringPboardType 的应用)+ // 会返回 nil,而 readObjectsForClasses: 能正确走类型转换拿到内容。+ // 剪贴板的写入方五花八门,这里不假定它们都规范声明了现代 UTI。+ NSString *s = [pb stringForType:NSPasteboardTypeString];+ if (s.length > 0) return copyCString(s);++ NSArray<NSString *> *objs =+ [pb readObjectsForClasses:@[NSString.class] options:nil];+ if (objs.count > 0) {+ NSString *first = objs.firstObject;+ if (first.length > 0) return copyCString(first);+ }++ // 最后退回原始字节:个别写入方提供的数据不带 BOM/编码声明,+ // 高层 API 会拒绝转换,但按 UTF-8 解出来往往是对的。+ NSData *data = [pb dataForType:NSPasteboardTypeString];+ if (data.length > 0) {+ NSString *decoded = [[NSString alloc] initWithData:data+ encoding:NSUTF8StringEncoding];+ if (decoded.length > 0) return copyCString(decoded);+ }+ return NULL;+}++char *cs_read_html(void) {+ NSPasteboard *pb = NSPasteboard.generalPasteboard;+ NSString *s = [pb stringForType:NSPasteboardTypeHTML];+ if (s.length > 0) return copyCString(s);++ NSData *data = [pb dataForType:NSPasteboardTypeHTML];+ if (data.length > 0) {+ NSString *decoded = [[NSString alloc] initWithData:data+ encoding:NSUTF8StringEncoding];+ if (decoded.length > 0) return copyCString(decoded);+ }+ return NULL;+}++// 返回文件路径数组的 JSON。CopySync 的 A 端靠它拿到源文件位置。+char *cs_read_file_urls_json(void) {+ NSArray<NSURL *> *urls = [NSPasteboard.generalPasteboard+ readObjectsForClasses:@[NSURL.class]+ options:@{NSPasteboardURLReadingFileURLsOnlyKey: @YES}];+ if (urls == nil) return NULL;++ NSMutableArray<NSString *> *paths = [NSMutableArray arrayWithCapacity:urls.count];+ for (NSURL *u in urls) {+ if (u.isFileURL && u.path != nil) [paths addObject:u.path];+ }+ return copyJSON(paths);+}++// 读取图片并统一编码为 PNG。+// 剪贴板里可能是 TIFF(系统截图常见),统一成 PNG 便于跨平台传输。+int cs_read_image_png(void **out, int *outLen) {+ *out = NULL;+ *outLen = 0;++ NSPasteboard *pb = NSPasteboard.generalPasteboard;+ NSData *png = [pb dataForType:NSPasteboardTypePNG];++ if (png == nil) {+ NSData *tiff = [pb dataForType:NSPasteboardTypeTIFF];+ if (tiff == nil) return 0;+ NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithData:tiff];+ if (rep == nil) return 0;+ png = [rep representationUsingType:NSBitmapImageFileTypePNG properties:@{}];+ if (png == nil) return 0;+ }++ void *buf = malloc(png.length);+ if (buf == NULL) return 0;+ memcpy(buf, png.bytes, png.length);+ *out = buf;+ *outLen = (int)png.length;+ return 1;+}++#pragma mark - 写入剪贴板++int cs_write_text(const char *utf8) {+ if (utf8 == NULL) return 0;+ NSString *s = @(utf8);+ NSPasteboard *pb = NSPasteboard.generalPasteboard;+ [pb clearContents];+ return [pb setString:s forType:NSPasteboardTypeString] ? 1 : 0;+}++int cs_write_html(const char *html, const char *plain) {+ if (html == NULL) return 0;+ NSPasteboard *pb = NSPasteboard.generalPasteboard;+ [pb clearContents];+ BOOL ok = [pb setString:@(html) forType:NSPasteboardTypeHTML];+ // 同时放纯文本兜底:很多应用不接受 HTML+ if (plain != NULL) [pb setString:@(plain) forType:NSPasteboardTypeString];+ return ok ? 1 : 0;+}++int cs_write_image_png(const void *data, int len) {+ if (data == NULL || len <= 0) return 0;+ NSData *png = [NSData dataWithBytes:data length:(NSUInteger)len];+ NSPasteboard *pb = NSPasteboard.generalPasteboard;+ [pb clearContents];+ return [pb setData:png forType:NSPasteboardTypePNG] ? 1 : 0;+}++// 把本地文件写进剪贴板,使其可被 Finder 直接粘贴。+//+// 文件必须已真实存在于磁盘——M-1 验证过,延迟渲染(promise)在 macOS 的+// 剪贴板粘贴路径上不成立,所以这里只能写真实路径。+int cs_write_files_json(const char *pathsJSON) {+ if (pathsJSON == NULL) return 0;++ NSData *data = [@(pathsJSON) dataUsingEncoding:NSUTF8StringEncoding];+ NSArray *paths = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];+ if (![paths isKindOfClass:NSArray.class] || paths.count == 0) return 0;++ NSMutableArray<NSURL *> *urls = [NSMutableArray arrayWithCapacity:paths.count];+ for (NSString *p in paths) {+ if (![p isKindOfClass:NSString.class]) continue;+ // 不存在的路径写进去只会让粘贴失败,不如提前剔除+ if (![NSFileManager.defaultManager fileExistsAtPath:p]) continue;+ [urls addObject:[NSURL fileURLWithPath:p]];+ }+ if (urls.count == 0) return 0;++ NSPasteboard *pb = NSPasteboard.generalPasteboard;+ [pb clearContents];+ return [pb writeObjects:urls] ? 1 : 0;+}++#pragma mark - 权限引导++void cs_open_permission_settings(void) {+ // 直达「隐私与安全性 → 从其他 App 粘贴」+ NSURL *url = [NSURL URLWithString:+ @"x-apple.systempreferences:com.apple.preference.security?Privacy_Pasteboard"];+ [NSWorkspace.sharedWorkspace openURL:url];+}++#pragma mark - 主线程 run loop++// 驱动 run loop 一小段时间。+//+// daemon 的主线程需要持续转动 run loop,否则剪贴板 API 的跨进程回调+// 与授权弹窗都无法工作。Go 侧在锁定的主线程上循环调用它。+void cs_run_loop_once(double seconds) {+ @autoreleasepool {+ [NSRunLoop.currentRunLoop runMode:NSDefaultRunLoopMode+ beforeDate:[NSDate dateWithTimeIntervalSinceNow:seconds]];+ }+}++// 初始化 NSApplication。+//+// 必须有 NSApplication 实例,AppKit 的剪贴板与 ViewBridge 机制才完整可用;+// Accessory 模式让 daemon 不出现在 Dock 和任务切换器里。+void cs_init_app(void) {+ @autoreleasepool {+ NSApplication *app = NSApplication.sharedApplication;+ [app setActivationPolicy:NSApplicationActivationPolicyAccessory];+ }+}diff --git a/client-core/internal/clipboard/other.go b/client-core/internal/clipboard/other.gonew file mode 100644index 0000000..35395d0--- /dev/null+++ b/client-core/internal/clipboard/other.go@@ -0,0 +1,25 @@+//go:build !darwin++package clipboard++import "time"++// 非 macOS 平台的占位实现。Windows 的实现是二期工作(M6/M7):+// 文本与图片走 SetClipboardData + WM_RENDERFORMAT,+// 文件粘贴需要在 Go 里实现 COM IDataObject。+type stubClipboard struct{}++func New() Clipboard { return stubClipboard{} }++func InitPlatform() {}++func (stubClipboard) Peek() (Snapshot, error) { return Snapshot{}, ErrUnsupported }+func (stubClipboard) Read() (Content, error) { return Content{}, ErrUnsupported }+func (stubClipboard) Write(Content) error { return ErrUnsupported }+func (stubClipboard) Permission() Permission { return PermissionNotApplicable }+func (stubClipboard) OpenPermissionSettings() error { return ErrUnsupported }++// 无原生事件循环可驱动时,单纯让出 CPU。+func pumpRunLoop(seconds float64) {+ time.Sleep(time.Duration(seconds * float64(time.Second)))+}diff --git a/client-core/internal/clipboard/watcher.go b/client-core/internal/clipboard/watcher.gonew file mode 100644index 0000000..0dd4aeb--- /dev/null+++ b/client-core/internal/clipboard/watcher.go@@ -0,0 +1,176 @@+package clipboard++import (+ "context"+ "log/slog"+ "time"+)++// Watcher 监听本机剪贴板变化。+//+// macOS 不提供剪贴板变更通知,只能轮询 changeCount。好在 M-1 实测表明+// changeCount、类型列表、detectMetadata 这三项都免授权且合计不到 0.03 秒,+// 因此 300ms 的轮询既跟手又不会造成负担。+type Watcher struct {+ cb Clipboard+ loop *MainLoop+ log *slog.Logger++ interval time.Duration+ onChange func(Snapshot)+ // onPermission 在授权状态变化时回调,界面据此引导用户去系统设置+ onPermission func(Permission)++ lastChange int64+ lastPermission Permission+ // selfWrites 记录本机主动写入剪贴板时的 changeCount,+ // 避免把"自己刚写进去的内容"当成用户的新复制再广播一遍。+ selfWrites map[int64]struct{}+}++type WatcherOptions struct {+ Clipboard Clipboard+ MainLoop *MainLoop+ Logger *slog.Logger+ Interval time.Duration+ OnChange func(Snapshot)+ OnPermission func(Permission)+}++func NewWatcher(opts WatcherOptions) *Watcher {+ log := opts.Logger+ if log == nil {+ log = slog.Default()+ }+ interval := opts.Interval+ if interval <= 0 {+ interval = 300 * time.Millisecond+ }+ return &Watcher{+ cb: opts.Clipboard,+ loop: opts.MainLoop,+ log: log,+ interval: interval,+ onChange: opts.OnChange,+ onPermission: opts.OnPermission,+ lastChange: -1,+ selfWrites: make(map[int64]struct{}),+ }+}++// SetOnChange 设置剪贴板变化的回调。+//+// 单独提供这个方法,是因为同步引擎需要在 Watcher 之后构造+// (引擎依赖 Watcher 读写剪贴板),无法在 NewWatcher 时就把回调传进去。+func (w *Watcher) SetOnChange(fn func(Snapshot)) { w.onChange = fn }++// Run 持续轮询直到 ctx 取消。可在任意 goroutine 中启动——+// 真正接触剪贴板的操作都会被投递到主线程执行。+func (w *Watcher) Run(ctx context.Context) {+ ticker := time.NewTicker(w.interval)+ defer ticker.Stop()++ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ w.poll(ctx)+ }+ }+}++func (w *Watcher) poll(ctx context.Context) {+ // 给足超时:万一主线程正卡在授权弹窗上,这里要能干净退出而不是堆积+ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)+ defer cancel()++ snap, err := CallResult(ctx, w.loop, w.cb.Peek)+ if err != nil {+ w.log.Debug("探测剪贴板失败", "err", err)+ return+ }++ if perm, err := CallResult(ctx, w.loop, func() (Permission, error) {+ return w.cb.Permission(), nil+ }); err == nil && perm != w.lastPermission {+ w.lastPermission = perm+ w.log.Info("剪贴板授权状态变化", "state", perm)+ if w.onPermission != nil {+ w.onPermission(perm)+ }+ }++ if snap.ChangeCount == w.lastChange {+ return+ }+ // 首轮只记录基线,不把启动前就存在的内容当作新复制广播出去+ first := w.lastChange < 0+ w.lastChange = snap.ChangeCount+ if first {+ w.log.Debug("剪贴板监听已就绪", "changeCount", snap.ChangeCount)+ return+ }++ // 本机刚写进去的内容不该被当成用户的新复制再同步一轮+ if _, mine := w.selfWrites[snap.ChangeCount]; mine {+ delete(w.selfWrites, snap.ChangeCount)+ w.log.Debug("跳过本机写入触发的变化", "changeCount", snap.ChangeCount)+ return+ }++ w.log.Debug("检测到剪贴板变化",+ "changeCount", snap.ChangeCount, "kind", snap.Kind,+ "type", snap.ContentType, "types", snap.Types)+ if w.onChange != nil {+ w.onChange(snap)+ }+}++// Read 在主线程读取剪贴板内容,并先行检查授权状态。+func (w *Watcher) Read(ctx context.Context) (Content, error) {+ perm, err := CallResult(ctx, w.loop, func() (Permission, error) {+ return w.cb.Permission(), nil+ })+ if err != nil {+ return Content{}, err+ }+ // 未授权时不要贸然读取:会阻塞在一个对后台进程可能不可见的弹窗上+ if !perm.CanReadSilently() {+ return Content{}, ErrPermissionRequired+ }+ return CallResult(ctx, w.loop, w.cb.Read)+}++// Write 在主线程写入剪贴板,并记下由此产生的 changeCount,+// 使下一轮轮询不会把它误判为用户的新复制。+func (w *Watcher) Write(ctx context.Context, content Content) error {+ return w.loop.Call(ctx, func() {+ if err := w.cb.Write(content); err != nil {+ w.log.Warn("写入剪贴板失败", "err", err)+ return+ }+ if snap, err := w.cb.Peek(); err == nil {+ w.selfWrites[snap.ChangeCount] = struct{}{}+ w.lastChange = snap.ChangeCount+ }+ })+}++func (w *Watcher) Permission(ctx context.Context) Permission {+ perm, err := CallResult(ctx, w.loop, func() (Permission, error) {+ return w.cb.Permission(), nil+ })+ if err != nil {+ return PermissionNotApplicable+ }+ return perm+}++func (w *Watcher) OpenPermissionSettings(ctx context.Context) error {+ return w.loop.Call(ctx, func() {+ if err := w.cb.OpenPermissionSettings(); err != nil {+ w.log.Warn("打开授权设置失败", "err", err)+ }+ })+}diff --git a/client-core/internal/config/config.go b/client-core/internal/config/config.gonew file mode 100644index 0000000..6553bf6--- /dev/null+++ b/client-core/internal/config/config.go@@ -0,0 +1,212 @@+// Package config 管理 daemon 的持久化配置与数据目录布局。+package config++import (+ "encoding/json"+ "fmt"+ "os"+ "path/filepath"+ "runtime"+ "time"+)++// Config 是用户可调的全部设置。字段与 proto 的 copysync.v1.Config 一一对应。+type Config struct {+ DeviceID string `json:"device_id"`+ DeviceName string `json:"device_name"`+ SignalingURL string `json:"signaling_url"`++ // 小于此值的内容在复制时自动推送给对端;大于则只同步元数据,+ // 等用户在 UI 里手动拉取。这是 M-1 否决纯懒模式后的折中点。+ AutoSyncThresholdBytes int64 `json:"auto_sync_threshold_bytes"`++ HistoryTTL Duration `json:"history_ttl"` // 历史记录元数据保留期+ CacheTTL Duration `json:"cache_ttl"` // 已落盘内容的保留期++ SyncText bool `json:"sync_text"`+ SyncHTML bool `json:"sync_html"`+ SyncImage bool `json:"sync_image"`+ SyncFile bool `json:"sync_file"`++ AutoApplyToClipboard bool `json:"auto_apply_to_clipboard"`+ LaunchAtLogin bool `json:"launch_at_login"`+}++func Default() Config {+ host, _ := os.Hostname()+ if host == "" {+ host = "未命名设备"+ }+ return Config{+ DeviceName: host,+ SignalingURL: "ws://127.0.0.1:8787/signal",+ AutoSyncThresholdBytes: 50 << 20, // 50 MiB+ HistoryTTL: Duration(3 * 24 * time.Hour),+ CacheTTL: Duration(3 * 24 * time.Hour),+ SyncText: true,+ SyncHTML: true,+ SyncImage: true,+ SyncFile: true,+ AutoApplyToClipboard: true,+ LaunchAtLogin: false,+ }+}++// Validate 修正越界值,避免用户或损坏的配置文件把 daemon 带进坏状态。+func (c *Config) Validate() {+ d := Default()+ if c.DeviceName == "" {+ c.DeviceName = d.DeviceName+ }+ if c.SignalingURL == "" {+ c.SignalingURL = d.SignalingURL+ }+ if c.AutoSyncThresholdBytes <= 0 {+ c.AutoSyncThresholdBytes = d.AutoSyncThresholdBytes+ }+ // TTL 至少一分钟,否则 GC 会把刚写入的记录立刻删掉+ if time.Duration(c.HistoryTTL) < time.Minute {+ c.HistoryTTL = d.HistoryTTL+ }+ if time.Duration(c.CacheTTL) < time.Minute {+ c.CacheTTL = d.CacheTTL+ }+ // 缓存活得比历史记录久没有意义:记录没了就找不到那些文件了+ if c.CacheTTL > c.HistoryTTL {+ c.CacheTTL = c.HistoryTTL+ }+}++// ─────────────────────────── 目录布局 ───────────────────────────++// Paths 是 daemon 用到的全部路径。集中在一处,便于测试时重定向。+type Paths struct {+ Root string // 配置与数据库+ Cache string // 收到的文件内容+ Config string+ DB string+ // daemon 启动后把 gRPC 端口和一次性 token 写在这里,供 UI 发现+ Endpoint string+}++func DefaultPaths() (Paths, error) {+ var root string+ switch runtime.GOOS {+ case "darwin":+ home, err := os.UserHomeDir()+ if err != nil {+ return Paths{}, err+ }+ root = filepath.Join(home, "Library", "Application Support", "CopySync")+ case "windows":+ base := os.Getenv("LOCALAPPDATA")+ if base == "" {+ var err error+ if base, err = os.UserConfigDir(); err != nil {+ return Paths{}, err+ }+ }+ root = filepath.Join(base, "CopySync")+ default:+ base, err := os.UserConfigDir()+ if err != nil {+ return Paths{}, err+ }+ root = filepath.Join(base, "copysync")+ }+ return pathsUnder(root), nil+}++func pathsUnder(root string) Paths {+ return Paths{+ Root: root,+ Cache: filepath.Join(root, "cache"),+ Config: filepath.Join(root, "config.json"),+ DB: filepath.Join(root, "copysync.db"),+ Endpoint: filepath.Join(root, "daemon.json"),+ }+}++// PathsUnder 让测试把整套目录指到临时位置。+func PathsUnder(root string) Paths { return pathsUnder(root) }++func (p Paths) EnsureDirs() error {+ for _, d := range []string{p.Root, p.Cache} {+ if err := os.MkdirAll(d, 0o700); err != nil {+ return fmt.Errorf("创建目录 %s: %w", d, err)+ }+ }+ return nil+}++// ─────────────────────────── 读写 ───────────────────────────++// Load 读取配置;文件不存在时写入并返回默认配置。+func Load(p Paths) (Config, error) {+ data, err := os.ReadFile(p.Config)+ if os.IsNotExist(err) {+ c := Default()+ if err := Save(p, c); err != nil {+ return c, err+ }+ return c, nil+ }+ if err != nil {+ return Config{}, fmt.Errorf("读取配置: %w", err)+ }++ c := Default() // 以默认值打底,缺失字段自动继承+ if err := json.Unmarshal(data, &c); err != nil {+ return Config{}, fmt.Errorf("解析配置 %s: %w", p.Config, err)+ }+ c.Validate()+ return c, nil+}++func Save(p Paths, c Config) error {+ if err := p.EnsureDirs(); err != nil {+ return err+ }+ data, err := json.MarshalIndent(c, "", " ")+ if err != nil {+ return err+ }+ // 先写临时文件再改名,避免写一半断电留下损坏的配置+ tmp := p.Config + ".tmp"+ if err := os.WriteFile(tmp, data, 0o600); err != nil {+ return err+ }+ return os.Rename(tmp, p.Config)+}++// ─────────────────────────── Duration ───────────────────────────++// Duration 让 time.Duration 在 JSON 里表现为 "72h" 这样的可读字符串,+// 而不是一长串纳秒整数——配置文件是给人看的。+type Duration time.Duration++func (d Duration) MarshalJSON() ([]byte, error) {+ return json.Marshal(time.Duration(d).String())+}++func (d *Duration) UnmarshalJSON(b []byte) error {+ var v any+ if err := json.Unmarshal(b, &v); err != nil {+ return err+ }+ switch value := v.(type) {+ case string:+ parsed, err := time.ParseDuration(value)+ if err != nil {+ return fmt.Errorf("无法解析时长 %q: %w", value, err)+ }+ *d = Duration(parsed)+ case float64: // 兼容手写成秒数的情况+ *d = Duration(time.Duration(value) * time.Second)+ default:+ return fmt.Errorf("时长字段类型不支持: %T", v)+ }+ return nil+}++func (d Duration) Std() time.Duration { return time.Duration(d) }diff --git a/client-core/internal/config/config_test.go b/client-core/internal/config/config_test.gonew file mode 100644index 0000000..3b80fb4--- /dev/null+++ b/client-core/internal/config/config_test.go@@ -0,0 +1,193 @@+package config++import (+ "encoding/json"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++func TestLoadCreatesDefaultsWhenMissing(t *testing.T) {+ p := PathsUnder(t.TempDir())+ cfg, err := Load(p)+ if err != nil {+ t.Fatalf("加载: %v", err)+ }+ if cfg.AutoSyncThresholdBytes != 50<<20 {+ t.Errorf("默认阈值 = %d,期望 50 MiB", cfg.AutoSyncThresholdBytes)+ }+ // 首次加载应把默认配置写盘,用户才能看到有哪些可调项+ if _, err := os.Stat(p.Config); err != nil {+ t.Errorf("默认配置未落盘: %v", err)+ }+}++// 新增配置项时,老配置文件里没有该字段,必须继承默认值而不是零值。+func TestLoadInheritsDefaultsForMissingFields(t *testing.T) {+ p := PathsUnder(t.TempDir())+ if err := p.EnsureDirs(); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(p.Config,+ []byte(`{"device_name":"我的电脑"}`), 0o600); err != nil {+ t.Fatal(err)+ }++ cfg, err := Load(p)+ if err != nil {+ t.Fatalf("加载: %v", err)+ }+ if cfg.DeviceName != "我的电脑" {+ t.Errorf("设备名 = %q", cfg.DeviceName)+ }+ if cfg.AutoSyncThresholdBytes != 50<<20 {+ t.Errorf("缺失字段未继承默认值: %d", cfg.AutoSyncThresholdBytes)+ }+ if !cfg.SyncText {+ t.Error("缺失的布尔项未继承默认值 true")+ }+}++func TestSaveLoadRoundTrip(t *testing.T) {+ p := PathsUnder(t.TempDir())+ want := Default()+ want.DeviceName = "测试设备"+ want.SignalingURL = "wss://example.com/signal"+ want.HistoryTTL = Duration(6 * time.Hour)++ if err := Save(p, want); err != nil {+ t.Fatalf("保存: %v", err)+ }+ got, err := Load(p)+ if err != nil {+ t.Fatalf("加载: %v", err)+ }+ if got.DeviceName != want.DeviceName || got.SignalingURL != want.SignalingURL {+ t.Errorf("往返后不一致: %+v", got)+ }+ if got.HistoryTTL.Std() != 6*time.Hour {+ t.Errorf("时长往返失败: %v", got.HistoryTTL.Std())+ }+}++// 时长写成 "72h" 而非纳秒整数——配置文件是给人读和改的。+func TestDurationIsHumanReadableInJSON(t *testing.T) {+ data, err := json.Marshal(Duration(72 * time.Hour))+ if err != nil {+ t.Fatal(err)+ }+ if string(data) != `"72h0m0s"` {+ t.Errorf("序列化结果 = %s,期望可读字符串", data)+ }++ p := PathsUnder(t.TempDir())+ if err := Save(p, Default()); err != nil {+ t.Fatal(err)+ }+ raw, _ := os.ReadFile(p.Config)+ if strings.Contains(string(raw), "259200000000000") {+ t.Error("配置文件里出现了纳秒整数,应为可读时长")+ }+}++func TestDurationAcceptsSeconds(t *testing.T) {+ // 手写配置时可能直接写数字,按秒解释比报错友好+ var d Duration+ if err := json.Unmarshal([]byte(`90`), &d); err != nil {+ t.Fatalf("解析数字失败: %v", err)+ }+ if d.Std() != 90*time.Second {+ t.Errorf("= %v,期望 90s", d.Std())+ }++ if err := json.Unmarshal([]byte(`"bad"`), &d); err == nil {+ t.Error("非法时长字符串应当报错")+ }+}++func TestValidateClampsBadValues(t *testing.T) {+ c := Config{+ DeviceName: "",+ SignalingURL: "",+ AutoSyncThresholdBytes: -1,+ HistoryTTL: Duration(time.Second), // 过短+ CacheTTL: Duration(0),+ }+ c.Validate()++ if c.DeviceName == "" || c.SignalingURL == "" {+ t.Error("空值未被补为默认值")+ }+ if c.AutoSyncThresholdBytes <= 0 {+ t.Errorf("负阈值未被修正: %d", c.AutoSyncThresholdBytes)+ }+ // TTL 过短会让 GC 立刻删掉刚写入的记录+ if c.HistoryTTL.Std() < time.Minute {+ t.Errorf("过短的 history_ttl 未被修正: %v", c.HistoryTTL.Std())+ }+}++// 缓存活得比记录久没有意义:记录没了就再也找不到那些文件。+func TestValidateCapsCacheTTLByHistoryTTL(t *testing.T) {+ c := Default()+ c.HistoryTTL = Duration(time.Hour)+ c.CacheTTL = Duration(24 * time.Hour)+ c.Validate()++ if c.CacheTTL > c.HistoryTTL {+ t.Errorf("cache_ttl (%v) 不应超过 history_ttl (%v)",+ c.CacheTTL.Std(), c.HistoryTTL.Std())+ }+}++func TestLoadRejectsCorruptFile(t *testing.T) {+ p := PathsUnder(t.TempDir())+ if err := p.EnsureDirs(); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(p.Config, []byte("{ 这不是 json"), 0o600); err != nil {+ t.Fatal(err)+ }+ if _, err := Load(p); err == nil {+ t.Error("损坏的配置文件应当报错,而不是静默用默认值覆盖用户设置")+ }+}++func TestPathsLayout(t *testing.T) {+ root := t.TempDir()+ p := PathsUnder(root)++ if p.Cache != filepath.Join(root, "cache") {+ t.Errorf("缓存目录 = %q", p.Cache)+ }+ if filepath.Base(p.Endpoint) != "daemon.json" {+ t.Errorf("endpoint 文件名 = %q,UI 依赖这个约定", p.Endpoint)+ }+ if err := p.EnsureDirs(); err != nil {+ t.Fatal(err)+ }+ info, err := os.Stat(p.Cache)+ if err != nil {+ t.Fatal(err)+ }+ // 缓存里是用户复制过的文件,不该让同机其他用户读到+ if perm := info.Mode().Perm(); perm != 0o700 {+ t.Errorf("缓存目录权限 = %o,期望 0700", perm)+ }+}++func TestSaveWritesPrivatePermissions(t *testing.T) {+ p := PathsUnder(t.TempDir())+ if err := Save(p, Default()); err != nil {+ t.Fatal(err)+ }+ info, err := os.Stat(p.Config)+ if err != nil {+ t.Fatal(err)+ }+ if perm := info.Mode().Perm(); perm != 0o600 {+ t.Errorf("配置文件权限 = %o,期望 0600", perm)+ }+}diff --git a/client-core/internal/gc/gc.go b/client-core/internal/gc/gc.gonew file mode 100644index 0000000..751db90--- /dev/null+++ b/client-core/internal/gc/gc.go@@ -0,0 +1,180 @@+// Package gc 回收过期的记录与缓存文件。+//+// 记录和文件分别存放在数据库与磁盘上,两者可能因进程崩溃或事务回滚而失配,+// 因此回收是双向的:既按记录删文件,也扫描磁盘清掉无人引用的孤儿目录。+package gc++import (+ "context"+ "log/slog"+ "time"++ "github.com/baiyuze/copysync/client-core/internal/cache"+ "github.com/baiyuze/copysync/client-core/internal/config"+ "github.com/baiyuze/copysync/client-core/internal/store"+)++// 启动后先等一会儿再首次回收:此时 daemon 正在建连、恢复状态,+// 没必要和它抢 I/O。+const (+ startupDelay = 20 * time.Second+ interval = time.Hour+)++type Collector struct {+ log *slog.Logger+ store *store.Store+ cache *cache.Cache+ loadConfig func() config.Config+ onRemoved func(ids []string)+ // 便于测试注入假时钟+ now func() time.Time+}++type Options struct {+ Logger *slog.Logger+ Store *store.Store+ Cache *cache.Cache+ LoadConfig func() config.Config+ OnRemoved func(ids []string)+}++func New(opts Options) *Collector {+ log := opts.Logger+ if log == nil {+ log = slog.Default()+ }+ return &Collector{+ log: log,+ store: opts.Store,+ cache: opts.Cache,+ loadConfig: opts.LoadConfig,+ onRemoved: opts.OnRemoved,+ now: time.Now,+ }+}++// Run 周期性回收,直到 ctx 取消。+func (c *Collector) Run(ctx context.Context) {+ select {+ case <-ctx.Done():+ return+ case <-time.After(startupDelay):+ }+ c.Collect()++ t := time.NewTicker(interval)+ defer t.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-t.C:+ c.Collect()+ }+ }+}++// Result 汇报一次回收的成果。+type Result struct {+ RecordsRemoved int+ CachesRemoved int+ OrphansRemoved int+}++// Collect 执行一次完整回收。+func (c *Collector) Collect() Result {+ var res Result+ now := c.now()++ // ── 第一步:删除过期记录及其缓存 ──+ expired, err := c.store.ExpiredClips(now)+ if err != nil {+ c.log.Warn("查询过期记录失败", "err", err)+ return res+ }++ ids := make([]string, 0, len(expired))+ for _, clip := range expired {+ if clip.CachePath != "" {+ if err := c.cache.Remove(clip.CachePath); err != nil {+ c.log.Warn("删除缓存失败", "clip", clip.ID, "err", err)+ } else {+ res.CachesRemoved+++ }+ }+ ids = append(ids, clip.ID)+ }+ if len(ids) > 0 {+ // 先删文件再删记录:反过来一旦中途失败,文件就永远没人认领了+ if err := c.store.DeleteClips(ids); err != nil {+ c.log.Warn("删除过期记录失败", "err", err)+ } else {+ res.RecordsRemoved = len(ids)+ if c.onRemoved != nil {+ c.onRemoved(ids)+ }+ }+ }++ // ── 第二步:清理仅缓存过期、但记录仍在有效期内的内容 ──+ // cache_ttl 可以短于 history_ttl:记录留着让用户看得见历史,+ // 但占地方的文件先腾出来,需要时可重新拉取。+ cfg := c.loadConfig()+ if cfg.CacheTTL < cfg.HistoryTTL {+ res.CachesRemoved += c.expireStaleCaches(now, cfg.CacheTTL.Std())+ }++ // ── 第三步:与磁盘对账,清掉无人引用的孤儿目录 ──+ referenced, err := c.store.CachePaths()+ if err != nil {+ c.log.Warn("读取缓存引用失败", "err", err)+ } else {+ orphans, err := c.cache.Orphans(referenced)+ if err != nil {+ c.log.Warn("扫描孤儿缓存失败", "err", err)+ } else {+ for _, o := range orphans {+ if err := c.cache.Remove(o); err == nil {+ res.OrphansRemoved+++ }+ }+ }+ }++ if res.RecordsRemoved+res.CachesRemoved+res.OrphansRemoved > 0 {+ c.log.Info("已回收过期内容",+ "记录", res.RecordsRemoved,+ "缓存", res.CachesRemoved,+ "孤儿目录", res.OrphansRemoved)+ }+ return res+}++// expireStaleCaches 释放超过 cacheTTL 的缓存文件,但保留记录本身。+func (c *Collector) expireStaleCaches(now time.Time, cacheTTL time.Duration) int {+ clips, err := c.store.ListClips(500, time.Time{}, store.KindUnspecified)+ if err != nil {+ c.log.Warn("读取记录失败", "err", err)+ return 0+ }++ var removed int+ cutoff := now.Add(-cacheTTL)+ for _, clip := range clips {+ if clip.CachePath == "" || clip.CreatedAt.After(cutoff) {+ continue+ }+ // 本机复制的记录指向用户自己的原始文件,缓存目录里通常没东西;+ // 即便有(比如截图),删掉也只影响对端再次拉取。+ if err := c.cache.Remove(clip.CachePath); err != nil {+ continue+ }+ removed+++ // 标记为已过期:记录仍在列表里可见,但点击时会提示内容已被清理+ if err := c.store.SetClipStatus(clip.ID, store.StatusExpired, "缓存已过期清理"); err != nil {+ c.log.Debug("更新过期状态失败", "clip", clip.ID, "err", err)+ }+ }+ return removed+}diff --git a/client-core/internal/identity/identity.go b/client-core/internal/identity/identity.gonew file mode 100644index 0000000..eba1656--- /dev/null+++ b/client-core/internal/identity/identity.go@@ -0,0 +1,116 @@+// Package identity 管理本机的 Ed25519 设备身份。+//+// 设备身份是整套安全模型的根:配对时双方交换公钥并由用户肉眼核对指纹,+// 之后所有经信令服务器转发的消息都带签名。服务器因此无法伪造 peer,+// 也就无法对 P2P 握手做中间人攻击。+package identity++import (+ "crypto/ed25519"+ "crypto/rand"+ "encoding/json"+ "fmt"+ "os"+ "path/filepath"++ "github.com/baiyuze/copysync/proto/deviceid"+)++type Identity struct {+ DeviceID string+ PublicKey ed25519.PublicKey+ privateKey ed25519.PrivateKey+}++// 磁盘格式。私钥以 0600 权限存放在用户目录下——与 Syncthing 等+// 同类工具一致。后续可换成 Keychain / DPAPI,接口不变。+type keyFile struct {+ DeviceID string `json:"device_id"`+ PublicKey []byte `json:"public_key"`+ PrivateKey []byte `json:"private_key"`+}++// LoadOrCreate 读取已有身份;不存在则生成一份并落盘。+func LoadOrCreate(path string) (*Identity, error) {+ data, err := os.ReadFile(path)+ switch {+ case err == nil:+ var kf keyFile+ if err := json.Unmarshal(data, &kf); err != nil {+ return nil, fmt.Errorf("解析身份文件 %s: %w", path, err)+ }+ if len(kf.PrivateKey) != ed25519.PrivateKeySize ||+ len(kf.PublicKey) != ed25519.PublicKeySize {+ return nil, fmt.Errorf("身份文件 %s 已损坏(密钥长度不对)", path)+ }+ id := &Identity{+ DeviceID: kf.DeviceID,+ PublicKey: kf.PublicKey,+ privateKey: kf.PrivateKey,+ }+ // 防御损坏或被篡改的文件:ID 必须能由公钥推出+ if want := DeviceIDFor(id.PublicKey); want != id.DeviceID {+ return nil, fmt.Errorf("身份文件 %s 的 device_id 与公钥不匹配", path)+ }+ return id, nil++ case os.IsNotExist(err):+ return create(path)++ default:+ return nil, fmt.Errorf("读取身份文件: %w", err)+ }+}++func create(path string) (*Identity, error) {+ pub, priv, err := ed25519.GenerateKey(rand.Reader)+ if err != nil {+ return nil, fmt.Errorf("生成密钥: %w", err)+ }+ id := &Identity{+ DeviceID: DeviceIDFor(pub),+ PublicKey: pub,+ privateKey: priv,+ }++ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {+ return nil, err+ }+ data, err := json.MarshalIndent(keyFile{+ DeviceID: id.DeviceID,+ PublicKey: pub,+ PrivateKey: priv,+ }, "", " ")+ if err != nil {+ return nil, err+ }+ // 0600:私钥只有当前用户可读+ tmp := path + ".tmp"+ if err := os.WriteFile(tmp, data, 0o600); err != nil {+ return nil, fmt.Errorf("写入身份文件: %w", err)+ }+ if err := os.Rename(tmp, path); err != nil {+ return nil, err+ }+ return id, nil+}++func (i *Identity) Sign(data []byte) []byte {+ return ed25519.Sign(i.privateKey, data)+}++func Verify(pub ed25519.PublicKey, data, sig []byte) bool {+ if len(pub) != ed25519.PublicKeySize {+ return false+ }+ return ed25519.Verify(pub, data, sig)+}++// Fingerprint 返回供用户肉眼核对的短指纹,形如 "K7X2-M9PL-4RT8"。+func (i *Identity) Fingerprint() string { return deviceid.Fingerprint(i.PublicKey) }++// 派生规则属于协议契约,与服务器共用同一份实现(proto/deviceid)。+var (+ FingerprintFor = deviceid.Fingerprint+ DeviceIDFor = deviceid.For+)diff --git a/client-core/internal/identity/identity_test.go b/client-core/internal/identity/identity_test.gonew file mode 100644index 0000000..b1fef88--- /dev/null+++ b/client-core/internal/identity/identity_test.go@@ -0,0 +1,166 @@+package identity++import (+ "crypto/ed25519"+ "encoding/json"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/baiyuze/copysync/proto/deviceid"+)++func TestCreateThenLoadIsStable(t *testing.T) {+ path := filepath.Join(t.TempDir(), "identity.json")++ first, err := LoadOrCreate(path)+ if err != nil {+ t.Fatalf("创建身份: %v", err)+ }+ second, err := LoadOrCreate(path)+ if err != nil {+ t.Fatalf("重新加载: %v", err)+ }++ // 身份必须跨重启稳定,否则每次启动都会变成"新设备",已配对关系全失效+ if first.DeviceID != second.DeviceID {+ t.Errorf("device_id 不稳定: %q vs %q", first.DeviceID, second.DeviceID)+ }+ if !first.PublicKey.Equal(second.PublicKey) {+ t.Error("公钥不稳定")+ }+ // 私钥也要能正常加载:签名要能被原公钥验证+ sig := second.Sign([]byte("payload"))+ if !Verify(first.PublicKey, []byte("payload"), sig) {+ t.Error("重新加载后的私钥与原公钥不配对")+ }+}++func TestPrivateKeyFilePermissions(t *testing.T) {+ path := filepath.Join(t.TempDir(), "identity.json")+ if _, err := LoadOrCreate(path); err != nil {+ t.Fatal(err)+ }+ info, err := os.Stat(path)+ if err != nil {+ t.Fatal(err)+ }+ // 文件里是设备私钥,同机其他用户绝不能读到+ if perm := info.Mode().Perm(); perm != 0o600 {+ t.Errorf("身份文件权限 = %o,期望 0600", perm)+ }+}++func TestSignAndVerify(t *testing.T) {+ id, err := LoadOrCreate(filepath.Join(t.TempDir(), "identity.json"))+ if err != nil {+ t.Fatal(err)+ }++ msg := []byte("signal payload")+ sig := id.Sign(msg)++ if !Verify(id.PublicKey, msg, sig) {+ t.Error("自己的签名验证失败")+ }+ if Verify(id.PublicKey, []byte("tampered"), sig) {+ t.Error("篡改后的内容仍通过验签")+ }++ other, _ := LoadOrCreate(filepath.Join(t.TempDir(), "other.json"))+ if Verify(other.PublicKey, msg, sig) {+ t.Error("用他人公钥验签竟然通过了")+ }+ // 长度不对的公钥不能 panic,信令里的公钥是对端传来的+ if Verify(ed25519.PublicKey("short"), msg, sig) {+ t.Error("非法长度的公钥应当直接判定失败")+ }+}++// device_id 由公钥确定性派生,服务器据此校验"这个 ID 确实属于这把公钥"。+// 客户端与服务器必须用同一套规则,否则设备根本连不上。+func TestDeviceIDDerivationMatchesSharedRule(t *testing.T) {+ id, err := LoadOrCreate(filepath.Join(t.TempDir(), "identity.json"))+ if err != nil {+ t.Fatal(err)+ }+ if id.DeviceID != deviceid.For(id.PublicKey) {+ t.Errorf("device_id 与共享派生规则不一致: %q vs %q",+ id.DeviceID, deviceid.For(id.PublicKey))+ }+ if !deviceid.Valid(id.DeviceID, id.PublicKey) {+ t.Error("自身的 device_id 未通过校验")+ }+ if id.Fingerprint() != deviceid.Fingerprint(id.PublicKey) {+ t.Error("指纹与共享规则不一致")+ }+}++// 指纹要给用户逐字比对,必须短、分组、无易混字符。+func TestFingerprintIsHumanComparable(t *testing.T) {+ id, _ := LoadOrCreate(filepath.Join(t.TempDir(), "identity.json"))+ fp := id.Fingerprint()++ parts := strings.Split(fp, "-")+ if len(parts) != 3 {+ t.Errorf("指纹 = %q,期望三段分组便于朗读", fp)+ }+ for _, p := range parts {+ if len(p) != 4 {+ t.Errorf("分段 %q 长度应为 4", p)+ }+ }+ // Base32 字符集不含 0/1/8/9,避免与 O/I/B/g 混淆+ for _, bad := range []rune{'0', '1', '8', '9'} {+ if strings.ContainsRune(fp, bad) {+ t.Errorf("指纹含易混字符 %q: %s", bad, fp)+ }+ }+}++// 身份文件被篡改(换了公钥但留着旧 ID)时必须拒绝加载,+// 否则会用一个与公钥不匹配的 ID 去连服务器,且永远连不上。+func TestTamperedIdentityRejected(t *testing.T) {+ path := filepath.Join(t.TempDir(), "identity.json")+ if _, err := LoadOrCreate(path); err != nil {+ t.Fatal(err)+ }++ raw, _ := os.ReadFile(path)+ var kf keyFile+ if err := json.Unmarshal(raw, &kf); err != nil {+ t.Fatal(err)+ }+ kf.DeviceID = "someoneelsesdeviceid"+ patched, _ := json.Marshal(kf)+ if err := os.WriteFile(path, patched, 0o600); err != nil {+ t.Fatal(err)+ }++ if _, err := LoadOrCreate(path); err == nil {+ t.Error("device_id 与公钥不匹配的身份文件应被拒绝")+ }+}++func TestCorruptIdentityRejected(t *testing.T) {+ path := filepath.Join(t.TempDir(), "identity.json")+ if err := os.WriteFile(path, []byte(`{"device_id":"x","public_key":"AAAA"}`), 0o600); err != nil {+ t.Fatal(err)+ }+ if _, err := LoadOrCreate(path); err == nil {+ t.Error("密钥长度不合法的文件应被拒绝")+ }+}++func TestDistinctDevicesGetDistinctIDs(t *testing.T) {+ a, _ := LoadOrCreate(filepath.Join(t.TempDir(), "a.json"))+ b, _ := LoadOrCreate(filepath.Join(t.TempDir(), "b.json"))++ if a.DeviceID == b.DeviceID {+ t.Error("两台设备生成了相同的 device_id")+ }+ if a.Fingerprint() == b.Fingerprint() {+ t.Error("两台设备生成了相同的指纹,用户将无法通过比对发现异常")+ }+}diff --git a/client-core/internal/pack/pack.go b/client-core/internal/pack/pack.gonew file mode 100644index 0000000..6e50227--- /dev/null+++ b/client-core/internal/pack/pack.go@@ -0,0 +1,249 @@+// Package pack 负责文件的流式打包与解包。+//+// 全程流式:边遍历边压缩边写出,不在内存或磁盘上留完整副本。+// 复制一个 2GB 的文件夹时,这决定了是立刻开始传输还是先卡住几分钟。+package pack++import (+ "archive/tar"+ "fmt"+ "io"+ "os"+ "path/filepath"+ "strings"++ "github.com/klauspost/compress/zstd"+)++// Stats 描述一次打包的规模,用于在传输前告知对端与界面。+type Stats struct {+ Files int+ Dirs int+ Bytes int64+}++// Scan 预扫描待传内容的规模。+//+// 用于在发送前给出总量,让进度条有分母。大目录扫描本身要耗时,+// 因此限制条目数上限,超出即停止并返回已统计的部分。+func Scan(paths []string, maxEntries int) (Stats, error) {+ var s Stats+ for _, root := range paths {+ err := filepath.Walk(root, func(_ string, info os.FileInfo, err error) error {+ if err != nil {+ return nil // 个别文件读不到不该中断整次扫描+ }+ if info.IsDir() {+ s.Dirs+++ } else {+ s.Files+++ s.Bytes += info.Size()+ }+ if maxEntries > 0 && s.Files+s.Dirs >= maxEntries {+ return errTooMany+ }+ return nil+ })+ if err == errTooMany {+ return s, nil // 只是规模超限,不是错误+ }+ if err != nil {+ return s, err+ }+ }+ return s, nil+}++var errTooMany = fmt.Errorf("条目数超过上限")++// Pack 把若干路径打包成 tar+zstd 流写入 w。+//+// 目录会被递归打包;多个路径各自作为顶层条目,+// 因此对端解包后能还原出与复制时相同的结构。+func Pack(w io.Writer, paths []string) error {+ enc, err := zstd.NewWriter(w,+ // 同步文件传输更看重速度而非极致压缩比——+ // 多数待传内容(图片、压缩包、二进制)本来就压不动。+ zstd.WithEncoderLevel(zstd.SpeedFastest))+ if err != nil {+ return fmt.Errorf("创建压缩流: %w", err)+ }+ defer enc.Close()++ tw := tar.NewWriter(enc)+ defer tw.Close()++ for _, p := range paths {+ if err := addPath(tw, p); err != nil {+ return err+ }+ }+ if err := tw.Close(); err != nil {+ return fmt.Errorf("关闭 tar 流: %w", err)+ }+ return enc.Close()+}++func addPath(tw *tar.Writer, root string) error {+ info, err := os.Lstat(root)+ if err != nil {+ return fmt.Errorf("读取 %s: %w", root, err)+ }+ // 以被复制项自身为顶层名,不带上它在源机器上的完整路径+ base := filepath.Base(root)++ if !info.IsDir() {+ return addFile(tw, root, base, info)+ }++ return filepath.Walk(root, func(path string, info os.FileInfo, err error) error {+ if err != nil {+ return nil // 跳过读不了的条目,尽量把能传的传过去+ }+ rel, err := filepath.Rel(root, path)+ if err != nil {+ return err+ }+ name := base+ if rel != "." {+ name = filepath.Join(base, rel)+ }+ return addFile(tw, path, name, info)+ })+}++func addFile(tw *tar.Writer, path, name string, info os.FileInfo) error {+ // 符号链接按链接本身打包,不跟随——跟随可能把整个外部目录卷进来+ var link string+ if info.Mode()&os.ModeSymlink != 0 {+ var err error+ if link, err = os.Readlink(path); err != nil {+ return nil+ }+ }++ hdr, err := tar.FileInfoHeader(info, link)+ if err != nil {+ return fmt.Errorf("构造 tar 头 %s: %w", path, err)+ }+ // tar 内统一用正斜杠,保证 Windows 与 macOS 之间可互解+ hdr.Name = filepath.ToSlash(name)+ if info.IsDir() {+ hdr.Name += "/"+ }++ if err := tw.WriteHeader(hdr); err != nil {+ return fmt.Errorf("写 tar 头 %s: %w", name, err)+ }+ if !info.Mode().IsRegular() {+ return nil // 目录与符号链接没有内容体+ }++ f, err := os.Open(path)+ if err != nil {+ return nil // 打开失败就跳过,不因单个文件中断整次传输+ }+ defer f.Close()++ if _, err := io.Copy(tw, f); err != nil {+ return fmt.Errorf("写入 %s 内容: %w", name, err)+ }+ return nil+}++// Unpack 把 tar+zstd 流解到 destDir,返回顶层条目的绝对路径。+//+// 返回顶层条目是因为写入剪贴板时需要的正是这些路径——+// 用户复制的是"这几个文件",粘贴出来也该是这几个。+func Unpack(r io.Reader, destDir string) ([]string, error) {+ if err := os.MkdirAll(destDir, 0o700); err != nil {+ return nil, err+ }++ dec, err := zstd.NewReader(r)+ if err != nil {+ return nil, fmt.Errorf("创建解压流: %w", err)+ }+ defer dec.Close()++ tr := tar.NewReader(dec)+ seen := make(map[string]struct{})+ var tops []string++ for {+ hdr, err := tr.Next()+ if err == io.EOF {+ break+ }+ if err != nil {+ return tops, fmt.Errorf("读取 tar 条目: %w", err)+ }++ target, err := safeJoin(destDir, hdr.Name)+ if err != nil {+ return tops, err+ }++ // 记录顶层条目,供写入剪贴板使用+ if top := topLevel(hdr.Name); top != "" {+ if _, ok := seen[top]; !ok {+ seen[top] = struct{}{}+ tops = append(tops, filepath.Join(destDir, top))+ }+ }++ switch hdr.Typeflag {+ case tar.TypeDir:+ if err := os.MkdirAll(target, 0o700); err != nil {+ return tops, err+ }+ case tar.TypeSymlink:+ os.Remove(target)+ if err := os.Symlink(hdr.Linkname, target); err != nil {+ return tops, fmt.Errorf("创建符号链接 %s: %w", target, err)+ }+ case tar.TypeReg:+ if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil {+ return tops, err+ }+ f, err := os.OpenFile(target,+ os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(hdr.Mode).Perm())+ if err != nil {+ return tops, fmt.Errorf("创建 %s: %w", target, err)+ }+ if _, err := io.Copy(f, tr); err != nil {+ f.Close()+ return tops, fmt.Errorf("写入 %s: %w", target, err)+ }+ f.Close()+ }+ }+ return tops, nil+}++// safeJoin 阻止 tar 条目用 ../ 逃出目标目录(Zip Slip)。+//+// 归档来自对端设备,即便已配对也不该无条件信任其中的路径。+func safeJoin(base, name string) (string, error) {+ clean := filepath.Clean(filepath.FromSlash(name))+ if filepath.IsAbs(clean) || strings.HasPrefix(clean, "..") {+ return "", fmt.Errorf("归档中含非法路径: %q", name)+ }+ target := filepath.Join(base, clean)+ if !strings.HasPrefix(target, filepath.Clean(base)+string(os.PathSeparator)) &&+ target != filepath.Clean(base) {+ return "", fmt.Errorf("归档条目逃出目标目录: %q", name)+ }+ return target, nil+}++func topLevel(name string) string {+ clean := strings.TrimPrefix(filepath.ToSlash(filepath.Clean(filepath.FromSlash(name))), "./")+ if clean == "." || clean == "" {+ return ""+ }+ if i := strings.Index(clean, "/"); i > 0 {+ return clean[:i]+ }+ return clean+}diff --git a/client-core/internal/pack/pack_test.go b/client-core/internal/pack/pack_test.gonew file mode 100644index 0000000..15f71bd--- /dev/null+++ b/client-core/internal/pack/pack_test.go@@ -0,0 +1,203 @@+package pack++import (+ "bytes"+ "os"+ "path/filepath"+ "sort"+ "testing"+)++func writeFile(t *testing.T, path, content string) {+ t.Helper()+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, []byte(content), 0o600); err != nil {+ t.Fatal(err)+ }+}++func TestPackUnpackSingleFile(t *testing.T) {+ src := t.TempDir()+ file := filepath.Join(src, "hello.txt")+ writeFile(t, file, "hello copysync")++ var buf bytes.Buffer+ if err := Pack(&buf, []string{file}); err != nil {+ t.Fatalf("打包: %v", err)+ }+ if buf.Len() == 0 {+ t.Fatal("打包结果为空")+ }++ dst := t.TempDir()+ tops, err := Unpack(&buf, dst)+ if err != nil {+ t.Fatalf("解包: %v", err)+ }++ // 顶层条目是写入剪贴板时要用的路径,缺了它对端就无从粘贴+ if len(tops) != 1 {+ t.Fatalf("顶层条目数 = %d,期望 1;实际 %v", len(tops), tops)+ }+ if filepath.Base(tops[0]) != "hello.txt" {+ t.Errorf("顶层条目 = %q,期望 hello.txt", tops[0])+ }++ got, err := os.ReadFile(filepath.Join(dst, "hello.txt"))+ if err != nil {+ t.Fatalf("读取解包结果: %v", err)+ }+ if string(got) != "hello copysync" {+ t.Errorf("内容 = %q,期望 %q", got, "hello copysync")+ }+}++func TestPackUnpackDirectory(t *testing.T) {+ src := t.TempDir()+ root := filepath.Join(src, "docs")+ writeFile(t, filepath.Join(root, "a.txt"), "AAA")+ writeFile(t, filepath.Join(root, "sub", "b.txt"), "BBB")++ var buf bytes.Buffer+ if err := Pack(&buf, []string{root}); err != nil {+ t.Fatalf("打包: %v", err)+ }++ dst := t.TempDir()+ tops, err := Unpack(&buf, dst)+ if err != nil {+ t.Fatalf("解包: %v", err)+ }+ if len(tops) != 1 || filepath.Base(tops[0]) != "docs" {+ t.Fatalf("顶层条目 = %v,期望只有 docs", tops)+ }++ // 目录结构要原样还原,用户复制的是什么,粘贴出来就该是什么+ for path, want := range map[string]string{+ filepath.Join(dst, "docs", "a.txt"): "AAA",+ filepath.Join(dst, "docs", "sub", "b.txt"): "BBB",+ } {+ got, err := os.ReadFile(path)+ if err != nil {+ t.Errorf("缺少 %s: %v", path, err)+ continue+ }+ if string(got) != want {+ t.Errorf("%s 内容 = %q,期望 %q", path, got, want)+ }+ }+}++func TestPackMultipleTopLevelEntries(t *testing.T) {+ src := t.TempDir()+ f1 := filepath.Join(src, "one.txt")+ f2 := filepath.Join(src, "two.txt")+ dir := filepath.Join(src, "folder")+ writeFile(t, f1, "1")+ writeFile(t, f2, "2")+ writeFile(t, filepath.Join(dir, "inner.txt"), "3")++ var buf bytes.Buffer+ if err := Pack(&buf, []string{f1, f2, dir}); err != nil {+ t.Fatalf("打包: %v", err)+ }++ dst := t.TempDir()+ tops, err := Unpack(&buf, dst)+ if err != nil {+ t.Fatalf("解包: %v", err)+ }++ names := make([]string, 0, len(tops))+ for _, p := range tops {+ names = append(names, filepath.Base(p))+ }+ sort.Strings(names)+ want := []string{"folder", "one.txt", "two.txt"}+ if len(names) != 3 || names[0] != want[0] || names[1] != want[1] || names[2] != want[2] {+ t.Errorf("顶层条目 = %v,期望 %v", names, want)+ }+}++func TestPackPreservesEmptyDirectory(t *testing.T) {+ src := t.TempDir()+ root := filepath.Join(src, "empty-root")+ if err := os.MkdirAll(filepath.Join(root, "nothing"), 0o700); err != nil {+ t.Fatal(err)+ }++ var buf bytes.Buffer+ if err := Pack(&buf, []string{root}); err != nil {+ t.Fatalf("打包: %v", err)+ }+ dst := t.TempDir()+ if _, err := Unpack(&buf, dst); err != nil {+ t.Fatalf("解包: %v", err)+ }+ if _, err := os.Stat(filepath.Join(dst, "empty-root", "nothing")); err != nil {+ t.Errorf("空目录未被还原: %v", err)+ }+}++// 归档来自对端设备,不能因为已配对就无条件信任其中的路径。+func TestUnpackRejectsPathEscape(t *testing.T) {+ for _, name := range []string{"../evil.txt", "/etc/passwd", "a/../../evil"} {+ if _, err := safeJoin("/tmp/base", name); err == nil {+ t.Errorf("路径 %q 应被拒绝", name)+ }+ }+ // 正常路径仍要放行+ if _, err := safeJoin("/tmp/base", "docs/a.txt"); err != nil {+ t.Errorf("正常路径被误拒: %v", err)+ }+}++func TestScanCountsBytes(t *testing.T) {+ src := t.TempDir()+ writeFile(t, filepath.Join(src, "a.txt"), "12345")+ writeFile(t, filepath.Join(src, "sub", "b.txt"), "678")++ s, err := Scan([]string{src}, 0)+ if err != nil {+ t.Fatalf("扫描: %v", err)+ }+ if s.Files != 2 {+ t.Errorf("文件数 = %d,期望 2", s.Files)+ }+ if s.Bytes != 8 {+ t.Errorf("字节数 = %d,期望 8", s.Bytes)+ }+}++// 超大目录全量扫描会让复制动作明显卡顿,因此要能在达到上限时及时收手。+func TestScanRespectsLimit(t *testing.T) {+ src := t.TempDir()+ for i := range 50 {+ writeFile(t, filepath.Join(src, string(rune('a'+i%26))+string(rune('0'+i/26))+".txt"), "x")+ }+ s, err := Scan([]string{src}, 10)+ if err != nil {+ t.Fatalf("扫描: %v", err)+ }+ if s.Files+s.Dirs > 12 { // 允许少量越界:上限在遍历回调里判定+ t.Errorf("扫描条目 = %d,未在上限附近停止", s.Files+s.Dirs)+ }+}++func TestTopLevel(t *testing.T) {+ cases := map[string]string{+ "hello.txt": "hello.txt",+ "docs/": "docs",+ "docs/a.txt": "docs",+ "docs/sub/b.txt": "docs",+ "./hello.txt": "hello.txt",+ ".": "",+ }+ for in, want := range cases {+ if got := topLevel(in); got != want {+ t.Errorf("topLevel(%q) = %q,期望 %q", in, got, want)+ }+ }+}diff --git a/client-core/internal/peers/manager.go b/client-core/internal/peers/manager.gonew file mode 100644index 0000000..eecf93b--- /dev/null+++ b/client-core/internal/peers/manager.go@@ -0,0 +1,690 @@+// Package peers 管理已配对设备:配对流程、在线状态、信令收发。+package peers++import (+ "context"+ "crypto/ed25519"+ "crypto/rand"+ "encoding/hex"+ "errors"+ "fmt"+ "log/slog"+ "runtime"+ "sync"+ "time"++ "github.com/baiyuze/copysync/client-core/internal/config"+ "github.com/baiyuze/copysync/client-core/internal/identity"+ "github.com/baiyuze/copysync/client-core/internal/store"+ "github.com/baiyuze/copysync/client-core/internal/transport/p2p"+ "github.com/baiyuze/copysync/client-core/internal/transport/signaling"+ "github.com/baiyuze/copysync/proto/deviceid"+ pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"+)++// pendingPair 是一次等待用户核对指纹的配对。+//+// 配对必须由双方各自确认指纹后才落库:信令服务器能替换转发中的公钥,+// 但无法让两端显示出相同的指纹——用户的肉眼核对是防中间人的最后一道闸。+type pendingPair struct {+ session string+ peer store.Device+ expiresAt time.Time+ // initiated 表示本机是配对码的发起方(对方兑换了我的码)+ initiated bool+}++const pendingTTL = 5 * time.Minute++type Manager struct {+ identity *identity.Identity+ store *store.Store+ log *slog.Logger++ loadConfig func() config.Config+ // 配对关系或在线状态变化时通知上层(推给 UI)+ onDeviceChanged func(*pb.Device)+ // 信令连上/断开、对端上下线时通知上层,UI 的连接状态靠它刷新+ onStatusChanged func()+ // 收到对端信令(SDP/candidate),M2 的 WebRTC 层在此接管+ onSignal func(from string, msg *pb.SignalMessage)++ client *signaling.Client+ p2p *p2p.Manager++ mu sync.RWMutex+ known map[string]store.Device // 已配对设备+ online map[string]bool+ conn map[string]p2p.ConnState // P2P 连接状态(直连/中转)+ pending map[string]*pendingPair // session -> 待确认配对+ // stashed 暂存配对确认前到达的信令,按对端 device_id 归集+ stashed map[string][]*pb.SignalMessage+ // 等待配对码的请求方(CreatePairingCode 是异步的,靠这个回传结果)+ codeWaiters []chan pairingCode+}++type pairingCode struct {+ code string+ expiresAt time.Time+}++type Options struct {+ Identity *identity.Identity+ Store *store.Store+ Logger *slog.Logger+ LoadConfig func() config.Config+ OnDeviceChanged func(*pb.Device)+ OnStatusChanged func()+ OnSignal func(from string, msg *pb.SignalMessage)+ // OnPeerMessage / OnPeerStream 是 P2P 数据面的入口,M4 的同步逻辑挂在这里+ OnPeerMessage func(deviceID string, msg *pb.PeerMessage)+ OnPeerStream func(deviceID, label string, stream *p2p.Stream)+}++func NewManager(opts Options) (*Manager, error) {+ log := opts.Logger+ if log == nil {+ log = slog.Default()+ }++ m := &Manager{+ identity: opts.Identity,+ store: opts.Store,+ log: log,+ loadConfig: opts.LoadConfig,+ onDeviceChanged: opts.OnDeviceChanged,+ onStatusChanged: opts.OnStatusChanged,+ onSignal: opts.OnSignal,+ known: make(map[string]store.Device),+ online: make(map[string]bool),+ conn: make(map[string]p2p.ConnState),+ pending: make(map[string]*pendingPair),+ stashed: make(map[string][]*pb.SignalMessage),+ }++ devices, err := opts.Store.ListDevices()+ if err != nil {+ return nil, fmt.Errorf("读取已配对设备: %w", err)+ }+ for _, d := range devices {+ m.known[d.ID] = d+ }++ m.p2p = p2p.NewManager(p2p.ManagerOptions{+ SelfID: opts.Identity.DeviceID,+ Logger: log,+ SendSignal: m.sendSignal,+ OnState: m.handleP2PState,+ OnMessage: opts.OnPeerMessage,+ OnStream: opts.OnPeerStream,+ })++ m.client = signaling.New(signaling.Options{+ Identity: opts.Identity,+ URL: opts.LoadConfig().SignalingURL,+ Logger: log,+ PublicKeyOf: m.publicKeyOf,+ DeviceInfo: m.deviceInfo,+ Handlers: signaling.Handlers{+ OnConnected: m.handleConnected,+ OnDisconnected: m.handleDisconnected,+ OnPresence: m.handlePresence,+ OnSignal: m.handleSignal,+ OnPairingCreated: m.handlePairingCreated,+ OnPairingRedeemed: m.handlePairingRedeemed,+ OnPairingResult: m.handlePairingResult,+ OnIceConfig: func(servers []*pb.IceServer) {+ m.p2p.SetICEServers(servers)+ },+ OnServerError: func(code, msg string) {+ log.Warn("信令服务器错误", "code", code, "msg", msg)+ },+ },+ })+ return m, nil+}++func (m *Manager) Run(ctx context.Context) {+ go m.gcPending(ctx)+ go m.reconnectLoop(ctx)+ m.client.Run(ctx)+}++// reconnectLoop 定期把"在线但尚未建立 P2P 通道"的对端重新连上。+//+// 单靠上线通知触发连接是不够的:配对刚完成时两端确认有先后,+// 先确认的一方发出的 offer 会被后确认的一方当作未配对消息丢弃;+// 网络切换、信令重连也会让某次握手失败。有了这道巡检,+// 连接状态最终总会收敛,而不需要用户手动重启。+func (m *Manager) reconnectLoop(ctx context.Context) {+ t := time.NewTicker(10 * time.Second)+ defer t.Stop()++ for {+ select {+ case <-ctx.Done():+ return+ case <-t.C:+ m.connectPending(ctx)+ }+ }+}++// connectPending 对所有在线但未连通的对端发起连接。+func (m *Manager) connectPending(ctx context.Context) {+ m.mu.RLock()+ var candidates []string+ for id := range m.known {+ if m.online[id] && m.p2p.State(id) == p2p.StateOffline {+ candidates = append(candidates, id)+ }+ }+ m.mu.RUnlock()++ for _, id := range candidates {+ connectCtx, cancel := context.WithTimeout(ctx, 30*time.Second)+ if err := m.p2p.Connect(connectCtx, id); err != nil {+ m.log.Debug("重连失败,稍后重试", "device", id, "err", err)+ }+ cancel()+ }+}++func (m *Manager) Connected() bool { return m.client.Connected() }++// SetSignalingURL 在用户于设置里改了服务器地址后调用,立即重连。+func (m *Manager) SetSignalingURL(url string) { m.client.SetURL(url) }++// ─────────────────────── 信令回调 ───────────────────────++// publicKeyOf 供信令层验签。+//+// 除已配对设备外,也认待确认配对中的对端公钥——那把公钥已随配对流程+// 取得并校验过与 device_id 相符。能验签不等于信任:是否建立互信仍由+// 用户在 ConfirmPairing 里决定,这里只是让早到的信令不至于被直接丢弃。+func (m *Manager) publicKeyOf(deviceID string) ed25519.PublicKey {+ m.mu.RLock()+ defer m.mu.RUnlock()++ if d, ok := m.known[deviceID]; ok {+ return ed25519.PublicKey(d.PublicKey)+ }+ for _, p := range m.pending {+ if p.peer.ID == deviceID {+ return ed25519.PublicKey(p.peer.PublicKey)+ }+ }+ return nil+}++func (m *Manager) deviceInfo() (name, platform string, paired []string) {+ m.mu.RLock()+ defer m.mu.RUnlock()+ ids := make([]string, 0, len(m.known))+ for id := range m.known {+ ids = append(ids, id)+ }+ return m.loadConfig().DeviceName, runtime.GOOS, ids+}++func (m *Manager) handleConnected() {+ m.log.Info("信令已连接", "url", m.client.URL())+ m.notifyAll()+ m.notifyStatus()+}++func (m *Manager) handleDisconnected(error) {+ m.mu.Lock()+ // 信令断开后无法得知对端状态,一律视为离线+ m.online = make(map[string]bool)+ m.mu.Unlock()+ m.notifyAll()+ m.notifyStatus()+}++func (m *Manager) handlePresence(deviceID string, online bool) {+ m.mu.Lock()+ m.online[deviceID] = online+ m.mu.Unlock()++ m.log.Debug("对端状态变化", "device", deviceID, "online", online)++ if online {+ // 对端上线即建立 P2P 通道,这样真正要传数据时已经就绪。+ // 谁发起由 p2p.Manager 内部按 device_id 字典序决定,这里无脑调用即可。+ go func() {+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()++ // 只在完全没有连接时发起。正在握手中就不要插手——+ // 重置会换掉 ICE ufrag,让对端已经发出的 answer 全部失配。+ if m.p2p.State(deviceID) != p2p.StateOffline {+ return+ }+ if err := m.p2p.Connect(ctx, deviceID); err != nil {+ m.log.Warn("建立 P2P 连接失败", "device", deviceID, "err", err)+ }+ }()+ } else {+ m.p2p.Disconnect(deviceID)+ m.mu.Lock()+ delete(m.conn, deviceID)+ m.mu.Unlock()+ }++ if d, ok := m.device(deviceID); ok {+ m.notify(d)+ }+ m.notifyStatus() // 在线对端数随之变化+}++func (m *Manager) handleSignal(from string, msg *pb.SignalMessage) {+ m.mu.RLock()+ _, paired := m.known[from]+ pendingPair := !paired && m.hasPendingLocked(from)+ m.mu.RUnlock()++ if !paired {+ if pendingPair {+ // 配对尚未确认,但对方已经在发起连接了。+ //+ // 两端确认配对必然有先后,先确认的一方发出的 offer 一定早于+ // 后确认方建立互信。直接丢弃会让握手石沉大海,只能等超时重试;+ // 暂存下来在确认后重放,用户确认完就能立刻连上。+ m.stashSignal(from, msg)+ return+ }+ m.log.Warn("忽略未配对设备的信令", "from", from)+ return+ }++ m.dispatchSignal(from, msg)+}++func (m *Manager) dispatchSignal(from string, msg *pb.SignalMessage) {+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()+ if err := m.p2p.HandleSignal(ctx, from, msg); err != nil {+ m.log.Warn("处理信令失败", "from", from, "err", err)+ }++ if m.onSignal != nil {+ m.onSignal(from, msg)+ }+}++func (m *Manager) hasPendingLocked(deviceID string) bool {+ for _, p := range m.pending {+ if p.peer.ID == deviceID {+ return true+ }+ }+ return false+}++// stashSignal 暂存配对确认前到达的信令。+func (m *Manager) stashSignal(from string, msg *pb.SignalMessage) {+ m.mu.Lock()+ defer m.mu.Unlock()++ // 只留少量:握手信令很快,堆积说明对端在异常重试,没必要全存+ const maxStashed = 32+ if len(m.stashed[from]) >= maxStashed {+ return+ }+ if m.stashed == nil {+ m.stashed = make(map[string][]*pb.SignalMessage)+ }+ m.stashed[from] = append(m.stashed[from], msg)+ m.log.Debug("暂存配对确认前到达的信令", "from", from, "已存", len(m.stashed[from]))+}++// replaySignals 在配对确认后重放暂存的信令。+func (m *Manager) replaySignals(from string) {+ m.mu.Lock()+ msgs := m.stashed[from]+ delete(m.stashed, from)+ m.mu.Unlock()++ if len(msgs) == 0 {+ return+ }+ m.log.Info("重放配对期间暂存的信令", "from", from, "条数", len(msgs))+ for _, msg := range msgs {+ m.dispatchSignal(from, msg)+ }+}++// handleP2PState 在直连/中转状态变化时刷新界面。+func (m *Manager) handleP2PState(deviceID string, state p2p.ConnState) {+ m.mu.Lock()+ m.conn[deviceID] = state+ m.mu.Unlock()++ m.log.Info("P2P 连接状态", "device", deviceID, "state", state)+ if d, ok := m.device(deviceID); ok {+ m.notify(d)+ }+}++func (m *Manager) sendSignal(ctx context.Context, to string, msg *pb.SignalMessage) error {+ return m.client.Signal(ctx, to, msg)+}++// P2P 暴露数据面给上层(M4 的同步逻辑用)。+func (m *Manager) P2P() *p2p.Manager { return m.p2p }++func (m *Manager) handlePairingCreated(code string, expiresAt time.Time) {+ m.mu.Lock()+ waiters := m.codeWaiters+ m.codeWaiters = nil+ m.mu.Unlock()++ for _, ch := range waiters {+ ch <- pairingCode{code, expiresAt}+ close(ch)+ }+}++// handlePairingRedeemed:本机是发起方,有人兑换了我的配对码。+// 同样要经用户确认指纹后才落库。+func (m *Manager) handlePairingRedeemed(ev *pb.PairingRedeemed) {+ m.addPending(store.Device{+ ID: ev.GetPeerDeviceId(),+ Name: ev.GetPeerDeviceName(),+ Platform: ev.GetPeerPlatform(),+ PublicKey: ev.GetPeerPublicKey(),+ }, true)+}++// handlePairingResult:本机是兑换方,拿到了发起方信息。+func (m *Manager) handlePairingResult(ev *pb.PairingRedeemResponse) {+ m.addPending(store.Device{+ ID: ev.GetPeerDeviceId(),+ Name: ev.GetPeerDeviceName(),+ Platform: ev.GetPeerPlatform(),+ PublicKey: ev.GetPeerPublicKey(),+ }, false)+}++func (m *Manager) addPending(peer store.Device, initiated bool) {+ // 校验对端 ID 确由其公钥派生,挡住服务器伪造的 device_id+ if !deviceid.Valid(peer.ID, peer.PublicKey) {+ m.log.Warn("拒绝配对:device_id 与公钥不匹配", "device", peer.ID)+ return+ }++ session := randomToken()+ m.mu.Lock()+ m.pending[session] = &pendingPair{+ session: session,+ peer: peer,+ expiresAt: time.Now().Add(pendingTTL),+ initiated: initiated,+ }+ m.mu.Unlock()++ m.log.Info("等待用户核对配对指纹",+ "peer", peer.Name, "device", peer.ID,+ "fingerprint", deviceid.Fingerprint(peer.PublicKey))++ // 发起方侧是被动收到的,主动推给 UI 让它弹出确认+ if initiated {+ m.notify(m.toProto(peer, false, session))+ }+}++// ─────────────────────── 对外 API ───────────────────────++var (+ ErrNotConnected = errors.New("未连接到信令服务器")+ ErrSessionUnknown = errors.New("配对会话不存在或已过期")+)++// CreatePairingCode 生成配对码。服务器异步返回,这里等待结果。+func (m *Manager) CreatePairingCode(ctx context.Context) (string, time.Time, error) {+ if !m.client.Connected() {+ return "", time.Time{}, ErrNotConnected+ }++ ch := make(chan pairingCode, 1)+ m.mu.Lock()+ m.codeWaiters = append(m.codeWaiters, ch)+ m.mu.Unlock()++ if err := m.client.CreatePairingCode(ctx); err != nil {+ return "", time.Time{}, err+ }++ select {+ case got := <-ch:+ return got.code, got.expiresAt, nil+ case <-ctx.Done():+ return "", time.Time{}, ctx.Err()+ case <-time.After(10 * time.Second):+ return "", time.Time{}, errors.New("等待配对码超时")+ }+}++// RedeemPairingCode 兑换配对码,返回待用户核对的对端信息与会话 ID。+// 此时尚未建立互信——必须再调 ConfirmPairing。+func (m *Manager) RedeemPairingCode(ctx context.Context, code string) (*pb.Device, string, error) {+ if !m.client.Connected() {+ return nil, "", ErrNotConnected+ }+ if err := m.client.RedeemPairingCode(ctx, code); err != nil {+ return nil, "", err+ }++ // 等待服务器回传发起方信息(经 handlePairingResult 落入 pending)+ deadline := time.After(10 * time.Second)+ for {+ select {+ case <-ctx.Done():+ return nil, "", ctx.Err()+ case <-deadline:+ return nil, "", errors.New("兑换配对码超时(配对码可能已失效)")+ case <-time.After(50 * time.Millisecond):+ m.mu.RLock()+ var found *pendingPair+ for _, p := range m.pending {+ if !p.initiated {+ found = p+ break+ }+ }+ m.mu.RUnlock()+ if found != nil {+ return m.toProto(found.peer, false, found.session), found.session, nil+ }+ }+ }+}++// ConfirmPairing 在用户核对指纹后落库,正式建立互信。+func (m *Manager) ConfirmPairing(ctx context.Context, session string, accept bool) error {+ m.mu.Lock()+ p, ok := m.pending[session]+ if ok {+ delete(m.pending, session)+ }+ m.mu.Unlock()++ if !ok {+ return ErrSessionUnknown+ }+ if !accept {+ m.log.Info("用户拒绝配对", "peer", p.peer.Name)+ m.mu.Lock()+ delete(m.stashed, p.peer.ID)+ m.mu.Unlock()+ return nil+ }++ p.peer.PairedAt = time.Now()+ if err := m.store.PutDevice(p.peer); err != nil {+ return fmt.Errorf("保存设备: %w", err)+ }++ m.mu.Lock()+ m.known[p.peer.ID] = p.peer+ m.mu.Unlock()++ m.log.Info("配对成功", "peer", p.peer.Name, "device", p.peer.ID)++ // 让服务器知道我们现在关心这个设备的在线状态+ if err := m.client.RefreshPaired(ctx); err != nil {+ m.log.Warn("刷新关注列表失败", "err", err)+ }+ if d, ok := m.device(p.peer.ID); ok {+ m.notify(d)+ }++ // 先重放对方在本端确认前发来的信令,这样握手能一次成功,+ // 不必等连接超时后再重来一轮。+ m.replaySignals(p.peer.ID)++ // 对方没抢先发起时,由本端补发一次。+ go func() {+ connectCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()+ if m.p2p.State(p.peer.ID) != p2p.StateOffline {+ return+ }+ if err := m.p2p.Connect(connectCtx, p.peer.ID); err != nil {+ m.log.Debug("配对后建立连接失败,将由巡检重试", "err", err)+ }+ }()+ return nil+}++func (m *Manager) Unpair(ctx context.Context, deviceID string) error {+ if err := m.store.DeleteDevice(deviceID); err != nil {+ return err+ }+ m.mu.Lock()+ delete(m.known, deviceID)+ delete(m.online, deviceID)+ m.mu.Unlock()++ if err := m.client.RefreshPaired(ctx); err != nil {+ m.log.Warn("刷新关注列表失败", "err", err)+ }+ m.log.Info("已解除配对", "device", deviceID)+ return nil+}++// Devices 返回本机与所有已配对设备。+func (m *Manager) Devices() (*pb.Device, []*pb.Device) {+ cfg := m.loadConfig()+ self := &pb.Device{+ Id: m.identity.DeviceID,+ Name: cfg.DeviceName,+ Platform: runtime.GOOS,+ Online: m.client.Connected(),+ PublicKeyFingerprint: m.identity.Fingerprint(),+ }++ m.mu.RLock()+ defer m.mu.RUnlock()+ peers := make([]*pb.Device, 0, len(m.known))+ for _, d := range m.known {+ peers = append(peers, m.toProtoLocked(d, m.online[d.ID], ""))+ }+ return self, peers+}++// Signal 向对端发送信令。M2 的 WebRTC 层用它交换 SDP 与 candidate。+func (m *Manager) Signal(ctx context.Context, to string, msg *pb.SignalMessage) error {+ return m.client.Signal(ctx, to, msg)+}++func (m *Manager) IsOnline(deviceID string) bool {+ m.mu.RLock()+ defer m.mu.RUnlock()+ return m.online[deviceID]+}++// ─────────────────────── 内部辅助 ───────────────────────++func (m *Manager) device(deviceID string) (*pb.Device, bool) {+ m.mu.RLock()+ defer m.mu.RUnlock()+ d, ok := m.known[deviceID]+ if !ok {+ return nil, false+ }+ return m.toProtoLocked(d, m.online[deviceID], ""), true+}++func (m *Manager) toProto(d store.Device, online bool, session string) *pb.Device {+ m.mu.RLock()+ defer m.mu.RUnlock()+ return m.toProtoLocked(d, online, session)+}++func (m *Manager) toProtoLocked(d store.Device, online bool, session string) *pb.Device {+ conn := pb.ConnectionKind_CONNECTION_KIND_OFFLINE+ if online {+ // 已有 P2P 通道时显示具体是直连还是中转,便于用户排查网络问题+ conn = m.conn[d.ID].Proto()+ }+ return &pb.Device{+ Id: d.ID,+ Name: d.Name,+ Platform: d.Platform,+ Online: online,+ Connection: conn,+ PublicKeyFingerprint: deviceid.Fingerprint(d.PublicKey),+ PairedAtUnix: d.PairedAt.Unix(),+ PairingSession: session,+ }+}++func (m *Manager) notify(d *pb.Device) {+ if m.onDeviceChanged != nil && d != nil {+ m.onDeviceChanged(d)+ }+}++func (m *Manager) notifyAll() {+ _, peers := m.Devices()+ for _, d := range peers {+ m.notify(d)+ }+}++func (m *Manager) notifyStatus() {+ if m.onStatusChanged != nil {+ m.onStatusChanged()+ }+}++// gcPending 清理用户迟迟未确认的配对会话。+func (m *Manager) gcPending(ctx context.Context) {+ t := time.NewTicker(time.Minute)+ defer t.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case now := <-t.C:+ m.mu.Lock()+ for k, p := range m.pending {+ if now.After(p.expiresAt) {+ delete(m.pending, k)+ }+ }+ m.mu.Unlock()+ }+ }+}++func randomToken() string {+ b := make([]byte, 16)+ if _, err := rand.Read(b); err != nil {+ // 密码学随机源不可用时没有安全的降级方案+ panic(fmt.Sprintf("生成会话 ID 失败: %v", err))+ }+ return hex.EncodeToString(b)+}diff --git a/client-core/internal/rpc/convert.go b/client-core/internal/rpc/convert.gonew file mode 100644index 0000000..36f9268--- /dev/null+++ b/client-core/internal/rpc/convert.go@@ -0,0 +1,104 @@+package rpc++import (+ "time"++ "github.com/baiyuze/copysync/client-core/internal/clipboard"+ "github.com/baiyuze/copysync/client-core/internal/config"+ "github.com/baiyuze/copysync/client-core/internal/store"+ pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"+)++// 内部类型与 proto 类型的互转。store 层刻意不直接用 proto 类型,+// 以免持久化格式被 wire 格式绑死。++func clipToProto(c store.Clip) *pb.ClipRecord {+ items := make([]*pb.ClipItem, 0, len(c.Items))+ for _, it := range c.Items {+ items = append(items, &pb.ClipItem{+ Name: it.Name,+ Size: it.Size,+ IsDir: it.IsDir,+ ContentType: it.ContentType,+ })+ }+ return &pb.ClipRecord{+ Id: c.ID,+ Kind: pb.ClipKind(c.Kind),+ Status: pb.ClipStatus(c.Status),+ OriginDeviceId: c.OriginDeviceID,+ OriginDeviceName: c.OriginDeviceName,+ Outgoing: c.Outgoing,+ Items: items,+ TotalSize: c.TotalSize,+ TextPreview: c.TextPreview,+ CreatedAtUnix: c.CreatedAt.Unix(),+ ExpiresAtUnix: c.ExpiresAt.Unix(),+ Error: c.Error,+ }+}++func configToProto(c config.Config) *pb.Config {+ return &pb.Config{+ AutoSyncThresholdBytes: c.AutoSyncThresholdBytes,+ HistoryTtlSeconds: int64(c.HistoryTTL.Std() / time.Second),+ CacheTtlSeconds: int64(c.CacheTTL.Std() / time.Second),+ SyncText: c.SyncText,+ SyncHtml: c.SyncHTML,+ SyncImage: c.SyncImage,+ SyncFile: c.SyncFile,+ AutoApplyToClipboard: c.AutoApplyToClipboard,+ LaunchAtLogin: c.LaunchAtLogin,+ DeviceName: c.DeviceName,+ SignalingUrl: c.SignalingURL,+ }+}++// configFromProto 以 base 打底再覆盖,这样 UI 只改动部分字段时+// 不会把没填的字段清零(proto3 无法区分"未设置"与"零值")。+func configFromProto(in *pb.Config, base config.Config) config.Config {+ c := base+ if in == nil {+ return c+ }+ if in.GetAutoSyncThresholdBytes() > 0 {+ c.AutoSyncThresholdBytes = in.GetAutoSyncThresholdBytes()+ }+ if in.GetHistoryTtlSeconds() > 0 {+ c.HistoryTTL = config.Duration(time.Duration(in.GetHistoryTtlSeconds()) * time.Second)+ }+ if in.GetCacheTtlSeconds() > 0 {+ c.CacheTTL = config.Duration(time.Duration(in.GetCacheTtlSeconds()) * time.Second)+ }+ if in.GetDeviceName() != "" {+ c.DeviceName = in.GetDeviceName()+ }+ if in.GetSignalingUrl() != "" {+ c.SignalingURL = in.GetSignalingUrl()+ }+ // 布尔项没有"未设置"语义,UI 每次都会带全量值,直接覆盖+ c.SyncText = in.GetSyncText()+ c.SyncHTML = in.GetSyncHtml()+ c.SyncImage = in.GetSyncImage()+ c.SyncFile = in.GetSyncFile()+ c.AutoApplyToClipboard = in.GetAutoApplyToClipboard()+ c.LaunchAtLogin = in.GetLaunchAtLogin()+ return c+}++func permissionToProto(p clipboard.Permission) pb.ClipboardPermission {+ switch p {+ case clipboard.PermissionNotApplicable:+ return pb.ClipboardPermission_CLIPBOARD_PERMISSION_NOT_APPLICABLE+ case clipboard.PermissionDefault:+ return pb.ClipboardPermission_CLIPBOARD_PERMISSION_DEFAULT+ case clipboard.PermissionAsk:+ return pb.ClipboardPermission_CLIPBOARD_PERMISSION_ASK+ case clipboard.PermissionAlwaysAllow:+ return pb.ClipboardPermission_CLIPBOARD_PERMISSION_ALWAYS_ALLOW+ case clipboard.PermissionAlwaysDeny:+ return pb.ClipboardPermission_CLIPBOARD_PERMISSION_ALWAYS_DENY+ default:+ return pb.ClipboardPermission_CLIPBOARD_PERMISSION_UNSPECIFIED+ }+}diff --git a/client-core/internal/rpc/endpoint.go b/client-core/internal/rpc/endpoint.gonew file mode 100644index 0000000..ac4d103--- /dev/null+++ b/client-core/internal/rpc/endpoint.go@@ -0,0 +1,60 @@+package rpc++import (+ "crypto/rand"+ "encoding/hex"+ "encoding/json"+ "fmt"+ "os"+ "path/filepath"+)++// Endpoint 是 daemon 写给 UI 的握手信息。+//+// daemon 监听 127.0.0.1 的随机端口,把端口和一次性 token 写进这个文件+// (权限 0600)。UI 启动时读取它来连接。用 token 是因为本机任何进程都能+// 连上 loopback 端口,仅靠"只监听 127.0.0.1"不足以防止其他程序乱连。+type Endpoint struct {+ Port int `json:"port"`+ Token string `json:"token"`+ PID int `json:"pid"`+ Version string `json:"version"`+}++func NewToken() (string, error) {+ b := make([]byte, 32)+ if _, err := rand.Read(b); err != nil {+ return "", fmt.Errorf("生成 token: %w", err)+ }+ return hex.EncodeToString(b), nil+}++func WriteEndpoint(path string, ep Endpoint) error {+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {+ return err+ }+ data, err := json.MarshalIndent(ep, "", " ")+ if err != nil {+ return err+ }+ tmp := path + ".tmp"+ if err := os.WriteFile(tmp, data, 0o600); err != nil {+ return fmt.Errorf("写入 endpoint 文件: %w", err)+ }+ return os.Rename(tmp, path)+}++func ReadEndpoint(path string) (Endpoint, error) {+ data, err := os.ReadFile(path)+ if err != nil {+ return Endpoint{}, err+ }+ var ep Endpoint+ if err := json.Unmarshal(data, &ep); err != nil {+ return Endpoint{}, fmt.Errorf("解析 endpoint 文件: %w", err)+ }+ return ep, nil+}++// RemoveEndpoint 在 daemon 退出时清理,避免 UI 连到一个已死的端口。+func RemoveEndpoint(path string) { _ = os.Remove(path) }diff --git a/client-core/internal/rpc/hub.go b/client-core/internal/rpc/hub.gonew file mode 100644index 0000000..5b3b283--- /dev/null+++ b/client-core/internal/rpc/hub.go@@ -0,0 +1,90 @@+package rpc++import (+ "sync"++ pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"+)++// Hub 把 daemon 内部发生的事件广播给所有已连接的 UI。+//+// 订阅者是慢速消费者时不能拖垮 daemon:每个订阅者有独立缓冲,+// 满了就丢弃该订阅者的这条事件,而不是阻塞发布方。UI 可以用+// SubscribeRequest.since_unix 重连补齐。+type Hub struct {+ mu sync.Mutex+ subs map[int]chan *pb.Event+ nextID int+}++func NewHub() *Hub {+ return &Hub{subs: make(map[int]chan *pb.Event)}+}++// Subscribe 返回事件通道与取消函数。调用方必须在结束时调用取消函数。+func (h *Hub) Subscribe() (<-chan *pb.Event, func()) {+ h.mu.Lock()+ defer h.mu.Unlock()++ id := h.nextID+ h.nextID+++ ch := make(chan *pb.Event, 64)+ h.subs[id] = ch++ return ch, func() {+ h.mu.Lock()+ defer h.mu.Unlock()+ if c, ok := h.subs[id]; ok {+ delete(h.subs, id)+ close(c)+ }+ }+}++func (h *Hub) Publish(e *pb.Event) {+ h.mu.Lock()+ defer h.mu.Unlock()+ for _, ch := range h.subs {+ select {+ case ch <- e:+ default:+ // 该订阅者积压严重,丢弃这条而不是阻塞其他订阅者+ }+ }+}++func (h *Hub) SubscriberCount() int {+ h.mu.Lock()+ defer h.mu.Unlock()+ return len(h.subs)+}++// 便捷构造:事件类型很多,包一层省得调用点到处写 oneof 包装。++func EventClipAdded(r *pb.ClipRecord) *pb.Event {+ return &pb.Event{Payload: &pb.Event_ClipAdded{ClipAdded: r}}+}++func EventClipUpdated(r *pb.ClipRecord) *pb.Event {+ return &pb.Event{Payload: &pb.Event_ClipUpdated{ClipUpdated: r}}+}++func EventClipRemoved(id string) *pb.Event {+ return &pb.Event{Payload: &pb.Event_ClipRemoved{ClipRemoved: id}}+}++func EventProgress(p *pb.TransferProgress) *pb.Event {+ return &pb.Event{Payload: &pb.Event_Progress{Progress: p}}+}++func EventDeviceChanged(d *pb.Device) *pb.Event {+ return &pb.Event{Payload: &pb.Event_DeviceChanged{DeviceChanged: d}}+}++func EventPermissionChanged(p pb.ClipboardPermission) *pb.Event {+ return &pb.Event{Payload: &pb.Event_PermissionChanged{PermissionChanged: p}}+}++func EventStatusChanged(s *pb.Status) *pb.Event {+ return &pb.Event{Payload: &pb.Event_StatusChanged{StatusChanged: s}}+}diff --git a/client-core/internal/rpc/server.go b/client-core/internal/rpc/server.gonew file mode 100644index 0000000..3a83ff6--- /dev/null+++ b/client-core/internal/rpc/server.go@@ -0,0 +1,330 @@+// Package rpc 是 daemon 暴露给 Flutter UI 的本地 gRPC 服务。+package rpc++import (+ "context"+ "crypto/subtle"+ "fmt"+ "net"+ "time"++ "google.golang.org/grpc"+ "google.golang.org/grpc/codes"+ "google.golang.org/grpc/metadata"+ "google.golang.org/grpc/status"++ "github.com/baiyuze/copysync/client-core/internal/clipboard"+ "github.com/baiyuze/copysync/client-core/internal/config"+ "github.com/baiyuze/copysync/client-core/internal/store"+ pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"+)++const tokenHeader = "x-copysync-token"++// Deps 是 Server 依赖的 daemon 内部能力。用接口而非具体类型,+// 让 rpc 层不必反向依赖尚未实现的 sync / transport 包。+type Deps struct {+ Store *store.Store+ Paths config.Paths+ Version string+ DeviceID string++ // LoadConfig / SaveConfig 由 daemon 提供,保证配置变更能即时生效+ LoadConfig func() config.Config+ SaveConfig func(config.Config) error++ // 以下在对应里程碑接上,未实现时为 nil,方法返回 Unimplemented+ Fetch func(ctx context.Context, clipID string) error+ ApplyToClipboard func(ctx context.Context, clipID string) error+ Permission func() clipboard.Permission+ OpenPermissionSettings func() error+ Devices func() (self *pb.Device, peers []*pb.Device)+ CreatePairingCode func(ctx context.Context) (code string, expiresAt time.Time, err error)+ RedeemPairingCode func(ctx context.Context, code string) (*pb.Device, string, error)+ ConfirmPairing func(ctx context.Context, session string, accept bool) error+ Unpair func(ctx context.Context, deviceID string) error+ SignalingConnected func() bool+ CacheBytesUsed func() int64+}++type Server struct {+ pb.UnimplementedDaemonServiceServer+ deps Deps+ hub *Hub+ token string+}++func NewServer(deps Deps, hub *Hub, token string) *Server {+ return &Server{deps: deps, hub: hub, token: token}+}++// Serve 在 127.0.0.1 的随机端口上启动 gRPC,返回实际端口。+// 只监听回环地址:daemon 不对外提供服务。+func (s *Server) Serve(ctx context.Context) (int, *grpc.Server, error) {+ lis, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ return 0, nil, fmt.Errorf("监听本地端口: %w", err)+ }++ gs := grpc.NewServer(+ grpc.UnaryInterceptor(s.authUnary),+ grpc.StreamInterceptor(s.authStream),+ )+ pb.RegisterDaemonServiceServer(gs, s)++ go func() {+ <-ctx.Done()+ gs.GracefulStop()+ }()+ go func() {+ if err := gs.Serve(lis); err != nil {+ // GracefulStop 会让 Serve 正常返回,这里只记录异常退出+ _ = err+ }+ }()++ return lis.Addr().(*net.TCPAddr).Port, gs, nil+}++// ─────────────────────────── 认证 ───────────────────────────++// 本机回环端口对同机其他进程同样可达,因此用一次性 token 把关。+func (s *Server) checkToken(ctx context.Context) error {+ md, ok := metadata.FromIncomingContext(ctx)+ if !ok {+ return status.Error(codes.Unauthenticated, "缺少认证信息")+ }+ vals := md.Get(tokenHeader)+ if len(vals) == 0 {+ return status.Error(codes.Unauthenticated, "缺少 token")+ }+ // 常数时间比较,避免时序侧信道+ if subtle.ConstantTimeCompare([]byte(vals[0]), []byte(s.token)) != 1 {+ return status.Error(codes.Unauthenticated, "token 无效")+ }+ return nil+}++func (s *Server) authUnary(ctx context.Context, req any,+ _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {+ if err := s.checkToken(ctx); err != nil {+ return nil, err+ }+ return handler(ctx, req)+}++func (s *Server) authStream(srv any, ss grpc.ServerStream,+ _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error {+ if err := s.checkToken(ss.Context()); err != nil {+ return err+ }+ return handler(srv, ss)+}++// ─────────────────────────── 事件流 ───────────────────────────++func (s *Server) Subscribe(req *pb.SubscribeRequest,+ stream grpc.ServerStreamingServer[pb.Event]) error {+ ch, cancel := s.hub.Subscribe()+ defer cancel()++ // 先补发断线期间错过的记录,再转入实时推送+ if req.GetSinceUnix() > 0 {+ since := time.Unix(req.GetSinceUnix(), 0)+ clips, err := s.deps.Store.ListClips(200, time.Time{}, store.KindUnspecified)+ if err != nil {+ return status.Errorf(codes.Internal, "读取历史: %v", err)+ }+ // ListClips 是倒序,补发时正序推送更符合 UI 预期+ for i := len(clips) - 1; i >= 0; i-- {+ if clips[i].CreatedAt.After(since) {+ if err := stream.Send(EventClipAdded(clipToProto(clips[i]))); err != nil {+ return err+ }+ }+ }+ }++ // 立即推一次状态,让 UI 不必等到下次变化才知道当前情况+ if st, err := s.GetStatus(stream.Context(), &pb.Empty{}); err == nil {+ if err := stream.Send(EventStatusChanged(st)); err != nil {+ return err+ }+ }++ for {+ select {+ case <-stream.Context().Done():+ return nil+ case e, ok := <-ch:+ if !ok {+ return nil+ }+ if err := stream.Send(e); err != nil {+ return err+ }+ }+ }+}++// ─────────────────────────── 历史记录 ───────────────────────────++func (s *Server) ListHistory(_ context.Context,+ req *pb.ListHistoryRequest) (*pb.ListHistoryResponse, error) {+ var before time.Time+ if req.GetBeforeUnix() > 0 {+ before = time.Unix(req.GetBeforeUnix(), 0)+ }+ clips, err := s.deps.Store.ListClips(int(req.GetLimit()), before, store.Kind(req.GetKindFilter()))+ if err != nil {+ return nil, status.Errorf(codes.Internal, "读取历史: %v", err)+ }+ out := make([]*pb.ClipRecord, 0, len(clips))+ for _, c := range clips {+ out = append(out, clipToProto(c))+ }+ return &pb.ListHistoryResponse{Records: out}, nil+}++func (s *Server) DeleteHistory(_ context.Context, req *pb.DeleteHistoryRequest) (*pb.Empty, error) {+ var err error+ if req.GetAll() {+ err = s.deps.Store.DeleteAllClips()+ } else {+ err = s.deps.Store.DeleteClips(req.GetIds())+ }+ if err != nil {+ return nil, status.Errorf(codes.Internal, "删除历史: %v", err)+ }+ for _, id := range req.GetIds() {+ s.hub.Publish(EventClipRemoved(id))+ }+ return &pb.Empty{}, nil+}++func (s *Server) Fetch(ctx context.Context, req *pb.FetchRequest) (*pb.Empty, error) {+ if s.deps.Fetch == nil {+ return nil, status.Error(codes.Unimplemented, "传输层尚未接入(M4)")+ }+ if err := s.deps.Fetch(ctx, req.GetClipId()); err != nil {+ return nil, status.Errorf(codes.Internal, "拉取失败: %v", err)+ }+ return &pb.Empty{}, nil+}++func (s *Server) ApplyToClipboard(ctx context.Context,+ req *pb.ApplyToClipboardRequest) (*pb.Empty, error) {+ if s.deps.ApplyToClipboard == nil {+ return nil, status.Error(codes.Unimplemented, "剪贴板写入尚未接入(M3)")+ }+ if err := s.deps.ApplyToClipboard(ctx, req.GetClipId()); err != nil {+ return nil, status.Errorf(codes.Internal, "写入剪贴板失败: %v", err)+ }+ return &pb.Empty{}, nil+}++// ─────────────────────────── 配置与状态 ───────────────────────────++func (s *Server) GetConfig(context.Context, *pb.Empty) (*pb.Config, error) {+ return configToProto(s.deps.LoadConfig()), nil+}++func (s *Server) UpdateConfig(_ context.Context, in *pb.Config) (*pb.Config, error) {+ c := configFromProto(in, s.deps.LoadConfig())+ c.Validate()+ if err := s.deps.SaveConfig(c); err != nil {+ return nil, status.Errorf(codes.Internal, "保存配置: %v", err)+ }+ return configToProto(c), nil+}++func (s *Server) GetStatus(context.Context, *pb.Empty) (*pb.Status, error) {+ cfg := s.deps.LoadConfig()+ st := &pb.Status{+ DeviceId: s.deps.DeviceID,+ DeviceName: cfg.DeviceName,+ Version: s.deps.Version,+ }+ if s.deps.Permission != nil {+ st.ClipboardPermission = permissionToProto(s.deps.Permission())+ }+ if s.deps.SignalingConnected != nil {+ st.SignalingConnected = s.deps.SignalingConnected()+ }+ if s.deps.CacheBytesUsed != nil {+ st.CacheBytesUsed = s.deps.CacheBytesUsed()+ }+ if s.deps.Devices != nil {+ _, peers := s.deps.Devices()+ for _, p := range peers {+ if p.GetOnline() {+ st.PeersOnline+++ }+ }+ }+ return st, nil+}++func (s *Server) RequestClipboardPermission(context.Context, *pb.Empty) (*pb.Empty, error) {+ if s.deps.OpenPermissionSettings == nil {+ return nil, status.Error(codes.Unimplemented, "当前平台无需授权")+ }+ if err := s.deps.OpenPermissionSettings(); err != nil {+ return nil, status.Errorf(codes.Internal, "打开设置失败: %v", err)+ }+ return &pb.Empty{}, nil+}++// ─────────────────────────── 设备与配对 ───────────────────────────++func (s *Server) ListDevices(context.Context, *pb.Empty) (*pb.ListDevicesResponse, error) {+ if s.deps.Devices == nil {+ return nil, status.Error(codes.Unimplemented, "配对尚未接入(M1)")+ }+ self, peers := s.deps.Devices()+ return &pb.ListDevicesResponse{Self: self, Peers: peers}, nil+}++func (s *Server) CreatePairingCode(ctx context.Context,+ _ *pb.Empty) (*pb.CreatePairingCodeResponse, error) {+ if s.deps.CreatePairingCode == nil {+ return nil, status.Error(codes.Unimplemented, "配对尚未接入(M1)")+ }+ code, exp, err := s.deps.CreatePairingCode(ctx)+ if err != nil {+ return nil, status.Errorf(codes.Internal, "生成配对码: %v", err)+ }+ return &pb.CreatePairingCodeResponse{Code: code, ExpiresAtUnix: exp.Unix()}, nil+}++func (s *Server) RedeemPairingCode(ctx context.Context,+ req *pb.RedeemPairingCodeRequest) (*pb.RedeemPairingCodeResponse, error) {+ if s.deps.RedeemPairingCode == nil {+ return nil, status.Error(codes.Unimplemented, "配对尚未接入(M1)")+ }+ peer, session, err := s.deps.RedeemPairingCode(ctx, req.GetCode())+ if err != nil {+ return nil, status.Errorf(codes.InvalidArgument, "兑换配对码: %v", err)+ }+ return &pb.RedeemPairingCodeResponse{Peer: peer, PairingSession: session}, nil+}++func (s *Server) ConfirmPairing(ctx context.Context, req *pb.ConfirmPairingRequest) (*pb.Empty, error) {+ if s.deps.ConfirmPairing == nil {+ return nil, status.Error(codes.Unimplemented, "配对尚未接入(M1)")+ }+ if err := s.deps.ConfirmPairing(ctx, req.GetPairingSession(), req.GetAccept()); err != nil {+ return nil, status.Errorf(codes.Internal, "确认配对: %v", err)+ }+ return &pb.Empty{}, nil+}++func (s *Server) Unpair(ctx context.Context, req *pb.UnpairRequest) (*pb.Empty, error) {+ if s.deps.Unpair == nil {+ return nil, status.Error(codes.Unimplemented, "配对尚未接入(M1)")+ }+ if err := s.deps.Unpair(ctx, req.GetDeviceId()); err != nil {+ return nil, status.Errorf(codes.Internal, "解除配对: %v", err)+ }+ return &pb.Empty{}, nil+}diff --git a/client-core/internal/store/store.go b/client-core/internal/store/store.gonew file mode 100644index 0000000..982c805--- /dev/null+++ b/client-core/internal/store/store.go@@ -0,0 +1,412 @@+// Package store 是 daemon 的本地持久化层:剪贴板历史、已配对设备、杂项元数据。+//+// 用 modernc.org/sqlite(纯 Go 实现)而非 mattn/go-sqlite3——剪贴板层已经+// 不得不引入 cgo,数据库这层能省则省,也让交叉编译简单些。+package store++import (+ "database/sql"+ "encoding/json"+ "errors"+ "fmt"+ "time"++ _ "modernc.org/sqlite"+)++type Kind int32++const (+ KindUnspecified Kind = 0+ KindText Kind = 1+ KindHTML Kind = 2+ KindImage Kind = 3+ KindFile Kind = 4+)++type Status int32++const (+ StatusUnspecified Status = 0+ StatusReady Status = 1 // 内容已在本地,可直接粘贴+ StatusRemoteOnly Status = 2 // 超过阈值,只有元数据+ StatusFetching Status = 3+ StatusFailed Status = 4+ StatusExpired Status = 5+)++type Item struct {+ Name string `json:"name"`+ Size int64 `json:"size"`+ IsDir bool `json:"is_dir"`+ ContentType string `json:"content_type"`+}++type Clip struct {+ ID string+ Kind Kind+ Status Status+ OriginDeviceID string+ OriginDeviceName string+ Outgoing bool // true=本机复制 false=从对端收到+ Items []Item+ TotalSize int64+ TextPreview string+ TextContent string // 文本/HTML 的完整内容,直接存库+ TextPlain string // HTML 的纯文本形式,供只认纯文本的输入框粘贴+ CachePath string // 相对 cache 目录的落盘位置+ SourcePaths []string // 本机复制时的源路径,供对端 fetch 时回源+ Error string+ CreatedAt time.Time+ ExpiresAt time.Time+}++type Device struct {+ ID string+ Name string+ Platform string+ PublicKey []byte+ PairedAt time.Time+}++type Store struct{ db *sql.DB }++func Open(path string) (*Store, error) {+ // busy_timeout 避免 GC 与写入并发时立刻报 SQLITE_BUSY;+ // WAL 让读写互不阻塞;foreign_keys 让 clip_items 的级联删除生效。+ dsn := path + "?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=foreign_keys(ON)"+ db, err := sql.Open("sqlite", dsn)+ if err != nil {+ return nil, fmt.Errorf("打开数据库: %w", err)+ }+ // modernc 的驱动在并发写时容易踩锁,单连接最省心,且本地负载极低+ db.SetMaxOpenConns(1)++ s := &Store{db: db}+ if err := s.migrate(); err != nil {+ db.Close()+ return nil, err+ }+ return s, nil+}++func (s *Store) Close() error { return s.db.Close() }++func (s *Store) migrate() error {+ const schema = `+CREATE TABLE IF NOT EXISTS clips (+ id TEXT PRIMARY KEY,+ kind INTEGER NOT NULL,+ status INTEGER NOT NULL,+ origin_device_id TEXT NOT NULL DEFAULT '',+ origin_device_name TEXT NOT NULL DEFAULT '',+ outgoing INTEGER NOT NULL DEFAULT 0,+ total_size INTEGER NOT NULL DEFAULT 0,+ text_preview TEXT NOT NULL DEFAULT '',+ text_content TEXT NOT NULL DEFAULT '',+ text_plain TEXT NOT NULL DEFAULT '',+ cache_path TEXT NOT NULL DEFAULT '',+ source_paths TEXT NOT NULL DEFAULT '[]',+ error TEXT NOT NULL DEFAULT '',+ created_at INTEGER NOT NULL,+ expires_at INTEGER NOT NULL+);+CREATE INDEX IF NOT EXISTS idx_clips_created ON clips(created_at DESC);+CREATE INDEX IF NOT EXISTS idx_clips_expires ON clips(expires_at);++CREATE TABLE IF NOT EXISTS clip_items (+ clip_id TEXT NOT NULL REFERENCES clips(id) ON DELETE CASCADE,+ idx INTEGER NOT NULL,+ name TEXT NOT NULL,+ size INTEGER NOT NULL DEFAULT 0,+ is_dir INTEGER NOT NULL DEFAULT 0,+ content_type TEXT NOT NULL DEFAULT '',+ PRIMARY KEY (clip_id, idx)+);++CREATE TABLE IF NOT EXISTS devices (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL DEFAULT '',+ platform TEXT NOT NULL DEFAULT '',+ public_key BLOB NOT NULL,+ paired_at INTEGER NOT NULL+);++CREATE TABLE IF NOT EXISTS meta (+ key TEXT PRIMARY KEY,+ value TEXT NOT NULL+);`+ if _, err := s.db.Exec(schema); err != nil {+ return fmt.Errorf("建表: %w", err)+ }+ // 建表语句对已有的库不生效,后加的列要单独补上+ return s.addColumnIfMissing("clips", "text_plain", "TEXT NOT NULL DEFAULT ''")+}++func (s *Store) addColumnIfMissing(table, column, decl string) error {+ rows, err := s.db.Query(`SELECT name FROM pragma_table_info(?)`, table)+ if err != nil {+ return fmt.Errorf("读取 %s 表结构: %w", table, err)+ }+ defer rows.Close()+ for rows.Next() {+ var name string+ if err := rows.Scan(&name); err != nil {+ return err+ }+ if name == column {+ return nil+ }+ }+ if err := rows.Err(); err != nil {+ return err+ }+ if _, err := s.db.Exec(`ALTER TABLE ` + table + ` ADD COLUMN ` + column + ` ` + decl); err != nil {+ return fmt.Errorf("为 %s 添加列 %s: %w", table, column, err)+ }+ return nil+}++// ─────────────────────────── clips ───────────────────────────++func (s *Store) PutClip(c Clip) error {+ tx, err := s.db.Begin()+ if err != nil {+ return err+ }+ defer tx.Rollback()++ srcJSON, err := json.Marshal(c.SourcePaths)+ if err != nil {+ return err+ }++ _, err = tx.Exec(`+INSERT INTO clips (id, kind, status, origin_device_id, origin_device_name, outgoing,+ total_size, text_preview, text_content, text_plain, cache_path,+ source_paths, error, created_at, expires_at)+VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)+ON CONFLICT(id) DO UPDATE SET+ status=excluded.status, total_size=excluded.total_size,+ text_preview=excluded.text_preview, text_content=excluded.text_content,+ text_plain=excluded.text_plain,+ cache_path=excluded.cache_path, source_paths=excluded.source_paths,+ error=excluded.error, expires_at=excluded.expires_at`,+ c.ID, c.Kind, c.Status, c.OriginDeviceID, c.OriginDeviceName, c.Outgoing,+ c.TotalSize, c.TextPreview, c.TextContent, c.TextPlain, c.CachePath,+ string(srcJSON), c.Error, c.CreatedAt.Unix(), c.ExpiresAt.Unix())+ if err != nil {+ return fmt.Errorf("写入 clip: %w", err)+ }++ // items 整体替换,避免增量更新的边界情况+ if _, err := tx.Exec(`DELETE FROM clip_items WHERE clip_id=?`, c.ID); err != nil {+ return err+ }+ for i, it := range c.Items {+ if _, err := tx.Exec(`+INSERT INTO clip_items (clip_id, idx, name, size, is_dir, content_type)+VALUES (?,?,?,?,?,?)`, c.ID, i, it.Name, it.Size, it.IsDir, it.ContentType); err != nil {+ return fmt.Errorf("写入 clip_item: %w", err)+ }+ }+ return tx.Commit()+}++var ErrNotFound = errors.New("记录不存在")++func (s *Store) GetClip(id string) (Clip, error) {+ rows, err := s.queryClips(`SELECT `+clipCols+` FROM clips WHERE id=?`, id)+ if err != nil {+ return Clip{}, err+ }+ if len(rows) == 0 {+ return Clip{}, ErrNotFound+ }+ return rows[0], nil+}++// ListClips 按时间倒序分页。before 为零值表示从最新开始。+func (s *Store) ListClips(limit int, before time.Time, kind Kind) ([]Clip, error) {+ if limit <= 0 || limit > 500 {+ limit = 100+ }+ q := `SELECT ` + clipCols + ` FROM clips WHERE 1=1`+ var args []any+ if !before.IsZero() {+ q += ` AND created_at < ?`+ args = append(args, before.Unix())+ }+ if kind != KindUnspecified {+ q += ` AND kind = ?`+ args = append(args, kind)+ }+ q += ` ORDER BY created_at DESC LIMIT ?`+ args = append(args, limit)+ return s.queryClips(q, args...)+}++const clipCols = `id, kind, status, origin_device_id, origin_device_name, outgoing,+ total_size, text_preview, text_content, text_plain, cache_path,+ source_paths, error, created_at, expires_at`++func (s *Store) queryClips(query string, args ...any) ([]Clip, error) {+ rows, err := s.db.Query(query, args...)+ if err != nil {+ return nil, fmt.Errorf("查询 clips: %w", err)+ }+ defer rows.Close()++ var out []Clip+ for rows.Next() {+ var c Clip+ var srcJSON string+ var created, expires int64+ if err := rows.Scan(&c.ID, &c.Kind, &c.Status, &c.OriginDeviceID, &c.OriginDeviceName,+ &c.Outgoing, &c.TotalSize, &c.TextPreview, &c.TextContent, &c.TextPlain,+ &c.CachePath, &srcJSON, &c.Error, &created, &expires); err != nil {+ return nil, err+ }+ c.CreatedAt = time.Unix(created, 0)+ c.ExpiresAt = time.Unix(expires, 0)+ _ = json.Unmarshal([]byte(srcJSON), &c.SourcePaths)+ out = append(out, c)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ // items 单独查,避免 JOIN 后的行展开处理+ for i := range out {+ if out[i].Items, err = s.itemsOf(out[i].ID); err != nil {+ return nil, err+ }+ }+ return out, nil+}++func (s *Store) itemsOf(clipID string) ([]Item, error) {+ rows, err := s.db.Query(`+SELECT name, size, is_dir, content_type FROM clip_items+WHERE clip_id=? ORDER BY idx`, clipID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ var out []Item+ for rows.Next() {+ var it Item+ if err := rows.Scan(&it.Name, &it.Size, &it.IsDir, &it.ContentType); err != nil {+ return nil, err+ }+ out = append(out, it)+ }+ return out, rows.Err()+}++func (s *Store) SetClipStatus(id string, st Status, errMsg string) error {+ _, err := s.db.Exec(`UPDATE clips SET status=?, error=? WHERE id=?`, st, errMsg, id)+ return err+}++func (s *Store) SetClipCache(id, cachePath string, totalSize int64) error {+ _, err := s.db.Exec(`+UPDATE clips SET cache_path=?, total_size=?, status=?, error='' WHERE id=?`,+ cachePath, totalSize, StatusReady, id)+ return err+}++func (s *Store) DeleteClips(ids []string) error {+ tx, err := s.db.Begin()+ if err != nil {+ return err+ }+ defer tx.Rollback()+ for _, id := range ids {+ if _, err := tx.Exec(`DELETE FROM clips WHERE id=?`, id); err != nil {+ return err+ }+ }+ return tx.Commit()+}++func (s *Store) DeleteAllClips() error {+ _, err := s.db.Exec(`DELETE FROM clips`)+ return err+}++// ExpiredClips 返回已过期的记录,交由 GC 先删缓存文件再删行。+func (s *Store) ExpiredClips(now time.Time) ([]Clip, error) {+ return s.queryClips(`SELECT `+clipCols+` FROM clips WHERE expires_at <= ?`, now.Unix())+}++// CachePaths 返回所有仍被引用的缓存路径,供 GC 与磁盘对账、清理孤儿文件。+func (s *Store) CachePaths() (map[string]struct{}, error) {+ rows, err := s.db.Query(`SELECT cache_path FROM clips WHERE cache_path <> ''`)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ out := map[string]struct{}{}+ for rows.Next() {+ var p string+ if err := rows.Scan(&p); err != nil {+ return nil, err+ }+ out[p] = struct{}{}+ }+ return out, rows.Err()+}++// ─────────────────────────── devices ───────────────────────────++func (s *Store) PutDevice(d Device) error {+ _, err := s.db.Exec(`+INSERT INTO devices (id, name, platform, public_key, paired_at) VALUES (?,?,?,?,?)+ON CONFLICT(id) DO UPDATE SET+ name=excluded.name, platform=excluded.platform, public_key=excluded.public_key`,+ d.ID, d.Name, d.Platform, d.PublicKey, d.PairedAt.Unix())+ return err+}++func (s *Store) ListDevices() ([]Device, error) {+ rows, err := s.db.Query(`+SELECT id, name, platform, public_key, paired_at FROM devices ORDER BY paired_at`)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ var out []Device+ for rows.Next() {+ var d Device+ var paired int64+ if err := rows.Scan(&d.ID, &d.Name, &d.Platform, &d.PublicKey, &paired); err != nil {+ return nil, err+ }+ d.PairedAt = time.Unix(paired, 0)+ out = append(out, d)+ }+ return out, rows.Err()+}++func (s *Store) DeleteDevice(id string) error {+ _, err := s.db.Exec(`DELETE FROM devices WHERE id=?`, id)+ return err+}++// ─────────────────────────── meta ───────────────────────────++func (s *Store) GetMeta(key string) (string, error) {+ var v string+ err := s.db.QueryRow(`SELECT value FROM meta WHERE key=?`, key).Scan(&v)+ if errors.Is(err, sql.ErrNoRows) {+ return "", ErrNotFound+ }+ return v, err+}++func (s *Store) SetMeta(key, value string) error {+ _, err := s.db.Exec(`+INSERT INTO meta (key, value) VALUES (?,?)+ON CONFLICT(key) DO UPDATE SET value=excluded.value`, key, value)+ return err+}diff --git a/client-core/internal/store/store_test.go b/client-core/internal/store/store_test.gonew file mode 100644index 0000000..de6103c--- /dev/null+++ b/client-core/internal/store/store_test.go@@ -0,0 +1,365 @@+package store++import (+ "database/sql"+ "path/filepath"+ "testing"+ "time"+)++func openTest(t *testing.T) *Store {+ t.Helper()+ s, err := Open(filepath.Join(t.TempDir(), "test.db"))+ if err != nil {+ t.Fatalf("打开数据库: %v", err)+ }+ t.Cleanup(func() { s.Close() })+ return s+}++func sampleClip(id string, created time.Time) Clip {+ return Clip{+ ID: id,+ Kind: KindFile,+ Status: StatusReady,+ OriginDeviceID: "dev-1",+ OriginDeviceName: "笔记本",+ TotalSize: 2048,+ CachePath: id + ".bin",+ SourcePaths: []string{"/tmp/a.txt", "/tmp/b.txt"},+ Items: []Item{+ {Name: "a.txt", Size: 1024, ContentType: "public.plain-text"},+ {Name: "docs", Size: 1024, IsDir: true},+ },+ CreatedAt: created,+ ExpiresAt: created.Add(72 * time.Hour),+ }+}++func TestPutAndGetRoundTrip(t *testing.T) {+ s := openTest(t)+ now := time.Now().Truncate(time.Second)+ want := sampleClip("clip-1", now)++ if err := s.PutClip(want); err != nil {+ t.Fatalf("写入: %v", err)+ }+ got, err := s.GetClip("clip-1")+ if err != nil {+ t.Fatalf("读取: %v", err)+ }++ if got.TotalSize != want.TotalSize || got.OriginDeviceName != want.OriginDeviceName {+ t.Errorf("基本字段不一致: %+v", got)+ }+ if len(got.Items) != 2 || got.Items[0].Name != "a.txt" || !got.Items[1].IsDir {+ t.Errorf("items 未正确往返: %+v", got.Items)+ }+ // 源路径供对端 fetch 时回源,丢了就再也拉不到原文件+ if len(got.SourcePaths) != 2 || got.SourcePaths[1] != "/tmp/b.txt" {+ t.Errorf("source_paths 未正确往返: %v", got.SourcePaths)+ }+ if !got.CreatedAt.Equal(now) {+ t.Errorf("创建时间 = %v,期望 %v", got.CreatedAt, now)+ }+}++func TestGetMissingClip(t *testing.T) {+ s := openTest(t)+ if _, err := s.GetClip("nope"); err != ErrNotFound {+ t.Errorf("err = %v,期望 ErrNotFound", err)+ }+}++// 同一条记录重复写入应当是更新而非报错——收到进度更新时会反复写。+func TestPutClipIsUpsert(t *testing.T) {+ s := openTest(t)+ now := time.Now()+ c := sampleClip("clip-1", now)+ if err := s.PutClip(c); err != nil {+ t.Fatal(err)+ }++ c.Status = StatusFetching+ c.TotalSize = 4096+ c.Items = []Item{{Name: "only.txt", Size: 4096}}+ if err := s.PutClip(c); err != nil {+ t.Fatalf("二次写入: %v", err)+ }++ got, _ := s.GetClip("clip-1")+ if got.Status != StatusFetching || got.TotalSize != 4096 {+ t.Errorf("更新未生效: status=%v size=%d", got.Status, got.TotalSize)+ }+ // items 是整体替换,不能残留旧条目+ if len(got.Items) != 1 || got.Items[0].Name != "only.txt" {+ t.Errorf("items 未被整体替换: %+v", got.Items)+ }+}++func TestListClipsOrderAndPaging(t *testing.T) {+ s := openTest(t)+ base := time.Now().Truncate(time.Second)+ for i := range 5 {+ c := sampleClip("clip-"+string(rune('a'+i)), base.Add(time.Duration(i)*time.Minute))+ if err := s.PutClip(c); err != nil {+ t.Fatal(err)+ }+ }++ got, err := s.ListClips(10, time.Time{}, KindUnspecified)+ if err != nil {+ t.Fatal(err)+ }+ if len(got) != 5 {+ t.Fatalf("返回 %d 条,期望 5", len(got))+ }+ // 倒序:最新的在最前,界面据此直接渲染+ for i := 1; i < len(got); i++ {+ if got[i].CreatedAt.After(got[i-1].CreatedAt) {+ t.Errorf("第 %d 条比前一条更新,排序不是倒序", i)+ }+ }++ // 游标分页:只返回早于 before 的记录+ page, err := s.ListClips(10, got[2].CreatedAt, KindUnspecified)+ if err != nil {+ t.Fatal(err)+ }+ for _, c := range page {+ if !c.CreatedAt.Before(got[2].CreatedAt) {+ t.Errorf("分页返回了不早于游标的记录: %v", c.ID)+ }+ }+}++func TestListClipsKindFilter(t *testing.T) {+ s := openTest(t)+ now := time.Now()+ fileClip := sampleClip("f", now)+ textClip := sampleClip("t", now.Add(time.Minute))+ textClip.Kind = KindText+ for _, c := range []Clip{fileClip, textClip} {+ if err := s.PutClip(c); err != nil {+ t.Fatal(err)+ }+ }++ got, err := s.ListClips(10, time.Time{}, KindText)+ if err != nil {+ t.Fatal(err)+ }+ if len(got) != 1 || got[0].ID != "t" {+ t.Errorf("类型过滤失效: %+v", got)+ }+}++// GC 依赖这个查询找出该删的记录;边界判定错了会导致缓存永不释放。+func TestExpiredClips(t *testing.T) {+ s := openTest(t)+ now := time.Now().Truncate(time.Second)++ fresh := sampleClip("fresh", now)+ fresh.ExpiresAt = now.Add(time.Hour)+ stale := sampleClip("stale", now.Add(-48*time.Hour))+ stale.ExpiresAt = now.Add(-time.Hour)+ for _, c := range []Clip{fresh, stale} {+ if err := s.PutClip(c); err != nil {+ t.Fatal(err)+ }+ }++ got, err := s.ExpiredClips(now)+ if err != nil {+ t.Fatal(err)+ }+ if len(got) != 1 || got[0].ID != "stale" {+ t.Fatalf("过期查询结果 = %+v,期望只有 stale", got)+ }+ // 过期记录要带着 cache_path 返回,GC 才知道该删哪个文件+ if got[0].CachePath == "" {+ t.Error("过期记录缺少 cache_path,GC 无法清理对应文件")+ }+}++// GC 要和磁盘对账,清掉没有记录引用的孤儿文件。+func TestCachePaths(t *testing.T) {+ s := openTest(t)+ now := time.Now()+ withCache := sampleClip("a", now)+ noCache := sampleClip("b", now)+ noCache.CachePath = ""+ for _, c := range []Clip{withCache, noCache} {+ if err := s.PutClip(c); err != nil {+ t.Fatal(err)+ }+ }++ paths, err := s.CachePaths()+ if err != nil {+ t.Fatal(err)+ }+ if len(paths) != 1 {+ t.Fatalf("返回 %d 条,期望 1(空 cache_path 应被排除)", len(paths))+ }+ if _, ok := paths["a.bin"]; !ok {+ t.Errorf("缺少 a.bin: %v", paths)+ }+}++// 删除记录时 clip_items 必须级联删除,否则会留下孤儿行。+func TestDeleteCascadesItems(t *testing.T) {+ s := openTest(t)+ if err := s.PutClip(sampleClip("clip-1", time.Now())); err != nil {+ t.Fatal(err)+ }+ if err := s.DeleteClips([]string{"clip-1"}); err != nil {+ t.Fatal(err)+ }++ items, err := s.itemsOf("clip-1")+ if err != nil {+ t.Fatal(err)+ }+ if len(items) != 0 {+ t.Errorf("删除记录后仍残留 %d 条 item", len(items))+ }+}++func TestSetClipCacheMarksReady(t *testing.T) {+ s := openTest(t)+ c := sampleClip("clip-1", time.Now())+ c.Status = StatusRemoteOnly+ c.CachePath = ""+ c.Error = "上次失败了"+ if err := s.PutClip(c); err != nil {+ t.Fatal(err)+ }++ if err := s.SetClipCache("clip-1", "downloaded.bin", 9999); err != nil {+ t.Fatal(err)+ }+ got, _ := s.GetClip("clip-1")+ if got.Status != StatusReady || got.CachePath != "downloaded.bin" || got.TotalSize != 9999 {+ t.Errorf("落盘后状态不对: %+v", got)+ }+ // 上一次的错误信息必须清掉,否则界面会一直显示旧的失败原因+ if got.Error != "" {+ t.Errorf("落盘成功后仍残留错误信息: %q", got.Error)+ }+}++func TestDeviceRoundTrip(t *testing.T) {+ s := openTest(t)+ d := Device{+ ID: "dev-1",+ Name: "台式机",+ Platform: "windows",+ PublicKey: []byte{1, 2, 3, 4},+ PairedAt: time.Now().Truncate(time.Second),+ }+ if err := s.PutDevice(d); err != nil {+ t.Fatal(err)+ }++ list, err := s.ListDevices()+ if err != nil {+ t.Fatal(err)+ }+ if len(list) != 1 || list[0].Name != "台式机" || string(list[0].PublicKey) != "\x01\x02\x03\x04" {+ t.Fatalf("设备未正确往返: %+v", list)+ }++ // 重连时设备名可能变了,应当更新而非插入重复行+ d.Name = "改名后的台式机"+ if err := s.PutDevice(d); err != nil {+ t.Fatal(err)+ }+ list, _ = s.ListDevices()+ if len(list) != 1 || list[0].Name != "改名后的台式机" {+ t.Errorf("重复写入未更新: %+v", list)+ }++ if err := s.DeleteDevice("dev-1"); err != nil {+ t.Fatal(err)+ }+ if list, _ = s.ListDevices(); len(list) != 0 {+ t.Errorf("删除后仍有 %d 台设备", len(list))+ }+}++func TestMetaRoundTrip(t *testing.T) {+ s := openTest(t)+ if _, err := s.GetMeta("missing"); err != ErrNotFound {+ t.Errorf("err = %v,期望 ErrNotFound", err)+ }+ if err := s.SetMeta("k", "v1"); err != nil {+ t.Fatal(err)+ }+ if err := s.SetMeta("k", "v2"); err != nil {+ t.Fatal(err)+ }+ got, err := s.GetMeta("k")+ if err != nil || got != "v2" {+ t.Errorf("got = %q, err = %v,期望 v2", got, err)+ }+}++func TestHTMLPlainTextRoundTrip(t *testing.T) {+ s := openTest(t)+ now := time.Now().Truncate(time.Second)+ c := Clip{+ ID: "html-1", Kind: KindHTML, Status: StatusReady,+ TextContent: "<meta charset='utf-8'><b>你好</b>", TextPlain: "你好",+ CreatedAt: now, ExpiresAt: now.Add(time.Hour),+ }+ if err := s.PutClip(c); err != nil {+ t.Fatalf("写入: %v", err)+ }+ got, err := s.GetClip("html-1")+ if err != nil {+ t.Fatalf("读取: %v", err)+ }+ if got.TextContent != c.TextContent || got.TextPlain != "你好" {+ t.Errorf("HTML 与纯文本未正确往返: content=%q plain=%q", got.TextContent, got.TextPlain)+ }+}++// 升级前的库没有 text_plain 列,打开时要自动补上,且旧记录照常可读。+func TestOpenMigratesOldSchema(t *testing.T) {+ path := filepath.Join(t.TempDir(), "old.db")+ old, err := sql.Open("sqlite", path)+ if err != nil {+ t.Fatal(err)+ }+ if _, err := old.Exec(`+CREATE TABLE clips (+ id TEXT PRIMARY KEY, kind INTEGER NOT NULL, status INTEGER NOT NULL,+ origin_device_id TEXT NOT NULL DEFAULT '', origin_device_name TEXT NOT NULL DEFAULT '',+ outgoing INTEGER NOT NULL DEFAULT 0, total_size INTEGER NOT NULL DEFAULT 0,+ text_preview TEXT NOT NULL DEFAULT '', text_content TEXT NOT NULL DEFAULT '',+ cache_path TEXT NOT NULL DEFAULT '', source_paths TEXT NOT NULL DEFAULT '[]',+ error TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL+);+INSERT INTO clips (id, kind, status, text_content, created_at, expires_at)+VALUES ('legacy', 2, 1, '<p>旧记录</p>', 1, 9999999999);`); err != nil {+ t.Fatalf("构造旧库: %v", err)+ }+ old.Close()++ // 打开两次:第二次列已存在,迁移必须是幂等的+ for i := range 2 {+ s, err := Open(path)+ if err != nil {+ t.Fatalf("第 %d 次打开: %v", i+1, err)+ }+ got, err := s.GetClip("legacy")+ if err != nil {+ t.Fatalf("读取旧记录: %v", err)+ }+ if got.TextContent != "<p>旧记录</p>" || got.TextPlain != "" {+ t.Errorf("旧记录内容异常: %+v", got)+ }+ s.Close()+ }+}diff --git a/client-core/internal/sync/chunkwriter.go b/client-core/internal/sync/chunkwriter.gonew file mode 100644index 0000000..9ab3698--- /dev/null+++ b/client-core/internal/sync/chunkwriter.go@@ -0,0 +1,137 @@+package sync++import (+ "context"+ "errors"+ "sync"+ "time"++ "github.com/pion/webrtc/v4"+)++// chunkWriter 把连续字节流切成 DataChannel 能承受的小块并施加背压。+//+// 两件事缺一不可:+// 1. 分片——SCTP 对超大消息的支持在各实现间差异很大,60 KiB 是稳妥值;+// 2. 背压——不管发送缓冲直接灌数据,传大文件会把内存吃光。+// 缓冲超过高水位时暂停读取源文件,等它回落再继续。+type chunkWriter struct {+ dc *webrtc.DataChannel+ onProgress func(sent int64)++ buf []byte+ sent int64++ mu sync.Mutex+ err error+}++func newChunkWriter(dc *webrtc.DataChannel, onProgress func(int64)) *chunkWriter {+ w := &chunkWriter{+ dc: dc,+ onProgress: onProgress,+ buf: make([]byte, 0, chunkSize),+ }+ dc.OnError(func(err error) {+ w.mu.Lock()+ w.err = err+ w.mu.Unlock()+ })+ return w+}++func (w *chunkWriter) Write(p []byte) (int, error) {+ total := len(p)+ for len(p) > 0 {+ space := chunkSize - len(w.buf)+ n := min(space, len(p))+ w.buf = append(w.buf, p[:n]...)+ p = p[n:]++ if len(w.buf) >= chunkSize {+ if err := w.flushChunk(); err != nil {+ return total - len(p), err+ }+ }+ }+ return total, nil+}++func (w *chunkWriter) Flush() error {+ if len(w.buf) == 0 {+ return nil+ }+ return w.flushChunk()+}++func (w *chunkWriter) flushChunk() error {+ if err := w.waitForBuffer(); err != nil {+ return err+ }+ if w.dc.ReadyState() != webrtc.DataChannelStateOpen {+ return errors.New("数据通道已关闭")+ }+ if err := w.dc.Send(w.buf); err != nil {+ return err+ }+ w.sent += int64(len(w.buf))+ w.buf = w.buf[:0]++ if w.onProgress != nil {+ w.onProgress(w.sent)+ }+ return nil+}++// waitForBuffer 在发送缓冲积压过多时等待它回落。+//+// 刻意用轮询而非 OnBufferedAmountLow 回调:那个回调是边沿触发的,+// 若缓冲在等待方进入 Wait 之前就已降到阈值以下,回调早已发生过,+// 等待就再也等不到唤醒——传 20 MB 文件时实测会卡死在 786 KB 处。+// 2 ms 的轮询间隔对文件传输而言开销可忽略,却彻底消除了丢失唤醒。+func (w *chunkWriter) waitForBuffer() error {+ const (+ pollInterval = 2 * time.Millisecond+ maxWait = 2 * time.Minute+ )+ deadline := time.Now().Add(maxWait)++ for w.dc.BufferedAmount() >= bufferHighWater {+ w.mu.Lock()+ err := w.err+ w.mu.Unlock()+ if err != nil {+ return err+ }+ if w.dc.ReadyState() != webrtc.DataChannelStateOpen {+ return errors.New("数据通道在传输中被关闭")+ }+ if time.Now().After(deadline) {+ return errors.New("等待发送缓冲排空超时")+ }+ time.Sleep(pollInterval)+ }+ return nil+}++// WaitDrained 等待发送缓冲彻底排空。+//+// 数据通道一关,尚未发出的数据就丢了;关闭前必须确认本地缓冲已清空。+func (w *chunkWriter) WaitDrained(ctx context.Context, timeout time.Duration) {+ deadline := time.Now().Add(timeout)+ for time.Now().Before(deadline) {+ if w.dc.BufferedAmount() == 0 {+ return+ }+ if w.dc.ReadyState() != webrtc.DataChannelStateOpen {+ return+ }+ select {+ case <-ctx.Done():+ return+ case <-time.After(5 * time.Millisecond):+ }+ }+}++func (w *chunkWriter) Sent() int64 { return w.sent }diff --git a/client-core/internal/sync/engine.go b/client-core/internal/sync/engine.gonew file mode 100644index 0000000..4eb6584--- /dev/null+++ b/client-core/internal/sync/engine.go@@ -0,0 +1,852 @@+// Package sync 是同步引擎:把本机剪贴板变化广播出去,+// 并把对端送来的内容落盘、写入本机剪贴板。+//+// 传输模型(M-1 实测后确定):按体积分流。+// - 文本 / HTML:内容很小,直接内联在 offer 里,无需二次传输+// - 图片、小于阈值的文件:随 offer 之后主动推送,对端可立即粘贴+// - 超过阈值的文件:只发元数据,等用户在界面上点「拉取」+//+// 之所以不是"对方按下粘贴键才传",是因为 macOS 的剪贴板延迟渲染+// 无法感知粘贴动作(详见 spikes/results.md)。+package sync++import (+ "context"+ "crypto/rand"+ "encoding/hex"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "time"++ "github.com/pion/webrtc/v4"++ "github.com/baiyuze/copysync/client-core/internal/cache"+ "github.com/baiyuze/copysync/client-core/internal/clipboard"+ "github.com/baiyuze/copysync/client-core/internal/config"+ "github.com/baiyuze/copysync/client-core/internal/pack"+ "github.com/baiyuze/copysync/client-core/internal/store"+ "github.com/baiyuze/copysync/client-core/internal/transport/p2p"+ pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"+)++const (+ // DataChannel 单条消息的上限。SCTP 对过大的消息支持参差,+ // 64 KiB 是各实现都稳妥的取值。+ chunkSize = 60 * 1024+ // 发送缓冲超过此值就暂停读取源文件,等它降下来再继续。+ // 没有背压的话,传大文件会把内存吃光。+ bufferHighWater = 1 << 20 // 1 MiB+ bufferLowWater = 256 << 10++ // 预扫描的条目上限。超大目录全扫一遍会让复制动作明显卡顿,+ // 超限时只报概要,进度条退化为未知总量。+ maxScanEntries = 20000++ streamIdleTimeout = 2 * time.Minute+)++type Engine struct {+ log *slog.Logger+ store *store.Store+ cache *cache.Cache+ watcher *clipboard.Watcher++ deviceID string+ deviceName func() string+ loadConfig func() config.Config++ // 传输层+ send func(deviceID string, msg *pb.PeerMessage) error+ broadcast func(msg *pb.PeerMessage) int+ openStream func(deviceID, label string) (*webrtc.DataChannel, error)+ onlinePeers func() []string++ // 事件回传给界面+ onRecord func(*pb.ClipRecord)+ onProgress func(*pb.TransferProgress)++ mu sync.Mutex+ // 正在接收中的流:stream_id -> 接收器+ incoming map[string]*receiver+}++type Options struct {+ Logger *slog.Logger+ Store *store.Store+ Cache *cache.Cache+ Watcher *clipboard.Watcher+ DeviceID string+ DeviceName func() string+ LoadConfig func() config.Config+ Send func(deviceID string, msg *pb.PeerMessage) error+ Broadcast func(msg *pb.PeerMessage) int+ OpenStream func(deviceID, label string) (*webrtc.DataChannel, error)+ OnlinePeers func() []string+ OnRecord func(*pb.ClipRecord)+ OnProgress func(*pb.TransferProgress)+}++func New(opts Options) *Engine {+ log := opts.Logger+ if log == nil {+ log = slog.Default()+ }+ return &Engine{+ log: log,+ store: opts.Store,+ cache: opts.Cache,+ watcher: opts.Watcher,+ deviceID: opts.DeviceID,+ deviceName: opts.DeviceName,+ loadConfig: opts.LoadConfig,+ send: opts.Send,+ broadcast: opts.Broadcast,+ openStream: opts.OpenStream,+ onlinePeers: opts.OnlinePeers,+ onRecord: opts.OnRecord,+ onProgress: opts.OnProgress,+ incoming: make(map[string]*receiver),+ }+}++// ─────────────────────── 本机复制 → 广播 ───────────────────────++// HandleClipboardChange 在本机剪贴板变化时调用。+func (e *Engine) HandleClipboardChange(ctx context.Context, snap clipboard.Snapshot) {+ cfg := e.loadConfig()+ if !e.kindEnabled(cfg, snap.Kind) {+ e.log.Debug("该类型已在设置中关闭,跳过", "kind", snap.Kind)+ return+ }++ readCtx, cancel := context.WithTimeout(ctx, 30*time.Second)+ defer cancel()++ content, err := e.watcher.Read(readCtx)+ if err != nil {+ if errors.Is(err, clipboard.ErrPermissionRequired) {+ // 授权缺失是常态而非异常:界面会引导用户去开,这里安静跳过+ e.log.Debug("尚未获得剪贴板授权,跳过本次变化")+ return+ }+ e.log.Warn("读取剪贴板失败", "err", err)+ return+ }++ e.log.Debug("已读取剪贴板内容",+ "kind", content.Kind, "文本长度", len(content.Text),+ "HTML长度", len(content.HTML), "图片字节", len(content.Image), "文件", content.Files)++ clip, err := e.recordOutgoing(content, cfg)+ if err != nil {+ e.log.Warn("记录本机复制失败", "err", err)+ return+ }++ e.emitRecord(clip)++ // 没有在线对端时只留本地记录,不必尝试发送+ if len(e.onlinePeers()) == 0 {+ return+ }++ offer := e.buildOffer(clip, cfg)+ sent := e.broadcast(&pb.PeerMessage{+ Payload: &pb.PeerMessage_Offer{Offer: offer},+ })+ e.log.Info("已广播剪贴板内容",+ "clip", clip.ID, "kind", clip.Kind, "size", clip.TotalSize, "对端数", sent)++ // 小内容随即推送,对端无需等待即可粘贴+ if offer.GetWillPush() && clip.Kind == store.KindFile || offer.GetWillPush() && clip.Kind == store.KindImage {+ for _, peer := range e.onlinePeers() {+ go e.pushTo(context.WithoutCancel(ctx), peer, clip)+ }+ }+}++// recordOutgoing 把本机复制的内容落库。+func (e *Engine) recordOutgoing(c clipboard.Content, cfg config.Config) (store.Clip, error) {+ now := time.Now()+ clip := store.Clip{+ ID: newID(),+ Status: store.StatusReady,+ OriginDeviceID: e.deviceID,+ OriginDeviceName: e.deviceName(),+ Outgoing: true,+ CreatedAt: now,+ ExpiresAt: now.Add(cfg.HistoryTTL.Std()),+ }++ switch c.Kind {+ case clipboard.KindText, clipboard.KindHTML:+ clip.Kind = store.KindText+ clip.TextContent = c.Text+ if c.Kind == clipboard.KindHTML {+ clip.Kind = store.KindHTML+ clip.TextContent = c.HTML+ clip.TextPlain = c.Text+ }+ clip.TextPreview = preview(plainText(clip))+ clip.TotalSize = int64(len(clip.TextContent))++ case clipboard.KindImage:+ clip.Kind = store.KindImage+ clip.TotalSize = int64(len(c.Image))+ clip.TextPreview = fmt.Sprintf("图片 %s", humanBytes(clip.TotalSize))+ // 图片直接落盘,供对端拉取时复用+ rel, abs, err := e.cache.Dir(clip.ID)+ if err != nil {+ return clip, err+ }+ imgPath := filepath.Join(abs, "image.png")+ if err := os.WriteFile(imgPath, c.Image, 0o600); err != nil {+ return clip, err+ }+ clip.CachePath = rel+ clip.SourcePaths = []string{imgPath}+ clip.Items = []store.Item{{+ Name: "image.png", Size: clip.TotalSize, ContentType: "public.png",+ }}++ case clipboard.KindFile:+ clip.Kind = store.KindFile+ clip.SourcePaths = c.Files+ stats, err := pack.Scan(c.Files, maxScanEntries)+ if err != nil {+ e.log.Debug("预扫描未完成", "err", err)+ }+ clip.TotalSize = stats.Bytes+ for _, p := range c.Files {+ info, err := os.Stat(p)+ if err != nil {+ continue+ }+ clip.Items = append(clip.Items, store.Item{+ Name: filepath.Base(p),+ Size: info.Size(),+ IsDir: info.IsDir(),+ })+ }+ if len(clip.Items) == 0 {+ return clip, errors.New("剪贴板中的文件都不可访问")+ }+ clip.TextPreview = describeItems(clip.Items)++ default:+ return clip, fmt.Errorf("不支持的剪贴板类型: %v", c.Kind)+ }++ if err := e.store.PutClip(clip); err != nil {+ return clip, err+ }+ return clip, nil+}++// buildOffer 决定这条内容是随即推送还是等对方来取。+func (e *Engine) buildOffer(clip store.Clip, cfg config.Config) *pb.ClipOffer {+ offer := &pb.ClipOffer{+ ClipId: clip.ID,+ Kind: pb.ClipKind(clip.Kind),+ TotalSize: clip.TotalSize,+ CreatedAtUnix: clip.CreatedAt.Unix(),+ }+ for _, it := range clip.Items {+ offer.Items = append(offer.Items, &pb.ClipItem{+ Name: it.Name, Size: it.Size, IsDir: it.IsDir, ContentType: it.ContentType,+ })+ }++ switch clip.Kind {+ case store.KindText, store.KindHTML:+ // 文本体积小,直接内联,省掉一次往返+ offer.TextContent = clip.TextContent+ offer.PlainText = clip.TextPlain+ offer.WillPush = false+ default:+ // 超过阈值的不主动推,避免无谓占用带宽和对端磁盘+ offer.WillPush = clip.TotalSize <= cfg.AutoSyncThresholdBytes+ }+ return offer+}++func (e *Engine) kindEnabled(cfg config.Config, k clipboard.Kind) bool {+ switch k {+ case clipboard.KindText:+ return cfg.SyncText+ case clipboard.KindHTML:+ return cfg.SyncHTML+ case clipboard.KindImage:+ return cfg.SyncImage+ case clipboard.KindFile:+ return cfg.SyncFile+ default:+ return false+ }+}++// ─────────────────────── 对端消息处理 ───────────────────────++func (e *Engine) HandlePeerMessage(ctx context.Context, from string, msg *pb.PeerMessage) {+ switch m := msg.GetPayload().(type) {+ case *pb.PeerMessage_Offer:+ e.handleOffer(ctx, from, m.Offer)+ case *pb.PeerMessage_Fetch:+ go e.handleFetch(context.WithoutCancel(ctx), from, m.Fetch.GetClipId())+ case *pb.PeerMessage_Reject:+ e.handleReject(m.Reject)+ case *pb.PeerMessage_Header:+ e.handleHeader(from, m.Header)+ case *pb.PeerMessage_Done:+ e.handleDone(m.Done)+ }+}++func (e *Engine) handleOffer(ctx context.Context, from string, offer *pb.ClipOffer) {+ cfg := e.loadConfig()+ now := time.Now()++ clip := store.Clip{+ ID: offer.GetClipId(),+ Kind: store.Kind(offer.GetKind()),+ OriginDeviceID: from,+ OriginDeviceName: e.peerName(from),+ Outgoing: false,+ TotalSize: offer.GetTotalSize(),+ TextContent: offer.GetTextContent(),+ TextPlain: offer.GetPlainText(),+ CreatedAt: time.Unix(offer.GetCreatedAtUnix(), 0),+ ExpiresAt: now.Add(cfg.HistoryTTL.Std()),+ }+ for _, it := range offer.GetItems() {+ clip.Items = append(clip.Items, store.Item{+ Name: it.GetName(), Size: it.GetSize(),+ IsDir: it.GetIsDir(), ContentType: it.GetContentType(),+ })+ }++ switch {+ case clip.Kind == store.KindText || clip.Kind == store.KindHTML:+ // 文本随 offer 一起到了,立即可用+ clip.Status = store.StatusReady+ clip.TextPreview = preview(plainText(clip))+ case offer.GetWillPush():+ // 对端马上会推流过来,先记为接收中+ clip.Status = store.StatusFetching+ clip.TextPreview = describeItems(clip.Items)+ default:+ // 超过阈值,等用户在界面上点拉取+ clip.Status = store.StatusRemoteOnly+ clip.TextPreview = describeItems(clip.Items)+ }++ if err := e.store.PutClip(clip); err != nil {+ e.log.Warn("保存对端记录失败", "err", err)+ return+ }+ e.emitRecord(clip)+ e.log.Info("收到对端剪贴板内容",+ "clip", clip.ID, "kind", clip.Kind, "status", clip.Status, "from", from)++ // 文本类内容可以马上写进剪贴板+ if clip.Status == store.StatusReady && cfg.AutoApplyToClipboard {+ if err := e.applyToClipboard(ctx, clip); err != nil {+ e.log.Warn("写入剪贴板失败", "err", err)+ }+ }+}++// handleFetch 响应对端的拉取请求:校验源文件仍在,然后开流发送。+func (e *Engine) handleFetch(ctx context.Context, from, clipID string) {+ clip, err := e.store.GetClip(clipID)+ if err != nil {+ e.reject(from, clipID, "记录不存在")+ return+ }+ if err := e.pushTo(ctx, from, clip); err != nil {+ e.log.Warn("响应拉取失败", "clip", clipID, "err", err)+ }+}++func (e *Engine) handleReject(r *pb.FetchReject) {+ e.log.Warn("对端拒绝了拉取请求", "clip", r.GetClipId(), "原因", r.GetReason())+ _ = e.store.SetClipStatus(r.GetClipId(), store.StatusFailed, r.GetReason())+ if clip, err := e.store.GetClip(r.GetClipId()); err == nil {+ e.emitRecord(clip)+ }+}++func (e *Engine) reject(to, clipID, reason string) {+ _ = e.send(to, &pb.PeerMessage{+ Payload: &pb.PeerMessage_Reject{Reject: &pb.FetchReject{+ ClipId: clipID, Reason: reason,+ }},+ })+}++// ─────────────────────── 发送 ───────────────────────++// pushTo 把某条记录的内容流式发给指定对端。+func (e *Engine) pushTo(ctx context.Context, peer string, clip store.Clip) error {+ paths, err := e.sourcePaths(clip)+ if err != nil {+ e.reject(peer, clip.ID, err.Error())+ return err+ }++ streamID := newID()+ packaging := pb.Packaging_PACKAGING_TAR+ if len(paths) == 1 {+ if info, err := os.Stat(paths[0]); err == nil && !info.IsDir() {+ packaging = pb.Packaging_PACKAGING_RAW+ }+ }++ // 先发头,对端据此准备接收;随后的裸字节都属于这条流+ if err := e.send(peer, &pb.PeerMessage{+ Payload: &pb.PeerMessage_Header{Header: &pb.TransferHeader{+ ClipId: clip.ID,+ StreamId: streamID,+ TotalBytes: clip.TotalSize,+ Compression: pb.Compression_COMPRESSION_ZSTD,+ Packaging: packaging,+ }},+ }); err != nil {+ return fmt.Errorf("发送传输头: %w", err)+ }++ dc, err := e.openStream(peer, streamID)+ if err != nil {+ return fmt.Errorf("打开数据流: %w", err)+ }++ opened := make(chan struct{})+ dc.OnOpen(func() { close(opened) })+ select {+ case <-opened:+ case <-time.After(30 * time.Second):+ dc.Close()+ return errors.New("数据流打开超时")+ case <-ctx.Done():+ dc.Close()+ return ctx.Err()+ }++ start := time.Now()+ w := newChunkWriter(dc, func(sent int64) {+ e.emitProgress(clip.ID, sent, clip.TotalSize, start)+ })++ var packErr error+ if packaging == pb.Packaging_PACKAGING_RAW {+ packErr = packRaw(w, paths[0])+ } else {+ packErr = pack.Pack(w, paths)+ }+ if flushErr := w.Flush(); packErr == nil {+ packErr = flushErr+ }++ // 等发送缓冲排空再关闭,否则尾部数据会被丢弃+ w.WaitDrained(ctx, 60*time.Second)+ dc.Close()++ ok := packErr == nil+ errMsg := ""+ if packErr != nil {+ errMsg = packErr.Error()+ }+ _ = e.send(peer, &pb.PeerMessage{+ Payload: &pb.PeerMessage_Done{Done: &pb.TransferDone{+ ClipId: clip.ID, StreamId: streamID, Ok: ok, Error: errMsg,+ }},+ })++ if packErr != nil {+ return packErr+ }+ e.log.Info("内容已发送",+ "clip", clip.ID, "to", peer, "字节", w.Sent(), "耗时", time.Since(start).Round(time.Millisecond))+ return nil+}++// sourcePaths 找出这条记录当前可用的源路径。+//+// 优先用原始位置(本机复制的内容),其次用缓存(从对端收来的内容)。+// 两者都没有时说明源文件已被移动或删除。+func (e *Engine) sourcePaths(clip store.Clip) ([]string, error) {+ if len(clip.SourcePaths) > 0 {+ var alive []string+ for _, p := range clip.SourcePaths {+ if _, err := os.Stat(p); err == nil {+ alive = append(alive, p)+ }+ }+ if len(alive) > 0 {+ return alive, nil+ }+ }+ if clip.CachePath != "" && e.cache.Exists(clip.CachePath) {+ return e.cache.Entries(clip.CachePath)+ }+ return nil, errors.New("源文件已不存在")+}++func packRaw(w io.Writer, path string) error {+ f, err := os.Open(path)+ if err != nil {+ return err+ }+ defer f.Close()+ // 单文件也走 zstd,与 tar 分支保持一致的解码路径+ return pack.Pack(w, []string{path})+}++// ─────────────────────── 接收 ───────────────────────++// receiver 承接一条进行中的数据流。+type receiver struct {+ clipID string+ streamID string+ from string+ total int64+ received int64+ pipeW *io.PipeWriter+ done chan error+ start time.Time+}++func (e *Engine) handleHeader(from string, h *pb.TransferHeader) {+ rel, abs, err := e.cache.Dir(h.GetClipId())+ if err != nil {+ e.log.Warn("准备缓存目录失败", "err", err)+ return+ }++ pr, pw := io.Pipe()+ r := &receiver{+ clipID: h.GetClipId(),+ streamID: h.GetStreamId(),+ from: from,+ total: h.GetTotalBytes(),+ pipeW: pw,+ done: make(chan error, 1),+ start: time.Now(),+ }++ e.mu.Lock()+ e.incoming[h.GetStreamId()] = r+ e.mu.Unlock()++ _ = e.store.SetClipStatus(h.GetClipId(), store.StatusFetching, "")++ // 边收边解包:不等整条流收完就开始落盘,大文件才不会先堆在内存里+ go func() {+ tops, err := pack.Unpack(pr, abs)+ if err != nil {+ pr.CloseWithError(err)+ e.log.Warn("解包失败", "clip", r.clipID, "err", err)+ _ = e.store.SetClipStatus(r.clipID, store.StatusFailed, err.Error())+ r.done <- err+ return+ }+ e.finishReceive(r, rel, tops)+ r.done <- nil+ }()+}++// HandlePeerStream 接管对端新开的数据通道。+func (e *Engine) HandlePeerStream(from, label string, stream *p2p.Stream) {+ e.mu.Lock()+ r := e.incoming[label]+ e.mu.Unlock()++ if r == nil {+ // 头还没到就先收到了流。等一小会儿,控制通道与数据通道是两条独立的路,+ // 到达顺序并不保证。+ go func() {+ deadline := time.Now().Add(10 * time.Second)+ for time.Now().Before(deadline) {+ time.Sleep(50 * time.Millisecond)+ e.mu.Lock()+ r = e.incoming[label]+ e.mu.Unlock()+ if r != nil {+ e.bindStream(r, stream)+ return+ }+ }+ e.log.Warn("收到无对应传输头的数据流,已丢弃", "stream", label, "from", from)+ stream.Close()+ }()+ return+ }+ e.bindStream(r, stream)+}++func (e *Engine) bindStream(r *receiver, stream *p2p.Stream) {+ e.log.Debug("已绑定数据流", "stream", r.streamID, "clip", r.clipID,+ "state", stream.ReadyState())++ idle := time.AfterFunc(streamIdleTimeout, func() {+ r.pipeW.CloseWithError(errors.New("传输超时中断"))+ stream.Close()+ })++ // Stream 的队列保证顺序与完整性,这里只管按序搬进管道。+ // 队列在对端关闭数据流时关闭,循环随之退出并收尾。+ go func() {+ defer idle.Stop()+ defer r.pipeW.Close()++ for chunk := range stream.Chunks() {+ idle.Reset(streamIdleTimeout)+ if _, err := r.pipeW.Write(chunk); err != nil {+ stream.Close()+ return+ }+ r.received += int64(len(chunk))+ e.emitProgress(r.clipID, r.received, r.total, r.start)+ }+ }()+}++func (e *Engine) finishReceive(r *receiver, cacheRel string, tops []string) {+ e.mu.Lock()+ delete(e.incoming, r.streamID)+ e.mu.Unlock()++ var size int64+ for _, p := range tops {+ if info, err := os.Stat(p); err == nil {+ size += info.Size()+ }+ }+ if err := e.store.SetClipCache(r.clipID, cacheRel, max64(size, r.received)); err != nil {+ e.log.Warn("更新缓存记录失败", "err", err)+ }++ clip, err := e.store.GetClip(r.clipID)+ if err != nil {+ return+ }+ e.emitRecord(clip)+ e.log.Info("内容接收完成",+ "clip", r.clipID, "from", r.from, "收到字节", r.received,+ "条目", len(tops), "耗时", time.Since(r.start).Round(time.Millisecond))++ if e.loadConfig().AutoApplyToClipboard {+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()+ if err := e.applyToClipboard(ctx, clip); err != nil {+ e.log.Warn("写入剪贴板失败", "err", err)+ }+ }+}++func (e *Engine) handleDone(d *pb.TransferDone) {+ if d.GetOk() {+ return+ }+ e.log.Warn("对端报告传输失败", "clip", d.GetClipId(), "err", d.GetError())+ _ = e.store.SetClipStatus(d.GetClipId(), store.StatusFailed, d.GetError())+ if clip, err := e.store.GetClip(d.GetClipId()); err == nil {+ e.emitRecord(clip)+ }+}++// ─────────────────────── 对外操作 ───────────────────────++// Fetch 主动拉取一条仅有元数据的记录。+func (e *Engine) Fetch(ctx context.Context, clipID string) error {+ clip, err := e.store.GetClip(clipID)+ if err != nil {+ return err+ }+ if clip.Outgoing {+ return errors.New("这是本机复制的内容,无需拉取")+ }+ if err := e.send(clip.OriginDeviceID, &pb.PeerMessage{+ Payload: &pb.PeerMessage_Fetch{Fetch: &pb.PeerFetch{ClipId: clipID}},+ }); err != nil {+ return fmt.Errorf("源设备当前不可达: %w", err)+ }+ _ = e.store.SetClipStatus(clipID, store.StatusFetching, "")+ if c, err := e.store.GetClip(clipID); err == nil {+ e.emitRecord(c)+ }+ return nil+}++// ApplyToClipboard 把某条已就绪的记录写入本机剪贴板。+func (e *Engine) ApplyToClipboard(ctx context.Context, clipID string) error {+ clip, err := e.store.GetClip(clipID)+ if err != nil {+ return err+ }+ return e.applyToClipboard(ctx, clip)+}++func (e *Engine) applyToClipboard(ctx context.Context, clip store.Clip) error {+ var content clipboard.Content++ switch clip.Kind {+ case store.KindText:+ content = clipboard.Content{Kind: clipboard.KindText, Text: clip.TextContent}+ case store.KindHTML:+ content = clipboard.Content{+ Kind: clipboard.KindHTML, HTML: clip.TextContent, Text: plainText(clip),+ }+ case store.KindImage, store.KindFile:+ paths, err := e.localPaths(clip)+ if err != nil {+ return err+ }+ if clip.Kind == store.KindImage && len(paths) == 1 {+ data, err := os.ReadFile(paths[0])+ if err == nil {+ content = clipboard.Content{Kind: clipboard.KindImage, Image: data}+ break+ }+ }+ content = clipboard.Content{Kind: clipboard.KindFile, Files: paths}+ default:+ return fmt.Errorf("不支持写入剪贴板的类型: %v", clip.Kind)+ }++ return e.watcher.Write(ctx, content)+}++// localPaths 返回这条记录在本机可用的实际路径。+func (e *Engine) localPaths(clip store.Clip) ([]string, error) {+ if clip.CachePath != "" && e.cache.Exists(clip.CachePath) {+ return e.cache.Entries(clip.CachePath)+ }+ if len(clip.SourcePaths) > 0 {+ var alive []string+ for _, p := range clip.SourcePaths {+ if _, err := os.Stat(p); err == nil {+ alive = append(alive, p)+ }+ }+ if len(alive) > 0 {+ return alive, nil+ }+ }+ return nil, errors.New("内容已不在本机(可能已过期被清理)")+}++// ─────────────────────── 辅助 ───────────────────────++func (e *Engine) emitRecord(clip store.Clip) {+ if e.onRecord == nil {+ return+ }+ items := make([]*pb.ClipItem, 0, len(clip.Items))+ for _, it := range clip.Items {+ items = append(items, &pb.ClipItem{+ Name: it.Name, Size: it.Size, IsDir: it.IsDir, ContentType: it.ContentType,+ })+ }+ e.onRecord(&pb.ClipRecord{+ Id: clip.ID,+ Kind: pb.ClipKind(clip.Kind),+ Status: pb.ClipStatus(clip.Status),+ OriginDeviceId: clip.OriginDeviceID,+ OriginDeviceName: clip.OriginDeviceName,+ Outgoing: clip.Outgoing,+ Items: items,+ TotalSize: clip.TotalSize,+ TextPreview: clip.TextPreview,+ CreatedAtUnix: clip.CreatedAt.Unix(),+ ExpiresAtUnix: clip.ExpiresAt.Unix(),+ Error: clip.Error,+ })+}++func (e *Engine) emitProgress(clipID string, sent, total int64, start time.Time) {+ if e.onProgress == nil {+ return+ }+ elapsed := time.Since(start).Seconds()+ var rate float64+ if elapsed > 0 {+ rate = float64(sent) / elapsed+ }+ e.onProgress(&pb.TransferProgress{+ ClipId: clipID, Transferred: sent, Total: total, BytesPerSecond: rate,+ })+}++// peerName 取对端设备名用于展示;查不到就退回 ID。+func (e *Engine) peerName(deviceID string) string {+ devices, err := e.store.ListDevices()+ if err != nil {+ return deviceID+ }+ for _, d := range devices {+ if d.ID == deviceID {+ return d.Name+ }+ }+ return deviceID+}++func newID() string {+ b := make([]byte, 12)+ if _, err := rand.Read(b); err != nil {+ return fmt.Sprintf("clip-%d", time.Now().UnixNano())+ }+ return hex.EncodeToString(b)+}++func preview(s string) string {+ s = strings.TrimSpace(strings.ReplaceAll(s, "\n", " "))+ const limit = 120+ if len(s) <= limit {+ return s+ }+ // 按 rune 截断,避免把多字节字符切一半+ runes := []rune(s)+ if len(runes) <= limit {+ return s+ }+ return string(runes[:limit]) + "…"+}++func describeItems(items []store.Item) string {+ switch len(items) {+ case 0:+ return ""+ case 1:+ return items[0].Name+ default:+ return fmt.Sprintf("%s 等 %d 项", items[0].Name, len(items))+ }+}++func humanBytes(n int64) string {+ const unit = 1024+ if n < unit {+ return fmt.Sprintf("%d B", n)+ }+ div, exp := int64(unit), 0+ for v := n / unit; v >= unit; v /= unit {+ div *= unit+ exp+++ }+ return fmt.Sprintf("%.1f %cB", float64(n)/float64(div), "KMGTPE"[exp])+}++func max64(a, b int64) int64 {+ if a > b {+ return a+ }+ return b+}diff --git a/client-core/internal/sync/plaintext.go b/client-core/internal/sync/plaintext.gonew file mode 100644index 0000000..c789ab1--- /dev/null+++ b/client-core/internal/sync/plaintext.go@@ -0,0 +1,148 @@+package sync++import (+ "strings"+ "unicode"+ "unicode/utf8"++ "golang.org/x/net/html"+ "golang.org/x/net/html/atom"++ "github.com/baiyuze/copysync/client-core/internal/store"+)++// plainText 返回记录的纯文本形式:写入剪贴板的纯文本类型、生成预览都用它。+//+// HTML 记录必须单独给出纯文本——只认纯文本的输入框会把 HTML 原样粘出来,+// 满屏 <meta charset='utf-8'> 之类的标签。+func plainText(c store.Clip) string {+ if c.Kind != store.KindHTML {+ return c.TextContent+ }+ if c.TextPlain != "" {+ return c.TextPlain+ }+ // 升级前存下的记录、旧版本对端发来的内容都没有纯文本,只能从 HTML 里提取+ return htmlToText(c.TextContent)+}++// htmlToText 把 HTML 粗略转成纯文本:去掉标签与不可见内容,块级元素换行。+// 只是兜底,源应用自己放进剪贴板的纯文本永远比这准确。+func htmlToText(s string) string {+ z := html.NewTokenizer(strings.NewReader(s))+ var w textWriter+ hidden, pre := 0, 0 // 处于 script/style 内、<pre> 内的嵌套深度++ for {+ tt := z.Next()+ switch tt {+ case html.ErrorToken:+ return strings.TrimSpace(w.String())++ case html.TextToken:+ if hidden > 0 {+ continue+ }+ if pre > 0 {+ w.raw(string(z.Text()))+ } else {+ w.collapsed(string(z.Text()))+ }++ case html.StartTagToken, html.SelfClosingTagToken, html.EndTagToken:+ name, _ := z.TagName()+ a := atom.Lookup(name)+ start := tt != html.EndTagToken+ switch {+ case a == atom.Script || a == atom.Style || a == atom.Title || a == atom.Template:+ if tt == html.StartTagToken {+ hidden+++ } else if tt == html.EndTagToken && hidden > 0 {+ hidden--+ }+ case a == atom.Br:+ w.raw("\n")+ case a == atom.Pre:+ if tt == html.StartTagToken {+ pre+++ } else if tt == html.EndTagToken && pre > 0 {+ pre--+ }+ w.lineBreak()+ case a == atom.Td || a == atom.Th:+ if start {+ w.separator()+ }+ case blockElements[a]:+ w.lineBreak()+ }+ }+ }+}++var blockElements = map[atom.Atom]bool{+ atom.P: true, atom.Div: true, atom.Li: true, atom.Ul: true, atom.Ol: true,+ atom.Tr: true, atom.Table: true, atom.Blockquote: true, atom.Hr: true,+ atom.H1: true, atom.H2: true, atom.H3: true, atom.H4: true, atom.H5: true, atom.H6: true,+ atom.Section: true, atom.Article: true, atom.Header: true, atom.Footer: true,+ atom.Dt: true, atom.Dd: true,+}++// textWriter 负责空白处理:HTML 源码里的换行与缩进不算内容,+// 换行只由块级元素与 <br> 产生。+type textWriter struct {+ b strings.Builder+ last rune+}++func (w *textWriter) String() string { return w.b.String() }++func (w *textWriter) atLineStart() bool { return w.b.Len() == 0 || w.last == '\n' }++func (w *textWriter) raw(s string) {+ if s == "" {+ return+ }+ w.b.WriteString(s)+ w.last, _ = utf8.DecodeLastRuneInString(s)+}++// collapsed 按浏览器的规则把连续空白折叠成一个空格,行首空白直接丢弃。+func (w *textWriter) collapsed(s string) {+ for _, r := range s {+ if unicode.IsSpace(r) {+ if !w.atLineStart() && w.last != ' ' {+ w.b.WriteByte(' ')+ w.last = ' '+ }+ continue+ }+ w.b.WriteRune(r)+ w.last = r+ }+}++func (w *textWriter) lineBreak() {+ if !w.atLineStart() {+ w.trimTrailingSpace()+ w.b.WriteByte('\n')+ w.last = '\n'+ }+}++func (w *textWriter) separator() {+ if !w.atLineStart() && w.last != ' ' {+ w.b.WriteByte(' ')+ w.last = ' '+ }+}++func (w *textWriter) trimTrailingSpace() {+ if w.last != ' ' {+ return+ }+ s := strings.TrimRight(w.b.String(), " ")+ w.b.Reset()+ w.b.WriteString(s)+ w.last, _ = utf8.DecodeLastRuneInString(s) // 空串时为 RuneError,atLineStart 看的是长度+}diff --git a/client-core/internal/sync/plaintext_test.go b/client-core/internal/sync/plaintext_test.gonew file mode 100644index 0000000..4936150--- /dev/null+++ b/client-core/internal/sync/plaintext_test.go@@ -0,0 +1,51 @@+package sync++import (+ "testing"++ "github.com/baiyuze/copysync/client-core/internal/store"+)++func TestHTMLToText(t *testing.T) {+ cases := []struct{ name, in, want string }{+ // 浏览器、Electron 应用复制文字时放进剪贴板的 HTML 就长这样+ {"浏览器的 meta 前缀", "<meta charset='utf-8'>用新签名覆盖安装,因为我快过期了签名",+ "用新签名覆盖安装,因为我快过期了签名"},+ {"实体解码", "<span>a & b <c></span>", "a & b <c>"},+ {"块级元素换行", "<div>第一行</div><div>第二行</div>", "第一行\n第二行"},+ {"br 换行", "一<br>二<br/>三", "一\n二\n三"},+ {"源码缩进不算内容", "<ul>\n <li>甲</li>\n <li>乙</li>\n</ul>", "甲\n乙"},+ {"文本内空白折叠", "<p>\n hello\n world\n</p>", "hello world"},+ {"不可见内容丢弃", "<style>p{color:red}</style><p>正文</p><script>alert(1)</script>", "正文"},+ {"pre 保留格式", "<pre>a\n b</pre>", "a\n b"},+ {"表格", "<table><tr><td>A</td><td>B</td></tr><tr><td>C</td><td>D</td></tr></table>",+ "A B\nC D"},+ }+ for _, c := range cases {+ t.Run(c.name, func(t *testing.T) {+ if got := htmlToText(c.in); got != c.want {+ t.Errorf("htmlToText(%q) = %q,期望 %q", c.in, got, c.want)+ }+ })+ }+}++func TestPlainText(t *testing.T) {+ // 源应用给出的纯文本优先,它比从 HTML 提取的准确+ html := store.Clip{Kind: store.KindHTML, TextContent: "<b>粗体</b>", TextPlain: "**粗体**"}+ if got := plainText(html); got != "**粗体**" {+ t.Errorf("有纯文本时应原样使用,得到 %q", got)+ }++ // 升级前的记录、旧版本对端发来的内容没有纯文本+ legacy := store.Clip{Kind: store.KindHTML, TextContent: "<meta charset='utf-8'>你好"}+ if got := plainText(legacy); got != "你好" {+ t.Errorf("缺纯文本时应从 HTML 提取,得到 %q", got)+ }++ // 纯文本记录里的尖括号是用户复制的内容本身(比如一段代码),绝不能当标签剥掉+ text := store.Clip{Kind: store.KindText, TextContent: "<div>不是标签</div>"}+ if got := plainText(text); got != "<div>不是标签</div>" {+ t.Errorf("纯文本记录应原样返回,得到 %q", got)+ }+}diff --git a/client-core/internal/transport/p2p/manager.go b/client-core/internal/transport/p2p/manager.gonew file mode 100644index 0000000..06ee9e3--- /dev/null+++ b/client-core/internal/transport/p2p/manager.go@@ -0,0 +1,229 @@+package p2p++import (+ "context"+ "log/slog"+ "sync"++ "github.com/pion/webrtc/v4"++ pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"+)++// Manager 管理与所有已配对设备的 P2P 连接。+type Manager struct {+ selfID string+ log *slog.Logger++ sendSignal func(ctx context.Context, to string, msg *pb.SignalMessage) error+ onState func(deviceID string, state ConnState)+ onMessage func(deviceID string, msg *pb.PeerMessage)+ onStream func(deviceID, label string, stream *Stream)++ mu sync.RWMutex+ peers map[string]*Peer+ iceServers []webrtc.ICEServer+ forceRelay bool+}++type ManagerOptions struct {+ SelfID string+ Logger *slog.Logger+ SendSignal func(ctx context.Context, to string, msg *pb.SignalMessage) error+ OnState func(deviceID string, state ConnState)+ OnMessage func(deviceID string, msg *pb.PeerMessage)+ OnStream func(deviceID, label string, stream *Stream)+ // ForceRelay 强制走 TURN 中转,用于验证中转链路+ ForceRelay bool+}++func NewManager(opts ManagerOptions) *Manager {+ log := opts.Logger+ if log == nil {+ log = slog.Default()+ }+ return &Manager{+ selfID: opts.SelfID,+ log: log,+ sendSignal: opts.SendSignal,+ onState: opts.OnState,+ onMessage: opts.OnMessage,+ onStream: opts.OnStream,+ peers: make(map[string]*Peer),+ forceRelay: opts.ForceRelay,+ }+}++// SetICEServers 更新 STUN/TURN 配置。信令服务器在握手时下发,+// TURN 凭证是短期的,需要定期刷新。+func (m *Manager) SetICEServers(servers []*pb.IceServer) {+ converted := make([]webrtc.ICEServer, 0, len(servers))+ for _, s := range servers {+ converted = append(converted, webrtc.ICEServer{+ URLs: s.GetUrls(),+ Username: s.GetUsername(),+ Credential: s.GetCredential(),+ })+ }++ m.mu.Lock()+ m.iceServers = converted+ m.mu.Unlock()++ m.log.Debug("ICE 配置已更新", "servers", len(converted))+}++// Connect 与对端建立连接。双方都可以调用,不会因此产生 glare。+//+// 由 device_id 字典序较小的一方发起 offer,另一方只准备好接收。+// 这个约定两端各自可算出、无需协商,从根上避免了双方同时发 offer 的竞争——+// 比事后用 rollback 去化解冲突简单得多,也更不容易出错。+func (m *Manager) Connect(ctx context.Context, deviceID string) error {+ p, err := m.peer(deviceID)+ if err != nil {+ return err+ }+ if m.selfID > deviceID {+ // 本端负责应答:Peer 对象已就绪,等对方的 offer 到来即可+ m.log.Debug("等待对端发起连接", "peer", deviceID)+ return nil+ }+ return p.Connect(ctx)+}++// HandleSignal 把验签后的信令分派给对应的 Peer。+func (m *Manager) HandleSignal(ctx context.Context, from string, msg *pb.SignalMessage) error {+ p, err := m.peer(from)+ if err != nil {+ return err+ }+ return p.HandleSignal(ctx, msg)+}++// Send 向对端发送控制消息。+func (m *Manager) Send(deviceID string, msg *pb.PeerMessage) error {+ m.mu.RLock()+ p := m.peers[deviceID]+ m.mu.RUnlock()++ if p == nil {+ return ErrNotConnected+ }+ return p.Send(msg)+}++// Broadcast 把消息发给所有已连接的对端,返回成功送达的数量。+func (m *Manager) Broadcast(msg *pb.PeerMessage) int {+ m.mu.RLock()+ peers := make([]*Peer, 0, len(m.peers))+ for _, p := range m.peers {+ peers = append(peers, p)+ }+ m.mu.RUnlock()++ var sent int+ for _, p := range peers {+ if err := p.Send(msg); err == nil {+ sent+++ }+ }+ return sent+}++func (m *Manager) OpenStream(deviceID, label string) (*webrtc.DataChannel, error) {+ m.mu.RLock()+ p := m.peers[deviceID]+ m.mu.RUnlock()++ if p == nil {+ return nil, ErrNotConnected+ }+ return p.OpenStream(label)+}++func (m *Manager) State(deviceID string) ConnState {+ m.mu.RLock()+ p := m.peers[deviceID]+ m.mu.RUnlock()++ if p == nil {+ return StateOffline+ }+ return p.State()+}++// Disconnect 断开并丢弃与某个对端的连接(解除配对或对端离线时)。+func (m *Manager) Disconnect(deviceID string) {+ m.mu.Lock()+ p := m.peers[deviceID]+ delete(m.peers, deviceID)+ m.mu.Unlock()++ if p != nil {+ p.Close()+ }+}++func (m *Manager) CloseAll() {+ m.mu.Lock()+ peers := m.peers+ m.peers = make(map[string]*Peer)+ m.mu.Unlock()++ for _, p := range peers {+ p.Close()+ }+}++// peer 取出或按需创建与某设备的连接对象。+func (m *Manager) peer(deviceID string) (*Peer, error) {+ m.mu.Lock()+ if p, ok := m.peers[deviceID]; ok {+ m.mu.Unlock()+ return p, nil+ }+ ice := m.iceServers+ forceRelay := m.forceRelay+ m.mu.Unlock()++ p, err := NewPeer(PeerOptions{+ DeviceID: deviceID,+ SelfID: m.selfID,+ Logger: m.log,+ ICEServers: ice,+ ForceRelay: forceRelay,+ SendSignal: func(ctx context.Context, msg *pb.SignalMessage) error {+ return m.sendSignal(ctx, deviceID, msg)+ },+ OnState: func(s ConnState) {+ if m.onState != nil {+ m.onState(deviceID, s)+ }+ },+ OnMessage: func(msg *pb.PeerMessage) {+ if m.onMessage != nil {+ m.onMessage(deviceID, msg)+ }+ },+ OnStream: func(label string, stream *Stream) {+ if m.onStream != nil {+ m.onStream(deviceID, label, stream)+ }+ },+ })+ if err != nil {+ return nil, err+ }++ m.mu.Lock()+ // 双检:并发调用时可能已有别的 goroutine 建好了+ if existing, ok := m.peers[deviceID]; ok {+ m.mu.Unlock()+ p.Close()+ return existing, nil+ }+ m.peers[deviceID] = p+ m.mu.Unlock()++ return p, nil+}diff --git a/client-core/internal/transport/p2p/peer.go b/client-core/internal/transport/p2p/peer.gonew file mode 100644index 0000000..44e34f4--- /dev/null+++ b/client-core/internal/transport/p2p/peer.go@@ -0,0 +1,625 @@+// Package p2p 在设备之间建立 WebRTC 连接:优先 ICE 直连打洞,+// 打不通时自动降级到 TURN 中转。+//+// 安全性依赖 DTLS:DataChannel 的内容经 DTLS+SCTP 加密,TURN 只转发 UDP+// 数据包,看不到明文。而 DTLS 证书指纹经信令传输时由设备私钥签名,+// 信令服务器无法替换——这封死了中间人攻击的入口。+package p2p++import (+ "context"+ "errors"+ "fmt"+ "log/slog"+ "strings"+ "sync"+ "time"++ "github.com/pion/webrtc/v4"+ "google.golang.org/protobuf/proto"++ pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"+)++// ConnState 是对端连接的状态,会上报给界面。+type ConnState int++const (+ StateOffline ConnState = iota+ StateConnecting+ StateDirect // ICE 打洞成功,点对点直连+ StateRelay // 打洞失败,经 TURN 中转+)++func (s ConnState) String() string {+ switch s {+ case StateConnecting:+ return "connecting"+ case StateDirect:+ return "direct"+ case StateRelay:+ return "relay"+ default:+ return "offline"+ }+}++func (s ConnState) Proto() pb.ConnectionKind {+ switch s {+ case StateDirect:+ return pb.ConnectionKind_CONNECTION_KIND_DIRECT+ case StateRelay:+ return pb.ConnectionKind_CONNECTION_KIND_RELAY+ case StateOffline:+ return pb.ConnectionKind_CONNECTION_KIND_OFFLINE+ default:+ return pb.ConnectionKind_CONNECTION_KIND_UNSPECIFIED+ }+}++const (+ controlChannelLabel = "control"+ connectTimeout = 30 * time.Second+)++// Peer 管理与单个对端的 WebRTC 连接。+type Peer struct {+ deviceID string+ log *slog.Logger++ // sendSignal 把信令发给对端(经信令服务器转发,带签名)+ sendSignal func(ctx context.Context, msg *pb.SignalMessage) error+ onState func(ConnState)+ onMessage func(*pb.PeerMessage)+ // onStream 处理对端新开的数据流(大文件传输用)+ onStream func(label string, stream *Stream)++ api *webrtc.API+ config webrtc.Configuration++ mu sync.Mutex+ pc *webrtc.PeerConnection+ control *webrtc.DataChannel+ state ConnState+ // 对端 DTLS 指纹,来自签名过的信令。握手完成后必须与实际使用的证书一致。+ expectFingerprint string+ // 已缓存但尚未能加入的 candidate(remote description 还没设置时会发生)+ pendingCandidates []webrtc.ICECandidateInit+ // polite 决定 glare(双方同时发起)时谁让步+ polite bool+ // makingOffer 用于识别 glare:本端正在发 offer 时又收到对方的 offer+ makingOffer bool++ // 连接就绪需要两个条件同时满足:ICE/DTLS 握手完成,且控制通道已打开。+ // 只看前者会导致状态报成"已连接"但 Send 立刻失败。+ pcConnected bool+ pendingKind ConnState+ // connectTimer 在握手迟迟不完成时触发重置,避免永久卡在 connecting+ connectTimer *time.Timer+ // dialing 表示 Connect 正在进行中,防止并发重入建出两个 PeerConnection+ dialing bool+}++type PeerOptions struct {+ DeviceID string+ SelfID string+ Logger *slog.Logger+ ICEServers []webrtc.ICEServer+ // ForceRelay 强制只用 TURN 中转,不尝试直连。+ // 用于验证中转链路是否可用——正常运行时应保持关闭。+ ForceRelay bool+ SendSignal func(ctx context.Context, msg *pb.SignalMessage) error+ OnState func(ConnState)+ OnMessage func(*pb.PeerMessage)+ OnStream func(label string, stream *Stream)+}++func NewPeer(opts PeerOptions) (*Peer, error) {+ log := opts.Logger+ if log == nil {+ log = slog.Default()+ }++ // 刻意不启用 SettingEngine.DetachDataChannels():+ // 它是全局开关,一旦开启,所有通道的 OnMessage/Send 都失效,必须改用+ // dc.Detach() 拿裸流。控制通道用消息回调更自然,而文件传输所需的+ // 分片与背压(BufferedAmount / OnBufferedAmountLow)本来就要自己处理,+ // 统一走消息接口反而让两类通道的代码保持一致。+ settings := webrtc.SettingEngine{}++ config := webrtc.Configuration{ICEServers: opts.ICEServers}+ if opts.ForceRelay {+ config.ICETransportPolicy = webrtc.ICETransportPolicyRelay+ }++ return &Peer{+ deviceID: opts.DeviceID,+ log: log.With("peer", opts.DeviceID),+ sendSignal: opts.SendSignal,+ onState: opts.OnState,+ onMessage: opts.OnMessage,+ onStream: opts.OnStream,+ api: webrtc.NewAPI(webrtc.WithSettingEngine(settings)),+ config: config,+ // 用 device_id 字典序决定礼让方:双方规则一致且无需协商,+ // 天然避免两端同时发 offer 时的死锁。+ polite: opts.SelfID > opts.DeviceID,+ }, nil+}++func (p *Peer) State() ConnState {+ p.mu.Lock()+ defer p.mu.Unlock()+ return p.state+}++func (p *Peer) setState(s ConnState) {+ p.mu.Lock()+ changed := p.state != s+ p.state = s+ p.mu.Unlock()++ if changed {+ p.log.Debug("连接状态变化", "state", s)+ if p.onState != nil {+ p.onState(s)+ }+ }+}++// Connect 主动发起连接。已在连接中或已连通时直接返回。+func (p *Peer) Connect(ctx context.Context) error {+ // 必须在同一个临界区里完成"检查 + 占位"。+ //+ // 否则两个 goroutine(配对确认与上线通知常常同时触发)都会看到+ // pc == nil,各建一个 PeerConnection,后者覆盖前者;对端回来的+ // answer 属于前一个,落到后一个身上就成了"时序不符"而被丢弃,+ // 握手随之永久卡住。+ p.mu.Lock()+ if p.pc != nil || p.dialing {+ p.mu.Unlock()+ return nil+ }+ p.dialing = true+ p.mu.Unlock()++ defer func() {+ p.mu.Lock()+ p.dialing = false+ p.mu.Unlock()+ }()++ pc, err := p.newPeerConnection()+ if err != nil {+ return err+ }++ // 发起方创建控制通道;应答方靠 OnDataChannel 拿到它+ ordered := true+ dc, err := pc.CreateDataChannel(controlChannelLabel, &webrtc.DataChannelInit{+ Ordered: &ordered,+ })+ if err != nil {+ return fmt.Errorf("创建控制通道: %w", err)+ }+ p.bindControl(dc)++ p.mu.Lock()+ p.makingOffer = true+ p.mu.Unlock()+ defer func() {+ p.mu.Lock()+ p.makingOffer = false+ p.mu.Unlock()+ }()++ offer, err := pc.CreateOffer(nil)+ if err != nil {+ return fmt.Errorf("创建 offer: %w", err)+ }+ if err := pc.SetLocalDescription(offer); err != nil {+ return fmt.Errorf("设置本地描述: %w", err)+ }++ p.setState(StateConnecting)+ p.armConnectTimeout()++ return p.sendSignal(ctx, &pb.SignalMessage{+ Payload: &pb.SignalMessage_Offer{Offer: &pb.SdpOffer{+ Sdp: offer.SDP,+ DtlsFingerprint: fingerprintFromSDP(offer.SDP),+ }},+ })+}++// armConnectTimeout 在握手迟迟不完成时重置连接,让上层得以重试。+//+// 现实中有多种情况会让 offer 石沉大海:对端刚完成配对、尚未把本端加入+// 已配对列表,于是把 offer 当作未配对设备的消息丢弃;或者信令在网络切换+// 时丢包。没有这道兜底,Peer 会永远停在 connecting。+func (p *Peer) armConnectTimeout() {+ p.mu.Lock()+ if p.connectTimer != nil {+ p.connectTimer.Stop()+ }+ p.connectTimer = time.AfterFunc(connectTimeout, func() {+ if p.State() == StateConnecting {+ p.log.Warn("连接握手超时,重置以便重试")+ p.Close()+ }+ })+ p.mu.Unlock()+}+func (p *Peer) HandleSignal(ctx context.Context, msg *pb.SignalMessage) error {+ switch m := msg.GetPayload().(type) {+ case *pb.SignalMessage_Offer:+ return p.handleOffer(ctx, m.Offer)+ case *pb.SignalMessage_Answer:+ return p.handleAnswer(m.Answer)+ case *pb.SignalMessage_Candidate:+ return p.handleCandidate(m.Candidate)+ default:+ return nil+ }+}++func (p *Peer) handleOffer(ctx context.Context, offer *pb.SdpOffer) error {+ p.mu.Lock()+ pc := p.pc+ polite := p.polite+ making := p.makingOffer+ p.mu.Unlock()++ // Perfect Negotiation:双方同时发 offer 时(glare),+ // 不礼让方忽略对方的 offer,礼让方回滚自己的 local description。+ //+ // 关键是回滚而非关闭重建——重建会换掉 ICE ufrag,+ // 让已经在途的 candidate 全部失配,连接就再也建不起来了。+ if pc != nil {+ collision := making || pc.SignalingState() != webrtc.SignalingStateStable+ if collision {+ if !polite {+ p.log.Debug("忽略对端 offer(本端不礼让)")+ return nil+ }+ p.log.Debug("礼让对端 offer,回滚本端的 local description")+ if err := pc.SetLocalDescription(webrtc.SessionDescription{+ Type: webrtc.SDPTypeRollback,+ }); err != nil {+ return fmt.Errorf("回滚本地描述: %w", err)+ }+ }+ } else {+ var err error+ if pc, err = p.newPeerConnection(); err != nil {+ return err+ }+ }++ p.mu.Lock()+ p.expectFingerprint = offer.GetDtlsFingerprint()+ p.mu.Unlock()++ if err := pc.SetRemoteDescription(webrtc.SessionDescription{+ Type: webrtc.SDPTypeOffer,+ SDP: offer.GetSdp(),+ }); err != nil {+ return fmt.Errorf("设置远端描述: %w", err)+ }+ p.flushPendingCandidates()++ answer, err := pc.CreateAnswer(nil)+ if err != nil {+ return fmt.Errorf("创建 answer: %w", err)+ }+ if err := pc.SetLocalDescription(answer); err != nil {+ return fmt.Errorf("设置本地描述: %w", err)+ }++ p.setState(StateConnecting)+ p.armConnectTimeout()++ return p.sendSignal(ctx, &pb.SignalMessage{+ Payload: &pb.SignalMessage_Answer{Answer: &pb.SdpAnswer{+ Sdp: answer.SDP,+ DtlsFingerprint: fingerprintFromSDP(answer.SDP),+ }},+ })+}++func (p *Peer) handleAnswer(answer *pb.SdpAnswer) error {+ p.mu.Lock()+ pc := p.pc+ p.expectFingerprint = answer.GetDtlsFingerprint()+ p.mu.Unlock()++ if pc == nil {+ return errors.New("收到 answer 但本端没有进行中的连接")+ }+ if pc.SignalingState() != webrtc.SignalingStateHaveLocalOffer {+ p.log.Debug("忽略时序不符的 answer", "state", pc.SignalingState())+ return nil+ }+ if err := pc.SetRemoteDescription(webrtc.SessionDescription{+ Type: webrtc.SDPTypeAnswer,+ SDP: answer.GetSdp(),+ }); err != nil {+ return fmt.Errorf("设置远端描述: %w", err)+ }+ p.flushPendingCandidates()+ return nil+}++func (p *Peer) handleCandidate(c *pb.IceCandidate) error {+ init := webrtc.ICECandidateInit{Candidate: c.GetCandidate()}+ if mid := c.GetSdpMid(); mid != "" {+ init.SDPMid = &mid+ }+ if idx := uint16(c.GetSdpMlineIndex()); true {+ init.SDPMLineIndex = &idx+ }++ p.mu.Lock()+ pc := p.pc+ // remote description 尚未设置时 AddICECandidate 会失败,先缓存+ if pc == nil || pc.RemoteDescription() == nil {+ p.pendingCandidates = append(p.pendingCandidates, init)+ p.mu.Unlock()+ return nil+ }+ p.mu.Unlock()++ return pc.AddICECandidate(init)+}++func (p *Peer) flushPendingCandidates() {+ p.mu.Lock()+ pc := p.pc+ pending := p.pendingCandidates+ p.pendingCandidates = nil+ p.mu.Unlock()++ if pc == nil {+ return+ }+ for _, c := range pending {+ if err := pc.AddICECandidate(c); err != nil {+ p.log.Debug("补加 candidate 失败", "err", err)+ }+ }+}++func (p *Peer) newPeerConnection() (*webrtc.PeerConnection, error) {+ pc, err := p.api.NewPeerConnection(p.config)+ if err != nil {+ return nil, fmt.Errorf("创建 PeerConnection: %w", err)+ }++ pc.OnICECandidate(func(c *webrtc.ICECandidate) {+ if c == nil {+ return // candidate 收集完毕+ }+ init := c.ToJSON()+ var mid string+ if init.SDPMid != nil {+ mid = *init.SDPMid+ }+ var idx uint32+ if init.SDPMLineIndex != nil {+ idx = uint32(*init.SDPMLineIndex)+ }+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ if err := p.sendSignal(ctx, &pb.SignalMessage{+ Payload: &pb.SignalMessage_Candidate{Candidate: &pb.IceCandidate{+ Candidate: init.Candidate,+ SdpMid: mid,+ SdpMlineIndex: idx,+ }},+ }); err != nil {+ p.log.Debug("发送 candidate 失败", "err", err)+ }+ })++ pc.OnDataChannel(func(dc *webrtc.DataChannel) {+ if dc.Label() == controlChannelLabel {+ p.bindControl(dc)+ return+ }+ // 数据流必须在回调里**立即**挂上接收器。+ //+ // pion 的 OnMessage 只是存一个 handler;在它被设置之前到达的消息+ // 会被直接丢弃,不做缓冲。上层拿到通道后还要查表、建管道,+ // 这中间的几毫秒足以让小文件的全部内容消失得无影无踪。+ // NewStream 先把消息接住,上层再决定怎么消费。+ stream := NewStream(dc)+ if p.onStream != nil {+ p.onStream(dc.Label(), stream)+ }+ })++ pc.OnConnectionStateChange(func(s webrtc.PeerConnectionState) {+ p.log.Debug("PeerConnection 状态", "state", s)+ switch s {+ case webrtc.PeerConnectionStateConnected:+ p.onConnected(pc)+ case webrtc.PeerConnectionStateFailed,+ webrtc.PeerConnectionStateClosed,+ webrtc.PeerConnectionStateDisconnected:+ p.setState(StateOffline)+ }+ })++ p.mu.Lock()+ p.pc = pc+ p.mu.Unlock()+ return pc, nil+}++// onConnected 在握手完成后校验 DTLS 指纹,并判定走的是直连还是中转。+func (p *Peer) onConnected(pc *webrtc.PeerConnection) {+ // ★ 安全校验:实际协商用的证书指纹必须与签名信令里声明的一致。+ // 不一致说明有人在中间替换了 SDP——立即断开。+ p.mu.Lock()+ expect := p.expectFingerprint+ p.mu.Unlock()++ if remote := pc.RemoteDescription(); remote != nil && expect != "" {+ actual := fingerprintFromSDP(remote.SDP)+ if !strings.EqualFold(actual, expect) {+ p.log.Error("DTLS 指纹不匹配,疑似中间人攻击,断开连接",+ "expect", expect, "actual", actual)+ p.Close()+ return+ }+ }++ kind := p.detectConnectionKind(pc)+ p.mu.Lock()+ p.pcConnected = true+ p.pendingKind = kind+ p.mu.Unlock()++ p.maybeReady()+}++// maybeReady 只有在传输握手完成**且**控制通道已打开时才对外报告"已连接"。+//+// 两者缺一不可:PeerConnection 进入 Connected 时 SCTP 可能仍在建流,+// 此时报告已连接会让调用方立刻发送并收到 ErrNotConnected。+func (p *Peer) maybeReady() {+ p.mu.Lock()+ ready := p.pcConnected && p.control != nil &&+ p.control.ReadyState() == webrtc.DataChannelStateOpen+ kind := p.pendingKind+ p.mu.Unlock()++ if ready {+ p.mu.Lock()+ if p.connectTimer != nil {+ p.connectTimer.Stop()+ p.connectTimer = nil+ }+ p.mu.Unlock()+ p.setState(kind)+ }+}++// detectConnectionKind 判断当前选中的 candidate 对是直连还是经 TURN 中转。+func (p *Peer) detectConnectionKind(pc *webrtc.PeerConnection) ConnState {+ stats := pc.GetStats()+ for _, s := range stats {+ pair, ok := s.(webrtc.ICECandidatePairStats)+ if !ok || pair.State != webrtc.StatsICECandidatePairStateSucceeded || !pair.Nominated {+ continue+ }+ for _, cs := range stats {+ c, ok := cs.(webrtc.ICECandidateStats)+ if !ok || c.ID != pair.LocalCandidateID {+ continue+ }+ if c.CandidateType == webrtc.ICECandidateTypeRelay {+ return StateRelay+ }+ return StateDirect+ }+ }+ // 拿不到明细时保守地报直连——功能不受影响,只是显示可能不准+ return StateDirect+}++func (p *Peer) bindControl(dc *webrtc.DataChannel) {+ p.mu.Lock()+ p.control = dc+ p.mu.Unlock()++ dc.OnOpen(func() {+ p.log.Debug("控制通道已打开")+ p.maybeReady()+ })+ // 应答方绑定控制通道时,传输层可能早已就绪,此时不会再触发 OnOpen+ if dc.ReadyState() == webrtc.DataChannelStateOpen {+ p.maybeReady()+ }+ dc.OnMessage(func(msg webrtc.DataChannelMessage) {+ var m pb.PeerMessage+ if err := proto.Unmarshal(msg.Data, &m); err != nil {+ p.log.Warn("控制消息解析失败", "err", err)+ return+ }+ if p.onMessage != nil {+ p.onMessage(&m)+ }+ })+}++var ErrNotConnected = errors.New("与对端的连接尚未建立")++// Send 经控制通道发送一条消息。+func (p *Peer) Send(m *pb.PeerMessage) error {+ p.mu.Lock()+ dc := p.control+ p.mu.Unlock()++ if dc == nil || dc.ReadyState() != webrtc.DataChannelStateOpen {+ return ErrNotConnected+ }+ data, err := proto.Marshal(m)+ if err != nil {+ return err+ }+ return dc.Send(data)+}++// OpenStream 为一次文件传输新开一条数据通道。+//+// 与控制通道分离,避免大文件把控制消息堵在队列后面。+func (p *Peer) OpenStream(label string) (*webrtc.DataChannel, error) {+ p.mu.Lock()+ pc := p.pc+ p.mu.Unlock()++ if pc == nil {+ return nil, ErrNotConnected+ }+ ordered := true+ return pc.CreateDataChannel(label, &webrtc.DataChannelInit{Ordered: &ordered})+}++func (p *Peer) Close() {+ p.mu.Lock()+ p.closeLocked()+ p.mu.Unlock()+ p.setState(StateOffline)+}++func (p *Peer) closeLocked() {+ if p.control != nil {+ p.control.Close()+ p.control = nil+ }+ if p.pc != nil {+ p.pc.Close()+ p.pc = nil+ }+ p.pendingCandidates = nil+ p.pcConnected = false+ p.makingOffer = false+ p.pendingKind = StateOffline+ p.dialing = false+ if p.connectTimer != nil {+ p.connectTimer.Stop()+ p.connectTimer = nil+ }+}++// fingerprintFromSDP 从 SDP 中提取 DTLS 证书指纹(a=fingerprint 行)。+func fingerprintFromSDP(sdp string) string {+ for _, line := range strings.Split(sdp, "\n") {+ line = strings.TrimSpace(line)+ if after, ok := strings.CutPrefix(line, "a=fingerprint:"); ok {+ return strings.TrimSpace(after)+ }+ }+ return ""+}diff --git a/client-core/internal/transport/p2p/peer_test.go b/client-core/internal/transport/p2p/peer_test.gonew file mode 100644index 0000000..e3d8cae--- /dev/null+++ b/client-core/internal/transport/p2p/peer_test.go@@ -0,0 +1,273 @@+package p2p_test++import (+ "context"+ "sync"+ "testing"+ "time"++ "github.com/baiyuze/copysync/client-core/internal/transport/p2p"+ pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"+)++// relay 把两个 Manager 直接对接起来,替代真实的信令服务器。+//+// 这样测试聚焦于 WebRTC 握手本身,不受网络与信令实现干扰;+// 信令链路已由 signaling 包的集成测试覆盖。+type relay struct {+ mu sync.Mutex+ targets map[string]*p2p.Manager+}++func newRelay() *relay {+ return &relay{targets: make(map[string]*p2p.Manager)}+}++func (r *relay) register(id string, m *p2p.Manager) {+ r.mu.Lock()+ defer r.mu.Unlock()+ r.targets[id] = m+}++// send 模拟信令服务器的转发:异步投递,贴近真实的网络时序。+func (r *relay) send(from string) func(context.Context, string, *pb.SignalMessage) error {+ return func(ctx context.Context, to string, msg *pb.SignalMessage) error {+ r.mu.Lock()+ target := r.targets[to]+ r.mu.Unlock()+ if target == nil {+ return nil+ }+ go func() {+ bg, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ _ = target.HandleSignal(bg, from, msg)+ }()+ return nil+ }+}++type harness struct {+ id string+ manager *p2p.Manager+ states chan p2p.ConnState+ messages chan *pb.PeerMessage+ streams chan *p2p.Stream+}++func newHarness(t *testing.T, id string, r *relay) *harness {+ t.Helper()++ h := &harness{+ id: id,+ states: make(chan p2p.ConnState, 16),+ messages: make(chan *pb.PeerMessage, 16),+ streams: make(chan *p2p.Stream, 8),+ }+ h.manager = p2p.NewManager(p2p.ManagerOptions{+ SelfID: id,+ SendSignal: r.send(id),+ OnState: func(_ string, s p2p.ConnState) {+ select {+ case h.states <- s:+ default:+ }+ },+ OnMessage: func(_ string, m *pb.PeerMessage) {+ select {+ case h.messages <- m:+ default:+ }+ },+ OnStream: func(_, _ string, st *p2p.Stream) {+ select {+ case h.streams <- st:+ default:+ }+ },+ })+ // 本地回环测试不需要 STUN/TURN:host candidate 足以直连+ h.manager.SetICEServers(nil)+ r.register(id, h.manager)+ t.Cleanup(h.manager.CloseAll)+ return h+}++// waitConnected 等到握手完成(直连或中转皆可)。+func waitConnected(t *testing.T, h *harness, peerID string) p2p.ConnState {+ t.Helper()+ deadline := time.After(30 * time.Second)+ for {+ select {+ case s := <-h.states:+ if s == p2p.StateDirect || s == p2p.StateRelay {+ return s+ }+ case <-deadline:+ t.Fatalf("%s 未能在 30 秒内与 %s 建立连接(当前 %v)",+ h.id, peerID, h.manager.State(peerID))+ return p2p.StateOffline+ }+ }+}++// TestPeersConnectAndExchangeMessages 是 M2 的核心验收:+// 两端能真正建立 WebRTC 连接,并在控制通道上互发消息。+func TestPeersConnectAndExchangeMessages(t *testing.T) {+ r := newRelay()+ // device_id 的字典序决定谁发起、谁礼让,这里刻意让 alice < bob+ alice := newHarness(t, "alice", r)+ bob := newHarness(t, "bob", r)++ ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)+ defer cancel()++ if err := alice.manager.Connect(ctx, "bob"); err != nil {+ t.Fatalf("发起连接: %v", err)+ }++ aliceState := waitConnected(t, alice, "bob")+ waitConnected(t, bob, "alice")+ t.Logf("连接方式:%v", aliceState)++ // 控制通道:alice → bob+ offer := &pb.PeerMessage{+ Payload: &pb.PeerMessage_Offer{Offer: &pb.ClipOffer{+ ClipId: "clip-1",+ Kind: pb.ClipKind_CLIP_KIND_TEXT,+ TotalSize: 11,+ // 文本内容直接内联,不需要二次传输+ TextContent: "hello peer",+ WillPush: true,+ }},+ }+ if err := alice.manager.Send("bob", offer); err != nil {+ t.Fatalf("发送控制消息: %v", err)+ }++ select {+ case got := <-bob.messages:+ if got.GetOffer().GetClipId() != "clip-1" {+ t.Errorf("clip_id = %q,期望 clip-1", got.GetOffer().GetClipId())+ }+ if got.GetOffer().GetTextContent() != "hello peer" {+ t.Errorf("内容 = %q,期望 hello peer", got.GetOffer().GetTextContent())+ }+ case <-time.After(10 * time.Second):+ t.Fatal("bob 未收到控制消息")+ }++ // 反方向也要通:拉取请求是由接收方发起的+ if err := bob.manager.Send("alice", &pb.PeerMessage{+ Payload: &pb.PeerMessage_Fetch{Fetch: &pb.PeerFetch{ClipId: "clip-1"}},+ }); err != nil {+ t.Fatalf("回发控制消息: %v", err)+ }+ select {+ case got := <-alice.messages:+ if got.GetFetch().GetClipId() != "clip-1" {+ t.Errorf("fetch clip_id = %q", got.GetFetch().GetClipId())+ }+ case <-time.After(10 * time.Second):+ t.Fatal("alice 未收到回发的控制消息")+ }+}++// TestSeparateStreamChannel 验证数据流与控制通道相互独立——+// 大文件传输不能把控制消息堵在队列后面。+func TestSeparateStreamChannel(t *testing.T) {+ r := newRelay()+ alice := newHarness(t, "alice", r)+ bob := newHarness(t, "bob", r)++ ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)+ defer cancel()++ if err := alice.manager.Connect(ctx, "bob"); err != nil {+ t.Fatalf("发起连接: %v", err)+ }+ waitConnected(t, alice, "bob")+ waitConnected(t, bob, "alice")++ dc, err := alice.manager.OpenStream("bob", "clip-1")+ if err != nil {+ t.Fatalf("开数据流: %v", err)+ }+ if dc.Label() != "clip-1" {+ t.Errorf("数据流 label = %q,期望 clip-1", dc.Label())+ }++ select {+ case got := <-bob.streams:+ if got.Label() != "clip-1" {+ t.Errorf("对端收到的 label = %q,期望 clip-1", got.Label())+ }+ // 数据流不该被当成控制消息处理+ select {+ case m := <-bob.messages:+ t.Errorf("数据流被误当作控制消息: %v", m)+ case <-time.After(300 * time.Millisecond):+ }+ case <-time.After(10 * time.Second):+ t.Fatal("bob 未收到新开的数据流")+ }+}++// TestSimultaneousConnectIsSafe 验证双方同时调用 Connect 不会互相干扰。+//+// 真实场景就是这样:两端几乎同时收到对方的上线通知,各自调用 Connect。+// Manager 内部按 device_id 字典序决定由谁发起,因此不会出现两个 offer 相撞。+func TestSimultaneousConnectIsSafe(t *testing.T) {+ r := newRelay()+ alice := newHarness(t, "alice", r)+ bob := newHarness(t, "bob", r)++ ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)+ defer cancel()++ var wg sync.WaitGroup+ wg.Add(2)+ go func() { defer wg.Done(); _ = alice.manager.Connect(ctx, "bob") }()+ go func() { defer wg.Done(); _ = bob.manager.Connect(ctx, "alice") }()+ wg.Wait()++ waitConnected(t, alice, "bob")+ waitConnected(t, bob, "alice")++ // 连接可用即证明没有因竞争而留下半开状态+ if err := alice.manager.Send("bob", &pb.PeerMessage{+ Payload: &pb.PeerMessage_Fetch{Fetch: &pb.PeerFetch{ClipId: "after-race"}},+ }); err != nil {+ t.Fatalf("并发 Connect 后仍无法发送: %v", err)+ }+ select {+ case got := <-bob.messages:+ if got.GetFetch().GetClipId() != "after-race" {+ t.Errorf("收到的 clip_id = %q", got.GetFetch().GetClipId())+ }+ case <-time.After(10 * time.Second):+ t.Fatal("并发 Connect 后消息未送达")+ }+}++// TestConnectFromAnswererSideAlone 验证只有应答方调用 Connect 时不会误发 offer。+// 它应当安静地等待,而不是自己也发起一轮协商。+func TestConnectFromAnswererSideAlone(t *testing.T) {+ r := newRelay()+ // "zoe" > "alice",所以 zoe 是应答方+ zoe := newHarness(t, "zoe", r)+ newHarness(t, "alice", r)++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ if err := zoe.manager.Connect(ctx, "alice"); err != nil {+ t.Fatalf("应答方调用 Connect 不该报错: %v", err)+ }+ // 没有对方发起,就应当一直停在 offline,而不是进入 connecting+ select {+ case s := <-zoe.states:+ t.Errorf("应答方不该主动改变状态,却变成了 %v", s)+ case <-time.After(1500 * time.Millisecond):+ }+}diff --git a/client-core/internal/transport/p2p/relay_test.go b/client-core/internal/transport/p2p/relay_test.gonew file mode 100644index 0000000..ae0e886--- /dev/null+++ b/client-core/internal/transport/p2p/relay_test.go@@ -0,0 +1,106 @@+package p2p_test++import (+ "context"+ "testing"+ "time"++ "github.com/baiyuze/copysync/client-core/internal/transport/p2p"+ pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"+ // 测试内已有一个名为 relay 的信令转发桩,这里给 TURN 包起别名以示区分+ turnrelay "github.com/baiyuze/copysync/server/relay"+)++// TestRelayFallback 验证「打洞失败就走服务器中转」这条兜底路径确实可用。+//+// 本地回环环境下 host candidate 总能直连,测不出真实的打洞失败,+// 因此用 ICETransportPolicy=relay 强制只走 TURN——若这条路能通,+// 真实网络中打洞失败时的降级就有保障。+func TestRelayFallback(t *testing.T) {+ turnSrv, err := turnrelay.New(turnrelay.Options{+ PublicIP: "127.0.0.1",+ Port: 34780, // 避开默认 3478,防止与本机已运行的服务冲突+ Secret: "test-secret",+ CredentialTTL: time.Hour,+ })+ if err != nil {+ t.Skipf("无法启动 TURN 服务(端口可能被占用): %v", err)+ }+ defer turnSrv.Close()++ r := newRelay()+ alice := newRelayHarness(t, "alice", r, turnSrv)+ bob := newRelayHarness(t, "bob", r, turnSrv)++ ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)+ defer cancel()++ if err := alice.manager.Connect(ctx, "bob"); err != nil {+ t.Fatalf("发起连接: %v", err)+ }++ state := waitConnected(t, alice, "bob")+ waitConnected(t, bob, "alice")++ // 强制 relay 策略下,连接方式必须被识别为中转——+ // 若这里报 direct,说明 detectConnectionKind 的判定是错的,+ // 用户界面上就会把中转误显示成直连。+ if state != p2p.StateRelay {+ t.Errorf("连接方式 = %v,强制 relay 时应为 relay", state)+ }++ // 中转链路同样要能正常收发+ if err := alice.manager.Send("bob", &pb.PeerMessage{+ Payload: &pb.PeerMessage_Fetch{Fetch: &pb.PeerFetch{ClipId: "via-relay"}},+ }); err != nil {+ t.Fatalf("经中转发送失败: %v", err)+ }+ select {+ case got := <-bob.messages:+ if got.GetFetch().GetClipId() != "via-relay" {+ t.Errorf("收到的 clip_id = %q", got.GetFetch().GetClipId())+ }+ case <-time.After(10 * time.Second):+ t.Fatal("经中转的消息未送达")+ }+}++func newRelayHarness(t *testing.T, id string, r *relay, turnSrv *turnrelay.Server) *harness {+ t.Helper()++ h := &harness{+ id: id,+ states: make(chan p2p.ConnState, 16),+ messages: make(chan *pb.PeerMessage, 16),+ streams: nil,+ }+ h.manager = p2p.NewManager(p2p.ManagerOptions{+ SelfID: id,+ SendSignal: r.send(id),+ ForceRelay: true,+ OnState: func(_ string, s p2p.ConnState) {+ select {+ case h.states <- s:+ default:+ }+ },+ OnMessage: func(_ string, m *pb.PeerMessage) {+ select {+ case h.messages <- m:+ default:+ }+ },+ })++ // 每台设备各自签发凭证,与真实流程一致+ cred := turnSrv.Issue(id)+ h.manager.SetICEServers([]*pb.IceServer{{+ Urls: cred.URLs,+ Username: cred.Username,+ Credential: cred.Password,+ }})++ r.register(id, h.manager)+ t.Cleanup(h.manager.CloseAll)+ return h+}diff --git a/client-core/internal/transport/p2p/stream.go b/client-core/internal/transport/p2p/stream.gonew file mode 100644index 0000000..9be5381--- /dev/null+++ b/client-core/internal/transport/p2p/stream.go@@ -0,0 +1,68 @@+package p2p++import (+ "sync"++ "github.com/pion/webrtc/v4"+)++// 队列深度约 256 个分片(≈15 MiB)。足以吸收消费侧(解压+落盘)的抖动,+// 又不至于让内存失控;满了之后回调自然阻塞,背压经 SCTP 传导回发送方。+const streamQueueDepth = 256++// Stream 包住一条用于传输内容的 DataChannel,解决两个致命问题。+//+// 其一是时序:pion 的 DataChannel.OnMessage 只是记下一个 handler,在它被+// 设置之前到达的消息会被直接丢弃、不做缓冲。而 OnDataChannel 回调返回后,+// 上层还要查表、建管道才能挂上接收逻辑——这中间的几毫秒足以让一个小文件的+// 全部内容凭空消失(实测:发送方 202 字节,接收方 0 字节)。+//+// 其二是顺序:任何"先缓冲、后回放"的写法都要小心,一旦回放期间有新消息+// 直抵 handler,就会排到旧消息前面,把 zstd 流彻底搞乱。+//+// 这里用一个队列同时解决两者:OnMessage 在 OnDataChannel 回调中当场挂上,+// 只负责入队;消费者从队列按序取用。入队顺序即到达顺序,不存在插队。+type Stream struct {+ dc *webrtc.DataChannel+ queue chan []byte++ closeOnce sync.Once+}++// NewStream 立即开始接收消息。必须在 OnDataChannel 回调中同步调用。+func NewStream(dc *webrtc.DataChannel) *Stream {+ s := &Stream{+ dc: dc,+ queue: make(chan []byte, streamQueueDepth),+ }++ dc.OnMessage(func(msg webrtc.DataChannelMessage) {+ // 必须复制:pion 复用底层缓冲,留着原切片会被后续消息覆盖+ chunk := make([]byte, len(msg.Data))+ copy(chunk, msg.Data)+ s.queue <- chunk+ })++ dc.OnClose(func() { s.finish() })++ return s+}++// Chunks 返回按到达顺序排列的数据分片。+// 通道在对端关闭数据流后关闭,消费者据此得知传输结束。+func (s *Stream) Chunks() <-chan []byte { return s.queue }++func (s *Stream) Label() string { return s.dc.Label() }++func (s *Stream) ReadyState() webrtc.DataChannelState { return s.dc.ReadyState() }++// Close 关闭底层通道。队列会在 OnClose 中随之关闭。+func (s *Stream) Close() error {+ err := s.dc.Close()+ s.finish()+ return err+}++func (s *Stream) finish() {+ s.closeOnce.Do(func() { close(s.queue) })+}diff --git a/client-core/internal/transport/p2p/stream_test.go b/client-core/internal/transport/p2p/stream_test.gonew file mode 100644index 0000000..a6abaed--- /dev/null+++ b/client-core/internal/transport/p2p/stream_test.go@@ -0,0 +1,168 @@+package p2p_test++import (+ "bytes"+ "context"+ "crypto/rand"+ "crypto/sha256"+ "testing"+ "time"++ "github.com/baiyuze/copysync/client-core/internal/transport/p2p"+)++// TestStreamDeliversPayloadIntact 是文件传输的核心保障。+//+// 它一次性锁住三个曾经真实发生过的故障:+// 1. 时序:OnMessage 挂得比首个分片晚 → 接收方收到 0 字节;+// 2. 顺序:缓冲回放期间新消息插队 → zstd 流损坏,报 "compressed size too big";+// 3. 背压:依赖边沿触发的 OnBufferedAmountLow → 丢失唤醒,20 MB 传到 786 KB 卡死。+//+// 随机负载 + 校验和比对能同时覆盖"有没有丢"和"顺序对不对"。+func TestStreamDeliversPayloadIntact(t *testing.T) {+ const payloadSize = 4 << 20 // 4 MiB,足以跨越多个分片与缓冲水位++ r := newRelay()+ alice := newHarness(t, "alice", r)+ bob := newHarness(t, "bob", r)++ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)+ defer cancel()++ if err := alice.manager.Connect(ctx, "bob"); err != nil {+ t.Fatalf("建立连接: %v", err)+ }+ waitConnected(t, alice, "bob")+ waitConnected(t, bob, "alice")++ payload := make([]byte, payloadSize)+ if _, err := rand.Read(payload); err != nil {+ t.Fatal(err)+ }+ want := sha256.Sum256(payload)++ dc, err := alice.manager.OpenStream("bob", "payload")+ if err != nil {+ t.Fatalf("开数据流: %v", err)+ }++ opened := make(chan struct{})+ dc.OnOpen(func() { close(opened) })+ select {+ case <-opened:+ case <-time.After(20 * time.Second):+ t.Fatal("数据流未能打开")+ }++ // 接收方:从队列按序取出并拼回完整内容+ var stream *p2p.Stream+ select {+ case stream = <-bob.streams:+ case <-time.After(20 * time.Second):+ t.Fatal("接收方未收到数据流")+ }++ received := make(chan []byte, 1)+ go func() {+ var buf bytes.Buffer+ for chunk := range stream.Chunks() {+ buf.Write(chunk)+ }+ received <- buf.Bytes()+ }()++ // 发送方:按 60 KiB 分片发出,中途不做任何节流之外的处理+ const chunk = 60 * 1024+ for off := 0; off < len(payload); off += chunk {+ end := min(off+chunk, len(payload))+ // 简单节流,避免测试里把发送缓冲撑爆(生产路径由 chunkWriter 负责背压)+ for dc.BufferedAmount() > 1<<20 {+ time.Sleep(2 * time.Millisecond)+ }+ if err := dc.Send(payload[off:end]); err != nil {+ t.Fatalf("发送分片 @%d: %v", off, err)+ }+ }+ for dc.BufferedAmount() > 0 {+ time.Sleep(5 * time.Millisecond)+ }+ dc.Close()++ select {+ case got := <-received:+ if len(got) != payloadSize {+ t.Fatalf("收到 %d 字节,期望 %d(有分片丢失)", len(got), payloadSize)+ }+ if gotSum := sha256.Sum256(got); gotSum != want {+ t.Error("校验和不一致:分片顺序被打乱了")+ }+ case <-time.After(60 * time.Second):+ t.Fatal("接收超时")+ }+}++// TestStreamBuffersEarlyMessages 验证在消费者挂上来之前到达的分片不会丢失。+//+// pion 的 OnMessage 不缓冲:handler 设置前到达的消息会被直接丢弃。+// Stream 必须在 OnDataChannel 回调里当场接住它们。+func TestStreamBuffersEarlyMessages(t *testing.T) {+ r := newRelay()+ alice := newHarness(t, "alice", r)+ bob := newHarness(t, "bob", r)++ ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)+ defer cancel()++ if err := alice.manager.Connect(ctx, "bob"); err != nil {+ t.Fatalf("建立连接: %v", err)+ }+ waitConnected(t, alice, "bob")+ waitConnected(t, bob, "alice")++ dc, err := alice.manager.OpenStream("bob", "early")+ if err != nil {+ t.Fatalf("开数据流: %v", err)+ }+ opened := make(chan struct{})+ dc.OnOpen(func() { close(opened) })+ select {+ case <-opened:+ case <-time.After(20 * time.Second):+ t.Fatal("数据流未能打开")+ }++ // 立刻发送,不给接收侧任何准备时间+ for i := range 5 {+ if err := dc.Send([]byte{byte('A' + i)}); err != nil {+ t.Fatalf("发送: %v", err)+ }+ }++ var stream *p2p.Stream+ select {+ case stream = <-bob.streams:+ case <-time.After(20 * time.Second):+ t.Fatal("接收方未收到数据流")+ }++ // 故意拖一会儿再消费,模拟上层查表建管道的耗时+ time.Sleep(300 * time.Millisecond)+ dc.Close()++ var got []byte+ timeout := time.After(20 * time.Second)+ for {+ select {+ case chunk, ok := <-stream.Chunks():+ if !ok {+ if string(got) != "ABCDE" {+ t.Errorf("收到 %q,期望 ABCDE(早到的分片被丢弃或乱序)", got)+ }+ return+ }+ got = append(got, chunk...)+ case <-timeout:+ t.Fatalf("接收超时,已收到 %q", got)+ }+ }+}diff --git a/client-core/internal/transport/signaling/client.go b/client-core/internal/transport/signaling/client.gonew file mode 100644index 0000000..4f75404--- /dev/null+++ b/client-core/internal/transport/signaling/client.go@@ -0,0 +1,425 @@+// Package signaling 是信令服务器的客户端:维持长连接、交换 SDP/candidate、+// 走配对流程。+//+// 信任模型:服务器只是个转发通道。所有经它转发的消息都由发送方用设备私钥签名,+// 接收方用配对时存下的对端公钥验签——服务器改不了内容,也冒充不了任何一方。+// 验签失败的消息直接丢弃。+package signaling++import (+ "context"+ "crypto/ed25519"+ cryptorand "crypto/rand"+ "errors"+ "fmt"+ "log/slog"+ "math/rand"+ "sync"+ "time"++ "github.com/coder/websocket"+ "google.golang.org/protobuf/proto"++ "github.com/baiyuze/copysync/client-core/internal/identity"+ pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"+)++const (+ maxMessageBytes = 256 << 10+ dialTimeout = 15 * time.Second+ writeTimeout = 10 * time.Second+ // 防重放:拒绝时间戳偏离过大的消息+ maxClockSkew = 5 * time.Minute+)++// Handlers 是调用方关心的事件。均在客户端的读循环中同步调用,+// 实现里不要做耗时操作。+type Handlers struct {+ OnConnected func()+ OnDisconnected func(err error)+ OnPresence func(deviceID string, online bool)+ OnSignal func(from string, msg *pb.SignalMessage)+ OnPairingCreated func(code string, expiresAt time.Time)+ OnPairingRedeemed func(peer *pb.PairingRedeemed)+ OnPairingResult func(peer *pb.PairingRedeemResponse)+ OnServerError func(code, message string)+ // OnIceConfig 在认证后收到,携带短期 TURN 凭证+ OnIceConfig func(servers []*pb.IceServer)+}++type Client struct {+ identity *identity.Identity+ log *slog.Logger+ handlers Handlers++ // PublicKeyOf 返回已配对设备的公钥,用于验签。返回 nil 表示未配对,+ // 此时来自该设备的消息一律丢弃。+ publicKeyOf func(deviceID string) ed25519.PublicKey+ // DeviceInfo 提供每次握手时上报的设备名与已配对列表+ deviceInfo func() (name, platform string, pairedIDs []string)++ mu sync.Mutex+ conn *websocket.Conn+ url string+ connected bool++ // 防重放:记录近期见过的 nonce+ seenNonces map[string]time.Time+}++type Options struct {+ Identity *identity.Identity+ URL string+ Logger *slog.Logger+ Handlers Handlers+ PublicKeyOf func(deviceID string) ed25519.PublicKey+ DeviceInfo func() (name, platform string, pairedIDs []string)+}++func New(opts Options) *Client {+ log := opts.Logger+ if log == nil {+ log = slog.Default()+ }+ return &Client{+ identity: opts.Identity,+ url: opts.URL,+ log: log,+ handlers: opts.Handlers,+ publicKeyOf: opts.PublicKeyOf,+ deviceInfo: opts.DeviceInfo,+ seenNonces: make(map[string]time.Time),+ }+}++// SetURL 更换信令服务器地址,下次重连生效。+// 当前连接会被断开,以便立即切换。+func (c *Client) SetURL(url string) {+ c.mu.Lock()+ changed := c.url != url+ c.url = url+ conn := c.conn+ c.mu.Unlock()++ if changed && conn != nil {+ conn.Close(websocket.StatusNormalClosure, "切换服务器")+ }+}++func (c *Client) URL() string {+ c.mu.Lock()+ defer c.mu.Unlock()+ return c.url+}++func (c *Client) Connected() bool {+ c.mu.Lock()+ defer c.mu.Unlock()+ return c.connected+}++// Run 维持与信令服务器的连接,断线后自动重连,直到 ctx 取消。+func (c *Client) Run(ctx context.Context) {+ backoff := time.Second+ const maxBackoff = 30 * time.Second++ for ctx.Err() == nil {+ err := c.session(ctx)+ if ctx.Err() != nil {+ return+ }+ if err != nil {+ c.log.Debug("信令连接中断", "err", err, "重试间隔", backoff)+ }++ // 加抖动,避免服务器重启后所有设备同时涌入+ jitter := time.Duration(rand.Int63n(int64(backoff / 2)))+ select {+ case <-ctx.Done():+ return+ case <-time.After(backoff + jitter):+ }+ if backoff < maxBackoff {+ backoff *= 2+ }+ }+}++// session 完成一次完整的连接生命周期。+func (c *Client) session(ctx context.Context) error {+ url := c.URL()+ if url == "" {+ return errors.New("未配置信令服务器地址")+ }++ dialCtx, cancel := context.WithTimeout(ctx, dialTimeout)+ conn, _, err := websocket.Dial(dialCtx, url, nil)+ cancel()+ if err != nil {+ return fmt.Errorf("连接 %s: %w", url, err)+ }+ conn.SetReadLimit(maxMessageBytes)+ defer conn.Close(websocket.StatusNormalClosure, "")++ if err := c.handshake(ctx, conn); err != nil {+ return fmt.Errorf("握手: %w", err)+ }++ c.mu.Lock()+ c.conn = conn+ c.connected = true+ c.mu.Unlock()++ if c.handlers.OnConnected != nil {+ c.handlers.OnConnected()+ }++ defer func() {+ c.mu.Lock()+ c.conn = nil+ c.connected = false+ c.mu.Unlock()+ if c.handlers.OnDisconnected != nil {+ c.handlers.OnDisconnected(err)+ }+ }()++ return c.readLoop(ctx, conn)+}++// handshake 应答服务器的 challenge,证明本机持有该公钥对应的私钥。+func (c *Client) handshake(ctx context.Context, conn *websocket.Conn) error {+ ctx, cancel := context.WithTimeout(ctx, dialTimeout)+ defer cancel()++ var env pb.ServerEnvelope+ if err := readProto(ctx, conn, &env); err != nil {+ return fmt.Errorf("读取 ServerHello: %w", err)+ }+ hello := env.GetHello()+ if hello == nil {+ return errors.New("服务器首条消息不是 ServerHello")+ }++ name, platform, paired := c.deviceInfo()+ return writeProto(ctx, conn, &pb.ClientEnvelope{+ Payload: &pb.ClientEnvelope_Hello{Hello: &pb.ClientHello{+ DeviceId: c.identity.DeviceID,+ DeviceName: name,+ Platform: platform,+ PublicKey: c.identity.PublicKey,+ Signature: c.identity.Sign(hello.GetChallenge()),+ PairedDeviceIds: paired,+ }},+ })+}++func (c *Client) readLoop(ctx context.Context, conn *websocket.Conn) error {+ for {+ var env pb.ServerEnvelope+ if err := readProto(ctx, conn, &env); err != nil {+ return err+ }++ switch p := env.GetPayload().(type) {+ case *pb.ServerEnvelope_Presence:+ if c.handlers.OnPresence != nil {+ c.handlers.OnPresence(p.Presence.GetDeviceId(), p.Presence.GetOnline())+ }++ case *pb.ServerEnvelope_Forwarded:+ c.handleForwarded(p.Forwarded)++ case *pb.ServerEnvelope_PairingCreated:+ if c.handlers.OnPairingCreated != nil {+ c.handlers.OnPairingCreated(+ p.PairingCreated.GetCode(),+ time.Unix(p.PairingCreated.GetExpiresAtUnix(), 0))+ }++ case *pb.ServerEnvelope_PairingRedeemed:+ if c.handlers.OnPairingRedeemed != nil {+ c.handlers.OnPairingRedeemed(p.PairingRedeemed)+ }++ case *pb.ServerEnvelope_PairingRedeemedResult:+ if c.handlers.OnPairingResult != nil {+ c.handlers.OnPairingResult(p.PairingRedeemedResult)+ }++ case *pb.ServerEnvelope_IceConfig:+ if c.handlers.OnIceConfig != nil {+ c.handlers.OnIceConfig(p.IceConfig.GetIceServers())+ }++ case *pb.ServerEnvelope_Error:+ c.log.Warn("服务器返回错误",+ "code", p.Error.GetCode(), "msg", p.Error.GetMessage())+ if c.handlers.OnServerError != nil {+ c.handlers.OnServerError(p.Error.GetCode(), p.Error.GetMessage())+ }+ }+ }+}++// handleForwarded 验签后再交给上层。+//+// 这是整个信任模型的落点:服务器能转发任意字节,但伪造不出对端的签名。+// 任何验签不过的消息都当作攻击丢弃,不向上层暴露。+func (c *Client) handleForwarded(signed *pb.Signed) {+ from := signed.GetFromDeviceId()+ pub := c.publicKeyOf(from)+ if pub == nil {+ c.log.Warn("丢弃未配对设备的消息", "from", from)+ return+ }+ if !ed25519.Verify(pub, signed.GetPayload(), signed.GetSignature()) {+ c.log.Warn("丢弃签名无效的消息", "from", from)+ return+ }++ var msg pb.SignalMessage+ if err := proto.Unmarshal(signed.GetPayload(), &msg); err != nil {+ c.log.Warn("丢弃无法解析的消息", "from", from, "err", err)+ return+ }++ // 防重放:时间戳超出容忍范围,或 nonce 重复出现过+ ts := time.Unix(msg.GetTimestampUnix(), 0)+ if skew := time.Since(ts); skew > maxClockSkew || skew < -maxClockSkew {+ c.log.Warn("丢弃时间戳异常的消息", "from", from, "偏差", skew)+ return+ }+ if c.seenNonce(msg.GetNonce()) {+ c.log.Warn("丢弃重放的消息", "from", from)+ return+ }++ if c.handlers.OnSignal != nil {+ c.handlers.OnSignal(from, &msg)+ }+}++// seenNonce 记录并判断 nonce 是否重复,同时清理过期条目。+func (c *Client) seenNonce(nonce []byte) bool {+ if len(nonce) == 0 {+ return false+ }+ key := string(nonce)++ c.mu.Lock()+ defer c.mu.Unlock()++ now := time.Now()+ if _, dup := c.seenNonces[key]; dup {+ return true+ }+ // 超出时钟容忍窗口的 nonce 不可能再被接受,可以安全丢弃+ for k, t := range c.seenNonces {+ if now.Sub(t) > maxClockSkew*2 {+ delete(c.seenNonces, k)+ }+ }+ c.seenNonces[key] = now+ return false+}++// ─────────────────────────── 发送 ───────────────────────────++var ErrNotConnected = errors.New("信令未连接")++func (c *Client) send(ctx context.Context, env *pb.ClientEnvelope) error {+ c.mu.Lock()+ conn := c.conn+ c.mu.Unlock()++ if conn == nil {+ return ErrNotConnected+ }+ ctx, cancel := context.WithTimeout(ctx, writeTimeout)+ defer cancel()+ return writeProto(ctx, conn, env)+}++// Signal 向对端发送一条已签名的信令。+func (c *Client) Signal(ctx context.Context, to string, msg *pb.SignalMessage) error {+ msg.ToDeviceId = to+ msg.TimestampUnix = time.Now().Unix()+ if msg.Nonce == nil {+ nonce := make([]byte, 16)+ if _, err := cryptorand.Read(nonce); err != nil {+ return err+ }+ msg.Nonce = nonce+ }++ payload, err := proto.Marshal(msg)+ if err != nil {+ return err+ }+ return c.send(ctx, &pb.ClientEnvelope{+ Payload: &pb.ClientEnvelope_Forward{Forward: &pb.Signed{+ Payload: payload,+ Signature: c.identity.Sign(payload),+ FromDeviceId: c.identity.DeviceID,+ }},+ })+}++func (c *Client) CreatePairingCode(ctx context.Context) error {+ name, _, _ := c.deviceInfo()+ return c.send(ctx, &pb.ClientEnvelope{+ Payload: &pb.ClientEnvelope_PairingCreate{PairingCreate: &pb.PairingCreateRequest{+ DeviceName: name,+ PublicKey: c.identity.PublicKey,+ }},+ })+}++func (c *Client) RedeemPairingCode(ctx context.Context, code string) error {+ name, _, _ := c.deviceInfo()+ return c.send(ctx, &pb.ClientEnvelope{+ Payload: &pb.ClientEnvelope_PairingRedeem{PairingRedeem: &pb.PairingRedeemRequest{+ Code: code,+ DeviceId: c.identity.DeviceID,+ DeviceName: name,+ PublicKey: c.identity.PublicKey,+ }},+ })+}++// RefreshPaired 在配对关系变化后重新上报关注列表,+// 这样服务器才会推送新配对设备的在线状态。+func (c *Client) RefreshPaired(ctx context.Context) error {+ name, platform, paired := c.deviceInfo()+ return c.send(ctx, &pb.ClientEnvelope{+ Payload: &pb.ClientEnvelope_Hello{Hello: &pb.ClientHello{+ DeviceId: c.identity.DeviceID,+ DeviceName: name,+ Platform: platform,+ PublicKey: c.identity.PublicKey,+ PairedDeviceIds: paired,+ }},+ })+}++// ─────────────────────── proto over websocket ───────────────────────++func readProto(ctx context.Context, conn *websocket.Conn, m proto.Message) error {+ typ, data, err := conn.Read(ctx)+ if err != nil {+ return err+ }+ if typ != websocket.MessageBinary {+ return fmt.Errorf("期望二进制消息,收到 %v", typ)+ }+ return proto.Unmarshal(data, m)+}++func writeProto(ctx context.Context, conn *websocket.Conn, m proto.Message) error {+ data, err := proto.Marshal(m)+ if err != nil {+ return err+ }+ return conn.Write(ctx, websocket.MessageBinary, data)+}diff --git a/client-core/internal/transport/signaling/client_test.go b/client-core/internal/transport/signaling/client_test.gonew file mode 100644index 0000000..1e2cc61--- /dev/null+++ b/client-core/internal/transport/signaling/client_test.go@@ -0,0 +1,338 @@+package signaling_test++import (+ "context"+ "crypto/ed25519"+ "net/http"+ "net/http/httptest"+ "path/filepath"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/baiyuze/copysync/client-core/internal/identity"+ "github.com/baiyuze/copysync/client-core/internal/transport/signaling"+ pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"+ "github.com/baiyuze/copysync/server/signal"+)++// peer 把一个设备身份、它的信令客户端、以及它观察到的事件打包在一起,+// 方便在测试里像操作真实设备那样操作它。+type peer struct {+ name string+ identity *identity.Identity+ client *signaling.Client++ mu sync.Mutex+ // 已配对对端的公钥。真实实现中来自 SQLite,这里用内存模拟。+ known map[string]ed25519.PublicKey++ presence chan presenceEvent+ signals chan signalEvent+ codes chan string+ paired chan pairedEvent+}++type presenceEvent struct {+ deviceID string+ online bool+}++type signalEvent struct {+ from string+ msg *pb.SignalMessage+}++type pairedEvent struct {+ deviceID string+ name string+ publicKey ed25519.PublicKey+}++func newPeer(t *testing.T, name, url string) *peer {+ t.Helper()++ id, err := identity.LoadOrCreate(filepath.Join(t.TempDir(), "identity.json"))+ if err != nil {+ t.Fatalf("创建身份: %v", err)+ }++ p := &peer{+ name: name,+ identity: id,+ known: make(map[string]ed25519.PublicKey),+ presence: make(chan presenceEvent, 16),+ signals: make(chan signalEvent, 16),+ codes: make(chan string, 4),+ paired: make(chan pairedEvent, 4),+ }++ p.client = signaling.New(signaling.Options{+ Identity: id,+ URL: url,+ PublicKeyOf: func(deviceID string) ed25519.PublicKey {+ p.mu.Lock()+ defer p.mu.Unlock()+ return p.known[deviceID]+ },+ DeviceInfo: func() (string, string, []string) {+ p.mu.Lock()+ defer p.mu.Unlock()+ ids := make([]string, 0, len(p.known))+ for k := range p.known {+ ids = append(ids, k)+ }+ return name, "test", ids+ },+ Handlers: signaling.Handlers{+ OnPresence: func(deviceID string, online bool) {+ p.presence <- presenceEvent{deviceID, online}+ },+ OnSignal: func(from string, msg *pb.SignalMessage) {+ p.signals <- signalEvent{from, msg}+ },+ OnPairingCreated: func(code string, _ time.Time) {+ p.codes <- code+ },+ // 发起方:有人兑换了我的配对码+ OnPairingRedeemed: func(ev *pb.PairingRedeemed) {+ p.remember(ev.GetPeerDeviceId(), ev.GetPeerPublicKey())+ p.paired <- pairedEvent{+ ev.GetPeerDeviceId(), ev.GetPeerDeviceName(), ev.GetPeerPublicKey(),+ }+ },+ // 兑换方:我兑换成功,拿到发起方信息+ OnPairingResult: func(ev *pb.PairingRedeemResponse) {+ p.remember(ev.GetPeerDeviceId(), ev.GetPeerPublicKey())+ p.paired <- pairedEvent{+ ev.GetPeerDeviceId(), ev.GetPeerDeviceName(), ev.GetPeerPublicKey(),+ }+ },+ },+ })+ return p+}++func (p *peer) remember(deviceID string, pub []byte) {+ p.mu.Lock()+ defer p.mu.Unlock()+ p.known[deviceID] = ed25519.PublicKey(pub)+}++func (p *peer) forget(deviceID string) {+ p.mu.Lock()+ defer p.mu.Unlock()+ delete(p.known, deviceID)+}++// startServer 起一个真实的信令服务器(httptest + websocket)。+func startServer(t *testing.T) string {+ t.Helper()++ mux := http.NewServeMux()+ mux.Handle("/signal", signal.NewServer(signal.Options{}))+ srv := httptest.NewServer(mux)+ t.Cleanup(srv.Close)++ return "ws" + strings.TrimPrefix(srv.URL, "http") + "/signal"+}++func waitConnected(t *testing.T, peers ...*peer) {+ t.Helper()+ deadline := time.Now().Add(5 * time.Second)+ for _, p := range peers {+ for !p.client.Connected() {+ if time.Now().After(deadline) {+ t.Fatalf("%s 未能连上信令服务器", p.name)+ }+ time.Sleep(10 * time.Millisecond)+ }+ }+}++func recvPaired(t *testing.T, p *peer) pairedEvent {+ t.Helper()+ select {+ case ev := <-p.paired:+ return ev+ case <-time.After(5 * time.Second):+ t.Fatalf("%s 未收到配对结果", p.name)+ return pairedEvent{}+ }+}++// TestPairingExchangesKeysBothWays 验证配对的核心语义:+// 双方都要拿到对方公钥,否则只有单向互信,签名验证会失败。+func TestPairingExchangesKeysBothWays(t *testing.T) {+ url := startServer(t)+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()++ alice := newPeer(t, "Alice", url)+ bob := newPeer(t, "Bob", url)+ go alice.client.Run(ctx)+ go bob.client.Run(ctx)+ waitConnected(t, alice, bob)++ if err := alice.client.CreatePairingCode(ctx); err != nil {+ t.Fatalf("生成配对码: %v", err)+ }+ var code string+ select {+ case code = <-alice.codes:+ case <-time.After(5 * time.Second):+ t.Fatal("未收到配对码")+ }+ if len(code) != 6 {+ t.Errorf("配对码长度应为 6,实际 %d(%q)", len(code), code)+ }++ if err := bob.client.RedeemPairingCode(ctx, code); err != nil {+ t.Fatalf("兑换配对码: %v", err)+ }++ // 兑换方拿到发起方信息+ got := recvPaired(t, bob)+ if got.deviceID != alice.identity.DeviceID {+ t.Errorf("Bob 拿到的对端 ID = %q,期望 %q", got.deviceID, alice.identity.DeviceID)+ }+ if got.name != "Alice" {+ t.Errorf("Bob 拿到的对端名 = %q,期望 Alice", got.name)+ }++ // 发起方也要拿到兑换方信息——否则 Alice 无法验证 Bob 的签名+ got = recvPaired(t, alice)+ if got.deviceID != bob.identity.DeviceID {+ t.Errorf("Alice 拿到的对端 ID = %q,期望 %q", got.deviceID, bob.identity.DeviceID)+ }++ // 双方存下的公钥必须与对方真实公钥一致+ alice.mu.Lock()+ bobKeyAtAlice := alice.known[bob.identity.DeviceID]+ alice.mu.Unlock()+ if !bobKeyAtAlice.Equal(bob.identity.PublicKey) {+ t.Error("Alice 存下的 Bob 公钥与真实公钥不一致")+ }+}++// TestSignalForwardingVerifiesSignature 验证信任模型的落点:+// 已配对设备间的消息能送达,未配对设备的消息必须被丢弃。+func TestSignalForwardingVerifiesSignature(t *testing.T) {+ url := startServer(t)+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()++ alice := newPeer(t, "Alice", url)+ bob := newPeer(t, "Bob", url)++ // 直接互相植入公钥,跳过配对流程+ alice.remember(bob.identity.DeviceID, bob.identity.PublicKey)+ bob.remember(alice.identity.DeviceID, alice.identity.PublicKey)++ go alice.client.Run(ctx)+ go bob.client.Run(ctx)+ waitConnected(t, alice, bob)++ send := &pb.SignalMessage{+ Payload: &pb.SignalMessage_Offer{Offer: &pb.SdpOffer{+ Sdp: "v=0 test-offer",+ DtlsFingerprint: "sha-256 AA:BB:CC",+ }},+ }+ if err := alice.client.Signal(ctx, bob.identity.DeviceID, send); err != nil {+ t.Fatalf("发送信令: %v", err)+ }++ select {+ case ev := <-bob.signals:+ if ev.from != alice.identity.DeviceID {+ t.Errorf("发送方 = %q,期望 %q", ev.from, alice.identity.DeviceID)+ }+ if got := ev.msg.GetOffer().GetSdp(); got != "v=0 test-offer" {+ t.Errorf("SDP = %q,期望 %q", got, "v=0 test-offer")+ }+ // DTLS 指纹经签名传递,是防中间人的锚点,必须完整到达+ if got := ev.msg.GetOffer().GetDtlsFingerprint(); got != "sha-256 AA:BB:CC" {+ t.Errorf("DTLS 指纹 = %q,期望 %q", got, "sha-256 AA:BB:CC")+ }+ case <-time.After(5 * time.Second):+ t.Fatal("Bob 未收到 Alice 的信令")+ }++ // Bob 忘掉 Alice 后,来自 Alice 的消息应被丢弃(模拟未配对设备的消息)+ bob.forget(alice.identity.DeviceID)+ if err := alice.client.Signal(ctx, bob.identity.DeviceID, &pb.SignalMessage{+ Payload: &pb.SignalMessage_Offer{Offer: &pb.SdpOffer{Sdp: "should-be-dropped"}},+ }); err != nil {+ t.Fatalf("发送信令: %v", err)+ }+ select {+ case ev := <-bob.signals:+ t.Errorf("未配对设备的消息本应被丢弃,却收到了:%v", ev.msg)+ case <-time.After(800 * time.Millisecond):+ // 符合预期+ }+}++// TestPresenceNotifiesWatchers 验证在线状态推送:+// 设备只会收到它关心(已配对)的对端的状态变化。+func TestPresenceNotifiesWatchers(t *testing.T) {+ url := startServer(t)+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()++ alice := newPeer(t, "Alice", url)+ bob := newPeer(t, "Bob", url)+ alice.remember(bob.identity.DeviceID, bob.identity.PublicKey)+ bob.remember(alice.identity.DeviceID, alice.identity.PublicKey)++ go alice.client.Run(ctx)+ waitConnected(t, alice)++ // Bob 后上线,Alice 应当收到上线通知+ bobCtx, bobCancel := context.WithCancel(ctx)+ go bob.client.Run(bobCtx)+ waitConnected(t, bob)++ select {+ case ev := <-alice.presence:+ if ev.deviceID != bob.identity.DeviceID || !ev.online {+ t.Errorf("期望 Bob 上线通知,实际 %+v", ev)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("Alice 未收到 Bob 的上线通知")+ }++ // Bob 断开,Alice 应当收到下线通知+ bobCancel()+ select {+ case ev := <-alice.presence:+ if ev.deviceID != bob.identity.DeviceID || ev.online {+ t.Errorf("期望 Bob 下线通知,实际 %+v", ev)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("Alice 未收到 Bob 的下线通知")+ }+}++// TestRedeemInvalidCode 验证错误的配对码不会建立任何关系。+func TestRedeemInvalidCode(t *testing.T) {+ url := startServer(t)+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()++ bob := newPeer(t, "Bob", url)+ go bob.client.Run(ctx)+ waitConnected(t, bob)++ if err := bob.client.RedeemPairingCode(ctx, "ZZZZZZ"); err != nil {+ t.Fatalf("发送兑换请求: %v", err)+ }+ select {+ case ev := <-bob.paired:+ t.Errorf("无效配对码本不该成功,却返回了 %+v", ev)+ case <-time.After(1 * time.Second):+ // 符合预期:服务器回错误,不产生配对+ }+}diff --git a/docs/.nojekyll b/docs/.nojekyllnew file mode 100644index 0000000..e69de29diff --git a/docs/404.html b/docs/404.htmlnew file mode 100644index 0000000..572fdf9--- /dev/null+++ b/docs/404.html@@ -0,0 +1,23 @@+<!doctype html>+<html lang="zh-CN">+<head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <meta name="robots" content="noindex">+ <title>页面不存在 / Page not found — CopySync</title>+ <link rel="icon" href="/copysync/assets/favicon.svg" type="image/svg+xml">+ <link rel="stylesheet" href="/copysync/assets/site.css">+</head>+<body>+ <main class="closing">+ <div class="wrap">+ <h2>这个页面不存在</h2>+ <p class="intro" style="margin-inline:auto">Page not found.</p>+ <div class="cta">+ <a class="button" href="/copysync/">回到首页</a>+ <a href="/copysync/en/">English home</a>+ </div>+ </div>+ </main>+</body>+</html>diff --git a/docs/assets/apple-touch-icon.png b/docs/assets/apple-touch-icon.pngnew file mode 100644index 0000000..10bdca8Binary files /dev/null and b/docs/assets/apple-touch-icon.png differdiff --git a/docs/assets/favicon-32.png b/docs/assets/favicon-32.pngnew file mode 100644index 0000000..b98909bBinary files /dev/null and b/docs/assets/favicon-32.png differdiff --git a/docs/assets/favicon.svg b/docs/assets/favicon.svgnew file mode 100644index 0000000..47e1bac--- /dev/null+++ b/docs/assets/favicon.svg@@ -0,0 +1,16 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="100 100 824 824">+ <!-- 浏览器标签页里尺寸很小:裁掉图标网格的留白与投影,只保留主体 -->+ <rect x="100" y="100" width="824" height="824" rx="184" fill="#F2F2F1"/>+ <rect x="230" y="220" width="340" height="420" rx="44" fill="#F5F5F4" stroke="#2C2C2E" stroke-width="32"/>+ <g fill="#2C2C2E">+ <rect x="290" y="310" width="200" height="36" rx="18"/>+ <rect x="290" y="390" width="150" height="36" rx="18"/>+ <rect x="290" y="470" width="104" height="36" rx="18"/>+ </g>+ <rect x="454" y="384" width="340" height="420" rx="44" fill="#0A66D8"/>+ <g fill="#FFFFFF">+ <rect x="514" y="474" width="200" height="36" rx="18"/>+ <rect x="514" y="554" width="150" height="36" rx="18"/>+ <rect x="514" y="634" width="104" height="36" rx="18"/>+ </g>+</svg>diff --git a/docs/assets/icon.png b/docs/assets/icon.pngnew file mode 100644index 0000000..1b544a7Binary files /dev/null and b/docs/assets/icon.png differdiff --git a/docs/assets/icon.svg b/docs/assets/icon.svgnew file mode 100644index 0000000..67f31c8--- /dev/null+++ b/docs/assets/icon.svg@@ -0,0 +1,28 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" role="img" aria-label="CopySync">+ <!-- 几何与 tools/icon/render.swift 一一对应,改动时两边同步 -->+ <defs>+ <linearGradient id="body" x1="0" y1="100" x2="0" y2="924" gradientUnits="userSpaceOnUse">+ <stop offset="0" stop-color="#FBFBFA"/>+ <stop offset="1" stop-color="#E8E8E6"/>+ </linearGradient>+ <filter id="bodyShadow" x="-20%" y="-20%" width="140%" height="140%">+ <feDropShadow dx="0" dy="12" stdDeviation="14" flood-color="#000" flood-opacity="0.28"/>+ </filter>+ <filter id="sheetShadow" x="-20%" y="-20%" width="140%" height="140%">+ <feDropShadow dx="0" dy="10" stdDeviation="12" flood-color="#000" flood-opacity="0.22"/>+ </filter>+ </defs>+ <rect x="100" y="100" width="824" height="824" rx="184" fill="url(#body)" filter="url(#bodyShadow)"/>+ <rect x="230" y="220" width="340" height="420" rx="44" fill="#F5F5F4" stroke="#2C2C2E" stroke-width="28"/>+ <g fill="#2C2C2E" fill-opacity="0.85">+ <rect x="290" y="310" width="200" height="30" rx="15"/>+ <rect x="290" y="390" width="150" height="30" rx="15"/>+ <rect x="290" y="470" width="104" height="30" rx="15"/>+ </g>+ <rect x="454" y="384" width="340" height="420" rx="44" fill="#0A66D8" filter="url(#sheetShadow)"/>+ <g fill="#FFFFFF" fill-opacity="0.95">+ <rect x="514" y="474" width="200" height="30" rx="15"/>+ <rect x="514" y="554" width="150" height="30" rx="15"/>+ <rect x="514" y="634" width="104" height="30" rx="15"/>+ </g>+</svg>diff --git a/docs/assets/og-en.png b/docs/assets/og-en.pngnew file mode 100644index 0000000..945c6fdBinary files /dev/null and b/docs/assets/og-en.png differdiff --git a/docs/assets/og.png b/docs/assets/og.pngnew file mode 100644index 0000000..f3091eeBinary files /dev/null and b/docs/assets/og.png differdiff --git a/docs/assets/screenshots/card-verify-dark.png b/docs/assets/screenshots/card-verify-dark.pngnew file mode 100644index 0000000..e727360Binary files /dev/null and b/docs/assets/screenshots/card-verify-dark.png differdiff --git a/docs/assets/screenshots/card-verify.png b/docs/assets/screenshots/card-verify.pngnew file mode 100644index 0000000..20e72adBinary files /dev/null and b/docs/assets/screenshots/card-verify.png differdiff --git a/docs/assets/screenshots/devices.png b/docs/assets/screenshots/devices.pngnew file mode 100644index 0000000..7546648Binary files /dev/null and b/docs/assets/screenshots/devices.png differdiff --git a/docs/assets/screenshots/history-dark.png b/docs/assets/screenshots/history-dark.pngnew file mode 100644index 0000000..3455b62Binary files /dev/null and b/docs/assets/screenshots/history-dark.png differdiff --git a/docs/assets/screenshots/history.png b/docs/assets/screenshots/history.pngnew file mode 100644index 0000000..047da6dBinary files /dev/null and b/docs/assets/screenshots/history.png differdiff --git a/docs/assets/screenshots/pairing.png b/docs/assets/screenshots/pairing.pngnew file mode 100644index 0000000..8e33169Binary files /dev/null and b/docs/assets/screenshots/pairing.png differdiff --git a/docs/assets/screenshots/settings.png b/docs/assets/screenshots/settings.pngnew file mode 100644index 0000000..475ab92Binary files /dev/null and b/docs/assets/screenshots/settings.png differdiff --git a/docs/assets/screenshots/verify.png b/docs/assets/screenshots/verify.pngnew file mode 100644index 0000000..c8291aaBinary files /dev/null and b/docs/assets/screenshots/verify.png differdiff --git a/docs/assets/screenshots/welcome.png b/docs/assets/screenshots/welcome.pngnew file mode 100644index 0000000..e8e7a30Binary files /dev/null and b/docs/assets/screenshots/welcome.png differdiff --git a/docs/assets/site.css b/docs/assets/site.cssnew file mode 100644index 0000000..848afa0--- /dev/null+++ b/docs/assets/site.css@@ -0,0 +1,982 @@+/* CopySync 项目主页+ *+ * 与 App 同一套颜色:大面积白与石墨灰,强调色只给按钮和链接。+ * 不加载网页字体:Mac 上就是 SF Pro 与苹方,和 App 本身一致,国内访问也快。+ */++:root {+ --page: #ffffff;+ --band: #f5f5f4;+ --ink: #1d1d1f;+ --dim: #6e6e73;+ --faint: #a1a1a6;+ --rule: #e4e4e2;+ --blue: #0a66d8;+ --blue-ink: #0857b8;+ --green: #248a3d;+ --code-bg: #f5f5f4;+ --shadow: 0 1px 2px rgba(0, 0, 0, 0.06), 0 8px 24px rgba(0, 0, 0, 0.06);++ --sans: -apple-system, BlinkMacSystemFont, "SF Pro Text", "PingFang SC", "Hiragino Sans GB",+ "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;+ --mono: ui-monospace, "SF Mono", Menlo, Consolas, monospace;++ --measure: 40rem;+ --wide: 68rem;+ color-scheme: light dark;+}++@media (prefers-color-scheme: dark) {+ :root {+ --page: #161617;+ --band: #1d1d1f;+ --ink: #f5f5f7;+ --dim: #98989d;+ --faint: #636366;+ --rule: #333335;+ --blue: #3b8beb;+ --blue-ink: #5aa0f0;+ --green: #32d74b;+ --code-bg: #232325;+ --shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);+ }+}++*,+*::before,+*::after {+ box-sizing: border-box;+}++html {+ -webkit-text-size-adjust: 100%;+ scroll-behavior: smooth;+}++body {+ margin: 0;+ background: var(--page);+ color: var(--ink);+ font: 17px/1.6 var(--sans);+ -webkit-font-smoothing: antialiased;+ text-rendering: optimizeLegibility;+}++img {+ max-width: 100%;+ height: auto;+ display: block;+}++a {+ color: var(--blue);+ text-decoration: none;+}++a:hover {+ color: var(--blue-ink);+ text-decoration: underline;+ text-underline-offset: 3px;+}++:focus-visible {+ outline: 2px solid var(--blue);+ outline-offset: 3px;+ border-radius: 4px;+}++code,+kbd,+pre {+ font-family: var(--mono);+ font-size: 0.88em;+}++p code,+li code,+td code {+ background: var(--code-bg);+ padding: 0.1em 0.35em;+ border-radius: 4px;+}++.wrap {+ width: min(100% - 3rem, var(--wide));+ margin-inline: auto;+}++.skip {+ position: absolute;+ left: -999px;+}++.skip:focus {+ left: 1rem;+ top: 1rem;+ background: var(--page);+ padding: 0.5rem 0.75rem;+ z-index: 10;+}++/* ─────────────────────────── 页头 ─────────────────────────── */++.site-header {+ position: sticky;+ top: 0;+ z-index: 5;+ background: color-mix(in srgb, var(--page) 86%, transparent);+ backdrop-filter: saturate(180%) blur(16px);+ -webkit-backdrop-filter: saturate(180%) blur(16px);+ border-bottom: 1px solid var(--rule);+}++.site-header .wrap {+ display: flex;+ align-items: center;+ gap: 1.5rem;+ height: 3.25rem;+}++.brand {+ display: flex;+ align-items: center;+ gap: 0.55rem;+ color: var(--ink);+ font-weight: 600;+ font-size: 1rem;+}++.brand:hover {+ color: var(--ink);+ text-decoration: none;+}++.brand img {+ width: 26px;+ height: 26px;+}++.site-nav {+ display: flex;+ gap: 1.5rem;+ margin-left: auto;+ font-size: 0.875rem;+}++.site-nav a {+ color: var(--dim);+}++.site-nav a:hover {+ color: var(--ink);+ text-decoration: none;+}++@media (max-width: 720px) {+ .site-nav .optional {+ display: none;+ }+}++/* ─────────────────────────── 首屏 ─────────────────────────── */++.hero {+ padding: 5.5rem 0 4rem;+}++.hero h1 {+ margin: 0;+ font-size: clamp(2.4rem, 1.2rem + 4.4vw, 4.25rem);+ line-height: 1.08;+ font-weight: 700;+ letter-spacing: -0.03em;+ max-width: 14em;+}++.hero .lede {+ margin: 1.5rem 0 0;+ max-width: 34rem;+ font-size: 1.25rem;+ line-height: 1.55;+ color: var(--dim);+}++.cta {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 0.75rem 1.5rem;+ margin-top: 2.25rem;+}++.button {+ display: inline-flex;+ align-items: center;+ gap: 0.5rem;+ padding: 0.75rem 1.35rem;+ border-radius: 10px;+ background: var(--blue);+ color: #fff;+ font-weight: 600;+ font-size: 1rem;+}++.button:hover {+ background: var(--blue-ink);+ color: #fff;+ text-decoration: none;+}++.button svg {+ width: 18px;+ height: 18px;+}++.cta .note {+ font-size: 0.875rem;+ color: var(--dim);+}++/* 首屏演示:两台 Mac,一次复制、一次粘贴 */++.demo {+ display: grid;+ grid-template-columns: 1fr minmax(7rem, 0.6fr) 1fr;+ align-items: center;+ max-width: 58rem;+ margin-top: 4.5rem;+}++.mac {+ margin: 0;+}++.mac-screen {+ position: relative;+ aspect-ratio: 16 / 10;+ border-radius: 14px 14px 4px 4px;+ border: 1px solid var(--rule);+ background: var(--band);+ padding: 15% 9% 0;+ overflow: hidden;+}++/* 屏幕顶部的菜单栏,让这块区域一眼读作 Mac 的桌面 */+.mac-screen::before {+ content: "";+ position: absolute;+ inset: 0 0 auto;+ height: 7%;+ background: color-mix(in srgb, var(--ink) 6%, var(--band));+ border-bottom: 1px solid var(--rule);+}++.mac-base {+ height: 9px;+ margin: 0 -5%;+ border-radius: 0 0 10px 10px;+ background: linear-gradient(var(--rule), var(--band));+ border: 1px solid var(--rule);+ border-top: none;+}++.mac figcaption {+ margin-top: 0.85rem;+ text-align: center;+ font-size: 0.875rem;+ color: var(--dim);+}++.file {+ display: flex;+ align-items: center;+ gap: 0.6rem;+ width: fit-content;+ max-width: 100%;+ padding: 0.55rem 0.8rem;+ border-radius: 8px;+ background: var(--page);+ border: 1px solid var(--rule);+ box-shadow: var(--shadow);+ font-size: 0.9rem;+ white-space: nowrap;+}++.file svg {+ flex: none;+ width: 20px;+ height: 20px;+ color: var(--dim);+}++.file small {+ color: var(--dim);+ font-size: 0.78rem;+}++.keys {+ position: absolute;+ right: 9%;+ bottom: 12%;+ display: flex;+ gap: 0.3rem;+}++.keys kbd {+ display: grid;+ place-items: center;+ min-width: 2.1rem;+ height: 2.1rem;+ padding: 0 0.4rem;+ border-radius: 7px;+ background: var(--page);+ border: 1px solid var(--rule);+ box-shadow: 0 2px 0 var(--rule);+ font: 600 0.95rem var(--sans);+ color: var(--ink);+}++.link {+ position: relative;+ height: 2px;+ margin: 0 0.75rem;+ margin-bottom: 2.4rem; /* 与两侧屏幕的中线对齐,抵消下方设备名的高度 */+ background-image: linear-gradient(90deg, var(--faint) 50%, transparent 50%);+ background-size: 8px 2px;+}++.link .packet {+ position: absolute;+ top: 50%;+ left: 0;+ width: 12px;+ height: 12px;+ margin-top: -6px;+ border-radius: 50%;+ background: var(--blue);+ opacity: 0;+}++.link-label {+ position: absolute;+ top: 0.9rem;+ left: 50%;+ transform: translateX(-50%);+ white-space: nowrap;+ font-size: 0.78rem;+ color: var(--dim);+}++.mac-b .file {+ opacity: 0;+}++/* 动画:一次性的完整演示。结束后停在终态 */+.demo.play .mac-a .file {+ animation: select 0.3s ease-out 0.5s both;+}++.demo.play .mac-a kbd {+ animation: press 0.35s ease-in-out 0.7s both;+}++.demo.play .packet {+ animation: travel 1s cubic-bezier(0.55, 0, 0.45, 1) 1.15s both;+}++.demo.play .mac-b kbd {+ animation: press 0.35s ease-in-out 2.25s both;+}++.demo.play .mac-b .file {+ animation: arrive 0.45s cubic-bezier(0.2, 0.9, 0.3, 1.2) 2.45s both;+}++@keyframes select {+ to {+ background: color-mix(in srgb, var(--blue) 14%, var(--page));+ border-color: color-mix(in srgb, var(--blue) 45%, var(--rule));+ }+}++@keyframes press {+ 40% {+ transform: translateY(2px);+ box-shadow: 0 0 0 var(--rule);+ background: color-mix(in srgb, var(--blue) 12%, var(--page));+ }+}++@keyframes travel {+ 0% {+ left: 0;+ opacity: 0;+ }+ 12%,+ 88% {+ opacity: 1;+ }+ 100% {+ left: calc(100% - 12px);+ opacity: 0;+ }+}++@keyframes arrive {+ from {+ opacity: 0;+ transform: translateY(8px) scale(0.96);+ }+ to {+ opacity: 1;+ transform: none;+ }+}++/* 不想看动画的用户直接看到终态 */+@media (prefers-reduced-motion: reduce) {+ .demo .mac-b .file {+ opacity: 1;+ }+ .demo.play * {+ animation: none !important;+ }+ html {+ scroll-behavior: auto;+ }+}++.replay {+ display: block;+ margin: 1.5rem auto 0;+ padding: 0.3rem 0.6rem;+ border: none;+ background: none;+ color: var(--dim);+ font: inherit;+ font-size: 0.8rem;+ cursor: pointer;+}++.replay:hover {+ color: var(--ink);+}++@media (max-width: 720px) {+ .demo {+ grid-template-columns: 1fr;+ gap: 0;+ }+ .link {+ width: 2px;+ height: 4.5rem;+ margin: 1rem auto;+ background-image: linear-gradient(180deg, var(--faint) 50%, transparent 50%);+ background-size: 2px 8px;+ }+ .link .packet {+ left: 50%;+ margin: 0 0 0 -6px;+ }+ .link-label {+ top: 50%;+ left: 1rem;+ transform: translateY(-50%);+ }+ @keyframes travel {+ 0% {+ top: 0;+ opacity: 0;+ }+ 12%,+ 88% {+ opacity: 1;+ }+ 100% {+ top: calc(100% - 12px);+ opacity: 0;+ }+ }+}++/* ─────────────────────────── 通用段落 ─────────────────────────── */++.section {+ padding: 6rem 0;+}++.section-band {+ background: var(--band);+}++.section h2 {+ margin: 0;+ font-size: clamp(1.75rem, 1.2rem + 1.6vw, 2.4rem);+ line-height: 1.2;+ font-weight: 700;+ letter-spacing: -0.02em;+ max-width: 20em;+}++.section h3 {+ margin: 0 0 0.5rem;+ font-size: 1.15rem;+ line-height: 1.35;+ font-weight: 600;+}++.section .intro {+ margin: 1rem 0 0;+ max-width: var(--measure);+ color: var(--dim);+ font-size: 1.1rem;+}++.prose {+ max-width: var(--measure);+}++.prose p,+.prose ul {+ margin: 1rem 0 0;+}++.prose ul {+ padding-left: 1.2rem;+}++.prose li + li {+ margin-top: 0.5rem;+}++.two-col {+ display: grid;+ grid-template-columns: minmax(0, 1fr) minmax(0, 1.15fr);+ gap: 4rem;+ align-items: start;+ margin-top: 3rem;+}++@media (max-width: 880px) {+ .two-col {+ grid-template-columns: 1fr;+ gap: 2.5rem;+ }+}++/* ─────────────────────────── 截图 ─────────────────────────── */++.shot {+ margin: 3rem 0 0;+}++/* 截图自带 macOS 窗口的阴影与留白,向两侧略微出血,视觉上与正文对齐 */+.shot img {+ width: calc(100% + 4.5%);+ max-width: none;+ margin-left: -2.25%;+}++.shot figcaption {+ margin-top: 0.5rem;+ text-align: center;+ font-size: 0.875rem;+ color: var(--dim);+}++/* ─────────────────────────── 表格 ─────────────────────────── */++.table-scroll {+ overflow-x: auto;+ margin-top: 2.5rem;+}++table {+ width: 100%;+ border-collapse: collapse;+ font-size: 0.95rem;+}++th,+td {+ padding: 0.8rem 1rem 0.8rem 0;+ text-align: left;+ vertical-align: top;+ border-bottom: 1px solid var(--rule);+}++thead th {+ font-weight: 600;+ font-size: 0.85rem;+ color: var(--dim);+}++tbody th {+ font-weight: 500;+}++.compare td,+.compare thead th:not(:first-child) {+ text-align: center;+ padding-right: 0.5rem;+ padding-left: 0.5rem;+}++.compare .ours {+ color: var(--ink);+ font-weight: 600;+}++.yes {+ color: var(--green);+ font-weight: 600;+}++.no {+ color: var(--faint);+}++.partial {+ color: var(--dim);+ font-size: 0.85rem;+}++/* ─────────────────────────── 工作原理 ─────────────────────────── */++.diagram {+ margin: 3rem 0 0;+}++.diagram svg {+ width: 100%;+ height: auto;+ display: block;+}++.diagram text {+ font-family: var(--sans);+}++.steps {+ list-style: none;+ counter-reset: step;+ margin: 3rem 0 0;+ padding: 0;+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: 2.5rem;+}++.steps li {+ counter-increment: step;+}++.steps li::before {+ content: counter(step);+ display: grid;+ place-items: center;+ width: 1.9rem;+ height: 1.9rem;+ margin-bottom: 0.9rem;+ border-radius: 50%;+ border: 1.5px solid var(--ink);+ font-weight: 600;+ font-size: 0.9rem;+}++.steps p {+ margin: 0;+ color: var(--dim);+}++@media (max-width: 880px) {+ .steps {+ grid-template-columns: 1fr;+ gap: 2rem;+ }+}++/* ─────────────────────────── 兜底 ─────────────────────────── */++.fallbacks {+ margin: 2.5rem 0 0;+ display: grid;+ grid-template-columns: minmax(0, 0.8fr) minmax(0, 1.2fr);+ border-top: 1px solid var(--rule);+}++.fallbacks dt,+.fallbacks dd {+ margin: 0;+ padding: 1rem 0;+ border-bottom: 1px solid var(--rule);+}++.fallbacks dt {+ padding-right: 2rem;+ font-weight: 600;+}++.fallbacks dd {+ color: var(--dim);+}++@media (max-width: 720px) {+ .fallbacks {+ grid-template-columns: 1fr;+ }+ .fallbacks dt {+ border-bottom: none;+ padding-bottom: 0.25rem;+ }+ .fallbacks dd {+ padding-top: 0;+ }+}++/* ─────────────────────────── 安装 ─────────────────────────── */++.install-steps {+ margin: 1.5rem 0 0;+ padding-left: 1.3rem;+}++.install-steps li {+ padding-left: 0.3rem;+}++.install-steps li + li {+ margin-top: 0.9rem;+}++.install-steps li::marker {+ font-weight: 600;+}++.install-steps .aside {+ display: block;+ margin-top: 0.3rem;+ color: var(--dim);+ font-size: 0.92rem;+}++.code {+ position: relative;+ margin: 1.25rem 0 0;+ border-radius: 10px;+ background: var(--code-bg);+ border: 1px solid var(--rule);+}++.code pre {+ margin: 0;+ padding: 1rem 4.5rem 1rem 1.1rem; /* 右侧给「复制」按钮留位置 */+ overflow-x: auto;+ line-height: 1.7;+}++.code .copy {+ position: absolute;+ top: 0.5rem;+ right: 0.5rem;+ padding: 0.25rem 0.55rem;+ border-radius: 6px;+ border: 1px solid var(--rule);+ background: var(--page);+ color: var(--dim);+ font: 500 0.75rem var(--sans);+ cursor: pointer;+}++.code .copy:hover {+ color: var(--ink);+}++.ports {+ margin-top: 1.5rem;+}++.ports td:first-child {+ font-family: var(--mono);+ font-size: 0.88rem;+ white-space: nowrap;+}++/* ─────────────────────────── 规格 ─────────────────────────── */++.specs th {+ width: 11rem;+ font-weight: 600;+ padding-right: 2rem;+}++.specs td {+ color: var(--dim);+}++/* ─────────────────────────── 常见问题 ─────────────────────────── */++.faq {+ margin-top: 2.5rem;+ max-width: 46rem;+ border-top: 1px solid var(--rule);+}++.faq details {+ border-bottom: 1px solid var(--rule);+}++.faq summary {+ display: flex;+ justify-content: space-between;+ gap: 1rem;+ padding: 1.1rem 0;+ cursor: pointer;+ list-style: none;+ font-weight: 600;+}++.faq summary::-webkit-details-marker {+ display: none;+}++.faq summary::after {+ content: "+";+ flex: none;+ color: var(--dim);+ font-weight: 400;+ font-size: 1.25rem;+ line-height: 1.2;+}++.faq details[open] summary::after {+ content: "−";+}++.faq .answer {+ padding: 0 0 1.25rem;+ color: var(--dim);+ max-width: var(--measure);+}++.faq .answer p {+ margin: 0;+}++.faq .answer p + p {+ margin-top: 0.75rem;+}++/* ─────────────────────────── 页脚 ─────────────────────────── */++.closing {+ padding: 6rem 0;+ text-align: center;+}++.closing h2 {+ margin: 0 auto;+}++.closing .cta {+ justify-content: center;+}++.site-footer {+ border-top: 1px solid var(--rule);+ padding: 2rem 0 3rem;+ font-size: 0.875rem;+ color: var(--dim);+}++.site-footer .wrap {+ display: flex;+ flex-wrap: wrap;+ gap: 1rem 2rem;+ justify-content: space-between;+}++.site-footer nav {+ display: flex;+ flex-wrap: wrap;+ gap: 1.5rem;+}++.site-footer a {+ color: var(--dim);+}++.site-footer a:hover {+ color: var(--ink);+}++/* ─────────────────────────── 零散 ─────────────────────────── */++.section .subhead {+ margin-top: 4.5rem;+}++.card-shot {+ margin: -1.5rem 0 0;+}++.card-shot img {+ width: 100%;+ max-width: 34rem;+ margin-inline: auto;+}++.aside-p {+ margin: 0.75rem 0 0;+ color: var(--dim);+ font-size: 0.95rem;+}++/* 架构图:颜色取自页面变量,深色模式自动跟随 */+.d-box {+ fill: var(--page);+ stroke: var(--rule);+ stroke-width: 1.5;+}++.d-title {+ font-size: 17px;+ font-weight: 600;+ fill: var(--ink);+}++.d-sub,+.d-note,+.d-legend text {+ font-size: 13px;+ fill: var(--dim);+}++.d-label {+ font-size: 14px;+ font-weight: 600;+ fill: var(--blue);+}++.d-direct,+.d-sig,+.d-relay {+ fill: none;+ stroke-linecap: round;+}++.d-direct {+ stroke: var(--blue);+ stroke-width: 3;+}++.d-sig {+ stroke: var(--faint);+ stroke-width: 1.5;+}++.d-relay {+ stroke: var(--faint);+ stroke-width: 1.5;+ stroke-dasharray: 6 6;+}diff --git a/docs/assets/site.js b/docs/assets/site.jsnew file mode 100644index 0000000..e5790f1--- /dev/null+++ b/docs/assets/site.js@@ -0,0 +1,44 @@+// 首屏演示与代码块的「复制」按钮。没有它们页面也完整可读。+(function () {+ var demo = document.querySelector(".demo");+ var replay = document.querySelector(".replay");++ function play() {+ if (!demo) return;+ demo.classList.remove("play");+ void demo.offsetWidth; // 强制重排,让动画从头再来+ demo.classList.add("play");+ }++ if (demo) {+ // 滚动到可见时才开始,避免用户还没看到就播完了+ if ("IntersectionObserver" in window) {+ var seen = new IntersectionObserver(function (entries) {+ if (entries[0].isIntersecting) {+ play();+ seen.disconnect();+ }+ }, { threshold: 0.5 });+ seen.observe(demo);+ } else {+ play();+ }+ }+ if (replay) replay.addEventListener("click", play);++ document.querySelectorAll(".code").forEach(function (block) {+ var button = block.querySelector(".copy");+ var pre = block.querySelector("pre");+ if (!button || !pre || !navigator.clipboard) {+ if (button) button.hidden = true;+ return;+ }+ var label = button.textContent;+ button.addEventListener("click", function () {+ navigator.clipboard.writeText(pre.innerText.trim()).then(function () {+ button.textContent = button.dataset.done || "Copied";+ setTimeout(function () { button.textContent = label; }, 1600);+ });+ });+ });+})();diff --git a/docs/en/index.html b/docs/en/index.htmlnew file mode 100644index 0000000..427e4a5--- /dev/null+++ b/docs/en/index.html@@ -0,0 +1,459 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <title>CopySync: sync the clipboard and files between Macs, across Apple IDs — open source</title>+ <meta name="description" content="CopySync lets you copy on one Mac and paste on another: text, images, files and folders. Works across Apple IDs and networks. Peer-to-peer, end-to-end encrypted, with a server you host yourself that can't read your data. Free and MIT licensed.">+ <link rel="canonical" href="https://baiyuze.github.io/copysync/en/">+ <link rel="alternate" hreflang="zh-CN" href="https://baiyuze.github.io/copysync/">+ <link rel="alternate" hreflang="en" href="https://baiyuze.github.io/copysync/en/">+ <link rel="alternate" hreflang="x-default" href="https://baiyuze.github.io/copysync/">+ <meta name="theme-color" content="#ffffff" media="(prefers-color-scheme: light)">+ <meta name="theme-color" content="#161617" media="(prefers-color-scheme: dark)">++ <meta property="og:type" content="website">+ <meta property="og:site_name" content="CopySync">+ <meta property="og:title" content="CopySync: copy on one Mac, paste on the other">+ <meta property="og:description" content="Text, images, files and folders. Across Apple IDs and networks, peer-to-peer and end-to-end encrypted, with a server you host. Free and open source.">+ <meta property="og:url" content="https://baiyuze.github.io/copysync/en/">+ <meta property="og:image" content="https://baiyuze.github.io/copysync/assets/og-en.png">+ <meta property="og:image:width" content="1200">+ <meta property="og:image:height" content="630">+ <meta property="og:locale" content="en_US">+ <meta property="og:locale:alternate" content="zh_CN">+ <meta name="twitter:card" content="summary_large_image">++ <link rel="icon" href="../assets/favicon.svg" type="image/svg+xml">+ <link rel="icon" href="../assets/favicon-32.png" sizes="32x32" type="image/png">+ <link rel="apple-touch-icon" href="../assets/apple-touch-icon.png">+ <link rel="stylesheet" href="../assets/site.css">++ <script type="application/ld+json">+ {+ "@context": "https://schema.org",+ "@graph": [+ {+ "@type": "SoftwareApplication",+ "@id": "https://baiyuze.github.io/copysync/#app",+ "name": "CopySync",+ "description": "Open-source tool that syncs the clipboard and files between Macs. Copy text, images, files or folders on one Mac and paste them on another. Devices connect directly over WebRTC with DTLS encryption, falling back to a TURN relay on a server the user hosts.",+ "applicationCategory": "UtilitiesApplication",+ "operatingSystem": "macOS 13 or later (Intel and Apple silicon)",+ "softwareVersion": "1.0.0",+ "datePublished": "2026-10-08",+ "inLanguage": "en",+ "license": "https://opensource.org/licenses/MIT",+ "isAccessibleForFree": true,+ "offers": { "@type": "Offer", "price": "0", "priceCurrency": "USD" },+ "downloadUrl": "https://github.com/baiyuze/copysync/releases/latest",+ "codeRepository": "https://github.com/baiyuze/copysync",+ "image": "https://baiyuze.github.io/copysync/assets/icon.png",+ "screenshot": "https://baiyuze.github.io/copysync/assets/screenshots/history.png",+ "fileSize": "45MB",+ "featureList": [+ "Syncs plain text, rich text, images, files and folders",+ "Works across Apple IDs and across networks",+ "Direct WebRTC connection with automatic TURN relay fallback",+ "End-to-end DTLS encryption and fingerprint verification when pairing",+ "Items under 50 MB are pushed on copy; larger files are pulled on demand",+ "History of the last 3 days"+ ],+ "author": { "@type": "Person", "name": "baiyuze", "url": "https://github.com/baiyuze" }+ },+ {+ "@type": "FAQPage",+ "mainEntity": [+ {+ "@type": "Question",+ "name": "How is CopySync different from Universal Clipboard?",+ "acceptedAnswer": { "@type": "Answer", "text": "Universal Clipboard needs both devices on the same Apple ID, with Bluetooth and Wi-Fi on, close to each other. CopySync only needs both Macs to reach your server, so different Apple IDs and different networks work. It also keeps a history and lets you pull large files on demand." }+ },+ {+ "@type": "Question",+ "name": "Can the CopySync server see what I copy?",+ "acceptedAnswer": { "@type": "Answer", "text": "No. With a direct connection the data never touches the server. When relaying, the server only forwards DTLS-encrypted UDP packets. It keeps no accounts and stores no clipboard content." }+ },+ {+ "@type": "Question",+ "name": "Do I need my own server to use CopySync?",+ "acceptedAnswer": { "@type": "Answer", "text": "Yes. There is no public server. On a LAN, run the server on one of your Macs; across networks you need a machine with a public IP, and the smallest cloud VM is enough." }+ },+ {+ "@type": "Question",+ "name": "Does CopySync support Windows or iPhone?",+ "acceptedAnswer": { "@type": "Answer", "text": "Windows is planned. iPhone and iPad are not supported: iOS does not allow apps to watch the clipboard in the background, so copy-and-it's-there can't work the way it does on the Mac." }+ },+ {+ "@type": "Question",+ "name": "Why does macOS say it can't verify the developer of CopySync?",+ "acceptedAnswer": { "@type": "Answer", "text": "CopySync isn't notarized by Apple yet, which requires a paid developer account. Open System Settings, go to Privacy & Security and click Open Anyway. You only need to do this once." }+ },+ {+ "@type": "Question",+ "name": "How does CopySync handle large files?",+ "acceptedAnswer": { "@type": "Answer", "text": "By default, anything under 50 MB is pushed to the other Mac as soon as you copy it. Larger files sync as a record, and you pull them from the history when you need them. The limit is adjustable from 1 MB to 1 GB." }+ },+ {+ "@type": "Question",+ "name": "Is CopySync free?",+ "acceptedAnswer": { "@type": "Answer", "text": "Yes. CopySync is open source under the MIT license, with the source on GitHub." }+ }+ ]+ }+ ]+ }+ </script>+</head>+<body>+ <a class="skip" href="#main">Skip to content</a>++ <header class="site-header">+ <div class="wrap">+ <a class="brand" href="./" aria-label="CopySync home">+ <img src="../assets/icon.svg" alt="" width="26" height="26">+ CopySync+ </a>+ <nav class="site-nav" aria-label="Page">+ <a class="optional" href="#how">How it works</a>+ <a class="optional" href="#install">Install</a>+ <a class="optional" href="#faq">FAQ</a>+ <a href="https://github.com/baiyuze/copysync">GitHub</a>+ <a href="../" hreflang="zh-CN" lang="zh-CN">简体中文</a>+ </nav>+ </div>+ </header>++ <main id="main">+ <section class="hero">+ <div class="wrap">+ <h1>Copy on this Mac.<br>Paste on that one.</h1>+ <p class="lede">Text, images, files, whole folders. No shared Apple ID required, no shared network required. Data moves directly between your devices, and stays encrypted even when it passes through your own server.</p>+ <div class="cta">+ <a class="button" href="https://github.com/baiyuze/copysync/releases/latest/download/CopySync-1.0.0.dmg">+ <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 3v10m0 0-4-4m4 4 4-4M4 16h12"/></svg>+ Download for macOS+ </a>+ <span class="note">Version 1.0.0, free and open source. macOS 13 or later, Intel and Apple silicon.</span>+ </div>++ <div class="demo" role="img" aria-label="Demo: a file is selected on a MacBook Pro and copied with Command C, travels over a direct connection to a MacBook Air, and is pasted there with Command V">+ <figure class="mac mac-a">+ <div class="mac-screen">+ <div class="file">+ <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M5 2.5h6.5L15.5 6.5V17a.5.5 0 0 1-.5.5H5a.5.5 0 0 1-.5-.5V3a.5.5 0 0 1 .5-.5Z"/><path d="M11.5 2.5v4h4"/></svg>+ <span>Q3 Review – final.key <small>38.2 MB</small></span>+ </div>+ <div class="keys"><kbd>⌘</kbd><kbd>C</kbd></div>+ </div>+ <div class="mac-base"></div>+ <figcaption>MacBook Pro</figcaption>+ </figure>+ <div class="link" aria-hidden="true">+ <span class="packet"></span>+ <span class="link-label">Direct, end-to-end encrypted</span>+ </div>+ <figure class="mac mac-b">+ <div class="mac-screen">+ <div class="file">+ <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M5 2.5h6.5L15.5 6.5V17a.5.5 0 0 1-.5.5H5a.5.5 0 0 1-.5-.5V3a.5.5 0 0 1 .5-.5Z"/><path d="M11.5 2.5v4h4"/></svg>+ <span>Q3 Review – final.key <small>38.2 MB</small></span>+ </div>+ <div class="keys"><kbd>⌘</kbd><kbd>V</kbd></div>+ </div>+ <div class="mac-base"></div>+ <figcaption>MacBook Air</figcaption>+ </figure>+ </div>+ <button class="replay" type="button">Play again</button>+ </div>+ </section>++ <section class="section section-band" aria-labelledby="history-title">+ <div class="wrap">+ <h2 id="history-title">Everything you copied, on every Mac</h2>+ <p class="intro">History keeps the last 3 days, ready to go back on the clipboard. Files under 50 MB have already arrived by the time you switch Macs; larger ones are a click away. The interface is in Simplified Chinese for now.</p>+ <figure class="shot">+ <picture>+ <source media="(prefers-color-scheme: dark)" srcset="../assets/screenshots/history-dark.png">+ <img src="../assets/screenshots/history.png" width="2112" height="1472" alt="CopySync history: files, images and text from a MacBook Air and a Mac mini; a large file shows a button to pull it to this Mac">+ </picture>+ </figure>+ </div>+ </section>++ <section class="section" aria-labelledby="why-title">+ <div class="wrap">+ <h2 id="why-title">Why not what's already there</h2>+ <div class="prose">+ <p>If you work on two Macs, you move things between them all day: a snippet of text, a screenshot, a file. The existing options each fall a little short:</p>+ <ul>+ <li><strong>Universal Clipboard</strong> needs both Macs on the same Apple ID, close together, with Bluetooth and Wi‑Fi on. A work Mac and a personal one rarely share an Apple ID, and large files often fail halfway.</li>+ <li><strong>AirDrop</strong> makes you pick a device and accept on the other side every time, and it moves files, not the clipboard.</li>+ <li><strong>Messaging yourself</strong> means manual downloads, recompressed images, and files left on someone else's server.</li>+ </ul>+ </div>+ <div class="table-scroll">+ <table class="compare">+ <caption class="skip">CopySync compared with other options</caption>+ <thead>+ <tr><th scope="col"></th><th scope="col" class="ours">CopySync</th><th scope="col">Universal Clipboard</th><th scope="col">AirDrop</th><th scope="col">Chat apps</th></tr>+ </thead>+ <tbody>+ <tr><th scope="row">Different Apple IDs</th><td class="yes">Yes</td><td class="no">No</td><td class="partial">Needs accepting</td><td class="yes">Yes</td></tr>+ <tr><th scope="row">Different networks (home and office)</th><td class="yes">Yes</td><td class="no">No</td><td class="no">No</td><td class="yes">Yes</td></tr>+ <tr><th scope="row">Paste right away, nothing to accept</th><td class="yes">Yes</td><td class="yes">Yes</td><td class="no">No</td><td class="no">No</td></tr>+ <tr><th scope="row">Files and whole folders</th><td class="yes">Yes</td><td class="partial">Unreliable</td><td class="yes">Yes</td><td class="partial">Zip first</td></tr>+ <tr><th scope="row">Find something you copied earlier</th><td class="yes">Yes</td><td class="no">No</td><td class="no">No</td><td class="partial">Scroll back</td></tr>+ <tr><th scope="row">Content stays off third-party servers</th><td class="yes">Yes</td><td class="yes">Yes</td><td class="yes">Yes</td><td class="no">No</td></tr>+ </tbody>+ </table>+ </div>+ </div>+ </section>++ <section class="section section-band" id="how" aria-labelledby="how-title">+ <div class="wrap">+ <h2 id="how-title">How it works</h2>+ <p class="intro">Your two Macs open an encrypted connection to each other. Your server only helps them find one another, and relays traffic when a direct path can't be made.</p>++ <figure class="diagram">+ <svg viewBox="0 0 960 400" role="img" aria-labelledby="diagram-title diagram-desc">+ <title id="diagram-title">How CopySync connects</title>+ <desc id="diagram-desc">Mac A and Mac B connect directly over WebRTC. Both connect to your server for signaling. If the direct connection fails, data is relayed through the server's TURN service.</desc>+ <rect class="d-box" x="360" y="24" width="240" height="96" rx="14"/>+ <text class="d-title" x="480" y="64" text-anchor="middle">Your server</text>+ <text class="d-sub" x="480" y="92" text-anchor="middle">Signaling, STUN, TURN relay</text>++ <path class="d-sig" d="M140 210V58H360"/>+ <path class="d-sig" d="M820 210V58H600"/>+ <path class="d-relay" d="M196 210V100H360"/>+ <path class="d-relay" d="M764 210V100H600"/>+ <text class="d-note" x="206" y="50">Signaling: connection details</text>+ <text class="d-note" x="206" y="128">Relay: only if direct fails</text>++ <rect class="d-box" x="40" y="210" width="240" height="120" rx="14"/>+ <text class="d-title" x="160" y="262" text-anchor="middle">Mac A</text>+ <text class="d-sub" x="160" y="290" text-anchor="middle">You copy here</text>+ <rect class="d-box" x="680" y="210" width="240" height="120" rx="14"/>+ <text class="d-title" x="800" y="262" text-anchor="middle">Mac B</text>+ <text class="d-sub" x="800" y="290" text-anchor="middle">You paste here</text>++ <path class="d-direct" d="M280 270H680"/>+ <text class="d-label" x="480" y="256" text-anchor="middle">Direct WebRTC, DTLS encrypted</text>+ <text class="d-note" x="480" y="298" text-anchor="middle">Data moves only between your Macs</text>++ <g class="d-legend" transform="translate(40 372)">+ <path class="d-direct" d="M0 0H28"/><text x="38" y="5">Data (direct)</text>+ <path class="d-relay" d="M190 0H218"/><text x="228" y="5">Data (relay, fallback)</text>+ <path class="d-sig" d="M420 0H448"/><text x="458" y="5">Signaling</text>+ </g>+ </svg>+ </figure>++ <h3 class="subhead">What happens when you copy</h3>+ <ol class="steps">+ <li>+ <h3>Notice</h3>+ <p>The background service checks the clipboard's change count at short intervals. Reading the count and types needs no permission and never shows a prompt.</p>+ </li>+ <li>+ <h3>Send</h3>+ <p>Text travels inside the message. Images and files under 50 MB are streamed right away. Larger files are announced as a record and sent when you ask for them.</p>+ </li>+ <li>+ <h3>Paste</h3>+ <p>The other Mac stores the content locally, then puts it on the clipboard. What you paste with ⌘V is a real local file.</p>+ </li>+ </ol>+ </div>+ </section>++ <section class="section" aria-labelledby="security-title">+ <div class="wrap two-col">+ <div class="prose">+ <h2 id="security-title">Your server can't see what you copy</h2>+ <ul>+ <li><strong>No accounts, no stored content.</strong> A device's identity is an Ed25519 key, and its ID is derived from the public key, so the server verifies identity without a user table.</li>+ <li><strong>You compare fingerprints when pairing.</strong> Each Mac shows a fingerprint of the other's key. The server could swap keys in transit, but it can't make both screens show the same fingerprint — that check is what stops a man in the middle.</li>+ <li><strong>Every message after that is signed</strong>, so the server can't impersonate your device. The direct channel's certificate is checked again after the handshake; a mismatch drops the connection.</li>+ <li><strong>The relay only forwards ciphertext.</strong> TURN carries encrypted packets, and relay credentials are issued per device and expire after 12 hours.</li>+ </ul>+ </div>+ <figure class="card-shot">+ <picture>+ <source media="(prefers-color-scheme: dark)" srcset="../assets/screenshots/card-verify-dark.png">+ <img src="../assets/screenshots/card-verify.png" width="1120" height="800" loading="lazy" alt="The fingerprint check during pairing shows R8NF-2WTC-QL5J and asks you to confirm it matches the other Mac exactly">+ </picture>+ </figure>+ </div>+ </section>++ <section class="section section-band" aria-labelledby="fallback-title">+ <div class="wrap">+ <h2 id="fallback-title">When things go wrong</h2>+ <p class="intro">Every network is different. Each of these cases was considered, and each has a test.</p>+ <dl class="fallbacks">+ <dt>No direct path between the Macs</dt>+ <dd>Common behind symmetric NAT and corporate firewalls. Traffic switches to the TURN relay on your server, still encrypted, and the device list shows "relay".</dd>+ <dt>Public STUN servers unreachable</dt>+ <dd>Public STUN is unreliable in some regions, including mainland China. Your server runs its own STUN, and clients prefer it.</dd>+ <dt>Server connection drops</dt>+ <dd>Reconnects automatically: the delay starts at 1 second and doubles up to 30, with jitter so devices don't all reconnect at once. The app shows the status live.</dd>+ <dt>File too large</dt>+ <dd>Above the limit only a record is synced, pulled when you need it. If the source file is gone by then, you get a clear message instead of a vague failure.</dd>+ <dt>Pasting into plain-text fields</dt>+ <dd>Rich text copied from the web is written as both HTML and plain text, so no markup leaks into what you paste.</dd>+ <dt>Clipboard access not granted yet</dt>+ <dd>Content isn't read, which would block on a prompt a background process can't show. The app asks you to grant access and links straight to the setting.</dd>+ <dt>Background service crashes</dt>+ <dd>macOS's launchd restarts it, throttled to once every 10 seconds.</dd>+ <dt>App updated or moved</dt>+ <dd>On launch the app re-points its login item and restarts the service on the new version.</dd>+ </dl>+ </div>+ </section>++ <section class="section" id="install" aria-labelledby="install-title">+ <div class="wrap">+ <h2 id="install-title">Install</h2>+ <p class="intro">Install the app on each Mac, and set up a server both of them can reach. If both Macs share a LAN, the server can run on one of them.</p>+ <div class="two-col">+ <div>+ <h3>On each Mac</h3>+ <ol class="install-steps">+ <li>Download <a href="https://github.com/baiyuze/copysync/releases/latest/download/CopySync-1.0.0.dmg">CopySync-1.0.0.dmg</a>, open it and drag CopySync into Applications.</li>+ <li>Open it from Applications.+ <span class="aside">The first time, macOS says it can't verify the developer: CopySync isn't notarized by Apple yet. Go to System Settings → Privacy & Security and click Open Anyway near the bottom. You only do this once.</span></li>+ <li>Click 启用后台同步 (Enable background sync).</li>+ <li>In 设置 (Settings), enter your server as <code>ws://server-address:8787/signal</code> and press Return.</li>+ <li>When macOS asks whether CopySync may read the clipboard, allow it.</li>+ <li>On one Mac, choose 设备 → 添加设备 (Devices → Add device) to get a 6-character code; enter it on the other, and confirm once the fingerprints match.</li>+ </ol>+ </div>+ <div>+ <h3>On the server</h3>+ <p class="aside-p">Any Linux, as root. On ARM, replace <code>amd64</code> with <code>arm64</code>.</p>+ <div class="code">+ <button class="copy" type="button" data-done="Copied">Copy</button>+<pre><code>curl -LO https://github.com/baiyuze/copysync/releases/latest/download/copysync-server-1.0.0-linux-amd64.tar.gz+tar xzf copysync-server-1.0.0-linux-amd64.tar.gz+cd copysync-server-1.0.0-linux-amd64+sudo ./install.sh YOUR_PUBLIC_IP</code></pre>+ </div>+ <p class="aside-p">The script registers a systemd service that starts on boot and prints the address to enter in the app. Open these ports in your firewall or security group:</p>+ <table class="ports">+ <thead><tr><th scope="col">Port</th><th scope="col">Purpose</th></tr></thead>+ <tbody>+ <tr><td>8787/tcp</td><td>Signaling</td></tr>+ <tr><td>3478/udp</td><td>STUN and TURN</td></tr>+ <tr><td>32768–60999/udp</td><td>Relay ports, assigned by the OS</td></tr>+ </tbody>+ </table>+ <p class="aside-p">Docker works too; see the <a href="https://github.com/baiyuze/copysync/blob/main/server/deploy/README.md">server deployment guide</a>.</p>+ </div>+ </div>+ </div>+ </section>++ <section class="section section-band" aria-labelledby="specs-title">+ <div class="wrap">+ <h2 id="specs-title">Specifications</h2>+ <div class="table-scroll">+ <table class="specs">+ <tbody>+ <tr><th scope="row">Version</th><td>1.0.0, released <time datetime="2026-10-08">October 8, 2026</time></td></tr>+ <tr><th scope="row">Mac app</th><td>macOS 13 Ventura or later; universal binary for Intel and Apple silicon, no Rosetta; 45 MB download</td></tr>+ <tr><th scope="row">Server</th><td>Linux on x86_64 or ARM64 (systemd or Docker), or macOS; about 15 MB of RAM</td></tr>+ <tr><th scope="row">Content</th><td>Plain text, rich text, images and screenshots, files, folders; each type can be turned off</td></tr>+ <tr><th scope="row">Transport</th><td>WebRTC data channels, direct first with TURN relay fallback; files streamed as tar + zstd</td></tr>+ <tr><th scope="row">Encryption and identity</th><td>End-to-end DTLS; Ed25519 device keys; every signaling message signed</td></tr>+ <tr><th scope="row">Pairing</th><td>6-character code valid for 5 minutes, using an alphabet without look-alikes such as 0/O and 1/I; fingerprints compared by you</td></tr>+ <tr><th scope="row">Auto-sync limit</th><td>50 MB by default, adjustable from 1 MB to 1 GB</td></tr>+ <tr><th scope="row">History</th><td>3 days by default, adjustable from 1 hour to 30 days; expired items removed automatically</td></tr>+ <tr><th scope="row">Measured speed</th><td>A 20 MB file transfers in about 330 ms over a direct LAN connection, checksums matching</td></tr>+ <tr><th scope="row">Built with</th><td>Go for the background service and server, Flutter for the app, Protocol Buffers for messages</td></tr>+ <tr><th scope="row">License</th><td>MIT</td></tr>+ </tbody>+ </table>+ </div>+ </div>+ </section>++ <section class="section" id="faq" aria-labelledby="faq-title">+ <div class="wrap">+ <h2 id="faq-title">Questions</h2>+ <div class="faq">+ <details>+ <summary>How is this different from Universal Clipboard?</summary>+ <div class="answer">+ <p>Universal Clipboard needs both devices on the same Apple ID, with Bluetooth and Wi‑Fi on, close to each other. CopySync only needs both Macs to reach your server, so different Apple IDs work, and so does one Mac at home and one at the office. It also keeps a history and lets you pull large files on demand.</p>+ <p>If your Macs share an Apple ID, sit side by side, and you mostly copy text, the built-in feature is already enough.</p>+ </div>+ </details>+ <details>+ <summary>Can the server see what I copy?</summary>+ <div class="answer">+ <p>No. With a direct connection the data never touches the server. When it relays, it forwards DTLS-encrypted packets. It keeps no accounts and stores no clipboard content. The code is open, so you can check.</p>+ </div>+ </details>+ <details>+ <summary>Do I need my own server?</summary>+ <div class="answer">+ <p>Yes. There is no public server, so nobody's data passes through anyone else's machine. On a LAN, run the server on one of your Macs. Across networks you need a machine with a public IP; the smallest cloud VM is enough.</p>+ </div>+ </details>+ <details>+ <summary>Windows? iPhone?</summary>+ <div class="answer">+ <p>Windows is planned. iPhone and iPad aren't supported: iOS doesn't let apps watch the clipboard in the background, so copy-and-it's-there can't work the way it does on the Mac.</p>+ </div>+ </details>+ <details>+ <summary>Why does macOS say it can't verify the developer?</summary>+ <div class="answer">+ <p>CopySync isn't notarized by Apple yet, which requires a paid developer account. Open System Settings → Privacy & Security and click Open Anyway near the bottom. You only do this once. You can also build it from source.</p>+ </div>+ </details>+ <details>+ <summary>What about large files?</summary>+ <div class="answer">+ <p>By default, anything under 50 MB is pushed to the other Mac as you copy it, so you can paste right away. Larger files sync as a record; pull them from the history when you need them. The limit is adjustable in Settings.</p>+ </div>+ </details>+ <details>+ <summary>Is it free?</summary>+ <div class="answer">+ <p>Yes. CopySync is open source under the MIT license, with the source on <a href="https://github.com/baiyuze/copysync">GitHub</a>.</p>+ </div>+ </details>+ </div>+ </div>+ </section>++ <section class="closing section-band" aria-labelledby="closing-title">+ <div class="wrap">+ <h2 id="closing-title">Two Macs, one clipboard.</h2>+ <div class="cta">+ <a class="button" href="https://github.com/baiyuze/copysync/releases/latest/download/CopySync-1.0.0.dmg">Download for macOS</a>+ <a href="https://github.com/baiyuze/copysync">View the source on GitHub</a>+ </div>+ </div>+ </section>+ </main>++ <footer class="site-footer">+ <div class="wrap">+ <span>CopySync is open source, released under the MIT license.</span>+ <nav aria-label="Footer">+ <a href="https://github.com/baiyuze/copysync/releases">All releases</a>+ <a href="https://github.com/baiyuze/copysync/blob/main/CHANGELOG.md">Changelog</a>+ <a href="https://github.com/baiyuze/copysync/issues">Report an issue</a>+ <a href="../" hreflang="zh-CN" lang="zh-CN">简体中文</a>+ </nav>+ </div>+ </footer>++ <script src="../assets/site.js" defer></script>+</body>+</html>diff --git a/docs/index.html b/docs/index.htmlnew file mode 100644index 0000000..52b2d60--- /dev/null+++ b/docs/index.html@@ -0,0 +1,459 @@+<!doctype html>+<html lang="zh-CN">+<head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <title>CopySync:在两台 Mac 之间同步剪贴板与文件,跨 Apple ID,开源免费</title>+ <meta name="description" content="CopySync 让你在一台 Mac 上复制,另一台 Mac 上直接粘贴。支持文本、图片、文件和文件夹,不要求同一个 Apple ID,跨网络可用。设备间 P2P 直连、端到端加密,服务器自己部署且看不到内容。MIT 开源。">+ <link rel="canonical" href="https://baiyuze.github.io/copysync/">+ <link rel="alternate" hreflang="zh-CN" href="https://baiyuze.github.io/copysync/">+ <link rel="alternate" hreflang="en" href="https://baiyuze.github.io/copysync/en/">+ <link rel="alternate" hreflang="x-default" href="https://baiyuze.github.io/copysync/">+ <meta name="theme-color" content="#ffffff" media="(prefers-color-scheme: light)">+ <meta name="theme-color" content="#161617" media="(prefers-color-scheme: dark)">++ <meta property="og:type" content="website">+ <meta property="og:site_name" content="CopySync">+ <meta property="og:title" content="CopySync:在这台 Mac 复制,到那台 Mac 粘贴">+ <meta property="og:description" content="文本、图片、文件、文件夹。跨 Apple ID、跨网络,P2P 直连、端到端加密,服务器自己部署。开源免费。">+ <meta property="og:url" content="https://baiyuze.github.io/copysync/">+ <meta property="og:image" content="https://baiyuze.github.io/copysync/assets/og.png">+ <meta property="og:image:width" content="1200">+ <meta property="og:image:height" content="630">+ <meta property="og:locale" content="zh_CN">+ <meta property="og:locale:alternate" content="en_US">+ <meta name="twitter:card" content="summary_large_image">++ <link rel="icon" href="assets/favicon.svg" type="image/svg+xml">+ <link rel="icon" href="assets/favicon-32.png" sizes="32x32" type="image/png">+ <link rel="apple-touch-icon" href="assets/apple-touch-icon.png">+ <link rel="stylesheet" href="assets/site.css">++ <script type="application/ld+json">+ {+ "@context": "https://schema.org",+ "@graph": [+ {+ "@type": "SoftwareApplication",+ "@id": "https://baiyuze.github.io/copysync/#app",+ "name": "CopySync",+ "description": "在两台 Mac 之间同步剪贴板与文件的开源工具。复制文本、图片、文件或文件夹后,另一台 Mac 可直接粘贴。设备间 WebRTC 直连、DTLS 端到端加密,打不通时经用户自建服务器的 TURN 中转。",+ "applicationCategory": "UtilitiesApplication",+ "operatingSystem": "macOS 13 及以上(Intel 与 Apple 芯片)",+ "softwareVersion": "1.0.0",+ "datePublished": "2026-10-08",+ "inLanguage": "zh-CN",+ "license": "https://opensource.org/licenses/MIT",+ "isAccessibleForFree": true,+ "offers": { "@type": "Offer", "price": "0", "priceCurrency": "CNY" },+ "downloadUrl": "https://github.com/baiyuze/copysync/releases/latest",+ "codeRepository": "https://github.com/baiyuze/copysync",+ "image": "https://baiyuze.github.io/copysync/assets/icon.png",+ "screenshot": "https://baiyuze.github.io/copysync/assets/screenshots/history.png",+ "fileSize": "45MB",+ "featureList": [+ "同步纯文本、带格式的文本、图片、文件与文件夹",+ "不要求同一个 Apple ID,跨网络可用",+ "WebRTC 直连,打不通时自动经 TURN 中转",+ "DTLS 端到端加密,配对时人工核对安全指纹",+ "50 MB 以内复制即推送,更大的文件按需拉取",+ "最近 3 天的复制记录"+ ],+ "author": { "@type": "Person", "name": "baiyuze", "url": "https://github.com/baiyuze" }+ },+ {+ "@type": "FAQPage",+ "mainEntity": [+ {+ "@type": "Question",+ "name": "CopySync 和 macOS 自带的通用剪贴板有什么区别?",+ "acceptedAnswer": { "@type": "Answer", "text": "通用剪贴板要求两台设备登录同一个 Apple ID、开着蓝牙和 Wi-Fi 并且离得近。CopySync 只要求两台 Mac 都能连上你部署的服务器,不同 Apple ID、不同网络都可以,另外有复制记录和大文件按需拉取。" }+ },+ {+ "@type": "Question",+ "name": "CopySync 的服务器会看到我复制的内容吗?",+ "acceptedAnswer": { "@type": "Answer", "text": "不会。直连时数据不经过服务器;需要中转时,服务器只转发 DTLS 加密后的 UDP 包。服务器不存账号,也不存任何复制内容。" }+ },+ {+ "@type": "Question",+ "name": "使用 CopySync 必须自己准备服务器吗?",+ "acceptedAnswer": { "@type": "Answer", "text": "是的,CopySync 不提供公共服务器。两台 Mac 在同一个局域网时,在其中一台上运行服务器即可;跨网络使用需要一台有公网 IP 的服务器,最低配置的云主机就够。" }+ },+ {+ "@type": "Question",+ "name": "CopySync 支持 Windows 和 iPhone 吗?",+ "acceptedAnswer": { "@type": "Answer", "text": "Windows 版在计划中。iPhone 和 iPad 暂不支持:iOS 不允许 App 在后台监听剪贴板,做不到 Mac 上那样复制后立即同步。" }+ },+ {+ "@type": "Question",+ "name": "为什么第一次打开 CopySync 提示无法验证开发者?",+ "acceptedAnswer": { "@type": "Answer", "text": "CopySync 还没有经过 Apple 公证,公证需要付费的开发者账号。到系统设置的隐私与安全性页面,点击「仍要打开」即可,只需要操作一次。" }+ },+ {+ "@type": "Question",+ "name": "CopySync 怎么处理大文件?",+ "acceptedAnswer": { "@type": "Answer", "text": "默认 50 MB 以内的内容在复制时直接推送到另一台 Mac;更大的文件只同步一条记录,需要时在复制记录里点「拉取到本机」。上限可以在设置里调整,范围 1 MB 到 1 GB。" }+ },+ {+ "@type": "Question",+ "name": "CopySync 收费吗?",+ "acceptedAnswer": { "@type": "Answer", "text": "免费。CopySync 以 MIT 许可开源,源码在 GitHub 上。" }+ }+ ]+ }+ ]+ }+ </script>+</head>+<body>+ <a class="skip" href="#main">跳到正文</a>++ <header class="site-header">+ <div class="wrap">+ <a class="brand" href="./" aria-label="CopySync 首页">+ <img src="assets/icon.svg" alt="" width="26" height="26">+ CopySync+ </a>+ <nav class="site-nav" aria-label="页面导航">+ <a class="optional" href="#how">工作原理</a>+ <a class="optional" href="#install">安装</a>+ <a class="optional" href="#faq">常见问题</a>+ <a href="https://github.com/baiyuze/copysync">GitHub</a>+ <a href="en/" hreflang="en" lang="en">English</a>+ </nav>+ </div>+ </header>++ <main id="main">+ <section class="hero">+ <div class="wrap">+ <h1>在这台 Mac 复制,<br>到那台 Mac 粘贴。</h1>+ <p class="lede">文本、图片、文件、整个文件夹都可以。不要求同一个 Apple ID,也不要求在同一个网络。数据在你的设备之间直接传输,经过你自己的服务器时也是加密的。</p>+ <div class="cta">+ <a class="button" href="https://github.com/baiyuze/copysync/releases/latest/download/CopySync-1.0.0.dmg">+ <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 3v10m0 0-4-4m4 4 4-4M4 16h12"/></svg>+ 下载 macOS 版+ </a>+ <span class="note">版本 1.0.0,免费开源。macOS 13 及以上,Intel 与 Apple 芯片通用。</span>+ </div>++ <div class="demo" role="img" aria-label="演示:在 MacBook Pro 上选中文件并按下 Command C,文件经直连传到 MacBook Air,在那里按下 Command V 粘贴出来">+ <figure class="mac mac-a">+ <div class="mac-screen">+ <div class="file">+ <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M5 2.5h6.5L15.5 6.5V17a.5.5 0 0 1-.5.5H5a.5.5 0 0 1-.5-.5V3a.5.5 0 0 1 .5-.5Z"/><path d="M11.5 2.5v4h4"/></svg>+ <span>季度汇报-终版.key <small>38.2 MB</small></span>+ </div>+ <div class="keys"><kbd>⌘</kbd><kbd>C</kbd></div>+ </div>+ <div class="mac-base"></div>+ <figcaption>MacBook Pro</figcaption>+ </figure>+ <div class="link" aria-hidden="true">+ <span class="packet"></span>+ <span class="link-label">直连,端到端加密</span>+ </div>+ <figure class="mac mac-b">+ <div class="mac-screen">+ <div class="file">+ <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M5 2.5h6.5L15.5 6.5V17a.5.5 0 0 1-.5.5H5a.5.5 0 0 1-.5-.5V3a.5.5 0 0 1 .5-.5Z"/><path d="M11.5 2.5v4h4"/></svg>+ <span>季度汇报-终版.key <small>38.2 MB</small></span>+ </div>+ <div class="keys"><kbd>⌘</kbd><kbd>V</kbd></div>+ </div>+ <div class="mac-base"></div>+ <figcaption>MacBook Air</figcaption>+ </figure>+ </div>+ <button class="replay" type="button">再演示一次</button>+ </div>+ </section>++ <section class="section section-band" aria-labelledby="history-title">+ <div class="wrap">+ <h2 id="history-title">所有设备上复制过的,都在这里</h2>+ <p class="intro">复制记录保留最近 3 天的内容,随时可以放回剪贴板。50 MB 以内的文件在你复制的时候就已经传好了,更大的文件需要时点一下再拉取。</p>+ <figure class="shot">+ <picture>+ <source media="(prefers-color-scheme: dark)" srcset="assets/screenshots/history-dark.png">+ <img src="assets/screenshots/history.png" width="2112" height="1472" alt="CopySync 的复制记录:来自 MacBook Air 和 Mac mini 的文件、图片、文字,大文件显示「拉取到本机」按钮">+ </picture>+ </figure>+ </div>+ </section>++ <section class="section" aria-labelledby="why-title">+ <div class="wrap">+ <h2 id="why-title">为什么不用现有的办法</h2>+ <div class="prose">+ <p>手边有两台 Mac 的人,每天都要把东西从这台挪到那台:一段文字、一张截图、一个文件。现有的办法都差一点:</p>+ <ul>+ <li><strong>通用剪贴板</strong>要求两台设备登录同一个 Apple ID、离得足够近、蓝牙和 Wi‑Fi 都开着。公司的电脑和自己的电脑很少是同一个 Apple ID,大文件也经常复制到一半就没了。</li>+ <li><strong>隔空投送</strong>每次都要选设备、在另一台上点接收,而且只传文件,不管剪贴板。</li>+ <li><strong>用聊天软件发给自己</strong>要手动下载,图片会被压缩,文件还会留在别人的服务器上。</li>+ </ul>+ </div>+ <div class="table-scroll">+ <table class="compare">+ <caption class="skip">CopySync 与其他方式的对比</caption>+ <thead>+ <tr><th scope="col"></th><th scope="col" class="ours">CopySync</th><th scope="col">通用剪贴板</th><th scope="col">隔空投送</th><th scope="col">聊天软件</th></tr>+ </thead>+ <tbody>+ <tr><th scope="row">不同 Apple ID 之间</th><td class="yes">可以</td><td class="no">不行</td><td class="partial">要对方接收</td><td class="yes">可以</td></tr>+ <tr><th scope="row">不在同一个网络(家里和公司)</th><td class="yes">可以</td><td class="no">不行</td><td class="no">不行</td><td class="yes">可以</td></tr>+ <tr><th scope="row">复制后直接粘贴,不用点接收</th><td class="yes">可以</td><td class="yes">可以</td><td class="no">不行</td><td class="no">不行</td></tr>+ <tr><th scope="row">文件与整个文件夹</th><td class="yes">可以</td><td class="partial">不稳定</td><td class="yes">可以</td><td class="partial">要先打包</td></tr>+ <tr><th scope="row">找回之前复制过的内容</th><td class="yes">可以</td><td class="no">不行</td><td class="no">不行</td><td class="partial">翻聊天记录</td></tr>+ <tr><th scope="row">内容不经过第三方服务器</th><td class="yes">不经过</td><td class="yes">不经过</td><td class="yes">不经过</td><td class="no">经过</td></tr>+ </tbody>+ </table>+ </div>+ </div>+ </section>++ <section class="section section-band" id="how" aria-labelledby="how-title">+ <div class="wrap">+ <h2 id="how-title">工作原理</h2>+ <p class="intro">两台 Mac 之间直接建立加密连接。你的服务器只负责让它们找到彼此,打不通直连的时候再帮忙转发。</p>++ <figure class="diagram">+ <svg viewBox="0 0 960 400" role="img" aria-labelledby="diagram-title diagram-desc">+ <title id="diagram-title">CopySync 的连接方式</title>+ <desc id="diagram-desc">Mac A 与 Mac B 之间是 WebRTC 直连;两台 Mac 都通过信令连接到你的服务器;直连失败时,数据经服务器的 TURN 中转。</desc>+ <rect class="d-box" x="360" y="24" width="240" height="96" rx="14"/>+ <text class="d-title" x="480" y="64" text-anchor="middle">你的服务器</text>+ <text class="d-sub" x="480" y="92" text-anchor="middle">信令、STUN、TURN 中转</text>++ <path class="d-sig" d="M140 210V58H360"/>+ <path class="d-sig" d="M820 210V58H600"/>+ <path class="d-relay" d="M196 210V100H360"/>+ <path class="d-relay" d="M764 210V100H600"/>+ <text class="d-note" x="210" y="50">信令:交换连接信息</text>+ <text class="d-note" x="210" y="128">中转:仅在打不通直连时</text>++ <rect class="d-box" x="40" y="210" width="240" height="120" rx="14"/>+ <text class="d-title" x="160" y="262" text-anchor="middle">Mac A</text>+ <text class="d-sub" x="160" y="290" text-anchor="middle">在这里复制</text>+ <rect class="d-box" x="680" y="210" width="240" height="120" rx="14"/>+ <text class="d-title" x="800" y="262" text-anchor="middle">Mac B</text>+ <text class="d-sub" x="800" y="290" text-anchor="middle">在这里粘贴</text>++ <path class="d-direct" d="M280 270H680"/>+ <text class="d-label" x="480" y="256" text-anchor="middle">WebRTC 直连,DTLS 加密</text>+ <text class="d-note" x="480" y="298" text-anchor="middle">数据只在两台 Mac 之间传输</text>++ <g class="d-legend" transform="translate(40 372)">+ <path class="d-direct" d="M0 0H28"/><text x="38" y="5">数据(直连)</text>+ <path class="d-relay" d="M190 0H218"/><text x="228" y="5">数据(中转,备用)</text>+ <path class="d-sig" d="M420 0H448"/><text x="458" y="5">信令</text>+ </g>+ </svg>+ </figure>++ <h3 class="subhead">一次复制的经过</h3>+ <ol class="steps">+ <li>+ <h3>感知</h3>+ <p>后台服务每隔一小段时间检查剪贴板的变更计数。只看计数和类型不需要授权,也不会弹出系统提示。</p>+ </li>+ <li>+ <h3>传输</h3>+ <p>文本随消息一起发出;50 MB 以内的图片和文件打包成流立即推送;更大的文件只发一条记录,等你需要时再传。</p>+ </li>+ <li>+ <h3>粘贴</h3>+ <p>另一台 Mac 先把内容存到本地,再写入剪贴板。按下 ⌘V 粘贴出来的,就是本地的真实文件。</p>+ </li>+ </ol>+ </div>+ </section>++ <section class="section" aria-labelledby="security-title">+ <div class="wrap two-col">+ <div class="prose">+ <h2 id="security-title">服务器看不到你复制了什么</h2>+ <ul>+ <li><strong>服务器不存账号,也不存内容。</strong>设备身份是一把 Ed25519 密钥,设备 ID 由公钥算出,服务器不需要用户表就能验证身份。</li>+ <li><strong>配对时由你核对安全指纹。</strong>两台屏幕各自显示对方公钥的指纹。服务器有能力替换转发中的公钥,但没法让两边显示出相同的指纹,这一步就是防中间人的闸门。</li>+ <li><strong>之后的每条消息都带签名</strong>,服务器无法冒充你的设备。直连通道的证书在握手后还会再核对一次,不一致立即断开。</li>+ <li><strong>中转也只是转发密文。</strong>TURN 转发的是加密后的数据包,中转凭证按设备单独签发,12 小时后过期。</li>+ </ul>+ </div>+ <figure class="card-shot">+ <picture>+ <source media="(prefers-color-scheme: dark)" srcset="assets/screenshots/card-verify-dark.png">+ <img src="assets/screenshots/card-verify.png" width="1120" height="800" loading="lazy" alt="配对时的「核对安全指纹」对话框,显示 R8NF-2WTC-QL5J,要求与另一台 Mac 上显示的完全一致">+ </picture>+ </figure>+ </div>+ </section>++ <section class="section section-band" aria-labelledby="fallback-title">+ <div class="wrap">+ <h2 id="fallback-title">出问题的时候会发生什么</h2>+ <p class="intro">每个人的网络环境都不一样。下面这些情况都考虑过,也都有对应的测试。</p>+ <dl class="fallbacks">+ <dt>两台 Mac 打不通直连</dt>+ <dd>常见于对称 NAT 和公司防火墙。自动改走你服务器上的 TURN 中转,内容依然加密,设备列表里显示「中转」。</dd>+ <dt>公共 STUN 服务器连不上</dt>+ <dd>国内访问公共 STUN 时通时断。服务器自带 STUN,客户端优先用它。</dd>+ <dt>服务器断开</dt>+ <dd>自动重连,间隔从 1 秒开始翻倍、最长 30 秒,并带随机抖动,避免一群设备同时重连。界面实时显示连接状态。</dd>+ <dt>文件太大</dt>+ <dd>超过上限的只同步一条记录,需要时再拉取。拉取时源文件已经被删,会明确告诉你,而不是不明不白地失败。</dd>+ <dt>粘贴到只认纯文本的地方</dt>+ <dd>从网页复制的带格式文字会同时写入 HTML 和纯文本两份,粘贴到哪里都不会冒出标签。</dd>+ <dt>还没授权读取剪贴板</dt>+ <dd>不去读内容,否则后台进程会卡在一个看不见的系统弹窗上。App 里会提示你去授权,并给出直达按钮。</dd>+ <dt>后台服务崩溃</dt>+ <dd>由 macOS 的 launchd 自动拉起,10 秒节流,不会疯狂重启。</dd>+ <dt>更新了 App,或者把它挪了位置</dt>+ <dd>打开 App 时会自动校正登录项,并把后台服务重启到新版本。</dd>+ </dl>+ </div>+ </section>++ <section class="section" id="install" aria-labelledby="install-title">+ <div class="wrap">+ <h2 id="install-title">安装</h2>+ <p class="intro">每台 Mac 装一个 App,再准备一台两边都能访问到的服务器。两台 Mac 在同一个局域网的话,服务器直接跑在其中一台上就行。</p>+ <div class="two-col">+ <div>+ <h3>在每台 Mac 上</h3>+ <ol class="install-steps">+ <li>下载 <a href="https://github.com/baiyuze/copysync/releases/latest/download/CopySync-1.0.0.dmg">CopySync-1.0.0.dmg</a>,打开后把 CopySync 拖进「应用程序」。</li>+ <li>从「应用程序」里打开。+ <span class="aside">第一次会提示「无法验证开发者」:CopySync 还没有经过 Apple 公证。到「系统设置 → 隐私与安全性」,点页面下方的「仍要打开」,只需要这一次。</span></li>+ <li>点「启用后台同步」。</li>+ <li>在「设置」里填入服务器地址 <code>ws://服务器地址:8787/signal</code>,按回车。</li>+ <li>系统询问是否允许读取剪贴板时,选择允许。</li>+ <li>一台点「设备 → 添加设备」生成 6 位配对码,另一台输入它;两边核对安全指纹一致后确认。</li>+ </ol>+ </div>+ <div>+ <h3>在服务器上</h3>+ <p class="aside-p">任意 Linux,需要 root。ARM 服务器把 <code>amd64</code> 换成 <code>arm64</code>。</p>+ <div class="code">+ <button class="copy" type="button" data-done="已复制">复制</button>+<pre><code>curl -LO https://github.com/baiyuze/copysync/releases/latest/download/copysync-server-1.0.0-linux-amd64.tar.gz+tar xzf copysync-server-1.0.0-linux-amd64.tar.gz+cd copysync-server-1.0.0-linux-amd64+sudo ./install.sh 你的公网IP</code></pre>+ </div>+ <p class="aside-p">脚本会注册开机自启的 systemd 服务,最后打印出 App 里要填的地址。防火墙或云安全组需要放行:</p>+ <table class="ports">+ <thead><tr><th scope="col">端口</th><th scope="col">用途</th></tr></thead>+ <tbody>+ <tr><td>8787/tcp</td><td>信令</td></tr>+ <tr><td>3478/udp</td><td>STUN 与 TURN</td></tr>+ <tr><td>32768–60999/udp</td><td>中转端口,由系统随机分配</td></tr>+ </tbody>+ </table>+ <p class="aside-p">也可以用 Docker 部署,见<a href="https://github.com/baiyuze/copysync/blob/main/server/deploy/README.md">服务器部署说明</a>。</p>+ </div>+ </div>+ </div>+ </section>++ <section class="section section-band" aria-labelledby="specs-title">+ <div class="wrap">+ <h2 id="specs-title">技术规格</h2>+ <div class="table-scroll">+ <table class="specs">+ <tbody>+ <tr><th scope="row">版本</th><td>1.0.0,<time datetime="2026-10-08">2026 年 10 月 8 日</time>发布</td></tr>+ <tr><th scope="row">Mac 客户端</th><td>macOS 13 Ventura 及以上;Intel 与 Apple 芯片通用,不需要 Rosetta;安装包 45 MB</td></tr>+ <tr><th scope="row">服务器</th><td>Linux x86_64 或 ARM64(systemd 或 Docker),也可以运行在 macOS 上;约 15 MB 内存</td></tr>+ <tr><th scope="row">同步的内容</th><td>纯文本、带格式的文本、图片与截图、文件、文件夹,可以按类型关闭</td></tr>+ <tr><th scope="row">传输</th><td>WebRTC 数据通道,直连优先,打不通时经 TURN 中转;文件以 tar + zstd 流式打包</td></tr>+ <tr><th scope="row">加密与身份</th><td>DTLS 端到端加密;设备身份为 Ed25519 密钥;信令消息逐条签名</td></tr>+ <tr><th scope="row">配对</th><td>6 位配对码,5 分钟内有效,字符集去掉了 0/O、1/I 等易混字符;配对时人工核对安全指纹</td></tr>+ <tr><th scope="row">自动同步上限</th><td>默认 50 MB,可在 1 MB 到 1 GB 之间调整</td></tr>+ <tr><th scope="row">记录保留</th><td>默认 3 天,可在 1 小时到 30 天之间调整,到期自动清理</td></tr>+ <tr><th scope="row">实测速度</th><td>局域网直连传输 20 MB 文件约 330 毫秒,校验和一致</td></tr>+ <tr><th scope="row">技术栈</th><td>后台服务与服务器用 Go,界面用 Flutter,消息定义用 Protocol Buffers</td></tr>+ <tr><th scope="row">许可</th><td>MIT 开源</td></tr>+ </tbody>+ </table>+ </div>+ </div>+ </section>++ <section class="section" id="faq" aria-labelledby="faq-title">+ <div class="wrap">+ <h2 id="faq-title">常见问题</h2>+ <div class="faq">+ <details>+ <summary>和 macOS 自带的「通用剪贴板」有什么区别?</summary>+ <div class="answer">+ <p>通用剪贴板要求两台设备登录同一个 Apple ID、开着蓝牙和 Wi‑Fi,并且离得近。CopySync 只要求两台 Mac 都能连上你部署的服务器:不同 Apple ID、一台在家一台在公司,都可以。另外它有复制记录,大文件也可以按需拉取。</p>+ <p>如果你的两台 Mac 是同一个 Apple ID、总在一起、主要复制文字,系统自带的已经够用了。</p>+ </div>+ </details>+ <details>+ <summary>服务器会看到我复制的内容吗?</summary>+ <div class="answer">+ <p>不会。直连时数据根本不经过服务器;需要中转时,服务器转发的是 DTLS 加密后的数据包。服务器不存账号,也不存任何复制内容。代码是开源的,可以自己核对。</p>+ </div>+ </details>+ <details>+ <summary>必须自己准备服务器吗?</summary>+ <div class="answer">+ <p>是的,CopySync 不提供公共服务器,这样就不会有任何人的数据经过别人的机器。两台 Mac 在同一个局域网时,在其中一台上运行服务器即可;跨网络使用需要一台有公网 IP 的服务器,最低配置的云主机就够。</p>+ </div>+ </details>+ <details>+ <summary>支持 Windows 和 iPhone 吗?</summary>+ <div class="answer">+ <p>Windows 版在计划中。iPhone 和 iPad 暂不支持:iOS 不允许 App 在后台监听剪贴板,做不到 Mac 上那种复制后立即同步的体验。</p>+ </div>+ </details>+ <details>+ <summary>为什么第一次打开提示「无法验证开发者」?</summary>+ <div class="answer">+ <p>CopySync 还没有经过 Apple 公证,公证需要每年付费的开发者账号。到「系统设置 → 隐私与安全性」,点页面下方的「仍要打开」即可,只需要这一次。也可以从源码自己构建。</p>+ </div>+ </details>+ <details>+ <summary>大文件怎么处理?</summary>+ <div class="answer">+ <p>默认 50 MB 以内的内容在你复制时就推送到另一台 Mac,那边可以直接粘贴;更大的文件只同步一条记录,需要时在复制记录里点「拉取到本机」再传。上限可以在设置里调整。</p>+ </div>+ </details>+ <details>+ <summary>收费吗?</summary>+ <div class="answer">+ <p>免费。CopySync 以 MIT 许可开源,源码在 <a href="https://github.com/baiyuze/copysync">GitHub</a> 上。</p>+ </div>+ </details>+ </div>+ </div>+ </section>++ <section class="closing section-band" aria-labelledby="closing-title">+ <div class="wrap">+ <h2 id="closing-title">两台 Mac,一个剪贴板。</h2>+ <div class="cta">+ <a class="button" href="https://github.com/baiyuze/copysync/releases/latest/download/CopySync-1.0.0.dmg">下载 macOS 版</a>+ <a href="https://github.com/baiyuze/copysync">在 GitHub 上查看源码</a>+ </div>+ </div>+ </section>+ </main>++ <footer class="site-footer">+ <div class="wrap">+ <span>CopySync 是开源软件,以 MIT 许可发布。</span>+ <nav aria-label="页脚链接">+ <a href="https://github.com/baiyuze/copysync/releases">所有版本</a>+ <a href="https://github.com/baiyuze/copysync/blob/main/CHANGELOG.md">更新记录</a>+ <a href="https://github.com/baiyuze/copysync/issues">反馈问题</a>+ <a href="en/" hreflang="en" lang="en">English</a>+ </nav>+ </div>+ </footer>++ <script src="assets/site.js" defer></script>+</body>+</html>diff --git a/docs/llms.txt b/docs/llms.txtnew file mode 100644index 0000000..2f372e5--- /dev/null+++ b/docs/llms.txt@@ -0,0 +1,29 @@+# CopySync++> CopySync is a free, open-source (MIT) macOS app that syncs the clipboard and files between Macs: copy on one Mac, paste on another. It works across different Apple IDs and different networks. Devices connect peer-to-peer over WebRTC with end-to-end DTLS encryption; when a direct connection fails, traffic is relayed through a TURN server the user hosts themselves. The server stores no accounts and cannot read clipboard content.+>+> CopySync 是一款免费开源(MIT)的 macOS 工具,在两台 Mac 之间同步剪贴板与文件:一台复制,另一台直接粘贴。不要求同一个 Apple ID,跨网络可用。设备间 WebRTC 直连、DTLS 端到端加密,打不通时经用户自建服务器的 TURN 中转;服务器不存账号,看不到复制内容。++Key facts:++- Current version: 1.0.0, released 2026-10-08.+- Client: macOS 13 Ventura or later, universal binary for Intel and Apple silicon. Distributed as a DMG; not notarized by Apple, so the first launch needs "Open Anyway" in System Settings → Privacy & Security.+- Server: a single static Go binary for Linux (x86_64, ARM64) or macOS, installed via systemd script or Docker Compose. Ports: 8787/tcp (signaling), 3478/udp (STUN/TURN), 32768–60999/udp (relay).+- Content synced: plain text, rich text (HTML plus a plain-text copy), images, files, folders.+- Items under 50 MB (adjustable 1 MB–1 GB) are pushed on copy; larger files sync as a record and are pulled on demand.+- History keeps 3 days by default (adjustable 1 hour–30 days).+- Pairing: 6-character code valid for 5 minutes, plus a human-verified fingerprint of the peer's Ed25519 public key to prevent man-in-the-middle attacks by the server.+- Not supported: Windows (planned), iPhone/iPad (iOS forbids background clipboard monitoring). Both Macs must be online at the same time; there is no store-and-forward.+- Compared with Apple's Universal Clipboard: no same-Apple-ID or proximity requirement, keeps a history, handles large files and folders.++## Docs++- [README (中文)](https://github.com/baiyuze/copysync/blob/main/README.md): features, installation, architecture, security model, fallbacks+- [README (English)](https://github.com/baiyuze/copysync/blob/main/README.en.md): the same in English+- [Server deployment](https://github.com/baiyuze/copysync/blob/main/server/deploy/README.md): systemd, Docker and manual setup+- [Changelog](https://github.com/baiyuze/copysync/blob/main/CHANGELOG.md)++## Download++- [Latest release](https://github.com/baiyuze/copysync/releases/latest): CopySync DMG for macOS and server packages for Linux and macOS+- [Source code](https://github.com/baiyuze/copysync)diff --git a/docs/robots.txt b/docs/robots.txtnew file mode 100644index 0000000..7be234b--- /dev/null+++ b/docs/robots.txt@@ -0,0 +1,4 @@+User-agent: *+Allow: /++Sitemap: https://baiyuze.github.io/copysync/sitemap.xmldiff --git a/docs/sitemap.xml b/docs/sitemap.xmlnew file mode 100644index 0000000..a357c99--- /dev/null+++ b/docs/sitemap.xml@@ -0,0 +1,18 @@+<?xml version="1.0" encoding="UTF-8"?>+<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"+ xmlns:xhtml="http://www.w3.org/1999/xhtml">+ <url>+ <loc>https://baiyuze.github.io/copysync/</loc>+ <lastmod>2026-10-08</lastmod>+ <xhtml:link rel="alternate" hreflang="zh-CN" href="https://baiyuze.github.io/copysync/"/>+ <xhtml:link rel="alternate" hreflang="en" href="https://baiyuze.github.io/copysync/en/"/>+ <xhtml:link rel="alternate" hreflang="x-default" href="https://baiyuze.github.io/copysync/"/>+ </url>+ <url>+ <loc>https://baiyuze.github.io/copysync/en/</loc>+ <lastmod>2026-10-08</lastmod>+ <xhtml:link rel="alternate" hreflang="zh-CN" href="https://baiyuze.github.io/copysync/"/>+ <xhtml:link rel="alternate" hreflang="en" href="https://baiyuze.github.io/copysync/en/"/>+ <xhtml:link rel="alternate" hreflang="x-default" href="https://baiyuze.github.io/copysync/"/>+ </url>+</urlset>diff --git a/go.work b/go.worknew file mode 100644index 0000000..eb0501e--- /dev/null+++ b/go.work@@ -0,0 +1,7 @@+go 1.26.3++use (+ ./proto+ ./server+ ./client-core+)diff --git a/go.work.sum b/go.work.sumnew file mode 100644index 0000000..cf77978--- /dev/null+++ b/go.work.sum@@ -0,0 +1,15 @@+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/pion/transport/v4 v4.0.2/go.mod h1:06hFI+jCFcok2X2MekVufNZ/uzNZXivGBPfviSVcjgM=+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=+github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0=+github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=+github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=+go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=+golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=+golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k=+golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=+golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=+golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=+golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=diff --git a/proto/buf.yaml b/proto/buf.yamlnew file mode 100644index 0000000..a518eb6--- /dev/null+++ b/proto/buf.yaml@@ -0,0 +1,14 @@+version: v2++lint:+ use:+ - STANDARD+ except:+ # 本项目的 proto 不对外发布,不强制 RPC 请求/响应类型独立命名+ - RPC_REQUEST_STANDARD_NAME+ - RPC_RESPONSE_STANDARD_NAME+ - RPC_REQUEST_RESPONSE_UNIQUE++breaking:+ use:+ - FILEdiff --git a/proto/copysync/v1/daemon.proto b/proto/copysync/v1/daemon.protonew file mode 100644index 0000000..c14d6ea--- /dev/null+++ b/proto/copysync/v1/daemon.proto@@ -0,0 +1,229 @@+// Flutter UI ↔ Go daemon 之间的接口。+//+// daemon 是常驻后台的核心进程,UI 只是控制台——关掉 UI 不影响同步。+// 事件走 server-streaming 主动推送,避免 UI 轮询。++syntax = "proto3";++package copysync.v1;++option go_package = "github.com/baiyuze/copysync/proto/gen/copysync/v1;copysyncv1";++service DaemonService {+ // 订阅事件流。UI 启动后第一件事,断线需重连。+ rpc Subscribe(SubscribeRequest) returns (stream Event);++ rpc ListHistory(ListHistoryRequest) returns (ListHistoryResponse);+ rpc DeleteHistory(DeleteHistoryRequest) returns (Empty);++ // 拉取仅有元数据的大文件记录。立即返回,进度走事件流。+ rpc Fetch(FetchRequest) returns (Empty);+ // 把某条已就绪的记录重新放进本机剪贴板+ rpc ApplyToClipboard(ApplyToClipboardRequest) returns (Empty);++ rpc ListDevices(Empty) returns (ListDevicesResponse);+ rpc CreatePairingCode(Empty) returns (CreatePairingCodeResponse);+ rpc RedeemPairingCode(RedeemPairingCodeRequest) returns (RedeemPairingCodeResponse);+ // 配对双方各自确认指纹后才真正互信+ rpc ConfirmPairing(ConfirmPairingRequest) returns (Empty);+ rpc Unpair(UnpairRequest) returns (Empty);++ rpc GetConfig(Empty) returns (Config);+ rpc UpdateConfig(Config) returns (Config);++ rpc GetStatus(Empty) returns (Status);+ // 引导用户授予剪贴板权限(打开系统设置面板)+ rpc RequestClipboardPermission(Empty) returns (Empty);+}++message Empty {}++// ─────────────────────────── 剪贴板记录 ───────────────────────────++enum ClipKind {+ CLIP_KIND_UNSPECIFIED = 0;+ CLIP_KIND_TEXT = 1;+ CLIP_KIND_HTML = 2;+ CLIP_KIND_IMAGE = 3;+ CLIP_KIND_FILE = 4; // 文件或文件夹,可多个+}++enum ClipStatus {+ CLIP_STATUS_UNSPECIFIED = 0;+ CLIP_STATUS_READY = 1; // 内容已在本地,可直接粘贴+ CLIP_STATUS_REMOTE_ONLY = 2; // 超过阈值,只有元数据,需手动拉取+ CLIP_STATUS_FETCHING = 3;+ CLIP_STATUS_FAILED = 4;+ CLIP_STATUS_EXPIRED = 5; // 超过 cache_ttl,内容已被 GC 删除+}++message ClipItem {+ string name = 1;+ int64 size = 2;+ bool is_dir = 3;+ string content_type = 4; // UTType 标识符,如 public.plain-text+}++message ClipRecord {+ string id = 1;+ ClipKind kind = 2;+ ClipStatus status = 3;++ string origin_device_id = 4;+ string origin_device_name = 5;+ bool outgoing = 6; // true=本机复制的 false=从对端收到的++ repeated ClipItem items = 7;+ int64 total_size = 8;+ string text_preview = 9; // 文本/HTML 的预览片段,列表展示用++ int64 created_at_unix = 10;+ int64 expires_at_unix = 11;+ string error = 12; // status=FAILED 时的具体原因+}++// ─────────────────────────── 事件流 ───────────────────────────++message SubscribeRequest {+ // 断线重连时带上最后收到的记录时间,daemon 补发这之后的记录+ int64 since_unix = 1;+}++message TransferProgress {+ string clip_id = 1;+ int64 transferred = 2;+ int64 total = 3; // 0 表示总量未知(流式打包时)+ double bytes_per_second = 4;+}++enum ConnectionKind {+ CONNECTION_KIND_UNSPECIFIED = 0;+ CONNECTION_KIND_OFFLINE = 1;+ CONNECTION_KIND_DIRECT = 2; // P2P 打洞成功+ CONNECTION_KIND_RELAY = 3; // 经 TURN 中转+}++message Device {+ string id = 1;+ string name = 2;+ string platform = 3; // darwin / windows+ bool online = 4;+ ConnectionKind connection = 5;+ string public_key_fingerprint = 6;+ int64 paired_at_unix = 7;++ // 非空表示这是一条**待用户核对指纹**的配对请求,而非已配对设备。+ // 用此值调 ConfirmPairing 完成或拒绝配对。+ // 配对码的发起方是被动收到兑换通知的,靠这个字段把确认入口推给界面。+ string pairing_session = 8;+}++// macOS 剪贴板授权状态,对应 NSPasteboardAccessBehavior。+// 非 ALWAYS_ALLOW 时 daemon 不会去读剪贴板内容,避免卡在授权弹窗上。+enum ClipboardPermission {+ CLIPBOARD_PERMISSION_UNSPECIFIED = 0;+ CLIPBOARD_PERMISSION_NOT_APPLICABLE = 1; // 未启用隐私机制的系统+ CLIPBOARD_PERMISSION_DEFAULT = 2;+ CLIPBOARD_PERMISSION_ASK = 3;+ CLIPBOARD_PERMISSION_ALWAYS_ALLOW = 4;+ CLIPBOARD_PERMISSION_ALWAYS_DENY = 5;+}++message Event {+ oneof payload {+ ClipRecord clip_added = 1;+ ClipRecord clip_updated = 2;+ string clip_removed = 3; // clip id+ TransferProgress progress = 4;+ Device device_changed = 5;+ ClipboardPermission permission_changed = 6;+ Status status_changed = 7;+ }+}++// ─────────────────────────── 查询与操作 ───────────────────────────++message ListHistoryRequest {+ int32 limit = 1;+ int64 before_unix = 2; // 分页游标+ ClipKind kind_filter = 3; // UNSPECIFIED 表示不过滤+}++message ListHistoryResponse {+ repeated ClipRecord records = 1;+}++message DeleteHistoryRequest {+ repeated string ids = 1;+ bool all = 2;+}++message FetchRequest {+ string clip_id = 1;+}++message ApplyToClipboardRequest {+ string clip_id = 1;+}++// ─────────────────────────── 设备与配对 ───────────────────────────++message ListDevicesResponse {+ Device self = 1;+ repeated Device peers = 2;+}++message CreatePairingCodeResponse {+ string code = 1;+ int64 expires_at_unix = 2;+}++message RedeemPairingCodeRequest {+ string code = 1;+}++message RedeemPairingCodeResponse {+ // 返回对端信息供用户肉眼核对指纹,确认后再调 ConfirmPairing+ Device peer = 1;+ string pairing_session = 2;+}++message ConfirmPairingRequest {+ string pairing_session = 1;+ bool accept = 2;+}++message UnpairRequest {+ string device_id = 1;+}++// ─────────────────────────── 配置与状态 ───────────────────────────++message Config {+ // 小于此值自动预取,大于此值只同步元数据等用户手动拉取+ int64 auto_sync_threshold_bytes = 1;+ int64 history_ttl_seconds = 2;+ int64 cache_ttl_seconds = 3;++ bool sync_text = 4;+ bool sync_html = 5;+ bool sync_image = 6;+ bool sync_file = 7;++ // 收到对端内容后是否自动覆盖本机剪贴板+ bool auto_apply_to_clipboard = 8;+ bool launch_at_login = 9;++ string device_name = 10;+ string signaling_url = 11;+}++message Status {+ string device_id = 1;+ string device_name = 2;+ bool signaling_connected = 3;+ ClipboardPermission clipboard_permission = 4;+ int64 cache_bytes_used = 5;+ int32 peers_online = 6;+ string version = 7;+}diff --git a/proto/copysync/v1/wire.proto b/proto/copysync/v1/wire.protonew file mode 100644index 0000000..d642e04--- /dev/null+++ b/proto/copysync/v1/wire.proto@@ -0,0 +1,226 @@+// 线上协议:客户端 ↔ 信令服务器,以及设备 ↔ 设备。+//+// 信令服务器只转发、不解密内容,也不存用户——设备靠配对时交换的+// Ed25519 公钥互相认证。所有经服务器中转的信令都带签名,+// 防止服务器伪造 peer 身份做中间人。++syntax = "proto3";++package copysync.v1;++// ClipKind / ClipItem 在此复用,避免两套等价定义+import "copysync/v1/daemon.proto";++option go_package = "github.com/baiyuze/copysync/proto/gen/copysync/v1;copysyncv1";++// ═══════════════════ 信令层(WebSocket 承载)═══════════════════++// 经服务器转发的消息一律包一层签名。接收方用配对时存下的+// 对端公钥验签,服务器无法伪造。+message Signed {+ bytes payload = 1; // 序列化后的 SignalMessage+ bytes signature = 2; // Ed25519 签名,覆盖 payload+ string from_device_id = 3;+}++message SignalMessage {+ // 防重放:接收方拒绝时间戳过旧或 nonce 重复的消息+ int64 timestamp_unix = 1;+ bytes nonce = 2;+ string to_device_id = 3;++ oneof payload {+ SdpOffer offer = 10;+ SdpAnswer answer = 11;+ IceCandidate candidate = 12;+ Ping ping = 13;+ }+}++message SdpOffer {+ string sdp = 1;+ // DTLS 证书指纹。经签名传输,杜绝信令服务器中间人攻击——+ // 这是 P2P 通道真正的安全锚点。+ string dtls_fingerprint = 2;+}++message SdpAnswer {+ string sdp = 1;+ string dtls_fingerprint = 2;+}++message IceCandidate {+ string candidate = 1;+ string sdp_mid = 2;+ uint32 sdp_mline_index = 3;+}++message Ping {+ int64 sent_at_unix = 1;+}++// ── 客户端 → 服务器(不经转发,直接处理)──++message ClientHello {+ string device_id = 1;+ string device_name = 2;+ string platform = 3;+ bytes public_key = 4; // Ed25519+ bytes signature = 5; // 对 challenge 的签名,证明持有私钥+ repeated string paired_device_ids = 6; // 关心哪些对端的在线状态+}++message ServerHello {+ bytes challenge = 1;+ repeated IceServer ice_servers = 2;+ int64 server_time_unix = 3;+}++message IceServer {+ repeated string urls = 1;+ string username = 2; // TURN 短期凭证+ string credential = 3;+ int64 expires_at_unix = 4;+}++message PeerPresence {+ string device_id = 1;+ bool online = 2;+}++// ── 配对 ──++message PairingCreateRequest {+ string device_name = 1;+ bytes public_key = 2;+}++message PairingCreateResponse {+ string code = 1; // 6 位,服务器侧 TTL 5 分钟+ int64 expires_at_unix = 2;+}++message PairingRedeemRequest {+ string code = 1;+ string device_id = 2;+ string device_name = 3;+ bytes public_key = 4;+}++message PairingRedeemResponse {+ string peer_device_id = 1;+ string peer_device_name = 2;+ string peer_platform = 3;+ bytes peer_public_key = 4;+}++// 服务器 → 发起方:有人兑换了你的配对码+message PairingRedeemed {+ string peer_device_id = 1;+ string peer_device_name = 2;+ string peer_platform = 3;+ bytes peer_public_key = 4;+}++// TURN 凭证是按设备签发且有有效期的,因此必须在认证完成后才能下发,+// 之后也会在临近过期时重新推送。+message IceConfig {+ repeated IceServer ice_servers = 1;+}++// 客户端 ↔ 服务器的顶层信封+message ServerEnvelope {+ oneof payload {+ ServerHello hello = 1;+ Signed forwarded = 2; // 转发自其他设备+ PeerPresence presence = 3;+ PairingCreateResponse pairing_created = 4;+ PairingRedeemResponse pairing_redeemed_result = 5;+ PairingRedeemed pairing_redeemed = 6;+ ServerError error = 7;+ IceConfig ice_config = 8;+ }+}++message ClientEnvelope {+ oneof payload {+ ClientHello hello = 1;+ Signed forward = 2; // 请服务器转发给 to_device_id+ PairingCreateRequest pairing_create = 3;+ PairingRedeemRequest pairing_redeem = 4;+ }+}++message ServerError {+ string code = 1;+ string message = 2;+}++// ═══════════════════ 设备间协议(DataChannel 承载)═══════════════════+//+// 控制消息与数据流走不同的 DataChannel,避免大文件传输阻塞控制通道。++// 控制通道消息+message PeerMessage {+ oneof payload {+ ClipOffer offer = 1; // 广播:我这边复制了东西+ PeerFetch fetch = 2; // 请求:把某条内容发给我+ FetchReject reject = 3; // 拒绝:源文件没了 / 已过期+ TransferHeader header = 4; // 数据流即将开始+ TransferDone done = 5;+ }+}++// 复制发生时广播给所有在线对端。+// 小于阈值的内容会紧接着主动推送;大于阈值的只发这条,等对方来取。+message ClipOffer {+ string clip_id = 1;+ ClipKind kind = 2;+ repeated ClipItem items = 3;+ int64 total_size = 4;+ string text_content = 5; // 文本/HTML 直接内联,无需二次传输+ int64 created_at_unix = 6;+ bool will_push = 7; // true=发送方会主动推,false=需 fetch+ // HTML 的纯文本形式(此时 text_content 是 HTML 标记)。旧版本不发这个字段,+ // 收到空值时由接收方从 HTML 中提取。+ string plain_text = 8;+}++// 与 daemon.proto 的 FetchRequest(UI→daemon)区分:这条是 daemon→peer+message PeerFetch {+ string clip_id = 1;+}++message FetchReject {+ string clip_id = 1;+ string reason = 2; // source_missing / expired / denied+}++// 数据流的第一条消息,之后是裸字节流直到 total_bytes+message TransferHeader {+ string clip_id = 1;+ string stream_id = 2;+ int64 total_bytes = 3; // 压缩后的字节数;0 表示未知(流式打包)+ Compression compression = 4;+ Packaging packaging = 5;+}++enum Compression {+ COMPRESSION_UNSPECIFIED = 0;+ COMPRESSION_NONE = 1;+ COMPRESSION_ZSTD = 2;+}++enum Packaging {+ PACKAGING_UNSPECIFIED = 0;+ PACKAGING_RAW = 1; // 单个文件,裸内容+ PACKAGING_TAR = 2; // 多文件或目录+}++message TransferDone {+ string clip_id = 1;+ string stream_id = 2;+ bool ok = 3;+ string error = 4;+ bytes sha256 = 5;+}diff --git a/proto/deviceid/deviceid.go b/proto/deviceid/deviceid.gonew file mode 100644index 0000000..f740814--- /dev/null+++ b/proto/deviceid/deviceid.go@@ -0,0 +1,48 @@+// Package deviceid 定义设备 ID 与指纹的派生规则。+//+// 这属于协议契约的一部分:客户端与服务器必须用完全相同的规则,+// 否则服务器无法校验「这个 device_id 确实属于这把公钥」。+// 因此放在 proto 模块里与 .proto 一同维护,而不是各自实现一份。+package deviceid++import (+ "crypto/ed25519"+ "crypto/sha256"+ "encoding/base32"+ "strings"+)++// 不带填充的 Base32:字符集无易混字符,适合展示与口头转述。+var enc = base32.StdEncoding.WithPadding(base32.NoPadding)++// For 由公钥确定性地派生设备 ID。+//+// 做成确定性派生,任何一方都能独立校验 ID 与公钥的对应关系——+// 服务器因此无需维护用户表也能拒绝伪造的 device_id。+func For(pub ed25519.PublicKey) string {+ sum := sha256.Sum256(pub)+ return strings.ToLower(enc.EncodeToString(sum[:16]))+}++// Fingerprint 返回供用户肉眼核对的短指纹,形如 "K7X2-M9PL-4RT8"。+//+// 配对时双方各自显示,用户确认一致后才建立互信。这一步是+// 防止信令服务器在配对阶段做中间人的关键——服务器可以替换公钥,+// 但无法让两端显示出相同的指纹。+func Fingerprint(pub ed25519.PublicKey) string {+ sum := sha256.Sum256(pub)+ s := enc.EncodeToString(sum[:8])+ parts := make([]string, 0, 3)+ for i := 0; i+4 <= len(s) && len(parts) < 3; i += 4 {+ parts = append(parts, s[i:i+4])+ }+ return strings.Join(parts, "-")+}++// Valid 校验 id 是否确实由 pub 派生而来。+func Valid(id string, pub ed25519.PublicKey) bool {+ if len(pub) != ed25519.PublicKeySize {+ return false+ }+ return id == For(pub)+}diff --git a/proto/gen/copysync/v1/daemon.pb.go b/proto/gen/copysync/v1/daemon.pb.gonew file mode 100644index 0000000..02f3703--- /dev/null+++ b/proto/gen/copysync/v1/daemon.pb.go@@ -0,0 +1,1904 @@+// Flutter UI ↔ Go daemon 之间的接口。+//+// daemon 是常驻后台的核心进程,UI 只是控制台——关掉 UI 不影响同步。+// 事件走 server-streaming 主动推送,避免 UI 轮询。++// Code generated by protoc-gen-go. DO NOT EDIT.+// versions:+// protoc-gen-go v1.36.12+// protoc (unknown)+// source: copysync/v1/daemon.proto++package copysyncv1++import (+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"+ reflect "reflect"+ sync "sync"+ unsafe "unsafe"+)++const (+ // Verify that this generated code is sufficiently up-to-date.+ _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)+ // Verify that runtime/protoimpl is sufficiently up-to-date.+ _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)+)++type ClipKind int32++const (+ ClipKind_CLIP_KIND_UNSPECIFIED ClipKind = 0+ ClipKind_CLIP_KIND_TEXT ClipKind = 1+ ClipKind_CLIP_KIND_HTML ClipKind = 2+ ClipKind_CLIP_KIND_IMAGE ClipKind = 3+ ClipKind_CLIP_KIND_FILE ClipKind = 4 // 文件或文件夹,可多个+)++// Enum value maps for ClipKind.+var (+ ClipKind_name = map[int32]string{+ 0: "CLIP_KIND_UNSPECIFIED",+ 1: "CLIP_KIND_TEXT",+ 2: "CLIP_KIND_HTML",+ 3: "CLIP_KIND_IMAGE",+ 4: "CLIP_KIND_FILE",+ }+ ClipKind_value = map[string]int32{+ "CLIP_KIND_UNSPECIFIED": 0,+ "CLIP_KIND_TEXT": 1,+ "CLIP_KIND_HTML": 2,+ "CLIP_KIND_IMAGE": 3,+ "CLIP_KIND_FILE": 4,+ }+)++func (x ClipKind) Enum() *ClipKind {+ p := new(ClipKind)+ *p = x+ return p+}++func (x ClipKind) String() string {+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))+}++func (ClipKind) Descriptor() protoreflect.EnumDescriptor {+ return file_copysync_v1_daemon_proto_enumTypes[0].Descriptor()+}++func (ClipKind) Type() protoreflect.EnumType {+ return &file_copysync_v1_daemon_proto_enumTypes[0]+}++func (x ClipKind) Number() protoreflect.EnumNumber {+ return protoreflect.EnumNumber(x)+}++// Deprecated: Use ClipKind.Descriptor instead.+func (ClipKind) EnumDescriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{0}+}++type ClipStatus int32++const (+ ClipStatus_CLIP_STATUS_UNSPECIFIED ClipStatus = 0+ ClipStatus_CLIP_STATUS_READY ClipStatus = 1 // 内容已在本地,可直接粘贴+ ClipStatus_CLIP_STATUS_REMOTE_ONLY ClipStatus = 2 // 超过阈值,只有元数据,需手动拉取+ ClipStatus_CLIP_STATUS_FETCHING ClipStatus = 3+ ClipStatus_CLIP_STATUS_FAILED ClipStatus = 4+ ClipStatus_CLIP_STATUS_EXPIRED ClipStatus = 5 // 超过 cache_ttl,内容已被 GC 删除+)++// Enum value maps for ClipStatus.+var (+ ClipStatus_name = map[int32]string{+ 0: "CLIP_STATUS_UNSPECIFIED",+ 1: "CLIP_STATUS_READY",+ 2: "CLIP_STATUS_REMOTE_ONLY",+ 3: "CLIP_STATUS_FETCHING",+ 4: "CLIP_STATUS_FAILED",+ 5: "CLIP_STATUS_EXPIRED",+ }+ ClipStatus_value = map[string]int32{+ "CLIP_STATUS_UNSPECIFIED": 0,+ "CLIP_STATUS_READY": 1,+ "CLIP_STATUS_REMOTE_ONLY": 2,+ "CLIP_STATUS_FETCHING": 3,+ "CLIP_STATUS_FAILED": 4,+ "CLIP_STATUS_EXPIRED": 5,+ }+)++func (x ClipStatus) Enum() *ClipStatus {+ p := new(ClipStatus)+ *p = x+ return p+}++func (x ClipStatus) String() string {+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))+}++func (ClipStatus) Descriptor() protoreflect.EnumDescriptor {+ return file_copysync_v1_daemon_proto_enumTypes[1].Descriptor()+}++func (ClipStatus) Type() protoreflect.EnumType {+ return &file_copysync_v1_daemon_proto_enumTypes[1]+}++func (x ClipStatus) Number() protoreflect.EnumNumber {+ return protoreflect.EnumNumber(x)+}++// Deprecated: Use ClipStatus.Descriptor instead.+func (ClipStatus) EnumDescriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{1}+}++type ConnectionKind int32++const (+ ConnectionKind_CONNECTION_KIND_UNSPECIFIED ConnectionKind = 0+ ConnectionKind_CONNECTION_KIND_OFFLINE ConnectionKind = 1+ ConnectionKind_CONNECTION_KIND_DIRECT ConnectionKind = 2 // P2P 打洞成功+ ConnectionKind_CONNECTION_KIND_RELAY ConnectionKind = 3 // 经 TURN 中转+)++// Enum value maps for ConnectionKind.+var (+ ConnectionKind_name = map[int32]string{+ 0: "CONNECTION_KIND_UNSPECIFIED",+ 1: "CONNECTION_KIND_OFFLINE",+ 2: "CONNECTION_KIND_DIRECT",+ 3: "CONNECTION_KIND_RELAY",+ }+ ConnectionKind_value = map[string]int32{+ "CONNECTION_KIND_UNSPECIFIED": 0,+ "CONNECTION_KIND_OFFLINE": 1,+ "CONNECTION_KIND_DIRECT": 2,+ "CONNECTION_KIND_RELAY": 3,+ }+)++func (x ConnectionKind) Enum() *ConnectionKind {+ p := new(ConnectionKind)+ *p = x+ return p+}++func (x ConnectionKind) String() string {+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))+}++func (ConnectionKind) Descriptor() protoreflect.EnumDescriptor {+ return file_copysync_v1_daemon_proto_enumTypes[2].Descriptor()+}++func (ConnectionKind) Type() protoreflect.EnumType {+ return &file_copysync_v1_daemon_proto_enumTypes[2]+}++func (x ConnectionKind) Number() protoreflect.EnumNumber {+ return protoreflect.EnumNumber(x)+}++// Deprecated: Use ConnectionKind.Descriptor instead.+func (ConnectionKind) EnumDescriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{2}+}++// macOS 剪贴板授权状态,对应 NSPasteboardAccessBehavior。+// 非 ALWAYS_ALLOW 时 daemon 不会去读剪贴板内容,避免卡在授权弹窗上。+type ClipboardPermission int32++const (+ ClipboardPermission_CLIPBOARD_PERMISSION_UNSPECIFIED ClipboardPermission = 0+ ClipboardPermission_CLIPBOARD_PERMISSION_NOT_APPLICABLE ClipboardPermission = 1 // 未启用隐私机制的系统+ ClipboardPermission_CLIPBOARD_PERMISSION_DEFAULT ClipboardPermission = 2+ ClipboardPermission_CLIPBOARD_PERMISSION_ASK ClipboardPermission = 3+ ClipboardPermission_CLIPBOARD_PERMISSION_ALWAYS_ALLOW ClipboardPermission = 4+ ClipboardPermission_CLIPBOARD_PERMISSION_ALWAYS_DENY ClipboardPermission = 5+)++// Enum value maps for ClipboardPermission.+var (+ ClipboardPermission_name = map[int32]string{+ 0: "CLIPBOARD_PERMISSION_UNSPECIFIED",+ 1: "CLIPBOARD_PERMISSION_NOT_APPLICABLE",+ 2: "CLIPBOARD_PERMISSION_DEFAULT",+ 3: "CLIPBOARD_PERMISSION_ASK",+ 4: "CLIPBOARD_PERMISSION_ALWAYS_ALLOW",+ 5: "CLIPBOARD_PERMISSION_ALWAYS_DENY",+ }+ ClipboardPermission_value = map[string]int32{+ "CLIPBOARD_PERMISSION_UNSPECIFIED": 0,+ "CLIPBOARD_PERMISSION_NOT_APPLICABLE": 1,+ "CLIPBOARD_PERMISSION_DEFAULT": 2,+ "CLIPBOARD_PERMISSION_ASK": 3,+ "CLIPBOARD_PERMISSION_ALWAYS_ALLOW": 4,+ "CLIPBOARD_PERMISSION_ALWAYS_DENY": 5,+ }+)++func (x ClipboardPermission) Enum() *ClipboardPermission {+ p := new(ClipboardPermission)+ *p = x+ return p+}++func (x ClipboardPermission) String() string {+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))+}++func (ClipboardPermission) Descriptor() protoreflect.EnumDescriptor {+ return file_copysync_v1_daemon_proto_enumTypes[3].Descriptor()+}++func (ClipboardPermission) Type() protoreflect.EnumType {+ return &file_copysync_v1_daemon_proto_enumTypes[3]+}++func (x ClipboardPermission) Number() protoreflect.EnumNumber {+ return protoreflect.EnumNumber(x)+}++// Deprecated: Use ClipboardPermission.Descriptor instead.+func (ClipboardPermission) EnumDescriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{3}+}++type Empty struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *Empty) Reset() {+ *x = Empty{}+ mi := &file_copysync_v1_daemon_proto_msgTypes[0]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *Empty) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*Empty) ProtoMessage() {}++func (x *Empty) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_daemon_proto_msgTypes[0]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use Empty.ProtoReflect.Descriptor instead.+func (*Empty) Descriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{0}+}++type ClipItem struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`+ Size int64 `protobuf:"varint,2,opt,name=size,proto3" json:"size,omitempty"`+ IsDir bool `protobuf:"varint,3,opt,name=is_dir,json=isDir,proto3" json:"is_dir,omitempty"`+ ContentType string `protobuf:"bytes,4,opt,name=content_type,json=contentType,proto3" json:"content_type,omitempty"` // UTType 标识符,如 public.plain-text+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ClipItem) Reset() {+ *x = ClipItem{}+ mi := &file_copysync_v1_daemon_proto_msgTypes[1]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ClipItem) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ClipItem) ProtoMessage() {}++func (x *ClipItem) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_daemon_proto_msgTypes[1]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ClipItem.ProtoReflect.Descriptor instead.+func (*ClipItem) Descriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{1}+}++func (x *ClipItem) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++func (x *ClipItem) GetSize() int64 {+ if x != nil {+ return x.Size+ }+ return 0+}++func (x *ClipItem) GetIsDir() bool {+ if x != nil {+ return x.IsDir+ }+ return false+}++func (x *ClipItem) GetContentType() string {+ if x != nil {+ return x.ContentType+ }+ return ""+}++type ClipRecord struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`+ Kind ClipKind `protobuf:"varint,2,opt,name=kind,proto3,enum=copysync.v1.ClipKind" json:"kind,omitempty"`+ Status ClipStatus `protobuf:"varint,3,opt,name=status,proto3,enum=copysync.v1.ClipStatus" json:"status,omitempty"`+ OriginDeviceId string `protobuf:"bytes,4,opt,name=origin_device_id,json=originDeviceId,proto3" json:"origin_device_id,omitempty"`+ OriginDeviceName string `protobuf:"bytes,5,opt,name=origin_device_name,json=originDeviceName,proto3" json:"origin_device_name,omitempty"`+ Outgoing bool `protobuf:"varint,6,opt,name=outgoing,proto3" json:"outgoing,omitempty"` // true=本机复制的 false=从对端收到的+ Items []*ClipItem `protobuf:"bytes,7,rep,name=items,proto3" json:"items,omitempty"`+ TotalSize int64 `protobuf:"varint,8,opt,name=total_size,json=totalSize,proto3" json:"total_size,omitempty"`+ TextPreview string `protobuf:"bytes,9,opt,name=text_preview,json=textPreview,proto3" json:"text_preview,omitempty"` // 文本/HTML 的预览片段,列表展示用+ CreatedAtUnix int64 `protobuf:"varint,10,opt,name=created_at_unix,json=createdAtUnix,proto3" json:"created_at_unix,omitempty"`+ ExpiresAtUnix int64 `protobuf:"varint,11,opt,name=expires_at_unix,json=expiresAtUnix,proto3" json:"expires_at_unix,omitempty"`+ Error string `protobuf:"bytes,12,opt,name=error,proto3" json:"error,omitempty"` // status=FAILED 时的具体原因+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ClipRecord) Reset() {+ *x = ClipRecord{}+ mi := &file_copysync_v1_daemon_proto_msgTypes[2]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ClipRecord) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ClipRecord) ProtoMessage() {}++func (x *ClipRecord) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_daemon_proto_msgTypes[2]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ClipRecord.ProtoReflect.Descriptor instead.+func (*ClipRecord) Descriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{2}+}++func (x *ClipRecord) GetId() string {+ if x != nil {+ return x.Id+ }+ return ""+}++func (x *ClipRecord) GetKind() ClipKind {+ if x != nil {+ return x.Kind+ }+ return ClipKind_CLIP_KIND_UNSPECIFIED+}++func (x *ClipRecord) GetStatus() ClipStatus {+ if x != nil {+ return x.Status+ }+ return ClipStatus_CLIP_STATUS_UNSPECIFIED+}++func (x *ClipRecord) GetOriginDeviceId() string {+ if x != nil {+ return x.OriginDeviceId+ }+ return ""+}++func (x *ClipRecord) GetOriginDeviceName() string {+ if x != nil {+ return x.OriginDeviceName+ }+ return ""+}++func (x *ClipRecord) GetOutgoing() bool {+ if x != nil {+ return x.Outgoing+ }+ return false+}++func (x *ClipRecord) GetItems() []*ClipItem {+ if x != nil {+ return x.Items+ }+ return nil+}++func (x *ClipRecord) GetTotalSize() int64 {+ if x != nil {+ return x.TotalSize+ }+ return 0+}++func (x *ClipRecord) GetTextPreview() string {+ if x != nil {+ return x.TextPreview+ }+ return ""+}++func (x *ClipRecord) GetCreatedAtUnix() int64 {+ if x != nil {+ return x.CreatedAtUnix+ }+ return 0+}++func (x *ClipRecord) GetExpiresAtUnix() int64 {+ if x != nil {+ return x.ExpiresAtUnix+ }+ return 0+}++func (x *ClipRecord) GetError() string {+ if x != nil {+ return x.Error+ }+ return ""+}++type SubscribeRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // 断线重连时带上最后收到的记录时间,daemon 补发这之后的记录+ SinceUnix int64 `protobuf:"varint,1,opt,name=since_unix,json=sinceUnix,proto3" json:"since_unix,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *SubscribeRequest) Reset() {+ *x = SubscribeRequest{}+ mi := &file_copysync_v1_daemon_proto_msgTypes[3]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *SubscribeRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*SubscribeRequest) ProtoMessage() {}++func (x *SubscribeRequest) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_daemon_proto_msgTypes[3]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use SubscribeRequest.ProtoReflect.Descriptor instead.+func (*SubscribeRequest) Descriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{3}+}++func (x *SubscribeRequest) GetSinceUnix() int64 {+ if x != nil {+ return x.SinceUnix+ }+ return 0+}++type TransferProgress struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ ClipId string `protobuf:"bytes,1,opt,name=clip_id,json=clipId,proto3" json:"clip_id,omitempty"`+ Transferred int64 `protobuf:"varint,2,opt,name=transferred,proto3" json:"transferred,omitempty"`+ Total int64 `protobuf:"varint,3,opt,name=total,proto3" json:"total,omitempty"` // 0 表示总量未知(流式打包时)+ BytesPerSecond float64 `protobuf:"fixed64,4,opt,name=bytes_per_second,json=bytesPerSecond,proto3" json:"bytes_per_second,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *TransferProgress) Reset() {+ *x = TransferProgress{}+ mi := &file_copysync_v1_daemon_proto_msgTypes[4]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *TransferProgress) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*TransferProgress) ProtoMessage() {}++func (x *TransferProgress) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_daemon_proto_msgTypes[4]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use TransferProgress.ProtoReflect.Descriptor instead.+func (*TransferProgress) Descriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{4}+}++func (x *TransferProgress) GetClipId() string {+ if x != nil {+ return x.ClipId+ }+ return ""+}++func (x *TransferProgress) GetTransferred() int64 {+ if x != nil {+ return x.Transferred+ }+ return 0+}++func (x *TransferProgress) GetTotal() int64 {+ if x != nil {+ return x.Total+ }+ return 0+}++func (x *TransferProgress) GetBytesPerSecond() float64 {+ if x != nil {+ return x.BytesPerSecond+ }+ return 0+}++type Device struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`+ Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`+ Platform string `protobuf:"bytes,3,opt,name=platform,proto3" json:"platform,omitempty"` // darwin / windows+ Online bool `protobuf:"varint,4,opt,name=online,proto3" json:"online,omitempty"`+ Connection ConnectionKind `protobuf:"varint,5,opt,name=connection,proto3,enum=copysync.v1.ConnectionKind" json:"connection,omitempty"`+ PublicKeyFingerprint string `protobuf:"bytes,6,opt,name=public_key_fingerprint,json=publicKeyFingerprint,proto3" json:"public_key_fingerprint,omitempty"`+ PairedAtUnix int64 `protobuf:"varint,7,opt,name=paired_at_unix,json=pairedAtUnix,proto3" json:"paired_at_unix,omitempty"`+ // 非空表示这是一条**待用户核对指纹**的配对请求,而非已配对设备。+ // 用此值调 ConfirmPairing 完成或拒绝配对。+ // 配对码的发起方是被动收到兑换通知的,靠这个字段把确认入口推给界面。+ PairingSession string `protobuf:"bytes,8,opt,name=pairing_session,json=pairingSession,proto3" json:"pairing_session,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *Device) Reset() {+ *x = Device{}+ mi := &file_copysync_v1_daemon_proto_msgTypes[5]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *Device) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*Device) ProtoMessage() {}++func (x *Device) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_daemon_proto_msgTypes[5]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use Device.ProtoReflect.Descriptor instead.+func (*Device) Descriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{5}+}++func (x *Device) GetId() string {+ if x != nil {+ return x.Id+ }+ return ""+}++func (x *Device) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++func (x *Device) GetPlatform() string {+ if x != nil {+ return x.Platform+ }+ return ""+}++func (x *Device) GetOnline() bool {+ if x != nil {+ return x.Online+ }+ return false+}++func (x *Device) GetConnection() ConnectionKind {+ if x != nil {+ return x.Connection+ }+ return ConnectionKind_CONNECTION_KIND_UNSPECIFIED+}++func (x *Device) GetPublicKeyFingerprint() string {+ if x != nil {+ return x.PublicKeyFingerprint+ }+ return ""+}++func (x *Device) GetPairedAtUnix() int64 {+ if x != nil {+ return x.PairedAtUnix+ }+ return 0+}++func (x *Device) GetPairingSession() string {+ if x != nil {+ return x.PairingSession+ }+ return ""+}++type Event struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // Types that are valid to be assigned to Payload:+ //+ // *Event_ClipAdded+ // *Event_ClipUpdated+ // *Event_ClipRemoved+ // *Event_Progress+ // *Event_DeviceChanged+ // *Event_PermissionChanged+ // *Event_StatusChanged+ Payload isEvent_Payload `protobuf_oneof:"payload"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *Event) Reset() {+ *x = Event{}+ mi := &file_copysync_v1_daemon_proto_msgTypes[6]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *Event) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*Event) ProtoMessage() {}++func (x *Event) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_daemon_proto_msgTypes[6]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use Event.ProtoReflect.Descriptor instead.+func (*Event) Descriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{6}+}++func (x *Event) GetPayload() isEvent_Payload {+ if x != nil {+ return x.Payload+ }+ return nil+}++func (x *Event) GetClipAdded() *ClipRecord {+ if x != nil {+ if x, ok := x.Payload.(*Event_ClipAdded); ok {+ return x.ClipAdded+ }+ }+ return nil+}++func (x *Event) GetClipUpdated() *ClipRecord {+ if x != nil {+ if x, ok := x.Payload.(*Event_ClipUpdated); ok {+ return x.ClipUpdated+ }+ }+ return nil+}++func (x *Event) GetClipRemoved() string {+ if x != nil {+ if x, ok := x.Payload.(*Event_ClipRemoved); ok {+ return x.ClipRemoved+ }+ }+ return ""+}++func (x *Event) GetProgress() *TransferProgress {+ if x != nil {+ if x, ok := x.Payload.(*Event_Progress); ok {+ return x.Progress+ }+ }+ return nil+}++func (x *Event) GetDeviceChanged() *Device {+ if x != nil {+ if x, ok := x.Payload.(*Event_DeviceChanged); ok {+ return x.DeviceChanged+ }+ }+ return nil+}++func (x *Event) GetPermissionChanged() ClipboardPermission {+ if x != nil {+ if x, ok := x.Payload.(*Event_PermissionChanged); ok {+ return x.PermissionChanged+ }+ }+ return ClipboardPermission_CLIPBOARD_PERMISSION_UNSPECIFIED+}++func (x *Event) GetStatusChanged() *Status {+ if x != nil {+ if x, ok := x.Payload.(*Event_StatusChanged); ok {+ return x.StatusChanged+ }+ }+ return nil+}++type isEvent_Payload interface {+ isEvent_Payload()+}++type Event_ClipAdded struct {+ ClipAdded *ClipRecord `protobuf:"bytes,1,opt,name=clip_added,json=clipAdded,proto3,oneof"`+}++type Event_ClipUpdated struct {+ ClipUpdated *ClipRecord `protobuf:"bytes,2,opt,name=clip_updated,json=clipUpdated,proto3,oneof"`+}++type Event_ClipRemoved struct {+ ClipRemoved string `protobuf:"bytes,3,opt,name=clip_removed,json=clipRemoved,proto3,oneof"` // clip id+}++type Event_Progress struct {+ Progress *TransferProgress `protobuf:"bytes,4,opt,name=progress,proto3,oneof"`+}++type Event_DeviceChanged struct {+ DeviceChanged *Device `protobuf:"bytes,5,opt,name=device_changed,json=deviceChanged,proto3,oneof"`+}++type Event_PermissionChanged struct {+ PermissionChanged ClipboardPermission `protobuf:"varint,6,opt,name=permission_changed,json=permissionChanged,proto3,enum=copysync.v1.ClipboardPermission,oneof"`+}++type Event_StatusChanged struct {+ StatusChanged *Status `protobuf:"bytes,7,opt,name=status_changed,json=statusChanged,proto3,oneof"`+}++func (*Event_ClipAdded) isEvent_Payload() {}++func (*Event_ClipUpdated) isEvent_Payload() {}++func (*Event_ClipRemoved) isEvent_Payload() {}++func (*Event_Progress) isEvent_Payload() {}++func (*Event_DeviceChanged) isEvent_Payload() {}++func (*Event_PermissionChanged) isEvent_Payload() {}++func (*Event_StatusChanged) isEvent_Payload() {}++type ListHistoryRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Limit int32 `protobuf:"varint,1,opt,name=limit,proto3" json:"limit,omitempty"`+ BeforeUnix int64 `protobuf:"varint,2,opt,name=before_unix,json=beforeUnix,proto3" json:"before_unix,omitempty"` // 分页游标+ KindFilter ClipKind `protobuf:"varint,3,opt,name=kind_filter,json=kindFilter,proto3,enum=copysync.v1.ClipKind" json:"kind_filter,omitempty"` // UNSPECIFIED 表示不过滤+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ListHistoryRequest) Reset() {+ *x = ListHistoryRequest{}+ mi := &file_copysync_v1_daemon_proto_msgTypes[7]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ListHistoryRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ListHistoryRequest) ProtoMessage() {}++func (x *ListHistoryRequest) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_daemon_proto_msgTypes[7]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ListHistoryRequest.ProtoReflect.Descriptor instead.+func (*ListHistoryRequest) Descriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{7}+}++func (x *ListHistoryRequest) GetLimit() int32 {+ if x != nil {+ return x.Limit+ }+ return 0+}++func (x *ListHistoryRequest) GetBeforeUnix() int64 {+ if x != nil {+ return x.BeforeUnix+ }+ return 0+}++func (x *ListHistoryRequest) GetKindFilter() ClipKind {+ if x != nil {+ return x.KindFilter+ }+ return ClipKind_CLIP_KIND_UNSPECIFIED+}++type ListHistoryResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Records []*ClipRecord `protobuf:"bytes,1,rep,name=records,proto3" json:"records,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ListHistoryResponse) Reset() {+ *x = ListHistoryResponse{}+ mi := &file_copysync_v1_daemon_proto_msgTypes[8]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ListHistoryResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ListHistoryResponse) ProtoMessage() {}++func (x *ListHistoryResponse) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_daemon_proto_msgTypes[8]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ListHistoryResponse.ProtoReflect.Descriptor instead.+func (*ListHistoryResponse) Descriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{8}+}++func (x *ListHistoryResponse) GetRecords() []*ClipRecord {+ if x != nil {+ return x.Records+ }+ return nil+}++type DeleteHistoryRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Ids []string `protobuf:"bytes,1,rep,name=ids,proto3" json:"ids,omitempty"`+ All bool `protobuf:"varint,2,opt,name=all,proto3" json:"all,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *DeleteHistoryRequest) Reset() {+ *x = DeleteHistoryRequest{}+ mi := &file_copysync_v1_daemon_proto_msgTypes[9]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *DeleteHistoryRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*DeleteHistoryRequest) ProtoMessage() {}++func (x *DeleteHistoryRequest) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_daemon_proto_msgTypes[9]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use DeleteHistoryRequest.ProtoReflect.Descriptor instead.+func (*DeleteHistoryRequest) Descriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{9}+}++func (x *DeleteHistoryRequest) GetIds() []string {+ if x != nil {+ return x.Ids+ }+ return nil+}++func (x *DeleteHistoryRequest) GetAll() bool {+ if x != nil {+ return x.All+ }+ return false+}++type FetchRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ ClipId string `protobuf:"bytes,1,opt,name=clip_id,json=clipId,proto3" json:"clip_id,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *FetchRequest) Reset() {+ *x = FetchRequest{}+ mi := &file_copysync_v1_daemon_proto_msgTypes[10]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *FetchRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*FetchRequest) ProtoMessage() {}++func (x *FetchRequest) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_daemon_proto_msgTypes[10]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use FetchRequest.ProtoReflect.Descriptor instead.+func (*FetchRequest) Descriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{10}+}++func (x *FetchRequest) GetClipId() string {+ if x != nil {+ return x.ClipId+ }+ return ""+}++type ApplyToClipboardRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ ClipId string `protobuf:"bytes,1,opt,name=clip_id,json=clipId,proto3" json:"clip_id,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ApplyToClipboardRequest) Reset() {+ *x = ApplyToClipboardRequest{}+ mi := &file_copysync_v1_daemon_proto_msgTypes[11]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ApplyToClipboardRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ApplyToClipboardRequest) ProtoMessage() {}++func (x *ApplyToClipboardRequest) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_daemon_proto_msgTypes[11]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ApplyToClipboardRequest.ProtoReflect.Descriptor instead.+func (*ApplyToClipboardRequest) Descriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{11}+}++func (x *ApplyToClipboardRequest) GetClipId() string {+ if x != nil {+ return x.ClipId+ }+ return ""+}++type ListDevicesResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Self *Device `protobuf:"bytes,1,opt,name=self,proto3" json:"self,omitempty"`+ Peers []*Device `protobuf:"bytes,2,rep,name=peers,proto3" json:"peers,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ListDevicesResponse) Reset() {+ *x = ListDevicesResponse{}+ mi := &file_copysync_v1_daemon_proto_msgTypes[12]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ListDevicesResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ListDevicesResponse) ProtoMessage() {}++func (x *ListDevicesResponse) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_daemon_proto_msgTypes[12]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ListDevicesResponse.ProtoReflect.Descriptor instead.+func (*ListDevicesResponse) Descriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{12}+}++func (x *ListDevicesResponse) GetSelf() *Device {+ if x != nil {+ return x.Self+ }+ return nil+}++func (x *ListDevicesResponse) GetPeers() []*Device {+ if x != nil {+ return x.Peers+ }+ return nil+}++type CreatePairingCodeResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Code string `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"`+ ExpiresAtUnix int64 `protobuf:"varint,2,opt,name=expires_at_unix,json=expiresAtUnix,proto3" json:"expires_at_unix,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *CreatePairingCodeResponse) Reset() {+ *x = CreatePairingCodeResponse{}+ mi := &file_copysync_v1_daemon_proto_msgTypes[13]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *CreatePairingCodeResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*CreatePairingCodeResponse) ProtoMessage() {}++func (x *CreatePairingCodeResponse) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_daemon_proto_msgTypes[13]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use CreatePairingCodeResponse.ProtoReflect.Descriptor instead.+func (*CreatePairingCodeResponse) Descriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{13}+}++func (x *CreatePairingCodeResponse) GetCode() string {+ if x != nil {+ return x.Code+ }+ return ""+}++func (x *CreatePairingCodeResponse) GetExpiresAtUnix() int64 {+ if x != nil {+ return x.ExpiresAtUnix+ }+ return 0+}++type RedeemPairingCodeRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Code string `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *RedeemPairingCodeRequest) Reset() {+ *x = RedeemPairingCodeRequest{}+ mi := &file_copysync_v1_daemon_proto_msgTypes[14]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *RedeemPairingCodeRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*RedeemPairingCodeRequest) ProtoMessage() {}++func (x *RedeemPairingCodeRequest) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_daemon_proto_msgTypes[14]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use RedeemPairingCodeRequest.ProtoReflect.Descriptor instead.+func (*RedeemPairingCodeRequest) Descriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{14}+}++func (x *RedeemPairingCodeRequest) GetCode() string {+ if x != nil {+ return x.Code+ }+ return ""+}++type RedeemPairingCodeResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // 返回对端信息供用户肉眼核对指纹,确认后再调 ConfirmPairing+ Peer *Device `protobuf:"bytes,1,opt,name=peer,proto3" json:"peer,omitempty"`+ PairingSession string `protobuf:"bytes,2,opt,name=pairing_session,json=pairingSession,proto3" json:"pairing_session,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *RedeemPairingCodeResponse) Reset() {+ *x = RedeemPairingCodeResponse{}+ mi := &file_copysync_v1_daemon_proto_msgTypes[15]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *RedeemPairingCodeResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*RedeemPairingCodeResponse) ProtoMessage() {}++func (x *RedeemPairingCodeResponse) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_daemon_proto_msgTypes[15]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use RedeemPairingCodeResponse.ProtoReflect.Descriptor instead.+func (*RedeemPairingCodeResponse) Descriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{15}+}++func (x *RedeemPairingCodeResponse) GetPeer() *Device {+ if x != nil {+ return x.Peer+ }+ return nil+}++func (x *RedeemPairingCodeResponse) GetPairingSession() string {+ if x != nil {+ return x.PairingSession+ }+ return ""+}++type ConfirmPairingRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ PairingSession string `protobuf:"bytes,1,opt,name=pairing_session,json=pairingSession,proto3" json:"pairing_session,omitempty"`+ Accept bool `protobuf:"varint,2,opt,name=accept,proto3" json:"accept,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ConfirmPairingRequest) Reset() {+ *x = ConfirmPairingRequest{}+ mi := &file_copysync_v1_daemon_proto_msgTypes[16]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ConfirmPairingRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ConfirmPairingRequest) ProtoMessage() {}++func (x *ConfirmPairingRequest) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_daemon_proto_msgTypes[16]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ConfirmPairingRequest.ProtoReflect.Descriptor instead.+func (*ConfirmPairingRequest) Descriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{16}+}++func (x *ConfirmPairingRequest) GetPairingSession() string {+ if x != nil {+ return x.PairingSession+ }+ return ""+}++func (x *ConfirmPairingRequest) GetAccept() bool {+ if x != nil {+ return x.Accept+ }+ return false+}++type UnpairRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ DeviceId string `protobuf:"bytes,1,opt,name=device_id,json=deviceId,proto3" json:"device_id,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *UnpairRequest) Reset() {+ *x = UnpairRequest{}+ mi := &file_copysync_v1_daemon_proto_msgTypes[17]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *UnpairRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*UnpairRequest) ProtoMessage() {}++func (x *UnpairRequest) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_daemon_proto_msgTypes[17]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use UnpairRequest.ProtoReflect.Descriptor instead.+func (*UnpairRequest) Descriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{17}+}++func (x *UnpairRequest) GetDeviceId() string {+ if x != nil {+ return x.DeviceId+ }+ return ""+}++type Config struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // 小于此值自动预取,大于此值只同步元数据等用户手动拉取+ AutoSyncThresholdBytes int64 `protobuf:"varint,1,opt,name=auto_sync_threshold_bytes,json=autoSyncThresholdBytes,proto3" json:"auto_sync_threshold_bytes,omitempty"`+ HistoryTtlSeconds int64 `protobuf:"varint,2,opt,name=history_ttl_seconds,json=historyTtlSeconds,proto3" json:"history_ttl_seconds,omitempty"`+ CacheTtlSeconds int64 `protobuf:"varint,3,opt,name=cache_ttl_seconds,json=cacheTtlSeconds,proto3" json:"cache_ttl_seconds,omitempty"`+ SyncText bool `protobuf:"varint,4,opt,name=sync_text,json=syncText,proto3" json:"sync_text,omitempty"`+ SyncHtml bool `protobuf:"varint,5,opt,name=sync_html,json=syncHtml,proto3" json:"sync_html,omitempty"`+ SyncImage bool `protobuf:"varint,6,opt,name=sync_image,json=syncImage,proto3" json:"sync_image,omitempty"`+ SyncFile bool `protobuf:"varint,7,opt,name=sync_file,json=syncFile,proto3" json:"sync_file,omitempty"`+ // 收到对端内容后是否自动覆盖本机剪贴板+ AutoApplyToClipboard bool `protobuf:"varint,8,opt,name=auto_apply_to_clipboard,json=autoApplyToClipboard,proto3" json:"auto_apply_to_clipboard,omitempty"`+ LaunchAtLogin bool `protobuf:"varint,9,opt,name=launch_at_login,json=launchAtLogin,proto3" json:"launch_at_login,omitempty"`+ DeviceName string `protobuf:"bytes,10,opt,name=device_name,json=deviceName,proto3" json:"device_name,omitempty"`+ SignalingUrl string `protobuf:"bytes,11,opt,name=signaling_url,json=signalingUrl,proto3" json:"signaling_url,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *Config) Reset() {+ *x = Config{}+ mi := &file_copysync_v1_daemon_proto_msgTypes[18]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *Config) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*Config) ProtoMessage() {}++func (x *Config) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_daemon_proto_msgTypes[18]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use Config.ProtoReflect.Descriptor instead.+func (*Config) Descriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{18}+}++func (x *Config) GetAutoSyncThresholdBytes() int64 {+ if x != nil {+ return x.AutoSyncThresholdBytes+ }+ return 0+}++func (x *Config) GetHistoryTtlSeconds() int64 {+ if x != nil {+ return x.HistoryTtlSeconds+ }+ return 0+}++func (x *Config) GetCacheTtlSeconds() int64 {+ if x != nil {+ return x.CacheTtlSeconds+ }+ return 0+}++func (x *Config) GetSyncText() bool {+ if x != nil {+ return x.SyncText+ }+ return false+}++func (x *Config) GetSyncHtml() bool {+ if x != nil {+ return x.SyncHtml+ }+ return false+}++func (x *Config) GetSyncImage() bool {+ if x != nil {+ return x.SyncImage+ }+ return false+}++func (x *Config) GetSyncFile() bool {+ if x != nil {+ return x.SyncFile+ }+ return false+}++func (x *Config) GetAutoApplyToClipboard() bool {+ if x != nil {+ return x.AutoApplyToClipboard+ }+ return false+}++func (x *Config) GetLaunchAtLogin() bool {+ if x != nil {+ return x.LaunchAtLogin+ }+ return false+}++func (x *Config) GetDeviceName() string {+ if x != nil {+ return x.DeviceName+ }+ return ""+}++func (x *Config) GetSignalingUrl() string {+ if x != nil {+ return x.SignalingUrl+ }+ return ""+}++type Status struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ DeviceId string `protobuf:"bytes,1,opt,name=device_id,json=deviceId,proto3" json:"device_id,omitempty"`+ DeviceName string `protobuf:"bytes,2,opt,name=device_name,json=deviceName,proto3" json:"device_name,omitempty"`+ SignalingConnected bool `protobuf:"varint,3,opt,name=signaling_connected,json=signalingConnected,proto3" json:"signaling_connected,omitempty"`+ ClipboardPermission ClipboardPermission `protobuf:"varint,4,opt,name=clipboard_permission,json=clipboardPermission,proto3,enum=copysync.v1.ClipboardPermission" json:"clipboard_permission,omitempty"`+ CacheBytesUsed int64 `protobuf:"varint,5,opt,name=cache_bytes_used,json=cacheBytesUsed,proto3" json:"cache_bytes_used,omitempty"`+ PeersOnline int32 `protobuf:"varint,6,opt,name=peers_online,json=peersOnline,proto3" json:"peers_online,omitempty"`+ Version string `protobuf:"bytes,7,opt,name=version,proto3" json:"version,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *Status) Reset() {+ *x = Status{}+ mi := &file_copysync_v1_daemon_proto_msgTypes[19]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *Status) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*Status) ProtoMessage() {}++func (x *Status) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_daemon_proto_msgTypes[19]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use Status.ProtoReflect.Descriptor instead.+func (*Status) Descriptor() ([]byte, []int) {+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{19}+}++func (x *Status) GetDeviceId() string {+ if x != nil {+ return x.DeviceId+ }+ return ""+}++func (x *Status) GetDeviceName() string {+ if x != nil {+ return x.DeviceName+ }+ return ""+}++func (x *Status) GetSignalingConnected() bool {+ if x != nil {+ return x.SignalingConnected+ }+ return false+}++func (x *Status) GetClipboardPermission() ClipboardPermission {+ if x != nil {+ return x.ClipboardPermission+ }+ return ClipboardPermission_CLIPBOARD_PERMISSION_UNSPECIFIED+}++func (x *Status) GetCacheBytesUsed() int64 {+ if x != nil {+ return x.CacheBytesUsed+ }+ return 0+}++func (x *Status) GetPeersOnline() int32 {+ if x != nil {+ return x.PeersOnline+ }+ return 0+}++func (x *Status) GetVersion() string {+ if x != nil {+ return x.Version+ }+ return ""+}++var File_copysync_v1_daemon_proto protoreflect.FileDescriptor++const file_copysync_v1_daemon_proto_rawDesc = "" ++ "\n" ++ "\x18copysync/v1/daemon.proto\x12\vcopysync.v1\"\a\n" ++ "\x05Empty\"l\n" ++ "\bClipItem\x12\x12\n" ++ "\x04name\x18\x01 \x01(\tR\x04name\x12\x12\n" ++ "\x04size\x18\x02 \x01(\x03R\x04size\x12\x15\n" ++ "\x06is_dir\x18\x03 \x01(\bR\x05isDir\x12!\n" ++ "\fcontent_type\x18\x04 \x01(\tR\vcontentType\"\xc1\x03\n" ++ "\n" ++ "ClipRecord\x12\x0e\n" ++ "\x02id\x18\x01 \x01(\tR\x02id\x12)\n" ++ "\x04kind\x18\x02 \x01(\x0e2\x15.copysync.v1.ClipKindR\x04kind\x12/\n" ++ "\x06status\x18\x03 \x01(\x0e2\x17.copysync.v1.ClipStatusR\x06status\x12(\n" ++ "\x10origin_device_id\x18\x04 \x01(\tR\x0eoriginDeviceId\x12,\n" ++ "\x12origin_device_name\x18\x05 \x01(\tR\x10originDeviceName\x12\x1a\n" ++ "\boutgoing\x18\x06 \x01(\bR\boutgoing\x12+\n" ++ "\x05items\x18\a \x03(\v2\x15.copysync.v1.ClipItemR\x05items\x12\x1d\n" ++ "\n" ++ "total_size\x18\b \x01(\x03R\ttotalSize\x12!\n" ++ "\ftext_preview\x18\t \x01(\tR\vtextPreview\x12&\n" ++ "\x0fcreated_at_unix\x18\n" ++ " \x01(\x03R\rcreatedAtUnix\x12&\n" ++ "\x0fexpires_at_unix\x18\v \x01(\x03R\rexpiresAtUnix\x12\x14\n" ++ "\x05error\x18\f \x01(\tR\x05error\"1\n" ++ "\x10SubscribeRequest\x12\x1d\n" ++ "\n" ++ "since_unix\x18\x01 \x01(\x03R\tsinceUnix\"\x8d\x01\n" ++ "\x10TransferProgress\x12\x17\n" ++ "\aclip_id\x18\x01 \x01(\tR\x06clipId\x12 \n" ++ "\vtransferred\x18\x02 \x01(\x03R\vtransferred\x12\x14\n" ++ "\x05total\x18\x03 \x01(\x03R\x05total\x12(\n" ++ "\x10bytes_per_second\x18\x04 \x01(\x01R\x0ebytesPerSecond\"\xa2\x02\n" ++ "\x06Device\x12\x0e\n" ++ "\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" ++ "\x04name\x18\x02 \x01(\tR\x04name\x12\x1a\n" ++ "\bplatform\x18\x03 \x01(\tR\bplatform\x12\x16\n" ++ "\x06online\x18\x04 \x01(\bR\x06online\x12;\n" ++ "\n" ++ "connection\x18\x05 \x01(\x0e2\x1b.copysync.v1.ConnectionKindR\n" ++ "connection\x124\n" ++ "\x16public_key_fingerprint\x18\x06 \x01(\tR\x14publicKeyFingerprint\x12$\n" ++ "\x0epaired_at_unix\x18\a \x01(\x03R\fpairedAtUnix\x12'\n" ++ "\x0fpairing_session\x18\b \x01(\tR\x0epairingSession\"\xbb\x03\n" ++ "\x05Event\x128\n" ++ "\n" ++ "clip_added\x18\x01 \x01(\v2\x17.copysync.v1.ClipRecordH\x00R\tclipAdded\x12<\n" ++ "\fclip_updated\x18\x02 \x01(\v2\x17.copysync.v1.ClipRecordH\x00R\vclipUpdated\x12#\n" ++ "\fclip_removed\x18\x03 \x01(\tH\x00R\vclipRemoved\x12;\n" ++ "\bprogress\x18\x04 \x01(\v2\x1d.copysync.v1.TransferProgressH\x00R\bprogress\x12<\n" ++ "\x0edevice_changed\x18\x05 \x01(\v2\x13.copysync.v1.DeviceH\x00R\rdeviceChanged\x12Q\n" ++ "\x12permission_changed\x18\x06 \x01(\x0e2 .copysync.v1.ClipboardPermissionH\x00R\x11permissionChanged\x12<\n" ++ "\x0estatus_changed\x18\a \x01(\v2\x13.copysync.v1.StatusH\x00R\rstatusChangedB\t\n" ++ "\apayload\"\x83\x01\n" ++ "\x12ListHistoryRequest\x12\x14\n" ++ "\x05limit\x18\x01 \x01(\x05R\x05limit\x12\x1f\n" ++ "\vbefore_unix\x18\x02 \x01(\x03R\n" ++ "beforeUnix\x126\n" ++ "\vkind_filter\x18\x03 \x01(\x0e2\x15.copysync.v1.ClipKindR\n" ++ "kindFilter\"H\n" ++ "\x13ListHistoryResponse\x121\n" ++ "\arecords\x18\x01 \x03(\v2\x17.copysync.v1.ClipRecordR\arecords\":\n" ++ "\x14DeleteHistoryRequest\x12\x10\n" ++ "\x03ids\x18\x01 \x03(\tR\x03ids\x12\x10\n" ++ "\x03all\x18\x02 \x01(\bR\x03all\"'\n" ++ "\fFetchRequest\x12\x17\n" ++ "\aclip_id\x18\x01 \x01(\tR\x06clipId\"2\n" ++ "\x17ApplyToClipboardRequest\x12\x17\n" ++ "\aclip_id\x18\x01 \x01(\tR\x06clipId\"i\n" ++ "\x13ListDevicesResponse\x12'\n" ++ "\x04self\x18\x01 \x01(\v2\x13.copysync.v1.DeviceR\x04self\x12)\n" ++ "\x05peers\x18\x02 \x03(\v2\x13.copysync.v1.DeviceR\x05peers\"W\n" ++ "\x19CreatePairingCodeResponse\x12\x12\n" ++ "\x04code\x18\x01 \x01(\tR\x04code\x12&\n" ++ "\x0fexpires_at_unix\x18\x02 \x01(\x03R\rexpiresAtUnix\".\n" ++ "\x18RedeemPairingCodeRequest\x12\x12\n" ++ "\x04code\x18\x01 \x01(\tR\x04code\"m\n" ++ "\x19RedeemPairingCodeResponse\x12'\n" ++ "\x04peer\x18\x01 \x01(\v2\x13.copysync.v1.DeviceR\x04peer\x12'\n" ++ "\x0fpairing_session\x18\x02 \x01(\tR\x0epairingSession\"X\n" ++ "\x15ConfirmPairingRequest\x12'\n" ++ "\x0fpairing_session\x18\x01 \x01(\tR\x0epairingSession\x12\x16\n" ++ "\x06accept\x18\x02 \x01(\bR\x06accept\",\n" ++ "\rUnpairRequest\x12\x1b\n" ++ "\tdevice_id\x18\x01 \x01(\tR\bdeviceId\"\xba\x03\n" ++ "\x06Config\x129\n" ++ "\x19auto_sync_threshold_bytes\x18\x01 \x01(\x03R\x16autoSyncThresholdBytes\x12.\n" ++ "\x13history_ttl_seconds\x18\x02 \x01(\x03R\x11historyTtlSeconds\x12*\n" ++ "\x11cache_ttl_seconds\x18\x03 \x01(\x03R\x0fcacheTtlSeconds\x12\x1b\n" ++ "\tsync_text\x18\x04 \x01(\bR\bsyncText\x12\x1b\n" ++ "\tsync_html\x18\x05 \x01(\bR\bsyncHtml\x12\x1d\n" ++ "\n" ++ "sync_image\x18\x06 \x01(\bR\tsyncImage\x12\x1b\n" ++ "\tsync_file\x18\a \x01(\bR\bsyncFile\x125\n" ++ "\x17auto_apply_to_clipboard\x18\b \x01(\bR\x14autoApplyToClipboard\x12&\n" ++ "\x0flaunch_at_login\x18\t \x01(\bR\rlaunchAtLogin\x12\x1f\n" ++ "\vdevice_name\x18\n" ++ " \x01(\tR\n" ++ "deviceName\x12#\n" ++ "\rsignaling_url\x18\v \x01(\tR\fsignalingUrl\"\xb3\x02\n" ++ "\x06Status\x12\x1b\n" ++ "\tdevice_id\x18\x01 \x01(\tR\bdeviceId\x12\x1f\n" ++ "\vdevice_name\x18\x02 \x01(\tR\n" ++ "deviceName\x12/\n" ++ "\x13signaling_connected\x18\x03 \x01(\bR\x12signalingConnected\x12S\n" ++ "\x14clipboard_permission\x18\x04 \x01(\x0e2 .copysync.v1.ClipboardPermissionR\x13clipboardPermission\x12(\n" ++ "\x10cache_bytes_used\x18\x05 \x01(\x03R\x0ecacheBytesUsed\x12!\n" ++ "\fpeers_online\x18\x06 \x01(\x05R\vpeersOnline\x12\x18\n" ++ "\aversion\x18\a \x01(\tR\aversion*v\n" ++ "\bClipKind\x12\x19\n" ++ "\x15CLIP_KIND_UNSPECIFIED\x10\x00\x12\x12\n" ++ "\x0eCLIP_KIND_TEXT\x10\x01\x12\x12\n" ++ "\x0eCLIP_KIND_HTML\x10\x02\x12\x13\n" ++ "\x0fCLIP_KIND_IMAGE\x10\x03\x12\x12\n" ++ "\x0eCLIP_KIND_FILE\x10\x04*\xa8\x01\n" ++ "\n" ++ "ClipStatus\x12\x1b\n" ++ "\x17CLIP_STATUS_UNSPECIFIED\x10\x00\x12\x15\n" ++ "\x11CLIP_STATUS_READY\x10\x01\x12\x1b\n" ++ "\x17CLIP_STATUS_REMOTE_ONLY\x10\x02\x12\x18\n" ++ "\x14CLIP_STATUS_FETCHING\x10\x03\x12\x16\n" ++ "\x12CLIP_STATUS_FAILED\x10\x04\x12\x17\n" ++ "\x13CLIP_STATUS_EXPIRED\x10\x05*\x85\x01\n" ++ "\x0eConnectionKind\x12\x1f\n" ++ "\x1bCONNECTION_KIND_UNSPECIFIED\x10\x00\x12\x1b\n" ++ "\x17CONNECTION_KIND_OFFLINE\x10\x01\x12\x1a\n" ++ "\x16CONNECTION_KIND_DIRECT\x10\x02\x12\x19\n" ++ "\x15CONNECTION_KIND_RELAY\x10\x03*\xf1\x01\n" ++ "\x13ClipboardPermission\x12$\n" ++ " CLIPBOARD_PERMISSION_UNSPECIFIED\x10\x00\x12'\n" ++ "#CLIPBOARD_PERMISSION_NOT_APPLICABLE\x10\x01\x12 \n" ++ "\x1cCLIPBOARD_PERMISSION_DEFAULT\x10\x02\x12\x1c\n" ++ "\x18CLIPBOARD_PERMISSION_ASK\x10\x03\x12%\n" ++ "!CLIPBOARD_PERMISSION_ALWAYS_ALLOW\x10\x04\x12$\n" ++ " CLIPBOARD_PERMISSION_ALWAYS_DENY\x10\x052\xdb\a\n" ++ "\rDaemonService\x12@\n" ++ "\tSubscribe\x12\x1d.copysync.v1.SubscribeRequest\x1a\x12.copysync.v1.Event0\x01\x12P\n" ++ "\vListHistory\x12\x1f.copysync.v1.ListHistoryRequest\x1a .copysync.v1.ListHistoryResponse\x12F\n" ++ "\rDeleteHistory\x12!.copysync.v1.DeleteHistoryRequest\x1a\x12.copysync.v1.Empty\x126\n" ++ "\x05Fetch\x12\x19.copysync.v1.FetchRequest\x1a\x12.copysync.v1.Empty\x12L\n" ++ "\x10ApplyToClipboard\x12$.copysync.v1.ApplyToClipboardRequest\x1a\x12.copysync.v1.Empty\x12C\n" ++ "\vListDevices\x12\x12.copysync.v1.Empty\x1a .copysync.v1.ListDevicesResponse\x12O\n" ++ "\x11CreatePairingCode\x12\x12.copysync.v1.Empty\x1a&.copysync.v1.CreatePairingCodeResponse\x12b\n" ++ "\x11RedeemPairingCode\x12%.copysync.v1.RedeemPairingCodeRequest\x1a&.copysync.v1.RedeemPairingCodeResponse\x12H\n" ++ "\x0eConfirmPairing\x12\".copysync.v1.ConfirmPairingRequest\x1a\x12.copysync.v1.Empty\x128\n" ++ "\x06Unpair\x12\x1a.copysync.v1.UnpairRequest\x1a\x12.copysync.v1.Empty\x124\n" ++ "\tGetConfig\x12\x12.copysync.v1.Empty\x1a\x13.copysync.v1.Config\x128\n" ++ "\fUpdateConfig\x12\x13.copysync.v1.Config\x1a\x13.copysync.v1.Config\x124\n" ++ "\tGetStatus\x12\x12.copysync.v1.Empty\x1a\x13.copysync.v1.Status\x12D\n" ++ "\x1aRequestClipboardPermission\x12\x12.copysync.v1.Empty\x1a\x12.copysync.v1.EmptyB>Z<github.com/baiyuze/copysync/proto/gen/copysync/v1;copysyncv1b\x06proto3"++var (+ file_copysync_v1_daemon_proto_rawDescOnce sync.Once+ file_copysync_v1_daemon_proto_rawDescData []byte+)++func file_copysync_v1_daemon_proto_rawDescGZIP() []byte {+ file_copysync_v1_daemon_proto_rawDescOnce.Do(func() {+ file_copysync_v1_daemon_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_copysync_v1_daemon_proto_rawDesc), len(file_copysync_v1_daemon_proto_rawDesc)))+ })+ return file_copysync_v1_daemon_proto_rawDescData+}++var file_copysync_v1_daemon_proto_enumTypes = make([]protoimpl.EnumInfo, 4)+var file_copysync_v1_daemon_proto_msgTypes = make([]protoimpl.MessageInfo, 20)+var file_copysync_v1_daemon_proto_goTypes = []any{+ (ClipKind)(0), // 0: copysync.v1.ClipKind+ (ClipStatus)(0), // 1: copysync.v1.ClipStatus+ (ConnectionKind)(0), // 2: copysync.v1.ConnectionKind+ (ClipboardPermission)(0), // 3: copysync.v1.ClipboardPermission+ (*Empty)(nil), // 4: copysync.v1.Empty+ (*ClipItem)(nil), // 5: copysync.v1.ClipItem+ (*ClipRecord)(nil), // 6: copysync.v1.ClipRecord+ (*SubscribeRequest)(nil), // 7: copysync.v1.SubscribeRequest+ (*TransferProgress)(nil), // 8: copysync.v1.TransferProgress+ (*Device)(nil), // 9: copysync.v1.Device+ (*Event)(nil), // 10: copysync.v1.Event+ (*ListHistoryRequest)(nil), // 11: copysync.v1.ListHistoryRequest+ (*ListHistoryResponse)(nil), // 12: copysync.v1.ListHistoryResponse+ (*DeleteHistoryRequest)(nil), // 13: copysync.v1.DeleteHistoryRequest+ (*FetchRequest)(nil), // 14: copysync.v1.FetchRequest+ (*ApplyToClipboardRequest)(nil), // 15: copysync.v1.ApplyToClipboardRequest+ (*ListDevicesResponse)(nil), // 16: copysync.v1.ListDevicesResponse+ (*CreatePairingCodeResponse)(nil), // 17: copysync.v1.CreatePairingCodeResponse+ (*RedeemPairingCodeRequest)(nil), // 18: copysync.v1.RedeemPairingCodeRequest+ (*RedeemPairingCodeResponse)(nil), // 19: copysync.v1.RedeemPairingCodeResponse+ (*ConfirmPairingRequest)(nil), // 20: copysync.v1.ConfirmPairingRequest+ (*UnpairRequest)(nil), // 21: copysync.v1.UnpairRequest+ (*Config)(nil), // 22: copysync.v1.Config+ (*Status)(nil), // 23: copysync.v1.Status+}+var file_copysync_v1_daemon_proto_depIdxs = []int32{+ 0, // 0: copysync.v1.ClipRecord.kind:type_name -> copysync.v1.ClipKind+ 1, // 1: copysync.v1.ClipRecord.status:type_name -> copysync.v1.ClipStatus+ 5, // 2: copysync.v1.ClipRecord.items:type_name -> copysync.v1.ClipItem+ 2, // 3: copysync.v1.Device.connection:type_name -> copysync.v1.ConnectionKind+ 6, // 4: copysync.v1.Event.clip_added:type_name -> copysync.v1.ClipRecord+ 6, // 5: copysync.v1.Event.clip_updated:type_name -> copysync.v1.ClipRecord+ 8, // 6: copysync.v1.Event.progress:type_name -> copysync.v1.TransferProgress+ 9, // 7: copysync.v1.Event.device_changed:type_name -> copysync.v1.Device+ 3, // 8: copysync.v1.Event.permission_changed:type_name -> copysync.v1.ClipboardPermission+ 23, // 9: copysync.v1.Event.status_changed:type_name -> copysync.v1.Status+ 0, // 10: copysync.v1.ListHistoryRequest.kind_filter:type_name -> copysync.v1.ClipKind+ 6, // 11: copysync.v1.ListHistoryResponse.records:type_name -> copysync.v1.ClipRecord+ 9, // 12: copysync.v1.ListDevicesResponse.self:type_name -> copysync.v1.Device+ 9, // 13: copysync.v1.ListDevicesResponse.peers:type_name -> copysync.v1.Device+ 9, // 14: copysync.v1.RedeemPairingCodeResponse.peer:type_name -> copysync.v1.Device+ 3, // 15: copysync.v1.Status.clipboard_permission:type_name -> copysync.v1.ClipboardPermission+ 7, // 16: copysync.v1.DaemonService.Subscribe:input_type -> copysync.v1.SubscribeRequest+ 11, // 17: copysync.v1.DaemonService.ListHistory:input_type -> copysync.v1.ListHistoryRequest+ 13, // 18: copysync.v1.DaemonService.DeleteHistory:input_type -> copysync.v1.DeleteHistoryRequest+ 14, // 19: copysync.v1.DaemonService.Fetch:input_type -> copysync.v1.FetchRequest+ 15, // 20: copysync.v1.DaemonService.ApplyToClipboard:input_type -> copysync.v1.ApplyToClipboardRequest+ 4, // 21: copysync.v1.DaemonService.ListDevices:input_type -> copysync.v1.Empty+ 4, // 22: copysync.v1.DaemonService.CreatePairingCode:input_type -> copysync.v1.Empty+ 18, // 23: copysync.v1.DaemonService.RedeemPairingCode:input_type -> copysync.v1.RedeemPairingCodeRequest+ 20, // 24: copysync.v1.DaemonService.ConfirmPairing:input_type -> copysync.v1.ConfirmPairingRequest+ 21, // 25: copysync.v1.DaemonService.Unpair:input_type -> copysync.v1.UnpairRequest+ 4, // 26: copysync.v1.DaemonService.GetConfig:input_type -> copysync.v1.Empty+ 22, // 27: copysync.v1.DaemonService.UpdateConfig:input_type -> copysync.v1.Config+ 4, // 28: copysync.v1.DaemonService.GetStatus:input_type -> copysync.v1.Empty+ 4, // 29: copysync.v1.DaemonService.RequestClipboardPermission:input_type -> copysync.v1.Empty+ 10, // 30: copysync.v1.DaemonService.Subscribe:output_type -> copysync.v1.Event+ 12, // 31: copysync.v1.DaemonService.ListHistory:output_type -> copysync.v1.ListHistoryResponse+ 4, // 32: copysync.v1.DaemonService.DeleteHistory:output_type -> copysync.v1.Empty+ 4, // 33: copysync.v1.DaemonService.Fetch:output_type -> copysync.v1.Empty+ 4, // 34: copysync.v1.DaemonService.ApplyToClipboard:output_type -> copysync.v1.Empty+ 16, // 35: copysync.v1.DaemonService.ListDevices:output_type -> copysync.v1.ListDevicesResponse+ 17, // 36: copysync.v1.DaemonService.CreatePairingCode:output_type -> copysync.v1.CreatePairingCodeResponse+ 19, // 37: copysync.v1.DaemonService.RedeemPairingCode:output_type -> copysync.v1.RedeemPairingCodeResponse+ 4, // 38: copysync.v1.DaemonService.ConfirmPairing:output_type -> copysync.v1.Empty+ 4, // 39: copysync.v1.DaemonService.Unpair:output_type -> copysync.v1.Empty+ 22, // 40: copysync.v1.DaemonService.GetConfig:output_type -> copysync.v1.Config+ 22, // 41: copysync.v1.DaemonService.UpdateConfig:output_type -> copysync.v1.Config+ 23, // 42: copysync.v1.DaemonService.GetStatus:output_type -> copysync.v1.Status+ 4, // 43: copysync.v1.DaemonService.RequestClipboardPermission:output_type -> copysync.v1.Empty+ 30, // [30:44] is the sub-list for method output_type+ 16, // [16:30] is the sub-list for method input_type+ 16, // [16:16] is the sub-list for extension type_name+ 16, // [16:16] is the sub-list for extension extendee+ 0, // [0:16] is the sub-list for field type_name+}++func init() { file_copysync_v1_daemon_proto_init() }+func file_copysync_v1_daemon_proto_init() {+ if File_copysync_v1_daemon_proto != nil {+ return+ }+ file_copysync_v1_daemon_proto_msgTypes[6].OneofWrappers = []any{+ (*Event_ClipAdded)(nil),+ (*Event_ClipUpdated)(nil),+ (*Event_ClipRemoved)(nil),+ (*Event_Progress)(nil),+ (*Event_DeviceChanged)(nil),+ (*Event_PermissionChanged)(nil),+ (*Event_StatusChanged)(nil),+ }+ type x struct{}+ out := protoimpl.TypeBuilder{+ File: protoimpl.DescBuilder{+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),+ RawDescriptor: unsafe.Slice(unsafe.StringData(file_copysync_v1_daemon_proto_rawDesc), len(file_copysync_v1_daemon_proto_rawDesc)),+ NumEnums: 4,+ NumMessages: 20,+ NumExtensions: 0,+ NumServices: 1,+ },+ GoTypes: file_copysync_v1_daemon_proto_goTypes,+ DependencyIndexes: file_copysync_v1_daemon_proto_depIdxs,+ EnumInfos: file_copysync_v1_daemon_proto_enumTypes,+ MessageInfos: file_copysync_v1_daemon_proto_msgTypes,+ }.Build()+ File_copysync_v1_daemon_proto = out.File+ file_copysync_v1_daemon_proto_goTypes = nil+ file_copysync_v1_daemon_proto_depIdxs = nil+}diff --git a/proto/gen/copysync/v1/daemon_grpc.pb.go b/proto/gen/copysync/v1/daemon_grpc.pb.gonew file mode 100644index 0000000..5bf8abe--- /dev/null+++ b/proto/gen/copysync/v1/daemon_grpc.pb.go@@ -0,0 +1,634 @@+// Flutter UI ↔ Go daemon 之间的接口。+//+// daemon 是常驻后台的核心进程,UI 只是控制台——关掉 UI 不影响同步。+// 事件走 server-streaming 主动推送,避免 UI 轮询。++// Code generated by protoc-gen-go-grpc. DO NOT EDIT.+// versions:+// - protoc-gen-go-grpc v1.6.2+// - protoc (unknown)+// source: copysync/v1/daemon.proto++package copysyncv1++import (+ context "context"+ grpc "google.golang.org/grpc"+ codes "google.golang.org/grpc/codes"+ status "google.golang.org/grpc/status"+)++// This is a compile-time assertion to ensure that this generated file+// is compatible with the grpc package it is being compiled against.+// Requires gRPC-Go v1.64.0 or later.+const _ = grpc.SupportPackageIsVersion9++const (+ DaemonService_Subscribe_FullMethodName = "/copysync.v1.DaemonService/Subscribe"+ DaemonService_ListHistory_FullMethodName = "/copysync.v1.DaemonService/ListHistory"+ DaemonService_DeleteHistory_FullMethodName = "/copysync.v1.DaemonService/DeleteHistory"+ DaemonService_Fetch_FullMethodName = "/copysync.v1.DaemonService/Fetch"+ DaemonService_ApplyToClipboard_FullMethodName = "/copysync.v1.DaemonService/ApplyToClipboard"+ DaemonService_ListDevices_FullMethodName = "/copysync.v1.DaemonService/ListDevices"+ DaemonService_CreatePairingCode_FullMethodName = "/copysync.v1.DaemonService/CreatePairingCode"+ DaemonService_RedeemPairingCode_FullMethodName = "/copysync.v1.DaemonService/RedeemPairingCode"+ DaemonService_ConfirmPairing_FullMethodName = "/copysync.v1.DaemonService/ConfirmPairing"+ DaemonService_Unpair_FullMethodName = "/copysync.v1.DaemonService/Unpair"+ DaemonService_GetConfig_FullMethodName = "/copysync.v1.DaemonService/GetConfig"+ DaemonService_UpdateConfig_FullMethodName = "/copysync.v1.DaemonService/UpdateConfig"+ DaemonService_GetStatus_FullMethodName = "/copysync.v1.DaemonService/GetStatus"+ DaemonService_RequestClipboardPermission_FullMethodName = "/copysync.v1.DaemonService/RequestClipboardPermission"+)++// DaemonServiceClient is the client API for DaemonService service.+//+// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.+type DaemonServiceClient interface {+ // 订阅事件流。UI 启动后第一件事,断线需重连。+ Subscribe(ctx context.Context, in *SubscribeRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[Event], error)+ ListHistory(ctx context.Context, in *ListHistoryRequest, opts ...grpc.CallOption) (*ListHistoryResponse, error)+ DeleteHistory(ctx context.Context, in *DeleteHistoryRequest, opts ...grpc.CallOption) (*Empty, error)+ // 拉取仅有元数据的大文件记录。立即返回,进度走事件流。+ Fetch(ctx context.Context, in *FetchRequest, opts ...grpc.CallOption) (*Empty, error)+ // 把某条已就绪的记录重新放进本机剪贴板+ ApplyToClipboard(ctx context.Context, in *ApplyToClipboardRequest, opts ...grpc.CallOption) (*Empty, error)+ ListDevices(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*ListDevicesResponse, error)+ CreatePairingCode(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*CreatePairingCodeResponse, error)+ RedeemPairingCode(ctx context.Context, in *RedeemPairingCodeRequest, opts ...grpc.CallOption) (*RedeemPairingCodeResponse, error)+ // 配对双方各自确认指纹后才真正互信+ ConfirmPairing(ctx context.Context, in *ConfirmPairingRequest, opts ...grpc.CallOption) (*Empty, error)+ Unpair(ctx context.Context, in *UnpairRequest, opts ...grpc.CallOption) (*Empty, error)+ GetConfig(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Config, error)+ UpdateConfig(ctx context.Context, in *Config, opts ...grpc.CallOption) (*Config, error)+ GetStatus(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Status, error)+ // 引导用户授予剪贴板权限(打开系统设置面板)+ RequestClipboardPermission(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error)+}++type daemonServiceClient struct {+ cc grpc.ClientConnInterface+}++func NewDaemonServiceClient(cc grpc.ClientConnInterface) DaemonServiceClient {+ return &daemonServiceClient{cc}+}++func (c *daemonServiceClient) Subscribe(ctx context.Context, in *SubscribeRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[Event], error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ stream, err := c.cc.NewStream(ctx, &DaemonService_ServiceDesc.Streams[0], DaemonService_Subscribe_FullMethodName, cOpts...)+ if err != nil {+ return nil, err+ }+ x := &grpc.GenericClientStream[SubscribeRequest, Event]{ClientStream: stream}+ if err := x.ClientStream.SendMsg(in); err != nil {+ return nil, err+ }+ if err := x.ClientStream.CloseSend(); err != nil {+ return nil, err+ }+ return x, nil+}++// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.+type DaemonService_SubscribeClient = grpc.ServerStreamingClient[Event]++func (c *daemonServiceClient) ListHistory(ctx context.Context, in *ListHistoryRequest, opts ...grpc.CallOption) (*ListHistoryResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(ListHistoryResponse)+ err := c.cc.Invoke(ctx, DaemonService_ListHistory_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *daemonServiceClient) DeleteHistory(ctx context.Context, in *DeleteHistoryRequest, opts ...grpc.CallOption) (*Empty, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(Empty)+ err := c.cc.Invoke(ctx, DaemonService_DeleteHistory_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *daemonServiceClient) Fetch(ctx context.Context, in *FetchRequest, opts ...grpc.CallOption) (*Empty, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(Empty)+ err := c.cc.Invoke(ctx, DaemonService_Fetch_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *daemonServiceClient) ApplyToClipboard(ctx context.Context, in *ApplyToClipboardRequest, opts ...grpc.CallOption) (*Empty, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(Empty)+ err := c.cc.Invoke(ctx, DaemonService_ApplyToClipboard_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *daemonServiceClient) ListDevices(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*ListDevicesResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(ListDevicesResponse)+ err := c.cc.Invoke(ctx, DaemonService_ListDevices_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *daemonServiceClient) CreatePairingCode(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*CreatePairingCodeResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(CreatePairingCodeResponse)+ err := c.cc.Invoke(ctx, DaemonService_CreatePairingCode_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *daemonServiceClient) RedeemPairingCode(ctx context.Context, in *RedeemPairingCodeRequest, opts ...grpc.CallOption) (*RedeemPairingCodeResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(RedeemPairingCodeResponse)+ err := c.cc.Invoke(ctx, DaemonService_RedeemPairingCode_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *daemonServiceClient) ConfirmPairing(ctx context.Context, in *ConfirmPairingRequest, opts ...grpc.CallOption) (*Empty, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(Empty)+ err := c.cc.Invoke(ctx, DaemonService_ConfirmPairing_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *daemonServiceClient) Unpair(ctx context.Context, in *UnpairRequest, opts ...grpc.CallOption) (*Empty, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(Empty)+ err := c.cc.Invoke(ctx, DaemonService_Unpair_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *daemonServiceClient) GetConfig(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Config, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(Config)+ err := c.cc.Invoke(ctx, DaemonService_GetConfig_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *daemonServiceClient) UpdateConfig(ctx context.Context, in *Config, opts ...grpc.CallOption) (*Config, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(Config)+ err := c.cc.Invoke(ctx, DaemonService_UpdateConfig_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *daemonServiceClient) GetStatus(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Status, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(Status)+ err := c.cc.Invoke(ctx, DaemonService_GetStatus_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *daemonServiceClient) RequestClipboardPermission(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(Empty)+ err := c.cc.Invoke(ctx, DaemonService_RequestClipboardPermission_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++// DaemonServiceServer is the server API for DaemonService service.+// All implementations must embed UnimplementedDaemonServiceServer+// for forward compatibility.+type DaemonServiceServer interface {+ // 订阅事件流。UI 启动后第一件事,断线需重连。+ Subscribe(*SubscribeRequest, grpc.ServerStreamingServer[Event]) error+ ListHistory(context.Context, *ListHistoryRequest) (*ListHistoryResponse, error)+ DeleteHistory(context.Context, *DeleteHistoryRequest) (*Empty, error)+ // 拉取仅有元数据的大文件记录。立即返回,进度走事件流。+ Fetch(context.Context, *FetchRequest) (*Empty, error)+ // 把某条已就绪的记录重新放进本机剪贴板+ ApplyToClipboard(context.Context, *ApplyToClipboardRequest) (*Empty, error)+ ListDevices(context.Context, *Empty) (*ListDevicesResponse, error)+ CreatePairingCode(context.Context, *Empty) (*CreatePairingCodeResponse, error)+ RedeemPairingCode(context.Context, *RedeemPairingCodeRequest) (*RedeemPairingCodeResponse, error)+ // 配对双方各自确认指纹后才真正互信+ ConfirmPairing(context.Context, *ConfirmPairingRequest) (*Empty, error)+ Unpair(context.Context, *UnpairRequest) (*Empty, error)+ GetConfig(context.Context, *Empty) (*Config, error)+ UpdateConfig(context.Context, *Config) (*Config, error)+ GetStatus(context.Context, *Empty) (*Status, error)+ // 引导用户授予剪贴板权限(打开系统设置面板)+ RequestClipboardPermission(context.Context, *Empty) (*Empty, error)+ mustEmbedUnimplementedDaemonServiceServer()+}++// UnimplementedDaemonServiceServer must be embedded to have+// forward compatible implementations.+//+// NOTE: this should be embedded by value instead of pointer to avoid a nil+// pointer dereference when methods are called.+type UnimplementedDaemonServiceServer struct{}++func (UnimplementedDaemonServiceServer) Subscribe(*SubscribeRequest, grpc.ServerStreamingServer[Event]) error {+ return status.Error(codes.Unimplemented, "method Subscribe not implemented")+}+func (UnimplementedDaemonServiceServer) ListHistory(context.Context, *ListHistoryRequest) (*ListHistoryResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method ListHistory not implemented")+}+func (UnimplementedDaemonServiceServer) DeleteHistory(context.Context, *DeleteHistoryRequest) (*Empty, error) {+ return nil, status.Error(codes.Unimplemented, "method DeleteHistory not implemented")+}+func (UnimplementedDaemonServiceServer) Fetch(context.Context, *FetchRequest) (*Empty, error) {+ return nil, status.Error(codes.Unimplemented, "method Fetch not implemented")+}+func (UnimplementedDaemonServiceServer) ApplyToClipboard(context.Context, *ApplyToClipboardRequest) (*Empty, error) {+ return nil, status.Error(codes.Unimplemented, "method ApplyToClipboard not implemented")+}+func (UnimplementedDaemonServiceServer) ListDevices(context.Context, *Empty) (*ListDevicesResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method ListDevices not implemented")+}+func (UnimplementedDaemonServiceServer) CreatePairingCode(context.Context, *Empty) (*CreatePairingCodeResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method CreatePairingCode not implemented")+}+func (UnimplementedDaemonServiceServer) RedeemPairingCode(context.Context, *RedeemPairingCodeRequest) (*RedeemPairingCodeResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method RedeemPairingCode not implemented")+}+func (UnimplementedDaemonServiceServer) ConfirmPairing(context.Context, *ConfirmPairingRequest) (*Empty, error) {+ return nil, status.Error(codes.Unimplemented, "method ConfirmPairing not implemented")+}+func (UnimplementedDaemonServiceServer) Unpair(context.Context, *UnpairRequest) (*Empty, error) {+ return nil, status.Error(codes.Unimplemented, "method Unpair not implemented")+}+func (UnimplementedDaemonServiceServer) GetConfig(context.Context, *Empty) (*Config, error) {+ return nil, status.Error(codes.Unimplemented, "method GetConfig not implemented")+}+func (UnimplementedDaemonServiceServer) UpdateConfig(context.Context, *Config) (*Config, error) {+ return nil, status.Error(codes.Unimplemented, "method UpdateConfig not implemented")+}+func (UnimplementedDaemonServiceServer) GetStatus(context.Context, *Empty) (*Status, error) {+ return nil, status.Error(codes.Unimplemented, "method GetStatus not implemented")+}+func (UnimplementedDaemonServiceServer) RequestClipboardPermission(context.Context, *Empty) (*Empty, error) {+ return nil, status.Error(codes.Unimplemented, "method RequestClipboardPermission not implemented")+}+func (UnimplementedDaemonServiceServer) mustEmbedUnimplementedDaemonServiceServer() {}+func (UnimplementedDaemonServiceServer) testEmbeddedByValue() {}++// UnsafeDaemonServiceServer may be embedded to opt out of forward compatibility for this service.+// Use of this interface is not recommended, as added methods to DaemonServiceServer will+// result in compilation errors.+type UnsafeDaemonServiceServer interface {+ mustEmbedUnimplementedDaemonServiceServer()+}++func RegisterDaemonServiceServer(s grpc.ServiceRegistrar, srv DaemonServiceServer) {+ // If the following call panics, it indicates UnimplementedDaemonServiceServer was+ // embedded by pointer and is nil. This will cause panics if an+ // unimplemented method is ever invoked, so we test this at initialization+ // time to prevent it from happening at runtime later due to I/O.+ if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {+ t.testEmbeddedByValue()+ }+ s.RegisterService(&DaemonService_ServiceDesc, srv)+}++func _DaemonService_Subscribe_Handler(srv interface{}, stream grpc.ServerStream) error {+ m := new(SubscribeRequest)+ if err := stream.RecvMsg(m); err != nil {+ return err+ }+ return srv.(DaemonServiceServer).Subscribe(m, &grpc.GenericServerStream[SubscribeRequest, Event]{ServerStream: stream})+}++// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.+type DaemonService_SubscribeServer = grpc.ServerStreamingServer[Event]++func _DaemonService_ListHistory_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(ListHistoryRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(DaemonServiceServer).ListHistory(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: DaemonService_ListHistory_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(DaemonServiceServer).ListHistory(ctx, req.(*ListHistoryRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _DaemonService_DeleteHistory_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(DeleteHistoryRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(DaemonServiceServer).DeleteHistory(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: DaemonService_DeleteHistory_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(DaemonServiceServer).DeleteHistory(ctx, req.(*DeleteHistoryRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _DaemonService_Fetch_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(FetchRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(DaemonServiceServer).Fetch(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: DaemonService_Fetch_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(DaemonServiceServer).Fetch(ctx, req.(*FetchRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _DaemonService_ApplyToClipboard_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(ApplyToClipboardRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(DaemonServiceServer).ApplyToClipboard(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: DaemonService_ApplyToClipboard_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(DaemonServiceServer).ApplyToClipboard(ctx, req.(*ApplyToClipboardRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _DaemonService_ListDevices_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(Empty)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(DaemonServiceServer).ListDevices(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: DaemonService_ListDevices_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(DaemonServiceServer).ListDevices(ctx, req.(*Empty))+ }+ return interceptor(ctx, in, info, handler)+}++func _DaemonService_CreatePairingCode_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(Empty)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(DaemonServiceServer).CreatePairingCode(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: DaemonService_CreatePairingCode_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(DaemonServiceServer).CreatePairingCode(ctx, req.(*Empty))+ }+ return interceptor(ctx, in, info, handler)+}++func _DaemonService_RedeemPairingCode_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(RedeemPairingCodeRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(DaemonServiceServer).RedeemPairingCode(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: DaemonService_RedeemPairingCode_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(DaemonServiceServer).RedeemPairingCode(ctx, req.(*RedeemPairingCodeRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _DaemonService_ConfirmPairing_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(ConfirmPairingRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(DaemonServiceServer).ConfirmPairing(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: DaemonService_ConfirmPairing_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(DaemonServiceServer).ConfirmPairing(ctx, req.(*ConfirmPairingRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _DaemonService_Unpair_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(UnpairRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(DaemonServiceServer).Unpair(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: DaemonService_Unpair_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(DaemonServiceServer).Unpair(ctx, req.(*UnpairRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _DaemonService_GetConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(Empty)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(DaemonServiceServer).GetConfig(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: DaemonService_GetConfig_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(DaemonServiceServer).GetConfig(ctx, req.(*Empty))+ }+ return interceptor(ctx, in, info, handler)+}++func _DaemonService_UpdateConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(Config)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(DaemonServiceServer).UpdateConfig(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: DaemonService_UpdateConfig_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(DaemonServiceServer).UpdateConfig(ctx, req.(*Config))+ }+ return interceptor(ctx, in, info, handler)+}++func _DaemonService_GetStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(Empty)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(DaemonServiceServer).GetStatus(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: DaemonService_GetStatus_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(DaemonServiceServer).GetStatus(ctx, req.(*Empty))+ }+ return interceptor(ctx, in, info, handler)+}++func _DaemonService_RequestClipboardPermission_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(Empty)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(DaemonServiceServer).RequestClipboardPermission(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: DaemonService_RequestClipboardPermission_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(DaemonServiceServer).RequestClipboardPermission(ctx, req.(*Empty))+ }+ return interceptor(ctx, in, info, handler)+}++// DaemonService_ServiceDesc is the grpc.ServiceDesc for DaemonService service.+// It's only intended for direct use with grpc.RegisterService,+// and not to be introspected or modified (even as a copy)+var DaemonService_ServiceDesc = grpc.ServiceDesc{+ ServiceName: "copysync.v1.DaemonService",+ HandlerType: (*DaemonServiceServer)(nil),+ Methods: []grpc.MethodDesc{+ {+ MethodName: "ListHistory",+ Handler: _DaemonService_ListHistory_Handler,+ },+ {+ MethodName: "DeleteHistory",+ Handler: _DaemonService_DeleteHistory_Handler,+ },+ {+ MethodName: "Fetch",+ Handler: _DaemonService_Fetch_Handler,+ },+ {+ MethodName: "ApplyToClipboard",+ Handler: _DaemonService_ApplyToClipboard_Handler,+ },+ {+ MethodName: "ListDevices",+ Handler: _DaemonService_ListDevices_Handler,+ },+ {+ MethodName: "CreatePairingCode",+ Handler: _DaemonService_CreatePairingCode_Handler,+ },+ {+ MethodName: "RedeemPairingCode",+ Handler: _DaemonService_RedeemPairingCode_Handler,+ },+ {+ MethodName: "ConfirmPairing",+ Handler: _DaemonService_ConfirmPairing_Handler,+ },+ {+ MethodName: "Unpair",+ Handler: _DaemonService_Unpair_Handler,+ },+ {+ MethodName: "GetConfig",+ Handler: _DaemonService_GetConfig_Handler,+ },+ {+ MethodName: "UpdateConfig",+ Handler: _DaemonService_UpdateConfig_Handler,+ },+ {+ MethodName: "GetStatus",+ Handler: _DaemonService_GetStatus_Handler,+ },+ {+ MethodName: "RequestClipboardPermission",+ Handler: _DaemonService_RequestClipboardPermission_Handler,+ },+ },+ Streams: []grpc.StreamDesc{+ {+ StreamName: "Subscribe",+ Handler: _DaemonService_Subscribe_Handler,+ ServerStreams: true,+ },+ },+ Metadata: "copysync/v1/daemon.proto",+}diff --git a/proto/gen/copysync/v1/wire.pb.go b/proto/gen/copysync/v1/wire.pb.gonew file mode 100644index 0000000..bd32fe0--- /dev/null+++ b/proto/gen/copysync/v1/wire.pb.go@@ -0,0 +1,2271 @@+// 线上协议:客户端 ↔ 信令服务器,以及设备 ↔ 设备。+//+// 信令服务器只转发、不解密内容,也不存用户——设备靠配对时交换的+// Ed25519 公钥互相认证。所有经服务器中转的信令都带签名,+// 防止服务器伪造 peer 身份做中间人。++// Code generated by protoc-gen-go. DO NOT EDIT.+// versions:+// protoc-gen-go v1.36.12+// protoc (unknown)+// source: copysync/v1/wire.proto++package copysyncv1++import (+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"+ reflect "reflect"+ sync "sync"+ unsafe "unsafe"+)++const (+ // Verify that this generated code is sufficiently up-to-date.+ _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)+ // Verify that runtime/protoimpl is sufficiently up-to-date.+ _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)+)++type Compression int32++const (+ Compression_COMPRESSION_UNSPECIFIED Compression = 0+ Compression_COMPRESSION_NONE Compression = 1+ Compression_COMPRESSION_ZSTD Compression = 2+)++// Enum value maps for Compression.+var (+ Compression_name = map[int32]string{+ 0: "COMPRESSION_UNSPECIFIED",+ 1: "COMPRESSION_NONE",+ 2: "COMPRESSION_ZSTD",+ }+ Compression_value = map[string]int32{+ "COMPRESSION_UNSPECIFIED": 0,+ "COMPRESSION_NONE": 1,+ "COMPRESSION_ZSTD": 2,+ }+)++func (x Compression) Enum() *Compression {+ p := new(Compression)+ *p = x+ return p+}++func (x Compression) String() string {+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))+}++func (Compression) Descriptor() protoreflect.EnumDescriptor {+ return file_copysync_v1_wire_proto_enumTypes[0].Descriptor()+}++func (Compression) Type() protoreflect.EnumType {+ return &file_copysync_v1_wire_proto_enumTypes[0]+}++func (x Compression) Number() protoreflect.EnumNumber {+ return protoreflect.EnumNumber(x)+}++// Deprecated: Use Compression.Descriptor instead.+func (Compression) EnumDescriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{0}+}++type Packaging int32++const (+ Packaging_PACKAGING_UNSPECIFIED Packaging = 0+ Packaging_PACKAGING_RAW Packaging = 1 // 单个文件,裸内容+ Packaging_PACKAGING_TAR Packaging = 2 // 多文件或目录+)++// Enum value maps for Packaging.+var (+ Packaging_name = map[int32]string{+ 0: "PACKAGING_UNSPECIFIED",+ 1: "PACKAGING_RAW",+ 2: "PACKAGING_TAR",+ }+ Packaging_value = map[string]int32{+ "PACKAGING_UNSPECIFIED": 0,+ "PACKAGING_RAW": 1,+ "PACKAGING_TAR": 2,+ }+)++func (x Packaging) Enum() *Packaging {+ p := new(Packaging)+ *p = x+ return p+}++func (x Packaging) String() string {+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))+}++func (Packaging) Descriptor() protoreflect.EnumDescriptor {+ return file_copysync_v1_wire_proto_enumTypes[1].Descriptor()+}++func (Packaging) Type() protoreflect.EnumType {+ return &file_copysync_v1_wire_proto_enumTypes[1]+}++func (x Packaging) Number() protoreflect.EnumNumber {+ return protoreflect.EnumNumber(x)+}++// Deprecated: Use Packaging.Descriptor instead.+func (Packaging) EnumDescriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{1}+}++// 经服务器转发的消息一律包一层签名。接收方用配对时存下的+// 对端公钥验签,服务器无法伪造。+type Signed struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Payload []byte `protobuf:"bytes,1,opt,name=payload,proto3" json:"payload,omitempty"` // 序列化后的 SignalMessage+ Signature []byte `protobuf:"bytes,2,opt,name=signature,proto3" json:"signature,omitempty"` // Ed25519 签名,覆盖 payload+ FromDeviceId string `protobuf:"bytes,3,opt,name=from_device_id,json=fromDeviceId,proto3" json:"from_device_id,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *Signed) Reset() {+ *x = Signed{}+ mi := &file_copysync_v1_wire_proto_msgTypes[0]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *Signed) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*Signed) ProtoMessage() {}++func (x *Signed) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[0]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use Signed.ProtoReflect.Descriptor instead.+func (*Signed) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{0}+}++func (x *Signed) GetPayload() []byte {+ if x != nil {+ return x.Payload+ }+ return nil+}++func (x *Signed) GetSignature() []byte {+ if x != nil {+ return x.Signature+ }+ return nil+}++func (x *Signed) GetFromDeviceId() string {+ if x != nil {+ return x.FromDeviceId+ }+ return ""+}++type SignalMessage struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // 防重放:接收方拒绝时间戳过旧或 nonce 重复的消息+ TimestampUnix int64 `protobuf:"varint,1,opt,name=timestamp_unix,json=timestampUnix,proto3" json:"timestamp_unix,omitempty"`+ Nonce []byte `protobuf:"bytes,2,opt,name=nonce,proto3" json:"nonce,omitempty"`+ ToDeviceId string `protobuf:"bytes,3,opt,name=to_device_id,json=toDeviceId,proto3" json:"to_device_id,omitempty"`+ // Types that are valid to be assigned to Payload:+ //+ // *SignalMessage_Offer+ // *SignalMessage_Answer+ // *SignalMessage_Candidate+ // *SignalMessage_Ping+ Payload isSignalMessage_Payload `protobuf_oneof:"payload"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *SignalMessage) Reset() {+ *x = SignalMessage{}+ mi := &file_copysync_v1_wire_proto_msgTypes[1]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *SignalMessage) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*SignalMessage) ProtoMessage() {}++func (x *SignalMessage) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[1]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use SignalMessage.ProtoReflect.Descriptor instead.+func (*SignalMessage) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{1}+}++func (x *SignalMessage) GetTimestampUnix() int64 {+ if x != nil {+ return x.TimestampUnix+ }+ return 0+}++func (x *SignalMessage) GetNonce() []byte {+ if x != nil {+ return x.Nonce+ }+ return nil+}++func (x *SignalMessage) GetToDeviceId() string {+ if x != nil {+ return x.ToDeviceId+ }+ return ""+}++func (x *SignalMessage) GetPayload() isSignalMessage_Payload {+ if x != nil {+ return x.Payload+ }+ return nil+}++func (x *SignalMessage) GetOffer() *SdpOffer {+ if x != nil {+ if x, ok := x.Payload.(*SignalMessage_Offer); ok {+ return x.Offer+ }+ }+ return nil+}++func (x *SignalMessage) GetAnswer() *SdpAnswer {+ if x != nil {+ if x, ok := x.Payload.(*SignalMessage_Answer); ok {+ return x.Answer+ }+ }+ return nil+}++func (x *SignalMessage) GetCandidate() *IceCandidate {+ if x != nil {+ if x, ok := x.Payload.(*SignalMessage_Candidate); ok {+ return x.Candidate+ }+ }+ return nil+}++func (x *SignalMessage) GetPing() *Ping {+ if x != nil {+ if x, ok := x.Payload.(*SignalMessage_Ping); ok {+ return x.Ping+ }+ }+ return nil+}++type isSignalMessage_Payload interface {+ isSignalMessage_Payload()+}++type SignalMessage_Offer struct {+ Offer *SdpOffer `protobuf:"bytes,10,opt,name=offer,proto3,oneof"`+}++type SignalMessage_Answer struct {+ Answer *SdpAnswer `protobuf:"bytes,11,opt,name=answer,proto3,oneof"`+}++type SignalMessage_Candidate struct {+ Candidate *IceCandidate `protobuf:"bytes,12,opt,name=candidate,proto3,oneof"`+}++type SignalMessage_Ping struct {+ Ping *Ping `protobuf:"bytes,13,opt,name=ping,proto3,oneof"`+}++func (*SignalMessage_Offer) isSignalMessage_Payload() {}++func (*SignalMessage_Answer) isSignalMessage_Payload() {}++func (*SignalMessage_Candidate) isSignalMessage_Payload() {}++func (*SignalMessage_Ping) isSignalMessage_Payload() {}++type SdpOffer struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Sdp string `protobuf:"bytes,1,opt,name=sdp,proto3" json:"sdp,omitempty"`+ // DTLS 证书指纹。经签名传输,杜绝信令服务器中间人攻击——+ // 这是 P2P 通道真正的安全锚点。+ DtlsFingerprint string `protobuf:"bytes,2,opt,name=dtls_fingerprint,json=dtlsFingerprint,proto3" json:"dtls_fingerprint,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *SdpOffer) Reset() {+ *x = SdpOffer{}+ mi := &file_copysync_v1_wire_proto_msgTypes[2]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *SdpOffer) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*SdpOffer) ProtoMessage() {}++func (x *SdpOffer) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[2]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use SdpOffer.ProtoReflect.Descriptor instead.+func (*SdpOffer) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{2}+}++func (x *SdpOffer) GetSdp() string {+ if x != nil {+ return x.Sdp+ }+ return ""+}++func (x *SdpOffer) GetDtlsFingerprint() string {+ if x != nil {+ return x.DtlsFingerprint+ }+ return ""+}++type SdpAnswer struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Sdp string `protobuf:"bytes,1,opt,name=sdp,proto3" json:"sdp,omitempty"`+ DtlsFingerprint string `protobuf:"bytes,2,opt,name=dtls_fingerprint,json=dtlsFingerprint,proto3" json:"dtls_fingerprint,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *SdpAnswer) Reset() {+ *x = SdpAnswer{}+ mi := &file_copysync_v1_wire_proto_msgTypes[3]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *SdpAnswer) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*SdpAnswer) ProtoMessage() {}++func (x *SdpAnswer) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[3]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use SdpAnswer.ProtoReflect.Descriptor instead.+func (*SdpAnswer) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{3}+}++func (x *SdpAnswer) GetSdp() string {+ if x != nil {+ return x.Sdp+ }+ return ""+}++func (x *SdpAnswer) GetDtlsFingerprint() string {+ if x != nil {+ return x.DtlsFingerprint+ }+ return ""+}++type IceCandidate struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Candidate string `protobuf:"bytes,1,opt,name=candidate,proto3" json:"candidate,omitempty"`+ SdpMid string `protobuf:"bytes,2,opt,name=sdp_mid,json=sdpMid,proto3" json:"sdp_mid,omitempty"`+ SdpMlineIndex uint32 `protobuf:"varint,3,opt,name=sdp_mline_index,json=sdpMlineIndex,proto3" json:"sdp_mline_index,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *IceCandidate) Reset() {+ *x = IceCandidate{}+ mi := &file_copysync_v1_wire_proto_msgTypes[4]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *IceCandidate) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*IceCandidate) ProtoMessage() {}++func (x *IceCandidate) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[4]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use IceCandidate.ProtoReflect.Descriptor instead.+func (*IceCandidate) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{4}+}++func (x *IceCandidate) GetCandidate() string {+ if x != nil {+ return x.Candidate+ }+ return ""+}++func (x *IceCandidate) GetSdpMid() string {+ if x != nil {+ return x.SdpMid+ }+ return ""+}++func (x *IceCandidate) GetSdpMlineIndex() uint32 {+ if x != nil {+ return x.SdpMlineIndex+ }+ return 0+}++type Ping struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ SentAtUnix int64 `protobuf:"varint,1,opt,name=sent_at_unix,json=sentAtUnix,proto3" json:"sent_at_unix,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *Ping) Reset() {+ *x = Ping{}+ mi := &file_copysync_v1_wire_proto_msgTypes[5]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *Ping) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*Ping) ProtoMessage() {}++func (x *Ping) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[5]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use Ping.ProtoReflect.Descriptor instead.+func (*Ping) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{5}+}++func (x *Ping) GetSentAtUnix() int64 {+ if x != nil {+ return x.SentAtUnix+ }+ return 0+}++type ClientHello struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ DeviceId string `protobuf:"bytes,1,opt,name=device_id,json=deviceId,proto3" json:"device_id,omitempty"`+ DeviceName string `protobuf:"bytes,2,opt,name=device_name,json=deviceName,proto3" json:"device_name,omitempty"`+ Platform string `protobuf:"bytes,3,opt,name=platform,proto3" json:"platform,omitempty"`+ PublicKey []byte `protobuf:"bytes,4,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"` // Ed25519+ Signature []byte `protobuf:"bytes,5,opt,name=signature,proto3" json:"signature,omitempty"` // 对 challenge 的签名,证明持有私钥+ PairedDeviceIds []string `protobuf:"bytes,6,rep,name=paired_device_ids,json=pairedDeviceIds,proto3" json:"paired_device_ids,omitempty"` // 关心哪些对端的在线状态+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ClientHello) Reset() {+ *x = ClientHello{}+ mi := &file_copysync_v1_wire_proto_msgTypes[6]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ClientHello) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ClientHello) ProtoMessage() {}++func (x *ClientHello) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[6]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ClientHello.ProtoReflect.Descriptor instead.+func (*ClientHello) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{6}+}++func (x *ClientHello) GetDeviceId() string {+ if x != nil {+ return x.DeviceId+ }+ return ""+}++func (x *ClientHello) GetDeviceName() string {+ if x != nil {+ return x.DeviceName+ }+ return ""+}++func (x *ClientHello) GetPlatform() string {+ if x != nil {+ return x.Platform+ }+ return ""+}++func (x *ClientHello) GetPublicKey() []byte {+ if x != nil {+ return x.PublicKey+ }+ return nil+}++func (x *ClientHello) GetSignature() []byte {+ if x != nil {+ return x.Signature+ }+ return nil+}++func (x *ClientHello) GetPairedDeviceIds() []string {+ if x != nil {+ return x.PairedDeviceIds+ }+ return nil+}++type ServerHello struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Challenge []byte `protobuf:"bytes,1,opt,name=challenge,proto3" json:"challenge,omitempty"`+ IceServers []*IceServer `protobuf:"bytes,2,rep,name=ice_servers,json=iceServers,proto3" json:"ice_servers,omitempty"`+ ServerTimeUnix int64 `protobuf:"varint,3,opt,name=server_time_unix,json=serverTimeUnix,proto3" json:"server_time_unix,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ServerHello) Reset() {+ *x = ServerHello{}+ mi := &file_copysync_v1_wire_proto_msgTypes[7]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ServerHello) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ServerHello) ProtoMessage() {}++func (x *ServerHello) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[7]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ServerHello.ProtoReflect.Descriptor instead.+func (*ServerHello) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{7}+}++func (x *ServerHello) GetChallenge() []byte {+ if x != nil {+ return x.Challenge+ }+ return nil+}++func (x *ServerHello) GetIceServers() []*IceServer {+ if x != nil {+ return x.IceServers+ }+ return nil+}++func (x *ServerHello) GetServerTimeUnix() int64 {+ if x != nil {+ return x.ServerTimeUnix+ }+ return 0+}++type IceServer struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Urls []string `protobuf:"bytes,1,rep,name=urls,proto3" json:"urls,omitempty"`+ Username string `protobuf:"bytes,2,opt,name=username,proto3" json:"username,omitempty"` // TURN 短期凭证+ Credential string `protobuf:"bytes,3,opt,name=credential,proto3" json:"credential,omitempty"`+ ExpiresAtUnix int64 `protobuf:"varint,4,opt,name=expires_at_unix,json=expiresAtUnix,proto3" json:"expires_at_unix,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *IceServer) Reset() {+ *x = IceServer{}+ mi := &file_copysync_v1_wire_proto_msgTypes[8]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *IceServer) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*IceServer) ProtoMessage() {}++func (x *IceServer) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[8]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use IceServer.ProtoReflect.Descriptor instead.+func (*IceServer) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{8}+}++func (x *IceServer) GetUrls() []string {+ if x != nil {+ return x.Urls+ }+ return nil+}++func (x *IceServer) GetUsername() string {+ if x != nil {+ return x.Username+ }+ return ""+}++func (x *IceServer) GetCredential() string {+ if x != nil {+ return x.Credential+ }+ return ""+}++func (x *IceServer) GetExpiresAtUnix() int64 {+ if x != nil {+ return x.ExpiresAtUnix+ }+ return 0+}++type PeerPresence struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ DeviceId string `protobuf:"bytes,1,opt,name=device_id,json=deviceId,proto3" json:"device_id,omitempty"`+ Online bool `protobuf:"varint,2,opt,name=online,proto3" json:"online,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *PeerPresence) Reset() {+ *x = PeerPresence{}+ mi := &file_copysync_v1_wire_proto_msgTypes[9]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *PeerPresence) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*PeerPresence) ProtoMessage() {}++func (x *PeerPresence) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[9]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use PeerPresence.ProtoReflect.Descriptor instead.+func (*PeerPresence) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{9}+}++func (x *PeerPresence) GetDeviceId() string {+ if x != nil {+ return x.DeviceId+ }+ return ""+}++func (x *PeerPresence) GetOnline() bool {+ if x != nil {+ return x.Online+ }+ return false+}++type PairingCreateRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ DeviceName string `protobuf:"bytes,1,opt,name=device_name,json=deviceName,proto3" json:"device_name,omitempty"`+ PublicKey []byte `protobuf:"bytes,2,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *PairingCreateRequest) Reset() {+ *x = PairingCreateRequest{}+ mi := &file_copysync_v1_wire_proto_msgTypes[10]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *PairingCreateRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*PairingCreateRequest) ProtoMessage() {}++func (x *PairingCreateRequest) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[10]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use PairingCreateRequest.ProtoReflect.Descriptor instead.+func (*PairingCreateRequest) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{10}+}++func (x *PairingCreateRequest) GetDeviceName() string {+ if x != nil {+ return x.DeviceName+ }+ return ""+}++func (x *PairingCreateRequest) GetPublicKey() []byte {+ if x != nil {+ return x.PublicKey+ }+ return nil+}++type PairingCreateResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Code string `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"` // 6 位,服务器侧 TTL 5 分钟+ ExpiresAtUnix int64 `protobuf:"varint,2,opt,name=expires_at_unix,json=expiresAtUnix,proto3" json:"expires_at_unix,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *PairingCreateResponse) Reset() {+ *x = PairingCreateResponse{}+ mi := &file_copysync_v1_wire_proto_msgTypes[11]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *PairingCreateResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*PairingCreateResponse) ProtoMessage() {}++func (x *PairingCreateResponse) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[11]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use PairingCreateResponse.ProtoReflect.Descriptor instead.+func (*PairingCreateResponse) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{11}+}++func (x *PairingCreateResponse) GetCode() string {+ if x != nil {+ return x.Code+ }+ return ""+}++func (x *PairingCreateResponse) GetExpiresAtUnix() int64 {+ if x != nil {+ return x.ExpiresAtUnix+ }+ return 0+}++type PairingRedeemRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Code string `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"`+ DeviceId string `protobuf:"bytes,2,opt,name=device_id,json=deviceId,proto3" json:"device_id,omitempty"`+ DeviceName string `protobuf:"bytes,3,opt,name=device_name,json=deviceName,proto3" json:"device_name,omitempty"`+ PublicKey []byte `protobuf:"bytes,4,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *PairingRedeemRequest) Reset() {+ *x = PairingRedeemRequest{}+ mi := &file_copysync_v1_wire_proto_msgTypes[12]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *PairingRedeemRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*PairingRedeemRequest) ProtoMessage() {}++func (x *PairingRedeemRequest) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[12]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use PairingRedeemRequest.ProtoReflect.Descriptor instead.+func (*PairingRedeemRequest) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{12}+}++func (x *PairingRedeemRequest) GetCode() string {+ if x != nil {+ return x.Code+ }+ return ""+}++func (x *PairingRedeemRequest) GetDeviceId() string {+ if x != nil {+ return x.DeviceId+ }+ return ""+}++func (x *PairingRedeemRequest) GetDeviceName() string {+ if x != nil {+ return x.DeviceName+ }+ return ""+}++func (x *PairingRedeemRequest) GetPublicKey() []byte {+ if x != nil {+ return x.PublicKey+ }+ return nil+}++type PairingRedeemResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ PeerDeviceId string `protobuf:"bytes,1,opt,name=peer_device_id,json=peerDeviceId,proto3" json:"peer_device_id,omitempty"`+ PeerDeviceName string `protobuf:"bytes,2,opt,name=peer_device_name,json=peerDeviceName,proto3" json:"peer_device_name,omitempty"`+ PeerPlatform string `protobuf:"bytes,3,opt,name=peer_platform,json=peerPlatform,proto3" json:"peer_platform,omitempty"`+ PeerPublicKey []byte `protobuf:"bytes,4,opt,name=peer_public_key,json=peerPublicKey,proto3" json:"peer_public_key,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *PairingRedeemResponse) Reset() {+ *x = PairingRedeemResponse{}+ mi := &file_copysync_v1_wire_proto_msgTypes[13]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *PairingRedeemResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*PairingRedeemResponse) ProtoMessage() {}++func (x *PairingRedeemResponse) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[13]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use PairingRedeemResponse.ProtoReflect.Descriptor instead.+func (*PairingRedeemResponse) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{13}+}++func (x *PairingRedeemResponse) GetPeerDeviceId() string {+ if x != nil {+ return x.PeerDeviceId+ }+ return ""+}++func (x *PairingRedeemResponse) GetPeerDeviceName() string {+ if x != nil {+ return x.PeerDeviceName+ }+ return ""+}++func (x *PairingRedeemResponse) GetPeerPlatform() string {+ if x != nil {+ return x.PeerPlatform+ }+ return ""+}++func (x *PairingRedeemResponse) GetPeerPublicKey() []byte {+ if x != nil {+ return x.PeerPublicKey+ }+ return nil+}++// 服务器 → 发起方:有人兑换了你的配对码+type PairingRedeemed struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ PeerDeviceId string `protobuf:"bytes,1,opt,name=peer_device_id,json=peerDeviceId,proto3" json:"peer_device_id,omitempty"`+ PeerDeviceName string `protobuf:"bytes,2,opt,name=peer_device_name,json=peerDeviceName,proto3" json:"peer_device_name,omitempty"`+ PeerPlatform string `protobuf:"bytes,3,opt,name=peer_platform,json=peerPlatform,proto3" json:"peer_platform,omitempty"`+ PeerPublicKey []byte `protobuf:"bytes,4,opt,name=peer_public_key,json=peerPublicKey,proto3" json:"peer_public_key,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *PairingRedeemed) Reset() {+ *x = PairingRedeemed{}+ mi := &file_copysync_v1_wire_proto_msgTypes[14]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *PairingRedeemed) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*PairingRedeemed) ProtoMessage() {}++func (x *PairingRedeemed) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[14]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use PairingRedeemed.ProtoReflect.Descriptor instead.+func (*PairingRedeemed) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{14}+}++func (x *PairingRedeemed) GetPeerDeviceId() string {+ if x != nil {+ return x.PeerDeviceId+ }+ return ""+}++func (x *PairingRedeemed) GetPeerDeviceName() string {+ if x != nil {+ return x.PeerDeviceName+ }+ return ""+}++func (x *PairingRedeemed) GetPeerPlatform() string {+ if x != nil {+ return x.PeerPlatform+ }+ return ""+}++func (x *PairingRedeemed) GetPeerPublicKey() []byte {+ if x != nil {+ return x.PeerPublicKey+ }+ return nil+}++// TURN 凭证是按设备签发且有有效期的,因此必须在认证完成后才能下发,+// 之后也会在临近过期时重新推送。+type IceConfig struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ IceServers []*IceServer `protobuf:"bytes,1,rep,name=ice_servers,json=iceServers,proto3" json:"ice_servers,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *IceConfig) Reset() {+ *x = IceConfig{}+ mi := &file_copysync_v1_wire_proto_msgTypes[15]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *IceConfig) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*IceConfig) ProtoMessage() {}++func (x *IceConfig) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[15]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use IceConfig.ProtoReflect.Descriptor instead.+func (*IceConfig) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{15}+}++func (x *IceConfig) GetIceServers() []*IceServer {+ if x != nil {+ return x.IceServers+ }+ return nil+}++// 客户端 ↔ 服务器的顶层信封+type ServerEnvelope struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // Types that are valid to be assigned to Payload:+ //+ // *ServerEnvelope_Hello+ // *ServerEnvelope_Forwarded+ // *ServerEnvelope_Presence+ // *ServerEnvelope_PairingCreated+ // *ServerEnvelope_PairingRedeemedResult+ // *ServerEnvelope_PairingRedeemed+ // *ServerEnvelope_Error+ // *ServerEnvelope_IceConfig+ Payload isServerEnvelope_Payload `protobuf_oneof:"payload"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ServerEnvelope) Reset() {+ *x = ServerEnvelope{}+ mi := &file_copysync_v1_wire_proto_msgTypes[16]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ServerEnvelope) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ServerEnvelope) ProtoMessage() {}++func (x *ServerEnvelope) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[16]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ServerEnvelope.ProtoReflect.Descriptor instead.+func (*ServerEnvelope) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{16}+}++func (x *ServerEnvelope) GetPayload() isServerEnvelope_Payload {+ if x != nil {+ return x.Payload+ }+ return nil+}++func (x *ServerEnvelope) GetHello() *ServerHello {+ if x != nil {+ if x, ok := x.Payload.(*ServerEnvelope_Hello); ok {+ return x.Hello+ }+ }+ return nil+}++func (x *ServerEnvelope) GetForwarded() *Signed {+ if x != nil {+ if x, ok := x.Payload.(*ServerEnvelope_Forwarded); ok {+ return x.Forwarded+ }+ }+ return nil+}++func (x *ServerEnvelope) GetPresence() *PeerPresence {+ if x != nil {+ if x, ok := x.Payload.(*ServerEnvelope_Presence); ok {+ return x.Presence+ }+ }+ return nil+}++func (x *ServerEnvelope) GetPairingCreated() *PairingCreateResponse {+ if x != nil {+ if x, ok := x.Payload.(*ServerEnvelope_PairingCreated); ok {+ return x.PairingCreated+ }+ }+ return nil+}++func (x *ServerEnvelope) GetPairingRedeemedResult() *PairingRedeemResponse {+ if x != nil {+ if x, ok := x.Payload.(*ServerEnvelope_PairingRedeemedResult); ok {+ return x.PairingRedeemedResult+ }+ }+ return nil+}++func (x *ServerEnvelope) GetPairingRedeemed() *PairingRedeemed {+ if x != nil {+ if x, ok := x.Payload.(*ServerEnvelope_PairingRedeemed); ok {+ return x.PairingRedeemed+ }+ }+ return nil+}++func (x *ServerEnvelope) GetError() *ServerError {+ if x != nil {+ if x, ok := x.Payload.(*ServerEnvelope_Error); ok {+ return x.Error+ }+ }+ return nil+}++func (x *ServerEnvelope) GetIceConfig() *IceConfig {+ if x != nil {+ if x, ok := x.Payload.(*ServerEnvelope_IceConfig); ok {+ return x.IceConfig+ }+ }+ return nil+}++type isServerEnvelope_Payload interface {+ isServerEnvelope_Payload()+}++type ServerEnvelope_Hello struct {+ Hello *ServerHello `protobuf:"bytes,1,opt,name=hello,proto3,oneof"`+}++type ServerEnvelope_Forwarded struct {+ Forwarded *Signed `protobuf:"bytes,2,opt,name=forwarded,proto3,oneof"` // 转发自其他设备+}++type ServerEnvelope_Presence struct {+ Presence *PeerPresence `protobuf:"bytes,3,opt,name=presence,proto3,oneof"`+}++type ServerEnvelope_PairingCreated struct {+ PairingCreated *PairingCreateResponse `protobuf:"bytes,4,opt,name=pairing_created,json=pairingCreated,proto3,oneof"`+}++type ServerEnvelope_PairingRedeemedResult struct {+ PairingRedeemedResult *PairingRedeemResponse `protobuf:"bytes,5,opt,name=pairing_redeemed_result,json=pairingRedeemedResult,proto3,oneof"`+}++type ServerEnvelope_PairingRedeemed struct {+ PairingRedeemed *PairingRedeemed `protobuf:"bytes,6,opt,name=pairing_redeemed,json=pairingRedeemed,proto3,oneof"`+}++type ServerEnvelope_Error struct {+ Error *ServerError `protobuf:"bytes,7,opt,name=error,proto3,oneof"`+}++type ServerEnvelope_IceConfig struct {+ IceConfig *IceConfig `protobuf:"bytes,8,opt,name=ice_config,json=iceConfig,proto3,oneof"`+}++func (*ServerEnvelope_Hello) isServerEnvelope_Payload() {}++func (*ServerEnvelope_Forwarded) isServerEnvelope_Payload() {}++func (*ServerEnvelope_Presence) isServerEnvelope_Payload() {}++func (*ServerEnvelope_PairingCreated) isServerEnvelope_Payload() {}++func (*ServerEnvelope_PairingRedeemedResult) isServerEnvelope_Payload() {}++func (*ServerEnvelope_PairingRedeemed) isServerEnvelope_Payload() {}++func (*ServerEnvelope_Error) isServerEnvelope_Payload() {}++func (*ServerEnvelope_IceConfig) isServerEnvelope_Payload() {}++type ClientEnvelope struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // Types that are valid to be assigned to Payload:+ //+ // *ClientEnvelope_Hello+ // *ClientEnvelope_Forward+ // *ClientEnvelope_PairingCreate+ // *ClientEnvelope_PairingRedeem+ Payload isClientEnvelope_Payload `protobuf_oneof:"payload"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ClientEnvelope) Reset() {+ *x = ClientEnvelope{}+ mi := &file_copysync_v1_wire_proto_msgTypes[17]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ClientEnvelope) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ClientEnvelope) ProtoMessage() {}++func (x *ClientEnvelope) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[17]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ClientEnvelope.ProtoReflect.Descriptor instead.+func (*ClientEnvelope) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{17}+}++func (x *ClientEnvelope) GetPayload() isClientEnvelope_Payload {+ if x != nil {+ return x.Payload+ }+ return nil+}++func (x *ClientEnvelope) GetHello() *ClientHello {+ if x != nil {+ if x, ok := x.Payload.(*ClientEnvelope_Hello); ok {+ return x.Hello+ }+ }+ return nil+}++func (x *ClientEnvelope) GetForward() *Signed {+ if x != nil {+ if x, ok := x.Payload.(*ClientEnvelope_Forward); ok {+ return x.Forward+ }+ }+ return nil+}++func (x *ClientEnvelope) GetPairingCreate() *PairingCreateRequest {+ if x != nil {+ if x, ok := x.Payload.(*ClientEnvelope_PairingCreate); ok {+ return x.PairingCreate+ }+ }+ return nil+}++func (x *ClientEnvelope) GetPairingRedeem() *PairingRedeemRequest {+ if x != nil {+ if x, ok := x.Payload.(*ClientEnvelope_PairingRedeem); ok {+ return x.PairingRedeem+ }+ }+ return nil+}++type isClientEnvelope_Payload interface {+ isClientEnvelope_Payload()+}++type ClientEnvelope_Hello struct {+ Hello *ClientHello `protobuf:"bytes,1,opt,name=hello,proto3,oneof"`+}++type ClientEnvelope_Forward struct {+ Forward *Signed `protobuf:"bytes,2,opt,name=forward,proto3,oneof"` // 请服务器转发给 to_device_id+}++type ClientEnvelope_PairingCreate struct {+ PairingCreate *PairingCreateRequest `protobuf:"bytes,3,opt,name=pairing_create,json=pairingCreate,proto3,oneof"`+}++type ClientEnvelope_PairingRedeem struct {+ PairingRedeem *PairingRedeemRequest `protobuf:"bytes,4,opt,name=pairing_redeem,json=pairingRedeem,proto3,oneof"`+}++func (*ClientEnvelope_Hello) isClientEnvelope_Payload() {}++func (*ClientEnvelope_Forward) isClientEnvelope_Payload() {}++func (*ClientEnvelope_PairingCreate) isClientEnvelope_Payload() {}++func (*ClientEnvelope_PairingRedeem) isClientEnvelope_Payload() {}++type ServerError struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Code string `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"`+ Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ServerError) Reset() {+ *x = ServerError{}+ mi := &file_copysync_v1_wire_proto_msgTypes[18]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ServerError) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ServerError) ProtoMessage() {}++func (x *ServerError) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[18]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ServerError.ProtoReflect.Descriptor instead.+func (*ServerError) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{18}+}++func (x *ServerError) GetCode() string {+ if x != nil {+ return x.Code+ }+ return ""+}++func (x *ServerError) GetMessage() string {+ if x != nil {+ return x.Message+ }+ return ""+}++// 控制通道消息+type PeerMessage struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // Types that are valid to be assigned to Payload:+ //+ // *PeerMessage_Offer+ // *PeerMessage_Fetch+ // *PeerMessage_Reject+ // *PeerMessage_Header+ // *PeerMessage_Done+ Payload isPeerMessage_Payload `protobuf_oneof:"payload"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *PeerMessage) Reset() {+ *x = PeerMessage{}+ mi := &file_copysync_v1_wire_proto_msgTypes[19]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *PeerMessage) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*PeerMessage) ProtoMessage() {}++func (x *PeerMessage) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[19]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use PeerMessage.ProtoReflect.Descriptor instead.+func (*PeerMessage) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{19}+}++func (x *PeerMessage) GetPayload() isPeerMessage_Payload {+ if x != nil {+ return x.Payload+ }+ return nil+}++func (x *PeerMessage) GetOffer() *ClipOffer {+ if x != nil {+ if x, ok := x.Payload.(*PeerMessage_Offer); ok {+ return x.Offer+ }+ }+ return nil+}++func (x *PeerMessage) GetFetch() *PeerFetch {+ if x != nil {+ if x, ok := x.Payload.(*PeerMessage_Fetch); ok {+ return x.Fetch+ }+ }+ return nil+}++func (x *PeerMessage) GetReject() *FetchReject {+ if x != nil {+ if x, ok := x.Payload.(*PeerMessage_Reject); ok {+ return x.Reject+ }+ }+ return nil+}++func (x *PeerMessage) GetHeader() *TransferHeader {+ if x != nil {+ if x, ok := x.Payload.(*PeerMessage_Header); ok {+ return x.Header+ }+ }+ return nil+}++func (x *PeerMessage) GetDone() *TransferDone {+ if x != nil {+ if x, ok := x.Payload.(*PeerMessage_Done); ok {+ return x.Done+ }+ }+ return nil+}++type isPeerMessage_Payload interface {+ isPeerMessage_Payload()+}++type PeerMessage_Offer struct {+ Offer *ClipOffer `protobuf:"bytes,1,opt,name=offer,proto3,oneof"` // 广播:我这边复制了东西+}++type PeerMessage_Fetch struct {+ Fetch *PeerFetch `protobuf:"bytes,2,opt,name=fetch,proto3,oneof"` // 请求:把某条内容发给我+}++type PeerMessage_Reject struct {+ Reject *FetchReject `protobuf:"bytes,3,opt,name=reject,proto3,oneof"` // 拒绝:源文件没了 / 已过期+}++type PeerMessage_Header struct {+ Header *TransferHeader `protobuf:"bytes,4,opt,name=header,proto3,oneof"` // 数据流即将开始+}++type PeerMessage_Done struct {+ Done *TransferDone `protobuf:"bytes,5,opt,name=done,proto3,oneof"`+}++func (*PeerMessage_Offer) isPeerMessage_Payload() {}++func (*PeerMessage_Fetch) isPeerMessage_Payload() {}++func (*PeerMessage_Reject) isPeerMessage_Payload() {}++func (*PeerMessage_Header) isPeerMessage_Payload() {}++func (*PeerMessage_Done) isPeerMessage_Payload() {}++// 复制发生时广播给所有在线对端。+// 小于阈值的内容会紧接着主动推送;大于阈值的只发这条,等对方来取。+type ClipOffer struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ ClipId string `protobuf:"bytes,1,opt,name=clip_id,json=clipId,proto3" json:"clip_id,omitempty"`+ Kind ClipKind `protobuf:"varint,2,opt,name=kind,proto3,enum=copysync.v1.ClipKind" json:"kind,omitempty"`+ Items []*ClipItem `protobuf:"bytes,3,rep,name=items,proto3" json:"items,omitempty"`+ TotalSize int64 `protobuf:"varint,4,opt,name=total_size,json=totalSize,proto3" json:"total_size,omitempty"`+ TextContent string `protobuf:"bytes,5,opt,name=text_content,json=textContent,proto3" json:"text_content,omitempty"` // 文本/HTML 直接内联,无需二次传输+ CreatedAtUnix int64 `protobuf:"varint,6,opt,name=created_at_unix,json=createdAtUnix,proto3" json:"created_at_unix,omitempty"`+ WillPush bool `protobuf:"varint,7,opt,name=will_push,json=willPush,proto3" json:"will_push,omitempty"` // true=发送方会主动推,false=需 fetch+ // HTML 的纯文本形式(此时 text_content 是 HTML 标记)。旧版本不发这个字段,+ // 收到空值时由接收方从 HTML 中提取。+ PlainText string `protobuf:"bytes,8,opt,name=plain_text,json=plainText,proto3" json:"plain_text,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ClipOffer) Reset() {+ *x = ClipOffer{}+ mi := &file_copysync_v1_wire_proto_msgTypes[20]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ClipOffer) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ClipOffer) ProtoMessage() {}++func (x *ClipOffer) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[20]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ClipOffer.ProtoReflect.Descriptor instead.+func (*ClipOffer) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{20}+}++func (x *ClipOffer) GetClipId() string {+ if x != nil {+ return x.ClipId+ }+ return ""+}++func (x *ClipOffer) GetKind() ClipKind {+ if x != nil {+ return x.Kind+ }+ return ClipKind_CLIP_KIND_UNSPECIFIED+}++func (x *ClipOffer) GetItems() []*ClipItem {+ if x != nil {+ return x.Items+ }+ return nil+}++func (x *ClipOffer) GetTotalSize() int64 {+ if x != nil {+ return x.TotalSize+ }+ return 0+}++func (x *ClipOffer) GetTextContent() string {+ if x != nil {+ return x.TextContent+ }+ return ""+}++func (x *ClipOffer) GetCreatedAtUnix() int64 {+ if x != nil {+ return x.CreatedAtUnix+ }+ return 0+}++func (x *ClipOffer) GetWillPush() bool {+ if x != nil {+ return x.WillPush+ }+ return false+}++func (x *ClipOffer) GetPlainText() string {+ if x != nil {+ return x.PlainText+ }+ return ""+}++// 与 daemon.proto 的 FetchRequest(UI→daemon)区分:这条是 daemon→peer+type PeerFetch struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ ClipId string `protobuf:"bytes,1,opt,name=clip_id,json=clipId,proto3" json:"clip_id,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *PeerFetch) Reset() {+ *x = PeerFetch{}+ mi := &file_copysync_v1_wire_proto_msgTypes[21]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *PeerFetch) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*PeerFetch) ProtoMessage() {}++func (x *PeerFetch) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[21]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use PeerFetch.ProtoReflect.Descriptor instead.+func (*PeerFetch) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{21}+}++func (x *PeerFetch) GetClipId() string {+ if x != nil {+ return x.ClipId+ }+ return ""+}++type FetchReject struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ ClipId string `protobuf:"bytes,1,opt,name=clip_id,json=clipId,proto3" json:"clip_id,omitempty"`+ Reason string `protobuf:"bytes,2,opt,name=reason,proto3" json:"reason,omitempty"` // source_missing / expired / denied+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *FetchReject) Reset() {+ *x = FetchReject{}+ mi := &file_copysync_v1_wire_proto_msgTypes[22]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *FetchReject) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*FetchReject) ProtoMessage() {}++func (x *FetchReject) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[22]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use FetchReject.ProtoReflect.Descriptor instead.+func (*FetchReject) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{22}+}++func (x *FetchReject) GetClipId() string {+ if x != nil {+ return x.ClipId+ }+ return ""+}++func (x *FetchReject) GetReason() string {+ if x != nil {+ return x.Reason+ }+ return ""+}++// 数据流的第一条消息,之后是裸字节流直到 total_bytes+type TransferHeader struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ ClipId string `protobuf:"bytes,1,opt,name=clip_id,json=clipId,proto3" json:"clip_id,omitempty"`+ StreamId string `protobuf:"bytes,2,opt,name=stream_id,json=streamId,proto3" json:"stream_id,omitempty"`+ TotalBytes int64 `protobuf:"varint,3,opt,name=total_bytes,json=totalBytes,proto3" json:"total_bytes,omitempty"` // 压缩后的字节数;0 表示未知(流式打包)+ Compression Compression `protobuf:"varint,4,opt,name=compression,proto3,enum=copysync.v1.Compression" json:"compression,omitempty"`+ Packaging Packaging `protobuf:"varint,5,opt,name=packaging,proto3,enum=copysync.v1.Packaging" json:"packaging,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *TransferHeader) Reset() {+ *x = TransferHeader{}+ mi := &file_copysync_v1_wire_proto_msgTypes[23]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *TransferHeader) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*TransferHeader) ProtoMessage() {}++func (x *TransferHeader) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[23]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use TransferHeader.ProtoReflect.Descriptor instead.+func (*TransferHeader) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{23}+}++func (x *TransferHeader) GetClipId() string {+ if x != nil {+ return x.ClipId+ }+ return ""+}++func (x *TransferHeader) GetStreamId() string {+ if x != nil {+ return x.StreamId+ }+ return ""+}++func (x *TransferHeader) GetTotalBytes() int64 {+ if x != nil {+ return x.TotalBytes+ }+ return 0+}++func (x *TransferHeader) GetCompression() Compression {+ if x != nil {+ return x.Compression+ }+ return Compression_COMPRESSION_UNSPECIFIED+}++func (x *TransferHeader) GetPackaging() Packaging {+ if x != nil {+ return x.Packaging+ }+ return Packaging_PACKAGING_UNSPECIFIED+}++type TransferDone struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ ClipId string `protobuf:"bytes,1,opt,name=clip_id,json=clipId,proto3" json:"clip_id,omitempty"`+ StreamId string `protobuf:"bytes,2,opt,name=stream_id,json=streamId,proto3" json:"stream_id,omitempty"`+ Ok bool `protobuf:"varint,3,opt,name=ok,proto3" json:"ok,omitempty"`+ Error string `protobuf:"bytes,4,opt,name=error,proto3" json:"error,omitempty"`+ Sha256 []byte `protobuf:"bytes,5,opt,name=sha256,proto3" json:"sha256,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *TransferDone) Reset() {+ *x = TransferDone{}+ mi := &file_copysync_v1_wire_proto_msgTypes[24]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *TransferDone) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*TransferDone) ProtoMessage() {}++func (x *TransferDone) ProtoReflect() protoreflect.Message {+ mi := &file_copysync_v1_wire_proto_msgTypes[24]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use TransferDone.ProtoReflect.Descriptor instead.+func (*TransferDone) Descriptor() ([]byte, []int) {+ return file_copysync_v1_wire_proto_rawDescGZIP(), []int{24}+}++func (x *TransferDone) GetClipId() string {+ if x != nil {+ return x.ClipId+ }+ return ""+}++func (x *TransferDone) GetStreamId() string {+ if x != nil {+ return x.StreamId+ }+ return ""+}++func (x *TransferDone) GetOk() bool {+ if x != nil {+ return x.Ok+ }+ return false+}++func (x *TransferDone) GetError() string {+ if x != nil {+ return x.Error+ }+ return ""+}++func (x *TransferDone) GetSha256() []byte {+ if x != nil {+ return x.Sha256+ }+ return nil+}++var File_copysync_v1_wire_proto protoreflect.FileDescriptor++const file_copysync_v1_wire_proto_rawDesc = "" ++ "\n" ++ "\x16copysync/v1/wire.proto\x12\vcopysync.v1\x1a\x18copysync/v1/daemon.proto\"f\n" ++ "\x06Signed\x12\x18\n" ++ "\apayload\x18\x01 \x01(\fR\apayload\x12\x1c\n" ++ "\tsignature\x18\x02 \x01(\fR\tsignature\x12$\n" ++ "\x0efrom_device_id\x18\x03 \x01(\tR\ffromDeviceId\"\xbe\x02\n" ++ "\rSignalMessage\x12%\n" ++ "\x0etimestamp_unix\x18\x01 \x01(\x03R\rtimestampUnix\x12\x14\n" ++ "\x05nonce\x18\x02 \x01(\fR\x05nonce\x12 \n" ++ "\fto_device_id\x18\x03 \x01(\tR\n" ++ "toDeviceId\x12-\n" ++ "\x05offer\x18\n" ++ " \x01(\v2\x15.copysync.v1.SdpOfferH\x00R\x05offer\x120\n" ++ "\x06answer\x18\v \x01(\v2\x16.copysync.v1.SdpAnswerH\x00R\x06answer\x129\n" ++ "\tcandidate\x18\f \x01(\v2\x19.copysync.v1.IceCandidateH\x00R\tcandidate\x12'\n" ++ "\x04ping\x18\r \x01(\v2\x11.copysync.v1.PingH\x00R\x04pingB\t\n" ++ "\apayload\"G\n" ++ "\bSdpOffer\x12\x10\n" ++ "\x03sdp\x18\x01 \x01(\tR\x03sdp\x12)\n" ++ "\x10dtls_fingerprint\x18\x02 \x01(\tR\x0fdtlsFingerprint\"H\n" ++ "\tSdpAnswer\x12\x10\n" ++ "\x03sdp\x18\x01 \x01(\tR\x03sdp\x12)\n" ++ "\x10dtls_fingerprint\x18\x02 \x01(\tR\x0fdtlsFingerprint\"m\n" ++ "\fIceCandidate\x12\x1c\n" ++ "\tcandidate\x18\x01 \x01(\tR\tcandidate\x12\x17\n" ++ "\asdp_mid\x18\x02 \x01(\tR\x06sdpMid\x12&\n" ++ "\x0fsdp_mline_index\x18\x03 \x01(\rR\rsdpMlineIndex\"(\n" ++ "\x04Ping\x12 \n" ++ "\fsent_at_unix\x18\x01 \x01(\x03R\n" ++ "sentAtUnix\"\xd0\x01\n" ++ "\vClientHello\x12\x1b\n" ++ "\tdevice_id\x18\x01 \x01(\tR\bdeviceId\x12\x1f\n" ++ "\vdevice_name\x18\x02 \x01(\tR\n" ++ "deviceName\x12\x1a\n" ++ "\bplatform\x18\x03 \x01(\tR\bplatform\x12\x1d\n" ++ "\n" ++ "public_key\x18\x04 \x01(\fR\tpublicKey\x12\x1c\n" ++ "\tsignature\x18\x05 \x01(\fR\tsignature\x12*\n" ++ "\x11paired_device_ids\x18\x06 \x03(\tR\x0fpairedDeviceIds\"\x8e\x01\n" ++ "\vServerHello\x12\x1c\n" ++ "\tchallenge\x18\x01 \x01(\fR\tchallenge\x127\n" ++ "\vice_servers\x18\x02 \x03(\v2\x16.copysync.v1.IceServerR\n" ++ "iceServers\x12(\n" ++ "\x10server_time_unix\x18\x03 \x01(\x03R\x0eserverTimeUnix\"\x83\x01\n" ++ "\tIceServer\x12\x12\n" ++ "\x04urls\x18\x01 \x03(\tR\x04urls\x12\x1a\n" ++ "\busername\x18\x02 \x01(\tR\busername\x12\x1e\n" ++ "\n" ++ "credential\x18\x03 \x01(\tR\n" ++ "credential\x12&\n" ++ "\x0fexpires_at_unix\x18\x04 \x01(\x03R\rexpiresAtUnix\"C\n" ++ "\fPeerPresence\x12\x1b\n" ++ "\tdevice_id\x18\x01 \x01(\tR\bdeviceId\x12\x16\n" ++ "\x06online\x18\x02 \x01(\bR\x06online\"V\n" ++ "\x14PairingCreateRequest\x12\x1f\n" ++ "\vdevice_name\x18\x01 \x01(\tR\n" ++ "deviceName\x12\x1d\n" ++ "\n" ++ "public_key\x18\x02 \x01(\fR\tpublicKey\"S\n" ++ "\x15PairingCreateResponse\x12\x12\n" ++ "\x04code\x18\x01 \x01(\tR\x04code\x12&\n" ++ "\x0fexpires_at_unix\x18\x02 \x01(\x03R\rexpiresAtUnix\"\x87\x01\n" ++ "\x14PairingRedeemRequest\x12\x12\n" ++ "\x04code\x18\x01 \x01(\tR\x04code\x12\x1b\n" ++ "\tdevice_id\x18\x02 \x01(\tR\bdeviceId\x12\x1f\n" ++ "\vdevice_name\x18\x03 \x01(\tR\n" ++ "deviceName\x12\x1d\n" ++ "\n" ++ "public_key\x18\x04 \x01(\fR\tpublicKey\"\xb4\x01\n" ++ "\x15PairingRedeemResponse\x12$\n" ++ "\x0epeer_device_id\x18\x01 \x01(\tR\fpeerDeviceId\x12(\n" ++ "\x10peer_device_name\x18\x02 \x01(\tR\x0epeerDeviceName\x12#\n" ++ "\rpeer_platform\x18\x03 \x01(\tR\fpeerPlatform\x12&\n" ++ "\x0fpeer_public_key\x18\x04 \x01(\fR\rpeerPublicKey\"\xae\x01\n" ++ "\x0fPairingRedeemed\x12$\n" ++ "\x0epeer_device_id\x18\x01 \x01(\tR\fpeerDeviceId\x12(\n" ++ "\x10peer_device_name\x18\x02 \x01(\tR\x0epeerDeviceName\x12#\n" ++ "\rpeer_platform\x18\x03 \x01(\tR\fpeerPlatform\x12&\n" ++ "\x0fpeer_public_key\x18\x04 \x01(\fR\rpeerPublicKey\"D\n" ++ "\tIceConfig\x127\n" ++ "\vice_servers\x18\x01 \x03(\v2\x16.copysync.v1.IceServerR\n" ++ "iceServers\"\x9e\x04\n" ++ "\x0eServerEnvelope\x120\n" ++ "\x05hello\x18\x01 \x01(\v2\x18.copysync.v1.ServerHelloH\x00R\x05hello\x123\n" ++ "\tforwarded\x18\x02 \x01(\v2\x13.copysync.v1.SignedH\x00R\tforwarded\x127\n" ++ "\bpresence\x18\x03 \x01(\v2\x19.copysync.v1.PeerPresenceH\x00R\bpresence\x12M\n" ++ "\x0fpairing_created\x18\x04 \x01(\v2\".copysync.v1.PairingCreateResponseH\x00R\x0epairingCreated\x12\\\n" ++ "\x17pairing_redeemed_result\x18\x05 \x01(\v2\".copysync.v1.PairingRedeemResponseH\x00R\x15pairingRedeemedResult\x12I\n" ++ "\x10pairing_redeemed\x18\x06 \x01(\v2\x1c.copysync.v1.PairingRedeemedH\x00R\x0fpairingRedeemed\x120\n" ++ "\x05error\x18\a \x01(\v2\x18.copysync.v1.ServerErrorH\x00R\x05error\x127\n" ++ "\n" ++ "ice_config\x18\b \x01(\v2\x16.copysync.v1.IceConfigH\x00R\ticeConfigB\t\n" ++ "\apayload\"\x96\x02\n" ++ "\x0eClientEnvelope\x120\n" ++ "\x05hello\x18\x01 \x01(\v2\x18.copysync.v1.ClientHelloH\x00R\x05hello\x12/\n" ++ "\aforward\x18\x02 \x01(\v2\x13.copysync.v1.SignedH\x00R\aforward\x12J\n" ++ "\x0epairing_create\x18\x03 \x01(\v2!.copysync.v1.PairingCreateRequestH\x00R\rpairingCreate\x12J\n" ++ "\x0epairing_redeem\x18\x04 \x01(\v2!.copysync.v1.PairingRedeemRequestH\x00R\rpairingRedeemB\t\n" ++ "\apayload\";\n" ++ "\vServerError\x12\x12\n" ++ "\x04code\x18\x01 \x01(\tR\x04code\x12\x18\n" ++ "\amessage\x18\x02 \x01(\tR\amessage\"\x94\x02\n" ++ "\vPeerMessage\x12.\n" ++ "\x05offer\x18\x01 \x01(\v2\x16.copysync.v1.ClipOfferH\x00R\x05offer\x12.\n" ++ "\x05fetch\x18\x02 \x01(\v2\x16.copysync.v1.PeerFetchH\x00R\x05fetch\x122\n" ++ "\x06reject\x18\x03 \x01(\v2\x18.copysync.v1.FetchRejectH\x00R\x06reject\x125\n" ++ "\x06header\x18\x04 \x01(\v2\x1b.copysync.v1.TransferHeaderH\x00R\x06header\x12/\n" ++ "\x04done\x18\x05 \x01(\v2\x19.copysync.v1.TransferDoneH\x00R\x04doneB\t\n" ++ "\apayload\"\xa2\x02\n" ++ "\tClipOffer\x12\x17\n" ++ "\aclip_id\x18\x01 \x01(\tR\x06clipId\x12)\n" ++ "\x04kind\x18\x02 \x01(\x0e2\x15.copysync.v1.ClipKindR\x04kind\x12+\n" ++ "\x05items\x18\x03 \x03(\v2\x15.copysync.v1.ClipItemR\x05items\x12\x1d\n" ++ "\n" ++ "total_size\x18\x04 \x01(\x03R\ttotalSize\x12!\n" ++ "\ftext_content\x18\x05 \x01(\tR\vtextContent\x12&\n" ++ "\x0fcreated_at_unix\x18\x06 \x01(\x03R\rcreatedAtUnix\x12\x1b\n" ++ "\twill_push\x18\a \x01(\bR\bwillPush\x12\x1d\n" ++ "\n" ++ "plain_text\x18\b \x01(\tR\tplainText\"$\n" ++ "\tPeerFetch\x12\x17\n" ++ "\aclip_id\x18\x01 \x01(\tR\x06clipId\">\n" ++ "\vFetchReject\x12\x17\n" ++ "\aclip_id\x18\x01 \x01(\tR\x06clipId\x12\x16\n" ++ "\x06reason\x18\x02 \x01(\tR\x06reason\"\xd9\x01\n" ++ "\x0eTransferHeader\x12\x17\n" ++ "\aclip_id\x18\x01 \x01(\tR\x06clipId\x12\x1b\n" ++ "\tstream_id\x18\x02 \x01(\tR\bstreamId\x12\x1f\n" ++ "\vtotal_bytes\x18\x03 \x01(\x03R\n" ++ "totalBytes\x12:\n" ++ "\vcompression\x18\x04 \x01(\x0e2\x18.copysync.v1.CompressionR\vcompression\x124\n" ++ "\tpackaging\x18\x05 \x01(\x0e2\x16.copysync.v1.PackagingR\tpackaging\"\x82\x01\n" ++ "\fTransferDone\x12\x17\n" ++ "\aclip_id\x18\x01 \x01(\tR\x06clipId\x12\x1b\n" ++ "\tstream_id\x18\x02 \x01(\tR\bstreamId\x12\x0e\n" ++ "\x02ok\x18\x03 \x01(\bR\x02ok\x12\x14\n" ++ "\x05error\x18\x04 \x01(\tR\x05error\x12\x16\n" ++ "\x06sha256\x18\x05 \x01(\fR\x06sha256*V\n" ++ "\vCompression\x12\x1b\n" ++ "\x17COMPRESSION_UNSPECIFIED\x10\x00\x12\x14\n" ++ "\x10COMPRESSION_NONE\x10\x01\x12\x14\n" ++ "\x10COMPRESSION_ZSTD\x10\x02*L\n" ++ "\tPackaging\x12\x19\n" ++ "\x15PACKAGING_UNSPECIFIED\x10\x00\x12\x11\n" ++ "\rPACKAGING_RAW\x10\x01\x12\x11\n" ++ "\rPACKAGING_TAR\x10\x02B>Z<github.com/baiyuze/copysync/proto/gen/copysync/v1;copysyncv1b\x06proto3"++var (+ file_copysync_v1_wire_proto_rawDescOnce sync.Once+ file_copysync_v1_wire_proto_rawDescData []byte+)++func file_copysync_v1_wire_proto_rawDescGZIP() []byte {+ file_copysync_v1_wire_proto_rawDescOnce.Do(func() {+ file_copysync_v1_wire_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_copysync_v1_wire_proto_rawDesc), len(file_copysync_v1_wire_proto_rawDesc)))+ })+ return file_copysync_v1_wire_proto_rawDescData+}++var file_copysync_v1_wire_proto_enumTypes = make([]protoimpl.EnumInfo, 2)+var file_copysync_v1_wire_proto_msgTypes = make([]protoimpl.MessageInfo, 25)+var file_copysync_v1_wire_proto_goTypes = []any{+ (Compression)(0), // 0: copysync.v1.Compression+ (Packaging)(0), // 1: copysync.v1.Packaging+ (*Signed)(nil), // 2: copysync.v1.Signed+ (*SignalMessage)(nil), // 3: copysync.v1.SignalMessage+ (*SdpOffer)(nil), // 4: copysync.v1.SdpOffer+ (*SdpAnswer)(nil), // 5: copysync.v1.SdpAnswer+ (*IceCandidate)(nil), // 6: copysync.v1.IceCandidate+ (*Ping)(nil), // 7: copysync.v1.Ping+ (*ClientHello)(nil), // 8: copysync.v1.ClientHello+ (*ServerHello)(nil), // 9: copysync.v1.ServerHello+ (*IceServer)(nil), // 10: copysync.v1.IceServer+ (*PeerPresence)(nil), // 11: copysync.v1.PeerPresence+ (*PairingCreateRequest)(nil), // 12: copysync.v1.PairingCreateRequest+ (*PairingCreateResponse)(nil), // 13: copysync.v1.PairingCreateResponse+ (*PairingRedeemRequest)(nil), // 14: copysync.v1.PairingRedeemRequest+ (*PairingRedeemResponse)(nil), // 15: copysync.v1.PairingRedeemResponse+ (*PairingRedeemed)(nil), // 16: copysync.v1.PairingRedeemed+ (*IceConfig)(nil), // 17: copysync.v1.IceConfig+ (*ServerEnvelope)(nil), // 18: copysync.v1.ServerEnvelope+ (*ClientEnvelope)(nil), // 19: copysync.v1.ClientEnvelope+ (*ServerError)(nil), // 20: copysync.v1.ServerError+ (*PeerMessage)(nil), // 21: copysync.v1.PeerMessage+ (*ClipOffer)(nil), // 22: copysync.v1.ClipOffer+ (*PeerFetch)(nil), // 23: copysync.v1.PeerFetch+ (*FetchReject)(nil), // 24: copysync.v1.FetchReject+ (*TransferHeader)(nil), // 25: copysync.v1.TransferHeader+ (*TransferDone)(nil), // 26: copysync.v1.TransferDone+ (ClipKind)(0), // 27: copysync.v1.ClipKind+ (*ClipItem)(nil), // 28: copysync.v1.ClipItem+}+var file_copysync_v1_wire_proto_depIdxs = []int32{+ 4, // 0: copysync.v1.SignalMessage.offer:type_name -> copysync.v1.SdpOffer+ 5, // 1: copysync.v1.SignalMessage.answer:type_name -> copysync.v1.SdpAnswer+ 6, // 2: copysync.v1.SignalMessage.candidate:type_name -> copysync.v1.IceCandidate+ 7, // 3: copysync.v1.SignalMessage.ping:type_name -> copysync.v1.Ping+ 10, // 4: copysync.v1.ServerHello.ice_servers:type_name -> copysync.v1.IceServer+ 10, // 5: copysync.v1.IceConfig.ice_servers:type_name -> copysync.v1.IceServer+ 9, // 6: copysync.v1.ServerEnvelope.hello:type_name -> copysync.v1.ServerHello+ 2, // 7: copysync.v1.ServerEnvelope.forwarded:type_name -> copysync.v1.Signed+ 11, // 8: copysync.v1.ServerEnvelope.presence:type_name -> copysync.v1.PeerPresence+ 13, // 9: copysync.v1.ServerEnvelope.pairing_created:type_name -> copysync.v1.PairingCreateResponse+ 15, // 10: copysync.v1.ServerEnvelope.pairing_redeemed_result:type_name -> copysync.v1.PairingRedeemResponse+ 16, // 11: copysync.v1.ServerEnvelope.pairing_redeemed:type_name -> copysync.v1.PairingRedeemed+ 20, // 12: copysync.v1.ServerEnvelope.error:type_name -> copysync.v1.ServerError+ 17, // 13: copysync.v1.ServerEnvelope.ice_config:type_name -> copysync.v1.IceConfig+ 8, // 14: copysync.v1.ClientEnvelope.hello:type_name -> copysync.v1.ClientHello+ 2, // 15: copysync.v1.ClientEnvelope.forward:type_name -> copysync.v1.Signed+ 12, // 16: copysync.v1.ClientEnvelope.pairing_create:type_name -> copysync.v1.PairingCreateRequest+ 14, // 17: copysync.v1.ClientEnvelope.pairing_redeem:type_name -> copysync.v1.PairingRedeemRequest+ 22, // 18: copysync.v1.PeerMessage.offer:type_name -> copysync.v1.ClipOffer+ 23, // 19: copysync.v1.PeerMessage.fetch:type_name -> copysync.v1.PeerFetch+ 24, // 20: copysync.v1.PeerMessage.reject:type_name -> copysync.v1.FetchReject+ 25, // 21: copysync.v1.PeerMessage.header:type_name -> copysync.v1.TransferHeader+ 26, // 22: copysync.v1.PeerMessage.done:type_name -> copysync.v1.TransferDone+ 27, // 23: copysync.v1.ClipOffer.kind:type_name -> copysync.v1.ClipKind+ 28, // 24: copysync.v1.ClipOffer.items:type_name -> copysync.v1.ClipItem+ 0, // 25: copysync.v1.TransferHeader.compression:type_name -> copysync.v1.Compression+ 1, // 26: copysync.v1.TransferHeader.packaging:type_name -> copysync.v1.Packaging+ 27, // [27:27] is the sub-list for method output_type+ 27, // [27:27] is the sub-list for method input_type+ 27, // [27:27] is the sub-list for extension type_name+ 27, // [27:27] is the sub-list for extension extendee+ 0, // [0:27] is the sub-list for field type_name+}++func init() { file_copysync_v1_wire_proto_init() }+func file_copysync_v1_wire_proto_init() {+ if File_copysync_v1_wire_proto != nil {+ return+ }+ file_copysync_v1_daemon_proto_init()+ file_copysync_v1_wire_proto_msgTypes[1].OneofWrappers = []any{+ (*SignalMessage_Offer)(nil),+ (*SignalMessage_Answer)(nil),+ (*SignalMessage_Candidate)(nil),+ (*SignalMessage_Ping)(nil),+ }+ file_copysync_v1_wire_proto_msgTypes[16].OneofWrappers = []any{+ (*ServerEnvelope_Hello)(nil),+ (*ServerEnvelope_Forwarded)(nil),+ (*ServerEnvelope_Presence)(nil),+ (*ServerEnvelope_PairingCreated)(nil),+ (*ServerEnvelope_PairingRedeemedResult)(nil),+ (*ServerEnvelope_PairingRedeemed)(nil),+ (*ServerEnvelope_Error)(nil),+ (*ServerEnvelope_IceConfig)(nil),+ }+ file_copysync_v1_wire_proto_msgTypes[17].OneofWrappers = []any{+ (*ClientEnvelope_Hello)(nil),+ (*ClientEnvelope_Forward)(nil),+ (*ClientEnvelope_PairingCreate)(nil),+ (*ClientEnvelope_PairingRedeem)(nil),+ }+ file_copysync_v1_wire_proto_msgTypes[19].OneofWrappers = []any{+ (*PeerMessage_Offer)(nil),+ (*PeerMessage_Fetch)(nil),+ (*PeerMessage_Reject)(nil),+ (*PeerMessage_Header)(nil),+ (*PeerMessage_Done)(nil),+ }+ type x struct{}+ out := protoimpl.TypeBuilder{+ File: protoimpl.DescBuilder{+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),+ RawDescriptor: unsafe.Slice(unsafe.StringData(file_copysync_v1_wire_proto_rawDesc), len(file_copysync_v1_wire_proto_rawDesc)),+ NumEnums: 2,+ NumMessages: 25,+ NumExtensions: 0,+ NumServices: 0,+ },+ GoTypes: file_copysync_v1_wire_proto_goTypes,+ DependencyIndexes: file_copysync_v1_wire_proto_depIdxs,+ EnumInfos: file_copysync_v1_wire_proto_enumTypes,+ MessageInfos: file_copysync_v1_wire_proto_msgTypes,+ }.Build()+ File_copysync_v1_wire_proto = out.File+ file_copysync_v1_wire_proto_goTypes = nil+ file_copysync_v1_wire_proto_depIdxs = nil+}diff --git a/proto/go.mod b/proto/go.modnew file mode 100644index 0000000..aec562a--- /dev/null+++ b/proto/go.mod@@ -0,0 +1,15 @@+module github.com/baiyuze/copysync/proto++go 1.26.3++require (+ google.golang.org/grpc v1.84.0+ google.golang.org/protobuf v1.36.12+)++require (+ golang.org/x/net v0.57.0 // indirect+ golang.org/x/sys v0.47.0 // indirect+ golang.org/x/text v0.40.0 // indirect+ google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800 // indirect+)diff --git a/proto/go.sum b/proto/go.sumnew file mode 100644index 0000000..4f06a88--- /dev/null+++ b/proto/go.sum@@ -0,0 +1,18 @@+github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=+github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=+golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=+golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=+golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=+golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=+golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=+golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=+gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=+gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=+google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800 h1:qEHAMpSaUhtD0p3NbEEI83HwNGFxEwaSJ1G9PLnCBZE=+google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=+google.golang.org/grpc v1.84.0 h1:soMyaPJ8pAak5PIQ0DGBUir0XRo2fRoMqhNWMLlLxO0=+google.golang.org/grpc v1.84.0/go.mod h1:ljCht0DrxQrXBDRTZp52Qxh3Ffk8CdYm2sj4O2QN2C0=+google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=+google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=diff --git a/scripts/build.sh b/scripts/build.shnew file mode 100755index 0000000..1673b6d--- /dev/null+++ b/scripts/build.sh@@ -0,0 +1,107 @@+#!/usr/bin/env bash+# 构建全部产物到 dist/。+#+# dist/CopySync.app 发给用户的 App:界面 + 内置的后台服务与命令行工具+# dist/CopySyncDaemon.app 后台服务单独一份,供 install-macos.sh 在开发时安装+# dist/copysync-server 信令 + TURN 中转服务器(macOS 版)+# dist/copysync-cli 调试用命令行+#+# daemon 刻意打包成 .app 而非裸二进制:macOS 的剪贴板授权(TCC)以+# bundle identifier 为主体,下个大版本起剪贴板隐私机制将强制执行,+# 届时没有稳定 bundle id 的进程无法保留用户的授权选择。++set -euo pipefail+cd "$(dirname "$0")/.."++DIST=dist+VERSION=${VERSION:-1.0.0}+rm -rf "$DIST" && mkdir -p "$DIST"++# 构建 x86_64 + arm64 通用二进制:两台 Mac 的芯片未必相同,单架构的+# daemon 到 Apple Silicon 上要靠 Rosetta,而 Rosetta 默认并未安装。+# daemon 含 cgo,交叉编译时必须给 clang 显式指定 -arch。+build_universal() { # <模块目录> <包路径> <输出路径> <ldflags>+ local dir=$1 pkg=$2 out=$3 ldflags=$4 tmp+ tmp=$(mktemp -d)+ for arch in amd64 arm64; do+ local clang_arch=$arch+ [[ $arch == amd64 ]] && clang_arch=x86_64+ (cd "$dir" && CGO_ENABLED=1 GOOS=darwin GOARCH=$arch CC="clang -arch $clang_arch" \+ go build -trimpath -ldflags "$ldflags" -o "$tmp/$arch" "$pkg")+ done+ lipo -create -output "$out" "$tmp/amd64" "$tmp/arm64"+ rm -rf "$tmp"+}++echo "▶ 构建 daemon"+build_universal client-core ./cmd/copysyncd "$DIST/copysyncd" \+ "-s -w -X main.version=$VERSION"++echo "▶ 构建 CLI"+build_universal client-core ./cmd/copysync-cli "$DIST/copysync-cli" "-s -w"++echo "▶ 构建服务器"+build_universal server ./cmd/copysync-server "$DIST/copysync-server" \+ "-s -w -X main.version=$VERSION"++# ── 把 daemon 包成 .app ──+APP="$DIST/CopySyncDaemon.app"+mkdir -p "$APP/Contents/MacOS"+mv "$DIST/copysyncd" "$APP/Contents/MacOS/copysyncd"+cat > "$APP/Contents/Info.plist" <<PLIST+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleExecutable</key> <string>copysyncd</string>+ <key>CFBundleIdentifier</key> <string>com.copysync.daemon</string>+ <key>CFBundleName</key> <string>CopySync Daemon</string>+ <key>CFBundleIconFile</key> <string>AppIcon</string>+ <key>CFBundlePackageType</key> <string>APPL</string>+ <key>CFBundleShortVersionString</key> <string>$VERSION</string>+ <key>CFBundleVersion</key> <string>$VERSION</string>+ <key>LSMinimumSystemVersion</key> <string>13.0</string>+ <!-- 后台常驻:不出现在 Dock 与任务切换器里 -->+ <key>LSUIElement</key> <true/>+</dict>+</plist>+PLIST+# 系统设置的「隐私与安全性」列表里会显示后台服务,给它同一个图标+mkdir -p "$APP/Contents/Resources"+cp assets/brand/AppIcon.icns "$APP/Contents/Resources/AppIcon.icns"+# ad-hoc 签名即可让 TCC 记住授权决定;正式分发应换成 Developer ID+codesign --force --sign - "$APP"+echo " ✓ $APP"++echo "▶ 构建图形界面"+(cd ui && flutter build macos --release \+ --build-name "$VERSION" --dart-define=APP_VERSION="$VERSION" 2>&1 | tail -1)+UI="$DIST/CopySync.app"+cp -R ui/build/macos/Build/Products/Release/CopySync.app "$UI"++# 后台服务与命令行工具内置进 App:用户只需把一个 App 拖进「应用程序」,+# 首次打开时由界面把后台服务注册为登录项(见 ui/lib/background_service.dart)+mkdir -p "$UI/Contents/Helpers"+cp -R "$APP" "$UI/Contents/Helpers/"+cp "$DIST/copysync-cli" "$UI/Contents/Helpers/copysync-cli"++# 签名由内向外:先签内置的组件,最后签外层 App。+# Flutter 增量构建在 Dart 代码变化后会重新生成 App.framework 却不重签,+# 留下失效签名,Apple Silicon 上会直接拒绝运行,这里一并重签。+codesign --force --sign - "$UI/Contents/Helpers/copysync-cli"+codesign --force --sign - "$UI/Contents/Helpers/CopySyncDaemon.app"+codesign --force --sign - "$UI/Contents/Frameworks/App.framework"+codesign --force --sign - --preserve-metadata=entitlements,requirements,flags "$UI"+codesign --verify --deep --strict "$UI" "$APP"+echo " ✓ $UI"++echo+echo "完成。产物:"+ls -1 "$DIST"+cat <<'EOF'++下一步:+ open dist/CopySync.app 首次打开会引导启用后台同步+ ./scripts/package.sh 打出 DMG 与服务器发布包+ ./dist/copysync-server -h 查看服务器参数+EOFdiff --git a/scripts/gen-proto.sh b/scripts/gen-proto.shnew file mode 100755index 0000000..63d4017--- /dev/null+++ b/scripts/gen-proto.sh@@ -0,0 +1,35 @@+#!/usr/bin/env bash+# 由 .proto 生成 Go 与 Dart 代码。+#+# 用 buf 而非 protoc:这台开发机访问不到 GitHub releases(下载预编译 protoc 超时),+# 而 Homebrew 在 Intel Mac 上没有 protobuf 预编译包、需从源码编译十余分钟。+# buf 是纯 Go 实现,可经 goproxy.cn 用 go install 装上,自带 protobuf 编译器。+#+# 首次准备环境:+# go install github.com/bufbuild/buf/cmd/buf@latest+# go install google.golang.org/protobuf/cmd/protoc-gen-go@latest+# go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest+# dart pub global activate protoc_plugin++set -euo pipefail+cd "$(dirname "$0")/.."++export PATH="$PATH:$(go env GOPATH)/bin:$HOME/.pub-cache/bin"++for tool in buf protoc-gen-go protoc-gen-go-grpc protoc-gen-dart; do+ command -v "$tool" >/dev/null || {+ echo "缺少 $tool —— 见本脚本顶部的环境准备步骤" >&2+ exit 1+ }+done++echo "▶ lint"+buf lint proto++echo "▶ 生成"+mkdir -p ui/lib/gen+buf generate proto++echo "✓ 完成"+echo " Go : $(find proto/gen -name '*.go' | wc -l | tr -d ' ') 个文件"+echo " Dart : $(find ui/lib/gen -name '*.dart' | wc -l | tr -d ' ') 个文件"diff --git a/scripts/install-macos.sh b/scripts/install-macos.shnew file mode 100755index 0000000..f511b58--- /dev/null+++ b/scripts/install-macos.sh@@ -0,0 +1,88 @@+#!/usr/bin/env bash+# 把 daemon 安装到用户目录并注册为开机自启(launchd LaunchAgent)。+#+# 用 LaunchAgent 而非 LaunchDaemon:剪贴板属于用户会话,+# 系统级守护进程根本访问不到登录用户的剪贴板。++set -euo pipefail+HERE="$(cd "$(dirname "$0")" && pwd)"++# 发布包里 app 与本脚本同级;源码仓库里则在 dist/ 下+if [[ -d "$HERE/CopySyncDaemon.app" ]]; then+ APP_SRC="$HERE/CopySyncDaemon.app"+else+ APP_SRC="$HERE/../dist/CopySyncDaemon.app"+fi+INSTALL_DIR="$HOME/Applications"+APP_DST="$INSTALL_DIR/CopySyncDaemon.app"+BIN="$APP_DST/Contents/MacOS/copysyncd"+LABEL="com.copysync.daemon"+PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"+LOG_DIR="$HOME/Library/Logs/CopySync"++[[ -d "$APP_SRC" ]] || { echo "找不到 $APP_SRC,请先运行 ./scripts/build.sh"; exit 1; }++echo "▶ 停止已在运行的实例"+launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || true+pkill -f copysyncd 2>/dev/null || true+# bootout 是异步的:旧服务没注销干净就 bootstrap 会报 "Bootstrap failed: 5"+for _ in {1..20}; do+ launchctl print "gui/$(id -u)/$LABEL" &>/dev/null || break+ sleep 0.25+done++echo "▶ 安装到 $APP_DST"+mkdir -p "$INSTALL_DIR" "$LOG_DIR"+rm -rf "$APP_DST"+cp -R "$APP_SRC" "$APP_DST"+# 经 AirDrop、浏览器、聊天软件传过来的包带隔离属性,ad-hoc 签名的 app+# 会被 Gatekeeper 拦下,而 launchd 拉起时没有弹窗让用户放行+xattr -dr com.apple.quarantine "$APP_DST" 2>/dev/null || true++echo "▶ 写入 LaunchAgent"+cat > "$PLIST" <<PLIST+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key> <string>$LABEL</string>+ <key>ProgramArguments</key>+ <array>+ <string>$BIN</string>+ </array>+ <key>RunAtLoad</key> <true/>+ <key>KeepAlive</key> <true/>+ <!-- 崩溃后不要疯狂重启,给系统留出喘息 -->+ <key>ThrottleInterval</key> <integer>10</integer>+ <key>StandardOutPath</key> <string>$LOG_DIR/daemon.log</string>+ <key>StandardErrorPath</key> <string>$LOG_DIR/daemon.log</string>+ <key>ProcessType</key> <string>Interactive</string>+</dict>+</plist>+PLIST++echo "▶ 启动"+launchctl bootstrap "gui/$(id -u)" "$PLIST"+sleep 2++if pgrep -f copysyncd > /dev/null; then+ echo " ✓ daemon 已启动"+else+ echo " ✗ 启动失败,查看 $LOG_DIR/daemon.log"+ exit 1+fi++cat <<EOF++安装完成。++ 日志 $LOG_DIR/daemon.log+ 数据目录 ~/Library/Application Support/CopySync+ 停止 launchctl bootout gui/\$(id -u)/$LABEL+ 卸载 上面的命令 + rm -rf "$APP_DST" "$PLIST"++接下来:+ 1. 打开 CopySync.app 配置信令服务器地址并配对设备+ 2. 若系统弹出「想要从其他 App 粘贴」,选择允许;+ 之后可在 系统设置 → 隐私与安全性 → 从其他 App 粘贴 中改为「始终允许」+EOFdiff --git a/scripts/package.sh b/scripts/package.shnew file mode 100755index 0000000..ddf5112--- /dev/null+++ b/scripts/package.sh@@ -0,0 +1,115 @@+#!/usr/bin/env bash+# 构建并打出可分发的发布包到 release/。+#+# CopySync-<版本>.dmg macOS 客户端,Intel 与 Apple 芯片通用+# copysync-server-<版本>-linux-amd64.tar.gz 信令服务器 + systemd / Docker 部署文件+# copysync-server-<版本>-linux-arm64.tar.gz+# copysync-server-<版本>-macos.tar.gz 把服务器放在其中一台 Mac 上时用+# SHA256SUMS+#+# 服务器是纯 Go,直接交叉编译;客户端依赖 cgo 与 Flutter,只能在 Mac 上构建。++set -euo pipefail+cd "$(dirname "$0")/.."++export VERSION=${VERSION:-1.0.0}+OUT=release++./scripts/build.sh+echo++rm -rf "$OUT" && mkdir -p "$OUT"+STAGE=$(mktemp -d)+trap 'rm -rf "$STAGE"' EXIT++# ─────────────────────────── DMG ───────────────────────────++# Finder 窗口的版式与 tools/dmg/background.swift 画的背景一一对应。+# 需要「自动化」权限去控制 Finder;拿不到就跳过,DMG 照样能装,只是图标排布是默认的。+layout_dmg() {+ osascript >/dev/null <<EOF &+tell application "Finder"+ tell disk "$1"+ open+ set current view of container window to icon view+ set toolbar visible of container window to false+ set statusbar visible of container window to false+ set bounds of container window to {200, 120, 840, 548}+ set opts to icon view options of container window+ set arrangement of opts to not arranged+ set icon size of opts to 112+ set text size of opts to 13+ set background picture of opts to file ".background:background.tiff"+ set position of item "CopySync.app" of container window to {160, 190}+ set position of item "Applications" of container window to {480, 190}+ update without registering applications+ delay 1+ close+ end tell+end tell+EOF+ local pid=$!+ for _ in {1..60}; do+ kill -0 "$pid" 2>/dev/null || { wait "$pid"; return $?; }+ sleep 1+ done+ kill "$pid" 2>/dev/null+ return 1+}++echo "▶ 打包 DMG"+VOL=CopySync+SRC="$STAGE/dmg"+mkdir -p "$SRC/.background"+ditto dist/CopySync.app "$SRC/CopySync.app"+ln -s /Applications "$SRC/Applications"+swift tools/dmg/background.swift "$STAGE/bg" >/dev/null+tiffutil -cathidpicheck "$STAGE/bg/background.png" "$STAGE/bg/[email protected]" \+ -out "$SRC/.background/background.tiff" 2>/dev/null++# 同名的卷还挂着的话,Finder 会把布局写到另一个窗口上+hdiutil detach "/Volumes/$VOL" -quiet 2>/dev/null || true+hdiutil create -volname "$VOL" -srcfolder "$SRC" -fs HFS+ -format UDRW -ov "$STAGE/rw.dmg" -quiet+MNT=$(hdiutil attach "$STAGE/rw.dmg" -readwrite -noverify -noautoopen | awk -F'\t' '/\/Volumes\//{print $NF}')+if layout_dmg "$VOL"; then+ echo " ✓ 安装窗口布局"+else+ echo " ! 没能设置安装窗口布局(Finder 自动化权限未授予),DMG 仍可正常安装"+fi+# 卷图标放在布局之后:-srcfolder 不会带上 .VolumeIcon.icns,+# 而 Finder 保存布局时又会清掉卷的自定义图标标记+cp assets/brand/AppIcon.icns "$MNT/.VolumeIcon.icns"+SetFile -a C "$MNT"+rm -rf "$MNT/.fseventsd"+sync+hdiutil detach "$MNT" -quiet+hdiutil convert "$STAGE/rw.dmg" -format UDZO -imagekey zlib-level=9 \+ -o "$OUT/CopySync-$VERSION.dmg" -quiet+echo " ✓ CopySync-$VERSION.dmg"++# ─────────────────────────── 服务器 ───────────────────────────++echo "▶ 打包服务器"+for arch in amd64 arm64; do+ name="copysync-server-$VERSION-linux-$arch"+ d="$STAGE/$name"+ mkdir -p "$d"+ (cd server && CGO_ENABLED=0 GOOS=linux GOARCH=$arch go build -trimpath \+ -ldflags "-s -w -X main.version=$VERSION" \+ -o "$d/copysync-server" ./cmd/copysync-server)+ cp server/deploy/{install.sh,copysync-server.service,Dockerfile,docker-compose.yml,env.example,README.md} "$d/"+ tar -C "$STAGE" -czf "$OUT/$name.tar.gz" "$name"+ echo " ✓ $name.tar.gz"+done++name="copysync-server-$VERSION-macos"+mkdir -p "$STAGE/$name"+cp dist/copysync-server server/deploy/README.md "$STAGE/$name/"+tar -C "$STAGE" -czf "$OUT/$name.tar.gz" "$name"+echo " ✓ $name.tar.gz"++(cd "$OUT" && shasum -a 256 -- * > SHA256SUMS)++echo+echo "完成。发布包:"+ls -lh "$OUT" | tail -n +2diff --git a/server/cmd/copysync-server/main.go b/server/cmd/copysync-server/main.gonew file mode 100644index 0000000..7a82540--- /dev/null+++ b/server/cmd/copysync-server/main.go@@ -0,0 +1,173 @@+// copysync-server 是 CopySync 的信令服务器。+//+// 它只做三件事:校验连上来的设备确实持有其声称公钥的私钥、+// 转达配对码、在设备间转发带签名的信令。它不存用户,+// 也读不懂设备间传输的内容——P2P 打通后数据根本不经过它,+// 打不通时走 TURN 中转,而 TURN 只转发 UDP 包,看不到 DTLS 内层。+package main++import (+ "context"+ "crypto/rand"+ "encoding/hex"+ "errors"+ "flag"+ "fmt"+ "log/slog"+ "net/http"+ "os"+ ossignal "os/signal" // 与内部的 signal 包重名,加别名区分+ "strings"+ "syscall"+ "time"++ pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"+ "github.com/baiyuze/copysync/server/relay"+ "github.com/baiyuze/copysync/server/signal"+)++var version = "0.1.0-dev"++func main() {+ var (+ addr = flag.String("addr", ":8787", "HTTP 监听地址")+ stunURLs = flag.String("stun", "stun:stun.l.google.com:19302",+ "STUN 服务器,逗号分隔")+ turnIP = flag.String("turn-ip", "",+ "TURN 对外公布的公网地址。留空则不启用中转,P2P 打不通时将无法传输")+ turnPort = flag.Int("turn-port", 3478, "TURN 监听端口")+ turnSecret = flag.String("turn-secret", "",+ "TURN 凭证派生密钥。留空自动生成(重启后已签发的凭证失效)")+ verbose = flag.Bool("v", false, "输出调试日志")+ showVersion = flag.Bool("version", false, "打印版本号后退出")+ )+ flag.Parse()++ if *showVersion {+ fmt.Println("copysync-server", version)+ return+ }++ level := slog.LevelInfo+ if *verbose {+ level = slog.LevelDebug+ }+ log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: level}))+ slog.SetDefault(log)++ cfg := serverConfig{+ addr: *addr,+ stunURLs: *stunURLs,+ turnIP: *turnIP,+ turnPort: *turnPort,+ turnSecret: *turnSecret,+ }+ if err := run(cfg, log); err != nil {+ log.Error("服务器退出", "err", err)+ os.Exit(1)+ }+}++type serverConfig struct {+ addr string+ stunURLs string+ turnIP string+ turnPort int+ turnSecret string+}++func run(cfg serverConfig, log *slog.Logger) error {+ ctx, stop := ossignal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)+ defer stop()++ stun := splitNonEmpty(cfg.stunURLs)++ // TURN 中转:P2P 打洞失败时兜底。它只转发 UDP 包,看不到 DTLS 内层明文。+ var turnSrv *relay.Server+ if cfg.turnIP != "" {+ secret := cfg.turnSecret+ if secret == "" {+ buf := make([]byte, 32)+ if _, err := rand.Read(buf); err != nil {+ return err+ }+ secret = hex.EncodeToString(buf)+ log.Warn("未指定 -turn-secret,已自动生成;重启后先前签发的凭证会失效")+ }+ var err error+ turnSrv, err = relay.New(relay.Options{+ PublicIP: cfg.turnIP,+ Port: cfg.turnPort,+ Secret: secret,+ Logger: log,+ })+ if err != nil {+ return err+ }+ defer turnSrv.Close()+ } else {+ log.Warn("未配置 -turn-ip,仅提供 STUN;对称 NAT 环境下设备可能无法互通")+ }++ sig := signal.NewServer(signal.Options{+ Logger: log,+ // 每台设备拿到的 TURN 凭证都是按其 device_id 单独签发、带有效期的+ ICEServers: func(deviceID string) []*pb.IceServer {+ var servers []*pb.IceServer+ if len(stun) > 0 {+ servers = append(servers, &pb.IceServer{Urls: stun})+ }+ if turnSrv != nil {+ c := turnSrv.Issue(deviceID)+ servers = append(servers, &pb.IceServer{+ Urls: c.URLs,+ Username: c.Username,+ Credential: c.Password,+ ExpiresAtUnix: c.ExpiresAt.Unix(),+ })+ }+ return servers+ },+ })++ mux := http.NewServeMux()+ mux.Handle("/signal", sig)+ mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{"status":"ok","version":"` + version + `"}`))+ })++ srv := &http.Server{+ Addr: cfg.addr,+ Handler: mux,+ // WebSocket 是长连接,不能设 WriteTimeout;+ // 空闲与读头超时仍然保留,防止慢速连接耗尽资源。+ ReadHeaderTimeout: 10 * time.Second,+ IdleTimeout: 2 * time.Minute,+ }++ go func() {+ <-ctx.Done()+ shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ _ = srv.Shutdown(shutdownCtx)+ }()++ log.Info("信令服务器已启动", "addr", cfg.addr, "stun", stun,+ "turn", cfg.turnIP != "", "version", version)+ if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {+ return err+ }+ log.Info("已停止")+ return nil+}++func splitNonEmpty(s string) []string {+ var out []string+ for _, p := range strings.Split(s, ",") {+ if p = strings.TrimSpace(p); p != "" {+ out = append(out, p)+ }+ }+ return out+}diff --git a/server/deploy/Dockerfile b/server/deploy/Dockerfilenew file mode 100644index 0000000..867a368--- /dev/null+++ b/server/deploy/Dockerfile@@ -0,0 +1,10 @@+# 发布包里的 copysync-server 是静态链接的 Linux 二进制,直接放进空镜像即可。+#+# docker compose up -d+#+# 也可以从源码构建:在仓库根目录执行+# docker build -f server/deploy/Dockerfile.source -t copysync-server .+FROM scratch+COPY copysync-server /copysync-server+EXPOSE 8787/tcp 3478/udp+ENTRYPOINT ["/copysync-server"]diff --git a/server/deploy/Dockerfile.source b/server/deploy/Dockerfile.sourcenew file mode 100644index 0000000..d52ffc8--- /dev/null+++ b/server/deploy/Dockerfile.source@@ -0,0 +1,16 @@+# 从源码构建服务器镜像。在仓库根目录执行:+#+# docker build -f server/deploy/Dockerfile.source -t copysync-server .+FROM golang:1.26 AS build+WORKDIR /src+COPY proto ./proto+COPY server ./server+ARG VERSION=dev+RUN cd server && CGO_ENABLED=0 go build -trimpath \+ -ldflags "-s -w -X main.version=${VERSION}" \+ -o /out/copysync-server ./cmd/copysync-server++FROM scratch+COPY --from=build /out/copysync-server /copysync-server+EXPOSE 8787/tcp 3478/udp+ENTRYPOINT ["/copysync-server"]diff --git a/server/deploy/README.md b/server/deploy/README.mdnew file mode 100644index 0000000..3efae76--- /dev/null+++ b/server/deploy/README.md@@ -0,0 +1,73 @@+# CopySync 服务器部署 / Server deployment++CopySync 的服务器只做两件事:让你的设备找到彼此(信令),以及在设备之间打不通直连时转发加密后的数据(TURN 中转)。它不存账号,也看不到你复制的内容。++The server only does two things: it lets your devices find each other (signaling), and relays encrypted traffic when a direct connection can't be established (TURN). It keeps no accounts and cannot read what you copy.++## 需要准备 / Requirements++- 一台两端设备都能访问到的机器。同一局域网内的话,用其中一台 Mac 也行。+- 跨公网使用时需要公网 IP,并放行以下端口:++| 端口 Port | 协议 | 用途 Purpose |+|---|---|---|+| 8787 | TCP | 信令 Signaling (WebSocket) |+| 3478 | UDP | STUN / TURN |+| 32768–60999 | UDP | TURN 中转端口,系统随机分配 / relay ports, assigned by the OS |++内存占用约 15 MB,1 核 512 MB 的机器足够。 Uses about 15 MB of RAM; the smallest VPS is enough.++## 方式一:systemd(推荐) / Option 1: systemd (recommended)++```bash+tar xzf copysync-server-*-linux-amd64.tar.gz+cd copysync-server-*-linux-amd64+sudo ./install.sh <公网IP / public IP>+```++脚本会把程序装到 `/usr/local/bin`,生成配置 `/etc/copysync/server.env`(含随机的 TURN 密钥),注册为开机自启的 systemd 服务。重复执行即为升级,已有配置不会被覆盖。++The script installs the binary to `/usr/local/bin`, writes `/etc/copysync/server.env` with a random TURN secret, and registers a systemd service that starts on boot. Running it again upgrades in place and keeps your config.++```bash+journalctl -u copysync-server -f # 日志 / logs+systemctl restart copysync-server # 改完配置后重启 / restart after editing config+copysync-server -version # 版本 / version+```++## 方式二:Docker / Option 2: Docker++```bash+cp env.example .env # 填入 TURN_IP 与 TURN_SECRET / set TURN_IP and TURN_SECRET+docker compose up -d+```++必须使用 `network_mode: host`(compose 文件里已经写好):TURN 为每个会话随机分配 UDP 端口,端口映射模式下这些端口不可达。++`network_mode: host` is required (already set in the compose file): TURN assigns a random UDP port per session, which port mapping can't expose.++## 方式三:直接运行 / Option 3: run it directly++```bash+./copysync-server -addr :8787 -turn-ip <公网IP> -turn-secret <随机字符串>+```++只在局域网内使用、不需要中转时,`-turn-ip` 可以省略。 On a LAN you can omit `-turn-ip`; relaying won't be available.++## 客户端设置 / Client setup++在每台 Mac 上打开 CopySync →「设置」→「信令服务器地址」,填入:++```+ws://<服务器地址>:8787/signal+```++放在 HTTPS 反向代理后面时用 `wss://`,代理需要支持 WebSocket 升级。 Behind an HTTPS reverse proxy, use `wss://` and make sure the proxy forwards WebSocket upgrades.++## 卸载 / Uninstall++```bash+sudo systemctl disable --now copysync-server+sudo rm /usr/local/bin/copysync-server /etc/systemd/system/copysync-server.service+sudo rm -r /etc/copysync+```diff --git a/server/deploy/copysync-server.service b/server/deploy/copysync-server.servicenew file mode 100644index 0000000..8136a4a--- /dev/null+++ b/server/deploy/copysync-server.service@@ -0,0 +1,21 @@+[Unit]+Description=CopySync 信令与 TURN 中转服务器+After=network-online.target+Wants=network-online.target++[Service]+# 启动参数写在这里,改完 systemctl restart copysync-server 即可+EnvironmentFile=/etc/copysync/server.env+ExecStart=/usr/local/bin/copysync-server $OPTIONS+Restart=on-failure+RestartSec=5++# 服务器不落盘、监听端口都在 1024 以上,无需任何特权+DynamicUser=yes+NoNewPrivileges=yes+ProtectSystem=strict+ProtectHome=yes+PrivateTmp=yes++[Install]+WantedBy=multi-user.targetdiff --git a/server/deploy/docker-compose.yml b/server/deploy/docker-compose.ymlnew file mode 100644index 0000000..826232e--- /dev/null+++ b/server/deploy/docker-compose.yml@@ -0,0 +1,21 @@+# CopySync 信令服务器+#+# cp env.example .env 然后把 .env 里的 TURN_IP 改成这台服务器的公网 IP+# docker compose up -d+#+# 客户端「设置」里填 ws://<公网IP>:8787/signal+#+# 必须用 host 网络:TURN 中转为每个会话随机分配 UDP 端口,+# 端口映射模式下这些端口不可达,P2P 打不通时的兜底就会失效。+services:+ copysync-server:+ build: .+ image: copysync-server:local+ container_name: copysync-server+ network_mode: host+ restart: unless-stopped+ command: >+ -addr :8787+ -turn-ip ${TURN_IP:?在 .env 中设置 TURN_IP}+ -turn-secret ${TURN_SECRET:?在 .env 中设置 TURN_SECRET}+ -stun stun:${TURN_IP}:3478,stun:stun.l.google.com:19302diff --git a/server/deploy/env.example b/server/deploy/env.examplenew file mode 100644index 0000000..904c870--- /dev/null+++ b/server/deploy/env.example@@ -0,0 +1,8 @@+# 复制为 .env 后修改。docker compose 会自动读取同目录下的 .env。++# 这台服务器的公网 IP,TURN 中转会把它告诉客户端+TURN_IP=203.0.113.10++# TURN 凭证的派生密钥,一串足够长的随机字符即可:openssl rand -hex 32+# 固定下来:每次重启都换的话,客户端手里已签发的凭证会失效+TURN_SECRET=diff --git a/server/deploy/install.sh b/server/deploy/install.shnew file mode 100755index 0000000..b0ad927--- /dev/null+++ b/server/deploy/install.sh@@ -0,0 +1,68 @@+#!/usr/bin/env bash+# 在 Linux 服务器上安装 copysync-server 并注册为 systemd 服务。+#+# sudo ./install.sh 仅信令 + STUN(同一局域网够用)+# sudo ./install.sh <公网IP> 同时启用 TURN 中转(跨公网、对称 NAT 时需要)+#+# 重复执行即为升级:替换二进制并重启,已有的 /etc/copysync/server.env 不会被覆盖。++set -euo pipefail+cd "$(dirname "$0")"++[[ $EUID -eq 0 ]] || { echo "请用 root 运行:sudo $0 $*"; exit 1; }++TURN_IP=${1:-}+ENV_FILE=/etc/copysync/server.env++echo "▶ 安装二进制到 /usr/local/bin"+install -m 755 copysync-server /usr/local/bin/copysync-server++echo "▶ 写入 systemd 单元"+install -m 644 copysync-server.service /etc/systemd/system/copysync-server.service++if [[ -f $ENV_FILE ]]; then+ echo "▶ 保留已有配置 $ENV_FILE"+else+ echo "▶ 生成配置 $ENV_FILE"+ mkdir -p /etc/copysync+ if [[ -n $TURN_IP ]]; then+ # 固定 secret:自动生成的话每次重启都会让已签发的 TURN 凭证失效+ # STUN 优先用自己:国内网络访问公共 STUN(如 Google 的)时通时断+ OPTIONS="-addr :8787 -turn-ip $TURN_IP -turn-secret $(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')"+ OPTIONS="$OPTIONS -stun stun:$TURN_IP:3478,stun:stun.l.google.com:19302"+ else+ OPTIONS="-addr :8787"+ fi+ printf 'OPTIONS="%s"\n' "$OPTIONS" > "$ENV_FILE"+ chmod 600 "$ENV_FILE"+fi++echo "▶ 启动"+systemctl daemon-reload+systemctl enable copysync-server >/dev/null+systemctl restart copysync-server+sleep 1++if systemctl is-active --quiet copysync-server; then+ echo " ✓ 已启动"+else+ echo " ✗ 启动失败,查看日志:journalctl -u copysync-server -n 50"+ exit 1+fi++cat <<EOF++安装完成:$(/usr/local/bin/copysync-server -version)+客户端「设置 → 信令服务器地址」填:ws://${TURN_IP:-<本机地址>}:8787/signal++ 配置 $ENV_FILE+ 日志 journalctl -u copysync-server -f+ 重启 systemctl restart copysync-server+ 卸载 systemctl disable --now copysync-server && rm /usr/local/bin/copysync-server /etc/systemd/system/copysync-server.service++防火墙 / 云安全组需放行:+ TCP 8787 信令(WebSocket)+ UDP 3478 TURN(仅启用中转时)+ UDP 32768-60999 TURN 中转分配的端口(仅启用中转时;由系统随机分配,+ 实际范围见 /proc/sys/net/ipv4/ip_local_port_range)+EOFdiff --git a/server/go.mod b/server/go.modnew file mode 100644index 0000000..1260894--- /dev/null+++ b/server/go.mod@@ -0,0 +1,28 @@+module github.com/baiyuze/copysync/server++go 1.26.3++replace github.com/baiyuze/copysync/proto => ../proto++require (+ github.com/baiyuze/copysync/proto v0.0.0-00010101000000-000000000000+ github.com/coder/websocket v1.8.15+ github.com/pion/turn/v4 v4.1.4+ google.golang.org/protobuf v1.36.12+)++require (+ github.com/pion/dtls/v3 v3.0.7 // indirect+ github.com/pion/logging v0.2.4 // indirect+ github.com/pion/randutil v0.1.0 // indirect+ github.com/pion/stun/v3 v3.0.1 // indirect+ github.com/pion/transport/v3 v3.0.8 // indirect+ github.com/pion/transport/v4 v4.0.1 // indirect+ github.com/wlynxg/anet v0.0.5 // indirect+ golang.org/x/crypto v0.54.0 // indirect+ golang.org/x/net v0.57.0 // indirect+ golang.org/x/sys v0.47.0 // indirect+ golang.org/x/text v0.40.0 // indirect+ google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800 // indirect+ google.golang.org/grpc v1.84.0 // indirect+)diff --git a/server/go.sum b/server/go.sumnew file mode 100644index 0000000..c4c7ea8--- /dev/null+++ b/server/go.sum@@ -0,0 +1,48 @@+github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=+github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=+github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=+github.com/pion/dtls/v3 v3.0.7 h1:bItXtTYYhZwkPFk4t1n3Kkf5TDrfj6+4wG+CZR8uI9Q=+github.com/pion/dtls/v3 v3.0.7/go.mod h1:uDlH5VPrgOQIw59irKYkMudSFprY9IEFCqz/eTz16f8=+github.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8=+github.com/pion/logging v0.2.4/go.mod h1:DffhXTKYdNZU+KtJ5pyQDjvOAh/GsNSyv1lbkFbe3so=+github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=+github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=+github.com/pion/stun/v3 v3.0.1 h1:jx1uUq6BdPihF0yF33Jj2mh+C9p0atY94IkdnW174kA=+github.com/pion/stun/v3 v3.0.1/go.mod h1:RHnvlKFg+qHgoKIqtQWMOJF52wsImCAf/Jh5GjX+4Tw=+github.com/pion/transport/v3 v3.0.8 h1:oI3myyYnTKUSTthu/NZZ8eu2I5sHbxbUNNFW62olaYc=+github.com/pion/transport/v3 v3.0.8/go.mod h1:+c2eewC5WJQHiAA46fkMMzoYZSuGzA/7E2FPrOYHctQ=+github.com/pion/transport/v4 v4.0.1 h1:sdROELU6BZ63Ab7FrOLn13M6YdJLY20wldXW2Cu2k8o=+github.com/pion/transport/v4 v4.0.1/go.mod h1:nEuEA4AD5lPdcIegQDpVLgNoDGreqM/YqmEx3ovP4jM=+github.com/pion/turn/v4 v4.1.4 h1:EU11yMXKIsK43FhcUnjLlrhE4nboHZq+TXBIi3QpcxQ=+github.com/pion/turn/v4 v4.1.4/go.mod h1:ES1DXVFKnOhuDkqn9hn5VJlSWmZPaRJLyBXoOeO/BmQ=+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=+github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=+github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=+github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU=+github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=+golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=+golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=+golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=+golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=+golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=+golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=+golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=+golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=+golang.org/x/time v0.10.0 h1:3usCWA8tQn0L8+hFJQNgzpWbd89begxN66o1Ojdn5L4=+golang.org/x/time v0.10.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=+gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=+gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=+google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800 h1:qEHAMpSaUhtD0p3NbEEI83HwNGFxEwaSJ1G9PLnCBZE=+google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=+google.golang.org/grpc v1.84.0 h1:soMyaPJ8pAak5PIQ0DGBUir0XRo2fRoMqhNWMLlLxO0=+google.golang.org/grpc v1.84.0/go.mod h1:ljCht0DrxQrXBDRTZp52Qxh3Ffk8CdYm2sj4O2QN2C0=+google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=+google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=diff --git a/server/pairing/pairing.go b/server/pairing/pairing.gonew file mode 100644index 0000000..5fc2846--- /dev/null+++ b/server/pairing/pairing.go@@ -0,0 +1,151 @@+// Package pairing 管理配对码的签发与兑换。+//+// 配对码只在内存中存活 5 分钟,服务器不持久化任何设备信息——+// 双方一旦交换到对方公钥,此后的互信就完全不依赖服务器了。+package pairing++import (+ "crypto/rand"+ "errors"+ "fmt"+ "math/big"+ "sync"+ "time"+)++// 配对码字符集刻意剔除易混字符(0/O、1/I/L),因为用户可能要口头转述。+const codeAlphabet = "23456789ABCDEFGHJKMNPQRSTUVWXYZ"++const (+ CodeLength = 6+ CodeTTL = 5 * time.Minute+)++var (+ ErrCodeNotFound = errors.New("配对码不存在或已过期")+ ErrSelfPairing = errors.New("不能与自己配对")+)++// Peer 是配对双方互相看到的信息。+type Peer struct {+ DeviceID string+ DeviceName string+ Platform string+ PublicKey []byte+}++type pending struct {+ code string+ initiator Peer+ expiresAt time.Time+ // 兑换方的信息经此通道回传给发起方,让发起方也能拿到对端公钥+ redeemed chan Peer+}++type Broker struct {+ mu sync.Mutex+ codes map[string]*pending+ // 便于测试时注入假时钟+ now func() time.Time+}++func NewBroker() *Broker {+ return &Broker{+ codes: make(map[string]*pending),+ now: time.Now,+ }+}++// Create 为发起方签发一个配对码。+// 返回的通道在有人兑换时收到对方信息;超时或 Cancel 时关闭。+func (b *Broker) Create(initiator Peer) (code string, expiresAt time.Time, ch <-chan Peer, err error) {+ b.mu.Lock()+ defer b.mu.Unlock()++ b.gcLocked()++ // 极小概率撞码,重试几次即可+ for attempt := 0; attempt < 8; attempt++ {+ c, genErr := generateCode()+ if genErr != nil {+ return "", time.Time{}, nil, genErr+ }+ if _, taken := b.codes[c]; taken {+ continue+ }+ p := &pending{+ code: c,+ initiator: initiator,+ expiresAt: b.now().Add(CodeTTL),+ redeemed: make(chan Peer, 1),+ }+ b.codes[c] = p+ return c, p.expiresAt, p.redeemed, nil+ }+ return "", time.Time{}, nil, errors.New("生成配对码失败:连续撞码")+}++// Redeem 用配对码换取发起方信息,同时把兑换方信息回传给发起方。+// 配对码一次性使用,兑换后立即失效。+func (b *Broker) Redeem(code string, redeemer Peer) (Peer, error) {+ b.mu.Lock()+ defer b.mu.Unlock()++ b.gcLocked()++ p, ok := b.codes[code]+ if !ok {+ return Peer{}, ErrCodeNotFound+ }+ if p.initiator.DeviceID == redeemer.DeviceID {+ return Peer{}, ErrSelfPairing+ }++ delete(b.codes, code)+ // 缓冲为 1,发起方即使暂时没在读也不会阻塞这里+ p.redeemed <- redeemer+ close(p.redeemed)++ return p.initiator, nil+}++// Cancel 撤销尚未被兑换的配对码(发起方关闭配对界面或断线时)。+func (b *Broker) Cancel(code string) {+ b.mu.Lock()+ defer b.mu.Unlock()+ if p, ok := b.codes[code]; ok {+ delete(b.codes, code)+ close(p.redeemed)+ }+}++// gcLocked 清理过期配对码。调用方必须已持有锁。+func (b *Broker) gcLocked() {+ now := b.now()+ for code, p := range b.codes {+ if now.After(p.expiresAt) {+ delete(b.codes, code)+ close(p.redeemed)+ }+ }+}++func (b *Broker) Len() int {+ b.mu.Lock()+ defer b.mu.Unlock()+ return len(b.codes)+}++func generateCode() (string, error) {+ out := make([]byte, CodeLength)+ max := big.NewInt(int64(len(codeAlphabet)))+ for i := range out {+ // 用密码学随机源:配对码在有效期内是唯一的准入凭证+ n, err := rand.Int(rand.Reader, max)+ if err != nil {+ return "", fmt.Errorf("生成配对码: %w", err)+ }+ out[i] = codeAlphabet[n.Int64()]+ }+ return string(out), nil+}diff --git a/server/pairing/pairing_test.go b/server/pairing/pairing_test.gonew file mode 100644index 0000000..3edfb5e--- /dev/null+++ b/server/pairing/pairing_test.go@@ -0,0 +1,144 @@+package pairing++import (+ "strings"+ "testing"+ "time"+)++func peerNamed(id string) Peer {+ return Peer{DeviceID: id, DeviceName: id, PublicKey: []byte("key-" + id)}+}++func TestCodeFormat(t *testing.T) {+ b := NewBroker()+ code, _, _, err := b.Create(peerNamed("alice"))+ if err != nil {+ t.Fatalf("生成配对码: %v", err)+ }+ if len(code) != CodeLength {+ t.Errorf("长度 = %d,期望 %d", len(code), CodeLength)+ }+ // 字符集刻意剔除了易混字符,用户可能要口头转述配对码+ for _, c := range code {+ if !strings.ContainsRune(codeAlphabet, c) {+ t.Errorf("配对码含字符集外的字符 %q(可能与 0/O、1/I 混淆)", c)+ }+ }+ for _, bad := range []string{"0", "O", "1", "I", "L"} {+ if strings.Contains(codeAlphabet, bad) {+ t.Errorf("字符集不该包含易混字符 %q", bad)+ }+ }+}++// 配对码是一次性凭证:兑换后必须立即失效,否则第三方可以重复使用它接入。+func TestCodeIsSingleUse(t *testing.T) {+ b := NewBroker()+ code, _, redeemed, _ := b.Create(peerNamed("alice"))++ initiator, err := b.Redeem(code, peerNamed("bob"))+ if err != nil {+ t.Fatalf("首次兑换应成功: %v", err)+ }+ if initiator.DeviceID != "alice" {+ t.Errorf("拿到的发起方 = %q,期望 alice", initiator.DeviceID)+ }++ if _, err := b.Redeem(code, peerNamed("mallory")); err == nil {+ t.Error("配对码被重复兑换了,应当一次性失效")+ }++ // 发起方必须收到兑换方信息,否则只能建立单向互信+ select {+ case got := <-redeemed:+ if got.DeviceID != "bob" {+ t.Errorf("回传的兑换方 = %q,期望 bob", got.DeviceID)+ }+ case <-time.After(time.Second):+ t.Error("发起方未收到兑换通知")+ }+}++func TestRedeemUnknownCode(t *testing.T) {+ b := NewBroker()+ if _, err := b.Redeem("ZZZZZZ", peerNamed("bob")); err != ErrCodeNotFound {+ t.Errorf("err = %v,期望 ErrCodeNotFound", err)+ }+}++// 与自己配对没有意义,且会让设备列表里出现自身。+func TestSelfPairingRejected(t *testing.T) {+ b := NewBroker()+ code, _, _, _ := b.Create(peerNamed("alice"))+ if _, err := b.Redeem(code, peerNamed("alice")); err != ErrSelfPairing {+ t.Errorf("err = %v,期望 ErrSelfPairing", err)+ }+}++func TestExpiredCodeRejected(t *testing.T) {+ b := NewBroker()+ now := time.Now()+ b.now = func() time.Time { return now }++ code, expires, redeemed, _ := b.Create(peerNamed("alice"))+ if !expires.Equal(now.Add(CodeTTL)) {+ t.Errorf("过期时间 = %v,期望 %v", expires, now.Add(CodeTTL))+ }++ // 拨快到过期之后+ b.now = func() time.Time { return now.Add(CodeTTL + time.Second) }++ if _, err := b.Redeem(code, peerNamed("bob")); err != ErrCodeNotFound {+ t.Errorf("过期配对码仍可兑换,err = %v", err)+ }+ // 过期时应关闭通道,避免发起方永久挂起+ select {+ case _, open := <-redeemed:+ if open {+ t.Error("过期后不该再回传兑换方信息")+ }+ case <-time.After(time.Second):+ t.Error("过期后通道未关闭,发起方会一直等待")+ }+ if b.Len() != 0 {+ t.Errorf("过期条目未被清理,剩余 %d 条", b.Len())+ }+}++func TestCancelReleasesWaiter(t *testing.T) {+ b := NewBroker()+ code, _, redeemed, _ := b.Create(peerNamed("alice"))++ b.Cancel(code)++ select {+ case _, open := <-redeemed:+ if open {+ t.Error("取消后不该再收到兑换方信息")+ }+ case <-time.After(time.Second):+ t.Error("取消后通道未关闭")+ }+ if _, err := b.Redeem(code, peerNamed("bob")); err != ErrCodeNotFound {+ t.Error("已取消的配对码仍可兑换")+ }+}++func TestConcurrentCodesAreUnique(t *testing.T) {+ b := NewBroker()+ seen := make(map[string]bool)+ for i := 0; i < 200; i++ {+ code, _, _, err := b.Create(peerNamed("alice"))+ if err != nil {+ t.Fatalf("第 %d 次生成失败: %v", i, err)+ }+ if seen[code] {+ t.Fatalf("生成了重复的配对码 %q", code)+ }+ seen[code] = true+ }+ if b.Len() != 200 {+ t.Errorf("在存配对码数 = %d,期望 200", b.Len())+ }+}diff --git a/server/relay/turn.go b/server/relay/turn.gonew file mode 100644index 0000000..c0d595a--- /dev/null+++ b/server/relay/turn.go@@ -0,0 +1,158 @@+// Package relay 是自建的 TURN 中转服务,供 P2P 打洞失败时兜底。+//+// TURN 只转发 UDP 数据包,看不到 DTLS 内层——即便走中转,+// 设备间的内容对服务器仍然是密文。+package relay++import (+ "crypto/hmac"+ "crypto/sha1"+ "encoding/base64"+ "fmt"+ "log/slog"+ "net"+ "strconv"+ "strings"+ "time"++ "github.com/pion/turn/v4"+)++// Server 封装 pion/turn,并按标准的 TURN REST API 方式签发短期凭证。+type Server struct {+ turn *turn.Server+ secret []byte+ publicIP string+ port int+ ttl time.Duration+ log *slog.Logger+}++type Options struct {+ // PublicIP 是客户端能访问到的地址。NAT 后部署时必须显式指定,+ // 否则 TURN 会把内网地址写进 relay candidate,外部设备连不上。+ PublicIP string+ Port int+ Realm string+ // Secret 用于派生短期凭证。与签发方共享,不下发给客户端。+ Secret string+ // CredentialTTL 决定签发的凭证多久过期+ CredentialTTL time.Duration+ Logger *slog.Logger+}++func New(opts Options) (*Server, error) {+ if opts.PublicIP == "" {+ return nil, fmt.Errorf("必须指定 TURN 的公网地址")+ }+ if opts.Port == 0 {+ opts.Port = 3478+ }+ if opts.Realm == "" {+ opts.Realm = "copysync"+ }+ if opts.CredentialTTL == 0 {+ opts.CredentialTTL = 12 * time.Hour+ }+ log := opts.Logger+ if log == nil {+ log = slog.Default()+ }++ udpConn, err := net.ListenPacket("udp4", "0.0.0.0:"+strconv.Itoa(opts.Port))+ if err != nil {+ return nil, fmt.Errorf("监听 TURN 端口 %d: %w", opts.Port, err)+ }++ secret := []byte(opts.Secret)+ s := &Server{+ secret: secret,+ publicIP: opts.PublicIP,+ port: opts.Port,+ ttl: opts.CredentialTTL,+ log: log,+ }++ ts, err := turn.NewServer(turn.ServerConfig{+ Realm: opts.Realm,+ // 凭证是 HMAC 派生的,无需维护用户表:+ // username = "<过期时间戳>:<device_id>",password = HMAC-SHA1(username, secret)+ AuthHandler: func(username, realm string, srcAddr net.Addr) ([]byte, bool) {+ key, ok := s.verify(username, realm)+ if !ok {+ log.Debug("TURN 认证失败", "username", username, "from", srcAddr)+ }+ return key, ok+ },+ PacketConnConfigs: []turn.PacketConnConfig{{+ PacketConn: udpConn,+ RelayAddressGenerator: &turn.RelayAddressGeneratorStatic{+ RelayAddress: net.ParseIP(opts.PublicIP),+ Address: "0.0.0.0",+ },+ }},+ })+ if err != nil {+ udpConn.Close()+ return nil, fmt.Errorf("启动 TURN 服务: %w", err)+ }+ s.turn = ts++ log.Info("TURN 中转已启动", "addr", opts.PublicIP, "port", opts.Port, "realm", opts.Realm)+ return s, nil+}++func (s *Server) Close() error {+ if s.turn == nil {+ return nil+ }+ return s.turn.Close()+}++// Credential 是签发给客户端的一次性 TURN 凭证。+type Credential struct {+ Username string+ Password string+ ExpiresAt time.Time+ URLs []string+}++// Issue 为指定设备签发短期 TURN 凭证。+//+// 采用标准的 TURN REST API 约定:用户名里编码过期时间,+// 密码由服务端密钥 HMAC 派生。服务器因此无需存储任何凭证。+func (s *Server) Issue(deviceID string) Credential {+ expires := time.Now().Add(s.ttl)+ username := fmt.Sprintf("%d:%s", expires.Unix(), deviceID)++ mac := hmac.New(sha1.New, s.secret)+ mac.Write([]byte(username))+ password := base64.StdEncoding.EncodeToString(mac.Sum(nil))++ return Credential{+ Username: username,+ Password: password,+ ExpiresAt: expires,+ URLs: []string{+ fmt.Sprintf("turn:%s:%d?transport=udp", s.publicIP, s.port),+ },+ }+}++// verify 校验凭证并返回 TURN 所需的鉴权 key。+func (s *Server) verify(username, realm string) ([]byte, bool) {+ parts := strings.SplitN(username, ":", 2)+ if len(parts) != 2 {+ return nil, false+ }+ exp, err := strconv.ParseInt(parts[0], 10, 64)+ if err != nil || time.Now().After(time.Unix(exp, 0)) {+ return nil, false // 格式错误或已过期+ }++ mac := hmac.New(sha1.New, s.secret)+ mac.Write([]byte(username))+ password := base64.StdEncoding.EncodeToString(mac.Sum(nil))++ return turn.GenerateAuthKey(username, realm, password), true+}diff --git a/server/signal/hub.go b/server/signal/hub.gonew file mode 100644index 0000000..eec02ce--- /dev/null+++ b/server/signal/hub.go@@ -0,0 +1,145 @@+// Package signal 是信令服务器:设备注册、在线状态广播、消息转发。+//+// 服务器不存任何用户数据,也读不懂设备间的内容——它只做三件事:+// 校验「连上来的设备确实持有其声称公钥的私钥」、告诉设备它关心的对端是否在线、+// 把带签名的信令原样转发。设备间的互信完全由配对时交换的公钥承担。+package signal++import (+ "sync"+)++// Conn 是一条已完成认证的设备连接。+type Conn struct {+ DeviceID string+ DeviceName string+ Platform string+ PublicKey []byte++ // send 是该连接的出站队列。写满说明对端消费不过来,+ // 此时丢弃消息而不是阻塞 hub——信令都是可重试的。+ send chan []byte++ // watching 是此设备关心在线状态的对端集合(即它已配对的设备)+ watching map[string]struct{}+}++func (c *Conn) Send(data []byte) bool {+ select {+ case c.send <- data:+ return true+ default:+ return false+ }+}++func (c *Conn) Outbound() <-chan []byte { return c.send }++type Hub struct {+ mu sync.RWMutex+ conns map[string]*Conn+}++func NewHub() *Hub {+ return &Hub{conns: make(map[string]*Conn)}+}++// Register 接纳一条新连接。同一设备重复连接时,旧连接被顶替并关闭——+// 客户端重连(网络切换、进程重启)时不应留下僵尸连接。+func (h *Hub) Register(c *Conn) (replaced *Conn) {+ h.mu.Lock()+ defer h.mu.Unlock()++ if old, ok := h.conns[c.DeviceID]; ok {+ delete(h.conns, c.DeviceID)+ replaced = old+ }+ h.conns[c.DeviceID] = c+ return replaced+}++// Unregister 移除连接。只有当前注册的那条才会被移除——+// 避免被顶替的旧连接在收尾时误删新连接。+func (h *Hub) Unregister(c *Conn) bool {+ h.mu.Lock()+ defer h.mu.Unlock()++ if cur, ok := h.conns[c.DeviceID]; ok && cur == c {+ delete(h.conns, c.DeviceID)+ return true+ }+ return false+}++func (h *Hub) Get(deviceID string) (*Conn, bool) {+ h.mu.RLock()+ defer h.mu.RUnlock()+ c, ok := h.conns[deviceID]+ return c, ok+}++func (h *Hub) Online(deviceID string) bool {+ h.mu.RLock()+ defer h.mu.RUnlock()+ _, ok := h.conns[deviceID]+ return ok+}++// SetWatching 记录某设备关心哪些对端的在线状态。+func (h *Hub) SetWatching(deviceID string, peers []string) {+ h.mu.Lock()+ defer h.mu.Unlock()++ c, ok := h.conns[deviceID]+ if !ok {+ return+ }+ c.watching = make(map[string]struct{}, len(peers))+ for _, p := range peers {+ c.watching[p] = struct{}{}+ }+}++// WatchersOf 返回正关注 deviceID 的所有在线连接。+//+// 只通知声明过关心该设备的连接:设备间是否配对只有客户端知道,+// 服务器不维护配对关系,靠 ClientHello 里带上来的列表来路由。+func (h *Hub) WatchersOf(deviceID string) []*Conn {+ h.mu.RLock()+ defer h.mu.RUnlock()++ var out []*Conn+ for id, c := range h.conns {+ if id == deviceID {+ continue+ }+ if _, ok := c.watching[deviceID]; ok {+ out = append(out, c)+ }+ }+ return out+}++// PresenceFor 返回 deviceID 所关注的对端中,当前在线的那些。+func (h *Hub) PresenceFor(deviceID string) []string {+ h.mu.RLock()+ defer h.mu.RUnlock()++ c, ok := h.conns[deviceID]+ if !ok {+ return nil+ }+ var online []string+ for peer := range c.watching {+ if _, ok := h.conns[peer]; ok {+ online = append(online, peer)+ }+ }+ return online+}++func (h *Hub) Count() int {+ h.mu.RLock()+ defer h.mu.RUnlock()+ return len(h.conns)+}diff --git a/server/signal/server.go b/server/signal/server.gonew file mode 100644index 0000000..4e26384--- /dev/null+++ b/server/signal/server.go@@ -0,0 +1,399 @@+package signal++import (+ "context"+ "crypto/ed25519"+ "crypto/rand"+ "errors"+ "fmt"+ "log/slog"+ "net/http"+ "time"++ "github.com/coder/websocket"+ "google.golang.org/protobuf/proto"++ "github.com/baiyuze/copysync/proto/deviceid"+ pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"+ "github.com/baiyuze/copysync/server/pairing"+)++const (+ // 信令消息都很小(最大的是 SDP,通常几 KB)+ maxMessageBytes = 256 << 10+ handshakeTimeout = 15 * time.Second+ writeTimeout = 10 * time.Second+ // 心跳:及时发现半开连接,否则对端会一直显示"在线"+ pingInterval = 30 * time.Second+ pongTimeout = 60 * time.Second+)++type Server struct {+ hub *Hub+ broker *pairing.Broker+ iceFunc func(deviceID string) []*pb.IceServer+ log *slog.Logger+}++type Options struct {+ // ICEServers 为每个设备签发 STUN/TURN 配置(含短期 TURN 凭证)+ ICEServers func(deviceID string) []*pb.IceServer+ Logger *slog.Logger+}++func NewServer(opts Options) *Server {+ log := opts.Logger+ if log == nil {+ log = slog.Default()+ }+ ice := opts.ICEServers+ if ice == nil {+ ice = func(string) []*pb.IceServer { return nil }+ }+ return &Server{+ hub: NewHub(),+ broker: pairing.NewBroker(),+ iceFunc: ice,+ log: log,+ }+}++func (s *Server) Hub() *Hub { return s.hub }++func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {+ ws, err := websocket.Accept(w, r, &websocket.AcceptOptions{+ // 客户端是桌面应用而非浏览器,不存在跨站请求伪造的场景+ InsecureSkipVerify: true,+ })+ if err != nil {+ s.log.Warn("websocket 握手失败", "err", err, "remote", r.RemoteAddr)+ return+ }+ ws.SetReadLimit(maxMessageBytes)++ ctx, cancel := context.WithCancel(r.Context())+ defer cancel()++ conn, err := s.handshake(ctx, ws)+ if err != nil {+ s.log.Warn("设备认证失败", "err", err, "remote", r.RemoteAddr)+ ws.Close(websocket.StatusPolicyViolation, "认证失败")+ return+ }++ s.log.Info("设备已连接",+ "device", conn.DeviceID, "name", conn.DeviceName,+ "platform", conn.Platform, "在线数", s.hub.Count())++ defer func() {+ if s.hub.Unregister(conn) {+ s.broadcastPresence(ctx, conn.DeviceID, false)+ s.log.Info("设备已断开", "device", conn.DeviceID, "在线数", s.hub.Count())+ }+ }()++ // 出站泵:所有写操作集中在这一个 goroutine,websocket 不支持并发写+ go s.writePump(ctx, ws, conn)++ s.readLoop(ctx, ws, conn)+}++// handshake 完成「证明你持有这把私钥」的挑战应答。+//+// 服务器不维护用户表,所以认证是自证式的:设备提交公钥和对 challenge 的签名,+// 服务器验签并校验 device_id 确由该公钥派生。这挡住了冒用他人 device_id 的连接。+func (s *Server) handshake(ctx context.Context, ws *websocket.Conn) (*Conn, error) {+ ctx, cancel := context.WithTimeout(ctx, handshakeTimeout)+ defer cancel()++ challenge := make([]byte, 32)+ if _, err := rand.Read(challenge); err != nil {+ return nil, err+ }++ hello := &pb.ServerEnvelope{+ Payload: &pb.ServerEnvelope_Hello{Hello: &pb.ServerHello{+ Challenge: challenge,+ ServerTimeUnix: time.Now().Unix(),+ }},+ }+ if err := writeProto(ctx, ws, hello); err != nil {+ return nil, fmt.Errorf("发送 ServerHello: %w", err)+ }++ var env pb.ClientEnvelope+ if err := readProto(ctx, ws, &env); err != nil {+ return nil, fmt.Errorf("读取 ClientHello: %w", err)+ }+ ch := env.GetHello()+ if ch == nil {+ return nil, errors.New("首条消息必须是 ClientHello")+ }++ pub := ed25519.PublicKey(ch.GetPublicKey())+ if len(pub) != ed25519.PublicKeySize {+ return nil, errors.New("公钥长度不合法")+ }+ if !ed25519.Verify(pub, challenge, ch.GetSignature()) {+ return nil, errors.New("challenge 签名验证失败")+ }+ if !deviceid.Valid(ch.GetDeviceId(), pub) {+ return nil, errors.New("device_id 与公钥不匹配")+ }++ conn := &Conn{+ DeviceID: ch.GetDeviceId(),+ DeviceName: ch.GetDeviceName(),+ Platform: ch.GetPlatform(),+ PublicKey: pub,+ send: make(chan []byte, 32),+ watching: make(map[string]struct{}, len(ch.GetPairedDeviceIds())),+ }+ for _, p := range ch.GetPairedDeviceIds() {+ conn.watching[p] = struct{}{}+ }++ if replaced := s.hub.Register(conn); replaced != nil {+ s.log.Info("顶替同设备的旧连接", "device", conn.DeviceID)+ close(replaced.send)+ }++ // ICE 配置含按设备签发的短期 TURN 凭证,必须等认证通过后才能下发+ if servers := s.iceFunc(conn.DeviceID); len(servers) > 0 {+ conn.Send(mustMarshal(&pb.ServerEnvelope{+ Payload: &pb.ServerEnvelope_IceConfig{+ IceConfig: &pb.IceConfig{IceServers: servers},+ },+ }))+ }++ // 先告诉新连接:它关心的对端里谁在线+ s.sendCurrentPresence(conn)+ // 再告诉关心它的对端:我上线了+ s.broadcastPresence(ctx, conn.DeviceID, true)++ return conn, nil+}++// sendCurrentPresence 把「该连接所关注的对端中当前在线的那些」推给它。+func (s *Server) sendCurrentPresence(conn *Conn) {+ for _, peer := range s.hub.PresenceFor(conn.DeviceID) {+ conn.Send(mustMarshal(&pb.ServerEnvelope{+ Payload: &pb.ServerEnvelope_Presence{Presence: &pb.PeerPresence{+ DeviceId: peer, Online: true,+ }},+ }))+ }+}++func (s *Server) readLoop(ctx context.Context, ws *websocket.Conn, conn *Conn) {+ for {+ var env pb.ClientEnvelope+ if err := readProto(ctx, ws, &env); err != nil {+ if ctx.Err() == nil && websocket.CloseStatus(err) == -1 {+ s.log.Debug("读取中断", "device", conn.DeviceID, "err", err)+ }+ return+ }++ switch p := env.GetPayload().(type) {+ case *pb.ClientEnvelope_Forward:+ s.forward(conn, p.Forward)+ case *pb.ClientEnvelope_PairingCreate:+ s.handlePairingCreate(ctx, conn, p.PairingCreate)+ case *pb.ClientEnvelope_PairingRedeem:+ s.handlePairingRedeem(conn, p.PairingRedeem)+ case *pb.ClientEnvelope_Hello:+ // 重复的 Hello 用来刷新关注列表(刚完成配对时会发)+ s.hub.SetWatching(conn.DeviceID, p.Hello.GetPairedDeviceIds())+ // 必须补发一次当前在线状态:presence 只在设备上下线的瞬间广播,+ // 新加入关注列表的对端此刻可能早已在线,不补发的话本端会一直显示它离线。+ s.sendCurrentPresence(conn)+ // 同理,对端也可能正关注着本设备却错过了上线广播+ s.broadcastPresence(ctx, conn.DeviceID, true)+ default:+ s.sendError(conn, "unknown_message", "未知的消息类型")+ }+ }+}++// forward 把带签名的信令原样转发。+//+// 服务器不验签也不解析内容——验签是接收方的事(它有对端公钥,服务器没有)。+// 服务器只确保 from_device_id 不能伪造:强制改写为连接自身的身份。+func (s *Server) forward(from *Conn, signed *pb.Signed) {+ if signed == nil {+ return+ }+ // 防止 A 冒充 B 向 C 发消息+ signed.FromDeviceId = from.DeviceID++ var inner pb.SignalMessage+ if err := proto.Unmarshal(signed.GetPayload(), &inner); err != nil {+ s.sendError(from, "bad_payload", "signal payload 无法解析")+ return+ }+ to := inner.GetToDeviceId()+ if to == "" {+ s.sendError(from, "missing_target", "缺少 to_device_id")+ return+ }++ target, ok := s.hub.Get(to)+ if !ok {+ s.sendError(from, "peer_offline", fmt.Sprintf("对端 %s 不在线", to))+ return+ }+ if !target.Send(mustMarshal(&pb.ServerEnvelope{+ Payload: &pb.ServerEnvelope_Forwarded{Forwarded: signed},+ })) {+ s.log.Warn("转发丢弃:对端出站队列已满", "from", from.DeviceID, "to", to)+ }+}++func (s *Server) handlePairingCreate(ctx context.Context, conn *Conn, req *pb.PairingCreateRequest) {+ code, expires, redeemed, err := s.broker.Create(pairing.Peer{+ DeviceID: conn.DeviceID,+ DeviceName: req.GetDeviceName(),+ Platform: conn.Platform,+ PublicKey: req.GetPublicKey(),+ })+ if err != nil {+ s.sendError(conn, "pairing_create_failed", err.Error())+ return+ }++ conn.Send(mustMarshal(&pb.ServerEnvelope{+ Payload: &pb.ServerEnvelope_PairingCreated{PairingCreated: &pb.PairingCreateResponse{+ Code: code,+ ExpiresAtUnix: expires.Unix(),+ }},+ }))++ // 等待有人兑换。兑换方的信息要回传给发起方,+ // 否则发起方拿不到对端公钥,配对只能单向完成。+ go func() {+ select {+ case peer, ok := <-redeemed:+ if !ok {+ return // 已过期或被取消+ }+ conn.Send(mustMarshal(&pb.ServerEnvelope{+ Payload: &pb.ServerEnvelope_PairingRedeemed{PairingRedeemed: &pb.PairingRedeemed{+ PeerDeviceId: peer.DeviceID,+ PeerDeviceName: peer.DeviceName,+ PeerPlatform: peer.Platform,+ PeerPublicKey: peer.PublicKey,+ }},+ }))+ s.log.Info("配对完成", "initiator", conn.DeviceID, "peer", peer.DeviceID)+ case <-ctx.Done():+ s.broker.Cancel(code)+ }+ }()+}++func (s *Server) handlePairingRedeem(conn *Conn, req *pb.PairingRedeemRequest) {+ initiator, err := s.broker.Redeem(req.GetCode(), pairing.Peer{+ DeviceID: conn.DeviceID,+ DeviceName: req.GetDeviceName(),+ Platform: conn.Platform,+ PublicKey: req.GetPublicKey(),+ })+ if err != nil {+ s.sendError(conn, "pairing_redeem_failed", err.Error())+ return+ }++ conn.Send(mustMarshal(&pb.ServerEnvelope{+ Payload: &pb.ServerEnvelope_PairingRedeemedResult{+ PairingRedeemedResult: &pb.PairingRedeemResponse{+ PeerDeviceId: initiator.DeviceID,+ PeerDeviceName: initiator.DeviceName,+ PeerPlatform: initiator.Platform,+ PeerPublicKey: initiator.PublicKey,+ },+ },+ }))+}++func (s *Server) broadcastPresence(_ context.Context, deviceID string, online bool) {+ data := mustMarshal(&pb.ServerEnvelope{+ Payload: &pb.ServerEnvelope_Presence{Presence: &pb.PeerPresence{+ DeviceId: deviceID, Online: online,+ }},+ })+ for _, w := range s.hub.WatchersOf(deviceID) {+ w.Send(data)+ }+}++func (s *Server) sendError(conn *Conn, code, msg string) {+ conn.Send(mustMarshal(&pb.ServerEnvelope{+ Payload: &pb.ServerEnvelope_Error{Error: &pb.ServerError{Code: code, Message: msg}},+ }))+}++// writePump 独占写端。websocket 连接不允许并发写,所有出站消息都经此串行化。+func (s *Server) writePump(ctx context.Context, ws *websocket.Conn, conn *Conn) {+ ping := time.NewTicker(pingInterval)+ defer ping.Stop()++ for {+ select {+ case <-ctx.Done():+ return+ case data, ok := <-conn.send:+ if !ok {+ ws.Close(websocket.StatusNormalClosure, "连接被顶替")+ return+ }+ wctx, cancel := context.WithTimeout(ctx, writeTimeout)+ err := ws.Write(wctx, websocket.MessageBinary, data)+ cancel()+ if err != nil {+ return+ }+ case <-ping.C:+ pctx, cancel := context.WithTimeout(ctx, pongTimeout)+ err := ws.Ping(pctx)+ cancel()+ if err != nil {+ s.log.Debug("心跳失败,断开", "device", conn.DeviceID, "err", err)+ ws.Close(websocket.StatusGoingAway, "心跳超时")+ return+ }+ }+ }+}++// ─────────────────────── proto over websocket ───────────────────────++func readProto(ctx context.Context, ws *websocket.Conn, m proto.Message) error {+ typ, data, err := ws.Read(ctx)+ if err != nil {+ return err+ }+ if typ != websocket.MessageBinary {+ return fmt.Errorf("期望二进制消息,收到 %v", typ)+ }+ return proto.Unmarshal(data, m)+}++func writeProto(ctx context.Context, ws *websocket.Conn, m proto.Message) error {+ data, err := proto.Marshal(m)+ if err != nil {+ return err+ }+ return ws.Write(ctx, websocket.MessageBinary, data)+}++// mustMarshal 用于出站信封:这些消息都是本地构造的,+// 序列化失败意味着程序有 bug,不该被静默吞掉。+func mustMarshal(m proto.Message) []byte {+ data, err := proto.Marshal(m)+ if err != nil {+ panic(fmt.Sprintf("序列化出站消息失败: %v", err))+ }+ return data+}diff --git a/spikes/README.md b/spikes/README.mdnew file mode 100644index 0000000..3d1d72c--- /dev/null+++ b/spikes/README.md@@ -0,0 +1,65 @@+# M-1 Spike:验证 macOS 剪贴板的两个致命假设++CopySync 的「纯懒模式」(复制时不传输,对端按下粘贴键才回源拉取)在技术上+**只能**通过剪贴板的延迟渲染(promise)机制实现——操作系统不提供「剪贴板被读取」+的通知,promise 回调是唯一能感知「对方按下了 Cmd+V」的时机。++这两个 spike 验证该路径是否真的走得通。**若假设不成立,整个架构需要重新设计。**++本机环境:macOS 15.7.3 (Sequoia) · Apple clang 17.0.0 · Xcode 26.x++---++## Spike A — 剪贴板读取的隐私提示(`privacy/`)++**要验证什么**:macOS 15 Sequoia 起,App 以编程方式读取*其他* App 放入剪贴板的内容时,+系统会弹出「"某某" 想要从其他 App 粘贴」的确认框。CopySync 的 daemon 需要持续监听剪贴板,+如果每次复制都弹窗,产品直接不可用。++**分阶段探测**,逐级判断哪一步触发提示:++| 阶段 | 操作 | 预期 |+|---|---|---|+| 1 | 读 `changeCount` | 应**不**触发(只是个计数器) |+| 2 | 读 `pasteboard.types` | 应**不**触发(只是类型列表) |+| 3 | `detectPatternsForPatterns:` (macOS 14+) | 官方宣称**不**触发,用于"窥探但不读取" |+| 4 | 读 `public.file-url` 的实际内容 | **很可能触发** ← 这是我们真正需要的 |++**成败判据**:+- 阶段 1/2 不触发 → 至少「感知到剪贴板变了」是免费的+- 阶段 4 触发但选「每次都允许」后永久静默 → 可接受,首次引导用户授权一次+- 阶段 4 每次都弹且无法永久授权 → **架构需调整**(改为用户主动触发同步,而非自动监听)++## Spike B — `NSFilePromiseProvider` 的实际可用性(`promise/`)++**要验证什么**:把 file promise 放进剪贴板后,目标 App 粘贴时能否正确触发回调、+回调里能否**异步延迟数秒**(模拟跨网络拉取)而不被系统超时杀掉。++程序把一个 promise 写进剪贴板,delegate 回调里先 `sleep 5s` 再写文件,+然后你去各个 App 里 `Cmd+V`,观察终端日志和 App 行为。++**成败判据**:+- Finder 能粘出文件、显示进度条、不超时 → 核心路径成立+- 5 秒延迟被杀 → 需要缩短首字节时间,或改为预落盘+- 大量常用 App 不支持 promise → 需要对这些 App 降级为「先落盘再给路径」++**兼容性矩阵**(在 `results.md` 里填写实测结果):+Finder / 微信 / 飞书 / Mail / VS Code / 钉钉 / Safari 上传框 / 终端拖拽区++---++## 运行++```bash+./build.sh+```++编译产物是两个 `.app` bundle(**不是**裸命令行工具)。这点很重要:macOS 的 TCC 隐私机制+以 bundle identifier 为授权主体,裸二进制的提示行为与真实 App 不一致,测出来的结论不可用。++```bash+./build/SpikeA.app/Contents/MacOS/SpikeA # 前台运行看日志+./build/SpikeB.app/Contents/MacOS/SpikeB+```++两个程序都在前台打印日志,`Ctrl+C` 退出。diff --git a/spikes/build.sh b/spikes/build.shnew file mode 100755index 0000000..178918e--- /dev/null+++ b/spikes/build.sh@@ -0,0 +1,62 @@+#!/usr/bin/env bash+# 把两个 spike 编译成 .app bundle。+#+# 必须是 bundle 而不是裸二进制:macOS 的 TCC 隐私机制以 bundle identifier+# 为授权主体,裸命令行工具的提示行为与真实 App 不一致,测出来的结论不可用。++set -euo pipefail+cd "$(dirname "$0")"++OUT=build+rm -rf "$OUT" && mkdir -p "$OUT"++build_app() {+ local name=$1 src=$2 bundle_id=$3+ local app="$OUT/$name.app"++ mkdir -p "$app/Contents/MacOS"++ cat > "$app/Contents/Info.plist" <<PLIST+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleExecutable</key> <string>$name</string>+ <key>CFBundleIdentifier</key> <string>$bundle_id</string>+ <key>CFBundleName</key> <string>$name</string>+ <key>CFBundlePackageType</key> <string>APPL</string>+ <key>CFBundleShortVersionString</key> <string>0.1</string>+ <key>CFBundleVersion</key> <string>1</string>+ <key>LSMinimumSystemVersion</key> <string>13.0</string>+ <key>LSUIElement</key> <true/>+</dict>+</plist>+PLIST++ clang -fobjc-arc -O0 -g -Wall \+ -framework Cocoa \+ -framework UniformTypeIdentifiers \+ -o "$app/Contents/MacOS/$name" "$src"++ # ad-hoc 签名:TCC 需要一个可识别的签名身份才能记住授权决定+ codesign --force --sign - "$app"++ echo " ✓ $app"+}++echo "编译中…"+build_app SpikeA privacy/main.m com.copysync.spike.privacy+build_app SpikeB promise/main.m com.copysync.spike.promise+build_app SpikeC writer/main.m com.copysync.spike.writer+build_app SpikeD receiver/main.m com.copysync.spike.receiver++cat <<EOF++完成。++ ./$OUT/SpikeA.app/Contents/MacOS/SpikeA [轮数] # 隐私机制探测(读方)+ ./$OUT/SpikeB.app/Contents/MacOS/SpikeB # promise 可用性+ ./$OUT/SpikeC.app/Contents/MacOS/SpikeC <mode> # 复制方模拟(file|text|image)++完整的隐私对照实验:./test-privacy.sh+EOFdiff --git a/spikes/privacy/main.m b/spikes/privacy/main.mnew file mode 100644index 0000000..19c56bb--- /dev/null+++ b/spikes/privacy/main.m@@ -0,0 +1,240 @@+// Spike A — macOS 剪贴板隐私机制探测+//+// 背景:macOS 15.4 引入了剪贴板隐私保护,目前是 developer preview(默认关闭),+// 下一个 macOS 大版本将强制执行。CopySync 的 daemon 恰好是+// 「后台程序化读取剪贴板」——完全命中被拦截的场景,必须提前验证。+//+// 要回答的问题:+// Q1. 哪些操作免提示?(changeCount / types / detectMetadata / 读内容)+// Q2. detectMetadataForTypes 能否拿到足够的信息做类型分类?+// Q3. 触发提示后 accessBehavior 如何变化?用户授权后能否永久静默?+// Q4. 每个阶段耗时多少?(耗时 > 1s 说明弹窗出现并等待了用户交互)+//+// 开启 preview 后再跑一次,即可预演未来 macOS 上的行为:+// defaults write com.copysync.spike.privacy EnablePasteboardPrivacyDeveloperPreview -bool yes++#import <Cocoa/Cocoa.h>+#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>++static const NSTimeInterval kPollInterval = 0.3;+static const NSTimeInterval kBlockThreshold = 1.0; // 超过此耗时即判定「弹窗出现过」++static void banner(const char *s) {+ fprintf(stderr, "\n════════════════════════════════════════════════════════\n");+ fprintf(stderr, " %s\n", s);+ fprintf(stderr, "════════════════════════════════════════════════════════\n");+ fflush(stderr);+}++static void line(const char *fmt, ...) {+ va_list ap; va_start(ap, fmt);+ fprintf(stderr, " → ");+ vfprintf(stderr, fmt, ap);+ fprintf(stderr, "\n");+ va_end(ap);+ fflush(stderr);+}++// 打印阶段标题并返回起始时刻,配合 endStage 测量耗时+static NSDate *beginStage(int n, const char *what) {+ fprintf(stderr, "\n [阶段 %d] %s\n", n, what);+ fflush(stderr);+ return NSDate.date;+}++static void endStage(NSDate *t0) {+ NSTimeInterval dt = -[t0 timeIntervalSinceNow];+ if (dt > kBlockThreshold) {+ fprintf(stderr, " ⏱ 耗时 %.2f 秒 ← 🔔 阻塞了!几乎可以确定弹出了授权框\n", dt);+ } else {+ fprintf(stderr, " ⏱ 耗时 %.3f 秒(无阻塞,未弹窗)\n", dt);+ }+ fflush(stderr);+}++// 在主线程安全地等待异步回调。+//+// 不能用 dispatch_semaphore_wait 直接阻塞主线程:+// 1. 若 completionHandler 恰好投递到主队列,会直接死锁;+// 2. 系统授权弹窗依赖主 run loop 才能显示和响应。+// 正确做法是 spin run loop —— 等待期间继续处理事件。+static BOOL waitSpinningRunLoop(dispatch_semaphore_t sem, NSTimeInterval timeout) {+ NSDate *deadline = [NSDate dateWithTimeIntervalSinceNow:timeout];+ while (dispatch_semaphore_wait(sem, DISPATCH_TIME_NOW) != 0) {+ if (deadline.timeIntervalSinceNow < 0) return NO;+ [NSRunLoop.currentRunLoop runMode:NSDefaultRunLoopMode+ beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.02]];+ }+ return YES;+}++static const char *behaviorName(NSInteger b) {+ switch (b) {+ case 0: return "Default (从未触发过提示,不出现在系统设置中)";+ case 1: return "Ask (每次程序化访问都询问)";+ case 2: return "AlwaysAllow(永久放行,静默)";+ case 3: return "AlwaysDeny (永久拒绝)";+ default: return "未知";+ }+}++static void reportAccessBehavior(NSPasteboard *pb) {+ if (@available(macOS 15.4, *)) {+ line("accessBehavior = %ld %s", (long)pb.accessBehavior,+ behaviorName(pb.accessBehavior));+ } else {+ line("accessBehavior 不可用(需 macOS 15.4+)");+ }+}++static void probe(NSPasteboard *pb, NSInteger change) {+ banner([[NSString stringWithFormat:@"剪贴板变化 #%ld %@", (long)change,+ [NSDateFormatter localizedStringFromDate:NSDate.date+ dateStyle:NSDateFormatterNoStyle+ timeStyle:NSDateFormatterMediumStyle]] UTF8String]);++ // ── 阶段 0:当前授权状态 ───────────────────────────────────+ NSDate *t = beginStage(0, "查询 accessBehavior(当前授权状态)");+ reportAccessBehavior(pb);+ endStage(t);++ // ── 阶段 1:changeCount ───────────────────────────────────+ // 「感知到剪贴板变了」的最低成本操作。若此处弹窗,任何后台监听都不可行。+ t = beginStage(1, "读 changeCount(纯计数器)");+ line("changeCount = %ld", (long)pb.changeCount);+ endStage(t);++ // ── 阶段 2:types ─────────────────────────────────────────+ // 传统的类型判断方式。隐私机制生效后这一步是否还免费,是个关键问题。+ t = beginStage(2, "读 types(类型列表,传统方式)");+ NSArray<NSPasteboardType> *types = pb.types;+ line("%lu 种类型:", (unsigned long)types.count);+ for (NSPasteboardType ty in types) fprintf(stderr, " · %s\n", ty.UTF8String);+ endStage(t);++ // ── 阶段 3:detectMetadataForTypes ────────────────────────+ // Apple 官方保证「不通知用户」的元数据探测。+ // 文档示例恰好就是 CopySync 的用例:判断文件引用的 content type。+ // 若此处能拿到足够信息,则「分类」环节完全免提示。+ if (@available(macOS 15.4, *)) {+ t = beginStage(3, "detectMetadataForTypes(官方保证不提示)← CopySync 依赖这个");+ dispatch_semaphore_t sem = dispatch_semaphore_create(0);+ [pb detectMetadataForTypes:[NSSet setWithObject:NSPasteboardMetadataTypeContentType]+ completionHandler:^(NSDictionary<NSPasteboardMetadataType, id> *md, NSError *err) {+ if (err) {+ line("错误:%s", err.localizedDescription.UTF8String);+ } else {+ UTType *ct = md[NSPasteboardMetadataTypeContentType];+ line("ContentType = %s", ct ? ct.identifier.UTF8String : "(nil)");+ if (ct) {+ line(" 是文件夹? %s 是图片? %s 是纯文本? %s",+ [ct conformsToType:UTTypeFolder] ? "是" : "否",+ [ct conformsToType:UTTypeImage] ? "是" : "否",+ [ct conformsToType:UTTypePlainText] ? "是" : "否");+ }+ }+ dispatch_semaphore_signal(sem);+ }];+ if (!waitSpinningRunLoop(sem, 30)) line("⚠️ 等待超时(30s)");+ endStage(t);+ }++ // ── 阶段 4:读取实际内容 ───────────────────────────────────+ // CopySync 的 A 端必须拿到源文件路径才能在对端粘贴时回源。+ // 这一步几乎必然触发提示——关键是用户授权后能否永久静默。+ BOOL hasFile = [types containsObject:NSPasteboardTypeFileURL];+ if (hasFile) {+ t = beginStage(4, "读 public.file-url 实际内容 ← A 端必须拿到的东西");+ NSArray<NSURL *> *urls = [pb readObjectsForClasses:@[NSURL.class] options:nil];+ line("%lu 个文件:", (unsigned long)urls.count);+ for (NSURL *u in urls) {+ NSNumber *isDir = nil, *size = nil;+ [u getResourceValue:&isDir forKey:NSURLIsDirectoryKey error:nil];+ [u getResourceValue:&size forKey:NSURLFileSizeKey error:nil];+ fprintf(stderr, " · %s%s %lld bytes\n", u.path.UTF8String,+ isDir.boolValue ? "/ (目录)" : "", size.longLongValue);+ }+ endStage(t);+ } else if ([types containsObject:NSPasteboardTypeString]) {+ t = beginStage(4, "读 public.utf8-plain-text 实际内容");+ NSString *s = [pb stringForType:NSPasteboardTypeString] ?: @"";+ NSString *p = s.length > 50 ? [[s substringToIndex:50] stringByAppendingString:@"…"] : s;+ line("%lu 字符:\"%s\"", (unsigned long)s.length,+ [p stringByReplacingOccurrencesOfString:@"\n" withString:@"⏎"].UTF8String);+ endStage(t);+ } else if ([types containsObject:NSPasteboardTypePNG] ||+ [types containsObject:NSPasteboardTypeTIFF]) {+ t = beginStage(4, "读图片位图数据");+ NSPasteboardType ty = [types containsObject:NSPasteboardTypePNG]+ ? NSPasteboardTypePNG : NSPasteboardTypeTIFF;+ line("%s → %lu bytes", ty.UTF8String, (unsigned long)[pb dataForType:ty].length);+ endStage(t);+ }++ // ── 阶段 5:读取后再查授权状态 ─────────────────────────────+ // 文档称:首次触发提示后,behavior 会从 Default 自动变为 Ask,+ // 并开始出现在系统设置中。验证这个状态迁移。+ beginStage(5, "读取后再查 accessBehavior(观察状态迁移)");+ reportAccessBehavior(pb);++ fprintf(stderr, "\n ✓ 本轮结束\n");+ fflush(stderr);+}++int main(int argc, const char *argv[]) {+ @autoreleasepool {+ NSApplication *app = NSApplication.sharedApplication;+ [app setActivationPolicy:NSApplicationActivationPolicyAccessory];++ // 轮数限制:便于脚本化测试,跑完 N 轮自动退出+ int maxRounds = (argc > 1) ? atoi(argv[1]) : 0; // 0 = 无限++ banner("Spike A — 剪贴板隐私机制探测");+ NSPasteboard *pb = NSPasteboard.generalPasteboard;+ fprintf(stderr, "\n bundle id : %s\n",+ NSBundle.mainBundle.bundleIdentifier.UTF8String ?: "(无)");+ BOOL previewOn = [NSUserDefaults.standardUserDefaults+ boolForKey:@"EnablePasteboardPrivacyDeveloperPreview"];+ fprintf(stderr, " 隐私预览 : %s\n", previewOn ? "已开启 ✓(预演未来 macOS 行为)" : "未开启");+ fprintf(stderr, " 轮数限制 : %d\n", maxRounds);+ fflush(stderr);+ reportAccessBehavior(pb);++ // 轮询必须跑在主线程。+ //+ // 隐私机制开启后,剪贴板 API 会经由 ViewBridge 与系统 UI 服务通信+ // (为了显示授权弹窗),其内部的 NSCFRunLoopSemaphore 依赖 run loop,+ // 在裸 dispatch queue 上调用会抛异常并崩溃。实测堆栈:+ // reportAccessBehavior → AppKit → ViewBridge -[NSCFRunLoopSemaphore wait]+ // → NSException raise → SIGSEGV+ //+ // 这条约束对 CopySync 同样成立:Go daemon 必须把剪贴板 cgo 调用+ // 调度到主线程,不能在任意 goroutine 里直接调。+ __block NSInteger last = pb.changeCount;+ __block int rounds = 0;+ __block BOOL busy = NO; // probe 可能阻塞在授权弹窗上,防止定时器重入++ fprintf(stderr, "\n 已就绪(changeCount=%ld,主线程轮询),等待复制动作…\n", (long)last);+ fflush(stderr);++ [NSTimer scheduledTimerWithTimeInterval:kPollInterval repeats:YES block:^(NSTimer *timer) {+ if (busy) return;+ NSInteger cur = pb.changeCount;+ if (cur == last) return;+ last = cur;++ busy = YES;+ probe(pb, cur);+ busy = NO;++ if (maxRounds > 0 && ++rounds >= maxRounds) {+ fprintf(stderr, "\n 已完成 %d 轮,退出。\n", rounds);+ fflush(stderr);+ exit(0);+ }+ }];++ [app run];+ }+ return 0;+}diff --git a/spikes/promise/main.m b/spikes/promise/main.mnew file mode 100644index 0000000..03f60e6--- /dev/null+++ b/spikes/promise/main.m@@ -0,0 +1,318 @@+// Spike B — NSFilePromiseProvider 可用性与兼容性验证+//+// 目的:验证 CopySync 的核心机制是否成立——+// 1. 往剪贴板写 file promise 后,目标 App 粘贴时能否触发回调?+// (这是「感知到对方按下 Cmd+V」的唯一途径)+// 2. 回调里能否长时间阻塞(模拟跨网络拉取)而不被系统超时杀掉?+// (决定大文件传输是否可行)+// 3. 哪些 App 支持 promise、哪些只认传统 file-url?+// (决定是否需要降级策略)+//+// 用法:运行后按提示输入命令写入不同形态的剪贴板内容,+// 然后去各个 App 里 Cmd+V,观察终端日志。++#import <Cocoa/Cocoa.h>+#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>++static NSMutableArray *gKeepAlive; // 保持 provider 存活,否则 ARC 会提前释放+static NSOperationQueue *gWorkQueue; // promise 回调在此队列执行,可安全阻塞+static NSTimeInterval gFakeLatency = 5.0; // 模拟「跨网络拉取」的耗时+static NSDate *gWriteTime; // 写入剪贴板的时刻,用于计算用户多久后粘贴++static void banner(const char *s) {+ fprintf(stderr, "\n════════════════════════════════════════════════════════\n");+ fprintf(stderr, " %s\n", s);+ fprintf(stderr, "════════════════════════════════════════════════════════\n");+ fflush(stderr);+}++static void say(const char *fmt, ...) {+ va_list ap; va_start(ap, fmt);+ vfprintf(stderr, fmt, ap);+ fprintf(stderr, "\n");+ va_end(ap);+ fflush(stderr);+}++#pragma mark - Promise delegate++@interface SpikeDelegate : NSObject <NSFilePromiseProviderDelegate>+@end++@implementation SpikeDelegate++// 系统询问「这个 promise 对应的文件叫什么名字」。+// 注意:这一步在粘贴发生之前就会被调用(目标 App 要先知道文件名),+// 所以它**不能**作为「用户按下了 Cmd+V」的信号。+- (NSString *)filePromiseProvider:(NSFilePromiseProvider *)provider+ fileNameForType:(NSString *)fileType {+ NSString *name = provider.userInfo[@"name"];+ say(" ├─ [fileNameForType] 被询问文件名 → %s (type=%s)",+ name.UTF8String, fileType.UTF8String);+ say(" ⚠️ 注意:此回调在粘贴前就会触发,不能当作粘贴信号");+ return name;+}++// ★ 这才是真正的「用户按下了 Cmd+V」信号。+// 系统给我们一个目标 URL,我们在这里把数据写进去。+// CopySync 正式实现中,这里会发出 PullRequest 并把网络流直接写入 url。+- (void)filePromiseProvider:(NSFilePromiseProvider *)provider+ writePromiseToURL:(NSURL *)url+ completionHandler:(void (^)(NSError *))done {+ NSString *name = provider.userInfo[@"name"];+ BOOL isFolder = [provider.userInfo[@"folder"] boolValue];+ NSTimeInterval sincePaste = -[gWriteTime timeIntervalSinceNow];++ say("\n ★★★ [writePromiseToURL] 粘贴被触发!");+ say(" ├─ 文件 : %s%s", name.UTF8String, isFolder ? " (目录)" : "");+ say(" ├─ 目标路径 : %s", url.path.UTF8String);+ say(" ├─ 距写入剪贴板 %.1f 秒", sincePaste);+ say(" ├─ 所在线程 : %s", NSThread.isMainThread ? "主线程 ⚠️" : "后台线程 ✓");+ say(" ├─ 模拟拉取中,将阻塞 %.0f 秒……", gFakeLatency);++ // 模拟跨网络拉取。真实实现中这里是 DataChannel → zstd → tar 的流式写入。+ NSDate *t0 = NSDate.date;+ fprintf(stderr, " │ ");+ for (NSTimeInterval spent = 0; spent < gFakeLatency; spent += 0.5) {+ [NSThread sleepForTimeInterval:0.5];+ fprintf(stderr, "▓"); fflush(stderr);+ }+ fprintf(stderr, "\n");++ NSError *err = nil;+ NSString *body = [NSString stringWithFormat:+ @"CopySync spike B\n写入时刻: %@\n阻塞时长: %.1f 秒\n用户粘贴延迟: %.1f 秒\n",+ NSDate.date, gFakeLatency, sincePaste];++ if (isFolder) {+ [NSFileManager.defaultManager createDirectoryAtURL:url+ withIntermediateDirectories:YES+ attributes:nil error:&err];+ if (!err) {+ for (int i = 1; i <= 3; i++) {+ NSURL *f = [url URLByAppendingPathComponent:+ [NSString stringWithFormat:@"file-%d.txt", i]];+ [body writeToURL:f atomically:YES encoding:NSUTF8StringEncoding error:&err];+ }+ }+ } else {+ [body writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:&err];+ }++ say(" ├─ 写入完成,实际耗时 %.1f 秒", -[t0 timeIntervalSinceNow]);+ say(" └─ %s", err ? (const char *)[NSString stringWithFormat:@"失败: %@", err].UTF8String+ : "成功 ✓ —— 去目标 App 确认文件是否真的出现了");+ done(err);+}++// 指定回调执行的队列。必须是后台队列,否则阻塞会冻结整个 App。+- (NSOperationQueue *)operationQueueForFilePromiseProvider:(NSFilePromiseProvider *)p {+ return gWorkQueue;+}++@end++#pragma mark - 延迟提供 file-url(老式 pasteboard owner 机制)++// NSFilePromiseProvider 主要服务于拖放;Finder 的剪贴板粘贴只认+// public.file-url / NSFilenamesPboardType。+//+// 老式的 declareTypes:owner: 机制允许我们声明这些 Finder 认识的类型,+// 但**不立即提供数据**——系统会在有人真正来取时回调 provideDataForType:。+// 这同样能拿到「用户按下了 Cmd+V」的信号,且目标 App 的兼容性好得多。+@interface LazyFileOwner : NSObject+@end++@implementation LazyFileOwner++- (void)pasteboard:(NSPasteboard *)sender provideDataForType:(NSPasteboardType)type {+ NSTimeInterval since = -[gWriteTime timeIntervalSinceNow];+ say("\n ★★★ [provideDataForType] 粘贴被触发!");+ say(" ├─ 请求类型 : %s", type.UTF8String);+ say(" ├─ 距写入剪贴板 %.1f 秒", since);+ say(" ├─ 所在线程 : %s", NSThread.isMainThread ? "主线程 ← 注意会冻结 UI" : "后台线程");+ say(" ├─ 模拟跨网络拉取,阻塞 %.0f 秒……", gFakeLatency);++ NSDate *t0 = NSDate.date;+ fprintf(stderr, " │ ");+ for (NSTimeInterval s = 0; s < gFakeLatency; s += 0.5) {+ [NSThread sleepForTimeInterval:0.5];+ fprintf(stderr, "▓"); fflush(stderr);+ }+ fprintf(stderr, "\n");++ // 此刻才落盘。真实实现中这里是 DataChannel → zstd → tar 的流式写入。+ NSString *dir = [NSTemporaryDirectory() stringByAppendingPathComponent:@"copysync-lazy"];+ [NSFileManager.defaultManager createDirectoryAtPath:dir+ withIntermediateDirectories:YES attributes:nil error:nil];+ NSString *path = [dir stringByAppendingPathComponent:@"copysync-lazy.txt"];+ NSError *err = nil;+ [[NSString stringWithFormat:+ @"CopySync — 延迟粘贴验证\n落盘时刻: %@\n阻塞时长: %.1f 秒\n粘贴延迟: %.1f 秒\n",+ NSDate.date, gFakeLatency, since]+ writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&err];++ BOOL ok = NO;+ if ([type isEqualToString:NSPasteboardTypeFileURL]) {+ ok = [sender setString:[NSURL fileURLWithPath:path].absoluteString forType:type];+ } else if ([type isEqualToString:NSFilenamesPboardType]) {+ ok = [sender setPropertyList:@[path] forType:type];+ } else {+ ok = [sender setString:path forType:type];+ }++ say(" ├─ 落盘%s 提供数据%s", err ? "失败" : "成功", ok ? "成功" : "失败");+ say(" └─ 回调耗时 %.1f 秒 —— 去 Finder 确认文件是否出现", -[t0 timeIntervalSinceNow]);+}++@end++#pragma mark - 写入剪贴板的几种形态++static SpikeDelegate *gDelegate;+static LazyFileOwner *gLazyOwner;++// 声明 Finder 认识的类型,但不提供数据——等对方来取时才回调+static void writeLazyFileURL(void) {+ NSPasteboard *pb = NSPasteboard.generalPasteboard;+ // declareTypes:owner: 自身会清空剪贴板并递增 changeCount+ [pb declareTypes:@[NSPasteboardTypeFileURL, NSFilenamesPboardType] owner:gLazyOwner];+ gWriteTime = NSDate.date;++ say("\n ✓ 已写入剪贴板:延迟 file-url(declareTypes:owner:,数据暂不提供)");+ say(" 剪贴板类型:");+ for (NSPasteboardType t in pb.types) fprintf(stderr, " · %s\n", t.UTF8String);+ say(" 现在去 Finder 按 Cmd+V");+}++static NSFilePromiseProvider *makeProvider(NSString *name, BOOL folder) {+ UTType *type = folder ? UTTypeFolder+ : ([UTType typeWithFilenameExtension:name.pathExtension] ?: UTTypeData);+ NSFilePromiseProvider *p = [[NSFilePromiseProvider alloc] initWithFileType:type.identifier+ delegate:gDelegate];+ p.userInfo = @{@"name": name, @"folder": @(folder)};+ [gKeepAlive addObject:p];+ return p;+}++static void writeToPasteboard(NSArray *objects, const char *what) {+ NSPasteboard *pb = NSPasteboard.generalPasteboard;+ [pb clearContents];+ BOOL ok = [pb writeObjects:objects];+ gWriteTime = NSDate.date;++ say("\n ✓ 已写入剪贴板:%s", what);+ say(" writeObjects 返回 %s", ok ? "YES" : "NO");+ say(" 剪贴板类型:");+ for (NSPasteboardType t in pb.types) {+ fprintf(stderr, " · %s\n", t.UTF8String);+ }+ say(" 现在去目标 App 按 Cmd+V,观察是否触发 writePromiseToURL");+}++// 对照组:传统的真实文件 URL。用来区分「App 不支持 promise」和「App 完全不能粘文件」。+static void writeRealFile(void) {+ NSURL *dir = [NSURL fileURLWithPath:NSTemporaryDirectory()];+ NSURL *f = [dir URLByAppendingPathComponent:@"copysync-real-file.txt"];+ [@"这是一个真实存在的文件(对照组)\n" writeToURL:f atomically:YES+ encoding:NSUTF8StringEncoding error:nil];+ writeToPasteboard(@[f], "对照组 — 传统 file-url(文件已真实存在)");+ say(" 路径:%s", f.path.UTF8String);+}++#pragma mark - main++// 执行一条写入命令。交互模式和命令行模式共用。+// 返回 NO 表示命令无法识别。+static BOOL doCommand(NSString *cmd) {+ if ([cmd isEqualToString:@"1"] || [cmd isEqualToString:@"single"]) {+ writeToPasteboard(@[makeProvider(@"copysync-single.txt", NO)], "单个文件 promise");+ } else if ([cmd isEqualToString:@"2"] || [cmd isEqualToString:@"folder"]) {+ writeToPasteboard(@[makeProvider(@"copysync-folder", YES)], "文件夹 promise");+ } else if ([cmd isEqualToString:@"3"] || [cmd isEqualToString:@"multi"]) {+ writeToPasteboard(@[makeProvider(@"copysync-a.txt", NO),+ makeProvider(@"copysync-b.txt", NO),+ makeProvider(@"copysync-c.txt", NO)],+ "多文件 promise(3 个)");+ } else if ([cmd isEqualToString:@"4"] || [cmd isEqualToString:@"real"]) {+ writeRealFile();+ } else if ([cmd isEqualToString:@"5"] || [cmd isEqualToString:@"lazy"]) {+ writeLazyFileURL();+ } else {+ return NO;+ }+ return YES;+}++static void printMenu(void) {+ say("\n ┌── 命令 ─────────────────────────────────────────");+ say(" │ 1 单个文件 promise (.txt)");+ say(" │ 2 文件夹 promise(内含 3 个文件)");+ say(" │ 3 多文件 promise(3 个 .txt)");+ say(" │ 4 对照组:传统 file-url(真实文件)");+ say(" │ 5 延迟 file-url(declareTypes:owner:)← 最有希望的方案");+ say(" │ d<秒> 设置模拟拉取延迟,如 d5 / d30 / d120");+ say(" │ q 退出");+ say(" └─────────────────────────────────────────────────");+ fprintf(stderr, " 当前延迟 %.0f 秒 > ", gFakeLatency);+ fflush(stderr);+}++int main(int argc, const char *argv[]) {+ @autoreleasepool {+ gKeepAlive = NSMutableArray.new;+ gDelegate = SpikeDelegate.new;+ gLazyOwner = LazyFileOwner.new; // 必须保持存活,否则系统回调时 owner 已释放+ gWorkQueue = NSOperationQueue.new;+ gWorkQueue.name = @"copysync.spike.promise";+ gWorkQueue.maxConcurrentOperationCount = 4;++ NSApplication *app = NSApplication.sharedApplication;+ [app setActivationPolicy:NSApplicationActivationPolicyAccessory];++ banner("Spike B — NSFilePromiseProvider 可用性验证");++ // 命令行模式:SpikeB <mode> [延迟秒数]+ // 写入后保持存活等待消费方,供脚本自动化测试。+ if (argc > 1) {+ if (argc > 2) gFakeLatency = atof(argv[2]);+ NSString *mode = @(argv[1]);+ say(" 模式:%s 模拟拉取延迟:%.0f 秒", mode.UTF8String, gFakeLatency);+ if (!doCommand(mode)) {+ say(" ✗ 未知模式:%s(可用:single/folder/multi/real)", mode.UTF8String);+ return 1;+ }+ say("\n 等待消费方取件…(进程保持存活)");+ [app run];+ return 0;+ }++ say("\n 要回答的问题:");+ say(" 1. 粘贴时能否触发 writePromiseToURL 回调?");+ say(" 2. 回调里阻塞 %.0f 秒会被系统超时杀掉吗?", gFakeLatency);+ say(" 3. 哪些 App 支持 promise?(Finder / 微信 / 飞书 / Mail / VS Code …)");+ say("\n 测试方法:选一个命令写入剪贴板 → 去目标 App 按 Cmd+V → 看日志");++ dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{+ char buf[64];+ while (true) {+ printMenu();+ if (!fgets(buf, sizeof buf, stdin)) break;+ NSString *cmd = [[NSString stringWithUTF8String:buf]+ stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];++ if ([cmd isEqualToString:@"q"]) { exit(0); }+ else if (doCommand(cmd)) { /* 已处理 */ }+ else if ([cmd hasPrefix:@"d"]) {+ double v = [cmd substringFromIndex:1].doubleValue;+ if (v > 0) { gFakeLatency = v; say(" ✓ 延迟设为 %.0f 秒", v); }+ else say(" ✗ 无效数值");+ }+ else if (cmd.length) say(" ✗ 未知命令:%s", cmd.UTF8String);+ }+ });++ [app run];+ }+ return 0;+}diff --git a/spikes/receiver/main.m b/spikes/receiver/main.mnew file mode 100644index 0000000..a5849c1--- /dev/null+++ b/spikes/receiver/main.m@@ -0,0 +1,107 @@+// Spike D — promise 消费方(模拟「按下 Cmd+V」)+//+// NSFilePromiseReceiver 正是 Finder 等 App 在粘贴 file promise 时内部使用的类。+// 用它可以精确模拟粘贴行为,从而**完全自动化**地验证:+//+// 1. promise 回调是否真的被触发?+// 2. 回调里阻塞 N 秒是否会被系统超时杀掉? ← 决定大文件传输是否可行+// 3. 文件内容是否完整送达?+//+// 这样不必依赖人工去各个 App 里按 Cmd+V,也不需要辅助功能权限。+//+// 用法:SpikeD [目标目录]++#import <Cocoa/Cocoa.h>++int main(int argc, const char *argv[]) {+ @autoreleasepool {+ NSApplication *app = NSApplication.sharedApplication;+ [app setActivationPolicy:NSApplicationActivationPolicyAccessory];++ NSString *destPath = argc > 1 ? @(argv[1]) : @"/tmp/copysync-paste-dest";+ NSURL *dest = [NSURL fileURLWithPath:destPath];+ [NSFileManager.defaultManager createDirectoryAtURL:dest+ withIntermediateDirectories:YES attributes:nil error:nil];++ NSPasteboard *pb = NSPasteboard.generalPasteboard;++ fprintf(stderr, "\n[SpikeD] bundle=%s\n",+ NSBundle.mainBundle.bundleIdentifier.UTF8String);+ fprintf(stderr, "[SpikeD] 粘贴目标目录:%s\n", destPath.UTF8String);+ fprintf(stderr, "[SpikeD] 剪贴板类型:\n");+ for (NSPasteboardType t in pb.types) {+ fprintf(stderr, " · %s\n", t.UTF8String);+ }++ // 从剪贴板取出 promise。这一步等价于 Finder 识别出「剪贴板里是承诺文件」。+ NSArray *receivers = [pb readObjectsForClasses:@[NSFilePromiseReceiver.class]+ options:nil];+ if (receivers.count == 0) {+ fprintf(stderr, "[SpikeD] ✗ 剪贴板里没有 file promise\n");+ fprintf(stderr, " (若剪贴板是普通文件 URL,说明写入方没用 promise 机制)\n");+ return 1;+ }++ fprintf(stderr, "[SpikeD] ✓ 找到 %lu 个 promise,开始请求文件…\n\n",+ (unsigned long)receivers.count);++ NSOperationQueue *q = NSOperationQueue.new;+ __block NSInteger pending = receivers.count;+ __block NSInteger failed = 0;+ NSDate *t0 = NSDate.date;++ for (NSFilePromiseReceiver *r in receivers) {+ fprintf(stderr, "[SpikeD] promise 声明的文件名:%s\n",+ r.fileNames.count ? r.fileNames.description.UTF8String : "(未提供)");++ // ★ 这一步触发对端的 writePromiseToURL 回调,等价于用户按下 Cmd+V+ [r receivePromisedFilesAtDestination:dest+ options:@{}+ operationQueue:q+ reader:^(NSURL *fileURL, NSError *err) {+ NSTimeInterval dt = -[t0 timeIntervalSinceNow];+ if (err) {+ failed++;+ fprintf(stderr, "[SpikeD] ✗ 失败(%.1fs):%s\n",+ dt, err.localizedDescription.UTF8String);+ } else {+ NSNumber *size = nil;+ [fileURL getResourceValue:&size forKey:NSURLFileSizeKey error:nil];+ NSNumber *isDir = nil;+ [fileURL getResourceValue:&isDir forKey:NSURLIsDirectoryKey error:nil];+ fprintf(stderr, "[SpikeD] ✓ 收到(耗时 %.1fs):%s %lld bytes%s\n",+ dt, fileURL.path.UTF8String, size.longLongValue,+ isDir.boolValue ? " (目录)" : "");+ // 打印内容前 200 字节,确认数据完整+ if (!isDir.boolValue) {+ NSString *body = [NSString stringWithContentsOfURL:fileURL+ encoding:NSUTF8StringEncoding+ error:nil];+ if (body.length) {+ NSString *p = body.length > 200 ? [body substringToIndex:200] : body;+ fprintf(stderr, " 内容:%s\n",+ [p stringByReplacingOccurrencesOfString:@"\n"+ withString:@" ⏎ "].UTF8String);+ }+ }+ }+ if (--pending == 0) {+ fprintf(stderr, "\n[SpikeD] 全部完成,总耗时 %.1fs,失败 %ld 个\n",+ -[t0 timeIntervalSinceNow], (long)failed);+ fflush(stderr);+ exit(failed ? 1 : 0);+ }+ }];+ }++ // 兜底超时:promise 若被系统静默丢弃,这里会兜住+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(300 * NSEC_PER_SEC)),+ dispatch_get_main_queue(), ^{+ fprintf(stderr, "\n[SpikeD] ✗ 300 秒仍未全部完成,判定超时\n");+ exit(2);+ });++ [app run];+ }+ return 0;+}diff --git a/spikes/results.md b/spikes/results.mdnew file mode 100644index 0000000..b04a624--- /dev/null+++ b/spikes/results.md@@ -0,0 +1,197 @@+# M-1 Spike 实测结果++环境:macOS 15.7.3 (Sequoia) · Apple clang 17.0.0 · 2026-09-21++---++## Spike A — 剪贴板隐私机制++### 背景更正(比计划中的假设更严重)++计划里写的是「Sequoia 起读剪贴板会弹提示」,实测后发现真实情况是:++- macOS **15.4** 引入该机制,但目前是 **developer preview,默认关闭**+- 需 `defaults write <bundle_id> EnablePasteboardPrivacyDeveloperPreview -bool yes` 才生效+- **下一个 macOS 大版本将强制执行**++所以今天不做任何事也能正常工作,但这是颗定时炸弹。CopySync 的 daemon 正是+「后台程序化读剪贴板」,完全命中被拦截的场景,必须现在就按新机制设计。++参考:[macOS 16 will warn when apps access pasteboard](https://appletreats.substack.com/p/macos-16-will-warn-when-apps-access)++### 实测数据(隐私机制开启时)++写方是独立 bundle id 的真实 GUI App(SpikeC),排除了 pbcopy/osascript+不被 TCC 视作「其他 App」的干扰。++| 阶段 | 操作 | 耗时 | 是否触发授权 |+|---|---|---|---|+| 0 | `pb.accessBehavior` | 0.001s | 否 ✓ |+| 1 | `pb.changeCount` | 0.000s | 否 ✓ |+| 2 | `pb.types`(类型列表) | 0.003s | **否 ✓** |+| 3 | `detectMetadataForTypes:` | 0.021s | **否 ✓** |+| 4 | `readObjectsForClasses:`(读 file-url) | **阻塞 90s 被杀** | **是** |++关闭隐私机制时,阶段 4 仅耗时 0.001s —— 差异完全来自授权拦截。++### 结论 1:类型分类完全免费++`detectMetadataForTypes:` 成功返回 `ContentType = public.plain-text`,+并能正确判断 `conformsToType:` 的文件夹 / 图片 / 纯文本归属。++意味着 CopySync 可以**免提示地**完成:+- 感知剪贴板变化(changeCount)+- 判断复制的是文件 / 文件夹 / 文本 / 图片(detectMetadata + types)++只有拿**源文件真实路径**时才需要授权 —— 而这是 A 端回源所必需的。++### 结论 2:必须在主线程调用剪贴板 API ★++隐私机制开启后,在后台 dispatch queue 上访问剪贴板会**直接崩溃**:++```+reportAccessBehavior → AppKit → ViewBridge -[NSCFRunLoopSemaphore wait]+ → NSException raise → EXC_BAD_ACCESS (SIGSEGV)+```++原因:剪贴板 API 要经 ViewBridge 与系统 UI 服务通信(以便显示授权框),+其内部 `NSCFRunLoopSemaphore` 依赖 run loop,裸 dispatch queue 上无 run loop 可用。++改为主线程 NSTimer 轮询后崩溃消失,变为正常阻塞等待授权。++**对 Go daemon 的直接约束**:剪贴板 cgo 调用不能在任意 goroutine 里发起,+必须调度到锁定的主线程(`runtime.LockOSThread` + 主 run loop),+或通过 `dispatch_async(dispatch_get_main_queue(), …)` 弹回主线程。++同理,等待异步回调时不能裸阻塞,要 spin run loop:++```objc+while (dispatch_semaphore_wait(sem, DISPATCH_TIME_NOW) != 0) {+ [NSRunLoop.currentRunLoop runMode:NSDefaultRunLoopMode+ beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.02]];+}+```++否则一旦 completionHandler 投递到主队列即死锁,且授权弹窗无法显示。++### 结论 3:授权状态会自动迁移++实测 `accessBehavior` 变化:`0 (Default)` → 触发一次弹窗 → `1 (Ask)`。++与 SDK 文档一致:首次触发后 App 开始出现在+「系统设置 → 隐私与安全性 → 从其他 App 粘贴」,用户可切换+Ask / AlwaysAllow / AlwaysDeny。++**设计要点**:读取前先查 `accessBehavior`,若不是 `AlwaysAllow` 就不要贸然读取+(否则会无限阻塞在弹窗上),而应在 UI 里引导用户去系统设置授权。++### 结论 4:粘贴场景天然豁免++SDK 文档明确:`.ask` 和 `.alwaysDeny` 下,+「user originated and paste related」的访问**永远被允许且不通知**。++意味着 B 端 promise 回调里的剪贴板访问不受限制 —— 只有 A 端的后台监听需要授权。++---++---++## Spike B — 延迟渲染(★ 结论:纯懒模式不成立)++### 测了两条路径,都无法感知「用户按下 Cmd+V」++**路径 1:`NSFilePromiseProvider`**++写入剪贴板后类型为 `Apple files promise pasteboard type` 等 promise 私有类型。+Finder 粘贴**毫无反应**,连 `fileNameForType` 都不触发 —— Finder 不认为+剪贴板里有可粘贴的文件。该 API 实际只服务于**拖放**,不覆盖剪贴板粘贴路径。++(用自建的 `NSFilePromiseReceiver` 消费方倒是能触发 `fileNameForType`,+但文件传输始终不完成,最终超时。)++**路径 2:`declareTypes:owner:` + `provideDataForType:`**++声明 Finder 认识的 `public.file-url` / `NSFilenamesPboardType`,不提供数据。+`provideDataForType:` **确实被触发了**,且回调里阻塞 5 秒未被系统杀掉。++但关键在触发时机——实测:++| 阶段 | 操作 | 回调次数 |+|---|---|---|+| 1 | 只写剪贴板,静置 12 秒,不做任何操作 | **1 次,在 0.0 秒** |+| 2 | 打开 Finder 窗口,再等 8 秒 | 仍 1 次,无新增 |+| 3 | 用户真正按 Cmd+V | **不再回调**,直接用缓存 |++用户粘贴出的文件内容自证:`落盘时刻 21:35:51 / 粘贴延迟 0.1 秒`,+而 Finder 窗口 21:35:49 才打开 —— 数据在用户按键前就备好了。++**系统在写入剪贴板后 0.1 秒内立即兑现 promise 并缓存,不等粘贴。**++### 对架构的影响++操作系统不提供「剪贴板被读取」的通知,延迟渲染是唯一能感知粘贴动作的机制。+它失效 ⇒ **无法知道对方何时按下 Cmd+V** ⇒ 「对方不粘贴就不传输」不成立。++可用的部分:`declareTypes:owner:` 能把文件正确送进 Finder 粘贴。+丢掉的是「延迟」,不是「粘贴」。++### 未测(因已不影响结论)++- 拖放场景下 `NSFilePromiseProvider` 是否真正延迟到「放下」时刻+ —— 拖放不是本项目要的交互+- 是否为 Universal Clipboard 导致的立即读取+ —— 即便是,也不能要求用户关闭该系统功能++---++---++## 后续在实现中发现的坑++### pasteboard 服务会被 promise owner 搞成僵尸状态 ★++M-1 的 SpikeB 用 `declareTypes:owner:` 声明了剪贴板所有权,进程被 kill 后,+系统 pasteboard 留下了「有类型声明但无数据」的空壳:++```+$ osascript -e 'clipboard info'+«class utf8», 0, «class ut16», 2, string, 0, Unicode text, 0+ ↑ 所有类型长度都是 0+$ pbpaste # 什么都没有+```++这个状态下**任何程序都读不到剪贴板**,包括 `pbpaste` 和 SpikeA 自己。+排查时一度误判为自己的 cgo 代码有问题,实际上:++```bash+killall pboard # 重启 pasteboard 服务,再复制一次即恢复+```++教训:调试剪贴板问题时,先用 `pbpaste` 确认剪贴板本身是否正常,+再怀疑自己的代码。这条已写入 README 的排障章节。++### 传输层的三个真实故障++均在 macOS 实机联调中撞出,各自对应回归测试+(`internal/transport/p2p/stream_test.go`):++| 现象 | 根因 |+|---|---|+| 控制消息完全收不到 | `SettingEngine.DetachDataChannels()` 是全局开关,开启后所有通道的 `OnMessage`/`Send` 失效 |+| 发 202 字节、收 0 字节 | pion 的 `OnMessage` 不缓冲,handler 设置前到达的消息直接丢弃 |+| zstd 报 "compressed size too big" | 「先缓冲后回放」的实现里,回放期间新消息插队,顺序被打乱 |+| 20 MB 传到 786 KB 卡死 | `OnBufferedAmountLow` 边沿触发,缓冲提前回落导致丢失唤醒 |++### 配对完成瞬间的信令竞态++两端确认配对必然有先后(实测相差 47 ms),先确认方发出的 offer 会被+后确认方当作「未配对设备的消息」丢弃,握手随即石沉大海,只能等 30 秒+超时重来。解法是暂存配对确认前到达的信令、确认后重放——配对完成到+建立直连的实测耗时从 30 秒降到 56 毫秒。++---++## 待确认++- [ ] Windows 侧 `CFSTR_FILECONTENTS` 虚拟文件是否也有同样的「立即兑现」问题+ (Windows 的 `IStream` 延迟渲染机制与 macOS 不同,可能仍然成立)diff --git a/spikes/test-privacy.sh b/spikes/test-privacy.shnew file mode 100755index 0000000..7ed403a--- /dev/null+++ b/spikes/test-privacy.sh@@ -0,0 +1,86 @@+#!/usr/bin/env bash+# 剪贴板隐私机制对照实验+#+# 同一套读取操作,分别在「隐私机制关闭」和「隐私机制开启」下各跑一轮,+# 直接对比哪些操作会被拦截。开启的那一轮预演的就是下一个 macOS 大版本的行为。+#+# 读方 = SpikeA (com.copysync.spike.privacy)+# 写方 = SpikeC (com.copysync.spike.writer) ← 独立 bundle id 的真实 GUI App,+# 这点很重要:pbcopy/osascript 是命令行工具,TCC 可能不当作「其他 App」++set -uo pipefail+cd "$(dirname "$0")"++BUNDLE=com.copysync.spike.privacy+A=./build/SpikeA.app/Contents/MacOS/SpikeA+C=./build/SpikeC.app/Contents/MacOS/SpikeC+TESTFILE=/tmp/copysync-spike-test.txt+MODE=${1:-file} # file | text | image++[[ -x "$A" && -x "$C" ]] || { echo "请先运行 ./build.sh"; exit 1; }+echo "CopySync spike 测试文件 $(date)" > "$TESTFILE"++# 等待进程结束,最多 $2 秒。返回 1 表示超时(通常意味着弹窗在等待用户点击)+wait_pid() {+ local pid=$1 limit=$2 i=0+ while kill -0 "$pid" 2>/dev/null; do+ sleep 1; i=$((i+1))+ [[ $i -ge $limit ]] && return 1+ done+ return 0+}++run_round() {+ local label="$1" log="$2" limit="$3"++ echo+ echo "┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"+ echo "┃ $label"+ echo "┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"++ "$A" 1 > "$log" 2>&1 &+ local apid=$!+ sleep 2++ "$C" "$MODE" "$TESTFILE" > /dev/null 2>&1 &+ local cpid=$!++ if ! wait_pid "$apid" "$limit"; then+ echo+ echo " ⚠️ 超过 ${limit}s 未结束 —— 很可能有授权弹窗正等着你点击。"+ echo " 请看屏幕,点击弹窗后脚本会继续(再等 60s)。"+ wait_pid "$apid" 60 || { echo " 仍未结束,强制终止。"; kill -9 "$apid" 2>/dev/null; }+ fi++ kill "$cpid" 2>/dev/null+ wait "$cpid" 2>/dev/null+ cat "$log"+}++echo "模式:$MODE 测试文件:$TESTFILE"++# ── 第一轮:隐私机制关闭(当前 macOS 15.7 的默认行为)────────+defaults delete "$BUNDLE" EnablePasteboardPrivacyDeveloperPreview 2>/dev/null+run_round "第 1 轮 — 隐私机制【关闭】(今天的默认行为)" /tmp/spike-priv-off.log 30++# ── 第二轮:隐私机制开启(预演下一个 macOS 大版本)──────────+defaults write "$BUNDLE" EnablePasteboardPrivacyDeveloperPreview -bool yes+run_round "第 2 轮 — 隐私机制【开启】(预演未来 macOS 的强制行为)" /tmp/spike-priv-on.log 25++cat <<EOF++━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+对比要点+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ · 阶段 1/2/3 在两轮中是否都无阻塞?+ → 决定 CopySync 能否免提示地「感知变化 + 判断类型」+ · 阶段 4(读实际内容)在第 2 轮是否阻塞/弹窗?+ → 决定 A 端拿源文件路径是否需要用户授权+ · 阶段 5 的 accessBehavior 是否从 Default 迁移到 Ask?+ → 验证「首次触发后出现在系统设置中」++日志:/tmp/spike-priv-off.log /tmp/spike-priv-on.log++清理开关(重要,避免影响后续测试):+ defaults delete $BUNDLE EnablePasteboardPrivacyDeveloperPreview+EOFdiff --git a/spikes/writer/main.m b/spikes/writer/main.mnew file mode 100644index 0000000..9e12edc--- /dev/null+++ b/spikes/writer/main.m@@ -0,0 +1,66 @@+// Spike C — 「复制方」模拟器+//+// 存在的唯一理由:给 Spike A 提供一个**真实 GUI App** 身份的剪贴板写入方。+//+// pbcopy / osascript 是命令行工具,TCC 可能不把它们当作「其他 App」,+// 用它们测出的「没有隐私提示」不可采信。这个程序有自己独立的+// bundle identifier 且是 NSApplication,与真实 App(Finder/微信)同等地位。+//+// 用法:+// SpikeC file <路径> 把文件 URL 写进剪贴板+// SpikeC text <内容> 把文本写进剪贴板+// SpikeC image 把一张生成的图片写进剪贴板++#import <Cocoa/Cocoa.h>++int main(int argc, const char *argv[]) {+ @autoreleasepool {+ NSApplication *app = NSApplication.sharedApplication;+ [app setActivationPolicy:NSApplicationActivationPolicyAccessory];++ NSString *mode = argc > 1 ? @(argv[1]) : @"text";+ NSString *arg = argc > 2 ? @(argv[2]) : @"default payload";++ NSPasteboard *pb = NSPasteboard.generalPasteboard;+ [pb clearContents];++ BOOL ok = NO;+ NSString *desc = nil;++ if ([mode isEqualToString:@"file"]) {+ NSURL *url = [NSURL fileURLWithPath:arg];+ ok = [pb writeObjects:@[url]];+ desc = [NSString stringWithFormat:@"file-url → %@", arg];++ } else if ([mode isEqualToString:@"image"]) {+ // 生成一张纯色图,模拟截图+ NSImage *img = [[NSImage alloc] initWithSize:NSMakeSize(320, 200)];+ [img lockFocus];+ [[NSColor systemTealColor] setFill];+ NSRectFill(NSMakeRect(0, 0, 320, 200));+ [img unlockFocus];+ ok = [pb writeObjects:@[img]];+ desc = @"image (320x200)";++ } else {+ ok = [pb setString:arg forType:NSPasteboardTypeString];+ desc = [NSString stringWithFormat:@"text → \"%@\"", arg];+ }++ fprintf(stderr,+ "[SpikeC] bundle=%s\n"+ "[SpikeC] 已写入:%s\n"+ "[SpikeC] 结果=%s changeCount=%ld\n"+ "[SpikeC] 保持存活 40 秒(模拟真实 App 持有剪贴板)…\n",+ NSBundle.mainBundle.bundleIdentifier.UTF8String,+ desc.UTF8String,+ ok ? "OK" : "FAIL",+ (long)pb.changeCount);+ fflush(stderr);++ // 真实 App 复制后不会立刻退出。保持存活,确保读方读取时+ // 剪贴板 owner 仍是一个活着的、不同 bundle id 的 GUI 进程。+ [NSThread sleepForTimeInterval:40];+ }+ return 0;+}diff --git a/tools/dmg/background.swift b/tools/dmg/background.swiftnew file mode 100644index 0000000..7347422--- /dev/null+++ b/tools/dmg/background.swift@@ -0,0 +1,69 @@+// 绘制 DMG 安装窗口的背景图(1x 与 2x 两份,由 tiffutil 合成一张多分辨率 TIFF)。+//+// swift tools/dmg/background.swift <输出目录>+//+// 版式与 scripts/package.sh 里 Finder 窗口的设置一一对应:+// 窗口 640×400,App 图标中心在 (160, 190),「应用程序」在 (480, 190)。++import AppKit++let W: CGFloat = 640, H: CGFloat = 400+let ink = NSColor(srgbRed: 0x1D / 255.0, green: 0x1D / 255.0, blue: 0x1F / 255.0, alpha: 1)+let dim = NSColor(srgbRed: 0x6E / 255.0, green: 0x6E / 255.0, blue: 0x73 / 255.0, alpha: 1)+let faint = NSColor(srgbRed: 0xB4 / 255.0, green: 0xB4 / 255.0, blue: 0xB8 / 255.0, alpha: 1)+let paper = NSColor(srgbRed: 0xF5 / 255.0, green: 0xF5 / 255.0, blue: 0xF4 / 255.0, alpha: 1)++/// 以左上角为原点给出坐标,换算成 AppKit 的左下原点。+func y(_ top: CGFloat) -> CGFloat { H - top }++func text(_ s: String, size: CGFloat, weight: NSFont.Weight, color: NSColor, centerTop: CGFloat) {+ let attrs: [NSAttributedString.Key: Any] = [+ .font: NSFont.systemFont(ofSize: size, weight: weight),+ .foregroundColor: color,+ ]+ let str = NSAttributedString(string: s, attributes: attrs)+ let sz = str.size()+ str.draw(at: NSPoint(x: (W - sz.width) / 2, y: y(centerTop) - sz.height / 2))+}++func draw() {+ paper.setFill()+ NSRect(x: 0, y: 0, width: W, height: H).fill()++ // 两个图标之间的箭头:细线,不抢图标的戏+ let arrow = NSBezierPath()+ arrow.lineWidth = 2+ arrow.lineCapStyle = .round+ arrow.lineJoinStyle = .round+ arrow.move(to: NSPoint(x: 246, y: y(190)))+ arrow.line(to: NSPoint(x: 394, y: y(190)))+ arrow.move(to: NSPoint(x: 382, y: y(180)))+ arrow.line(to: NSPoint(x: 394, y: y(190)))+ arrow.line(to: NSPoint(x: 382, y: y(200)))+ faint.setStroke()+ arrow.stroke()++ text("把 CopySync 拖到「应用程序」文件夹", size: 14, weight: .medium, color: ink, centerTop: 300)+ text("Drag CopySync to the Applications folder", size: 12, weight: .regular, color: dim, centerTop: 322)+ text("首次打开如被拦截:系统设置 → 隐私与安全性 → 仍要打开", size: 11, weight: .regular,+ color: dim, centerTop: 366)+}++func render(scale: CGFloat, to url: URL) throws {+ let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(W * scale),+ pixelsHigh: Int(H * scale), bitsPerSample: 8, samplesPerPixel: 4,+ hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB,+ bytesPerRow: 0, bitsPerPixel: 0)!+ rep.size = NSSize(width: W, height: H) // 2x 图的点尺寸仍是 640×400+ NSGraphicsContext.saveGraphicsState()+ NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)+ draw()+ NSGraphicsContext.restoreGraphicsState()+ try rep.representation(using: .png, properties: [:])!.write(to: url)+}++let out = URL(fileURLWithPath: CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : ".")+try FileManager.default.createDirectory(at: out, withIntermediateDirectories: true)+try render(scale: 1, to: out.appendingPathComponent("background.png"))+try render(scale: 2, to: out.appendingPathComponent("[email protected]"))+print("✓ \(out.path)")diff --git a/tools/icon/render.swift b/tools/icon/render.swiftnew file mode 100644index 0000000..5b88ac9--- /dev/null+++ b/tools/icon/render.swift@@ -0,0 +1,109 @@+// 绘制 CopySync 的 App 图标,输出各尺寸 PNG。+//+// swift tools/icon/render.swift <输出目录>+//+// 造型:两张错位的纸。后一张描边、前一张实色,表示「这台复制、那台出现」。+// 网站用的 tools/icon/icon.svg 与这里的几何参数一一对应,改动时两边同步。+// 画布按 Apple 的 macOS 图标网格:1024 画布,主体 824×824 居中,四周留出阴影空间。++import AppKit++let graphite = NSColor(srgbRed: 0x2C / 255.0, green: 0x2C / 255.0, blue: 0x2E / 255.0, alpha: 1)+let blue = NSColor(srgbRed: 0x0A / 255.0, green: 0x66 / 255.0, blue: 0xD8 / 255.0, alpha: 1)+let bodyTop = NSColor(srgbRed: 0xFB / 255.0, green: 0xFB / 255.0, blue: 0xFA / 255.0, alpha: 1)+let bodyBottom = NSColor(srgbRed: 0xE8 / 255.0, green: 0xE8 / 255.0, blue: 0xE6 / 255.0, alpha: 1)+let paper = NSColor(srgbRed: 0xF5 / 255.0, green: 0xF5 / 255.0, blue: 0xF4 / 255.0, alpha: 1)++/// 以 1024 画布、左上角为原点的坐标描述图形,绘制时再翻转到 CoreGraphics 的左下原点。+func draw(in ctx: CGContext) {+ ctx.translateBy(x: 0, y: 1024)+ ctx.scaleBy(x: 1, y: -1)++ // ── 主体:圆角方块 + 投影 ──+ let body = CGPath(roundedRect: CGRect(x: 100, y: 100, width: 824, height: 824),+ cornerWidth: 184, cornerHeight: 184, transform: nil)+ ctx.saveGState()+ // 阴影偏移不受上面的翻转影响,仍按左下原点计,负值才是向下+ ctx.setShadow(offset: CGSize(width: 0, height: -12), blur: 28,+ color: NSColor(white: 0, alpha: 0.28).cgColor)+ ctx.addPath(body)+ ctx.setFillColor(bodyBottom.cgColor)+ ctx.fillPath()+ ctx.restoreGState()++ // 自上而下极轻的明暗,模拟 macOS 图标统一的顶光+ ctx.saveGState()+ ctx.addPath(body)+ ctx.clip()+ let grad = CGGradient(colorsSpace: CGColorSpace(name: CGColorSpace.sRGB),+ colors: [bodyTop.cgColor, bodyBottom.cgColor] as CFArray,+ locations: [0, 1])!+ ctx.drawLinearGradient(grad, start: CGPoint(x: 512, y: 100), end: CGPoint(x: 512, y: 924),+ options: [])+ ctx.restoreGState()++ // ── 后一张纸:描边 ──+ // 两张纸沿对角线拉开,只在一角重叠:两边的三行字都完整露出,+ // 读作「同一份内容在两处」,而不是系统里那个「拷贝」符号+ let back = CGRect(x: 230, y: 220, width: 340, height: 420)+ let backPath = CGPath(roundedRect: back, cornerWidth: 44, cornerHeight: 44, transform: nil)+ ctx.addPath(backPath)+ ctx.setFillColor(paper.cgColor)+ ctx.fillPath()+ ctx.addPath(backPath)+ ctx.setStrokeColor(graphite.cgColor)+ ctx.setLineWidth(28)+ ctx.strokePath()+ lines(in: ctx, sheet: back, color: graphite.withAlphaComponent(0.85))++ // ── 前一张纸:实色,压在后一张上 ──+ let front = CGRect(x: 454, y: 384, width: 340, height: 420)+ let frontPath = CGPath(roundedRect: front, cornerWidth: 44, cornerHeight: 44, transform: nil)+ ctx.saveGState()+ ctx.setShadow(offset: CGSize(width: 0, height: -10), blur: 24,+ color: NSColor(white: 0, alpha: 0.22).cgColor)+ ctx.addPath(frontPath)+ ctx.setFillColor(blue.cgColor)+ ctx.fillPath()+ ctx.restoreGState()+ lines(in: ctx, sheet: front, color: NSColor(white: 1, alpha: 0.95))+}++/// 纸上的三行字:长、中、短。+func lines(in ctx: CGContext, sheet: CGRect, color: NSColor) {+ let x = sheet.minX + 60+ let widths: [CGFloat] = [200, 150, 104]+ ctx.setFillColor(color.cgColor)+ for (i, w) in widths.enumerated() {+ let y = sheet.minY + 90 + CGFloat(i) * 80+ let bar = CGPath(roundedRect: CGRect(x: x, y: y, width: w, height: 30),+ cornerWidth: 15, cornerHeight: 15, transform: nil)+ ctx.addPath(bar)+ ctx.fillPath()+ }+}++func render(size: Int, to url: URL) throws {+ let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: size, pixelsHigh: size,+ bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true,+ isPlanar: false, colorSpaceName: .deviceRGB,+ bytesPerRow: 0, bitsPerPixel: 0)!+ let gctx = NSGraphicsContext(bitmapImageRep: rep)!+ let ctx = gctx.cgContext+ ctx.interpolationQuality = .high+ ctx.setShouldAntialias(true)+ ctx.scaleBy(x: CGFloat(size) / 1024, y: CGFloat(size) / 1024)+ draw(in: ctx)+ gctx.flushGraphics()+ guard let png = rep.representation(using: .png, properties: [:]) else {+ throw NSError(domain: "icon", code: 1)+ }+ try png.write(to: url)+}++let out = URL(fileURLWithPath: CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : ".")+try FileManager.default.createDirectory(at: out, withIntermediateDirectories: true)+for size in [16, 32, 64, 128, 180, 256, 512, 1024] {+ try render(size: size, to: out.appendingPathComponent("icon_\(size).png"))+}+print("✓ \(out.path)")diff --git a/tools/screenshots/frame.swift b/tools/screenshots/frame.swiftnew file mode 100644index 0000000..24c48f7--- /dev/null+++ b/tools/screenshots/frame.swift@@ -0,0 +1,85 @@+// 给渲染出的界面截图加上 macOS 窗口外框:圆角、窗口阴影、红绿灯按钮与细边框。+//+// swift tools/screenshots/frame.swift <输入目录> <输出目录>+//+// 输入是 2 倍图(960×640 的窗口渲染为 1920×1280)。红绿灯的位置量自真实窗口:+// 直径 12pt,圆心距窗口左上角 14pt,间隔 20pt。++import AppKit++let scale: CGFloat = 2+let radius: CGFloat = 10 * scale+let margin = (left: 48 * scale, right: 48 * scale, top: 32 * scale, bottom: 64 * scale)++func rgb(_ hex: UInt32, _ a: CGFloat = 1) -> CGColor {+ CGColor(srgbRed: CGFloat((hex >> 16) & 0xFF) / 255, green: CGFloat((hex >> 8) & 0xFF) / 255,+ blue: CGFloat(hex & 0xFF) / 255, alpha: a)+}++func frame(_ input: URL, to output: URL) throws {+ guard let src = NSBitmapImageRep(data: try Data(contentsOf: input))?.cgImage else { return }+ let dark = input.lastPathComponent.contains("dark")+ let w = CGFloat(src.width), h = CGFloat(src.height)+ let W = Int(w + margin.left + margin.right), H = Int(h + margin.top + margin.bottom)++ let ctx = CGContext(data: nil, width: W, height: H, bitsPerComponent: 8, bytesPerRow: 0,+ space: CGColorSpace(name: CGColorSpace.sRGB)!,+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!+ // CoreGraphics 原点在左下;窗口矩形按左上原点算好再换算+ let win = CGRect(x: margin.left, y: margin.bottom, width: w, height: h)+ let shape = CGPath(roundedRect: win, cornerWidth: radius, cornerHeight: radius, transform: nil)++ // macOS 的窗口阴影:大而淡,略向下+ ctx.saveGState()+ ctx.setShadow(offset: CGSize(width: 0, height: -18 * scale), blur: 40 * scale,+ color: rgb(0x000000, dark ? 0.45 : 0.22))+ ctx.addPath(shape)+ ctx.setFillColor(rgb(0x000000))+ ctx.fillPath()+ ctx.restoreGState()++ ctx.saveGState()+ ctx.addPath(shape)+ ctx.clip()+ ctx.draw(src, in: win)+ ctx.restoreGState()++ // 细边框:浅色窗口是一圈淡灰,深色窗口是一圈淡白+ ctx.addPath(CGPath(roundedRect: win.insetBy(dx: 0.5, dy: 0.5), cornerWidth: radius,+ cornerHeight: radius, transform: nil))+ ctx.setStrokeColor(dark ? rgb(0xFFFFFF, 0.14) : rgb(0x000000, 0.16))+ ctx.setLineWidth(1)+ ctx.strokePath()++ // 红绿灯+ let lights: [(UInt32, UInt32)] = [(0xFF5F57, 0xE2463F), (0xFEBC2E, 0xE1A116), (0x28C840, 0x14AE2B)]+ for (i, (fill, stroke)) in lights.enumerated() {+ let cx = win.minX + (14 + CGFloat(i) * 20) * scale+ let cy = win.maxY - 14 * scale+ let r = 6 * scale+ let dot = CGRect(x: cx - r, y: cy - r, width: r * 2, height: r * 2)+ ctx.setFillColor(rgb(fill))+ ctx.fillEllipse(in: dot)+ ctx.setStrokeColor(rgb(stroke, 0.9))+ ctx.setLineWidth(1)+ ctx.strokeEllipse(in: dot.insetBy(dx: 0.5, dy: 0.5))+ }++ let rep = NSBitmapImageRep(cgImage: ctx.makeImage()!)+ try rep.representation(using: .png, properties: [:])!.write(to: output)+}++let args = CommandLine.arguments+let inDir = URL(fileURLWithPath: args[1]), outDir = URL(fileURLWithPath: args[2])+try FileManager.default.createDirectory(at: outDir, withIntermediateDirectories: true)+for name in try FileManager.default.contentsOfDirectory(atPath: inDir.path) where name.hasSuffix(".png") {+ let src = inDir.appendingPathComponent(name), dst = outDir.appendingPathComponent(name)+ // card- 开头的是单独渲染的对话框,自带圆角与阴影,不套窗口外框+ if name.hasPrefix("card-") {+ try? FileManager.default.removeItem(at: dst)+ try FileManager.default.copyItem(at: src, to: dst)+ } else {+ try frame(src, to: dst)+ }+}+print("✓ \(outDir.path)")diff --git a/tools/screenshots/prepare_fonts.py b/tools/screenshots/prepare_fonts.pynew file mode 100644index 0000000..734be3c--- /dev/null+++ b/tools/screenshots/prepare_fonts.py@@ -0,0 +1,54 @@+"""从本机的 macOS 系统字体生成截图渲染用的静态字体文件。++ python3 tools/screenshots/prepare_fonts.py <输出目录>++Flutter 的测试环境只认单个字体文件里的第一个字形集,也不会把字重映射到可变字体的轴上,+直接加载系统字体的话标题会是"假粗体"。这里把 PingFang.ttc 拆成单独的字重,+把可变字体 SFNS.ttf 实例化成固定字重,让截图与真实 App 的渲染一致。++这些是 Apple 的系统字体,只在本机生成到临时目录,不要提交进仓库。+需要 fonttools:pip install fonttools+"""++import glob+import os+import sys++from fontTools.ttLib import TTCollection, TTFont+from fontTools.varLib.instancer import instantiateVariableFont++out = sys.argv[1] if len(sys.argv) > 1 else "fonts"+os.makedirs(out, exist_ok=True)++# ── 中文:PingFang SC 的三个字重 ──+pingfang = (glob.glob("/System/Library/AssetsV2/com_apple_MobileAsset_Font*/*/AssetData/PingFang.ttc")+ + glob.glob("/System/Library/Fonts/PingFang.ttc"))[0]+wanted = {"PingFang SC Regular": "PingFang-Regular", "PingFang SC Medium": "PingFang-Medium",+ "PingFang SC Semibold": "PingFang-Semibold"}+for font in TTCollection(pingfang).fonts:+ name = font["name"].getDebugName(4)+ if name in wanted:+ font.save(os.path.join(out, wanted.pop(name) + ".ttf"))+if wanted:+ sys.exit(f"PingFang.ttc 里缺少:{', '.join(wanted)}")++# ── 等宽:Menlo,用于配对码与安全指纹 ──+menlo = {"Menlo Regular": "Menlo-Regular", "Menlo Bold": "Menlo-Bold"}+for font in TTCollection("/System/Library/Fonts/Menlo.ttc").fonts:+ name = font["name"].getDebugName(4)+ if name in menlo:+ font.save(os.path.join(out, menlo.pop(name) + ".ttf"))++# ── 西文:SF Pro 实例化为固定字重(opsz 取正文尺寸)──+for weight, label in [(400, "Regular"), (500, "Medium"), (600, "Semibold")]:+ vf = TTFont("/System/Library/Fonts/SFNS.ttf")+ axes = {a.axisTag: a for a in vf["fvar"].axes}+ loc = {"wght": weight}+ if "opsz" in axes:+ loc["opsz"] = max(axes["opsz"].minValue, min(17, axes["opsz"].maxValue))+ for tag, a in axes.items():+ loc.setdefault(tag, a.defaultValue)+ instantiateVariableFont(vf, loc, inplace=True)+ vf.save(os.path.join(out, f"SF-{label}.ttf"))++print("✓", out)diff --git a/tools/screenshots/render.sh b/tools/screenshots/render.shnew file mode 100755index 0000000..aaa4f39--- /dev/null+++ b/tools/screenshots/render.sh@@ -0,0 +1,23 @@+#!/usr/bin/env bash+# 重新生成 README 与网站用的界面截图,输出到 docs/assets/screenshots/。+#+# ./tools/screenshots/render.sh+#+# 截图用演示数据渲染,不连接后台服务,不会出现本机真实的剪贴板内容。+# 需要 macOS、Flutter,以及 fonttools(pip install fonttools)。++set -euo pipefail+cd "$(dirname "$0")/../.."++FONTS=$(mktemp -d)+trap 'rm -rf "$FONTS"' EXIT++echo "▶ 准备字体"+python3 tools/screenshots/prepare_fonts.py "$FONTS"++echo "▶ 渲染界面"+rm -rf ui/tool/screenshots/out+(cd ui && SCREENSHOT_FONTS="$FONTS" flutter test tool/screenshots/screenshots_test.dart 2>&1 | tail -1)++echo "▶ 加窗口外框"+swift tools/screenshots/frame.swift ui/tool/screenshots/out docs/assets/screenshotsdiff --git a/tools/site/og.swift b/tools/site/og.swiftnew file mode 100644index 0000000..2edfb3b--- /dev/null+++ b/tools/site/og.swift@@ -0,0 +1,62 @@+// 生成网站的分享图(Open Graph,1200×630):左侧图标与标题,右侧露出一部分真实截图。+//+// swift tools/site/og.swift+//+// 输出 docs/assets/og.png(中文)与 docs/assets/og-en.png(英文)。++import AppKit++let W: CGFloat = 1200, H: CGFloat = 630+let paper = NSColor(srgbRed: 0xF5 / 255.0, green: 0xF5 / 255.0, blue: 0xF4 / 255.0, alpha: 1)+let ink = NSColor(srgbRed: 0x1D / 255.0, green: 0x1D / 255.0, blue: 0x1F / 255.0, alpha: 1)+let dim = NSColor(srgbRed: 0x6E / 255.0, green: 0x6E / 255.0, blue: 0x73 / 255.0, alpha: 1)++func render(title: String, note: String, to path: String) throws {+ let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(W), pixelsHigh: Int(H),+ bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,+ colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!+ NSGraphicsContext.saveGraphicsState()+ NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)+ defer { NSGraphicsContext.restoreGraphicsState() }++ paper.setFill()+ NSRect(x: 0, y: 0, width: W, height: H).fill()++ // 右侧截图:带窗口外框的那张,向右下出血+ if let shot = NSImage(contentsOfFile: "docs/assets/screenshots/history.png") {+ let h: CGFloat = 560+ let w = h * shot.size.width / shot.size.height+ shot.draw(in: NSRect(x: 600, y: H - 70 - h, width: w, height: h))+ }++ // 左侧:图标、产品名、一句话、注脚(坐标按左上原点换算)+ func y(_ top: CGFloat, _ height: CGFloat) -> CGFloat { H - top - height }+ NSImage(contentsOfFile: "assets/brand/icon-1024.png")?+ .draw(in: NSRect(x: 64, y: y(72, 112), width: 112, height: 112))++ let name = NSAttributedString(string: "CopySync", attributes: [+ .font: NSFont.systemFont(ofSize: 34, weight: .semibold), .foregroundColor: ink,+ ])+ name.draw(at: NSPoint(x: 80, y: y(200, 42)))++ let para = NSMutableParagraphStyle()+ para.lineSpacing = 6+ let headline = NSAttributedString(string: title, attributes: [+ .font: NSFont.systemFont(ofSize: 54, weight: .bold), .foregroundColor: ink,+ .paragraphStyle: para, .kern: -1,+ ])+ headline.draw(in: NSRect(x: 80, y: y(262, 150), width: 540, height: 150))++ let foot = NSAttributedString(string: note, attributes: [+ .font: NSFont.systemFont(ofSize: 22, weight: .regular), .foregroundColor: dim,+ ])+ foot.draw(at: NSPoint(x: 80, y: y(470, 28)))++ try rep.representation(using: .png, properties: [:])!.write(to: URL(fileURLWithPath: path))+}++try render(title: "在这台 Mac 复制,\n到那台 Mac 粘贴。", note: "免费开源,macOS 13 及以上",+ to: "docs/assets/og.png")+try render(title: "Copy on this Mac.\nPaste on that one.", note: "Free and open source, macOS 13+",+ to: "docs/assets/og-en.png")+print("✓ docs/assets/og.png, og-en.png")diff --git a/ui/.gitignore b/ui/.gitignorenew file mode 100644index 0000000..3820a95--- /dev/null+++ b/ui/.gitignore@@ -0,0 +1,45 @@+# Miscellaneous+*.class+*.log+*.pyc+*.swp+.DS_Store+.atom/+.build/+.buildlog/+.history+.svn/+.swiftpm/+migrate_working_dir/++# IntelliJ related+*.iml+*.ipr+*.iws+.idea/++# The .vscode folder contains launch configuration and tasks you configure in+# VS Code which you may wish to be included in version control, so this line+# is commented out by default.+#.vscode/++# Flutter/Dart/Pub related+**/doc/api/+**/ios/Flutter/.last_build_id+.dart_tool/+.flutter-plugins-dependencies+.pub-cache/+.pub/+/build/+/coverage/++# Symbolication related+app.*.symbols++# Obfuscation related+app.*.map.json++# Android Studio will place build artifacts here+/android/app/debug+/android/app/profile+/android/app/releasediff --git a/ui/.metadata b/ui/.metadatanew file mode 100644index 0000000..875bc02--- /dev/null+++ b/ui/.metadata@@ -0,0 +1,33 @@+# This file tracks properties of this Flutter project.+# Used by Flutter tool to assess capabilities and perform upgrades etc.+#+# This file should be version controlled and should not be manually edited.++version:+ revision: "6b182d2c7585eba26d4edce0f97630effd256c33"+ channel: "stable"++project_type: app++# Tracks metadata for the flutter migrate command+migration:+ platforms:+ - platform: root+ create_revision: 6b182d2c7585eba26d4edce0f97630effd256c33+ base_revision: 6b182d2c7585eba26d4edce0f97630effd256c33+ - platform: macos+ create_revision: 6b182d2c7585eba26d4edce0f97630effd256c33+ base_revision: 6b182d2c7585eba26d4edce0f97630effd256c33+ - platform: windows+ create_revision: 6b182d2c7585eba26d4edce0f97630effd256c33+ base_revision: 6b182d2c7585eba26d4edce0f97630effd256c33++ # User provided section++ # List of Local paths (relative to this file) that should be+ # ignored by the migrate tool.+ #+ # Files that are not part of the templates will be ignored by default.+ unmanaged_files:+ - 'lib/main.dart'+ - 'ios/Runner.xcodeproj/project.pbxproj'diff --git a/ui/README.md b/ui/README.mdnew file mode 100644index 0000000..1e46a96--- /dev/null+++ b/ui/README.md@@ -0,0 +1,21 @@+# CopySync 界面++CopySync 的 macOS 界面(Flutter):复制记录、设备配对、设置,以及首次启动时启用后台同步。++界面本身不碰剪贴板,也不联网:所有操作都经本机 gRPC 交给后台服务 `copysyncd`+(见 `../client-core`)。连接信息由后台服务写在+`~/Library/Application Support/CopySync/daemon.json`。++```bash+flutter run -d macos # 开发运行,需要后台服务已在运行(../scripts/install-macos.sh)+flutter test # 界面测试+```++| 目录 | 内容 |+|---|---|+| `lib/app_state.dart` | 唯一的状态源:连接、断线重连、事件合并 |+| `lib/background_service.dart` | 把内置的后台服务注册为登录项、升级后重启 |+| `lib/pages/` | 复制记录、设备、设置、首次启动引导 |+| `lib/theme.dart` | 颜色、字号、间距 |+| `lib/gen/` | 由 `../proto` 生成的代码,不要手改 |+| `tool/screenshots/` | 用演示数据渲染 README 与网站的截图,见 `../tools/screenshots/render.sh` |diff --git a/ui/analysis_options.yaml b/ui/analysis_options.yamlnew file mode 100644index 0000000..0d29021--- /dev/null+++ b/ui/analysis_options.yaml@@ -0,0 +1,28 @@+# This file configures the analyzer, which statically analyzes Dart code to+# check for errors, warnings, and lints.+#+# The issues identified by the analyzer are surfaced in the UI of Dart-enabled+# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be+# invoked from the command line by running `flutter analyze`.++# The following line activates a set of recommended lints for Flutter apps,+# packages, and plugins designed to encourage good coding practices.+include: package:flutter_lints/flutter.yaml++linter:+ # The lint rules applied to this project can be customized in the+ # section below to disable rules from the `package:flutter_lints/flutter.yaml`+ # included above or to enable additional rules. A list of all available lints+ # and their documentation is published at https://dart.dev/lints.+ #+ # Instead of disabling a lint rule for the entire project in the+ # section below, it can also be suppressed for a single line of code+ # or a specific dart file by using the `// ignore: name_of_lint` and+ # `// ignore_for_file: name_of_lint` syntax on the line or in the file+ # producing the lint.+ rules:+ # avoid_print: false # Uncomment to disable the `avoid_print` rule+ # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule++# Additional information about this file can be found at+# https://dart.dev/guides/language/analysis-optionsdiff --git a/ui/assets/app_icon.png b/ui/assets/app_icon.pngnew file mode 100644index 0000000..1b544a7Binary files /dev/null and b/ui/assets/app_icon.png differdiff --git a/ui/lib/app_state.dart b/ui/lib/app_state.dartnew file mode 100644index 0000000..2c0bf9d--- /dev/null+++ b/ui/lib/app_state.dart@@ -0,0 +1,349 @@+import 'dart:async';++import 'package:flutter/foundation.dart';+import 'package:grpc/grpc.dart';++import 'background_service.dart';+import 'daemon_client.dart';+import 'gen/copysync/v1/daemon.pb.dart';+import 'gen/copysync/v1/daemon.pbgrpc.dart' show DaemonServiceClient;++/// daemon 连接的生命周期状态。+enum LinkState { connecting, online, offline }++/// 应用的单一状态源。+///+/// 所有与 daemon 的交互都经过这里:页面只读状态、调方法,不直接碰 gRPC。+/// 这样断线重连、事件合并这些琐事集中在一处,页面代码保持干净。+class AppState extends ChangeNotifier {+ AppState({BackgroundService? service}) : service = service ?? BackgroundService();++ final BackgroundService service;++ DaemonConnection? _conn;+ StreamSubscription<Event>? _events;+ Timer? _retry;++ LinkState _link = LinkState.connecting;+ String? _error;+ Status? _status;+ Config? _config;+ Device? _self;+ List<Device> _peers = const [];+ final List<ClipRecord> _records = [];++ /// 待用户核对指纹的配对请求。非空时界面弹出确认。+ Device? _pendingPairing;++ /// 连不上后台服务时,它的安装状态。界面据此决定显示欢迎页还是重启提示。+ ServiceState? _serviceState;+ bool _serviceChecked = false;++ LinkState get link => _link;+ String? get error => _error;+ Status? get status => _status;+ Config? get config => _config;+ Device? get self => _self;+ List<Device> get peers => List.unmodifiable(_peers);+ List<ClipRecord> get records => List.unmodifiable(_records);+ Device? get pendingPairing => _pendingPairing;+ ServiceState? get serviceState => _serviceState;++ bool get isOnline => _link == LinkState.online;+ int get onlinePeerCount => _peers.where((p) => p.online).length;++ @override+ void dispose() {+ _retry?.cancel();+ _events?.cancel();+ _conn?.close();+ super.dispose();+ }++ // ─────────────────────────── 连接 ───────────────────────────++ Future<void> connect() async {+ _retry?.cancel();+ _setLink(LinkState.connecting, null);++ try {+ final conn = await DaemonConnection.connect();+ _conn = conn;++ // 首屏需要的数据一次取齐,避免界面分几次闪烁+ final results = await Future.wait([+ conn.client.listHistory(ListHistoryRequest(limit: 200)),+ conn.client.getConfig(Empty()),+ conn.client.getStatus(Empty()),+ ]);++ _records+ ..clear()+ ..addAll((results[0] as ListHistoryResponse).records);+ _config = results[1] as Config;+ _status = results[2] as Status;++ await _loadDevices();++ _events = conn.client.subscribe(SubscribeRequest()).listen(+ _onEvent,+ onError: (Object e) => _scheduleRetry('连接中断:${_describe(e)}'),+ onDone: () => _scheduleRetry('后台服务已断开'),+ );++ _serviceState = null;+ _setLink(LinkState.online, null);+ _ensureServiceCurrent();+ } on DaemonNotRunning {+ await _refreshServiceState();+ _scheduleRetry('后台服务未运行');+ } catch (e) {+ await _refreshServiceState();+ _scheduleRetry(_describe(e));+ }+ }++ Future<void> _refreshServiceState() async {+ try {+ _serviceState = await service.state();+ } catch (_) {+ _serviceState = null;+ }+ }++ /// 连上的后台服务不一定是这个 App 内置的那份,每次启动核对一次:+ /// - 登录项指向别处(旧版脚本装的、或 App 换了位置):改为指向当前 App+ /// - 覆盖安装了新版 App:launchd 里跑的还是旧进程,按新的可执行文件重启+ /// 两种情况都会让当前连接断开,随后的自动重连会连上新进程。+ Future<void> _ensureServiceCurrent() async {+ if (!service.available || _serviceChecked) return;+ _serviceChecked = true;+ try {+ final s = await service.state();+ if (s == ServiceState.stale) {+ await service.install();+ return;+ }+ final running = _status?.version ?? '';+ if (s == ServiceState.running &&+ appVersion != 'dev' &&+ running.isNotEmpty &&+ running != appVersion) {+ await service.restart();+ }+ } catch (_) {+ // 核对失败不影响使用:旧进程仍在正常工作+ }+ }++ /// 截图与界面测试用:直接填入数据,不连接后台服务。+ @visibleForTesting+ void debugSeed({+ required Status status,+ required Config config,+ required Device self,+ List<Device> peers = const [],+ List<ClipRecord> records = const [],+ Device? pendingPairing,+ LinkState link = LinkState.online,+ ServiceState? serviceState,+ }) {+ _status = status;+ _config = config;+ _self = self;+ _peers = peers;+ _records+ ..clear()+ ..addAll(records);+ _pendingPairing = pendingPairing;+ _serviceState = serviceState;+ _link = link;+ notifyListeners();+ }++ // ─────────────────────────── 后台服务 ───────────────────────────++ /// 注册后台服务并连接。用于首次启用,也用于修复被移动过的 App。+ Future<void> enableService() async {+ await service.install();+ await _refreshServiceState();+ await connect();+ }++ Future<void> restartService() async {+ await service.restart();+ await connect();+ }++ /// 停用后台服务:关闭同步并取消开机自启。+ Future<void> disableService() async {+ _retry?.cancel();+ await service.uninstall();+ await _refreshServiceState();+ _scheduleRetry('后台服务已停用');+ }++ Future<void> _loadDevices() async {+ final conn = _conn;+ if (conn == null) return;+ try {+ final resp = await conn.client.listDevices(Empty());+ _self = resp.self;+ _peers = resp.peers;+ notifyListeners();+ } on GrpcError catch (e) {+ // 配对能力尚未接入时返回 Unimplemented,属预期情况+ if (e.code != StatusCode.unimplemented) rethrow;+ }+ }++ void _scheduleRetry(String message) {+ _events?.cancel();+ _events = null;+ _conn?.close();+ _conn = null;+ _setLink(LinkState.offline, message);+ // daemon 可能正在重启,自动重连省去用户手动操作+ _retry = Timer(const Duration(seconds: 3), connect);+ }++ void _setLink(LinkState state, String? error) {+ _link = state;+ _error = error;+ notifyListeners();+ }++ void _onEvent(Event ev) {+ final added = ev.whichPayload();+ switch (added) {+ case Event_Payload.clipAdded:+ _records.insert(0, ev.clipAdded);+ if (_records.length > 500) _records.removeLast();++ case Event_Payload.clipUpdated:+ final i = _records.indexWhere((r) => r.id == ev.clipUpdated.id);+ if (i >= 0) {+ _records[i] = ev.clipUpdated;+ } else {+ _records.insert(0, ev.clipUpdated);+ }++ case Event_Payload.clipRemoved:+ _records.removeWhere((r) => r.id == ev.clipRemoved);++ case Event_Payload.deviceChanged:+ _onDeviceChanged(ev.deviceChanged);++ case Event_Payload.statusChanged:+ _status = ev.statusChanged;++ case Event_Payload.progress:+ final i = _records.indexWhere((r) => r.id == ev.progress.clipId);+ if (i >= 0) {+ _records[i] = _records[i]..status = ClipStatus.CLIP_STATUS_FETCHING;+ }++ default:+ break;+ }+ notifyListeners();+ }++ void _onDeviceChanged(Device d) {+ // 带 pairingSession 的不是已配对设备,而是一条待确认的配对请求+ if (d.pairingSession.isNotEmpty) {+ _pendingPairing = d;+ return;+ }+ final i = _peers.indexWhere((p) => p.id == d.id);+ final next = List<Device>.from(_peers);+ if (i >= 0) {+ next[i] = d;+ } else {+ next.add(d);+ }+ _peers = next;+ }++ // ─────────────────────────── 操作 ───────────────────────────++ DaemonServiceClient get _client {+ final c = _conn;+ if (c == null) throw StateError('后台服务未连接');+ return c.client;+ }++ Future<String> createPairingCode() async {+ final resp = await _client.createPairingCode(Empty());+ return resp.code;+ }++ /// 兑换配对码,返回待核对指纹的对端信息。+ Future<Device> redeemPairingCode(String code) async {+ final resp = await _client.redeemPairingCode(+ RedeemPairingCodeRequest(code: code.trim().toUpperCase()),+ );+ _pendingPairing = resp.peer..pairingSession = resp.pairingSession;+ notifyListeners();+ return _pendingPairing!;+ }++ Future<void> confirmPairing(String session, bool accept) async {+ await _client.confirmPairing(+ ConfirmPairingRequest(pairingSession: session, accept: accept),+ );+ _pendingPairing = null;+ await _loadDevices();+ }++ void dismissPendingPairing() {+ _pendingPairing = null;+ notifyListeners();+ }++ Future<void> unpair(String deviceId) async {+ await _client.unpair(UnpairRequest(deviceId: deviceId));+ _peers = _peers.where((p) => p.id != deviceId).toList();+ notifyListeners();+ }++ Future<void> updateConfig(Config next) async {+ _config = await _client.updateConfig(next);+ notifyListeners();+ }++ Future<void> deleteRecords({List<String>? ids, bool all = false}) async {+ await _client.deleteHistory(+ DeleteHistoryRequest(ids: ids ?? const [], all: all),+ );+ if (all) {+ _records.clear();+ } else if (ids != null) {+ _records.removeWhere((r) => ids.contains(r.id));+ }+ notifyListeners();+ }++ Future<void> fetch(String clipId) =>+ _client.fetch(FetchRequest(clipId: clipId));++ Future<void> applyToClipboard(String clipId) =>+ _client.applyToClipboard(ApplyToClipboardRequest(clipId: clipId));++ Future<void> requestClipboardPermission() =>+ _client.requestClipboardPermission(Empty());++ /// 把 gRPC 异常翻译成用户能看懂的话,而不是抛一串堆栈。+ static String _describe(Object e) {+ if (e is GrpcError) {+ if (e.code == StatusCode.unimplemented) return '该功能尚未接入';+ if (e.code == StatusCode.unavailable) return '无法连接后台服务';+ return e.message ?? e.codeName;+ }+ if (e is DaemonNotRunning) return '后台服务未运行';+ if (e is StateError) return e.message;+ return e.toString();+ }++ static String describeError(Object e) => _describe(e);+}diff --git a/ui/lib/background_service.dart b/ui/lib/background_service.dartnew file mode 100644index 0000000..872b606--- /dev/null+++ b/ui/lib/background_service.dart@@ -0,0 +1,155 @@+import 'dart:io';++/// 构建时注入的版本号(build.sh 传 --dart-define=APP_VERSION)。+/// 用来判断后台服务是不是跟界面同一个版本。+const appVersion = String.fromEnvironment('APP_VERSION', defaultValue: 'dev');++/// 后台服务的安装状态。+enum ServiceState {+ /// 开发构建:App 包里没有内置后台服务,只能用源码目录的脚本安装+ unavailable,++ /// 直接从 DMG 里打开、或被系统随机化路径(App Translocation)运行:+ /// 这时注册的登录项会指向一个随时消失的路径,必须先把 App 移到「应用程序」+ mustMove,++ /// 尚未注册为登录项+ notInstalled,++ /// 已注册,但指向的不是当前这个 App(被移动过,或旧版脚本装的)+ stale,++ /// 已注册,launchd 中没有在运行+ stopped,++ running,+}++/// 管理随 App 一起分发的后台服务(剪贴板监听与同步进程)。+///+/// 后台服务内置在 `CopySync.app/Contents/Helpers/` 下,由界面在首次启动时+/// 注册成 launchd 的 LaunchAgent:开机自启、崩溃自动拉起,关掉窗口也照常同步。+/// 用 LaunchAgent 而非 LaunchDaemon:剪贴板属于登录用户的会话,系统级进程访问不到。+class BackgroundService {+ BackgroundService({String? executable, String? home})+ : _executable = executable ?? Platform.resolvedExecutable,+ _home = home ?? Platform.environment['HOME'] ?? '';++ static const label = 'com.copysync.daemon';++ final String _executable;+ final String _home;++ /// `…/CopySync.app`,由可执行文件 `…/CopySync.app/Contents/MacOS/CopySync` 上溯三级。+ String get _bundle => File(_executable).parent.parent.parent.path;++ String get helperApp => '$_bundle/Contents/Helpers/CopySyncDaemon.app';+ String get helperBinary => '$helperApp/Contents/MacOS/copysyncd';+ String get plistPath => '$_home/Library/LaunchAgents/$label.plist';+ String get logPath => '$_home/Library/Logs/CopySync/daemon.log';++ /// 旧版 install.sh 装在这里,迁移时清理掉+ String get _legacyApp => '$_home/Applications/CopySyncDaemon.app';++ bool get available => Platform.isMacOS && File(helperBinary).existsSync();++ bool get _runningFromTemporaryLocation =>+ _bundle.startsWith('/Volumes/') || _bundle.contains('/AppTranslocation/');++ Future<ServiceState> state() async {+ if (!available) return ServiceState.unavailable;+ if (_runningFromTemporaryLocation) return ServiceState.mustMove;+ final plist = File(plistPath);+ if (!await plist.exists()) return ServiceState.notInstalled;+ if (!(await plist.readAsString()).contains(helperBinary)) return ServiceState.stale;+ final r = await Process.run('launchctl', ['print', await _target()]);+ if (r.exitCode != 0) return ServiceState.stopped;+ return '${r.stdout}'.contains('state = running')+ ? ServiceState.running+ : ServiceState.stopped;+ }++ /// 注册并启动。重复调用即为修复:先注销旧的再重新注册。+ Future<void> install() async {+ await _bootout();++ final legacy = Directory(_legacyApp);+ if (await legacy.exists()) await legacy.delete(recursive: true);++ // 用户打开 App 时已经放行过整个包,内置的后台服务不该再被隔离属性拦下:+ // launchd 拉起它时没有任何弹窗可以让用户确认+ await Process.run('xattr', ['-dr', 'com.apple.quarantine', helperApp]);++ await Directory(File(plistPath).parent.path).create(recursive: true);+ await Directory(File(logPath).parent.path).create(recursive: true);+ await File(plistPath).writeAsString(_plist());++ final r = await Process.run('launchctl', ['bootstrap', await _domain(), plistPath]);+ if (r.exitCode != 0) {+ throw ServiceException('启动后台服务失败:${'${r.stderr}'.trim()}');+ }+ }++ /// 让 launchd 结束旧进程并按当前的 App 重新拉起。用于 App 更新后。+ Future<void> restart() async {+ final r = await Process.run('launchctl', ['kickstart', '-k', await _target()]);+ if (r.exitCode != 0) {+ throw ServiceException('重启后台服务失败:${'${r.stderr}'.trim()}');+ }+ }++ /// 停用并移除登录项。数据目录保留,重新启用后历史记录与配对关系都还在。+ Future<void> uninstall() async {+ await _bootout();+ final plist = File(plistPath);+ if (await plist.exists()) await plist.delete();+ }++ Future<void> _bootout() async {+ await Process.run('launchctl', ['bootout', await _target()]);+ // bootout 是异步的:旧服务没注销干净就 bootstrap 会报 "Bootstrap failed: 5"+ for (var i = 0; i < 20; i++) {+ final r = await Process.run('launchctl', ['print', await _target()]);+ if (r.exitCode != 0) return;+ await Future<void>.delayed(const Duration(milliseconds: 250));+ }+ }++ String? _uid;+ Future<String> _domain() async {+ _uid ??= '${(await Process.run('id', ['-u'])).stdout}'.trim();+ return 'gui/$_uid';+ }++ Future<String> _target() async => '${await _domain()}/$label';++ String _plist() => '''+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key> <string>$label</string>+ <key>ProgramArguments</key>+ <array>+ <string>${_xml(helperBinary)}</string>+ </array>+ <key>RunAtLoad</key> <true/>+ <key>KeepAlive</key> <true/>+ <key>ThrottleInterval</key> <integer>10</integer>+ <key>StandardOutPath</key> <string>${_xml(logPath)}</string>+ <key>StandardErrorPath</key> <string>${_xml(logPath)}</string>+ <key>ProcessType</key> <string>Interactive</string>+</dict>+</plist>+''';++ static String _xml(String s) =>+ s.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>');+}++class ServiceException implements Exception {+ ServiceException(this.message);+ final String message;+ @override+ String toString() => message;+}diff --git a/ui/lib/daemon_client.dart b/ui/lib/daemon_client.dartnew file mode 100644index 0000000..723d955--- /dev/null+++ b/ui/lib/daemon_client.dart@@ -0,0 +1,101 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';++import 'package:grpc/grpc.dart';++import 'gen/copysync/v1/daemon.pbgrpc.dart';++/// daemon 写在数据目录下的握手信息。+///+/// daemon 监听 127.0.0.1 的随机端口,把端口与一次性 token 写进 daemon.json。+/// 用 token 是因为本机任意进程都能连上回环端口,仅"只监听 127.0.0.1"不够。+class DaemonEndpoint {+ const DaemonEndpoint({+ required this.port,+ required this.token,+ required this.pid,+ required this.version,+ });++ final int port;+ final String token;+ final int pid;+ final String version;++ factory DaemonEndpoint.fromJson(Map<String, dynamic> json) => DaemonEndpoint(+ port: json['port'] as int,+ token: json['token'] as String,+ pid: json['pid'] as int? ?? 0,+ version: json['version'] as String? ?? '',+ );++ /// 数据目录。必须与 Go 侧 config.DefaultPaths() 完全一致,+ /// 否则 UI 找不到 daemon。+ ///+ /// 刻意不用 path_provider:它在 macOS 上返回的是+ /// `~/Library/Application Support/<bundle_id>`,与 daemon 用的+ /// `~/Library/Application Support/CopySync` 并不是同一个位置。+ static String defaultDataDir() {+ if (Platform.isMacOS) {+ final home = Platform.environment['HOME'] ?? '';+ return '$home/Library/Application Support/CopySync';+ }+ if (Platform.isWindows) {+ final base = Platform.environment['LOCALAPPDATA'] ??+ Platform.environment['APPDATA'] ??+ '';+ return '$base\\CopySync';+ }+ final home = Platform.environment['HOME'] ?? '';+ return '$home/.config/copysync';+ }++ static File endpointFile([String? dataDir]) =>+ File('${dataDir ?? defaultDataDir()}${Platform.pathSeparator}daemon.json');++ static Future<DaemonEndpoint> read([String? dataDir]) async {+ final file = endpointFile(dataDir);+ if (!await file.exists()) {+ throw DaemonNotRunning('未找到 ${file.path}');+ }+ final raw = jsonDecode(await file.readAsString()) as Map<String, dynamic>;+ return DaemonEndpoint.fromJson(raw);+ }+}++class DaemonNotRunning implements Exception {+ DaemonNotRunning(this.detail);+ final String detail;+ @override+ String toString() => 'daemon 未运行($detail)';+}++/// 与 daemon 的一条 gRPC 连接。+class DaemonConnection {+ DaemonConnection._(this._channel, this.client, this.endpoint);++ final ClientChannel _channel;+ final DaemonServiceClient client;+ final DaemonEndpoint endpoint;++ static Future<DaemonConnection> connect({String? dataDir}) async {+ final ep = await DaemonEndpoint.read(dataDir);+ final channel = ClientChannel(+ '127.0.0.1',+ port: ep.port,+ options: const ChannelOptions(+ credentials: ChannelCredentials.insecure(),+ // daemon 在本机,握手应当很快;连不上就尽快报错而不是干等+ connectionTimeout: Duration(seconds: 5),+ ),+ );+ final client = DaemonServiceClient(+ channel,+ options: CallOptions(metadata: {'x-copysync-token': ep.token}),+ );+ return DaemonConnection._(channel, client, ep);+ }++ Future<void> close() => _channel.shutdown();+}diff --git a/ui/lib/gen/copysync/v1/daemon.pb.dart b/ui/lib/gen/copysync/v1/daemon.pb.dartnew file mode 100644index 0000000..0e0395e--- /dev/null+++ b/ui/lib/gen/copysync/v1/daemon.pb.dart@@ -0,0 +1,1848 @@+// This is a generated file - do not edit.+//+// Generated from copysync/v1/daemon.proto.++// @dart = 3.3++// ignore_for_file: annotate_overrides, camel_case_types, comment_references+// ignore_for_file: constant_identifier_names+// ignore_for_file: curly_braces_in_flow_control_structures+// ignore_for_file: deprecated_member_use_from_same_package, library_prefixes+// ignore_for_file: non_constant_identifier_names, prefer_relative_imports++import 'dart:core' as $core;++import 'package:fixnum/fixnum.dart' as $fixnum;+import 'package:protobuf/protobuf.dart' as $pb;++import 'daemon.pbenum.dart';++export 'package:protobuf/protobuf.dart' show GeneratedMessageGenericExtensions;++export 'daemon.pbenum.dart';++class Empty extends $pb.GeneratedMessage {+ factory Empty() => Empty._();++ Empty._();++ factory Empty.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ Empty()..mergeFromBuffer(data, registry);+ factory Empty.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ Empty()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'Empty',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: Empty.$_createMessage)+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ Empty clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ Empty copyWith(void Function(Empty) updates) =>+ super.copyWith((message) => updates(message as Empty)) as Empty;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use Empty() / Empty.new instead')+ static Empty create() => Empty._();+ static $pb.GeneratedMessage $_createMessage() => Empty._();+ @$core.override+ Empty createEmptyInstance() => Empty._();+ @$core.pragma('dart2js:noInline')+ static Empty getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<Empty>(Empty.$_createMessage);+ static Empty? _defaultInstance;+}++class ClipItem extends $pb.GeneratedMessage {+ factory ClipItem({+ $core.String? name,+ $fixnum.Int64? size,+ $core.bool? isDir,+ $core.String? contentType,+ }) {+ final result = ClipItem._();+ if (name != null) result.name = name;+ if (size != null) result.size = size;+ if (isDir != null) result.isDir = isDir;+ if (contentType != null) result.contentType = contentType;+ return result;+ }++ ClipItem._();++ factory ClipItem.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ClipItem()..mergeFromBuffer(data, registry);+ factory ClipItem.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ClipItem()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'ClipItem',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: ClipItem.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'name')+ ..aInt64(2, _omitFieldNames ? '' : 'size')+ ..aOB(3, _omitFieldNames ? '' : 'isDir')+ ..aOS(4, _omitFieldNames ? '' : 'contentType')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ClipItem clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ClipItem copyWith(void Function(ClipItem) updates) =>+ super.copyWith((message) => updates(message as ClipItem)) as ClipItem;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use ClipItem() / ClipItem.new instead')+ static ClipItem create() => ClipItem._();+ static $pb.GeneratedMessage $_createMessage() => ClipItem._();+ @$core.override+ ClipItem createEmptyInstance() => ClipItem._();+ @$core.pragma('dart2js:noInline')+ static ClipItem getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<ClipItem>(ClipItem.$_createMessage);+ static ClipItem? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get name => $_getSZ(0);+ @$pb.TagNumber(1)+ set name($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasName() => $_has(0);+ @$pb.TagNumber(1)+ void clearName() => $_clearField(1);++ @$pb.TagNumber(2)+ $fixnum.Int64 get size => $_getI64(1);+ @$pb.TagNumber(2)+ set size($fixnum.Int64 value) => $_setInt64(1, value);+ @$pb.TagNumber(2)+ $core.bool hasSize() => $_has(1);+ @$pb.TagNumber(2)+ void clearSize() => $_clearField(2);++ @$pb.TagNumber(3)+ $core.bool get isDir => $_getBF(2);+ @$pb.TagNumber(3)+ set isDir($core.bool value) => $_setBool(2, value);+ @$pb.TagNumber(3)+ $core.bool hasIsDir() => $_has(2);+ @$pb.TagNumber(3)+ void clearIsDir() => $_clearField(3);++ @$pb.TagNumber(4)+ $core.String get contentType => $_getSZ(3);+ @$pb.TagNumber(4)+ set contentType($core.String value) => $_setString(3, value);+ @$pb.TagNumber(4)+ $core.bool hasContentType() => $_has(3);+ @$pb.TagNumber(4)+ void clearContentType() => $_clearField(4);+}++class ClipRecord extends $pb.GeneratedMessage {+ factory ClipRecord({+ $core.String? id,+ ClipKind? kind,+ ClipStatus? status,+ $core.String? originDeviceId,+ $core.String? originDeviceName,+ $core.bool? outgoing,+ $core.Iterable<ClipItem>? items,+ $fixnum.Int64? totalSize,+ $core.String? textPreview,+ $fixnum.Int64? createdAtUnix,+ $fixnum.Int64? expiresAtUnix,+ $core.String? error,+ }) {+ final result = ClipRecord._();+ if (id != null) result.id = id;+ if (kind != null) result.kind = kind;+ if (status != null) result.status = status;+ if (originDeviceId != null) result.originDeviceId = originDeviceId;+ if (originDeviceName != null) result.originDeviceName = originDeviceName;+ if (outgoing != null) result.outgoing = outgoing;+ if (items != null) result.items.addAll(items);+ if (totalSize != null) result.totalSize = totalSize;+ if (textPreview != null) result.textPreview = textPreview;+ if (createdAtUnix != null) result.createdAtUnix = createdAtUnix;+ if (expiresAtUnix != null) result.expiresAtUnix = expiresAtUnix;+ if (error != null) result.error = error;+ return result;+ }++ ClipRecord._();++ factory ClipRecord.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ClipRecord()..mergeFromBuffer(data, registry);+ factory ClipRecord.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ClipRecord()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'ClipRecord',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: ClipRecord.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'id')+ ..aE<ClipKind>(2, _omitFieldNames ? '' : 'kind',+ enumValues: ClipKind.values)+ ..aE<ClipStatus>(3, _omitFieldNames ? '' : 'status',+ enumValues: ClipStatus.values)+ ..aOS(4, _omitFieldNames ? '' : 'originDeviceId')+ ..aOS(5, _omitFieldNames ? '' : 'originDeviceName')+ ..aOB(6, _omitFieldNames ? '' : 'outgoing')+ ..pPM<ClipItem>(7, _omitFieldNames ? '' : 'items',+ subBuilder: ClipItem.$_createMessage)+ ..aInt64(8, _omitFieldNames ? '' : 'totalSize')+ ..aOS(9, _omitFieldNames ? '' : 'textPreview')+ ..aInt64(10, _omitFieldNames ? '' : 'createdAtUnix')+ ..aInt64(11, _omitFieldNames ? '' : 'expiresAtUnix')+ ..aOS(12, _omitFieldNames ? '' : 'error')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ClipRecord clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ClipRecord copyWith(void Function(ClipRecord) updates) =>+ super.copyWith((message) => updates(message as ClipRecord)) as ClipRecord;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use ClipRecord() / ClipRecord.new instead')+ static ClipRecord create() => ClipRecord._();+ static $pb.GeneratedMessage $_createMessage() => ClipRecord._();+ @$core.override+ ClipRecord createEmptyInstance() => ClipRecord._();+ @$core.pragma('dart2js:noInline')+ static ClipRecord getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<ClipRecord>(ClipRecord.$_createMessage);+ static ClipRecord? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get id => $_getSZ(0);+ @$pb.TagNumber(1)+ set id($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasId() => $_has(0);+ @$pb.TagNumber(1)+ void clearId() => $_clearField(1);++ @$pb.TagNumber(2)+ ClipKind get kind => $_getN(1);+ @$pb.TagNumber(2)+ set kind(ClipKind value) => $_setField(2, value);+ @$pb.TagNumber(2)+ $core.bool hasKind() => $_has(1);+ @$pb.TagNumber(2)+ void clearKind() => $_clearField(2);++ @$pb.TagNumber(3)+ ClipStatus get status => $_getN(2);+ @$pb.TagNumber(3)+ set status(ClipStatus value) => $_setField(3, value);+ @$pb.TagNumber(3)+ $core.bool hasStatus() => $_has(2);+ @$pb.TagNumber(3)+ void clearStatus() => $_clearField(3);++ @$pb.TagNumber(4)+ $core.String get originDeviceId => $_getSZ(3);+ @$pb.TagNumber(4)+ set originDeviceId($core.String value) => $_setString(3, value);+ @$pb.TagNumber(4)+ $core.bool hasOriginDeviceId() => $_has(3);+ @$pb.TagNumber(4)+ void clearOriginDeviceId() => $_clearField(4);++ @$pb.TagNumber(5)+ $core.String get originDeviceName => $_getSZ(4);+ @$pb.TagNumber(5)+ set originDeviceName($core.String value) => $_setString(4, value);+ @$pb.TagNumber(5)+ $core.bool hasOriginDeviceName() => $_has(4);+ @$pb.TagNumber(5)+ void clearOriginDeviceName() => $_clearField(5);++ @$pb.TagNumber(6)+ $core.bool get outgoing => $_getBF(5);+ @$pb.TagNumber(6)+ set outgoing($core.bool value) => $_setBool(5, value);+ @$pb.TagNumber(6)+ $core.bool hasOutgoing() => $_has(5);+ @$pb.TagNumber(6)+ void clearOutgoing() => $_clearField(6);++ @$pb.TagNumber(7)+ $pb.PbList<ClipItem> get items => $_getList(6);++ @$pb.TagNumber(8)+ $fixnum.Int64 get totalSize => $_getI64(7);+ @$pb.TagNumber(8)+ set totalSize($fixnum.Int64 value) => $_setInt64(7, value);+ @$pb.TagNumber(8)+ $core.bool hasTotalSize() => $_has(7);+ @$pb.TagNumber(8)+ void clearTotalSize() => $_clearField(8);++ @$pb.TagNumber(9)+ $core.String get textPreview => $_getSZ(8);+ @$pb.TagNumber(9)+ set textPreview($core.String value) => $_setString(8, value);+ @$pb.TagNumber(9)+ $core.bool hasTextPreview() => $_has(8);+ @$pb.TagNumber(9)+ void clearTextPreview() => $_clearField(9);++ @$pb.TagNumber(10)+ $fixnum.Int64 get createdAtUnix => $_getI64(9);+ @$pb.TagNumber(10)+ set createdAtUnix($fixnum.Int64 value) => $_setInt64(9, value);+ @$pb.TagNumber(10)+ $core.bool hasCreatedAtUnix() => $_has(9);+ @$pb.TagNumber(10)+ void clearCreatedAtUnix() => $_clearField(10);++ @$pb.TagNumber(11)+ $fixnum.Int64 get expiresAtUnix => $_getI64(10);+ @$pb.TagNumber(11)+ set expiresAtUnix($fixnum.Int64 value) => $_setInt64(10, value);+ @$pb.TagNumber(11)+ $core.bool hasExpiresAtUnix() => $_has(10);+ @$pb.TagNumber(11)+ void clearExpiresAtUnix() => $_clearField(11);++ @$pb.TagNumber(12)+ $core.String get error => $_getSZ(11);+ @$pb.TagNumber(12)+ set error($core.String value) => $_setString(11, value);+ @$pb.TagNumber(12)+ $core.bool hasError() => $_has(11);+ @$pb.TagNumber(12)+ void clearError() => $_clearField(12);+}++class SubscribeRequest extends $pb.GeneratedMessage {+ factory SubscribeRequest({+ $fixnum.Int64? sinceUnix,+ }) {+ final result = SubscribeRequest._();+ if (sinceUnix != null) result.sinceUnix = sinceUnix;+ return result;+ }++ SubscribeRequest._();++ factory SubscribeRequest.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ SubscribeRequest()..mergeFromBuffer(data, registry);+ factory SubscribeRequest.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ SubscribeRequest()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'SubscribeRequest',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: SubscribeRequest.$_createMessage)+ ..aInt64(1, _omitFieldNames ? '' : 'sinceUnix')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ SubscribeRequest clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ SubscribeRequest copyWith(void Function(SubscribeRequest) updates) =>+ super.copyWith((message) => updates(message as SubscribeRequest))+ as SubscribeRequest;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use SubscribeRequest() / SubscribeRequest.new instead')+ static SubscribeRequest create() => SubscribeRequest._();+ static $pb.GeneratedMessage $_createMessage() => SubscribeRequest._();+ @$core.override+ SubscribeRequest createEmptyInstance() => SubscribeRequest._();+ @$core.pragma('dart2js:noInline')+ static SubscribeRequest getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<SubscribeRequest>(+ SubscribeRequest.$_createMessage);+ static SubscribeRequest? _defaultInstance;++ /// 断线重连时带上最后收到的记录时间,daemon 补发这之后的记录+ @$pb.TagNumber(1)+ $fixnum.Int64 get sinceUnix => $_getI64(0);+ @$pb.TagNumber(1)+ set sinceUnix($fixnum.Int64 value) => $_setInt64(0, value);+ @$pb.TagNumber(1)+ $core.bool hasSinceUnix() => $_has(0);+ @$pb.TagNumber(1)+ void clearSinceUnix() => $_clearField(1);+}++class TransferProgress extends $pb.GeneratedMessage {+ factory TransferProgress({+ $core.String? clipId,+ $fixnum.Int64? transferred,+ $fixnum.Int64? total,+ $core.double? bytesPerSecond,+ }) {+ final result = TransferProgress._();+ if (clipId != null) result.clipId = clipId;+ if (transferred != null) result.transferred = transferred;+ if (total != null) result.total = total;+ if (bytesPerSecond != null) result.bytesPerSecond = bytesPerSecond;+ return result;+ }++ TransferProgress._();++ factory TransferProgress.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ TransferProgress()..mergeFromBuffer(data, registry);+ factory TransferProgress.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ TransferProgress()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'TransferProgress',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: TransferProgress.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'clipId')+ ..aInt64(2, _omitFieldNames ? '' : 'transferred')+ ..aInt64(3, _omitFieldNames ? '' : 'total')+ ..aD(4, _omitFieldNames ? '' : 'bytesPerSecond')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ TransferProgress clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ TransferProgress copyWith(void Function(TransferProgress) updates) =>+ super.copyWith((message) => updates(message as TransferProgress))+ as TransferProgress;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use TransferProgress() / TransferProgress.new instead')+ static TransferProgress create() => TransferProgress._();+ static $pb.GeneratedMessage $_createMessage() => TransferProgress._();+ @$core.override+ TransferProgress createEmptyInstance() => TransferProgress._();+ @$core.pragma('dart2js:noInline')+ static TransferProgress getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<TransferProgress>(+ TransferProgress.$_createMessage);+ static TransferProgress? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get clipId => $_getSZ(0);+ @$pb.TagNumber(1)+ set clipId($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasClipId() => $_has(0);+ @$pb.TagNumber(1)+ void clearClipId() => $_clearField(1);++ @$pb.TagNumber(2)+ $fixnum.Int64 get transferred => $_getI64(1);+ @$pb.TagNumber(2)+ set transferred($fixnum.Int64 value) => $_setInt64(1, value);+ @$pb.TagNumber(2)+ $core.bool hasTransferred() => $_has(1);+ @$pb.TagNumber(2)+ void clearTransferred() => $_clearField(2);++ @$pb.TagNumber(3)+ $fixnum.Int64 get total => $_getI64(2);+ @$pb.TagNumber(3)+ set total($fixnum.Int64 value) => $_setInt64(2, value);+ @$pb.TagNumber(3)+ $core.bool hasTotal() => $_has(2);+ @$pb.TagNumber(3)+ void clearTotal() => $_clearField(3);++ @$pb.TagNumber(4)+ $core.double get bytesPerSecond => $_getN(3);+ @$pb.TagNumber(4)+ set bytesPerSecond($core.double value) => $_setDouble(3, value);+ @$pb.TagNumber(4)+ $core.bool hasBytesPerSecond() => $_has(3);+ @$pb.TagNumber(4)+ void clearBytesPerSecond() => $_clearField(4);+}++class Device extends $pb.GeneratedMessage {+ factory Device({+ $core.String? id,+ $core.String? name,+ $core.String? platform,+ $core.bool? online,+ ConnectionKind? connection,+ $core.String? publicKeyFingerprint,+ $fixnum.Int64? pairedAtUnix,+ $core.String? pairingSession,+ }) {+ final result = Device._();+ if (id != null) result.id = id;+ if (name != null) result.name = name;+ if (platform != null) result.platform = platform;+ if (online != null) result.online = online;+ if (connection != null) result.connection = connection;+ if (publicKeyFingerprint != null)+ result.publicKeyFingerprint = publicKeyFingerprint;+ if (pairedAtUnix != null) result.pairedAtUnix = pairedAtUnix;+ if (pairingSession != null) result.pairingSession = pairingSession;+ return result;+ }++ Device._();++ factory Device.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ Device()..mergeFromBuffer(data, registry);+ factory Device.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ Device()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'Device',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: Device.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'id')+ ..aOS(2, _omitFieldNames ? '' : 'name')+ ..aOS(3, _omitFieldNames ? '' : 'platform')+ ..aOB(4, _omitFieldNames ? '' : 'online')+ ..aE<ConnectionKind>(5, _omitFieldNames ? '' : 'connection',+ enumValues: ConnectionKind.values)+ ..aOS(6, _omitFieldNames ? '' : 'publicKeyFingerprint')+ ..aInt64(7, _omitFieldNames ? '' : 'pairedAtUnix')+ ..aOS(8, _omitFieldNames ? '' : 'pairingSession')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ Device clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ Device copyWith(void Function(Device) updates) =>+ super.copyWith((message) => updates(message as Device)) as Device;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use Device() / Device.new instead')+ static Device create() => Device._();+ static $pb.GeneratedMessage $_createMessage() => Device._();+ @$core.override+ Device createEmptyInstance() => Device._();+ @$core.pragma('dart2js:noInline')+ static Device getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<Device>(Device.$_createMessage);+ static Device? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get id => $_getSZ(0);+ @$pb.TagNumber(1)+ set id($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasId() => $_has(0);+ @$pb.TagNumber(1)+ void clearId() => $_clearField(1);++ @$pb.TagNumber(2)+ $core.String get name => $_getSZ(1);+ @$pb.TagNumber(2)+ set name($core.String value) => $_setString(1, value);+ @$pb.TagNumber(2)+ $core.bool hasName() => $_has(1);+ @$pb.TagNumber(2)+ void clearName() => $_clearField(2);++ @$pb.TagNumber(3)+ $core.String get platform => $_getSZ(2);+ @$pb.TagNumber(3)+ set platform($core.String value) => $_setString(2, value);+ @$pb.TagNumber(3)+ $core.bool hasPlatform() => $_has(2);+ @$pb.TagNumber(3)+ void clearPlatform() => $_clearField(3);++ @$pb.TagNumber(4)+ $core.bool get online => $_getBF(3);+ @$pb.TagNumber(4)+ set online($core.bool value) => $_setBool(3, value);+ @$pb.TagNumber(4)+ $core.bool hasOnline() => $_has(3);+ @$pb.TagNumber(4)+ void clearOnline() => $_clearField(4);++ @$pb.TagNumber(5)+ ConnectionKind get connection => $_getN(4);+ @$pb.TagNumber(5)+ set connection(ConnectionKind value) => $_setField(5, value);+ @$pb.TagNumber(5)+ $core.bool hasConnection() => $_has(4);+ @$pb.TagNumber(5)+ void clearConnection() => $_clearField(5);++ @$pb.TagNumber(6)+ $core.String get publicKeyFingerprint => $_getSZ(5);+ @$pb.TagNumber(6)+ set publicKeyFingerprint($core.String value) => $_setString(5, value);+ @$pb.TagNumber(6)+ $core.bool hasPublicKeyFingerprint() => $_has(5);+ @$pb.TagNumber(6)+ void clearPublicKeyFingerprint() => $_clearField(6);++ @$pb.TagNumber(7)+ $fixnum.Int64 get pairedAtUnix => $_getI64(6);+ @$pb.TagNumber(7)+ set pairedAtUnix($fixnum.Int64 value) => $_setInt64(6, value);+ @$pb.TagNumber(7)+ $core.bool hasPairedAtUnix() => $_has(6);+ @$pb.TagNumber(7)+ void clearPairedAtUnix() => $_clearField(7);++ /// 非空表示这是一条**待用户核对指纹**的配对请求,而非已配对设备。+ /// 用此值调 ConfirmPairing 完成或拒绝配对。+ /// 配对码的发起方是被动收到兑换通知的,靠这个字段把确认入口推给界面。+ @$pb.TagNumber(8)+ $core.String get pairingSession => $_getSZ(7);+ @$pb.TagNumber(8)+ set pairingSession($core.String value) => $_setString(7, value);+ @$pb.TagNumber(8)+ $core.bool hasPairingSession() => $_has(7);+ @$pb.TagNumber(8)+ void clearPairingSession() => $_clearField(8);+}++enum Event_Payload {+ clipAdded,+ clipUpdated,+ clipRemoved,+ progress,+ deviceChanged,+ permissionChanged,+ statusChanged,+ notSet+}++class Event extends $pb.GeneratedMessage {+ factory Event({+ ClipRecord? clipAdded,+ ClipRecord? clipUpdated,+ $core.String? clipRemoved,+ TransferProgress? progress,+ Device? deviceChanged,+ ClipboardPermission? permissionChanged,+ Status? statusChanged,+ }) {+ final result = Event._();+ if (clipAdded != null) result.clipAdded = clipAdded;+ if (clipUpdated != null) result.clipUpdated = clipUpdated;+ if (clipRemoved != null) result.clipRemoved = clipRemoved;+ if (progress != null) result.progress = progress;+ if (deviceChanged != null) result.deviceChanged = deviceChanged;+ if (permissionChanged != null) result.permissionChanged = permissionChanged;+ if (statusChanged != null) result.statusChanged = statusChanged;+ return result;+ }++ Event._();++ factory Event.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ Event()..mergeFromBuffer(data, registry);+ factory Event.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ Event()..mergeFromJson(json, registry);++ static const $core.Map<$core.int, Event_Payload> _Event_PayloadByTag = {+ 1: Event_Payload.clipAdded,+ 2: Event_Payload.clipUpdated,+ 3: Event_Payload.clipRemoved,+ 4: Event_Payload.progress,+ 5: Event_Payload.deviceChanged,+ 6: Event_Payload.permissionChanged,+ 7: Event_Payload.statusChanged,+ 0: Event_Payload.notSet+ };+ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'Event',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: Event.$_createMessage)+ ..oo(0, [1, 2, 3, 4, 5, 6, 7])+ ..aOM<ClipRecord>(1, _omitFieldNames ? '' : 'clipAdded',+ subBuilder: ClipRecord.$_createMessage)+ ..aOM<ClipRecord>(2, _omitFieldNames ? '' : 'clipUpdated',+ subBuilder: ClipRecord.$_createMessage)+ ..aOS(3, _omitFieldNames ? '' : 'clipRemoved')+ ..aOM<TransferProgress>(4, _omitFieldNames ? '' : 'progress',+ subBuilder: TransferProgress.$_createMessage)+ ..aOM<Device>(5, _omitFieldNames ? '' : 'deviceChanged',+ subBuilder: Device.$_createMessage)+ ..aE<ClipboardPermission>(6, _omitFieldNames ? '' : 'permissionChanged',+ enumValues: ClipboardPermission.values)+ ..aOM<Status>(7, _omitFieldNames ? '' : 'statusChanged',+ subBuilder: Status.$_createMessage)+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ Event clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ Event copyWith(void Function(Event) updates) =>+ super.copyWith((message) => updates(message as Event)) as Event;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use Event() / Event.new instead')+ static Event create() => Event._();+ static $pb.GeneratedMessage $_createMessage() => Event._();+ @$core.override+ Event createEmptyInstance() => Event._();+ @$core.pragma('dart2js:noInline')+ static Event getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<Event>(Event.$_createMessage);+ static Event? _defaultInstance;++ @$pb.TagNumber(1)+ @$pb.TagNumber(2)+ @$pb.TagNumber(3)+ @$pb.TagNumber(4)+ @$pb.TagNumber(5)+ @$pb.TagNumber(6)+ @$pb.TagNumber(7)+ Event_Payload whichPayload() => _Event_PayloadByTag[$_whichOneof(0)]!;+ @$pb.TagNumber(1)+ @$pb.TagNumber(2)+ @$pb.TagNumber(3)+ @$pb.TagNumber(4)+ @$pb.TagNumber(5)+ @$pb.TagNumber(6)+ @$pb.TagNumber(7)+ void clearPayload() => $_clearField($_whichOneof(0));++ @$pb.TagNumber(1)+ ClipRecord get clipAdded => $_getN(0);+ @$pb.TagNumber(1)+ set clipAdded(ClipRecord value) => $_setField(1, value);+ @$pb.TagNumber(1)+ $core.bool hasClipAdded() => $_has(0);+ @$pb.TagNumber(1)+ void clearClipAdded() => $_clearField(1);+ @$pb.TagNumber(1)+ ClipRecord ensureClipAdded() => $_ensure(0);++ @$pb.TagNumber(2)+ ClipRecord get clipUpdated => $_getN(1);+ @$pb.TagNumber(2)+ set clipUpdated(ClipRecord value) => $_setField(2, value);+ @$pb.TagNumber(2)+ $core.bool hasClipUpdated() => $_has(1);+ @$pb.TagNumber(2)+ void clearClipUpdated() => $_clearField(2);+ @$pb.TagNumber(2)+ ClipRecord ensureClipUpdated() => $_ensure(1);++ @$pb.TagNumber(3)+ $core.String get clipRemoved => $_getSZ(2);+ @$pb.TagNumber(3)+ set clipRemoved($core.String value) => $_setString(2, value);+ @$pb.TagNumber(3)+ $core.bool hasClipRemoved() => $_has(2);+ @$pb.TagNumber(3)+ void clearClipRemoved() => $_clearField(3);++ @$pb.TagNumber(4)+ TransferProgress get progress => $_getN(3);+ @$pb.TagNumber(4)+ set progress(TransferProgress value) => $_setField(4, value);+ @$pb.TagNumber(4)+ $core.bool hasProgress() => $_has(3);+ @$pb.TagNumber(4)+ void clearProgress() => $_clearField(4);+ @$pb.TagNumber(4)+ TransferProgress ensureProgress() => $_ensure(3);++ @$pb.TagNumber(5)+ Device get deviceChanged => $_getN(4);+ @$pb.TagNumber(5)+ set deviceChanged(Device value) => $_setField(5, value);+ @$pb.TagNumber(5)+ $core.bool hasDeviceChanged() => $_has(4);+ @$pb.TagNumber(5)+ void clearDeviceChanged() => $_clearField(5);+ @$pb.TagNumber(5)+ Device ensureDeviceChanged() => $_ensure(4);++ @$pb.TagNumber(6)+ ClipboardPermission get permissionChanged => $_getN(5);+ @$pb.TagNumber(6)+ set permissionChanged(ClipboardPermission value) => $_setField(6, value);+ @$pb.TagNumber(6)+ $core.bool hasPermissionChanged() => $_has(5);+ @$pb.TagNumber(6)+ void clearPermissionChanged() => $_clearField(6);++ @$pb.TagNumber(7)+ Status get statusChanged => $_getN(6);+ @$pb.TagNumber(7)+ set statusChanged(Status value) => $_setField(7, value);+ @$pb.TagNumber(7)+ $core.bool hasStatusChanged() => $_has(6);+ @$pb.TagNumber(7)+ void clearStatusChanged() => $_clearField(7);+ @$pb.TagNumber(7)+ Status ensureStatusChanged() => $_ensure(6);+}++class ListHistoryRequest extends $pb.GeneratedMessage {+ factory ListHistoryRequest({+ $core.int? limit,+ $fixnum.Int64? beforeUnix,+ ClipKind? kindFilter,+ }) {+ final result = ListHistoryRequest._();+ if (limit != null) result.limit = limit;+ if (beforeUnix != null) result.beforeUnix = beforeUnix;+ if (kindFilter != null) result.kindFilter = kindFilter;+ return result;+ }++ ListHistoryRequest._();++ factory ListHistoryRequest.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ListHistoryRequest()..mergeFromBuffer(data, registry);+ factory ListHistoryRequest.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ListHistoryRequest()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'ListHistoryRequest',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: ListHistoryRequest.$_createMessage)+ ..aI(1, _omitFieldNames ? '' : 'limit')+ ..aInt64(2, _omitFieldNames ? '' : 'beforeUnix')+ ..aE<ClipKind>(3, _omitFieldNames ? '' : 'kindFilter',+ enumValues: ClipKind.values)+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ListHistoryRequest clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ListHistoryRequest copyWith(void Function(ListHistoryRequest) updates) =>+ super.copyWith((message) => updates(message as ListHistoryRequest))+ as ListHistoryRequest;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use ListHistoryRequest() / ListHistoryRequest.new instead')+ static ListHistoryRequest create() => ListHistoryRequest._();+ static $pb.GeneratedMessage $_createMessage() => ListHistoryRequest._();+ @$core.override+ ListHistoryRequest createEmptyInstance() => ListHistoryRequest._();+ @$core.pragma('dart2js:noInline')+ static ListHistoryRequest getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<ListHistoryRequest>(+ ListHistoryRequest.$_createMessage);+ static ListHistoryRequest? _defaultInstance;++ @$pb.TagNumber(1)+ $core.int get limit => $_getIZ(0);+ @$pb.TagNumber(1)+ set limit($core.int value) => $_setSignedInt32(0, value);+ @$pb.TagNumber(1)+ $core.bool hasLimit() => $_has(0);+ @$pb.TagNumber(1)+ void clearLimit() => $_clearField(1);++ @$pb.TagNumber(2)+ $fixnum.Int64 get beforeUnix => $_getI64(1);+ @$pb.TagNumber(2)+ set beforeUnix($fixnum.Int64 value) => $_setInt64(1, value);+ @$pb.TagNumber(2)+ $core.bool hasBeforeUnix() => $_has(1);+ @$pb.TagNumber(2)+ void clearBeforeUnix() => $_clearField(2);++ @$pb.TagNumber(3)+ ClipKind get kindFilter => $_getN(2);+ @$pb.TagNumber(3)+ set kindFilter(ClipKind value) => $_setField(3, value);+ @$pb.TagNumber(3)+ $core.bool hasKindFilter() => $_has(2);+ @$pb.TagNumber(3)+ void clearKindFilter() => $_clearField(3);+}++class ListHistoryResponse extends $pb.GeneratedMessage {+ factory ListHistoryResponse({+ $core.Iterable<ClipRecord>? records,+ }) {+ final result = ListHistoryResponse._();+ if (records != null) result.records.addAll(records);+ return result;+ }++ ListHistoryResponse._();++ factory ListHistoryResponse.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ListHistoryResponse()..mergeFromBuffer(data, registry);+ factory ListHistoryResponse.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ListHistoryResponse()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'ListHistoryResponse',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: ListHistoryResponse.$_createMessage)+ ..pPM<ClipRecord>(1, _omitFieldNames ? '' : 'records',+ subBuilder: ClipRecord.$_createMessage)+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ListHistoryResponse clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ListHistoryResponse copyWith(void Function(ListHistoryResponse) updates) =>+ super.copyWith((message) => updates(message as ListHistoryResponse))+ as ListHistoryResponse;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core+ .Deprecated('Use ListHistoryResponse() / ListHistoryResponse.new instead')+ static ListHistoryResponse create() => ListHistoryResponse._();+ static $pb.GeneratedMessage $_createMessage() => ListHistoryResponse._();+ @$core.override+ ListHistoryResponse createEmptyInstance() => ListHistoryResponse._();+ @$core.pragma('dart2js:noInline')+ static ListHistoryResponse getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<ListHistoryResponse>(+ ListHistoryResponse.$_createMessage);+ static ListHistoryResponse? _defaultInstance;++ @$pb.TagNumber(1)+ $pb.PbList<ClipRecord> get records => $_getList(0);+}++class DeleteHistoryRequest extends $pb.GeneratedMessage {+ factory DeleteHistoryRequest({+ $core.Iterable<$core.String>? ids,+ $core.bool? all,+ }) {+ final result = DeleteHistoryRequest._();+ if (ids != null) result.ids.addAll(ids);+ if (all != null) result.all = all;+ return result;+ }++ DeleteHistoryRequest._();++ factory DeleteHistoryRequest.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ DeleteHistoryRequest()..mergeFromBuffer(data, registry);+ factory DeleteHistoryRequest.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ DeleteHistoryRequest()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'DeleteHistoryRequest',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: DeleteHistoryRequest.$_createMessage)+ ..pPS(1, _omitFieldNames ? '' : 'ids')+ ..aOB(2, _omitFieldNames ? '' : 'all')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ DeleteHistoryRequest clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ DeleteHistoryRequest copyWith(void Function(DeleteHistoryRequest) updates) =>+ super.copyWith((message) => updates(message as DeleteHistoryRequest))+ as DeleteHistoryRequest;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated(+ 'Use DeleteHistoryRequest() / DeleteHistoryRequest.new instead')+ static DeleteHistoryRequest create() => DeleteHistoryRequest._();+ static $pb.GeneratedMessage $_createMessage() => DeleteHistoryRequest._();+ @$core.override+ DeleteHistoryRequest createEmptyInstance() => DeleteHistoryRequest._();+ @$core.pragma('dart2js:noInline')+ static DeleteHistoryRequest getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<DeleteHistoryRequest>(+ DeleteHistoryRequest.$_createMessage);+ static DeleteHistoryRequest? _defaultInstance;++ @$pb.TagNumber(1)+ $pb.PbList<$core.String> get ids => $_getList(0);++ @$pb.TagNumber(2)+ $core.bool get all => $_getBF(1);+ @$pb.TagNumber(2)+ set all($core.bool value) => $_setBool(1, value);+ @$pb.TagNumber(2)+ $core.bool hasAll() => $_has(1);+ @$pb.TagNumber(2)+ void clearAll() => $_clearField(2);+}++class FetchRequest extends $pb.GeneratedMessage {+ factory FetchRequest({+ $core.String? clipId,+ }) {+ final result = FetchRequest._();+ if (clipId != null) result.clipId = clipId;+ return result;+ }++ FetchRequest._();++ factory FetchRequest.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ FetchRequest()..mergeFromBuffer(data, registry);+ factory FetchRequest.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ FetchRequest()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'FetchRequest',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: FetchRequest.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'clipId')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ FetchRequest clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ FetchRequest copyWith(void Function(FetchRequest) updates) =>+ super.copyWith((message) => updates(message as FetchRequest))+ as FetchRequest;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use FetchRequest() / FetchRequest.new instead')+ static FetchRequest create() => FetchRequest._();+ static $pb.GeneratedMessage $_createMessage() => FetchRequest._();+ @$core.override+ FetchRequest createEmptyInstance() => FetchRequest._();+ @$core.pragma('dart2js:noInline')+ static FetchRequest getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<FetchRequest>(+ FetchRequest.$_createMessage);+ static FetchRequest? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get clipId => $_getSZ(0);+ @$pb.TagNumber(1)+ set clipId($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasClipId() => $_has(0);+ @$pb.TagNumber(1)+ void clearClipId() => $_clearField(1);+}++class ApplyToClipboardRequest extends $pb.GeneratedMessage {+ factory ApplyToClipboardRequest({+ $core.String? clipId,+ }) {+ final result = ApplyToClipboardRequest._();+ if (clipId != null) result.clipId = clipId;+ return result;+ }++ ApplyToClipboardRequest._();++ factory ApplyToClipboardRequest.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ApplyToClipboardRequest()..mergeFromBuffer(data, registry);+ factory ApplyToClipboardRequest.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ApplyToClipboardRequest()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'ApplyToClipboardRequest',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: ApplyToClipboardRequest.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'clipId')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ApplyToClipboardRequest clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ApplyToClipboardRequest copyWith(+ void Function(ApplyToClipboardRequest) updates) =>+ super.copyWith((message) => updates(message as ApplyToClipboardRequest))+ as ApplyToClipboardRequest;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated(+ 'Use ApplyToClipboardRequest() / ApplyToClipboardRequest.new instead')+ static ApplyToClipboardRequest create() => ApplyToClipboardRequest._();+ static $pb.GeneratedMessage $_createMessage() => ApplyToClipboardRequest._();+ @$core.override+ ApplyToClipboardRequest createEmptyInstance() => ApplyToClipboardRequest._();+ @$core.pragma('dart2js:noInline')+ static ApplyToClipboardRequest getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<ApplyToClipboardRequest>(+ ApplyToClipboardRequest.$_createMessage);+ static ApplyToClipboardRequest? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get clipId => $_getSZ(0);+ @$pb.TagNumber(1)+ set clipId($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasClipId() => $_has(0);+ @$pb.TagNumber(1)+ void clearClipId() => $_clearField(1);+}++class ListDevicesResponse extends $pb.GeneratedMessage {+ factory ListDevicesResponse({+ Device? self,+ $core.Iterable<Device>? peers,+ }) {+ final result = ListDevicesResponse._();+ if (self != null) result.self = self;+ if (peers != null) result.peers.addAll(peers);+ return result;+ }++ ListDevicesResponse._();++ factory ListDevicesResponse.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ListDevicesResponse()..mergeFromBuffer(data, registry);+ factory ListDevicesResponse.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ListDevicesResponse()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'ListDevicesResponse',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: ListDevicesResponse.$_createMessage)+ ..aOM<Device>(1, _omitFieldNames ? '' : 'self',+ subBuilder: Device.$_createMessage)+ ..pPM<Device>(2, _omitFieldNames ? '' : 'peers',+ subBuilder: Device.$_createMessage)+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ListDevicesResponse clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ListDevicesResponse copyWith(void Function(ListDevicesResponse) updates) =>+ super.copyWith((message) => updates(message as ListDevicesResponse))+ as ListDevicesResponse;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core+ .Deprecated('Use ListDevicesResponse() / ListDevicesResponse.new instead')+ static ListDevicesResponse create() => ListDevicesResponse._();+ static $pb.GeneratedMessage $_createMessage() => ListDevicesResponse._();+ @$core.override+ ListDevicesResponse createEmptyInstance() => ListDevicesResponse._();+ @$core.pragma('dart2js:noInline')+ static ListDevicesResponse getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<ListDevicesResponse>(+ ListDevicesResponse.$_createMessage);+ static ListDevicesResponse? _defaultInstance;++ @$pb.TagNumber(1)+ Device get self => $_getN(0);+ @$pb.TagNumber(1)+ set self(Device value) => $_setField(1, value);+ @$pb.TagNumber(1)+ $core.bool hasSelf() => $_has(0);+ @$pb.TagNumber(1)+ void clearSelf() => $_clearField(1);+ @$pb.TagNumber(1)+ Device ensureSelf() => $_ensure(0);++ @$pb.TagNumber(2)+ $pb.PbList<Device> get peers => $_getList(1);+}++class CreatePairingCodeResponse extends $pb.GeneratedMessage {+ factory CreatePairingCodeResponse({+ $core.String? code,+ $fixnum.Int64? expiresAtUnix,+ }) {+ final result = CreatePairingCodeResponse._();+ if (code != null) result.code = code;+ if (expiresAtUnix != null) result.expiresAtUnix = expiresAtUnix;+ return result;+ }++ CreatePairingCodeResponse._();++ factory CreatePairingCodeResponse.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ CreatePairingCodeResponse()..mergeFromBuffer(data, registry);+ factory CreatePairingCodeResponse.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ CreatePairingCodeResponse()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'CreatePairingCodeResponse',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: CreatePairingCodeResponse.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'code')+ ..aInt64(2, _omitFieldNames ? '' : 'expiresAtUnix')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ CreatePairingCodeResponse clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ CreatePairingCodeResponse copyWith(+ void Function(CreatePairingCodeResponse) updates) =>+ super.copyWith((message) => updates(message as CreatePairingCodeResponse))+ as CreatePairingCodeResponse;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated(+ 'Use CreatePairingCodeResponse() / CreatePairingCodeResponse.new instead')+ static CreatePairingCodeResponse create() => CreatePairingCodeResponse._();+ static $pb.GeneratedMessage $_createMessage() =>+ CreatePairingCodeResponse._();+ @$core.override+ CreatePairingCodeResponse createEmptyInstance() =>+ CreatePairingCodeResponse._();+ @$core.pragma('dart2js:noInline')+ static CreatePairingCodeResponse getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<CreatePairingCodeResponse>(+ CreatePairingCodeResponse.$_createMessage);+ static CreatePairingCodeResponse? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get code => $_getSZ(0);+ @$pb.TagNumber(1)+ set code($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasCode() => $_has(0);+ @$pb.TagNumber(1)+ void clearCode() => $_clearField(1);++ @$pb.TagNumber(2)+ $fixnum.Int64 get expiresAtUnix => $_getI64(1);+ @$pb.TagNumber(2)+ set expiresAtUnix($fixnum.Int64 value) => $_setInt64(1, value);+ @$pb.TagNumber(2)+ $core.bool hasExpiresAtUnix() => $_has(1);+ @$pb.TagNumber(2)+ void clearExpiresAtUnix() => $_clearField(2);+}++class RedeemPairingCodeRequest extends $pb.GeneratedMessage {+ factory RedeemPairingCodeRequest({+ $core.String? code,+ }) {+ final result = RedeemPairingCodeRequest._();+ if (code != null) result.code = code;+ return result;+ }++ RedeemPairingCodeRequest._();++ factory RedeemPairingCodeRequest.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ RedeemPairingCodeRequest()..mergeFromBuffer(data, registry);+ factory RedeemPairingCodeRequest.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ RedeemPairingCodeRequest()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'RedeemPairingCodeRequest',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: RedeemPairingCodeRequest.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'code')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ RedeemPairingCodeRequest clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ RedeemPairingCodeRequest copyWith(+ void Function(RedeemPairingCodeRequest) updates) =>+ super.copyWith((message) => updates(message as RedeemPairingCodeRequest))+ as RedeemPairingCodeRequest;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated(+ 'Use RedeemPairingCodeRequest() / RedeemPairingCodeRequest.new instead')+ static RedeemPairingCodeRequest create() => RedeemPairingCodeRequest._();+ static $pb.GeneratedMessage $_createMessage() => RedeemPairingCodeRequest._();+ @$core.override+ RedeemPairingCodeRequest createEmptyInstance() =>+ RedeemPairingCodeRequest._();+ @$core.pragma('dart2js:noInline')+ static RedeemPairingCodeRequest getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<RedeemPairingCodeRequest>(+ RedeemPairingCodeRequest.$_createMessage);+ static RedeemPairingCodeRequest? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get code => $_getSZ(0);+ @$pb.TagNumber(1)+ set code($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasCode() => $_has(0);+ @$pb.TagNumber(1)+ void clearCode() => $_clearField(1);+}++class RedeemPairingCodeResponse extends $pb.GeneratedMessage {+ factory RedeemPairingCodeResponse({+ Device? peer,+ $core.String? pairingSession,+ }) {+ final result = RedeemPairingCodeResponse._();+ if (peer != null) result.peer = peer;+ if (pairingSession != null) result.pairingSession = pairingSession;+ return result;+ }++ RedeemPairingCodeResponse._();++ factory RedeemPairingCodeResponse.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ RedeemPairingCodeResponse()..mergeFromBuffer(data, registry);+ factory RedeemPairingCodeResponse.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ RedeemPairingCodeResponse()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'RedeemPairingCodeResponse',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: RedeemPairingCodeResponse.$_createMessage)+ ..aOM<Device>(1, _omitFieldNames ? '' : 'peer',+ subBuilder: Device.$_createMessage)+ ..aOS(2, _omitFieldNames ? '' : 'pairingSession')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ RedeemPairingCodeResponse clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ RedeemPairingCodeResponse copyWith(+ void Function(RedeemPairingCodeResponse) updates) =>+ super.copyWith((message) => updates(message as RedeemPairingCodeResponse))+ as RedeemPairingCodeResponse;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated(+ 'Use RedeemPairingCodeResponse() / RedeemPairingCodeResponse.new instead')+ static RedeemPairingCodeResponse create() => RedeemPairingCodeResponse._();+ static $pb.GeneratedMessage $_createMessage() =>+ RedeemPairingCodeResponse._();+ @$core.override+ RedeemPairingCodeResponse createEmptyInstance() =>+ RedeemPairingCodeResponse._();+ @$core.pragma('dart2js:noInline')+ static RedeemPairingCodeResponse getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<RedeemPairingCodeResponse>(+ RedeemPairingCodeResponse.$_createMessage);+ static RedeemPairingCodeResponse? _defaultInstance;++ /// 返回对端信息供用户肉眼核对指纹,确认后再调 ConfirmPairing+ @$pb.TagNumber(1)+ Device get peer => $_getN(0);+ @$pb.TagNumber(1)+ set peer(Device value) => $_setField(1, value);+ @$pb.TagNumber(1)+ $core.bool hasPeer() => $_has(0);+ @$pb.TagNumber(1)+ void clearPeer() => $_clearField(1);+ @$pb.TagNumber(1)+ Device ensurePeer() => $_ensure(0);++ @$pb.TagNumber(2)+ $core.String get pairingSession => $_getSZ(1);+ @$pb.TagNumber(2)+ set pairingSession($core.String value) => $_setString(1, value);+ @$pb.TagNumber(2)+ $core.bool hasPairingSession() => $_has(1);+ @$pb.TagNumber(2)+ void clearPairingSession() => $_clearField(2);+}++class ConfirmPairingRequest extends $pb.GeneratedMessage {+ factory ConfirmPairingRequest({+ $core.String? pairingSession,+ $core.bool? accept,+ }) {+ final result = ConfirmPairingRequest._();+ if (pairingSession != null) result.pairingSession = pairingSession;+ if (accept != null) result.accept = accept;+ return result;+ }++ ConfirmPairingRequest._();++ factory ConfirmPairingRequest.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ConfirmPairingRequest()..mergeFromBuffer(data, registry);+ factory ConfirmPairingRequest.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ConfirmPairingRequest()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'ConfirmPairingRequest',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: ConfirmPairingRequest.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'pairingSession')+ ..aOB(2, _omitFieldNames ? '' : 'accept')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ConfirmPairingRequest clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ConfirmPairingRequest copyWith(+ void Function(ConfirmPairingRequest) updates) =>+ super.copyWith((message) => updates(message as ConfirmPairingRequest))+ as ConfirmPairingRequest;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated(+ 'Use ConfirmPairingRequest() / ConfirmPairingRequest.new instead')+ static ConfirmPairingRequest create() => ConfirmPairingRequest._();+ static $pb.GeneratedMessage $_createMessage() => ConfirmPairingRequest._();+ @$core.override+ ConfirmPairingRequest createEmptyInstance() => ConfirmPairingRequest._();+ @$core.pragma('dart2js:noInline')+ static ConfirmPairingRequest getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<ConfirmPairingRequest>(+ ConfirmPairingRequest.$_createMessage);+ static ConfirmPairingRequest? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get pairingSession => $_getSZ(0);+ @$pb.TagNumber(1)+ set pairingSession($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasPairingSession() => $_has(0);+ @$pb.TagNumber(1)+ void clearPairingSession() => $_clearField(1);++ @$pb.TagNumber(2)+ $core.bool get accept => $_getBF(1);+ @$pb.TagNumber(2)+ set accept($core.bool value) => $_setBool(1, value);+ @$pb.TagNumber(2)+ $core.bool hasAccept() => $_has(1);+ @$pb.TagNumber(2)+ void clearAccept() => $_clearField(2);+}++class UnpairRequest extends $pb.GeneratedMessage {+ factory UnpairRequest({+ $core.String? deviceId,+ }) {+ final result = UnpairRequest._();+ if (deviceId != null) result.deviceId = deviceId;+ return result;+ }++ UnpairRequest._();++ factory UnpairRequest.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ UnpairRequest()..mergeFromBuffer(data, registry);+ factory UnpairRequest.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ UnpairRequest()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'UnpairRequest',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: UnpairRequest.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'deviceId')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ UnpairRequest clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ UnpairRequest copyWith(void Function(UnpairRequest) updates) =>+ super.copyWith((message) => updates(message as UnpairRequest))+ as UnpairRequest;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use UnpairRequest() / UnpairRequest.new instead')+ static UnpairRequest create() => UnpairRequest._();+ static $pb.GeneratedMessage $_createMessage() => UnpairRequest._();+ @$core.override+ UnpairRequest createEmptyInstance() => UnpairRequest._();+ @$core.pragma('dart2js:noInline')+ static UnpairRequest getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<UnpairRequest>(+ UnpairRequest.$_createMessage);+ static UnpairRequest? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get deviceId => $_getSZ(0);+ @$pb.TagNumber(1)+ set deviceId($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasDeviceId() => $_has(0);+ @$pb.TagNumber(1)+ void clearDeviceId() => $_clearField(1);+}++class Config extends $pb.GeneratedMessage {+ factory Config({+ $fixnum.Int64? autoSyncThresholdBytes,+ $fixnum.Int64? historyTtlSeconds,+ $fixnum.Int64? cacheTtlSeconds,+ $core.bool? syncText,+ $core.bool? syncHtml,+ $core.bool? syncImage,+ $core.bool? syncFile,+ $core.bool? autoApplyToClipboard,+ $core.bool? launchAtLogin,+ $core.String? deviceName,+ $core.String? signalingUrl,+ }) {+ final result = Config._();+ if (autoSyncThresholdBytes != null)+ result.autoSyncThresholdBytes = autoSyncThresholdBytes;+ if (historyTtlSeconds != null) result.historyTtlSeconds = historyTtlSeconds;+ if (cacheTtlSeconds != null) result.cacheTtlSeconds = cacheTtlSeconds;+ if (syncText != null) result.syncText = syncText;+ if (syncHtml != null) result.syncHtml = syncHtml;+ if (syncImage != null) result.syncImage = syncImage;+ if (syncFile != null) result.syncFile = syncFile;+ if (autoApplyToClipboard != null)+ result.autoApplyToClipboard = autoApplyToClipboard;+ if (launchAtLogin != null) result.launchAtLogin = launchAtLogin;+ if (deviceName != null) result.deviceName = deviceName;+ if (signalingUrl != null) result.signalingUrl = signalingUrl;+ return result;+ }++ Config._();++ factory Config.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ Config()..mergeFromBuffer(data, registry);+ factory Config.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ Config()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'Config',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: Config.$_createMessage)+ ..aInt64(1, _omitFieldNames ? '' : 'autoSyncThresholdBytes')+ ..aInt64(2, _omitFieldNames ? '' : 'historyTtlSeconds')+ ..aInt64(3, _omitFieldNames ? '' : 'cacheTtlSeconds')+ ..aOB(4, _omitFieldNames ? '' : 'syncText')+ ..aOB(5, _omitFieldNames ? '' : 'syncHtml')+ ..aOB(6, _omitFieldNames ? '' : 'syncImage')+ ..aOB(7, _omitFieldNames ? '' : 'syncFile')+ ..aOB(8, _omitFieldNames ? '' : 'autoApplyToClipboard')+ ..aOB(9, _omitFieldNames ? '' : 'launchAtLogin')+ ..aOS(10, _omitFieldNames ? '' : 'deviceName')+ ..aOS(11, _omitFieldNames ? '' : 'signalingUrl')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ Config clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ Config copyWith(void Function(Config) updates) =>+ super.copyWith((message) => updates(message as Config)) as Config;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use Config() / Config.new instead')+ static Config create() => Config._();+ static $pb.GeneratedMessage $_createMessage() => Config._();+ @$core.override+ Config createEmptyInstance() => Config._();+ @$core.pragma('dart2js:noInline')+ static Config getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<Config>(Config.$_createMessage);+ static Config? _defaultInstance;++ /// 小于此值自动预取,大于此值只同步元数据等用户手动拉取+ @$pb.TagNumber(1)+ $fixnum.Int64 get autoSyncThresholdBytes => $_getI64(0);+ @$pb.TagNumber(1)+ set autoSyncThresholdBytes($fixnum.Int64 value) => $_setInt64(0, value);+ @$pb.TagNumber(1)+ $core.bool hasAutoSyncThresholdBytes() => $_has(0);+ @$pb.TagNumber(1)+ void clearAutoSyncThresholdBytes() => $_clearField(1);++ @$pb.TagNumber(2)+ $fixnum.Int64 get historyTtlSeconds => $_getI64(1);+ @$pb.TagNumber(2)+ set historyTtlSeconds($fixnum.Int64 value) => $_setInt64(1, value);+ @$pb.TagNumber(2)+ $core.bool hasHistoryTtlSeconds() => $_has(1);+ @$pb.TagNumber(2)+ void clearHistoryTtlSeconds() => $_clearField(2);++ @$pb.TagNumber(3)+ $fixnum.Int64 get cacheTtlSeconds => $_getI64(2);+ @$pb.TagNumber(3)+ set cacheTtlSeconds($fixnum.Int64 value) => $_setInt64(2, value);+ @$pb.TagNumber(3)+ $core.bool hasCacheTtlSeconds() => $_has(2);+ @$pb.TagNumber(3)+ void clearCacheTtlSeconds() => $_clearField(3);++ @$pb.TagNumber(4)+ $core.bool get syncText => $_getBF(3);+ @$pb.TagNumber(4)+ set syncText($core.bool value) => $_setBool(3, value);+ @$pb.TagNumber(4)+ $core.bool hasSyncText() => $_has(3);+ @$pb.TagNumber(4)+ void clearSyncText() => $_clearField(4);++ @$pb.TagNumber(5)+ $core.bool get syncHtml => $_getBF(4);+ @$pb.TagNumber(5)+ set syncHtml($core.bool value) => $_setBool(4, value);+ @$pb.TagNumber(5)+ $core.bool hasSyncHtml() => $_has(4);+ @$pb.TagNumber(5)+ void clearSyncHtml() => $_clearField(5);++ @$pb.TagNumber(6)+ $core.bool get syncImage => $_getBF(5);+ @$pb.TagNumber(6)+ set syncImage($core.bool value) => $_setBool(5, value);+ @$pb.TagNumber(6)+ $core.bool hasSyncImage() => $_has(5);+ @$pb.TagNumber(6)+ void clearSyncImage() => $_clearField(6);++ @$pb.TagNumber(7)+ $core.bool get syncFile => $_getBF(6);+ @$pb.TagNumber(7)+ set syncFile($core.bool value) => $_setBool(6, value);+ @$pb.TagNumber(7)+ $core.bool hasSyncFile() => $_has(6);+ @$pb.TagNumber(7)+ void clearSyncFile() => $_clearField(7);++ /// 收到对端内容后是否自动覆盖本机剪贴板+ @$pb.TagNumber(8)+ $core.bool get autoApplyToClipboard => $_getBF(7);+ @$pb.TagNumber(8)+ set autoApplyToClipboard($core.bool value) => $_setBool(7, value);+ @$pb.TagNumber(8)+ $core.bool hasAutoApplyToClipboard() => $_has(7);+ @$pb.TagNumber(8)+ void clearAutoApplyToClipboard() => $_clearField(8);++ @$pb.TagNumber(9)+ $core.bool get launchAtLogin => $_getBF(8);+ @$pb.TagNumber(9)+ set launchAtLogin($core.bool value) => $_setBool(8, value);+ @$pb.TagNumber(9)+ $core.bool hasLaunchAtLogin() => $_has(8);+ @$pb.TagNumber(9)+ void clearLaunchAtLogin() => $_clearField(9);++ @$pb.TagNumber(10)+ $core.String get deviceName => $_getSZ(9);+ @$pb.TagNumber(10)+ set deviceName($core.String value) => $_setString(9, value);+ @$pb.TagNumber(10)+ $core.bool hasDeviceName() => $_has(9);+ @$pb.TagNumber(10)+ void clearDeviceName() => $_clearField(10);++ @$pb.TagNumber(11)+ $core.String get signalingUrl => $_getSZ(10);+ @$pb.TagNumber(11)+ set signalingUrl($core.String value) => $_setString(10, value);+ @$pb.TagNumber(11)+ $core.bool hasSignalingUrl() => $_has(10);+ @$pb.TagNumber(11)+ void clearSignalingUrl() => $_clearField(11);+}++class Status extends $pb.GeneratedMessage {+ factory Status({+ $core.String? deviceId,+ $core.String? deviceName,+ $core.bool? signalingConnected,+ ClipboardPermission? clipboardPermission,+ $fixnum.Int64? cacheBytesUsed,+ $core.int? peersOnline,+ $core.String? version,+ }) {+ final result = Status._();+ if (deviceId != null) result.deviceId = deviceId;+ if (deviceName != null) result.deviceName = deviceName;+ if (signalingConnected != null)+ result.signalingConnected = signalingConnected;+ if (clipboardPermission != null)+ result.clipboardPermission = clipboardPermission;+ if (cacheBytesUsed != null) result.cacheBytesUsed = cacheBytesUsed;+ if (peersOnline != null) result.peersOnline = peersOnline;+ if (version != null) result.version = version;+ return result;+ }++ Status._();++ factory Status.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ Status()..mergeFromBuffer(data, registry);+ factory Status.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ Status()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'Status',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: Status.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'deviceId')+ ..aOS(2, _omitFieldNames ? '' : 'deviceName')+ ..aOB(3, _omitFieldNames ? '' : 'signalingConnected')+ ..aE<ClipboardPermission>(4, _omitFieldNames ? '' : 'clipboardPermission',+ enumValues: ClipboardPermission.values)+ ..aInt64(5, _omitFieldNames ? '' : 'cacheBytesUsed')+ ..aI(6, _omitFieldNames ? '' : 'peersOnline')+ ..aOS(7, _omitFieldNames ? '' : 'version')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ Status clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ Status copyWith(void Function(Status) updates) =>+ super.copyWith((message) => updates(message as Status)) as Status;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use Status() / Status.new instead')+ static Status create() => Status._();+ static $pb.GeneratedMessage $_createMessage() => Status._();+ @$core.override+ Status createEmptyInstance() => Status._();+ @$core.pragma('dart2js:noInline')+ static Status getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<Status>(Status.$_createMessage);+ static Status? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get deviceId => $_getSZ(0);+ @$pb.TagNumber(1)+ set deviceId($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasDeviceId() => $_has(0);+ @$pb.TagNumber(1)+ void clearDeviceId() => $_clearField(1);++ @$pb.TagNumber(2)+ $core.String get deviceName => $_getSZ(1);+ @$pb.TagNumber(2)+ set deviceName($core.String value) => $_setString(1, value);+ @$pb.TagNumber(2)+ $core.bool hasDeviceName() => $_has(1);+ @$pb.TagNumber(2)+ void clearDeviceName() => $_clearField(2);++ @$pb.TagNumber(3)+ $core.bool get signalingConnected => $_getBF(2);+ @$pb.TagNumber(3)+ set signalingConnected($core.bool value) => $_setBool(2, value);+ @$pb.TagNumber(3)+ $core.bool hasSignalingConnected() => $_has(2);+ @$pb.TagNumber(3)+ void clearSignalingConnected() => $_clearField(3);++ @$pb.TagNumber(4)+ ClipboardPermission get clipboardPermission => $_getN(3);+ @$pb.TagNumber(4)+ set clipboardPermission(ClipboardPermission value) => $_setField(4, value);+ @$pb.TagNumber(4)+ $core.bool hasClipboardPermission() => $_has(3);+ @$pb.TagNumber(4)+ void clearClipboardPermission() => $_clearField(4);++ @$pb.TagNumber(5)+ $fixnum.Int64 get cacheBytesUsed => $_getI64(4);+ @$pb.TagNumber(5)+ set cacheBytesUsed($fixnum.Int64 value) => $_setInt64(4, value);+ @$pb.TagNumber(5)+ $core.bool hasCacheBytesUsed() => $_has(4);+ @$pb.TagNumber(5)+ void clearCacheBytesUsed() => $_clearField(5);++ @$pb.TagNumber(6)+ $core.int get peersOnline => $_getIZ(5);+ @$pb.TagNumber(6)+ set peersOnline($core.int value) => $_setSignedInt32(5, value);+ @$pb.TagNumber(6)+ $core.bool hasPeersOnline() => $_has(5);+ @$pb.TagNumber(6)+ void clearPeersOnline() => $_clearField(6);++ @$pb.TagNumber(7)+ $core.String get version => $_getSZ(6);+ @$pb.TagNumber(7)+ set version($core.String value) => $_setString(6, value);+ @$pb.TagNumber(7)+ $core.bool hasVersion() => $_has(6);+ @$pb.TagNumber(7)+ void clearVersion() => $_clearField(7);+}++const $core.bool _omitFieldNames =+ $core.bool.fromEnvironment('protobuf.omit_field_names');+const $core.bool _omitMessageNames =+ $core.bool.fromEnvironment('protobuf.omit_message_names');diff --git a/ui/lib/gen/copysync/v1/daemon.pbenum.dart b/ui/lib/gen/copysync/v1/daemon.pbenum.dartnew file mode 100644index 0000000..3f2488e--- /dev/null+++ b/ui/lib/gen/copysync/v1/daemon.pbenum.dart@@ -0,0 +1,141 @@+// This is a generated file - do not edit.+//+// Generated from copysync/v1/daemon.proto.++// @dart = 3.3++// ignore_for_file: annotate_overrides, camel_case_types, comment_references+// ignore_for_file: constant_identifier_names+// ignore_for_file: curly_braces_in_flow_control_structures+// ignore_for_file: deprecated_member_use_from_same_package, library_prefixes+// ignore_for_file: non_constant_identifier_names, prefer_relative_imports++import 'dart:core' as $core;++import 'package:protobuf/protobuf.dart' as $pb;++class ClipKind extends $pb.ProtobufEnum {+ static const ClipKind CLIP_KIND_UNSPECIFIED =+ ClipKind._(0, _omitEnumNames ? '' : 'CLIP_KIND_UNSPECIFIED');+ static const ClipKind CLIP_KIND_TEXT =+ ClipKind._(1, _omitEnumNames ? '' : 'CLIP_KIND_TEXT');+ static const ClipKind CLIP_KIND_HTML =+ ClipKind._(2, _omitEnumNames ? '' : 'CLIP_KIND_HTML');+ static const ClipKind CLIP_KIND_IMAGE =+ ClipKind._(3, _omitEnumNames ? '' : 'CLIP_KIND_IMAGE');+ static const ClipKind CLIP_KIND_FILE =+ ClipKind._(4, _omitEnumNames ? '' : 'CLIP_KIND_FILE');++ static const $core.List<ClipKind> values = <ClipKind>[+ CLIP_KIND_UNSPECIFIED,+ CLIP_KIND_TEXT,+ CLIP_KIND_HTML,+ CLIP_KIND_IMAGE,+ CLIP_KIND_FILE,+ ];++ static final $core.List<ClipKind?> _byValue =+ $pb.ProtobufEnum.$_initByValueList(values, 4);+ static ClipKind? valueOf($core.int value) =>+ value < 0 || value >= _byValue.length ? null : _byValue[value];++ const ClipKind._(super.value, super.name);+}++class ClipStatus extends $pb.ProtobufEnum {+ static const ClipStatus CLIP_STATUS_UNSPECIFIED =+ ClipStatus._(0, _omitEnumNames ? '' : 'CLIP_STATUS_UNSPECIFIED');+ static const ClipStatus CLIP_STATUS_READY =+ ClipStatus._(1, _omitEnumNames ? '' : 'CLIP_STATUS_READY');+ static const ClipStatus CLIP_STATUS_REMOTE_ONLY =+ ClipStatus._(2, _omitEnumNames ? '' : 'CLIP_STATUS_REMOTE_ONLY');+ static const ClipStatus CLIP_STATUS_FETCHING =+ ClipStatus._(3, _omitEnumNames ? '' : 'CLIP_STATUS_FETCHING');+ static const ClipStatus CLIP_STATUS_FAILED =+ ClipStatus._(4, _omitEnumNames ? '' : 'CLIP_STATUS_FAILED');+ static const ClipStatus CLIP_STATUS_EXPIRED =+ ClipStatus._(5, _omitEnumNames ? '' : 'CLIP_STATUS_EXPIRED');++ static const $core.List<ClipStatus> values = <ClipStatus>[+ CLIP_STATUS_UNSPECIFIED,+ CLIP_STATUS_READY,+ CLIP_STATUS_REMOTE_ONLY,+ CLIP_STATUS_FETCHING,+ CLIP_STATUS_FAILED,+ CLIP_STATUS_EXPIRED,+ ];++ static final $core.List<ClipStatus?> _byValue =+ $pb.ProtobufEnum.$_initByValueList(values, 5);+ static ClipStatus? valueOf($core.int value) =>+ value < 0 || value >= _byValue.length ? null : _byValue[value];++ const ClipStatus._(super.value, super.name);+}++class ConnectionKind extends $pb.ProtobufEnum {+ static const ConnectionKind CONNECTION_KIND_UNSPECIFIED =+ ConnectionKind._(0, _omitEnumNames ? '' : 'CONNECTION_KIND_UNSPECIFIED');+ static const ConnectionKind CONNECTION_KIND_OFFLINE =+ ConnectionKind._(1, _omitEnumNames ? '' : 'CONNECTION_KIND_OFFLINE');+ static const ConnectionKind CONNECTION_KIND_DIRECT =+ ConnectionKind._(2, _omitEnumNames ? '' : 'CONNECTION_KIND_DIRECT');+ static const ConnectionKind CONNECTION_KIND_RELAY =+ ConnectionKind._(3, _omitEnumNames ? '' : 'CONNECTION_KIND_RELAY');++ static const $core.List<ConnectionKind> values = <ConnectionKind>[+ CONNECTION_KIND_UNSPECIFIED,+ CONNECTION_KIND_OFFLINE,+ CONNECTION_KIND_DIRECT,+ CONNECTION_KIND_RELAY,+ ];++ static final $core.List<ConnectionKind?> _byValue =+ $pb.ProtobufEnum.$_initByValueList(values, 3);+ static ConnectionKind? valueOf($core.int value) =>+ value < 0 || value >= _byValue.length ? null : _byValue[value];++ const ConnectionKind._(super.value, super.name);+}++/// macOS 剪贴板授权状态,对应 NSPasteboardAccessBehavior。+/// 非 ALWAYS_ALLOW 时 daemon 不会去读剪贴板内容,避免卡在授权弹窗上。+class ClipboardPermission extends $pb.ProtobufEnum {+ static const ClipboardPermission CLIPBOARD_PERMISSION_UNSPECIFIED =+ ClipboardPermission._(+ 0, _omitEnumNames ? '' : 'CLIPBOARD_PERMISSION_UNSPECIFIED');+ static const ClipboardPermission CLIPBOARD_PERMISSION_NOT_APPLICABLE =+ ClipboardPermission._(+ 1, _omitEnumNames ? '' : 'CLIPBOARD_PERMISSION_NOT_APPLICABLE');+ static const ClipboardPermission CLIPBOARD_PERMISSION_DEFAULT =+ ClipboardPermission._(+ 2, _omitEnumNames ? '' : 'CLIPBOARD_PERMISSION_DEFAULT');+ static const ClipboardPermission CLIPBOARD_PERMISSION_ASK =+ ClipboardPermission._(+ 3, _omitEnumNames ? '' : 'CLIPBOARD_PERMISSION_ASK');+ static const ClipboardPermission CLIPBOARD_PERMISSION_ALWAYS_ALLOW =+ ClipboardPermission._(+ 4, _omitEnumNames ? '' : 'CLIPBOARD_PERMISSION_ALWAYS_ALLOW');+ static const ClipboardPermission CLIPBOARD_PERMISSION_ALWAYS_DENY =+ ClipboardPermission._(+ 5, _omitEnumNames ? '' : 'CLIPBOARD_PERMISSION_ALWAYS_DENY');++ static const $core.List<ClipboardPermission> values = <ClipboardPermission>[+ CLIPBOARD_PERMISSION_UNSPECIFIED,+ CLIPBOARD_PERMISSION_NOT_APPLICABLE,+ CLIPBOARD_PERMISSION_DEFAULT,+ CLIPBOARD_PERMISSION_ASK,+ CLIPBOARD_PERMISSION_ALWAYS_ALLOW,+ CLIPBOARD_PERMISSION_ALWAYS_DENY,+ ];++ static final $core.List<ClipboardPermission?> _byValue =+ $pb.ProtobufEnum.$_initByValueList(values, 5);+ static ClipboardPermission? valueOf($core.int value) =>+ value < 0 || value >= _byValue.length ? null : _byValue[value];++ const ClipboardPermission._(super.value, super.name);+}++const $core.bool _omitEnumNames =+ $core.bool.fromEnvironment('protobuf.omit_enum_names');diff --git a/ui/lib/gen/copysync/v1/daemon.pbgrpc.dart b/ui/lib/gen/copysync/v1/daemon.pbgrpc.dartnew file mode 100644index 0000000..50cce05--- /dev/null+++ b/ui/lib/gen/copysync/v1/daemon.pbgrpc.dart@@ -0,0 +1,431 @@+// This is a generated file - do not edit.+//+// Generated from copysync/v1/daemon.proto.++// @dart = 3.3++// ignore_for_file: annotate_overrides, camel_case_types, comment_references+// ignore_for_file: constant_identifier_names+// ignore_for_file: curly_braces_in_flow_control_structures+// ignore_for_file: deprecated_member_use_from_same_package, library_prefixes+// ignore_for_file: non_constant_identifier_names, prefer_relative_imports++import 'dart:async' as $async;+import 'dart:core' as $core;++import 'package:grpc/service_api.dart' as $grpc;+import 'package:protobuf/protobuf.dart' as $pb;++import 'daemon.pb.dart' as $0;++export 'daemon.pb.dart';++@$pb.GrpcServiceName('copysync.v1.DaemonService')+class DaemonServiceClient extends $grpc.Client {+ /// The hostname for this service.+ static const $core.String defaultHost = '';++ /// OAuth scopes needed for the client.+ static const $core.List<$core.String> oauthScopes = [+ '',+ ];++ DaemonServiceClient(super.channel, {super.options, super.interceptors});++ /// 订阅事件流。UI 启动后第一件事,断线需重连。+ $grpc.ResponseStream<$0.Event> subscribe(+ $0.SubscribeRequest request, {+ $grpc.CallOptions? options,+ }) {+ return $createStreamingCall(+ _$subscribe, $async.Stream.fromIterable([request]),+ options: options);+ }++ $grpc.ResponseFuture<$0.ListHistoryResponse> listHistory(+ $0.ListHistoryRequest request, {+ $grpc.CallOptions? options,+ }) {+ return $createUnaryCall(_$listHistory, request, options: options);+ }++ $grpc.ResponseFuture<$0.Empty> deleteHistory(+ $0.DeleteHistoryRequest request, {+ $grpc.CallOptions? options,+ }) {+ return $createUnaryCall(_$deleteHistory, request, options: options);+ }++ /// 拉取仅有元数据的大文件记录。立即返回,进度走事件流。+ $grpc.ResponseFuture<$0.Empty> fetch(+ $0.FetchRequest request, {+ $grpc.CallOptions? options,+ }) {+ return $createUnaryCall(_$fetch, request, options: options);+ }++ /// 把某条已就绪的记录重新放进本机剪贴板+ $grpc.ResponseFuture<$0.Empty> applyToClipboard(+ $0.ApplyToClipboardRequest request, {+ $grpc.CallOptions? options,+ }) {+ return $createUnaryCall(_$applyToClipboard, request, options: options);+ }++ $grpc.ResponseFuture<$0.ListDevicesResponse> listDevices(+ $0.Empty request, {+ $grpc.CallOptions? options,+ }) {+ return $createUnaryCall(_$listDevices, request, options: options);+ }++ $grpc.ResponseFuture<$0.CreatePairingCodeResponse> createPairingCode(+ $0.Empty request, {+ $grpc.CallOptions? options,+ }) {+ return $createUnaryCall(_$createPairingCode, request, options: options);+ }++ $grpc.ResponseFuture<$0.RedeemPairingCodeResponse> redeemPairingCode(+ $0.RedeemPairingCodeRequest request, {+ $grpc.CallOptions? options,+ }) {+ return $createUnaryCall(_$redeemPairingCode, request, options: options);+ }++ /// 配对双方各自确认指纹后才真正互信+ $grpc.ResponseFuture<$0.Empty> confirmPairing(+ $0.ConfirmPairingRequest request, {+ $grpc.CallOptions? options,+ }) {+ return $createUnaryCall(_$confirmPairing, request, options: options);+ }++ $grpc.ResponseFuture<$0.Empty> unpair(+ $0.UnpairRequest request, {+ $grpc.CallOptions? options,+ }) {+ return $createUnaryCall(_$unpair, request, options: options);+ }++ $grpc.ResponseFuture<$0.Config> getConfig(+ $0.Empty request, {+ $grpc.CallOptions? options,+ }) {+ return $createUnaryCall(_$getConfig, request, options: options);+ }++ $grpc.ResponseFuture<$0.Config> updateConfig(+ $0.Config request, {+ $grpc.CallOptions? options,+ }) {+ return $createUnaryCall(_$updateConfig, request, options: options);+ }++ $grpc.ResponseFuture<$0.Status> getStatus(+ $0.Empty request, {+ $grpc.CallOptions? options,+ }) {+ return $createUnaryCall(_$getStatus, request, options: options);+ }++ /// 引导用户授予剪贴板权限(打开系统设置面板)+ $grpc.ResponseFuture<$0.Empty> requestClipboardPermission(+ $0.Empty request, {+ $grpc.CallOptions? options,+ }) {+ return $createUnaryCall(_$requestClipboardPermission, request,+ options: options);+ }++ // method descriptors++ static final _$subscribe = $grpc.ClientMethod<$0.SubscribeRequest, $0.Event>(+ '/copysync.v1.DaemonService/Subscribe',+ ($0.SubscribeRequest value) => value.writeToBuffer(),+ $0.Event.fromBuffer);+ static final _$listHistory =+ $grpc.ClientMethod<$0.ListHistoryRequest, $0.ListHistoryResponse>(+ '/copysync.v1.DaemonService/ListHistory',+ ($0.ListHistoryRequest value) => value.writeToBuffer(),+ $0.ListHistoryResponse.fromBuffer);+ static final _$deleteHistory =+ $grpc.ClientMethod<$0.DeleteHistoryRequest, $0.Empty>(+ '/copysync.v1.DaemonService/DeleteHistory',+ ($0.DeleteHistoryRequest value) => value.writeToBuffer(),+ $0.Empty.fromBuffer);+ static final _$fetch = $grpc.ClientMethod<$0.FetchRequest, $0.Empty>(+ '/copysync.v1.DaemonService/Fetch',+ ($0.FetchRequest value) => value.writeToBuffer(),+ $0.Empty.fromBuffer);+ static final _$applyToClipboard =+ $grpc.ClientMethod<$0.ApplyToClipboardRequest, $0.Empty>(+ '/copysync.v1.DaemonService/ApplyToClipboard',+ ($0.ApplyToClipboardRequest value) => value.writeToBuffer(),+ $0.Empty.fromBuffer);+ static final _$listDevices =+ $grpc.ClientMethod<$0.Empty, $0.ListDevicesResponse>(+ '/copysync.v1.DaemonService/ListDevices',+ ($0.Empty value) => value.writeToBuffer(),+ $0.ListDevicesResponse.fromBuffer);+ static final _$createPairingCode =+ $grpc.ClientMethod<$0.Empty, $0.CreatePairingCodeResponse>(+ '/copysync.v1.DaemonService/CreatePairingCode',+ ($0.Empty value) => value.writeToBuffer(),+ $0.CreatePairingCodeResponse.fromBuffer);+ static final _$redeemPairingCode = $grpc.ClientMethod<+ $0.RedeemPairingCodeRequest, $0.RedeemPairingCodeResponse>(+ '/copysync.v1.DaemonService/RedeemPairingCode',+ ($0.RedeemPairingCodeRequest value) => value.writeToBuffer(),+ $0.RedeemPairingCodeResponse.fromBuffer);+ static final _$confirmPairing =+ $grpc.ClientMethod<$0.ConfirmPairingRequest, $0.Empty>(+ '/copysync.v1.DaemonService/ConfirmPairing',+ ($0.ConfirmPairingRequest value) => value.writeToBuffer(),+ $0.Empty.fromBuffer);+ static final _$unpair = $grpc.ClientMethod<$0.UnpairRequest, $0.Empty>(+ '/copysync.v1.DaemonService/Unpair',+ ($0.UnpairRequest value) => value.writeToBuffer(),+ $0.Empty.fromBuffer);+ static final _$getConfig = $grpc.ClientMethod<$0.Empty, $0.Config>(+ '/copysync.v1.DaemonService/GetConfig',+ ($0.Empty value) => value.writeToBuffer(),+ $0.Config.fromBuffer);+ static final _$updateConfig = $grpc.ClientMethod<$0.Config, $0.Config>(+ '/copysync.v1.DaemonService/UpdateConfig',+ ($0.Config value) => value.writeToBuffer(),+ $0.Config.fromBuffer);+ static final _$getStatus = $grpc.ClientMethod<$0.Empty, $0.Status>(+ '/copysync.v1.DaemonService/GetStatus',+ ($0.Empty value) => value.writeToBuffer(),+ $0.Status.fromBuffer);+ static final _$requestClipboardPermission =+ $grpc.ClientMethod<$0.Empty, $0.Empty>(+ '/copysync.v1.DaemonService/RequestClipboardPermission',+ ($0.Empty value) => value.writeToBuffer(),+ $0.Empty.fromBuffer);+}++@$pb.GrpcServiceName('copysync.v1.DaemonService')+abstract class DaemonServiceBase extends $grpc.Service {+ $core.String get $name => 'copysync.v1.DaemonService';++ DaemonServiceBase() {+ $addMethod($grpc.ServiceMethod<$0.SubscribeRequest, $0.Event>(+ 'Subscribe',+ subscribe_Pre,+ false,+ true,+ ($core.List<$core.int> value) => $0.SubscribeRequest.fromBuffer(value),+ ($0.Event value) => value.writeToBuffer()));+ $addMethod(+ $grpc.ServiceMethod<$0.ListHistoryRequest, $0.ListHistoryResponse>(+ 'ListHistory',+ listHistory_Pre,+ false,+ false,+ ($core.List<$core.int> value) =>+ $0.ListHistoryRequest.fromBuffer(value),+ ($0.ListHistoryResponse value) => value.writeToBuffer()));+ $addMethod($grpc.ServiceMethod<$0.DeleteHistoryRequest, $0.Empty>(+ 'DeleteHistory',+ deleteHistory_Pre,+ false,+ false,+ ($core.List<$core.int> value) =>+ $0.DeleteHistoryRequest.fromBuffer(value),+ ($0.Empty value) => value.writeToBuffer()));+ $addMethod($grpc.ServiceMethod<$0.FetchRequest, $0.Empty>(+ 'Fetch',+ fetch_Pre,+ false,+ false,+ ($core.List<$core.int> value) => $0.FetchRequest.fromBuffer(value),+ ($0.Empty value) => value.writeToBuffer()));+ $addMethod($grpc.ServiceMethod<$0.ApplyToClipboardRequest, $0.Empty>(+ 'ApplyToClipboard',+ applyToClipboard_Pre,+ false,+ false,+ ($core.List<$core.int> value) =>+ $0.ApplyToClipboardRequest.fromBuffer(value),+ ($0.Empty value) => value.writeToBuffer()));+ $addMethod($grpc.ServiceMethod<$0.Empty, $0.ListDevicesResponse>(+ 'ListDevices',+ listDevices_Pre,+ false,+ false,+ ($core.List<$core.int> value) => $0.Empty.fromBuffer(value),+ ($0.ListDevicesResponse value) => value.writeToBuffer()));+ $addMethod($grpc.ServiceMethod<$0.Empty, $0.CreatePairingCodeResponse>(+ 'CreatePairingCode',+ createPairingCode_Pre,+ false,+ false,+ ($core.List<$core.int> value) => $0.Empty.fromBuffer(value),+ ($0.CreatePairingCodeResponse value) => value.writeToBuffer()));+ $addMethod($grpc.ServiceMethod<$0.RedeemPairingCodeRequest,+ $0.RedeemPairingCodeResponse>(+ 'RedeemPairingCode',+ redeemPairingCode_Pre,+ false,+ false,+ ($core.List<$core.int> value) =>+ $0.RedeemPairingCodeRequest.fromBuffer(value),+ ($0.RedeemPairingCodeResponse value) => value.writeToBuffer()));+ $addMethod($grpc.ServiceMethod<$0.ConfirmPairingRequest, $0.Empty>(+ 'ConfirmPairing',+ confirmPairing_Pre,+ false,+ false,+ ($core.List<$core.int> value) =>+ $0.ConfirmPairingRequest.fromBuffer(value),+ ($0.Empty value) => value.writeToBuffer()));+ $addMethod($grpc.ServiceMethod<$0.UnpairRequest, $0.Empty>(+ 'Unpair',+ unpair_Pre,+ false,+ false,+ ($core.List<$core.int> value) => $0.UnpairRequest.fromBuffer(value),+ ($0.Empty value) => value.writeToBuffer()));+ $addMethod($grpc.ServiceMethod<$0.Empty, $0.Config>(+ 'GetConfig',+ getConfig_Pre,+ false,+ false,+ ($core.List<$core.int> value) => $0.Empty.fromBuffer(value),+ ($0.Config value) => value.writeToBuffer()));+ $addMethod($grpc.ServiceMethod<$0.Config, $0.Config>(+ 'UpdateConfig',+ updateConfig_Pre,+ false,+ false,+ ($core.List<$core.int> value) => $0.Config.fromBuffer(value),+ ($0.Config value) => value.writeToBuffer()));+ $addMethod($grpc.ServiceMethod<$0.Empty, $0.Status>(+ 'GetStatus',+ getStatus_Pre,+ false,+ false,+ ($core.List<$core.int> value) => $0.Empty.fromBuffer(value),+ ($0.Status value) => value.writeToBuffer()));+ $addMethod($grpc.ServiceMethod<$0.Empty, $0.Empty>(+ 'RequestClipboardPermission',+ requestClipboardPermission_Pre,+ false,+ false,+ ($core.List<$core.int> value) => $0.Empty.fromBuffer(value),+ ($0.Empty value) => value.writeToBuffer()));+ }++ $async.Stream<$0.Event> subscribe_Pre($grpc.ServiceCall $call,+ $async.Future<$0.SubscribeRequest> $request) async* {+ yield* subscribe($call, await $request);+ }++ $async.Stream<$0.Event> subscribe(+ $grpc.ServiceCall call, $0.SubscribeRequest request);++ $async.Future<$0.ListHistoryResponse> listHistory_Pre($grpc.ServiceCall $call,+ $async.Future<$0.ListHistoryRequest> $request) async {+ return listHistory($call, await $request);+ }++ $async.Future<$0.ListHistoryResponse> listHistory(+ $grpc.ServiceCall call, $0.ListHistoryRequest request);++ $async.Future<$0.Empty> deleteHistory_Pre($grpc.ServiceCall $call,+ $async.Future<$0.DeleteHistoryRequest> $request) async {+ return deleteHistory($call, await $request);+ }++ $async.Future<$0.Empty> deleteHistory(+ $grpc.ServiceCall call, $0.DeleteHistoryRequest request);++ $async.Future<$0.Empty> fetch_Pre(+ $grpc.ServiceCall $call, $async.Future<$0.FetchRequest> $request) async {+ return fetch($call, await $request);+ }++ $async.Future<$0.Empty> fetch(+ $grpc.ServiceCall call, $0.FetchRequest request);++ $async.Future<$0.Empty> applyToClipboard_Pre($grpc.ServiceCall $call,+ $async.Future<$0.ApplyToClipboardRequest> $request) async {+ return applyToClipboard($call, await $request);+ }++ $async.Future<$0.Empty> applyToClipboard(+ $grpc.ServiceCall call, $0.ApplyToClipboardRequest request);++ $async.Future<$0.ListDevicesResponse> listDevices_Pre(+ $grpc.ServiceCall $call, $async.Future<$0.Empty> $request) async {+ return listDevices($call, await $request);+ }++ $async.Future<$0.ListDevicesResponse> listDevices(+ $grpc.ServiceCall call, $0.Empty request);++ $async.Future<$0.CreatePairingCodeResponse> createPairingCode_Pre(+ $grpc.ServiceCall $call, $async.Future<$0.Empty> $request) async {+ return createPairingCode($call, await $request);+ }++ $async.Future<$0.CreatePairingCodeResponse> createPairingCode(+ $grpc.ServiceCall call, $0.Empty request);++ $async.Future<$0.RedeemPairingCodeResponse> redeemPairingCode_Pre(+ $grpc.ServiceCall $call,+ $async.Future<$0.RedeemPairingCodeRequest> $request) async {+ return redeemPairingCode($call, await $request);+ }++ $async.Future<$0.RedeemPairingCodeResponse> redeemPairingCode(+ $grpc.ServiceCall call, $0.RedeemPairingCodeRequest request);++ $async.Future<$0.Empty> confirmPairing_Pre($grpc.ServiceCall $call,+ $async.Future<$0.ConfirmPairingRequest> $request) async {+ return confirmPairing($call, await $request);+ }++ $async.Future<$0.Empty> confirmPairing(+ $grpc.ServiceCall call, $0.ConfirmPairingRequest request);++ $async.Future<$0.Empty> unpair_Pre(+ $grpc.ServiceCall $call, $async.Future<$0.UnpairRequest> $request) async {+ return unpair($call, await $request);+ }++ $async.Future<$0.Empty> unpair(+ $grpc.ServiceCall call, $0.UnpairRequest request);++ $async.Future<$0.Config> getConfig_Pre(+ $grpc.ServiceCall $call, $async.Future<$0.Empty> $request) async {+ return getConfig($call, await $request);+ }++ $async.Future<$0.Config> getConfig($grpc.ServiceCall call, $0.Empty request);++ $async.Future<$0.Config> updateConfig_Pre(+ $grpc.ServiceCall $call, $async.Future<$0.Config> $request) async {+ return updateConfig($call, await $request);+ }++ $async.Future<$0.Config> updateConfig(+ $grpc.ServiceCall call, $0.Config request);++ $async.Future<$0.Status> getStatus_Pre(+ $grpc.ServiceCall $call, $async.Future<$0.Empty> $request) async {+ return getStatus($call, await $request);+ }++ $async.Future<$0.Status> getStatus($grpc.ServiceCall call, $0.Empty request);++ $async.Future<$0.Empty> requestClipboardPermission_Pre(+ $grpc.ServiceCall $call, $async.Future<$0.Empty> $request) async {+ return requestClipboardPermission($call, await $request);+ }++ $async.Future<$0.Empty> requestClipboardPermission(+ $grpc.ServiceCall call, $0.Empty request);+}diff --git a/ui/lib/gen/copysync/v1/daemon.pbjson.dart b/ui/lib/gen/copysync/v1/daemon.pbjson.dartnew file mode 100644index 0000000..f3dcb67--- /dev/null+++ b/ui/lib/gen/copysync/v1/daemon.pbjson.dart@@ -0,0 +1,585 @@+// This is a generated file - do not edit.+//+// Generated from copysync/v1/daemon.proto.++// @dart = 3.3++// ignore_for_file: annotate_overrides, camel_case_types, comment_references+// ignore_for_file: constant_identifier_names+// ignore_for_file: curly_braces_in_flow_control_structures+// ignore_for_file: deprecated_member_use_from_same_package, library_prefixes+// ignore_for_file: non_constant_identifier_names, prefer_relative_imports+// ignore_for_file: unused_import++import 'dart:convert' as $convert;+import 'dart:core' as $core;+import 'dart:typed_data' as $typed_data;++@$core.Deprecated('Use clipKindDescriptor instead')+const ClipKind$json = {+ '1': 'ClipKind',+ '2': [+ {'1': 'CLIP_KIND_UNSPECIFIED', '2': 0},+ {'1': 'CLIP_KIND_TEXT', '2': 1},+ {'1': 'CLIP_KIND_HTML', '2': 2},+ {'1': 'CLIP_KIND_IMAGE', '2': 3},+ {'1': 'CLIP_KIND_FILE', '2': 4},+ ],+};++/// Descriptor for `ClipKind`. Decode as a `google.protobuf.EnumDescriptorProto`.+final $typed_data.Uint8List clipKindDescriptor = $convert.base64Decode(+ 'CghDbGlwS2luZBIZChVDTElQX0tJTkRfVU5TUEVDSUZJRUQQABISCg5DTElQX0tJTkRfVEVYVB'+ 'ABEhIKDkNMSVBfS0lORF9IVE1MEAISEwoPQ0xJUF9LSU5EX0lNQUdFEAMSEgoOQ0xJUF9LSU5E'+ 'X0ZJTEUQBA==');++@$core.Deprecated('Use clipStatusDescriptor instead')+const ClipStatus$json = {+ '1': 'ClipStatus',+ '2': [+ {'1': 'CLIP_STATUS_UNSPECIFIED', '2': 0},+ {'1': 'CLIP_STATUS_READY', '2': 1},+ {'1': 'CLIP_STATUS_REMOTE_ONLY', '2': 2},+ {'1': 'CLIP_STATUS_FETCHING', '2': 3},+ {'1': 'CLIP_STATUS_FAILED', '2': 4},+ {'1': 'CLIP_STATUS_EXPIRED', '2': 5},+ ],+};++/// Descriptor for `ClipStatus`. Decode as a `google.protobuf.EnumDescriptorProto`.+final $typed_data.Uint8List clipStatusDescriptor = $convert.base64Decode(+ 'CgpDbGlwU3RhdHVzEhsKF0NMSVBfU1RBVFVTX1VOU1BFQ0lGSUVEEAASFQoRQ0xJUF9TVEFUVV'+ 'NfUkVBRFkQARIbChdDTElQX1NUQVRVU19SRU1PVEVfT05MWRACEhgKFENMSVBfU1RBVFVTX0ZF'+ 'VENISU5HEAMSFgoSQ0xJUF9TVEFUVVNfRkFJTEVEEAQSFwoTQ0xJUF9TVEFUVVNfRVhQSVJFRB'+ 'AF');++@$core.Deprecated('Use connectionKindDescriptor instead')+const ConnectionKind$json = {+ '1': 'ConnectionKind',+ '2': [+ {'1': 'CONNECTION_KIND_UNSPECIFIED', '2': 0},+ {'1': 'CONNECTION_KIND_OFFLINE', '2': 1},+ {'1': 'CONNECTION_KIND_DIRECT', '2': 2},+ {'1': 'CONNECTION_KIND_RELAY', '2': 3},+ ],+};++/// Descriptor for `ConnectionKind`. Decode as a `google.protobuf.EnumDescriptorProto`.+final $typed_data.Uint8List connectionKindDescriptor = $convert.base64Decode(+ 'Cg5Db25uZWN0aW9uS2luZBIfChtDT05ORUNUSU9OX0tJTkRfVU5TUEVDSUZJRUQQABIbChdDT0'+ '5ORUNUSU9OX0tJTkRfT0ZGTElORRABEhoKFkNPTk5FQ1RJT05fS0lORF9ESVJFQ1QQAhIZChVD'+ 'T05ORUNUSU9OX0tJTkRfUkVMQVkQAw==');++@$core.Deprecated('Use clipboardPermissionDescriptor instead')+const ClipboardPermission$json = {+ '1': 'ClipboardPermission',+ '2': [+ {'1': 'CLIPBOARD_PERMISSION_UNSPECIFIED', '2': 0},+ {'1': 'CLIPBOARD_PERMISSION_NOT_APPLICABLE', '2': 1},+ {'1': 'CLIPBOARD_PERMISSION_DEFAULT', '2': 2},+ {'1': 'CLIPBOARD_PERMISSION_ASK', '2': 3},+ {'1': 'CLIPBOARD_PERMISSION_ALWAYS_ALLOW', '2': 4},+ {'1': 'CLIPBOARD_PERMISSION_ALWAYS_DENY', '2': 5},+ ],+};++/// Descriptor for `ClipboardPermission`. Decode as a `google.protobuf.EnumDescriptorProto`.+final $typed_data.Uint8List clipboardPermissionDescriptor = $convert.base64Decode(+ 'ChNDbGlwYm9hcmRQZXJtaXNzaW9uEiQKIENMSVBCT0FSRF9QRVJNSVNTSU9OX1VOU1BFQ0lGSU'+ 'VEEAASJwojQ0xJUEJPQVJEX1BFUk1JU1NJT05fTk9UX0FQUExJQ0FCTEUQARIgChxDTElQQk9B'+ 'UkRfUEVSTUlTU0lPTl9ERUZBVUxUEAISHAoYQ0xJUEJPQVJEX1BFUk1JU1NJT05fQVNLEAMSJQ'+ 'ohQ0xJUEJPQVJEX1BFUk1JU1NJT05fQUxXQVlTX0FMTE9XEAQSJAogQ0xJUEJPQVJEX1BFUk1J'+ 'U1NJT05fQUxXQVlTX0RFTlkQBQ==');++@$core.Deprecated('Use emptyDescriptor instead')+const Empty$json = {+ '1': 'Empty',+};++/// Descriptor for `Empty`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List emptyDescriptor =+ $convert.base64Decode('CgVFbXB0eQ==');++@$core.Deprecated('Use clipItemDescriptor instead')+const ClipItem$json = {+ '1': 'ClipItem',+ '2': [+ {'1': 'name', '3': 1, '4': 1, '5': 9, '10': 'name'},+ {'1': 'size', '3': 2, '4': 1, '5': 3, '10': 'size'},+ {'1': 'is_dir', '3': 3, '4': 1, '5': 8, '10': 'isDir'},+ {'1': 'content_type', '3': 4, '4': 1, '5': 9, '10': 'contentType'},+ ],+};++/// Descriptor for `ClipItem`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List clipItemDescriptor = $convert.base64Decode(+ 'CghDbGlwSXRlbRISCgRuYW1lGAEgASgJUgRuYW1lEhIKBHNpemUYAiABKANSBHNpemUSFQoGaX'+ 'NfZGlyGAMgASgIUgVpc0RpchIhCgxjb250ZW50X3R5cGUYBCABKAlSC2NvbnRlbnRUeXBl');++@$core.Deprecated('Use clipRecordDescriptor instead')+const ClipRecord$json = {+ '1': 'ClipRecord',+ '2': [+ {'1': 'id', '3': 1, '4': 1, '5': 9, '10': 'id'},+ {+ '1': 'kind',+ '3': 2,+ '4': 1,+ '5': 14,+ '6': '.copysync.v1.ClipKind',+ '10': 'kind'+ },+ {+ '1': 'status',+ '3': 3,+ '4': 1,+ '5': 14,+ '6': '.copysync.v1.ClipStatus',+ '10': 'status'+ },+ {'1': 'origin_device_id', '3': 4, '4': 1, '5': 9, '10': 'originDeviceId'},+ {+ '1': 'origin_device_name',+ '3': 5,+ '4': 1,+ '5': 9,+ '10': 'originDeviceName'+ },+ {'1': 'outgoing', '3': 6, '4': 1, '5': 8, '10': 'outgoing'},+ {+ '1': 'items',+ '3': 7,+ '4': 3,+ '5': 11,+ '6': '.copysync.v1.ClipItem',+ '10': 'items'+ },+ {'1': 'total_size', '3': 8, '4': 1, '5': 3, '10': 'totalSize'},+ {'1': 'text_preview', '3': 9, '4': 1, '5': 9, '10': 'textPreview'},+ {'1': 'created_at_unix', '3': 10, '4': 1, '5': 3, '10': 'createdAtUnix'},+ {'1': 'expires_at_unix', '3': 11, '4': 1, '5': 3, '10': 'expiresAtUnix'},+ {'1': 'error', '3': 12, '4': 1, '5': 9, '10': 'error'},+ ],+};++/// Descriptor for `ClipRecord`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List clipRecordDescriptor = $convert.base64Decode(+ 'CgpDbGlwUmVjb3JkEg4KAmlkGAEgASgJUgJpZBIpCgRraW5kGAIgASgOMhUuY29weXN5bmMudj'+ 'EuQ2xpcEtpbmRSBGtpbmQSLwoGc3RhdHVzGAMgASgOMhcuY29weXN5bmMudjEuQ2xpcFN0YXR1'+ 'c1IGc3RhdHVzEigKEG9yaWdpbl9kZXZpY2VfaWQYBCABKAlSDm9yaWdpbkRldmljZUlkEiwKEm'+ '9yaWdpbl9kZXZpY2VfbmFtZRgFIAEoCVIQb3JpZ2luRGV2aWNlTmFtZRIaCghvdXRnb2luZxgG'+ 'IAEoCFIIb3V0Z29pbmcSKwoFaXRlbXMYByADKAsyFS5jb3B5c3luYy52MS5DbGlwSXRlbVIFaX'+ 'RlbXMSHQoKdG90YWxfc2l6ZRgIIAEoA1IJdG90YWxTaXplEiEKDHRleHRfcHJldmlldxgJIAEo'+ 'CVILdGV4dFByZXZpZXcSJgoPY3JlYXRlZF9hdF91bml4GAogASgDUg1jcmVhdGVkQXRVbml4Ei'+ 'YKD2V4cGlyZXNfYXRfdW5peBgLIAEoA1INZXhwaXJlc0F0VW5peBIUCgVlcnJvchgMIAEoCVIF'+ 'ZXJyb3I=');++@$core.Deprecated('Use subscribeRequestDescriptor instead')+const SubscribeRequest$json = {+ '1': 'SubscribeRequest',+ '2': [+ {'1': 'since_unix', '3': 1, '4': 1, '5': 3, '10': 'sinceUnix'},+ ],+};++/// Descriptor for `SubscribeRequest`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List subscribeRequestDescriptor = $convert.base64Decode(+ 'ChBTdWJzY3JpYmVSZXF1ZXN0Eh0KCnNpbmNlX3VuaXgYASABKANSCXNpbmNlVW5peA==');++@$core.Deprecated('Use transferProgressDescriptor instead')+const TransferProgress$json = {+ '1': 'TransferProgress',+ '2': [+ {'1': 'clip_id', '3': 1, '4': 1, '5': 9, '10': 'clipId'},+ {'1': 'transferred', '3': 2, '4': 1, '5': 3, '10': 'transferred'},+ {'1': 'total', '3': 3, '4': 1, '5': 3, '10': 'total'},+ {'1': 'bytes_per_second', '3': 4, '4': 1, '5': 1, '10': 'bytesPerSecond'},+ ],+};++/// Descriptor for `TransferProgress`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List transferProgressDescriptor = $convert.base64Decode(+ 'ChBUcmFuc2ZlclByb2dyZXNzEhcKB2NsaXBfaWQYASABKAlSBmNsaXBJZBIgCgt0cmFuc2Zlcn'+ 'JlZBgCIAEoA1ILdHJhbnNmZXJyZWQSFAoFdG90YWwYAyABKANSBXRvdGFsEigKEGJ5dGVzX3Bl'+ 'cl9zZWNvbmQYBCABKAFSDmJ5dGVzUGVyU2Vjb25k');++@$core.Deprecated('Use deviceDescriptor instead')+const Device$json = {+ '1': 'Device',+ '2': [+ {'1': 'id', '3': 1, '4': 1, '5': 9, '10': 'id'},+ {'1': 'name', '3': 2, '4': 1, '5': 9, '10': 'name'},+ {'1': 'platform', '3': 3, '4': 1, '5': 9, '10': 'platform'},+ {'1': 'online', '3': 4, '4': 1, '5': 8, '10': 'online'},+ {+ '1': 'connection',+ '3': 5,+ '4': 1,+ '5': 14,+ '6': '.copysync.v1.ConnectionKind',+ '10': 'connection'+ },+ {+ '1': 'public_key_fingerprint',+ '3': 6,+ '4': 1,+ '5': 9,+ '10': 'publicKeyFingerprint'+ },+ {'1': 'paired_at_unix', '3': 7, '4': 1, '5': 3, '10': 'pairedAtUnix'},+ {'1': 'pairing_session', '3': 8, '4': 1, '5': 9, '10': 'pairingSession'},+ ],+};++/// Descriptor for `Device`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List deviceDescriptor = $convert.base64Decode(+ 'CgZEZXZpY2USDgoCaWQYASABKAlSAmlkEhIKBG5hbWUYAiABKAlSBG5hbWUSGgoIcGxhdGZvcm'+ '0YAyABKAlSCHBsYXRmb3JtEhYKBm9ubGluZRgEIAEoCFIGb25saW5lEjsKCmNvbm5lY3Rpb24Y'+ 'BSABKA4yGy5jb3B5c3luYy52MS5Db25uZWN0aW9uS2luZFIKY29ubmVjdGlvbhI0ChZwdWJsaW'+ 'Nfa2V5X2ZpbmdlcnByaW50GAYgASgJUhRwdWJsaWNLZXlGaW5nZXJwcmludBIkCg5wYWlyZWRf'+ 'YXRfdW5peBgHIAEoA1IMcGFpcmVkQXRVbml4EicKD3BhaXJpbmdfc2Vzc2lvbhgIIAEoCVIOcG'+ 'FpcmluZ1Nlc3Npb24=');++@$core.Deprecated('Use eventDescriptor instead')+const Event$json = {+ '1': 'Event',+ '2': [+ {+ '1': 'clip_added',+ '3': 1,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.ClipRecord',+ '9': 0,+ '10': 'clipAdded'+ },+ {+ '1': 'clip_updated',+ '3': 2,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.ClipRecord',+ '9': 0,+ '10': 'clipUpdated'+ },+ {'1': 'clip_removed', '3': 3, '4': 1, '5': 9, '9': 0, '10': 'clipRemoved'},+ {+ '1': 'progress',+ '3': 4,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.TransferProgress',+ '9': 0,+ '10': 'progress'+ },+ {+ '1': 'device_changed',+ '3': 5,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.Device',+ '9': 0,+ '10': 'deviceChanged'+ },+ {+ '1': 'permission_changed',+ '3': 6,+ '4': 1,+ '5': 14,+ '6': '.copysync.v1.ClipboardPermission',+ '9': 0,+ '10': 'permissionChanged'+ },+ {+ '1': 'status_changed',+ '3': 7,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.Status',+ '9': 0,+ '10': 'statusChanged'+ },+ ],+ '8': [+ {'1': 'payload'},+ ],+};++/// Descriptor for `Event`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List eventDescriptor = $convert.base64Decode(+ 'CgVFdmVudBI4CgpjbGlwX2FkZGVkGAEgASgLMhcuY29weXN5bmMudjEuQ2xpcFJlY29yZEgAUg'+ 'ljbGlwQWRkZWQSPAoMY2xpcF91cGRhdGVkGAIgASgLMhcuY29weXN5bmMudjEuQ2xpcFJlY29y'+ 'ZEgAUgtjbGlwVXBkYXRlZBIjCgxjbGlwX3JlbW92ZWQYAyABKAlIAFILY2xpcFJlbW92ZWQSOw'+ 'oIcHJvZ3Jlc3MYBCABKAsyHS5jb3B5c3luYy52MS5UcmFuc2ZlclByb2dyZXNzSABSCHByb2dy'+ 'ZXNzEjwKDmRldmljZV9jaGFuZ2VkGAUgASgLMhMuY29weXN5bmMudjEuRGV2aWNlSABSDWRldm'+ 'ljZUNoYW5nZWQSUQoScGVybWlzc2lvbl9jaGFuZ2VkGAYgASgOMiAuY29weXN5bmMudjEuQ2xp'+ 'cGJvYXJkUGVybWlzc2lvbkgAUhFwZXJtaXNzaW9uQ2hhbmdlZBI8Cg5zdGF0dXNfY2hhbmdlZB'+ 'gHIAEoCzITLmNvcHlzeW5jLnYxLlN0YXR1c0gAUg1zdGF0dXNDaGFuZ2VkQgkKB3BheWxvYWQ=');++@$core.Deprecated('Use listHistoryRequestDescriptor instead')+const ListHistoryRequest$json = {+ '1': 'ListHistoryRequest',+ '2': [+ {'1': 'limit', '3': 1, '4': 1, '5': 5, '10': 'limit'},+ {'1': 'before_unix', '3': 2, '4': 1, '5': 3, '10': 'beforeUnix'},+ {+ '1': 'kind_filter',+ '3': 3,+ '4': 1,+ '5': 14,+ '6': '.copysync.v1.ClipKind',+ '10': 'kindFilter'+ },+ ],+};++/// Descriptor for `ListHistoryRequest`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List listHistoryRequestDescriptor = $convert.base64Decode(+ 'ChJMaXN0SGlzdG9yeVJlcXVlc3QSFAoFbGltaXQYASABKAVSBWxpbWl0Eh8KC2JlZm9yZV91bm'+ 'l4GAIgASgDUgpiZWZvcmVVbml4EjYKC2tpbmRfZmlsdGVyGAMgASgOMhUuY29weXN5bmMudjEu'+ 'Q2xpcEtpbmRSCmtpbmRGaWx0ZXI=');++@$core.Deprecated('Use listHistoryResponseDescriptor instead')+const ListHistoryResponse$json = {+ '1': 'ListHistoryResponse',+ '2': [+ {+ '1': 'records',+ '3': 1,+ '4': 3,+ '5': 11,+ '6': '.copysync.v1.ClipRecord',+ '10': 'records'+ },+ ],+};++/// Descriptor for `ListHistoryResponse`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List listHistoryResponseDescriptor = $convert.base64Decode(+ 'ChNMaXN0SGlzdG9yeVJlc3BvbnNlEjEKB3JlY29yZHMYASADKAsyFy5jb3B5c3luYy52MS5DbG'+ 'lwUmVjb3JkUgdyZWNvcmRz');++@$core.Deprecated('Use deleteHistoryRequestDescriptor instead')+const DeleteHistoryRequest$json = {+ '1': 'DeleteHistoryRequest',+ '2': [+ {'1': 'ids', '3': 1, '4': 3, '5': 9, '10': 'ids'},+ {'1': 'all', '3': 2, '4': 1, '5': 8, '10': 'all'},+ ],+};++/// Descriptor for `DeleteHistoryRequest`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List deleteHistoryRequestDescriptor = $convert.base64Decode(+ 'ChREZWxldGVIaXN0b3J5UmVxdWVzdBIQCgNpZHMYASADKAlSA2lkcxIQCgNhbGwYAiABKAhSA2'+ 'FsbA==');++@$core.Deprecated('Use fetchRequestDescriptor instead')+const FetchRequest$json = {+ '1': 'FetchRequest',+ '2': [+ {'1': 'clip_id', '3': 1, '4': 1, '5': 9, '10': 'clipId'},+ ],+};++/// Descriptor for `FetchRequest`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List fetchRequestDescriptor = $convert+ .base64Decode('CgxGZXRjaFJlcXVlc3QSFwoHY2xpcF9pZBgBIAEoCVIGY2xpcElk');++@$core.Deprecated('Use applyToClipboardRequestDescriptor instead')+const ApplyToClipboardRequest$json = {+ '1': 'ApplyToClipboardRequest',+ '2': [+ {'1': 'clip_id', '3': 1, '4': 1, '5': 9, '10': 'clipId'},+ ],+};++/// Descriptor for `ApplyToClipboardRequest`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List applyToClipboardRequestDescriptor =+ $convert.base64Decode(+ 'ChdBcHBseVRvQ2xpcGJvYXJkUmVxdWVzdBIXCgdjbGlwX2lkGAEgASgJUgZjbGlwSWQ=');++@$core.Deprecated('Use listDevicesResponseDescriptor instead')+const ListDevicesResponse$json = {+ '1': 'ListDevicesResponse',+ '2': [+ {+ '1': 'self',+ '3': 1,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.Device',+ '10': 'self'+ },+ {+ '1': 'peers',+ '3': 2,+ '4': 3,+ '5': 11,+ '6': '.copysync.v1.Device',+ '10': 'peers'+ },+ ],+};++/// Descriptor for `ListDevicesResponse`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List listDevicesResponseDescriptor = $convert.base64Decode(+ 'ChNMaXN0RGV2aWNlc1Jlc3BvbnNlEicKBHNlbGYYASABKAsyEy5jb3B5c3luYy52MS5EZXZpY2'+ 'VSBHNlbGYSKQoFcGVlcnMYAiADKAsyEy5jb3B5c3luYy52MS5EZXZpY2VSBXBlZXJz');++@$core.Deprecated('Use createPairingCodeResponseDescriptor instead')+const CreatePairingCodeResponse$json = {+ '1': 'CreatePairingCodeResponse',+ '2': [+ {'1': 'code', '3': 1, '4': 1, '5': 9, '10': 'code'},+ {'1': 'expires_at_unix', '3': 2, '4': 1, '5': 3, '10': 'expiresAtUnix'},+ ],+};++/// Descriptor for `CreatePairingCodeResponse`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List createPairingCodeResponseDescriptor =+ $convert.base64Decode(+ 'ChlDcmVhdGVQYWlyaW5nQ29kZVJlc3BvbnNlEhIKBGNvZGUYASABKAlSBGNvZGUSJgoPZXhwaX'+ 'Jlc19hdF91bml4GAIgASgDUg1leHBpcmVzQXRVbml4');++@$core.Deprecated('Use redeemPairingCodeRequestDescriptor instead')+const RedeemPairingCodeRequest$json = {+ '1': 'RedeemPairingCodeRequest',+ '2': [+ {'1': 'code', '3': 1, '4': 1, '5': 9, '10': 'code'},+ ],+};++/// Descriptor for `RedeemPairingCodeRequest`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List redeemPairingCodeRequestDescriptor =+ $convert.base64Decode(+ 'ChhSZWRlZW1QYWlyaW5nQ29kZVJlcXVlc3QSEgoEY29kZRgBIAEoCVIEY29kZQ==');++@$core.Deprecated('Use redeemPairingCodeResponseDescriptor instead')+const RedeemPairingCodeResponse$json = {+ '1': 'RedeemPairingCodeResponse',+ '2': [+ {+ '1': 'peer',+ '3': 1,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.Device',+ '10': 'peer'+ },+ {'1': 'pairing_session', '3': 2, '4': 1, '5': 9, '10': 'pairingSession'},+ ],+};++/// Descriptor for `RedeemPairingCodeResponse`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List redeemPairingCodeResponseDescriptor = $convert.base64Decode(+ 'ChlSZWRlZW1QYWlyaW5nQ29kZVJlc3BvbnNlEicKBHBlZXIYASABKAsyEy5jb3B5c3luYy52MS'+ '5EZXZpY2VSBHBlZXISJwoPcGFpcmluZ19zZXNzaW9uGAIgASgJUg5wYWlyaW5nU2Vzc2lvbg==');++@$core.Deprecated('Use confirmPairingRequestDescriptor instead')+const ConfirmPairingRequest$json = {+ '1': 'ConfirmPairingRequest',+ '2': [+ {'1': 'pairing_session', '3': 1, '4': 1, '5': 9, '10': 'pairingSession'},+ {'1': 'accept', '3': 2, '4': 1, '5': 8, '10': 'accept'},+ ],+};++/// Descriptor for `ConfirmPairingRequest`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List confirmPairingRequestDescriptor = $convert.base64Decode(+ 'ChVDb25maXJtUGFpcmluZ1JlcXVlc3QSJwoPcGFpcmluZ19zZXNzaW9uGAEgASgJUg5wYWlyaW'+ '5nU2Vzc2lvbhIWCgZhY2NlcHQYAiABKAhSBmFjY2VwdA==');++@$core.Deprecated('Use unpairRequestDescriptor instead')+const UnpairRequest$json = {+ '1': 'UnpairRequest',+ '2': [+ {'1': 'device_id', '3': 1, '4': 1, '5': 9, '10': 'deviceId'},+ ],+};++/// Descriptor for `UnpairRequest`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List unpairRequestDescriptor = $convert.base64Decode(+ 'Cg1VbnBhaXJSZXF1ZXN0EhsKCWRldmljZV9pZBgBIAEoCVIIZGV2aWNlSWQ=');++@$core.Deprecated('Use configDescriptor instead')+const Config$json = {+ '1': 'Config',+ '2': [+ {+ '1': 'auto_sync_threshold_bytes',+ '3': 1,+ '4': 1,+ '5': 3,+ '10': 'autoSyncThresholdBytes'+ },+ {+ '1': 'history_ttl_seconds',+ '3': 2,+ '4': 1,+ '5': 3,+ '10': 'historyTtlSeconds'+ },+ {'1': 'cache_ttl_seconds', '3': 3, '4': 1, '5': 3, '10': 'cacheTtlSeconds'},+ {'1': 'sync_text', '3': 4, '4': 1, '5': 8, '10': 'syncText'},+ {'1': 'sync_html', '3': 5, '4': 1, '5': 8, '10': 'syncHtml'},+ {'1': 'sync_image', '3': 6, '4': 1, '5': 8, '10': 'syncImage'},+ {'1': 'sync_file', '3': 7, '4': 1, '5': 8, '10': 'syncFile'},+ {+ '1': 'auto_apply_to_clipboard',+ '3': 8,+ '4': 1,+ '5': 8,+ '10': 'autoApplyToClipboard'+ },+ {'1': 'launch_at_login', '3': 9, '4': 1, '5': 8, '10': 'launchAtLogin'},+ {'1': 'device_name', '3': 10, '4': 1, '5': 9, '10': 'deviceName'},+ {'1': 'signaling_url', '3': 11, '4': 1, '5': 9, '10': 'signalingUrl'},+ ],+};++/// Descriptor for `Config`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List configDescriptor = $convert.base64Decode(+ 'CgZDb25maWcSOQoZYXV0b19zeW5jX3RocmVzaG9sZF9ieXRlcxgBIAEoA1IWYXV0b1N5bmNUaH'+ 'Jlc2hvbGRCeXRlcxIuChNoaXN0b3J5X3R0bF9zZWNvbmRzGAIgASgDUhFoaXN0b3J5VHRsU2Vj'+ 'b25kcxIqChFjYWNoZV90dGxfc2Vjb25kcxgDIAEoA1IPY2FjaGVUdGxTZWNvbmRzEhsKCXN5bm'+ 'NfdGV4dBgEIAEoCFIIc3luY1RleHQSGwoJc3luY19odG1sGAUgASgIUghzeW5jSHRtbBIdCgpz'+ 'eW5jX2ltYWdlGAYgASgIUglzeW5jSW1hZ2USGwoJc3luY19maWxlGAcgASgIUghzeW5jRmlsZR'+ 'I1ChdhdXRvX2FwcGx5X3RvX2NsaXBib2FyZBgIIAEoCFIUYXV0b0FwcGx5VG9DbGlwYm9hcmQS'+ 'JgoPbGF1bmNoX2F0X2xvZ2luGAkgASgIUg1sYXVuY2hBdExvZ2luEh8KC2RldmljZV9uYW1lGA'+ 'ogASgJUgpkZXZpY2VOYW1lEiMKDXNpZ25hbGluZ191cmwYCyABKAlSDHNpZ25hbGluZ1VybA==');++@$core.Deprecated('Use statusDescriptor instead')+const Status$json = {+ '1': 'Status',+ '2': [+ {'1': 'device_id', '3': 1, '4': 1, '5': 9, '10': 'deviceId'},+ {'1': 'device_name', '3': 2, '4': 1, '5': 9, '10': 'deviceName'},+ {+ '1': 'signaling_connected',+ '3': 3,+ '4': 1,+ '5': 8,+ '10': 'signalingConnected'+ },+ {+ '1': 'clipboard_permission',+ '3': 4,+ '4': 1,+ '5': 14,+ '6': '.copysync.v1.ClipboardPermission',+ '10': 'clipboardPermission'+ },+ {'1': 'cache_bytes_used', '3': 5, '4': 1, '5': 3, '10': 'cacheBytesUsed'},+ {'1': 'peers_online', '3': 6, '4': 1, '5': 5, '10': 'peersOnline'},+ {'1': 'version', '3': 7, '4': 1, '5': 9, '10': 'version'},+ ],+};++/// Descriptor for `Status`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List statusDescriptor = $convert.base64Decode(+ 'CgZTdGF0dXMSGwoJZGV2aWNlX2lkGAEgASgJUghkZXZpY2VJZBIfCgtkZXZpY2VfbmFtZRgCIA'+ 'EoCVIKZGV2aWNlTmFtZRIvChNzaWduYWxpbmdfY29ubmVjdGVkGAMgASgIUhJzaWduYWxpbmdD'+ 'b25uZWN0ZWQSUwoUY2xpcGJvYXJkX3Blcm1pc3Npb24YBCABKA4yIC5jb3B5c3luYy52MS5DbG'+ 'lwYm9hcmRQZXJtaXNzaW9uUhNjbGlwYm9hcmRQZXJtaXNzaW9uEigKEGNhY2hlX2J5dGVzX3Vz'+ 'ZWQYBSABKANSDmNhY2hlQnl0ZXNVc2VkEiEKDHBlZXJzX29ubGluZRgGIAEoBVILcGVlcnNPbm'+ 'xpbmUSGAoHdmVyc2lvbhgHIAEoCVIHdmVyc2lvbg==');diff --git a/ui/lib/gen/copysync/v1/wire.pb.dart b/ui/lib/gen/copysync/v1/wire.pb.dartnew file mode 100644index 0000000..19a5468--- /dev/null+++ b/ui/lib/gen/copysync/v1/wire.pb.dart@@ -0,0 +1,2416 @@+// This is a generated file - do not edit.+//+// Generated from copysync/v1/wire.proto.++// @dart = 3.3++// ignore_for_file: annotate_overrides, camel_case_types, comment_references+// ignore_for_file: constant_identifier_names+// ignore_for_file: curly_braces_in_flow_control_structures+// ignore_for_file: deprecated_member_use_from_same_package, library_prefixes+// ignore_for_file: non_constant_identifier_names, prefer_relative_imports++import 'dart:core' as $core;++import 'package:fixnum/fixnum.dart' as $fixnum;+import 'package:protobuf/protobuf.dart' as $pb;++import 'daemon.pb.dart' as $0;+import 'wire.pbenum.dart';++export 'package:protobuf/protobuf.dart' show GeneratedMessageGenericExtensions;++export 'wire.pbenum.dart';++/// 经服务器转发的消息一律包一层签名。接收方用配对时存下的+/// 对端公钥验签,服务器无法伪造。+class Signed extends $pb.GeneratedMessage {+ factory Signed({+ $core.List<$core.int>? payload,+ $core.List<$core.int>? signature,+ $core.String? fromDeviceId,+ }) {+ final result = Signed._();+ if (payload != null) result.payload = payload;+ if (signature != null) result.signature = signature;+ if (fromDeviceId != null) result.fromDeviceId = fromDeviceId;+ return result;+ }++ Signed._();++ factory Signed.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ Signed()..mergeFromBuffer(data, registry);+ factory Signed.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ Signed()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'Signed',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: Signed.$_createMessage)+ ..a<$core.List<$core.int>>(+ 1, _omitFieldNames ? '' : 'payload', $pb.PbFieldType.OY)+ ..a<$core.List<$core.int>>(+ 2, _omitFieldNames ? '' : 'signature', $pb.PbFieldType.OY)+ ..aOS(3, _omitFieldNames ? '' : 'fromDeviceId')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ Signed clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ Signed copyWith(void Function(Signed) updates) =>+ super.copyWith((message) => updates(message as Signed)) as Signed;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use Signed() / Signed.new instead')+ static Signed create() => Signed._();+ static $pb.GeneratedMessage $_createMessage() => Signed._();+ @$core.override+ Signed createEmptyInstance() => Signed._();+ @$core.pragma('dart2js:noInline')+ static Signed getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<Signed>(Signed.$_createMessage);+ static Signed? _defaultInstance;++ @$pb.TagNumber(1)+ $core.List<$core.int> get payload => $_getN(0);+ @$pb.TagNumber(1)+ set payload($core.List<$core.int> value) => $_setBytes(0, value);+ @$pb.TagNumber(1)+ $core.bool hasPayload() => $_has(0);+ @$pb.TagNumber(1)+ void clearPayload() => $_clearField(1);++ @$pb.TagNumber(2)+ $core.List<$core.int> get signature => $_getN(1);+ @$pb.TagNumber(2)+ set signature($core.List<$core.int> value) => $_setBytes(1, value);+ @$pb.TagNumber(2)+ $core.bool hasSignature() => $_has(1);+ @$pb.TagNumber(2)+ void clearSignature() => $_clearField(2);++ @$pb.TagNumber(3)+ $core.String get fromDeviceId => $_getSZ(2);+ @$pb.TagNumber(3)+ set fromDeviceId($core.String value) => $_setString(2, value);+ @$pb.TagNumber(3)+ $core.bool hasFromDeviceId() => $_has(2);+ @$pb.TagNumber(3)+ void clearFromDeviceId() => $_clearField(3);+}++enum SignalMessage_Payload { offer, answer, candidate, ping, notSet }++class SignalMessage extends $pb.GeneratedMessage {+ factory SignalMessage({+ $fixnum.Int64? timestampUnix,+ $core.List<$core.int>? nonce,+ $core.String? toDeviceId,+ SdpOffer? offer,+ SdpAnswer? answer,+ IceCandidate? candidate,+ Ping? ping,+ }) {+ final result = SignalMessage._();+ if (timestampUnix != null) result.timestampUnix = timestampUnix;+ if (nonce != null) result.nonce = nonce;+ if (toDeviceId != null) result.toDeviceId = toDeviceId;+ if (offer != null) result.offer = offer;+ if (answer != null) result.answer = answer;+ if (candidate != null) result.candidate = candidate;+ if (ping != null) result.ping = ping;+ return result;+ }++ SignalMessage._();++ factory SignalMessage.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ SignalMessage()..mergeFromBuffer(data, registry);+ factory SignalMessage.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ SignalMessage()..mergeFromJson(json, registry);++ static const $core.Map<$core.int, SignalMessage_Payload>+ _SignalMessage_PayloadByTag = {+ 10: SignalMessage_Payload.offer,+ 11: SignalMessage_Payload.answer,+ 12: SignalMessage_Payload.candidate,+ 13: SignalMessage_Payload.ping,+ 0: SignalMessage_Payload.notSet+ };+ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'SignalMessage',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: SignalMessage.$_createMessage)+ ..oo(0, [10, 11, 12, 13])+ ..aInt64(1, _omitFieldNames ? '' : 'timestampUnix')+ ..a<$core.List<$core.int>>(+ 2, _omitFieldNames ? '' : 'nonce', $pb.PbFieldType.OY)+ ..aOS(3, _omitFieldNames ? '' : 'toDeviceId')+ ..aOM<SdpOffer>(10, _omitFieldNames ? '' : 'offer',+ subBuilder: SdpOffer.$_createMessage)+ ..aOM<SdpAnswer>(11, _omitFieldNames ? '' : 'answer',+ subBuilder: SdpAnswer.$_createMessage)+ ..aOM<IceCandidate>(12, _omitFieldNames ? '' : 'candidate',+ subBuilder: IceCandidate.$_createMessage)+ ..aOM<Ping>(13, _omitFieldNames ? '' : 'ping',+ subBuilder: Ping.$_createMessage)+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ SignalMessage clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ SignalMessage copyWith(void Function(SignalMessage) updates) =>+ super.copyWith((message) => updates(message as SignalMessage))+ as SignalMessage;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use SignalMessage() / SignalMessage.new instead')+ static SignalMessage create() => SignalMessage._();+ static $pb.GeneratedMessage $_createMessage() => SignalMessage._();+ @$core.override+ SignalMessage createEmptyInstance() => SignalMessage._();+ @$core.pragma('dart2js:noInline')+ static SignalMessage getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<SignalMessage>(+ SignalMessage.$_createMessage);+ static SignalMessage? _defaultInstance;++ @$pb.TagNumber(10)+ @$pb.TagNumber(11)+ @$pb.TagNumber(12)+ @$pb.TagNumber(13)+ SignalMessage_Payload whichPayload() =>+ _SignalMessage_PayloadByTag[$_whichOneof(0)]!;+ @$pb.TagNumber(10)+ @$pb.TagNumber(11)+ @$pb.TagNumber(12)+ @$pb.TagNumber(13)+ void clearPayload() => $_clearField($_whichOneof(0));++ /// 防重放:接收方拒绝时间戳过旧或 nonce 重复的消息+ @$pb.TagNumber(1)+ $fixnum.Int64 get timestampUnix => $_getI64(0);+ @$pb.TagNumber(1)+ set timestampUnix($fixnum.Int64 value) => $_setInt64(0, value);+ @$pb.TagNumber(1)+ $core.bool hasTimestampUnix() => $_has(0);+ @$pb.TagNumber(1)+ void clearTimestampUnix() => $_clearField(1);++ @$pb.TagNumber(2)+ $core.List<$core.int> get nonce => $_getN(1);+ @$pb.TagNumber(2)+ set nonce($core.List<$core.int> value) => $_setBytes(1, value);+ @$pb.TagNumber(2)+ $core.bool hasNonce() => $_has(1);+ @$pb.TagNumber(2)+ void clearNonce() => $_clearField(2);++ @$pb.TagNumber(3)+ $core.String get toDeviceId => $_getSZ(2);+ @$pb.TagNumber(3)+ set toDeviceId($core.String value) => $_setString(2, value);+ @$pb.TagNumber(3)+ $core.bool hasToDeviceId() => $_has(2);+ @$pb.TagNumber(3)+ void clearToDeviceId() => $_clearField(3);++ @$pb.TagNumber(10)+ SdpOffer get offer => $_getN(3);+ @$pb.TagNumber(10)+ set offer(SdpOffer value) => $_setField(10, value);+ @$pb.TagNumber(10)+ $core.bool hasOffer() => $_has(3);+ @$pb.TagNumber(10)+ void clearOffer() => $_clearField(10);+ @$pb.TagNumber(10)+ SdpOffer ensureOffer() => $_ensure(3);++ @$pb.TagNumber(11)+ SdpAnswer get answer => $_getN(4);+ @$pb.TagNumber(11)+ set answer(SdpAnswer value) => $_setField(11, value);+ @$pb.TagNumber(11)+ $core.bool hasAnswer() => $_has(4);+ @$pb.TagNumber(11)+ void clearAnswer() => $_clearField(11);+ @$pb.TagNumber(11)+ SdpAnswer ensureAnswer() => $_ensure(4);++ @$pb.TagNumber(12)+ IceCandidate get candidate => $_getN(5);+ @$pb.TagNumber(12)+ set candidate(IceCandidate value) => $_setField(12, value);+ @$pb.TagNumber(12)+ $core.bool hasCandidate() => $_has(5);+ @$pb.TagNumber(12)+ void clearCandidate() => $_clearField(12);+ @$pb.TagNumber(12)+ IceCandidate ensureCandidate() => $_ensure(5);++ @$pb.TagNumber(13)+ Ping get ping => $_getN(6);+ @$pb.TagNumber(13)+ set ping(Ping value) => $_setField(13, value);+ @$pb.TagNumber(13)+ $core.bool hasPing() => $_has(6);+ @$pb.TagNumber(13)+ void clearPing() => $_clearField(13);+ @$pb.TagNumber(13)+ Ping ensurePing() => $_ensure(6);+}++class SdpOffer extends $pb.GeneratedMessage {+ factory SdpOffer({+ $core.String? sdp,+ $core.String? dtlsFingerprint,+ }) {+ final result = SdpOffer._();+ if (sdp != null) result.sdp = sdp;+ if (dtlsFingerprint != null) result.dtlsFingerprint = dtlsFingerprint;+ return result;+ }++ SdpOffer._();++ factory SdpOffer.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ SdpOffer()..mergeFromBuffer(data, registry);+ factory SdpOffer.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ SdpOffer()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'SdpOffer',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: SdpOffer.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'sdp')+ ..aOS(2, _omitFieldNames ? '' : 'dtlsFingerprint')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ SdpOffer clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ SdpOffer copyWith(void Function(SdpOffer) updates) =>+ super.copyWith((message) => updates(message as SdpOffer)) as SdpOffer;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use SdpOffer() / SdpOffer.new instead')+ static SdpOffer create() => SdpOffer._();+ static $pb.GeneratedMessage $_createMessage() => SdpOffer._();+ @$core.override+ SdpOffer createEmptyInstance() => SdpOffer._();+ @$core.pragma('dart2js:noInline')+ static SdpOffer getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<SdpOffer>(SdpOffer.$_createMessage);+ static SdpOffer? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get sdp => $_getSZ(0);+ @$pb.TagNumber(1)+ set sdp($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasSdp() => $_has(0);+ @$pb.TagNumber(1)+ void clearSdp() => $_clearField(1);++ /// DTLS 证书指纹。经签名传输,杜绝信令服务器中间人攻击——+ /// 这是 P2P 通道真正的安全锚点。+ @$pb.TagNumber(2)+ $core.String get dtlsFingerprint => $_getSZ(1);+ @$pb.TagNumber(2)+ set dtlsFingerprint($core.String value) => $_setString(1, value);+ @$pb.TagNumber(2)+ $core.bool hasDtlsFingerprint() => $_has(1);+ @$pb.TagNumber(2)+ void clearDtlsFingerprint() => $_clearField(2);+}++class SdpAnswer extends $pb.GeneratedMessage {+ factory SdpAnswer({+ $core.String? sdp,+ $core.String? dtlsFingerprint,+ }) {+ final result = SdpAnswer._();+ if (sdp != null) result.sdp = sdp;+ if (dtlsFingerprint != null) result.dtlsFingerprint = dtlsFingerprint;+ return result;+ }++ SdpAnswer._();++ factory SdpAnswer.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ SdpAnswer()..mergeFromBuffer(data, registry);+ factory SdpAnswer.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ SdpAnswer()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'SdpAnswer',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: SdpAnswer.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'sdp')+ ..aOS(2, _omitFieldNames ? '' : 'dtlsFingerprint')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ SdpAnswer clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ SdpAnswer copyWith(void Function(SdpAnswer) updates) =>+ super.copyWith((message) => updates(message as SdpAnswer)) as SdpAnswer;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use SdpAnswer() / SdpAnswer.new instead')+ static SdpAnswer create() => SdpAnswer._();+ static $pb.GeneratedMessage $_createMessage() => SdpAnswer._();+ @$core.override+ SdpAnswer createEmptyInstance() => SdpAnswer._();+ @$core.pragma('dart2js:noInline')+ static SdpAnswer getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<SdpAnswer>(SdpAnswer.$_createMessage);+ static SdpAnswer? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get sdp => $_getSZ(0);+ @$pb.TagNumber(1)+ set sdp($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasSdp() => $_has(0);+ @$pb.TagNumber(1)+ void clearSdp() => $_clearField(1);++ @$pb.TagNumber(2)+ $core.String get dtlsFingerprint => $_getSZ(1);+ @$pb.TagNumber(2)+ set dtlsFingerprint($core.String value) => $_setString(1, value);+ @$pb.TagNumber(2)+ $core.bool hasDtlsFingerprint() => $_has(1);+ @$pb.TagNumber(2)+ void clearDtlsFingerprint() => $_clearField(2);+}++class IceCandidate extends $pb.GeneratedMessage {+ factory IceCandidate({+ $core.String? candidate,+ $core.String? sdpMid,+ $core.int? sdpMlineIndex,+ }) {+ final result = IceCandidate._();+ if (candidate != null) result.candidate = candidate;+ if (sdpMid != null) result.sdpMid = sdpMid;+ if (sdpMlineIndex != null) result.sdpMlineIndex = sdpMlineIndex;+ return result;+ }++ IceCandidate._();++ factory IceCandidate.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ IceCandidate()..mergeFromBuffer(data, registry);+ factory IceCandidate.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ IceCandidate()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'IceCandidate',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: IceCandidate.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'candidate')+ ..aOS(2, _omitFieldNames ? '' : 'sdpMid')+ ..aI(3, _omitFieldNames ? '' : 'sdpMlineIndex',+ fieldType: $pb.PbFieldType.OU3)+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ IceCandidate clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ IceCandidate copyWith(void Function(IceCandidate) updates) =>+ super.copyWith((message) => updates(message as IceCandidate))+ as IceCandidate;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use IceCandidate() / IceCandidate.new instead')+ static IceCandidate create() => IceCandidate._();+ static $pb.GeneratedMessage $_createMessage() => IceCandidate._();+ @$core.override+ IceCandidate createEmptyInstance() => IceCandidate._();+ @$core.pragma('dart2js:noInline')+ static IceCandidate getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<IceCandidate>(+ IceCandidate.$_createMessage);+ static IceCandidate? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get candidate => $_getSZ(0);+ @$pb.TagNumber(1)+ set candidate($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasCandidate() => $_has(0);+ @$pb.TagNumber(1)+ void clearCandidate() => $_clearField(1);++ @$pb.TagNumber(2)+ $core.String get sdpMid => $_getSZ(1);+ @$pb.TagNumber(2)+ set sdpMid($core.String value) => $_setString(1, value);+ @$pb.TagNumber(2)+ $core.bool hasSdpMid() => $_has(1);+ @$pb.TagNumber(2)+ void clearSdpMid() => $_clearField(2);++ @$pb.TagNumber(3)+ $core.int get sdpMlineIndex => $_getIZ(2);+ @$pb.TagNumber(3)+ set sdpMlineIndex($core.int value) => $_setUnsignedInt32(2, value);+ @$pb.TagNumber(3)+ $core.bool hasSdpMlineIndex() => $_has(2);+ @$pb.TagNumber(3)+ void clearSdpMlineIndex() => $_clearField(3);+}++class Ping extends $pb.GeneratedMessage {+ factory Ping({+ $fixnum.Int64? sentAtUnix,+ }) {+ final result = Ping._();+ if (sentAtUnix != null) result.sentAtUnix = sentAtUnix;+ return result;+ }++ Ping._();++ factory Ping.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ Ping()..mergeFromBuffer(data, registry);+ factory Ping.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ Ping()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'Ping',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: Ping.$_createMessage)+ ..aInt64(1, _omitFieldNames ? '' : 'sentAtUnix')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ Ping clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ Ping copyWith(void Function(Ping) updates) =>+ super.copyWith((message) => updates(message as Ping)) as Ping;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use Ping() / Ping.new instead')+ static Ping create() => Ping._();+ static $pb.GeneratedMessage $_createMessage() => Ping._();+ @$core.override+ Ping createEmptyInstance() => Ping._();+ @$core.pragma('dart2js:noInline')+ static Ping getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<Ping>(Ping.$_createMessage);+ static Ping? _defaultInstance;++ @$pb.TagNumber(1)+ $fixnum.Int64 get sentAtUnix => $_getI64(0);+ @$pb.TagNumber(1)+ set sentAtUnix($fixnum.Int64 value) => $_setInt64(0, value);+ @$pb.TagNumber(1)+ $core.bool hasSentAtUnix() => $_has(0);+ @$pb.TagNumber(1)+ void clearSentAtUnix() => $_clearField(1);+}++class ClientHello extends $pb.GeneratedMessage {+ factory ClientHello({+ $core.String? deviceId,+ $core.String? deviceName,+ $core.String? platform,+ $core.List<$core.int>? publicKey,+ $core.List<$core.int>? signature,+ $core.Iterable<$core.String>? pairedDeviceIds,+ }) {+ final result = ClientHello._();+ if (deviceId != null) result.deviceId = deviceId;+ if (deviceName != null) result.deviceName = deviceName;+ if (platform != null) result.platform = platform;+ if (publicKey != null) result.publicKey = publicKey;+ if (signature != null) result.signature = signature;+ if (pairedDeviceIds != null) result.pairedDeviceIds.addAll(pairedDeviceIds);+ return result;+ }++ ClientHello._();++ factory ClientHello.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ClientHello()..mergeFromBuffer(data, registry);+ factory ClientHello.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ClientHello()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'ClientHello',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: ClientHello.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'deviceId')+ ..aOS(2, _omitFieldNames ? '' : 'deviceName')+ ..aOS(3, _omitFieldNames ? '' : 'platform')+ ..a<$core.List<$core.int>>(+ 4, _omitFieldNames ? '' : 'publicKey', $pb.PbFieldType.OY)+ ..a<$core.List<$core.int>>(+ 5, _omitFieldNames ? '' : 'signature', $pb.PbFieldType.OY)+ ..pPS(6, _omitFieldNames ? '' : 'pairedDeviceIds')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ClientHello clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ClientHello copyWith(void Function(ClientHello) updates) =>+ super.copyWith((message) => updates(message as ClientHello))+ as ClientHello;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use ClientHello() / ClientHello.new instead')+ static ClientHello create() => ClientHello._();+ static $pb.GeneratedMessage $_createMessage() => ClientHello._();+ @$core.override+ ClientHello createEmptyInstance() => ClientHello._();+ @$core.pragma('dart2js:noInline')+ static ClientHello getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<ClientHello>(+ ClientHello.$_createMessage);+ static ClientHello? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get deviceId => $_getSZ(0);+ @$pb.TagNumber(1)+ set deviceId($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasDeviceId() => $_has(0);+ @$pb.TagNumber(1)+ void clearDeviceId() => $_clearField(1);++ @$pb.TagNumber(2)+ $core.String get deviceName => $_getSZ(1);+ @$pb.TagNumber(2)+ set deviceName($core.String value) => $_setString(1, value);+ @$pb.TagNumber(2)+ $core.bool hasDeviceName() => $_has(1);+ @$pb.TagNumber(2)+ void clearDeviceName() => $_clearField(2);++ @$pb.TagNumber(3)+ $core.String get platform => $_getSZ(2);+ @$pb.TagNumber(3)+ set platform($core.String value) => $_setString(2, value);+ @$pb.TagNumber(3)+ $core.bool hasPlatform() => $_has(2);+ @$pb.TagNumber(3)+ void clearPlatform() => $_clearField(3);++ @$pb.TagNumber(4)+ $core.List<$core.int> get publicKey => $_getN(3);+ @$pb.TagNumber(4)+ set publicKey($core.List<$core.int> value) => $_setBytes(3, value);+ @$pb.TagNumber(4)+ $core.bool hasPublicKey() => $_has(3);+ @$pb.TagNumber(4)+ void clearPublicKey() => $_clearField(4);++ @$pb.TagNumber(5)+ $core.List<$core.int> get signature => $_getN(4);+ @$pb.TagNumber(5)+ set signature($core.List<$core.int> value) => $_setBytes(4, value);+ @$pb.TagNumber(5)+ $core.bool hasSignature() => $_has(4);+ @$pb.TagNumber(5)+ void clearSignature() => $_clearField(5);++ @$pb.TagNumber(6)+ $pb.PbList<$core.String> get pairedDeviceIds => $_getList(5);+}++class ServerHello extends $pb.GeneratedMessage {+ factory ServerHello({+ $core.List<$core.int>? challenge,+ $core.Iterable<IceServer>? iceServers,+ $fixnum.Int64? serverTimeUnix,+ }) {+ final result = ServerHello._();+ if (challenge != null) result.challenge = challenge;+ if (iceServers != null) result.iceServers.addAll(iceServers);+ if (serverTimeUnix != null) result.serverTimeUnix = serverTimeUnix;+ return result;+ }++ ServerHello._();++ factory ServerHello.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ServerHello()..mergeFromBuffer(data, registry);+ factory ServerHello.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ServerHello()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'ServerHello',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: ServerHello.$_createMessage)+ ..a<$core.List<$core.int>>(+ 1, _omitFieldNames ? '' : 'challenge', $pb.PbFieldType.OY)+ ..pPM<IceServer>(2, _omitFieldNames ? '' : 'iceServers',+ subBuilder: IceServer.$_createMessage)+ ..aInt64(3, _omitFieldNames ? '' : 'serverTimeUnix')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ServerHello clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ServerHello copyWith(void Function(ServerHello) updates) =>+ super.copyWith((message) => updates(message as ServerHello))+ as ServerHello;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use ServerHello() / ServerHello.new instead')+ static ServerHello create() => ServerHello._();+ static $pb.GeneratedMessage $_createMessage() => ServerHello._();+ @$core.override+ ServerHello createEmptyInstance() => ServerHello._();+ @$core.pragma('dart2js:noInline')+ static ServerHello getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<ServerHello>(+ ServerHello.$_createMessage);+ static ServerHello? _defaultInstance;++ @$pb.TagNumber(1)+ $core.List<$core.int> get challenge => $_getN(0);+ @$pb.TagNumber(1)+ set challenge($core.List<$core.int> value) => $_setBytes(0, value);+ @$pb.TagNumber(1)+ $core.bool hasChallenge() => $_has(0);+ @$pb.TagNumber(1)+ void clearChallenge() => $_clearField(1);++ @$pb.TagNumber(2)+ $pb.PbList<IceServer> get iceServers => $_getList(1);++ @$pb.TagNumber(3)+ $fixnum.Int64 get serverTimeUnix => $_getI64(2);+ @$pb.TagNumber(3)+ set serverTimeUnix($fixnum.Int64 value) => $_setInt64(2, value);+ @$pb.TagNumber(3)+ $core.bool hasServerTimeUnix() => $_has(2);+ @$pb.TagNumber(3)+ void clearServerTimeUnix() => $_clearField(3);+}++class IceServer extends $pb.GeneratedMessage {+ factory IceServer({+ $core.Iterable<$core.String>? urls,+ $core.String? username,+ $core.String? credential,+ $fixnum.Int64? expiresAtUnix,+ }) {+ final result = IceServer._();+ if (urls != null) result.urls.addAll(urls);+ if (username != null) result.username = username;+ if (credential != null) result.credential = credential;+ if (expiresAtUnix != null) result.expiresAtUnix = expiresAtUnix;+ return result;+ }++ IceServer._();++ factory IceServer.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ IceServer()..mergeFromBuffer(data, registry);+ factory IceServer.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ IceServer()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'IceServer',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: IceServer.$_createMessage)+ ..pPS(1, _omitFieldNames ? '' : 'urls')+ ..aOS(2, _omitFieldNames ? '' : 'username')+ ..aOS(3, _omitFieldNames ? '' : 'credential')+ ..aInt64(4, _omitFieldNames ? '' : 'expiresAtUnix')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ IceServer clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ IceServer copyWith(void Function(IceServer) updates) =>+ super.copyWith((message) => updates(message as IceServer)) as IceServer;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use IceServer() / IceServer.new instead')+ static IceServer create() => IceServer._();+ static $pb.GeneratedMessage $_createMessage() => IceServer._();+ @$core.override+ IceServer createEmptyInstance() => IceServer._();+ @$core.pragma('dart2js:noInline')+ static IceServer getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<IceServer>(IceServer.$_createMessage);+ static IceServer? _defaultInstance;++ @$pb.TagNumber(1)+ $pb.PbList<$core.String> get urls => $_getList(0);++ @$pb.TagNumber(2)+ $core.String get username => $_getSZ(1);+ @$pb.TagNumber(2)+ set username($core.String value) => $_setString(1, value);+ @$pb.TagNumber(2)+ $core.bool hasUsername() => $_has(1);+ @$pb.TagNumber(2)+ void clearUsername() => $_clearField(2);++ @$pb.TagNumber(3)+ $core.String get credential => $_getSZ(2);+ @$pb.TagNumber(3)+ set credential($core.String value) => $_setString(2, value);+ @$pb.TagNumber(3)+ $core.bool hasCredential() => $_has(2);+ @$pb.TagNumber(3)+ void clearCredential() => $_clearField(3);++ @$pb.TagNumber(4)+ $fixnum.Int64 get expiresAtUnix => $_getI64(3);+ @$pb.TagNumber(4)+ set expiresAtUnix($fixnum.Int64 value) => $_setInt64(3, value);+ @$pb.TagNumber(4)+ $core.bool hasExpiresAtUnix() => $_has(3);+ @$pb.TagNumber(4)+ void clearExpiresAtUnix() => $_clearField(4);+}++class PeerPresence extends $pb.GeneratedMessage {+ factory PeerPresence({+ $core.String? deviceId,+ $core.bool? online,+ }) {+ final result = PeerPresence._();+ if (deviceId != null) result.deviceId = deviceId;+ if (online != null) result.online = online;+ return result;+ }++ PeerPresence._();++ factory PeerPresence.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ PeerPresence()..mergeFromBuffer(data, registry);+ factory PeerPresence.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ PeerPresence()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'PeerPresence',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: PeerPresence.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'deviceId')+ ..aOB(2, _omitFieldNames ? '' : 'online')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ PeerPresence clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ PeerPresence copyWith(void Function(PeerPresence) updates) =>+ super.copyWith((message) => updates(message as PeerPresence))+ as PeerPresence;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use PeerPresence() / PeerPresence.new instead')+ static PeerPresence create() => PeerPresence._();+ static $pb.GeneratedMessage $_createMessage() => PeerPresence._();+ @$core.override+ PeerPresence createEmptyInstance() => PeerPresence._();+ @$core.pragma('dart2js:noInline')+ static PeerPresence getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<PeerPresence>(+ PeerPresence.$_createMessage);+ static PeerPresence? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get deviceId => $_getSZ(0);+ @$pb.TagNumber(1)+ set deviceId($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasDeviceId() => $_has(0);+ @$pb.TagNumber(1)+ void clearDeviceId() => $_clearField(1);++ @$pb.TagNumber(2)+ $core.bool get online => $_getBF(1);+ @$pb.TagNumber(2)+ set online($core.bool value) => $_setBool(1, value);+ @$pb.TagNumber(2)+ $core.bool hasOnline() => $_has(1);+ @$pb.TagNumber(2)+ void clearOnline() => $_clearField(2);+}++class PairingCreateRequest extends $pb.GeneratedMessage {+ factory PairingCreateRequest({+ $core.String? deviceName,+ $core.List<$core.int>? publicKey,+ }) {+ final result = PairingCreateRequest._();+ if (deviceName != null) result.deviceName = deviceName;+ if (publicKey != null) result.publicKey = publicKey;+ return result;+ }++ PairingCreateRequest._();++ factory PairingCreateRequest.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ PairingCreateRequest()..mergeFromBuffer(data, registry);+ factory PairingCreateRequest.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ PairingCreateRequest()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'PairingCreateRequest',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: PairingCreateRequest.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'deviceName')+ ..a<$core.List<$core.int>>(+ 2, _omitFieldNames ? '' : 'publicKey', $pb.PbFieldType.OY)+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ PairingCreateRequest clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ PairingCreateRequest copyWith(void Function(PairingCreateRequest) updates) =>+ super.copyWith((message) => updates(message as PairingCreateRequest))+ as PairingCreateRequest;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated(+ 'Use PairingCreateRequest() / PairingCreateRequest.new instead')+ static PairingCreateRequest create() => PairingCreateRequest._();+ static $pb.GeneratedMessage $_createMessage() => PairingCreateRequest._();+ @$core.override+ PairingCreateRequest createEmptyInstance() => PairingCreateRequest._();+ @$core.pragma('dart2js:noInline')+ static PairingCreateRequest getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<PairingCreateRequest>(+ PairingCreateRequest.$_createMessage);+ static PairingCreateRequest? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get deviceName => $_getSZ(0);+ @$pb.TagNumber(1)+ set deviceName($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasDeviceName() => $_has(0);+ @$pb.TagNumber(1)+ void clearDeviceName() => $_clearField(1);++ @$pb.TagNumber(2)+ $core.List<$core.int> get publicKey => $_getN(1);+ @$pb.TagNumber(2)+ set publicKey($core.List<$core.int> value) => $_setBytes(1, value);+ @$pb.TagNumber(2)+ $core.bool hasPublicKey() => $_has(1);+ @$pb.TagNumber(2)+ void clearPublicKey() => $_clearField(2);+}++class PairingCreateResponse extends $pb.GeneratedMessage {+ factory PairingCreateResponse({+ $core.String? code,+ $fixnum.Int64? expiresAtUnix,+ }) {+ final result = PairingCreateResponse._();+ if (code != null) result.code = code;+ if (expiresAtUnix != null) result.expiresAtUnix = expiresAtUnix;+ return result;+ }++ PairingCreateResponse._();++ factory PairingCreateResponse.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ PairingCreateResponse()..mergeFromBuffer(data, registry);+ factory PairingCreateResponse.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ PairingCreateResponse()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'PairingCreateResponse',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: PairingCreateResponse.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'code')+ ..aInt64(2, _omitFieldNames ? '' : 'expiresAtUnix')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ PairingCreateResponse clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ PairingCreateResponse copyWith(+ void Function(PairingCreateResponse) updates) =>+ super.copyWith((message) => updates(message as PairingCreateResponse))+ as PairingCreateResponse;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated(+ 'Use PairingCreateResponse() / PairingCreateResponse.new instead')+ static PairingCreateResponse create() => PairingCreateResponse._();+ static $pb.GeneratedMessage $_createMessage() => PairingCreateResponse._();+ @$core.override+ PairingCreateResponse createEmptyInstance() => PairingCreateResponse._();+ @$core.pragma('dart2js:noInline')+ static PairingCreateResponse getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<PairingCreateResponse>(+ PairingCreateResponse.$_createMessage);+ static PairingCreateResponse? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get code => $_getSZ(0);+ @$pb.TagNumber(1)+ set code($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasCode() => $_has(0);+ @$pb.TagNumber(1)+ void clearCode() => $_clearField(1);++ @$pb.TagNumber(2)+ $fixnum.Int64 get expiresAtUnix => $_getI64(1);+ @$pb.TagNumber(2)+ set expiresAtUnix($fixnum.Int64 value) => $_setInt64(1, value);+ @$pb.TagNumber(2)+ $core.bool hasExpiresAtUnix() => $_has(1);+ @$pb.TagNumber(2)+ void clearExpiresAtUnix() => $_clearField(2);+}++class PairingRedeemRequest extends $pb.GeneratedMessage {+ factory PairingRedeemRequest({+ $core.String? code,+ $core.String? deviceId,+ $core.String? deviceName,+ $core.List<$core.int>? publicKey,+ }) {+ final result = PairingRedeemRequest._();+ if (code != null) result.code = code;+ if (deviceId != null) result.deviceId = deviceId;+ if (deviceName != null) result.deviceName = deviceName;+ if (publicKey != null) result.publicKey = publicKey;+ return result;+ }++ PairingRedeemRequest._();++ factory PairingRedeemRequest.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ PairingRedeemRequest()..mergeFromBuffer(data, registry);+ factory PairingRedeemRequest.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ PairingRedeemRequest()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'PairingRedeemRequest',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: PairingRedeemRequest.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'code')+ ..aOS(2, _omitFieldNames ? '' : 'deviceId')+ ..aOS(3, _omitFieldNames ? '' : 'deviceName')+ ..a<$core.List<$core.int>>(+ 4, _omitFieldNames ? '' : 'publicKey', $pb.PbFieldType.OY)+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ PairingRedeemRequest clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ PairingRedeemRequest copyWith(void Function(PairingRedeemRequest) updates) =>+ super.copyWith((message) => updates(message as PairingRedeemRequest))+ as PairingRedeemRequest;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated(+ 'Use PairingRedeemRequest() / PairingRedeemRequest.new instead')+ static PairingRedeemRequest create() => PairingRedeemRequest._();+ static $pb.GeneratedMessage $_createMessage() => PairingRedeemRequest._();+ @$core.override+ PairingRedeemRequest createEmptyInstance() => PairingRedeemRequest._();+ @$core.pragma('dart2js:noInline')+ static PairingRedeemRequest getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<PairingRedeemRequest>(+ PairingRedeemRequest.$_createMessage);+ static PairingRedeemRequest? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get code => $_getSZ(0);+ @$pb.TagNumber(1)+ set code($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasCode() => $_has(0);+ @$pb.TagNumber(1)+ void clearCode() => $_clearField(1);++ @$pb.TagNumber(2)+ $core.String get deviceId => $_getSZ(1);+ @$pb.TagNumber(2)+ set deviceId($core.String value) => $_setString(1, value);+ @$pb.TagNumber(2)+ $core.bool hasDeviceId() => $_has(1);+ @$pb.TagNumber(2)+ void clearDeviceId() => $_clearField(2);++ @$pb.TagNumber(3)+ $core.String get deviceName => $_getSZ(2);+ @$pb.TagNumber(3)+ set deviceName($core.String value) => $_setString(2, value);+ @$pb.TagNumber(3)+ $core.bool hasDeviceName() => $_has(2);+ @$pb.TagNumber(3)+ void clearDeviceName() => $_clearField(3);++ @$pb.TagNumber(4)+ $core.List<$core.int> get publicKey => $_getN(3);+ @$pb.TagNumber(4)+ set publicKey($core.List<$core.int> value) => $_setBytes(3, value);+ @$pb.TagNumber(4)+ $core.bool hasPublicKey() => $_has(3);+ @$pb.TagNumber(4)+ void clearPublicKey() => $_clearField(4);+}++class PairingRedeemResponse extends $pb.GeneratedMessage {+ factory PairingRedeemResponse({+ $core.String? peerDeviceId,+ $core.String? peerDeviceName,+ $core.String? peerPlatform,+ $core.List<$core.int>? peerPublicKey,+ }) {+ final result = PairingRedeemResponse._();+ if (peerDeviceId != null) result.peerDeviceId = peerDeviceId;+ if (peerDeviceName != null) result.peerDeviceName = peerDeviceName;+ if (peerPlatform != null) result.peerPlatform = peerPlatform;+ if (peerPublicKey != null) result.peerPublicKey = peerPublicKey;+ return result;+ }++ PairingRedeemResponse._();++ factory PairingRedeemResponse.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ PairingRedeemResponse()..mergeFromBuffer(data, registry);+ factory PairingRedeemResponse.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ PairingRedeemResponse()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'PairingRedeemResponse',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: PairingRedeemResponse.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'peerDeviceId')+ ..aOS(2, _omitFieldNames ? '' : 'peerDeviceName')+ ..aOS(3, _omitFieldNames ? '' : 'peerPlatform')+ ..a<$core.List<$core.int>>(+ 4, _omitFieldNames ? '' : 'peerPublicKey', $pb.PbFieldType.OY)+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ PairingRedeemResponse clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ PairingRedeemResponse copyWith(+ void Function(PairingRedeemResponse) updates) =>+ super.copyWith((message) => updates(message as PairingRedeemResponse))+ as PairingRedeemResponse;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated(+ 'Use PairingRedeemResponse() / PairingRedeemResponse.new instead')+ static PairingRedeemResponse create() => PairingRedeemResponse._();+ static $pb.GeneratedMessage $_createMessage() => PairingRedeemResponse._();+ @$core.override+ PairingRedeemResponse createEmptyInstance() => PairingRedeemResponse._();+ @$core.pragma('dart2js:noInline')+ static PairingRedeemResponse getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<PairingRedeemResponse>(+ PairingRedeemResponse.$_createMessage);+ static PairingRedeemResponse? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get peerDeviceId => $_getSZ(0);+ @$pb.TagNumber(1)+ set peerDeviceId($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasPeerDeviceId() => $_has(0);+ @$pb.TagNumber(1)+ void clearPeerDeviceId() => $_clearField(1);++ @$pb.TagNumber(2)+ $core.String get peerDeviceName => $_getSZ(1);+ @$pb.TagNumber(2)+ set peerDeviceName($core.String value) => $_setString(1, value);+ @$pb.TagNumber(2)+ $core.bool hasPeerDeviceName() => $_has(1);+ @$pb.TagNumber(2)+ void clearPeerDeviceName() => $_clearField(2);++ @$pb.TagNumber(3)+ $core.String get peerPlatform => $_getSZ(2);+ @$pb.TagNumber(3)+ set peerPlatform($core.String value) => $_setString(2, value);+ @$pb.TagNumber(3)+ $core.bool hasPeerPlatform() => $_has(2);+ @$pb.TagNumber(3)+ void clearPeerPlatform() => $_clearField(3);++ @$pb.TagNumber(4)+ $core.List<$core.int> get peerPublicKey => $_getN(3);+ @$pb.TagNumber(4)+ set peerPublicKey($core.List<$core.int> value) => $_setBytes(3, value);+ @$pb.TagNumber(4)+ $core.bool hasPeerPublicKey() => $_has(3);+ @$pb.TagNumber(4)+ void clearPeerPublicKey() => $_clearField(4);+}++/// 服务器 → 发起方:有人兑换了你的配对码+class PairingRedeemed extends $pb.GeneratedMessage {+ factory PairingRedeemed({+ $core.String? peerDeviceId,+ $core.String? peerDeviceName,+ $core.String? peerPlatform,+ $core.List<$core.int>? peerPublicKey,+ }) {+ final result = PairingRedeemed._();+ if (peerDeviceId != null) result.peerDeviceId = peerDeviceId;+ if (peerDeviceName != null) result.peerDeviceName = peerDeviceName;+ if (peerPlatform != null) result.peerPlatform = peerPlatform;+ if (peerPublicKey != null) result.peerPublicKey = peerPublicKey;+ return result;+ }++ PairingRedeemed._();++ factory PairingRedeemed.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ PairingRedeemed()..mergeFromBuffer(data, registry);+ factory PairingRedeemed.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ PairingRedeemed()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'PairingRedeemed',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: PairingRedeemed.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'peerDeviceId')+ ..aOS(2, _omitFieldNames ? '' : 'peerDeviceName')+ ..aOS(3, _omitFieldNames ? '' : 'peerPlatform')+ ..a<$core.List<$core.int>>(+ 4, _omitFieldNames ? '' : 'peerPublicKey', $pb.PbFieldType.OY)+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ PairingRedeemed clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ PairingRedeemed copyWith(void Function(PairingRedeemed) updates) =>+ super.copyWith((message) => updates(message as PairingRedeemed))+ as PairingRedeemed;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use PairingRedeemed() / PairingRedeemed.new instead')+ static PairingRedeemed create() => PairingRedeemed._();+ static $pb.GeneratedMessage $_createMessage() => PairingRedeemed._();+ @$core.override+ PairingRedeemed createEmptyInstance() => PairingRedeemed._();+ @$core.pragma('dart2js:noInline')+ static PairingRedeemed getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<PairingRedeemed>(+ PairingRedeemed.$_createMessage);+ static PairingRedeemed? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get peerDeviceId => $_getSZ(0);+ @$pb.TagNumber(1)+ set peerDeviceId($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasPeerDeviceId() => $_has(0);+ @$pb.TagNumber(1)+ void clearPeerDeviceId() => $_clearField(1);++ @$pb.TagNumber(2)+ $core.String get peerDeviceName => $_getSZ(1);+ @$pb.TagNumber(2)+ set peerDeviceName($core.String value) => $_setString(1, value);+ @$pb.TagNumber(2)+ $core.bool hasPeerDeviceName() => $_has(1);+ @$pb.TagNumber(2)+ void clearPeerDeviceName() => $_clearField(2);++ @$pb.TagNumber(3)+ $core.String get peerPlatform => $_getSZ(2);+ @$pb.TagNumber(3)+ set peerPlatform($core.String value) => $_setString(2, value);+ @$pb.TagNumber(3)+ $core.bool hasPeerPlatform() => $_has(2);+ @$pb.TagNumber(3)+ void clearPeerPlatform() => $_clearField(3);++ @$pb.TagNumber(4)+ $core.List<$core.int> get peerPublicKey => $_getN(3);+ @$pb.TagNumber(4)+ set peerPublicKey($core.List<$core.int> value) => $_setBytes(3, value);+ @$pb.TagNumber(4)+ $core.bool hasPeerPublicKey() => $_has(3);+ @$pb.TagNumber(4)+ void clearPeerPublicKey() => $_clearField(4);+}++/// TURN 凭证是按设备签发且有有效期的,因此必须在认证完成后才能下发,+/// 之后也会在临近过期时重新推送。+class IceConfig extends $pb.GeneratedMessage {+ factory IceConfig({+ $core.Iterable<IceServer>? iceServers,+ }) {+ final result = IceConfig._();+ if (iceServers != null) result.iceServers.addAll(iceServers);+ return result;+ }++ IceConfig._();++ factory IceConfig.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ IceConfig()..mergeFromBuffer(data, registry);+ factory IceConfig.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ IceConfig()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'IceConfig',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: IceConfig.$_createMessage)+ ..pPM<IceServer>(1, _omitFieldNames ? '' : 'iceServers',+ subBuilder: IceServer.$_createMessage)+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ IceConfig clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ IceConfig copyWith(void Function(IceConfig) updates) =>+ super.copyWith((message) => updates(message as IceConfig)) as IceConfig;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use IceConfig() / IceConfig.new instead')+ static IceConfig create() => IceConfig._();+ static $pb.GeneratedMessage $_createMessage() => IceConfig._();+ @$core.override+ IceConfig createEmptyInstance() => IceConfig._();+ @$core.pragma('dart2js:noInline')+ static IceConfig getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<IceConfig>(IceConfig.$_createMessage);+ static IceConfig? _defaultInstance;++ @$pb.TagNumber(1)+ $pb.PbList<IceServer> get iceServers => $_getList(0);+}++enum ServerEnvelope_Payload {+ hello,+ forwarded,+ presence,+ pairingCreated,+ pairingRedeemedResult,+ pairingRedeemed,+ error,+ iceConfig,+ notSet+}++/// 客户端 ↔ 服务器的顶层信封+class ServerEnvelope extends $pb.GeneratedMessage {+ factory ServerEnvelope({+ ServerHello? hello,+ Signed? forwarded,+ PeerPresence? presence,+ PairingCreateResponse? pairingCreated,+ PairingRedeemResponse? pairingRedeemedResult,+ PairingRedeemed? pairingRedeemed,+ ServerError? error,+ IceConfig? iceConfig,+ }) {+ final result = ServerEnvelope._();+ if (hello != null) result.hello = hello;+ if (forwarded != null) result.forwarded = forwarded;+ if (presence != null) result.presence = presence;+ if (pairingCreated != null) result.pairingCreated = pairingCreated;+ if (pairingRedeemedResult != null)+ result.pairingRedeemedResult = pairingRedeemedResult;+ if (pairingRedeemed != null) result.pairingRedeemed = pairingRedeemed;+ if (error != null) result.error = error;+ if (iceConfig != null) result.iceConfig = iceConfig;+ return result;+ }++ ServerEnvelope._();++ factory ServerEnvelope.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ServerEnvelope()..mergeFromBuffer(data, registry);+ factory ServerEnvelope.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ServerEnvelope()..mergeFromJson(json, registry);++ static const $core.Map<$core.int, ServerEnvelope_Payload>+ _ServerEnvelope_PayloadByTag = {+ 1: ServerEnvelope_Payload.hello,+ 2: ServerEnvelope_Payload.forwarded,+ 3: ServerEnvelope_Payload.presence,+ 4: ServerEnvelope_Payload.pairingCreated,+ 5: ServerEnvelope_Payload.pairingRedeemedResult,+ 6: ServerEnvelope_Payload.pairingRedeemed,+ 7: ServerEnvelope_Payload.error,+ 8: ServerEnvelope_Payload.iceConfig,+ 0: ServerEnvelope_Payload.notSet+ };+ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'ServerEnvelope',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: ServerEnvelope.$_createMessage)+ ..oo(0, [1, 2, 3, 4, 5, 6, 7, 8])+ ..aOM<ServerHello>(1, _omitFieldNames ? '' : 'hello',+ subBuilder: ServerHello.$_createMessage)+ ..aOM<Signed>(2, _omitFieldNames ? '' : 'forwarded',+ subBuilder: Signed.$_createMessage)+ ..aOM<PeerPresence>(3, _omitFieldNames ? '' : 'presence',+ subBuilder: PeerPresence.$_createMessage)+ ..aOM<PairingCreateResponse>(4, _omitFieldNames ? '' : 'pairingCreated',+ subBuilder: PairingCreateResponse.$_createMessage)+ ..aOM<PairingRedeemResponse>(+ 5, _omitFieldNames ? '' : 'pairingRedeemedResult',+ subBuilder: PairingRedeemResponse.$_createMessage)+ ..aOM<PairingRedeemed>(6, _omitFieldNames ? '' : 'pairingRedeemed',+ subBuilder: PairingRedeemed.$_createMessage)+ ..aOM<ServerError>(7, _omitFieldNames ? '' : 'error',+ subBuilder: ServerError.$_createMessage)+ ..aOM<IceConfig>(8, _omitFieldNames ? '' : 'iceConfig',+ subBuilder: IceConfig.$_createMessage)+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ServerEnvelope clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ServerEnvelope copyWith(void Function(ServerEnvelope) updates) =>+ super.copyWith((message) => updates(message as ServerEnvelope))+ as ServerEnvelope;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use ServerEnvelope() / ServerEnvelope.new instead')+ static ServerEnvelope create() => ServerEnvelope._();+ static $pb.GeneratedMessage $_createMessage() => ServerEnvelope._();+ @$core.override+ ServerEnvelope createEmptyInstance() => ServerEnvelope._();+ @$core.pragma('dart2js:noInline')+ static ServerEnvelope getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<ServerEnvelope>(+ ServerEnvelope.$_createMessage);+ static ServerEnvelope? _defaultInstance;++ @$pb.TagNumber(1)+ @$pb.TagNumber(2)+ @$pb.TagNumber(3)+ @$pb.TagNumber(4)+ @$pb.TagNumber(5)+ @$pb.TagNumber(6)+ @$pb.TagNumber(7)+ @$pb.TagNumber(8)+ ServerEnvelope_Payload whichPayload() =>+ _ServerEnvelope_PayloadByTag[$_whichOneof(0)]!;+ @$pb.TagNumber(1)+ @$pb.TagNumber(2)+ @$pb.TagNumber(3)+ @$pb.TagNumber(4)+ @$pb.TagNumber(5)+ @$pb.TagNumber(6)+ @$pb.TagNumber(7)+ @$pb.TagNumber(8)+ void clearPayload() => $_clearField($_whichOneof(0));++ @$pb.TagNumber(1)+ ServerHello get hello => $_getN(0);+ @$pb.TagNumber(1)+ set hello(ServerHello value) => $_setField(1, value);+ @$pb.TagNumber(1)+ $core.bool hasHello() => $_has(0);+ @$pb.TagNumber(1)+ void clearHello() => $_clearField(1);+ @$pb.TagNumber(1)+ ServerHello ensureHello() => $_ensure(0);++ @$pb.TagNumber(2)+ Signed get forwarded => $_getN(1);+ @$pb.TagNumber(2)+ set forwarded(Signed value) => $_setField(2, value);+ @$pb.TagNumber(2)+ $core.bool hasForwarded() => $_has(1);+ @$pb.TagNumber(2)+ void clearForwarded() => $_clearField(2);+ @$pb.TagNumber(2)+ Signed ensureForwarded() => $_ensure(1);++ @$pb.TagNumber(3)+ PeerPresence get presence => $_getN(2);+ @$pb.TagNumber(3)+ set presence(PeerPresence value) => $_setField(3, value);+ @$pb.TagNumber(3)+ $core.bool hasPresence() => $_has(2);+ @$pb.TagNumber(3)+ void clearPresence() => $_clearField(3);+ @$pb.TagNumber(3)+ PeerPresence ensurePresence() => $_ensure(2);++ @$pb.TagNumber(4)+ PairingCreateResponse get pairingCreated => $_getN(3);+ @$pb.TagNumber(4)+ set pairingCreated(PairingCreateResponse value) => $_setField(4, value);+ @$pb.TagNumber(4)+ $core.bool hasPairingCreated() => $_has(3);+ @$pb.TagNumber(4)+ void clearPairingCreated() => $_clearField(4);+ @$pb.TagNumber(4)+ PairingCreateResponse ensurePairingCreated() => $_ensure(3);++ @$pb.TagNumber(5)+ PairingRedeemResponse get pairingRedeemedResult => $_getN(4);+ @$pb.TagNumber(5)+ set pairingRedeemedResult(PairingRedeemResponse value) =>+ $_setField(5, value);+ @$pb.TagNumber(5)+ $core.bool hasPairingRedeemedResult() => $_has(4);+ @$pb.TagNumber(5)+ void clearPairingRedeemedResult() => $_clearField(5);+ @$pb.TagNumber(5)+ PairingRedeemResponse ensurePairingRedeemedResult() => $_ensure(4);++ @$pb.TagNumber(6)+ PairingRedeemed get pairingRedeemed => $_getN(5);+ @$pb.TagNumber(6)+ set pairingRedeemed(PairingRedeemed value) => $_setField(6, value);+ @$pb.TagNumber(6)+ $core.bool hasPairingRedeemed() => $_has(5);+ @$pb.TagNumber(6)+ void clearPairingRedeemed() => $_clearField(6);+ @$pb.TagNumber(6)+ PairingRedeemed ensurePairingRedeemed() => $_ensure(5);++ @$pb.TagNumber(7)+ ServerError get error => $_getN(6);+ @$pb.TagNumber(7)+ set error(ServerError value) => $_setField(7, value);+ @$pb.TagNumber(7)+ $core.bool hasError() => $_has(6);+ @$pb.TagNumber(7)+ void clearError() => $_clearField(7);+ @$pb.TagNumber(7)+ ServerError ensureError() => $_ensure(6);++ @$pb.TagNumber(8)+ IceConfig get iceConfig => $_getN(7);+ @$pb.TagNumber(8)+ set iceConfig(IceConfig value) => $_setField(8, value);+ @$pb.TagNumber(8)+ $core.bool hasIceConfig() => $_has(7);+ @$pb.TagNumber(8)+ void clearIceConfig() => $_clearField(8);+ @$pb.TagNumber(8)+ IceConfig ensureIceConfig() => $_ensure(7);+}++enum ClientEnvelope_Payload {+ hello,+ forward,+ pairingCreate,+ pairingRedeem,+ notSet+}++class ClientEnvelope extends $pb.GeneratedMessage {+ factory ClientEnvelope({+ ClientHello? hello,+ Signed? forward,+ PairingCreateRequest? pairingCreate,+ PairingRedeemRequest? pairingRedeem,+ }) {+ final result = ClientEnvelope._();+ if (hello != null) result.hello = hello;+ if (forward != null) result.forward = forward;+ if (pairingCreate != null) result.pairingCreate = pairingCreate;+ if (pairingRedeem != null) result.pairingRedeem = pairingRedeem;+ return result;+ }++ ClientEnvelope._();++ factory ClientEnvelope.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ClientEnvelope()..mergeFromBuffer(data, registry);+ factory ClientEnvelope.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ClientEnvelope()..mergeFromJson(json, registry);++ static const $core.Map<$core.int, ClientEnvelope_Payload>+ _ClientEnvelope_PayloadByTag = {+ 1: ClientEnvelope_Payload.hello,+ 2: ClientEnvelope_Payload.forward,+ 3: ClientEnvelope_Payload.pairingCreate,+ 4: ClientEnvelope_Payload.pairingRedeem,+ 0: ClientEnvelope_Payload.notSet+ };+ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'ClientEnvelope',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: ClientEnvelope.$_createMessage)+ ..oo(0, [1, 2, 3, 4])+ ..aOM<ClientHello>(1, _omitFieldNames ? '' : 'hello',+ subBuilder: ClientHello.$_createMessage)+ ..aOM<Signed>(2, _omitFieldNames ? '' : 'forward',+ subBuilder: Signed.$_createMessage)+ ..aOM<PairingCreateRequest>(3, _omitFieldNames ? '' : 'pairingCreate',+ subBuilder: PairingCreateRequest.$_createMessage)+ ..aOM<PairingRedeemRequest>(4, _omitFieldNames ? '' : 'pairingRedeem',+ subBuilder: PairingRedeemRequest.$_createMessage)+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ClientEnvelope clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ClientEnvelope copyWith(void Function(ClientEnvelope) updates) =>+ super.copyWith((message) => updates(message as ClientEnvelope))+ as ClientEnvelope;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use ClientEnvelope() / ClientEnvelope.new instead')+ static ClientEnvelope create() => ClientEnvelope._();+ static $pb.GeneratedMessage $_createMessage() => ClientEnvelope._();+ @$core.override+ ClientEnvelope createEmptyInstance() => ClientEnvelope._();+ @$core.pragma('dart2js:noInline')+ static ClientEnvelope getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<ClientEnvelope>(+ ClientEnvelope.$_createMessage);+ static ClientEnvelope? _defaultInstance;++ @$pb.TagNumber(1)+ @$pb.TagNumber(2)+ @$pb.TagNumber(3)+ @$pb.TagNumber(4)+ ClientEnvelope_Payload whichPayload() =>+ _ClientEnvelope_PayloadByTag[$_whichOneof(0)]!;+ @$pb.TagNumber(1)+ @$pb.TagNumber(2)+ @$pb.TagNumber(3)+ @$pb.TagNumber(4)+ void clearPayload() => $_clearField($_whichOneof(0));++ @$pb.TagNumber(1)+ ClientHello get hello => $_getN(0);+ @$pb.TagNumber(1)+ set hello(ClientHello value) => $_setField(1, value);+ @$pb.TagNumber(1)+ $core.bool hasHello() => $_has(0);+ @$pb.TagNumber(1)+ void clearHello() => $_clearField(1);+ @$pb.TagNumber(1)+ ClientHello ensureHello() => $_ensure(0);++ @$pb.TagNumber(2)+ Signed get forward => $_getN(1);+ @$pb.TagNumber(2)+ set forward(Signed value) => $_setField(2, value);+ @$pb.TagNumber(2)+ $core.bool hasForward() => $_has(1);+ @$pb.TagNumber(2)+ void clearForward() => $_clearField(2);+ @$pb.TagNumber(2)+ Signed ensureForward() => $_ensure(1);++ @$pb.TagNumber(3)+ PairingCreateRequest get pairingCreate => $_getN(2);+ @$pb.TagNumber(3)+ set pairingCreate(PairingCreateRequest value) => $_setField(3, value);+ @$pb.TagNumber(3)+ $core.bool hasPairingCreate() => $_has(2);+ @$pb.TagNumber(3)+ void clearPairingCreate() => $_clearField(3);+ @$pb.TagNumber(3)+ PairingCreateRequest ensurePairingCreate() => $_ensure(2);++ @$pb.TagNumber(4)+ PairingRedeemRequest get pairingRedeem => $_getN(3);+ @$pb.TagNumber(4)+ set pairingRedeem(PairingRedeemRequest value) => $_setField(4, value);+ @$pb.TagNumber(4)+ $core.bool hasPairingRedeem() => $_has(3);+ @$pb.TagNumber(4)+ void clearPairingRedeem() => $_clearField(4);+ @$pb.TagNumber(4)+ PairingRedeemRequest ensurePairingRedeem() => $_ensure(3);+}++class ServerError extends $pb.GeneratedMessage {+ factory ServerError({+ $core.String? code,+ $core.String? message,+ }) {+ final result = ServerError._();+ if (code != null) result.code = code;+ if (message != null) result.message = message;+ return result;+ }++ ServerError._();++ factory ServerError.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ServerError()..mergeFromBuffer(data, registry);+ factory ServerError.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ServerError()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'ServerError',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: ServerError.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'code')+ ..aOS(2, _omitFieldNames ? '' : 'message')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ServerError clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ServerError copyWith(void Function(ServerError) updates) =>+ super.copyWith((message) => updates(message as ServerError))+ as ServerError;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use ServerError() / ServerError.new instead')+ static ServerError create() => ServerError._();+ static $pb.GeneratedMessage $_createMessage() => ServerError._();+ @$core.override+ ServerError createEmptyInstance() => ServerError._();+ @$core.pragma('dart2js:noInline')+ static ServerError getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<ServerError>(+ ServerError.$_createMessage);+ static ServerError? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get code => $_getSZ(0);+ @$pb.TagNumber(1)+ set code($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasCode() => $_has(0);+ @$pb.TagNumber(1)+ void clearCode() => $_clearField(1);++ @$pb.TagNumber(2)+ $core.String get message => $_getSZ(1);+ @$pb.TagNumber(2)+ set message($core.String value) => $_setString(1, value);+ @$pb.TagNumber(2)+ $core.bool hasMessage() => $_has(1);+ @$pb.TagNumber(2)+ void clearMessage() => $_clearField(2);+}++enum PeerMessage_Payload { offer, fetch, reject, header, done, notSet }++/// 控制通道消息+class PeerMessage extends $pb.GeneratedMessage {+ factory PeerMessage({+ ClipOffer? offer,+ PeerFetch? fetch,+ FetchReject? reject,+ TransferHeader? header,+ TransferDone? done,+ }) {+ final result = PeerMessage._();+ if (offer != null) result.offer = offer;+ if (fetch != null) result.fetch = fetch;+ if (reject != null) result.reject = reject;+ if (header != null) result.header = header;+ if (done != null) result.done = done;+ return result;+ }++ PeerMessage._();++ factory PeerMessage.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ PeerMessage()..mergeFromBuffer(data, registry);+ factory PeerMessage.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ PeerMessage()..mergeFromJson(json, registry);++ static const $core.Map<$core.int, PeerMessage_Payload>+ _PeerMessage_PayloadByTag = {+ 1: PeerMessage_Payload.offer,+ 2: PeerMessage_Payload.fetch,+ 3: PeerMessage_Payload.reject,+ 4: PeerMessage_Payload.header,+ 5: PeerMessage_Payload.done,+ 0: PeerMessage_Payload.notSet+ };+ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'PeerMessage',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: PeerMessage.$_createMessage)+ ..oo(0, [1, 2, 3, 4, 5])+ ..aOM<ClipOffer>(1, _omitFieldNames ? '' : 'offer',+ subBuilder: ClipOffer.$_createMessage)+ ..aOM<PeerFetch>(2, _omitFieldNames ? '' : 'fetch',+ subBuilder: PeerFetch.$_createMessage)+ ..aOM<FetchReject>(3, _omitFieldNames ? '' : 'reject',+ subBuilder: FetchReject.$_createMessage)+ ..aOM<TransferHeader>(4, _omitFieldNames ? '' : 'header',+ subBuilder: TransferHeader.$_createMessage)+ ..aOM<TransferDone>(5, _omitFieldNames ? '' : 'done',+ subBuilder: TransferDone.$_createMessage)+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ PeerMessage clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ PeerMessage copyWith(void Function(PeerMessage) updates) =>+ super.copyWith((message) => updates(message as PeerMessage))+ as PeerMessage;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use PeerMessage() / PeerMessage.new instead')+ static PeerMessage create() => PeerMessage._();+ static $pb.GeneratedMessage $_createMessage() => PeerMessage._();+ @$core.override+ PeerMessage createEmptyInstance() => PeerMessage._();+ @$core.pragma('dart2js:noInline')+ static PeerMessage getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<PeerMessage>(+ PeerMessage.$_createMessage);+ static PeerMessage? _defaultInstance;++ @$pb.TagNumber(1)+ @$pb.TagNumber(2)+ @$pb.TagNumber(3)+ @$pb.TagNumber(4)+ @$pb.TagNumber(5)+ PeerMessage_Payload whichPayload() =>+ _PeerMessage_PayloadByTag[$_whichOneof(0)]!;+ @$pb.TagNumber(1)+ @$pb.TagNumber(2)+ @$pb.TagNumber(3)+ @$pb.TagNumber(4)+ @$pb.TagNumber(5)+ void clearPayload() => $_clearField($_whichOneof(0));++ @$pb.TagNumber(1)+ ClipOffer get offer => $_getN(0);+ @$pb.TagNumber(1)+ set offer(ClipOffer value) => $_setField(1, value);+ @$pb.TagNumber(1)+ $core.bool hasOffer() => $_has(0);+ @$pb.TagNumber(1)+ void clearOffer() => $_clearField(1);+ @$pb.TagNumber(1)+ ClipOffer ensureOffer() => $_ensure(0);++ @$pb.TagNumber(2)+ PeerFetch get fetch => $_getN(1);+ @$pb.TagNumber(2)+ set fetch(PeerFetch value) => $_setField(2, value);+ @$pb.TagNumber(2)+ $core.bool hasFetch() => $_has(1);+ @$pb.TagNumber(2)+ void clearFetch() => $_clearField(2);+ @$pb.TagNumber(2)+ PeerFetch ensureFetch() => $_ensure(1);++ @$pb.TagNumber(3)+ FetchReject get reject => $_getN(2);+ @$pb.TagNumber(3)+ set reject(FetchReject value) => $_setField(3, value);+ @$pb.TagNumber(3)+ $core.bool hasReject() => $_has(2);+ @$pb.TagNumber(3)+ void clearReject() => $_clearField(3);+ @$pb.TagNumber(3)+ FetchReject ensureReject() => $_ensure(2);++ @$pb.TagNumber(4)+ TransferHeader get header => $_getN(3);+ @$pb.TagNumber(4)+ set header(TransferHeader value) => $_setField(4, value);+ @$pb.TagNumber(4)+ $core.bool hasHeader() => $_has(3);+ @$pb.TagNumber(4)+ void clearHeader() => $_clearField(4);+ @$pb.TagNumber(4)+ TransferHeader ensureHeader() => $_ensure(3);++ @$pb.TagNumber(5)+ TransferDone get done => $_getN(4);+ @$pb.TagNumber(5)+ set done(TransferDone value) => $_setField(5, value);+ @$pb.TagNumber(5)+ $core.bool hasDone() => $_has(4);+ @$pb.TagNumber(5)+ void clearDone() => $_clearField(5);+ @$pb.TagNumber(5)+ TransferDone ensureDone() => $_ensure(4);+}++/// 复制发生时广播给所有在线对端。+/// 小于阈值的内容会紧接着主动推送;大于阈值的只发这条,等对方来取。+class ClipOffer extends $pb.GeneratedMessage {+ factory ClipOffer({+ $core.String? clipId,+ $0.ClipKind? kind,+ $core.Iterable<$0.ClipItem>? items,+ $fixnum.Int64? totalSize,+ $core.String? textContent,+ $fixnum.Int64? createdAtUnix,+ $core.bool? willPush,+ $core.String? plainText,+ }) {+ final result = ClipOffer._();+ if (clipId != null) result.clipId = clipId;+ if (kind != null) result.kind = kind;+ if (items != null) result.items.addAll(items);+ if (totalSize != null) result.totalSize = totalSize;+ if (textContent != null) result.textContent = textContent;+ if (createdAtUnix != null) result.createdAtUnix = createdAtUnix;+ if (willPush != null) result.willPush = willPush;+ if (plainText != null) result.plainText = plainText;+ return result;+ }++ ClipOffer._();++ factory ClipOffer.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ClipOffer()..mergeFromBuffer(data, registry);+ factory ClipOffer.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ ClipOffer()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'ClipOffer',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: ClipOffer.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'clipId')+ ..aE<$0.ClipKind>(2, _omitFieldNames ? '' : 'kind',+ enumValues: $0.ClipKind.values)+ ..pPM<$0.ClipItem>(3, _omitFieldNames ? '' : 'items',+ subBuilder: $0.ClipItem.$_createMessage)+ ..aInt64(4, _omitFieldNames ? '' : 'totalSize')+ ..aOS(5, _omitFieldNames ? '' : 'textContent')+ ..aInt64(6, _omitFieldNames ? '' : 'createdAtUnix')+ ..aOB(7, _omitFieldNames ? '' : 'willPush')+ ..aOS(8, _omitFieldNames ? '' : 'plainText')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ClipOffer clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ ClipOffer copyWith(void Function(ClipOffer) updates) =>+ super.copyWith((message) => updates(message as ClipOffer)) as ClipOffer;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use ClipOffer() / ClipOffer.new instead')+ static ClipOffer create() => ClipOffer._();+ static $pb.GeneratedMessage $_createMessage() => ClipOffer._();+ @$core.override+ ClipOffer createEmptyInstance() => ClipOffer._();+ @$core.pragma('dart2js:noInline')+ static ClipOffer getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<ClipOffer>(ClipOffer.$_createMessage);+ static ClipOffer? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get clipId => $_getSZ(0);+ @$pb.TagNumber(1)+ set clipId($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasClipId() => $_has(0);+ @$pb.TagNumber(1)+ void clearClipId() => $_clearField(1);++ @$pb.TagNumber(2)+ $0.ClipKind get kind => $_getN(1);+ @$pb.TagNumber(2)+ set kind($0.ClipKind value) => $_setField(2, value);+ @$pb.TagNumber(2)+ $core.bool hasKind() => $_has(1);+ @$pb.TagNumber(2)+ void clearKind() => $_clearField(2);++ @$pb.TagNumber(3)+ $pb.PbList<$0.ClipItem> get items => $_getList(2);++ @$pb.TagNumber(4)+ $fixnum.Int64 get totalSize => $_getI64(3);+ @$pb.TagNumber(4)+ set totalSize($fixnum.Int64 value) => $_setInt64(3, value);+ @$pb.TagNumber(4)+ $core.bool hasTotalSize() => $_has(3);+ @$pb.TagNumber(4)+ void clearTotalSize() => $_clearField(4);++ @$pb.TagNumber(5)+ $core.String get textContent => $_getSZ(4);+ @$pb.TagNumber(5)+ set textContent($core.String value) => $_setString(4, value);+ @$pb.TagNumber(5)+ $core.bool hasTextContent() => $_has(4);+ @$pb.TagNumber(5)+ void clearTextContent() => $_clearField(5);++ @$pb.TagNumber(6)+ $fixnum.Int64 get createdAtUnix => $_getI64(5);+ @$pb.TagNumber(6)+ set createdAtUnix($fixnum.Int64 value) => $_setInt64(5, value);+ @$pb.TagNumber(6)+ $core.bool hasCreatedAtUnix() => $_has(5);+ @$pb.TagNumber(6)+ void clearCreatedAtUnix() => $_clearField(6);++ @$pb.TagNumber(7)+ $core.bool get willPush => $_getBF(6);+ @$pb.TagNumber(7)+ set willPush($core.bool value) => $_setBool(6, value);+ @$pb.TagNumber(7)+ $core.bool hasWillPush() => $_has(6);+ @$pb.TagNumber(7)+ void clearWillPush() => $_clearField(7);++ /// HTML 的纯文本形式(此时 text_content 是 HTML 标记)。旧版本不发这个字段,+ /// 收到空值时由接收方从 HTML 中提取。+ @$pb.TagNumber(8)+ $core.String get plainText => $_getSZ(7);+ @$pb.TagNumber(8)+ set plainText($core.String value) => $_setString(7, value);+ @$pb.TagNumber(8)+ $core.bool hasPlainText() => $_has(7);+ @$pb.TagNumber(8)+ void clearPlainText() => $_clearField(8);+}++/// 与 daemon.proto 的 FetchRequest(UI→daemon)区分:这条是 daemon→peer+class PeerFetch extends $pb.GeneratedMessage {+ factory PeerFetch({+ $core.String? clipId,+ }) {+ final result = PeerFetch._();+ if (clipId != null) result.clipId = clipId;+ return result;+ }++ PeerFetch._();++ factory PeerFetch.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ PeerFetch()..mergeFromBuffer(data, registry);+ factory PeerFetch.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ PeerFetch()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'PeerFetch',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: PeerFetch.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'clipId')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ PeerFetch clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ PeerFetch copyWith(void Function(PeerFetch) updates) =>+ super.copyWith((message) => updates(message as PeerFetch)) as PeerFetch;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use PeerFetch() / PeerFetch.new instead')+ static PeerFetch create() => PeerFetch._();+ static $pb.GeneratedMessage $_createMessage() => PeerFetch._();+ @$core.override+ PeerFetch createEmptyInstance() => PeerFetch._();+ @$core.pragma('dart2js:noInline')+ static PeerFetch getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<PeerFetch>(PeerFetch.$_createMessage);+ static PeerFetch? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get clipId => $_getSZ(0);+ @$pb.TagNumber(1)+ set clipId($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasClipId() => $_has(0);+ @$pb.TagNumber(1)+ void clearClipId() => $_clearField(1);+}++class FetchReject extends $pb.GeneratedMessage {+ factory FetchReject({+ $core.String? clipId,+ $core.String? reason,+ }) {+ final result = FetchReject._();+ if (clipId != null) result.clipId = clipId;+ if (reason != null) result.reason = reason;+ return result;+ }++ FetchReject._();++ factory FetchReject.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ FetchReject()..mergeFromBuffer(data, registry);+ factory FetchReject.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ FetchReject()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'FetchReject',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: FetchReject.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'clipId')+ ..aOS(2, _omitFieldNames ? '' : 'reason')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ FetchReject clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ FetchReject copyWith(void Function(FetchReject) updates) =>+ super.copyWith((message) => updates(message as FetchReject))+ as FetchReject;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use FetchReject() / FetchReject.new instead')+ static FetchReject create() => FetchReject._();+ static $pb.GeneratedMessage $_createMessage() => FetchReject._();+ @$core.override+ FetchReject createEmptyInstance() => FetchReject._();+ @$core.pragma('dart2js:noInline')+ static FetchReject getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<FetchReject>(+ FetchReject.$_createMessage);+ static FetchReject? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get clipId => $_getSZ(0);+ @$pb.TagNumber(1)+ set clipId($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasClipId() => $_has(0);+ @$pb.TagNumber(1)+ void clearClipId() => $_clearField(1);++ @$pb.TagNumber(2)+ $core.String get reason => $_getSZ(1);+ @$pb.TagNumber(2)+ set reason($core.String value) => $_setString(1, value);+ @$pb.TagNumber(2)+ $core.bool hasReason() => $_has(1);+ @$pb.TagNumber(2)+ void clearReason() => $_clearField(2);+}++/// 数据流的第一条消息,之后是裸字节流直到 total_bytes+class TransferHeader extends $pb.GeneratedMessage {+ factory TransferHeader({+ $core.String? clipId,+ $core.String? streamId,+ $fixnum.Int64? totalBytes,+ Compression? compression,+ Packaging? packaging,+ }) {+ final result = TransferHeader._();+ if (clipId != null) result.clipId = clipId;+ if (streamId != null) result.streamId = streamId;+ if (totalBytes != null) result.totalBytes = totalBytes;+ if (compression != null) result.compression = compression;+ if (packaging != null) result.packaging = packaging;+ return result;+ }++ TransferHeader._();++ factory TransferHeader.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ TransferHeader()..mergeFromBuffer(data, registry);+ factory TransferHeader.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ TransferHeader()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'TransferHeader',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: TransferHeader.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'clipId')+ ..aOS(2, _omitFieldNames ? '' : 'streamId')+ ..aInt64(3, _omitFieldNames ? '' : 'totalBytes')+ ..aE<Compression>(4, _omitFieldNames ? '' : 'compression',+ enumValues: Compression.values)+ ..aE<Packaging>(5, _omitFieldNames ? '' : 'packaging',+ enumValues: Packaging.values)+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ TransferHeader clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ TransferHeader copyWith(void Function(TransferHeader) updates) =>+ super.copyWith((message) => updates(message as TransferHeader))+ as TransferHeader;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use TransferHeader() / TransferHeader.new instead')+ static TransferHeader create() => TransferHeader._();+ static $pb.GeneratedMessage $_createMessage() => TransferHeader._();+ @$core.override+ TransferHeader createEmptyInstance() => TransferHeader._();+ @$core.pragma('dart2js:noInline')+ static TransferHeader getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<TransferHeader>(+ TransferHeader.$_createMessage);+ static TransferHeader? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get clipId => $_getSZ(0);+ @$pb.TagNumber(1)+ set clipId($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasClipId() => $_has(0);+ @$pb.TagNumber(1)+ void clearClipId() => $_clearField(1);++ @$pb.TagNumber(2)+ $core.String get streamId => $_getSZ(1);+ @$pb.TagNumber(2)+ set streamId($core.String value) => $_setString(1, value);+ @$pb.TagNumber(2)+ $core.bool hasStreamId() => $_has(1);+ @$pb.TagNumber(2)+ void clearStreamId() => $_clearField(2);++ @$pb.TagNumber(3)+ $fixnum.Int64 get totalBytes => $_getI64(2);+ @$pb.TagNumber(3)+ set totalBytes($fixnum.Int64 value) => $_setInt64(2, value);+ @$pb.TagNumber(3)+ $core.bool hasTotalBytes() => $_has(2);+ @$pb.TagNumber(3)+ void clearTotalBytes() => $_clearField(3);++ @$pb.TagNumber(4)+ Compression get compression => $_getN(3);+ @$pb.TagNumber(4)+ set compression(Compression value) => $_setField(4, value);+ @$pb.TagNumber(4)+ $core.bool hasCompression() => $_has(3);+ @$pb.TagNumber(4)+ void clearCompression() => $_clearField(4);++ @$pb.TagNumber(5)+ Packaging get packaging => $_getN(4);+ @$pb.TagNumber(5)+ set packaging(Packaging value) => $_setField(5, value);+ @$pb.TagNumber(5)+ $core.bool hasPackaging() => $_has(4);+ @$pb.TagNumber(5)+ void clearPackaging() => $_clearField(5);+}++class TransferDone extends $pb.GeneratedMessage {+ factory TransferDone({+ $core.String? clipId,+ $core.String? streamId,+ $core.bool? ok,+ $core.String? error,+ $core.List<$core.int>? sha256,+ }) {+ final result = TransferDone._();+ if (clipId != null) result.clipId = clipId;+ if (streamId != null) result.streamId = streamId;+ if (ok != null) result.ok = ok;+ if (error != null) result.error = error;+ if (sha256 != null) result.sha256 = sha256;+ return result;+ }++ TransferDone._();++ factory TransferDone.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ TransferDone()..mergeFromBuffer(data, registry);+ factory TransferDone.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ TransferDone()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'TransferDone',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),+ createEmptyInstance: TransferDone.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'clipId')+ ..aOS(2, _omitFieldNames ? '' : 'streamId')+ ..aOB(3, _omitFieldNames ? '' : 'ok')+ ..aOS(4, _omitFieldNames ? '' : 'error')+ ..a<$core.List<$core.int>>(+ 5, _omitFieldNames ? '' : 'sha256', $pb.PbFieldType.OY)+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ TransferDone clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ TransferDone copyWith(void Function(TransferDone) updates) =>+ super.copyWith((message) => updates(message as TransferDone))+ as TransferDone;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use TransferDone() / TransferDone.new instead')+ static TransferDone create() => TransferDone._();+ static $pb.GeneratedMessage $_createMessage() => TransferDone._();+ @$core.override+ TransferDone createEmptyInstance() => TransferDone._();+ @$core.pragma('dart2js:noInline')+ static TransferDone getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<TransferDone>(+ TransferDone.$_createMessage);+ static TransferDone? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get clipId => $_getSZ(0);+ @$pb.TagNumber(1)+ set clipId($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasClipId() => $_has(0);+ @$pb.TagNumber(1)+ void clearClipId() => $_clearField(1);++ @$pb.TagNumber(2)+ $core.String get streamId => $_getSZ(1);+ @$pb.TagNumber(2)+ set streamId($core.String value) => $_setString(1, value);+ @$pb.TagNumber(2)+ $core.bool hasStreamId() => $_has(1);+ @$pb.TagNumber(2)+ void clearStreamId() => $_clearField(2);++ @$pb.TagNumber(3)+ $core.bool get ok => $_getBF(2);+ @$pb.TagNumber(3)+ set ok($core.bool value) => $_setBool(2, value);+ @$pb.TagNumber(3)+ $core.bool hasOk() => $_has(2);+ @$pb.TagNumber(3)+ void clearOk() => $_clearField(3);++ @$pb.TagNumber(4)+ $core.String get error => $_getSZ(3);+ @$pb.TagNumber(4)+ set error($core.String value) => $_setString(3, value);+ @$pb.TagNumber(4)+ $core.bool hasError() => $_has(3);+ @$pb.TagNumber(4)+ void clearError() => $_clearField(4);++ @$pb.TagNumber(5)+ $core.List<$core.int> get sha256 => $_getN(4);+ @$pb.TagNumber(5)+ set sha256($core.List<$core.int> value) => $_setBytes(4, value);+ @$pb.TagNumber(5)+ $core.bool hasSha256() => $_has(4);+ @$pb.TagNumber(5)+ void clearSha256() => $_clearField(5);+}++const $core.bool _omitFieldNames =+ $core.bool.fromEnvironment('protobuf.omit_field_names');+const $core.bool _omitMessageNames =+ $core.bool.fromEnvironment('protobuf.omit_message_names');diff --git a/ui/lib/gen/copysync/v1/wire.pbenum.dart b/ui/lib/gen/copysync/v1/wire.pbenum.dartnew file mode 100644index 0000000..dacc575--- /dev/null+++ b/ui/lib/gen/copysync/v1/wire.pbenum.dart@@ -0,0 +1,62 @@+// This is a generated file - do not edit.+//+// Generated from copysync/v1/wire.proto.++// @dart = 3.3++// ignore_for_file: annotate_overrides, camel_case_types, comment_references+// ignore_for_file: constant_identifier_names+// ignore_for_file: curly_braces_in_flow_control_structures+// ignore_for_file: deprecated_member_use_from_same_package, library_prefixes+// ignore_for_file: non_constant_identifier_names, prefer_relative_imports++import 'dart:core' as $core;++import 'package:protobuf/protobuf.dart' as $pb;++class Compression extends $pb.ProtobufEnum {+ static const Compression COMPRESSION_UNSPECIFIED =+ Compression._(0, _omitEnumNames ? '' : 'COMPRESSION_UNSPECIFIED');+ static const Compression COMPRESSION_NONE =+ Compression._(1, _omitEnumNames ? '' : 'COMPRESSION_NONE');+ static const Compression COMPRESSION_ZSTD =+ Compression._(2, _omitEnumNames ? '' : 'COMPRESSION_ZSTD');++ static const $core.List<Compression> values = <Compression>[+ COMPRESSION_UNSPECIFIED,+ COMPRESSION_NONE,+ COMPRESSION_ZSTD,+ ];++ static final $core.List<Compression?> _byValue =+ $pb.ProtobufEnum.$_initByValueList(values, 2);+ static Compression? valueOf($core.int value) =>+ value < 0 || value >= _byValue.length ? null : _byValue[value];++ const Compression._(super.value, super.name);+}++class Packaging extends $pb.ProtobufEnum {+ static const Packaging PACKAGING_UNSPECIFIED =+ Packaging._(0, _omitEnumNames ? '' : 'PACKAGING_UNSPECIFIED');+ static const Packaging PACKAGING_RAW =+ Packaging._(1, _omitEnumNames ? '' : 'PACKAGING_RAW');+ static const Packaging PACKAGING_TAR =+ Packaging._(2, _omitEnumNames ? '' : 'PACKAGING_TAR');++ static const $core.List<Packaging> values = <Packaging>[+ PACKAGING_UNSPECIFIED,+ PACKAGING_RAW,+ PACKAGING_TAR,+ ];++ static final $core.List<Packaging?> _byValue =+ $pb.ProtobufEnum.$_initByValueList(values, 2);+ static Packaging? valueOf($core.int value) =>+ value < 0 || value >= _byValue.length ? null : _byValue[value];++ const Packaging._(super.value, super.name);+}++const $core.bool _omitEnumNames =+ $core.bool.fromEnvironment('protobuf.omit_enum_names');diff --git a/ui/lib/gen/copysync/v1/wire.pbjson.dart b/ui/lib/gen/copysync/v1/wire.pbjson.dartnew file mode 100644index 0000000..19a505f--- /dev/null+++ b/ui/lib/gen/copysync/v1/wire.pbjson.dart@@ -0,0 +1,691 @@+// This is a generated file - do not edit.+//+// Generated from copysync/v1/wire.proto.++// @dart = 3.3++// ignore_for_file: annotate_overrides, camel_case_types, comment_references+// ignore_for_file: constant_identifier_names+// ignore_for_file: curly_braces_in_flow_control_structures+// ignore_for_file: deprecated_member_use_from_same_package, library_prefixes+// ignore_for_file: non_constant_identifier_names, prefer_relative_imports+// ignore_for_file: unused_import++import 'dart:convert' as $convert;+import 'dart:core' as $core;+import 'dart:typed_data' as $typed_data;++@$core.Deprecated('Use compressionDescriptor instead')+const Compression$json = {+ '1': 'Compression',+ '2': [+ {'1': 'COMPRESSION_UNSPECIFIED', '2': 0},+ {'1': 'COMPRESSION_NONE', '2': 1},+ {'1': 'COMPRESSION_ZSTD', '2': 2},+ ],+};++/// Descriptor for `Compression`. Decode as a `google.protobuf.EnumDescriptorProto`.+final $typed_data.Uint8List compressionDescriptor = $convert.base64Decode(+ 'CgtDb21wcmVzc2lvbhIbChdDT01QUkVTU0lPTl9VTlNQRUNJRklFRBAAEhQKEENPTVBSRVNTSU'+ '9OX05PTkUQARIUChBDT01QUkVTU0lPTl9aU1REEAI=');++@$core.Deprecated('Use packagingDescriptor instead')+const Packaging$json = {+ '1': 'Packaging',+ '2': [+ {'1': 'PACKAGING_UNSPECIFIED', '2': 0},+ {'1': 'PACKAGING_RAW', '2': 1},+ {'1': 'PACKAGING_TAR', '2': 2},+ ],+};++/// Descriptor for `Packaging`. Decode as a `google.protobuf.EnumDescriptorProto`.+final $typed_data.Uint8List packagingDescriptor = $convert.base64Decode(+ 'CglQYWNrYWdpbmcSGQoVUEFDS0FHSU5HX1VOU1BFQ0lGSUVEEAASEQoNUEFDS0FHSU5HX1JBVx'+ 'ABEhEKDVBBQ0tBR0lOR19UQVIQAg==');++@$core.Deprecated('Use signedDescriptor instead')+const Signed$json = {+ '1': 'Signed',+ '2': [+ {'1': 'payload', '3': 1, '4': 1, '5': 12, '10': 'payload'},+ {'1': 'signature', '3': 2, '4': 1, '5': 12, '10': 'signature'},+ {'1': 'from_device_id', '3': 3, '4': 1, '5': 9, '10': 'fromDeviceId'},+ ],+};++/// Descriptor for `Signed`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List signedDescriptor = $convert.base64Decode(+ 'CgZTaWduZWQSGAoHcGF5bG9hZBgBIAEoDFIHcGF5bG9hZBIcCglzaWduYXR1cmUYAiABKAxSCX'+ 'NpZ25hdHVyZRIkCg5mcm9tX2RldmljZV9pZBgDIAEoCVIMZnJvbURldmljZUlk');++@$core.Deprecated('Use signalMessageDescriptor instead')+const SignalMessage$json = {+ '1': 'SignalMessage',+ '2': [+ {'1': 'timestamp_unix', '3': 1, '4': 1, '5': 3, '10': 'timestampUnix'},+ {'1': 'nonce', '3': 2, '4': 1, '5': 12, '10': 'nonce'},+ {'1': 'to_device_id', '3': 3, '4': 1, '5': 9, '10': 'toDeviceId'},+ {+ '1': 'offer',+ '3': 10,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.SdpOffer',+ '9': 0,+ '10': 'offer'+ },+ {+ '1': 'answer',+ '3': 11,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.SdpAnswer',+ '9': 0,+ '10': 'answer'+ },+ {+ '1': 'candidate',+ '3': 12,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.IceCandidate',+ '9': 0,+ '10': 'candidate'+ },+ {+ '1': 'ping',+ '3': 13,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.Ping',+ '9': 0,+ '10': 'ping'+ },+ ],+ '8': [+ {'1': 'payload'},+ ],+};++/// Descriptor for `SignalMessage`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List signalMessageDescriptor = $convert.base64Decode(+ 'Cg1TaWduYWxNZXNzYWdlEiUKDnRpbWVzdGFtcF91bml4GAEgASgDUg10aW1lc3RhbXBVbml4Eh'+ 'QKBW5vbmNlGAIgASgMUgVub25jZRIgCgx0b19kZXZpY2VfaWQYAyABKAlSCnRvRGV2aWNlSWQS'+ 'LQoFb2ZmZXIYCiABKAsyFS5jb3B5c3luYy52MS5TZHBPZmZlckgAUgVvZmZlchIwCgZhbnN3ZX'+ 'IYCyABKAsyFi5jb3B5c3luYy52MS5TZHBBbnN3ZXJIAFIGYW5zd2VyEjkKCWNhbmRpZGF0ZRgM'+ 'IAEoCzIZLmNvcHlzeW5jLnYxLkljZUNhbmRpZGF0ZUgAUgljYW5kaWRhdGUSJwoEcGluZxgNIA'+ 'EoCzIRLmNvcHlzeW5jLnYxLlBpbmdIAFIEcGluZ0IJCgdwYXlsb2Fk');++@$core.Deprecated('Use sdpOfferDescriptor instead')+const SdpOffer$json = {+ '1': 'SdpOffer',+ '2': [+ {'1': 'sdp', '3': 1, '4': 1, '5': 9, '10': 'sdp'},+ {'1': 'dtls_fingerprint', '3': 2, '4': 1, '5': 9, '10': 'dtlsFingerprint'},+ ],+};++/// Descriptor for `SdpOffer`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List sdpOfferDescriptor = $convert.base64Decode(+ 'CghTZHBPZmZlchIQCgNzZHAYASABKAlSA3NkcBIpChBkdGxzX2ZpbmdlcnByaW50GAIgASgJUg'+ '9kdGxzRmluZ2VycHJpbnQ=');++@$core.Deprecated('Use sdpAnswerDescriptor instead')+const SdpAnswer$json = {+ '1': 'SdpAnswer',+ '2': [+ {'1': 'sdp', '3': 1, '4': 1, '5': 9, '10': 'sdp'},+ {'1': 'dtls_fingerprint', '3': 2, '4': 1, '5': 9, '10': 'dtlsFingerprint'},+ ],+};++/// Descriptor for `SdpAnswer`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List sdpAnswerDescriptor = $convert.base64Decode(+ 'CglTZHBBbnN3ZXISEAoDc2RwGAEgASgJUgNzZHASKQoQZHRsc19maW5nZXJwcmludBgCIAEoCV'+ 'IPZHRsc0ZpbmdlcnByaW50');++@$core.Deprecated('Use iceCandidateDescriptor instead')+const IceCandidate$json = {+ '1': 'IceCandidate',+ '2': [+ {'1': 'candidate', '3': 1, '4': 1, '5': 9, '10': 'candidate'},+ {'1': 'sdp_mid', '3': 2, '4': 1, '5': 9, '10': 'sdpMid'},+ {'1': 'sdp_mline_index', '3': 3, '4': 1, '5': 13, '10': 'sdpMlineIndex'},+ ],+};++/// Descriptor for `IceCandidate`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List iceCandidateDescriptor = $convert.base64Decode(+ 'CgxJY2VDYW5kaWRhdGUSHAoJY2FuZGlkYXRlGAEgASgJUgljYW5kaWRhdGUSFwoHc2RwX21pZB'+ 'gCIAEoCVIGc2RwTWlkEiYKD3NkcF9tbGluZV9pbmRleBgDIAEoDVINc2RwTWxpbmVJbmRleA==');++@$core.Deprecated('Use pingDescriptor instead')+const Ping$json = {+ '1': 'Ping',+ '2': [+ {'1': 'sent_at_unix', '3': 1, '4': 1, '5': 3, '10': 'sentAtUnix'},+ ],+};++/// Descriptor for `Ping`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List pingDescriptor = $convert+ .base64Decode('CgRQaW5nEiAKDHNlbnRfYXRfdW5peBgBIAEoA1IKc2VudEF0VW5peA==');++@$core.Deprecated('Use clientHelloDescriptor instead')+const ClientHello$json = {+ '1': 'ClientHello',+ '2': [+ {'1': 'device_id', '3': 1, '4': 1, '5': 9, '10': 'deviceId'},+ {'1': 'device_name', '3': 2, '4': 1, '5': 9, '10': 'deviceName'},+ {'1': 'platform', '3': 3, '4': 1, '5': 9, '10': 'platform'},+ {'1': 'public_key', '3': 4, '4': 1, '5': 12, '10': 'publicKey'},+ {'1': 'signature', '3': 5, '4': 1, '5': 12, '10': 'signature'},+ {'1': 'paired_device_ids', '3': 6, '4': 3, '5': 9, '10': 'pairedDeviceIds'},+ ],+};++/// Descriptor for `ClientHello`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List clientHelloDescriptor = $convert.base64Decode(+ 'CgtDbGllbnRIZWxsbxIbCglkZXZpY2VfaWQYASABKAlSCGRldmljZUlkEh8KC2RldmljZV9uYW'+ '1lGAIgASgJUgpkZXZpY2VOYW1lEhoKCHBsYXRmb3JtGAMgASgJUghwbGF0Zm9ybRIdCgpwdWJs'+ 'aWNfa2V5GAQgASgMUglwdWJsaWNLZXkSHAoJc2lnbmF0dXJlGAUgASgMUglzaWduYXR1cmUSKg'+ 'oRcGFpcmVkX2RldmljZV9pZHMYBiADKAlSD3BhaXJlZERldmljZUlkcw==');++@$core.Deprecated('Use serverHelloDescriptor instead')+const ServerHello$json = {+ '1': 'ServerHello',+ '2': [+ {'1': 'challenge', '3': 1, '4': 1, '5': 12, '10': 'challenge'},+ {+ '1': 'ice_servers',+ '3': 2,+ '4': 3,+ '5': 11,+ '6': '.copysync.v1.IceServer',+ '10': 'iceServers'+ },+ {'1': 'server_time_unix', '3': 3, '4': 1, '5': 3, '10': 'serverTimeUnix'},+ ],+};++/// Descriptor for `ServerHello`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List serverHelloDescriptor = $convert.base64Decode(+ 'CgtTZXJ2ZXJIZWxsbxIcCgljaGFsbGVuZ2UYASABKAxSCWNoYWxsZW5nZRI3CgtpY2Vfc2Vydm'+ 'VycxgCIAMoCzIWLmNvcHlzeW5jLnYxLkljZVNlcnZlclIKaWNlU2VydmVycxIoChBzZXJ2ZXJf'+ 'dGltZV91bml4GAMgASgDUg5zZXJ2ZXJUaW1lVW5peA==');++@$core.Deprecated('Use iceServerDescriptor instead')+const IceServer$json = {+ '1': 'IceServer',+ '2': [+ {'1': 'urls', '3': 1, '4': 3, '5': 9, '10': 'urls'},+ {'1': 'username', '3': 2, '4': 1, '5': 9, '10': 'username'},+ {'1': 'credential', '3': 3, '4': 1, '5': 9, '10': 'credential'},+ {'1': 'expires_at_unix', '3': 4, '4': 1, '5': 3, '10': 'expiresAtUnix'},+ ],+};++/// Descriptor for `IceServer`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List iceServerDescriptor = $convert.base64Decode(+ 'CglJY2VTZXJ2ZXISEgoEdXJscxgBIAMoCVIEdXJscxIaCgh1c2VybmFtZRgCIAEoCVIIdXNlcm'+ '5hbWUSHgoKY3JlZGVudGlhbBgDIAEoCVIKY3JlZGVudGlhbBImCg9leHBpcmVzX2F0X3VuaXgY'+ 'BCABKANSDWV4cGlyZXNBdFVuaXg=');++@$core.Deprecated('Use peerPresenceDescriptor instead')+const PeerPresence$json = {+ '1': 'PeerPresence',+ '2': [+ {'1': 'device_id', '3': 1, '4': 1, '5': 9, '10': 'deviceId'},+ {'1': 'online', '3': 2, '4': 1, '5': 8, '10': 'online'},+ ],+};++/// Descriptor for `PeerPresence`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List peerPresenceDescriptor = $convert.base64Decode(+ 'CgxQZWVyUHJlc2VuY2USGwoJZGV2aWNlX2lkGAEgASgJUghkZXZpY2VJZBIWCgZvbmxpbmUYAi'+ 'ABKAhSBm9ubGluZQ==');++@$core.Deprecated('Use pairingCreateRequestDescriptor instead')+const PairingCreateRequest$json = {+ '1': 'PairingCreateRequest',+ '2': [+ {'1': 'device_name', '3': 1, '4': 1, '5': 9, '10': 'deviceName'},+ {'1': 'public_key', '3': 2, '4': 1, '5': 12, '10': 'publicKey'},+ ],+};++/// Descriptor for `PairingCreateRequest`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List pairingCreateRequestDescriptor = $convert.base64Decode(+ 'ChRQYWlyaW5nQ3JlYXRlUmVxdWVzdBIfCgtkZXZpY2VfbmFtZRgBIAEoCVIKZGV2aWNlTmFtZR'+ 'IdCgpwdWJsaWNfa2V5GAIgASgMUglwdWJsaWNLZXk=');++@$core.Deprecated('Use pairingCreateResponseDescriptor instead')+const PairingCreateResponse$json = {+ '1': 'PairingCreateResponse',+ '2': [+ {'1': 'code', '3': 1, '4': 1, '5': 9, '10': 'code'},+ {'1': 'expires_at_unix', '3': 2, '4': 1, '5': 3, '10': 'expiresAtUnix'},+ ],+};++/// Descriptor for `PairingCreateResponse`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List pairingCreateResponseDescriptor = $convert.base64Decode(+ 'ChVQYWlyaW5nQ3JlYXRlUmVzcG9uc2USEgoEY29kZRgBIAEoCVIEY29kZRImCg9leHBpcmVzX2'+ 'F0X3VuaXgYAiABKANSDWV4cGlyZXNBdFVuaXg=');++@$core.Deprecated('Use pairingRedeemRequestDescriptor instead')+const PairingRedeemRequest$json = {+ '1': 'PairingRedeemRequest',+ '2': [+ {'1': 'code', '3': 1, '4': 1, '5': 9, '10': 'code'},+ {'1': 'device_id', '3': 2, '4': 1, '5': 9, '10': 'deviceId'},+ {'1': 'device_name', '3': 3, '4': 1, '5': 9, '10': 'deviceName'},+ {'1': 'public_key', '3': 4, '4': 1, '5': 12, '10': 'publicKey'},+ ],+};++/// Descriptor for `PairingRedeemRequest`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List pairingRedeemRequestDescriptor = $convert.base64Decode(+ 'ChRQYWlyaW5nUmVkZWVtUmVxdWVzdBISCgRjb2RlGAEgASgJUgRjb2RlEhsKCWRldmljZV9pZB'+ 'gCIAEoCVIIZGV2aWNlSWQSHwoLZGV2aWNlX25hbWUYAyABKAlSCmRldmljZU5hbWUSHQoKcHVi'+ 'bGljX2tleRgEIAEoDFIJcHVibGljS2V5');++@$core.Deprecated('Use pairingRedeemResponseDescriptor instead')+const PairingRedeemResponse$json = {+ '1': 'PairingRedeemResponse',+ '2': [+ {'1': 'peer_device_id', '3': 1, '4': 1, '5': 9, '10': 'peerDeviceId'},+ {'1': 'peer_device_name', '3': 2, '4': 1, '5': 9, '10': 'peerDeviceName'},+ {'1': 'peer_platform', '3': 3, '4': 1, '5': 9, '10': 'peerPlatform'},+ {'1': 'peer_public_key', '3': 4, '4': 1, '5': 12, '10': 'peerPublicKey'},+ ],+};++/// Descriptor for `PairingRedeemResponse`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List pairingRedeemResponseDescriptor = $convert.base64Decode(+ 'ChVQYWlyaW5nUmVkZWVtUmVzcG9uc2USJAoOcGVlcl9kZXZpY2VfaWQYASABKAlSDHBlZXJEZX'+ 'ZpY2VJZBIoChBwZWVyX2RldmljZV9uYW1lGAIgASgJUg5wZWVyRGV2aWNlTmFtZRIjCg1wZWVy'+ 'X3BsYXRmb3JtGAMgASgJUgxwZWVyUGxhdGZvcm0SJgoPcGVlcl9wdWJsaWNfa2V5GAQgASgMUg'+ '1wZWVyUHVibGljS2V5');++@$core.Deprecated('Use pairingRedeemedDescriptor instead')+const PairingRedeemed$json = {+ '1': 'PairingRedeemed',+ '2': [+ {'1': 'peer_device_id', '3': 1, '4': 1, '5': 9, '10': 'peerDeviceId'},+ {'1': 'peer_device_name', '3': 2, '4': 1, '5': 9, '10': 'peerDeviceName'},+ {'1': 'peer_platform', '3': 3, '4': 1, '5': 9, '10': 'peerPlatform'},+ {'1': 'peer_public_key', '3': 4, '4': 1, '5': 12, '10': 'peerPublicKey'},+ ],+};++/// Descriptor for `PairingRedeemed`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List pairingRedeemedDescriptor = $convert.base64Decode(+ 'Cg9QYWlyaW5nUmVkZWVtZWQSJAoOcGVlcl9kZXZpY2VfaWQYASABKAlSDHBlZXJEZXZpY2VJZB'+ 'IoChBwZWVyX2RldmljZV9uYW1lGAIgASgJUg5wZWVyRGV2aWNlTmFtZRIjCg1wZWVyX3BsYXRm'+ 'b3JtGAMgASgJUgxwZWVyUGxhdGZvcm0SJgoPcGVlcl9wdWJsaWNfa2V5GAQgASgMUg1wZWVyUH'+ 'VibGljS2V5');++@$core.Deprecated('Use iceConfigDescriptor instead')+const IceConfig$json = {+ '1': 'IceConfig',+ '2': [+ {+ '1': 'ice_servers',+ '3': 1,+ '4': 3,+ '5': 11,+ '6': '.copysync.v1.IceServer',+ '10': 'iceServers'+ },+ ],+};++/// Descriptor for `IceConfig`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List iceConfigDescriptor = $convert.base64Decode(+ 'CglJY2VDb25maWcSNwoLaWNlX3NlcnZlcnMYASADKAsyFi5jb3B5c3luYy52MS5JY2VTZXJ2ZX'+ 'JSCmljZVNlcnZlcnM=');++@$core.Deprecated('Use serverEnvelopeDescriptor instead')+const ServerEnvelope$json = {+ '1': 'ServerEnvelope',+ '2': [+ {+ '1': 'hello',+ '3': 1,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.ServerHello',+ '9': 0,+ '10': 'hello'+ },+ {+ '1': 'forwarded',+ '3': 2,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.Signed',+ '9': 0,+ '10': 'forwarded'+ },+ {+ '1': 'presence',+ '3': 3,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.PeerPresence',+ '9': 0,+ '10': 'presence'+ },+ {+ '1': 'pairing_created',+ '3': 4,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.PairingCreateResponse',+ '9': 0,+ '10': 'pairingCreated'+ },+ {+ '1': 'pairing_redeemed_result',+ '3': 5,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.PairingRedeemResponse',+ '9': 0,+ '10': 'pairingRedeemedResult'+ },+ {+ '1': 'pairing_redeemed',+ '3': 6,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.PairingRedeemed',+ '9': 0,+ '10': 'pairingRedeemed'+ },+ {+ '1': 'error',+ '3': 7,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.ServerError',+ '9': 0,+ '10': 'error'+ },+ {+ '1': 'ice_config',+ '3': 8,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.IceConfig',+ '9': 0,+ '10': 'iceConfig'+ },+ ],+ '8': [+ {'1': 'payload'},+ ],+};++/// Descriptor for `ServerEnvelope`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List serverEnvelopeDescriptor = $convert.base64Decode(+ 'Cg5TZXJ2ZXJFbnZlbG9wZRIwCgVoZWxsbxgBIAEoCzIYLmNvcHlzeW5jLnYxLlNlcnZlckhlbG'+ 'xvSABSBWhlbGxvEjMKCWZvcndhcmRlZBgCIAEoCzITLmNvcHlzeW5jLnYxLlNpZ25lZEgAUglm'+ 'b3J3YXJkZWQSNwoIcHJlc2VuY2UYAyABKAsyGS5jb3B5c3luYy52MS5QZWVyUHJlc2VuY2VIAF'+ 'IIcHJlc2VuY2USTQoPcGFpcmluZ19jcmVhdGVkGAQgASgLMiIuY29weXN5bmMudjEuUGFpcmlu'+ 'Z0NyZWF0ZVJlc3BvbnNlSABSDnBhaXJpbmdDcmVhdGVkElwKF3BhaXJpbmdfcmVkZWVtZWRfcm'+ 'VzdWx0GAUgASgLMiIuY29weXN5bmMudjEuUGFpcmluZ1JlZGVlbVJlc3BvbnNlSABSFXBhaXJp'+ 'bmdSZWRlZW1lZFJlc3VsdBJJChBwYWlyaW5nX3JlZGVlbWVkGAYgASgLMhwuY29weXN5bmMudj'+ 'EuUGFpcmluZ1JlZGVlbWVkSABSD3BhaXJpbmdSZWRlZW1lZBIwCgVlcnJvchgHIAEoCzIYLmNv'+ 'cHlzeW5jLnYxLlNlcnZlckVycm9ySABSBWVycm9yEjcKCmljZV9jb25maWcYCCABKAsyFi5jb3'+ 'B5c3luYy52MS5JY2VDb25maWdIAFIJaWNlQ29uZmlnQgkKB3BheWxvYWQ=');++@$core.Deprecated('Use clientEnvelopeDescriptor instead')+const ClientEnvelope$json = {+ '1': 'ClientEnvelope',+ '2': [+ {+ '1': 'hello',+ '3': 1,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.ClientHello',+ '9': 0,+ '10': 'hello'+ },+ {+ '1': 'forward',+ '3': 2,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.Signed',+ '9': 0,+ '10': 'forward'+ },+ {+ '1': 'pairing_create',+ '3': 3,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.PairingCreateRequest',+ '9': 0,+ '10': 'pairingCreate'+ },+ {+ '1': 'pairing_redeem',+ '3': 4,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.PairingRedeemRequest',+ '9': 0,+ '10': 'pairingRedeem'+ },+ ],+ '8': [+ {'1': 'payload'},+ ],+};++/// Descriptor for `ClientEnvelope`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List clientEnvelopeDescriptor = $convert.base64Decode(+ 'Cg5DbGllbnRFbnZlbG9wZRIwCgVoZWxsbxgBIAEoCzIYLmNvcHlzeW5jLnYxLkNsaWVudEhlbG'+ 'xvSABSBWhlbGxvEi8KB2ZvcndhcmQYAiABKAsyEy5jb3B5c3luYy52MS5TaWduZWRIAFIHZm9y'+ 'd2FyZBJKCg5wYWlyaW5nX2NyZWF0ZRgDIAEoCzIhLmNvcHlzeW5jLnYxLlBhaXJpbmdDcmVhdG'+ 'VSZXF1ZXN0SABSDXBhaXJpbmdDcmVhdGUSSgoOcGFpcmluZ19yZWRlZW0YBCABKAsyIS5jb3B5'+ 'c3luYy52MS5QYWlyaW5nUmVkZWVtUmVxdWVzdEgAUg1wYWlyaW5nUmVkZWVtQgkKB3BheWxvYW'+ 'Q=');++@$core.Deprecated('Use serverErrorDescriptor instead')+const ServerError$json = {+ '1': 'ServerError',+ '2': [+ {'1': 'code', '3': 1, '4': 1, '5': 9, '10': 'code'},+ {'1': 'message', '3': 2, '4': 1, '5': 9, '10': 'message'},+ ],+};++/// Descriptor for `ServerError`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List serverErrorDescriptor = $convert.base64Decode(+ 'CgtTZXJ2ZXJFcnJvchISCgRjb2RlGAEgASgJUgRjb2RlEhgKB21lc3NhZ2UYAiABKAlSB21lc3'+ 'NhZ2U=');++@$core.Deprecated('Use peerMessageDescriptor instead')+const PeerMessage$json = {+ '1': 'PeerMessage',+ '2': [+ {+ '1': 'offer',+ '3': 1,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.ClipOffer',+ '9': 0,+ '10': 'offer'+ },+ {+ '1': 'fetch',+ '3': 2,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.PeerFetch',+ '9': 0,+ '10': 'fetch'+ },+ {+ '1': 'reject',+ '3': 3,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.FetchReject',+ '9': 0,+ '10': 'reject'+ },+ {+ '1': 'header',+ '3': 4,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.TransferHeader',+ '9': 0,+ '10': 'header'+ },+ {+ '1': 'done',+ '3': 5,+ '4': 1,+ '5': 11,+ '6': '.copysync.v1.TransferDone',+ '9': 0,+ '10': 'done'+ },+ ],+ '8': [+ {'1': 'payload'},+ ],+};++/// Descriptor for `PeerMessage`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List peerMessageDescriptor = $convert.base64Decode(+ 'CgtQZWVyTWVzc2FnZRIuCgVvZmZlchgBIAEoCzIWLmNvcHlzeW5jLnYxLkNsaXBPZmZlckgAUg'+ 'VvZmZlchIuCgVmZXRjaBgCIAEoCzIWLmNvcHlzeW5jLnYxLlBlZXJGZXRjaEgAUgVmZXRjaBIy'+ 'CgZyZWplY3QYAyABKAsyGC5jb3B5c3luYy52MS5GZXRjaFJlamVjdEgAUgZyZWplY3QSNQoGaG'+ 'VhZGVyGAQgASgLMhsuY29weXN5bmMudjEuVHJhbnNmZXJIZWFkZXJIAFIGaGVhZGVyEi8KBGRv'+ 'bmUYBSABKAsyGS5jb3B5c3luYy52MS5UcmFuc2ZlckRvbmVIAFIEZG9uZUIJCgdwYXlsb2Fk');++@$core.Deprecated('Use clipOfferDescriptor instead')+const ClipOffer$json = {+ '1': 'ClipOffer',+ '2': [+ {'1': 'clip_id', '3': 1, '4': 1, '5': 9, '10': 'clipId'},+ {+ '1': 'kind',+ '3': 2,+ '4': 1,+ '5': 14,+ '6': '.copysync.v1.ClipKind',+ '10': 'kind'+ },+ {+ '1': 'items',+ '3': 3,+ '4': 3,+ '5': 11,+ '6': '.copysync.v1.ClipItem',+ '10': 'items'+ },+ {'1': 'total_size', '3': 4, '4': 1, '5': 3, '10': 'totalSize'},+ {'1': 'text_content', '3': 5, '4': 1, '5': 9, '10': 'textContent'},+ {'1': 'created_at_unix', '3': 6, '4': 1, '5': 3, '10': 'createdAtUnix'},+ {'1': 'will_push', '3': 7, '4': 1, '5': 8, '10': 'willPush'},+ {'1': 'plain_text', '3': 8, '4': 1, '5': 9, '10': 'plainText'},+ ],+};++/// Descriptor for `ClipOffer`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List clipOfferDescriptor = $convert.base64Decode(+ 'CglDbGlwT2ZmZXISFwoHY2xpcF9pZBgBIAEoCVIGY2xpcElkEikKBGtpbmQYAiABKA4yFS5jb3'+ 'B5c3luYy52MS5DbGlwS2luZFIEa2luZBIrCgVpdGVtcxgDIAMoCzIVLmNvcHlzeW5jLnYxLkNs'+ 'aXBJdGVtUgVpdGVtcxIdCgp0b3RhbF9zaXplGAQgASgDUgl0b3RhbFNpemUSIQoMdGV4dF9jb2'+ '50ZW50GAUgASgJUgt0ZXh0Q29udGVudBImCg9jcmVhdGVkX2F0X3VuaXgYBiABKANSDWNyZWF0'+ 'ZWRBdFVuaXgSGwoJd2lsbF9wdXNoGAcgASgIUgh3aWxsUHVzaBIdCgpwbGFpbl90ZXh0GAggAS'+ 'gJUglwbGFpblRleHQ=');++@$core.Deprecated('Use peerFetchDescriptor instead')+const PeerFetch$json = {+ '1': 'PeerFetch',+ '2': [+ {'1': 'clip_id', '3': 1, '4': 1, '5': 9, '10': 'clipId'},+ ],+};++/// Descriptor for `PeerFetch`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List peerFetchDescriptor =+ $convert.base64Decode('CglQZWVyRmV0Y2gSFwoHY2xpcF9pZBgBIAEoCVIGY2xpcElk');++@$core.Deprecated('Use fetchRejectDescriptor instead')+const FetchReject$json = {+ '1': 'FetchReject',+ '2': [+ {'1': 'clip_id', '3': 1, '4': 1, '5': 9, '10': 'clipId'},+ {'1': 'reason', '3': 2, '4': 1, '5': 9, '10': 'reason'},+ ],+};++/// Descriptor for `FetchReject`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List fetchRejectDescriptor = $convert.base64Decode(+ 'CgtGZXRjaFJlamVjdBIXCgdjbGlwX2lkGAEgASgJUgZjbGlwSWQSFgoGcmVhc29uGAIgASgJUg'+ 'ZyZWFzb24=');++@$core.Deprecated('Use transferHeaderDescriptor instead')+const TransferHeader$json = {+ '1': 'TransferHeader',+ '2': [+ {'1': 'clip_id', '3': 1, '4': 1, '5': 9, '10': 'clipId'},+ {'1': 'stream_id', '3': 2, '4': 1, '5': 9, '10': 'streamId'},+ {'1': 'total_bytes', '3': 3, '4': 1, '5': 3, '10': 'totalBytes'},+ {+ '1': 'compression',+ '3': 4,+ '4': 1,+ '5': 14,+ '6': '.copysync.v1.Compression',+ '10': 'compression'+ },+ {+ '1': 'packaging',+ '3': 5,+ '4': 1,+ '5': 14,+ '6': '.copysync.v1.Packaging',+ '10': 'packaging'+ },+ ],+};++/// Descriptor for `TransferHeader`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List transferHeaderDescriptor = $convert.base64Decode(+ 'Cg5UcmFuc2ZlckhlYWRlchIXCgdjbGlwX2lkGAEgASgJUgZjbGlwSWQSGwoJc3RyZWFtX2lkGA'+ 'IgASgJUghzdHJlYW1JZBIfCgt0b3RhbF9ieXRlcxgDIAEoA1IKdG90YWxCeXRlcxI6Cgtjb21w'+ 'cmVzc2lvbhgEIAEoDjIYLmNvcHlzeW5jLnYxLkNvbXByZXNzaW9uUgtjb21wcmVzc2lvbhI0Cg'+ 'lwYWNrYWdpbmcYBSABKA4yFi5jb3B5c3luYy52MS5QYWNrYWdpbmdSCXBhY2thZ2luZw==');++@$core.Deprecated('Use transferDoneDescriptor instead')+const TransferDone$json = {+ '1': 'TransferDone',+ '2': [+ {'1': 'clip_id', '3': 1, '4': 1, '5': 9, '10': 'clipId'},+ {'1': 'stream_id', '3': 2, '4': 1, '5': 9, '10': 'streamId'},+ {'1': 'ok', '3': 3, '4': 1, '5': 8, '10': 'ok'},+ {'1': 'error', '3': 4, '4': 1, '5': 9, '10': 'error'},+ {'1': 'sha256', '3': 5, '4': 1, '5': 12, '10': 'sha256'},+ ],+};++/// Descriptor for `TransferDone`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List transferDoneDescriptor = $convert.base64Decode(+ 'CgxUcmFuc2ZlckRvbmUSFwoHY2xpcF9pZBgBIAEoCVIGY2xpcElkEhsKCXN0cmVhbV9pZBgCIA'+ 'EoCVIIc3RyZWFtSWQSDgoCb2sYAyABKAhSAm9rEhQKBWVycm9yGAQgASgJUgVlcnJvchIWCgZz'+ 'aGEyNTYYBSABKAxSBnNoYTI1Ng==');diff --git a/ui/lib/main.dart b/ui/lib/main.dartnew file mode 100644index 0000000..e0aec87--- /dev/null+++ b/ui/lib/main.dart@@ -0,0 +1,295 @@+import 'package:flutter/cupertino.dart';+import 'package:flutter/material.dart';++import 'app_state.dart';+import 'background_service.dart';+import 'pages/devices_page.dart';+import 'pages/history_page.dart';+import 'pages/service_page.dart';+import 'pages/settings_page.dart';+import 'theme.dart';+import 'widgets/common.dart';+import 'widgets/pairing_dialog.dart';++void main() => runApp(const CopySyncApp());++class CopySyncApp extends StatefulWidget {+ const CopySyncApp({super.key, this.state});++ /// 测试与截图用:注入预先填好数据的状态,不去连真实的后台服务。+ final AppState? state;++ @override+ State<CopySyncApp> createState() => _CopySyncAppState();+}++class _CopySyncAppState extends State<CopySyncApp> {+ late final AppState _state;++ @override+ void initState() {+ super.initState();+ _state = widget.state ?? (AppState()..connect());+ }++ @override+ void dispose() {+ if (widget.state == null) _state.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ // AppScope 必须包在 MaterialApp 外面:showDialog 推出的路由挂在 Navigator 上,+ // 与 home 是兄弟而非后代,放在 home 里的话对话框里就取不到 AppState。+ return AppScope(+ state: _state,+ child: MaterialApp(+ title: 'CopySync',+ debugShowCheckedModeBanner: false,+ theme: buildTheme(Brightness.light),+ darkTheme: buildTheme(Brightness.dark),+ home: const Shell(),+ ),+ );+ }+}++/// 把 AppState 传递给整棵子树。用 InheritedNotifier 而非引入+/// provider 之类的依赖——状态只有一个,没必要为此多一个包。+class AppScope extends InheritedNotifier<AppState> {+ const AppScope({super.key, required AppState state, required super.child})+ : super(notifier: state);++ static AppState of(BuildContext context) {+ final scope = context.dependOnInheritedWidgetOfExactType<AppScope>();+ assert(scope != null, 'AppScope 未在上层提供');+ return scope!.notifier!;+ }++ /// 只读取一次、不订阅变化。用于事件回调里拿实例。+ static AppState read(BuildContext context) =>+ context.getInheritedWidgetOfExactType<AppScope>()!.notifier!;+}++enum Section { history, devices, settings }++class Shell extends StatefulWidget {+ const Shell({super.key, this.initialSection = Section.history});++ final Section initialSection;++ @override+ State<Shell> createState() => _ShellState();+}++class _ShellState extends State<Shell> {+ late Section _section = widget.initialSection;+ bool _pairingDialogOpen = false;++ @override+ Widget build(BuildContext context) {+ final state = AppScope.of(context);++ // 对端发起配对时主动弹出确认——指纹核对不能等用户自己去翻页面+ final pending = state.pendingPairing;+ if (pending != null && !_pairingDialogOpen) {+ _pairingDialogOpen = true;+ WidgetsBinding.instance.addPostFrameCallback((_) async {+ await showPairingConfirmDialog(context, pending);+ if (mounted) setState(() => _pairingDialogOpen = false);+ });+ }++ // 后台服务没装或没在跑时,其他页面都无从谈起,先引导把它启用+ final service = state.serviceState;+ final needsService = state.link == LinkState.offline &&+ service != null &&+ service != ServiceState.running;++ return Scaffold(+ body: Row(+ children: [+ _Sidebar(current: _section, onSelect: (s) => setState(() => _section = s)),+ Expanded(+ child: needsService+ ? const ServicePage()+ : switch (_section) {+ Section.history => const HistoryPage(),+ Section.devices => const DevicesPage(),+ Section.settings => const SettingsPage(),+ },+ ),+ ],+ ),+ );+ }+}++class _Sidebar extends StatelessWidget {+ const _Sidebar({required this.current, required this.onSelect});++ final Section current;+ final ValueChanged<Section> onSelect;++ @override+ Widget build(BuildContext context) {+ final state = AppScope.of(context);+ final p = context.palette;++ return Container(+ width: 200,+ decoration: BoxDecoration(+ color: p.sidebar,+ border: Border(right: BorderSide(color: p.border)),+ ),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ // 顶部留白是 macOS 红绿灯按钮所在的标题栏+ const SizedBox(height: 52),+ Padding(+ padding: const EdgeInsets.fromLTRB(Insets.lg, 0, Insets.lg, Insets.lg),+ child: Row(+ children: [+ const AppMark(size: 22),+ const SizedBox(width: Insets.sm),+ Text('CopySync', style: context.text.titleSmall),+ ],+ ),+ ),+ _NavItem(+ icon: CupertinoIcons.clock,+ label: '复制记录',+ selected: current == Section.history,+ trailing: state.records.isEmpty ? null : '${state.records.length}',+ onTap: () => onSelect(Section.history),+ ),+ _NavItem(+ icon: CupertinoIcons.device_laptop,+ label: '设备',+ selected: current == Section.devices,+ onTap: () => onSelect(Section.devices),+ ),+ _NavItem(+ icon: CupertinoIcons.gear,+ label: '设置',+ selected: current == Section.settings,+ onTap: () => onSelect(Section.settings),+ ),+ const Spacer(),+ const _ConnectionFooter(),+ ],+ ),+ );+ }+}++class _NavItem extends StatefulWidget {+ const _NavItem({+ required this.icon,+ required this.label,+ required this.selected,+ required this.onTap,+ this.trailing,+ });++ final IconData icon;+ final String label;+ final bool selected;+ final VoidCallback onTap;+ final String? trailing;++ @override+ State<_NavItem> createState() => _NavItemState();+}++class _NavItemState extends State<_NavItem> {+ bool _hovered = false;++ @override+ Widget build(BuildContext context) {+ final p = context.palette;+ final selected = widget.selected;++ return Padding(+ padding: const EdgeInsets.symmetric(horizontal: Insets.sm, vertical: 1),+ child: MouseRegion(+ cursor: SystemMouseCursors.click,+ onEnter: (_) => setState(() => _hovered = true),+ onExit: (_) => setState(() => _hovered = false),+ child: GestureDetector(+ onTap: widget.onTap,+ child: Container(+ height: 30,+ padding: const EdgeInsets.symmetric(horizontal: 10),+ decoration: BoxDecoration(+ color: selected ? p.selection : (_hovered ? p.hover : Colors.transparent),+ borderRadius: BorderRadius.circular(Radii.sm),+ ),+ child: Row(+ children: [+ Icon(widget.icon, size: 16, color: selected ? p.accent : p.textDim),+ const SizedBox(width: 10),+ Expanded(+ child: Text(+ widget.label,+ style: context.text.labelLarge?.copyWith(+ fontWeight: selected ? FontWeight.w600 : FontWeight.w500,+ ),+ ),+ ),+ if (widget.trailing != null)+ Text(widget.trailing!, style: context.text.labelSmall),+ ],+ ),+ ),+ ),+ ),+ );+ }+}++/// 侧边栏底部的连接状态。常驻可见,用户不必进设置页就知道能不能用。+class _ConnectionFooter extends StatelessWidget {+ const _ConnectionFooter();++ @override+ Widget build(BuildContext context) {+ final state = AppScope.of(context);+ final p = context.palette;+ final signaling = state.status?.signalingConnected ?? false;+ final online = state.onlinePeerCount;++ final (color, label) = switch (state.link) {+ LinkState.connecting => (p.textFaint, '正在连接…'),+ LinkState.offline => (p.danger, state.error ?? '后台服务未运行'),+ LinkState.online when !signaling => (p.warning, '未连接服务器'),+ LinkState.online when online > 0 => (p.online, '$online 台设备在线'),+ LinkState.online => (p.online, '已连接服务器'),+ };++ return Container(+ padding: const EdgeInsets.fromLTRB(Insets.lg, Insets.md, Insets.lg, Insets.md),+ decoration: BoxDecoration(border: Border(top: BorderSide(color: p.border))),+ child: Row(+ children: [+ Container(+ width: 7,+ height: 7,+ decoration: BoxDecoration(color: color, shape: BoxShape.circle),+ ),+ const SizedBox(width: Insets.sm),+ Expanded(+ child: Text(+ label,+ style: context.text.bodySmall,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ ),+ ],+ ),+ );+ }+}diff --git a/ui/lib/pages/devices_page.dart b/ui/lib/pages/devices_page.dartnew file mode 100644index 0000000..d83c368--- /dev/null+++ b/ui/lib/pages/devices_page.dart@@ -0,0 +1,199 @@+import 'package:flutter/cupertino.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../app_state.dart';+import '../gen/copysync/v1/daemon.pb.dart';+import '../main.dart';+import '../theme.dart';+import '../widgets/common.dart';+import '../widgets/pairing_dialog.dart';++class DevicesPage extends StatelessWidget {+ const DevicesPage({super.key});++ @override+ Widget build(BuildContext context) {+ final state = AppScope.of(context);+ final canPair = state.isOnline && (state.status?.signalingConnected ?? false);++ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ PageHeader(+ title: '设备',+ subtitle: state.peers.isEmpty+ ? '配对之后,设备之间就会同步剪贴板'+ : '已配对 ${state.peers.length} 台,${state.onlinePeerCount} 台在线',+ actions: [+ FilledButton.icon(+ onPressed: canPair ? () => _startPairing(context) : null,+ icon: const Icon(CupertinoIcons.plus, size: 14),+ label: const Text('添加设备'),+ ),+ ],+ ),+ Expanded(+ child: ListView(+ padding: const EdgeInsets.fromLTRB(Insets.xl, 0, Insets.xl, Insets.xl),+ children: [+ if (state.self != null)+ GroupSection(+ title: '这台 Mac',+ footnote: '配对时,两台设备会互相显示对方的安全指纹,核对一致才能确认。',+ child: GroupBox(children: [_DeviceRow(device: state.self!, isSelf: true)]),+ ),+ if (state.peers.isEmpty)+ Padding(+ padding: const EdgeInsets.only(top: Insets.xl),+ child: EmptyState(+ icon: CupertinoIcons.device_laptop,+ title: '还没有配对的设备',+ description: canPair+ ? '在另一台电脑上打开 CopySync,用 6 位配对码把两台连起来。'+ : '先在「设置」里连接信令服务器,才能配对设备。',+ action: canPair+ ? FilledButton(+ onPressed: () => _startPairing(context),+ child: const Text('添加设备'),+ )+ : null,+ ),+ )+ else+ GroupSection(+ title: '已配对的设备',+ footnote: '直连:数据在两台设备之间直接传输。'+ '中转:网络环境打不通直连时,经你的服务器转发,内容依然是端到端加密的。',+ child: GroupBox(+ dividerIndent: 52,+ children: [for (final d in state.peers) _DeviceRow(device: d)],+ ),+ ),+ ],+ ),+ ),+ ],+ );+ }++ void _startPairing(BuildContext context) =>+ showDialog(context: context, builder: (_) => const PairingDialog());+}++class _DeviceRow extends StatelessWidget {+ const _DeviceRow({required this.device, this.isSelf = false});++ final Device device;+ final bool isSelf;++ @override+ Widget build(BuildContext context) {+ final p = context.palette;+ return Padding(+ padding: const EdgeInsets.fromLTRB(Insets.lg, Insets.md, Insets.sm, Insets.md),+ child: Row(+ children: [+ Icon(platformIcon(device.platform), size: 22, color: p.textDim),+ const SizedBox(width: Insets.md + 2),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(device.name, style: context.text.labelLarge),+ const SizedBox(height: 2),+ Text(+ device.publicKeyFingerprint,+ // 等宽:用户要逐字符比对,等宽能显著降低看错的概率+ style: context.text.bodySmall?.copyWith(fontFamily: monoFamily, letterSpacing: 0.4),+ ),+ ],+ ),+ ),+ if (isSelf)+ Padding(+ padding: const EdgeInsets.only(right: Insets.sm),+ child: Text('本机', style: context.text.bodySmall),+ )+ else ...[+ StatusDot(+ color: device.online ? p.online : p.textFaint,+ label: device.online ? connectionLabel(device) : '离线',+ ),+ const SizedBox(width: Insets.sm),+ _DeviceMenu(device: device),+ ],+ ],+ ),+ );+ }+}++String connectionLabel(Device d) => switch (d.connection) {+ ConnectionKind.CONNECTION_KIND_DIRECT => '直连',+ ConnectionKind.CONNECTION_KIND_RELAY => '中转',+ _ => '在线',+ };++IconData platformIcon(String platform) => switch (platform) {+ 'windows' => CupertinoIcons.desktopcomputer,+ _ => CupertinoIcons.device_laptop,+ };++class _DeviceMenu extends StatelessWidget {+ const _DeviceMenu({required this.device});++ final Device device;++ @override+ Widget build(BuildContext context) {+ return PopupMenuButton<String>(+ tooltip: '更多操作',+ padding: EdgeInsets.zero,+ position: PopupMenuPosition.under,+ itemBuilder: (ctx) => [+ const PopupMenuItem(value: 'copy', height: 34, child: Text('拷贝安全指纹')),+ PopupMenuItem(+ value: 'unpair',+ height: 34,+ child: Text('解除配对…', style: TextStyle(color: ctx.palette.danger)),+ ),+ ],+ onSelected: (v) => v == 'copy' ? _copy(context) : _unpair(context),+ child: const IgnorePointer(+ child: IconAction(icon: CupertinoIcons.ellipsis, tooltip: ''),+ ),+ );+ }++ Future<void> _copy(BuildContext context) async {+ await Clipboard.setData(ClipboardData(text: device.publicKeyFingerprint));+ if (context.mounted) showToast(context, '安全指纹已拷贝');+ }++ Future<void> _unpair(BuildContext context) async {+ final state = AppScope.read(context);+ final ok = await showDialog<bool>(+ context: context,+ builder: (ctx) => AlertDialog(+ title: Text('解除与「${device.name}」的配对?'),+ content: const Text('两台设备将不再同步。以后想恢复,需要重新配对并核对指纹。'),+ actions: [+ OutlinedButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('取消')),+ FilledButton(+ onPressed: () => Navigator.pop(ctx, true),+ style: FilledButton.styleFrom(backgroundColor: ctx.palette.danger),+ child: const Text('解除配对'),+ ),+ ],+ ),+ );+ if (ok != true) return;+ try {+ await state.unpair(device.id);+ if (context.mounted) showToast(context, '已解除配对');+ } catch (e) {+ if (context.mounted) showToast(context, AppState.describeError(e), error: true);+ }+ }+}diff --git a/ui/lib/pages/history_page.dart b/ui/lib/pages/history_page.dartnew file mode 100644index 0000000..e2851ef--- /dev/null+++ b/ui/lib/pages/history_page.dart@@ -0,0 +1,311 @@+import 'package:flutter/cupertino.dart';+import 'package:flutter/material.dart';++import '../app_state.dart';+import '../gen/copysync/v1/daemon.pb.dart';+import '../main.dart';+import '../theme.dart';+import '../widgets/common.dart';++enum _Filter { all, text, image, file }++class HistoryPage extends StatefulWidget {+ const HistoryPage({super.key});++ @override+ State<HistoryPage> createState() => _HistoryPageState();+}++class _HistoryPageState extends State<HistoryPage> {+ _Filter _filter = _Filter.all;++ bool _matches(ClipRecord r) => switch (_filter) {+ _Filter.all => true,+ // 富文本也是文字,用户不关心它在剪贴板里是不是 HTML+ _Filter.text =>+ r.kind == ClipKind.CLIP_KIND_TEXT || r.kind == ClipKind.CLIP_KIND_HTML,+ _Filter.image => r.kind == ClipKind.CLIP_KIND_IMAGE,+ _Filter.file => r.kind == ClipKind.CLIP_KIND_FILE,+ };++ @override+ Widget build(BuildContext context) {+ final state = AppScope.of(context);+ final records = state.records.where(_matches).toList();+ final ttl = state.config?.historyTtlSeconds.toInt();++ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ PageHeader(+ title: '复制记录',+ subtitle: state.records.isEmpty+ ? '在任意一台设备上复制,内容会出现在这里'+ : '共 ${state.records.length} 条${ttl == null ? '' : ',保留 ${_ttlLabel(ttl)}'}',+ actions: [+ if (state.records.isNotEmpty) ...[+ Segmented<_Filter>(+ value: _filter,+ segments: const [+ (_Filter.all, '全部'),+ (_Filter.text, '文本'),+ (_Filter.image, '图片'),+ (_Filter.file, '文件'),+ ],+ onChanged: (f) => setState(() => _filter = f),+ ),+ IconAction(+ icon: CupertinoIcons.trash,+ tooltip: '清空记录',+ onTap: () => _confirmClear(context, state),+ ),+ ],+ ],+ ),+ if (_needsPermission(state.status?.clipboardPermission))+ Padding(+ padding: const EdgeInsets.fromLTRB(Insets.xl, 0, Insets.xl, Insets.md),+ child: _PermissionNotice(permission: state.status!.clipboardPermission),+ ),+ Expanded(+ child: records.isEmpty+ ? EmptyState(+ icon: _filter == _Filter.all+ ? CupertinoIcons.doc_on_clipboard+ : CupertinoIcons.line_horizontal_3_decrease,+ title: _filter == _Filter.all ? '还没有记录' : '没有这一类的记录',+ description: _filter == _Filter.all+ ? '在任意一台已配对的设备上复制文本、图片或文件,记录会出现在这里。'+ : null,+ )+ : CustomScrollView(+ slivers: [+ SliverPadding(+ padding: const EdgeInsets.fromLTRB(Insets.xl, 0, Insets.xl, Insets.xl),+ sliver: DecoratedSliver(+ decoration: BoxDecoration(+ color: context.palette.surface,+ borderRadius: BorderRadius.circular(Radii.md),+ border: Border.all(color: context.palette.border),+ ),+ sliver: SliverPadding(+ padding: const EdgeInsets.all(Insets.xs),+ sliver: SliverList.separated(+ itemCount: records.length,+ separatorBuilder: (_, _) => const Divider(indent: 44, endIndent: 8),+ itemBuilder: (_, i) => _RecordRow(record: records[i]),+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ ],+ );+ }++ static bool _needsPermission(ClipboardPermission? p) =>+ p == ClipboardPermission.CLIPBOARD_PERMISSION_DEFAULT ||+ p == ClipboardPermission.CLIPBOARD_PERMISSION_ASK ||+ p == ClipboardPermission.CLIPBOARD_PERMISSION_ALWAYS_DENY;++ static String _ttlLabel(int seconds) =>+ seconds % 86400 == 0 ? '${seconds ~/ 86400} 天' : '${(seconds / 3600).round()} 小时';++ Future<void> _confirmClear(BuildContext context, AppState state) async {+ final ok = await showDialog<bool>(+ context: context,+ builder: (ctx) => AlertDialog(+ title: const Text('清空全部记录?'),+ content: const Text('所有设备上同步来的记录和已缓存的文件都会从这台 Mac 上删除。原始文件不受影响。'),+ actions: [+ OutlinedButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('取消')),+ FilledButton(+ onPressed: () => Navigator.pop(ctx, true),+ style: FilledButton.styleFrom(backgroundColor: ctx.palette.danger),+ child: const Text('清空'),+ ),+ ],+ ),+ );+ if (ok != true || !context.mounted) return;+ try {+ await state.deleteRecords(all: true);+ if (context.mounted) showToast(context, '记录已清空');+ } catch (e) {+ if (context.mounted) showToast(context, AppState.describeError(e), error: true);+ }+ }+}++/// 读剪贴板需要用户授权。没授权时整个产品等于不工作,所以放在最显眼的位置。+class _PermissionNotice extends StatelessWidget {+ const _PermissionNotice({required this.permission});++ final ClipboardPermission permission;++ @override+ Widget build(BuildContext context) {+ final denied = permission == ClipboardPermission.CLIPBOARD_PERMISSION_ALWAYS_DENY;+ return Notice(+ title: denied ? '已禁止 CopySync 读取剪贴板' : '允许 CopySync 读取剪贴板',+ message: denied+ ? '在这台 Mac 上复制的内容不会同步出去。到系统设置里把 CopySync Daemon 改为「允许」。'+ : '否则 macOS 每次都会弹窗询问。到系统设置里把 CopySync Daemon 改为「允许」。',+ action: OutlinedButton(+ onPressed: () async {+ try {+ await AppScope.read(context).requestClipboardPermission();+ } catch (e) {+ if (context.mounted) showToast(context, AppState.describeError(e), error: true);+ }+ },+ child: const Text('打开系统设置'),+ ),+ );+ }+}++class _RecordRow extends StatefulWidget {+ const _RecordRow({required this.record});++ final ClipRecord record;++ @override+ State<_RecordRow> createState() => _RecordRowState();+}++class _RecordRowState extends State<_RecordRow> {+ bool _hovered = false;+ bool _busy = false;++ @override+ Widget build(BuildContext context) {+ final r = widget.record;+ final p = context.palette;++ return MouseRegion(+ onEnter: (_) => setState(() => _hovered = true),+ onExit: (_) => setState(() => _hovered = false),+ child: Container(+ constraints: const BoxConstraints(minHeight: 52),+ padding: const EdgeInsets.symmetric(horizontal: Insets.md, vertical: Insets.sm),+ decoration: BoxDecoration(+ color: _hovered ? p.hover : Colors.transparent,+ borderRadius: BorderRadius.circular(Radii.sm),+ ),+ child: Row(+ children: [+ Icon(kindIcon(r), size: 18, color: p.textDim),+ const SizedBox(width: Insets.md),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(+ recordTitle(r),+ style: context.text.labelLarge,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ const SizedBox(height: 2),+ Text(+ [+ r.outgoing ? '本机' : '来自 ${r.originDeviceName}',+ if (r.totalSize > 0) humanBytes(r.totalSize.toInt()),+ relativeTime(DateTime.fromMillisecondsSinceEpoch(r.createdAtUnix.toInt() * 1000)),+ ].join(' · '),+ style: context.text.bodySmall,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ ],+ ),+ ),+ const SizedBox(width: Insets.md),+ _trailing(context, r),+ ],+ ),+ ),+ );+ }++ Widget _trailing(BuildContext context, ClipRecord r) {+ final p = context.palette;+ if (_busy) {+ return const SizedBox(+ width: 16,+ height: 16,+ child: CircularProgressIndicator(strokeWidth: 2),+ );+ }+ switch (r.status) {+ case ClipStatus.CLIP_STATUS_REMOTE_ONLY:+ // 超过自动同步阈值的大文件:只有元数据,需要时再拉+ return OutlinedButton(+ onPressed: () => _run(() => AppScope.read(context).fetch(r.id), '开始拉取'),+ child: const Text('拉取到本机'),+ );+ case ClipStatus.CLIP_STATUS_FETCHING:+ return const SizedBox(width: 72, child: LinearProgressIndicator(minHeight: 3));+ case ClipStatus.CLIP_STATUS_FAILED:+ return Tooltip(+ message: r.error.isEmpty ? '传输失败' : r.error,+ child: Text('传输失败', style: context.text.bodySmall?.copyWith(color: p.danger)),+ );+ case ClipStatus.CLIP_STATUS_EXPIRED:+ return Text('已过期', style: context.text.bodySmall?.copyWith(color: p.textFaint));+ default:+ // 悬停时才显示操作,静态时列表保持干净+ if (!_hovered) return const SizedBox(height: 28);+ return Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ TextButton(+ onPressed: () =>+ _run(() => AppScope.read(context).applyToClipboard(r.id), '已放入剪贴板'),+ child: const Text('放入剪贴板'),+ ),+ IconAction(+ icon: CupertinoIcons.trash,+ tooltip: '删除这条记录',+ onTap: () => _run(() => AppScope.read(context).deleteRecords(ids: [r.id]), '已删除'),+ ),+ ],+ );+ }+ }++ Future<void> _run(Future<void> Function() action, String success) async {+ setState(() => _busy = true);+ try {+ await action();+ if (mounted) showToast(context, success);+ } catch (e) {+ if (mounted) showToast(context, AppState.describeError(e), error: true);+ } finally {+ if (mounted) setState(() => _busy = false);+ }+ }+}++/// 按内容类型区分的图标:只靠形状区分,不靠颜色。+IconData kindIcon(ClipRecord r) => switch (r.kind) {+ ClipKind.CLIP_KIND_TEXT => CupertinoIcons.text_alignleft,+ ClipKind.CLIP_KIND_HTML => CupertinoIcons.doc_richtext,+ ClipKind.CLIP_KIND_IMAGE => CupertinoIcons.photo,+ ClipKind.CLIP_KIND_FILE when r.items.length > 1 => CupertinoIcons.doc_on_doc,+ ClipKind.CLIP_KIND_FILE when r.items.isNotEmpty && r.items.first.isDir =>+ CupertinoIcons.folder,+ ClipKind.CLIP_KIND_FILE => CupertinoIcons.doc,+ _ => CupertinoIcons.question_circle,+ };++String recordTitle(ClipRecord r) {+ if (r.textPreview.isNotEmpty) return r.textPreview.replaceAll('\n', ' ').trim();+ if (r.items.isEmpty) return '(空)';+ if (r.items.length == 1) return r.items.first.name;+ return '${r.items.first.name} 等 ${r.items.length} 项';+}diff --git a/ui/lib/pages/service_page.dart b/ui/lib/pages/service_page.dartnew file mode 100644index 0000000..b84127a--- /dev/null+++ b/ui/lib/pages/service_page.dart@@ -0,0 +1,115 @@+import 'package:flutter/material.dart';++import '../app_state.dart';+import '../background_service.dart';+import '../main.dart';+import '../theme.dart';+import '../widgets/common.dart';++/// 后台服务没装、没在跑时的引导页。+///+/// 首次打开 App 时用户看到的就是这一页:说明后台进程是做什么的,+/// 然后一个按钮把它注册为登录项。不需要打开终端。+class ServicePage extends StatefulWidget {+ const ServicePage({super.key});++ @override+ State<ServicePage> createState() => _ServicePageState();+}++class _ServicePageState extends State<ServicePage> {+ bool _busy = false;+ String? _error;++ Future<void> _run(Future<void> Function() action) async {+ setState(() {+ _busy = true;+ _error = null;+ });+ try {+ await action();+ } catch (e) {+ if (mounted) setState(() => _error = AppState.describeError(e));+ } finally {+ if (mounted) setState(() => _busy = false);+ }+ }++ @override+ Widget build(BuildContext context) {+ final state = AppScope.of(context);+ final (title, body, button) = switch (state.serviceState) {+ ServiceState.mustMove => (+ '先把 CopySync 移到「应用程序」',+ 'CopySync 现在是直接从安装盘里打开的。把它拖进「应用程序」文件夹,'+ '推出安装盘,再从「应用程序」里打开,就可以启用后台同步。',+ null,+ ),+ ServiceState.notInstalled => (+ '开始使用 CopySync',+ 'CopySync 会在后台运行一个小进程,用来感知剪贴板的变化,并与你的其他设备保持连接。'+ '启用后它随系统登录自动启动,关掉这个窗口也会照常同步。',+ '启用后台同步',+ ),+ ServiceState.stale => (+ '重新启用后台同步',+ 'CopySync 换了位置,或者之前用旧版安装脚本装过。重新启用一次,'+ '让后台进程指向当前这个 App。历史记录与配对关系都会保留。',+ '重新启用',+ ),+ ServiceState.stopped => (+ '后台服务没有运行',+ '它可能刚刚退出,系统通常会在几秒内把它重新拉起。'+ '如果一直停在这一页,点下面的按钮重新启动。',+ '重新启动',+ ),+ _ => (+ '后台服务没有运行',+ '这是开发构建,App 里没有内置后台服务。'+ '在源码目录运行 ./scripts/install-macos.sh 安装它。',+ null,+ ),+ };++ return Center(+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 420),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ const AppMark(size: 64),+ const SizedBox(height: Insets.xl),+ Text(title, style: context.text.headlineSmall),+ const SizedBox(height: Insets.sm),+ Text(body, style: context.text.bodyMedium?.copyWith(color: context.palette.textDim)),+ if (button != null) ...[+ const SizedBox(height: Insets.xl),+ FilledButton(+ onPressed: _busy ? null : () => _run(state.enableService),+ child: _busy+ ? const SizedBox(+ width: 14,+ height: 14,+ child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),+ )+ : Text(button),+ ),+ ],+ if (_error != null) ...[+ const SizedBox(height: Insets.md),+ Text(_error!, style: context.text.bodySmall?.copyWith(color: context.palette.danger)),+ ],+ const SizedBox(height: Insets.xl),+ Text(+ state.serviceState == ServiceState.stopped+ ? '运行日志:${state.service.logPath.replaceFirst(RegExp(r'^/Users/[^/]+'), '~')}'+ : '随时可以在「设置」中停用后台同步。',+ style: context.text.bodySmall,+ ),+ ],+ ),+ ),+ );+ }+}diff --git a/ui/lib/pages/settings_page.dart b/ui/lib/pages/settings_page.dartnew file mode 100644index 0000000..3d57e35--- /dev/null+++ b/ui/lib/pages/settings_page.dart@@ -0,0 +1,434 @@+import 'dart:io';++import 'package:fixnum/fixnum.dart';+import 'package:flutter/cupertino.dart';+import 'package:flutter/material.dart';++import '../app_state.dart';+import '../gen/copysync/v1/daemon.pb.dart';+import '../main.dart';+import '../theme.dart';+import '../widgets/common.dart';++class SettingsPage extends StatefulWidget {+ const SettingsPage({super.key});++ @override+ State<SettingsPage> createState() => _SettingsPageState();+}++class _SettingsPageState extends State<SettingsPage> {+ final _serverController = TextEditingController();+ final _nameController = TextEditingController();+ bool _serverDirty = false;+ bool _nameDirty = false;+ String? _lastLoadedServer;+ String? _lastLoadedName;++ @override+ void dispose() {+ _serverController.dispose();+ _nameController.dispose();+ super.dispose();+ }++ /// 用户正在编辑时不要用服务端下发的值覆盖输入框,+ /// 否则打字打到一半会被"吃掉"。+ void _syncControllers(Config cfg) {+ if (!_serverDirty && cfg.signalingUrl != _lastLoadedServer) {+ _serverController.text = cfg.signalingUrl;+ _lastLoadedServer = cfg.signalingUrl;+ }+ if (!_nameDirty && cfg.deviceName != _lastLoadedName) {+ _nameController.text = cfg.deviceName;+ _lastLoadedName = cfg.deviceName;+ }+ }++ @override+ Widget build(BuildContext context) {+ final state = AppScope.of(context);+ final cfg = state.config;++ if (cfg == null) {+ return const Center(child: CircularProgressIndicator(strokeWidth: 2.5));+ }+ _syncControllers(cfg);++ final p = context.palette;+ final connected = state.status?.signalingConnected == true;++ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ const PageHeader(title: '设置'),+ Expanded(+ child: ListView(+ padding: const EdgeInsets.fromLTRB(Insets.xl, 0, Insets.xl, Insets.xxl),+ children: [+ GroupSection(+ title: '服务器',+ footnote: '服务器只负责让设备找到彼此、协商直连。设备之间传输的内容它看不到。',+ child: GroupBox(children: [+ SettingRow(+ title: '信令服务器地址',+ description: '按回车保存,保存后立即重新连接',+ child: SizedBox(+ width: 290,+ child: TextField(+ controller: _serverController,+ style: context.text.bodyMedium?.copyWith(fontFamily: monoFamily, fontSize: 12),+ decoration: InputDecoration(+ hintText: 'ws://服务器地址:8787/signal',+ suffixIcon: _serverDirty+ ? IconButton(+ tooltip: '保存',+ icon: Icon(CupertinoIcons.checkmark, size: 14, color: p.accent),+ onPressed: () => _saveServer(state, cfg),+ )+ : null,+ ),+ onChanged: (_) => setState(() => _serverDirty = true),+ onSubmitted: (_) => _saveServer(state, cfg),+ ),+ ),+ ),+ SettingRow(+ title: '连接状态',+ description: connected ? '已连接到信令服务器' : '连不上服务器。检查地址是否正确、服务器是否在运行。',+ child: StatusDot(+ color: connected ? p.online : p.danger,+ label: connected ? '已连接' : '未连接',+ ),+ ),+ ]),+ ),+ GroupSection(+ title: '这台 Mac',+ child: GroupBox(children: [+ SettingRow(+ title: '设备名称',+ description: '显示在其他设备的列表里',+ child: SizedBox(+ width: 220,+ child: TextField(+ controller: _nameController,+ decoration: InputDecoration(+ suffixIcon: _nameDirty+ ? IconButton(+ tooltip: '保存',+ icon: Icon(CupertinoIcons.checkmark, size: 14, color: p.accent),+ onPressed: () => _saveName(state, cfg),+ )+ : null,+ ),+ onChanged: (_) => setState(() => _nameDirty = true),+ onSubmitted: (_) => _saveName(state, cfg),+ ),+ ),+ ),+ ]),+ ),+ GroupSection(+ title: '同步',+ footnote: '小于阈值的内容在复制时直接推送到其他设备;超过阈值的只同步一条记录,'+ '需要时在「复制记录」里点「拉取到本机」,避免大文件无谓地占用带宽和磁盘。',+ child: GroupBox(children: [+ SettingRow(+ title: '自动同步上限',+ description: '超过这个大小的文件改为手动拉取',+ child: _ThresholdSelector(+ value: cfg.autoSyncThresholdBytes.toInt(),+ onChanged: (v) => _update(state, cfg..autoSyncThresholdBytes = Int64(v)),+ ),+ ),+ SettingRow(+ title: '收到后直接写入剪贴板',+ description: '关闭后,需要在「复制记录」里手动放入剪贴板',+ child: SmallSwitch(+ value: cfg.autoApplyToClipboard,+ onChanged: (v) => _update(state, cfg..autoApplyToClipboard = v),+ ),+ ),+ ]),+ ),+ GroupSection(+ title: '同步哪些内容',+ child: GroupBox(children: [+ _ToggleRow(+ title: '文件与文件夹',+ value: cfg.syncFile,+ onChanged: (v) => _update(state, cfg..syncFile = v),+ ),+ _ToggleRow(+ title: '纯文本',+ value: cfg.syncText,+ onChanged: (v) => _update(state, cfg..syncText = v),+ ),+ _ToggleRow(+ title: '带格式的文本',+ value: cfg.syncHtml,+ onChanged: (v) => _update(state, cfg..syncHtml = v),+ ),+ _ToggleRow(+ title: '图片与截图',+ value: cfg.syncImage,+ onChanged: (v) => _update(state, cfg..syncImage = v),+ ),+ ]),+ ),+ GroupSection(+ title: '存储',+ footnote: '到期的记录与缓存文件会被自动清理。',+ child: GroupBox(children: [+ SettingRow(+ title: '记录保留',+ child: _DurationSelector(+ seconds: cfg.historyTtlSeconds.toInt(),+ onChanged: (v) => _update(state, cfg..historyTtlSeconds = Int64(v)),+ ),+ ),+ SettingRow(+ title: '缓存文件保留',+ description: '不会超过记录的保留时长',+ child: _DurationSelector(+ seconds: cfg.cacheTtlSeconds.toInt(),+ onChanged: (v) => _update(state, cfg..cacheTtlSeconds = Int64(v)),+ ),+ ),+ SettingRow(+ title: '缓存占用',+ child: Text(+ humanBytes(state.status?.cacheBytesUsed.toInt() ?? 0),+ style: context.text.bodyMedium?.copyWith(color: p.textDim),+ ),+ ),+ ]),+ ),+ if (state.service.available)+ GroupSection(+ title: '后台同步',+ footnote: '停用后不再同步,也不会开机启动。历史记录与配对关系会保留,重新打开 App 即可再次启用。',+ child: GroupBox(children: [+ SettingRow(+ title: '后台服务',+ description: '随系统登录自动启动,关掉窗口也照常同步',+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ OutlinedButton(+ onPressed: () => _serviceAction(state.restartService, '后台服务已重新启动'),+ child: const Text('重新启动'),+ ),+ const SizedBox(width: Insets.sm),+ OutlinedButton(+ onPressed: () => _confirmDisable(state),+ child: const Text('停用…'),+ ),+ ],+ ),+ ),+ ]),+ ),+ GroupSection(+ title: '关于',+ child: GroupBox(children: [+ SettingRow(+ title: 'CopySync ${state.status?.version ?? ''}',+ description: '开源软件,MIT 许可',+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ TextButton(+ onPressed: () => _open('https://baiyuze.github.io/copysync/'),+ child: const Text('项目主页'),+ ),+ TextButton(+ onPressed: () => _open('https://github.com/baiyuze/copysync/issues'),+ child: const Text('反馈问题'),+ ),+ ],+ ),+ ),+ ]),+ ),+ ],+ ),+ ),+ ],+ );+ }++ static void _open(String url) => Process.run('open', [url]);++ Future<void> _serviceAction(Future<void> Function() action, String message) async {+ try {+ await action();+ if (mounted) showToast(context, message);+ } catch (e) {+ if (mounted) showToast(context, AppState.describeError(e), error: true);+ }+ }++ Future<void> _confirmDisable(AppState state) async {+ final ok = await showDialog<bool>(+ context: context,+ builder: (ctx) => AlertDialog(+ title: const Text('停用后台同步?'),+ content: const Text('这台 Mac 将停止同步,也不再开机启动。历史记录和配对关系会保留。'),+ actions: [+ OutlinedButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('取消')),+ FilledButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('停用')),+ ],+ ),+ );+ if (ok == true) await _serviceAction(state.disableService, '后台同步已停用');+ }++ Future<void> _saveServer(AppState state, Config cfg) async {+ final url = _serverController.text.trim();+ if (!url.startsWith('ws://') && !url.startsWith('wss://')) {+ showToast(context, '地址需以 ws:// 或 wss:// 开头', error: true);+ return;+ }+ setState(() => _serverDirty = false);+ _lastLoadedServer = url;+ await _update(state, cfg..signalingUrl = url, message: '服务器地址已更新,正在重连');+ }++ Future<void> _saveName(AppState state, Config cfg) async {+ final name = _nameController.text.trim();+ if (name.isEmpty) return;+ setState(() => _nameDirty = false);+ _lastLoadedName = name;+ await _update(state, cfg..deviceName = name, message: '设备名称已更新');+ }++ Future<void> _update(AppState state, Config next, {String? message}) async {+ try {+ await state.updateConfig(next);+ if (mounted && message != null) showToast(context, message);+ } catch (e) {+ if (mounted) showToast(context, AppState.describeError(e), error: true);+ }+ }+}++class _ToggleRow extends StatelessWidget {+ const _ToggleRow({+ required this.title,+ required this.value,+ required this.onChanged,+ });++ final String title;+ final bool value;+ final ValueChanged<bool> onChanged;++ @override+ Widget build(BuildContext context) {+ return SettingRow(+ title: title,+ child: SmallSwitch(value: value, onChanged: onChanged),+ );+ }+}++class _ThresholdSelector extends StatelessWidget {+ const _ThresholdSelector({required this.value, required this.onChanged});++ final int value;+ final ValueChanged<int> onChanged;++ static const _options = <int, String>{+ 1 << 20: '1 MB',+ 10 << 20: '10 MB',+ 50 << 20: '50 MB',+ 200 << 20: '200 MB',+ 1024 << 20: '1 GB',+ };++ @override+ Widget build(BuildContext context) {+ // 当前值不在预设里时补一项,避免 DropdownButton 因找不到值而报错+ final options = Map<int, String>.from(_options);+ options.putIfAbsent(value, () => humanBytes(value));++ return _Dropdown<int>(+ value: value,+ items: options.entries.toList()..sort((a, b) => a.key.compareTo(b.key)),+ onChanged: onChanged,+ );+ }+}++class _DurationSelector extends StatelessWidget {+ const _DurationSelector({required this.seconds, required this.onChanged});++ final int seconds;+ final ValueChanged<int> onChanged;++ static const _options = <int, String>{+ 3600: '1 小时',+ 86400: '1 天',+ 3 * 86400: '3 天',+ 7 * 86400: '7 天',+ 30 * 86400: '30 天',+ };++ @override+ Widget build(BuildContext context) {+ final options = Map<int, String>.from(_options);+ options.putIfAbsent(seconds, () => '${(seconds / 3600).round()} 小时');++ return _Dropdown<int>(+ value: seconds,+ items: options.entries.toList()..sort((a, b) => a.key.compareTo(b.key)),+ onChanged: onChanged,+ );+ }+}++/// macOS 弹出按钮:当前值 + 上下箭头,点开是菜单。+class _Dropdown<T> extends StatelessWidget {+ const _Dropdown({+ required this.value,+ required this.items,+ required this.onChanged,+ });++ final T value;+ final List<MapEntry<T, String>> items;+ final ValueChanged<T> onChanged;++ @override+ Widget build(BuildContext context) {+ final p = context.palette;+ final current = items.firstWhere((e) => e.key == value, orElse: () => items.first);+ return PopupMenuButton<T>(+ tooltip: '',+ initialValue: value,+ position: PopupMenuPosition.under,+ onSelected: onChanged,+ itemBuilder: (_) => [+ for (final e in items) PopupMenuItem(value: e.key, height: 32, child: Text(e.value)),+ ],+ child: Container(+ padding: const EdgeInsets.fromLTRB(10, 5, 8, 5),+ decoration: BoxDecoration(+ color: p.surface,+ borderRadius: BorderRadius.circular(Radii.sm),+ border: Border.all(color: p.border),+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(current.value, style: context.text.labelLarge),+ const SizedBox(width: 6),+ Icon(CupertinoIcons.chevron_up_chevron_down, size: 12, color: p.textDim),+ ],+ ),+ ),+ );+ }+}diff --git a/ui/lib/theme.dart b/ui/lib/theme.dartnew file mode 100644index 0000000..f893a2b--- /dev/null+++ b/ui/lib/theme.dart@@ -0,0 +1,299 @@+import 'package:flutter/material.dart';++/// CopySync 的设计系统。+///+/// 这是一个常驻后台的系统工具,界面要像 macOS 自带的应用一样安静:+/// 大面积中性的石墨灰,强调色只出现在按钮、选中态和链接上。+/// 不用渐变、不用彩色图标底、不用发光——这些都会让工具显得像一个营销页面。+abstract final class AppColors {+ // 强调色:比系统蓝略深,白底上的文字对比度达到 WCAG AA+ static const accent = Color(0xFF0A66D8);+ static const accentDark = Color(0xFF3B8BEB);+}++/// 间距阶梯。全应用只用这几个值,避免出现 7px、13px 这类随手写的数字,+/// 那是界面显得"不够整齐"的主要来源。+abstract final class Insets {+ static const xs = 4.0;+ static const sm = 8.0;+ static const md = 12.0;+ static const lg = 16.0;+ static const xl = 24.0;+ static const xxl = 32.0;+}++/// 圆角按层级区分:控件小、分组容器中、对话框大。+abstract final class Radii {+ static const sm = 6.0;+ static const md = 10.0;+ static const lg = 14.0;+}++/// 语义化的颜色角色。页面代码只用这些名字,不判断亮暗模式。+@immutable+class AppPalette extends ThemeExtension<AppPalette> {+ const AppPalette({+ required this.accent,+ required this.background,+ required this.sidebar,+ required this.surface,+ required this.border,+ required this.separator,+ required this.text,+ required this.textDim,+ required this.textFaint,+ required this.selection,+ required this.hover,+ required this.fill,+ required this.online,+ required this.warning,+ required this.danger,+ });++ final Color accent;+ final Color background; // 内容区底色+ final Color sidebar;+ final Color surface; // 分组容器、对话框+ final Color border; // 容器外框+ final Color separator; // 容器内的行分隔线+ final Color text;+ final Color textDim;+ final Color textFaint;+ final Color selection; // 侧边栏选中项+ final Color hover;+ final Color fill; // 分段控件轨道、代码块等浅色填充+ final Color online;+ final Color warning;+ final Color danger;++ static const light = AppPalette(+ accent: AppColors.accent,+ background: Color(0xFFF5F5F4),+ sidebar: Color(0xFFEBEBE9),+ surface: Color(0xFFFFFFFF),+ border: Color(0xFFE0E0DD),+ separator: Color(0xFFECECEA),+ text: Color(0xFF1D1D1F),+ textDim: Color(0xFF6E6E73),+ textFaint: Color(0xFFA1A1A6),+ selection: Color(0xFFDCDCD9),+ hover: Color(0x0A000000),+ fill: Color(0xFFEEEEEC),+ // 状态色取 Apple 的深色变体:浅底上作为文字也清晰可读+ online: Color(0xFF248A3D),+ warning: Color(0xFFB25000),+ danger: Color(0xFFD70015),+ );++ static const dark = AppPalette(+ accent: AppColors.accentDark,+ background: Color(0xFF1C1C1E),+ sidebar: Color(0xFF232325),+ surface: Color(0xFF2A2A2C),+ border: Color(0xFF3A3A3C),+ separator: Color(0xFF333335),+ text: Color(0xFFF5F5F7),+ textDim: Color(0xFF98989D),+ textFaint: Color(0xFF636366),+ selection: Color(0xFF3A3A3C),+ hover: Color(0x0FFFFFFF),+ fill: Color(0xFF323234),+ online: Color(0xFF32D74B),+ warning: Color(0xFFFF9F0A),+ danger: Color(0xFFFF453A),+ );++ @override+ AppPalette copyWith() => this;++ @override+ AppPalette lerp(AppPalette? other, double t) {+ if (other == null) return this;+ Color l(Color a, Color b) => Color.lerp(a, b, t)!;+ return AppPalette(+ accent: l(accent, other.accent),+ background: l(background, other.background),+ sidebar: l(sidebar, other.sidebar),+ surface: l(surface, other.surface),+ border: l(border, other.border),+ separator: l(separator, other.separator),+ text: l(text, other.text),+ textDim: l(textDim, other.textDim),+ textFaint: l(textFaint, other.textFaint),+ selection: l(selection, other.selection),+ hover: l(hover, other.hover),+ fill: l(fill, other.fill),+ online: l(online, other.online),+ warning: l(warning, other.warning),+ danger: l(danger, other.danger),+ );+ }+}++extension PaletteAccess on BuildContext {+ AppPalette get palette => Theme.of(this).extension<AppPalette>()!;+ TextTheme get text => Theme.of(this).textTheme;+}++/// 等宽字体:配对码、指纹、服务器地址这类需要逐字符核对的内容。+const monoFamily = 'Menlo';++/// [fontFamily] 只给截图渲染用:App 本身不指定,跟随系统字体(SF Pro 与苹方)。+ThemeData buildTheme(Brightness brightness, {String? fontFamily, List<String>? fontFamilyFallback}) {+ final dark = brightness == Brightness.dark;+ final p = dark ? AppPalette.dark : AppPalette.light;++ final scheme = ColorScheme.fromSeed(seedColor: p.accent, brightness: brightness).copyWith(+ primary: p.accent,+ onPrimary: Colors.white,+ surface: p.background,+ onSurface: p.text,+ error: p.danger,+ );++ // 字号偏小、字重克制:桌面工具的信息密度应当高于移动应用。+ // 层级靠字号与字重区分,不靠颜色。+ var textTheme = TextTheme(+ headlineSmall: TextStyle(+ fontSize: 22, fontWeight: FontWeight.w600, color: p.text, letterSpacing: -0.4),+ titleMedium: TextStyle(+ fontSize: 15, fontWeight: FontWeight.w600, color: p.text, letterSpacing: -0.2),+ titleSmall: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: p.text),+ // 输入框默认用 bodyLarge,不定义的话会是移动端的 16px,比周围的字大一号+ bodyLarge: TextStyle(fontSize: 13, color: p.text),+ bodyMedium: TextStyle(fontSize: 13, color: p.text, height: 1.45),+ bodySmall: TextStyle(fontSize: 12, color: p.textDim, height: 1.4),+ labelLarge: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: p.text),+ labelMedium: TextStyle(fontSize: 12, fontWeight: FontWeight.w500, color: p.textDim),+ labelSmall: TextStyle(fontSize: 11, fontWeight: FontWeight.w500, color: p.textDim),+ );+ if (fontFamily != null) {+ textTheme = textTheme.apply(fontFamily: fontFamily, fontFamilyFallback: fontFamilyFallback);+ }++ final controlShape = RoundedRectangleBorder(borderRadius: BorderRadius.circular(Radii.sm));+ const controlPadding = EdgeInsets.symmetric(horizontal: 14, vertical: 9);++ return ThemeData(+ useMaterial3: true,+ brightness: brightness,+ colorScheme: scheme,+ scaffoldBackgroundColor: p.background,+ canvasColor: p.surface,+ textTheme: textTheme,+ fontFamily: fontFamily,+ fontFamilyFallback: fontFamilyFallback,+ extensions: [p],+ splashFactory: NoSplash.splashFactory, // 桌面端没有触摸涟漪+ highlightColor: Colors.transparent,+ hoverColor: p.hover,+ dividerTheme: DividerThemeData(color: p.separator, thickness: 1, space: 1),+ iconTheme: IconThemeData(color: p.textDim, size: 16),+ filledButtonTheme: FilledButtonThemeData(+ style: FilledButton.styleFrom(+ backgroundColor: p.accent,+ foregroundColor: Colors.white,+ disabledBackgroundColor: p.fill,+ disabledForegroundColor: p.textFaint,+ shape: controlShape,+ padding: controlPadding,+ minimumSize: const Size(0, 32),+ textStyle: textTheme.labelLarge,+ elevation: 0,+ ),+ ),+ outlinedButtonTheme: OutlinedButtonThemeData(+ style: OutlinedButton.styleFrom(+ foregroundColor: p.text,+ backgroundColor: p.surface,+ shape: controlShape,+ padding: controlPadding,+ minimumSize: const Size(0, 32),+ textStyle: textTheme.labelLarge,+ side: BorderSide(color: p.border),+ ),+ ),+ textButtonTheme: TextButtonThemeData(+ style: TextButton.styleFrom(+ foregroundColor: p.accent,+ shape: controlShape,+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),+ minimumSize: const Size(0, 30),+ textStyle: textTheme.labelLarge,+ ),+ ),+ inputDecorationTheme: InputDecorationTheme(+ isDense: true,+ filled: true,+ fillColor: p.surface,+ contentPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 9),+ border: OutlineInputBorder(+ borderRadius: BorderRadius.circular(Radii.sm),+ borderSide: BorderSide(color: p.border),+ ),+ enabledBorder: OutlineInputBorder(+ borderRadius: BorderRadius.circular(Radii.sm),+ borderSide: BorderSide(color: p.border),+ ),+ focusedBorder: OutlineInputBorder(+ borderRadius: BorderRadius.circular(Radii.sm),+ borderSide: BorderSide(color: p.accent, width: 1.5),+ ),+ hintStyle: textTheme.bodyMedium?.copyWith(color: p.textFaint),+ ),+ switchTheme: SwitchThemeData(+ thumbColor: const WidgetStatePropertyAll(Colors.white),+ trackColor: WidgetStateProperty.resolveWith(+ (s) => s.contains(WidgetState.selected) ? p.accent : p.selection),+ trackOutlineColor: const WidgetStatePropertyAll(Colors.transparent),+ materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,+ ),+ // Material 3 的对话框与菜单默认没有阴影,只靠颜色区分层级;+ // macOS 的弹窗和菜单都有明显的投影,这里补上+ dialogTheme: DialogThemeData(+ backgroundColor: p.surface,+ surfaceTintColor: Colors.transparent,+ elevation: 18,+ shadowColor: Color(dark ? 0x99000000 : 0x40000000),+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Radii.lg)),+ titleTextStyle: textTheme.titleMedium,+ contentTextStyle: textTheme.bodyMedium?.copyWith(color: p.textDim),+ ),+ popupMenuTheme: PopupMenuThemeData(+ color: p.surface,+ surfaceTintColor: Colors.transparent,+ elevation: 8,+ shadowColor: Color(dark ? 0x99000000 : 0x33000000),+ textStyle: textTheme.bodyMedium,+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(Radii.md),+ side: BorderSide(color: p.border),+ ),+ ),+ snackBarTheme: SnackBarThemeData(+ behavior: SnackBarBehavior.floating,+ backgroundColor: dark ? const Color(0xFF3A3A3C) : const Color(0xFF2C2C2E),+ contentTextStyle: const TextStyle(fontSize: 13, color: Colors.white),+ elevation: 6,+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Radii.md)),+ ),+ tooltipTheme: TooltipThemeData(+ decoration: BoxDecoration(+ color: dark ? const Color(0xFF3A3A3C) : const Color(0xFF2C2C2E),+ borderRadius: BorderRadius.circular(Radii.sm),+ ),+ textStyle: const TextStyle(fontSize: 12, color: Colors.white),+ waitDuration: const Duration(milliseconds: 500),+ ),+ progressIndicatorTheme: ProgressIndicatorThemeData(+ color: p.accent,+ linearTrackColor: p.fill,+ circularTrackColor: Colors.transparent,+ ),+ scrollbarTheme: ScrollbarThemeData(+ thickness: const WidgetStatePropertyAll(6),+ radius: const Radius.circular(3),+ thumbColor: WidgetStatePropertyAll(p.textFaint.withValues(alpha: 0.5)),+ ),+ );+}diff --git a/ui/lib/widgets/common.dart b/ui/lib/widgets/common.dartnew file mode 100644index 0000000..2970f74--- /dev/null+++ b/ui/lib/widgets/common.dart@@ -0,0 +1,445 @@+import 'package:flutter/cupertino.dart';+import 'package:flutter/material.dart';++import '../theme.dart';++/// 页面统一的标题区。保证各页视觉节奏一致。+class PageHeader extends StatelessWidget {+ const PageHeader({+ super.key,+ required this.title,+ this.subtitle,+ this.actions = const [],+ });++ final String title;+ final String? subtitle;+ final List<Widget> actions;++ @override+ Widget build(BuildContext context) {+ return Padding(+ // 顶部留出 macOS 红绿灯所在的标题栏高度+ padding: const EdgeInsets.fromLTRB(Insets.xl, 44, Insets.xl, Insets.lg),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.end,+ children: [+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(title, style: context.text.headlineSmall),+ if (subtitle != null) ...[+ const SizedBox(height: 2),+ Text(subtitle!, style: context.text.bodySmall),+ ],+ ],+ ),+ ),+ for (final a in actions) ...[const SizedBox(width: Insets.sm), a],+ ],+ ),+ );+ }+}++/// 分组容器:白底、细边框,内部各行之间用缩进的细线分隔。+/// 与「系统设置」的分组列表同一种做法——用分隔线而不是一张张独立卡片。+class GroupBox extends StatelessWidget {+ const GroupBox({super.key, required this.children, this.dividerIndent = Insets.lg});++ final List<Widget> children;+ final double dividerIndent;++ @override+ Widget build(BuildContext context) {+ return Container(+ clipBehavior: Clip.antiAlias,+ decoration: BoxDecoration(+ color: context.palette.surface,+ borderRadius: BorderRadius.circular(Radii.md),+ border: Border.all(color: context.palette.border),+ ),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ for (var i = 0; i < children.length; i++) ...[+ if (i > 0) Divider(indent: dividerIndent),+ children[i],+ ],+ ],+ ),+ );+ }+}++/// 分组的标题与脚注。+class GroupSection extends StatelessWidget {+ const GroupSection({super.key, required this.title, required this.child, this.footnote});++ final String title;+ final String? footnote;+ final Widget child;++ @override+ Widget build(BuildContext context) {+ return Padding(+ padding: const EdgeInsets.only(bottom: Insets.xl),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Padding(+ padding: const EdgeInsets.only(left: 2, bottom: Insets.sm),+ child: Text(title, style: context.text.titleSmall),+ ),+ child,+ if (footnote != null)+ Padding(+ padding: const EdgeInsets.only(left: 2, top: Insets.sm, right: Insets.xl),+ child: Text(footnote!, style: context.text.bodySmall),+ ),+ ],+ ),+ );+ }+}++/// 设置项行:左侧标题与说明,右侧控件。+class SettingRow extends StatelessWidget {+ const SettingRow({super.key, required this.title, required this.child, this.description});++ final String title;+ final String? description;+ final Widget child;++ @override+ Widget build(BuildContext context) {+ return ConstrainedBox(+ constraints: const BoxConstraints(minHeight: 48),+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: Insets.lg, vertical: 10),+ child: Row(+ children: [+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(title, style: context.text.labelLarge),+ if (description != null) ...[+ const SizedBox(height: 2),+ Text(description!, style: context.text.bodySmall),+ ],+ ],+ ),+ ),+ const SizedBox(width: Insets.lg),+ child,+ ],+ ),+ ),+ );+ }+}++/// macOS 尺寸的开关:Material 默认的开关对桌面来说太大。+class SmallSwitch extends StatelessWidget {+ const SmallSwitch({super.key, required this.value, required this.onChanged});++ final bool value;+ final ValueChanged<bool>? onChanged;++ @override+ Widget build(BuildContext context) {+ return SizedBox(+ height: 24,+ child: FittedBox(+ child: Switch(value: value, onChanged: onChanged),+ ),+ );+ }+}++/// 分段控件,对应 macOS 的 NSSegmentedControl:浅灰轨道,选中段浮起为白色。+class Segmented<T> extends StatelessWidget {+ const Segmented({+ super.key,+ required this.value,+ required this.segments,+ required this.onChanged,+ });++ final T value;+ final List<(T, String)> segments;+ final ValueChanged<T> onChanged;++ @override+ Widget build(BuildContext context) {+ final p = context.palette;+ return Container(+ padding: const EdgeInsets.all(2),+ decoration: BoxDecoration(+ color: p.fill,+ borderRadius: BorderRadius.circular(Radii.sm + 1),+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ for (final (v, label) in segments)+ MouseRegion(+ cursor: SystemMouseCursors.click,+ child: GestureDetector(+ onTap: () => onChanged(v),+ child: AnimatedContainer(+ duration: const Duration(milliseconds: 120),+ padding: const EdgeInsets.symmetric(horizontal: Insets.md, vertical: 4),+ decoration: BoxDecoration(+ color: v == value ? p.surface : Colors.transparent,+ borderRadius: BorderRadius.circular(Radii.sm - 1),+ boxShadow: v == value+ ? const [+ BoxShadow(+ color: Color(0x1A000000), blurRadius: 2, offset: Offset(0, 1)),+ ]+ : null,+ ),+ child: Text(+ label,+ style: context.text.labelMedium?.copyWith(+ color: v == value ? p.text : p.textDim,+ ),+ ),+ ),+ ),+ ),+ ],+ ),+ );+ }+}++/// 空状态。给出下一步该做什么,而不是只说"暂无数据"。+class EmptyState extends StatelessWidget {+ const EmptyState({+ super.key,+ required this.icon,+ required this.title,+ this.description,+ this.action,+ });++ final IconData icon;+ final String title;+ final String? description;+ final Widget? action;++ @override+ Widget build(BuildContext context) {+ return Center(+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 340),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(icon, size: 36, color: context.palette.textFaint),+ const SizedBox(height: Insets.lg),+ Text(title, style: context.text.titleMedium, textAlign: TextAlign.center),+ if (description != null) ...[+ const SizedBox(height: 6),+ Text(description!, style: context.text.bodySmall, textAlign: TextAlign.center),+ ],+ if (action != null) ...[+ const SizedBox(height: Insets.xl),+ action!,+ ],+ ],+ ),+ ),+ );+ }+}++/// 行内提示条:说明问题,并给出解决它的按钮。+class Notice extends StatelessWidget {+ const Notice({+ super.key,+ required this.title,+ required this.message,+ this.action,+ this.icon = CupertinoIcons.exclamationmark_circle,+ this.iconColor,+ });++ final String title;+ final String message;+ final Widget? action;+ final IconData icon;+ final Color? iconColor;++ @override+ Widget build(BuildContext context) {+ final p = context.palette;+ return Container(+ padding: const EdgeInsets.fromLTRB(Insets.lg, Insets.md, Insets.md, Insets.md),+ decoration: BoxDecoration(+ color: p.surface,+ borderRadius: BorderRadius.circular(Radii.md),+ border: Border.all(color: p.border),+ ),+ child: Row(+ children: [+ Icon(icon, size: 18, color: iconColor ?? p.warning),+ const SizedBox(width: Insets.md),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(title, style: context.text.labelLarge),+ const SizedBox(height: 2),+ Text(message, style: context.text.bodySmall),+ ],+ ),+ ),+ if (action != null) ...[const SizedBox(width: Insets.md), action!],+ ],+ ),+ );+ }+}++/// 状态圆点 + 文字。设备在线状态、连接状态都用它,保持一致。+class StatusDot extends StatelessWidget {+ const StatusDot({super.key, required this.color, required this.label, this.labelColor});++ final Color color;+ final String label;+ final Color? labelColor;++ @override+ Widget build(BuildContext context) {+ return Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Container(+ width: 7,+ height: 7,+ decoration: BoxDecoration(color: color, shape: BoxShape.circle),+ ),+ const SizedBox(width: 6),+ Text(label, style: context.text.bodySmall?.copyWith(color: labelColor)),+ ],+ );+ }+}++/// App 图标。侧边栏、欢迎页、关于里都用同一张图,而不是另画一个符号。+class AppMark extends StatelessWidget {+ const AppMark({super.key, this.size = 20});++ final double size;++ @override+ Widget build(BuildContext context) {+ return Image.asset(+ 'assets/app_icon.png',+ width: size,+ height: size,+ filterQuality: FilterQuality.medium,+ );+ }+}++/// 可点击的图标按钮,悬停时出现浅色底。+class IconAction extends StatefulWidget {+ const IconAction({super.key, required this.icon, required this.tooltip, this.onTap});++ final IconData icon;+ final String tooltip;+ final VoidCallback? onTap;++ @override+ State<IconAction> createState() => _IconActionState();+}++class _IconActionState extends State<IconAction> {+ bool _hovered = false;++ @override+ Widget build(BuildContext context) {+ final p = context.palette;+ return Tooltip(+ message: widget.tooltip,+ child: MouseRegion(+ cursor: SystemMouseCursors.click,+ onEnter: (_) => setState(() => _hovered = true),+ onExit: (_) => setState(() => _hovered = false),+ child: GestureDetector(+ onTap: widget.onTap,+ child: Container(+ width: 28,+ height: 28,+ decoration: BoxDecoration(+ color: _hovered ? p.hover : Colors.transparent,+ borderRadius: BorderRadius.circular(Radii.sm),+ ),+ child: Icon(widget.icon, size: 16, color: _hovered ? p.text : p.textDim),+ ),+ ),+ ),+ );+ }+}++/// 字节数的可读形式。+String humanBytes(int n) {+ if (n < 1024) return '$n B';+ const units = ['KB', 'MB', 'GB', 'TB'];+ var v = n / 1024;+ var i = 0;+ while (v >= 1024 && i < units.length - 1) {+ v /= 1024;+ i++;+ }+ return '${v.toStringAsFixed(v >= 100 ? 0 : 1)} ${units[i]}';+}++/// 相对时间。刚刚发生的事用"刚刚"比"14:03:22"更符合直觉。+String relativeTime(DateTime t, {DateTime? now}) {+ final d = (now ?? DateTime.now()).difference(t);+ if (d.inSeconds < 10) return '刚刚';+ if (d.inMinutes < 1) return '${d.inSeconds} 秒前';+ if (d.inHours < 1) return '${d.inMinutes} 分钟前';+ if (d.inDays < 1) return '${d.inHours} 小时前';+ if (d.inDays < 7) return '${d.inDays} 天前';+ return '${t.month}月${t.day}日';+}++void showToast(BuildContext context, String message, {bool error = false}) {+ final p = context.palette;+ ScaffoldMessenger.of(context)+ ..hideCurrentSnackBar()+ ..showSnackBar(SnackBar(+ content: Row(+ children: [+ Icon(+ error ? CupertinoIcons.exclamationmark_circle : CupertinoIcons.checkmark_circle,+ size: 16,+ color: error ? PaletteColors.onDark(p.danger) : PaletteColors.onDark(p.online),+ ),+ const SizedBox(width: Insets.sm),+ Expanded(child: Text(message)),+ ],+ ),+ duration: const Duration(seconds: 3),+ width: 360,+ ));+}++/// 提示条是深色底,浅色模式下的深绿、深红在上面看不清,换成亮色版本。+abstract final class PaletteColors {+ static Color onDark(Color c) {+ if (c == AppPalette.light.online) return AppPalette.dark.online;+ if (c == AppPalette.light.danger) return AppPalette.dark.danger;+ return c;+ }+}diff --git a/ui/lib/widgets/pairing_dialog.dart b/ui/lib/widgets/pairing_dialog.dartnew file mode 100644index 0000000..30c2455--- /dev/null+++ b/ui/lib/widgets/pairing_dialog.dart@@ -0,0 +1,388 @@+import 'package:flutter/cupertino.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../app_state.dart';+import '../gen/copysync/v1/daemon.pb.dart';+import '../main.dart';+import '../theme.dart';+import 'common.dart';++/// 配对对话框:既能生成配对码,也能输入对方的配对码。+///+/// 两种角色放在一个对话框里切换,因为用户在打开它之前+/// 往往还没想好"我这边生成还是那边生成"。+class PairingDialog extends StatefulWidget {+ const PairingDialog({super.key});++ @override+ State<PairingDialog> createState() => _PairingDialogState();+}++class _PairingDialogState extends State<PairingDialog> {+ int _tab = 0;++ @override+ Widget build(BuildContext context) {+ return Dialog(+ child: SizedBox(+ width: 420,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(Insets.xl, Insets.lg, Insets.md, 0),+ child: Row(+ children: [+ Expanded(child: Text('添加设备', style: context.text.titleMedium)),+ IconAction(+ icon: CupertinoIcons.xmark,+ tooltip: '关闭',+ onTap: () => Navigator.pop(context),+ ),+ ],+ ),+ ),+ const SizedBox(height: Insets.md),+ Segmented<int>(+ value: _tab,+ segments: const [(0, '生成配对码'), (1, '输入配对码')],+ onChanged: (t) => setState(() => _tab = t),+ ),+ SizedBox(+ height: 272,+ // IndexedStack 让两页都常驻:来回切换不会重新生成配对码+ child: IndexedStack(+ index: _tab,+ children: const [_GenerateTab(), _JoinTab()],+ ),+ ),+ ],+ ),+ ),+ );+ }+}++class _GenerateTab extends StatefulWidget {+ const _GenerateTab();++ @override+ State<_GenerateTab> createState() => _GenerateTabState();+}++class _GenerateTabState extends State<_GenerateTab> {+ String? _code;+ String? _error;+ bool _loading = false;++ @override+ void initState() {+ super.initState();+ _generate();+ }++ Future<void> _generate() async {+ setState(() {+ _loading = true;+ _error = null;+ });+ try {+ final code = await AppScope.read(context).createPairingCode();+ if (mounted) setState(() => _code = code);+ } catch (e) {+ if (mounted) setState(() => _error = AppState.describeError(e));+ } finally {+ if (mounted) setState(() => _loading = false);+ }+ }++ @override+ Widget build(BuildContext context) {+ final p = context.palette;+ if (_loading) {+ return const Center(child: CircularProgressIndicator(strokeWidth: 2));+ }+ if (_error != null) {+ return Padding(+ padding: const EdgeInsets.all(Insets.xl),+ child: EmptyState(+ icon: CupertinoIcons.exclamationmark_circle,+ title: '没能生成配对码',+ description: _error,+ action: OutlinedButton(onPressed: _generate, child: const Text('重试')),+ ),+ );+ }++ return Padding(+ padding: const EdgeInsets.all(Insets.xl),+ child: Column(+ children: [+ Text('在另一台设备上输入这个配对码', style: context.text.bodySmall),+ const SizedBox(height: Insets.lg),+ // 配对码是本页的主角:放大、等宽、字距拉开,方便照着念+ MouseRegion(+ cursor: SystemMouseCursors.click,+ child: GestureDetector(+ onTap: () async {+ await Clipboard.setData(ClipboardData(text: _code ?? ''));+ if (context.mounted) showToast(context, '配对码已拷贝');+ },+ child: Container(+ width: double.infinity,+ padding: const EdgeInsets.symmetric(vertical: Insets.lg),+ decoration: BoxDecoration(+ color: p.fill,+ borderRadius: BorderRadius.circular(Radii.md),+ ),+ child: Text(+ _code ?? '',+ textAlign: TextAlign.center,+ style: TextStyle(+ fontSize: 34,+ fontWeight: FontWeight.w600,+ fontFamily: monoFamily,+ letterSpacing: 10,+ color: p.text,+ ),+ ),+ ),+ ),+ ),+ const SizedBox(height: Insets.sm),+ Text('点击可拷贝,5 分钟内有效', style: context.text.labelSmall),+ const Spacer(),+ Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Icon(CupertinoIcons.lock_shield, size: 15, color: p.textDim),+ const SizedBox(width: Insets.sm),+ Expanded(+ child: Text(+ '对方输入后,两台设备会各自显示一串安全指纹,逐字核对一致再确认。',+ style: context.text.bodySmall,+ ),+ ),+ ],+ ),+ ],+ ),+ );+ }+}++class _JoinTab extends StatefulWidget {+ const _JoinTab();++ @override+ State<_JoinTab> createState() => _JoinTabState();+}++class _JoinTabState extends State<_JoinTab> {+ final _controller = TextEditingController();+ bool _busy = false;+ String? _error;++ @override+ void dispose() {+ _controller.dispose();+ super.dispose();+ }++ Future<void> _submit() async {+ final code = _controller.text.trim();+ if (code.length != 6) {+ setState(() => _error = '配对码是 6 位字母或数字');+ return;+ }+ setState(() {+ _busy = true;+ _error = null;+ });+ try {+ final peer = await AppScope.read(context).redeemPairingCode(code);+ if (!mounted) return;+ Navigator.pop(context);+ await showPairingConfirmDialog(context, peer);+ } catch (e) {+ if (mounted) setState(() => _error = AppState.describeError(e));+ } finally {+ if (mounted) setState(() => _busy = false);+ }+ }++ @override+ Widget build(BuildContext context) {+ final p = context.palette;+ return Padding(+ padding: const EdgeInsets.all(Insets.xl),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Text('输入另一台设备上显示的配对码',+ style: context.text.bodySmall, textAlign: TextAlign.center),+ const SizedBox(height: Insets.lg),+ TextField(+ controller: _controller,+ maxLength: 6,+ textCapitalization: TextCapitalization.characters,+ textAlign: TextAlign.center,+ style: const TextStyle(+ fontSize: 28,+ fontWeight: FontWeight.w600,+ fontFamily: monoFamily,+ letterSpacing: 10,+ ),+ inputFormatters: [+ // 配对码字符集不含易混字符,这里统一转大写并过滤+ FilteringTextInputFormatter.allow(RegExp('[a-zA-Z0-9]')),+ TextInputFormatter.withFunction(+ (_, next) => next.copyWith(text: next.text.toUpperCase()),+ ),+ ],+ decoration: InputDecoration(+ counterText: '',+ hintText: '······',+ hintStyle: TextStyle(letterSpacing: 10, fontSize: 28, color: p.textFaint),+ contentPadding: const EdgeInsets.symmetric(vertical: Insets.md),+ ),+ onSubmitted: (_) => _submit(),+ ),+ if (_error != null) ...[+ const SizedBox(height: Insets.sm),+ Text(+ _error!,+ style: context.text.bodySmall?.copyWith(color: p.danger),+ textAlign: TextAlign.center,+ ),+ ],+ const Spacer(),+ FilledButton(+ onPressed: _busy ? null : _submit,+ child: _busy+ ? const SizedBox(+ width: 14,+ height: 14,+ child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),+ )+ : const Text('继续'),+ ),+ ],+ ),+ );+ }+}++/// 指纹核对对话框。+///+/// 这是整个安全模型里唯一依赖人的环节:信令服务器能替换转发中的公钥,+/// 但无法让两台设备显示出相同的指纹。所以这一步不能做成"点确定就过",+/// 必须让用户真的看见并比对。+Future<void> showPairingConfirmDialog(BuildContext context, Device peer) {+ return showDialog<void>(+ context: context,+ barrierDismissible: false,+ builder: (ctx) => PairingConfirmDialog(peer: peer),+ );+}++class PairingConfirmDialog extends StatefulWidget {+ const PairingConfirmDialog({super.key, required this.peer});++ final Device peer;++ @override+ State<PairingConfirmDialog> createState() => _PairingConfirmDialogState();+}++class _PairingConfirmDialogState extends State<PairingConfirmDialog> {+ bool _busy = false;++ Future<void> _respond(bool accept) async {+ setState(() => _busy = true);+ final state = AppScope.read(context);+ try {+ await state.confirmPairing(widget.peer.pairingSession, accept);+ if (!mounted) return;+ Navigator.pop(context);+ showToast(context, accept ? '配对完成' : '已拒绝配对');+ } catch (e) {+ if (!mounted) return;+ Navigator.pop(context);+ showToast(context, AppState.describeError(e), error: true);+ }+ }++ @override+ Widget build(BuildContext context) {+ final p = context.palette;+ final peer = widget.peer;+ return Dialog(+ child: SizedBox(+ width: 420,+ child: Padding(+ padding: const EdgeInsets.all(Insets.xl),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Text('核对安全指纹', style: context.text.titleMedium),+ const SizedBox(height: 2),+ Text('正在与「${peer.name}」配对', style: context.text.bodySmall),+ const SizedBox(height: Insets.xl),+ Container(+ padding: const EdgeInsets.symmetric(vertical: Insets.lg),+ decoration: BoxDecoration(+ color: p.fill,+ borderRadius: BorderRadius.circular(Radii.md),+ ),+ child: Text(+ peer.publicKeyFingerprint,+ textAlign: TextAlign.center,+ style: TextStyle(+ fontSize: 24,+ fontWeight: FontWeight.w600,+ fontFamily: monoFamily,+ letterSpacing: 2,+ color: p.text,+ ),+ ),+ ),+ const SizedBox(height: Insets.lg),+ Text(+ '确认这串字符与对方屏幕上显示的完全一致。'+ '不一致说明连接可能被第三方篡改,请拒绝。',+ style: context.text.bodySmall,+ ),+ const SizedBox(height: Insets.xl),+ Row(+ children: [+ Expanded(+ child: OutlinedButton(+ onPressed: _busy ? null : () => _respond(false),+ child: const Text('不一致,拒绝'),+ ),+ ),+ const SizedBox(width: Insets.md),+ Expanded(+ child: FilledButton(+ onPressed: _busy ? null : () => _respond(true),+ child: _busy+ ? const SizedBox(+ width: 14,+ height: 14,+ child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),+ )+ : const Text('一致,确认配对'),+ ),+ ),+ ],+ ),+ ],+ ),+ ),+ ),+ );+ }+}diff --git a/ui/macos/.gitignore b/ui/macos/.gitignorenew file mode 100644index 0000000..746adbb--- /dev/null+++ b/ui/macos/.gitignore@@ -0,0 +1,7 @@+# Flutter-related+**/Flutter/ephemeral/+**/Pods/++# Xcode-related+**/dgph+**/xcuserdata/diff --git a/ui/macos/Flutter/Flutter-Debug.xcconfig b/ui/macos/Flutter/Flutter-Debug.xcconfignew file mode 100644index 0000000..c2efd0b--- /dev/null+++ b/ui/macos/Flutter/Flutter-Debug.xcconfig@@ -0,0 +1 @@+#include "ephemeral/Flutter-Generated.xcconfig"diff --git a/ui/macos/Flutter/Flutter-Release.xcconfig b/ui/macos/Flutter/Flutter-Release.xcconfignew file mode 100644index 0000000..c2efd0b--- /dev/null+++ b/ui/macos/Flutter/Flutter-Release.xcconfig@@ -0,0 +1 @@+#include "ephemeral/Flutter-Generated.xcconfig"diff --git a/ui/macos/Flutter/GeneratedPluginRegistrant.swift b/ui/macos/Flutter/GeneratedPluginRegistrant.swiftnew file mode 100644index 0000000..cccf817--- /dev/null+++ b/ui/macos/Flutter/GeneratedPluginRegistrant.swift@@ -0,0 +1,10 @@+//+// Generated file. Do not edit.+//++import FlutterMacOS+import Foundation+++func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {+}diff --git a/ui/macos/Runner.xcodeproj/project.pbxproj b/ui/macos/Runner.xcodeproj/project.pbxprojnew file mode 100644index 0000000..4d5d874--- /dev/null+++ b/ui/macos/Runner.xcodeproj/project.pbxproj@@ -0,0 +1,729 @@+// !$*UTF8*$!+{+ archiveVersion = 1;+ classes = {+ };+ objectVersion = 54;+ objects = {++/* Begin PBXAggregateTarget section */+ 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = {+ isa = PBXAggregateTarget;+ buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */;+ buildPhases = (+ 33CC111E2044C6BF0003C045 /* ShellScript */,+ );+ dependencies = (+ );+ name = "Flutter Assemble";+ productName = FLX;+ };+/* End PBXAggregateTarget section */++/* Begin PBXBuildFile section */+ 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; };+ 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; };+ 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; };+ 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; };+ 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; };+ 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; };+ 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; };+/* End PBXBuildFile section */++/* Begin PBXContainerItemProxy section */+ 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = {+ isa = PBXContainerItemProxy;+ containerPortal = 33CC10E52044A3C60003C045 /* Project object */;+ proxyType = 1;+ remoteGlobalIDString = 33CC10EC2044A3C60003C045;+ remoteInfo = Runner;+ };+ 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = {+ isa = PBXContainerItemProxy;+ containerPortal = 33CC10E52044A3C60003C045 /* Project object */;+ proxyType = 1;+ remoteGlobalIDString = 33CC111A2044C6BA0003C045;+ remoteInfo = FLX;+ };+/* End PBXContainerItemProxy section */++/* Begin PBXCopyFilesBuildPhase section */+ 33CC110E2044A8840003C045 /* Bundle Framework */ = {+ isa = PBXCopyFilesBuildPhase;+ buildActionMask = 2147483647;+ dstPath = "";+ dstSubfolderSpec = 10;+ files = (+ );+ name = "Bundle Framework";+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXCopyFilesBuildPhase section */++/* Begin PBXFileReference section */+ 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };+ 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = "<group>"; };+ 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = "<group>"; };+ 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = "<group>"; };+ 33CC10ED2044A3C60003C045 /* copysync_ui.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "copysync_ui.app"; sourceTree = BUILT_PRODUCTS_DIR; };+ 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };+ 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = "<group>"; };+ 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = "<group>"; };+ 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = "<group>"; };+ 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = "<group>"; };+ 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = "<group>"; };+ 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = "<group>"; };+ 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = "<group>"; };+ 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = "<group>"; };+ 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = "<group>"; };+ 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = "<group>"; };+ 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = "<group>"; };+ 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = "<group>"; };+ 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = "<group>"; };+/* End PBXFileReference section */++/* Begin PBXFrameworksBuildPhase section */+ 331C80D2294CF70F00263BE5 /* Frameworks */ = {+ isa = PBXFrameworksBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ 33CC10EA2044A3C60003C045 /* Frameworks */ = {+ isa = PBXFrameworksBuildPhase;+ buildActionMask = 2147483647;+ files = (+ 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXFrameworksBuildPhase section */++/* Begin PBXGroup section */+ 331C80D6294CF71000263BE5 /* RunnerTests */ = {+ isa = PBXGroup;+ children = (+ 331C80D7294CF71000263BE5 /* RunnerTests.swift */,+ );+ path = RunnerTests;+ sourceTree = "<group>";+ };+ 33BA886A226E78AF003329D5 /* Configs */ = {+ isa = PBXGroup;+ children = (+ 33E5194F232828860026EE4D /* AppInfo.xcconfig */,+ 9740EEB21CF90195004384FC /* Debug.xcconfig */,+ 7AFA3C8E1D35360C0083082E /* Release.xcconfig */,+ 333000ED22D3DE5D00554162 /* Warnings.xcconfig */,+ );+ path = Configs;+ sourceTree = "<group>";+ };+ 33CC10E42044A3C60003C045 = {+ isa = PBXGroup;+ children = (+ 33FAB671232836740065AC1E /* Runner */,+ 33CEB47122A05771004F2AC0 /* Flutter */,+ 331C80D6294CF71000263BE5 /* RunnerTests */,+ 33CC10EE2044A3C60003C045 /* Products */,+ D73912EC22F37F3D000D13A0 /* Frameworks */,+ );+ sourceTree = "<group>";+ };+ 33CC10EE2044A3C60003C045 /* Products */ = {+ isa = PBXGroup;+ children = (+ 33CC10ED2044A3C60003C045 /* copysync_ui.app */,+ 331C80D5294CF71000263BE5 /* RunnerTests.xctest */,+ );+ name = Products;+ sourceTree = "<group>";+ };+ 33CC11242044D66E0003C045 /* Resources */ = {+ isa = PBXGroup;+ children = (+ 33CC10F22044A3C60003C045 /* Assets.xcassets */,+ 33CC10F42044A3C60003C045 /* MainMenu.xib */,+ 33CC10F72044A3C60003C045 /* Info.plist */,+ );+ name = Resources;+ path = ..;+ sourceTree = "<group>";+ };+ 33CEB47122A05771004F2AC0 /* Flutter */ = {+ isa = PBXGroup;+ children = (+ 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */,+ 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */,+ 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */,+ 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */,+ 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */,+ );+ path = Flutter;+ sourceTree = "<group>";+ };+ 33FAB671232836740065AC1E /* Runner */ = {+ isa = PBXGroup;+ children = (+ 33CC10F02044A3C60003C045 /* AppDelegate.swift */,+ 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */,+ 33E51913231747F40026EE4D /* DebugProfile.entitlements */,+ 33E51914231749380026EE4D /* Release.entitlements */,+ 33CC11242044D66E0003C045 /* Resources */,+ 33BA886A226E78AF003329D5 /* Configs */,+ );+ path = Runner;+ sourceTree = "<group>";+ };+ D73912EC22F37F3D000D13A0 /* Frameworks */ = {+ isa = PBXGroup;+ children = (+ );+ name = Frameworks;+ sourceTree = "<group>";+ };+/* End PBXGroup section */++/* Begin PBXNativeTarget section */+ 331C80D4294CF70F00263BE5 /* RunnerTests */ = {+ isa = PBXNativeTarget;+ buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */;+ buildPhases = (+ 331C80D1294CF70F00263BE5 /* Sources */,+ 331C80D2294CF70F00263BE5 /* Frameworks */,+ 331C80D3294CF70F00263BE5 /* Resources */,+ );+ buildRules = (+ );+ dependencies = (+ 331C80DA294CF71000263BE5 /* PBXTargetDependency */,+ );+ name = RunnerTests;+ productName = RunnerTests;+ productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */;+ productType = "com.apple.product-type.bundle.unit-test";+ };+ 33CC10EC2044A3C60003C045 /* Runner */ = {+ isa = PBXNativeTarget;+ buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */;+ buildPhases = (+ 33CC10E92044A3C60003C045 /* Sources */,+ 33CC10EA2044A3C60003C045 /* Frameworks */,+ 33CC10EB2044A3C60003C045 /* Resources */,+ 33CC110E2044A8840003C045 /* Bundle Framework */,+ 3399D490228B24CF009A79C7 /* ShellScript */,+ );+ buildRules = (+ );+ dependencies = (+ 33CC11202044C79F0003C045 /* PBXTargetDependency */,+ );+ name = Runner;+ packageProductDependencies = (+ 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */,+ );+ productName = Runner;+ productReference = 33CC10ED2044A3C60003C045 /* copysync_ui.app */;+ productType = "com.apple.product-type.application";+ };+/* End PBXNativeTarget section */++/* Begin PBXProject section */+ 33CC10E52044A3C60003C045 /* Project object */ = {+ isa = PBXProject;+ attributes = {+ BuildIndependentTargetsInParallel = YES;+ LastSwiftUpdateCheck = 0920;+ LastUpgradeCheck = 1510;+ ORGANIZATIONNAME = "";+ TargetAttributes = {+ 331C80D4294CF70F00263BE5 = {+ CreatedOnToolsVersion = 14.0;+ TestTargetID = 33CC10EC2044A3C60003C045;+ };+ 33CC10EC2044A3C60003C045 = {+ CreatedOnToolsVersion = 9.2;+ LastSwiftMigration = 1100;+ ProvisioningStyle = Automatic;+ SystemCapabilities = {+ com.apple.Sandbox = {+ enabled = 1;+ };+ };+ };+ 33CC111A2044C6BA0003C045 = {+ CreatedOnToolsVersion = 9.2;+ ProvisioningStyle = Manual;+ };+ };+ };+ buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */;+ compatibilityVersion = "Xcode 9.3";+ developmentRegion = en;+ hasScannedForEncodings = 0;+ knownRegions = (+ en,+ Base,+ );+ mainGroup = 33CC10E42044A3C60003C045;+ packageReferences = (+ 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */,+ );+ productRefGroup = 33CC10EE2044A3C60003C045 /* Products */;+ projectDirPath = "";+ projectRoot = "";+ targets = (+ 33CC10EC2044A3C60003C045 /* Runner */,+ 331C80D4294CF70F00263BE5 /* RunnerTests */,+ 33CC111A2044C6BA0003C045 /* Flutter Assemble */,+ );+ };+/* End PBXProject section */++/* Begin PBXResourcesBuildPhase section */+ 331C80D3294CF70F00263BE5 /* Resources */ = {+ isa = PBXResourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ 33CC10EB2044A3C60003C045 /* Resources */ = {+ isa = PBXResourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */,+ 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXResourcesBuildPhase section */++/* Begin PBXShellScriptBuildPhase section */+ 3399D490228B24CF009A79C7 /* ShellScript */ = {+ isa = PBXShellScriptBuildPhase;+ alwaysOutOfDate = 1;+ buildActionMask = 2147483647;+ files = (+ );+ inputFileListPaths = (+ );+ inputPaths = (+ );+ outputFileListPaths = (+ );+ outputPaths = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ shellPath = /bin/sh;+ shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n";+ };+ 33CC111E2044C6BF0003C045 /* ShellScript */ = {+ isa = PBXShellScriptBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ inputFileListPaths = (+ Flutter/ephemeral/FlutterInputs.xcfilelist,+ );+ inputPaths = (+ Flutter/ephemeral/tripwire,+ );+ outputFileListPaths = (+ Flutter/ephemeral/FlutterOutputs.xcfilelist,+ );+ outputPaths = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ shellPath = /bin/sh;+ shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire";+ };+/* End PBXShellScriptBuildPhase section */++/* Begin PBXSourcesBuildPhase section */+ 331C80D1294CF70F00263BE5 /* Sources */ = {+ isa = PBXSourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ 33CC10E92044A3C60003C045 /* Sources */ = {+ isa = PBXSourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */,+ 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */,+ 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXSourcesBuildPhase section */++/* Begin PBXTargetDependency section */+ 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = {+ isa = PBXTargetDependency;+ target = 33CC10EC2044A3C60003C045 /* Runner */;+ targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */;+ };+ 33CC11202044C79F0003C045 /* PBXTargetDependency */ = {+ isa = PBXTargetDependency;+ target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */;+ targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */;+ };+/* End PBXTargetDependency section */++/* Begin PBXVariantGroup section */+ 33CC10F42044A3C60003C045 /* MainMenu.xib */ = {+ isa = PBXVariantGroup;+ children = (+ 33CC10F52044A3C60003C045 /* Base */,+ );+ name = MainMenu.xib;+ path = Runner;+ sourceTree = "<group>";+ };+/* End PBXVariantGroup section */++/* Begin XCBuildConfiguration section */+ 331C80DB294CF71000263BE5 /* Debug */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ BUNDLE_LOADER = "$(TEST_HOST)";+ CURRENT_PROJECT_VERSION = 1;+ GENERATE_INFOPLIST_FILE = YES;+ MARKETING_VERSION = 1.0;+ PRODUCT_BUNDLE_IDENTIFIER = com.copysync.copysyncUi.RunnerTests;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SWIFT_VERSION = 5.0;+ TEST_HOST = "$(BUILT_PRODUCTS_DIR)/copysync_ui.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/copysync_ui";+ };+ name = Debug;+ };+ 331C80DC294CF71000263BE5 /* Release */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ BUNDLE_LOADER = "$(TEST_HOST)";+ CURRENT_PROJECT_VERSION = 1;+ GENERATE_INFOPLIST_FILE = YES;+ MARKETING_VERSION = 1.0;+ PRODUCT_BUNDLE_IDENTIFIER = com.copysync.copysyncUi.RunnerTests;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SWIFT_VERSION = 5.0;+ TEST_HOST = "$(BUILT_PRODUCTS_DIR)/copysync_ui.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/copysync_ui";+ };+ name = Release;+ };+ 331C80DD294CF71000263BE5 /* Profile */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ BUNDLE_LOADER = "$(TEST_HOST)";+ CURRENT_PROJECT_VERSION = 1;+ GENERATE_INFOPLIST_FILE = YES;+ MARKETING_VERSION = 1.0;+ PRODUCT_BUNDLE_IDENTIFIER = com.copysync.copysyncUi.RunnerTests;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SWIFT_VERSION = 5.0;+ TEST_HOST = "$(BUILT_PRODUCTS_DIR)/copysync_ui.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/copysync_ui";+ };+ name = Profile;+ };+ 338D0CE9231458BD00FA5F75 /* Profile */ = {+ isa = XCBuildConfiguration;+ baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;+ buildSettings = {+ ALWAYS_SEARCH_USER_PATHS = NO;+ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;+ CLANG_ANALYZER_NONNULL = YES;+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";+ CLANG_CXX_LIBRARY = "libc++";+ CLANG_ENABLE_MODULES = YES;+ CLANG_ENABLE_OBJC_ARC = YES;+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;+ CLANG_WARN_BOOL_CONVERSION = YES;+ CLANG_WARN_CONSTANT_CONVERSION = YES;+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;+ CLANG_WARN_EMPTY_BODY = YES;+ CLANG_WARN_ENUM_CONVERSION = YES;+ CLANG_WARN_INFINITE_RECURSION = YES;+ CLANG_WARN_INT_CONVERSION = YES;+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;+ CLANG_WARN_SUSPICIOUS_MOVE = YES;+ CODE_SIGN_IDENTITY = "-";+ COPY_PHASE_STRIP = NO;+ DEAD_CODE_STRIPPING = YES;+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";+ ENABLE_NS_ASSERTIONS = NO;+ ENABLE_STRICT_OBJC_MSGSEND = YES;+ ENABLE_USER_SCRIPT_SANDBOXING = NO;+ GCC_C_LANGUAGE_STANDARD = gnu11;+ GCC_NO_COMMON_BLOCKS = YES;+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;+ GCC_WARN_UNUSED_FUNCTION = YES;+ GCC_WARN_UNUSED_VARIABLE = YES;+ MACOSX_DEPLOYMENT_TARGET = 13.0;+ MTL_ENABLE_DEBUG_INFO = NO;+ SDKROOT = macosx;+ SWIFT_COMPILATION_MODE = wholemodule;+ SWIFT_OPTIMIZATION_LEVEL = "-O";+ };+ name = Profile;+ };+ 338D0CEA231458BD00FA5F75 /* Profile */ = {+ isa = XCBuildConfiguration;+ baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */;+ buildSettings = {+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;+ CLANG_ENABLE_MODULES = YES;+ CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements;+ CODE_SIGN_STYLE = Automatic;+ COMBINE_HIDPI_IMAGES = YES;+ INFOPLIST_FILE = Runner/Info.plist;+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/../Frameworks",+ );+ PROVISIONING_PROFILE_SPECIFIER = "";+ SWIFT_VERSION = 5.0;+ };+ name = Profile;+ };+ 338D0CEB231458BD00FA5F75 /* Profile */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ CODE_SIGN_STYLE = Manual;+ PRODUCT_NAME = "$(TARGET_NAME)";+ };+ name = Profile;+ };+ 33CC10F92044A3C60003C045 /* Debug */ = {+ isa = XCBuildConfiguration;+ baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */;+ buildSettings = {+ ALWAYS_SEARCH_USER_PATHS = NO;+ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;+ CLANG_ANALYZER_NONNULL = YES;+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";+ CLANG_CXX_LIBRARY = "libc++";+ CLANG_ENABLE_MODULES = YES;+ CLANG_ENABLE_OBJC_ARC = YES;+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;+ CLANG_WARN_BOOL_CONVERSION = YES;+ CLANG_WARN_CONSTANT_CONVERSION = YES;+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;+ CLANG_WARN_EMPTY_BODY = YES;+ CLANG_WARN_ENUM_CONVERSION = YES;+ CLANG_WARN_INFINITE_RECURSION = YES;+ CLANG_WARN_INT_CONVERSION = YES;+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;+ CLANG_WARN_SUSPICIOUS_MOVE = YES;+ CODE_SIGN_IDENTITY = "-";+ COPY_PHASE_STRIP = NO;+ DEAD_CODE_STRIPPING = YES;+ DEBUG_INFORMATION_FORMAT = dwarf;+ ENABLE_STRICT_OBJC_MSGSEND = YES;+ ENABLE_TESTABILITY = YES;+ ENABLE_USER_SCRIPT_SANDBOXING = NO;+ GCC_C_LANGUAGE_STANDARD = gnu11;+ GCC_DYNAMIC_NO_PIC = NO;+ GCC_NO_COMMON_BLOCKS = YES;+ GCC_OPTIMIZATION_LEVEL = 0;+ GCC_PREPROCESSOR_DEFINITIONS = (+ "DEBUG=1",+ "$(inherited)",+ );+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;+ GCC_WARN_UNUSED_FUNCTION = YES;+ GCC_WARN_UNUSED_VARIABLE = YES;+ MACOSX_DEPLOYMENT_TARGET = 13.0;+ MTL_ENABLE_DEBUG_INFO = YES;+ ONLY_ACTIVE_ARCH = YES;+ SDKROOT = macosx;+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;+ SWIFT_OPTIMIZATION_LEVEL = "-Onone";+ };+ name = Debug;+ };+ 33CC10FA2044A3C60003C045 /* Release */ = {+ isa = XCBuildConfiguration;+ baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;+ buildSettings = {+ ALWAYS_SEARCH_USER_PATHS = NO;+ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;+ CLANG_ANALYZER_NONNULL = YES;+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";+ CLANG_CXX_LIBRARY = "libc++";+ CLANG_ENABLE_MODULES = YES;+ CLANG_ENABLE_OBJC_ARC = YES;+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;+ CLANG_WARN_BOOL_CONVERSION = YES;+ CLANG_WARN_CONSTANT_CONVERSION = YES;+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;+ CLANG_WARN_EMPTY_BODY = YES;+ CLANG_WARN_ENUM_CONVERSION = YES;+ CLANG_WARN_INFINITE_RECURSION = YES;+ CLANG_WARN_INT_CONVERSION = YES;+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;+ CLANG_WARN_SUSPICIOUS_MOVE = YES;+ CODE_SIGN_IDENTITY = "-";+ COPY_PHASE_STRIP = NO;+ DEAD_CODE_STRIPPING = YES;+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";+ ENABLE_NS_ASSERTIONS = NO;+ ENABLE_STRICT_OBJC_MSGSEND = YES;+ ENABLE_USER_SCRIPT_SANDBOXING = NO;+ GCC_C_LANGUAGE_STANDARD = gnu11;+ GCC_NO_COMMON_BLOCKS = YES;+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;+ GCC_WARN_UNUSED_FUNCTION = YES;+ GCC_WARN_UNUSED_VARIABLE = YES;+ MACOSX_DEPLOYMENT_TARGET = 13.0;+ MTL_ENABLE_DEBUG_INFO = NO;+ SDKROOT = macosx;+ SWIFT_COMPILATION_MODE = wholemodule;+ SWIFT_OPTIMIZATION_LEVEL = "-O";+ };+ name = Release;+ };+ 33CC10FC2044A3C60003C045 /* Debug */ = {+ isa = XCBuildConfiguration;+ baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */;+ buildSettings = {+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;+ CLANG_ENABLE_MODULES = YES;+ CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements;+ CODE_SIGN_STYLE = Automatic;+ COMBINE_HIDPI_IMAGES = YES;+ INFOPLIST_FILE = Runner/Info.plist;+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/../Frameworks",+ );+ PROVISIONING_PROFILE_SPECIFIER = "";+ SWIFT_OPTIMIZATION_LEVEL = "-Onone";+ SWIFT_VERSION = 5.0;+ };+ name = Debug;+ };+ 33CC10FD2044A3C60003C045 /* Release */ = {+ isa = XCBuildConfiguration;+ baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */;+ buildSettings = {+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;+ CLANG_ENABLE_MODULES = YES;+ CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements;+ CODE_SIGN_STYLE = Automatic;+ COMBINE_HIDPI_IMAGES = YES;+ INFOPLIST_FILE = Runner/Info.plist;+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/../Frameworks",+ );+ PROVISIONING_PROFILE_SPECIFIER = "";+ SWIFT_VERSION = 5.0;+ };+ name = Release;+ };+ 33CC111C2044C6BA0003C045 /* Debug */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ CODE_SIGN_STYLE = Manual;+ PRODUCT_NAME = "$(TARGET_NAME)";+ };+ name = Debug;+ };+ 33CC111D2044C6BA0003C045 /* Release */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ CODE_SIGN_STYLE = Automatic;+ PRODUCT_NAME = "$(TARGET_NAME)";+ };+ name = Release;+ };+/* End XCBuildConfiguration section */++/* Begin XCConfigurationList section */+ 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ 331C80DB294CF71000263BE5 /* Debug */,+ 331C80DC294CF71000263BE5 /* Release */,+ 331C80DD294CF71000263BE5 /* Profile */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Release;+ };+ 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ 33CC10F92044A3C60003C045 /* Debug */,+ 33CC10FA2044A3C60003C045 /* Release */,+ 338D0CE9231458BD00FA5F75 /* Profile */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Release;+ };+ 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ 33CC10FC2044A3C60003C045 /* Debug */,+ 33CC10FD2044A3C60003C045 /* Release */,+ 338D0CEA231458BD00FA5F75 /* Profile */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Release;+ };+ 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ 33CC111C2044C6BA0003C045 /* Debug */,+ 33CC111D2044C6BA0003C045 /* Release */,+ 338D0CEB231458BD00FA5F75 /* Profile */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Release;+ };+/* End XCConfigurationList section */++/* Begin XCLocalSwiftPackageReference section */+ 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = {+ isa = XCLocalSwiftPackageReference;+ relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage;+ };+/* End XCLocalSwiftPackageReference section */++/* Begin XCSwiftPackageProductDependency section */+ 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = {+ isa = XCSwiftPackageProductDependency;+ productName = FlutterGeneratedPluginSwiftPackage;+ };+/* End XCSwiftPackageProductDependency section */+ };+ rootObject = 33CC10E52044A3C60003C045 /* Project object */;+}diff --git a/ui/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ui/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plistnew file mode 100644index 0000000..18d9810--- /dev/null+++ b/ui/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>IDEDidComputeMac32BitWarning</key>+ <true/>+</dict>+</plist>diff --git a/ui/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/ui/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcschemenew file mode 100644index 0000000..628f3e8--- /dev/null+++ b/ui/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme@@ -0,0 +1,117 @@+<?xml version="1.0" encoding="UTF-8"?>+<Scheme+ LastUpgradeVersion = "1510"+ version = "1.3">+ <BuildAction+ parallelizeBuildables = "YES"+ buildImplicitDependencies = "YES">+ <PreActions>+ <ExecutionAction+ ActionType = "Xcode.IDEStandardExecutionActionsCore.ExecutionActionType.ShellScriptAction">+ <ActionContent+ title = "Run Prepare Flutter Framework Script"+ scriptText = ""$FLUTTER_ROOT"/packages/flutter_tools/bin/macos_assemble.sh prepare ">+ <EnvironmentBuildable>+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "33CC10EC2044A3C60003C045"+ BuildableName = "copysync_ui.app"+ BlueprintName = "Runner"+ ReferencedContainer = "container:Runner.xcodeproj">+ </BuildableReference>+ </EnvironmentBuildable>+ </ActionContent>+ </ExecutionAction>+ </PreActions>+ <BuildActionEntries>+ <BuildActionEntry+ buildForTesting = "YES"+ buildForRunning = "YES"+ buildForProfiling = "YES"+ buildForArchiving = "YES"+ buildForAnalyzing = "YES">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "33CC10EC2044A3C60003C045"+ BuildableName = "copysync_ui.app"+ BlueprintName = "Runner"+ ReferencedContainer = "container:Runner.xcodeproj">+ </BuildableReference>+ </BuildActionEntry>+ </BuildActionEntries>+ </BuildAction>+ <TestAction+ buildConfiguration = "Debug"+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"+ shouldUseLaunchSchemeArgsEnv = "YES">+ <MacroExpansion>+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "33CC10EC2044A3C60003C045"+ BuildableName = "copysync_ui.app"+ BlueprintName = "Runner"+ ReferencedContainer = "container:Runner.xcodeproj">+ </BuildableReference>+ </MacroExpansion>+ <Testables>+ <TestableReference+ skipped = "NO"+ parallelizable = "YES">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "331C80D4294CF70F00263BE5"+ BuildableName = "RunnerTests.xctest"+ BlueprintName = "RunnerTests"+ ReferencedContainer = "container:Runner.xcodeproj">+ </BuildableReference>+ </TestableReference>+ </Testables>+ </TestAction>+ <LaunchAction+ buildConfiguration = "Debug"+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"+ launchStyle = "0"+ useCustomWorkingDirectory = "NO"+ ignoresPersistentStateOnLaunch = "NO"+ debugDocumentVersioning = "YES"+ debugServiceExtension = "internal"+ enableGPUValidationMode = "1"+ allowLocationSimulation = "YES">+ <BuildableProductRunnable+ runnableDebuggingMode = "0">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "33CC10EC2044A3C60003C045"+ BuildableName = "copysync_ui.app"+ BlueprintName = "Runner"+ ReferencedContainer = "container:Runner.xcodeproj">+ </BuildableReference>+ </BuildableProductRunnable>+ </LaunchAction>+ <ProfileAction+ buildConfiguration = "Profile"+ shouldUseLaunchSchemeArgsEnv = "YES"+ savedToolIdentifier = ""+ useCustomWorkingDirectory = "NO"+ debugDocumentVersioning = "YES">+ <BuildableProductRunnable+ runnableDebuggingMode = "0">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "33CC10EC2044A3C60003C045"+ BuildableName = "copysync_ui.app"+ BlueprintName = "Runner"+ ReferencedContainer = "container:Runner.xcodeproj">+ </BuildableReference>+ </BuildableProductRunnable>+ </ProfileAction>+ <AnalyzeAction+ buildConfiguration = "Debug">+ </AnalyzeAction>+ <ArchiveAction+ buildConfiguration = "Release"+ revealArchiveInOrganizer = "YES">+ </ArchiveAction>+</Scheme>diff --git a/ui/macos/Runner.xcworkspace/contents.xcworkspacedata b/ui/macos/Runner.xcworkspace/contents.xcworkspacedatanew file mode 100644index 0000000..1d526a1--- /dev/null+++ b/ui/macos/Runner.xcworkspace/contents.xcworkspacedata@@ -0,0 +1,7 @@+<?xml version="1.0" encoding="UTF-8"?>+<Workspace+ version = "1.0">+ <FileRef+ location = "group:Runner.xcodeproj">+ </FileRef>+</Workspace>diff --git a/ui/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ui/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plistnew file mode 100644index 0000000..18d9810--- /dev/null+++ b/ui/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>IDEDidComputeMac32BitWarning</key>+ <true/>+</dict>+</plist>diff --git a/ui/macos/Runner/AppDelegate.swift b/ui/macos/Runner/AppDelegate.swiftnew file mode 100644index 0000000..b3c1761--- /dev/null+++ b/ui/macos/Runner/AppDelegate.swift@@ -0,0 +1,13 @@+import Cocoa+import FlutterMacOS++@main+class AppDelegate: FlutterAppDelegate {+ override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {+ return true+ }++ override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {+ return true+ }+}diff --git a/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.jsonnew file mode 100644index 0000000..a2ec33f--- /dev/null+++ b/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json@@ -0,0 +1,68 @@+{+ "images" : [+ {+ "size" : "16x16",+ "idiom" : "mac",+ "filename" : "app_icon_16.png",+ "scale" : "1x"+ },+ {+ "size" : "16x16",+ "idiom" : "mac",+ "filename" : "app_icon_32.png",+ "scale" : "2x"+ },+ {+ "size" : "32x32",+ "idiom" : "mac",+ "filename" : "app_icon_32.png",+ "scale" : "1x"+ },+ {+ "size" : "32x32",+ "idiom" : "mac",+ "filename" : "app_icon_64.png",+ "scale" : "2x"+ },+ {+ "size" : "128x128",+ "idiom" : "mac",+ "filename" : "app_icon_128.png",+ "scale" : "1x"+ },+ {+ "size" : "128x128",+ "idiom" : "mac",+ "filename" : "app_icon_256.png",+ "scale" : "2x"+ },+ {+ "size" : "256x256",+ "idiom" : "mac",+ "filename" : "app_icon_256.png",+ "scale" : "1x"+ },+ {+ "size" : "256x256",+ "idiom" : "mac",+ "filename" : "app_icon_512.png",+ "scale" : "2x"+ },+ {+ "size" : "512x512",+ "idiom" : "mac",+ "filename" : "app_icon_512.png",+ "scale" : "1x"+ },+ {+ "size" : "512x512",+ "idiom" : "mac",+ "filename" : "app_icon_1024.png",+ "scale" : "2x"+ }+ ],+ "info" : {+ "version" : 1,+ "author" : "xcode"+ }+}diff --git a/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.pngnew file mode 100644index 0000000..d2f4ba2Binary files /dev/null and b/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differdiff --git a/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.pngnew file mode 100644index 0000000..d3cf927Binary files /dev/null and b/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differdiff --git a/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.pngnew file mode 100644index 0000000..4612cb7Binary files /dev/null and b/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differdiff --git a/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.pngnew file mode 100644index 0000000..1b544a7Binary files /dev/null and b/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differdiff --git a/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.pngnew file mode 100644index 0000000..b98909bBinary files /dev/null and b/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differdiff --git a/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.pngnew file mode 100644index 0000000..c8af89cBinary files /dev/null and b/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differdiff --git a/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.pngnew file mode 100644index 0000000..97812f9Binary files /dev/null and b/ui/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differdiff --git a/ui/macos/Runner/Base.lproj/MainMenu.xib b/ui/macos/Runner/Base.lproj/MainMenu.xibnew file mode 100644index 0000000..80e867a--- /dev/null+++ b/ui/macos/Runner/Base.lproj/MainMenu.xib@@ -0,0 +1,343 @@+<?xml version="1.0" encoding="UTF-8"?>+<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="14490.70" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">+ <dependencies>+ <deployment identifier="macosx"/>+ <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="14490.70"/>+ <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>+ </dependencies>+ <objects>+ <customObject id="-2" userLabel="File's Owner" customClass="NSApplication">+ <connections>+ <outlet property="delegate" destination="Voe-Tx-rLC" id="GzC-gU-4Uq"/>+ </connections>+ </customObject>+ <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>+ <customObject id="-3" userLabel="Application" customClass="NSObject"/>+ <customObject id="Voe-Tx-rLC" customClass="AppDelegate" customModule="Runner" customModuleProvider="target">+ <connections>+ <outlet property="applicationMenu" destination="uQy-DD-JDr" id="XBo-yE-nKs"/>+ <outlet property="mainFlutterWindow" destination="QvC-M9-y7g" id="gIp-Ho-8D9"/>+ </connections>+ </customObject>+ <customObject id="YLy-65-1bz" customClass="NSFontManager"/>+ <menu title="Main Menu" systemMenu="main" id="AYu-sK-qS6">+ <items>+ <menuItem title="APP_NAME" id="1Xt-HY-uBw">+ <modifierMask key="keyEquivalentModifierMask"/>+ <menu key="submenu" title="APP_NAME" systemMenu="apple" id="uQy-DD-JDr">+ <items>+ <menuItem title="About APP_NAME" id="5kV-Vb-QxS">+ <modifierMask key="keyEquivalentModifierMask"/>+ <connections>+ <action selector="orderFrontStandardAboutPanel:" target="-1" id="Exp-CZ-Vem"/>+ </connections>+ </menuItem>+ <menuItem isSeparatorItem="YES" id="VOq-y0-SEH"/>+ <menuItem title="Preferences…" keyEquivalent="," id="BOF-NM-1cW"/>+ <menuItem isSeparatorItem="YES" id="wFC-TO-SCJ"/>+ <menuItem title="Services" id="NMo-om-nkz">+ <modifierMask key="keyEquivalentModifierMask"/>+ <menu key="submenu" title="Services" systemMenu="services" id="hz9-B4-Xy5"/>+ </menuItem>+ <menuItem isSeparatorItem="YES" id="4je-JR-u6R"/>+ <menuItem title="Hide APP_NAME" keyEquivalent="h" id="Olw-nP-bQN">+ <connections>+ <action selector="hide:" target="-1" id="PnN-Uc-m68"/>+ </connections>+ </menuItem>+ <menuItem title="Hide Others" keyEquivalent="h" id="Vdr-fp-XzO">+ <modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>+ <connections>+ <action selector="hideOtherApplications:" target="-1" id="VT4-aY-XCT"/>+ </connections>+ </menuItem>+ <menuItem title="Show All" id="Kd2-mp-pUS">+ <modifierMask key="keyEquivalentModifierMask"/>+ <connections>+ <action selector="unhideAllApplications:" target="-1" id="Dhg-Le-xox"/>+ </connections>+ </menuItem>+ <menuItem isSeparatorItem="YES" id="kCx-OE-vgT"/>+ <menuItem title="Quit APP_NAME" keyEquivalent="q" id="4sb-4s-VLi">+ <connections>+ <action selector="terminate:" target="-1" id="Te7-pn-YzF"/>+ </connections>+ </menuItem>+ </items>+ </menu>+ </menuItem>+ <menuItem title="Edit" id="5QF-Oa-p0T">+ <modifierMask key="keyEquivalentModifierMask"/>+ <menu key="submenu" title="Edit" id="W48-6f-4Dl">+ <items>+ <menuItem title="Undo" keyEquivalent="z" id="dRJ-4n-Yzg">+ <connections>+ <action selector="undo:" target="-1" id="M6e-cu-g7V"/>+ </connections>+ </menuItem>+ <menuItem title="Redo" keyEquivalent="Z" id="6dh-zS-Vam">+ <connections>+ <action selector="redo:" target="-1" id="oIA-Rs-6OD"/>+ </connections>+ </menuItem>+ <menuItem isSeparatorItem="YES" id="WRV-NI-Exz"/>+ <menuItem title="Cut" keyEquivalent="x" id="uRl-iY-unG">+ <connections>+ <action selector="cut:" target="-1" id="YJe-68-I9s"/>+ </connections>+ </menuItem>+ <menuItem title="Copy" keyEquivalent="c" id="x3v-GG-iWU">+ <connections>+ <action selector="copy:" target="-1" id="G1f-GL-Joy"/>+ </connections>+ </menuItem>+ <menuItem title="Paste" keyEquivalent="v" id="gVA-U4-sdL">+ <connections>+ <action selector="paste:" target="-1" id="UvS-8e-Qdg"/>+ </connections>+ </menuItem>+ <menuItem title="Paste and Match Style" keyEquivalent="V" id="WeT-3V-zwk">+ <modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>+ <connections>+ <action selector="pasteAsPlainText:" target="-1" id="cEh-KX-wJQ"/>+ </connections>+ </menuItem>+ <menuItem title="Delete" id="pa3-QI-u2k">+ <modifierMask key="keyEquivalentModifierMask"/>+ <connections>+ <action selector="delete:" target="-1" id="0Mk-Ml-PaM"/>+ </connections>+ </menuItem>+ <menuItem title="Select All" keyEquivalent="a" id="Ruw-6m-B2m">+ <connections>+ <action selector="selectAll:" target="-1" id="VNm-Mi-diN"/>+ </connections>+ </menuItem>+ <menuItem isSeparatorItem="YES" id="uyl-h8-XO2"/>+ <menuItem title="Find" id="4EN-yA-p0u">+ <modifierMask key="keyEquivalentModifierMask"/>+ <menu key="submenu" title="Find" id="1b7-l0-nxx">+ <items>+ <menuItem title="Find…" tag="1" keyEquivalent="f" id="Xz5-n4-O0W">+ <connections>+ <action selector="performFindPanelAction:" target="-1" id="cD7-Qs-BN4"/>+ </connections>+ </menuItem>+ <menuItem title="Find and Replace…" tag="12" keyEquivalent="f" id="YEy-JH-Tfz">+ <modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>+ <connections>+ <action selector="performFindPanelAction:" target="-1" id="WD3-Gg-5AJ"/>+ </connections>+ </menuItem>+ <menuItem title="Find Next" tag="2" keyEquivalent="g" id="q09-fT-Sye">+ <connections>+ <action selector="performFindPanelAction:" target="-1" id="NDo-RZ-v9R"/>+ </connections>+ </menuItem>+ <menuItem title="Find Previous" tag="3" keyEquivalent="G" id="OwM-mh-QMV">+ <connections>+ <action selector="performFindPanelAction:" target="-1" id="HOh-sY-3ay"/>+ </connections>+ </menuItem>+ <menuItem title="Use Selection for Find" tag="7" keyEquivalent="e" id="buJ-ug-pKt">+ <connections>+ <action selector="performFindPanelAction:" target="-1" id="U76-nv-p5D"/>+ </connections>+ </menuItem>+ <menuItem title="Jump to Selection" keyEquivalent="j" id="S0p-oC-mLd">+ <connections>+ <action selector="centerSelectionInVisibleArea:" target="-1" id="IOG-6D-g5B"/>+ </connections>+ </menuItem>+ </items>+ </menu>+ </menuItem>+ <menuItem title="Spelling and Grammar" id="Dv1-io-Yv7">+ <modifierMask key="keyEquivalentModifierMask"/>+ <menu key="submenu" title="Spelling" id="3IN-sU-3Bg">+ <items>+ <menuItem title="Show Spelling and Grammar" keyEquivalent=":" id="HFo-cy-zxI">+ <connections>+ <action selector="showGuessPanel:" target="-1" id="vFj-Ks-hy3"/>+ </connections>+ </menuItem>+ <menuItem title="Check Document Now" keyEquivalent=";" id="hz2-CU-CR7">+ <connections>+ <action selector="checkSpelling:" target="-1" id="fz7-VC-reM"/>+ </connections>+ </menuItem>+ <menuItem isSeparatorItem="YES" id="bNw-od-mp5"/>+ <menuItem title="Check Spelling While Typing" id="rbD-Rh-wIN">+ <modifierMask key="keyEquivalentModifierMask"/>+ <connections>+ <action selector="toggleContinuousSpellChecking:" target="-1" id="7w6-Qz-0kB"/>+ </connections>+ </menuItem>+ <menuItem title="Check Grammar With Spelling" id="mK6-2p-4JG">+ <modifierMask key="keyEquivalentModifierMask"/>+ <connections>+ <action selector="toggleGrammarChecking:" target="-1" id="muD-Qn-j4w"/>+ </connections>+ </menuItem>+ <menuItem title="Correct Spelling Automatically" id="78Y-hA-62v">+ <modifierMask key="keyEquivalentModifierMask"/>+ <connections>+ <action selector="toggleAutomaticSpellingCorrection:" target="-1" id="2lM-Qi-WAP"/>+ </connections>+ </menuItem>+ </items>+ </menu>+ </menuItem>+ <menuItem title="Substitutions" id="9ic-FL-obx">+ <modifierMask key="keyEquivalentModifierMask"/>+ <menu key="submenu" title="Substitutions" id="FeM-D8-WVr">+ <items>+ <menuItem title="Show Substitutions" id="z6F-FW-3nz">+ <modifierMask key="keyEquivalentModifierMask"/>+ <connections>+ <action selector="orderFrontSubstitutionsPanel:" target="-1" id="oku-mr-iSq"/>+ </connections>+ </menuItem>+ <menuItem isSeparatorItem="YES" id="gPx-C9-uUO"/>+ <menuItem title="Smart Copy/Paste" id="9yt-4B-nSM">+ <modifierMask key="keyEquivalentModifierMask"/>+ <connections>+ <action selector="toggleSmartInsertDelete:" target="-1" id="3IJ-Se-DZD"/>+ </connections>+ </menuItem>+ <menuItem title="Smart Quotes" id="hQb-2v-fYv">+ <modifierMask key="keyEquivalentModifierMask"/>+ <connections>+ <action selector="toggleAutomaticQuoteSubstitution:" target="-1" id="ptq-xd-QOA"/>+ </connections>+ </menuItem>+ <menuItem title="Smart Dashes" id="rgM-f4-ycn">+ <modifierMask key="keyEquivalentModifierMask"/>+ <connections>+ <action selector="toggleAutomaticDashSubstitution:" target="-1" id="oCt-pO-9gS"/>+ </connections>+ </menuItem>+ <menuItem title="Smart Links" id="cwL-P1-jid">+ <modifierMask key="keyEquivalentModifierMask"/>+ <connections>+ <action selector="toggleAutomaticLinkDetection:" target="-1" id="Gip-E3-Fov"/>+ </connections>+ </menuItem>+ <menuItem title="Data Detectors" id="tRr-pd-1PS">+ <modifierMask key="keyEquivalentModifierMask"/>+ <connections>+ <action selector="toggleAutomaticDataDetection:" target="-1" id="R1I-Nq-Kbl"/>+ </connections>+ </menuItem>+ <menuItem title="Text Replacement" id="HFQ-gK-NFA">+ <modifierMask key="keyEquivalentModifierMask"/>+ <connections>+ <action selector="toggleAutomaticTextReplacement:" target="-1" id="DvP-Fe-Py6"/>+ </connections>+ </menuItem>+ </items>+ </menu>+ </menuItem>+ <menuItem title="Transformations" id="2oI-Rn-ZJC">+ <modifierMask key="keyEquivalentModifierMask"/>+ <menu key="submenu" title="Transformations" id="c8a-y6-VQd">+ <items>+ <menuItem title="Make Upper Case" id="vmV-6d-7jI">+ <modifierMask key="keyEquivalentModifierMask"/>+ <connections>+ <action selector="uppercaseWord:" target="-1" id="sPh-Tk-edu"/>+ </connections>+ </menuItem>+ <menuItem title="Make Lower Case" id="d9M-CD-aMd">+ <modifierMask key="keyEquivalentModifierMask"/>+ <connections>+ <action selector="lowercaseWord:" target="-1" id="iUZ-b5-hil"/>+ </connections>+ </menuItem>+ <menuItem title="Capitalize" id="UEZ-Bs-lqG">+ <modifierMask key="keyEquivalentModifierMask"/>+ <connections>+ <action selector="capitalizeWord:" target="-1" id="26H-TL-nsh"/>+ </connections>+ </menuItem>+ </items>+ </menu>+ </menuItem>+ <menuItem title="Speech" id="xrE-MZ-jX0">+ <modifierMask key="keyEquivalentModifierMask"/>+ <menu key="submenu" title="Speech" id="3rS-ZA-NoH">+ <items>+ <menuItem title="Start Speaking" id="Ynk-f8-cLZ">+ <modifierMask key="keyEquivalentModifierMask"/>+ <connections>+ <action selector="startSpeaking:" target="-1" id="654-Ng-kyl"/>+ </connections>+ </menuItem>+ <menuItem title="Stop Speaking" id="Oyz-dy-DGm">+ <modifierMask key="keyEquivalentModifierMask"/>+ <connections>+ <action selector="stopSpeaking:" target="-1" id="dX8-6p-jy9"/>+ </connections>+ </menuItem>+ </items>+ </menu>+ </menuItem>+ </items>+ </menu>+ </menuItem>+ <menuItem title="View" id="H8h-7b-M4v">+ <modifierMask key="keyEquivalentModifierMask"/>+ <menu key="submenu" title="View" id="HyV-fh-RgO">+ <items>+ <menuItem title="Enter Full Screen" keyEquivalent="f" id="4J7-dP-txa">+ <modifierMask key="keyEquivalentModifierMask" control="YES" command="YES"/>+ <connections>+ <action selector="toggleFullScreen:" target="-1" id="dU3-MA-1Rq"/>+ </connections>+ </menuItem>+ </items>+ </menu>+ </menuItem>+ <menuItem title="Window" id="aUF-d1-5bR">+ <modifierMask key="keyEquivalentModifierMask"/>+ <menu key="submenu" title="Window" systemMenu="window" id="Td7-aD-5lo">+ <items>+ <menuItem title="Minimize" keyEquivalent="m" id="OY7-WF-poV">+ <connections>+ <action selector="performMiniaturize:" target="-1" id="VwT-WD-YPe"/>+ </connections>+ </menuItem>+ <menuItem title="Zoom" id="R4o-n2-Eq4">+ <modifierMask key="keyEquivalentModifierMask"/>+ <connections>+ <action selector="performZoom:" target="-1" id="DIl-cC-cCs"/>+ </connections>+ </menuItem>+ <menuItem isSeparatorItem="YES" id="eu3-7i-yIM"/>+ <menuItem title="Bring All to Front" id="LE2-aR-0XJ">+ <modifierMask key="keyEquivalentModifierMask"/>+ <connections>+ <action selector="arrangeInFront:" target="-1" id="DRN-fu-gQh"/>+ </connections>+ </menuItem>+ </items>+ </menu>+ </menuItem>+ <menuItem title="Help" id="EPT-qC-fAb">+ <modifierMask key="keyEquivalentModifierMask"/>+ <menu key="submenu" title="Help" systemMenu="help" id="rJ0-wn-3NY"/>+ </menuItem>+ </items>+ <point key="canvasLocation" x="142" y="-258"/>+ </menu>+ <window title="APP_NAME" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" releasedWhenClosed="NO" animationBehavior="default" id="QvC-M9-y7g" customClass="MainFlutterWindow" customModule="Runner" customModuleProvider="target">+ <windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES"/>+ <rect key="contentRect" x="335" y="390" width="800" height="600"/>+ <rect key="screenRect" x="0.0" y="0.0" width="2560" height="1577"/>+ <view key="contentView" wantsLayer="YES" id="EiT-Mj-1SZ">+ <rect key="frame" x="0.0" y="0.0" width="800" height="600"/>+ <autoresizingMask key="autoresizingMask"/>+ </view>+ </window>+ </objects>+</document>diff --git a/ui/macos/Runner/Configs/AppInfo.xcconfig b/ui/macos/Runner/Configs/AppInfo.xcconfignew file mode 100644index 0000000..7d40cc9--- /dev/null+++ b/ui/macos/Runner/Configs/AppInfo.xcconfig@@ -0,0 +1,9 @@+// Application-level settings for the Runner target.++// App 名称,也是菜单栏与「关于」里显示的名字+PRODUCT_NAME = CopySync++// 剪贴板授权(TCC)以 bundle identifier 为主体,发布后不要再改+PRODUCT_BUNDLE_IDENTIFIER = com.copysync.app++PRODUCT_COPYRIGHT = Copyright © 2026 baiyuze. Released under the MIT License.diff --git a/ui/macos/Runner/Configs/Debug.xcconfig b/ui/macos/Runner/Configs/Debug.xcconfignew file mode 100644index 0000000..36b0fd9--- /dev/null+++ b/ui/macos/Runner/Configs/Debug.xcconfig@@ -0,0 +1,2 @@+#include "../../Flutter/Flutter-Debug.xcconfig"+#include "Warnings.xcconfig"diff --git a/ui/macos/Runner/Configs/Release.xcconfig b/ui/macos/Runner/Configs/Release.xcconfignew file mode 100644index 0000000..dff4f49--- /dev/null+++ b/ui/macos/Runner/Configs/Release.xcconfig@@ -0,0 +1,2 @@+#include "../../Flutter/Flutter-Release.xcconfig"+#include "Warnings.xcconfig"diff --git a/ui/macos/Runner/Configs/Warnings.xcconfig b/ui/macos/Runner/Configs/Warnings.xcconfignew file mode 100644index 0000000..42bcbf4--- /dev/null+++ b/ui/macos/Runner/Configs/Warnings.xcconfig@@ -0,0 +1,13 @@+WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings+GCC_WARN_UNDECLARED_SELECTOR = YES+CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES+CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE+CLANG_WARN__DUPLICATE_METHOD_MATCH = YES+CLANG_WARN_PRAGMA_PACK = YES+CLANG_WARN_STRICT_PROTOTYPES = YES+CLANG_WARN_COMMA = YES+GCC_WARN_STRICT_SELECTOR_MATCH = YES+CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES+CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES+GCC_WARN_SHADOW = YES+CLANG_WARN_UNREACHABLE_CODE = YESdiff --git a/ui/macos/Runner/DebugProfile.entitlements b/ui/macos/Runner/DebugProfile.entitlementsnew file mode 100644index 0000000..5ef2752--- /dev/null+++ b/ui/macos/Runner/DebugProfile.entitlements@@ -0,0 +1,19 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <!-- 刻意关闭沙盒。CopySync 需要:+ 1. 读取 daemon 写在 ~/Library/Application Support/CopySync 下的 daemon.json+ 2. 访问用户复制的任意路径文件(沙盒只允许访问自身容器)+ 分发走 Developer ID 签名 + 公证,不上 App Store。 -->+ <key>com.apple.security.app-sandbox</key>+ <false/>+ <key>com.apple.security.cs.allow-jit</key>+ <true/>+ <!-- 连接 daemon 的本地 gRPC 端口 -->+ <key>com.apple.security.network.client</key>+ <true/>+ <key>com.apple.security.network.server</key>+ <true/>+</dict>+</plist>diff --git a/ui/macos/Runner/Info.plist b/ui/macos/Runner/Info.plistnew file mode 100644index 0000000..f90097e--- /dev/null+++ b/ui/macos/Runner/Info.plist@@ -0,0 +1,34 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleDevelopmentRegion</key>+ <string>$(DEVELOPMENT_LANGUAGE)</string>+ <key>CFBundleExecutable</key>+ <string>$(EXECUTABLE_NAME)</string>+ <key>CFBundleIconFile</key>+ <string></string>+ <key>CFBundleIdentifier</key>+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>+ <key>CFBundleInfoDictionaryVersion</key>+ <string>6.0</string>+ <key>CFBundleName</key>+ <string>$(PRODUCT_NAME)</string>+ <key>CFBundlePackageType</key>+ <string>APPL</string>+ <key>CFBundleShortVersionString</key>+ <string>$(FLUTTER_BUILD_NAME)</string>+ <key>CFBundleVersion</key>+ <string>$(FLUTTER_BUILD_NUMBER)</string>+ <key>LSApplicationCategoryType</key>+ <string>public.app-category.utilities</string>+ <key>LSMinimumSystemVersion</key>+ <string>$(MACOSX_DEPLOYMENT_TARGET)</string>+ <key>NSHumanReadableCopyright</key>+ <string>$(PRODUCT_COPYRIGHT)</string>+ <key>NSMainNibFile</key>+ <string>MainMenu</string>+ <key>NSPrincipalClass</key>+ <string>NSApplication</string>+</dict>+</plist>diff --git a/ui/macos/Runner/MainFlutterWindow.swift b/ui/macos/Runner/MainFlutterWindow.swiftnew file mode 100644index 0000000..f78870e--- /dev/null+++ b/ui/macos/Runner/MainFlutterWindow.swift@@ -0,0 +1,25 @@+import Cocoa+import FlutterMacOS++class MainFlutterWindow: NSWindow {+ override func awakeFromNib() {+ let flutterViewController = FlutterViewController()+ self.contentViewController = flutterViewController++ // 标题栏透明、内容铺到窗口顶部:侧边栏一直延伸到红绿灯下面,+ // 与「系统设置」「备忘录」等自带应用的窗口形态一致+ self.titlebarAppearsTransparent = true+ self.titleVisibility = .hidden+ self.styleMask.insert(.fullSizeContentView)++ self.minSize = NSSize(width: 760, height: 520)+ self.setContentSize(NSSize(width: 960, height: 640))+ self.center()+ // 记住用户调整过的窗口大小与位置+ self.setFrameAutosaveName("CopySyncMainWindow")++ RegisterGeneratedPlugins(registry: flutterViewController)++ super.awakeFromNib()+ }+}diff --git a/ui/macos/Runner/Release.entitlements b/ui/macos/Runner/Release.entitlementsnew file mode 100644index 0000000..4254257--- /dev/null+++ b/ui/macos/Runner/Release.entitlements@@ -0,0 +1,13 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <!-- 见 DebugProfile.entitlements 中的说明:刻意不启用沙盒 -->+ <key>com.apple.security.app-sandbox</key>+ <false/>+ <key>com.apple.security.network.client</key>+ <true/>+ <key>com.apple.security.network.server</key>+ <true/>+</dict>+</plist>diff --git a/ui/macos/RunnerTests/RunnerTests.swift b/ui/macos/RunnerTests/RunnerTests.swiftnew file mode 100644index 0000000..61f3bd1--- /dev/null+++ b/ui/macos/RunnerTests/RunnerTests.swift@@ -0,0 +1,12 @@+import Cocoa+import FlutterMacOS+import XCTest++class RunnerTests: XCTestCase {++ func testExample() {+ // If you add code to the Runner application, consider adding tests here.+ // See https://developer.apple.com/documentation/xctest for more information about using XCTest.+ }++}diff --git a/ui/pubspec.lock b/ui/pubspec.locknew file mode 100644index 0000000..254690b--- /dev/null+++ b/ui/pubspec.lock@@ -0,0 +1,309 @@+# Generated by pub+# See https://dart.dev/tools/pub/glossary#lockfile+packages:+ async:+ dependency: transitive+ description:+ name: async+ sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37+ url: "https://pub.dev"+ source: hosted+ version: "2.13.1"+ boolean_selector:+ dependency: transitive+ description:+ name: boolean_selector+ sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea"+ url: "https://pub.dev"+ source: hosted+ version: "2.1.2"+ characters:+ dependency: transitive+ description:+ name: characters+ sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b+ url: "https://pub.dev"+ source: hosted+ version: "1.4.1"+ clock:+ dependency: transitive+ description:+ name: clock+ sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b+ url: "https://pub.dev"+ source: hosted+ version: "1.1.2"+ collection:+ dependency: transitive+ description:+ name: collection+ sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"+ url: "https://pub.dev"+ source: hosted+ version: "1.19.1"+ crypto:+ dependency: transitive+ description:+ name: crypto+ sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf+ url: "https://pub.dev"+ source: hosted+ version: "3.0.7"+ cupertino_icons:+ dependency: "direct main"+ description:+ name: cupertino_icons+ sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd"+ url: "https://pub.dev"+ source: hosted+ version: "1.0.9"+ fake_async:+ dependency: transitive+ description:+ name: fake_async+ sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44"+ url: "https://pub.dev"+ source: hosted+ version: "1.3.3"+ fixnum:+ dependency: "direct main"+ description:+ name: fixnum+ sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be+ url: "https://pub.dev"+ source: hosted+ version: "1.1.1"+ flutter:+ dependency: "direct main"+ description: flutter+ source: sdk+ version: "0.0.0"+ flutter_lints:+ dependency: "direct dev"+ description:+ name: flutter_lints+ sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1"+ url: "https://pub.dev"+ source: hosted+ version: "6.0.0"+ flutter_test:+ dependency: "direct dev"+ description: flutter+ source: sdk+ version: "0.0.0"+ google_cloud:+ dependency: transitive+ description:+ name: google_cloud+ sha256: b385e20726ef5315d302c5933bfb728103116c5be2d3d17094b01a82da538c1f+ url: "https://pub.dev"+ source: hosted+ version: "0.5.0"+ google_identity_services_web:+ dependency: transitive+ description:+ name: google_identity_services_web+ sha256: "5d187c46dc59e02646e10fe82665fc3884a9b71bc1c90c2b8b749316d33ee454"+ url: "https://pub.dev"+ source: hosted+ version: "0.3.3+1"+ googleapis_auth:+ dependency: transitive+ description:+ name: googleapis_auth+ sha256: d31822528becea550f7c7a9ab73a4518e31e48f201ab574be7e141f262923f27+ url: "https://pub.dev"+ source: hosted+ version: "2.3.4"+ grpc:+ dependency: "direct main"+ description:+ name: grpc+ sha256: "86be3a7d39ad865b214a7370021ac80e68939238b507730de6d97fc662cb2723"+ url: "https://pub.dev"+ source: hosted+ version: "5.1.0"+ http:+ dependency: transitive+ description:+ name: http+ sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412"+ url: "https://pub.dev"+ source: hosted+ version: "1.6.0"+ http2:+ dependency: transitive+ description:+ name: http2+ sha256: "382d3aefc5bd6dc68c6b892d7664f29b5beb3251611ae946a98d35158a82bbfa"+ url: "https://pub.dev"+ source: hosted+ version: "2.3.1"+ http_parser:+ dependency: transitive+ description:+ name: http_parser+ sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571"+ url: "https://pub.dev"+ source: hosted+ version: "4.1.2"+ leak_tracker:+ dependency: transitive+ description:+ name: leak_tracker+ sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de"+ url: "https://pub.dev"+ source: hosted+ version: "11.0.2"+ leak_tracker_flutter_testing:+ dependency: transitive+ description:+ name: leak_tracker_flutter_testing+ sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1"+ url: "https://pub.dev"+ source: hosted+ version: "3.0.10"+ leak_tracker_testing:+ dependency: transitive+ description:+ name: leak_tracker_testing+ sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1"+ url: "https://pub.dev"+ source: hosted+ version: "3.0.2"+ lints:+ dependency: transitive+ description:+ name: lints+ sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df"+ url: "https://pub.dev"+ source: hosted+ version: "6.1.0"+ matcher:+ dependency: transitive+ description:+ name: matcher+ sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861+ url: "https://pub.dev"+ source: hosted+ version: "0.12.19"+ material_color_utilities:+ dependency: transitive+ description:+ name: material_color_utilities+ sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b"+ url: "https://pub.dev"+ source: hosted+ version: "0.13.0"+ meta:+ dependency: transitive+ description:+ name: meta+ sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349"+ url: "https://pub.dev"+ source: hosted+ version: "1.18.0"+ path:+ dependency: transitive+ description:+ name: path+ sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"+ url: "https://pub.dev"+ source: hosted+ version: "1.9.1"+ protobuf:+ dependency: "direct main"+ description:+ name: protobuf+ sha256: "13b6717366aa7ec3792dd62c19c7d33a785708224365f2db23c5ca01f1c1a0f2"+ url: "https://pub.dev"+ source: hosted+ version: "6.1.0"+ sky_engine:+ dependency: transitive+ description: flutter+ source: sdk+ version: "0.0.0"+ source_span:+ dependency: transitive+ description:+ name: source_span+ sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab"+ url: "https://pub.dev"+ source: hosted+ version: "1.10.2"+ stack_trace:+ dependency: transitive+ description:+ name: stack_trace+ sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1"+ url: "https://pub.dev"+ source: hosted+ version: "1.12.1"+ stream_channel:+ dependency: transitive+ description:+ name: stream_channel+ sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d"+ url: "https://pub.dev"+ source: hosted+ version: "2.1.4"+ string_scanner:+ dependency: transitive+ description:+ name: string_scanner+ sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43"+ url: "https://pub.dev"+ source: hosted+ version: "1.4.1"+ term_glyph:+ dependency: transitive+ description:+ name: term_glyph+ sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e"+ url: "https://pub.dev"+ source: hosted+ version: "1.2.2"+ test_api:+ dependency: transitive+ description:+ name: test_api+ sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e"+ url: "https://pub.dev"+ source: hosted+ version: "0.7.11"+ typed_data:+ dependency: transitive+ description:+ name: typed_data+ sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006+ url: "https://pub.dev"+ source: hosted+ version: "1.4.0"+ vector_math:+ dependency: transitive+ description:+ name: vector_math+ sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b+ url: "https://pub.dev"+ source: hosted+ version: "2.2.0"+ vm_service:+ dependency: transitive+ description:+ name: vm_service+ sha256: "5f37239c4851efcef929cea7824e76df7f2f0970aef85d66bbc430afa40e72f0"+ url: "https://pub.dev"+ source: hosted+ version: "15.3.0"+ web:+ dependency: transitive+ description:+ name: web+ sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"+ url: "https://pub.dev"+ source: hosted+ version: "1.1.1"+sdks:+ dart: ">=3.12.2 <4.0.0"+ flutter: ">=3.18.0-18.0.pre.54"diff --git a/ui/pubspec.yaml b/ui/pubspec.yamlnew file mode 100644index 0000000..5cb1559--- /dev/null+++ b/ui/pubspec.yaml@@ -0,0 +1,95 @@+name: copysync_ui+description: "CopySync 的 macOS 界面:查看复制记录、配对设备、管理设置。"+# The following line prevents the package from being accidentally published to+# pub.dev using `flutter pub publish`. This is preferred for private packages.+publish_to: 'none' # Remove this line if you wish to publish to pub.dev++# The following defines the version and build number for your application.+# A version number is three numbers separated by dots, like 1.2.43+# followed by an optional build number separated by a +.+# Both the version and the builder number may be overridden in flutter+# build by specifying --build-name and --build-number, respectively.+# In Android, build-name is used as versionName while build-number used as versionCode.+# Read more about Android versioning at https://developer.android.com/studio/publish/versioning+# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.+# Read more about iOS versioning at+# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html+# In Windows, build-name is used as the major, minor, and patch parts+# of the product and file versions while build-number is used as the build suffix.+version: 1.0.0+1++environment:+ sdk: ^3.12.2++# Dependencies specify other packages that your package needs in order to work.+# To automatically upgrade your package dependencies to the latest versions+# consider running `flutter pub upgrade --major-versions`. Alternatively,+# dependencies can be manually updated by changing the version numbers below to+# the latest version available on pub.dev. To see which dependencies have newer+# versions available, run `flutter pub outdated`.+dependencies:+ flutter:+ sdk: flutter++ # The following adds the Cupertino Icons font to your application.+ # Use with the CupertinoIcons class for iOS style icons.+ cupertino_icons: ^1.0.8+ grpc: ^5.1.0+ protobuf: ^6.1.0+ fixnum: ^1.1.1++dev_dependencies:+ flutter_test:+ sdk: flutter++ # The "flutter_lints" package below contains a set of recommended lints to+ # encourage good coding practices. The lint set provided by the package is+ # activated in the `analysis_options.yaml` file located at the root of your+ # package. See that file for information about deactivating specific lint+ # rules and activating additional ones.+ flutter_lints: ^6.0.0++# For information on the generic Dart part of this file, see the+# following page: https://dart.dev/tools/pub/pubspec++# The following section is specific to Flutter packages.+flutter:++ # The following line ensures that the Material Icons font is+ # included with your application, so that you can use the icons in+ # the material Icons class.+ uses-material-design: true++ assets:+ - assets/app_icon.png++ # To add assets to your application, add an assets section, like this:+ # assets:+ # - images/a_dot_burr.jpeg+ # - images/a_dot_ham.jpeg++ # An image asset can refer to one or more resolution-specific "variants", see+ # https://flutter.dev/to/resolution-aware-images++ # For details regarding adding assets from package dependencies, see+ # https://flutter.dev/to/asset-from-package++ # To add custom fonts to your application, add a fonts section here,+ # in this "flutter" section. Each entry in this list should have a+ # "family" key with the font family name, and a "fonts" key with a+ # list giving the asset and other descriptors for the font. For+ # example:+ # fonts:+ # - family: Schyler+ # fonts:+ # - asset: fonts/Schyler-Regular.ttf+ # - asset: fonts/Schyler-Italic.ttf+ # style: italic+ # - family: Trajan Pro+ # fonts:+ # - asset: fonts/TrajanPro.ttf+ # - asset: fonts/TrajanPro_Bold.ttf+ # weight: 700+ #+ # For details regarding fonts from package dependencies,+ # see https://flutter.dev/to/font-from-packagediff --git a/ui/test/widget_test.dart b/ui/test/widget_test.dartnew file mode 100644index 0000000..fe69411--- /dev/null+++ b/ui/test/widget_test.dart@@ -0,0 +1,82 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';++import 'package:copysync_ui/daemon_client.dart';+import 'package:copysync_ui/main.dart';+import 'package:copysync_ui/widgets/common.dart';+import 'package:copysync_ui/widgets/pairing_dialog.dart';++void main() {+ testWidgets('应用启动后显示三个导航区', (tester) async {+ await tester.pumpWidget(const CopySyncApp());+ await tester.pump();++ expect(find.text('CopySync'), findsOneWidget);+ // 「复制记录」同时出现在侧边栏与页面标题中+ expect(find.text('复制记录'), findsWidgets);+ expect(find.text('设备'), findsWidgets);+ expect(find.text('设置'), findsWidgets);+ });++ testWidgets('daemon 未运行时给出下一步指引而非空白页', (tester) async {+ await tester.pumpWidget(const CopySyncApp());+ await tester.pump(const Duration(milliseconds: 300));++ // 空状态要说明该做什么,不能只写"暂无数据"+ expect(find.text('还没有记录'), findsOneWidget);+ expect(find.byType(EmptyState), findsOneWidget);+ });++ testWidgets('可以切换到设备页', (tester) async {+ await tester.pumpWidget(const CopySyncApp());+ await tester.pump();++ // 点侧边栏的「设备」(第一个匹配项是导航条目)+ await tester.tap(find.text('设备').first);+ await tester.pump();++ expect(find.text('还没有配对的设备'), findsOneWidget);+ expect(find.text('添加设备'), findsWidgets);+ });++ testWidgets('配对对话框里能取到 AppState', (tester) async {+ await tester.pumpWidget(const CopySyncApp());+ await tester.pump();++ // 测试环境没有 daemon,「添加设备」按钮是禁用的,直接按页面里的方式弹出+ showDialog<void>(+ context: tester.element(find.byType(Shell)),+ builder: (_) => const PairingDialog(),+ );+ await tester.pumpAndSettle();++ // 对话框挂在 Navigator 上而非 home 之下,AppScope 若放在 home 里,+ // 这里会报 "Null check operator used on a null value"+ expect(find.text('生成配对码'), findsOneWidget);+ expect(find.textContaining('Null check'), findsNothing);+ });++ test('数据目录路径与 Go 侧 config.DefaultPaths 保持一致', () {+ final dir = DaemonEndpoint.defaultDataDir();+ // 路径不一致会导致 UI 根本找不到 daemon,这里锁住约定+ expect(dir, contains('CopySync'));+ expect(DaemonEndpoint.endpointFile(dir).path, endsWith('daemon.json'));+ });++ group('格式化', () {+ test('humanBytes 在各量级下可读', () {+ expect(humanBytes(512), '512 B');+ expect(humanBytes(1536), '1.5 KB');+ expect(humanBytes(50 * 1024 * 1024), '50.0 MB');+ // 三位数时省略小数,避免 "150.0 MB" 这样冗余的显示+ expect(humanBytes(150 * 1024 * 1024), '150 MB');+ });++ test('relativeTime 对新近事件用口语化表述', () {+ final now = DateTime.now();+ expect(relativeTime(now), '刚刚');+ expect(relativeTime(now.subtract(const Duration(minutes: 5))), '5 分钟前');+ expect(relativeTime(now.subtract(const Duration(hours: 3))), '3 小时前');+ });+ });+}diff --git a/ui/tool/screenshots/screenshots_test.dart b/ui/tool/screenshots/screenshots_test.dartnew file mode 100644index 0000000..45360b7--- /dev/null+++ b/ui/tool/screenshots/screenshots_test.dart@@ -0,0 +1,337 @@+// 生成 README 与网站用的界面截图:演示数据,不连接后台服务,不读真实剪贴板。+//+// 不要直接运行,用仓库根目录的 tools/screenshots/render.sh——+// 它会先从本机系统字体生成渲染用的字体文件,渲染完再加上 macOS 窗口外框。+//+// 放在 tool/ 而非 test/:它依赖本机字体,不该随 flutter test 在 CI 上跑。+// ignore_for_file: invalid_use_of_visible_for_testing_member+import 'dart:io';+import 'dart:ui' show ImageByteFormat;++import 'package:copysync_ui/app_state.dart';+import 'package:copysync_ui/background_service.dart';+import 'package:copysync_ui/gen/copysync/v1/daemon.pb.dart';+import 'package:copysync_ui/main.dart';+import 'package:copysync_ui/theme.dart';+import 'package:copysync_ui/widgets/pairing_dialog.dart';+import 'package:fixnum/fixnum.dart';+import 'package:flutter/foundation.dart';+import 'package:flutter/gestures.dart';+import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';++/// 生成配对码不走后台服务,直接给一个固定值。+class _DemoState extends AppState {+ @override+ Future<String> createPairingCode() async => 'K7MP2X';+}++Future<void> _loadFonts() async {+ final dir = Platform.environment['SCREENSHOT_FONTS'];+ if (dir == null) throw StateError('用 tools/screenshots/render.sh 运行,它会设置 SCREENSHOT_FONTS');++ Future<void> family(String name, List<String> files) async {+ final loader = FontLoader(name);+ for (final f in files) {+ loader.addFont(Future.value(ByteData.sublistView(File('$dir/$f').readAsBytesSync())));+ }+ await loader.load();+ }++ await family('SF', ['SF-Regular.ttf', 'SF-Medium.ttf', 'SF-Semibold.ttf']);+ await family('PingFang', ['PingFang-Regular.ttf', 'PingFang-Medium.ttf', 'PingFang-Semibold.ttf']);+ await family(monoFamily, ['Menlo-Regular.ttf', 'Menlo-Bold.ttf']);+ // 图标字体随依赖包打进测试资源,但测试环境不会自动加载+ final icons = FontLoader('packages/cupertino_icons/CupertinoIcons')+ ..addFont(rootBundle.load('packages/cupertino_icons/assets/CupertinoIcons.ttf'));+ await icons.load();+}++final _now = DateTime.now();+Int64 _ago(Duration d) => Int64(_now.subtract(d).millisecondsSinceEpoch ~/ 1000);++ClipRecord _clip(+ String id,+ ClipKind kind, {+ String preview = '',+ bool outgoing = false,+ String from = 'MacBook Air',+ int size = 0,+ required Duration ago,+ ClipStatus status = ClipStatus.CLIP_STATUS_READY,+ List<ClipItem> items = const [],+}) =>+ ClipRecord(+ id: id,+ kind: kind,+ status: status,+ outgoing: outgoing,+ originDeviceName: outgoing ? 'MacBook Pro' : from,+ textPreview: preview,+ totalSize: Int64(size),+ createdAtUnix: _ago(ago),+ items: items,+ );++const _mb = 1024 * 1024;++AppState _demo({LinkState link = LinkState.online,+ ServiceState? service, Device? pending, bool empty = false}) {+ final state = _DemoState();+ state.debugSeed(+ link: link,+ serviceState: service,+ pendingPairing: pending,+ status: Status(+ version: '1.0.0',+ deviceName: 'MacBook Pro',+ signalingConnected: link == LinkState.online,+ clipboardPermission: ClipboardPermission.CLIPBOARD_PERMISSION_ALWAYS_ALLOW,+ cacheBytesUsed: Int64(412 * _mb),+ peersOnline: 2,+ ),+ config: Config(+ signalingUrl: 'wss://sync.example.com/signal',+ deviceName: 'MacBook Pro',+ autoSyncThresholdBytes: Int64(50 * _mb),+ historyTtlSeconds: Int64(3 * 86400),+ cacheTtlSeconds: Int64(86400),+ syncText: true,+ syncHtml: true,+ syncImage: true,+ syncFile: true,+ autoApplyToClipboard: true,+ ),+ self: Device(id: 'self', name: 'MacBook Pro', platform: 'darwin', publicKeyFingerprint: 'H3QD-7KXA-M2PV'),+ peers: empty ? const [] : [+ Device(+ id: 'air',+ name: 'MacBook Air',+ platform: 'darwin',+ online: true,+ connection: ConnectionKind.CONNECTION_KIND_DIRECT,+ publicKeyFingerprint: 'R8NF-2WTC-QL5J',+ ),+ Device(+ id: 'mini',+ name: 'Mac mini',+ platform: 'darwin',+ online: true,+ connection: ConnectionKind.CONNECTION_KIND_RELAY,+ publicKeyFingerprint: 'B6YE-X4MH-9DKS',+ ),+ Device(id: 'imac', name: 'iMac', platform: 'darwin', publicKeyFingerprint: 'T2VA-LP7Q-8ZRN'),+ ],+ records: empty ? const [] : [+ _clip('1', ClipKind.CLIP_KIND_TEXT,+ preview: 'git push origin release/1.0 && gh release create v1.0.0',+ outgoing: true, size: 54, ago: const Duration(seconds: 4)),+ _clip('2', ClipKind.CLIP_KIND_IMAGE,+ preview: '图片 2.4 MB', size: (2.4 * _mb).round(), ago: const Duration(minutes: 2),+ items: [ClipItem(name: 'image.png', size: Int64((2.4 * _mb).round()))]),+ _clip('3', ClipKind.CLIP_KIND_FILE,+ size: (38.2 * _mb).round(), ago: const Duration(minutes: 9),+ items: [ClipItem(name: '季度汇报-终版.key', size: Int64((38.2 * _mb).round()))]),+ _clip('4', ClipKind.CLIP_KIND_FILE,+ size: (1.3 * 1024 * _mb).round(), ago: const Duration(minutes: 14),+ from: 'Mac mini', status: ClipStatus.CLIP_STATUS_REMOTE_ONLY,+ items: [ClipItem(name: '发布演示录屏.mov', size: Int64((1.3 * 1024 * _mb).round()))]),+ _clip('5', ClipKind.CLIP_KIND_HTML,+ preview: '会议结论:周二灰度 10%,观察两天没问题周四全量;回滚预案见文档第 3 节',+ from: 'Mac mini', size: 2310, ago: const Duration(minutes: 26)),+ _clip('6', ClipKind.CLIP_KIND_FILE,+ outgoing: true, size: 126 * _mb, ago: const Duration(minutes: 41),+ items: [ClipItem(name: 'design-assets', size: Int64(126 * _mb), isDir: true)]),+ _clip('7', ClipKind.CLIP_KIND_FILE,+ size: (18.6 * _mb).round(), ago: const Duration(hours: 1),+ status: ClipStatus.CLIP_STATUS_FETCHING,+ items: [ClipItem(name: '合同扫描件.pdf', size: Int64((18.6 * _mb).round()))]),+ _clip('8', ClipKind.CLIP_KIND_TEXT,+ preview: 'https://github.com/baiyuze/copysync/releases', outgoing: true, size: 44,+ ago: const Duration(hours: 3)),+ _clip('9', ClipKind.CLIP_KIND_FILE,+ size: (4.1 * _mb).round(), ago: const Duration(hours: 5),+ items: [+ ClipItem(name: 'IMG_2041.HEIC', size: Int64((1.4 * _mb).round())),+ ClipItem(name: 'IMG_2042.HEIC', size: Int64((1.3 * _mb).round())),+ ClipItem(name: 'IMG_2043.HEIC', size: Int64((1.4 * _mb).round())),+ ]),+ _clip('10', ClipKind.CLIP_KIND_IMAGE,+ preview: '图片 864 KB', outgoing: true, size: 864 * 1024, ago: const Duration(days: 1),+ items: [ClipItem(name: 'image.png', size: Int64(864 * 1024))]),+ ],+ );+ return state;+}++final _boundary = GlobalKey();++Future<void> _shoot(+ WidgetTester tester,+ String name, {+ required AppState state,+ Section section = Section.history,+ Brightness brightness = Brightness.light,+ Future<void> Function()? arrange,+ bool settle = true,+}) async {+ // 960×640 的窗口,按 Retina 2 倍渲染+ tester.view.physicalSize = const Size(1920, 1280);+ tester.view.devicePixelRatio = 2;+ addTearDown(tester.view.reset);+ // 平台覆盖必须在测试体内复原:框架在执行 tearDown 之前就会检查它+ debugDefaultTargetPlatformOverride = TargetPlatform.macOS;+ // 测试框架默认把阴影画成实心描边(便于图片比对),截图要真实的模糊阴影+ debugDisableShadows = false;+ try {+ await _render(tester, name, state: state, section: section, brightness: brightness,+ arrange: arrange, settle: settle);+ } finally {+ debugDefaultTargetPlatformOverride = null;+ debugDisableShadows = true;+ }+}++Future<void> _render(+ WidgetTester tester,+ String name, {+ required AppState state,+ required Section section,+ required Brightness brightness,+ required Future<void> Function()? arrange,+ required bool settle,+}) async {++ final theme = buildTheme(brightness, fontFamily: 'SF', fontFamilyFallback: const ['PingFang']);+ await tester.pumpWidget(RepaintBoundary(+ key: _boundary,+ child: AppScope(+ state: state,+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: theme,+ home: Shell(initialSection: section),+ ),+ ),+ ));+ await tester.pump();+ // 图片解码是真实的异步操作,在测试的假时钟里不会自己完成+ await tester.runAsync(() async {+ for (final el in find.byType(Image).evaluate()) {+ await precacheImage((el.widget as Image).image, el);+ }+ });+ await tester.pump();+ if (arrange != null) await arrange();+ // 「拉取中」的进度条是无限动画,有它在的页面不能等动画结束+ settle ? await tester.pumpAndSettle() : await tester.pump(const Duration(milliseconds: 400));+ await _capture(tester, name);+}++/// 自己按 2 倍截取:matchesGoldenFile 只按 1 倍输出,放到 Retina 屏上会糊。+Future<void> _capture(WidgetTester tester, String name) async {+ final boundary = tester.renderObject<RenderRepaintBoundary>(find.byKey(_boundary));+ await tester.runAsync(() async {+ final image = await boundary.toImage(pixelRatio: 2);+ final png = await image.toByteData(format: ImageByteFormat.png);+ File('tool/screenshots/out/$name.png')+ ..createSync(recursive: true)+ ..writeAsBytesSync(png!.buffer.asUint8List());+ });+}++void main() {+ setUpAll(() async {+ TestWidgetsFlutterBinding.ensureInitialized();+ await _loadFonts();+ });++ testWidgets('history', (tester) async {+ await _shoot(tester, 'history', state: _demo(), settle: false, arrange: () async {+ // 悬停在一条记录上,展示「放入剪贴板」+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);+ await mouse.addPointer(location: Offset.zero);+ addTearDown(mouse.removePointer);+ await mouse.moveTo(tester.getCenter(find.text('季度汇报-终版.key')));+ await tester.pump();+ });+ });++ testWidgets('history-dark', (tester) async {+ await _shoot(tester, 'history-dark',+ state: _demo(), brightness: Brightness.dark, settle: false);+ });++ testWidgets('devices', (tester) async {+ await _shoot(tester, 'devices', state: _demo(), section: Section.devices);+ });++ testWidgets('pairing', (tester) async {+ await _shoot(tester, 'pairing', state: _demo(), section: Section.devices, arrange: () async {+ showDialog<void>(+ context: tester.element(find.byType(Shell)),+ builder: (_) => const PairingDialog(),+ );+ });+ });++ testWidgets('verify', (tester) async {+ await _shoot(tester, 'verify',+ section: Section.devices,+ state: _demo(+ pending: Device(+ id: 'new',+ name: 'MacBook Air',+ platform: 'darwin',+ publicKeyFingerprint: 'R8NF-2WTC-QL5J',+ pairingSession: 's1',+ ),+ ));+ });++ testWidgets('settings', (tester) async {+ await _shoot(tester, 'settings', state: _demo(), section: Section.settings);+ });++ // 网站上与文字并排展示的对话框:单独渲染,透明背景,保留对话框自己的圆角与阴影+ for (final dark in [false, true]) {+ testWidgets(dark ? 'card-verify-dark' : 'card-verify', (tester) async {+ tester.view.physicalSize = const Size(1120, 800);+ tester.view.devicePixelRatio = 2;+ addTearDown(tester.view.reset);+ debugDefaultTargetPlatformOverride = TargetPlatform.macOS;+ debugDisableShadows = false;+ try {+ final brightness = dark ? Brightness.dark : Brightness.light;+ await tester.pumpWidget(RepaintBoundary(+ key: _boundary,+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: buildTheme(brightness, fontFamily: 'SF', fontFamilyFallback: const ['PingFang']),+ home: Scaffold(+ backgroundColor: Colors.transparent,+ body: Center(+ child: PairingConfirmDialog(+ peer: Device(name: 'MacBook Air', publicKeyFingerprint: 'R8NF-2WTC-QL5J'),+ ),+ ),+ ),+ ),+ ));+ await tester.pumpAndSettle();+ await _capture(tester, dark ? 'card-verify-dark' : 'card-verify');+ } finally {+ debugDefaultTargetPlatformOverride = null;+ debugDisableShadows = true;+ }+ });+ }++ testWidgets('welcome', (tester) async {+ // 首次打开时还没有任何记录和设备+ final state = _demo(link: LinkState.offline, service: ServiceState.notInstalled, empty: true);+ await _shoot(tester, 'welcome', state: state);+ });+}diff --git a/ui/windows/.gitignore b/ui/windows/.gitignorenew file mode 100644index 0000000..d492d0d--- /dev/null+++ b/ui/windows/.gitignore@@ -0,0 +1,17 @@+flutter/ephemeral/++# Visual Studio user-specific files.+*.suo+*.user+*.userosscache+*.sln.docstates++# Visual Studio build-related files.+x64/+x86/++# Visual Studio cache files+# files ending in .cache can be ignored+*.[Cc]ache+# but keep track of directories ending in .cache+!*.[Cc]ache/diff --git a/ui/windows/CMakeLists.txt b/ui/windows/CMakeLists.txtnew file mode 100644index 0000000..fa726f6--- /dev/null+++ b/ui/windows/CMakeLists.txt@@ -0,0 +1,108 @@+# Project-level configuration.+cmake_minimum_required(VERSION 3.14)+project(copysync_ui LANGUAGES CXX)++# The name of the executable created for the application. Change this to change+# the on-disk name of your application.+set(BINARY_NAME "copysync_ui")++# Explicitly opt in to modern CMake behaviors to avoid warnings with recent+# versions of CMake.+cmake_policy(VERSION 3.14...3.25)++# Define build configuration option.+get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)+if(IS_MULTICONFIG)+ set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release"+ CACHE STRING "" FORCE)+else()+ if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)+ set(CMAKE_BUILD_TYPE "Debug" CACHE+ STRING "Flutter build mode" FORCE)+ set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS+ "Debug" "Profile" "Release")+ endif()+endif()+# Define settings for the Profile build mode.+set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}")+set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}")+set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}")+set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}")++# Use Unicode for all projects.+add_definitions(-DUNICODE -D_UNICODE)++# Compilation settings that should be applied to most targets.+#+# Be cautious about adding new options here, as plugins use this function by+# default. In most cases, you should add new options to specific targets instead+# of modifying this function.+function(APPLY_STANDARD_SETTINGS TARGET)+ target_compile_features(${TARGET} PUBLIC cxx_std_17)+ target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100")+ target_compile_options(${TARGET} PRIVATE /EHsc)+ target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0")+ target_compile_definitions(${TARGET} PRIVATE "$<$<CONFIG:Debug>:_DEBUG>")+endfunction()++# Flutter library and tool build rules.+set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")+add_subdirectory(${FLUTTER_MANAGED_DIR})++# Application build; see runner/CMakeLists.txt.+add_subdirectory("runner")+++# Generated plugin build rules, which manage building the plugins and adding+# them to the application.+include(flutter/generated_plugins.cmake)+++# === Installation ===+# Support files are copied into place next to the executable, so that it can+# run in place. This is done instead of making a separate bundle (as on Linux)+# so that building and running from within Visual Studio will work.+set(BUILD_BUNDLE_DIR "$<TARGET_FILE_DIR:${BINARY_NAME}>")+# Make the "install" step default, as it's required to run.+set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1)+if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)+ set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE)+endif()++set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")+set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}")++install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"+ COMPONENT Runtime)++install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"+ COMPONENT Runtime)++install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"+ COMPONENT Runtime)++if(PLUGIN_BUNDLED_LIBRARIES)+ install(FILES "${PLUGIN_BUNDLED_LIBRARIES}"+ DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"+ COMPONENT Runtime)+endif()++# Copy the native assets provided by the build.dart from all packages.+set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/")+install(DIRECTORY "${NATIVE_ASSETS_DIR}"+ DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"+ COMPONENT Runtime)++# Fully re-copy the assets directory on each build to avoid having stale files+# from a previous install.+set(FLUTTER_ASSET_DIR_NAME "flutter_assets")+install(CODE "+ file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")+ " COMPONENT Runtime)+install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"+ DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)++# Install the AOT library on non-Debug builds only.+install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"+ CONFIGURATIONS Profile;Release+ COMPONENT Runtime)diff --git a/ui/windows/flutter/CMakeLists.txt b/ui/windows/flutter/CMakeLists.txtnew file mode 100644index 0000000..903f489--- /dev/null+++ b/ui/windows/flutter/CMakeLists.txt@@ -0,0 +1,109 @@+# This file controls Flutter-level build steps. It should not be edited.+cmake_minimum_required(VERSION 3.14)++set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral")++# Configuration provided via flutter tool.+include(${EPHEMERAL_DIR}/generated_config.cmake)++# TODO: Move the rest of this into files in ephemeral. See+# https://github.com/flutter/flutter/issues/57146.+set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper")++# Set fallback configurations for older versions of the flutter tool.+if (NOT DEFINED FLUTTER_TARGET_PLATFORM)+ set(FLUTTER_TARGET_PLATFORM "windows-x64")+endif()++# === Flutter Library ===+set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll")++# Published to parent scope for install step.+set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)+set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE)+set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE)+set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE)++list(APPEND FLUTTER_LIBRARY_HEADERS+ "flutter_export.h"+ "flutter_windows.h"+ "flutter_messenger.h"+ "flutter_plugin_registrar.h"+ "flutter_texture_registrar.h"+)+list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/")+add_library(flutter INTERFACE)+target_include_directories(flutter INTERFACE+ "${EPHEMERAL_DIR}"+)+target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib")+add_dependencies(flutter flutter_assemble)++# === Wrapper ===+list(APPEND CPP_WRAPPER_SOURCES_CORE+ "core_implementations.cc"+ "standard_codec.cc"+)+list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/")+list(APPEND CPP_WRAPPER_SOURCES_PLUGIN+ "plugin_registrar.cc"+)+list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/")+list(APPEND CPP_WRAPPER_SOURCES_APP+ "flutter_engine.cc"+ "flutter_view_controller.cc"+)+list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/")++# Wrapper sources needed for a plugin.+add_library(flutter_wrapper_plugin STATIC+ ${CPP_WRAPPER_SOURCES_CORE}+ ${CPP_WRAPPER_SOURCES_PLUGIN}+)+apply_standard_settings(flutter_wrapper_plugin)+set_target_properties(flutter_wrapper_plugin PROPERTIES+ POSITION_INDEPENDENT_CODE ON)+set_target_properties(flutter_wrapper_plugin PROPERTIES+ CXX_VISIBILITY_PRESET hidden)+target_link_libraries(flutter_wrapper_plugin PUBLIC flutter)+target_include_directories(flutter_wrapper_plugin PUBLIC+ "${WRAPPER_ROOT}/include"+)+add_dependencies(flutter_wrapper_plugin flutter_assemble)++# Wrapper sources needed for the runner.+add_library(flutter_wrapper_app STATIC+ ${CPP_WRAPPER_SOURCES_CORE}+ ${CPP_WRAPPER_SOURCES_APP}+)+apply_standard_settings(flutter_wrapper_app)+target_link_libraries(flutter_wrapper_app PUBLIC flutter)+target_include_directories(flutter_wrapper_app PUBLIC+ "${WRAPPER_ROOT}/include"+)+add_dependencies(flutter_wrapper_app flutter_assemble)++# === Flutter tool backend ===+# _phony_ is a non-existent file to force this command to run every time,+# since currently there's no way to get a full input/output list from the+# flutter tool.+set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_")+set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE)+add_custom_command(+ OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}+ ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN}+ ${CPP_WRAPPER_SOURCES_APP}+ ${PHONY_OUTPUT}+ COMMAND ${CMAKE_COMMAND} -E env+ ${FLUTTER_TOOL_ENVIRONMENT}+ "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat"+ ${FLUTTER_TARGET_PLATFORM} $<CONFIG>+ VERBATIM+)+add_custom_target(flutter_assemble DEPENDS+ "${FLUTTER_LIBRARY}"+ ${FLUTTER_LIBRARY_HEADERS}+ ${CPP_WRAPPER_SOURCES_CORE}+ ${CPP_WRAPPER_SOURCES_PLUGIN}+ ${CPP_WRAPPER_SOURCES_APP}+)diff --git a/ui/windows/flutter/generated_plugin_registrant.cc b/ui/windows/flutter/generated_plugin_registrant.ccnew file mode 100644index 0000000..8b6d468--- /dev/null+++ b/ui/windows/flutter/generated_plugin_registrant.cc@@ -0,0 +1,11 @@+//+// Generated file. Do not edit.+//++// clang-format off++#include "generated_plugin_registrant.h"+++void RegisterPlugins(flutter::PluginRegistry* registry) {+}diff --git a/ui/windows/flutter/generated_plugin_registrant.h b/ui/windows/flutter/generated_plugin_registrant.hnew file mode 100644index 0000000..dc139d8--- /dev/null+++ b/ui/windows/flutter/generated_plugin_registrant.h@@ -0,0 +1,15 @@+//+// Generated file. Do not edit.+//++// clang-format off++#ifndef GENERATED_PLUGIN_REGISTRANT_+#define GENERATED_PLUGIN_REGISTRANT_++#include <flutter/plugin_registry.h>++// Registers Flutter plugins.+void RegisterPlugins(flutter::PluginRegistry* registry);++#endif // GENERATED_PLUGIN_REGISTRANT_diff --git a/ui/windows/flutter/generated_plugins.cmake b/ui/windows/flutter/generated_plugins.cmakenew file mode 100644index 0000000..b93c4c3--- /dev/null+++ b/ui/windows/flutter/generated_plugins.cmake@@ -0,0 +1,23 @@+#+# Generated file, do not edit.+#++list(APPEND FLUTTER_PLUGIN_LIST+)++list(APPEND FLUTTER_FFI_PLUGIN_LIST+)++set(PLUGIN_BUNDLED_LIBRARIES)++foreach(plugin ${FLUTTER_PLUGIN_LIST})+ add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin})+ target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin)+ list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>)+ list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})+endforeach(plugin)++foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST})+ add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin})+ list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})+endforeach(ffi_plugin)diff --git a/ui/windows/runner/CMakeLists.txt b/ui/windows/runner/CMakeLists.txtnew file mode 100644index 0000000..394917c--- /dev/null+++ b/ui/windows/runner/CMakeLists.txt@@ -0,0 +1,40 @@+cmake_minimum_required(VERSION 3.14)+project(runner LANGUAGES CXX)++# Define the application target. To change its name, change BINARY_NAME in the+# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer+# work.+#+# Any new source files that you add to the application should be added here.+add_executable(${BINARY_NAME} WIN32+ "flutter_window.cpp"+ "main.cpp"+ "utils.cpp"+ "win32_window.cpp"+ "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"+ "Runner.rc"+ "runner.exe.manifest"+)++# Apply the standard set of build settings. This can be removed for applications+# that need different build settings.+apply_standard_settings(${BINARY_NAME})++# Add preprocessor definitions for the build version.+target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"")+target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}")+target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}")+target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}")+target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}")++# Disable Windows macros that collide with C++ standard library functions.+target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX")++# Add dependency libraries and include directories. Add any application-specific+# dependencies here.+target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app)+target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib")+target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")++# Run the Flutter tool portions of the build. This must not be removed.+add_dependencies(${BINARY_NAME} flutter_assemble)diff --git a/ui/windows/runner/Runner.rc b/ui/windows/runner/Runner.rcnew file mode 100644index 0000000..13acfc5--- /dev/null+++ b/ui/windows/runner/Runner.rc@@ -0,0 +1,121 @@+// Microsoft Visual C++ generated resource script.+//+#pragma code_page(65001)+#include "resource.h"++#define APSTUDIO_READONLY_SYMBOLS+/////////////////////////////////////////////////////////////////////////////+//+// Generated from the TEXTINCLUDE 2 resource.+//+#include "winres.h"++/////////////////////////////////////////////////////////////////////////////+#undef APSTUDIO_READONLY_SYMBOLS++/////////////////////////////////////////////////////////////////////////////+// English (United States) resources++#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)+LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US++#ifdef APSTUDIO_INVOKED+/////////////////////////////////////////////////////////////////////////////+//+// TEXTINCLUDE+//++1 TEXTINCLUDE+BEGIN+ "resource.h\0"+END++2 TEXTINCLUDE+BEGIN+ "#include ""winres.h""\r\n"+ "\0"+END++3 TEXTINCLUDE+BEGIN+ "\r\n"+ "\0"+END++#endif // APSTUDIO_INVOKED+++/////////////////////////////////////////////////////////////////////////////+//+// Icon+//++// Icon with lowest ID value placed first to ensure application icon+// remains consistent on all systems.+IDI_APP_ICON ICON "resources\\app_icon.ico"+++/////////////////////////////////////////////////////////////////////////////+//+// Version+//++#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD)+#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD+#else+#define VERSION_AS_NUMBER 1,0,0,0+#endif++#if defined(FLUTTER_VERSION)+#define VERSION_AS_STRING FLUTTER_VERSION+#else+#define VERSION_AS_STRING "1.0.0"+#endif++VS_VERSION_INFO VERSIONINFO+ FILEVERSION VERSION_AS_NUMBER+ PRODUCTVERSION VERSION_AS_NUMBER+ FILEFLAGSMASK VS_FFI_FILEFLAGSMASK+#ifdef _DEBUG+ FILEFLAGS VS_FF_DEBUG+#else+ FILEFLAGS 0x0L+#endif+ FILEOS VOS__WINDOWS32+ FILETYPE VFT_APP+ FILESUBTYPE 0x0L+BEGIN+ BLOCK "StringFileInfo"+ BEGIN+ BLOCK "040904e4"+ BEGIN+ VALUE "CompanyName", "com.copysync" "\0"+ VALUE "FileDescription", "copysync_ui" "\0"+ VALUE "FileVersion", VERSION_AS_STRING "\0"+ VALUE "InternalName", "copysync_ui" "\0"+ VALUE "LegalCopyright", "Copyright (C) 2026 com.copysync. All rights reserved." "\0"+ VALUE "OriginalFilename", "copysync_ui.exe" "\0"+ VALUE "ProductName", "copysync_ui" "\0"+ VALUE "ProductVersion", VERSION_AS_STRING "\0"+ END+ END+ BLOCK "VarFileInfo"+ BEGIN+ VALUE "Translation", 0x409, 1252+ END+END++#endif // English (United States) resources+/////////////////////////////////////////////////////////////////////////////++++#ifndef APSTUDIO_INVOKED+/////////////////////////////////////////////////////////////////////////////+//+// Generated from the TEXTINCLUDE 3 resource.+//+++/////////////////////////////////////////////////////////////////////////////+#endif // not APSTUDIO_INVOKEDdiff --git a/ui/windows/runner/flutter_window.cpp b/ui/windows/runner/flutter_window.cppnew file mode 100644index 0000000..955ee30--- /dev/null+++ b/ui/windows/runner/flutter_window.cpp@@ -0,0 +1,71 @@+#include "flutter_window.h"++#include <optional>++#include "flutter/generated_plugin_registrant.h"++FlutterWindow::FlutterWindow(const flutter::DartProject& project)+ : project_(project) {}++FlutterWindow::~FlutterWindow() {}++bool FlutterWindow::OnCreate() {+ if (!Win32Window::OnCreate()) {+ return false;+ }++ RECT frame = GetClientArea();++ // The size here must match the window dimensions to avoid unnecessary surface+ // creation / destruction in the startup path.+ flutter_controller_ = std::make_unique<flutter::FlutterViewController>(+ frame.right - frame.left, frame.bottom - frame.top, project_);+ // Ensure that basic setup of the controller was successful.+ if (!flutter_controller_->engine() || !flutter_controller_->view()) {+ return false;+ }+ RegisterPlugins(flutter_controller_->engine());+ SetChildContent(flutter_controller_->view()->GetNativeWindow());++ flutter_controller_->engine()->SetNextFrameCallback([&]() {+ this->Show();+ });++ // Flutter can complete the first frame before the "show window" callback is+ // registered. The following call ensures a frame is pending to ensure the+ // window is shown. It is a no-op if the first frame hasn't completed yet.+ flutter_controller_->ForceRedraw();++ return true;+}++void FlutterWindow::OnDestroy() {+ if (flutter_controller_) {+ flutter_controller_ = nullptr;+ }++ Win32Window::OnDestroy();+}++LRESULT+FlutterWindow::MessageHandler(HWND hwnd, UINT const message,+ WPARAM const wparam,+ LPARAM const lparam) noexcept {+ // Give Flutter, including plugins, an opportunity to handle window messages.+ if (flutter_controller_) {+ std::optional<LRESULT> result =+ flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam,+ lparam);+ if (result) {+ return *result;+ }+ }++ switch (message) {+ case WM_FONTCHANGE:+ flutter_controller_->engine()->ReloadSystemFonts();+ break;+ }++ return Win32Window::MessageHandler(hwnd, message, wparam, lparam);+}diff --git a/ui/windows/runner/flutter_window.h b/ui/windows/runner/flutter_window.hnew file mode 100644index 0000000..6da0652--- /dev/null+++ b/ui/windows/runner/flutter_window.h@@ -0,0 +1,33 @@+#ifndef RUNNER_FLUTTER_WINDOW_H_+#define RUNNER_FLUTTER_WINDOW_H_++#include <flutter/dart_project.h>+#include <flutter/flutter_view_controller.h>++#include <memory>++#include "win32_window.h"++// A window that does nothing but host a Flutter view.+class FlutterWindow : public Win32Window {+ public:+ // Creates a new FlutterWindow hosting a Flutter view running |project|.+ explicit FlutterWindow(const flutter::DartProject& project);+ virtual ~FlutterWindow();++ protected:+ // Win32Window:+ bool OnCreate() override;+ void OnDestroy() override;+ LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam,+ LPARAM const lparam) noexcept override;++ private:+ // The project to run.+ flutter::DartProject project_;++ // The Flutter instance hosted by this window.+ std::unique_ptr<flutter::FlutterViewController> flutter_controller_;+};++#endif // RUNNER_FLUTTER_WINDOW_H_diff --git a/ui/windows/runner/main.cpp b/ui/windows/runner/main.cppnew file mode 100644index 0000000..0083d49--- /dev/null+++ b/ui/windows/runner/main.cpp@@ -0,0 +1,43 @@+#include <flutter/dart_project.h>+#include <flutter/flutter_view_controller.h>+#include <windows.h>++#include "flutter_window.h"+#include "utils.h"++int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,+ _In_ wchar_t *command_line, _In_ int show_command) {+ // Attach to console when present (e.g., 'flutter run') or create a+ // new console when running with a debugger.+ if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {+ CreateAndAttachConsole();+ }++ // Initialize COM, so that it is available for use in the library and/or+ // plugins.+ ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);++ flutter::DartProject project(L"data");++ std::vector<std::string> command_line_arguments =+ GetCommandLineArguments();++ project.set_dart_entrypoint_arguments(std::move(command_line_arguments));++ FlutterWindow window(project);+ Win32Window::Point origin(10, 10);+ Win32Window::Size size(1280, 720);+ if (!window.Create(L"copysync_ui", origin, size)) {+ return EXIT_FAILURE;+ }+ window.SetQuitOnClose(true);++ ::MSG msg;+ while (::GetMessage(&msg, nullptr, 0, 0)) {+ ::TranslateMessage(&msg);+ ::DispatchMessage(&msg);+ }++ ::CoUninitialize();+ return EXIT_SUCCESS;+}diff --git a/ui/windows/runner/resource.h b/ui/windows/runner/resource.hnew file mode 100644index 0000000..66a65d1--- /dev/null+++ b/ui/windows/runner/resource.h@@ -0,0 +1,16 @@+//{{NO_DEPENDENCIES}}+// Microsoft Visual C++ generated include file.+// Used by Runner.rc+//+#define IDI_APP_ICON 101++// Next default values for new objects+//+#ifdef APSTUDIO_INVOKED+#ifndef APSTUDIO_READONLY_SYMBOLS+#define _APS_NEXT_RESOURCE_VALUE 102+#define _APS_NEXT_COMMAND_VALUE 40001+#define _APS_NEXT_CONTROL_VALUE 1001+#define _APS_NEXT_SYMED_VALUE 101+#endif+#endifdiff --git a/ui/windows/runner/resources/app_icon.ico b/ui/windows/runner/resources/app_icon.iconew file mode 100644index 0000000..c04e20cBinary files /dev/null and b/ui/windows/runner/resources/app_icon.ico differdiff --git a/ui/windows/runner/runner.exe.manifest b/ui/windows/runner/runner.exe.manifestnew file mode 100644index 0000000..153653e--- /dev/null+++ b/ui/windows/runner/runner.exe.manifest@@ -0,0 +1,14 @@+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">+ <application xmlns="urn:schemas-microsoft-com:asm.v3">+ <windowsSettings>+ <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>+ </windowsSettings>+ </application>+ <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">+ <application>+ <!-- Windows 10 and Windows 11 -->+ <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>+ </application>+ </compatibility>+</assembly>diff --git a/ui/windows/runner/utils.cpp b/ui/windows/runner/utils.cppnew file mode 100644index 0000000..3cb7146--- /dev/null+++ b/ui/windows/runner/utils.cpp@@ -0,0 +1,69 @@+#include "utils.h"++#include <flutter_windows.h>+#include <io.h>+#include <stdio.h>+#include <windows.h>++#include <iostream>++void CreateAndAttachConsole() {+ if (::AllocConsole()) {+ FILE *unused;+ if (freopen_s(&unused, "CONOUT$", "w", stdout)) {+ _dup2(_fileno(stdout), 1);+ }+ if (freopen_s(&unused, "CONOUT$", "w", stderr)) {+ _dup2(_fileno(stdout), 2);+ }+ std::ios::sync_with_stdio();+ FlutterDesktopResyncOutputStreams();+ }+}++std::vector<std::string> GetCommandLineArguments() {+ // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use.+ int argc;+ wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);+ if (argv == nullptr) {+ return std::vector<std::string>();+ }++ std::vector<std::string> command_line_arguments;++ // Skip the first argument as it's the binary name.+ for (int i = 1; i < argc; i++) {+ command_line_arguments.push_back(Utf8FromUtf16(argv[i]));+ }++ ::LocalFree(argv);++ return command_line_arguments;+}++std::string Utf8FromUtf16(const wchar_t* utf16_string) {+ if (utf16_string == nullptr) {+ return std::string();+ }+ // First, find the length of the string with a safe upper bound (CWE-126).+ // UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING.+ int input_length = static_cast<int>(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS));+ // Now use that bounded length to determine the required buffer size.+ // When an explicit length is passed, WideCharToMultiByte does not include+ // the null terminator in its returned size.+ int target_length = ::WideCharToMultiByte(+ CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,+ input_length, nullptr, 0, nullptr, nullptr);+ std::string utf8_string;+ if (target_length == 0 || static_cast<size_t>(target_length) > utf8_string.max_size()) {+ return utf8_string;+ }+ utf8_string.resize(target_length);+ int converted_length = ::WideCharToMultiByte(+ CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,+ input_length, utf8_string.data(), target_length, nullptr, nullptr);+ if (converted_length == 0) {+ return std::string();+ }+ return utf8_string;+}diff --git a/ui/windows/runner/utils.h b/ui/windows/runner/utils.hnew file mode 100644index 0000000..3879d54--- /dev/null+++ b/ui/windows/runner/utils.h@@ -0,0 +1,19 @@+#ifndef RUNNER_UTILS_H_+#define RUNNER_UTILS_H_++#include <string>+#include <vector>++// Creates a console for the process, and redirects stdout and stderr to+// it for both the runner and the Flutter library.+void CreateAndAttachConsole();++// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string+// encoded in UTF-8. Returns an empty std::string on failure.+std::string Utf8FromUtf16(const wchar_t* utf16_string);++// Gets the command line arguments passed in as a std::vector<std::string>,+// encoded in UTF-8. Returns an empty std::vector<std::string> on failure.+std::vector<std::string> GetCommandLineArguments();++#endif // RUNNER_UTILS_H_diff --git a/ui/windows/runner/win32_window.cpp b/ui/windows/runner/win32_window.cppnew file mode 100644index 0000000..60608d0--- /dev/null+++ b/ui/windows/runner/win32_window.cpp@@ -0,0 +1,288 @@+#include "win32_window.h"++#include <dwmapi.h>+#include <flutter_windows.h>++#include "resource.h"++namespace {++/// Window attribute that enables dark mode window decorations.+///+/// Redefined in case the developer's machine has a Windows SDK older than+/// version 10.0.22000.0.+/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute+#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE+#define DWMWA_USE_IMMERSIVE_DARK_MODE 20+#endif++constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW";++/// Registry key for app theme preference.+///+/// A value of 0 indicates apps should use dark mode. A non-zero or missing+/// value indicates apps should use light mode.+constexpr const wchar_t kGetPreferredBrightnessRegKey[] =+ L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize";+constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme";++// The number of Win32Window objects that currently exist.+static int g_active_window_count = 0;++using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd);++// Scale helper to convert logical scaler values to physical using passed in+// scale factor+int Scale(int source, double scale_factor) {+ return static_cast<int>(source * scale_factor);+}++// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module.+// This API is only needed for PerMonitor V1 awareness mode.+void EnableFullDpiSupportIfAvailable(HWND hwnd) {+ HMODULE user32_module = LoadLibraryA("User32.dll");+ if (!user32_module) {+ return;+ }+ auto enable_non_client_dpi_scaling =+ reinterpret_cast<EnableNonClientDpiScaling*>(+ GetProcAddress(user32_module, "EnableNonClientDpiScaling"));+ if (enable_non_client_dpi_scaling != nullptr) {+ enable_non_client_dpi_scaling(hwnd);+ }+ FreeLibrary(user32_module);+}++} // namespace++// Manages the Win32Window's window class registration.+class WindowClassRegistrar {+ public:+ ~WindowClassRegistrar() = default;++ // Returns the singleton registrar instance.+ static WindowClassRegistrar* GetInstance() {+ if (!instance_) {+ instance_ = new WindowClassRegistrar();+ }+ return instance_;+ }++ // Returns the name of the window class, registering the class if it hasn't+ // previously been registered.+ const wchar_t* GetWindowClass();++ // Unregisters the window class. Should only be called if there are no+ // instances of the window.+ void UnregisterWindowClass();++ private:+ WindowClassRegistrar() = default;++ static WindowClassRegistrar* instance_;++ bool class_registered_ = false;+};++WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr;++const wchar_t* WindowClassRegistrar::GetWindowClass() {+ if (!class_registered_) {+ WNDCLASS window_class{};+ window_class.hCursor = LoadCursor(nullptr, IDC_ARROW);+ window_class.lpszClassName = kWindowClassName;+ window_class.style = CS_HREDRAW | CS_VREDRAW;+ window_class.cbClsExtra = 0;+ window_class.cbWndExtra = 0;+ window_class.hInstance = GetModuleHandle(nullptr);+ window_class.hIcon =+ LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON));+ window_class.hbrBackground = 0;+ window_class.lpszMenuName = nullptr;+ window_class.lpfnWndProc = Win32Window::WndProc;+ RegisterClass(&window_class);+ class_registered_ = true;+ }+ return kWindowClassName;+}++void WindowClassRegistrar::UnregisterWindowClass() {+ UnregisterClass(kWindowClassName, nullptr);+ class_registered_ = false;+}++Win32Window::Win32Window() {+ ++g_active_window_count;+}++Win32Window::~Win32Window() {+ --g_active_window_count;+ Destroy();+}++bool Win32Window::Create(const std::wstring& title,+ const Point& origin,+ const Size& size) {+ Destroy();++ const wchar_t* window_class =+ WindowClassRegistrar::GetInstance()->GetWindowClass();++ const POINT target_point = {static_cast<LONG>(origin.x),+ static_cast<LONG>(origin.y)};+ HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST);+ UINT dpi = FlutterDesktopGetDpiForMonitor(monitor);+ double scale_factor = dpi / 96.0;++ HWND window = CreateWindow(+ window_class, title.c_str(), WS_OVERLAPPEDWINDOW,+ Scale(origin.x, scale_factor), Scale(origin.y, scale_factor),+ Scale(size.width, scale_factor), Scale(size.height, scale_factor),+ nullptr, nullptr, GetModuleHandle(nullptr), this);++ if (!window) {+ return false;+ }++ UpdateTheme(window);++ return OnCreate();+}++bool Win32Window::Show() {+ return ShowWindow(window_handle_, SW_SHOWNORMAL);+}++// static+LRESULT CALLBACK Win32Window::WndProc(HWND const window,+ UINT const message,+ WPARAM const wparam,+ LPARAM const lparam) noexcept {+ if (message == WM_NCCREATE) {+ auto window_struct = reinterpret_cast<CREATESTRUCT*>(lparam);+ SetWindowLongPtr(window, GWLP_USERDATA,+ reinterpret_cast<LONG_PTR>(window_struct->lpCreateParams));++ auto that = static_cast<Win32Window*>(window_struct->lpCreateParams);+ EnableFullDpiSupportIfAvailable(window);+ that->window_handle_ = window;+ } else if (Win32Window* that = GetThisFromHandle(window)) {+ return that->MessageHandler(window, message, wparam, lparam);+ }++ return DefWindowProc(window, message, wparam, lparam);+}++LRESULT+Win32Window::MessageHandler(HWND hwnd,+ UINT const message,+ WPARAM const wparam,+ LPARAM const lparam) noexcept {+ switch (message) {+ case WM_DESTROY:+ window_handle_ = nullptr;+ Destroy();+ if (quit_on_close_) {+ PostQuitMessage(0);+ }+ return 0;++ case WM_DPICHANGED: {+ auto newRectSize = reinterpret_cast<RECT*>(lparam);+ LONG newWidth = newRectSize->right - newRectSize->left;+ LONG newHeight = newRectSize->bottom - newRectSize->top;++ SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth,+ newHeight, SWP_NOZORDER | SWP_NOACTIVATE);++ return 0;+ }+ case WM_SIZE: {+ RECT rect = GetClientArea();+ if (child_content_ != nullptr) {+ // Size and position the child window.+ MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left,+ rect.bottom - rect.top, TRUE);+ }+ return 0;+ }++ case WM_ACTIVATE:+ if (child_content_ != nullptr) {+ SetFocus(child_content_);+ }+ return 0;++ case WM_DWMCOLORIZATIONCOLORCHANGED:+ UpdateTheme(hwnd);+ return 0;+ }++ return DefWindowProc(window_handle_, message, wparam, lparam);+}++void Win32Window::Destroy() {+ OnDestroy();++ if (window_handle_) {+ DestroyWindow(window_handle_);+ window_handle_ = nullptr;+ }+ if (g_active_window_count == 0) {+ WindowClassRegistrar::GetInstance()->UnregisterWindowClass();+ }+}++Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept {+ return reinterpret_cast<Win32Window*>(+ GetWindowLongPtr(window, GWLP_USERDATA));+}++void Win32Window::SetChildContent(HWND content) {+ child_content_ = content;+ SetParent(content, window_handle_);+ RECT frame = GetClientArea();++ MoveWindow(content, frame.left, frame.top, frame.right - frame.left,+ frame.bottom - frame.top, true);++ SetFocus(child_content_);+}++RECT Win32Window::GetClientArea() {+ RECT frame;+ GetClientRect(window_handle_, &frame);+ return frame;+}++HWND Win32Window::GetHandle() {+ return window_handle_;+}++void Win32Window::SetQuitOnClose(bool quit_on_close) {+ quit_on_close_ = quit_on_close;+}++bool Win32Window::OnCreate() {+ // No-op; provided for subclasses.+ return true;+}++void Win32Window::OnDestroy() {+ // No-op; provided for subclasses.+}++void Win32Window::UpdateTheme(HWND const window) {+ DWORD light_mode;+ DWORD light_mode_size = sizeof(light_mode);+ LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey,+ kGetPreferredBrightnessRegValue,+ RRF_RT_REG_DWORD, nullptr, &light_mode,+ &light_mode_size);++ if (result == ERROR_SUCCESS) {+ BOOL enable_dark_mode = light_mode == 0;+ DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE,+ &enable_dark_mode, sizeof(enable_dark_mode));+ }+}diff --git a/ui/windows/runner/win32_window.h b/ui/windows/runner/win32_window.hnew file mode 100644index 0000000..e901dde--- /dev/null+++ b/ui/windows/runner/win32_window.h@@ -0,0 +1,102 @@+#ifndef RUNNER_WIN32_WINDOW_H_+#define RUNNER_WIN32_WINDOW_H_++#include <windows.h>++#include <functional>+#include <memory>+#include <string>++// A class abstraction for a high DPI-aware Win32 Window. Intended to be+// inherited from by classes that wish to specialize with custom+// rendering and input handling+class Win32Window {+ public:+ struct Point {+ unsigned int x;+ unsigned int y;+ Point(unsigned int x, unsigned int y) : x(x), y(y) {}+ };++ struct Size {+ unsigned int width;+ unsigned int height;+ Size(unsigned int width, unsigned int height)+ : width(width), height(height) {}+ };++ Win32Window();+ virtual ~Win32Window();++ // Creates a win32 window with |title| that is positioned and sized using+ // |origin| and |size|. New windows are created on the default monitor. Window+ // sizes are specified to the OS in physical pixels, hence to ensure a+ // consistent size this function will scale the inputted width and height as+ // as appropriate for the default monitor. The window is invisible until+ // |Show| is called. Returns true if the window was created successfully.+ bool Create(const std::wstring& title, const Point& origin, const Size& size);++ // Show the current window. Returns true if the window was successfully shown.+ bool Show();++ // Release OS resources associated with window.+ void Destroy();++ // Inserts |content| into the window tree.+ void SetChildContent(HWND content);++ // Returns the backing Window handle to enable clients to set icon and other+ // window properties. Returns nullptr if the window has been destroyed.+ HWND GetHandle();++ // If true, closing this window will quit the application.+ void SetQuitOnClose(bool quit_on_close);++ // Return a RECT representing the bounds of the current client area.+ RECT GetClientArea();++ protected:+ // Processes and route salient window messages for mouse handling,+ // size change and DPI. Delegates handling of these to member overloads that+ // inheriting classes can handle.+ virtual LRESULT MessageHandler(HWND window,+ UINT const message,+ WPARAM const wparam,+ LPARAM const lparam) noexcept;++ // Called when CreateAndShow is called, allowing subclass window-related+ // setup. Subclasses should return false if setup fails.+ virtual bool OnCreate();++ // Called when Destroy is called.+ virtual void OnDestroy();++ private:+ friend class WindowClassRegistrar;++ // OS callback called by message pump. Handles the WM_NCCREATE message which+ // is passed when the non-client area is being created and enables automatic+ // non-client DPI scaling so that the non-client area automatically+ // responds to changes in DPI. All other messages are handled by+ // MessageHandler.+ static LRESULT CALLBACK WndProc(HWND const window,+ UINT const message,+ WPARAM const wparam,+ LPARAM const lparam) noexcept;++ // Retrieves a class instance pointer for |window|+ static Win32Window* GetThisFromHandle(HWND const window) noexcept;++ // Update the window frame's theme to match the system theme.+ static void UpdateTheme(HWND const window);++ bool quit_on_close_ = false;++ // window handle for top level window.+ HWND window_handle_ = nullptr;++ // window handle for hosted content.+ HWND child_content_ = nullptr;+};++#endif // RUNNER_WIN32_WINDOW_H_